diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile new file mode 100644 index 0000000000000..66f20ccfb5fe4 --- /dev/null +++ b/.devcontainer/Dockerfile @@ -0,0 +1,7 @@ +# See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.154.0/containers/javascript-node/.devcontainer/base.Dockerfile + +# [Choice] Node.js version: 14, 12, 10 +ARG VARIANT="14-buster" +FROM mcr.microsoft.com/vscode/devcontainers/javascript-node:0-${VARIANT} + +RUN sudo -u node npm install -g gulp-cli diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000000000..f96ffd6c02a1c --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,16 @@ +{ + "name": "Node.js", + "build": { + "dockerfile": "Dockerfile", + "args": { + "VARIANT": "14" + } + }, + "settings": { + "terminal.integrated.shell.linux": "/bin/bash" + }, + "extensions": [ + "dbaeumer.vscode-eslint" + ], + "remoteUser": "node" +} diff --git a/.github/issue_template.md b/.github/issue_template.md deleted file mode 100644 index 891d574568df3..0000000000000 --- a/.github/issue_template.md +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - -**TypeScript Version:** 3.0.0-dev.201xxxxx - - -**Search Terms:** - -**Code** - -```ts -// A *self-contained* demonstration of the problem follows... -// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc. -``` - -**Expected behavior:** - -**Actual behavior:** - -**Playground Link:** - -**Related Issues:** diff --git a/.github/workflows/new-release-branch.yaml b/.github/workflows/new-release-branch.yaml index 8cb80522ae283..6c07e96bbbbc9 100644 --- a/.github/workflows/new-release-branch.yaml +++ b/.github/workflows/new-release-branch.yaml @@ -22,7 +22,7 @@ jobs: sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' src/compiler/corePublic.ts sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' tests/baselines/reference/api/typescript.d.ts sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' tests/baselines/reference/api/tsserverlibrary.d.ts - sed -i -e 's/const version = `${versionMajorMinor}.0-.*`/const version = `${versionMajorMinor}.0-${{ github.event.client_payload.core_tag || 'dev' }}`/g' src/compiler/corePublic.ts + sed -i -e 's/const version\(: string\)\{0,1\} = `${versionMajorMinor}.0-.*`/const version = `${versionMajorMinor}.0-${{ github.event.client_payload.core_tag || 'dev' }}`/g' src/compiler/corePublic.ts npm ci gulp LKG npm test diff --git a/.github/workflows/set-version.yaml b/.github/workflows/set-version.yaml index f337d5b58f472..d5bd8faa83438 100644 --- a/.github/workflows/set-version.yaml +++ b/.github/workflows/set-version.yaml @@ -28,7 +28,7 @@ jobs: sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' src/compiler/corePublic.ts sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' tests/baselines/reference/api/typescript.d.ts sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' tests/baselines/reference/api/tsserverlibrary.d.ts - sed -i -e 's/const version = .*;/const version = "${{ github.event.client_payload.package_version }}" as string;/g' src/compiler/corePublic.ts + sed -i -e 's/const version\(: string\)\{0,1\} = .*;/const version = "${{ github.event.client_payload.package_version }}" as string;/g' src/compiler/corePublic.ts npm ci gulp LKG npm test diff --git a/.github/workflows/update-package-lock.yaml b/.github/workflows/update-package-lock.yaml index 24defcb1f93f6..0e4d1509333e3 100644 --- a/.github/workflows/update-package-lock.yaml +++ b/.github/workflows/update-package-lock.yaml @@ -5,6 +5,7 @@ on: # This is probably 6am UTC, which is 10pm PST or 11pm PDT # Alternatively, 6am local is also fine - cron: '0 6 * * *' + workflow_dispatch: {} jobs: build: diff --git a/.gitignore b/.gitignore index d2bfafe567fb5..f63a2aeea0266 100644 --- a/.gitignore +++ b/.gitignore @@ -85,6 +85,7 @@ tests/baselines/reference/dt .failed-tests TEST-results.xml package-lock.json +tests/cases/user/npm/npm tests/cases/user/TypeScript-React-Starter/TypeScript-React-Starter tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter tests/cases/user/TypeScript-React-Native-Starter/TypeScript-React-Native-Starter diff --git a/.npmignore b/.npmignore index 7a8f8d5129113..55bd5fc5d4a7f 100644 --- a/.npmignore +++ b/.npmignore @@ -10,6 +10,7 @@ scripts src tests Jakefile.js +.devcontainer .eslintrc .eslintignore .editorconfig diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 95437f807ce2c..98c5dc0238dbc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -70,6 +70,13 @@ In general, things we find useful when reviewing suggestions are: ## Tips +### Using a development container + +This repository includes a [development container](https://code.visualstudio.com/docs/remote/containers) that you can use to quickly create an isolated development environment with all the tools you need to start working on TypeScript. To get started with a dev container and VS Code, either: + +- Clone the TypeScript repository locally and use the `Open Folder in Container` command. +- Use the `Clone Repository in Container Volume` command to clone the TypeScript repository into a new container. + ### Faster clones The TypeScript repository is relatively large. To save some time, you might want to clone it without the repo's full history using `git clone --depth=1`. @@ -153,17 +160,17 @@ gulp runtests --tests=2dArrays ## Debugging the tests -You can debug with VS Code or Node instead with `gulp runtests --inspect`: +You can debug with VS Code or Node instead with `gulp runtests -i`: ```Shell -gulp runtests --tests=2dArrays --inspect +gulp runtests --tests=2dArrays -i ``` You can also use the [provided VS Code launch configuration](./.vscode/launch.template.json) to launch a debug session for an open test file. Rename the file 'launch.json', open the test file of interest, and launch the debugger from the debug panel (or press F5). ## Adding a Test -To add a new test case, add a `.ts` file in `tests\cases\compiler` with code that shows the your bug is now fixed, or your new feature now works. +To add a new test case, add a `.ts` file in `tests\cases\compiler` with code that shows the bug is now fixed, or your new feature now works. These files support metadata tags in the format `// @metaDataName: value`. The supported names and values are the same as those supported in the compiler itself, with the addition of the `fileName` flag. diff --git a/Gulpfile.js b/Gulpfile.js index afd4b24e8f3bb..8e48e613aa06b 100644 --- a/Gulpfile.js +++ b/Gulpfile.js @@ -453,8 +453,7 @@ task("runtests").flags = { "-t --tests=": "Pattern for tests to run.", " --failed": "Runs tests listed in '.failed-tests'.", "-r --reporter=": "The mocha reporter to use.", - "-d --debug": "Runs tests in debug mode (NodeJS 6 and earlier)", - "-i --inspect": "Runs tests in inspector mode (NodeJS 8 and later)", + "-i --break": "Runs tests in inspector mode (NodeJS 8 and later)", " --keepFailed": "Keep tests in .failed-tests even if they pass", " --light": "Run tests in light mode (fewer verifications, but tests run faster)", " --dirty": "Run tests without first cleaning test output directories", diff --git a/README.md b/README.md index 2fcf721123428..f21b70854c793 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ with any additional questions or comments. ## Documentation * [TypeScript in 5 minutes](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html) -* [Programming handbook](https://www.typescriptlang.org/docs/handbook/basic-types.html) +* [Programming handbook](https://www.typescriptlang.org/docs/handbook/intro.html) * [Homepage](https://www.typescriptlang.org/) ## Building diff --git a/lib/cs/diagnosticMessages.generated.json b/lib/cs/diagnosticMessages.generated.json index 3e78bf65c43c3..b30f628f70987 100644 --- a/lib/cs/diagnosticMessages.generated.json +++ b/lib/cs/diagnosticMessages.generated.json @@ -199,6 +199,7 @@ "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Implementace se nedá deklarovat v ambientních kontextech.", "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "Alias importu se nemůže odkazovat na deklaraci, která se exportovala pomocí export type.", "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "Alias importu se nemůže odkazovat na deklaraci, která se importovala pomocí import type.", + "An_import_alias_cannot_use_import_type_1392": "Alias importu nemůže používat import type.", "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Deklarace importu jde použít jenom v oboru názvů nebo modulu.", "An_import_declaration_cannot_have_modifiers_1191": "Deklarace importu nemůže mít modifikátory.", "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Cesta pro import nemůže končit příponou {0}. Zvažte možnost importovat místo toho {1}.", @@ -443,6 +444,7 @@ "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Výchozí export modulu má nebo používá privátní název {0}.", "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "Definice následujících identifikátorů je v konfliktu s definicemi v jiném souboru: {0}", "Delete_all_unused_declarations_95024": "Odstranit všechny nepoužívané deklarace", + "Delete_all_unused_imports_95147": "Odstranit všechny nepoužívané importy", "Delete_the_outputs_of_all_projects_6365": "Odstranit výstupy všech projektů", "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Zastaralé] Použijte místo toho --jsxFactory. Určí objekt vyvolaný pro createElement při cílení na generování JSX react.", "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Zastaralé] Použijte místo toho --outFile. Zřetězí a vygeneruje výstup do jednoho souboru.", @@ -668,6 +670,7 @@ "Index_signatures_are_incompatible_2330": "Signatury indexu jsou nekompatibilní.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Jednotlivé deklarace ve sloučené deklaraci {0} musí být všechny exportované nebo všechny místní.", "Infer_all_types_from_usage_95023": "Odvodit všechny typy z použití", + "Infer_function_return_type_95148": "Odvodit návratový typ funkce", "Infer_parameter_types_from_usage_95012": "Odvodit typy parametrů z využití", "Infer_this_type_of_0_from_usage_95080": "Vyvodit typ this pro {0} z použití", "Infer_type_of_0_from_usage_95011": "Odvodit typ {0} z využití", @@ -814,7 +817,6 @@ "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Osmičkové literály nejsou povolené v inicializátoru členů výčtů. Použijte syntaxi {0}.", "Octal_literals_are_not_allowed_in_strict_mode_1121": "Osmičkové literály nejsou ve striktním režimu povolené.", "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Osmičkové literály nejsou dostupné při cílení na ECMAScript 5 a vyšší. Použijte syntaxi {0}.", - "Only_ECMAScript_imports_may_use_import_type_1370": "import type můžou používat jen importy ECMAScript.", "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "V příkazu for...in se povoluje deklarovat jenom jednu proměnnou.", "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "V příkazu for...of se povoluje deklarovat jenom jednu proměnnou.", "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Klíčovým slovem new se dá volat jenom funkce void.", @@ -920,9 +922,11 @@ "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Odkazy projektu nemůžou tvořit cyklický graf. Zjistil se cyklus: {0}", "Projects_in_this_build_Colon_0_6355": "Projekty v tomto sestavení: {0}", "Projects_to_reference_6300": "Projekty, které se mají odkazovat", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "Vlastnost {0} pochází ze signatury indexu, proto je zapotřebí k ní přistupovat pomocí ['{0}'].", "Property_0_does_not_exist_on_const_enum_1_2479": "Vlastnost {0} ve výčtu const {1} neexistuje.", "Property_0_does_not_exist_on_type_1_2339": "Vlastnost {0} v typu {1} neexistuje.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "Vlastnost {0} v typu {1} neexistuje. Měli jste na mysli {2}?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "Vlastnost {0} v typu {1} neexistuje. Chtěli jste místo toho přistoupit ke statickému členu {2}?", "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "Vlastnost {0} neexistuje u typu {1}. Potřebujete změnit cílovou knihovnu? Zkuste změnit možnost kompilátoru lib na {2} nebo novější.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Vlastnost {0} nemá žádný inicializátor a není jednoznačně přiřazena v konstruktoru.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Vlastnost {0} má implicitně typ any, protože její přistupující objekt get nemá anotaci návratového typu.", @@ -932,7 +936,6 @@ "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Vlastnost {0} v typu {1} nejde přiřadit ke stejné vlastnosti v základním typu {2}.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Vlastnost {0} v typu {1} nejde přiřadit typu {2}.", "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "Vlastnost {0} v typu {1} odkazuje na jiného člena, ke kterému není možné získat přístup z typu {2}.", - "Property_0_is_a_static_member_of_type_1_2576": "Vlastnost {0} není statický člen typu {1}.", "Property_0_is_declared_but_its_value_is_never_read_6138": "Deklaruje se vlastnost {0}, ale její hodnota se vůbec nečte.", "Property_0_is_incompatible_with_index_signature_2530": "Vlastnost {0} není kompatibilní se signaturou indexu.", "Property_0_is_incompatible_with_rest_element_type_2573": "Vlastnost {0} není kompatibilní s typem elementu rest.", @@ -1007,6 +1010,7 @@ "Report_errors_in_js_files_8019": "Ohlásit chyby v souborech .js", "Report_errors_on_unused_locals_6134": "Umožňuje nahlásit chyby u nevyužitých místních hodnot.", "Report_errors_on_unused_parameters_6135": "Umožňuje nahlásit chyby u nevyužitých parametrů.", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803": "Vyžadovat, aby nedeklarované vlastnosti ze signatur indexů používaly přístupy k elementům", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Požadované parametry typu nemůžou být až za volitelnými parametry typu.", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "Překlad pro modul {0} se našel v mezipaměti umístění {1}.", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "keyof překládejte jen na názvy vlastností s hodnotami typu string (ne čísla ani symboly).", @@ -1146,7 +1150,7 @@ "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "První parametr metody then příslibu musí být zpětné volání.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Globální typ JSX.{0} by neměl mít více než jednu vlastnost.", "The_implementation_signature_is_declared_here_2750": "Signatura implementace se deklarovala tady.", - "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "Metavlastnost import.meta se povoluje jen v případě, že možnost --module je nastavená na esnext nebo system.", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system_1343": "Metavlastnost import.meta se povoluje jen v případě, že možnost --module je nastavená na es2020, esnext nebo system.", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Odvozený typ {0} se nedá pojmenovat bez odkazu na {1}. Pravděpodobně to nebude přenosné. Vyžaduje se anotace typu.", "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "Odvozený typ {0} se odkazuje na typ s cyklickou strukturou, která se nedá triviálně serializovat. Musí se použít anotace typu.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Odvozený typ {0} odkazuje na nepřístupný typ {1}. Musí se použít anotace typu.", @@ -1216,7 +1220,7 @@ "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "Tento výraz se nedá volat, protože je to přístupový objekt get. Nechtěli jste ho použít bez ()?", "This_expression_is_not_constructable_2351": "Tento výraz se nedá vytvořit.", "This_file_already_has_a_default_export_95130": "Tento soubor už má výchozí export.", - "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "Tento import se nikdy nepoužívá jako hodnota a musí používat import type, protože importsNotUsedAsValues je nastavené na error.", + "This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set__1371": "Tento import se nikdy nepoužívá jako hodnota a musí používat import type, protože importsNotUsedAsValues je nastavené na error.", "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Toto je deklarace, která se rozšiřuje. Zvažte možnost přesunout rozšiřující deklaraci do stejného souboru.", "This_may_be_converted_to_an_async_function_80006": "Toto je možné převést na asynchronní funkci.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "Na tento modul je možné se pomocí importů nebo exportů ECMAScript odkazovat jen tak, že se zapne příznak {0} a odkáže se na výchozí export.", @@ -1342,6 +1346,8 @@ "Updating_output_of_project_0_6373": "Aktualizuje se výstup projektu {0}...", "Updating_output_timestamps_of_project_0_6359": "Aktualizují se výstupní časová razítka projektu {0}...", "Updating_unchanged_output_timestamps_of_project_0_6371": "Aktualizují se nezměněná výstupní časová razítka projektu {0}...", + "Use_element_access_for_0_95145": "Použít přístup k elementům pro {0}", + "Use_element_access_for_all_undeclared_properties_95146": "Použít přístup k elementům pro všechny nedeklarované vlastnosti", "Use_synthetic_default_member_95016": "Použije syntetického výchozího člena.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Použití řetězce v příkazu for...of se podporuje jenom v ECMAScript 5 nebo vyšší verzi.", "Using_compiler_options_of_project_reference_redirect_0_6215": "Using compiler options of project reference redirect '{0}'.", diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json index dc1fb7e93ff6d..fd5b94c64271a 100644 --- a/lib/de/diagnosticMessages.generated.json +++ b/lib/de/diagnosticMessages.generated.json @@ -199,6 +199,7 @@ "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Eine Implementierung darf nicht in Umgebungskontexten deklariert werden.", "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "Ein Importalias kann nicht auf eine Deklaration verweisen, die mithilfe von \"export type\" exportiert wurde.", "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "Ein Importalias kann nicht auf eine Deklaration verweisen, die mithilfe von \"import type\" importiert wurde.", + "An_import_alias_cannot_use_import_type_1392": "Ein Importalias kann \"import type\" nicht verwenden.", "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Eine Importdeklaration darf nur in einem Namespace oder Modul verwendet werden.", "An_import_declaration_cannot_have_modifiers_1191": "Eine Importdeklaration darf keine Modifizierer besitzen.", "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Ein Importpfad darf nicht mit einer Erweiterung \"{0}\" enden. Importieren Sie ggf. stattdessen \"{1}\".", @@ -443,6 +444,7 @@ "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Der Standardexport des Moduls besitzt oder verwendet den privaten Namen \"{0}\".", "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "Definitionen der folgenden Bezeichner stehen in Konflikt mit denen in einer anderen Datei: {0}", "Delete_all_unused_declarations_95024": "Alle nicht verwendeten Deklarationen löschen", + "Delete_all_unused_imports_95147": "Alle nicht verwendeten Importe löschen", "Delete_the_outputs_of_all_projects_6365": "Ausgaben aller Projekte löschen", "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Veraltet] Verwenden Sie stattdessen \"--jsxFactory\". Geben Sie das Objekt an, das für \"createElement\" aufgerufen wurde, wenn das Ziel die JSX-Ausgabe \"react\" ist.", "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Veraltet] Verwenden Sie stattdessen \"--outFile\". Verketten und Ausgeben in eine einzige Datei", @@ -668,6 +670,7 @@ "Index_signatures_are_incompatible_2330": "Die Indexsignaturen sind nicht kompatibel.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Einzelne Deklarationen in der gemergten Deklaration \"{0}\" müssen alle exportiert oder alle lokal sein.", "Infer_all_types_from_usage_95023": "Alle Typen aus der Syntax ableiten", + "Infer_function_return_type_95148": "Funktionsrückgabetyp ableiten", "Infer_parameter_types_from_usage_95012": "Parametertypen aus der Nutzung ableiten", "Infer_this_type_of_0_from_usage_95080": "Typ \"this\" von \"{0}\" aus Syntax ableiten", "Infer_type_of_0_from_usage_95011": "Typ von \"{0}\" aus der Nutzung ableiten", @@ -814,7 +817,6 @@ "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Oktalliterale sind in einem Mitgliederenumerationsinitialisierer nicht zulässig. Verwenden Sie die Syntax \"{0}\".", "Octal_literals_are_not_allowed_in_strict_mode_1121": "Oktalliterale sind im Strict-Modus unzulässig.", "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Oktalliterale sind bei der Zielgruppenadressierung von ECMAScript 5 und höher nicht verfügbar. Verwenden Sie die Syntax \"{0}\".", - "Only_ECMAScript_imports_may_use_import_type_1370": "Nur ECMAScript-Importe können \"import type\" verwenden.", "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "In einer for...in-Anweisung ist nur eine einzige Variablendeklaration zulässig.", "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "In einer for...of-Anweisung ist nur eine einzige Variablendeklaration zulässig.", "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Nur eine void-Funktion kann mit dem Schlüsselwort \"new\" aufgerufen werden.", @@ -920,9 +922,11 @@ "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Projektverweise dürfen keinen kreisförmigen Graphen bilden. Zyklus erkannt: {0}", "Projects_in_this_build_Colon_0_6355": "Projekte in diesem Build: {0}", "Projects_to_reference_6300": "Zu referenzierende Projekte", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "Die Eigenschaft \"{0}\" stammt aus einer Indexsignatur. Der Zugriff muss daher mit [\"{0}\"] erfolgen.", "Property_0_does_not_exist_on_const_enum_1_2479": "Die Eigenschaft \"{0}\" ist für die const-Enumeration \"{1}\" nicht vorhanden.", "Property_0_does_not_exist_on_type_1_2339": "Die Eigenschaft \"{0}\" ist für den Typ \"{1}\" nicht vorhanden.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "Die Eigenschaft \"{0}\" existiert nicht für Typ \"{1}\". Meinten Sie \"{2}\"?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "Die Eigenschaft \"{0}\" ist für den Typ \"{1}\" nicht vorhanden. Möchten Sie stattdessen auf den statischen Member \"{2}\" zugreifen?", "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "Die Eigenschaft \"{0}\" ist für den Typ \"{1}\" nicht vorhanden. Müssen Sie Ihre Zielbibliothek ändern? Ändern Sie die Compileroption \"lib\" in \"{2}\" oder höher.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Die Eigenschaft \"{0}\" weist keinen Initialisierer auf und ist im Konstruktor nicht definitiv zugewiesen.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Die Eigenschaft \"{0}\" weist implizit den Typ \"any\" auf, weil ihrem get-Accessor eine Parametertypanmerkung fehlt.", @@ -932,7 +936,6 @@ "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Die Eigenschaft \"{0}\" im Typ \"{1}\" kann nicht der gleichen Eigenschaft in Basistyp \"{2}\" zugewiesen werden.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Die Eigenschaft \"{0}\" im Typ \"{1}\" kann dem Typ \"{2}\" nicht zugewiesen werden.", "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "Die Eigenschaft \"{0}\" im Typ \"{1}\" verweist auf einen anderen Member, auf den nicht aus Typ \"{2}\" zugegriffen werden kann.", - "Property_0_is_a_static_member_of_type_1_2576": "Die Eigenschaft \"{0}\" ist ein statischer Member vom Typ \"{1}\".", "Property_0_is_declared_but_its_value_is_never_read_6138": "Die Eigenschaft \"{0}\" ist deklariert, aber ihr Wert wird nie gelesen.", "Property_0_is_incompatible_with_index_signature_2530": "Die Eigenschaft \"{0}\" ist nicht mit der Indexsignatur kompatibel.", "Property_0_is_incompatible_with_rest_element_type_2573": "Die Eigenschaft \"{0}\" ist nicht mit dem rest-Elementtyp kompatibel.", @@ -1007,6 +1010,7 @@ "Report_errors_in_js_files_8019": "Fehler in .js-Dateien melden.", "Report_errors_on_unused_locals_6134": "Fehler für nicht verwendete lokale Variablen melden.", "Report_errors_on_unused_parameters_6135": "Fehler für nicht verwendete Parameter melden.", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803": "Nicht deklarierte Eigenschaften aus Indexsignaturen müssen Elementzugriffe verwenden.", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Erforderliche Typparameter dürfen nicht auf optionale Typparameter folgen.", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "Die Auflösung für das Modul \"{0}\" wurde im Cache des Standorts \"{1}\" gefunden.", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "\"keyof\" darf nur in Eigenschaftennamen mit Zeichenfolgenwert aufgelöst werden (keine Ziffern oder Symbole).", @@ -1146,7 +1150,7 @@ "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Der erste Parameter der \"then\"-Methode einer Zusage muss ein Rückruf sein.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Der globale Typ \"JSX.{0}\" darf nur eine Eigenschaft aufweisen.", "The_implementation_signature_is_declared_here_2750": "Die Implementierungssignatur wird hier deklariert.", - "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "Die Metaeigenschaft \"import.meta\" ist nur zulässig, wenn die Option \"--module\" den Wert \"esnext\" oder \"system\" aufweist.", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system_1343": "Die Metaeigenschaft \"import.meta\" ist nur zulässig, wenn die Option \"--module\" den Wert \"es2020\", \"esnext\" oder \"system\" aufweist.", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Der abgeleitete Typ von \"{0}\" kann nicht ohne einen Verweis auf \"{1}\" benannt werden. Eine Portierung ist wahrscheinlich nicht möglich. Eine Typanmerkung ist erforderlich.", "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "Der abgeleitete Typ von \"{0}\" verweist auf einen Typ mit zyklischer Struktur, die nicht trivial serialisiert werden kann. Es ist eine Typanmerkung erforderlich.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Der abgeleitete Typ von \"{0}\" verweist auf einen Typ \"{1}\", auf den nicht zugegriffen werden kann. Eine Typanmerkung ist erforderlich.", @@ -1216,7 +1220,7 @@ "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "Dieser Ausdruck kann nicht aufgerufen werden, weil es sich um eine get-Zugriffsmethode handelt. Möchten Sie den Wert ohne \"()\" verwenden?", "This_expression_is_not_constructable_2351": "Dieser Ausdruck kann nicht erstellt werden.", "This_file_already_has_a_default_export_95130": "Diese Datei weist bereits einen Standardexport auf.", - "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "Dieser Import wird nie als Wert verwendet und muss \"import type\" verwenden, weil \"importsNotUsedAsValues\" auf \"error\" festgelegt ist.", + "This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set__1371": "Dieser Import wird nie als Wert verwendet und muss \"import type\" verwenden, weil \"importsNotUsedAsValues\" auf \"error\" festgelegt ist.", "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Dies ist die erweiterte Deklaration. Die erweiternde Deklaration sollte in dieselbe Datei verschoben werden.", "This_may_be_converted_to_an_async_function_80006": "Es kann eine Konvertierung in ein asynchrone Funktion durchgeführt werden.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "Auf dieses Modul kann nur mit ECMAScript-Importen/-Exporten verwiesen werden, indem das Flag \"{0}\" aktiviert und auf den Standardexport verwiesen wird.", @@ -1342,6 +1346,8 @@ "Updating_output_of_project_0_6373": "Ausgabe von Projekt \"{0}\" wird aktualisiert...", "Updating_output_timestamps_of_project_0_6359": "Ausgabezeitstempel von Projekt \"{0}\" werden aktualisiert...", "Updating_unchanged_output_timestamps_of_project_0_6371": "Unveränderte Ausgabezeitstempel von Projekt \"{0}\" werden aktualisiert...", + "Use_element_access_for_0_95145": "Elementzugriff für \"{0}\" verwenden", + "Use_element_access_for_all_undeclared_properties_95146": "Elementzugriff für alle nicht deklarierten Eigenschaften verwenden", "Use_synthetic_default_member_95016": "Verwenden Sie den synthetischen Member \"default\".", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Das Verwenden einer Zeichenfolge in einer for...of-Anweisung wird nur in ECMAScript 5 oder höher unterstützt.", "Using_compiler_options_of_project_reference_redirect_0_6215": "Compileroptionen der Projektverweisumleitung \"{0}\" werden verwendet.", diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json index 469d98901aa1a..3915265e39646 100644 --- a/lib/es/diagnosticMessages.generated.json +++ b/lib/es/diagnosticMessages.generated.json @@ -199,6 +199,7 @@ "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Una implementación no se puede declarar en contextos de ambiente.", "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "Un alias de importación no puede hacer referencia a una declaración que se exportó mediante \"export type\".", "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "Un alias de importación no puede hacer referencia a una declaración que se importó mediante \"import type\".", + "An_import_alias_cannot_use_import_type_1392": "Un alias de importación no puede usar \"import type\"", "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Una declaración de importación solo se puede usar en un espacio de nombres o un módulo.", "An_import_declaration_cannot_have_modifiers_1191": "Una declaración de importación no puede tener modificadores.", "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Una ruta de acceso de importación no puede terminar con una extensión '{0}'. Puede importar '{1}' en su lugar.", @@ -443,6 +444,7 @@ "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "La exportación predeterminada del módulo tiene o usa el nombre privado '{0}'.", "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "Las definiciones de los identificadores siguientes entran en conflicto con las de otro archivo: {0}", "Delete_all_unused_declarations_95024": "Eliminar todas las declaraciones sin usar", + "Delete_all_unused_imports_95147": "Eliminar todas las importaciones sin usar", "Delete_the_outputs_of_all_projects_6365": "Eliminar las salidas de todos los proyectos", "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[En desuso] Use \"--jsxFactory\" en su lugar. Especifique el objeto invocado para createElement cuando el destino sea la emisión de JSX \"react\"", "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[En desuso] Use \"--outFile\" en su lugar. Concatena y emite la salida en un solo archivo.", @@ -668,6 +670,7 @@ "Index_signatures_are_incompatible_2330": "Las signaturas de índice no son compatibles.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Las declaraciones individuales de la declaración '{0}' combinada deben ser todas exportadas o todas locales.", "Infer_all_types_from_usage_95023": "Deducir todos los tipos del uso", + "Infer_function_return_type_95148": "Deducir el tipo de valor devuelto de función", "Infer_parameter_types_from_usage_95012": "Deducir los tipos de parámetro del uso", "Infer_this_type_of_0_from_usage_95080": "Inferir el tipo \"this\" de \"{0}\" a partir del uso", "Infer_type_of_0_from_usage_95011": "Deducir el tipo de \"{0}\" del uso", @@ -814,7 +817,6 @@ "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "No se permiten literales octales en el inicializador de miembros de enumeraciones. Use la sintaxis \"{0}\".", "Octal_literals_are_not_allowed_in_strict_mode_1121": "Los literales octales no se permiten en modo strict.", "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Los literales octales no están disponibles cuando el destino es ECMAScript 5 y superior. Use la sintaxis \"{0}\".", - "Only_ECMAScript_imports_may_use_import_type_1370": "Solo las importaciones de ECMAScript pueden usar \"import type\".", "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "Solo se permite una declaración de variable en una instrucción \"for...in\".", "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "Solo se permite una declaración de variable en una instrucción \"for...of\".", "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Solo se puede llamar a una función void con la palabra clave \"new\".", @@ -920,9 +922,11 @@ "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Las referencias del proyecto no pueden formar un gráfico circular. Ciclo detectado: {0}", "Projects_in_this_build_Colon_0_6355": "Proyectos de esta compilación: {0}", "Projects_to_reference_6300": "Proyectos a los que se hará referencia", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "La propiedad \"{0}\" procede de una signatura de índice, por lo que debe accederse a ella con [\"{0}\"].", "Property_0_does_not_exist_on_const_enum_1_2479": "La propiedad '{0}' no existe en la enumeración 'const' '{1}'.", "Property_0_does_not_exist_on_type_1_2339": "La propiedad '{0}' no existe en el tipo '{1}'.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "La propiedad \"{0}\" no existe en el tipo \"{1}\". ¿Quería decir \"{2}\"?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "La propiedad \"{0}\" no existe en el tipo \"{1}\". ¿Pretendía acceder al miembro estático \"{2}\"?", "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "No existe la propiedad \"{0}\" en el tipo \"{1}\". ¿Necesita cambiar la biblioteca de destino? Pruebe a cambiar la opción del compilador \"lib\" a \"{2}\" o posterior.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La propiedad \"{0}\" no tiene inicializador y no está asignada de forma definitiva en el constructor.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La propiedad '{0}' tiene el tipo 'any' de forma implícita, porque a su descriptor de acceso get le falta una anotación de tipo de valor devuelto.", @@ -932,7 +936,6 @@ "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "La propiedad \"{0}\" del tipo \"{1}\" no se puede asignar a la misma propiedad del tipo base \"{2}\".", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "La propiedad \"{0}\" del tipo \"{1}\" no se puede asignar al tipo \"{2}\".", "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "La propiedad \"{0}\" del tipo \"{1}\" hace referencia a un miembro distinto al que no se puede acceder desde el tipo \"{2}\".", - "Property_0_is_a_static_member_of_type_1_2576": "La propiedad \"{0}\" es un miembro estático del tipo \"{1}\".", "Property_0_is_declared_but_its_value_is_never_read_6138": "La propiedad \"{0}\" se declara, pero su valor no se lee nunca.", "Property_0_is_incompatible_with_index_signature_2530": "La propiedad '{0}' es incompatible con la signatura de índice.", "Property_0_is_incompatible_with_rest_element_type_2573": "La propiedad \"{0}\" es incompatible con el tipo de elemento rest.", @@ -1007,6 +1010,7 @@ "Report_errors_in_js_files_8019": "Notifique los errores de los archivos .js.", "Report_errors_on_unused_locals_6134": "Informe de errores sobre variables locales no usadas.", "Report_errors_on_unused_parameters_6135": "Informe de errores sobre parámetros no usados.", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803": "Se requieren propiedades no declaradas de las signaturas de índice para usar los accesos de elemento.", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Los parámetros de tipo requeridos pueden no seguir parámetros de tipo opcionales.", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "La resolución del módulo \"{0}\" se encontró en la memoria caché de la ubicación \"{1}\".", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolver \"keyof\" exclusivamente como nombres de propiedad con valores de cadena (sin números ni símbolos).", @@ -1146,7 +1150,7 @@ "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "El primer parámetro del método \"then\" de una promesa debe ser una devolución de llamada.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "El tipo \"JSX.{0}\" global no puede tener más de una propiedad.", "The_implementation_signature_is_declared_here_2750": "La signatura de implementación se declara aquí.", - "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "La propiedad Meta \"import.meta\" solo se permite cuando la opción \"--module\" es \"esnext\" o \"system\".", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system_1343": "La propiedad Meta \"import.meta\" solo se permite cuando la opción \"--module\" es \"es2020\", \"esnext\" o \"system\".", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "No se puede asignar un nombre al tipo inferido de \"{0}\" sin una referencia a \"{1}\". Es probable que no sea portable. Se requiere una anotación de tipo.", "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "El tipo deducido de \"{0}\" hace referencia a un tipo con una estructura cíclica que no se puede serializar trivialmente. Es necesaria una anotación de tipo.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "El tipo inferido de \"{0}\" hace referencia a un tipo \"{1}\" no accesible. Se requiere una anotación de tipo.", @@ -1216,7 +1220,7 @@ "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "No se puede llamar a esta expresión porque es un descriptor de acceso \"get\". ¿Pretendía usarlo sin \"()\"?", "This_expression_is_not_constructable_2351": "No se puede construir esta expresión.", "This_file_already_has_a_default_export_95130": "Este archivo ya tiene una exportación predeterminada", - "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "Esta importación nunca se usa como valor y debe utilizar \"import type\" porque el valor \"importsNotUsedAsValues\" está establecido en \"error\".", + "This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set__1371": "Esta importación nunca se usa como valor y debe utilizar \"import type\" porque \"importsNotUsedAsValues\" está establecido en \"error\".", "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Esta es la declaración que se está aumentando. Considere la posibilidad de mover la declaración en aumento al mismo archivo.", "This_may_be_converted_to_an_async_function_80006": "Puede convertirse en una función asincrónica.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "Solo se puede hacer referencia a este módulo con las importaciones o exportaciones de ECMAScript mediante la activación de la marca \"{0}\" y la referencia a su exportación predeterminada.", @@ -1342,6 +1346,8 @@ "Updating_output_of_project_0_6373": "Actualizando la salida del proyecto \"{0}\"...", "Updating_output_timestamps_of_project_0_6359": "Actualizando las marcas de hora de salida del proyecto \"{0}\"...", "Updating_unchanged_output_timestamps_of_project_0_6371": "Actualizando las marcas de hora de salida no modificadas del proyecto \"{0}\"...", + "Use_element_access_for_0_95145": "Usar acceso de elemento para \"{0}\"", + "Use_element_access_for_all_undeclared_properties_95146": "Use el acceso de elemento para todas las propiedades no declaradas.", "Use_synthetic_default_member_95016": "Use el miembro sintético \"default\".", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "El uso de una cadena en una instrucción \"for...of\" solo se admite en ECMAScript 5 y versiones posteriores.", "Using_compiler_options_of_project_reference_redirect_0_6215": "Uso de las opciones del compilador de redireccionamiento de la referencia del proyecto \"{0}\".", diff --git a/lib/fr/diagnosticMessages.generated.json b/lib/fr/diagnosticMessages.generated.json index 77604a61dba6c..6536e5a33285a 100644 --- a/lib/fr/diagnosticMessages.generated.json +++ b/lib/fr/diagnosticMessages.generated.json @@ -199,6 +199,7 @@ "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Impossible de déclarer une implémentation dans des contextes ambiants.", "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "Un alias d'importation ne peut pas référencer une déclaration exportée à l'aide de 'export type'.", "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "Un alias d'importation ne peut pas référencer une déclaration importée à l'aide de 'import type'.", + "An_import_alias_cannot_use_import_type_1392": "Un alias d'importation ne peut pas utiliser 'import type'", "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Une déclaration d'importation peut uniquement être utilisée dans un espace de noms ou un module.", "An_import_declaration_cannot_have_modifiers_1191": "Une déclaration d'importation ne peut pas avoir de modificateurs.", "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Un chemin d'importation ne peut pas finir par une extension '{0}'. Importez '{1}' à la place.", @@ -443,6 +444,7 @@ "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "L'exportation par défaut du module a utilisé ou utilise le nom privé '{0}'.", "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "Les définitions des identificateurs suivants sont en conflit avec celles d'un autre fichier : {0}", "Delete_all_unused_declarations_95024": "Supprimer toutes les déclarations inutilisées", + "Delete_all_unused_imports_95147": "Supprimer toutes les importations inutilisées", "Delete_the_outputs_of_all_projects_6365": "Supprimer les sorties de tous les projets", "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Déconseillé] Utilisez '--jsxFactory' à la place. Permet de spécifier l'objet appelé pour createElement durant le ciblage de 'react' pour l'émission JSX", "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Déconseillé] Utilisez '--outFile' à la place. Permet de concaténer et d'émettre la sortie vers un seul fichier", @@ -668,6 +670,7 @@ "Index_signatures_are_incompatible_2330": "Les signatures d'index sont incompatibles.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Les déclarations individuelles de la déclaration fusionnée '{0}' doivent toutes être exportées ou locales.", "Infer_all_types_from_usage_95023": "Déduire tous les types de l'utilisation", + "Infer_function_return_type_95148": "Déduire le type de retour de la fonction", "Infer_parameter_types_from_usage_95012": "Déduire les types des paramètres à partir de l'utilisation", "Infer_this_type_of_0_from_usage_95080": "Déduire le type 'this' de '{0}' à partir de l'utilisation", "Infer_type_of_0_from_usage_95011": "Déduire le type de '{0}' à partir de l'utilisation", @@ -814,7 +817,6 @@ "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Les littéraux octaux ne sont pas autorisés dans l'initialiseur des membres d'enums. Utilisez la syntaxe '{0}'.", "Octal_literals_are_not_allowed_in_strict_mode_1121": "Les littéraux octaux ne sont pas autorisés en mode strict.", "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Les littéraux octaux ne sont pas disponibles lorsque vous ciblez ECMAScript 5 et ultérieur. Utilisez la syntaxe '{0}'.", - "Only_ECMAScript_imports_may_use_import_type_1370": "Seules les importations ECMAScript peuvent utiliser 'import type'.", "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "Une seule déclaration de variable est autorisée dans une instruction 'for...in'.", "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "Seule une déclaration de variable unique est autorisée dans une instruction 'for...of'.", "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Seule une fonction void peut être appelée avec le mot clé 'new'.", @@ -920,9 +922,11 @@ "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Les références de projet ne peuvent pas former un graphe circulaire. Cycle détecté : {0}", "Projects_in_this_build_Colon_0_6355": "Projets dans cette build : {0}", "Projects_to_reference_6300": "Projets à référencer", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "La propriété '{0}' est issue d'une signature d'index, elle doit donc faire l'objet d'un accès avec ['{0}'].", "Property_0_does_not_exist_on_const_enum_1_2479": "La propriété '{0}' n'existe pas sur l'enum 'const' '{1}'.", "Property_0_does_not_exist_on_type_1_2339": "La propriété '{0}' n'existe pas sur le type '{1}'.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "La propriété '{0}' n'existe pas sur le type '{1}'. Est-ce qu'il ne s'agit pas plutôt de '{2}' ?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "La propriété '{0}' n'existe pas sur le type '{1}'. Ne vouliez-vous pas plutôt accéder au membre statique '{2}' ?", "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "La propriété '{0}' n'existe pas sur le type '{1}'. Devez-vous changer votre bibliothèque cible ? Essayez de changer l'option de compilateur 'lib' en '{2}' ou une version ultérieure.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La propriété '{0}' n'a aucun initialiseur et n'est pas définitivement assignée dans le constructeur.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La propriété '{0}' a implicitement le type 'any', car son accesseur get ne dispose pas d'une annotation de type de retour.", @@ -932,7 +936,6 @@ "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Impossible d'assigner la propriété '{0}' du type '{1}' à la même propriété du type de base '{2}'.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "La propriété '{0}' du type '{1}' ne peut pas être assignée au type '{2}'.", "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "La propriété '{0}' du type '{1}' fait référence à un membre distinct, qui n'est pas accessible à partir du type '{2}'.", - "Property_0_is_a_static_member_of_type_1_2576": "La propriété '{0}' est un membre statique de type '{1}'.", "Property_0_is_declared_but_its_value_is_never_read_6138": "La propriété '{0}' est déclarée mais sa valeur n'est jamais lue.", "Property_0_is_incompatible_with_index_signature_2530": "La propriété '{0}' est incompatible avec la signature d'index.", "Property_0_is_incompatible_with_rest_element_type_2573": "La propriété '{0}' est incompatible avec le type d'élément rest.", @@ -1007,6 +1010,7 @@ "Report_errors_in_js_files_8019": "Signalez les erreurs dans les fichiers .js.", "Report_errors_on_unused_locals_6134": "Signaler les erreurs sur les variables locales inutilisées.", "Report_errors_on_unused_parameters_6135": "Signaler les erreurs sur les paramètres inutilisés.", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803": "Les propriétés non déclarées sont imposées à partir des signatures d'index pour permettre l'utilisation des accès aux éléments.", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Les paramètres de type obligatoires ne peuvent pas être placés à la suite des paramètres de type optionnels.", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "La résolution du module '{0}' a été trouvée dans le cache à l'emplacement '{1}'.", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Résoudre 'keyof' en noms de propriétés de valeur chaîne uniquement (aucun nombre ou symbole).", @@ -1216,7 +1220,7 @@ "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "Impossible d'appeler cette expression, car il s'agit d'un accesseur 'get'. Voulez-vous vraiment l'utiliser sans '()' ?", "This_expression_is_not_constructable_2351": "Impossible de construire cette expression.", "This_file_already_has_a_default_export_95130": "Ce fichier a déjà une exportation par défaut", - "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "Cette importation n'est jamais utilisée en tant que valeur. Elle doit utiliser 'import type', car 'importsNotUsedAsValues' a la valeur 'error'.", + "This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set__1371": "Cette importation n'est jamais utilisée en tant que valeur. Elle doit utiliser 'import type', car 'importsNotUsedAsValues' a la valeur 'error'.", "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Ceci est la déclaration augmentée. Pensez à déplacer la déclaration d'augmentation dans le même fichier.", "This_may_be_converted_to_an_async_function_80006": "Ceci peut être converti en fonction asynchrone.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "Vous pouvez référencer ce module uniquement avec les importations/exportations ECMAScript en activant l'indicateur '{0}' et en référençant son exportation par défaut.", @@ -1342,6 +1346,8 @@ "Updating_output_of_project_0_6373": "Mise à jour de la sortie du projet '{0}'...", "Updating_output_timestamps_of_project_0_6359": "Mise à jour des horodatages de sortie du projet '{0}'...", "Updating_unchanged_output_timestamps_of_project_0_6371": "Mise à jour des horodatages de sortie inchangés du projet '{0}'...", + "Use_element_access_for_0_95145": "Utiliser l'accès à l'élément pour '{0}'", + "Use_element_access_for_all_undeclared_properties_95146": "L'accès à l'élément est utilisé pour toutes les propriétés non déclarées.", "Use_synthetic_default_member_95016": "Utilisez un membre 'default' synthétique.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "L'utilisation d'une chaîne dans une instruction 'for...of' est prise en charge uniquement dans ECMAScript 5 et version supérieure.", "Using_compiler_options_of_project_reference_redirect_0_6215": "Utilisation des options de compilateur de la redirection de référence de projet : '{0}'.", diff --git a/lib/it/diagnosticMessages.generated.json b/lib/it/diagnosticMessages.generated.json index 4b2f431dca499..89f966406732e 100644 --- a/lib/it/diagnosticMessages.generated.json +++ b/lib/it/diagnosticMessages.generated.json @@ -199,6 +199,7 @@ "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Non è possibile dichiarare un'implementazione in contesti di ambiente.", "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "Un alias di importazione non può fare riferimento a una dichiarazione esportata con 'export type'.", "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "Un alias di importazione non può fare riferimento a una dichiarazione importata con 'import type'.", + "An_import_alias_cannot_use_import_type_1392": "Un alias di importazione non può usare 'import type'", "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "È possibile usare una dichiarazione di importazione solo in uno spazio dei nomi o in un modulo.", "An_import_declaration_cannot_have_modifiers_1191": "Una dichiarazione di importazione non può contenere modificatori.", "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Un percorso di importazione non può terminare con l'estensione '{0}'. In alternativa, provare a importare '{1}'.", @@ -443,6 +444,7 @@ "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "L'esportazione predefinita del modulo contiene o usa il nome privato '{0}'.", "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "Le definizioni degli identificatori seguenti sono in conflitto con quelle di un altro file: {0}", "Delete_all_unused_declarations_95024": "Eliminare tutte le dichiarazioni non usate", + "Delete_all_unused_imports_95147": "Eliminare tutte le direttive import non usate", "Delete_the_outputs_of_all_projects_6365": "Eliminare gli output di tutti i progetti", "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Deprecata] In alternativa, usare '--jsxFactory'. Specifica l'oggetto richiamato per createElement quando la destinazione è la creazione JSX 'react'", "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Deprecata] In alternativa, usare '--outFile'. Concatena e crea l'output in un singolo file", @@ -668,6 +670,7 @@ "Index_signatures_are_incompatible_2330": "Le firme dell'indice sono incompatibili.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Le singole dichiarazioni della dichiarazione sottoposta a merge '{0}' devono essere tutte esportate o tutte locali.", "Infer_all_types_from_usage_95023": "Derivare tutti i tipi dall'utilizzo", + "Infer_function_return_type_95148": "Dedurre il tipo restituito della funzione", "Infer_parameter_types_from_usage_95012": "Derivare i tipi di parametro dall'utilizzo", "Infer_this_type_of_0_from_usage_95080": "Derivare il tipo 'this' di '{0}' dall'utilizzo", "Infer_type_of_0_from_usage_95011": "Derivare il tipo di '{0}' dall'utilizzo", @@ -814,7 +817,6 @@ "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "I valori letterali ottali non sono consentiti nell'inizializzatore di membri di enumerazioni. Usare la sintassi '{0}'.", "Octal_literals_are_not_allowed_in_strict_mode_1121": "I valori letterali ottali non sono consentiti in modalità strict.", "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "I valori letterali ottali non sono disponibili quando la destinazione è ECMAScript 5 e versioni successive. Usare la sintassi '{0}'.", - "Only_ECMAScript_imports_may_use_import_type_1370": "Solo le importazioni ECMAScript possono usare 'import type'.", "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "In un'istruzione 'for...in' è consentita solo una singola dichiarazione di variabile.", "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "In un'istruzione 'for...of' è consentita solo una singola dichiarazione di variabile.", "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Con la parola chiave 'new' può essere chiamata solo una funzione void.", @@ -920,9 +922,11 @@ "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "I riferimenti al progetto non possono formare un grafico circolare. Ciclo rilevato: {0}", "Projects_in_this_build_Colon_0_6355": "Progetti in questa compilazione: {0}", "Projects_to_reference_6300": "Progetti cui fare riferimento", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "La proprietà '{0}' deriva da una firma dell'indice, quindi è necessario accedervi con ['{0}'].", "Property_0_does_not_exist_on_const_enum_1_2479": "La proprietà '{0}' non esiste nell'enumerazione 'const' '{1}'.", "Property_0_does_not_exist_on_type_1_2339": "La proprietà '{0}' non esiste nel tipo '{1}'.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "La proprietà '{0}' non esiste nel tipo '{1}'. Si intendeva '{2}'?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "La proprietà '{0}' non esiste nel tipo '{1}'. Si intendeva accedere al membro statico '{2}'?", "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "La proprietà '{0}' non esiste nel tipo '{1}'. È necessario modificare la libreria di destinazione? Provare a impostare l'opzione `lib` del compilatore su '{2}' o versioni successive.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La proprietà '{0}' non include alcun inizializzatore e non viene assolutamente assegnata nel costruttore.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La proprietà '{0}' contiene implicitamente il tipo 'any', perché nella relativa funzione di accesso get manca un'annotazione di tipo restituito.", @@ -932,7 +936,6 @@ "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "La proprietà '{0}' nel tipo '{1}' non è assegnabile alla stessa proprietà nel tipo di base '{2}'.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "La proprietà '{0}' nel tipo '{1}' non è assegnabile al tipo '{2}'.", "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "La proprietà '{0}' nel tipo '{1}' fa riferimento a un membro diverso a cui non è possibile accedere dall'interno del tipo '{2}'.", - "Property_0_is_a_static_member_of_type_1_2576": "La proprietà '{0}' è un membro statico di tipo '{1}'.", "Property_0_is_declared_but_its_value_is_never_read_6138": "La proprietà '{0}' è dichiarata, ma il suo valore non viene mai letto.", "Property_0_is_incompatible_with_index_signature_2530": "La proprietà '{0}' non è compatibile con la firma dell'indice.", "Property_0_is_incompatible_with_rest_element_type_2573": "La proprietà '{0}' non è compatibile con il tipo di elemento rest.", @@ -1007,6 +1010,7 @@ "Report_errors_in_js_files_8019": "Segnala gli errori presenti nei file con estensione js.", "Report_errors_on_unused_locals_6134": "Segnala errori relativi a variabili locali non usate.", "Report_errors_on_unused_parameters_6135": "Segnala errori relativi a parametri non usati.", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803": "Richiedere alle proprietà non dichiarate da firme dell'indice di usare gli accessi agli elementi.", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "I parametri di tipo obbligatori potrebbero non seguire i parametri di tipo facoltativi.", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "La risoluzione per il modulo '{0}' è stata trovata nella cache dal percorso '{1}'.", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Risolvere 'keyof' solo in nomi di proprietà con valori stringa (senza numeri o simboli).", @@ -1146,7 +1150,7 @@ "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Il primo parametro del metodo 'then' di una promessa deve essere un callback.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Il tipo globale 'JSX.{0}' non può contenere più di una proprietà.", "The_implementation_signature_is_declared_here_2750": "In questo punto viene dichiarata la firma di implementazione.", - "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "La metaproprietà 'import.meta' è consentita solo se l'opzione '--module' è impostata su 'esnext' o 'system'.", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system_1343": "La metaproprietà 'import.meta' è consentita solo se l'opzione '--module' è impostata su 'es2020', 'esnext' o 'system'.", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Non è possibile assegnare un nome al tipo derivato di '{0}' senza un riferimento a '{1}'. È probabile che non sia portabile. È necessaria un'annotazione di tipo.", "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "Il tipo dedotto di '{0}' fa riferimento a un tipo con una struttura ciclica che non può essere facilmente serializzata. È necessaria un'annotazione di tipo.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Il tipo dedotto di '{0}' fa riferimento a un tipo '{1}' non accessibile. È necessaria un'annotazione di tipo.", @@ -1216,7 +1220,7 @@ "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "Non è possibile chiamare questa espressione perché è una funzione di accesso 'get'. Si intendeva usarla senza '()'?", "This_expression_is_not_constructable_2351": "Questa espressione non può essere costruita.", "This_file_already_has_a_default_export_95130": "Per questo file esiste già un'esportazione predefinita", - "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "Questa importazione non viene mai usata come valore e deve usare 'import type' perché 'importsNotUsedAsValues' è impostato su 'error'.", + "This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set__1371": "Questa importazione non viene mai usata come valore e deve usare 'import type' perché 'importsNotUsedAsValues' è impostato su 'error'.", "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Questa è la dichiarazione che verrà aumentata. Provare a spostare la dichiarazione che causa l'aumento nello stesso file.", "This_may_be_converted_to_an_async_function_80006": "Può essere convertita in una funzione asincrona.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "È possibile fare riferimento a questo modulo solo con importazioni/esportazioni ECMAScript attivando il flag '{0}' e facendo riferimento alla relativa esportazione predefinita.", @@ -1342,6 +1346,8 @@ "Updating_output_of_project_0_6373": "Aggiornamento dell'output del progetto '{0}'...", "Updating_output_timestamps_of_project_0_6359": "Aggiornamento dei timestamp di output del progetto '{0}'...", "Updating_unchanged_output_timestamps_of_project_0_6371": "Aggiornamento dei timestamp di output non modificati del progetto '{0}'...", + "Use_element_access_for_0_95145": "Usare l'accesso agli elementi per '{0}'", + "Use_element_access_for_all_undeclared_properties_95146": "Usare l'accesso agli elementi per tutte le proprietà non dichiarate.", "Use_synthetic_default_member_95016": "Usare il membro 'default' sintetico.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "L'uso di una stringa in un'istruzione 'for...of' è supportato solo in ECMAScript 5 e versioni successive.", "Using_compiler_options_of_project_reference_redirect_0_6215": "Using compiler options of project reference redirect '{0}'.", diff --git a/lib/ja/diagnosticMessages.generated.json b/lib/ja/diagnosticMessages.generated.json index 9298ae520578a..d000046af107e 100644 --- a/lib/ja/diagnosticMessages.generated.json +++ b/lib/ja/diagnosticMessages.generated.json @@ -199,6 +199,7 @@ "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "実装は環境コンテキストでは宣言できません。", "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "インポート エイリアスは、'export type' を使用してエクスポートされた宣言を参照できません。", "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "インポート エイリアスは、'import type' を使用してインポートされた宣言を参照できません。", + "An_import_alias_cannot_use_import_type_1392": "インポート エイリアスで 'import type' を使用することはできません", "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "インポート宣言は名前空間またはモジュールでのみ使用可能です。", "An_import_declaration_cannot_have_modifiers_1191": "インポート宣言に修飾子を指定することはできません。", "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "インポート パスの末尾を拡張子 '{0}' にすることはできません。代わりに '{1}' のインポートをご検討ください。", @@ -443,6 +444,7 @@ "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "モジュールの既定エクスポートがプライベート名 '{0}' を持っているか、使用しています。", "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "次の識別子の定義が、別のファイル内の定義と競合しています: {0}", "Delete_all_unused_declarations_95024": "未使用の宣言をすべて削除します", + "Delete_all_unused_imports_95147": "未使用の import をすべて削除します", "Delete_the_outputs_of_all_projects_6365": "すべてのプロジェクトの出力を削除します", "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[非推奨] 代わりに '--jsxFactory' を使います。'react' JSX 発行を対象とするときに、createElement に対して呼び出されたオブジェクトを指定します", "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[非推奨] 代わりに '--outFile' を使います。出力を連結して 1 つのファイルを生成します", @@ -668,6 +670,7 @@ "Index_signatures_are_incompatible_2330": "インデックスの署名に互換性がありません。", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "マージされた宣言 '{0}' の個々の宣言はすべてエクスポートされるか、すべてローカルであるかのどちらかである必要があります。", "Infer_all_types_from_usage_95023": "使用法からすべての型を推論します", + "Infer_function_return_type_95148": "関数の戻り値の型を推論します", "Infer_parameter_types_from_usage_95012": "使用状況からパラメーターの型を推論する", "Infer_this_type_of_0_from_usage_95080": "使い方から '{0}' の 'this' 型を推論する", "Infer_type_of_0_from_usage_95011": "使用状況から '{0}' の型を推論する", @@ -814,7 +817,6 @@ "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "8 進数のリテラルは、列挙型メンバーの初期化子では許可されていません。構文 '{0}' を使用してください。", "Octal_literals_are_not_allowed_in_strict_mode_1121": "厳格モードでは Octal リテラルは使用できません。", "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "ECMAScript 5 以降を対象にする場合、8 進数のリテラルは使用できません。構文 '{0}' を使用してください。", - "Only_ECMAScript_imports_may_use_import_type_1370": "'import type' を使用できるのは、ECMAScript のインポートのみです。", "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "'for...in' ステートメントで使用できる変数宣言は 1 つのみです。", "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "'for...of' ステートメントで使用できる変数宣言は 1 つのみです。", "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "'new' キーワードを指定して呼び出せるのは void 関数のみです。", @@ -920,9 +922,11 @@ "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": "参照するプロジェクト", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "プロパティ '{0}' はインデックス シグネチャに基づいているため、['{0}'] を使用してアクセスする必要があります。", "Property_0_does_not_exist_on_const_enum_1_2479": "プロパティ '{0}' が 'const' 列挙型 '{1}' に存在しません。", "Property_0_does_not_exist_on_type_1_2339": "プロパティ '{0}' は型 '{1}' に存在しません。", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "プロパティ '{0}' は型 '{1}' に存在していません。'{2}' ですか?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "プロパティ '{0}' は型 '{1}' には存在しません。代わりに静的メンバー '{2}' にアクセスしようとしていましたか?", "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "プロパティ '{0}' が型 '{1}' に存在しません。ターゲット ライブラリを変更する必要がありますか? 'lib' コンパイラ オプションを '{2}' 以降に変更してみてください。", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "プロパティ '{0}' に初期化子がなく、コンストラクターで明確に割り当てられていません。", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "プロパティ '{0}' には型 'any' が暗黙的に設定されています。get アクセサーには戻り値の型の注釈がないためです。", @@ -932,7 +936,6 @@ "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "型 '{1}' のプロパティ '{0}' を基本データ型 '{2}' の同じプロパティに割り当てることはできません。", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "型 '{1}' のプロパティ '{0}' を型 '{2}' に割り当てることはできません。", "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "型 '{1}' のプロパティ '{0}' は、型 '{2}' 内からアクセスできない別のメンバーを参照しています。", - "Property_0_is_a_static_member_of_type_1_2576": "プロパティ '{0}' は型 '{1}' の静的メンバーです。", "Property_0_is_declared_but_its_value_is_never_read_6138": "プロパティ '{0}' が宣言されていますが、その値が読み取られることはありません。", "Property_0_is_incompatible_with_index_signature_2530": "プロパティ '{0}' はインデックス シグネチャと互換性がありません。", "Property_0_is_incompatible_with_rest_element_type_2573": "プロパティ '{0}' は rest 要素の型と互換性がありません。", @@ -1007,6 +1010,7 @@ "Report_errors_in_js_files_8019": ".js ファイルのエラーを報告します。", "Report_errors_on_unused_locals_6134": "使用されていないローカルに関するエラーを報告します。", "Report_errors_on_unused_parameters_6135": "使用されていないパラメーターに関するエラーを報告します。", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803": "要素アクセスを使用するには、インデックス シグネチャからの宣言されていないプロパティが必要です。", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "必須の型パラメーターの後に、オプションの型パラメーターを続けることはできません。", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "モジュール '{0}' の解決が場所 '{1}' のキャッシュに見つかりました。", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "'keyof' を文字列値のプロパティ名のみに解決します (数字または記号なし)。", @@ -1146,7 +1150,7 @@ "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise では、'then' メソッドの最初のパラメーターはコールバックでなければなりません。", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "グローバル型 'JSX.{0}' には複数のプロパティが含まれていない可能性があります。", "The_implementation_signature_is_declared_here_2750": "実装シグネチャはここで宣言されています。", - "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "'import.meta' メタプロパティは、'--module' オプションが 'esnext' または 'system' の場合にのみ許可されます。", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system_1343": "'import.meta' メタプロパティは、'--module' オプションが 'es2020'、'esnext'、または 'system' の場合にのみ許可されます。", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "'{0}' の推論された型には、'{1}' への参照なしで名前を付けることはできません。これは、移植性がない可能性があります。型の注釈が必要です。", "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "'{0}' の推論された型は、循環構造を持つ型を参照しています。この型のシリアル化は自明ではありません。型の注釈が必要です。", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}' の推定型はアクセス不可能な '{1}' 型を参照します。型の注釈が必要です。", @@ -1216,7 +1220,7 @@ "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "この式は 'get' アクセサーであるため、呼び出すことができません。'()' なしで使用しますか?", "This_expression_is_not_constructable_2351": "この式はコンストラクト可能ではありません。", "This_file_already_has_a_default_export_95130": "このファイルには、既に既定のエクスポートがあります", - "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "このインポートは値として使用されることはありません。'importsNotUsedAsValues' が 'error' に設定されているため、'import type' を使用する必要があります。", + "This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set__1371": "このインポートは値として使用されることはありません。'importsNotUsedAsValues' が 'error' に設定されているため、'import type' を使用する必要があります。", "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "これは拡張される宣言です。拡張する側の宣言を同じファイルに移動することを検討してください。", "This_may_be_converted_to_an_async_function_80006": "これは非同期関数に変換できます。", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "このモジュールは、'{0}' フラグをオンにして既定のエクスポートを参照することにより、ECMAScript のインポートまたはエクスポートのみを使用して参照できます。", @@ -1342,6 +1346,8 @@ "Updating_output_of_project_0_6373": "プロジェクト '{0}' の出力を更新しています...", "Updating_output_timestamps_of_project_0_6359": "プロジェクト '{0}' の出力タイムスタンプを更新しています...", "Updating_unchanged_output_timestamps_of_project_0_6371": "プロジェクト '{0}' の変更されていない出力タイムスタンプを更新しています...", + "Use_element_access_for_0_95145": "'{0}' に要素アクセスを使用する", + "Use_element_access_for_all_undeclared_properties_95146": "宣言されていないすべてのプロパティに対して要素アクセスを使用します。", "Use_synthetic_default_member_95016": "合成 'default' メンバーを使用します。", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "'for...of' ステートメントでの文字列の使用は ECMAScript 5 以上でのみサポートされています。", "Using_compiler_options_of_project_reference_redirect_0_6215": "Using compiler options of project reference redirect '{0}'.", diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json index afb5401daf690..6012dd7d2dc87 100644 --- a/lib/ko/diagnosticMessages.generated.json +++ b/lib/ko/diagnosticMessages.generated.json @@ -199,6 +199,7 @@ "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "앰비언트 컨텍스트에서는 구현을 선언할 수 없습니다.", "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "가져오기 별칭은 '내보내기 형식'을 사용하여 내보낸 선언을 참조할 수 없습니다.", "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "가져오기 별칭은 '가져오기 형식'을 사용하여 가져온 선언을 참조할 수 없습니다.", + "An_import_alias_cannot_use_import_type_1392": "가져오기 별칭은 'import type'을 사용할 수 없습니다.", "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "내보내기 선언은 네임스페이스 또는 모듈에서만 사용할 수 있습니다.", "An_import_declaration_cannot_have_modifiers_1191": "가져오기 선언에는 한정자를 사용할 수 없습니다.", "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "가져오기 경로는 '{0}' 확장으로 끝날 수 없습니다. 대신 '{1}' 가져오기를 고려하세요.", @@ -443,6 +444,7 @@ "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "모듈의 기본 내보내기에서 프라이빗 이름 '{0}'을(를) 가지고 있거나 사용 중입니다.", "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "{0} 식별자의 정의가 다른 파일의 정의와 충돌합니다.", "Delete_all_unused_declarations_95024": "사용하지 않는 선언 모두 삭제", + "Delete_all_unused_imports_95147": "사용하지 않는 가져오기 모두 삭제", "Delete_the_outputs_of_all_projects_6365": "모든 프로젝트의 출력 삭제", "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[사용되지 않음] 대신 '--jsxFactory'를 사용합니다. 'react' JSX 내보내기를 대상으로 할 경우 createElement에 대해 호출되는 개체를 지정합니다.", "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[사용되지 않음] 대신 '--outFile'을 사용합니다. 출력을 연결하고 단일 파일로 내보냅니다.", @@ -668,6 +670,7 @@ "Index_signatures_are_incompatible_2330": "인덱스 시그니처가 호환되지 않습니다.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "병합된 선언 '{0}'의 개별 선언은 모두 내보내 졌거나 모두 로컬이어야 합니다.", "Infer_all_types_from_usage_95023": "사용량에서 모든 형식 유추", + "Infer_function_return_type_95148": "함수 반환 형식 유추", "Infer_parameter_types_from_usage_95012": "사용량에서 매개 변수 형식 유추", "Infer_this_type_of_0_from_usage_95080": "사용량에서 '{0}'의 'this' 형식 유추", "Infer_type_of_0_from_usage_95011": "사용량에서 '{0}'의 형식 유추", @@ -814,7 +817,6 @@ "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "8진수 리터럴은 열거형 멤버 이니셜라이저에서 사용할 수 없습니다. '{0}' 구문을 사용하세요.", "Octal_literals_are_not_allowed_in_strict_mode_1121": "strict 모드에서는 8진수 리터럴이 허용되지 않습니다.", "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "ECMAScript 5 이상을 대상으로 하는 경우 8진수 리터럴을 사용할 수 없습니다. '{0}' 구문을 사용하세요.", - "Only_ECMAScript_imports_may_use_import_type_1370": "ECMAScript 가져오기만 'import type'을 사용할 수 있습니다.", "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "'for...in' 문에는 단일 변수 선언만 허용됩니다.", "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "'for...of' 문에는 단일 변수 선언만 허용됩니다.", "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "void 함수만 'new' 키워드로 호출할 수 있습니다.", @@ -920,9 +922,11 @@ "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": "참조할 프로젝트", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "'{0}' 속성은 인덱스 시그니처에서 가져오는 것이므로 ['{0}']을(를) 사용하여 액세스해야 합니다.", "Property_0_does_not_exist_on_const_enum_1_2479": "'const' 열거형 '{1}'에 '{0}' 속성이 없습니다.", "Property_0_does_not_exist_on_type_1_2339": "'{1}' 형식에 '{0}' 속성이 없습니다.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "'{0}' 속성이 '{1}' 형식에 없습니다. '{2}'을(를) 사용하시겠습니까?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "'{0}' 속성이 '{1}' 형식에 없습니다. 대신 정적 멤버 '{2}'에 액세스하려고 하셨습니까?", "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "'{0}' 속성이 '{1}' 형식에 없습니다. 대상 라이브러리를 변경해야 하는 경우 'lib' 컴파일러 옵션을 '{2}' 이상으로 변경해 보세요.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "속성 '{0}'은(는) 이니셜라이저가 없고 생성자에 할당되어 있지 않습니다.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "'{0}' 속성에는 해당 get 접근자에 반환 형식 주석이 없으므로 암시적으로 'any' 형식이 포함됩니다.", @@ -932,7 +936,6 @@ "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "'{1}' 형식의 '{0}' 속성을 기본 형식 '{2}'의 동일한 속성에 할당할 수 없습니다.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "'{1}' 형식의 '{0}' 속성을 '{2}' 형식에 할당할 수 없습니다.", "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "'{1}' 형식의 '{0}' 속성이 '{2}' 형식 내에서 액세스할 수 없는 다른 멤버를 참조합니다.", - "Property_0_is_a_static_member_of_type_1_2576": "'{0}' 속성이 '{1}' 형식의 정적 멤버가 아닙니다.", "Property_0_is_declared_but_its_value_is_never_read_6138": "속성 '{0}'이(가) 선언은 되었지만 해당 값이 읽히지는 않았습니다.", "Property_0_is_incompatible_with_index_signature_2530": "'{0}' 속성이 인덱스 시그니처와 호환되지 않습니다.", "Property_0_is_incompatible_with_rest_element_type_2573": "'{0}' 속성이 rest 요소 형식과 호환되지 않습니다.", @@ -1007,6 +1010,7 @@ "Report_errors_in_js_files_8019": ".js 파일의 오류를 보고합니다.", "Report_errors_on_unused_locals_6134": "사용되지 않은 로컬 항목에 대한 오류를 보고합니다.", "Report_errors_on_unused_parameters_6135": "사용되지 않은 매개 변수에 대한 오류를 보고합니다.", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803": "요소 액세스를 사용하려면 인덱스 시그니처의 선언되지 않은 속성이 필요합니다.", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "필수 형식 매개 변수는 선택적 형식 매개 변수 다음에 올 수 없습니다.", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "'{0}' 모듈에 대한 해결을 '{1}' 위치의 캐시에서 찾았습니다.", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "문자열 값 속성 이름에 대해서만 'keyof'를 확인합니다(숫자나 기호 아님).", @@ -1146,7 +1150,7 @@ "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "프라미스에서 'then' 메서드의 첫 번째 매개 변수는 콜백이어야 합니다.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "전역 형식 'JSX.{0}'에 속성이 둘 이상 있을 수 없습니다.", "The_implementation_signature_is_declared_here_2750": "여기에서는 구현 시그니처가 선언됩니다.", - "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "'import.meta' 메타 속성은 '--module' 옵션이 'esnext' 또는 'system'인 경우에만 사용할 수 있습니다.", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system_1343": "'import.meta' 메타 속성은 '--module' 옵션이 'es2020', 'esnext' 또는 'system'인 경우에만 허용됩니다.", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "'{0}'의 유추된 형식 이름을 지정하려면 '{1}'에 대한 참조가 있어야 합니다. 이식하지 못할 수 있습니다. 형식 주석이 필요합니다.", "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "'{0}'의 유추된 형식이 일반적으로 직렬화될 수 없는 순환 구조가 있는 형식을 참조합니다. 형식 주석이 필요합니다.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}'의 유추 형식이 액세스할 수 없는 '{1}' 형식을 참조합니다. 형식 주석이 필요합니다.", @@ -1216,7 +1220,7 @@ "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "이 식은 'get' 접근자이므로 호출할 수 없습니다. '()' 없이 사용하시겠습니까?", "This_expression_is_not_constructable_2351": "이 식은 생성할 수 없습니다.", "This_file_already_has_a_default_export_95130": "이 파일에 이미 기본 내보내기가 있습니다.", - "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "이 가져오기는 값으로 사용되지 않아야 하며 'importsNotUsedAsValues'가 'error'로 설정되어 있기 때문에 'import type'을 사용해야 합니다.", + "This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set__1371": "이 가져오기는 값으로 사용되지 않으며 'importsNotUsedAsValues'가 'error'로 설정되어 있기 때문에 'import type'을 사용해야 합니다.", "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "확대되는 선언입니다. 확대하는 선언을 같은 파일로 이동하는 것이 좋습니다.", "This_may_be_converted_to_an_async_function_80006": "비동기 함수로 변환될 수 있습니다.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "이 모듈은 '{0}' 플래그를 켜고 기본 내보내기를 참조하여 ECMAScript 가져오기/내보내기를 통해서만 참조할 수 있습니다.", @@ -1342,6 +1346,8 @@ "Updating_output_of_project_0_6373": "'{0}' 프로젝트의 출력을 업데이트하는 중...", "Updating_output_timestamps_of_project_0_6359": "'{0}' 프로젝트의 출력 타임스탬프를 업데이트하는 중...", "Updating_unchanged_output_timestamps_of_project_0_6371": "'{0}' 프로젝트의 변경되지 않은 출력 타임스탬프를 업데이트하는 중...", + "Use_element_access_for_0_95145": "'{0}'에 요소 액세스 사용", + "Use_element_access_for_all_undeclared_properties_95146": "선언되지 않은 모든 속성에 요소 액세스를 사용합니다.", "Use_synthetic_default_member_95016": "가상 '기본' 멤버를 사용합니다.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "ECMAScript 5 이상에서만 'for...of' 문에서 문자열을 사용할 수 있습니다.", "Using_compiler_options_of_project_reference_redirect_0_6215": "프로젝트 참조 리디렉션 '{0}'의 컴파일러 옵션을 사용 중입니다.", diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 960a6800eaeb4..c5cd8c3897aa2 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -22,19 +22,24 @@ and limitations under the License. /// DOM APIs ///////////////////////////// -interface Account { - displayName: string; - id: string; - imageURL?: string; - name?: string; - rpDisplayName: string; -} - interface AddEventListenerOptions extends EventListenerOptions { once?: boolean; passive?: boolean; } +interface AddressErrors { + addressLine?: string; + city?: string; + country?: string; + dependentLocality?: string; + organization?: string; + phone?: string; + postalCode?: string; + recipient?: string; + region?: string; + sortingCode?: string; +} + interface AesCbcParams extends Algorithm { iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; } @@ -84,13 +89,6 @@ interface AnimationPlaybackEventInit extends EventInit { timelineTime?: number | null; } -interface AssertionOptions { - allowList?: ScopedCredentialDescriptor[]; - extensions?: WebAuthnExtensions; - rpId?: string; - timeoutSeconds?: number; -} - interface AssignedNodesOptions { flatten?: boolean; } @@ -209,15 +207,6 @@ interface ChannelSplitterOptions extends AudioNodeOptions { numberOfOutputs?: number; } -interface ClientData { - challenge: string; - extensions?: WebAuthnExtensions; - hashAlg: string | Algorithm; - origin: string; - rpId: string; - tokenBinding?: string; -} - interface ClientQueryOptions { includeUncontrolled?: boolean; type?: ClientTypes; @@ -365,10 +354,6 @@ interface DelayOptions extends AudioNodeOptions { maxDelayTime?: number; } -interface DeviceLightEventInit extends EventInit { - value?: number; -} - interface DeviceMotionEventAccelerationInit { x?: number | null; y?: number | null; @@ -966,9 +951,14 @@ interface PannerOptions extends AudioNodeOptions { rolloffFactor?: number; } +interface PayerErrors { + email?: string; + name?: string; + phone?: string; +} + interface PaymentCurrencyAmount { currency: string; - currencySystem?: string; value: string; } @@ -992,6 +982,9 @@ interface PaymentDetailsModifier { interface PaymentDetailsUpdate extends PaymentDetailsBase { error?: string; + payerErrors?: PayerErrors; + paymentMethodErrors?: any; + shippingAddressErrors?: AddressErrors; total?: PaymentItem; } @@ -1001,17 +994,23 @@ interface PaymentItem { pending?: boolean; } +interface PaymentMethodChangeEventInit extends PaymentRequestUpdateEventInit { + methodDetails?: any; + methodName?: string; +} + interface PaymentMethodData { data?: any; supportedMethods: string | string[]; } interface PaymentOptions { + requestBillingAddress?: boolean; requestPayerEmail?: boolean; requestPayerName?: boolean; requestPayerPhone?: boolean; requestShipping?: boolean; - shippingType?: string; + shippingType?: PaymentShippingType; } interface PaymentRequestUpdateEventInit extends EventInit { @@ -1024,6 +1023,13 @@ interface PaymentShippingOption { selected?: boolean; } +interface PaymentValidationErrors { + error?: string; + payer?: PayerErrors; + paymentMethod?: any; + shippingAddress?: AddressErrors; +} + interface Pbkdf2Params extends Algorithm { hash: HashAlgorithmIdentifier; iterations: number; @@ -1165,7 +1171,7 @@ interface QueuingStrategy { interface QueuingStrategyInit { /** * Creates a new ByteLengthQueuingStrategy with the provided high water mark. - * + * * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. */ highWaterMark: number; @@ -1184,12 +1190,11 @@ interface RTCConfiguration { iceCandidatePoolSize?: number; iceServers?: RTCIceServer[]; iceTransportPolicy?: RTCIceTransportPolicy; - peerIdentity?: string; rtcpMuxPolicy?: RTCRtcpMuxPolicy; } interface RTCDTMFToneChangeEventInit extends EventInit { - tone: string; + tone?: string; } interface RTCDataChannelEventInit extends EventInit { @@ -1202,7 +1207,6 @@ interface RTCDataChannelInit { maxRetransmits?: number; negotiated?: boolean; ordered?: boolean; - priority?: RTCPriorityType; protocol?: string; } @@ -1222,7 +1226,6 @@ interface RTCErrorEventInit extends EventInit { interface RTCErrorInit { errorDetail: RTCErrorDetailType; - httpRequestStatusCode?: number; receivedAlert?: number; sctpCauseCode?: number; sdpLineNumber?: number; @@ -1312,7 +1315,7 @@ interface RTCIceParameters { } interface RTCIceServer { - credential?: string | RTCOAuthCredential; + credential?: string; credentialType?: RTCIceCredentialType; urls: string | string[]; username?: string; @@ -1332,6 +1335,11 @@ interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { packetsReceived?: number; } +interface RTCLocalSessionDescriptionInit { + sdp?: string; + type?: RTCSdpType; +} + interface RTCMediaStreamTrackStats extends RTCStats { audioLevel?: number; echoReturnLoss?: number; @@ -1349,13 +1357,7 @@ interface RTCMediaStreamTrackStats extends RTCStats { trackIdentifier?: string; } -interface RTCOAuthCredential { - accessToken: string; - macKey: string; -} - interface RTCOfferAnswerOptions { - voiceActivityDetection?: boolean; } interface RTCOfferOptions extends RTCOfferAnswerOptions { @@ -1372,8 +1374,9 @@ interface RTCOutboundRTPStreamStats extends RTCRTPStreamStats { } interface RTCPeerConnectionIceErrorEventInit extends EventInit { + address?: string | null; errorCode: number; - hostCandidate?: string; + port?: number | null; statusText?: string; url?: string; } @@ -1438,16 +1441,9 @@ interface RTCRtpContributingSource { timestamp: number; } -interface RTCRtpDecodingParameters extends RTCRtpCodingParameters { -} - interface RTCRtpEncodingParameters extends RTCRtpCodingParameters { active?: boolean; - codecPayloadType?: number; - dtx?: RTCDtxStatus; maxBitrate?: number; - maxFramerate?: number; - ptime?: number; scaleResolutionDownBy?: number; } @@ -1480,7 +1476,6 @@ interface RTCRtpParameters { } interface RTCRtpReceiveParameters extends RTCRtpParameters { - encodings: RTCRtpDecodingParameters[]; } interface RTCRtpRtxParameters { @@ -1488,9 +1483,7 @@ interface RTCRtpRtxParameters { } interface RTCRtpSendParameters extends RTCRtpParameters { - degradationPreference?: RTCDegradationPreference; encodings: RTCRtpEncodingParameters[]; - priority?: RTCPriorityType; transactionId: string; } @@ -1512,7 +1505,7 @@ interface RTCRtpUnhandled { interface RTCSessionDescriptionInit { sdp?: string; - type?: RTCSdpType; + type: RTCSdpType; } interface RTCSrtpKeyParam { @@ -1541,10 +1534,6 @@ interface RTCStats { type?: RTCStatsType; } -interface RTCStatsEventInit extends EventInit { - report: RTCStatsReport; -} - interface RTCStatsReport { } @@ -1587,7 +1576,7 @@ interface ReadableWritablePair { readable: ReadableStream; /** * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. - * + * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. */ writable: WritableStream; @@ -1707,24 +1696,6 @@ interface SVGBoundingBoxOptions { stroke?: boolean; } -interface ScopedCredentialDescriptor { - id: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; - transports?: Transport[]; - type: ScopedCredentialType; -} - -interface ScopedCredentialOptions { - excludeList?: ScopedCredentialDescriptor[]; - extensions?: WebAuthnExtensions; - rpId?: string; - timeoutSeconds?: number; -} - -interface ScopedCredentialParameters { - algorithm: string | Algorithm; - type: ScopedCredentialType; -} - interface ScrollIntoViewOptions extends ScrollOptions { block?: ScrollLogicalPosition; inline?: ScrollLogicalPosition; @@ -1752,14 +1723,6 @@ interface SecurityPolicyViolationEventInit extends EventInit { violatedDirective?: string; } -interface ServiceWorkerMessageEventInit extends EventInit { - data?: any; - lastEventId?: string; - origin?: string; - ports?: MessagePort[] | null; - source?: ServiceWorker | MessagePort | null; -} - interface ShadowRootInit { delegatesFocus?: boolean; mode: ShadowRootMode; @@ -1832,19 +1795,19 @@ interface StreamPipeOptions { preventCancel?: boolean; /** * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * + * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - * + * * Errors and closures of the source and destination streams propagate as follows: - * + * * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. - * + * * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. - * + * * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - * + * * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. - * + * * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. */ preventClose?: boolean; @@ -1954,9 +1917,6 @@ interface WaveShaperOptions extends AudioNodeOptions { oversample?: OverSampleType; } -interface WebAuthnExtensions { -} - interface WebGLContextAttributes { alpha?: boolean; antialias?: boolean; @@ -3404,7 +3364,7 @@ interface CanvasFilters { interface CanvasGradient { /** * Adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset at one end of the gradient, 1.0 is the offset at the other end. - * + * * Throws an "IndexSizeError" DOMException if the offset is out of range. Throws a "SyntaxError" DOMException if the color cannot be parsed. */ addColorStop(offset: number, color: string): void; @@ -3571,13 +3531,13 @@ declare var CharacterData: { interface ChildNode extends Node { /** * Inserts nodes just after node, while replacing strings in nodes with equivalent Text nodes. - * + * * Throws a "HierarchyRequestError" DOMException if the constraints of the node tree are violated. */ after(...nodes: (Node | string)[]): void; /** * Inserts nodes just before node, while replacing strings in nodes with equivalent Text nodes. - * + * * Throws a "HierarchyRequestError" DOMException if the constraints of the node tree are violated. */ before(...nodes: (Node | string)[]): void; @@ -3587,7 +3547,7 @@ interface ChildNode extends Node { remove(): void; /** * Replaces node with nodes, while replacing strings in nodes with equivalent Text nodes. - * + * * Throws a "HierarchyRequestError" DOMException if the constraints of the node tree are violated. */ replaceWith(...nodes: (Node | string)[]): void; @@ -3891,10 +3851,6 @@ declare var DOMImplementation: { new(): DOMImplementation; }; -interface DOML2DeprecatedColorProperty { - color: string; -} - interface DOMMatrix extends DOMMatrixReadOnly { a: number; b: number; @@ -4005,11 +3961,11 @@ declare var DOMMatrixReadOnly: { interface DOMParser { /** * Parses string using either the HTML or XML parser, according to type, and returns the resulting Document. type can be "text/html" (which will invoke the HTML parser), or any of "text/xml", "application/xml", "application/xhtml+xml", or "image/svg+xml" (which will invoke the XML parser). - * + * * For the XML parser, if string cannot be parsed, then the returned Document will contain elements describing the resulting error. - * + * * Note that script elements are not evaluated during parsing, and the resulting document's encoding will always be UTF-8. - * + * * Values other than the above for type will cause a TypeError exception to be thrown. */ parseFromString(string: string, type: DOMParserSupportedType): Document; @@ -4161,16 +4117,16 @@ interface DOMTokenList { readonly length: number; /** * Returns the associated set as string. - * + * * Can be set, to change the associated attribute. */ value: string; toString(): string; /** * Adds all arguments passed, except those already present. - * + * * Throws a "SyntaxError" DOMException if one of the arguments is the empty string. - * + * * Throws an "InvalidCharacterError" DOMException if one of the arguments contains any ASCII whitespace. */ add(...tokens: string[]): void; @@ -4184,35 +4140,35 @@ interface DOMTokenList { item(index: number): string | null; /** * Removes arguments passed, if they are present. - * + * * Throws a "SyntaxError" DOMException if one of the arguments is the empty string. - * + * * Throws an "InvalidCharacterError" DOMException if one of the arguments contains any ASCII whitespace. */ remove(...tokens: string[]): void; /** * Replaces token with newToken. - * + * * Returns true if token was replaced with newToken, and false otherwise. - * + * * Throws a "SyntaxError" DOMException if one of the arguments is the empty string. - * + * * Throws an "InvalidCharacterError" DOMException if one of the arguments contains any ASCII whitespace. */ replace(oldToken: string, newToken: string): void; /** * Returns true if token is in the associated attribute's supported tokens. Returns false otherwise. - * + * * Throws a TypeError if the associated attribute has no supported tokens defined. */ supports(token: string): boolean; /** * If force is not given, "toggles" token, removing it if it's present and adding it if it's not present. If force is true, adds token (same as add()). If force is false, removes token (same as remove()). - * + * * Returns true if token is now present, and false otherwise. - * + * * Throws a "SyntaxError" DOMException if token is empty. - * + * * Throws an "InvalidCharacterError" DOMException if token contains any spaces. */ toggle(token: string, force?: boolean): boolean; @@ -4242,17 +4198,17 @@ declare var DataCue: { interface DataTransfer { /** * Returns the kind of operation that is currently selected. If the kind of operation isn't one of those that is allowed by the effectAllowed attribute, then the operation will fail. - * + * * Can be set, to change the selected operation. - * + * * The possible values are "none", "copy", "link", and "move". */ dropEffect: "none" | "copy" | "link" | "move"; /** * Returns the kinds of operations that are to be allowed. - * + * * Can be set (during the dragstart event), to change the allowed operations. - * + * * The possible values are "none", "copy", "copyLink", "copyMove", "link", "linkMove", "move", "all", and "uninitialized", */ effectAllowed: "none" | "copy" | "copyLink" | "copyMove" | "link" | "linkMove" | "move" | "all" | "uninitialized"; @@ -4380,16 +4336,6 @@ declare var DeviceAcceleration: { new(): DeviceAcceleration; }; -/** The DeviceLightEvent provides web developers with information from photo sensors or similiar detectors about ambient light levels near the device. For example this may be useful to adjust the screen's brightness based on the current ambient light level in order to save energy or provide better readability. */ -interface DeviceLightEvent extends Event { - readonly value: number; -} - -declare var DeviceLightEvent: { - prototype: DeviceLightEvent; - new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -}; - /** The DeviceMotionEvent provides web developers with information about the speed of changes for the device's position and orientation. */ interface DeviceMotionEvent extends Event { readonly acceleration: DeviceMotionEventAcceleration | null; @@ -4523,15 +4469,15 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad readonly contentType: string; /** * Returns the HTTP cookies that apply to the Document. If there are no cookies or cookies can't be applied to this resource, the empty string will be returned. - * + * * Can be set, to add a new cookie to the element's set of HTTP cookies. - * + * * If the contents are sandboxed into a unique origin (e.g. in an iframe with the sandbox attribute), a "SecurityError" DOMException will be thrown on getting and setting. */ cookie: string; /** * Returns the script element, or the SVG script element, that is currently executing, as long as the element represents a classic script. In the case of reentrant script execution, returns the one that most recently started executing amongst those that have not yet finished executing. - * + * * Returns null if the Document is not currently executing a script or SVG script element (e.g., because the running script is an event handler, or a timeout), or if the currently executing script or SVG script element represents a module script. */ readonly currentScript: HTMLOrSVGScriptElement | null; @@ -4654,7 +4600,7 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad vlinkColor: string; /** * Moves node from another document and returns it. - * + * * If node is a document, throws a "NotSupportedError" DOMException or, if node is a shadow root, throws a "HierarchyRequestError" DOMException. */ adoptNode(source: T): T; @@ -4698,17 +4644,17 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad createElement(tagName: string, options?: ElementCreationOptions): HTMLElement; /** * Returns an element with namespace namespace. Its namespace prefix will be everything before ":" (U+003E) in qualifiedName or null. Its local name will be everything after ":" (U+003E) in qualifiedName or qualifiedName. - * + * * If localName does not match the Name production an "InvalidCharacterError" DOMException will be thrown. - * + * * If one of the following conditions is true a "NamespaceError" DOMException will be thrown: - * + * * localName does not match the QName production. * Namespace prefix is not null and namespace is the empty string. * Namespace prefix is "xml" and namespace is not the XML namespace. * qualifiedName or namespace prefix is "xmlns" and namespace is not the XMLNS namespace. * namespace is the XMLNS namespace and neither qualifiedName nor namespace prefix is "xmlns". - * + * * When supplied, options's is can be used to create a customized built-in element. */ createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement; @@ -4724,7 +4670,6 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad createEvent(eventInterface: "CloseEvent"): CloseEvent; createEvent(eventInterface: "CompositionEvent"): CompositionEvent; createEvent(eventInterface: "CustomEvent"): CustomEvent; - createEvent(eventInterface: "DeviceLightEvent"): DeviceLightEvent; createEvent(eventInterface: "DeviceMotionEvent"): DeviceMotionEvent; createEvent(eventInterface: "DeviceOrientationEvent"): DeviceOrientationEvent; createEvent(eventInterface: "DragEvent"): DragEvent; @@ -4739,10 +4684,6 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad createEvent(eventInterface: "InputEvent"): InputEvent; createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; createEvent(eventInterface: "ListeningStateChangedEvent"): ListeningStateChangedEvent; - createEvent(eventInterface: "MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; - createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; - createEvent(eventInterface: "MSPointerEvent"): MSPointerEvent; createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; createEvent(eventInterface: "MediaQueryListEvent"): MediaQueryListEvent; @@ -4757,6 +4698,7 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad createEvent(eventInterface: "OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; createEvent(eventInterface: "OverflowEvent"): OverflowEvent; createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface: "PaymentMethodChangeEvent"): PaymentMethodChangeEvent; createEvent(eventInterface: "PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; createEvent(eventInterface: "PermissionRequestedEvent"): PermissionRequestedEvent; createEvent(eventInterface: "PointerEvent"): PointerEvent; @@ -4773,12 +4715,10 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad createEvent(eventInterface: "RTCPeerConnectionIceErrorEvent"): RTCPeerConnectionIceErrorEvent; createEvent(eventInterface: "RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; createEvent(eventInterface: "RTCSsrcConflictEvent"): RTCSsrcConflictEvent; - createEvent(eventInterface: "RTCStatsEvent"): RTCStatsEvent; createEvent(eventInterface: "RTCTrackEvent"): RTCTrackEvent; createEvent(eventInterface: "SVGZoomEvent"): SVGZoomEvent; createEvent(eventInterface: "SVGZoomEvents"): SVGZoomEvent; createEvent(eventInterface: "SecurityPolicyViolationEvent"): SecurityPolicyViolationEvent; - createEvent(eventInterface: "ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; createEvent(eventInterface: "SpeechRecognitionErrorEvent"): SpeechRecognitionErrorEvent; createEvent(eventInterface: "SpeechRecognitionEvent"): SpeechRecognitionEvent; createEvent(eventInterface: "SpeechSynthesisErrorEvent"): SpeechSynthesisErrorEvent; @@ -4869,11 +4809,11 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad getElementsByTagName(qualifiedName: string): HTMLCollectionOf; /** * If namespace and localName are "*" returns a HTMLCollection of all descendant elements. - * + * * If only namespace is "*" returns a HTMLCollection of all descendant elements whose local name is localName. - * + * * If only localName is "*" returns a HTMLCollection of all descendant elements whose namespace is namespace. - * + * * Otherwise, returns a HTMLCollection of all descendant elements whose namespace is namespace and local name is localName. */ getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; @@ -4889,7 +4829,7 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad hasFocus(): boolean; /** * Returns a copy of node. If deep is true, the copy also includes the node's descendants. - * + * * If node is a document or a shadow root, throws a "NotSupportedError" DOMException. */ importNode(importedNode: T, deep: boolean): T; @@ -4974,7 +4914,6 @@ interface DocumentEvent { createEvent(eventInterface: "CloseEvent"): CloseEvent; createEvent(eventInterface: "CompositionEvent"): CompositionEvent; createEvent(eventInterface: "CustomEvent"): CustomEvent; - createEvent(eventInterface: "DeviceLightEvent"): DeviceLightEvent; createEvent(eventInterface: "DeviceMotionEvent"): DeviceMotionEvent; createEvent(eventInterface: "DeviceOrientationEvent"): DeviceOrientationEvent; createEvent(eventInterface: "DragEvent"): DragEvent; @@ -4989,10 +4928,6 @@ interface DocumentEvent { createEvent(eventInterface: "InputEvent"): InputEvent; createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; createEvent(eventInterface: "ListeningStateChangedEvent"): ListeningStateChangedEvent; - createEvent(eventInterface: "MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; - createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; - createEvent(eventInterface: "MSPointerEvent"): MSPointerEvent; createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; createEvent(eventInterface: "MediaQueryListEvent"): MediaQueryListEvent; @@ -5007,6 +4942,7 @@ interface DocumentEvent { createEvent(eventInterface: "OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; createEvent(eventInterface: "OverflowEvent"): OverflowEvent; createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface: "PaymentMethodChangeEvent"): PaymentMethodChangeEvent; createEvent(eventInterface: "PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; createEvent(eventInterface: "PermissionRequestedEvent"): PermissionRequestedEvent; createEvent(eventInterface: "PointerEvent"): PointerEvent; @@ -5023,12 +4959,10 @@ interface DocumentEvent { createEvent(eventInterface: "RTCPeerConnectionIceErrorEvent"): RTCPeerConnectionIceErrorEvent; createEvent(eventInterface: "RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; createEvent(eventInterface: "RTCSsrcConflictEvent"): RTCSsrcConflictEvent; - createEvent(eventInterface: "RTCStatsEvent"): RTCStatsEvent; createEvent(eventInterface: "RTCTrackEvent"): RTCTrackEvent; createEvent(eventInterface: "SVGZoomEvent"): SVGZoomEvent; createEvent(eventInterface: "SVGZoomEvents"): SVGZoomEvent; createEvent(eventInterface: "SecurityPolicyViolationEvent"): SecurityPolicyViolationEvent; - createEvent(eventInterface: "ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; createEvent(eventInterface: "SpeechRecognitionErrorEvent"): SpeechRecognitionErrorEvent; createEvent(eventInterface: "SpeechRecognitionEvent"): SpeechRecognitionEvent; createEvent(eventInterface: "SpeechSynthesisErrorEvent"): SpeechSynthesisErrorEvent; @@ -5276,7 +5210,7 @@ interface Element extends Node, Animatable, ChildNode, InnerHTML, NonDocumentTyp removeAttributeNode(attr: Attr): Attr; /** * Displays element fullscreen and resolves promise when done. - * + * * When supplied, options's navigationUI member indicates whether showing navigation UI while in fullscreen is preferred or not. If set to "show", navigation simplicity is preferred over screen space, and if set to "hide", more screen space is preferred. User agents are always free to honor user preference over the application's. The default value "auto" indicates no application preference. */ requestFullscreen(options?: FullscreenOptions): Promise; @@ -5301,7 +5235,7 @@ interface Element extends Node, Animatable, ChildNode, InnerHTML, NonDocumentTyp setPointerCapture(pointerId: number): void; /** * If force is not given, "toggles" qualifiedName, removing it if it is present and adding it if it is not present. If force is true, adds qualifiedName. If force is false, removes qualifiedName. - * + * * Returns true if qualifiedName is now present, and false otherwise. */ toggleAttribute(qualifiedName: string, force?: boolean): boolean; @@ -5471,15 +5405,15 @@ declare var EventSource: { interface EventTarget { /** * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. - * + * * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. - * + * * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. - * + * * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. - * + * * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. - * + * * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. */ addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; @@ -6146,9 +6080,9 @@ interface HTMLAllCollection { item(nameOrIndex?: string): HTMLCollection | Element | null; /** * Returns the item with ID or name name from the collection. - * + * * If there are multiple matching items, then an HTMLCollection object containing all those elements is returned. - * + * * Only button, form, iframe, input, map, meta, object, select, and textarea elements can have a name for the purpose of this method; their name is given by the value of their name attribute. */ namedItem(name: string): HTMLCollection | Element | null; @@ -6360,29 +6294,6 @@ declare var HTMLBaseElement: { new(): HTMLBaseElement; }; -/** Provides special properties (beyond the regular HTMLElement interface it also has available to it by inheritance) for manipulating elements. */ -interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { - /** - * Sets or retrieves the current typeface family. - */ - /** @deprecated */ - face: string; - /** - * Sets or retrieves the font size of the object. - */ - /** @deprecated */ - size: number; - addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; - removeEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; - removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; -} - -declare var HTMLBaseFontElement: { - prototype: HTMLBaseFontElement; - new(): HTMLBaseFontElement; -}; - interface HTMLBodyElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { "orientationchange": Event; } @@ -6809,7 +6720,7 @@ declare var HTMLFontElement: { interface HTMLFormControlsCollection extends HTMLCollectionBase { /** * Returns the item with ID or name name from the collection. - * + * * If there are multiple matching items, then a RadioNodeList object containing all those elements is returned. */ namedItem(name: string): RadioNodeList | Element | null; @@ -8058,25 +7969,25 @@ declare var HTMLOptionElement: { interface HTMLOptionsCollection extends HTMLCollectionOf { /** * Returns the number of elements in the collection. - * + * * When set to a smaller number, truncates the number of option elements in the corresponding container. - * + * * When set to a greater number, adds new blank option elements to that container. */ length: number; /** * Returns the index of the first selected item, if any, or −1 if there is no selected item. - * + * * Can be set, to change the selection. */ selectedIndex: number; /** * Inserts element before the node given by before. - * + * * The before argument can be a number, in which case element is inserted before the item with that number, or an element from the collection, in which case element is inserted before that element. - * + * * If before is omitted, null, or a number out of range, then element will be added at the end of the list. - * + * * This method will throw a "HierarchyRequestError" DOMException if element is an ancestor of the element into which it is to be inserted. */ add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; @@ -9155,15 +9066,15 @@ interface IDBCursor { continuePrimaryKey(key: IDBValidKey, primaryKey: IDBValidKey): void; /** * Delete the record pointed at by the cursor with a new value. - * + * * If successful, request's result will be undefined. */ delete(): IDBRequest; /** * Updated the record pointed at by the cursor with a new value. - * + * * Throws a "DataError" DOMException if the effective object store uses in-line keys and the key would have changed. - * + * * If successful, request's result will be the record's key. */ update(value: any): IDBRequest; @@ -9218,13 +9129,13 @@ interface IDBDatabase extends EventTarget { close(): void; /** * Creates a new object store with the given name and options and returns a new IDBObjectStore. - * + * * Throws a "InvalidStateError" DOMException if not called within an upgrade transaction. */ createObjectStore(name: string, options?: IDBObjectStoreParameters): IDBObjectStore; /** * Deletes the object store with the given name. - * + * * Throws a "InvalidStateError" DOMException if not called within an upgrade transaction. */ deleteObjectStore(name: string): void; @@ -9247,7 +9158,7 @@ declare var IDBDatabase: { interface IDBFactory { /** * Compares two values as keys. Returns -1 if key1 precedes key2, 1 if key2 precedes key1, and 0 if the keys are equal. - * + * * Throws a "DataError" DOMException if either input is not a valid key. */ cmp(first: any, second: any): number; @@ -9281,43 +9192,43 @@ interface IDBIndex { readonly unique: boolean; /** * Retrieves the number of records matching the given key or key range in query. - * + * * If successful, request's result will be the count. */ count(key?: IDBValidKey | IDBKeyRange): IDBRequest; /** * Retrieves the value of the first record matching the given key or key range in query. - * + * * If successful, request's result will be the value, or undefined if there was no matching record. */ get(key: IDBValidKey | IDBKeyRange): IDBRequest; /** * Retrieves the values of the records matching the given key or key range in query (up to count if given). - * + * * If successful, request's result will be an Array of the values. */ getAll(query?: IDBValidKey | IDBKeyRange | null, count?: number): IDBRequest; /** * Retrieves the keys of records matching the given key or key range in query (up to count if given). - * + * * If successful, request's result will be an Array of the keys. */ getAllKeys(query?: IDBValidKey | IDBKeyRange | null, count?: number): IDBRequest; /** * Retrieves the key of the first record matching the given key or key range in query. - * + * * If successful, request's result will be the key, or undefined if there was no matching record. */ getKey(key: IDBValidKey | IDBKeyRange): IDBRequest; /** * Opens a cursor over the records matching query, ordered by direction. If query is null, all records in index are matched. - * + * * If successful, request's result will be an IDBCursorWithValue, or null if there were no matching records. */ openCursor(query?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; /** * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in index are matched. - * + * * If successful, request's result will be an IDBCursor, or null if there were no matching records. */ openKeyCursor(query?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; @@ -9397,88 +9308,88 @@ interface IDBObjectStore { readonly transaction: IDBTransaction; /** * Adds or updates a record in store with the given value and key. - * + * * If the store uses in-line keys and key is specified a "DataError" DOMException will be thrown. - * + * * If put() is used, any existing record with the key will be replaced. If add() is used, and if a record with the key already exists the request will fail, with request's error set to a "ConstraintError" DOMException. - * + * * If successful, request's result will be the record's key. */ add(value: any, key?: IDBValidKey): IDBRequest; /** * Deletes all records in store. - * + * * If successful, request's result will be undefined. */ clear(): IDBRequest; /** * Retrieves the number of records matching the given key or key range in query. - * + * * If successful, request's result will be the count. */ count(key?: IDBValidKey | IDBKeyRange): IDBRequest; /** * Creates a new index in store with the given name, keyPath and options and returns a new IDBIndex. If the keyPath and options define constraints that cannot be satisfied with the data already in store the upgrade transaction will abort with a "ConstraintError" DOMException. - * + * * Throws an "InvalidStateError" DOMException if not called within an upgrade transaction. */ createIndex(name: string, keyPath: string | string[], options?: IDBIndexParameters): IDBIndex; /** * Deletes records in store with the given key or in the given key range in query. - * + * * If successful, request's result will be undefined. */ delete(key: IDBValidKey | IDBKeyRange): IDBRequest; /** * Deletes the index in store with the given name. - * + * * Throws an "InvalidStateError" DOMException if not called within an upgrade transaction. */ deleteIndex(name: string): void; /** * Retrieves the value of the first record matching the given key or key range in query. - * + * * If successful, request's result will be the value, or undefined if there was no matching record. */ get(query: IDBValidKey | IDBKeyRange): IDBRequest; /** * Retrieves the values of the records matching the given key or key range in query (up to count if given). - * + * * If successful, request's result will be an Array of the values. */ getAll(query?: IDBValidKey | IDBKeyRange | null, count?: number): IDBRequest; /** * Retrieves the keys of records matching the given key or key range in query (up to count if given). - * + * * If successful, request's result will be an Array of the keys. */ getAllKeys(query?: IDBValidKey | IDBKeyRange | null, count?: number): IDBRequest; /** * Retrieves the key of the first record matching the given key or key range in query. - * + * * If successful, request's result will be the key, or undefined if there was no matching record. */ getKey(query: IDBValidKey | IDBKeyRange): IDBRequest; index(name: string): IDBIndex; /** * Opens a cursor over the records matching query, ordered by direction. If query is null, all records in store are matched. - * + * * If successful, request's result will be an IDBCursorWithValue pointing at the first matching record, or null if there were no matching records. */ openCursor(query?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; /** * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in store are matched. - * + * * If successful, request's result will be an IDBCursor pointing at the first matching record, or null if there were no matching records. */ openKeyCursor(query?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; /** * Adds or updates a record in store with the given value and key. - * + * * If the store uses in-line keys and key is specified a "DataError" DOMException will be thrown. - * + * * If put() is used, any existing record with the key will be replaced. If add() is used, and if a record with the key already exists the request will fail, with request's error set to a "ConstraintError" DOMException. - * + * * If successful, request's result will be the record's key. */ put(value: any, key?: IDBValidKey): IDBRequest; @@ -9798,25 +9709,25 @@ interface Location { readonly ancestorOrigins: DOMStringList; /** * Returns the Location object's URL's fragment (includes leading "#" if non-empty). - * + * * Can be set, to navigate to the same URL with a changed fragment (ignores leading "#"). */ hash: string; /** * Returns the Location object's URL's host and port (if different from the default port for the scheme). - * + * * Can be set, to navigate to the same URL with a changed host and port. */ host: string; /** * Returns the Location object's URL's host. - * + * * Can be set, to navigate to the same URL with a changed host. */ hostname: string; /** * Returns the Location object's URL. - * + * * Can be set, to navigate to the given URL. */ href: string; @@ -9827,25 +9738,25 @@ interface Location { readonly origin: string; /** * Returns the Location object's URL's path. - * + * * Can be set, to navigate to the same URL with a changed path. */ pathname: string; /** * Returns the Location object's URL's port. - * + * * Can be set, to navigate to the same URL with a changed port. */ port: string; /** * Returns the Location object's URL's scheme. - * + * * Can be set, to navigate to the same URL with a changed scheme. */ protocol: string; /** * Returns the Location object's URL's query (includes leading "?" if non-empty). - * + * * Can be set, to navigate to the same URL with a changed query (ignores leading "?"). */ search: string; @@ -9938,43 +9849,6 @@ declare var MSGesture: { new(): MSGesture; }; -/** The MSGestureEvent is a proprietary interface specific to Internet Explorer and Microsoft Edge which represents events that occur due to touch gestures. Events using this interface include MSGestureStart, MSGestureEnd, MSGestureTap, MSGestureHold, MSGestureChange, and MSInertiaStart. */ -interface MSGestureEvent extends UIEvent { - readonly clientX: number; - readonly clientY: number; - readonly expansion: number; - readonly gestureObject: any; - readonly hwTimestamp: number; - readonly offsetX: number; - readonly offsetY: number; - readonly rotation: number; - readonly scale: number; - readonly screenX: number; - readonly screenY: number; - readonly translationX: number; - readonly translationY: number; - readonly velocityAngular: number; - readonly velocityExpansion: number; - readonly velocityX: number; - readonly velocityY: number; - initGestureEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void; - readonly MSGESTURE_FLAG_BEGIN: number; - readonly MSGESTURE_FLAG_CANCEL: number; - readonly MSGESTURE_FLAG_END: number; - readonly MSGESTURE_FLAG_INERTIA: number; - readonly MSGESTURE_FLAG_NONE: number; -} - -declare var MSGestureEvent: { - prototype: MSGestureEvent; - new(): MSGestureEvent; - readonly MSGESTURE_FLAG_BEGIN: number; - readonly MSGESTURE_FLAG_CANCEL: number; - readonly MSGESTURE_FLAG_END: number; - readonly MSGESTURE_FLAG_INERTIA: number; - readonly MSGESTURE_FLAG_NONE: number; -}; - /** The msGraphicsTrust() constructor returns an object that provides properties for info on protected video playback. */ interface MSGraphicsTrust { readonly constrictionActive: boolean; @@ -10036,25 +9910,6 @@ declare var MSMediaKeyError: { readonly MS_MEDIA_KEYERR_UNKNOWN: number; }; -interface MSMediaKeyMessageEvent extends Event { - readonly destinationURL: string | null; - readonly message: Uint8Array; -} - -declare var MSMediaKeyMessageEvent: { - prototype: MSMediaKeyMessageEvent; - new(): MSMediaKeyMessageEvent; -}; - -interface MSMediaKeyNeededEvent extends Event { - readonly initData: Uint8Array | null; -} - -declare var MSMediaKeyNeededEvent: { - prototype: MSMediaKeyNeededEvent; - new(): MSMediaKeyNeededEvent; -}; - interface MSMediaKeySession extends EventTarget { readonly error: MSMediaKeyError | null; readonly keySystem: string; @@ -10089,29 +9944,6 @@ interface MSNavigatorDoNotTrack { storeWebWideTrackingException(args: StoreExceptionsInformation): void; } -interface MSPointerEvent extends MouseEvent { - readonly currentPoint: any; - readonly height: number; - readonly hwTimestamp: number; - readonly intermediatePoints: any; - readonly isPrimary: boolean; - readonly pointerId: number; - readonly pointerType: any; - readonly pressure: number; - readonly rotation: number; - readonly tiltX: number; - readonly tiltY: number; - readonly width: number; - getCurrentPoint(element: Element): void; - getIntermediatePoints(element: Element): void; - initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; -} - -declare var MSPointerEvent: { - prototype: MSPointerEvent; - new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -}; - interface MSStream { readonly type: string; msClose(): void; @@ -10436,7 +10268,6 @@ declare var MediaStreamEvent: { interface MediaStreamTrackEventMap { "ended": Event; - "isolationchange": Event; "mute": Event; "unmute": Event; } @@ -10445,12 +10276,10 @@ interface MediaStreamTrackEventMap { interface MediaStreamTrack extends EventTarget { enabled: boolean; readonly id: string; - readonly isolated: boolean; readonly kind: string; readonly label: string; readonly muted: boolean; onended: ((this: MediaStreamTrack, ev: Event) => any) | null; - onisolationchange: ((this: MediaStreamTrack, ev: Event) => any) | null; onmute: ((this: MediaStreamTrack, ev: Event) => any) | null; onunmute: ((this: MediaStreamTrack, ev: Event) => any) | null; readonly readyState: MediaStreamTrackState; @@ -10550,7 +10379,7 @@ interface MessagePort extends EventTarget { close(): void; /** * Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side. - * + * * Throws a "DataCloneError" DOMException if transfer contains duplicate objects or port, or if message could not be cloned. */ postMessage(message: any, transfer: Transferable[]): void; @@ -10668,7 +10497,7 @@ interface MutationObserver { disconnect(): void; /** * Instructs the user agent to observe a given target (a node) and report any mutations based on the criteria given by options (an object). - * + * * The options argument allows for setting mutation observation options via object members. */ observe(target: Node, options?: MutationObserverInit): void; @@ -11258,27 +11087,27 @@ declare var OfflineAudioContext: { interface OffscreenCanvas extends EventTarget { /** * These attributes return the dimensions of the OffscreenCanvas object's bitmap. - * + * * They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it). */ height: number; /** * These attributes return the dimensions of the OffscreenCanvas object's bitmap. - * + * * They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it). */ width: number; /** * Returns a promise that will fulfill with a new Blob object representing a file containing the image in the OffscreenCanvas object. - * + * * The argument, if provided, is a dictionary that controls the encoding options of the image file to be created. The type field specifies the file format and has a default value of "image/png"; that type is also used if the requested type isn't supported. If the image format supports variable quality (such as "image/jpeg"), then the quality field is a number in the range 0.0 to 1.0 inclusive indicating the desired quality level for the resulting image. */ convertToBlob(options?: ImageEncodeOptions): Promise; /** * Returns an object that exposes an API for drawing on the OffscreenCanvas object. contextId specifies the desired API: "2d", "bitmaprenderer", "webgl", or "webgl2". options is handled by that API. - * + * * This specification defines the "2d" context below, which is similar but distinct from the "2d" context that is created from a canvas element. The WebGL specifications define the "webgl" and "webgl2" contexts. [WEBGL] - * + * * Returns null if the canvas has already been initialized with another context type (e.g., trying to get a "2d" context after getting a "webgl" context). */ getContext(contextId: "2d", options?: CanvasRenderingContext2DSettings): OffscreenCanvasRenderingContext2D | null; @@ -11354,11 +11183,11 @@ declare var OverflowEvent: { interface PageTransitionEvent extends Event { /** * For the pageshow event, returns false if the page is newly being loaded (and the load event will fire). Otherwise, returns true. - * + * * For the pagehide event, returns false if the page is going away for the last time. Otherwise, returns true, meaning that (if nothing conspires to make the page unsalvageable) the page might be reused if the user navigates back to this page. - * + * * Things that can cause the page to be unsalvageable include: - * + * * Listening for beforeunload events * Listening for unload events * Having iframes that are not salvageable @@ -11416,13 +11245,13 @@ interface ParentNode { readonly lastElementChild: Element | null; /** * Inserts nodes after the last child of node, while replacing strings in nodes with equivalent Text nodes. - * + * * Throws a "HierarchyRequestError" DOMException if the constraints of the node tree are violated. */ append(...nodes: (Node | string)[]): void; /** * Inserts nodes before the first child of node, while replacing strings in nodes with equivalent Text nodes. - * + * * Throws a "HierarchyRequestError" DOMException if the constraints of the node tree are violated. */ prepend(...nodes: (Node | string)[]): void; @@ -11455,11 +11284,10 @@ declare var Path2D: { /** This Payment Request API interface is used to store shipping or payment address information. */ interface PaymentAddress { - readonly addressLine: string[]; + readonly addressLine: ReadonlyArray; readonly city: string; readonly country: string; readonly dependentLocality: string; - readonly languageCode: string; readonly organization: string; readonly phone: string; readonly postalCode: string; @@ -11474,7 +11302,18 @@ declare var PaymentAddress: { new(): PaymentAddress; }; +interface PaymentMethodChangeEvent extends PaymentRequestUpdateEvent { + readonly methodDetails: any; + readonly methodName: string; +} + +declare var PaymentMethodChangeEvent: { + prototype: PaymentMethodChangeEvent; + new(type: string, eventInitDict?: PaymentMethodChangeEventInit): PaymentMethodChangeEvent; +}; + interface PaymentRequestEventMap { + "paymentmethodchange": Event; "shippingaddresschange": Event; "shippingoptionchange": Event; } @@ -11482,6 +11321,7 @@ interface PaymentRequestEventMap { /** This Payment Request API interface is the primary access point into the API, and lets web content and apps accept payments from the end user. */ interface PaymentRequest extends EventTarget { readonly id: string; + onpaymentmethodchange: ((this: PaymentRequest, ev: Event) => any) | null; onshippingaddresschange: ((this: PaymentRequest, ev: Event) => any) | null; onshippingoptionchange: ((this: PaymentRequest, ev: Event) => any) | null; readonly shippingAddress: PaymentAddress | null; @@ -11489,7 +11329,7 @@ interface PaymentRequest extends EventTarget { readonly shippingType: PaymentShippingType | null; abort(): Promise; canMakePayment(): Promise; - show(): Promise; + show(detailsPromise: PaymentDetailsUpdate | Promise): Promise; addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -11511,10 +11351,15 @@ declare var PaymentRequestUpdateEvent: { new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; }; +interface PaymentResponseEventMap { + "payerdetailchange": Event; +} + /** This Payment Request API interface is returned after a user selects a payment method and approves a payment request. */ -interface PaymentResponse { +interface PaymentResponse extends EventTarget { readonly details: any; readonly methodName: string; + onpayerdetailchange: ((this: PaymentResponse, ev: Event) => any) | null; readonly payerEmail: string | null; readonly payerName: string | null; readonly payerPhone: string | null; @@ -11522,7 +11367,12 @@ interface PaymentResponse { readonly shippingAddress: PaymentAddress | null; readonly shippingOption: string | null; complete(result?: PaymentComplete): Promise; + retry(errorFields?: PaymentValidationErrors): Promise; toJSON(): any; + addEventListener(type: K, listener: (this: PaymentResponse, ev: PaymentResponseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: PaymentResponse, ev: PaymentResponseEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var PaymentResponse: { @@ -11976,7 +11826,6 @@ interface RTCCertificate { declare var RTCCertificate: { prototype: RTCCertificate; new(): RTCCertificate; - getSupportedAlgorithms(): AlgorithmIdentifier[]; }; interface RTCDTMFSenderEventMap { @@ -12006,7 +11855,7 @@ interface RTCDTMFToneChangeEvent extends Event { declare var RTCDTMFToneChangeEvent: { prototype: RTCDTMFToneChangeEvent; - new(type: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; + new(type: string, eventInitDict?: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; }; interface RTCDataChannelEventMap { @@ -12018,7 +11867,7 @@ interface RTCDataChannelEventMap { } interface RTCDataChannel extends EventTarget { - binaryType: string; + binaryType: BinaryType; readonly bufferedAmount: number; bufferedAmountLowThreshold: number; readonly id: number | null; @@ -12032,7 +11881,6 @@ interface RTCDataChannel extends EventTarget { onmessage: ((this: RTCDataChannel, ev: MessageEvent) => any) | null; onopen: ((this: RTCDataChannel, ev: Event) => any) | null; readonly ordered: boolean; - readonly priority: RTCPriorityType; readonly protocol: string; readonly readyState: RTCDataChannelState; close(): void; @@ -12116,7 +11964,6 @@ declare var RTCDtmfSender: { interface RTCError extends DOMException { readonly errorDetail: RTCErrorDetailType; - readonly httpRequestStatusCode: number | null; readonly receivedAlert: number | null; readonly sctpCauseCode: number | null; readonly sdpLineNumber: number | null; @@ -12209,7 +12056,6 @@ interface RTCIceTransportEventMap { /** Provides access to information about the ICE transport layer over which the data is being sent and received. */ interface RTCIceTransport extends EventTarget { - readonly component: RTCIceComponent; readonly gatheringState: RTCIceGathererState; ongatheringstatechange: ((this: RTCIceTransport, ev: Event) => any) | null; onselectedcandidatepairchange: ((this: RTCIceTransport, ev: Event) => any) | null; @@ -12260,7 +12106,6 @@ interface RTCPeerConnectionEventMap { "icegatheringstatechange": Event; "negotiationneeded": Event; "signalingstatechange": Event; - "statsended": RTCStatsEvent; "track": RTCTrackEvent; } @@ -12283,7 +12128,6 @@ interface RTCPeerConnection extends EventTarget { onicegatheringstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; onnegotiationneeded: ((this: RTCPeerConnection, ev: Event) => any) | null; onsignalingstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; - onstatsended: ((this: RTCPeerConnection, ev: RTCStatsEvent) => any) | null; ontrack: ((this: RTCPeerConnection, ev: RTCTrackEvent) => any) | null; readonly peerIdentity: Promise; readonly pendingLocalDescription: RTCSessionDescription | null; @@ -12305,9 +12149,10 @@ interface RTCPeerConnection extends EventTarget { getStats(selector?: MediaStreamTrack | null): Promise; getTransceivers(): RTCRtpTransceiver[]; removeTrack(sender: RTCRtpSender): void; - setConfiguration(configuration: RTCConfiguration): void; + restartIce(): void; + setConfiguration(configuration?: RTCConfiguration): void; setIdentityProvider(provider: string, options?: RTCIdentityProviderOptions): void; - setLocalDescription(description: RTCSessionDescriptionInit): Promise; + setLocalDescription(description?: RTCSessionDescriptionInit): Promise; setRemoteDescription(description: RTCSessionDescriptionInit): Promise; addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -12319,13 +12164,13 @@ declare var RTCPeerConnection: { prototype: RTCPeerConnection; new(configuration?: RTCConfiguration): RTCPeerConnection; generateCertificate(keygenAlgorithm: AlgorithmIdentifier): Promise; - getDefaultIceServers(): RTCIceServer[]; }; interface RTCPeerConnectionIceErrorEvent extends Event { + readonly address: string | null; readonly errorCode: number; readonly errorText: string; - readonly hostCandidate: string; + readonly port: number | null; readonly url: string; } @@ -12337,7 +12182,6 @@ declare var RTCPeerConnectionIceErrorEvent: { /** Events that occurs in relation to ICE candidates with the target, usually an RTCPeerConnection. Only one event is of this type: icecandidate. */ interface RTCPeerConnectionIceEvent extends Event { readonly candidate: RTCIceCandidate | null; - readonly url: string | null; } declare var RTCPeerConnectionIceEvent: { @@ -12347,7 +12191,6 @@ declare var RTCPeerConnectionIceEvent: { /** This WebRTC API interface manages the reception and decoding of data for a MediaStreamTrack on an RTCPeerConnection. */ interface RTCRtpReceiver { - readonly rtcpTransport: RTCDtlsTransport | null; readonly track: MediaStreamTrack; readonly transport: RTCDtlsTransport | null; getContributingSources(): RTCRtpContributingSource[]; @@ -12365,7 +12208,6 @@ declare var RTCRtpReceiver: { /** Provides the ability to control and obtain details about how a particular MediaStreamTrack is encoded and sent to a remote peer. */ interface RTCRtpSender { readonly dtmf: RTCDTMFSender | null; - readonly rtcpTransport: RTCDtlsTransport | null; readonly track: MediaStreamTrack | null; readonly transport: RTCDtlsTransport | null; getParameters(): RTCRtpSendParameters; @@ -12426,7 +12268,7 @@ interface RTCSessionDescription { declare var RTCSessionDescription: { prototype: RTCSessionDescription; - new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; + new(descriptionInitDict: RTCSessionDescriptionInit): RTCSessionDescription; }; interface RTCSrtpSdesTransportEventMap { @@ -12457,15 +12299,6 @@ declare var RTCSsrcConflictEvent: { new(): RTCSsrcConflictEvent; }; -interface RTCStatsEvent extends Event { - readonly report: RTCStatsReport; -} - -declare var RTCStatsEvent: { - prototype: RTCStatsEvent; - new(type: string, eventInitDict: RTCStatsEventInit): RTCStatsEvent; -}; - interface RTCStatsProvider extends EventTarget { getStats(): Promise; msGetStats(): Promise; @@ -13947,46 +13780,6 @@ declare var SVGNumberList: { interface SVGPathElement extends SVGGraphicsElement { /** @deprecated */ readonly pathSegList: SVGPathSegList; - /** @deprecated */ - createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; - /** @deprecated */ - createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; - /** @deprecated */ - createSVGPathSegClosePath(): SVGPathSegClosePath; - /** @deprecated */ - createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; - /** @deprecated */ - createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; - /** @deprecated */ - createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; - /** @deprecated */ - createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; - /** @deprecated */ - createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; - /** @deprecated */ - createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; - /** @deprecated */ - createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; - /** @deprecated */ - createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; - /** @deprecated */ - createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; - /** @deprecated */ - createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; - /** @deprecated */ - createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; - /** @deprecated */ - createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; - /** @deprecated */ - createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; - /** @deprecated */ - createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; - /** @deprecated */ - createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; - /** @deprecated */ - createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; - /** @deprecated */ - getPathSegAtLength(distance: number): number; getPointAtLength(distance: number): SVGPoint; getTotalLength(): number; addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -14424,25 +14217,11 @@ interface SVGSVGElementEventMap extends SVGElementEventMap { /** Provides access to the properties of elements, as well as methods to manipulate them. This interface contains also various miscellaneous commonly-used utility methods, such as matrix operations and the ability to control the time of redraw on visual rendering devices. */ interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewBox, SVGZoomAndPan { - /** @deprecated */ - contentScriptType: string; - /** @deprecated */ - contentStyleType: string; currentScale: number; readonly currentTranslate: SVGPoint; readonly height: SVGAnimatedLength; onunload: ((this: SVGSVGElement, ev: Event) => any) | null; onzoom: ((this: SVGSVGElement, ev: SVGZoomEvent) => any) | null; - /** @deprecated */ - readonly pixelUnitToMillimeterX: number; - /** @deprecated */ - readonly pixelUnitToMillimeterY: number; - /** @deprecated */ - readonly screenPixelToMillimeterX: number; - /** @deprecated */ - readonly screenPixelToMillimeterY: number; - /** @deprecated */ - readonly viewport: SVGRect; readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; @@ -14770,9 +14549,7 @@ declare var SVGUnitTypes: { /** Corresponds to the element. */ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { - readonly animatedInstanceRoot: SVGElementInstance | null; readonly height: SVGAnimatedLength; - readonly instanceRoot: SVGElementInstance | null; readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; @@ -14805,16 +14582,12 @@ declare var SVGViewElement: { readonly SVG_ZOOMANDPAN_UNKNOWN: number; }; -/** Used to reflect the zoomAndPan attribute, and is mixed in to other interfaces for elements that support this attribute. */ interface SVGZoomAndPan { - readonly zoomAndPan: number; -} - -declare var SVGZoomAndPan: { + zoomAndPan: number; readonly SVG_ZOOMANDPAN_DISABLE: number; readonly SVG_ZOOMANDPAN_MAGNIFY: number; readonly SVG_ZOOMANDPAN_UNKNOWN: number; -}; +} interface SVGZoomEvent extends UIEvent { readonly newScale: number; @@ -14829,26 +14602,6 @@ declare var SVGZoomEvent: { new(): SVGZoomEvent; }; -interface ScopedCredential { - readonly id: ArrayBuffer; - readonly type: ScopedCredentialType; -} - -declare var ScopedCredential: { - prototype: ScopedCredential; - new(): ScopedCredential; -}; - -interface ScopedCredentialInfo { - readonly credential: ScopedCredential; - readonly publicKey: CryptoKey; -} - -declare var ScopedCredentialInfo: { - prototype: ScopedCredentialInfo; - new(): ScopedCredentialInfo; -}; - /** A screen, usually the one on which the current window is being rendered, and is obtained using window.screen. */ interface Screen { readonly availHeight: number; @@ -15016,22 +14769,6 @@ declare var ServiceWorkerContainer: { new(): ServiceWorkerContainer; }; -/** This ServiceWorker API interface contains information about an event sent to a ServiceWorkerContainer target. This extends the default message event to allow setting a ServiceWorker object as the source of a message. The event object is accessed via the handler function of a message event, when fired by a message received from a service worker. - * @deprecated In modern browsers, this interface has been deprecated. Service worker messages will now use the MessageEvent interface, for consistency with other web messaging features. - */ -interface ServiceWorkerMessageEvent extends Event { - readonly data: any; - readonly lastEventId: string; - readonly origin: string; - readonly ports: ReadonlyArray | null; - readonly source: ServiceWorker | MessagePort | null; -} - -declare var ServiceWorkerMessageEvent: { - prototype: ServiceWorkerMessageEvent; - new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; -}; - interface ServiceWorkerRegistrationEventMap { "updatefound": Event; } @@ -15414,7 +15151,7 @@ interface Storage { removeItem(key: string): void; /** * Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously. - * + * * Throws a "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.) */ setItem(key: string, value: string): void; @@ -15564,7 +15301,7 @@ declare var Text: { interface TextDecoder extends TextDecoderCommon { /** * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. - * + * * ``` * var string = "", decoder = new TextDecoder(encoding), buffer; * while(buffer = next_chunk()) { @@ -15572,7 +15309,7 @@ interface TextDecoder extends TextDecoderCommon { * } * string += decoder.decode(); // end-of-queue * ``` - * + * * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. */ decode(input?: BufferSource, options?: TextDecodeOptions): string; @@ -15690,34 +15427,6 @@ interface TextMetrics { * Returns the measurement described below. */ readonly actualBoundingBoxRight: number; - /** - * Returns the measurement described below. - */ - readonly alphabeticBaseline: number; - /** - * Returns the measurement described below. - */ - readonly emHeightAscent: number; - /** - * Returns the measurement described below. - */ - readonly emHeightDescent: number; - /** - * Returns the measurement described below. - */ - readonly fontBoundingBoxAscent: number; - /** - * Returns the measurement described below. - */ - readonly fontBoundingBoxDescent: number; - /** - * Returns the measurement described below. - */ - readonly hangingBaseline: number; - /** - * Returns the measurement described below. - */ - readonly ideographicBaseline: number; /** * Returns the measurement described below. */ @@ -15745,9 +15454,9 @@ interface TextTrack extends EventTarget { readonly cues: TextTrackCueList | null; /** * Returns the ID of the given track. - * + * * For in-band tracks, this is the ID that can be used with a fragment if the format supports media fragment syntax, and that can be used with the getTrackById() method. - * + * * For TextTrack objects corresponding to track elements, this is the ID of the track element. */ readonly id: string; @@ -15769,12 +15478,11 @@ interface TextTrack extends EventTarget { readonly language: string; /** * Returns the text track mode, represented by a string from the following list: - * + * * Can be set, to change the mode. */ mode: TextTrackMode; oncuechange: ((this: TextTrack, ev: Event) => any) | null; - readonly sourceBuffer: SourceBuffer | null; /** * Adds the given cue to textTrack's text track list of cues. */ @@ -15803,13 +15511,13 @@ interface TextTrackCueEventMap { interface TextTrackCue extends EventTarget { /** * Returns the text track cue end time, in seconds. - * + * * Can be set. */ endTime: number; /** * Returns the text track cue identifier. - * + * * Can be set. */ id: string; @@ -15817,13 +15525,13 @@ interface TextTrackCue extends EventTarget { onexit: ((this: TextTrackCue, ev: Event) => any) | null; /** * Returns true if the text track cue pause-on-exit flag is set, false otherwise. - * + * * Can be set. */ pauseOnExit: boolean; /** * Returns the text track cue start time, in seconds. - * + * * Can be set. */ startTime: number; @@ -15849,7 +15557,7 @@ interface TextTrackCueList { readonly length: number; /** * Returns the first text track cue (in text track cue order) with text track cue identifier id. - * + * * Returns null if none of the cues have the given identifier or if the argument is the empty string. */ getCueById(id: string): TextTrackCue | null; @@ -15893,13 +15601,13 @@ interface TimeRanges { readonly length: number; /** * Returns the time for the end of the range with the given index. - * + * * Throws an "IndexSizeError" DOMException if the index is out of range. */ end(index: number): number; /** * Returns the time for the start of the range with the given index. - * + * * Throws an "IndexSizeError" DOMException if the index is out of range. */ start(index: number): number; @@ -16212,7 +15920,6 @@ interface VRPose { readonly linearVelocity: Float32Array | null; readonly orientation: Float32Array | null; readonly position: Float32Array | null; - readonly timestamp: number; } declare var VRPose: { @@ -16439,28 +16146,6 @@ declare var WaveShaperNode: { new(context: BaseAudioContext, options?: WaveShaperOptions): WaveShaperNode; }; -interface WebAuthentication { - getAssertion(assertionChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: ScopedCredentialOptions): Promise; -} - -declare var WebAuthentication: { - prototype: WebAuthentication; - new(): WebAuthentication; -}; - -interface WebAuthnAssertion { - readonly authenticatorData: ArrayBuffer; - readonly clientData: ArrayBuffer; - readonly credential: ScopedCredential; - readonly signature: ArrayBuffer; -} - -declare var WebAuthnAssertion: { - prototype: WebAuthnAssertion; - new(): WebAuthnAssertion; -}; - interface WebGL2RenderingContext extends WebGL2RenderingContextBase, WebGL2RenderingContextOverloads, WebGLRenderingContextBase { } @@ -17438,7 +17123,7 @@ declare var WebGLActiveInfo: { }; /** Part of the WebGL API and represents an opaque buffer object storing data such as vertices or colors. */ -interface WebGLBuffer extends WebGLObject { +interface WebGLBuffer { } declare var WebGLBuffer: { @@ -17457,7 +17142,7 @@ declare var WebGLContextEvent: { }; /** Part of the WebGL API and represents a collection of buffers that serve as a rendering destination. */ -interface WebGLFramebuffer extends WebGLObject { +interface WebGLFramebuffer { } declare var WebGLFramebuffer: { @@ -17465,16 +17150,8 @@ declare var WebGLFramebuffer: { new(): WebGLFramebuffer; }; -interface WebGLObject { -} - -declare var WebGLObject: { - prototype: WebGLObject; - new(): WebGLObject; -}; - /** The WebGLProgram is part of the WebGL API and is a combination of two compiled WebGLShaders consisting of a vertex shader and a fragment shader (both written in GLSL). */ -interface WebGLProgram extends WebGLObject { +interface WebGLProgram { } declare var WebGLProgram: { @@ -17482,7 +17159,7 @@ declare var WebGLProgram: { new(): WebGLProgram; }; -interface WebGLQuery extends WebGLObject { +interface WebGLQuery { } declare var WebGLQuery: { @@ -17491,7 +17168,7 @@ declare var WebGLQuery: { }; /** Part of the WebGL API and represents a buffer that can contain an image, or can be source or target of an rendering operation. */ -interface WebGLRenderbuffer extends WebGLObject { +interface WebGLRenderbuffer { } declare var WebGLRenderbuffer: { @@ -18270,7 +17947,7 @@ interface WebGLRenderingContextOverloads { uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; } -interface WebGLSampler extends WebGLObject { +interface WebGLSampler { } declare var WebGLSampler: { @@ -18279,7 +17956,7 @@ declare var WebGLSampler: { }; /** The WebGLShader is part of the WebGL API and can either be a vertex or a fragment shader. A WebGLProgram requires both types of shaders. */ -interface WebGLShader extends WebGLObject { +interface WebGLShader { } declare var WebGLShader: { @@ -18299,7 +17976,7 @@ declare var WebGLShaderPrecisionFormat: { new(): WebGLShaderPrecisionFormat; }; -interface WebGLSync extends WebGLObject { +interface WebGLSync { } declare var WebGLSync: { @@ -18308,7 +17985,7 @@ declare var WebGLSync: { }; /** Part of the WebGL API and represents an opaque texture object providing storage and state for texturing operations. */ -interface WebGLTexture extends WebGLObject { +interface WebGLTexture { } declare var WebGLTexture: { @@ -18316,7 +17993,7 @@ declare var WebGLTexture: { new(): WebGLTexture; }; -interface WebGLTransformFeedback extends WebGLObject { +interface WebGLTransformFeedback { } declare var WebGLTransformFeedback: { @@ -18333,7 +18010,7 @@ declare var WebGLUniformLocation: { new(): WebGLUniformLocation; }; -interface WebGLVertexArrayObject extends WebGLObject { +interface WebGLVertexArrayObject { } declare var WebGLVertexArrayObject: { @@ -18341,7 +18018,7 @@ declare var WebGLVertexArrayObject: { new(): WebGLVertexArrayObject; }; -interface WebGLVertexArrayObjectOES extends WebGLObject { +interface WebGLVertexArrayObjectOES { } interface WebKitPoint { @@ -18365,13 +18042,13 @@ interface WebSocketEventMap { interface WebSocket extends EventTarget { /** * Returns a string that indicates how binary data from the WebSocket object is exposed to scripts: - * + * * Can be set, to change how binary data is returned. The default is "blob". */ binaryType: BinaryType; /** * Returns the number of bytes of application data (UTF-8 text and binary data) that have been queued using send() but not yet been transmitted to the network. - * + * * If the WebSocket connection is closed, this attribute's value will only increase with each call to the send() method. (The number does not reset to zero once the connection closes.) */ readonly bufferedAmount: number; @@ -18454,7 +18131,6 @@ interface WindowEventMap extends GlobalEventHandlersEventMap, WindowEventHandler "compassneedscalibration": Event; "contextmenu": MouseEvent; "dblclick": MouseEvent; - "devicelight": DeviceLightEvent; "devicemotion": DeviceMotionEvent; "deviceorientation": DeviceOrientationEvent; "deviceorientationabsolute": DeviceOrientationEvent; @@ -18491,21 +18167,6 @@ interface WindowEventMap extends GlobalEventHandlersEventMap, WindowEventHandler "mouseover": MouseEvent; "mouseup": MouseEvent; "mousewheel": Event; - "MSGestureChange": Event; - "MSGestureDoubleTap": Event; - "MSGestureEnd": Event; - "MSGestureHold": Event; - "MSGestureStart": Event; - "MSGestureTap": Event; - "MSInertiaStart": Event; - "MSPointerCancel": Event; - "MSPointerDown": Event; - "MSPointerEnter": Event; - "MSPointerLeave": Event; - "MSPointerMove": Event; - "MSPointerOut": Event; - "MSPointerOver": Event; - "MSPointerUp": Event; "offline": Event; "online": Event; "orientationchange": Event; @@ -18536,9 +18197,6 @@ interface WindowEventMap extends GlobalEventHandlersEventMap, WindowEventHandler "vrdisplayconnect": Event; "vrdisplaydeactivate": Event; "vrdisplaydisconnect": Event; - "vrdisplayfocus": Event; - "vrdisplaypointerrestricted": Event; - "vrdisplaypointerunrestricted": Event; "vrdisplaypresentchange": Event; "waiting": Event; } @@ -18571,28 +18229,12 @@ interface Window extends EventTarget, AnimationFrameProvider, GlobalEventHandler readonly navigator: Navigator; offscreenBuffering: string | boolean; oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; - ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; ondeviceorientationabsolute: ((this: Window, ev: DeviceOrientationEvent) => any) | null; ongamepadconnected: ((this: Window, ev: GamepadEvent) => any) | null; ongamepaddisconnected: ((this: Window, ev: GamepadEvent) => any) | null; onmousewheel: ((this: Window, ev: Event) => any) | null; - onmsgesturechange: ((this: Window, ev: Event) => any) | null; - onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; - onmsgestureend: ((this: Window, ev: Event) => any) | null; - onmsgesturehold: ((this: Window, ev: Event) => any) | null; - onmsgesturestart: ((this: Window, ev: Event) => any) | null; - onmsgesturetap: ((this: Window, ev: Event) => any) | null; - onmsinertiastart: ((this: Window, ev: Event) => any) | null; - onmspointercancel: ((this: Window, ev: Event) => any) | null; - onmspointerdown: ((this: Window, ev: Event) => any) | null; - onmspointerenter: ((this: Window, ev: Event) => any) | null; - onmspointerleave: ((this: Window, ev: Event) => any) | null; - onmspointermove: ((this: Window, ev: Event) => any) | null; - onmspointerout: ((this: Window, ev: Event) => any) | null; - onmspointerover: ((this: Window, ev: Event) => any) | null; - onmspointerup: ((this: Window, ev: Event) => any) | null; /** @deprecated */ onorientationchange: ((this: Window, ev: Event) => any) | null; onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; @@ -18601,11 +18243,8 @@ interface Window extends EventTarget, AnimationFrameProvider, GlobalEventHandler onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; - onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; - onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; - onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; - opener: any; + opener: WindowProxy | null; /** @deprecated */ readonly orientation: string | number; readonly outerHeight: number; @@ -18852,26 +18491,26 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget { readonly response: any; /** * Returns the text response. - * + * * Throws an "InvalidStateError" DOMException if responseType is not the empty string or "text". */ readonly responseText: string; /** * Returns the response type. - * + * * Can be set to change the response type. Values are: the empty string (default), "arraybuffer", "blob", "document", "json", and "text". - * + * * When set: setting to "document" is ignored if current global object is not a Window object. - * + * * When set: throws an "InvalidStateError" DOMException if state is loading or done. - * + * * When set: throws an "InvalidAccessError" DOMException if the synchronous flag is set and current global object is a Window object. */ responseType: XMLHttpRequestResponseType; readonly responseURL: string; /** * Returns the document response. - * + * * Throws an "InvalidStateError" DOMException if responseType is not the empty string or "document". */ readonly responseXML: Document | null; @@ -18879,7 +18518,7 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget { readonly statusText: string; /** * Can be set to a time in milliseconds. When set to a non-zero value will cause fetching to terminate after the given time has passed. When the time has passed, the request has not yet completed, and the synchronous flag is unset, a timeout event will then be dispatched, or a "TimeoutError" DOMException will be thrown otherwise (for the send() method). - * + * * When set: throws an "InvalidAccessError" DOMException if the synchronous flag is set and current global object is a Window object. */ timeout: number; @@ -18889,7 +18528,7 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget { readonly upload: XMLHttpRequestUpload; /** * True when credentials are to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. Initially false. - * + * * When set: throws an "InvalidStateError" DOMException if state is not unsent or opened, or if the send() flag is set. */ withCredentials: boolean; @@ -18901,32 +18540,32 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget { getResponseHeader(name: string): string | null; /** * Sets the request method, request URL, and synchronous flag. - * + * * Throws a "SyntaxError" DOMException if either method is not a valid HTTP method or url cannot be parsed. - * + * * Throws a "SecurityError" DOMException if method is a case-insensitive match for `CONNECT`, `TRACE`, or `TRACK`. - * + * * Throws an "InvalidAccessError" DOMException if async is false, current global object is a Window object, and the timeout attribute is not zero or the responseType attribute is not the empty string. */ open(method: string, url: string): void; open(method: string, url: string, async: boolean, username?: string | null, password?: string | null): void; /** * Acts as if the `Content-Type` header value for response is mime. (It does not actually change the header though.) - * + * * Throws an "InvalidStateError" DOMException if state is loading or done. */ overrideMimeType(mime: string): void; /** * Initiates the request. The body argument provides the request body, if any, and is ignored if the request method is GET or HEAD. - * + * * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set. */ send(body?: Document | BodyInit | null): void; /** * Combines a header in author request headers. - * + * * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set. - * + * * Throws a "SyntaxError" DOMException if name is not a header name or if value is not a header value. */ setRequestHeader(name: string, value: string): void; @@ -19133,52 +18772,52 @@ declare namespace CSS { declare namespace WebAssembly { interface CompileError { } - + var CompileError: { prototype: CompileError; new(): CompileError; }; - + interface Global { value: any; valueOf(): any; } - + var Global: { prototype: Global; new(descriptor: GlobalDescriptor, v?: any): Global; }; - + interface Instance { readonly exports: Exports; } - + var Instance: { prototype: Instance; new(module: Module, importObject?: Imports): Instance; }; - + interface LinkError { } - + var LinkError: { prototype: LinkError; new(): LinkError; }; - + interface Memory { readonly buffer: ArrayBuffer; grow(delta: number): number; } - + var Memory: { prototype: Memory; new(descriptor: MemoryDescriptor): Memory; }; - + interface Module { } - + var Module: { prototype: Module; new(bytes: BufferSource): Module; @@ -19186,59 +18825,60 @@ declare namespace WebAssembly { exports(moduleObject: Module): ModuleExportDescriptor[]; imports(moduleObject: Module): ModuleImportDescriptor[]; }; - + interface RuntimeError { } - + var RuntimeError: { prototype: RuntimeError; new(): RuntimeError; }; - + interface Table { readonly length: number; get(index: number): Function | null; grow(delta: number): number; set(index: number, value: Function | null): void; } - + var Table: { prototype: Table; new(descriptor: TableDescriptor): Table; }; - + interface GlobalDescriptor { mutable?: boolean; value: ValueType; } - + interface MemoryDescriptor { initial: number; maximum?: number; + shared?: boolean; } - + interface ModuleExportDescriptor { kind: ImportExportKind; name: string; } - + interface ModuleImportDescriptor { kind: ImportExportKind; module: string; name: string; } - + interface TableDescriptor { element: TableKind; initial: number; maximum?: number; } - + interface WebAssemblyInstantiatedSource { instance: Instance; module: Module; } - + type ImportExportKind = "function" | "global" | "memory" | "table"; type TableKind = "anyfunc"; type ValueType = "f32" | "f64" | "i32" | "i64"; @@ -19406,7 +19046,6 @@ interface HTMLElementTagNameMap { "audio": HTMLAudioElement; "b": HTMLElement; "base": HTMLBaseElement; - "basefont": HTMLBaseFontElement; "bdi": HTMLElement; "bdo": HTMLElement; "blockquote": HTMLQuoteElement; @@ -19621,28 +19260,12 @@ declare const name: void; declare var navigator: Navigator; declare var offscreenBuffering: string | boolean; declare var oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; -declare var ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; declare var ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; declare var ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; declare var ondeviceorientationabsolute: ((this: Window, ev: DeviceOrientationEvent) => any) | null; declare var ongamepadconnected: ((this: Window, ev: GamepadEvent) => any) | null; declare var ongamepaddisconnected: ((this: Window, ev: GamepadEvent) => any) | null; declare var onmousewheel: ((this: Window, ev: Event) => any) | null; -declare var onmsgesturechange: ((this: Window, ev: Event) => any) | null; -declare var onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; -declare var onmsgestureend: ((this: Window, ev: Event) => any) | null; -declare var onmsgesturehold: ((this: Window, ev: Event) => any) | null; -declare var onmsgesturestart: ((this: Window, ev: Event) => any) | null; -declare var onmsgesturetap: ((this: Window, ev: Event) => any) | null; -declare var onmsinertiastart: ((this: Window, ev: Event) => any) | null; -declare var onmspointercancel: ((this: Window, ev: Event) => any) | null; -declare var onmspointerdown: ((this: Window, ev: Event) => any) | null; -declare var onmspointerenter: ((this: Window, ev: Event) => any) | null; -declare var onmspointerleave: ((this: Window, ev: Event) => any) | null; -declare var onmspointermove: ((this: Window, ev: Event) => any) | null; -declare var onmspointerout: ((this: Window, ev: Event) => any) | null; -declare var onmspointerover: ((this: Window, ev: Event) => any) | null; -declare var onmspointerup: ((this: Window, ev: Event) => any) | null; /** @deprecated */ declare var onorientationchange: ((this: Window, ev: Event) => any) | null; declare var onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; @@ -19651,11 +19274,8 @@ declare var onvrdisplayblur: ((this: Window, ev: Event) => any) | null; declare var onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; declare var onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; declare var onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; -declare var onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; -declare var onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; -declare var onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; declare var onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; -declare var opener: any; +declare var opener: WindowProxy | null; /** @deprecated */ declare var orientation: string | number; declare var outerHeight: number; @@ -20168,15 +19788,13 @@ type PushEncryptionKeyName = "auth" | "p256dh"; type PushPermissionState = "denied" | "granted" | "prompt"; type RTCBundlePolicy = "balanced" | "max-bundle" | "max-compat"; type RTCDataChannelState = "closed" | "closing" | "connecting" | "open"; -type RTCDegradationPreference = "balanced" | "maintain-framerate" | "maintain-resolution"; type RTCDtlsRole = "auto" | "client" | "server"; type RTCDtlsTransportState = "closed" | "connected" | "connecting" | "failed" | "new"; -type RTCDtxStatus = "disabled" | "enabled"; -type RTCErrorDetailType = "data-channel-failure" | "dtls-failure" | "fingerprint-failure" | "hardware-encoder-error" | "hardware-encoder-not-available" | "idp-bad-script-failure" | "idp-execution-failure" | "idp-load-failure" | "idp-need-login" | "idp-timeout" | "idp-tls-failure" | "idp-token-expired" | "idp-token-invalid" | "sctp-failure" | "sdp-syntax-error"; +type RTCErrorDetailType = "data-channel-failure" | "dtls-failure" | "fingerprint-failure" | "hardware-encoder-error" | "hardware-encoder-not-available" | "sctp-failure" | "sdp-syntax-error"; type RTCIceCandidateType = "host" | "prflx" | "relay" | "srflx"; type RTCIceComponent = "rtcp" | "rtp"; type RTCIceConnectionState = "checking" | "closed" | "completed" | "connected" | "disconnected" | "failed" | "new"; -type RTCIceCredentialType = "oauth" | "password"; +type RTCIceCredentialType = "password"; type RTCIceGatherPolicy = "all" | "nohost" | "relay"; type RTCIceGathererState = "complete" | "gathering" | "new"; type RTCIceGatheringState = "complete" | "gathering" | "new"; @@ -20186,8 +19804,7 @@ type RTCIceTcpCandidateType = "active" | "passive" | "so"; type RTCIceTransportPolicy = "all" | "relay"; type RTCIceTransportState = "checking" | "closed" | "completed" | "connected" | "disconnected" | "failed" | "new"; type RTCPeerConnectionState = "closed" | "connected" | "connecting" | "disconnected" | "failed" | "new"; -type RTCPriorityType = "high" | "low" | "medium" | "very-low"; -type RTCRtcpMuxPolicy = "negotiate" | "require"; +type RTCRtcpMuxPolicy = "require"; type RTCRtpTransceiverDirection = "inactive" | "recvonly" | "sendonly" | "sendrecv" | "stopped"; type RTCSctpTransportState = "closed" | "connected" | "connecting"; type RTCSdpType = "answer" | "offer" | "pranswer" | "rollback"; @@ -20206,7 +19823,6 @@ type ResidentKeyRequirement = "discouraged" | "preferred" | "required"; type ResizeObserverBoxOptions = "border-box" | "content-box" | "device-pixel-content-box"; type ResizeQuality = "high" | "low" | "medium" | "pixelated"; type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; -type ScopedCredentialType = "ScopedCred"; type ScrollBehavior = "auto" | "smooth"; type ScrollLogicalPosition = "center" | "end" | "nearest" | "start"; type ScrollRestoration = "auto" | "manual"; @@ -20220,7 +19836,6 @@ type SpeechSynthesisErrorCode = "audio-busy" | "audio-hardware" | "canceled" | " type TextTrackKind = "captions" | "chapters" | "descriptions" | "metadata" | "subtitles"; type TextTrackMode = "disabled" | "hidden" | "showing"; type TouchType = "direct" | "stylus"; -type Transport = "ble" | "nfc" | "usb"; type UserVerificationRequirement = "discouraged" | "preferred" | "required"; type VRDisplayEventReason = "mounted" | "navigation" | "requested" | "unmounted"; type VideoFacingModeEnum = "environment" | "left" | "right" | "user"; diff --git a/lib/lib.dom.iterable.d.ts b/lib/lib.dom.iterable.d.ts index ebd56d76790a8..7e86bc19b28f7 100644 --- a/lib/lib.dom.iterable.d.ts +++ b/lib/lib.dom.iterable.d.ts @@ -139,7 +139,7 @@ interface IDBDatabase { interface IDBObjectStore { /** * Creates a new index in store with the given name, keyPath and options and returns a new IDBIndex. If the keyPath and options define constraints that cannot be satisfied with the data already in store the upgrade transaction will abort with a "ConstraintError" DOMException. - * + * * Throws an "InvalidStateError" DOMException if not called within an upgrade transaction. */ createIndex(name: string, keyPath: string | Iterable, options?: IDBIndexParameters): IDBIndex; @@ -287,10 +287,6 @@ interface WEBGL_draw_buffers { drawBuffersWEBGL(buffers: Iterable): void; } -interface WebAuthentication { - makeCredential(accountInformation: Account, cryptoParameters: Iterable, attestationChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: ScopedCredentialOptions): Promise; -} - interface WebGL2RenderingContextBase { clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Iterable, srcOffset?: GLuint): void; clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Iterable, srcOffset?: GLuint): void; diff --git a/lib/lib.es2015.core.d.ts b/lib/lib.es2015.core.d.ts index f33038d6df6d0..20aa06f6d0a2c 100644 --- a/lib/lib.es2015.core.d.ts +++ b/lib/lib.es2015.core.d.ts @@ -268,8 +268,8 @@ interface NumberConstructor { /** * Converts A string to an integer. - * @param s A string to convert into a number. - * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * @param string A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in `string`. * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. * All other strings are considered decimal. */ diff --git a/lib/lib.es2015.iterable.d.ts b/lib/lib.es2015.iterable.d.ts index 0dcbcfab26c83..06a503099acb2 100644 --- a/lib/lib.es2015.iterable.d.ts +++ b/lib/lib.es2015.iterable.d.ts @@ -25,7 +25,7 @@ interface SymbolConstructor { * A method that returns the default iterator for an object. Called by the semantics of the * for-of statement. */ - readonly iterator: symbol; + readonly iterator: unique symbol; } interface IteratorYieldResult { diff --git a/lib/lib.es2015.symbol.wellknown.d.ts b/lib/lib.es2015.symbol.wellknown.d.ts index b2831957a1aaa..b98e2f08ffb77 100644 --- a/lib/lib.es2015.symbol.wellknown.d.ts +++ b/lib/lib.es2015.symbol.wellknown.d.ts @@ -25,61 +25,61 @@ interface SymbolConstructor { * A method that determines if a constructor object recognizes an object as one of the * constructor’s instances. Called by the semantics of the instanceof operator. */ - readonly hasInstance: symbol; + readonly hasInstance: unique symbol; /** * A Boolean value that if true indicates that an object should flatten to its array elements * by Array.prototype.concat. */ - readonly isConcatSpreadable: symbol; + readonly isConcatSpreadable: unique symbol; /** * A regular expression method that matches the regular expression against a string. Called * by the String.prototype.match method. */ - readonly match: symbol; + readonly match: unique symbol; /** * A regular expression method that replaces matched substrings of a string. Called by the * String.prototype.replace method. */ - readonly replace: symbol; + readonly replace: unique symbol; /** * A regular expression method that returns the index within a string that matches the * regular expression. Called by the String.prototype.search method. */ - readonly search: symbol; + readonly search: unique symbol; /** * A function valued property that is the constructor function that is used to create * derived objects. */ - readonly species: symbol; + readonly species: unique symbol; /** * A regular expression method that splits a string at the indices that match the regular * expression. Called by the String.prototype.split method. */ - readonly split: symbol; + readonly split: unique symbol; /** * A method that converts an object to a corresponding primitive value. * Called by the ToPrimitive abstract operation. */ - readonly toPrimitive: symbol; + readonly toPrimitive: unique symbol; /** * A String value that is used in the creation of the default string description of an object. * Called by the built-in method Object.prototype.toString. */ - readonly toStringTag: symbol; + readonly toStringTag: unique symbol; /** * An Object whose own property names are property names that are excluded from the 'with' * environment bindings of the associated objects. */ - readonly unscopables: symbol; + readonly unscopables: unique symbol; } interface Symbol { diff --git a/lib/lib.es2018.asynciterable.d.ts b/lib/lib.es2018.asynciterable.d.ts index 2c3a970854e5d..88f9d8fbab16e 100644 --- a/lib/lib.es2018.asynciterable.d.ts +++ b/lib/lib.es2018.asynciterable.d.ts @@ -26,7 +26,7 @@ interface SymbolConstructor { * A method that returns the default async iterator for an object. Called by the semantics of * the for-await-of statement. */ - readonly asyncIterator: symbol; + readonly asyncIterator: unique symbol; } interface AsyncIterator { diff --git a/lib/lib.es2020.bigint.d.ts b/lib/lib.es2020.bigint.d.ts index 6dc8b25acf2e7..92acfe4a4af67 100644 --- a/lib/lib.es2020.bigint.d.ts +++ b/lib/lib.es2020.bigint.d.ts @@ -121,7 +121,7 @@ interface BigInt { } interface BigIntConstructor { - (value?: any): bigint; + (value: bigint | boolean | number | string): bigint; readonly prototype: BigInt; /** diff --git a/lib/lib.es2020.intl.d.ts b/lib/lib.es2020.intl.d.ts index 25c6aa1b8f272..2470d08b6fefc 100644 --- a/lib/lib.es2020.intl.d.ts +++ b/lib/lib.es2020.intl.d.ts @@ -21,13 +21,12 @@ and limitations under the License. declare namespace Intl { /** - * [BCP 47 language tag](http://tools.ietf.org/html/rfc5646) definition. + * [Unicode BCP 47 Locale Identifiers](https://unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers) definition. * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument). * - * [Wikipedia](https://en.wikipedia.org/wiki/IETF_language_tag). */ - type BCP47LanguageTag = string; + type UnicodeBCP47LocaleIdentifier = string; /** * Unit to use in the relative time internationalized message. @@ -74,239 +73,6 @@ declare namespace Intl { */ type RelativeTimeFormatStyle = "long" | "short" | "narrow"; - /** - * Unicode Calendar Identifier - * - * [Reference](http://unicode.org/reports/tr35/#UnicodeCalendarIdentifier) - * - * [Source](https://github.com/unicode-org/cldr/blob/b805d0b/common/bcp47/calendar.xml) - */ - type Calendar = - // Thai Buddhist calendar - | "buddhist" - // Traditional Chinese calendar - | "chinese" - // Coptic calendar - | "coptic" - // Traditional Korean calendar - | "dangi" - // Ethiopic calendar, Amete Alem (epoch approx. 5493 B.C.E) - | "ethiopic-amete-alem" | "ethioaa" - // Ethiopic calendar, Amete Mihret (epoch approx, 8 C.E.) - | "ethiopic" - // Gregorian calendar - | "gregorian" - // Gregorian calendar (alias) - | "gregory" - // Traditional Hebrew calendar - | "hebrew" - // Indian calendar - | "indian" - // Islamic calendar - | "islamic" - // Islamic calendar, Umm al-Qura - | "islamic-umalqura" - // Islamic calendar, tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29] - astronomical epoch) - | "islamic-tbla" - // Islamic calendar, tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29] - civil epoch) - | "islamic-civil" - | "islamicc" // Deprecated alias - // Islamic calendar, Saudi Arabia sighting - | "islamic-rgsa" - // ISO calendar (Gregorian calendar using the ISO 8601 calendar week rules) - | "iso8601" - // Japanese Imperial calendar - | "japanese" - // Persian calendar - | "persian" - // Republic of China calendar - | "roc" - ; - - /** - * Unicode Number System Identifier - * - * [Reference](http://unicode.org/reports/tr35/#UnicodeNumberSystemIdentifier) - * - * [Source](https://github.com/unicode-org/cldr/blob/be7a953/common/bcp47/number.xml) - */ - type NumberingSystem = - // Adlam digits - | "adlm" - // Ahom digits - | "ahom" - // Arabic-Indic digits - | "arab" - // Extended Arabic-Indic digits - | "arabext" - // Armenian upper case numerals — algorithmic - | "armn" - // Armenian lower case numerals — algorithmic - | "armnlow" - // Balinese digits - | "bali" - // Bengali digits - | "beng" - // Bhaiksuki digits - | "bhks" - // Brahmi digits - | "brah" - // Chakma digits - | "cakm" - // Cham digits - | "cham" - // Cyrillic numerals — algorithmic - | "cyrl" - // Devanagari digits - | "deva" - // Dives Akuru digits - | "diak" - // Ethiopic numerals — algorithmic - | "ethi" - // Financial numerals — may be algorithmic - | "finance" - // Full width digits - | "fullwide" - // Georgian numerals — algorithmic - | "geor" - // Gunjala Gondi digits - | "gong" - // Masaram Gondi digits - | "gonm" - // Greek upper case numerals — algorithmic - | "grek" - // Greek lower case numerals — algorithmic - | "greklow" - // Gujarati digits - | "gujr" - // Gurmukhi digits - | "guru" - // Han-character day-of-month numbering for lunar/other traditional calendars" - | "hanidays" - // Positional decimal system using Chinese number ideographs as digits - | "hanidec" - // Simplified Chinese numerals — algorithmic - | "hans" - // Simplified Chinese financial numerals — algorithmic - | "hansfin" - // Traditional Chinese numerals — algorithmic - | "hant" - // Traditional Chinese financial numerals — algorithmic - | "hantfin" - // Hebrew numerals — algorithmic - | "hebr" - // Pahawh Hmong digits - | "hmng" - // Nyiakeng Puachue Hmong digits - | "hmnp" - // Javanese digits - | "java" - // Japanese numerals — algorithmic - | "jpan" - // Japanese financial numerals — algorithmic - | "jpanfin" - // Japanese first-year Gannen numbering for Japanese calendar - | "jpanyear" - // Kayah Li digits - | "kali" - // Khmer digits - | "khmr" - // Kannada digits - | "knda" - // Tai Tham Hora (secular) digits - | "lana" - // Tai Tham Tham (ecclesiastical) digits - | "lanatham" - // Lao digits - | "laoo" - // Latin digits - | "latn" - // Lepcha digits - | "lepc" - // Limbu digits - | "limb" - // Mathematical bold digits - | "mathbold" - // Mathematical double-struck digits - | "mathdbl" - // Mathematical monospace digits - | "mathmono" - // Mathematical sans-serif bold digits - | "mathsanb" - // Mathematical sans-serif digits - | "mathsans" - // Malayalam digits - | "mlym" - // Modi digits - | "modi" - // Mongolian digits - | "mong" - // Mro digits - | "mroo" - // Meetei Mayek digits - | "mtei" - // Myanmar digits - | "mymr" - // Myanmar Shan digits - | "mymrshan" - // Myanmar Tai Laing digits - | "mymrtlng" - // Native digits - | "native" - // Newa digits - | "newa" - // N'Ko digits - | "nkoo" - // Ol Chiki digits - | "olck" - // Oriya digits - | "orya" - // Osmanya digits - | "osma" - // Hanifi Rohingya digits - | "rohg" - // Roman upper case numerals — algorithmic - | "roman" - // Roman lowercase numerals — algorithmic - | "romanlow" - // Saurashtra digits - | "saur" - // Sharada digits - | "shrd" - // Khudawadi digits - | "sind" - // Sinhala Lith digits - | "sinh" - // Sora_Sompeng digits - | "sora" - // Sundanese digits - | "sund" - // Takri digits - | "takr" - // New Tai Lue digits - | "talu" - // Tamil numerals — algorithmic - | "taml" - // Modern Tamil decimal digits - | "tamldec" - // Telugu digits - | "telu" - // Thai digits - | "thai" - // Tirhuta digits - | "tirh" - // Tibetan digits - | "tibt" - // Traditional numerals — may be algorithmic - | "traditional" | "traditio" - // Vai digits - | "vaii" - // Warang Citi digits - | "wara" - // Wancho digits - | "wcho" - ; - /** * An object with some or all of properties of `options` parameter * of `Intl.RelativeTimeFormat` constructor. @@ -331,7 +97,7 @@ declare namespace Intl { * [Specification](https://tc39.es/ecma402/#table-relativetimeformat-resolvedoptions-properties) */ interface ResolvedRelativeTimeFormatOptions { - locale: BCP47LanguageTag; + locale: UnicodeBCP47LocaleIdentifier; style: RelativeTimeFormatStyle; numeric: RelativeTimeFormatNumeric; numberingSystem: string; @@ -474,7 +240,7 @@ declare namespace Intl { * [Specification](https://tc39.es/ecma402/#sec-intl-relativetimeformat-constructor). */ new( - locales?: BCP47LanguageTag | BCP47LanguageTag[], + locales?: UnicodeBCP47LocaleIdentifier | UnicodeBCP47LocaleIdentifier[], options?: RelativeTimeFormatOptions, ): RelativeTimeFormat; @@ -510,9 +276,9 @@ declare namespace Intl { * [Specification](https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.supportedLocalesOf). */ supportedLocalesOf( - locales: BCP47LanguageTag | BCP47LanguageTag[], + locales?: UnicodeBCP47LocaleIdentifier | UnicodeBCP47LocaleIdentifier[], options?: RelativeTimeFormatOptions, - ): BCP47LanguageTag[]; + ): UnicodeBCP47LocaleIdentifier[]; }; interface NumberFormatOptions { @@ -534,9 +300,9 @@ declare namespace Intl { interface DateTimeFormatOptions { dateStyle?: "full" | "long" | "medium" | "short"; timeStyle?: "full" | "long" | "medium" | "short"; - calendar?: Calendar; + calendar?: string; dayPeriod?: "narrow" | "short" | "long"; - numberingSystem?: NumberingSystem; + numberingSystem?: string; hourCycle?: "h11" | "h12" | "h23" | "h24"; fractionalSecondDigits?: 0 | 1 | 2 | 3; } diff --git a/lib/lib.es2020.symbol.wellknown.d.ts b/lib/lib.es2020.symbol.wellknown.d.ts index 4bac52fecd3d6..7df0a2f45774a 100644 --- a/lib/lib.es2020.symbol.wellknown.d.ts +++ b/lib/lib.es2020.symbol.wellknown.d.ts @@ -26,7 +26,7 @@ interface SymbolConstructor { * A regular expression method that matches the regular expression against a string. Called * by the String.prototype.matchAll method. */ - readonly matchAll: symbol; + readonly matchAll: unique symbol; } interface RegExp { diff --git a/lib/lib.es2021.d.ts b/lib/lib.es2021.d.ts new file mode 100644 index 0000000000000..1cb1e732ad858 --- /dev/null +++ b/lib/lib.es2021.d.ts @@ -0,0 +1,24 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// +/// +/// +/// diff --git a/lib/lib.es2021.full.d.ts b/lib/lib.es2021.full.d.ts new file mode 100644 index 0000000000000..53488737712c8 --- /dev/null +++ b/lib/lib.es2021.full.d.ts @@ -0,0 +1,25 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +/// +/// +/// +/// +/// diff --git a/lib/lib.es2021.promise.d.ts b/lib/lib.es2021.promise.d.ts new file mode 100644 index 0000000000000..6a56c55128861 --- /dev/null +++ b/lib/lib.es2021.promise.d.ts @@ -0,0 +1,43 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface AggregateError extends Error { + errors: any[] +} + +interface AggregateErrorConstructor { + new(errors: Iterable, message?: string): AggregateError; + (errors: Iterable, message?: string): AggregateError; + readonly prototype: AggregateError; +} + +declare var AggregateError: AggregateErrorConstructor; + +/** + * Represents the completion of an asynchronous operation + */ +interface PromiseConstructor { + /** + * The any function returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected with an AggregateError containing an array of rejection reasons if all of the given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm. + * @param values An array or iterable of Promises. + * @returns A new Promise. + */ + any(values: (T | PromiseLike)[] | Iterable>): Promise +} diff --git a/lib/lib.es2021.string.d.ts b/lib/lib.es2021.string.d.ts new file mode 100644 index 0000000000000..89b27e2fe9094 --- /dev/null +++ b/lib/lib.es2021.string.d.ts @@ -0,0 +1,35 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface String { + /** + * Replace all instances of a substring in a string, using a regular expression or search string. + * @param searchValue A string to search for. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replaceAll(searchValue: string | RegExp, replaceValue: string): string; + + /** + * Replace all instances of a substring in a string, using a regular expression or search string. + * @param searchValue A string to search for. + * @param replacer A function that returns the replacement text. + */ + replaceAll(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string; +} diff --git a/lib/lib.es2021.weakref.d.ts b/lib/lib.es2021.weakref.d.ts new file mode 100644 index 0000000000000..eb7764242d7b9 --- /dev/null +++ b/lib/lib.es2021.weakref.d.ts @@ -0,0 +1,75 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface WeakRef { + readonly [Symbol.toStringTag]: "WeakRef"; + + /** + * Returns the WeakRef instance's target object, or undefined if the target object has been + * reclaimed. + */ + deref(): T | undefined; +} + +interface WeakRefConstructor { + readonly prototype: WeakRef; + + /** + * Creates a WeakRef instance for the given target object. + * @param target The target object for the WeakRef instance. + */ + new(target: T): WeakRef; +} + +declare var WeakRef: WeakRefConstructor; + +interface FinalizationRegistry { + readonly [Symbol.toStringTag]: "FinalizationRegistry"; + + /** + * Registers an object with the registry. + * @param target The target object to register. + * @param heldValue The value to pass to the finalizer for this object. This cannot be the + * target object. + * @param unregisterToken The token to pass to the unregister method to unregister the target + * object. If provided (and not undefined), this must be an object. If not provided, the target + * cannot be unregistered. + */ + register(target: object, heldValue: T, unregisterToken?: object): void; + + /** + * Unregisters an object from the registry. + * @param unregisterToken The token that was used as the unregisterToken argument when calling + * register to register the target object. + */ + unregister(unregisterToken: object): void; +} + +interface FinalizationRegistryConstructor { + readonly prototype: FinalizationRegistry; + + /** + * Creates a finalization registry with an associated cleanup callback + * @param cleanupCallback The callback to call after an object in the registry has been reclaimed. + */ + new(cleanupCallback: (heldValue: T) => void): FinalizationRegistry; +} + +declare var FinalizationRegistry: FinalizationRegistryConstructor; diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 221882e80f6d5..606c9f2012307 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -33,12 +33,12 @@ declare function eval(x: string): any; /** * Converts a string to an integer. - * @param s A string to convert into a number. - * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * @param string A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in `string`. * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. * All other strings are considered decimal. */ -declare function parseInt(s: string, radix?: number): number; +declare function parseInt(string: string, radix?: number): number; /** * Converts a string to a floating-point number. @@ -197,14 +197,14 @@ interface ObjectConstructor { * @param p The property name. * @param attributes Descriptor for the property. It can be for a data property or an accessor property. */ - defineProperty(o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType): any; + defineProperty(o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType): T; /** * Adds one or more properties to an object, and/or modifies attributes of existing properties. * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. */ - defineProperties(o: any, properties: PropertyDescriptorMap & ThisType): any; + defineProperties(o: T, properties: PropertyDescriptorMap & ThisType): T; /** * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. @@ -1093,7 +1093,7 @@ interface ReadonlyArray { */ toString(): string; /** - * Returns a string representation of an array. The elements are converted to string using their toLocalString methods. + * Returns a string representation of an array. The elements are converted to string using their toLocaleString methods. */ toLocaleString(): string; /** @@ -1227,7 +1227,7 @@ interface Array { */ toString(): string; /** - * Returns a string representation of an array. The elements are converted to string using their toLocalString methods. + * Returns a string representation of an array. The elements are converted to string using their toLocaleString methods. */ toLocaleString(): string; /** @@ -1528,7 +1528,7 @@ type Parameters any> = T extends (...args: infer P) /** * Obtain the parameters of a constructor function type in a tuple */ -type ConstructorParameters any> = T extends new (...args: infer P) => any ? P : never; +type ConstructorParameters any> = T extends abstract new (...args: infer P) => any ? P : never; /** * Obtain the return type of a function type @@ -1538,7 +1538,7 @@ type ReturnType any> = T extends (...args: any) => i /** * Obtain the return type of a constructor function type */ -type InstanceType any> = T extends new (...args: any) => infer R ? R : any; +type InstanceType any> = T extends abstract new (...args: any) => infer R ? R : any; /** * Convert string literal type to uppercase @@ -4351,8 +4351,8 @@ declare namespace Intl { interface DateTimeFormatOptions { localeMatcher?: "best fit" | "lookup"; - weekday?: "long" | "short" | "narrow"; - era?: "long" | "short" | "narrow"; + weekday?: "long" | "short" | "narrow"; + era?: "long" | "short" | "narrow"; year?: "numeric" | "2-digit"; month?: "numeric" | "2-digit" | "long" | "short" | "narrow"; day?: "numeric" | "2-digit"; diff --git a/lib/lib.esnext.d.ts b/lib/lib.esnext.d.ts index ae7aaecd7ae7a..f1a4c7e1404d8 100644 --- a/lib/lib.esnext.d.ts +++ b/lib/lib.esnext.d.ts @@ -18,8 +18,5 @@ and limitations under the License. /// -/// +/// /// -/// -/// -/// diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index 1e0472624ae41..528778ffdbebe 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -382,11 +382,6 @@ interface PushPermissionDescriptor extends PermissionDescriptor { userVisibleOnly?: boolean; } -interface PushSubscriptionChangeEventInit extends ExtendableEventInit { - newSubscription?: PushSubscription; - oldSubscription?: PushSubscription; -} - interface PushSubscriptionJSON { endpoint?: string; expirationTime?: number | null; @@ -406,7 +401,7 @@ interface QueuingStrategy { interface QueuingStrategyInit { /** * Creates a new ByteLengthQueuingStrategy with the provided high water mark. - * + * * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. */ highWaterMark: number; @@ -426,7 +421,7 @@ interface ReadableWritablePair { readable: ReadableStream; /** * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. - * + * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. */ writable: WritableStream; @@ -536,19 +531,19 @@ interface StreamPipeOptions { preventCancel?: boolean; /** * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * + * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - * + * * Errors and closures of the source and destination streams propagate as follows: - * + * * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. - * + * * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. - * + * * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - * + * * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. - * + * * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. */ preventClose?: boolean; @@ -833,7 +828,7 @@ interface CanvasFilters { interface CanvasGradient { /** * Adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset at one end of the gradient, 1.0 is the offset at the other end. - * + * * Throws an "IndexSizeError" DOMException if the offset is out of range. Throws a "SyntaxError" DOMException if the color cannot be parsed. */ addColorStop(offset: number, color: string): void; @@ -1515,15 +1510,15 @@ declare var EventSource: { interface EventTarget { /** * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. - * + * * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. - * + * * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. - * + * * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. - * + * * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. - * + * * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. */ addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; @@ -1570,7 +1565,6 @@ declare var ExtendableMessageEvent: { interface FetchEvent extends ExtendableEvent { readonly clientId: string; readonly preloadResponse: Promise; - readonly replacesClientId: string; readonly request: Request; readonly resultingClientId: string; respondWith(r: Response | Promise): void; @@ -1730,15 +1724,15 @@ interface IDBCursor { continuePrimaryKey(key: IDBValidKey, primaryKey: IDBValidKey): void; /** * Delete the record pointed at by the cursor with a new value. - * + * * If successful, request's result will be undefined. */ delete(): IDBRequest; /** * Updated the record pointed at by the cursor with a new value. - * + * * Throws a "DataError" DOMException if the effective object store uses in-line keys and the key would have changed. - * + * * If successful, request's result will be the record's key. */ update(value: any): IDBRequest; @@ -1793,13 +1787,13 @@ interface IDBDatabase extends EventTarget { close(): void; /** * Creates a new object store with the given name and options and returns a new IDBObjectStore. - * + * * Throws a "InvalidStateError" DOMException if not called within an upgrade transaction. */ createObjectStore(name: string, options?: IDBObjectStoreParameters): IDBObjectStore; /** * Deletes the object store with the given name. - * + * * Throws a "InvalidStateError" DOMException if not called within an upgrade transaction. */ deleteObjectStore(name: string): void; @@ -1822,7 +1816,7 @@ declare var IDBDatabase: { interface IDBFactory { /** * Compares two values as keys. Returns -1 if key1 precedes key2, 1 if key2 precedes key1, and 0 if the keys are equal. - * + * * Throws a "DataError" DOMException if either input is not a valid key. */ cmp(first: any, second: any): number; @@ -1856,43 +1850,43 @@ interface IDBIndex { readonly unique: boolean; /** * Retrieves the number of records matching the given key or key range in query. - * + * * If successful, request's result will be the count. */ count(key?: IDBValidKey | IDBKeyRange): IDBRequest; /** * Retrieves the value of the first record matching the given key or key range in query. - * + * * If successful, request's result will be the value, or undefined if there was no matching record. */ get(key: IDBValidKey | IDBKeyRange): IDBRequest; /** * Retrieves the values of the records matching the given key or key range in query (up to count if given). - * + * * If successful, request's result will be an Array of the values. */ getAll(query?: IDBValidKey | IDBKeyRange | null, count?: number): IDBRequest; /** * Retrieves the keys of records matching the given key or key range in query (up to count if given). - * + * * If successful, request's result will be an Array of the keys. */ getAllKeys(query?: IDBValidKey | IDBKeyRange | null, count?: number): IDBRequest; /** * Retrieves the key of the first record matching the given key or key range in query. - * + * * If successful, request's result will be the key, or undefined if there was no matching record. */ getKey(key: IDBValidKey | IDBKeyRange): IDBRequest; /** * Opens a cursor over the records matching query, ordered by direction. If query is null, all records in index are matched. - * + * * If successful, request's result will be an IDBCursorWithValue, or null if there were no matching records. */ openCursor(query?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; /** * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in index are matched. - * + * * If successful, request's result will be an IDBCursor, or null if there were no matching records. */ openKeyCursor(query?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; @@ -1972,88 +1966,88 @@ interface IDBObjectStore { readonly transaction: IDBTransaction; /** * Adds or updates a record in store with the given value and key. - * + * * If the store uses in-line keys and key is specified a "DataError" DOMException will be thrown. - * + * * If put() is used, any existing record with the key will be replaced. If add() is used, and if a record with the key already exists the request will fail, with request's error set to a "ConstraintError" DOMException. - * + * * If successful, request's result will be the record's key. */ add(value: any, key?: IDBValidKey): IDBRequest; /** * Deletes all records in store. - * + * * If successful, request's result will be undefined. */ clear(): IDBRequest; /** * Retrieves the number of records matching the given key or key range in query. - * + * * If successful, request's result will be the count. */ count(key?: IDBValidKey | IDBKeyRange): IDBRequest; /** * Creates a new index in store with the given name, keyPath and options and returns a new IDBIndex. If the keyPath and options define constraints that cannot be satisfied with the data already in store the upgrade transaction will abort with a "ConstraintError" DOMException. - * + * * Throws an "InvalidStateError" DOMException if not called within an upgrade transaction. */ createIndex(name: string, keyPath: string | string[], options?: IDBIndexParameters): IDBIndex; /** * Deletes records in store with the given key or in the given key range in query. - * + * * If successful, request's result will be undefined. */ delete(key: IDBValidKey | IDBKeyRange): IDBRequest; /** * Deletes the index in store with the given name. - * + * * Throws an "InvalidStateError" DOMException if not called within an upgrade transaction. */ deleteIndex(name: string): void; /** * Retrieves the value of the first record matching the given key or key range in query. - * + * * If successful, request's result will be the value, or undefined if there was no matching record. */ get(query: IDBValidKey | IDBKeyRange): IDBRequest; /** * Retrieves the values of the records matching the given key or key range in query (up to count if given). - * + * * If successful, request's result will be an Array of the values. */ getAll(query?: IDBValidKey | IDBKeyRange | null, count?: number): IDBRequest; /** * Retrieves the keys of records matching the given key or key range in query (up to count if given). - * + * * If successful, request's result will be an Array of the keys. */ getAllKeys(query?: IDBValidKey | IDBKeyRange | null, count?: number): IDBRequest; /** * Retrieves the key of the first record matching the given key or key range in query. - * + * * If successful, request's result will be the key, or undefined if there was no matching record. */ getKey(query: IDBValidKey | IDBKeyRange): IDBRequest; index(name: string): IDBIndex; /** * Opens a cursor over the records matching query, ordered by direction. If query is null, all records in store are matched. - * + * * If successful, request's result will be an IDBCursorWithValue pointing at the first matching record, or null if there were no matching records. */ openCursor(query?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; /** * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in store are matched. - * + * * If successful, request's result will be an IDBCursor pointing at the first matching record, or null if there were no matching records. */ openKeyCursor(query?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; /** * Adds or updates a record in store with the given value and key. - * + * * If the store uses in-line keys and key is specified a "DataError" DOMException will be thrown. - * + * * If put() is used, any existing record with the key will be replaced. If add() is used, and if a record with the key already exists the request will fail, with request's error set to a "ConstraintError" DOMException. - * + * * If successful, request's result will be the record's key. */ put(value: any, key?: IDBValidKey): IDBRequest; @@ -2299,7 +2293,7 @@ interface MessagePort extends EventTarget { close(): void; /** * Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side. - * + * * Throws a "DataCloneError" DOMException if transfer contains duplicate objects or port, or if message could not be cloned. */ postMessage(message: any, transfer: Transferable[]): void; @@ -2447,27 +2441,27 @@ interface OES_vertex_array_object { interface OffscreenCanvas extends EventTarget { /** * These attributes return the dimensions of the OffscreenCanvas object's bitmap. - * + * * They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it). */ height: number; /** * These attributes return the dimensions of the OffscreenCanvas object's bitmap. - * + * * They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it). */ width: number; /** * Returns a promise that will fulfill with a new Blob object representing a file containing the image in the OffscreenCanvas object. - * + * * The argument, if provided, is a dictionary that controls the encoding options of the image file to be created. The type field specifies the file format and has a default value of "image/png"; that type is also used if the requested type isn't supported. If the image format supports variable quality (such as "image/jpeg"), then the quality field is a number in the range 0.0 to 1.0 inclusive indicating the desired quality level for the resulting image. */ convertToBlob(options?: ImageEncodeOptions): Promise; /** * Returns an object that exposes an API for drawing on the OffscreenCanvas object. contextId specifies the desired API: "2d", "bitmaprenderer", "webgl", or "webgl2". options is handled by that API. - * + * * This specification defines the "2d" context below, which is similar but distinct from the "2d" context that is created from a canvas element. The WebGL specifications define the "webgl" and "webgl2" contexts. [WEBGL] - * + * * Returns null if the canvas has already been initialized with another context type (e.g., trying to get a "2d" context after getting a "webgl" context). */ getContext(contextId: "2d", options?: CanvasRenderingContext2DSettings): OffscreenCanvasRenderingContext2D | null; @@ -2722,16 +2716,6 @@ declare var PushSubscription: { new(): PushSubscription; }; -interface PushSubscriptionChangeEvent extends ExtendableEvent { - readonly newSubscription: PushSubscription | null; - readonly oldSubscription: PushSubscription | null; -} - -declare var PushSubscriptionChangeEvent: { - prototype: PushSubscriptionChangeEvent; - new(type: string, eventInitDict?: PushSubscriptionChangeEventInit): PushSubscriptionChangeEvent; -}; - interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; readonly userVisibleOnly: boolean; @@ -2933,7 +2917,6 @@ interface ServiceWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { "notificationclick": NotificationEvent; "notificationclose": NotificationEvent; "push": PushEvent; - "pushsubscriptionchange": PushSubscriptionChangeEvent; "sync": SyncEvent; } @@ -2948,7 +2931,6 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { onnotificationclick: ((this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any) | null; onnotificationclose: ((this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any) | null; onpush: ((this: ServiceWorkerGlobalScope, ev: PushEvent) => any) | null; - onpushsubscriptionchange: ((this: ServiceWorkerGlobalScope, ev: PushSubscriptionChangeEvent) => any) | null; onsync: ((this: ServiceWorkerGlobalScope, ev: SyncEvent) => any) | null; readonly registration: ServiceWorkerRegistration; readonly serviceWorker: ServiceWorker; @@ -3098,7 +3080,7 @@ declare var SyncManager: { interface TextDecoder extends TextDecoderCommon { /** * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. - * + * * ``` * var string = "", decoder = new TextDecoder(encoding), buffer; * while(buffer = next_chunk()) { @@ -3106,7 +3088,7 @@ interface TextDecoder extends TextDecoderCommon { * } * string += decoder.decode(); // end-of-queue * ``` - * + * * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. */ decode(input?: BufferSource, options?: TextDecodeOptions): string; @@ -3194,34 +3176,6 @@ interface TextMetrics { * Returns the measurement described below. */ readonly actualBoundingBoxRight: number; - /** - * Returns the measurement described below. - */ - readonly alphabeticBaseline: number; - /** - * Returns the measurement described below. - */ - readonly emHeightAscent: number; - /** - * Returns the measurement described below. - */ - readonly emHeightDescent: number; - /** - * Returns the measurement described below. - */ - readonly fontBoundingBoxAscent: number; - /** - * Returns the measurement described below. - */ - readonly fontBoundingBoxDescent: number; - /** - * Returns the measurement described below. - */ - readonly hangingBaseline: number; - /** - * Returns the measurement described below. - */ - readonly ideographicBaseline: number; /** * Returns the measurement described below. */ @@ -4407,7 +4361,7 @@ declare var WebGLActiveInfo: { }; /** Part of the WebGL API and represents an opaque buffer object storing data such as vertices or colors. */ -interface WebGLBuffer extends WebGLObject { +interface WebGLBuffer { } declare var WebGLBuffer: { @@ -4426,7 +4380,7 @@ declare var WebGLContextEvent: { }; /** Part of the WebGL API and represents a collection of buffers that serve as a rendering destination. */ -interface WebGLFramebuffer extends WebGLObject { +interface WebGLFramebuffer { } declare var WebGLFramebuffer: { @@ -4434,16 +4388,8 @@ declare var WebGLFramebuffer: { new(): WebGLFramebuffer; }; -interface WebGLObject { -} - -declare var WebGLObject: { - prototype: WebGLObject; - new(): WebGLObject; -}; - /** The WebGLProgram is part of the WebGL API and is a combination of two compiled WebGLShaders consisting of a vertex shader and a fragment shader (both written in GLSL). */ -interface WebGLProgram extends WebGLObject { +interface WebGLProgram { } declare var WebGLProgram: { @@ -4451,7 +4397,7 @@ declare var WebGLProgram: { new(): WebGLProgram; }; -interface WebGLQuery extends WebGLObject { +interface WebGLQuery { } declare var WebGLQuery: { @@ -4460,7 +4406,7 @@ declare var WebGLQuery: { }; /** Part of the WebGL API and represents a buffer that can contain an image, or can be source or target of an rendering operation. */ -interface WebGLRenderbuffer extends WebGLObject { +interface WebGLRenderbuffer { } declare var WebGLRenderbuffer: { @@ -5239,7 +5185,7 @@ interface WebGLRenderingContextOverloads { uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; } -interface WebGLSampler extends WebGLObject { +interface WebGLSampler { } declare var WebGLSampler: { @@ -5248,7 +5194,7 @@ declare var WebGLSampler: { }; /** The WebGLShader is part of the WebGL API and can either be a vertex or a fragment shader. A WebGLProgram requires both types of shaders. */ -interface WebGLShader extends WebGLObject { +interface WebGLShader { } declare var WebGLShader: { @@ -5268,7 +5214,7 @@ declare var WebGLShaderPrecisionFormat: { new(): WebGLShaderPrecisionFormat; }; -interface WebGLSync extends WebGLObject { +interface WebGLSync { } declare var WebGLSync: { @@ -5277,7 +5223,7 @@ declare var WebGLSync: { }; /** Part of the WebGL API and represents an opaque texture object providing storage and state for texturing operations. */ -interface WebGLTexture extends WebGLObject { +interface WebGLTexture { } declare var WebGLTexture: { @@ -5285,7 +5231,7 @@ declare var WebGLTexture: { new(): WebGLTexture; }; -interface WebGLTransformFeedback extends WebGLObject { +interface WebGLTransformFeedback { } declare var WebGLTransformFeedback: { @@ -5302,7 +5248,7 @@ declare var WebGLUniformLocation: { new(): WebGLUniformLocation; }; -interface WebGLVertexArrayObject extends WebGLObject { +interface WebGLVertexArrayObject { } declare var WebGLVertexArrayObject: { @@ -5310,7 +5256,7 @@ declare var WebGLVertexArrayObject: { new(): WebGLVertexArrayObject; }; -interface WebGLVertexArrayObjectOES extends WebGLObject { +interface WebGLVertexArrayObjectOES { } interface WebSocketEventMap { @@ -5324,13 +5270,13 @@ interface WebSocketEventMap { interface WebSocket extends EventTarget { /** * Returns a string that indicates how binary data from the WebSocket object is exposed to scripts: - * + * * Can be set, to change how binary data is returned. The default is "blob". */ binaryType: BinaryType; /** * Returns the number of bytes of application data (UTF-8 text and binary data) that have been queued using send() but not yet been transmitted to the network. - * + * * If the WebSocket connection is closed, this attribute's value will only increase with each call to the send() method. (The number does not reset to zero once the connection closes.) */ readonly bufferedAmount: number; @@ -5383,7 +5329,6 @@ declare var WebSocket: { /** This ServiceWorker API interface represents the scope of a service worker client that is a document in a browser context, controlled by an active worker. The service worker client independently selects and uses a service worker for its own loading and sub-resources. */ interface WindowClient extends Client { - readonly ancestorOrigins: ReadonlyArray; readonly focused: boolean; readonly visibilityState: VisibilityState; focus(): Promise; @@ -5506,7 +5451,6 @@ declare var WorkerLocation: { /** A subset of the Navigator interface allowed to be accessed from a Worker. Such an object is initialized for each worker and is available via the WorkerGlobalScope.navigator property obtained by calling window.self.navigator. */ interface WorkerNavigator extends NavigatorConcurrentHardware, NavigatorID, NavigatorLanguage, NavigatorOnLine, NavigatorStorage { readonly permissions: Permissions; - readonly serviceWorker: ServiceWorkerContainer; } declare var WorkerNavigator: { @@ -5569,19 +5513,19 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget { readonly response: any; /** * Returns the text response. - * + * * Throws an "InvalidStateError" DOMException if responseType is not the empty string or "text". */ readonly responseText: string; /** * Returns the response type. - * + * * Can be set to change the response type. Values are: the empty string (default), "arraybuffer", "blob", "document", "json", and "text". - * + * * When set: setting to "document" is ignored if current global object is not a Window object. - * + * * When set: throws an "InvalidStateError" DOMException if state is loading or done. - * + * * When set: throws an "InvalidAccessError" DOMException if the synchronous flag is set and current global object is a Window object. */ responseType: XMLHttpRequestResponseType; @@ -5590,7 +5534,7 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget { readonly statusText: string; /** * Can be set to a time in milliseconds. When set to a non-zero value will cause fetching to terminate after the given time has passed. When the time has passed, the request has not yet completed, and the synchronous flag is unset, a timeout event will then be dispatched, or a "TimeoutError" DOMException will be thrown otherwise (for the send() method). - * + * * When set: throws an "InvalidAccessError" DOMException if the synchronous flag is set and current global object is a Window object. */ timeout: number; @@ -5600,7 +5544,7 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget { readonly upload: XMLHttpRequestUpload; /** * True when credentials are to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. Initially false. - * + * * When set: throws an "InvalidStateError" DOMException if state is not unsent or opened, or if the send() flag is set. */ withCredentials: boolean; @@ -5612,32 +5556,32 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget { getResponseHeader(name: string): string | null; /** * Sets the request method, request URL, and synchronous flag. - * + * * Throws a "SyntaxError" DOMException if either method is not a valid HTTP method or url cannot be parsed. - * + * * Throws a "SecurityError" DOMException if method is a case-insensitive match for `CONNECT`, `TRACE`, or `TRACK`. - * + * * Throws an "InvalidAccessError" DOMException if async is false, current global object is a Window object, and the timeout attribute is not zero or the responseType attribute is not the empty string. */ open(method: string, url: string): void; open(method: string, url: string, async: boolean, username?: string | null, password?: string | null): void; /** * Acts as if the `Content-Type` header value for response is mime. (It does not actually change the header though.) - * + * * Throws an "InvalidStateError" DOMException if state is loading or done. */ overrideMimeType(mime: string): void; /** * Initiates the request. The body argument provides the request body, if any, and is ignored if the request method is GET or HEAD. - * + * * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set. */ send(body?: BodyInit | null): void; /** * Combines a header in author request headers. - * + * * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set. - * + * * Throws a "SyntaxError" DOMException if name is not a header name or if value is not a header value. */ setRequestHeader(name: string, value: string): void; @@ -5737,34 +5681,34 @@ declare namespace WebAssembly { value: any; valueOf(): any; } - + var Global: { prototype: Global; new(descriptor: GlobalDescriptor, v?: any): Global; }; - + interface Instance { readonly exports: Exports; } - + var Instance: { prototype: Instance; new(module: Module, importObject?: Imports): Instance; }; - + interface Memory { readonly buffer: ArrayBuffer; grow(delta: number): number; } - + var Memory: { prototype: Memory; new(descriptor: MemoryDescriptor): Memory; }; - + interface Module { } - + var Module: { prototype: Module; new(bytes: BufferSource): Module; @@ -5772,51 +5716,52 @@ declare namespace WebAssembly { exports(moduleObject: Module): ModuleExportDescriptor[]; imports(moduleObject: Module): ModuleImportDescriptor[]; }; - + interface Table { readonly length: number; get(index: number): Function | null; grow(delta: number): number; set(index: number, value: Function | null): void; } - + var Table: { prototype: Table; new(descriptor: TableDescriptor): Table; }; - + interface GlobalDescriptor { mutable?: boolean; value: ValueType; } - + interface MemoryDescriptor { initial: number; maximum?: number; + shared?: boolean; } - + interface ModuleExportDescriptor { kind: ImportExportKind; name: string; } - + interface ModuleImportDescriptor { kind: ImportExportKind; module: string; name: string; } - + interface TableDescriptor { element: TableKind; initial: number; maximum?: number; } - + interface WebAssemblyInstantiatedSource { instance: Instance; module: Module; } - + type ImportExportKind = "function" | "global" | "memory" | "table"; type TableKind = "anyfunc"; type ValueType = "f32" | "f64" | "i32" | "i64"; diff --git a/lib/lib.webworker.iterable.d.ts b/lib/lib.webworker.iterable.d.ts index cef75d9e6d28f..2f3bdc9361fbf 100644 --- a/lib/lib.webworker.iterable.d.ts +++ b/lib/lib.webworker.iterable.d.ts @@ -80,7 +80,7 @@ interface IDBDatabase { interface IDBObjectStore { /** * Creates a new index in store with the given name, keyPath and options and returns a new IDBIndex. If the keyPath and options define constraints that cannot be satisfied with the data already in store the upgrade transaction will abort with a "ConstraintError" DOMException. - * + * * Throws an "InvalidStateError" DOMException if not called within an upgrade transaction. */ createIndex(name: string, keyPath: string | Iterable, options?: IDBIndexParameters): IDBIndex; diff --git a/lib/pl/diagnosticMessages.generated.json b/lib/pl/diagnosticMessages.generated.json index fb5cc54f24f1b..ee8ffaafcb15e 100644 --- a/lib/pl/diagnosticMessages.generated.json +++ b/lib/pl/diagnosticMessages.generated.json @@ -199,6 +199,7 @@ "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Implementacja nie może być zadeklarowana w otaczających kontekstach.", "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "Alias importu nie może odwoływać się do deklaracji, która została wyeksportowana przy użyciu elementu „export type”.", "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "Alias importu nie może odwoływać się do deklaracji, która została zaimportowana przy użyciu elementu „import type”.", + "An_import_alias_cannot_use_import_type_1392": "Alias importu nie może używać właściwości „import type”", "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Deklaracja importu może być używana tylko w przestrzeni nazw lub module.", "An_import_declaration_cannot_have_modifiers_1191": "Deklaracja importu nie może mieć modyfikatorów.", "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Ścieżka importu nie może kończyć się rozszerzeniem „{0}”. Rozważ zaimportowanie „{1}”.", @@ -443,6 +444,7 @@ "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Domyślny eksport modułu ma nazwę prywatną „{0}” lub używa tej nazwy.", "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "Definicje następujących identyfikatorów powodują konflikt z tymi w innym pliku: {0}", "Delete_all_unused_declarations_95024": "Usuń wszystkie nieużywane deklaracje", + "Delete_all_unused_imports_95147": "Usuń wszystkie nieużywane importy", "Delete_the_outputs_of_all_projects_6365": "Usuń dane wyjściowe wszystkich projektów", "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Przestarzałe] Użyj w zastępstwie opcji „--jsxFactory”. Określ obiekt wywoływany dla elementu createElement przy określaniu jako celu emisji JSX „react”", "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Przestarzałe] Użyj w zastępstwie opcji „--outFile”. Połącz dane wyjściowe i wyemituj jako jeden plik", @@ -668,6 +670,7 @@ "Index_signatures_are_incompatible_2330": "Sygnatury indeksów są niezgodne.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Wszystkie poszczególne deklaracje w scalonej deklaracji „{0}” muszą być wyeksportowane lub lokalne.", "Infer_all_types_from_usage_95023": "Wywnioskuj wszystkie typy na podstawie użycia", + "Infer_function_return_type_95148": "Wnioskuj zwracany typ funkcji", "Infer_parameter_types_from_usage_95012": "Wnioskuj typy parametrów na podstawie użycia", "Infer_this_type_of_0_from_usage_95080": "Wnioskuj typ „this” elementu „{0}” na podstawie użycia", "Infer_type_of_0_from_usage_95011": "Wnioskuj typ elementu „{0}” na podstawie użycia", @@ -814,7 +817,6 @@ "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Literały ósemkowe są niedozwolone w inicjatorze składowych wyliczeń. Użyj składni „{0}”.", "Octal_literals_are_not_allowed_in_strict_mode_1121": "Literały ósemkowe są niedozwolone w trybie z ograniczeniami.", "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Literały ósemkowe są niedostępne, jeśli językiem docelowym jest ECMAScript 5 lub nowszy. Użyj składni „{0}”.", - "Only_ECMAScript_imports_may_use_import_type_1370": "Tylko importy modułów języka ECMAScript mogą używać aliasu „typ importu”.", "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "W instrukcji „for...in” jest dozwolona tylko pojedyncza deklaracja zmiennej.", "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "W instrukcji „for...of” jest dozwolona tylko pojedyncza deklaracja zmiennej.", "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Tylko funkcja typu void może być wywoływana za pomocą słowa kluczowego „new”.", @@ -920,9 +922,11 @@ "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Odwołania do projektu nie mogą tworzyć grafu kołowego. Wykryto cykl: {0}", "Projects_in_this_build_Colon_0_6355": "Projekty w tej kompilacji: {0}", "Projects_to_reference_6300": "Projekty do przywołania", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "Właściwość „{0}” pochodzi z sygnatury indeksu, dlatego należy uzyskiwać do niej dostęp za pomocą elementu [„{0}”].", "Property_0_does_not_exist_on_const_enum_1_2479": "Właściwość „{0}” nie istnieje w wyliczeniu ze specyfikatorem „const” „{1}”.", "Property_0_does_not_exist_on_type_1_2339": "Właściwość „{0}” nie istnieje w typie „{1}”.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "Właściwość „{0}” nie istnieje w typie „{1}”. Czy chodziło Ci o „{2}”?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "Właściwość „{0}” nie istnieje w typie „{1}”. Czy chodziło o uzyskanie dostępu do statycznego elementu członkowskiego „{2}”?", "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "Właściwość „{0}” nie istnieje w typie „{1}”. Czy chcesz zmienić bibliotekę docelową? Spróbuj zmienić opcję kompilatora `lib` na „{2}” lub nowszą.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Właściwość „{0}” nie ma inicjatora i nie jest na pewno przypisana w konstruktorze.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Dla właściwości „{0}” niejawnie określono typ „any”, ponieważ jego metoda dostępu „get” nie ma adnotacji zwracanego typu.", @@ -932,7 +936,6 @@ "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Właściwości „{0}” w typie „{1}” nie można przypisać do tej samej właściwości w typie podstawowym „{2}”.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Właściwości „{0}” w typie „{1}” nie można przypisać do typu „{2}”.", "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "Właściwość „{0}” w typie „{1}” odwołuje się do innego elementu członkowskiego, do którego nie można uzyskać dostępu z typu „{2}”.", - "Property_0_is_a_static_member_of_type_1_2576": "Właściwość „{0}” jest statyczną składową typu „{1}”.", "Property_0_is_declared_but_its_value_is_never_read_6138": "Właściwość „{0}” jest zadeklarowana, ale jej wartość nie jest nigdy odczytywana.", "Property_0_is_incompatible_with_index_signature_2530": "Właściwość „{0}” jest niezgodna z sygnaturą indeksu.", "Property_0_is_incompatible_with_rest_element_type_2573": "Właściwość „{0}” jest niezgodna z typem elementu rest.", @@ -1007,6 +1010,7 @@ "Report_errors_in_js_files_8019": "Zgłaszaj błędy w plikach js.", "Report_errors_on_unused_locals_6134": "Raportuj błędy dla nieużywanych elementów lokalnych.", "Report_errors_on_unused_parameters_6135": "Raportuj błędy dla nieużywanych parametrów.", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803": "Wymagaj, aby niezadeklarowane właściwości z sygnatur indeksów korzystały z dostępów do elementów.", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Wymagane parametry typu mogą nie być zgodne z opcjonalnymi parametrami typu.", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "Znaleziono rozwiązanie dla modułu „{0}” w pamięci podręcznej z lokalizacji „{1}”.", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Rozwiązuj elementy „keyof” tylko do nazw właściwości mających jako wartość ciągi (nie liczby czy symbole).", @@ -1146,7 +1150,7 @@ "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Pierwszym parametrem metody „then” obietnicy musi być wywołanie zwrotne.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Dla typu globalnego „JSX.{0}” nie można określić więcej niż jednej właściwości.", "The_implementation_signature_is_declared_here_2750": "Sygnatura implementacji jest zadeklarowana tutaj.", - "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "Metawłaściwość „import.meta” jest dozwolona tylko wtedy, gdy opcja „--module” ma wartość „esnext” lub „system”.", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system_1343": "Metawłaściwość „import.meta” jest dozwolona tylko wtedy, gdy opcja „--module” ma wartość „es2020”, „esnext” lub „system”.", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Wywnioskowany typ „{0}” nie może być nazwany bez odwołania do elementu „{1}”. Prawdopodobnie nie jest to przenośne. Konieczna jest adnotacja typu.", "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "Wywnioskowany typ elementu „{0}” odwołuje się do typu ze strukturą cykliczną, którego nie można serializować w prosty sposób. Wymagana jest adnotacja typu.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Wnioskowany typ „{0}” przywołuje niedostępny typ „{1}”. Adnotacja typu jest konieczna.", @@ -1216,7 +1220,7 @@ "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "Tego wyrażenia nie można wywoływać, ponieważ jest to metoda dostępu „get”. Czy chodziło Ci o użycie go bez znaków „()”?", "This_expression_is_not_constructable_2351": "Tego wyrażenia nie można skonstruować.", "This_file_already_has_a_default_export_95130": "Ten plik ma już domyślny eksport", - "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "Ten import nigdy nie jest używany jako wartość i musi używać aliasu „import type”, ponieważ opcja „importsNotUsedAsValues” jest ustawiona na wartość „error”.", + "This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set__1371": "Ten import nigdy nie jest używany jako wartość i musi używać aliasu „import type”, ponieważ opcja „importsNotUsedAsValues” jest ustawiona na wartość „error”.", "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "To jest rozszerzana deklaracja. Rozważ przeniesienie deklaracji rozszerzenia do tego samego pliku.", "This_may_be_converted_to_an_async_function_80006": "To można przekonwertować na funkcję asynchroniczną.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "Do tego modułu można odwoływać się tylko za pomocą importów/eksportów języka ECMAScript, włączając flagę „{0}” i odwołując się do jego eksportu domyślnego.", @@ -1342,6 +1346,8 @@ "Updating_output_of_project_0_6373": "Trwa aktualizowanie danych wyjściowych projektu „{0}”...", "Updating_output_timestamps_of_project_0_6359": "Trwa aktualizowanie sygnatury czasowej danych wyjściowych projektu „{0}”...", "Updating_unchanged_output_timestamps_of_project_0_6371": "Trwa aktualizowanie niezmienionych sygnatur czasowych danych wyjściowych projektu „{0}”...", + "Use_element_access_for_0_95145": "Użyj dostępu do elementu w przypadku elementu „{0}”", + "Use_element_access_for_all_undeclared_properties_95146": "Użyj dostępu do elementu w przypadku wszystkich niezadeklarowanych właściwości.", "Use_synthetic_default_member_95016": "Użyj syntetycznej składowej „default”.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Używanie ciągu w instrukcji „for...of” jest obsługiwane tylko w języku ECMAScript 5 lub nowszym.", "Using_compiler_options_of_project_reference_redirect_0_6215": "Using compiler options of project reference redirect '{0}'.", diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index 22e0d7f857e8c..d8faa2a20130d 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -501,6 +501,7 @@ declare namespace ts.server.protocol { type OrganizeImportsScope = GetCombinedCodeFixScope; interface OrganizeImportsRequestArgs { scope: OrganizeImportsScope; + skipDestructiveCodeActions?: boolean; } interface OrganizeImportsResponse extends Response { body: readonly FileCodeEdits[]; @@ -603,6 +604,41 @@ declare namespace ts.server.protocol { */ body?: string[]; } + /** + * A request to get encoded semantic classifications for a span in the file + */ + interface EncodedSemanticClassificationsRequest extends FileRequest { + arguments: EncodedSemanticClassificationsRequestArgs; + } + /** + * Arguments for EncodedSemanticClassificationsRequest request. + */ + interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { + /** + * Start position of the span. + */ + start: number; + /** + * Length of the span. + */ + length: number; + /** + * Optional parameter for the semantic highlighting response, if absent it + * defaults to "original". + */ + format?: "original" | "2020"; + } + /** The response for a EncodedSemanticClassificationsRequest */ + interface EncodedSemanticClassificationsResponse extends Response { + body?: EncodedSemanticClassificationsResponseBody; + } + /** + * Implementation response message. Gives series of text spans depending on the format ar. + */ + interface EncodedSemanticClassificationsResponseBody { + endOfLineState: EndOfLineState; + spans: number[]; + } /** * Arguments in document highlight request; include: filesToSearch, file, * line, offset. @@ -672,21 +708,36 @@ declare namespace ts.server.protocol { */ file: string; } + interface JSDocTagInfo { + /** Name of the JSDoc tag */ + name: string; + /** + * Comment text after the JSDoc tag -- the text after the tag name until the next tag or end of comment + * Display parts when UserPreferences.displayPartsForJSDoc is true, flattened to string otherwise. + */ + text?: string | SymbolDisplayPart[]; + } interface TextSpanWithContext extends TextSpan { contextStart?: Location; contextEnd?: Location; } interface FileSpanWithContext extends FileSpan, TextSpanWithContext { } + interface DefinitionInfo extends FileSpanWithContext { + /** + * When true, the file may or may not exist. + */ + unverified?: boolean; + } interface DefinitionInfoAndBoundSpan { - definitions: readonly FileSpanWithContext[]; + definitions: readonly DefinitionInfo[]; textSpan: TextSpan; } /** * Definition response message. Gives text range for definition. */ interface DefinitionResponse extends Response { - body?: FileSpanWithContext[]; + body?: DefinitionInfo[]; } interface DefinitionInfoAndBoundSpanResponse extends Response { body?: DefinitionInfoAndBoundSpan; @@ -1070,18 +1121,21 @@ declare namespace ts.server.protocol { FixedPollingInterval = "FixedPollingInterval", PriorityPollingInterval = "PriorityPollingInterval", DynamicPriorityPolling = "DynamicPriorityPolling", + FixedChunkSizePolling = "FixedChunkSizePolling", UseFsEvents = "UseFsEvents", UseFsEventsOnParentDirectory = "UseFsEventsOnParentDirectory" } const enum WatchDirectoryKind { UseFsEvents = "UseFsEvents", FixedPollingInterval = "FixedPollingInterval", - DynamicPriorityPolling = "DynamicPriorityPolling" + DynamicPriorityPolling = "DynamicPriorityPolling", + FixedChunkSizePolling = "FixedChunkSizePolling" } const enum PollingWatchKind { FixedInterval = "FixedInterval", PriorityInterval = "PriorityInterval", - DynamicPriority = "DynamicPriority" + DynamicPriority = "DynamicPriority", + FixedChunkSize = "FixedChunkSize" } interface WatchOptions { watchFile?: WatchFileKind | ts.WatchFileKind; @@ -1383,6 +1437,7 @@ declare namespace ts.server.protocol { */ interface QuickInfoRequest extends FileLocationRequest { command: CommandTypes.Quickinfo; + arguments: FileLocationRequestArgs; } /** * Body of QuickInfoResponse. @@ -1410,8 +1465,9 @@ declare namespace ts.server.protocol { displayString: string; /** * Documentation associated with symbol. + * Display parts when UserPreferences.displayPartsForJSDoc is true, flattened to string otherwise. */ - documentation: string; + documentation: string | SymbolDisplayPart[]; /** * JSDoc tags associated with symbol. */ @@ -1532,7 +1588,7 @@ declare namespace ts.server.protocol { command: CommandTypes.Formatonkey; arguments: FormatOnKeyRequestArgs; } - type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#"; + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; /** * Arguments for completions messages. */ @@ -1577,6 +1633,7 @@ declare namespace ts.server.protocol { interface CompletionEntryIdentifier { name: string; source?: string; + data?: unknown; } /** * Completion entry details request; value of command field is @@ -1601,6 +1658,11 @@ declare namespace ts.server.protocol { */ kind: string; } + /** A part of a symbol description that links from a jsdoc @link tag to a declaration */ + interface JSDocLinkDisplayPart extends SymbolDisplayPart { + /** The location of the declaration that the @link tag links to. */ + target: FileSpan; + } /** * An item found in a completion response. */ @@ -1628,6 +1690,10 @@ declare namespace ts.server.protocol { * coupled with `replacementSpan` to replace a dotted access with a bracket access. */ insertText?: string; + /** + * `insertText` should be interpreted as a snippet if true. + */ + isSnippet?: true; /** * An optional span that indicates the text to be replaced by this completion item. * If present, this span should be used instead of the default one. @@ -1643,6 +1709,10 @@ declare namespace ts.server.protocol { * Identifier (not necessarily human-readable) identifying where this completion came from. */ source?: string; + /** + * Human-readable description of the `source`. + */ + sourceDisplay?: SymbolDisplayPart[]; /** * If true, this completion should be highlighted as recommended. There will only be one of these. * This will be set when we know the user should write an expression with a certain type and that type is an enum or constructable class. @@ -1656,9 +1726,20 @@ declare namespace ts.server.protocol { isFromUncheckedFile?: true; /** * If true, this completion was for an auto-import of a module not yet in the program, but listed - * in the project package.json. + * in the project package.json. Used for telemetry reporting. */ isPackageJsonImport?: true; + /** + * If true, this completion was an auto-import-style completion of an import statement (i.e., the + * module specifier was inserted along with the imported identifier). Used for telemetry reporting. + */ + isImportStatementCompletion?: true; + /** + * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, + * that allows TS Server to look up the symbol represented by the completion item, disambiguating + * items with the same name. + */ + data?: unknown; } /** * Additional completion entry details, available on demand @@ -1693,9 +1774,13 @@ declare namespace ts.server.protocol { */ codeActions?: CodeAction[]; /** - * Human-readable description of the `source` from the CompletionEntry. + * @deprecated Use `sourceDisplay` instead. */ source?: SymbolDisplayPart[]; + /** + * Human-readable description of the `source` from the CompletionEntry. + */ + sourceDisplay?: SymbolDisplayPart[]; } /** @deprecated Prefer CompletionInfoResponse, which supports several top-level fields in addition to the array of entries. */ interface CompletionsResponse extends Response { @@ -1714,6 +1799,7 @@ declare namespace ts.server.protocol { * must be used to commit that completion entry. */ readonly optionalReplacementSpan?: TextSpan; + readonly isIncomplete?: boolean; readonly entries: readonly CompletionEntry[]; } interface CompletionDetailsResponse extends Response { @@ -2496,6 +2582,15 @@ declare namespace ts.server.protocol { * This affects lone identifier completions but not completions on the right hand side of `obj.`. */ readonly includeCompletionsForModuleExports?: boolean; + /** + * Enables auto-import-style completions on partially-typed import statements. E.g., allows + * `import write|` to be completed to `import { writeFile } from "fs"`. + */ + readonly includeCompletionsForImportStatements?: boolean; + /** + * Allows completions to be formatted with snippet text, indicated by `CompletionItem["isSnippet"]`. + */ + readonly includeCompletionsWithSnippetText?: boolean; /** * If enabled, the completion list will include completions with invalid identifier names. * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. @@ -2516,6 +2611,8 @@ declare namespace ts.server.protocol { readonly provideRefactorNotApplicableReason?: boolean; readonly allowRenameOfImportPath?: boolean; readonly includePackageJsonAutoImports?: "auto" | "on" | "off"; + readonly displayPartsForJSDoc?: boolean; + readonly generateReturnInDocTemplate?: boolean; } interface CompilerOptions { allowJs?: boolean; @@ -2623,8 +2720,36 @@ declare namespace ts.server.protocol { ES2018 = "ES2018", ES2019 = "ES2019", ES2020 = "ES2020", + ES2021 = "ES2021", ESNext = "ESNext" } + const enum ClassificationType { + comment = 1, + identifier = 2, + keyword = 3, + numericLiteral = 4, + operator = 5, + stringLiteral = 6, + regularExpressionLiteral = 7, + whiteSpace = 8, + text = 9, + punctuation = 10, + className = 11, + enumName = 12, + interfaceName = 13, + moduleName = 14, + typeParameterName = 15, + typeAliasName = 16, + parameterName = 17, + docCommentTagName = 18, + jsxOpenTagName = 19, + jsxCloseTagName = 20, + jsxSelfClosingTagName = 21, + jsxAttribute = 22, + jsxText = 23, + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25 + } } declare namespace ts.server.protocol { @@ -2730,7 +2855,13 @@ declare namespace ts.server.protocol { */ jsxAttribute = "JSX attribute", /** String literal */ - string = "string" + string = "string", + /** Jsdoc @link: in `{@link C link text}`, the before and after text "{@link " and "}" */ + link = "link", + /** Jsdoc @link: in `{@link C link text}`, the entity name "C" */ + linkName = "link name", + /** Jsdoc @link: in `{@link C link text}`, the link text "link text" */ + linkText = "link text" } export interface TypeAcquisition { @@ -2754,11 +2885,6 @@ declare namespace ts.server.protocol { scriptKind?: ScriptKind; } - interface JSDocTagInfo { - name: string; - text?: string; - } - /** * Type of objects whose values are all of the same type. * The `in` and `for-in` operators can *not* be safely used, @@ -2785,6 +2911,7 @@ declare namespace ts.server.protocol { } declare namespace ts { // these types are empty stubs for types from services and should not be used directly + export type EndOfLineState = never; export type ScriptKind = never; export type WatchFileKind = never; export type WatchDirectoryKind = never; diff --git a/lib/pt-br/diagnosticMessages.generated.json b/lib/pt-br/diagnosticMessages.generated.json index adeb412ef0c4f..80ce2712e3eb0 100644 --- a/lib/pt-br/diagnosticMessages.generated.json +++ b/lib/pt-br/diagnosticMessages.generated.json @@ -151,8 +151,8 @@ "Add_undefined_type_to_property_0_95018": "Adicionar tipo 'indefinido' à propriedade '{0}'", "Add_unknown_conversion_for_non_overlapping_types_95069": "Adicionar conversão 'unknown' para tipos sem sobreposição", "Add_unknown_to_all_conversions_of_non_overlapping_types_95070": "Adicionar 'unknown' a todas as conversões de tipos sem sobreposição", - "Add_void_to_Promise_resolved_without_a_value_95143": "Adicionar 'void' à Promessa resolvida sem um valor", - "Add_void_to_all_Promises_resolved_without_a_value_95144": "Adicionar 'void' a todas as Promessas resolvidas sem um valor", + "Add_void_to_Promise_resolved_without_a_value_95143": "Adicionar 'void' ao Promise resolvido sem um valor", + "Add_void_to_all_Promises_resolved_without_a_value_95144": "Adicionar 'void' a todos os Promises resolvidos sem um valor", "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "Adicionar um arquivo tsconfig.json ajudará a organizar projetos que contêm arquivos TypeScript e JavaScript. Saiba mais em https://aka.ms/tsconfig.", "Additional_Checks_6176": "Verificações Adicionais", "Advanced_Options_6178": "Opções Avançadas", @@ -199,6 +199,7 @@ "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Uma implementação não pode ser declarada em contextos de ambiente.", "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "Um alias de importação não pode fazer referência a uma declaração que foi exportada usando 'tipo de exportação'.", "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "Um alias de importação não pode fazer referência a uma declaração que foi importada usando 'tipo de importação'.", + "An_import_alias_cannot_use_import_type_1392": "Um alias de importação não pode usar um 'tipo de importação'", "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Uma declaração de importação só pode ser usada em um namespace ou módulo.", "An_import_declaration_cannot_have_modifiers_1191": "Uma declaração de importação não pode ter modificadores.", "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Um caminho de importação não pode terminar com uma extensão '{0}'. Considere importar '{1}'.", @@ -443,6 +444,7 @@ "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "A exportação padrão do módulo tem ou está usando o nome particular '{0}'.", "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "As definições dos seguintes identificadores estão em conflito com as de outro arquivo: {0}", "Delete_all_unused_declarations_95024": "Excluir todas as declarações não usadas", + "Delete_all_unused_imports_95147": "Excluir todas as importações não usadas", "Delete_the_outputs_of_all_projects_6365": "Excluir as saídas de todos os projetos", "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Preterido] Use '--jsxFactory' no lugar. Especifique o objeto invocado para createElement ao direcionar uma emissão de JSX 'react'", "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Preterido] Use '--outFile' no lugar. Concatene e emita uma saída para um arquivo único", @@ -668,6 +670,7 @@ "Index_signatures_are_incompatible_2330": "As assinaturas de índice são incompatíveis.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Todas as declarações individuais na declaração mesclada '{0}' devem ser exportadas ou ficar no local.", "Infer_all_types_from_usage_95023": "Inferir todos os tipos de uso", + "Infer_function_return_type_95148": "Inferir o tipo de retorno da função", "Infer_parameter_types_from_usage_95012": "Inferir tipos de parâmetro pelo uso", "Infer_this_type_of_0_from_usage_95080": "Inferir tipo 'this' de '{0}' do uso", "Infer_type_of_0_from_usage_95011": "Inferir tipo de '{0}' pelo uso", @@ -814,7 +817,6 @@ "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Literais octais não são permitidos em inicializador de membros de enumerações. Use a sintaxe '{0}'.", "Octal_literals_are_not_allowed_in_strict_mode_1121": "Literais octais não são permitidos no modo estrito.", "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Literais octais não estão disponíveis quando se tem como destino ECMAScript 5 e superiores. Use a sintaxe '{0}'.", - "Only_ECMAScript_imports_may_use_import_type_1370": "Somente importações ECMAScript podem usar 'import type'.", "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "É permitida apenas uma única declaração de variável em uma instrução 'for...in'.", "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "É permitida apenas uma única declaração de variável em uma instrução 'for...of'.", "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "Apenas uma função void pode ser chamada com a palavra-chave 'new'.", @@ -920,9 +922,11 @@ "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 a serem referenciados", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "A propriedade '{0}' vem de uma assinatura de índice, portanto, ela precisa ser acessada com ['{0}'].", "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_mean_2_2551": "A propriedade '{0}' não existe no tipo '{1}'. Você quis dizer '{2}'?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "A propriedade '{0}' não existe no tipo '{1}'. Você queria acessar o membro estático '{2}'?", "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "A propriedade '{0}' não existe no tipo '{1}'. Você precisa alterar sua biblioteca de destino? Tente alterar a opção `lib` do compilador para '{2}' ou posterior.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "A propriedade '{0}' não tem nenhum inicializador e não está definitivamente atribuída no construtor.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "A propriedade '{0}' tem implicitamente o tipo 'any' porque o acessador get não tem uma anotação de tipo de retorno.", @@ -932,7 +936,6 @@ "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "A propriedade '{0}' no tipo '{1}' não pode ser atribuída à mesma propriedade no tipo base '{2}'.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "A propriedade '{0}' no tipo '{1}' não pode ser atribuída ao tipo '{2}'.", "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "A propriedade '{0}' no tipo '{1}' se refere a um membro diferente que não pode ser acessado por meio do tipo '{2}'.", - "Property_0_is_a_static_member_of_type_1_2576": "A propriedade '{0}' é um membro estático do tipo '{1}'.", "Property_0_is_declared_but_its_value_is_never_read_6138": "A propriedade '{0}' é declarada, mas seu valor nunca é lido.", "Property_0_is_incompatible_with_index_signature_2530": "A propriedade '{0}' é incompatível com a assinatura de índice.", "Property_0_is_incompatible_with_rest_element_type_2573": "A propriedade '{0}' é incompatível com o tipo de elemento REST.", @@ -994,8 +997,8 @@ "Remove_unnecessary_await_95086": "Remover 'await' desnecessário", "Remove_unreachable_code_95050": "Remover código inacessível", "Remove_unused_declaration_for_Colon_0_90004": "Remover declaração não usada para: '{0}'", - "Remove_unused_declarations_for_Colon_0_90041": "Remover a declaração não usada de: '{0}'", - "Remove_unused_destructuring_declaration_90039": "Remover a declaração de desestruturação não usada", + "Remove_unused_declarations_for_Colon_0_90041": "Remova as declarações não usadas de: '{0}'", + "Remove_unused_destructuring_declaration_90039": "Remova a declaração de desestruturação não usada", "Remove_unused_label_95053": "Remover rótulo não utilizado", "Remove_variable_statement_90010": "Remover instrução de variável", "Replace_0_with_Promise_1_90036": "Substituir '{0}' por 'Promise<{1}>'", @@ -1007,6 +1010,7 @@ "Report_errors_in_js_files_8019": "Relatar erros em arquivos .js.", "Report_errors_on_unused_locals_6134": "Relatar erros nos locais não utilizados.", "Report_errors_on_unused_parameters_6135": "Relatar erros nos parâmetros não utilizados.", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803": "Exigir que as propriedades não declaradas de assinaturas de índice usem acessos de elemento.", "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' somente para nomes de propriedades com valores de cadeia de caracteres (sem números nem símbolos).", @@ -1113,7 +1117,7 @@ "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337": "As chamadas super não são permitidas fora dos construtores ou em funções aninhadas dentro dos construtores.", "Suppress_excess_property_checks_for_object_literals_6072": "Verificações de propriedade de excesso de compactação para literais de objeto.", "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055": "Suprimir erros de noImplicitAny para objetos de indexação sem assinaturas de índice.", - "Switch_each_misused_0_to_1_95138": "Mudar cada '{0}' usado incorretamente para '{1}'", + "Switch_each_misused_0_to_1_95138": "Mude cada '{0}' usado incorretamente para '{1}'", "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470": "A referência 'symbol' não se refere ao objeto global do construtor Symbol.", "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6228": "Chame sincronicamente retornos de chamadas e atualize o estado de observadores de diretório em plataformas que não têm suporte à observação recursiva nativamente.", "Syntax_Colon_0_6023": "Sintaxe: {0}", @@ -1146,7 +1150,7 @@ "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "O primeiro parâmetro do método 'then' de uma promessa deve ser um retorno de chamada.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "O tipo global 'JSX.{0}' não pode ter mais de uma propriedade.", "The_implementation_signature_is_declared_here_2750": "A assinatura de implementação é declarada aqui.", - "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "A metapropriedade 'import.meta' só é permitida quando a opção '--module' é 'esnext' ou 'system'.", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system_1343": "A metapropriedade 'import.meta' só é permitida quando a opção '--module' é 'es2020', 'esnext' ou 'system'.", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "O tipo inferido de '{0}' não pode ser nomeado sem uma referência a '{1}'. Isso provavelmente não é portátil. Uma anotação de tipo é necessária.", "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "O tipo inferido '{0}' faz referência a um tipo com uma estrutura cíclica que não pode ser serializada trivialmente. Uma anotação de tipo é necessária.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "O tipo inferido de '{0}' faz referência a um tipo '{1}' inacessível. Uma anotação de tipo é necessária.", @@ -1216,7 +1220,7 @@ "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "Esta expressão não pode ser chamada porque é um acessador 'get'. Você quis usá-la sem '()'?", "This_expression_is_not_constructable_2351": "Essa expressão não pode ser construída.", "This_file_already_has_a_default_export_95130": "Este arquivo já tem uma exportação padrão", - "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "Essa importação nunca é usada como um valor e deve usar 'tipo de importação' porque 'importsNotUsedAsValues' está definido como 'erro'.", + "This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set__1371": "Esta importação nunca é usada como um valor e precisa usar um 'tipo de importação' porque 'importsNotUsedAsValues' está definido como 'erro'.", "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Esta é a declaração que está sendo aumentada. Considere mover a declaração em aumento para o mesmo arquivo.", "This_may_be_converted_to_an_async_function_80006": "Isso pode ser convertido em uma função assíncrona.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "Esse módulo só pode ser referenciado com importações/exportações de ECMAScript ligando o sinalizador '{0}' e referenciando sua exportação padrão.", @@ -1342,6 +1346,8 @@ "Updating_output_of_project_0_6373": "Atualizando a saída do projeto '{0}'...", "Updating_output_timestamps_of_project_0_6359": "Atualizando os carimbos de data/hora de saída do projeto '{0}'...", "Updating_unchanged_output_timestamps_of_project_0_6371": "Atualizando os carimbos de data/hora de saída inalterados do projeto '{0}'...", + "Use_element_access_for_0_95145": "Usar o acesso de elemento para '{0}'", + "Use_element_access_for_all_undeclared_properties_95146": "Usar o acesso de elemento para todas as propriedades não declaradas.", "Use_synthetic_default_member_95016": "Use o membro sintético 'padrão'.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Há suporte para o uso de uma cadeia de caracteres em uma instrução 'for...of' somente no ECMAScript 5 e superior.", "Using_compiler_options_of_project_reference_redirect_0_6215": "Usando as opções do compilador de redirecionamento de referência do projeto '{0}'.", diff --git a/lib/ru/diagnosticMessages.generated.json b/lib/ru/diagnosticMessages.generated.json index f946a660bd6ab..438b21a22360f 100644 --- a/lib/ru/diagnosticMessages.generated.json +++ b/lib/ru/diagnosticMessages.generated.json @@ -199,6 +199,7 @@ "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Реализацию невозможно объявить в окружающих контекстах.", "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "Псевдоним импорта не может ссылаться на объявление, экспортированное с помощью \"export type\".", "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "Псевдоним импорта не может ссылаться на объявление, импортированное с помощью \"import type\".", + "An_import_alias_cannot_use_import_type_1392": "Псевдоним импорта не может использовать \"import type\".", "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "Объявление импорта может быть использовано только в пространстве имен или модуле.", "An_import_declaration_cannot_have_modifiers_1191": "Объявление импорта не может иметь модификаторы.", "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Путь импорта не может заканчиваться расширением \"{0}\". Попробуйте импортировать \"{1}\".", @@ -443,6 +444,7 @@ "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Экспорт модуля по умолчанию использует или имеет закрытое имя \"{0}\".", "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "Определения следующих идентификаторов конфликтуют с определениями в другом файле: {0}", "Delete_all_unused_declarations_95024": "Удалить все неиспользуемые объявления", + "Delete_all_unused_imports_95147": "Удаление всех неиспользуемых импортов", "Delete_the_outputs_of_all_projects_6365": "Удалить выходные данные всех проектов", "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Устарело.] Используйте --jsxFactory. Укажите объект, вызываемый для createElement при целевом порождении JSX react", "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Устарело.] Используйте --outFile. Сцепление и порождение выходных данных в одном файле", @@ -668,6 +670,7 @@ "Index_signatures_are_incompatible_2330": "Сигнатуры индекса несовместимы.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "Все отдельные объявления в объединенном объявлении \"{0}\" должны быть экспортированными или локальными.", "Infer_all_types_from_usage_95023": "Вывести все типы исходя из использования", + "Infer_function_return_type_95148": "Вывод типа возвращаемого значения функции", "Infer_parameter_types_from_usage_95012": "Выведите типы параметров на основании их использования", "Infer_this_type_of_0_from_usage_95080": "Определить тип \"this\" для \"{0}\" из использования", "Infer_type_of_0_from_usage_95011": "Выведите тип \"{0}\" на основании его использования", @@ -814,7 +817,6 @@ "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Восьмеричные литералы запрещены в инициализаторах членов перечисления. Используйте синтаксис \"{0}\".", "Octal_literals_are_not_allowed_in_strict_mode_1121": "Восьмеричные литералы запрещено использовать в строгом режиме.", "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "Восьмеричные литералы недоступны при выборе целевой платформы ECMAScript 5 и более поздних. Используйте синтаксис \"{0}\".", - "Only_ECMAScript_imports_may_use_import_type_1370": "Только импорты ECMAScript могут использовать \"import type\".", "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "В операторе for...in разрешено только одно объявление переменной.", "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "В операторе for...of разрешено только одно объявление переменной.", "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "С помощью ключевого слова new можно вызвать только функцию void.", @@ -920,9 +922,11 @@ "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": "Проекты для ссылки", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "Свойство \"{0}\" поступает из сигнатуры индекса, поэтому доступ к нему должен осуществляться с помощью [\"{0}\"].", "Property_0_does_not_exist_on_const_enum_1_2479": "Свойство \"{0}\" не существует в перечислении const \"{1}\".", "Property_0_does_not_exist_on_type_1_2339": "Свойство \"{0}\" не существует в типе \"{1}\".", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "Свойство \"{0}\" не существует в типе \"{1}\". Вы имели в виду \"{2}\"?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "Свойство \"{0}\" отсутствует в типе \"{1}\". Вы хотели обратиться к статическому элементу \"{2}\"?", "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "Свойство \"{0}\" не существует в типе \"{1}\". Вы хотите изменить целевую библиотеку? Попробуйте изменить параметр компилятора \"lib\" на \"{2}\" или более поздней версии.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Свойство \"{0}\" не имеет инициализатора, и ему не гарантировано присваивание в конструкторе.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Свойство \"{0}\" неявно имеет тип \"все\", так как для его метода доступа get не задана заметка с типом возвращаемого значения.", @@ -932,7 +936,6 @@ "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Свойство \"{0}\" в типе \"{1}\" невозможно присвоить тому же свойству в базовом типе \"{2}\".", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Свойство \"{0}\" в типе \"{1}\" не может быть присвоено типу \"{2}\".", "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "Свойство \"{0}\" в типе \"{1}\" ссылается на другой член, к которому невозможно обратиться из типа \"{2}\".", - "Property_0_is_a_static_member_of_type_1_2576": "Свойство \"{0}\" является статическим элементом типа \"{1}\".", "Property_0_is_declared_but_its_value_is_never_read_6138": "Свойство \"{0}\" объявлено, но его значение не было прочитано.", "Property_0_is_incompatible_with_index_signature_2530": "Свойство \"{0}\" несовместимо с сигнатурой индекса.", "Property_0_is_incompatible_with_rest_element_type_2573": "Свойство \"{0}\" несовместимо с типом элементов rest.", @@ -1007,6 +1010,7 @@ "Report_errors_in_js_files_8019": "Сообщать об ошибках в JS-файлах.", "Report_errors_on_unused_locals_6134": "Сообщать об ошибках в неиспользованных локальных переменных.", "Report_errors_on_unused_parameters_6135": "Сообщать об ошибках в неиспользованных параметрах.", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803": "Требовать необъявленные свойства из сигнатур индекса для использования доступа к элементам.", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Обязательные параметры типа не могут следовать за необязательными параметрами типа.", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "Разрешение для модуля \"{0}\" найдено в кэше из расположения \"{1}\".", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Разрешать \"keyof\" только в имена свойств со строковым значением (не числа и не символы).", @@ -1146,7 +1150,7 @@ "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Первым параметром метода then класса promise должен быть обратный вызов.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Глобальный тип \"JSX.{0}\" не может иметь больше одного свойства.", "The_implementation_signature_is_declared_here_2750": "Здесь объявлена сигнатура реализации.", - "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "Метасвойство \"import.meta\" разрешено, только если параметр \"--module\" имеет значение \"esnext\" или \"system\".", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system_1343": "Метасвойство \"import.meta\" разрешено, только если параметр \"--module\" имеет значение \"es2020\", \"esnext\" или \"system\".", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Выводимому типу \"{0}\" невозможно присвоить имя без ссылки на \"{1}\". Вероятно, оно не является переносимым. Требуется заметка с типом.", "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "Выводимый тип \"{0}\" ссылается на тип с циклической структурой, которая не может быть элементарно сериализована. Требуется заметка с типом.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Выведенный тип \"{0}\" ссылается на недоступный тип \"{1}\". Требуется аннотация типа.", @@ -1216,7 +1220,7 @@ "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "Это выражение не может быть вызвано, так как оно является методом доступа get. Вы хотели использовать его без \"()\"?", "This_expression_is_not_constructable_2351": "Это выражение не может быть построено.", "This_file_already_has_a_default_export_95130": "Этот файл уже имеет экспорт по умолчанию.", - "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "Этот импорт никогда не используется в качестве значения и должен использовать \"import type\", так как для \"importsNotUsedAsValues\" задано значение \"error\".", + "This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set__1371": "Этот импорт никогда не используется в качестве значения и должен использовать \"import type\", так как для \"importsNotUsedAsValues\" задано значение \"error\".", "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Это объявление дополняется другим объявлением. Попробуйте переместить дополняющее объявление в тот же файл.", "This_may_be_converted_to_an_async_function_80006": "Это можно преобразовать в асинхронную функцию.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "На этот модуль можно ссылаться только с помощью импортов/экспортов ECMAScript, включив флаг \"{0}\" и сославшись на его экспорт по умолчанию.", @@ -1342,6 +1346,8 @@ "Updating_output_of_project_0_6373": "Обновление выходных данных проекта \"{0}\"...", "Updating_output_timestamps_of_project_0_6359": "Обновление меток времени в выходных данных проекта \"{0}\"...", "Updating_unchanged_output_timestamps_of_project_0_6371": "Обновление меток времени в неизменившихся выходных данных проекта \"{0}\"...", + "Use_element_access_for_0_95145": "Использовать доступ к элементам для \"{0}\".", + "Use_element_access_for_all_undeclared_properties_95146": "Использовать доступ к элементам для всех необъявленных свойств.", "Use_synthetic_default_member_95016": "Используйте искусственный элемент \"default\".", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Использование строки для оператора for...of поддерживается только в ECMAScript 5 и более поздних версиях.", "Using_compiler_options_of_project_reference_redirect_0_6215": "Использование параметров компилятора для перенаправления ссылки на проект \"{0}\".", diff --git a/lib/tr/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json index 2b206ac61e70a..fdc2cd6fd8f9c 100644 --- a/lib/tr/diagnosticMessages.generated.json +++ b/lib/tr/diagnosticMessages.generated.json @@ -199,6 +199,7 @@ "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "Uygulama, çevresel bağlamda bildirilemez.", "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "İçeri aktarma diğer adı, 'export type' kullanılarak dışarı aktarılan bir bildirime başvuramaz.", "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "İçeri aktarma diğer adı, 'import type' kullanılarak içeri aktarılan bir bildirime başvuramaz.", + "An_import_alias_cannot_use_import_type_1392": "İçeri aktarma diğer adı, 'import type' kullanamaz", "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "İçeri aktarma bildirimi yalnızca bir ad alanında veya modülde kullanılabilir.", "An_import_declaration_cannot_have_modifiers_1191": "İçeri aktarma bildirimi, değiştiricilere sahip olamaz.", "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "İçeri aktarma yolu '{0}' uzantısıyla bitemez. Bunun yerine '{1}' öğesini içeri aktarmayı deneyin.", @@ -443,6 +444,7 @@ "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.", "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "Şu tanımlayıcıların tanımları başka bir dosyadaki tanımlarla çakışıyor: {0}", "Delete_all_unused_declarations_95024": "Kullanılmayan tüm bildirimleri sil", + "Delete_all_unused_imports_95147": "Kullanılmayan tüm içeri aktarmaları sil", "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", @@ -668,6 +670,7 @@ "Index_signatures_are_incompatible_2330": "Dizin imzaları uyumsuz.", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "'{0}' birleştirilmiş bildirimindeki bildirimlerin tümü dışarı aktarılmış veya yerel olmalıdır.", "Infer_all_types_from_usage_95023": "Tüm türleri kullanımdan çıkar", + "Infer_function_return_type_95148": "İşlev dönüş türünü çıkarsa", "Infer_parameter_types_from_usage_95012": "Parametre türleri için kullanımdan çıkarım yap", "Infer_this_type_of_0_from_usage_95080": "Kullanımdan '{0}' öğesinin 'this' türünü çıkarsa", "Infer_type_of_0_from_usage_95011": "'{0}' türü için kullanımdan çıkarım yap", @@ -814,7 +817,6 @@ "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "Sabit listesi üyelerinin başlatıcısında sekizlik sabit değerlere izin verilmez. '{0}' söz dizimini kullanın.", "Octal_literals_are_not_allowed_in_strict_mode_1121": "Katı modda sekizlik sabit değerlere izin verilmez.", "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "ECMAScript 5 ve üzeri hedeflenirken sekizlik sabit değerler kullanılamaz. '{0}' söz dizimini kullanın.", - "Only_ECMAScript_imports_may_use_import_type_1370": "Yalnızca ECMAScript içeri aktarma işlemleri 'import type' kullanabilir.", "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "'for...in' deyiminde yalnızca tek bir değişken bildirimine izin verilir.", "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "'for...of' deyiminde yalnızca tek bir değişken bildirimine izin verilir.", "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "'new' anahtar sözcüğüyle yalnızca void işlevi çağrılabilir.", @@ -920,9 +922,11 @@ "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Proje başvuruları döngüsel bir grafik formu oluşturamaz. Döngü tespit edildi: {0}", "Projects_in_this_build_Colon_0_6355": "Bu derlemedeki projeler: {0}", "Projects_to_reference_6300": "Başvurulacak projeler", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "'{0}' özelliği bir dizin imzasından geldiğinden ['{0}'] ile erişilmelidir.", "Property_0_does_not_exist_on_const_enum_1_2479": "'{0}' özelliği, '{1}' 'const' sabit listesi üzerinde değil.", "Property_0_does_not_exist_on_type_1_2339": "'{0}' özelliği, '{1}' türünde değil.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "'{0}' özelliği '{1}' türünde yok. Bunu mu demek istediniz: '{2}'?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "'{0}' özelliği '{1}' türünde yok. Bunun yerine '{2}' statik üyesine erişmek mi istediniz?", "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "'{0}' özelliği '{1}' türünde yok. Hedef kitaplığınızı değiştirmeniz mi gerekiyor? `lib` derleyici seçeneğini '{2}' veya üzeri olarak değiştirmeyi deneyin.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "'{0}' özelliği başlatıcı içermiyor ve oluşturucuda kesin olarak atanmamış.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "'{0}' özelliği, get erişimcisinin dönüş türü ek açıklaması olmadığı için örtük olarak 'any' türü içeriyor.", @@ -932,7 +936,6 @@ "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "'{1}' türündeki '{0}' özelliği, '{2}' temel türündeki aynı özelliğe atanamaz.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "'{1}' türündeki '{0}' özelliği, '{2}' türüne atanamaz.", "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "'{1}' türündeki '{0}' özelliği, '{2}' türünün içinden erişilemeyen farklı bir üyeye başvuruyor.", - "Property_0_is_a_static_member_of_type_1_2576": "'{0}' özelliği, '{1}' türünde statik bir üye.", "Property_0_is_declared_but_its_value_is_never_read_6138": "'{0}' özelliği bildirildi ancak değeri hiç okunmadı.", "Property_0_is_incompatible_with_index_signature_2530": "'{0}' özelliği, dizin imzasıyla uyumsuz.", "Property_0_is_incompatible_with_rest_element_type_2573": "'{0}' özelliği REST öğesi türüyle uyumsuz.", @@ -1007,6 +1010,7 @@ "Report_errors_in_js_files_8019": ".js dosyalarındaki hataları bildirin.", "Report_errors_on_unused_locals_6134": "Kullanılmayan yerel öğelerdeki hataları bildirin.", "Report_errors_on_unused_parameters_6135": "Kullanılmayan parametrelerdeki hataları bildirin.", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803": "Öğe erişimlerini kullanmak için dizin imzalarından bildirilmemiş özellikler gerektirin.", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Gerekli tür parametreleri, isteğe bağlı tür parametrelerini takip edemez.", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "'{0}' modülünün çözümü '{1}' konumundaki önbellekte bulundu.", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "'Keyof' değerini yalnızca dize değerli özellik adlarına (sayılar veya simgeler olmadan) çözümleyin.", @@ -1216,7 +1220,7 @@ "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "Bu ifade 'get' erişimcisi olduğundan çağrılamaz. Bunu '()' olmadan mı kullanmak istiyorsunuz?", "This_expression_is_not_constructable_2351": "Bu ifade oluşturulabilir değil.", "This_file_already_has_a_default_export_95130": "Bu dosyanın zaten varsayılan bir dışarı aktarması var", - "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "'importsNotUsedAsValues', 'error' olarak ayarlandığından bu içeri aktarma hiçbir zaman bir değer olarak kullanılmaz ve 'import type' kullanmalıdır.", + "This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set__1371": "'importsNotUsedAsValues' 'error' olarak ayarlandığından, bu içeri aktarma hiçbir zaman değer olarak kullanılmaz ve 'import type' kullanmalıdır.", "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Bu, genişletilmekte olan bildirimdir. Genişleten bildirimi aynı dosyaya taşımayı düşünün.", "This_may_be_converted_to_an_async_function_80006": "Bu, asenkron bir işleve dönüştürülebilir.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "Bu modüle yalnızca '{0}' bayrağını açıp modülün varsayılan dışarı aktarma işlemine başvurarak ECMAScript içeri/dışarı aktarma işlemleri ile başvurulabilir.", @@ -1342,6 +1346,8 @@ "Updating_output_of_project_0_6373": "'{0}' projesinin çıkışı güncelleştiriliyor...", "Updating_output_timestamps_of_project_0_6359": "'{0}' projesinin çıkış zaman damgaları güncelleştiriliyor...", "Updating_unchanged_output_timestamps_of_project_0_6371": "'{0}' projesinin değiştirilmemiş çıkış zaman damgaları güncelleştiriliyor...", + "Use_element_access_for_0_95145": "'{0}' için öğe erişimi kullan", + "Use_element_access_for_all_undeclared_properties_95146": "Tüm bildirilmemiş özellikler için öğe erişimi kullanın.", "Use_synthetic_default_member_95016": "Yapay 'default' üyesini kullanın.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "'for...of' deyiminde dize kullanma yalnızca ECMAScript 5 veya üzerinde desteklenir.", "Using_compiler_options_of_project_reference_redirect_0_6215": "'{0}' proje başvurusu yeniden yönlendirmesinin derleyici seçenekleri kullanılıyor.", diff --git a/lib/tsc.js b/lib/tsc.js index f32c6225a899a..83f54758acd6c 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -64,8 +64,8 @@ var __generator = (this && this.__generator) || function (thisArg, body) { }; var ts; (function (ts) { - ts.versionMajorMinor = "4.2"; - ts.version = ts.versionMajorMinor + ".0-dev"; + ts.versionMajorMinor = "4.3"; + ts.version = "4.3.2"; var NativeCollections; (function (NativeCollections) { function tryGetNativeMap() { @@ -2005,6 +2005,8 @@ var ts; } } Debug.assertMissingNode = assertMissingNode; + function type(_value) { } + Debug.type = type; function getFunctionName(func) { if (typeof func !== "function") { return ""; @@ -2246,11 +2248,11 @@ var ts; this.objectFlags & 8 ? "TupleType" : this.objectFlags & 16 ? "AnonymousType" : this.objectFlags & 32 ? "MappedType" : - this.objectFlags & 2048 ? "ReverseMappedType" : + this.objectFlags & 1024 ? "ReverseMappedType" : this.objectFlags & 256 ? "EvolvingArrayType" : "ObjectType" : "Type"; - var remainingObjectFlags = this.flags & 524288 ? this.objectFlags & ~2367 : 0; + var remainingObjectFlags = this.flags & 524288 ? this.objectFlags & ~1343 : 0; return "" + typeHeader + (this.symbol ? " '" + ts.symbolName(this.symbol) + "'" : "") + (remainingObjectFlags ? " (" + formatObjectFlags(remainingObjectFlags) + ")" : ""); } }, @@ -2708,40 +2710,41 @@ var ts; typeof PerformanceObserver === "function" && hasRequiredAPI(performance, PerformanceObserver)) { return { + shouldWriteNativeEvents: true, performance: performance, PerformanceObserver: PerformanceObserver }; } } function tryGetNodePerformanceHooks() { - if (typeof module === "object" && typeof require === "function") { + if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof module === "object" && typeof require === "function") { try { - var _a = require("perf_hooks"), performance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; - if (hasRequiredAPI(performance_1, PerformanceObserver_1)) { + var performance_1; + var _a = require("perf_hooks"), nodePerformance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; + if (hasRequiredAPI(nodePerformance_1, PerformanceObserver_1)) { + performance_1 = nodePerformance_1; var version_1 = new ts.Version(process.versions.node); var range = new ts.VersionRange("<12.16.3 || 13 <13.13"); if (range.test(version_1)) { - return { - performance: { - get timeOrigin() { return performance_1.timeOrigin; }, - now: function () { return performance_1.now(); }, - mark: function (name) { return performance_1.mark(name); }, - measure: function (name, start, end) { - if (start === void 0) { start = "nodeStart"; } - if (end === undefined) { - end = "__performance.measure-fix__"; - performance_1.mark(end); - } - performance_1.measure(name, start, end); - if (end === "__performance.measure-fix__") { - performance_1.clearMarks("__performance.measure-fix__"); - } + performance_1 = { + get timeOrigin() { return nodePerformance_1.timeOrigin; }, + now: function () { return nodePerformance_1.now(); }, + mark: function (name) { return nodePerformance_1.mark(name); }, + measure: function (name, start, end) { + if (start === void 0) { start = "nodeStart"; } + if (end === undefined) { + end = "__performance.measure-fix__"; + nodePerformance_1.mark(end); } - }, - PerformanceObserver: PerformanceObserver_1 + nodePerformance_1.measure(name, start, end); + if (end === "__performance.measure-fix__") { + nodePerformance_1.clearMarks("__performance.measure-fix__"); + } + } }; } return { + shouldWriteNativeEvents: false, performance: performance_1, PerformanceObserver: PerformanceObserver_1 }; @@ -2766,7 +2769,6 @@ var ts; var performance; (function (performance) { var perfHooks; - var perfObserver; var performanceImpl; function createTimerIf(condition, measureName, startMarkName, endMarkName) { return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer; @@ -2795,14 +2797,30 @@ var ts; } performance.createTimer = createTimer; performance.nullTimer = { enter: ts.noop, exit: ts.noop }; + var enabled = false; + var timeorigin = ts.timestamp(); + var marks = new ts.Map(); var counts = new ts.Map(); var durations = new ts.Map(); function mark(markName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + var _a; + if (enabled) { + var count = (_a = counts.get(markName)) !== null && _a !== void 0 ? _a : 0; + counts.set(markName, count + 1); + marks.set(markName, ts.timestamp()); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + } } performance.mark = mark; function measure(measureName, startMarkName, endMarkName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + var _a, _b; + if (enabled) { + var end = (_a = (endMarkName !== undefined ? marks.get(endMarkName) : undefined)) !== null && _a !== void 0 ? _a : ts.timestamp(); + var start = (_b = (startMarkName !== undefined ? marks.get(startMarkName) : undefined)) !== null && _b !== void 0 ? _b : timeorigin; + var previousDuration = durations.get(measureName) || 0; + durations.set(measureName, previousDuration + (end - start)); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + } } performance.measure = measure; function getCount(markName) { @@ -2818,38 +2836,35 @@ var ts; } performance.forEachMeasure = forEachMeasure; function isEnabled() { - return !!performanceImpl; + return enabled; } performance.isEnabled = isEnabled; - function enable() { - if (!performanceImpl) { + function enable(system) { + var _a; + if (system === void 0) { system = ts.sys; } + if (!enabled) { + enabled = true; perfHooks || (perfHooks = ts.tryGetNativePerformanceHooks()); - if (!perfHooks) - return false; - perfObserver || (perfObserver = new perfHooks.PerformanceObserver(updateStatisticsFromList)); - perfObserver.observe({ entryTypes: ["mark", "measure"] }); - performanceImpl = perfHooks.performance; + if (perfHooks) { + timeorigin = perfHooks.performance.timeOrigin; + if (perfHooks.shouldWriteNativeEvents || ((_a = system === null || system === void 0 ? void 0 : system.cpuProfilingEnabled) === null || _a === void 0 ? void 0 : _a.call(system)) || (system === null || system === void 0 ? void 0 : system.debugMode)) { + performanceImpl = perfHooks.performance; + } + } } return true; } performance.enable = enable; function disable() { - perfObserver === null || perfObserver === void 0 ? void 0 : perfObserver.disconnect(); - performanceImpl = undefined; - counts.clear(); - durations.clear(); - } - performance.disable = disable; - function updateStatisticsFromList(list) { - for (var _i = 0, _a = list.getEntriesByType("mark"); _i < _a.length; _i++) { - var mark_1 = _a[_i]; - counts.set(mark_1.name, (counts.get(mark_1.name) || 0) + 1); - } - for (var _b = 0, _c = list.getEntriesByType("measure"); _b < _c.length; _b++) { - var measure_1 = _c[_b]; - durations.set(measure_1.name, (durations.get(measure_1.name) || 0) + measure_1.duration); + if (enabled) { + marks.clear(); + counts.clear(); + durations.clear(); + performanceImpl = undefined; + enabled = false; } } + performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); var ts; @@ -2889,38 +2904,37 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var tracing; - (function (tracing) { + var tracingEnabled; + (function (tracingEnabled) { var fs; var traceCount = 0; - var traceFd; + var traceFd = 0; var mode; + var typeCatalog = []; var legendPath; var legend = []; ; function startTracing(tracingMode, traceDir, configFilePath) { - ts.Debug.assert(!traceFd, "Tracing already started"); + ts.Debug.assert(!ts.tracing, "Tracing already started"); if (fs === undefined) { try { fs = require("fs"); } - catch (_a) { - fs = false; + catch (e) { + throw new Error("tracing requires having fs\n(original error: " + (e.message || e) + ")"); } } - if (!fs) { - return; - } mode = tracingMode; + typeCatalog.length = 0; if (legendPath === undefined) { legendPath = ts.combinePaths(traceDir, "legend.json"); } if (!fs.existsSync(traceDir)) { fs.mkdirSync(traceDir, { recursive: true }); } - var countPart = mode === 1 ? "." + process.pid + "-" + ++traceCount : - mode === 2 ? "." + process.pid : - ""; + var countPart = mode === "build" ? "." + process.pid + "-" + ++traceCount + : mode === "server" ? "." + process.pid + : ""; var tracePath = ts.combinePaths(traceDir, "trace" + countPart + ".json"); var typesPath = ts.combinePaths(traceDir, "types" + countPart + ".json"); legend.push({ @@ -2929,83 +2943,73 @@ var ts; typesPath: typesPath, }); traceFd = fs.openSync(tracePath, "w"); + ts.tracing = tracingEnabled; var meta = { cat: "__metadata", ph: "M", ts: 1000 * ts.timestamp(), pid: 1, tid: 1 }; fs.writeSync(traceFd, "[\n" + [__assign({ name: "process_name", args: { name: "tsc" } }, meta), __assign({ name: "thread_name", args: { name: "Main" } }, meta), __assign(__assign({ name: "TracingStartedInBrowser" }, meta), { cat: "disabled-by-default-devtools.timeline" })] .map(function (v) { return JSON.stringify(v); }).join(",\n")); } - tracing.startTracing = startTracing; - function stopTracing(typeCatalog) { - if (!traceFd) { - ts.Debug.assert(!fs, "Tracing is not in progress"); - return; - } - ts.Debug.assert(fs); - ts.Debug.assert(!!typeCatalog === (mode !== 2)); + tracingEnabled.startTracing = startTracing; + function stopTracing() { + ts.Debug.assert(ts.tracing, "Tracing is not in progress"); + ts.Debug.assert(!!typeCatalog.length === (mode !== "server")); fs.writeSync(traceFd, "\n]\n"); fs.closeSync(traceFd); - traceFd = undefined; - if (typeCatalog) { + ts.tracing = undefined; + if (typeCatalog.length) { dumpTypes(typeCatalog); } else { legend[legend.length - 1].typesPath = undefined; } } - tracing.stopTracing = stopTracing; - function isTracing() { - return !!traceFd; + tracingEnabled.stopTracing = stopTracing; + function recordType(type) { + if (mode !== "server") { + typeCatalog.push(type); + } } - tracing.isTracing = isTracing; + tracingEnabled.recordType = recordType; function instant(phase, name, args) { - if (!traceFd) - return; writeEvent("I", phase, name, args, "\"s\":\"g\""); } - tracing.instant = instant; + tracingEnabled.instant = instant; var eventStack = []; function push(phase, name, args, separateBeginAndEnd) { if (separateBeginAndEnd === void 0) { separateBeginAndEnd = false; } - if (!traceFd) - return; if (separateBeginAndEnd) { writeEvent("B", phase, name, args); } eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } - tracing.push = push; + tracingEnabled.push = push; function pop() { - if (!traceFd) - return; ts.Debug.assert(eventStack.length > 0); writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); eventStack.length--; } - tracing.pop = pop; + tracingEnabled.pop = pop; function popAll() { - if (!traceFd) - return; var endTime = 1000 * ts.timestamp(); for (var i = eventStack.length - 1; i >= 0; i--) { writeStackEvent(i, endTime); } eventStack.length = 0; } - tracing.popAll = popAll; + tracingEnabled.popAll = popAll; + var sampleInterval = 1000 * 10; function writeStackEvent(index, endTime) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { writeEvent("E", phase, name, args, undefined, endTime); } - else { + else if (sampleInterval - (time % sampleInterval) <= endTime - time) { writeEvent("X", phase, name, args, "\"dur\":" + (endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { if (time === void 0) { time = 1000 * ts.timestamp(); } - ts.Debug.assert(traceFd); - ts.Debug.assert(fs); - if (mode === 2 && phase === "checkTypes") + if (mode === "server" && phase === "checkTypes") return; ts.performance.mark("beginTracing"); fs.writeSync(traceFd, ",\n{\"pid\":1,\"tid\":1,\"ph\":\"" + eventType + "\",\"cat\":\"" + phase + "\",\"ts\":" + time + ",\"name\":\"" + name + "\""); @@ -3017,15 +3021,24 @@ var ts; ts.performance.mark("endTracing"); ts.performance.measure("Tracing", "beginTracing", "endTracing"); } - function indexFromOne(lc) { - return { - line: lc.line + 1, - character: lc.character + 1, - }; + function getLocation(node) { + var file = ts.getSourceFileOfNode(node); + return !file + ? undefined + : { + path: file.path, + start: indexFromOne(ts.getLineAndCharacterOfPosition(file, node.pos)), + end: indexFromOne(ts.getLineAndCharacterOfPosition(file, node.end)), + }; + function indexFromOne(lc) { + return { + line: lc.line + 1, + character: lc.character + 1, + }; + } } function dumpTypes(types) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; - ts.Debug.assert(fs); + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x; ts.performance.mark("beginDumpTypes"); var typesPath = legend[legend.length - 1].typesPath; var typesFd = fs.openSync(typesPath, "w"); @@ -3036,14 +3049,12 @@ var ts; var type = types[i]; var objectFlags = type.objectFlags; var symbol = (_a = type.aliasSymbol) !== null && _a !== void 0 ? _a : type.symbol; - var firstDeclaration = (_b = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _b === void 0 ? void 0 : _b[0]; - var firstFile = firstDeclaration && ts.getSourceFileOfNode(firstDeclaration); var display = void 0; if ((objectFlags & 16) | (type.flags & 2944)) { try { - display = (_c = type.checker) === null || _c === void 0 ? void 0 : _c.typeToString(type); + display = (_b = type.checker) === null || _b === void 0 ? void 0 : _b.typeToString(type); } - catch (_s) { + catch (_y) { display = undefined; } } @@ -3051,26 +3062,52 @@ var ts; if (type.flags & 8388608) { var indexedAccessType = type; indexedAccessProperties = { - indexedAccessObjectType: (_d = indexedAccessType.objectType) === null || _d === void 0 ? void 0 : _d.id, - indexedAccessIndexType: (_e = indexedAccessType.indexType) === null || _e === void 0 ? void 0 : _e.id, + indexedAccessObjectType: (_c = indexedAccessType.objectType) === null || _c === void 0 ? void 0 : _c.id, + indexedAccessIndexType: (_d = indexedAccessType.indexType) === null || _d === void 0 ? void 0 : _d.id, }; } var referenceProperties = {}; if (objectFlags & 4) { var referenceType = type; referenceProperties = { - instantiatedType: (_f = referenceType.target) === null || _f === void 0 ? void 0 : _f.id, - typeArguments: (_g = referenceType.resolvedTypeArguments) === null || _g === void 0 ? void 0 : _g.map(function (t) { return t.id; }), + instantiatedType: (_e = referenceType.target) === null || _e === void 0 ? void 0 : _e.id, + typeArguments: (_f = referenceType.resolvedTypeArguments) === null || _f === void 0 ? void 0 : _f.map(function (t) { return t.id; }), + referenceLocation: getLocation(referenceType.node), }; } var conditionalProperties = {}; if (type.flags & 16777216) { var conditionalType = type; conditionalProperties = { - conditionalCheckType: (_h = conditionalType.checkType) === null || _h === void 0 ? void 0 : _h.id, - conditionalExtendsType: (_j = conditionalType.extendsType) === null || _j === void 0 ? void 0 : _j.id, - conditionalTrueType: (_l = (_k = conditionalType.resolvedTrueType) === null || _k === void 0 ? void 0 : _k.id) !== null && _l !== void 0 ? _l : -1, - conditionalFalseType: (_o = (_m = conditionalType.resolvedFalseType) === null || _m === void 0 ? void 0 : _m.id) !== null && _o !== void 0 ? _o : -1, + conditionalCheckType: (_g = conditionalType.checkType) === null || _g === void 0 ? void 0 : _g.id, + conditionalExtendsType: (_h = conditionalType.extendsType) === null || _h === void 0 ? void 0 : _h.id, + conditionalTrueType: (_k = (_j = conditionalType.resolvedTrueType) === null || _j === void 0 ? void 0 : _j.id) !== null && _k !== void 0 ? _k : -1, + conditionalFalseType: (_m = (_l = conditionalType.resolvedFalseType) === null || _l === void 0 ? void 0 : _l.id) !== null && _m !== void 0 ? _m : -1, + }; + } + var substitutionProperties = {}; + if (type.flags & 33554432) { + var substitutionType = type; + substitutionProperties = { + substitutionBaseType: (_o = substitutionType.baseType) === null || _o === void 0 ? void 0 : _o.id, + substituteType: (_p = substitutionType.substitute) === null || _p === void 0 ? void 0 : _p.id, + }; + } + var reverseMappedProperties = {}; + if (objectFlags & 1024) { + var reverseMappedType = type; + reverseMappedProperties = { + reverseMappedSourceType: (_q = reverseMappedType.source) === null || _q === void 0 ? void 0 : _q.id, + reverseMappedMappedType: (_r = reverseMappedType.mappedType) === null || _r === void 0 ? void 0 : _r.id, + reverseMappedConstraintType: (_s = reverseMappedType.constraintType) === null || _s === void 0 ? void 0 : _s.id, + }; + } + var evolvingArrayProperties = {}; + if (objectFlags & 256) { + var evolvingArrayType = type; + evolvingArrayProperties = { + evolvingArrayElementType: evolvingArrayType.elementType.id, + evolvingArrayFinalType: (_t = evolvingArrayType.finalArrayType) === null || _t === void 0 ? void 0 : _t.id, }; } var recursionToken = void 0; @@ -3082,11 +3119,7 @@ var ts; recursionIdentityMap.set(recursionIdentity, recursionToken); } } - var descriptor = __assign(__assign(__assign(__assign({ id: type.id, intrinsicName: type.intrinsicName, symbolName: (symbol === null || symbol === void 0 ? void 0 : symbol.escapedName) && ts.unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, unionTypes: (type.flags & 1048576) ? (_p = type.types) === null || _p === void 0 ? void 0 : _p.map(function (t) { return t.id; }) : undefined, intersectionTypes: (type.flags & 2097152) ? type.types.map(function (t) { return t.id; }) : undefined, aliasTypeArguments: (_q = type.aliasTypeArguments) === null || _q === void 0 ? void 0 : _q.map(function (t) { return t.id; }), keyofType: (type.flags & 4194304) ? (_r = type.type) === null || _r === void 0 ? void 0 : _r.id : undefined }, indexedAccessProperties), referenceProperties), conditionalProperties), { firstDeclaration: firstDeclaration && { - path: firstFile.path, - start: indexFromOne(ts.getLineAndCharacterOfPosition(firstFile, firstDeclaration.pos)), - end: indexFromOne(ts.getLineAndCharacterOfPosition(ts.getSourceFileOfNode(firstDeclaration), firstDeclaration.end)), - }, flags: ts.Debug.formatTypeFlags(type.flags).split("|"), display: display }); + var descriptor = __assign(__assign(__assign(__assign(__assign(__assign(__assign({ id: type.id, intrinsicName: type.intrinsicName, symbolName: (symbol === null || symbol === void 0 ? void 0 : symbol.escapedName) && ts.unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, isTuple: objectFlags & 8 ? true : undefined, unionTypes: (type.flags & 1048576) ? (_u = type.types) === null || _u === void 0 ? void 0 : _u.map(function (t) { return t.id; }) : undefined, intersectionTypes: (type.flags & 2097152) ? type.types.map(function (t) { return t.id; }) : undefined, aliasTypeArguments: (_v = type.aliasTypeArguments) === null || _v === void 0 ? void 0 : _v.map(function (t) { return t.id; }), keyofType: (type.flags & 4194304) ? (_w = type.type) === null || _w === void 0 ? void 0 : _w.id : undefined }, indexedAccessProperties), referenceProperties), conditionalProperties), substitutionProperties), reverseMappedProperties), evolvingArrayProperties), { destructuringPattern: getLocation(type.pattern), firstDeclaration: getLocation((_x = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _x === void 0 ? void 0 : _x[0]), flags: ts.Debug.formatTypeFlags(type.flags).split("|"), display: display }); fs.writeSync(typesFd, JSON.stringify(descriptor)); if (i < numTypes - 1) { fs.writeSync(typesFd, ",\n"); @@ -3101,11 +3134,12 @@ var ts; if (!legendPath) { return; } - ts.Debug.assert(fs); fs.writeFileSync(legendPath, JSON.stringify(legend)); } - tracing.dumpLegend = dumpLegend; - })(tracing = ts.tracing || (ts.tracing = {})); + tracingEnabled.dumpLegend = dumpLegend; + })(tracingEnabled || (tracingEnabled = {})); + ts.startTracing = tracingEnabled.startTracing; + ts.dumpTracingLegend = tracingEnabled.dumpLegend; })(ts || (ts = {})); var ts; (function (ts) { @@ -3174,20 +3208,23 @@ var ts; WatchFileKind[WatchFileKind["FixedPollingInterval"] = 0] = "FixedPollingInterval"; WatchFileKind[WatchFileKind["PriorityPollingInterval"] = 1] = "PriorityPollingInterval"; WatchFileKind[WatchFileKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; - WatchFileKind[WatchFileKind["UseFsEvents"] = 3] = "UseFsEvents"; - WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 4] = "UseFsEventsOnParentDirectory"; + WatchFileKind[WatchFileKind["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; + WatchFileKind[WatchFileKind["UseFsEvents"] = 4] = "UseFsEvents"; + WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 5] = "UseFsEventsOnParentDirectory"; })(WatchFileKind = ts.WatchFileKind || (ts.WatchFileKind = {})); var WatchDirectoryKind; (function (WatchDirectoryKind) { WatchDirectoryKind[WatchDirectoryKind["UseFsEvents"] = 0] = "UseFsEvents"; WatchDirectoryKind[WatchDirectoryKind["FixedPollingInterval"] = 1] = "FixedPollingInterval"; WatchDirectoryKind[WatchDirectoryKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; + WatchDirectoryKind[WatchDirectoryKind["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; })(WatchDirectoryKind = ts.WatchDirectoryKind || (ts.WatchDirectoryKind = {})); var PollingWatchKind; (function (PollingWatchKind) { PollingWatchKind[PollingWatchKind["FixedInterval"] = 0] = "FixedInterval"; PollingWatchKind[PollingWatchKind["PriorityInterval"] = 1] = "PriorityInterval"; PollingWatchKind[PollingWatchKind["DynamicPriority"] = 2] = "DynamicPriority"; + PollingWatchKind[PollingWatchKind["FixedChunkSize"] = 3] = "FixedChunkSize"; })(PollingWatchKind = ts.PollingWatchKind || (ts.PollingWatchKind = {})); var ModuleKind; (function (ModuleKind) { @@ -3741,6 +3778,10 @@ var ts; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); ts.missingFileModifiedTime = new Date(0); + function getModifiedTime(host, fileName) { + return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; + } + ts.getModifiedTime = getModifiedTime; function createPollingIntervalBasedLevels(levels) { var _a; return _a = {}, @@ -3795,6 +3836,44 @@ var ts; } } ts.setCustomPollingValues = setCustomPollingValues; + function pollWatchedFileQueue(host, queue, pollIndex, chunkSize, callbackOnWatchFileStat) { + var definedValueCopyToIndex = pollIndex; + for (var canVisit = queue.length; chunkSize && canVisit; nextPollIndex(), canVisit--) { + var watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + chunkSize--; + var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(host, watchedFile.fileName)); + if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + callbackOnWatchFileStat === null || callbackOnWatchFileStat === void 0 ? void 0 : callbackOnWatchFileStat(watchedFile, pollIndex, fileChanged); + if (queue[pollIndex]) { + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } function createDynamicPriorityPollingWatchFile(host) { var watchedFiles = []; var changedFilesInLastPoll = []; @@ -3807,7 +3886,7 @@ var ts; fileName: fileName, callback: callback, unchangedPolls: 0, - mtime: getModifiedTime(fileName) + mtime: getModifiedTime(host, fileName) }; watchedFiles.push(file); addToPollingIntervalQueue(file, defaultPollingInterval); @@ -3843,23 +3922,9 @@ var ts; } } function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { - var needsVisit = queue.length; - var definedValueCopyToIndex = pollIndex; - for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { - var watchedFile = queue[pollIndex]; - if (!watchedFile) { - continue; - } - else if (watchedFile.isClosed) { - queue[pollIndex] = undefined; - continue; - } - polled++; - var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); - if (watchedFile.isClosed) { - queue[pollIndex] = undefined; - } - else if (fileChanged) { + return pollWatchedFileQueue(host, queue, pollIndex, chunkSize, onWatchFileStat); + function onWatchFileStat(watchedFile, pollIndex, fileChanged) { + if (fileChanged) { watchedFile.unchangedPolls = 0; if (queue !== changedFilesInLastPoll) { queue[pollIndex] = undefined; @@ -3879,24 +3944,6 @@ var ts; queue[pollIndex] = undefined; addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); } - if (queue[pollIndex]) { - if (definedValueCopyToIndex < pollIndex) { - queue[definedValueCopyToIndex] = watchedFile; - queue[pollIndex] = undefined; - } - definedValueCopyToIndex++; - } - } - return pollIndex; - function nextPollIndex() { - pollIndex++; - if (pollIndex === queue.length) { - if (definedValueCopyToIndex < pollIndex) { - queue.length = definedValueCopyToIndex; - } - pollIndex = 0; - definedValueCopyToIndex = 0; - } } } function pollingIntervalQueue(pollingInterval) { @@ -3925,9 +3972,6 @@ var ts; function scheduleNextPoll(pollingInterval) { pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); } - function getModifiedTime(fileName) { - return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; - } } ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) { @@ -3974,6 +4018,37 @@ var ts; return watcher; } } + function createFixedChunkSizePollingWatchFile(host) { + var watchedFiles = []; + var pollIndex = 0; + var pollScheduled; + return watchFile; + function watchFile(fileName, callback) { + var file = { + fileName: fileName, + callback: callback, + mtime: getModifiedTime(host, fileName) + }; + watchedFiles.push(file); + scheduleNextPoll(); + return { + close: function () { + file.isClosed = true; + ts.unorderedRemoveItem(watchedFiles, file); + } + }; + } + function pollQueue() { + pollScheduled = undefined; + pollIndex = pollWatchedFileQueue(host, watchedFiles, pollIndex, pollingChunkSize[PollingInterval.Low]); + scheduleNextPoll(); + } + function scheduleNextPoll() { + if (!watchedFiles.length || pollScheduled) + return; + pollScheduled = host.setTimeout(pollQueue, PollingInterval.High); + } + } function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) { var cache = new ts.Map(); var callbacksCache = ts.createMultiMap(); @@ -4248,8 +4323,9 @@ var ts; }; } function createSystemWatchFunctions(_a) { - var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory; + var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind; var dynamicPollingWatchFile; + var fixedChunkSizePollingWatchFile; var nonPollingWatchFile; var hostRecursiveDirectoryWatcher; return { @@ -4266,6 +4342,8 @@ var ts; return pollingWatchFile(fileName, callback, pollingInterval, undefined); case ts.WatchFileKind.DynamicPriorityPolling: return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, undefined); + case ts.WatchFileKind.FixedChunkSizePolling: + return ensureFixedChunkSizePollingWatchFile()(fileName, callback, undefined, undefined); case ts.WatchFileKind.UseFsEvents: return fsWatch(fileName, 0, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), false, pollingInterval, ts.getFallbackOptions(options)); case ts.WatchFileKind.UseFsEventsOnParentDirectory: @@ -4278,8 +4356,10 @@ var ts; } } function ensureDynamicPollingWatchFile() { - return dynamicPollingWatchFile || - (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })); + return dynamicPollingWatchFile || (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })); + } + function ensureFixedChunkSizePollingWatchFile() { + return fixedChunkSizePollingWatchFile || (fixedChunkSizePollingWatchFile = createFixedChunkSizePollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })); } function updateOptionsForWatchFile(options, useNonPollingWatchers) { if (options && options.watchFile !== undefined) @@ -4298,7 +4378,7 @@ var ts; default: return useNonPollingWatchers ? generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) : - { watchFile: ts.WatchFileKind.FixedPollingInterval }; + { watchFile: (defaultWatchFileKind === null || defaultWatchFileKind === void 0 ? void 0 : defaultWatchFileKind()) || ts.WatchFileKind.FixedPollingInterval }; } } function generateWatchFileOptions(watchFile, fallbackPolling, options) { @@ -4337,6 +4417,8 @@ var ts; return pollingWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, undefined); case ts.WatchDirectoryKind.DynamicPriorityPolling: return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, undefined); + case ts.WatchDirectoryKind.FixedChunkSizePolling: + return ensureFixedChunkSizePollingWatchFile()(directoryName, function () { return callback(directoryName); }, undefined, undefined); case ts.WatchDirectoryKind.UseFsEvents: return fsWatch(directoryName, 1, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), recursive, PollingInterval.Medium, ts.getFallbackOptions(watchDirectoryOptions)); default: @@ -4402,13 +4484,13 @@ var ts; } var activeSession; var profilePath = "./profile.cpuprofile"; - var realpathSync = (_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync; var Buffer = require("buffer").Buffer; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + var realpathSync = useCaseSensitiveFileNames ? ((_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync) : _fs.realpathSync; var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); var getCurrentDirectory = ts.memoize(function () { return process.cwd(); }); var _c = createSystemWatchFunctions({ @@ -4427,6 +4509,7 @@ var ts; tscWatchFile: process.env.TSC_WATCHFILE, useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER, tscWatchDirectory: process.env.TSC_WATCHDIRECTORY, + defaultWatchFileKind: function () { var _a, _b; return (_b = (_a = sys).defaultWatchFileKind) === null || _b === void 0 ? void 0 : _b.call(_a); }, }), watchFile = _c.watchFile, watchDirectory = _c.watchDirectory; var nodeSystem = { args: process.argv.slice(2), @@ -4492,6 +4575,7 @@ var ts; }, enableCPUProfiler: enableCPUProfiler, disableCPUProfiler: disableCPUProfiler, + cpuProfilingEnabled: function () { return !!activeSession || ts.contains(process.execArgv, "--cpu-prof") || ts.contains(process.execArgv, "--prof"); }, realpath: realpath, debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -4694,7 +4778,7 @@ var ts; return event === "rename" && (!relativeName || relativeName === lastDirectoryPart || - relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) && + (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && !fileSystemEntryExists(fileOrDirectory, entryKind) ? invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : callback(event, relativeName); @@ -4976,7 +5060,7 @@ var ts; Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1103, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103", "'for await' loops are only allowed within async functions and at the top levels of modules."), A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), @@ -5025,7 +5109,7 @@ var ts; A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), - A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_1166", "A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type."), A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), @@ -5085,7 +5169,7 @@ var ts; A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), - An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231", "An export assignment must be at the top level of a file or module declaration."), An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), @@ -5111,6 +5195,7 @@ var ts; A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1258, ts.DiagnosticCategory.Error, "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258", "A default export must be at the top level of a file or module declaration."), Module_0_can_only_be_default_imported_using_the_1_flag: diag(1259, ts.DiagnosticCategory.Error, "Module_0_can_only_be_default_imported_using_the_1_flag_1259", "Module '{0}' can only be default-imported using the '{1}' flag"), Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), @@ -5197,7 +5282,7 @@ var ts; Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), Provides_a_root_package_name_when_using_outFile_with_declarations: diag(1390, ts.DiagnosticCategory.Message, "Provides_a_root_package_name_when_using_outFile_with_declarations_1390", "Provides a root package name when using outFile with declarations."), - The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The `bundledPackageName` option must be provided when using outFile and node module resolution with declaration emit."), + The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The 'bundledPackageName' option must be provided when using outFile and node module resolution with declaration emit."), An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), @@ -5237,6 +5322,9 @@ var ts; File_is_output_of_project_reference_source_0: diag(1428, ts.DiagnosticCategory.Message, "File_is_output_of_project_reference_source_0_1428", "File is output of project reference source '{0}'"), File_redirects_to_file_0: diag(1429, ts.DiagnosticCategory.Message, "File_redirects_to_file_0_1429", "File redirects to file '{0}'"), The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), + for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), + Decorators_may_not_be_applied_to_this_parameters: diag(1433, ts.DiagnosticCategory.Error, "Decorators_may_not_be_applied_to_this_parameters_1433", "Decorators may not be applied to 'this' parameters."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", undefined, true), @@ -5304,7 +5392,7 @@ var ts; The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), - The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_in_expression_must_not_be_a_primitive: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_not_be_a_primitive_2361", "The right-hand side of an 'in' expression must not be a primitive."), The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), @@ -5322,8 +5410,7 @@ var ts; A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers."), Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), - Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."), - get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."), + The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type: diag(2380, ts.DiagnosticCategory.Error, "The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type_2380", "The return type of a 'get' accessor must be assignable to its 'set' accessor type"), A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."), Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."), Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), @@ -5386,7 +5473,7 @@ var ts; Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), - Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_cl_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'. This is an instance of class '{2}'."), The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), @@ -5486,14 +5573,13 @@ var ts; The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the `lib` compiler option to '{2}' or later."), + Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{2}' or later."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), - Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), - Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), + A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter: diag(2556, ts.DiagnosticCategory.Error, "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556", "A spread argument must either have a tuple type or be passed to a rest parameter."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), @@ -5516,17 +5602,17 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to '{1}' or later."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{1}' or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later."), Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."), Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add `node` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add `jquery` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add 'jquery' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), @@ -5559,6 +5645,12 @@ var ts; Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target: diag(2625, ts.DiagnosticCategory.Error, "Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target_2625", "Variadic element at position {0} in source does not match element at position {1} in target."), Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target: diag(2626, ts.DiagnosticCategory.Error, "Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target_2626", "Type at position {0} in source is not compatible with type at position {1} in target."), Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target: diag(2627, ts.DiagnosticCategory.Error, "Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target_2627", "Type at positions {0} through {1} in source is not compatible with type at position {2} in target."), + Cannot_assign_to_0_because_it_is_an_enum: diag(2628, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_an_enum_2628", "Cannot assign to '{0}' because it is an enum."), + Cannot_assign_to_0_because_it_is_a_class: diag(2629, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_class_2629", "Cannot assign to '{0}' because it is a class."), + Cannot_assign_to_0_because_it_is_a_function: diag(2630, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_function_2630", "Cannot assign to '{0}' because it is a function."), + Cannot_assign_to_0_because_it_is_a_namespace: diag(2631, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_namespace_2631", "Cannot assign to '{0}' because it is a namespace."), + Cannot_assign_to_0_because_it_is_an_import: diag(2632, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_an_import_2632", "Cannot assign to '{0}' because it is an import."), + JSX_property_access_expressions_cannot_include_JSX_namespace_names: diag(2633, ts.DiagnosticCategory.Error, "JSX_property_access_expressions_cannot_include_JSX_namespace_names_2633", "JSX property access expressions cannot include JSX namespace names"), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -5605,7 +5697,7 @@ var ts; Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), @@ -5613,14 +5705,14 @@ var ts; _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a 'delete' operator must be a property reference."), The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a 'delete' operator cannot be a read-only property."), - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), - A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), - A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), @@ -5682,7 +5774,7 @@ var ts; The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."), Overload_0_of_1_2_gave_the_following_error: diag(2772, ts.DiagnosticCategory.Error, "Overload_0_of_1_2_gave_the_following_error_2772", "Overload {0} of {1}, '{2}', gave the following error."), Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"), - This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it__2774", "This condition will always return true since the function is always defined. Did you mean to call it instead?"), + This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774", "This condition will always return true since this function is always defined. Did you mean to call it instead?"), Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation: diag(2775, ts.DiagnosticCategory.Error, "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775", "Assertions require every name in the call target to be declared with an explicit type annotation."), Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name: diag(2776, ts.DiagnosticCategory.Error, "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776", "Assertions require the call target to be an identifier or qualified name."), The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access: diag(2777, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777", "The operand of an increment or decrement operator may not be an optional property access."), @@ -5706,6 +5798,21 @@ var ts; The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types: diag(2795, ts.DiagnosticCategory.Error, "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795", "The 'intrinsic' keyword can only be used to declare compiler provided intrinsic types."), It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked: diag(2796, ts.DiagnosticCategory.Error, "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796", "It is likely that you are missing a comma to separate these two template expressions. They form a tagged template expression which cannot be invoked."), A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract: diag(2797, ts.DiagnosticCategory.Error, "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797", "A mixin class that extends from a type variable containing an abstract construct signature must also be declared 'abstract'."), + The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), + Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), + Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), + This_condition_will_always_return_true_since_this_0_is_always_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_is_always_defined_2801", "This condition will always return true since this '{0}' is always defined."), + Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher: diag(2802, ts.DiagnosticCategory.Error, "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802", "Type '{0}' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher."), + Cannot_assign_to_private_method_0_Private_methods_are_not_writable: diag(2803, ts.DiagnosticCategory.Error, "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803", "Cannot assign to private method '{0}'. Private methods are not writable."), + Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name: diag(2804, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804", "Duplicate identifier '{0}'. Static and instance elements cannot share the same private name."), + Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag: diag(2805, ts.DiagnosticCategory.Error, "Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_no_2805", "Static fields with private names can't have initializers when the '--useDefineForClassFields' flag is not specified with a '--target' of 'esnext'. Consider adding the '--useDefineForClassFields' flag."), + Private_accessor_was_defined_without_a_getter: diag(2806, ts.DiagnosticCategory.Error, "Private_accessor_was_defined_without_a_getter_2806", "Private accessor was defined without a getter."), + This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0: diag(2807, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807", "This syntax requires an imported helper named '{1}' with {2} parameters, which is not compatible with the one in '{0}'. Consider upgrading your version of '{0}'."), + A_get_accessor_must_be_at_least_as_accessible_as_the_setter: diag(2808, ts.DiagnosticCategory.Error, "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808", "A get accessor must be at least as accessible as the setter"), + Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses: diag(2809, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809", "Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses."), + Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false: diag(2810, ts.DiagnosticCategory.Error, "Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnex_2810", "Property '{0}' may not be used in a static property's initializer in the same class when 'target' is 'esnext' and 'useDefineForClassFields' is 'false'."), + Initializer_for_property_0: diag(2811, ts.DiagnosticCategory.Error, "Initializer_for_property_0_2811", "Initializer for property '{0}'"), + Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom: diag(2812, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812", "Property '{0}' does not exist on type '{1}'. Try changing the 'lib' compiler option to include 'dom'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5778,6 +5885,7 @@ var ts; Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2: diag(4084, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084", "Exported type alias '{0}' has or is using private name '{1}' from module {2}."), Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), @@ -5799,6 +5907,11 @@ var ts; Type_arguments_for_0_circularly_reference_themselves: diag(4109, ts.DiagnosticCategory.Error, "Type_arguments_for_0_circularly_reference_themselves_4109", "Type arguments for '{0}' circularly reference themselves."), Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."), Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0: diag(4111, ts.DiagnosticCategory.Error, "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111", "Property '{0}' comes from an index signature, so it must be accessed with ['{0}']."), + This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class: diag(4112, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112", "This member cannot have an 'override' modifier because its containing class '{0}' does not extend another class."), + This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0: diag(4113, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113", "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'."), + This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0: diag(4114, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114", "This member must have an 'override' modifier because it overrides a member in the base class '{0}'."), + This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115", "This parameter property must have an 'override' modifier because it overrides a member in base class '{0}'."), + This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0: diag(4116, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116", "This member must have an 'override' modifier because it overrides an abstract method that is declared in the base class '{0}'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -5833,7 +5946,7 @@ var ts; Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), - Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option `--tsBuildInfoFile` is specified."), + Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option '--tsBuildInfoFile' is specified."), _0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2: diag(5075, ts.DiagnosticCategory.Error, "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075", "'{0}' is assignable to the constraint of type '{1}', but '{1}' could be instantiated with a different subtype of constraint '{2}'."), _0_and_1_operations_cannot_be_mixed_without_parentheses: diag(5076, ts.DiagnosticCategory.Error, "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076", "'{0}' and '{1}' operations cannot be mixed without parentheses."), Unknown_build_option_0_Did_you_mean_1: diag(5077, ts.DiagnosticCategory.Error, "Unknown_build_option_0_Did_you_mean_1_5077", "Unknown build option '{0}'. Did you mean '{1}'?"), @@ -5846,10 +5959,14 @@ var ts; Tuple_members_must_all_have_names_or_all_not_have_names: diag(5084, ts.DiagnosticCategory.Error, "Tuple_members_must_all_have_names_or_all_not_have_names_5084", "Tuple members must all have names or all not have names."), A_tuple_member_cannot_be_both_optional_and_rest: diag(5085, ts.DiagnosticCategory.Error, "A_tuple_member_cannot_be_both_optional_and_rest_5085", "A tuple member cannot be both optional and rest."), A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type: diag(5086, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086", "A labeled tuple element is declared as optional with a question mark after the name and before the colon, rather than after the type."), - A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a `...` before the name, rather than before the type."), + A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a '...' before the name, rather than before the type."), The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), + Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."), + The_root_value_of_a_0_file_must_be_an_object: diag(5092, ts.DiagnosticCategory.Error, "The_root_value_of_a_0_file_must_be_an_object_5092", "The root value of a '{0}' file must be an object."), + Compiler_option_0_may_only_be_used_with_build: diag(5093, ts.DiagnosticCategory.Error, "Compiler_option_0_may_only_be_used_with_build_5093", "Compiler option '--{0}' may only be used with '--build'."), + Compiler_option_0_may_not_be_used_with_build: diag(5094, ts.DiagnosticCategory.Error, "Compiler_option_0_may_not_be_used_with_build_5094", "Compiler option '--{0}' may not be used with '--build'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5865,7 +5982,7 @@ var ts; Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), @@ -6060,9 +6177,9 @@ var ts; Emit_class_fields_with_Define_instead_of_Set: diag(6222, ts.DiagnosticCategory.Message, "Emit_class_fields_with_Define_instead_of_Set_6222", "Emit class fields with Define instead of Set."), Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."), Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."), - Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."), - Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling'."), - Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority'."), + Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."), + Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling'."), + Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority_FixedChunkSize: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority', 'FixedChunkSize'."), Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively: diag(6228, ts.DiagnosticCategory.Message, "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6228", "Synchronously call callbacks and update the state of directory watchers on platforms that don't support recursive watching natively."), Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3: diag(6229, ts.DiagnosticCategory.Error, "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229", "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'."), Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."), @@ -6073,7 +6190,11 @@ var ts; Disable_loading_referenced_projects: diag(6235, ts.DiagnosticCategory.Message, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."), Arguments_for_the_rest_parameter_0_were_not_provided: diag(6236, ts.DiagnosticCategory.Error, "Arguments_for_the_rest_parameter_0_were_not_provided_6236", "Arguments for the rest parameter '{0}' were not provided."), Generates_an_event_trace_and_a_list_of_types: diag(6237, ts.DiagnosticCategory.Message, "Generates_an_event_trace_and_a_list_of_types_6237", "Generates an event trace and a list of types."), - Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the `jsx` and `jsxs` factory functions from. eg, react"), + Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the 'jsx' and 'jsxs' factory functions from. eg, react"), + File_0_exists_according_to_earlier_cached_lookups: diag(6239, ts.DiagnosticCategory.Message, "File_0_exists_according_to_earlier_cached_lookups_6239", "File '{0}' exists according to earlier cached lookups."), + File_0_does_not_exist_according_to_earlier_cached_lookups: diag(6240, ts.DiagnosticCategory.Message, "File_0_does_not_exist_according_to_earlier_cached_lookups_6240", "File '{0}' does not exist according to earlier cached lookups."), + Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1: diag(6241, ts.DiagnosticCategory.Message, "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241", "Resolution for type reference directive '{0}' was found in cache from location '{1}'."), + Resolving_type_reference_directive_0_containing_file_1: diag(6242, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_6242", "======== Resolving type reference directive '{0}', containing file '{1}'. ========"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -6118,16 +6239,19 @@ var ts; Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382", "Skipping build of project '{0}' because its dependency '{1}' was not built"), Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383", "Project '{0}' can't be built because its dependency '{1}' was not built"), Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, ts.DiagnosticCategory.Message, "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384", "Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it."), - _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated", undefined, undefined, true), + _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", undefined, undefined, true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), + The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", undefined, undefined, true), + Project_0_is_being_forcibly_rebuilt: diag(6388, ts.DiagnosticCategory.Message, "Project_0_is_being_forcibly_rebuilt_6388", "Project '{0}' is being forcibly rebuilt"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option: diag(6504, ts.DiagnosticCategory.Error, "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504", "File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?"), Print_names_of_files_and_the_reason_they_are_part_of_the_compilation: diag(6505, ts.DiagnosticCategory.Message, "Print_names_of_files_and_the_reason_they_are_part_of_the_compilation_6505", "Print names of files and the reason they are part of the compilation."), - Require_undeclared_properties_from_index_signatures_to_use_element_accesses: diag(6803, ts.DiagnosticCategory.Error, "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803", "Require undeclared properties from index signatures to use element accesses."), Include_undefined_in_index_signature_results: diag(6800, ts.DiagnosticCategory.Message, "Include_undefined_in_index_signature_results_6800", "Include 'undefined' in index signature results"), + Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier: diag(6801, ts.DiagnosticCategory.Message, "Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier_6801", "Ensure overriding members in derived classes are marked with an 'override' modifier."), + Require_undeclared_properties_from_index_signatures_to_use_element_accesses: diag(6802, ts.DiagnosticCategory.Message, "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6802", "Require undeclared properties from index signatures to use element accesses."), 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."), @@ -6160,7 +6284,7 @@ var ts; Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), - If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'"), The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), @@ -6200,7 +6324,7 @@ var ts; JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), - Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one '@augments' or '@extends' tag."), Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), @@ -6445,6 +6569,10 @@ var ts; Add_all_missing_function_declarations: diag(95157, ts.DiagnosticCategory.Message, "Add_all_missing_function_declarations_95157", "Add all missing function declarations"), Method_not_implemented: diag(95158, ts.DiagnosticCategory.Message, "Method_not_implemented_95158", "Method not implemented."), Function_not_implemented: diag(95159, ts.DiagnosticCategory.Message, "Function_not_implemented_95159", "Function not implemented."), + Add_override_modifier: diag(95160, ts.DiagnosticCategory.Message, "Add_override_modifier_95160", "Add 'override' modifier"), + Remove_override_modifier: diag(95161, ts.DiagnosticCategory.Message, "Remove_override_modifier_95161", "Remove 'override' modifier"), + Add_all_missing_override_modifiers: diag(95162, ts.DiagnosticCategory.Message, "Add_all_missing_override_modifiers_95162", "Add all missing 'override' modifiers"), + Remove_all_unnecessary_override_modifiers: diag(95163, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_override_modifiers_95163", "Remove all unnecessary 'override' modifiers"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -6459,8 +6587,6 @@ var ts; The_shadowing_declaration_of_0_is_defined_here: diag(18017, ts.DiagnosticCategory.Error, "The_shadowing_declaration_of_0_is_defined_here_18017", "The shadowing declaration of '{0}' is defined here"), The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here: diag(18018, ts.DiagnosticCategory.Error, "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018", "The declaration of '{0}' that you probably intended to use is defined here"), _0_modifier_cannot_be_used_with_a_private_identifier: diag(18019, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_private_identifier_18019", "'{0}' modifier cannot be used with a private identifier."), - A_method_cannot_be_named_with_a_private_identifier: diag(18022, ts.DiagnosticCategory.Error, "A_method_cannot_be_named_with_a_private_identifier_18022", "A method cannot be named with a private identifier."), - An_accessor_cannot_be_named_with_a_private_identifier: diag(18023, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_named_with_a_private_identifier_18023", "An accessor cannot be named with a private identifier."), An_enum_member_cannot_be_named_with_a_private_identifier: diag(18024, ts.DiagnosticCategory.Error, "An_enum_member_cannot_be_named_with_a_private_identifier_18024", "An enum member cannot be named with a private identifier."), can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), Compiler_reserves_name_0_when_emitting_private_identifier_downlevel: diag(18027, ts.DiagnosticCategory.Error, "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027", "Compiler reserves name '{0}' when emitting private identifier downlevel."), @@ -6472,6 +6598,7 @@ var ts; Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead: diag(18033, ts.DiagnosticCategory.Error, "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033", "Only numeric enums can have computed members, but this expression has type '{0}'. If you do not need exhaustiveness checks, consider using an object literal instead."), Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compiler_option_is_specified_e_g_Fragment: diag(18034, ts.DiagnosticCategory.Message, "Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compi_18034", "Specify the JSX fragment factory function to use when targeting 'react' JSX emit with 'jsxFactory' compiler option is specified, e.g. 'Fragment'."), Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(18035, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name_18035", "Invalid value for 'jsxFragmentFactory'. '{0}' is not a valid identifier or qualified-name."), + Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator: diag(18036, ts.DiagnosticCategory.Error, "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036", "Class decorators can't be used with static private identifier. Consider removing the experimental decorator."), }; })(ts || (ts = {})); var ts; @@ -6537,6 +6664,7 @@ var ts; _a.private = 120, _a.protected = 121, _a.public = 122, + _a.override = 156, _a.readonly = 142, _a.require = 143, _a.global = 154, @@ -6563,7 +6691,7 @@ var ts; _a.yield = 124, _a.async = 129, _a.await = 130, - _a.of = 156, + _a.of = 157, _a); var textToKeyword = new ts.Map(ts.getEntries(textToKeywordObj)); var textToToken = new ts.Map(ts.getEntries(__assign(__assign({}, textToKeywordObj), { "{": 18, "}": 19, "(": 20, ")": 21, "[": 22, "]": 23, ".": 24, "...": 25, ";": 26, ",": 27, "<": 29, ">": 31, "<=": 32, ">=": 33, "==": 34, "!=": 35, "===": 36, "!==": 37, "=>": 38, "+": 39, "-": 40, "**": 42, "*": 41, "/": 43, "%": 44, "++": 45, "--": 46, "<<": 47, ">": 48, ">>>": 49, "&": 50, "|": 51, "^": 52, "!": 53, "~": 54, "&&": 55, "||": 56, "?": 57, "??": 60, "?.": 28, ":": 58, "=": 62, "+=": 63, "-=": 64, "*=": 65, "**=": 66, "/=": 67, "%=": 68, "<<=": 69, ">>=": 70, ">>>=": 71, "&=": 72, "|=": 73, "^=": 77, "||=": 74, "&&=": 75, "??=": 76, "@": 59, "`": 61 }))); @@ -6780,11 +6908,11 @@ var ts; } } ts.couldStartTrivia = couldStartTrivia; - function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { - if (stopAtComments === void 0) { stopAtComments = false; } + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments, inJSDoc) { if (ts.positionIsSynthesized(pos)) { return pos; } + var canConsumeStar = false; while (true) { var ch = text.charCodeAt(pos); switch (ch) { @@ -6797,6 +6925,7 @@ var ts; if (stopAfterLineBreak) { return pos; } + canConsumeStar = !!inJSDoc; continue; case 9: case 11: @@ -6816,6 +6945,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } if (text.charCodeAt(pos + 1) === 42) { @@ -6827,6 +6957,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } break; @@ -6836,12 +6967,21 @@ var ts; case 62: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos); + canConsumeStar = false; continue; } break; case 35: if (pos === 0 && isShebangTrivia(text, pos)) { pos = scanShebangTrivia(text, pos); + canConsumeStar = false; + continue; + } + break; + case 42: + if (canConsumeStar) { + pos++; + canConsumeStar = false; continue; } break; @@ -7108,6 +7248,7 @@ var ts; reScanJsxToken: reScanJsxToken, reScanLessThanToken: reScanLessThanToken, reScanQuestionToken: reScanQuestionToken, + reScanInvalidIdentifier: reScanInvalidIdentifier, scanJsxToken: scanJsxToken, scanJsDocToken: scanJsDocToken, scan: scan, @@ -8061,15 +8202,9 @@ var ts; } return token = 79; default: - if (isIdentifierStart(ch, languageVersion)) { - pos += charSize(ch); - while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) - pos += charSize(ch); - tokenValue = text.substring(tokenPos, pos); - if (ch === 92) { - tokenValue += scanIdentifierParts(); - } - return token = getIdentifierToken(); + var identifierKind = scanIdentifier(ch, languageVersion); + if (identifierKind) { + return token = identifierKind; } else if (isWhiteSpaceSingleLine(ch)) { pos += charSize(ch); @@ -8086,6 +8221,31 @@ var ts; } } } + function reScanInvalidIdentifier() { + ts.Debug.assert(token === 0, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'."); + pos = tokenPos = startPos; + tokenFlags = 0; + var ch = codePointAt(text, pos); + var identifierKind = scanIdentifier(ch, 99); + if (identifierKind) { + return token = identifierKind; + } + pos += charSize(ch); + return token; + } + function scanIdentifier(startCharacter, languageVersion) { + var ch = startCharacter; + if (isIdentifierStart(ch, languageVersion)) { + pos += charSize(ch); + while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) + pos += charSize(ch); + tokenValue = text.substring(tokenPos, pos); + if (ch === 92) { + tokenValue += scanIdentifierParts(); + } + return getIdentifierToken(); + } + } function reScanGreaterToken() { if (token === 31) { if (text.charCodeAt(pos) === 62) { @@ -8189,9 +8349,10 @@ var ts; pos = tokenPos; return token = scanTemplateAndSetTokenValue(true); } - function reScanJsxToken() { + function reScanJsxToken(allowMultilineJsxText) { + if (allowMultilineJsxText === void 0) { allowMultilineJsxText = true; } pos = tokenPos = startPos; - return token = scanJsxToken(); + return token = scanJsxToken(allowMultilineJsxText); } function reScanLessThanToken() { if (token === 47) { @@ -8205,7 +8366,8 @@ var ts; pos = tokenPos + 1; return token = 57; } - function scanJsxToken() { + function scanJsxToken(allowMultilineJsxText) { + if (allowMultilineJsxText === void 0) { allowMultilineJsxText = true; } startPos = tokenPos = pos; if (pos >= end) { return token = 1; @@ -8224,11 +8386,7 @@ var ts; return token = 18; } var firstNonWhitespace = 0; - var lastNonWhitespace = -1; while (pos < end) { - if (!isWhiteSpaceSingleLine(char)) { - lastNonWhitespace = pos; - } char = text.charCodeAt(pos); if (char === 123) { break; @@ -8246,18 +8404,18 @@ var ts; if (char === 125) { error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1); } - if (lastNonWhitespace > 0) - lastNonWhitespace++; if (isLineBreak(char) && firstNonWhitespace === 0) { firstNonWhitespace = -1; } + else if (!allowMultilineJsxText && isLineBreak(char) && firstNonWhitespace > 0) { + break; + } else if (!isWhiteSpaceLike(char)) { firstNonWhitespace = pos; } pos++; } - var endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace; - tokenValue = text.substring(startPos, endPosition); + tokenValue = text.substring(startPos, pos); return firstNonWhitespace === -1 ? 12 : 11; } function scanJsxIdentifier() { @@ -8274,6 +8432,7 @@ var ts; tokenValue += ":"; pos++; namespaceSeparator = true; + token = 78; continue; } var oldPos = pos; @@ -8513,6 +8672,8 @@ var ts; switch (options.target) { case 99: return "lib.esnext.full.d.ts"; + case 8: + return "lib.es2021.full.d.ts"; case 7: return "lib.es2020.full.d.ts"; case 6: @@ -8640,9 +8801,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 159) { + if (d && d.kind === 160) { for (var current = d; current; current = current.parent) { - if (isFunctionLike(current) || isClassLike(current) || current.kind === 253) { + if (isFunctionLike(current) || isClassLike(current) || current.kind === 254) { return current; } } @@ -8650,7 +8811,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node, parent) { - return ts.hasSyntacticModifier(node, 92) && parent.kind === 166; + return ts.hasSyntacticModifier(node, 16476) && parent.kind === 167; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -8680,14 +8841,14 @@ var ts; node = walkUpBindingElementsAndPatterns(node); } var flags = getFlags(node); - if (node.kind === 249) { + if (node.kind === 250) { node = node.parent; } - if (node && node.kind === 250) { + if (node && node.kind === 251) { flags |= getFlags(node); node = node.parent; } - if (node && node.kind === 232) { + if (node && node.kind === 233) { flags |= getFlags(node); } return flags; @@ -8704,8 +8865,10 @@ var ts; return getCombinedFlags(node, function (n) { return n.flags; }); } ts.getCombinedNodeFlags = getCombinedNodeFlags; + ts.supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; function validateLocaleAndSetLanguage(locale, sys, errors) { - var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + var lowerCaseLocale = locale.toLowerCase(); + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale); if (!matchResult) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); @@ -8714,7 +8877,7 @@ var ts; } var language = matchResult[1]; var territory = matchResult[3]; - if (!trySetLanguageAndTerritory(language, territory, errors)) { + if (ts.contains(ts.supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) { trySetLanguageAndTerritory(language, undefined, errors); } ts.setUILocale(locale); @@ -8806,7 +8969,7 @@ var ts; } ts.idText = idText; function symbolName(symbol) { - if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) { + if (symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) { return idText(symbol.valueDeclaration.name); } return unescapeLeadingUnderscores(symbol.escapedName); @@ -8821,30 +8984,30 @@ var ts; return getDeclarationIdentifier(hostNode); } switch (hostNode.kind) { - case 232: + case 233: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } break; - case 233: + case 234: var expr = hostNode.expression; - if (expr.kind === 216 && expr.operatorToken.kind === 62) { + if (expr.kind === 217 && expr.operatorToken.kind === 62) { expr = expr.left; } switch (expr.kind) { - case 201: - return expr.name; case 202: + return expr.name; + case 203: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; } } break; - case 207: { + case 208: { return getDeclarationIdentifier(hostNode.expression); } - case 245: { + case 246: { if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } @@ -8878,16 +9041,16 @@ var ts; switch (declaration.kind) { case 78: return declaration; - case 333: - case 326: { + case 337: + case 330: { var name = declaration.name; - if (name.kind === 157) { + if (name.kind === 158) { return name.right; } break; } - case 203: - case 216: { + case 204: + case 217: { var expr_1 = declaration; switch (ts.getAssignmentDeclarationKind(expr_1)) { case 1: @@ -8903,15 +9066,15 @@ var ts; return undefined; } } - case 331: + case 335: return getNameOfJSDocTypedef(declaration); - case 325: + case 329: return nameForNamelessJSDocTypedef(declaration); - case 266: { + case 267: { var expression = declaration.expression; return ts.isIdentifier(expression) ? expression : undefined; } - case 202: + case 203: var expr = declaration; if (ts.isBindableStaticElementAccessExpression(expr)) { return expr.argumentExpression; @@ -8924,7 +9087,7 @@ var ts; if (declaration === undefined) return undefined; return getNonAssignedNameOfDeclaration(declaration) || - (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + (ts.isFunctionExpression(declaration) || ts.isArrowFunction(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); } ts.getNameOfDeclaration = getNameOfDeclaration; function getAssignedName(node) { @@ -9034,6 +9197,10 @@ var ts; return getFirstJSDocTag(node, ts.isJSDocReadonlyTag, true); } ts.getJSDocReadonlyTagNoCache = getJSDocReadonlyTagNoCache; + function getJSDocOverrideTagNoCache(node) { + return getFirstJSDocTag(node, ts.isJSDocOverrideTag, true); + } + ts.getJSDocOverrideTagNoCache = getJSDocOverrideTagNoCache; function getJSDocDeprecatedTag(node) { return getFirstJSDocTag(node, ts.isJSDocDeprecatedTag); } @@ -9123,12 +9290,19 @@ var ts; return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + function getTextOfJSDocComment(comment) { + return typeof comment === "string" ? comment + : comment === null || comment === void 0 ? void 0 : comment.map(function (c) { + return c.kind === 313 ? c.text : "{@link " + (c.name ? ts.entityNameToString(c.name) + " " : "") + c.text + "}"; + }).join(""); + } + ts.getTextOfJSDocComment = getTextOfJSDocComment; function getEffectiveTypeParameterDeclarations(node) { if (ts.isJSDocSignature(node)) { return ts.emptyArray; } if (ts.isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 311); + ts.Debug.assert(node.parent.kind === 312); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } if (node.typeParameters) { @@ -9153,12 +9327,12 @@ var ts; undefined; } ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter; - function isIdentifierOrPrivateIdentifier(node) { + function isMemberName(node) { return node.kind === 78 || node.kind === 79; } - ts.isIdentifierOrPrivateIdentifier = isIdentifierOrPrivateIdentifier; + ts.isMemberName = isMemberName; function isGetOrSetAccessorDeclaration(node) { - return node.kind === 168 || node.kind === 167; + return node.kind === 169 || node.kind === 168; } ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; function isPropertyAccessChain(node) { @@ -9176,10 +9350,10 @@ var ts; function isOptionalChain(node) { var kind = node.kind; return !!(node.flags & 32) && - (kind === 201 - || kind === 202 + (kind === 202 || kind === 203 - || kind === 225); + || kind === 204 + || kind === 226); } ts.isOptionalChain = isOptionalChain; function isOptionalChainRoot(node) { @@ -9197,7 +9371,7 @@ var ts; } ts.isOutermostOptionalChain = isOutermostOptionalChain; function isNullishCoalesce(node) { - return node.kind === 216 && node.operatorToken.kind === 60; + return node.kind === 217 && node.operatorToken.kind === 60; } ts.isNullishCoalesce = isNullishCoalesce; function isConstTypeReference(node) { @@ -9214,17 +9388,17 @@ var ts; } ts.isNonNullChain = isNonNullChain; function isBreakOrContinueStatement(node) { - return node.kind === 241 || node.kind === 240; + return node.kind === 242 || node.kind === 241; } ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isNamedExportBindings(node) { - return node.kind === 269 || node.kind === 268; + return node.kind === 270 || node.kind === 269; } ts.isNamedExportBindings = isNamedExportBindings; function isUnparsedTextLike(node) { switch (node.kind) { - case 294: case 295: + case 296: return true; default: return false; @@ -9233,12 +9407,12 @@ var ts; ts.isUnparsedTextLike = isUnparsedTextLike; function isUnparsedNode(node) { return isUnparsedTextLike(node) || - node.kind === 292 || - node.kind === 296; + node.kind === 293 || + node.kind === 297; } ts.isUnparsedNode = isUnparsedNode; function isJSDocPropertyLikeTag(node) { - return node.kind === 333 || node.kind === 326; + return node.kind === 337 || node.kind === 330; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isNode(node) { @@ -9246,11 +9420,15 @@ var ts; } ts.isNode = isNode; function isNodeKind(kind) { - return kind >= 157; + return kind >= 158; } ts.isNodeKind = isNodeKind; + function isTokenKind(kind) { + return kind >= 0 && kind <= 157; + } + ts.isTokenKind = isTokenKind; function isToken(n) { - return n.kind >= 0 && n.kind <= 156; + return isTokenKind(n.kind); } ts.isToken = isToken; function isNodeArray(array) { @@ -9285,13 +9463,13 @@ var ts; ts.isImportOrExportSpecifier = isImportOrExportSpecifier; function isTypeOnlyImportOrExportDeclaration(node) { switch (node.kind) { - case 265: - case 270: + case 266: + case 271: return node.parent.parent.isTypeOnly; - case 263: + case 264: return node.parent.isTypeOnly; - case 262: - case 260: + case 263: + case 261: return node.isTypeOnly; default: return false; @@ -9306,10 +9484,10 @@ var ts; return ts.isIdentifier(node) && (node.autoGenerateFlags & 7) > 0; } ts.isGeneratedIdentifier = isGeneratedIdentifier; - function isPrivateIdentifierPropertyDeclaration(node) { - return ts.isPropertyDeclaration(node) && ts.isPrivateIdentifier(node.name); + function isPrivateIdentifierClassElementDeclaration(node) { + return (ts.isPropertyDeclaration(node) || isMethodOrAccessor(node)) && ts.isPrivateIdentifier(node.name); } - ts.isPrivateIdentifierPropertyDeclaration = isPrivateIdentifierPropertyDeclaration; + ts.isPrivateIdentifierClassElementDeclaration = isPrivateIdentifierClassElementDeclaration; function isPrivateIdentifierPropertyAccessExpression(node) { return ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name); } @@ -9327,17 +9505,18 @@ var ts; case 121: case 142: case 123: + case 156: return true; } return false; } ts.isModifierKind = isModifierKind; function isParameterPropertyModifier(kind) { - return !!(ts.modifierToFlag(kind) & 92); + return !!(ts.modifierToFlag(kind) & 16476); } ts.isParameterPropertyModifier = isParameterPropertyModifier; function isClassMemberModifier(idToken) { - return isParameterPropertyModifier(idToken) || idToken === 123; + return isParameterPropertyModifier(idToken) || idToken === 123 || idToken === 156; } ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { @@ -9346,7 +9525,7 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 157 + return kind === 158 || kind === 78; } ts.isEntityName = isEntityName; @@ -9356,18 +9535,18 @@ var ts; || kind === 79 || kind === 10 || kind === 8 - || kind === 158; + || kind === 159; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; return kind === 78 - || kind === 196 - || kind === 197; + || kind === 197 + || kind === 198; } ts.isBindingName = isBindingName; function isFunctionLike(node) { - return node && isFunctionLikeKind(node.kind); + return !!node && isFunctionLikeKind(node.kind); } ts.isFunctionLike = isFunctionLike; function isFunctionLikeDeclaration(node) { @@ -9376,13 +9555,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 251: - case 165: + case 252: case 166: case 167: case 168: - case 208: + case 169: case 209: + case 210: return true; default: return false; @@ -9390,14 +9569,14 @@ var ts; } function isFunctionLikeKind(kind) { switch (kind) { - case 164: - case 169: - case 313: + case 165: case 170: + case 315: case 171: - case 174: - case 308: + case 172: case 175: + case 309: + case 176: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -9410,28 +9589,28 @@ var ts; ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock; function isClassElement(node) { var kind = node.kind; - return kind === 166 - || kind === 163 - || kind === 165 - || kind === 167 + return kind === 167 + || kind === 164 + || kind === 166 || kind === 168 - || kind === 171 - || kind === 229; + || kind === 169 + || kind === 172 + || kind === 230; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 252 || node.kind === 221); + return node && (node.kind === 253 || node.kind === 222); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 167 || node.kind === 168); + return node && (node.kind === 168 || node.kind === 169); } ts.isAccessor = isAccessor; function isMethodOrAccessor(node) { switch (node.kind) { - case 165: - case 167: + case 166: case 168: + case 169: return true; default: return false; @@ -9440,11 +9619,11 @@ var ts; ts.isMethodOrAccessor = isMethodOrAccessor; function isTypeElement(node) { var kind = node.kind; - return kind === 170 - || kind === 169 - || kind === 162 - || kind === 164 - || kind === 171; + return kind === 171 + || kind === 170 + || kind === 163 + || kind === 165 + || kind === 172; } ts.isTypeElement = isTypeElement; function isClassOrTypeElement(node) { @@ -9453,12 +9632,12 @@ var ts; ts.isClassOrTypeElement = isClassOrTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 288 - || kind === 289 + return kind === 289 || kind === 290 - || kind === 165 - || kind === 167 - || kind === 168; + || kind === 291 + || kind === 166 + || kind === 168 + || kind === 169; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; function isTypeNode(node) { @@ -9467,8 +9646,8 @@ var ts; ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 174: case 175: + case 176: return true; } return false; @@ -9477,29 +9656,29 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 197 - || kind === 196; + return kind === 198 + || kind === 197; } return false; } ts.isBindingPattern = isBindingPattern; function isAssignmentPattern(node) { var kind = node.kind; - return kind === 199 - || kind === 200; + return kind === 200 + || kind === 201; } ts.isAssignmentPattern = isAssignmentPattern; function isArrayBindingElement(node) { var kind = node.kind; - return kind === 198 - || kind === 222; + return kind === 199 + || kind === 223; } ts.isArrayBindingElement = isArrayBindingElement; function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 249: - case 160: - case 198: + case 250: + case 161: + case 199: return true; } return false; @@ -9512,8 +9691,8 @@ var ts; ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 196: - case 200: + case 197: + case 201: return true; } return false; @@ -9521,8 +9700,8 @@ var ts; ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 197: - case 199: + case 198: + case 200: return true; } return false; @@ -9530,25 +9709,25 @@ var ts; ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { var kind = node.kind; - return kind === 201 - || kind === 157 - || kind === 195; + return kind === 202 + || kind === 158 + || kind === 196; } ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 201 - || kind === 157; + return kind === 202 + || kind === 158; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { + case 276: case 275: - case 274: - case 203: case 204: case 205: - case 161: + case 206: + case 162: return true; default: return false; @@ -9556,12 +9735,12 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 203 || node.kind === 204; + return node.kind === 204 || node.kind === 205; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 218 + return kind === 219 || kind === 14; } ts.isTemplateLiteral = isTemplateLiteral; @@ -9571,33 +9750,33 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 201: case 202: - case 204: case 203: - case 273: - case 274: - case 277: case 205: - case 199: - case 207: + case 204: + case 274: + case 275: + case 278: + case 206: case 200: - case 221: case 208: + case 201: + case 222: + case 209: case 78: case 13: case 8: case 9: case 10: case 14: - case 218: + case 219: case 94: case 103: case 107: case 109: case 105: - case 225: case 226: + case 227: case 99: return true; default: @@ -9610,13 +9789,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 214: case 215: - case 210: + case 216: case 211: case 212: case 213: - case 206: + case 214: + case 207: return true; default: return isLeftHandSideExpressionKind(kind); @@ -9624,9 +9803,9 @@ var ts; } function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 215: + case 216: return true; - case 214: + case 215: return expr.operator === 45 || expr.operator === 46; default: @@ -9640,15 +9819,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 217: - case 219: - case 209: - case 216: + case 218: case 220: - case 224: - case 222: - case 337: - case 336: + case 210: + case 217: + case 221: + case 225: + case 223: + case 341: + case 340: return true; default: return isUnaryExpressionKind(kind); @@ -9656,8 +9835,8 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 206 - || kind === 224; + return kind === 207 + || kind === 225; } ts.isAssertionExpression = isAssertionExpression; function isNotEmittedOrPartiallyEmittedNode(node) { @@ -9667,13 +9846,13 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 237: case 238: case 239: - case 235: + case 240: case 236: + case 237: return true; - case 245: + case 246: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -9696,7 +9875,7 @@ var ts; } ts.isExternalModuleIndicator = isExternalModuleIndicator; function isForInOrOfStatement(node) { - return node.kind === 238 || node.kind === 239; + return node.kind === 239 || node.kind === 240; } ts.isForInOrOfStatement = isForInOrOfStatement; function isConciseBody(node) { @@ -9715,109 +9894,109 @@ var ts; ts.isForInitializer = isForInitializer; function isModuleBody(node) { var kind = node.kind; - return kind === 257 - || kind === 256 + return kind === 258 + || kind === 257 || kind === 78; } ts.isModuleBody = isModuleBody; function isNamespaceBody(node) { var kind = node.kind; - return kind === 257 - || kind === 256; + return kind === 258 + || kind === 257; } ts.isNamespaceBody = isNamespaceBody; function isJSDocNamespaceBody(node) { var kind = node.kind; return kind === 78 - || kind === 256; + || kind === 257; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; function isNamedImportBindings(node) { var kind = node.kind; - return kind === 264 - || kind === 263; + return kind === 265 + || kind === 264; } ts.isNamedImportBindings = isNamedImportBindings; function isModuleOrEnumDeclaration(node) { - return node.kind === 256 || node.kind === 255; + return node.kind === 257 || node.kind === 256; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 209 - || kind === 198 + return kind === 210 + || kind === 199 + || kind === 253 + || kind === 222 + || kind === 167 + || kind === 256 + || kind === 292 + || kind === 271 || kind === 252 - || kind === 221 + || kind === 209 + || kind === 168 + || kind === 263 + || kind === 261 + || kind === 266 + || kind === 254 + || kind === 281 || kind === 166 - || kind === 255 - || kind === 291 - || kind === 270 - || kind === 251 - || kind === 208 - || kind === 167 - || kind === 262 - || kind === 260 - || kind === 265 - || kind === 253 - || kind === 280 || kind === 165 + || kind === 257 + || kind === 260 + || kind === 264 + || kind === 270 + || kind === 161 + || kind === 289 || kind === 164 - || kind === 256 - || kind === 259 - || kind === 263 - || kind === 269 - || kind === 160 - || kind === 288 || kind === 163 - || kind === 162 - || kind === 168 - || kind === 289 - || kind === 254 - || kind === 159 - || kind === 249 - || kind === 331 - || kind === 324 - || kind === 333; + || kind === 169 + || kind === 290 + || kind === 255 + || kind === 160 + || kind === 250 + || kind === 335 + || kind === 328 + || kind === 337; } function isDeclarationStatementKind(kind) { - return kind === 251 - || kind === 271 - || kind === 252 + return kind === 252 + || kind === 272 || kind === 253 || kind === 254 || kind === 255 || kind === 256 + || kind === 257 + || kind === 262 || kind === 261 - || kind === 260 + || kind === 268 || kind === 267 - || kind === 266 - || kind === 259; + || kind === 260; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 241 + return kind === 242 + || kind === 241 + || kind === 249 + || kind === 236 + || kind === 234 + || kind === 232 + || kind === 239 || kind === 240 - || kind === 248 + || kind === 238 || kind === 235 + || kind === 246 + || kind === 243 + || kind === 245 + || kind === 247 + || kind === 248 || kind === 233 - || kind === 231 - || kind === 238 - || kind === 239 || kind === 237 - || kind === 234 - || kind === 245 - || kind === 242 || kind === 244 - || kind === 246 - || kind === 247 - || kind === 232 - || kind === 236 - || kind === 243 - || kind === 335 || kind === 339 - || kind === 338; + || kind === 343 + || kind === 342; } function isDeclaration(node) { - if (node.kind === 159) { - return (node.parent && node.parent.kind !== 330) || ts.isInJSFile(node); + if (node.kind === 160) { + return (node.parent && node.parent.kind !== 334) || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -9838,10 +10017,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 230) + if (node.kind !== 231) return false; if (node.parent !== undefined) { - if (node.parent.kind === 247 || node.parent.kind === 287) { + if (node.parent.kind === 248 || node.parent.kind === 288) { return false; } } @@ -9851,13 +10030,13 @@ var ts; var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) - || kind === 230; + || kind === 231; } ts.isStatementOrBlock = isStatementOrBlock; function isModuleReference(node) { var kind = node.kind; - return kind === 272 - || kind === 157 + return kind === 273 + || kind === 158 || kind === 78; } ts.isModuleReference = isModuleReference; @@ -9865,60 +10044,66 @@ var ts; var kind = node.kind; return kind === 107 || kind === 78 - || kind === 201; + || kind === 202; } ts.isJsxTagNameExpression = isJsxTagNameExpression; function isJsxChild(node) { var kind = node.kind; - return kind === 273 - || kind === 283 - || kind === 274 + return kind === 274 + || kind === 284 + || kind === 275 || kind === 11 - || kind === 277; + || kind === 278; } ts.isJsxChild = isJsxChild; function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 280 - || kind === 282; + return kind === 281 + || kind === 283; } ts.isJsxAttributeLike = isJsxAttributeLike; function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 10 - || kind === 283; + || kind === 284; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 275 - || kind === 274; + return kind === 276 + || kind === 275; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 284 - || kind === 285; + return kind === 285 + || kind === 286; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; function isJSDocNode(node) { - return node.kind >= 301 && node.kind <= 333; + return node.kind >= 302 && node.kind <= 337; } ts.isJSDocNode = isJSDocNode; function isJSDocCommentContainingNode(node) { - return node.kind === 311 || node.kind === 310 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + return node.kind === 312 + || node.kind === 311 + || node.kind === 313 + || node.kind === 316 + || isJSDocTag(node) + || ts.isJSDocTypeLiteral(node) + || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; function isJSDocTag(node) { - return node.kind >= 314 && node.kind <= 333; + return node.kind >= 317 && node.kind <= 337; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { - return node.kind === 168; + return node.kind === 169; } ts.isSetAccessor = isSetAccessor; function isGetAccessor(node) { - return node.kind === 167; + return node.kind === 168; } ts.isGetAccessor = isGetAccessor; function hasJSDocNodes(node) { @@ -9936,13 +10121,13 @@ var ts; ts.hasInitializer = hasInitializer; function hasOnlyExpressionInitializer(node) { switch (node.kind) { - case 249: - case 160: - case 198: - case 162: + case 250: + case 161: + case 199: case 163: - case 288: - case 291: + case 164: + case 289: + case 292: return true; default: return false; @@ -9950,11 +10135,11 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - return node.kind === 280 || node.kind === 282 || isObjectLiteralElementLike(node); + return node.kind === 281 || node.kind === 283 || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; function isTypeReferenceType(node) { - return node.kind === 173 || node.kind === 223; + return node.kind === 174 || node.kind === 224; } ts.isTypeReferenceType = isTypeReferenceType; var MAX_SMI_X86 = 1073741823; @@ -10175,7 +10360,9 @@ var ts; } ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + return oldResolution.resolvedFileName === newResolution.resolvedFileName + && oldResolution.primary === newResolution.primary + && oldResolution.originalPath === newResolution.originalPath; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { @@ -10209,7 +10396,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 297) { + while (node && node.kind !== 298) { node = node.parent; } return node; @@ -10217,11 +10404,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 230: - case 258: - case 237: + case 231: + case 259: case 238: case 239: + case 240: return true; } return false; @@ -10371,10 +10558,10 @@ var ts; if (includeJsDoc && ts.hasJSDocNodes(node)) { return getTokenPosOfNode(node.jsDoc[0], sourceFile); } - if (node.kind === 334 && node._children.length > 0) { + if (node.kind === 338 && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, false, false, isInJSDoc(node)); } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { @@ -10485,9 +10672,11 @@ var ts; DataView: ["setBigInt64", "setBigUint64", "getBigInt64", "getBigUint64"], RelativeTimeFormat: ["format", "formatToParts", "resolvedOptions"] }, - esnext: { + es2021: { PromiseConstructor: ["any"], - String: ["replaceAll"], + String: ["replaceAll"] + }, + esnext: { NumberFormat: ["formatToParts"] } }; @@ -10564,7 +10753,7 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 249 && node.parent.kind === 287; + return node.kind === 250 && node.parent.kind === 288; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { @@ -10588,11 +10777,11 @@ var ts; } ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { - return node && node.kind === 256 && (!node.body); + return !!node && node.kind === 257 && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 297 || - node.kind === 256 || + return node.kind === 298 || + node.kind === 257 || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -10606,16 +10795,17 @@ var ts; ts.isExternalModuleAugmentation = isExternalModuleAugmentation; function isModuleAugmentationExternal(node) { switch (node.parent.kind) { - case 297: + case 298: return ts.isExternalModule(node.parent); - case 257: + case 258: return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } ts.isModuleAugmentationExternal = isModuleAugmentationExternal; function getNonAugmentationDeclaration(symbol) { - return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); + var _a; + return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); } ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration; function isEffectiveExternalModule(node, compilerOptions) { @@ -10652,22 +10842,22 @@ var ts; ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile; function isBlockScope(node, parentNode) { switch (node.kind) { - case 297: - case 258: - case 287: - case 256: - case 237: + case 298: + case 259: + case 288: + case 257: case 238: case 239: - case 166: - case 165: + case 240: case 167: + case 166: case 168: - case 251: - case 208: + case 169: + case 252: case 209: + case 210: return true; - case 230: + case 231: return !ts.isFunctionLike(parentNode); } return false; @@ -10675,9 +10865,9 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 324: - case 331: - case 313: + case 328: + case 335: + case 315: return true; default: ts.assertType(node); @@ -10687,25 +10877,25 @@ var ts; ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { - case 169: case 170: - case 164: case 171: - case 174: + case 165: + case 172: case 175: - case 308: - case 252: - case 221: + case 176: + case 309: case 253: + case 222: case 254: - case 330: - case 251: - case 165: + case 255: + case 334: + case 252: case 166: case 167: case 168: - case 208: + case 169: case 209: + case 210: return true; default: ts.assertType(node); @@ -10715,8 +10905,8 @@ var ts; ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { + case 262: case 261: - case 260: return true; default: return false; @@ -10725,15 +10915,15 @@ var ts; ts.isAnyImportSyntax = isAnyImportSyntax; function isLateVisibilityPaintedStatement(node) { switch (node.kind) { + case 262: case 261: - case 260: - case 232: - case 252: - case 251: - case 256: - case 254: + case 233: case 253: + case 252: + case 257: case 255: + case 254: + case 256: return true; default: return false; @@ -10761,7 +10951,7 @@ var ts; } ts.getNameFromIndexInfo = getNameFromIndexInfo; function isComputedNonLiteralName(name) { - return name.kind === 158 && !isStringOrNumericLiteralLike(name.expression); + return name.kind === 159 && !isStringOrNumericLiteralLike(name.expression); } ts.isComputedNonLiteralName = isComputedNonLiteralName; function getTextOfPropertyName(name) { @@ -10773,7 +10963,7 @@ var ts; case 8: case 14: return ts.escapeLeadingUnderscores(name.text); - case 158: + case 159: if (isStringOrNumericLiteralLike(name.expression)) return ts.escapeLeadingUnderscores(name.expression.text); return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames"); @@ -10789,9 +10979,9 @@ var ts; case 79: case 78: return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); - case 157: + case 158: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 201: + case 202: if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) { return entityNameToString(name.expression) + "." + entityNameToString(name.name); } @@ -10877,7 +11067,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 230) { + if (node.body && node.body.kind === 231) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -10889,34 +11079,34 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 297: + case 298: var pos_1 = ts.skipTrivia(sourceFile.text, 0, false); if (pos_1 === sourceFile.text.length) { return ts.createTextSpan(0, 0); } return getSpanOfTokenAtPosition(sourceFile, pos_1); - case 249: - case 198: - case 252: - case 221: + case 250: + case 199: case 253: + case 222: + case 254: + case 257: case 256: - case 255: - case 291: - case 251: - case 208: - case 165: - case 167: + case 292: + case 252: + case 209: + case 166: case 168: - case 254: + case 169: + case 255: + case 164: case 163: - case 162: errorNode = node.name; break; - case 209: + case 210: return getErrorSpanForArrowFunction(sourceFile, node); - case 284: case 285: + case 286: var start = ts.skipTrivia(sourceFile.text, node.pos); var end = node.statements.length > 0 ? node.statements[0].pos : node.end; return ts.createTextSpanFromBounds(start, end); @@ -10965,11 +11155,11 @@ var ts; } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 203 && n.expression.kind === 105; + return n.kind === 204 && n.expression.kind === 105; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 203 && n.expression.kind === 99; + return n.kind === 204 && n.expression.kind === 99; } ts.isImportCall = isImportCall; function isImportMeta(n) { @@ -10983,7 +11173,7 @@ var ts; } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { - return node.kind === 233 + return node.kind === 234 && node.expression.kind === 10; } ts.isPrologueDirective = isPrologueDirective; @@ -11011,11 +11201,12 @@ var ts; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 160 || - node.kind === 159 || - node.kind === 208 || + var commentRanges = (node.kind === 161 || + node.kind === 160 || node.kind === 209 || - node.kind === 207) ? + node.kind === 210 || + node.kind === 208 || + node.kind === 250) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); return ts.filter(commentRanges, function (comment) { @@ -11030,7 +11221,7 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (172 <= node.kind && node.kind <= 195) { + if (173 <= node.kind && node.kind <= 196) { return true; } switch (node.kind) { @@ -11046,63 +11237,63 @@ var ts; case 141: return true; case 113: - return node.parent.kind !== 212; - case 223: + return node.parent.kind !== 213; + case 224: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 159: - return node.parent.kind === 190 || node.parent.kind === 185; + case 160: + return node.parent.kind === 191 || node.parent.kind === 186; case 78: - if (node.parent.kind === 157 && node.parent.right === node) { + if (node.parent.kind === 158 && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 201 && node.parent.name === node) { + else if (node.parent.kind === 202 && node.parent.name === node) { node = node.parent; } - ts.Debug.assert(node.kind === 78 || node.kind === 157 || node.kind === 201, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); - case 157: - case 201: + ts.Debug.assert(node.kind === 78 || node.kind === 158 || node.kind === 202, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + case 158: + case 202: case 107: { var parent = node.parent; - if (parent.kind === 176) { + if (parent.kind === 177) { return false; } - if (parent.kind === 195) { + if (parent.kind === 196) { return !parent.isTypeOf; } - if (172 <= parent.kind && parent.kind <= 195) { + if (173 <= parent.kind && parent.kind <= 196) { return true; } switch (parent.kind) { - case 223: + case 224: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 159: + case 160: return node === parent.constraint; - case 330: + case 334: return node === parent.constraint; + case 164: case 163: - case 162: - case 160: - case 249: + case 161: + case 250: return node === parent.type; - case 251: - case 208: + case 252: case 209: + case 210: + case 167: case 166: case 165: - case 164: - case 167: case 168: - return node === parent.type; case 169: + return node === parent.type; case 170: case 171: + case 172: return node === parent.type; - case 206: + case 207: return node === parent.type; - case 203: case 204: - return ts.contains(parent.typeArguments, node); case 205: + return ts.contains(parent.typeArguments, node); + case 206: return false; } } @@ -11124,23 +11315,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 242: + case 243: return visitor(node); - case 258: - case 230: - case 234: + case 259: + case 231: case 235: case 236: case 237: case 238: case 239: - case 243: + case 240: case 244: - case 284: - case 285: case 245: - case 247: - case 287: + case 285: + case 286: + case 246: + case 248: + case 288: return ts.forEachChild(node, traverse); } } @@ -11150,21 +11341,21 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 219: + case 220: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 255: - case 253: case 256: case 254: + case 257: + case 255: return; default: if (ts.isFunctionLike(node)) { - if (node.name && node.name.kind === 158) { + if (node.name && node.name.kind === 159) { traverse(node.name.expression); return; } @@ -11177,10 +11368,10 @@ var ts; } ts.forEachYieldExpression = forEachYieldExpression; function getRestParameterElementType(node) { - if (node && node.kind === 178) { + if (node && node.kind === 179) { return node.elementType; } - else if (node && node.kind === 173) { + else if (node && node.kind === 174) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -11190,12 +11381,12 @@ var ts; ts.getRestParameterElementType = getRestParameterElementType; function getMembersOfDeclaration(node) { switch (node.kind) { + case 254: case 253: - case 252: - case 221: - case 177: + case 222: + case 178: return node.members; - case 200: + case 201: return node.properties; } } @@ -11203,14 +11394,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 198: - case 291: - case 160: - case 288: - case 163: - case 162: + case 199: + case 292: + case 161: case 289: - case 249: + case 164: + case 163: + case 290: + case 250: return true; } } @@ -11222,8 +11413,8 @@ var ts; } ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { - return node.parent.kind === 250 - && node.parent.parent.kind === 232; + return node.parent.kind === 251 + && node.parent.parent.kind === 233; } ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; function isValidESSymbolDeclaration(node) { @@ -11234,13 +11425,13 @@ var ts; ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 165: - case 164: case 166: + case 165: case 167: case 168: - case 251: - case 208: + case 169: + case 252: + case 209: return true; } return false; @@ -11251,7 +11442,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 245) { + if (node.statement.kind !== 246) { return node.statement; } node = node.statement; @@ -11259,17 +11450,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 230 && ts.isFunctionLike(node.parent); + return node && node.kind === 231 && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 165 && node.parent.kind === 200; + return node && node.kind === 166 && node.parent.kind === 201; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 165 && - (node.parent.kind === 200 || - node.parent.kind === 221); + return node.kind === 166 && + (node.parent.kind === 201 || + node.parent.kind === 222); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -11282,7 +11473,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return objectLiteral.properties.filter(function (property) { - if (property.kind === 288) { + if (property.kind === 289) { var propName = getTextOfPropertyName(property.name); return key === propName || (!!key2 && key2 === propName); } @@ -11331,46 +11522,46 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { - ts.Debug.assert(node.kind !== 297); + ts.Debug.assert(node.kind !== 298); while (true) { node = node.parent; if (!node) { return ts.Debug.fail(); } switch (node.kind) { - case 158: + case 159: if (ts.isClassLike(node.parent.parent)) { return node; } node = node.parent; break; - case 161: - if (node.parent.kind === 160 && ts.isClassElement(node.parent.parent)) { + case 162: + if (node.parent.kind === 161 && ts.isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (ts.isClassElement(node.parent)) { node = node.parent; } break; - case 209: + case 210: if (!includeArrowFunctions) { continue; } - case 251: - case 208: - case 256: - case 163: - case 162: - case 165: + case 252: + case 209: + case 257: case 164: + case 163: case 166: + case 165: case 167: case 168: case 169: case 170: case 171: - case 255: - case 297: + case 172: + case 256: + case 298: return node; } } @@ -11388,9 +11579,9 @@ var ts; var container = getThisContainer(node, false); if (container) { switch (container.kind) { - case 166: - case 251: - case 208: + case 167: + case 252: + case 209: return container; } } @@ -11404,25 +11595,25 @@ var ts; return node; } switch (node.kind) { - case 158: + case 159: node = node.parent; break; - case 251: - case 208: + case 252: case 209: + case 210: if (!stopOnFunctions) { continue; } - case 163: - case 162: - case 165: case 164: + case 163: case 166: + case 165: case 167: case 168: + case 169: return node; - case 161: - if (node.parent.kind === 160 && ts.isClassElement(node.parent.parent)) { + case 162: + if (node.parent.kind === 161 && ts.isClassElement(node.parent.parent)) { node = node.parent.parent; } else if (ts.isClassElement(node.parent)) { @@ -11434,14 +11625,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 208 || func.kind === 209) { + if (func.kind === 209 || func.kind === 210) { var prev = func; var parent = func.parent; - while (parent.kind === 207) { + while (parent.kind === 208) { prev = parent; parent = parent.parent; } - if (parent.kind === 203 && parent.expression === prev) { + if (parent.kind === 204 && parent.expression === prev) { return parent; } } @@ -11454,13 +11645,13 @@ var ts; ts.isSuperOrSuperProperty = isSuperOrSuperProperty; function isSuperProperty(node) { var kind = node.kind; - return (kind === 201 || kind === 202) + return (kind === 202 || kind === 203) && node.expression.kind === 105; } ts.isSuperProperty = isSuperProperty; function isThisProperty(node) { var kind = node.kind; - return (kind === 201 || kind === 202) + return (kind === 202 || kind === 203) && node.expression.kind === 107; } ts.isThisProperty = isThisProperty; @@ -11469,16 +11660,24 @@ var ts; return !!node && ts.isVariableDeclaration(node) && ((_a = node.initializer) === null || _a === void 0 ? void 0 : _a.kind) === 107; } ts.isThisInitializedDeclaration = isThisInitializedDeclaration; + function isThisInitializedObjectBindingExpression(node) { + return !!node + && (ts.isShorthandPropertyAssignment(node) || ts.isPropertyAssignment(node)) + && ts.isBinaryExpression(node.parent.parent) + && node.parent.parent.operatorToken.kind === 62 + && node.parent.parent.right.kind === 107; + } + ts.isThisInitializedObjectBindingExpression = isThisInitializedObjectBindingExpression; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 173: + case 174: return node.typeName; - case 223: + case 224: return isEntityNameExpression(node.expression) ? node.expression : undefined; case 78: - case 157: + case 158: return node; } return undefined; @@ -11486,10 +11685,10 @@ var ts; ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { switch (node.kind) { - case 205: + case 206: return node.tag; + case 276: case 275: - case 274: return node.tagName; default: return node.expression; @@ -11501,21 +11700,21 @@ var ts; return false; } switch (node.kind) { - case 252: + case 253: return true; - case 163: - return parent.kind === 252; - case 167: + case 164: + return parent.kind === 253; case 168: - case 165: + case 169: + case 166: return node.body !== undefined - && parent.kind === 252; - case 160: + && parent.kind === 253; + case 161: return parent.body !== undefined - && (parent.kind === 166 - || parent.kind === 165 - || parent.kind === 168) - && grandparent.kind === 252; + && (parent.kind === 167 + || parent.kind === 166 + || parent.kind === 169) + && grandparent.kind === 253; } return false; } @@ -11531,10 +11730,10 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { - case 252: + case 253: return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); - case 165: - case 168: + case 166: + case 169: return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); default: return false; @@ -11543,9 +11742,9 @@ var ts; ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 275 || - parent.kind === 274 || - parent.kind === 276) { + if (parent.kind === 276 || + parent.kind === 275 || + parent.kind === 277) { return parent.tagName === node; } return false; @@ -11558,44 +11757,44 @@ var ts; case 109: case 94: case 13: - case 199: case 200: case 201: case 202: case 203: case 204: case 205: - case 224: case 206: case 225: case 207: + case 226: case 208: - case 221: case 209: - case 212: + case 222: case 210: + case 213: case 211: - case 214: + case 212: case 215: case 216: case 217: - case 220: case 218: - case 222: - case 273: - case 274: - case 277: + case 221: case 219: - case 213: - case 226: + case 223: + case 274: + case 275: + case 278: + case 220: + case 214: + case 227: return true; - case 157: - while (node.parent.kind === 157) { + case 158: + while (node.parent.kind === 158) { node = node.parent; } - return node.parent.kind === 176 || isJSXTagName(node); + return node.parent.kind === 177 || isJSXTagName(node); case 78: - if (node.parent.kind === 176 || isJSXTagName(node)) { + if (node.parent.kind === 177 || isJSXTagName(node)) { return true; } case 8: @@ -11612,49 +11811,49 @@ var ts; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 249: - case 160: + case 250: + case 161: + case 164: case 163: - case 162: - case 291: - case 288: - case 198: + case 292: + case 289: + case 199: return parent.initializer === node; - case 233: case 234: case 235: case 236: - case 242: + case 237: case 243: case 244: - case 284: - case 246: + case 245: + case 285: + case 247: return parent.expression === node; - case 237: + case 238: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 250) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 251) || forStatement.condition === node || forStatement.incrementor === node; - case 238: case 239: + case 240: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 250) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 251) || forInStatement.expression === node; - case 206: - case 224: + case 207: + case 225: return node === parent.expression; - case 228: + case 229: return node === parent.expression; - case 158: + case 159: return node === parent.expression; - case 161: + case 162: + case 284: case 283: - case 282: - case 290: + case 291: return true; - case 223: + case 224: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 289: + case 290: return parent.objectAssignmentInitializer === node; default: return isExpressionNode(parent); @@ -11662,14 +11861,18 @@ var ts; } ts.isInExpressionContext = isInExpressionContext; function isPartOfTypeQuery(node) { - while (node.kind === 157 || node.kind === 78) { + while (node.kind === 158 || node.kind === 78) { node = node.parent; } - return node.kind === 176; + return node.kind === 177; } ts.isPartOfTypeQuery = isPartOfTypeQuery; + function isNamespaceReexportDeclaration(node) { + return ts.isNamespaceExport(node) && !!node.parent.moduleSpecifier; + } + ts.isNamespaceReexportDeclaration = isNamespaceReexportDeclaration; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 260 && node.moduleReference.kind === 272; + return node.kind === 261 && node.moduleReference.kind === 273; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -11678,12 +11881,11 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function getExternalModuleRequireArgument(node) { - return isRequireVariableDeclaration(node, true) - && getLeftmostAccessExpression(node.initializer).arguments[0]; + return isRequireVariableDeclaration(node) && getLeftmostAccessExpression(node.initializer).arguments[0]; } ts.getExternalModuleRequireArgument = getExternalModuleRequireArgument; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 260 && node.moduleReference.kind !== 272; + return node.kind === 261 && node.moduleReference.kind !== 273; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJS(file) { @@ -11719,7 +11921,7 @@ var ts; } ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, requireStringLiteralLikeArgument) { - if (callExpression.kind !== 203) { + if (callExpression.kind !== 204) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; @@ -11733,18 +11935,17 @@ var ts; return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; - function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) { - if (node.kind === 198) { + function isRequireVariableDeclaration(node) { + if (node.kind === 199) { node = node.parent.parent; } - return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), requireStringLiteralLikeArgument); + return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), true); } ts.isRequireVariableDeclaration = isRequireVariableDeclaration; - function isRequireVariableStatement(node, requireStringLiteralLikeArgument) { - if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; } + function isRequireVariableStatement(node) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 - && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); }); + && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl); }); } ts.isRequireVariableStatement = isRequireVariableStatement; function isSingleOrDoubleQuote(charCode) { @@ -11800,11 +12001,11 @@ var ts; function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); - return e.kind === 208 || e.kind === 209 ? initializer : undefined; + return e.kind === 209 || e.kind === 210 ? initializer : undefined; } - if (initializer.kind === 208 || - initializer.kind === 221 || - initializer.kind === 209) { + if (initializer.kind === 209 || + initializer.kind === 222 || + initializer.kind === 210) { return initializer; } if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { @@ -11903,8 +12104,7 @@ var ts; } ts.isLiteralLikeAccess = isLiteralLikeAccess; function isLiteralLikeElementAccess(node) { - return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) || - isWellKnownSymbolSyntactically(node.argumentExpression)); + return ts.isElementAccessExpression(node) && isStringOrNumericLiteralLike(node.argumentExpression); } ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess; function isBindableStaticAccessExpression(node, excludeThisKeyword) { @@ -11976,9 +12176,6 @@ var ts; return ts.escapeLeadingUnderscores(name.text); } } - if (ts.isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) { - return getPropertyNameForKnownSymbolName(ts.idText(node.argumentExpression.name)); - } return undefined; } ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName; @@ -12023,7 +12220,7 @@ var ts; ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { return isInJSFile(expr) && - expr.parent && expr.parent.kind === 233 && + expr.parent && expr.parent.kind === 234 && (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) && !!ts.getJSDocTypeTag(expr.parent); } @@ -12043,23 +12240,37 @@ var ts; return false; } var decl = symbol.valueDeclaration; - return decl.kind === 251 || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + return decl.kind === 252 || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); } ts.isFunctionSymbol = isFunctionSymbol; + function tryGetModuleSpecifierFromDeclaration(node) { + var _a, _b, _c; + switch (node.kind) { + case 250: + return node.initializer.arguments[0].text; + case 262: + return (_a = ts.tryCast(node.moduleSpecifier, ts.isStringLiteralLike)) === null || _a === void 0 ? void 0 : _a.text; + case 261: + return (_c = ts.tryCast((_b = ts.tryCast(node.moduleReference, ts.isExternalModuleReference)) === null || _b === void 0 ? void 0 : _b.expression, ts.isStringLiteralLike)) === null || _c === void 0 ? void 0 : _c.text; + default: + ts.Debug.assertNever(node); + } + } + ts.tryGetModuleSpecifierFromDeclaration = tryGetModuleSpecifierFromDeclaration; function importFromModuleSpecifier(node) { return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent); } ts.importFromModuleSpecifier = importFromModuleSpecifier; function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { - case 261: - case 267: + case 262: + case 268: return node.parent; - case 272: + case 273: return node.parent.parent; - case 203: + case 204: return isImportCall(node.parent) || isRequireCall(node.parent, false) ? node.parent : undefined; - case 191: + case 192: ts.Debug.assert(ts.isStringLiteral(node)); return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: @@ -12069,15 +12280,17 @@ var ts; ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { - case 261: - case 267: + case 262: + case 268: return node.moduleSpecifier; - case 260: - return node.moduleReference.kind === 272 ? node.moduleReference.expression : undefined; - case 195: + case 261: + return node.moduleReference.kind === 273 ? node.moduleReference.expression : undefined; + case 196: return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; - case 203: + case 204: return node.arguments[0]; + case 257: + return node.name.kind === 10 ? node.name : undefined; default: return ts.Debug.assertNever(node); } @@ -12085,11 +12298,11 @@ var ts; ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { switch (node.kind) { - case 261: + case 262: return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); - case 260: + case 261: return node; - case 267: + case 268: return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport); default: return ts.Debug.assertNever(node); @@ -12097,7 +12310,7 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 261 && !!node.importClause && !!node.importClause.name; + return node.kind === 262 && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function forEachImportClauseDeclaration(node, action) { @@ -12118,13 +12331,13 @@ var ts; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 160: + case 161: + case 166: case 165: - case 164: + case 290: case 289: - case 288: + case 164: case 163: - case 162: return node.questionToken !== undefined; } } @@ -12138,7 +12351,7 @@ var ts; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 331 || node.kind === 324 || node.kind === 325; + return node.kind === 335 || node.kind === 328 || node.kind === 329; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -12163,12 +12376,12 @@ var ts; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { - case 232: + case 233: var v = getSingleVariableOfVariableStatement(node); return v && v.initializer; - case 163: + case 164: return node.initializer; - case 288: + case 289: return node.initializer; } } @@ -12180,7 +12393,7 @@ var ts; function getNestedModuleDeclaration(node) { return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 256 + node.body.kind === 257 ? node.body : undefined; } @@ -12194,11 +12407,11 @@ var ts; if (ts.hasJSDocNodes(node)) { result = ts.append(result, ts.last(node.jsDoc)); } - if (node.kind === 160) { + if (node.kind === 161) { result = ts.addRange(result, (noCache ? ts.getJSDocParameterTagsNoCache : ts.getJSDocParameterTags)(node)); break; } - if (node.kind === 159) { + if (node.kind === 160) { result = ts.addRange(result, (noCache ? ts.getJSDocTypeParameterTagsNoCache : ts.getJSDocTypeParameterTags)(node)); break; } @@ -12209,10 +12422,11 @@ var ts; ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; function getNextJSDocCommentLocation(node) { var parent = node.parent; - if (parent.kind === 288 || - parent.kind === 266 || - parent.kind === 163 || - parent.kind === 233 && node.kind === 201 || + if (parent.kind === 289 || + parent.kind === 267 || + parent.kind === 164 || + parent.kind === 234 && node.kind === 202 || + parent.kind === 243 || getNestedModuleDeclaration(parent) || ts.isBinaryExpression(node) && node.operatorToken.kind === 62) { return parent; @@ -12291,7 +12505,7 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 309; + return node.dotDotDotToken !== undefined || !!type && type.kind === 310; } ts.isRestParameter = isRestParameter; function hasTypeArguments(node) { @@ -12302,31 +12516,34 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 216: + case 217: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? binaryOperator === 62 || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? 1 : 2 : 0; - case 214: case 215: + case 216: var unaryOperator = parent.operator; return unaryOperator === 45 || unaryOperator === 46 ? 2 : 0; - case 238: case 239: + case 240: return parent.initializer === node ? 1 : 0; - case 207: - case 199: - case 220: - case 225: + case 208: + case 200: + case 221: + case 226: node = parent; break; - case 289: + case 291: + node = parent.parent; + break; + case 290: if (parent.name !== node) { return 0; } node = parent.parent; break; - case 288: + case 289: if (parent.name === node) { return 0; } @@ -12345,22 +12562,22 @@ var ts; ts.isAssignmentTarget = isAssignmentTarget; function isNodeWithPossibleHoistedDeclaration(node) { switch (node.kind) { - case 230: - case 232: - case 243: - case 234: + case 231: + case 233: case 244: - case 258: - case 284: - case 285: + case 235: case 245: - case 237: + case 259: + case 285: + case 286: + case 246: case 238: case 239: - case 235: + case 240: case 236: - case 247: - case 287: + case 237: + case 248: + case 288: return true; } return false; @@ -12377,16 +12594,16 @@ var ts; return node; } function walkUpParenthesizedTypes(node) { - return walkUp(node, 186); + return walkUp(node, 187); } ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; function walkUpParenthesizedExpressions(node) { - return walkUp(node, 207); + return walkUp(node, 208); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; function walkUpParenthesizedTypesAndGetParentAndChild(node) { var child; - while (node && node.kind === 186) { + while (node && node.kind === 187) { child = node; node = node.parent; } @@ -12398,17 +12615,17 @@ var ts; } ts.skipParentheses = skipParentheses; function skipParenthesesUp(node) { - while (node.kind === 207) { + while (node.kind === 208) { node = node.parent; } return node; } function isDeleteTarget(node) { - if (node.kind !== 201 && node.kind !== 202) { + if (node.kind !== 202 && node.kind !== 203) { return false; } node = walkUpParenthesizedExpressions(node.parent); - return node && node.kind === 210; + return node && node.kind === 211; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -12458,63 +12675,63 @@ var ts; ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return isStringOrNumericLiteralLike(node) && - node.parent.kind === 158 && + node.parent.kind === 159 && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { + case 164: case 163: - case 162: + case 166: case 165: - case 164: - case 167: case 168: - case 291: - case 288: - case 201: + case 169: + case 292: + case 289: + case 202: return parent.name === node; - case 157: + case 158: return parent.right === node; - case 198: - case 265: + case 199: + case 266: return parent.propertyName === node; - case 270: - case 280: + case 271: + case 281: return true; } return false; } ts.isIdentifierName = isIdentifierName; function isAliasSymbolDeclaration(node) { - return node.kind === 260 || - node.kind === 259 || - node.kind === 262 && !!node.name || - node.kind === 263 || - node.kind === 269 || - node.kind === 265 || + return node.kind === 261 || + node.kind === 260 || + node.kind === 263 && !!node.name || + node.kind === 264 || node.kind === 270 || - node.kind === 266 && exportAssignmentIsAlias(node) || + node.kind === 266 || + node.kind === 271 || + node.kind === 267 && exportAssignmentIsAlias(node) || ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 && exportAssignmentIsAlias(node) || ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 && isAliasableExpression(node.parent.right) || - node.kind === 289 || - node.kind === 288 && isAliasableExpression(node.initializer); + node.kind === 290 || + node.kind === 289 && isAliasableExpression(node.initializer); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getAliasDeclarationFromName(node) { switch (node.parent.kind) { - case 262: - case 265: case 263: - case 270: case 266: - case 260: + case 264: + case 271: + case 267: + case 261: return node.parent; - case 157: + case 158: do { node = node.parent; - } while (node.parent.kind === 157); + } while (node.parent.kind === 158); return getAliasDeclarationFromName(node); } } @@ -12533,7 +12750,7 @@ var ts; } ts.getExportAssignmentExpression = getExportAssignmentExpression; function getPropertyAssignmentAliasLikeExpression(node) { - return node.kind === 289 ? node.name : node.kind === 288 ? node.initializer : + return node.kind === 290 ? node.name : node.kind === 289 ? node.initializer : node.parent.right; } ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression; @@ -12597,11 +12814,11 @@ var ts; } ts.getAncestor = getAncestor; function isKeyword(token) { - return 80 <= token && token <= 156; + return 80 <= token && token <= 157; } ts.isKeyword = isKeyword; function isContextualKeyword(token) { - return 125 <= token && token <= 156; + return 125 <= token && token <= 157; } ts.isContextualKeyword = isContextualKeyword; function isNonContextualKeyword(token) { @@ -12637,13 +12854,13 @@ var ts; } var flags = 0; switch (node.kind) { - case 251: - case 208: - case 165: + case 252: + case 209: + case 166: if (node.asteriskToken) { flags |= 1; } - case 209: + case 210: if (hasSyntacticModifier(node, 256)) { flags |= 2; } @@ -12657,10 +12874,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 251: - case 208: + case 252: case 209: - case 165: + case 210: + case 166: return node.body !== undefined && node.asteriskToken === undefined && hasSyntacticModifier(node, 256); @@ -12682,19 +12899,14 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - if (!(name.kind === 158 || name.kind === 202)) { + if (!(name.kind === 159 || name.kind === 203)) { return false; } var expr = ts.isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression; return !isStringOrNumericLiteralLike(expr) && - !isSignedNumericLiteral(expr) && - !isWellKnownSymbolSyntactically(expr); + !isSignedNumericLiteral(expr); } ts.isDynamicName = isDynamicName; - function isWellKnownSymbolSyntactically(node) { - return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); - } - ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { switch (name.kind) { case 78: @@ -12703,12 +12915,9 @@ var ts; case 10: case 8: return ts.escapeLeadingUnderscores(name.text); - case 158: + case 159: var nameExpression = name.expression; - if (isWellKnownSymbolSyntactically(nameExpression)) { - return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - else if (isStringOrNumericLiteralLike(nameExpression)) { + if (isStringOrNumericLiteralLike(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); } else if (isSignedNumericLiteral(nameExpression)) { @@ -12736,21 +12945,17 @@ var ts; } ts.isPropertyNameLiteral = isPropertyNameLiteral; function getTextOfIdentifierOrLiteral(node) { - return ts.isIdentifierOrPrivateIdentifier(node) ? ts.idText(node) : node.text; + return ts.isMemberName(node) ? ts.idText(node) : node.text; } ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { - return ts.isIdentifierOrPrivateIdentifier(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text); + return ts.isMemberName(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForUniqueESSymbol(symbol) { return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName; } ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol; - function getPropertyNameForKnownSymbolName(symbolName) { - return "__@" + symbolName; - } - ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) { return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description; } @@ -12769,11 +12974,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 160; + return root.kind === 161; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 198) { + while (node.kind === 199) { node = node.parent.parent; } return node; @@ -12781,15 +12986,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 166 - || kind === 208 - || kind === 251 + return kind === 167 || kind === 209 - || kind === 165 - || kind === 167 + || kind === 252 + || kind === 210 + || kind === 166 || kind === 168 - || kind === 256 - || kind === 297; + || kind === 169 + || kind === 257 + || kind === 298; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -12803,23 +13008,23 @@ var ts; ts.getOriginalSourceFile = getOriginalSourceFile; function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 204 && expression.arguments !== undefined; + var hasArguments = expression.kind === 205 && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 204: + case 205: return hasArguments ? 0 : 1; - case 214: - case 211: + case 215: case 212: - case 210: case 213: - case 217: - case 219: + case 211: + case 214: + case 218: + case 220: return 1; - case 216: + case 217: switch (operator) { case 42: case 62: @@ -12846,15 +13051,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 204 && expression.arguments !== undefined; + var hasArguments = expression.kind === 205 && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 216) { + if (expression.kind === 217) { return expression.operatorToken.kind; } - else if (expression.kind === 214 || expression.kind === 215) { + else if (expression.kind === 215 || expression.kind === 216) { return expression.operator; } else { @@ -12864,15 +13069,15 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 337: + case 341: return 0; - case 220: + case 221: return 1; - case 219: + case 220: return 2; - case 217: + case 218: return 4; - case 216: + case 217: switch (operatorKind) { case 27: return 0; @@ -12896,25 +13101,26 @@ var ts; default: return getBinaryOperatorPrecedence(operatorKind); } - case 206: - case 225: - case 214: - case 211: + case 207: + case 226: + case 215: case 212: - case 210: case 213: + case 211: + case 214: return 16; - case 215: + case 216: return 17; - case 203: - return 18; case 204: - return hasArguments ? 19 : 18; + return 18; case 205: - case 201: + return hasArguments ? 19 : 18; + case 206: case 202: + case 203: + case 227: return 19; - case 224: + case 225: return 11; case 107: case 105: @@ -12925,19 +13131,19 @@ var ts; case 8: case 9: case 10: - case 199: case 200: - case 208: + case 201: case 209: - case 221: + case 210: + case 222: case 13: case 14: - case 218: - case 207: - case 222: - case 273: + case 219: + case 208: + case 223: case 274: - case 277: + case 275: + case 278: return 20; default: return -1; @@ -12991,7 +13197,7 @@ var ts; function getSemanticJsxChildren(children) { return ts.filter(children, function (i) { switch (i.kind) { - case 283: + case 284: return !!i.expression; case 11: return !i.containsOnlyTriviaWhiteSpaces; @@ -13358,11 +13564,19 @@ var ts; return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getCanonicalAbsolutePath(host, path) { + return host.getCanonicalFileName(ts.getNormalizedAbsolutePath(path, host.getCurrentDirectory())); + } function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); if (!file || file.isDeclarationFile) { return undefined; } + var specifier = getExternalModuleName(declaration); + if (specifier && ts.isStringLiteralLike(specifier) && !ts.pathIsRelative(specifier.text) && + getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ts.ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1) { + return undefined; + } return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; @@ -13431,8 +13645,8 @@ var ts; return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !host.isSourceFileFromExternalLibrary(sourceFile) && - !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) && - (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName)); + (forceDtsEmit || (!(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) && + !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName))); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -13522,10 +13736,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 167) { + if (accessor.kind === 168) { getAccessor = accessor; } - else if (accessor.kind === 168) { + else if (accessor.kind === 169) { setAccessor = accessor; } else { @@ -13545,10 +13759,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 167 && !getAccessor) { + if (member.kind === 168 && !getAccessor) { getAccessor = member; } - if (member.kind === 168 && !setAccessor) { + if (member.kind === 169 && !setAccessor) { setAccessor = member; } } @@ -13587,7 +13801,7 @@ var ts; } ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; function isNonTypeAliasTemplate(tag) { - return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 311 && tag.parent.tags.some(isJSDocTypeAlias)); + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 312 && tag.parent.tags.some(isJSDocTypeAlias)); } function getEffectiveSetAccessorTypeAnnotationNode(node) { var parameter = getSetAccessorValueParameter(node); @@ -13762,6 +13976,18 @@ var ts; return hasSyntacticModifier(node, 32); } ts.hasStaticModifier = hasStaticModifier; + function hasOverrideModifier(node) { + return hasEffectiveModifier(node, 16384); + } + ts.hasOverrideModifier = hasOverrideModifier; + function hasAbstractModifier(node) { + return hasSyntacticModifier(node, 128); + } + ts.hasAbstractModifier = hasAbstractModifier; + function hasAmbientModifier(node) { + return hasSyntacticModifier(node, 2); + } + ts.hasAmbientModifier = hasAmbientModifier; function hasEffectiveReadonlyModifier(node) { return hasEffectiveModifier(node, 64); } @@ -13775,7 +14001,7 @@ var ts; } ts.getSelectedSyntacticModifierFlags = getSelectedSyntacticModifierFlags; function getModifierFlagsWorker(node, includeJSDoc, alwaysIncludeJSDoc) { - if (node.kind >= 0 && node.kind <= 156) { + if (node.kind >= 0 && node.kind <= 157) { return 0; } if (!(node.modifierFlagsCache & 536870912)) { @@ -13810,6 +14036,8 @@ var ts; flags |= 16; if (ts.getJSDocReadonlyTagNoCache(node)) flags |= 64; + if (ts.getJSDocOverrideTagNoCache(node)) + flags |= 16384; } if (ts.getJSDocDeprecatedTagNoCache(node)) flags |= 8192; @@ -13852,10 +14080,15 @@ var ts; case 87: return 512; case 129: return 256; case 142: return 64; + case 156: return 16384; } return 0; } ts.modifierToFlag = modifierToFlag; + function createModifiers(modifierFlags) { + return modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; + } + ts.createModifiers = createModifiers; function isLogicalOperator(token) { return token === 56 || token === 55 @@ -13897,11 +14130,15 @@ var ts; && ts.isLeftHandSideExpression(node.left); } ts.isAssignmentExpression = isAssignmentExpression; + function isLeftHandSideOfAssignment(node) { + return isAssignmentExpression(node.parent) && node.parent.left === node; + } + ts.isLeftHandSideOfAssignment = isLeftHandSideOfAssignment; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, true)) { var kind = node.left.kind; - return kind === 200 - || kind === 199; + return kind === 201 + || kind === 200; } return false; } @@ -13918,12 +14155,12 @@ var ts; switch (node.kind) { case 78: return node; - case 157: + case 158: do { node = node.left; } while (node.kind !== 78); return node; - case 201: + case 202: do { node = node.expression; } while (node.kind !== 78); @@ -13932,9 +14169,12 @@ var ts; } ts.getFirstIdentifier = getFirstIdentifier; function isDottedName(node) { - return node.kind === 78 || node.kind === 107 || node.kind === 105 || - node.kind === 201 && isDottedName(node.expression) || - node.kind === 207 && isDottedName(node.expression); + return node.kind === 78 + || node.kind === 107 + || node.kind === 105 + || node.kind === 227 + || node.kind === 202 && isDottedName(node.expression) + || node.kind === 208 && isDottedName(node.expression); } ts.isDottedName = isDottedName; function isPropertyAccessEntityNameExpression(node) { @@ -13948,6 +14188,12 @@ var ts; return baseStr + "." + entityNameToString(expr.name); } } + else if (ts.isElementAccessExpression(expr)) { + var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); + if (baseStr !== undefined && ts.isPropertyName(expr.argumentExpression)) { + return baseStr + "." + getPropertyNameForPropertyNameNode(expr.argumentExpression); + } + } else if (ts.isIdentifier(expr)) { return ts.unescapeLeadingUnderscores(expr.escapedText); } @@ -13959,22 +14205,22 @@ var ts; } ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 157 && node.parent.right === node) || - (node.parent.kind === 201 && node.parent.name === node); + return (node.parent.kind === 158 && node.parent.right === node) || + (node.parent.kind === 202 && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 200 && + return expression.kind === 201 && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 199 && + return expression.kind === 200 && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - if (!isExportDefaultSymbol(symbol)) + if (!isExportDefaultSymbol(symbol) || !symbol.declarations) return undefined; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; @@ -14241,8 +14487,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 255: case 256: + case 257: return parseNode === parseNode.parent.name; } } @@ -14268,9 +14514,11 @@ var ts; return symbol.flags & 33554432 ? symbol.checkFlags : 0; } ts.getCheckFlags = getCheckFlags; - function getDeclarationModifierFlagsFromSymbol(s) { + function getDeclarationModifierFlagsFromSymbol(s, isWrite) { + if (isWrite === void 0) { isWrite = false; } if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + var declaration = (isWrite && s.declarations && ts.find(s.declarations, function (d) { return d.kind === 169; })) || s.valueDeclaration; + var flags = ts.getCombinedModifierFlags(declaration); return s.parent && s.parent.flags & 32 ? flags : flags & ~28; } if (getCheckFlags(s) & 6) { @@ -14308,32 +14556,32 @@ var ts; if (!parent) return 0; switch (parent.kind) { - case 207: + case 208: return accessKind(parent); + case 216: case 215: - case 214: var operator = parent.operator; return operator === 45 || operator === 46 ? writeOrReadWrite() : 0; - case 216: + case 217: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? operatorToken.kind === 62 ? 1 : writeOrReadWrite() : 0; - case 201: + case 202: return parent.name !== node ? 0 : accessKind(parent); - case 288: { + case 289: { var parentAccess = accessKind(parent.parent); return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; } - case 289: + case 290: return node === parent.objectAssignmentInitializer ? 0 : accessKind(parent.parent); - case 199: + case 200: return accessKind(parent); default: return 0; } function writeOrReadWrite() { - return parent.parent && skipParenthesesUp(parent.parent).kind === 233 ? 1 : 2; + return parent.parent && skipParenthesesUp(parent.parent).kind === 234 ? 1 : 2; } } function reverseAccessKind(a) { @@ -14405,7 +14653,8 @@ var ts; } ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol; function getClassLikeDeclarationOfSymbol(symbol) { - return ts.find(symbol.declarations, ts.isClassLike); + var _a; + return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isClassLike); } ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; function getObjectFlags(type) { @@ -14447,7 +14696,6 @@ var ts; ts.getLastChild = getLastChild; function addToSeen(seen, key, value) { if (value === void 0) { value = true; } - key = String(key); if (seen.has(key)) { return false; } @@ -14460,7 +14708,7 @@ var ts; } ts.isObjectTypeDeclaration = isObjectTypeDeclaration; function isTypeNodeKind(kind) { - return (kind >= 172 && kind <= 195) + return (kind >= 173 && kind <= 196) || kind === 128 || kind === 152 || kind === 144 @@ -14472,25 +14720,25 @@ var ts; || kind === 113 || kind === 150 || kind === 141 - || kind === 223 - || kind === 303 + || kind === 224 || kind === 304 || kind === 305 || kind === 306 || kind === 307 || kind === 308 - || kind === 309; + || kind === 309 + || kind === 310; } ts.isTypeNodeKind = isTypeNodeKind; function isAccessExpression(node) { - return node.kind === 201 || node.kind === 202; + return node.kind === 202 || node.kind === 203; } ts.isAccessExpression = isAccessExpression; function getNameOfAccessExpression(node) { - if (node.kind === 201) { + if (node.kind === 202) { return node.name; } - ts.Debug.assert(node.kind === 202); + ts.Debug.assert(node.kind === 203); return node.argumentExpression; } ts.getNameOfAccessExpression = getNameOfAccessExpression; @@ -14505,7 +14753,7 @@ var ts; } ts.isBundleFileTextLike = isBundleFileTextLike; function isNamedImportsOrExports(node) { - return node.kind === 264 || node.kind === 268; + return node.kind === 265 || node.kind === 269; } ts.isNamedImportsOrExports = isNamedImportsOrExports; function getLeftmostAccessExpression(expr) { @@ -14518,27 +14766,27 @@ var ts; function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 215: + case 216: node = node.operand; continue; - case 216: + case 217: node = node.left; continue; - case 217: + case 218: node = node.condition; continue; - case 205: + case 206: node = node.tag; continue; - case 203: + case 204: if (stopAtCallExpressions) { return node; } - case 224: - case 202: - case 201: case 225: - case 336: + case 203: + case 202: + case 226: + case 340: node = node.expression; continue; } @@ -14557,7 +14805,7 @@ var ts; } function Type(checker, flags) { this.flags = flags; - if (ts.Debug.isDebugging || ts.tracing.isTracing()) { + if (ts.Debug.isDebugging || ts.tracing) { this.checker = checker; } } @@ -14898,6 +15146,10 @@ var ts; return !!(compilerOptions.declaration || compilerOptions.composite); } ts.getEmitDeclarations = getEmitDeclarations; + function shouldPreserveConstEnums(compilerOptions) { + return !!(compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + } + ts.shouldPreserveConstEnums = shouldPreserveConstEnums; function isIncrementalCompilation(options) { return !!(options.incremental || options.composite); } @@ -14910,6 +15162,10 @@ var ts; return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs; } ts.getAllowJSCompilerOption = getAllowJSCompilerOption; + function getUseDefineForClassFields(compilerOptions) { + return compilerOptions.useDefineForClassFields === undefined ? compilerOptions.target === 99 : compilerOptions.useDefineForClassFields; + } + ts.getUseDefineForClassFields = getUseDefineForClassFields; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { return oldOptions !== newOptions && ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); @@ -14931,7 +15187,7 @@ var ts; ts.getJSXTransformEnabled = getJSXTransformEnabled; function getJSXImplicitImportBase(compilerOptions, file) { var jsxImportSourcePragmas = file === null || file === void 0 ? void 0 : file.pragmas.get("jsximportsource"); - var jsxImportSourcePragma = ts.isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[0] : jsxImportSourcePragmas; + var jsxImportSourcePragma = ts.isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[jsxImportSourcePragmas.length - 1] : jsxImportSourcePragmas; return compilerOptions.jsx === 4 || compilerOptions.jsx === 5 || compilerOptions.jsxImportSource || @@ -14959,37 +15215,62 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createSymlinkCache() { + function createSymlinkCache(cwd, getCanonicalFileName) { var symlinkedDirectories; + var symlinkedDirectoriesByRealpath; var symlinkedFiles; return { getSymlinkedFiles: function () { return symlinkedFiles; }, getSymlinkedDirectories: function () { return symlinkedDirectories; }, + getSymlinkedDirectoriesByRealpath: function () { return symlinkedDirectoriesByRealpath; }, setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); }, - setSymlinkedDirectory: function (path, directory) { return (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(path, directory); }, + setSymlinkedDirectory: function (symlink, real) { + var symlinkPath = ts.toPath(symlink, cwd, getCanonicalFileName); + if (!containsIgnoredPath(symlinkPath)) { + symlinkPath = ts.ensureTrailingDirectorySeparator(symlinkPath); + if (real !== false && !(symlinkedDirectories === null || symlinkedDirectories === void 0 ? void 0 : symlinkedDirectories.has(symlinkPath))) { + (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = ts.createMultiMap())).add(ts.ensureTrailingDirectorySeparator(real.realPath), symlink); + } + (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); + } + }, + setSymlinkedDirectoryFromSymlinkedFile: function (symlink, real) { + this.setSymlinkedFile(ts.toPath(symlink, cwd, getCanonicalFileName), real); + var _a = guessDirectorySymlink(real, symlink, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _a[0], commonOriginal = _a[1]; + if (commonResolved && commonOriginal) { + this.setSymlinkedDirectory(commonOriginal, { + real: commonResolved, + realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName), + }); + } + }, }; } ts.createSymlinkCache = createSymlinkCache; function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { - var cache = createSymlinkCache(); - var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { - return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) { - return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + var cache = createSymlinkCache(cwd, getCanonicalFileName); + var symlinks = ts.flatMap(files, function (sf) { + var pairs = sf.resolvedModules && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedModules.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) ? [res.resolvedFileName, res.originalPath] : undefined; + })); + return ts.concatenate(pairs, sf.resolvedTypeReferenceDirectiveNames && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedTypeReferenceDirectiveNames.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) && res.resolvedFileName ? [res.resolvedFileName, res.originalPath] : undefined; }))); - })); + }); for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + cache.setSymlinkedFile(ts.toPath(originalPath, cwd, getCanonicalFileName), resolvedPath); var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1]; if (commonResolved && commonOriginal) { - cache.setSymlinkedDirectory(ts.toPath(commonOriginal, cwd, getCanonicalFileName), { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); + cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); } } return cache; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(a, cwd)); + var bParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(b, cwd)); var isDirectory = false; while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && @@ -15312,6 +15593,14 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + function numberOfDirectorySeparators(str) { + var match = str.match(/\//g); + return match ? match.length : 0; + } + function compareNumberOfDirectorySeparators(path1, path2) { + return ts.compareValues(numberOfDirectorySeparators(path1), numberOfDirectorySeparators(path2)); + } + ts.compareNumberOfDirectorySeparators = compareNumberOfDirectorySeparators; function getExtensionPriority(path, supportedExtensions) { for (var i = supportedExtensions.length - 1; i >= 0; i--) { if (ts.fileExtensionIs(path, supportedExtensions[i])) { @@ -15558,37 +15847,37 @@ var ts; } ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite; function typeOnlyDeclarationIsExport(typeOnlyDeclaration) { - return typeOnlyDeclaration.kind === 270; + return typeOnlyDeclaration.kind === 271; } ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport; function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) { - while (node.kind === 78 || node.kind === 201) { + while (node.kind === 78 || node.kind === 202) { node = node.parent; } - if (node.kind !== 158) { + if (node.kind !== 159) { return false; } if (hasSyntacticModifier(node.parent, 128)) { return true; } var containerKind = node.parent.parent.kind; - return containerKind === 253 || containerKind === 177; + return containerKind === 254 || containerKind === 178; } function isIdentifierInNonEmittingHeritageClause(node) { if (node.kind !== 78) return false; var heritageClause = ts.findAncestor(node.parent, function (parent) { switch (parent.kind) { - case 286: + case 287: return true; - case 201: - case 223: + case 202: + case 224: return false; default: return "quit"; } }); - return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 116 || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 253; + return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 116 || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 254; } function isIdentifierTypeReference(node) { return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName); @@ -15710,6 +15999,76 @@ var ts; } } ts.expressionResultIsUnused = expressionResultIsUnused; + function containsIgnoredPath(path) { + return ts.some(ts.ignoredPaths, function (p) { return ts.stringContains(path, p); }); + } + ts.containsIgnoredPath = containsIgnoredPath; + function getContainingNodeArray(node) { + if (!node.parent) + return undefined; + switch (node.kind) { + case 160: + var parent_1 = node.parent; + return parent_1.kind === 186 ? undefined : parent_1.typeParameters; + case 161: + return node.parent.parameters; + case 195: + return node.parent.templateSpans; + case 229: + return node.parent.templateSpans; + case 162: + return node.parent.decorators; + case 287: + return node.parent.heritageClauses; + } + var parent = node.parent; + if (ts.isJSDocTag(node)) { + return ts.isJSDocTypeLiteral(node.parent) ? undefined : node.parent.tags; + } + switch (parent.kind) { + case 178: + case 254: + return ts.isTypeElement(node) ? parent.members : undefined; + case 183: + case 184: + return parent.types; + case 180: + case 200: + case 341: + case 265: + case 269: + return parent.elements; + case 201: + case 282: + return parent.properties; + case 204: + case 205: + return ts.isTypeNode(node) ? parent.typeArguments : + parent.expression === node ? undefined : + parent.arguments; + case 274: + case 278: + return ts.isJsxChild(node) ? parent.children : undefined; + case 276: + case 275: + return ts.isTypeNode(node) ? parent.typeArguments : undefined; + case 231: + case 285: + case 286: + case 258: + return parent.statements; + case 259: + return parent.clauses; + case 253: + case 222: + return ts.isClassElement(node) ? parent.members : undefined; + case 256: + return ts.isEnumMember(node) ? parent.members : undefined; + case 298: + return parent.statements; + } + } + ts.getContainingNodeArray = getContainingNodeArray; })(ts || (ts = {})); var ts; (function (ts) { @@ -15747,7 +16106,11 @@ var ts; var ts; (function (ts) { function createParenthesizerRules(factory) { + var binaryLeftOperandParenthesizerCache; + var binaryRightOperandParenthesizerCache; return { + getParenthesizeLeftSideOfBinaryForOperator: getParenthesizeLeftSideOfBinaryForOperator, + getParenthesizeRightSideOfBinaryForOperator: getParenthesizeRightSideOfBinaryForOperator, parenthesizeLeftSideOfBinary: parenthesizeLeftSideOfBinary, parenthesizeRightSideOfBinary: parenthesizeRightSideOfBinary, parenthesizeExpressionOfComputedPropertyName: parenthesizeExpressionOfComputedPropertyName, @@ -15768,11 +16131,29 @@ var ts; parenthesizeConstituentTypesOfUnionOrIntersectionType: parenthesizeConstituentTypesOfUnionOrIntersectionType, parenthesizeTypeArguments: parenthesizeTypeArguments, }; + function getParenthesizeLeftSideOfBinaryForOperator(operatorKind) { + binaryLeftOperandParenthesizerCache || (binaryLeftOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeLeftSideOfBinary(operatorKind, node); }; + binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } + function getParenthesizeRightSideOfBinaryForOperator(operatorKind) { + binaryRightOperandParenthesizerCache || (binaryRightOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeRightSideOfBinary(operatorKind, undefined, node); }; + binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { - var binaryOperatorPrecedence = ts.getOperatorPrecedence(216, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(216, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(217, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(217, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); - if (!isLeftSideOfBinary && operand.kind === 209 && binaryOperatorPrecedence > 3) { + if (!isLeftSideOfBinary && operand.kind === 210 && binaryOperatorPrecedence > 3) { return true; } var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); @@ -15780,7 +16161,7 @@ var ts; case -1: if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 - && operand.kind === 219) { + && operand.kind === 220) { return false; } return true; @@ -15819,7 +16200,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 216 && node.operatorToken.kind === 39) { + if (node.kind === 217 && node.operatorToken.kind === 39) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -15835,7 +16216,7 @@ var ts; } function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); - if (skipped.kind === 207) { + if (skipped.kind === 208) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -15852,7 +16233,7 @@ var ts; return ts.isCommaSequence(expression) ? factory.createParenthesizedExpression(expression) : expression; } function parenthesizeConditionOfConditionalExpression(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(217, 57); + var conditionalPrecedence = ts.getOperatorPrecedence(218, 57); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1) { @@ -15871,8 +16252,8 @@ var ts; var needsParens = ts.isCommaSequence(check); if (!needsParens) { switch (ts.getLeftmostExpression(check, false).kind) { - case 221: - case 208: + case 222: + case 209: needsParens = true; } } @@ -15881,9 +16262,9 @@ var ts; function parenthesizeExpressionOfNew(expression) { var leftmostExpr = ts.getLeftmostExpression(expression, true); switch (leftmostExpr.kind) { - case 203: - return factory.createParenthesizedExpression(expression); case 204: + return factory.createParenthesizedExpression(expression); + case 205: return !leftmostExpr.arguments ? factory.createParenthesizedExpression(expression) : expression; @@ -15893,7 +16274,7 @@ var ts; function parenthesizeLeftSideOfAccess(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 204 || emittedExpression.arguments)) { + && (emittedExpression.kind !== 205 || emittedExpression.arguments)) { return expression; } return ts.setTextRange(factory.createParenthesizedExpression(expression), expression); @@ -15911,7 +16292,7 @@ var ts; function parenthesizeExpressionForDisallowedComma(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(216, 27); + var commaPrecedence = ts.getOperatorPrecedence(217, 27); return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(factory.createParenthesizedExpression(expression), expression); } function parenthesizeExpressionOfExpressionStatement(expression) { @@ -15919,41 +16300,41 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 208 || kind === 209) { + if (kind === 209 || kind === 210) { var updated = factory.updateCallExpression(emittedExpression, ts.setTextRange(factory.createParenthesizedExpression(callee), callee), emittedExpression.typeArguments, emittedExpression.arguments); return factory.restoreOuterExpressions(expression, updated, 8); } } var leftmostExpressionKind = ts.getLeftmostExpression(emittedExpression, false).kind; - if (leftmostExpressionKind === 200 || leftmostExpressionKind === 208) { + if (leftmostExpressionKind === 201 || leftmostExpressionKind === 209) { return ts.setTextRange(factory.createParenthesizedExpression(expression), expression); } return expression; } function parenthesizeConciseBodyOfArrowFunction(body) { - if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, false).kind === 200)) { + if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, false).kind === 201)) { return ts.setTextRange(factory.createParenthesizedExpression(body), body); } return body; } function parenthesizeMemberOfConditionalType(member) { - return member.kind === 184 ? factory.createParenthesizedType(member) : member; + return member.kind === 185 ? factory.createParenthesizedType(member) : member; } function parenthesizeMemberOfElementType(member) { switch (member.kind) { - case 182: case 183: - case 174: + case 184: case 175: + case 176: return factory.createParenthesizedType(member); } return parenthesizeMemberOfConditionalType(member); } function parenthesizeElementTypeOfArrayType(member) { switch (member.kind) { - case 176: - case 188: - case 185: + case 177: + case 189: + case 186: return factory.createParenthesizedType(member); } return parenthesizeMemberOfElementType(member); @@ -15972,6 +16353,8 @@ var ts; } ts.createParenthesizerRules = createParenthesizerRules; ts.nullParenthesizerRules = { + getParenthesizeLeftSideOfBinaryForOperator: function (_) { return ts.identity; }, + getParenthesizeRightSideOfBinaryForOperator: function (_) { return ts.identity; }, parenthesizeLeftSideOfBinary: function (_binaryOperator, leftSide) { return leftSide; }, parenthesizeRightSideOfBinary: function (_binaryOperator, _leftSide, rightSide) { return rightSide; }, parenthesizeExpressionOfComputedPropertyName: ts.identity, @@ -16056,11 +16439,11 @@ var ts; } function convertToAssignmentPattern(node) { switch (node.kind) { - case 197: - case 199: - return convertToArrayAssignmentPattern(node); - case 196: + case 198: case 200: + return convertToArrayAssignmentPattern(node); + case 197: + case 201: return convertToObjectAssignmentPattern(node); } } @@ -16379,18 +16762,18 @@ var ts; createMissingDeclaration: createMissingDeclaration, createExternalModuleReference: createExternalModuleReference, updateExternalModuleReference: updateExternalModuleReference, - get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(303); }, - get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(304); }, - get createJSDocNonNullableType() { return getJSDocUnaryTypeCreateFunction(306); }, - get updateJSDocNonNullableType() { return getJSDocUnaryTypeUpdateFunction(306); }, - get createJSDocNullableType() { return getJSDocUnaryTypeCreateFunction(305); }, - get updateJSDocNullableType() { return getJSDocUnaryTypeUpdateFunction(305); }, - get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(307); }, - get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(307); }, - get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(309); }, - get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(309); }, - get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(310); }, - get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(310); }, + get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(304); }, + get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(305); }, + get createJSDocNonNullableType() { return getJSDocUnaryTypeCreateFunction(307); }, + get updateJSDocNonNullableType() { return getJSDocUnaryTypeUpdateFunction(307); }, + get createJSDocNullableType() { return getJSDocUnaryTypeCreateFunction(306); }, + get updateJSDocNullableType() { return getJSDocUnaryTypeUpdateFunction(306); }, + get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(308); }, + get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(308); }, + get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(310); }, + get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(310); }, + get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(311); }, + get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(311); }, createJSDocFunctionType: createJSDocFunctionType, updateJSDocFunctionType: updateJSDocFunctionType, createJSDocTypeLiteral: createJSDocTypeLiteral, @@ -16417,30 +16800,36 @@ var ts; updateJSDocSeeTag: updateJSDocSeeTag, createJSDocNameReference: createJSDocNameReference, updateJSDocNameReference: updateJSDocNameReference, - get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(329); }, - get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(329); }, - get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(327); }, - get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(327); }, - get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(328); }, - get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(328); }, - get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(325); }, - get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(325); }, - get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(317); }, - get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(317); }, - get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(319); }, - get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(319); }, - get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(320); }, - get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(320); }, - get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(321); }, - get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(321); }, - get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(322); }, - get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(322); }, - get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(323); }, - get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(323); }, - get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(318); }, - get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(318); }, + createJSDocLink: createJSDocLink, + updateJSDocLink: updateJSDocLink, + get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(333); }, + get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(333); }, + get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(331); }, + get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(331); }, + get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(332); }, + get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(332); }, + get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(329); }, + get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(329); }, + get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(320); }, + get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(320); }, + get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(322); }, + get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(322); }, + get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(323); }, + get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(323); }, + get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(324); }, + get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(324); }, + get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(325); }, + get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(325); }, + get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(326); }, + get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(326); }, + get createJSDocOverrideTag() { return getJSDocSimpleTagCreateFunction(327); }, + get updateJSDocOverrideTag() { return getJSDocSimpleTagUpdateFunction(327); }, + get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(321); }, + get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(321); }, createJSDocUnknownTag: createJSDocUnknownTag, updateJSDocUnknownTag: updateJSDocUnknownTag, + createJSDocText: createJSDocText, + updateJSDocText: updateJSDocText, createJSDocComment: createJSDocComment, updateJSDocComment: updateJSDocComment, createJsxElement: createJsxElement, @@ -16611,11 +17000,11 @@ var ts; node.name = name; if (name) { switch (node.kind) { - case 165: - case 167: + case 166: case 168: - case 163: - case 288: + case 169: + case 164: + case 289: if (ts.isIdentifier(name)) { node.transformFlags |= propagateIdentifierNameFlags(name); break; @@ -16654,7 +17043,7 @@ var ts; function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) { var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type); node.body = body; - node.transformFlags |= propagateChildFlags(node.body) & ~8388608; + node.transformFlags |= propagateChildFlags(node.body) & ~16777216; if (!body) node.transformFlags |= 1; return node; @@ -16702,7 +17091,7 @@ var ts; var node = createBaseLiteral(8, typeof value === "number" ? value + "" : value); node.numericLiteralFlags = numericLiteralFlags; if (numericLiteralFlags & 384) - node.transformFlags |= 256; + node.transformFlags |= 512; return node; } function createBigIntLiteral(value) { @@ -16719,7 +17108,7 @@ var ts; var node = createBaseStringLiteral(text, isSingleQuote); node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; if (hasExtendedUnicodeEscape) - node.transformFlags |= 256; + node.transformFlags |= 512; return node; } function createStringLiteralFromNode(sourceNode) { @@ -16767,7 +17156,7 @@ var ts; node.typeArguments = createNodeArray(typeArguments); } if (node.originalKeywordKind === 130) { - node.transformFlags |= 8388608; + node.transformFlags |= 16777216; } return node; } @@ -16786,8 +17175,11 @@ var ts; } return name; } - function createLoopVariable() { - return createBaseGeneratedIdentifier("", 2); + function createLoopVariable(reservedInNestedScopes) { + var flags = 2; + if (reservedInNestedScopes) + flags |= 8; + return createBaseGeneratedIdentifier("", flags); } function createUniqueName(text, flags) { if (flags === void 0) { flags = 0; } @@ -16807,14 +17199,14 @@ var ts; ts.Debug.fail("First character of private identifier must be #: " + text); var node = baseFactory.createBasePrivateIdentifierNode(79); node.escapedText = ts.escapeLeadingUnderscores(text); - node.transformFlags |= 4194304; + node.transformFlags |= 8388608; return node; } function createBaseToken(kind) { return baseFactory.createBaseTokenNode(kind); } function createToken(token) { - ts.Debug.assert(token >= 0 && token <= 156, "Invalid token"); + ts.Debug.assert(token >= 0 && token <= 157, "Invalid token"); ts.Debug.assert(token <= 14 || token >= 17, "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals."); ts.Debug.assert(token <= 8 || token >= 14, "Invalid token. Use 'createLiteralLikeNode' to create literals."); ts.Debug.assert(token !== 78, "Invalid token. Use 'createIdentifier' to create identifiers"); @@ -16823,8 +17215,8 @@ var ts; switch (token) { case 129: transformFlags = - 64 | - 32; + 128 | + 64; break; case 122: case 120: @@ -16838,6 +17230,7 @@ var ts; case 155: case 141: case 145: + case 156: case 147: case 131: case 148: @@ -16848,10 +17241,10 @@ var ts; break; case 123: case 105: - transformFlags = 256; + transformFlags = 512; break; case 107: - transformFlags = 4096; + transformFlags = 8192; break; } if (transformFlags) { @@ -16906,6 +17299,9 @@ var ts; if (flags & 32) { result.push(createModifier(123)); } + if (flags & 16384) { + result.push(createModifier(156)); + } if (flags & 64) { result.push(createModifier(142)); } @@ -16915,7 +17311,7 @@ var ts; return result; } function createQualifiedName(left, right) { - var node = createBaseNode(157); + var node = createBaseNode(158); node.left = left; node.right = asName(right); node.transformFlags |= @@ -16930,12 +17326,12 @@ var ts; : node; } function createComputedPropertyName(expression) { - var node = createBaseNode(158); + var node = createBaseNode(159); node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 256 | - 32768; + 512 | + 65536; return node; } function updateComputedPropertyName(node, expression) { @@ -16944,7 +17340,7 @@ var ts; : node; } function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createBaseNamedDeclaration(159, undefined, undefined, name); + var node = createBaseNamedDeclaration(160, undefined, undefined, name); node.constraint = constraint; node.default = defaultType; node.transformFlags = 1; @@ -16958,7 +17354,7 @@ var ts; : node; } function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(160, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); + var node = createBaseVariableLikeDeclaration(161, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.dotDotDotToken = dotDotDotToken; node.questionToken = questionToken; if (ts.isThisIdentifier(node.name)) { @@ -16970,10 +17366,10 @@ var ts; propagateChildFlags(node.questionToken); if (questionToken) node.transformFlags |= 1; - if (ts.modifiersToFlags(node.modifiers) & 92) - node.transformFlags |= 2048; + if (ts.modifiersToFlags(node.modifiers) & 16476) + node.transformFlags |= 4096; if (initializer || dotDotDotToken) - node.transformFlags |= 256; + node.transformFlags |= 512; } return node; } @@ -16989,12 +17385,12 @@ var ts; : node; } function createDecorator(expression) { - var node = createBaseNode(161); + var node = createBaseNode(162); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.transformFlags |= propagateChildFlags(node.expression) | 1 | - 2048; + 4096; return node; } function updateDecorator(node, expression) { @@ -17003,7 +17399,7 @@ var ts; : node; } function createPropertySignature(modifiers, name, questionToken, type) { - var node = createBaseNamedDeclaration(162, undefined, modifiers, name); + var node = createBaseNamedDeclaration(163, undefined, modifiers, name); node.type = type; node.questionToken = questionToken; node.transformFlags = 1; @@ -17018,15 +17414,15 @@ var ts; : node; } function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(163, decorators, modifiers, name, type, initializer); + var node = createBaseVariableLikeDeclaration(164, decorators, modifiers, name, type, initializer); node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.transformFlags |= propagateChildFlags(node.questionToken) | propagateChildFlags(node.exclamationToken) | - 4194304; + 8388608; if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) { - node.transformFlags |= 2048; + node.transformFlags |= 4096; } if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2) { node.transformFlags |= 1; @@ -17045,7 +17441,7 @@ var ts; : node; } function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(164, undefined, modifiers, name, typeParameters, parameters, type); + var node = createBaseSignatureDeclaration(165, undefined, modifiers, name, typeParameters, parameters, type); node.questionToken = questionToken; node.transformFlags = 1; return node; @@ -17061,26 +17457,26 @@ var ts; : node; } function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(165, decorators, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(166, decorators, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.questionToken = questionToken; node.transformFlags |= propagateChildFlags(node.asteriskToken) | propagateChildFlags(node.questionToken) | - 256; + 512; if (questionToken) { node.transformFlags |= 1; } if (ts.modifiersToFlags(node.modifiers) & 256) { if (asteriskToken) { - node.transformFlags |= 32; + node.transformFlags |= 64; } else { - node.transformFlags |= 64; + node.transformFlags |= 128; } } else if (asteriskToken) { - node.transformFlags |= 512; + node.transformFlags |= 1024; } return node; } @@ -17098,8 +17494,8 @@ var ts; : node; } function createConstructorDeclaration(decorators, modifiers, parameters, body) { - var node = createBaseFunctionLikeDeclaration(166, decorators, modifiers, undefined, undefined, parameters, undefined, body); - node.transformFlags |= 256; + var node = createBaseFunctionLikeDeclaration(167, decorators, modifiers, undefined, undefined, parameters, undefined, body); + node.transformFlags |= 512; return node; } function updateConstructorDeclaration(node, decorators, modifiers, parameters, body) { @@ -17111,7 +17507,7 @@ var ts; : node; } function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) { - return createBaseFunctionLikeDeclaration(167, decorators, modifiers, name, undefined, parameters, type, body); + return createBaseFunctionLikeDeclaration(168, decorators, modifiers, name, undefined, parameters, type, body); } function updateGetAccessorDeclaration(node, decorators, modifiers, name, parameters, type, body) { return node.decorators !== decorators @@ -17124,7 +17520,7 @@ var ts; : node; } function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) { - return createBaseFunctionLikeDeclaration(168, decorators, modifiers, name, undefined, parameters, undefined, body); + return createBaseFunctionLikeDeclaration(169, decorators, modifiers, name, undefined, parameters, undefined, body); } function updateSetAccessorDeclaration(node, decorators, modifiers, name, parameters, body) { return node.decorators !== decorators @@ -17136,7 +17532,7 @@ var ts; : node; } function createCallSignature(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(169, undefined, undefined, undefined, typeParameters, parameters, type); + var node = createBaseSignatureDeclaration(170, undefined, undefined, undefined, typeParameters, parameters, type); node.transformFlags = 1; return node; } @@ -17148,7 +17544,7 @@ var ts; : node; } function createConstructSignature(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(170, undefined, undefined, undefined, typeParameters, parameters, type); + var node = createBaseSignatureDeclaration(171, undefined, undefined, undefined, typeParameters, parameters, type); node.transformFlags = 1; return node; } @@ -17160,7 +17556,7 @@ var ts; : node; } function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createBaseSignatureDeclaration(171, decorators, modifiers, undefined, undefined, parameters, type); + var node = createBaseSignatureDeclaration(172, decorators, modifiers, undefined, undefined, parameters, type); node.transformFlags = 1; return node; } @@ -17173,7 +17569,7 @@ var ts; : node; } function createTemplateLiteralTypeSpan(type, literal) { - var node = createBaseNode(194); + var node = createBaseNode(195); node.type = type; node.literal = literal; node.transformFlags = 1; @@ -17189,7 +17585,7 @@ var ts; return createToken(kind); } function createTypePredicateNode(assertsModifier, parameterName, type) { - var node = createBaseNode(172); + var node = createBaseNode(173); node.assertsModifier = assertsModifier; node.parameterName = asName(parameterName); node.type = type; @@ -17204,7 +17600,7 @@ var ts; : node; } function createTypeReferenceNode(typeName, typeArguments) { - var node = createBaseNode(173); + var node = createBaseNode(174); node.typeName = asName(typeName); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(createNodeArray(typeArguments)); node.transformFlags = 1; @@ -17217,7 +17613,7 @@ var ts; : node; } function createFunctionTypeNode(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(174, undefined, undefined, undefined, typeParameters, parameters, type); + var node = createBaseSignatureDeclaration(175, undefined, undefined, undefined, typeParameters, parameters, type); node.transformFlags = 1; return node; } @@ -17238,7 +17634,7 @@ var ts; ts.Debug.fail("Incorrect number of arguments specified."); } function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(175, undefined, modifiers, undefined, typeParameters, parameters, type); + var node = createBaseSignatureDeclaration(176, undefined, modifiers, undefined, typeParameters, parameters, type); node.transformFlags = 1; return node; } @@ -17266,7 +17662,7 @@ var ts; return updateConstructorTypeNode1(node, node.modifiers, typeParameters, parameters, type); } function createTypeQueryNode(exprName) { - var node = createBaseNode(176); + var node = createBaseNode(177); node.exprName = exprName; node.transformFlags = 1; return node; @@ -17277,7 +17673,7 @@ var ts; : node; } function createTypeLiteralNode(members) { - var node = createBaseNode(177); + var node = createBaseNode(178); node.members = createNodeArray(members); node.transformFlags = 1; return node; @@ -17288,7 +17684,7 @@ var ts; : node; } function createArrayTypeNode(elementType) { - var node = createBaseNode(178); + var node = createBaseNode(179); node.elementType = parenthesizerRules().parenthesizeElementTypeOfArrayType(elementType); node.transformFlags = 1; return node; @@ -17299,7 +17695,7 @@ var ts; : node; } function createTupleTypeNode(elements) { - var node = createBaseNode(179); + var node = createBaseNode(180); node.elements = createNodeArray(elements); node.transformFlags = 1; return node; @@ -17310,7 +17706,7 @@ var ts; : node; } function createNamedTupleMember(dotDotDotToken, name, questionToken, type) { - var node = createBaseNode(192); + var node = createBaseNode(193); node.dotDotDotToken = dotDotDotToken; node.name = name; node.questionToken = questionToken; @@ -17327,7 +17723,7 @@ var ts; : node; } function createOptionalTypeNode(type) { - var node = createBaseNode(180); + var node = createBaseNode(181); node.type = parenthesizerRules().parenthesizeElementTypeOfArrayType(type); node.transformFlags = 1; return node; @@ -17338,7 +17734,7 @@ var ts; : node; } function createRestTypeNode(type) { - var node = createBaseNode(181); + var node = createBaseNode(182); node.type = type; node.transformFlags = 1; return node; @@ -17360,19 +17756,19 @@ var ts; : node; } function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(182, types); + return createUnionOrIntersectionTypeNode(183, types); } function updateUnionTypeNode(node, types) { return updateUnionOrIntersectionTypeNode(node, types); } function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(183, types); + return createUnionOrIntersectionTypeNode(184, types); } function updateIntersectionTypeNode(node, types) { return updateUnionOrIntersectionTypeNode(node, types); } function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { - var node = createBaseNode(184); + var node = createBaseNode(185); node.checkType = parenthesizerRules().parenthesizeMemberOfConditionalType(checkType); node.extendsType = parenthesizerRules().parenthesizeMemberOfConditionalType(extendsType); node.trueType = trueType; @@ -17389,7 +17785,7 @@ var ts; : node; } function createInferTypeNode(typeParameter) { - var node = createBaseNode(185); + var node = createBaseNode(186); node.typeParameter = typeParameter; node.transformFlags = 1; return node; @@ -17400,7 +17796,7 @@ var ts; : node; } function createTemplateLiteralType(head, templateSpans) { - var node = createBaseNode(193); + var node = createBaseNode(194); node.head = head; node.templateSpans = createNodeArray(templateSpans); node.transformFlags = 1; @@ -17414,7 +17810,7 @@ var ts; } function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { if (isTypeOf === void 0) { isTypeOf = false; } - var node = createBaseNode(195); + var node = createBaseNode(196); node.argument = argument; node.qualifier = qualifier; node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); @@ -17432,7 +17828,7 @@ var ts; : node; } function createParenthesizedType(type) { - var node = createBaseNode(186); + var node = createBaseNode(187); node.type = type; node.transformFlags = 1; return node; @@ -17443,12 +17839,12 @@ var ts; : node; } function createThisTypeNode() { - var node = createBaseNode(187); + var node = createBaseNode(188); node.transformFlags = 1; return node; } function createTypeOperatorNode(operator, type) { - var node = createBaseNode(188); + var node = createBaseNode(189); node.operator = operator; node.type = parenthesizerRules().parenthesizeMemberOfElementType(type); node.transformFlags = 1; @@ -17460,7 +17856,7 @@ var ts; : node; } function createIndexedAccessTypeNode(objectType, indexType) { - var node = createBaseNode(189); + var node = createBaseNode(190); node.objectType = parenthesizerRules().parenthesizeMemberOfElementType(objectType); node.indexType = indexType; node.transformFlags = 1; @@ -17473,7 +17869,7 @@ var ts; : node; } function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type) { - var node = createBaseNode(190); + var node = createBaseNode(191); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.nameType = nameType; @@ -17492,7 +17888,7 @@ var ts; : node; } function createLiteralTypeNode(literal) { - var node = createBaseNode(191); + var node = createBaseNode(192); node.literal = literal; node.transformFlags = 1; return node; @@ -17503,16 +17899,16 @@ var ts; : node; } function createObjectBindingPattern(elements) { - var node = createBaseNode(196); + var node = createBaseNode(197); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | - 256 | - 131072; - if (node.transformFlags & 8192) { + 512 | + 262144; + if (node.transformFlags & 16384) { node.transformFlags |= - 32 | - 16384; + 64 | + 32768; } return node; } @@ -17522,12 +17918,12 @@ var ts; : node; } function createArrayBindingPattern(elements) { - var node = createBaseNode(197); + var node = createBaseNode(198); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | - 256 | - 131072; + 512 | + 262144; return node; } function updateArrayBindingPattern(node, elements) { @@ -17536,19 +17932,19 @@ var ts; : node; } function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createBaseBindingLikeDeclaration(198, undefined, undefined, name, initializer); + var node = createBaseBindingLikeDeclaration(199, undefined, undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; node.transformFlags |= propagateChildFlags(node.dotDotDotToken) | - 256; + 512; if (node.propertyName) { node.transformFlags |= ts.isIdentifier(node.propertyName) ? propagateIdentifierNameFlags(node.propertyName) : propagateChildFlags(node.propertyName); } if (dotDotDotToken) - node.transformFlags |= 8192; + node.transformFlags |= 16384; return node; } function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) { @@ -17564,7 +17960,7 @@ var ts; return node; } function createArrayLiteralExpression(elements, multiLine) { - var node = createBaseExpression(199); + var node = createBaseExpression(200); node.elements = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(elements)); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.elements); @@ -17576,7 +17972,7 @@ var ts; : node; } function createObjectLiteralExpression(properties, multiLine) { - var node = createBaseExpression(200); + var node = createBaseExpression(201); node.properties = createNodeArray(properties); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.properties); @@ -17588,7 +17984,7 @@ var ts; : node; } function createPropertyAccessExpression(expression, name) { - var node = createBaseExpression(201); + var node = createBaseExpression(202); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.name = asName(name); node.transformFlags = @@ -17598,8 +17994,8 @@ var ts; propagateChildFlags(node.name)); if (ts.isSuperKeyword(expression)) { node.transformFlags |= - 64 | - 32; + 128 | + 64; } return node; } @@ -17613,13 +18009,13 @@ var ts; : node; } function createPropertyAccessChain(expression, questionDotToken, name) { - var node = createBaseExpression(201); + var node = createBaseExpression(202); node.flags |= 32; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.questionDotToken = questionDotToken; node.name = asName(name); node.transformFlags |= - 8 | + 16 | propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | (ts.isIdentifier(node.name) ? @@ -17636,7 +18032,7 @@ var ts; : node; } function createElementAccessExpression(expression, index) { - var node = createBaseExpression(202); + var node = createBaseExpression(203); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.argumentExpression = asExpression(index); node.transformFlags |= @@ -17644,8 +18040,8 @@ var ts; propagateChildFlags(node.argumentExpression); if (ts.isSuperKeyword(expression)) { node.transformFlags |= - 64 | - 32; + 128 | + 64; } return node; } @@ -17659,7 +18055,7 @@ var ts; : node; } function createElementAccessChain(expression, questionDotToken, index) { - var node = createBaseExpression(202); + var node = createBaseExpression(203); node.flags |= 32; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.questionDotToken = questionDotToken; @@ -17668,7 +18064,7 @@ var ts; propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | propagateChildFlags(node.argumentExpression) | - 8; + 16; return node; } function updateElementAccessChain(node, expression, questionDotToken, argumentExpression) { @@ -17680,7 +18076,7 @@ var ts; : node; } function createCallExpression(expression, typeArguments, argumentsArray) { - var node = createBaseExpression(203); + var node = createBaseExpression(204); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); @@ -17692,10 +18088,10 @@ var ts; node.transformFlags |= 1; } if (ts.isImportKeyword(node.expression)) { - node.transformFlags |= 2097152; + node.transformFlags |= 4194304; } else if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 4096; + node.transformFlags |= 8192; } return node; } @@ -17710,7 +18106,7 @@ var ts; : node; } function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) { - var node = createBaseExpression(203); + var node = createBaseExpression(204); node.flags |= 32; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.questionDotToken = questionDotToken; @@ -17721,12 +18117,12 @@ var ts; propagateChildFlags(node.questionDotToken) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | - 8; + 16; if (node.typeArguments) { node.transformFlags |= 1; } if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 4096; + node.transformFlags |= 8192; } return node; } @@ -17740,7 +18136,7 @@ var ts; : node; } function createNewExpression(expression, typeArguments, argumentsArray) { - var node = createBaseExpression(204); + var node = createBaseExpression(205); node.expression = parenthesizerRules().parenthesizeExpressionOfNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(argumentsArray) : undefined; @@ -17748,7 +18144,7 @@ var ts; propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | - 8; + 16; if (node.typeArguments) { node.transformFlags |= 1; } @@ -17762,7 +18158,7 @@ var ts; : node; } function createTaggedTemplateExpression(tag, typeArguments, template) { - var node = createBaseExpression(205); + var node = createBaseExpression(206); node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag); node.typeArguments = asNodeArray(typeArguments); node.template = template; @@ -17770,12 +18166,12 @@ var ts; propagateChildFlags(node.tag) | propagateChildrenFlags(node.typeArguments) | propagateChildFlags(node.template) | - 256; + 512; if (node.typeArguments) { node.transformFlags |= 1; } if (ts.hasInvalidEscape(node.template)) { - node.transformFlags |= 32; + node.transformFlags |= 64; } return node; } @@ -17787,7 +18183,7 @@ var ts; : node; } function createTypeAssertion(type, expression) { - var node = createBaseExpression(206); + var node = createBaseExpression(207); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.type = type; node.transformFlags |= @@ -17803,7 +18199,7 @@ var ts; : node; } function createParenthesizedExpression(expression) { - var node = createBaseExpression(207); + var node = createBaseExpression(208); node.expression = expression; node.transformFlags = propagateChildFlags(node.expression); return node; @@ -17814,7 +18210,7 @@ var ts; : node; } function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(208, undefined, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(209, undefined, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.asteriskToken); if (node.typeParameters) { @@ -17822,14 +18218,14 @@ var ts; } if (ts.modifiersToFlags(node.modifiers) & 256) { if (node.asteriskToken) { - node.transformFlags |= 32; + node.transformFlags |= 64; } else { - node.transformFlags |= 64; + node.transformFlags |= 128; } } else if (node.asteriskToken) { - node.transformFlags |= 512; + node.transformFlags |= 1024; } return node; } @@ -17845,13 +18241,13 @@ var ts; : node; } function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createBaseFunctionLikeDeclaration(209, undefined, modifiers, undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body)); + var node = createBaseFunctionLikeDeclaration(210, undefined, modifiers, undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body)); node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38); node.transformFlags |= propagateChildFlags(node.equalsGreaterThanToken) | - 256; + 512; if (ts.modifiersToFlags(node.modifiers) & 256) { - node.transformFlags |= 64; + node.transformFlags |= 128; } return node; } @@ -17866,7 +18262,7 @@ var ts; : node; } function createDeleteExpression(expression) { - var node = createBaseExpression(210); + var node = createBaseExpression(211); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -17877,7 +18273,7 @@ var ts; : node; } function createTypeOfExpression(expression) { - var node = createBaseExpression(211); + var node = createBaseExpression(212); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -17888,7 +18284,7 @@ var ts; : node; } function createVoidExpression(expression) { - var node = createBaseExpression(212); + var node = createBaseExpression(213); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -17899,13 +18295,13 @@ var ts; : node; } function createAwaitExpression(expression) { - var node = createBaseExpression(213); + var node = createBaseExpression(214); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression) | + 128 | 64 | - 32 | - 524288; + 1048576; return node; } function updateAwaitExpression(node, expression) { @@ -17914,7 +18310,7 @@ var ts; : node; } function createPrefixUnaryExpression(operator, operand) { - var node = createBaseExpression(214); + var node = createBaseExpression(215); node.operator = operator; node.operand = parenthesizerRules().parenthesizeOperandOfPrefixUnary(operand); node.transformFlags |= propagateChildFlags(node.operand); @@ -17926,7 +18322,7 @@ var ts; : node; } function createPostfixUnaryExpression(operand, operator) { - var node = createBaseExpression(215); + var node = createBaseExpression(216); node.operator = operator; node.operand = parenthesizerRules().parenthesizeOperandOfPostfixUnary(operand); node.transformFlags = propagateChildFlags(node.operand); @@ -17938,7 +18334,7 @@ var ts; : node; } function createBinaryExpression(left, operator, right) { - var node = createBaseExpression(216); + var node = createBaseExpression(217); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = parenthesizerRules().parenthesizeLeftSideOfBinary(operatorKind, left); @@ -17949,43 +18345,43 @@ var ts; propagateChildFlags(node.operatorToken) | propagateChildFlags(node.right); if (operatorKind === 60) { - node.transformFlags |= 8; + node.transformFlags |= 16; } else if (operatorKind === 62) { if (ts.isObjectLiteralExpression(node.left)) { node.transformFlags |= - 256 | - 32 | - 1024 | + 512 | + 64 | + 2048 | propagateAssignmentPatternFlags(node.left); } else if (ts.isArrayLiteralExpression(node.left)) { node.transformFlags |= - 256 | - 1024 | + 512 | + 2048 | propagateAssignmentPatternFlags(node.left); } } else if (operatorKind === 42 || operatorKind === 66) { - node.transformFlags |= 128; + node.transformFlags |= 256; } else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) { - node.transformFlags |= 4; + node.transformFlags |= 8; } return node; } function propagateAssignmentPatternFlags(node) { - if (node.transformFlags & 16384) - return 16384; - if (node.transformFlags & 32) { + if (node.transformFlags & 32768) + return 32768; + if (node.transformFlags & 64) { for (var _i = 0, _a = ts.getElementsOfBindingOrAssignmentPattern(node); _i < _a.length; _i++) { var element = _a[_i]; var target = ts.getTargetOfBindingOrAssignmentElement(element); if (target && ts.isAssignmentPattern(target)) { - if (target.transformFlags & 16384) { - return 16384; + if (target.transformFlags & 32768) { + return 32768; } - if (target.transformFlags & 32) { + if (target.transformFlags & 64) { var flags_1 = propagateAssignmentPatternFlags(target); if (flags_1) return flags_1; @@ -18003,7 +18399,7 @@ var ts; : node; } function createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse) { - var node = createBaseExpression(217); + var node = createBaseExpression(218); node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression(condition); node.questionToken = questionToken !== null && questionToken !== void 0 ? questionToken : createToken(57); node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue); @@ -18027,13 +18423,13 @@ var ts; : node; } function createTemplateExpression(head, templateSpans) { - var node = createBaseExpression(218); + var node = createBaseExpression(219); node.head = head; node.templateSpans = createNodeArray(templateSpans); node.transformFlags |= propagateChildFlags(node.head) | propagateChildrenFlags(node.templateSpans) | - 256; + 512; return node; } function updateTemplateExpression(node, head, templateSpans) { @@ -18068,9 +18464,9 @@ var ts; node.text = text; node.rawText = rawText; node.templateFlags = templateFlags & 2048; - node.transformFlags |= 256; + node.transformFlags |= 512; if (node.templateFlags) { - node.transformFlags |= 32; + node.transformFlags |= 64; } return node; } @@ -18088,15 +18484,15 @@ var ts; } function createYieldExpression(asteriskToken, expression) { ts.Debug.assert(!asteriskToken || !!expression, "A `YieldExpression` with an asteriskToken must have an expression."); - var node = createBaseExpression(219); + var node = createBaseExpression(220); node.expression = expression && parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.asteriskToken) | - 256 | - 32 | - 262144; + 512 | + 64 | + 524288; return node; } function updateYieldExpression(node, asteriskToken, expression) { @@ -18106,12 +18502,12 @@ var ts; : node; } function createSpreadElement(expression) { - var node = createBaseExpression(220); + var node = createBaseExpression(221); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 256 | - 8192; + 512 | + 16384; return node; } function updateSpreadElement(node, expression) { @@ -18120,8 +18516,8 @@ var ts; : node; } function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(221, decorators, modifiers, name, typeParameters, heritageClauses, members); - node.transformFlags |= 256; + var node = createBaseClassLikeDeclaration(222, decorators, modifiers, name, typeParameters, heritageClauses, members); + node.transformFlags |= 512; return node; } function updateClassExpression(node, decorators, modifiers, name, typeParameters, heritageClauses, members) { @@ -18135,16 +18531,16 @@ var ts; : node; } function createOmittedExpression() { - return createBaseExpression(222); + return createBaseExpression(223); } function createExpressionWithTypeArguments(expression, typeArguments) { - var node = createBaseNode(223); + var node = createBaseNode(224); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | - 256; + 512; return node; } function updateExpressionWithTypeArguments(node, expression, typeArguments) { @@ -18154,7 +18550,7 @@ var ts; : node; } function createAsExpression(expression, type) { - var node = createBaseExpression(224); + var node = createBaseExpression(225); node.expression = expression; node.type = type; node.transformFlags |= @@ -18170,7 +18566,7 @@ var ts; : node; } function createNonNullExpression(expression) { - var node = createBaseExpression(225); + var node = createBaseExpression(226); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.transformFlags |= propagateChildFlags(node.expression) | @@ -18186,7 +18582,7 @@ var ts; : node; } function createNonNullChain(expression) { - var node = createBaseExpression(225); + var node = createBaseExpression(226); node.flags |= 32; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.transformFlags |= @@ -18201,13 +18597,13 @@ var ts; : node; } function createMetaProperty(keywordToken, name) { - var node = createBaseExpression(226); + var node = createBaseExpression(227); node.keywordToken = keywordToken; node.name = name; node.transformFlags |= propagateChildFlags(node.name); switch (keywordToken) { case 102: - node.transformFlags |= 256; + node.transformFlags |= 512; break; case 99: node.transformFlags |= 4; @@ -18223,13 +18619,13 @@ var ts; : node; } function createTemplateSpan(expression, literal) { - var node = createBaseNode(228); + var node = createBaseNode(229); node.expression = expression; node.literal = literal; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.literal) | - 256; + 512; return node; } function updateTemplateSpan(node, expression, literal) { @@ -18239,12 +18635,12 @@ var ts; : node; } function createSemicolonClassElement() { - var node = createBaseNode(229); - node.transformFlags |= 256; + var node = createBaseNode(230); + node.transformFlags |= 512; return node; } function createBlock(statements, multiLine) { - var node = createBaseNode(230); + var node = createBaseNode(231); node.statements = createNodeArray(statements); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.statements); @@ -18256,7 +18652,7 @@ var ts; : node; } function createVariableStatement(modifiers, declarationList) { - var node = createBaseDeclaration(232, undefined, modifiers); + var node = createBaseDeclaration(233, undefined, modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; node.transformFlags |= propagateChildFlags(node.declarationList); @@ -18272,10 +18668,10 @@ var ts; : node; } function createEmptyStatement() { - return createBaseNode(231); + return createBaseNode(232); } function createExpressionStatement(expression) { - var node = createBaseNode(233); + var node = createBaseNode(234); node.expression = parenthesizerRules().parenthesizeExpressionOfExpressionStatement(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -18286,7 +18682,7 @@ var ts; : node; } function createIfStatement(expression, thenStatement, elseStatement) { - var node = createBaseNode(234); + var node = createBaseNode(235); node.expression = expression; node.thenStatement = asEmbeddedStatement(thenStatement); node.elseStatement = asEmbeddedStatement(elseStatement); @@ -18304,7 +18700,7 @@ var ts; : node; } function createDoStatement(statement, expression) { - var node = createBaseNode(235); + var node = createBaseNode(236); node.statement = asEmbeddedStatement(statement); node.expression = expression; node.transformFlags |= @@ -18319,7 +18715,7 @@ var ts; : node; } function createWhileStatement(expression, statement) { - var node = createBaseNode(236); + var node = createBaseNode(237); node.expression = expression; node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -18334,7 +18730,7 @@ var ts; : node; } function createForStatement(initializer, condition, incrementor, statement) { - var node = createBaseNode(237); + var node = createBaseNode(238); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -18355,7 +18751,7 @@ var ts; : node; } function createForInStatement(initializer, expression, statement) { - var node = createBaseNode(238); + var node = createBaseNode(239); node.initializer = initializer; node.expression = expression; node.statement = asEmbeddedStatement(statement); @@ -18373,7 +18769,7 @@ var ts; : node; } function createForOfStatement(awaitModifier, initializer, expression, statement) { - var node = createBaseNode(239); + var node = createBaseNode(240); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); @@ -18383,9 +18779,9 @@ var ts; propagateChildFlags(node.initializer) | propagateChildFlags(node.expression) | propagateChildFlags(node.statement) | - 256; + 512; if (awaitModifier) - node.transformFlags |= 32; + node.transformFlags |= 64; return node; } function updateForOfStatement(node, awaitModifier, initializer, expression, statement) { @@ -18397,11 +18793,11 @@ var ts; : node; } function createContinueStatement(label) { - var node = createBaseNode(240); + var node = createBaseNode(241); node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 1048576; + 2097152; return node; } function updateContinueStatement(node, label) { @@ -18410,11 +18806,11 @@ var ts; : node; } function createBreakStatement(label) { - var node = createBaseNode(241); + var node = createBaseNode(242); node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 1048576; + 2097152; return node; } function updateBreakStatement(node, label) { @@ -18423,12 +18819,12 @@ var ts; : node; } function createReturnStatement(expression) { - var node = createBaseNode(242); + var node = createBaseNode(243); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression) | - 32 | - 1048576; + 64 | + 2097152; return node; } function updateReturnStatement(node, expression) { @@ -18437,7 +18833,7 @@ var ts; : node; } function createWithStatement(expression, statement) { - var node = createBaseNode(243); + var node = createBaseNode(244); node.expression = expression; node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -18452,7 +18848,7 @@ var ts; : node; } function createSwitchStatement(expression, caseBlock) { - var node = createBaseNode(244); + var node = createBaseNode(245); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.caseBlock = caseBlock; node.transformFlags |= @@ -18467,7 +18863,7 @@ var ts; : node; } function createLabeledStatement(label, statement) { - var node = createBaseNode(245); + var node = createBaseNode(246); node.label = asName(label); node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -18482,7 +18878,7 @@ var ts; : node; } function createThrowStatement(expression) { - var node = createBaseNode(246); + var node = createBaseNode(247); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -18493,7 +18889,7 @@ var ts; : node; } function createTryStatement(tryBlock, catchClause, finallyBlock) { - var node = createBaseNode(247); + var node = createBaseNode(248); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -18511,10 +18907,10 @@ var ts; : node; } function createDebuggerStatement() { - return createBaseNode(248); + return createBaseNode(249); } function createVariableDeclaration(name, exclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(249, undefined, undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); + var node = createBaseVariableLikeDeclaration(250, undefined, undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.exclamationToken = exclamationToken; node.transformFlags |= propagateChildFlags(node.exclamationToken); if (exclamationToken) { @@ -18532,16 +18928,16 @@ var ts; } function createVariableDeclarationList(declarations, flags) { if (flags === void 0) { flags = 0; } - var node = createBaseNode(250); + var node = createBaseNode(251); node.flags |= flags & 3; node.declarations = createNodeArray(declarations); node.transformFlags |= propagateChildrenFlags(node.declarations) | - 1048576; + 2097152; if (flags & 3) { node.transformFlags |= - 256 | - 65536; + 512 | + 131072; } return node; } @@ -18551,7 +18947,7 @@ var ts; : node; } function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(251, decorators, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(252, decorators, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; if (!node.body || ts.modifiersToFlags(node.modifiers) & 2) { node.transformFlags = 1; @@ -18559,17 +18955,17 @@ var ts; else { node.transformFlags |= propagateChildFlags(node.asteriskToken) | - 1048576; + 2097152; if (ts.modifiersToFlags(node.modifiers) & 256) { if (node.asteriskToken) { - node.transformFlags |= 32; + node.transformFlags |= 64; } else { - node.transformFlags |= 64; + node.transformFlags |= 128; } } else if (node.asteriskToken) { - node.transformFlags |= 512; + node.transformFlags |= 1024; } } return node; @@ -18587,13 +18983,13 @@ var ts; : node; } function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(252, decorators, modifiers, name, typeParameters, heritageClauses, members); + var node = createBaseClassLikeDeclaration(253, decorators, modifiers, name, typeParameters, heritageClauses, members); if (ts.modifiersToFlags(node.modifiers) & 2) { node.transformFlags = 1; } else { - node.transformFlags |= 256; - if (node.transformFlags & 2048) { + node.transformFlags |= 512; + if (node.transformFlags & 4096) { node.transformFlags |= 1; } } @@ -18610,7 +19006,7 @@ var ts; : node; } function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(253, decorators, modifiers, name, typeParameters, heritageClauses); + var node = createBaseInterfaceOrClassLikeDeclaration(254, decorators, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags = 1; return node; @@ -18626,7 +19022,7 @@ var ts; : node; } function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createBaseGenericNamedDeclaration(254, decorators, modifiers, name, typeParameters); + var node = createBaseGenericNamedDeclaration(255, decorators, modifiers, name, typeParameters); node.type = type; node.transformFlags = 1; return node; @@ -18641,12 +19037,12 @@ var ts; : node; } function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createBaseNamedDeclaration(255, decorators, modifiers, name); + var node = createBaseNamedDeclaration(256, decorators, modifiers, name); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members) | 1; - node.transformFlags &= ~8388608; + node.transformFlags &= ~16777216; return node; } function updateEnumDeclaration(node, decorators, modifiers, name, members) { @@ -18659,7 +19055,7 @@ var ts; } function createModuleDeclaration(decorators, modifiers, name, body, flags) { if (flags === void 0) { flags = 0; } - var node = createBaseDeclaration(256, decorators, modifiers); + var node = createBaseDeclaration(257, decorators, modifiers); node.flags |= flags & (16 | 4 | 1024); node.name = name; node.body = body; @@ -18672,7 +19068,7 @@ var ts; propagateChildFlags(node.body) | 1; } - node.transformFlags &= ~8388608; + node.transformFlags &= ~16777216; return node; } function updateModuleDeclaration(node, decorators, modifiers, name, body) { @@ -18684,7 +19080,7 @@ var ts; : node; } function createModuleBlock(statements) { - var node = createBaseNode(257); + var node = createBaseNode(258); node.statements = createNodeArray(statements); node.transformFlags |= propagateChildrenFlags(node.statements); return node; @@ -18695,7 +19091,7 @@ var ts; : node; } function createCaseBlock(clauses) { - var node = createBaseNode(258); + var node = createBaseNode(259); node.clauses = createNodeArray(clauses); node.transformFlags |= propagateChildrenFlags(node.clauses); return node; @@ -18706,7 +19102,7 @@ var ts; : node; } function createNamespaceExportDeclaration(name) { - var node = createBaseNamedDeclaration(259, undefined, undefined, name); + var node = createBaseNamedDeclaration(260, undefined, undefined, name); node.transformFlags = 1; return node; } @@ -18716,13 +19112,13 @@ var ts; : node; } function createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference) { - var node = createBaseNamedDeclaration(260, decorators, modifiers, name); + var node = createBaseNamedDeclaration(261, decorators, modifiers, name); node.isTypeOnly = isTypeOnly; node.moduleReference = moduleReference; node.transformFlags |= propagateChildFlags(node.moduleReference); if (!ts.isExternalModuleReference(node.moduleReference)) node.transformFlags |= 1; - node.transformFlags &= ~8388608; + node.transformFlags &= ~16777216; return node; } function updateImportEqualsDeclaration(node, decorators, modifiers, isTypeOnly, name, moduleReference) { @@ -18735,13 +19131,13 @@ var ts; : node; } function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createBaseDeclaration(261, decorators, modifiers); + var node = createBaseDeclaration(262, decorators, modifiers); node.importClause = importClause; node.moduleSpecifier = moduleSpecifier; node.transformFlags |= propagateChildFlags(node.importClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~8388608; + node.transformFlags &= ~16777216; return node; } function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) { @@ -18753,7 +19149,7 @@ var ts; : node; } function createImportClause(isTypeOnly, name, namedBindings) { - var node = createBaseNode(262); + var node = createBaseNode(263); node.isTypeOnly = isTypeOnly; node.name = name; node.namedBindings = namedBindings; @@ -18763,7 +19159,7 @@ var ts; if (isTypeOnly) { node.transformFlags |= 1; } - node.transformFlags &= ~8388608; + node.transformFlags &= ~16777216; return node; } function updateImportClause(node, isTypeOnly, name, namedBindings) { @@ -18774,10 +19170,10 @@ var ts; : node; } function createNamespaceImport(name) { - var node = createBaseNode(263); + var node = createBaseNode(264); node.name = name; node.transformFlags |= propagateChildFlags(node.name); - node.transformFlags &= ~8388608; + node.transformFlags &= ~16777216; return node; } function updateNamespaceImport(node, name) { @@ -18786,12 +19182,12 @@ var ts; : node; } function createNamespaceExport(name) { - var node = createBaseNode(269); + var node = createBaseNode(270); node.name = name; node.transformFlags |= propagateChildFlags(node.name) | 4; - node.transformFlags &= ~8388608; + node.transformFlags &= ~16777216; return node; } function updateNamespaceExport(node, name) { @@ -18800,10 +19196,10 @@ var ts; : node; } function createNamedImports(elements) { - var node = createBaseNode(264); + var node = createBaseNode(265); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~8388608; + node.transformFlags &= ~16777216; return node; } function updateNamedImports(node, elements) { @@ -18812,13 +19208,13 @@ var ts; : node; } function createImportSpecifier(propertyName, name) { - var node = createBaseNode(265); + var node = createBaseNode(266); node.propertyName = propertyName; node.name = name; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~8388608; + node.transformFlags &= ~16777216; return node; } function updateImportSpecifier(node, propertyName, name) { @@ -18828,13 +19224,13 @@ var ts; : node; } function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createBaseDeclaration(266, decorators, modifiers); + var node = createBaseDeclaration(267, decorators, modifiers); node.isExportEquals = isExportEquals; node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary(62, undefined, expression) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~8388608; + node.transformFlags &= ~16777216; return node; } function updateExportAssignment(node, decorators, modifiers, expression) { @@ -18845,14 +19241,14 @@ var ts; : node; } function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier) { - var node = createBaseDeclaration(267, decorators, modifiers); + var node = createBaseDeclaration(268, decorators, modifiers); node.isTypeOnly = isTypeOnly; node.exportClause = exportClause; node.moduleSpecifier = moduleSpecifier; node.transformFlags |= propagateChildFlags(node.exportClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~8388608; + node.transformFlags &= ~16777216; return node; } function updateExportDeclaration(node, decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier) { @@ -18865,10 +19261,10 @@ var ts; : node; } function createNamedExports(elements) { - var node = createBaseNode(268); + var node = createBaseNode(269); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~8388608; + node.transformFlags &= ~16777216; return node; } function updateNamedExports(node, elements) { @@ -18877,13 +19273,13 @@ var ts; : node; } function createExportSpecifier(propertyName, name) { - var node = createBaseNode(270); + var node = createBaseNode(271); node.propertyName = asName(propertyName); node.name = asName(name); node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~8388608; + node.transformFlags &= ~16777216; return node; } function updateExportSpecifier(node, propertyName, name) { @@ -18893,14 +19289,14 @@ var ts; : node; } function createMissingDeclaration() { - var node = createBaseDeclaration(271, undefined, undefined); + var node = createBaseDeclaration(272, undefined, undefined); return node; } function createExternalModuleReference(expression) { - var node = createBaseNode(272); + var node = createBaseNode(273); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~8388608; + node.transformFlags &= ~16777216; return node; } function updateExternalModuleReference(node, expression) { @@ -18922,7 +19318,7 @@ var ts; : node; } function createJSDocFunctionType(parameters, type) { - var node = createBaseSignatureDeclaration(308, undefined, undefined, undefined, undefined, parameters, type); + var node = createBaseSignatureDeclaration(309, undefined, undefined, undefined, undefined, parameters, type); return node; } function updateJSDocFunctionType(node, parameters, type) { @@ -18933,7 +19329,7 @@ var ts; } function createJSDocTypeLiteral(propertyTags, isArrayType) { if (isArrayType === void 0) { isArrayType = false; } - var node = createBaseNode(312); + var node = createBaseNode(314); node.jsDocPropertyTags = asNodeArray(propertyTags); node.isArrayType = isArrayType; return node; @@ -18945,7 +19341,7 @@ var ts; : node; } function createJSDocTypeExpression(type) { - var node = createBaseNode(301); + var node = createBaseNode(302); node.type = type; return node; } @@ -18955,7 +19351,7 @@ var ts; : node; } function createJSDocSignature(typeParameters, parameters, type) { - var node = createBaseNode(313); + var node = createBaseNode(315); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; @@ -18981,7 +19377,7 @@ var ts; return node; } function createJSDocTemplateTag(tagName, constraint, typeParameters, comment) { - var node = createBaseJSDocTag(330, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment); + var node = createBaseJSDocTag(334, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment); node.constraint = constraint; node.typeParameters = createNodeArray(typeParameters); return node; @@ -18996,7 +19392,7 @@ var ts; : node; } function createJSDocTypedefTag(tagName, typeExpression, fullName, comment) { - var node = createBaseJSDocTag(331, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment); + var node = createBaseJSDocTag(335, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment); node.typeExpression = typeExpression; node.fullName = fullName; node.name = ts.getJSDocTypeAliasName(fullName); @@ -19012,7 +19408,7 @@ var ts; : node; } function createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { - var node = createBaseJSDocTag(326, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment); + var node = createBaseJSDocTag(330, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -19031,7 +19427,7 @@ var ts; : node; } function createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { - var node = createBaseJSDocTag(333, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment); + var node = createBaseJSDocTag(337, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -19050,7 +19446,7 @@ var ts; : node; } function createJSDocCallbackTag(tagName, typeExpression, fullName, comment) { - var node = createBaseJSDocTag(324, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment); + var node = createBaseJSDocTag(328, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment); node.typeExpression = typeExpression; node.fullName = fullName; node.name = ts.getJSDocTypeAliasName(fullName); @@ -19066,7 +19462,7 @@ var ts; : node; } function createJSDocAugmentsTag(tagName, className, comment) { - var node = createBaseJSDocTag(315, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment); + var node = createBaseJSDocTag(318, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment); node.class = className; return node; } @@ -19079,12 +19475,12 @@ var ts; : node; } function createJSDocImplementsTag(tagName, className, comment) { - var node = createBaseJSDocTag(316, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment); + var node = createBaseJSDocTag(319, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment); node.class = className; return node; } function createJSDocSeeTag(tagName, name, comment) { - var node = createBaseJSDocTag(332, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment); + var node = createBaseJSDocTag(336, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment); node.name = name; return node; } @@ -19096,7 +19492,7 @@ var ts; : node; } function createJSDocNameReference(name) { - var node = createBaseNode(302); + var node = createBaseNode(303); node.name = name; return node; } @@ -19105,6 +19501,17 @@ var ts; ? update(createJSDocNameReference(name), node) : node; } + function createJSDocLink(name, text) { + var node = createBaseNode(316); + node.name = name; + node.text = text; + return node; + } + function updateJSDocLink(node, name, text) { + return node.name !== name + ? update(createJSDocLink(name, text), node) + : node; + } function updateJSDocImplementsTag(node, tagName, className, comment) { if (tagName === void 0) { tagName = getDefaultTagName(node); } return node.tagName !== tagName @@ -19138,7 +19545,7 @@ var ts; : node; } function createJSDocUnknownTag(tagName, comment) { - var node = createBaseJSDocTag(314, tagName, comment); + var node = createBaseJSDocTag(317, tagName, comment); return node; } function updateJSDocUnknownTag(node, tagName, comment) { @@ -19147,8 +19554,18 @@ var ts; ? update(createJSDocUnknownTag(tagName, comment), node) : node; } + function createJSDocText(text) { + var node = createBaseNode(313); + node.text = text; + return node; + } + function updateJSDocText(node, text) { + return node.text !== text + ? update(createJSDocText(text), node) + : node; + } function createJSDocComment(comment, tags) { - var node = createBaseNode(311); + var node = createBaseNode(312); node.comment = comment; node.tags = asNodeArray(tags); return node; @@ -19160,7 +19577,7 @@ var ts; : node; } function createJsxElement(openingElement, children, closingElement) { - var node = createBaseNode(273); + var node = createBaseNode(274); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -19179,7 +19596,7 @@ var ts; : node; } function createJsxSelfClosingElement(tagName, typeArguments, attributes) { - var node = createBaseNode(274); + var node = createBaseNode(275); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -19201,7 +19618,7 @@ var ts; : node; } function createJsxOpeningElement(tagName, typeArguments, attributes) { - var node = createBaseNode(275); + var node = createBaseNode(276); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -19223,7 +19640,7 @@ var ts; : node; } function createJsxClosingElement(tagName) { - var node = createBaseNode(276); + var node = createBaseNode(277); node.tagName = tagName; node.transformFlags |= propagateChildFlags(node.tagName) | @@ -19236,7 +19653,7 @@ var ts; : node; } function createJsxFragment(openingFragment, children, closingFragment) { - var node = createBaseNode(277); + var node = createBaseNode(278); node.openingFragment = openingFragment; node.children = createNodeArray(children); node.closingFragment = closingFragment; @@ -19268,17 +19685,17 @@ var ts; : node; } function createJsxOpeningFragment() { - var node = createBaseNode(278); + var node = createBaseNode(279); node.transformFlags |= 2; return node; } function createJsxJsxClosingFragment() { - var node = createBaseNode(279); + var node = createBaseNode(280); node.transformFlags |= 2; return node; } function createJsxAttribute(name, initializer) { - var node = createBaseNode(280); + var node = createBaseNode(281); node.name = name; node.initializer = initializer; node.transformFlags |= @@ -19294,7 +19711,7 @@ var ts; : node; } function createJsxAttributes(properties) { - var node = createBaseNode(281); + var node = createBaseNode(282); node.properties = createNodeArray(properties); node.transformFlags |= propagateChildrenFlags(node.properties) | @@ -19307,7 +19724,7 @@ var ts; : node; } function createJsxSpreadAttribute(expression) { - var node = createBaseNode(282); + var node = createBaseNode(283); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression) | @@ -19320,7 +19737,7 @@ var ts; : node; } function createJsxExpression(dotDotDotToken, expression) { - var node = createBaseNode(283); + var node = createBaseNode(284); node.dotDotDotToken = dotDotDotToken; node.expression = expression; node.transformFlags |= @@ -19335,7 +19752,7 @@ var ts; : node; } function createCaseClause(expression, statements) { - var node = createBaseNode(284); + var node = createBaseNode(285); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.statements = createNodeArray(statements); node.transformFlags |= @@ -19350,7 +19767,7 @@ var ts; : node; } function createDefaultClause(statements) { - var node = createBaseNode(285); + var node = createBaseNode(286); node.statements = createNodeArray(statements); node.transformFlags = propagateChildrenFlags(node.statements); return node; @@ -19361,13 +19778,13 @@ var ts; : node; } function createHeritageClause(token, types) { - var node = createBaseNode(286); + var node = createBaseNode(287); node.token = token; node.types = createNodeArray(types); node.transformFlags |= propagateChildrenFlags(node.types); switch (token) { case 93: - node.transformFlags |= 256; + node.transformFlags |= 512; break; case 116: node.transformFlags |= 1; @@ -19383,7 +19800,7 @@ var ts; : node; } function createCatchClause(variableDeclaration, block) { - var node = createBaseNode(287); + var node = createBaseNode(288); variableDeclaration = !ts.isString(variableDeclaration) ? variableDeclaration : createVariableDeclaration(variableDeclaration, undefined, undefined, undefined); node.variableDeclaration = variableDeclaration; node.block = block; @@ -19391,7 +19808,7 @@ var ts; propagateChildFlags(node.variableDeclaration) | propagateChildFlags(node.block); if (!variableDeclaration) - node.transformFlags |= 16; + node.transformFlags |= 32; return node; } function updateCatchClause(node, variableDeclaration, block) { @@ -19401,7 +19818,7 @@ var ts; : node; } function createPropertyAssignment(name, initializer) { - var node = createBaseNamedDeclaration(288, undefined, undefined, name); + var node = createBaseNamedDeclaration(289, undefined, undefined, name); node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); node.transformFlags |= propagateChildFlags(node.name) | @@ -19426,11 +19843,11 @@ var ts; : node; } function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createBaseNamedDeclaration(289, undefined, undefined, name); + var node = createBaseNamedDeclaration(290, undefined, undefined, name); node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); node.transformFlags |= propagateChildFlags(node.objectAssignmentInitializer) | - 256; + 512; return node; } function finishUpdateShorthandPropertyAssignment(updated, original) { @@ -19453,12 +19870,12 @@ var ts; : node; } function createSpreadAssignment(expression) { - var node = createBaseNode(290); + var node = createBaseNode(291); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 32 | - 16384; + 64 | + 32768; return node; } function updateSpreadAssignment(node, expression) { @@ -19467,7 +19884,7 @@ var ts; : node; } function createEnumMember(name, initializer) { - var node = createBaseNode(291); + var node = createBaseNode(292); node.name = asName(name); node.initializer = initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); node.transformFlags |= @@ -19483,7 +19900,7 @@ var ts; : node; } function createSourceFile(statements, endOfFileToken, flags) { - var node = baseFactory.createBaseSourceFileNode(297); + var node = baseFactory.createBaseSourceFileNode(298); node.statements = createNodeArray(statements); node.endOfFileToken = endOfFileToken; node.flags |= flags; @@ -19500,7 +19917,7 @@ var ts; return node; } function cloneSourceFileWithChanges(source, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) { - var node = baseFactory.createBaseSourceFileNode(297); + var node = baseFactory.createBaseSourceFileNode(298); for (var p in source) { if (p === "emitNode" || ts.hasProperty(node, p) || !ts.hasProperty(source, p)) continue; @@ -19536,7 +19953,7 @@ var ts; } function createBundle(sourceFiles, prepends) { if (prepends === void 0) { prepends = ts.emptyArray; } - var node = createBaseNode(298); + var node = createBaseNode(299); node.prepends = prepends; node.sourceFiles = sourceFiles; return node; @@ -19549,7 +19966,7 @@ var ts; : node; } function createUnparsedSource(prologues, syntheticReferences, texts) { - var node = createBaseNode(299); + var node = createBaseNode(300); node.prologues = prologues; node.syntheticReferences = syntheticReferences; node.texts = texts; @@ -19566,49 +19983,49 @@ var ts; return node; } function createUnparsedPrologue(data) { - return createBaseUnparsedNode(292, data); + return createBaseUnparsedNode(293, data); } function createUnparsedPrepend(data, texts) { - var node = createBaseUnparsedNode(293, data); + var node = createBaseUnparsedNode(294, data); node.texts = texts; return node; } function createUnparsedTextLike(data, internal) { - return createBaseUnparsedNode(internal ? 295 : 294, data); + return createBaseUnparsedNode(internal ? 296 : 295, data); } function createUnparsedSyntheticReference(section) { - var node = createBaseNode(296); + var node = createBaseNode(297); node.data = section.data; node.section = section; return node; } function createInputFiles() { - var node = createBaseNode(300); + var node = createBaseNode(301); node.javascriptText = ""; node.declarationText = ""; return node; } function createSyntheticExpression(type, isSpread, tupleNameSource) { if (isSpread === void 0) { isSpread = false; } - var node = createBaseNode(227); + var node = createBaseNode(228); node.type = type; node.isSpread = isSpread; node.tupleNameSource = tupleNameSource; return node; } function createSyntaxList(children) { - var node = createBaseNode(334); + var node = createBaseNode(338); node._children = children; return node; } function createNotEmittedStatement(original) { - var node = createBaseNode(335); + var node = createBaseNode(339); node.original = original; ts.setTextRange(node, original); return node; } function createPartiallyEmittedExpression(expression, original) { - var node = createBaseNode(336); + var node = createBaseNode(340); node.expression = expression; node.original = original; node.transformFlags |= @@ -19634,7 +20051,7 @@ var ts; return node; } function createCommaListExpression(elements) { - var node = createBaseNode(337); + var node = createBaseNode(341); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); node.transformFlags |= propagateChildrenFlags(node.elements); return node; @@ -19645,19 +20062,19 @@ var ts; : node; } function createEndOfDeclarationMarker(original) { - var node = createBaseNode(339); + var node = createBaseNode(343); node.emitNode = {}; node.original = original; return node; } function createMergeDeclarationMarker(original) { - var node = createBaseNode(338); + var node = createBaseNode(342); node.emitNode = {}; node.original = original; return node; } function createSyntheticReferenceExpression(expression, thisArg) { - var node = createBaseNode(340); + var node = createBaseNode(344); node.expression = expression; node.thisArg = thisArg; node.transformFlags |= @@ -19675,7 +20092,7 @@ var ts; if (node === undefined) { return node; } - var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(297) : + var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(298) : ts.isIdentifier(node) ? baseFactory.createBaseIdentifierNode(78) : ts.isPrivateIdentifier(node) ? baseFactory.createBasePrivateIdentifierNode(79) : !ts.isNodeKind(node.kind) ? baseFactory.createBaseTokenNode(node.kind) : @@ -19757,11 +20174,11 @@ var ts; } function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 207: return updateParenthesizedExpression(outerExpression, expression); - case 206: return updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 224: return updateAsExpression(outerExpression, expression, outerExpression.type); - case 225: return updateNonNullExpression(outerExpression, expression); - case 336: return updatePartiallyEmittedExpression(outerExpression, expression); + case 208: return updateParenthesizedExpression(outerExpression, expression); + case 207: return updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 225: return updateAsExpression(outerExpression, expression, outerExpression.type); + case 226: return updateNonNullExpression(outerExpression, expression); + case 340: return updatePartiallyEmittedExpression(outerExpression, expression); } } function isIgnorableParen(node) { @@ -19801,13 +20218,13 @@ var ts; case 9: case 10: return false; - case 199: + case 200: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 200: + case 201: return target.properties.length > 0; default: return true; @@ -20088,23 +20505,24 @@ var ts; } function getDefaultTagNameForKind(kind) { switch (kind) { - case 329: return "type"; - case 327: return "returns"; - case 328: return "this"; - case 325: return "enum"; - case 317: return "author"; - case 319: return "class"; - case 320: return "public"; - case 321: return "private"; - case 322: return "protected"; - case 323: return "readonly"; - case 330: return "template"; - case 331: return "typedef"; - case 326: return "param"; - case 333: return "prop"; - case 324: return "callback"; - case 315: return "augments"; - case 316: return "implements"; + case 333: return "type"; + case 331: return "returns"; + case 332: return "this"; + case 329: return "enum"; + case 320: return "author"; + case 322: return "class"; + case 323: return "public"; + case 324: return "private"; + case 325: return "protected"; + case 326: return "readonly"; + case 327: return "override"; + case 334: return "template"; + case 335: return "typedef"; + case 330: return "param"; + case 337: return "prop"; + case 328: return "callback"; + case 318: return "augments"; + case 319: return "implements"; default: return ts.Debug.fail("Unsupported kind: " + ts.Debug.formatSyntaxKind(kind)); } @@ -20154,10 +20572,10 @@ var ts; return tokenValue; } function propagateIdentifierNameFlags(node) { - return propagateChildFlags(node) & ~8388608; + return propagateChildFlags(node) & ~16777216; } function propagatePropertyNameFlagsOfChild(node, transformFlags) { - return transformFlags | (node.transformFlags & 4096); + return transformFlags | (node.transformFlags & 8192); } function propagateChildFlags(child) { if (!child) @@ -20177,36 +20595,36 @@ var ts; children.transformFlags = subtreeFlags; } function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 172 && kind <= 195) { + if (kind >= 173 && kind <= 196) { return -2; } switch (kind) { - case 203: case 204: - case 199: - return 536879104; - case 256: - return 546379776; - case 160: + case 205: + case 200: + return 536887296; + case 257: + return 555888640; + case 161: return 536870912; + case 210: + return 557748224; case 209: - return 547309568; - case 208: - case 251: - return 547313664; - case 250: - return 537018368; case 252: - case 221: - return 536905728; - case 166: - return 547311616; - case 163: - return 536875008; - case 165: + return 557756416; + case 251: + return 537165824; + case 253: + case 222: + return 536940544; case 167: + return 557752320; + case 164: + return 536879104; + case 166: case 168: - return 538923008; + case 169: + return 540975104; case 128: case 144: case 155: @@ -20216,30 +20634,30 @@ var ts; case 131: case 148: case 113: - case 159: - case 162: - case 164: - case 169: + case 160: + case 163: + case 165: case 170: case 171: - case 253: + case 172: case 254: + case 255: return -2; - case 200: - return 536922112; - case 287: - return 536887296; - case 196: + case 201: + return 536973312; + case 288: + return 536903680; case 197: - return 536879104; - case 206: - case 224: - case 336: + case 198: + return 536887296; case 207: + case 225: + case 340: + case 208: case 105: return 536870912; - case 201: case 202: + case 203: return 536870912; default: return 536870912; @@ -20522,7 +20940,7 @@ var ts; var _a; if (!node.emitNode) { if (ts.isParseTreeNode(node)) { - if (node.kind === 297) { + if (node.kind === 298) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = (_a = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)))) !== null && _a !== void 0 ? _a : ts.Debug.fail("Could not determine parsed source file."); @@ -20885,13 +21303,27 @@ var ts; context.requestEmitHelper(ts.createBindingHelper); return factory.createCallExpression(getUnscopedHelperName("__exportStar"), undefined, [moduleExpression, exportsExpression]); } - function createClassPrivateFieldGetHelper(receiver, privateField) { + function createClassPrivateFieldGetHelper(receiver, state, kind, f) { context.requestEmitHelper(ts.classPrivateFieldGetHelper); - return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), undefined, [receiver, privateField]); + var args; + if (!f) { + args = [receiver, state, factory.createStringLiteral(kind)]; + } + else { + args = [receiver, state, factory.createStringLiteral(kind), f]; + } + return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), undefined, args); } - function createClassPrivateFieldSetHelper(receiver, privateField, value) { + function createClassPrivateFieldSetHelper(receiver, state, value, kind, f) { context.requestEmitHelper(ts.classPrivateFieldSetHelper); - return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), undefined, [receiver, privateField, value]); + var args; + if (!f) { + args = [receiver, state, value, factory.createStringLiteral(kind)]; + } + else { + args = [receiver, state, value, factory.createStringLiteral(kind), f]; + } + return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), undefined, args); } } ts.createEmitHelperFactory = createEmitHelperFactory; @@ -21069,13 +21501,13 @@ var ts; name: "typescript:classPrivateFieldGet", importName: "__classPrivateFieldGet", scoped: false, - text: "\n var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, privateMap) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to get private field on non-instance\");\n }\n return privateMap.get(receiver);\n };" + text: "\n var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n };" }; ts.classPrivateFieldSetHelper = { name: "typescript:classPrivateFieldSet", importName: "__classPrivateFieldSet", scoped: false, - text: "\n var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, privateMap, value) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to set private field on non-instance\");\n }\n privateMap.set(receiver, value);\n return value;\n };" + text: "\n var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n };" }; var allUnscopedEmitHelpers; function getAllUnscopedEmitHelpers() { @@ -21162,22 +21594,78 @@ var ts; return node.kind === 17; } ts.isTemplateTail = isTemplateTail; + function isDotDotDotToken(node) { + return node.kind === 25; + } + ts.isDotDotDotToken = isDotDotDotToken; + function isCommaToken(node) { + return node.kind === 27; + } + ts.isCommaToken = isCommaToken; + function isPlusToken(node) { + return node.kind === 39; + } + ts.isPlusToken = isPlusToken; + function isMinusToken(node) { + return node.kind === 40; + } + ts.isMinusToken = isMinusToken; + function isAsteriskToken(node) { + return node.kind === 41; + } + ts.isAsteriskToken = isAsteriskToken; + function isExclamationToken(node) { + return node.kind === 53; + } + ts.isExclamationToken = isExclamationToken; + function isQuestionToken(node) { + return node.kind === 57; + } + ts.isQuestionToken = isQuestionToken; + function isColonToken(node) { + return node.kind === 58; + } + ts.isColonToken = isColonToken; + function isQuestionDotToken(node) { + return node.kind === 28; + } + ts.isQuestionDotToken = isQuestionDotToken; + function isEqualsGreaterThanToken(node) { + return node.kind === 38; + } + ts.isEqualsGreaterThanToken = isEqualsGreaterThanToken; function isIdentifier(node) { return node.kind === 78; } ts.isIdentifier = isIdentifier; - function isQualifiedName(node) { - return node.kind === 157; - } - ts.isQualifiedName = isQualifiedName; - function isComputedPropertyName(node) { - return node.kind === 158; - } - ts.isComputedPropertyName = isComputedPropertyName; function isPrivateIdentifier(node) { return node.kind === 79; } ts.isPrivateIdentifier = isPrivateIdentifier; + function isExportModifier(node) { + return node.kind === 92; + } + ts.isExportModifier = isExportModifier; + function isAsyncModifier(node) { + return node.kind === 129; + } + ts.isAsyncModifier = isAsyncModifier; + function isAssertsKeyword(node) { + return node.kind === 127; + } + ts.isAssertsKeyword = isAssertsKeyword; + function isAwaitKeyword(node) { + return node.kind === 130; + } + ts.isAwaitKeyword = isAwaitKeyword; + function isReadonlyKeyword(node) { + return node.kind === 142; + } + ts.isReadonlyKeyword = isReadonlyKeyword; + function isStaticModifier(node) { + return node.kind === 123; + } + ts.isStaticModifier = isStaticModifier; function isSuperKeyword(node) { return node.kind === 105; } @@ -21186,724 +21674,728 @@ var ts; return node.kind === 99; } ts.isImportKeyword = isImportKeyword; - function isCommaToken(node) { - return node.kind === 27; - } - ts.isCommaToken = isCommaToken; - function isQuestionToken(node) { - return node.kind === 57; + function isQualifiedName(node) { + return node.kind === 158; } - ts.isQuestionToken = isQuestionToken; - function isExclamationToken(node) { - return node.kind === 53; + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 159; } - ts.isExclamationToken = isExclamationToken; + ts.isComputedPropertyName = isComputedPropertyName; function isTypeParameterDeclaration(node) { - return node.kind === 159; + return node.kind === 160; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; function isParameter(node) { - return node.kind === 160; + return node.kind === 161; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 161; + return node.kind === 162; } ts.isDecorator = isDecorator; function isPropertySignature(node) { - return node.kind === 162; + return node.kind === 163; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 163; + return node.kind === 164; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 164; + return node.kind === 165; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 165; + return node.kind === 166; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 166; + return node.kind === 167; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 167; + return node.kind === 168; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 168; + return node.kind === 169; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 169; + return node.kind === 170; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 170; + return node.kind === 171; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 171; + return node.kind === 172; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; function isTypePredicateNode(node) { - return node.kind === 172; + return node.kind === 173; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 173; + return node.kind === 174; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 174; + return node.kind === 175; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 175; + return node.kind === 176; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 176; + return node.kind === 177; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 177; + return node.kind === 178; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 178; + return node.kind === 179; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 179; + return node.kind === 180; } ts.isTupleTypeNode = isTupleTypeNode; function isNamedTupleMember(node) { - return node.kind === 192; + return node.kind === 193; } ts.isNamedTupleMember = isNamedTupleMember; function isOptionalTypeNode(node) { - return node.kind === 180; + return node.kind === 181; } ts.isOptionalTypeNode = isOptionalTypeNode; function isRestTypeNode(node) { - return node.kind === 181; + return node.kind === 182; } ts.isRestTypeNode = isRestTypeNode; function isUnionTypeNode(node) { - return node.kind === 182; + return node.kind === 183; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 183; + return node.kind === 184; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isConditionalTypeNode(node) { - return node.kind === 184; + return node.kind === 185; } ts.isConditionalTypeNode = isConditionalTypeNode; function isInferTypeNode(node) { - return node.kind === 185; + return node.kind === 186; } ts.isInferTypeNode = isInferTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 186; + return node.kind === 187; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 187; + return node.kind === 188; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 188; + return node.kind === 189; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 189; + return node.kind === 190; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 190; + return node.kind === 191; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 191; + return node.kind === 192; } ts.isLiteralTypeNode = isLiteralTypeNode; function isImportTypeNode(node) { - return node.kind === 195; + return node.kind === 196; } ts.isImportTypeNode = isImportTypeNode; function isTemplateLiteralTypeSpan(node) { - return node.kind === 194; + return node.kind === 195; } ts.isTemplateLiteralTypeSpan = isTemplateLiteralTypeSpan; function isTemplateLiteralTypeNode(node) { - return node.kind === 193; + return node.kind === 194; } ts.isTemplateLiteralTypeNode = isTemplateLiteralTypeNode; function isObjectBindingPattern(node) { - return node.kind === 196; + return node.kind === 197; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 197; + return node.kind === 198; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 198; + return node.kind === 199; } ts.isBindingElement = isBindingElement; function isArrayLiteralExpression(node) { - return node.kind === 199; + return node.kind === 200; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 200; + return node.kind === 201; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 201; + return node.kind === 202; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 202; + return node.kind === 203; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 203; + return node.kind === 204; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 204; + return node.kind === 205; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 205; + return node.kind === 206; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertionExpression(node) { - return node.kind === 206; + return node.kind === 207; } ts.isTypeAssertionExpression = isTypeAssertionExpression; function isParenthesizedExpression(node) { - return node.kind === 207; + return node.kind === 208; } ts.isParenthesizedExpression = isParenthesizedExpression; function isFunctionExpression(node) { - return node.kind === 208; + return node.kind === 209; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 209; + return node.kind === 210; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 210; + return node.kind === 211; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 211; + return node.kind === 212; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 212; + return node.kind === 213; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 213; + return node.kind === 214; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 214; + return node.kind === 215; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 215; + return node.kind === 216; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 216; + return node.kind === 217; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 217; + return node.kind === 218; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 218; + return node.kind === 219; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 219; + return node.kind === 220; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 220; + return node.kind === 221; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 221; + return node.kind === 222; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 222; + return node.kind === 223; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 223; + return node.kind === 224; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 224; + return node.kind === 225; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 225; + return node.kind === 226; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 226; + return node.kind === 227; } ts.isMetaProperty = isMetaProperty; function isSyntheticExpression(node) { - return node.kind === 227; + return node.kind === 228; } ts.isSyntheticExpression = isSyntheticExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 336; + return node.kind === 340; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isCommaListExpression(node) { - return node.kind === 337; + return node.kind === 341; } ts.isCommaListExpression = isCommaListExpression; function isTemplateSpan(node) { - return node.kind === 228; + return node.kind === 229; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 229; + return node.kind === 230; } ts.isSemicolonClassElement = isSemicolonClassElement; function isBlock(node) { - return node.kind === 230; + return node.kind === 231; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 232; + return node.kind === 233; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 231; + return node.kind === 232; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 233; + return node.kind === 234; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 234; + return node.kind === 235; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 235; + return node.kind === 236; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 236; + return node.kind === 237; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 237; + return node.kind === 238; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 238; + return node.kind === 239; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 239; + return node.kind === 240; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 240; + return node.kind === 241; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 241; + return node.kind === 242; } ts.isBreakStatement = isBreakStatement; function isReturnStatement(node) { - return node.kind === 242; + return node.kind === 243; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 243; + return node.kind === 244; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 244; + return node.kind === 245; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 245; + return node.kind === 246; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 246; + return node.kind === 247; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 247; + return node.kind === 248; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 248; + return node.kind === 249; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 249; + return node.kind === 250; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 250; + return node.kind === 251; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 251; + return node.kind === 252; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 252; + return node.kind === 253; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 253; + return node.kind === 254; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 254; + return node.kind === 255; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 255; + return node.kind === 256; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 256; + return node.kind === 257; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 257; + return node.kind === 258; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 258; + return node.kind === 259; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 259; + return node.kind === 260; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 260; + return node.kind === 261; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 261; + return node.kind === 262; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 262; + return node.kind === 263; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 263; + return node.kind === 264; } ts.isNamespaceImport = isNamespaceImport; function isNamespaceExport(node) { - return node.kind === 269; + return node.kind === 270; } ts.isNamespaceExport = isNamespaceExport; function isNamedImports(node) { - return node.kind === 264; + return node.kind === 265; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 265; + return node.kind === 266; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 266; + return node.kind === 267; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 267; + return node.kind === 268; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 268; + return node.kind === 269; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 270; + return node.kind === 271; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 271; + return node.kind === 272; } ts.isMissingDeclaration = isMissingDeclaration; function isNotEmittedStatement(node) { - return node.kind === 335; + return node.kind === 339; } ts.isNotEmittedStatement = isNotEmittedStatement; function isSyntheticReference(node) { - return node.kind === 340; + return node.kind === 344; } ts.isSyntheticReference = isSyntheticReference; function isMergeDeclarationMarker(node) { - return node.kind === 338; + return node.kind === 342; } ts.isMergeDeclarationMarker = isMergeDeclarationMarker; function isEndOfDeclarationMarker(node) { - return node.kind === 339; + return node.kind === 343; } ts.isEndOfDeclarationMarker = isEndOfDeclarationMarker; function isExternalModuleReference(node) { - return node.kind === 272; + return node.kind === 273; } ts.isExternalModuleReference = isExternalModuleReference; function isJsxElement(node) { - return node.kind === 273; + return node.kind === 274; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 274; + return node.kind === 275; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 275; + return node.kind === 276; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 276; + return node.kind === 277; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxFragment(node) { - return node.kind === 277; + return node.kind === 278; } ts.isJsxFragment = isJsxFragment; function isJsxOpeningFragment(node) { - return node.kind === 278; + return node.kind === 279; } ts.isJsxOpeningFragment = isJsxOpeningFragment; function isJsxClosingFragment(node) { - return node.kind === 279; + return node.kind === 280; } ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 280; + return node.kind === 281; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 281; + return node.kind === 282; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 282; + return node.kind === 283; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 283; + return node.kind === 284; } ts.isJsxExpression = isJsxExpression; function isCaseClause(node) { - return node.kind === 284; + return node.kind === 285; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 285; + return node.kind === 286; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 286; + return node.kind === 287; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 287; + return node.kind === 288; } ts.isCatchClause = isCatchClause; function isPropertyAssignment(node) { - return node.kind === 288; + return node.kind === 289; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 289; + return node.kind === 290; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 290; + return node.kind === 291; } ts.isSpreadAssignment = isSpreadAssignment; function isEnumMember(node) { - return node.kind === 291; + return node.kind === 292; } ts.isEnumMember = isEnumMember; function isUnparsedPrepend(node) { - return node.kind === 293; + return node.kind === 294; } ts.isUnparsedPrepend = isUnparsedPrepend; function isSourceFile(node) { - return node.kind === 297; + return node.kind === 298; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 298; + return node.kind === 299; } ts.isBundle = isBundle; function isUnparsedSource(node) { - return node.kind === 299; + return node.kind === 300; } ts.isUnparsedSource = isUnparsedSource; function isJSDocTypeExpression(node) { - return node.kind === 301; + return node.kind === 302; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocNameReference(node) { - return node.kind === 302; + return node.kind === 303; } ts.isJSDocNameReference = isJSDocNameReference; + function isJSDocLink(node) { + return node.kind === 316; + } + ts.isJSDocLink = isJSDocLink; function isJSDocAllType(node) { - return node.kind === 303; + return node.kind === 304; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 304; + return node.kind === 305; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 305; + return node.kind === 306; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 306; + return node.kind === 307; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 307; + return node.kind === 308; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 308; + return node.kind === 309; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 309; + return node.kind === 310; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDocNamepathType(node) { - return node.kind === 310; + return node.kind === 311; } ts.isJSDocNamepathType = isJSDocNamepathType; function isJSDoc(node) { - return node.kind === 311; + return node.kind === 312; } ts.isJSDoc = isJSDoc; function isJSDocTypeLiteral(node) { - return node.kind === 312; + return node.kind === 314; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; function isJSDocSignature(node) { - return node.kind === 313; + return node.kind === 315; } ts.isJSDocSignature = isJSDocSignature; function isJSDocAugmentsTag(node) { - return node.kind === 315; + return node.kind === 318; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocAuthorTag(node) { - return node.kind === 317; + return node.kind === 320; } ts.isJSDocAuthorTag = isJSDocAuthorTag; function isJSDocClassTag(node) { - return node.kind === 319; + return node.kind === 322; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocCallbackTag(node) { - return node.kind === 324; + return node.kind === 328; } ts.isJSDocCallbackTag = isJSDocCallbackTag; function isJSDocPublicTag(node) { - return node.kind === 320; + return node.kind === 323; } ts.isJSDocPublicTag = isJSDocPublicTag; function isJSDocPrivateTag(node) { - return node.kind === 321; + return node.kind === 324; } ts.isJSDocPrivateTag = isJSDocPrivateTag; function isJSDocProtectedTag(node) { - return node.kind === 322; + return node.kind === 325; } ts.isJSDocProtectedTag = isJSDocProtectedTag; function isJSDocReadonlyTag(node) { - return node.kind === 323; + return node.kind === 326; } ts.isJSDocReadonlyTag = isJSDocReadonlyTag; + function isJSDocOverrideTag(node) { + return node.kind === 327; + } + ts.isJSDocOverrideTag = isJSDocOverrideTag; function isJSDocDeprecatedTag(node) { - return node.kind === 318; + return node.kind === 321; } ts.isJSDocDeprecatedTag = isJSDocDeprecatedTag; function isJSDocSeeTag(node) { - return node.kind === 332; + return node.kind === 336; } ts.isJSDocSeeTag = isJSDocSeeTag; function isJSDocEnumTag(node) { - return node.kind === 325; + return node.kind === 329; } ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocParameterTag(node) { - return node.kind === 326; + return node.kind === 330; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 327; + return node.kind === 331; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocThisTag(node) { - return node.kind === 328; + return node.kind === 332; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocTypeTag(node) { - return node.kind === 329; + return node.kind === 333; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 330; + return node.kind === 334; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 331; + return node.kind === 335; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocUnknownTag(node) { - return node.kind === 314; + return node.kind === 317; } ts.isJSDocUnknownTag = isJSDocUnknownTag; function isJSDocPropertyTag(node) { - return node.kind === 333; + return node.kind === 337; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocImplementsTag(node) { - return node.kind === 316; + return node.kind === 319; } ts.isJSDocImplementsTag = isJSDocImplementsTag; function isSyntaxList(n) { - return n.kind === 334; + return n.kind === 338; } ts.isSyntaxList = isSyntaxList; })(ts || (ts = {})); @@ -21918,7 +22410,7 @@ var ts; return ts.setTextRange(factory.createElementAccessExpression(target, memberName.expression), location); } else { - var expression = ts.setTextRange(ts.isIdentifierOrPrivateIdentifier(memberName) + var expression = ts.setTextRange(ts.isMemberName(memberName) ? factory.createPropertyAccessExpression(target, memberName) : factory.createElementAccessExpression(target, memberName), memberName); ts.getOrCreateEmitNode(expression).flags |= 64; @@ -22064,14 +22556,14 @@ var ts; ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals."); } switch (property.kind) { - case 167: case 168: + case 169: return createExpressionForAccessorDeclaration(factory, node.properties, property, receiver, !!node.multiLine); - case 288: - return createExpressionForPropertyAssignment(factory, property, receiver); case 289: + return createExpressionForPropertyAssignment(factory, property, receiver); + case 290: return createExpressionForShorthandPropertyAssignment(factory, property, receiver); - case 165: + case 166: return createExpressionForMethodDeclaration(factory, property, receiver); } } @@ -22114,21 +22606,21 @@ var ts; } ts.startsWithUseStrict = startsWithUseStrict; function isCommaSequence(node) { - return node.kind === 216 && node.operatorToken.kind === 27 || - node.kind === 337; + return node.kind === 217 && node.operatorToken.kind === 27 || + node.kind === 341; } ts.isCommaSequence = isCommaSequence; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 15; } switch (node.kind) { - case 207: + case 208: return (kinds & 1) !== 0; - case 206: - case 224: - return (kinds & 2) !== 0; + case 207: case 225: + return (kinds & 2) !== 0; + case 226: return (kinds & 4) !== 0; - case 336: + case 340: return (kinds & 8) !== 0; } return false; @@ -22240,10 +22732,10 @@ var ts; var name = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name) ? name : factory.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 261 && node.importClause) { + if (node.kind === 262 && node.importClause) { return factory.getGeneratedNameForNode(node); } - if (node.kind === 267 && node.moduleSpecifier) { + if (node.kind === 268 && node.moduleSpecifier) { return factory.getGeneratedNameForNode(node); } return undefined; @@ -22306,11 +22798,11 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 288: - return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); case 289: - return bindingElement.name; + return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); case 290: + return bindingElement.name; + case 291: return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } return undefined; @@ -22326,11 +22818,11 @@ var ts; ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement; function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 160: - case 198: + case 161: + case 199: return bindingElement.dotDotDotToken; - case 220: - case 290: + case 221: + case 291: return bindingElement; } return undefined; @@ -22344,7 +22836,7 @@ var ts; ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 198: + case 199: if (bindingElement.propertyName) { var propertyName = bindingElement.propertyName; if (ts.isPrivateIdentifier(propertyName)) { @@ -22355,7 +22847,7 @@ var ts; : propertyName; } break; - case 288: + case 289: if (bindingElement.name) { var propertyName = bindingElement.name; if (ts.isPrivateIdentifier(propertyName)) { @@ -22366,7 +22858,7 @@ var ts; : propertyName; } break; - case 290: + case 291: if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) { return ts.Debug.failBadSyntaxKind(bindingElement.name); } @@ -22385,11 +22877,11 @@ var ts; } function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 196: case 197: - case 199: - return name.elements; + case 198: case 200: + return name.elements; + case 201: return name.properties; } } @@ -22408,43 +22900,253 @@ var ts; ts.getJSDocTypeAliasName = getJSDocTypeAliasName; function canHaveModifiers(node) { var kind = node.kind; - return kind === 160 - || kind === 162 + return kind === 161 || kind === 163 || kind === 164 || kind === 165 || kind === 166 || kind === 167 || kind === 168 - || kind === 171 - || kind === 208 + || kind === 169 + || kind === 172 || kind === 209 - || kind === 221 - || kind === 232 - || kind === 251 + || kind === 210 + || kind === 222 + || kind === 233 || kind === 252 || kind === 253 || kind === 254 || kind === 255 || kind === 256 - || kind === 260 + || kind === 257 || kind === 261 - || kind === 266 - || kind === 267; + || kind === 262 + || kind === 267 + || kind === 268; } ts.canHaveModifiers = canHaveModifiers; - function isExportModifier(node) { - return node.kind === 92; - } - ts.isExportModifier = isExportModifier; - function isAsyncModifier(node) { - return node.kind === 129; - } - ts.isAsyncModifier = isAsyncModifier; - function isStaticModifier(node) { - return node.kind === 123; + ts.isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); + ts.isQuestionOrExclamationToken = ts.or(ts.isQuestionToken, ts.isExclamationToken); + ts.isIdentifierOrThisTypeNode = ts.or(ts.isIdentifier, ts.isThisTypeNode); + ts.isReadonlyKeywordOrPlusOrMinusToken = ts.or(ts.isReadonlyKeyword, ts.isPlusToken, ts.isMinusToken); + ts.isQuestionOrPlusOrMinusToken = ts.or(ts.isQuestionToken, ts.isPlusToken, ts.isMinusToken); + ts.isModuleName = ts.or(ts.isIdentifier, ts.isStringLiteral); + function isLiteralTypeLikeExpression(node) { + var kind = node.kind; + return kind === 103 + || kind === 109 + || kind === 94 + || ts.isLiteralExpression(node) + || ts.isPrefixUnaryExpression(node); + } + ts.isLiteralTypeLikeExpression = isLiteralTypeLikeExpression; + function isExponentiationOperator(kind) { + return kind === 42; + } + function isMultiplicativeOperator(kind) { + return kind === 41 + || kind === 43 + || kind === 44; + } + function isMultiplicativeOperatorOrHigher(kind) { + return isExponentiationOperator(kind) + || isMultiplicativeOperator(kind); + } + function isAdditiveOperator(kind) { + return kind === 39 + || kind === 40; + } + function isAdditiveOperatorOrHigher(kind) { + return isAdditiveOperator(kind) + || isMultiplicativeOperatorOrHigher(kind); + } + function isShiftOperator(kind) { + return kind === 47 + || kind === 48 + || kind === 49; + } + function isShiftOperatorOrHigher(kind) { + return isShiftOperator(kind) + || isAdditiveOperatorOrHigher(kind); + } + function isRelationalOperator(kind) { + return kind === 29 + || kind === 32 + || kind === 31 + || kind === 33 + || kind === 101 + || kind === 100; + } + function isRelationalOperatorOrHigher(kind) { + return isRelationalOperator(kind) + || isShiftOperatorOrHigher(kind); + } + function isEqualityOperator(kind) { + return kind === 34 + || kind === 36 + || kind === 35 + || kind === 37; + } + function isEqualityOperatorOrHigher(kind) { + return isEqualityOperator(kind) + || isRelationalOperatorOrHigher(kind); + } + function isBitwiseOperator(kind) { + return kind === 50 + || kind === 51 + || kind === 52; + } + function isBitwiseOperatorOrHigher(kind) { + return isBitwiseOperator(kind) + || isEqualityOperatorOrHigher(kind); + } + function isLogicalOperator(kind) { + return kind === 55 + || kind === 56; + } + function isLogicalOperatorOrHigher(kind) { + return isLogicalOperator(kind) + || isBitwiseOperatorOrHigher(kind); + } + function isAssignmentOperatorOrHigher(kind) { + return kind === 60 + || isLogicalOperatorOrHigher(kind) + || ts.isAssignmentOperator(kind); + } + function isBinaryOperator(kind) { + return isAssignmentOperatorOrHigher(kind) + || kind === 27; + } + function isBinaryOperatorToken(node) { + return isBinaryOperator(node.kind); + } + ts.isBinaryOperatorToken = isBinaryOperatorToken; + var BinaryExpressionState; + (function (BinaryExpressionState) { + function enter(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, outerState) { + var prevUserState = stackIndex > 0 ? userStateStack[stackIndex - 1] : undefined; + ts.Debug.assertEqual(stateStack[stackIndex], enter); + userStateStack[stackIndex] = machine.onEnter(nodeStack[stackIndex], prevUserState, outerState); + stateStack[stackIndex] = nextState(machine, enter); + return stackIndex; + } + BinaryExpressionState.enter = enter; + function left(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], left); + ts.Debug.assertIsDefined(machine.onLeft); + stateStack[stackIndex] = nextState(machine, left); + var nextNode = machine.onLeft(nodeStack[stackIndex].left, userStateStack[stackIndex], nodeStack[stackIndex]); + if (nextNode) { + checkCircularity(stackIndex, nodeStack, nextNode); + return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode); + } + return stackIndex; + } + BinaryExpressionState.left = left; + function operator(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], operator); + ts.Debug.assertIsDefined(machine.onOperator); + stateStack[stackIndex] = nextState(machine, operator); + machine.onOperator(nodeStack[stackIndex].operatorToken, userStateStack[stackIndex], nodeStack[stackIndex]); + return stackIndex; + } + BinaryExpressionState.operator = operator; + function right(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], right); + ts.Debug.assertIsDefined(machine.onRight); + stateStack[stackIndex] = nextState(machine, right); + var nextNode = machine.onRight(nodeStack[stackIndex].right, userStateStack[stackIndex], nodeStack[stackIndex]); + if (nextNode) { + checkCircularity(stackIndex, nodeStack, nextNode); + return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode); + } + return stackIndex; + } + BinaryExpressionState.right = right; + function exit(machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], exit); + stateStack[stackIndex] = nextState(machine, exit); + var result = machine.onExit(nodeStack[stackIndex], userStateStack[stackIndex]); + if (stackIndex > 0) { + stackIndex--; + if (machine.foldState) { + var side = stateStack[stackIndex] === exit ? "right" : "left"; + userStateStack[stackIndex] = machine.foldState(userStateStack[stackIndex], result, side); + } + } + else { + resultHolder.value = result; + } + return stackIndex; + } + BinaryExpressionState.exit = exit; + function done(_machine, stackIndex, stateStack, _nodeStack, _userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], done); + return stackIndex; + } + BinaryExpressionState.done = done; + function nextState(machine, currentState) { + switch (currentState) { + case enter: + if (machine.onLeft) + return left; + case left: + if (machine.onOperator) + return operator; + case operator: + if (machine.onRight) + return right; + case right: return exit; + case exit: return done; + case done: return done; + default: ts.Debug.fail("Invalid state"); + } + } + BinaryExpressionState.nextState = nextState; + function pushStack(stackIndex, stateStack, nodeStack, userStateStack, node) { + stackIndex++; + stateStack[stackIndex] = enter; + nodeStack[stackIndex] = node; + userStateStack[stackIndex] = undefined; + return stackIndex; + } + function checkCircularity(stackIndex, nodeStack, node) { + if (ts.Debug.shouldAssert(2)) { + while (stackIndex >= 0) { + ts.Debug.assert(nodeStack[stackIndex] !== node, "Circular traversal detected."); + stackIndex--; + } + } + } + })(BinaryExpressionState || (BinaryExpressionState = {})); + var BinaryExpressionStateMachine = (function () { + function BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState) { + this.onEnter = onEnter; + this.onLeft = onLeft; + this.onOperator = onOperator; + this.onRight = onRight; + this.onExit = onExit; + this.foldState = foldState; + } + return BinaryExpressionStateMachine; + }()); + function createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState) { + var machine = new BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState); + return trampoline; + function trampoline(node, outerState) { + var resultHolder = { value: undefined }; + var stateStack = [BinaryExpressionState.enter]; + var nodeStack = [node]; + var userStateStack = [undefined]; + var stackIndex = 0; + while (stateStack[stackIndex] !== BinaryExpressionState.done) { + stackIndex = stateStack[stackIndex](machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, outerState); + } + ts.Debug.assertEqual(stackIndex, 0); + return resultHolder.value; + } } - ts.isStaticModifier = isStaticModifier; + ts.createBinaryExpressionTrampoline = createBinaryExpressionTrampoline; })(ts || (ts = {})); var ts; (function (ts) { @@ -22492,19 +23194,19 @@ var ts; } ts.isJSDocLikeText = isJSDocLikeText; function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 156) { + if (!node || node.kind <= 157) { return; } switch (node.kind) { - case 157: + case 158: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 159: + case 160: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 289: + case 290: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -22512,9 +23214,9 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 290: + case 291: return visitNode(cbNode, node.expression); - case 160: + case 161: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || @@ -22522,7 +23224,7 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 163: + case 164: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -22530,51 +23232,51 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 162: + case 163: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 288: + case 289: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.initializer); - case 249: + case 250: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 198: + case 199: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 174: case 175: - case 169: + case 176: case 170: case 171: + case 172: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 165: - case 164: case 166: + case 165: case 167: case 168: - case 208: - case 251: + case 169: case 209: + case 252: + case 210: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -22586,435 +23288,446 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 173: + case 174: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 172: + case 173: return visitNode(cbNode, node.assertsModifier) || visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 176: - return visitNode(cbNode, node.exprName); case 177: - return visitNodes(cbNode, cbNodes, node.members); + return visitNode(cbNode, node.exprName); case 178: - return visitNode(cbNode, node.elementType); + return visitNodes(cbNode, cbNodes, node.members); case 179: + return visitNode(cbNode, node.elementType); + case 180: return visitNodes(cbNode, cbNodes, node.elements); - case 182: case 183: - return visitNodes(cbNode, cbNodes, node.types); case 184: + return visitNodes(cbNode, cbNodes, node.types); + case 185: return visitNode(cbNode, node.checkType) || visitNode(cbNode, node.extendsType) || visitNode(cbNode, node.trueType) || visitNode(cbNode, node.falseType); - case 185: + case 186: return visitNode(cbNode, node.typeParameter); - case 195: + case 196: return visitNode(cbNode, node.argument) || visitNode(cbNode, node.qualifier) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 186: - case 188: - return visitNode(cbNode, node.type); + case 187: case 189: + return visitNode(cbNode, node.type); + case 190: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 190: + case 191: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.nameType) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 191: - return visitNode(cbNode, node.literal); case 192: + return visitNode(cbNode, node.literal); + case 193: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 196: case 197: - return visitNodes(cbNode, cbNodes, node.elements); - case 199: + case 198: return visitNodes(cbNode, cbNodes, node.elements); case 200: - return visitNodes(cbNode, cbNodes, node.properties); + return visitNodes(cbNode, cbNodes, node.elements); case 201: + return visitNodes(cbNode, cbNodes, node.properties); + case 202: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || visitNode(cbNode, node.name); - case 202: + case 203: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || visitNode(cbNode, node.argumentExpression); - case 203: case 204: + case 205: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 205: + case 206: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.template); - case 206: + case 207: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 207: - return visitNode(cbNode, node.expression); - case 210: + case 208: return visitNode(cbNode, node.expression); case 211: return visitNode(cbNode, node.expression); case 212: return visitNode(cbNode, node.expression); - case 214: - return visitNode(cbNode, node.operand); - case 219: - return visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.expression); case 213: return visitNode(cbNode, node.expression); case 215: return visitNode(cbNode, node.operand); + case 220: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 214: + return visitNode(cbNode, node.expression); case 216: + return visitNode(cbNode, node.operand); + case 217: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 224: + case 225: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 225: - return visitNode(cbNode, node.expression); case 226: + return visitNode(cbNode, node.expression); + case 227: return visitNode(cbNode, node.name); - case 217: + case 218: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 220: + case 221: return visitNode(cbNode, node.expression); - case 230: - case 257: + case 231: + case 258: return visitNodes(cbNode, cbNodes, node.statements); - case 297: + case 298: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 232: + case 233: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 250: + case 251: return visitNodes(cbNode, cbNodes, node.declarations); - case 233: - return visitNode(cbNode, node.expression); case 234: + return visitNode(cbNode, node.expression); + case 235: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 235: + case 236: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 236: + case 237: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 237: + case 238: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 238: + case 239: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 239: + case 240: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 240: case 241: - return visitNode(cbNode, node.label); case 242: - return visitNode(cbNode, node.expression); + return visitNode(cbNode, node.label); case 243: + return visitNode(cbNode, node.expression); + case 244: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 244: + case 245: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 258: + case 259: return visitNodes(cbNode, cbNodes, node.clauses); - case 284: + case 285: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 285: + case 286: return visitNodes(cbNode, cbNodes, node.statements); - case 245: + case 246: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 246: - return visitNode(cbNode, node.expression); case 247: + return visitNode(cbNode, node.expression); + case 248: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 287: + case 288: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 161: + case 162: return visitNode(cbNode, node.expression); - case 252: - case 221: + case 253: + case 222: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 253: + case 254: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 254: + case 255: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 255: + case 256: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 291: + case 292: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 256: + case 257: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 260: + case 261: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 261: + case 262: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 262: + case 263: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 259: + case 260: return visitNode(cbNode, node.name); - case 263: + case 264: return visitNode(cbNode, node.name); - case 269: + case 270: return visitNode(cbNode, node.name); - case 264: - case 268: + case 265: + case 269: return visitNodes(cbNode, cbNodes, node.elements); - case 267: + case 268: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 265: - case 270: + case 266: + case 271: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 266: + case 267: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 218: + case 219: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 228: + case 229: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 193: - return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); case 194: + return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + case 195: return visitNode(cbNode, node.type) || visitNode(cbNode, node.literal); - case 158: + case 159: return visitNode(cbNode, node.expression); - case 286: + case 287: return visitNodes(cbNode, cbNodes, node.types); - case 223: + case 224: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 272: + case 273: return visitNode(cbNode, node.expression); - case 271: + case 272: return visitNodes(cbNode, cbNodes, node.decorators); - case 337: + case 341: return visitNodes(cbNode, cbNodes, node.elements); - case 273: + case 274: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 277: + case 278: return visitNode(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingFragment); - case 274: case 275: + case 276: return visitNode(cbNode, node.tagName) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); - case 281: + case 282: return visitNodes(cbNode, cbNodes, node.properties); - case 280: + case 281: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 282: - return visitNode(cbNode, node.expression); case 283: + return visitNode(cbNode, node.expression); + case 284: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 276: + case 277: return visitNode(cbNode, node.tagName); - case 180: case 181: - case 301: - case 306: - case 305: + case 182: + case 302: case 307: - case 309: - return visitNode(cbNode, node.type); + case 306: case 308: + case 310: + return visitNode(cbNode, node.type); + case 309: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 311: - return visitNodes(cbNode, cbNodes, node.tags); - case 332: + case 312: + return (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) + || visitNodes(cbNode, cbNodes, node.tags); + case 336: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.name); - case 302: + visitNode(cbNode, node.name) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 303: return visitNode(cbNode, node.name); - case 326: - case 333: + case 330: + case 337: return visitNode(cbNode, node.tagName) || (node.isNameFirst ? visitNode(cbNode, node.name) || - visitNode(cbNode, node.typeExpression) + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) : visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.name)); - case 317: - return visitNode(cbNode, node.tagName); - case 316: + visitNode(cbNode, node.name)) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 320: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.class); - case 315: + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 319: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.class); - case 330: + visitNode(cbNode, node.class) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 318: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 334: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.constraint) || - visitNodes(cbNode, cbNodes, node.typeParameters); - case 331: + visitNodes(cbNode, cbNodes, node.typeParameters) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 335: return visitNode(cbNode, node.tagName) || (node.typeExpression && - node.typeExpression.kind === 301 + node.typeExpression.kind === 302 ? visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName) + visitNode(cbNode, node.fullName) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) : visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression)); - case 324: + visitNode(cbNode, node.typeExpression)) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 328: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression); - case 327: + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 331: + case 333: + case 332: case 329: - case 328: - case 325: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.typeExpression); - case 313: + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 315: return ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 312: - return ts.forEach(node.jsDocPropertyTags, cbNode); + case 316: + return visitNode(cbNode, node.name); case 314: - case 319: - case 320: - case 321: + return ts.forEach(node.jsDocPropertyTags, cbNode); + case 317: case 322: case 323: - return visitNode(cbNode, node.tagName); - case 336: + case 324: + case 325: + case 326: + case 321: + return visitNode(cbNode, node.tagName) + || (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 340: return visitNode(cbNode, node.expression); } } ts.forEachChild = forEachChild; function forEachChildRecursively(rootNode, cbNode, cbNodes) { - var stack = [rootNode]; - while (stack.length) { - var parent = stack.pop(); - var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent)); - if (res) { - return res; - } - } - return; - function gatherPossibleChildren(node) { - var children = []; - forEachChild(node, addWorkItem, addWorkItem); - return children; - function addWorkItem(n) { - children.unshift(n); - } - } - function visitAllPossibleChildren(parent, children) { - for (var _i = 0, children_5 = children; _i < children_5.length; _i++) { - var child = children_5[_i]; - if (ts.isArray(child)) { - if (cbNodes) { - var res = cbNodes(child, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - } - for (var i = child.length - 1; i >= 0; i--) { - var realChild = child[i]; - var res = cbNode(realChild, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - stack.push(realChild); - } - } - else { - stack.push(child); - var res = cbNode(child, parent); + var queue = gatherPossibleChildren(rootNode); + var parents = []; + while (parents.length < queue.length) { + parents.push(rootNode); + } + while (queue.length !== 0) { + var current = queue.pop(); + var parent = parents.pop(); + if (ts.isArray(current)) { + if (cbNodes) { + var res = cbNodes(current, parent); if (res) { if (res === "skip") continue; return res; } } + for (var i = current.length - 1; i >= 0; --i) { + queue.push(current[i]); + parents.push(parent); + } + } + else { + var res = cbNode(current, parent); + if (res) { + if (res === "skip") + continue; + return res; + } + if (current.kind >= 158) { + for (var _i = 0, _a = gatherPossibleChildren(current); _i < _a.length; _i++) { + var child = _a[_i]; + queue.push(child); + parents.push(current); + } + } } } } ts.forEachChildRecursively = forEachChildRecursively; + function gatherPossibleChildren(node) { + var children = []; + forEachChild(node, addWorkItem, addWorkItem); + return children; + function addWorkItem(n) { + children.unshift(n); + } + } function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - ts.tracing.push("parse", "createSourceFile", { path: fileName }, true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse", "createSourceFile", { path: fileName }, true); ts.performance.mark("beforeParse"); var result; ts.perfLogger.logStartParseSourceFile(fileName); @@ -23027,7 +23740,7 @@ var ts; ts.perfLogger.logStopParseSourceFile(); ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } ts.createSourceFile = createSourceFile; @@ -23103,11 +23816,12 @@ var ts; var topLevel = true; var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + var _a; if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); if (scriptKind === 6) { var result_3 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); - ts.convertToObjectWorker(result_3, result_3.parseDiagnostics, false, undefined, undefined); + ts.convertToObjectWorker(result_3, (_a = result_3.statements[0]) === null || _a === void 0 ? void 0 : _a.expression, result_3.parseDiagnostics, false, undefined, undefined); result_3.referencedFiles = ts.emptyArray; result_3.typeReferenceDirectives = ts.emptyArray; result_3.libReferenceDirectives = ts.emptyArray; @@ -23144,34 +23858,50 @@ var ts; endOfFileToken = parseTokenNode(); } else { - var expression = void 0; - switch (token()) { - case 22: - expression = parseArrayLiteralExpression(); - break; - case 109: - case 94: - case 103: - expression = parseTokenNode(); - break; - case 40: - if (lookAhead(function () { return nextToken() === 8 && nextToken() !== 58; })) { - expression = parsePrefixUnaryExpression(); - } - else { - expression = parseObjectLiteralExpression(); - } - break; - case 8: - case 10: - if (lookAhead(function () { return nextToken() !== 58; })) { - expression = parseLiteralNode(); + var expressions = void 0; + while (token() !== 1) { + var expression_1 = void 0; + switch (token()) { + case 22: + expression_1 = parseArrayLiteralExpression(); + break; + case 109: + case 94: + case 103: + expression_1 = parseTokenNode(); + break; + case 40: + if (lookAhead(function () { return nextToken() === 8 && nextToken() !== 58; })) { + expression_1 = parsePrefixUnaryExpression(); + } + else { + expression_1 = parseObjectLiteralExpression(); + } + break; + case 8: + case 10: + if (lookAhead(function () { return nextToken() !== 58; })) { + expression_1 = parseLiteralNode(); + break; + } + default: + expression_1 = parseObjectLiteralExpression(); break; + } + if (expressions && ts.isArray(expressions)) { + expressions.push(expression_1); + } + else if (expressions) { + expressions = [expressions, expression_1]; + } + else { + expressions = expression_1; + if (token() !== 1) { + parseErrorAtCurrentToken(ts.Diagnostics.Unexpected_token); } - default: - expression = parseObjectLiteralExpression(); - break; + } } + var expression = ts.isArray(expressions) ? finishNode(factory.createArrayLiteralExpression(expressions), pos) : ts.Debug.checkDefined(expressions); var statement = factory.createExpressionStatement(expression); finishNode(statement, pos); statements = createNodeArray([statement], pos); @@ -23352,7 +24082,7 @@ var ts; return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements)); function containsPossibleTopLevelAwait(node) { return !(node.flags & 32768) - && !!(node.transformFlags & 8388608); + && !!(node.transformFlags & 16777216); } function findNextStatementWithAwait(statements, start) { for (var i = start; i < statements.length; i++) { @@ -23386,7 +24116,7 @@ var ts; var sourceFile = factory.createSourceFile(statements, endOfFileToken, flags); ts.setTextRangePosWidth(sourceFile, 0, sourceText.length); setExternalModuleIndicator(sourceFile); - if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 8388608) { + if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 16777216) { sourceFile = reparseTopLevelAwait(sourceFile); } sourceFile.text = sourceText; @@ -23696,7 +24426,7 @@ var ts; ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, "", "", undefined) : kind === 8 ? factory.createNumericLiteral("", undefined) : kind === 10 ? factory.createStringLiteral("", undefined) : - kind === 271 ? factory.createMissingDeclaration() : + kind === 272 ? factory.createMissingDeclaration() : factory.createToken(kind); return finishNode(result, pos); } @@ -23708,8 +24438,8 @@ var ts; return identifier; } function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) { - identifierCount++; if (isIdentifier) { + identifierCount++; var pos = getNodePos(); var originalKeywordKind = token(); var text = internIdentifier(scanner.getTokenValue()); @@ -23720,6 +24450,10 @@ var ts; parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); return createIdentifier(true); } + if (token() === 0 && scanner.tryScan(function () { return scanner.reScanInvalidIdentifier() === 78; })) { + return createIdentifier(true); + } + identifierCount++; var reportAtCurrentPosition = token() === 1; var isReservedWord = scanner.isReservedWord(); var msgArg = scanner.getTokenText(); @@ -24023,8 +24757,7 @@ var ts; var listPos = getNodePos(); while (!isListTerminator(kind)) { if (isListElement(kind, false)) { - var element = parseListElement(kind, parseElement); - list.push(element); + list.push(parseListElement(kind, parseElement)); continue; } if (abortParsingListOrMoveToNextToken(kind)) { @@ -24107,14 +24840,14 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 166: - case 171: case 167: + case 172: case 168: - case 163: - case 229: + case 169: + case 164: + case 230: return true; - case 165: + case 166: var methodDeclaration = node; var nameIsConstructor = methodDeclaration.name.kind === 78 && methodDeclaration.name.originalKeywordKind === 132; @@ -24126,8 +24859,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 284: case 285: + case 286: return true; } } @@ -24136,65 +24869,65 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 251: - case 232: - case 230: - case 234: + case 252: case 233: - case 246: + case 231: + case 235: + case 234: + case 247: + case 243: + case 245: case 242: - case 244: case 241: + case 239: case 240: case 238: - case 239: case 237: - case 236: - case 243: - case 231: - case 247: - case 245: - case 235: + case 244: + case 232: case 248: + case 246: + case 236: + case 249: + case 262: case 261: - case 260: + case 268: case 267: - case 266: - case 256: - case 252: + case 257: case 253: - case 255: case 254: + case 256: + case 255: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 291; + return node.kind === 292; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 170: - case 164: case 171: - case 162: - case 169: + case 165: + case 172: + case 163: + case 170: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 249) { + if (node.kind !== 250) { return false; } var variableDeclarator = node; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 160) { + if (node.kind !== 161) { return false; } var parameter = node; @@ -24422,14 +25155,14 @@ var ts; } function typeHasArrowFunctionBlockingParseError(node) { switch (node.kind) { - case 173: - return ts.nodeIsMissing(node.typeName); case 174: - case 175: { + return ts.nodeIsMissing(node.typeName); + case 175: + case 176: { var _a = node, parameters = _a.parameters, type = _a.type; return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); } - case 186: + case 187: return typeHasArrowFunctionBlockingParseError(node.type); default: return false; @@ -24571,11 +25304,14 @@ var ts; function parseParameterWorker(inOuterAwaitContext) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); + var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); if (token() === 107) { - var node_1 = factory.createParameterDeclaration(undefined, undefined, undefined, createIdentifier(true), undefined, parseTypeAnnotation(), undefined); + var node_1 = factory.createParameterDeclaration(decorators, undefined, undefined, createIdentifier(true), undefined, parseTypeAnnotation(), undefined); + if (decorators) { + parseErrorAtRange(decorators[0], ts.Diagnostics.Decorators_may_not_be_applied_to_this_parameters); + } return withJSDoc(finishNode(node_1, pos), hasJSDoc); } - var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); var savedTopLevel = topLevel; topLevel = false; var modifiers = parseModifiers(); @@ -24632,14 +25368,14 @@ var ts; function parseSignatureMember(kind) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); - if (kind === 170) { + if (kind === 171) { parseExpected(102); } var typeParameters = parseTypeParameters(); var parameters = parseParameters(4); var type = parseReturnType(58, true); parseTypeMemberSemicolon(); - var node = kind === 169 + var node = kind === 170 ? factory.createCallSignature(typeParameters, parameters, type) : factory.createConstructSignature(typeParameters, parameters, type); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -24700,7 +25436,10 @@ var ts; return withJSDoc(finishNode(node, pos), hasJSDoc); } function isTypeMemberStart() { - if (token() === 20 || token() === 29) { + if (token() === 20 || + token() === 29 || + token() === 134 || + token() === 146) { return true; } var idToken = false; @@ -24727,14 +25466,20 @@ var ts; } function parseTypeMember() { if (token() === 20 || token() === 29) { - return parseSignatureMember(169); + return parseSignatureMember(170); } if (token() === 102 && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(170); + return parseSignatureMember(171); } var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiers(); + if (parseContextualModifier(134)) { + return parseAccessorDeclaration(pos, hasJSDoc, undefined, modifiers, 168); + } + if (parseContextualModifier(146)) { + return parseAccessorDeclaration(pos, hasJSDoc, undefined, modifiers, 169); + } if (isIndexSignature()) { return parseIndexSignatureDeclaration(pos, hasJSDoc, undefined, modifiers); } @@ -25574,7 +26319,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand, pos); } function isInOrOfKeyword(t) { - return t === 100 || t === 156; + return t === 100 || t === 157; } function parseBinaryExpressionRest(precedence, leftOperand, pos) { while (true) { @@ -25658,7 +26403,7 @@ var ts; if (token() === 42) { var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); var end = simpleUnaryExpression.end; - if (simpleUnaryExpression.kind === 206) { + if (simpleUnaryExpression.kind === 207) { parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -25774,7 +26519,7 @@ var ts; var pos = getNodePos(); var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 275) { + if (opening.kind === 276) { var children = parseJsxChildren(opening); var closingElement = parseJsxClosingElement(inExpressionContext); if (!tagNamesAreEquivalent(opening.tagName, closingElement.tagName)) { @@ -25782,11 +26527,11 @@ var ts; } result = finishNode(factory.createJsxElement(opening, children, closingElement), pos); } - else if (opening.kind === 278) { + else if (opening.kind === 279) { result = finishNode(factory.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos); } else { - ts.Debug.assert(opening.kind === 274); + ts.Debug.assert(opening.kind === 275); result = opening; } if (inExpressionContext && token() === 29) { @@ -26234,10 +26979,10 @@ var ts; var decorators = parseDecorators(); var modifiers = parseModifiers(); if (parseContextualModifier(134)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168); } if (parseContextualModifier(146)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 169); } var asteriskToken = parseOptionalToken(41); var tokenIsIdentifier = isIdentifier(); @@ -26340,6 +27085,7 @@ var ts; } function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); var openBracePosition = scanner.getTokenPos(); if (parseExpected(18, diagnosticMessage) || ignoreMissingOpenBrace) { var multiLine = scanner.hasPrecedingLineBreak(); @@ -26350,11 +27096,16 @@ var ts; ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); } } - return finishNode(factory.createBlock(statements, multiLine), pos); + var result = withJSDoc(finishNode(factory.createBlock(statements, multiLine), pos), hasJSDoc); + if (token() === 62) { + parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses); + nextToken(); + } + return result; } else { var statements = createMissingList(); - return finishNode(factory.createBlock(statements, undefined), pos); + return withJSDoc(finishNode(factory.createBlock(statements, undefined), pos), hasJSDoc); } } function parseFunctionBlock(flags, diagnosticMessage) { @@ -26379,21 +27130,24 @@ var ts; } function parseEmptyStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(26); - return finishNode(factory.createEmptyStatement(), pos); + return withJSDoc(finishNode(factory.createEmptyStatement(), pos), hasJSDoc); } function parseIfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(98); parseExpected(20); var expression = allowInAnd(parseExpression); parseExpected(21); var thenStatement = parseStatement(); var elseStatement = parseOptional(90) ? parseStatement() : undefined; - return finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos); + return withJSDoc(finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc); } function parseDoStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(89); var statement = parseStatement(); parseExpected(114); @@ -26401,19 +27155,21 @@ var ts; var expression = allowInAnd(parseExpression); parseExpected(21); parseOptional(26); - return finishNode(factory.createDoStatement(statement, expression), pos); + return withJSDoc(finishNode(factory.createDoStatement(statement, expression), pos), hasJSDoc); } function parseWhileStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(114); parseExpected(20); var expression = allowInAnd(parseExpression); parseExpected(21); var statement = parseStatement(); - return finishNode(factory.createWhileStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWhileStatement(expression, statement), pos), hasJSDoc); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(96); var awaitToken = parseOptionalToken(130); parseExpected(20); @@ -26427,7 +27183,7 @@ var ts; } } var node; - if (awaitToken ? parseExpected(156) : parseOptional(156)) { + if (awaitToken ? parseExpected(157) : parseOptional(157)) { var expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(21); node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement()); @@ -26449,33 +27205,36 @@ var ts; parseExpected(21); node = factory.createForStatement(initializer, condition, incrementor, parseStatement()); } - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseBreakOrContinueStatement(kind) { var pos = getNodePos(); - parseExpected(kind === 241 ? 80 : 85); + var hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(kind === 242 ? 80 : 85); var label = canParseSemicolon() ? undefined : parseIdentifier(); parseSemicolon(); - var node = kind === 241 + var node = kind === 242 ? factory.createBreakStatement(label) : factory.createContinueStatement(label); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseReturnStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(104); var expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression); parseSemicolon(); - return finishNode(factory.createReturnStatement(expression), pos); + return withJSDoc(finishNode(factory.createReturnStatement(expression), pos), hasJSDoc); } function parseWithStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(115); parseExpected(20); var expression = allowInAnd(parseExpression); parseExpected(21); var statement = doInsideOfContext(16777216, parseStatement); - return finishNode(factory.createWithStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWithStatement(expression, statement), pos), hasJSDoc); } function parseCaseClause() { var pos = getNodePos(); @@ -26504,15 +27263,17 @@ var ts; } function parseSwitchStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(106); parseExpected(20); var expression = allowInAnd(parseExpression); parseExpected(21); var caseBlock = parseCaseBlock(); - return finishNode(factory.createSwitchStatement(expression, caseBlock), pos); + return withJSDoc(finishNode(factory.createSwitchStatement(expression, caseBlock), pos), hasJSDoc); } function parseThrowStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(108); var expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); if (expression === undefined) { @@ -26520,10 +27281,11 @@ var ts; expression = finishNode(factory.createIdentifier(""), getNodePos()); } parseSemicolon(); - return finishNode(factory.createThrowStatement(expression), pos); + return withJSDoc(finishNode(factory.createThrowStatement(expression), pos), hasJSDoc); } function parseTryStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(110); var tryBlock = parseBlock(false); var catchClause = token() === 82 ? parseCatchClause() : undefined; @@ -26532,7 +27294,7 @@ var ts; parseExpected(95); finallyBlock = parseBlock(false); } - return finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos); + return withJSDoc(finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); } function parseCatchClause() { var pos = getNodePos(); @@ -26550,9 +27312,10 @@ var ts; } function parseDebuggerStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(86); parseSemicolon(); - return finishNode(factory.createDebuggerStatement(), pos); + return withJSDoc(finishNode(factory.createDebuggerStatement(), pos), hasJSDoc); } function parseExpressionOrLabeledStatement() { var pos = getNodePos(); @@ -26726,9 +27489,9 @@ var ts; case 96: return parseForOrForInOrForOfStatement(); case 85: - return parseBreakOrContinueStatement(240); - case 80: return parseBreakOrContinueStatement(241); + case 80: + return parseBreakOrContinueStatement(242); case 104: return parseReturnStatement(); case 115: @@ -26838,7 +27601,7 @@ var ts; } default: if (decorators || modifiers) { - var missing = createMissingNode(271, true, ts.Diagnostics.Declaration_expected); + var missing = createMissingNode(272, true, ts.Diagnostics.Declaration_expected); ts.setTextRangePos(missing, pos); missing.decorators = decorators; missing.modifiers = modifiers; @@ -26919,6 +27682,7 @@ var ts; } function parseVariableDeclaration(allowExclamation) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); var name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations); var exclamationToken; if (allowExclamation && name.kind === 78 && @@ -26928,7 +27692,7 @@ var ts; var type = parseTypeAnnotation(); var initializer = isInOrOfKeyword(token()) ? undefined : parseInitializer(); var node = factory.createVariableDeclaration(name, exclamationToken, type, initializer); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseVariableDeclarationList(inForStatementInitializer) { var pos = getNodePos(); @@ -26947,7 +27711,7 @@ var ts; } nextToken(); var declarations; - if (token() === 156 && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 157 && lookAhead(canFollowContextualOfKeyword)) { declarations = createMissingList(); } else { @@ -27045,11 +27809,11 @@ var ts; var parameters = parseParameters(0); var type = parseReturnType(58, false); var body = parseFunctionBlockOrSemicolon(0); - var node = kind === 167 + var node = kind === 168 ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body); node.typeParameters = typeParameters; - if (type && node.kind === 168) + if (type && node.kind === 169) node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -27162,10 +27926,10 @@ var ts; var decorators = parseDecorators(); var modifiers = parseModifiers(true); if (parseContextualModifier(134)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168); } if (parseContextualModifier(146)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 169); } if (token() === 132 || token() === 10) { var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers); @@ -27200,10 +27964,10 @@ var ts; return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), undefined, undefined, 221); + return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), undefined, undefined, 222); } function parseClassDeclaration(pos, hasJSDoc, decorators, modifiers) { - return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 252); + return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 253); } function parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, kind) { var savedAwaitContext = inAwaitContext(); @@ -27222,7 +27986,7 @@ var ts; members = createMissingList(); } setAwaitContext(savedAwaitContext); - var node = kind === 252 + var node = kind === 253 ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -27430,7 +28194,7 @@ var ts; var namedBindings; if (!identifier || parseOptional(27)) { - namedBindings = token() === 41 ? parseNamespaceImport() : parseNamedImportsOrExports(264); + namedBindings = token() === 41 ? parseNamespaceImport() : parseNamedImportsOrExports(265); } return finishNode(factory.createImportClause(isTypeOnly, identifier, namedBindings), pos); } @@ -27466,16 +28230,16 @@ var ts; } function parseNamedImportsOrExports(kind) { var pos = getNodePos(); - var node = kind === 264 + var node = kind === 265 ? factory.createNamedImports(parseBracketedList(23, parseImportSpecifier, 18, 19)) : factory.createNamedExports(parseBracketedList(23, parseExportSpecifier, 18, 19)); return finishNode(node, pos); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(270); + return parseImportOrExportSpecifier(271); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(265); + return parseImportOrExportSpecifier(266); } function parseImportOrExportSpecifier(kind) { var pos = getNodePos(); @@ -27496,10 +28260,10 @@ var ts; else { name = identifierName; } - if (kind === 265 && checkIdentifierIsKeyword) { + if (kind === 266 && checkIdentifierIsKeyword) { parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } - var node = kind === 265 + var node = kind === 266 ? factory.createImportSpecifier(propertyName, name) : factory.createExportSpecifier(propertyName, name); return finishNode(node, pos); @@ -27522,7 +28286,7 @@ var ts; moduleSpecifier = parseModuleSpecifier(); } else { - exportClause = parseNamedImportsOrExports(268); + exportClause = parseNamedImportsOrExports(269); if (token() === 153 || (token() === 10 && !scanner.hasPrecedingLineBreak())) { parseExpected(153); moduleSpecifier = parseModuleSpecifier(); @@ -27656,7 +28420,10 @@ var ts; var tags; var tagsPos; var tagsEnd; + var linkEnd; + var commentsPos; var comments = []; + var parts = []; return scanner.scanRange(start + 3, length - 5, function () { var state = 1; var margin; @@ -27680,6 +28447,8 @@ var ts; case 59: if (state === 0 || state === 1) { removeTrailingWhitespace(comments); + if (!commentsPos) + commentsPos = getNodePos(); addTag(parseTag(indent)); state = 0; margin = undefined; @@ -27716,6 +28485,21 @@ var ts; break; case 1: break loop; + case 18: + state = 2; + var commentEnd = scanner.getStartPos(); + var linkStart = scanner.getTextPos() - 1; + var link = parseJSDocLink(linkStart); + if (link) { + if (!linkEnd) { + removeLeadingNewlines(comments); + } + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : start, commentEnd)); + parts.push(link); + comments = []; + linkEnd = scanner.getTextPos(); + break; + } default: state = 2; pushComment(scanner.getTokenText()); @@ -27723,9 +28507,14 @@ var ts; } nextTokenJSDoc(); } - removeLeadingNewlines(comments); removeTrailingWhitespace(comments); - return createJSDocComment(); + if (parts.length && comments.length) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : start, commentsPos)); + } + if (parts.length && tags) + ts.Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); + var tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); + return finishNode(factory.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : comments.length ? comments.join("") : undefined, tagsArray), start, end); }); function removeLeadingNewlines(comments) { while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { @@ -27737,11 +28526,6 @@ var ts; comments.pop(); } } - function createJSDocComment() { - var comment = comments.length ? comments.join("") : undefined; - var tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); - return finishNode(factory.createJSDocComment(comment, tagsArray), start, end); - } function isNextNonwhitespaceTokenEndOfFile() { while (true) { nextTokenJSDoc(); @@ -27820,6 +28604,9 @@ var ts; case "readonly": tag = parseSimpleTag(start, factory.createJSDocReadonlyTag, tagName, margin, indentText); break; + case "override": + tag = parseSimpleTag(start, factory.createJSDocOverrideTag, tagName, margin, indentText); + break; case "deprecated": hasDeprecatedTag = true; tag = parseSimpleTag(start, factory.createJSDocDeprecatedTag, tagName, margin, indentText); @@ -27866,8 +28653,12 @@ var ts; return parseTagComments(margin, indentText.slice(margin)); } function parseTagComments(indent, initialMargin) { + var commentsPos = getNodePos(); var comments = []; + var parts = []; + var linkEnd; var state = 0; + var previousWhitespace = true; var margin; function pushComment(text) { if (!margin) { @@ -27891,7 +28682,8 @@ var ts; indent = 0; break; case 59: - if (state === 3) { + if (state === 3 + || state === 2 && (!previousWhitespace || lookAhead(isNextJSDocTokenWhitespace))) { comments.push(scanner.getTokenText()); break; } @@ -27912,13 +28704,18 @@ var ts; break; case 18: state = 2; - if (lookAhead(function () { return nextTokenJSDoc() === 59 && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) { - pushComment(scanner.getTokenText()); - nextTokenJSDoc(); + var commentEnd = scanner.getStartPos(); + var linkStart = scanner.getTextPos() - 1; + var link = parseJSDocLink(linkStart); + if (link) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : commentsPos, commentEnd)); + parts.push(link); + comments = []; + linkEnd = scanner.getTextPos(); + } + else { pushComment(scanner.getTokenText()); - nextTokenJSDoc(); } - pushComment(scanner.getTokenText()); break; case 61: if (state === 3) { @@ -27942,15 +28739,50 @@ var ts; pushComment(scanner.getTokenText()); break; } + previousWhitespace = token() === 5; tok = nextTokenJSDoc(); } removeLeadingNewlines(comments); removeTrailingWhitespace(comments); - return comments.length === 0 ? undefined : comments.join(""); + if (parts.length) { + if (comments.length) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : commentsPos)); + } + return createNodeArray(parts, commentsPos, scanner.getTextPos()); + } + else if (comments.length) { + return comments.join(""); + } + } + function isNextJSDocTokenWhitespace() { + var next = nextTokenJSDoc(); + return next === 5 || next === 4; + } + function parseJSDocLink(start) { + if (!tryParse(parseJSDocLinkPrefix)) { + return undefined; + } + nextTokenJSDoc(); + skipWhitespace(); + var name = ts.tokenIsIdentifierOrKeyword(token()) + ? parseEntityName(true) + : undefined; + var text = []; + while (token() !== 19 && token() !== 4 && token() !== 1) { + text.push(scanner.getTokenText()); + nextTokenJSDoc(); + } + return finishNode(factory.createJSDocLink(name, text.join("")), start, scanner.getTextPos()); + } + function parseJSDocLinkPrefix() { + skipWhitespaceOrAsterisk(); + return token() === 18 + && nextTokenJSDoc() === 59 + && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) + && scanner.getTokenValue() === "link"; } function parseUnknownTag(start, tagName, indent, indentText) { - var end = getNodePos(); - return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function addTag(tag) { if (!tag) { @@ -27992,7 +28824,7 @@ var ts; switch (node.kind) { case 145: return true; - case 178: + case 179: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments; @@ -28003,11 +28835,11 @@ var ts; var isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; - skipWhitespace(); - if (isNameFirst) { + var indentText = skipWhitespaceOrAsterisk(); + if (isNameFirst && !lookAhead(parseJSDocLinkPrefix)) { typeExpression = tryParseTypeExpression(); } - var comment = parseTagComments(indent + scanner.getStartPos() - start); + var comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); var nestedTypeLiteral = target !== 4 && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; @@ -28024,12 +28856,12 @@ var ts; var child = void 0; var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { - if (child.kind === 326 || child.kind === 333) { + if (child.kind === 330 || child.kind === 337) { children = ts.append(children, child); } } if (children) { - var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 178), pos); + var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 179), pos); return finishNode(factory.createJSDocTypeExpression(literal), pos); } } @@ -28039,27 +28871,34 @@ var ts; parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeExpression = tryParseTypeExpression(); - var end = getNodePos(); - return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function parseTypeTag(start, tagName, indent, indentText) { if (ts.some(tags, ts.isJSDocTypeTag)) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeExpression = parseJSDocTypeExpression(true); - var end = getNodePos(); - var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined; - return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start, end); + var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; + return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start); } function parseSeeTag(start, tagName, indent, indentText) { - var nameExpression = parseJSDocNameReference(); - var end = getNodePos(); - var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined; - return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start, end); + var isLink = lookAhead(function () { return nextTokenJSDoc() === 59 && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; }); + var nameExpression = isLink ? undefined : parseJSDocNameReference(); + var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; + return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start); } function parseAuthorTag(start, tagName, indent, indentText) { - var comments = parseAuthorNameAndEmail() + (parseTrailingTagComments(start, end, indent, indentText) || ""); - return finishNode(factory.createJSDocAuthorTag(tagName, comments || undefined), start); + var commentStart = getNodePos(); + var textOnly = parseAuthorNameAndEmail(); + var commentEnd = scanner.getStartPos(); + var comments = parseTrailingTagComments(start, commentEnd, indent, indentText); + if (!comments) { + commentEnd = scanner.getStartPos(); + } + var allParts = typeof comments !== "string" + ? createNodeArray(ts.concatenate([finishNode(textOnly, commentStart, commentEnd)], comments), commentStart) + : textOnly.text + comments; + return finishNode(factory.createJSDocAuthorTag(tagName, allParts), start); } function parseAuthorNameAndEmail() { var comments = []; @@ -28080,17 +28919,15 @@ var ts; comments.push(scanner.getTokenText()); token = nextTokenJSDoc(); } - return comments.join(""); + return factory.createJSDocText(comments.join("")); } function parseImplementsTag(start, tagName, margin, indentText) { var className = parseExpressionWithTypeArgumentsForAugments(); - var end = getNodePos(); - return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseAugmentsTag(start, tagName, margin, indentText) { var className = parseExpressionWithTypeArgumentsForAugments(); - var end = getNodePos(); - return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseExpressionWithTypeArgumentsForAugments() { var usedBrace = parseOptional(18); @@ -28114,20 +28951,17 @@ var ts; return node; } function parseSimpleTag(start, createTag, tagName, margin, indentText) { - var end = getNodePos(); - return finishNode(createTag(tagName, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(createTag(tagName, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseThisTag(start, tagName, margin, indentText) { var typeExpression = parseJSDocTypeExpression(true); skipWhitespace(); - var end = getNodePos(); - return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseEnumTag(start, tagName, margin, indentText) { var typeExpression = parseJSDocTypeExpression(true); skipWhitespace(); - var end = getNodePos(); - return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseTypedefTag(start, tagName, indent, indentText) { var _a; @@ -28144,7 +28978,7 @@ var ts; var hasChildren = false; while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { hasChildren = true; - if (child.kind === 329) { + if (child.kind === 333) { if (childTypeTag) { parseErrorAtCurrentToken(ts.Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags); var lastError = ts.lastOrUndefined(parseDiagnostics); @@ -28162,7 +28996,7 @@ var ts; } } if (hasChildren) { - var isArrayType = typeExpression && typeExpression.type.kind === 178; + var isArrayType = typeExpression && typeExpression.type.kind === 179; var jsdocTypeLiteral = factory.createJSDocTypeLiteral(jsDocPropertyTags, isArrayType); typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : @@ -28212,17 +29046,16 @@ var ts; var returnTag = tryParse(function () { if (parseOptionalJsdoc(59)) { var tag = parseTag(indent); - if (tag && tag.kind === 327) { + if (tag && tag.kind === 331) { return tag; } } }); var typeExpression = finishNode(factory.createJSDocSignature(undefined, parameters, returnTag), start); - var end = getNodePos(); if (!comment) { - comment = parseTrailingTagComments(start, end, indent, indentText); + comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); } - return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start, end); + return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start); } function escapedTextsEqual(a, b) { while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { @@ -28247,7 +29080,7 @@ var ts; case 59: if (canParseTag) { var child = tryParseChildTag(target, indent); - if (child && (child.kind === 326 || child.kind === 333) && + if (child && (child.kind === 330 || child.kind === 337) && target !== 4 && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -28304,6 +29137,9 @@ var ts; function parseTemplateTagTypeParameter() { var typeParameterPos = getNodePos(); var name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); + if (ts.nodeIsMissing(name)) { + return undefined; + } return finishNode(factory.createTypeParameterDeclaration(name, undefined, undefined), typeParameterPos); } function parseTemplateTagTypeParameters() { @@ -28311,7 +29147,10 @@ var ts; var typeParameters = []; do { skipWhitespace(); - typeParameters.push(parseTemplateTagTypeParameter()); + var node = parseTemplateTagTypeParameter(); + if (node !== undefined) { + typeParameters.push(node); + } skipWhitespaceOrAsterisk(); } while (parseOptionalJsdoc(27)); return createNodeArray(typeParameters, pos); @@ -28319,8 +29158,7 @@ var ts; function parseTemplateTag(start, tagName, indent, indentText) { var constraint = token() === 18 ? parseJSDocTypeExpression() : undefined; var typeParameters = parseTemplateTagTypeParameters(); - var end = getNodePos(); - return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function parseOptionalJsdoc(t) { if (token() === t) { @@ -28920,6 +29758,7 @@ var ts; ["es2018", "lib.es2018.d.ts"], ["es2019", "lib.es2019.d.ts"], ["es2020", "lib.es2020.d.ts"], + ["es2021", "lib.es2021.d.ts"], ["esnext", "lib.esnext.d.ts"], ["dom", "lib.dom.d.ts"], ["dom.iterable", "lib.dom.iterable.d.ts"], @@ -28957,14 +29796,17 @@ var ts; ["es2020.string", "lib.es2020.string.d.ts"], ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"], ["es2020.intl", "lib.es2020.intl.d.ts"], + ["es2021.promise", "lib.es2021.promise.d.ts"], + ["es2021.string", "lib.es2021.string.d.ts"], + ["es2021.weakref", "lib.es2021.weakref.d.ts"], ["esnext.array", "lib.es2019.array.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"], ["esnext.intl", "lib.esnext.intl.d.ts"], ["esnext.bigint", "lib.es2020.bigint.d.ts"], - ["esnext.string", "lib.esnext.string.d.ts"], - ["esnext.promise", "lib.esnext.promise.d.ts"], - ["esnext.weakref", "lib.esnext.weakref.d.ts"] + ["esnext.string", "lib.es2021.string.d.ts"], + ["esnext.promise", "lib.es2021.promise.d.ts"], + ["esnext.weakref", "lib.es2021.weakref.d.ts"] ]; ts.libs = libEntries.map(function (entry) { return entry[0]; }); ts.libMap = new ts.Map(libEntries); @@ -28975,11 +29817,12 @@ var ts; fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval, prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval, dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling, + fixedchunksizepolling: ts.WatchFileKind.FixedChunkSizePolling, usefsevents: ts.WatchFileKind.UseFsEvents, usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory, })), category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory, + description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling_UseFsEvents_UseFsEventsOnParentDirectory, }, { name: "watchDirectory", @@ -28987,9 +29830,10 @@ var ts; usefsevents: ts.WatchDirectoryKind.UseFsEvents, fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval, dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling, + fixedchunksizepolling: ts.WatchDirectoryKind.FixedChunkSizePolling, })), category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling, + description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling, }, { name: "fallbackPolling", @@ -28997,9 +29841,10 @@ var ts; fixedinterval: ts.PollingWatchKind.FixedInterval, priorityinterval: ts.PollingWatchKind.PriorityInterval, dynamicpriority: ts.PollingWatchKind.DynamicPriority, + fixedchunksize: ts.PollingWatchKind.FixedChunkSize, })), category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority, + description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority_FixedChunkSize, }, { name: "synchronousWatchDirectory", @@ -29156,6 +30001,7 @@ var ts; es2018: 5, es2019: 6, es2020: 7, + es2021: 8, esnext: 99, })), affectsSourceFile: true, @@ -29164,9 +30010,9 @@ var ts; paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT, }; - ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsWithoutBuild = [ { name: "all", type: "boolean", @@ -29526,6 +30372,14 @@ var ts; category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Include_undefined_in_index_signature_results }, + { + name: "noImplicitOverride", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier + }, { name: "noPropertyAccessFromIndexSignature", type: "boolean", @@ -29927,7 +30781,8 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins }, - ]); + ]; + ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsWithoutBuild); ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; }); ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); @@ -29937,7 +30792,7 @@ var ts; ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) { return ts.hasProperty(option, "transpileOptionValue"); }); - ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsOnlyBuild = [ { name: "verbose", shortName: "v", @@ -29965,7 +30820,8 @@ var ts; description: ts.Diagnostics.Delete_the_outputs_of_all_projects, type: "boolean" } - ]); + ]; + ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsOnlyBuild); ts.typeAcquisitionDeclarations = [ { name: "enableAutoDiscovery", @@ -30013,6 +30869,10 @@ var ts; return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations)); } ts.getOptionsNameMap = getOptionsNameMap; + var compilerOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_only_be_used_with_build, + getOptionsNameMap: getBuildOptionsNameMap + }; ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, target: 1, @@ -30068,6 +30928,10 @@ var ts; return option.name; } function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) { + var _a; + if ((_a = diagnostics.alternateMode) === null || _a === void 0 ? void 0 : _a.getOptionsNameMap().optionsNameMap.has(unknownOption.toLowerCase())) { + return createDiagnostics(diagnostics.alternateMode.diagnostic, unknownOption); + } var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName); return possibleOption ? createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : @@ -30216,6 +31080,7 @@ var ts; return i; } ts.compilerOptionsDidYouMeanDiagnostics = { + alternateMode: compilerOptionsAlternateMode, getOptionsNameMap: getOptionsNameMap, optionDeclarations: ts.optionDeclarations, unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, @@ -30246,7 +31111,12 @@ var ts; function getBuildOptionsNameMap() { return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts)); } + var buildOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_not_be_used_with_build, + getOptionsNameMap: getOptionsNameMap + }; var buildOptionsDidYouMeanDiagnostics = { + alternateMode: buildOptionsAlternateMode, getOptionsNameMap: getBuildOptionsNameMap, optionDeclarations: ts.buildOpts, unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0, @@ -30305,7 +31175,7 @@ var ts; function parseConfigFileTextToJson(fileName, jsonText) { var jsonSourceFile = ts.parseJsonText(fileName, jsonText); return { - config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + config: convertConfigFileToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics, false, undefined), error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined }; } @@ -30430,22 +31300,39 @@ var ts; } return _tsconfigRootOptions; } + function convertConfigFileToObject(sourceFile, errors, reportOptionsErrors, optionsIterator) { + var _a; + var rootExpression = (_a = sourceFile.statements[0]) === null || _a === void 0 ? void 0 : _a.expression; + var knownRootOptions = reportOptionsErrors ? getTsconfigRootOptionsMap() : undefined; + if (rootExpression && rootExpression.kind !== 201) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, rootExpression, ts.Diagnostics.The_root_value_of_a_0_file_must_be_an_object, ts.getBaseFileName(sourceFile.fileName) === "jsconfig.json" ? "jsconfig.json" : "tsconfig.json")); + if (ts.isArrayLiteralExpression(rootExpression)) { + var firstObject = ts.find(rootExpression.elements, ts.isObjectLiteralExpression); + if (firstObject) { + return convertToObjectWorker(sourceFile, firstObject, errors, true, knownRootOptions, optionsIterator); + } + } + return {}; + } + return convertToObjectWorker(sourceFile, rootExpression, errors, true, knownRootOptions, optionsIterator); + } function convertToObject(sourceFile, errors) { - return convertToObjectWorker(sourceFile, errors, true, undefined, undefined); + var _a; + return convertToObjectWorker(sourceFile, (_a = sourceFile.statements[0]) === null || _a === void 0 ? void 0 : _a.expression, errors, true, undefined, undefined); } ts.convertToObject = convertToObject; - function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { - if (!sourceFile.statements.length) { + function convertToObjectWorker(sourceFile, rootExpression, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!rootExpression) { return returnValue ? {} : undefined; } - return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + return convertPropertyValueToJson(rootExpression, knownRootOptions); function isRootOptionMap(knownOptions) { return knownRootOptions && knownRootOptions.elementOptions === knownOptions; } function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) { var result = returnValue ? {} : undefined; var _loop_4 = function (element) { - if (element.kind !== 288) { + if (element.kind !== 289) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); return "continue"; } @@ -30532,13 +31419,13 @@ var ts; case 8: reportInvalidOptionValue(option && option.type !== "number"); return validateValue(Number(valueExpression.text)); - case 214: + case 215: if (valueExpression.operator !== 40 || valueExpression.operand.kind !== 8) { break; } reportInvalidOptionValue(option && option.type !== "number"); return validateValue(-Number(valueExpression.operand.text)); - case 200: + case 201: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; if (option) { @@ -30548,7 +31435,7 @@ var ts; else { return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression, undefined, undefined, undefined)); } - case 199: + case 200: reportInvalidOptionValue(option && option.type !== "list"); return validateValue(convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element)); } @@ -31024,14 +31911,14 @@ var ts; } if (ownConfig.extendedConfigPath) { resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, resolutionStack, errors, extendedConfigCache); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { var baseRaw_1 = extendedConfig.raw; var raw_1 = ownConfig.raw; + var relativeDifference_1; var setPropertyInRawIfNotUndefined = function (propertyName) { - var value = raw_1[propertyName] || baseRaw_1[propertyName]; - if (value) { - raw_1[propertyName] = value; + if (!raw_1[propertyName] && baseRaw_1[propertyName]) { + raw_1[propertyName] = ts.map(baseRaw_1[propertyName], function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1 || (relativeDifference_1 = ts.convertToRelativePath(ts.getDirectoryPath(ownConfig.extendedConfigPath), basePath, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames))), path); }); } }; setPropertyInRawIfNotUndefined("include"); @@ -31110,7 +31997,7 @@ var ts; } } }; - var json = convertToObjectWorker(sourceFile, errors, true, getTsconfigRootOptionsMap(), optionsIterator); + var json = convertConfigFileToObject(sourceFile, errors, true, optionsIterator); if (!typeAcquisition) { if (typingOptionstypeAcquisition) { typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? @@ -31147,7 +32034,7 @@ var ts; errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig)); return undefined; } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) { + function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache) { var _a; var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath); var value; @@ -31159,21 +32046,7 @@ var ts; else { extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (!extendedResult.parseDiagnostics.length) { - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); - if (isSuccessfulParsedTsconfig(extendedConfig)) { - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); - var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; - var mapPropertiesInRawIfNotUndefined = function (propertyName) { - if (raw_2[propertyName]) { - raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); - } - }; - var raw_2 = extendedConfig.raw; - mapPropertiesInRawIfNotUndefined("include"); - mapPropertiesInRawIfNotUndefined("exclude"); - mapPropertiesInRawIfNotUndefined("files"); - } + extendedConfig = parseConfig(undefined, extendedResult, host, ts.getDirectoryPath(extendedConfigPath), ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); } if (extendedConfigCache) { extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig }); @@ -31728,13 +32601,24 @@ var ts; return typeRoots; } var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache) { var traceEnabled = isTraceEnabled(options, host); if (redirectedReference) { options = redirectedReference.commandLine.options; } - var failedLookupLocations = []; - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var containingDirectory = containingFile ? ts.getDirectoryPath(containingFile) : undefined; + var perFolderCache = containingDirectory ? cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference) : undefined; + var result = perFolderCache && perFolderCache.get(typeReferenceDirectiveName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile); + if (redirectedReference) + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + trace(host, ts.Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory); + traceResult(result); + } + return result; + } var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -31757,6 +32641,8 @@ var ts; trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); } } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -31767,17 +32653,31 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); - if (traceEnabled) { - if (packageId) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, ts.packageIdToString(packageId), primary); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); - } + resolvedTypeReferenceDirective = { + primary: primary, + resolvedFileName: resolvedFileName, + originalPath: fileName === resolvedFileName ? undefined : fileName, + packageId: packageId, + isExternalLibraryImport: pathContainsNodeModules(fileName), + }; + } + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, result); + if (traceEnabled) + traceResult(result); + return result; + function traceResult(result) { + var _a; + if (!((_a = result.resolvedTypeReferenceDirective) === null || _a === void 0 ? void 0 : _a.resolvedFileName)) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + else if (result.resolvedTypeReferenceDirective.packageId) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, ts.packageIdToString(result.resolvedTypeReferenceDirective.packageId), result.resolvedTypeReferenceDirective.primary); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, result.resolvedTypeReferenceDirective.primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } - return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { if (typeRoots && typeRoots.length) { if (traceEnabled) { @@ -31805,20 +32705,16 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = void 0; + var result_4; if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, undefined, undefined); - result = searchResult && searchResult.value; + result_4 = searchResult && searchResult.value; } else { var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; - result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, false, moduleResolutionState, true); - } - var resolvedFile = resolvedTypeScriptOnly(result); - if (!resolvedFile && traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + result_4 = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, false, moduleResolutionState, true); } - return resolvedFile; + return resolvedTypeScriptOnly(result_4); } else { if (traceEnabled) { @@ -31858,21 +32754,20 @@ var ts; return result; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; - function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) { - return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName); - } - ts.createModuleResolutionCache = createModuleResolutionCache; function createCacheWithRedirects(options) { var ownMap = new ts.Map(); var redirectsMap = new ts.Map(); return { - ownMap: ownMap, + getOwnMap: getOwnMap, redirectsMap: redirectsMap, getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, clear: clear, setOwnOptions: setOwnOptions, setOwnMap: setOwnMap }; + function getOwnMap() { + return ownMap; + } function setOwnOptions(newOptions) { options = newOptions; } @@ -31897,25 +32792,86 @@ var ts; } } ts.createCacheWithRedirects = createCacheWithRedirects; - function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { - return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap }; + function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { + var cache; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear }; + function getPackageJsonInfo(packageJsonPath) { + return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); + } + function setPackageJsonInfo(packageJsonPath, info) { + (cache || (cache = new ts.Map())).set(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info); + } + function clear() { + cache = undefined; + } + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + function updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + if (!options.configFile) + return; + if (directoryToModuleNameMap.redirectsMap.size === 0) { + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size === 0); + ts.Debug.assert(directoryToModuleNameMap.getOwnMap().size === 0); + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.getOwnMap().size === 0); + directoryToModuleNameMap.redirectsMap.set(options.configFile.path, directoryToModuleNameMap.getOwnMap()); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.redirectsMap.set(options.configFile.path, moduleNameToDirectoryMap.getOwnMap()); + } + else { + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size > 0); + var ref = { + sourceFile: options.configFile, + commandLine: { options: options } + }; + directoryToModuleNameMap.setOwnMap(directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnMap(moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); + } + directoryToModuleNameMap.setOwnOptions(options); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnOptions(options); + } + function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap) { + return { + getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, + clear: clear, + update: update, + }; + function clear() { + directoryToModuleNameMap.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap); + } function getOrCreateCacheForDirectory(directoryName, redirectedReference) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, function () { return new ts.Map(); }); } + } + function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + moduleNameToDirectoryMap || (moduleNameToDirectoryMap = createCacheWithRedirects(options)); + var packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName); + return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, + clear: clear, + update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; } }); + function clear() { + preDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + packageJsonInfoCache.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); + } function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); } - function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { - var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); - var result = cache.get(key); - if (!result) { - result = create(); - cache.set(key, result); - } - return result; - } function createPerModuleNameCache() { var directoryPathMap = new ts.Map(); return { get: get, set: set }; @@ -31963,7 +32919,17 @@ var ts; } } } - ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + ts.createModuleResolutionCache = createModuleResolutionCache; + function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { + var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); + return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + function clear() { + preDirectoryResolutionCache.clear(); + packageJsonInfoCache.clear(); + } + } + ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache) { var containingDirectory = ts.getDirectoryPath(containingFile); var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); @@ -32167,7 +33133,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, state.resultFromCache); function tryResolve(extensions) { @@ -32225,7 +33191,7 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { - var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, false, state) : undefined; return withPackageId(packageInfo, resolvedFromFile); } @@ -32247,7 +33213,7 @@ var ts; } ts.pathContainsNodeModules = pathContainsNodeModules; function parseNodeModuleFromPath(resolved) { - var path = ts.normalizePath(resolved.path); + var path = ts.normalizePath(resolved); var idx = path.lastIndexOf(ts.nodeModulesPathPart); if (idx === -1) { return undefined; @@ -32259,6 +33225,7 @@ var ts; } return path.slice(0, indexAfterPackageName); } + ts.parseNodeModuleFromPath = parseNodeModuleFromPath; function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; @@ -32332,21 +33299,43 @@ var ts; return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { + var _a, _b, _c; var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); + if (onlyRecordFailures) { + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + var existing = (_a = state.packageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfo(packageJsonPath); + if (existing !== undefined) { + if (typeof existing !== "boolean") { + if (traceEnabled) + trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + return existing; + } + else { + if (existing && traceEnabled) + trace(host, ts.Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + } + var directoryExists = ts.directoryProbablyExists(packageDirectory, host); if (directoryExists && host.fileExists(packageJsonPath)) { var packageJsonContent = ts.readJson(packageJsonPath, host); if (traceEnabled) { trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); - return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + return result; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + (_c = state.packageJsonInfoCache) === null || _c === void 0 ? void 0 : _c.setPackageJsonInfo(packageJsonPath, directoryExists); state.failedLookupLocations.push(packageJsonPath); } } @@ -32576,7 +33565,7 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations, state.resultFromCache); @@ -32609,13 +33598,13 @@ var ts; } } ts.classicNameResolver = classicNameResolver; - function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache, packageJsonInfoCache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, false); return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations, state.resultFromCache); } @@ -32647,23 +33636,23 @@ var ts; } function getModuleInstanceStateWorker(node, visited) { switch (node.kind) { - case 253: case 254: - return 0; case 255: + return 0; + case 256: if (ts.isEnumConst(node)) { return 2; } break; + case 262: case 261: - case 260: if (!(ts.hasSyntacticModifier(node, 1))) { return 0; } break; - case 267: + case 268: var exportDeclaration = node; - if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 268) { + if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 269) { var state = 0; for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; @@ -32678,7 +33667,7 @@ var ts; return state; } break; - case 257: { + case 258: { var state_1 = 0; ts.forEachChild(node, function (n) { var childState = getModuleInstanceStateCached(n, visited); @@ -32697,7 +33686,7 @@ var ts; }); return state_1; } - case 256: + case 257: return getModuleInstanceState(node, visited); case 78: if (node.isInJSDocNamespace) { @@ -32743,14 +33732,14 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { - ts.tracing.push("bind", "bindSourceFile", { path: file.path }, true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind", "bindSourceFile", { path: file.path }, true); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); ts.performance.measure("Bind", "beforeBind", "afterBind"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -32782,6 +33771,7 @@ var ts; var classifiableNames; var unreachableFlow = { flags: 1 }; var reportedUnreachableFlow = { flags: 1 }; + var bindBinaryExpressionFlow = createBindBinaryExpressionFlow(); function createDiagnosticForNode(node, message, arg0, arg1, arg2) { return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); } @@ -32854,7 +33844,7 @@ var ts; } } function getDeclarationName(node) { - if (node.kind === 266) { + if (node.kind === 267) { return node.isExportEquals ? "export=" : "default"; } var name = ts.getNameOfDeclaration(node); @@ -32863,7 +33853,7 @@ var ts; var moduleName = ts.getTextOfIdentifierOrLiteral(name); return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); } - if (name.kind === 158) { + if (name.kind === 159) { var nameExpression = name.expression; if (ts.isStringOrNumericLiteralLike(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); @@ -32871,11 +33861,9 @@ var ts; if (ts.isSignedNumericLiteral(nameExpression)) { return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text; } - ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); - return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - if (ts.isWellKnownSymbolSyntactically(name)) { - return ts.getPropertyNameForKnownSymbolName(ts.idText(name.name)); + else { + ts.Debug.fail("Only computed properties with literal names have declaration names"); + } } if (ts.isPrivateIdentifier(name)) { var containingClass = ts.getContainingClass(node); @@ -32888,31 +33876,31 @@ var ts; return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } switch (node.kind) { - case 166: + case 167: return "__constructor"; - case 174: - case 169: - case 313: - return "__call"; case 175: case 170: - return "__new"; + case 315: + return "__call"; + case 176: case 171: + return "__new"; + case 172: return "__index"; - case 267: + case 268: return "__export"; - case 297: + case 298: return "export="; - case 216: + case 217: if (ts.getAssignmentDeclarationKind(node) === 2) { return "export="; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 308: + case 309: return (ts.isJSDocConstructSignature(node) ? "__new" : "__call"); - case 160: - ts.Debug.assert(node.parent.kind === 308, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + case 161: + ts.Debug.assert(node.parent.kind === 309, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -32967,7 +33955,7 @@ var ts; } else { if (symbol.declarations && symbol.declarations.length && - (node.kind === 266 && !node.isExportEquals)) { + (node.kind === 267 && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName_1 = false; multipleDefaultExports_1 = true; @@ -33005,7 +33993,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = !!(ts.getCombinedModifierFlags(node) & 1) || jsdocTreatAsExported(node); if (symbolFlags & 2097152) { - if (node.kind === 270 || (node.kind === 260 && hasExportModifier)) { + if (node.kind === 271 || (node.kind === 261 && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -33052,7 +34040,7 @@ var ts; var saveThisParentContainer = thisParentContainer; var savedBlockScopeContainer = blockScopeContainer; if (containerFlags & 1) { - if (node.kind !== 209) { + if (node.kind !== 210) { thisParentContainer = container; } container = blockScopeContainer = node; @@ -33081,7 +34069,7 @@ var ts; currentFlow.node = node; } } - currentReturnTarget = isIIFE || node.kind === 166 || (ts.isInJSFile(node) && (node.kind === 251 || node.kind === 208)) ? createBranchLabel() : undefined; + currentReturnTarget = isIIFE || node.kind === 167 || (ts.isInJSFile(node) && (node.kind === 252 || node.kind === 209)) ? createBranchLabel() : undefined; currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; @@ -33095,13 +34083,14 @@ var ts; node.flags |= 512; node.endFlowNode = currentFlow; } - if (node.kind === 297) { + if (node.kind === 298) { node.flags |= emitFlags; + node.endFlowNode = currentFlow; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 166 || (ts.isInJSFile(node) && (node.kind === 251 || node.kind === 208))) { + if (node.kind === 167 || (ts.isInJSFile(node) && (node.kind === 252 || node.kind === 209))) { node.returnFlowNode = currentFlow; } } @@ -33128,8 +34117,8 @@ var ts; blockScopeContainer = savedBlockScopeContainer; } function bindEachFunctionsFirst(nodes) { - bindEach(nodes, function (n) { return n.kind === 251 ? bind(n) : undefined; }); - bindEach(nodes, function (n) { return n.kind !== 251 ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind === 252 ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 252 ? bind(n) : undefined; }); } function bindEach(nodes, bindFunction) { if (bindFunction === void 0) { bindFunction = bind; } @@ -33150,59 +34139,59 @@ var ts; inAssignmentPattern = saveInAssignmentPattern; return; } - if (node.kind >= 232 && node.kind <= 248 && !options.allowUnreachableCode) { + if (node.kind >= 233 && node.kind <= 249 && !options.allowUnreachableCode) { node.flowNode = currentFlow; } switch (node.kind) { - case 236: + case 237: bindWhileStatement(node); break; - case 235: + case 236: bindDoStatement(node); break; - case 237: + case 238: bindForStatement(node); break; - case 238: case 239: + case 240: bindForInOrForOfStatement(node); break; - case 234: + case 235: bindIfStatement(node); break; - case 242: - case 246: + case 243: + case 247: bindReturnOrThrow(node); break; + case 242: case 241: - case 240: bindBreakOrContinueStatement(node); break; - case 247: + case 248: bindTryStatement(node); break; - case 244: + case 245: bindSwitchStatement(node); break; - case 258: + case 259: bindCaseBlock(node); break; - case 284: + case 285: bindCaseClause(node); break; - case 233: + case 234: bindExpressionStatement(node); break; - case 245: + case 246: bindLabeledStatement(node); break; - case 214: + case 215: bindPrefixUnaryExpressionFlow(node); break; - case 215: + case 216: bindPostfixUnaryExpressionFlow(node); break; - case 216: + case 217: if (ts.isDestructuringAssignment(node)) { inAssignmentPattern = saveInAssignmentPattern; bindDestructuringAssignmentFlow(node); @@ -33210,46 +34199,46 @@ var ts; } bindBinaryExpressionFlow(node); break; - case 210: + case 211: bindDeleteExpressionFlow(node); break; - case 217: + case 218: bindConditionalExpressionFlow(node); break; - case 249: + case 250: bindVariableDeclarationFlow(node); break; - case 201: case 202: + case 203: bindAccessExpressionFlow(node); break; - case 203: + case 204: bindCallExpressionFlow(node); break; - case 225: + case 226: bindNonNullExpressionFlow(node); break; - case 331: - case 324: - case 325: + case 335: + case 328: + case 329: bindJSDocTypeAlias(node); break; - case 297: { + case 298: { bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); break; } - case 230: - case 257: + case 231: + case 258: bindEachFunctionsFirst(node.statements); break; - case 198: + case 199: bindBindingElementFlow(node); break; + case 201: case 200: - case 199: - case 288: - case 220: + case 289: + case 221: inAssignmentPattern = saveInAssignmentPattern; default: bindEachChild(node); @@ -33263,29 +34252,29 @@ var ts; case 78: case 79: case 107: - case 201: case 202: - return containsNarrowableReference(expr); case 203: + return containsNarrowableReference(expr); + case 204: return hasNarrowableArgument(expr); - case 207: - case 225: + case 208: + case 226: return isNarrowingExpression(expr.expression); - case 216: + case 217: return isNarrowingBinaryExpression(expr); - case 214: + case 215: return expr.operator === 53 && isNarrowingExpression(expr.operand); - case 211: + case 212: return isNarrowingExpression(expr.expression); } return false; } function isNarrowableReference(expr) { - return expr.kind === 78 || expr.kind === 79 || expr.kind === 107 || expr.kind === 105 || - (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isBinaryExpression(expr) && expr.operatorToken.kind === 27 && isNarrowableReference(expr.right) || - ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || - ts.isAssignmentExpression(expr) && isNarrowableReference(expr.left); + return ts.isDottedName(expr) + || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) + || ts.isBinaryExpression(expr) && expr.operatorToken.kind === 27 && isNarrowableReference(expr.right) + || ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) + || ts.isAssignmentExpression(expr) && isNarrowableReference(expr.left); } function containsNarrowableReference(expr) { return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression); @@ -33299,7 +34288,7 @@ var ts; } } } - if (expr.expression.kind === 201 && + if (expr.expression.kind === 202 && containsNarrowableReference(expr.expression.expression)) { return true; } @@ -33335,9 +34324,9 @@ var ts; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 207: + case 208: return isNarrowableOperand(expr.expression); - case 216: + case 217: switch (expr.operatorToken.kind) { case 62: return isNarrowableOperand(expr.left); @@ -33412,26 +34401,26 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 234: - case 236: case 235: - return parent.expression === node; case 237: - case 217: + case 236: + return parent.expression === node; + case 238: + case 218: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 207) { + if (node.kind === 208) { node = node.expression; } - else if (node.kind === 214 && node.operator === 53) { + else if (node.kind === 215 && node.operator === 53) { node = node.operand; } else { - return node.kind === 216 && (node.operatorToken.kind === 55 || + return node.kind === 217 && (node.operatorToken.kind === 55 || node.operatorToken.kind === 56 || node.operatorToken.kind === 60); } @@ -33478,7 +34467,7 @@ var ts; } function setContinueTarget(node, target) { var label = activeLabelList; - while (label && node.parent.kind === 245) { + while (label && node.parent.kind === 246) { label.continueTarget = target; label = label.next; node = node.parent; @@ -33529,12 +34518,12 @@ var ts; bind(node.expression); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 239) { + if (node.kind === 240) { bind(node.awaitModifier); } addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 250) { + if (node.initializer.kind !== 251) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -33556,7 +34545,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 242) { + if (node.kind === 243) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -33573,7 +34562,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 241 ? breakTarget : continueTarget; + var flowLabel = node.kind === 242 ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -33646,7 +34635,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 285; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 286; }); node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; if (!hasDefault) { addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); @@ -33689,9 +34678,9 @@ var ts; maybeBindExpressionFlowIfCall(node.expression); } function maybeBindExpressionFlowIfCall(node) { - if (node.kind === 203) { + if (node.kind === 204) { var call = node; - if (ts.isDottedName(call.expression) && call.expression.kind !== 105) { + if (call.expression.kind !== 105 && ts.isDottedName(call.expression)) { currentFlow = createFlowCall(currentFlow, call); } } @@ -33715,7 +34704,7 @@ var ts; currentFlow = finishFlowLabel(postStatementLabel); } function bindDestructuringTargetFlow(node) { - if (node.kind === 216 && node.operatorToken.kind === 62) { + if (node.kind === 217 && node.operatorToken.kind === 62) { bindAssignmentTargetFlow(node.left); } else { @@ -33726,10 +34715,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowMutation(16, currentFlow, node); } - else if (node.kind === 199) { + else if (node.kind === 200) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 220) { + if (e.kind === 221) { bindAssignmentTargetFlow(e.expression); } else { @@ -33737,16 +34726,16 @@ var ts; } } } - else if (node.kind === 200) { + else if (node.kind === 201) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 288) { + if (p.kind === 289) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 289) { + else if (p.kind === 290) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 290) { + else if (p.kind === 291) { bindAssignmentTargetFlow(p.expression); } } @@ -33811,108 +34800,97 @@ var ts; } bindAssignmentTargetFlow(node.left); } - function bindBinaryExpressionFlow(node) { - var workStacks = { - expr: [node], - state: [1], - inStrictMode: [undefined], - parent: [undefined], - }; - var stackIndex = 0; - while (stackIndex >= 0) { - node = workStacks.expr[stackIndex]; - switch (workStacks.state[stackIndex]) { - case 0: { - ts.setParent(node, parent); - var saveInStrictMode = inStrictMode; - bindWorker(node); - var saveParent = parent; - parent = node; - advanceState(1, saveInStrictMode, saveParent); - break; - } - case 1: { - var operator = node.operatorToken.kind; - if (operator === 55 || operator === 56 || operator === 60 || - ts.isLogicalOrCoalescingAssignmentOperator(operator)) { - if (isTopLevelLogicalExpression(node)) { - var postExpressionLabel = createBranchLabel(); - bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel); - currentFlow = finishFlowLabel(postExpressionLabel); - } - else { - bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget); - } - completeNode(); - } - else { - advanceState(2); - maybeBind(node.left); - } - break; + function createBindBinaryExpressionFlow() { + return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, undefined); + function onEnter(node, state) { + if (state) { + state.stackIndex++; + ts.setParent(node, parent); + var saveInStrictMode = inStrictMode; + bindWorker(node); + var saveParent = parent; + parent = node; + state.skip = false; + state.inStrictModeStack[state.stackIndex] = saveInStrictMode; + state.parentStack[state.stackIndex] = saveParent; + } + else { + state = { + stackIndex: 0, + skip: false, + inStrictModeStack: [undefined], + parentStack: [undefined] + }; + } + var operator = node.operatorToken.kind; + if (operator === 55 || + operator === 56 || + operator === 60 || + ts.isLogicalOrCoalescingAssignmentOperator(operator)) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); } - case 2: { - if (node.operatorToken.kind === 27) { - maybeBindExpressionFlowIfCall(node.left); - } - advanceState(3); - maybeBind(node.operatorToken); - break; + else { + bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget); } - case 3: { - advanceState(4); - maybeBind(node.right); - break; + state.skip = true; + } + return state; + } + function onLeft(left, state, _node) { + if (!state.skip) { + return maybeBind(left); + } + } + function onOperator(operatorToken, state, node) { + if (!state.skip) { + if (operatorToken.kind === 27) { + maybeBindExpressionFlowIfCall(node.left); } - case 4: { - var operator = node.operatorToken.kind; - if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { - bindAssignmentTargetFlow(node.left); - if (operator === 62 && node.left.kind === 202) { - var elementAccess = node.left; - if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowMutation(256, currentFlow, node); - } + bind(operatorToken); + } + } + function onRight(right, state, _node) { + if (!state.skip) { + return maybeBind(right); + } + } + function onExit(node, state) { + if (!state.skip) { + var operator = node.operatorToken.kind; + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 62 && node.left.kind === 203) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowMutation(256, currentFlow, node); } } - completeNode(); - break; } - default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for bindBinaryExpressionFlow"); - } - } - function advanceState(state, isInStrictMode, parent) { - workStacks.state[stackIndex] = state; - if (isInStrictMode !== undefined) { - workStacks.inStrictMode[stackIndex] = isInStrictMode; } - if (parent !== undefined) { - workStacks.parent[stackIndex] = parent; + var savedInStrictMode = state.inStrictModeStack[state.stackIndex]; + var savedParent = state.parentStack[state.stackIndex]; + if (savedInStrictMode !== undefined) { + inStrictMode = savedInStrictMode; } - } - function completeNode() { - if (workStacks.inStrictMode[stackIndex] !== undefined) { - inStrictMode = workStacks.inStrictMode[stackIndex]; - parent = workStacks.parent[stackIndex]; + if (savedParent !== undefined) { + parent = savedParent; } - stackIndex--; + state.skip = false; + state.stackIndex--; } function maybeBind(node) { if (node && ts.isBinaryExpression(node) && !ts.isDestructuringAssignment(node)) { - stackIndex++; - workStacks.expr[stackIndex] = node; - workStacks.state[stackIndex] = 0; - workStacks.inStrictMode[stackIndex] = undefined; - workStacks.parent[stackIndex] = undefined; - } - else { - bind(node); + return node; } + bind(node); } } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 201) { + if (node.expression.kind === 202) { bindAssignmentTargetFlow(node.expression); } } @@ -33964,7 +34942,7 @@ var ts; } function bindJSDocTypeAlias(node) { ts.setParent(node.tagName, node); - if (node.kind !== 325 && node.fullName) { + if (node.kind !== 329 && node.fullName) { ts.setParent(node.fullName, node); ts.setParentRecursive(node.fullName, false); } @@ -33972,7 +34950,7 @@ var ts; function bindJSDocClassTag(node) { bindEachChild(node); var host = ts.getHostSignatureFromJSDoc(node); - if (host && host.kind !== 165) { + if (host && host.kind !== 166) { addDeclarationToSymbol(host.symbol, host, 32); } } @@ -33985,15 +34963,15 @@ var ts; } function bindOptionalChainRest(node) { switch (node.kind) { - case 201: + case 202: bind(node.questionDotToken); bind(node.name); break; - case 202: + case 203: bind(node.questionDotToken); bind(node.argumentExpression); break; - case 203: + case 204: bind(node.questionDotToken); bindEach(node.typeArguments); bindEach(node.arguments); @@ -34044,7 +35022,7 @@ var ts; } else { var expr = ts.skipParentheses(node.expression); - if (expr.kind === 208 || expr.kind === 209) { + if (expr.kind === 209 || expr.kind === 210) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -34056,7 +35034,7 @@ var ts; } } } - if (node.expression.kind === 201) { + if (node.expression.kind === 202) { var propertyAccess = node.expression; if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowMutation(256, currentFlow, node); @@ -34065,53 +35043,53 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 221: - case 252: - case 255: - case 200: - case 177: - case 312: - case 281: - return 1; + case 222: case 253: - return 1 | 64; case 256: + case 201: + case 178: + case 314: + case 282: + return 1; case 254: - case 190: + return 1 | 64; + case 257: + case 255: + case 191: return 1 | 32; - case 297: + case 298: return 1 | 4 | 32; - case 165: + case 166: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { return 1 | 4 | 32 | 8 | 128; } - case 166: - case 251: - case 164: case 167: + case 252: + case 165: case 168: case 169: - case 313: - case 308: - case 174: case 170: - case 171: + case 315: + case 309: case 175: + case 171: + case 172: + case 176: return 1 | 4 | 32 | 8; - case 208: case 209: + case 210: return 1 | 4 | 32 | 8 | 16; - case 257: + case 258: return 4; - case 163: + case 164: return node.initializer ? 4 : 0; - case 287: - case 237: + case 288: case 238: case 239: - case 258: + case 240: + case 259: return 2; - case 230: + case 231: return ts.isFunctionLike(node.parent) ? 0 : 2; } return 0; @@ -34124,40 +35102,40 @@ var ts; } function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { switch (container.kind) { - case 256: + case 257: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 297: + case 298: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 221: - case 252: + case 222: + case 253: return declareClassMember(node, symbolFlags, symbolExcludes); - case 255: + case 256: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 177: - case 312: - case 200: - case 253: - case 281: + case 178: + case 314: + case 201: + case 254: + case 282: return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 174: case 175: - case 169: + case 176: case 170: - case 313: case 171: - case 165: - case 164: + case 315: + case 172: case 166: + case 165: case 167: case 168: - case 251: - case 208: + case 169: + case 252: case 209: - case 308: - case 331: - case 324: - case 254: - case 190: + case 210: + case 309: + case 335: + case 328: + case 255: + case 191: return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); } } @@ -34236,11 +35214,11 @@ var ts; var seen = new ts.Map(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 290 || prop.name.kind !== 78) { + if (prop.kind === 291 || prop.name.kind !== 78) { continue; } var identifier = prop.name; - var currentKind = prop.kind === 288 || prop.kind === 289 || prop.kind === 165 + var currentKind = prop.kind === 289 || prop.kind === 290 || prop.kind === 166 ? 1 : 2; var existingKind = seen.get(identifier.escapedText); @@ -34272,10 +35250,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 256: + case 257: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 297: + case 298: if (ts.isExternalOrCommonJsModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -34299,9 +35277,9 @@ var ts; var saveCurrentFlow = currentFlow; for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { var typeAlias = delayedTypeAliases_1[_i]; - var host = ts.getJSDocHost(typeAlias); - container = (host && ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1); })) || file; - blockScopeContainer = (host && ts.getEnclosingBlockScopeContainer(host)) || file; + var host = typeAlias.parent.parent; + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; currentFlow = initFlowNode({ flags: 2 }); parent = typeAlias; bind(typeAlias.typeExpression); @@ -34447,8 +35425,8 @@ var ts; } function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2) { - if (blockScopeContainer.kind !== 297 && - blockScopeContainer.kind !== 256 && + if (blockScopeContainer.kind !== 298 && + blockScopeContainer.kind !== 257 && !ts.isFunctionLike(blockScopeContainer)) { var errorSpan = ts.getErrorSpanForNode(file, node); file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); @@ -34510,7 +35488,7 @@ var ts; ts.setParent(node, parent); var saveInStrictMode = inStrictMode; bindWorker(node); - if (node.kind > 156) { + if (node.kind > 157) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -34578,17 +35556,23 @@ var ts; break; } case 107: - if (currentFlow && (ts.isExpression(node) || parent.kind === 289)) { + if (currentFlow && (ts.isExpression(node) || parent.kind === 290)) { node.flowNode = currentFlow; } return checkContextualIdentifier(node); + case 158: + if (currentFlow && parent.kind === 177) { + node.flowNode = currentFlow; + } + break; + case 227: case 105: node.flowNode = currentFlow; break; case 79: return checkPrivateIdentifier(node); - case 201: case 202: + case 203: var expr = node; if (currentFlow && isNarrowableReference(expr)) { expr.flowNode = currentFlow; @@ -34603,7 +35587,7 @@ var ts; declareSymbol(file.locals, undefined, expr.expression, 1 | 134217728, 111550); } break; - case 216: + case 217: var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1: @@ -34638,74 +35622,74 @@ var ts; ts.Debug.fail("Unknown binary expression special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 287: + case 288: return checkStrictModeCatchClause(node); - case 210: + case 211: return checkStrictModeDeleteExpression(node); case 8: return checkStrictModeNumericLiteral(node); - case 215: + case 216: return checkStrictModePostfixUnaryExpression(node); - case 214: + case 215: return checkStrictModePrefixUnaryExpression(node); - case 243: + case 244: return checkStrictModeWithStatement(node); - case 245: + case 246: return checkStrictModeLabeledStatement(node); - case 187: + case 188: seenThisKeyword = true; return; - case 172: + case 173: break; - case 159: - return bindTypeParameter(node); case 160: + return bindTypeParameter(node); + case 161: return bindParameter(node); - case 249: + case 250: return bindVariableDeclarationOrBindingElement(node); - case 198: + case 199: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); + case 164: case 163: - case 162: return bindPropertyWorker(node); - case 288: case 289: + case 290: return bindPropertyOrMethodOrAccessor(node, 4, 0); - case 291: + case 292: return bindPropertyOrMethodOrAccessor(node, 8, 900095); - case 169: case 170: case 171: + case 172: return declareSymbolAndAddToSymbolTable(node, 131072, 0); + case 166: case 165: - case 164: return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 103359); - case 251: + case 252: return bindFunctionDeclaration(node); - case 166: - return declareSymbolAndAddToSymbolTable(node, 16384, 0); case 167: - return bindPropertyOrMethodOrAccessor(node, 32768, 46015); + return declareSymbolAndAddToSymbolTable(node, 16384, 0); case 168: + return bindPropertyOrMethodOrAccessor(node, 32768, 46015); + case 169: return bindPropertyOrMethodOrAccessor(node, 65536, 78783); - case 174: - case 308: - case 313: case 175: + case 309: + case 315: + case 176: return bindFunctionOrConstructorType(node); - case 177: - case 312: - case 190: + case 178: + case 314: + case 191: return bindAnonymousTypeWorker(node); - case 319: + case 322: return bindJSDocClassTag(node); - case 200: + case 201: return bindObjectLiteralExpression(node); - case 208: case 209: + case 210: return bindFunctionExpression(node); - case 203: + case 204: var assignmentKind = ts.getAssignmentDeclarationKind(node); switch (assignmentKind) { case 7: @@ -34723,60 +35707,60 @@ var ts; bindCallExpression(node); } break; - case 221: - case 252: + case 222: + case 253: inStrictMode = true; return bindClassLikeDeclaration(node); - case 253: - return bindBlockScopedDeclaration(node, 64, 788872); case 254: - return bindBlockScopedDeclaration(node, 524288, 788968); + return bindBlockScopedDeclaration(node, 64, 788872); case 255: - return bindEnumDeclaration(node); + return bindBlockScopedDeclaration(node, 524288, 788968); case 256: + return bindEnumDeclaration(node); + case 257: return bindModuleDeclaration(node); - case 281: + case 282: return bindJsxAttributes(node); - case 280: + case 281: return bindJsxAttribute(node, 4, 0); - case 260: - case 263: - case 265: - case 270: + case 261: + case 264: + case 266: + case 271: return declareSymbolAndAddToSymbolTable(node, 2097152, 2097152); - case 259: + case 260: return bindNamespaceExportDeclaration(node); - case 262: + case 263: return bindImportClause(node); - case 267: + case 268: return bindExportDeclaration(node); - case 266: + case 267: return bindExportAssignment(node); - case 297: + case 298: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 230: + case 231: if (!ts.isFunctionLike(node.parent)) { return; } - case 257: + case 258: return updateStrictModeStatementList(node.statements); - case 326: - if (node.parent.kind === 313) { + case 330: + if (node.parent.kind === 315) { return bindParameter(node); } - if (node.parent.kind !== 312) { + if (node.parent.kind !== 314) { break; } - case 333: + case 337: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 307 ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 308 ? 4 | 16777216 : 4; return declareSymbolAndAddToSymbolTable(propTag, flags, 0); - case 331: - case 324: - case 325: + case 335: + case 328: + case 329: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } @@ -34803,7 +35787,7 @@ var ts; } function bindExportAssignment(node) { if (!container.symbol || !container.symbol.exports) { - bindAnonymousDeclaration(node, 2097152, getDeclarationName(node)); + bindAnonymousDeclaration(node, 111551, getDeclarationName(node)); } else { var flags = ts.exportAssignmentIsAlias(node) @@ -34920,8 +35904,8 @@ var ts; } var thisContainer = ts.getThisContainer(node, false); switch (thisContainer.kind) { - case 251: - case 208: + case 252: + case 209: var constructorSymbol = thisContainer.symbol; if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 62) { var l = thisContainer.parent.left; @@ -34940,11 +35924,11 @@ var ts; addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32); } break; - case 166: - case 163: - case 165: case 167: + case 164: + case 166: case 168: + case 169: var containingClass = thisContainer.parent; var symbolTable = ts.hasSyntacticModifier(thisContainer, 32) ? containingClass.symbol.exports : containingClass.symbol.members; if (ts.hasDynamicName(node)) { @@ -34954,7 +35938,7 @@ var ts; declareSymbol(symbolTable, containingClass.symbol, node, 4 | 67108864, 0, true); } break; - case 297: + case 298: if (ts.hasDynamicName(node)) { break; } @@ -34982,7 +35966,7 @@ var ts; if (node.expression.kind === 107) { bindThisPropertyAssignment(node); } - else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 297) { + else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 298) { if (ts.isPrototypeAccess(node.expression)) { bindPrototypePropertyAssignment(node, node.parent); } @@ -35013,7 +35997,7 @@ var ts; } function bindObjectDefinePropertyAssignment(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); - var isToplevel = node.parent.parent.kind === 297; + var isToplevel = node.parent.parent.kind === 298; namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, false, false); bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, false); } @@ -35107,8 +36091,8 @@ var ts; } function isTopLevelNamespaceAssignment(propertyAccess) { return ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 297 - : propertyAccess.parent.parent.kind === 297; + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 298 + : propertyAccess.parent.parent.kind === 298; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) { var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer); @@ -35174,7 +36158,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 252) { + if (node.kind === 253) { bindBlockScopedDeclaration(node, 32, 899503); } else { @@ -35206,7 +36190,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { - if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node, true) && !ts.getJSDocTypeTag(node)) { + if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node) && !ts.getJSDocTypeTag(node)) { declareSymbolAndAddToSymbolTable(node, 2097152, 2097152); } else if (ts.isBlockOrCatchScoped(node)) { @@ -35221,7 +36205,7 @@ var ts; } } function bindParameter(node) { - if (node.kind === 326 && container.kind !== 313) { + if (node.kind === 330 && container.kind !== 315) { return; } if (inStrictMode && !(node.flags & 8388608)) { @@ -35294,7 +36278,7 @@ var ts; declareSymbolAndAddToSymbolTable(node, 262144, 526824); } } - else if (node.parent.kind === 185) { + else if (node.parent.kind === 186) { var container_2 = getInferTypeContainer(node.parent); if (container_2) { if (!container_2.locals) { @@ -35312,16 +36296,16 @@ var ts; } function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); - return instanceState === 1 || (instanceState === 2 && !!options.preserveConstEnums); + return instanceState === 1 || (instanceState === 2 && ts.shouldPreserveConstEnums(options)); } function checkUnreachable(node) { if (!(currentFlow.flags & 1)) { return false; } if (currentFlow === unreachableFlow) { - var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 231) || - node.kind === 252 || - (node.kind === 256 && shouldReportErrorOnModuleDeclaration(node)); + var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 232) || + node.kind === 253 || + (node.kind === 257 && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -35353,12 +36337,12 @@ var ts; } function isPurelyTypeDeclaration(s) { switch (s.kind) { - case 253: case 254: + case 255: return true; - case 256: + case 257: return getModuleInstanceState(s) !== 1; - case 255: + case 256: return ts.hasSyntacticModifier(s, 2048); default: return false; @@ -35549,7 +36533,7 @@ var ts; symbol.exports.forEach(visitSymbol); } ts.forEach(symbol.declarations, function (d) { - if (d.type && d.type.kind === 176) { + if (d.type && d.type.kind === 177) { var query = d.type; var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); visitSymbol(entity); @@ -35649,12 +36633,12 @@ var ts; var instantiationCount = 0; var instantiationDepth = 0; var currentNode; - var typeCatalog = []; var emptySymbols = ts.createSymbolTable(); var arrayVariances = [1]; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); @@ -35663,7 +36647,8 @@ var ts; var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16384; + var checkBinaryExpression = createCheckBinaryExpression(); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); var globals = ts.createSymbolTable(); @@ -35680,7 +36665,6 @@ var ts; getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, - getTypeCatalog: function () { return typeCatalog; }, getTypeCount: function () { return typeCount; }, getInstantiationCount: function () { return totalInstantiationCount; }, getRelationCacheSizes: function () { return ({ @@ -35843,6 +36827,7 @@ var ts; return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, + getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: function (node, candidatesOutArray, argumentCount) { return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0); @@ -35886,6 +36871,7 @@ var ts; }, tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); }, + tryFindAmbientModule: function (moduleName) { return tryFindAmbientModule(moduleName, true); }, tryFindAmbientModuleWithoutAugmentations: function (moduleName) { return tryFindAmbientModule(moduleName, false); }, @@ -35998,6 +36984,7 @@ var ts; var templateLiteralTypes = new ts.Map(); var stringMappingTypes = new ts.Map(); var substitutionTypes = new ts.Map(); + var subtypeReductionCache = new ts.Map(); var evolvingArrayTypes = []; var undefinedProperties = new ts.Map(); var unknownSymbol = createSymbol(4, "unknown"); @@ -36006,14 +36993,14 @@ var ts; var autoType = createIntrinsicType(1, "any"); var wildcardType = createIntrinsicType(1, "any"); var errorType = createIntrinsicType(1, "error"); - var nonInferrableAnyType = createIntrinsicType(1, "any", 524288); + var nonInferrableAnyType = createIntrinsicType(1, "any", 131072); var intrinsicMarkerType = createIntrinsicType(1, "intrinsic"); var unknownType = createIntrinsicType(2, "unknown"); var undefinedType = createIntrinsicType(32768, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768, "undefined", 524288); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768, "undefined", 131072); var optionalType = createIntrinsicType(32768, "undefined"); var nullType = createIntrinsicType(65536, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536, "null", 524288); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536, "null", 131072); var stringType = createIntrinsicType(4, "string"); var numberType = createIntrinsicType(8, "number"); var bigintType = createIntrinsicType(64, "bigint"); @@ -36037,7 +37024,7 @@ var ts; var voidType = createIntrinsicType(16384, "void"); var neverType = createIntrinsicType(131072, "never"); var silentNeverType = createIntrinsicType(131072, "never"); - var nonInferrableType = createIntrinsicType(131072, "never", 2097152); + var nonInferrableType = createIntrinsicType(131072, "never", 524288); var implicitNeverType = createIntrinsicType(131072, "never"); var unreachableNeverType = createIntrinsicType(131072, "never"); var nonPrimitiveType = createIntrinsicType(67108864, "object"); @@ -36049,14 +37036,14 @@ var ts; var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 ? wildcardType : t; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - emptyJsxObjectType.objectFlags |= 4096; + emptyJsxObjectType.objectFlags |= 2048; var emptyTypeLiteralSymbol = createSymbol(2048, "__type"); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); emptyGenericType.instantiations = new ts.Map(); var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - anyFunctionType.objectFlags |= 2097152; + anyFunctionType.objectFlags |= 524288; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -36127,6 +37114,7 @@ var ts; var anyReadonlyArrayType; var deferredGlobalNonNullableTypeAlias; var deferredGlobalESSymbolConstructorSymbol; + var deferredGlobalESSymbolConstructorTypeSymbol; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; @@ -36178,7 +37166,7 @@ var ts; var flowNodePostSuper = []; var potentialThisCollisions = []; var potentialNewTargetCollisions = []; - var potentialWeakMapCollisions = []; + var potentialWeakMapSetCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); var suggestionDiagnostics = ts.createDiagnosticCollection(); @@ -36321,6 +37309,24 @@ var ts; } return diagnostic; } + function addDeprecatedSuggestionWorker(declarations, diagnostic) { + var deprecatedTag = Array.isArray(declarations) ? ts.forEach(declarations, ts.getJSDocDeprecatedTag) : ts.getJSDocDeprecatedTag(declarations); + if (deprecatedTag) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(deprecatedTag, ts.Diagnostics.The_declaration_was_marked_as_deprecated_here)); + } + suggestionDiagnostics.add(diagnostic); + return diagnostic; + } + function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { + var diagnostic = ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, deprecatedEntity); + return addDeprecatedSuggestionWorker(declarations, diagnostic); + } + function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) { + var diagnostic = deprecatedEntity + ? ts.createDiagnosticForNode(location, ts.Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity) + : ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, signatureString); + return addDeprecatedSuggestionWorker(declaration, diagnostic); + } function createSymbol(flags, name, checkFlags) { symbolCount++; var symbol = (new Symbol(flags | 33554432, name)); @@ -36423,7 +37429,7 @@ var ts; } else if (target.flags & 1024) { if (target !== globalThisSymbol) { - error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(source.declarations && ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } } else { @@ -36456,9 +37462,11 @@ var ts; } return target; function addDuplicateLocations(locs, symbol) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - ts.pushIfUnique(locs, decl); + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, decl); + } } } } @@ -36504,9 +37512,9 @@ var ts; }); } function mergeModuleAugmentation(moduleName) { - var _a, _b; + var _a, _b, _c; var moduleAugmentation = moduleName.parent; - if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + if (((_a = moduleAugmentation.symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]) !== moduleAugmentation) { ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); return; } @@ -36531,10 +37539,10 @@ var ts; patternAmbientModuleAugmentations.set(moduleName.text, merged); } else { - if (((_a = mainModule_1.exports) === null || _a === void 0 ? void 0 : _a.get("__export")) && ((_b = moduleAugmentation.symbol.exports) === null || _b === void 0 ? void 0 : _b.size)) { + if (((_b = mainModule_1.exports) === null || _b === void 0 ? void 0 : _b.get("__export")) && ((_c = moduleAugmentation.symbol.exports) === null || _c === void 0 ? void 0 : _c.size)) { var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports"); - for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) { - var _d = _c[_i], key = _d[0], value = _d[1]; + for (var _i = 0, _d = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _d.length; _i++) { + var _e = _d[_i], key = _e[0], value = _e[1]; if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) { mergeSymbol(resolvedExports.get(key), value); } @@ -36573,7 +37581,7 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks()); } function isGlobalSourceFile(node) { - return node.kind === 297 && !ts.isExternalOrCommonJsModule(node); + return node.kind === 298 && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -36620,15 +37628,15 @@ var ts; return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) { - if (declaration.kind === 198) { - var errorBindingElement = ts.getAncestor(usage, 198); + if (declaration.kind === 199) { + var errorBindingElement = ts.getAncestor(usage, 199); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 249), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 250), usage); } - else if (declaration.kind === 249) { + else if (declaration.kind === 250) { return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } else if (ts.isClassDeclaration(declaration)) { @@ -36638,23 +37646,23 @@ var ts; return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, false); } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { - return !(compilerOptions.target === 99 && !!compilerOptions.useDefineForClassFields + return !(compilerOptions.target === 99 && useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); } return true; } - if (usage.parent.kind === 270 || (usage.parent.kind === 266 && usage.parent.isExportEquals)) { + if (usage.parent.kind === 271 || (usage.parent.kind === 267 && usage.parent.isExportEquals)) { return true; } - if (usage.kind === 266 && usage.isExportEquals) { + if (usage.kind === 267 && usage.isExportEquals) { return true; } if (!!(usage.flags & 4194304) || isInTypeQuery(usage) || usageInTypeDeclaration()) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (compilerOptions.target === 99 && !!compilerOptions.useDefineForClassFields + if (compilerOptions.target === 99 && useDefineForClassFields && ts.getContainingClass(declaration) && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, true); @@ -36669,9 +37677,9 @@ var ts; } function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { switch (declaration.parent.parent.kind) { - case 232: - case 237: - case 239: + case 233: + case 238: + case 240: if (isSameScopeDescendentOf(usage, declaration, declContainer)) { return true; } @@ -36689,16 +37697,16 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 163 && + current.parent.kind === 164 && current.parent.initializer === current; if (initializerOfProperty) { if (ts.hasSyntacticModifier(current.parent, 32)) { - if (declaration.kind === 165) { + if (declaration.kind === 166) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 163 && !ts.hasSyntacticModifier(declaration, 32); + var isDeclarationInstanceProperty = declaration.kind === 164 && !ts.hasSyntacticModifier(declaration, 32); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -36716,18 +37724,18 @@ var ts; return "quit"; } switch (node.kind) { - case 209: + case 210: return true; - case 163: + case 164: return stopAtAnyPropertyDeclaration && (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent) ? "quit" : true; - case 230: + case 231: switch (node.parent.kind) { - case 167: - case 165: case 168: + case 166: + case 169: return true; default: return false; @@ -36742,7 +37750,11 @@ var ts; function useOuterVariableScopeInParameter(result, location, lastLocation) { var target = ts.getEmitScriptTarget(compilerOptions); var functionLocation = location; - if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + if (ts.isParameter(lastLocation) + && functionLocation.body + && result.valueDeclaration + && result.valueDeclaration.pos >= functionLocation.body.pos + && result.valueDeclaration.end <= functionLocation.body.end) { if (target >= 2) { var links = getNodeLinks(functionLocation); if (links.declarationRequiresScopeChange === undefined) { @@ -36758,19 +37770,19 @@ var ts; } function requiresScopeChangeWorker(node) { switch (node.kind) { + case 210: case 209: - case 208: - case 251: - case 166: - return false; - case 165: + case 252: case 167: + return false; + case 166: case 168: - case 288: + case 169: + case 289: return requiresScopeChangeWorker(node.name); - case 163: + case 164: if (ts.hasStaticModifier(node)) { - return target < 99 || !compilerOptions.useDefineForClassFields; + return target < 99 || !useDefineForClassFields; } return requiresScopeChangeWorker(node.name); default: @@ -36791,6 +37803,7 @@ var ts; return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); } function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { + var _a; var originalLocation = location; var result; var lastLocation; @@ -36806,11 +37819,11 @@ var ts; if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 788968 && lastLocation.kind !== 311) { + if (meaning & result.flags & 788968 && lastLocation.kind !== 312) { useResult = result.flags & 262144 ? lastLocation === location.type || - lastLocation.kind === 160 || - lastLocation.kind === 159 + lastLocation.kind === 161 || + lastLocation.kind === 160 : false; } if (meaning & result.flags & 3) { @@ -36819,13 +37832,13 @@ var ts; } else if (result.flags & 1) { useResult = - lastLocation.kind === 160 || + lastLocation.kind === 161 || (lastLocation === location.type && !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); } } } - else if (location.kind === 184) { + else if (location.kind === 185) { useResult = lastLocation === location.trueType; } if (useResult) { @@ -36838,13 +37851,13 @@ var ts; } withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation); switch (location.kind) { - case 297: + case 298: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; - case 256: + case 257: var moduleExports = getSymbolOfNode(location).exports || emptySymbols; - if (location.kind === 297 || (ts.isModuleDeclaration(location) && location.flags & 8388608 && !ts.isGlobalScopeAugmentation(location))) { + if (location.kind === 298 || (ts.isModuleDeclaration(location) && location.flags & 8388608 && !ts.isGlobalScopeAugmentation(location))) { if (result = moduleExports.get("default")) { var localSymbol = ts.getLocalSymbolForExportDefault(result); if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { @@ -36855,12 +37868,12 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 && - (ts.getDeclarationOfKind(moduleExport, 270) || ts.getDeclarationOfKind(moduleExport, 269))) { + (ts.getDeclarationOfKind(moduleExport, 271) || ts.getDeclarationOfKind(moduleExport, 270))) { break; } } if (name !== "default" && (result = lookup(moduleExports, name, meaning & 2623475))) { - if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !((_a = result.declarations) === null || _a === void 0 ? void 0 : _a.some(ts.isJSDocTypeAlias))) { result = undefined; } else { @@ -36868,12 +37881,12 @@ var ts; } } break; - case 255: + case 256: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { break loop; } break; - case 163: + case 164: if (!ts.hasSyntacticModifier(location, 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { @@ -36883,9 +37896,9 @@ var ts; } } break; - case 252: - case 221: case 253: + case 222: + case 254: if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 788968)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = undefined; @@ -36897,7 +37910,7 @@ var ts; } break loop; } - if (location.kind === 221 && meaning & 32) { + if (location.kind === 222 && meaning & 32) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -36905,7 +37918,7 @@ var ts; } } break; - case 223: + case 224: if (lastLocation === location.expression && location.parent.token === 93) { var container = location.parent.parent; if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 788968))) { @@ -36916,30 +37929,30 @@ var ts; } } break; - case 158: + case 159: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 253) { + if (ts.isClassLike(grandparent) || grandparent.kind === 254) { if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } } break; - case 209: + case 210: if (compilerOptions.target >= 2) { break; } - case 165: case 166: case 167: case 168: - case 251: + case 169: + case 252: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 208: + case 209: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; @@ -36952,23 +37965,23 @@ var ts; } } break; - case 161: - if (location.parent && location.parent.kind === 160) { + case 162: + if (location.parent && location.parent.kind === 161) { location = location.parent; } - if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 252)) { + if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 253)) { location = location.parent; } break; - case 331: - case 324: - case 325: + case 335: + case 328: + case 329: var root = ts.getJSDocRoot(location); if (root) { location = root.parent; } break; - case 160: + case 161: if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && ts.isBindingPattern(lastLocation))) { if (!associatedDeclarationForContainingInitializerOrBindingName) { @@ -36976,7 +37989,7 @@ var ts; } } break; - case 198: + case 199: if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && ts.isBindingPattern(lastLocation))) { if (ts.isParameterDeclaration(location) && !associatedDeclarationForContainingInitializerOrBindingName) { @@ -36984,7 +37997,7 @@ var ts; } } break; - case 185: + case 186: if (meaning & 262144) { var parameterName = location.typeParameter.name; if (parameterName && name === parameterName.escapedText) { @@ -37005,7 +38018,7 @@ var ts; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 297); + ts.Debug.assert(lastLocation.kind === 298); if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } @@ -37034,6 +38047,10 @@ var ts; var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + var isGlobalScopeAugmentationDeclaration = suggestion && suggestion.valueDeclaration && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); + if (isGlobalScopeAugmentationDeclaration) { + suggestion = undefined; + } if (suggestion) { var suggestionName = symbolToString(suggestion); var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); @@ -37059,7 +38076,7 @@ var ts; return undefined; } if (nameNotFoundMessage) { - if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 && compilerOptions.useDefineForClassFields)) { + if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 && useDefineForClassFields)) { var propertyName = propertyWithInvalidInitializer.name; error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); return undefined; @@ -37111,9 +38128,9 @@ var ts; } } function getIsDeferredContext(location, lastLocation) { - if (location.kind !== 209 && location.kind !== 208) { + if (location.kind !== 210 && location.kind !== 209) { return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) || - (location.kind === 163 && !ts.hasSyntacticModifier(location, 32))) && (!lastLocation || lastLocation !== location.name)); + (location.kind === 164 && !ts.hasSyntacticModifier(location, 32))) && (!lastLocation || lastLocation !== location.name)); } if (lastLocation && lastLocation === location.name) { return false; @@ -37125,12 +38142,12 @@ var ts; } function isSelfReferenceLocation(node) { switch (node.kind) { - case 251: case 252: case 253: - case 255: case 254: case 256: + case 255: + case 257: return true; default: return false; @@ -37140,12 +38157,14 @@ var ts; return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } function isTypeParameterSymbolDeclaredInContainer(symbol, container) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (decl.kind === 159) { - var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; - if (parent === container) { - return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.kind === 160) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); + } } } } @@ -37191,9 +38210,9 @@ var ts; function getEntityNameForExtendingInterface(node) { switch (node.kind) { case 78: - case 201: + case 202: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 223: + case 224: if (ts.isEntityNameExpression(node.expression)) { return node.expression; } @@ -37236,7 +38255,7 @@ var ts; return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown"; } function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) { - if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 270) { + if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 271) { error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name); return true; } @@ -37305,11 +38324,12 @@ var ts; return false; } function checkResolvedBlockScopedVariable(result, errorLocation) { + var _a; ts.Debug.assert(!!(result.flags & 2 || result.flags & 32 || result.flags & 384)); if (result.flags & (16 | 1 | 67108864) && result.flags & 32) { return; } - var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 255); }); + var declaration = (_a = result.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 256); }); if (declaration === undefined) return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration"); if (!(declaration.flags & 8388608) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -37326,7 +38346,7 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128)); - if (compilerOptions.preserveConstEnums) { + if (ts.shouldPreserveConstEnums(compilerOptions)) { diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); } } @@ -37340,39 +38360,39 @@ var ts; } function getAnyImportSyntax(node) { switch (node.kind) { - case 260: + case 261: return node; - case 262: - return node.parent; case 263: + return node.parent; + case 264: return node.parent.parent; - case 265: + case 266: return node.parent.parent.parent; default: return undefined; } } function getDeclarationOfAliasSymbol(symbol) { - return ts.find(symbol.declarations, isAliasSymbolDeclaration); + return symbol.declarations && ts.findLast(symbol.declarations, isAliasSymbolDeclaration); } function isAliasSymbolDeclaration(node) { - return node.kind === 260 - || node.kind === 259 - || node.kind === 262 && !!node.name - || node.kind === 263 - || node.kind === 269 - || node.kind === 265 + return node.kind === 261 + || node.kind === 260 + || node.kind === 263 && !!node.name + || node.kind === 264 || node.kind === 270 - || node.kind === 266 && ts.exportAssignmentIsAlias(node) + || node.kind === 266 + || node.kind === 271 + || node.kind === 267 && ts.exportAssignmentIsAlias(node) || ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 && ts.exportAssignmentIsAlias(node) || ts.isAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 && isAliasableOrJsExpression(node.parent.right) - || node.kind === 289 - || node.kind === 288 && isAliasableOrJsExpression(node.initializer) - || ts.isRequireVariableDeclaration(node, true); + || node.kind === 290 + || node.kind === 289 && isAliasableOrJsExpression(node.initializer) + || ts.isRequireVariableDeclaration(node); } function isAliasableOrJsExpression(e) { return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e); @@ -37385,7 +38405,7 @@ var ts; ? resolveSymbol(getPropertyOfType(resolveExternalModuleTypeByLiteral(name), commonJSPropertyAccess.name.escapedText)) : undefined; } - if (ts.isVariableDeclaration(node) || node.moduleReference.kind === 272) { + if (ts.isVariableDeclaration(node) || node.moduleReference.kind === 273) { var immediate = resolveExternalModuleName(node, ts.getExternalModuleRequireArgument(node) || ts.getExternalModuleImportEqualsDeclarationExpression(node)); var resolved_4 = resolveExternalModuleSymbol(immediate); markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, false); @@ -37439,6 +38459,7 @@ var ts; return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), undefined, dontResolveAlias); } function getTargetOfImportClause(node, dontResolveAlias) { + var _a; var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { var exportDefaultSymbol = void 0; @@ -37448,7 +38469,7 @@ var ts; else { exportDefaultSymbol = resolveExportByName(moduleSymbol, "default", node, dontResolveAlias); } - var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); if (!exportDefaultSymbol && !hasSyntheticDefault) { if (hasExportAssignmentSymbol(moduleSymbol)) { @@ -37456,7 +38477,9 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); var exportAssignment = exportEqualsSymbol.valueDeclaration; var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName); - ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); + if (exportAssignment) { + ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); + } } else { reportNonDefaultExport(moduleSymbol, node); @@ -37472,7 +38495,7 @@ var ts; } } function reportNonDefaultExport(moduleSymbol, node) { - var _a, _b; + var _a, _b, _c; if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); } @@ -37480,7 +38503,7 @@ var ts; var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export"); if (exportStar) { - var defaultExport = ts.find(exportStar.declarations, function (decl) { + var defaultExport = (_c = exportStar.declarations) === null || _c === void 0 ? void 0 : _c.find(function (decl) { var _a, _b; return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier && ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default"))); @@ -37540,7 +38563,7 @@ var ts; } } function getExternalModuleMember(node, specifier, dontResolveAlias) { - var _a; + var _a, _b; if (dontResolveAlias === void 0) { dontResolveAlias = false; } var moduleSpecifier = ts.getExternalModuleRequireArgument(node) || node.moduleSpecifier; var moduleSymbol = resolveExternalModuleName(node, moduleSpecifier); @@ -37549,7 +38572,7 @@ var ts; return undefined; } var suppressInteropError = name.escapedText === "default" && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop); - var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, dontResolveAlias, suppressInteropError); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, false, suppressInteropError); if (targetSymbol) { if (name.escapedText) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { @@ -37565,7 +38588,7 @@ var ts; symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); var symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias); if (symbolFromModule === undefined && name.escapedText === "default") { - var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } @@ -37585,7 +38608,7 @@ var ts; } } else { - if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default")) { + if ((_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.has("default")) { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); } else { @@ -37598,8 +38621,8 @@ var ts; } } function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) { - var _a; - var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText); + var _a, _b; + var localSymbol = (_b = (_a = moduleSymbol.valueDeclaration) === null || _a === void 0 ? void 0 : _a.locals) === null || _b === void 0 ? void 0 : _b.get(name.escapedText); var exports = moduleSymbol.exports; if (localSymbol) { var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export="); @@ -37611,9 +38634,11 @@ var ts; var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined; var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); - ts.addRelatedInfo.apply(void 0, __spreadArray([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { - return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); - }))); + if (localSymbol.declarations) { + ts.addRelatedInfo.apply(void 0, __spreadArray([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { + return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); + }))); + } } } else { @@ -37700,31 +38725,31 @@ var ts; function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { - case 260: - case 249: + case 261: + case 250: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 262: - return getTargetOfImportClause(node, dontRecursivelyResolve); case 263: + return getTargetOfImportClause(node, dontRecursivelyResolve); + case 264: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 269: + case 270: return getTargetOfNamespaceExport(node, dontRecursivelyResolve); - case 265: - case 198: + case 266: + case 199: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 270: + case 271: return getTargetOfExportSpecifier(node, 111551 | 788968 | 1920, dontRecursivelyResolve); - case 266: - case 216: + case 267: + case 217: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 259: + case 260: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); - case 289: + case 290: return resolveEntityName(node.name, 111551 | 788968 | 1920, true, dontRecursivelyResolve); - case 288: + case 289: return getTargetOfPropertyAssignment(node, dontRecursivelyResolve); + case 203: case 202: - case 201: return getTargetOfAccessExpression(node, dontRecursivelyResolve); default: return ts.Debug.fail(); @@ -37832,11 +38857,11 @@ var ts; if (entityName.kind === 78 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } - if (entityName.kind === 78 || entityName.parent.kind === 157) { + if (entityName.kind === 78 || entityName.parent.kind === 158) { return resolveEntityName(entityName, 1920, false, dontResolveAlias); } else { - ts.Debug.assert(entityName.parent.kind === 260); + ts.Debug.assert(entityName.parent.kind === 261); return resolveEntityName(entityName, 111551 | 788968 | 1920, false, dontResolveAlias); } } @@ -37857,9 +38882,9 @@ var ts; return getMergedSymbol(symbolFromJSPrototype); } } - else if (name.kind === 157 || name.kind === 201) { - var left = name.kind === 157 ? name.left : name.expression; - var right = name.kind === 157 ? name.right : name.name; + else if (name.kind === 158 || name.kind === 202) { + var left = name.kind === 158 ? name.left : name.expression; + var right = name.kind === 158 ? name.right : name.name; var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -37867,18 +38892,17 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJSFile(name)) { - if (namespace.valueDeclaration && - ts.isVariableDeclaration(namespace.valueDeclaration) && - namespace.valueDeclaration.initializer && - isCommonJsRequire(namespace.valueDeclaration.initializer)) { - var moduleName = namespace.valueDeclaration.initializer.arguments[0]; - var moduleSym = resolveExternalModuleName(moduleName, moduleName); - if (moduleSym) { - var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); - if (resolvedModuleSymbol) { - namespace = resolvedModuleSymbol; - } + if (namespace.valueDeclaration && + ts.isInJSFile(namespace.valueDeclaration) && + ts.isVariableDeclaration(namespace.valueDeclaration) && + namespace.valueDeclaration.initializer && + isCommonJsRequire(namespace.valueDeclaration.initializer)) { + var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + var moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; } } } @@ -37899,7 +38923,7 @@ var ts; throw ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); - if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 || name.parent.kind === 266)) { + if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 || name.parent.kind === 267)) { markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, undefined, true); } return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); @@ -38104,7 +39128,7 @@ var ts; function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { - if (!suppressInteropError && !(symbol.flags & (1536 | 3)) && !ts.getDeclarationOfKind(symbol, 297)) { + if (!suppressInteropError && !(symbol.flags & (1536 | 3)) && !ts.getDeclarationOfKind(symbol, 298)) { var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop"; @@ -38154,7 +39178,10 @@ var ts; var exports = getExportsOfModuleAsArray(moduleSymbol); var exportEquals = resolveExternalModuleSymbol(moduleSymbol); if (exportEquals !== moduleSymbol) { - ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); + var type = getTypeOfSymbol(exportEquals); + if (shouldTreatPropertiesOfExternalModuleAsExports(type)) { + ts.addRange(exports, getPropertiesOfType(type)); + } } return exports; } @@ -38174,11 +39201,13 @@ var ts; return undefined; } var type = getTypeOfSymbol(exportEquals); - return type.flags & 131068 || - ts.getObjectFlags(type) & 1 || - isArrayOrTupleLikeType(type) - ? undefined - : getPropertyOfType(type, memberName); + return shouldTreatPropertiesOfExternalModuleAsExports(type) ? getPropertyOfType(type, memberName) : undefined; + } + function shouldTreatPropertiesOfExternalModuleAsExports(resolvedExternalModuleType) { + return !(resolvedExternalModuleType.flags & 131068 || + ts.getObjectFlags(resolvedExternalModuleType) & 1 || + isArrayType(resolvedExternalModuleType) || + isTupleType(resolvedExternalModuleType)); } function getExportsOfSymbol(symbol) { return symbol.flags & 6256 ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports") : @@ -38228,11 +39257,13 @@ var ts; if (exportStars) { var nestedSymbols = ts.createSymbolTable(); var lookupTable_1 = new ts.Map(); - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - var exportedSymbols = visit(resolvedModule); - extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + if (exportStars.declarations) { + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + } } lookupTable_1.forEach(function (_a, id) { var exportsWithDuplicate = _a.exportsWithDuplicate; @@ -38307,11 +39338,26 @@ var ts; var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); var objectLiteralContainer = getVariableDeclarationOfObjectLiteral(container, meaning); - if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920, false)) { + if (enclosingDeclaration && + container.flags & getQualifiedLeftMeaning(meaning) && + getAccessibleSymbolChain(container, enclosingDeclaration, 1920, false)) { return ts.append(ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers), objectLiteralContainer); } - var res = ts.append(ts.append(additionalContainers, container), objectLiteralContainer); - return ts.concatenate(res, reexportContainers); + var firstVariableMatch = !(container.flags & getQualifiedLeftMeaning(meaning)) + && container.flags & 788968 + && getDeclaredTypeOfSymbol(container).flags & 524288 + && meaning === 111551 + ? forEachSymbolTableInScope(enclosingDeclaration, function (t) { + return ts.forEachEntry(t, function (s) { + if (s.flags & getQualifiedLeftMeaning(meaning) && getTypeOfSymbol(s) === getDeclaredTypeOfSymbol(container)) { + return s; + } + }); + }) : undefined; + var res = firstVariableMatch ? __spreadArray(__spreadArray([firstVariableMatch], additionalContainers), [container]) : __spreadArray(__spreadArray([], additionalContainers), [container]); + res = ts.append(res, objectLiteralContainer); + res = ts.addRange(res, reexportContainers); + return res; } var candidates = ts.mapDefined(symbol.declarations, function (d) { if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) { @@ -38380,7 +39426,7 @@ var ts; var members = node.members; for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { var member = members_3[_i]; - if (member.kind === 166 && ts.nodeIsPresent(member.body)) { + if (member.kind === 167 && ts.nodeIsPresent(member.body)) { return member; } } @@ -38389,7 +39435,9 @@ var ts; var result = new Type(checker, flags); typeCount++; result.id = typeCount; - typeCatalog.push(result); + if (produceDiagnostics) { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.recordType(result); + } return result; } function createOriginType(flags) { @@ -38445,14 +39493,22 @@ var ts; }); return result || ts.emptyArray; } + function getNamedOrIndexSignatureMembers(members) { + var result = getNamedMembers(members); + var index = getIndexSymbolFromSymbolTable(members); + return index ? ts.concatenate(result, [index]) : result; + } function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - type.members = members; - type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members); - type.callSignatures = callSignatures; - type.constructSignatures = constructSignatures; - type.stringIndexInfo = stringIndexInfo; - type.numberIndexInfo = numberIndexInfo; - return type; + var resolved = type; + resolved.members = members; + resolved.properties = ts.emptyArray; + resolved.callSignatures = callSignatures; + resolved.constructSignatures = constructSignatures; + resolved.stringIndexInfo = stringIndexInfo; + resolved.numberIndexInfo = numberIndexInfo; + if (members !== emptySymbols) + resolved.properties = getNamedMembers(members); + return resolved; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { return setStructuredTypeMembers(createObjectType(16, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); @@ -38474,24 +39530,24 @@ var ts; var result; var _loop_8 = function (location) { if (location.locals && !isGlobalSourceFile(location)) { - if (result = callback(location.locals)) { + if (result = callback(location.locals, undefined, true)) { return { value: result }; } } switch (location.kind) { - case 297: + case 298: if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 256: + case 257: var sym = getSymbolOfNode(location); - if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) { + if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols, undefined, true)) { return { value: result }; } break; - case 252: - case 221: case 253: + case 222: + case 254: var table_1; (getSymbolOfNode(location).members || emptySymbols).forEach(function (memberSymbol, key) { if (memberSymbol.flags & (788968 & ~67108864)) { @@ -38509,7 +39565,7 @@ var ts; if (typeof state_2 === "object") return state_2.value; } - return callback(globals); + return callback(globals, undefined, true); } function getQualifiedLeftMeaning(rightMeaning) { return rightMeaning === 111551 ? 111551 : 1920; @@ -38525,11 +39581,11 @@ var ts; visitedSymbolTablesMap.set(id, visitedSymbolTables = []); } return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); - function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification, isLocalNameLookup) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - var result = trySymbolTable(symbols, ignoreQualification); + var result = trySymbolTable(symbols, ignoreQualification, isLocalNameLookup); visitedSymbolTables.pop(); return result; } @@ -38542,7 +39598,7 @@ var ts; !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning)); } - function trySymbolTable(symbols, ignoreQualification) { + function trySymbolTable(symbols, ignoreQualification, isLocalNameLookup) { if (isAccessible(symbols.get(symbol.escapedName), undefined, ignoreQualification)) { return [symbol]; } @@ -38552,7 +39608,8 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) - && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 270))) { + && (isLocalNameLookup ? !ts.some(symbolFromSymbolTable.declarations, ts.isNamespaceReexportDeclaration) : true) + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 271))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification); if (candidate) { @@ -38588,7 +39645,7 @@ var ts; if (symbolFromSymbolTable === symbol) { return true; } - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 270)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 271)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -38602,10 +39659,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 163: - case 165: - case 167: + case 164: + case 166: case 168: + case 169: continue; default: return false; @@ -38642,7 +39699,7 @@ var ts; return hasAccessibleDeclarations; } } - else if (allowModules) { + if (allowModules) { if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { if (shouldComputeAliasesToMakeVisible) { earlyModuleBail = true; @@ -38688,7 +39745,8 @@ var ts; return { accessibility: 2, errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), - errorModuleName: symbolToString(symbolExternalModule) + errorModuleName: symbolToString(symbolExternalModule), + errorNode: ts.isInJSFile(enclosingDeclaration) ? enclosingDeclaration : undefined, }; } } @@ -38704,10 +39762,10 @@ var ts; return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 297 && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 298 && ts.isExternalOrCommonJsModule(declaration)); } function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { - return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 297 && ts.isExternalOrCommonJsModule(declaration)); + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 298 && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -38756,13 +39814,13 @@ var ts; } function isEntityNameVisible(entityName, enclosingDeclaration) { var meaning; - if (entityName.parent.kind === 176 || + if (entityName.parent.kind === 177 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || - entityName.parent.kind === 158) { + entityName.parent.kind === 159) { meaning = 111551 | 1048576; } - else if (entityName.kind === 157 || entityName.kind === 201 || - entityName.parent.kind === 260) { + else if (entityName.kind === 158 || entityName.kind === 202 || + entityName.parent.kind === 261) { meaning = 1920; } else { @@ -38798,7 +39856,7 @@ var ts; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); - var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 297 ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true }); + var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 298 ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4, entity, sourceFile, writer); return writer; @@ -38810,10 +39868,10 @@ var ts; function signatureToStringWorker(writer) { var sigOutput; if (flags & 262144) { - sigOutput = kind === 1 ? 175 : 174; + sigOutput = kind === 1 ? 176 : 175; } else { - sigOutput = kind === 1 ? 170 : 169; + sigOutput = kind === 1 ? 171 : 170; } var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 | 512); var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); @@ -38853,14 +39911,14 @@ var ts; return typeToString(type, undefined, 64); } function symbolValueDeclarationIsContextSensitive(symbol) { - return symbol && symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration); + return symbol && !!symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration); } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0; } return flags & 814775659; } function isClassInstanceSide(type) { - return !!type.symbol && !!(type.symbol.flags & 32) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(ts.getObjectFlags(type) & 1073741824)); + return !!type.symbol && !!(type.symbol.flags & 32) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288) && !!(ts.getObjectFlags(type) & 16777216))); } function createNodeBuilder() { return { @@ -39187,7 +40245,9 @@ var ts; if (isJSConstructor(symbol.valueDeclaration)) { return symbolToTypeNode(symbol, context, isInstanceType); } - else if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 221 && context.flags & 2048) || + else if (symbol.flags & 32 + && !getBaseTypeVariableOfClass(symbol) + && !(symbol.valueDeclaration && symbol.valueDeclaration.kind === 222 && context.flags & 2048) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, isInstanceType); @@ -39215,7 +40275,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 297 || declaration.parent.kind === 257; + return declaration.parent.kind === 298 || declaration.parent.kind === 258; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { return (!!(context.flags & 4096) || ((_a = context.visitedTypes) === null || _a === void 0 ? void 0 : _a.has(typeId))) && @@ -39263,12 +40323,12 @@ var ts; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 174, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 175, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 175, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 176, context); return signatureNode; } } @@ -39434,17 +40494,17 @@ var ts; var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 169, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 170, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; if (signature.flags & 4) continue; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 170, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 171, context)); } if (resolvedType.stringIndexInfo) { var indexSignature = void 0; - if (resolvedType.objectFlags & 2048) { + if (resolvedType.objectFlags & 1024) { indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0, context, createElidedInformationPlaceholder(context)); } else { @@ -39488,15 +40548,23 @@ var ts; } return ts.factory.createKeywordTypeNode(128); } + function shouldUsePlaceholderForProperty(propertySymbol, context) { + var _a; + return !!(ts.getCheckFlags(propertySymbol) & 8192) + && (ts.contains(context.reverseMappedStack, propertySymbol) + || (((_a = context.reverseMappedStack) === null || _a === void 0 ? void 0 : _a[0]) + && !(ts.getObjectFlags(ts.last(context.reverseMappedStack).propertyType) & 16))); + } function addPropertyToElementList(propertySymbol, context, typeElements) { + var _a; var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192); - var propertyType = propertyIsReverseMapped && context.flags & 33554432 ? + var propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 && isLateBoundName(propertySymbol.escapedName)) { var decl = ts.first(propertySymbol.declarations); - if (hasLateBindableName(decl)) { + if (propertySymbol.declarations && hasLateBindableName(decl)) { if (ts.isBinaryExpression(decl)) { var name = ts.getNameOfDeclaration(decl); if (name && ts.isElementAccessExpression(name) && ts.isPropertyAccessEntityNameExpression(name.argumentExpression)) { @@ -39508,29 +40576,34 @@ var ts; } } } - context.enclosingDeclaration = saveEnclosingDeclaration; + context.enclosingDeclaration = propertySymbol.valueDeclaration || ((_a = propertySymbol.declarations) === null || _a === void 0 ? void 0 : _a[0]) || saveEnclosingDeclaration; var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context); + context.enclosingDeclaration = saveEnclosingDeclaration; context.approximateLength += (ts.symbolName(propertySymbol).length + 1); var optionalToken = propertySymbol.flags & 16777216 ? ts.factory.createToken(57) : undefined; if (propertySymbol.flags & (16 | 8192) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768); }), 0); for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { var signature = signatures_1[_i]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 164, context, { name: propertyName, questionToken: optionalToken }); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 165, context, { name: propertyName, questionToken: optionalToken }); typeElements.push(preserveCommentsOn(methodDeclaration)); } } else { - var savedFlags = context.flags; - context.flags |= propertyIsReverseMapped ? 33554432 : 0; var propertyTypeNode = void 0; - if (propertyIsReverseMapped && !!(savedFlags & 33554432)) { + if (shouldUsePlaceholderForProperty(propertySymbol, context)) { propertyTypeNode = createElidedInformationPlaceholder(context); } else { + if (propertyIsReverseMapped) { + context.reverseMappedStack || (context.reverseMappedStack = []); + context.reverseMappedStack.push(propertySymbol); + } propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(128); + if (propertyIsReverseMapped) { + context.reverseMappedStack.pop(); + } } - context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(142)] : undefined; if (modifiers) { context.approximateLength += 9; @@ -39539,9 +40612,10 @@ var ts; typeElements.push(preserveCommentsOn(propertySignature)); } function preserveCommentsOn(node) { - if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 333; })) { - var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 333; }); - var commentText = d.comment; + var _a; + if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 337; })) { + var d = (_a = propertySymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 337; }); + var commentText = ts.getTextOfJSDocComment(d.comment); if (commentText) { ts.setSyntheticLeadingComments(node, [{ kind: 3, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]); } @@ -39568,25 +40642,25 @@ var ts; } var mayHaveNameCollisions = !(context.flags & 64); var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; - var result_4 = []; + var result_5 = []; var i = 0; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var type = types_2[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result_4.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", undefined)); + result_5.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result_4.push(typeNode_1); + result_5.push(typeNode_1); } break; } context.approximateLength += 2; var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result_4.push(typeNode); + result_5.push(typeNode); if (seenNames && ts.isIdentifierTypeReference(typeNode)) { - seenNames.add(typeNode.typeName.escapedText, [type, result_4.length - 1]); + seenNames.add(typeNode.typeName.escapedText, [type, result_5.length - 1]); } } } @@ -39601,13 +40675,13 @@ var ts; })) { for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { var _a = types_3[_i], type = _a[0], resultIndex = _a[1]; - result_4[resultIndex] = typeToTypeNodeHelper(type, context); + result_5[resultIndex] = typeToTypeNodeHelper(type, context); } } }); context.flags = saveContextFlags; } - return result_4; + return result_5; } } function typesAreSameReference(a, b) { @@ -39642,7 +40716,7 @@ var ts; typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); } var expandedParams = getExpandedParameters(signature, true)[0]; - var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 166, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); + var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 167, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -39669,25 +40743,25 @@ var ts; } } var modifiers = options === null || options === void 0 ? void 0 : options.modifiers; - if ((kind === 175) && signature.flags & 4) { + if ((kind === 176) && signature.flags & 4) { var flags = ts.modifiersToFlags(modifiers); modifiers = ts.factory.createModifiersFromModifierFlags(flags | 128); } context.approximateLength += 3; - var node = kind === 169 ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : - kind === 170 ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : - kind === 164 ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : - kind === 165 ? ts.factory.createMethodDeclaration(undefined, modifiers, undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), undefined, typeParameters, parameters, returnTypeNode, undefined) : - kind === 166 ? ts.factory.createConstructorDeclaration(undefined, modifiers, parameters, undefined) : - kind === 167 ? ts.factory.createGetAccessorDeclaration(undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, undefined) : - kind === 168 ? ts.factory.createSetAccessorDeclaration(undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, undefined) : - kind === 171 ? ts.factory.createIndexSignature(undefined, modifiers, parameters, returnTypeNode) : - kind === 308 ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : - kind === 174 ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 175 ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 251 ? ts.factory.createFunctionDeclaration(undefined, modifiers, undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, undefined) : - kind === 208 ? ts.factory.createFunctionExpression(modifiers, undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : - kind === 209 ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, undefined, ts.factory.createBlock([])) : + var node = kind === 170 ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : + kind === 171 ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : + kind === 165 ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : + kind === 166 ? ts.factory.createMethodDeclaration(undefined, modifiers, undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), undefined, typeParameters, parameters, returnTypeNode, undefined) : + kind === 167 ? ts.factory.createConstructorDeclaration(undefined, modifiers, parameters, undefined) : + kind === 168 ? ts.factory.createGetAccessorDeclaration(undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, undefined) : + kind === 169 ? ts.factory.createSetAccessorDeclaration(undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, undefined) : + kind === 172 ? ts.factory.createIndexSignature(undefined, modifiers, parameters, returnTypeNode) : + kind === 309 ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : + kind === 175 ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : + kind === 176 ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : + kind === 252 ? ts.factory.createFunctionDeclaration(undefined, modifiers, undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, undefined) : + kind === 209 ? ts.factory.createFunctionExpression(modifiers, undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : + kind === 210 ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, undefined, ts.factory.createBlock([])) : ts.Debug.assertNever(kind); if (typeArguments) { node.typeArguments = ts.factory.createNodeArray(typeArguments); @@ -39709,9 +40783,9 @@ var ts; return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 160); + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 161); if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 326); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 330); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -39726,7 +40800,7 @@ var ts; var dotDotDotToken = isRest ? ts.factory.createToken(25) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 78 ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name), 16777216) : - parameterDeclaration.name.kind === 157 ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216) : + parameterDeclaration.name.kind === 158 ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216) : cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); @@ -39872,11 +40946,11 @@ var ts; } function getSpecifierForModuleSymbol(symbol, context) { var _a; - var file = ts.getDeclarationOfKind(symbol, 297); + var file = ts.getDeclarationOfKind(symbol, 298); if (!file) { var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); }); if (equivalentFileSymbol) { - file = ts.getDeclarationOfKind(equivalentFileSymbol, 297); + file = ts.getDeclarationOfKind(equivalentFileSymbol, 298); } } if (file && file.moduleName !== undefined) { @@ -39886,8 +40960,8 @@ var ts; if (context.tracker.trackReferencedAmbientModule) { var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); if (ts.length(ambientDecls)) { - for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { - var decl = ambientDecls_1[_i]; + for (var _i = 0, _b = ambientDecls; _i < _b.length; _i++) { + var decl = _b[_i]; context.tracker.trackReferencedAmbientModule(decl, symbol); } } @@ -39909,7 +40983,7 @@ var ts; var isBundle_1 = !!ts.outFile(compilerOptions); var moduleResolverHost = context.tracker.moduleResolverHost; var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; - specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "project-relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); (_a = links.specifierCache) !== null && _a !== void 0 ? _a : (links.specifierCache = new ts.Map()); links.specifierCache.set(contextFile.path, specifier); } @@ -40129,9 +41203,6 @@ var ts; if (fromNameType) { return fromNameType; } - if (ts.isKnownSymbol(symbol)) { - return ts.factory.createComputedPropertyName(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("Symbol"), symbol.escapedName.substr(3))); - } var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName); var stringNamed = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isStringNamed); return createPropertyNameNodeForIdentifierOrLiteral(rawName, stringNamed, singleQuote); @@ -40181,12 +41252,12 @@ var ts; function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { if (type !== errorType && enclosingDeclaration) { var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation) && !ts.isGetAccessorDeclaration(declWithExistingAnnotation)) { var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { - var result_5 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); - if (result_5) { - return result_5; + var result_6 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_6) { + return result_6; } } } @@ -40203,10 +41274,14 @@ var ts; function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { if (type !== errorType && context.enclosingDeclaration) { var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); - if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { - var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); - if (result) { - return result; + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation) { + var annotated = getTypeFromTypeNode(annotation); + var thisInstantiated = annotated.flags & 262144 && annotated.isThisType ? instantiateType(annotated, signature.mapper) : annotated; + if (thisInstantiated === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } } } } @@ -40249,7 +41324,7 @@ var ts; } return transformed === existing ? ts.setTextRange(ts.factory.cloneNode(existing), existing) : transformed; function visitExistingNodeTreeSymbols(node) { - if (ts.isJSDocAllType(node) || node.kind === 310) { + if (ts.isJSDocAllType(node) || node.kind === 311) { return ts.factory.createKeywordTypeNode(128); } if (ts.isJSDocUnknownType(node)) { @@ -40351,8 +41426,8 @@ var ts; } } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { - var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 165, true); - var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 164, false); + var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 166, true); + var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 165, false); var enclosingDeclaration = context.enclosingDeclaration; var results = []; var visitedSymbols = new ts.Set(); @@ -40526,6 +41601,7 @@ var ts; } } function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) { + var _a, _b; var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName); var isDefault = symbol.escapedName === "default"; if (isPrivate && !(context.flags & 131072) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) { @@ -40576,9 +41652,9 @@ var ts; if (textRange && ts.isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) { textRange = textRange.parent.parent; } - var propertyAccessRequire = ts.find(symbol.declarations, ts.isPropertyAccessExpression); + var propertyAccessRequire = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isPropertyAccessExpression); if (propertyAccessRequire && ts.isBinaryExpression(propertyAccessRequire.parent) && ts.isIdentifier(propertyAccessRequire.parent.right) - && type.symbol && ts.isSourceFile(type.symbol.valueDeclaration)) { + && ((_b = type.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration) && ts.isSourceFile(type.symbol.valueDeclaration)) { var alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right; addResult(ts.factory.createExportDeclaration(undefined, undefined, false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(alias, localName)])), 0); context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, 111551); @@ -40601,7 +41677,10 @@ var ts; serializeEnum(symbol, symbolName, modifierFlags); } if (symbol.flags & 32) { - if (symbol.flags & 4 && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { + if (symbol.flags & 4 + && symbol.valueDeclaration + && ts.isBinaryExpression(symbol.valueDeclaration.parent) + && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags); } else { @@ -40621,12 +41700,14 @@ var ts; serializeMaybeAliasAssignment(symbol); } if (symbol.flags & 8388608) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - if (!resolvedModule) - continue; - addResult(ts.factory.createExportDeclaration(undefined, undefined, false, undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0); + if (symbol.declarations) { + for (var _i = 0, _c = symbol.declarations; _i < _c.length; _i++) { + var node = _c[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + if (!resolvedModule) + continue; + addResult(ts.factory.createExportDeclaration(undefined, undefined, false, undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0); + } } } if (needsPostExportDefault) { @@ -40655,14 +41736,15 @@ var ts; function addResult(node, additionalModifierFlags) { if (ts.canHaveModifiers(node)) { var newModifierFlags = 0; + var enclosingDeclaration_1 = context.enclosingDeclaration && + (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 && - context.enclosingDeclaration && - (isExportingScope(context.enclosingDeclaration) || ts.isModuleDeclaration(context.enclosingDeclaration)) && + enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && canHaveExportModifier(node)) { newModifierFlags |= 1; } if (addingDeclare && !(newModifierFlags & 1) && - (!context.enclosingDeclaration || !(context.enclosingDeclaration.flags & 8388608)) && + (!enclosingDeclaration_1 || !(enclosingDeclaration_1.flags & 8388608)) && (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) { newModifierFlags |= 2; } @@ -40676,19 +41758,23 @@ var ts; results.push(node); } function serializeTypeAlias(symbol, symbolName, modifierFlags) { + var _a; var aliasType = getDeclaredTypeOfTypeAlias(symbol); var typeParams = getSymbolLinks(symbol).typeParameters; var typeParamDecls = ts.map(typeParams, function (p) { return typeParameterToDeclaration(p, context); }); - var jsdocAliasDecl = ts.find(symbol.declarations, ts.isJSDocTypeAlias); - var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined; + var jsdocAliasDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isJSDocTypeAlias); + var commentText = ts.getTextOfJSDocComment(jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined); var oldFlags = context.flags; context.flags |= 8388608; + var oldEnclosingDecl = context.enclosingDeclaration; + context.enclosingDeclaration = jsdocAliasDecl; var typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(undefined, undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; + context.enclosingDeclaration = oldEnclosingDecl; } function serializeInterface(symbol, symbolName, modifierFlags) { var interfaceType = getDeclaredTypeOfClassOrInterface(symbol); @@ -40697,8 +41783,8 @@ var ts; var baseTypes = getBaseTypes(interfaceType); var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined; var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); }); - var callSignatures = serializeSignatures(0, interfaceType, baseType, 169); - var constructSignatures = serializeSignatures(1, interfaceType, baseType, 170); + var callSignatures = serializeSignatures(0, interfaceType, baseType, 170); + var constructSignatures = serializeSignatures(1, interfaceType, baseType, 171); var indexSignatures = serializeIndexSignatures(interfaceType, baseType); var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(93, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551); }))]; addResult(ts.factory.createInterfaceDeclaration(undefined, undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures), constructSignatures), callSignatures), members)), modifierFlags); @@ -40750,14 +41836,25 @@ var ts; var signatures = getSignaturesOfType(type, 0); for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; - var decl = signatureToSignatureDeclarationHelper(sig, 251, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled }); - addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags); + var decl = signatureToSignatureDeclarationHelper(sig, 252, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled }); + addResult(ts.setTextRange(decl, getSignatureTextRangeLocation(sig)), modifierFlags); } if (!(symbol.flags & (512 | 1024) && !!symbol.exports && !!symbol.exports.size)) { var props = ts.filter(getPropertiesOfType(type), isNamespaceMember); serializeAsNamespaceDeclaration(props, localName, modifierFlags, true); } } + function getSignatureTextRangeLocation(signature) { + if (signature.declaration && signature.declaration.parent) { + if (ts.isBinaryExpression(signature.declaration.parent) && ts.getAssignmentDeclarationKind(signature.declaration.parent) === 5) { + return signature.declaration.parent; + } + if (ts.isVariableDeclaration(signature.declaration.parent) && signature.declaration.parent.parent) { + return signature.declaration.parent.parent; + } + } + return signature.declaration; + } function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) { if (ts.length(props)) { var localVsRemoteMap = ts.arrayToMultiMap(props, function (p) { @@ -40823,8 +41920,8 @@ var ts; return undefined; } function serializeAsClass(symbol, localName, modifierFlags) { - var _a; - var originalDecl = ts.find(symbol.declarations, ts.isClassLike); + var _a, _b; + var originalDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isClassLike); var oldEnclosing = context.enclosingDeclaration; context.enclosingDeclaration = originalDecl || oldEnclosing; var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -40835,7 +41932,7 @@ var ts; var implementsExpressions = originalImplements && sanitizeJSDocImplements(originalImplements) || ts.mapDefined(getImplementsTypes(classType), serializeImplementedType); var staticType = getTypeOfSymbol(symbol); - var isClass = !!((_a = staticType.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration) && ts.isClassLike(staticType.symbol.valueDeclaration); + var isClass = !!((_b = staticType.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration) && ts.isClassLike(staticType.symbol.valueDeclaration); var staticBaseType = isClass ? getBaseConstructorTypeOfClass(staticType) : anyType; @@ -40843,11 +41940,11 @@ var ts; var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType)); var publicSymbolProps = ts.filter(symbolProps, function (s) { var valueDecl = s.valueDeclaration; - return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); + return !!valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); }); var hasPrivateIdentifier = ts.some(symbolProps, function (s) { var valueDecl = s.valueDeclaration; - return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); + return !!valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); }); var privateProperties = hasPrivateIdentifier ? [ts.factory.createPropertyDeclaration(undefined, undefined, ts.factory.createPrivateIdentifier("#private"), undefined, undefined, undefined)] : @@ -40860,7 +41957,7 @@ var ts; !ts.some(getSignaturesOfType(staticType, 1)); var constructors = isNonConstructableClassLikeInJsFile ? [ts.factory.createConstructorDeclaration(undefined, ts.factory.createModifiersFromModifierFlags(8), [], undefined)] : - serializeSignatures(1, staticType, staticBaseType, 166); + serializeSignatures(1, staticType, staticBaseType, 167); var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); context.enclosingDeclaration = oldEnclosing; addResult(ts.setTextRange(ts.factory.createClassDeclaration(undefined, undefined, localName, typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures), staticMembers), constructors), publicProperties), privateProperties)), symbol.declarations && ts.filter(symbol.declarations, function (d) { return ts.isClassDeclaration(d) || ts.isClassExpression(d); })[0]), modifierFlags); @@ -40881,8 +41978,8 @@ var ts; var targetName = getInternalSymbolName(target, verbatimTargetName); includePrivateSymbol(target); switch (node.kind) { - case 198: - if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 249) { + case 199: + if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 250) { var specifier_1 = getSpecifierForModuleSymbol(target.parent || target, context); var propertyName = node.propertyName; addResult(ts.factory.createImportDeclaration(undefined, undefined, ts.factory.createImportClause(false, undefined, ts.factory.createNamedImports([ts.factory.createImportSpecifier(propertyName && ts.isIdentifier(propertyName) ? ts.factory.createIdentifier(ts.idText(propertyName)) : undefined, ts.factory.createIdentifier(localName))])), ts.factory.createStringLiteral(specifier_1)), 0); @@ -40890,12 +41987,12 @@ var ts; } ts.Debug.failBadSyntaxKind(((_c = node.parent) === null || _c === void 0 ? void 0 : _c.parent) || node, "Unhandled binding element grandparent kind in declaration serialization"); break; - case 289: - if (((_e = (_d = node.parent) === null || _d === void 0 ? void 0 : _d.parent) === null || _e === void 0 ? void 0 : _e.kind) === 216) { + case 290: + if (((_e = (_d = node.parent) === null || _d === void 0 ? void 0 : _d.parent) === null || _e === void 0 ? void 0 : _e.kind) === 217) { serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), targetName); } break; - case 249: + case 250: if (ts.isPropertyAccessExpression(node.initializer)) { var initializer = node.initializer; var uniqueName = ts.factory.createUniqueName(localName); @@ -40904,7 +42001,7 @@ var ts; addResult(ts.factory.createImportEqualsDeclaration(undefined, undefined, false, ts.factory.createIdentifier(localName), ts.factory.createQualifiedName(uniqueName, initializer.name)), modifierFlags); break; } - case 260: + case 261: if (target.escapedName === "export=" && ts.some(target.declarations, ts.isJsonSourceFile)) { serializeMaybeAliasAssignment(symbol); break; @@ -40914,33 +42011,33 @@ var ts; ? symbolToName(target, context, 67108863, false) : ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)))), isLocalImport ? modifierFlags : 0); break; - case 259: + case 260: addResult(ts.factory.createNamespaceExportDeclaration(ts.idText(node.name)), 0); break; - case 262: + case 263: addResult(ts.factory.createImportDeclaration(undefined, undefined, ts.factory.createImportClause(false, ts.factory.createIdentifier(localName), undefined), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0); break; - case 263: + case 264: addResult(ts.factory.createImportDeclaration(undefined, undefined, ts.factory.createImportClause(false, undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0); break; - case 269: + case 270: addResult(ts.factory.createExportDeclaration(undefined, undefined, false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0); break; - case 265: + case 266: addResult(ts.factory.createImportDeclaration(undefined, undefined, ts.factory.createImportClause(false, undefined, ts.factory.createNamedImports([ ts.factory.createImportSpecifier(localName !== verbatimTargetName ? ts.factory.createIdentifier(verbatimTargetName) : undefined, ts.factory.createIdentifier(localName)) ])), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0); break; - case 270: + case 271: var specifier = node.parent.parent.moduleSpecifier; serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.factory.createStringLiteral(specifier.text) : undefined); break; - case 266: + case 267: serializeMaybeAliasAssignment(symbol); break; - case 216: - case 201: + case 217: case 202: + case 203: if (symbol.escapedName === "default" || symbol.escapedName === "export=") { serializeMaybeAliasAssignment(symbol); } @@ -41034,6 +42131,7 @@ var ts; } function makeSerializePropertySymbol(createProperty, methodKind, useAccessors) { return function serializePropertySymbol(p, isStatic, baseType) { + var _a, _b, _c, _d, _e; var modifierFlags = ts.getDeclarationModifierFlagsFromSymbol(p); var isPrivate = !!(modifierFlags & 8); if (isStatic && (p.flags & (788968 | 1920 | 2097152))) { @@ -41048,26 +42146,26 @@ var ts; } var flag = (modifierFlags & ~256) | (isStatic ? 32 : 0); var name = getPropertyNameNodeForSymbol(p, context); - var firstPropertyLikeDecl = ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression)); + var firstPropertyLikeDecl = (_a = p.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression)); if (p.flags & 98304 && useAccessors) { var result = []; if (p.flags & 65536) { - result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration(undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration(undefined, undefined, undefined, "arg", undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl)); + result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration(undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration(undefined, undefined, undefined, "arg", undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], undefined), ((_b = p.declarations) === null || _b === void 0 ? void 0 : _b.find(ts.isSetAccessor)) || firstPropertyLikeDecl)); } if (p.flags & 32768) { var isPrivate_1 = modifierFlags & 8; - result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration(undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl)); + result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration(undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), undefined), ((_c = p.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isGetAccessor)) || firstPropertyLikeDecl)); } return result; } else if (p.flags & (4 | 3 | 98304)) { - return ts.setTextRange(createProperty(undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 : 0) | flag), name, p.flags & 16777216 ? ts.factory.createToken(57) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl); + return ts.setTextRange(createProperty(undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 : 0) | flag), name, p.flags & 16777216 ? ts.factory.createToken(57) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), undefined), ((_d = p.declarations) === null || _d === void 0 ? void 0 : _d.find(ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration))) || firstPropertyLikeDecl); } if (p.flags & (8192 | 16)) { var type = getTypeOfSymbol(p); var signatures = getSignaturesOfType(type, 0); if (flag & 8) { - return ts.setTextRange(createProperty(undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 : 0) | flag), name, p.flags & 16777216 ? ts.factory.createToken(57) : undefined, undefined, undefined), ts.find(p.declarations, ts.isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations[0]); + return ts.setTextRange(createProperty(undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 : 0) | flag), name, p.flags & 16777216 ? ts.factory.createToken(57) : undefined, undefined, undefined), ((_e = p.declarations) === null || _e === void 0 ? void 0 : _e.find(ts.isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); } var results_1 = []; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { @@ -41077,7 +42175,8 @@ var ts; questionToken: p.flags & 16777216 ? ts.factory.createToken(57) : undefined, modifiers: flag ? ts.factory.createModifiersFromModifierFlags(flag) : undefined }); - results_1.push(ts.setTextRange(decl, sig.declaration)); + var location = sig.declaration && ts.isPrototypePropertyAssignment(sig.declaration.parent) ? sig.declaration.parent : sig.declaration; + results_1.push(ts.setTextRange(decl, location)); } return results_1; } @@ -41283,9 +42382,9 @@ var ts; return "public"; } function getTypeAliasForTypeLiteral(type) { - if (type.symbol && type.symbol.flags & 2048) { + if (type.symbol && type.symbol.flags & 2048 && type.symbol.declarations) { var node = ts.walkUpParenthesizedTypes(type.symbol.declarations[0].parent); - if (node.kind === 254) { + if (node.kind === 255) { return getSymbolOfNode(node); } } @@ -41293,11 +42392,11 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 257 && + node.parent.kind === 258 && ts.isExternalModuleAugmentation(node.parent.parent); } function isDefaultBindingContext(location) { - return location.kind === 297 || ts.isAmbientModule(location); + return location.kind === 298 || ts.isAmbientModule(location); } function getNameOfSymbolFromNameType(symbol, context) { var nameType = getSymbolLinks(symbol).nameType; @@ -41345,17 +42444,17 @@ var ts; if (!declaration) { declaration = symbol.declarations[0]; } - if (declaration.parent && declaration.parent.kind === 249) { + if (declaration.parent && declaration.parent.kind === 250) { return ts.declarationNameToString(declaration.parent.name); } switch (declaration.kind) { - case 221: - case 208: + case 222: case 209: + case 210: if (context && !context.encounteredError && !(context.flags & 131072)) { context.encounteredError = true; } - return declaration.kind === 221 ? "(Anonymous class)" : "(Anonymous function)"; + return declaration.kind === 222 ? "(Anonymous class)" : "(Anonymous function)"; } } var name = getNameOfSymbolFromNameType(symbol, context); @@ -41372,68 +42471,68 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 324: - case 331: - case 325: + case 328: + case 335: + case 329: return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); - case 198: + case 199: return isDeclarationVisible(node.parent.parent); - case 249: + case 250: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { return false; } - case 256: - case 252: + case 257: case 253: case 254: - case 251: case 255: - case 260: + case 252: + case 256: + case 261: if (ts.isExternalModuleAugmentation(node)) { return true; } var parent = getDeclarationContainer(node); if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 260 && parent.kind !== 297 && parent.flags & 8388608)) { + !(node.kind !== 261 && parent.kind !== 298 && parent.flags & 8388608)) { return isGlobalSourceFile(parent); } return isDeclarationVisible(parent); + case 164: case 163: - case 162: - case 167: case 168: + case 169: + case 166: case 165: - case 164: if (ts.hasEffectiveModifier(node, 8 | 16)) { return false; } - case 166: - case 170: - case 169: + case 167: case 171: - case 160: - case 257: - case 174: + case 170: + case 172: + case 161: + case 258: case 175: - case 177: - case 173: + case 176: case 178: + case 174: case 179: - case 182: + case 180: case 183: - case 186: - case 192: + case 184: + case 187: + case 193: return isDeclarationVisible(node.parent); - case 262: case 263: - case 265: + case 264: + case 266: return false; - case 159: - case 297: - case 259: + case 160: + case 298: + case 260: return true; - case 266: + case 267: return false; default: return false; @@ -41442,10 +42541,10 @@ var ts; } function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 266) { + if (node.parent && node.parent.kind === 267) { exportSymbol = resolveName(node, node.escapedText, 111551 | 788968 | 1920 | 2097152, undefined, node, false); } - else if (node.parent.kind === 270) { + else if (node.parent.kind === 271) { exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 | 788968 | 1920 | 2097152); } var result; @@ -41533,12 +42632,12 @@ var ts; function getDeclarationContainer(node) { return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 249: case 250: + case 251: + case 266: case 265: case 264: case 263: - case 262: return false; default: return true; @@ -41594,9 +42693,16 @@ var ts; var stringIndexInfo = getIndexInfoOfType(source, 0); var numberIndexInfo = getIndexInfoOfType(source, 1); var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= 131072; + result.objectFlags |= 8388608; return result; } + function isGenericTypeWithUndefinedConstraint(type) { + return !!(type.flags & 465829888) && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 32768); + } + function getNonUndefinedType(type) { + var typeOrConstraint = someType(type, isGenericTypeWithUndefinedConstraint) ? mapType(type, function (t) { return t.flags & 465829888 ? getBaseConstraintOrType(t) : t; }) : type; + return getTypeWithFacts(typeOrConstraint, 524288); + } function getFlowTypeOfDestructuring(node, declaredType) { var reference = getSyntheticElementAccess(node); return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType; @@ -41622,23 +42728,23 @@ var ts; function getParentElementAccess(node) { var ancestor = node.parent.parent; switch (ancestor.kind) { - case 198: - case 288: - return getSyntheticElementAccess(ancestor); case 199: + case 289: + return getSyntheticElementAccess(ancestor); + case 200: return getSyntheticElementAccess(node.parent); - case 249: + case 250: return ancestor.initializer; - case 216: + case 217: return ancestor.right; } } function getDestructuringPropertyName(node) { var parent = node.parent; - if (node.kind === 198 && parent.kind === 196) { + if (node.kind === 199 && parent.kind === 197) { return getLiteralPropertyNameText(node.propertyName || node.name); } - if (node.kind === 288 || node.kind === 289) { + if (node.kind === 289 || node.kind === 290) { return getLiteralPropertyNameText(node.name); } return "" + parent.elements.indexOf(node); @@ -41660,7 +42766,7 @@ var ts; parentType = getTypeWithFacts(parentType, 524288); } var type; - if (pattern.kind === 196) { + if (pattern.kind === 197) { if (declaration.dotDotDotToken) { parentType = getReducedType(parentType); if (parentType.flags & 2 || !isValidSpreadType(parentType)) { @@ -41679,7 +42785,7 @@ var ts; else { var name = declaration.propertyName || declaration.name; var indexType = getLiteralTypeFromPropertyName(name); - var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, undefined, name, undefined, undefined, 16), declaration.name); + var declaredType = getIndexedAccessType(parentType, indexType, undefined, name, undefined, undefined, 16); type = getFlowTypeOfDestructuring(declaration, declaredType); } } @@ -41694,7 +42800,7 @@ var ts; else if (isArrayLikeType(parentType)) { var indexType = getLiteralType(index_2); var accessFlags = hasDefaultValue(declaration) ? 8 : 0; - var declaredType = getConstraintForLocation(getIndexedAccessTypeOrUndefined(parentType, indexType, undefined, declaration.name, accessFlags | 16) || errorType, declaration.name); + var declaredType = getIndexedAccessTypeOrUndefined(parentType, indexType, undefined, declaration.name, accessFlags | 16) || errorType; type = getFlowTypeOfDestructuring(declaration, declaredType); } else { @@ -41705,11 +42811,9 @@ var ts; return type; } if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) { - return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768) ? - getTypeWithFacts(type, 524288) : - type; + return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768) ? getNonUndefinedType(type) : type; } - return widenTypeInferredFromInitializer(declaration, getUnionType([getTypeWithFacts(type, 524288), checkDeclarationInitializer(declaration)], 2)); + return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration)], 2)); } function getTypeForDeclarationFromJSDocComment(declaration) { var jsdocType = ts.getJSDocType(declaration); @@ -41724,18 +42828,18 @@ var ts; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 199 && expr.elements.length === 0; + return expr.kind === 200 && expr.elements.length === 0; } function addOptionality(type, optional) { if (optional === void 0) { optional = true; } return strictNullChecks && optional ? getOptionalType(type) : type; } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 238) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239) { var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); return indexType.flags & (262144 | 4194304) ? getExtractStringType(indexType) : stringType; } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 240) { var forOfStatement = declaration.parent.parent; return checkRightHandSideOfForOf(forOfStatement) || anyType; } @@ -41761,8 +42865,8 @@ var ts; } if (ts.isParameter(declaration)) { var func = declaration.parent; - if (func.kind === 168 && !hasNonBindableDynamicName(func)) { - var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 167); + if (func.kind === 169 && hasBindableName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 168); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -41819,7 +42923,7 @@ var ts; links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && ts.every(symbol.declarations, function (declaration) { return ts.isBinaryExpression(declaration) && isPossiblyAliasedThisProperty(declaration) && - (declaration.left.kind !== 202 || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && + (declaration.left.kind !== 203 || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && !getAnnotatedTypeForAssignmentDeclaration(undefined, declaration, symbol, declaration); }); } @@ -41833,13 +42937,32 @@ var ts; !declaration.initializer && (noImplicitAny || ts.isInJSFile(declaration)); } function getDeclaringConstructor(symbol) { + if (!symbol.declarations) { + return; + } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var container = ts.getThisContainer(declaration, false); - if (container && (container.kind === 166 || isJSConstructor(container))) { + if (container && (container.kind === 167 || isJSConstructor(container))) { return container; } } + ; + } + function getFlowTypeFromCommonJSExport(symbol) { + var file = ts.getSourceFileOfNode(symbol.declarations[0]); + var accessName = ts.unescapeLeadingUnderscores(symbol.escapedName); + var areAllModuleExports = symbol.declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && ts.isModuleExportsAccessExpression(d.expression); }); + var reference = areAllModuleExports + ? ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("module"), ts.factory.createIdentifier("exports")), accessName) + : ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("exports"), accessName); + if (areAllModuleExports) { + ts.setParent(reference.expression.expression, reference.expression); + } + ts.setParent(reference.expression, reference); + ts.setParent(reference, file); + reference.flowNode = file.endFlowNode; + return getFlowTypeOfReference(reference, autoType, undefinedType); } function getFlowTypeInConstructor(symbol, constructor) { var accessName = ts.startsWith(symbol.escapedName, "__#") @@ -41856,7 +42979,10 @@ var ts; return everyType(flowType, isNullableType) ? undefined : convertAutoToAny(flowType); } function getFlowTypeOfProperty(reference, prop) { - var initialType = prop && (!isAutoTypedProperty(prop) || ts.getEffectiveModifierFlags(prop.valueDeclaration) & 2) && getTypeOfPropertyInBaseClass(prop) || undefinedType; + var initialType = (prop === null || prop === void 0 ? void 0 : prop.valueDeclaration) + && (!isAutoTypedProperty(prop) || ts.getEffectiveModifierFlags(prop.valueDeclaration) & 2) + && getTypeOfPropertyInBaseClass(prop) + || undefinedType; return getFlowTypeOfReference(reference, autoType, initialType); } function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) { @@ -41866,7 +42992,7 @@ var ts; if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + var containerObjectType = symbol.valueDeclaration && getJSContainerObjectType(symbol.valueDeclaration, symbol, container); return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var type; @@ -41876,40 +43002,42 @@ var ts; type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol)); } if (!type) { - var jsdocType = void 0; var types = void 0; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : - ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : - undefined; - if (!expression) { - continue; - } - var kind = ts.isAccessExpression(expression) - ? ts.getAssignmentDeclarationPropertyAccessKind(expression) - : ts.getAssignmentDeclarationKind(expression); - if (kind === 4 || ts.isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) { - if (isDeclarationInConstructor(expression)) { - definedInConstructor = true; + if (symbol.declarations) { + var jsdocType = void 0; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : + ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + continue; } - else { - definedInMethod = true; + var kind = ts.isAccessExpression(expression) + ? ts.getAssignmentDeclarationPropertyAccessKind(expression) + : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 || ts.isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + if (!ts.isCallExpression(expression)) { + jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } - if (!ts.isCallExpression(expression)) { - jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); - } - if (!jsdocType) { - (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); - } + type = jsdocType; } - type = jsdocType; if (!type) { if (!ts.length(types)) { return errorType; } - var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; + var constructorTypes = definedInConstructor && symbol.declarations ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; if (definedInMethod) { var propType = getTypeOfPropertyInBaseClass(symbol); if (propType) { @@ -41922,7 +43050,7 @@ var ts; } } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); - if (filterType(widened, function (t) { return !!(t.flags & ~98304); }) === neverType) { + if (symbol.valueDeclaration && filterType(widened, function (t) { return !!(t.flags & ~98304); }) === neverType) { reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } @@ -41946,10 +43074,11 @@ var ts; mergeSymbolTable(exports, s.exports); } var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - type.objectFlags |= 16384; + type.objectFlags |= 8192; return type; } function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) { + var _a; var typeNode = ts.getEffectiveTypeAnnotationNode(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -41960,7 +43089,7 @@ var ts; errorNextVariableOrPropertyDeclarationMustHaveSameType(undefined, declaredType, declaration, type); } } - if (symbol.parent) { + if ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) { var typeNode_2 = ts.getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration); if (typeNode_2) { return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode_2), symbol.escapedName); @@ -42013,7 +43142,7 @@ var ts; var exportedMember = members_4.get(name); if (exportedMember && exportedMember !== s) { if (s.flags & 111551 && exportedMember.flags & 111551) { - if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { + if (s.valueDeclaration && exportedMember.valueDeclaration && ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName); var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration; ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName)); @@ -42034,9 +43163,9 @@ var ts; } }); var result = createAnonymousType(initialSize !== members_4.size ? undefined : exportedType.symbol, members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo); - result.objectFlags |= (ts.getObjectFlags(type) & 16384); + result.objectFlags |= (ts.getObjectFlags(type) & 8192); if (result.symbol && result.symbol.flags & 32 && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { - result.objectFlags |= 1073741824; + result.objectFlags |= 16777216; } return result; } @@ -42053,9 +43182,9 @@ var ts; } function isDeclarationInConstructor(expression) { var thisContainer = ts.getThisContainer(expression, false); - return thisContainer.kind === 166 || - thisContainer.kind === 251 || - (thisContainer.kind === 208 && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + return thisContainer.kind === 167 || + thisContainer.kind === 252 || + (thisContainer.kind === 209 && !ts.isPrototypePropertyAssignment(thisContainer.parent)); } function getConstructorDefinedThisAssignmentTypes(types, declarations) { ts.Debug.assert(types.length === declarations.length); @@ -42082,7 +43211,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 | 1048576; + var objectFlags = 128 | 262144; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -42105,14 +43234,14 @@ var ts; result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; - result.objectFlags |= 1048576; + result.objectFlags |= 262144; } return result; } function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - var restElement = lastElement && lastElement.kind === 198 && lastElement.dotDotDotToken ? lastElement : undefined; + var restElement = lastElement && lastElement.kind === 199 && lastElement.dotDotDotToken ? lastElement : undefined; if (elements.length === 0 || elements.length === 1 && restElement) { return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; } @@ -42123,22 +43252,30 @@ var ts; if (includePatternInType) { result = cloneTypeReference(result); result.pattern = pattern; - result.objectFlags |= 1048576; + result.objectFlags |= 262144; } return result; } function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { if (includePatternInType === void 0) { includePatternInType = false; } if (reportErrors === void 0) { reportErrors = false; } - return pattern.kind === 196 + return pattern.kind === 197 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, true), declaration, reportErrors); } + function isGlobalSymbolConstructor(node) { + var symbol = getSymbolOfNode(node); + var globalSymbol = getGlobalESSymbolConstructorTypeSymbol(false); + return globalSymbol && symbol && symbol === globalSymbol; + } function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) { if (type) { + if (type.flags & 4096 && isGlobalSymbolConstructor(declaration.parent)) { + type = getESSymbolLikeTypeForNode(declaration); + } if (reportErrors) { reportErrorsFromWidening(declaration, type); } @@ -42157,7 +43294,7 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 160 ? root.parent : root; + var memberDeclaration = root.kind === 161 ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function tryGetTypeFromEffectiveTypeNode(declaration) { @@ -42183,18 +43320,30 @@ var ts; if (symbol === requireSymbol) { return anyType; } - if (symbol.flags & 134217728) { + if (symbol.flags & 134217728 && symbol.valueDeclaration) { var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var result = createSymbol(fileSymbol.flags, "exports"); + result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : []; + result.parent = symbol; + result.target = fileSymbol; + if (fileSymbol.valueDeclaration) + result.valueDeclaration = fileSymbol.valueDeclaration; + if (fileSymbol.members) + result.members = new ts.Map(fileSymbol.members); + if (fileSymbol.exports) + result.exports = new ts.Map(fileSymbol.exports); var members = ts.createSymbolTable(); - members.set("exports", fileSymbol); + members.set("exports", result); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); } + ts.Debug.assertIsDefined(symbol.valueDeclaration); var declaration = symbol.valueDeclaration; if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { - var decl = declaration; - if (!decl.type) + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode === undefined) { return anyType; - var type_1 = getTypeOfNode(decl.type); + } + var type_1 = getTypeOfNode(typeNode); return isTypeAny(type_1) || type_1 === unknownType ? type_1 : errorType; } if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) { @@ -42210,7 +43359,7 @@ var ts; return reportCircularityError(symbol); } var type; - if (declaration.kind === 266) { + if (declaration.kind === 267) { type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } else if (ts.isBinaryExpression(declaration) || @@ -42262,7 +43411,7 @@ var ts; type = getTypeOfEnumMember(symbol); } else if (ts.isAccessor(declaration)) { - type = resolveTypeOfAccessors(symbol); + type = resolveTypeOfAccessors(symbol) || ts.Debug.fail("Non-write accessor resolution must always produce a type"); } else { return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol)); @@ -42277,7 +43426,7 @@ var ts; } function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { - if (accessor.kind === 167) { + if (accessor.kind === 168) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation; } @@ -42301,59 +43450,72 @@ var ts; } function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); - return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + return links.type || (links.type = getTypeOfAccessorsWorker(symbol) || ts.Debug.fail("Read type of accessor must always produce a type")); } - function getTypeOfAccessorsWorker(symbol) { + function getTypeOfSetAccessor(symbol) { + var links = getSymbolLinks(symbol); + return links.writeType || (links.writeType = getTypeOfAccessorsWorker(symbol, true)); + } + function getTypeOfAccessorsWorker(symbol, writing) { + if (writing === void 0) { writing = false; } if (!pushTypeResolution(symbol, 0)) { return errorType; } - var type = resolveTypeOfAccessors(symbol); + var type = resolveTypeOfAccessors(symbol, writing); if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter = ts.getDeclarationOfKind(symbol, 167); + var getter = ts.getDeclarationOfKind(symbol, 168); error(getter, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } return type; } - function resolveTypeOfAccessors(symbol) { - var getter = ts.getDeclarationOfKind(symbol, 167); - var setter = ts.getDeclarationOfKind(symbol, 168); + function resolveTypeOfAccessors(symbol, writing) { + if (writing === void 0) { writing = false; } + var getter = ts.getDeclarationOfKind(symbol, 168); + var setter = ts.getDeclarationOfKind(symbol, 169); + var setterType = getAnnotatedAccessorType(setter); + if (writing && setterType) { + return instantiateTypeIfNeeded(setterType, symbol); + } if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { - return jsDocType; + return instantiateTypeIfNeeded(jsDocType, symbol); } } - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - return getterReturnType; + var getterType = getAnnotatedAccessorType(getter); + if (getterType) { + return instantiateTypeIfNeeded(getterType, symbol); } - else { - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - return setterParameterType; + if (setterType) { + return setterType; + } + if (getter && getter.body) { + var returnTypeFromBody = getReturnTypeFromBody(getter); + return instantiateTypeIfNeeded(returnTypeFromBody, symbol); + } + if (setter) { + if (!isPrivateWithinAmbient(setter)) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); } - else { - if (getter && getter.body) { - return getReturnTypeFromBody(getter); - } - else { - if (setter) { - if (!isPrivateWithinAmbient(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 exist a getter as we are current checking either setter or getter in this function"); - if (!isPrivateWithinAmbient(getter)) { - errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } - } - return anyType; - } + return anyType; + } + else if (getter) { + ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } + return anyType; + } + return undefined; + function instantiateTypeIfNeeded(type, symbol) { + if (ts.getCheckFlags(symbol) & 1) { + var links = getSymbolLinks(symbol); + return instantiateType(type, links.mapper); } + return type; } } function getBaseTypeVariableOfClass(symbol) { @@ -42382,9 +43544,9 @@ var ts; if (symbol.flags & 1536 && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration && (declaration.kind === 216 || + else if (declaration && (declaration.kind === 217 || ts.isAccessExpression(declaration) && - declaration.parent.kind === 216)) { + declaration.parent.kind === 217)) { return getWidenedTypeForAssignmentDeclaration(symbol); } else if (symbol.flags & 512 && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { @@ -42418,9 +43580,11 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); - links.type = targetSymbol.flags & 111551 - ? getTypeOfSymbol(targetSymbol) - : errorType; + var exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(getDeclarationOfAliasSymbol(symbol), true); + links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) + : isDuplicatedCommonJSExport(symbol.declarations) ? autoType + : targetSymbol.flags & 111551 ? getTypeOfSymbol(targetSymbol) + : errorType; } return links.type; } @@ -42444,7 +43608,7 @@ var ts; error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); return errorType; } - if (noImplicitAny && (declaration.kind !== 160 || declaration.initializer)) { + if (noImplicitAny && (declaration.kind !== 161 || declaration.initializer)) { error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); } return anyType; @@ -42458,6 +43622,15 @@ var ts; } return links.type; } + function getSetAccessorTypeOfSymbol(symbol) { + if (symbol.flags & 98304) { + var type = getTypeOfSetAccessor(symbol); + if (type) { + return type; + } + } + return getTypeOfSymbol(symbol); + } function getTypeOfSymbol(symbol) { var checkFlags = ts.getCheckFlags(symbol); if (checkFlags & 65536) { @@ -42534,63 +43707,69 @@ var ts; return undefined; } switch (node.kind) { - case 232: - case 252: - case 221: case 253: - case 169: + case 222: + case 254: case 170: - case 164: - case 174: - case 175: - case 308: - case 251: + case 171: case 165: - case 208: + case 175: + case 176: + case 309: + case 252: + case 166: case 209: - case 254: - case 330: - case 331: - case 325: - case 324: - case 190: - case 184: + case 210: + case 255: + case 334: + case 335: + case 329: + case 328: + case 191: + case 185: { var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 190) { + if (node.kind === 191) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } - else if (node.kind === 184) { + else if (node.kind === 185) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } - else if (node.kind === 232 && !ts.isInJSFile(node)) { - break; - } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && - (node.kind === 252 || node.kind === 221 || node.kind === 253 || isJSConstructor(node)) && + (node.kind === 253 || node.kind === 222 || node.kind === 254 || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; - case 326: + } + case 330: var paramSymbol = ts.getParameterSymbolFromJSDoc(node); if (paramSymbol) { node = paramSymbol.valueDeclaration; } break; + case 312: { + var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + return node.tags + ? appendTypeParameters(outerTypeParameters, ts.flatMap(node.tags, function (t) { return ts.isJSDocTemplateTag(t) ? t.typeParameters : undefined; })) + : outerTypeParameters; + } } } } function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 253); + var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 254); ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + if (!symbol.declarations) { + return; + } var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 253 || - node.kind === 252 || - node.kind === 221 || + if (node.kind === 254 || + node.kind === 253 || + node.kind === 222 || isJSConstructor(node) || ts.isTypeAlias(node)) { var declaration = node; @@ -42670,7 +43849,9 @@ var ts; ctorReturn = getReturnTypeOfSignature(ctorSig[0]); } } - ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + if (baseConstructorType.symbol.declarations) { + ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } } return type.resolvedBaseConstructorType = errorType; } @@ -42680,20 +43861,22 @@ var ts; } function getImplementsTypes(type) { var resolvedImplementsTypes = ts.emptyArray; - for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration); - if (!implementsTypeNodes) - continue; - for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) { - var node = implementsTypeNodes_1[_b]; - var implementsType = getTypeFromTypeNode(node); - if (implementsType !== errorType) { - if (resolvedImplementsTypes === ts.emptyArray) { - resolvedImplementsTypes = [implementsType]; - } - else { - resolvedImplementsTypes.push(implementsType); + if (type.symbol.declarations) { + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration); + if (!implementsTypeNodes) + continue; + for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) { + var node = implementsTypeNodes_1[_b]; + var implementsType = getTypeFromTypeNode(node); + if (implementsType !== errorType) { + if (resolvedImplementsTypes === ts.emptyArray) { + resolvedImplementsTypes = [implementsType]; + } + else { + resolvedImplementsTypes.push(implementsType); + } } } } @@ -42720,10 +43903,10 @@ var ts; else { ts.Debug.fail("type must be class or interface"); } - if (!popTypeResolution()) { + if (!popTypeResolution() && type.symbol.declarations) { for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 252 || declaration.kind === 253) { + if (declaration.kind === 253 || declaration.kind === 254) { reportCircularBaseType(declaration, type); } } @@ -42801,38 +43984,43 @@ var ts; } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; - for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 253 && ts.getInterfaceBaseTypeNodes(declaration)) { - for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { - var node = _c[_b]; - var baseType = getReducedType(getTypeFromTypeNode(node)); - if (baseType !== errorType) { - if (isValidBaseType(baseType)) { - if (type !== baseType && !hasBaseType(baseType, type)) { - if (type.resolvedBaseTypes === ts.emptyArray) { - type.resolvedBaseTypes = [baseType]; + if (type.symbol.declarations) { + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 254 && ts.getInterfaceBaseTypeNodes(declaration)) { + for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { + var node = _c[_b]; + var baseType = getReducedType(getTypeFromTypeNode(node)); + if (baseType !== errorType) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } } else { - type.resolvedBaseTypes.push(baseType); + reportCircularBaseType(declaration, type); } } else { - reportCircularBaseType(declaration, type); + error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } - else { - error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); - } } } } } } function isThislessInterface(symbol) { + if (!symbol.declarations) { + return true; + } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 253) { + if (declaration.kind === 254) { if (declaration.flags & 128) { return false; } @@ -42857,7 +44045,7 @@ var ts; var originalLinks = links; if (!links.declaredType) { var kind = symbol.flags & 32 ? 1 : 2; - var merged = mergeJSSymbols(symbol, getAssignedClassSymbol(symbol.valueDeclaration)); + var merged = mergeJSSymbols(symbol, symbol.valueDeclaration && getAssignedClassSymbol(symbol.valueDeclaration)); if (merged) { symbol = links = merged; } @@ -42881,12 +44069,13 @@ var ts; return links.declaredType; } function getDeclaredTypeOfTypeAlias(symbol) { + var _a; var links = getSymbolLinks(symbol); if (!links.declaredType) { if (!pushTypeResolution(symbol, 2)) { return errorType; } - var declaration = ts.Debug.checkDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found"); + var declaration = ts.Debug.checkDefined((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias), "Type alias symbol with no valid declaration found"); var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; if (popTypeResolution()) { @@ -42909,7 +44098,7 @@ var ts; if (ts.isStringLiteralLike(expr)) { return true; } - else if (expr.kind === 216) { + else if (expr.kind === 217) { return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); } return false; @@ -42924,12 +44113,12 @@ var ts; case 8: case 14: return true; - case 214: + case 215: return expr.operator === 40 && expr.operand.kind === 8; case 78: return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); - case 216: + case 217: return isStringConcatExpression(expr); default: return false; @@ -42941,16 +44130,18 @@ var ts; return links.enumKind; } var hasNonLiteralMember = false; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 255) { - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - if (member.initializer && ts.isStringLiteralLike(member.initializer)) { - return links.enumKind = 1; - } - if (!isLiteralEnumMember(member)) { - hasNonLiteralMember = true; + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 256) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + if (member.initializer && ts.isStringLiteralLike(member.initializer)) { + return links.enumKind = 1; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; + } } } } @@ -42968,15 +44159,17 @@ var ts; if (getEnumKind(symbol) === 1) { enumCount++; var memberTypeList = []; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 255) { - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var value = getEnumMemberValue(member); - var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member))); - getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 256) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var value = getEnumMemberValue(member); + var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member))); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + } } } } @@ -43048,11 +44241,11 @@ var ts; case 113: case 150: case 141: - case 191: + case 192: return true; - case 178: + case 179: return isThislessType(node.elementType); - case 173: + case 174: return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; @@ -43068,7 +44261,7 @@ var ts; function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - return (node.kind === 166 || (!!returnType && isThislessType(returnType))) && + return (node.kind === 167 || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } @@ -43077,14 +44270,14 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { + case 164: case 163: - case 162: return isThislessVariableLikeDeclaration(declaration); - case 165: - case 164: case 166: + case 165: case 167: case 168: + case 169: return isThislessFunctionLikeDeclaration(declaration); } } @@ -43108,7 +44301,7 @@ var ts; } } function isStaticPrivateIdentifierProperty(s) { - return !!s.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(s.valueDeclaration) && ts.hasSyntacticModifier(s.valueDeclaration, 32); + return !!s.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(s.valueDeclaration) && ts.hasSyntacticModifier(s.valueDeclaration, 32); } function resolveDeclaredMembers(type) { if (!type.declaredProperties) { @@ -43144,8 +44337,8 @@ var ts; var name = ts.getNameOfDeclaration(node); return !!name && isLateBindableName(name); } - function hasNonBindableDynamicName(node) { - return ts.hasDynamicName(node) && !hasLateBindableName(node); + function hasBindableName(node) { + return !ts.hasDynamicName(node) || hasLateBindableName(node); } function isNonBindableDynamicName(node) { return ts.isDynamicName(node) && !isLateBindableName(node); @@ -43352,19 +44545,22 @@ var ts; sig.resolvedMinArgumentCount = undefined; sig.target = undefined; sig.mapper = undefined; - sig.unionSignatures = undefined; + sig.compositeSignatures = undefined; + sig.compositeKind = undefined; return sig; } function cloneSignature(sig) { var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, undefined, undefined, sig.minArgumentCount, sig.flags & 39); result.target = sig.target; result.mapper = sig.mapper; - result.unionSignatures = sig.unionSignatures; + result.compositeSignatures = sig.compositeSignatures; + result.compositeKind = sig.compositeKind; return result; } function createUnionSignature(signature, unionSignatures) { var result = cloneSignature(signature); - result.unionSignatures = unionSignatures; + result.compositeSignatures = unionSignatures; + result.compositeKind = 1048576; result.target = undefined; result.mapper = undefined; return result; @@ -43508,7 +44704,7 @@ var ts; if (signatures !== masterList) { var signature_1 = signatures[0]; ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); - results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters && !compareTypeParametersIdentical(signature_1.typeParameters, s.typeParameters); }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); }); + results = !!signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters && !compareTypeParametersIdentical(signature_1.typeParameters, s.typeParameters); }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); }); if (!results) { return "break"; } @@ -43525,9 +44721,12 @@ var ts; return result || ts.emptyArray; } function compareTypeParametersIdentical(sourceParams, targetParams) { - if (sourceParams.length !== targetParams.length) { + if (ts.length(sourceParams) !== ts.length(targetParams)) { return false; } + if (!sourceParams || !targetParams) { + return true; + } var mapper = createTypeMapper(targetParams, sourceParams); for (var i = 0; i < sourceParams.length; i++) { var source = sourceParams[i]; @@ -43598,9 +44797,10 @@ var ts; var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter, paramMapper); var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); var result = createSignature(declaration, typeParams, thisParam, params, undefined, undefined, minArgCount, (left.flags | right.flags) & 39); - result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); + result.compositeKind = 1048576; + result.compositeSignatures = ts.concatenate(left.compositeKind !== 2097152 && left.compositeSignatures || [left], [right]); if (paramMapper) { - result.mapper = left.mapper && left.unionSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; + result.mapper = left.compositeKind !== 2097152 && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; } return result; } @@ -43720,6 +44920,7 @@ var ts; else { var members = emptySymbols; var stringIndexInfo = void 0; + var numberIndexInfo = void 0; if (symbol.exports) { members = getExportsOfSymbol(symbol); if (symbol === globalThisSymbol) { @@ -43732,20 +44933,31 @@ var ts; members = varsOnly_1; } } + var baseConstructorIndexInfo = void 0; setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); if (symbol.flags & 32) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); if (baseConstructorType.flags & (524288 | 2097152 | 8650752)) { - members = ts.createSymbolTable(getNamedMembers(members)); + members = ts.createSymbolTable(getNamedOrIndexSignatureMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } else if (baseConstructorType === anyType) { - stringIndexInfo = createIndexInfo(anyType, false); + baseConstructorIndexInfo = createIndexInfo(anyType, false); + } + } + var indexSymbol = getIndexSymbolFromSymbolTable(members); + if (indexSymbol) { + stringIndexInfo = getIndexInfoOfIndexSymbol(indexSymbol, 0); + numberIndexInfo = getIndexInfoOfIndexSymbol(indexSymbol, 1); + } + else { + stringIndexInfo = baseConstructorIndexInfo; + if (symbol.flags & 384 && (getDeclaredTypeOfSymbol(symbol).flags & 32 || + ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296); }))) { + numberIndexInfo = enumNumberIndexInfo; } } - var numberIndexInfo = symbol.flags & 384 && (getDeclaredTypeOfSymbol(symbol).flags & 32 || - ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296); })) ? enumNumberIndexInfo : undefined; setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); if (symbol.flags & (16 | 8192)) { type.callSignatures = getSignaturesOfSymbol(symbol); @@ -43765,6 +44977,15 @@ var ts; } } } + function replaceIndexedAccess(instantiable, type, replacement) { + return instantiateType(instantiable, createTypeMapper([type.indexType, type.objectType], [getLiteralType(0), createTupleType([replacement])])); + } + function getIndexInfoOfIndexSymbol(indexSymbol, indexKind) { + var declaration = getIndexDeclarationOfIndexSymbol(indexSymbol, indexKind); + if (!declaration) + return undefined; + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasEffectiveModifier(declaration, 64), declaration); + } function resolveReverseMappedTypeMembers(type) { var indexInfo = getIndexInfoOfType(type.source, 0); var modifiers = getMappedTypeModifiers(type.mappedType); @@ -43779,8 +45000,18 @@ var ts; inferredProp.declarations = prop.declarations; inferredProp.nameType = getSymbolLinks(prop).nameType; inferredProp.propertyType = getTypeOfSymbol(prop); - inferredProp.mappedType = type.mappedType; - inferredProp.constraintType = type.constraintType; + if (type.constraintType.type.flags & 8388608 + && type.constraintType.type.objectType.flags & 262144 + && type.constraintType.type.indexType.flags & 262144) { + var newTypeParam = type.constraintType.type.objectType; + var newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type, newTypeParam); + inferredProp.mappedType = newMappedType; + inferredProp.constraintType = getIndexType(newTypeParam); + } + else { + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + } members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -43926,7 +45157,7 @@ var ts; } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); - return constraintDeclaration.kind === 188 && + return constraintDeclaration.kind === 189 && constraintDeclaration.operator === 138; } function getModifiersTypeFromMappedType(type) { @@ -43972,7 +45203,7 @@ var ts; else if (type.objectFlags & 3) { resolveClassOrInterfaceMembers(type); } - else if (type.objectFlags & 2048) { + else if (type.objectFlags & 1024) { resolveReverseMappedTypeMembers(type); } else if (type.objectFlags & 16) { @@ -44213,12 +45444,22 @@ var ts; if (t.flags & 3145728) { var types = t.types; var baseTypes = []; + var different = false; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type_3 = types_8[_i]; var baseType = getBaseConstraint(type_3); if (baseType) { + if (baseType !== type_3) { + different = true; + } baseTypes.push(baseType); } + else { + different = true; + } + } + if (!different) { + return t; } return t.flags & 1048576 && baseTypes.length === types.length ? getUnionType(baseTypes) : t.flags & 2097152 && baseTypes.length ? getIntersectionType(baseTypes) : @@ -44316,6 +45557,7 @@ var ts; return getReducedType(getApparentType(getReducedType(type))); } function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) { + var _a, _b; var singleProp; var propSet; var indexTypes; @@ -44323,8 +45565,9 @@ var ts; var optionalFlag = isUnion ? 0 : 16777216; var syntheticFlag = 4; var checkFlags = 0; - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var current = _a[_i]; + var mergedInstantiations = false; + for (var _i = 0, _c = containingType.types; _i < _c.length; _i++) { + var current = _c[_i]; var type = getApparentType(current); if (!(type === errorType || type.flags & 131072)) { var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); @@ -44340,13 +45583,19 @@ var ts; singleProp = prop; } else if (prop !== singleProp) { - if (!propSet) { - propSet = new ts.Map(); - propSet.set(getSymbolId(singleProp), singleProp); + var isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp); + if (isInstantiation && compareProperties(singleProp, prop, function (a, b) { return a === b ? -1 : 0; }) === -1) { + mergedInstantiations = !!singleProp.parent && !!ts.length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent)); } - var id = getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + else { + if (!propSet) { + propSet = new ts.Map(); + propSet.set(getSymbolId(singleProp), singleProp); + } + var id = getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } } checkFlags |= (isReadonlySymbol(prop) ? 8 : 0) | @@ -44364,7 +45613,7 @@ var ts; checkFlags |= 32 | (indexInfo.isReadonly ? 8 : 0); indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } - else if (isObjectLiteralType(type)) { + else if (isObjectLiteralType(type) && !(ts.getObjectFlags(type) & 4194304)) { checkFlags |= 32; indexTypes = ts.append(indexTypes, undefinedType); } @@ -44378,7 +45627,16 @@ var ts; return undefined; } if (!propSet && !(checkFlags & 16) && !indexTypes) { - return singleProp; + if (mergedInstantiations) { + var clone_1 = createSymbolWithType(singleProp, singleProp.type); + clone_1.parent = (_b = (_a = singleProp.valueDeclaration) === null || _a === void 0 ? void 0 : _a.symbol) === null || _b === void 0 ? void 0 : _b.parent; + clone_1.containingType = containingType; + clone_1.mapper = singleProp.mapper; + return clone_1; + } + else { + return singleProp; + } } var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; @@ -44387,8 +45645,8 @@ var ts; var propTypes = []; var firstValueDeclaration; var hasNonUniformValueDeclaration = false; - for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { - var prop = props_1[_b]; + for (var _d = 0, props_1 = props; _d < props_1.length; _d++) { + var prop = props_1[_d]; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } @@ -44451,15 +45709,15 @@ var ts; return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; } function getReducedType(type) { - if (type.flags & 1048576 && type.objectFlags & 268435456) { + if (type.flags & 1048576 && type.objectFlags & 67108864) { return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); } else if (type.flags & 2097152) { - if (!(type.objectFlags & 268435456)) { - type.objectFlags |= 268435456 | - (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 : 0); + if (!(type.objectFlags & 67108864)) { + type.objectFlags |= 67108864 | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 134217728 : 0); } - return type.objectFlags & 536870912 ? neverType : type; + return type.objectFlags & 134217728 ? neverType : type; } return type; } @@ -44486,7 +45744,7 @@ var ts; return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024); } function elaborateNeverIntersection(errorInfo, type) { - if (ts.getObjectFlags(type) & 536870912) { + if (type.flags & 2097152 && ts.getObjectFlags(type) & 134217728) { var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); if (neverProp) { return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, undefined, 536870912), symbolToString(neverProp)); @@ -44557,7 +45815,8 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var prop = _a[_i]; if (kind === 0 || isNumericLiteralName(prop.escapedName)) { - propTypes.push(getTypeOfSymbol(prop)); + var propType = getTypeOfSymbol(prop); + propTypes.push(prop.flags & 16777216 ? getTypeWithFacts(propType, 524288) : propType); } } if (kind === 0) { @@ -44587,10 +45846,10 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJSFile(node) && (node.type && node.type.kind === 307 + return ts.isInJSFile(node) && (node.type && node.type.kind === 308 || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 307; + return isBracketed || !!typeExpression && typeExpression.type.kind === 308; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -44618,12 +45877,15 @@ var ts; } return false; } + function isOptionalPropertyDeclaration(node) { + return ts.isPropertyDeclaration(node) && node.questionToken; + } function isOptionalJSDocPropertyLikeTag(node) { if (!ts.isJSDocPropertyLikeTag(node)) { return false; } var isBracketed = node.isBracketed, typeExpression = node.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 307; + return isBracketed || !!typeExpression && typeExpression.type.kind === 308; } function createTypePredicate(kind, parameterName, parameterIndex, type) { return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; @@ -44696,7 +45958,7 @@ var ts; else { parameters.push(paramSymbol); } - if (type && type.kind === 191) { + if (type && type.kind === 192) { flags |= 2; } var isOptionalParameter_1 = isOptionalJSDocPropertyLikeTag(param) || @@ -44707,16 +45969,16 @@ var ts; minArgumentCount = parameters.length; } } - if ((declaration.kind === 167 || declaration.kind === 168) && - !hasNonBindableDynamicName(declaration) && + if ((declaration.kind === 168 || declaration.kind === 169) && + hasBindableName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 167 ? 168 : 167; + var otherKind = declaration.kind === 168 ? 169 : 168; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 166 ? + var classType = declaration.kind === 167 ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); @@ -44752,8 +46014,7 @@ var ts; if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node))) return undefined; var typeTag = ts.getJSDocTypeTag(node); - var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); - return signature && getErasedSignature(signature); + return (typeTag === null || typeTag === void 0 ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); } function getReturnTypeOfTypeTag(node) { var signature = getSignatureOfTypeTag(node); @@ -44776,14 +46037,14 @@ var ts; switch (node.kind) { case 78: return node.escapedText === argumentsSymbol.escapedName && getResolvedSymbol(node) === argumentsSymbol; - case 163: - case 165: - case 167: + case 164: + case 166: case 168: - return node.name.kind === 158 + case 169: + return node.name.kind === 159 && traverse(node.name); - case 201: case 202: + case 203: return traverse(node.expression); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); @@ -44791,7 +46052,7 @@ var ts; } } function getSignaturesOfSymbol(symbol) { - if (!symbol) + if (!symbol || !symbol.declarations) return ts.emptyArray; var result = []; for (var i = 0; i < symbol.declarations.length; i++) { @@ -44829,8 +46090,8 @@ var ts; var targetTypePredicate = getTypePredicateOfSignature(signature.target); signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; } - else if (signature.unionSignatures) { - signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + else if (signature.compositeSignatures) { + signature.resolvedTypePredicate = getUnionOrIntersectionTypePredicate(signature.compositeSignatures, signature.compositeKind) || noTypePredicate; } else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); @@ -44852,17 +46113,20 @@ var ts; function createTypePredicateFromTypePredicateNode(node, signature) { var parameterName = node.parameterName; var type = node.type && getTypeFromTypeNode(node.type); - return parameterName.kind === 187 ? + return parameterName.kind === 188 ? createTypePredicate(node.assertsModifier ? 2 : 0, undefined, undefined, type) : createTypePredicate(node.assertsModifier ? 3 : 1, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type); } + function getUnionOrIntersectionType(types, kind, unionReduction) { + return kind !== 2097152 ? getUnionType(types, unionReduction) : getIntersectionType(types); + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3)) { return errorType; } var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : - signature.unionSignatures ? instantiateType(getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2), signature.mapper) : + signature.compositeSignatures ? instantiateType(getUnionOrIntersectionType(ts.map(signature.compositeSignatures, getReturnTypeOfSignature), signature.compositeKind, 2), signature.mapper) : getReturnTypeFromAnnotation(signature.declaration) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (signature.flags & 8) { @@ -44895,7 +46159,7 @@ var ts; return signature.resolvedReturnType; } function getReturnTypeFromAnnotation(declaration) { - if (declaration.kind === 166) { + if (declaration.kind === 167) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); } if (ts.isJSDocConstructSignature(declaration)) { @@ -44905,12 +46169,12 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 167 && !hasNonBindableDynamicName(declaration)) { + if (declaration.kind === 168 && hasBindableName(declaration)) { var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 168); + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 169); var setterType = getAnnotatedAccessorType(setter); if (setterType) { return setterType; @@ -44980,16 +46244,24 @@ var ts; function getBaseSignature(signature) { var typeParameters = signature.typeParameters; if (typeParameters) { - var typeEraser_1 = createTypeEraser(typeParameters); - var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || unknownType; }); - return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), true); + if (signature.baseSignatureCache) { + return signature.baseSignatureCache; + } + var typeEraser = createTypeEraser(typeParameters); + var baseConstraintMapper_1 = createTypeMapper(typeParameters, ts.map(typeParameters, function (tp) { return getConstraintOfTypeParameter(tp) || unknownType; })); + var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(tp, baseConstraintMapper_1) || unknownType; }); + for (var i = 0; i < typeParameters.length - 1; i++) { + baseConstraints = instantiateTypes(baseConstraints, baseConstraintMapper_1); + } + baseConstraints = instantiateTypes(baseConstraints, typeEraser); + return signature.baseSignatureCache = instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), true); } return signature; } function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { var kind = signature.declaration ? signature.declaration.kind : 0; - var isConstructor = kind === 166 || kind === 170 || kind === 175; + var isConstructor = kind === 167 || kind === 171 || kind === 176; var type = createObjectType(16); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -45000,12 +46272,22 @@ var ts; return signature.isolatedSignatureType; } function getIndexSymbol(symbol) { - return symbol.members.get("__index"); + return symbol.members ? getIndexSymbolFromSymbolTable(symbol.members) : undefined; + } + function getIndexSymbolFromSymbolTable(symbolTable) { + return symbolTable.get("__index"); } function getIndexDeclarationOfSymbol(symbol, kind) { + var indexSymbol = symbol && getIndexSymbol(symbol); + return indexSymbol && getIndexDeclarationOfIndexSymbol(indexSymbol, kind); + } + function getIndexDeclarationOfSymbolTable(symbolTable, kind) { + var indexSymbol = symbolTable && getIndexSymbolFromSymbolTable(symbolTable); + return indexSymbol && getIndexDeclarationOfIndexSymbol(indexSymbol, kind); + } + function getIndexDeclarationOfIndexSymbol(indexSymbol, kind) { var syntaxKind = kind === 1 ? 144 : 147; - var indexSymbol = getIndexSymbol(symbol); - if (indexSymbol) { + if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; var node = ts.cast(decl, ts.isIndexSignatureDeclaration); @@ -45033,13 +46315,14 @@ var ts; return ts.mapDefined(ts.filter(type.symbol && type.symbol.declarations, ts.isTypeParameterDeclaration), ts.getEffectiveConstraintOfTypeParameter)[0]; } function getInferredTypeParameterConstraint(typeParameter) { + var _a; var inferences; - if (typeParameter.symbol) { - for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.parent.kind === 185) { - var _b = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _c = _b[0], childTypeParameter = _c === void 0 ? declaration.parent : _c, grandParent = _b[1]; - if (grandParent.kind === 173) { + if ((_a = typeParameter.symbol) === null || _a === void 0 ? void 0 : _a.declarations) { + for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (declaration.parent.kind === 186) { + var _c = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _d = _c[0], childTypeParameter = _d === void 0 ? declaration.parent : _d, grandParent = _c[1]; + if (grandParent.kind === 174) { var typeReference = grandParent; var typeParameters = getTypeParametersForTypeReference(typeReference); if (typeParameters) { @@ -45056,17 +46339,25 @@ var ts; } } } - else if (grandParent.kind === 160 && grandParent.dotDotDotToken || - grandParent.kind === 181 || - grandParent.kind === 192 && grandParent.dotDotDotToken) { + else if (grandParent.kind === 161 && grandParent.dotDotDotToken || + grandParent.kind === 182 || + grandParent.kind === 193 && grandParent.dotDotDotToken) { inferences = ts.append(inferences, createArrayType(unknownType)); } - else if (grandParent.kind === 194) { + else if (grandParent.kind === 195) { inferences = ts.append(inferences, stringType); } - else if (grandParent.kind === 159 && grandParent.parent.kind === 190) { + else if (grandParent.kind === 160 && grandParent.parent.kind === 191) { inferences = ts.append(inferences, keyofConstraintType); } + else if (grandParent.kind === 191 && grandParent.type && + ts.skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 185 && + grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 191 && + grandParent.parent.checkType.type) { + var checkMappedType_1 = grandParent.parent.checkType; + var nodeType = getTypeFromTypeNode(checkMappedType_1.type); + inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); + } } } } @@ -45086,7 +46377,7 @@ var ts; else { var type = getTypeFromTypeNode(constraintDeclaration); if (type.flags & 1 && type !== errorType) { - type = constraintDeclaration.parent.parent.kind === 190 ? keyofConstraintType : unknownType; + type = constraintDeclaration.parent.parent.kind === 191 ? keyofConstraintType : unknownType; } typeParameter.constraint = type; } @@ -45095,7 +46386,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - var tp = ts.getDeclarationOfKind(typeParameter.symbol, 159); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 160); var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; return host && getSymbolOfNode(host); } @@ -45122,6 +46413,9 @@ var ts; } return result; } + function getAliasId(aliasSymbol, aliasTypeArguments) { + return aliasSymbol ? "@" + getSymbolId(aliasSymbol) + (aliasTypeArguments ? ":" + getTypeListId(aliasTypeArguments) : "") : ""; + } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { @@ -45130,7 +46424,7 @@ var ts; result |= ts.getObjectFlags(type); } } - return result & 3670016; + return result & 917504; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -45152,15 +46446,18 @@ var ts; type.resolvedTypeArguments = source.resolvedTypeArguments; return type; } - function createDeferredTypeReference(target, node, mapper) { - var aliasSymbol = getAliasSymbolForTypeNode(node); - var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + function createDeferredTypeReference(target, node, mapper, aliasSymbol, aliasTypeArguments) { + if (!aliasSymbol) { + aliasSymbol = getAliasSymbolForTypeNode(node); + var localAliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + aliasTypeArguments = mapper ? instantiateTypes(localAliasTypeArguments, mapper) : localAliasTypeArguments; + } var type = createObjectType(4, target.symbol); type.target = target; type.node = node; type.mapper = mapper; type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = mapper ? instantiateTypes(aliasTypeArguments, mapper) : aliasTypeArguments; + type.aliasTypeArguments = aliasTypeArguments; return type; } function getTypeArguments(type) { @@ -45171,8 +46468,8 @@ var ts; } var node = type.node; var typeArguments = !node ? ts.emptyArray : - node.kind === 173 ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : - node.kind === 178 ? [getTypeFromTypeNode(node.elementType)] : + node.kind === 174 ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : + node.kind === 179 ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); if (popTypeResolution()) { type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; @@ -45210,7 +46507,7 @@ var ts; return errorType; } } - if (node.kind === 173 && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) { + if (node.kind === 174 && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) { return createDeferredTypeReference(type, node, undefined); } var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs)); @@ -45218,17 +46515,17 @@ var ts; } return checkNoTypeArguments(node, symbol) ? type : errorType; } - function getTypeAliasInstantiation(symbol, typeArguments) { + function getTypeAliasInstantiation(symbol, typeArguments, aliasSymbol, aliasTypeArguments) { var type = getDeclaredTypeOfSymbol(symbol); if (type === intrinsicMarkerType && intrinsicTypeKinds.has(symbol.escapedName) && typeArguments && typeArguments.length === 1) { return getStringMappingType(symbol, typeArguments[0]); } var links = getSymbolLinks(symbol); var typeParameters = links.typeParameters; - var id = getTypeListId(typeArguments); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments)); } return instantiation; } @@ -45244,15 +46541,22 @@ var ts; ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return errorType; } - return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node)); + var aliasSymbol = getAliasSymbolForTypeNode(node); + var newAliasSymbol = aliasSymbol && (isLocalTypeAlias(symbol) || !isLocalTypeAlias(aliasSymbol)) ? aliasSymbol : undefined; + return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), newAliasSymbol, getTypeArgumentsForAliasSymbol(newAliasSymbol)); } return checkNoTypeArguments(node, symbol) ? type : errorType; } + function isLocalTypeAlias(symbol) { + var _a; + var declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias); + return !!(declaration && ts.getContainingFunction(declaration)); + } function getTypeReferenceName(node) { switch (node.kind) { - case 173: + case 174: return node.typeName; - case 223: + case 224: var expr = node.expression; if (ts.isEntityNameExpression(expr)) { return expr; @@ -45299,7 +46603,7 @@ var ts; var valueType = getTypeOfSymbol(symbol); var typeType = valueType; if (symbol.valueDeclaration) { - var isImportTypeWithQualifier = node.kind === 195 && node.qualifier; + var isImportTypeWithQualifier = node.kind === 196 && node.qualifier; if (valueType.symbol && valueType.symbol !== symbol && isImportTypeWithQualifier) { typeType = getTypeReferenceType(node, valueType.symbol); } @@ -45324,7 +46628,7 @@ var ts; return result; } function isUnaryTupleTypeNode(node) { - return node.kind === 179 && node.elements.length === 1; + return node.kind === 180 && node.elements.length === 1; } function getImpliedConstraint(type, checkNode, extendsNode) { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elements[0], extendsNode.elements[0]) : @@ -45333,9 +46637,13 @@ var ts; } function getConditionalFlowTypeOfType(type, node) { var constraints; - while (node && !ts.isStatement(node) && node.kind !== 311) { + var covariant = true; + while (node && !ts.isStatement(node) && node.kind !== 312) { var parent = node.parent; - if (parent.kind === 184 && node === parent.trueType) { + if (parent.kind === 161) { + covariant = !covariant; + } + if ((covariant || type.flags & 8650752) && parent.kind === 185 && node === parent.trueType) { var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -45346,7 +46654,7 @@ var ts; return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type; } function isJSDocTypeReference(node) { - return !!(node.flags & 4194304) && (node.kind === 173 || node.kind === 195); + return !!(node.flags & 4194304) && (node.kind === 174 || node.kind === 196); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -45449,13 +46757,15 @@ var ts; function getTypeOfGlobalSymbol(symbol, arity) { function getTypeDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { - var declaration = declarations_3[_i]; - switch (declaration.kind) { - case 252: - case 253: - case 255: - return declaration; + if (declarations) { + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; + switch (declaration.kind) { + case 253: + case 254: + case 256: + return declaration; + } } } } @@ -45498,6 +46808,9 @@ var ts; function getGlobalESSymbolConstructorSymbol(reportErrors) { return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); } + function getGlobalESSymbolConstructorTypeSymbol(reportErrors) { + return deferredGlobalESSymbolConstructorTypeSymbol || (deferredGlobalESSymbolConstructorTypeSymbol = getGlobalTypeSymbol("SymbolConstructor", reportErrors)); + } function getGlobalESSymbolType(reportErrors) { return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", 0, reportErrors)) || emptyObjectType; } @@ -45571,11 +46884,11 @@ var ts; } function getTupleElementFlags(node) { switch (node.kind) { - case 180: - return 2; case 181: + return 2; + case 182: return getRestTypeElementFlags(node); - case 192: + case 193: return node.questionToken ? 2 : node.dotDotDotToken ? getRestTypeElementFlags(node) : 1; @@ -45593,57 +46906,57 @@ var ts; return readonly ? globalReadonlyArrayType : globalArrayType; } var elementFlags = ts.map(node.elements, getTupleElementFlags); - var missingName = ts.some(node.elements, function (e) { return e.kind !== 192; }); + var missingName = ts.some(node.elements, function (e) { return e.kind !== 193; }); return getTupleTargetType(elementFlags, readonly, missingName ? undefined : node.elements); } function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) { - return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 178 ? mayResolveTypeAlias(node.elementType) : - node.kind === 179 ? ts.some(node.elements, mayResolveTypeAlias) : + return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 179 ? mayResolveTypeAlias(node.elementType) : + node.kind === 180 ? ts.some(node.elements, mayResolveTypeAlias) : hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias)); } function isResolvedByTypeAlias(node) { var parent = node.parent; switch (parent.kind) { - case 186: - case 192: - case 173: - case 182: + case 187: + case 193: + case 174: case 183: - case 189: case 184: - case 188: - case 178: + case 190: + case 185: + case 189: case 179: + case 180: return isResolvedByTypeAlias(parent); - case 254: + case 255: return true; } return false; } function mayResolveTypeAlias(node) { switch (node.kind) { - case 173: + case 174: return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node.typeName, 788968).flags & 524288); - case 176: + case 177: return true; - case 188: + case 189: return node.operator !== 151 && mayResolveTypeAlias(node.type); - case 186: - case 180: - case 192: - case 307: - case 305: + case 187: + case 181: + case 193: + case 308: case 306: - case 301: + case 307: + case 302: return mayResolveTypeAlias(node.type); - case 181: - return node.type.kind !== 178 || mayResolveTypeAlias(node.type.elementType); case 182: + return node.type.kind !== 179 || mayResolveTypeAlias(node.type.elementType); case 183: + case 184: return ts.some(node.types, mayResolveTypeAlias); - case 189: + case 190: return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType); - case 184: + case 185: return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) || mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType); } @@ -45656,12 +46969,12 @@ var ts; if (target === emptyGenericType) { links.resolvedType = emptyObjectType; } - else if (!(node.kind === 179 && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8); })) && isDeferredTypeReferenceNode(node)) { - links.resolvedType = node.kind === 179 && node.elements.length === 0 ? target : + else if (!(node.kind === 180 && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8); })) && isDeferredTypeReferenceNode(node)) { + links.resolvedType = node.kind === 180 && node.elements.length === 0 ? target : createDeferredTypeReference(target, node, undefined); } else { - var elementTypes = node.kind === 178 ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); + var elementTypes = node.kind === 179 ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); links.resolvedType = createNormalizedTypeReference(target, elementTypes); } } @@ -45777,7 +47090,14 @@ var ts; addElement(type, 8, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]); } else if (isTupleType(type)) { - ts.forEach(getTypeArguments(type), function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); + var elements = getTypeArguments(type); + if (elements.length + expandedTypes.length >= 10000) { + error(currentNode, ts.isPartOfTypeNode(currentNode) + ? ts.Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent + : ts.Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent); + return { value: errorType }; + } + ts.forEach(elements, function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); } else { addElement(isArrayLikeType(type) && getIndexTypeOfType(type, 1) || errorType, 4, (_b = target.labeledElementDeclarations) === null || _b === void 0 ? void 0 : _b[i]); @@ -45788,7 +47108,9 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - _loop_13(i); + var state_4 = _loop_13(i); + if (typeof state_4 === "object") + return state_4.value; } for (var i = 0; i < lastRequiredIndex; i++) { if (expandedFlags[i] & 2) @@ -45871,7 +47193,7 @@ var ts; if (type === wildcardType) includes |= 8388608; if (!strictNullChecks && flags & 98304) { - if (!(ts.getObjectFlags(type) & 524288)) + if (!(ts.getObjectFlags(type) & 131072)) includes |= 4194304; } else { @@ -45891,62 +47213,66 @@ var ts; } return includes; } - function isSetOfLiteralsFromSameEnum(types) { - var first = types[0]; - if (first.flags & 1024) { - var firstEnum = getParentOfSymbol(first.symbol); - for (var i = 1; i < types.length; i++) { - var other = types[i]; - if (!(other.flags & 1024) || (firstEnum !== getParentOfSymbol(other.symbol))) { - return false; - } - } - return true; + function removeSubtypes(types, hasObjectTypes) { + var id = getTypeListId(types); + var match = subtypeReductionCache.get(id); + if (match) { + return match; } - return false; - } - function removeSubtypes(types, primitivesOnly) { + var hasEmptyObject = hasObjectTypes && ts.some(types, function (t) { return !!(t.flags & 524288) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t)); }); var len = types.length; - if (len === 0 || isSetOfLiteralsFromSameEnum(types)) { - return true; - } var i = len; var count = 0; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var target = types_11[_i]; - if (source !== target) { - if (count === 100000) { - var estimatedCount = (count / (len - i)) * len; - if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) { - ts.tracing.instant("checkTypes", "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); - error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); - return false; + if (hasEmptyObject || source.flags & 469499904) { + var keyProperty = source.flags & (524288 | 2097152 | 58982400) ? + ts.find(getPropertiesOfType(source), function (p) { return isUnitType(getTypeOfSymbol(p)); }) : + undefined; + var keyPropertyType = keyProperty && getRegularTypeOfLiteralType(getTypeOfSymbol(keyProperty)); + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var target = types_11[_i]; + if (source !== target) { + if (count === 100000) { + var estimatedCount = (count / (len - i)) * len; + if (estimatedCount > 1000000) { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes", "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); + error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); + return undefined; + } + } + count++; + if (keyProperty && target.flags & (524288 | 2097152 | 58982400)) { + var t = getTypeOfPropertyOfType(target, keyProperty.escapedName); + if (t && isUnitType(t) && getRegularTypeOfLiteralType(t) !== keyPropertyType) { + continue; + } + } + if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1) || + !(ts.getObjectFlags(getTargetType(target)) & 1) || + isTypeDerivedFrom(source, target))) { + ts.orderedRemoveItemAt(types, i); + break; } - } - count++; - if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1) || - !(ts.getObjectFlags(getTargetType(target)) & 1) || - isTypeDerivedFrom(source, target))) { - ts.orderedRemoveItemAt(types, i); - break; } } } } - return true; + subtypeReductionCache.set(id, types); + return types; } - function removeRedundantLiteralTypes(types, includes) { + function removeRedundantLiteralTypes(types, includes, reduceVoidUndefined) { var i = types.length; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 134217856 && includes & 4 || - t.flags & 256 && includes & 8 || - t.flags & 2048 && includes & 64 || - t.flags & 8192 && includes & 4096 || + var flags = t.flags; + var remove = flags & 128 && includes & 4 || + flags & 256 && includes & 8 || + flags & 2048 && includes & 64 || + flags & 8192 && includes & 4096 || + reduceVoidUndefined && flags & 32768 && includes & 16384 || isFreshLiteralType(t) && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); @@ -45978,7 +47304,7 @@ var ts; if (t.flags & 1048576) { var origin = t.origin; if (t.aliasSymbol || origin && !(origin.flags & 1048576)) { - namedUnions.push(t); + ts.pushIfUnique(namedUnions, t); } else if (origin && origin.flags & 1048576) { addNamedUnions(namedUnions, origin.types); @@ -46005,20 +47331,17 @@ var ts; if (includes & 3) { return includes & 1 ? includes & 8388608 ? wildcardType : anyType : unknownType; } - switch (unionReduction) { - case 1: - if (includes & (134220672 | 8192)) { - removeRedundantLiteralTypes(typeSet, includes); - } - if (includes & 128 && includes & 134217728) { - removeStringLiteralsMatchedByTemplateLiterals(typeSet); - } - break; - case 2: - if (!removeSubtypes(typeSet, !(includes & 262144))) { - return errorType; - } - break; + if (includes & (2944 | 8192) || includes & 16384 && includes & 32768) { + removeRedundantLiteralTypes(typeSet, includes, !!(unionReduction & 2)); + } + if (includes & 128 && includes & 134217728) { + removeStringLiteralsMatchedByTemplateLiterals(typeSet); + } + if (unionReduction === 2) { + typeSet = removeSubtypes(typeSet, !!(includes & 524288)); + if (!typeSet) { + return errorType; + } } if (typeSet.length === 0) { return includes & 65536 ? includes & 4194304 ? nullType : nullWideningType : @@ -46051,18 +47374,23 @@ var ts; origin = createOriginUnionOrIntersectionType(1048576, reducedTypes); } } - var objectFlags = (includes & 468598819 ? 0 : 262144) | - (includes & 2097152 ? 268435456 : 0); + var objectFlags = (includes & 468598819 ? 0 : 65536) | + (includes & 2097152 ? 67108864 : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } - function getUnionTypePredicate(signatures) { + function getUnionOrIntersectionTypePredicate(signatures, kind) { var first; var types = []; for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { var sig = signatures_6[_i]; var pred = getTypePredicateOfSignature(sig); if (!pred || pred.kind === 2 || pred.kind === 3) { - continue; + if (kind !== 2097152) { + continue; + } + else { + return; + } } if (first) { if (!typePredicateKindsMatch(first, pred)) { @@ -46077,8 +47405,8 @@ var ts; if (!first) { return undefined; } - var unionType = getUnionType(types); - return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, unionType); + var compositeType = getUnionOrIntersectionType(types, kind); + return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, compositeType); } function typePredicateKindsMatch(a, b) { return a.kind === b.kind && a.parameterIndex === b.parameterIndex; @@ -46102,8 +47430,8 @@ var ts; var typeKey = !origin ? getTypeListId(types) : origin.flags & 1048576 ? "|" + getTypeListId(origin.types) : origin.flags & 2097152 ? "&" + getTypeListId(origin.types) : - "#" + origin.type.id; - var id = typeKey + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + "#" + origin.type.id + "|" + getTypeListId(types); + var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { type = createUnionType(types, aliasSymbol, aliasTypeArguments, origin); @@ -46215,14 +47543,14 @@ var ts; } function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144); }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536); }); if (index < 0) { return false; } var i = index + 1; while (i < types.length) { var t = types[i]; - if (ts.getObjectFlags(t) & 262144) { + if (ts.getObjectFlags(t) & 65536) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -46246,7 +47574,7 @@ var ts; } } } - types[index] = getUnionTypeFromSortedList(result, 262144); + types[index] = getUnionTypeFromSortedList(result, 65536); return true; } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { @@ -46295,7 +47623,7 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } - var id = getTypeListId(typeSet) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeSet) + getAliasId(aliasSymbol, aliasTypeArguments); var result = intersectionTypes.get(id); if (!result) { if (includes & 1048576) { @@ -46330,7 +47658,7 @@ var ts; function checkCrossProductUnion(types) { var size = getCrossProductUnionSize(types); if (size >= 100000) { - ts.tracing.instant("checkTypes", "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes", "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); return false; } @@ -46380,11 +47708,15 @@ var ts; type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, false)); } + function instantiateTypeAsMappedNameType(nameType, type, t) { + return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); + } function getIndexTypeForMappedType(type, noIndexSignatures) { var constraint = filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 | 4)); }); var nameType = type.declaration.nameType && getTypeFromTypeNode(type.declaration.nameType); + var properties = nameType && everyType(constraint, function (t) { return !!(t.flags & (4 | 8 | 131072)); }) && getPropertiesOfType(getApparentType(getModifiersTypeFromMappedType(type))); return nameType ? - mapType(constraint, function (t) { return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); }) : + getUnionType([mapType(constraint, function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); }), mapType(getUnionType(ts.map(properties || ts.emptyArray, function (p) { return getLiteralTypeFromProperty(p, 8576); })), function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); })]) : constraint; } function maybeNonDistributiveNameType(type) { @@ -46410,13 +47742,13 @@ var ts; function getLiteralTypeFromProperty(prop, include) { if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24)) { var type = getSymbolLinks(getLateBoundSymbol(prop)).nameType; - if (!type && !ts.isKnownSymbol(prop)) { + if (!type) { if (prop.escapedName === "default") { type = getLiteralType("default"); } else { var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); - type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + type = name && getLiteralTypeFromPropertyName(name) || (!ts.isKnownSymbol(prop) ? getLiteralType(ts.symbolName(prop)) : undefined); } } if (type && type.flags & include) { @@ -46515,7 +47847,6 @@ var ts; var type = templateLiteralTypes.get(id); if (!type) { templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes)); - type.regularType = type; } return type; function addSpans(texts, types) { @@ -46547,10 +47878,8 @@ var ts; return type.flags & 128 ? type.value : type.flags & 256 ? "" + type.value : type.flags & 2048 ? ts.pseudoBigIntToString(type.value) : - type.flags & 512 ? type.intrinsicName : - type.flags & 65536 ? "null" : - type.flags & 32768 ? "undefined" : - undefined; + type.flags & (512 | 98304) ? type.intrinsicName : + undefined; } function createTemplateLiteralType(texts, types) { var type = createType(134217728); @@ -46600,7 +47929,7 @@ var ts; if (noImplicitAny) { return false; } - if (ts.getObjectFlags(type) & 16384) { + if (ts.getObjectFlags(type) & 8192) { return true; } if (type.flags & 1048576) { @@ -46610,19 +47939,17 @@ var ts; return ts.some(type.types, isJSLiteralType); } if (type.flags & 465829888) { - return isJSLiteralType(getResolvedBaseConstraint(type)); + var constraint = getResolvedBaseConstraint(type); + return constraint !== type && isJSLiteralType(constraint); } return false; } function getPropertyNameFromIndex(indexType, accessNode) { - var accessExpression = accessNode && accessNode.kind === 202 ? accessNode : undefined; return isTypeUsableAsPropertyName(indexType) ? getPropertyNameFromType(indexType) : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? - ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : - accessNode && ts.isPropertyName(accessNode) ? - ts.getPropertyNameForPropertyNameNode(accessNode) : - undefined; + accessNode && ts.isPropertyName(accessNode) ? + ts.getPropertyNameForPropertyNameNode(accessNode) : + undefined; } function isUncalledFunctionReference(node, symbol) { if (symbol.flags & (16 | 8192)) { @@ -46636,17 +47963,17 @@ var ts; } function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, suppressNoImplicitAnyError, accessNode, accessFlags, noUncheckedIndexedAccessCandidate, reportDeprecated) { var _a; - var accessExpression = accessNode && accessNode.kind === 202 ? accessNode : undefined; + var accessExpression = accessNode && accessNode.kind === 203 ? accessNode : undefined; var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode); if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { - if (reportDeprecated && accessNode && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 && isUncalledFunctionReference(accessNode, prop)) { + if (reportDeprecated && accessNode && prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 && isUncalledFunctionReference(accessNode, prop)) { var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); - errorOrSuggestion(false, deprecatedNode, ts.Diagnostics._0_is_deprecated, propName); + addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName); } if (accessExpression) { - markPropertyAsReferenced(prop, accessExpression, accessExpression.expression.kind === 107); + markPropertyAsReferenced(prop, accessExpression, isSelfTypeAccess(accessExpression.expression, objectType.symbol)); if (isAssignmentToReadonlyEntity(accessExpression, prop, ts.getAssignmentTargetKind(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); return undefined; @@ -46796,13 +48123,13 @@ var ts; } } function getIndexNodeForAccessExpression(accessNode) { - return accessNode.kind === 202 ? accessNode.argumentExpression : - accessNode.kind === 189 ? accessNode.indexType : - accessNode.kind === 158 ? accessNode.expression : + return accessNode.kind === 203 ? accessNode.argumentExpression : + accessNode.kind === 190 ? accessNode.indexType : + accessNode.kind === 159 ? accessNode.expression : accessNode; } function isPatternLiteralPlaceholderType(type) { - return templateConstraintType.types.indexOf(type) !== -1 || !!(type.flags & 1); + return !!(type.flags & (1 | 4 | 8 | 64)); } function isPatternLiteralType(type) { return !!(type.flags & 134217728) && ts.every(type.types, isPatternLiteralPlaceholderType); @@ -46815,6 +48142,13 @@ var ts; } return !!(type.objectFlags & 8388608); } + if (type.flags & 33554432) { + if (!(type.objectFlags & 4194304)) { + type.objectFlags |= 4194304 | + (isGenericObjectType(type.substitute) || isGenericObjectType(type.baseType) ? 8388608 : 0); + } + return !!(type.objectFlags & 8388608); + } return !!(type.flags & 58982400) || isGenericMappedType(type) || isGenericTupleType(type); } function isGenericIndexType(type) { @@ -46825,6 +48159,13 @@ var ts; } return !!(type.objectFlags & 33554432); } + if (type.flags & 33554432) { + if (!(type.objectFlags & 16777216)) { + type.objectFlags |= 16777216 | + (isGenericIndexType(type.substitute) || isGenericIndexType(type.baseType) ? 33554432 : 0); + } + return !!(type.objectFlags & 33554432); + } return !!(type.flags & (58982400 | 4194304 | 134217728 | 268435456)) && !isPatternLiteralType(type); } function isThisTypeParameter(type) { @@ -46876,6 +48217,12 @@ var ts; } return type[cache] = type; } + function isConditionalTypeAlwaysTrueDisregardingInferTypes(type) { + var extendsInferParamMapper = type.root.inferTypeParameters && createTypeMapper(type.root.inferTypeParameters, ts.map(type.root.inferTypeParameters, function () { return wildcardType; })); + var checkType = type.checkType; + var extendsType = type.extendsType; + return isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(instantiateType(extendsType, extendsInferParamMapper))); + } function getSimplifiedConditionalType(type, writing) { var checkType = type.checkType; var extendsType = type.extendsType; @@ -46934,13 +48281,13 @@ var ts; if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & 98304) && isTypeAssignableToKind(indexType, 4 | 8)) { indexType = stringType; } - if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 189 ? + if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 190 ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, objectType.target.fixedLength) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, objectType.target.fixedLength)))) { if (objectType.flags & 3) { return objectType; } - var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + getAliasId(aliasSymbol, aliasTypeArguments); var type = indexedAccessTypes.get(id); if (!type) { indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined)); @@ -47009,13 +48356,24 @@ var ts; } return type; } - function getConditionalType(root, mapper) { + function isTypicalNondistributiveConditional(root) { + return !root.isDistributive + && root.node.checkType.kind === 180 + && ts.length(root.node.checkType.elements) === 1 + && root.node.extendsType.kind === 180 + && ts.length(root.node.extendsType.elements) === 1; + } + function unwrapNondistributiveConditionalTuple(root, type) { + return isTypicalNondistributiveConditional(root) && isTupleType(type) ? getTypeArguments(type)[0] : type; + } + function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { var result; var extraTypes; while (true) { - var checkType = instantiateType(root.checkType, mapper); + var isUnwrapped = isTypicalNondistributiveConditional(root); + var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); - var extendsType = instantiateType(root.extendsType, mapper); + var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } @@ -47023,14 +48381,14 @@ var ts; if (root.inferTypeParameters) { var context = createInferenceContext(root.inferTypeParameters, undefined, 0); if (!checkTypeInstantiable) { - inferTypes(context.inferences, checkType, extendsType, 256 | 512); + inferTypes(context.inferences, checkType, extendsType, 512 | 1024); } - combinedMapper = mergeTypeMappers(mapper, context.mapper); + combinedMapper = mapper ? combineTypeMappers(context.mapper, mapper) : context.mapper; } - var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + var inferredExtendsType = combinedMapper ? instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), combinedMapper) : extendsType; if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) { - if (!(inferredExtendsType.flags & 3) && (checkType.flags & 1 || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { - if (checkType.flags & 1) { + if (!(inferredExtendsType.flags & 3) && ((checkType.flags & 1 && !isUnwrapped) || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { + if (checkType.flags & 1 && !isUnwrapped) { (extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper)); } var falseType_1 = getTypeFromTypeNode(root.node.falseType); @@ -47051,12 +48409,12 @@ var ts; } result = createType(16777216); result.root = root; - result.checkType = checkType; - result.extendsType = extendsType; + result.checkType = instantiateType(root.checkType, mapper); + result.extendsType = instantiateType(root.extendsType, mapper); result.mapper = mapper; result.combinedMapper = combinedMapper; - result.aliasSymbol = root.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); + result.aliasSymbol = aliasSymbol || root.aliasSymbol; + result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(root.aliasTypeArguments, mapper); break; } return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result; @@ -47255,7 +48613,7 @@ var ts; } } var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0), getIndexInfoOfType(type, 1)); - spread.objectFlags |= 128 | 1048576; + spread.objectFlags |= 128 | 262144; return spread; } } @@ -47352,13 +48710,14 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.objectFlags |= 128 | 1048576 | 1024 | objectFlags; + spread.objectFlags |= 128 | 262144 | 4194304 | objectFlags; return spread; } function isSpreadableProperty(prop) { - return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) && + var _a; + return !ts.some(prop.declarations, ts.isPrivateIdentifierClassElementDeclaration) && (!(prop.flags & (8192 | 32768 | 65536)) || - !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); })); + !((_a = prop.declarations) === null || _a === void 0 ? void 0 : _a.some(function (decl) { return ts.isClassLike(decl.parent); }))); } function getSpreadSymbol(prop, readonly) { var isSetonlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); @@ -47383,11 +48742,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 134220672) { + if (type.flags & 2944) { if (!type.freshType) { - var freshType = type.flags & 134217728 ? - createTemplateLiteralType(type.texts, type.types) : - createLiteralType(type.flags, type.value, type.symbol); + var freshType = createLiteralType(type.flags, type.value, type.symbol); freshType.regularType = type; freshType.freshType = freshType; type.freshType = freshType; @@ -47397,12 +48754,12 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 134220672 ? type.regularType : + return type.flags & 2944 ? type.regularType : type.flags & 1048576 ? (type.regularType || (type.regularType = mapType(type, getRegularTypeOfLiteralType))) : type; } function isFreshLiteralType(type) { - return !!(type.flags & 134220672) && type.freshType === type; + return !!(type.flags & 2944) && type.freshType === type; } function getLiteralType(value, enumId, symbol) { var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n"; @@ -47444,7 +48801,7 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 253)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 254)) { if (!ts.hasSyntacticModifier(container, 32) && (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; @@ -47475,17 +48832,17 @@ var ts; } function getArrayElementTypeNode(node) { switch (node.kind) { - case 186: + case 187: return getArrayElementTypeNode(node.type); - case 179: + case 180: if (node.elements.length === 1) { node = node.elements[0]; - if (node.kind === 181 || node.kind === 192 && node.dotDotDotToken) { + if (node.kind === 182 || node.kind === 193 && node.dotDotDotToken) { return getArrayElementTypeNode(node.type); } } break; - case 178: + case 179: return node.elementType; } return undefined; @@ -47503,8 +48860,8 @@ var ts; function getTypeFromTypeNodeWorker(node) { switch (node.kind) { case 128: - case 303: case 304: + case 305: return anyType; case 152: return unknownType; @@ -47530,66 +48887,66 @@ var ts; return node.flags & 131072 && !noImplicitAny ? anyType : nonPrimitiveType; case 136: return intrinsicMarkerType; - case 187: + case 188: case 107: return getTypeFromThisTypeNode(node); - case 191: + case 192: return getTypeFromLiteralTypeNode(node); - case 173: + case 174: return getTypeFromTypeReference(node); - case 172: + case 173: return node.assertsModifier ? voidType : booleanType; - case 223: + case 224: return getTypeFromTypeReference(node); - case 176: + case 177: return getTypeFromTypeQueryNode(node); - case 178: case 179: - return getTypeFromArrayOrTupleTypeNode(node); case 180: + return getTypeFromArrayOrTupleTypeNode(node); + case 181: return getTypeFromOptionalTypeNode(node); - case 182: - return getTypeFromUnionTypeNode(node); case 183: + return getTypeFromUnionTypeNode(node); + case 184: return getTypeFromIntersectionTypeNode(node); - case 305: + case 306: return getTypeFromJSDocNullableTypeNode(node); - case 307: + case 308: return addOptionality(getTypeFromTypeNode(node.type)); - case 192: + case 193: return getTypeFromNamedTupleTypeNode(node); - case 186: - case 306: - case 301: + case 187: + case 307: + case 302: return getTypeFromTypeNode(node.type); - case 181: + case 182: return getTypeFromRestTypeNode(node); - case 309: + case 310: return getTypeFromJSDocVariadicType(node); - case 174: case 175: - case 177: - case 312: - case 308: - case 313: + case 176: + case 178: + case 314: + case 309: + case 315: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 188: - return getTypeFromTypeOperatorNode(node); case 189: - return getTypeFromIndexedAccessTypeNode(node); + return getTypeFromTypeOperatorNode(node); case 190: + return getTypeFromIndexedAccessTypeNode(node); + case 191: return getTypeFromMappedTypeNode(node); - case 184: - return getTypeFromConditionalTypeNode(node); case 185: + return getTypeFromConditionalTypeNode(node); + case 186: return getTypeFromInferTypeNode(node); - case 193: + case 194: return getTypeFromTemplateTypeNode(node); - case 195: + case 196: return getTypeFromImportTypeNode(node); case 78: - case 157: - case 201: + case 158: + case 202: var symbol = getSymbolAtLocation(node); return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: @@ -47723,7 +49080,7 @@ var ts; } return result; } - function getObjectTypeInstantiation(type, mapper) { + function getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { var declaration = type.objectFlags & 4 ? type.node : type.symbol.declarations[0]; var links = getNodeLinks(declaration); var target = type.objectFlags & 4 ? links.resolvedType : @@ -47736,25 +49093,28 @@ var ts; outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } typeParameters = outerTypeParameters || ts.emptyArray; - typeParameters = (target.objectFlags & 4 || target.symbol.flags & 2048) && !target.aliasTypeArguments ? - ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration); }) : + var allDeclarations_1 = type.objectFlags & 4 ? [declaration] : type.symbol.declarations; + typeParameters = (target.objectFlags & 4 || target.symbol.flags & 8192 || target.symbol.flags & 2048) && !target.aliasTypeArguments ? + ts.filter(typeParameters, function (tp) { return ts.some(allDeclarations_1, function (d) { return isTypeParameterPossiblyReferenced(tp, d); }); }) : typeParameters; links.outerTypeParameters = typeParameters; } if (typeParameters.length) { var combinedMapper_1 = combineTypeMappers(type.mapper, mapper); var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); }); - var id = getTypeListId(typeArguments); + var newAliasSymbol = aliasSymbol || type.aliasSymbol; + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + var id = getTypeListId(typeArguments) + getAliasId(newAliasSymbol, newAliasTypeArguments); if (!target.instantiations) { target.instantiations = new ts.Map(); - target.instantiations.set(getTypeListId(typeParameters), target); + target.instantiations.set(getTypeListId(typeParameters) + getAliasId(target.aliasSymbol, target.aliasTypeArguments), target); } var result = target.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(typeParameters, typeArguments); - result = target.objectFlags & 4 ? createDeferredTypeReference(type.target, type.node, newMapper) : - target.objectFlags & 32 ? instantiateMappedType(target, newMapper) : - instantiateAnonymousType(target, newMapper); + result = target.objectFlags & 4 ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) : + target.objectFlags & 32 ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) : + instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments); target.instantiations.set(id, result); } return result; @@ -47762,30 +49122,33 @@ var ts; return type; } function maybeTypeParameterReference(node) { - return !(node.kind === 157 || - node.parent.kind === 173 && node.parent.typeArguments && node === node.parent.typeName || - node.parent.kind === 195 && node.parent.typeArguments && node === node.parent.qualifier); + return !(node.kind === 158 || + node.parent.kind === 174 && node.parent.typeArguments && node === node.parent.typeName || + node.parent.kind === 196 && node.parent.typeArguments && node === node.parent.qualifier); } function isTypeParameterPossiblyReferenced(tp, node) { if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container = tp.symbol.declarations[0].parent; for (var n = node; n !== container; n = n.parent) { - if (!n || n.kind === 230 || n.kind === 184 && ts.forEachChild(n.extendsType, containsReference)) { + if (!n || n.kind === 231 || n.kind === 185 && ts.forEachChild(n.extendsType, containsReference)) { return true; } } - return !!ts.forEachChild(node, containsReference); + return containsReference(node); } return true; function containsReference(node) { switch (node.kind) { - case 187: + case 188: return !!tp.isThisType; case 78: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNodeWorker(node) === tp; - case 176: + case 177: return true; + case 166: + case 165: + return (!node.type && !!node.body) || !!ts.forEachChild(node, containsReference); } return !!ts.forEachChild(node, containsReference); } @@ -47800,12 +49163,12 @@ var ts; } return undefined; } - function instantiateMappedType(type, mapper) { + function instantiateMappedType(type, mapper, aliasSymbol, aliasTypeArguments) { var typeVariable = getHomomorphicTypeVariable(type); if (typeVariable) { var mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapType(getReducedType(mappedTypeVariable), function (t) { + return mapTypeWithAlias(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 | 58982400 | 524288 | 2097152) && t !== wildcardType && t !== errorType) { if (!type.declaration.nameType) { if (isArrayType(t)) { @@ -47821,10 +49184,10 @@ var ts; return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper)); } return t; - }); + }, aliasSymbol, aliasTypeArguments); } } - return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper); + return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments); } function getModifiedReadonlyState(state, modifiers) { return modifiers & 1 ? true : modifiers & 2 ? false : state; @@ -47866,7 +49229,7 @@ var ts; strictNullChecks && modifiers & 8 && isOptional ? getTypeWithFacts(propType, 524288) : propType; } - function instantiateAnonymousType(type, mapper) { + function instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments) { var result = createObjectType(type.objectFlags | 64, type.symbol); if (type.objectFlags & 32) { result.declaration = type.declaration; @@ -47878,52 +49241,55 @@ var ts; } result.target = type; result.mapper = mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + result.aliasSymbol = aliasSymbol || type.aliasSymbol; + result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); return result; } - function getConditionalTypeInstantiation(type, mapper) { + function getConditionalTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { var root = type.root; if (root.outerTypeParameters) { var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); }); - var id = getTypeListId(typeArguments); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var result = root.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); - result = instantiateConditionalType(root, newMapper); + result = instantiateConditionalType(root, newMapper, aliasSymbol, aliasTypeArguments); root.instantiations.set(id, result); } return result; } return type; } - function instantiateConditionalType(root, mapper) { + function instantiateConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { if (root.isDistributive) { var checkType_1 = root.checkType; var instantiatedType = getMappedType(checkType_1, mapper); if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 | 131072)) { - return mapType(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); }); + return mapTypeWithAlias(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); }, aliasSymbol, aliasTypeArguments); } } - return getConditionalType(root, mapper); + return getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments); } function instantiateType(type, mapper) { - if (!(type && mapper && couldContainTypeVariables(type))) { + return type && mapper ? instantiateTypeWithAlias(type, mapper, undefined, undefined) : type; + } + function instantiateTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) { + if (!couldContainTypeVariables(type)) { return type; } if (instantiationDepth === 50 || instantiationCount >= 5000000) { - ts.tracing.instant("checkTypes", "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes", "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); return errorType; } totalInstantiationCount++; instantiationCount++; instantiationDepth++; - var result = instantiateTypeWorker(type, mapper); + var result = instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments); instantiationDepth--; return result; } - function instantiateTypeWorker(type, mapper) { + function instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments) { var flags = type.flags; if (flags & 262144) { return getMappedType(type, mapper); @@ -47931,12 +49297,15 @@ var ts; if (flags & 524288) { var objectFlags = type.objectFlags; if (objectFlags & (4 | 16 | 32)) { - if (objectFlags & 4 && !(type.node)) { + if (objectFlags & 4 && !type.node) { var resolvedTypeArguments = type.resolvedTypeArguments; var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type; } - return getObjectTypeInstantiation(type, mapper); + if (objectFlags & 1024) { + return instantiateReverseMappedType(type, mapper); + } + return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments); } return type; } @@ -47944,10 +49313,14 @@ var ts; var origin = type.flags & 1048576 ? type.origin : undefined; var types = origin && origin.flags & 3145728 ? origin.types : type.types; var newTypes = instantiateTypes(types, mapper); - return newTypes === types ? type : - flags & 2097152 || origin && origin.flags & 2097152 ? - getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : - getUnionType(newTypes, 1, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + if (newTypes === types && aliasSymbol === type.aliasSymbol) { + return type; + } + var newAliasSymbol = aliasSymbol || type.aliasSymbol; + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + return flags & 2097152 || origin && origin.flags & 2097152 ? + getIntersectionType(newTypes, newAliasSymbol, newAliasTypeArguments) : + getUnionType(newTypes, 1, newAliasSymbol, newAliasTypeArguments); } if (flags & 4194304) { return getIndexType(instantiateType(type.type, mapper)); @@ -47959,10 +49332,12 @@ var ts; return getStringMappingType(type.symbol, instantiateType(type.type, mapper)); } if (flags & 8388608) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.noUncheckedIndexedAccessCandidate, undefined, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + var newAliasSymbol = aliasSymbol || type.aliasSymbol; + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.noUncheckedIndexedAccessCandidate, undefined, newAliasSymbol, newAliasTypeArguments); } if (flags & 16777216) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper), aliasSymbol, aliasTypeArguments); } if (flags & 33554432) { var maybeVariable = instantiateType(type.baseType, mapper); @@ -47979,6 +49354,21 @@ var ts; } return type; } + function instantiateReverseMappedType(type, mapper) { + var innerMappedType = instantiateType(type.mappedType, mapper); + if (!(ts.getObjectFlags(innerMappedType) & 32)) { + return type; + } + var innerIndexType = instantiateType(type.constraintType, mapper); + if (!(innerIndexType.flags & 4194304)) { + return type; + } + var instantiated = inferTypeForHomomorphicMappedType(instantiateType(type.source, mapper), innerMappedType, innerIndexType); + if (instantiated) { + return instantiated; + } + return type; + } function getPermissiveInstantiation(type) { return type.flags & (131068 | 3 | 131072) ? type : type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); @@ -47998,34 +49388,34 @@ var ts; return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); } function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 165 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 208: case 209: - case 165: - case 251: + case 210: + case 166: + case 252: return isContextSensitiveFunctionLikeDeclaration(node); - case 200: + case 201: return ts.some(node.properties, isContextSensitive); - case 199: + case 200: return ts.some(node.elements, isContextSensitive); - case 217: + case 218: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 216: + case 217: return (node.operatorToken.kind === 56 || node.operatorToken.kind === 60) && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 288: + case 289: return isContextSensitive(node.initializer); - case 207: + case 208: return isContextSensitive(node.expression); - case 281: + case 282: return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); - case 280: { + case 281: { var initializer = node.initializer; return !!initializer && isContextSensitive(initializer); } - case 283: { + case 284: { var expression = node.expression; return !!expression && isContextSensitive(expression); } @@ -48041,7 +49431,7 @@ var ts; if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 209) { + if (node.kind !== 210) { var parameter = ts.firstOrUndefined(node.parameters); if (!(parameter && ts.parameterIsThisKeyword(parameter))) { return true; @@ -48051,7 +49441,7 @@ var ts; return false; } function hasContextSensitiveReturnExpression(node) { - return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 230 && isContextSensitive(node.body); + return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 231 && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -48131,23 +49521,23 @@ var ts; return true; } switch (node.kind) { - case 283: - case 207: + case 284: + case 208: return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); - case 216: + case 217: switch (node.operatorToken.kind) { case 62: case 27: return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); } break; - case 200: + case 201: return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 199: + case 200: return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 281: + case 282: return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 209: + case 210: return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer); } return false; @@ -48334,16 +49724,16 @@ var ts; } function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) { switch (child.kind) { - case 283: + case 284: return { errorNode: child, innerExpression: child.expression, nameType: nameType }; case 11: if (child.containsOnlyTriviaWhiteSpaces) { break; } return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() }; - case 273: case 274: - case 277: + case 275: + case 278: return { errorNode: child, innerExpression: child, nameType: nameType }; default: return ts.Debug.assertNever(child, "Found invalid jsx child"); @@ -48485,11 +49875,11 @@ var ts; } _b = prop.kind; switch (_b) { + case 169: return [3, 2]; case 168: return [3, 2]; - case 167: return [3, 2]; - case 165: return [3, 2]; - case 289: return [3, 2]; - case 288: return [3, 4]; + case 166: return [3, 2]; + case 290: return [3, 2]; + case 289: return [3, 4]; } return [3, 6]; case 2: return [4, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; @@ -48553,8 +49943,8 @@ var ts; return 0; } var kind = target.declaration ? target.declaration.kind : 0; - var strictVariance = !(checkMode & 3) && strictFunctionTypes && kind !== 165 && - kind !== 164 && kind !== 166; + var strictVariance = !(checkMode & 3) && strictFunctionTypes && kind !== 166 && + kind !== 165 && kind !== 167; var result = -1; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { @@ -48767,7 +50157,7 @@ var ts; if (relation === assignableRelation || relation === comparableRelation) { if (s & 1) return true; - if (s & (8 | 256) && !(s & 1024) && (t & 32 || t & 256 && t & 1024)) + if (s & (8 | 256) && !(s & 1024) && (t & 32 || relation === assignableRelation && t & 256 && t & 1024)) return true; } return false; @@ -48804,7 +50194,7 @@ var ts; return false; } function isIgnoredJsxProperty(source, sourceProp) { - return ts.getObjectFlags(source) & 4096 && !isUnhyphenatedJsxName(sourceProp.escapedName); + return ts.getObjectFlags(source) & 2048 && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { while (true) { @@ -48814,6 +50204,7 @@ var ts; type.flags & 33554432 ? writing ? type.baseType : type.substitute : type.flags & 25165824 ? getSimplifiedType(type, writing) : type; + t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) break; type = t; @@ -48840,7 +50231,7 @@ var ts; reportIncompatibleStack(); } if (overflow) { - ts.tracing.instant("checkTypes", "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes", "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); @@ -48964,6 +50355,14 @@ var ts; } break; } + case ts.Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target.code: { + secondaryRootErrors.unshift([ts.Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target, args[0], args[1]]); + break; + } + case ts.Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target.code: { + secondaryRootErrors.unshift([ts.Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target, args[0], args[1], args[2]]); + break; + } default: return ts.Debug.fail("Unhandled Diagnostic: " + msg.code); } @@ -49022,6 +50421,7 @@ var ts; reportError(ts.Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2, needsOriginalSource ? sourceType : generalizedSourceType, targetType, typeToString(constraint)); } else { + errorInfo = undefined; reportError(ts.Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, generalizedSourceType); } } @@ -49076,7 +50476,7 @@ var ts; if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { return -1; } - reportErrorResults(originalSource, originalTarget, 0, !!(ts.getObjectFlags(originalSource) & 4096)); + reportErrorResults(originalSource, originalTarget, 0, !!(ts.getObjectFlags(originalSource) & 2048)); return 0; } var source = getNormalizedType(originalSource, false); @@ -49093,16 +50493,16 @@ var ts; target.types.length <= 3 && maybeTypeOfKind(target, 98304)) { var nullStrippedTarget = extractTypesOfKind(target, ~98304); if (!(nullStrippedTarget.flags & (1048576 | 131072))) { - if (source === nullStrippedTarget) - return -1; - target = nullStrippedTarget; + target = getNormalizedType(nullStrippedTarget, true); } + if (source === nullStrippedTarget) + return -1; } if (relation === comparableRelation && !(target.flags & 131072) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1; - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096); - var isPerformingExcessPropertyChecks = !(intersectionState & 2) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048); + var isPerformingExcessPropertyChecks = !(intersectionState & 2) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384); if (isPerformingExcessPropertyChecks) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -49155,7 +50555,7 @@ var ts; } } if (result && !inPropertyCheck && (target.flags & 2097152 && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 && getApparentType(source).flags & 3670016 && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152); }))) { + isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 && getApparentType(source).flags & 3670016 && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 524288); }))) { inPropertyCheck = true; result &= recursiveTypeRelatedTo(source, target, reportErrors, 4); inPropertyCheck = false; @@ -49164,8 +50564,10 @@ var ts; return result; function reportErrorResults(source, target, result, isComparingJsxAttributes) { if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; + var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); + var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); + source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; + target = (originalTarget.aliasSymbol || targetHasBase) ? originalTarget : target; var maybeSuppress = overrideNextErrorInfo > 0; if (maybeSuppress) { overrideNextErrorInfo--; @@ -49204,13 +50606,13 @@ var ts; } } function traceUnionsOrIntersectionsTooLarge(source, target) { - if (!ts.tracing.isTracing()) { + if (!ts.tracing) { return; } if ((source.flags & 3145728) && (target.flags & 3145728)) { var sourceUnionOrIntersection = source; var targetUnionOrIntersection = target; - if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 262144) { + if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 65536) { return; } var sourceSize = sourceUnionOrIntersection.types.length; @@ -49234,11 +50636,11 @@ var ts; } traceUnionsOrIntersectionsTooLarge(source, target); if (flags & 3145728) { - var result_6 = eachTypeRelatedToSomeType(source, target); - if (result_6) { - result_6 &= eachTypeRelatedToSomeType(target, source); + var result_7 = eachTypeRelatedToSomeType(source, target); + if (result_7) { + result_7 &= eachTypeRelatedToSomeType(target, source); } - return result_6; + return result_7; } return recursiveTypeRelatedTo(source, target, false, 0); } @@ -49252,10 +50654,11 @@ var ts; return getUnionType(ts.reduceLeft(types, appendPropType, undefined) || ts.emptyArray); } function hasExcessProperties(source, target, reportErrors) { - if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384) { + var _a; + if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 8192) { return false; } - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048); if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; @@ -49288,7 +50691,7 @@ var ts; } } else { - var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + var objectLiteralDeclaration_1 = ((_a = source.symbol) === null || _a === void 0 ? void 0 : _a.declarations) && ts.firstOrUndefined(source.symbol.declarations); var suggestion = void 0; if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) { var propDeclaration = prop.valueDeclaration; @@ -49317,11 +50720,11 @@ var ts; } } }; - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - var state_4 = _loop_16(prop); - if (typeof state_4 === "object") - return state_4.value; + for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { + var prop = _b[_i]; + var state_5 = _loop_16(prop); + if (typeof state_5 === "object") + return state_5.value; } return false; } @@ -49343,8 +50746,17 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 1048576 && containsType(targetTypes, source)) { - return -1; + if (target.flags & 1048576) { + if (containsType(targetTypes, source)) { + return -1; + } + var match = getMatchingUnionConstituentForType(target, source); + if (match) { + var related = isRelatedTo(source, match, false); + if (related) { + return related; + } + } } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { var type = targetTypes_1[_i]; @@ -49487,8 +50899,12 @@ var ts; targetStack = []; } else { + var broadestEquivalentId = id.split(",").map(function (i) { return i.replace(/-\d+/g, function (_match, offset) { + var index = ts.length(id.slice(0, offset).match(/[-=]/g) || undefined); + return "=" + index; + }); }).join(","); for (var i = 0; i < maybeCount; i++) { - if (id === maybeKeys[i]) { + if (id === maybeKeys[i] || broadestEquivalentId === maybeKeys[i]) { return 3; } } @@ -49518,7 +50934,7 @@ var ts; }; } if (expandingFlags === 3) { - ts.tracing.instant("checkTypes", "recursiveTypeRelatedTo_DepthLimit", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes", "recursiveTypeRelatedTo_DepthLimit", { sourceId: source.id, sourceIdStack: sourceStack.map(function (t) { return t.id; }), targetId: target.id, @@ -49549,9 +50965,9 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { - ts.tracing.push("checkTypes", "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes", "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) { @@ -49570,6 +50986,15 @@ var ts; if (target.flags & 2097152) { return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2); } + if (relation === comparableRelation && target.flags & 131068) { + var constraints = ts.sameMap(source.types, function (t) { return t.flags & 131068 ? t : getBaseConstraintOfType(t) || unknownType; }); + if (constraints !== source.types) { + source = getIntersectionType(constraints); + if (!(source.flags & 2097152)) { + return isRelatedTo(source, target, false); + } + } + } return someTypeRelatedToType(source, target, false, 1); } var flags = source.flags & target.flags; @@ -49577,21 +51002,21 @@ var ts; if (flags & 4194304) { return isRelatedTo(source.type, target.type, false); } - var result_7 = 0; + var result_8 = 0; if (flags & 8388608) { - if (result_7 = isRelatedTo(source.objectType, target.objectType, false)) { - if (result_7 &= isRelatedTo(source.indexType, target.indexType, false)) { - return result_7; + if (result_8 = isRelatedTo(source.objectType, target.objectType, false)) { + if (result_8 &= isRelatedTo(source.indexType, target.indexType, false)) { + return result_8; } } } if (flags & 16777216) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_7 = isRelatedTo(source.checkType, target.checkType, false)) { - if (result_7 &= isRelatedTo(source.extendsType, target.extendsType, false)) { - if (result_7 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { - if (result_7 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { - return result_7; + if (result_8 = isRelatedTo(source.checkType, target.checkType, false)) { + if (result_8 &= isRelatedTo(source.extendsType, target.extendsType, false)) { + if (result_8 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { + if (result_8 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { + return result_8; } } } @@ -49656,6 +51081,18 @@ var ts; } } else if (target.flags & 8388608) { + if (source.flags & 8388608) { + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + if (reportErrors) { + originalErrorInfo = errorInfo; + } + } if (relation === assignableRelation || relation === comparableRelation) { var objectType = target.objectType; var indexType = target.indexType; @@ -49664,11 +51101,22 @@ var ts; if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) { var accessFlags = 2 | (baseObjectType !== objectType ? 1 : 0); var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, target.noUncheckedIndexedAccessCandidate, undefined, accessFlags); - if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) { - return result; + if (constraint) { + if (reportErrors && originalErrorInfo) { + resetErrorInfo(saveErrorInfo); + } + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + if (reportErrors && originalErrorInfo && errorInfo) { + errorInfo = countMessageChainBreadth([originalErrorInfo]) <= countMessageChainBreadth([errorInfo]) ? originalErrorInfo : errorInfo; + } } } } + if (reportErrors) { + originalErrorInfo = undefined; + } } else if (isGenericMappedType(target) && !target.declaration.nameType) { var template = getTemplateTypeFromMappedType(target); @@ -49707,25 +51155,39 @@ var ts; } } } - else if (target.flags & 134217728 && source.flags & 128) { - if (isPatternLiteralType(target)) { - var result_8 = inferLiteralsFromTemplateLiteralType(source, target); - if (result_8 && ts.every(result_8, function (r, i) { return isStringLiteralTypeValueParsableAsType(r, target.types[i]); })) { - return -1; - } + else if (target.flags & 16777216) { + var c = target; + var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); + var skipFalse = !skipTrue && isConditionalTypeAlwaysTrueDisregardingInferTypes(c); + var distributionMapper = void 0; + var checkVar = getActualTypeVariable(c.root.checkType); + if (c.root.isDistributive && checkVar.flags & 262144) { + var newParam = cloneTypeParameter(checkVar); + distributionMapper = prependTypeMapping(checkVar, newParam, c.mapper); + newParam.mapper = distributionMapper; + } + var localResult = void 0; + if (skipTrue || (localResult = isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.trueType), distributionMapper) : getTrueTypeFromConditionalType(c), false))) { + if (!skipFalse) { + localResult = (localResult || 3) & isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.falseType), distributionMapper) : getFalseTypeFromConditionalType(c), false); + } + } + if (localResult) { + resetErrorInfo(saveErrorInfo); + return localResult; } } - if (source.flags & 8650752) { - if (source.flags & 8388608 && target.flags & 8388608) { - if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { - result &= isRelatedTo(source.indexType, target.indexType, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } + else if (target.flags & 134217728) { + if (source.flags & 134217728) { + instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } - else { + var result_9 = inferTypesFromTemplateLiteralType(source, target); + if (result_9 && ts.every(result_9, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { + return -1; + } + } + if (source.flags & 8650752) { + if (!(source.flags & 8388608 && target.flags & 8388608)) { var constraint = getConstraintOfType(source); if (!constraint || (source.flags & 262144 && constraint.flags & 1)) { if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864))) { @@ -49737,7 +51199,7 @@ var ts; resetErrorInfo(saveErrorInfo); return result; } - else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, undefined, intersectionState)) { + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors && !(target.flags & source.flags & 262144), undefined, intersectionState)) { resetErrorInfo(saveErrorInfo); return result; } @@ -49750,17 +51212,10 @@ var ts; } } else if (source.flags & 134217728) { - if (target.flags & 134217728) { - if (source.texts.length === target.texts.length && - source.types.length === target.types.length && - ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) && - ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 | 4)) || !!isRelatedTo(t, target.types[i], false); })) { - return -1; - } - } - else { - var constraint = getBaseConstraintOfType(source); - if (result = isRelatedTo(constraint && constraint !== source ? constraint : stringType, target, reportErrors)) { + if (!(target.flags & 134217728)) { + var baseConstraint = getBaseConstraintOfType(source); + var constraint = baseConstraint && baseConstraint !== source ? baseConstraint : stringType; + if (result = isRelatedTo(constraint, target, reportErrors)) { resetErrorInfo(saveErrorInfo); return result; } @@ -49788,7 +51243,7 @@ var ts; var mapper = void 0; if (sourceParams) { var ctx = createInferenceContext(sourceParams, undefined, 0, isRelatedTo); - inferTypes(ctx.inferences, target.extendsType, sourceExtends, 256 | 512); + inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 | 1024); sourceExtends = instantiateType(sourceExtends, ctx.mapper); mapper = ctx.mapper; } @@ -49841,7 +51296,7 @@ var ts; return 0; } if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target && - !(ts.getObjectFlags(source) & 8192 || ts.getObjectFlags(target) & 8192)) { + !(ts.getObjectFlags(source) & 4096 || ts.getObjectFlags(target) & 4096)) { var variances = getVariances(source.target); if (variances === ts.emptyArray) { return 1; @@ -49859,7 +51314,7 @@ var ts; return 0; } } - else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 && !isEmptyObjectType(source)) { + else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 16384 && !isEmptyObjectType(source)) { return 0; } if (source.flags & (524288 | 2097152) && target.flags & 524288) { @@ -49887,14 +51342,19 @@ var ts; if (source.flags & (524288 | 2097152) && target.flags & 1048576) { var objectOnlyTarget = extractTypesOfKind(target, 524288 | 2097152 | 33554432); if (objectOnlyTarget.flags & 1048576) { - var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_9) { - return result_9; + var result_10 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_10) { + return result_10; } } } } return 0; + function countMessageChainBreadth(info) { + if (!info) + return 0; + return ts.reduceLeft(info, function (value, chain) { return value + 1 + countMessageChainBreadth(chain.next); }, 0); + } function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) { if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) { return result; @@ -49931,13 +51391,13 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_10; + var result_11; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + if (result_11 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { - return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_11 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } } @@ -49953,7 +51413,7 @@ var ts; var sourceProperty = sourcePropertiesFiltered_1[_i]; numCombinations *= countTypes(getTypeOfSymbol(sourceProperty)); if (numCombinations > 25) { - ts.tracing.instant("checkTypes", "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes", "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); return 0; } } @@ -49986,8 +51446,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_6 = _loop_18(i); - switch (state_6) { + var state_7 = _loop_18(i); + switch (state_7) { case "continue-outer": continue outer; } } @@ -50000,9 +51460,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_5 = _loop_17(combination); - if (typeof state_5 === "object") - return state_5.value; + var state_6 = _loop_17(combination); + if (typeof state_6 === "object") + return state_6.value; } var result = -1; for (var _b = 0, matchingTypes_1 = matchingTypes; _b < matchingTypes_1.length; _b++) { @@ -50050,7 +51510,7 @@ var ts; ts.Debug.assertIsDefined(links.deferralParent); ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576); - var result_11 = unionParent ? 0 : -1; + var result_12 = unionParent ? 0 : -1; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -50059,7 +51519,7 @@ var ts; if (!related) { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_11 &= related; + result_12 &= related; } else { if (related) { @@ -50067,13 +51527,13 @@ var ts; } } } - if (unionParent && !result_11 && targetIsOptional) { - result_11 = isRelatedTo(source, undefinedType); + if (unionParent && !result_12 && targetIsOptional) { + result_12 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_11 && reportErrors) { + if (unionParent && !result_12 && reportErrors) { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_11; + return result_12; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, undefined, intersectionState); @@ -50377,7 +51837,7 @@ var ts; var targetSignature = ts.first(targetSignatures); result = signatureRelatedTo(sourceSignature, targetSignature, eraseGenerics, reportErrors, incompatibleReporter(sourceSignature, targetSignature)); if (!result && reportErrors && kind === 1 && (sourceObjectFlags & targetObjectFlags) && - (((_a = targetSignature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 166 || ((_b = sourceSignature.declaration) === null || _b === void 0 ? void 0 : _b.kind) === 166)) { + (((_a = targetSignature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 167 || ((_b = sourceSignature.declaration) === null || _b === void 0 ? void 0 : _b.kind) === 167)) { var constructSignatureToString = function (signature) { return signatureToString(signature, undefined, 262144, kind); }; @@ -50480,9 +51940,15 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetType = getIndexTypeOfType(target, kind); - if (!targetType || targetType.flags & 1 && !sourceIsPrimitive) { + if (!targetType) { return -1; } + if (targetType.flags & 1 && !sourceIsPrimitive) { + var stringIndexType = kind === 0 ? targetType : getIndexTypeOfType(target, 0); + if (stringIndexType && stringIndexType.flags & 1) { + return -1; + } + } if (isGenericMappedType(source)) { return getIndexTypeOfType(target, 0) ? isRelatedTo(getTemplateTypeFromMappedType(source), targetType, reportErrors) : 0; } @@ -50618,7 +52084,7 @@ var ts; } function getMarkerTypeReference(type, source, target) { var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); - result.objectFlags |= 8192; + result.objectFlags |= 4096; return result; } function getAliasVariances(symbol) { @@ -50634,7 +52100,7 @@ var ts; if (typeParameters === void 0) { typeParameters = ts.emptyArray; } var variances = cache.variances; if (!variances) { - ts.tracing.push("checkTypes", "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes", "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); cache.variances = ts.emptyArray; variances = []; var _loop_19 = function (tp) { @@ -50665,7 +52131,7 @@ var ts; _loop_19(tp); } cache.variances = variances; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } return variances; } @@ -50690,7 +52156,7 @@ var ts; return !!(ts.getObjectFlags(type) & 4) && !type.node; } function isTypeReferenceWithGenericArguments(type) { - return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return !!(t.flags & 262144) || isTypeReferenceWithGenericArguments(t); }); } function getTypeReferenceId(type, typeParameters, depth) { if (depth === void 0) { depth = 0; } @@ -50759,21 +52225,19 @@ var ts; return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); } - function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? + function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) { + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p, writing) & 16 ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } function isDeeplyNestedType(type, stack, depth) { if (depth >= 5) { var identity_1 = getRecursionIdentity(type); - if (identity_1) { - var count = 0; - for (var i = 0; i < depth; i++) { - if (getRecursionIdentity(stack[i]) === identity_1) { - count++; - if (count >= 5) { - return true; - } + var count = 0; + for (var i = 0; i < depth; i++) { + if (getRecursionIdentity(stack[i]) === identity_1) { + count++; + if (count >= 5) { + return true; } } } @@ -50792,6 +52256,9 @@ var ts; return type.target; } } + if (type.flags & 262144) { + return type.symbol; + } if (type.flags & 8388608) { do { type = type.objectType; @@ -50801,7 +52268,7 @@ var ts; if (type.flags & 16777216) { return type.root; } - return undefined; + return type; } function isPropertyIdenticalTo(sourceProp, targetProp) { return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0; @@ -50923,6 +52390,9 @@ var ts; return true; } function getSupertypeOrUnion(types) { + if (types.length === 1) { + return types[0]; + } return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); @@ -50954,9 +52424,32 @@ var ts; function isArrayLikeType(type) { return isArrayType(type) || !(type.flags & 98304) && isTypeAssignableTo(type, anyReadonlyArrayType); } + function getSingleBaseForNonAugmentingSubtype(type) { + if (!(ts.getObjectFlags(type) & 4) || !(ts.getObjectFlags(type.target) & 3)) { + return undefined; + } + if (ts.getObjectFlags(type) & 33554432) { + return ts.getObjectFlags(type) & 67108864 ? type.cachedEquivalentBaseType : undefined; + } + type.objectFlags |= 33554432; + var target = type.target; + var bases = getBaseTypes(target); + if (bases.length !== 1) { + return undefined; + } + if (getMembersOfSymbol(type.symbol).size) { + return undefined; + } + var instantiatedBase = !ts.length(target.typeParameters) ? bases[0] : instantiateType(bases[0], createTypeMapper(target.typeParameters, getTypeArguments(type).slice(0, target.typeParameters.length))); + if (ts.length(getTypeArguments(type)) > ts.length(target.typeParameters)) { + instantiatedBase = getTypeWithThisArgument(instantiatedBase, ts.last(getTypeArguments(type))); + } + type.objectFlags |= 67108864; + return type.cachedEquivalentBaseType = instantiatedBase; + } function isEmptyArrayLiteralType(type) { - var elementType = isArrayType(type) ? getTypeArguments(type)[0] : undefined; - return elementType === undefinedWideningType || elementType === implicitNeverType; + var elementType = getElementTypeOfArrayType(type); + return strictNullChecks ? elementType === implicitNeverType : elementType === undefinedWideningType; } function isTupleLikeType(type) { return isTupleType(type) || !!getPropertyOfType(type, "0"); @@ -50980,6 +52473,13 @@ var ts; function isUnitType(type) { return !!(type.flags & 109440); } + function isUnitLikeType(type) { + return type.flags & 2097152 ? ts.some(type.types, isUnitType) : + !!(type.flags & 109440); + } + function extractUnitType(type) { + return type.flags & 2097152 ? ts.find(type.types, isUnitType) || type : type; + } function isLiteralType(type) { return type.flags & 16 ? true : type.flags & 1048576 ? type.flags & 1024 ? true : ts.every(type.types, isUnitType) : @@ -50987,7 +52487,7 @@ var ts; } function getBaseTypeOfLiteralType(type) { return type.flags & 1024 ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 ? stringType : + type.flags & 128 ? stringType : type.flags & 256 ? numberType : type.flags & 2048 ? bigintType : type.flags & 512 ? booleanType : @@ -50996,7 +52496,7 @@ var ts; } function getWidenedLiteralType(type) { return type.flags & 1024 && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 && isFreshLiteralType(type) ? stringType : + type.flags & 128 && isFreshLiteralType(type) ? stringType : type.flags & 256 && isFreshLiteralType(type) ? numberType : type.flags & 2048 && isFreshLiteralType(type) ? bigintType : type.flags & 512 && isFreshLiteralType(type) ? booleanType : @@ -51118,13 +52618,13 @@ var ts; return type.flags & 32768 ? type : getUnionType([type, undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { + var reducedType = getTypeWithFacts(type, 2097152); if (!deferredGlobalNonNullableTypeAlias) { deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288, undefined) || unknownSymbol; } - if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { - return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); - } - return getTypeWithFacts(type, 2097152); + return deferredGlobalNonNullableTypeAlias !== unknownSymbol ? + getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [reducedType]) : + reducedType; } function getNonNullableType(type) { return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; @@ -51153,7 +52653,7 @@ var ts; function isObjectTypeWithInferableIndex(type) { return type.flags & 2097152 ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 | 2048 | 384 | 512)) !== 0 && - !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 && isObjectTypeWithInferableIndex(type.source)); + !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8); @@ -51181,7 +52681,7 @@ var ts; return members; } function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768)) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 16384)) { return type; } var regularType = type.regularType; @@ -51192,7 +52692,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags; - regularNew.objectFlags |= resolved.objectFlags & ~32768; + regularNew.objectFlags |= resolved.objectFlags & ~16384; type.regularType = regularNew; return regularNew; } @@ -51222,7 +52722,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { var t = _a[_i]; - if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024)) { + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 4194304)) { for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { var prop = _c[_b]; names.set(prop.escapedName, prop); @@ -51269,14 +52769,14 @@ var ts; var stringIndexInfo = getIndexInfoOfType(type, 0); var numberIndexInfo = getIndexInfoOfType(type, 1); var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); - result.objectFlags |= (ts.getObjectFlags(type) & (16384 | 2097152)); + result.objectFlags |= (ts.getObjectFlags(type) & (8192 | 524288)); return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, undefined); } function getWidenedTypeWithContext(type, context) { - if (ts.getObjectFlags(type) & 1572864) { + if (ts.getObjectFlags(type) & 393216) { if (context === undefined && type.widened) { return type.widened; } @@ -51307,7 +52807,7 @@ var ts; } function reportWideningErrorsInType(type) { var errorReported = false; - if (ts.getObjectFlags(type) & 524288) { + if (ts.getObjectFlags(type) & 131072) { if (type.flags & 1048576) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -51333,7 +52833,7 @@ var ts; for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (ts.getObjectFlags(t) & 524288) { + if (ts.getObjectFlags(t) & 131072) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -51351,12 +52851,12 @@ var ts; } var diagnostic; switch (declaration.kind) { - case 216: + case 217: + case 164: case 163: - case 162: diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 160: + case 161: var param = declaration; if (ts.isIdentifier(param.name) && (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && @@ -51371,22 +52871,22 @@ var ts; noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 198: + case 199: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; if (!noImplicitAny) { return; } break; - case 308: + case 309: error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; - case 251: + case 252: + case 166: case 165: - case 164: - case 167: case 168: - case 208: + case 169: case 209: + case 210: if (noImplicitAny && !declaration.name) { if (wideningKind === 3) { error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString); @@ -51400,7 +52900,7 @@ var ts; wideningKind === 3 ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; - case 190: + case 191: if (noImplicitAny) { error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); } @@ -51411,7 +52911,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); } @@ -51523,23 +53023,23 @@ var ts; } function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - if (objectFlags & 67108864) { - return !!(objectFlags & 134217728); + if (objectFlags & 1048576) { + return !!(objectFlags & 2097152); } var result = !!(type.flags & 465829888 || type.flags & 524288 && !isNonGenericTopLevelType(type) && (objectFlags & 4 && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations || - objectFlags & (32 | 131072)) || + objectFlags & (32 | 1024 | 8388608)) || type.flags & 3145728 && !(type.flags & 1024) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables)); if (type.flags & 3899393) { - type.objectFlags |= 67108864 | (result ? 134217728 : 0); + type.objectFlags |= 1048576 | (result ? 2097152 : 0); } return result; } function isNonGenericTopLevelType(type) { if (type.aliasSymbol && !type.aliasTypeArguments) { - var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 254); - return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 297 ? true : n.kind === 256 ? false : "quit"; })); + var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 255); + return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 298 ? true : n.kind === 257 ? false : "quit"; })); } return false; } @@ -51581,7 +53081,7 @@ var ts; return type; } function isPartiallyInferableType(type) { - return !(ts.getObjectFlags(type) & 2097152) || + return !(ts.getObjectFlags(type) & 524288) || isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }) || isTupleType(type) && ts.some(getTypeArguments(type), isPartiallyInferableType); } @@ -51599,14 +53099,18 @@ var ts; source.target.elementFlags; return createTupleType(elementTypes, elementFlags, source.target.readonly, source.target.labeledElementDeclarations); } - var reversed = createObjectType(2048 | 16, undefined); + var reversed = createObjectType(1024 | 16, undefined); reversed.source = source; reversed.mappedType = target; reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + return links.type; } function inferReverseMappedType(sourceType, target, constraint) { var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); @@ -51690,49 +53194,94 @@ var ts; var flags = scanner.getTokenFlags(); return success && result === 9 && scanner.getTextPos() === (s.length + 1) && !(flags & 512); } - function isStringLiteralTypeValueParsableAsType(s, target) { - if (target.flags & 1048576) { - return !!forEachType(target, function (t) { return isStringLiteralTypeValueParsableAsType(s, t); }); - } - switch (target) { - case stringType: return true; - case numberType: return s.value !== "" && isFinite(+(s.value)); - case bigintType: return s.value !== "" && isValidBigIntString(s.value); - case trueType: return s.value === "true"; - case falseType: return s.value === "false"; - case undefinedType: return s.value === "undefined"; - case nullType: return s.value === "null"; - default: return !!(target.flags & 1); - } - } - function inferLiteralsFromTemplateLiteralType(source, target) { - var value = source.value; - var texts = target.texts; - var lastIndex = texts.length - 1; - var startText = texts[0]; - var endText = texts[lastIndex]; - if (!(value.startsWith(startText) && value.slice(startText.length).endsWith(endText))) + function isValidTypeForTemplateLiteralPlaceholder(source, target) { + if (source === target || target.flags & (1 | 4)) { + return true; + } + if (source.flags & 128) { + var value = source.value; + return !!(target.flags & 8 && value !== "" && isFinite(+value) || + target.flags & 64 && value !== "" && isValidBigIntString(value) || + target.flags & (512 | 98304) && value === target.intrinsicName); + } + if (source.flags & 134217728) { + var texts = source.texts; + return texts.length === 2 && texts[0] === "" && texts[1] === "" && isTypeAssignableTo(source.types[0], target); + } + return isTypeAssignableTo(source, target); + } + function inferTypesFromTemplateLiteralType(source, target) { + return source.flags & 128 ? inferFromLiteralPartsToTemplateLiteral([source.value], ts.emptyArray, target) : + source.flags & 134217728 ? + ts.arraysEqual(source.texts, target.texts) ? ts.map(source.types, getStringLikeTypeForType) : + inferFromLiteralPartsToTemplateLiteral(source.texts, source.types, target) : + undefined; + } + function getStringLikeTypeForType(type) { + return type.flags & (1 | 402653316) ? type : getTemplateLiteralType(["", ""], [type]); + } + function inferFromLiteralPartsToTemplateLiteral(sourceTexts, sourceTypes, target) { + var lastSourceIndex = sourceTexts.length - 1; + var sourceStartText = sourceTexts[0]; + var sourceEndText = sourceTexts[lastSourceIndex]; + var targetTexts = target.texts; + var lastTargetIndex = targetTexts.length - 1; + var targetStartText = targetTexts[0]; + var targetEndText = targetTexts[lastTargetIndex]; + if (lastSourceIndex === 0 && sourceStartText.length < targetStartText.length + targetEndText.length || + !sourceStartText.startsWith(targetStartText) || !sourceEndText.endsWith(targetEndText)) return undefined; + var remainingEndText = sourceEndText.slice(0, sourceEndText.length - targetEndText.length); var matches = []; - var str = value.slice(startText.length, value.length - endText.length); - var pos = 0; - for (var i = 1; i < lastIndex; i++) { - var delim = texts[i]; - var delimPos = delim.length > 0 ? str.indexOf(delim, pos) : pos < str.length ? pos + 1 : -1; - if (delimPos < 0) + var seg = 0; + var pos = targetStartText.length; + for (var i = 1; i < lastTargetIndex; i++) { + var delim = targetTexts[i]; + if (delim.length > 0) { + var s = seg; + var p = pos; + while (true) { + p = getSourceText(s).indexOf(delim, p); + if (p >= 0) + break; + s++; + if (s === sourceTexts.length) + return undefined; + p = 0; + } + addMatch(s, p); + pos += delim.length; + } + else if (pos < getSourceText(seg).length) { + addMatch(seg, pos + 1); + } + else if (seg < lastSourceIndex) { + addMatch(seg + 1, 0); + } + else { return undefined; - matches.push(getLiteralType(str.slice(pos, delimPos))); - pos = delimPos + delim.length; + } } - matches.push(getLiteralType(str.slice(pos))); + addMatch(lastSourceIndex, getSourceText(lastSourceIndex).length); return matches; + function getSourceText(index) { + return index < lastSourceIndex ? sourceTexts[index] : remainingEndText; + } + function addMatch(s, p) { + var matchType = s === seg ? + getLiteralType(getSourceText(s).slice(pos, p)) : + getTemplateLiteralType(__spreadArray(__spreadArray([sourceTexts[seg].slice(pos)], sourceTexts.slice(seg + 1, s)), [getSourceText(s).slice(0, p)]), sourceTypes.slice(seg, s)); + matches.push(matchType); + seg = s; + pos = p; + } } function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) { if (priority === void 0) { priority = 0; } if (contravariant === void 0) { contravariant = false; } var bivariant = false; var propagationType; - var inferencePriority = 1024; + var inferencePriority = 2048; var allowComplexConstraintInference = true; var visited; var sourceStack; @@ -51788,8 +53337,8 @@ var ts; target = getActualTypeVariable(target); } if (target.flags & 8650752) { - if (ts.getObjectFlags(source) & 2097152 || source === nonInferrableAnyType || source === silentNeverType || - (priority & 64 && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + if (ts.getObjectFlags(source) & 524288 || source === nonInferrableAnyType || source === silentNeverType || + (priority & 128 && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); @@ -51814,7 +53363,7 @@ var ts; clearCachedInferences(inferences); } } - if (!(priority & 64) && target.flags & 262144 && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 128) && target.flags & 262144 && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; clearCachedInferences(inferences); } @@ -51850,7 +53399,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4) && target.flags & 4194304) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - inferWithPriority(empty, target.type, 128); + inferWithPriority(empty, target.type, 256); contravariant = !contravariant; } else if (source.flags & 8388608 && target.flags & 8388608) { @@ -51862,6 +53411,13 @@ var ts; inferFromTypes(source.type, target.type); } } + else if (source.flags & 33554432) { + inferFromTypes(source.baseType, target); + var oldPriority = priority; + priority |= 4; + inferFromTypes(source.substitute, target); + priority = oldPriority; + } else if (target.flags & 16777216) { invokeOnce(source, target, inferToConditionalType); } @@ -51880,7 +53436,7 @@ var ts; } else { source = getReducedType(source); - if (!(priority & 256 && source.flags & (2097152 | 465829888))) { + if (!(priority & 512 && source.flags & (2097152 | 465829888))) { var apparentSource = getApparentType(source); if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 | 2097152))) { allowComplexConstraintInference = false; @@ -51908,24 +53464,20 @@ var ts; } (visited || (visited = new ts.Map())).set(key, -1); var saveInferencePriority = inferencePriority; - inferencePriority = 1024; + inferencePriority = 2048; var saveExpandingFlags = expandingFlags; - var sourceIdentity = getRecursionIdentity(source) || source; - var targetIdentity = getRecursionIdentity(target) || target; - if (sourceIdentity && ts.contains(sourceStack, sourceIdentity)) + var sourceIdentity = getRecursionIdentity(source); + var targetIdentity = getRecursionIdentity(target); + if (ts.contains(sourceStack, sourceIdentity)) expandingFlags |= 1; - if (targetIdentity && ts.contains(targetStack, targetIdentity)) + if (ts.contains(targetStack, targetIdentity)) expandingFlags |= 2; if (expandingFlags !== 3) { - if (sourceIdentity) - (sourceStack || (sourceStack = [])).push(sourceIdentity); - if (targetIdentity) - (targetStack || (targetStack = [])).push(targetIdentity); + (sourceStack || (sourceStack = [])).push(sourceIdentity); + (targetStack || (targetStack = [])).push(targetIdentity); action(source, target); - if (targetIdentity) - targetStack.pop(); - if (sourceIdentity) - sourceStack.pop(); + targetStack.pop(); + sourceStack.pop(); } else { inferencePriority = -1; @@ -51965,7 +53517,7 @@ var ts; } } function inferFromContravariantTypes(source, target) { - if (strictFunctionTypes || priority & 512) { + if (strictFunctionTypes || priority & 1024) { contravariant = !contravariant; inferFromTypes(source, target); contravariant = !contravariant; @@ -52013,7 +53565,7 @@ var ts; else { for (var i = 0; i < sources.length; i++) { var saveInferencePriority = inferencePriority; - inferencePriority = 1024; + inferencePriority = 2048; inferFromTypes(sources[i], t); if (inferencePriority === priority) matched_1[i] = true; @@ -52071,15 +53623,15 @@ var ts; if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) { var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); if (inferredType) { - inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 ? - 8 : - 4); + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 524288 ? + 16 : + 8); } } return true; } if (constraintType.flags & 262144) { - inferWithPriority(getIndexType(source), constraintType, 16); + inferWithPriority(getIndexType(source), constraintType, 32); var extendedConstraint = getConstraintOfType(constraintType); if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) { return true; @@ -52102,16 +53654,14 @@ var ts; } else { var savePriority = priority; - priority |= contravariant ? 32 : 0; + priority |= contravariant ? 64 : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; inferToMultipleTypes(source, targetTypes, target.flags); priority = savePriority; } } function inferToTemplateLiteralType(source, target) { - var matches = source.flags & 128 ? inferLiteralsFromTemplateLiteralType(source, target) : - source.flags & 134217728 && ts.arraysEqual(source.texts, target.texts) ? source.types : - undefined; + var matches = inferTypesFromTemplateLiteralType(source, target); var types = target.types; for (var i = 0; i < types.length; i++) { inferFromTypes(matches ? matches[i] : neverType, types[i]); @@ -52213,7 +53763,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 2097152); + var skipParameters = !!(ts.getObjectFlags(source) & 524288); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -52222,7 +53772,7 @@ var ts; if (!skipParameters) { var saveBivariant = bivariant; var kind = target.declaration ? target.declaration.kind : 0; - bivariant = bivariant || kind === 165 || kind === 164 || kind === 166; + bivariant = bivariant || kind === 166 || kind === 165 || kind === 167; applyToParameterTypes(source, target, inferFromContravariantTypes); bivariant = saveBivariant; } @@ -52249,7 +53799,7 @@ var ts; } } function isTypeOrBaseIdenticalTo(s, t) { - return isTypeIdenticalTo(s, t) || !!(t.flags & 4 && s.flags & 134217856 || t.flags & 8 && s.flags & 256); + return isTypeIdenticalTo(s, t) || !!(t.flags & 4 && s.flags & 128 || t.flags & 8 && s.flags & 256); } function isTypeCloselyMatchedBy(s, t) { return !!(s.flags & 524288 && t.flags & 524288 && s.symbol && s.symbol === t.symbol || @@ -52263,7 +53813,7 @@ var ts; return !!(ts.getObjectFlags(type) & 128); } function isObjectOrArrayLiteralType(type) { - return !!(ts.getObjectFlags(type) & (128 | 65536)); + return !!(ts.getObjectFlags(type) & (128 | 32768)); } function unionObjectAndArrayLiteralCandidates(candidates) { if (candidates.length > 1) { @@ -52276,7 +53826,7 @@ var ts; return candidates; } function getContravariantInference(inference) { - return inference.priority & 208 ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + return inference.priority & 416 ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } function getCovariantInference(inference, signature) { var candidates = unionObjectAndArrayLiteralCandidates(inference.candidates); @@ -52286,7 +53836,7 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - var unwidenedType = inference.priority & 208 ? + var unwidenedType = inference.priority & 416 ? getUnionType(baseCandidates, 2) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -52384,7 +53934,7 @@ var ts; case "BigUint64Array": return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later; default: - if (node.parent.kind === 289) { + if (node.parent.kind === 290) { return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer; } else { @@ -52401,20 +53951,20 @@ var ts; return links.resolvedSymbol; } function isInTypeQuery(node) { - return !!ts.findAncestor(node, function (n) { return n.kind === 176 ? true : n.kind === 78 || n.kind === 157 ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 177 ? true : n.kind === 78 || n.kind === 158 ? false : "quit"; }); } function getFlowCacheKey(node, declaredType, initialType, flowContainer) { switch (node.kind) { case 78: var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; case 107: return "0|" + (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType); - case 225: - case 207: + case 226: + case 208: return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); - case 201: case 202: + case 203: var propName = getAccessedPropertyName(node); if (propName !== undefined) { var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); @@ -52425,43 +53975,51 @@ var ts; } function isMatchingReference(source, target) { switch (target.kind) { - case 207: - case 225: + case 208: + case 226: return isMatchingReference(source, target.expression); - case 216: + case 217: return (ts.isAssignmentExpression(target) && isMatchingReference(source, target.left)) || (ts.isBinaryExpression(target) && target.operatorToken.kind === 27 && isMatchingReference(source, target.right)); } switch (source.kind) { + case 227: + return target.kind === 227 + && source.keywordToken === target.keywordToken + && source.name.escapedText === target.name.escapedText; case 78: case 79: return target.kind === 78 && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 249 || target.kind === 198) && + (target.kind === 250 || target.kind === 199) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); case 107: return target.kind === 107; case 105: return target.kind === 105; - case 225: - case 207: + case 226: + case 208: return isMatchingReference(source.expression, target); - case 201: case 202: + case 203: return ts.isAccessExpression(target) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 216: + case 158: + return ts.isAccessExpression(target) && + source.right.escapedText === getAccessedPropertyName(target) && + isMatchingReference(source.left, target.expression); + case 217: return (ts.isBinaryExpression(source) && source.operatorToken.kind === 27 && isMatchingReference(source.right, target)); } return false; } function containsTruthyCheck(source, target) { return isMatchingReference(source, target) || - (target.kind === 216 && target.operatorToken.kind === 55 && + (target.kind === 217 && target.operatorToken.kind === 55 && (containsTruthyCheck(source, target.left) || containsTruthyCheck(source, target.right))); } function getAccessedPropertyName(access) { - return access.kind === 201 ? access.name.escapedText : + return access.kind === 202 ? access.name.escapedText : ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : undefined; } @@ -52511,6 +54069,75 @@ var ts; } return result; } + function mapTypesByKeyProperty(types, name) { + var map = new ts.Map(); + var count = 0; + var _loop_20 = function (type) { + if (type.flags & (524288 | 2097152 | 58982400)) { + var discriminant = getTypeOfPropertyOfType(type, name); + if (discriminant) { + if (!isLiteralType(discriminant)) { + return { value: undefined }; + } + var duplicate_1 = false; + forEachType(discriminant, function (t) { + var id = getTypeId(getRegularTypeOfLiteralType(t)); + var existing = map.get(id); + if (!existing) { + map.set(id, type); + } + else if (existing !== unknownType) { + map.set(id, unknownType); + duplicate_1 = true; + } + }); + if (!duplicate_1) + count++; + } + } + }; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; + var state_8 = _loop_20(type); + if (typeof state_8 === "object") + return state_8.value; + } + return count >= 10 && count * 2 >= types.length ? map : undefined; + } + function getKeyPropertyName(unionType) { + var types = unionType.types; + if (types.length < 10 || ts.getObjectFlags(unionType) & 65536) { + return undefined; + } + if (unionType.keyPropertyName === undefined) { + var keyPropertyName = ts.forEach(types, function (t) { + return t.flags & (524288 | 58982400) ? + ts.forEach(getPropertiesOfType(t), function (p) { return isUnitType(getTypeOfSymbol(p)) ? p.escapedName : undefined; }) : + undefined; + }); + var mapByKeyProperty = keyPropertyName && mapTypesByKeyProperty(types, keyPropertyName); + unionType.keyPropertyName = mapByKeyProperty ? keyPropertyName : ""; + unionType.constituentMap = mapByKeyProperty; + } + return unionType.keyPropertyName.length ? unionType.keyPropertyName : undefined; + } + function getConstituentTypeForKeyType(unionType, keyType) { + var _a; + var result = (_a = unionType.constituentMap) === null || _a === void 0 ? void 0 : _a.get(getTypeId(getRegularTypeOfLiteralType(keyType))); + return result !== unknownType ? result : undefined; + } + function getMatchingUnionConstituentForType(unionType, type) { + var keyPropertyName = getKeyPropertyName(unionType); + var propType = keyPropertyName && getTypeOfPropertyOfType(type, keyPropertyName); + return propType && getConstituentTypeForKeyType(unionType, propType); + } + function getMatchingUnionConstituentForObjectLiteral(unionType, node) { + var keyPropertyName = getKeyPropertyName(unionType); + var propNode = keyPropertyName && ts.find(node.properties, function (p) { return p.symbol && p.kind === 289 && + p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer); }); + var propType = propNode && getTypeOfExpression(propNode.initializer); + return propType && getConstituentTypeForKeyType(unionType, propType); + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -52523,7 +54150,7 @@ var ts; } } } - if (expression.expression.kind === 201 && + if (expression.expression.kind === 202 && isOrContainsMatchingReference(reference, expression.expression.expression)) { return true; } @@ -52563,20 +54190,13 @@ var ts; } return declaredType; } - function getTypeFactsOfTypes(types) { - var result = 0; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; - result |= getTypeFacts(t); - } - return result; - } function isFunctionObjectType(type) { var resolved = resolveStructuredTypeMembers(type); return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type) { + function getTypeFacts(type, ignoreObjects) { + if (ignoreObjects === void 0) { ignoreObjects = false; } var flags = type.flags; if (flags & 4) { return strictNullChecks ? 16317953 : 16776705; @@ -52613,7 +54233,7 @@ var ts; (type === falseType || type === regularFalseType) ? 12121864 : 7927560 : (type === falseType || type === regularFalseType) ? 12580616 : 16774920; } - if (flags & 524288) { + if (flags & 524288 && !ignoreObjects) { return ts.getObjectFlags(type) & 16 && isEmptyObjectType(type) ? strictNullChecks ? 16318463 : 16777215 : isFunctionObjectType(type) ? @@ -52636,11 +54256,15 @@ var ts; return 0; } if (flags & 465829888) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType) : + return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : strictNullChecks ? 7929345 : 16776705; } - if (flags & 3145728) { - return getTypeFactsOfTypes(type.types); + if (flags & 1048576) { + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0); + } + if (flags & 2097152) { + ignoreObjects || (ignoreObjects = maybeTypeOfKind(type, 131068)); + return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t, ignoreObjects); }, 16777215); } return 16777215; } @@ -52648,18 +54272,16 @@ var ts; return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { - if (defaultExpression) { - var defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, 524288), defaultType]); - } - return type; + return defaultExpression ? + getUnionType([getNonUndefinedType(type), getTypeOfExpression(defaultExpression)]) : + type; } function getTypeOfDestructuredProperty(type, name) { var nameType = getLiteralTypeFromPropertyName(name); if (!isTypeUsableAsPropertyName(nameType)) return errorType; var text = getPropertyNameFromType(nameType); - return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || + return getTypeOfPropertyOfType(type, text) || isNumericLiteralName(text) && includeUndefinedInIndexSignature(getIndexTypeOfType(type, 1)) || includeUndefinedInIndexSignature(getIndexTypeOfType(type, 0)) || errorType; @@ -52680,15 +54302,15 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(65, type, undefinedType, undefined) || errorType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 199 && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 288 && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 200 && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 289 && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 216 && parent.parent.left === parent || - parent.parent.kind === 239 && parent.parent.initializer === parent; + return parent.parent.kind === 217 && parent.parent.left === parent || + parent.parent.kind === 240 && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); @@ -52705,21 +54327,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 238: - return stringType; case 239: + return stringType; + case 240: return checkRightHandSideOfForOf(parent) || errorType; - case 216: + case 217: return getAssignedTypeOfBinaryExpression(parent); - case 210: + case 211: return undefinedType; - case 199: + case 200: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 220: + case 221: return getAssignedTypeOfSpreadExpression(parent); - case 288: - return getAssignedTypeOfPropertyAssignment(parent); case 289: + return getAssignedTypeOfPropertyAssignment(parent); + case 290: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return errorType; @@ -52727,7 +54349,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 196 ? + var type = pattern.kind === 197 ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : @@ -52742,30 +54364,30 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 238) { + if (node.parent.parent.kind === 239) { return stringType; } - if (node.parent.parent.kind === 239) { + if (node.parent.parent.kind === 240) { return checkRightHandSideOfForOf(node.parent.parent) || errorType; } return errorType; } function getInitialType(node) { - return node.kind === 249 ? + return node.kind === 250 ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function isEmptyArrayAssignment(node) { - return node.kind === 249 && node.initializer && + return node.kind === 250 && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 198 && node.parent.kind === 216 && + node.kind !== 199 && node.parent.kind === 217 && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 207: + case 208: return getReferenceCandidate(node.expression); - case 216: + case 217: switch (node.operatorToken.kind) { case 62: case 74: @@ -52780,13 +54402,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 207 || - parent.kind === 216 && parent.operatorToken.kind === 62 && parent.left === node || - parent.kind === 216 && parent.operatorToken.kind === 27 && parent.right === node ? + return parent.kind === 208 || + parent.kind === 217 && parent.operatorToken.kind === 62 && parent.left === node || + parent.kind === 217 && parent.operatorToken.kind === 27 && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 284) { + if (clause.kind === 285) { return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); } return neverType; @@ -52806,7 +54428,7 @@ var ts; var witnesses = []; for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { var clause = _a[_i]; - if (clause.kind === 284) { + if (clause.kind === 285) { if (ts.isStringLiteralLike(clause.expression)) { witnesses.push(clause.expression.text); continue; @@ -52842,14 +54464,35 @@ var ts; function forEachType(type, f) { return type.flags & 1048576 ? ts.forEach(type.types, f) : f(type); } + function someType(type, f) { + return type.flags & 1048576 ? ts.some(type.types, f) : f(type); + } function everyType(type, f) { return type.flags & 1048576 ? ts.every(type.types, f) : f(type); } + function everyContainedType(type, f) { + return type.flags & 3145728 ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 1048576) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); + if (filtered === types) { + return type; + } + var origin = type.origin; + var newOrigin = void 0; + if (origin && origin.flags & 1048576) { + var originTypes = origin.types; + var originFiltered = ts.filter(originTypes, function (t) { return !!(t.flags & 1048576) || f(t); }); + if (originTypes.length - originFiltered.length === types.length - filtered.length) { + if (originFiltered.length === 1) { + return originFiltered[0]; + } + newOrigin = createOriginUnionOrIntersectionType(1048576, originFiltered); + } + } + return getUnionTypeFromSortedList(filtered, type.objectFlags, undefined, undefined, newOrigin); } return type.flags & 131072 || f(type) ? type : neverType; } @@ -52882,6 +54525,11 @@ var ts; } return changed ? mappedTypes && getUnionType(mappedTypes, noReductions ? 0 : 1) : type; } + function mapTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) { + return type.flags & 1048576 && aliasSymbol ? + getUnionType(ts.map(type.types, mapper), 1, aliasSymbol, aliasTypeArguments) : + mapType(type, mapper); + } function getConstituentCount(type) { return type.flags & 3145728 ? type.types.length : 1; } @@ -52954,12 +54602,12 @@ var ts; var root = getReferenceRoot(node); var parent = root.parent; var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" || - parent.parent.kind === 203 + parent.parent.kind === 204 && ts.isIdentifier(parent.name) && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 202 && + var isElementAssignment = parent.kind === 203 && parent.expression === root && - parent.parent.kind === 216 && + parent.parent.kind === 217 && parent.parent.operatorToken.kind === 62 && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && @@ -52967,8 +54615,8 @@ var ts; return isLengthPushOrUnshift || isElementAssignment; } function isDeclarationWithExplicitTypeAnnotation(declaration) { - return (declaration.kind === 249 || declaration.kind === 160 || - declaration.kind === 163 || declaration.kind === 162) && + return (declaration.kind === 250 || declaration.kind === 161 || + declaration.kind === 164 || declaration.kind === 163) && !!ts.getEffectiveTypeAnnotationNode(declaration); } function getExplicitTypeOfSymbol(symbol, diagnostic) { @@ -52987,7 +54635,7 @@ var ts; if (isDeclarationWithExplicitTypeAnnotation(declaration)) { return getTypeOfSymbol(symbol); } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 240) { var statement = declaration.parent.parent; var expressionType = getTypeOfDottedName(statement.expression, undefined); if (expressionType) { @@ -53011,11 +54659,25 @@ var ts; return getExplicitThisType(node); case 105: return checkSuperExpression(node); - case 201: + case 202: { var type = getTypeOfDottedName(node.expression, diagnostic); - var prop = type && getPropertyOfType(type, node.name.escapedText); - return prop && getExplicitTypeOfSymbol(prop, diagnostic); - case 207: + if (type) { + var name = node.name; + var prop = void 0; + if (ts.isPrivateIdentifier(name)) { + if (!type.symbol) { + return undefined; + } + prop = getPropertyOfType(type, ts.getSymbolNameForPrivateIdentifier(type.symbol, name.escapedText)); + } + else { + prop = getPropertyOfType(type, name.escapedText); + } + return prop && getExplicitTypeOfSymbol(prop, diagnostic); + } + return undefined; + } + case 208: return getTypeOfDottedName(node.expression, diagnostic); } } @@ -53025,7 +54687,7 @@ var ts; var signature = links.effectsSignature; if (signature === undefined) { var funcType = void 0; - if (node.parent.kind === 233) { + if (node.parent.kind === 234) { funcType = getTypeOfDottedName(node.expression, undefined); } else if (node.expression.kind !== 105) { @@ -53069,7 +54731,7 @@ var ts; } function isFalseExpression(expr) { var node = ts.skipParentheses(expr); - return node.kind === 94 || node.kind === 216 && (node.operatorToken.kind === 55 && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + return node.kind === 94 || node.kind === 217 && (node.operatorToken.kind === 55 && (isFalseExpression(node.left) || isFalseExpression(node.right)) || node.operatorToken.kind === 56 && isFalseExpression(node.left) && isFalseExpression(node.right)); } function isReachableFlowNodeWorker(flow, noCacheCheck) { @@ -53190,7 +54852,7 @@ var ts; var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); sharedFlowCount = sharedFlowStart; var resultType = ts.getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); - if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 225 && getTypeWithFacts(resultType, 2097152).flags & 131072) { + if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 226 && !(resultType.flags & 131072) && getTypeWithFacts(resultType, 2097152).flags & 131072) { return declaredType; } return resultType; @@ -53203,7 +54865,7 @@ var ts; } function getTypeAtFlowNode(flow) { if (flowDepth === 2000) { - ts.tracing.instant("checkTypes", "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes", "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); flowAnalysisDisabled = true; reportFlowControlError(reference); return errorType; @@ -53268,8 +54930,8 @@ var ts; else if (flags & 2) { var container = flow.node; if (container && container !== flowContainer && - reference.kind !== 201 && reference.kind !== 202 && + reference.kind !== 203 && reference.kind !== 107) { flow = container.flowNode; continue; @@ -53290,7 +54952,7 @@ var ts; } function getInitialOrAssignedType(flow) { var node = flow.node; - return getConstraintForLocation(node.kind === 249 || node.kind === 198 ? + return getNarrowableTypeForReference(node.kind === 250 || node.kind === 199 ? getInitialType(node) : getAssignedType(node), reference); } @@ -53322,13 +54984,13 @@ var ts; } if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { var init = ts.getDeclaredExpandoInitializer(node); - if (init && (init.kind === 208 || init.kind === 209)) { + if (init && (init.kind === 209 || init.kind === 210)) { return getTypeAtFlowNode(flow.antecedent); } } return declaredType; } - if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 238 && isMatchingReference(reference, node.parent.parent.expression)) { + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 239 && isMatchingReference(reference, node.parent.parent.expression)) { return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); } return undefined; @@ -53338,7 +55000,7 @@ var ts; if (node.kind === 94) { return unreachableNeverType; } - if (node.kind === 216) { + if (node.kind === 217) { if (node.operatorToken.kind === 55) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); } @@ -53369,7 +55031,7 @@ var ts; function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 203 ? + var expr = node.kind === 204 ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { @@ -53377,7 +55039,7 @@ var ts; var type = getTypeFromFlowType(flowType); if (ts.getObjectFlags(type) & 256) { var evolvedType_1 = type; - if (node.kind === 203) { + if (node.kind === 204) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); @@ -53417,7 +55079,7 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (expr.kind === 211 && isMatchingReference(reference, expr.expression)) { + else if (expr.kind === 212 && isMatchingReference(reference, expr.expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else { @@ -53425,12 +55087,12 @@ var ts; if (optionalChainContainsReference(expr, reference)) { type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 | 131072)); }); } - else if (expr.kind === 211 && optionalChainContainsReference(expr.expression, reference)) { + else if (expr.kind === 212 && optionalChainContainsReference(expr.expression, reference)) { type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 || t.flags & 128 && t.value === "undefined"); }); } } if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + type = narrowTypeBySwitchOnDiscriminantProperty(type, expr, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } } return createFlowType(type, isIncomplete(flowType)); @@ -53559,16 +55221,42 @@ var ts; if (propName === undefined) { return type; } - var propType = getTypeOfPropertyOfType(type, propName); + var removeNullable = strictNullChecks && ts.isOptionalChain(access) && maybeTypeOfKind(type, 98304); + var propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, 2097152) : type, propName); if (!propType) { return type; } + propType = removeNullable ? getOptionalType(propType) : propType; var narrowedPropType = narrowType(propType); return filterType(type, function (t) { var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName); return !(discriminantType.flags & 131072) && isTypeComparableTo(discriminantType, narrowedPropType); }); } + function narrowTypeByDiscriminantProperty(type, access, operator, value, assumeTrue) { + if ((operator === 36 || operator === 37) && type.flags & 1048576) { + var keyPropertyName = getKeyPropertyName(type); + if (keyPropertyName && keyPropertyName === getAccessedPropertyName(access)) { + var candidate_2 = getConstituentTypeForKeyType(type, getTypeOfExpression(value)); + if (candidate_2) { + return operator === (assumeTrue ? 36 : 37) ? candidate_2 : + isUnitType(getTypeOfPropertyOfType(candidate_2, keyPropertyName) || unknownType) ? filterType(type, function (t) { return t !== candidate_2; }) : + type; + } + } + } + return narrowTypeByDiscriminant(type, access, function (t) { return narrowTypeByEquality(t, operator, value, assumeTrue); }); + } + function narrowTypeBySwitchOnDiscriminantProperty(type, access, switchStatement, clauseStart, clauseEnd) { + if (clauseStart < clauseEnd && type.flags & 1048576 && getKeyPropertyName(type) === getAccessedPropertyName(access)) { + var clauseTypes = getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd); + var candidate = getUnionType(ts.map(clauseTypes, function (t) { return getConstituentTypeForKeyType(type, t) || unknownType; })); + if (candidate !== unknownType) { + return candidate; + } + } + return narrowTypeByDiscriminant(type, access, function (t) { return narrowTypeBySwitchOnDiscriminant(t, switchStatement, clauseStart, clauseEnd); }); + } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? 4194304 : 8388608); @@ -53592,7 +55280,8 @@ var ts; return !assumeTrue; } function narrowByInKeyword(type, literal, assumeTrue) { - if (type.flags & (1048576 | 524288) + if (type.flags & 1048576 + || type.flags & 524288 && declaredType !== type || isThisTypeParameter(type) || type.flags & 2097152 && ts.every(type.types, function (t) { return t.symbol !== globalThisSymbol; })) { var propName_1 = ts.escapeLeadingUnderscores(literal.text); @@ -53611,40 +55300,40 @@ var ts; case 35: case 36: case 37: - var operator_1 = expr.operatorToken.kind; - var left_1 = getReferenceCandidate(expr.left); - var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 211 && ts.isStringLiteralLike(right_1)) { - return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + var operator = expr.operatorToken.kind; + var left = getReferenceCandidate(expr.left); + var right = getReferenceCandidate(expr.right); + if (left.kind === 212 && ts.isStringLiteralLike(right)) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); } - if (right_1.kind === 211 && ts.isStringLiteralLike(left_1)) { - return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + if (right.kind === 212 && ts.isStringLiteralLike(left)) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); } - if (isMatchingReference(reference, left_1)) { - return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + if (isMatchingReference(reference, left)) { + return narrowTypeByEquality(type, operator, right, assumeTrue); } - if (isMatchingReference(reference, right_1)) { - return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + if (isMatchingReference(reference, right)) { + return narrowTypeByEquality(type, operator, left, assumeTrue); } if (strictNullChecks) { - if (optionalChainContainsReference(left_1, reference)) { - type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue); + if (optionalChainContainsReference(left, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator, right, assumeTrue); } - else if (optionalChainContainsReference(right_1, reference)) { - type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); + else if (optionalChainContainsReference(right, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator, left, assumeTrue); } } - if (isMatchingReferenceDiscriminant(left_1, type)) { - return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + if (isMatchingReferenceDiscriminant(left, type)) { + return narrowTypeByDiscriminantProperty(type, left, operator, right, assumeTrue); } - if (isMatchingReferenceDiscriminant(right_1, type)) { - return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + if (isMatchingReferenceDiscriminant(right, type)) { + return narrowTypeByDiscriminantProperty(type, right, operator, left, assumeTrue); } - if (isMatchingConstructorReference(left_1)) { - return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue); + if (isMatchingConstructorReference(left)) { + return narrowTypeByConstructor(type, operator, right, assumeTrue); } - if (isMatchingConstructorReference(right_1)) { - return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue); + if (isMatchingConstructorReference(right)) { + return narrowTypeByConstructor(type, operator, left, assumeTrue); } break; case 101: @@ -53699,13 +55388,12 @@ var ts; } if (assumeTrue) { var filterFn = operator === 34 ? - (function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); }) : + function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); } : function (t) { return areTypesComparable(t, valueType); }; return replacePrimitivesWithLiterals(filterType(type, filterFn), valueType); } if (isUnitType(valueType)) { - var regularType_1 = getRegularTypeOfLiteralType(valueType); - return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; }); + return filterType(type, function (t) { return !(isUnitLikeType(t) && areTypesComparable(t, valueType)); }); } return type; } @@ -53724,7 +55412,7 @@ var ts; return type; } if (assumeTrue && type.flags & 2 && literal.text === "object") { - if (typeOfExpr.parent.parent.kind === 216) { + if (typeOfExpr.parent.parent.kind === 217) { var expr = typeOfExpr.parent.parent; if (expr.operatorToken.kind === 55 && expr.right === typeOfExpr.parent && containsTruthyCheck(reference, expr.left)) { return nonPrimitiveType; @@ -53776,7 +55464,7 @@ var ts; if (!hasDefaultClause) { return caseType; } - var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + var defaultType = filterType(type, function (t) { return !(isUnitLikeType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(extractUnitType(t)))); }); return caseType.flags & 131072 ? defaultType : getUnionType([caseType, defaultType]); } function getImpliedTypeFromTypeofGuard(type, text) { @@ -53904,7 +55592,16 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { - return filterType(type, function (t) { return !isRelated(t, candidate); }); + return filterType(type, function (t) { + if (!isRelated(t, candidate)) { + return true; + } + var constraint = getBaseConstraintOfType(t); + if (constraint && constraint !== t) { + return !isRelated(constraint, candidate); + } + return false; + }); } if (type.flags & 1048576) { var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); @@ -53912,7 +55609,10 @@ var ts; return assignableType; } } - return isTypeSubtypeOf(candidate, type) ? candidate : isTypeSubtypeOf(type, candidate) ? type : getIntersectionType([type, candidate]); + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -53951,17 +55651,17 @@ var ts; case 78: case 107: case 105: - case 201: case 202: - return narrowTypeByTruthiness(type, expr, assumeTrue); case 203: + return narrowTypeByTruthiness(type, expr, assumeTrue); + case 204: return narrowTypeByCallExpression(type, expr, assumeTrue); - case 207: - case 225: + case 208: + case 226: return narrowType(type, expr.expression, assumeTrue); - case 216: + case 217: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 214: + case 215: if (expr.operator === 53) { return narrowType(type, expr.operand, !assumeTrue); } @@ -53981,28 +55681,34 @@ var ts; } function getTypeOfSymbolAtLocation(symbol, location) { symbol = symbol.exportSymbol || symbol; - if (location.kind === 78) { + if (location.kind === 78 || location.kind === 79) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { + if (ts.isExpressionNode(location) && (!ts.isAssignmentTarget(location) || ts.isWriteAccess(location))) { var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } } } + if (ts.isDeclarationName(location) && ts.isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) { + return resolveTypeOfAccessors(location.parent.symbol, true); + } return getTypeOfSymbol(symbol); } function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 257 || - node.kind === 297 || - node.kind === 163; + node.kind === 258 || + node.kind === 298 || + node.kind === 164; }); } function isParameterAssigned(symbol) { + if (!symbol.valueDeclaration) { + return false; + } var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); if (!(links.flags & 8388608)) { @@ -54020,7 +55726,7 @@ var ts; if (node.kind === 78) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 160) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 161) { symbol.isAssigned = true; } } @@ -54035,7 +55741,7 @@ var ts; function removeOptionalityFromDeclaredType(declaredType, declaration) { if (pushTypeResolution(declaration.symbol, 2)) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 160 && + declaration.kind === 161 && declaration.initializer && getFalsyFlags(declaredType) & 32768 && !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768); @@ -54049,19 +55755,28 @@ var ts; } function isConstraintPosition(node) { var parent = node.parent; - return parent.kind === 201 || - parent.kind === 203 && parent.expression === node || - parent.kind === 202 && parent.expression === node || - parent.kind === 198 && parent.name === node && !!parent.initializer; + return parent.kind === 202 || + parent.kind === 204 && parent.expression === node || + parent.kind === 203 && parent.expression === node && + !isGenericIndexType(getTypeOfExpression(parent.argumentExpression)); } - function typeHasNullableConstraint(type) { - return type.flags & 58982400 && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 98304); + function isGenericTypeWithUnionConstraint(type) { + return !!(type.flags & 465829888 && getBaseConstraintOrType(type).flags & (98304 | 1048576)); } - function getConstraintForLocation(type, node) { - if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { - return mapType(getWidenedType(type), getBaseConstraintOrType); - } - return type; + function containsGenericType(type) { + return !!(type.flags & 465829888 || type.flags & 3145728 && ts.some(type.types, containsGenericType)); + } + function hasContextualTypeWithNoGenericTypes(node) { + var contextualType = (ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && + !((ts.isJsxOpeningElement(node.parent) || ts.isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && + getContextualType(node); + return contextualType && !someType(contextualType, containsGenericType); + } + function getNarrowableTypeForReference(type, reference, checkMode) { + var substituteConstraints = !(checkMode && checkMode & 2) && + someType(type, isGenericTypeWithUnionConstraint) && + (isConstraintPosition(reference) || hasContextualTypeWithNoGenericTypes(reference)); + return substituteConstraints ? mapType(type, function (t) { return t.flags & 465829888 ? getBaseConstraintOrType(t) : t; }) : type; } function isExportOrExportExpression(location) { return !!ts.findAncestor(location, function (e) { return e.parent && ts.isExportAssignment(e.parent) && e.parent.expression === e && ts.isEntityNameExpression(e); }); @@ -54070,7 +55785,9 @@ var ts; if (isNonLocalAlias(symbol, 111551) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { var target = resolveAlias(symbol); if (target.flags & 111551) { - if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(target)) { + if (compilerOptions.isolatedModules || + ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || + !isConstEnumOrConstEnumOnlyModule(target)) { markAliasSymbolAsReferenced(symbol); } else { @@ -54079,7 +55796,7 @@ var ts; } } } - function checkIdentifier(node) { + function checkIdentifier(node, checkMode) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { return errorType; @@ -54087,7 +55804,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2) { - if (container.kind === 209) { + if (container.kind === 210) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasSyntacticModifier(container, 256)) { @@ -54102,12 +55819,12 @@ var ts; } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var sourceSymbol = localOrExportSymbol.flags & 2097152 ? resolveAlias(localOrExportSymbol) : localOrExportSymbol; - if (getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 && isUncalledFunctionReference(node, sourceSymbol)) { - errorOrSuggestion(false, node, ts.Diagnostics._0_is_deprecated, node.escapedText); + if (sourceSymbol.declarations && getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 && isUncalledFunctionReference(node, sourceSymbol)) { + addDeprecatedSuggestion(node, sourceSymbol.declarations, node.escapedText); } var declaration = localOrExportSymbol.valueDeclaration; - if (localOrExportSymbol.flags & 32) { - if (declaration.kind === 252 + if (declaration && localOrExportSymbol.flags & 32) { + if (declaration.kind === 253 && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -54119,11 +55836,11 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration.kind === 221) { + else if (declaration.kind === 222) { var container = ts.getThisContainer(node, false); - while (container.kind !== 297) { + while (container.kind !== 298) { if (container.parent === declaration) { - if (container.kind === 163 && ts.hasSyntacticModifier(container, 32)) { + if (container.kind === 164 && ts.hasSyntacticModifier(container, 32)) { getNodeLinks(declaration).flags |= 16777216; getNodeLinks(node).flags |= 33554432; } @@ -54134,12 +55851,18 @@ var ts; } } checkNestedBlockScopedBinding(node, symbol); - var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); + var type = getTypeOfSymbol(localOrExportSymbol); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3) && !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + var assignmentError = localOrExportSymbol.flags & 384 ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_an_enum + : localOrExportSymbol.flags & 32 ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_class + : localOrExportSymbol.flags & 1536 ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_namespace + : localOrExportSymbol.flags & 16 ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_function + : localOrExportSymbol.flags & 2097152 ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_an_import + : ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable; + error(node, assignmentError, symbolToString(symbol)); return errorType; } if (isReadonlySymbol(localOrExportSymbol)) { @@ -54159,7 +55882,7 @@ var ts; } } else if (isAlias) { - declaration = ts.find(symbol.declarations, isSomeImportDeclaration); + declaration = getDeclarationOfAliasSymbol(symbol); } else { return type; @@ -54167,22 +55890,23 @@ var ts; if (!declaration) { return type; } - var isParameter = ts.getRootDeclaration(declaration).kind === 160; + type = getNarrowableTypeForReference(type, node, checkMode); + var isParameter = ts.getRootDeclaration(declaration).kind === 161; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); var isModuleExports = symbol.flags & 134217728; - while (flowContainer !== declarationContainer && (flowContainer.kind === 208 || - flowContainer.kind === 209 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 209 || + flowContainer.kind === 210 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 | 16384)) !== 0 || - isInTypeQuery(node) || node.parent.kind === 270) || - node.parent.kind === 225 || - declaration.kind === 249 && declaration.exclamationToken || + isInTypeQuery(node) || node.parent.kind === 271) || + node.parent.kind === 226 || + declaration.kind === 250 && declaration.exclamationToken || declaration.flags & 8388608; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : type === autoType || type === autoArrayType ? undefinedType : @@ -54203,35 +55927,31 @@ var ts; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } - function isInsideFunction(node, threshold) { - return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); + function isInsideFunctionOrInstancePropertyInitializer(node, threshold) { + return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n) || (n.parent && ts.isPropertyDeclaration(n.parent) && !ts.hasStaticModifier(n.parent) && n.parent.initializer === n); }); } 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 getEnclosingIterationStatement(node) { + return ts.findAncestor(node, function (n) { return (!n || ts.nodeStartsNewLexicalEnvironment(n)) ? "quit" : ts.isIterationStatement(n, false); }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 || (symbol.flags & (2 | 32)) === 0 || + !symbol.valueDeclaration || ts.isSourceFile(symbol.valueDeclaration) || - symbol.valueDeclaration.parent.kind === 287) { + symbol.valueDeclaration.parent.kind === 288) { return; } var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - var usedInFunction = isInsideFunction(node.parent, container); - var current = container; - var containedInIterationStatement = false; - while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { - if (ts.isIterationStatement(current, false)) { - containedInIterationStatement = true; - break; - } - current = current.parent; - } - if (containedInIterationStatement) { - if (usedInFunction) { + var isCaptured = isInsideFunctionOrInstancePropertyInitializer(node, container); + var enclosingIterationStatement = getEnclosingIterationStatement(container); + if (enclosingIterationStatement) { + if (isCaptured) { var capturesBlockScopeBindingInLoopBody = true; if (ts.isForStatement(container)) { - var varDeclList = ts.getAncestor(symbol.valueDeclaration, 250); + var varDeclList = ts.getAncestor(symbol.valueDeclaration, 251); if (varDeclList && varDeclList.parent === container) { var part = getPartOfForStatementContainingNode(node.parent, container); if (part) { @@ -54246,18 +55966,18 @@ var ts; } } if (capturesBlockScopeBindingInLoopBody) { - getNodeLinks(current).flags |= 65536; + getNodeLinks(enclosingIterationStatement).flags |= 65536; } } if (ts.isForStatement(container)) { - var varDeclList = ts.getAncestor(symbol.valueDeclaration, 250); + var varDeclList = ts.getAncestor(symbol.valueDeclaration, 251); if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 4194304; } } getNodeLinks(symbol.valueDeclaration).flags |= 524288; } - if (usedInFunction) { + if (isCaptured) { getNodeLinks(symbol.valueDeclaration).flags |= 262144; } } @@ -54267,14 +55987,14 @@ var ts; } function isAssignedInBodyOfForStatement(node, container) { var current = node; - while (current.parent.kind === 207) { + while (current.parent.kind === 208) { current = current.parent; } var isAssigned = false; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 214 || current.parent.kind === 215)) { + else if ((current.parent.kind === 215 || current.parent.kind === 216)) { var expr = current.parent; isAssigned = expr.operator === 45 || expr.operator === 46; } @@ -54285,7 +56005,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2; - if (container.kind === 163 || container.kind === 166) { + if (container.kind === 164 || container.kind === 167) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4; } @@ -54316,32 +56036,32 @@ var ts; function checkThisExpression(node) { var container = ts.getThisContainer(node, true); var capturedByArrowFunction = false; - if (container.kind === 166) { + if (container.kind === 167) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } - if (container.kind === 209) { + if (container.kind === 210) { container = ts.getThisContainer(container, false); capturedByArrowFunction = true; } switch (container.kind) { - case 256: + case 257: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); break; - case 255: + case 256: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); break; - case 166: + case 167: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); } break; + case 164: case 163: - case 162: - if (ts.hasSyntacticModifier(container, 32) && !(compilerOptions.target === 99 && compilerOptions.useDefineForClassFields)) { + if (ts.hasSyntacticModifier(container, 32) && !(compilerOptions.target === 99 && useDefineForClassFields)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; - case 158: + case 159: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -54422,7 +56142,7 @@ var ts; } } function getClassNameFromPrototypeMethod(container) { - if (container.kind === 208 && + if (container.kind === 209 && ts.isBinaryExpression(container.parent) && ts.getAssignmentDeclarationKind(container.parent) === 3) { return container.parent @@ -54430,20 +56150,20 @@ var ts; .expression .expression; } - else if (container.kind === 165 && - container.parent.kind === 200 && + else if (container.kind === 166 && + container.parent.kind === 201 && ts.isBinaryExpression(container.parent.parent) && ts.getAssignmentDeclarationKind(container.parent.parent) === 6) { return container.parent.parent.left.expression; } - else if (container.kind === 208 && - container.parent.kind === 288 && - container.parent.parent.kind === 200 && + else if (container.kind === 209 && + container.parent.kind === 289 && + container.parent.parent.kind === 201 && ts.isBinaryExpression(container.parent.parent.parent) && ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6) { return container.parent.parent.parent.left.expression; } - else if (container.kind === 208 && + else if (container.kind === 209 && ts.isPropertyAssignment(container.parent) && ts.isIdentifier(container.parent.name) && (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && @@ -54465,7 +56185,7 @@ var ts; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 308) { + if (jsdocType && jsdocType.kind === 309) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -54479,15 +56199,15 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 160 && n.parent === constructorDecl; }); + return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 161 && n.parent === constructorDecl; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 203 && node.parent.expression === node; + var isCallExpression = node.parent.kind === 204 && node.parent.expression === node; var immediateContainer = ts.getSuperContainer(node, true); var container = immediateContainer; var needToCaptureLexicalThis = false; if (!isCallExpression) { - while (container && container.kind === 209) { + while (container && container.kind === 210) { container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = languageVersion < 2; } @@ -54495,14 +56215,14 @@ var ts; var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; if (!canUseSuperExpression) { - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 158; }); - if (current && current.kind === 158) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 159; }); + if (current && current.kind === 159) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 200)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 201)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -54510,7 +56230,7 @@ var ts; } return errorType; } - if (!isCallExpression && immediateContainer.kind === 166) { + if (!isCallExpression && immediateContainer.kind === 167) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } if (ts.hasSyntacticModifier(container, 32) || isCallExpression) { @@ -54520,7 +56240,7 @@ var ts; nodeCheckFlag = 256; } getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 165 && ts.hasSyntacticModifier(container, 256)) { + if (container.kind === 166 && ts.hasSyntacticModifier(container, 256)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096; } @@ -54531,7 +56251,7 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node.parent, container); } - if (container.parent.kind === 200) { + if (container.parent.kind === 201) { if (languageVersion < 2) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return errorType; @@ -54550,7 +56270,7 @@ var ts; if (!baseClassType) { return errorType; } - if (container.kind === 166 && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 167 && isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return errorType; } @@ -54562,24 +56282,24 @@ var ts; return false; } if (isCallExpression) { - return container.kind === 166; + return container.kind === 167; } else { - if (ts.isClassLike(container.parent) || container.parent.kind === 200) { + if (ts.isClassLike(container.parent) || container.parent.kind === 201) { if (ts.hasSyntacticModifier(container, 32)) { - return container.kind === 165 || - container.kind === 164 || - container.kind === 167 || - container.kind === 168; + return container.kind === 166 || + container.kind === 165 || + container.kind === 168 || + container.kind === 169; } else { - return container.kind === 165 || - container.kind === 164 || - container.kind === 167 || + return container.kind === 166 || + container.kind === 165 || container.kind === 168 || + container.kind === 169 || + container.kind === 164 || container.kind === 163 || - container.kind === 162 || - container.kind === 166; + container.kind === 167; } } } @@ -54587,10 +56307,10 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 165 || - func.kind === 167 || - func.kind === 168) && func.parent.kind === 200 ? func.parent : - func.kind === 208 && func.parent.kind === 288 ? func.parent.parent : + return (func.kind === 166 || + func.kind === 168 || + func.kind === 169) && func.parent.kind === 201 ? func.parent : + func.kind === 209 && func.parent.kind === 289 ? func.parent.parent : undefined; } function getThisTypeArgument(type) { @@ -54602,7 +56322,7 @@ var ts; }); } function getContextualThisParameterType(func) { - if (func.kind === 209) { + if (func.kind === 210) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -54626,7 +56346,7 @@ var ts; if (thisType) { return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral))); } - if (literal.parent.kind !== 288) { + if (literal.parent.kind !== 289) { break; } literal = literal.parent.parent; @@ -54635,7 +56355,7 @@ var ts; return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral)); } var parent = ts.walkUpParenthesizedExpressions(func.parent); - if (parent.kind === 216 && parent.operatorToken.kind === 62) { + if (parent.kind === 217 && parent.operatorToken.kind === 62) { var target = parent.left; if (ts.isAccessExpression(target)) { var expression = target.expression; @@ -54686,11 +56406,11 @@ var ts; return getTypeFromTypeNode(typeNode); } switch (declaration.kind) { - case 160: + case 161: return getContextuallyTypedParameterType(declaration); - case 198: + case 199: return getContextualTypeForBindingElement(declaration); - case 163: + case 164: if (ts.hasSyntacticModifier(declaration, 32)) { return getContextualTypeForStaticPropertyDeclaration(declaration); } @@ -54700,10 +56420,10 @@ var ts; var parent = declaration.parent.parent; var name = declaration.propertyName || declaration.name; var parentType = getContextualTypeForVariableLikeDeclaration(parent) || - parent.kind !== 198 && parent.initializer && checkDeclarationInitializer(parent); + parent.kind !== 199 && parent.initializer && checkDeclarationInitializer(parent); if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name)) return undefined; - if (parent.name.kind === 197) { + if (parent.name.kind === 198) { var index = ts.indexOfNode(declaration.parent.elements, declaration); if (index < 0) return undefined; @@ -54824,7 +56544,7 @@ var ts; return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 205) { + if (template.parent.kind === 206) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -54851,16 +56571,16 @@ var ts; } } function getContextualTypeForAssignmentDeclaration(binaryExpression) { + var _a, _b; var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0: return getTypeOfExpression(binaryExpression.left); + case 4: + return getContextualTypeForThisPropertyAssignment(binaryExpression); case 5: - case 1: - case 6: - case 3: if (isPossiblyAliasedThisProperty(binaryExpression, kind)) { - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + return getContextualTypeForThisPropertyAssignment(binaryExpression); } else if (!binaryExpression.left.symbol) { return getTypeOfExpression(binaryExpression.left); @@ -54879,11 +56599,11 @@ var ts; var id = lhs.expression; var parentSymbol = resolveName(id, id.escapedText, 111551, undefined, id.escapedText, true); if (parentSymbol) { - var annotated = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); - if (annotated) { + var annotated_1 = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated_1) { var nameStr = ts.getElementOrPropertyAccessName(lhs); if (nameStr !== undefined) { - return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr); + return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated_1), nameStr); } } return undefined; @@ -54891,9 +56611,14 @@ var ts; } return ts.isInJSFile(decl) ? undefined : getTypeOfExpression(binaryExpression.left); } + case 1: + case 6: + case 3: + var valueDeclaration = (_a = binaryExpression.left.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration; case 2: - case 4: - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + valueDeclaration || (valueDeclaration = (_b = binaryExpression.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration); + var annotated = valueDeclaration && ts.getEffectiveTypeAnnotationNode(valueDeclaration); + return annotated ? getTypeFromTypeNode(annotated) : undefined; case 7: case 8: case 9: @@ -54914,7 +56639,7 @@ var ts; var symbol = resolveName(declaration.left, name, 111551, undefined, undefined, true, true); return ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration); } - function getContextualTypeForThisPropertyAssignment(binaryExpression, kind) { + function getContextualTypeForThisPropertyAssignment(binaryExpression) { if (!binaryExpression.symbol) return getTypeOfExpression(binaryExpression.left); if (binaryExpression.symbol.valueDeclaration) { @@ -54926,8 +56651,6 @@ var ts; } } } - if (kind === 2) - return undefined; var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression); if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, false))) { return undefined; @@ -54978,9 +56701,13 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + if (propertyAssignmentType) { + return propertyAssignmentType; + } var type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { - if (!hasNonBindableDynamicName(element)) { + if (hasBindableName(element)) { var symbolName_3 = getSymbolOfNode(element).escapedName; var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); if (propertyType) { @@ -55050,19 +56777,19 @@ var ts; case 78: case 150: return true; - case 201: - case 207: + case 202: + case 208: return isPossiblyDiscriminantValue(node.expression); - case 283: + case 284: 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 === 288 && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 289 && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 280 && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function getApparentTypeOfContextualType(node, contextFlags) { var contextualType = ts.isObjectLiteralMethod(node) ? @@ -55071,15 +56798,9 @@ var ts; var instantiatedType = instantiateContextualType(contextualType, node, contextFlags); if (instantiatedType && !(contextFlags && contextFlags & 2 && instantiatedType.flags & 8650752)) { var apparentType = mapType(instantiatedType, getApparentType, true); - if (apparentType.flags & 1048576) { - if (ts.isObjectLiteralExpression(node)) { - return discriminateContextualTypeByObjectMembers(node, apparentType); - } - else if (ts.isJsxAttributes(node)) { - return discriminateContextualTypeByJSXAttributes(node, apparentType); - } - } - return apparentType; + return apparentType.flags & 1048576 && ts.isObjectLiteralExpression(node) ? discriminateContextualTypeByObjectMembers(node, apparentType) : + apparentType.flags & 1048576 && ts.isJsxAttributes(node) ? discriminateContextualTypeByJSXAttributes(node, apparentType) : + apparentType; } } function instantiateContextualType(contextualType, node, contextFlags) { @@ -55117,56 +56838,58 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 249: - case 160: + case 250: + case 161: + case 164: case 163: - case 162: - case 198: + case 199: return getContextualTypeForInitializerExpression(node, contextFlags); - case 209: - case 242: + case 210: + case 243: return getContextualTypeForReturnExpression(node); - case 219: + case 220: return getContextualTypeForYieldOperand(parent); - case 213: + case 214: return getContextualTypeForAwaitOperand(parent, contextFlags); - case 203: + case 204: if (parent.expression.kind === 99) { return stringType; } - case 204: + case 205: return getContextualTypeForArgument(parent, node); - case 206: - case 224: + case 207: + case 225: return ts.isConstTypeReference(parent.type) ? tryFindWhenConstTypeReference(parent) : getTypeFromTypeNode(parent.type); - case 216: + case 217: return getContextualTypeForBinaryOperand(node, contextFlags); - case 288: case 289: - return getContextualTypeForObjectLiteralElement(parent, contextFlags); case 290: - return getApparentTypeOfContextualType(parent.parent, contextFlags); - case 199: { + return getContextualTypeForObjectLiteralElement(parent, contextFlags); + case 291: + return getContextualType(parent.parent, contextFlags); + case 200: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 217: + case 218: return getContextualTypeForConditionalOperand(node, contextFlags); - case 228: - ts.Debug.assert(parent.parent.kind === 218); + case 229: + ts.Debug.assert(parent.parent.kind === 219); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 207: { + case 208: { var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags); } - case 283: + case 226: + return getContextualType(parent, contextFlags); + case 284: return getContextualTypeForJsxExpression(parent); - case 280: - case 282: + case 281: + case 283: return getContextualTypeForJsxAttribute(parent); + case 276: case 275: - case 274: return getContextualJsxElementAttributesType(parent, contextFlags); } return undefined; @@ -55199,9 +56922,9 @@ var ts; return propsType; } function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { - if (sig.unionSignatures) { + if (sig.compositeSignatures) { var results = []; - for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) { + for (var _i = 0, _a = sig.compositeSignatures; _i < _a.length; _i++) { var signature = _a[_i]; var instance = getReturnTypeOfSignature(signature); if (isTypeAny(instance)) { @@ -55240,14 +56963,17 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); var ctorType = getStaticTypeOfReferencedJsxConstructor(context); + if (managedSym.flags & 524288) { + var params = getSymbolLinks(managedSym).typeParameters; + if (ts.length(params) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], params, 2, ts.isInJSFile(context)); + return getTypeAliasInstantiation(managedSym, args); + } + } if (ts.length(declaredManagedType.typeParameters) >= 2) { var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } - else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); - return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); - } } return attributesType; } @@ -55286,14 +57012,85 @@ var ts; return apparentAttributesType; } } - function getContextualCallSignature(type, node) { - var signatures = getSignaturesOfType(type, 0); - if (signatures.length === 1) { - var signature = signatures[0]; - if (!isAritySmaller(signature, node)) { - return signature; + function getIntersectedSignatures(signatures) { + return ts.getStrictOptionValue(compilerOptions, "noImplicitAny") + ? ts.reduceLeft(signatures, function (left, right) { + return left === right || !left ? left + : compareTypeParametersIdentical(left.typeParameters, right.typeParameters) ? combineSignaturesOfIntersectionMembers(left, right) + : undefined; + }) + : undefined; + } + function combineIntersectionThisParam(left, right, mapper) { + if (!left || !right) { + return left || right; + } + var thisType = getUnionType([getTypeOfSymbol(left), instantiateType(getTypeOfSymbol(right), mapper)]); + return createSymbolWithType(left, thisType); + } + function combineIntersectionParameters(left, right, mapper) { + var leftCount = getParameterCount(left); + var rightCount = getParameterCount(right); + var longest = leftCount >= rightCount ? left : right; + var shorter = longest === left ? right : left; + var longestCount = longest === left ? leftCount : rightCount; + var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right)); + var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest); + var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0)); + for (var i = 0; i < longestCount; i++) { + var longestParamType = tryGetTypeAtPosition(longest, i); + if (longest === right) { + longestParamType = instantiateType(longestParamType, mapper); + } + var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType; + if (shorter === right) { + shorterParamType = instantiateType(shorterParamType, mapper); + } + var unionParamType = getUnionType([longestParamType, shorterParamType]); + var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1); + var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter); + var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i); + var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i); + var paramName = leftName === rightName ? leftName : + !leftName ? rightName : + !rightName ? leftName : + undefined; + var paramSymbol = createSymbol(1 | (isOptional && !isRestParam ? 16777216 : 0), paramName || "arg" + i); + paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType; + params[i] = paramSymbol; + } + if (needsExtraRestElement) { + var restParamSymbol = createSymbol(1, "args"); + restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount)); + if (shorter === right) { + restParamSymbol.type = instantiateType(restParamSymbol.type, mapper); } + params[longestCount] = restParamSymbol; + } + return params; + } + function combineSignaturesOfIntersectionMembers(left, right) { + var typeParams = left.typeParameters || right.typeParameters; + var paramMapper; + if (left.typeParameters && right.typeParameters) { + paramMapper = createTypeMapper(right.typeParameters, left.typeParameters); + } + var declaration = left.declaration; + var params = combineIntersectionParameters(left, right, paramMapper); + var thisParam = combineIntersectionThisParam(left.thisParameter, right.thisParameter, paramMapper); + var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); + var result = createSignature(declaration, typeParams, thisParam, params, undefined, undefined, minArgCount, (left.flags | right.flags) & 39); + result.compositeKind = 2097152; + result.compositeSignatures = ts.concatenate(left.compositeKind === 2097152 && left.compositeSignatures || [left], [right]); + if (paramMapper) { + result.mapper = left.compositeKind === 2097152 && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; } + return result; + } + function getContextualCallSignature(type, node) { + var signatures = getSignaturesOfType(type, 0); + var applicableByArity = ts.filter(signatures, function (s) { return !isAritySmaller(s, node); }); + return applicableByArity.length === 1 ? applicableByArity[0] : getIntersectedSignatures(applicableByArity); } function isAritySmaller(signature, target) { var targetParameterCount = 0; @@ -55309,7 +57106,7 @@ var ts; return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 208 || node.kind === 209; + return node.kind === 209 || node.kind === 210; } function getContextualSignatureForFunctionLikeDeclaration(node) { return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) @@ -55317,7 +57114,7 @@ var ts; : undefined; } function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 165 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 || ts.isObjectLiteralMethod(node)); var typeTagSignature = getSignatureOfTypeTag(node); if (typeTagSignature) { return typeTagSignature; @@ -55361,8 +57158,8 @@ var ts; return node.isSpread ? getIndexedAccessType(node.type, numberType) : node.type; } function hasDefaultValue(node) { - return (node.kind === 198 && !!node.initializer) || - (node.kind === 216 && node.operatorToken.kind === 62); + return (node.kind === 199 && !!node.initializer) || + (node.kind === 217 && node.operatorToken.kind === 62); } function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; @@ -55374,7 +57171,7 @@ var ts; var inConstContext = isConstContext(node); for (var i = 0; i < elementCount; i++) { var e = elements[i]; - if (e.kind === 220) { + if (e.kind === 221) { if (languageVersion < 2) { checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 : 1024); } @@ -55405,7 +57202,7 @@ var ts; if (inDestructuringPattern) { return createTupleType(elementTypes, elementFlags); } - if (forceTuple || inConstContext || contextualType && forEachType(contextualType, isTupleLikeType)) { + if (forceTuple || inConstContext || contextualType && someType(contextualType, isTupleLikeType)) { return createArrayLiteralType(createTupleType(elementTypes, elementFlags, inConstContext)); } return createArrayLiteralType(createArrayType(elementTypes.length ? @@ -55419,13 +57216,13 @@ var ts; var literalType = type.literalType; if (!literalType) { literalType = type.literalType = cloneTypeReference(type); - literalType.objectFlags |= 65536 | 1048576; + literalType.objectFlags |= 32768 | 262144; } return literalType; } function isNumericName(name) { switch (name.kind) { - case 158: + case 159: return isNumericComputedName(name); case 78: return isNumericLiteralName(name.escapedText); @@ -55449,14 +57246,20 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); + if (ts.isPropertyDeclaration(node.parent) && !ts.hasStaticModifier(node.parent) && ts.isClassExpression(node.parent.parent)) { + var container = ts.getEnclosingBlockScopeContainer(node.parent.parent); + var enclosingIterationStatement = getEnclosingIterationStatement(container); + if (enclosingIterationStatement) { + getNodeLinks(enclosingIterationStatement).flags |= 65536; + getNodeLinks(node).flags |= 524288; + getNodeLinks(node.parent.parent).flags |= 524288; + } + } if (links.resolvedType.flags & 98304 || !isTypeAssignableToKind(links.resolvedType, 402653316 | 296 | 12288) && !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } - else { - checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, true); - } } return links.resolvedType; } @@ -55495,7 +57298,7 @@ var ts; var spread = emptyObjectType; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 196 || contextualType.pattern.kind === 200); + (contextualType.pattern.kind === 197 || contextualType.pattern.kind === 201); var inConstContext = isConstContext(node); var checkFlags = inConstContext ? 8 : 0; var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); @@ -55507,7 +57310,7 @@ var ts; var hasComputedNumberProperty = false; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; - if (elem.name && ts.isComputedPropertyName(elem.name) && !ts.isWellKnownSymbolSyntactically(elem.name)) { + if (elem.name && ts.isComputedPropertyName(elem.name)) { checkComputedPropertyName(elem.name); } } @@ -55515,13 +57318,13 @@ var ts; for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var memberDecl = _c[_b]; var member = getSymbolOfNode(memberDecl); - var computedNameType = memberDecl.name && memberDecl.name.kind === 158 && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + var computedNameType = memberDecl.name && memberDecl.name.kind === 159 ? checkComputedPropertyName(memberDecl.name) : undefined; - if (memberDecl.kind === 288 || - memberDecl.kind === 289 || + if (memberDecl.kind === 289 || + memberDecl.kind === 290 || ts.isObjectLiteralMethod(memberDecl)) { - var type = memberDecl.kind === 288 ? checkPropertyAssignment(memberDecl, checkMode) : - memberDecl.kind === 289 ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : + var type = memberDecl.kind === 289 ? checkPropertyAssignment(memberDecl, checkMode) : + memberDecl.kind === 290 ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); @@ -55533,7 +57336,7 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= ts.getObjectFlags(type) & 3670016; + objectFlags |= ts.getObjectFlags(type) & 917504; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? createSymbol(4 | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096) : @@ -55542,8 +57345,8 @@ var ts; prop.nameType = nameType; } if (inDestructuringPattern) { - var isOptional = (memberDecl.kind === 288 && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 289 && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 289 && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 290 && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216; } @@ -55567,7 +57370,7 @@ var ts; member = prop; allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop); } - else if (memberDecl.kind === 290) { + else if (memberDecl.kind === 291) { if (languageVersion < 2) { checkExternalEmitHelpers(memberDecl, 2); } @@ -55579,19 +57382,24 @@ var ts; hasComputedNumberProperty = false; } var type = getReducedType(checkExpression(memberDecl.expression)); - if (!isValidSpreadType(type)) { - error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return errorType; + if (isValidSpreadType(type)) { + if (allPropertiesTable) { + checkSpreadPropOverrides(type, allPropertiesTable, memberDecl); + } + offset = propertiesArray.length; + if (spread === errorType) { + continue; + } + spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext); } - if (allPropertiesTable) { - checkSpreadPropOverrides(type, allPropertiesTable, memberDecl); + else { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + spread = errorType; } - spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext); - offset = propertiesArray.length; continue; } else { - ts.Debug.assert(memberDecl.kind === 167 || memberDecl.kind === 168); + ts.Debug.assert(memberDecl.kind === 168 || memberDecl.kind === 169); checkNodeDeferred(memberDecl); } if (computedNameType && !(computedNameType.flags & 8576)) { @@ -55612,7 +57420,7 @@ var ts; } propertiesArray.push(member); } - if (contextualTypeHasPattern && node.parent.kind !== 290) { + if (contextualTypeHasPattern && node.parent.kind !== 291) { for (var _d = 0, _e = getPropertiesOfType(contextualType); _d < _e.length; _d++) { var prop = _e[_d]; if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) { @@ -55624,6 +57432,9 @@ var ts; } } } + if (spread === errorType) { + return errorType; + } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext); @@ -55639,9 +57450,9 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= objectFlags | 128 | 1048576; + result.objectFlags |= objectFlags | 128 | 262144; if (isJSObjectLiteral) { - result.objectFlags |= 16384; + result.objectFlags |= 8192; } if (patternWithComputedProperties) { result.objectFlags |= 512; @@ -55715,14 +57526,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var objectFlags = 4096; + var objectFlags = 2048; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= ts.getObjectFlags(exprType) & 3670016; + objectFlags |= ts.getObjectFlags(exprType) & 917504; var attributeSymbol = createSymbol(4 | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -55738,7 +57549,7 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 282); + ts.Debug.assert(attributeDecl.kind === 283); if (attributesTable.size > 0) { spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, false); attributesTable = ts.createSymbolTable(); @@ -55763,7 +57574,7 @@ var ts; spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, false); } } - var parent = openingLikeElement.parent.kind === 273 ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 274 ? openingLikeElement.parent : undefined; if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = checkJsxChildren(parent, checkMode); if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { @@ -55774,7 +57585,7 @@ var ts; var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); var childrenPropSymbol = createSymbol(4, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - childrenContextualType && forEachType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : + childrenContextualType && someType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : createArrayType(getUnionType(childrenTypes)); childrenPropSymbol.valueDeclaration = ts.factory.createPropertySignature(undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), undefined, undefined); ts.setParent(childrenPropSymbol.valueDeclaration, attributes); @@ -55794,7 +57605,7 @@ var ts; function createJsxAttributesType() { objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, undefined, undefined); - result.objectFlags |= objectFlags | 128 | 1048576; + result.objectFlags |= objectFlags | 128 | 262144; return result; } } @@ -55807,7 +57618,7 @@ var ts; childrenTypes.push(stringType); } } - else if (child.kind === 283 && !child.expression) { + else if (child.kind === 284 && !child.expression) { continue; } else { @@ -55930,7 +57741,7 @@ var ts; else if (propertiesOfJsxElementAttribPropInterface.length === 1) { return propertiesOfJsxElementAttribPropInterface[0].escapedName; } - else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + else if (propertiesOfJsxElementAttribPropInterface.length > 1 && jsxElementAttribPropInterfaceSym.declarations) { error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer)); } } @@ -56019,11 +57830,11 @@ var ts; if (!links.resolvedJsxElementAttributesType) { var symbol = getIntrinsicTagSymbol(node); if (links.jsxFlags & 1) { - return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol) || errorType; } else if (links.jsxFlags & 2) { return links.resolvedJsxElementAttributesType = - getIndexTypeOfType(getDeclaredTypeOfSymbol(symbol), 0); + getIndexTypeOfType(getJsxType(JsxNames.IntrinsicElements, node), 0) || errorType; } else { return links.resolvedJsxElementAttributesType = errorType; @@ -56140,34 +57951,37 @@ var ts; ts.getAssignmentDeclarationKind(parent) === 3; } } - function checkPropertyAccessibility(node, isSuper, type, prop) { - var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 157 ? node.right : node.kind === 195 ? node : node.name; + function checkPropertyAccessibility(node, isSuper, writing, type, prop, reportError) { + if (reportError === void 0) { reportError = true; } + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop, writing); + var errorNode = node.kind === 158 ? node.right : + node.kind === 196 ? node : + node.kind === 199 && node.propertyName ? node.propertyName : node.name; if (isSuper) { if (languageVersion < 2) { if (symbolHasNonMethodDeclaration(prop)) { - error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + if (reportError) { + error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + } return false; } } if (flags & 128) { - error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + if (reportError) { + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + } return false; } } - if ((flags & 128) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { + if ((flags & 128) && symbolHasNonMethodDeclaration(prop) && + (ts.isThisProperty(node) || ts.isThisInitializedObjectBindingExpression(node) || ts.isObjectBindingPattern(node.parent) && ts.isThisInitializedDeclaration(node.parent.parent))) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); 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; - } - } - if (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name)) { - if (!ts.getContainingClass(node)) { - error(errorNode, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + if (reportError) { + error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); + } return false; } - return true; } if (!(flags & 24)) { return true; @@ -56175,7 +57989,9 @@ var ts; if (flags & 8) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + if (reportError) { + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + } return false; } return true; @@ -56185,12 +58001,14 @@ var ts; } var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + return isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing) ? enclosingClass : undefined; }); if (!enclosingClass) { var thisParameter = void 0; if (flags & 32 || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + if (reportError) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + } return false; } var thisType = getTypeFromTypeNode(thisParameter.type); @@ -56203,7 +58021,9 @@ var ts; type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); } if (!type || !hasBaseType(type, enclosingClass)) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + if (reportError) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2, symbolToString(prop), typeToString(enclosingClass), typeToString(type)); + } return false; } return true; @@ -56259,20 +58079,20 @@ var ts; } return nonNullType; } - function checkPropertyAccessExpression(node) { - return node.flags & 32 ? checkPropertyAccessChain(node) : - checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + function checkPropertyAccessExpression(node, checkMode) { + return node.flags & 32 ? checkPropertyAccessChain(node, checkMode) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name, checkMode); } - function checkPropertyAccessChain(node) { + function checkPropertyAccessChain(node, checkMode) { var leftType = checkExpression(node.expression); var nonOptionalType = getOptionalExpressionType(leftType, node.expression); - return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name, checkMode), node, nonOptionalType !== leftType); } - function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); + function checkQualifiedName(node, checkMode) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right, checkMode); } function isMethodAccessForCall(node) { - while (node.parent.kind === 207) { + while (node.parent.kind === 208) { node = node.parent; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; @@ -56304,10 +58124,9 @@ var ts; } var diagName = diagnosticName(right); if (propertyOnType) { - var typeValueDecl = propertyOnType.valueDeclaration; - var typeClass_1 = ts.getContainingClass(typeValueDecl); - ts.Debug.assert(!!typeClass_1); - if (lexicallyScopedIdentifier) { + var typeValueDecl = ts.Debug.checkDefined(propertyOnType.valueDeclaration); + var typeClass_1 = ts.Debug.checkDefined(ts.getContainingClass(typeValueDecl)); + if (lexicallyScopedIdentifier === null || lexicallyScopedIdentifier === void 0 ? void 0 : lexicallyScopedIdentifier.valueDeclaration) { var lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration; var lexicalClass = ts.getContainingClass(lexicalValueDecl); ts.Debug.assert(!!lexicalClass); @@ -56326,17 +58145,42 @@ var ts; return (isConstructorDeclaredProperty(prop) || ts.isThisProperty(node) && isAutoTypedProperty(prop)) && ts.getThisContainer(node, true) === getDeclaringConstructor(prop); } - function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right, checkMode) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); var apparentType = getApparentType(assignmentKind !== 0 || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); - if (ts.isPrivateIdentifier(right)) { - checkExternalEmitHelpers(node, 524288); - } var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType; var prop; if (ts.isPrivateIdentifier(right)) { + if (languageVersion < 99) { + if (assignmentKind !== 0) { + checkExternalEmitHelpers(node, 1048576); + } + if (assignmentKind !== 1) { + checkExternalEmitHelpers(node, 524288); + } + } var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right); + if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && ts.isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) { + grammarErrorOnNode(right, ts.Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, ts.idText(right)); + } + if ((lexicallyScopedSymbol === null || lexicallyScopedSymbol === void 0 ? void 0 : lexicallyScopedSymbol.valueDeclaration) && (compilerOptions.target === 99 && !useDefineForClassFields)) { + var lexicalClass_1 = ts.getContainingClass(lexicallyScopedSymbol.valueDeclaration); + var parentStaticFieldInitializer = ts.findAncestor(node, function (n) { + if (n === lexicalClass_1) + return "quit"; + if (ts.isPropertyDeclaration(n.parent) && ts.hasStaticModifier(n.parent) && n.parent.initializer === n && n.parent.parent === lexicalClass_1) { + return true; + } + return false; + }); + if (parentStaticFieldInitializer) { + var parentStaticFieldInitializerSymbol = getSymbolOfNode(parentStaticFieldInitializer.parent); + ts.Debug.assert(parentStaticFieldInitializerSymbol, "Initializer without declaration symbol"); + var diagnostic = error(node, ts.Diagnostics.Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false, ts.symbolName(lexicallyScopedSymbol)); + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(parentStaticFieldInitializer.parent, ts.Diagnostics.Initializer_for_property_0, ts.symbolName(parentStaticFieldInitializerSymbol))); + } + } if (isAnyLike) { if (lexicallyScopedSymbol) { return apparentType; @@ -56350,6 +58194,12 @@ var ts; if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) { return errorType; } + else { + var isSetonlyAccessor = prop && prop.flags & 65536 && !(prop.flags & 32768); + if (isSetonlyAccessor && assignmentKind !== 1) { + error(node, ts.Diagnostics.Private_accessor_was_defined_without_a_getter); + } + } } else { if (isAnyLike) { @@ -56360,7 +58210,7 @@ var ts; } prop = getPropertyOfType(apparentType, right.escapedText); } - if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + if (ts.isIdentifier(left) && parentSymbol && (compilerOptions.isolatedModules || !(prop && isConstEnumOrConstEnumOnlyModule(prop)) || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) { markAliasReferenced(parentSymbol, node); } var propType; @@ -56393,37 +58243,41 @@ var ts; } } else { - if (getDeclarationNodeFlagsFromSymbol(prop) & 134217728 && isUncalledFunctionReference(node, prop)) { - errorOrSuggestion(false, right, ts.Diagnostics._0_is_deprecated, right.escapedText); + if (prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 && isUncalledFunctionReference(node, prop)) { + addDeprecatedSuggestion(right, prop.declarations, right.escapedText); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node, left.kind === 107); + markPropertyAsReferenced(prop, node, isSelfTypeAccess(left, parentSymbol)); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left.kind === 105, apparentType, prop); + var writing = ts.isWriteAccess(node); + checkPropertyAccessibility(node, left.kind === 105, writing, apparentType, prop); if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) { error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } - propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : getConstraintForLocation(getTypeOfSymbol(prop), node); + propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : writing ? getSetAccessorTypeOfSymbol(prop) : getTypeOfSymbol(prop); } - return getFlowTypeOfAccessExpression(node, prop, propType, right); + return getFlowTypeOfAccessExpression(node, prop, propType, right, checkMode); } - function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { + function getFlowTypeOfAccessExpression(node, prop, propType, errorNode, checkMode) { var assignmentKind = ts.getAssignmentTargetKind(node); - if (!ts.isAccessExpression(node) || - assignmentKind === 1 || - prop && !(prop.flags & (3 | 4 | 98304)) && !(prop.flags & 8192 && propType.flags & 1048576)) { + if (assignmentKind === 1 || + prop && + !(prop.flags & (3 | 4 | 98304)) + && !(prop.flags & 8192 && propType.flags & 1048576) + && !isDuplicatedCommonJSExport(prop.declarations)) { return propType; } if (propType === autoType) { return getFlowTypeOfProperty(node, prop); } + propType = getNarrowableTypeForReference(propType, node, checkMode); var assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 107) { + if (strictNullChecks && strictPropertyInitialization && ts.isAccessExpression(node) && node.expression.kind === 107) { var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); - if (flowContainer.kind === 166 && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608)) { + if (flowContainer.kind === 167 && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608)) { assumeUninitialized = true; } } @@ -56449,13 +58303,14 @@ var ts; var diagnosticMessage; var declarationName = ts.idText(right); if (isInPropertyInitializer(node) + && !isOptionalPropertyDeclaration(valueDeclaration) && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) - && !isPropertyDeclaredInAncestorClass(prop)) { + && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } - else if (valueDeclaration.kind === 252 && - node.parent.kind !== 173 && + else if (valueDeclaration.kind === 253 && + node.parent.kind !== 174 && !(valueDeclaration.flags & 8388608) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); @@ -56467,22 +58322,22 @@ var ts; function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 163: + case 164: return true; - case 288: - case 165: - case 167: + case 289: + case 166: case 168: - case 290: - case 158: - case 228: - case 283: - case 280: + case 169: + case 291: + case 159: + case 229: + case 284: case 281: case 282: - case 275: - case 223: - case 286: + case 283: + case 276: + case 224: + case 287: return false; default: return ts.isExpressionNode(node) ? false : "quit"; @@ -56550,7 +58405,10 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, missingProperty, container); + var diagnostic = containerSeemsToBeEmptyDomElement(containingType) + ? ts.Diagnostics.Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom + : ts.Diagnostics.Property_0_does_not_exist_on_type_1; + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), diagnostic, missingProperty, container); } } } @@ -56561,9 +58419,14 @@ var ts; } diagnostics.add(resultDiagnostic); } + function containerSeemsToBeEmptyDomElement(containingType) { + return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && + everyContainedType(containingType, function (type) { return type.symbol && /^(EventTarget|Node|((HTML[a-zA-Z]*)?Element))$/.test(ts.unescapeLeadingUnderscores(type.symbol.escapedName)); }) && + isEmptyObjectType(containingType); + } function typeHasStaticProperty(propName, containingType) { var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); - return prop !== undefined && prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32); + return prop !== undefined && !!prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32); } function getSuggestedLibForNonExistentName(name) { var missingName = diagnosticName(name); @@ -56594,7 +58457,15 @@ var ts; } } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 111551); + var props = getPropertiesOfType(containingType); + if (typeof name !== "string") { + var parent_2 = name.parent; + if (ts.isPropertyAccessExpression(parent_2)) { + props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_2, containingType, prop); }); + } + name = ts.idText(name); + } + return getSpellingSuggestionForName(name, props, 111551); } function getSuggestedSymbolForNonexistentJSXAttribute(name, containingType) { var strName = ts.isString(name) ? name : ts.idText(name); @@ -56670,20 +58541,20 @@ var ts; return undefined; } } - function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isSelfTypeAccess) { var valueDeclaration = prop && (prop.flags & 106500) && prop.valueDeclaration; if (!valueDeclaration) { return; } var hasPrivateModifier = ts.hasEffectiveModifier(valueDeclaration, 8); - var hasPrivateIdentifier = ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name); + var hasPrivateIdentifier = prop.valueDeclaration && ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name); if (!hasPrivateModifier && !hasPrivateIdentifier) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536)) { return; } - if (isThisAccess) { + if (isSelfTypeAccess) { var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); if (containingMethod && containingMethod.symbol === prop) { return; @@ -56691,18 +58562,22 @@ var ts; } (ts.getCheckFlags(prop) & 1 ? getSymbolLinks(prop).target : prop).isReferenced = 67108863; } + function isSelfTypeAccess(name, parent) { + return name.kind === 107 + || !!parent && ts.isEntityNameExpression(name) && parent === getResolvedSymbol(ts.getFirstIdentifier(name)); + } function isValidPropertyAccess(node, propertyName) { switch (node.kind) { - case 201: + case 202: return isValidPropertyAccessWithType(node, node.expression.kind === 105, propertyName, getWidenedType(checkExpression(node.expression))); - case 157: + case 158: return isValidPropertyAccessWithType(node, false, propertyName, getWidenedType(checkExpression(node.left))); - case 195: + case 196: return isValidPropertyAccessWithType(node, false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind === 201 && node.expression.kind === 105, property.escapedName, type); + return isValidPropertyAccessWithType(node, node.kind === 202 && node.expression.kind === 105, property.escapedName, type); } function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { if (type === errorType || isTypeAny(type)) { @@ -56710,17 +58585,17 @@ var ts; } var prop = getPropertyOfType(type, propertyName); if (prop) { - if (ts.isPropertyAccessExpression(node) && prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)) { + if (prop.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration)) { var declClass_1 = ts.getContainingClass(prop.valueDeclaration); return !ts.isOptionalChain(node) && !!ts.findAncestor(node, function (parent) { return parent === declClass_1; }); } - return checkPropertyAccessibility(node, isSuper, type, prop); + return checkPropertyAccessibility(node, isSuper, false, type, prop, false); } return ts.isInJSFile(node) && (type.flags & 1048576) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 250) { + if (initializer.kind === 251) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); @@ -56742,7 +58617,7 @@ var ts; var child = expr; var node = expr.parent; while (node) { - if (node.kind === 238 && + if (node.kind === 239 && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -56755,16 +58630,16 @@ var ts; } return false; } - function checkIndexedAccess(node) { - return node.flags & 32 ? checkElementAccessChain(node) : - checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + function checkIndexedAccess(node, checkMode) { + return node.flags & 32 ? checkElementAccessChain(node, checkMode) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression), checkMode); } - function checkElementAccessChain(node) { + function checkElementAccessChain(node, checkMode) { var exprType = checkExpression(node.expression); var nonOptionalType = getOptionalExpressionType(exprType, node.expression); - return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression), checkMode), node, nonOptionalType !== exprType); } - function checkElementAccessExpression(node, exprType) { + function checkElementAccessExpression(node, exprType, checkMode) { var objectType = ts.getAssignmentTargetKind(node) !== 0 || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; var indexExpression = node.argumentExpression; var indexType = checkExpression(indexExpression); @@ -56780,37 +58655,7 @@ var ts; 2 | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 : 0) : 0; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, undefined, node, accessFlags | 16) || errorType; - return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); - } - function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { - if (expressionType === errorType) { - return false; - } - if (!ts.isWellKnownSymbolSyntactically(expression)) { - return false; - } - if ((expressionType.flags & 12288) === 0) { - if (reportError) { - error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); - } - return false; - } - var leftHandSide = expression.expression; - var leftHandSideSymbol = getResolvedSymbol(leftHandSide); - if (!leftHandSideSymbol) { - return false; - } - var globalESSymbol = getGlobalESSymbolConstructorSymbol(true); - if (!globalESSymbol) { - return false; - } - if (leftHandSideSymbol !== globalESSymbol) { - if (reportError) { - error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); - } - return false; - } - return true; + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, getNodeLinks(node).resolvedSymbol, indexedAccessType, indexExpression, checkMode), node); } function callLikeExpressionMayHaveTypeArguments(node) { return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node); @@ -56819,13 +58664,13 @@ var ts; if (callLikeExpressionMayHaveTypeArguments(node)) { ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 205) { + if (node.kind === 206) { checkExpression(node.template); } else if (ts.isJsxOpeningLikeElement(node)) { checkExpression(node.attributes); } - else if (node.kind !== 161) { + else if (node.kind !== 162) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -56874,7 +58719,7 @@ var ts; } } function isSpreadArgument(arg) { - return !!arg && (arg.kind === 220 || arg.kind === 227 && arg.isSpread); + return !!arg && (arg.kind === 221 || arg.kind === 228 && arg.isSpread); } function getSpreadArgumentIndex(args) { return ts.findIndex(args, isSpreadArgument); @@ -56891,9 +58736,9 @@ var ts; var callIsIncomplete = false; var effectiveParameterCount = getParameterCount(signature); var effectiveMinimumArguments = getMinArgumentCount(signature); - if (node.kind === 205) { + if (node.kind === 206) { argCount = args.length; - if (node.template.kind === 218) { + if (node.template.kind === 219) { var lastSpan = ts.last(node.template.templateSpans); callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; } @@ -56903,7 +58748,7 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 161) { + else if (node.kind === 162) { argCount = getDecoratorArgumentCount(node, signature); } else if (ts.isJsxOpeningLikeElement(node)) { @@ -56916,7 +58761,7 @@ var ts; effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); } else if (!node.arguments) { - ts.Debug.assert(node.kind === 204); + ts.Debug.assert(node.kind === 205); return getMinArgumentCount(signature) === 0; } else { @@ -56978,7 +58823,7 @@ var ts; }); if (!inferenceContext) { applyToReturnTypes(contextualSignature, signature, function (source, target) { - inferTypes(context.inferences, source, target, 64); + inferTypes(context.inferences, source, target, 128); }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); @@ -56989,11 +58834,20 @@ var ts; inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } + function getThisArgumentType(thisArgumentNode) { + if (!thisArgumentNode) { + return voidType; + } + var thisArgumentType = checkExpression(thisArgumentNode); + return ts.isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) : + ts.isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) : + thisArgumentType; + } function inferTypeArguments(node, signature, args, checkMode, context) { if (ts.isJsxOpeningLikeElement(node)) { return inferJsxTypeArguments(node, signature, checkMode, context); } - if (node.kind !== 161) { + if (node.kind !== 162) { var contextualType = getContextualType(node, ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }) ? 8 : 0); if (contextualType) { var outerContext = getInferenceContext(node); @@ -57004,7 +58858,7 @@ var ts; getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 64); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128); var returnContext = createInferenceContext(signature.typeParameters, signature, context.flags); var returnSourceType = instantiateType(contextualType, outerContext && outerContext.returnMapper); inferTypes(returnContext.inferences, returnSourceType, inferenceTargetType); @@ -57022,12 +58876,11 @@ var ts; var thisType = getThisTypeOfSignature(signature); if (thisType) { var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context.inferences, thisArgumentType, thisType); + inferTypes(context.inferences, getThisArgumentType(thisArgumentNode), thisType); } for (var i = 0; i < argCount; i++) { var arg = args[i]; - if (arg.kind !== 222) { + if (arg.kind !== 223) { var paramType = getTypeAtPosition(signature, i); var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode); inferTypes(context.inferences, argType, paramType); @@ -57049,7 +58902,7 @@ var ts; if (index >= argCount - 1) { var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { - return getMutableArrayOrTupleType(arg.kind === 227 ? arg.type : + return getMutableArrayOrTupleType(arg.kind === 228 ? arg.type : checkExpressionWithContextualType(arg.expression, restType, context, checkMode)); } } @@ -57059,13 +58912,13 @@ var ts; for (var i = index; i < argCount; i++) { var arg = args[i]; if (isSpreadArgument(arg)) { - var spreadType = arg.kind === 227 ? arg.type : checkExpression(arg.expression); + var spreadType = arg.kind === 228 ? arg.type : checkExpression(arg.expression); if (isArrayLikeType(spreadType)) { types.push(spreadType); flags.push(8); } else { - types.push(checkIteratedTypeOrElementType(33, spreadType, undefinedType, arg.kind === 220 ? arg.expression : arg)); + types.push(checkIteratedTypeOrElementType(33, spreadType, undefinedType, arg.kind === 221 ? arg.expression : arg)); flags.push(4); } } @@ -57076,7 +58929,7 @@ var ts; types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); flags.push(1); } - if (arg.kind === 227 && arg.tupleNameSource) { + if (arg.kind === 228 && arg.tupleNameSource) { names.push(arg.tupleNameSource); } } @@ -57207,21 +59060,9 @@ var ts; return undefined; } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 204) { + if (thisType && thisType !== voidType && node.kind !== 205) { var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = void 0; - if (thisArgumentNode) { - thisArgumentType = checkExpression(thisArgumentNode); - if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { - thisArgumentType = getNonNullableType(thisArgumentType); - } - else if (ts.isOptionalChain(thisArgumentNode.parent)) { - thisArgumentType = removeOptionalTypeMarker(thisArgumentType); - } - } - else { - thisArgumentType = voidType; - } + var thisArgumentType = getThisArgumentType(thisArgumentNode); var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -57234,7 +59075,7 @@ var ts; var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { var arg = args[i]; - if (arg.kind !== 222) { + if (arg.kind !== 223) { var paramType = getTypeAtPosition(signature, i); var argType = checkExpressionWithContextualType(arg, paramType, undefined, checkMode); var checkArgType = checkMode & 4 ? getRegularTypeOfObjectLiteral(argType) : argType; @@ -57272,7 +59113,7 @@ var ts; } } function getThisArgumentOfCall(node) { - if (node.kind === 203) { + if (node.kind === 204) { var callee = ts.skipOuterExpressions(node.expression); if (ts.isAccessExpression(callee)) { return callee.expression; @@ -57286,17 +59127,17 @@ var ts; return result; } function getEffectiveCallArguments(node) { - if (node.kind === 205) { + if (node.kind === 206) { var template = node.template; var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; - if (template.kind === 218) { + if (template.kind === 219) { ts.forEach(template.templateSpans, function (span) { args_3.push(span.expression); }); } return args_3; } - if (node.kind === 161) { + if (node.kind === 162) { return getEffectiveDecoratorArguments(node); } if (ts.isJsxOpeningLikeElement(node)) { @@ -57306,9 +59147,9 @@ var ts; var spreadIndex = getSpreadArgumentIndex(args); if (spreadIndex >= 0) { var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_20 = function (i) { + var _loop_21 = function (i) { var arg = args[i]; - var spreadType = arg.kind === 220 && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); + var spreadType = arg.kind === 221 && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); if (spreadType && isTupleType(spreadType)) { ts.forEach(getTypeArguments(spreadType), function (t, i) { var _a; @@ -57322,7 +59163,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_20(i); + _loop_21(i); } return effectiveArgs_1; } @@ -57332,23 +59173,23 @@ var ts; var parent = node.parent; var expr = node.expression; switch (parent.kind) { - case 252: - case 221: + case 253: + case 222: return [ createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) ]; - case 160: + case 161: var func = parent.parent; return [ - createSyntheticExpression(expr, parent.parent.kind === 166 ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, parent.parent.kind === 167 ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), createSyntheticExpression(expr, anyType), createSyntheticExpression(expr, numberType) ]; - case 163: - case 165: - case 167: + case 164: + case 166: case 168: - var hasPropDesc = parent.kind !== 163 && languageVersion !== 0; + case 169: + var hasPropDesc = parent.kind !== 164 && languageVersion !== 0; return [ createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), @@ -57359,16 +59200,16 @@ var ts; } function getDecoratorArgumentCount(node, signature) { switch (node.parent.kind) { - case 252: - case 221: + case 253: + case 222: return 1; - case 163: + case 164: return 2; - case 165: - case 167: + case 166: case 168: + case 169: return languageVersion === 0 || signature.parameters.length <= 2 ? 2 : 3; - case 160: + case 161: return 3; default: return ts.Debug.fail(); @@ -57414,77 +59255,61 @@ var ts; return constructorSymbol === globalPromiseSymbol; } function getArgumentArityError(node, signatures, args) { + var _a; + var spreadIndex = getSpreadArgumentIndex(args); + if (spreadIndex > -1) { + return ts.createDiagnosticForNode(args[spreadIndex], ts.Diagnostics.A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter); + } var min = Number.POSITIVE_INFINITY; var max = Number.NEGATIVE_INFINITY; - var belowArgCount = Number.NEGATIVE_INFINITY; - var aboveArgCount = Number.POSITIVE_INFINITY; - var argCount = args.length; + var maxBelow = Number.NEGATIVE_INFINITY; + var minAbove = Number.POSITIVE_INFINITY; var closestSignature; for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { var sig = signatures_8[_i]; - var minCount = getMinArgumentCount(sig); - var maxCount = getParameterCount(sig); - if (minCount < argCount && minCount > belowArgCount) - belowArgCount = minCount; - if (argCount < maxCount && maxCount < aboveArgCount) - aboveArgCount = maxCount; - if (minCount < min) { - min = minCount; + var minParameter = getMinArgumentCount(sig); + var maxParameter = getParameterCount(sig); + if (minParameter < min) { + min = minParameter; closestSignature = sig; } - max = Math.max(max, maxCount); + max = Math.max(max, maxParameter); + if (minParameter < args.length && minParameter > maxBelow) + maxBelow = minParameter; + if (args.length < maxParameter && maxParameter < minAbove) + minAbove = maxParameter; } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); - var paramRange = hasRestParameter ? min : - min < max ? min + "-" + max : - min; - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var spanArray; - var related; - var error = hasRestParameter || hasSpreadArgument ? - hasRestParameter && hasSpreadArgument ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - paramRange === 1 && argCount === 0 && isPromiseResolveArityError(node) ? - ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : - ts.Diagnostics.Expected_0_arguments_but_got_1; - if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { - var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; - if (paramDecl) { - related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : - ts.isRestParameter(paramDecl) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined); - } - } - if (min < argCount && argCount < max) { - return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); - } - if (!hasSpreadArgument && argCount < min) { - var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1; - } - if (hasRestParameter || hasSpreadArgument) { - spanArray = ts.factory.createNodeArray(args); - if (hasSpreadArgument && argCount) { - var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined; - spanArray = ts.factory.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1))); + var parameterRange = hasRestParameter ? min + : min < max ? min + "-" + max + : min; + var error = hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 + : parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node) ? ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise + : ts.Diagnostics.Expected_0_arguments_but_got_1; + if (min < args.length && args.length < max) { + return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove); + } + else if (args.length < min) { + var diagnostic = getDiagnosticForCallNode(node, error, parameterRange, args.length); + var parameter = (_a = closestSignature === null || closestSignature === void 0 ? void 0 : closestSignature.declaration) === null || _a === void 0 ? void 0 : _a.parameters[closestSignature.thisParameter ? args.length + 1 : args.length]; + if (parameter) { + var parameterError = ts.createDiagnosticForNode(parameter, ts.isBindingPattern(parameter.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided + : ts.isRestParameter(parameter) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided + : ts.Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : !ts.isBindingPattern(parameter.name) ? ts.idText(ts.getFirstIdentifier(parameter.name)) : undefined); + return ts.addRelatedInfo(diagnostic, parameterError); } + return diagnostic; } else { - spanArray = ts.factory.createNodeArray(args.slice(max)); - } - var pos = ts.first(spanArray).pos; - var end = ts.last(spanArray).end; - if (end === pos) { - end++; + var errorSpan = ts.factory.createNodeArray(args.slice(max)); + var pos = ts.first(errorSpan).pos; + var end = ts.last(errorSpan).end; + if (end === pos) { + end++; + } + ts.setTextRangePosEnd(errorSpan, pos, end); + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), errorSpan, error, parameterRange, args.length); } - ts.setTextRangePosEnd(spanArray, pos, end); - var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var argCount = typeArguments.length; @@ -57513,8 +59338,8 @@ var ts; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) { - var isTaggedTemplate = node.kind === 205; - var isDecorator = node.kind === 161; + var isTaggedTemplate = node.kind === 206; + var isDecorator = node.kind === 162; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var reportErrors = !candidatesOutArray && produceDiagnostics; var typeArguments; @@ -57539,7 +59364,7 @@ var ts; var candidateForArgumentArityError; var candidateForTypeArgumentError; var result; - var signatureHelpTrailingComma = !!(checkMode & 16) && node.kind === 203 && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = !!(checkMode & 16) && node.kind === 204 && node.arguments.hasTrailingComma; if (candidates.length > 1) { result = chooseOverload(candidates, subtypeRelation, isSingleNonGenericCandidate, signatureHelpTrailingComma); } @@ -57579,7 +59404,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_21 = function (c) { + var _loop_22 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0, true, chain_2); if (diags_2) { @@ -57597,7 +59422,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_21(c); + _loop_22(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); @@ -57740,7 +59565,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_22 = function (i) { + var _loop_23 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -57748,7 +59573,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_22(i); + _loop_23(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0; @@ -57895,7 +59720,7 @@ var ts; } function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144) || - !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 | 131072)) && isTypeAssignableTo(funcType, globalFunctionType); + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & 1048576) && !(getReducedType(apparentFuncType).flags & 131072) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray, checkMode) { if (node.arguments && languageVersion < 1) { @@ -57987,7 +59812,7 @@ var ts; } var declaration = signature.declaration; var modifiers = ts.getSelectedEffectiveModifierFlags(declaration, 24); - if (!modifiers || declaration.kind !== 166) { + if (!modifiers || declaration.kind !== 167) { return true; } var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol); @@ -58119,16 +59944,16 @@ var ts; } function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 252: - case 221: + case 253: + case 222: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 160: + case 161: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 163: + case 164: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 165: - case 167: + case 166: case 168: + case 169: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; default: return ts.Debug.fail(); @@ -58209,16 +60034,16 @@ var ts; } function resolveSignature(node, candidatesOutArray, checkMode) { switch (node.kind) { - case 203: - return resolveCallExpression(node, candidatesOutArray, checkMode); case 204: - return resolveNewExpression(node, candidatesOutArray, checkMode); + return resolveCallExpression(node, candidatesOutArray, checkMode); case 205: + return resolveNewExpression(node, candidatesOutArray, checkMode); + case 206: return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode); - case 161: + case 162: return resolveDecorator(node, candidatesOutArray, checkMode); + case 276: case 275: - case 274: return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode); } throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); @@ -58328,7 +60153,7 @@ var ts; return false; } var parent = node.parent; - while (parent && parent.kind === 201) { + while (parent && parent.kind === 202) { parent = parent.parent; } if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 62) { @@ -58348,12 +60173,12 @@ var ts; if (node.expression.kind === 105) { return voidType; } - if (node.kind === 204) { + if (node.kind === 205) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 166 && - declaration.kind !== 170 && - declaration.kind !== 175 && + declaration.kind !== 167 && + declaration.kind !== 171 && + declaration.kind !== 176 && !ts.isJSDocConstructSignature(declaration) && !isJSConstructor(declaration)) { if (noImplicitAny) { @@ -58369,7 +60194,7 @@ var ts; if (returnType.flags & 12288 && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } - if (node.kind === 203 && node.parent.kind === 233 && + if (node.kind === 204 && !node.questionDotToken && node.parent.kind === 234 && returnType.flags & 16384 && getTypePredicateOfSignature(signature)) { if (!ts.isDottedName(node.expression)) { error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name); @@ -58383,7 +60208,7 @@ var ts; var jsSymbol = getSymbolOfExpando(node, false); if ((_a = jsSymbol === null || jsSymbol === void 0 ? void 0 : jsSymbol.exports) === null || _a === void 0 ? void 0 : _a.size) { var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - jsAssignmentType.objectFlags |= 16384; + jsAssignmentType.objectFlags |= 8192; return getIntersectionType([returnType, jsAssignmentType]); } } @@ -58392,26 +60217,27 @@ var ts; function checkDeprecatedSignature(signature, node) { if (signature.declaration && signature.declaration.flags & 134217728) { var suggestionNode = getDeprecatedSuggestionNode(node); - errorOrSuggestion(false, suggestionNode, ts.Diagnostics._0_is_deprecated, signatureToString(signature)); + var name = ts.tryGetPropertyAccessOrIdentifierToString(ts.getInvokedExpression(node)); + addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature)); } } function getDeprecatedSuggestionNode(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 203: - case 161: case 204: - return getDeprecatedSuggestionNode(node.expression); + case 162: case 205: + return getDeprecatedSuggestionNode(node.expression); + case 206: return getDeprecatedSuggestionNode(node.tag); + case 276: case 275: - case 274: return getDeprecatedSuggestionNode(node.tagName); - case 202: + case 203: return node.argumentExpression; - case 201: + case 202: return node.name; - case 173: + case 174: var typeReference = node; return ts.isQualifiedName(typeReference.typeName) ? typeReference.typeName.right : typeReference; default: @@ -58458,10 +60284,11 @@ var ts; return createPromiseReturnType(node, anyType); } function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { + var _a; if (allowSyntheticDefaultImports && type && type !== errorType) { var synthType = type; if (!synthType.syntheticType) { - var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var file = (_a = originalSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, false); if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); @@ -58497,9 +60324,9 @@ var ts; return false; } var targetDeclarationKind = resolvedRequire.flags & 16 - ? 251 + ? 252 : resolvedRequire.flags & 3 - ? 249 + ? 250 : 0; if (targetDeclarationKind !== 0) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); @@ -58528,19 +60355,19 @@ var ts; case 9: case 109: case 94: - case 199: case 200: - case 218: + case 201: + case 219: return true; - case 207: + case 208: return isValidConstAssertionArgument(node.expression); - case 214: + case 215: var op = node.operator; var arg = node.operand; return op === 40 && (arg.kind === 8 || arg.kind === 9) || op === 39 && arg.kind === 8; - case 201: case 202: + case 203: var expr = node.expression; if (ts.isIdentifier(expr)) { var symbol = getSymbolAtLocation(expr); @@ -58596,7 +60423,7 @@ var ts; error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return errorType; } - else if (container.kind === 166) { + else if (container.kind === 167) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -58643,7 +60470,7 @@ var ts; return restParameter.escapedName; } function isValidDeclarationForTupleLabel(d) { - return d.kind === 192 || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name)); + return d.kind === 193 || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name)); } function getNameableDeclarationAtPosition(signature, pos) { var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); @@ -58797,7 +60624,14 @@ var ts; } } function assignContextualParameterTypes(signature, context) { - signature.typeParameters = context.typeParameters; + if (context.typeParameters) { + if (!signature.typeParameters) { + signature.typeParameters = context.typeParameters; + } + else { + return; + } + } if (context.thisParameter) { var parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { @@ -58900,7 +60734,7 @@ var ts; var yieldType; var nextType; var fallbackReturnType = voidType; - if (func.body.kind !== 230) { + if (func.body.kind !== 231) { returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8); if (isAsync) { returnType = checkAwaitedType(returnType, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -59050,7 +60884,7 @@ var ts; return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node)); } function computeExhaustiveSwitchStatement(node) { - if (node.expression.kind === 211) { + if (node.expression.kind === 212) { var operandType = getTypeOfExpression(node.expression.expression); var witnesses = getSwitchClauseTypeOfWitnesses(node, false); var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, true); @@ -59105,11 +60939,11 @@ var ts; } function mayReturnNever(func) { switch (func.kind) { - case 208: case 209: + case 210: return true; - case 165: - return func.parent.kind === 200; + case 166: + return func.parent.kind === 201; default: return false; } @@ -59123,18 +60957,19 @@ var ts; if (type && maybeTypeOfKind(type, 1 | 16384)) { return; } - if (func.kind === 164 || ts.nodeIsMissing(func.body) || func.body.kind !== 230 || !functionHasImplicitReturn(func)) { + if (func.kind === 165 || ts.nodeIsMissing(func.body) || func.body.kind !== 231 || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 512; + var errorNode = ts.getEffectiveReturnTypeNode(func) || func; if (type && type.flags & 131072) { - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + error(errorNode, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (type && !hasExplicitReturn) { - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + error(errorNode, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) { - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + error(errorNode, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); } else if (compilerOptions.noImplicitReturns) { if (!type) { @@ -59146,11 +60981,11 @@ var ts; return; } } - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + error(errorNode, ts.Diagnostics.Not_all_code_paths_return_a_value); } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 165 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 || ts.isObjectLiteralMethod(node)); checkNodeDeferred(node); if (checkMode && checkMode & 4 && isContextSensitive(node)) { if (!ts.getEffectiveReturnTypeNode(node) && !hasContextSensitiveParameters(node)) { @@ -59163,14 +60998,14 @@ var ts; var returnType = getReturnTypeFromBody(node, checkMode); var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, undefined, 0, 0); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); - returnOnlyType.objectFlags |= 2097152; + returnOnlyType.objectFlags |= 524288; return links.contextFreeType = returnOnlyType; } } return anyFunctionType; } var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 208) { + if (!hasGrammarError && node.kind === 209) { checkGrammarForGenerator(node); } contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -59211,7 +61046,7 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 165 || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnType = getReturnTypeFromAnnotation(node); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); @@ -59219,7 +61054,7 @@ var ts; if (!ts.getEffectiveReturnTypeNode(node)) { getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 230) { + if (node.body.kind === 231) { checkSourceElement(node.body); } else { @@ -59291,7 +61126,7 @@ var ts; ts.isAccessExpression(expr) && expr.expression.kind === 107) { var ctor = ts.getContainingFunction(expr); - if (!(ctor && (ctor.kind === 166 || isJSConstructor(ctor)))) { + if (!(ctor && (ctor.kind === 167 || isJSConstructor(ctor)))) { return true; } if (symbol.valueDeclaration) { @@ -59315,7 +61150,7 @@ var ts; var symbol_2 = getNodeLinks(node).resolvedSymbol; if (symbol_2.flags & 2097152) { var declaration = getDeclarationOfAliasSymbol(symbol_2); - return !!declaration && declaration.kind === 263; + return !!declaration && declaration.kind === 264; } } } @@ -59393,7 +61228,7 @@ var ts; var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); var func = ts.getContainingFunction(node); - if (func && func.kind !== 166 && (ts.getFunctionFlags(func) & 2) === 0) { + if (func && func.kind !== 167 && (ts.getFunctionFlags(func) & 2) === 0) { var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); ts.addRelatedInfo(diagnostic, relatedInfo); } @@ -59551,8 +61386,11 @@ var ts; isTypeAssignableToKind(leftType, 4194304 | 134217728 | 268435456 | 262144))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!allTypesAssignableToKind(rightType, 67108864 | 58982400)) { - error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + var rightTypeConstraint = getConstraintOfType(rightType); + if (!allTypesAssignableToKind(rightType, 67108864 | 58982400) || + rightTypeConstraint && (isTypeAssignableToKind(rightType, 3145728) && !allTypesAssignableToKind(rightTypeConstraint, 67108864 | 58982400) || + !maybeTypeOfKind(rightTypeConstraint, 67108864 | 58982400 | 524288))) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_not_be_a_primitive); } return booleanType; } @@ -59570,7 +61408,7 @@ var ts; if (rightIsThis === void 0) { rightIsThis = false; } var properties = node.properties; var property = properties[propertyIndex]; - if (property.kind === 288 || property.kind === 289) { + if (property.kind === 289 || property.kind === 290) { var name = property.name; var exprType = getLiteralTypeFromPropertyName(name); if (isTypeUsableAsPropertyName(exprType)) { @@ -59578,14 +61416,14 @@ var ts; var prop = getPropertyOfType(objectLiteralType, text); if (prop) { markPropertyAsReferenced(prop, property, rightIsThis); - checkPropertyAccessibility(property, false, objectLiteralType, prop); + checkPropertyAccessibility(property, false, true, objectLiteralType, prop); } } var elementType = getIndexedAccessType(objectLiteralType, exprType, undefined, name, undefined, undefined, 16); var type = getFlowTypeOfDestructuring(property, elementType); - return checkDestructuringAssignment(property.kind === 289 ? property : property.initializer, type); + return checkDestructuringAssignment(property.kind === 290 ? property : property.initializer, type); } - else if (property.kind === 290) { + else if (property.kind === 291) { if (propertyIndex < properties.length - 1) { error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } @@ -59620,7 +61458,7 @@ var ts; var inBoundsType = compilerOptions.noUncheckedIndexedAccess ? undefined : possiblyOutOfBoundsType; for (var i = 0; i < elements.length; i++) { var type = possiblyOutOfBoundsType; - if (node.elements[i].kind === 220) { + if (node.elements[i].kind === 221) { type = inBoundsType = inBoundsType !== null && inBoundsType !== void 0 ? inBoundsType : (checkIteratedTypeOrElementType(65, sourceType, undefinedType, node) || errorType); } checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, type, checkMode); @@ -59630,8 +61468,8 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 222) { - if (element.kind !== 220) { + if (element.kind !== 223) { + if (element.kind !== 221) { var indexType = getLiteralType(elementIndex); if (isArrayLikeType(sourceType)) { var accessFlags = 16 | (hasDefaultValue(element) ? 8 : 0); @@ -59647,7 +61485,7 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 216 && restExpression.operatorToken.kind === 62) { + if (restExpression.kind === 217 && restExpression.operatorToken.kind === 62) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -59663,7 +61501,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; - if (exprOrAssignment.kind === 289) { + if (exprOrAssignment.kind === 290) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { if (strictNullChecks && @@ -59677,24 +61515,24 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 216 && target.operatorToken.kind === 62) { + if (target.kind === 217 && target.operatorToken.kind === 62) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 200) { + if (target.kind === 201) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } - if (target.kind === 199) { + if (target.kind === 200) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 290 ? + var error = target.parent.kind === 291 ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; - var optionalError = target.parent.kind === 290 ? + var optionalError = target.parent.kind === 291 ? ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access; if (checkReferenceExpression(target, error, optionalError)) { @@ -59711,8 +61549,8 @@ var ts; case 78: case 10: case 13: - case 205: - case 218: + case 206: + case 219: case 14: case 8: case 9: @@ -59720,27 +61558,27 @@ var ts; case 94: case 103: case 150: - case 208: - case 221: case 209: - case 199: + case 222: + case 210: case 200: - case 211: - case 225: + case 201: + case 212: + case 226: + case 275: case 274: - case 273: return true; - case 217: + case 218: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 216: + case 217: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 214: case 215: + case 216: switch (node.operator) { case 53: case 39: @@ -59749,9 +61587,9 @@ var ts; return true; } return false; - case 212: - case 206: - case 224: + case 213: + case 207: + case 225: default: return false; } @@ -59759,74 +61597,107 @@ var ts; function isTypeEqualityComparableTo(source, target) { return (target.flags & 98304) !== 0 || isTypeComparableTo(source, target); } - function checkBinaryExpression(node, checkMode) { - var workStacks = { - expr: [node], - state: [0], - leftType: [undefined] + function createCheckBinaryExpression() { + var trampoline = ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState); + return function (node, checkMode) { + var result = trampoline(node, checkMode); + ts.Debug.assertIsDefined(result); + return result; }; - var stackIndex = 0; - var lastResult; - while (stackIndex >= 0) { - node = workStacks.expr[stackIndex]; - switch (workStacks.state[stackIndex]) { - case 0: { - if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { - finishInvocation(checkExpression(node.right, checkMode)); - break; - } - checkGrammarNullishCoalesceWithLogicalExpression(node); - var operator = node.operatorToken.kind; - if (operator === 62 && (node.left.kind === 200 || node.left.kind === 199)) { - finishInvocation(checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 107)); - break; - } - advanceState(1); - maybeCheckExpression(node.left); - break; - } - case 1: { - var leftType = lastResult; - workStacks.leftType[stackIndex] = leftType; - var operator = node.operatorToken.kind; - if (operator === 55 || operator === 56 || operator === 60) { - if (operator === 55) { - var parent = ts.walkUpParenthesizedExpressions(node.parent); - checkTestingKnownTruthyCallableType(node.left, leftType, ts.isIfStatement(parent) ? parent.thenStatement : undefined); - } - checkTruthinessOfType(leftType, node.left); + function onEnter(node, state, checkMode) { + if (state) { + state.stackIndex++; + state.skip = false; + setLeftType(state, undefined); + setLastResult(state, undefined); + } + else { + state = { + checkMode: checkMode, + skip: false, + stackIndex: 0, + typeStack: [undefined, undefined], + }; + } + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { + state.skip = true; + setLastResult(state, checkExpression(node.right, checkMode)); + return state; + } + checkGrammarNullishCoalesceWithLogicalExpression(node); + var operator = node.operatorToken.kind; + if (operator === 62 && (node.left.kind === 201 || node.left.kind === 200)) { + state.skip = true; + setLastResult(state, checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 107)); + return state; + } + return state; + } + function onLeft(left, state, _node) { + if (!state.skip) { + return maybeCheckExpression(state, left); + } + } + function onOperator(operatorToken, state, node) { + if (!state.skip) { + var leftType = getLastResult(state); + ts.Debug.assertIsDefined(leftType); + setLeftType(state, leftType); + setLastResult(state, undefined); + var operator = operatorToken.kind; + if (operator === 55 || operator === 56 || operator === 60) { + if (operator === 55) { + var parent = ts.walkUpParenthesizedExpressions(node.parent); + checkTestingKnownTruthyCallableOrAwaitableType(node.left, leftType, ts.isIfStatement(parent) ? parent.thenStatement : undefined); } - advanceState(2); - maybeCheckExpression(node.right); - break; + checkTruthinessOfType(leftType, node.left); } - case 2: { - var leftType = workStacks.leftType[stackIndex]; - var rightType = lastResult; - finishInvocation(checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node)); - break; - } - default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for checkBinaryExpression"); } } - return lastResult; - function finishInvocation(result) { - lastResult = result; - stackIndex--; - } - function advanceState(nextState) { - workStacks.state[stackIndex] = nextState; + function onRight(right, state, _node) { + if (!state.skip) { + return maybeCheckExpression(state, right); + } } - function maybeCheckExpression(node) { - if (ts.isBinaryExpression(node)) { - stackIndex++; - workStacks.expr[stackIndex] = node; - workStacks.state[stackIndex] = 0; - workStacks.leftType[stackIndex] = undefined; + function onExit(node, state) { + var result; + if (state.skip) { + result = getLastResult(state); } else { - lastResult = checkExpression(node, checkMode); + var leftType = getLeftType(state); + ts.Debug.assertIsDefined(leftType); + var rightType = getLastResult(state); + ts.Debug.assertIsDefined(rightType); + result = checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node); + } + state.skip = false; + setLeftType(state, undefined); + setLastResult(state, undefined); + state.stackIndex--; + return result; + } + function foldState(state, result, _side) { + setLastResult(state, result); + return state; + } + function maybeCheckExpression(state, node) { + if (ts.isBinaryExpression(node)) { + return node; } + setLastResult(state, checkExpression(node, state.checkMode)); + } + function getLeftType(state) { + return state.typeStack[state.stackIndex]; + } + function setLeftType(state, type) { + state.typeStack[state.stackIndex] = type; + } + function getLastResult(state) { + return state.typeStack[state.stackIndex + 1]; + } + function setLastResult(state, type) { + state.typeStack[state.stackIndex + 1] = type; } } function checkGrammarNullishCoalesceWithLogicalExpression(node) { @@ -59842,7 +61713,7 @@ var ts; } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 62 && (left.kind === 200 || left.kind === 199)) { + if (operator === 62 && (left.kind === 201 || left.kind === 200)) { return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 107); } var leftType; @@ -60058,7 +61929,7 @@ var ts; if (propType.symbol && propType.symbol.flags & 32) { var name = prop.escapedName; var symbol = resolveName(prop.valueDeclaration, name, 788968, undefined, name, false); - if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { + if ((symbol === null || symbol === void 0 ? void 0 : symbol.declarations) && symbol.declarations.some(ts.isJSDocTypedefTag)) { addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop); addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol); } @@ -60234,7 +62105,7 @@ var ts; } function checkConditionalExpression(node, checkMode) { var type = checkTruthinessExpression(node.condition); - checkTestingKnownTruthyCallableType(node.condition, type, node.whenTrue); + checkTestingKnownTruthyCallableOrAwaitableType(node.condition, type, node.whenTrue); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); return getUnionType([type1, type2], 2); @@ -60251,10 +62122,14 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return getFreshTypeOfLiteralType(getTemplateLiteralType(texts, types)); + return isConstContext(node) || someType(getContextualType(node) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; + } + function isTemplateLiteralContextualType(type) { + return !!(type.flags & (128 | 134217728) || + type.flags & 58982400 && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 402653316)); } function getContextNode(node) { - if (node.kind === 281 && !ts.isJsxSelfClosingElement(node.parent)) { + if (node.kind === 282 && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; } return node; @@ -60267,7 +62142,7 @@ var ts; context.contextualType = contextualType; context.inferenceContext = inferenceContext; var type = checkExpression(node, checkMode | 1 | (inferenceContext ? 2 : 0)); - var result = maybeTypeOfKind(type, 134220672) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -60294,13 +62169,13 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 206 || node.kind === 224; + return node.kind === 207 || node.kind === 225; } function checkDeclarationInitializer(declaration, contextualType) { var initializer = ts.getEffectiveInitializer(declaration); var type = getQuickTypeOfExpression(initializer) || (contextualType ? checkExpressionWithContextualType(initializer, contextualType, undefined, 0) : checkExpressionCached(initializer)); - return ts.isParameter(declaration) && declaration.name.kind === 197 && + return ts.isParameter(declaration) && declaration.name.kind === 198 && isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ? padTupleType(type, declaration.name) : type; } @@ -60310,7 +62185,7 @@ var ts; var elementFlags = type.target.elementFlags.slice(); for (var i = getTypeReferenceArity(type); i < patternElements.length; i++) { var e = patternElements[i]; - if (i < patternElements.length - 1 || !(e.kind === 198 && e.dotDotDotToken)) { + if (i < patternElements.length - 1 || !(e.kind === 199 && e.dotDotDotToken)) { elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, false, false) : anyType); elementFlags.push(2); if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) { @@ -60342,13 +62217,13 @@ var ts; } if (contextualType.flags & 58982400) { var constraint = getBaseConstraintOfType(contextualType) || unknownType; - return maybeTypeOfKind(constraint, 4) && maybeTypeOfKind(candidateType, 134217856) || + return maybeTypeOfKind(constraint, 4) && maybeTypeOfKind(candidateType, 128) || maybeTypeOfKind(constraint, 8) && maybeTypeOfKind(candidateType, 256) || maybeTypeOfKind(constraint, 64) && maybeTypeOfKind(candidateType, 2048) || maybeTypeOfKind(constraint, 4096) && maybeTypeOfKind(candidateType, 8192) || isLiteralOfContextualType(candidateType, constraint); } - return !!(contextualType.flags & (134217856 | 4194304 | 268435456) && maybeTypeOfKind(candidateType, 134217856) || + return !!(contextualType.flags & (128 | 4194304 | 134217728 | 268435456) && maybeTypeOfKind(candidateType, 128) || contextualType.flags & 256 && maybeTypeOfKind(candidateType, 256) || contextualType.flags & 2048 && maybeTypeOfKind(candidateType, 2048) || contextualType.flags & 512 && maybeTypeOfKind(candidateType, 512) || @@ -60369,14 +62244,14 @@ var ts; getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node)); } function checkPropertyAssignment(node, checkMode) { - if (node.name.kind === 158) { + if (node.name.kind === 159) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); } function checkObjectLiteralMethod(node, checkMode) { checkGrammarMethod(node); - if (node.name.kind === 158) { + if (node.name.kind === 159) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -60558,7 +62433,7 @@ var ts; } } function checkExpression(node, checkMode, forceTuple) { - ts.tracing.push("check", "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check", "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -60568,15 +62443,15 @@ var ts; checkConstEnumAccess(node, type); } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return type; } function checkConstEnumAccess(node, type) { - var ok = (node.parent.kind === 201 && node.parent.expression === node) || - (node.parent.kind === 202 && node.parent.expression === node) || - ((node.kind === 78 || node.kind === 157) && isInRightSideOfImportOrExportAssignment(node) || - (node.parent.kind === 176 && node.parent.exprName === node)) || - (node.parent.kind === 270); + var ok = (node.parent.kind === 202 && node.parent.expression === node) || + (node.parent.kind === 203 && node.parent.expression === node) || + ((node.kind === 78 || node.kind === 158) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 177 && node.parent.exprName === node)) || + (node.parent.kind === 271); if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } @@ -60599,15 +62474,15 @@ var ts; var kind = node.kind; if (cancellationToken) { switch (kind) { - case 221: - case 208: + case 222: case 209: + case 210: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { case 78: - return checkIdentifier(node); + return checkIdentifier(node, checkMode); case 107: return checkThisExpression(node); case 105: @@ -60627,77 +62502,77 @@ var ts; return trueType; case 94: return falseType; - case 218: + case 219: return checkTemplateExpression(node); case 13: return globalRegExpType; - case 199: - return checkArrayLiteral(node, checkMode, forceTuple); case 200: - return checkObjectLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 201: - return checkPropertyAccessExpression(node); - case 157: - return checkQualifiedName(node); + return checkObjectLiteral(node, checkMode); case 202: - return checkIndexedAccess(node); + return checkPropertyAccessExpression(node, checkMode); + case 158: + return checkQualifiedName(node, checkMode); case 203: + return checkIndexedAccess(node, checkMode); + case 204: if (node.expression.kind === 99) { return checkImportCallExpression(node); } - case 204: - return checkCallExpression(node, checkMode); case 205: + return checkCallExpression(node, checkMode); + case 206: return checkTaggedTemplateExpression(node); - case 207: + case 208: return checkParenthesizedExpression(node, checkMode); - case 221: + case 222: return checkClassExpression(node); - case 208: case 209: + case 210: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 211: + case 212: return checkTypeOfExpression(node); - case 206: - case 224: - return checkAssertion(node); + case 207: case 225: - return checkNonNullAssertion(node); + return checkAssertion(node); case 226: + return checkNonNullAssertion(node); + case 227: return checkMetaProperty(node); - case 210: + case 211: return checkDeleteExpression(node); - case 212: - return checkVoidExpression(node); case 213: - return checkAwaitExpression(node); + return checkVoidExpression(node); case 214: - return checkPrefixUnaryExpression(node); + return checkAwaitExpression(node); case 215: - return checkPostfixUnaryExpression(node); + return checkPrefixUnaryExpression(node); case 216: - return checkBinaryExpression(node, checkMode); + return checkPostfixUnaryExpression(node); case 217: + return checkBinaryExpression(node, checkMode); + case 218: return checkConditionalExpression(node, checkMode); - case 220: + case 221: return checkSpreadExpression(node, checkMode); - case 222: + case 223: return undefinedWideningType; - case 219: + case 220: return checkYieldExpression(node); - case 227: + case 228: return checkSyntheticExpression(node); - case 283: + case 284: return checkJsxExpression(node, checkMode); - case 273: - return checkJsxElement(node, checkMode); case 274: + return checkJsxElement(node, checkMode); + case 275: return checkJsxSelfClosingElement(node, checkMode); - case 277: + case 278: return checkJsxFragment(node); - case 281: + case 282: return checkJsxAttributes(node, checkMode); - case 275: + case 276: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return errorType; @@ -60726,11 +62601,11 @@ var ts; checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (ts.hasSyntacticModifier(node, 92)) { - if (!(func.kind === 166 && ts.nodeIsPresent(func.body))) { + if (ts.hasSyntacticModifier(node, 16476)) { + if (!(func.kind === 167 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } - if (func.kind === 166 && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") { + if (func.kind === 167 && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") { error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name); } } @@ -60741,13 +62616,13 @@ var ts; if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 166 || func.kind === 170 || func.kind === 175) { + if (func.kind === 167 || func.kind === 171 || func.kind === 176) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } - if (func.kind === 209) { + if (func.kind === 210) { error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); } - if (func.kind === 167 || func.kind === 168) { + if (func.kind === 168 || func.kind === 169) { error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters); } } @@ -60801,13 +62676,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { + case 210: + case 170: + case 252: case 209: - case 169: - case 251: - case 208: - case 174: + case 175: + case 166: case 165: - case 164: var parent = node.parent; if (node === parent.type) { return parent; @@ -60825,7 +62700,7 @@ var ts; error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 197 || name.kind === 196) { + else if (name.kind === 198 || name.kind === 197) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -60833,12 +62708,12 @@ var ts; } } function checkSignatureDeclaration(node) { - if (node.kind === 171) { + if (node.kind === 172) { checkGrammarIndexSignature(node); } - else if (node.kind === 174 || node.kind === 251 || node.kind === 175 || - node.kind === 169 || node.kind === 166 || - node.kind === 170) { + else if (node.kind === 175 || node.kind === 252 || node.kind === 176 || + node.kind === 170 || node.kind === 167 || + node.kind === 171) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); @@ -60863,10 +62738,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 170: + case 171: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 169: + case 170: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -60890,7 +62765,7 @@ var ts; checkAsyncFunctionReturnType(node, returnTypeNode); } } - if (node.kind !== 171 && node.kind !== 308) { + if (node.kind !== 172 && node.kind !== 309) { registerForUnusedIdentifiersCheck(node); } } @@ -60901,7 +62776,7 @@ var ts; var privateIdentifiers = new ts.Map(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 166) { + if (member.kind === 167) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) { @@ -60913,25 +62788,27 @@ var ts; var isStatic = ts.hasSyntacticModifier(member, 32); var name = member.name; if (!name) { - return; + continue; } - var names = ts.isPrivateIdentifier(name) ? privateIdentifiers : + var isPrivate = ts.isPrivateIdentifier(name); + var privateStaticFlags = isPrivate && isStatic ? 16 : 0; + var names = isPrivate ? privateIdentifiers : isStatic ? staticNames : instanceNames; var memberName = name && ts.getPropertyNameForPropertyNameNode(name); if (memberName) { switch (member.kind) { - case 167: - addName(names, name, memberName, 1); - break; case 168: - addName(names, name, memberName, 2); + addName(names, name, memberName, 1 | privateStaticFlags); break; - case 163: - addName(names, name, memberName, 3); + case 169: + addName(names, name, memberName, 2 | privateStaticFlags); break; - case 165: - addName(names, name, memberName, 8); + case 164: + addName(names, name, memberName, 3 | privateStaticFlags); + break; + case 166: + addName(names, name, memberName, 8 | privateStaticFlags); break; } } @@ -60940,16 +62817,23 @@ var ts; function addName(names, location, name, meaning) { var prev = names.get(name); if (prev) { - if (prev & 8) { - if (meaning !== 8) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); - } - } - else if (prev & meaning) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + if ((prev & 16) !== (meaning & 16)) { + error(location, ts.Diagnostics.Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name, ts.getTextOfNode(location)); } else { - names.set(name, prev | meaning); + var prevIsMethod = !!(prev & 8); + var isMethod = !!(meaning & 8); + if (prevIsMethod || isMethod) { + if (prevIsMethod !== isMethod) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + } + else if (prev & meaning & ~16) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names.set(name, prev | meaning); + } } } else { @@ -60982,7 +62866,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 162) { + if (member.kind === 163) { var memberName = void 0; var name = member.name; switch (name.kind) { @@ -61007,14 +62891,14 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 253) { + if (node.kind === 254) { var nodeSymbol = getSymbolOfNode(node); - if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + if (nodeSymbol.declarations && nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; } } var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); - if (indexSymbol) { + if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { var seenNumericIndexer = false; var seenStringIndexer = false; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -61047,10 +62931,9 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); - if (ts.isPrivateIdentifier(node.name) && languageVersion < 99) { - for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) { - getNodeLinks(lexicalScope).flags |= 67108864; - } + setNodeLinksForPrivateIdentifierScope(node); + if (ts.isPrivateIdentifier(node.name) && ts.hasStaticModifier(node) && node.initializer && languageVersion === 99 && !compilerOptions.useDefineForClassFields) { + error(node.initializer, ts.Diagnostics.Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag); } } function checkPropertySignature(node) { @@ -61062,13 +62945,28 @@ var ts; function checkMethodDeclaration(node) { if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); - if (ts.isPrivateIdentifier(node.name)) { - error(node, ts.Diagnostics.A_method_cannot_be_named_with_a_private_identifier); - } checkFunctionOrMethodDeclaration(node); - if (ts.hasSyntacticModifier(node, 128) && node.kind === 165 && node.body) { + if (ts.hasSyntacticModifier(node, 128) && node.kind === 166 && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } + if (ts.isPrivateIdentifier(node.name) && !ts.getContainingClass(node)) { + error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + } + setNodeLinksForPrivateIdentifierScope(node); + } + function setNodeLinksForPrivateIdentifierScope(node) { + if (ts.isPrivateIdentifier(node.name) && languageVersion < 99) { + for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) { + getNodeLinks(lexicalScope).flags |= 67108864; + } + if (ts.isClassExpression(node.parent)) { + var enclosingIterationStatement = getEnclosingIterationStatement(node.parent); + if (enclosingIterationStatement) { + getNodeLinks(node.name).flags |= 524288; + getNodeLinks(enclosingIterationStatement).flags |= 65536; + } + } + } } function checkConstructorDeclaration(node) { checkSignatureDeclaration(node); @@ -61087,10 +62985,10 @@ var ts; return; } function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) { - if (ts.isPrivateIdentifierPropertyDeclaration(n)) { + if (ts.isPrivateIdentifierClassElementDeclaration(n)) { return true; } - return n.kind === 163 && + return n.kind === 164 && !ts.hasSyntacticModifier(n, 32) && !!n.initializer; } @@ -61103,15 +63001,15 @@ var ts; if (classExtendsNull) { error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } - var superCallShouldBeFirst = (compilerOptions.target !== 99 || !compilerOptions.useDefineForClassFields) && + var superCallShouldBeFirst = (compilerOptions.target !== 99 || !useDefineForClassFields) && (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 92); })); + ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 16476); })); if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement = void 0; for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) { var statement = statements_4[_i]; - if (statement.kind === 233 && ts.isSuperCall(statement.expression)) { + if (statement.kind === 234 && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -61135,48 +63033,47 @@ var ts; checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 167) { + if (node.kind === 168) { if (!(node.flags & 8388608) && ts.nodeIsPresent(node.body) && (node.flags & 256)) { if (!(node.flags & 512)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } } } - if (node.name.kind === 158) { + if (node.name.kind === 159) { checkComputedPropertyName(node.name); } - if (ts.isPrivateIdentifier(node.name)) { - error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier); - } - if (!hasNonBindableDynamicName(node)) { - var otherKind = node.kind === 167 ? 168 : 167; - var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); - if (otherAccessor) { - var nodeFlags = ts.getEffectiveModifierFlags(node); - var otherFlags = ts.getEffectiveModifierFlags(otherAccessor); - if ((nodeFlags & 28) !== (otherFlags & 28)) { - error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + if (hasBindableName(node)) { + var symbol = getSymbolOfNode(node); + var getter = ts.getDeclarationOfKind(symbol, 168); + var setter = ts.getDeclarationOfKind(symbol, 169); + if (getter && setter && !(getNodeCheckFlags(getter) & 1)) { + getNodeLinks(getter).flags |= 1; + var getterFlags = ts.getEffectiveModifierFlags(getter); + var setterFlags = ts.getEffectiveModifierFlags(setter); + if ((getterFlags & 128) !== (setterFlags & 128)) { + error(getter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(setter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } + if (((getterFlags & 16) && !(setterFlags & (16 | 8))) || + ((getterFlags & 8) && !(setterFlags & 8))) { + error(getter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(setter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); } - if ((nodeFlags & 128) !== (otherFlags & 128)) { - error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + var getterType = getAnnotatedAccessorType(getter); + var setterType = getAnnotatedAccessorType(setter); + if (getterType && setterType) { + checkTypeAssignableTo(getterType, setterType, getter, ts.Diagnostics.The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type); } - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 167) { + if (node.kind === 168) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } checkSourceElement(node.body); - } - function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { - var firstType = getAnnotatedType(first); - var secondType = getAnnotatedType(second); - if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { - error(first, message); - } + setNodeLinksForPrivateIdentifierScope(node); } function checkMissingDeclaration(node) { checkDecorators(node); @@ -61213,7 +63110,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 173 && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 174 && 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); } ts.forEach(node.typeArguments, checkSourceElement); @@ -61228,7 +63125,7 @@ var ts; var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 134217728); })) { - errorOrSuggestion(false, getDeprecatedSuggestionNode(node), ts.Diagnostics._0_is_deprecated, symbol.escapedName); + addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 && symbol.flags & 8) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); @@ -61266,7 +63163,7 @@ var ts; var hasNamedElement = ts.some(elementTypes, ts.isNamedTupleMember); for (var _i = 0, elementTypes_1 = elementTypes; _i < elementTypes_1.length; _i++) { var e = elementTypes_1[_i]; - if (e.kind !== 192 && hasNamedElement) { + if (e.kind !== 193 && hasNamedElement) { grammarErrorOnNode(e, ts.Diagnostics.Tuple_members_must_all_have_names_or_all_not_have_names); break; } @@ -61314,7 +63211,7 @@ var ts; var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType, false))) { - if (accessNode.kind === 202 && ts.isAssignmentTarget(accessNode) && + if (accessNode.kind === 203 && ts.isAssignmentTarget(accessNode) && ts.getObjectFlags(objectType) & 32 && getMappedTypeModifiers(objectType) & 1) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } @@ -61370,7 +63267,7 @@ var ts; ts.forEachChild(node, checkSourceElement); } function checkInferType(node) { - if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 184 && n.parent.extendsType === n; })) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 185 && n.parent.extendsType === n; })) { grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); @@ -61393,23 +63290,23 @@ var ts; if (node.dotDotDotToken && node.questionToken) { grammarErrorOnNode(node, ts.Diagnostics.A_tuple_member_cannot_be_both_optional_and_rest); } - if (node.type.kind === 180) { + if (node.type.kind === 181) { grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type); } - if (node.type.kind === 181) { + if (node.type.kind === 182) { grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type); } checkSourceElement(node.type); getTypeFromTypeNode(node); } function isPrivateWithinAmbient(node) { - return (ts.hasEffectiveModifier(node, 8) || ts.isPrivateIdentifierPropertyDeclaration(node)) && !!(node.flags & 8388608); + return (ts.hasEffectiveModifier(node, 8) || ts.isPrivateIdentifierClassElementDeclaration(node)) && !!(node.flags & 8388608); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); - if (n.parent.kind !== 253 && - n.parent.kind !== 252 && - n.parent.kind !== 221 && + if (n.parent.kind !== 254 && + n.parent.kind !== 253 && + n.parent.kind !== 222 && n.flags & 8388608) { if (!(flags & 2) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { flags |= 1; @@ -61490,7 +63387,7 @@ var ts; ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - var reportError = (node.kind === 165 || node.kind === 164) && + var reportError = (node.kind === 166 || node.kind === 165) && ts.hasSyntacticModifier(node, 32) !== ts.hasSyntacticModifier(subsequentNode, 32); if (reportError) { var diagnostic = ts.hasSyntacticModifier(node, 32) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; @@ -61521,48 +63418,50 @@ var ts; var multipleConstructorImplementation = false; var hasNonAmbientClass = false; var functionDeclarations = []; - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var current = declarations_4[_i]; - var node = current; - var inAmbientContext = node.flags & 8388608; - var inAmbientContextOrInterface = node.parent && (node.parent.kind === 253 || node.parent.kind === 177) || inAmbientContext; - if (inAmbientContextOrInterface) { - previousDeclaration = undefined; - } - if ((node.kind === 252 || node.kind === 221) && !inAmbientContext) { - hasNonAmbientClass = true; - } - if (node.kind === 251 || node.kind === 165 || node.kind === 164 || node.kind === 166) { - functionDeclarations.push(node); - var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); - someNodeFlags |= currentNodeFlags; - allNodeFlags &= currentNodeFlags; - someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); - allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); - var bodyIsPresent = ts.nodeIsPresent(node.body); - if (bodyIsPresent && bodyDeclaration) { - if (isConstructor) { - multipleConstructorImplementation = true; + if (declarations) { + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; + var node = current; + var inAmbientContext = node.flags & 8388608; + var inAmbientContextOrInterface = node.parent && (node.parent.kind === 254 || node.parent.kind === 178) || inAmbientContext; + if (inAmbientContextOrInterface) { + previousDeclaration = undefined; + } + if ((node.kind === 253 || node.kind === 222) && !inAmbientContext) { + hasNonAmbientClass = true; + } + if (node.kind === 252 || node.kind === 166 || node.kind === 165 || node.kind === 167) { + functionDeclarations.push(node); + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); + var bodyIsPresent = ts.nodeIsPresent(node.body); + if (bodyIsPresent && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } + } + else if ((previousDeclaration === null || previousDeclaration === void 0 ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (bodyIsPresent) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } } else { - duplicateFunctionDeclaration = true; + hasOverloads = true; } - } - else if ((previousDeclaration === null || previousDeclaration === void 0 ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) { - reportImplementationExpectedError(previousDeclaration); - } - if (bodyIsPresent) { - if (!bodyDeclaration) { - bodyDeclaration = node; + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; } } - else { - hasOverloads = true; - } - previousDeclaration = node; - if (!inAmbientContextOrInterface) { - lastSeenNonAmbientDeclaration = node; - } } } if (multipleConstructorImplementation) { @@ -61585,8 +63484,10 @@ var ts; reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { - checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); - checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (declarations) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + } if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); @@ -61652,38 +63553,41 @@ var ts; function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { - case 253: case 254: - case 331: - case 324: - case 325: + case 255: + case 335: + case 328: + case 329: return 2; - case 256: + case 257: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 ? 4 | 1 : 4; - case 252: - case 255: - case 291: + case 253: + case 256: + case 292: return 2 | 1; - case 297: + case 298: return 2 | 1 | 4; - case 266: - if (!ts.isEntityNameExpression(d.expression)) { + case 267: + case 217: + var node_2 = d; + var expression = ts.isExportAssignment(node_2) ? node_2.expression : node_2.right; + if (!ts.isEntityNameExpression(expression)) { return 1; } - d = d.expression; - case 260: + d = expression; + case 261: + case 264: case 263: - case 262: - var result_12 = 0; + var result_13 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_12 |= getDeclarationSpaces(d); }); - return result_12; - case 249: - case 198: - case 251: - case 265: + ts.forEach(target.declarations, function (d) { result_13 |= getDeclarationSpaces(d); }); + return result_13; + case 250: + case 199: + case 252: + case 266: case 78: return 1; default: @@ -61841,22 +63745,22 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 252: + case 253: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 160: + case 161: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 163: + case 164: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 165: - case 167: + case 166: case 168: + case 169: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -61892,15 +63796,15 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { + case 184: case 183: - case 182: return getEntityNameForDecoratorMetadataFromTypeList(node.types); - case 184: + case 185: return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); - case 186: - case 192: + case 187: + case 193: return getEntityNameForDecoratorMetadata(node.type); - case 173: + case 174: return node.typeName; } } @@ -61909,13 +63813,13 @@ var ts; var commonEntityName; for (var _i = 0, types_23 = types; _i < types_23.length; _i++) { var typeNode = types_23[_i]; - while (typeNode.kind === 186 || typeNode.kind === 192) { + while (typeNode.kind === 187 || typeNode.kind === 193) { typeNode = typeNode.type; } if (typeNode.kind === 141) { continue; } - if (!strictNullChecks && (typeNode.kind === 191 && typeNode.literal.kind === 103 || typeNode.kind === 150)) { + if (!strictNullChecks && (typeNode.kind === 192 && typeNode.literal.kind === 103 || typeNode.kind === 150)) { continue; } var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); @@ -61951,13 +63855,13 @@ var ts; } var firstDecorator = node.decorators[0]; checkExternalEmitHelpers(firstDecorator, 8); - if (node.kind === 160) { + if (node.kind === 161) { checkExternalEmitHelpers(firstDecorator, 32); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16); switch (node.kind) { - case 252: + case 253: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -61966,23 +63870,23 @@ var ts; } } break; - case 167: case 168: - var otherKind = node.kind === 167 ? 168 : 167; + case 169: + var otherKind = node.kind === 168 ? 169 : 168; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); break; - case 165: + case 166: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 163: + case 164: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 160: + case 161: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); var containingSignature = node.parent; for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { @@ -62041,7 +63945,7 @@ var ts; else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 157 ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 158 ? node.name.right : node.name)); } } } @@ -62085,23 +63989,24 @@ var ts; switch (node.kind) { case 78: return node; - case 201: + case 202: return node.name; default: return undefined; } } function checkFunctionOrMethodDeclaration(node) { + var _a; checkDecorators(node); checkSignatureDeclaration(node); var functionFlags = ts.getFunctionFlags(node); - if (node.name && node.name.kind === 158) { + if (node.name && node.name.kind === 159) { checkComputedPropertyName(node.name); } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { var symbol = getSymbolOfNode(node); var localSymbol = node.localSymbol || symbol; - var firstDeclaration = ts.find(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072); }); + var firstDeclaration = (_a = localSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072); }); if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); } @@ -62109,7 +64014,7 @@ var ts; checkFunctionOrConstructorSymbol(symbol); } } - var body = node.kind === 164 ? undefined : node.body; + var body = node.kind === 165 ? undefined : node.body; checkSourceElement(body); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node)); if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { @@ -62142,42 +64047,42 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 252: - case 221: + case 253: + case 222: checkUnusedClassMembers(node, addDiagnostic); checkUnusedTypeParameters(node, addDiagnostic); break; - case 297: - case 256: - case 230: - case 258: - case 237: + case 298: + case 257: + case 231: + case 259: case 238: case 239: + case 240: checkUnusedLocalsAndParameters(node, addDiagnostic); break; - case 166: - case 208: - case 251: - case 209: - case 165: case 167: + case 209: + case 252: + case 210: + case 166: case 168: + case 169: if (node.body) { checkUnusedLocalsAndParameters(node, addDiagnostic); } checkUnusedTypeParameters(node, addDiagnostic); break; - case 164: - case 169: + case 165: case 170: - case 174: + case 171: case 175: + case 176: + case 255: case 254: - case 253: checkUnusedTypeParameters(node, addDiagnostic); break; - case 185: + case 186: checkUnusedInferTypeParameter(node, addDiagnostic); break; default: @@ -62197,11 +64102,11 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 165: - case 163: - case 167: + case 166: + case 164: case 168: - if (member.kind === 168 && member.symbol.flags & 32768) { + case 169: + if (member.kind === 169 && member.symbol.flags & 32768) { break; } var symbol = getSymbolOfNode(member); @@ -62211,7 +64116,7 @@ var ts; addDiagnostic(member, 0, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; - case 166: + case 167: for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasSyntacticModifier(parameter, 8)) { @@ -62219,8 +64124,8 @@ var ts; } } break; - case 171: - case 229: + case 172: + case 230: break; default: ts.Debug.fail(); @@ -62234,7 +64139,8 @@ var ts; } } function checkUnusedTypeParameters(node, addDiagnostic) { - if (ts.last(getSymbolOfNode(node).declarations) !== node) + var declarations = getSymbolOfNode(node).declarations; + if (!declarations || ts.last(declarations) !== node) return; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); var seenParentsWithEveryUnused = new ts.Set(); @@ -62244,7 +64150,7 @@ var ts; continue; var name = ts.idText(typeParameter.name); var parent = typeParameter.parent; - if (parent.kind !== 185 && parent.typeParameters.every(isTypeParameterUnused)) { + if (parent.kind !== 186 && parent.typeParameters.every(isTypeParameterUnused)) { if (ts.tryAddToSet(seenParentsWithEveryUnused, parent)) { var sourceFile = ts.getSourceFileOfNode(parent); var range = ts.isJSDocTemplateTag(parent) @@ -62278,11 +64184,11 @@ var ts; return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } function isValidUnusedLocalDeclaration(declaration) { - if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { - return !!ts.findAncestor(declaration.parent, function (ancestor) { - return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : - ts.isForOfStatement(ancestor) ? true : "quit"; - }); + if (ts.isBindingElement(declaration)) { + if (ts.isObjectBindingPattern(declaration.parent)) { + return !!(declaration.propertyName && isIdentifierThatStartsWithUnderscore(declaration.name)); + } + return isIdentifierThatStartsWithUnderscore(declaration.name); } return ts.isAmbientModule(declaration) || (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); @@ -62295,38 +64201,40 @@ var ts; if (local.flags & 262144 ? !(local.flags & 3 && !(local.isReferenced & 3)) : local.isReferenced || local.exportSymbol) { return; } - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (isValidUnusedLocalDeclaration(declaration)) { - continue; - } - if (isImportedDeclaration(declaration)) { - addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); - } - else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { - var lastElement = ts.last(declaration.parent.elements); - if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { - addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + if (local.declarations) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (isValidUnusedLocalDeclaration(declaration)) { + continue; } - } - else if (ts.isVariableDeclaration(declaration)) { - addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); - } - else { - var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); - var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); - if (parameter && name) { - if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { - if (ts.isBindingElement(declaration) && ts.isArrayBindingPattern(declaration.parent)) { - addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); - } - else { - addDiagnostic(parameter, 1, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); - } + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); } } + else if (ts.isVariableDeclaration(declaration)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } else { - errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); + if (parameter && name) { + if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { + if (ts.isBindingElement(declaration) && ts.isArrayBindingPattern(declaration.parent)) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + else { + addDiagnostic(parameter, 1, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); + } + } + } + else { + errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); + } } } } @@ -62336,7 +64244,7 @@ var ts; var importDecl = importClause.parent; var nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? - (importClause.namedBindings.kind === 263 ? 1 : importClause.namedBindings.elements.length) + (importClause.namedBindings.kind === 264 ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { addDiagnostic(importDecl, 0, unuseds.length === 1 @@ -62354,7 +64262,7 @@ var ts; var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 : 0; if (bindingPattern.elements.length === bindingElements.length) { - if (bindingElements.length === 1 && bindingPattern.parent.kind === 249 && bindingPattern.parent.parent.kind === 250) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 250 && bindingPattern.parent.parent.kind === 251) { addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { @@ -62375,7 +64283,7 @@ var ts; if (declarationList.declarations.length === declarations.length) { addDiagnostic(declarationList, 0, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) - : ts.createDiagnosticForNode(declarationList.parent.kind === 232 ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + : ts.createDiagnosticForNode(declarationList.parent.kind === 233 ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { @@ -62389,21 +64297,21 @@ var ts; switch (name.kind) { case 78: return ts.idText(name); + case 198: case 197: - case 196: return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); default: return ts.Debug.assertNever(name); } } function isImportedDeclaration(node) { - return node.kind === 262 || node.kind === 265 || node.kind === 263; + return node.kind === 263 || node.kind === 266 || node.kind === 264; } function importClauseFromImported(decl) { - return decl.kind === 262 ? decl : decl.kind === 263 ? decl.parent : decl.parent.parent; + return decl.kind === 263 ? decl : decl.kind === 264 ? decl.parent : decl.parent.parent; } function checkBlock(node) { - if (node.kind === 230) { + if (node.kind === 231) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -62432,19 +64340,19 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 163 || - node.kind === 162 || + if (node.kind === 164 || + node.kind === 163 || + node.kind === 166 || node.kind === 165 || - node.kind === 164 || - node.kind === 167 || - node.kind === 168) { + node.kind === 168 || + node.kind === 169) { return false; } if (node.flags & 8388608) { return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 160 && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 161 && ts.nodeIsMissing(root.parent.body)) { return false; } return true; @@ -62479,10 +64387,11 @@ var ts; return false; }); } - function checkWeakMapCollision(node) { + function checkWeakMapSetCollision(node) { var enclosingBlockScope = ts.getEnclosingBlockScopeContainer(node); if (getNodeCheckFlags(enclosingBlockScope) & 67108864) { - errorSkippedOn("noEmit", node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, "WeakMap"); + ts.Debug.assert(ts.isNamedDeclaration(node) && ts.isIdentifier(node.name) && typeof node.name.escapedText === "string", "The target of a WeakMap/WeakSet collision check should be an identifier"); + errorSkippedOn("noEmit", node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, node.name.escapedText); } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { @@ -62496,7 +64405,7 @@ var ts; return; } var parent = getDeclarationContainer(node); - if (parent.kind === 297 && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 298 && ts.isExternalOrCommonJsModule(parent)) { errorSkippedOn("noEmit", name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } @@ -62508,7 +64417,7 @@ var ts; return; } var parent = getDeclarationContainer(node); - if (parent.kind === 297 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048) { + if (parent.kind === 298 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048) { errorSkippedOn("noEmit", name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } @@ -62516,7 +64425,7 @@ var ts; if ((ts.getCombinedNodeFlags(node) & 3) !== 0 || ts.isParameterDeclaration(node)) { return; } - if (node.kind === 249 && !node.initializer) { + if (node.kind === 250 && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -62528,15 +64437,15 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 250); - var container = varDeclList.parent.kind === 232 && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 251); + var container = varDeclList.parent.kind === 233 && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; var namesShareScope = container && - (container.kind === 230 && ts.isFunctionLike(container.parent) || + (container.kind === 231 && ts.isFunctionLike(container.parent) || + container.kind === 258 || container.kind === 257 || - container.kind === 256 || - container.kind === 297); + container.kind === 298); if (!namesShareScope) { var name = symbolToString(localDeclarationSymbol); error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); @@ -62557,17 +64466,17 @@ var ts; if (!node.name) { return; } - if (node.name.kind === 158) { + if (node.name.kind === 159) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 198) { - if (node.parent.kind === 196 && languageVersion < 99) { + if (ts.isBindingElement(node)) { + if (ts.isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < 5) { checkExternalEmitHelpers(node, 4); } - if (node.propertyName && node.propertyName.kind === 158) { + if (node.propertyName && node.propertyName.kind === 159) { checkComputedPropertyName(node.propertyName); } var parent = node.parent.parent; @@ -62580,13 +64489,13 @@ var ts; var property = getPropertyOfType(parentType, nameText); if (property) { markPropertyAsReferenced(property, undefined, false); - checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 105, parentType, property); + checkPropertyAccessibility(node, !!parent.initializer && parent.initializer.kind === 105, false, parentType, property); } } } } if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 197 && languageVersion < 2 && compilerOptions.downlevelIteration) { + if (node.name.kind === 198 && languageVersion < 2 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512); } ts.forEach(node.name.elements, checkSourceElement); @@ -62596,7 +64505,7 @@ var ts; return; } if (ts.isBindingPattern(node.name)) { - var needCheckInitializer = node.initializer && node.parent.parent.kind !== 238; + var needCheckInitializer = node.initializer && node.parent.parent.kind !== 239; var needCheckWidenedType = node.name.elements.length === 0; if (needCheckInitializer || needCheckWidenedType) { var widenedType = getWidenedTypeForVariableLikeDeclaration(node); @@ -62621,7 +64530,7 @@ var ts; return; } var symbol = getSymbolOfNode(node); - if (symbol.flags & 2097152 && ts.isRequireVariableDeclaration(node, true)) { + if (symbol.flags & 2097152 && ts.isRequireVariableDeclaration(node)) { checkAliasSymbol(node); return; } @@ -62633,11 +64542,11 @@ var ts; ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && !!((_a = symbol.exports) === null || _a === void 0 ? void 0 : _a.size); - if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 238) { + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 239) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, undefined); } } - if (symbol.declarations.length > 1) { + if (symbol.declarations && symbol.declarations.length > 1) { if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) { error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } @@ -62653,25 +64562,26 @@ var ts; if (node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, undefined); } - if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 163 && node.kind !== 162) { + if (node.kind !== 164 && node.kind !== 163) { checkExportsOnMergedDeclarations(node); - if (node.kind === 249 || node.kind === 198) { + if (node.kind === 250 || node.kind === 199) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - if (languageVersion < 99 && needCollisionCheckForIdentifier(node, node.name, "WeakMap")) { - potentialWeakMapCollisions.push(node); + if (languageVersion < 99 + && (needCollisionCheckForIdentifier(node, node.name, "WeakMap") || needCollisionCheckForIdentifier(node, node.name, "WeakSet"))) { + potentialWeakMapSetCollisions.push(node); } } } function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) { var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); - var message = nextDeclaration.kind === 163 || nextDeclaration.kind === 162 + var message = nextDeclaration.kind === 164 || nextDeclaration.kind === 163 ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; var declName = ts.declarationNameToString(nextDeclarationName); @@ -62681,8 +64591,8 @@ var ts; } } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 160 && right.kind === 249) || - (left.kind === 249 && right.kind === 160)) { + if ((left.kind === 161 && right.kind === 250) || + (left.kind === 250 && right.kind === 161)) { return true; } if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { @@ -62697,10 +64607,10 @@ var ts; return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { - ts.tracing.push("check", "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check", "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); checkGrammarVariableDeclaration(node); checkVariableLikeDeclaration(node); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkBindingElement(node) { checkGrammarBindingElement(node); @@ -62718,44 +64628,49 @@ var ts; function checkIfStatement(node) { checkGrammarStatementInAmbientContext(node); var type = checkTruthinessExpression(node.expression); - checkTestingKnownTruthyCallableType(node.expression, type, node.thenStatement); + checkTestingKnownTruthyCallableOrAwaitableType(node.expression, type, node.thenStatement); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 231) { + if (node.thenStatement.kind === 232) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); } - function checkTestingKnownTruthyCallableType(condExpr, type, body) { - if (!strictNullChecks) { + function checkTestingKnownTruthyCallableOrAwaitableType(condExpr, type, body) { + if (!strictNullChecks) + return; + if (getFalsyFlags(type)) return; - } var location = ts.isBinaryExpression(condExpr) ? condExpr.right : condExpr; var testedNode = ts.isIdentifier(location) ? location : ts.isPropertyAccessExpression(location) ? location.name : ts.isBinaryExpression(location) && ts.isIdentifier(location.right) ? location.right : undefined; - if (!testedNode) { - return; - } - var possiblyFalsy = getFalsyFlags(type); - if (possiblyFalsy) { + var isPropertyExpressionCast = ts.isPropertyAccessExpression(location) + && ts.isAssertionExpression(ts.skipParentheses(location.expression)); + if (!testedNode || isPropertyExpressionCast) { return; } var callSignatures = getSignaturesOfType(type, 0); - if (callSignatures.length === 0) { + var isPromise = !!getAwaitedTypeOfPromise(type); + if (callSignatures.length === 0 && !isPromise) { return; } var testedSymbol = getSymbolAtLocation(testedNode); if (!testedSymbol) { return; } - var isUsed = ts.isBinaryExpression(condExpr.parent) && isFunctionUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) - || body && isFunctionUsedInConditionBody(condExpr, body, testedNode, testedSymbol); + var isUsed = ts.isBinaryExpression(condExpr.parent) && isSymbolUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) + || body && isSymbolUsedInConditionBody(condExpr, body, testedNode, testedSymbol); if (!isUsed) { - error(location, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead); + if (isPromise) { + errorAndMaybeSuggestAwait(location, true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, getTypeNameForErrorDisplay(type)); + } + else { + error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead); + } } } - function isFunctionUsedInConditionBody(expr, body, testedNode, testedSymbol) { + function isSymbolUsedInConditionBody(expr, body, testedNode, testedSymbol) { return !!ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); @@ -62790,7 +64705,7 @@ var ts; return ts.forEachChild(childNode, check); }); } - function isFunctionUsedInBinaryExpressionChain(node, testedSymbol) { + function isSymbolUsedInBinaryExpressionChain(node, testedSymbol) { while (ts.isBinaryExpression(node) && node.operatorToken.kind === 55) { var isUsed = ts.forEachChild(node.right, function visit(child) { if (ts.isIdentifier(child)) { @@ -62829,12 +64744,12 @@ var ts; } function checkForStatement(node) { if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 250) { + if (node.initializer && node.initializer.kind === 251) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 250) { + if (node.initializer.kind === 251) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -62861,13 +64776,13 @@ var ts; else if (compilerOptions.downlevelIteration && languageVersion < 2) { checkExternalEmitHelpers(node, 256); } - if (node.initializer.kind === 250) { + if (node.initializer.kind === 251) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node); - if (varExpr.kind === 199 || varExpr.kind === 200) { + if (varExpr.kind === 200 || varExpr.kind === 201) { checkDestructuringAssignment(varExpr, iteratedType || errorType); } else { @@ -62886,7 +64801,7 @@ var ts; function checkForInStatement(node) { checkGrammarForInOrForOfStatement(node); var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression)); - if (node.initializer.kind === 250) { + if (node.initializer.kind === 251) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -62896,7 +64811,7 @@ var ts; else { var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 199 || varExpr.kind === 200) { + if (varExpr.kind === 200 || varExpr.kind === 201) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -62987,18 +64902,8 @@ var ts; } if (!isArrayLikeType(arrayType)) { if (errorNode && !reportedError) { - var yieldType = getIterationTypeOfIterable(use, 0, inputType, undefined); - var _a = !(use & 4) || hasStringConstituent - ? downlevelIteration - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] - : yieldType - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false] - : [ts.Diagnostics.Type_0_is_not_an_array_type, true] - : downlevelIteration - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] - : yieldType - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false] - : [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true], defaultDiagnostic = _a[0], maybeMissingAwait = _a[1]; + var allowsStrings = !!(use & 4) && !hasStringConstituent; + var _a = getIterationDiagnosticDetails(allowsStrings, downlevelIteration), defaultDiagnostic = _a[0], maybeMissingAwait = _a[1]; errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType)); } return hasStringConstituent ? possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType : undefined; @@ -63011,6 +64916,40 @@ var ts; return getUnionType(possibleOutOfBounds ? [arrayElementType, stringType, undefinedType] : [arrayElementType, stringType], 2); } return (use & 128) ? includeUndefinedInIndexSignature(arrayElementType) : arrayElementType; + function getIterationDiagnosticDetails(allowsStrings, downlevelIteration) { + var _a; + if (downlevelIteration) { + return allowsStrings + ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] + : [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]; + } + var yieldType = getIterationTypeOfIterable(use, 0, inputType, undefined); + if (yieldType) { + return [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]; + } + if (isES2015OrLaterIterable((_a = inputType.symbol) === null || _a === void 0 ? void 0 : _a.escapedName)) { + return [ts.Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, true]; + } + return allowsStrings + ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true] + : [ts.Diagnostics.Type_0_is_not_an_array_type, true]; + } + } + function isES2015OrLaterIterable(n) { + switch (n) { + case "Float32Array": + case "Float64Array": + case "Int16Array": + case "Int32Array": + case "Int8Array": + case "NodeList": + case "Uint16Array": + case "Uint32Array": + case "Uint8Array": + case "Uint8ClampedArray": + return true; + } + return false; } function getIterationTypeOfIterable(use, typeKind, inputType, errorNode) { if (isTypeAny(inputType)) { @@ -63175,9 +65114,14 @@ var ts; return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType)); } } + function getPropertyNameForKnownSymbolName(symbolName) { + var ctorType = getGlobalESSymbolConstructorSymbol(false); + var uniqueType = ctorType && getTypeOfPropertyOfType(getTypeOfSymbol(ctorType), ts.escapeLeadingUnderscores(symbolName)); + return uniqueType && isTypeUsableAsPropertyName(uniqueType) ? getPropertyNameFromType(uniqueType) : "__@" + symbolName; + } function getIterationTypesOfIterableSlow(type, resolver, errorNode) { var _a; - var method = getPropertyOfType(type, ts.getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); + var method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); var methodType = method && !(method.flags & 16777216) ? getTypeOfSymbol(method) : undefined; if (isTypeAny(methodType)) { return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); @@ -63384,12 +65328,12 @@ var ts; var functionFlags = ts.getFunctionFlags(func); if (strictNullChecks || node.expression || returnType.flags & 131072) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - if (func.kind === 168) { + if (func.kind === 169) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 166) { + else if (func.kind === 167) { if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -63404,7 +65348,7 @@ var ts; } } } - else if (func.kind !== 166 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + else if (func.kind !== 167 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } } @@ -63429,7 +65373,7 @@ var ts; var expressionType = checkExpression(node.expression); var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { - if (clause.kind === 285 && !hasDuplicateDefaultClause) { + if (clause.kind === 286 && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -63438,7 +65382,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 284) { + if (produceDiagnostics && clause.kind === 285) { var caseType = checkExpression(clause.expression); var caseIsLiteral = isLiteralType(caseType); var comparedExpressionType = expressionType; @@ -63465,7 +65409,7 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 245 && current.label.escapedText === node.label.escapedText) { + if (current.kind === 246 && current.label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } @@ -63491,10 +65435,11 @@ var ts; if (catchClause) { if (catchClause.variableDeclaration) { var declaration = catchClause.variableDeclaration; - if (declaration.type) { + var typeNode = ts.getEffectiveTypeAnnotationNode(ts.getRootDeclaration(declaration)); + if (typeNode) { var type = getTypeForVariableLikeDeclaration(declaration, false); if (type && !(type.flags & 3)) { - grammarErrorOnFirstToken(declaration.type, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified); + grammarErrorOnFirstToken(typeNode, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified); } } else if (declaration.initializer) { @@ -63505,7 +65450,7 @@ var ts; if (blockLocals_1) { ts.forEachKey(catchClause.locals, function (caughtName) { var blockLocal = blockLocals_1.get(caughtName); - if (blockLocal && (blockLocal.flags & 2) !== 0) { + if ((blockLocal === null || blockLocal === void 0 ? void 0 : blockLocal.valueDeclaration) && (blockLocal.flags & 2) !== 0) { grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); } }); @@ -63518,22 +65463,25 @@ var ts; checkBlock(node.finallyBlock); } } - function checkIndexConstraints(type) { - var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1); - var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0); + function checkIndexConstraints(type, isStatic) { + var _a, _b, _c, _d; + var declaredNumberIndexer = getIndexDeclarationOfSymbolTable(isStatic ? (_a = type.symbol) === null || _a === void 0 ? void 0 : _a.exports : (_b = type.symbol) === null || _b === void 0 ? void 0 : _b.members, 1); + var declaredStringIndexer = getIndexDeclarationOfSymbolTable(isStatic ? (_c = type.symbol) === null || _c === void 0 ? void 0 : _c.exports : (_d = type.symbol) === null || _d === void 0 ? void 0 : _d.members, 0); var stringIndexType = getIndexTypeOfType(type, 0); var numberIndexType = getIndexTypeOfType(type, 1); if (stringIndexType || numberIndexType) { ts.forEach(getPropertiesOfObjectType(type), function (prop) { + if (isStatic && prop.flags & 4194304) + return; var propType = getTypeOfSymbol(prop); checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); }); var classDeclaration = type.symbol.valueDeclaration; - if (ts.getObjectFlags(type) & 1 && ts.isClassLike(classDeclaration)) { - for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (!ts.hasSyntacticModifier(member, 32) && hasNonBindableDynamicName(member)) { + if (ts.getObjectFlags(type) & 1 && classDeclaration && ts.isClassLike(classDeclaration)) { + for (var _i = 0, _e = classDeclaration.members; _i < _e.length; _i++) { + var member = _e[_i]; + if (!ts.hasSyntacticModifier(member, 32) && !hasBindableName(member)) { var symbol = getSymbolOfNode(member); var propType = getTypeOfSymbol(symbol); checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0); @@ -63547,7 +65495,7 @@ var ts; errorNode = declaredNumberIndexer || declaredStringIndexer; if (!errorNode && (ts.getObjectFlags(type) & 2)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); - errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + errorNode = someBaseTypeHasBothIndexers || !type.symbol.declarations ? undefined : type.symbol.declarations[0]; } } if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { @@ -63567,8 +65515,8 @@ var ts; } var errorNode; if (propDeclaration && name && - (propDeclaration.kind === 216 || - name.kind === 158 || + (propDeclaration.kind === 217 || + name.kind === 159 || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } @@ -63577,7 +65525,7 @@ var ts; } else if (ts.getObjectFlags(containingType) & 2) { var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); - errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + errorNode = someBaseClassHasBothPropertyAndIndexer || !containingType.symbol.declarations ? undefined : containingType.symbol.declarations[0]; } if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { var errorMessage = indexKind === 0 @@ -63591,6 +65539,7 @@ var ts; switch (name.escapedText) { case "any": case "unknown": + case "never": case "number": case "bigint": case "boolean": @@ -63633,7 +65582,7 @@ var ts; function checkTypeParametersNotReferenced(root, typeParameters, index) { visit(root); function visit(node) { - if (node.kind === 173) { + if (node.kind === 174) { var type = getTypeFromTypeReference(node); if (type.flags & 262144) { for (var i = index; i < typeParameters.length; i++) { @@ -63647,14 +65596,14 @@ var ts; } } function checkTypeParameterListsIdentical(symbol) { - if (symbol.declarations.length === 1) { + if (symbol.declarations && symbol.declarations.length === 1) { return; } var links = getSymbolLinks(symbol); if (!links.typeParametersChecked) { links.typeParametersChecked = true; var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); - if (declarations.length <= 1) { + if (!declarations || declarations.length <= 1) { return; } var type = getDeclaredTypeOfSymbol(symbol); @@ -63708,6 +65657,9 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { + if (ts.some(node.decorators) && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { + grammarErrorOnNode(node.decorators[0], ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); + } if (!node.name && !ts.hasSyntacticModifier(node, 512)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } @@ -63735,7 +65687,8 @@ var ts; checkTypeParameterListsIdentical(symbol); checkFunctionOrConstructorSymbol(symbol); checkClassForDuplicateDeclarations(node); - if (!(node.flags & 8388608)) { + var nodeInAmbientContext = !!(node.flags & 8388608); + if (!nodeInAmbientContext) { checkClassForStaticPropertyNameConflicts(node); } var baseTypeNode = ts.getEffectiveBaseTypeNode(node); @@ -63791,6 +65744,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } + checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { @@ -63820,13 +65774,75 @@ var ts; } if (produceDiagnostics) { checkIndexConstraints(type); + checkIndexConstraints(staticType, true); checkTypeForDuplicateIndexSignatures(node); checkPropertyInitialization(node); } } + function checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType) { + var nodeInAmbientContext = !!(node.flags & 8388608); + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); + var baseTypes = baseTypeNode && getBaseTypes(type); + var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; + var baseStaticType = getBaseConstructorTypeOfClass(type); + var _loop_24 = function (member) { + if (ts.hasAmbientModifier(member)) { + return "continue"; + } + if (ts.isConstructorDeclaration(member)) { + ts.forEach(member.parameters, function (param) { + if (ts.isParameterPropertyDeclaration(param, member)) { + checkClassMember(param, true); + } + }); + } + checkClassMember(member); + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_24(member); + } + function checkClassMember(member, memberIsParameterProperty) { + var hasOverride = ts.hasOverrideModifier(member); + var hasStatic = ts.hasStaticModifier(member); + if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (!declaredProp) { + return; + } + var thisType = hasStatic ? staticType : typeWithThis; + var baseType = hasStatic ? baseStaticType : baseWithThis; + var prop = getPropertyOfType(thisType, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseType, declaredProp.escapedName); + var baseClassName = typeToString(baseWithThis); + if (prop && !baseProp && hasOverride) { + error(member, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); + } + else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.valueDeclaration) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { + var baseHasAbstract = ts.hasAbstractModifier(baseProp.valueDeclaration); + if (hasOverride) { + return; + } + if (!baseHasAbstract) { + var diag = memberIsParameterProperty ? + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : + ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; + error(member, diag, baseClassName); + } + else if (ts.hasAbstractModifier(member) && baseHasAbstract) { + error(member, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); + } + } + } + else if (hasOverride) { + var className = typeToString(type); + error(member, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, className); + } + } + } function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { var issuedMemberError = false; - var _loop_23 = function (member) { + var _loop_25 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -63844,7 +65860,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_23(member); + _loop_25(member); } if (!issuedMemberError) { checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); @@ -63867,10 +65883,11 @@ var ts; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 252 || d.kind === 253; + return d.kind === 253 || d.kind === 254; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { + var _a, _b; var baseProperties = getPropertiesOfType(baseType); basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { var baseProperty = baseProperties_1[_i]; @@ -63888,8 +65905,8 @@ var ts; if (derived === base) { var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol); if (baseDeclarationFlags & 128 && (!derivedClassDecl || !ts.hasSyntacticModifier(derivedClassDecl, 128))) { - for (var _a = 0, _b = getBaseTypes(type); _a < _b.length; _a++) { - var otherBaseType = _b[_a]; + for (var _c = 0, _d = getBaseTypes(type); _c < _d.length; _c++) { + var otherBaseType = _d[_c]; if (otherBaseType === baseType) continue; var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName); @@ -63898,7 +65915,7 @@ var ts; continue basePropertyCheck; } } - if (derivedClassDecl.kind === 221) { + if (derivedClassDecl.kind === 222) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -63916,7 +65933,7 @@ var ts; var derivedPropertyFlags = derived.flags & 98308; if (basePropertyFlags && derivedPropertyFlags) { if (baseDeclarationFlags & 128 && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer) - || base.valueDeclaration && base.valueDeclaration.parent.kind === 253 + || base.valueDeclaration && base.valueDeclaration.parent.kind === 254 || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) { continue; } @@ -63928,13 +65945,13 @@ var ts; ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } - else if (compilerOptions.useDefineForClassFields) { - var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 163 && !d.initializer; }); + else if (useDefineForClassFields) { + var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 164 && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432) && !(baseDeclarationFlags & 128) && !(derivedDeclarationFlags & 128) - && !derived.declarations.some(function (d) { return !!(d.flags & 8388608); })) { + && !((_b = derived.declarations) === null || _b === void 0 ? void 0 : _b.some(function (d) { return !!(d.flags & 8388608); }))) { var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol)); var propName = uninitialized.name; if (uninitialized.exclamationToken @@ -64043,7 +66060,7 @@ var ts; } } function isInstancePropertyWithoutInitializer(node) { - return node.kind === 163 && + return node.kind === 164 && !ts.hasSyntacticModifier(node, 32 | 128) && !node.exclamationToken && !node.initializer; @@ -64065,7 +66082,7 @@ var ts; checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 253); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 254); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -64175,7 +66192,7 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 214: + case 215: var value_2 = evaluate(expr.operand); if (typeof value_2 === "number") { switch (expr.operator) { @@ -64185,7 +66202,7 @@ var ts; } } break; - case 216: + case 217: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { @@ -64214,7 +66231,7 @@ var ts; case 8: checkGrammarNumericLiteral(expr); return +expr.text; - case 207: + case 208: return evaluate(expr.expression); case 78: var identifier = expr; @@ -64222,14 +66239,14 @@ var ts; return +(identifier.escapedText); } return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); + case 203: case 202: - case 201: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384) { var name = void 0; - if (ex.kind === 201) { + if (ex.kind === 202) { name = ex.name.escapedText; } else { @@ -64247,7 +66264,7 @@ var ts; if (memberSymbol) { var declaration = memberSymbol.valueDeclaration; if (declaration !== member) { - if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + if (declaration && isBlockScopedNameDeclaredBeforeUse(declaration, member)) { return getEnumMemberValue(declaration); } error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); @@ -64262,8 +66279,8 @@ var ts; } function isConstantMemberAccess(node) { return node.kind === 78 || - node.kind === 201 && isConstantMemberAccess(node.expression) || - node.kind === 202 && isConstantMemberAccess(node.expression) && + node.kind === 202 && isConstantMemberAccess(node.expression) || + node.kind === 203 && isConstantMemberAccess(node.expression) && ts.isStringLiteralLike(node.argumentExpression); } function checkEnumDeclaration(node) { @@ -64280,7 +66297,7 @@ var ts; var enumSymbol = getSymbolOfNode(node); var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); if (node === firstDeclaration) { - if (enumSymbol.declarations.length > 1) { + if (enumSymbol.declarations && enumSymbol.declarations.length > 1) { var enumIsConst_1 = ts.isEnumConst(node); ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) { @@ -64290,7 +66307,7 @@ var ts; } var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { - if (declaration.kind !== 255) { + if (declaration.kind !== 256) { return false; } var enumDeclaration = declaration; @@ -64316,12 +66333,14 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; - if ((declaration.kind === 252 || - (declaration.kind === 251 && ts.nodeIsPresent(declaration.body))) && - !(declaration.flags & 8388608)) { - return declaration; + if (declarations) { + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 253 || + (declaration.kind === 252 && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 8388608)) { + return declaration; + } } } return undefined; @@ -64366,8 +66385,9 @@ var ts; var symbol = getSymbolOfNode(node); if (symbol.flags & 512 && !inAmbientContext + && symbol.declarations && symbol.declarations.length > 1 - && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions))) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -64377,7 +66397,7 @@ var ts; error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); } } - var mergedClass = ts.getDeclarationOfKind(symbol, 252); + var mergedClass = ts.getDeclarationOfKind(symbol, 253); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768; @@ -64419,37 +66439,38 @@ var ts; } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { + var _a; switch (node.kind) { - case 232: - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; + case 233: + for (var _i = 0, _b = node.declarationList.declarations; _i < _b.length; _i++) { + var decl = _b[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 266: case 267: + case 268: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 260: case 261: + case 262: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 198: - case 249: + case 199: + case 250: var name = node.name; if (ts.isBindingPattern(name)) { - for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { - var el = _c[_b]; + for (var _c = 0, _d = name.elements; _c < _d.length; _c++) { + var el = _d[_c]; checkModuleAugmentationElement(el, isGlobalAugmentation); } break; } - case 252: - case 255: - case 251: case 253: case 256: + case 252: case 254: + case 257: + case 255: if (isGlobalAugmentation) { return; } @@ -64457,7 +66478,7 @@ var ts; if (symbol) { var reportError = !(symbol.flags & 33554432); if (!reportError) { - reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + reportError = !!((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.declarations) && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); } } break; @@ -64467,12 +66488,12 @@ var ts; switch (node.kind) { case 78: return node; - case 157: + case 158: do { node = node.left; } while (node.kind !== 78); return node; - case 201: + case 202: do { if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) { return node.name; @@ -64491,9 +66512,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 257 && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 297 && !inAmbientExternalModule) { - error(moduleName, node.kind === 267 ? + var inAmbientExternalModule = node.parent.kind === 258 && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 298 && !inAmbientExternalModule) { + error(moduleName, node.kind === 268 ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -64507,6 +66528,7 @@ var ts; return true; } function checkAliasSymbol(node) { + var _a; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { @@ -64515,20 +66537,20 @@ var ts; (symbol.flags & 788968 ? 788968 : 0) | (symbol.flags & 1920 ? 1920 : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 270 ? + var message = node.kind === 271 ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } if (compilerOptions.isolatedModules - && node.kind === 270 + && node.kind === 271 && !node.parent.parent.isTypeOnly && !(target.flags & 111551) && !(node.flags & 8388608)) { error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type); } - if (ts.isImportSpecifier(node) && ts.every(target.declarations, function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728); })) { - errorOrSuggestion(false, node.name, ts.Diagnostics._0_is_deprecated, symbol.escapedName); + if (ts.isImportSpecifier(node) && ((_a = target.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728); }))) { + addDeprecatedSuggestion(node.name, target.declarations, symbol.escapedName); } } } @@ -64536,7 +66558,7 @@ var ts; checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkAliasSymbol(node); - if (node.kind === 265 && + if (node.kind === 266 && ts.idText(node.propertyName || node.name) === "default" && compilerOptions.esModuleInterop && moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) { @@ -64557,7 +66579,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 263) { + if (importClause.namedBindings.kind === 264) { checkImportBinding(importClause.namedBindings); if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015 && compilerOptions.esModuleInterop) { checkExternalEmitHelpers(node, 65536); @@ -64583,7 +66605,7 @@ var ts; if (ts.hasSyntacticModifier(node, 1)) { markExportAsReferenced(node); } - if (node.moduleReference.kind !== 272) { + if (node.moduleReference.kind !== 273) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { if (target.flags & 111551) { @@ -64621,10 +66643,10 @@ var ts; if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) { ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 257 && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 257 && + var inAmbientExternalModule = node.parent.kind === 258 && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 258 && !node.moduleSpecifier && node.flags & 8388608; - if (node.parent.kind !== 297 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + if (node.parent.kind !== 298 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -64651,14 +66673,14 @@ var ts; } function checkGrammarExportDeclaration(node) { var _a; - var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 268; + var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 269; if (isTypeOnlyExportStar) { grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type); } return !isTypeOnlyExportStar; } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 297 || node.parent.kind === 257 || node.parent.kind === 256; + var isInAppropriateContext = node.parent.kind === 298 || node.parent.kind === 258 || node.parent.kind === 257; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -64706,7 +66728,7 @@ var ts; if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; var symbol = resolveName(exportedName, exportedName.escapedText, 111551 | 788968 | 1920 | 2097152, undefined, undefined, true); - if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { @@ -64727,11 +66749,14 @@ var ts; } } function checkExportAssignment(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + var illegalContextMessage = node.isExportEquals + ? ts.Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration + : ts.Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration; + if (checkGrammarModuleElementContext(node, illegalContextMessage)) { return; } - var container = node.parent.kind === 297 ? node.parent : node.parent.parent; - if (container.kind === 256 && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 298 ? node.parent : node.parent.parent; + if (container.kind === 257 && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -64786,7 +66811,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { + if (declaration && !isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -64805,10 +66830,12 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + if (!isDuplicatedCommonJSExport(declarations)) { + for (var _i = 0, _b = declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } } } } @@ -64817,6 +66844,11 @@ var ts; links.exportsChecked = true; } } + function isDuplicatedCommonJSExport(declarations) { + return declarations + && declarations.length > 1 + && declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && (ts.isExportsIdentifier(d.expression) || ts.isModuleExportsAccessExpression(d.expression)); }); + } function checkSourceElement(node) { if (node) { var saveCurrentNode = currentNode; @@ -64836,170 +66868,170 @@ var ts; var kind = node.kind; if (cancellationToken) { switch (kind) { - case 256: - case 252: + case 257: case 253: - case 251: + case 254: + case 252: cancellationToken.throwIfCancellationRequested(); } } - if (kind >= 232 && kind <= 248 && node.flowNode && !isReachableFlowNode(node.flowNode)) { + if (kind >= 233 && kind <= 249 && node.flowNode && !isReachableFlowNode(node.flowNode)) { errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected); } switch (kind) { - case 159: - return checkTypeParameter(node); case 160: + return checkTypeParameter(node); + case 161: return checkParameter(node); - case 163: + case 164: return checkPropertyDeclaration(node); - case 162: + case 163: return checkPropertySignature(node); + case 176: case 175: - case 174: - case 169: case 170: case 171: + case 172: return checkSignatureDeclaration(node); + case 166: case 165: - case 164: return checkMethodDeclaration(node); - case 166: - return checkConstructorDeclaration(node); case 167: + return checkConstructorDeclaration(node); case 168: + case 169: return checkAccessorDeclaration(node); - case 173: + case 174: return checkTypeReferenceNode(node); - case 172: + case 173: return checkTypePredicate(node); - case 176: - return checkTypeQuery(node); case 177: - return checkTypeLiteral(node); + return checkTypeQuery(node); case 178: - return checkArrayType(node); + return checkTypeLiteral(node); case 179: + return checkArrayType(node); + case 180: return checkTupleType(node); - case 182: case 183: + case 184: return checkUnionOrIntersectionType(node); - case 186: - case 180: + case 187: case 181: + case 182: return checkSourceElement(node.type); - case 187: - return checkThisType(node); case 188: + return checkThisType(node); + case 189: return checkTypeOperator(node); - case 184: - return checkConditionalType(node); case 185: + return checkConditionalType(node); + case 186: return checkInferType(node); - case 193: + case 194: return checkTemplateLiteralType(node); - case 195: + case 196: return checkImportType(node); - case 192: + case 193: return checkNamedTupleMember(node); - case 315: + case 318: return checkJSDocAugmentsTag(node); - case 316: + case 319: return checkJSDocImplementsTag(node); - case 331: - case 324: - case 325: + case 335: + case 328: + case 329: return checkJSDocTypeAliasTag(node); - case 330: + case 334: return checkJSDocTemplateTag(node); - case 329: + case 333: return checkJSDocTypeTag(node); - case 326: + case 330: return checkJSDocParameterTag(node); - case 333: + case 337: return checkJSDocPropertyTag(node); - case 308: + case 309: checkJSDocFunctionType(node); + case 307: case 306: - case 305: - case 303: case 304: - case 312: + case 305: + case 314: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 309: + case 310: checkJSDocVariadicType(node); return; - case 301: + case 302: return checkSourceElement(node.type); - case 189: - return checkIndexedAccessType(node); case 190: + return checkIndexedAccessType(node); + case 191: return checkMappedType(node); - case 251: + case 252: return checkFunctionDeclaration(node); - case 230: - case 257: + case 231: + case 258: return checkBlock(node); - case 232: - return checkVariableStatement(node); case 233: - return checkExpressionStatement(node); + return checkVariableStatement(node); case 234: - return checkIfStatement(node); + return checkExpressionStatement(node); case 235: - return checkDoStatement(node); + return checkIfStatement(node); case 236: - return checkWhileStatement(node); + return checkDoStatement(node); case 237: - return checkForStatement(node); + return checkWhileStatement(node); case 238: - return checkForInStatement(node); + return checkForStatement(node); case 239: - return checkForOfStatement(node); + return checkForInStatement(node); case 240: + return checkForOfStatement(node); case 241: - return checkBreakOrContinueStatement(node); case 242: - return checkReturnStatement(node); + return checkBreakOrContinueStatement(node); case 243: - return checkWithStatement(node); + return checkReturnStatement(node); case 244: - return checkSwitchStatement(node); + return checkWithStatement(node); case 245: - return checkLabeledStatement(node); + return checkSwitchStatement(node); case 246: - return checkThrowStatement(node); + return checkLabeledStatement(node); case 247: + return checkThrowStatement(node); + case 248: return checkTryStatement(node); - case 249: + case 250: return checkVariableDeclaration(node); - case 198: + case 199: return checkBindingElement(node); - case 252: - return checkClassDeclaration(node); case 253: - return checkInterfaceDeclaration(node); + return checkClassDeclaration(node); case 254: - return checkTypeAliasDeclaration(node); + return checkInterfaceDeclaration(node); case 255: - return checkEnumDeclaration(node); + return checkTypeAliasDeclaration(node); case 256: + return checkEnumDeclaration(node); + case 257: return checkModuleDeclaration(node); - case 261: + case 262: return checkImportDeclaration(node); - case 260: + case 261: return checkImportEqualsDeclaration(node); - case 267: + case 268: return checkExportDeclaration(node); - case 266: + case 267: return checkExportAssignment(node); - case 231: - case 248: + case 232: + case 249: checkGrammarStatementInAmbientContext(node); return; - case 271: + case 272: return checkMissingDeclaration(node); } } @@ -65041,8 +67073,11 @@ var ts; var paramTag = node.parent.parent; if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { var host_1 = ts.getHostSignatureFromJSDoc(paramTag); - if (host_1) { - var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var isCallbackTag = ts.isJSDocCallbackTag(paramTag.parent.parent); + if (host_1 || isCallbackTag) { + var lastParamDeclaration = isCallbackTag + ? ts.lastOrUndefined(paramTag.parent.parent.typeExpression.parameters) + : ts.lastOrUndefined(host_1.parameters); var symbol = ts.getParameterSymbolFromJSDoc(paramTag); if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { @@ -65071,48 +67106,48 @@ var ts; } } function checkDeferredNode(node) { - ts.tracing.push("check", "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check", "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; switch (node.kind) { - case 203: case 204: case 205: - case 161: - case 275: + case 206: + case 162: + case 276: resolveUntypedCall(node); break; - case 208: case 209: + case 210: + case 166: case 165: - case 164: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 167: case 168: + case 169: checkAccessorDeclaration(node); break; - case 221: + case 222: checkClassExpressionDeferred(node); break; - case 274: + case 275: checkJsxSelfClosingElementDeferred(node); break; - case 273: + case 274: checkJsxElementDeferred(node); break; } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkSourceFile(node) { - ts.tracing.push("check", "checkSourceFile", { path: node.path }, true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check", "checkSourceFile", { path: node.path }, true); ts.performance.mark("beforeCheck"); checkSourceFileWorker(node); ts.performance.mark("afterCheck"); ts.performance.measure("Check", "beforeCheck", "afterCheck"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function unusedIsError(kind, isAmbient) { if (isAmbient) { @@ -65139,7 +67174,7 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - ts.clear(potentialWeakMapCollisions); + ts.clear(potentialWeakMapSetCollisions); ts.forEach(node.statements, checkSourceElement); checkSourceElement(node.endOfFileToken); checkDeferredNodes(node); @@ -65169,9 +67204,9 @@ var ts; ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); ts.clear(potentialNewTargetCollisions); } - if (potentialWeakMapCollisions.length) { - ts.forEach(potentialWeakMapCollisions, checkWeakMapCollision); - ts.clear(potentialWeakMapCollisions); + if (potentialWeakMapSetCollisions.length) { + ts.forEach(potentialWeakMapSetCollisions, checkWeakMapSetCollision); + ts.clear(potentialWeakMapSetCollisions); } links.flags |= 1; } @@ -65229,27 +67264,27 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 297: - if (!ts.isExternalOrCommonJsModule(location)) + case 298: + if (!ts.isExternalModule(location)) break; - case 256: - copySymbols(getSymbolOfNode(location).exports, meaning & 2623475); + case 257: + copyLocallyVisibleExportSymbols(getSymbolOfNode(location).exports, meaning & 2623475); break; - case 255: + case 256: copySymbols(getSymbolOfNode(location).exports, meaning & 8); break; - case 221: + case 222: var className = location.name; if (className) { copySymbol(location.symbol, meaning); } - case 252: case 253: + case 254: if (!isStatic) { copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968); } break; - case 208: + case 209: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -65279,6 +67314,15 @@ var ts; }); } } + function copyLocallyVisibleExportSymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + if (!ts.getDeclarationOfKind(symbol, 271) && !ts.getDeclarationOfKind(symbol, 270)) { + copySymbol(symbol, meaning); + } + }); + } + } } function isTypeDeclarationName(name) { return name.kind === 78 && @@ -65287,44 +67331,44 @@ var ts; } function isTypeDeclaration(node) { switch (node.kind) { - case 159: - case 252: + case 160: case 253: case 254: case 255: - case 331: - case 324: - case 325: + case 256: + case 335: + case 328: + case 329: return true; - case 262: + case 263: return node.isTypeOnly; - case 265: - case 270: + case 266: + case 271: return node.parent.parent.isTypeOnly; default: return false; } } function isTypeReferenceIdentifier(node) { - while (node.parent.kind === 157) { + while (node.parent.kind === 158) { node = node.parent; } - return node.parent.kind === 173; + return node.parent.kind === 174; } function isHeritageClauseElementIdentifier(node) { - while (node.parent.kind === 201) { + while (node.parent.kind === 202) { node = node.parent; } - return node.parent.kind === 223; + return node.parent.kind === 224; } - function isJSDocEntryNameReference(node) { - while (node.parent.kind === 157) { + function getJSDocEntryNameReference(node) { + while (node.parent.kind === 158) { node = node.parent; } - while (node.parent.kind === 201) { + while (node.parent.kind === 202) { node = node.parent; } - return node.parent.kind === 302; + return ts.isJSDocNameReference(node.parent) ? node.parent : undefined; } function forEachEnclosingClass(node, callback) { var result; @@ -65352,13 +67396,13 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 157) { + while (nodeOnRightSide.parent.kind === 158) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 260) { + if (nodeOnRightSide.parent.kind === 261) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } - if (nodeOnRightSide.parent.kind === 266) { + if (nodeOnRightSide.parent.kind === 267) { return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; @@ -65384,7 +67428,7 @@ var ts; node = parent; parent = parent.parent; } - if (parent && parent.kind === 195 && parent.qualifier === node) { + if (parent && parent.kind === 196 && parent.qualifier === node) { return parent; } return undefined; @@ -65394,7 +67438,7 @@ var ts; return getSymbolOfNode(name.parent); } if (ts.isInJSFile(name) && - name.parent.kind === 201 && + name.parent.kind === 202 && name.parent === name.parent.parent.left) { if (!ts.isPrivateIdentifier(name)) { var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name); @@ -65403,14 +67447,14 @@ var ts; } } } - if (name.parent.kind === 266 && ts.isEntityNameExpression(name)) { + if (name.parent.kind === 267 && ts.isEntityNameExpression(name)) { var success = resolveEntityName(name, 111551 | 788968 | 1920 | 2097152, true); if (success && success !== unknownSymbol) { return success; } } else if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name) && isInRightSideOfImportOrExportAssignment(name)) { - var importEqualsDeclaration = ts.getAncestor(name, 260); + var importEqualsDeclaration = ts.getAncestor(name, 261); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(name, true); } @@ -65427,7 +67471,7 @@ var ts; } if (isHeritageClauseElementIdentifier(name)) { var meaning = 0; - if (name.parent.kind === 223) { + if (name.parent.kind === 224) { meaning = 788968; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) { meaning |= 111551; @@ -65442,10 +67486,10 @@ var ts; return entityNameSymbol; } } - if (name.parent.kind === 326) { + if (name.parent.kind === 330) { return ts.getParameterSymbolFromJSDoc(name.parent); } - if (name.parent.kind === 159 && name.parent.parent.kind === 330) { + if (name.parent.kind === 160 && name.parent.parent.kind === 334) { ts.Debug.assert(!ts.isInJSFile(name)); var typeParameter = ts.getTypeParameterFromJsDoc(name.parent); return typeParameter && typeParameter.symbol; @@ -65461,35 +67505,54 @@ var ts; } return resolveEntityName(name, 111551, false, true); } - else if (name.kind === 201 || name.kind === 157) { + else if (name.kind === 202 || name.kind === 158) { var links = getNodeLinks(name); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (name.kind === 201) { - checkPropertyAccessExpression(name); + if (name.kind === 202) { + checkPropertyAccessExpression(name, 0); } else { - checkQualifiedName(name); + checkQualifiedName(name, 0); } return links.resolvedSymbol; } } else if (isTypeReferenceIdentifier(name)) { - var meaning = name.parent.kind === 173 ? 788968 : 1920; + var meaning = name.parent.kind === 174 ? 788968 : 1920; return resolveEntityName(name, meaning, false, true); } - else if (isJSDocEntryNameReference(name)) { + var jsdocReference = getJSDocEntryNameReference(name); + if (jsdocReference || ts.isJSDocLink(name.parent)) { var meaning = 788968 | 1920 | 111551; - return resolveEntityName(name, meaning, false, true, ts.getHostSignatureFromJSDoc(name)); + var symbol = resolveEntityName(name, meaning, false, false, ts.getHostSignatureFromJSDoc(name)); + if (symbol) { + return symbol; + } + else if (ts.isQualifiedName(name) && ts.isIdentifier(name.left)) { + var links = getNodeLinks(name); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + checkQualifiedName(name, 0); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + var s = resolveEntityName(name.left, meaning, false); + if (s) { + var t = getDeclaredTypeOfSymbol(s); + return getPropertyOfType(t, name.right.escapedText); + } + } } - if (name.parent.kind === 172) { + if (name.parent.kind === 173) { return resolveEntityName(name, 1); } return undefined; } function getSymbolAtLocation(node, ignoreErrors) { - if (node.kind === 297) { + if (node.kind === 298) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } var parent = node.parent; @@ -65510,8 +67573,8 @@ var ts; if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfNameOrPropertyAccessExpression(node); } - else if (parent.kind === 198 && - grandParent.kind === 196 && + else if (parent.kind === 199 && + grandParent.kind === 197 && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); @@ -65523,8 +67586,8 @@ var ts; switch (node.kind) { case 78: case 79: - case 201: - case 157: + case 202: + case 158: return getSymbolOfNameOrPropertyAccessExpression(node); case 107: var container = ts.getThisContainer(node, false); @@ -65537,20 +67600,20 @@ var ts; if (ts.isInExpressionContext(node)) { return checkExpression(node).symbol; } - case 187: + case 188: return getTypeFromThisTypeNode(node).symbol; case 105: return checkExpression(node).symbol; case 132: var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 166) { + if (constructorDeclaration && constructorDeclaration.kind === 167) { return constructorDeclaration.parent.symbol; } return undefined; case 10: case 14: if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 261 || node.parent.kind === 267) && node.parent.moduleSpecifier === node) || + ((node.parent.kind === 262 || node.parent.kind === 268) && node.parent.moduleSpecifier === node) || ((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, ignoreErrors); @@ -65570,7 +67633,7 @@ var ts; case 38: case 83: return getSymbolOfNode(node.parent); - case 195: + case 196: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined; case 92: return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined; @@ -65579,7 +67642,7 @@ var ts; } } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 289) { + if (location && location.kind === 290) { return resolveEntityName(location.name, 111551 | 2097152); } return undefined; @@ -65646,20 +67709,20 @@ var ts; return errorType; } function getTypeOfAssignmentPattern(expr) { - ts.Debug.assert(expr.kind === 200 || expr.kind === 199); - if (expr.parent.kind === 239) { + ts.Debug.assert(expr.kind === 201 || expr.kind === 200); + if (expr.parent.kind === 240) { var iteratedType = checkRightHandSideOfForOf(expr.parent); return checkDestructuringAssignment(expr, iteratedType || errorType); } - if (expr.parent.kind === 216) { + if (expr.parent.kind === 217) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || errorType); } - if (expr.parent.kind === 288) { - var node_2 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); - var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_2) || errorType; - var propertyIndex = ts.indexOfNode(node_2.properties, expr.parent); - return checkObjectLiteralDestructuringPropertyAssignment(node_2, typeOfParentObjectLiteral, propertyIndex); + if (expr.parent.kind === 289) { + var node_3 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); + var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_3) || errorType; + var propertyIndex = ts.indexOfNode(node_3.properties, expr.parent); + return checkObjectLiteralDestructuringPropertyAssignment(node_3, typeOfParentObjectLiteral, propertyIndex); } var node = ts.cast(expr.parent, ts.isArrayLiteralExpression); var typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType; @@ -65690,7 +67753,7 @@ var ts; case 8: case 10: return getLiteralType(name.text); - case 158: + case 159: var nameType = checkComputedPropertyName(name); return isTypeAssignableToKind(nameType, 12288) ? nameType : stringType; default: @@ -65776,6 +67839,7 @@ var ts; return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name; } function getReferencedExportContainer(nodeIn, prefixLocals) { + var _a; var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node, isNameOfModuleOrEnumDeclaration(node)); @@ -65789,7 +67853,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 297) { + if (parentSymbol_1.flags & 512 && ((_a = parentSymbol_1.valueDeclaration) === null || _a === void 0 ? void 0 : _a.kind) === 298) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); var symbolIsUmdExport = symbolFile !== referenceFile; @@ -65814,11 +67878,12 @@ var ts; return undefined; } function isSymbolOfDestructuredElementOfCatchBinding(symbol) { - return ts.isBindingElement(symbol.valueDeclaration) - && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 287; + return symbol.valueDeclaration + && ts.isBindingElement(symbol.valueDeclaration) + && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 288; } function isSymbolOfDeclarationWithCollidingName(symbol) { - if (symbol.flags & 418 && !ts.isSourceFile(symbol.valueDeclaration)) { + if (symbol.flags & 418 && symbol.valueDeclaration && !ts.isSourceFile(symbol.valueDeclaration)) { var links = getSymbolLinks(symbol); if (links.isDeclarationWithCollidingName === undefined) { var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); @@ -65830,7 +67895,7 @@ var ts; else if (nodeLinks_1.flags & 262144) { var isDeclaredInLoop = nodeLinks_1.flags & 524288; var inLoopInitializer = ts.isIterationStatement(container, false); - var inLoopBodyBlock = container.kind === 230 && ts.isIterationStatement(container.parent, false); + var inLoopBodyBlock = container.kind === 231 && ts.isIterationStatement(container.parent, false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -65866,19 +67931,19 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 260: + case 261: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 262: case 263: - case 265: - case 270: + case 264: + case 266: + case 271: var symbol = getSymbolOfNode(node) || unknownSymbol; return isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol); - case 267: + case 268: var exportClause = node.exportClause; return !!exportClause && (ts.isNamespaceExport(exportClause) || ts.some(exportClause.elements, isValueAliasDeclaration)); - case 266: + case 267: return node.expression && node.expression.kind === 78 ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; @@ -65887,7 +67952,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 297 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 298 || !ts.isInternalModuleImportEqualsDeclaration(node)) { return false; } var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); @@ -65899,7 +67964,7 @@ var ts; return true; } return !!(target.flags & 111551) && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; @@ -65907,13 +67972,14 @@ var ts; function isReferencedAliasDeclaration(node, checkChildren) { if (isAliasSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); - if (symbol && getSymbolLinks(symbol).referenced) { + var links = symbol && getSymbolLinks(symbol); + if (links === null || links === void 0 ? void 0 : links.referenced) { return true; } var target = getSymbolLinks(symbol).target; if (target && ts.getEffectiveModifierFlags(node) & 1 && target.flags & 111551 && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { return true; } } @@ -65938,13 +68004,13 @@ var ts; !isOptionalParameter(parameter) && !ts.isJSDocParameterTag(parameter) && !!parameter.initializer && - !ts.hasSyntacticModifier(parameter, 92); + !ts.hasSyntacticModifier(parameter, 16476); } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && - ts.hasSyntacticModifier(parameter, 92); + ts.hasSyntacticModifier(parameter, 16476); } function isOptionalUninitializedParameter(parameter) { return !!strictNullChecks && @@ -65979,15 +68045,15 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 291: - case 201: + case 292: case 202: + case 203: return true; } return false; } function getConstantValue(node) { - if (node.kind === 291) { + if (node.kind === 292) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -66132,8 +68198,7 @@ var ts; } function isLiteralConstDeclaration(node) { if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 2944) && isFreshLiteralType(type); + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } @@ -66245,12 +68310,12 @@ var ts; getJsxFragmentFactoryEntity: getJsxFragmentFactoryEntity, getAllAccessorDeclarations: function (accessor) { accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); - var otherKind = accessor.kind === 168 ? 167 : 168; + var otherKind = accessor.kind === 169 ? 168 : 169; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; - var setAccessor = accessor.kind === 168 ? accessor : otherAccessor; - var getAccessor = accessor.kind === 167 ? accessor : otherAccessor; + var setAccessor = accessor.kind === 169 ? accessor : otherAccessor; + var getAccessor = accessor.kind === 168 ? accessor : otherAccessor; return { firstAccessor: firstAccessor, secondAccessor: secondAccessor, @@ -66266,7 +68331,7 @@ var ts; }, getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) { var n = ts.getParseTreeNode(node); - ts.Debug.assert(n && n.kind === 297, "Non-sourcefile node passed into getDeclarationsForSourceFile"); + ts.Debug.assert(n && n.kind === 298, "Non-sourcefile node passed into getDeclarationsForSourceFile"); var sym = getSymbolOfNode(node); if (!sym) { return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled); @@ -66289,11 +68354,13 @@ var ts; var s = _a[_i]; if (s.mergeId) { var merged = getMergedSymbol(s); - for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { - var d = _c[_b]; - var declFile = ts.getSourceFileOfNode(d); - if (declFile === importTarget) { - return true; + if (merged.declarations) { + for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declFile = ts.getSourceFileOfNode(d); + if (declFile === importTarget) { + return true; + } } } } @@ -66301,24 +68368,21 @@ var ts; return false; } function isInHeritageClause(node) { - return node.parent && node.parent.kind === 223 && node.parent.parent && node.parent.parent.kind === 286; + return node.parent && node.parent.kind === 224 && node.parent.parent && node.parent.parent.kind === 287; } function getTypeReferenceDirectivesForEntityName(node) { if (!fileToDirective) { return undefined; } var meaning = 788968 | 1920; - if ((node.kind === 78 && isInTypeQuery(node)) || (node.kind === 201 && !isInHeritageClause(node))) { + if ((node.kind === 78 && isInTypeQuery(node)) || (node.kind === 202 && !isInHeritageClause(node))) { meaning = 111551 | 1048576; } var symbol = resolveEntityName(node, meaning, true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } function getTypeReferenceDirectivesForSymbol(symbol, meaning) { - if (!fileToDirective) { - return undefined; - } - if (!isSymbolFromTypeDeclarationFile(symbol)) { + if (!fileToDirective || !isSymbolFromTypeDeclarationFile(symbol)) { return undefined; } var typeReferenceDirectives; @@ -66351,7 +68415,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 297 && current.flags & 512) { + if (current.valueDeclaration && current.valueDeclaration.kind === 298 && current.flags & 512) { return false; } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -66378,12 +68442,12 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = declaration.kind === 256 ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 257 ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, undefined); if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 297); + return ts.getDeclarationOfKind(moduleSymbol, 298); } function initializeTypeChecker() { for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { @@ -66399,7 +68463,7 @@ var ts; } if (!ts.isExternalOrCommonJsModule(file)) { var fileGlobalThisSymbol = file.locals.get("globalThis"); - if (fileGlobalThisSymbol) { + if (fileGlobalThisSymbol === null || fileGlobalThisSymbol === void 0 ? void 0 : fileGlobalThisSymbol.declarations) { for (var _d = 0, _e = fileGlobalThisSymbol.declarations; _d < _e.length; _d++) { var declaration = _e[_d]; diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis")); @@ -66507,6 +68571,16 @@ var ts; if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name); } + else if (helper & 524288) { + if (!ts.some(getSignaturesOfSymbol(symbol), function (signature) { return getParameterCount(signature) > 3; })) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name, 4); + } + } + else if (helper & 1048576) { + if (!ts.some(getSignaturesOfSymbol(symbol), function (signature) { return getParameterCount(signature) > 4; })) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name, 5); + } + } } } } @@ -66555,14 +68629,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { - if (node.kind === 165 && !ts.nodeIsPresent(node.body)) { + if (node.kind === 166 && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 167 || node.kind === 168) { + else if (node.kind === 168 || node.kind === 169) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -66575,24 +68649,40 @@ var ts; if (quickResult !== undefined) { return quickResult; } - var lastStatic, lastDeclare, lastAsync, lastReadonly; + var lastStatic, lastDeclare, lastAsync, lastReadonly, lastOverride; var flags = 0; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; if (modifier.kind !== 142) { - if (node.kind === 162 || node.kind === 164) { + if (node.kind === 163 || node.kind === 165) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 171) { + if (node.kind === 172 && (modifier.kind !== 123 || !ts.isClassLike(node.parent))) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { case 84: - if (node.kind !== 255) { + if (node.kind !== 256) { return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(84)); } break; + case 156: + if (flags & 16384) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "override"); + } + else if (flags & 2) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare"); + } + else if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly"); + } + else if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "async"); + } + flags |= 16384; + lastOverride = modifier; + break; case 122: case 121: case 120: @@ -66600,6 +68690,9 @@ var ts; if (flags & 28) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } + else if (flags & 16384) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "override"); + } else if (flags & 32) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } @@ -66609,7 +68702,7 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 257 || node.parent.kind === 297) { + else if (node.parent.kind === 258 || node.parent.kind === 298) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128) { @@ -66620,7 +68713,7 @@ var ts; return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); } } - else if (ts.isPrivateIdentifierPropertyDeclaration(node)) { + else if (ts.isPrivateIdentifierClassElementDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier); } flags |= ts.modifierToFlag(modifier.kind); @@ -66635,17 +68728,17 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 257 || node.parent.kind === 297) { + else if (node.parent.kind === 258 || node.parent.kind === 298) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 160) { + else if (node.kind === 161) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - else if (ts.isPrivateIdentifierPropertyDeclaration(node)) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "static"); + else if (flags & 16384) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "override"); } flags |= 32; lastStatic = modifier; @@ -66654,7 +68747,7 @@ var ts; if (flags & 64) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 163 && node.kind !== 162 && node.kind !== 171 && node.kind !== 160) { + else if (node.kind !== 164 && node.kind !== 163 && node.kind !== 172 && node.kind !== 161) { return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64; @@ -66676,14 +68769,14 @@ var ts; else if (ts.isClassLike(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "export"); } - else if (node.kind === 160) { + else if (node.kind === 161) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1; break; case 87: - var container = node.parent.kind === 297 ? node.parent : node.parent.parent; - if (container.kind === 256 && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 298 ? node.parent : node.parent.parent; + if (container.kind === 257 && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512; @@ -66695,16 +68788,19 @@ var ts; else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } + else if (flags & 16384) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override"); + } else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare"); } - else if (node.kind === 160) { + else if (node.kind === 161) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if ((node.parent.flags & 8388608) && node.parent.kind === 257) { + else if ((node.parent.flags & 8388608) && node.parent.kind === 258) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } - else if (ts.isPrivateIdentifierPropertyDeclaration(node)) { + else if (ts.isPrivateIdentifierClassElementDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare"); } flags |= 2; @@ -66714,15 +68810,15 @@ var ts; if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 252 && - node.kind !== 175) { - if (node.kind !== 165 && - node.kind !== 163 && - node.kind !== 167 && - node.kind !== 168) { + if (node.kind !== 253 && + node.kind !== 176) { + if (node.kind !== 166 && + node.kind !== 164 && + node.kind !== 168 && + node.kind !== 169) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 252 && ts.hasSyntacticModifier(node.parent, 128))) { + if (!(node.parent.kind === 253 && ts.hasSyntacticModifier(node.parent, 128))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32) { @@ -66734,6 +68830,9 @@ var ts; if (flags & 256 && lastAsync) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); } + if (flags & 16384) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override"); + } } if (ts.isNamedDeclaration(node) && node.name.kind === 79) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract"); @@ -66747,7 +68846,7 @@ var ts; else if (flags & 2 || node.parent.flags & 8388608) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 160) { + else if (node.kind === 161) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } if (flags & 128) { @@ -66758,13 +68857,16 @@ var ts; break; } } - if (node.kind === 166) { + if (node.kind === 167) { if (flags & 32) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } if (flags & 128) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); } + if (flags & 16384) { + return grammarErrorOnNode(lastOverride, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); + } else if (flags & 256) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } @@ -66773,13 +68875,13 @@ var ts; } return false; } - else if ((node.kind === 261 || node.kind === 260) && flags & 2) { + else if ((node.kind === 262 || node.kind === 261) && flags & 2) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 160 && (flags & 92) && ts.isBindingPattern(node.name)) { + else if (node.kind === 161 && (flags & 16476) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 160 && (flags & 92) && node.dotDotDotToken) { + else if (node.kind === 161 && (flags & 16476) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256) { @@ -66796,38 +68898,38 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 167: case 168: - case 166: + case 169: + case 167: + case 164: case 163: - case 162: + case 166: case 165: - case 164: - case 171: - case 256: + case 172: + case 257: + case 262: case 261: - case 260: + case 268: case 267: - case 266: - case 208: case 209: - case 160: + case 210: + case 161: return false; default: - if (node.parent.kind === 257 || node.parent.kind === 297) { + if (node.parent.kind === 258 || node.parent.kind === 298) { return false; } switch (node.kind) { - case 251: - return nodeHasAnyModifiersExcept(node, 129); case 252: - case 175: - return nodeHasAnyModifiersExcept(node, 125); + return nodeHasAnyModifiersExcept(node, 129); case 253: - case 232: + case 176: + return nodeHasAnyModifiersExcept(node, 125); case 254: - return true; + case 233: case 255: + return true; + case 256: return nodeHasAnyModifiersExcept(node, 84); default: ts.Debug.fail(); @@ -66839,10 +68941,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 165: - case 251: - case 208: + case 166: + case 252: case 209: + case 210: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -67001,7 +69103,7 @@ var ts; if (args) { for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { var arg = args_4[_i]; - if (arg.kind === 222) { + if (arg.kind === 223) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -67075,20 +69177,20 @@ var ts; return false; } function checkGrammarComputedPropertyName(node) { - if (node.kind !== 158) { + if (node.kind !== 159) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 216 && computedPropertyName.expression.operatorToken.kind === 27) { + if (computedPropertyName.expression.kind === 217 && computedPropertyName.expression.operatorToken.kind === 27) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 251 || - node.kind === 208 || - node.kind === 165); + ts.Debug.assert(node.kind === 252 || + node.kind === 209 || + node.kind === 166); if (node.flags & 8388608) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -67107,7 +69209,7 @@ var ts; var seen = new ts.Map(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 290) { + if (prop.kind === 291) { if (inDestructuring) { var expression = ts.skipParentheses(prop.expression); if (ts.isArrayLiteralExpression(expression) || ts.isObjectLiteralExpression(expression)) { @@ -67117,41 +69219,41 @@ var ts; continue; } var name = prop.name; - if (name.kind === 158) { + if (name.kind === 159) { checkGrammarComputedPropertyName(name); } - if (prop.kind === 289 && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 290 && !inDestructuring && prop.objectAssignmentInitializer) { return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern); } if (name.kind === 79) { - return grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); } if (prop.modifiers) { for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; - if (mod.kind !== 129 || prop.kind !== 165) { + if (mod.kind !== 129 || prop.kind !== 166) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } } var currentKind = void 0; switch (prop.kind) { - case 289: + case 290: checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); - case 288: + case 289: checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8) { checkGrammarNumericLiteral(name); } currentKind = 4; break; - case 165: + case 166: currentKind = 8; break; - case 167: + case 168: currentKind = 1; break; - case 168: + case 169: currentKind = 2; break; default: @@ -67186,11 +69288,12 @@ var ts; } } function checkGrammarJsxElement(node) { + checkGrammarJsxName(node.tagName); checkGrammarTypeArguments(node, node.typeArguments); var seen = new ts.Map(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 282) { + if (attr.kind === 283) { continue; } var name = attr.name, initializer = attr.initializer; @@ -67200,11 +69303,32 @@ var ts; else { return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - if (initializer && initializer.kind === 283 && !initializer.expression) { + if (initializer && initializer.kind === 284 && !initializer.expression) { return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } } + function checkGrammarJsxName(node) { + if (ts.isPropertyAccessExpression(node)) { + var propName = node; + do { + var check_1 = checkGrammarJsxNestedIdentifier(propName.name); + if (check_1) { + return check_1; + } + propName = propName.expression; + } while (ts.isPropertyAccessExpression(propName)); + var check = checkGrammarJsxNestedIdentifier(propName); + if (check) { + return check; + } + } + function checkGrammarJsxNestedIdentifier(name) { + if (ts.isIdentifier(name) && ts.idText(name).indexOf(":") !== -1) { + return grammarErrorOnNode(name, ts.Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names); + } + } + } function checkGrammarJsxExpression(node) { if (node.expression && ts.isCommaSequence(node.expression)) { return grammarErrorOnNode(node.expression, ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array); @@ -67214,24 +69338,36 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 239 && forInOrOfStatement.awaitModifier) { - if ((forInOrOfStatement.flags & 32768) === 0) { + if (forInOrOfStatement.kind === 240 && forInOrOfStatement.awaitModifier) { + if (!(forInOrOfStatement.flags & 32768)) { var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement); - if (!hasParseDiagnostics(sourceFile)) { - var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); - var func = ts.getContainingFunction(forInOrOfStatement); - if (func && func.kind !== 166) { - ts.Debug.assert((ts.getFunctionFlags(func) & 2) === 0, "Enclosing function should never be an async function."); - var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); - ts.addRelatedInfo(diagnostic, relatedInfo); - } - diagnostics.add(diagnostic); - return true; + if (ts.isInTopLevelContext(forInOrOfStatement)) { + if (!hasParseDiagnostics(sourceFile)) { + if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module)); + } + if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher)); + } + } + } + else { + if (!hasParseDiagnostics(sourceFile)) { + var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); + var func = ts.getContainingFunction(forInOrOfStatement); + if (func && func.kind !== 167) { + ts.Debug.assert((ts.getFunctionFlags(func) & 2) === 0, "Enclosing function should never be an async function."); + var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); + ts.addRelatedInfo(diagnostic, relatedInfo); + } + diagnostics.add(diagnostic); + return true; + } } return false; } } - if (forInOrOfStatement.initializer.kind === 250) { + if (forInOrOfStatement.initializer.kind === 251) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -67239,20 +69375,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 238 + var diagnostic = forInOrOfStatement.kind === 239 ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 238 + var diagnostic = forInOrOfStatement.kind === 239 ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 238 + var diagnostic = forInOrOfStatement.kind === 239 ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -67262,26 +69398,34 @@ var ts; return false; } function checkGrammarAccessor(accessor) { - if (!(accessor.flags & 8388608)) { + if (!(accessor.flags & 8388608) && (accessor.parent.kind !== 178) && (accessor.parent.kind !== 254)) { if (languageVersion < 1) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } + if (languageVersion < 2 && ts.isPrivateIdentifier(accessor.name)) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } if (accessor.body === undefined && !ts.hasSyntacticModifier(accessor, 128)) { return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } - if (accessor.body && ts.hasSyntacticModifier(accessor, 128)) { - return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + if (accessor.body) { + if (ts.hasSyntacticModifier(accessor, 128)) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + if (accessor.parent.kind === 178 || accessor.parent.kind === 254) { + return grammarErrorOnNode(accessor.body, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } } if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, accessor.kind === 167 ? + return grammarErrorOnNode(accessor.name, accessor.kind === 168 ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - if (accessor.kind === 168) { + if (accessor.kind === 169) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -67299,10 +69443,10 @@ var ts; return false; } function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 167 ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 168 ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 167 ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 168 ? 1 : 2)) { return ts.getThisParameter(accessor); } } @@ -67319,7 +69463,7 @@ var ts; } } switch (parent.kind) { - case 249: + case 250: var decl = parent; if (decl.name.kind !== 78) { return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); @@ -67331,13 +69475,13 @@ var ts; return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); } break; - case 163: + case 164: if (!ts.hasSyntacticModifier(parent, 32) || !ts.hasEffectiveModifier(parent, 64)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; - case 162: + case 163: if (!ts.hasSyntacticModifier(parent, 64)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } @@ -67347,7 +69491,7 @@ var ts; } } else if (node.operator === 142) { - if (node.type.kind !== 178 && node.type.kind !== 179) { + if (node.type.kind !== 179 && node.type.kind !== 180) { return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(148)); } } @@ -67361,8 +69505,8 @@ var ts; if (checkGrammarFunctionLikeDeclaration(node)) { return true; } - if (node.kind === 165) { - if (node.parent.kind === 200) { + if (node.kind === 166) { + if (node.parent.kind === 201) { if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 129)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } @@ -67381,17 +69525,20 @@ var ts; } } if (ts.isClassLike(node.parent)) { + if (languageVersion < 2 && ts.isPrivateIdentifier(node.name)) { + return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } if (node.flags & 8388608) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.kind === 165 && !node.body) { + else if (node.kind === 166 && !node.body) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 253) { + else if (node.parent.kind === 254) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 177) { + else if (node.parent.kind === 178) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } @@ -67402,9 +69549,9 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 245: + case 246: if (node.label && current.label.escapedText === node.label.escapedText) { - var isMisplacedContinueLabel = node.kind === 240 + var isMisplacedContinueLabel = node.kind === 241 && !ts.isIterationStatement(current.statement, true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -67412,8 +69559,8 @@ var ts; return false; } break; - case 244: - if (node.kind === 241 && !node.label) { + case 245: + if (node.kind === 242 && !node.label) { return false; } break; @@ -67426,13 +69573,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 241 + var message = node.kind === 242 ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 241 + var message = node.kind === 242 ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -67455,12 +69602,12 @@ var ts; } function isStringOrNumberLiteralExpression(expr) { return ts.isStringOrNumericLiteralLike(expr) || - expr.kind === 214 && expr.operator === 40 && + expr.kind === 215 && expr.operator === 40 && expr.operand.kind === 8; } function isBigIntLiteralExpression(expr) { return expr.kind === 9 || - expr.kind === 214 && expr.operator === 40 && + expr.kind === 215 && expr.operator === 40 && expr.operand.kind === 9; } function isSimpleLiteralEnumReference(expr) { @@ -67491,7 +69638,7 @@ var ts; } } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 238 && node.parent.parent.kind !== 239) { + if (node.parent.parent.kind !== 239 && node.parent.parent.kind !== 240) { if (node.flags & 8388608) { checkAmbientInitializer(node); } @@ -67504,7 +69651,7 @@ var ts; } } } - if (node.exclamationToken && (node.parent.parent.kind !== 232 || !node.type || node.initializer || node.flags & 8388608)) { + if (node.exclamationToken && (node.parent.parent.kind !== 233 || !node.type || node.initializer || node.flags & 8388608)) { var message = node.initializer ? ts.Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type @@ -67566,15 +69713,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 234: case 235: case 236: - case 243: case 237: + case 244: case 238: case 239: + case 240: return false; - case 245: + case 246: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -67659,14 +69806,14 @@ var ts; if (ts.isStringLiteral(node.name) && node.name.text === "constructor") { return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor); } - if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type)) { return true; } if (languageVersion < 2 && ts.isPrivateIdentifier(node.name)) { return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); } } - else if (node.parent.kind === 253) { + else if (node.parent.kind === 254) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -67674,7 +69821,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 177) { + else if (node.parent.kind === 178) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -67696,13 +69843,13 @@ var ts; } } function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 253 || - node.kind === 254 || + if (node.kind === 254 || + node.kind === 255 || + node.kind === 262 || node.kind === 261 || - node.kind === 260 || + node.kind === 268 || node.kind === 267 || - node.kind === 266 || - node.kind === 259 || + node.kind === 260 || ts.hasSyntacticModifier(node, 2 | 1 | 512)) { return false; } @@ -67711,7 +69858,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 232) { + if (ts.isDeclaration(decl) || decl.kind === 233) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -67728,7 +69875,7 @@ var ts; if (!links.hasReportedStatementInAmbientContext && (ts.isFunctionLike(node.parent) || ts.isAccessor(node.parent))) { return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); } - if (node.parent.kind === 230 || node.parent.kind === 257 || node.parent.kind === 297) { + if (node.parent.kind === 231 || node.parent.kind === 258 || node.parent.kind === 298) { var links_2 = getNodeLinks(node.parent); if (!links_2.hasReportedStatementInAmbientContext) { return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); @@ -67745,10 +69892,10 @@ var ts; if (languageVersion >= 1) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 191)) { + else if (ts.isChildOfNodeWithKind(node, 192)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 291)) { + else if (ts.isChildOfNodeWithKind(node, 292)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { @@ -67843,7 +69990,7 @@ var ts; } } function findBestTypeForObjectLiteral(source, unionTarget) { - if (ts.getObjectFlags(source) & 128 && forEachType(unionTarget, isArrayLikeType)) { + if (ts.getObjectFlags(source) & 128 && someType(unionTarget, isArrayLikeType)) { return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } @@ -67890,6 +70037,10 @@ var ts; } function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) { if (target.flags & 1048576 && source.flags & (2097152 | 524288)) { + var match = getMatchingUnionConstituentForType(target, source); + if (match) { + return match; + } var sourceProperties = getPropertiesOfType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); @@ -67906,31 +70057,18 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 251 && declaration.kind !== 165) || + return (declaration.kind !== 252 && declaration.kind !== 166) || !!declaration.body; } function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 265: - case 270: + case 266: + case 271: return ts.isIdentifier(name); default: return ts.isDeclarationName(name); } } - function isSomeImportDeclaration(decl) { - switch (decl.kind) { - case 262: - case 260: - case 263: - case 265: - return true; - case 78: - return decl.parent.kind === 265; - default: - return false; - } - } var JsxNames; (function (JsxNames) { JsxNames.JSX = "JSX"; @@ -67961,7 +70099,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); function visitNode(node, visitor, test, lift) { if (node === undefined || visitor === undefined) { return node; @@ -68116,6 +70253,21 @@ var ts; return updated; } ts.visitFunctionBody = visitFunctionBody; + function visitIterationBody(body, visitor, context) { + context.startBlockScope(); + var updated = visitNode(body, visitor, ts.isStatement, context.factory.liftToBlock); + var declarations = context.endBlockScope(); + if (ts.some(declarations)) { + if (ts.isBlock(updated)) { + declarations.push.apply(declarations, updated.statements); + return context.factory.updateBlock(updated, declarations); + } + declarations.push(updated); + return context.factory.createBlock(declarations); + } + return updated; + } + ts.visitIterationBody = visitIterationBody; function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor, nodeVisitor) { if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } if (nodeVisitor === void 0) { nodeVisitor = visitNode; } @@ -68123,282 +70275,416 @@ var ts; return undefined; } var kind = node.kind; - if ((kind > 0 && kind <= 156) || kind === 187) { + if ((kind > 0 && kind <= 157) || kind === 188) { return node; } var factory = context.factory; switch (kind) { case 78: - return factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); - case 157: - return factory.updateQualifiedName(node, nodeVisitor(node.left, visitor, ts.isEntityName), nodeVisitor(node.right, visitor, ts.isIdentifier)); + ts.Debug.type(node); + return factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNodeOrTypeParameterDeclaration)); case 158: - return factory.updateComputedPropertyName(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateQualifiedName(node, nodeVisitor(node.left, visitor, ts.isEntityName), nodeVisitor(node.right, visitor, ts.isIdentifier)); case 159: - return factory.updateTypeParameterDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateComputedPropertyName(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 160: - return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateTypeParameterDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode)); case 161: - return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 162: - return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 163: - return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 164: - return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isQuestionOrExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 165: - return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + ts.Debug.type(node); + return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 166: - return factory.updateConstructorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + ts.Debug.type(node); + return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 167: - return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + ts.Debug.type(node); + return factory.updateConstructorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 168: - return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + ts.Debug.type(node); + return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 169: - return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 170: - return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 171: - return factory.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 172: - return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor), nodeVisitor(node.parameterName, visitor), nodeVisitor(node.type, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 173: - return factory.updateTypeReferenceNode(node, nodeVisitor(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor, ts.isAssertsKeyword), nodeVisitor(node.parameterName, visitor, ts.isIdentifierOrThisTypeNode), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 174: - return factory.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateTypeReferenceNode(node, nodeVisitor(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 175: - return factory.updateConstructorTypeNode(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 176: - return factory.updateTypeQueryNode(node, nodeVisitor(node.exprName, visitor, ts.isEntityName)); + ts.Debug.type(node); + return factory.updateConstructorTypeNode(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 177: - return factory.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); + ts.Debug.type(node); + return factory.updateTypeQueryNode(node, nodeVisitor(node.exprName, visitor, ts.isEntityName)); case 178: - return factory.updateArrayTypeNode(node, nodeVisitor(node.elementType, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); case 179: - return factory.updateTupleTypeNode(node, nodesVisitor(node.elements, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateArrayTypeNode(node, nodeVisitor(node.elementType, visitor, ts.isTypeNode)); case 180: - return factory.updateOptionalTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateTupleTypeNode(node, nodesVisitor(node.elements, visitor, ts.isTypeNode)); case 181: - return factory.updateRestTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateOptionalTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); case 182: - return factory.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateRestTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); case 183: - return factory.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 184: - return factory.updateConditionalTypeNode(node, nodeVisitor(node.checkType, visitor, ts.isTypeNode), nodeVisitor(node.extendsType, visitor, ts.isTypeNode), nodeVisitor(node.trueType, visitor, ts.isTypeNode), nodeVisitor(node.falseType, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); case 185: + ts.Debug.type(node); + return factory.updateConditionalTypeNode(node, nodeVisitor(node.checkType, visitor, ts.isTypeNode), nodeVisitor(node.extendsType, visitor, ts.isTypeNode), nodeVisitor(node.trueType, visitor, ts.isTypeNode), nodeVisitor(node.falseType, visitor, ts.isTypeNode)); + case 186: + ts.Debug.type(node); return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); - case 195: + case 196: + ts.Debug.type(node); return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); - case 192: - return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); - case 186: + case 193: + ts.Debug.type(node); + return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isDotDotDotToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isQuestionToken), visitNode(node.type, visitor, ts.isTypeNode)); + case 187: + ts.Debug.type(node); return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 188: - return factory.updateTypeOperatorNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); case 189: - return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateTypeOperatorNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); case 190: - return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode)); case 191: + ts.Debug.type(node); + return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 192: + ts.Debug.type(node); return factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression)); - case 193: - return factory.updateTemplateLiteralType(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateLiteralTypeSpan)); case 194: + ts.Debug.type(node); + return factory.updateTemplateLiteralType(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateLiteralTypeSpan)); + case 195: + ts.Debug.type(node); return factory.updateTemplateLiteralTypeSpan(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); - case 196: - return factory.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); case 197: - return factory.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); + ts.Debug.type(node); + return factory.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); case 198: - return factory.updateBindingElement(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.propertyName, visitor, ts.isPropertyName), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.initializer, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); case 199: - return factory.updateArrayLiteralExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateBindingElement(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.propertyName, visitor, ts.isPropertyName), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 200: - return factory.updateObjectLiteralExpression(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); + ts.Debug.type(node); + return factory.updateArrayLiteralExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression)); case 201: + ts.Debug.type(node); + return factory.updateObjectLiteralExpression(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); + case 202: if (node.flags & 32) { - return factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier)); + ts.Debug.type(node); + return factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodeVisitor(node.name, visitor, ts.isMemberName)); } - return factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isIdentifierOrPrivateIdentifier)); - case 202: + ts.Debug.type(node); + return factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isMemberName)); + case 203: if (node.flags & 32) { - return factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); } + ts.Debug.type(node); return factory.updateElementAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); - case 203: + case 204: if (node.flags & 32) { - return factory.updateCallChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateCallChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); } + ts.Debug.type(node); return factory.updateCallExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 204: - return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); case 205: - return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); + ts.Debug.type(node); + return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); case 206: - return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); case 207: - return factory.updateParenthesizedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression)); case 208: - return factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + ts.Debug.type(node); + return factory.updateParenthesizedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 209: - return factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, ts.isToken), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + ts.Debug.type(node); + return factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 210: - return factory.updateDeleteExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, ts.isEqualsGreaterThanToken), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 211: - return factory.updateTypeOfExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateDeleteExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 212: - return factory.updateVoidExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateTypeOfExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 213: - return factory.updateAwaitExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateVoidExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 214: - return factory.updatePrefixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateAwaitExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 215: - return factory.updatePostfixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updatePrefixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression)); case 216: - return factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isToken), nodeVisitor(node.right, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updatePostfixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression)); case 217: - return factory.updateConditionalExpression(node, nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.whenTrue, visitor, ts.isExpression), nodeVisitor(node.colonToken, tokenVisitor, ts.isToken), nodeVisitor(node.whenFalse, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isBinaryOperatorToken), nodeVisitor(node.right, visitor, ts.isExpression)); case 218: - return factory.updateTemplateExpression(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); + ts.Debug.type(node); + return factory.updateConditionalExpression(node, nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.whenTrue, visitor, ts.isExpression), nodeVisitor(node.colonToken, tokenVisitor, ts.isColonToken), nodeVisitor(node.whenFalse, visitor, ts.isExpression)); case 219: - return factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.expression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateTemplateExpression(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); case 220: - return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.expression, visitor, ts.isExpression)); case 221: + ts.Debug.type(node); + return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + case 222: + ts.Debug.type(node); return factory.updateClassExpression(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 223: - return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 224: - return factory.updateAsExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.type, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); case 225: + ts.Debug.type(node); + return factory.updateAsExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 226: if (node.flags & 32) { + ts.Debug.type(node); return factory.updateNonNullChain(node, nodeVisitor(node.expression, visitor, ts.isExpression)); } + ts.Debug.type(node); return factory.updateNonNullExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 226: + case 227: + ts.Debug.type(node); return factory.updateMetaProperty(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 228: + case 229: + ts.Debug.type(node); return factory.updateTemplateSpan(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); - case 230: + case 231: + ts.Debug.type(node); return factory.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 232: - return factory.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.declarationList, visitor, ts.isVariableDeclarationList)); case 233: - return factory.updateExpressionStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.declarationList, visitor, ts.isVariableDeclarationList)); case 234: - return factory.updateIfStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.thenStatement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.elseStatement, visitor, ts.isStatement, factory.liftToBlock)); + ts.Debug.type(node); + return factory.updateExpressionStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 235: - return factory.updateDoStatement(node, nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.expression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateIfStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.thenStatement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.elseStatement, visitor, ts.isStatement, factory.liftToBlock)); case 236: - return factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + ts.Debug.type(node); + return factory.updateDoStatement(node, visitIterationBody(node.statement, visitor, context), nodeVisitor(node.expression, visitor, ts.isExpression)); case 237: - return factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.incrementor, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + ts.Debug.type(node); + return factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); case 238: - return factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + ts.Debug.type(node); + return factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.incrementor, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); case 239: - return factory.updateForOfStatement(node, nodeVisitor(node.awaitModifier, tokenVisitor, ts.isToken), nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + ts.Debug.type(node); + return factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); case 240: - return factory.updateContinueStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier)); + ts.Debug.type(node); + return factory.updateForOfStatement(node, nodeVisitor(node.awaitModifier, tokenVisitor, ts.isAwaitKeyword), nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); case 241: - return factory.updateBreakStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier)); + ts.Debug.type(node); + return factory.updateContinueStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier)); case 242: - return factory.updateReturnStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateBreakStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier)); case 243: - return factory.updateWithStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + ts.Debug.type(node); + return factory.updateReturnStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 244: - return factory.updateSwitchStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.caseBlock, visitor, ts.isCaseBlock)); + ts.Debug.type(node); + return factory.updateWithStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); case 245: - return factory.updateLabeledStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + ts.Debug.type(node); + return factory.updateSwitchStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.caseBlock, visitor, ts.isCaseBlock)); case 246: - return factory.updateThrowStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateLabeledStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); case 247: + ts.Debug.type(node); + return factory.updateThrowStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + case 248: + ts.Debug.type(node); return factory.updateTryStatement(node, nodeVisitor(node.tryBlock, visitor, ts.isBlock), nodeVisitor(node.catchClause, visitor, ts.isCatchClause), nodeVisitor(node.finallyBlock, visitor, ts.isBlock)); - case 249: - return factory.updateVariableDeclaration(node, nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 250: - return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); + ts.Debug.type(node); + return factory.updateVariableDeclaration(node, nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.exclamationToken, tokenVisitor, ts.isExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 251: - return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + ts.Debug.type(node); + return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); case 252: - return factory.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); + ts.Debug.type(node); + return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); case 253: - return factory.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); + ts.Debug.type(node); + return factory.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 254: - return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + ts.Debug.type(node); + return factory.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); case 255: - return factory.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); + ts.Debug.type(node); + return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); case 256: - return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.body, visitor, ts.isModuleBody)); + ts.Debug.type(node); + return factory.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); case 257: - return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + ts.Debug.type(node); + return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); case 258: - return factory.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); + ts.Debug.type(node); + return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 259: - return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); + ts.Debug.type(node); + return factory.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); case 260: - return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); + ts.Debug.type(node); + return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); case 261: - return factory.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); case 262: - return factory.updateImportClause(node, node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.namedBindings, visitor, ts.isNamedImportBindings)); + ts.Debug.type(node); + return factory.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression)); case 263: + ts.Debug.type(node); + return factory.updateImportClause(node, node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.namedBindings, visitor, ts.isNamedImportBindings)); + case 264: + ts.Debug.type(node); return factory.updateNamespaceImport(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 269: + case 270: + ts.Debug.type(node); return factory.updateNamespaceExport(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 264: - return factory.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); case 265: - return factory.updateImportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); + ts.Debug.type(node); + return factory.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); case 266: - return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateImportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); case 267: - return factory.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); case 268: + ts.Debug.type(node); + return factory.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression)); + case 269: + ts.Debug.type(node); return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); - case 270: + case 271: + ts.Debug.type(node); return factory.updateExportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 272: - return factory.updateExternalModuleReference(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 273: - return factory.updateJsxElement(node, nodeVisitor(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingElement, visitor, ts.isJsxClosingElement)); + ts.Debug.type(node); + return factory.updateExternalModuleReference(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 274: - return factory.updateJsxSelfClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes)); + ts.Debug.type(node); + return factory.updateJsxElement(node, nodeVisitor(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingElement, visitor, ts.isJsxClosingElement)); case 275: - return factory.updateJsxOpeningElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes)); + ts.Debug.type(node); + return factory.updateJsxSelfClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes)); case 276: - return factory.updateJsxClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression)); + ts.Debug.type(node); + return factory.updateJsxOpeningElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes)); case 277: + ts.Debug.type(node); + return factory.updateJsxClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression)); + case 278: + ts.Debug.type(node); return factory.updateJsxFragment(node, nodeVisitor(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingFragment, visitor, ts.isJsxClosingFragment)); - case 280: - return factory.updateJsxAttribute(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); case 281: - return factory.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); + ts.Debug.type(node); + return factory.updateJsxAttribute(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); case 282: - return factory.updateJsxSpreadAttribute(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); case 283: - return factory.updateJsxExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateJsxSpreadAttribute(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 284: - return factory.updateCaseClause(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); + ts.Debug.type(node); + return factory.updateJsxExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); case 285: - return factory.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); + ts.Debug.type(node); + return factory.updateCaseClause(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); case 286: - return factory.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); + ts.Debug.type(node); + return factory.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); case 287: - return factory.updateCatchClause(node, nodeVisitor(node.variableDeclaration, visitor, ts.isVariableDeclaration), nodeVisitor(node.block, visitor, ts.isBlock)); + ts.Debug.type(node); + return factory.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); case 288: - return factory.updatePropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateCatchClause(node, nodeVisitor(node.variableDeclaration, visitor, ts.isVariableDeclaration), nodeVisitor(node.block, visitor, ts.isBlock)); case 289: - return factory.updateShorthandPropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.objectAssignmentInitializer, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updatePropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression)); case 290: - return factory.updateSpreadAssignment(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateShorthandPropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.objectAssignmentInitializer, visitor, ts.isExpression)); case 291: + ts.Debug.type(node); + return factory.updateSpreadAssignment(node, nodeVisitor(node.expression, visitor, ts.isExpression)); + case 292: + ts.Debug.type(node); return factory.updateEnumMember(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 297: + case 298: + ts.Debug.type(node); return factory.updateSourceFile(node, visitLexicalEnvironment(node.statements, visitor, context)); - case 336: + case 340: + ts.Debug.type(node); return factory.updatePartiallyEmittedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 337: + case 341: + ts.Debug.type(node); return factory.updateCommaListExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; @@ -69021,7 +71307,7 @@ var ts; function chainBundle(context, transformSourceFile) { return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - return node.kind === 297 ? transformSourceFile(node) : transformBundle(node); + return node.kind === 298 ? transformSourceFile(node) : transformBundle(node); } function transformBundle(node) { return context.factory.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); @@ -69070,7 +71356,7 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 261: + case 262: externalImports.push(node); if (!hasImportStar && getImportNeedsImportStarHelper(node)) { hasImportStar = true; @@ -69079,12 +71365,12 @@ var ts; hasImportDefault = true; } break; - case 260: - if (node.moduleReference.kind === 272) { + case 261: + if (node.moduleReference.kind === 273) { externalImports.push(node); } break; - case 267: + case 268: if (node.moduleSpecifier) { if (!node.exportClause) { externalImports.push(node); @@ -69110,12 +71396,12 @@ var ts; addExportedNamesForExportDeclaration(node); } break; - case 266: + case 267: if (node.isExportEquals && !exportEquals) { exportEquals = node; } break; - case 232: + case 233: if (ts.hasSyntacticModifier(node, 1)) { for (var _b = 0, _c = node.declarationList.declarations; _b < _c.length; _b++) { var decl = _c[_b]; @@ -69123,7 +71409,7 @@ var ts; } } break; - case 251: + case 252: if (ts.hasSyntacticModifier(node, 1)) { if (ts.hasSyntacticModifier(node, 512)) { if (!hasExportDefault) { @@ -69141,7 +71427,7 @@ var ts; } } break; - case 252: + case 253: if (ts.hasSyntacticModifier(node, 1)) { if (ts.hasSyntacticModifier(node, 512)) { if (!hasExportDefault) { @@ -69222,8 +71508,7 @@ var ts; } ts.isSimpleCopiableExpression = isSimpleCopiableExpression; function isSimpleInlineableExpression(expression) { - return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression) || - ts.isWellKnownSymbolSyntactically(expression); + return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression); } ts.isSimpleInlineableExpression = isSimpleInlineableExpression; function isCompoundAssignment(kind) { @@ -69280,10 +71565,14 @@ var ts; && ts.hasStaticModifier(member) === isStatic; } function isInitializedProperty(member) { - return member.kind === 163 + return member.kind === 164 && member.initializer !== undefined; } ts.isInitializedProperty = isInitializedProperty; + function isNonStaticMethodOrAccessorWithPrivateName(member) { + return !ts.hasStaticModifier(member) && ts.isMethodOrAccessor(member) && ts.isPrivateIdentifier(member.name); + } + ts.isNonStaticMethodOrAccessorWithPrivateName = isNonStaticMethodOrAccessorWithPrivateName; })(ts || (ts = {})); var ts; (function (ts) { @@ -69485,8 +71774,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 - && !(element.transformFlags & (8192 | 16384)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (8192 | 16384)) + && !(element.transformFlags & (16384 | 32768)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (16384 | 32768)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor)); } @@ -69533,7 +71822,7 @@ var ts; for (var i = 0; i < numElements; i++) { var element = elements[i]; if (flattenContext.level >= 1) { - if (element.transformFlags & 16384 || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { + if (element.transformFlags & 32768 || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { flattenContext.hasTransformedPriorElement = true; var temp = flattenContext.context.factory.createTempVariable(undefined); if (flattenContext.hoistTempVariables) { @@ -69707,8 +71996,8 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(201); context.enableSubstitution(202); + context.enableSubstitution(203); var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; @@ -69721,14 +72010,14 @@ var ts; var applicableSubstitutions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - if (node.kind === 298) { + if (node.kind === 299) { return transformBundle(node); } return transformSourceFile(node); } function transformBundle(node) { return factory.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 300) { + if (prepend.kind === 301) { return ts.createUnparsedSourceFile(prepend, "js"); } return prepend; @@ -69761,16 +72050,16 @@ var ts; } function onBeforeVisitNode(node) { switch (node.kind) { - case 297: + case 298: + case 259: case 258: - case 257: - case 230: + case 231: currentLexicalScope = node; currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; + case 253: case 252: - case 251: if (ts.hasSyntacticModifier(node, 2)) { break; } @@ -69778,7 +72067,7 @@ var ts; recordEmittedDeclarationInScope(node); } else { - ts.Debug.assert(node.kind === 252 || ts.hasSyntacticModifier(node, 512)); + ts.Debug.assert(node.kind === 253 || ts.hasSyntacticModifier(node, 512)); } if (ts.isClassDeclaration(node)) { currentNameScope = node; @@ -69800,10 +72089,10 @@ var ts; } function sourceElementVisitorWorker(node) { switch (node.kind) { + case 262: case 261: - case 260: - case 266: case 267: + case 268: return visitElidableStatement(node); default: return visitorWorker(node); @@ -69818,13 +72107,13 @@ var ts; return node; } switch (node.kind) { - case 261: + case 262: return visitImportDeclaration(node); - case 260: + case 261: return visitImportEqualsDeclaration(node); - case 266: - return visitExportAssignment(node); case 267: + return visitExportAssignment(node); + case 268: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -69834,11 +72123,11 @@ var ts; return saveStateAndInvoke(node, namespaceElementVisitorWorker); } function namespaceElementVisitorWorker(node) { - if (node.kind === 267 || - node.kind === 261 || + if (node.kind === 268 || node.kind === 262 || - (node.kind === 260 && - node.moduleReference.kind === 272)) { + node.kind === 263 || + (node.kind === 261 && + node.moduleReference.kind === 273)) { return undefined; } else if (node.transformFlags & 1 || ts.hasSyntacticModifier(node, 1)) { @@ -69851,23 +72140,23 @@ var ts; } function classElementVisitorWorker(node) { switch (node.kind) { - case 166: + case 167: return visitConstructor(node); - case 163: + case 164: return visitPropertyDeclaration(node); - case 171: - case 167: + case 172: case 168: - case 165: + case 169: + case 166: return visitorWorker(node); - case 229: + case 230: return node; default: return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { - if (ts.modifierToFlag(node.kind) & 2270) { + if (ts.modifierToFlag(node.kind) & 18654) { return undefined; } else if (currentNamespace && node.kind === 92) { @@ -69890,13 +72179,13 @@ var ts; case 84: case 133: case 142: - case 178: case 179: case 180: case 181: - case 177: - case 172: - case 159: + case 182: + case 178: + case 173: + case 160: case 128: case 152: case 131: @@ -69905,79 +72194,79 @@ var ts; case 141: case 113: case 148: + case 176: case 175: + case 177: case 174: - case 176: - case 173: - case 182: case 183: case 184: - case 186: + case 185: case 187: case 188: case 189: case 190: case 191: - case 171: - case 161: - case 254: + case 192: + case 172: + case 162: + case 255: return undefined; - case 163: + case 164: return visitPropertyDeclaration(node); - case 259: + case 260: return undefined; - case 166: + case 167: return visitConstructor(node); - case 253: + case 254: return factory.createNotEmittedStatement(node); - case 252: + case 253: return visitClassDeclaration(node); - case 221: + case 222: return visitClassExpression(node); - case 286: + case 287: return visitHeritageClause(node); - case 223: + case 224: return visitExpressionWithTypeArguments(node); - case 165: + case 166: return visitMethodDeclaration(node); - case 167: - return visitGetAccessor(node); case 168: + return visitGetAccessor(node); + case 169: return visitSetAccessor(node); - case 251: + case 252: return visitFunctionDeclaration(node); - case 208: - return visitFunctionExpression(node); case 209: + return visitFunctionExpression(node); + case 210: return visitArrowFunction(node); - case 160: + case 161: return visitParameter(node); - case 207: + case 208: return visitParenthesizedExpression(node); - case 206: - case 224: + case 207: + case 225: return visitAssertionExpression(node); - case 203: - return visitCallExpression(node); case 204: - return visitNewExpression(node); + return visitCallExpression(node); case 205: + return visitNewExpression(node); + case 206: return visitTaggedTemplateExpression(node); - case 225: + case 226: return visitNonNullExpression(node); - case 255: + case 256: return visitEnumDeclaration(node); - case 232: + case 233: return visitVariableStatement(node); - case 249: + case 250: return visitVariableDeclaration(node); - case 256: + case 257: return visitModuleDeclaration(node); - case 260: + case 261: return visitImportEqualsDeclaration(node); - case 274: - return visitJsxSelfClosingElement(node); case 275: + return visitJsxSelfClosingElement(node); + case 276: return visitJsxJsxOpeningElement(node); default: return ts.visitEachChild(node, visitor, context); @@ -70024,7 +72313,7 @@ var ts; return facts; } function hasTypeScriptClassSyntax(node) { - return !!(node.transformFlags & 2048); + return !!(node.transformFlags & 4096); } function isClassLikeDeclarationWithTypeScriptSyntax(node) { return ts.some(node.decorators) @@ -70189,12 +72478,12 @@ var ts; } function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 167: case 168: + case 169: return getAllDecoratorsOfAccessors(node, member); - case 165: + case 166: return getAllDecoratorsOfMethod(member); - case 163: + case 164: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -70273,7 +72562,7 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, true); var descriptor = languageVersion > 0 - ? member.kind === 163 + ? member.kind === 164 ? factory.createVoidZero() : factory.createNull() : undefined; @@ -70359,22 +72648,22 @@ var ts; } function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 165 - || kind === 167 + return kind === 166 || kind === 168 - || kind === 163; + || kind === 169 + || kind === 164; } function shouldAddReturnTypeMetadata(node) { - return node.kind === 165; + return node.kind === 166; } function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 252: - case 221: + case 253: + case 222: return ts.getFirstConstructorWithBody(node) !== undefined; - case 165: - case 167: + case 166: case 168: + case 169: return true; } return false; @@ -70386,15 +72675,15 @@ var ts; } function serializeTypeOfNode(node) { switch (node.kind) { - case 163: - case 160: + case 164: + case 161: return serializeTypeNode(node.type); + case 169: case 168: - case 167: return serializeTypeNode(getAccessorTypeNode(node)); - case 252: - case 221: - case 165: + case 253: + case 222: + case 166: return factory.createIdentifier("Function"); default: return factory.createVoidZero(); @@ -70426,7 +72715,7 @@ var ts; return factory.createArrayLiteralExpression(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 167) { + if (container && node.kind === 168) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -70452,27 +72741,27 @@ var ts; case 150: case 141: return factory.createVoidZero(); - case 186: + case 187: return serializeTypeNode(node.type); - case 174: case 175: + case 176: return factory.createIdentifier("Function"); - case 178: case 179: + case 180: return factory.createIdentifier("Array"); - case 172: + case 173: case 131: return factory.createIdentifier("Boolean"); case 147: return factory.createIdentifier("String"); case 145: return factory.createIdentifier("Object"); - case 191: + case 192: switch (node.literal.kind) { case 10: case 14: return factory.createIdentifier("String"); - case 214: + case 215: case 8: return factory.createIdentifier("Number"); case 9: @@ -70493,36 +72782,36 @@ var ts; return languageVersion < 2 ? getGlobalSymbolNameWithFallback() : factory.createIdentifier("Symbol"); - case 173: + case 174: return serializeTypeReferenceNode(node); + case 184: case 183: - case 182: return serializeTypeList(node.types); - case 184: + case 185: return serializeTypeList([node.trueType, node.falseType]); - case 188: + case 189: if (node.operator === 142) { return serializeTypeNode(node.type); } break; - case 176: - case 189: - case 190: case 177: + case 190: + case 191: + case 178: case 128: case 152: - case 187: - case 195: + case 188: + case 196: break; - case 303: case 304: - case 308: + case 305: case 309: case 310: + case 311: break; - case 305: case 306: case 307: + case 308: return serializeTypeNode(node.type); default: return ts.Debug.failBadSyntaxKind(node); @@ -70533,13 +72822,13 @@ var ts; var serializedUnion; for (var _i = 0, types_24 = types; _i < types_24.length; _i++) { var typeNode = types_24[_i]; - while (typeNode.kind === 186) { + while (typeNode.kind === 187) { typeNode = typeNode.type; } if (typeNode.kind === 141) { continue; } - if (!strictNullChecks && (typeNode.kind === 191 && typeNode.literal.kind === 103 || typeNode.kind === 150)) { + if (!strictNullChecks && (typeNode.kind === 192 && typeNode.literal.kind === 103 || typeNode.kind === 150)) { continue; } var serializedIndividual = serializeTypeNode(typeNode); @@ -70619,7 +72908,7 @@ var ts; name.original = undefined; ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); return name; - case 157: + case 158: return serializeQualifiedNameAsExpression(node); } } @@ -70854,8 +73143,7 @@ var ts; } function shouldEmitEnumDeclaration(node) { return !ts.isEnumConst(node) - || compilerOptions.preserveConstEnums - || compilerOptions.isolatedModules; + || ts.shouldPreserveConstEnums(compilerOptions); } function visitEnumDeclaration(node) { if (!shouldEmitEnumDeclaration(node)) { @@ -70931,7 +73219,7 @@ var ts; if (!node) { return true; } - return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions)); } function hasNamespaceQualifiedExportName(node) { return isExportOfNamespace(node) @@ -70964,11 +73252,11 @@ var ts; function addVarForEnumOrModuleDeclaration(statements, node) { var statement = factory.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.createVariableDeclarationList([ factory.createVariableDeclaration(factory.getLocalName(node, false, true)) - ], currentLexicalScope.kind === 297 ? 0 : 1)); + ], currentLexicalScope.kind === 298 ? 0 : 1)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { - if (node.kind === 255) { + if (node.kind === 256) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -71034,7 +73322,7 @@ var ts; var statementsLocation; var blockLocation; if (node.body) { - if (node.body.kind === 257) { + if (node.body.kind === 258) { saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = node.body.statements; blockLocation = node.body; @@ -71059,13 +73347,13 @@ var ts; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), true); ts.setTextRange(block, blockLocation); - if (!node.body || node.body.kind !== 257) { + if (!node.body || node.body.kind !== 258) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 256) { + if (moduleDeclaration.body.kind === 257) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -71093,7 +73381,7 @@ var ts; return (name || namedBindings) ? factory.updateImportClause(node, false, name, namedBindings) : undefined; } function visitNamedImportBindings(node) { - if (node.kind === 263) { + if (node.kind === 264) { return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } else { @@ -71242,15 +73530,15 @@ var ts; if ((enabledSubstitutions & 2) === 0) { enabledSubstitutions |= 2; context.enableSubstitution(78); - context.enableSubstitution(289); - context.enableEmitNotification(256); + context.enableSubstitution(290); + context.enableEmitNotification(257); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 256; + return ts.getOriginalNode(node).kind === 257; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 255; + return ts.getOriginalNode(node).kind === 256; } function onEmitNode(hint, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; @@ -71296,9 +73584,9 @@ var ts; switch (node.kind) { case 78: return substituteExpressionIdentifier(node); - case 201: - return substitutePropertyAccessExpression(node); case 202: + return substitutePropertyAccessExpression(node); + case 203: return substituteElementAccessExpression(node); } return node; @@ -71315,10 +73603,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; if (classAlias) { - var clone_1 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_1, node); - ts.setCommentRange(clone_1, node); - return clone_1; + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -71328,9 +73616,9 @@ var ts; function trySubstituteNamespaceExportedName(node) { if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var container = resolver.getReferencedExportContainer(node, false); - if (container && container.kind !== 297) { - var substitute = (applicableSubstitutions & 2 && container.kind === 256) || - (applicableSubstitutions & 8 && container.kind === 255); + if (container && container.kind !== 298) { + var substitute = (applicableSubstitutions & 2 && container.kind === 257) || + (applicableSubstitutions & 8 && container.kind === 256); if (substitute) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(container), node), node); } @@ -71372,11 +73660,12 @@ var ts; var ts; (function (ts) { function transformClassFields(context) { - var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment; + var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, addBlockScopedVariable = context.addBlockScopedVariable; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var shouldTransformPrivateFields = languageVersion < 99; + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); + var shouldTransformPrivateElements = languageVersion < 99; var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; var enabledSubstitutions; @@ -71389,7 +73678,7 @@ var ts; function transformSourceFile(node) { var options = context.getCompilerOptions(); if (node.isDeclarationFile - || options.useDefineForClassFields && options.target === 99) { + || useDefineForClassFields && options.target === 99) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -71397,65 +73686,65 @@ var ts; return visited; } function visitor(node) { - if (!(node.transformFlags & 4194304)) + if (!(node.transformFlags & 8388608)) return node; switch (node.kind) { - case 221: - case 252: + case 222: + case 253: return visitClassLike(node); - case 163: + case 164: return visitPropertyDeclaration(node); - case 232: + case 233: return visitVariableStatement(node); - case 201: + case 202: return visitPropertyAccessExpression(node); - case 214: - return visitPrefixUnaryExpression(node); case 215: + return visitPrefixUnaryExpression(node); + case 216: return visitPostfixUnaryExpression(node, false); - case 203: + case 204: return visitCallExpression(node); - case 216: + case 217: return visitBinaryExpression(node); case 79: return visitPrivateIdentifier(node); - case 233: + case 234: return visitExpressionStatement(node); - case 237: + case 238: return visitForStatement(node); - case 205: + case 206: return visitTaggedTemplateExpression(node); } return ts.visitEachChild(node, visitor, context); } function visitorDestructuringTarget(node) { switch (node.kind) { + case 201: case 200: - case 199: return visitAssignmentPattern(node); default: return visitor(node); } } function visitPrivateIdentifier(node) { - if (!shouldTransformPrivateFields) { + if (!shouldTransformPrivateElements) { return node; } return ts.setOriginalNode(factory.createIdentifier(""), node); } function classElementVisitor(node) { switch (node.kind) { - case 166: - return undefined; case 167: + return undefined; case 168: - case 165: - return ts.visitEachChild(node, classElementVisitor, context); - case 163: + case 169: + case 166: + return visitMethodOrAccessorDeclaration(node); + case 164: return visitPropertyDeclaration(node); - case 158: + case 159: return visitComputedPropertyName(node); - case 229: + case 230: return node; default: return visitor(node); @@ -71480,36 +73769,83 @@ var ts; } return node; } + function visitMethodOrAccessorDeclaration(node) { + ts.Debug.assert(!ts.some(node.decorators)); + if (!shouldTransformPrivateElements || !ts.isPrivateIdentifier(node.name)) { + return ts.visitEachChild(node, classElementVisitor, context); + } + var info = accessPrivateIdentifier(node.name); + ts.Debug.assert(info, "Undeclared private name for property declaration."); + if (!info.isValid) { + return node; + } + var functionName = getHoistedFunctionName(node); + if (functionName) { + getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return !ts.isStaticModifier(m); }), node.asteriskToken, functionName, undefined, ts.visitParameterList(node.parameters, classElementVisitor, context), undefined, ts.visitFunctionBody(node.body, classElementVisitor, context)))); + } + return undefined; + } + function getHoistedFunctionName(node) { + ts.Debug.assert(ts.isPrivateIdentifier(node.name)); + var info = accessPrivateIdentifier(node.name); + ts.Debug.assert(info, "Undeclared private name for property declaration."); + if (info.kind === "m") { + return info.methodName; + } + if (info.kind === "a") { + if (ts.isGetAccessor(node)) { + return info.getterName; + } + if (ts.isSetAccessor(node)) { + return info.setterName; + } + } + } function visitPropertyDeclaration(node) { ts.Debug.assert(!ts.some(node.decorators)); - if (!shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) { - return factory.updatePropertyDeclaration(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, undefined, undefined, undefined); + if (ts.isPrivateIdentifier(node.name)) { + if (!shouldTransformPrivateElements) { + return factory.updatePropertyDeclaration(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, undefined, undefined, undefined); + } + var info = accessPrivateIdentifier(node.name); + ts.Debug.assert(info, "Undeclared private name for property declaration."); + if (!info.isValid) { + return node; + } } - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { getPendingExpressions().push(expr); } return undefined; } function createPrivateIdentifierAccess(info, receiver) { - receiver = ts.visitNode(receiver, visitor, ts.isExpression); - switch (info.placement) { - case 0: - return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(ts.nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver), info.weakMapName); - default: return ts.Debug.fail("Unexpected private identifier placement"); + return createPrivateIdentifierAccessHelper(info, ts.visitNode(receiver, visitor, ts.isExpression)); + } + function createPrivateIdentifierAccessHelper(info, receiver) { + ts.setCommentRange(receiver, ts.moveRangePos(receiver, -1)); + switch (info.kind) { + case "a": + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.getterName); + case "m": + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.methodName); + case "f": + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.variableName); + default: + ts.Debug.assertNever(info, "Unknown private element type"); } } function visitPropertyAccessExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifier(node.name)) { var privateIdentifierInfo = accessPrivateIdentifier(node.name); if (privateIdentifierInfo) { - return ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node); + return ts.setTextRange(ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node), node); } } return ts.visitEachChild(node, visitor, context); } function visitPrefixUnaryExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { var operator = node.operator === 45 ? 39 : node.operator === 46 ? 40 : undefined; @@ -71524,7 +73860,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitPostfixUnaryExpression(node, valueIsDiscarded) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { var operator = node.operator === 45 ? 39 : node.operator === 46 ? 40 : undefined; @@ -71544,7 +73880,7 @@ var ts; } function visitForStatement(node) { if (node.incrementor && ts.isPostfixUnaryExpression(node.incrementor)) { - return factory.updateForStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), visitPostfixUnaryExpression(node.incrementor, true), ts.visitNode(node.statement, visitor, ts.isStatement)); + return factory.updateForStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), visitPostfixUnaryExpression(node.incrementor, true), ts.visitIterationBody(node.statement, visitor, context)); } return ts.visitEachChild(node, visitor, context); } @@ -71564,21 +73900,24 @@ var ts; return { readExpression: readExpression, initializeExpression: initializeExpression }; } function visitCallExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; + if (ts.isCallChain(node)) { + return factory.updateCallChain(node, factory.createPropertyAccessChain(ts.visitNode(target, visitor), node.questionDotToken, "call"), undefined, undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); + } return factory.updateCallExpression(node, factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "call"), undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); } return ts.visitEachChild(node, visitor, context); } function visitTaggedTemplateExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) { var _a = factory.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; return factory.updateTaggedTemplateExpression(node, factory.createCallExpression(factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "bind"), undefined, [ts.visitNode(thisArg, visitor, ts.isExpression)]), undefined, ts.visitNode(node.template, visitor, ts.isTemplateLiteral)); } return ts.visitEachChild(node, visitor, context); } function visitBinaryExpression(node) { - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { if (ts.isDestructuringAssignment(node)) { var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; @@ -71592,62 +73931,83 @@ var ts; if (ts.isAssignmentExpression(node) && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) { var info = accessPrivateIdentifier(node.left.name); if (info) { - return ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node); + return ts.setTextRange(ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node), node); } } } return ts.visitEachChild(node, visitor, context); } function createPrivateIdentifierAssignment(info, receiver, right, operator) { - switch (info.placement) { - case 0: { - return createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator); - } - default: return ts.Debug.fail("Unexpected private identifier placement"); - } - } - function createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator) { receiver = ts.visitNode(receiver, visitor, ts.isExpression); right = ts.visitNode(right, visitor, ts.isExpression); if (ts.isCompoundAssignment(operator)) { var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression; - return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(initializeExpression || readExpression, info.weakMapName, factory.createBinaryExpression(context.getEmitHelperFactory().createClassPrivateFieldGetHelper(readExpression, info.weakMapName), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right)); - } - else { - return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.weakMapName, right); + receiver = initializeExpression || readExpression; + right = factory.createBinaryExpression(createPrivateIdentifierAccessHelper(info, readExpression), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right); + } + ts.setCommentRange(receiver, ts.moveRangePos(receiver, -1)); + switch (info.kind) { + case "a": + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, info.setterName); + case "m": + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, undefined); + case "f": + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, info.variableName); + default: + ts.Debug.assertNever(info, "Unknown private element type"); } } function visitClassLike(node) { var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { startPrivateIdentifierEnvironment(); + var name = ts.getNameOfDeclaration(node); + if (name && ts.isIdentifier(name)) { + getPrivateIdentifierEnvironment().className = ts.idText(name); + } + var privateInstanceMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); + if (ts.some(privateInstanceMethodsAndAccessors)) { + getPrivateIdentifierEnvironment().weakSetName = createHoistedVariableForClass("instances", privateInstanceMethodsAndAccessors[0].name); + } } var result = ts.isClassDeclaration(node) ? visitClassDeclaration(node) : visitClassExpression(node); - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { endPrivateIdentifierEnvironment(); } pendingExpressions = savedPendingExpressions; return result; } function doesClassElementNeedTransform(node) { - return ts.isPropertyDeclaration(node) || (shouldTransformPrivateFields && node.name && ts.isPrivateIdentifier(node.name)); + return ts.isPropertyDeclaration(node) || (shouldTransformPrivateElements && node.name && ts.isPrivateIdentifier(node.name)); + } + function getPrivateInstanceMethodsAndAccessors(node) { + return ts.filter(node.members, ts.isNonStaticMethodOrAccessorWithPrivateName); } function visitClassDeclaration(node) { if (!ts.forEach(node.members, doesClassElementNeedTransform)) { return ts.visitEachChild(node, visitor, context); } + var staticProperties = ts.getProperties(node, false, true); + var pendingPrivateStateAssignment; + if (shouldTransformPrivateElements && ts.some(node.members, function (m) { return ts.hasStaticModifier(m) && !!m.name && ts.isPrivateIdentifier(m.name); })) { + var temp = factory.createTempVariable(hoistVariableDeclaration, true); + getPrivateIdentifierEnvironment().classConstructor = factory.cloneNode(temp); + pendingPrivateStateAssignment = factory.createAssignment(temp, factory.getInternalName(node)); + } var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103); var statements = [ factory.updateClassDeclaration(node, undefined, node.modifiers, node.name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)) ]; + if (pendingPrivateStateAssignment) { + getPendingExpressions().unshift(pendingPrivateStateAssignment); + } if (ts.some(pendingExpressions)) { statements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))); } - var staticProperties = ts.getProperties(node, true, true); if (ts.some(staticProperties)) { addPropertyStatements(statements, staticProperties, factory.getInternalName(node)); } @@ -71658,11 +74018,24 @@ var ts; return ts.visitEachChild(node, visitor, context); } var isDecoratedClassDeclaration = ts.isClassDeclaration(ts.getOriginalNode(node)); - var staticProperties = ts.getProperties(node, true, true); + var staticProperties = ts.getProperties(node, false, true); var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103); + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216; + var temp; + function createClassTempVar() { + var classCheckFlags = resolver.getNodeCheckFlags(node); + var isClassWithConstructorReference = classCheckFlags & 16777216; + var requiresBlockScopedVar = classCheckFlags & 524288; + return factory.createTempVariable(requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, !!isClassWithConstructorReference); + } + if (shouldTransformPrivateElements && ts.some(node.members, function (m) { return ts.hasStaticModifier(m) && !!m.name && ts.isPrivateIdentifier(m.name); })) { + temp = createClassTempVar(); + getPrivateIdentifierEnvironment().classConstructor = factory.cloneNode(temp); + } var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)); - if (ts.some(staticProperties) || ts.some(pendingExpressions)) { + var hasTransformableStatics = ts.some(staticProperties, function (p) { return !!p.initializer || (shouldTransformPrivateElements && ts.isPrivateIdentifier(p.name)); }); + if (hasTransformableStatics || ts.some(pendingExpressions)) { if (isDecoratedClassDeclaration) { ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration."); if (pendingStatements && pendingExpressions && ts.some(pendingExpressions)) { @@ -71671,12 +74044,14 @@ var ts; if (pendingStatements && ts.some(staticProperties)) { addPropertyStatements(pendingStatements, staticProperties, factory.getInternalName(node)); } + if (temp) { + return factory.inlineExpressions([factory.createAssignment(temp, classExpression), temp]); + } return classExpression; } else { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216; - var temp = factory.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + temp || (temp = createClassTempVar()); if (isClassWithConstructorReference) { enableSubstitutionForClassAliases(); var alias = factory.cloneNode(temp); @@ -71694,13 +74069,16 @@ var ts; return classExpression; } function transformClassMembers(node, isDerivedClass) { - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (ts.isPrivateIdentifierPropertyDeclaration(member)) { - addPrivateIdentifierToEnvironment(member.name); + if (ts.isPrivateIdentifierClassElementDeclaration(member)) { + addPrivateIdentifierToEnvironment(member); } } + if (ts.some(getPrivateInstanceMethodsAndAccessors(node))) { + createBrandCheckWeakSetForPrivateMethods(); + } } var members = []; var constructor = transformConstructor(node, isDerivedClass); @@ -71710,19 +74088,24 @@ var ts; ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); return ts.setTextRange(factory.createNodeArray(members), node.members); } - function isPropertyDeclarationThatRequiresConstructorStatement(member) { - if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128)) { + function createBrandCheckWeakSetForPrivateMethods() { + var weakSetName = getPrivateIdentifierEnvironment().weakSetName; + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + getPendingExpressions().push(factory.createAssignment(weakSetName, factory.createNewExpression(factory.createIdentifier("WeakSet"), undefined, []))); + } + function isClassElementThatRequiresConstructorStatement(member) { + if (ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128)) { return false; } - if (context.getCompilerOptions().useDefineForClassFields) { + if (useDefineForClassFields) { return languageVersion < 99; } - return ts.isInitializedProperty(member) || shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyDeclaration(member); + return ts.isInitializedProperty(member) || shouldTransformPrivateElements && ts.isPrivateIdentifierClassElementDeclaration(member); } function transformConstructor(node, isDerivedClass) { var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration); - var properties = node.members.filter(isPropertyDeclarationThatRequiresConstructorStatement); - if (!ts.some(properties)) { + var elements = node.members.filter(isClassElementThatRequiresConstructorStatement); + if (!ts.some(elements)) { return constructor; } var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context); @@ -71733,12 +74116,13 @@ var ts; return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(factory.createConstructorDeclaration(undefined, undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { - var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; var properties = ts.getProperties(node, false, false); if (!useDefineForClassFields) { properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); }); } - if (!constructor && !ts.some(properties)) { + var privateMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); + var needsConstructorBody = ts.some(properties) || ts.some(privateMethodsAndAccessors); + if (!constructor && !needsConstructorBody) { return ts.visitFunctionBody(undefined, visitor, context); } resumeLexicalEnvironment(); @@ -71762,7 +74146,9 @@ var ts; indexOfFirstStatement = afterParameterProperties; } } - addPropertyStatements(statements, properties, factory.createThis()); + var receiver = factory.createThis(); + addMethodStatements(statements, privateMethodsAndAccessors, receiver); + addPropertyStatements(statements, properties, receiver); if (constructor) { ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); } @@ -71801,27 +74187,30 @@ var ts; } function transformProperty(property, receiver) { var _a; - var emitAssignment = !context.getCompilerOptions().useDefineForClassFields; + var emitAssignment = !useDefineForClassFields; var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression) ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name)) : property.name; - if (shouldTransformPrivateFields && ts.isPrivateIdentifier(propertyName)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifier(propertyName)) { var privateIdentifierInfo = accessPrivateIdentifier(propertyName); if (privateIdentifierInfo) { - switch (privateIdentifierInfo.placement) { - case 0: { - return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.weakMapName); + if (privateIdentifierInfo.kind === "f") { + if (!privateIdentifierInfo.isStatic) { + return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.brandCheckIdentifier); + } + else { + return createPrivateStaticFieldInitializer(privateIdentifierInfo.variableName, ts.visitNode(property.initializer, visitor, ts.isExpression)); } } + else { + return undefined; + } } else { ts.Debug.fail("Undeclared private name for property declaration."); } } - if (ts.isPrivateIdentifier(propertyName) && !property.initializer) { - return undefined; - } - if (ts.isPrivateIdentifier(propertyName) && !property.initializer) { + if ((ts.isPrivateIdentifier(propertyName) || ts.hasStaticModifier(property)) && !property.initializer) { return undefined; } var propertyOriginalNode = ts.getOriginalNode(property); @@ -71850,6 +74239,14 @@ var ts; classAliases = []; } } + function addMethodStatements(statements, methods, receiver) { + if (!shouldTransformPrivateElements || !ts.some(methods)) { + return; + } + var weakSetName = getPrivateIdentifierEnvironment().weakSetName; + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + statements.push(factory.createExpressionStatement(createPrivateInstanceMethodInitializer(receiver, weakSetName))); + } function onSubstituteNode(hint, node) { node = previousOnSubstituteNode(hint, node); if (hint === 1) { @@ -71874,10 +74271,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; if (classAlias) { - var clone_2 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_2, node); - ts.setCommentRange(clone_2, node); - return clone_2; + var clone_3 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_3, node); + ts.setCommentRange(clone_3, node); + return clone_3; } } } @@ -71892,7 +74289,12 @@ var ts; var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left); if (!alreadyTransformed && !inlinable && shouldHoist) { var generatedName = factory.getGeneratedNameForNode(name); - hoistVariableDeclaration(generatedName); + if (resolver.getNodeCheckFlags(name) & 524288) { + addBlockScopedVariable(generatedName); + } + else { + hoistVariableDeclaration(generatedName); + } return factory.createAssignment(generatedName, expression); } return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression; @@ -71906,21 +74308,163 @@ var ts; currentPrivateIdentifierEnvironment = privateIdentifierEnvironmentStack.pop(); } function getPrivateIdentifierEnvironment() { - return currentPrivateIdentifierEnvironment || (currentPrivateIdentifierEnvironment = new ts.Map()); + if (!currentPrivateIdentifierEnvironment) { + currentPrivateIdentifierEnvironment = { + className: "", + identifiers: new ts.Map() + }; + } + return currentPrivateIdentifierEnvironment; } function getPendingExpressions() { return pendingExpressions || (pendingExpressions = []); } - function addPrivateIdentifierToEnvironment(name) { - var text = ts.getTextOfPropertyName(name); - var weakMapName = factory.createUniqueName("_" + text.substring(1), 16 | 8); - hoistVariableDeclaration(weakMapName); - getPrivateIdentifierEnvironment().set(name.escapedText, { placement: 0, weakMapName: weakMapName }); - getPendingExpressions().push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), undefined, []))); + function addPrivateIdentifierToEnvironment(node) { + var _a; + var text = ts.getTextOfPropertyName(node.name); + var env = getPrivateIdentifierEnvironment(); + var weakSetName = env.weakSetName, classConstructor = env.classConstructor; + var assignmentExpressions = []; + var privateName = node.name.escapedText; + var previousInfo = env.identifiers.get(privateName); + var isValid = !isReservedPrivateName(node.name) && previousInfo === undefined; + if (ts.hasStaticModifier(node)) { + ts.Debug.assert(classConstructor, "weakSetName should be set in private identifier environment"); + if (ts.isPropertyDeclaration(node)) { + var variableName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: "f", + variableName: variableName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + else if (ts.isMethodDeclaration(node)) { + var functionName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: "m", + methodName: functionName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + else if (ts.isGetAccessorDeclaration(node)) { + var getterName = createHoistedVariableForPrivateName(text + "_get", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" && previousInfo.isStatic && !previousInfo.getterName) { + previousInfo.getterName = getterName; + } + else { + env.identifiers.set(privateName, { + kind: "a", + getterName: getterName, + setterName: undefined, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + } + else if (ts.isSetAccessorDeclaration(node)) { + var setterName = createHoistedVariableForPrivateName(text + "_set", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" && previousInfo.isStatic && !previousInfo.setterName) { + previousInfo.setterName = setterName; + } + else { + env.identifiers.set(privateName, { + kind: "a", + getterName: undefined, + setterName: setterName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + } + else { + ts.Debug.assertNever(node, "Unknown class element type."); + } + } + else if (ts.isPropertyDeclaration(node)) { + var weakMapName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: "f", + brandCheckIdentifier: weakMapName, + isStatic: false, + variableName: undefined, + isValid: isValid, + }); + assignmentExpressions.push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), undefined, []))); + } + else if (ts.isMethodDeclaration(node)) { + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + env.identifiers.set(privateName, { + kind: "m", + methodName: createHoistedVariableForPrivateName(text, node), + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + else if (ts.isAccessor(node)) { + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + if (ts.isGetAccessor(node)) { + var getterName = createHoistedVariableForPrivateName(text + "_get", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" && !previousInfo.isStatic && !previousInfo.getterName) { + previousInfo.getterName = getterName; + } + else { + env.identifiers.set(privateName, { + kind: "a", + getterName: getterName, + setterName: undefined, + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + } + else { + var setterName = createHoistedVariableForPrivateName(text + "_set", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" && !previousInfo.isStatic && !previousInfo.setterName) { + previousInfo.setterName = setterName; + } + else { + env.identifiers.set(privateName, { + kind: "a", + getterName: undefined, + setterName: setterName, + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + } + } + else { + ts.Debug.assertNever(node, "Unknown class element type."); + } + (_a = getPendingExpressions()).push.apply(_a, assignmentExpressions); + } + function createHoistedVariableForClass(name, node) { + var className = getPrivateIdentifierEnvironment().className; + var prefix = className ? "_" + className : ""; + var identifier = factory.createUniqueName(prefix + "_" + name, 16); + if (resolver.getNodeCheckFlags(node) & 524288) { + addBlockScopedVariable(identifier); + } + else { + hoistVariableDeclaration(identifier); + } + return identifier; + } + function createHoistedVariableForPrivateName(privateName, node) { + return createHoistedVariableForClass(privateName.substring(1), node.name); } function accessPrivateIdentifier(name) { if (currentPrivateIdentifierEnvironment) { - var info = currentPrivateIdentifierEnvironment.get(name.escapedText); + var info = currentPrivateIdentifierEnvironment.identifiers.get(name.escapedText); if (info) { return info; } @@ -71930,7 +74474,7 @@ var ts; if (!env) { continue; } - var info = env.get(name.escapedText); + var info = env.identifiers.get(name.escapedText); if (info) { return info; } @@ -71990,9 +74534,20 @@ var ts; } } ts.transformClassFields = transformClassFields; + function createPrivateStaticFieldInitializer(variableName, initializer) { + return ts.factory.createAssignment(variableName, ts.factory.createObjectLiteralExpression([ + ts.factory.createPropertyAssignment("value", initializer || ts.factory.createVoidZero()) + ])); + } function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) { return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakMapName, "set"), undefined, [receiver, initializer || ts.factory.createVoidZero()]); } + function createPrivateInstanceMethodInitializer(receiver, weakSetName) { + return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakSetName, "add"), undefined, [receiver]); + } + function isReservedPrivateName(node) { + return node.escapedText === "#constructor"; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -72049,37 +74604,37 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 64) === 0) { + if ((node.transformFlags & 128) === 0) { return node; } switch (node.kind) { case 129: return undefined; - case 213: + case 214: return visitAwaitExpression(node); - case 165: + case 166: return doWithContext(1 | 2, visitMethodDeclaration, node); - case 251: + case 252: return doWithContext(1 | 2, visitFunctionDeclaration, node); - case 208: - return doWithContext(1 | 2, visitFunctionExpression, node); case 209: + return doWithContext(1 | 2, visitFunctionExpression, node); + case 210: return doWithContext(1, visitArrowFunction, node); - case 201: + case 202: if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105) { capturedSuperProperties.add(node.name.escapedText); } return ts.visitEachChild(node, visitor, context); - case 202: + case 203: if (capturedSuperProperties && node.expression.kind === 105) { hasSuperElementAccess = true; } return ts.visitEachChild(node, visitor, context); - case 167: case 168: - case 166: - case 252: - case 221: + case 169: + case 167: + case 253: + case 222: return doWithContext(1 | 2, visitDefault, node); default: return ts.visitEachChild(node, visitor, context); @@ -72088,27 +74643,27 @@ var ts; function asyncBodyVisitor(node) { if (ts.isNodeWithPossibleHoistedDeclaration(node)) { switch (node.kind) { - case 232: + case 233: return visitVariableStatementInAsyncBody(node); - case 237: - return visitForStatementInAsyncBody(node); case 238: - return visitForInStatementInAsyncBody(node); + return visitForStatementInAsyncBody(node); case 239: + return visitForInStatementInAsyncBody(node); + case 240: return visitForOfStatementInAsyncBody(node); - case 287: + case 288: return visitCatchClauseInAsyncBody(node); - case 230: - case 244: - case 258: - case 284: + case 231: + case 245: + case 259: case 285: - case 247: - case 235: + case 286: + case 248: case 236: - case 234: - case 243: - case 245: + case 237: + case 235: + case 244: + case 246: return ts.visitEachChild(node, asyncBodyVisitor, context); default: return ts.Debug.assertNever(node, "Unhandled node."); @@ -72149,18 +74704,18 @@ var ts; function visitForInStatementInAsyncBody(node) { return factory.updateForInStatement(node, isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames(node.initializer, true) - : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock)); + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context)); } function visitForOfStatementInAsyncBody(node) { return factory.updateForOfStatement(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames(node.initializer, true) - : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock)); + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context)); } function visitForStatementInAsyncBody(node) { var initializer = node.initializer; return factory.updateForStatement(node, isVariableDeclarationListWithCollidingName(initializer) ? visitVariableDeclarationListWithCollidingNames(initializer, false) - : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock)); + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context)); } function visitAwaitExpression(node) { if (inTopLevelContext()) { @@ -72260,7 +74815,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 209; + var isArrowFunction = node.kind === 210; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; enclosingFunctionParameterNames = new ts.Set(); @@ -72341,15 +74896,15 @@ var ts; function enableSubstitutionForAsyncMethodsWithSuper() { if ((enabledSubstitutions & 1) === 0) { enabledSubstitutions |= 1; - context.enableSubstitution(203); - context.enableSubstitution(201); + context.enableSubstitution(204); context.enableSubstitution(202); - context.enableEmitNotification(252); - context.enableEmitNotification(165); - context.enableEmitNotification(167); - context.enableEmitNotification(168); + context.enableSubstitution(203); + context.enableEmitNotification(253); context.enableEmitNotification(166); - context.enableEmitNotification(232); + context.enableEmitNotification(168); + context.enableEmitNotification(169); + context.enableEmitNotification(167); + context.enableEmitNotification(233); } } function onEmitNode(hint, node, emitCallback) { @@ -72381,11 +74936,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 201: - return substitutePropertyAccessExpression(node); case 202: - return substituteElementAccessExpression(node); + return substitutePropertyAccessExpression(node); case 203: + return substituteElementAccessExpression(node); + case 204: return substituteCallExpression(node); } return node; @@ -72416,11 +74971,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 252 - || kind === 166 - || kind === 165 + return kind === 253 || kind === 167 - || kind === 168; + || kind === 166 + || kind === 168 + || kind === 169; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096) { @@ -72527,74 +75082,74 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitorWorker(node, expressionResultIsUnused) { - if ((node.transformFlags & 32) === 0) { + if ((node.transformFlags & 64) === 0) { return node; } switch (node.kind) { - case 213: + case 214: return visitAwaitExpression(node); - case 219: + case 220: return visitYieldExpression(node); - case 242: + case 243: return visitReturnStatement(node); - case 245: + case 246: return visitLabeledStatement(node); - case 200: + case 201: return visitObjectLiteralExpression(node); - case 216: + case 217: return visitBinaryExpression(node, expressionResultIsUnused); - case 337: + case 341: return visitCommaListExpression(node, expressionResultIsUnused); - case 287: + case 288: return visitCatchClause(node); - case 232: + case 233: return visitVariableStatement(node); - case 249: + case 250: return visitVariableDeclaration(node); - case 235: case 236: - case 238: - return doWithHierarchyFacts(visitDefault, node, 0, 2); + case 237: case 239: + return doWithHierarchyFacts(visitDefault, node, 0, 2); + case 240: return visitForOfStatement(node, undefined); - case 237: + case 238: return doWithHierarchyFacts(visitForStatement, node, 0, 2); - case 212: + case 213: return visitVoidExpression(node); - case 166: + case 167: return doWithHierarchyFacts(visitConstructorDeclaration, node, 2, 1); - case 165: + case 166: return doWithHierarchyFacts(visitMethodDeclaration, node, 2, 1); - case 167: - return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2, 1); case 168: + return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2, 1); + case 169: return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2, 1); - case 251: + case 252: return doWithHierarchyFacts(visitFunctionDeclaration, node, 2, 1); - case 208: - return doWithHierarchyFacts(visitFunctionExpression, node, 2, 1); case 209: + return doWithHierarchyFacts(visitFunctionExpression, node, 2, 1); + case 210: return doWithHierarchyFacts(visitArrowFunction, node, 2, 0); - case 160: + case 161: return visitParameter(node); - case 233: + case 234: return visitExpressionStatement(node); - case 207: + case 208: return visitParenthesizedExpression(node, expressionResultIsUnused); - case 205: + case 206: return visitTaggedTemplateExpression(node); - case 201: + case 202: if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105) { capturedSuperProperties.add(node.name.escapedText); } return ts.visitEachChild(node, visitor, context); - case 202: + case 203: if (capturedSuperProperties && node.expression.kind === 105) { hasSuperElementAccess = true; } return ts.visitEachChild(node, visitor, context); - case 252: - case 221: + case 253: + case 222: return doWithHierarchyFacts(visitDefault, node, 2, 1); default: return ts.visitEachChild(node, visitor, context); @@ -72627,7 +75182,7 @@ var ts; function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 239 && statement.awaitModifier) { + if (statement.kind === 240 && statement.awaitModifier) { return visitForOfStatement(statement, node); } return factory.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, factory.liftToBlock), node); @@ -72639,7 +75194,7 @@ var ts; var objects = []; for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { var e = elements_4[_i]; - if (e.kind === 290) { + if (e.kind === 291) { if (chunkObject) { objects.push(factory.createObjectLiteralExpression(chunkObject)); chunkObject = undefined; @@ -72648,7 +75203,7 @@ var ts; objects.push(ts.visitNode(target, visitor, ts.isExpression)); } else { - chunkObject = ts.append(chunkObject, e.kind === 288 + chunkObject = ts.append(chunkObject, e.kind === 289 ? factory.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } @@ -72659,9 +75214,9 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 16384) { + if (node.transformFlags & 32768) { var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 200) { + if (objects.length && objects[0].kind !== 201) { objects.unshift(factory.createObjectLiteralExpression()); } var expression = objects[0]; @@ -72700,7 +75255,7 @@ var ts; return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction); } function visitBinaryExpression(node, expressionResultIsUnused) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 16384) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 32768) { return ts.flattenDestructuringAssignment(node, visitor, context, 1, !expressionResultIsUnused); } if (node.operatorToken.kind === 27) { @@ -72727,7 +75282,7 @@ var ts; function visitCatchClause(node) { if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name) && - node.variableDeclaration.name.transformFlags & 16384) { + node.variableDeclaration.name.transformFlags & 32768) { var name = factory.getGeneratedNameForNode(node.variableDeclaration.name); var updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, undefined, undefined, name); var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1); @@ -72762,20 +75317,20 @@ var ts; return visitVariableDeclarationWorker(node, false); } function visitVariableDeclarationWorker(node, exportedVariableStatement) { - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 16384) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 32768) { return ts.flattenDestructuringBinding(node, visitor, context, 1, undefined, exportedVariableStatement); } return ts.visitEachChild(node, visitor, context); } function visitForStatement(node) { - return factory.updateForStatement(node, ts.visitNode(node.initializer, visitorWithUnusedExpressionResult, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitorWithUnusedExpressionResult, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement)); + return factory.updateForStatement(node, ts.visitNode(node.initializer, visitorWithUnusedExpressionResult, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitorWithUnusedExpressionResult, ts.isExpression), ts.visitIterationBody(node.statement, visitor, context)); } function visitVoidExpression(node) { return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context); } function visitForOfStatement(node, outermostLabeledStatement) { var ancestorFacts = enterSubtree(0, 2); - if (node.initializer.transformFlags & 16384) { + if (node.initializer.transformFlags & 32768) { node = transformForOfStatementWithObjectRest(node); } var result = node.awaitModifier ? @@ -72812,7 +75367,7 @@ var ts; var bodyLocation; var statementsLocation; var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; - var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + var statement = ts.visitIterationBody(node.statement, visitor, context); if (ts.isBlock(statement)) { ts.addRange(statements, statement.statements); bodyLocation = statement; @@ -72864,7 +75419,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 16384) { + if (node.transformFlags & 32768) { return factory.updateParameterDeclaration(node, undefined, undefined, node.dotDotDotToken, factory.getGeneratedNameForNode(node), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } return ts.visitEachChild(node, visitor, context); @@ -72990,7 +75545,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 & 16384) { + if (parameter.transformFlags & 32768) { var temp = factory.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1, temp, false, true); if (ts.some(declarations)) { @@ -73005,15 +75560,15 @@ var ts; function enableSubstitutionForAsyncMethodsWithSuper() { if ((enabledSubstitutions & 1) === 0) { enabledSubstitutions |= 1; - context.enableSubstitution(203); - context.enableSubstitution(201); + context.enableSubstitution(204); context.enableSubstitution(202); - context.enableEmitNotification(252); - context.enableEmitNotification(165); - context.enableEmitNotification(167); - context.enableEmitNotification(168); + context.enableSubstitution(203); + context.enableEmitNotification(253); context.enableEmitNotification(166); - context.enableEmitNotification(232); + context.enableEmitNotification(168); + context.enableEmitNotification(169); + context.enableEmitNotification(167); + context.enableEmitNotification(233); } } function onEmitNode(hint, node, emitCallback) { @@ -73045,11 +75600,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 201: - return substitutePropertyAccessExpression(node); case 202: - return substituteElementAccessExpression(node); + return substitutePropertyAccessExpression(node); case 203: + return substituteElementAccessExpression(node); + case 204: return substituteCallExpression(node); } return node; @@ -73080,11 +75635,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 252 - || kind === 166 - || kind === 165 + return kind === 253 || kind === 167 - || kind === 168; + || kind === 166 + || kind === 168 + || kind === 169; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096) { @@ -73109,11 +75664,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 16) === 0) { + if ((node.transformFlags & 32) === 0) { return node; } switch (node.kind) { - case 287: + case 288: return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); @@ -73140,25 +75695,29 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 8) === 0) { + if ((node.transformFlags & 16) === 0) { return node; } switch (node.kind) { - case 201: + case 204: { + var updated = visitNonOptionalCallExpression(node, false); + ts.Debug.assertNotNode(updated, ts.isSyntheticReference); + return updated; + } case 202: case 203: - if (node.flags & 32) { + if (ts.isOptionalChain(node)) { var updated = visitOptionalExpression(node, false, false); ts.Debug.assertNotNode(updated, ts.isSyntheticReference); return updated; } return ts.visitEachChild(node, visitor, context); - case 216: + case 217: if (node.operatorToken.kind === 60) { return transformNullishCoalescingExpression(node); } return ts.visitEachChild(node, visitor, context); - case 210: + case 211: return visitDeleteExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -73197,7 +75756,7 @@ var ts; thisArg = expression; } } - expression = node.kind === 201 + expression = node.kind === 202 ? factory.updatePropertyAccessExpression(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)) : factory.updateElementAccessExpression(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); return thisArg ? factory.createSyntheticReferenceExpression(expression, thisArg) : expression; @@ -73206,14 +75765,22 @@ var ts; if (ts.isOptionalChain(node)) { return visitOptionalExpression(node, captureThisArg, false); } + if (ts.isParenthesizedExpression(node.expression) && ts.isOptionalChain(ts.skipParentheses(node.expression))) { + var expression = visitNonOptionalParenthesizedExpression(node.expression, true, false); + var args = ts.visitNodes(node.arguments, visitor, ts.isExpression); + if (ts.isSyntheticReference(expression)) { + return ts.setTextRange(factory.createFunctionCallCall(expression.expression, expression.thisArg, args), node); + } + return factory.updateCallExpression(node, expression, undefined, args); + } return ts.visitEachChild(node, visitor, context); } function visitNonOptionalExpression(node, captureThisArg, isDelete) { switch (node.kind) { - case 207: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete); - case 201: - case 202: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete); - case 203: return visitNonOptionalCallExpression(node, captureThisArg); + case 208: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete); + case 202: + case 203: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete); + case 204: return visitNonOptionalCallExpression(node, captureThisArg); default: return ts.visitNode(node, visitor, ts.isExpression); } } @@ -73232,8 +75799,8 @@ var ts; for (var i = 0; i < chain.length; i++) { var segment = chain[i]; switch (segment.kind) { - case 201: case 202: + case 203: if (i === chain.length - 1 && captureThisArg) { if (!ts.isSimpleCopiableExpression(rightExpression)) { thisArg = factory.createTempVariable(hoistVariableDeclaration); @@ -73243,11 +75810,11 @@ var ts; thisArg = rightExpression; } } - rightExpression = segment.kind === 201 + rightExpression = segment.kind === 202 ? factory.createPropertyAccessExpression(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)) : factory.createElementAccessExpression(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); break; - case 203: + case 204: if (i === 0 && leftThisArg) { rightExpression = factory.createFunctionCallCall(rightExpression, leftThisArg.kind === 105 ? factory.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); } @@ -73286,7 +75853,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function transformESNext(context) { + function transformES2021(context) { var hoistVariableDeclaration = context.hoistVariableDeclaration, factory = context.factory; return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { @@ -73296,11 +75863,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 4) === 0) { + if ((node.transformFlags & 8) === 0) { return node; } switch (node.kind) { - case 216: + case 217: var binaryExpression = node; if (ts.isLogicalOrCoalescingAssignmentExpression(binaryExpression)) { return transformLogicalAssignment(binaryExpression); @@ -73335,6 +75902,28 @@ var ts; return factory.createBinaryExpression(left, nonAssignmentOperator, factory.createParenthesizedExpression(factory.createAssignment(assignmentTarget, right))); } } + ts.transformES2021 = transformES2021; +})(ts || (ts = {})); +var ts; +(function (ts) { + function transformESNext(context) { + return ts.chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if ((node.transformFlags & 4) === 0) { + return node; + } + switch (node.kind) { + default: + return ts.visitEachChild(node, visitor, context); + } + } + } ts.transformESNext = transformESNext; })(ts || (ts = {})); var ts; @@ -73434,13 +76023,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 273: - return visitJsxElement(node, false); case 274: + return visitJsxElement(node, false); + case 275: return visitJsxSelfClosingElement(node, false); - case 277: + case 278: return visitJsxFragment(node, false); - case 283: + case 284: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -73450,13 +76039,13 @@ var ts; switch (node.kind) { case 11: return visitJsxText(node); - case 283: + case 284: return visitJsxExpression(node); - case 273: - return visitJsxElement(node, true); case 274: + return visitJsxElement(node, true); + case 275: return visitJsxSelfClosingElement(node, true); - case 277: + case 278: return visitJsxFragment(node, true); default: return ts.Debug.failBadSyntaxKind(node); @@ -73493,9 +76082,9 @@ var ts; function convertJsxChildrenToChildrenPropObject(children) { var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); if (ts.length(nonWhitespaceChildren) === 1) { - var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]); - return result_13 && factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", result_13) + var result_14 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result_14 && factory.createObjectLiteralExpression([ + factory.createPropertyAssignment("children", result_14) ]); } var result = ts.mapDefined(children, transformJsxChildToExpression); @@ -73560,15 +76149,23 @@ var ts; objectProperties = factory.createNull(); } else { - var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread - ? ts.map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); - if (ts.isJsxSpreadAttribute(attrs[0])) { - segments.unshift(factory.createObjectLiteralExpression()); + var target = compilerOptions.target; + if (target && target >= 5) { + objectProperties = factory.createObjectLiteralExpression(ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { + return isSpread ? ts.map(attrs, transformJsxSpreadAttributeToSpreadAssignment) : ts.map(attrs, transformJsxAttributeToObjectLiteralElement); + }))); } - objectProperties = ts.singleOrUndefined(segments); - if (!objectProperties) { - objectProperties = emitHelpers().createAssignHelper(segments); + else { + var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + segments.unshift(factory.createObjectLiteralExpression()); + } + objectProperties = ts.singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = emitHelpers().createAssignHelper(segments); + } } } var callee = currentFileState.importSpecifier === undefined @@ -73597,6 +76194,9 @@ var ts; } return element; } + function transformJsxSpreadAttributeToSpreadAssignment(node) { + return factory.createSpreadAssignment(ts.visitNode(node.expression, visitor, ts.isExpression)); + } function transformJsxSpreadAttributeToExpression(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } @@ -73614,7 +76214,7 @@ var ts; var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote); return ts.setTextRange(literal, node); } - else if (node.kind === 283) { + else if (node.kind === 284) { if (node.expression === undefined) { return factory.createTrue(); } @@ -73674,7 +76274,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 273) { + if (node.kind === 274) { return getTagName(node.openingElement); } else { @@ -73970,11 +76570,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 128) === 0) { + if ((node.transformFlags & 256) === 0) { return node; } switch (node.kind) { - case 216: + case 217: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -74064,11 +76664,11 @@ var ts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 8192) !== 0 - && node.kind === 242 + && node.kind === 243 && !node.expression; } function isOrMayContainReturnCompletion(node) { - return node.transformFlags & 1048576 + return node.transformFlags & 2097152 && (ts.isReturnStatement(node) || ts.isIfStatement(node) || ts.isWithStatement(node) @@ -74083,7 +76683,7 @@ var ts; || ts.isBlock(node)); } function shouldVisitNode(node) { - return (node.transformFlags & 256) !== 0 + return (node.transformFlags & 512) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 8192 && isOrMayContainReturnCompletion(node)) || (ts.isIterationStatement(node, false) && shouldConvertIterationStatement(node)) @@ -74105,65 +76705,65 @@ var ts; switch (node.kind) { case 123: return undefined; - case 252: + case 253: return visitClassDeclaration(node); - case 221: + case 222: return visitClassExpression(node); - case 160: + case 161: return visitParameter(node); - case 251: + case 252: return visitFunctionDeclaration(node); - case 209: + case 210: return visitArrowFunction(node); - case 208: + case 209: return visitFunctionExpression(node); - case 249: + case 250: return visitVariableDeclaration(node); case 78: return visitIdentifier(node); - case 250: + case 251: return visitVariableDeclarationList(node); - case 244: + case 245: return visitSwitchStatement(node); - case 258: + case 259: return visitCaseBlock(node); - case 230: + case 231: return visitBlock(node, false); + case 242: case 241: - case 240: return visitBreakOrContinueStatement(node); - case 245: + case 246: return visitLabeledStatement(node); - case 235: case 236: - return visitDoOrWhileStatement(node, undefined); case 237: - return visitForStatement(node, undefined); + return visitDoOrWhileStatement(node, undefined); case 238: - return visitForInStatement(node, undefined); + return visitForStatement(node, undefined); case 239: + return visitForInStatement(node, undefined); + case 240: return visitForOfStatement(node, undefined); - case 233: + case 234: return visitExpressionStatement(node); - case 200: + case 201: return visitObjectLiteralExpression(node); - case 287: + case 288: return visitCatchClause(node); - case 289: + case 290: return visitShorthandPropertyAssignment(node); - case 158: + case 159: return visitComputedPropertyName(node); - case 199: + case 200: return visitArrayLiteralExpression(node); - case 203: - return visitCallExpression(node); case 204: + return visitCallExpression(node); + case 205: return visitNewExpression(node); - case 207: + case 208: return visitParenthesizedExpression(node, expressionResultIsUnused); - case 216: + case 217: return visitBinaryExpression(node, expressionResultIsUnused); - case 337: + case 341: return visitCommaListExpression(node, expressionResultIsUnused); case 14: case 15: @@ -74174,30 +76774,30 @@ var ts; return visitStringLiteral(node); case 8: return visitNumericLiteral(node); - case 205: + case 206: return visitTaggedTemplateExpression(node); - case 218: - return visitTemplateExpression(node); case 219: - return visitYieldExpression(node); + return visitTemplateExpression(node); case 220: + return visitYieldExpression(node); + case 221: return visitSpreadElement(node); case 105: return visitSuperKeyword(false); case 107: return visitThisKeyword(node); - case 226: + case 227: return visitMetaProperty(node); - case 165: + case 166: return visitMethodDeclaration(node); - case 167: case 168: + case 169: return visitAccessorDeclaration(node); - case 232: + case 233: return visitVariableStatement(node); - case 242: + case 243: return visitReturnStatement(node); - case 212: + case 213: return visitVoidExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -74281,14 +76881,14 @@ var ts; } function visitBreakOrContinueStatement(node) { if (convertedLoopState) { - var jump = node.kind === 241 ? 2 : 4; + var jump = node.kind === 242 ? 2 : 4; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; var label = node.label; if (!label) { - if (node.kind === 241) { + if (node.kind === 242) { convertedLoopState.nonLocalJumps |= 2; labelMarker = "break"; } @@ -74298,7 +76898,7 @@ var ts; } } else { - if (node.kind === 241) { + if (node.kind === 242) { labelMarker = "break-" + label.escapedText; setLabeledJump(convertedLoopState, true, ts.idText(label), labelMarker); } @@ -74463,7 +77063,7 @@ var ts; factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); insertCaptureNewTargetIfNeeded(prologue, constructor, false); if (isDerivedClass) { - if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 4096)) { + if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 8192)) { var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression); var returnStatement = factory.createReturnStatement(superCallExpression); ts.setCommentRange(returnStatement, ts.getCommentRange(superCall)); @@ -74485,17 +77085,17 @@ var ts; return block; } function isSufficientlyCoveredByReturnStatements(statement) { - if (statement.kind === 242) { + if (statement.kind === 243) { return true; } - else if (statement.kind === 234) { + else if (statement.kind === 235) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); } } - else if (statement.kind === 230) { + else if (statement.kind === 231) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -74603,7 +77203,7 @@ var ts; return true; } function insertCaptureThisForNodeIfNeeded(statements, node) { - if (hierarchyFacts & 32768 && node.kind !== 209) { + if (hierarchyFacts & 32768 && node.kind !== 210) { insertCaptureThisForNode(statements, node, factory.createThis()); return true; } @@ -74622,18 +77222,18 @@ var ts; if (hierarchyFacts & 16384) { var newTarget = void 0; switch (node.kind) { - case 209: + case 210: return statements; - case 165: - case 167: + case 166: case 168: + case 169: newTarget = factory.createVoidZero(); break; - case 166: + case 167: newTarget = factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createThis(), 4), "constructor"); break; - case 251: - case 208: + case 252: + case 209: newTarget = factory.createConditionalExpression(factory.createLogicalAnd(ts.setEmitFlags(factory.createThis(), 4), factory.createBinaryExpression(ts.setEmitFlags(factory.createThis(), 4), 101, factory.getLocalName(node))), undefined, factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createThis(), 4), "constructor"), undefined, factory.createVoidZero()); break; default: @@ -74654,20 +77254,20 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 229: + case 230: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 165: + case 166: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 167: case 168: + case 169: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 166: + case 167: break; default: ts.Debug.failBadSyntaxKind(member, currentSourceFile && currentSourceFile.fileName); @@ -74684,7 +77284,7 @@ var ts; var memberFunction = transformFunctionLikeToExpression(member, member, undefined, container); var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName); var e; - if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) { + if (!ts.isPrivateIdentifier(propertyName) && ts.getUseDefineForClassFields(context.getCompilerOptions())) { var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName; @@ -74749,7 +77349,7 @@ var ts; return call; } function visitArrowFunction(node) { - if (node.transformFlags & 4096) { + if (node.transformFlags & 8192) { hierarchyFacts |= 32768; } var savedConvertedLoopState = convertedLoopState; @@ -74802,7 +77402,7 @@ var ts; : enterSubtree(16286, 65); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 && !name && (node.kind === 251 || node.kind === 208)) { + if (hierarchyFacts & 16384 && !name && (node.kind === 252 || node.kind === 209)) { name = factory.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152, 0); @@ -74835,7 +77435,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 209); + ts.Debug.assert(node.kind === 210); statementsLocation = ts.moveRangeEnd(body, -1); var equalsGreaterThanToken = node.equalsGreaterThanToken; if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) { @@ -74956,7 +77556,7 @@ var ts; return updated; } function visitVariableDeclarationList(node) { - if (node.flags & 3 || node.transformFlags & 131072) { + if (node.flags & 3 || node.transformFlags & 262144) { if (node.flags & 3) { enableSubstitutionsForBlockScopedBindings(); } @@ -74967,7 +77567,7 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 131072 + if (node.transformFlags & 262144 && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -74977,8 +77577,8 @@ var ts; } 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]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var node = declarations_9[_i]; pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); end = Math.max(end, node.end); } @@ -75039,14 +77639,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 235: case 236: - return visitDoOrWhileStatement(node, outermostLabeledStatement); case 237: - return visitForStatement(node, outermostLabeledStatement); + return visitDoOrWhileStatement(node, outermostLabeledStatement); case 238: - return visitForInStatement(node, outermostLabeledStatement); + return visitForStatement(node, outermostLabeledStatement); case 239: + return visitForInStatement(node, outermostLabeledStatement); + case 240: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -75169,9 +77769,9 @@ var ts; var numInitialProperties = -1, hasComputed = false; for (var i = 0; i < properties.length; i++) { var property = properties[i]; - if ((property.transformFlags & 262144 && + if ((property.transformFlags & 524288 && hierarchyFacts & 4) - || (hasComputed = ts.Debug.checkDefined(property.name).kind === 158)) { + || (hasComputed = ts.Debug.checkDefined(property.name).kind === 159)) { numInitialProperties = i; break; } @@ -75264,24 +77864,24 @@ var ts; loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts); } else { - var clone_3 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, true)); - loop = factory.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_4 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, true)); + loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); } } else { - var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + loop = factory.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel); } statements.push(loop); return statements; } function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { switch (node.kind) { - case 237: return convertForStatement(node, initializerFunction, convertedLoopBody); - case 238: return convertForInStatement(node, convertedLoopBody); - case 239: return convertForOfStatement(node, convertedLoopBody); - case 235: return convertDoStatement(node, convertedLoopBody); - case 236: return convertWhileStatement(node, convertedLoopBody); + case 238: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 239: return convertForInStatement(node, convertedLoopBody); + case 240: return convertForOfStatement(node, convertedLoopBody); + case 236: return convertDoStatement(node, convertedLoopBody); + case 237: return convertWhileStatement(node, convertedLoopBody); default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); } } @@ -75305,11 +77905,11 @@ var ts; function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { - case 237: case 238: case 239: + case 240: var initializer = node.initializer; - if (initializer && initializer.kind === 250) { + if (initializer && initializer.kind === 251) { loopInitializer = initializer; } break; @@ -75393,7 +77993,7 @@ var ts; } function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = factory.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 262144) !== 0; + var containsYield = (node.initializer.transformFlags & 524288) !== 0; var emitFlags = 0; if (currentState.containsLexicalThis) emitFlags |= 8; @@ -75437,7 +78037,7 @@ var ts; var loopBody = factory.createBlock(statements, true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 262144) !== 0; + var containsYield = (node.statement.transformFlags & 524288) !== 0; var emitFlags = 524288; if (currentState.containsLexicalThis) emitFlags |= 8; @@ -75573,20 +78173,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 167: case 168: + case 169: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; - case 165: + case 166: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 288: + case 289: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 289: + case 290: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -75657,7 +78257,7 @@ var ts; var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (node.kind === 167) { + if (node.kind === 168) { updated = factory.updateGetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { @@ -75738,7 +78338,7 @@ var ts; return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); } function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { - if (node.transformFlags & 8192 || + if (node.transformFlags & 16384 || node.expression.kind === 105 || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -75746,7 +78346,7 @@ var ts; ts.setEmitFlags(thisArg, 4); } var resultingCall = void 0; - if (node.transformFlags & 8192) { + if (node.transformFlags & 16384) { resultingCall = factory.createFunctionApplyCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 105 ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); } else { @@ -75891,13 +78491,13 @@ var ts; if ((enabledSubstitutions & 1) === 0) { enabledSubstitutions |= 1; context.enableSubstitution(107); - context.enableEmitNotification(166); - context.enableEmitNotification(165); context.enableEmitNotification(167); + context.enableEmitNotification(166); context.enableEmitNotification(168); + context.enableEmitNotification(169); + context.enableEmitNotification(210); context.enableEmitNotification(209); - context.enableEmitNotification(208); - context.enableEmitNotification(251); + context.enableEmitNotification(252); } } function onSubstituteNode(hint, node) { @@ -75921,10 +78521,10 @@ var ts; } function isNameOfDeclarationWithCollidingName(node) { switch (node.parent.kind) { - case 198: - case 252: - case 255: - case 249: + case 199: + case 253: + case 256: + case 250: return node.parent.name === node && resolver.isDeclarationWithCollidingName(node.parent); } @@ -75985,11 +78585,11 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 233) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 234) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 203) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 204) { return false; } var callTarget = statementExpression.expression; @@ -75997,7 +78597,7 @@ var ts; return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 220) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 221) { return false; } var expression = callArgument.expression; @@ -76016,24 +78616,24 @@ var ts; if (compilerOptions.jsx === 1 || compilerOptions.jsx === 3) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(275); context.enableEmitNotification(276); - context.enableEmitNotification(274); + context.enableEmitNotification(277); + context.enableEmitNotification(275); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(201); - context.enableSubstitution(288); + context.enableSubstitution(202); + context.enableSubstitution(289); return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { return node; } function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 275: case 276: - case 274: + case 277: + case 275: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -76126,7 +78726,7 @@ var ts; var withBlockStack; return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || (node.transformFlags & 512) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 1024) === 0) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -76144,7 +78744,7 @@ var ts; else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) { return visitGenerator(node); } - else if (transformFlags & 512) { + else if (transformFlags & 1024) { return ts.visitEachChild(node, visitor, context); } else { @@ -76153,13 +78753,13 @@ var ts; } function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 235: - return visitDoStatement(node); case 236: + return visitDoStatement(node); + case 237: return visitWhileStatement(node); - case 244: - return visitSwitchStatement(node); case 245: + return visitSwitchStatement(node); + case 246: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -76167,30 +78767,30 @@ var ts; } function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 251: + case 252: return visitFunctionDeclaration(node); - case 208: + case 209: return visitFunctionExpression(node); - case 167: case 168: + case 169: return visitAccessorDeclaration(node); - case 232: + case 233: return visitVariableStatement(node); - case 237: - return visitForStatement(node); case 238: + return visitForStatement(node); + case 239: return visitForInStatement(node); - case 241: + case 242: return visitBreakStatement(node); - case 240: + case 241: return visitContinueStatement(node); - case 242: + case 243: return visitReturnStatement(node); default: - if (node.transformFlags & 262144) { + if (node.transformFlags & 524288) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 | 1048576)) { + else if (node.transformFlags & (1024 | 2097152)) { return ts.visitEachChild(node, visitor, context); } else { @@ -76200,23 +78800,23 @@ var ts; } function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 216: + case 217: return visitBinaryExpression(node); - case 337: + case 341: return visitCommaListExpression(node); - case 217: + case 218: return visitConditionalExpression(node); - case 219: + case 220: return visitYieldExpression(node); - case 199: - return visitArrayLiteralExpression(node); case 200: + return visitArrayLiteralExpression(node); + case 201: return visitObjectLiteralExpression(node); - case 202: - return visitElementAccessExpression(node); case 203: - return visitCallExpression(node); + return visitElementAccessExpression(node); case 204: + return visitCallExpression(node); + case 205: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -76224,9 +78824,9 @@ var ts; } function visitGenerator(node) { switch (node.kind) { - case 251: + case 252: return visitFunctionDeclaration(node); - case 208: + case 209: return visitFunctionExpression(node); default: return ts.Debug.failBadSyntaxKind(node); @@ -76328,7 +78928,7 @@ var ts; return ts.setTextRange(factory.createBlock(statements, body.multiLine), body); } function visitVariableStatement(node) { - if (node.transformFlags & 262144) { + if (node.transformFlags & 524288) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -76363,10 +78963,10 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 201: + case 202: target = factory.updatePropertyAccessExpression(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 202: + case 203: target = factory.updateElementAccessExpression(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression))); break; default: @@ -76578,35 +79178,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 230: + case 231: return transformAndEmitBlock(node); - case 233: - return transformAndEmitExpressionStatement(node); case 234: - return transformAndEmitIfStatement(node); + return transformAndEmitExpressionStatement(node); case 235: - return transformAndEmitDoStatement(node); + return transformAndEmitIfStatement(node); case 236: - return transformAndEmitWhileStatement(node); + return transformAndEmitDoStatement(node); case 237: - return transformAndEmitForStatement(node); + return transformAndEmitWhileStatement(node); case 238: + return transformAndEmitForStatement(node); + case 239: return transformAndEmitForInStatement(node); - case 240: - return transformAndEmitContinueStatement(node); case 241: - return transformAndEmitBreakStatement(node); + return transformAndEmitContinueStatement(node); case 242: - return transformAndEmitReturnStatement(node); + return transformAndEmitBreakStatement(node); case 243: - return transformAndEmitWithStatement(node); + return transformAndEmitReturnStatement(node); case 244: - return transformAndEmitSwitchStatement(node); + return transformAndEmitWithStatement(node); case 245: - return transformAndEmitLabeledStatement(node); + return transformAndEmitSwitchStatement(node); case 246: - return transformAndEmitThrowStatement(node); + return transformAndEmitLabeledStatement(node); case 247: + return transformAndEmitThrowStatement(node); + case 248: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -76769,7 +79369,7 @@ var ts; var variables = ts.getInitializedVariables(initializer); node = factory.updateForStatement(node, variables.length > 0 ? factory.inlineExpressions(ts.map(variables, transformInitializedVariable)) - : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitIterationBody(node.statement, visitor, context)); } else { node = ts.visitEachChild(node, visitor, context); @@ -76900,7 +79500,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 285 && defaultClauseIndex === -1) { + if (clause.kind === 286 && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -76910,7 +79510,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 284) { + if (clause.kind === 285) { if (containsYield(clause.expression) && pendingClauses.length > 0) { break; } @@ -77001,7 +79601,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 262144) !== 0; + return !!node && (node.transformFlags & 524288) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -77033,10 +79633,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_5 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); - ts.setSourceMapRange(clone_5, node); - ts.setCommentRange(clone_5, node); - return clone_5; + var clone_6 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -77716,11 +80316,11 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(78); - context.enableSubstitution(216); - context.enableSubstitution(214); + context.enableSubstitution(217); context.enableSubstitution(215); - context.enableSubstitution(289); - context.enableEmitNotification(297); + context.enableSubstitution(216); + context.enableSubstitution(290); + context.enableEmitNotification(298); var moduleInfoMap = []; var deferredExports = []; var currentSourceFile; @@ -77731,7 +80331,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 2097152 || + node.transformFlags & 4194304 || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && ts.outFile(compilerOptions)))) { return node; } @@ -77914,30 +80514,30 @@ var ts; } function sourceElementVisitor(node) { switch (node.kind) { - case 261: + case 262: return visitImportDeclaration(node); - case 260: + case 261: return visitImportEqualsDeclaration(node); - case 267: + case 268: return visitExportDeclaration(node); - case 266: + case 267: return visitExportAssignment(node); - case 232: + case 233: return visitVariableStatement(node); - case 251: - return visitFunctionDeclaration(node); case 252: + return visitFunctionDeclaration(node); + case 253: return visitClassDeclaration(node); - case 338: + case 342: return visitMergeDeclarationMarker(node); - case 339: + case 343: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); } } function moduleExpressionElementVisitor(node) { - if (!(node.transformFlags & 2097152) && !(node.transformFlags & 1024)) { + if (!(node.transformFlags & 4194304) && !(node.transformFlags & 2048)) { return node; } if (ts.isImportCall(node)) { @@ -77955,24 +80555,24 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; switch (elem.kind) { - case 288: + case 289: if (destructuringNeedsFlattening(elem.initializer)) { return true; } break; - case 289: + case 290: if (destructuringNeedsFlattening(elem.name)) { return true; } break; - case 290: + case 291: if (destructuringNeedsFlattening(elem.expression)) { return true; } break; - case 165: - case 167: + case 166: case 168: + case 169: return false; default: ts.Debug.assertNever(elem, "Unhandled object member kind"); } @@ -78006,7 +80606,7 @@ var ts; var externalModuleName = ts.getExternalModuleNameLiteral(factory, node, currentSourceFile, host, resolver, compilerOptions); var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument; - var containsLexicalThis = !!(node.transformFlags & 4096); + var containsLexicalThis = !!(node.transformFlags & 8192); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -78324,7 +80924,7 @@ var ts; } } function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 232) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 233) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -78356,10 +80956,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 263: + case 264: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 264: + case 265: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding, true); @@ -78474,7 +81074,7 @@ var ts; return node; } function onEmitNode(hint, node, emitCallback) { - if (node.kind === 297) { + if (node.kind === 298) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -78516,10 +81116,10 @@ var ts; switch (node.kind) { case 78: return substituteExpressionIdentifier(node); - case 216: + case 217: return substituteBinaryExpression(node); + case 216: case 215: - case 214: return substituteUnaryExpression(node); } return node; @@ -78533,9 +81133,9 @@ var ts; } return node; } - if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64)) && !ts.isLocalName(node)) { + else if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64)) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 297) { + if (exportContainer && exportContainer.kind === 298) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), node); } var importDeclaration = resolver.getReferencedImportDeclaration(node); @@ -78578,14 +81178,20 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 215 - ? ts.setTextRange(factory.createBinaryExpression(node.operand, factory.createToken(node.operator === 45 ? 63 : 64), factory.createNumericLiteral(1)), node) + var expression = node.kind === 216 + ? ts.setTextRange(factory.createPrefixUnaryExpression(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { var exportName = exportedNames_3[_i]; noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression); } + if (node.kind === 216) { + noSubstitution[ts.getNodeId(expression)] = true; + expression = node.operator === 45 + ? factory.createSubtract(expression, factory.createNumericLiteral(1)) + : factory.createAdd(expression, factory.createNumericLiteral(1)); + } return expression; } } @@ -78621,12 +81227,12 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(78); - context.enableSubstitution(289); - context.enableSubstitution(216); - context.enableSubstitution(214); + context.enableSubstitution(290); + context.enableSubstitution(217); context.enableSubstitution(215); - context.enableSubstitution(226); - context.enableEmitNotification(297); + context.enableSubstitution(216); + context.enableSubstitution(227); + context.enableEmitNotification(298); var moduleInfoMap = []; var deferredExports = []; var exportFunctionsMap = []; @@ -78641,7 +81247,7 @@ var ts; var noSubstitution; return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 2097152)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 4194304)) { return node; } var id = ts.getOriginalNodeId(node); @@ -78715,7 +81321,7 @@ var ts; ts.addRange(statements, hoistedStatements); ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); - var modifiers = node.transformFlags & 524288 ? + var modifiers = node.transformFlags & 1048576 ? factory.createModifiersFromModifierFlags(256) : undefined; var moduleObject = factory.createObjectLiteralExpression([ @@ -78733,7 +81339,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 267 && externalImport.exportClause) { + if (externalImport.kind === 268 && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -78794,15 +81400,15 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(factory, entry, currentSourceFile); switch (entry.kind) { - case 261: + case 262: if (!entry.importClause) { break; } - case 260: + case 261: ts.Debug.assert(importVariableName !== undefined); statements.push(factory.createExpressionStatement(factory.createAssignment(importVariableName, parameterName))); break; - case 267: + case 268: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { if (ts.isNamedExports(entry.exportClause)) { @@ -78832,13 +81438,13 @@ var ts; } function sourceElementVisitor(node) { switch (node.kind) { - case 261: + case 262: return visitImportDeclaration(node); - case 260: + case 261: return visitImportEqualsDeclaration(node); - case 267: + case 268: return visitExportDeclaration(node); - case 266: + case 267: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -78963,7 +81569,7 @@ var ts; } function shouldHoistVariableDeclarationList(node) { return (ts.getEmitFlags(node) & 2097152) === 0 - && (enclosingBlockScopedContainer.kind === 297 + && (enclosingBlockScopedContainer.kind === 298 || (ts.getOriginalNode(node).flags & 3) === 0); } function transformInitializedVariable(node, isExportedDeclaration) { @@ -78985,7 +81591,7 @@ var ts; : preventSubstitution(ts.setTextRange(factory.createAssignment(name, value), location)); } function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 232) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 233) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasSyntacticModifier(node.original, 1); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -79024,10 +81630,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 263: + case 264: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 264: + case 265: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -79127,43 +81733,43 @@ var ts; } function nestedElementVisitor(node) { switch (node.kind) { - case 232: + case 233: return visitVariableStatement(node); - case 251: - return visitFunctionDeclaration(node); case 252: + return visitFunctionDeclaration(node); + case 253: return visitClassDeclaration(node); - case 237: - return visitForStatement(node); case 238: - return visitForInStatement(node); + return visitForStatement(node); case 239: + return visitForInStatement(node); + case 240: return visitForOfStatement(node); - case 235: - return visitDoStatement(node); case 236: + return visitDoStatement(node); + case 237: return visitWhileStatement(node); - case 245: + case 246: return visitLabeledStatement(node); - case 243: - return visitWithStatement(node); case 244: + return visitWithStatement(node); + case 245: return visitSwitchStatement(node); - case 258: + case 259: return visitCaseBlock(node); - case 284: - return visitCaseClause(node); case 285: + return visitCaseClause(node); + case 286: return visitDefaultClause(node); - case 247: + case 248: return visitTryStatement(node); - case 287: + case 288: return visitCatchClause(node); - case 230: + case 231: return visitBlock(node); - case 338: + case 342: return visitMergeDeclarationMarker(node); - case 339: + case 343: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -79172,21 +81778,21 @@ var ts; function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory.updateForStatement(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + node = factory.updateForStatement(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } function visitForInStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory.updateForInStatement(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); + node = factory.updateForInStatement(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } function visitForOfStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory.updateForOfStatement(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); + node = factory.updateForOfStatement(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -79211,10 +81817,10 @@ var ts; } } function visitDoStatement(node) { - return factory.updateDoStatement(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); + return factory.updateDoStatement(node, ts.visitIterationBody(node.statement, nestedElementVisitor, context), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); } function visitWhileStatement(node) { - return factory.updateWhileStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); + return factory.updateWhileStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); } function visitLabeledStatement(node) { return factory.updateLabeledStatement(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); @@ -79262,7 +81868,7 @@ var ts; else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 1024) || (node.transformFlags & 2097152)) { + else if ((node.transformFlags & 2048) || (node.transformFlags & 4194304)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -79302,7 +81908,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 297; + return container !== undefined && container.kind === 298; } else { return false; @@ -79317,7 +81923,7 @@ var ts; return node; } function onEmitNode(hint, node, emitCallback) { - if (node.kind === 297) { + if (node.kind === 298) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -79353,7 +81959,7 @@ var ts; } function substituteUnspecified(node) { switch (node.kind) { - case 289: + case 290: return substituteShorthandPropertyAssignment(node); } return node; @@ -79378,12 +81984,12 @@ var ts; switch (node.kind) { case 78: return substituteExpressionIdentifier(node); - case 216: + case 217: return substituteBinaryExpression(node); - case 214: case 215: + case 216: return substituteUnaryExpression(node); - case 226: + case 227: return substituteMetaProperty(node); } return node; @@ -79436,14 +82042,14 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 215 + var expression = node.kind === 216 ? ts.setTextRange(factory.createPrefixUnaryExpression(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 215) { + if (node.kind === 216) { expression = node.operator === 45 ? factory.createSubtract(preventSubstitution(expression), factory.createNumericLiteral(1)) : factory.createAdd(preventSubstitution(expression), factory.createNumericLiteral(1)); @@ -79466,7 +82072,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, false); - if (exportContainer && exportContainer.kind === 297) { + if (exportContainer && exportContainer.kind === 298) { exportedNames = ts.append(exportedNames, factory.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -79495,7 +82101,7 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(297); + context.enableEmitNotification(298); context.enableSubstitution(78); var helperNameSubstitutions; return ts.chainBundle(context, transformSourceFile); @@ -79527,11 +82133,11 @@ var ts; } function visitor(node) { switch (node.kind) { - case 260: + case 261: return undefined; - case 266: - return visitExportAssignment(node); case 267: + return visitExportAssignment(node); + case 268: var exportDecl = node; return visitExportDeclaration(exportDecl); } @@ -79606,7 +82212,8 @@ var ts; ts.isTypeAliasDeclaration(node) || ts.isConstructorDeclaration(node) || ts.isIndexSignatureDeclaration(node) || - ts.isPropertyAccessExpression(node); + ts.isPropertyAccessExpression(node) || + ts.isJSDocTypeAlias(node); } ts.canProduceDiagnostics = canProduceDiagnostics; function createGetSymbolAccessibilityDiagnosticForNodeName(node) { @@ -79635,7 +82242,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 252) { + else if (node.parent.kind === 253) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -79664,7 +82271,7 @@ var ts; ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 252) { + else if (node.parent.kind === 253) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -79704,22 +82311,22 @@ var ts; else if (ts.isImportEqualsDeclaration(node)) { return getImportEntityNameVisibilityError; } - else if (ts.isTypeAliasDeclaration(node)) { + else if (ts.isTypeAliasDeclaration(node) || ts.isJSDocTypeAlias(node)) { return getTypeAliasDeclarationVisibilityError; } else { return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 249 || node.kind === 198) { + if (node.kind === 250 || node.kind === 199) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } - else if (node.kind === 163 || node.kind === 201 || node.kind === 162 || - (node.kind === 160 && ts.hasSyntacticModifier(node.parent, 8))) { + else if (node.kind === 164 || node.kind === 202 || node.kind === 163 || + (node.kind === 161 && ts.hasSyntacticModifier(node.parent, 8))) { if (ts.hasSyntacticModifier(node, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -79727,7 +82334,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 252 || node.kind === 160) { + else if (node.parent.kind === 253 || node.kind === 161) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -79751,7 +82358,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (node.kind === 168) { + if (node.kind === 169) { if (ts.hasSyntacticModifier(node, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : @@ -79788,23 +82395,23 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 170: + case 171: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 169: + case 170: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 171: + case 172: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; + case 166: case 165: - case 164: if (ts.hasSyntacticModifier(node, 32)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -79812,7 +82419,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 252) { + else if (node.parent.kind === 253) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -79825,7 +82432,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 251: + case 252: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -79850,27 +82457,27 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 166: + case 167: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 170: - case 175: + case 171: + case 176: return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 169: + case 170: return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 171: + case 172: return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + case 166: case 165: - case 164: if (ts.hasSyntacticModifier(node.parent, 32)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? @@ -79878,7 +82485,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 252) { + else if (node.parent.parent.kind === 253) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -79890,15 +82497,15 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 251: - case 174: + case 252: + case 175: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; + case 169: case 168: - case 167: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -79911,39 +82518,39 @@ var ts; function getTypeParameterConstraintVisibilityError() { var diagnosticMessage; switch (node.parent.kind) { - case 252: + case 253: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 253: + case 254: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 190: + case 191: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1; break; - case 175: - case 170: + case 176: + case 171: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 169: + case 170: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; + case 166: case 165: - case 164: if (ts.hasSyntacticModifier(node.parent, 32)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 252) { + else if (node.parent.parent.kind === 253) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 174: - case 251: + case 175: + case 252: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 254: + case 255: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -79979,11 +82586,13 @@ var ts; typeName: node.name }; } - function getTypeAliasDeclarationVisibilityError() { + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name + diagnosticMessage: symbolAccessibilityResult.errorModuleName + ? ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2 + : ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: ts.isJSDocTypeAlias(node) ? ts.Debug.checkDefined(node.typeExpression) : node.type, + typeName: ts.isJSDocTypeAlias(node) ? ts.getNameOfDeclaration(node) : node.name, }; } } @@ -80003,7 +82612,7 @@ var ts; } function isInternalDeclaration(node, currentSourceFile) { var parseTreeNode = ts.getParseTreeNode(node); - if (parseTreeNode && parseTreeNode.kind === 160) { + if (parseTreeNode && parseTreeNode.kind === 161) { var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode); var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined; var text = currentSourceFile.text; @@ -80055,6 +82664,7 @@ var ts; reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; + var errorFallbackNode; var currentSourceFile; var refs; var libs; @@ -80119,8 +82729,8 @@ var ts; recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } function reportInaccessibleUniqueSymbolError() { @@ -80144,35 +82754,38 @@ var ts; } } function reportTruncationError() { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); } } function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { - var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); + var _a; + var primaryDeclaration = (_a = parentSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; }); - for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { - var augmentations = augmentingDeclarations_1[_i]; - context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + if (augmentingDeclarations) { + for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { + var augmentations = augmentingDeclarations_1[_i]; + context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + } } } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; - getSymbolAccessibilityDiagnostic = function (s) { return ({ + getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ diagnosticMessage: s.errorModuleName ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit, errorNode: s.errorNode || sourceFile - }); }; + })); }; var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled); getSymbolAccessibilityDiagnostic = oldDiag; return result; } function transformRoot(node) { - if (node.kind === 297 && node.isDeclarationFile) { + if (node.kind === 298 && node.isDeclarationFile) { return node; } - if (node.kind === 298) { + if (node.kind === 299) { isBundledEmit = true; refs = new ts.Map(); libs = new ts.Map(); @@ -80202,7 +82815,7 @@ var ts; var updated = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements); return factory.updateSourceFile(sourceFile, transformAndReplaceLatePaintedStatements(updated), true, [], [], false, []); }), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 300) { + if (prepend.kind === 301) { var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal); hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib; collectReferences(sourceFile, refs); @@ -80292,7 +82905,7 @@ var ts; declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { - var specifier = ts.moduleSpecifiers.getModuleSpecifier(__assign(__assign({}, options), { baseUrl: options.baseUrl && ts.toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }), currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, undefined); + var specifier = ts.moduleSpecifiers.getModuleSpecifier(options, currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, undefined); if (!ts.pathIsRelative(specifier)) { recordTypeReferenceDirectivesIfNecessary([specifier]); return; @@ -80334,7 +82947,7 @@ var ts; return name; } else { - if (name.kind === 197) { + if (name.kind === 198) { return factory.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); } else { @@ -80342,7 +82955,7 @@ var ts; } } function visitBindingElement(elem) { - if (elem.kind === 222) { + if (elem.kind === 223) { return elem; } return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); @@ -80376,7 +82989,7 @@ var ts; if (shouldPrintWithInitializer(node)) { return; } - var shouldUseResolverType = node.kind === 160 && + var shouldUseResolverType = node.kind === 161 && (resolver.isRequiredInitializedParameter(node) || resolver.isOptionalUninitializedParameterProperty(node)); if (type && !shouldUseResolverType) { @@ -80385,7 +82998,7 @@ var ts; if (!ts.getParseTreeNode(node)) { return type ? ts.visitNode(type, visitDeclarationSubtree) : factory.createKeywordTypeNode(128); } - if (node.kind === 168) { + if (node.kind === 169) { return factory.createKeywordTypeNode(128); } errorNameNode = node.name; @@ -80394,12 +83007,12 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); } - if (node.kind === 249 || node.kind === 198) { + if (node.kind === 250 || node.kind === 199) { return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } - if (node.kind === 160 - || node.kind === 163 - || node.kind === 162) { + if (node.kind === 161 + || node.kind === 164 + || node.kind === 163) { if (!node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); @@ -80416,19 +83029,19 @@ var ts; function isDeclarationAndNotVisible(node) { node = ts.getParseTreeNode(node); switch (node.kind) { - case 251: - case 256: - case 253: case 252: + case 257: case 254: + case 253: case 255: + case 256: return !resolver.isDeclarationVisible(node); - case 249: + case 250: return !getBindingNameVisible(node); - case 260: case 261: + case 262: + case 268: case 267: - case 266: return false; } return false; @@ -80505,7 +83118,7 @@ var ts; function rewriteModuleSpecifier(parent, input) { if (!input) return undefined; - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 256 && parent.kind !== 195); + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 257 && parent.kind !== 196); if (ts.isStringLiteralLike(input)) { if (isBundledEmit) { var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); @@ -80525,7 +83138,7 @@ var ts; function transformImportEqualsDeclaration(decl) { if (!resolver.isDeclarationVisible(decl)) return; - if (decl.moduleReference.kind === 272) { + if (decl.moduleReference.kind === 273) { var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); return factory.updateImportEqualsDeclaration(decl, undefined, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); } @@ -80545,7 +83158,7 @@ var ts; if (!decl.importClause.namedBindings) { return visibleDefaultBinding && factory.updateImportDeclaration(decl, undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } - if (decl.importClause.namedBindings.kind === 263) { + if (decl.importClause.namedBindings.kind === 264) { var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : undefined; return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; } @@ -80612,7 +83225,7 @@ var ts; var oldDiag = getSymbolAccessibilityDiagnostic; var canProduceDiagnostic = ts.canProduceDiagnostics(input); var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; - var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 177 || input.kind === 190) && input.parent.kind !== 254); + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 178 || input.kind === 191) && input.parent.kind !== 255); if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { if (ts.hasEffectiveModifier(input, 8)) { if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) @@ -80631,67 +83244,67 @@ var ts; } if (isProcessedComponent(input)) { switch (input.kind) { - case 223: { + case 224: { if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { checkEntityNameVisibility(input.expression, enclosingDeclaration); } var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(factory.updateExpressionWithTypeArguments(node, node.expression, node.typeArguments)); } - case 173: { + case 174: { checkEntityNameVisibility(input.typeName, enclosingDeclaration); var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(factory.updateTypeReferenceNode(node, node.typeName, node.typeArguments)); } - case 170: + case 171: return cleanup(factory.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); - case 166: { + case 167: { var ctor = factory.createConstructorDeclaration(undefined, ensureModifiers(input), updateParamsList(input, input.parameters, 0), undefined); return cleanup(ctor); } - case 165: { + case 166: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(undefined); } var sig = factory.createMethodDeclaration(undefined, ensureModifiers(input), undefined, input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined); return cleanup(sig); } - case 167: { + case 168: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(undefined); } var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input)); return cleanup(factory.updateGetAccessorDeclaration(input, undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8)), ensureType(input, accessorType), undefined)); } - case 168: { + case 169: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(undefined); } return cleanup(factory.updateSetAccessorDeclaration(input, undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8)), undefined)); } - case 163: + case 164: if (ts.isPrivateIdentifier(input.name)) { return cleanup(undefined); } return cleanup(factory.updatePropertyDeclaration(input, undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); - case 162: + case 163: if (ts.isPrivateIdentifier(input.name)) { return cleanup(undefined); } return cleanup(factory.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type))); - case 164: { + case 165: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(undefined); } return cleanup(factory.updateMethodSignature(input, ensureModifiers(input), input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 169: { + case 170: { return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 171: { + case 172: { return cleanup(factory.updateIndexSignature(input, undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(128))); } - case 249: { + case 250: { if (ts.isBindingPattern(input.name)) { return recreateBindingPattern(input.name); } @@ -80699,13 +83312,13 @@ var ts; suppressNewDiagnosticContexts = true; return cleanup(factory.updateVariableDeclaration(input, input.name, undefined, ensureType(input, input.type), ensureNoInitializer(input))); } - case 159: { + case 160: { if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { return cleanup(factory.updateTypeParameterDeclaration(input, input.name, undefined, undefined)); } return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); } - case 184: { + case 185: { var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree); var oldEnclosingDecl = enclosingDeclaration; @@ -80715,13 +83328,13 @@ var ts; var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); return cleanup(factory.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); } - case 174: { + case 175: { return cleanup(factory.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 175: { + case 176: { return cleanup(factory.updateConstructorTypeNode(input, ensureModifiers(input), ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 195: { + case 196: { if (!ts.isLiteralImportTypeNode(input)) return cleanup(input); return cleanup(factory.updateImportTypeNode(input, factory.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); @@ -80753,7 +83366,7 @@ var ts; } } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 165 && ts.hasEffectiveModifier(node.parent, 8); + return node.parent.kind === 166 && ts.hasEffectiveModifier(node.parent, 8); } function visitDeclarationStatements(input) { if (!isPreservedDeclarationStatement(input)) { @@ -80762,14 +83375,14 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 267: { + case 268: { if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; } resultHasScopeMarker = true; return factory.updateExportDeclaration(input, undefined, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); } - case 266: { + case 267: { if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; } @@ -80783,7 +83396,9 @@ var ts; diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: input }); }; + errorFallbackNode = input; var varDecl = factory.createVariableDeclaration(newId, undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), undefined); + errorFallbackNode = undefined; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133)] : [], factory.createVariableDeclarationList([varDecl], 2)); return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } @@ -80797,17 +83412,17 @@ var ts; if (ts.isImportEqualsDeclaration(statement) || ts.hasEffectiveModifier(statement, 512) || !ts.canHaveModifiers(statement)) { return statement; } - var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (11263 ^ 1)); + var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (27647 ^ 1)); return factory.updateModifiers(statement, modifiers); } function transformTopLevelDeclaration(input) { if (shouldStripInternal(input)) return; switch (input.kind) { - case 260: { + case 261: { return transformImportEqualsDeclaration(input); } - case 261: { + case 262: { return transformImportDeclaration(input); } } @@ -80827,12 +83442,12 @@ var ts; } var previousNeedsDeclare = needsDeclare; switch (input.kind) { - case 254: + case 255: return cleanup(factory.updateTypeAliasDeclaration(input, undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); - case 253: { + case 254: { return cleanup(factory.updateInterfaceDeclaration(input, undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } - case 251: { + case 252: { var clean = cleanup(factory.updateFunctionDeclaration(input, undefined, ensureModifiers(input), undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined)); if (clean && resolver.isExpandoFunctionDeclaration(input)) { var props = resolver.getPropertiesOfContainerFunction(input); @@ -80842,7 +83457,7 @@ var ts; fakespace_1.symbol = props[0].parent; var exportMappings_1 = []; var declarations = ts.mapDefined(props, function (p) { - if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + if (!p.valueDeclaration || !ts.isPropertyAccessExpression(p.valueDeclaration)) { return undefined; } getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration); @@ -80884,10 +83499,10 @@ var ts; return clean; } } - case 256: { + case 257: { needsDeclare = false; var inner = input.body; - if (inner && inner.kind === 257) { + if (inner && inner.kind === 258) { var oldNeedsScopeFix = needsScopeFixMarker; var oldHasScopeFix = resultHasScopeMarker; resultHasScopeMarker = false; @@ -80923,7 +83538,9 @@ var ts; return cleanup(factory.updateModuleDeclaration(input, undefined, mods, input.name, body)); } } - case 252: { + case 253: { + errorNameNode = input.name; + errorFallbackNode = input; var modifiers = factory.createNodeArray(ensureModifiers(input)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -80931,7 +83548,7 @@ var ts; if (ctor) { var oldDiag_1 = getSymbolAccessibilityDiagnostic; parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { - if (!ts.hasSyntacticModifier(param, 92) || shouldStripInternal(param)) + if (!ts.hasSyntacticModifier(param, 16476) || shouldStripInternal(param)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 78) { @@ -80991,10 +83608,10 @@ var ts; return cleanup(factory.updateClassDeclaration(input, undefined, modifiers, input.name, typeParameters, heritageClauses, members)); } } - case 232: { + case 233: { return cleanup(transformVariableStatement(input)); } - case 255: { + case 256: { return cleanup(factory.updateEnumDeclaration(input, undefined, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; @@ -81011,12 +83628,14 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 256) { + if (input.kind === 257) { needsDeclare = previousNeedsDeclare; } if (node === input) { return node; } + errorFallbackNode = undefined; + errorNameNode = undefined; return node && ts.setOriginalNode(preserveJsDoc(node, input), input); } } @@ -81032,7 +83651,7 @@ var ts; return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); } function recreateBindingElement(e) { - if (e.kind === 222) { + if (e.kind === 223) { return; } if (e.name) { @@ -81080,9 +83699,9 @@ var ts; return factory.createModifiersFromModifierFlags(newFlags); } function ensureModifierFlags(node) { - var mask = 11263 ^ (4 | 256); + var mask = 27647 ^ (4 | 256 | 16384); var additions = (needsDeclare && !isAlwaysType(node)) ? 2 : 0; - var parentIsFile = node.parent.kind === 297; + var parentIsFile = node.parent.kind === 298; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { mask ^= 2; additions = 0; @@ -81109,7 +83728,7 @@ var ts; } ts.transformDeclarations = transformDeclarations; function isAlwaysType(node) { - if (node.kind === 253) { + if (node.kind === 254) { return true; } return false; @@ -81118,7 +83737,7 @@ var ts; return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); } function maskModifierFlags(node, modifierMask, modifierAdditions) { - if (modifierMask === void 0) { modifierMask = 11263 ^ 4; } + if (modifierMask === void 0) { modifierMask = 27647 ^ 4; } if (modifierAdditions === void 0) { modifierAdditions = 0; } var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions; if (flags & 512 && !(flags & 1)) { @@ -81131,7 +83750,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 167 + return accessor.kind === 168 ? accessor.type : accessor.parameters.length > 0 ? accessor.parameters[0].type @@ -81140,52 +83759,52 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { + case 164: case 163: - case 162: return !ts.hasEffectiveModifier(node, 8); - case 160: - case 249: + case 161: + case 250: return true; } return false; } function isPreservedDeclarationStatement(node) { switch (node.kind) { - case 251: - case 256: - case 260: - case 253: case 252: + case 257: + case 261: case 254: + case 253: case 255: - case 232: - case 261: + case 256: + case 233: + case 262: + case 268: case 267: - case 266: return true; } return false; } function isProcessedComponent(node) { switch (node.kind) { - case 170: - case 166: - case 165: + case 171: case 167: + case 166: case 168: - case 163: - case 162: - case 164: case 169: - case 171: - case 249: - case 159: - case 223: - case 173: - case 184: + case 164: + case 163: + case 165: + case 170: + case 172: + case 250: + case 160: + case 224: case 174: + case 185: case 175: - case 195: + case 176: + case 196: return true; } return false; @@ -81228,6 +83847,9 @@ var ts; if (languageVersion < 99) { transformers.push(ts.transformESNext); } + if (languageVersion < 8) { + transformers.push(ts.transformES2021); + } if (languageVersion < 7) { transformers.push(ts.transformES2020); } @@ -81286,7 +83908,7 @@ var ts; } ts.noEmitNotification = noEmitNotification; function transformNodes(resolver, host, factory, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(341); + var enabledSyntaxKindFeatures = new Array(345); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentStatements; @@ -81297,6 +83919,9 @@ var ts; var lexicalEnvironmentFlagsStack = []; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; + var blockScopedVariableDeclarationsStack = []; + var blockScopeStackOffset = 0; + var blockScopedVariableDeclarations; var emitHelpers; var onSubstituteNode = noEmitSubstitution; var onEmitNode = noEmitNotification; @@ -81317,6 +83942,9 @@ var ts; hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, addInitializationStatement: addInitializationStatement, + startBlockScope: startBlockScope, + endBlockScope: endBlockScope, + addBlockScopedVariable: addBlockScopedVariable, requestEmitHelper: requestEmitHelper, readEmitHelpers: readEmitHelpers, enableSubstitution: enableSubstitution, @@ -81356,9 +83984,9 @@ var ts; var transformed = []; for (var _a = 0, nodes_3 = nodes; _a < nodes_3.length; _a++) { var node = nodes_3[_a]; - ts.tracing.push("emit", "transformNodes", node.kind === 297 ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit", "transformNodes", node.kind === 298 ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); transformed.push((allowDtsFiles ? transformation : transformRoot)(node)); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } state = 2; ts.performance.mark("afterTransform"); @@ -81518,6 +84146,31 @@ var ts; function getLexicalEnvironmentFlags() { return lexicalEnvironmentFlags; } + function startBlockScope() { + ts.Debug.assert(state > 0, "Cannot start a block scope during initialization."); + ts.Debug.assert(state < 2, "Cannot start a block scope after transformation has completed."); + blockScopedVariableDeclarationsStack[blockScopeStackOffset] = blockScopedVariableDeclarations; + blockScopeStackOffset++; + blockScopedVariableDeclarations = undefined; + } + function endBlockScope() { + ts.Debug.assert(state > 0, "Cannot end a block scope during initialization."); + ts.Debug.assert(state < 2, "Cannot end a block scope after transformation has completed."); + var statements = ts.some(blockScopedVariableDeclarations) ? + [ + factory.createVariableStatement(undefined, factory.createVariableDeclarationList(blockScopedVariableDeclarations.map(function (identifier) { return factory.createVariableDeclaration(identifier); }), 1)) + ] : undefined; + blockScopeStackOffset--; + blockScopedVariableDeclarations = blockScopedVariableDeclarationsStack[blockScopeStackOffset]; + if (blockScopeStackOffset === 0) { + blockScopedVariableDeclarationsStack = []; + } + return statements; + } + function addBlockScopedVariable(name) { + ts.Debug.assert(blockScopeStackOffset > 0, "Cannot add a block scoped variable outside of an iteration body."); + (blockScopedVariableDeclarations || (blockScopedVariableDeclarations = [])).push(name); + } function requestEmitHelper(helper) { ts.Debug.assert(state > 0, "Cannot modify the transformation context during initialization."); ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); @@ -81556,35 +84209,37 @@ var ts; } ts.transformNodes = transformNodes; ts.nullTransformationContext = { - get factory() { return ts.factory; }, - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: ts.returnUndefined, + factory: ts.factory, getCompilerOptions: function () { return ({}); }, - getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + getEmitHost: ts.notImplemented, getEmitHelperFactory: ts.notImplemented, + startLexicalEnvironment: ts.noop, + resumeLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop, + endLexicalEnvironment: ts.returnUndefined, setLexicalEnvironmentFlags: ts.noop, getLexicalEnvironmentFlags: function () { return 0; }, - hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + hoistFunctionDeclaration: ts.noop, addInitializationStatement: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, + startBlockScope: ts.noop, + endBlockScope: ts.returnUndefined, + addBlockScopedVariable: ts.noop, requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop, + readEmitHelpers: ts.notImplemented, + enableSubstitution: ts.noop, + enableEmitNotification: ts.noop, + isSubstitutionEnabled: ts.notImplemented, + isEmitNotificationEnabled: ts.notImplemented, + onSubstituteNode: noEmitSubstitution, + onEmitNode: noEmitNotification, addDiagnostic: ts.noop, }; })(ts || (ts = {})); var ts; (function (ts) { var brackets = createBracketsMap(); - var syntheticParent = { pos: -1, end: -1 }; function isBuildInfoFile(file) { return ts.fileExtensionIs(file, ".tsbuildinfo"); } @@ -81657,7 +84312,7 @@ var ts; ts.getOutputPathsForBundle = getOutputPathsForBundle; function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); - if (sourceFile.kind === 298) { + if (sourceFile.kind === 299) { return getOutputPathsForBundle(options, forceDtsPaths); } else { @@ -81864,15 +84519,15 @@ var ts; sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); }) }; } - ts.tracing.push("emit", "emitJsFileOrBundle", { jsFilePath: jsFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit", "emitJsFileOrBundle", { jsFilePath: jsFilePath }); emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit", "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit", "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit", "emitBuildInfo", { buildInfoPath: buildInfoPath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit", "emitBuildInfo", { buildInfoPath: buildInfoPath }); emitBuildInfo(bundleBuildInfo, buildInfoPath); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { if (jsFilePath) { @@ -81987,12 +84642,12 @@ var ts; if (!declBlocked || forceDtsEmit) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, { - sourceMap: compilerOptions.declarationMap, + sourceMap: !forceDtsEmit && compilerOptions.declarationMap, sourceRoot: compilerOptions.sourceRoot, mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, }); - if (forceDtsEmit && declarationTransform.transformed[0].kind === 297) { + if (forceDtsEmit && declarationTransform.transformed[0].kind === 298) { var sourceFile = declarationTransform.transformed[0]; exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; } @@ -82015,8 +84670,8 @@ var ts; ts.forEachChild(node, collectLinkedAliases); } function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) { - var bundle = sourceFileOrBundle.kind === 298 ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 297 ? sourceFileOrBundle : undefined; + var bundle = sourceFileOrBundle.kind === 299 ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 298 ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; var sourceMapGenerator; if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { @@ -82054,7 +84709,7 @@ var ts; } function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { return (mapOptions.sourceMap || mapOptions.inlineSourceMap) - && (sourceFileOrBundle.kind !== 297 || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json")); + && (sourceFileOrBundle.kind !== 298 || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json")); } function getSourceRoot(mapOptions) { var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || ""); @@ -82100,7 +84755,7 @@ var ts; } ts.emitFiles = emitFiles; function getBuildInfoText(buildInfo) { - return JSON.stringify(buildInfo, undefined, 2); + return JSON.stringify(buildInfo); } ts.getBuildInfoText = getBuildInfoText; function getBuildInfo(buildInfoText) { @@ -82263,7 +84918,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = ts.getNewLineCharacter(printerOptions); var moduleKind = ts.getEmitModuleKind(printerOptions); @@ -82300,9 +84955,11 @@ var ts; var detachedCommentsInfo; var hasWrittenComment = false; var commentsDisabled = !!printerOptions.removeComments; - var lastNode; var lastSubstitution; + var currentParenthesizerRule; var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; + var parenthesizer = ts.factory.parenthesizer; + var emitBinaryExpression = createEmitBinaryExpression(); reset(); return { printNode: printNode, @@ -82328,9 +84985,9 @@ var ts; break; } switch (node.kind) { - case 297: return printFile(node); - case 298: return printBundle(node); - case 299: return printUnparsedSource(node); + case 298: return printFile(node); + case 299: return printBundle(node); + case 300: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -82364,7 +85021,7 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - emitList(syntheticParent, nodes, format); + emitList(undefined, nodes, format); reset(); writer = previousWriter; } @@ -82497,7 +85154,7 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - pipelineEmit(hint, node); + pipelineEmit(hint, node, undefined); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -82525,51 +85182,54 @@ var ts; currentSourceFile = undefined; currentLineMap = undefined; detachedCommentsInfo = undefined; - lastNode = undefined; - lastSubstitution = undefined; setWriter(undefined, undefined); } function getCurrentLineMap() { return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); } - function emit(node) { + function emit(node, parenthesizerRule) { if (node === undefined) return; var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node); - var substitute = pipelineEmit(4, node); + pipelineEmit(4, node, parenthesizerRule); recordBundleFileInternalSectionEnd(prevSourceFileTextKind); - return substitute; } function emitIdentifierName(node) { if (node === undefined) return; - return pipelineEmit(2, node); + pipelineEmit(2, node, undefined); } - function emitExpression(node) { + function emitExpression(node, parenthesizerRule) { if (node === undefined) return; - return pipelineEmit(1, node); + pipelineEmit(1, node, parenthesizerRule); } function emitJsxAttributeValue(node) { - return pipelineEmit(ts.isStringLiteral(node) ? 6 : 4, node); + pipelineEmit(ts.isStringLiteral(node) ? 6 : 4, node); } - function pipelineEmit(emitHint, node) { - var savedLastNode = lastNode; - var savedLastSubstitution = lastSubstitution; - var savedPreserveSourceNewlines = preserveSourceNewlines; - lastNode = node; - lastSubstitution = undefined; - if (preserveSourceNewlines && !!(ts.getEmitFlags(node) & 134217728)) { + function beforeEmitNode(node) { + if (preserveSourceNewlines && (ts.getEmitFlags(node) & 134217728)) { preserveSourceNewlines = false; } + } + function afterEmitNode(savedPreserveSourceNewlines) { + preserveSourceNewlines = savedPreserveSourceNewlines; + } + function pipelineEmit(emitHint, node, parenthesizerRule) { + currentParenthesizerRule = parenthesizerRule; var pipelinePhase = getPipelinePhase(0, emitHint, node); pipelinePhase(emitHint, node); - ts.Debug.assert(lastNode === node); - var substitute = lastSubstitution; - lastNode = savedLastNode; - lastSubstitution = savedLastSubstitution; - preserveSourceNewlines = savedPreserveSourceNewlines; - return substitute || node; + currentParenthesizerRule = undefined; + } + function shouldEmitComments(node) { + return !commentsDisabled && !ts.isSourceFile(node); + } + function shouldEmitSourceMaps(node) { + return !sourceMapsDisabled && + !ts.isSourceFile(node) && + !ts.isInJsonFile(node) && + !ts.isUnparsedSource(node) && + !ts.isUnparsedPrepend(node); } function getPipelinePhase(phase, emitHint, node) { switch (phase) { @@ -82578,16 +85238,19 @@ var ts; return pipelineEmitWithNotification; } case 1: - if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) { + if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) { + if (currentParenthesizerRule) { + lastSubstitution = currentParenthesizerRule(lastSubstitution); + } return pipelineEmitWithSubstitution; } case 2: - if (!commentsDisabled && node.kind !== 297) { + if (shouldEmitComments(node)) { return pipelineEmitWithComments; } case 3: - if (!sourceMapsDisabled && node.kind !== 297 && !ts.isInJsonFile(node)) { - return pipelineEmitWithSourceMap; + if (shouldEmitSourceMaps(node)) { + return pipelineEmitWithSourceMaps; } case 4: return pipelineEmitWithHint; @@ -82599,13 +85262,24 @@ var ts; return getPipelinePhase(currentPhase + 1, emitHint, node); } function pipelineEmitWithNotification(hint, node) { - ts.Debug.assert(lastNode === node); var pipelinePhase = getNextPipelinePhase(0, hint, node); onEmitNode(hint, node, pipelinePhase); - ts.Debug.assert(lastNode === node); } function pipelineEmitWithHint(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (preserveSourceNewlines) { + var savedPreserveSourceNewlines = preserveSourceNewlines; + beforeEmitNode(node); + pipelineEmitWithHintWorker(hint, node); + afterEmitNode(savedPreserveSourceNewlines); + } + else { + pipelineEmitWithHintWorker(hint, node); + } + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); + currentParenthesizerRule = undefined; + } + function pipelineEmitWithHintWorker(hint, node) { if (hint === 0) return emitSourceFile(ts.cast(node, ts.isSourceFile)); if (hint === 2) @@ -82619,289 +85293,311 @@ var ts; return emitEmptyStatement(true); } if (hint === 4) { - if (ts.isKeyword(node.kind)) - return writeTokenNode(node, writeKeyword); switch (node.kind) { case 15: case 16: case 17: return emitLiteral(node, false); - case 299: - case 293: - return emitUnparsedSourceOrPrepend(node); - case 292: - return writeUnparsedNode(node); - case 294: - case 295: - return emitUnparsedTextLike(node); - case 296: - return emitUnparsedSyntheticReference(node); case 78: return emitIdentifier(node); case 79: return emitPrivateIdentifier(node); - case 157: - return emitQualifiedName(node); case 158: - return emitComputedPropertyName(node); + return emitQualifiedName(node); case 159: - return emitTypeParameter(node); + return emitComputedPropertyName(node); case 160: - return emitParameter(node); + return emitTypeParameter(node); case 161: - return emitDecorator(node); + return emitParameter(node); case 162: - return emitPropertySignature(node); + return emitDecorator(node); case 163: - return emitPropertyDeclaration(node); + return emitPropertySignature(node); case 164: - return emitMethodSignature(node); + return emitPropertyDeclaration(node); case 165: - return emitMethodDeclaration(node); + return emitMethodSignature(node); case 166: - return emitConstructor(node); + return emitMethodDeclaration(node); case 167: + return emitConstructor(node); case 168: - return emitAccessorDeclaration(node); case 169: - return emitCallSignature(node); + return emitAccessorDeclaration(node); case 170: - return emitConstructSignature(node); + return emitCallSignature(node); case 171: - return emitIndexSignature(node); - case 194: - return emitTemplateTypeSpan(node); + return emitConstructSignature(node); case 172: - return emitTypePredicate(node); + return emitIndexSignature(node); case 173: - return emitTypeReference(node); + return emitTypePredicate(node); case 174: - return emitFunctionType(node); - case 308: - return emitJSDocFunctionType(node); + return emitTypeReference(node); case 175: - return emitConstructorType(node); + return emitFunctionType(node); case 176: - return emitTypeQuery(node); + return emitConstructorType(node); case 177: - return emitTypeLiteral(node); + return emitTypeQuery(node); case 178: - return emitArrayType(node); + return emitTypeLiteral(node); case 179: - return emitTupleType(node); + return emitArrayType(node); case 180: + return emitTupleType(node); + case 181: return emitOptionalType(node); - case 182: - return emitUnionType(node); case 183: - return emitIntersectionType(node); + return emitUnionType(node); case 184: - return emitConditionalType(node); + return emitIntersectionType(node); case 185: - return emitInferType(node); + return emitConditionalType(node); case 186: + return emitInferType(node); + case 187: return emitParenthesizedType(node); - case 223: + case 224: return emitExpressionWithTypeArguments(node); - case 187: - return emitThisType(); case 188: - return emitTypeOperator(node); + return emitThisType(); case 189: - return emitIndexedAccessType(node); + return emitTypeOperator(node); case 190: - return emitMappedType(node); + return emitIndexedAccessType(node); case 191: + return emitMappedType(node); + case 192: return emitLiteralType(node); case 193: + return emitNamedTupleMember(node); + case 194: return emitTemplateType(node); case 195: - return emitImportTypeNode(node); - case 303: - writePunctuation("*"); - return; - case 304: - writePunctuation("?"); - return; - case 305: - return emitJSDocNullableType(node); - case 306: - return emitJSDocNonNullableType(node); - case 307: - return emitJSDocOptionalType(node); - case 181: - case 309: - return emitRestOrJSDocVariadicType(node); - case 192: - return emitNamedTupleMember(node); + return emitTemplateTypeSpan(node); case 196: - return emitObjectBindingPattern(node); + return emitImportTypeNode(node); case 197: - return emitArrayBindingPattern(node); + return emitObjectBindingPattern(node); case 198: + return emitArrayBindingPattern(node); + case 199: return emitBindingElement(node); - case 228: - return emitTemplateSpan(node); case 229: - return emitSemicolonClassElement(); + return emitTemplateSpan(node); case 230: + return emitSemicolonClassElement(); + case 231: return emitBlock(node); - case 232: + case 233: return emitVariableStatement(node); - case 231: + case 232: return emitEmptyStatement(false); - case 233: - return emitExpressionStatement(node); case 234: - return emitIfStatement(node); + return emitExpressionStatement(node); case 235: - return emitDoStatement(node); + return emitIfStatement(node); case 236: - return emitWhileStatement(node); + return emitDoStatement(node); case 237: - return emitForStatement(node); + return emitWhileStatement(node); case 238: - return emitForInStatement(node); + return emitForStatement(node); case 239: - return emitForOfStatement(node); + return emitForInStatement(node); case 240: - return emitContinueStatement(node); + return emitForOfStatement(node); case 241: - return emitBreakStatement(node); + return emitContinueStatement(node); case 242: - return emitReturnStatement(node); + return emitBreakStatement(node); case 243: - return emitWithStatement(node); + return emitReturnStatement(node); case 244: - return emitSwitchStatement(node); + return emitWithStatement(node); case 245: - return emitLabeledStatement(node); + return emitSwitchStatement(node); case 246: - return emitThrowStatement(node); + return emitLabeledStatement(node); case 247: - return emitTryStatement(node); + return emitThrowStatement(node); case 248: - return emitDebuggerStatement(node); + return emitTryStatement(node); case 249: - return emitVariableDeclaration(node); + return emitDebuggerStatement(node); case 250: - return emitVariableDeclarationList(node); + return emitVariableDeclaration(node); case 251: - return emitFunctionDeclaration(node); + return emitVariableDeclarationList(node); case 252: - return emitClassDeclaration(node); + return emitFunctionDeclaration(node); case 253: - return emitInterfaceDeclaration(node); + return emitClassDeclaration(node); case 254: - return emitTypeAliasDeclaration(node); + return emitInterfaceDeclaration(node); case 255: - return emitEnumDeclaration(node); + return emitTypeAliasDeclaration(node); case 256: - return emitModuleDeclaration(node); + return emitEnumDeclaration(node); case 257: - return emitModuleBlock(node); + return emitModuleDeclaration(node); case 258: - return emitCaseBlock(node); + return emitModuleBlock(node); case 259: - return emitNamespaceExportDeclaration(node); + return emitCaseBlock(node); case 260: - return emitImportEqualsDeclaration(node); + return emitNamespaceExportDeclaration(node); case 261: - return emitImportDeclaration(node); + return emitImportEqualsDeclaration(node); case 262: - return emitImportClause(node); + return emitImportDeclaration(node); case 263: + return emitImportClause(node); + case 264: return emitNamespaceImport(node); - case 269: + case 270: return emitNamespaceExport(node); - case 264: - return emitNamedImports(node); case 265: - return emitImportSpecifier(node); + return emitNamedImports(node); case 266: - return emitExportAssignment(node); + return emitImportSpecifier(node); case 267: - return emitExportDeclaration(node); + return emitExportAssignment(node); case 268: + return emitExportDeclaration(node); + case 269: return emitNamedExports(node); - case 270: - return emitExportSpecifier(node); case 271: - return; + return emitExportSpecifier(node); case 272: + return; + case 273: return emitExternalModuleReference(node); case 11: return emitJsxText(node); - case 275: - case 278: - return emitJsxOpeningElementOrFragment(node); case 276: case 279: - return emitJsxClosingElementOrFragment(node); + return emitJsxOpeningElementOrFragment(node); + case 277: case 280: - return emitJsxAttribute(node); + return emitJsxClosingElementOrFragment(node); case 281: - return emitJsxAttributes(node); + return emitJsxAttribute(node); case 282: - return emitJsxSpreadAttribute(node); + return emitJsxAttributes(node); case 283: - return emitJsxExpression(node); + return emitJsxSpreadAttribute(node); case 284: - return emitCaseClause(node); + return emitJsxExpression(node); case 285: - return emitDefaultClause(node); + return emitCaseClause(node); case 286: - return emitHeritageClause(node); + return emitDefaultClause(node); case 287: - return emitCatchClause(node); + return emitHeritageClause(node); case 288: - return emitPropertyAssignment(node); + return emitCatchClause(node); case 289: - return emitShorthandPropertyAssignment(node); + return emitPropertyAssignment(node); case 290: - return emitSpreadAssignment(node); + return emitShorthandPropertyAssignment(node); case 291: + return emitSpreadAssignment(node); + case 292: return emitEnumMember(node); + case 293: + return writeUnparsedNode(node); + case 300: + case 294: + return emitUnparsedSourceOrPrepend(node); + case 295: + case 296: + return emitUnparsedTextLike(node); + case 297: + return emitUnparsedSyntheticReference(node); + case 298: + return emitSourceFile(node); + case 299: + return ts.Debug.fail("Bundles should be printed using printBundle"); + case 301: + return ts.Debug.fail("InputFiles should not be printed"); + case 302: + return emitJSDocTypeExpression(node); + case 303: + return emitJSDocNameReference(node); + case 304: + return writePunctuation("*"); + case 305: + return writePunctuation("?"); + case 306: + return emitJSDocNullableType(node); + case 307: + return emitJSDocNonNullableType(node); + case 308: + return emitJSDocOptionalType(node); + case 309: + return emitJSDocFunctionType(node); + case 182: + case 310: + return emitRestOrJSDocVariadicType(node); + case 311: + return; + case 312: + return emitJSDoc(node); + case 314: + return emitJSDocTypeLiteral(node); + case 315: + return emitJSDocSignature(node); + case 317: + case 322: + return emitJSDocSimpleTag(node); + case 318: + case 319: + return emitJSDocHeritageTag(node); + case 320: + case 321: + return; + case 323: + case 324: + case 325: case 326: - case 333: - return emitJSDocPropertyLikeTag(node); case 327: - case 329: + return; case 328: - case 325: - return emitJSDocSimpleTypedTag(node); - case 316: - case 315: - return emitJSDocHeritageTag(node); + return emitJSDocCallbackTag(node); case 330: - return emitJSDocTemplateTag(node); + case 337: + return emitJSDocPropertyLikeTag(node); + case 329: case 331: - return emitJSDocTypedefTag(node); - case 324: - return emitJSDocCallbackTag(node); - case 313: - return emitJSDocSignature(node); - case 312: - return emitJSDocTypeLiteral(node); - case 319: - case 314: - return emitJSDocSimpleTag(node); case 332: + case 333: + return emitJSDocSimpleTypedTag(node); + case 334: + return emitJSDocTemplateTag(node); + case 335: + return emitJSDocTypedefTag(node); + case 336: return emitJSDocSeeTag(node); - case 302: - return emitJSDocNameReference(node); - case 311: - return emitJSDoc(node); + case 339: + case 343: + case 342: + return; } if (ts.isExpression(node)) { hint = 1; if (substituteNode !== ts.noEmitSubstitution) { - lastSubstitution = node = substituteNode(hint, node); + var substitute = substituteNode(hint, node) || node; + if (substitute !== node) { + node = substitute; + if (currentParenthesizerRule) { + node = currentParenthesizerRule(node); + } + } } } - else if (ts.isToken(node)) { - return writeTokenNode(node, writePunctuation); - } } if (hint === 1) { switch (node.kind) { @@ -82914,80 +85610,88 @@ var ts; return emitLiteral(node, false); case 78: return emitIdentifier(node); - case 94: - case 103: - case 105: - case 109: - case 107: - case 99: - writeTokenNode(node, writeKeyword); - return; - case 199: - return emitArrayLiteralExpression(node); case 200: - return emitObjectLiteralExpression(node); + return emitArrayLiteralExpression(node); case 201: - return emitPropertyAccessExpression(node); + return emitObjectLiteralExpression(node); case 202: - return emitElementAccessExpression(node); + return emitPropertyAccessExpression(node); case 203: - return emitCallExpression(node); + return emitElementAccessExpression(node); case 204: - return emitNewExpression(node); + return emitCallExpression(node); case 205: - return emitTaggedTemplateExpression(node); + return emitNewExpression(node); case 206: - return emitTypeAssertionExpression(node); + return emitTaggedTemplateExpression(node); case 207: - return emitParenthesizedExpression(node); + return emitTypeAssertionExpression(node); case 208: - return emitFunctionExpression(node); + return emitParenthesizedExpression(node); case 209: - return emitArrowFunction(node); + return emitFunctionExpression(node); case 210: - return emitDeleteExpression(node); + return emitArrowFunction(node); case 211: - return emitTypeOfExpression(node); + return emitDeleteExpression(node); case 212: - return emitVoidExpression(node); + return emitTypeOfExpression(node); case 213: - return emitAwaitExpression(node); + return emitVoidExpression(node); case 214: - return emitPrefixUnaryExpression(node); + return emitAwaitExpression(node); case 215: - return emitPostfixUnaryExpression(node); + return emitPrefixUnaryExpression(node); case 216: - return emitBinaryExpression(node); + return emitPostfixUnaryExpression(node); case 217: - return emitConditionalExpression(node); + return emitBinaryExpression(node); case 218: - return emitTemplateExpression(node); + return emitConditionalExpression(node); case 219: - return emitYieldExpression(node); + return emitTemplateExpression(node); case 220: - return emitSpreadExpression(node); + return emitYieldExpression(node); case 221: - return emitClassExpression(node); + return emitSpreadElement(node); case 222: + return emitClassExpression(node); + case 223: return; - case 224: - return emitAsExpression(node); case 225: - return emitNonNullExpression(node); + return emitAsExpression(node); case 226: + return emitNonNullExpression(node); + case 227: return emitMetaProperty(node); - case 273: - return emitJsxElement(node); + case 228: + return ts.Debug.fail("SyntheticExpression should never be printed."); case 274: + return emitJsxElement(node); + case 275: return emitJsxSelfClosingElement(node); - case 277: + case 278: return emitJsxFragment(node); - case 336: + case 338: + return ts.Debug.fail("SyntaxList should not be printed"); + case 339: + return; + case 340: return emitPartiallyEmittedExpression(node); - case 337: + case 341: return emitCommaList(node); + case 342: + case 343: + return; + case 344: + return ts.Debug.fail("SyntheticReferenceExpression should not be printed"); } } + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + if (ts.isTokenKind(node.kind)) + return writeTokenNode(node, writePunctuation); + ts.Debug.fail("Unhandled SyntaxKind: " + ts.Debug.formatSyntaxKind(node.kind) + "."); } function emitMappedTypeParameter(node) { emit(node.name); @@ -82997,10 +85701,11 @@ var ts; emit(node.constraint); } function pipelineEmitWithSubstitution(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); var pipelinePhase = getNextPipelinePhase(1, hint, node); - pipelinePhase(hint, lastSubstitution); - ts.Debug.assert(lastNode === node || lastSubstitution === node); + ts.Debug.assertIsDefined(lastSubstitution); + node = lastSubstitution; + lastSubstitution = undefined; + pipelinePhase(hint, node); } function getHelpersFromBundledSourceFiles(bundle) { var result; @@ -83026,7 +85731,7 @@ var ts; } function emitHelpers(node) { var helpersEmitted = false; - var bundle = node.kind === 298 ? node : undefined; + var bundle = node.kind === 299 ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -83100,7 +85805,7 @@ var ts; var pos = getTextPosWithWriteLine(); writeUnparsedNode(unparsed); if (bundleFileInfo) { - updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 294 ? + updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 295 ? "text" : "internal"); } @@ -83139,7 +85844,7 @@ var ts; } function emitComputedPropertyName(node) { writePunctuation("["); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName); writePunctuation("]"); } function emitTypeParameter(node) { @@ -83163,17 +85868,17 @@ var ts; emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); - if (node.parent && node.parent.kind === 308 && !node.name) { + if (node.parent && node.parent.kind === 309 && !node.name) { emit(node.type); } else { emitTypeAnnotation(node.type); } - emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitDecorator(decorator) { writePunctuation("@"); - emitExpression(decorator.expression); + emitExpression(decorator.expression, parenthesizer.parenthesizeLeftSideOfAccess); } function emitPropertySignature(node) { emitDecorators(node, node.decorators); @@ -83221,7 +85926,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeKeyword(node.kind === 167 ? "get" : "set"); + writeKeyword(node.kind === 168 ? "get" : "set"); writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); @@ -83332,7 +86037,7 @@ var ts; writePunctuation("}"); } function emitArrayType(node) { - emit(node.elementType); + emit(node.elementType, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("["); writePunctuation("]"); } @@ -83355,21 +86060,21 @@ var ts; emit(node.type); } function emitOptionalType(node) { - emit(node.type); + emit(node.type, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("?"); } function emitUnionType(node) { - emitList(node, node.types, 516); + emitList(node, node.types, 516, parenthesizer.parenthesizeMemberOfElementType); } function emitIntersectionType(node) { - emitList(node, node.types, 520); + emitList(node, node.types, 520, parenthesizer.parenthesizeMemberOfElementType); } function emitConditionalType(node) { - emit(node.checkType); + emit(node.checkType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writeKeyword("extends"); writeSpace(); - emit(node.extendsType); + emit(node.extendsType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writePunctuation("?"); writeSpace(); @@ -83395,10 +86100,10 @@ var ts; function emitTypeOperator(node) { writeTokenText(node.operator, writeKeyword); writeSpace(); - emit(node.type); + emit(node.type, parenthesizer.parenthesizeMemberOfElementType); } function emitIndexedAccessType(node) { - emit(node.objectType); + emit(node.objectType, parenthesizer.parenthesizeMemberOfElementType); writePunctuation("["); emit(node.indexType); writePunctuation("]"); @@ -83488,12 +86193,12 @@ var ts; writeSpace(); } emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitArrayLiteralExpression(node) { var elements = node.elements; var preferNewLine = node.multiLine ? 65536 : 0; - emitExpressionList(node, elements, 8914 | preferNewLine); + emitExpressionList(node, elements, 8914 | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitObjectLiteralExpression(node) { ts.forEach(node.properties, generateMemberNames); @@ -83509,13 +86214,13 @@ var ts; } } function emitPropertyAccessExpression(node) { - var expression = ts.cast(emitExpression(node.expression), ts.isExpression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); var token = node.questionDotToken || ts.setTextRangePosEnd(ts.factory.createToken(24), node.expression.end, node.name.pos); var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token); var linesAfterDot = getLinesBetweenNodes(node, token, node.name); writeLinesAndIndent(linesBeforeDot, false); var shouldEmitDotDot = token.kind !== 28 && - mayNeedDotDotForPropertyAccess(expression) && + mayNeedDotDotForPropertyAccess(node.expression) && !writer.hasTrailingComment() && !writer.hasTrailingWhitespace(); if (shouldEmitDotDot) { @@ -83544,27 +86249,27 @@ var ts; } } function emitElementAccessExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTokenWithComment(22, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); emitTokenWithComment(23, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 2576); + emitExpressionList(node, node.arguments, 2576, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitNewExpression(node) { emitTokenWithComment(102, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfNew); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 18960); + emitExpressionList(node, node.arguments, 18960, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitTaggedTemplateExpression(node) { - emitExpression(node.tag); + emitExpression(node.tag, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); writeSpace(); emitExpression(node.template); @@ -83573,12 +86278,12 @@ var ts; writePunctuation("<"); emit(node.type); writePunctuation(">"); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20, node.pos, writePunctuation, node); var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); - emitExpression(node.expression); + emitExpression(node.expression, undefined); writeLineSeparatorsAfter(node.expression, node); decreaseIndentIf(indented); emitTokenWithComment(21, node.expression ? node.expression.end : openParenPos, writePunctuation, node); @@ -83602,91 +86307,127 @@ var ts; function emitDeleteExpression(node) { emitTokenWithComment(88, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitTypeOfExpression(node) { emitTokenWithComment(111, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitVoidExpression(node) { emitTokenWithComment(113, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitAwaitExpression(node) { emitTokenWithComment(130, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitPrefixUnaryExpression(node) { writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { writeSpace(); } - emitExpression(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPrefixUnary); } function shouldEmitWhitespaceBeforeOperand(node) { var operand = node.operand; - return operand.kind === 214 + return operand.kind === 215 && ((node.operator === 39 && (operand.operator === 39 || operand.operator === 45)) || (node.operator === 40 && (operand.operator === 40 || operand.operator === 46))); } function emitPostfixUnaryExpression(node) { - emitExpression(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary); writeTokenText(node.operator, writeOperator); } - function emitBinaryExpression(node) { - var nodeStack = [node]; - var stateStack = [0]; - var stackIndex = 0; - while (stackIndex >= 0) { - node = nodeStack[stackIndex]; - switch (stateStack[stackIndex]) { - case 0: { - maybePipelineEmitExpression(node.left); - break; - } - case 1: { - var isCommaOperator = node.operatorToken.kind !== 27; - var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); - var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); - writeLinesAndIndent(linesBeforeOperator, isCommaOperator); - emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken, node.operatorToken.kind === 100 ? writeKeyword : writeOperator); - emitTrailingCommentsOfPosition(node.operatorToken.end, true); - writeLinesAndIndent(linesAfterOperator, true); - maybePipelineEmitExpression(node.right); - break; - } - case 2: { - var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); - var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); - decreaseIndentIf(linesBeforeOperator, linesAfterOperator); - stackIndex--; - break; - } - default: return ts.Debug.fail("Invalid state " + stateStack[stackIndex] + " for emitBinaryExpressionWorker"); + function createEmitBinaryExpression() { + return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, undefined); + function onEnter(node, state) { + if (state) { + state.stackIndex++; + state.preserveSourceNewlinesStack[state.stackIndex] = preserveSourceNewlines; + state.containerPosStack[state.stackIndex] = containerPos; + state.containerEndStack[state.stackIndex] = containerEnd; + state.declarationListContainerEndStack[state.stackIndex] = declarationListContainerEnd; + var emitComments_1 = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node); + var emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node); + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (emitComments_1) + emitCommentsBeforeNode(node); + if (emitSourceMaps) + emitSourceMapsBeforeNode(node); + beforeEmitNode(node); } - } - function maybePipelineEmitExpression(next) { - stateStack[stackIndex]++; - var savedLastNode = lastNode; - var savedLastSubstitution = lastSubstitution; - lastNode = next; - lastSubstitution = undefined; + else { + state = { + stackIndex: 0, + preserveSourceNewlinesStack: [undefined], + containerPosStack: [-1], + containerEndStack: [-1], + declarationListContainerEndStack: [-1], + shouldEmitCommentsStack: [false], + shouldEmitSourceMapsStack: [false], + }; + } + return state; + } + function onLeft(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "left"); + } + function onOperator(operatorToken, _state, node) { + var isCommaOperator = operatorToken.kind !== 27; + var linesBeforeOperator = getLinesBetweenNodes(node, node.left, operatorToken); + var linesAfterOperator = getLinesBetweenNodes(node, operatorToken, node.right); + writeLinesAndIndent(linesBeforeOperator, isCommaOperator); + emitLeadingCommentsOfPosition(operatorToken.pos); + writeTokenNode(operatorToken, operatorToken.kind === 100 ? writeKeyword : writeOperator); + emitTrailingCommentsOfPosition(operatorToken.end, true); + writeLinesAndIndent(linesAfterOperator, true); + } + function onRight(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "right"); + } + function onExit(node, state) { + var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); + var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); + decreaseIndentIf(linesBeforeOperator, linesAfterOperator); + if (state.stackIndex > 0) { + var savedPreserveSourceNewlines = state.preserveSourceNewlinesStack[state.stackIndex]; + var savedContainerPos = state.containerPosStack[state.stackIndex]; + var savedContainerEnd = state.containerEndStack[state.stackIndex]; + var savedDeclarationListContainerEnd = state.declarationListContainerEndStack[state.stackIndex]; + var shouldEmitComments_1 = state.shouldEmitCommentsStack[state.stackIndex]; + var shouldEmitSourceMaps_1 = state.shouldEmitSourceMapsStack[state.stackIndex]; + afterEmitNode(savedPreserveSourceNewlines); + if (shouldEmitSourceMaps_1) + emitSourceMapsAfterNode(node); + if (shouldEmitComments_1) + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); + state.stackIndex--; + } + } + function maybeEmitExpression(next, parent, side) { + var parenthesizerRule = side === "left" ? + parenthesizer.getParenthesizeLeftSideOfBinaryForOperator(parent.operatorToken.kind) : + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(parent.operatorToken.kind); var pipelinePhase = getPipelinePhase(0, 1, next); - if (pipelinePhase === pipelineEmitWithHint && ts.isBinaryExpression(next)) { - stackIndex++; - stateStack[stackIndex] = 0; - nodeStack[stackIndex] = next; + if (pipelinePhase === pipelineEmitWithSubstitution) { + ts.Debug.assertIsDefined(lastSubstitution); + next = parenthesizerRule(ts.cast(lastSubstitution, ts.isExpression)); + pipelinePhase = getNextPipelinePhase(1, 1, next); + lastSubstitution = undefined; } - else { - pipelinePhase(1, next); + if (pipelinePhase === pipelineEmitWithComments || + pipelinePhase === pipelineEmitWithSourceMaps || + pipelinePhase === pipelineEmitWithHint) { + if (ts.isBinaryExpression(next)) { + return next; + } } - ts.Debug.assert(lastNode === next); - lastNode = savedLastNode; - lastSubstitution = savedLastSubstitution; + currentParenthesizerRule = parenthesizerRule; + pipelinePhase(1, next); } } function emitConditionalExpression(node) { @@ -83694,16 +86435,16 @@ var ts; var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue); var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken); var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse); - emitExpression(node.condition); + emitExpression(node.condition, parenthesizer.parenthesizeConditionOfConditionalExpression); writeLinesAndIndent(linesBeforeQuestion, true); emit(node.questionToken); writeLinesAndIndent(linesAfterQuestion, true); - emitExpression(node.whenTrue); + emitExpression(node.whenTrue, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion); writeLinesAndIndent(linesBeforeColon, true); emit(node.colonToken); writeLinesAndIndent(linesAfterColon, true); - emitExpression(node.whenFalse); + emitExpression(node.whenFalse, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeColon, linesAfterColon); } function emitTemplateExpression(node) { @@ -83713,22 +86454,22 @@ var ts; function emitYieldExpression(node) { emitTokenWithComment(124, node.pos, writeKeyword, node); emit(node.asteriskToken); - emitExpressionWithLeadingSpace(node.expression); + emitExpressionWithLeadingSpace(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } - function emitSpreadExpression(node) { + function emitSpreadElement(node) { emitTokenWithComment(25, node.pos, writePunctuation, node); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitClassExpression(node) { generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); } function emitAsExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, undefined); if (node.type) { writeSpace(); writeKeyword("as"); @@ -83737,7 +86478,7 @@ var ts; } } function emitNonNullExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); writeOperator("!"); } function emitMetaProperty(node) { @@ -83772,7 +86513,7 @@ var ts; } } function emitExpressionStatement(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfExpressionStatement); if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeTrailingSemicolon(); } @@ -83787,7 +86528,7 @@ var ts; if (node.elseStatement) { writeLineOrSpace(node, node.thenStatement, node.elseStatement); emitTokenWithComment(90, node.thenStatement.end, writeKeyword, node); - if (node.elseStatement.kind === 234) { + if (node.elseStatement.kind === 235) { writeSpace(); emit(node.elseStatement); } @@ -83850,7 +86591,7 @@ var ts; emitTokenWithComment(20, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(156, node.initializer.end, writeKeyword, node); + emitTokenWithComment(157, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTokenWithComment(21, node.expression.end, writePunctuation, node); @@ -83858,7 +86599,7 @@ var ts; } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 250) { + if (node.kind === 251) { emit(node); } else { @@ -83895,7 +86636,7 @@ var ts; } pos = writeTokenText(token, writer, pos); if (isSimilarNode && contextNode.end !== pos) { - var isJsxExprContext = contextNode.kind === 283; + var isJsxExprContext = contextNode.kind === 284; emitTrailingCommentsOfPosition(pos, !isJsxExprContext, isJsxExprContext); } return pos; @@ -83956,7 +86697,7 @@ var ts; emit(node.name); emit(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); @@ -83975,9 +86716,6 @@ var ts; emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } - function emitBlockCallback(_hint, body) { - emitBlockFunctionBody(body); - } function emitSignatureAndBody(node, emitSignatureHead) { var body = node.body; if (body) { @@ -83990,12 +86728,7 @@ var ts; ts.forEach(node.parameters, generateNames); generateNames(node.body); emitSignatureHead(node); - if (onEmitNode) { - onEmitNode(4, body, emitBlockCallback); - } - else { - emitBlockFunctionBody(body); - } + emitBlockFunctionBody(body); popNameGenerationScope(node); if (indentedFlag) { decreaseIndent(); @@ -84004,7 +86737,7 @@ var ts; else { emitSignatureHead(node); writeSpace(); - emitExpression(body); + emitExpression(body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); } } else { @@ -84042,6 +86775,7 @@ var ts; return true; } function emitBlockFunctionBody(body) { + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(body); writeSpace(); writePunctuation("{"); increaseIndent(); @@ -84056,6 +86790,7 @@ var ts; } decreaseIndent(); writeToken(19, body.statements.end, writePunctuation, body); + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, true); @@ -84070,7 +86805,7 @@ var ts; increaseIndent(); } else { - emitList(body, body.statements, 1, statementOffset); + emitList(body, body.statements, 1, undefined, statementOffset); } } function emitClassDeclaration(node) { @@ -84145,7 +86880,7 @@ var ts; var body = node.body; if (!body) return writeTrailingSemicolon(); - while (body.kind === 256) { + while (body && ts.isModuleDeclaration(body)) { writePunctuation("."); emit(body.name); body = body.body; @@ -84235,7 +86970,9 @@ var ts; emitTokenWithComment(87, nextPos, writeKeyword, node); } writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, node.isExportEquals ? + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(62) : + parenthesizer.parenthesizeExpressionOfExportDefault); writeTrailingSemicolon(); } function emitExportDeclaration(node) { @@ -84398,7 +87135,7 @@ var ts; function emitCaseClause(node) { emitTokenWithComment(81, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { @@ -84447,7 +87184,7 @@ var ts; var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } - emitExpression(initializer); + emitExpression(initializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitShorthandPropertyAssignment(node) { emit(node.name); @@ -84455,34 +87192,37 @@ var ts; writeSpace(); writePunctuation("="); writeSpace(); - emitExpression(node.objectAssignmentInitializer); + emitExpression(node.objectAssignmentInitializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } } function emitSpreadAssignment(node) { if (node.expression) { emitTokenWithComment(25, node.pos, writePunctuation, node); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } } function emitEnumMember(node) { emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitJSDoc(node) { write("/**"); if (node.comment) { - var lines = node.comment.split(/\r\n?|\n/g); - for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { - var line = lines_2[_a]; - writeLine(); - writeSpace(); - writePunctuation("*"); - writeSpace(); - write(line); + var text = ts.getTextOfJSDocComment(node.comment); + if (text) { + var lines = text.split(/\r\n?|\n/g); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } } } if (node.tags) { - if (node.tags.length === 1 && node.tags[0].kind === 329 && !node.comment) { + if (node.tags.length === 1 && node.tags[0].kind === 333 && !node.comment) { writeSpace(); emit(node.tags[0]); } @@ -84527,7 +87267,7 @@ var ts; function emitJSDocTypedefTag(tag) { emitJSDocTagName(tag.tagName); if (tag.typeExpression) { - if (tag.typeExpression.kind === 301) { + if (tag.typeExpression.kind === 302) { emitJSDocTypeExpression(tag.typeExpression); } else { @@ -84546,7 +87286,7 @@ var ts; emit(tag.fullName); } emitJSDocComment(tag.comment); - if (tag.typeExpression && tag.typeExpression.kind === 312) { + if (tag.typeExpression && tag.typeExpression.kind === 314) { emitJSDocTypeLiteral(tag.typeExpression); } } @@ -84599,9 +87339,10 @@ var ts; emit(tagName); } function emitJSDocComment(comment) { - if (comment) { + var text = ts.getTextOfJSDocComment(comment); + if (text) { writeSpace(); - write(comment); + write(text); } } function emitJSDocTypeExpression(typeExpression) { @@ -84699,14 +87440,14 @@ var ts; emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitTripleSlashDirectivesIfNeeded(node); - emitList(node, statements, 1, index === -1 ? statements.length : index); + emitList(node, statements, 1, undefined, index === -1 ? statements.length : index); popNameGenerationScope(node); } function emitPartiallyEmittedExpression(node) { emitExpression(node.expression); } function emitCommaList(node) { - emitExpressionList(node, node.elements, 528); + emitExpressionList(node, node.elements, 528, undefined); } function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) { var needsToSetSourceFile = !!sourceFile; @@ -84843,12 +87584,12 @@ var ts; emit(node); } } - function emitInitializer(node, equalCommentStartPos, container) { + function emitInitializer(node, equalCommentStartPos, container, parenthesizerRule) { if (node) { writeSpace(); emitTokenWithComment(62, equalCommentStartPos, writeOperator, container); writeSpace(); - emitExpression(node); + emitExpression(node, parenthesizerRule); } } function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { @@ -84863,10 +87604,10 @@ var ts; emit(node); } } - function emitExpressionWithLeadingSpace(node) { + function emitExpressionWithLeadingSpace(node, parenthesizerRule) { if (node) { writeSpace(); - emitExpression(node); + emitExpression(node, parenthesizerRule); } } function emitWithTrailingSpace(node) { @@ -84896,7 +87637,7 @@ var ts; emitList(parentNode, decorators, 2146305); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 53776); + emitList(parentNode, typeArguments, 53776, parenthesizer.parenthesizeMemberOfElementType); } function emitTypeParameters(parentNode, typeParameters) { if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { @@ -84935,12 +87676,6 @@ var ts; function emitParametersForIndexSignature(parentNode, parameters) { emitList(parentNode, parameters, 8848); } - function emitList(parentNode, children, format, start, count) { - emitNodeList(emit, parentNode, children, format, start, count); - } - function emitExpressionList(parentNode, children, format, start, count) { - emitNodeList(emitExpression, parentNode, children, format, start, count); - } function writeDelimiter(format) { switch (format & 60) { case 0: @@ -84963,7 +87698,13 @@ var ts; break; } } - function emitNodeList(emit, parentNode, children, format, start, count) { + function emitList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count); + } + function emitExpressionList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emitExpression, parentNode, children, format, parenthesizerRule, start, count); + } + function emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; @@ -84982,7 +87723,7 @@ var ts; } if (format & 15360) { writePunctuation(getOpeningBracket(format)); - if (isEmpty && !isUndefined) { + if (isEmpty && children) { emitTrailingCommentsOfPosition(children.pos, true); } } @@ -84990,7 +87731,7 @@ var ts; onBeforeEmitNodeArray(children); } if (isEmpty) { - if (format & 1 && !(preserveSourceNewlines && ts.rangeIsOnSingleLine(parentNode, currentSourceFile))) { + if (format & 1 && !(preserveSourceNewlines && (!parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile)))) { writeLine(); } else if (format & 256 && !(format & 524288)) { @@ -84998,6 +87739,7 @@ var ts; } } else { + ts.Debug.type(children); var mayEmitInterveningComments = (format & 262144) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); @@ -85021,7 +87763,7 @@ var ts; writeDelimiter(format); } else if (previousSibling) { - if (format & 60 && previousSibling.end !== parentNode.end) { + if (format & 60 && previousSibling.end !== (parentNode ? parentNode.end : -1)) { emitLeadingCommentsOfPosition(previousSibling.end); } writeDelimiter(format); @@ -85050,7 +87792,12 @@ var ts; shouldEmitInterveningComments = mayEmitInterveningComments; } nextListElementPos = child.pos; - emit(child); + if (emit.length === 1) { + emit(child); + } + else { + emit(child, parenthesizerRule); + } if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); shouldDecreaseIndentAfterEmit = false; @@ -85068,7 +87815,7 @@ var ts; writePunctuation(","); } } - if (previousSibling && parentNode.end !== previousSibling.end && (format & 60) && !skipTrailingComments) { + if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60) && !skipTrailingComments) { emitLeadingCommentsOfPosition(hasTrailingComma && (children === null || children === void 0 ? void 0 : children.end) ? children.end : previousSibling.end); } if (format & 128) { @@ -85087,7 +87834,7 @@ var ts; onAfterEmitNodeArray(children); } if (format & 15360) { - if (isEmpty && !isUndefined) { + if (isEmpty && children) { emitLeadingCommentsOfPosition(children.end); } writePunctuation(getClosingBracket(format)); @@ -85213,7 +87960,7 @@ var ts; } var firstChild_1 = children[0]; if (firstChild_1 === undefined) { - return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; + return !parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } if (firstChild_1.pos === nextListElementPos) { return 0; @@ -85221,7 +87968,8 @@ var ts; if (firstChild_1.kind === 11) { return 0; } - if (!ts.positionIsSynthesized(parentNode.pos) && + if (parentNode && + !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || ts.getOriginalNode(firstChild_1.parent) === ts.getOriginalNode(parentNode))) { if (preserveSourceNewlines) { @@ -85243,10 +87991,10 @@ var ts; if (nextNode.kind === 11) { return 0; } - else if (!ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode) && previousNode.parent === nextNode.parent) { - if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); }); - } + else if (preserveSourceNewlines && siblingNodePositionsAreComparable(previousNode, nextNode)) { + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); }); + } + else if (!preserveSourceNewlines && !ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode)) { return ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1; } else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) { @@ -85265,9 +88013,9 @@ var ts; } var lastChild = ts.lastOrUndefined(children); if (lastChild === undefined) { - return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; + return !parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } - if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { + if (parentNode && !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { if (preserveSourceNewlines) { var end_1 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end; return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_1, parentNode.end, currentSourceFile, includeComments); }); @@ -85337,7 +88085,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 207 && ts.nodeIsSynthesized(node)) { + while (node.kind === 208 && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -85401,84 +88149,84 @@ var ts; if (!node) return; switch (node.kind) { - case 230: + case 231: ts.forEach(node.statements, generateNames); break; - case 245: - case 243: - case 235: + case 246: + case 244: case 236: + case 237: generateNames(node.statement); break; - case 234: + case 235: generateNames(node.thenStatement); generateNames(node.elseStatement); break; - case 237: - case 239: case 238: + case 240: + case 239: generateNames(node.initializer); generateNames(node.statement); break; - case 244: + case 245: generateNames(node.caseBlock); break; - case 258: + case 259: ts.forEach(node.clauses, generateNames); break; - case 284: case 285: + case 286: ts.forEach(node.statements, generateNames); break; - case 247: + case 248: generateNames(node.tryBlock); generateNames(node.catchClause); generateNames(node.finallyBlock); break; - case 287: + case 288: generateNames(node.variableDeclaration); generateNames(node.block); break; - case 232: + case 233: generateNames(node.declarationList); break; - case 250: + case 251: ts.forEach(node.declarations, generateNames); break; - case 249: - case 160: - case 198: - case 252: + case 250: + case 161: + case 199: + case 253: generateNameIfNeeded(node.name); break; - case 251: + case 252: generateNameIfNeeded(node.name); if (ts.getEmitFlags(node) & 524288) { ts.forEach(node.parameters, generateNames); generateNames(node.body); } break; - case 196: case 197: + case 198: ts.forEach(node.elements, generateNames); break; - case 261: + case 262: generateNames(node.importClause); break; - case 262: + case 263: generateNameIfNeeded(node.name); generateNames(node.namedBindings); break; - case 263: + case 264: generateNameIfNeeded(node.name); break; - case 269: + case 270: generateNameIfNeeded(node.name); break; - case 264: + case 265: ts.forEach(node.elements, generateNames); break; - case 265: + case 266: generateNameIfNeeded(node.propertyName || node.name); break; } @@ -85487,12 +88235,12 @@ var ts; if (!node) return; switch (node.kind) { - case 288: case 289: - case 163: - case 165: - case 167: + case 290: + case 164: + case 166: case 168: + case 169: generateNameIfNeeded(node.name); break; } @@ -85626,23 +88374,23 @@ var ts; switch (node.kind) { case 78: return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16), !!(flags & 8)); + case 257: case 256: - case 255: return generateNameForModuleOrEnum(node); - case 261: - case 267: + case 262: + case 268: return generateNameForImportOrExportDeclaration(node); - case 251: case 252: - case 266: + case 253: + case 267: return generateNameForExportDefault(); - case 221: + case 222: return generateNameForClassExpression(); - case 165: - case 167: + case 166: case 168: + case 169: return generateNameForMethodOrAccessor(node); - case 158: + case 159: return makeTempVariableName(0, true); default: return makeTempVariableName(0); @@ -85675,54 +88423,65 @@ var ts; return node; } function pipelineEmitWithComments(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); + var pipelinePhase = getNextPipelinePhase(2, hint, node); + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + emitCommentsBeforeNode(node); + pipelinePhase(hint, node); + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitCommentsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); + if (emitFlags & 2048) { + commentsDisabled = true; + } + } + function emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + if (emitFlags & 2048) { + commentsDisabled = false; + } + emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitLeadingCommentsOfNode(node, emitFlags, pos, end) { enterComment(); hasWrittenComment = false; - var emitFlags = ts.getEmitFlags(node); - var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; - var isEmittedNode = node.kind !== 335; var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0 || node.kind === 11; var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0 || node.kind === 11; - var savedContainerPos = containerPos; - var savedContainerEnd = containerEnd; - var savedDeclarationListContainerEnd = declarationListContainerEnd; if ((pos > 0 || end > 0) && pos !== end) { if (!skipLeadingComments) { - emitLeadingComments(pos, isEmittedNode); + emitLeadingComments(pos, node.kind !== 339); } if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512) !== 0)) { containerPos = pos; } if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024) !== 0)) { containerEnd = end; - if (node.kind === 250) { + if (node.kind === 251) { declarationListContainerEnd = end; } } } ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); exitComment(); - var pipelinePhase = getNextPipelinePhase(2, hint, node); - if (emitFlags & 2048) { - commentsDisabled = true; - pipelinePhase(hint, node); - commentsDisabled = false; - } - else { - pipelinePhase(hint, node); - } + } + function emitTrailingCommentsOfNode(node, emitFlags, pos, end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { enterComment(); + var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0 || node.kind === 11; ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); if ((pos > 0 || end > 0) && pos !== end) { containerPos = savedContainerPos; containerEnd = savedContainerEnd; declarationListContainerEnd = savedDeclarationListContainerEnd; - if (!skipTrailingComments && isEmittedNode) { + if (!skipTrailingComments && node.kind !== 339) { emitTrailingComments(end); } } exitComment(); - ts.Debug.assert(lastNode === node || lastSubstitution === node); } function emitLeadingSynthesizedComment(comment) { if (comment.hasLeadingNewline || comment.kind === 2) { @@ -85782,6 +88541,23 @@ var ts; } exitComment(); } + function siblingNodePositionsAreComparable(previousNode, nextNode) { + if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) { + return false; + } + if (nextNode.pos < previousNode.end) { + return false; + } + previousNode = ts.getOriginalNode(previousNode); + nextNode = ts.getOriginalNode(nextNode); + var parent = previousNode.parent; + if (!parent || parent !== nextNode.parent) { + return false; + } + var parentNodeArray = ts.getContainingNodeArray(previousNode); + var prevNodeIndex = parentNodeArray === null || parentNodeArray === void 0 ? void 0 : parentNodeArray.indexOf(previousNode); + return prevNodeIndex !== undefined && prevNodeIndex > -1 && parentNodeArray.indexOf(nextNode) === prevNodeIndex + 1; + } function emitLeadingComments(pos, isEmittedNode) { hasWrittenComment = false; if (isEmittedNode) { @@ -85933,42 +88709,47 @@ var ts; } return node.parsedSourceMap || undefined; } - function pipelineEmitWithSourceMap(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); + function pipelineEmitWithSourceMaps(hint, node) { var pipelinePhase = getNextPipelinePhase(3, hint, node); - if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) { - pipelinePhase(hint, node); - } - else if (ts.isUnparsedNode(node)) { + emitSourceMapsBeforeNode(node); + pipelinePhase(hint, node); + emitSourceMapsAfterNode(node); + } + function emitSourceMapsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + if (ts.isUnparsedNode(node)) { + ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); var parsed = getParsedSourceMap(node.parent); if (parsed && sourceMapGenerator) { sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); } - pipelinePhase(hint, node); } else { - var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; - var emitFlags = ts.getEmitFlags(node); - if (node.kind !== 335 + var source = sourceMapRange.source || sourceMapSource; + if (node.kind !== 339 && (emitFlags & 16) === 0 - && pos >= 0) { - emitSourcePos(source, skipSourceTrivia(source, pos)); + && sourceMapRange.pos >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); } if (emitFlags & 64) { sourceMapsDisabled = true; - pipelinePhase(hint, node); - sourceMapsDisabled = false; } - else { - pipelinePhase(hint, node); + } + } + function emitSourceMapsAfterNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + if (!ts.isUnparsedNode(node)) { + if (emitFlags & 64) { + sourceMapsDisabled = false; } - if (node.kind !== 335 + if (node.kind !== 339 && (emitFlags & 32) === 0 - && end >= 0) { - emitSourcePos(source, end); + && sourceMapRange.end >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); } } - ts.Debug.assert(lastNode === node || lastSubstitution === node); } function skipSourceTrivia(source, pos) { return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(source.text, pos); @@ -86090,12 +88871,20 @@ var ts; return ts.getBaseFileName(ts.normalizePath(fileName)); } function createCachedFileSystemEntries(rootDir, rootDirPath) { - var resultFromHost = { - files: ts.map(host.readDirectory(rootDir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories(rootDir) || [] - }; - cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); - return resultFromHost; + var _a; + if (!host.realpath || ts.ensureTrailingDirectorySeparator(toPath(host.realpath(rootDir))) === rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); + return resultFromHost; + } + if ((_a = host.directoryExists) === null || _a === void 0 ? void 0 : _a.call(host, rootDir)) { + cachedReadDirectoryResult.set(rootDirPath, false); + return false; + } + return undefined; } function tryReadDirectory(rootDir, rootDirPath) { rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath); @@ -86164,17 +88953,32 @@ var ts; } function readDirectory(rootDir, extensions, excludes, includes, depth) { var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { + var rootResult = tryReadDirectory(rootDir, rootDirPath); + var rootSymLinkResult; + if (rootResult !== undefined) { return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir) { var path = toPath(dir); if (path === rootDirPath) { - return result; - } - return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + return rootResult || getFileSystemEntriesFromHost(dir, path); + } + var result = tryReadDirectory(dir, path); + return result !== undefined ? + result || getFileSystemEntriesFromHost(dir, path) : + ts.emptyFileSystemEntries; + } + function getFileSystemEntriesFromHost(dir, path) { + if (rootSymLinkResult && path === rootDirPath) + return rootSymLinkResult; + var result = { + files: ts.map(host.readDirectory(dir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || ts.emptyArray, + directories: host.getDirectories(dir) || ts.emptyArray + }; + if (path === rootDirPath) + rootSymLinkResult = result; + return result; } } function realpath(s) { @@ -86182,7 +88986,7 @@ var ts; } function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { + if (existingResult !== undefined) { clearCache(); return undefined; } @@ -86230,9 +89034,9 @@ var ts; ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial"; ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full"; })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {})); - function updateSharedExtendedConfigFileWatcher(projectPath, parsed, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath) { + function updateSharedExtendedConfigFileWatcher(projectPath, options, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath) { var _a; - var extendedConfigs = ts.arrayToMap(((_a = parsed === null || parsed === void 0 ? void 0 : parsed.options.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath); + var extendedConfigs = ts.arrayToMap(((_a = options === null || options === void 0 ? void 0 : options.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath); extendedConfigFilesMap.forEach(function (watcher, extendedConfigFilePath) { if (!extendedConfigs.has(extendedConfigFilePath)) { watcher.projects.delete(projectPath); @@ -86247,12 +89051,12 @@ var ts; else { extendedConfigFilesMap.set(extendedConfigFilePath, { projects: new ts.Set([projectPath]), - fileWatcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath), + watcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath), close: function () { var existing = extendedConfigFilesMap.get(extendedConfigFilePath); if (!existing || existing.projects.size !== 0) return; - existing.fileWatcher.close(); + existing.watcher.close(); extendedConfigFilesMap.delete(extendedConfigFilePath); }, }); @@ -86260,6 +89064,25 @@ var ts; }); } ts.updateSharedExtendedConfigFileWatcher = updateSharedExtendedConfigFileWatcher; + function clearSharedExtendedConfigFileWatcher(projectPath, extendedConfigFilesMap) { + extendedConfigFilesMap.forEach(function (watcher) { + if (watcher.projects.delete(projectPath)) + watcher.close(); + }); + } + ts.clearSharedExtendedConfigFileWatcher = clearSharedExtendedConfigFileWatcher; + function cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath) { + if (!extendedConfigCache.delete(extendedConfigFilePath)) + return; + extendedConfigCache.forEach(function (_a, key) { + var _b; + var extendedResult = _a.extendedResult; + if ((_b = extendedResult.extendedSourceFiles) === null || _b === void 0 ? void 0 : _b.some(function (extendedFile) { return toPath(extendedFile) === extendedConfigFilePath; })) { + cleanExtendedConfigCache(extendedConfigCache, key, toPath); + } + }); + } + ts.cleanExtendedConfigCache = cleanExtendedConfigCache; function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) { var missingFilePaths = program.getMissingFilePaths(); var newMissingFilePathMap = ts.arrayToMap(missingFilePaths, ts.identity, ts.returnTrue); @@ -86291,7 +89114,7 @@ var ts; } ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; function isIgnoredFileFromWildCardWatching(_a) { - var watchedDirPath = _a.watchedDirPath, fileOrDirectory = _a.fileOrDirectory, fileOrDirectoryPath = _a.fileOrDirectoryPath, configFileName = _a.configFileName, options = _a.options, program = _a.program, extraFileExtensions = _a.extraFileExtensions, currentDirectory = _a.currentDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, writeLog = _a.writeLog; + var watchedDirPath = _a.watchedDirPath, fileOrDirectory = _a.fileOrDirectory, fileOrDirectoryPath = _a.fileOrDirectoryPath, configFileName = _a.configFileName, options = _a.options, program = _a.program, extraFileExtensions = _a.extraFileExtensions, currentDirectory = _a.currentDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, writeLog = _a.writeLog, toPath = _a.toPath; var newPath = ts.removeIgnoredPath(fileOrDirectoryPath); if (!newPath) { writeLog("Project: " + configFileName + " Detected ignored path: " + fileOrDirectory); @@ -86320,7 +89143,8 @@ var ts; return false; } var filePathWithoutExtension = ts.removeFileExtension(fileOrDirectoryPath); - var realProgram = isBuilderProgram(program) ? program.getProgramOrUndefined() : program; + var realProgram = ts.isArray(program) ? undefined : isBuilderProgram(program) ? program.getProgramOrUndefined() : program; + var builderProgram = !realProgram && !ts.isArray(program) ? program : undefined; if (hasSourceFile((filePathWithoutExtension + ".ts")) || hasSourceFile((filePathWithoutExtension + ".tsx"))) { writeLog("Project: " + configFileName + " Detected output file: " + fileOrDirectory); @@ -86330,7 +89154,9 @@ var ts; function hasSourceFile(file) { return realProgram ? !!realProgram.getSourceFileByPath(file) : - program.getState().fileInfos.has(file); + builderProgram ? + builderProgram.getState().fileInfos.has(file) : + !!ts.find(program, function (rootFile) { return toPath(rootFile) === file; }); } } ts.isIgnoredFileFromWildCardWatching = isIgnoredFileFromWildCardWatching; @@ -86783,7 +89609,7 @@ var ts; var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; var lineContent = file.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); - lineContent = lineContent.replace("\t", " "); + lineContent = lineContent.replace(/\t/g, " "); context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); context += indent + formatColorAndReset(ts.padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; @@ -86970,30 +89796,23 @@ var ts; return { file: file, pos: pos, end: end, packageId: packageId }; } ts.getReferencedFileLocation = getReferencedFileLocation; - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { - if (!program || (hasChangedAutomaticTypeDirectiveNames === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames())) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) { + if (!program || (hasChangedAutomaticTypeDirectiveNames === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames())) return false; - } - if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) { + if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) return false; - } var seenResolvedRefs; - if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) return false; - } - if (program.getSourceFiles().some(sourceFileNotUptoDate)) { + if (program.getSourceFiles().some(sourceFileNotUptoDate)) return false; - } - if (program.getMissingFilePaths().some(fileExists)) { + if (program.getMissingFilePaths().some(fileExists)) return false; - } var currentOptions = program.getCompilerOptions(); - if (!ts.compareDataObjects(currentOptions, newOptions)) { + if (!ts.compareDataObjects(currentOptions, newOptions)) return false; - } - if (currentOptions.configFile && newOptions.configFile) { + if (currentOptions.configFile && newOptions.configFile) return currentOptions.configFile.text === newOptions.configFile.text; - } return true; function sourceFileNotUptoDate(sourceFile) { return !sourceFileVersionUptoDate(sourceFile) || @@ -87003,25 +89822,28 @@ var ts; return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName); } function projectReferenceUptoDate(oldRef, newRef, index) { - if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { - return false; - } - return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + return ts.projectReferenceIsEqualTo(oldRef, newRef) && + resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); } function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { if (oldResolvedRef) { - if (ts.contains(seenResolvedRefs, oldResolvedRef)) { + if (ts.contains(seenResolvedRefs, oldResolvedRef)) return true; - } - if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + var refPath_1 = resolveProjectReferencePath(oldRef); + var newParsedCommandLine = getParsedCommandLine(refPath_1); + if (!newParsedCommandLine) + return false; + if (oldResolvedRef.commandLine.options.configFile !== newParsedCommandLine.options.configFile) + return false; + if (!ts.arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newParsedCommandLine.fileNames)) return false; - } (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) { return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]); }); } - return !fileExists(resolveProjectReferencePath(oldRef)); + var refPath = resolveProjectReferencePath(oldRef); + return !getParsedCommandLine(refPath); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -87070,7 +89892,7 @@ var ts; var currentNodeModulesDepth = 0; var modulesWithElidedImports = new ts.Map(); var sourceFilesFoundSearchingNodeModules = new ts.Map(); - ts.tracing.push("program", "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, true); ts.performance.mark("beforeProgram"); var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHostLike(host); @@ -87084,6 +89906,7 @@ var ts; var hasEmitBlockingDiagnostics = new ts.Map(); var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; + var typeReferenceDirectiveResolutionCache; var actualResolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { @@ -87097,7 +89920,7 @@ var ts; }); }; } else { - moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options); + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName, options); var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } @@ -87106,7 +89929,8 @@ var ts; actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); }; } else { - var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; + typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } var packageIdToSourceFile = new ts.Map(); @@ -87130,13 +89954,13 @@ var ts; getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect, forEachResolvedProjectReference: forEachResolvedProjectReference }), onProgramCreateComplete = _d.onProgramCreateComplete, fileExists = _d.fileExists, directoryExists = _d.directoryExists; - ts.tracing.push("program", "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); var structureIsReused; - ts.tracing.push("program", "tryReuseStructureFromOldProgram", {}); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "tryReuseStructureFromOldProgram", {}); structureIsReused = tryReuseStructureFromOldProgram(); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (structureIsReused !== 2) { processingDefaultLibFiles = []; processingOtherFiles = []; @@ -87174,19 +89998,19 @@ var ts; }); } } - ts.tracing.push("program", "processRootFiles", { count: rootNames.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "processRootFiles", { count: rootNames.length }); ts.forEach(rootNames, function (name, index) { return processRootFile(name, false, false, { kind: ts.FileIncludeKind.RootFile, index: index }); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { - ts.tracing.push("program", "processTypeReferences", { count: typeReferences.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "processTypeReferences", { count: typeReferences.length }); var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i], { kind: ts.FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: (_b = resolutions[i]) === null || _b === void 0 ? void 0 : _b.packageId }); } - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } if (rootNames.length && !skipDefaultLib) { var defaultLibraryFileName = getDefaultLibraryFileName(); @@ -87218,12 +90042,24 @@ var ts; host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); } } - oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference) { - if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { - host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), false); + if (!host.getParsedCommandLine) { + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference) { + if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), false); + } + }); + } + } + if (oldProgram && host.onReleaseParsedCommandLine) { + forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, parent, index) { + var oldReference = (parent === null || parent === void 0 ? void 0 : parent.commandLine.projectReferences[index]) || oldProgram.getProjectReferences()[index]; + var oldRefPath = resolveProjectReferencePath(oldReference); + if (!(projectReferenceRedirects === null || projectReferenceRedirects === void 0 ? void 0 : projectReferenceRedirects.has(toPath(oldRefPath)))) { + host.onReleaseParsedCommandLine(oldRefPath, oldResolvedRef, oldProgram.getCompilerOptions()); } }); } + typeReferenceDirectiveResolutionCache = undefined; oldProgram = undefined; var program = { getRootFileNames: function () { return rootNames; }, @@ -87251,7 +90087,6 @@ var ts; getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, - getTypeCatalog: function () { return getDiagnosticsProducingTypeChecker().getTypeCatalog(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getInstantiationCount: function () { return getDiagnosticsProducingTypeChecker().getInstantiationCount(); }, getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); }, @@ -87298,19 +90133,19 @@ var ts; verifyCompilerOptions(); ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return program; function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) { if (!moduleNames.length) return ts.emptyArray; var containingFileName = ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); var redirectedReference = getRedirectReferenceForResolution(containingFile); - ts.tracing.push("program", "resolveModuleNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "resolveModuleNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveModule"); var result = actualResolveModuleNamesWorker(moduleNames, containingFileName, reusedNames, redirectedReference); ts.performance.mark("afterResolveModule"); ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile) { @@ -87318,12 +90153,12 @@ var ts; return []; var containingFileName = !ts.isString(containingFile) ? ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile; var redirectedReference = !ts.isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined; - ts.tracing.push("program", "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveTypeReference"); var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference); ts.performance.mark("afterResolveTypeReference"); ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function getRedirectReferenceForResolution(file) { @@ -87398,13 +90233,13 @@ var ts; } var oldSourceFile = oldProgram && oldProgram.getSourceFile(file.fileName); if (oldSourceFile !== file && file.resolvedModules) { - var result_14 = []; + var result_15 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_14.push(resolvedModule); + result_15.push(resolvedModule); } - return result_14; + return result_15; } var unknownModuleNames; var result; @@ -87482,7 +90317,9 @@ var ts; var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; var newResolvedRef = parseProjectReferenceConfigFile(newRef); if (oldResolvedRef) { - return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + return !newResolvedRef || + newResolvedRef.sourceFile !== oldResolvedRef.sourceFile || + !ts.arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newResolvedRef.commandLine.fileNames); } else { return newResolvedRef !== undefined; @@ -87699,12 +90536,12 @@ var ts; } function emitBuildInfo(writeFileCallback) { ts.Debug.assert(!ts.outFile(options)); - ts.tracing.push("emit", "emitBuildInfo", {}, true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit", "emitBuildInfo", {}, true); ts.performance.mark("beforeEmit"); var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), undefined, ts.noTransformers, false, true); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return emitResult; } function getResolvedProjectReferences() { @@ -87748,9 +90585,9 @@ var ts; return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); } function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) { - ts.tracing.push("emit", "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit", "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, true); var result = runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function isEmitBlocked(emitFileName) { @@ -87918,79 +90755,79 @@ var ts; return diagnostics; function walk(node, parent) { switch (parent.kind) { - case 160: - case 163: - case 165: + case 161: + case 164: + case 166: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?")); return "skip"; } - case 164: - case 166: + case 165: case 167: case 168: - case 208: - case 251: + case 169: case 209: - case 249: + case 252: + case 210: + case 250: if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files)); return "skip"; } } switch (node.kind) { - case 262: + case 263: if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type")); return "skip"; } break; - case 267: + case 268: if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type")); return "skip"; } break; - case 260: + case 261: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files)); return "skip"; - case 266: + case 267: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 286: + case 287: var heritageClause = node; if (heritageClause.token === 116) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 253: + case 254: var interfaceKeyword = ts.tokenToString(117); ts.Debug.assertIsDefined(interfaceKeyword); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword)); return "skip"; - case 256: + case 257: var moduleKeyword = node.flags & 16 ? ts.tokenToString(140) : ts.tokenToString(139); ts.Debug.assertIsDefined(moduleKeyword); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword)); return "skip"; - case 254: + case 255: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files)); return "skip"; - case 255: + case 256: var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(91)); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword)); return "skip"; - case 225: + case 226: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files)); return "skip"; - case 224: + case 225: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files)); return "skip"; - case 206: + case 207: ts.Debug.fail(); } } @@ -87999,26 +90836,26 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning)); } switch (parent.kind) { - case 252: - case 221: - case 165: + case 253: + case 222: case 166: case 167: case 168: - case 208: - case 251: + case 169: case 209: + case 252: + case 210: if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files)); return "skip"; } - case 232: + case 233: if (nodes === parent.modifiers) { - checkModifiers(parent.modifiers, parent.kind === 232); + checkModifiers(parent.modifiers, parent.kind === 233); return "skip"; } break; - case 163: + case 164: if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { var modifier = _a[_i]; @@ -88029,18 +90866,18 @@ var ts; return "skip"; } break; - case 160: + case 161: if (nodes === parent.modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 203: case 204: - case 223: - case 274: - case 275: case 205: + case 224: + case 275: + case 276: + case 206: if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files)); return "skip"; @@ -88062,6 +90899,7 @@ var ts; case 142: case 133: case 125: + case 156: diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind))); break; case 123: @@ -88334,13 +91172,13 @@ var ts; return redirect; } function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { - ts.tracing.push("program", "findSourceFile", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "findSourceFile", { fileName: fileName, isDefaultLib: isDefaultLib || undefined, fileIncludeKind: ts.FileIncludeKind[reason.kind], }); var result = findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { @@ -88565,9 +91403,9 @@ var ts; } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { - ts.tracing.push("program", "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective); @@ -88630,11 +91468,13 @@ var ts; return host.getCanonicalFileName(fileName); } function processImportedModules(file) { + var _a; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { var moduleNames = getModuleNames(file); var resolutions = resolveModuleNamesReusingOldState(moduleNames, file); ts.Debug.assert(resolutions.length === moduleNames.length); + var optionsForFile = (useSourceOfProjectReferenceRedirect ? (_a = getRedirectReferenceForResolution(file)) === null || _a === void 0 ? void 0 : _a.commandLine.options : undefined) || options; for (var index = 0; index < moduleNames.length; index++) { var resolution = resolutions[index]; ts.setResolvedModule(file, moduleNames[index], resolution); @@ -88650,11 +91490,11 @@ var ts; } var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; var shouldAddFile = resolvedFileName - && !getResolutionDiagnostic(options, resolution) - && !options.noResolve + && !getResolutionDiagnostic(optionsForFile, resolution) + && !optionsForFile.noResolve && index < file.imports.length && !elideImport - && !(isJsFile && !ts.getAllowJSCompilerOption(options)) + && !(isJsFile && !ts.getAllowJSCompilerOption(optionsForFile)) && (ts.isInJSFile(file.imports[index]) || !(file.imports[index].flags & 4194304)); if (elideImport) { modulesWithElidedImports.set(file.path, true); @@ -88849,6 +91689,9 @@ var ts; if (options.module === ts.ModuleKind.None && languageVersion < 2) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } + if (options.preserveConstEnums === false) { + createDiagnosticForOptionName(ts.Diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled, "preserveConstEnums", "isolatedModules"); + } var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); @@ -88877,6 +91720,7 @@ var ts; } } if (options.outDir || + options.rootDir || options.sourceRoot || options.mapRoot) { var dir = getCommonSourceDirectory(); @@ -89341,7 +92185,7 @@ var ts; } function handleDirectoryCouldBeSymlink(directory) { var _a; - if (!host.getResolvedProjectReferences()) + if (!host.getResolvedProjectReferences() || ts.containsIgnoredPath(directory)) return; if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart)) return; @@ -89356,7 +92200,7 @@ var ts; symlinkCache.setSymlinkedDirectory(directoryPath, false); return; } - symlinkCache.setSymlinkedDirectory(directoryPath, { + symlinkCache.setSymlinkedDirectory(directory, { real: ts.ensureTrailingDirectorySeparator(real), realPath: realPath }); @@ -89588,12 +92432,15 @@ var ts; } for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { var ambientModule = _g[_f]; - if (ambientModule.declarations.length > 1) { + if (ambientModule.declarations && ambientModule.declarations.length > 1) { addReferenceFromAmbientModule(ambientModule); } } return referencedFiles; function addReferenceFromAmbientModule(symbol) { + if (!symbol.declarations) { + return; + } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var declarationSourceFile = ts.getSourceFileOfNode(declaration); @@ -89611,7 +92458,7 @@ var ts; return oldState && !oldState.referencedMap === !newReferencedMap; } BuilderState.canReuseOldState = canReuseOldState; - function create(newProgram, getCanonicalFileName, oldState) { + function create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { var fileInfos = new ts.Map(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? new ts.Map() : undefined; var exportedModulesMap = referencedMap ? new ts.Map() : undefined; @@ -89634,13 +92481,14 @@ var ts; } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) }); + fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined }); } return { fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState }; } BuilderState.create = create; @@ -89655,6 +92503,7 @@ var ts; referencedMap: state.referencedMap && new ts.Map(state.referencedMap), exportedModulesMap: state.exportedModulesMap && new ts.Map(state.exportedModulesMap), hasCalledUpdateShapeSignature: new ts.Set(state.hasCalledUpdateShapeSignature), + useFileVersionAsSignature: state.useFileVersionAsSignature, }; } BuilderState.clone = clone; @@ -89694,19 +92543,9 @@ var ts; return ts.Debug.fail(); var prevSignature = info.signature; var latestSignature; - if (sourceFile.isDeclarationFile) { - latestSignature = sourceFile.version; - if (exportedModulesMapCache && latestSignature !== prevSignature) { - var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined; - exportedModulesMapCache.set(sourceFile.resolvedPath, references || false); - } - } - else { + if (!sourceFile.isDeclarationFile && !state.useFileVersionAsSignature) { var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, true, cancellationToken, undefined, true); - var firstDts_1 = emitOutput_1.outputFiles && - programOfThisState.getCompilerOptions().declarationMap ? - emitOutput_1.outputFiles.length > 1 ? emitOutput_1.outputFiles[1] : undefined : - emitOutput_1.outputFiles.length > 0 ? emitOutput_1.outputFiles[0] : undefined; + var firstDts_1 = ts.firstOrUndefined(emitOutput_1.outputFiles); if (firstDts_1) { ts.Debug.assert(ts.fileExtensionIs(firstDts_1.name, ".d.ts"), "File extension for signature expected to be dts", function () { return "Found: " + ts.getAnyExtensionFromPath(firstDts_1.name) + " for " + firstDts_1.name + ":: All output files: " + JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; })); }); latestSignature = (computeHash || ts.generateDjb2Hash)(firstDts_1.text); @@ -89714,12 +92553,16 @@ var ts; updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache); } } - else { - latestSignature = prevSignature; + } + if (latestSignature === undefined) { + latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined; + exportedModulesMapCache.set(sourceFile.resolvedPath, references || false); } } cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature); - return !prevSignature || latestSignature !== prevSignature; + return latestSignature !== prevSignature; } BuilderState.updateShapeSignature = updateShapeSignature; function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) { @@ -89807,7 +92650,7 @@ var ts; } function isFileAffectingGlobalScope(sourceFile) { return containsGlobalScopeAugmentation(sourceFile) || - !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + !ts.isExternalOrCommonJsModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); } function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { if (state.allFilesExcludingDefaultLibraryFile) { @@ -89868,8 +92711,8 @@ var ts; function hasSameKeys(map1, map2) { return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); } - function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { - var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); state.compilerOptions = compilerOptions; @@ -90063,6 +92906,7 @@ var ts; return undefined; } function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash) { + var _a; removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath); if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) { if (!state.cleanedDiagnosticsOfLibFiles) { @@ -90075,8 +92919,12 @@ var ts; removeSemanticDiagnosticsOf(state, f.resolvedPath); }); } + ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap); return; } + else { + ts.Debug.assert(state.hasCalledUpdateShapeSignature.has(affectedFile.resolvedPath) || ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.has(affectedFile.resolvedPath)), "Signature not updated for affected file: " + affectedFile.fileName); + } if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) { forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); }); } @@ -90230,81 +93078,113 @@ var ts; return undefined; var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory(); var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); - var fileInfos = {}; - state.fileInfos.forEach(function (value, key) { + var fileNames = []; + var fileNameToFileId = new ts.Map(); + var fileIdsList; + var fileNamesToFileIdListId; + var fileInfos = ts.arrayFrom(state.fileInfos.entries(), function (_a) { + var key = _a[0], value = _a[1]; + var fileId = toFileId(key); + ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope }; + var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + return value.version === actualSignature ? + value.affectsGlobalScope ? + { version: value.version, signature: undefined, affectsGlobalScope: true } : + value.version : + actualSignature !== undefined ? + signature === undefined ? + value : + { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope } : + { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope }; }); - var result = { - fileInfos: fileInfos, - options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath) - }; + var referencedMap; if (state.referencedMap) { - var referencedMap = {}; - for (var _i = 0, _a = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { - var key = _a[_i]; - referencedMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.referencedMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); - } - result.referencedMap = referencedMap; + referencedMap = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive).map(function (key) { return [ + toFileId(key), + toFileIdListId(state.referencedMap.get(key)) + ]; }); } + var exportedModulesMap; if (state.exportedModulesMap) { - var exportedModulesMap = {}; - for (var _b = 0, _c = ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) { - var key = _c[_b]; + exportedModulesMap = ts.mapDefined(ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive), function (key) { var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key); if (newValue === undefined) - exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.exportedModulesMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); + return [toFileId(key), toFileIdListId(state.exportedModulesMap.get(key))]; else if (newValue) - exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); - } - result.exportedModulesMap = exportedModulesMap; + return [toFileId(key), toFileIdListId(newValue)]; + }); } + var semanticDiagnosticsPerFile; if (state.semanticDiagnosticsPerFile) { - var semanticDiagnosticsPerFile = []; - for (var _d = 0, _e = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) { - var key = _e[_d]; + for (var _i = 0, _a = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var key = _a[_i]; var value = state.semanticDiagnosticsPerFile.get(key); - semanticDiagnosticsPerFile.push(value.length ? + (semanticDiagnosticsPerFile || (semanticDiagnosticsPerFile = [])).push(value.length ? [ - relativeToBuildInfo(key), + toFileId(key), state.hasReusableDiagnostic ? value : convertToReusableDiagnostics(value, relativeToBuildInfo) ] : - relativeToBuildInfo(key)); + toFileId(key)); } - result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile; } + var affectedFilesPendingEmit; if (state.affectedFilesPendingEmit) { - var affectedFilesPendingEmit = []; var seenFiles = new ts.Set(); - for (var _f = 0, _g = state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(ts.compareStringsCaseSensitive); _f < _g.length; _f++) { - var path = _g[_f]; + for (var _b = 0, _c = state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) { + var path = _c[_b]; if (ts.tryAddToSet(seenFiles, path)) { - affectedFilesPendingEmit.push([relativeToBuildInfo(path), state.affectedFilesPendingEmitKind.get(path)]); + (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push([toFileId(path), state.affectedFilesPendingEmitKind.get(path)]); } } - result.affectedFilesPendingEmit = affectedFilesPendingEmit; } - return result; + return { + fileNames: fileNames, + fileInfos: fileInfos, + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + fileIdsList: fileIdsList, + referencedMap: referencedMap, + exportedModulesMap: exportedModulesMap, + semanticDiagnosticsPerFile: semanticDiagnosticsPerFile, + affectedFilesPendingEmit: affectedFilesPendingEmit, + }; function relativeToBuildInfoEnsuringAbsolutePath(path) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory)); } function relativeToBuildInfo(path) { return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName)); } + function toFileId(path) { + var fileId = fileNameToFileId.get(path); + if (fileId === undefined) { + fileNames.push(relativeToBuildInfo(path)); + fileNameToFileId.set(path, fileId = fileNames.length); + } + return fileId; + } + function toFileIdListId(set) { + var fileIds = ts.arrayFrom(set.keys(), toFileId).sort(ts.compareValues); + var key = fileIds.join(); + var fileIdListId = fileNamesToFileIdListId === null || fileNamesToFileIdListId === void 0 ? void 0 : fileNamesToFileIdListId.get(key); + if (fileIdListId === undefined) { + (fileIdsList || (fileIdsList = [])).push(fileIds); + (fileNamesToFileIdListId || (fileNamesToFileIdListId = new ts.Map())).set(key, fileIdListId = fileIdsList.length); + } + return fileIdListId; + } } - function convertToReusableCompilerOptions(options, relativeToBuildInfo) { - var result = {}; + function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { + var result; var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo); + for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var name = _a[_i]; + var optionInfo = optionsNameMap.get(name.toLowerCase()); + if ((optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || name === "skipLibCheck" || name === "skipDefaultLibCheck") { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); } } - if (result.configFilePath) { - result.configFilePath = relativeToBuildInfo(result.configFilePath); - } return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { @@ -90389,7 +93269,7 @@ var ts; } var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); var computeHash = ts.maybeBind(host, host.createHash); - var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState, host.disableUseFileVersionAsSignature); var backupState; newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); }; newProgram = undefined; @@ -90557,35 +93437,31 @@ var ts; state.affectedFilesPendingEmitIndex = 0; } } - function getMapOfReferencedSet(mapLike, toPath) { - if (!mapLike) - return undefined; - var map = new ts.Map(); - for (var key in mapLike) { - if (ts.hasProperty(mapLike, key)) { - map.set(toPath(key), new ts.Set(mapLike[key].map(toPath))); - } - } - return map; + function toBuilderStateFileInfo(fileInfo) { + return ts.isString(fileInfo) ? + { version: fileInfo, signature: fileInfo, affectsGlobalScope: undefined } : + ts.isString(fileInfo.signature) ? + fileInfo : + { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope }; } + ts.toBuilderStateFileInfo = toBuilderStateFileInfo; function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { + var _a; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var filePaths = program.fileNames.map(toPath); + var filePathsSetList = (_a = program.fileIdsList) === null || _a === void 0 ? void 0 : _a.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); var fileInfos = new ts.Map(); - for (var key in program.fileInfos) { - if (ts.hasProperty(program.fileInfos, key)) { - fileInfos.set(toPath(key), program.fileInfos[key]); - } - } + program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); var state = { fileInfos: fileInfos, - compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), - referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), - exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), - semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + referencedMap: toMapOfReferencedSet(program.referencedMap), + exportedModulesMap: toMapOfReferencedSet(program.exportedModulesMap), + semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), hasReusableDiagnostic: true, - affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }), - affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }, function (value) { return value[1]; }), + affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), + affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, }; return { @@ -90618,6 +93494,15 @@ var ts; function toAbsolutePath(path) { return ts.getNormalizedAbsolutePath(path, buildInfoDirectory); } + function toFilePath(fileId) { + return filePaths[fileId - 1]; + } + function toFilePathsSet(fileIdsListId) { + return filePathsSetList[fileIdsListId - 1]; + } + function toMapOfReferencedSet(referenceMap) { + return referenceMap && ts.arrayToMap(referenceMap, function (value) { return toFilePath(value[0]); }, function (value) { return toFilePathsSet(value[1]); }); + } } ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { @@ -90717,17 +93602,18 @@ var ts; var resolutionsWithFailedLookups = []; var resolvedFileToResolution = ts.createMultiMap(); var hasChangedAutomaticTypeDirectiveNames = false; - var failedLookupChecks = []; - var startsWithPathChecks = []; - var isInDirectoryChecks = []; + var failedLookupChecks; + var startsWithPathChecks; + var isInDirectoryChecks; var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); var resolvedModuleNames = new ts.Map(); var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); - var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var moduleResolutionCache = ts.createModuleResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, undefined, perDirectoryResolvedModuleNames, nonRelativeModuleNameCache); var resolvedTypeReferenceDirectives = new ts.Map(); var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); + var typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, undefined, moduleResolutionCache.getPackageJsonInfoCache(), perDirectoryResolvedTypeReferenceDirectives); var failedLookupDefaultExtensions = [".ts", ".tsx", ".js", ".jsx", ".json"]; var customFailedLookupPaths = new ts.Map(); var directoryWatchesOfFailedLookups = new ts.Map(); @@ -90750,6 +93636,7 @@ var ts; invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, createHasInvalidatedResolution: createHasInvalidatedResolution, + isFileWithInvalidatedNonRelativeUnresolvedImports: isFileWithInvalidatedNonRelativeUnresolvedImports, updateTypeRootsWatch: updateTypeRootsWatch, closeTypeRootsWatch: closeTypeRootsWatch, clear: clear @@ -90775,9 +93662,9 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; clearPerDirectoryResolutions(); hasChangedAutomaticTypeDirectiveNames = false; } @@ -90808,9 +93695,8 @@ var ts; isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { - perDirectoryResolvedModuleNames.clear(); - nonRelativeModuleNameCache.clear(); - perDirectoryResolvedTypeReferenceDirectives.clear(); + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } @@ -90833,7 +93719,7 @@ var ts; } var globalCache = resolutionHost.getGlobalCache(); if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { - var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; if (resolvedModule) { primaryResult.resolvedModule = resolvedModule; (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations); @@ -90842,6 +93728,9 @@ var ts; } return primaryResult; } + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + return ts.resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache); + } function resolveNamesWithLocalCache(_a) { var _b; var names = _a.names, containingFile = _a.containingFile, redirectedReference = _a.redirectedReference, cache = _a.cache, perDirectoryCacheWithRedirects = _a.perDirectoryCacheWithRedirects, loader = _a.loader, getResolutionWithResolvedFileName = _a.getResolutionWithResolvedFileName, shouldRetryResolution = _a.shouldRetryResolution, reusedNames = _a.reusedNames, logChanges = _a.logChanges; @@ -90924,7 +93813,7 @@ var ts; redirectedReference: redirectedReference, cache: resolvedTypeReferenceDirectives, perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives, - loader: ts.resolveTypeReferenceDirective, + loader: resolveTypeReferenceDirective, getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective, shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, }); @@ -91180,7 +94069,7 @@ var ts; } function scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { if (isCreatingWatchedDirectory) { - isInDirectoryChecks.push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); } else { var updatedPath = removeIgnoredPath(fileOrDirectoryPath); @@ -91193,8 +94082,8 @@ var ts; var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { - failedLookupChecks.push(fileOrDirectoryPath); - startsWithPathChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { @@ -91203,27 +94092,30 @@ var ts; if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { return false; } - failedLookupChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + var packagePath = ts.parseNodeModuleFromPath(fileOrDirectoryPath); + if (packagePath) + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks.length && !startsWithPathChecks.length && !isInDirectoryChecks.length) { + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { return false; } var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { return resolution.failedLookupLocations.some(function (location) { var locationPath = resolutionHost.toPath(location); return ts.contains(failedLookupChecks, locationPath) || - startsWithPathChecks.some(function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath); }) || - isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); }); + ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || + (isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); })); }); } function closeTypeRootsWatch() { @@ -91336,6 +94228,9 @@ var ts; return [ambient]; var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); + if (!moduleSourceFile) { + return []; + } var modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host); var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); var existingSpecifier = ts.forEach(modulePaths, function (modulePath) { return ts.forEach(host.getFileIncludeReasons().get(ts.toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)), function (reason) { @@ -91388,7 +94283,7 @@ var ts; if (!baseUrl && !paths || relativePreference === 0) { return relativePath; } - var baseDirectory = ts.getPathsBasePath(compilerOptions, host) || baseUrl; + var baseDirectory = ts.getNormalizedAbsolutePath(ts.getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory()); var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName); if (!relativeToBaseUrl) { return relativePath; @@ -91403,7 +94298,9 @@ var ts; return nonRelative; } if (relativePreference === 3) { - var projectDirectory = host.getCurrentDirectory(); + var projectDirectory = compilerOptions.configFilePath ? + ts.toPath(ts.getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) : + info.getCanonicalFileName(host.getCurrentDirectory()); var modulePath = ts.toPath(moduleFileName, projectDirectory, getCanonicalFileName); var sourceIsInternal = ts.startsWith(sourceDirectory, projectDirectory); var targetIsInternal = ts.startsWith(modulePath, projectDirectory); @@ -91437,12 +94334,8 @@ var ts; return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined; }) || false; } - function numberOfDirectorySeparators(str) { - var match = str.match(/\//g); - return match ? match.length : 0; - } function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) { - return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareValues(numberOfDirectorySeparators(a.path), numberOfDirectorySeparators(b.path)); + return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareNumberOfDirectorySeparators(a.path, b.path); } function getNearestAncestorDirectoryWithPackageJson(host, fileName) { if (host.getNearestAncestorDirectoryWithPackageJson) { @@ -91456,45 +94349,57 @@ var ts; var getCanonicalFileName = ts.hostGetCanonicalFileName(host); var cwd = host.getCurrentDirectory(); var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined; - var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray; + var importedPath = ts.toPath(importedFileName, cwd, getCanonicalFileName); + var redirects = host.redirectTargetsMap.get(importedPath) || ts.emptyArray; var importedFileNames = __spreadArray(__spreadArray(__spreadArray([], (referenceRedirect ? [referenceRedirect] : ts.emptyArray)), [importedFileName]), redirects); var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + var shouldFilterIgnoredPaths = !ts.every(targets, ts.containsIgnoredPath); if (!preferSymlinks) { - var result_15 = ts.forEach(targets, function (p) { return cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + var result_16 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_16) + return result_16; } var links = host.getSymlinkCache ? host.getSymlinkCache() : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd); - var symlinkedDirectories = links.getSymlinkedDirectories(); - var useCaseSensitiveFileNames = !host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames(); - var result = symlinkedDirectories && ts.forEachEntry(symlinkedDirectories, function (resolved, path) { - if (resolved === false) - return undefined; - if (ts.startsWithDirectory(importingFileName, resolved.realPath, getCanonicalFileName)) { + var symlinkedDirectories = links.getSymlinkedDirectoriesByRealpath(); + var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); + var result = symlinkedDirectories && ts.forEachAncestorDirectory(ts.getDirectoryPath(fullImportedFileName), function (realPathDirectory) { + var symlinkDirectories = symlinkedDirectories.get(ts.ensureTrailingDirectorySeparator(ts.toPath(realPathDirectory, cwd, getCanonicalFileName))); + if (!symlinkDirectories) return undefined; + if (ts.startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) { + return false; } return ts.forEach(targets, function (target) { - if (!ts.containsPath(resolved.real, target, !useCaseSensitiveFileNames)) { + if (!ts.startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) { return; } - var relative = ts.getRelativePathFromDirectory(resolved.real, target, getCanonicalFileName); - var option = ts.resolvePath(path, relative); - if (!host.fileExists || host.fileExists(option)) { - var result_16 = cb(option, target === referenceRedirect); - if (result_16) - return result_16; + var relative = ts.getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName); + for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { + var symlinkDirectory = symlinkDirectories_1[_i]; + var option = ts.resolvePath(symlinkDirectory, relative); + var result_17 = cb(option, target === referenceRedirect); + shouldFilterIgnoredPaths = true; + if (result_17) + return result_17; } }); }); - return result || - (preferSymlinks ? ts.forEach(targets, function (p) { return cb(p, p === referenceRedirect); }) : undefined); + return result || (preferSymlinks + ? ts.forEach(targets, function (p) { return shouldFilterIgnoredPaths && ts.containsIgnoredPath(p) ? undefined : cb(p, p === referenceRedirect); }) + : undefined); } moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule; function getAllModulePaths(importingFileName, importedFileName, host) { - var cwd = host.getCurrentDirectory(); + var _a; + var cache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + if (cache) { + var cached = cache.get(importingFileName, ts.toPath(importedFileName, host.getCurrentDirectory(), getCanonicalFileName)); + if (typeof cached === "object") + return cached; + } var allFileNames = new ts.Map(); var importedFileFromNodeModules = false; forEachFileNameOfModule(importingFileName, importedFileName, host, true, function (path, isRedirect) { @@ -91503,7 +94408,7 @@ var ts; importedFileFromNodeModules = importedFileFromNodeModules || isInNodeModules; }); var sortedPaths = []; - var _loop_24 = function (directory) { + var _loop_26 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -91526,10 +94431,10 @@ var ts; out_directory_1 = directory; }; var out_directory_1; - for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_7 = _loop_24(directory); + for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { + var state_9 = _loop_26(directory); directory = out_directory_1; - if (state_7 === "break") + if (state_9 === "break") break; } if (allFileNames.size) { @@ -91538,10 +94443,14 @@ var ts; remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators); sortedPaths.push.apply(sortedPaths, remainingPaths); } + if (cache) { + cache.set(importingFileName, ts.toPath(importedFileName, host.getCurrentDirectory(), getCanonicalFileName), sortedPaths); + } return sortedPaths; } function tryGetModuleNameFromAmbientModule(moduleSymbol, checker) { - var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); + var _a; + var decl = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { return decl.name.text; } @@ -91587,7 +94496,7 @@ var ts; ts.startsWith(relativeToBaseUrl, prefix) && ts.endsWith(relativeToBaseUrl, suffix) || !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); return key.replace("*", matchedStar); } } @@ -91855,10 +94764,10 @@ var ts; }; } ts.createWatchStatusReporter = createWatchStatusReporter; - function parseConfigFileWithSystem(configFileName, optionsToExtend, watchOptionsToExtend, system, reportDiagnostic) { + function parseConfigFileWithSystem(configFileName, optionsToExtend, extendedConfigCache, watchOptionsToExtend, system, reportDiagnostic) { var host = system; host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; - var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, undefined, watchOptionsToExtend); + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend); host.onUnRecoverableConfigFileDiagnostic = undefined; return result; } @@ -92108,7 +95017,10 @@ var ts; MissingFile: "Missing file", WildcardDirectory: "Wild card directory", FailedLookupLocations: "Failed Lookup Locations", - TypeRoots: "Type roots" + TypeRoots: "Type roots", + ConfigFileOfReferencedProject: "Config file of referened project", + ExtendedConfigOfReferencedProject: "Extended config file of referenced project", + WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project", }; function createWatchFactory(host, options) { var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; @@ -92155,6 +95067,7 @@ var ts; getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }), createHash: ts.maybeBind(host, host.createHash), readDirectory: ts.maybeBind(host, host.readDirectory), + disableUseFileVersionAsSignature: host.disableUseFileVersionAsSignature, }; function writeFile(fileName, text, writeByteOrderMark, onError) { try { @@ -92206,7 +95119,8 @@ var ts; createDirectory: function (path) { return system.createDirectory(path); }, writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, createHash: ts.maybeBind(system, system.createHash), - createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram + createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, + disableUseFileVersionAsSignature: system.disableUseFileVersionAsSignature, }; } ts.createProgramHost = createProgramHost; @@ -92282,6 +95196,7 @@ var ts; if (system === void 0) { system = ts.sys; } var host = ts.createCompilerHostWorker(options, undefined, system); host.createHash = ts.maybeBind(system, system.createHash); + host.disableUseFileVersionAsSignature = system.disableUseFileVersionAsSignature; ts.setGetSourceFileAsHashVersioned(host, system); ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); }); return host; @@ -92325,11 +95240,13 @@ var ts; function createWatchProgram(host) { var builderProgram; var reloadLevel; - var extendedConfigFilesMap; var missingFilesMap; var watchedWildcardDirectories; var timerToUpdateProgram; var timerToInvalidateFailedLookupResolutions; + var parsedConfigs; + var sharedExtendedConfigFileWatchers; + var extendedConfigCache = host.extendedConfigCache; var sourceFilesCache = new ts.Map(); var missingFilePathsRequestedForRelease; var hasChangedCompilerOptions = false; @@ -92377,6 +95294,7 @@ var ts; compilerHost.getNewLine = function () { return newLine; }; compilerHost.fileExists = fileExists; compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile; + compilerHost.onReleaseParsedCommandLine = onReleaseParsedCommandLine; compilerHost.toPath = toPath; compilerHost.getCompilationSettings = function () { return compilerOptions; }; compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect); @@ -92389,6 +95307,7 @@ var ts; compilerHost.fileIsOpen = ts.returnFalse; compilerHost.getCurrentProgram = getCurrentProgram; compilerHost.writeLog = writeLog; + compilerHost.getParsedCommandLine = getParsedCommandLine; var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : currentDirectory, false); @@ -92414,7 +95333,8 @@ var ts; builderProgram = readBuilderProgram(compilerOptions, compilerHost); synchronizeProgram(); watchConfigFileWildCardDirectories(); - watchExtendedConfigFiles(); + if (configFileName) + updateExtendedConfigFilesWatches(toPath(configFileName), compilerOptions, watchOptions, ts.WatchType.ExtendedConfigFile); return configFileName ? { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } : { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close }; @@ -92431,9 +95351,11 @@ var ts; configFileWatcher.close(); configFileWatcher = undefined; } - if (extendedConfigFilesMap) { - ts.clearMap(extendedConfigFilesMap, ts.closeFileWatcher); - extendedConfigFilesMap = undefined; + extendedConfigCache === null || extendedConfigCache === void 0 ? void 0 : extendedConfigCache.clear(); + extendedConfigCache = undefined; + if (sharedExtendedConfigFileWatchers) { + ts.clearMap(sharedExtendedConfigFileWatchers, ts.closeFileWatcherOf); + sharedExtendedConfigFileWatchers = undefined; } if (watchedWildcardDirectories) { ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); @@ -92443,6 +95365,17 @@ var ts; ts.clearMap(missingFilesMap, ts.closeFileWatcher); missingFilesMap = undefined; } + if (parsedConfigs) { + ts.clearMap(parsedConfigs, function (config) { + var _a; + (_a = config.watcher) === null || _a === void 0 ? void 0 : _a.close(); + config.watcher = undefined; + if (config.watchedDirectories) + ts.clearMap(config.watchedDirectories, ts.closeFileWatcherOf); + config.watchedDirectories = undefined; + }); + parsedConfigs = undefined; + } } function getCurrentBuilderProgram() { return builderProgram; @@ -92461,7 +95394,7 @@ var ts; } } var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { builderProgram = createProgram(undefined, undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; @@ -92479,6 +95412,8 @@ var ts; writeLog("CreatingProgramWith::"); writeLog(" roots: " + JSON.stringify(rootFileNames)); writeLog(" options: " + JSON.stringify(compilerOptions)); + if (projectReferences) + writeLog(" projectReferences: " + JSON.stringify(projectReferences)); var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; @@ -92677,10 +95612,10 @@ var ts; hasChangedCompilerOptions = true; synchronizeProgram(); watchConfigFileWildCardDirectories(); - watchExtendedConfigFiles(); + updateExtendedConfigFilesWatches(toPath(configFileName), compilerOptions, watchOptions, ts.WatchType.ExtendedConfigFile); } function parseConfigFile() { - setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, undefined, watchOptionsToExtend, extraFileExtensions)); + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, extendedConfigCache || (extendedConfigCache = new ts.Map()), watchOptionsToExtend, extraFileExtensions)); } function setConfigFileParsingResult(configFileParseResult) { rootFileNames = configFileParseResult.fileNames; @@ -92692,6 +95627,53 @@ var ts; canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInputFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } + function getParsedCommandLine(configFileName) { + var configPath = toPath(configFileName); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath); + if (config) { + if (!config.reloadLevel) + return config.parsedCommandLine; + if (config.parsedCommandLine && config.reloadLevel === ts.ConfigFileProgramReloadLevel.Partial && !host.getParsedCommandLine) { + writeLog("Reloading new file names and options"); + var fileNames = ts.getFileNamesFromConfigSpecs(config.parsedCommandLine.options.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost); + config.parsedCommandLine = __assign(__assign({}, config.parsedCommandLine), { fileNames: fileNames }); + config.reloadLevel = undefined; + return config.parsedCommandLine; + } + } + writeLog("Loading config file: " + configFileName); + var parsedCommandLine = host.getParsedCommandLine ? + host.getParsedCommandLine(configFileName) : + getParsedCommandLineFromConfigFileHost(configFileName); + if (config) { + config.parsedCommandLine = parsedCommandLine; + config.reloadLevel = undefined; + } + else { + (parsedConfigs || (parsedConfigs = new ts.Map())).set(configPath, config = { parsedCommandLine: parsedCommandLine }); + } + watchReferencedProject(configFileName, configPath, config); + return parsedCommandLine; + } + function getParsedCommandLineFromConfigFileHost(configFileName) { + var onUnRecoverableConfigFileDiagnostic = parseConfigFileHost.onUnRecoverableConfigFileDiagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + var parsedCommandLine = ts.getParsedCommandLineOfConfigFile(configFileName, undefined, parseConfigFileHost, extendedConfigCache || (extendedConfigCache = new ts.Map()), watchOptionsToExtend); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = onUnRecoverableConfigFileDiagnostic; + return parsedCommandLine; + } + function onReleaseParsedCommandLine(fileName) { + var _a; + var path = toPath(fileName); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(path); + if (!config) + return; + parsedConfigs.delete(path); + if (config.watchedDirectories) + ts.clearMap(config.watchedDirectories, ts.closeFileWatcherOf); + (_a = config.watcher) === null || _a === void 0 ? void 0 : _a.close(); + ts.clearSharedExtendedConfigFileWatcher(path, sharedExtendedConfigFileWatchers); + } function watchFilePath(path, file, callback, pollingInterval, options, watchType) { return watchFile(file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options, watchType); } @@ -92700,7 +95682,6 @@ var ts; if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) { resolutionCache.invalidateResolutionOfFile(path); } - resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); nextSourceFileVersion(path); scheduleProgramUpdate(); } @@ -92710,7 +95691,9 @@ var ts; } } function watchMissingFilePath(missingFilePath) { - return watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); + return (parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.has(missingFilePath)) ? + ts.noopFileWatcher : + watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); @@ -92744,10 +95727,11 @@ var ts; configFileName: configFileName, extraFileExtensions: extraFileExtensions, options: compilerOptions, - program: getCurrentBuilderProgram(), + program: getCurrentBuilderProgram() || rootFileNames, currentDirectory: currentDirectory, useCaseSensitiveFileNames: useCaseSensitiveFileNames, - writeLog: writeLog + writeLog: writeLog, + toPath: toPath, })) return; if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) { @@ -92756,15 +95740,76 @@ var ts; } }, flags, watchOptions, ts.WatchType.WildcardDirectory); } - function watchExtendedConfigFiles() { - var _a; - ts.mutateMap(extendedConfigFilesMap || (extendedConfigFilesMap = new ts.Map()), ts.arrayToMap(((_a = compilerOptions.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath), { - createNewValue: watchExtendedConfigFile, - onDeleteValue: ts.closeFileWatcher - }); - } - function watchExtendedConfigFile(extendedConfigFile) { - return watchFile(extendedConfigFile, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ExtendedConfigFile); + function updateExtendedConfigFilesWatches(forProjectPath, options, watchOptions, watchType) { + ts.updateSharedExtendedConfigFileWatcher(forProjectPath, options, sharedExtendedConfigFileWatchers || (sharedExtendedConfigFileWatchers = new ts.Map()), function (extendedConfigFileName, extendedConfigFilePath) { return watchFile(extendedConfigFileName, function (_fileName, eventKind) { + var _a; + updateCachedSystemWithFile(extendedConfigFileName, extendedConfigFilePath, eventKind); + if (extendedConfigCache) + ts.cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath); + var projects = (_a = sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects; + if (!(projects === null || projects === void 0 ? void 0 : projects.size)) + return; + projects.forEach(function (projectPath) { + if (toPath(configFileName) === projectPath) { + reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + } + else { + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(projectPath); + if (config) + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(projectPath); + } + scheduleProgramUpdate(); + }); + }, ts.PollingInterval.High, watchOptions, watchType); }, toPath); + } + function watchReferencedProject(configFileName, configPath, commandLine) { + var _a, _b, _c, _d, _e; + commandLine.watcher || (commandLine.watcher = watchFile(configFileName, function (_fileName, eventKind) { + updateCachedSystemWithFile(configFileName, configPath, eventKind); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath); + if (config) + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(configPath); + scheduleProgramUpdate(); + }, ts.PollingInterval.High, ((_a = commandLine.parsedCommandLine) === null || _a === void 0 ? void 0 : _a.watchOptions) || watchOptions, ts.WatchType.ConfigFileOfReferencedProject)); + if ((_b = commandLine.parsedCommandLine) === null || _b === void 0 ? void 0 : _b.wildcardDirectories) { + ts.updateWatchingWildcardDirectories(commandLine.watchedDirectories || (commandLine.watchedDirectories = new ts.Map()), new ts.Map(ts.getEntries((_c = commandLine.parsedCommandLine) === null || _c === void 0 ? void 0 : _c.wildcardDirectories)), function (directory, flags) { + var _a; + return watchDirectory(directory, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + nextSourceFileVersion(fileOrDirectoryPath); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath); + if (!(config === null || config === void 0 ? void 0 : config.parsedCommandLine)) + return; + if (ts.isIgnoredFileFromWildCardWatching({ + watchedDirPath: toPath(directory), + fileOrDirectory: fileOrDirectory, + fileOrDirectoryPath: fileOrDirectoryPath, + configFileName: configFileName, + options: config.parsedCommandLine.options, + program: config.parsedCommandLine.fileNames, + currentDirectory: currentDirectory, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + writeLog: writeLog, + toPath: toPath, + })) + return; + if (config.reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) { + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + scheduleProgramUpdate(); + } + }, flags, ((_a = commandLine.parsedCommandLine) === null || _a === void 0 ? void 0 : _a.watchOptions) || watchOptions, ts.WatchType.WildcardDirectoryOfReferencedProject); + }); + } + else if (commandLine.watchedDirectories) { + ts.clearMap(commandLine.watchedDirectories, ts.closeFileWatcherOf); + commandLine.watchedDirectories = undefined; + } + updateExtendedConfigFilesWatches(configPath, (_d = commandLine.parsedCommandLine) === null || _d === void 0 ? void 0 : _d.options, ((_e = commandLine.parsedCommandLine) === null || _e === void 0 ? void 0 : _e.watchOptions) || watchOptions, ts.WatchType.ExtendedConfigOfReferencedProject); } } ts.createWatchProgram = createWatchProgram; @@ -92897,12 +95942,19 @@ var ts; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined; + var typeReferenceDirectiveResolutionCache = !compilerHost.resolveTypeReferenceDirectives ? ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()) : undefined; if (!compilerHost.resolveModuleNames) { var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; }; compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3); }; } + if (!compilerHost.resolveTypeReferenceDirectives) { + var loader_4 = function (moduleName, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(moduleName, containingFile, state.projectCompilerOptions, compilerHost, redirectedReference, state.typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return ts.loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_4); + }; + } var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -92926,6 +95978,7 @@ var ts; projectErrorsReported: new ts.Map(), compilerHost: compilerHost, moduleResolutionCache: moduleResolutionCache, + typeReferenceDirectiveResolutionCache: typeReferenceDirectiveResolutionCache, buildOrder: undefined, readFileWithCache: function (f) { return host.readFile(f); }, projectCompilerOptions: baseCompilerOptions, @@ -92962,6 +96015,10 @@ var ts; function isParsedCommandLine(entry) { return !!entry.options; } + function getCachedParsedConfigFile(state, configFilePath) { + var value = state.configFileCache.get(configFilePath); + return value && isParsedCommandLine(value) ? value : undefined; + } function parseConfigFile(state, configFileName, configFilePath) { var configFileCache = state.configFileCache; var value = configFileCache.get(configFilePath); @@ -93101,7 +96158,7 @@ var ts; function disableCache(state) { if (!state.cache) return; - var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache; + var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache, typeReferenceDirectiveResolutionCache = state.typeReferenceDirectiveResolutionCache; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; host.directoryExists = cache.originalDirectoryExists; @@ -93110,10 +96167,8 @@ var ts; compilerHost.getSourceFile = cache.originalGetSourceFile; state.readFileWithCache = cache.originalReadFileWithCache; extendedConfigCache.clear(); - if (moduleResolutionCache) { - moduleResolutionCache.directoryToModuleNameMap.clear(); - moduleResolutionCache.moduleNameToDirectoryMap.clear(); - } + moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache === null || typeReferenceDirectiveResolutionCache === void 0 ? void 0 : typeReferenceDirectiveResolutionCache.clear(); state.cache = undefined; } function clearProjectStatus(state, resolved) { @@ -93279,6 +96334,7 @@ var ts; return withProgramOrUndefined(action) || ts.emptyArray; } function createProgram() { + var _a, _b; ts.Debug.assert(program === undefined); if (state.options.dry) { reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project); @@ -93296,7 +96352,8 @@ var ts; } var host = state.host, compilerHost = state.compilerHost; state.projectCompilerOptions = config.options; - updateModuleResolutionCache(state, project, config); + (_a = state.moduleResolutionCache) === null || _a === void 0 ? void 0 : _a.update(config.options); + (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options); program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences); if (state.watch) { state.builderPrograms.set(projectPath, program); @@ -93458,7 +96515,7 @@ var ts; emitBundle(writeFile, customTransformers); break; case BuildStep.BuildInvalidatedProjectOfBundle: - ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken); + ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken, writeFile, customTransformers); step = BuildStep.Done; break; case BuildStep.QueueReferencingProjects: @@ -93594,30 +96651,8 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } - function updateModuleResolutionCache(state, proj, config) { - if (!state.moduleResolutionCache) - return; - var moduleResolutionCache = state.moduleResolutionCache; - var projPath = toPath(state, proj); - if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) { - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0); - moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap); - moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap); - } - else { - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0); - var ref = { - sourceFile: config.options.configFile, - commandLine: config - }; - moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); - } - moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options); - } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { - var tsconfigTime = state.host.getModifiedTime(configFile) || ts.missingFileModifiedTime; + var tsconfigTime = ts.getModifiedTime(state.host, configFile); if (oldestOutputFileTime < tsconfigTime) { return { type: ts.UpToDateStatusType.OutOfDateWithSelf, @@ -93627,6 +96662,7 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { + var force = !!state.options.force; var newestInputFileName = undefined; var newestInputFileTime = minimumDate; var host = state.host; @@ -93638,10 +96674,13 @@ var ts; reason: inputFile + " does not exist" }; } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; + if (!force) { + var inputTime = ts.getModifiedTime(host, inputFile); + host.getModifiedTime(inputFile); + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } } if (!project.fileNames.length && !ts.canJsonReportNoInputFiles(project.raw)) { @@ -93657,28 +96696,30 @@ var ts; var missingOutputFileName; var newestDeclarationFileContentChangedTime = minimumDate; var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { - var output = outputs_1[_b]; - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = 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 outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + if (!force) { + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = ts.getModifiedTime(host, output); + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + if (isDeclarationFile(output)) { + var outputModifiedTime = ts.getModifiedTime(host, output); + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } } } var pseudoUpToDate = false; @@ -93710,7 +96751,7 @@ var ts; upstreamProjectName: ref.path }; } - if (!missingOutputFileName) { + if (!force && !missingOutputFileName) { if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { continue; } @@ -93749,7 +96790,7 @@ var ts; if (extendedConfigStatus) return extendedConfigStatus; } - if (!state.buildInfoChecked.has(resolvedPath)) { + if (!force && !state.buildInfoChecked.has(resolvedPath)) { state.buildInfoChecked.set(resolvedPath, true); var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); if (buildInfoPath) { @@ -93808,7 +96849,7 @@ var ts; reportStatus(state, verboseMessage, proj.options.configFilePath); } if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, ts.getModifiedTime(host, file)); } host.setModifiedTime(file, now); } @@ -93883,7 +96924,7 @@ var ts; } } } - function build(state, project, cancellationToken, onlyReferences) { + function build(state, project, cancellationToken, writeFile, getCustomTransformers, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); if (!buildOrder) return ts.ExitStatus.InvalidProject_OutputsSkipped; @@ -93895,7 +96936,7 @@ var ts; if (!invalidatedProject) break; reportQueue = false; - invalidatedProject.done(cancellationToken); + invalidatedProject.done(cancellationToken, writeFile, getCustomTransformers === null || getCustomTransformers === void 0 ? void 0 : getCustomTransformers(invalidatedProject.project)); if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; } @@ -93929,8 +96970,13 @@ var ts; continue; } var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames()); + if (!outputs.length) + continue; + var inputFileNames = new ts.Set(parsed.fileNames.map(function (f) { return toPath(state, f); })); for (var _a = 0, outputs_3 = outputs; _a < outputs_3.length; _a++) { var output = outputs_3[_a]; + if (inputFileNames.has(toPath(state, output))) + continue; if (host.fileExists(output)) { if (filesToDelete) { filesToDelete.push(output); @@ -94004,7 +97050,7 @@ var ts; }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); } function watchExtendedConfigFiles(state, resolvedPath, parsed) { - ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { + ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { var _a; return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (projectConfigFilePath) { return invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ts.ConfigFileProgramReloadLevel.Full); @@ -94015,6 +97061,7 @@ var ts; if (!state.watch) return; ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), new ts.Map(ts.getEntries(parsed.wildcardDirectories)), function (dir, flags) { return state.watchDirectory(dir, function (fileOrDirectory) { + var _a; if (ts.isIgnoredFileFromWildCardWatching({ watchedDirPath: toPath(state, dir), fileOrDirectory: fileOrDirectory, @@ -94022,9 +97069,10 @@ var ts; configFileName: resolved, currentDirectory: state.currentDirectory, options: parsed.options, - program: state.builderPrograms.get(resolvedPath), + program: state.builderPrograms.get(resolvedPath) || ((_a = getCachedParsedConfigFile(state, resolvedPath)) === null || _a === void 0 ? void 0 : _a.fileNames), useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames, - writeLog: function (s) { return state.writeLog(s); } + writeLog: function (s) { return state.writeLog(s); }, + toPath: function (fileName) { return toPath(state, fileName); } })) return; invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Partial); @@ -94056,19 +97104,16 @@ var ts; } function stopWatching(state) { ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher); - ts.clearMap(state.allWatchedExtendedConfigFiles, function (watcher) { - watcher.projects.clear(); - watcher.close(); - }); + ts.clearMap(state.allWatchedExtendedConfigFiles, ts.closeFileWatcherOf); ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); }); ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); }); } function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) { var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions); return { - build: function (project, cancellationToken) { return build(state, project, cancellationToken); }, + build: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers); }, clean: function (project) { return clean(state, project); }, - buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, true); }, + buildReferences: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers, true); }, cleanReferences: function (project) { return clean(state, project, true); }, getNextInvalidatedProject: function (cancellationToken) { setupInitialBuild(state, cancellationToken); @@ -94154,6 +97199,9 @@ var ts; } } function reportUpToDateStatus(state, configFileName, status) { + if (state.options.force && (status.type === ts.UpToDateStatusType.UpToDate || status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes)) { + return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); + } switch (status.type) { case ts.UpToDateStatusType.OutOfDateWithSelf: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); @@ -94415,7 +97463,8 @@ var ts; var currentDirectory = sys.getCurrentDirectory(); var commandLineOptions = ts.convertToOptionsWithAbsolutePaths(commandLine.options, function (fileName) { return ts.getNormalizedAbsolutePath(fileName, currentDirectory); }); if (configFileName) { - var configParseResult = ts.parseConfigFileWithSystem(configFileName, commandLineOptions, commandLine.watchOptions, sys, reportDiagnostic); + var extendedConfigCache = new ts.Map(); + var configParseResult = ts.parseConfigFileWithSystem(configFileName, commandLineOptions, extendedConfigCache, commandLine.watchOptions, sys, reportDiagnostic); if (commandLineOptions.showConfig) { if (configParseResult.errors.length !== 0) { reportDiagnostic = updateReportDiagnostic(sys, reportDiagnostic, configParseResult.options); @@ -94429,7 +97478,7 @@ var ts; if (ts.isWatchSet(configParseResult.options)) { if (reportWatchModeWithoutSysSupport(sys, reportDiagnostic)) return; - return createWatchOfConfigFile(sys, cb, reportDiagnostic, configParseResult, commandLineOptions, commandLine.watchOptions); + return createWatchOfConfigFile(sys, cb, reportDiagnostic, configParseResult, commandLineOptions, commandLine.watchOptions, extendedConfigCache); } else if (ts.isIncrementalCompilation(configParseResult.options)) { performIncrementalCompilation(sys, cb, reportDiagnostic, configParseResult); @@ -94528,7 +97577,7 @@ var ts; updateSolutionBuilderHost(sys, cb, buildHost); var builder = ts.createSolutionBuilder(buildHost, projects, buildOptions); var exitStatus = buildOptions.clean ? builder.clean() : builder.build(); - ts.tracing.dumpLegend(); + ts.dumpTracingLegend(); return sys.exit(exitStatus); } function createReportErrorSummary(sys, options) { @@ -94606,7 +97655,7 @@ var ts; function createWatchStatusReporter(sys, options) { return ts.createWatchStatusReporter(sys, shouldBePretty(sys, options)); } - function createWatchOfConfigFile(system, cb, reportDiagnostic, configParseResult, optionsToExtend, watchOptionsToExtend) { + function createWatchOfConfigFile(system, cb, reportDiagnostic, configParseResult, optionsToExtend, watchOptionsToExtend, extendedConfigCache) { var watchCompilerHost = ts.createWatchCompilerHostOfConfigFile({ configFileName: configParseResult.options.configFilePath, optionsToExtend: optionsToExtend, @@ -94617,6 +97666,7 @@ var ts; }); updateWatchCompilationHost(system, cb, watchCompilerHost); watchCompilerHost.configFileParsingResult = configParseResult; + watchCompilerHost.extendedConfigCache = extendedConfigCache; return ts.createWatchProgram(watchCompilerHost); } function createWatchOfFilesAndCompilerOptions(system, cb, reportDiagnostic, rootFiles, options, watchOptions) { @@ -94639,16 +97689,16 @@ var ts; } function enableStatisticsAndTracing(system, compilerOptions, isBuildMode) { if (canReportDiagnostics(system, compilerOptions)) { - ts.performance.enable(); + ts.performance.enable(system); } if (canTrace(system, compilerOptions)) { - ts.tracing.startTracing(isBuildMode ? 1 : 0, compilerOptions.generateTrace, compilerOptions.configFilePath); + ts.startTracing(isBuildMode ? "build" : "project", compilerOptions.generateTrace, compilerOptions.configFilePath); } } function reportStatistics(sys, program) { var compilerOptions = program.getCompilerOptions(); if (canTrace(sys, compilerOptions)) { - ts.tracing.stopTracing(program.getTypeCatalog()); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.stopTracing(); } var statistics; if (canReportDiagnostics(sys, compilerOptions)) { diff --git a/lib/tsserver.js b/lib/tsserver.js index fea2c7355c212..58028943d1d1f 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -92,11 +92,11 @@ var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "4.2"; + ts.versionMajorMinor = "4.3"; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = ts.versionMajorMinor + ".0-dev"; + ts.version = "4.3.2"; /* @internal */ var Comparison; (function (Comparison) { @@ -2400,6 +2400,8 @@ var ts; } } Debug.assertMissingNode = assertMissingNode; + function type(_value) { } + Debug.type = type; function getFunctionName(func) { if (typeof func !== "function") { return ""; @@ -2661,11 +2663,11 @@ var ts; this.objectFlags & 8 /* Tuple */ ? "TupleType" : this.objectFlags & 16 /* Anonymous */ ? "AnonymousType" : this.objectFlags & 32 /* Mapped */ ? "MappedType" : - this.objectFlags & 2048 /* ReverseMapped */ ? "ReverseMappedType" : + this.objectFlags & 1024 /* ReverseMapped */ ? "ReverseMappedType" : this.objectFlags & 256 /* EvolvingArray */ ? "EvolvingArrayType" : "ObjectType" : "Type"; - var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~2367 /* ObjectTypeKindMask */ : 0; + var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~1343 /* ObjectTypeKindMask */ : 0; return "" + typeHeader + (this.symbol ? " '" + ts.symbolName(this.symbol) + "'" : "") + (remainingObjectFlags ? " (" + formatObjectFlags(remainingObjectFlags) + ")" : ""); } }, @@ -3211,16 +3213,22 @@ var ts; typeof PerformanceObserver === "function" && hasRequiredAPI(performance, PerformanceObserver)) { return { + // For now we always write native performance events when running in the browser. We may + // make this conditional in the future if we find that native web performance hooks + // in the browser also slow down compilation. + shouldWriteNativeEvents: true, performance: performance, PerformanceObserver: PerformanceObserver }; } } function tryGetNodePerformanceHooks() { - if (typeof module === "object" && typeof require === "function") { + if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof module === "object" && typeof require === "function") { try { - var _a = require("perf_hooks"), performance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; - if (hasRequiredAPI(performance_1, PerformanceObserver_1)) { + var performance_1; + var _a = require("perf_hooks"), nodePerformance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; + if (hasRequiredAPI(nodePerformance_1, PerformanceObserver_1)) { + performance_1 = nodePerformance_1; // There is a bug in Node's performance.measure prior to 12.16.3/13.13.0 that does not // match the Web Performance API specification. Node's implementation did not allow // optional `start` and `end` arguments for `performance.measure`. @@ -3228,27 +3236,26 @@ var ts; var version_1 = new ts.Version(process.versions.node); var range = new ts.VersionRange("<12.16.3 || 13 <13.13"); if (range.test(version_1)) { - return { - performance: { - get timeOrigin() { return performance_1.timeOrigin; }, - now: function () { return performance_1.now(); }, - mark: function (name) { return performance_1.mark(name); }, - measure: function (name, start, end) { - if (start === void 0) { start = "nodeStart"; } - if (end === undefined) { - end = "__performance.measure-fix__"; - performance_1.mark(end); - } - performance_1.measure(name, start, end); - if (end === "__performance.measure-fix__") { - performance_1.clearMarks("__performance.measure-fix__"); - } + performance_1 = { + get timeOrigin() { return nodePerformance_1.timeOrigin; }, + now: function () { return nodePerformance_1.now(); }, + mark: function (name) { return nodePerformance_1.mark(name); }, + measure: function (name, start, end) { + if (start === void 0) { start = "nodeStart"; } + if (end === undefined) { + end = "__performance.measure-fix__"; + nodePerformance_1.mark(end); + } + nodePerformance_1.measure(name, start, end); + if (end === "__performance.measure-fix__") { + nodePerformance_1.clearMarks("__performance.measure-fix__"); } - }, - PerformanceObserver: PerformanceObserver_1 + } }; } return { + // By default, only write native events when generating a cpu profile or using the v8 profiler. + shouldWriteNativeEvents: false, performance: performance_1, PerformanceObserver: PerformanceObserver_1 }; @@ -3279,7 +3286,6 @@ var ts; var performance; (function (performance) { var perfHooks; - var perfObserver; // when set, indicates the implementation of `Performance` to use for user timing. // when unset, indicates user timing is unavailable or disabled. var performanceImpl; @@ -3310,6 +3316,9 @@ var ts; } performance.createTimer = createTimer; performance.nullTimer = { enter: ts.noop, exit: ts.noop }; + var enabled = false; + var timeorigin = ts.timestamp(); + var marks = new ts.Map(); var counts = new ts.Map(); var durations = new ts.Map(); /** @@ -3318,7 +3327,13 @@ var ts; * @param markName The name of the mark. */ function mark(markName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + var _a; + if (enabled) { + var count = (_a = counts.get(markName)) !== null && _a !== void 0 ? _a : 0; + counts.set(markName, count + 1); + marks.set(markName, ts.timestamp()); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + } } performance.mark = mark; /** @@ -3331,7 +3346,14 @@ var ts; * used. */ function measure(measureName, startMarkName, endMarkName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + var _a, _b; + if (enabled) { + var end = (_a = (endMarkName !== undefined ? marks.get(endMarkName) : undefined)) !== null && _a !== void 0 ? _a : ts.timestamp(); + var start = (_b = (startMarkName !== undefined ? marks.get(startMarkName) : undefined)) !== null && _b !== void 0 ? _b : timeorigin; + var previousDuration = durations.get(measureName) || 0; + durations.set(measureName, previousDuration + (end - start)); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + } } performance.measure = measure; /** @@ -3365,40 +3387,41 @@ var ts; * Indicates whether the performance API is enabled. */ function isEnabled() { - return !!performanceImpl; + return enabled; } performance.isEnabled = isEnabled; /** Enables (and resets) performance measurements for the compiler. */ - function enable() { - if (!performanceImpl) { + function enable(system) { + var _a; + if (system === void 0) { system = ts.sys; } + if (!enabled) { + enabled = true; perfHooks || (perfHooks = ts.tryGetNativePerformanceHooks()); - if (!perfHooks) - return false; - perfObserver || (perfObserver = new perfHooks.PerformanceObserver(updateStatisticsFromList)); - perfObserver.observe({ entryTypes: ["mark", "measure"] }); - performanceImpl = perfHooks.performance; + if (perfHooks) { + timeorigin = perfHooks.performance.timeOrigin; + // NodeJS's Web Performance API is currently slower than expected, but we'd still like + // to be able to leverage native trace events when node is run with either `--cpu-prof` + // or `--prof`, if we're running with our own `--generateCpuProfile` flag, or when + // running in debug mode (since its possible to generate a cpu profile while debugging). + if (perfHooks.shouldWriteNativeEvents || ((_a = system === null || system === void 0 ? void 0 : system.cpuProfilingEnabled) === null || _a === void 0 ? void 0 : _a.call(system)) || (system === null || system === void 0 ? void 0 : system.debugMode)) { + performanceImpl = perfHooks.performance; + } + } } return true; } performance.enable = enable; /** Disables performance measurements for the compiler. */ function disable() { - perfObserver === null || perfObserver === void 0 ? void 0 : perfObserver.disconnect(); - performanceImpl = undefined; - counts.clear(); - durations.clear(); - } - performance.disable = disable; - function updateStatisticsFromList(list) { - for (var _i = 0, _a = list.getEntriesByType("mark"); _i < _a.length; _i++) { - var mark_1 = _a[_i]; - counts.set(mark_1.name, (counts.get(mark_1.name) || 0) + 1); - } - for (var _b = 0, _c = list.getEntriesByType("measure"); _b < _c.length; _b++) { - var measure_1 = _c[_b]; - durations.set(measure_1.name, (durations.get(measure_1.name) || 0) + measure_1.duration); + if (enabled) { + marks.clear(); + counts.clear(); + durations.clear(); + performanceImpl = undefined; + enabled = false; } } + performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); /* @internal */ @@ -3442,40 +3465,35 @@ var ts; /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; })(ts || (ts = {})); +/* Tracing events for the compiler. */ /*@internal*/ -/** Tracing events for the compiler. */ var ts; (function (ts) { - var tracing; - (function (tracing) { - var Mode; - (function (Mode) { - Mode[Mode["Project"] = 0] = "Project"; - Mode[Mode["Build"] = 1] = "Build"; - Mode[Mode["Server"] = 2] = "Server"; - })(Mode = tracing.Mode || (tracing.Mode = {})); + // enable the above using startTracing() + // `tracingEnabled` should never be used directly, only through the above + var tracingEnabled; + (function (tracingEnabled) { var fs; var traceCount = 0; - var traceFd; + var traceFd = 0; var mode; + var typeCatalog = []; // NB: id is index + 1 var legendPath; var legend = []; ; - /** Starts tracing for the given project (unless the `fs` module is unavailable). */ + /** Starts tracing for the given project. */ function startTracing(tracingMode, traceDir, configFilePath) { - ts.Debug.assert(!traceFd, "Tracing already started"); + ts.Debug.assert(!ts.tracing, "Tracing already started"); if (fs === undefined) { try { fs = require("fs"); } - catch (_a) { - fs = false; + catch (e) { + throw new Error("tracing requires having fs\n(original error: " + (e.message || e) + ")"); } } - if (!fs) { - return; - } mode = tracingMode; + typeCatalog.length = 0; if (legendPath === undefined) { legendPath = ts.combinePaths(traceDir, "legend.json"); } @@ -3483,9 +3501,9 @@ var ts; if (!fs.existsSync(traceDir)) { fs.mkdirSync(traceDir, { recursive: true }); } - var countPart = mode === 1 /* Build */ ? "." + process.pid + "-" + ++traceCount : - mode === 2 /* Server */ ? "." + process.pid : - ""; + var countPart = mode === "build" ? "." + process.pid + "-" + ++traceCount + : mode === "server" ? "." + process.pid + : ""; var tracePath = ts.combinePaths(traceDir, "trace" + countPart + ".json"); var typesPath = ts.combinePaths(traceDir, "types" + countPart + ".json"); legend.push({ @@ -3494,25 +3512,22 @@ var ts; typesPath: typesPath, }); traceFd = fs.openSync(tracePath, "w"); + ts.tracing = tracingEnabled; // only when traceFd is properly set // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import) var meta = { cat: "__metadata", ph: "M", ts: 1000 * ts.timestamp(), pid: 1, tid: 1 }; fs.writeSync(traceFd, "[\n" + [__assign({ name: "process_name", args: { name: "tsc" } }, meta), __assign({ name: "thread_name", args: { name: "Main" } }, meta), __assign(__assign({ name: "TracingStartedInBrowser" }, meta), { cat: "disabled-by-default-devtools.timeline" })] .map(function (v) { return JSON.stringify(v); }).join(",\n")); } - tracing.startTracing = startTracing; - /** Stops tracing for the in-progress project and dumps the type catalog (unless the `fs` module is unavailable). */ - function stopTracing(typeCatalog) { - if (!traceFd) { - ts.Debug.assert(!fs, "Tracing is not in progress"); - return; - } - ts.Debug.assert(fs); - ts.Debug.assert(!!typeCatalog === (mode !== 2 /* Server */)); // Have a type catalog iff not in server mode + tracingEnabled.startTracing = startTracing; + /** Stops tracing for the in-progress project and dumps the type catalog. */ + function stopTracing() { + ts.Debug.assert(ts.tracing, "Tracing is not in progress"); + ts.Debug.assert(!!typeCatalog.length === (mode !== "server")); // Have a type catalog iff not in server mode fs.writeSync(traceFd, "\n]\n"); fs.closeSync(traceFd); - traceFd = undefined; - if (typeCatalog) { + ts.tracing = undefined; + if (typeCatalog.length) { dumpTypes(typeCatalog); } else { @@ -3521,11 +3536,13 @@ var ts; legend[legend.length - 1].typesPath = undefined; } } - tracing.stopTracing = stopTracing; - function isTracing() { - return !!traceFd; + tracingEnabled.stopTracing = stopTracing; + function recordType(type) { + if (mode !== "server") { + typeCatalog.push(type); + } } - tracing.isTracing = isTracing; + tracingEnabled.recordType = recordType; var Phase; (function (Phase) { Phase["Parse"] = "parse"; @@ -3535,13 +3552,11 @@ var ts; Phase["CheckTypes"] = "checkTypes"; Phase["Emit"] = "emit"; Phase["Session"] = "session"; - })(Phase = tracing.Phase || (tracing.Phase = {})); + })(Phase = tracingEnabled.Phase || (tracingEnabled.Phase = {})); function instant(phase, name, args) { - if (!traceFd) - return; writeEvent("I", phase, name, args, "\"s\":\"g\""); } - tracing.instant = instant; + tracingEnabled.instant = instant; var eventStack = []; /** * @param separateBeginAndEnd - used for special cases where we need the trace point even if the event @@ -3551,47 +3566,42 @@ var ts; */ function push(phase, name, args, separateBeginAndEnd) { if (separateBeginAndEnd === void 0) { separateBeginAndEnd = false; } - if (!traceFd) - return; if (separateBeginAndEnd) { writeEvent("B", phase, name, args); } eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } - tracing.push = push; + tracingEnabled.push = push; function pop() { - if (!traceFd) - return; ts.Debug.assert(eventStack.length > 0); writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); eventStack.length--; } - tracing.pop = pop; + tracingEnabled.pop = pop; function popAll() { - if (!traceFd) - return; var endTime = 1000 * ts.timestamp(); for (var i = eventStack.length - 1; i >= 0; i--) { writeStackEvent(i, endTime); } eventStack.length = 0; } - tracing.popAll = popAll; + tracingEnabled.popAll = popAll; + // sample every 10ms + var sampleInterval = 1000 * 10; function writeStackEvent(index, endTime) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); } - else { + // test if [time,endTime) straddles a sampling point + else if (sampleInterval - (time % sampleInterval) <= endTime - time) { writeEvent("X", phase, name, args, "\"dur\":" + (endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { if (time === void 0) { time = 1000 * ts.timestamp(); } - ts.Debug.assert(traceFd); - ts.Debug.assert(fs); // In server mode, there's no easy way to dump type information, so we drop events that would require it. - if (mode === 2 /* Server */ && phase === "checkTypes" /* CheckTypes */) + if (mode === "server" && phase === "checkTypes" /* CheckTypes */) return; ts.performance.mark("beginTracing"); fs.writeSync(traceFd, ",\n{\"pid\":1,\"tid\":1,\"ph\":\"" + eventType + "\",\"cat\":\"" + phase + "\",\"ts\":" + time + ",\"name\":\"" + name + "\""); @@ -3603,15 +3613,24 @@ var ts; ts.performance.mark("endTracing"); ts.performance.measure("Tracing", "beginTracing", "endTracing"); } - function indexFromOne(lc) { - return { - line: lc.line + 1, - character: lc.character + 1, - }; + function getLocation(node) { + var file = ts.getSourceFileOfNode(node); + return !file + ? undefined + : { + path: file.path, + start: indexFromOne(ts.getLineAndCharacterOfPosition(file, node.pos)), + end: indexFromOne(ts.getLineAndCharacterOfPosition(file, node.end)), + }; + function indexFromOne(lc) { + return { + line: lc.line + 1, + character: lc.character + 1, + }; + } } function dumpTypes(types) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; - ts.Debug.assert(fs); + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x; ts.performance.mark("beginDumpTypes"); var typesPath = legend[legend.length - 1].typesPath; var typesFd = fs.openSync(typesPath, "w"); @@ -3623,15 +3642,13 @@ var ts; var type = types[i]; var objectFlags = type.objectFlags; var symbol = (_a = type.aliasSymbol) !== null && _a !== void 0 ? _a : type.symbol; - var firstDeclaration = (_b = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _b === void 0 ? void 0 : _b[0]; - var firstFile = firstDeclaration && ts.getSourceFileOfNode(firstDeclaration); // It's slow to compute the display text, so skip it unless it's really valuable (or cheap) var display = void 0; if ((objectFlags & 16 /* Anonymous */) | (type.flags & 2944 /* Literal */)) { try { - display = (_c = type.checker) === null || _c === void 0 ? void 0 : _c.typeToString(type); + display = (_b = type.checker) === null || _b === void 0 ? void 0 : _b.typeToString(type); } - catch (_s) { + catch (_y) { display = undefined; } } @@ -3639,26 +3656,52 @@ var ts; if (type.flags & 8388608 /* IndexedAccess */) { var indexedAccessType = type; indexedAccessProperties = { - indexedAccessObjectType: (_d = indexedAccessType.objectType) === null || _d === void 0 ? void 0 : _d.id, - indexedAccessIndexType: (_e = indexedAccessType.indexType) === null || _e === void 0 ? void 0 : _e.id, + indexedAccessObjectType: (_c = indexedAccessType.objectType) === null || _c === void 0 ? void 0 : _c.id, + indexedAccessIndexType: (_d = indexedAccessType.indexType) === null || _d === void 0 ? void 0 : _d.id, }; } var referenceProperties = {}; if (objectFlags & 4 /* Reference */) { var referenceType = type; referenceProperties = { - instantiatedType: (_f = referenceType.target) === null || _f === void 0 ? void 0 : _f.id, - typeArguments: (_g = referenceType.resolvedTypeArguments) === null || _g === void 0 ? void 0 : _g.map(function (t) { return t.id; }), + instantiatedType: (_e = referenceType.target) === null || _e === void 0 ? void 0 : _e.id, + typeArguments: (_f = referenceType.resolvedTypeArguments) === null || _f === void 0 ? void 0 : _f.map(function (t) { return t.id; }), + referenceLocation: getLocation(referenceType.node), }; } var conditionalProperties = {}; if (type.flags & 16777216 /* Conditional */) { var conditionalType = type; conditionalProperties = { - conditionalCheckType: (_h = conditionalType.checkType) === null || _h === void 0 ? void 0 : _h.id, - conditionalExtendsType: (_j = conditionalType.extendsType) === null || _j === void 0 ? void 0 : _j.id, - conditionalTrueType: (_l = (_k = conditionalType.resolvedTrueType) === null || _k === void 0 ? void 0 : _k.id) !== null && _l !== void 0 ? _l : -1, - conditionalFalseType: (_o = (_m = conditionalType.resolvedFalseType) === null || _m === void 0 ? void 0 : _m.id) !== null && _o !== void 0 ? _o : -1, + conditionalCheckType: (_g = conditionalType.checkType) === null || _g === void 0 ? void 0 : _g.id, + conditionalExtendsType: (_h = conditionalType.extendsType) === null || _h === void 0 ? void 0 : _h.id, + conditionalTrueType: (_k = (_j = conditionalType.resolvedTrueType) === null || _j === void 0 ? void 0 : _j.id) !== null && _k !== void 0 ? _k : -1, + conditionalFalseType: (_m = (_l = conditionalType.resolvedFalseType) === null || _l === void 0 ? void 0 : _l.id) !== null && _m !== void 0 ? _m : -1, + }; + } + var substitutionProperties = {}; + if (type.flags & 33554432 /* Substitution */) { + var substitutionType = type; + substitutionProperties = { + substitutionBaseType: (_o = substitutionType.baseType) === null || _o === void 0 ? void 0 : _o.id, + substituteType: (_p = substitutionType.substitute) === null || _p === void 0 ? void 0 : _p.id, + }; + } + var reverseMappedProperties = {}; + if (objectFlags & 1024 /* ReverseMapped */) { + var reverseMappedType = type; + reverseMappedProperties = { + reverseMappedSourceType: (_q = reverseMappedType.source) === null || _q === void 0 ? void 0 : _q.id, + reverseMappedMappedType: (_r = reverseMappedType.mappedType) === null || _r === void 0 ? void 0 : _r.id, + reverseMappedConstraintType: (_s = reverseMappedType.constraintType) === null || _s === void 0 ? void 0 : _s.id, + }; + } + var evolvingArrayProperties = {}; + if (objectFlags & 256 /* EvolvingArray */) { + var evolvingArrayType = type; + evolvingArrayProperties = { + evolvingArrayElementType: evolvingArrayType.elementType.id, + evolvingArrayFinalType: (_t = evolvingArrayType.finalArrayType) === null || _t === void 0 ? void 0 : _t.id, }; } // We can't print out an arbitrary object, so just assign each one a unique number. @@ -3672,11 +3715,7 @@ var ts; recursionIdentityMap.set(recursionIdentity, recursionToken); } } - var descriptor = __assign(__assign(__assign(__assign({ id: type.id, intrinsicName: type.intrinsicName, symbolName: (symbol === null || symbol === void 0 ? void 0 : symbol.escapedName) && ts.unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, unionTypes: (type.flags & 1048576 /* Union */) ? (_p = type.types) === null || _p === void 0 ? void 0 : _p.map(function (t) { return t.id; }) : undefined, intersectionTypes: (type.flags & 2097152 /* Intersection */) ? type.types.map(function (t) { return t.id; }) : undefined, aliasTypeArguments: (_q = type.aliasTypeArguments) === null || _q === void 0 ? void 0 : _q.map(function (t) { return t.id; }), keyofType: (type.flags & 4194304 /* Index */) ? (_r = type.type) === null || _r === void 0 ? void 0 : _r.id : undefined }, indexedAccessProperties), referenceProperties), conditionalProperties), { firstDeclaration: firstDeclaration && { - path: firstFile.path, - start: indexFromOne(ts.getLineAndCharacterOfPosition(firstFile, firstDeclaration.pos)), - end: indexFromOne(ts.getLineAndCharacterOfPosition(ts.getSourceFileOfNode(firstDeclaration), firstDeclaration.end)), - }, flags: ts.Debug.formatTypeFlags(type.flags).split("|"), display: display }); + var descriptor = __assign(__assign(__assign(__assign(__assign(__assign(__assign({ id: type.id, intrinsicName: type.intrinsicName, symbolName: (symbol === null || symbol === void 0 ? void 0 : symbol.escapedName) && ts.unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, isTuple: objectFlags & 8 /* Tuple */ ? true : undefined, unionTypes: (type.flags & 1048576 /* Union */) ? (_u = type.types) === null || _u === void 0 ? void 0 : _u.map(function (t) { return t.id; }) : undefined, intersectionTypes: (type.flags & 2097152 /* Intersection */) ? type.types.map(function (t) { return t.id; }) : undefined, aliasTypeArguments: (_v = type.aliasTypeArguments) === null || _v === void 0 ? void 0 : _v.map(function (t) { return t.id; }), keyofType: (type.flags & 4194304 /* Index */) ? (_w = type.type) === null || _w === void 0 ? void 0 : _w.id : undefined }, indexedAccessProperties), referenceProperties), conditionalProperties), substitutionProperties), reverseMappedProperties), evolvingArrayProperties), { destructuringPattern: getLocation(type.pattern), firstDeclaration: getLocation((_x = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _x === void 0 ? void 0 : _x[0]), flags: ts.Debug.formatTypeFlags(type.flags).split("|"), display: display }); fs.writeSync(typesFd, JSON.stringify(descriptor)); if (i < numTypes - 1) { fs.writeSync(typesFd, ",\n"); @@ -3691,11 +3730,13 @@ var ts; if (!legendPath) { return; } - ts.Debug.assert(fs); fs.writeFileSync(legendPath, JSON.stringify(legend)); } - tracing.dumpLegend = dumpLegend; - })(tracing = ts.tracing || (ts.tracing = {})); + tracingEnabled.dumpLegend = dumpLegend; + })(tracingEnabled || (tracingEnabled = {})); + // define after tracingEnabled is initialized + ts.startTracing = tracingEnabled.startTracing; + ts.dumpTracingLegend = tracingEnabled.dumpLegend; })(ts || (ts = {})); var ts; (function (ts) { @@ -3871,215 +3912,216 @@ var ts; SyntaxKind[SyntaxKind["FromKeyword"] = 153] = "FromKeyword"; SyntaxKind[SyntaxKind["GlobalKeyword"] = 154] = "GlobalKeyword"; SyntaxKind[SyntaxKind["BigIntKeyword"] = 155] = "BigIntKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 156] = "OfKeyword"; + SyntaxKind[SyntaxKind["OverrideKeyword"] = 156] = "OverrideKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 157] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 157] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 158] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 158] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 159] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 159] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 160] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 161] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 160] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 161] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 162] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 162] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 163] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 164] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 165] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 166] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 167] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 168] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 169] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 170] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 171] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 163] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 164] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 165] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 166] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 167] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 168] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 169] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 170] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 171] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 172] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 172] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 173] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 174] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 175] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 176] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 177] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 178] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 179] = "TupleType"; - SyntaxKind[SyntaxKind["OptionalType"] = 180] = "OptionalType"; - SyntaxKind[SyntaxKind["RestType"] = 181] = "RestType"; - SyntaxKind[SyntaxKind["UnionType"] = 182] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 183] = "IntersectionType"; - SyntaxKind[SyntaxKind["ConditionalType"] = 184] = "ConditionalType"; - SyntaxKind[SyntaxKind["InferType"] = 185] = "InferType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 186] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 187] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 188] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 189] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 190] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 191] = "LiteralType"; - SyntaxKind[SyntaxKind["NamedTupleMember"] = 192] = "NamedTupleMember"; - SyntaxKind[SyntaxKind["TemplateLiteralType"] = 193] = "TemplateLiteralType"; - SyntaxKind[SyntaxKind["TemplateLiteralTypeSpan"] = 194] = "TemplateLiteralTypeSpan"; - SyntaxKind[SyntaxKind["ImportType"] = 195] = "ImportType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 173] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 174] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 175] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 176] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 177] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 178] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 179] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 180] = "TupleType"; + SyntaxKind[SyntaxKind["OptionalType"] = 181] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 182] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 183] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 184] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 185] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 186] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 187] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 188] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 189] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 190] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 191] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 192] = "LiteralType"; + SyntaxKind[SyntaxKind["NamedTupleMember"] = 193] = "NamedTupleMember"; + SyntaxKind[SyntaxKind["TemplateLiteralType"] = 194] = "TemplateLiteralType"; + SyntaxKind[SyntaxKind["TemplateLiteralTypeSpan"] = 195] = "TemplateLiteralTypeSpan"; + SyntaxKind[SyntaxKind["ImportType"] = 196] = "ImportType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 196] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 197] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 198] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 197] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 198] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 199] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 199] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 200] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 201] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 202] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 203] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 204] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 205] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 206] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 207] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 208] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 209] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 210] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 211] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 212] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 213] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 214] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 215] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 216] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 217] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 218] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 219] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 220] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 221] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 222] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 223] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 224] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 225] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 226] = "MetaProperty"; - SyntaxKind[SyntaxKind["SyntheticExpression"] = 227] = "SyntheticExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 200] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 201] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 202] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 203] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 204] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 205] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 206] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 207] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 208] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 209] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 210] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 211] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 212] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 213] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 214] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 215] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 216] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 217] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 218] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 219] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 220] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 221] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 222] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 223] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 224] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 225] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 226] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 227] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 228] = "SyntheticExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 228] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 229] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 229] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 230] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 230] = "Block"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 231] = "EmptyStatement"; - SyntaxKind[SyntaxKind["VariableStatement"] = 232] = "VariableStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 233] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 234] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 235] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 236] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 237] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 238] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 239] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 240] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 241] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 242] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 243] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 244] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 245] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 246] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 247] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 248] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 249] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 250] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 251] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 252] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 253] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 254] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 255] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 256] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 257] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 258] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 259] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 260] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 261] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 262] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 263] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 264] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 265] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 266] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 267] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 268] = "NamedExports"; - SyntaxKind[SyntaxKind["NamespaceExport"] = 269] = "NamespaceExport"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 270] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 271] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 231] = "Block"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 232] = "EmptyStatement"; + SyntaxKind[SyntaxKind["VariableStatement"] = 233] = "VariableStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 234] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 235] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 236] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 237] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 238] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 239] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 240] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 241] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 242] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 243] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 244] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 245] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 246] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 247] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 248] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 249] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 250] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 251] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 252] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 253] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 254] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 255] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 256] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 257] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 258] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 259] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 260] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 261] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 262] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 263] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 264] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 265] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 266] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 267] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 268] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 269] = "NamedExports"; + SyntaxKind[SyntaxKind["NamespaceExport"] = 270] = "NamespaceExport"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 271] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 272] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 272] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 273] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 273] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 274] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 275] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 276] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxFragment"] = 277] = "JsxFragment"; - SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 278] = "JsxOpeningFragment"; - SyntaxKind[SyntaxKind["JsxClosingFragment"] = 279] = "JsxClosingFragment"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 280] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 281] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 282] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 283] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 274] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 275] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 276] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 277] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 278] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 279] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 280] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 281] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 282] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 283] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 284] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 284] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 285] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 286] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 287] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 285] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 286] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 287] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 288] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 288] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 289] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 290] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 289] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 290] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 291] = "SpreadAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 291] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 292] = "EnumMember"; // Unparsed - SyntaxKind[SyntaxKind["UnparsedPrologue"] = 292] = "UnparsedPrologue"; - SyntaxKind[SyntaxKind["UnparsedPrepend"] = 293] = "UnparsedPrepend"; - SyntaxKind[SyntaxKind["UnparsedText"] = 294] = "UnparsedText"; - SyntaxKind[SyntaxKind["UnparsedInternalText"] = 295] = "UnparsedInternalText"; - SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 296] = "UnparsedSyntheticReference"; + SyntaxKind[SyntaxKind["UnparsedPrologue"] = 293] = "UnparsedPrologue"; + SyntaxKind[SyntaxKind["UnparsedPrepend"] = 294] = "UnparsedPrepend"; + SyntaxKind[SyntaxKind["UnparsedText"] = 295] = "UnparsedText"; + SyntaxKind[SyntaxKind["UnparsedInternalText"] = 296] = "UnparsedInternalText"; + SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 297] = "UnparsedSyntheticReference"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 297] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 298] = "Bundle"; - SyntaxKind[SyntaxKind["UnparsedSource"] = 299] = "UnparsedSource"; - SyntaxKind[SyntaxKind["InputFiles"] = 300] = "InputFiles"; + SyntaxKind[SyntaxKind["SourceFile"] = 298] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 299] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 300] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 301] = "InputFiles"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 301] = "JSDocTypeExpression"; - SyntaxKind[SyntaxKind["JSDocNameReference"] = 302] = "JSDocNameReference"; - // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 303] = "JSDocAllType"; - // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 304] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 305] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 306] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 307] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 308] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 309] = "JSDocVariadicType"; - // https://jsdoc.app/about-namepaths.html - SyntaxKind[SyntaxKind["JSDocNamepathType"] = 310] = "JSDocNamepathType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 311] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 312] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocSignature"] = 313] = "JSDocSignature"; - SyntaxKind[SyntaxKind["JSDocTag"] = 314] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 315] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 316] = "JSDocImplementsTag"; - SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 317] = "JSDocAuthorTag"; - SyntaxKind[SyntaxKind["JSDocDeprecatedTag"] = 318] = "JSDocDeprecatedTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 319] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocPublicTag"] = 320] = "JSDocPublicTag"; - SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 321] = "JSDocPrivateTag"; - SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 322] = "JSDocProtectedTag"; - SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 323] = "JSDocReadonlyTag"; - SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 324] = "JSDocCallbackTag"; - SyntaxKind[SyntaxKind["JSDocEnumTag"] = 325] = "JSDocEnumTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 326] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 327] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocThisTag"] = 328] = "JSDocThisTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 329] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 330] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 331] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocSeeTag"] = 332] = "JSDocSeeTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 333] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 302] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocNameReference"] = 303] = "JSDocNameReference"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 304] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 305] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 306] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 307] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 308] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 309] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 310] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocNamepathType"] = 311] = "JSDocNamepathType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 312] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocText"] = 313] = "JSDocText"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 314] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 315] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocLink"] = 316] = "JSDocLink"; + SyntaxKind[SyntaxKind["JSDocTag"] = 317] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 318] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 319] = "JSDocImplementsTag"; + SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 320] = "JSDocAuthorTag"; + SyntaxKind[SyntaxKind["JSDocDeprecatedTag"] = 321] = "JSDocDeprecatedTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 322] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocPublicTag"] = 323] = "JSDocPublicTag"; + SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 324] = "JSDocPrivateTag"; + SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 325] = "JSDocProtectedTag"; + SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 326] = "JSDocReadonlyTag"; + SyntaxKind[SyntaxKind["JSDocOverrideTag"] = 327] = "JSDocOverrideTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 328] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 329] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 330] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 331] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 332] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 333] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 334] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 335] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocSeeTag"] = 336] = "JSDocSeeTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 337] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 334] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 338] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 335] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 336] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 337] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 338] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 339] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 340] = "SyntheticReferenceExpression"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 339] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 340] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 341] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 342] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 343] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 344] = "SyntheticReferenceExpression"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 341] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 345] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 62] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 77] = "LastAssignment"; @@ -4088,15 +4130,15 @@ var ts; SyntaxKind[SyntaxKind["FirstReservedWord"] = 80] = "FirstReservedWord"; SyntaxKind[SyntaxKind["LastReservedWord"] = 115] = "LastReservedWord"; SyntaxKind[SyntaxKind["FirstKeyword"] = 80] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 156] = "LastKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 157] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 116] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 124] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 172] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 195] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 173] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 196] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 77] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 156] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 157] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; @@ -4105,15 +4147,15 @@ var ts; SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken"; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 29] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 77] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstStatement"] = 232] = "FirstStatement"; - SyntaxKind[SyntaxKind["LastStatement"] = 248] = "LastStatement"; - SyntaxKind[SyntaxKind["FirstNode"] = 157] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 301] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 333] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 314] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 333] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstStatement"] = 233] = "FirstStatement"; + SyntaxKind[SyntaxKind["LastStatement"] = 249] = "LastStatement"; + SyntaxKind[SyntaxKind["FirstNode"] = 158] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 302] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 337] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 317] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 337] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 125] = "FirstContextualKeyword"; - /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 156] = "LastContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 157] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -4183,14 +4225,15 @@ var ts; ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; ModifierFlags[ModifierFlags["HasComputedJSDocModifiers"] = 4096] = "HasComputedJSDocModifiers"; ModifierFlags[ModifierFlags["Deprecated"] = 8192] = "Deprecated"; + ModifierFlags[ModifierFlags["Override"] = 16384] = "Override"; ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. - ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 16476] = "ParameterPropertyModifier"; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; - ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; + ModifierFlags[ModifierFlags["TypeScriptModifier"] = 18654] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; - ModifierFlags[ModifierFlags["All"] = 11263] = "All"; + ModifierFlags[ModifierFlags["All"] = 27647] = "All"; })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); var JsxFlags; (function (JsxFlags) { @@ -4371,6 +4414,8 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["NoUndefinedOptionalParameterType"] = 1073741824] = "NoUndefinedOptionalParameterType"; // Error handling NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifiedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifiedNameInPlaceOfIdentifier"; + /** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */ NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier"; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection"; @@ -4385,7 +4430,6 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; - NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -4690,10 +4734,6 @@ var ts; TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["StringLikeLiteral"] = 134217856] = "StringLikeLiteral"; - /* @internal */ - TypeFlags[TypeFlags["FreshableLiteral"] = 134220672] = "FreshableLiteral"; - /* @internal */ TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; /* @internal */ TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; @@ -4742,6 +4782,9 @@ var ts; /* @internal */ TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags + // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check + // for a certain TypeFlags value to determine their meaning. var ObjectFlags; (function (ObjectFlags) { ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; @@ -4754,50 +4797,59 @@ var ts; ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; - ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; - ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; - ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; - ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; - ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; - ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral"; - ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 1024] = "ReverseMapped"; + ObjectFlags[ObjectFlags["JsxAttributes"] = 2048] = "JsxAttributes"; + ObjectFlags[ObjectFlags["MarkerType"] = 4096] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 8192] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 16384] = "FreshLiteral"; + ObjectFlags[ObjectFlags["ArrayLiteral"] = 32768] = "ArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion"; + ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType"; + ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral"; + ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 262144] = "ContainsObjectOrArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType"; + ObjectFlags[ObjectFlags["NonInferrableType"] = 524288] = "NonInferrableType"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; + ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 1048576] = "CouldContainTypeVariablesComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; + ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 2097152] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; + ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags"; + // Object flags that uniquely identify the kind of ObjectType /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed"; + ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 1343] = "ObjectTypeKindMask"; + // Flags that require TypeFlags.Object + ObjectFlags[ObjectFlags["ContainsSpread"] = 4194304] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ObjectRestType"] = 8388608] = "ObjectRestType"; /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 16777216] = "IsClassInstanceClone"; + // Flags that require TypeFlags.Object and ObjectFlags.Reference /* @internal */ - ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeCalculated"] = 33554432] = "IdenticalBaseTypeCalculated"; /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeExists"] = 67108864] = "IdenticalBaseTypeExists"; + // Flags that require TypeFlags.UnionOrIntersection or TypeFlags.Substitution /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection"; + ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 1073741824] = "IsClassInstanceClone"; - ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; /* @internal */ - ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; + ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags"; - // Object flags that uniquely identify the kind of ObjectType + ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + // Flags that require TypeFlags.Union + /* @internal */ + ObjectFlags[ObjectFlags["ContainsIntersections"] = 67108864] = "ContainsIntersections"; + // Flags that require TypeFlags.Intersection + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 67108864] = "IsNeverIntersectionComputed"; /* @internal */ - ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 2367] = "ObjectTypeKindMask"; + ObjectFlags[ObjectFlags["IsNeverIntersection"] = 134217728] = "IsNeverIntersection"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ var VarianceFlags; @@ -4871,16 +4923,17 @@ var ts; (function (InferencePriority) { InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; InferencePriority[InferencePriority["SpeculativeTuple"] = 2] = "SpeculativeTuple"; - InferencePriority[InferencePriority["HomomorphicMappedType"] = 4] = "HomomorphicMappedType"; - InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 8] = "PartialHomomorphicMappedType"; - InferencePriority[InferencePriority["MappedTypeConstraint"] = 16] = "MappedTypeConstraint"; - InferencePriority[InferencePriority["ContravariantConditional"] = 32] = "ContravariantConditional"; - InferencePriority[InferencePriority["ReturnType"] = 64] = "ReturnType"; - InferencePriority[InferencePriority["LiteralKeyof"] = 128] = "LiteralKeyof"; - InferencePriority[InferencePriority["NoConstraints"] = 256] = "NoConstraints"; - InferencePriority[InferencePriority["AlwaysStrict"] = 512] = "AlwaysStrict"; - InferencePriority[InferencePriority["MaxValue"] = 1024] = "MaxValue"; - InferencePriority[InferencePriority["PriorityImpliesCombination"] = 208] = "PriorityImpliesCombination"; + InferencePriority[InferencePriority["SubstituteSource"] = 4] = "SubstituteSource"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 8] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 16] = "PartialHomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 32] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ContravariantConditional"] = 64] = "ContravariantConditional"; + InferencePriority[InferencePriority["ReturnType"] = 128] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 256] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 512] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 1024] = "AlwaysStrict"; + InferencePriority[InferencePriority["MaxValue"] = 2048] = "MaxValue"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 416] = "PriorityImpliesCombination"; InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); /* @internal */ @@ -4958,20 +5011,23 @@ var ts; WatchFileKind[WatchFileKind["FixedPollingInterval"] = 0] = "FixedPollingInterval"; WatchFileKind[WatchFileKind["PriorityPollingInterval"] = 1] = "PriorityPollingInterval"; WatchFileKind[WatchFileKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; - WatchFileKind[WatchFileKind["UseFsEvents"] = 3] = "UseFsEvents"; - WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 4] = "UseFsEventsOnParentDirectory"; + WatchFileKind[WatchFileKind["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; + WatchFileKind[WatchFileKind["UseFsEvents"] = 4] = "UseFsEvents"; + WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 5] = "UseFsEventsOnParentDirectory"; })(WatchFileKind = ts.WatchFileKind || (ts.WatchFileKind = {})); var WatchDirectoryKind; (function (WatchDirectoryKind) { WatchDirectoryKind[WatchDirectoryKind["UseFsEvents"] = 0] = "UseFsEvents"; WatchDirectoryKind[WatchDirectoryKind["FixedPollingInterval"] = 1] = "FixedPollingInterval"; WatchDirectoryKind[WatchDirectoryKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; + WatchDirectoryKind[WatchDirectoryKind["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; })(WatchDirectoryKind = ts.WatchDirectoryKind || (ts.WatchDirectoryKind = {})); var PollingWatchKind; (function (PollingWatchKind) { PollingWatchKind[PollingWatchKind["FixedInterval"] = 0] = "FixedInterval"; PollingWatchKind[PollingWatchKind["PriorityInterval"] = 1] = "PriorityInterval"; PollingWatchKind[PollingWatchKind["DynamicPriority"] = 2] = "DynamicPriority"; + PollingWatchKind[PollingWatchKind["FixedChunkSize"] = 3] = "FixedChunkSize"; })(PollingWatchKind = ts.PollingWatchKind || (ts.PollingWatchKind = {})); var ModuleKind; (function (ModuleKind) { @@ -5032,6 +5088,7 @@ var ts; ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019"; ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020"; + ScriptTarget[ScriptTarget["ES2021"] = 8] = "ES2021"; ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext"; ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest"; @@ -5194,29 +5251,30 @@ var ts; TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript"; TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx"; TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext"; - TransformFlags[TransformFlags["ContainsES2020"] = 8] = "ContainsES2020"; - TransformFlags[TransformFlags["ContainsES2019"] = 16] = "ContainsES2019"; - TransformFlags[TransformFlags["ContainsES2018"] = 32] = "ContainsES2018"; - TransformFlags[TransformFlags["ContainsES2017"] = 64] = "ContainsES2017"; - TransformFlags[TransformFlags["ContainsES2016"] = 128] = "ContainsES2016"; - TransformFlags[TransformFlags["ContainsES2015"] = 256] = "ContainsES2015"; - TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; - TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 1024] = "ContainsDestructuringAssignment"; + TransformFlags[TransformFlags["ContainsES2021"] = 8] = "ContainsES2021"; + TransformFlags[TransformFlags["ContainsES2020"] = 16] = "ContainsES2020"; + TransformFlags[TransformFlags["ContainsES2019"] = 32] = "ContainsES2019"; + TransformFlags[TransformFlags["ContainsES2018"] = 64] = "ContainsES2018"; + TransformFlags[TransformFlags["ContainsES2017"] = 128] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 256] = "ContainsES2016"; + TransformFlags[TransformFlags["ContainsES2015"] = 512] = "ContainsES2015"; + TransformFlags[TransformFlags["ContainsGenerator"] = 1024] = "ContainsGenerator"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 2048] = "ContainsTypeScriptClassSyntax"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 4096] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsRestOrSpread"] = 8192] = "ContainsRestOrSpread"; - TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 16384] = "ContainsObjectRestOrSpread"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 32768] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 65536] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 131072] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 262144] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsAwait"] = 524288] = "ContainsAwait"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 1048576] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 2097152] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["ContainsClassFields"] = 4194304] = "ContainsClassFields"; - TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 8388608] = "ContainsPossibleTopLevelAwait"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 16384] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 32768] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 65536] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 131072] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 262144] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 524288] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsAwait"] = 1048576] = "ContainsAwait"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 2097152] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 4194304] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["ContainsClassFields"] = 8388608] = "ContainsClassFields"; + TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 16777216] = "ContainsPossibleTopLevelAwait"; // 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 @@ -5226,37 +5284,38 @@ var ts; TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript"; TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx"; TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext"; - TransformFlags[TransformFlags["AssertES2020"] = 8] = "AssertES2020"; - TransformFlags[TransformFlags["AssertES2019"] = 16] = "AssertES2019"; - TransformFlags[TransformFlags["AssertES2018"] = 32] = "AssertES2018"; - TransformFlags[TransformFlags["AssertES2017"] = 64] = "AssertES2017"; - TransformFlags[TransformFlags["AssertES2016"] = 128] = "AssertES2016"; - TransformFlags[TransformFlags["AssertES2015"] = 256] = "AssertES2015"; - TransformFlags[TransformFlags["AssertGenerator"] = 512] = "AssertGenerator"; - TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 1024] = "AssertDestructuringAssignment"; + TransformFlags[TransformFlags["AssertES2021"] = 8] = "AssertES2021"; + TransformFlags[TransformFlags["AssertES2020"] = 16] = "AssertES2020"; + TransformFlags[TransformFlags["AssertES2019"] = 32] = "AssertES2019"; + TransformFlags[TransformFlags["AssertES2018"] = 64] = "AssertES2018"; + TransformFlags[TransformFlags["AssertES2017"] = 128] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 256] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 512] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 1024] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 2048] = "AssertDestructuringAssignment"; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes"; TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes"; TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 547309568] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 547313664] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 547311616] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 538923008] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["PropertyExcludes"] = 536875008] = "PropertyExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 536905728] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 546379776] = "ModuleExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 557748224] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 557756416] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 557752320] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 540975104] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["PropertyExcludes"] = 536879104] = "PropertyExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 536940544] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 555888640] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536922112] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536879104] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537018368] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536973312] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536887296] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537165824] = "VariableDeclarationListExcludes"; TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 536887296] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 536879104] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 536903680] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 536887296] = "BindingPatternExcludes"; // Propagating flags // - Bitmasks for flags that should propagate from a child - TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 4096] = "PropertyNamePropagatingFlags"; + TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 8192] = "PropertyNamePropagatingFlags"; // Masks // - Additional bitmasks })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); @@ -6124,7 +6183,7 @@ var ts; * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. * Comparison is case-sensitive between the canonical paths. * - * @deprecated Use `containsPath` if possible. + * Use `containsPath` if file names are not already reduced and absolute. */ function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { var canonicalFileName = getCanonicalFileName(fileName); @@ -6244,6 +6303,11 @@ var ts; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time + /* @internal */ + function getModifiedTime(host, fileName) { + return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; + } + ts.getModifiedTime = getModifiedTime; function createPollingIntervalBasedLevels(levels) { var _a; return _a = {}, @@ -6300,6 +6364,51 @@ var ts; } } ts.setCustomPollingValues = setCustomPollingValues; + function pollWatchedFileQueue(host, queue, pollIndex, chunkSize, callbackOnWatchFileStat) { + var definedValueCopyToIndex = pollIndex; + // Max visit would be all elements of the queue + for (var canVisit = queue.length; chunkSize && canVisit; nextPollIndex(), canVisit--) { + var watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + // Only files polled count towards chunkSize + chunkSize--; + var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(host, watchedFile.fileName)); + if (watchedFile.isClosed) { + // Closed watcher as part of callback + queue[pollIndex] = undefined; + continue; + } + callbackOnWatchFileStat === null || callbackOnWatchFileStat === void 0 ? void 0 : callbackOnWatchFileStat(watchedFile, pollIndex, fileChanged); + // Defragment the queue while we are at it + if (queue[pollIndex]) { + // Copy this file to the non hole location + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + // Return next poll index + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + // There are holes from definedValueCopyToIndex to end of queue, change queue size + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } /* @internal */ function createDynamicPriorityPollingWatchFile(host) { var watchedFiles = []; @@ -6313,7 +6422,7 @@ var ts; fileName: fileName, callback: callback, unchangedPolls: 0, - mtime: getModifiedTime(fileName) + mtime: getModifiedTime(host, fileName) }; watchedFiles.push(file); addToPollingIntervalQueue(file, defaultPollingInterval); @@ -6356,25 +6465,9 @@ var ts; } } function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { - // Max visit would be all elements of the queue - var needsVisit = queue.length; - var definedValueCopyToIndex = pollIndex; - for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { - var watchedFile = queue[pollIndex]; - if (!watchedFile) { - continue; - } - else if (watchedFile.isClosed) { - queue[pollIndex] = undefined; - continue; - } - polled++; - var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); - if (watchedFile.isClosed) { - // Closed watcher as part of callback - queue[pollIndex] = undefined; - } - else if (fileChanged) { + return pollWatchedFileQueue(host, queue, pollIndex, chunkSize, onWatchFileStat); + function onWatchFileStat(watchedFile, pollIndex, fileChanged) { + if (fileChanged) { watchedFile.unchangedPolls = 0; // Changed files go to changedFilesInLastPoll queue if (queue !== changedFilesInLastPoll) { @@ -6396,27 +6489,6 @@ var ts; queue[pollIndex] = undefined; addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); } - if (queue[pollIndex]) { - // Copy this file to the non hole location - if (definedValueCopyToIndex < pollIndex) { - queue[definedValueCopyToIndex] = watchedFile; - queue[pollIndex] = undefined; - } - definedValueCopyToIndex++; - } - } - // Return next poll index - return pollIndex; - function nextPollIndex() { - pollIndex++; - if (pollIndex === queue.length) { - if (definedValueCopyToIndex < pollIndex) { - // There are holes from nextDefinedValueIndex to end of queue, change queue size - queue.length = definedValueCopyToIndex; - } - pollIndex = 0; - definedValueCopyToIndex = 0; - } } } function pollingIntervalQueue(pollingInterval) { @@ -6445,9 +6517,6 @@ var ts; function scheduleNextPoll(pollingInterval) { pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); } - function getModifiedTime(fileName) { - return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; - } } ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) { @@ -6498,6 +6567,37 @@ var ts; return watcher; } } + function createFixedChunkSizePollingWatchFile(host) { + var watchedFiles = []; + var pollIndex = 0; + var pollScheduled; + return watchFile; + function watchFile(fileName, callback) { + var file = { + fileName: fileName, + callback: callback, + mtime: getModifiedTime(host, fileName) + }; + watchedFiles.push(file); + scheduleNextPoll(); + return { + close: function () { + file.isClosed = true; + ts.unorderedRemoveItem(watchedFiles, file); + } + }; + } + function pollQueue() { + pollScheduled = undefined; + pollIndex = pollWatchedFileQueue(host, watchedFiles, pollIndex, pollingChunkSize[PollingInterval.Low]); + scheduleNextPoll(); + } + function scheduleNextPoll() { + if (!watchedFiles.length || pollScheduled) + return; + pollScheduled = host.setTimeout(pollQueue, PollingInterval.High); + } + } /* @internal */ function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) { var cache = new ts.Map(); @@ -6820,8 +6920,9 @@ var ts; } /*@internal*/ function createSystemWatchFunctions(_a) { - var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory; + var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind; var dynamicPollingWatchFile; + var fixedChunkSizePollingWatchFile; var nonPollingWatchFile; var hostRecursiveDirectoryWatcher; return { @@ -6838,6 +6939,8 @@ var ts; return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined); case ts.WatchFileKind.DynamicPriorityPolling: return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined); + case ts.WatchFileKind.FixedChunkSizePolling: + return ensureFixedChunkSizePollingWatchFile()(fileName, callback, /* pollingInterval */ undefined, /*options*/ undefined); case ts.WatchFileKind.UseFsEvents: return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options)); @@ -6851,8 +6954,10 @@ var ts; } } function ensureDynamicPollingWatchFile() { - return dynamicPollingWatchFile || - (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })); + return dynamicPollingWatchFile || (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })); + } + function ensureFixedChunkSizePollingWatchFile() { + return fixedChunkSizePollingWatchFile || (fixedChunkSizePollingWatchFile = createFixedChunkSizePollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })); } function updateOptionsForWatchFile(options, useNonPollingWatchers) { if (options && options.watchFile !== undefined) @@ -6878,7 +6983,7 @@ var ts; // Use notifications from FS to watch with falling back to fs.watchFile generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) : // Default to do not use fixed polling interval - { watchFile: ts.WatchFileKind.FixedPollingInterval }; + { watchFile: (defaultWatchFileKind === null || defaultWatchFileKind === void 0 ? void 0 : defaultWatchFileKind()) || ts.WatchFileKind.FixedPollingInterval }; } } function generateWatchFileOptions(watchFile, fallbackPolling, options) { @@ -6919,6 +7024,10 @@ var ts; case ts.WatchDirectoryKind.DynamicPriorityPolling: return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, /*options*/ undefined); + case ts.WatchDirectoryKind.FixedChunkSizePolling: + return ensureFixedChunkSizePollingWatchFile()(directoryName, function () { return callback(directoryName); }, + /* pollingInterval */ undefined, + /*options*/ undefined); case ts.WatchDirectoryKind.UseFsEvents: return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), recursive, PollingInterval.Medium, ts.getFallbackOptions(watchDirectoryOptions)); default: @@ -6997,13 +7106,13 @@ var ts; } var activeSession; var profilePath = "./profile.cpuprofile"; - var realpathSync = (_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync; var Buffer = require("buffer").Buffer; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + var realpathSync = useCaseSensitiveFileNames ? ((_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync) : _fs.realpathSync; var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); var getCurrentDirectory = ts.memoize(function () { return process.cwd(); }); var _c = createSystemWatchFunctions({ @@ -7024,6 +7133,7 @@ var ts; tscWatchFile: process.env.TSC_WATCHFILE, useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER, tscWatchDirectory: process.env.TSC_WATCHDIRECTORY, + defaultWatchFileKind: function () { var _a, _b; return (_b = (_a = sys).defaultWatchFileKind) === null || _b === void 0 ? void 0 : _b.call(_a); }, }), watchFile = _c.watchFile, watchDirectory = _c.watchDirectory; var nodeSystem = { args: process.argv.slice(2), @@ -7092,6 +7202,7 @@ var ts; }, enableCPUProfiler: enableCPUProfiler, disableCPUProfiler: disableCPUProfiler, + cpuProfilingEnabled: function () { return !!activeSession || ts.contains(process.execArgv, "--cpu-prof") || ts.contains(process.execArgv, "--prof"); }, realpath: realpath, debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -7341,7 +7452,7 @@ var ts; return event === "rename" && (!relativeName || relativeName === lastDirectoryPart || - relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) && + (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && !fileSystemEntryExists(fileOrDirectory, entryKind) ? invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : callback(event, relativeName); @@ -7651,7 +7762,7 @@ var ts; Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1103, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103", "'for await' loops are only allowed within async functions and at the top levels of modules."), A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), @@ -7700,7 +7811,7 @@ var ts; A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), - A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_1166", "A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type."), A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), @@ -7760,7 +7871,7 @@ var ts; A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), - An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231", "An export assignment must be at the top level of a file or module declaration."), An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), @@ -7786,6 +7897,7 @@ var ts; A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1258, ts.DiagnosticCategory.Error, "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258", "A default export must be at the top level of a file or module declaration."), Module_0_can_only_be_default_imported_using_the_1_flag: diag(1259, ts.DiagnosticCategory.Error, "Module_0_can_only_be_default_imported_using_the_1_flag_1259", "Module '{0}' can only be default-imported using the '{1}' flag"), Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), @@ -7872,7 +7984,7 @@ var ts; Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), Provides_a_root_package_name_when_using_outFile_with_declarations: diag(1390, ts.DiagnosticCategory.Message, "Provides_a_root_package_name_when_using_outFile_with_declarations_1390", "Provides a root package name when using outFile with declarations."), - The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The `bundledPackageName` option must be provided when using outFile and node module resolution with declaration emit."), + The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The 'bundledPackageName' option must be provided when using outFile and node module resolution with declaration emit."), An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), @@ -7912,6 +8024,9 @@ var ts; File_is_output_of_project_reference_source_0: diag(1428, ts.DiagnosticCategory.Message, "File_is_output_of_project_reference_source_0_1428", "File is output of project reference source '{0}'"), File_redirects_to_file_0: diag(1429, ts.DiagnosticCategory.Message, "File_redirects_to_file_0_1429", "File redirects to file '{0}'"), The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), + for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), + Decorators_may_not_be_applied_to_this_parameters: diag(1433, ts.DiagnosticCategory.Error, "Decorators_may_not_be_applied_to_this_parameters_1433", "Decorators may not be applied to 'this' parameters."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -7979,7 +8094,7 @@ var ts; The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), - The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_in_expression_must_not_be_a_primitive: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_not_be_a_primitive_2361", "The right-hand side of an 'in' expression must not be a primitive."), The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), @@ -7997,8 +8112,7 @@ var ts; A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers."), Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), - Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."), - get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."), + The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type: diag(2380, ts.DiagnosticCategory.Error, "The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type_2380", "The return type of a 'get' accessor must be assignable to its 'set' accessor type"), A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."), Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."), Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), @@ -8061,7 +8175,7 @@ var ts; Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), - Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_cl_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'. This is an instance of class '{2}'."), The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), @@ -8161,14 +8275,13 @@ var ts; The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the `lib` compiler option to '{2}' or later."), + Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{2}' or later."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), - Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), - Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), + A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter: diag(2556, ts.DiagnosticCategory.Error, "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556", "A spread argument must either have a tuple type or be passed to a rest parameter."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), @@ -8191,17 +8304,17 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to '{1}' or later."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{1}' or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later."), Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."), Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add `node` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add `jquery` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add 'jquery' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), @@ -8234,6 +8347,12 @@ var ts; Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target: diag(2625, ts.DiagnosticCategory.Error, "Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target_2625", "Variadic element at position {0} in source does not match element at position {1} in target."), Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target: diag(2626, ts.DiagnosticCategory.Error, "Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target_2626", "Type at position {0} in source is not compatible with type at position {1} in target."), Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target: diag(2627, ts.DiagnosticCategory.Error, "Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target_2627", "Type at positions {0} through {1} in source is not compatible with type at position {2} in target."), + Cannot_assign_to_0_because_it_is_an_enum: diag(2628, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_an_enum_2628", "Cannot assign to '{0}' because it is an enum."), + Cannot_assign_to_0_because_it_is_a_class: diag(2629, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_class_2629", "Cannot assign to '{0}' because it is a class."), + Cannot_assign_to_0_because_it_is_a_function: diag(2630, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_function_2630", "Cannot assign to '{0}' because it is a function."), + Cannot_assign_to_0_because_it_is_a_namespace: diag(2631, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_namespace_2631", "Cannot assign to '{0}' because it is a namespace."), + Cannot_assign_to_0_because_it_is_an_import: diag(2632, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_an_import_2632", "Cannot assign to '{0}' because it is an import."), + JSX_property_access_expressions_cannot_include_JSX_namespace_names: diag(2633, ts.DiagnosticCategory.Error, "JSX_property_access_expressions_cannot_include_JSX_namespace_names_2633", "JSX property access expressions cannot include JSX namespace names"), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -8280,7 +8399,7 @@ var ts; Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), @@ -8288,14 +8407,14 @@ var ts; _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a 'delete' operator must be a property reference."), The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a 'delete' operator cannot be a read-only property."), - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), - A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), - A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), @@ -8357,7 +8476,7 @@ var ts; The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."), Overload_0_of_1_2_gave_the_following_error: diag(2772, ts.DiagnosticCategory.Error, "Overload_0_of_1_2_gave_the_following_error_2772", "Overload {0} of {1}, '{2}', gave the following error."), Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"), - This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it__2774", "This condition will always return true since the function is always defined. Did you mean to call it instead?"), + This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774", "This condition will always return true since this function is always defined. Did you mean to call it instead?"), Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation: diag(2775, ts.DiagnosticCategory.Error, "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775", "Assertions require every name in the call target to be declared with an explicit type annotation."), Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name: diag(2776, ts.DiagnosticCategory.Error, "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776", "Assertions require the call target to be an identifier or qualified name."), The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access: diag(2777, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777", "The operand of an increment or decrement operator may not be an optional property access."), @@ -8381,6 +8500,21 @@ var ts; The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types: diag(2795, ts.DiagnosticCategory.Error, "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795", "The 'intrinsic' keyword can only be used to declare compiler provided intrinsic types."), It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked: diag(2796, ts.DiagnosticCategory.Error, "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796", "It is likely that you are missing a comma to separate these two template expressions. They form a tagged template expression which cannot be invoked."), A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract: diag(2797, ts.DiagnosticCategory.Error, "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797", "A mixin class that extends from a type variable containing an abstract construct signature must also be declared 'abstract'."), + The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), + Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), + Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), + This_condition_will_always_return_true_since_this_0_is_always_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_is_always_defined_2801", "This condition will always return true since this '{0}' is always defined."), + Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher: diag(2802, ts.DiagnosticCategory.Error, "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802", "Type '{0}' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher."), + Cannot_assign_to_private_method_0_Private_methods_are_not_writable: diag(2803, ts.DiagnosticCategory.Error, "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803", "Cannot assign to private method '{0}'. Private methods are not writable."), + Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name: diag(2804, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804", "Duplicate identifier '{0}'. Static and instance elements cannot share the same private name."), + Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag: diag(2805, ts.DiagnosticCategory.Error, "Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_no_2805", "Static fields with private names can't have initializers when the '--useDefineForClassFields' flag is not specified with a '--target' of 'esnext'. Consider adding the '--useDefineForClassFields' flag."), + Private_accessor_was_defined_without_a_getter: diag(2806, ts.DiagnosticCategory.Error, "Private_accessor_was_defined_without_a_getter_2806", "Private accessor was defined without a getter."), + This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0: diag(2807, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807", "This syntax requires an imported helper named '{1}' with {2} parameters, which is not compatible with the one in '{0}'. Consider upgrading your version of '{0}'."), + A_get_accessor_must_be_at_least_as_accessible_as_the_setter: diag(2808, ts.DiagnosticCategory.Error, "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808", "A get accessor must be at least as accessible as the setter"), + Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses: diag(2809, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809", "Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses."), + Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false: diag(2810, ts.DiagnosticCategory.Error, "Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnex_2810", "Property '{0}' may not be used in a static property's initializer in the same class when 'target' is 'esnext' and 'useDefineForClassFields' is 'false'."), + Initializer_for_property_0: diag(2811, ts.DiagnosticCategory.Error, "Initializer_for_property_0_2811", "Initializer for property '{0}'"), + Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom: diag(2812, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812", "Property '{0}' does not exist on type '{1}'. Try changing the 'lib' compiler option to include 'dom'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -8453,6 +8587,7 @@ var ts; Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2: diag(4084, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084", "Exported type alias '{0}' has or is using private name '{1}' from module {2}."), Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), @@ -8474,6 +8609,11 @@ var ts; Type_arguments_for_0_circularly_reference_themselves: diag(4109, ts.DiagnosticCategory.Error, "Type_arguments_for_0_circularly_reference_themselves_4109", "Type arguments for '{0}' circularly reference themselves."), Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."), Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0: diag(4111, ts.DiagnosticCategory.Error, "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111", "Property '{0}' comes from an index signature, so it must be accessed with ['{0}']."), + This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class: diag(4112, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112", "This member cannot have an 'override' modifier because its containing class '{0}' does not extend another class."), + This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0: diag(4113, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113", "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'."), + This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0: diag(4114, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114", "This member must have an 'override' modifier because it overrides a member in the base class '{0}'."), + This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115", "This parameter property must have an 'override' modifier because it overrides a member in base class '{0}'."), + This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0: diag(4116, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116", "This member must have an 'override' modifier because it overrides an abstract method that is declared in the base class '{0}'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -8508,7 +8648,7 @@ var ts; Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), - Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option `--tsBuildInfoFile` is specified."), + Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option '--tsBuildInfoFile' is specified."), _0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2: diag(5075, ts.DiagnosticCategory.Error, "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075", "'{0}' is assignable to the constraint of type '{1}', but '{1}' could be instantiated with a different subtype of constraint '{2}'."), _0_and_1_operations_cannot_be_mixed_without_parentheses: diag(5076, ts.DiagnosticCategory.Error, "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076", "'{0}' and '{1}' operations cannot be mixed without parentheses."), Unknown_build_option_0_Did_you_mean_1: diag(5077, ts.DiagnosticCategory.Error, "Unknown_build_option_0_Did_you_mean_1_5077", "Unknown build option '{0}'. Did you mean '{1}'?"), @@ -8521,10 +8661,14 @@ var ts; Tuple_members_must_all_have_names_or_all_not_have_names: diag(5084, ts.DiagnosticCategory.Error, "Tuple_members_must_all_have_names_or_all_not_have_names_5084", "Tuple members must all have names or all not have names."), A_tuple_member_cannot_be_both_optional_and_rest: diag(5085, ts.DiagnosticCategory.Error, "A_tuple_member_cannot_be_both_optional_and_rest_5085", "A tuple member cannot be both optional and rest."), A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type: diag(5086, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086", "A labeled tuple element is declared as optional with a question mark after the name and before the colon, rather than after the type."), - A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a `...` before the name, rather than before the type."), + A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a '...' before the name, rather than before the type."), The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), + Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."), + The_root_value_of_a_0_file_must_be_an_object: diag(5092, ts.DiagnosticCategory.Error, "The_root_value_of_a_0_file_must_be_an_object_5092", "The root value of a '{0}' file must be an object."), + Compiler_option_0_may_only_be_used_with_build: diag(5093, ts.DiagnosticCategory.Error, "Compiler_option_0_may_only_be_used_with_build_5093", "Compiler option '--{0}' may only be used with '--build'."), + Compiler_option_0_may_not_be_used_with_build: diag(5094, ts.DiagnosticCategory.Error, "Compiler_option_0_may_not_be_used_with_build_5094", "Compiler option '--{0}' may not be used with '--build'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -8540,7 +8684,7 @@ var ts; Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), @@ -8735,9 +8879,9 @@ var ts; Emit_class_fields_with_Define_instead_of_Set: diag(6222, ts.DiagnosticCategory.Message, "Emit_class_fields_with_Define_instead_of_Set_6222", "Emit class fields with Define instead of Set."), Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."), Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."), - Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."), - Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling'."), - Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority'."), + Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."), + Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling'."), + Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority_FixedChunkSize: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority', 'FixedChunkSize'."), Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively: diag(6228, ts.DiagnosticCategory.Message, "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6228", "Synchronously call callbacks and update the state of directory watchers on platforms that don't support recursive watching natively."), Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3: diag(6229, ts.DiagnosticCategory.Error, "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229", "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'."), Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."), @@ -8748,7 +8892,11 @@ var ts; Disable_loading_referenced_projects: diag(6235, ts.DiagnosticCategory.Message, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."), Arguments_for_the_rest_parameter_0_were_not_provided: diag(6236, ts.DiagnosticCategory.Error, "Arguments_for_the_rest_parameter_0_were_not_provided_6236", "Arguments for the rest parameter '{0}' were not provided."), Generates_an_event_trace_and_a_list_of_types: diag(6237, ts.DiagnosticCategory.Message, "Generates_an_event_trace_and_a_list_of_types_6237", "Generates an event trace and a list of types."), - Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the `jsx` and `jsxs` factory functions from. eg, react"), + Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the 'jsx' and 'jsxs' factory functions from. eg, react"), + File_0_exists_according_to_earlier_cached_lookups: diag(6239, ts.DiagnosticCategory.Message, "File_0_exists_according_to_earlier_cached_lookups_6239", "File '{0}' exists according to earlier cached lookups."), + File_0_does_not_exist_according_to_earlier_cached_lookups: diag(6240, ts.DiagnosticCategory.Message, "File_0_does_not_exist_according_to_earlier_cached_lookups_6240", "File '{0}' does not exist according to earlier cached lookups."), + Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1: diag(6241, ts.DiagnosticCategory.Message, "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241", "Resolution for type reference directive '{0}' was found in cache from location '{1}'."), + Resolving_type_reference_directive_0_containing_file_1: diag(6242, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_6242", "======== Resolving type reference directive '{0}', containing file '{1}'. ========"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -8793,16 +8941,19 @@ var ts; Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382", "Skipping build of project '{0}' because its dependency '{1}' was not built"), Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383", "Project '{0}' can't be built because its dependency '{1}' was not built"), Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, ts.DiagnosticCategory.Message, "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384", "Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it."), - _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), + The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + Project_0_is_being_forcibly_rebuilt: diag(6388, ts.DiagnosticCategory.Message, "Project_0_is_being_forcibly_rebuilt_6388", "Project '{0}' is being forcibly rebuilt"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option: diag(6504, ts.DiagnosticCategory.Error, "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504", "File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?"), Print_names_of_files_and_the_reason_they_are_part_of_the_compilation: diag(6505, ts.DiagnosticCategory.Message, "Print_names_of_files_and_the_reason_they_are_part_of_the_compilation_6505", "Print names of files and the reason they are part of the compilation."), - Require_undeclared_properties_from_index_signatures_to_use_element_accesses: diag(6803, ts.DiagnosticCategory.Error, "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803", "Require undeclared properties from index signatures to use element accesses."), Include_undefined_in_index_signature_results: diag(6800, ts.DiagnosticCategory.Message, "Include_undefined_in_index_signature_results_6800", "Include 'undefined' in index signature results"), + Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier: diag(6801, ts.DiagnosticCategory.Message, "Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier_6801", "Ensure overriding members in derived classes are marked with an 'override' modifier."), + Require_undeclared_properties_from_index_signatures_to_use_element_accesses: diag(6802, ts.DiagnosticCategory.Message, "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6802", "Require undeclared properties from index signatures to use element accesses."), 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."), @@ -8835,7 +8986,7 @@ var ts; Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), - If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'"), The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), @@ -8875,7 +9026,7 @@ var ts; JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), - Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one '@augments' or '@extends' tag."), Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), @@ -9120,6 +9271,10 @@ var ts; Add_all_missing_function_declarations: diag(95157, ts.DiagnosticCategory.Message, "Add_all_missing_function_declarations_95157", "Add all missing function declarations"), Method_not_implemented: diag(95158, ts.DiagnosticCategory.Message, "Method_not_implemented_95158", "Method not implemented."), Function_not_implemented: diag(95159, ts.DiagnosticCategory.Message, "Function_not_implemented_95159", "Function not implemented."), + Add_override_modifier: diag(95160, ts.DiagnosticCategory.Message, "Add_override_modifier_95160", "Add 'override' modifier"), + Remove_override_modifier: diag(95161, ts.DiagnosticCategory.Message, "Remove_override_modifier_95161", "Remove 'override' modifier"), + Add_all_missing_override_modifiers: diag(95162, ts.DiagnosticCategory.Message, "Add_all_missing_override_modifiers_95162", "Add all missing 'override' modifiers"), + Remove_all_unnecessary_override_modifiers: diag(95163, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_override_modifiers_95163", "Remove all unnecessary 'override' modifiers"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -9134,8 +9289,6 @@ var ts; The_shadowing_declaration_of_0_is_defined_here: diag(18017, ts.DiagnosticCategory.Error, "The_shadowing_declaration_of_0_is_defined_here_18017", "The shadowing declaration of '{0}' is defined here"), The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here: diag(18018, ts.DiagnosticCategory.Error, "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018", "The declaration of '{0}' that you probably intended to use is defined here"), _0_modifier_cannot_be_used_with_a_private_identifier: diag(18019, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_private_identifier_18019", "'{0}' modifier cannot be used with a private identifier."), - A_method_cannot_be_named_with_a_private_identifier: diag(18022, ts.DiagnosticCategory.Error, "A_method_cannot_be_named_with_a_private_identifier_18022", "A method cannot be named with a private identifier."), - An_accessor_cannot_be_named_with_a_private_identifier: diag(18023, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_named_with_a_private_identifier_18023", "An accessor cannot be named with a private identifier."), An_enum_member_cannot_be_named_with_a_private_identifier: diag(18024, ts.DiagnosticCategory.Error, "An_enum_member_cannot_be_named_with_a_private_identifier_18024", "An enum member cannot be named with a private identifier."), can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), Compiler_reserves_name_0_when_emitting_private_identifier_downlevel: diag(18027, ts.DiagnosticCategory.Error, "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027", "Compiler reserves name '{0}' when emitting private identifier downlevel."), @@ -9147,6 +9300,7 @@ var ts; Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead: diag(18033, ts.DiagnosticCategory.Error, "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033", "Only numeric enums can have computed members, but this expression has type '{0}'. If you do not need exhaustiveness checks, consider using an object literal instead."), Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compiler_option_is_specified_e_g_Fragment: diag(18034, ts.DiagnosticCategory.Message, "Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compi_18034", "Specify the JSX fragment factory function to use when targeting 'react' JSX emit with 'jsxFactory' compiler option is specified, e.g. 'Fragment'."), Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(18035, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name_18035", "Invalid value for 'jsxFragmentFactory'. '{0}' is not a valid identifier or qualified-name."), + Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator: diag(18036, ts.DiagnosticCategory.Error, "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036", "Class decorators can't be used with static private identifier. Consider removing the experimental decorator."), }; })(ts || (ts = {})); var ts; @@ -9214,6 +9368,7 @@ var ts; _a.private = 120 /* PrivateKeyword */, _a.protected = 121 /* ProtectedKeyword */, _a.public = 122 /* PublicKeyword */, + _a.override = 156 /* OverrideKeyword */, _a.readonly = 142 /* ReadonlyKeyword */, _a.require = 143 /* RequireKeyword */, _a.global = 154 /* GlobalKeyword */, @@ -9240,7 +9395,7 @@ var ts; _a.yield = 124 /* YieldKeyword */, _a.async = 129 /* AsyncKeyword */, _a.await = 130 /* AwaitKeyword */, - _a.of = 156 /* OfKeyword */, + _a.of = 157 /* OfKeyword */, _a); var textToKeyword = new ts.Map(ts.getEntries(textToKeywordObj)); var textToToken = new ts.Map(ts.getEntries(__assign(__assign({}, textToKeywordObj), { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 29 /* LessThanToken */, ">": 31 /* GreaterThanToken */, "<=": 32 /* LessThanEqualsToken */, ">=": 33 /* GreaterThanEqualsToken */, "==": 34 /* EqualsEqualsToken */, "!=": 35 /* ExclamationEqualsToken */, "===": 36 /* EqualsEqualsEqualsToken */, "!==": 37 /* ExclamationEqualsEqualsToken */, "=>": 38 /* EqualsGreaterThanToken */, "+": 39 /* PlusToken */, "-": 40 /* MinusToken */, "**": 42 /* AsteriskAsteriskToken */, "*": 41 /* AsteriskToken */, "/": 43 /* SlashToken */, "%": 44 /* PercentToken */, "++": 45 /* PlusPlusToken */, "--": 46 /* MinusMinusToken */, "<<": 47 /* LessThanLessThanToken */, ">": 48 /* GreaterThanGreaterThanToken */, ">>>": 49 /* GreaterThanGreaterThanGreaterThanToken */, "&": 50 /* AmpersandToken */, "|": 51 /* BarToken */, "^": 52 /* CaretToken */, "!": 53 /* ExclamationToken */, "~": 54 /* TildeToken */, "&&": 55 /* AmpersandAmpersandToken */, "||": 56 /* BarBarToken */, "?": 57 /* QuestionToken */, "??": 60 /* QuestionQuestionToken */, "?.": 28 /* QuestionDotToken */, ":": 58 /* ColonToken */, "=": 62 /* EqualsToken */, "+=": 63 /* PlusEqualsToken */, "-=": 64 /* MinusEqualsToken */, "*=": 65 /* AsteriskEqualsToken */, "**=": 66 /* AsteriskAsteriskEqualsToken */, "/=": 67 /* SlashEqualsToken */, "%=": 68 /* PercentEqualsToken */, "<<=": 69 /* LessThanLessThanEqualsToken */, ">>=": 70 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 72 /* AmpersandEqualsToken */, "|=": 73 /* BarEqualsToken */, "^=": 77 /* CaretEqualsToken */, "||=": 74 /* BarBarEqualsToken */, "&&=": 75 /* AmpersandAmpersandEqualsToken */, "??=": 76 /* QuestionQuestionEqualsToken */, "@": 59 /* AtToken */, "`": 61 /* BacktickToken */ }))); @@ -9556,11 +9711,11 @@ var ts; } ts.couldStartTrivia = couldStartTrivia; /* @internal */ - function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { - if (stopAtComments === void 0) { stopAtComments = false; } + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments, inJSDoc) { if (ts.positionIsSynthesized(pos)) { return pos; } + var canConsumeStar = false; // Keep in sync with couldStartTrivia while (true) { var ch = text.charCodeAt(pos); @@ -9575,6 +9730,7 @@ var ts; if (stopAfterLineBreak) { return pos; } + canConsumeStar = !!inJSDoc; continue; case 9 /* tab */: case 11 /* verticalTab */: @@ -9594,6 +9750,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { @@ -9605,6 +9762,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } break; @@ -9614,12 +9772,21 @@ var ts; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos); + canConsumeStar = false; continue; } break; case 35 /* hash */: if (pos === 0 && isShebangTrivia(text, pos)) { pos = scanShebangTrivia(text, pos); + canConsumeStar = false; + continue; + } + break; + case 42 /* asterisk */: + if (canConsumeStar) { + pos++; + canConsumeStar = false; continue; } break; @@ -9924,6 +10091,7 @@ var ts; reScanJsxToken: reScanJsxToken, reScanLessThanToken: reScanLessThanToken, reScanQuestionToken: reScanQuestionToken, + reScanInvalidIdentifier: reScanInvalidIdentifier, scanJsxToken: scanJsxToken, scanJsDocToken: scanJsDocToken, scan: scan, @@ -10926,15 +11094,9 @@ var ts; } return token = 79 /* PrivateIdentifier */; default: - if (isIdentifierStart(ch, languageVersion)) { - pos += charSize(ch); - while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) - pos += charSize(ch); - tokenValue = text.substring(tokenPos, pos); - if (ch === 92 /* backslash */) { - tokenValue += scanIdentifierParts(); - } - return token = getIdentifierToken(); + var identifierKind = scanIdentifier(ch, languageVersion); + if (identifierKind) { + return token = identifierKind; } else if (isWhiteSpaceSingleLine(ch)) { pos += charSize(ch); @@ -10951,6 +11113,31 @@ var ts; } } } + function reScanInvalidIdentifier() { + ts.Debug.assert(token === 0 /* Unknown */, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'."); + pos = tokenPos = startPos; + tokenFlags = 0; + var ch = codePointAt(text, pos); + var identifierKind = scanIdentifier(ch, 99 /* ESNext */); + if (identifierKind) { + return token = identifierKind; + } + pos += charSize(ch); + return token; // Still `SyntaKind.Unknown` + } + function scanIdentifier(startCharacter, languageVersion) { + var ch = startCharacter; + if (isIdentifierStart(ch, languageVersion)) { + pos += charSize(ch); + while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) + pos += charSize(ch); + tokenValue = text.substring(tokenPos, pos); + if (ch === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return getIdentifierToken(); + } + } function reScanGreaterToken() { if (token === 31 /* GreaterThanToken */) { if (text.charCodeAt(pos) === 62 /* greaterThan */) { @@ -11063,9 +11250,10 @@ var ts; pos = tokenPos; return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true); } - function reScanJsxToken() { + function reScanJsxToken(allowMultilineJsxText) { + if (allowMultilineJsxText === void 0) { allowMultilineJsxText = true; } pos = tokenPos = startPos; - return token = scanJsxToken(); + return token = scanJsxToken(allowMultilineJsxText); } function reScanLessThanToken() { if (token === 47 /* LessThanLessThanToken */) { @@ -11079,7 +11267,8 @@ var ts; pos = tokenPos + 1; return token = 57 /* QuestionToken */; } - function scanJsxToken() { + function scanJsxToken(allowMultilineJsxText) { + if (allowMultilineJsxText === void 0) { allowMultilineJsxText = true; } startPos = tokenPos = pos; if (pos >= end) { return token = 1 /* EndOfFileToken */; @@ -11099,15 +11288,9 @@ var ts; } // First non-whitespace character on this line. var firstNonWhitespace = 0; - var lastNonWhitespace = -1; // These initial values are special because the first line is: // firstNonWhitespace = 0 to indicate that we want leading whitespace, while (pos < end) { - // We want to keep track of the last non-whitespace (but including - // newlines character for hitting the end of the JSX Text region) - if (!isWhiteSpaceSingleLine(char)) { - lastNonWhitespace = pos; - } char = text.charCodeAt(pos); if (char === 123 /* openBrace */) { break; @@ -11125,8 +11308,6 @@ var ts; if (char === 125 /* closeBrace */) { error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1); } - if (lastNonWhitespace > 0) - lastNonWhitespace++; // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces. // i.e (- : whitespace) //
---- @@ -11136,13 +11317,17 @@ var ts; if (isLineBreak(char) && firstNonWhitespace === 0) { firstNonWhitespace = -1; } + else if (!allowMultilineJsxText && isLineBreak(char) && firstNonWhitespace > 0) { + // Stop JsxText on each line during formatting. This allows the formatter to + // indent each line correctly. + break; + } else if (!isWhiteSpaceLike(char)) { firstNonWhitespace = pos; } pos++; } - var endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace; - tokenValue = text.substring(startPos, endPosition); + tokenValue = text.substring(startPos, pos); return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */; } // Scans a JSX identifier; these differ from normal identifiers in that @@ -11165,6 +11350,7 @@ var ts; tokenValue += ":"; pos++; namespaceSeparator = true; + token = 78 /* Identifier */; // swap from keyword kind to identifier kind continue; } var oldPos = pos; @@ -11421,6 +11607,8 @@ var ts; switch (options.target) { case 99 /* ESNext */: return "lib.esnext.full.d.ts"; + case 8 /* ES2021 */: + return "lib.es2021.full.d.ts"; case 7 /* ES2020 */: return "lib.es2020.full.d.ts"; case 6 /* ES2019 */: @@ -11639,9 +11827,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 159 /* TypeParameter */) { + if (d && d.kind === 160 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (isFunctionLike(current) || isClassLike(current) || current.kind === 253 /* InterfaceDeclaration */) { + if (isFunctionLike(current) || isClassLike(current) || current.kind === 254 /* InterfaceDeclaration */) { return current; } } @@ -11649,7 +11837,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node, parent) { - return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 166 /* Constructor */; + return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) && parent.kind === 167 /* Constructor */; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -11679,14 +11867,14 @@ var ts; node = walkUpBindingElementsAndPatterns(node); } var flags = getFlags(node); - if (node.kind === 249 /* VariableDeclaration */) { + if (node.kind === 250 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 250 /* VariableDeclarationList */) { + if (node && node.kind === 251 /* VariableDeclarationList */) { flags |= getFlags(node); node = node.parent; } - if (node && node.kind === 232 /* VariableStatement */) { + if (node && node.kind === 233 /* VariableStatement */) { flags |= getFlags(node); } return flags; @@ -11704,19 +11892,22 @@ var ts; // nodes like variable declarations and binding elements can returned a view of their flags // that includes the modifiers from their container. i.e. flags like export/declare aren't // stored on the variable declaration directly, but on the containing variable statement - // (if it has one). Similarly, flags for let/const are store on the variable declaration + // (if it has one). Similarly, flags for let/const are stored on the variable declaration // list. By calling this function, all those flags are combined so that the client can treat // the node as if it actually had those flags. function getCombinedNodeFlags(node) { return getCombinedFlags(node, function (n) { return n.flags; }); } ts.getCombinedNodeFlags = getCombinedNodeFlags; + /* @internal */ + ts.supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; /** * Checks to see if the locale is in the appropriate format, * and if it is, attempts to set the appropriate language. */ function validateLocaleAndSetLanguage(locale, sys, errors) { - var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + var lowerCaseLocale = locale.toLowerCase(); + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale); if (!matchResult) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); @@ -11727,7 +11918,7 @@ var ts; var territory = matchResult[3]; // First try the entire locale, then fall back to just language if that's all we have. // Either ways do not fail, and fallback to the English diagnostic strings. - if (!trySetLanguageAndTerritory(language, territory, errors)) { + if (ts.contains(ts.supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) { trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); } // Set the UI locale for string collation @@ -11834,7 +12025,7 @@ var ts; } ts.idText = idText; function symbolName(symbol) { - if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) { + if (symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) { return idText(symbol.valueDeclaration.name); } return unescapeLeadingUnderscores(symbol.escapedName); @@ -11856,30 +12047,30 @@ var ts; } // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } break; - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: var expr = hostNode.expression; - if (expr.kind === 216 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) { + if (expr.kind === 217 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) { expr = expr.left; } switch (expr.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return expr.name; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; } } break; - case 207 /* ParenthesizedExpression */: { + case 208 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } - case 245 /* LabeledStatement */: { + case 246 /* LabeledStatement */: { if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } @@ -11916,16 +12107,16 @@ var ts; switch (declaration.kind) { case 78 /* Identifier */: return declaration; - case 333 /* JSDocPropertyTag */: - case 326 /* JSDocParameterTag */: { + case 337 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: { var name = declaration.name; - if (name.kind === 157 /* QualifiedName */) { + if (name.kind === 158 /* QualifiedName */) { return name.right; } break; } - case 203 /* CallExpression */: - case 216 /* BinaryExpression */: { + case 204 /* CallExpression */: + case 217 /* BinaryExpression */: { var expr_1 = declaration; switch (ts.getAssignmentDeclarationKind(expr_1)) { case 1 /* ExportsProperty */: @@ -11941,15 +12132,15 @@ var ts; return undefined; } } - case 331 /* JSDocTypedefTag */: + case 335 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); - case 325 /* JSDocEnumTag */: + case 329 /* JSDocEnumTag */: return nameForNamelessJSDocTypedef(declaration); - case 266 /* ExportAssignment */: { + case 267 /* ExportAssignment */: { var expression = declaration.expression; return ts.isIdentifier(expression) ? expression : undefined; } - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: var expr = declaration; if (ts.isBindableStaticElementAccessExpression(expr)) { return expr.argumentExpression; @@ -11962,7 +12153,7 @@ var ts; if (declaration === undefined) return undefined; return getNonAssignedNameOfDeclaration(declaration) || - (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + (ts.isFunctionExpression(declaration) || ts.isArrowFunction(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); } ts.getNameOfDeclaration = getNameOfDeclaration; /*@internal*/ @@ -12115,6 +12306,10 @@ var ts; return getFirstJSDocTag(node, ts.isJSDocReadonlyTag, /*noCache*/ true); } ts.getJSDocReadonlyTagNoCache = getJSDocReadonlyTagNoCache; + function getJSDocOverrideTagNoCache(node) { + return getFirstJSDocTag(node, ts.isJSDocOverrideTag, /*noCache*/ true); + } + ts.getJSDocOverrideTagNoCache = getJSDocOverrideTagNoCache; /** Gets the JSDoc deprecated tag for the node if present */ function getJSDocDeprecatedTag(node) { return getFirstJSDocTag(node, ts.isJSDocDeprecatedTag); @@ -12235,6 +12430,14 @@ var ts; return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + /** Gets the text of a jsdoc comment, flattening links to their text. */ + function getTextOfJSDocComment(comment) { + return typeof comment === "string" ? comment + : comment === null || comment === void 0 ? void 0 : comment.map(function (c) { + return c.kind === 313 /* JSDocText */ ? c.text : "{@link " + (c.name ? ts.entityNameToString(c.name) + " " : "") + c.text + "}"; + }).join(""); + } + ts.getTextOfJSDocComment = getTextOfJSDocComment; /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. @@ -12244,7 +12447,7 @@ var ts; return ts.emptyArray; } if (ts.isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 311 /* JSDocComment */); + ts.Debug.assert(node.parent.kind === 312 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } if (node.typeParameters) { @@ -12270,13 +12473,13 @@ var ts; } ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter; // #region - function isIdentifierOrPrivateIdentifier(node) { + function isMemberName(node) { return node.kind === 78 /* Identifier */ || node.kind === 79 /* PrivateIdentifier */; } - ts.isIdentifierOrPrivateIdentifier = isIdentifierOrPrivateIdentifier; + ts.isMemberName = isMemberName; /* @internal */ function isGetOrSetAccessorDeclaration(node) { - return node.kind === 168 /* SetAccessor */ || node.kind === 167 /* GetAccessor */; + return node.kind === 169 /* SetAccessor */ || node.kind === 168 /* GetAccessor */; } ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; function isPropertyAccessChain(node) { @@ -12294,10 +12497,10 @@ var ts; function isOptionalChain(node) { var kind = node.kind; return !!(node.flags & 32 /* OptionalChain */) && - (kind === 201 /* PropertyAccessExpression */ - || kind === 202 /* ElementAccessExpression */ - || kind === 203 /* CallExpression */ - || kind === 225 /* NonNullExpression */); + (kind === 202 /* PropertyAccessExpression */ + || kind === 203 /* ElementAccessExpression */ + || kind === 204 /* CallExpression */ + || kind === 226 /* NonNullExpression */); } ts.isOptionalChain = isOptionalChain; /* @internal */ @@ -12332,7 +12535,7 @@ var ts; } ts.isOutermostOptionalChain = isOutermostOptionalChain; function isNullishCoalesce(node) { - return node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */; + return node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */; } ts.isNullishCoalesce = isNullishCoalesce; function isConstTypeReference(node) { @@ -12349,17 +12552,17 @@ var ts; } ts.isNonNullChain = isNonNullChain; function isBreakOrContinueStatement(node) { - return node.kind === 241 /* BreakStatement */ || node.kind === 240 /* ContinueStatement */; + return node.kind === 242 /* BreakStatement */ || node.kind === 241 /* ContinueStatement */; } ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isNamedExportBindings(node) { - return node.kind === 269 /* NamespaceExport */ || node.kind === 268 /* NamedExports */; + return node.kind === 270 /* NamespaceExport */ || node.kind === 269 /* NamedExports */; } ts.isNamedExportBindings = isNamedExportBindings; function isUnparsedTextLike(node) { switch (node.kind) { - case 294 /* UnparsedText */: - case 295 /* UnparsedInternalText */: + case 295 /* UnparsedText */: + case 296 /* UnparsedInternalText */: return true; default: return false; @@ -12368,12 +12571,12 @@ var ts; ts.isUnparsedTextLike = isUnparsedTextLike; function isUnparsedNode(node) { return isUnparsedTextLike(node) || - node.kind === 292 /* UnparsedPrologue */ || - node.kind === 296 /* UnparsedSyntheticReference */; + node.kind === 293 /* UnparsedPrologue */ || + node.kind === 297 /* UnparsedSyntheticReference */; } ts.isUnparsedNode = isUnparsedNode; function isJSDocPropertyLikeTag(node) { - return node.kind === 333 /* JSDocPropertyTag */ || node.kind === 326 /* JSDocParameterTag */; + return node.kind === 337 /* JSDocPropertyTag */ || node.kind === 330 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; // #endregion @@ -12389,16 +12592,25 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 157 /* FirstNode */; + return kind >= 158 /* FirstNode */; } ts.isNodeKind = isNodeKind; + /** + * True if kind is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + function isTokenKind(kind) { + return kind >= 0 /* FirstToken */ && kind <= 157 /* LastToken */; + } + ts.isTokenKind = isTokenKind; /** * True if node is of some token syntax kind. * For example, this is true for an IfKeyword but not for an IfStatement. * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. */ function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 156 /* LastToken */; + return isTokenKind(n.kind); } ts.isToken = isToken; // Node Arrays @@ -12439,13 +12651,13 @@ var ts; ts.isImportOrExportSpecifier = isImportOrExportSpecifier; function isTypeOnlyImportOrExportDeclaration(node) { switch (node.kind) { - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return node.parent.parent.isTypeOnly; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return node.parent.isTypeOnly; - case 262 /* ImportClause */: - case 260 /* ImportEqualsDeclaration */: + case 263 /* ImportClause */: + case 261 /* ImportEqualsDeclaration */: return node.isTypeOnly; default: return false; @@ -12464,10 +12676,10 @@ var ts; ts.isGeneratedIdentifier = isGeneratedIdentifier; // Private Identifiers /*@internal*/ - function isPrivateIdentifierPropertyDeclaration(node) { - return ts.isPropertyDeclaration(node) && ts.isPrivateIdentifier(node.name); + function isPrivateIdentifierClassElementDeclaration(node) { + return (ts.isPropertyDeclaration(node) || isMethodOrAccessor(node)) && ts.isPrivateIdentifier(node.name); } - ts.isPrivateIdentifierPropertyDeclaration = isPrivateIdentifierPropertyDeclaration; + ts.isPrivateIdentifierClassElementDeclaration = isPrivateIdentifierClassElementDeclaration; /*@internal*/ function isPrivateIdentifierPropertyAccessExpression(node) { return ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name); @@ -12488,6 +12700,7 @@ var ts; case 121 /* ProtectedKeyword */: case 142 /* ReadonlyKeyword */: case 123 /* StaticKeyword */: + case 156 /* OverrideKeyword */: return true; } return false; @@ -12495,12 +12708,12 @@ var ts; ts.isModifierKind = isModifierKind; /* @internal */ function isParameterPropertyModifier(kind) { - return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + return !!(ts.modifierToFlag(kind) & 16476 /* ParameterPropertyModifier */); } ts.isParameterPropertyModifier = isParameterPropertyModifier; /* @internal */ function isClassMemberModifier(idToken) { - return isParameterPropertyModifier(idToken) || idToken === 123 /* StaticKeyword */; + return isParameterPropertyModifier(idToken) || idToken === 123 /* StaticKeyword */ || idToken === 156 /* OverrideKeyword */; } ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { @@ -12509,7 +12722,7 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 157 /* QualifiedName */ + return kind === 158 /* QualifiedName */ || kind === 78 /* Identifier */; } ts.isEntityName = isEntityName; @@ -12519,19 +12732,19 @@ var ts; || kind === 79 /* PrivateIdentifier */ || kind === 10 /* StringLiteral */ || kind === 8 /* NumericLiteral */ - || kind === 158 /* ComputedPropertyName */; + || kind === 159 /* ComputedPropertyName */; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; return kind === 78 /* Identifier */ - || kind === 196 /* ObjectBindingPattern */ - || kind === 197 /* ArrayBindingPattern */; + || kind === 197 /* ObjectBindingPattern */ + || kind === 198 /* ArrayBindingPattern */; } ts.isBindingName = isBindingName; // Functions function isFunctionLike(node) { - return node && isFunctionLikeKind(node.kind); + return !!node && isFunctionLikeKind(node.kind); } ts.isFunctionLike = isFunctionLike; /* @internal */ @@ -12541,13 +12754,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; default: return false; @@ -12556,14 +12769,14 @@ var ts; /* @internal */ function isFunctionLikeKind(kind) { switch (kind) { - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 313 /* JSDocSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 174 /* FunctionType */: - case 308 /* JSDocFunctionType */: - case 175 /* ConstructorType */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 315 /* JSDocSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 175 /* FunctionType */: + case 309 /* JSDocFunctionType */: + case 176 /* ConstructorType */: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -12578,29 +12791,29 @@ var ts; // Classes function isClassElement(node) { var kind = node.kind; - return kind === 166 /* Constructor */ - || kind === 163 /* PropertyDeclaration */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 171 /* IndexSignature */ - || kind === 229 /* SemicolonClassElement */; + return kind === 167 /* Constructor */ + || kind === 164 /* PropertyDeclaration */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 172 /* IndexSignature */ + || kind === 230 /* SemicolonClassElement */; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */); + return node && (node.kind === 253 /* ClassDeclaration */ || node.kind === 222 /* ClassExpression */); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 167 /* GetAccessor */ || node.kind === 168 /* SetAccessor */); + return node && (node.kind === 168 /* GetAccessor */ || node.kind === 169 /* SetAccessor */); } ts.isAccessor = isAccessor; /* @internal */ function isMethodOrAccessor(node) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return true; default: return false; @@ -12610,11 +12823,11 @@ var ts; // Type members function isTypeElement(node) { var kind = node.kind; - return kind === 170 /* ConstructSignature */ - || kind === 169 /* CallSignature */ - || kind === 162 /* PropertySignature */ - || kind === 164 /* MethodSignature */ - || kind === 171 /* IndexSignature */; + return kind === 171 /* ConstructSignature */ + || kind === 170 /* CallSignature */ + || kind === 163 /* PropertySignature */ + || kind === 165 /* MethodSignature */ + || kind === 172 /* IndexSignature */; } ts.isTypeElement = isTypeElement; function isClassOrTypeElement(node) { @@ -12623,12 +12836,12 @@ var ts; ts.isClassOrTypeElement = isClassOrTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 288 /* PropertyAssignment */ - || kind === 289 /* ShorthandPropertyAssignment */ - || kind === 290 /* SpreadAssignment */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 289 /* PropertyAssignment */ + || kind === 290 /* ShorthandPropertyAssignment */ + || kind === 291 /* SpreadAssignment */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; // Type @@ -12643,8 +12856,8 @@ var ts; ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return true; } return false; @@ -12655,8 +12868,8 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 197 /* ArrayBindingPattern */ - || kind === 196 /* ObjectBindingPattern */; + return kind === 198 /* ArrayBindingPattern */ + || kind === 197 /* ObjectBindingPattern */; } return false; } @@ -12664,15 +12877,15 @@ var ts; /* @internal */ function isAssignmentPattern(node) { var kind = node.kind; - return kind === 199 /* ArrayLiteralExpression */ - || kind === 200 /* ObjectLiteralExpression */; + return kind === 200 /* ArrayLiteralExpression */ + || kind === 201 /* ObjectLiteralExpression */; } ts.isAssignmentPattern = isAssignmentPattern; /* @internal */ function isArrayBindingElement(node) { var kind = node.kind; - return kind === 198 /* BindingElement */ - || kind === 222 /* OmittedExpression */; + return kind === 199 /* BindingElement */ + || kind === 223 /* OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; /** @@ -12681,9 +12894,9 @@ var ts; /* @internal */ function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: return true; } return false; @@ -12704,8 +12917,8 @@ var ts; /* @internal */ function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 196 /* ObjectBindingPattern */: - case 200 /* ObjectLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 201 /* ObjectLiteralExpression */: return true; } return false; @@ -12717,8 +12930,8 @@ var ts; /* @internal */ function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 197 /* ArrayBindingPattern */: - case 199 /* ArrayLiteralExpression */: + case 198 /* ArrayBindingPattern */: + case 200 /* ArrayLiteralExpression */: return true; } return false; @@ -12727,26 +12940,26 @@ var ts; /* @internal */ function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { var kind = node.kind; - return kind === 201 /* PropertyAccessExpression */ - || kind === 157 /* QualifiedName */ - || kind === 195 /* ImportType */; + return kind === 202 /* PropertyAccessExpression */ + || kind === 158 /* QualifiedName */ + || kind === 196 /* ImportType */; } ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; // Expression function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 201 /* PropertyAccessExpression */ - || kind === 157 /* QualifiedName */; + return kind === 202 /* PropertyAccessExpression */ + || kind === 158 /* QualifiedName */; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 205 /* TaggedTemplateExpression */: - case 161 /* Decorator */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 206 /* TaggedTemplateExpression */: + case 162 /* Decorator */: return true; default: return false; @@ -12754,12 +12967,12 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 203 /* CallExpression */ || node.kind === 204 /* NewExpression */; + return node.kind === 204 /* CallExpression */ || node.kind === 205 /* NewExpression */; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 218 /* TemplateExpression */ + return kind === 219 /* TemplateExpression */ || kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; @@ -12770,33 +12983,33 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: - case 204 /* NewExpression */: - case 203 /* CallExpression */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: - case 205 /* TaggedTemplateExpression */: - case 199 /* ArrayLiteralExpression */: - case 207 /* ParenthesizedExpression */: - case 200 /* ObjectLiteralExpression */: - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 205 /* NewExpression */: + case 204 /* CallExpression */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: + case 206 /* TaggedTemplateExpression */: + case 200 /* ArrayLiteralExpression */: + case 208 /* ParenthesizedExpression */: + case 201 /* ObjectLiteralExpression */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: case 78 /* Identifier */: case 13 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: case 9 /* BigIntLiteral */: case 10 /* StringLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: case 94 /* FalseKeyword */: case 103 /* NullKeyword */: case 107 /* ThisKeyword */: case 109 /* TrueKeyword */: case 105 /* SuperKeyword */: - case 225 /* NonNullExpression */: - case 226 /* MetaProperty */: + case 226 /* NonNullExpression */: + case 227 /* MetaProperty */: case 99 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression return true; default: @@ -12810,13 +13023,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: - case 210 /* DeleteExpression */: - case 211 /* TypeOfExpression */: - case 212 /* VoidExpression */: - case 213 /* AwaitExpression */: - case 206 /* TypeAssertionExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 211 /* DeleteExpression */: + case 212 /* TypeOfExpression */: + case 213 /* VoidExpression */: + case 214 /* AwaitExpression */: + case 207 /* TypeAssertionExpression */: return true; default: return isLeftHandSideExpressionKind(kind); @@ -12825,9 +13038,9 @@ var ts; /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return true; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */; default: @@ -12846,15 +13059,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 217 /* ConditionalExpression */: - case 219 /* YieldExpression */: - case 209 /* ArrowFunction */: - case 216 /* BinaryExpression */: - case 220 /* SpreadElement */: - case 224 /* AsExpression */: - case 222 /* OmittedExpression */: - case 337 /* CommaListExpression */: - case 336 /* PartiallyEmittedExpression */: + case 218 /* ConditionalExpression */: + case 220 /* YieldExpression */: + case 210 /* ArrowFunction */: + case 217 /* BinaryExpression */: + case 221 /* SpreadElement */: + case 225 /* AsExpression */: + case 223 /* OmittedExpression */: + case 341 /* CommaListExpression */: + case 340 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -12862,8 +13075,8 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 206 /* TypeAssertionExpression */ - || kind === 224 /* AsExpression */; + return kind === 207 /* TypeAssertionExpression */ + || kind === 225 /* AsExpression */; } ts.isAssertionExpression = isAssertionExpression; /* @internal */ @@ -12874,13 +13087,13 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return true; - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -12909,7 +13122,7 @@ var ts; ts.isExternalModuleIndicator = isExternalModuleIndicator; /* @internal */ function isForInOrOfStatement(node) { - return node.kind === 238 /* ForInStatement */ || node.kind === 239 /* ForOfStatement */; + return node.kind === 239 /* ForInStatement */ || node.kind === 240 /* ForOfStatement */; } ts.isForInOrOfStatement = isForInOrOfStatement; // Element @@ -12933,114 +13146,114 @@ var ts; /* @internal */ function isModuleBody(node) { var kind = node.kind; - return kind === 257 /* ModuleBlock */ - || kind === 256 /* ModuleDeclaration */ + return kind === 258 /* ModuleBlock */ + || kind === 257 /* ModuleDeclaration */ || kind === 78 /* Identifier */; } ts.isModuleBody = isModuleBody; /* @internal */ function isNamespaceBody(node) { var kind = node.kind; - return kind === 257 /* ModuleBlock */ - || kind === 256 /* ModuleDeclaration */; + return kind === 258 /* ModuleBlock */ + || kind === 257 /* ModuleDeclaration */; } ts.isNamespaceBody = isNamespaceBody; /* @internal */ function isJSDocNamespaceBody(node) { var kind = node.kind; return kind === 78 /* Identifier */ - || kind === 256 /* ModuleDeclaration */; + || kind === 257 /* ModuleDeclaration */; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; /* @internal */ function isNamedImportBindings(node) { var kind = node.kind; - return kind === 264 /* NamedImports */ - || kind === 263 /* NamespaceImport */; + return kind === 265 /* NamedImports */ + || kind === 264 /* NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; /* @internal */ function isModuleOrEnumDeclaration(node) { - return node.kind === 256 /* ModuleDeclaration */ || node.kind === 255 /* EnumDeclaration */; + return node.kind === 257 /* ModuleDeclaration */ || node.kind === 256 /* EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 209 /* ArrowFunction */ - || kind === 198 /* BindingElement */ - || kind === 252 /* ClassDeclaration */ - || kind === 221 /* ClassExpression */ - || kind === 166 /* Constructor */ - || kind === 255 /* EnumDeclaration */ - || kind === 291 /* EnumMember */ - || kind === 270 /* ExportSpecifier */ - || kind === 251 /* FunctionDeclaration */ - || kind === 208 /* FunctionExpression */ - || kind === 167 /* GetAccessor */ - || kind === 262 /* ImportClause */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 265 /* ImportSpecifier */ - || kind === 253 /* InterfaceDeclaration */ - || kind === 280 /* JsxAttribute */ - || kind === 165 /* MethodDeclaration */ - || kind === 164 /* MethodSignature */ - || kind === 256 /* ModuleDeclaration */ - || kind === 259 /* NamespaceExportDeclaration */ - || kind === 263 /* NamespaceImport */ - || kind === 269 /* NamespaceExport */ - || kind === 160 /* Parameter */ - || kind === 288 /* PropertyAssignment */ - || kind === 163 /* PropertyDeclaration */ - || kind === 162 /* PropertySignature */ - || kind === 168 /* SetAccessor */ - || kind === 289 /* ShorthandPropertyAssignment */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 159 /* TypeParameter */ - || kind === 249 /* VariableDeclaration */ - || kind === 331 /* JSDocTypedefTag */ - || kind === 324 /* JSDocCallbackTag */ - || kind === 333 /* JSDocPropertyTag */; + return kind === 210 /* ArrowFunction */ + || kind === 199 /* BindingElement */ + || kind === 253 /* ClassDeclaration */ + || kind === 222 /* ClassExpression */ + || kind === 167 /* Constructor */ + || kind === 256 /* EnumDeclaration */ + || kind === 292 /* EnumMember */ + || kind === 271 /* ExportSpecifier */ + || kind === 252 /* FunctionDeclaration */ + || kind === 209 /* FunctionExpression */ + || kind === 168 /* GetAccessor */ + || kind === 263 /* ImportClause */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 266 /* ImportSpecifier */ + || kind === 254 /* InterfaceDeclaration */ + || kind === 281 /* JsxAttribute */ + || kind === 166 /* MethodDeclaration */ + || kind === 165 /* MethodSignature */ + || kind === 257 /* ModuleDeclaration */ + || kind === 260 /* NamespaceExportDeclaration */ + || kind === 264 /* NamespaceImport */ + || kind === 270 /* NamespaceExport */ + || kind === 161 /* Parameter */ + || kind === 289 /* PropertyAssignment */ + || kind === 164 /* PropertyDeclaration */ + || kind === 163 /* PropertySignature */ + || kind === 169 /* SetAccessor */ + || kind === 290 /* ShorthandPropertyAssignment */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 160 /* TypeParameter */ + || kind === 250 /* VariableDeclaration */ + || kind === 335 /* JSDocTypedefTag */ + || kind === 328 /* JSDocCallbackTag */ + || kind === 337 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { - return kind === 251 /* FunctionDeclaration */ - || kind === 271 /* MissingDeclaration */ - || kind === 252 /* ClassDeclaration */ - || kind === 253 /* InterfaceDeclaration */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 255 /* EnumDeclaration */ - || kind === 256 /* ModuleDeclaration */ - || kind === 261 /* ImportDeclaration */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 267 /* ExportDeclaration */ - || kind === 266 /* ExportAssignment */ - || kind === 259 /* NamespaceExportDeclaration */; + return kind === 252 /* FunctionDeclaration */ + || kind === 272 /* MissingDeclaration */ + || kind === 253 /* ClassDeclaration */ + || kind === 254 /* InterfaceDeclaration */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 256 /* EnumDeclaration */ + || kind === 257 /* ModuleDeclaration */ + || kind === 262 /* ImportDeclaration */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 268 /* ExportDeclaration */ + || kind === 267 /* ExportAssignment */ + || kind === 260 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 241 /* BreakStatement */ - || kind === 240 /* ContinueStatement */ - || kind === 248 /* DebuggerStatement */ - || kind === 235 /* DoStatement */ - || kind === 233 /* ExpressionStatement */ - || kind === 231 /* EmptyStatement */ - || kind === 238 /* ForInStatement */ - || kind === 239 /* ForOfStatement */ - || kind === 237 /* ForStatement */ - || kind === 234 /* IfStatement */ - || kind === 245 /* LabeledStatement */ - || kind === 242 /* ReturnStatement */ - || kind === 244 /* SwitchStatement */ - || kind === 246 /* ThrowStatement */ - || kind === 247 /* TryStatement */ - || kind === 232 /* VariableStatement */ - || kind === 236 /* WhileStatement */ - || kind === 243 /* WithStatement */ - || kind === 335 /* NotEmittedStatement */ - || kind === 339 /* EndOfDeclarationMarker */ - || kind === 338 /* MergeDeclarationMarker */; + return kind === 242 /* BreakStatement */ + || kind === 241 /* ContinueStatement */ + || kind === 249 /* DebuggerStatement */ + || kind === 236 /* DoStatement */ + || kind === 234 /* ExpressionStatement */ + || kind === 232 /* EmptyStatement */ + || kind === 239 /* ForInStatement */ + || kind === 240 /* ForOfStatement */ + || kind === 238 /* ForStatement */ + || kind === 235 /* IfStatement */ + || kind === 246 /* LabeledStatement */ + || kind === 243 /* ReturnStatement */ + || kind === 245 /* SwitchStatement */ + || kind === 247 /* ThrowStatement */ + || kind === 248 /* TryStatement */ + || kind === 233 /* VariableStatement */ + || kind === 237 /* WhileStatement */ + || kind === 244 /* WithStatement */ + || kind === 339 /* NotEmittedStatement */ + || kind === 343 /* EndOfDeclarationMarker */ + || kind === 342 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { - if (node.kind === 159 /* TypeParameter */) { - return (node.parent && node.parent.kind !== 330 /* JSDocTemplateTag */) || ts.isInJSFile(node); + if (node.kind === 160 /* TypeParameter */) { + return (node.parent && node.parent.kind !== 334 /* JSDocTemplateTag */) || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -13067,10 +13280,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 230 /* Block */) + if (node.kind !== 231 /* Block */) return false; if (node.parent !== undefined) { - if (node.parent.kind === 247 /* TryStatement */ || node.parent.kind === 287 /* CatchClause */) { + if (node.parent.kind === 248 /* TryStatement */ || node.parent.kind === 288 /* CatchClause */) { return false; } } @@ -13084,15 +13297,15 @@ var ts; var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) - || kind === 230 /* Block */; + || kind === 231 /* Block */; } ts.isStatementOrBlock = isStatementOrBlock; // Module references /* @internal */ function isModuleReference(node) { var kind = node.kind; - return kind === 272 /* ExternalModuleReference */ - || kind === 157 /* QualifiedName */ + return kind === 273 /* ExternalModuleReference */ + || kind === 158 /* QualifiedName */ || kind === 78 /* Identifier */; } ts.isModuleReference = isModuleReference; @@ -13102,70 +13315,76 @@ var ts; var kind = node.kind; return kind === 107 /* ThisKeyword */ || kind === 78 /* Identifier */ - || kind === 201 /* PropertyAccessExpression */; + || kind === 202 /* PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; /* @internal */ function isJsxChild(node) { var kind = node.kind; - return kind === 273 /* JsxElement */ - || kind === 283 /* JsxExpression */ - || kind === 274 /* JsxSelfClosingElement */ + return kind === 274 /* JsxElement */ + || kind === 284 /* JsxExpression */ + || kind === 275 /* JsxSelfClosingElement */ || kind === 11 /* JsxText */ - || kind === 277 /* JsxFragment */; + || kind === 278 /* JsxFragment */; } ts.isJsxChild = isJsxChild; /* @internal */ function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 280 /* JsxAttribute */ - || kind === 282 /* JsxSpreadAttribute */; + return kind === 281 /* JsxAttribute */ + || kind === 283 /* JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; /* @internal */ function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 10 /* StringLiteral */ - || kind === 283 /* JsxExpression */; + || kind === 284 /* JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 275 /* JsxOpeningElement */ - || kind === 274 /* JsxSelfClosingElement */; + return kind === 276 /* JsxOpeningElement */ + || kind === 275 /* JsxSelfClosingElement */; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 284 /* CaseClause */ - || kind === 285 /* DefaultClause */; + return kind === 285 /* CaseClause */ + || kind === 286 /* DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; // JSDoc /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 301 /* FirstJSDocNode */ && node.kind <= 333 /* LastJSDocNode */; + return node.kind >= 302 /* FirstJSDocNode */ && node.kind <= 337 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 311 /* JSDocComment */ || node.kind === 310 /* JSDocNamepathType */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + return node.kind === 312 /* JSDocComment */ + || node.kind === 311 /* JSDocNamepathType */ + || node.kind === 313 /* JSDocText */ + || node.kind === 316 /* JSDocLink */ + || isJSDocTag(node) + || ts.isJSDocTypeLiteral(node) + || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 314 /* FirstJSDocTagNode */ && node.kind <= 333 /* LastJSDocTagNode */; + return node.kind >= 317 /* FirstJSDocTagNode */ && node.kind <= 337 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { - return node.kind === 168 /* SetAccessor */; + return node.kind === 169 /* SetAccessor */; } ts.isSetAccessor = isSetAccessor; function isGetAccessor(node) { - return node.kind === 167 /* GetAccessor */; + return node.kind === 168 /* GetAccessor */; } ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ @@ -13191,13 +13410,13 @@ var ts; /** True if has initializer node attached to it. */ function hasOnlyExpressionInitializer(node) { switch (node.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: - case 162 /* PropertySignature */: - case 163 /* PropertyDeclaration */: - case 288 /* PropertyAssignment */: - case 291 /* EnumMember */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: + case 163 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 289 /* PropertyAssignment */: + case 292 /* EnumMember */: return true; default: return false; @@ -13205,12 +13424,12 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - return node.kind === 280 /* JsxAttribute */ || node.kind === 282 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); + return node.kind === 281 /* JsxAttribute */ || node.kind === 283 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; /* @internal */ function isTypeReferenceType(node) { - return node.kind === 173 /* TypeReference */ || node.kind === 223 /* ExpressionWithTypeArguments */; + return node.kind === 174 /* TypeReference */ || node.kind === 224 /* ExpressionWithTypeArguments */; } ts.isTypeReferenceType = isTypeReferenceType; var MAX_SMI_X86 = 1073741823; @@ -13449,7 +13668,9 @@ var ts; } ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + return oldResolution.resolvedFileName === newResolution.resolvedFileName + && oldResolution.primary === newResolution.primary + && oldResolution.originalPath === newResolution.originalPath; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { @@ -13491,7 +13712,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 297 /* SourceFile */) { + while (node && node.kind !== 298 /* SourceFile */) { node = node.parent; } return node; @@ -13499,11 +13720,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 230 /* Block */: - case 258 /* CaseBlock */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 231 /* Block */: + case 259 /* CaseBlock */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: return true; } return false; @@ -13699,10 +13920,12 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 334 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 338 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, + /*stopAfterLineBreak*/ false, + /*stopAtComments*/ false, isInJSDoc(node)); } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { @@ -13821,9 +14044,11 @@ var ts; DataView: ["setBigInt64", "setBigUint64", "getBigInt64", "getBigUint64"], RelativeTimeFormat: ["format", "formatToParts", "resolvedOptions"] }, - esnext: { + es2021: { PromiseConstructor: ["any"], - String: ["replaceAll"], + String: ["replaceAll"] + }, + esnext: { NumberFormat: ["formatToParts"] } }; @@ -13916,7 +14141,7 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 249 /* VariableDeclaration */ && node.parent.kind === 287 /* CatchClause */; + return node.kind === 250 /* VariableDeclaration */ && node.parent.kind === 288 /* CatchClause */; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { @@ -13948,11 +14173,11 @@ var ts; ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. - return node && node.kind === 256 /* ModuleDeclaration */ && (!node.body); + return !!node && node.kind === 257 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 297 /* SourceFile */ || - node.kind === 256 /* ModuleDeclaration */ || + return node.kind === 298 /* SourceFile */ || + node.kind === 257 /* ModuleDeclaration */ || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -13969,16 +14194,17 @@ var ts; // - defined in the top level scope and source file is an external module // - defined inside ambient module declaration located in the top level scope and source file not an external module switch (node.parent.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: return ts.isExternalModule(node.parent); - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } ts.isModuleAugmentationExternal = isModuleAugmentationExternal; function getNonAugmentationDeclaration(symbol) { - return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); + var _a; + return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); } ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration; function isEffectiveExternalModule(node, compilerOptions) { @@ -14024,22 +14250,22 @@ var ts; ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile; function isBlockScope(node, parentNode) { switch (node.kind) { - case 297 /* SourceFile */: - case 258 /* CaseBlock */: - case 287 /* CatchClause */: - case 256 /* ModuleDeclaration */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 298 /* SourceFile */: + case 259 /* CaseBlock */: + case 288 /* CatchClause */: + case 257 /* ModuleDeclaration */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; - case 230 /* Block */: + case 231 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block return !ts.isFunctionLike(parentNode); @@ -14049,9 +14275,9 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: - case 313 /* JSDocSignature */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: + case 315 /* JSDocSignature */: return true; default: ts.assertType(node); @@ -14061,25 +14287,25 @@ var ts; ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 164 /* MethodSignature */: - case 171 /* IndexSignature */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 308 /* JSDocFunctionType */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 330 /* JSDocTemplateTag */: - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 165 /* MethodSignature */: + case 172 /* IndexSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 309 /* JSDocFunctionType */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 334 /* JSDocTemplateTag */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; default: ts.assertType(node); @@ -14089,8 +14315,8 @@ var ts; ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: return true; default: return false; @@ -14099,15 +14325,15 @@ var ts; ts.isAnyImportSyntax = isAnyImportSyntax; function isLateVisibilityPaintedStatement(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 232 /* VariableStatement */: - case 252 /* ClassDeclaration */: - case 251 /* FunctionDeclaration */: - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 233 /* VariableStatement */: + case 253 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: return true; default: return false; @@ -14140,7 +14366,7 @@ var ts; } ts.getNameFromIndexInfo = getNameFromIndexInfo; function isComputedNonLiteralName(name) { - return name.kind === 158 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); + return name.kind === 159 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); } ts.isComputedNonLiteralName = isComputedNonLiteralName; function getTextOfPropertyName(name) { @@ -14152,7 +14378,7 @@ var ts; case 8 /* NumericLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: if (isStringOrNumericLiteralLike(name.expression)) return ts.escapeLeadingUnderscores(name.expression.text); return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames"); @@ -14168,9 +14394,9 @@ var ts; case 79 /* PrivateIdentifier */: case 78 /* Identifier */: return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) { return entityNameToString(name.expression) + "." + entityNameToString(name.name); } @@ -14256,7 +14482,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 230 /* Block */) { + if (node.body && node.body.kind === 231 /* Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -14270,7 +14496,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -14279,28 +14505,28 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 249 /* VariableDeclaration */: - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 254 /* TypeAliasDeclaration */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 250 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 255 /* TypeAliasDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: errorNode = node.name; break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: var start = ts.skipTrivia(sourceFile.text, node.pos); var end = node.statements.length > 0 ? node.statements[0].pos : node.end; return ts.createTextSpanFromBounds(start, end); @@ -14352,11 +14578,11 @@ var ts; } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 203 /* CallExpression */ && n.expression.kind === 105 /* SuperKeyword */; + return n.kind === 204 /* CallExpression */ && n.expression.kind === 105 /* SuperKeyword */; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 203 /* CallExpression */ && n.expression.kind === 99 /* ImportKeyword */; + return n.kind === 204 /* CallExpression */ && n.expression.kind === 99 /* ImportKeyword */; } ts.isImportCall = isImportCall; function isImportMeta(n) { @@ -14370,7 +14596,7 @@ var ts; } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { - return node.kind === 233 /* ExpressionStatement */ + return node.kind === 234 /* ExpressionStatement */ && node.expression.kind === 10 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; @@ -14398,11 +14624,12 @@ var ts; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 160 /* Parameter */ || - node.kind === 159 /* TypeParameter */ || - node.kind === 208 /* FunctionExpression */ || - node.kind === 209 /* ArrowFunction */ || - node.kind === 207 /* ParenthesizedExpression */) ? + var commentRanges = (node.kind === 161 /* Parameter */ || + node.kind === 160 /* TypeParameter */ || + node.kind === 209 /* FunctionExpression */ || + node.kind === 210 /* ArrowFunction */ || + node.kind === 208 /* ParenthesizedExpression */ || + node.kind === 250 /* VariableDeclaration */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -14418,7 +14645,7 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (172 /* FirstTypeNode */ <= node.kind && node.kind <= 195 /* LastTypeNode */) { + if (173 /* FirstTypeNode */ <= node.kind && node.kind <= 196 /* LastTypeNode */) { return true; } switch (node.kind) { @@ -14434,32 +14661,32 @@ var ts; case 141 /* NeverKeyword */: return true; case 113 /* VoidKeyword */: - return node.parent.kind !== 212 /* VoidExpression */; - case 223 /* ExpressionWithTypeArguments */: + return node.parent.kind !== 213 /* VoidExpression */; + case 224 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 159 /* TypeParameter */: - return node.parent.kind === 190 /* MappedType */ || node.parent.kind === 185 /* InferType */; + case 160 /* TypeParameter */: + return node.parent.kind === 191 /* MappedType */ || node.parent.kind === 186 /* InferType */; // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container case 78 /* Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 157 /* QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 158 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 202 /* PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 78 /* Identifier */ || node.kind === 157 /* QualifiedName */ || node.kind === 201 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + ts.Debug.assert(node.kind === 78 /* Identifier */ || node.kind === 158 /* QualifiedName */ || node.kind === 202 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); // falls through - case 157 /* QualifiedName */: - case 201 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: case 107 /* ThisKeyword */: { var parent = node.parent; - if (parent.kind === 176 /* TypeQuery */) { + if (parent.kind === 177 /* TypeQuery */) { return false; } - if (parent.kind === 195 /* ImportType */) { + if (parent.kind === 196 /* ImportType */) { return !parent.isTypeOf; } // Do not recursively call isPartOfTypeNode on the parent. In the example: @@ -14468,40 +14695,40 @@ var ts; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. // Only C and A.B.C are type nodes. - if (172 /* FirstTypeNode */ <= parent.kind && parent.kind <= 195 /* LastTypeNode */) { + if (173 /* FirstTypeNode */ <= parent.kind && parent.kind <= 196 /* LastTypeNode */) { return true; } switch (parent.kind) { - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return node === parent.constraint; - case 330 /* JSDocTemplateTag */: + case 334 /* JSDocTemplateTag */: return node === parent.constraint; - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 160 /* Parameter */: - case 249 /* VariableDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 161 /* Parameter */: + case 250 /* VariableDeclaration */: return node === parent.type; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return node === parent.type; - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return node === parent.type; - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: return node === parent.type; - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: return ts.contains(parent.typeArguments, node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -14526,23 +14753,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitor(node); - case 258 /* CaseBlock */: - case 230 /* Block */: - case 234 /* IfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 243 /* WithStatement */: - case 244 /* SwitchStatement */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: - case 245 /* LabeledStatement */: - case 247 /* TryStatement */: - case 287 /* CatchClause */: + case 259 /* CaseBlock */: + case 231 /* Block */: + case 235 /* IfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 244 /* WithStatement */: + case 245 /* SwitchStatement */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 246 /* LabeledStatement */: + case 248 /* TryStatement */: + case 288 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -14552,23 +14779,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 255 /* EnumDeclaration */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: // These are not allowed inside a generator now, but eventually they may be allowed // as local types. Regardless, skip them to avoid the work. return; default: if (ts.isFunctionLike(node)) { - if (node.name && node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 159 /* ComputedPropertyName */) { // Note that we will not include methods/accessors of a class because they would require // first descending into the class. This is by design. traverse(node.name.expression); @@ -14591,10 +14818,10 @@ var ts; * @param node The type node. */ function getRestParameterElementType(node) { - if (node && node.kind === 178 /* ArrayType */) { + if (node && node.kind === 179 /* ArrayType */) { return node.elementType; } - else if (node && node.kind === 173 /* TypeReference */) { + else if (node && node.kind === 174 /* TypeReference */) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -14604,12 +14831,12 @@ var ts; ts.getRestParameterElementType = getRestParameterElementType; function getMembersOfDeclaration(node) { switch (node.kind) { - case 253 /* InterfaceDeclaration */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 177 /* TypeLiteral */: + case 254 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 178 /* TypeLiteral */: return node.members; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return node.properties; } } @@ -14617,14 +14844,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 198 /* BindingElement */: - case 291 /* EnumMember */: - case 160 /* Parameter */: - case 288 /* PropertyAssignment */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 289 /* ShorthandPropertyAssignment */: - case 249 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 292 /* EnumMember */: + case 161 /* Parameter */: + case 289 /* PropertyAssignment */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 290 /* ShorthandPropertyAssignment */: + case 250 /* VariableDeclaration */: return true; } } @@ -14636,8 +14863,8 @@ var ts; } ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { - return node.parent.kind === 250 /* VariableDeclarationList */ - && node.parent.parent.kind === 232 /* VariableStatement */; + return node.parent.kind === 251 /* VariableDeclarationList */ + && node.parent.parent.kind === 233 /* VariableStatement */; } ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; function isValidESSymbolDeclaration(node) { @@ -14648,13 +14875,13 @@ var ts; ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return true; } return false; @@ -14665,7 +14892,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 245 /* LabeledStatement */) { + if (node.statement.kind !== 246 /* LabeledStatement */) { return node.statement; } node = node.statement; @@ -14673,17 +14900,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 230 /* Block */ && ts.isFunctionLike(node.parent); + return node && node.kind === 231 /* Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 165 /* MethodDeclaration */ && node.parent.kind === 200 /* ObjectLiteralExpression */; + return node && node.kind === 166 /* MethodDeclaration */ && node.parent.kind === 201 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 165 /* MethodDeclaration */ && - (node.parent.kind === 200 /* ObjectLiteralExpression */ || - node.parent.kind === 221 /* ClassExpression */); + return node.kind === 166 /* MethodDeclaration */ && + (node.parent.kind === 201 /* ObjectLiteralExpression */ || + node.parent.kind === 222 /* ClassExpression */); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -14696,7 +14923,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return objectLiteral.properties.filter(function (property) { - if (property.kind === 288 /* PropertyAssignment */) { + if (property.kind === 289 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); return key === propName || (!!key2 && key2 === propName); } @@ -14745,14 +14972,14 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { - ts.Debug.assert(node.kind !== 297 /* SourceFile */); + ts.Debug.assert(node.kind !== 298 /* SourceFile */); while (true) { node = node.parent; if (!node) { return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. } switch (node.kind) { - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: // If the grandparent node is an object literal (as opposed to a class), // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container @@ -14767,9 +14994,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 161 /* Decorator */: + case 162 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 160 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 161 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -14780,26 +15007,26 @@ var ts; node = node.parent; } break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // falls through - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 256 /* ModuleDeclaration */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 255 /* EnumDeclaration */: - case 297 /* SourceFile */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 257 /* ModuleDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 256 /* EnumDeclaration */: + case 298 /* SourceFile */: return node; } } @@ -14818,9 +15045,9 @@ var ts; var container = getThisContainer(node, /*includeArrowFunctions*/ false); if (container) { switch (container.kind) { - case 166 /* Constructor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 167 /* Constructor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return container; } } @@ -14842,27 +15069,27 @@ var ts; return node; } switch (node.kind) { - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: node = node.parent; break; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: if (!stopOnFunctions) { continue; } // falls through - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return node; - case 161 /* Decorator */: + case 162 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 160 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 161 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -14878,14 +15105,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 208 /* FunctionExpression */ || func.kind === 209 /* ArrowFunction */) { + if (func.kind === 209 /* FunctionExpression */ || func.kind === 210 /* ArrowFunction */) { var prev = func; var parent = func.parent; - while (parent.kind === 207 /* ParenthesizedExpression */) { + while (parent.kind === 208 /* ParenthesizedExpression */) { prev = parent; parent = parent.parent; } - if (parent.kind === 203 /* CallExpression */ && parent.expression === prev) { + if (parent.kind === 204 /* CallExpression */ && parent.expression === prev) { return parent; } } @@ -14901,7 +15128,7 @@ var ts; */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 201 /* PropertyAccessExpression */ || kind === 202 /* ElementAccessExpression */) + return (kind === 202 /* PropertyAccessExpression */ || kind === 203 /* ElementAccessExpression */) && node.expression.kind === 105 /* SuperKeyword */; } ts.isSuperProperty = isSuperProperty; @@ -14910,7 +15137,7 @@ var ts; */ function isThisProperty(node) { var kind = node.kind; - return (kind === 201 /* PropertyAccessExpression */ || kind === 202 /* ElementAccessExpression */) + return (kind === 202 /* PropertyAccessExpression */ || kind === 203 /* ElementAccessExpression */) && node.expression.kind === 107 /* ThisKeyword */; } ts.isThisProperty = isThisProperty; @@ -14919,17 +15146,25 @@ var ts; return !!node && ts.isVariableDeclaration(node) && ((_a = node.initializer) === null || _a === void 0 ? void 0 : _a.kind) === 107 /* ThisKeyword */; } ts.isThisInitializedDeclaration = isThisInitializedDeclaration; + function isThisInitializedObjectBindingExpression(node) { + return !!node + && (ts.isShorthandPropertyAssignment(node) || ts.isPropertyAssignment(node)) + && ts.isBinaryExpression(node.parent.parent) + && node.parent.parent.operatorToken.kind === 62 /* EqualsToken */ + && node.parent.parent.right.kind === 107 /* ThisKeyword */; + } + ts.isThisInitializedObjectBindingExpression = isThisInitializedObjectBindingExpression; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return node.typeName; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) ? node.expression : undefined; // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s. case 78 /* Identifier */: - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return node; } return undefined; @@ -14937,10 +15172,10 @@ var ts; ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { switch (node.kind) { - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return node.tag; - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return node.tagName; default: return node.expression; @@ -14953,25 +15188,25 @@ var ts; return false; } switch (node.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: // classes are valid targets return true; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return parent.kind === 252 /* ClassDeclaration */; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: + return parent.kind === 253 /* ClassDeclaration */; + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && parent.kind === 252 /* ClassDeclaration */; - case 160 /* Parameter */: + && parent.kind === 253 /* ClassDeclaration */; + case 161 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; return parent.body !== undefined - && (parent.kind === 166 /* Constructor */ - || parent.kind === 165 /* MethodDeclaration */ - || parent.kind === 168 /* SetAccessor */) - && grandparent.kind === 252 /* ClassDeclaration */; + && (parent.kind === 167 /* Constructor */ + || parent.kind === 166 /* MethodDeclaration */ + || parent.kind === 169 /* SetAccessor */) + && grandparent.kind === 253 /* ClassDeclaration */; } return false; } @@ -14987,10 +15222,10 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 - case 165 /* MethodDeclaration */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 169 /* SetAccessor */: return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 default: return false; @@ -14999,9 +15234,9 @@ var ts; ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 275 /* JsxOpeningElement */ || - parent.kind === 274 /* JsxSelfClosingElement */ || - parent.kind === 276 /* JsxClosingElement */) { + if (parent.kind === 276 /* JsxOpeningElement */ || + parent.kind === 275 /* JsxSelfClosingElement */ || + parent.kind === 277 /* JsxClosingElement */) { return parent.tagName === node; } return false; @@ -15014,44 +15249,44 @@ var ts; case 109 /* TrueKeyword */: case 94 /* FalseKeyword */: case 13 /* RegularExpressionLiteral */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 205 /* TaggedTemplateExpression */: - case 224 /* AsExpression */: - case 206 /* TypeAssertionExpression */: - case 225 /* NonNullExpression */: - case 207 /* ParenthesizedExpression */: - case 208 /* FunctionExpression */: - case 221 /* ClassExpression */: - case 209 /* ArrowFunction */: - case 212 /* VoidExpression */: - case 210 /* DeleteExpression */: - case 211 /* TypeOfExpression */: - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: - case 216 /* BinaryExpression */: - case 217 /* ConditionalExpression */: - case 220 /* SpreadElement */: - case 218 /* TemplateExpression */: - case 222 /* OmittedExpression */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: - case 219 /* YieldExpression */: - case 213 /* AwaitExpression */: - case 226 /* MetaProperty */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 206 /* TaggedTemplateExpression */: + case 225 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 226 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 209 /* FunctionExpression */: + case 222 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 213 /* VoidExpression */: + case 211 /* DeleteExpression */: + case 212 /* TypeOfExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 217 /* BinaryExpression */: + case 218 /* ConditionalExpression */: + case 221 /* SpreadElement */: + case 219 /* TemplateExpression */: + case 223 /* OmittedExpression */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: + case 220 /* YieldExpression */: + case 214 /* AwaitExpression */: + case 227 /* MetaProperty */: return true; - case 157 /* QualifiedName */: - while (node.parent.kind === 157 /* QualifiedName */) { + case 158 /* QualifiedName */: + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 176 /* TypeQuery */ || isJSXTagName(node); + return node.parent.kind === 177 /* TypeQuery */ || isJSXTagName(node); case 78 /* Identifier */: - if (node.parent.kind === 176 /* TypeQuery */ || isJSXTagName(node)) { + if (node.parent.kind === 177 /* TypeQuery */ || isJSXTagName(node)) { return true; } // falls through @@ -15069,49 +15304,49 @@ var ts; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 291 /* EnumMember */: - case 288 /* PropertyAssignment */: - case 198 /* BindingElement */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 292 /* EnumMember */: + case 289 /* PropertyAssignment */: + case 199 /* BindingElement */: return parent.initializer === node; - case 233 /* ExpressionStatement */: - case 234 /* IfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 242 /* ReturnStatement */: - case 243 /* WithStatement */: - case 244 /* SwitchStatement */: - case 284 /* CaseClause */: - case 246 /* ThrowStatement */: + case 234 /* ExpressionStatement */: + case 235 /* IfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 243 /* ReturnStatement */: + case 244 /* WithStatement */: + case 245 /* SwitchStatement */: + case 285 /* CaseClause */: + case 247 /* ThrowStatement */: return parent.expression === node; - case 237 /* ForStatement */: + case 238 /* ForStatement */: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 250 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 251 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 250 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 251 /* VariableDeclarationList */) || forInStatement.expression === node; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return node === parent.expression; - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return node === parent.expression; - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return node === parent.expression; - case 161 /* Decorator */: - case 283 /* JsxExpression */: - case 282 /* JsxSpreadAttribute */: - case 290 /* SpreadAssignment */: + case 162 /* Decorator */: + case 284 /* JsxExpression */: + case 283 /* JsxSpreadAttribute */: + case 291 /* SpreadAssignment */: return true; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return parent.objectAssignmentInitializer === node; default: return isExpressionNode(parent); @@ -15119,14 +15354,18 @@ var ts; } ts.isInExpressionContext = isInExpressionContext; function isPartOfTypeQuery(node) { - while (node.kind === 157 /* QualifiedName */ || node.kind === 78 /* Identifier */) { + while (node.kind === 158 /* QualifiedName */ || node.kind === 78 /* Identifier */) { node = node.parent; } - return node.kind === 176 /* TypeQuery */; + return node.kind === 177 /* TypeQuery */; } ts.isPartOfTypeQuery = isPartOfTypeQuery; + function isNamespaceReexportDeclaration(node) { + return ts.isNamespaceExport(node) && !!node.parent.moduleSpecifier; + } + ts.isNamespaceReexportDeclaration = isNamespaceReexportDeclaration; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 272 /* ExternalModuleReference */; + return node.kind === 261 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 273 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -15135,12 +15374,11 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function getExternalModuleRequireArgument(node) { - return isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true) - && getLeftmostAccessExpression(node.initializer).arguments[0]; + return isRequireVariableDeclaration(node) && getLeftmostAccessExpression(node.initializer).arguments[0]; } ts.getExternalModuleRequireArgument = getExternalModuleRequireArgument; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 272 /* ExternalModuleReference */; + return node.kind === 261 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 273 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJS(file) { @@ -15176,7 +15414,7 @@ var ts; } ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, requireStringLiteralLikeArgument) { - if (callExpression.kind !== 203 /* CallExpression */) { + if (callExpression.kind !== 204 /* CallExpression */) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; @@ -15190,18 +15428,21 @@ var ts; return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; - function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) { - if (node.kind === 198 /* BindingElement */) { + /** + * Returns true if the node is a VariableDeclaration initialized to a require call (see `isRequireCall`). + * This function does not test if the node is in a JavaScript file or not. + */ + function isRequireVariableDeclaration(node) { + if (node.kind === 199 /* BindingElement */) { node = node.parent.parent; } - return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), requireStringLiteralLikeArgument); + return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), /*requireStringLiteralLikeArgument*/ true); } ts.isRequireVariableDeclaration = isRequireVariableDeclaration; - function isRequireVariableStatement(node, requireStringLiteralLikeArgument) { - if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; } + function isRequireVariableStatement(node) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 - && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); }); + && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl); }); } ts.isRequireVariableStatement = isRequireVariableStatement; function isSingleOrDoubleQuote(charCode) { @@ -15273,11 +15514,11 @@ var ts; function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); - return e.kind === 208 /* FunctionExpression */ || e.kind === 209 /* ArrowFunction */ ? initializer : undefined; + return e.kind === 209 /* FunctionExpression */ || e.kind === 210 /* ArrowFunction */ ? initializer : undefined; } - if (initializer.kind === 208 /* FunctionExpression */ || - initializer.kind === 221 /* ClassExpression */ || - initializer.kind === 209 /* ArrowFunction */) { + if (initializer.kind === 209 /* FunctionExpression */ || + initializer.kind === 222 /* ClassExpression */ || + initializer.kind === 210 /* ArrowFunction */) { return initializer; } if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { @@ -15398,8 +15639,7 @@ var ts; ts.isLiteralLikeAccess = isLiteralLikeAccess; /** x[0] OR x['a'] OR x[Symbol.y] */ function isLiteralLikeElementAccess(node) { - return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) || - isWellKnownSymbolSyntactically(node.argumentExpression)); + return ts.isElementAccessExpression(node) && isStringOrNumericLiteralLike(node.argumentExpression); } ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess; /** Any series of property and element accesses. */ @@ -15479,9 +15719,6 @@ var ts; return ts.escapeLeadingUnderscores(name.text); } } - if (ts.isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) { - return getPropertyNameForKnownSymbolName(ts.idText(node.argumentExpression.name)); - } return undefined; } ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName; @@ -15531,7 +15768,7 @@ var ts; ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { return isInJSFile(expr) && - expr.parent && expr.parent.kind === 233 /* ExpressionStatement */ && + expr.parent && expr.parent.kind === 234 /* ExpressionStatement */ && (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) && !!ts.getJSDocTypeTag(expr.parent); } @@ -15552,23 +15789,37 @@ var ts; return false; } var decl = symbol.valueDeclaration; - return decl.kind === 251 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + return decl.kind === 252 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); } ts.isFunctionSymbol = isFunctionSymbol; + function tryGetModuleSpecifierFromDeclaration(node) { + var _a, _b, _c; + switch (node.kind) { + case 250 /* VariableDeclaration */: + return node.initializer.arguments[0].text; + case 262 /* ImportDeclaration */: + return (_a = ts.tryCast(node.moduleSpecifier, ts.isStringLiteralLike)) === null || _a === void 0 ? void 0 : _a.text; + case 261 /* ImportEqualsDeclaration */: + return (_c = ts.tryCast((_b = ts.tryCast(node.moduleReference, ts.isExternalModuleReference)) === null || _b === void 0 ? void 0 : _b.expression, ts.isStringLiteralLike)) === null || _c === void 0 ? void 0 : _c.text; + default: + ts.Debug.assertNever(node); + } + } + ts.tryGetModuleSpecifierFromDeclaration = tryGetModuleSpecifierFromDeclaration; function importFromModuleSpecifier(node) { return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent); } ts.importFromModuleSpecifier = importFromModuleSpecifier; function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: return node.parent; - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: return node.parent.parent; - case 203 /* CallExpression */: + case 204 /* CallExpression */: return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined; - case 191 /* LiteralType */: + case 192 /* LiteralType */: ts.Debug.assert(ts.isStringLiteral(node)); return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: @@ -15578,15 +15829,17 @@ var ts; ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: return node.moduleSpecifier; - case 260 /* ImportEqualsDeclaration */: - return node.moduleReference.kind === 272 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; - case 195 /* ImportType */: + case 261 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 273 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 196 /* ImportType */: return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; - case 203 /* CallExpression */: + case 204 /* CallExpression */: return node.arguments[0]; + case 257 /* ModuleDeclaration */: + return node.name.kind === 10 /* StringLiteral */ ? node.name : undefined; default: return ts.Debug.assertNever(node); } @@ -15594,11 +15847,11 @@ var ts; ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return node; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport); default: return ts.Debug.assertNever(node); @@ -15606,7 +15859,7 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 261 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; + return node.kind === 262 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function forEachImportClauseDeclaration(node, action) { @@ -15627,13 +15880,13 @@ var ts; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 160 /* Parameter */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 289 /* ShorthandPropertyAssignment */: - case 288 /* PropertyAssignment */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 161 /* Parameter */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 290 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -15647,7 +15900,7 @@ var ts; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 331 /* JSDocTypedefTag */ || node.kind === 324 /* JSDocCallbackTag */ || node.kind === 325 /* JSDocEnumTag */; + return node.kind === 335 /* JSDocTypedefTag */ || node.kind === 328 /* JSDocCallbackTag */ || node.kind === 329 /* JSDocEnumTag */; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -15672,12 +15925,12 @@ var ts; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: var v = getSingleVariableOfVariableStatement(node); return v && v.initializer; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return node.initializer; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return node.initializer; } } @@ -15689,7 +15942,7 @@ var ts; function getNestedModuleDeclaration(node) { return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 256 /* ModuleDeclaration */ + node.body.kind === 257 /* ModuleDeclaration */ ? node.body : undefined; } @@ -15704,11 +15957,11 @@ var ts; if (ts.hasJSDocNodes(node)) { result = ts.append(result, ts.last(node.jsDoc)); } - if (node.kind === 160 /* Parameter */) { + if (node.kind === 161 /* Parameter */) { result = ts.addRange(result, (noCache ? ts.getJSDocParameterTagsNoCache : ts.getJSDocParameterTags)(node)); break; } - if (node.kind === 159 /* TypeParameter */) { + if (node.kind === 160 /* TypeParameter */) { result = ts.addRange(result, (noCache ? ts.getJSDocTypeParameterTagsNoCache : ts.getJSDocTypeParameterTags)(node)); break; } @@ -15719,10 +15972,11 @@ var ts; ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; function getNextJSDocCommentLocation(node) { var parent = node.parent; - if (parent.kind === 288 /* PropertyAssignment */ || - parent.kind === 266 /* ExportAssignment */ || - parent.kind === 163 /* PropertyDeclaration */ || - parent.kind === 233 /* ExpressionStatement */ && node.kind === 201 /* PropertyAccessExpression */ || + if (parent.kind === 289 /* PropertyAssignment */ || + parent.kind === 267 /* ExportAssignment */ || + parent.kind === 164 /* PropertyDeclaration */ || + parent.kind === 234 /* ExpressionStatement */ && node.kind === 202 /* PropertyAccessExpression */ || + parent.kind === 243 /* ReturnStatement */ || getNestedModuleDeclaration(parent) || ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) { return parent; @@ -15809,7 +16063,7 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 309 /* JSDocVariadicType */; + return node.dotDotDotToken !== undefined || !!type && type.kind === 310 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; function hasTypeArguments(node) { @@ -15826,31 +16080,34 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? binaryOperator === 62 /* EqualsToken */ || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? 1 /* Definite */ : 2 /* Compound */ : 0 /* None */; - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: var unaryOperator = parent.operator; return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; - case 207 /* ParenthesizedExpression */: - case 199 /* ArrayLiteralExpression */: - case 220 /* SpreadElement */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 200 /* ArrayLiteralExpression */: + case 221 /* SpreadElement */: + case 226 /* NonNullExpression */: node = parent; break; - case 289 /* ShorthandPropertyAssignment */: + case 291 /* SpreadAssignment */: + node = parent.parent; + break; + case 290 /* ShorthandPropertyAssignment */: if (parent.name !== node) { return 0 /* None */; } node = parent.parent; break; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: if (parent.name === node) { return 0 /* None */; } @@ -15877,22 +16134,22 @@ var ts; */ function isNodeWithPossibleHoistedDeclaration(node) { switch (node.kind) { - case 230 /* Block */: - case 232 /* VariableStatement */: - case 243 /* WithStatement */: - case 234 /* IfStatement */: - case 244 /* SwitchStatement */: - case 258 /* CaseBlock */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: - case 245 /* LabeledStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 247 /* TryStatement */: - case 287 /* CatchClause */: + case 231 /* Block */: + case 233 /* VariableStatement */: + case 244 /* WithStatement */: + case 235 /* IfStatement */: + case 245 /* SwitchStatement */: + case 259 /* CaseBlock */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 246 /* LabeledStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 248 /* TryStatement */: + case 288 /* CatchClause */: return true; } return false; @@ -15909,11 +16166,11 @@ var ts; return node; } function walkUpParenthesizedTypes(node) { - return walkUp(node, 186 /* ParenthesizedType */); + return walkUp(node, 187 /* ParenthesizedType */); } ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; function walkUpParenthesizedExpressions(node) { - return walkUp(node, 207 /* ParenthesizedExpression */); + return walkUp(node, 208 /* ParenthesizedExpression */); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; /** @@ -15923,7 +16180,7 @@ var ts; */ function walkUpParenthesizedTypesAndGetParentAndChild(node) { var child; - while (node && node.kind === 186 /* ParenthesizedType */) { + while (node && node.kind === 187 /* ParenthesizedType */) { child = node; node = node.parent; } @@ -15935,18 +16192,18 @@ var ts; } ts.skipParentheses = skipParentheses; function skipParenthesesUp(node) { - while (node.kind === 207 /* ParenthesizedExpression */) { + while (node.kind === 208 /* 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 !== 201 /* PropertyAccessExpression */ && node.kind !== 202 /* ElementAccessExpression */) { + if (node.kind !== 202 /* PropertyAccessExpression */ && node.kind !== 203 /* ElementAccessExpression */) { return false; } node = walkUpParenthesizedExpressions(node.parent); - return node && node.kind === 210 /* DeleteExpression */; + return node && node.kind === 211 /* DeleteExpression */; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -15999,7 +16256,7 @@ var ts; ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return isStringOrNumericLiteralLike(node) && - node.parent.kind === 158 /* ComputedPropertyName */ && + node.parent.kind === 159 /* ComputedPropertyName */ && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; @@ -16007,26 +16264,26 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 291 /* EnumMember */: - case 288 /* PropertyAssignment */: - case 201 /* PropertyAccessExpression */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 292 /* EnumMember */: + case 289 /* PropertyAssignment */: + case 202 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: // Name on right hand side of dot in a type query or type reference return parent.right === node; - case 198 /* BindingElement */: - case 265 /* ImportSpecifier */: + case 199 /* BindingElement */: + case 266 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 270 /* ExportSpecifier */: - case 280 /* JsxAttribute */: + case 271 /* ExportSpecifier */: + case 281 /* JsxAttribute */: // Any name in an export specifier or JSX Attribute return true; } @@ -16046,33 +16303,33 @@ var ts; // {} // {name: } function isAliasSymbolDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ || - node.kind === 259 /* NamespaceExportDeclaration */ || - node.kind === 262 /* ImportClause */ && !!node.name || - node.kind === 263 /* NamespaceImport */ || - node.kind === 269 /* NamespaceExport */ || - node.kind === 265 /* ImportSpecifier */ || - node.kind === 270 /* ExportSpecifier */ || - node.kind === 266 /* ExportAssignment */ && exportAssignmentIsAlias(node) || + return node.kind === 261 /* ImportEqualsDeclaration */ || + node.kind === 260 /* NamespaceExportDeclaration */ || + node.kind === 263 /* ImportClause */ && !!node.name || + node.kind === 264 /* NamespaceImport */ || + node.kind === 270 /* NamespaceExport */ || + node.kind === 266 /* ImportSpecifier */ || + node.kind === 271 /* ExportSpecifier */ || + node.kind === 267 /* ExportAssignment */ && exportAssignmentIsAlias(node) || ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) || ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableExpression(node.parent.right) || - node.kind === 289 /* ShorthandPropertyAssignment */ || - node.kind === 288 /* PropertyAssignment */ && isAliasableExpression(node.initializer); + node.kind === 290 /* ShorthandPropertyAssignment */ || + node.kind === 289 /* PropertyAssignment */ && isAliasableExpression(node.initializer); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getAliasDeclarationFromName(node) { switch (node.parent.kind) { - case 262 /* ImportClause */: - case 265 /* ImportSpecifier */: - case 263 /* NamespaceImport */: - case 270 /* ExportSpecifier */: - case 266 /* ExportAssignment */: - case 260 /* ImportEqualsDeclaration */: + case 263 /* ImportClause */: + case 266 /* ImportSpecifier */: + case 264 /* NamespaceImport */: + case 271 /* ExportSpecifier */: + case 267 /* ExportAssignment */: + case 261 /* ImportEqualsDeclaration */: return node.parent; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: do { node = node.parent; - } while (node.parent.kind === 157 /* QualifiedName */); + } while (node.parent.kind === 158 /* QualifiedName */); return getAliasDeclarationFromName(node); } } @@ -16091,7 +16348,7 @@ var ts; } ts.getExportAssignmentExpression = getExportAssignmentExpression; function getPropertyAssignmentAliasLikeExpression(node) { - return node.kind === 289 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 288 /* PropertyAssignment */ ? node.initializer : + return node.kind === 290 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 289 /* PropertyAssignment */ ? node.initializer : node.parent.right; } ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression; @@ -16157,11 +16414,11 @@ var ts; } ts.getAncestor = getAncestor; function isKeyword(token) { - return 80 /* FirstKeyword */ <= token && token <= 156 /* LastKeyword */; + return 80 /* FirstKeyword */ <= token && token <= 157 /* LastKeyword */; } ts.isKeyword = isKeyword; function isContextualKeyword(token) { - return 125 /* FirstContextualKeyword */ <= token && token <= 156 /* LastContextualKeyword */; + return 125 /* FirstContextualKeyword */ <= token && token <= 157 /* LastContextualKeyword */; } ts.isContextualKeyword = isContextualKeyword; function isNonContextualKeyword(token) { @@ -16205,14 +16462,14 @@ var ts; } var flags = 0 /* Normal */; switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: if (node.asteriskToken) { flags |= 1 /* Generator */; } // falls through - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: if (hasSyntacticModifier(node, 256 /* Async */)) { flags |= 2 /* Async */; } @@ -16226,10 +16483,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: return node.body !== undefined && node.asteriskToken === undefined && hasSyntacticModifier(node, 256 /* Async */); @@ -16252,9 +16509,6 @@ var ts; * 3. The computed name is *not* expressed as a NumericLiteral. * 4. The computed name is *not* expressed as a PlusToken or MinusToken * immediately followed by a NumericLiteral. - * 5. The computed name is *not* expressed as `Symbol.`, where `` - * is a property of the Symbol constructor that denotes a built-in - * Symbol. */ function hasDynamicName(declaration) { var name = ts.getNameOfDeclaration(declaration); @@ -16262,24 +16516,14 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - if (!(name.kind === 158 /* ComputedPropertyName */ || name.kind === 202 /* ElementAccessExpression */)) { + if (!(name.kind === 159 /* ComputedPropertyName */ || name.kind === 203 /* ElementAccessExpression */)) { return false; } var expr = ts.isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression; return !isStringOrNumericLiteralLike(expr) && - !isSignedNumericLiteral(expr) && - !isWellKnownSymbolSyntactically(expr); + !isSignedNumericLiteral(expr); } ts.isDynamicName = isDynamicName; - /** - * Checks if the expression is of the form: - * Symbol.name - * where Symbol is literally the word "Symbol", and name is any identifierName - */ - function isWellKnownSymbolSyntactically(node) { - return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); - } - ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { switch (name.kind) { case 78 /* Identifier */: @@ -16288,12 +16532,9 @@ var ts; case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: var nameExpression = name.expression; - if (isWellKnownSymbolSyntactically(nameExpression)) { - return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - else if (isStringOrNumericLiteralLike(nameExpression)) { + if (isStringOrNumericLiteralLike(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); } else if (isSignedNumericLiteral(nameExpression)) { @@ -16321,21 +16562,17 @@ var ts; } ts.isPropertyNameLiteral = isPropertyNameLiteral; function getTextOfIdentifierOrLiteral(node) { - return ts.isIdentifierOrPrivateIdentifier(node) ? ts.idText(node) : node.text; + return ts.isMemberName(node) ? ts.idText(node) : node.text; } ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { - return ts.isIdentifierOrPrivateIdentifier(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text); + return ts.isMemberName(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForUniqueESSymbol(symbol) { return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName; } ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol; - function getPropertyNameForKnownSymbolName(symbolName) { - return "__@" + symbolName; - } - ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) { return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description; } @@ -16357,11 +16594,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 160 /* Parameter */; + return root.kind === 161 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 198 /* BindingElement */) { + while (node.kind === 199 /* BindingElement */) { node = node.parent.parent; } return node; @@ -16369,15 +16606,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 166 /* Constructor */ - || kind === 208 /* FunctionExpression */ - || kind === 251 /* FunctionDeclaration */ - || kind === 209 /* ArrowFunction */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 256 /* ModuleDeclaration */ - || kind === 297 /* SourceFile */; + return kind === 167 /* Constructor */ + || kind === 209 /* FunctionExpression */ + || kind === 252 /* FunctionDeclaration */ + || kind === 210 /* ArrowFunction */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 257 /* ModuleDeclaration */ + || kind === 298 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -16396,23 +16633,23 @@ var ts; })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 204 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 205 /* NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 204 /* NewExpression */: + case 205 /* NewExpression */: return hasArguments ? 0 /* Left */ : 1 /* Right */; - case 214 /* PrefixUnaryExpression */: - case 211 /* TypeOfExpression */: - case 212 /* VoidExpression */: - case 210 /* DeleteExpression */: - case 213 /* AwaitExpression */: - case 217 /* ConditionalExpression */: - case 219 /* YieldExpression */: + case 215 /* PrefixUnaryExpression */: + case 212 /* TypeOfExpression */: + case 213 /* VoidExpression */: + case 211 /* DeleteExpression */: + case 214 /* AwaitExpression */: + case 218 /* ConditionalExpression */: + case 220 /* YieldExpression */: return 1 /* Right */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (operator) { case 42 /* AsteriskAsteriskToken */: case 62 /* EqualsToken */: @@ -16439,15 +16676,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 204 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 205 /* NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 216 /* BinaryExpression */) { + if (expression.kind === 217 /* BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 214 /* PrefixUnaryExpression */ || expression.kind === 215 /* PostfixUnaryExpression */) { + else if (expression.kind === 215 /* PrefixUnaryExpression */ || expression.kind === 216 /* PostfixUnaryExpression */) { return expression.operator; } else { @@ -16626,15 +16863,15 @@ var ts; })(OperatorPrecedence = ts.OperatorPrecedence || (ts.OperatorPrecedence = {})); function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return 0 /* Comma */; - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return 1 /* Spread */; - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return 2 /* Yield */; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return 4 /* Conditional */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (operatorKind) { case 27 /* CommaToken */: return 0 /* Comma */; @@ -16659,25 +16896,26 @@ var ts; return getBinaryOperatorPrecedence(operatorKind); } // TODO: Should prefix `++` and `--` be moved to the `Update` precedence? - case 206 /* TypeAssertionExpression */: - case 225 /* NonNullExpression */: - case 214 /* PrefixUnaryExpression */: - case 211 /* TypeOfExpression */: - case 212 /* VoidExpression */: - case 210 /* DeleteExpression */: - case 213 /* AwaitExpression */: + case 207 /* TypeAssertionExpression */: + case 226 /* NonNullExpression */: + case 215 /* PrefixUnaryExpression */: + case 212 /* TypeOfExpression */: + case 213 /* VoidExpression */: + case 211 /* DeleteExpression */: + case 214 /* AwaitExpression */: return 16 /* Unary */; - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return 17 /* Update */; - case 203 /* CallExpression */: + case 204 /* CallExpression */: return 18 /* LeftHandSide */; - case 204 /* NewExpression */: + case 205 /* NewExpression */: return hasArguments ? 19 /* Member */ : 18 /* LeftHandSide */; - case 205 /* TaggedTemplateExpression */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 206 /* TaggedTemplateExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 227 /* MetaProperty */: return 19 /* Member */; - case 224 /* AsExpression */: + case 225 /* AsExpression */: return 11 /* Relational */; case 107 /* ThisKeyword */: case 105 /* SuperKeyword */: @@ -16688,19 +16926,19 @@ var ts; case 8 /* NumericLiteral */: case 9 /* BigIntLiteral */: case 10 /* StringLiteral */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 221 /* ClassExpression */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 222 /* ClassExpression */: case 13 /* RegularExpressionLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: - case 218 /* TemplateExpression */: - case 207 /* ParenthesizedExpression */: - case 222 /* OmittedExpression */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: + case 219 /* TemplateExpression */: + case 208 /* ParenthesizedExpression */: + case 223 /* OmittedExpression */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: return 20 /* Primary */; default: return -1 /* Invalid */; @@ -16756,7 +16994,7 @@ var ts; function getSemanticJsxChildren(children) { return ts.filter(children, function (i) { switch (i.kind) { - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return !!i.expression; case 11 /* JsxText */: return !i.containsOnlyTriviaWhiteSpaces; @@ -17150,11 +17388,20 @@ var ts; return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getCanonicalAbsolutePath(host, path) { + return host.getCanonicalFileName(ts.getNormalizedAbsolutePath(path, host.getCurrentDirectory())); + } function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); if (!file || file.isDeclarationFile) { return undefined; } + // If the declaration already uses a non-relative name, and is outside the common source directory, continue to use it + var specifier = getExternalModuleName(declaration); + if (specifier && ts.isStringLiteralLike(specifier) && !ts.pathIsRelative(specifier.text) && + getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ts.ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1) { + return undefined; + } return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; @@ -17238,8 +17485,8 @@ var ts; return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !host.isSourceFileFromExternalLibrary(sourceFile) && - !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) && - (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName)); + (forceDtsEmit || (!(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) && + !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName))); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -17334,10 +17581,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 167 /* GetAccessor */) { + if (accessor.kind === 168 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 168 /* SetAccessor */) { + else if (accessor.kind === 169 /* SetAccessor */) { setAccessor = accessor; } else { @@ -17357,10 +17604,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 167 /* GetAccessor */ && !getAccessor) { + if (member.kind === 168 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 168 /* SetAccessor */ && !setAccessor) { + if (member.kind === 169 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -17409,7 +17656,7 @@ var ts; ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** template tags are only available when a typedef isn't already using them */ function isNonTypeAliasTemplate(tag) { - return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 311 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 312 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); } /** * Gets the effective type annotation of the value parameter of a set accessor. If the node @@ -17632,6 +17879,18 @@ var ts; return hasSyntacticModifier(node, 32 /* Static */); } ts.hasStaticModifier = hasStaticModifier; + function hasOverrideModifier(node) { + return hasEffectiveModifier(node, 16384 /* Override */); + } + ts.hasOverrideModifier = hasOverrideModifier; + function hasAbstractModifier(node) { + return hasSyntacticModifier(node, 128 /* Abstract */); + } + ts.hasAbstractModifier = hasAbstractModifier; + function hasAmbientModifier(node) { + return hasSyntacticModifier(node, 2 /* Ambient */); + } + ts.hasAmbientModifier = hasAmbientModifier; function hasEffectiveReadonlyModifier(node) { return hasEffectiveModifier(node, 64 /* Readonly */); } @@ -17645,7 +17904,7 @@ var ts; } ts.getSelectedSyntacticModifierFlags = getSelectedSyntacticModifierFlags; function getModifierFlagsWorker(node, includeJSDoc, alwaysIncludeJSDoc) { - if (node.kind >= 0 /* FirstToken */ && node.kind <= 156 /* LastToken */) { + if (node.kind >= 0 /* FirstToken */ && node.kind <= 157 /* LastToken */) { return 0 /* None */; } if (!(node.modifierFlagsCache & 536870912 /* HasComputedFlags */)) { @@ -17690,6 +17949,8 @@ var ts; flags |= 16 /* Protected */; if (ts.getJSDocReadonlyTagNoCache(node)) flags |= 64 /* Readonly */; + if (ts.getJSDocOverrideTagNoCache(node)) + flags |= 16384 /* Override */; } if (ts.getJSDocDeprecatedTagNoCache(node)) flags |= 8192 /* Deprecated */; @@ -17742,10 +18003,15 @@ var ts; case 87 /* DefaultKeyword */: return 512 /* Default */; case 129 /* AsyncKeyword */: return 256 /* Async */; case 142 /* ReadonlyKeyword */: return 64 /* Readonly */; + case 156 /* OverrideKeyword */: return 16384 /* Override */; } return 0 /* None */; } ts.modifierToFlag = modifierToFlag; + function createModifiers(modifierFlags) { + return modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; + } + ts.createModifiers = createModifiers; function isLogicalOperator(token) { return token === 56 /* BarBarToken */ || token === 55 /* AmpersandAmpersandToken */ @@ -17788,11 +18054,15 @@ var ts; && ts.isLeftHandSideExpression(node.left); } ts.isAssignmentExpression = isAssignmentExpression; + function isLeftHandSideOfAssignment(node) { + return isAssignmentExpression(node.parent) && node.parent.left === node; + } + ts.isLeftHandSideOfAssignment = isLeftHandSideOfAssignment; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { var kind = node.left.kind; - return kind === 200 /* ObjectLiteralExpression */ - || kind === 199 /* ArrayLiteralExpression */; + return kind === 201 /* ObjectLiteralExpression */ + || kind === 200 /* ArrayLiteralExpression */; } return false; } @@ -17809,12 +18079,12 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: do { node = node.left; } while (node.kind !== 78 /* Identifier */); return node; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: do { node = node.expression; } while (node.kind !== 78 /* Identifier */); @@ -17823,9 +18093,12 @@ var ts; } ts.getFirstIdentifier = getFirstIdentifier; function isDottedName(node) { - return node.kind === 78 /* Identifier */ || node.kind === 107 /* ThisKeyword */ || node.kind === 105 /* SuperKeyword */ || - node.kind === 201 /* PropertyAccessExpression */ && isDottedName(node.expression) || - node.kind === 207 /* ParenthesizedExpression */ && isDottedName(node.expression); + return node.kind === 78 /* Identifier */ + || node.kind === 107 /* ThisKeyword */ + || node.kind === 105 /* SuperKeyword */ + || node.kind === 227 /* MetaProperty */ + || node.kind === 202 /* PropertyAccessExpression */ && isDottedName(node.expression) + || node.kind === 208 /* ParenthesizedExpression */ && isDottedName(node.expression); } ts.isDottedName = isDottedName; function isPropertyAccessEntityNameExpression(node) { @@ -17839,6 +18112,12 @@ var ts; return baseStr + "." + entityNameToString(expr.name); } } + else if (ts.isElementAccessExpression(expr)) { + var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); + if (baseStr !== undefined && ts.isPropertyName(expr.argumentExpression)) { + return baseStr + "." + getPropertyNameForPropertyNameNode(expr.argumentExpression); + } + } else if (ts.isIdentifier(expr)) { return ts.unescapeLeadingUnderscores(expr.escapedText); } @@ -17850,22 +18129,22 @@ var ts; } ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 157 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 158 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 202 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 200 /* ObjectLiteralExpression */ && + return expression.kind === 201 /* ObjectLiteralExpression */ && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 199 /* ArrayLiteralExpression */ && + return expression.kind === 200 /* ArrayLiteralExpression */ && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - if (!isExportDefaultSymbol(symbol)) + if (!isExportDefaultSymbol(symbol) || !symbol.declarations) return undefined; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; @@ -18192,8 +18471,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 255 /* EnumDeclaration */: - case 256 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 257 /* ModuleDeclaration */: return parseNode === parseNode.parent.name; } } @@ -18220,9 +18499,11 @@ var ts; return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0; } ts.getCheckFlags = getCheckFlags; - function getDeclarationModifierFlagsFromSymbol(s) { + function getDeclarationModifierFlagsFromSymbol(s, isWrite) { + if (isWrite === void 0) { isWrite = false; } if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + var declaration = (isWrite && s.declarations && ts.find(s.declarations, function (d) { return d.kind === 169 /* SetAccessor */; })) || s.valueDeclaration; + var flags = ts.getCombinedModifierFlags(declaration); return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; } if (getCheckFlags(s) & 6 /* Synthetic */) { @@ -18270,35 +18551,35 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return accessKind(parent); - case 215 /* PostfixUnaryExpression */: - case 214 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: var operator = parent.operator; return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? operatorToken.kind === 62 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() : 0 /* Read */; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); - case 288 /* PropertyAssignment */: { + case 289 /* 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 289 /* ShorthandPropertyAssignment */: + case 290 /* 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 199 /* ArrayLiteralExpression */: + case 200 /* 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 && skipParenthesesUp(parent.parent).kind === 233 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 234 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; } } function reverseAccessKind(a) { @@ -18386,7 +18667,8 @@ var ts; } ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol; function getClassLikeDeclarationOfSymbol(symbol) { - return ts.find(symbol.declarations, ts.isClassLike); + var _a; + return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isClassLike); } ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; function getObjectFlags(type) { @@ -18429,7 +18711,6 @@ var ts; ts.getLastChild = getLastChild; function addToSeen(seen, key, value) { if (value === void 0) { value = true; } - key = String(key); if (seen.has(key)) { return false; } @@ -18442,7 +18723,7 @@ var ts; } ts.isObjectTypeDeclaration = isObjectTypeDeclaration; function isTypeNodeKind(kind) { - return (kind >= 172 /* FirstTypeNode */ && kind <= 195 /* LastTypeNode */) + return (kind >= 173 /* FirstTypeNode */ && kind <= 196 /* LastTypeNode */) || kind === 128 /* AnyKeyword */ || kind === 152 /* UnknownKeyword */ || kind === 144 /* NumberKeyword */ @@ -18454,25 +18735,25 @@ var ts; || kind === 113 /* VoidKeyword */ || kind === 150 /* UndefinedKeyword */ || kind === 141 /* NeverKeyword */ - || kind === 223 /* ExpressionWithTypeArguments */ - || kind === 303 /* JSDocAllType */ - || kind === 304 /* JSDocUnknownType */ - || kind === 305 /* JSDocNullableType */ - || kind === 306 /* JSDocNonNullableType */ - || kind === 307 /* JSDocOptionalType */ - || kind === 308 /* JSDocFunctionType */ - || kind === 309 /* JSDocVariadicType */; + || kind === 224 /* ExpressionWithTypeArguments */ + || kind === 304 /* JSDocAllType */ + || kind === 305 /* JSDocUnknownType */ + || kind === 306 /* JSDocNullableType */ + || kind === 307 /* JSDocNonNullableType */ + || kind === 308 /* JSDocOptionalType */ + || kind === 309 /* JSDocFunctionType */ + || kind === 310 /* JSDocVariadicType */; } ts.isTypeNodeKind = isTypeNodeKind; function isAccessExpression(node) { - return node.kind === 201 /* PropertyAccessExpression */ || node.kind === 202 /* ElementAccessExpression */; + return node.kind === 202 /* PropertyAccessExpression */ || node.kind === 203 /* ElementAccessExpression */; } ts.isAccessExpression = isAccessExpression; function getNameOfAccessExpression(node) { - if (node.kind === 201 /* PropertyAccessExpression */) { + if (node.kind === 202 /* PropertyAccessExpression */) { return node.name; } - ts.Debug.assert(node.kind === 202 /* ElementAccessExpression */); + ts.Debug.assert(node.kind === 203 /* ElementAccessExpression */); return node.argumentExpression; } ts.getNameOfAccessExpression = getNameOfAccessExpression; @@ -18487,7 +18768,7 @@ var ts; } ts.isBundleFileTextLike = isBundleFileTextLike; function isNamedImportsOrExports(node) { - return node.kind === 264 /* NamedImports */ || node.kind === 268 /* NamedExports */; + return node.kind === 265 /* NamedImports */ || node.kind === 269 /* NamedExports */; } ts.isNamedImportsOrExports = isNamedImportsOrExports; function getLeftmostAccessExpression(expr) { @@ -18500,28 +18781,28 @@ var ts; function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: node = node.operand; continue; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: node = node.left; continue; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: node = node.condition; continue; - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: node = node.tag; continue; - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (stopAtCallExpressions) { return node; } // falls through - case 224 /* AsExpression */: - case 202 /* ElementAccessExpression */: - case 201 /* PropertyAccessExpression */: - case 225 /* NonNullExpression */: - case 336 /* PartiallyEmittedExpression */: + case 225 /* AsExpression */: + case 203 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 226 /* NonNullExpression */: + case 340 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -18540,7 +18821,7 @@ var ts; } function Type(checker, flags) { this.flags = flags; - if (ts.Debug.isDebugging || ts.tracing.isTracing()) { + if (ts.Debug.isDebugging || ts.tracing) { this.checker = checker; } } @@ -18884,6 +19165,10 @@ var ts; return !!(compilerOptions.declaration || compilerOptions.composite); } ts.getEmitDeclarations = getEmitDeclarations; + function shouldPreserveConstEnums(compilerOptions) { + return !!(compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + } + ts.shouldPreserveConstEnums = shouldPreserveConstEnums; function isIncrementalCompilation(options) { return !!(options.incremental || options.composite); } @@ -18896,6 +19181,10 @@ var ts; return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs; } ts.getAllowJSCompilerOption = getAllowJSCompilerOption; + function getUseDefineForClassFields(compilerOptions) { + return compilerOptions.useDefineForClassFields === undefined ? compilerOptions.target === 99 /* ESNext */ : compilerOptions.useDefineForClassFields; + } + ts.getUseDefineForClassFields = getUseDefineForClassFields; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { return oldOptions !== newOptions && ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); @@ -18917,7 +19206,7 @@ var ts; ts.getJSXTransformEnabled = getJSXTransformEnabled; function getJSXImplicitImportBase(compilerOptions, file) { var jsxImportSourcePragmas = file === null || file === void 0 ? void 0 : file.pragmas.get("jsximportsource"); - var jsxImportSourcePragma = ts.isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[0] : jsxImportSourcePragmas; + var jsxImportSourcePragma = ts.isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[jsxImportSourcePragmas.length - 1] : jsxImportSourcePragmas; return compilerOptions.jsx === 4 /* ReactJSX */ || compilerOptions.jsx === 5 /* ReactJSXDev */ || compilerOptions.jsxImportSource || @@ -18946,37 +19235,65 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createSymlinkCache() { + function createSymlinkCache(cwd, getCanonicalFileName) { var symlinkedDirectories; + var symlinkedDirectoriesByRealpath; var symlinkedFiles; return { getSymlinkedFiles: function () { return symlinkedFiles; }, getSymlinkedDirectories: function () { return symlinkedDirectories; }, + getSymlinkedDirectoriesByRealpath: function () { return symlinkedDirectoriesByRealpath; }, setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); }, - setSymlinkedDirectory: function (path, directory) { return (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(path, directory); }, + setSymlinkedDirectory: function (symlink, real) { + // Large, interconnected dependency graphs in pnpm will have a huge number of symlinks + // where both the realpath and the symlink path are inside node_modules/.pnpm. Since + // this path is never a candidate for a module specifier, we can ignore it entirely. + var symlinkPath = ts.toPath(symlink, cwd, getCanonicalFileName); + if (!containsIgnoredPath(symlinkPath)) { + symlinkPath = ts.ensureTrailingDirectorySeparator(symlinkPath); + if (real !== false && !(symlinkedDirectories === null || symlinkedDirectories === void 0 ? void 0 : symlinkedDirectories.has(symlinkPath))) { + (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = ts.createMultiMap())).add(ts.ensureTrailingDirectorySeparator(real.realPath), symlink); + } + (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); + } + }, + setSymlinkedDirectoryFromSymlinkedFile: function (symlink, real) { + this.setSymlinkedFile(ts.toPath(symlink, cwd, getCanonicalFileName), real); + var _a = guessDirectorySymlink(real, symlink, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _a[0], commonOriginal = _a[1]; + if (commonResolved && commonOriginal) { + this.setSymlinkedDirectory(commonOriginal, { + real: commonResolved, + realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName), + }); + } + }, }; } ts.createSymlinkCache = createSymlinkCache; function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { - var cache = createSymlinkCache(); - var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { - return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) { - return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + var cache = createSymlinkCache(cwd, getCanonicalFileName); + var symlinks = ts.flatMap(files, function (sf) { + var pairs = sf.resolvedModules && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedModules.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) ? [res.resolvedFileName, res.originalPath] : undefined; + })); + return ts.concatenate(pairs, sf.resolvedTypeReferenceDirectiveNames && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedTypeReferenceDirectiveNames.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) && res.resolvedFileName ? [res.resolvedFileName, res.originalPath] : undefined; }))); - })); + }); for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + cache.setSymlinkedFile(ts.toPath(originalPath, cwd, getCanonicalFileName), resolvedPath); var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1]; if (commonResolved && commonOriginal) { - cache.setSymlinkedDirectory(ts.toPath(commonOriginal, cwd, getCanonicalFileName), { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); + cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); } } return cache; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(a, cwd)); + var bParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(b, cwd)); var isDirectory = false; while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && @@ -19360,6 +19677,14 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + function numberOfDirectorySeparators(str) { + var match = str.match(/\//g); + return match ? match.length : 0; + } + function compareNumberOfDirectorySeparators(path1, path2) { + return ts.compareValues(numberOfDirectorySeparators(path1), numberOfDirectorySeparators(path2)); + } + ts.compareNumberOfDirectorySeparators = compareNumberOfDirectorySeparators; /** * Extension boundaries by priority. Lower numbers indicate higher priorities, and are * aligned to the offset of the highest priority extension in the @@ -19656,21 +19981,21 @@ var ts; } ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite; function typeOnlyDeclarationIsExport(typeOnlyDeclaration) { - return typeOnlyDeclaration.kind === 270 /* ExportSpecifier */; + return typeOnlyDeclaration.kind === 271 /* ExportSpecifier */; } ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport; function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) { - while (node.kind === 78 /* Identifier */ || node.kind === 201 /* PropertyAccessExpression */) { + while (node.kind === 78 /* Identifier */ || node.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - if (node.kind !== 158 /* ComputedPropertyName */) { + if (node.kind !== 159 /* ComputedPropertyName */) { return false; } if (hasSyntacticModifier(node.parent, 128 /* Abstract */)) { return true; } var containerKind = node.parent.parent.kind; - return containerKind === 253 /* InterfaceDeclaration */ || containerKind === 177 /* TypeLiteral */; + return containerKind === 254 /* InterfaceDeclaration */ || containerKind === 178 /* TypeLiteral */; } /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */ function isIdentifierInNonEmittingHeritageClause(node) { @@ -19678,16 +20003,16 @@ var ts; return false; var heritageClause = ts.findAncestor(node.parent, function (parent) { switch (parent.kind) { - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: return true; - case 201 /* PropertyAccessExpression */: - case 223 /* ExpressionWithTypeArguments */: + case 202 /* PropertyAccessExpression */: + case 224 /* ExpressionWithTypeArguments */: return false; default: return "quit"; } }); - return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 116 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 253 /* InterfaceDeclaration */; + return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 116 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 254 /* InterfaceDeclaration */; } function isIdentifierTypeReference(node) { return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName); @@ -19840,6 +20165,76 @@ var ts; } } ts.expressionResultIsUnused = expressionResultIsUnused; + function containsIgnoredPath(path) { + return ts.some(ts.ignoredPaths, function (p) { return ts.stringContains(path, p); }); + } + ts.containsIgnoredPath = containsIgnoredPath; + function getContainingNodeArray(node) { + if (!node.parent) + return undefined; + switch (node.kind) { + case 160 /* TypeParameter */: + var parent_1 = node.parent; + return parent_1.kind === 186 /* InferType */ ? undefined : parent_1.typeParameters; + case 161 /* Parameter */: + return node.parent.parameters; + case 195 /* TemplateLiteralTypeSpan */: + return node.parent.templateSpans; + case 229 /* TemplateSpan */: + return node.parent.templateSpans; + case 162 /* Decorator */: + return node.parent.decorators; + case 287 /* HeritageClause */: + return node.parent.heritageClauses; + } + var parent = node.parent; + if (ts.isJSDocTag(node)) { + return ts.isJSDocTypeLiteral(node.parent) ? undefined : node.parent.tags; + } + switch (parent.kind) { + case 178 /* TypeLiteral */: + case 254 /* InterfaceDeclaration */: + return ts.isTypeElement(node) ? parent.members : undefined; + case 183 /* UnionType */: + case 184 /* IntersectionType */: + return parent.types; + case 180 /* TupleType */: + case 200 /* ArrayLiteralExpression */: + case 341 /* CommaListExpression */: + case 265 /* NamedImports */: + case 269 /* NamedExports */: + return parent.elements; + case 201 /* ObjectLiteralExpression */: + case 282 /* JsxAttributes */: + return parent.properties; + case 204 /* CallExpression */: + case 205 /* NewExpression */: + return ts.isTypeNode(node) ? parent.typeArguments : + parent.expression === node ? undefined : + parent.arguments; + case 274 /* JsxElement */: + case 278 /* JsxFragment */: + return ts.isJsxChild(node) ? parent.children : undefined; + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + return ts.isTypeNode(node) ? parent.typeArguments : undefined; + case 231 /* Block */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 258 /* ModuleBlock */: + return parent.statements; + case 259 /* CaseBlock */: + return parent.clauses; + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + return ts.isClassElement(node) ? parent.members : undefined; + case 256 /* EnumDeclaration */: + return ts.isEnumMember(node) ? parent.members : undefined; + case 298 /* SourceFile */: + return parent.statements; + } + } + ts.getContainingNodeArray = getContainingNodeArray; })(ts || (ts = {})); /* @internal */ var ts; @@ -19884,7 +20279,11 @@ var ts; var ts; (function (ts) { function createParenthesizerRules(factory) { + var binaryLeftOperandParenthesizerCache; + var binaryRightOperandParenthesizerCache; return { + getParenthesizeLeftSideOfBinaryForOperator: getParenthesizeLeftSideOfBinaryForOperator, + getParenthesizeRightSideOfBinaryForOperator: getParenthesizeRightSideOfBinaryForOperator, parenthesizeLeftSideOfBinary: parenthesizeLeftSideOfBinary, parenthesizeRightSideOfBinary: parenthesizeRightSideOfBinary, parenthesizeExpressionOfComputedPropertyName: parenthesizeExpressionOfComputedPropertyName, @@ -19905,6 +20304,24 @@ var ts; parenthesizeConstituentTypesOfUnionOrIntersectionType: parenthesizeConstituentTypesOfUnionOrIntersectionType, parenthesizeTypeArguments: parenthesizeTypeArguments, }; + function getParenthesizeLeftSideOfBinaryForOperator(operatorKind) { + binaryLeftOperandParenthesizerCache || (binaryLeftOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeLeftSideOfBinary(operatorKind, node); }; + binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } + function getParenthesizeRightSideOfBinaryForOperator(operatorKind) { + binaryRightOperandParenthesizerCache || (binaryRightOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeRightSideOfBinary(operatorKind, /*leftSide*/ undefined, node); }; + binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } /** * Determines whether the operand to a BinaryExpression needs to be parenthesized. * @@ -19931,10 +20348,10 @@ var ts; // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - var binaryOperatorPrecedence = ts.getOperatorPrecedence(216 /* BinaryExpression */, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(216 /* BinaryExpression */, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(217 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(217 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); - if (!isLeftSideOfBinary && operand.kind === 209 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */) { + if (!isLeftSideOfBinary && operand.kind === 210 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */) { // We need to parenthesize arrow functions on the right side to avoid it being // parsed as parenthesized expression: `a && (() => {})` return true; @@ -19946,7 +20363,7 @@ var ts; // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ - && operand.kind === 219 /* YieldExpression */) { + && operand.kind === 220 /* YieldExpression */) { return false; } return true; @@ -20034,7 +20451,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) { + if (node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -20060,7 +20477,7 @@ var ts; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. - if (skipped.kind === 207 /* ParenthesizedExpression */) { + if (skipped.kind === 208 /* ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -20077,7 +20494,7 @@ var ts; return ts.isCommaSequence(expression) ? factory.createParenthesizedExpression(expression) : expression; } function parenthesizeConditionOfConditionalExpression(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(217 /* ConditionalExpression */, 57 /* QuestionToken */); + var conditionalPrecedence = ts.getOperatorPrecedence(218 /* ConditionalExpression */, 57 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) { @@ -20110,8 +20527,8 @@ var ts; var needsParens = ts.isCommaSequence(check); if (!needsParens) { switch (ts.getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: needsParens = true; } } @@ -20124,9 +20541,9 @@ var ts; function parenthesizeExpressionOfNew(expression) { var leftmostExpr = ts.getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); switch (leftmostExpr.kind) { - case 203 /* CallExpression */: + case 204 /* CallExpression */: return factory.createParenthesizedExpression(expression); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return !leftmostExpr.arguments ? factory.createParenthesizedExpression(expression) : expression; // TODO(rbuckton): Verify this assertion holds @@ -20146,7 +20563,7 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 204 /* NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 205 /* NewExpression */ || emittedExpression.arguments)) { // TODO(rbuckton): Verify whether this assertion holds. return expression; } @@ -20168,7 +20585,7 @@ var ts; function parenthesizeExpressionForDisallowedComma(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(216 /* BinaryExpression */, 27 /* CommaToken */); + var commaPrecedence = ts.getOperatorPrecedence(217 /* BinaryExpression */, 27 /* CommaToken */); // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(factory.createParenthesizedExpression(expression), expression); } @@ -20177,44 +20594,44 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 208 /* FunctionExpression */ || kind === 209 /* ArrowFunction */) { + if (kind === 209 /* FunctionExpression */ || kind === 210 /* ArrowFunction */) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. var updated = factory.updateCallExpression(emittedExpression, ts.setTextRange(factory.createParenthesizedExpression(callee), callee), emittedExpression.typeArguments, emittedExpression.arguments); return factory.restoreOuterExpressions(expression, updated, 8 /* PartiallyEmittedExpressions */); } } var leftmostExpressionKind = ts.getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; - if (leftmostExpressionKind === 200 /* ObjectLiteralExpression */ || leftmostExpressionKind === 208 /* FunctionExpression */) { + if (leftmostExpressionKind === 201 /* ObjectLiteralExpression */ || leftmostExpressionKind === 209 /* FunctionExpression */) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return ts.setTextRange(factory.createParenthesizedExpression(expression), expression); } return expression; } function parenthesizeConciseBodyOfArrowFunction(body) { - if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 200 /* ObjectLiteralExpression */)) { + if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 201 /* ObjectLiteralExpression */)) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return ts.setTextRange(factory.createParenthesizedExpression(body), body); } return body; } function parenthesizeMemberOfConditionalType(member) { - return member.kind === 184 /* ConditionalType */ ? factory.createParenthesizedType(member) : member; + return member.kind === 185 /* ConditionalType */ ? factory.createParenthesizedType(member) : member; } function parenthesizeMemberOfElementType(member) { switch (member.kind) { - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return factory.createParenthesizedType(member); } return parenthesizeMemberOfConditionalType(member); } function parenthesizeElementTypeOfArrayType(member) { switch (member.kind) { - case 176 /* TypeQuery */: - case 188 /* TypeOperator */: - case 185 /* InferType */: + case 177 /* TypeQuery */: + case 189 /* TypeOperator */: + case 186 /* InferType */: return factory.createParenthesizedType(member); } return parenthesizeMemberOfElementType(member); @@ -20233,6 +20650,8 @@ var ts; } ts.createParenthesizerRules = createParenthesizerRules; ts.nullParenthesizerRules = { + getParenthesizeLeftSideOfBinaryForOperator: function (_) { return ts.identity; }, + getParenthesizeRightSideOfBinaryForOperator: function (_) { return ts.identity; }, parenthesizeLeftSideOfBinary: function (_binaryOperator, leftSide) { return leftSide; }, parenthesizeRightSideOfBinary: function (_binaryOperator, _leftSide, rightSide) { return rightSide; }, parenthesizeExpressionOfComputedPropertyName: ts.identity, @@ -20318,11 +20737,11 @@ var ts; } function convertToAssignmentPattern(node) { switch (node.kind) { - case 197 /* ArrayBindingPattern */: - case 199 /* ArrayLiteralExpression */: + case 198 /* ArrayBindingPattern */: + case 200 /* ArrayLiteralExpression */: return convertToArrayAssignmentPattern(node); - case 196 /* ObjectBindingPattern */: - case 200 /* ObjectLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 201 /* ObjectLiteralExpression */: return convertToObjectAssignmentPattern(node); } } @@ -20663,18 +21082,18 @@ var ts; createExternalModuleReference: createExternalModuleReference, updateExternalModuleReference: updateExternalModuleReference, // lazily load factory members for JSDoc types with similar structure - get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(303 /* JSDocAllType */); }, - get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(304 /* JSDocUnknownType */); }, - get createJSDocNonNullableType() { return getJSDocUnaryTypeCreateFunction(306 /* JSDocNonNullableType */); }, - get updateJSDocNonNullableType() { return getJSDocUnaryTypeUpdateFunction(306 /* JSDocNonNullableType */); }, - get createJSDocNullableType() { return getJSDocUnaryTypeCreateFunction(305 /* JSDocNullableType */); }, - get updateJSDocNullableType() { return getJSDocUnaryTypeUpdateFunction(305 /* JSDocNullableType */); }, - get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(307 /* JSDocOptionalType */); }, - get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(307 /* JSDocOptionalType */); }, - get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(309 /* JSDocVariadicType */); }, - get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(309 /* JSDocVariadicType */); }, - get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(310 /* JSDocNamepathType */); }, - get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(310 /* JSDocNamepathType */); }, + get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(304 /* JSDocAllType */); }, + get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(305 /* JSDocUnknownType */); }, + get createJSDocNonNullableType() { return getJSDocUnaryTypeCreateFunction(307 /* JSDocNonNullableType */); }, + get updateJSDocNonNullableType() { return getJSDocUnaryTypeUpdateFunction(307 /* JSDocNonNullableType */); }, + get createJSDocNullableType() { return getJSDocUnaryTypeCreateFunction(306 /* JSDocNullableType */); }, + get updateJSDocNullableType() { return getJSDocUnaryTypeUpdateFunction(306 /* JSDocNullableType */); }, + get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(308 /* JSDocOptionalType */); }, + get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(308 /* JSDocOptionalType */); }, + get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(310 /* JSDocVariadicType */); }, + get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(310 /* JSDocVariadicType */); }, + get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(311 /* JSDocNamepathType */); }, + get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(311 /* JSDocNamepathType */); }, createJSDocFunctionType: createJSDocFunctionType, updateJSDocFunctionType: updateJSDocFunctionType, createJSDocTypeLiteral: createJSDocTypeLiteral, @@ -20701,31 +21120,37 @@ var ts; updateJSDocSeeTag: updateJSDocSeeTag, createJSDocNameReference: createJSDocNameReference, updateJSDocNameReference: updateJSDocNameReference, + createJSDocLink: createJSDocLink, + updateJSDocLink: updateJSDocLink, // lazily load factory members for JSDoc tags with similar structure - get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(329 /* JSDocTypeTag */); }, - get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(329 /* JSDocTypeTag */); }, - get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(327 /* JSDocReturnTag */); }, - get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(327 /* JSDocReturnTag */); }, - get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(328 /* JSDocThisTag */); }, - get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(328 /* JSDocThisTag */); }, - get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(325 /* JSDocEnumTag */); }, - get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(325 /* JSDocEnumTag */); }, - get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(317 /* JSDocAuthorTag */); }, - get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(317 /* JSDocAuthorTag */); }, - get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(319 /* JSDocClassTag */); }, - get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(319 /* JSDocClassTag */); }, - get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(320 /* JSDocPublicTag */); }, - get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(320 /* JSDocPublicTag */); }, - get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(321 /* JSDocPrivateTag */); }, - get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(321 /* JSDocPrivateTag */); }, - get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(322 /* JSDocProtectedTag */); }, - get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(322 /* JSDocProtectedTag */); }, - get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(323 /* JSDocReadonlyTag */); }, - get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(323 /* JSDocReadonlyTag */); }, - get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(318 /* JSDocDeprecatedTag */); }, - get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(318 /* JSDocDeprecatedTag */); }, + get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(333 /* JSDocTypeTag */); }, + get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(333 /* JSDocTypeTag */); }, + get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(331 /* JSDocReturnTag */); }, + get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(331 /* JSDocReturnTag */); }, + get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(332 /* JSDocThisTag */); }, + get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(332 /* JSDocThisTag */); }, + get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(329 /* JSDocEnumTag */); }, + get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(329 /* JSDocEnumTag */); }, + get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(320 /* JSDocAuthorTag */); }, + get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(320 /* JSDocAuthorTag */); }, + get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(322 /* JSDocClassTag */); }, + get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(322 /* JSDocClassTag */); }, + get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(323 /* JSDocPublicTag */); }, + get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(323 /* JSDocPublicTag */); }, + get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(324 /* JSDocPrivateTag */); }, + get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(324 /* JSDocPrivateTag */); }, + get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(325 /* JSDocProtectedTag */); }, + get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(325 /* JSDocProtectedTag */); }, + get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(326 /* JSDocReadonlyTag */); }, + get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(326 /* JSDocReadonlyTag */); }, + get createJSDocOverrideTag() { return getJSDocSimpleTagCreateFunction(327 /* JSDocOverrideTag */); }, + get updateJSDocOverrideTag() { return getJSDocSimpleTagUpdateFunction(327 /* JSDocOverrideTag */); }, + get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(321 /* JSDocDeprecatedTag */); }, + get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(321 /* JSDocDeprecatedTag */); }, createJSDocUnknownTag: createJSDocUnknownTag, updateJSDocUnknownTag: updateJSDocUnknownTag, + createJSDocText: createJSDocText, + updateJSDocText: updateJSDocText, createJSDocComment: createJSDocComment, updateJSDocComment: updateJSDocComment, createJsxElement: createJsxElement, @@ -20909,11 +21334,11 @@ var ts; // don't propagate child flags. if (name) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 163 /* PropertyDeclaration */: - case 288 /* PropertyAssignment */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 289 /* PropertyAssignment */: if (ts.isIdentifier(name)) { node.transformFlags |= propagateIdentifierNameFlags(name); break; @@ -20954,7 +21379,7 @@ var ts; function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) { var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type); node.body = body; - node.transformFlags |= propagateChildFlags(node.body) & ~8388608 /* ContainsPossibleTopLevelAwait */; + node.transformFlags |= propagateChildFlags(node.body) & ~16777216 /* ContainsPossibleTopLevelAwait */; if (!body) node.transformFlags |= 1 /* ContainsTypeScript */; return node; @@ -21007,7 +21432,7 @@ var ts; var node = createBaseLiteral(8 /* NumericLiteral */, typeof value === "number" ? value + "" : value); node.numericLiteralFlags = numericLiteralFlags; if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -21026,7 +21451,7 @@ var ts; var node = createBaseStringLiteral(text, isSingleQuote); node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; if (hasExtendedUnicodeEscape) - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -21082,7 +21507,7 @@ var ts; node.typeArguments = createNodeArray(typeArguments); } if (node.originalKeywordKind === 130 /* AwaitKeyword */) { - node.transformFlags |= 8388608 /* ContainsPossibleTopLevelAwait */; + node.transformFlags |= 16777216 /* ContainsPossibleTopLevelAwait */; } return node; } @@ -21105,8 +21530,11 @@ var ts; } /** Create a unique temporary variable for use in a loop. */ // @api - function createLoopVariable() { - return createBaseGeneratedIdentifier("", 2 /* Loop */); + function createLoopVariable(reservedInNestedScopes) { + var flags = 2 /* Loop */; + if (reservedInNestedScopes) + flags |= 8 /* ReservedInNestedScopes */; + return createBaseGeneratedIdentifier("", flags); } /** Create a unique name based on the supplied text. */ // @api @@ -21131,7 +21559,7 @@ var ts; ts.Debug.fail("First character of private identifier must be #: " + text); var node = baseFactory.createBasePrivateIdentifierNode(79 /* PrivateIdentifier */); node.escapedText = ts.escapeLeadingUnderscores(text); - node.transformFlags |= 4194304 /* ContainsClassFields */; + node.transformFlags |= 8388608 /* ContainsClassFields */; return node; } // @@ -21141,7 +21569,7 @@ var ts; return baseFactory.createBaseTokenNode(kind); } function createToken(token) { - ts.Debug.assert(token >= 0 /* FirstToken */ && token <= 156 /* LastToken */, "Invalid token"); + ts.Debug.assert(token >= 0 /* FirstToken */ && token <= 157 /* LastToken */, "Invalid token"); ts.Debug.assert(token <= 14 /* FirstTemplateToken */ || token >= 17 /* LastTemplateToken */, "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals."); ts.Debug.assert(token <= 8 /* FirstLiteralToken */ || token >= 14 /* LastLiteralToken */, "Invalid token. Use 'createLiteralLikeNode' to create literals."); ts.Debug.assert(token !== 78 /* Identifier */, "Invalid token. Use 'createIdentifier' to create identifiers"); @@ -21151,8 +21579,8 @@ var ts; case 129 /* AsyncKeyword */: // 'async' modifier is ES2017 (async functions) or ES2018 (async generators) transformFlags = - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */; break; case 122 /* PublicKeyword */: case 120 /* PrivateKeyword */: @@ -21166,6 +21594,7 @@ var ts; case 155 /* BigIntKeyword */: case 141 /* NeverKeyword */: case 145 /* ObjectKeyword */: + case 156 /* OverrideKeyword */: case 147 /* StringKeyword */: case 131 /* BooleanKeyword */: case 148 /* SymbolKeyword */: @@ -21176,11 +21605,11 @@ var ts; break; case 123 /* StaticKeyword */: case 105 /* SuperKeyword */: - transformFlags = 256 /* ContainsES2015 */; + transformFlags = 512 /* ContainsES2015 */; break; case 107 /* ThisKeyword */: // 'this' indicates a lexical 'this' - transformFlags = 4096 /* ContainsLexicalThis */; + transformFlags = 8192 /* ContainsLexicalThis */; break; } if (transformFlags) { @@ -21248,6 +21677,9 @@ var ts; if (flags & 32 /* Static */) { result.push(createModifier(123 /* StaticKeyword */)); } + if (flags & 16384 /* Override */) { + result.push(createModifier(156 /* OverrideKeyword */)); + } if (flags & 64 /* Readonly */) { result.push(createModifier(142 /* ReadonlyKeyword */)); } @@ -21261,7 +21693,7 @@ var ts; // // @api function createQualifiedName(left, right) { - var node = createBaseNode(157 /* QualifiedName */); + var node = createBaseNode(158 /* QualifiedName */); node.left = left; node.right = asName(right); node.transformFlags |= @@ -21278,12 +21710,12 @@ var ts; } // @api function createComputedPropertyName(expression) { - var node = createBaseNode(158 /* ComputedPropertyName */); + var node = createBaseNode(159 /* ComputedPropertyName */); node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 256 /* ContainsES2015 */ | - 32768 /* ContainsComputedPropertyName */; + 512 /* ContainsES2015 */ | + 65536 /* ContainsComputedPropertyName */; return node; } // @api @@ -21297,7 +21729,7 @@ var ts; // // @api function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createBaseNamedDeclaration(159 /* TypeParameter */, + var node = createBaseNamedDeclaration(160 /* TypeParameter */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.constraint = constraint; @@ -21315,7 +21747,7 @@ var ts; } // @api function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(160 /* Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); + var node = createBaseVariableLikeDeclaration(161 /* Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.dotDotDotToken = dotDotDotToken; node.questionToken = questionToken; if (ts.isThisIdentifier(node.name)) { @@ -21327,10 +21759,10 @@ var ts; propagateChildFlags(node.questionToken); if (questionToken) node.transformFlags |= 1 /* ContainsTypeScript */; - if (ts.modifiersToFlags(node.modifiers) & 92 /* ParameterPropertyModifier */) - node.transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */; + if (ts.modifiersToFlags(node.modifiers) & 16476 /* ParameterPropertyModifier */) + node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; if (initializer || dotDotDotToken) - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; } return node; } @@ -21348,12 +21780,12 @@ var ts; } // @api function createDecorator(expression) { - var node = createBaseNode(161 /* Decorator */); + var node = createBaseNode(162 /* Decorator */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */ | - 2048 /* ContainsTypeScriptClassSyntax */; + 4096 /* ContainsTypeScriptClassSyntax */; return node; } // @api @@ -21367,7 +21799,7 @@ var ts; // // @api function createPropertySignature(modifiers, name, questionToken, type) { - var node = createBaseNamedDeclaration(162 /* PropertySignature */, + var node = createBaseNamedDeclaration(163 /* PropertySignature */, /*decorators*/ undefined, modifiers, name); node.type = type; node.questionToken = questionToken; @@ -21385,15 +21817,15 @@ var ts; } // @api function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(163 /* PropertyDeclaration */, decorators, modifiers, name, type, initializer); + var node = createBaseVariableLikeDeclaration(164 /* PropertyDeclaration */, decorators, modifiers, name, type, initializer); node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.transformFlags |= propagateChildFlags(node.questionToken) | propagateChildFlags(node.exclamationToken) | - 4194304 /* ContainsClassFields */; + 8388608 /* ContainsClassFields */; if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) { - node.transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */; + node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) { node.transformFlags |= 1 /* ContainsTypeScript */; @@ -21414,7 +21846,7 @@ var ts; } // @api function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(164 /* MethodSignature */, + var node = createBaseSignatureDeclaration(165 /* MethodSignature */, /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type); node.questionToken = questionToken; node.transformFlags = 1 /* ContainsTypeScript */; @@ -21433,26 +21865,26 @@ var ts; } // @api function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(165 /* MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(166 /* MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.questionToken = questionToken; node.transformFlags |= propagateChildFlags(node.asteriskToken) | propagateChildFlags(node.questionToken) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (questionToken) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (asteriskToken) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } else { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } } else if (asteriskToken) { - node.transformFlags |= 512 /* ContainsGenerator */; + node.transformFlags |= 1024 /* ContainsGenerator */; } return node; } @@ -21472,11 +21904,11 @@ var ts; } // @api function createConstructorDeclaration(decorators, modifiers, parameters, body) { - var node = createBaseFunctionLikeDeclaration(166 /* Constructor */, decorators, modifiers, + var node = createBaseFunctionLikeDeclaration(167 /* Constructor */, decorators, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -21490,7 +21922,7 @@ var ts; } // @api function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) { - return createBaseFunctionLikeDeclaration(167 /* GetAccessor */, decorators, modifiers, name, + return createBaseFunctionLikeDeclaration(168 /* GetAccessor */, decorators, modifiers, name, /*typeParameters*/ undefined, parameters, type, body); } // @api @@ -21506,7 +21938,7 @@ var ts; } // @api function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) { - return createBaseFunctionLikeDeclaration(168 /* SetAccessor */, decorators, modifiers, name, + return createBaseFunctionLikeDeclaration(169 /* SetAccessor */, decorators, modifiers, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); } @@ -21522,7 +21954,7 @@ var ts; } // @api function createCallSignature(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(169 /* CallSignature */, + var node = createBaseSignatureDeclaration(170 /* CallSignature */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); @@ -21539,7 +21971,7 @@ var ts; } // @api function createConstructSignature(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(170 /* ConstructSignature */, + var node = createBaseSignatureDeclaration(171 /* ConstructSignature */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); @@ -21556,7 +21988,7 @@ var ts; } // @api function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createBaseSignatureDeclaration(171 /* IndexSignature */, decorators, modifiers, + var node = createBaseSignatureDeclaration(172 /* IndexSignature */, decorators, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21573,7 +22005,7 @@ var ts; } // @api function createTemplateLiteralTypeSpan(type, literal) { - var node = createBaseNode(194 /* TemplateLiteralTypeSpan */); + var node = createBaseNode(195 /* TemplateLiteralTypeSpan */); node.type = type; node.literal = literal; node.transformFlags = 1 /* ContainsTypeScript */; @@ -21595,7 +22027,7 @@ var ts; } // @api function createTypePredicateNode(assertsModifier, parameterName, type) { - var node = createBaseNode(172 /* TypePredicate */); + var node = createBaseNode(173 /* TypePredicate */); node.assertsModifier = assertsModifier; node.parameterName = asName(parameterName); node.type = type; @@ -21612,7 +22044,7 @@ var ts; } // @api function createTypeReferenceNode(typeName, typeArguments) { - var node = createBaseNode(173 /* TypeReference */); + var node = createBaseNode(174 /* TypeReference */); node.typeName = asName(typeName); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(createNodeArray(typeArguments)); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21627,7 +22059,7 @@ var ts; } // @api function createFunctionTypeNode(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(174 /* FunctionType */, + var node = createBaseSignatureDeclaration(175 /* FunctionType */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); @@ -21653,7 +22085,7 @@ var ts; ts.Debug.fail("Incorrect number of arguments specified."); } function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(175 /* ConstructorType */, + var node = createBaseSignatureDeclaration(176 /* ConstructorType */, /*decorators*/ undefined, modifiers, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21687,7 +22119,7 @@ var ts; } // @api function createTypeQueryNode(exprName) { - var node = createBaseNode(176 /* TypeQuery */); + var node = createBaseNode(177 /* TypeQuery */); node.exprName = exprName; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21700,7 +22132,7 @@ var ts; } // @api function createTypeLiteralNode(members) { - var node = createBaseNode(177 /* TypeLiteral */); + var node = createBaseNode(178 /* TypeLiteral */); node.members = createNodeArray(members); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21713,7 +22145,7 @@ var ts; } // @api function createArrayTypeNode(elementType) { - var node = createBaseNode(178 /* ArrayType */); + var node = createBaseNode(179 /* ArrayType */); node.elementType = parenthesizerRules().parenthesizeElementTypeOfArrayType(elementType); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21726,7 +22158,7 @@ var ts; } // @api function createTupleTypeNode(elements) { - var node = createBaseNode(179 /* TupleType */); + var node = createBaseNode(180 /* TupleType */); node.elements = createNodeArray(elements); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21739,7 +22171,7 @@ var ts; } // @api function createNamedTupleMember(dotDotDotToken, name, questionToken, type) { - var node = createBaseNode(192 /* NamedTupleMember */); + var node = createBaseNode(193 /* NamedTupleMember */); node.dotDotDotToken = dotDotDotToken; node.name = name; node.questionToken = questionToken; @@ -21758,7 +22190,7 @@ var ts; } // @api function createOptionalTypeNode(type) { - var node = createBaseNode(180 /* OptionalType */); + var node = createBaseNode(181 /* OptionalType */); node.type = parenthesizerRules().parenthesizeElementTypeOfArrayType(type); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21771,7 +22203,7 @@ var ts; } // @api function createRestTypeNode(type) { - var node = createBaseNode(181 /* RestType */); + var node = createBaseNode(182 /* RestType */); node.type = type; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21795,7 +22227,7 @@ var ts; } // @api function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(182 /* UnionType */, types); + return createUnionOrIntersectionTypeNode(183 /* UnionType */, types); } // @api function updateUnionTypeNode(node, types) { @@ -21803,7 +22235,7 @@ var ts; } // @api function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(183 /* IntersectionType */, types); + return createUnionOrIntersectionTypeNode(184 /* IntersectionType */, types); } // @api function updateIntersectionTypeNode(node, types) { @@ -21811,7 +22243,7 @@ var ts; } // @api function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { - var node = createBaseNode(184 /* ConditionalType */); + var node = createBaseNode(185 /* ConditionalType */); node.checkType = parenthesizerRules().parenthesizeMemberOfConditionalType(checkType); node.extendsType = parenthesizerRules().parenthesizeMemberOfConditionalType(extendsType); node.trueType = trueType; @@ -21830,7 +22262,7 @@ var ts; } // @api function createInferTypeNode(typeParameter) { - var node = createBaseNode(185 /* InferType */); + var node = createBaseNode(186 /* InferType */); node.typeParameter = typeParameter; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21843,7 +22275,7 @@ var ts; } // @api function createTemplateLiteralType(head, templateSpans) { - var node = createBaseNode(193 /* TemplateLiteralType */); + var node = createBaseNode(194 /* TemplateLiteralType */); node.head = head; node.templateSpans = createNodeArray(templateSpans); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21859,7 +22291,7 @@ var ts; // @api function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { if (isTypeOf === void 0) { isTypeOf = false; } - var node = createBaseNode(195 /* ImportType */); + var node = createBaseNode(196 /* ImportType */); node.argument = argument; node.qualifier = qualifier; node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); @@ -21879,7 +22311,7 @@ var ts; } // @api function createParenthesizedType(type) { - var node = createBaseNode(186 /* ParenthesizedType */); + var node = createBaseNode(187 /* ParenthesizedType */); node.type = type; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21892,13 +22324,13 @@ var ts; } // @api function createThisTypeNode() { - var node = createBaseNode(187 /* ThisType */); + var node = createBaseNode(188 /* ThisType */); node.transformFlags = 1 /* ContainsTypeScript */; return node; } // @api function createTypeOperatorNode(operator, type) { - var node = createBaseNode(188 /* TypeOperator */); + var node = createBaseNode(189 /* TypeOperator */); node.operator = operator; node.type = parenthesizerRules().parenthesizeMemberOfElementType(type); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21912,7 +22344,7 @@ var ts; } // @api function createIndexedAccessTypeNode(objectType, indexType) { - var node = createBaseNode(189 /* IndexedAccessType */); + var node = createBaseNode(190 /* IndexedAccessType */); node.objectType = parenthesizerRules().parenthesizeMemberOfElementType(objectType); node.indexType = indexType; node.transformFlags = 1 /* ContainsTypeScript */; @@ -21927,7 +22359,7 @@ var ts; } // @api function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type) { - var node = createBaseNode(190 /* MappedType */); + var node = createBaseNode(191 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.nameType = nameType; @@ -21948,7 +22380,7 @@ var ts; } // @api function createLiteralTypeNode(literal) { - var node = createBaseNode(191 /* LiteralType */); + var node = createBaseNode(192 /* LiteralType */); node.literal = literal; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21964,16 +22396,16 @@ var ts; // // @api function createObjectBindingPattern(elements) { - var node = createBaseNode(196 /* ObjectBindingPattern */); + var node = createBaseNode(197 /* ObjectBindingPattern */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | - 256 /* ContainsES2015 */ | - 131072 /* ContainsBindingPattern */; - if (node.transformFlags & 8192 /* ContainsRestOrSpread */) { + 512 /* ContainsES2015 */ | + 262144 /* ContainsBindingPattern */; + if (node.transformFlags & 16384 /* ContainsRestOrSpread */) { node.transformFlags |= - 32 /* ContainsES2018 */ | - 16384 /* ContainsObjectRestOrSpread */; + 64 /* ContainsES2018 */ | + 32768 /* ContainsObjectRestOrSpread */; } return node; } @@ -21985,12 +22417,12 @@ var ts; } // @api function createArrayBindingPattern(elements) { - var node = createBaseNode(197 /* ArrayBindingPattern */); + var node = createBaseNode(198 /* ArrayBindingPattern */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | - 256 /* ContainsES2015 */ | - 131072 /* ContainsBindingPattern */; + 512 /* ContainsES2015 */ | + 262144 /* ContainsBindingPattern */; return node; } // @api @@ -22001,21 +22433,21 @@ var ts; } // @api function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createBaseBindingLikeDeclaration(198 /* BindingElement */, + var node = createBaseBindingLikeDeclaration(199 /* BindingElement */, /*decorators*/ undefined, - /*modifiers*/ undefined, name, initializer); + /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; node.transformFlags |= propagateChildFlags(node.dotDotDotToken) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (node.propertyName) { node.transformFlags |= ts.isIdentifier(node.propertyName) ? propagateIdentifierNameFlags(node.propertyName) : propagateChildFlags(node.propertyName); } if (dotDotDotToken) - node.transformFlags |= 8192 /* ContainsRestOrSpread */; + node.transformFlags |= 16384 /* ContainsRestOrSpread */; return node; } // @api @@ -22037,7 +22469,7 @@ var ts; } // @api function createArrayLiteralExpression(elements, multiLine) { - var node = createBaseExpression(199 /* ArrayLiteralExpression */); + var node = createBaseExpression(200 /* ArrayLiteralExpression */); node.elements = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(elements)); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.elements); @@ -22051,7 +22483,7 @@ var ts; } // @api function createObjectLiteralExpression(properties, multiLine) { - var node = createBaseExpression(200 /* ObjectLiteralExpression */); + var node = createBaseExpression(201 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.properties); @@ -22065,7 +22497,7 @@ var ts; } // @api function createPropertyAccessExpression(expression, name) { - var node = createBaseExpression(201 /* PropertyAccessExpression */); + var node = createBaseExpression(202 /* PropertyAccessExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.name = asName(name); node.transformFlags = @@ -22077,8 +22509,8 @@ var ts; // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators node.transformFlags |= - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */; } return node; } @@ -22094,13 +22526,13 @@ var ts; } // @api function createPropertyAccessChain(expression, questionDotToken, name) { - var node = createBaseExpression(201 /* PropertyAccessExpression */); + var node = createBaseExpression(202 /* PropertyAccessExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.questionDotToken = questionDotToken; node.name = asName(name); node.transformFlags |= - 8 /* ContainsES2020 */ | + 16 /* ContainsES2020 */ | propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | (ts.isIdentifier(node.name) ? @@ -22121,7 +22553,7 @@ var ts; } // @api function createElementAccessExpression(expression, index) { - var node = createBaseExpression(202 /* ElementAccessExpression */); + var node = createBaseExpression(203 /* ElementAccessExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.argumentExpression = asExpression(index); node.transformFlags |= @@ -22131,8 +22563,8 @@ var ts; // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators node.transformFlags |= - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */; } return node; } @@ -22148,7 +22580,7 @@ var ts; } // @api function createElementAccessChain(expression, questionDotToken, index) { - var node = createBaseExpression(202 /* ElementAccessExpression */); + var node = createBaseExpression(203 /* ElementAccessExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.questionDotToken = questionDotToken; @@ -22157,7 +22589,7 @@ var ts; propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | propagateChildFlags(node.argumentExpression) | - 8 /* ContainsES2020 */; + 16 /* ContainsES2020 */; return node; } // @api @@ -22173,7 +22605,7 @@ var ts; } // @api function createCallExpression(expression, typeArguments, argumentsArray) { - var node = createBaseExpression(203 /* CallExpression */); + var node = createBaseExpression(204 /* CallExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); @@ -22185,10 +22617,10 @@ var ts; node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.isImportKeyword(node.expression)) { - node.transformFlags |= 2097152 /* ContainsDynamicImport */; + node.transformFlags |= 4194304 /* ContainsDynamicImport */; } else if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 4096 /* ContainsLexicalThis */; + node.transformFlags |= 8192 /* ContainsLexicalThis */; } return node; } @@ -22205,7 +22637,7 @@ var ts; } // @api function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) { - var node = createBaseExpression(203 /* CallExpression */); + var node = createBaseExpression(204 /* CallExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.questionDotToken = questionDotToken; @@ -22216,12 +22648,12 @@ var ts; propagateChildFlags(node.questionDotToken) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | - 8 /* ContainsES2020 */; + 16 /* ContainsES2020 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 4096 /* ContainsLexicalThis */; + node.transformFlags |= 8192 /* ContainsLexicalThis */; } return node; } @@ -22237,7 +22669,7 @@ var ts; } // @api function createNewExpression(expression, typeArguments, argumentsArray) { - var node = createBaseExpression(204 /* NewExpression */); + var node = createBaseExpression(205 /* NewExpression */); node.expression = parenthesizerRules().parenthesizeExpressionOfNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(argumentsArray) : undefined; @@ -22245,7 +22677,7 @@ var ts; propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | - 8 /* ContainsES2020 */; + 16 /* ContainsES2020 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } @@ -22261,7 +22693,7 @@ var ts; } // @api function createTaggedTemplateExpression(tag, typeArguments, template) { - var node = createBaseExpression(205 /* TaggedTemplateExpression */); + var node = createBaseExpression(206 /* TaggedTemplateExpression */); node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag); node.typeArguments = asNodeArray(typeArguments); node.template = template; @@ -22269,12 +22701,12 @@ var ts; propagateChildFlags(node.tag) | propagateChildrenFlags(node.typeArguments) | propagateChildFlags(node.template) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.hasInvalidEscape(node.template)) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } return node; } @@ -22288,7 +22720,7 @@ var ts; } // @api function createTypeAssertion(type, expression) { - var node = createBaseExpression(206 /* TypeAssertionExpression */); + var node = createBaseExpression(207 /* TypeAssertionExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.type = type; node.transformFlags |= @@ -22306,7 +22738,7 @@ var ts; } // @api function createParenthesizedExpression(expression) { - var node = createBaseExpression(207 /* ParenthesizedExpression */); + var node = createBaseExpression(208 /* ParenthesizedExpression */); node.expression = expression; node.transformFlags = propagateChildFlags(node.expression); return node; @@ -22319,7 +22751,7 @@ var ts; } // @api function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(208 /* FunctionExpression */, + var node = createBaseFunctionLikeDeclaration(209 /* FunctionExpression */, /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.asteriskToken); @@ -22328,14 +22760,14 @@ var ts; } if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (node.asteriskToken) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } else { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } } else if (node.asteriskToken) { - node.transformFlags |= 512 /* ContainsGenerator */; + node.transformFlags |= 1024 /* ContainsGenerator */; } return node; } @@ -22353,15 +22785,15 @@ var ts; } // @api function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createBaseFunctionLikeDeclaration(209 /* ArrowFunction */, + var node = createBaseFunctionLikeDeclaration(210 /* ArrowFunction */, /*decorators*/ undefined, modifiers, /*name*/ undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body)); node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* EqualsGreaterThanToken */); node.transformFlags |= propagateChildFlags(node.equalsGreaterThanToken) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } return node; } @@ -22378,7 +22810,7 @@ var ts; } // @api function createDeleteExpression(expression) { - var node = createBaseExpression(210 /* DeleteExpression */); + var node = createBaseExpression(211 /* DeleteExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -22391,7 +22823,7 @@ var ts; } // @api function createTypeOfExpression(expression) { - var node = createBaseExpression(211 /* TypeOfExpression */); + var node = createBaseExpression(212 /* TypeOfExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -22404,7 +22836,7 @@ var ts; } // @api function createVoidExpression(expression) { - var node = createBaseExpression(212 /* VoidExpression */); + var node = createBaseExpression(213 /* VoidExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -22417,13 +22849,13 @@ var ts; } // @api function createAwaitExpression(expression) { - var node = createBaseExpression(213 /* AwaitExpression */); + var node = createBaseExpression(214 /* AwaitExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */ | - 524288 /* ContainsAwait */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */ | + 1048576 /* ContainsAwait */; return node; } // @api @@ -22434,7 +22866,7 @@ var ts; } // @api function createPrefixUnaryExpression(operator, operand) { - var node = createBaseExpression(214 /* PrefixUnaryExpression */); + var node = createBaseExpression(215 /* PrefixUnaryExpression */); node.operator = operator; node.operand = parenthesizerRules().parenthesizeOperandOfPrefixUnary(operand); node.transformFlags |= propagateChildFlags(node.operand); @@ -22448,7 +22880,7 @@ var ts; } // @api function createPostfixUnaryExpression(operand, operator) { - var node = createBaseExpression(215 /* PostfixUnaryExpression */); + var node = createBaseExpression(216 /* PostfixUnaryExpression */); node.operator = operator; node.operand = parenthesizerRules().parenthesizeOperandOfPostfixUnary(operand); node.transformFlags = propagateChildFlags(node.operand); @@ -22462,7 +22894,7 @@ var ts; } // @api function createBinaryExpression(left, operator, right) { - var node = createBaseExpression(216 /* BinaryExpression */); + var node = createBaseExpression(217 /* BinaryExpression */); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = parenthesizerRules().parenthesizeLeftSideOfBinary(operatorKind, left); @@ -22473,45 +22905,45 @@ var ts; propagateChildFlags(node.operatorToken) | propagateChildFlags(node.right); if (operatorKind === 60 /* QuestionQuestionToken */) { - node.transformFlags |= 8 /* ContainsES2020 */; + node.transformFlags |= 16 /* ContainsES2020 */; } else if (operatorKind === 62 /* EqualsToken */) { if (ts.isObjectLiteralExpression(node.left)) { node.transformFlags |= - 256 /* ContainsES2015 */ | - 32 /* ContainsES2018 */ | - 1024 /* ContainsDestructuringAssignment */ | + 512 /* ContainsES2015 */ | + 64 /* ContainsES2018 */ | + 2048 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left); } else if (ts.isArrayLiteralExpression(node.left)) { node.transformFlags |= - 256 /* ContainsES2015 */ | - 1024 /* ContainsDestructuringAssignment */ | + 512 /* ContainsES2015 */ | + 2048 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left); } } else if (operatorKind === 42 /* AsteriskAsteriskToken */ || operatorKind === 66 /* AsteriskAsteriskEqualsToken */) { - node.transformFlags |= 128 /* ContainsES2016 */; + node.transformFlags |= 256 /* ContainsES2016 */; } else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) { - node.transformFlags |= 4 /* ContainsESNext */; + node.transformFlags |= 8 /* ContainsES2021 */; } return node; } function propagateAssignmentPatternFlags(node) { - if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) - return 16384 /* ContainsObjectRestOrSpread */; - if (node.transformFlags & 32 /* ContainsES2018 */) { + if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) + return 32768 /* ContainsObjectRestOrSpread */; + if (node.transformFlags & 64 /* ContainsES2018 */) { // check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c' // will not be correctly interpreted by the ES2018 transformer for (var _i = 0, _a = ts.getElementsOfBindingOrAssignmentPattern(node); _i < _a.length; _i++) { var element = _a[_i]; var target = ts.getTargetOfBindingOrAssignmentElement(element); if (target && ts.isAssignmentPattern(target)) { - if (target.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { - return 16384 /* ContainsObjectRestOrSpread */; + if (target.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { + return 32768 /* ContainsObjectRestOrSpread */; } - if (target.transformFlags & 32 /* ContainsES2018 */) { + if (target.transformFlags & 64 /* ContainsES2018 */) { var flags_1 = propagateAssignmentPatternFlags(target); if (flags_1) return flags_1; @@ -22531,7 +22963,7 @@ var ts; } // @api function createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse) { - var node = createBaseExpression(217 /* ConditionalExpression */); + var node = createBaseExpression(218 /* ConditionalExpression */); node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression(condition); node.questionToken = questionToken !== null && questionToken !== void 0 ? questionToken : createToken(57 /* QuestionToken */); node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue); @@ -22557,13 +22989,13 @@ var ts; } // @api function createTemplateExpression(head, templateSpans) { - var node = createBaseExpression(218 /* TemplateExpression */); + var node = createBaseExpression(219 /* TemplateExpression */); node.head = head; node.templateSpans = createNodeArray(templateSpans); node.transformFlags |= propagateChildFlags(node.head) | propagateChildrenFlags(node.templateSpans) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } // @api @@ -22602,9 +23034,9 @@ var ts; node.text = text; node.rawText = rawText; node.templateFlags = templateFlags & 2048 /* TemplateLiteralLikeFlags */; - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; if (node.templateFlags) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } return node; } @@ -22627,15 +23059,15 @@ var ts; // @api function createYieldExpression(asteriskToken, expression) { ts.Debug.assert(!asteriskToken || !!expression, "A `YieldExpression` with an asteriskToken must have an expression."); - var node = createBaseExpression(219 /* YieldExpression */); + var node = createBaseExpression(220 /* YieldExpression */); node.expression = expression && parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.asteriskToken) | - 256 /* ContainsES2015 */ | - 32 /* ContainsES2018 */ | - 262144 /* ContainsYield */; + 512 /* ContainsES2015 */ | + 64 /* ContainsES2018 */ | + 524288 /* ContainsYield */; return node; } // @api @@ -22647,12 +23079,12 @@ var ts; } // @api function createSpreadElement(expression) { - var node = createBaseExpression(220 /* SpreadElement */); + var node = createBaseExpression(221 /* SpreadElement */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 256 /* ContainsES2015 */ | - 8192 /* ContainsRestOrSpread */; + 512 /* ContainsES2015 */ | + 16384 /* ContainsRestOrSpread */; return node; } // @api @@ -22663,8 +23095,8 @@ var ts; } // @api function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(221 /* ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members); - node.transformFlags |= 256 /* ContainsES2015 */; + var node = createBaseClassLikeDeclaration(222 /* ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members); + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -22680,17 +23112,17 @@ var ts; } // @api function createOmittedExpression() { - return createBaseExpression(222 /* OmittedExpression */); + return createBaseExpression(223 /* OmittedExpression */); } // @api function createExpressionWithTypeArguments(expression, typeArguments) { - var node = createBaseNode(223 /* ExpressionWithTypeArguments */); + var node = createBaseNode(224 /* ExpressionWithTypeArguments */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } // @api @@ -22702,7 +23134,7 @@ var ts; } // @api function createAsExpression(expression, type) { - var node = createBaseExpression(224 /* AsExpression */); + var node = createBaseExpression(225 /* AsExpression */); node.expression = expression; node.type = type; node.transformFlags |= @@ -22720,7 +23152,7 @@ var ts; } // @api function createNonNullExpression(expression) { - var node = createBaseExpression(225 /* NonNullExpression */); + var node = createBaseExpression(226 /* NonNullExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.transformFlags |= propagateChildFlags(node.expression) | @@ -22738,7 +23170,7 @@ var ts; } // @api function createNonNullChain(expression) { - var node = createBaseExpression(225 /* NonNullExpression */); + var node = createBaseExpression(226 /* NonNullExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.transformFlags |= @@ -22755,13 +23187,13 @@ var ts; } // @api function createMetaProperty(keywordToken, name) { - var node = createBaseExpression(226 /* MetaProperty */); + var node = createBaseExpression(227 /* MetaProperty */); node.keywordToken = keywordToken; node.name = name; node.transformFlags |= propagateChildFlags(node.name); switch (keywordToken) { case 102 /* NewKeyword */: - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; break; case 99 /* ImportKeyword */: node.transformFlags |= 4 /* ContainsESNext */; @@ -22782,13 +23214,13 @@ var ts; // // @api function createTemplateSpan(expression, literal) { - var node = createBaseNode(228 /* TemplateSpan */); + var node = createBaseNode(229 /* TemplateSpan */); node.expression = expression; node.literal = literal; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.literal) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } // @api @@ -22800,8 +23232,8 @@ var ts; } // @api function createSemicolonClassElement() { - var node = createBaseNode(229 /* SemicolonClassElement */); - node.transformFlags |= 256 /* ContainsES2015 */; + var node = createBaseNode(230 /* SemicolonClassElement */); + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @@ -22809,7 +23241,7 @@ var ts; // // @api function createBlock(statements, multiLine) { - var node = createBaseNode(230 /* Block */); + var node = createBaseNode(231 /* Block */); node.statements = createNodeArray(statements); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.statements); @@ -22823,7 +23255,7 @@ var ts; } // @api function createVariableStatement(modifiers, declarationList) { - var node = createBaseDeclaration(232 /* VariableStatement */, /*decorators*/ undefined, modifiers); + var node = createBaseDeclaration(233 /* VariableStatement */, /*decorators*/ undefined, modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; node.transformFlags |= propagateChildFlags(node.declarationList); @@ -22841,11 +23273,11 @@ var ts; } // @api function createEmptyStatement() { - return createBaseNode(231 /* EmptyStatement */); + return createBaseNode(232 /* EmptyStatement */); } // @api function createExpressionStatement(expression) { - var node = createBaseNode(233 /* ExpressionStatement */); + var node = createBaseNode(234 /* ExpressionStatement */); node.expression = parenthesizerRules().parenthesizeExpressionOfExpressionStatement(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -22858,7 +23290,7 @@ var ts; } // @api function createIfStatement(expression, thenStatement, elseStatement) { - var node = createBaseNode(234 /* IfStatement */); + var node = createBaseNode(235 /* IfStatement */); node.expression = expression; node.thenStatement = asEmbeddedStatement(thenStatement); node.elseStatement = asEmbeddedStatement(elseStatement); @@ -22878,7 +23310,7 @@ var ts; } // @api function createDoStatement(statement, expression) { - var node = createBaseNode(235 /* DoStatement */); + var node = createBaseNode(236 /* DoStatement */); node.statement = asEmbeddedStatement(statement); node.expression = expression; node.transformFlags |= @@ -22895,7 +23327,7 @@ var ts; } // @api function createWhileStatement(expression, statement) { - var node = createBaseNode(236 /* WhileStatement */); + var node = createBaseNode(237 /* WhileStatement */); node.expression = expression; node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -22912,7 +23344,7 @@ var ts; } // @api function createForStatement(initializer, condition, incrementor, statement) { - var node = createBaseNode(237 /* ForStatement */); + var node = createBaseNode(238 /* ForStatement */); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -22935,7 +23367,7 @@ var ts; } // @api function createForInStatement(initializer, expression, statement) { - var node = createBaseNode(238 /* ForInStatement */); + var node = createBaseNode(239 /* ForInStatement */); node.initializer = initializer; node.expression = expression; node.statement = asEmbeddedStatement(statement); @@ -22955,7 +23387,7 @@ var ts; } // @api function createForOfStatement(awaitModifier, initializer, expression, statement) { - var node = createBaseNode(239 /* ForOfStatement */); + var node = createBaseNode(240 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); @@ -22965,9 +23397,9 @@ var ts; propagateChildFlags(node.initializer) | propagateChildFlags(node.expression) | propagateChildFlags(node.statement) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (awaitModifier) - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; return node; } // @api @@ -22981,11 +23413,11 @@ var ts; } // @api function createContinueStatement(label) { - var node = createBaseNode(240 /* ContinueStatement */); + var node = createBaseNode(241 /* ContinueStatement */); node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -22996,11 +23428,11 @@ var ts; } // @api function createBreakStatement(label) { - var node = createBaseNode(241 /* BreakStatement */); + var node = createBaseNode(242 /* BreakStatement */); node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -23011,13 +23443,13 @@ var ts; } // @api function createReturnStatement(expression) { - var node = createBaseNode(242 /* ReturnStatement */); + var node = createBaseNode(243 /* ReturnStatement */); node.expression = expression; // return in an ES2018 async generator must be awaited node.transformFlags |= propagateChildFlags(node.expression) | - 32 /* ContainsES2018 */ | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 64 /* ContainsES2018 */ | + 2097152 /* ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -23028,7 +23460,7 @@ var ts; } // @api function createWithStatement(expression, statement) { - var node = createBaseNode(243 /* WithStatement */); + var node = createBaseNode(244 /* WithStatement */); node.expression = expression; node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -23045,7 +23477,7 @@ var ts; } // @api function createSwitchStatement(expression, caseBlock) { - var node = createBaseNode(244 /* SwitchStatement */); + var node = createBaseNode(245 /* SwitchStatement */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.caseBlock = caseBlock; node.transformFlags |= @@ -23062,7 +23494,7 @@ var ts; } // @api function createLabeledStatement(label, statement) { - var node = createBaseNode(245 /* LabeledStatement */); + var node = createBaseNode(246 /* LabeledStatement */); node.label = asName(label); node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -23079,7 +23511,7 @@ var ts; } // @api function createThrowStatement(expression) { - var node = createBaseNode(246 /* ThrowStatement */); + var node = createBaseNode(247 /* ThrowStatement */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -23092,7 +23524,7 @@ var ts; } // @api function createTryStatement(tryBlock, catchClause, finallyBlock) { - var node = createBaseNode(247 /* TryStatement */); + var node = createBaseNode(248 /* TryStatement */); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -23112,11 +23544,11 @@ var ts; } // @api function createDebuggerStatement() { - return createBaseNode(248 /* DebuggerStatement */); + return createBaseNode(249 /* DebuggerStatement */); } // @api function createVariableDeclaration(name, exclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(249 /* VariableDeclaration */, + var node = createBaseVariableLikeDeclaration(250 /* VariableDeclaration */, /*decorators*/ undefined, /*modifiers*/ undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.exclamationToken = exclamationToken; @@ -23138,16 +23570,16 @@ var ts; // @api function createVariableDeclarationList(declarations, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createBaseNode(250 /* VariableDeclarationList */); + var node = createBaseNode(251 /* VariableDeclarationList */); node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); node.transformFlags |= propagateChildrenFlags(node.declarations) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; if (flags & 3 /* BlockScoped */) { node.transformFlags |= - 256 /* ContainsES2015 */ | - 65536 /* ContainsBlockScopedBinding */; + 512 /* ContainsES2015 */ | + 131072 /* ContainsBlockScopedBinding */; } return node; } @@ -23159,7 +23591,7 @@ var ts; } // @api function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(251 /* FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(252 /* FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; if (!node.body || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) { node.transformFlags = 1 /* ContainsTypeScript */; @@ -23167,17 +23599,17 @@ var ts; else { node.transformFlags |= propagateChildFlags(node.asteriskToken) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (node.asteriskToken) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } else { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } } else if (node.asteriskToken) { - node.transformFlags |= 512 /* ContainsGenerator */; + node.transformFlags |= 1024 /* ContainsGenerator */; } } return node; @@ -23197,13 +23629,13 @@ var ts; } // @api function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(252 /* ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members); + var node = createBaseClassLikeDeclaration(253 /* ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members); if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) { node.transformFlags = 1 /* ContainsTypeScript */; } else { - node.transformFlags |= 256 /* ContainsES2015 */; - if (node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */) { + node.transformFlags |= 512 /* ContainsES2015 */; + if (node.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */) { node.transformFlags |= 1 /* ContainsTypeScript */; } } @@ -23222,7 +23654,7 @@ var ts; } // @api function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(253 /* InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses); + var node = createBaseInterfaceOrClassLikeDeclaration(254 /* InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -23240,7 +23672,7 @@ var ts; } // @api function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createBaseGenericNamedDeclaration(254 /* TypeAliasDeclaration */, decorators, modifiers, name, typeParameters); + var node = createBaseGenericNamedDeclaration(255 /* TypeAliasDeclaration */, decorators, modifiers, name, typeParameters); node.type = type; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -23257,12 +23689,12 @@ var ts; } // @api function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createBaseNamedDeclaration(255 /* EnumDeclaration */, decorators, modifiers, name); + var node = createBaseNamedDeclaration(256 /* EnumDeclaration */, decorators, modifiers, name); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members) | 1 /* ContainsTypeScript */; - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` return node; } // @api @@ -23277,7 +23709,7 @@ var ts; // @api function createModuleDeclaration(decorators, modifiers, name, body, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createBaseDeclaration(256 /* ModuleDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(257 /* ModuleDeclaration */, decorators, modifiers); node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 1024 /* GlobalAugmentation */); node.name = name; node.body = body; @@ -23290,7 +23722,7 @@ var ts; propagateChildFlags(node.body) | 1 /* ContainsTypeScript */; } - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. return node; } // @api @@ -23304,7 +23736,7 @@ var ts; } // @api function createModuleBlock(statements) { - var node = createBaseNode(257 /* ModuleBlock */); + var node = createBaseNode(258 /* ModuleBlock */); node.statements = createNodeArray(statements); node.transformFlags |= propagateChildrenFlags(node.statements); return node; @@ -23317,7 +23749,7 @@ var ts; } // @api function createCaseBlock(clauses) { - var node = createBaseNode(258 /* CaseBlock */); + var node = createBaseNode(259 /* CaseBlock */); node.clauses = createNodeArray(clauses); node.transformFlags |= propagateChildrenFlags(node.clauses); return node; @@ -23330,7 +23762,7 @@ var ts; } // @api function createNamespaceExportDeclaration(name) { - var node = createBaseNamedDeclaration(259 /* NamespaceExportDeclaration */, + var node = createBaseNamedDeclaration(260 /* NamespaceExportDeclaration */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.transformFlags = 1 /* ContainsTypeScript */; @@ -23344,13 +23776,13 @@ var ts; } // @api function createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference) { - var node = createBaseNamedDeclaration(260 /* ImportEqualsDeclaration */, decorators, modifiers, name); + var node = createBaseNamedDeclaration(261 /* ImportEqualsDeclaration */, decorators, modifiers, name); node.isTypeOnly = isTypeOnly; node.moduleReference = moduleReference; node.transformFlags |= propagateChildFlags(node.moduleReference); if (!ts.isExternalModuleReference(node.moduleReference)) node.transformFlags |= 1 /* ContainsTypeScript */; - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context return node; } // @api @@ -23365,13 +23797,13 @@ var ts; } // @api function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createBaseDeclaration(261 /* ImportDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(262 /* ImportDeclaration */, decorators, modifiers); node.importClause = importClause; node.moduleSpecifier = moduleSpecifier; node.transformFlags |= propagateChildFlags(node.importClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23385,7 +23817,7 @@ var ts; } // @api function createImportClause(isTypeOnly, name, namedBindings) { - var node = createBaseNode(262 /* ImportClause */); + var node = createBaseNode(263 /* ImportClause */); node.isTypeOnly = isTypeOnly; node.name = name; node.namedBindings = namedBindings; @@ -23395,7 +23827,7 @@ var ts; if (isTypeOnly) { node.transformFlags |= 1 /* ContainsTypeScript */; } - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23408,10 +23840,10 @@ var ts; } // @api function createNamespaceImport(name) { - var node = createBaseNode(263 /* NamespaceImport */); + var node = createBaseNode(264 /* NamespaceImport */); node.name = name; node.transformFlags |= propagateChildFlags(node.name); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23422,12 +23854,12 @@ var ts; } // @api function createNamespaceExport(name) { - var node = createBaseNode(269 /* NamespaceExport */); + var node = createBaseNode(270 /* NamespaceExport */); node.name = name; node.transformFlags |= propagateChildFlags(node.name) | 4 /* ContainsESNext */; - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23438,10 +23870,10 @@ var ts; } // @api function createNamedImports(elements) { - var node = createBaseNode(264 /* NamedImports */); + var node = createBaseNode(265 /* NamedImports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23452,13 +23884,13 @@ var ts; } // @api function createImportSpecifier(propertyName, name) { - var node = createBaseNode(265 /* ImportSpecifier */); + var node = createBaseNode(266 /* ImportSpecifier */); node.propertyName = propertyName; node.name = name; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23470,13 +23902,13 @@ var ts; } // @api function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createBaseDeclaration(266 /* ExportAssignment */, decorators, modifiers); + var node = createBaseDeclaration(267 /* ExportAssignment */, decorators, modifiers); node.isExportEquals = isExportEquals; node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary(62 /* EqualsToken */, /*leftSide*/ undefined, expression) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23489,14 +23921,14 @@ var ts; } // @api function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier) { - var node = createBaseDeclaration(267 /* ExportDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(268 /* ExportDeclaration */, decorators, modifiers); node.isTypeOnly = isTypeOnly; node.exportClause = exportClause; node.moduleSpecifier = moduleSpecifier; node.transformFlags |= propagateChildFlags(node.exportClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23511,10 +23943,10 @@ var ts; } // @api function createNamedExports(elements) { - var node = createBaseNode(268 /* NamedExports */); + var node = createBaseNode(269 /* NamedExports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23525,13 +23957,13 @@ var ts; } // @api function createExportSpecifier(propertyName, name) { - var node = createBaseNode(270 /* ExportSpecifier */); + var node = createBaseNode(271 /* ExportSpecifier */); node.propertyName = asName(propertyName); node.name = asName(name); node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23543,7 +23975,7 @@ var ts; } // @api function createMissingDeclaration() { - var node = createBaseDeclaration(271 /* MissingDeclaration */, + var node = createBaseDeclaration(272 /* MissingDeclaration */, /*decorators*/ undefined, /*modifiers*/ undefined); return node; @@ -23553,10 +23985,10 @@ var ts; // // @api function createExternalModuleReference(expression) { - var node = createBaseNode(272 /* ExternalModuleReference */); + var node = createBaseNode(273 /* ExternalModuleReference */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23598,7 +24030,7 @@ var ts; } // @api function createJSDocFunctionType(parameters, type) { - var node = createBaseSignatureDeclaration(308 /* JSDocFunctionType */, + var node = createBaseSignatureDeclaration(309 /* JSDocFunctionType */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, @@ -23615,7 +24047,7 @@ var ts; // @api function createJSDocTypeLiteral(propertyTags, isArrayType) { if (isArrayType === void 0) { isArrayType = false; } - var node = createBaseNode(312 /* JSDocTypeLiteral */); + var node = createBaseNode(314 /* JSDocTypeLiteral */); node.jsDocPropertyTags = asNodeArray(propertyTags); node.isArrayType = isArrayType; return node; @@ -23629,7 +24061,7 @@ var ts; } // @api function createJSDocTypeExpression(type) { - var node = createBaseNode(301 /* JSDocTypeExpression */); + var node = createBaseNode(302 /* JSDocTypeExpression */); node.type = type; return node; } @@ -23641,7 +24073,7 @@ var ts; } // @api function createJSDocSignature(typeParameters, parameters, type) { - var node = createBaseNode(313 /* JSDocSignature */); + var node = createBaseNode(315 /* JSDocSignature */); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; @@ -23670,7 +24102,7 @@ var ts; } // @api function createJSDocTemplateTag(tagName, constraint, typeParameters, comment) { - var node = createBaseJSDocTag(330 /* JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment); + var node = createBaseJSDocTag(334 /* JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment); node.constraint = constraint; node.typeParameters = createNodeArray(typeParameters); return node; @@ -23687,7 +24119,7 @@ var ts; } // @api function createJSDocTypedefTag(tagName, typeExpression, fullName, comment) { - var node = createBaseJSDocTag(331 /* JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment); + var node = createBaseJSDocTag(335 /* JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment); node.typeExpression = typeExpression; node.fullName = fullName; node.name = ts.getJSDocTypeAliasName(fullName); @@ -23705,7 +24137,7 @@ var ts; } // @api function createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { - var node = createBaseJSDocTag(326 /* JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment); + var node = createBaseJSDocTag(330 /* JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -23726,7 +24158,7 @@ var ts; } // @api function createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { - var node = createBaseJSDocTag(333 /* JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment); + var node = createBaseJSDocTag(337 /* JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -23747,7 +24179,7 @@ var ts; } // @api function createJSDocCallbackTag(tagName, typeExpression, fullName, comment) { - var node = createBaseJSDocTag(324 /* JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment); + var node = createBaseJSDocTag(328 /* JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment); node.typeExpression = typeExpression; node.fullName = fullName; node.name = ts.getJSDocTypeAliasName(fullName); @@ -23765,7 +24197,7 @@ var ts; } // @api function createJSDocAugmentsTag(tagName, className, comment) { - var node = createBaseJSDocTag(315 /* JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment); + var node = createBaseJSDocTag(318 /* JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment); node.class = className; return node; } @@ -23780,13 +24212,13 @@ var ts; } // @api function createJSDocImplementsTag(tagName, className, comment) { - var node = createBaseJSDocTag(316 /* JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment); + var node = createBaseJSDocTag(319 /* JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment); node.class = className; return node; } // @api function createJSDocSeeTag(tagName, name, comment) { - var node = createBaseJSDocTag(332 /* JSDocSeeTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment); + var node = createBaseJSDocTag(336 /* JSDocSeeTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment); node.name = name; return node; } @@ -23800,7 +24232,7 @@ var ts; } // @api function createJSDocNameReference(name) { - var node = createBaseNode(302 /* JSDocNameReference */); + var node = createBaseNode(303 /* JSDocNameReference */); node.name = name; return node; } @@ -23811,6 +24243,19 @@ var ts; : node; } // @api + function createJSDocLink(name, text) { + var node = createBaseNode(316 /* JSDocLink */); + node.name = name; + node.text = text; + return node; + } + // @api + function updateJSDocLink(node, name, text) { + return node.name !== name + ? update(createJSDocLink(name, text), node) + : node; + } + // @api function updateJSDocImplementsTag(node, tagName, className, comment) { if (tagName === void 0) { tagName = getDefaultTagName(node); } return node.tagName !== tagName @@ -23871,7 +24316,7 @@ var ts; } // @api function createJSDocUnknownTag(tagName, comment) { - var node = createBaseJSDocTag(314 /* JSDocTag */, tagName, comment); + var node = createBaseJSDocTag(317 /* JSDocTag */, tagName, comment); return node; } // @api @@ -23882,8 +24327,20 @@ var ts; : node; } // @api + function createJSDocText(text) { + var node = createBaseNode(313 /* JSDocText */); + node.text = text; + return node; + } + // @api + function updateJSDocText(node, text) { + return node.text !== text + ? update(createJSDocText(text), node) + : node; + } + // @api function createJSDocComment(comment, tags) { - var node = createBaseNode(311 /* JSDocComment */); + var node = createBaseNode(312 /* JSDocComment */); node.comment = comment; node.tags = asNodeArray(tags); return node; @@ -23900,7 +24357,7 @@ var ts; // // @api function createJsxElement(openingElement, children, closingElement) { - var node = createBaseNode(273 /* JsxElement */); + var node = createBaseNode(274 /* JsxElement */); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -23921,7 +24378,7 @@ var ts; } // @api function createJsxSelfClosingElement(tagName, typeArguments, attributes) { - var node = createBaseNode(274 /* JsxSelfClosingElement */); + var node = createBaseNode(275 /* JsxSelfClosingElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -23945,7 +24402,7 @@ var ts; } // @api function createJsxOpeningElement(tagName, typeArguments, attributes) { - var node = createBaseNode(275 /* JsxOpeningElement */); + var node = createBaseNode(276 /* JsxOpeningElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -23969,7 +24426,7 @@ var ts; } // @api function createJsxClosingElement(tagName) { - var node = createBaseNode(276 /* JsxClosingElement */); + var node = createBaseNode(277 /* JsxClosingElement */); node.tagName = tagName; node.transformFlags |= propagateChildFlags(node.tagName) | @@ -23984,7 +24441,7 @@ var ts; } // @api function createJsxFragment(openingFragment, children, closingFragment) { - var node = createBaseNode(277 /* JsxFragment */); + var node = createBaseNode(278 /* JsxFragment */); node.openingFragment = openingFragment; node.children = createNodeArray(children); node.closingFragment = closingFragment; @@ -24020,19 +24477,19 @@ var ts; } // @api function createJsxOpeningFragment() { - var node = createBaseNode(278 /* JsxOpeningFragment */); + var node = createBaseNode(279 /* JsxOpeningFragment */); node.transformFlags |= 2 /* ContainsJsx */; return node; } // @api function createJsxJsxClosingFragment() { - var node = createBaseNode(279 /* JsxClosingFragment */); + var node = createBaseNode(280 /* JsxClosingFragment */); node.transformFlags |= 2 /* ContainsJsx */; return node; } // @api function createJsxAttribute(name, initializer) { - var node = createBaseNode(280 /* JsxAttribute */); + var node = createBaseNode(281 /* JsxAttribute */); node.name = name; node.initializer = initializer; node.transformFlags |= @@ -24050,7 +24507,7 @@ var ts; } // @api function createJsxAttributes(properties) { - var node = createBaseNode(281 /* JsxAttributes */); + var node = createBaseNode(282 /* JsxAttributes */); node.properties = createNodeArray(properties); node.transformFlags |= propagateChildrenFlags(node.properties) | @@ -24065,7 +24522,7 @@ var ts; } // @api function createJsxSpreadAttribute(expression) { - var node = createBaseNode(282 /* JsxSpreadAttribute */); + var node = createBaseNode(283 /* JsxSpreadAttribute */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression) | @@ -24080,7 +24537,7 @@ var ts; } // @api function createJsxExpression(dotDotDotToken, expression) { - var node = createBaseNode(283 /* JsxExpression */); + var node = createBaseNode(284 /* JsxExpression */); node.dotDotDotToken = dotDotDotToken; node.expression = expression; node.transformFlags |= @@ -24100,7 +24557,7 @@ var ts; // // @api function createCaseClause(expression, statements) { - var node = createBaseNode(284 /* CaseClause */); + var node = createBaseNode(285 /* CaseClause */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.statements = createNodeArray(statements); node.transformFlags |= @@ -24117,7 +24574,7 @@ var ts; } // @api function createDefaultClause(statements) { - var node = createBaseNode(285 /* DefaultClause */); + var node = createBaseNode(286 /* DefaultClause */); node.statements = createNodeArray(statements); node.transformFlags = propagateChildrenFlags(node.statements); return node; @@ -24130,13 +24587,13 @@ var ts; } // @api function createHeritageClause(token, types) { - var node = createBaseNode(286 /* HeritageClause */); + var node = createBaseNode(287 /* HeritageClause */); node.token = token; node.types = createNodeArray(types); node.transformFlags |= propagateChildrenFlags(node.types); switch (token) { case 93 /* ExtendsKeyword */: - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; break; case 116 /* ImplementsKeyword */: node.transformFlags |= 1 /* ContainsTypeScript */; @@ -24154,7 +24611,7 @@ var ts; } // @api function createCatchClause(variableDeclaration, block) { - var node = createBaseNode(287 /* CatchClause */); + var node = createBaseNode(288 /* CatchClause */); variableDeclaration = !ts.isString(variableDeclaration) ? variableDeclaration : createVariableDeclaration(variableDeclaration, /*exclamationToken*/ undefined, /*type*/ undefined, @@ -24165,7 +24622,7 @@ var ts; propagateChildFlags(node.variableDeclaration) | propagateChildFlags(node.block); if (!variableDeclaration) - node.transformFlags |= 16 /* ContainsES2019 */; + node.transformFlags |= 32 /* ContainsES2019 */; return node; } // @api @@ -24180,7 +24637,7 @@ var ts; // // @api function createPropertyAssignment(name, initializer) { - var node = createBaseNamedDeclaration(288 /* PropertyAssignment */, + var node = createBaseNamedDeclaration(289 /* PropertyAssignment */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); @@ -24210,13 +24667,13 @@ var ts; } // @api function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createBaseNamedDeclaration(289 /* ShorthandPropertyAssignment */, + var node = createBaseNamedDeclaration(290 /* ShorthandPropertyAssignment */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); node.transformFlags |= propagateChildFlags(node.objectAssignmentInitializer) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } function finishUpdateShorthandPropertyAssignment(updated, original) { @@ -24242,12 +24699,12 @@ var ts; } // @api function createSpreadAssignment(expression) { - var node = createBaseNode(290 /* SpreadAssignment */); + var node = createBaseNode(291 /* SpreadAssignment */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 32 /* ContainsES2018 */ | - 16384 /* ContainsObjectRestOrSpread */; + 64 /* ContainsES2018 */ | + 32768 /* ContainsObjectRestOrSpread */; return node; } // @api @@ -24261,7 +24718,7 @@ var ts; // // @api function createEnumMember(name, initializer) { - var node = createBaseNode(291 /* EnumMember */); + var node = createBaseNode(292 /* EnumMember */); node.name = asName(name); node.initializer = initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); node.transformFlags |= @@ -24282,7 +24739,7 @@ var ts; // // @api function createSourceFile(statements, endOfFileToken, flags) { - var node = baseFactory.createBaseSourceFileNode(297 /* SourceFile */); + var node = baseFactory.createBaseSourceFileNode(298 /* SourceFile */); node.statements = createNodeArray(statements); node.endOfFileToken = endOfFileToken; node.flags |= flags; @@ -24299,7 +24756,7 @@ var ts; return node; } function cloneSourceFileWithChanges(source, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) { - var node = baseFactory.createBaseSourceFileNode(297 /* SourceFile */); + var node = baseFactory.createBaseSourceFileNode(298 /* SourceFile */); for (var p in source) { if (p === "emitNode" || ts.hasProperty(node, p) || !ts.hasProperty(source, p)) continue; @@ -24337,7 +24794,7 @@ var ts; // @api function createBundle(sourceFiles, prepends) { if (prepends === void 0) { prepends = ts.emptyArray; } - var node = createBaseNode(298 /* Bundle */); + var node = createBaseNode(299 /* Bundle */); node.prepends = prepends; node.sourceFiles = sourceFiles; return node; @@ -24352,7 +24809,7 @@ var ts; } // @api function createUnparsedSource(prologues, syntheticReferences, texts) { - var node = createBaseNode(299 /* UnparsedSource */); + var node = createBaseNode(300 /* UnparsedSource */); node.prologues = prologues; node.syntheticReferences = syntheticReferences; node.texts = texts; @@ -24370,28 +24827,28 @@ var ts; } // @api function createUnparsedPrologue(data) { - return createBaseUnparsedNode(292 /* UnparsedPrologue */, data); + return createBaseUnparsedNode(293 /* UnparsedPrologue */, data); } // @api function createUnparsedPrepend(data, texts) { - var node = createBaseUnparsedNode(293 /* UnparsedPrepend */, data); + var node = createBaseUnparsedNode(294 /* UnparsedPrepend */, data); node.texts = texts; return node; } // @api function createUnparsedTextLike(data, internal) { - return createBaseUnparsedNode(internal ? 295 /* UnparsedInternalText */ : 294 /* UnparsedText */, data); + return createBaseUnparsedNode(internal ? 296 /* UnparsedInternalText */ : 295 /* UnparsedText */, data); } // @api function createUnparsedSyntheticReference(section) { - var node = createBaseNode(296 /* UnparsedSyntheticReference */); + var node = createBaseNode(297 /* UnparsedSyntheticReference */); node.data = section.data; node.section = section; return node; } // @api function createInputFiles() { - var node = createBaseNode(300 /* InputFiles */); + var node = createBaseNode(301 /* InputFiles */); node.javascriptText = ""; node.declarationText = ""; return node; @@ -24402,7 +24859,7 @@ var ts; // @api function createSyntheticExpression(type, isSpread, tupleNameSource) { if (isSpread === void 0) { isSpread = false; } - var node = createBaseNode(227 /* SyntheticExpression */); + var node = createBaseNode(228 /* SyntheticExpression */); node.type = type; node.isSpread = isSpread; node.tupleNameSource = tupleNameSource; @@ -24410,7 +24867,7 @@ var ts; } // @api function createSyntaxList(children) { - var node = createBaseNode(334 /* SyntaxList */); + var node = createBaseNode(338 /* SyntaxList */); node._children = children; return node; } @@ -24425,7 +24882,7 @@ var ts; */ // @api function createNotEmittedStatement(original) { - var node = createBaseNode(335 /* NotEmittedStatement */); + var node = createBaseNode(339 /* NotEmittedStatement */); node.original = original; ts.setTextRange(node, original); return node; @@ -24439,7 +24896,7 @@ var ts; */ // @api function createPartiallyEmittedExpression(expression, original) { - var node = createBaseNode(336 /* PartiallyEmittedExpression */); + var node = createBaseNode(340 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; node.transformFlags |= @@ -24467,7 +24924,7 @@ var ts; } // @api function createCommaListExpression(elements) { - var node = createBaseNode(337 /* CommaListExpression */); + var node = createBaseNode(341 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); node.transformFlags |= propagateChildrenFlags(node.elements); return node; @@ -24484,7 +24941,7 @@ var ts; */ // @api function createEndOfDeclarationMarker(original) { - var node = createBaseNode(339 /* EndOfDeclarationMarker */); + var node = createBaseNode(343 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -24495,14 +24952,14 @@ var ts; */ // @api function createMergeDeclarationMarker(original) { - var node = createBaseNode(338 /* MergeDeclarationMarker */); + var node = createBaseNode(342 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; } // @api function createSyntheticReferenceExpression(expression, thisArg) { - var node = createBaseNode(340 /* SyntheticReferenceExpression */); + var node = createBaseNode(344 /* SyntheticReferenceExpression */); node.expression = expression; node.thisArg = thisArg; node.transformFlags |= @@ -24524,7 +24981,7 @@ var ts; if (node === undefined) { return node; } - var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(297 /* SourceFile */) : + var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(298 /* SourceFile */) : ts.isIdentifier(node) ? baseFactory.createBaseIdentifierNode(78 /* Identifier */) : ts.isPrivateIdentifier(node) ? baseFactory.createBasePrivateIdentifierNode(79 /* PrivateIdentifier */) : !ts.isNodeKind(node.kind) ? baseFactory.createBaseTokenNode(node.kind) : @@ -24631,11 +25088,11 @@ var ts; } function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 207 /* ParenthesizedExpression */: return updateParenthesizedExpression(outerExpression, expression); - case 206 /* TypeAssertionExpression */: return updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 224 /* AsExpression */: return updateAsExpression(outerExpression, expression, outerExpression.type); - case 225 /* NonNullExpression */: return updateNonNullExpression(outerExpression, expression); - case 336 /* PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression); + case 208 /* ParenthesizedExpression */: return updateParenthesizedExpression(outerExpression, expression); + case 207 /* TypeAssertionExpression */: return updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 225 /* AsExpression */: return updateAsExpression(outerExpression, expression, outerExpression.type); + case 226 /* NonNullExpression */: return updateNonNullExpression(outerExpression, expression); + case 340 /* PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -24689,13 +25146,13 @@ var ts; case 9 /* BigIntLiteral */: case 10 /* StringLiteral */: return false; - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return target.properties.length > 0; default: return true; @@ -25098,23 +25555,24 @@ var ts; } function getDefaultTagNameForKind(kind) { switch (kind) { - case 329 /* JSDocTypeTag */: return "type"; - case 327 /* JSDocReturnTag */: return "returns"; - case 328 /* JSDocThisTag */: return "this"; - case 325 /* JSDocEnumTag */: return "enum"; - case 317 /* JSDocAuthorTag */: return "author"; - case 319 /* JSDocClassTag */: return "class"; - case 320 /* JSDocPublicTag */: return "public"; - case 321 /* JSDocPrivateTag */: return "private"; - case 322 /* JSDocProtectedTag */: return "protected"; - case 323 /* JSDocReadonlyTag */: return "readonly"; - case 330 /* JSDocTemplateTag */: return "template"; - case 331 /* JSDocTypedefTag */: return "typedef"; - case 326 /* JSDocParameterTag */: return "param"; - case 333 /* JSDocPropertyTag */: return "prop"; - case 324 /* JSDocCallbackTag */: return "callback"; - case 315 /* JSDocAugmentsTag */: return "augments"; - case 316 /* JSDocImplementsTag */: return "implements"; + case 333 /* JSDocTypeTag */: return "type"; + case 331 /* JSDocReturnTag */: return "returns"; + case 332 /* JSDocThisTag */: return "this"; + case 329 /* JSDocEnumTag */: return "enum"; + case 320 /* JSDocAuthorTag */: return "author"; + case 322 /* JSDocClassTag */: return "class"; + case 323 /* JSDocPublicTag */: return "public"; + case 324 /* JSDocPrivateTag */: return "private"; + case 325 /* JSDocProtectedTag */: return "protected"; + case 326 /* JSDocReadonlyTag */: return "readonly"; + case 327 /* JSDocOverrideTag */: return "override"; + case 334 /* JSDocTemplateTag */: return "template"; + case 335 /* JSDocTypedefTag */: return "typedef"; + case 330 /* JSDocParameterTag */: return "param"; + case 337 /* JSDocPropertyTag */: return "prop"; + case 328 /* JSDocCallbackTag */: return "callback"; + case 318 /* JSDocAugmentsTag */: return "augments"; + case 319 /* JSDocImplementsTag */: return "implements"; default: return ts.Debug.fail("Unsupported kind: " + ts.Debug.formatSyntaxKind(kind)); } @@ -25167,10 +25625,10 @@ var ts; } function propagateIdentifierNameFlags(node) { // An IdentifierName is allowed to be `await` - return propagateChildFlags(node) & ~8388608 /* ContainsPossibleTopLevelAwait */; + return propagateChildFlags(node) & ~16777216 /* ContainsPossibleTopLevelAwait */; } function propagatePropertyNameFlagsOfChild(node, transformFlags) { - return transformFlags | (node.transformFlags & 4096 /* PropertyNamePropagatingFlags */); + return transformFlags | (node.transformFlags & 8192 /* PropertyNamePropagatingFlags */); } function propagateChildFlags(child) { if (!child) @@ -25194,36 +25652,36 @@ var ts; */ /* @internal */ function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 172 /* FirstTypeNode */ && kind <= 195 /* LastTypeNode */) { + if (kind >= 173 /* FirstTypeNode */ && kind <= 196 /* LastTypeNode */) { return -2 /* TypeExcludes */; } switch (kind) { - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 199 /* ArrayLiteralExpression */: - return 536879104 /* ArrayLiteralOrCallOrNewExcludes */; - case 256 /* ModuleDeclaration */: - return 546379776 /* ModuleExcludes */; - case 160 /* Parameter */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 200 /* ArrayLiteralExpression */: + return 536887296 /* ArrayLiteralOrCallOrNewExcludes */; + case 257 /* ModuleDeclaration */: + return 555888640 /* ModuleExcludes */; + case 161 /* Parameter */: return 536870912 /* ParameterExcludes */; - case 209 /* ArrowFunction */: - return 547309568 /* ArrowFunctionExcludes */; - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - return 547313664 /* FunctionExcludes */; - case 250 /* VariableDeclarationList */: - return 537018368 /* VariableDeclarationListExcludes */; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - return 536905728 /* ClassExcludes */; - case 166 /* Constructor */: - return 547311616 /* ConstructorExcludes */; - case 163 /* PropertyDeclaration */: - return 536875008 /* PropertyExcludes */; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - return 538923008 /* MethodOrAccessorExcludes */; + case 210 /* ArrowFunction */: + return 557748224 /* ArrowFunctionExcludes */; + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + return 557756416 /* FunctionExcludes */; + case 251 /* VariableDeclarationList */: + return 537165824 /* VariableDeclarationListExcludes */; + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + return 536940544 /* ClassExcludes */; + case 167 /* Constructor */: + return 557752320 /* ConstructorExcludes */; + case 164 /* PropertyDeclaration */: + return 536879104 /* PropertyExcludes */; + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return 540975104 /* MethodOrAccessorExcludes */; case 128 /* AnyKeyword */: case 144 /* NumberKeyword */: case 155 /* BigIntKeyword */: @@ -25233,30 +25691,30 @@ var ts; case 131 /* BooleanKeyword */: case 148 /* SymbolKeyword */: case 113 /* VoidKeyword */: - case 159 /* TypeParameter */: - case 162 /* PropertySignature */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 160 /* TypeParameter */: + case 163 /* PropertySignature */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return -2 /* TypeExcludes */; - case 200 /* ObjectLiteralExpression */: - return 536922112 /* ObjectLiteralExcludes */; - case 287 /* CatchClause */: - return 536887296 /* CatchClauseExcludes */; - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: - return 536879104 /* BindingPatternExcludes */; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: - case 336 /* PartiallyEmittedExpression */: - case 207 /* ParenthesizedExpression */: + case 201 /* ObjectLiteralExpression */: + return 536973312 /* ObjectLiteralExcludes */; + case 288 /* CatchClause */: + return 536903680 /* CatchClauseExcludes */; + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + return 536887296 /* BindingPatternExcludes */; + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: + case 340 /* PartiallyEmittedExpression */: + case 208 /* ParenthesizedExpression */: case 105 /* SuperKeyword */: return 536870912 /* OuterExpressionExcludes */; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return 536870912 /* PropertyAccessExcludes */; default: return 536870912 /* NodeExcludes */; @@ -25555,7 +26013,7 @@ var ts; // To avoid holding onto transformation artifacts, we keep track of any // parse tree node we are annotating. This allows us to clean them up after // all transformations have completed. - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = (_a = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)))) !== null && _a !== void 0 ? _a : ts.Debug.fail("Could not determine parsed source file."); @@ -26042,13 +26500,27 @@ var ts; /*typeArguments*/ undefined, [moduleExpression, exportsExpression]); } // Class Fields Helpers - function createClassPrivateFieldGetHelper(receiver, privateField) { + function createClassPrivateFieldGetHelper(receiver, state, kind, f) { context.requestEmitHelper(ts.classPrivateFieldGetHelper); - return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ undefined, [receiver, privateField]); + var args; + if (!f) { + args = [receiver, state, factory.createStringLiteral(kind)]; + } + else { + args = [receiver, state, factory.createStringLiteral(kind), f]; + } + return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ undefined, args); } - function createClassPrivateFieldSetHelper(receiver, privateField, value) { + function createClassPrivateFieldSetHelper(receiver, state, value, kind, f) { context.requestEmitHelper(ts.classPrivateFieldSetHelper); - return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, [receiver, privateField, value]); + var args; + if (!f) { + args = [receiver, state, value, factory.createStringLiteral(kind)]; + } + else { + args = [receiver, state, value, factory.createStringLiteral(kind), f]; + } + return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, args); } } ts.createEmitHelperFactory = createEmitHelperFactory; @@ -26288,7 +26760,6 @@ var ts; scoped: false, text: "\n var __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n };" }; - // emit output for the __export helper function ts.exportStarHelper = { name: "typescript:export-star", importName: "__exportStar", @@ -26297,18 +26768,116 @@ var ts; priority: 2, text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n };" }; - // Class fields helpers + /** + * Parameters: + * @param receiver — The object from which the private member will be read. + * @param state — One of the following: + * - A WeakMap used to read a private instance field. + * - A WeakSet used as an instance brand for private instance methods and accessors. + * - A function value that should be the undecorated class constructor used to brand check private static fields, methods, and accessors. + * @param kind — (optional pre TS 4.3, required for TS 4.3+) One of the following values: + * - undefined — Indicates a private instance field (pre TS 4.3). + * - "f" — Indicates a private field (instance or static). + * - "m" — Indicates a private method (instance or static). + * - "a" — Indicates a private accessor (instance or static). + * @param f — (optional pre TS 4.3) Depends on the arguments for state and kind: + * - If kind is "m", this should be the function corresponding to the static or instance method. + * - If kind is "a", this should be the function corresponding to the getter method, or undefined if the getter was not defined. + * - If kind is "f" and state is a function, this should be an object holding the value of a static field, or undefined if the static field declaration has not yet been evaluated. + * Usage: + * This helper will only ever be used by the compiler in the following ways: + * + * Reading from a private instance field (pre TS 4.3): + * __classPrivateFieldGet(, ) + * + * Reading from a private instance field (TS 4.3+): + * __classPrivateFieldGet(, , "f") + * + * Reading from a private instance get accessor (when defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", ) + * + * Reading from a private instance get accessor (when not defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Reading from a private instance method (TS 4.3+): + * __classPrivateFieldGet(, , "m", ) + * + * Reading from a private static field (TS 4.3+): + * __classPrivateFieldGet(, , "f", <{ value: any }>) + * + * Reading from a private static get accessor (when defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", ) + * + * Reading from a private static get accessor (when not defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Reading from a private static method (TS 4.3+): + * __classPrivateFieldGet(, , "m", ) + */ ts.classPrivateFieldGetHelper = { name: "typescript:classPrivateFieldGet", importName: "__classPrivateFieldGet", scoped: false, - text: "\n var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, privateMap) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to get private field on non-instance\");\n }\n return privateMap.get(receiver);\n };" + text: "\n var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n };" }; + /** + * Parameters: + * @param receiver — The object on which the private member will be set. + * @param state — One of the following: + * - A WeakMap used to store a private instance field. + * - A WeakSet used as an instance brand for private instance methods and accessors. + * - A function value that should be the undecorated class constructor used to brand check private static fields, methods, and accessors. + * @param value — The value to set. + * @param kind — (optional pre TS 4.3, required for TS 4.3+) One of the following values: + * - undefined — Indicates a private instance field (pre TS 4.3). + * - "f" — Indicates a private field (instance or static). + * - "m" — Indicates a private method (instance or static). + * - "a" — Indicates a private accessor (instance or static). + * @param f — (optional pre TS 4.3) Depends on the arguments for state and kind: + * - If kind is "m", this should be the function corresponding to the static or instance method. + * - If kind is "a", this should be the function corresponding to the setter method, or undefined if the setter was not defined. + * - If kind is "f" and state is a function, this should be an object holding the value of a static field, or undefined if the static field declaration has not yet been evaluated. + * Usage: + * This helper will only ever be used by the compiler in the following ways: + * + * Writing to a private instance field (pre TS 4.3): + * __classPrivateFieldSet(, , ) + * + * Writing to a private instance field (TS 4.3+): + * __classPrivateFieldSet(, , , "f") + * + * Writing to a private instance set accessor (when defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", ) + * + * Writing to a private instance set accessor (when not defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Writing to a private instance method (TS 4.3+): + * __classPrivateFieldSet(, , , "m", ) + * NOTE: This always results in a runtime error. + * + * Writing to a private static field (TS 4.3+): + * __classPrivateFieldSet(, , , "f", <{ value: any }>) + * + * Writing to a private static set accessor (when defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", ) + * + * Writing to a private static set accessor (when not defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Writing to a private static method (TS 4.3+): + * __classPrivateFieldSet(, , , "m", ) + * NOTE: This always results in a runtime error. + */ ts.classPrivateFieldSetHelper = { name: "typescript:classPrivateFieldSet", importName: "__classPrivateFieldSet", scoped: false, - text: "\n var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, privateMap, value) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to set private field on non-instance\");\n }\n privateMap.set(receiver, value);\n return value;\n };" + text: "\n var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n };" }; var allUnscopedEmitHelpers; function getAllUnscopedEmitHelpers() { @@ -26397,25 +26966,93 @@ var ts; return node.kind === 17 /* TemplateTail */; } ts.isTemplateTail = isTemplateTail; + // Punctuation + function isDotDotDotToken(node) { + return node.kind === 25 /* DotDotDotToken */; + } + ts.isDotDotDotToken = isDotDotDotToken; + /*@internal*/ + function isCommaToken(node) { + return node.kind === 27 /* CommaToken */; + } + ts.isCommaToken = isCommaToken; + function isPlusToken(node) { + return node.kind === 39 /* PlusToken */; + } + ts.isPlusToken = isPlusToken; + function isMinusToken(node) { + return node.kind === 40 /* MinusToken */; + } + ts.isMinusToken = isMinusToken; + function isAsteriskToken(node) { + return node.kind === 41 /* AsteriskToken */; + } + ts.isAsteriskToken = isAsteriskToken; + /*@internal*/ + function isExclamationToken(node) { + return node.kind === 53 /* ExclamationToken */; + } + ts.isExclamationToken = isExclamationToken; + /*@internal*/ + function isQuestionToken(node) { + return node.kind === 57 /* QuestionToken */; + } + ts.isQuestionToken = isQuestionToken; + /*@internal*/ + function isColonToken(node) { + return node.kind === 58 /* ColonToken */; + } + ts.isColonToken = isColonToken; + /*@internal*/ + function isQuestionDotToken(node) { + return node.kind === 28 /* QuestionDotToken */; + } + ts.isQuestionDotToken = isQuestionDotToken; + /*@internal*/ + function isEqualsGreaterThanToken(node) { + return node.kind === 38 /* EqualsGreaterThanToken */; + } + ts.isEqualsGreaterThanToken = isEqualsGreaterThanToken; // Identifiers function isIdentifier(node) { return node.kind === 78 /* Identifier */; } ts.isIdentifier = isIdentifier; - // Names - function isQualifiedName(node) { - return node.kind === 157 /* QualifiedName */; - } - ts.isQualifiedName = isQualifiedName; - function isComputedPropertyName(node) { - return node.kind === 158 /* ComputedPropertyName */; - } - ts.isComputedPropertyName = isComputedPropertyName; function isPrivateIdentifier(node) { return node.kind === 79 /* PrivateIdentifier */; } ts.isPrivateIdentifier = isPrivateIdentifier; - // Tokens + // Reserved Words + /* @internal */ + function isExportModifier(node) { + return node.kind === 92 /* ExportKeyword */; + } + ts.isExportModifier = isExportModifier; + /* @internal */ + function isAsyncModifier(node) { + return node.kind === 129 /* AsyncKeyword */; + } + ts.isAsyncModifier = isAsyncModifier; + /* @internal */ + function isAssertsKeyword(node) { + return node.kind === 127 /* AssertsKeyword */; + } + ts.isAssertsKeyword = isAssertsKeyword; + /* @internal */ + function isAwaitKeyword(node) { + return node.kind === 130 /* AwaitKeyword */; + } + ts.isAwaitKeyword = isAwaitKeyword; + /* @internal */ + function isReadonlyKeyword(node) { + return node.kind === 142 /* ReadonlyKeyword */; + } + ts.isReadonlyKeyword = isReadonlyKeyword; + /* @internal */ + function isStaticModifier(node) { + return node.kind === 123 /* StaticKeyword */; + } + ts.isStaticModifier = isStaticModifier; /*@internal*/ function isSuperKeyword(node) { return node.kind === 105 /* SuperKeyword */; @@ -26426,597 +27063,591 @@ var ts; return node.kind === 99 /* ImportKeyword */; } ts.isImportKeyword = isImportKeyword; - /*@internal*/ - function isCommaToken(node) { - return node.kind === 27 /* CommaToken */; - } - ts.isCommaToken = isCommaToken; - /*@internal*/ - function isQuestionToken(node) { - return node.kind === 57 /* QuestionToken */; + // Names + function isQualifiedName(node) { + return node.kind === 158 /* QualifiedName */; } - ts.isQuestionToken = isQuestionToken; - /*@internal*/ - function isExclamationToken(node) { - return node.kind === 53 /* ExclamationToken */; + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 159 /* ComputedPropertyName */; } - ts.isExclamationToken = isExclamationToken; + ts.isComputedPropertyName = isComputedPropertyName; // Signature elements function isTypeParameterDeclaration(node) { - return node.kind === 159 /* TypeParameter */; + return node.kind === 160 /* TypeParameter */; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; // TODO(rbuckton): Rename to 'isParameterDeclaration' function isParameter(node) { - return node.kind === 160 /* Parameter */; + return node.kind === 161 /* Parameter */; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 161 /* Decorator */; + return node.kind === 162 /* Decorator */; } ts.isDecorator = isDecorator; // TypeMember function isPropertySignature(node) { - return node.kind === 162 /* PropertySignature */; + return node.kind === 163 /* PropertySignature */; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 163 /* PropertyDeclaration */; + return node.kind === 164 /* PropertyDeclaration */; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 164 /* MethodSignature */; + return node.kind === 165 /* MethodSignature */; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 165 /* MethodDeclaration */; + return node.kind === 166 /* MethodDeclaration */; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 166 /* Constructor */; + return node.kind === 167 /* Constructor */; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 167 /* GetAccessor */; + return node.kind === 168 /* GetAccessor */; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 168 /* SetAccessor */; + return node.kind === 169 /* SetAccessor */; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 169 /* CallSignature */; + return node.kind === 170 /* CallSignature */; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 170 /* ConstructSignature */; + return node.kind === 171 /* ConstructSignature */; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 171 /* IndexSignature */; + return node.kind === 172 /* IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; // Type function isTypePredicateNode(node) { - return node.kind === 172 /* TypePredicate */; + return node.kind === 173 /* TypePredicate */; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 173 /* TypeReference */; + return node.kind === 174 /* TypeReference */; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 174 /* FunctionType */; + return node.kind === 175 /* FunctionType */; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 175 /* ConstructorType */; + return node.kind === 176 /* ConstructorType */; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 176 /* TypeQuery */; + return node.kind === 177 /* TypeQuery */; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 177 /* TypeLiteral */; + return node.kind === 178 /* TypeLiteral */; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 178 /* ArrayType */; + return node.kind === 179 /* ArrayType */; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 179 /* TupleType */; + return node.kind === 180 /* TupleType */; } ts.isTupleTypeNode = isTupleTypeNode; function isNamedTupleMember(node) { - return node.kind === 192 /* NamedTupleMember */; + return node.kind === 193 /* NamedTupleMember */; } ts.isNamedTupleMember = isNamedTupleMember; function isOptionalTypeNode(node) { - return node.kind === 180 /* OptionalType */; + return node.kind === 181 /* OptionalType */; } ts.isOptionalTypeNode = isOptionalTypeNode; function isRestTypeNode(node) { - return node.kind === 181 /* RestType */; + return node.kind === 182 /* RestType */; } ts.isRestTypeNode = isRestTypeNode; function isUnionTypeNode(node) { - return node.kind === 182 /* UnionType */; + return node.kind === 183 /* UnionType */; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 183 /* IntersectionType */; + return node.kind === 184 /* IntersectionType */; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isConditionalTypeNode(node) { - return node.kind === 184 /* ConditionalType */; + return node.kind === 185 /* ConditionalType */; } ts.isConditionalTypeNode = isConditionalTypeNode; function isInferTypeNode(node) { - return node.kind === 185 /* InferType */; + return node.kind === 186 /* InferType */; } ts.isInferTypeNode = isInferTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 186 /* ParenthesizedType */; + return node.kind === 187 /* ParenthesizedType */; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 187 /* ThisType */; + return node.kind === 188 /* ThisType */; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 188 /* TypeOperator */; + return node.kind === 189 /* TypeOperator */; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 189 /* IndexedAccessType */; + return node.kind === 190 /* IndexedAccessType */; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 190 /* MappedType */; + return node.kind === 191 /* MappedType */; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 191 /* LiteralType */; + return node.kind === 192 /* LiteralType */; } ts.isLiteralTypeNode = isLiteralTypeNode; function isImportTypeNode(node) { - return node.kind === 195 /* ImportType */; + return node.kind === 196 /* ImportType */; } ts.isImportTypeNode = isImportTypeNode; function isTemplateLiteralTypeSpan(node) { - return node.kind === 194 /* TemplateLiteralTypeSpan */; + return node.kind === 195 /* TemplateLiteralTypeSpan */; } ts.isTemplateLiteralTypeSpan = isTemplateLiteralTypeSpan; function isTemplateLiteralTypeNode(node) { - return node.kind === 193 /* TemplateLiteralType */; + return node.kind === 194 /* TemplateLiteralType */; } ts.isTemplateLiteralTypeNode = isTemplateLiteralTypeNode; // Binding patterns function isObjectBindingPattern(node) { - return node.kind === 196 /* ObjectBindingPattern */; + return node.kind === 197 /* ObjectBindingPattern */; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 197 /* ArrayBindingPattern */; + return node.kind === 198 /* ArrayBindingPattern */; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 198 /* BindingElement */; + return node.kind === 199 /* BindingElement */; } ts.isBindingElement = isBindingElement; // Expression function isArrayLiteralExpression(node) { - return node.kind === 199 /* ArrayLiteralExpression */; + return node.kind === 200 /* ArrayLiteralExpression */; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 200 /* ObjectLiteralExpression */; + return node.kind === 201 /* ObjectLiteralExpression */; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 201 /* PropertyAccessExpression */; + return node.kind === 202 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 202 /* ElementAccessExpression */; + return node.kind === 203 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 203 /* CallExpression */; + return node.kind === 204 /* CallExpression */; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 204 /* NewExpression */; + return node.kind === 205 /* NewExpression */; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 205 /* TaggedTemplateExpression */; + return node.kind === 206 /* TaggedTemplateExpression */; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertionExpression(node) { - return node.kind === 206 /* TypeAssertionExpression */; + return node.kind === 207 /* TypeAssertionExpression */; } ts.isTypeAssertionExpression = isTypeAssertionExpression; function isParenthesizedExpression(node) { - return node.kind === 207 /* ParenthesizedExpression */; + return node.kind === 208 /* ParenthesizedExpression */; } ts.isParenthesizedExpression = isParenthesizedExpression; function isFunctionExpression(node) { - return node.kind === 208 /* FunctionExpression */; + return node.kind === 209 /* FunctionExpression */; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 209 /* ArrowFunction */; + return node.kind === 210 /* ArrowFunction */; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 210 /* DeleteExpression */; + return node.kind === 211 /* DeleteExpression */; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 211 /* TypeOfExpression */; + return node.kind === 212 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 212 /* VoidExpression */; + return node.kind === 213 /* VoidExpression */; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 213 /* AwaitExpression */; + return node.kind === 214 /* AwaitExpression */; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 214 /* PrefixUnaryExpression */; + return node.kind === 215 /* PrefixUnaryExpression */; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 215 /* PostfixUnaryExpression */; + return node.kind === 216 /* PostfixUnaryExpression */; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 216 /* BinaryExpression */; + return node.kind === 217 /* BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 217 /* ConditionalExpression */; + return node.kind === 218 /* ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 218 /* TemplateExpression */; + return node.kind === 219 /* TemplateExpression */; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 219 /* YieldExpression */; + return node.kind === 220 /* YieldExpression */; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 220 /* SpreadElement */; + return node.kind === 221 /* SpreadElement */; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 221 /* ClassExpression */; + return node.kind === 222 /* ClassExpression */; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 222 /* OmittedExpression */; + return node.kind === 223 /* OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 223 /* ExpressionWithTypeArguments */; + return node.kind === 224 /* ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 224 /* AsExpression */; + return node.kind === 225 /* AsExpression */; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 225 /* NonNullExpression */; + return node.kind === 226 /* NonNullExpression */; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 226 /* MetaProperty */; + return node.kind === 227 /* MetaProperty */; } ts.isMetaProperty = isMetaProperty; function isSyntheticExpression(node) { - return node.kind === 227 /* SyntheticExpression */; + return node.kind === 228 /* SyntheticExpression */; } ts.isSyntheticExpression = isSyntheticExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 336 /* PartiallyEmittedExpression */; + return node.kind === 340 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isCommaListExpression(node) { - return node.kind === 337 /* CommaListExpression */; + return node.kind === 341 /* CommaListExpression */; } ts.isCommaListExpression = isCommaListExpression; // Misc function isTemplateSpan(node) { - return node.kind === 228 /* TemplateSpan */; + return node.kind === 229 /* TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 229 /* SemicolonClassElement */; + return node.kind === 230 /* SemicolonClassElement */; } ts.isSemicolonClassElement = isSemicolonClassElement; // Elements function isBlock(node) { - return node.kind === 230 /* Block */; + return node.kind === 231 /* Block */; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 232 /* VariableStatement */; + return node.kind === 233 /* VariableStatement */; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 231 /* EmptyStatement */; + return node.kind === 232 /* EmptyStatement */; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 233 /* ExpressionStatement */; + return node.kind === 234 /* ExpressionStatement */; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 234 /* IfStatement */; + return node.kind === 235 /* IfStatement */; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 235 /* DoStatement */; + return node.kind === 236 /* DoStatement */; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 236 /* WhileStatement */; + return node.kind === 237 /* WhileStatement */; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 237 /* ForStatement */; + return node.kind === 238 /* ForStatement */; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 238 /* ForInStatement */; + return node.kind === 239 /* ForInStatement */; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 239 /* ForOfStatement */; + return node.kind === 240 /* ForOfStatement */; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 240 /* ContinueStatement */; + return node.kind === 241 /* ContinueStatement */; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 241 /* BreakStatement */; + return node.kind === 242 /* BreakStatement */; } ts.isBreakStatement = isBreakStatement; function isReturnStatement(node) { - return node.kind === 242 /* ReturnStatement */; + return node.kind === 243 /* ReturnStatement */; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 243 /* WithStatement */; + return node.kind === 244 /* WithStatement */; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 244 /* SwitchStatement */; + return node.kind === 245 /* SwitchStatement */; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 245 /* LabeledStatement */; + return node.kind === 246 /* LabeledStatement */; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 246 /* ThrowStatement */; + return node.kind === 247 /* ThrowStatement */; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 247 /* TryStatement */; + return node.kind === 248 /* TryStatement */; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 248 /* DebuggerStatement */; + return node.kind === 249 /* DebuggerStatement */; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 249 /* VariableDeclaration */; + return node.kind === 250 /* VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 250 /* VariableDeclarationList */; + return node.kind === 251 /* VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 251 /* FunctionDeclaration */; + return node.kind === 252 /* FunctionDeclaration */; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 252 /* ClassDeclaration */; + return node.kind === 253 /* ClassDeclaration */; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 253 /* InterfaceDeclaration */; + return node.kind === 254 /* InterfaceDeclaration */; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 254 /* TypeAliasDeclaration */; + return node.kind === 255 /* TypeAliasDeclaration */; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 255 /* EnumDeclaration */; + return node.kind === 256 /* EnumDeclaration */; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 256 /* ModuleDeclaration */; + return node.kind === 257 /* ModuleDeclaration */; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 257 /* ModuleBlock */; + return node.kind === 258 /* ModuleBlock */; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 258 /* CaseBlock */; + return node.kind === 259 /* CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 259 /* NamespaceExportDeclaration */; + return node.kind === 260 /* NamespaceExportDeclaration */; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */; + return node.kind === 261 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 261 /* ImportDeclaration */; + return node.kind === 262 /* ImportDeclaration */; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 262 /* ImportClause */; + return node.kind === 263 /* ImportClause */; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 263 /* NamespaceImport */; + return node.kind === 264 /* NamespaceImport */; } ts.isNamespaceImport = isNamespaceImport; function isNamespaceExport(node) { - return node.kind === 269 /* NamespaceExport */; + return node.kind === 270 /* NamespaceExport */; } ts.isNamespaceExport = isNamespaceExport; function isNamedImports(node) { - return node.kind === 264 /* NamedImports */; + return node.kind === 265 /* NamedImports */; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 265 /* ImportSpecifier */; + return node.kind === 266 /* ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 266 /* ExportAssignment */; + return node.kind === 267 /* ExportAssignment */; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 267 /* ExportDeclaration */; + return node.kind === 268 /* ExportDeclaration */; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 268 /* NamedExports */; + return node.kind === 269 /* NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 270 /* ExportSpecifier */; + return node.kind === 271 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 271 /* MissingDeclaration */; + return node.kind === 272 /* MissingDeclaration */; } ts.isMissingDeclaration = isMissingDeclaration; function isNotEmittedStatement(node) { - return node.kind === 335 /* NotEmittedStatement */; + return node.kind === 339 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ function isSyntheticReference(node) { - return node.kind === 340 /* SyntheticReferenceExpression */; + return node.kind === 344 /* SyntheticReferenceExpression */; } ts.isSyntheticReference = isSyntheticReference; /* @internal */ function isMergeDeclarationMarker(node) { - return node.kind === 338 /* MergeDeclarationMarker */; + return node.kind === 342 /* MergeDeclarationMarker */; } ts.isMergeDeclarationMarker = isMergeDeclarationMarker; /* @internal */ function isEndOfDeclarationMarker(node) { - return node.kind === 339 /* EndOfDeclarationMarker */; + return node.kind === 343 /* EndOfDeclarationMarker */; } ts.isEndOfDeclarationMarker = isEndOfDeclarationMarker; // Module References function isExternalModuleReference(node) { - return node.kind === 272 /* ExternalModuleReference */; + return node.kind === 273 /* ExternalModuleReference */; } ts.isExternalModuleReference = isExternalModuleReference; // JSX function isJsxElement(node) { - return node.kind === 273 /* JsxElement */; + return node.kind === 274 /* JsxElement */; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 274 /* JsxSelfClosingElement */; + return node.kind === 275 /* JsxSelfClosingElement */; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 275 /* JsxOpeningElement */; + return node.kind === 276 /* JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 276 /* JsxClosingElement */; + return node.kind === 277 /* JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxFragment(node) { - return node.kind === 277 /* JsxFragment */; + return node.kind === 278 /* JsxFragment */; } ts.isJsxFragment = isJsxFragment; function isJsxOpeningFragment(node) { - return node.kind === 278 /* JsxOpeningFragment */; + return node.kind === 279 /* JsxOpeningFragment */; } ts.isJsxOpeningFragment = isJsxOpeningFragment; function isJsxClosingFragment(node) { - return node.kind === 279 /* JsxClosingFragment */; + return node.kind === 280 /* JsxClosingFragment */; } ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 280 /* JsxAttribute */; + return node.kind === 281 /* JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 281 /* JsxAttributes */; + return node.kind === 282 /* JsxAttributes */; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 282 /* JsxSpreadAttribute */; + return node.kind === 283 /* JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 283 /* JsxExpression */; + return node.kind === 284 /* JsxExpression */; } ts.isJsxExpression = isJsxExpression; // Clauses function isCaseClause(node) { - return node.kind === 284 /* CaseClause */; + return node.kind === 285 /* CaseClause */; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 285 /* DefaultClause */; + return node.kind === 286 /* DefaultClause */; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 286 /* HeritageClause */; + return node.kind === 287 /* HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 287 /* CatchClause */; + return node.kind === 288 /* CatchClause */; } ts.isCatchClause = isCatchClause; // Property assignments function isPropertyAssignment(node) { - return node.kind === 288 /* PropertyAssignment */; + return node.kind === 289 /* PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 289 /* ShorthandPropertyAssignment */; + return node.kind === 290 /* ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 290 /* SpreadAssignment */; + return node.kind === 291 /* SpreadAssignment */; } ts.isSpreadAssignment = isSpreadAssignment; // Enum function isEnumMember(node) { - return node.kind === 291 /* EnumMember */; + return node.kind === 292 /* EnumMember */; } ts.isEnumMember = isEnumMember; // Unparsed // TODO(rbuckton): isUnparsedPrologue function isUnparsedPrepend(node) { - return node.kind === 293 /* UnparsedPrepend */; + return node.kind === 294 /* UnparsedPrepend */; } ts.isUnparsedPrepend = isUnparsedPrepend; // TODO(rbuckton): isUnparsedText @@ -27024,156 +27655,164 @@ var ts; // TODO(rbuckton): isUnparsedSyntheticReference // Top-level nodes function isSourceFile(node) { - return node.kind === 297 /* SourceFile */; + return node.kind === 298 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 298 /* Bundle */; + return node.kind === 299 /* Bundle */; } ts.isBundle = isBundle; function isUnparsedSource(node) { - return node.kind === 299 /* UnparsedSource */; + return node.kind === 300 /* UnparsedSource */; } ts.isUnparsedSource = isUnparsedSource; // TODO(rbuckton): isInputFiles // JSDoc Elements function isJSDocTypeExpression(node) { - return node.kind === 301 /* JSDocTypeExpression */; + return node.kind === 302 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocNameReference(node) { - return node.kind === 302 /* JSDocNameReference */; + return node.kind === 303 /* JSDocNameReference */; } ts.isJSDocNameReference = isJSDocNameReference; + function isJSDocLink(node) { + return node.kind === 316 /* JSDocLink */; + } + ts.isJSDocLink = isJSDocLink; function isJSDocAllType(node) { - return node.kind === 303 /* JSDocAllType */; + return node.kind === 304 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 304 /* JSDocUnknownType */; + return node.kind === 305 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 305 /* JSDocNullableType */; + return node.kind === 306 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 306 /* JSDocNonNullableType */; + return node.kind === 307 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 307 /* JSDocOptionalType */; + return node.kind === 308 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 308 /* JSDocFunctionType */; + return node.kind === 309 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 309 /* JSDocVariadicType */; + return node.kind === 310 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDocNamepathType(node) { - return node.kind === 310 /* JSDocNamepathType */; + return node.kind === 311 /* JSDocNamepathType */; } ts.isJSDocNamepathType = isJSDocNamepathType; function isJSDoc(node) { - return node.kind === 311 /* JSDocComment */; + return node.kind === 312 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocTypeLiteral(node) { - return node.kind === 312 /* JSDocTypeLiteral */; + return node.kind === 314 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; function isJSDocSignature(node) { - return node.kind === 313 /* JSDocSignature */; + return node.kind === 315 /* JSDocSignature */; } ts.isJSDocSignature = isJSDocSignature; // JSDoc Tags function isJSDocAugmentsTag(node) { - return node.kind === 315 /* JSDocAugmentsTag */; + return node.kind === 318 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocAuthorTag(node) { - return node.kind === 317 /* JSDocAuthorTag */; + return node.kind === 320 /* JSDocAuthorTag */; } ts.isJSDocAuthorTag = isJSDocAuthorTag; function isJSDocClassTag(node) { - return node.kind === 319 /* JSDocClassTag */; + return node.kind === 322 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocCallbackTag(node) { - return node.kind === 324 /* JSDocCallbackTag */; + return node.kind === 328 /* JSDocCallbackTag */; } ts.isJSDocCallbackTag = isJSDocCallbackTag; function isJSDocPublicTag(node) { - return node.kind === 320 /* JSDocPublicTag */; + return node.kind === 323 /* JSDocPublicTag */; } ts.isJSDocPublicTag = isJSDocPublicTag; function isJSDocPrivateTag(node) { - return node.kind === 321 /* JSDocPrivateTag */; + return node.kind === 324 /* JSDocPrivateTag */; } ts.isJSDocPrivateTag = isJSDocPrivateTag; function isJSDocProtectedTag(node) { - return node.kind === 322 /* JSDocProtectedTag */; + return node.kind === 325 /* JSDocProtectedTag */; } ts.isJSDocProtectedTag = isJSDocProtectedTag; function isJSDocReadonlyTag(node) { - return node.kind === 323 /* JSDocReadonlyTag */; + return node.kind === 326 /* JSDocReadonlyTag */; } ts.isJSDocReadonlyTag = isJSDocReadonlyTag; + function isJSDocOverrideTag(node) { + return node.kind === 327 /* JSDocOverrideTag */; + } + ts.isJSDocOverrideTag = isJSDocOverrideTag; function isJSDocDeprecatedTag(node) { - return node.kind === 318 /* JSDocDeprecatedTag */; + return node.kind === 321 /* JSDocDeprecatedTag */; } ts.isJSDocDeprecatedTag = isJSDocDeprecatedTag; function isJSDocSeeTag(node) { - return node.kind === 332 /* JSDocSeeTag */; + return node.kind === 336 /* JSDocSeeTag */; } ts.isJSDocSeeTag = isJSDocSeeTag; function isJSDocEnumTag(node) { - return node.kind === 325 /* JSDocEnumTag */; + return node.kind === 329 /* JSDocEnumTag */; } ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocParameterTag(node) { - return node.kind === 326 /* JSDocParameterTag */; + return node.kind === 330 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 327 /* JSDocReturnTag */; + return node.kind === 331 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocThisTag(node) { - return node.kind === 328 /* JSDocThisTag */; + return node.kind === 332 /* JSDocThisTag */; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocTypeTag(node) { - return node.kind === 329 /* JSDocTypeTag */; + return node.kind === 333 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 330 /* JSDocTemplateTag */; + return node.kind === 334 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 331 /* JSDocTypedefTag */; + return node.kind === 335 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocUnknownTag(node) { - return node.kind === 314 /* JSDocTag */; + return node.kind === 317 /* JSDocTag */; } ts.isJSDocUnknownTag = isJSDocUnknownTag; function isJSDocPropertyTag(node) { - return node.kind === 333 /* JSDocPropertyTag */; + return node.kind === 337 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocImplementsTag(node) { - return node.kind === 316 /* JSDocImplementsTag */; + return node.kind === 319 /* JSDocImplementsTag */; } ts.isJSDocImplementsTag = isJSDocImplementsTag; // Synthesized list /* @internal */ function isSyntaxList(n) { - return n.kind === 334 /* SyntaxList */; + return n.kind === 338 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; })(ts || (ts = {})); @@ -27190,7 +27829,7 @@ var ts; return ts.setTextRange(factory.createElementAccessExpression(target, memberName.expression), location); } else { - var expression = ts.setTextRange(ts.isIdentifierOrPrivateIdentifier(memberName) + var expression = ts.setTextRange(ts.isMemberName(memberName) ? factory.createPropertyAccessExpression(target, memberName) : factory.createElementAccessExpression(target, memberName), memberName); ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */; @@ -27372,14 +28011,14 @@ var ts; ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals."); } switch (property.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return createExpressionForAccessorDeclaration(factory, node.properties, property, receiver, !!node.multiLine); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return createExpressionForPropertyAssignment(factory, property, receiver); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(factory, property, receiver); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return createExpressionForMethodDeclaration(factory, property, receiver); } } @@ -27432,21 +28071,21 @@ var ts; } ts.startsWithUseStrict = startsWithUseStrict; function isCommaSequence(node) { - return node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || - node.kind === 337 /* CommaListExpression */; + return node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || + node.kind === 341 /* CommaListExpression */; } ts.isCommaSequence = isCommaSequence; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 15 /* All */; } switch (node.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return (kinds & 1 /* Parentheses */) !== 0; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return (kinds & 2 /* TypeAssertions */) !== 0; - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return (kinds & 4 /* NonNullAssertions */) !== 0; - case 336 /* PartiallyEmittedExpression */: + case 340 /* PartiallyEmittedExpression */: return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -27567,10 +28206,10 @@ var ts; var name = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name) ? name : factory.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 261 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 262 /* ImportDeclaration */ && node.importClause) { return factory.getGeneratedNameForNode(node); } - if (node.kind === 267 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 268 /* ExportDeclaration */ && node.moduleSpecifier) { return factory.getGeneratedNameForNode(node); } return undefined; @@ -27689,7 +28328,7 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // `b` in `({ a: b } = ...)` // `b` in `({ a: b = 1 } = ...)` // `{b}` in `({ a: {b} } = ...)` @@ -27701,11 +28340,11 @@ var ts; // `b[0]` in `({ a: b[0] } = ...)` // `b[0]` in `({ a: b[0] = 1 } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: // `a` in `({ a } = ...)` // `a` in `({ a = 1 } = ...)` return bindingElement.name; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } @@ -27737,12 +28376,12 @@ var ts; */ function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 160 /* Parameter */: - case 198 /* BindingElement */: + case 161 /* Parameter */: + case 199 /* BindingElement */: // `...` in `let [...a] = ...` return bindingElement.dotDotDotToken; - case 220 /* SpreadElement */: - case 290 /* SpreadAssignment */: + case 221 /* SpreadElement */: + case 291 /* SpreadAssignment */: // `...` in `[...a] = ...` return bindingElement; } @@ -27760,7 +28399,7 @@ var ts; ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 198 /* BindingElement */: + case 199 /* BindingElement */: // `a` in `let { a: b } = ...` // `[a]` in `let { [a]: b } = ...` // `"a"` in `let { "a": b } = ...` @@ -27775,7 +28414,7 @@ var ts; : propertyName; } break; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // `a` in `({ a: b } = ...)` // `[a]` in `({ [a]: b } = ...)` // `"a"` in `({ "a": b } = ...)` @@ -27790,7 +28429,7 @@ var ts; : propertyName; } break; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) { return ts.Debug.failBadSyntaxKind(bindingElement.name); @@ -27813,13 +28452,13 @@ var ts; */ function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: - case 199 /* ArrayLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + case 200 /* ArrayLiteralExpression */: // `a` in `{a}` // `a` in `[a]` return name.elements; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: // `a` in `{a}` return name.properties; } @@ -27840,46 +28479,294 @@ var ts; ts.getJSDocTypeAliasName = getJSDocTypeAliasName; function canHaveModifiers(node) { var kind = node.kind; - return kind === 160 /* Parameter */ - || kind === 162 /* PropertySignature */ - || kind === 163 /* PropertyDeclaration */ - || kind === 164 /* MethodSignature */ - || kind === 165 /* MethodDeclaration */ - || kind === 166 /* Constructor */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 171 /* IndexSignature */ - || kind === 208 /* FunctionExpression */ - || kind === 209 /* ArrowFunction */ - || kind === 221 /* ClassExpression */ - || kind === 232 /* VariableStatement */ - || kind === 251 /* FunctionDeclaration */ - || kind === 252 /* ClassDeclaration */ - || kind === 253 /* InterfaceDeclaration */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 255 /* EnumDeclaration */ - || kind === 256 /* ModuleDeclaration */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 261 /* ImportDeclaration */ - || kind === 266 /* ExportAssignment */ - || kind === 267 /* ExportDeclaration */; + return kind === 161 /* Parameter */ + || kind === 163 /* PropertySignature */ + || kind === 164 /* PropertyDeclaration */ + || kind === 165 /* MethodSignature */ + || kind === 166 /* MethodDeclaration */ + || kind === 167 /* Constructor */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 172 /* IndexSignature */ + || kind === 209 /* FunctionExpression */ + || kind === 210 /* ArrowFunction */ + || kind === 222 /* ClassExpression */ + || kind === 233 /* VariableStatement */ + || kind === 252 /* FunctionDeclaration */ + || kind === 253 /* ClassDeclaration */ + || kind === 254 /* InterfaceDeclaration */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 256 /* EnumDeclaration */ + || kind === 257 /* ModuleDeclaration */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 262 /* ImportDeclaration */ + || kind === 267 /* ExportAssignment */ + || kind === 268 /* ExportDeclaration */; } ts.canHaveModifiers = canHaveModifiers; - /* @internal */ - function isExportModifier(node) { - return node.kind === 92 /* ExportKeyword */; - } - ts.isExportModifier = isExportModifier; - /* @internal */ - function isAsyncModifier(node) { - return node.kind === 129 /* AsyncKeyword */; - } - ts.isAsyncModifier = isAsyncModifier; - /* @internal */ - function isStaticModifier(node) { - return node.kind === 123 /* StaticKeyword */; + ts.isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); + ts.isQuestionOrExclamationToken = ts.or(ts.isQuestionToken, ts.isExclamationToken); + ts.isIdentifierOrThisTypeNode = ts.or(ts.isIdentifier, ts.isThisTypeNode); + ts.isReadonlyKeywordOrPlusOrMinusToken = ts.or(ts.isReadonlyKeyword, ts.isPlusToken, ts.isMinusToken); + ts.isQuestionOrPlusOrMinusToken = ts.or(ts.isQuestionToken, ts.isPlusToken, ts.isMinusToken); + ts.isModuleName = ts.or(ts.isIdentifier, ts.isStringLiteral); + function isLiteralTypeLikeExpression(node) { + var kind = node.kind; + return kind === 103 /* NullKeyword */ + || kind === 109 /* TrueKeyword */ + || kind === 94 /* FalseKeyword */ + || ts.isLiteralExpression(node) + || ts.isPrefixUnaryExpression(node); + } + ts.isLiteralTypeLikeExpression = isLiteralTypeLikeExpression; + function isExponentiationOperator(kind) { + return kind === 42 /* AsteriskAsteriskToken */; + } + function isMultiplicativeOperator(kind) { + return kind === 41 /* AsteriskToken */ + || kind === 43 /* SlashToken */ + || kind === 44 /* PercentToken */; + } + function isMultiplicativeOperatorOrHigher(kind) { + return isExponentiationOperator(kind) + || isMultiplicativeOperator(kind); + } + function isAdditiveOperator(kind) { + return kind === 39 /* PlusToken */ + || kind === 40 /* MinusToken */; + } + function isAdditiveOperatorOrHigher(kind) { + return isAdditiveOperator(kind) + || isMultiplicativeOperatorOrHigher(kind); + } + function isShiftOperator(kind) { + return kind === 47 /* LessThanLessThanToken */ + || kind === 48 /* GreaterThanGreaterThanToken */ + || kind === 49 /* GreaterThanGreaterThanGreaterThanToken */; + } + function isShiftOperatorOrHigher(kind) { + return isShiftOperator(kind) + || isAdditiveOperatorOrHigher(kind); + } + function isRelationalOperator(kind) { + return kind === 29 /* LessThanToken */ + || kind === 32 /* LessThanEqualsToken */ + || kind === 31 /* GreaterThanToken */ + || kind === 33 /* GreaterThanEqualsToken */ + || kind === 101 /* InstanceOfKeyword */ + || kind === 100 /* InKeyword */; + } + function isRelationalOperatorOrHigher(kind) { + return isRelationalOperator(kind) + || isShiftOperatorOrHigher(kind); + } + function isEqualityOperator(kind) { + return kind === 34 /* EqualsEqualsToken */ + || kind === 36 /* EqualsEqualsEqualsToken */ + || kind === 35 /* ExclamationEqualsToken */ + || kind === 37 /* ExclamationEqualsEqualsToken */; + } + function isEqualityOperatorOrHigher(kind) { + return isEqualityOperator(kind) + || isRelationalOperatorOrHigher(kind); + } + function isBitwiseOperator(kind) { + return kind === 50 /* AmpersandToken */ + || kind === 51 /* BarToken */ + || kind === 52 /* CaretToken */; + } + function isBitwiseOperatorOrHigher(kind) { + return isBitwiseOperator(kind) + || isEqualityOperatorOrHigher(kind); + } + // NOTE: The version in utilities includes ExclamationToken, which is not a binary operator. + function isLogicalOperator(kind) { + return kind === 55 /* AmpersandAmpersandToken */ + || kind === 56 /* BarBarToken */; + } + function isLogicalOperatorOrHigher(kind) { + return isLogicalOperator(kind) + || isBitwiseOperatorOrHigher(kind); + } + function isAssignmentOperatorOrHigher(kind) { + return kind === 60 /* QuestionQuestionToken */ + || isLogicalOperatorOrHigher(kind) + || ts.isAssignmentOperator(kind); + } + function isBinaryOperator(kind) { + return isAssignmentOperatorOrHigher(kind) + || kind === 27 /* CommaToken */; + } + function isBinaryOperatorToken(node) { + return isBinaryOperator(node.kind); + } + ts.isBinaryOperatorToken = isBinaryOperatorToken; + var BinaryExpressionState; + (function (BinaryExpressionState) { + /** + * Handles walking into a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function enter(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, outerState) { + var prevUserState = stackIndex > 0 ? userStateStack[stackIndex - 1] : undefined; + ts.Debug.assertEqual(stateStack[stackIndex], enter); + userStateStack[stackIndex] = machine.onEnter(nodeStack[stackIndex], prevUserState, outerState); + stateStack[stackIndex] = nextState(machine, enter); + return stackIndex; + } + BinaryExpressionState.enter = enter; + /** + * Handles walking the `left` side of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function left(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], left); + ts.Debug.assertIsDefined(machine.onLeft); + stateStack[stackIndex] = nextState(machine, left); + var nextNode = machine.onLeft(nodeStack[stackIndex].left, userStateStack[stackIndex], nodeStack[stackIndex]); + if (nextNode) { + checkCircularity(stackIndex, nodeStack, nextNode); + return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode); + } + return stackIndex; + } + BinaryExpressionState.left = left; + /** + * Handles walking the `operatorToken` of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function operator(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], operator); + ts.Debug.assertIsDefined(machine.onOperator); + stateStack[stackIndex] = nextState(machine, operator); + machine.onOperator(nodeStack[stackIndex].operatorToken, userStateStack[stackIndex], nodeStack[stackIndex]); + return stackIndex; + } + BinaryExpressionState.operator = operator; + /** + * Handles walking the `right` side of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function right(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], right); + ts.Debug.assertIsDefined(machine.onRight); + stateStack[stackIndex] = nextState(machine, right); + var nextNode = machine.onRight(nodeStack[stackIndex].right, userStateStack[stackIndex], nodeStack[stackIndex]); + if (nextNode) { + checkCircularity(stackIndex, nodeStack, nextNode); + return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode); + } + return stackIndex; + } + BinaryExpressionState.right = right; + /** + * Handles walking out of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function exit(machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], exit); + stateStack[stackIndex] = nextState(machine, exit); + var result = machine.onExit(nodeStack[stackIndex], userStateStack[stackIndex]); + if (stackIndex > 0) { + stackIndex--; + if (machine.foldState) { + var side = stateStack[stackIndex] === exit ? "right" : "left"; + userStateStack[stackIndex] = machine.foldState(userStateStack[stackIndex], result, side); + } + } + else { + resultHolder.value = result; + } + return stackIndex; + } + BinaryExpressionState.exit = exit; + /** + * Handles a frame that is already done. + * @returns The `done` state. + */ + function done(_machine, stackIndex, stateStack, _nodeStack, _userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], done); + return stackIndex; + } + BinaryExpressionState.done = done; + function nextState(machine, currentState) { + switch (currentState) { + case enter: + if (machine.onLeft) + return left; + // falls through + case left: + if (machine.onOperator) + return operator; + // falls through + case operator: + if (machine.onRight) + return right; + // falls through + case right: return exit; + case exit: return done; + case done: return done; + default: ts.Debug.fail("Invalid state"); + } + } + BinaryExpressionState.nextState = nextState; + function pushStack(stackIndex, stateStack, nodeStack, userStateStack, node) { + stackIndex++; + stateStack[stackIndex] = enter; + nodeStack[stackIndex] = node; + userStateStack[stackIndex] = undefined; + return stackIndex; + } + function checkCircularity(stackIndex, nodeStack, node) { + if (ts.Debug.shouldAssert(2 /* Aggressive */)) { + while (stackIndex >= 0) { + ts.Debug.assert(nodeStack[stackIndex] !== node, "Circular traversal detected."); + stackIndex--; + } + } + } + })(BinaryExpressionState || (BinaryExpressionState = {})); + /** + * Holds state machine handler functions + */ + var BinaryExpressionStateMachine = /** @class */ (function () { + function BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState) { + this.onEnter = onEnter; + this.onLeft = onLeft; + this.onOperator = onOperator; + this.onRight = onRight; + this.onExit = onExit; + this.foldState = foldState; + } + return BinaryExpressionStateMachine; + }()); + function createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState) { + var machine = new BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState); + return trampoline; + function trampoline(node, outerState) { + var resultHolder = { value: undefined }; + var stateStack = [BinaryExpressionState.enter]; + var nodeStack = [node]; + var userStateStack = [undefined]; + var stackIndex = 0; + while (stateStack[stackIndex] !== BinaryExpressionState.done) { + stackIndex = stateStack[stackIndex](machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, outerState); + } + ts.Debug.assertEqual(stackIndex, 0); + return resultHolder.value; + } } - ts.isStaticModifier = isStaticModifier; + ts.createBinaryExpressionTrampoline = createBinaryExpressionTrampoline; })(ts || (ts = {})); var ts; (function (ts) { @@ -27961,19 +28848,19 @@ var ts; * that they appear in the source code. The language service depends on this property to locate nodes by position. */ function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 156 /* LastToken */) { + if (!node || node.kind <= 157 /* LastToken */) { return; } switch (node.kind) { - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -27981,9 +28868,9 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: return visitNode(cbNode, node.expression); - case 160 /* Parameter */: + case 161 /* Parameter */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || @@ -27991,7 +28878,7 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -27999,51 +28886,51 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.initializer); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -28055,374 +28942,390 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return visitNode(cbNode, node.assertsModifier) || visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return visitNodes(cbNode, cbNodes, node.members); - case 178 /* ArrayType */: + case 179 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 179 /* TupleType */: + case 180 /* TupleType */: return visitNodes(cbNode, cbNodes, node.elements); - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: return visitNodes(cbNode, cbNodes, node.types); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return visitNode(cbNode, node.checkType) || visitNode(cbNode, node.extendsType) || visitNode(cbNode, node.trueType) || visitNode(cbNode, node.falseType); - case 185 /* InferType */: + case 186 /* InferType */: return visitNode(cbNode, node.typeParameter); - case 195 /* ImportType */: + case 196 /* ImportType */: return visitNode(cbNode, node.argument) || visitNode(cbNode, node.qualifier) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 186 /* ParenthesizedType */: - case 188 /* TypeOperator */: + case 187 /* ParenthesizedType */: + case 189 /* TypeOperator */: return visitNode(cbNode, node.type); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 190 /* MappedType */: + case 191 /* MappedType */: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.nameType) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 191 /* LiteralType */: + case 192 /* LiteralType */: return visitNode(cbNode, node.literal); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: return visitNodes(cbNode, cbNodes, node.elements); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitNodes(cbNode, cbNodes, node.properties); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || visitNode(cbNode, node.name); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || visitNode(cbNode, node.argumentExpression); - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.template); - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 224 /* AsExpression */: + case 225 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return visitNode(cbNode, node.expression); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return visitNode(cbNode, node.name); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return visitNode(cbNode, node.expression); - case 230 /* Block */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 258 /* ModuleBlock */: return visitNodes(cbNode, cbNodes, node.statements); - case 297 /* SourceFile */: + case 298 /* SourceFile */: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return visitNodes(cbNode, cbNodes, node.declarations); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 240 /* ContinueStatement */: - case 241 /* BreakStatement */: + case 241 /* ContinueStatement */: + case 242 /* BreakStatement */: return visitNode(cbNode, node.label); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return visitNodes(cbNode, cbNodes, node.clauses); - case 284 /* CaseClause */: + case 285 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: return visitNodes(cbNode, cbNodes, node.statements); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 161 /* Decorator */: + case 162 /* Decorator */: return visitNode(cbNode, node.expression); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 291 /* EnumMember */: + case 292 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: return visitNode(cbNode, node.name); - case 264 /* NamedImports */: - case 268 /* NamedExports */: + case 265 /* NamedImports */: + case 269 /* NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 194 /* TemplateLiteralTypeSpan */: + case 195 /* TemplateLiteralTypeSpan */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.literal); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: return visitNodes(cbNode, cbNodes, node.types); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 271 /* MissingDeclaration */: + case 272 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return visitNode(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingFragment); - case 274 /* JsxSelfClosingElement */: - case 275 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 282 /* JsxSpreadAttribute */: + case 283 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 276 /* JsxClosingElement */: + case 277 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 180 /* OptionalType */: - case 181 /* RestType */: - case 301 /* JSDocTypeExpression */: - case 306 /* JSDocNonNullableType */: - case 305 /* JSDocNullableType */: - case 307 /* JSDocOptionalType */: - case 309 /* JSDocVariadicType */: + case 181 /* OptionalType */: + case 182 /* RestType */: + case 302 /* JSDocTypeExpression */: + case 307 /* JSDocNonNullableType */: + case 306 /* JSDocNullableType */: + case 308 /* JSDocOptionalType */: + case 310 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 311 /* JSDocComment */: - return visitNodes(cbNode, cbNodes, node.tags); - case 332 /* JSDocSeeTag */: + case 312 /* JSDocComment */: + return (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) + || visitNodes(cbNode, cbNodes, node.tags); + case 336 /* JSDocSeeTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.name); - case 302 /* JSDocNameReference */: + visitNode(cbNode, node.name) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 303 /* JSDocNameReference */: return visitNode(cbNode, node.name); - case 326 /* JSDocParameterTag */: - case 333 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: return visitNode(cbNode, node.tagName) || (node.isNameFirst ? visitNode(cbNode, node.name) || - visitNode(cbNode, node.typeExpression) + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) : visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.name)); - case 317 /* JSDocAuthorTag */: - return visitNode(cbNode, node.tagName); - case 316 /* JSDocImplementsTag */: + visitNode(cbNode, node.name)) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 320 /* JSDocAuthorTag */: + return visitNode(cbNode, node.tagName) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 319 /* JSDocImplementsTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.class); - case 315 /* JSDocAugmentsTag */: + visitNode(cbNode, node.class) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 318 /* JSDocAugmentsTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.class); - case 330 /* JSDocTemplateTag */: + visitNode(cbNode, node.class) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 334 /* JSDocTemplateTag */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.constraint) || - visitNodes(cbNode, cbNodes, node.typeParameters); - case 331 /* JSDocTypedefTag */: + visitNodes(cbNode, cbNodes, node.typeParameters) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 335 /* JSDocTypedefTag */: return visitNode(cbNode, node.tagName) || (node.typeExpression && - node.typeExpression.kind === 301 /* JSDocTypeExpression */ + node.typeExpression.kind === 302 /* JSDocTypeExpression */ ? visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName) + visitNode(cbNode, node.fullName) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) : visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression)); - case 324 /* JSDocCallbackTag */: + visitNode(cbNode, node.typeExpression)) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 328 /* JSDocCallbackTag */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression); - case 327 /* JSDocReturnTag */: - case 329 /* JSDocTypeTag */: - case 328 /* JSDocThisTag */: - case 325 /* JSDocEnumTag */: + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 331 /* JSDocReturnTag */: + case 333 /* JSDocTypeTag */: + case 332 /* JSDocThisTag */: + case 329 /* JSDocEnumTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.typeExpression); - case 313 /* JSDocSignature */: + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 315 /* JSDocSignature */: return ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 312 /* JSDocTypeLiteral */: + case 316 /* JSDocLink */: + return visitNode(cbNode, node.name); + case 314 /* JSDocTypeLiteral */: return ts.forEach(node.jsDocPropertyTags, cbNode); - case 314 /* JSDocTag */: - case 319 /* JSDocClassTag */: - case 320 /* JSDocPublicTag */: - case 321 /* JSDocPrivateTag */: - case 322 /* JSDocProtectedTag */: - case 323 /* JSDocReadonlyTag */: - return visitNode(cbNode, node.tagName); - case 336 /* PartiallyEmittedExpression */: + case 317 /* JSDocTag */: + case 322 /* JSDocClassTag */: + case 323 /* JSDocPublicTag */: + case 324 /* JSDocPrivateTag */: + case 325 /* JSDocProtectedTag */: + case 326 /* JSDocReadonlyTag */: + case 321 /* JSDocDeprecatedTag */: + return visitNode(cbNode, node.tagName) + || (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 340 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -28442,62 +29345,58 @@ var ts; * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure. */ function forEachChildRecursively(rootNode, cbNode, cbNodes) { - var stack = [rootNode]; - while (stack.length) { - var parent = stack.pop(); - var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent)); - if (res) { - return res; - } - } - return; - function gatherPossibleChildren(node) { - var children = []; - forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal - return children; - function addWorkItem(n) { - children.unshift(n); - } - } - function visitAllPossibleChildren(parent, children) { - for (var _i = 0, children_5 = children; _i < children_5.length; _i++) { - var child = children_5[_i]; - if (ts.isArray(child)) { - if (cbNodes) { - var res = cbNodes(child, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - } - for (var i = child.length - 1; i >= 0; i--) { - var realChild = child[i]; - var res = cbNode(realChild, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - stack.push(realChild); - } - } - else { - stack.push(child); - var res = cbNode(child, parent); + var queue = gatherPossibleChildren(rootNode); + var parents = []; // tracks parent references for elements in queue + while (parents.length < queue.length) { + parents.push(rootNode); + } + while (queue.length !== 0) { + var current = queue.pop(); + var parent = parents.pop(); + if (ts.isArray(current)) { + if (cbNodes) { + var res = cbNodes(current, parent); if (res) { if (res === "skip") continue; return res; } } + for (var i = current.length - 1; i >= 0; --i) { + queue.push(current[i]); + parents.push(parent); + } + } + else { + var res = cbNode(current, parent); + if (res) { + if (res === "skip") + continue; + return res; + } + if (current.kind >= 158 /* FirstNode */) { + // add children in reverse order to the queue, so popping gives the first child + for (var _i = 0, _a = gatherPossibleChildren(current); _i < _a.length; _i++) { + var child = _a[_i]; + queue.push(child); + parents.push(current); + } + } } } } ts.forEachChildRecursively = forEachChildRecursively; + function gatherPossibleChildren(node) { + var children = []; + forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal + return children; + function addWorkItem(n) { + children.unshift(n); + } + } function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeParse"); var result; ts.perfLogger.logStartParseSourceFile(fileName); @@ -28510,7 +29409,7 @@ var ts; ts.perfLogger.logStopParseSourceFile(); ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } ts.createSourceFile = createSourceFile; @@ -28692,11 +29591,12 @@ var ts; // attached to the EOF token. var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + var _a; if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); if (scriptKind === 6 /* JSON */) { var result_3 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); - ts.convertToObjectWorker(result_3, result_3.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + ts.convertToObjectWorker(result_3, (_a = result_3.statements[0]) === null || _a === void 0 ? void 0 : _a.expression, result_3.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); result_3.referencedFiles = ts.emptyArray; result_3.typeReferenceDirectives = ts.emptyArray; result_3.libReferenceDirectives = ts.emptyArray; @@ -28736,35 +29636,54 @@ var ts; endOfFileToken = parseTokenNode(); } else { - var expression = void 0; - switch (token()) { - case 22 /* OpenBracketToken */: - expression = parseArrayLiteralExpression(); - break; - case 109 /* TrueKeyword */: - case 94 /* FalseKeyword */: - case 103 /* NullKeyword */: - expression = parseTokenNode(); - break; - case 40 /* MinusToken */: - if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) { - expression = parsePrefixUnaryExpression(); - } - else { - expression = parseObjectLiteralExpression(); - } - break; - case 8 /* NumericLiteral */: - case 10 /* StringLiteral */: - if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) { - expression = parseLiteralNode(); + // Loop and synthesize an ArrayLiteralExpression if there are more than + // one top-level expressions to ensure all input text is consumed. + var expressions = void 0; + while (token() !== 1 /* EndOfFileToken */) { + var expression_1 = void 0; + switch (token()) { + case 22 /* OpenBracketToken */: + expression_1 = parseArrayLiteralExpression(); break; + case 109 /* TrueKeyword */: + case 94 /* FalseKeyword */: + case 103 /* NullKeyword */: + expression_1 = parseTokenNode(); + break; + case 40 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) { + expression_1 = parsePrefixUnaryExpression(); + } + else { + expression_1 = parseObjectLiteralExpression(); + } + break; + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) { + expression_1 = parseLiteralNode(); + break; + } + // falls through + default: + expression_1 = parseObjectLiteralExpression(); + break; + } + // Error recovery: collect multiple top-level expressions + if (expressions && ts.isArray(expressions)) { + expressions.push(expression_1); + } + else if (expressions) { + expressions = [expressions, expression_1]; + } + else { + expressions = expression_1; + if (token() !== 1 /* EndOfFileToken */) { + parseErrorAtCurrentToken(ts.Diagnostics.Unexpected_token); } - // falls through - default: - expression = parseObjectLiteralExpression(); - break; + } } + var expression = ts.isArray(expressions) ? finishNode(factory.createArrayLiteralExpression(expressions), pos) : ts.Debug.checkDefined(expressions); var statement = factory.createExpressionStatement(expression); finishNode(statement, pos); statements = createNodeArray([statement], pos); @@ -28959,7 +29878,7 @@ var ts; return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements)); function containsPossibleTopLevelAwait(node) { return !(node.flags & 32768 /* AwaitContext */) - && !!(node.transformFlags & 8388608 /* ContainsPossibleTopLevelAwait */); + && !!(node.transformFlags & 16777216 /* ContainsPossibleTopLevelAwait */); } function findNextStatementWithAwait(statements, start) { for (var i = start; i < statements.length; i++) { @@ -29000,7 +29919,7 @@ var ts; ts.setTextRangePosWidth(sourceFile, 0, sourceText.length); setExternalModuleIndicator(sourceFile); // If we parsed this as an external module, it may contain top-level await - if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 8388608 /* ContainsPossibleTopLevelAwait */) { + if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 16777216 /* ContainsPossibleTopLevelAwait */) { sourceFile = reparseTopLevelAwait(sourceFile); } sourceFile.text = sourceText; @@ -29371,7 +30290,7 @@ var ts; ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, "", "", /*templateFlags*/ undefined) : kind === 8 /* NumericLiteral */ ? factory.createNumericLiteral("", /*numericLiteralFlags*/ undefined) : kind === 10 /* StringLiteral */ ? factory.createStringLiteral("", /*isSingleQuote*/ undefined) : - kind === 271 /* MissingDeclaration */ ? factory.createMissingDeclaration() : + kind === 272 /* MissingDeclaration */ ? factory.createMissingDeclaration() : factory.createToken(kind); return finishNode(result, pos); } @@ -29386,8 +30305,8 @@ var ts; // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for // each identifier in order to reduce memory consumption. function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) { - identifierCount++; if (isIdentifier) { + identifierCount++; var pos = getNodePos(); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker var originalKeywordKind = token(); @@ -29399,6 +30318,11 @@ var ts; parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); return createIdentifier(/*isIdentifier*/ true); } + if (token() === 0 /* Unknown */ && scanner.tryScan(function () { return scanner.reScanInvalidIdentifier() === 78 /* Identifier */; })) { + // Scanner has already recorded an 'Invalid character' error, so no need to add another from the parser. + return createIdentifier(/*isIdentifier*/ true); + } + identifierCount++; // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; var isReservedWord = scanner.isReservedWord(); @@ -29753,8 +30677,7 @@ var ts; var listPos = getNodePos(); while (!isListTerminator(kind)) { if (isListElement(kind, /*inErrorRecovery*/ false)) { - var element = parseListElement(kind, parseElement); - list.push(element); + list.push(parseListElement(kind, parseElement)); continue; } if (abortParsingListOrMoveToNextToken(kind)) { @@ -29904,14 +30827,14 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 166 /* Constructor */: - case 171 /* IndexSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 163 /* PropertyDeclaration */: - case 229 /* SemicolonClassElement */: + case 167 /* Constructor */: + case 172 /* IndexSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 230 /* SemicolonClassElement */: return true; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. @@ -29926,8 +30849,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: return true; } } @@ -29936,58 +30859,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 232 /* VariableStatement */: - case 230 /* Block */: - case 234 /* IfStatement */: - case 233 /* ExpressionStatement */: - case 246 /* ThrowStatement */: - case 242 /* ReturnStatement */: - case 244 /* SwitchStatement */: - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 237 /* ForStatement */: - case 236 /* WhileStatement */: - case 243 /* WithStatement */: - case 231 /* EmptyStatement */: - case 247 /* TryStatement */: - case 245 /* LabeledStatement */: - case 235 /* DoStatement */: - case 248 /* DebuggerStatement */: - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 252 /* FunctionDeclaration */: + case 233 /* VariableStatement */: + case 231 /* Block */: + case 235 /* IfStatement */: + case 234 /* ExpressionStatement */: + case 247 /* ThrowStatement */: + case 243 /* ReturnStatement */: + case 245 /* SwitchStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 238 /* ForStatement */: + case 237 /* WhileStatement */: + case 244 /* WithStatement */: + case 232 /* EmptyStatement */: + case 248 /* TryStatement */: + case 246 /* LabeledStatement */: + case 236 /* DoStatement */: + case 249 /* DebuggerStatement */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 291 /* EnumMember */; + return node.kind === 292 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 170 /* ConstructSignature */: - case 164 /* MethodSignature */: - case 171 /* IndexSignature */: - case 162 /* PropertySignature */: - case 169 /* CallSignature */: + case 171 /* ConstructSignature */: + case 165 /* MethodSignature */: + case 172 /* IndexSignature */: + case 163 /* PropertySignature */: + case 170 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 249 /* VariableDeclaration */) { + if (node.kind !== 250 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -30008,7 +30931,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 160 /* Parameter */) { + if (node.kind !== 161 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -30289,14 +31212,14 @@ var ts; // If true, we should abort parsing an error function. function typeHasArrowFunctionBlockingParseError(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return ts.nodeIsMissing(node.typeName); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: { + case 175 /* FunctionType */: + case 176 /* ConstructorType */: { var _a = node, parameters = _a.parameters, type = _a.type; return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); } - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return typeHasArrowFunctionBlockingParseError(node.type); default: return false; @@ -30477,19 +31400,21 @@ var ts; function parseParameterWorker(inOuterAwaitContext) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); + // FormalParameter [Yield,Await]: + // BindingElement[?Yield,?Await] + // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. + var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); if (token() === 107 /* ThisKeyword */) { - var node_1 = factory.createParameterDeclaration( - /*decorators*/ undefined, + var node_1 = factory.createParameterDeclaration(decorators, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), /*questionToken*/ undefined, parseTypeAnnotation(), /*initializer*/ undefined); + if (decorators) { + parseErrorAtRange(decorators[0], ts.Diagnostics.Decorators_may_not_be_applied_to_this_parameters); + } return withJSDoc(finishNode(node_1, pos), hasJSDoc); } - // FormalParameter [Yield,Await]: - // BindingElement[?Yield,?Await] - // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. - var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); var savedTopLevel = topLevel; topLevel = false; var modifiers = parseModifiers(); @@ -30576,14 +31501,14 @@ var ts; function parseSignatureMember(kind) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); - if (kind === 170 /* ConstructSignature */) { + if (kind === 171 /* ConstructSignature */) { parseExpected(102 /* NewKeyword */); } var typeParameters = parseTypeParameters(); var parameters = parseParameters(4 /* Type */); var type = parseReturnType(58 /* ColonToken */, /*isType*/ true); parseTypeMemberSemicolon(); - var node = kind === 169 /* CallSignature */ + var node = kind === 170 /* CallSignature */ ? factory.createCallSignature(typeParameters, parameters, type) : factory.createConstructSignature(typeParameters, parameters, type); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -30674,7 +31599,10 @@ var ts; } function isTypeMemberStart() { // Return true if we have the start of a signature member - if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) { + if (token() === 20 /* OpenParenToken */ || + token() === 29 /* LessThanToken */ || + token() === 134 /* GetKeyword */ || + token() === 146 /* SetKeyword */) { return true; } var idToken = false; @@ -30706,14 +31634,20 @@ var ts; } function parseTypeMember() { if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) { - return parseSignatureMember(169 /* CallSignature */); + return parseSignatureMember(170 /* CallSignature */); } if (token() === 102 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(170 /* ConstructSignature */); + return parseSignatureMember(171 /* ConstructSignature */); } var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiers(); + if (parseContextualModifier(134 /* GetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 168 /* GetAccessor */); + } + if (parseContextualModifier(146 /* SetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 169 /* SetAccessor */); + } if (isIndexSignature()) { return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers); } @@ -31746,7 +32680,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand, pos); } function isInOrOfKeyword(t) { - return t === 100 /* InKeyword */ || t === 156 /* OfKeyword */; + return t === 100 /* InKeyword */ || t === 157 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand, pos) { while (true) { @@ -31886,7 +32820,7 @@ var ts; if (token() === 42 /* AsteriskAsteriskToken */) { var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); var end = simpleUnaryExpression.end; - if (simpleUnaryExpression.kind === 206 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 207 /* TypeAssertionExpression */) { parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -32137,7 +33071,7 @@ var ts; var pos = getNodePos(); var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 275 /* JsxOpeningElement */) { + if (opening.kind === 276 /* JsxOpeningElement */) { var children = parseJsxChildren(opening); var closingElement = parseJsxClosingElement(inExpressionContext); if (!tagNamesAreEquivalent(opening.tagName, closingElement.tagName)) { @@ -32145,11 +33079,11 @@ var ts; } result = finishNode(factory.createJsxElement(opening, children, closingElement), pos); } - else if (opening.kind === 278 /* JsxOpeningFragment */) { + else if (opening.kind === 279 /* JsxOpeningFragment */) { result = finishNode(factory.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos); } else { - ts.Debug.assert(opening.kind === 274 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 275 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -32649,10 +33583,10 @@ var ts; var decorators = parseDecorators(); var modifiers = parseModifiers(); if (parseContextualModifier(134 /* GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167 /* GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* GetAccessor */); } if (parseContextualModifier(146 /* SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 169 /* SetAccessor */); } var asteriskToken = parseOptionalToken(41 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); @@ -32770,6 +33704,7 @@ var ts; // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); var openBracePosition = scanner.getTokenPos(); if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { var multiLine = scanner.hasPrecedingLineBreak(); @@ -32780,11 +33715,16 @@ var ts; ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); } } - return finishNode(factory.createBlock(statements, multiLine), pos); + var result = withJSDoc(finishNode(factory.createBlock(statements, multiLine), pos), hasJSDoc); + if (token() === 62 /* EqualsToken */) { + parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses); + nextToken(); + } + return result; } else { var statements = createMissingList(); - return finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos); + return withJSDoc(finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos), hasJSDoc); } } function parseFunctionBlock(flags, diagnosticMessage) { @@ -32811,21 +33751,24 @@ var ts; } function parseEmptyStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(26 /* SemicolonToken */); - return finishNode(factory.createEmptyStatement(), pos); + return withJSDoc(finishNode(factory.createEmptyStatement(), pos), hasJSDoc); } function parseIfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(98 /* IfKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var thenStatement = parseStatement(); var elseStatement = parseOptional(90 /* ElseKeyword */) ? parseStatement() : undefined; - return finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos); + return withJSDoc(finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc); } function parseDoStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(89 /* DoKeyword */); var statement = parseStatement(); parseExpected(114 /* WhileKeyword */); @@ -32837,19 +33780,21 @@ var ts; // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. parseOptional(26 /* SemicolonToken */); - return finishNode(factory.createDoStatement(statement, expression), pos); + return withJSDoc(finishNode(factory.createDoStatement(statement, expression), pos), hasJSDoc); } function parseWhileStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(114 /* WhileKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var statement = parseStatement(); - return finishNode(factory.createWhileStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWhileStatement(expression, statement), pos), hasJSDoc); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(96 /* ForKeyword */); var awaitToken = parseOptionalToken(130 /* AwaitKeyword */); parseExpected(20 /* OpenParenToken */); @@ -32863,7 +33808,7 @@ var ts; } } var node; - if (awaitToken ? parseExpected(156 /* OfKeyword */) : parseOptional(156 /* OfKeyword */)) { + if (awaitToken ? parseExpected(157 /* OfKeyword */) : parseOptional(157 /* OfKeyword */)) { var expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(21 /* CloseParenToken */); node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement()); @@ -32885,33 +33830,36 @@ var ts; parseExpected(21 /* CloseParenToken */); node = factory.createForStatement(initializer, condition, incrementor, parseStatement()); } - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseBreakOrContinueStatement(kind) { var pos = getNodePos(); - parseExpected(kind === 241 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */); + var hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(kind === 242 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */); var label = canParseSemicolon() ? undefined : parseIdentifier(); parseSemicolon(); - var node = kind === 241 /* BreakStatement */ + var node = kind === 242 /* BreakStatement */ ? factory.createBreakStatement(label) : factory.createContinueStatement(label); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseReturnStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(104 /* ReturnKeyword */); var expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression); parseSemicolon(); - return finishNode(factory.createReturnStatement(expression), pos); + return withJSDoc(finishNode(factory.createReturnStatement(expression), pos), hasJSDoc); } function parseWithStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(115 /* WithKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement); - return finishNode(factory.createWithStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWithStatement(expression, statement), pos), hasJSDoc); } function parseCaseClause() { var pos = getNodePos(); @@ -32940,17 +33888,19 @@ var ts; } function parseSwitchStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(106 /* SwitchKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var caseBlock = parseCaseBlock(); - return finishNode(factory.createSwitchStatement(expression, caseBlock), pos); + return withJSDoc(finishNode(factory.createSwitchStatement(expression, caseBlock), pos), hasJSDoc); } function parseThrowStatement() { // ThrowStatement[Yield] : // throw [no LineTerminator here]Expression[In, ?Yield]; var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(108 /* ThrowKeyword */); // Because of automatic semicolon insertion, we need to report error if this // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' @@ -32963,11 +33913,12 @@ var ts; expression = finishNode(factory.createIdentifier(""), getNodePos()); } parseSemicolon(); - return finishNode(factory.createThrowStatement(expression), pos); + return withJSDoc(finishNode(factory.createThrowStatement(expression), pos), hasJSDoc); } // TODO: Review for error recovery function parseTryStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(110 /* TryKeyword */); var tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); var catchClause = token() === 82 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -32978,7 +33929,7 @@ var ts; parseExpected(95 /* FinallyKeyword */); finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } - return finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos); + return withJSDoc(finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); } function parseCatchClause() { var pos = getNodePos(); @@ -32997,9 +33948,10 @@ var ts; } function parseDebuggerStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(86 /* DebuggerKeyword */); parseSemicolon(); - return finishNode(factory.createDebuggerStatement(), pos); + return withJSDoc(finishNode(factory.createDebuggerStatement(), pos), hasJSDoc); } function parseExpressionOrLabeledStatement() { // Avoiding having to do the lookahead for a labeled statement by just trying to parse @@ -33207,9 +34159,9 @@ var ts; case 96 /* ForKeyword */: return parseForOrForInOrForOfStatement(); case 85 /* ContinueKeyword */: - return parseBreakOrContinueStatement(240 /* ContinueStatement */); + return parseBreakOrContinueStatement(241 /* ContinueStatement */); case 80 /* BreakKeyword */: - return parseBreakOrContinueStatement(241 /* BreakStatement */); + return parseBreakOrContinueStatement(242 /* BreakStatement */); case 104 /* ReturnKeyword */: return parseReturnStatement(); case 115 /* WithKeyword */: @@ -33329,7 +34281,7 @@ var ts; if (decorators || modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - var missing = createMissingNode(271 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var missing = createMissingNode(272 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); ts.setTextRangePos(missing, pos); missing.decorators = decorators; missing.modifiers = modifiers; @@ -33411,6 +34363,7 @@ var ts; } function parseVariableDeclaration(allowExclamation) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); var name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations); var exclamationToken; if (allowExclamation && name.kind === 78 /* Identifier */ && @@ -33420,7 +34373,7 @@ var ts; var type = parseTypeAnnotation(); var initializer = isInOrOfKeyword(token()) ? undefined : parseInitializer(); var node = factory.createVariableDeclaration(name, exclamationToken, type, initializer); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseVariableDeclarationList(inForStatementInitializer) { var pos = getNodePos(); @@ -33448,7 +34401,7 @@ var ts; // this context. // The checker will then give an error that there is an empty declaration list. var declarations; - if (token() === 156 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 157 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { declarations = createMissingList(); } else { @@ -33552,12 +34505,12 @@ var ts; var parameters = parseParameters(0 /* None */); var type = parseReturnType(58 /* ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(0 /* None */); - var node = kind === 167 /* GetAccessor */ + var node = kind === 168 /* GetAccessor */ ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body); // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors node.typeParameters = typeParameters; - if (type && node.kind === 168 /* SetAccessor */) + if (type && node.kind === 169 /* SetAccessor */) node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -33700,10 +34653,10 @@ var ts; var decorators = parseDecorators(); var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); if (parseContextualModifier(134 /* GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167 /* GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* GetAccessor */); } if (parseContextualModifier(146 /* SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 169 /* SetAccessor */); } if (token() === 132 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) { var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers); @@ -33742,10 +34695,10 @@ var ts; return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, 221 /* ClassExpression */); + return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, 222 /* ClassExpression */); } function parseClassDeclaration(pos, hasJSDoc, decorators, modifiers) { - return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 252 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 253 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, kind) { var savedAwaitContext = inAwaitContext(); @@ -33767,7 +34720,7 @@ var ts; members = createMissingList(); } setAwaitContext(savedAwaitContext); - var node = kind === 252 /* ClassDeclaration */ + var node = kind === 253 /* ClassDeclaration */ ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -34006,7 +34959,7 @@ var ts; var namedBindings; if (!identifier || parseOptional(27 /* CommaToken */)) { - namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(264 /* NamedImports */); + namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(265 /* NamedImports */); } return finishNode(factory.createImportClause(isTypeOnly, identifier, namedBindings), pos); } @@ -34054,16 +35007,16 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - var node = kind === 264 /* NamedImports */ + var node = kind === 265 /* NamedImports */ ? factory.createNamedImports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseImportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */)) : factory.createNamedExports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */)); return finishNode(node, pos); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(270 /* ExportSpecifier */); + return parseImportOrExportSpecifier(271 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(265 /* ImportSpecifier */); + return parseImportOrExportSpecifier(266 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var pos = getNodePos(); @@ -34090,10 +35043,10 @@ var ts; else { name = identifierName; } - if (kind === 265 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 266 /* ImportSpecifier */ && checkIdentifierIsKeyword) { parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } - var node = kind === 265 /* ImportSpecifier */ + var node = kind === 266 /* ImportSpecifier */ ? factory.createImportSpecifier(propertyName, name) : factory.createExportSpecifier(propertyName, name); return finishNode(node, pos); @@ -34116,7 +35069,7 @@ var ts; moduleSpecifier = parseModuleSpecifier(); } else { - exportClause = parseNamedImportsOrExports(268 /* NamedExports */); + exportClause = parseNamedImportsOrExports(269 /* NamedExports */); // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. @@ -34305,7 +35258,10 @@ var ts; var tags; var tagsPos; var tagsEnd; + var linkEnd; + var commentsPos; var comments = []; + var parts = []; // + 3 for leading /**, - 5 in total for /** */ return scanner.scanRange(start + 3, length - 5, function () { // Initially we can parse out a tag. We also have seen a starting asterisk. @@ -34334,6 +35290,8 @@ var ts; case 59 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingWhitespace(comments); + if (!commentsPos) + commentsPos = getNodePos(); addTag(parseTag(indent)); // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning @@ -34376,6 +35334,22 @@ var ts; break; case 1 /* EndOfFileToken */: break loop; + case 18 /* OpenBraceToken */: + state = 2 /* SavingComments */; + var commentEnd = scanner.getStartPos(); + var linkStart = scanner.getTextPos() - 1; + var link = parseJSDocLink(linkStart); + if (link) { + if (!linkEnd) { + removeLeadingNewlines(comments); + } + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : start, commentEnd)); + parts.push(link); + comments = []; + linkEnd = scanner.getTextPos(); + break; + } + // fallthrough if it's not a {@link sequence default: // 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 @@ -34386,9 +35360,14 @@ var ts; } nextTokenJSDoc(); } - removeLeadingNewlines(comments); removeTrailingWhitespace(comments); - return createJSDocComment(); + if (parts.length && comments.length) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : start, commentsPos)); + } + if (parts.length && tags) + ts.Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); + var tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); + return finishNode(factory.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : comments.length ? comments.join("") : undefined, tagsArray), start, end); }); function removeLeadingNewlines(comments) { while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { @@ -34400,11 +35379,6 @@ var ts; comments.pop(); } } - function createJSDocComment() { - var comment = comments.length ? comments.join("") : undefined; - var tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); - return finishNode(factory.createJSDocComment(comment, tagsArray), start, end); - } function isNextNonwhitespaceTokenEndOfFile() { // We must use infinite lookahead, as there could be any number of newlines :( while (true) { @@ -34484,6 +35458,9 @@ var ts; case "readonly": tag = parseSimpleTag(start, factory.createJSDocReadonlyTag, tagName, margin, indentText); break; + case "override": + tag = parseSimpleTag(start, factory.createJSDocOverrideTag, tagName, margin, indentText); + break; case "deprecated": hasDeprecatedTag = true; tag = parseSimpleTag(start, factory.createJSDocDeprecatedTag, tagName, margin, indentText); @@ -34531,8 +35508,12 @@ var ts; return parseTagComments(margin, indentText.slice(margin)); } function parseTagComments(indent, initialMargin) { + var commentsPos = getNodePos(); var comments = []; + var parts = []; + var linkEnd; var state = 0 /* BeginningOfLine */; + var previousWhitespace = true; var margin; function pushComment(text) { if (!margin) { @@ -34558,7 +35539,9 @@ var ts; indent = 0; break; case 59 /* AtToken */: - if (state === 3 /* SavingBackticks */) { + if (state === 3 /* SavingBackticks */ + || state === 2 /* SavingComments */ && (!previousWhitespace || lookAhead(isNextJSDocTokenWhitespace))) { + // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace or not before whitespace comments.push(scanner.getTokenText()); break; } @@ -34582,13 +35565,18 @@ var ts; break; case 18 /* OpenBraceToken */: state = 2 /* SavingComments */; - if (lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) { - pushComment(scanner.getTokenText()); - nextTokenJSDoc(); + var commentEnd = scanner.getStartPos(); + var linkStart = scanner.getTextPos() - 1; + var link = parseJSDocLink(linkStart); + if (link) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : commentsPos, commentEnd)); + parts.push(link); + comments = []; + linkEnd = scanner.getTextPos(); + } + else { pushComment(scanner.getTokenText()); - nextTokenJSDoc(); } - pushComment(scanner.getTokenText()); break; case 61 /* BacktickToken */: if (state === 3 /* SavingBackticks */) { @@ -34615,15 +35603,51 @@ var ts; pushComment(scanner.getTokenText()); break; } + previousWhitespace = token() === 5 /* WhitespaceTrivia */; tok = nextTokenJSDoc(); } removeLeadingNewlines(comments); removeTrailingWhitespace(comments); - return comments.length === 0 ? undefined : comments.join(""); + if (parts.length) { + if (comments.length) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : commentsPos)); + } + return createNodeArray(parts, commentsPos, scanner.getTextPos()); + } + else if (comments.length) { + return comments.join(""); + } + } + function isNextJSDocTokenWhitespace() { + var next = nextTokenJSDoc(); + return next === 5 /* WhitespaceTrivia */ || next === 4 /* NewLineTrivia */; + } + function parseJSDocLink(start) { + if (!tryParse(parseJSDocLinkPrefix)) { + return undefined; + } + nextTokenJSDoc(); // start at token after link, then skip any whitespace + skipWhitespace(); + // parseEntityName logs an error for non-identifier, so create a MissingNode ourselves to avoid the error + var name = ts.tokenIsIdentifierOrKeyword(token()) + ? parseEntityName(/*allowReservedWords*/ true) + : undefined; + var text = []; + while (token() !== 19 /* CloseBraceToken */ && token() !== 4 /* NewLineTrivia */ && token() !== 1 /* EndOfFileToken */) { + text.push(scanner.getTokenText()); + nextTokenJSDoc(); + } + return finishNode(factory.createJSDocLink(name, text.join("")), start, scanner.getTextPos()); + } + function parseJSDocLinkPrefix() { + skipWhitespaceOrAsterisk(); + return token() === 18 /* OpenBraceToken */ + && nextTokenJSDoc() === 59 /* AtToken */ + && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) + && scanner.getTokenValue() === "link"; } function parseUnknownTag(start, tagName, indent, indentText) { - var end = getNodePos(); - return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function addTag(tag) { if (!tag) { @@ -34668,7 +35692,7 @@ var ts; switch (node.kind) { case 145 /* ObjectKeyword */: return true; - case 178 /* ArrayType */: + case 179 /* ArrayType */: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments; @@ -34679,11 +35703,11 @@ var ts; var isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; - skipWhitespace(); - if (isNameFirst) { + var indentText = skipWhitespaceOrAsterisk(); + if (isNameFirst && !lookAhead(parseJSDocLinkPrefix)) { typeExpression = tryParseTypeExpression(); } - var comment = parseTagComments(indent + scanner.getStartPos() - start); + var comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; @@ -34700,12 +35724,12 @@ var ts; var child = void 0; var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { - if (child.kind === 326 /* JSDocParameterTag */ || child.kind === 333 /* JSDocPropertyTag */) { + if (child.kind === 330 /* JSDocParameterTag */ || child.kind === 337 /* JSDocPropertyTag */) { children = ts.append(children, child); } } if (children) { - var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 178 /* ArrayType */), pos); + var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 179 /* ArrayType */), pos); return finishNode(factory.createJSDocTypeExpression(literal), pos); } } @@ -34715,27 +35739,34 @@ var ts; parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeExpression = tryParseTypeExpression(); - var end = getNodePos(); - return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function parseTypeTag(start, tagName, indent, indentText) { if (ts.some(tags, ts.isJSDocTypeTag)) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); - var end = getNodePos(); - var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined; - return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start, end); + var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; + return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start); } function parseSeeTag(start, tagName, indent, indentText) { - var nameExpression = parseJSDocNameReference(); - var end = getNodePos(); - var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined; - return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start, end); + var isLink = lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; }); + var nameExpression = isLink ? undefined : parseJSDocNameReference(); + var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; + return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start); } function parseAuthorTag(start, tagName, indent, indentText) { - var comments = parseAuthorNameAndEmail() + (parseTrailingTagComments(start, end, indent, indentText) || ""); - return finishNode(factory.createJSDocAuthorTag(tagName, comments || undefined), start); + var commentStart = getNodePos(); + var textOnly = parseAuthorNameAndEmail(); + var commentEnd = scanner.getStartPos(); + var comments = parseTrailingTagComments(start, commentEnd, indent, indentText); + if (!comments) { + commentEnd = scanner.getStartPos(); + } + var allParts = typeof comments !== "string" + ? createNodeArray(ts.concatenate([finishNode(textOnly, commentStart, commentEnd)], comments), commentStart) // cast away readonly + : textOnly.text + comments; + return finishNode(factory.createJSDocAuthorTag(tagName, allParts), start); } function parseAuthorNameAndEmail() { var comments = []; @@ -34756,17 +35787,15 @@ var ts; comments.push(scanner.getTokenText()); token = nextTokenJSDoc(); } - return comments.join(""); + return factory.createJSDocText(comments.join("")); } function parseImplementsTag(start, tagName, margin, indentText) { var className = parseExpressionWithTypeArgumentsForAugments(); - var end = getNodePos(); - return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseAugmentsTag(start, tagName, margin, indentText) { var className = parseExpressionWithTypeArgumentsForAugments(); - var end = getNodePos(); - return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseExpressionWithTypeArgumentsForAugments() { var usedBrace = parseOptional(18 /* OpenBraceToken */); @@ -34790,20 +35819,17 @@ var ts; return node; } function parseSimpleTag(start, createTag, tagName, margin, indentText) { - var end = getNodePos(); - return finishNode(createTag(tagName, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(createTag(tagName, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseThisTag(start, tagName, margin, indentText) { var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); - var end = getNodePos(); - return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseEnumTag(start, tagName, margin, indentText) { var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); - var end = getNodePos(); - return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseTypedefTag(start, tagName, indent, indentText) { var _a; @@ -34820,7 +35846,7 @@ var ts; var hasChildren = false; while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { hasChildren = true; - if (child.kind === 329 /* JSDocTypeTag */) { + if (child.kind === 333 /* JSDocTypeTag */) { if (childTypeTag) { parseErrorAtCurrentToken(ts.Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags); var lastError = ts.lastOrUndefined(parseDiagnostics); @@ -34838,7 +35864,7 @@ var ts; } } if (hasChildren) { - var isArrayType = typeExpression && typeExpression.type.kind === 178 /* ArrayType */; + var isArrayType = typeExpression && typeExpression.type.kind === 179 /* ArrayType */; var jsdocTypeLiteral = factory.createJSDocTypeLiteral(jsDocPropertyTags, isArrayType); typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : @@ -34891,17 +35917,16 @@ var ts; var returnTag = tryParse(function () { if (parseOptionalJsdoc(59 /* AtToken */)) { var tag = parseTag(indent); - if (tag && tag.kind === 327 /* JSDocReturnTag */) { + if (tag && tag.kind === 331 /* JSDocReturnTag */) { return tag; } } }); var typeExpression = finishNode(factory.createJSDocSignature(/*typeParameters*/ undefined, parameters, returnTag), start); - var end = getNodePos(); if (!comment) { - comment = parseTrailingTagComments(start, end, indent, indentText); + comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); } - return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start, end); + return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start); } function escapedTextsEqual(a, b) { while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { @@ -34926,7 +35951,7 @@ var ts; case 59 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target, indent); - if (child && (child.kind === 326 /* JSDocParameterTag */ || child.kind === 333 /* JSDocPropertyTag */) && + if (child && (child.kind === 330 /* JSDocParameterTag */ || child.kind === 337 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -34983,6 +36008,9 @@ var ts; function parseTemplateTagTypeParameter() { var typeParameterPos = getNodePos(); var name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); + if (ts.nodeIsMissing(name)) { + return undefined; + } return finishNode(factory.createTypeParameterDeclaration(name, /*constraint*/ undefined, /*defaultType*/ undefined), typeParameterPos); } function parseTemplateTagTypeParameters() { @@ -34990,7 +36018,10 @@ var ts; var typeParameters = []; do { skipWhitespace(); - typeParameters.push(parseTemplateTagTypeParameter()); + var node = parseTemplateTagTypeParameter(); + if (node !== undefined) { + typeParameters.push(node); + } skipWhitespaceOrAsterisk(); } while (parseOptionalJsdoc(27 /* CommaToken */)); return createNodeArray(typeParameters, pos); @@ -35009,8 +36040,7 @@ var ts; // TODO: Consider only parsing a single type parameter if there is a constraint. var constraint = token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; var typeParameters = parseTemplateTagTypeParameters(); - var end = getNodePos(); - return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function parseOptionalJsdoc(t) { if (token() === t) { @@ -35825,6 +36855,7 @@ var ts; ["es2018", "lib.es2018.d.ts"], ["es2019", "lib.es2019.d.ts"], ["es2020", "lib.es2020.d.ts"], + ["es2021", "lib.es2021.d.ts"], ["esnext", "lib.esnext.d.ts"], // Host only ["dom", "lib.dom.d.ts"], @@ -35864,14 +36895,17 @@ var ts; ["es2020.string", "lib.es2020.string.d.ts"], ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"], ["es2020.intl", "lib.es2020.intl.d.ts"], + ["es2021.promise", "lib.es2021.promise.d.ts"], + ["es2021.string", "lib.es2021.string.d.ts"], + ["es2021.weakref", "lib.es2021.weakref.d.ts"], ["esnext.array", "lib.es2019.array.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"], ["esnext.intl", "lib.esnext.intl.d.ts"], ["esnext.bigint", "lib.es2020.bigint.d.ts"], - ["esnext.string", "lib.esnext.string.d.ts"], - ["esnext.promise", "lib.esnext.promise.d.ts"], - ["esnext.weakref", "lib.esnext.weakref.d.ts"] + ["esnext.string", "lib.es2021.string.d.ts"], + ["esnext.promise", "lib.es2021.promise.d.ts"], + ["esnext.weakref", "lib.es2021.weakref.d.ts"] ]; /** * An array of supported "lib" reference file names used to determine the order for inclusion @@ -35895,11 +36929,12 @@ var ts; fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval, prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval, dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling, + fixedchunksizepolling: ts.WatchFileKind.FixedChunkSizePolling, usefsevents: ts.WatchFileKind.UseFsEvents, usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory, })), category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory, + description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling_UseFsEvents_UseFsEventsOnParentDirectory, }, { name: "watchDirectory", @@ -35907,9 +36942,10 @@ var ts; usefsevents: ts.WatchDirectoryKind.UseFsEvents, fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval, dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling, + fixedchunksizepolling: ts.WatchDirectoryKind.FixedChunkSizePolling, })), category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling, + description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling, }, { name: "fallbackPolling", @@ -35917,9 +36953,10 @@ var ts; fixedinterval: ts.PollingWatchKind.FixedInterval, priorityinterval: ts.PollingWatchKind.PriorityInterval, dynamicpriority: ts.PollingWatchKind.DynamicPriority, + fixedchunksize: ts.PollingWatchKind.FixedChunkSize, })), category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority, + description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority_FixedChunkSize, }, { name: "synchronousWatchDirectory", @@ -36078,6 +37115,7 @@ var ts; es2018: 5 /* ES2018 */, es2019: 6 /* ES2019 */, es2020: 7 /* ES2020 */, + es2021: 8 /* ES2021 */, esnext: 99 /* ESNext */, })), affectsSourceFile: true, @@ -36086,10 +37124,10 @@ var ts; paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT, }; - /* @internal */ - ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsWithoutBuild = [ + // CommandLine only options { name: "all", type: "boolean", @@ -36452,6 +37490,14 @@ var ts; category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Include_undefined_in_index_signature_results }, + { + name: "noImplicitOverride", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier + }, { name: "noPropertyAccessFromIndexSignature", type: "boolean", @@ -36867,7 +37913,9 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins }, - ]); + ]; + /* @internal */ + ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsWithoutBuild); /* @internal */ ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); /* @internal */ @@ -36882,8 +37930,7 @@ var ts; ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) { return ts.hasProperty(option, "transpileOptionValue"); }); - /* @internal */ - ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsOnlyBuild = [ { name: "verbose", shortName: "v", @@ -36911,7 +37958,9 @@ var ts; description: ts.Diagnostics.Delete_the_outputs_of_all_projects, type: "boolean" } - ]); + ]; + /* @internal */ + ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsOnlyBuild); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -36965,6 +38014,10 @@ var ts; return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations)); } ts.getOptionsNameMap = getOptionsNameMap; + var compilerOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_only_be_used_with_build, + getOptionsNameMap: getBuildOptionsNameMap + }; /* @internal */ ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, @@ -37026,6 +38079,10 @@ var ts; return option.name; } function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) { + var _a; + if ((_a = diagnostics.alternateMode) === null || _a === void 0 ? void 0 : _a.getOptionsNameMap().optionsNameMap.has(unknownOption.toLowerCase())) { + return createDiagnostics(diagnostics.alternateMode.diagnostic, unknownOption); + } var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName); return possibleOption ? createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : @@ -37180,6 +38237,7 @@ var ts; } /*@internal*/ ts.compilerOptionsDidYouMeanDiagnostics = { + alternateMode: compilerOptionsAlternateMode, getOptionsNameMap: getOptionsNameMap, optionDeclarations: ts.optionDeclarations, unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, @@ -37212,7 +38270,12 @@ var ts; function getBuildOptionsNameMap() { return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts)); } + var buildOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_not_be_used_with_build, + getOptionsNameMap: getOptionsNameMap + }; var buildOptionsDidYouMeanDiagnostics = { + alternateMode: buildOptionsAlternateMode, getOptionsNameMap: getBuildOptionsNameMap, optionDeclarations: ts.buildOpts, unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0, @@ -37288,7 +38351,7 @@ var ts; function parseConfigFileTextToJson(fileName, jsonText) { var jsonSourceFile = ts.parseJsonText(fileName, jsonText); return { - config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + config: convertConfigFileToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics, /*reportOptionsErrors*/ false, /*optionsIterator*/ undefined), error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined }; } @@ -37418,11 +38481,31 @@ var ts; } return _tsconfigRootOptions; } + function convertConfigFileToObject(sourceFile, errors, reportOptionsErrors, optionsIterator) { + var _a; + var rootExpression = (_a = sourceFile.statements[0]) === null || _a === void 0 ? void 0 : _a.expression; + var knownRootOptions = reportOptionsErrors ? getTsconfigRootOptionsMap() : undefined; + if (rootExpression && rootExpression.kind !== 201 /* ObjectLiteralExpression */) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, rootExpression, ts.Diagnostics.The_root_value_of_a_0_file_must_be_an_object, ts.getBaseFileName(sourceFile.fileName) === "jsconfig.json" ? "jsconfig.json" : "tsconfig.json")); + // Last-ditch error recovery. Somewhat useful because the JSON parser will recover from some parse errors by + // synthesizing a top-level array literal expression. There's a reasonable chance the first element of that + // array is a well-formed configuration object, made into an array element by stray characters. + if (ts.isArrayLiteralExpression(rootExpression)) { + var firstObject = ts.find(rootExpression.elements, ts.isObjectLiteralExpression); + if (firstObject) { + return convertToObjectWorker(sourceFile, firstObject, errors, /*returnValue*/ true, knownRootOptions, optionsIterator); + } + } + return {}; + } + return convertToObjectWorker(sourceFile, rootExpression, errors, /*returnValue*/ true, knownRootOptions, optionsIterator); + } /** * Convert the json syntax tree into the json value */ function convertToObject(sourceFile, errors) { - return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + var _a; + return convertToObjectWorker(sourceFile, (_a = sourceFile.statements[0]) === null || _a === void 0 ? void 0 : _a.expression, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); } ts.convertToObject = convertToObject; /** @@ -37431,18 +38514,18 @@ var ts; * Otherwise it just checks the errors and returns undefined */ /*@internal*/ - function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { - if (!sourceFile.statements.length) { + function convertToObjectWorker(sourceFile, rootExpression, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!rootExpression) { return returnValue ? {} : undefined; } - return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + return convertPropertyValueToJson(rootExpression, knownRootOptions); function isRootOptionMap(knownOptions) { return knownRootOptions && knownRootOptions.elementOptions === knownOptions; } function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) { var result = returnValue ? {} : undefined; var _loop_4 = function (element) { - if (element.kind !== 288 /* PropertyAssignment */) { + if (element.kind !== 289 /* PropertyAssignment */) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); return "continue"; } @@ -37536,13 +38619,13 @@ var ts; case 8 /* NumericLiteral */: reportInvalidOptionValue(option && option.type !== "number"); return validateValue(Number(valueExpression.text)); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { break; // not valid JSON syntax } reportInvalidOptionValue(option && option.type !== "number"); return validateValue(-Number(valueExpression.operand.text)); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; // Currently having element option declaration in the tsconfig with type "object" @@ -37559,7 +38642,7 @@ var ts; return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined)); } - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: reportInvalidOptionValue(option && option.type !== "list"); return validateValue(convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element)); } @@ -38107,14 +39190,14 @@ var ts; if (ownConfig.extendedConfigPath) { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, resolutionStack, errors, extendedConfigCache); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { var baseRaw_1 = extendedConfig.raw; var raw_1 = ownConfig.raw; + var relativeDifference_1; var setPropertyInRawIfNotUndefined = function (propertyName) { - var value = raw_1[propertyName] || baseRaw_1[propertyName]; - if (value) { - raw_1[propertyName] = value; + if (!raw_1[propertyName] && baseRaw_1[propertyName]) { + raw_1[propertyName] = ts.map(baseRaw_1[propertyName], function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1 || (relativeDifference_1 = ts.convertToRelativePath(ts.getDirectoryPath(ownConfig.extendedConfigPath), basePath, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames))), path); }); } }; setPropertyInRawIfNotUndefined("include"); @@ -38196,7 +39279,7 @@ var ts; } } }; - var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); + var json = convertConfigFileToObject(sourceFile, errors, /*reportOptionsErrors*/ true, optionsIterator); if (!typeAcquisition) { if (typingOptionstypeAcquisition) { typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? @@ -38234,7 +39317,7 @@ var ts; errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig)); return undefined; } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) { + function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache) { var _a; var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath); var value; @@ -38246,22 +39329,7 @@ var ts; else { extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (!extendedResult.parseDiagnostics.length) { - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); - if (isSuccessfulParsedTsconfig(extendedConfig)) { - // Update the paths to reflect base path - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); - var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; - var mapPropertiesInRawIfNotUndefined = function (propertyName) { - if (raw_2[propertyName]) { - raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); - } - }; - var raw_2 = extendedConfig.raw; - mapPropertiesInRawIfNotUndefined("include"); - mapPropertiesInRawIfNotUndefined("exclude"); - mapPropertiesInRawIfNotUndefined("files"); - } + extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, ts.getDirectoryPath(extendedConfigPath), ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); } if (extendedConfigCache) { extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig }); @@ -38958,13 +40026,24 @@ var ts; * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache) { var traceEnabled = isTraceEnabled(options, host); if (redirectedReference) { options = redirectedReference.commandLine.options; } - var failedLookupLocations = []; - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var containingDirectory = containingFile ? ts.getDirectoryPath(containingFile) : undefined; + var perFolderCache = containingDirectory ? cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference) : undefined; + var result = perFolderCache && perFolderCache.get(typeReferenceDirectiveName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile); + if (redirectedReference) + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + trace(host, ts.Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory); + traceResult(result); + } + return result; + } var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -38987,6 +40066,8 @@ var ts; trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); } } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -38997,17 +40078,31 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); - if (traceEnabled) { - if (packageId) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, ts.packageIdToString(packageId), primary); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); - } + resolvedTypeReferenceDirective = { + primary: primary, + resolvedFileName: resolvedFileName, + originalPath: fileName === resolvedFileName ? undefined : fileName, + packageId: packageId, + isExternalLibraryImport: pathContainsNodeModules(fileName), + }; + } + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, result); + if (traceEnabled) + traceResult(result); + return result; + function traceResult(result) { + var _a; + if (!((_a = result.resolvedTypeReferenceDirective) === null || _a === void 0 ? void 0 : _a.resolvedFileName)) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + else if (result.resolvedTypeReferenceDirective.packageId) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, ts.packageIdToString(result.resolvedTypeReferenceDirective.packageId), result.resolvedTypeReferenceDirective.primary); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, result.resolvedTypeReferenceDirective.primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } - return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { // Check primary library paths if (typeRoots && typeRoots.length) { @@ -39037,20 +40132,16 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = void 0; + var result_4; if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); - result = searchResult && searchResult.value; + result_4 = searchResult && searchResult.value; } else { var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; - result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); - } - var resolvedFile = resolvedTypeScriptOnly(result); - if (!resolvedFile && traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + result_4 = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); } - return resolvedFile; + return resolvedTypeScriptOnly(result_4); } else { if (traceEnabled) { @@ -39105,22 +40196,21 @@ var ts; return result; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; - function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) { - return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName); - } - ts.createModuleResolutionCache = createModuleResolutionCache; /*@internal*/ function createCacheWithRedirects(options) { var ownMap = new ts.Map(); var redirectsMap = new ts.Map(); return { - ownMap: ownMap, + getOwnMap: getOwnMap, redirectsMap: redirectsMap, getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, clear: clear, setOwnOptions: setOwnOptions, setOwnMap: setOwnMap }; + function getOwnMap() { + return ownMap; + } function setOwnOptions(newOptions) { options = newOptions; } @@ -39146,26 +40236,88 @@ var ts; } } ts.createCacheWithRedirects = createCacheWithRedirects; - /*@internal*/ - function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { - return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap }; + function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { + var cache; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear }; + function getPackageJsonInfo(packageJsonPath) { + return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); + } + function setPackageJsonInfo(packageJsonPath, info) { + (cache || (cache = new ts.Map())).set(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info); + } + function clear() { + cache = undefined; + } + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + function updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + if (!options.configFile) + return; + if (directoryToModuleNameMap.redirectsMap.size === 0) { + // The own map will be for projectCompilerOptions + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size === 0); + ts.Debug.assert(directoryToModuleNameMap.getOwnMap().size === 0); + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.getOwnMap().size === 0); + directoryToModuleNameMap.redirectsMap.set(options.configFile.path, directoryToModuleNameMap.getOwnMap()); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.redirectsMap.set(options.configFile.path, moduleNameToDirectoryMap.getOwnMap()); + } + else { + // Set correct own map + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size > 0); + var ref = { + sourceFile: options.configFile, + commandLine: { options: options } + }; + directoryToModuleNameMap.setOwnMap(directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnMap(moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); + } + directoryToModuleNameMap.setOwnOptions(options); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnOptions(options); + } + function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap) { + return { + getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, + clear: clear, + update: update, + }; + function clear() { + directoryToModuleNameMap.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap); + } function getOrCreateCacheForDirectory(directoryName, redirectedReference) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, function () { return new ts.Map(); }); } + } + function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + moduleNameToDirectoryMap || (moduleNameToDirectoryMap = createCacheWithRedirects(options)); + var packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName); + return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, + clear: clear, + update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; } }); + function clear() { + preDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + packageJsonInfoCache.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); + } function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); } - function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { - var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); - var result = cache.get(key); - if (!result) { - result = create(); - cache.set(key, result); - } - return result; - } function createPerModuleNameCache() { var directoryPathMap = new ts.Map(); return { get: get, set: set }; @@ -39232,7 +40384,17 @@ var ts; } } } - ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + ts.createModuleResolutionCache = createModuleResolutionCache; + function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { + var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); + return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + function clear() { + preDirectoryResolutionCache.clear(); + packageJsonInfoCache.clear(); + } + } + ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache) { var containingDirectory = ts.getDirectoryPath(containingFile); var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); @@ -39510,7 +40672,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, state.resultFromCache); function tryResolve(extensions) { @@ -39570,7 +40732,7 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { - var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined; return withPackageId(packageInfo, resolvedFromFile); } @@ -39603,8 +40765,9 @@ var ts; * For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo" * For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo" */ + /* @internal */ function parseNodeModuleFromPath(resolved) { - var path = ts.normalizePath(resolved.path); + var path = ts.normalizePath(resolved); var idx = path.lastIndexOf(ts.nodeModulesPathPart); if (idx === -1) { return undefined; @@ -39616,6 +40779,7 @@ var ts; } return path.slice(0, indexAfterPackageName); } + ts.parseNodeModuleFromPath = parseNodeModuleFromPath; function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; @@ -39699,21 +40863,43 @@ var ts; return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { + var _a, _b, _c; var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); + if (onlyRecordFailures) { + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + var existing = (_a = state.packageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfo(packageJsonPath); + if (existing !== undefined) { + if (typeof existing !== "boolean") { + if (traceEnabled) + trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + return existing; + } + else { + if (existing && traceEnabled) + trace(host, ts.Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + } + var directoryExists = ts.directoryProbablyExists(packageDirectory, host); if (directoryExists && host.fileExists(packageJsonPath)) { var packageJsonContent = ts.readJson(packageJsonPath, host); if (traceEnabled) { trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); - return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + return result; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + (_c = state.packageJsonInfoCache) === null || _c === void 0 ? void 0 : _c.setPackageJsonInfo(packageJsonPath, directoryExists); // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results state.failedLookupLocations.push(packageJsonPath); } @@ -39962,7 +41148,7 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath @@ -40003,13 +41189,13 @@ var ts; * This is the minumum code needed to expose that functionality; the rest is in the host. */ /* @internal */ - function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache, packageJsonInfoCache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache); } @@ -40055,26 +41241,26 @@ var ts; // A module is uninstantiated if it contains only switch (node.kind) { // 1. interface declarations, type alias declarations - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return 0 /* NonInstantiated */; // 2. const enum declarations - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: if (ts.isEnumConst(node)) { return 2 /* ConstEnumOnly */; } break; // 3. non-exported import declarations - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: if (!(ts.hasSyntacticModifier(node, 1 /* Export */))) { return 0 /* NonInstantiated */; } break; // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: var exportDeclaration = node; - if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 268 /* NamedExports */) { + if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 269 /* NamedExports */) { var state = 0 /* NonInstantiated */; for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; @@ -40090,7 +41276,7 @@ var ts; } break; // 5. other uninstantiated module declarations. - case 257 /* ModuleBlock */: { + case 258 /* ModuleBlock */: { var state_1 = 0 /* NonInstantiated */; ts.forEachChild(node, function (n) { var childState = getModuleInstanceStateCached(n, visited); @@ -40112,7 +41298,7 @@ var ts; }); return state_1; } - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return getModuleInstanceState(node, visited); case 78 /* Identifier */: // Only jsdoc typedef definition can exist in jsdoc namespace, and it should @@ -40184,14 +41370,14 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { - ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); ts.performance.measure("Bind", "beforeBind", "afterBind"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -40230,6 +41416,7 @@ var ts; var classifiableNames; var unreachableFlow = { flags: 1 /* Unreachable */ }; var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; + var bindBinaryExpressionFlow = createBindBinaryExpressionFlow(); /** * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) @@ -40312,7 +41499,7 @@ var ts; // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { - if (node.kind === 266 /* ExportAssignment */) { + if (node.kind === 267 /* ExportAssignment */) { return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; } var name = ts.getNameOfDeclaration(node); @@ -40321,7 +41508,7 @@ var ts; var moduleName = ts.getTextOfIdentifierOrLiteral(name); return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); } - if (name.kind === 158 /* ComputedPropertyName */) { + if (name.kind === 159 /* ComputedPropertyName */) { var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteralLike(nameExpression)) { @@ -40330,11 +41517,9 @@ var ts; if (ts.isSignedNumericLiteral(nameExpression)) { return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text; } - ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); - return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - if (ts.isWellKnownSymbolSyntactically(name)) { - return ts.getPropertyNameForKnownSymbolName(ts.idText(name.name)); + else { + ts.Debug.fail("Only computed properties with literal names have declaration names"); + } } if (ts.isPrivateIdentifier(name)) { // containingClass exists because private names only allowed inside classes @@ -40349,36 +41534,36 @@ var ts; return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return "__constructor" /* Constructor */; - case 174 /* FunctionType */: - case 169 /* CallSignature */: - case 313 /* JSDocSignature */: + case 175 /* FunctionType */: + case 170 /* CallSignature */: + case 315 /* JSDocSignature */: return "__call" /* Call */; - case 175 /* ConstructorType */: - case 170 /* ConstructSignature */: + case 176 /* ConstructorType */: + case 171 /* ConstructSignature */: return "__new" /* New */; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: return "__index" /* Index */; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return "__export" /* ExportStar */; - case 297 /* SourceFile */: + case 298 /* SourceFile */: // json file should behave as // module.exports = ... return "export=" /* ExportEquals */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); - case 160 /* Parameter */: + case 161 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 308 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + ts.Debug.assert(node.parent.kind === 309 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -40478,7 +41663,7 @@ var ts; // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if (symbol.declarations && symbol.declarations.length && - (node.kind === 266 /* ExportAssignment */ && !node.isExportEquals)) { + (node.kind === 267 /* ExportAssignment */ && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName_1 = false; multipleDefaultExports_1 = true; @@ -40517,7 +41702,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = !!(ts.getCombinedModifierFlags(node) & 1 /* Export */) || jsdocTreatAsExported(node); if (symbolFlags & 2097152 /* Alias */) { - if (node.kind === 270 /* ExportSpecifier */ || (node.kind === 260 /* ImportEqualsDeclaration */ && hasExportModifier)) { + if (node.kind === 271 /* ExportSpecifier */ || (node.kind === 261 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -40606,7 +41791,7 @@ var ts; // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. if (containerFlags & 1 /* IsContainer */) { - if (node.kind !== 209 /* ArrowFunction */) { + if (node.kind !== 210 /* ArrowFunction */) { thisParentContainer = container; } container = blockScopeContainer = node; @@ -40639,7 +41824,7 @@ var ts; } // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property initialization checks. - currentReturnTarget = isIIFE || node.kind === 166 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */)) ? createBranchLabel() : undefined; + currentReturnTarget = isIIFE || node.kind === 167 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 252 /* FunctionDeclaration */ || node.kind === 209 /* FunctionExpression */)) ? createBranchLabel() : undefined; currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; @@ -40654,13 +41839,14 @@ var ts; node.flags |= 512 /* HasExplicitReturn */; node.endFlowNode = currentFlow; } - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { node.flags |= emitFlags; + node.endFlowNode = currentFlow; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 166 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */))) { + if (node.kind === 167 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 252 /* FunctionDeclaration */ || node.kind === 209 /* FunctionExpression */))) { node.returnFlowNode = currentFlow; } } @@ -40687,8 +41873,8 @@ var ts; blockScopeContainer = savedBlockScopeContainer; } function bindEachFunctionsFirst(nodes) { - bindEach(nodes, function (n) { return n.kind === 251 /* FunctionDeclaration */ ? bind(n) : undefined; }); - bindEach(nodes, function (n) { return n.kind !== 251 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind === 252 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 252 /* FunctionDeclaration */ ? bind(n) : undefined; }); } function bindEach(nodes, bindFunction) { if (bindFunction === void 0) { bindFunction = bind; } @@ -40711,59 +41897,59 @@ var ts; inAssignmentPattern = saveInAssignmentPattern; return; } - if (node.kind >= 232 /* FirstStatement */ && node.kind <= 248 /* LastStatement */ && !options.allowUnreachableCode) { + if (node.kind >= 233 /* FirstStatement */ && node.kind <= 249 /* LastStatement */ && !options.allowUnreachableCode) { node.flowNode = currentFlow; } switch (node.kind) { - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: bindWhileStatement(node); break; - case 235 /* DoStatement */: + case 236 /* DoStatement */: bindDoStatement(node); break; - case 237 /* ForStatement */: + case 238 /* ForStatement */: bindForStatement(node); break; - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: bindForInOrForOfStatement(node); break; - case 234 /* IfStatement */: + case 235 /* IfStatement */: bindIfStatement(node); break; - case 242 /* ReturnStatement */: - case 246 /* ThrowStatement */: + case 243 /* ReturnStatement */: + case 247 /* ThrowStatement */: bindReturnOrThrow(node); break; - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 247 /* TryStatement */: + case 248 /* TryStatement */: bindTryStatement(node); break; - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: bindSwitchStatement(node); break; - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: bindCaseBlock(node); break; - case 284 /* CaseClause */: + case 285 /* CaseClause */: bindCaseClause(node); break; - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: bindExpressionStatement(node); break; - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: bindLabeledStatement(node); break; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: bindPostfixUnaryExpressionFlow(node); break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.isDestructuringAssignment(node)) { // Carry over whether we are in an assignment pattern to // binary expressions that could actually be an initializer @@ -40773,47 +41959,47 @@ var ts; } bindBinaryExpressionFlow(node); break; - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: bindDeleteExpressionFlow(node); break; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: bindConditionalExpressionFlow(node); break; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: bindVariableDeclarationFlow(node); break; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: bindAccessExpressionFlow(node); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: bindCallExpressionFlow(node); break; - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: bindNonNullExpressionFlow(node); break; - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: bindJSDocTypeAlias(node); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime - case 297 /* SourceFile */: { + case 298 /* SourceFile */: { bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); break; } - case 230 /* Block */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 258 /* ModuleBlock */: bindEachFunctionsFirst(node.statements); break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: bindBindingElementFlow(node); break; - case 200 /* ObjectLiteralExpression */: - case 199 /* ArrayLiteralExpression */: - case 288 /* PropertyAssignment */: - case 220 /* SpreadElement */: + case 201 /* ObjectLiteralExpression */: + case 200 /* ArrayLiteralExpression */: + case 289 /* PropertyAssignment */: + case 221 /* SpreadElement */: // Carry over whether we are in an assignment pattern of Object and Array literals // as well as their children that are valid assignment targets. inAssignmentPattern = saveInAssignmentPattern; @@ -40830,29 +42016,29 @@ var ts; case 78 /* Identifier */: case 79 /* PrivateIdentifier */: case 107 /* ThisKeyword */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return containsNarrowableReference(expr); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return hasNarrowableArgument(expr); - case 207 /* ParenthesizedExpression */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: return isNarrowingExpression(expr.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return isNarrowingBinaryExpression(expr); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return isNarrowingExpression(expr.expression); } return false; } function isNarrowableReference(expr) { - return expr.kind === 78 /* Identifier */ || expr.kind === 79 /* PrivateIdentifier */ || expr.kind === 107 /* ThisKeyword */ || expr.kind === 105 /* SuperKeyword */ || - (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isBinaryExpression(expr) && expr.operatorToken.kind === 27 /* CommaToken */ && isNarrowableReference(expr.right) || - ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || - ts.isAssignmentExpression(expr) && isNarrowableReference(expr.left); + return ts.isDottedName(expr) + || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) + || ts.isBinaryExpression(expr) && expr.operatorToken.kind === 27 /* CommaToken */ && isNarrowableReference(expr.right) + || ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) + || ts.isAssignmentExpression(expr) && isNarrowableReference(expr.left); } function containsNarrowableReference(expr) { return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression); @@ -40866,7 +42052,7 @@ var ts; } } } - if (expr.expression.kind === 201 /* PropertyAccessExpression */ && + if (expr.expression.kind === 202 /* PropertyAccessExpression */ && containsNarrowableReference(expr.expression.expression)) { return true; } @@ -40902,9 +42088,9 @@ var ts; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isNarrowableOperand(expr.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (expr.operatorToken.kind) { case 62 /* EqualsToken */: return isNarrowableOperand(expr.left); @@ -40980,26 +42166,26 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 234 /* IfStatement */: - case 236 /* WhileStatement */: - case 235 /* DoStatement */: + case 235 /* IfStatement */: + case 237 /* WhileStatement */: + case 236 /* DoStatement */: return parent.expression === node; - case 237 /* ForStatement */: - case 217 /* ConditionalExpression */: + case 238 /* ForStatement */: + case 218 /* ConditionalExpression */: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 207 /* ParenthesizedExpression */) { + if (node.kind === 208 /* ParenthesizedExpression */) { node = node.expression; } - else if (node.kind === 214 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) { + else if (node.kind === 215 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) { node = node.operand; } else { - return node.kind === 216 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ || + return node.kind === 217 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */); } @@ -41046,7 +42232,7 @@ var ts; } function setContinueTarget(node, target) { var label = activeLabelList; - while (label && node.parent.kind === 245 /* LabeledStatement */) { + while (label && node.parent.kind === 246 /* LabeledStatement */) { label.continueTarget = target; label = label.next; node = node.parent; @@ -41097,12 +42283,12 @@ var ts; bind(node.expression); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 239 /* ForOfStatement */) { + if (node.kind === 240 /* ForOfStatement */) { bind(node.awaitModifier); } addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 250 /* VariableDeclarationList */) { + if (node.initializer.kind !== 251 /* VariableDeclarationList */) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -41124,7 +42310,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 242 /* ReturnStatement */) { + if (node.kind === 243 /* ReturnStatement */) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -41141,7 +42327,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 241 /* BreakStatement */ ? breakTarget : continueTarget; + var flowLabel = node.kind === 242 /* BreakStatement */ ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -41246,7 +42432,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 285 /* DefaultClause */; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 286 /* DefaultClause */; }); // We mark a switch statement as possibly exhaustive if it has no default clause and if all // case clauses have unreachable end points (e.g. they all return). Note, we no longer need // this property in control flow analysis, it's there only for backwards compatibility. @@ -41294,9 +42480,9 @@ var ts; function maybeBindExpressionFlowIfCall(node) { // A top level or LHS of comma expression call expression with a dotted function name and at least one argument // is potentially an assertion and is therefore included in the control flow. - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { var call = node; - if (ts.isDottedName(call.expression) && call.expression.kind !== 105 /* SuperKeyword */) { + if (call.expression.kind !== 105 /* SuperKeyword */ && ts.isDottedName(call.expression)) { currentFlow = createFlowCall(currentFlow, call); } } @@ -41320,7 +42506,7 @@ var ts; currentFlow = finishFlowLabel(postStatementLabel); } function bindDestructuringTargetFlow(node) { - if (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) { + if (node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) { bindAssignmentTargetFlow(node.left); } else { @@ -41331,10 +42517,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node); } - else if (node.kind === 199 /* ArrayLiteralExpression */) { + else if (node.kind === 200 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 220 /* SpreadElement */) { + if (e.kind === 221 /* SpreadElement */) { bindAssignmentTargetFlow(e.expression); } else { @@ -41342,16 +42528,16 @@ var ts; } } } - else if (node.kind === 200 /* ObjectLiteralExpression */) { + else if (node.kind === 201 /* ObjectLiteralExpression */) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 288 /* PropertyAssignment */) { + if (p.kind === 289 /* PropertyAssignment */) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 289 /* ShorthandPropertyAssignment */) { + else if (p.kind === 290 /* ShorthandPropertyAssignment */) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 290 /* SpreadAssignment */) { + else if (p.kind === 291 /* SpreadAssignment */) { bindAssignmentTargetFlow(p.expression); } } @@ -41416,128 +42602,102 @@ var ts; } bindAssignmentTargetFlow(node.left); } - var BindBinaryExpressionFlowState; - (function (BindBinaryExpressionFlowState) { - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindThenBindChildren"] = 0] = "BindThenBindChildren"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["MaybeBindLeft"] = 1] = "MaybeBindLeft"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindToken"] = 2] = "BindToken"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindRight"] = 3] = "BindRight"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["FinishBind"] = 4] = "FinishBind"; - })(BindBinaryExpressionFlowState || (BindBinaryExpressionFlowState = {})); - function bindBinaryExpressionFlow(node) { - var workStacks = { - expr: [node], - state: [1 /* MaybeBindLeft */], - inStrictMode: [undefined], - parent: [undefined], - }; - var stackIndex = 0; - while (stackIndex >= 0) { - node = workStacks.expr[stackIndex]; - switch (workStacks.state[stackIndex]) { - case 0 /* BindThenBindChildren */: { - // This state is used only when recuring, to emulate the work that `bind` does before - // reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work. - ts.setParent(node, parent); - var saveInStrictMode = inStrictMode; - bindWorker(node); - var saveParent = parent; - parent = node; - advanceState(1 /* MaybeBindLeft */, saveInStrictMode, saveParent); - break; - } - case 1 /* MaybeBindLeft */: { - var operator = node.operatorToken.kind; - // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions - // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too - // For now, though, since the common cases are chained `+`, leaving it recursive is fine - if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */ || - ts.isLogicalOrCoalescingAssignmentOperator(operator)) { - if (isTopLevelLogicalExpression(node)) { - var postExpressionLabel = createBranchLabel(); - bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel); - currentFlow = finishFlowLabel(postExpressionLabel); - } - else { - bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget); - } - completeNode(); - } - else { - advanceState(2 /* BindToken */); - maybeBind(node.left); - } - break; + function createBindBinaryExpressionFlow() { + return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined); + function onEnter(node, state) { + if (state) { + state.stackIndex++; + // Emulate the work that `bind` does before reaching `bindChildren`. A normal call to + // `bindBinaryExpressionFlow` will already have done this work. + ts.setParent(node, parent); + var saveInStrictMode = inStrictMode; + bindWorker(node); + var saveParent = parent; + parent = node; + state.skip = false; + state.inStrictModeStack[state.stackIndex] = saveInStrictMode; + state.parentStack[state.stackIndex] = saveParent; + } + else { + state = { + stackIndex: 0, + skip: false, + inStrictModeStack: [undefined], + parentStack: [undefined] + }; + } + // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions + // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too + // For now, though, since the common cases are chained `+`, leaving it recursive is fine + var operator = node.operatorToken.kind; + if (operator === 55 /* AmpersandAmpersandToken */ || + operator === 56 /* BarBarToken */ || + operator === 60 /* QuestionQuestionToken */ || + ts.isLogicalOrCoalescingAssignmentOperator(operator)) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); } - case 2 /* BindToken */: { - if (node.operatorToken.kind === 27 /* CommaToken */) { - maybeBindExpressionFlowIfCall(node.left); - } - advanceState(3 /* BindRight */); - maybeBind(node.operatorToken); - break; + else { + bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget); } - case 3 /* BindRight */: { - advanceState(4 /* FinishBind */); - maybeBind(node.right); - break; + state.skip = true; + } + return state; + } + function onLeft(left, state, _node) { + if (!state.skip) { + return maybeBind(left); + } + } + function onOperator(operatorToken, state, node) { + if (!state.skip) { + if (operatorToken.kind === 27 /* CommaToken */) { + maybeBindExpressionFlowIfCall(node.left); } - case 4 /* FinishBind */: { - var operator = node.operatorToken.kind; - if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { - bindAssignmentTargetFlow(node.left); - if (operator === 62 /* EqualsToken */ && node.left.kind === 202 /* ElementAccessExpression */) { - var elementAccess = node.left; - if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); - } + bind(operatorToken); + } + } + function onRight(right, state, _node) { + if (!state.skip) { + return maybeBind(right); + } + } + function onExit(node, state) { + if (!state.skip) { + var operator = node.operatorToken.kind; + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 62 /* EqualsToken */ && node.left.kind === 203 /* ElementAccessExpression */) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); } } - completeNode(); - break; } - default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for bindBinaryExpressionFlow"); - } - } - /** - * Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new - * head state; so `advanceState` must be called before any `maybeBind` during a state's execution. - */ - function advanceState(state, isInStrictMode, parent) { - workStacks.state[stackIndex] = state; - if (isInStrictMode !== undefined) { - workStacks.inStrictMode[stackIndex] = isInStrictMode; } - if (parent !== undefined) { - workStacks.parent[stackIndex] = parent; + var savedInStrictMode = state.inStrictModeStack[state.stackIndex]; + var savedParent = state.parentStack[state.stackIndex]; + if (savedInStrictMode !== undefined) { + inStrictMode = savedInStrictMode; } - } - function completeNode() { - if (workStacks.inStrictMode[stackIndex] !== undefined) { - inStrictMode = workStacks.inStrictMode[stackIndex]; - parent = workStacks.parent[stackIndex]; + if (savedParent !== undefined) { + parent = savedParent; } - stackIndex--; + state.skip = false; + state.stackIndex--; } - /** - * If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it - */ function maybeBind(node) { if (node && ts.isBinaryExpression(node) && !ts.isDestructuringAssignment(node)) { - stackIndex++; - workStacks.expr[stackIndex] = node; - workStacks.state[stackIndex] = 0 /* BindThenBindChildren */; - workStacks.inStrictMode[stackIndex] = undefined; - workStacks.parent[stackIndex] = undefined; - } - else { - bind(node); + return node; } + bind(node); } } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 201 /* PropertyAccessExpression */) { + if (node.expression.kind === 202 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -41594,7 +42754,7 @@ var ts; } function bindJSDocTypeAlias(node) { ts.setParent(node.tagName, node); - if (node.kind !== 325 /* JSDocEnumTag */ && node.fullName) { + if (node.kind !== 329 /* JSDocEnumTag */ && node.fullName) { ts.setParent(node.fullName, node); ts.setParentRecursive(node.fullName, /*incremental*/ false); } @@ -41602,7 +42762,7 @@ var ts; function bindJSDocClassTag(node) { bindEachChild(node); var host = ts.getHostSignatureFromJSDoc(node); - if (host && host.kind !== 165 /* MethodDeclaration */) { + if (host && host.kind !== 166 /* MethodDeclaration */) { addDeclarationToSymbol(host.symbol, host, 32 /* Class */); } } @@ -41615,15 +42775,15 @@ var ts; } function bindOptionalChainRest(node) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: bind(node.questionDotToken); bind(node.name); break; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: bind(node.questionDotToken); bind(node.argumentExpression); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: bind(node.questionDotToken); bindEach(node.typeArguments); bindEach(node.arguments); @@ -41688,7 +42848,7 @@ var ts; // an immediately invoked function expression (IIFE). Initialize the flowNode property to // the current control flow (which includes evaluation of the IIFE arguments). var expr = ts.skipParentheses(node.expression); - if (expr.kind === 208 /* FunctionExpression */ || expr.kind === 209 /* ArrowFunction */) { + if (expr.kind === 209 /* FunctionExpression */ || expr.kind === 210 /* ArrowFunction */) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -41700,7 +42860,7 @@ var ts; } } } - if (node.expression.kind === 201 /* PropertyAccessExpression */) { + if (node.expression.kind === 202 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); @@ -41709,54 +42869,54 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 200 /* ObjectLiteralExpression */: - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 281 /* JsxAttributes */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 201 /* ObjectLiteralExpression */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 282 /* JsxAttributes */: return 1 /* IsContainer */; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return 1 /* IsContainer */ | 64 /* IsInterface */; - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 190 /* MappedType */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 191 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 297 /* SourceFile */: + case 298 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; } // falls through - case 166 /* Constructor */: - case 251 /* FunctionDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 169 /* CallSignature */: - case 313 /* JSDocSignature */: - case 308 /* JSDocFunctionType */: - case 174 /* FunctionType */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 175 /* ConstructorType */: + case 167 /* Constructor */: + case 252 /* FunctionDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 170 /* CallSignature */: + case 315 /* JSDocSignature */: + case 309 /* JSDocFunctionType */: + case 175 /* FunctionType */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 176 /* ConstructorType */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return 4 /* IsControlFlowContainer */; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 287 /* CatchClause */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 258 /* CaseBlock */: + case 288 /* CatchClause */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 259 /* CaseBlock */: return 2 /* IsBlockScopedContainer */; - case 230 /* Block */: + case 231 /* Block */: // do not treat blocks directly inside a function as a block-scoped-container. // Locals that reside in this block should go to the function locals. Otherwise 'x' // would not appear to be a redeclaration of a block scoped local in the following @@ -41789,45 +42949,45 @@ var ts; // members are declared (for example, a member of a class will go into a specific // symbol table depending on if it is static or not). We defer to specialized // handlers to take care of declaring these child members. - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 297 /* SourceFile */: + case 298 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 200 /* ObjectLiteralExpression */: - case 253 /* InterfaceDeclaration */: - case 281 /* JsxAttributes */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 201 /* ObjectLiteralExpression */: + case 254 /* InterfaceDeclaration */: + case 282 /* JsxAttributes */: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the // object / type / interface declaring them). An exception is type parameters, // which are in scope without qualification (similar to 'locals'). return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 313 /* JSDocSignature */: - case 171 /* IndexSignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 308 /* JSDocFunctionType */: - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 254 /* TypeAliasDeclaration */: - case 190 /* MappedType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 315 /* JSDocSignature */: + case 172 /* IndexSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 309 /* JSDocFunctionType */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 255 /* TypeAliasDeclaration */: + case 191 /* MappedType */: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -41928,7 +43088,7 @@ var ts; var seen = new ts.Map(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 290 /* SpreadAssignment */ || prop.name.kind !== 78 /* Identifier */) { + if (prop.kind === 291 /* SpreadAssignment */ || prop.name.kind !== 78 /* Identifier */) { continue; } var identifier = prop.name; @@ -41940,7 +43100,7 @@ var ts; // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 288 /* PropertyAssignment */ || prop.kind === 289 /* ShorthandPropertyAssignment */ || prop.kind === 165 /* MethodDeclaration */ + var currentKind = prop.kind === 289 /* PropertyAssignment */ || prop.kind === 290 /* ShorthandPropertyAssignment */ || prop.kind === 166 /* MethodDeclaration */ ? 1 /* Property */ : 2 /* Accessor */; var existingKind = seen.get(identifier.escapedText); @@ -41972,10 +43132,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (ts.isExternalOrCommonJsModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -42000,9 +43160,9 @@ var ts; var saveCurrentFlow = currentFlow; for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { var typeAlias = delayedTypeAliases_1[_i]; - var host = ts.getJSDocHost(typeAlias); - container = (host && ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); })) || file; - blockScopeContainer = (host && ts.getEnclosingBlockScopeContainer(host)) || file; + var host = typeAlias.parent.parent; + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); @@ -42174,8 +43334,8 @@ var ts; function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2 /* ES2015 */) { // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 297 /* SourceFile */ && - blockScopeContainer.kind !== 256 /* ModuleDeclaration */ && + if (blockScopeContainer.kind !== 298 /* SourceFile */ && + blockScopeContainer.kind !== 257 /* ModuleDeclaration */ && !ts.isFunctionLike(blockScopeContainer)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. @@ -42270,7 +43430,7 @@ var ts; // the current 'container' node when it changes. This helps us know which symbol table // a local should go into for example. Since terminal nodes are known not to have // children, as an optimization we don't process those. - if (node.kind > 156 /* LastToken */) { + if (node.kind > 157 /* LastToken */) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -42346,17 +43506,23 @@ var ts; } // falls through case 107 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 289 /* ShorthandPropertyAssignment */)) { + if (currentFlow && (ts.isExpression(node) || parent.kind === 290 /* ShorthandPropertyAssignment */)) { node.flowNode = currentFlow; } return checkContextualIdentifier(node); + case 158 /* QualifiedName */: + if (currentFlow && parent.kind === 177 /* TypeQuery */) { + node.flowNode = currentFlow; + } + break; + case 227 /* MetaProperty */: case 105 /* SuperKeyword */: node.flowNode = currentFlow; break; case 79 /* PrivateIdentifier */: return checkPrivateIdentifier(node); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: var expr = node; if (currentFlow && isNarrowableReference(expr)) { expr.flowNode = currentFlow; @@ -42371,7 +43537,7 @@ var ts; declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */); } break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: @@ -42407,78 +43573,78 @@ var ts; ts.Debug.fail("Unknown binary expression special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return checkStrictModeCatchClause(node); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return checkStrictModeDeleteExpression(node); case 8 /* NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return checkStrictModeWithStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return checkStrictModeLabeledStatement(node); - case 187 /* ThisType */: + case 188 /* ThisType */: seenThisKeyword = true; return; - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: break; // Binding the children will handle everything - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return bindTypeParameter(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return bindParameter(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return bindVariableDeclarationOrBindingElement(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return bindPropertyWorker(node); - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 291 /* EnumMember */: + case 292 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: // If this is an ObjectLiteralExpression method, then it sits in the same space // 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 */ : 103359 /* MethodExcludes */); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return bindFunctionDeclaration(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */); - case 174 /* FunctionType */: - case 308 /* JSDocFunctionType */: - case 313 /* JSDocSignature */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 309 /* JSDocFunctionType */: + case 315 /* JSDocSignature */: + case 176 /* ConstructorType */: return bindFunctionOrConstructorType(node); - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 190 /* MappedType */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 191 /* MappedType */: return bindAnonymousTypeWorker(node); - case 319 /* JSDocClassTag */: + case 322 /* JSDocClassTag */: return bindJSDocClassTag(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return bindFunctionExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: var assignmentKind = ts.getAssignmentDeclarationKind(node); switch (assignmentKind) { case 7 /* ObjectDefinePropertyValue */: @@ -42497,65 +43663,65 @@ var ts; } break; // Members of classes, interfaces, and modules - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: // All classes are automatically in strict mode in ES6. inStrictMode = true; return bindClassLikeDeclaration(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return bindEnumDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return bindModuleDeclaration(node); // Jsx-attributes - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return bindJsxAttributes(node); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); // Imports and exports - case 260 /* ImportEqualsDeclaration */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 261 /* ImportEqualsDeclaration */: + case 264 /* NamespaceImport */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return bindNamespaceExportDeclaration(node); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return bindImportClause(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return bindExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return bindExportAssignment(node); - case 297 /* SourceFile */: + case 298 /* SourceFile */: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 230 /* Block */: + case 231 /* Block */: if (!ts.isFunctionLike(node.parent)) { return; } // falls through - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 326 /* JSDocParameterTag */: - if (node.parent.kind === 313 /* JSDocSignature */) { + case 330 /* JSDocParameterTag */: + if (node.parent.kind === 315 /* JSDocSignature */) { return bindParameter(node); } - if (node.parent.kind !== 312 /* JSDocTypeLiteral */) { + if (node.parent.kind !== 314 /* JSDocTypeLiteral */) { break; } // falls through - case 333 /* JSDocPropertyTag */: + case 337 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 307 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 308 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } @@ -42583,8 +43749,8 @@ var ts; } function bindExportAssignment(node) { if (!container.symbol || !container.symbol.exports) { - // Export assignment in some sort of block construct - bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + // Incorrect export assignment in some sort of block construct + bindAnonymousDeclaration(node, 111551 /* Value */, getDeclarationName(node)); } else { var flags = ts.exportAssignmentIsAlias(node) @@ -42718,8 +43884,8 @@ var ts; } var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: var constructorSymbol = thisContainer.symbol; // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 62 /* EqualsToken */) { @@ -42741,11 +43907,11 @@ var ts; addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */); } break; - case 166 /* Constructor */: - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 167 /* Constructor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // this.foo assignment in a JavaScript class // Bind this property to the containing class var containingClass = thisContainer.parent; @@ -42757,7 +43923,7 @@ var ts; declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true); } break; - case 297 /* SourceFile */: + case 298 /* SourceFile */: // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script if (ts.hasDynamicName(node)) { break; @@ -42786,7 +43952,7 @@ var ts; if (node.expression.kind === 107 /* ThisKeyword */) { bindThisPropertyAssignment(node); } - else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 297 /* SourceFile */) { + else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 298 /* SourceFile */) { if (ts.isPrototypeAccess(node.expression)) { bindPrototypePropertyAssignment(node, node.parent); } @@ -42826,7 +43992,7 @@ var ts; } function bindObjectDefinePropertyAssignment(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); - var isToplevel = node.parent.parent.kind === 297 /* SourceFile */; + var isToplevel = node.parent.parent.kind === 298 /* SourceFile */; namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false); bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); } @@ -42935,8 +44101,8 @@ var ts; } function isTopLevelNamespaceAssignment(propertyAccess) { return ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 297 /* SourceFile */ - : propertyAccess.parent.parent.kind === 297 /* SourceFile */; + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 298 /* SourceFile */ + : propertyAccess.parent.parent.kind === 298 /* SourceFile */; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) { var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer); @@ -43015,7 +44181,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 252 /* ClassDeclaration */) { + if (node.kind === 253 /* ClassDeclaration */) { bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */); } else { @@ -43057,7 +44223,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { - if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true) && !ts.getJSDocTypeTag(node)) { + if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node) && !ts.getJSDocTypeTag(node)) { declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } else if (ts.isBlockOrCatchScoped(node)) { @@ -43081,7 +44247,7 @@ var ts; } } function bindParameter(node) { - if (node.kind === 326 /* JSDocParameterTag */ && container.kind !== 313 /* JSDocSignature */) { + if (node.kind === 330 /* JSDocParameterTag */ && container.kind !== 315 /* JSDocSignature */) { return; } if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) { @@ -43158,7 +44324,7 @@ var ts; declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */); } } - else if (node.parent.kind === 185 /* InferType */) { + else if (node.parent.kind === 186 /* InferType */) { var container_2 = getInferTypeContainer(node.parent); if (container_2) { if (!container_2.locals) { @@ -43177,7 +44343,7 @@ var ts; // reachability checks function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && ts.shouldPreserveConstEnums(options)); } function checkUnreachable(node) { if (!(currentFlow.flags & 1 /* Unreachable */)) { @@ -43186,11 +44352,11 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 231 /* EmptyStatement */) || + (ts.isStatementButNotDeclaration(node) && node.kind !== 232 /* EmptyStatement */) || // report error on class declarations - node.kind === 252 /* ClassDeclaration */ || + node.kind === 253 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 256 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); + (node.kind === 257 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -43234,12 +44400,12 @@ var ts; } function isPurelyTypeDeclaration(s) { switch (s.kind) { - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return true; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return getModuleInstanceState(s) !== 1 /* Instantiated */; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return ts.hasSyntacticModifier(s, 2048 /* Const */); default: return false; @@ -43439,7 +44605,7 @@ var ts; // (their type resolved directly to the member deeply referenced) // So to get the intervening symbols, we need to check if there's a type // query node on any of the symbol's declarations and get symbols there - if (d.type && d.type.kind === 176 /* TypeQuery */) { + if (d.type && d.type.kind === 177 /* TypeQuery */) { var query = d.type; var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); visitSymbol(entity); @@ -43666,6 +44832,7 @@ var ts; DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor"; DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment"; DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method"; + DeclarationMeaning[DeclarationMeaning["PrivateStatic"] = 16] = "PrivateStatic"; DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor"; DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod"; })(DeclarationMeaning || (DeclarationMeaning = {})); @@ -43757,12 +44924,12 @@ var ts; var instantiationCount = 0; var instantiationDepth = 0; var currentNode; - var typeCatalog = []; // NB: id is index + 1 var emptySymbols = ts.createSymbolTable(); var arrayVariances = [1 /* Covariant */]; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); @@ -43771,7 +44938,8 @@ var ts; var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16384 /* FreshLiteral */; + var checkBinaryExpression = createCheckBinaryExpression(); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); var globals = ts.createSymbolTable(); @@ -43794,7 +44962,6 @@ var ts; getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, - getTypeCatalog: function () { return typeCatalog; }, getTypeCount: function () { return typeCount; }, getInstantiationCount: function () { return totalInstantiationCount; }, getRelationCacheSizes: function () { return ({ @@ -43958,6 +45125,7 @@ var ts; return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, + getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: function (node, candidatesOutArray, argumentCount) { return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */); @@ -44001,6 +45169,7 @@ var ts; }, tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); }, + tryFindAmbientModule: function (moduleName) { return tryFindAmbientModule(moduleName, /*withAugmentations*/ true); }, tryFindAmbientModuleWithoutAugmentations: function (moduleName) { // we deliberately exclude augmentations // since we are only interested in declarations of the module itself @@ -44119,6 +45288,7 @@ var ts; var templateLiteralTypes = new ts.Map(); var stringMappingTypes = new ts.Map(); var substitutionTypes = new ts.Map(); + var subtypeReductionCache = new ts.Map(); var evolvingArrayTypes = []; var undefinedProperties = new ts.Map(); var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -44127,14 +45297,14 @@ var ts; var autoType = createIntrinsicType(1 /* Any */, "any"); var wildcardType = createIntrinsicType(1 /* Any */, "any"); var errorType = createIntrinsicType(1 /* Any */, "error"); - var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */); + var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 131072 /* ContainsWideningType */); var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */); var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined"); var nullType = createIntrinsicType(65536 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 131072 /* ContainsWideningType */); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); @@ -44160,7 +45330,7 @@ var ts; var voidType = createIntrinsicType(16384 /* Void */, "void"); var neverType = createIntrinsicType(131072 /* Never */, "never"); var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); - var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */); + var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 524288 /* NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); @@ -44172,7 +45342,7 @@ var ts; var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; + emptyJsxObjectType.objectFlags |= 2048 /* JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -44181,7 +45351,7 @@ var ts; var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */; + anyFunctionType.objectFlags |= 524288 /* NonInferrableType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -44261,6 +45431,7 @@ var ts; // This allows users to just specify library files they want to used through --lib // and they will not get an error from not having unrelated library files var deferredGlobalESSymbolConstructorSymbol; + var deferredGlobalESSymbolConstructorTypeSymbol; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; @@ -44312,7 +45483,7 @@ var ts; var flowNodePostSuper = []; var potentialThisCollisions = []; var potentialNewTargetCollisions = []; - var potentialWeakMapCollisions = []; + var potentialWeakMapSetCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); var suggestionDiagnostics = ts.createDiagnosticCollection(); @@ -44459,6 +45630,25 @@ var ts; } return diagnostic; } + function addDeprecatedSuggestionWorker(declarations, diagnostic) { + var deprecatedTag = Array.isArray(declarations) ? ts.forEach(declarations, ts.getJSDocDeprecatedTag) : ts.getJSDocDeprecatedTag(declarations); + if (deprecatedTag) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(deprecatedTag, ts.Diagnostics.The_declaration_was_marked_as_deprecated_here)); + } + // We call `addRelatedInfo()` before adding the diagnostic to prevent duplicates. + suggestionDiagnostics.add(diagnostic); + return diagnostic; + } + function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { + var diagnostic = ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, deprecatedEntity); + return addDeprecatedSuggestionWorker(declarations, diagnostic); + } + function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) { + var diagnostic = deprecatedEntity + ? ts.createDiagnosticForNode(location, ts.Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity) + : ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, signatureString); + return addDeprecatedSuggestionWorker(declaration, diagnostic); + } function createSymbol(flags, name, checkFlags) { symbolCount++; var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); @@ -44572,7 +45762,7 @@ var ts; // as we will already report a "Declaration name conflicts..." error, and this error // won't make much sense. if (target !== globalThisSymbol) { - error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(source.declarations && ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } } else { // error @@ -44606,9 +45796,11 @@ var ts; } return target; function addDuplicateLocations(locs, symbol) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - ts.pushIfUnique(locs, decl); + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, decl); + } } } } @@ -44654,9 +45846,9 @@ var ts; }); } function mergeModuleAugmentation(moduleName) { - var _a, _b; + var _a, _b, _c; var moduleAugmentation = moduleName.parent; - if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + if (((_a = moduleAugmentation.symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]) !== moduleAugmentation) { // this is a combined symbol for multiple augmentations within the same file. // its symbol already has accumulated information for all declarations // so we need to add it just once - do the work only for first declaration @@ -44693,11 +45885,11 @@ var ts; patternAmbientModuleAugmentations.set(moduleName.text, merged); } else { - if (((_a = mainModule_1.exports) === null || _a === void 0 ? void 0 : _a.get("__export" /* ExportStar */)) && ((_b = moduleAugmentation.symbol.exports) === null || _b === void 0 ? void 0 : _b.size)) { + if (((_b = mainModule_1.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */)) && ((_c = moduleAugmentation.symbol.exports) === null || _c === void 0 ? void 0 : _c.size)) { // We may need to merge the module augmentation's exports into the target symbols of the resolved exports var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */); - for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) { - var _d = _c[_i], key = _d[0], value = _d[1]; + for (var _i = 0, _d = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _d.length; _i++) { + var _e = _d[_i], key = _e[0], value = _e[1]; if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) { mergeSymbol(resolvedExports.get(key), value); } @@ -44738,7 +45930,7 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks()); } function isGlobalSourceFile(node) { - return node.kind === 297 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 298 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -44797,17 +45989,17 @@ var ts; } if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) { // declaration is before usage - if (declaration.kind === 198 /* BindingElement */) { + if (declaration.kind === 199 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) - var errorBindingElement = ts.getAncestor(usage, 198 /* BindingElement */); + var errorBindingElement = ts.getAncestor(usage, 199 /* BindingElement */); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 249 /* VariableDeclaration */), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 250 /* VariableDeclaration */), usage); } - else if (declaration.kind === 249 /* VariableDeclaration */) { + else if (declaration.kind === 250 /* VariableDeclaration */) { // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } @@ -44821,7 +46013,7 @@ var ts; } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property - return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + return !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); } @@ -44837,19 +46029,19 @@ var ts; // or if usage is in a type context: // 1. inside a type query (typeof in type position) // 2. inside a jsdoc comment - if (usage.parent.kind === 270 /* ExportSpecifier */ || (usage.parent.kind === 266 /* ExportAssignment */ && usage.parent.isExportEquals)) { + if (usage.parent.kind === 271 /* ExportSpecifier */ || (usage.parent.kind === 267 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; } // When resolving symbols for exports, the `usage` location passed in can be the export site directly - if (usage.kind === 266 /* ExportAssignment */ && usage.isExportEquals) { + if (usage.kind === 267 /* ExportAssignment */ && usage.isExportEquals) { return true; } if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + if (compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); @@ -44864,9 +46056,9 @@ var ts; } function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { switch (declaration.parent.parent.kind) { - case 232 /* VariableStatement */: - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: + case 233 /* VariableStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, declContainer)) { @@ -44887,16 +46079,16 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 163 /* PropertyDeclaration */ && + current.parent.kind === 164 /* PropertyDeclaration */ && current.parent.initializer === current; if (initializerOfProperty) { if (ts.hasSyntacticModifier(current.parent, 32 /* Static */)) { - if (declaration.kind === 165 /* MethodDeclaration */) { + if (declaration.kind === 166 /* MethodDeclaration */) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 163 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(declaration, 32 /* Static */); + var isDeclarationInstanceProperty = declaration.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(declaration, 32 /* Static */); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -44918,19 +46110,19 @@ var ts; return "quit"; } switch (node.kind) { - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return true; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // even when stopping at any property declaration, they need to come from the same class return stopAtAnyPropertyDeclaration && (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent) ? "quit" : true; - case 230 /* Block */: + case 231 /* Block */: switch (node.parent.kind) { - case 167 /* GetAccessor */: - case 165 /* MethodDeclaration */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 166 /* MethodDeclaration */: + case 169 /* SetAccessor */: return true; default: return false; @@ -44945,7 +46137,11 @@ var ts; function useOuterVariableScopeInParameter(result, location, lastLocation) { var target = ts.getEmitScriptTarget(compilerOptions); var functionLocation = location; - if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + if (ts.isParameter(lastLocation) + && functionLocation.body + && result.valueDeclaration + && result.valueDeclaration.pos >= functionLocation.body.pos + && result.valueDeclaration.end <= functionLocation.body.end) { // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body // - static field in a class expression // - optional chaining pre-es2020 @@ -44966,21 +46162,21 @@ var ts; } function requiresScopeChangeWorker(node) { switch (node.kind) { - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 166 /* Constructor */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 167 /* Constructor */: // do not descend into these return false; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 288 /* PropertyAssignment */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 289 /* PropertyAssignment */: return requiresScopeChangeWorker(node.name); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // static properties in classes introduce temporary variables if (ts.hasStaticModifier(node)) { - return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields; + return target < 99 /* ESNext */ || !useDefineForClassFields; } return requiresScopeChangeWorker(node.name); default: @@ -45009,6 +46205,7 @@ var ts; return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); } function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { + var _a; var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; @@ -45031,12 +46228,12 @@ 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 & 788968 /* Type */ && lastLocation.kind !== 311 /* JSDocComment */) { + if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 312 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || - lastLocation.kind === 160 /* Parameter */ || - lastLocation.kind === 159 /* TypeParameter */ + lastLocation.kind === 161 /* Parameter */ || + lastLocation.kind === 160 /* TypeParameter */ // local types not visible outside the function body : false; } @@ -45051,13 +46248,13 @@ var ts; // however it is detected separately when checking initializers of parameters // to make sure that they reference no variables declared after them. useResult = - lastLocation.kind === 160 /* Parameter */ || + lastLocation.kind === 161 /* Parameter */ || (lastLocation === location.type && !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); } } } - else if (location.kind === 184 /* ConditionalType */) { + else if (location.kind === 185 /* ConditionalType */) { // A type parameter declared using 'infer T' in a conditional type is visible only in // the true branch of the conditional type. useResult = lastLocation === location.trueType; @@ -45072,14 +46269,14 @@ var ts; } withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation); switch (location.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; // falls through - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports || emptySymbols; - if (location.kind === 297 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) { + if (location.kind === 298 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports.get("default" /* Default */)) { @@ -45103,13 +46300,13 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && - (ts.getDeclarationOfKind(moduleExport, 270 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 269 /* NamespaceExport */))) { + (ts.getDeclarationOfKind(moduleExport, 271 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 270 /* NamespaceExport */))) { break; } } // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs) if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) { - if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !((_a = result.declarations) === null || _a === void 0 ? void 0 : _a.some(ts.isJSDocTypeAlias))) { result = undefined; } else { @@ -45117,12 +46314,12 @@ var ts; } } break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // TypeScript 1.0 spec (April 2014): 8.4.1 // Initializer expressions for instance member variables are evaluated in the scope // of the class constructor body but are not permitted to reference parameters or @@ -45139,9 +46336,9 @@ var ts; } } break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: // 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! @@ -45160,7 +46357,7 @@ var ts; } break loop; } - if (location.kind === 221 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 222 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -45168,7 +46365,7 @@ var ts; } } break; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 93 /* ExtendsKeyword */) { var container = location.parent.parent; @@ -45188,9 +46385,9 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 253 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 254 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -45198,24 +46395,24 @@ var ts; } } break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: // when targeting ES6 or higher there is no 'arguments' in an arrow function // for lower compile targets the resolved symbol is used to emit an error if (compilerOptions.target >= 2 /* ES2015 */) { break; } // falls through - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -45228,7 +46425,7 @@ var ts; } } break; - case 161 /* Decorator */: + case 162 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -45237,7 +46434,7 @@ var ts; // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. // } // - if (location.parent && location.parent.kind === 160 /* Parameter */) { + if (location.parent && location.parent.kind === 161 /* Parameter */) { location = location.parent; } // @@ -45252,20 +46449,20 @@ var ts; // declare function y(x: T): any; // @param(1 as T) // <-- T should resolve to the type alias outside of class C // class C {} - if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 252 /* ClassDeclaration */)) { + if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 253 /* ClassDeclaration */)) { location = location.parent; } break; - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: // js type aliases do not resolve names from their host, so skip past it var root = ts.getJSDocRoot(location); if (root) { location = root.parent; } break; - case 160 /* Parameter */: + case 161 /* Parameter */: if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && ts.isBindingPattern(lastLocation))) { if (!associatedDeclarationForContainingInitializerOrBindingName) { @@ -45273,7 +46470,7 @@ var ts; } } break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && ts.isBindingPattern(lastLocation))) { if (ts.isParameterDeclaration(location) && !associatedDeclarationForContainingInitializerOrBindingName) { @@ -45281,7 +46478,7 @@ var ts; } } break; - case 185 /* InferType */: + case 186 /* InferType */: if (meaning & 262144 /* TypeParameter */) { var parameterName = location.typeParameter.name; if (parameterName && name === parameterName.escapedText) { @@ -45305,7 +46502,7 @@ var ts; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 297 /* SourceFile */); + ts.Debug.assert(lastLocation.kind === 298 /* SourceFile */); if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } @@ -45334,6 +46531,10 @@ var ts; var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + var isGlobalScopeAugmentationDeclaration = suggestion && suggestion.valueDeclaration && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); + if (isGlobalScopeAugmentationDeclaration) { + suggestion = undefined; + } if (suggestion) { var suggestionName = symbolToString(suggestion); var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); @@ -45360,7 +46561,7 @@ var ts; } // Perform extra checks only if error reporting was requested if (nameNotFoundMessage) { - if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields)) { // We have a match, but the reference occurred within a property initializer and the identifier also binds // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed // with ESNext+useDefineForClassFields because the scope semantics are different. @@ -45430,10 +46631,10 @@ var ts; } } function getIsDeferredContext(location, lastLocation) { - if (location.kind !== 209 /* ArrowFunction */ && location.kind !== 208 /* FunctionExpression */) { + if (location.kind !== 210 /* ArrowFunction */ && location.kind !== 209 /* FunctionExpression */) { // initializers in instance property declaration of class like entities are executed in constructor and thus deferred return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) || - (location.kind === 163 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(location, 32 /* Static */))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred + (location.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(location, 32 /* Static */))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred } if (lastLocation && lastLocation === location.name) { return false; @@ -45446,12 +46647,12 @@ var ts; } function isSelfReferenceLocation(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 256 /* ModuleDeclaration */: // For `namespace N { N; }` + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 257 /* ModuleDeclaration */: // For `namespace N { N; }` return true; default: return false; @@ -45461,12 +46662,14 @@ var ts; return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } function isTypeParameterSymbolDeclaredInContainer(symbol, container) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (decl.kind === 159 /* TypeParameter */) { - var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; - if (parent === container) { - return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.kind === 160 /* TypeParameter */) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + } } } } @@ -45519,9 +46722,9 @@ var ts; function getEntityNameForExtendingInterface(node) { switch (node.kind) { case 78 /* Identifier */: - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: if (ts.isEntityNameExpression(node.expression)) { return node.expression; } @@ -45565,7 +46768,7 @@ var ts; return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown"; } function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) { - if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 270 /* ExportSpecifier */) { + if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 271 /* ExportSpecifier */) { error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name); return true; } @@ -45634,13 +46837,14 @@ var ts; return false; } function checkResolvedBlockScopedVariable(result, errorLocation) { + var _a; ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) { // constructor functions aren't block scoped return; } // Block-scoped variables cannot be used before their definition - var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 255 /* EnumDeclaration */); }); + var declaration = (_a = result.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 256 /* EnumDeclaration */); }); if (declaration === undefined) return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration"); if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -45657,7 +46861,7 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); - if (compilerOptions.preserveConstEnums) { + if (ts.shouldPreserveConstEnums(compilerOptions)) { diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); } } @@ -45675,20 +46879,20 @@ var ts; } function getAnyImportSyntax(node) { switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return node; - case 262 /* ImportClause */: + case 263 /* ImportClause */: return node.parent; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return node.parent.parent; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: return node.parent.parent.parent; default: return undefined; } } function getDeclarationOfAliasSymbol(symbol) { - return ts.find(symbol.declarations, isAliasSymbolDeclaration); + return symbol.declarations && ts.findLast(symbol.declarations, isAliasSymbolDeclaration); } /** * An alias symbol is created by one of the following declarations: @@ -45703,25 +46907,26 @@ var ts; * module.exports = * {} * {name: } + * const { x } = require ... */ function isAliasSymbolDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ - || node.kind === 259 /* NamespaceExportDeclaration */ - || node.kind === 262 /* ImportClause */ && !!node.name - || node.kind === 263 /* NamespaceImport */ - || node.kind === 269 /* NamespaceExport */ - || node.kind === 265 /* ImportSpecifier */ - || node.kind === 270 /* ExportSpecifier */ - || node.kind === 266 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + return node.kind === 261 /* ImportEqualsDeclaration */ + || node.kind === 260 /* NamespaceExportDeclaration */ + || node.kind === 263 /* ImportClause */ && !!node.name + || node.kind === 264 /* NamespaceImport */ + || node.kind === 270 /* NamespaceExport */ + || node.kind === 266 /* ImportSpecifier */ + || node.kind === 271 /* ExportSpecifier */ + || node.kind === 267 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) || ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && ts.exportAssignmentIsAlias(node) || ts.isAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableOrJsExpression(node.parent.right) - || node.kind === 289 /* ShorthandPropertyAssignment */ - || node.kind === 288 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) - || ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true); + || node.kind === 290 /* ShorthandPropertyAssignment */ + || node.kind === 289 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) + || ts.isRequireVariableDeclaration(node); } function isAliasableOrJsExpression(e) { return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e); @@ -45734,7 +46939,7 @@ var ts; ? resolveSymbol(getPropertyOfType(resolveExternalModuleTypeByLiteral(name), commonJSPropertyAccess.name.escapedText)) : undefined; } - if (ts.isVariableDeclaration(node) || node.moduleReference.kind === 272 /* ExternalModuleReference */) { + if (ts.isVariableDeclaration(node) || node.moduleReference.kind === 273 /* ExternalModuleReference */) { var immediate = resolveExternalModuleName(node, ts.getExternalModuleRequireArgument(node) || ts.getExternalModuleImportEqualsDeclarationExpression(node)); var resolved_4 = resolveExternalModuleSymbol(immediate); markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false); @@ -45801,6 +47006,7 @@ var ts; return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias); } function getTargetOfImportClause(node, dontResolveAlias) { + var _a; var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { var exportDefaultSymbol = void 0; @@ -45810,7 +47016,7 @@ var ts; else { exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias); } - var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); if (!exportDefaultSymbol && !hasSyntheticDefault) { if (hasExportAssignmentSymbol(moduleSymbol)) { @@ -45818,7 +47024,9 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */); var exportAssignment = exportEqualsSymbol.valueDeclaration; var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName); - ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); + if (exportAssignment) { + ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); + } } else { reportNonDefaultExport(moduleSymbol, node); @@ -45835,7 +47043,7 @@ var ts; } } function reportNonDefaultExport(moduleSymbol, node) { - var _a, _b; + var _a, _b, _c; if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); } @@ -45843,7 +47051,7 @@ var ts; var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */); if (exportStar) { - var defaultExport = ts.find(exportStar.declarations, function (decl) { + var defaultExport = (_c = exportStar.declarations) === null || _c === void 0 ? void 0 : _c.find(function (decl) { var _a, _b; return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier && ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */))); @@ -45921,7 +47129,7 @@ var ts; } } function getExternalModuleMember(node, specifier, dontResolveAlias) { - var _a; + var _a, _b; if (dontResolveAlias === void 0) { dontResolveAlias = false; } var moduleSpecifier = ts.getExternalModuleRequireArgument(node) || node.moduleSpecifier; var moduleSymbol = resolveExternalModuleName(node, moduleSpecifier); // TODO: GH#18217 @@ -45930,7 +47138,7 @@ var ts; return undefined; } var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop); - var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, dontResolveAlias, suppressInteropError); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, /*dontResolveAlias*/ false, suppressInteropError); if (targetSymbol) { if (name.escapedText) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { @@ -45948,7 +47156,7 @@ var ts; symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); var symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias); if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) { - var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } @@ -45968,7 +47176,7 @@ var ts; } } else { - if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default" /* Default */)) { + if ((_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */)) { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); } else { @@ -45981,8 +47189,8 @@ var ts; } } function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) { - var _a; - var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText); + var _a, _b; + var localSymbol = (_b = (_a = moduleSymbol.valueDeclaration) === null || _a === void 0 ? void 0 : _a.locals) === null || _b === void 0 ? void 0 : _b.get(name.escapedText); var exports = moduleSymbol.exports; if (localSymbol) { var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */); @@ -45994,9 +47202,11 @@ var ts; var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined; var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); - ts.addRelatedInfo.apply(void 0, __spreadArray([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { - return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); - }))); + if (localSymbol.declarations) { + ts.addRelatedInfo.apply(void 0, __spreadArray([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { + return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); + }))); + } } } else { @@ -46083,31 +47293,31 @@ var ts; function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: - case 249 /* VariableDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 250 /* VariableDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return getTargetOfImportClause(node, dontRecursivelyResolve); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: return getTargetOfNamespaceExport(node, dontRecursivelyResolve); - case 265 /* ImportSpecifier */: - case 198 /* BindingElement */: + case 266 /* ImportSpecifier */: + case 199 /* BindingElement */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); - case 266 /* ExportAssignment */: - case 216 /* BinaryExpression */: + case 267 /* ExportAssignment */: + case 217 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return getTargetOfPropertyAssignment(node, dontRecursivelyResolve); - case 202 /* ElementAccessExpression */: - case 201 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: return getTargetOfAccessExpression(node, dontRecursivelyResolve); default: return ts.Debug.fail(); @@ -46259,13 +47469,13 @@ var ts; entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 78 /* Identifier */ || entityName.parent.kind === 157 /* QualifiedName */) { + if (entityName.kind === 78 /* Identifier */ || entityName.parent.kind === 158 /* QualifiedName */) { return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 260 /* ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 261 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } @@ -46289,9 +47499,9 @@ var ts; return getMergedSymbol(symbolFromJSPrototype); } } - else if (name.kind === 157 /* QualifiedName */ || name.kind === 201 /* PropertyAccessExpression */) { - var left = name.kind === 157 /* QualifiedName */ ? name.left : name.expression; - var right = name.kind === 157 /* QualifiedName */ ? name.right : name.name; + else if (name.kind === 158 /* QualifiedName */ || name.kind === 202 /* PropertyAccessExpression */) { + var left = name.kind === 158 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 158 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -46299,18 +47509,17 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJSFile(name)) { - if (namespace.valueDeclaration && - ts.isVariableDeclaration(namespace.valueDeclaration) && - namespace.valueDeclaration.initializer && - isCommonJsRequire(namespace.valueDeclaration.initializer)) { - var moduleName = namespace.valueDeclaration.initializer.arguments[0]; - var moduleSym = resolveExternalModuleName(moduleName, moduleName); - if (moduleSym) { - var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); - if (resolvedModuleSymbol) { - namespace = resolvedModuleSymbol; - } + if (namespace.valueDeclaration && + ts.isInJSFile(namespace.valueDeclaration) && + ts.isVariableDeclaration(namespace.valueDeclaration) && + namespace.valueDeclaration.initializer && + isCommonJsRequire(namespace.valueDeclaration.initializer)) { + var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + var moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; } } } @@ -46331,7 +47540,7 @@ var ts; throw ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); - if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 266 /* ExportAssignment */)) { + if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 267 /* ExportAssignment */)) { markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true); } return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); @@ -46568,7 +47777,7 @@ var ts; function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { - if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 297 /* SourceFile */)) { + if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 298 /* SourceFile */)) { var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop"; @@ -46619,7 +47828,10 @@ var ts; var exports = getExportsOfModuleAsArray(moduleSymbol); var exportEquals = resolveExternalModuleSymbol(moduleSymbol); if (exportEquals !== moduleSymbol) { - ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); + var type = getTypeOfSymbol(exportEquals); + if (shouldTreatPropertiesOfExternalModuleAsExports(type)) { + ts.addRange(exports, getPropertiesOfType(type)); + } } return exports; } @@ -46639,11 +47851,14 @@ var ts; return undefined; } var type = getTypeOfSymbol(exportEquals); - return type.flags & 131068 /* Primitive */ || - ts.getObjectFlags(type) & 1 /* Class */ || - isArrayOrTupleLikeType(type) - ? undefined - : getPropertyOfType(type, memberName); + return shouldTreatPropertiesOfExternalModuleAsExports(type) ? getPropertyOfType(type, memberName) : undefined; + } + function shouldTreatPropertiesOfExternalModuleAsExports(resolvedExternalModuleType) { + return !(resolvedExternalModuleType.flags & 131068 /* Primitive */ || + ts.getObjectFlags(resolvedExternalModuleType) & 1 /* Class */ || + // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path + isArrayType(resolvedExternalModuleType) || + isTupleType(resolvedExternalModuleType)); } function getExportsOfSymbol(symbol) { return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : @@ -46701,11 +47916,13 @@ var ts; if (exportStars) { var nestedSymbols = ts.createSymbolTable(); var lookupTable_1 = new ts.Map(); - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - var exportedSymbols = visit(resolvedModule); - extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + if (exportStars.declarations) { + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + } } lookupTable_1.forEach(function (_a, id) { var exportsWithDuplicate = _a.exportsWithDuplicate; @@ -46788,11 +48005,28 @@ var ts; var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); var objectLiteralContainer = getVariableDeclarationOfObjectLiteral(container, meaning); - if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { + if (enclosingDeclaration && + container.flags & getQualifiedLeftMeaning(meaning) && + getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { return ts.append(ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers), objectLiteralContainer); // This order expresses a preference for the real container if it is in scope } - var res = ts.append(ts.append(additionalContainers, container), objectLiteralContainer); - return ts.concatenate(res, reexportContainers); + // we potentially have a symbol which is a member of the instance side of something - look for a variable in scope with the container's type + // which may be acting like a namespace (eg, `Symbol` acts like a namespace when looking up `Symbol.toStringTag`) + var firstVariableMatch = !(container.flags & getQualifiedLeftMeaning(meaning)) + && container.flags & 788968 /* Type */ + && getDeclaredTypeOfSymbol(container).flags & 524288 /* Object */ + && meaning === 111551 /* Value */ + ? forEachSymbolTableInScope(enclosingDeclaration, function (t) { + return ts.forEachEntry(t, function (s) { + if (s.flags & getQualifiedLeftMeaning(meaning) && getTypeOfSymbol(s) === getDeclaredTypeOfSymbol(container)) { + return s; + } + }); + }) : undefined; + var res = firstVariableMatch ? __spreadArray(__spreadArray([firstVariableMatch], additionalContainers), [container]) : __spreadArray(__spreadArray([], additionalContainers), [container]); + res = ts.append(res, objectLiteralContainer); + res = ts.addRange(res, reexportContainers); + return res; } var candidates = ts.mapDefined(symbol.declarations, function (d) { if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) { @@ -46870,7 +48104,7 @@ var ts; var members = node.members; for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { var member = members_3[_i]; - if (member.kind === 166 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 167 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -46879,7 +48113,9 @@ var ts; var result = new Type(checker, flags); typeCount++; result.id = typeCount; - typeCatalog.push(result); + if (produceDiagnostics) { // Only record types from one checker + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.recordType(result); + } return result; } function createOriginType(flags) { @@ -46939,14 +48175,23 @@ var ts; }); return result || ts.emptyArray; } + function getNamedOrIndexSignatureMembers(members) { + var result = getNamedMembers(members); + var index = getIndexSymbolFromSymbolTable(members); + return index ? ts.concatenate(result, [index]) : result; + } function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - type.members = members; - type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members); - type.callSignatures = callSignatures; - type.constructSignatures = constructSignatures; - type.stringIndexInfo = stringIndexInfo; - type.numberIndexInfo = numberIndexInfo; - return type; + var resolved = type; + resolved.members = members; + resolved.properties = ts.emptyArray; + resolved.callSignatures = callSignatures; + resolved.constructSignatures = constructSignatures; + resolved.stringIndexInfo = stringIndexInfo; + resolved.numberIndexInfo = numberIndexInfo; + // This can loop back to getPropertyOfType() which would crash if `callSignatures` & `constructSignatures` are not initialized. + if (members !== emptySymbols) + resolved.properties = getNamedMembers(members); + return resolved; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); @@ -46969,28 +48214,28 @@ var ts; var _loop_8 = function (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { - if (result = callback(location.locals)) { + if (result = callback(location.locals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } } switch (location.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } // falls through - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var sym = getSymbolOfNode(location); // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred // to one another anyway) - if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) { + if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: // Type parameters are bound into `members` lists so they can merge across declarations // This is troublesome, since in all other respects, they behave like locals :cries: // TODO: the below is shared with similar code in `resolveName` - in fact, rephrasing all this symbol @@ -47016,7 +48261,7 @@ var ts; if (typeof state_2 === "object") return state_2.value; } - return callback(globals); + return callback(globals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true); } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace @@ -47036,11 +48281,11 @@ var ts; /** * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) */ - function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification, isLocalNameLookup) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - var result = trySymbolTable(symbols, ignoreQualification); + var result = trySymbolTable(symbols, ignoreQualification, isLocalNameLookup); visitedSymbolTables.pop(); return result; } @@ -47058,7 +48303,7 @@ var ts; !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning)); } - function trySymbolTable(symbols, ignoreQualification) { + function trySymbolTable(symbols, ignoreQualification, isLocalNameLookup) { // If symbol is directly available by its name in the symbol table if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { return [symbol]; @@ -47071,9 +48316,11 @@ var ts; && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // If we're looking up a local name to reference directly, omit namespace reexports, otherwise when we're trawling through an export list to make a dotted name, we can keep it + && (isLocalNameLookup ? !ts.some(symbolFromSymbolTable.declarations, ts.isNamespaceReexportDeclaration) : true) // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ // See similar comment in `resolveName` for details - && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 270 /* ExportSpecifier */))) { + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 271 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification); if (candidate) { @@ -47117,7 +48364,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 270 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 271 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -47132,10 +48379,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: continue; default: return false; @@ -47173,7 +48420,7 @@ var ts; return hasAccessibleDeclarations; } } - else if (allowModules) { + if (allowModules) { if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { if (shouldComputeAliasesToMakeVisible) { earlyModuleBail = true; @@ -47247,7 +48494,8 @@ var ts; return { accessibility: 2 /* CannotBeNamed */, errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), - errorModuleName: symbolToString(symbolExternalModule) + errorModuleName: symbolToString(symbolExternalModule), + errorNode: ts.isInJSFile(enclosingDeclaration) ? enclosingDeclaration : undefined, }; } } @@ -47264,10 +48512,10 @@ var ts; return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { - return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -47323,14 +48571,14 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 176 /* TypeQuery */ || + if (entityName.parent.kind === 177 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || - entityName.parent.kind === 158 /* ComputedPropertyName */) { + entityName.parent.kind === 159 /* ComputedPropertyName */) { // Typeof value meaning = 111551 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 157 /* QualifiedName */ || entityName.kind === 201 /* PropertyAccessExpression */ || - entityName.parent.kind === 260 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 158 /* QualifiedName */ || entityName.kind === 202 /* PropertyAccessExpression */ || + entityName.parent.kind === 261 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1920 /* Namespace */; @@ -47371,7 +48619,7 @@ var ts; function symbolToStringWorker(writer) { var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217 // add neverAsciiEscape for GH#39027 - var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 297 /* SourceFile */ ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true }); + var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 298 /* SourceFile */ ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); return writer; @@ -47383,10 +48631,10 @@ var ts; function signatureToStringWorker(writer) { var sigOutput; if (flags & 262144 /* WriteArrowStyleSignature */) { - sigOutput = kind === 1 /* Construct */ ? 175 /* ConstructorType */ : 174 /* FunctionType */; + sigOutput = kind === 1 /* Construct */ ? 176 /* ConstructorType */ : 175 /* FunctionType */; } else { - sigOutput = kind === 1 /* Construct */ ? 170 /* ConstructSignature */ : 169 /* CallSignature */; + sigOutput = kind === 1 /* Construct */ ? 171 /* ConstructSignature */ : 170 /* CallSignature */; } var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); @@ -47426,14 +48674,14 @@ var ts; return typeToString(type, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); } function symbolValueDeclarationIsContextSensitive(symbol) { - return symbol && symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration); + return symbol && !!symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration); } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0 /* None */; } return flags & 814775659 /* NodeBuilderFlagsMask */; } function isClassInstanceSide(type) { - return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(ts.getObjectFlags(type) & 1073741824 /* IsClassInstanceClone */)); + return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288 /* Object */) && !!(ts.getObjectFlags(type) & 16777216 /* IsClassInstanceClone */))); } function createNodeBuilder() { return { @@ -47767,7 +49015,9 @@ var ts; 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 === 221 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || + else if (symbol.flags & 32 /* Class */ + && !getBaseTypeVariableOfClass(symbol) + && !(symbol.valueDeclaration && symbol.valueDeclaration.kind === 222 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, isInstanceType); @@ -47798,7 +49048,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 297 /* SourceFile */ || declaration.parent.kind === 257 /* ModuleBlock */; + return declaration.parent.kind === 298 /* SourceFile */ || declaration.parent.kind === 258 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -47849,12 +49099,12 @@ var ts; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 174 /* FunctionType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 175 /* FunctionType */, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 175 /* ConstructorType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 176 /* ConstructorType */, context); return signatureNode; } } @@ -48034,17 +49284,17 @@ var ts; var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 169 /* CallSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 170 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; if (signature.flags & 4 /* Abstract */) continue; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 170 /* ConstructSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 171 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { var indexSignature = void 0; - if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + if (resolvedType.objectFlags & 1024 /* ReverseMapped */) { indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context, createElidedInformationPlaceholder(context)); } else { @@ -48088,15 +49338,29 @@ var ts; } return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } + function shouldUsePlaceholderForProperty(propertySymbol, context) { + var _a; + // Use placeholders for reverse mapped types we've either already descended into, or which + // are nested reverse mappings within a mapping over a non-anonymous type. The later is a restriction mostly just to + // reduce the blowup in printback size from doing, eg, a deep reverse mapping over `Window`. + // Since anonymous types usually come from expressions, this allows us to preserve the output + // for deep mappings which likely come from expressions, while truncating those parts which + // come from mappings over library functions. + return !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */) + && (ts.contains(context.reverseMappedStack, propertySymbol) + || (((_a = context.reverseMappedStack) === null || _a === void 0 ? void 0 : _a[0]) + && !(ts.getObjectFlags(ts.last(context.reverseMappedStack).propertyType) & 16 /* Anonymous */))); + } function addPropertyToElementList(propertySymbol, context, typeElements) { + var _a; var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */); - var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? + var propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */ && isLateBoundName(propertySymbol.escapedName)) { var decl = ts.first(propertySymbol.declarations); - if (hasLateBindableName(decl)) { + if (propertySymbol.declarations && hasLateBindableName(decl)) { if (ts.isBinaryExpression(decl)) { var name = ts.getNameOfDeclaration(decl); if (name && ts.isElementAccessExpression(name) && ts.isPropertyAccessEntityNameExpression(name.argumentExpression)) { @@ -48108,29 +49372,34 @@ var ts; } } } - context.enclosingDeclaration = saveEnclosingDeclaration; + context.enclosingDeclaration = propertySymbol.valueDeclaration || ((_a = propertySymbol.declarations) === null || _a === void 0 ? void 0 : _a[0]) || saveEnclosingDeclaration; var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context); + context.enclosingDeclaration = saveEnclosingDeclaration; context.approximateLength += (ts.symbolName(propertySymbol).length + 1); var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */); for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { var signature = signatures_1[_i]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 164 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken }); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 165 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken }); typeElements.push(preserveCommentsOn(methodDeclaration)); } } else { - var savedFlags = context.flags; - context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; var propertyTypeNode = void 0; - if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + if (shouldUsePlaceholderForProperty(propertySymbol, context)) { propertyTypeNode = createElidedInformationPlaceholder(context); } else { + if (propertyIsReverseMapped) { + context.reverseMappedStack || (context.reverseMappedStack = []); + context.reverseMappedStack.push(propertySymbol); + } propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); + if (propertyIsReverseMapped) { + context.reverseMappedStack.pop(); + } } - context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(142 /* ReadonlyKeyword */)] : undefined; if (modifiers) { context.approximateLength += 9; @@ -48139,9 +49408,10 @@ var ts; typeElements.push(preserveCommentsOn(propertySignature)); } function preserveCommentsOn(node) { - if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 333 /* JSDocPropertyTag */; })) { - var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 333 /* JSDocPropertyTag */; }); - var commentText = d.comment; + var _a; + if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 337 /* JSDocPropertyTag */; })) { + var d = (_a = propertySymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 337 /* JSDocPropertyTag */; }); + var commentText = ts.getTextOfJSDocComment(d.comment); if (commentText) { ts.setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]); } @@ -48170,25 +49440,25 @@ var ts; var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */); /** Map from type reference identifier text to [type, index in `result` where the type node is] */ var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; - var result_4 = []; + var result_5 = []; var i = 0; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var type = types_2[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result_4.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + result_5.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result_4.push(typeNode_1); + result_5.push(typeNode_1); } break; } context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result_4.push(typeNode); + result_5.push(typeNode); if (seenNames && ts.isIdentifierTypeReference(typeNode)) { - seenNames.add(typeNode.typeName.escapedText, [type, result_4.length - 1]); + seenNames.add(typeNode.typeName.escapedText, [type, result_5.length - 1]); } } } @@ -48210,13 +49480,13 @@ var ts; })) { for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { var _a = types_3[_i], type = _a[0], resultIndex = _a[1]; - result_4[resultIndex] = typeToTypeNodeHelper(type, context); + result_5[resultIndex] = typeToTypeNodeHelper(type, context); } } }); context.flags = saveContextFlags; } - return result_4; + return result_5; } } function typesAreSameReference(a, b) { @@ -48258,7 +49528,7 @@ var ts; } var expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0]; // If the expanded parameter list had a variadic in a non-trailing position, don't expand it - var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 166 /* Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); + var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 167 /* Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -48285,25 +49555,25 @@ var ts; } } var modifiers = options === null || options === void 0 ? void 0 : options.modifiers; - if ((kind === 175 /* ConstructorType */) && signature.flags & 4 /* Abstract */) { + if ((kind === 176 /* ConstructorType */) && signature.flags & 4 /* Abstract */) { var flags = ts.modifiersToFlags(modifiers); modifiers = ts.factory.createModifiersFromModifierFlags(flags | 128 /* Abstract */); } context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum - var node = kind === 169 /* CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : - kind === 170 /* ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : - kind === 164 /* MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : - kind === 165 /* MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === 166 /* Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) : - kind === 167 /* GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : - kind === 168 /* SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : - kind === 171 /* IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) : - kind === 308 /* JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : - kind === 174 /* FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 175 /* ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 251 /* FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === 208 /* FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : - kind === 209 /* ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) : + var node = kind === 170 /* CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : + kind === 171 /* ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : + kind === 165 /* MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : + kind === 166 /* MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 167 /* Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) : + kind === 168 /* GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : + kind === 169 /* SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : + kind === 172 /* IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) : + kind === 309 /* JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : + kind === 175 /* FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : + kind === 176 /* ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : + kind === 252 /* FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 209 /* FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : + kind === 210 /* ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) : ts.Debug.assertNever(kind); if (typeArguments) { node.typeArguments = ts.factory.createNodeArray(typeArguments); @@ -48325,9 +49595,9 @@ var ts; return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 160 /* Parameter */); + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 161 /* Parameter */); if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 326 /* JSDocParameterTag */); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 330 /* JSDocParameterTag */); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -48342,7 +49612,7 @@ var ts; var dotDotDotToken = isRest ? ts.factory.createToken(25 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 78 /* Identifier */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : - parameterDeclaration.name.kind === 157 /* QualifiedName */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 158 /* QualifiedName */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); @@ -48507,11 +49777,11 @@ var ts; } function getSpecifierForModuleSymbol(symbol, context) { var _a; - var file = ts.getDeclarationOfKind(symbol, 297 /* SourceFile */); + var file = ts.getDeclarationOfKind(symbol, 298 /* SourceFile */); if (!file) { var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); }); if (equivalentFileSymbol) { - file = ts.getDeclarationOfKind(equivalentFileSymbol, 297 /* SourceFile */); + file = ts.getDeclarationOfKind(equivalentFileSymbol, 298 /* SourceFile */); } } if (file && file.moduleName !== undefined) { @@ -48522,8 +49792,8 @@ var ts; if (context.tracker.trackReferencedAmbientModule) { var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); if (ts.length(ambientDecls)) { - for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { - var decl = ambientDecls_1[_i]; + for (var _i = 0, _b = ambientDecls; _i < _b.length; _i++) { + var decl = _b[_i]; context.tracker.trackReferencedAmbientModule(decl, symbol); } } @@ -48550,7 +49820,7 @@ var ts; // specifier preference var moduleResolverHost = context.tracker.moduleResolverHost; var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; - specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "project-relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); (_a = links.specifierCache) !== null && _a !== void 0 ? _a : (links.specifierCache = new ts.Map()); links.specifierCache.set(contextFile.path, specifier); } @@ -48694,7 +49964,7 @@ var ts; var chain = lookupSymbolChain(symbol, context, meaning); if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) { + && !(context.flags & 65536 /* AllowQualifiedNameInPlaceOfIdentifier */)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); @@ -48774,9 +50044,6 @@ var ts; if (fromNameType) { return fromNameType; } - if (ts.isKnownSymbol(symbol)) { - return ts.factory.createComputedPropertyName(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("Symbol"), symbol.escapedName.substr(3))); - } var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName); var stringNamed = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isStringNamed); return createPropertyNameNodeForIdentifierOrLiteral(rawName, stringNamed, singleQuote); @@ -48843,13 +50110,13 @@ var ts; function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { if (type !== errorType && enclosingDeclaration) { var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation) && !ts.isGetAccessorDeclaration(declWithExistingAnnotation)) { // try to reuse the existing annotation var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { - var result_5 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); - if (result_5) { - return result_5; + var result_6 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_6) { + return result_6; } } } @@ -48866,10 +50133,14 @@ var ts; function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { if (type !== errorType && context.enclosingDeclaration) { var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); - if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { - var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); - if (result) { - return result; + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation) { + var annotated = getTypeFromTypeNode(annotation); + var thisInstantiated = annotated.flags & 262144 /* TypeParameter */ && annotated.isThisType ? instantiateType(annotated, signature.mapper) : annotated; + if (thisInstantiated === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } } } } @@ -48913,7 +50184,7 @@ var ts; return transformed === existing ? ts.setTextRange(ts.factory.cloneNode(existing), existing) : transformed; function visitExistingNodeTreeSymbols(node) { // We don't _actually_ support jsdoc namepath types, emit `any` instead - if (ts.isJSDocAllType(node) || node.kind === 310 /* JSDocNamepathType */) { + if (ts.isJSDocAllType(node) || node.kind === 311 /* JSDocNamepathType */) { return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } if (ts.isJSDocUnknownType(node)) { @@ -49032,8 +50303,8 @@ var ts; } } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { - var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 165 /* MethodDeclaration */, /*useAcessors*/ true); - var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 164 /* MethodSignature */, /*useAcessors*/ false); + var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 166 /* MethodDeclaration */, /*useAcessors*/ true); + var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 165 /* MethodSignature */, /*useAcessors*/ false); // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of // declaration mapping // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration @@ -49045,7 +50316,7 @@ var ts; var deferredPrivatesStack = []; var oldcontext = context; context = __assign(__assign({}, oldcontext), { usedSymbolNames: new ts.Set(oldcontext.usedSymbolNames), remappedSymbolNames: new ts.Map(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { - var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false); + var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeAliases*/ false); if (accessibleResult.accessibility === 0 /* Accessible */) { // Lookup the root symbol of the chain of refs we'll use to access it and serialize it var chain = lookupSymbolChainWorker(sym, context, meaning); @@ -49254,6 +50525,7 @@ var ts; // If it's a class/interface/function: emit a class/interface/function with a `default` modifier // These forms can merge, eg (`export default 12; export default interface A {}`) function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) { + var _a, _b; var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName); var isDefault = symbol.escapedName === "default" /* Default */; if (isPrivate && !(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) { @@ -49312,9 +50584,9 @@ var ts; if (textRange && ts.isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) { textRange = textRange.parent.parent; } - var propertyAccessRequire = ts.find(symbol.declarations, ts.isPropertyAccessExpression); + var propertyAccessRequire = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isPropertyAccessExpression); if (propertyAccessRequire && ts.isBinaryExpression(propertyAccessRequire.parent) && ts.isIdentifier(propertyAccessRequire.parent.right) - && type.symbol && ts.isSourceFile(type.symbol.valueDeclaration)) { + && ((_b = type.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration) && ts.isSourceFile(type.symbol.valueDeclaration)) { var alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right; addResult(ts.factory.createExportDeclaration( /*decorators*/ undefined, @@ -49364,7 +50636,10 @@ var ts; serializeEnum(symbol, symbolName, modifierFlags); } if (symbol.flags & 32 /* Class */) { - if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { + if (symbol.flags & 4 /* Property */ + && symbol.valueDeclaration + && ts.isBinaryExpression(symbol.valueDeclaration.parent) + && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members, // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today. @@ -49390,12 +50665,14 @@ var ts; if (symbol.flags & 8388608 /* ExportStar */) { // synthesize export * from "moduleReference" // Straightforward - only one thing to do - make an export declaration - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - if (!resolvedModule) - continue; - addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */); + if (symbol.declarations) { + for (var _i = 0, _c = symbol.declarations; _i < _c.length; _i++) { + var node = _c[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + if (!resolvedModule) + continue; + addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */); + } } } if (needsPostExportDefault) { @@ -49433,15 +50710,16 @@ var ts; function addResult(node, additionalModifierFlags) { if (ts.canHaveModifiers(node)) { var newModifierFlags = 0 /* None */; + var enclosingDeclaration_1 = context.enclosingDeclaration && + (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 /* Export */ && - context.enclosingDeclaration && - (isExportingScope(context.enclosingDeclaration) || ts.isModuleDeclaration(context.enclosingDeclaration)) && + enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && canHaveExportModifier(node)) { // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private newModifierFlags |= 1 /* Export */; } if (addingDeclare && !(newModifierFlags & 1 /* Export */) && - (!context.enclosingDeclaration || !(context.enclosingDeclaration.flags & 8388608 /* Ambient */)) && + (!enclosingDeclaration_1 || !(enclosingDeclaration_1.flags & 8388608 /* Ambient */)) && (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) { // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope newModifierFlags |= 2 /* Ambient */; @@ -49456,19 +50734,23 @@ var ts; results.push(node); } function serializeTypeAlias(symbol, symbolName, modifierFlags) { + var _a; var aliasType = getDeclaredTypeOfTypeAlias(symbol); var typeParams = getSymbolLinks(symbol).typeParameters; var typeParamDecls = ts.map(typeParams, function (p) { return typeParameterToDeclaration(p, context); }); - var jsdocAliasDecl = ts.find(symbol.declarations, ts.isJSDocTypeAlias); - var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined; + var jsdocAliasDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isJSDocTypeAlias); + var commentText = ts.getTextOfJSDocComment(jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined); var oldFlags = context.flags; context.flags |= 8388608 /* InTypeAlias */; + var oldEnclosingDecl = context.enclosingDeclaration; + context.enclosingDeclaration = jsdocAliasDecl; var typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; + context.enclosingDeclaration = oldEnclosingDecl; } function serializeInterface(symbol, symbolName, modifierFlags) { var interfaceType = getDeclaredTypeOfClassOrInterface(symbol); @@ -49477,8 +50759,8 @@ var ts; var baseTypes = getBaseTypes(interfaceType); var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined; var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); }); - var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 169 /* CallSignature */); - var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 170 /* ConstructSignature */); + var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 170 /* CallSignature */); + var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 171 /* ConstructSignature */); var indexSignatures = serializeIndexSignatures(interfaceType, baseType); var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(93 /* ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551 /* Value */); }))]; addResult(ts.factory.createInterfaceDeclaration( @@ -49547,9 +50829,8 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; // Each overload becomes a separate function declaration, in order - var decl = signatureToSignatureDeclarationHelper(sig, 251 /* FunctionDeclaration */, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled }); - // for expressions assigned to `var`s, use the `var` as the text range - addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags); + var decl = signatureToSignatureDeclarationHelper(sig, 252 /* FunctionDeclaration */, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled }); + addResult(ts.setTextRange(decl, getSignatureTextRangeLocation(sig)), modifierFlags); } // Module symbol emit will take care of module-y members, provided it has exports if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) { @@ -49557,6 +50838,18 @@ var ts; serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true); } } + function getSignatureTextRangeLocation(signature) { + if (signature.declaration && signature.declaration.parent) { + if (ts.isBinaryExpression(signature.declaration.parent) && ts.getAssignmentDeclarationKind(signature.declaration.parent) === 5 /* Property */) { + return signature.declaration.parent; + } + // for expressions assigned to `var`s, use the `var` as the text range + if (ts.isVariableDeclaration(signature.declaration.parent) && signature.declaration.parent.parent) { + return signature.declaration.parent.parent; + } + } + return signature.declaration; + } function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) { if (ts.length(props)) { var localVsRemoteMap = ts.arrayToMultiMap(props, function (p) { @@ -49643,8 +50936,8 @@ var ts; return undefined; } function serializeAsClass(symbol, localName, modifierFlags) { - var _a; - var originalDecl = ts.find(symbol.declarations, ts.isClassLike); + var _a, _b; + var originalDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isClassLike); var oldEnclosing = context.enclosingDeclaration; context.enclosingDeclaration = originalDecl || oldEnclosing; var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -49655,7 +50948,7 @@ var ts; var implementsExpressions = originalImplements && sanitizeJSDocImplements(originalImplements) || ts.mapDefined(getImplementsTypes(classType), serializeImplementedType); var staticType = getTypeOfSymbol(symbol); - var isClass = !!((_a = staticType.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration) && ts.isClassLike(staticType.symbol.valueDeclaration); + var isClass = !!((_b = staticType.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration) && ts.isClassLike(staticType.symbol.valueDeclaration); var staticBaseType = isClass ? getBaseConstructorTypeOfClass(staticType) : anyType; @@ -49666,14 +50959,14 @@ var ts; // a union/intersection base type, but inherited properties // don't matter here. var valueDecl = s.valueDeclaration; - return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); + return !!valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); }); var hasPrivateIdentifier = ts.some(symbolProps, function (s) { // `valueDeclaration` could be undefined if inherited from // a union/intersection base type, but inherited properties // don't matter here. var valueDecl = s.valueDeclaration; - return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); + return !!valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); }); // Boil down all private properties into a single one. var privateProperties = hasPrivateIdentifier ? @@ -49696,7 +50989,7 @@ var ts; !ts.some(getSignaturesOfType(staticType, 1 /* Construct */)); var constructors = isNonConstructableClassLikeInJsFile ? [ts.factory.createConstructorDeclaration(/*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(8 /* Private */), [], /*body*/ undefined)] : - serializeSignatures(1 /* Construct */, staticType, staticBaseType, 166 /* Constructor */); + serializeSignatures(1 /* Construct */, staticType, staticBaseType, 167 /* Constructor */); var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); context.enclosingDeclaration = oldEnclosing; addResult(ts.setTextRange(ts.factory.createClassDeclaration( @@ -49723,8 +51016,8 @@ var ts; var targetName = getInternalSymbolName(target, verbatimTargetName); includePrivateSymbol(target); // the target may be within the same scope - attempt to serialize it first switch (node.kind) { - case 198 /* BindingElement */: - if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 249 /* VariableDeclaration */) { + case 199 /* BindingElement */: + if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 250 /* VariableDeclaration */) { // const { SomeClass } = require('./lib'); var specifier_1 = getSpecifierForModuleSymbol(target.parent || target, context); // './lib' var propertyName = node.propertyName; @@ -49736,13 +51029,13 @@ var ts; // We don't know how to serialize this (nested?) binding element ts.Debug.failBadSyntaxKind(((_c = node.parent) === null || _c === void 0 ? void 0 : _c.parent) || node, "Unhandled binding element grandparent kind in declaration serialization"); break; - case 289 /* ShorthandPropertyAssignment */: - if (((_e = (_d = node.parent) === null || _d === void 0 ? void 0 : _d.parent) === null || _e === void 0 ? void 0 : _e.kind) === 216 /* BinaryExpression */) { + case 290 /* ShorthandPropertyAssignment */: + if (((_e = (_d = node.parent) === null || _d === void 0 ? void 0 : _d.parent) === null || _e === void 0 ? void 0 : _e.kind) === 217 /* BinaryExpression */) { // module.exports = { SomeClass } serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), targetName); } break; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: // commonjs require: const x = require('y') if (ts.isPropertyAccessExpression(node.initializer)) { // const x = require('y').z @@ -49762,7 +51055,7 @@ var ts; break; } // else fall through and treat commonjs require just like import= - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // This _specifically_ only exists to handle json declarations - where we make aliases, but since // we emit no declarations for the json document, must not refer to it in the declarations if (target.escapedName === "export=" /* ExportEquals */ && ts.some(target.declarations, ts.isJsonSourceFile)) { @@ -49779,13 +51072,13 @@ var ts; ? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false) : ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)))), isLocalImport ? modifierFlags : 0 /* None */); break; - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: // export as namespace foo // TODO: Not part of a file's local or export symbol tables // Is bound into file.symbol.globalExports instead, which we don't currently traverse addResult(ts.factory.createNamespaceExportDeclaration(ts.idText(node.name)), 0 /* None */); break; - case 262 /* ImportClause */: + case 263 /* ImportClause */: addResult(ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, ts.factory.createIdentifier(localName), /*namedBindings*/ undefined), @@ -49794,18 +51087,18 @@ var ts; // In such cases, the `target` refers to the module itself already ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: addResult(ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */); break; - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: addResult(ts.factory.createExportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */); break; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: addResult(ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause( @@ -49814,7 +51107,7 @@ var ts; ts.factory.createImportSpecifier(localName !== verbatimTargetName ? ts.factory.createIdentifier(verbatimTargetName) : undefined, ts.factory.createIdentifier(localName)) ])), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: // does not use localName because the symbol name in this case refers to the name in the exports table, // which we must exactly preserve var specifier = node.parent.parent.moduleSpecifier; @@ -49822,12 +51115,12 @@ var ts; // another file serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.factory.createStringLiteral(specifier.text) : undefined); break; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: serializeMaybeAliasAssignment(symbol); break; - case 216 /* BinaryExpression */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 217 /* BinaryExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: // Could be best encoded as though an export specifier or as though an export assignment // If name is default or export=, do an export assignment // Otherwise do an export specifier @@ -49961,6 +51254,7 @@ var ts; } function makeSerializePropertySymbol(createProperty, methodKind, useAccessors) { return function serializePropertySymbol(p, isStatic, baseType) { + var _a, _b, _c, _d, _e; var modifierFlags = ts.getDeclarationModifierFlagsFromSymbol(p); var isPrivate = !!(modifierFlags & 8 /* Private */); if (isStatic && (p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */))) { @@ -49977,7 +51271,7 @@ var ts; } var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0); var name = getPropertyNameNodeForSymbol(p, context); - var firstPropertyLikeDecl = ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression)); + var firstPropertyLikeDecl = (_a = p.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression)); if (p.flags & 98304 /* Accessor */ && useAccessors) { var result = []; if (p.flags & 65536 /* SetAccessor */) { @@ -49987,13 +51281,13 @@ var ts; /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "arg", /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], - /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl)); + /*body*/ undefined), ((_b = p.declarations) === null || _b === void 0 ? void 0 : _b.find(ts.isSetAccessor)) || firstPropertyLikeDecl)); } if (p.flags & 32768 /* GetAccessor */) { var isPrivate_1 = modifierFlags & 8 /* Private */; result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration( /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), - /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl)); + /*body*/ undefined), ((_c = p.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isGetAccessor)) || firstPropertyLikeDecl)); } return result; } @@ -50004,7 +51298,7 @@ var ts; /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ - /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl); + /*initializer*/ undefined), ((_d = p.declarations) === null || _d === void 0 ? void 0 : _d.find(ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration))) || firstPropertyLikeDecl); } if (p.flags & (8192 /* Method */ | 16 /* Function */)) { var type = getTypeOfSymbol(p); @@ -50013,7 +51307,7 @@ var ts; return ts.setTextRange(createProperty( /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, /*type*/ undefined, - /*initializer*/ undefined), ts.find(p.declarations, ts.isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations[0]); + /*initializer*/ undefined), ((_e = p.declarations) === null || _e === void 0 ? void 0 : _e.find(ts.isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); } var results_1 = []; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { @@ -50024,7 +51318,8 @@ var ts; questionToken: p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, modifiers: flag ? ts.factory.createModifiersFromModifierFlags(flag) : undefined }); - results_1.push(ts.setTextRange(decl, sig.declaration)); + var location = sig.declaration && ts.isPrototypePropertyAssignment(sig.declaration.parent) ? sig.declaration.parent : sig.declaration; + results_1.push(ts.setTextRange(decl, location)); } return results_1; } @@ -50240,9 +51535,9 @@ var ts; return "public"; } function getTypeAliasForTypeLiteral(type) { - if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { + if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */ && type.symbol.declarations) { var node = ts.walkUpParenthesizedTypes(type.symbol.declarations[0].parent); - if (node.kind === 254 /* TypeAliasDeclaration */) { + if (node.kind === 255 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -50250,11 +51545,11 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 257 /* ModuleBlock */ && + node.parent.kind === 258 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } function isDefaultBindingContext(location) { - return location.kind === 297 /* SourceFile */ || ts.isAmbientModule(location); + return location.kind === 298 /* SourceFile */ || ts.isAmbientModule(location); } function getNameOfSymbolFromNameType(symbol, context) { var nameType = getSymbolLinks(symbol).nameType; @@ -50313,17 +51608,17 @@ var ts; if (!declaration) { declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway } - if (declaration.parent && declaration.parent.kind === 249 /* VariableDeclaration */) { + if (declaration.parent && declaration.parent.kind === 250 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } switch (declaration.kind) { - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { context.encounteredError = true; } - return declaration.kind === 221 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; + return declaration.kind === 222 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } var name = getNameOfSymbolFromNameType(symbol, context); @@ -50340,28 +51635,28 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: - case 325 /* JSDocEnumTag */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: + case 329 /* JSDocEnumTag */: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // falls through - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 251 /* FunctionDeclaration */: - case 255 /* EnumDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 252 /* FunctionDeclaration */: + case 256 /* EnumDeclaration */: + case 261 /* ImportEqualsDeclaration */: // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; @@ -50369,55 +51664,55 @@ var ts; var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 260 /* ImportEqualsDeclaration */ && parent.kind !== 297 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) { + !(node.kind !== 261 /* ImportEqualsDeclaration */ && parent.kind !== 298 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible return isDeclarationVisible(parent); - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasEffectiveModifier(node, 8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so: // falls through - case 166 /* Constructor */: - case 170 /* ConstructSignature */: - case 169 /* CallSignature */: - case 171 /* IndexSignature */: - case 160 /* Parameter */: - case 257 /* ModuleBlock */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 177 /* TypeLiteral */: - case 173 /* TypeReference */: - case 178 /* ArrayType */: - case 179 /* TupleType */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 186 /* ParenthesizedType */: - case 192 /* NamedTupleMember */: + case 167 /* Constructor */: + case 171 /* ConstructSignature */: + case 170 /* CallSignature */: + case 172 /* IndexSignature */: + case 161 /* Parameter */: + case 258 /* ModuleBlock */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 178 /* TypeLiteral */: + case 174 /* TypeReference */: + case 179 /* ArrayType */: + case 180 /* TupleType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 187 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: return isDeclarationVisible(node.parent); // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: + case 266 /* ImportSpecifier */: return false; // Type parameters are always visible - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: // Source file and namespace export are always visible // falls through - case 297 /* SourceFile */: - case 259 /* NamespaceExportDeclaration */: + case 298 /* SourceFile */: + case 260 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return false; default: return false; @@ -50426,10 +51721,10 @@ var ts; } function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 266 /* ExportAssignment */) { + if (node.parent && node.parent.kind === 267 /* ExportAssignment */) { exportSymbol = resolveName(node, node.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } - else if (node.parent.kind === 270 /* ExportSpecifier */) { + else if (node.parent.kind === 271 /* ExportSpecifier */) { exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; @@ -50534,12 +51829,12 @@ var ts; function getDeclarationContainer(node) { return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 249 /* VariableDeclaration */: - case 250 /* VariableDeclarationList */: - case 265 /* ImportSpecifier */: - case 264 /* NamedImports */: - case 263 /* NamespaceImport */: - case 262 /* ImportClause */: + case 250 /* VariableDeclaration */: + case 251 /* VariableDeclarationList */: + case 266 /* ImportSpecifier */: + case 265 /* NamedImports */: + case 264 /* NamespaceImport */: + case 263 /* ImportClause */: return false; default: return true; @@ -50602,9 +51897,16 @@ var ts; var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= 131072 /* ObjectRestType */; + result.objectFlags |= 8388608 /* ObjectRestType */; return result; } + function isGenericTypeWithUndefinedConstraint(type) { + return !!(type.flags & 465829888 /* Instantiable */) && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 32768 /* Undefined */); + } + function getNonUndefinedType(type) { + var typeOrConstraint = someType(type, isGenericTypeWithUndefinedConstraint) ? mapType(type, function (t) { return t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type; + return getTypeWithFacts(typeOrConstraint, 524288 /* NEUndefined */); + } // Determine the control flow type associated with a destructuring declaration or assignment. The following // forms of destructuring are possible: // let { x } = obj; // BindingElement @@ -50639,23 +51941,23 @@ var ts; function getParentElementAccess(node) { var ancestor = node.parent.parent; switch (ancestor.kind) { - case 198 /* BindingElement */: - case 288 /* PropertyAssignment */: + case 199 /* BindingElement */: + case 289 /* PropertyAssignment */: return getSyntheticElementAccess(ancestor); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return getSyntheticElementAccess(node.parent); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return ancestor.initializer; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return ancestor.right; } } function getDestructuringPropertyName(node) { var parent = node.parent; - if (node.kind === 198 /* BindingElement */ && parent.kind === 196 /* ObjectBindingPattern */) { + if (node.kind === 199 /* BindingElement */ && parent.kind === 197 /* ObjectBindingPattern */) { return getLiteralPropertyNameText(node.propertyName || node.name); } - if (node.kind === 288 /* PropertyAssignment */ || node.kind === 289 /* ShorthandPropertyAssignment */) { + if (node.kind === 289 /* PropertyAssignment */ || node.kind === 290 /* ShorthandPropertyAssignment */) { return getLiteralPropertyNameText(node.name); } return "" + parent.elements.indexOf(node); @@ -50681,7 +51983,7 @@ var ts; parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */); } var type; - if (pattern.kind === 196 /* ObjectBindingPattern */) { + if (pattern.kind === 197 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { parentType = getReducedType(parentType); if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { @@ -50701,7 +52003,7 @@ var ts; // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name = declaration.propertyName || declaration.name; var indexType = getLiteralTypeFromPropertyName(name); - var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */), declaration.name); + var declaredType = getIndexedAccessType(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */); type = getFlowTypeOfDestructuring(declaration, declaredType); } } @@ -50722,7 +52024,7 @@ var ts; else if (isArrayLikeType(parentType)) { var indexType = getLiteralType(index_2); var accessFlags = hasDefaultValue(declaration) ? 8 /* NoTupleBoundsCheck */ : 0; - var declaredType = getConstraintForLocation(getIndexedAccessTypeOrUndefined(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, declaration.name, accessFlags | 16 /* ExpressionPosition */) || errorType, declaration.name); + var declaredType = getIndexedAccessTypeOrUndefined(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, declaration.name, accessFlags | 16 /* ExpressionPosition */) || errorType; type = getFlowTypeOfDestructuring(declaration, declaredType); } else { @@ -50735,11 +52037,9 @@ var ts; if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ? - getTypeWithFacts(type, 524288 /* NEUndefined */) : - type; + return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ? getNonUndefinedType(type) : type; } - return widenTypeInferredFromInitializer(declaration, getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), checkDeclarationInitializer(declaration)], 2 /* Subtype */)); + return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration)], 2 /* Subtype */)); } function getTypeForDeclarationFromJSDocComment(declaration) { var jsdocType = ts.getJSDocType(declaration); @@ -50754,7 +52054,7 @@ var ts; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 199 /* ArrayLiteralExpression */ && expr.elements.length === 0; + return expr.kind === 200 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { if (optional === void 0) { optional = true; } @@ -50764,11 +52064,11 @@ var ts; function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 238 /* ForInStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForInStatement */) { var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 240 /* ForOfStatement */) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -50805,8 +52105,8 @@ var ts; if (ts.isParameter(declaration)) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 168 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { - var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 167 /* GetAccessor */); + if (func.kind === 169 /* SetAccessor */ && hasBindableName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 168 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -50877,7 +52177,7 @@ var ts; links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && ts.every(symbol.declarations, function (declaration) { return ts.isBinaryExpression(declaration) && isPossiblyAliasedThisProperty(declaration) && - (declaration.left.kind !== 202 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && + (declaration.left.kind !== 203 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ undefined, declaration, symbol, declaration); }); } @@ -50893,13 +52193,33 @@ var ts; !declaration.initializer && (noImplicitAny || ts.isInJSFile(declaration)); } function getDeclaringConstructor(symbol) { + if (!symbol.declarations) { + return; + } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var container = ts.getThisContainer(declaration, /*includeArrowFunctions*/ false); - if (container && (container.kind === 166 /* Constructor */ || isJSConstructor(container))) { + if (container && (container.kind === 167 /* Constructor */ || isJSConstructor(container))) { return container; } } + ; + } + /** Create a synthetic property access flow node after the last statement of the file */ + function getFlowTypeFromCommonJSExport(symbol) { + var file = ts.getSourceFileOfNode(symbol.declarations[0]); + var accessName = ts.unescapeLeadingUnderscores(symbol.escapedName); + var areAllModuleExports = symbol.declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && ts.isModuleExportsAccessExpression(d.expression); }); + var reference = areAllModuleExports + ? ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("module"), ts.factory.createIdentifier("exports")), accessName) + : ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("exports"), accessName); + if (areAllModuleExports) { + ts.setParent(reference.expression.expression, reference.expression); + } + ts.setParent(reference.expression, reference); + ts.setParent(reference, file); + reference.flowNode = file.endFlowNode; + return getFlowTypeOfReference(reference, autoType, undefinedType); } function getFlowTypeInConstructor(symbol, constructor) { var accessName = ts.startsWith(symbol.escapedName, "__#") @@ -50917,7 +52237,10 @@ var ts; return everyType(flowType, isNullableType) ? undefined : convertAutoToAny(flowType); } function getFlowTypeOfProperty(reference, prop) { - var initialType = prop && (!isAutoTypedProperty(prop) || ts.getEffectiveModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType; + var initialType = (prop === null || prop === void 0 ? void 0 : prop.valueDeclaration) + && (!isAutoTypedProperty(prop) || ts.getEffectiveModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) + && getTypeOfPropertyInBaseClass(prop) + || undefinedType; return getFlowTypeOfReference(reference, autoType, initialType); } function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) { @@ -50928,7 +52251,7 @@ var ts; if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + var containerObjectType = symbol.valueDeclaration && getJSContainerObjectType(symbol.valueDeclaration, symbol, container); return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var type; @@ -50940,40 +52263,42 @@ var ts; type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol)); } if (!type) { - var jsdocType = void 0; var types = void 0; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : - ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : - undefined; - if (!expression) { - continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere - } - var kind = ts.isAccessExpression(expression) - ? ts.getAssignmentDeclarationPropertyAccessKind(expression) - : ts.getAssignmentDeclarationKind(expression); - if (kind === 4 /* ThisProperty */ || ts.isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) { - if (isDeclarationInConstructor(expression)) { - definedInConstructor = true; + if (symbol.declarations) { + var jsdocType = void 0; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : + ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere } - else { - definedInMethod = true; + var kind = ts.isAccessExpression(expression) + ? ts.getAssignmentDeclarationPropertyAccessKind(expression) + : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */ || ts.isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + if (!ts.isCallExpression(expression)) { + jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } - if (!ts.isCallExpression(expression)) { - jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); - } - if (!jsdocType) { - (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); - } + type = jsdocType; } - type = jsdocType; if (!type) { if (!ts.length(types)) { return errorType; // No types from any declarations :( } - var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; + var constructorTypes = definedInConstructor && symbol.declarations ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { var propType = getTypeOfPropertyInBaseClass(symbol); @@ -50987,7 +52312,7 @@ var ts; } } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); - if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { + if (symbol.valueDeclaration && filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } @@ -51011,10 +52336,11 @@ var ts; mergeSymbolTable(exports, s.exports); } var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - type.objectFlags |= 16384 /* JSLiteral */; + type.objectFlags |= 8192 /* JSLiteral */; return type; } function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) { + var _a; var typeNode = ts.getEffectiveTypeAnnotationNode(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -51025,7 +52351,7 @@ var ts; errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type); } } - if (symbol.parent) { + if ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) { var typeNode_2 = ts.getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration); if (typeNode_2) { return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode_2), symbol.escapedName); @@ -51089,7 +52415,7 @@ var ts; // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because // it's unclear what that's supposed to mean, so it's probably a mistake. - if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { + if (s.valueDeclaration && exportedMember.valueDeclaration && ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName); var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration; ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName)); @@ -51111,9 +52437,9 @@ var ts; }); var result = createAnonymousType(initialSize !== members_4.size ? undefined : exportedType.symbol, // Only set the type's symbol if it looks to be the same as the original type members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo); - result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + result.objectFlags |= (ts.getObjectFlags(type) & 8192 /* JSLiteral */); // Propagate JSLiteral flag if (result.symbol && result.symbol.flags & 32 /* Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { - result.objectFlags |= 1073741824 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type + result.objectFlags |= 16777216 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type } return result; } @@ -51132,9 +52458,9 @@ var ts; var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. // Function expressions that are assigned to the prototype count as methods. - return thisContainer.kind === 166 /* Constructor */ || - thisContainer.kind === 251 /* FunctionDeclaration */ || - (thisContainer.kind === 208 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + return thisContainer.kind === 167 /* Constructor */ || + thisContainer.kind === 252 /* FunctionDeclaration */ || + (thisContainer.kind === 209 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); } function getConstructorDefinedThisAssignmentTypes(types, declarations) { ts.Debug.assert(types.length === declarations.length); @@ -51172,7 +52498,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -51196,7 +52522,7 @@ var ts; result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -51204,7 +52530,7 @@ var ts; function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - var restElement = lastElement && lastElement.kind === 198 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : undefined; + var restElement = lastElement && lastElement.kind === 199 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : undefined; if (elements.length === 0 || elements.length === 1 && restElement) { return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } @@ -51215,7 +52541,7 @@ var ts; if (includePatternInType) { result = cloneTypeReference(result); result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -51229,7 +52555,7 @@ var ts; function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { if (includePatternInType === void 0) { includePatternInType = false; } if (reportErrors === void 0) { reportErrors = false; } - return pattern.kind === 196 /* ObjectBindingPattern */ + return pattern.kind === 197 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -51245,8 +52571,17 @@ var ts; function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors); } + function isGlobalSymbolConstructor(node) { + var symbol = getSymbolOfNode(node); + var globalSymbol = getGlobalESSymbolConstructorTypeSymbol(/*reportErrors*/ false); + return globalSymbol && symbol && symbol === globalSymbol; + } function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) { if (type) { + // TODO: If back compat with pre-3.0/4.0 libs isn't required, remove the following SymbolConstructor special case transforming `symbol` into `unique symbol` + if (type.flags & 4096 /* ESSymbol */ && isGlobalSymbolConstructor(declaration.parent)) { + type = getESSymbolLikeTypeForNode(declaration); + } if (reportErrors) { reportErrorsFromWidening(declaration, type); } @@ -51268,7 +52603,7 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 160 /* Parameter */ ? root.parent : root; + var memberDeclaration = root.kind === 161 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function tryGetTypeFromEffectiveTypeNode(declaration) { @@ -51299,19 +52634,31 @@ var ts; if (symbol === requireSymbol) { return anyType; } - if (symbol.flags & 134217728 /* ModuleExports */) { + if (symbol.flags & 134217728 /* ModuleExports */ && symbol.valueDeclaration) { var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var result = createSymbol(fileSymbol.flags, "exports"); + result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : []; + result.parent = symbol; + result.target = fileSymbol; + if (fileSymbol.valueDeclaration) + result.valueDeclaration = fileSymbol.valueDeclaration; + if (fileSymbol.members) + result.members = new ts.Map(fileSymbol.members); + if (fileSymbol.exports) + result.exports = new ts.Map(fileSymbol.exports); var members = ts.createSymbolTable(); - members.set("exports", fileSymbol); + members.set("exports", result); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); } // Handle catch clause variables + ts.Debug.assertIsDefined(symbol.valueDeclaration); var declaration = symbol.valueDeclaration; if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { - var decl = declaration; - if (!decl.type) + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode === undefined) { return anyType; - var type_1 = getTypeOfNode(decl.type); + } + var type_1 = getTypeOfNode(typeNode); // an errorType will make `checkTryStatement` issue an error return isTypeAny(type_1) || type_1 === unknownType ? type_1 : errorType; } @@ -51331,7 +52678,7 @@ var ts; return reportCircularityError(symbol); } var type; - if (declaration.kind === 266 /* ExportAssignment */) { + if (declaration.kind === 267 /* ExportAssignment */) { type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } else if (ts.isBinaryExpression(declaration) || @@ -51386,7 +52733,7 @@ var ts; type = getTypeOfEnumMember(symbol); } else if (ts.isAccessor(declaration)) { - type = resolveTypeOfAccessors(symbol); + type = resolveTypeOfAccessors(symbol) || ts.Debug.fail("Non-write accessor resolution must always produce a type"); } else { return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol)); @@ -51402,7 +52749,7 @@ var ts; } function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { - if (accessor.kind === 167 /* GetAccessor */) { + if (accessor.kind === 168 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation; } @@ -51426,63 +52773,78 @@ var ts; } function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); - return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + return links.type || (links.type = getTypeOfAccessorsWorker(symbol) || ts.Debug.fail("Read type of accessor must always produce a type")); + } + function getTypeOfSetAccessor(symbol) { + var links = getSymbolLinks(symbol); + return links.writeType || (links.writeType = getTypeOfAccessorsWorker(symbol, /*writing*/ true)); } - function getTypeOfAccessorsWorker(symbol) { + function getTypeOfAccessorsWorker(symbol, writing) { + if (writing === void 0) { writing = false; } if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } - var type = resolveTypeOfAccessors(symbol); + var type = resolveTypeOfAccessors(symbol, writing); if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter = ts.getDeclarationOfKind(symbol, 167 /* GetAccessor */); + var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); error(getter, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } return type; } - function resolveTypeOfAccessors(symbol) { - var getter = ts.getDeclarationOfKind(symbol, 167 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 168 /* SetAccessor */); + function resolveTypeOfAccessors(symbol, writing) { + if (writing === void 0) { writing = false; } + var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); + // For write operations, prioritize type annotations on the setter + if (writing && setterType) { + return instantiateTypeIfNeeded(setterType, symbol); + } + // Else defer to the getter type if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { - return jsDocType; + return instantiateTypeIfNeeded(jsDocType, symbol); } } - // First try to see if the user specified a return type on the get-accessor. - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - return getterReturnType; + // Try to see if the user specified a return type on the get-accessor. + var getterType = getAnnotatedAccessorType(getter); + if (getterType) { + return instantiateTypeIfNeeded(getterType, symbol); } - else { - // If the user didn't specify a return type, try to use the set-accessor's parameter type. - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - return setterParameterType; + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + if (setterType) { + return setterType; + } + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + var returnTypeFromBody = getReturnTypeFromBody(getter); + return instantiateTypeIfNeeded(returnTypeFromBody, symbol); + } + // Otherwise, fall back to 'any'. + if (setter) { + if (!isPrivateWithinAmbient(setter)) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); } - else { - // If there are no specified types, try to infer it from the body of the get accessor if it exists. - if (getter && getter.body) { - return getReturnTypeFromBody(getter); - } - // Otherwise, fall back to 'any'. - else { - if (setter) { - if (!isPrivateWithinAmbient(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 exist a getter as we are current checking either setter or getter in this function"); - if (!isPrivateWithinAmbient(getter)) { - errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } - } - return anyType; - } + return anyType; + } + else if (getter) { + ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } + return anyType; + } + return undefined; + function instantiateTypeIfNeeded(type, symbol) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + var links = getSymbolLinks(symbol); + return instantiateType(type, links.mapper); } + return type; } } function getBaseTypeVariableOfClass(symbol) { @@ -51512,9 +52874,9 @@ var ts; if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration && (declaration.kind === 216 /* BinaryExpression */ || + else if (declaration && (declaration.kind === 217 /* BinaryExpression */ || ts.isAccessExpression(declaration) && - declaration.parent.kind === 216 /* BinaryExpression */)) { + declaration.parent.kind === 217 /* BinaryExpression */)) { return getWidenedTypeForAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { @@ -51548,14 +52910,16 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); + var exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(getDeclarationOfAliasSymbol(symbol), /*dontResolveAlias*/ true); // It only makes sense to get the type of a value symbol. If the result of resolving // the alias is not a value, then it has no type. To get the type associated with a // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 111551 /* Value */ - ? getTypeOfSymbol(targetSymbol) - : errorType; + links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) + : isDuplicatedCommonJSExport(symbol.declarations) ? autoType + : targetSymbol.flags & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) + : errorType; } return links.type; } @@ -51581,7 +52945,7 @@ var ts; return errorType; } // Check if variable has initializer that circularly references the variable itself - if (noImplicitAny && (declaration.kind !== 160 /* Parameter */ || declaration.initializer)) { + if (noImplicitAny && (declaration.kind !== 161 /* Parameter */ || declaration.initializer)) { error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); } // Circularities could also result from parameters in function expressions that end up @@ -51598,6 +52962,15 @@ var ts; } return links.type; } + function getSetAccessorTypeOfSymbol(symbol) { + if (symbol.flags & 98304 /* Accessor */) { + var type = getTypeOfSetAccessor(symbol); + if (type) { + return type; + } + } + return getTypeOfSymbol(symbol); + } function getTypeOfSymbol(symbol) { var checkFlags = ts.getCheckFlags(symbol); if (checkFlags & 65536 /* DeferredType */) { @@ -51680,66 +53053,72 @@ var ts; return undefined; } switch (node.kind) { - case 232 /* VariableStatement */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 164 /* MethodSignature */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 308 /* JSDocFunctionType */: - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 254 /* TypeAliasDeclaration */: - case 330 /* JSDocTemplateTag */: - case 331 /* JSDocTypedefTag */: - case 325 /* JSDocEnumTag */: - case 324 /* JSDocCallbackTag */: - case 190 /* MappedType */: - case 184 /* ConditionalType */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 165 /* MethodSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 309 /* JSDocFunctionType */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 255 /* TypeAliasDeclaration */: + case 334 /* JSDocTemplateTag */: + case 335 /* JSDocTypedefTag */: + case 329 /* JSDocEnumTag */: + case 328 /* JSDocCallbackTag */: + case 191 /* MappedType */: + case 185 /* ConditionalType */: { var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 190 /* MappedType */) { + if (node.kind === 191 /* MappedType */) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } - else if (node.kind === 184 /* ConditionalType */) { + else if (node.kind === 185 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } - else if (node.kind === 232 /* VariableStatement */ && !ts.isInJSFile(node)) { - break; - } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && - (node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */ || node.kind === 253 /* InterfaceDeclaration */ || isJSConstructor(node)) && + (node.kind === 253 /* ClassDeclaration */ || node.kind === 222 /* ClassExpression */ || node.kind === 254 /* InterfaceDeclaration */ || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; - case 326 /* JSDocParameterTag */: + } + case 330 /* JSDocParameterTag */: var paramSymbol = ts.getParameterSymbolFromJSDoc(node); if (paramSymbol) { node = paramSymbol.valueDeclaration; } break; + case 312 /* JSDocComment */: { + var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + return node.tags + ? appendTypeParameters(outerTypeParameters, ts.flatMap(node.tags, function (t) { return ts.isJSDocTemplateTag(t) ? t.typeParameters : undefined; })) + : outerTypeParameters; + } } } } // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 253 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 254 /* InterfaceDeclaration */); ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, // interface, or type alias. function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + if (!symbol.declarations) { + return; + } var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 253 /* InterfaceDeclaration */ || - node.kind === 252 /* ClassDeclaration */ || - node.kind === 221 /* ClassExpression */ || + if (node.kind === 254 /* InterfaceDeclaration */ || + node.kind === 253 /* ClassDeclaration */ || + node.kind === 222 /* ClassExpression */ || isJSConstructor(node) || ts.isTypeAlias(node)) { var declaration = node; @@ -51833,7 +53212,9 @@ var ts; ctorReturn = getReturnTypeOfSignature(ctorSig[0]); } } - ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + if (baseConstructorType.symbol.declarations) { + ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } } return type.resolvedBaseConstructorType = errorType; } @@ -51843,20 +53224,22 @@ var ts; } function getImplementsTypes(type) { var resolvedImplementsTypes = ts.emptyArray; - for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration); - if (!implementsTypeNodes) - continue; - for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) { - var node = implementsTypeNodes_1[_b]; - var implementsType = getTypeFromTypeNode(node); - if (implementsType !== errorType) { - if (resolvedImplementsTypes === ts.emptyArray) { - resolvedImplementsTypes = [implementsType]; - } - else { - resolvedImplementsTypes.push(implementsType); + if (type.symbol.declarations) { + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration); + if (!implementsTypeNodes) + continue; + for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) { + var node = implementsTypeNodes_1[_b]; + var implementsType = getTypeFromTypeNode(node); + if (implementsType !== errorType) { + if (resolvedImplementsTypes === ts.emptyArray) { + resolvedImplementsTypes = [implementsType]; + } + else { + resolvedImplementsTypes.push(implementsType); + } } } } @@ -51883,10 +53266,10 @@ var ts; else { ts.Debug.fail("type must be class or interface"); } - if (!popTypeResolution()) { + if (!popTypeResolution() && type.symbol.declarations) { for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 252 /* ClassDeclaration */ || declaration.kind === 253 /* InterfaceDeclaration */) { + if (declaration.kind === 253 /* ClassDeclaration */ || declaration.kind === 254 /* InterfaceDeclaration */) { reportCircularBaseType(declaration, type); } } @@ -51979,29 +53362,31 @@ var ts; } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; - for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 253 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { - for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { - var node = _c[_b]; - var baseType = getReducedType(getTypeFromTypeNode(node)); - if (baseType !== errorType) { - if (isValidBaseType(baseType)) { - if (type !== baseType && !hasBaseType(baseType, type)) { - if (type.resolvedBaseTypes === ts.emptyArray) { - type.resolvedBaseTypes = [baseType]; + if (type.symbol.declarations) { + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 254 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { + var node = _c[_b]; + var baseType = getReducedType(getTypeFromTypeNode(node)); + if (baseType !== errorType) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } } else { - type.resolvedBaseTypes.push(baseType); + reportCircularBaseType(declaration, type); } } else { - reportCircularBaseType(declaration, type); + error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } - else { - error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); - } } } } @@ -52015,9 +53400,12 @@ var ts; * and if none of the base interfaces have a "this" type. */ function isThislessInterface(symbol) { + if (!symbol.declarations) { + return true; + } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 253 /* InterfaceDeclaration */) { + if (declaration.kind === 254 /* InterfaceDeclaration */) { if (declaration.flags & 128 /* ContainsThis */) { return false; } @@ -52042,7 +53430,7 @@ var ts; var originalLinks = links; if (!links.declaredType) { var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */; - var merged = mergeJSSymbols(symbol, getAssignedClassSymbol(symbol.valueDeclaration)); + var merged = mergeJSSymbols(symbol, symbol.valueDeclaration && getAssignedClassSymbol(symbol.valueDeclaration)); if (merged) { // note:we overwrite links because we just cloned the symbol symbol = links = merged; @@ -52072,6 +53460,7 @@ var ts; return links.declaredType; } function getDeclaredTypeOfTypeAlias(symbol) { + var _a; var links = getSymbolLinks(symbol); if (!links.declaredType) { // Note that we use the links object as the target here because the symbol object is used as the unique @@ -52079,7 +53468,7 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return errorType; } - var declaration = ts.Debug.checkDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found"); + var declaration = ts.Debug.checkDefined((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias), "Type alias symbol with no valid declaration found"); var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; @@ -52105,7 +53494,7 @@ var ts; if (ts.isStringLiteralLike(expr)) { return true; } - else if (expr.kind === 216 /* BinaryExpression */) { + else if (expr.kind === 217 /* BinaryExpression */) { return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); } return false; @@ -52120,12 +53509,12 @@ var ts; case 8 /* NumericLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: return true; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return expr.operator === 40 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; case 78 /* Identifier */: return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return isStringConcatExpression(expr); default: return false; @@ -52137,16 +53526,18 @@ var ts; return links.enumKind; } var hasNonLiteralMember = false; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 255 /* EnumDeclaration */) { - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - if (member.initializer && ts.isStringLiteralLike(member.initializer)) { - return links.enumKind = 1 /* Literal */; - } - if (!isLiteralEnumMember(member)) { - hasNonLiteralMember = true; + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 256 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + if (member.initializer && ts.isStringLiteralLike(member.initializer)) { + return links.enumKind = 1 /* Literal */; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; + } } } } @@ -52164,15 +53555,17 @@ var ts; if (getEnumKind(symbol) === 1 /* Literal */) { enumCount++; var memberTypeList = []; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 255 /* EnumDeclaration */) { - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var value = getEnumMemberValue(member); - var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member))); - getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 256 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var value = getEnumMemberValue(member); + var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member))); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + } } } } @@ -52249,11 +53642,11 @@ var ts; case 113 /* VoidKeyword */: case 150 /* UndefinedKeyword */: case 141 /* NeverKeyword */: - case 191 /* LiteralType */: + case 192 /* LiteralType */: return true; - case 178 /* ArrayType */: + case 179 /* ArrayType */: return isThislessType(node.elementType); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; @@ -52279,7 +53672,7 @@ var ts; function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - return (node.kind === 166 /* Constructor */ || (!!returnType && isThislessType(returnType))) && + return (node.kind === 167 /* Constructor */ || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } @@ -52295,14 +53688,14 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return isThislessVariableLikeDeclaration(declaration); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return isThislessFunctionLikeDeclaration(declaration); } } @@ -52328,7 +53721,7 @@ var ts; } } function isStaticPrivateIdentifierProperty(s) { - return !!s.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(s.valueDeclaration) && ts.hasSyntacticModifier(s.valueDeclaration, 32 /* Static */); + return !!s.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(s.valueDeclaration) && ts.hasSyntacticModifier(s.valueDeclaration, 32 /* Static */); } function resolveDeclaredMembers(type) { if (!type.declaredProperties) { @@ -52380,10 +53773,10 @@ var ts; return !!name && isLateBindableName(name); } /** - * Indicates whether a declaration has a dynamic name that cannot be late-bound. + * Indicates whether a declaration has an early-bound name or a dynamic name that can be late-bound. */ - function hasNonBindableDynamicName(node) { - return ts.hasDynamicName(node) && !hasLateBindableName(node); + function hasBindableName(node) { + return !ts.hasDynamicName(node) || hasLateBindableName(node); } /** * Indicates whether a declaration name is a dynamic name that cannot be late-bound. @@ -52653,7 +54046,8 @@ var ts; sig.resolvedMinArgumentCount = undefined; sig.target = undefined; sig.mapper = undefined; - sig.unionSignatures = undefined; + sig.compositeSignatures = undefined; + sig.compositeKind = undefined; return sig; } function cloneSignature(sig) { @@ -52661,12 +54055,14 @@ var ts; /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 39 /* PropagatingFlags */); result.target = sig.target; result.mapper = sig.mapper; - result.unionSignatures = sig.unionSignatures; + result.compositeSignatures = sig.compositeSignatures; + result.compositeKind = sig.compositeKind; return result; } function createUnionSignature(signature, unionSignatures) { var result = cloneSignature(signature); - result.unionSignatures = unionSignatures; + result.compositeSignatures = unionSignatures; + result.compositeKind = 1048576 /* Union */; result.target = undefined; result.mapper = undefined; return result; @@ -52825,7 +54221,7 @@ var ts; if (signatures !== masterList) { var signature_1 = signatures[0]; ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); - results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters && !compareTypeParametersIdentical(signature_1.typeParameters, s.typeParameters); }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); }); + results = !!signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters && !compareTypeParametersIdentical(signature_1.typeParameters, s.typeParameters); }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); }); if (!results) { return "break"; } @@ -52842,9 +54238,12 @@ var ts; return result || ts.emptyArray; } function compareTypeParametersIdentical(sourceParams, targetParams) { - if (sourceParams.length !== targetParams.length) { + if (ts.length(sourceParams) !== ts.length(targetParams)) { return false; } + if (!sourceParams || !targetParams) { + return true; + } var mapper = createTypeMapper(targetParams, sourceParams); for (var i = 0; i < sourceParams.length; i++) { var source = sourceParams[i]; @@ -52926,9 +54325,10 @@ var ts; var result = createSignature(declaration, typeParams, thisParam, params, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 39 /* PropagatingFlags */); - result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); + result.compositeKind = 1048576 /* Union */; + result.compositeSignatures = ts.concatenate(left.compositeKind !== 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); if (paramMapper) { - result.mapper = left.mapper && left.unionSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; + result.mapper = left.compositeKind !== 2097152 /* Intersection */ && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; } return result; } @@ -53061,6 +54461,7 @@ var ts; // Combinations of function, class, enum and module var members = emptySymbols; var stringIndexInfo = void 0; + var numberIndexInfo = void 0; if (symbol.exports) { members = getExportsOfSymbol(symbol); if (symbol === globalThisSymbol) { @@ -53073,20 +54474,31 @@ var ts; members = varsOnly_1; } } + var baseConstructorIndexInfo = void 0; setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) { - members = ts.createSymbolTable(getNamedMembers(members)); + members = ts.createSymbolTable(getNamedOrIndexSignatureMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } else if (baseConstructorType === anyType) { - stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + baseConstructorIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + } + } + var indexSymbol = getIndexSymbolFromSymbolTable(members); + if (indexSymbol) { + stringIndexInfo = getIndexInfoOfIndexSymbol(indexSymbol, 0 /* String */); + numberIndexInfo = getIndexInfoOfIndexSymbol(indexSymbol, 1 /* Number */); + } + else { + stringIndexInfo = baseConstructorIndexInfo; + if (symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ || + ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); }))) { + numberIndexInfo = enumNumberIndexInfo; } } - var numberIndexInfo = symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ || - ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); })) ? enumNumberIndexInfo : undefined; setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); // We resolve the members before computing the signatures because a signature may use // typeof with a qualified name expression that circularly references the type we are @@ -53111,6 +54523,18 @@ var ts; } } } + function replaceIndexedAccess(instantiable, type, replacement) { + // map type.indexType to 0 + // map type.objectType to `[TReplacement]` + // thus making the indexed access `[TReplacement][0]` or `TReplacement` + return instantiateType(instantiable, createTypeMapper([type.indexType, type.objectType], [getLiteralType(0), createTupleType([replacement])])); + } + function getIndexInfoOfIndexSymbol(indexSymbol, indexKind) { + var declaration = getIndexDeclarationOfIndexSymbol(indexSymbol, indexKind); + if (!declaration) + return undefined; + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasEffectiveModifier(declaration, 64 /* Readonly */), declaration); + } function resolveReverseMappedTypeMembers(type) { var indexInfo = getIndexInfoOfType(type.source, 0 /* String */); var modifiers = getMappedTypeModifiers(type.mappedType); @@ -53125,8 +54549,21 @@ var ts; inferredProp.declarations = prop.declarations; inferredProp.nameType = getSymbolLinks(prop).nameType; inferredProp.propertyType = getTypeOfSymbol(prop); - inferredProp.mappedType = type.mappedType; - inferredProp.constraintType = type.constraintType; + if (type.constraintType.type.flags & 8388608 /* IndexedAccess */ + && type.constraintType.type.objectType.flags & 262144 /* TypeParameter */ + && type.constraintType.type.indexType.flags & 262144 /* TypeParameter */) { + // A reverse mapping of `{[K in keyof T[K_1]]: T[K_1]}` is the same as that of `{[K in keyof T]: T}`, since all we care about is + // inferring to the "type parameter" (or indexed access) shared by the constraint and template. So, to reduce the number of + // type identities produced, we simplify such indexed access occurences + var newTypeParam = type.constraintType.type.objectType; + var newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type, newTypeParam); + inferredProp.mappedType = newMappedType; + inferredProp.constraintType = getIndexType(newTypeParam); + } + else { + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + } members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -53288,7 +54725,7 @@ var ts; } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 - return constraintDeclaration.kind === 188 /* TypeOperator */ && + return constraintDeclaration.kind === 189 /* TypeOperator */ && constraintDeclaration.operator === 138 /* KeyOfKeyword */; } function getModifiersTypeFromMappedType(type) { @@ -53340,7 +54777,7 @@ var ts; else if (type.objectFlags & 3 /* ClassOrInterface */) { resolveClassOrInterfaceMembers(type); } - else if (type.objectFlags & 2048 /* ReverseMapped */) { + else if (type.objectFlags & 1024 /* ReverseMapped */) { resolveReverseMappedTypeMembers(type); } else if (type.objectFlags & 16 /* Anonymous */) { @@ -53624,12 +55061,22 @@ var ts; if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; + var different = false; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type_3 = types_8[_i]; var baseType = getBaseConstraint(type_3); if (baseType) { + if (baseType !== type_3) { + different = true; + } baseTypes.push(baseType); } + else { + different = true; + } + } + if (!different) { + return t; } return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : @@ -53749,6 +55196,7 @@ var ts; return getReducedType(getApparentType(getReducedType(type))); } function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) { + var _a, _b; var singleProp; var propSet; var indexTypes; @@ -53757,8 +55205,9 @@ var ts; var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var current = _a[_i]; + var mergedInstantiations = false; + for (var _i = 0, _c = containingType.types; _i < _c.length; _i++) { + var current = _c[_i]; var type = getApparentType(current); if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); @@ -53774,13 +55223,25 @@ var ts; singleProp = prop; } else if (prop !== singleProp) { - if (!propSet) { - propSet = new ts.Map(); - propSet.set(getSymbolId(singleProp), singleProp); + var isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp); + // If the symbols are instances of one another with identical types - consider the symbols + // equivalent and just use the first one, which thus allows us to avoid eliding private + // members when intersecting a (this-)instantiations of a class with it's raw base or another instance + if (isInstantiation && compareProperties(singleProp, prop, function (a, b) { return a === b ? -1 /* True */ : 0 /* False */; }) === -1 /* True */) { + // If we merged instantiations of a generic type, we replicate the symbol parent resetting behavior we used + // to do when we recorded multiple distinct symbols so that we still get, eg, `Array.length` printed + // back and not `Array.length` when we're looking at a `.length` access on a `string[] | number[]` + mergedInstantiations = !!singleProp.parent && !!ts.length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent)); } - var id = getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + else { + if (!propSet) { + propSet = new ts.Map(); + propSet.set(getSymbolId(singleProp), singleProp); + } + var id = getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | @@ -53798,7 +55259,7 @@ var ts; checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0); indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } - else if (isObjectLiteralType(type)) { + else if (isObjectLiteralType(type) && !(ts.getObjectFlags(type) & 4194304 /* ContainsSpread */)) { checkFlags |= 32 /* WritePartial */; indexTypes = ts.append(indexTypes, undefinedType); } @@ -53814,7 +55275,19 @@ var ts; return undefined; } if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { - return singleProp; + if (mergedInstantiations) { + // No symbol from a union/intersection should have a `.parent` set (since unions/intersections don't act as symbol parents) + // Unless that parent is "reconstituted" from the "first value declaration" on the symbol (which is likely different than its instantiated parent!) + // They also have a `.containingType` set, which affects some services endpoints behavior, like `getRootSymbol` + var clone_1 = createSymbolWithType(singleProp, singleProp.type); + clone_1.parent = (_b = (_a = singleProp.valueDeclaration) === null || _a === void 0 ? void 0 : _a.symbol) === null || _b === void 0 ? void 0 : _b.parent; + clone_1.containingType = containingType; + clone_1.mapper = singleProp.mapper; + return clone_1; + } + else { + return singleProp; + } } var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; @@ -53823,8 +55296,8 @@ var ts; var propTypes = []; var firstValueDeclaration; var hasNonUniformValueDeclaration = false; - for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { - var prop = props_1[_b]; + for (var _d = 0, props_1 = props; _d < props_1.length; _d++) { + var prop = props_1[_d]; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } @@ -53901,15 +55374,15 @@ var ts; * no constituent property has type 'never', but the intersection of the constituent property types is 'never'. */ function getReducedType(type) { - if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) { + if (type.flags & 1048576 /* Union */ && type.objectFlags & 67108864 /* ContainsIntersections */) { return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); } else if (type.flags & 2097152 /* Intersection */) { - if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { - type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | - (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0); + if (!(type.objectFlags & 67108864 /* IsNeverIntersectionComputed */)) { + type.objectFlags |= 67108864 /* IsNeverIntersectionComputed */ | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 134217728 /* IsNeverIntersection */ : 0); } - return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; + return type.objectFlags & 134217728 /* IsNeverIntersection */ ? neverType : type; } return type; } @@ -53939,7 +55412,7 @@ var ts; return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */); } function elaborateNeverIntersection(errorInfo, type) { - if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) { + if (type.flags & 2097152 /* Intersection */ && ts.getObjectFlags(type) & 134217728 /* IsNeverIntersection */) { var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); if (neverProp) { return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(neverProp)); @@ -54026,7 +55499,8 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var prop = _a[_i]; if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { - propTypes.push(getTypeOfSymbol(prop)); + var propType = getTypeOfSymbol(prop); + propTypes.push(prop.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType); } } if (kind === 0 /* String */) { @@ -54060,10 +55534,10 @@ var ts; function isJSDocOptionalParameter(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 === 307 /* JSDocOptionalType */ + node.type && node.type.kind === 308 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 307 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 308 /* JSDocOptionalType */; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -54095,12 +55569,15 @@ var ts; } return false; } + function isOptionalPropertyDeclaration(node) { + return ts.isPropertyDeclaration(node) && node.questionToken; + } function isOptionalJSDocPropertyLikeTag(node) { if (!ts.isJSDocPropertyLikeTag(node)) { return false; } var isBracketed = node.isBracketed, typeExpression = node.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 307 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 308 /* JSDocOptionalType */; } function createTypePredicate(kind, parameterName, parameterIndex, type) { return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; @@ -54182,7 +55659,7 @@ var ts; else { parameters.push(paramSymbol); } - if (type && type.kind === 191 /* LiteralType */) { + if (type && type.kind === 192 /* LiteralType */) { flags |= 2 /* HasLiteralTypes */; } // Record a new minimum argument count if this is not an optional parameter @@ -54195,16 +55672,16 @@ var ts; } } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 167 /* GetAccessor */ || declaration.kind === 168 /* SetAccessor */) && - !hasNonBindableDynamicName(declaration) && + if ((declaration.kind === 168 /* GetAccessor */ || declaration.kind === 169 /* SetAccessor */) && + hasBindableName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; + var otherKind = declaration.kind === 168 /* GetAccessor */ ? 169 /* SetAccessor */ : 168 /* GetAccessor */; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 166 /* Constructor */ ? + var classType = declaration.kind === 167 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); @@ -54249,8 +55726,7 @@ var ts; if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node))) return undefined; var typeTag = ts.getJSDocTypeTag(node); - var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); - return signature && getErasedSignature(signature); + return (typeTag === null || typeTag === void 0 ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); } function getReturnTypeOfTypeTag(node) { var signature = getSignatureOfTypeTag(node); @@ -54273,14 +55749,14 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node.escapedText === argumentsSymbol.escapedName && getResolvedSymbol(node) === argumentsSymbol; - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - return node.name.kind === 158 /* ComputedPropertyName */ + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return node.name.kind === 159 /* ComputedPropertyName */ && traverse(node.name); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return traverse(node.expression); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); @@ -54288,7 +55764,7 @@ var ts; } } function getSignaturesOfSymbol(symbol) { - if (!symbol) + if (!symbol || !symbol.declarations) return ts.emptyArray; var result = []; for (var i = 0; i < symbol.declarations.length; i++) { @@ -54329,8 +55805,8 @@ var ts; var targetTypePredicate = getTypePredicateOfSignature(signature.target); signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; } - else if (signature.unionSignatures) { - signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + else if (signature.compositeSignatures) { + signature.resolvedTypePredicate = getUnionOrIntersectionTypePredicate(signature.compositeSignatures, signature.compositeKind) || noTypePredicate; } else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); @@ -54352,17 +55828,20 @@ var ts; function createTypePredicateFromTypePredicateNode(node, signature) { var parameterName = node.parameterName; var type = node.type && getTypeFromTypeNode(node.type); - return parameterName.kind === 187 /* ThisType */ ? + return parameterName.kind === 188 /* ThisType */ ? createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) : createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type); } + function getUnionOrIntersectionType(types, kind, unionReduction) { + return kind !== 2097152 /* Intersection */ ? getUnionType(types, unionReduction) : getIntersectionType(types); + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { return errorType; } var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : - signature.unionSignatures ? instantiateType(getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */), signature.mapper) : + signature.compositeSignatures ? instantiateType(getUnionOrIntersectionType(ts.map(signature.compositeSignatures, getReturnTypeOfSignature), signature.compositeKind, 2 /* Subtype */), signature.mapper) : getReturnTypeFromAnnotation(signature.declaration) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (signature.flags & 8 /* IsInnerCallChain */) { @@ -54395,7 +55874,7 @@ var ts; return signature.resolvedReturnType; } function getReturnTypeFromAnnotation(declaration) { - if (declaration.kind === 166 /* Constructor */) { + if (declaration.kind === 167 /* Constructor */) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); } if (ts.isJSDocConstructSignature(declaration)) { @@ -54405,12 +55884,12 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 167 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + if (declaration.kind === 168 /* GetAccessor */ && hasBindableName(declaration)) { var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 168 /* SetAccessor */); + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 169 /* SetAccessor */); var setterType = getAnnotatedAccessorType(setter); if (setterType) { return setterType; @@ -54487,9 +55966,20 @@ var ts; function getBaseSignature(signature) { var typeParameters = signature.typeParameters; if (typeParameters) { - var typeEraser_1 = createTypeEraser(typeParameters); - var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || unknownType; }); - return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); + if (signature.baseSignatureCache) { + return signature.baseSignatureCache; + } + var typeEraser = createTypeEraser(typeParameters); + var baseConstraintMapper_1 = createTypeMapper(typeParameters, ts.map(typeParameters, function (tp) { return getConstraintOfTypeParameter(tp) || unknownType; })); + var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(tp, baseConstraintMapper_1) || unknownType; }); + // Run N type params thru the immediate constraint mapper up to N times + // This way any noncircular interdependent type parameters are definitely resolved to their external dependencies + for (var i = 0; i < typeParameters.length - 1; i++) { + baseConstraints = instantiateTypes(baseConstraints, baseConstraintMapper_1); + } + // and then apply a type eraser to remove any remaining circularly dependent type parameters + baseConstraints = instantiateTypes(baseConstraints, typeEraser); + return signature.baseSignatureCache = instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); } return signature; } @@ -54500,7 +55990,7 @@ var ts; // will result in a different declaration kind. if (!signature.isolatedSignatureType) { var kind = signature.declaration ? signature.declaration.kind : 0 /* Unknown */; - var isConstructor = kind === 166 /* Constructor */ || kind === 170 /* ConstructSignature */ || kind === 175 /* ConstructorType */; + var isConstructor = kind === 167 /* Constructor */ || kind === 171 /* ConstructSignature */ || kind === 176 /* ConstructorType */; var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -54511,12 +56001,22 @@ var ts; return signature.isolatedSignatureType; } function getIndexSymbol(symbol) { - return symbol.members.get("__index" /* Index */); + return symbol.members ? getIndexSymbolFromSymbolTable(symbol.members) : undefined; + } + function getIndexSymbolFromSymbolTable(symbolTable) { + return symbolTable.get("__index" /* Index */); } function getIndexDeclarationOfSymbol(symbol, kind) { + var indexSymbol = symbol && getIndexSymbol(symbol); + return indexSymbol && getIndexDeclarationOfIndexSymbol(indexSymbol, kind); + } + function getIndexDeclarationOfSymbolTable(symbolTable, kind) { + var indexSymbol = symbolTable && getIndexSymbolFromSymbolTable(symbolTable); + return indexSymbol && getIndexDeclarationOfIndexSymbol(indexSymbol, kind); + } + function getIndexDeclarationOfIndexSymbol(indexSymbol, kind) { var syntaxKind = kind === 1 /* Number */ ? 144 /* NumberKeyword */ : 147 /* StringKeyword */; - var indexSymbol = getIndexSymbol(symbol); - if (indexSymbol) { + if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; var node = ts.cast(decl, ts.isIndexSignatureDeclaration); @@ -54544,17 +56044,18 @@ var ts; return ts.mapDefined(ts.filter(type.symbol && type.symbol.declarations, ts.isTypeParameterDeclaration), ts.getEffectiveConstraintOfTypeParameter)[0]; } function getInferredTypeParameterConstraint(typeParameter) { + var _a; var inferences; - if (typeParameter.symbol) { - for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.parent.kind === 185 /* InferType */) { + if ((_a = typeParameter.symbol) === null || _a === void 0 ? void 0 : _a.declarations) { + for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (declaration.parent.kind === 186 /* InferType */) { // When an 'infer T' declaration is immediately contained in a type reference node // (such as 'Foo'), T's constraint is inferred from the constraint of the // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are // present, we form an intersection of the inferred constraint types. - var _b = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _c = _b[0], childTypeParameter = _c === void 0 ? declaration.parent : _c, grandParent = _b[1]; - if (grandParent.kind === 173 /* TypeReference */) { + var _c = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _d = _c[0], childTypeParameter = _d === void 0 ? declaration.parent : _d, grandParent = _c[1]; + if (grandParent.kind === 174 /* TypeReference */) { var typeReference = grandParent; var typeParameters = getTypeParametersForTypeReference(typeReference); if (typeParameters) { @@ -54579,21 +56080,32 @@ var ts; } // When an 'infer T' declaration is immediately contained in a rest parameter declaration, a rest type // or a named rest tuple element, we infer an 'unknown[]' constraint. - else if (grandParent.kind === 160 /* Parameter */ && grandParent.dotDotDotToken || - grandParent.kind === 181 /* RestType */ || - grandParent.kind === 192 /* NamedTupleMember */ && grandParent.dotDotDotToken) { + else if (grandParent.kind === 161 /* Parameter */ && grandParent.dotDotDotToken || + grandParent.kind === 182 /* RestType */ || + grandParent.kind === 193 /* NamedTupleMember */ && grandParent.dotDotDotToken) { inferences = ts.append(inferences, createArrayType(unknownType)); } // When an 'infer T' declaration is immediately contained in a string template type, we infer a 'string' // constraint. - else if (grandParent.kind === 194 /* TemplateLiteralTypeSpan */) { + else if (grandParent.kind === 195 /* TemplateLiteralTypeSpan */) { inferences = ts.append(inferences, stringType); } // When an 'infer T' declaration is in the constraint position of a mapped type, we infer a 'keyof any' // constraint. - else if (grandParent.kind === 159 /* TypeParameter */ && grandParent.parent.kind === 190 /* MappedType */) { + else if (grandParent.kind === 160 /* TypeParameter */ && grandParent.parent.kind === 191 /* MappedType */) { inferences = ts.append(inferences, keyofConstraintType); } + // When an 'infer T' declaration is the template of a mapped type, and that mapped type is the extends + // clause of a conditional whose check type is also a mapped type, give it a constraint equal to the template + // of the check type's mapped type + else if (grandParent.kind === 191 /* MappedType */ && grandParent.type && + ts.skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 185 /* ConditionalType */ && + grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 191 /* MappedType */ && + grandParent.parent.checkType.type) { + var checkMappedType_1 = grandParent.parent.checkType; + var nodeType = getTypeFromTypeNode(checkMappedType_1.type); + inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); + } } } } @@ -54616,7 +56128,7 @@ var ts; if (type.flags & 1 /* Any */ && type !== errorType) { // Allow errorType to propegate to keep downstream errors suppressed // use keyofConstraintType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was), // use unknown otherwise - type = constraintDeclaration.parent.parent.kind === 190 /* MappedType */ ? keyofConstraintType : unknownType; + type = constraintDeclaration.parent.parent.kind === 191 /* MappedType */ ? keyofConstraintType : unknownType; } typeParameter.constraint = type; } @@ -54625,7 +56137,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - var tp = ts.getDeclarationOfKind(typeParameter.symbol, 159 /* TypeParameter */); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 160 /* TypeParameter */); var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; return host && getSymbolOfNode(host); } @@ -54652,6 +56164,9 @@ var ts; } return result; } + function getAliasId(aliasSymbol, aliasTypeArguments) { + return aliasSymbol ? "@" + getSymbolId(aliasSymbol) + (aliasTypeArguments ? ":" + getTypeListId(aliasTypeArguments) : "") : ""; + } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type // of an object literal or the anyFunctionType. This is because there are operations in the type checker @@ -54664,7 +56179,7 @@ var ts; result |= ts.getObjectFlags(type); } } - return result & 3670016 /* PropagatingFlags */; + return result & 917504 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -54686,15 +56201,18 @@ var ts; type.resolvedTypeArguments = source.resolvedTypeArguments; return type; } - function createDeferredTypeReference(target, node, mapper) { - var aliasSymbol = getAliasSymbolForTypeNode(node); - var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + function createDeferredTypeReference(target, node, mapper, aliasSymbol, aliasTypeArguments) { + if (!aliasSymbol) { + aliasSymbol = getAliasSymbolForTypeNode(node); + var localAliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + aliasTypeArguments = mapper ? instantiateTypes(localAliasTypeArguments, mapper) : localAliasTypeArguments; + } var type = createObjectType(4 /* Reference */, target.symbol); type.target = target; type.node = node; type.mapper = mapper; type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = mapper ? instantiateTypes(aliasTypeArguments, mapper) : aliasTypeArguments; + type.aliasTypeArguments = aliasTypeArguments; return type; } function getTypeArguments(type) { @@ -54705,8 +56223,8 @@ var ts; } var node = type.node; var typeArguments = !node ? ts.emptyArray : - node.kind === 173 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : - node.kind === 178 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : + node.kind === 174 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : + node.kind === 179 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); if (popTypeResolution()) { type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; @@ -54748,7 +56266,7 @@ var ts; return errorType; } } - if (node.kind === 173 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) { + if (node.kind === 174 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) { return createDeferredTypeReference(type, node, /*mapper*/ undefined); } // In a type reference, the outer type parameters of the referenced class or interface are automatically @@ -54759,17 +56277,17 @@ var ts; } return checkNoTypeArguments(node, symbol) ? type : errorType; } - function getTypeAliasInstantiation(symbol, typeArguments) { + function getTypeAliasInstantiation(symbol, typeArguments, aliasSymbol, aliasTypeArguments) { var type = getDeclaredTypeOfSymbol(symbol); if (type === intrinsicMarkerType && intrinsicTypeKinds.has(symbol.escapedName) && typeArguments && typeArguments.length === 1) { return getStringMappingType(symbol, typeArguments[0]); } var links = getSymbolLinks(symbol); var typeParameters = links.typeParameters; - var id = getTypeListId(typeArguments); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments)); } return instantiation; } @@ -54790,15 +56308,26 @@ var ts; ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return errorType; } - return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node)); + // We refrain from associating a local type alias with an instantiation of a top-level type alias + // because the local alias may end up being referenced in an inferred return type where it is not + // accessible--which in turn may lead to a large structural expansion of the type when generating + // a .d.ts file. See #43622 for an example. + var aliasSymbol = getAliasSymbolForTypeNode(node); + var newAliasSymbol = aliasSymbol && (isLocalTypeAlias(symbol) || !isLocalTypeAlias(aliasSymbol)) ? aliasSymbol : undefined; + return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), newAliasSymbol, getTypeArgumentsForAliasSymbol(newAliasSymbol)); } return checkNoTypeArguments(node, symbol) ? type : errorType; } + function isLocalTypeAlias(symbol) { + var _a; + var declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias); + return !!(declaration && ts.getContainingFunction(declaration)); + } function getTypeReferenceName(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return node.typeName; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. var expr = node.expression; @@ -54854,7 +56383,7 @@ var ts; var valueType = getTypeOfSymbol(symbol); var typeType = valueType; if (symbol.valueDeclaration) { - var isImportTypeWithQualifier = node.kind === 195 /* ImportType */ && node.qualifier; + var isImportTypeWithQualifier = node.kind === 196 /* ImportType */ && node.qualifier; // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL} if (valueType.symbol && valueType.symbol !== symbol && isImportTypeWithQualifier) { typeType = getTypeReferenceType(node, valueType.symbol); @@ -54880,7 +56409,7 @@ var ts; return result; } function isUnaryTupleTypeNode(node) { - return node.kind === 179 /* TupleType */ && node.elements.length === 1; + return node.kind === 180 /* TupleType */ && node.elements.length === 1; } function getImpliedConstraint(type, checkNode, extendsNode) { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elements[0], extendsNode.elements[0]) : @@ -54889,9 +56418,17 @@ var ts; } function getConditionalFlowTypeOfType(type, node) { var constraints; - while (node && !ts.isStatement(node) && node.kind !== 311 /* JSDocComment */) { + var covariant = true; + while (node && !ts.isStatement(node) && node.kind !== 312 /* JSDocComment */) { var parent = node.parent; - if (parent.kind === 184 /* ConditionalType */ && node === parent.trueType) { + // only consider variance flipped by parameter locations - `keyof` types would usually be considered variance inverting, but + // often get used in indexed accesses where they behave sortof invariantly, but our checking is lax + if (parent.kind === 161 /* Parameter */) { + covariant = !covariant; + } + // Always substitute on type parameters, regardless of variance, since even + // in contravariant positions, they may rely on substituted constraints to be valid + if ((covariant || type.flags & 8650752 /* TypeVariable */) && parent.kind === 185 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -54902,7 +56439,7 @@ var ts; return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type; } function isJSDocTypeReference(node) { - return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 173 /* TypeReference */ || node.kind === 195 /* ImportType */); + return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 174 /* TypeReference */ || node.kind === 196 /* ImportType */); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -55012,13 +56549,15 @@ var ts; function getTypeOfGlobalSymbol(symbol, arity) { function getTypeDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { - var declaration = declarations_3[_i]; - switch (declaration.kind) { - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - return declaration; + if (declarations) { + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; + switch (declaration.kind) { + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + return declaration; + } } } } @@ -55062,6 +56601,9 @@ var ts; function getGlobalESSymbolConstructorSymbol(reportErrors) { return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); } + function getGlobalESSymbolConstructorTypeSymbol(reportErrors) { + return deferredGlobalESSymbolConstructorTypeSymbol || (deferredGlobalESSymbolConstructorTypeSymbol = getGlobalTypeSymbol("SymbolConstructor", reportErrors)); + } function getGlobalESSymbolType(reportErrors) { return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType; } @@ -55138,11 +56680,11 @@ var ts; } function getTupleElementFlags(node) { switch (node.kind) { - case 180 /* OptionalType */: + case 181 /* OptionalType */: return 2 /* Optional */; - case 181 /* RestType */: + case 182 /* RestType */: return getRestTypeElementFlags(node); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return node.questionToken ? 2 /* Optional */ : node.dotDotDotToken ? getRestTypeElementFlags(node) : 1 /* Required */; @@ -55160,14 +56702,14 @@ var ts; return readonly ? globalReadonlyArrayType : globalArrayType; } var elementFlags = ts.map(node.elements, getTupleElementFlags); - var missingName = ts.some(node.elements, function (e) { return e.kind !== 192 /* NamedTupleMember */; }); + var missingName = ts.some(node.elements, function (e) { return e.kind !== 193 /* NamedTupleMember */; }); return getTupleTargetType(elementFlags, readonly, /*associatedNames*/ missingName ? undefined : node.elements); } // Return true if the given type reference node is directly aliased or if it needs to be deferred // because it is possibly contained in a circular chain of eagerly resolved types. function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) { - return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 178 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) : - node.kind === 179 /* TupleType */ ? ts.some(node.elements, mayResolveTypeAlias) : + return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 179 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) : + node.kind === 180 /* TupleType */ ? ts.some(node.elements, mayResolveTypeAlias) : hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias)); } // Return true when the given node is transitively contained in type constructs that eagerly @@ -55176,18 +56718,18 @@ var ts; function isResolvedByTypeAlias(node) { var parent = node.parent; switch (parent.kind) { - case 186 /* ParenthesizedType */: - case 192 /* NamedTupleMember */: - case 173 /* TypeReference */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 189 /* IndexedAccessType */: - case 184 /* ConditionalType */: - case 188 /* TypeOperator */: - case 178 /* ArrayType */: - case 179 /* TupleType */: + case 187 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: + case 174 /* TypeReference */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 190 /* IndexedAccessType */: + case 185 /* ConditionalType */: + case 189 /* TypeOperator */: + case 179 /* ArrayType */: + case 180 /* TupleType */: return isResolvedByTypeAlias(parent); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return true; } return false; @@ -55196,28 +56738,28 @@ var ts; // of a type alias. function mayResolveTypeAlias(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node.typeName, 788968 /* Type */).flags & 524288 /* TypeAlias */); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return true; - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return node.operator !== 151 /* UniqueKeyword */ && mayResolveTypeAlias(node.type); - case 186 /* ParenthesizedType */: - case 180 /* OptionalType */: - case 192 /* NamedTupleMember */: - case 307 /* JSDocOptionalType */: - case 305 /* JSDocNullableType */: - case 306 /* JSDocNonNullableType */: - case 301 /* JSDocTypeExpression */: + case 187 /* ParenthesizedType */: + case 181 /* OptionalType */: + case 193 /* NamedTupleMember */: + case 308 /* JSDocOptionalType */: + case 306 /* JSDocNullableType */: + case 307 /* JSDocNonNullableType */: + case 302 /* JSDocTypeExpression */: return mayResolveTypeAlias(node.type); - case 181 /* RestType */: - return node.type.kind !== 178 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType); - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 182 /* RestType */: + return node.type.kind !== 179 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType); + case 183 /* UnionType */: + case 184 /* IntersectionType */: return ts.some(node.types, mayResolveTypeAlias); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) || mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType); } @@ -55230,12 +56772,12 @@ var ts; if (target === emptyGenericType) { links.resolvedType = emptyObjectType; } - else if (!(node.kind === 179 /* TupleType */ && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8 /* Variadic */); })) && isDeferredTypeReferenceNode(node)) { - links.resolvedType = node.kind === 179 /* TupleType */ && node.elements.length === 0 ? target : + else if (!(node.kind === 180 /* TupleType */ && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8 /* Variadic */); })) && isDeferredTypeReferenceNode(node)) { + links.resolvedType = node.kind === 180 /* TupleType */ && node.elements.length === 0 ? target : createDeferredTypeReference(target, node, /*mapper*/ undefined); } else { - var elementTypes = node.kind === 178 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); + var elementTypes = node.kind === 179 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); links.resolvedType = createNormalizedTypeReference(target, elementTypes); } } @@ -55367,8 +56909,15 @@ var ts; addElement(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]); } else if (isTupleType(type)) { + var elements = getTypeArguments(type); + if (elements.length + expandedTypes.length >= 10000) { + error(currentNode, ts.isPartOfTypeNode(currentNode) + ? ts.Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent + : ts.Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent); + return { value: errorType }; + } // Spread variadic elements with tuple types into the resulting tuple. - ts.forEach(getTypeArguments(type), function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); + ts.forEach(elements, function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); } else { // Treat everything else as an array type and create a rest element. @@ -55381,7 +56930,9 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - _loop_13(i); + var state_4 = _loop_13(i); + if (typeof state_4 === "object") + return state_4.value; } // Turn optional elements preceding the last required element into required elements for (var i = 0; i < lastRequiredIndex; i++) { @@ -55470,7 +57021,7 @@ var ts; if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { - if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) + if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */)) includes |= 4194304 /* IncludesNonWideningType */; } else { @@ -55492,67 +57043,76 @@ var ts; } return includes; } - function isSetOfLiteralsFromSameEnum(types) { - var first = types[0]; - if (first.flags & 1024 /* EnumLiteral */) { - var firstEnum = getParentOfSymbol(first.symbol); - for (var i = 1; i < types.length; i++) { - var other = types[i]; - if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { - return false; - } - } - return true; + function removeSubtypes(types, hasObjectTypes) { + var id = getTypeListId(types); + var match = subtypeReductionCache.get(id); + if (match) { + return match; } - return false; - } - function removeSubtypes(types, primitivesOnly) { + // We assume that redundant primitive types have already been removed from the types array and that there + // are no any and unknown types in the array. Thus, the only possible supertypes for primitive types are empty + // object types, and if none of those are present we can exclude primitive types from the subtype check. + var hasEmptyObject = hasObjectTypes && ts.some(types, function (t) { return !!(t.flags & 524288 /* Object */) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t)); }); var len = types.length; - if (len === 0 || isSetOfLiteralsFromSameEnum(types)) { - return true; - } var i = len; var count = 0; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var target = types_11[_i]; - if (source !== target) { - if (count === 100000) { - // After 100000 subtype checks we estimate the remaining amount of work by assuming the - // same ratio of checks per element. If the estimated number of remaining type checks is - // greater than an upper limit we deem the union type too complex to represent. The - // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example - // caps union types at 5000 unique literal types and 1000 unique object types. - var estimatedCount = (count / (len - i)) * len; - if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); - error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); - return false; + if (hasEmptyObject || source.flags & 469499904 /* StructuredOrInstantiable */) { + // Find the first property with a unit type, if any. When constituents have a property by the same name + // but of a different unit type, we can quickly disqualify them from subtype checks. This helps subtype + // reduction of large discriminated union types. + var keyProperty = source.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */) ? + ts.find(getPropertiesOfType(source), function (p) { return isUnitType(getTypeOfSymbol(p)); }) : + undefined; + var keyPropertyType = keyProperty && getRegularTypeOfLiteralType(getTypeOfSymbol(keyProperty)); + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var target = types_11[_i]; + if (source !== target) { + if (count === 100000) { + // After 100000 subtype checks we estimate the remaining amount of work by assuming the + // same ratio of checks per element. If the estimated number of remaining type checks is + // greater than 1M we deem the union type too complex to represent. This for example + // caps union types at 1000 unique object types. + var estimatedCount = (count / (len - i)) * len; + if (estimatedCount > 1000000) { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); + error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); + return undefined; + } + } + count++; + if (keyProperty && target.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */)) { + var t = getTypeOfPropertyOfType(target, keyProperty.escapedName); + if (t && isUnitType(t) && getRegularTypeOfLiteralType(t) !== keyPropertyType) { + continue; + } + } + if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { + ts.orderedRemoveItemAt(types, i); + break; } - } - count++; - if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || - !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || - isTypeDerivedFrom(source, target))) { - ts.orderedRemoveItemAt(types, i); - break; } } } } - return true; + subtypeReductionCache.set(id, types); + return types; } - function removeRedundantLiteralTypes(types, includes) { + function removeRedundantLiteralTypes(types, includes, reduceVoidUndefined) { var i = types.length; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 134217856 /* StringLikeLiteral */ && includes & 4 /* String */ || - t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || - t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || - t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + var flags = t.flags; + var remove = flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + reduceVoidUndefined && flags & 32768 /* Undefined */ && includes & 16384 /* Void */ || isFreshLiteralType(t) && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); @@ -55584,7 +57144,7 @@ var ts; if (t.flags & 1048576 /* Union */) { var origin = t.origin; if (t.aliasSymbol || origin && !(origin.flags & 1048576 /* Union */)) { - namedUnions.push(t); + ts.pushIfUnique(namedUnions, t); } else if (origin && origin.flags & 1048576 /* Union */) { addNamedUnions(namedUnions, origin.types); @@ -55618,20 +57178,17 @@ var ts; if (includes & 3 /* AnyOrUnknown */) { return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; } - switch (unionReduction) { - case 1 /* Literal */: - if (includes & (134220672 /* FreshableLiteral */ | 8192 /* UniqueESSymbol */)) { - removeRedundantLiteralTypes(typeSet, includes); - } - if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { - removeStringLiteralsMatchedByTemplateLiterals(typeSet); - } - break; - case 2 /* Subtype */: - if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) { - return errorType; - } - break; + if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */) || includes & 16384 /* Void */ && includes & 32768 /* Undefined */) { + removeRedundantLiteralTypes(typeSet, includes, !!(unionReduction & 2 /* Subtype */)); + } + if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { + removeStringLiteralsMatchedByTemplateLiterals(typeSet); + } + if (unionReduction === 2 /* Subtype */) { + typeSet = removeSubtypes(typeSet, !!(includes & 524288 /* Object */)); + if (!typeSet) { + return errorType; + } } if (typeSet.length === 0) { return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType : @@ -55666,18 +57223,23 @@ var ts; origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes); } } - var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) | - (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0); + var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | + (includes & 2097152 /* Intersection */ ? 67108864 /* ContainsIntersections */ : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } - function getUnionTypePredicate(signatures) { + function getUnionOrIntersectionTypePredicate(signatures, kind) { var first; var types = []; for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { var sig = signatures_6[_i]; var pred = getTypePredicateOfSignature(sig); if (!pred || pred.kind === 2 /* AssertsThis */ || pred.kind === 3 /* AssertsIdentifier */) { - continue; + if (kind !== 2097152 /* Intersection */) { + continue; + } + else { + return; // intersections demand all members be type predicates for the result to have a predicate + } } if (first) { if (!typePredicateKindsMatch(first, pred)) { @@ -55691,11 +57253,11 @@ var ts; types.push(pred.type); } if (!first) { - // No union signatures had a type predicate. + // No signatures had a type predicate. return undefined; } - var unionType = getUnionType(types); - return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, unionType); + var compositeType = getUnionOrIntersectionType(types, kind); + return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, compositeType); } function typePredicateKindsMatch(a, b) { return a.kind === b.kind && a.parameterIndex === b.parameterIndex; @@ -55720,8 +57282,8 @@ var ts; var typeKey = !origin ? getTypeListId(types) : origin.flags & 1048576 /* Union */ ? "|" + getTypeListId(origin.types) : origin.flags & 2097152 /* Intersection */ ? "&" + getTypeListId(origin.types) : - "#" + origin.type.id; - var id = typeKey + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + "#" + origin.type.id + "|" + getTypeListId(types); // origin type id alone is insufficient, as `keyof x` may resolve to multiple WIP values while `x` is still resolving + var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { type = createUnionType(types, aliasSymbol, aliasTypeArguments, origin); @@ -55847,7 +57409,7 @@ var ts; // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); }); if (index < 0) { return false; } @@ -55856,7 +57418,7 @@ var ts; // the unionTypes array. while (i < types.length) { var t = types[i]; - if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) { + if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -55885,14 +57447,14 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */); + types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */); return true; } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { var result = createType(2097152 /* Intersection */); result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */); result.types = types; - result.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. + result.aliasSymbol = aliasSymbol; result.aliasTypeArguments = aliasTypeArguments; return result; } @@ -55953,7 +57515,7 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } - var id = getTypeListId(typeSet) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeSet) + getAliasId(aliasSymbol, aliasTypeArguments); var result = intersectionTypes.get(id); if (!result) { if (includes & 1048576 /* Union */) { @@ -55996,7 +57558,7 @@ var ts; function checkCrossProductUnion(types) { var size = getCrossProductUnionSize(types); if (size >= 100000) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); return false; } @@ -56046,11 +57608,17 @@ var ts; type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } + function instantiateTypeAsMappedNameType(nameType, type, t) { + return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); + } function getIndexTypeForMappedType(type, noIndexSignatures) { var constraint = filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); }); var nameType = type.declaration.nameType && getTypeFromTypeNode(type.declaration.nameType); + // If the constraint is exclusively string/number/never type(s), we need to pull the property names from the modified type and run them through the `nameType` mapper as well + // since they won't appear in the constraint, due to subtype reducing with the string/number index types + var properties = nameType && everyType(constraint, function (t) { return !!(t.flags & (4 /* String */ | 8 /* Number */ | 131072 /* Never */)); }) && getPropertiesOfType(getApparentType(getModifiersTypeFromMappedType(type))); return nameType ? - mapType(constraint, function (t) { return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); }) : + getUnionType([mapType(constraint, function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); }), mapType(getUnionType(ts.map(properties || ts.emptyArray, function (p) { return getLiteralTypeFromProperty(p, 8576 /* StringOrNumberLiteralOrUnique */); })), function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); })]) : constraint; } // Ordinarily we reduce a keyof M, where M is a mapped type { [P in K as N

]: X }, to simply N. This however presumes @@ -56080,13 +57648,13 @@ var ts; function getLiteralTypeFromProperty(prop, include) { if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { var type = getSymbolLinks(getLateBoundSymbol(prop)).nameType; - if (!type && !ts.isKnownSymbol(prop)) { + if (!type) { if (prop.escapedName === "default" /* Default */) { type = getLiteralType("default"); } else { var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); - type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + type = name && getLiteralTypeFromPropertyName(name) || (!ts.isKnownSymbol(prop) ? getLiteralType(ts.symbolName(prop)) : undefined); } } if (type && type.flags & include) { @@ -56186,7 +57754,6 @@ var ts; var type = templateLiteralTypes.get(id); if (!type) { templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes)); - type.regularType = type; } return type; function addSpans(texts, types) { @@ -56218,10 +57785,8 @@ var ts; return type.flags & 128 /* StringLiteral */ ? type.value : type.flags & 256 /* NumberLiteral */ ? "" + type.value : type.flags & 2048 /* BigIntLiteral */ ? ts.pseudoBigIntToString(type.value) : - type.flags & 512 /* BooleanLiteral */ ? type.intrinsicName : - type.flags & 65536 /* Null */ ? "null" : - type.flags & 32768 /* Undefined */ ? "undefined" : - undefined; + type.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) ? type.intrinsicName : + undefined; } function createTemplateLiteralType(texts, types) { var type = createType(134217728 /* TemplateLiteral */); @@ -56280,7 +57845,7 @@ var ts; if (noImplicitAny) { return false; // Flag is meaningless under `noImplicitAny` mode } - if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + if (ts.getObjectFlags(type) & 8192 /* JSLiteral */) { return true; } if (type.flags & 1048576 /* Union */) { @@ -56290,20 +57855,18 @@ var ts; return ts.some(type.types, isJSLiteralType); } if (type.flags & 465829888 /* Instantiable */) { - return isJSLiteralType(getResolvedBaseConstraint(type)); + var constraint = getResolvedBaseConstraint(type); + return constraint !== type && isJSLiteralType(constraint); } return false; } function getPropertyNameFromIndex(indexType, accessNode) { - var accessExpression = accessNode && accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode : undefined; return isTypeUsableAsPropertyName(indexType) ? getPropertyNameFromType(indexType) : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : - accessNode && ts.isPropertyName(accessNode) ? - // late bound names are handled in the first branch, so here we only need to handle normal names - ts.getPropertyNameForPropertyNameNode(accessNode) : - undefined; + accessNode && ts.isPropertyName(accessNode) ? + // late bound names are handled in the first branch, so here we only need to handle normal names + ts.getPropertyNameForPropertyNameNode(accessNode) : + undefined; } function isUncalledFunctionReference(node, symbol) { if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { @@ -56317,17 +57880,17 @@ var ts; } function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, suppressNoImplicitAnyError, accessNode, accessFlags, noUncheckedIndexedAccessCandidate, reportDeprecated) { var _a; - var accessExpression = accessNode && accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode : undefined; + var accessExpression = accessNode && accessNode.kind === 203 /* ElementAccessExpression */ ? accessNode : undefined; var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode); if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { - if (reportDeprecated && accessNode && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) { + if (reportDeprecated && accessNode && prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) { var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); - errorOrSuggestion(/* isError */ false, deprecatedNode, ts.Diagnostics._0_is_deprecated, propName); + addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName); } if (accessExpression) { - markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 107 /* ThisKeyword */); + markPropertyAsReferenced(prop, accessExpression, isSelfTypeAccess(accessExpression.expression, objectType.symbol)); if (isAssignmentToReadonlyEntity(accessExpression, prop, ts.getAssignmentTargetKind(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); return undefined; @@ -56477,13 +58040,13 @@ var ts; } } function getIndexNodeForAccessExpression(accessNode) { - return accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode.argumentExpression : - accessNode.kind === 189 /* IndexedAccessType */ ? accessNode.indexType : - accessNode.kind === 158 /* ComputedPropertyName */ ? accessNode.expression : + return accessNode.kind === 203 /* ElementAccessExpression */ ? accessNode.argumentExpression : + accessNode.kind === 190 /* IndexedAccessType */ ? accessNode.indexType : + accessNode.kind === 159 /* ComputedPropertyName */ ? accessNode.expression : accessNode; } function isPatternLiteralPlaceholderType(type) { - return templateConstraintType.types.indexOf(type) !== -1 || !!(type.flags & 1 /* Any */); + return !!(type.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 64 /* BigInt */)); } function isPatternLiteralType(type) { return !!(type.flags & 134217728 /* TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType); @@ -56496,6 +58059,13 @@ var ts; } return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) { + type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ | + (isGenericObjectType(type.substitute) || isGenericObjectType(type.baseType) ? 8388608 /* IsGenericObjectType */ : 0); + } + return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); + } return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type) || isGenericTupleType(type); } function isGenericIndexType(type) { @@ -56506,6 +58076,13 @@ var ts; } return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) { + type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ | + (isGenericIndexType(type.substitute) || isGenericIndexType(type.baseType) ? 33554432 /* IsGenericIndexType */ : 0); + } + return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); + } return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) && !isPatternLiteralType(type); } function isThisTypeParameter(type) { @@ -56581,6 +58158,12 @@ var ts; } return type[cache] = type; } + function isConditionalTypeAlwaysTrueDisregardingInferTypes(type) { + var extendsInferParamMapper = type.root.inferTypeParameters && createTypeMapper(type.root.inferTypeParameters, ts.map(type.root.inferTypeParameters, function () { return wildcardType; })); + var checkType = type.checkType; + var extendsType = type.extendsType; + return isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(instantiateType(extendsType, extendsInferParamMapper))); + } function getSimplifiedConditionalType(type, writing) { var checkType = type.checkType; var extendsType = type.extendsType; @@ -56651,14 +58234,14 @@ var ts; // for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved // eagerly using the constraint type of 'this' at the given location. - if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 189 /* IndexedAccessType */ ? + if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 190 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, objectType.target.fixedLength) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, objectType.target.fixedLength)))) { if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; } // Defer the operation by creating an indexed access type. - var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + getAliasId(aliasSymbol, aliasTypeArguments); var type = indexedAccessTypes.get(id); if (!type) { indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined)); @@ -56734,16 +58317,32 @@ var ts; } return type; } - function getConditionalType(root, mapper) { + function isTypicalNondistributiveConditional(root) { + return !root.isDistributive + && root.node.checkType.kind === 180 /* TupleType */ + && ts.length(root.node.checkType.elements) === 1 + && root.node.extendsType.kind === 180 /* TupleType */ + && ts.length(root.node.extendsType.elements) === 1; + } + /** + * We syntactually check for common nondistributive conditional shapes and unwrap them into + * the intended comparison - we do this so we can check if the unwrapped types are generic or + * not and appropriately defer condition calculation + */ + function unwrapNondistributiveConditionalTuple(root, type) { + return isTypicalNondistributiveConditional(root) && isTupleType(type) ? getTypeArguments(type)[0] : type; + } + function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { var result; var extraTypes; // We loop here for an immediately nested conditional type in the false position, effectively treating // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { - var checkType = instantiateType(root.checkType, mapper); + var isUnwrapped = isTypicalNondistributiveConditional(root); + var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); - var extendsType = instantiateType(root.extendsType, mapper); + var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } @@ -56754,21 +58353,24 @@ var ts; // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. - inferTypes(context.inferences, checkType, extendsType, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(context.inferences, checkType, extendsType, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); } - combinedMapper = mergeTypeMappers(mapper, context.mapper); + // It's possible for 'infer T' type paramteters to be given uninstantiated constraints when the + // those type parameters are used in type references (see getInferredTypeParameterConstraint). For + // that reason we need context.mapper to be first in the combined mapper. See #42636 for examples. + combinedMapper = mapper ? combineTypeMappers(context.mapper, mapper) : context.mapper; } // Instantiate the extends type including inferences for 'infer T' type parameters - var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + var inferredExtendsType = combinedMapper ? instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), combinedMapper) : extendsType; // We attempt to resolve the conditional type only when the check and extends types are non-generic if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) { // Return falseType for a definitely false extends check. We check an instantiations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instantiations will be and we can just return the false branch type. - if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { + if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && ((checkType.flags & 1 /* Any */ && !isUnwrapped) || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { // Return union of trueType and falseType for 'any' since it matches anything - if (checkType.flags & 1 /* Any */) { + if (checkType.flags & 1 /* Any */ && !isUnwrapped) { (extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper)); } // If falseType is an immediately nested conditional type that isn't distributive or has an @@ -56797,12 +58399,12 @@ var ts; // Return a deferred type for a check that is neither definitely true nor definitely false result = createType(16777216 /* Conditional */); result.root = root; - result.checkType = checkType; - result.extendsType = extendsType; + result.checkType = instantiateType(root.checkType, mapper); + result.extendsType = instantiateType(root.extendsType, mapper); result.mapper = mapper; result.combinedMapper = combinedMapper; - result.aliasSymbol = root.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 + result.aliasSymbol = aliasSymbol || root.aliasSymbol; + result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 break; } return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result; @@ -57008,7 +58610,7 @@ var ts; } } var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return spread; } } @@ -57114,14 +58716,15 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */ | 4194304 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ function isSpreadableProperty(prop) { - return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) && + var _a; + return !ts.some(prop.declarations, ts.isPrivateIdentifierClassElementDeclaration) && (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || - !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); })); + !((_a = prop.declarations) === null || _a === void 0 ? void 0 : _a.some(function (decl) { return ts.isClassLike(decl.parent); }))); } function getSpreadSymbol(prop, readonly) { var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); @@ -57146,11 +58749,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 134220672 /* FreshableLiteral */) { + if (type.flags & 2944 /* Literal */) { if (!type.freshType) { - var freshType = type.flags & 134217728 /* TemplateLiteral */ ? - createTemplateLiteralType(type.texts, type.types) : - createLiteralType(type.flags, type.value, type.symbol); + var freshType = createLiteralType(type.flags, type.value, type.symbol); freshType.regularType = type; freshType.freshType = freshType; type.freshType = freshType; @@ -57160,12 +58761,12 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 134220672 /* FreshableLiteral */ ? type.regularType : + return type.flags & 2944 /* Literal */ ? type.regularType : type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = mapType(type, getRegularTypeOfLiteralType))) : type; } function isFreshLiteralType(type) { - return !!(type.flags & 134220672 /* FreshableLiteral */) && type.freshType === type; + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -57211,7 +58812,7 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 253 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 254 /* InterfaceDeclaration */)) { if (!ts.hasSyntacticModifier(container, 32 /* Static */) && (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; @@ -57246,17 +58847,17 @@ var ts; } function getArrayElementTypeNode(node) { switch (node.kind) { - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return getArrayElementTypeNode(node.type); - case 179 /* TupleType */: + case 180 /* TupleType */: if (node.elements.length === 1) { node = node.elements[0]; - if (node.kind === 181 /* RestType */ || node.kind === 192 /* NamedTupleMember */ && node.dotDotDotToken) { + if (node.kind === 182 /* RestType */ || node.kind === 193 /* NamedTupleMember */ && node.dotDotDotToken) { return getArrayElementTypeNode(node.type); } } break; - case 178 /* ArrayType */: + case 179 /* ArrayType */: return node.elementType; } return undefined; @@ -57274,8 +58875,8 @@ var ts; function getTypeFromTypeNodeWorker(node) { switch (node.kind) { case 128 /* AnyKeyword */: - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: return anyType; case 152 /* UnknownKeyword */: return unknownType; @@ -57302,70 +58903,70 @@ var ts; return node.flags & 131072 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType; case 136 /* IntrinsicKeyword */: return intrinsicMarkerType; - case 187 /* ThisType */: + case 188 /* ThisType */: case 107 /* ThisKeyword */: // TODO(rbuckton): `ThisKeyword` is no longer a `TypeNode`, but we defensively allow it here because of incorrect casts in the Language Service and because of `isPartOfTypeNode`. return getTypeFromThisTypeNode(node); - case 191 /* LiteralType */: + case 192 /* LiteralType */: return getTypeFromLiteralTypeNode(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return getTypeFromTypeReference(node); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return node.assertsModifier ? voidType : booleanType; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 178 /* ArrayType */: - case 179 /* TupleType */: + case 179 /* ArrayType */: + case 180 /* TupleType */: return getTypeFromArrayOrTupleTypeNode(node); - case 180 /* OptionalType */: + case 181 /* OptionalType */: return getTypeFromOptionalTypeNode(node); - case 182 /* UnionType */: + case 183 /* UnionType */: return getTypeFromUnionTypeNode(node); - case 183 /* IntersectionType */: + case 184 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 305 /* JSDocNullableType */: + case 306 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 307 /* JSDocOptionalType */: + case 308 /* JSDocOptionalType */: return addOptionality(getTypeFromTypeNode(node.type)); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return getTypeFromNamedTupleTypeNode(node); - case 186 /* ParenthesizedType */: - case 306 /* JSDocNonNullableType */: - case 301 /* JSDocTypeExpression */: + case 187 /* ParenthesizedType */: + case 307 /* JSDocNonNullableType */: + case 302 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 181 /* RestType */: + case 182 /* RestType */: return getTypeFromRestTypeNode(node); - case 309 /* JSDocVariadicType */: + case 310 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 308 /* JSDocFunctionType */: - case 313 /* JSDocSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 309 /* JSDocFunctionType */: + case 315 /* JSDocSignature */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return getTypeFromIndexedAccessTypeNode(node); - case 190 /* MappedType */: + case 191 /* MappedType */: return getTypeFromMappedTypeNode(node); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return getTypeFromConditionalTypeNode(node); - case 185 /* InferType */: + case 186 /* InferType */: return getTypeFromInferTypeNode(node); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: return getTypeFromTemplateTypeNode(node); - case 195 /* ImportType */: + case 196 /* ImportType */: return getTypeFromImportTypeNode(node); // This function assumes that an identifier, qualified name, or property access expression is a type expression // Callers should first ensure this by calling `isPartOfTypeNode` // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s. case 78 /* Identifier */: - case 157 /* QualifiedName */: - case 201 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: var symbol = getSymbolAtLocation(node); return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: @@ -57518,7 +59119,7 @@ var ts; } return result; } - function getObjectTypeInstantiation(type, mapper) { + function getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { var declaration = type.objectFlags & 4 /* Reference */ ? type.node : type.symbol.declarations[0]; var links = getNodeLinks(declaration); var target = type.objectFlags & 4 /* Reference */ ? links.resolvedType : @@ -57535,8 +59136,9 @@ var ts; outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } typeParameters = outerTypeParameters || ts.emptyArray; - typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? - ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration); }) : + var allDeclarations_1 = type.objectFlags & 4 /* Reference */ ? [declaration] : type.symbol.declarations; + typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 8192 /* Method */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? + ts.filter(typeParameters, function (tp) { return ts.some(allDeclarations_1, function (d) { return isTypeParameterPossiblyReferenced(tp, d); }); }) : typeParameters; links.outerTypeParameters = typeParameters; } @@ -57546,17 +59148,19 @@ var ts; // instantiation cache key from the type IDs of the type arguments. var combinedMapper_1 = combineTypeMappers(type.mapper, mapper); var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); }); - var id = getTypeListId(typeArguments); + var newAliasSymbol = aliasSymbol || type.aliasSymbol; + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + var id = getTypeListId(typeArguments) + getAliasId(newAliasSymbol, newAliasTypeArguments); if (!target.instantiations) { target.instantiations = new ts.Map(); - target.instantiations.set(getTypeListId(typeParameters), target); + target.instantiations.set(getTypeListId(typeParameters) + getAliasId(target.aliasSymbol, target.aliasTypeArguments), target); } var result = target.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(typeParameters, typeArguments); - result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper) : - target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) : - instantiateAnonymousType(target, newMapper); + result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) : + target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) : + instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments); target.instantiations.set(id, result); } return result; @@ -57564,9 +59168,9 @@ var ts; return type; } function maybeTypeParameterReference(node) { - return !(node.kind === 157 /* QualifiedName */ || - node.parent.kind === 173 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName || - node.parent.kind === 195 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier); + return !(node.kind === 158 /* QualifiedName */ || + node.parent.kind === 174 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName || + node.parent.kind === 196 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier); } function isTypeParameterPossiblyReferenced(tp, node) { // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks @@ -57575,22 +59179,25 @@ var ts; if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container = tp.symbol.declarations[0].parent; for (var n = node; n !== container; n = n.parent) { - if (!n || n.kind === 230 /* Block */ || n.kind === 184 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) { + if (!n || n.kind === 231 /* Block */ || n.kind === 185 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) { return true; } } - return !!ts.forEachChild(node, containsReference); + return containsReference(node); } return true; function containsReference(node) { switch (node.kind) { - case 187 /* ThisType */: + case 188 /* ThisType */: return !!tp.isThisType; case 78 /* Identifier */: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return true; + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + return (!node.type && !!node.body) || !!ts.forEachChild(node, containsReference); } return !!ts.forEachChild(node, containsReference); } @@ -57605,7 +59212,7 @@ var ts; } return undefined; } - function instantiateMappedType(type, mapper) { + function instantiateMappedType(type, mapper, aliasSymbol, aliasTypeArguments) { // 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. @@ -57620,7 +59227,7 @@ var ts; if (typeVariable) { var mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapType(getReducedType(mappedTypeVariable), function (t) { + return mapTypeWithAlias(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) { if (!type.declaration.nameType) { if (isArrayType(t)) { @@ -57636,11 +59243,11 @@ var ts; return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper)); } return t; - }); + }, aliasSymbol, aliasTypeArguments); } } // If the constraint type of the instantiation is the wildcard type, return the wildcard type. - return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper); + return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments); } function getModifiedReadonlyState(state, modifiers) { return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state; @@ -57687,7 +59294,7 @@ var ts; strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; } - function instantiateAnonymousType(type, mapper) { + function instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; @@ -57700,29 +59307,29 @@ var ts; } result.target = type; result.mapper = mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + result.aliasSymbol = aliasSymbol || type.aliasSymbol; + result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); return result; } - function getConditionalTypeInstantiation(type, mapper) { + function getConditionalTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { var root = type.root; if (root.outerTypeParameters) { // We are instantiating a conditional type that has one or more type parameters in scope. Apply the // mapper to the type parameters to produce the effective list of type arguments, and compute the // instantiation cache key from the type IDs of the type arguments. var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); }); - var id = getTypeListId(typeArguments); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var result = root.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); - result = instantiateConditionalType(root, newMapper); + result = instantiateConditionalType(root, newMapper, aliasSymbol, aliasTypeArguments); root.instantiations.set(id, result); } return result; } return type; } - function instantiateConditionalType(root, mapper) { + function instantiateConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { // Check if we have a conditional type where the check type is a naked type parameter. If so, // the conditional type is distributive over union types and when T is instantiated to a union // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y). @@ -57730,31 +59337,34 @@ var ts; var checkType_1 = root.checkType; var instantiatedType = getMappedType(checkType_1, mapper); if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) { - return mapType(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); }); + return mapTypeWithAlias(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); }, aliasSymbol, aliasTypeArguments); } } - return getConditionalType(root, mapper); + return getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments); } function instantiateType(type, mapper) { - if (!(type && mapper && couldContainTypeVariables(type))) { + return type && mapper ? instantiateTypeWithAlias(type, mapper, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined) : type; + } + function instantiateTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) { + if (!couldContainTypeVariables(type)) { return type; } if (instantiationDepth === 50 || instantiationCount >= 5000000) { // 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. - ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); return errorType; } totalInstantiationCount++; instantiationCount++; instantiationDepth++; - var result = instantiateTypeWorker(type, mapper); + var result = instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments); instantiationDepth--; return result; } - function instantiateTypeWorker(type, mapper) { + function instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments) { var flags = type.flags; if (flags & 262144 /* TypeParameter */) { return getMappedType(type, mapper); @@ -57762,12 +59372,15 @@ var ts; if (flags & 524288 /* Object */) { var objectFlags = type.objectFlags; if (objectFlags & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */)) { - if (objectFlags & 4 /* Reference */ && !(type.node)) { + if (objectFlags & 4 /* Reference */ && !type.node) { var resolvedTypeArguments = type.resolvedTypeArguments; var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type; } - return getObjectTypeInstantiation(type, mapper); + if (objectFlags & 1024 /* ReverseMapped */) { + return instantiateReverseMappedType(type, mapper); + } + return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments); } return type; } @@ -57775,10 +59388,14 @@ var ts; var origin = type.flags & 1048576 /* Union */ ? type.origin : undefined; var types = origin && origin.flags & 3145728 /* UnionOrIntersection */ ? origin.types : type.types; var newTypes = instantiateTypes(types, mapper); - return newTypes === types ? type : - flags & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ? - getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : - getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + if (newTypes === types && aliasSymbol === type.aliasSymbol) { + return type; + } + var newAliasSymbol = aliasSymbol || type.aliasSymbol; + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + return flags & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ? + getIntersectionType(newTypes, newAliasSymbol, newAliasTypeArguments) : + getUnionType(newTypes, 1 /* Literal */, newAliasSymbol, newAliasTypeArguments); } if (flags & 4194304 /* Index */) { return getIndexType(instantiateType(type.type, mapper)); @@ -57790,10 +59407,12 @@ var ts; return getStringMappingType(type.symbol, instantiateType(type.type, mapper)); } if (flags & 8388608 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + var newAliasSymbol = aliasSymbol || type.aliasSymbol; + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, newAliasSymbol, newAliasTypeArguments); } if (flags & 16777216 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper), aliasSymbol, aliasTypeArguments); } if (flags & 33554432 /* Substitution */) { var maybeVariable = instantiateType(type.baseType, mapper); @@ -57810,6 +59429,21 @@ var ts; } return type; } + function instantiateReverseMappedType(type, mapper) { + var innerMappedType = instantiateType(type.mappedType, mapper); + if (!(ts.getObjectFlags(innerMappedType) & 32 /* Mapped */)) { + return type; + } + var innerIndexType = instantiateType(type.constraintType, mapper); + if (!(innerIndexType.flags & 4194304 /* Index */)) { + return type; + } + var instantiated = inferTypeForHomomorphicMappedType(instantiateType(type.source, mapper), innerMappedType, innerIndexType); + if (instantiated) { + return instantiated; + } + return type; // Nested invocation of `inferTypeForHomomorphicMappedType` or the `source` instantiated into something unmappable + } function getPermissiveInstantiation(type) { return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); @@ -57836,35 +59470,35 @@ var 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) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 251 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type return isContextSensitiveFunctionLikeDeclaration(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return ts.some(node.properties, isContextSensitive); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return ts.some(node.elements, isContextSensitive); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return (node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */) && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isContextSensitive(node.expression); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); - case 280 /* JsxAttribute */: { + case 281 /* JsxAttribute */: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. var initializer = node.initializer; return !!initializer && isContextSensitive(initializer); } - case 283 /* JsxExpression */: { + case 284 /* JsxExpression */: { // It is possible to that node.expression is undefined (e.g

) var expression = node.expression; return !!expression && isContextSensitive(expression); @@ -57883,7 +59517,7 @@ var ts; if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 209 /* ArrowFunction */) { + if (node.kind !== 210 /* ArrowFunction */) { // If the first parameter is not an explicit 'this' parameter, then the function has // an implicit 'this' parameter which is subject to contextual typing. var parameter = ts.firstOrUndefined(node.parameters); @@ -57896,7 +59530,7 @@ var ts; } function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 230 /* Block */ && isContextSensitive(node.body); + return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 231 /* Block */ && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -57999,23 +59633,23 @@ var ts; return true; } switch (node.kind) { - case 283 /* JsxExpression */: - case 207 /* ParenthesizedExpression */: + case 284 /* JsxExpression */: + case 208 /* ParenthesizedExpression */: return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (node.operatorToken.kind) { case 62 /* EqualsToken */: case 27 /* CommaToken */: return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); } break; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer); } return false; @@ -58215,7 +59849,7 @@ var ts; } function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) { switch (child.kind) { - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: // child is of the type of the expression return { errorNode: child, innerExpression: child.expression, nameType: nameType }; case 11 /* JsxText */: @@ -58224,9 +59858,9 @@ var ts; } // child is a string return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() }; - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: // child is of type JSX.Element return { errorNode: child, innerExpression: child, nameType: nameType }; default: @@ -58374,11 +60008,11 @@ var ts; } _b = prop.kind; switch (_b) { - case 168 /* SetAccessor */: return [3 /*break*/, 2]; - case 167 /* GetAccessor */: return [3 /*break*/, 2]; - case 165 /* MethodDeclaration */: return [3 /*break*/, 2]; - case 289 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; - case 288 /* PropertyAssignment */: return [3 /*break*/, 4]; + case 169 /* SetAccessor */: return [3 /*break*/, 2]; + case 168 /* GetAccessor */: return [3 /*break*/, 2]; + case 166 /* MethodDeclaration */: return [3 /*break*/, 2]; + case 290 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 289 /* PropertyAssignment */: return [3 /*break*/, 4]; } return [3 /*break*/, 6]; case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; @@ -58455,8 +60089,8 @@ var ts; return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; - var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 165 /* MethodDeclaration */ && - kind !== 164 /* MethodSignature */ && kind !== 166 /* Constructor */; + var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 166 /* MethodDeclaration */ && + kind !== 165 /* MethodSignature */ && kind !== 167 /* Constructor */; var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { @@ -58689,7 +60323,7 @@ var ts; // Type number or any numeric literal type is assignable to any numeric enum type or any // numeric enum literal type. This rule exists for backwards compatibility reasons because // bit-flag enum types sometimes look like literal enum types with numeric literal values. - if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) + if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || relation === assignableRelation && t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) return true; } return false; @@ -58726,7 +60360,7 @@ var ts; return false; } function isIgnoredJsxProperty(source, sourceProp) { - return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); + return ts.getObjectFlags(source) & 2048 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { while (true) { @@ -58736,6 +60370,7 @@ var ts; type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute : type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : type; + t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) break; type = t; @@ -58773,7 +60408,7 @@ var ts; reportIncompatibleStack(); } if (overflow) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); @@ -58909,6 +60544,14 @@ var ts; } break; } + case ts.Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target.code: { + secondaryRootErrors.unshift([ts.Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target, args[0], args[1]]); + break; + } + case ts.Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target.code: { + secondaryRootErrors.unshift([ts.Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target, args[0], args[1], args[2]]); + break; + } default: return ts.Debug.fail("Unhandled Diagnostic: " + msg.code); } @@ -58969,6 +60612,7 @@ var ts; reportError(ts.Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2, needsOriginalSource ? sourceType : generalizedSourceType, targetType, typeToString(constraint)); } else { + errorInfo = undefined; reportError(ts.Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, generalizedSourceType); } } @@ -59044,7 +60688,7 @@ var ts; if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { return -1 /* True */; } - reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */)); + reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 2048 /* JsxAttributes */)); return 0 /* False */; } // Normalize the source and target types: Turn fresh literal types into regular literal types, @@ -59079,16 +60723,16 @@ var ts; target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) { var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */); if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) { - if (source === nullStrippedTarget) - return -1 /* True */; - target = nullStrippedTarget; + target = getNormalizedType(nullStrippedTarget, /*writing*/ true); } + if (source === nullStrippedTarget) + return -1 /* True */; } if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); + var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384 /* FreshLiteral */); if (isPerformingExcessPropertyChecks) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -59173,7 +60817,7 @@ var ts; // We suppress recursive intersection property checks because they can generate lots of work when relating // recursive intersections that are structurally similar but not exactly identical. See #37854. if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) { + isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 524288 /* NonInferrableType */); }))) { inPropertyCheck = true; result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */); inPropertyCheck = false; @@ -59182,8 +60826,10 @@ var ts; return result; function reportErrorResults(source, target, result, isComparingJsxAttributes) { if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; + var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); + var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); + source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; + target = (originalTarget.aliasSymbol || targetHasBase) ? originalTarget : target; var maybeSuppress = overrideNextErrorInfo > 0; if (maybeSuppress) { overrideNextErrorInfo--; @@ -59224,13 +60870,13 @@ var ts; } } function traceUnionsOrIntersectionsTooLarge(source, target) { - if (!ts.tracing.isTracing()) { + if (!ts.tracing) { return; } if ((source.flags & 3145728 /* UnionOrIntersection */) && (target.flags & 3145728 /* UnionOrIntersection */)) { var sourceUnionOrIntersection = source; var targetUnionOrIntersection = target; - if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 262144 /* PrimitiveUnion */) { + if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 65536 /* PrimitiveUnion */) { // There's a fast path for comparing primitive unions return; } @@ -59255,11 +60901,11 @@ var ts; } traceUnionsOrIntersectionsTooLarge(source, target); if (flags & 3145728 /* UnionOrIntersection */) { - var result_6 = eachTypeRelatedToSomeType(source, target); - if (result_6) { - result_6 &= eachTypeRelatedToSomeType(target, source); + var result_7 = eachTypeRelatedToSomeType(source, target); + if (result_7) { + result_7 &= eachTypeRelatedToSomeType(target, source); } - return result_6; + return result_7; } return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */); } @@ -59273,10 +60919,11 @@ var ts; return getUnionType(ts.reduceLeft(types, appendPropType, /*initial*/ undefined) || ts.emptyArray); } function hasExcessProperties(source, target, reportErrors) { - if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + var _a; + if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 8192 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; @@ -59319,7 +60966,7 @@ var ts; } else { // use the property's value declaration if the property is assigned inside the literal itself - var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + var objectLiteralDeclaration_1 = ((_a = source.symbol) === null || _a === void 0 ? void 0 : _a.declarations) && ts.firstOrUndefined(source.symbol.declarations); var suggestion = void 0; if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) { var propDeclaration = prop.valueDeclaration; @@ -59348,11 +60995,11 @@ var ts; } } }; - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - var state_4 = _loop_16(prop); - if (typeof state_4 === "object") - return state_4.value; + for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { + var prop = _b[_i]; + var state_5 = _loop_16(prop); + if (typeof state_5 === "object") + return state_5.value; } return false; } @@ -59374,8 +61021,17 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) { - return -1 /* True */; + if (target.flags & 1048576 /* Union */) { + if (containsType(targetTypes, source)) { + return -1 /* True */; + } + var match = getMatchingUnionConstituentForType(target, source); + if (match) { + var related = isRelatedTo(source, match, /*reportErrors*/ false); + if (related) { + return related; + } + } } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { var type = targetTypes_1[_i]; @@ -59549,9 +61205,16 @@ var ts; targetStack = []; } else { + // generate a key where all type parameter id positions are replaced with unconstrained type parameter ids + // this isn't perfect - nested type references passed as type arguments will muck up the indexes and thus + // prevent finding matches- but it should hit up the common cases + var broadestEquivalentId = id.split(",").map(function (i) { return i.replace(/-\d+/g, function (_match, offset) { + var index = ts.length(id.slice(0, offset).match(/[-=]/g) || undefined); + return "=" + index; + }); }).join(","); for (var i = 0; i < maybeCount; i++) { // If source and target are already being compared, consider them related with assumptions - if (id === maybeKeys[i]) { + if (id === maybeKeys[i] || broadestEquivalentId === maybeKeys[i]) { return 3 /* Maybe */; } } @@ -59581,7 +61244,7 @@ var ts; }; } if (expandingFlags === 3 /* Both */) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { sourceId: source.id, sourceIdStack: sourceStack.map(function (t) { return t.id; }), targetId: target.id, @@ -59616,9 +61279,9 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { - ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) { @@ -59640,8 +61303,21 @@ var ts; if (target.flags & 2097152 /* Intersection */) { return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */); } - // Source is an intersection. Check to see if any constituents of the intersection are immediately related - // to the target. + // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the + // constraints of all non-primitive types in the source into a new intersection. We do this because the + // intersection may further constrain the constraints of the non-primitive types. For example, given a type + // parameter 'T extends 1 | 2', the intersection 'T & 1' should be reduced to '1' such that it doesn't + // appear to be comparable to '2'. + if (relation === comparableRelation && target.flags & 131068 /* Primitive */) { + var constraints = ts.sameMap(source.types, function (t) { return t.flags & 131068 /* Primitive */ ? t : getBaseConstraintOfType(t) || unknownType; }); + if (constraints !== source.types) { + source = getIntersectionType(constraints); + if (!(source.flags & 2097152 /* Intersection */)) { + return isRelatedTo(source, target, /*reportErrors*/ false); + } + } + } + // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually // useful and leads to some confusing error messages. Instead it is better to let the below checks @@ -59661,21 +61337,21 @@ var ts; if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_7 = 0 /* False */; + var result_8 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_7 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_8; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_7 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_8; } } } @@ -59755,6 +61431,20 @@ var ts; } } else if (target.flags & 8388608 /* IndexedAccess */) { + if (source.flags & 8388608 /* IndexedAccess */) { + // Relate components directly before falling back to constraint relationships + // A type S[K] is related to a type T[J] if S is related to T and K is related to J. + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + if (reportErrors) { + originalErrorInfo = errorInfo; + } + } // A type S is related to a type T[K] if S is related to C, where C is the base // constraint of T[K] for writing. if (relation === assignableRelation || relation === comparableRelation) { @@ -59765,11 +61455,24 @@ var ts; if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) { var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0); var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, target.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, accessFlags); - if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) { - return result; + if (constraint) { + if (reportErrors && originalErrorInfo) { + // create a new chain for the constraint error + resetErrorInfo(saveErrorInfo); + } + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + // prefer the shorter chain of the constraint comparison chain, and the direct comparison chain + if (reportErrors && originalErrorInfo && errorInfo) { + errorInfo = countMessageChainBreadth([originalErrorInfo]) <= countMessageChainBreadth([errorInfo]) ? originalErrorInfo : errorInfo; + } } } } + if (reportErrors) { + originalErrorInfo = undefined; + } } else if (isGenericMappedType(target) && !target.declaration.nameType) { // A source type T is related to a target type { [P in X]: T[P] } @@ -59813,27 +61516,48 @@ var ts; } } } - else if (target.flags & 134217728 /* TemplateLiteral */ && source.flags & 128 /* StringLiteral */) { - if (isPatternLiteralType(target)) { - // match all non-`string` segments - var result_8 = inferLiteralsFromTemplateLiteralType(source, target); - if (result_8 && ts.every(result_8, function (r, i) { return isStringLiteralTypeValueParsableAsType(r, target.types[i]); })) { - return -1 /* True */; - } + else if (target.flags & 16777216 /* Conditional */) { + var c = target; + // Check if the conditional is always true or always false but still deferred for distribution purposes + var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); + var skipFalse = !skipTrue && isConditionalTypeAlwaysTrueDisregardingInferTypes(c); + // Instantiate with a replacement mapper if the conditional is distributive, replacing the check type with a clone of itself, + // this way {x: string | number, y: string | number} -> (T extends T ? { x: T, y: T } : never) appropriately _fails_ when + // T = string | number (since that will end up distributing and producing `{x: string, y: string} | {x: number, y: number}`, + // to which `{x: string | number, y: string | number}` isn't assignable) + var distributionMapper = void 0; + var checkVar = getActualTypeVariable(c.root.checkType); + if (c.root.isDistributive && checkVar.flags & 262144 /* TypeParameter */) { + var newParam = cloneTypeParameter(checkVar); + distributionMapper = prependTypeMapping(checkVar, newParam, c.mapper); + newParam.mapper = distributionMapper; + } + // TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't) + var localResult = void 0; + if (skipTrue || (localResult = isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.trueType), distributionMapper) : getTrueTypeFromConditionalType(c), /*reportErrors*/ false))) { + if (!skipFalse) { + localResult = (localResult || 3 /* Maybe */) & isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.falseType), distributionMapper) : getFalseTypeFromConditionalType(c), /*reportErrors*/ false); + } + } + if (localResult) { + resetErrorInfo(saveErrorInfo); + return localResult; } } - if (source.flags & 8650752 /* TypeVariable */) { - if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { - // A type S[K] is related to a type T[J] if S is related to T and K is related to J. - if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { - result &= isRelatedTo(source.indexType, target.indexType, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } + else if (target.flags & 134217728 /* TemplateLiteral */) { + if (source.flags & 134217728 /* TemplateLiteral */) { + // Report unreliable variance for type variables referenced in template literal type placeholders. + // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. + instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } - else { + var result_9 = inferTypesFromTemplateLiteralType(source, target); + if (result_9 && ts.every(result_9, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { + return -1 /* True */; + } + } + if (source.flags & 8650752 /* TypeVariable */) { + // IndexedAccess comparisons are handled above in the `target.flags & TypeFlage.IndexedAccess` branch + if (!(source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */)) { var constraint = getConstraintOfType(source); if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. @@ -59848,7 +61572,7 @@ var ts; return result; } // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example - else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, intersectionState)) { + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors && !(target.flags & source.flags & 262144 /* TypeParameter */), /*headMessage*/ undefined, intersectionState)) { resetErrorInfo(saveErrorInfo); return result; } @@ -59861,17 +61585,10 @@ var ts; } } else if (source.flags & 134217728 /* TemplateLiteral */) { - if (target.flags & 134217728 /* TemplateLiteral */) { - if (source.texts.length === target.texts.length && - source.types.length === target.types.length && - ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) && - ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 /* Any */ | 4 /* String */)) || !!isRelatedTo(t, target.types[i], /*reportErrors*/ false); })) { - return -1 /* True */; - } - } - else { - var constraint = getBaseConstraintOfType(source); - if (result = isRelatedTo(constraint && constraint !== source ? constraint : stringType, target, reportErrors)) { + if (!(target.flags & 134217728 /* TemplateLiteral */)) { + var baseConstraint = getBaseConstraintOfType(source); + var constraint = baseConstraint && baseConstraint !== source ? baseConstraint : stringType; + if (result = isRelatedTo(constraint, target, reportErrors)) { resetErrorInfo(saveErrorInfo); return result; } @@ -59903,7 +61620,7 @@ var ts; if (sourceParams) { // If the source has infer type parameters, we instantiate them in the context of the target var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo); - inferTypes(ctx.inferences, target.extendsType, sourceExtends, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); sourceExtends = instantiateType(sourceExtends, ctx.mapper); mapper = ctx.mapper; } @@ -59961,7 +61678,7 @@ var ts; return 0 /* False */; } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && - !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { + !(ts.getObjectFlags(source) & 4096 /* MarkerType */ || ts.getObjectFlags(target) & 4096 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. @@ -59989,7 +61706,7 @@ var ts; } // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})` // and not `{} <- fresh({}) <- {[idx: string]: any}` - else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) { + else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 16384 /* FreshLiteral */ && !isEmptyObjectType(source)) { return 0 /* False */; } // Even if relationship doesn't hold for unions, intersections, or generic type references, @@ -60027,14 +61744,19 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_9) { - return result_9; + var result_10 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_10) { + return result_10; } } } } return 0 /* False */; + function countMessageChainBreadth(info) { + if (!info) + return 0; + return ts.reduceLeft(info, function (value, chain) { return value + 1 + countMessageChainBreadth(chain.next); }, 0); + } function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) { if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) { return result; @@ -60096,13 +61818,13 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_10; + var result_11; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + if (result_11 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { - return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_11 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } } @@ -60133,7 +61855,7 @@ var ts; numCombinations *= countTypes(getTypeOfSymbol(sourceProperty)); if (numCombinations > 25) { // We've reached the complexity limit. - ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); return 0 /* False */; } } @@ -60172,8 +61894,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_6 = _loop_18(i); - switch (state_6) { + var state_7 = _loop_18(i); + switch (state_7) { case "continue-outer": continue outer; } } @@ -60186,9 +61908,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_5 = _loop_17(combination); - if (typeof state_5 === "object") - return state_5.value; + var state_6 = _loop_17(combination); + if (typeof state_6 === "object") + return state_6.value; } // Compare the remaining non-discriminant properties of each match. var result = -1 /* True */; @@ -60242,7 +61964,7 @@ var ts; ts.Debug.assertIsDefined(links.deferralParent); ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */); - var result_11 = unionParent ? 0 /* False */ : -1 /* True */; + var result_12 = unionParent ? 0 /* False */ : -1 /* True */; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -60252,7 +61974,7 @@ var ts; // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_11 &= related; + result_12 &= related; } else { if (related) { @@ -60260,17 +61982,17 @@ var ts; } } } - if (unionParent && !result_11 && targetIsOptional) { - result_11 = isRelatedTo(source, undefinedType); + if (unionParent && !result_12 && targetIsOptional) { + result_12 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_11 && reportErrors) { + if (unionParent && !result_12 && reportErrors) { // The easiest way to get the right errors here is to un-defer (which may be costly) // If it turns out this is too costly too often, we can replicate the error handling logic within // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union // type on which to hand discriminable properties, which we are expressly trying to avoid here) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_11; + return result_12; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState); @@ -60601,7 +62323,7 @@ var ts; var targetSignature = ts.first(targetSignatures); result = signatureRelatedTo(sourceSignature, targetSignature, eraseGenerics, reportErrors, incompatibleReporter(sourceSignature, targetSignature)); if (!result && reportErrors && kind === 1 /* Construct */ && (sourceObjectFlags & targetObjectFlags) && - (((_a = targetSignature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 166 /* Constructor */ || ((_b = sourceSignature.declaration) === null || _b === void 0 ? void 0 : _b.kind) === 166 /* Constructor */)) { + (((_a = targetSignature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 167 /* Constructor */ || ((_b = sourceSignature.declaration) === null || _b === void 0 ? void 0 : _b.kind) === 167 /* Constructor */)) { var constructSignatureToString = function (signature) { return signatureToString(signature, /*enclosingDeclaration*/ undefined, 262144 /* WriteArrowStyleSignature */, kind); }; @@ -60709,10 +62431,17 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetType = getIndexTypeOfType(target, kind); - if (!targetType || targetType.flags & 1 /* Any */ && !sourceIsPrimitive) { - // Index signature of type any permits assignment from everything but primitives + if (!targetType) { return -1 /* True */; } + if (targetType.flags & 1 /* Any */ && !sourceIsPrimitive) { + // An index signature of type `any` permits assignment from everything but primitives, + // provided that there is also a `string` index signature of type `any`. + var stringIndexType = kind === 0 /* String */ ? targetType : getIndexTypeOfType(target, 0 /* String */); + if (stringIndexType && stringIndexType.flags & 1 /* Any */) { + return -1 /* True */; + } + } if (isGenericMappedType(source)) { // A generic mapped type { [P in K]: T } is related to a type with an index signature // { [x: string]: U }, and optionally with an index signature { [x: number]: V }, @@ -60867,7 +62596,7 @@ var ts; // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); - result.objectFlags |= 8192 /* MarkerType */; + result.objectFlags |= 4096 /* MarkerType */; return result; } function getAliasVariances(symbol) { @@ -60888,7 +62617,7 @@ var ts; if (typeParameters === void 0) { typeParameters = ts.emptyArray; } var variances = cache.variances; if (!variances) { - ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); // The emptyArray singleton is used to signal a recursive invocation. cache.variances = ts.emptyArray; variances = []; @@ -60927,7 +62656,7 @@ var ts; _loop_19(tp); } cache.variances = variances; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } return variances; } @@ -60955,7 +62684,7 @@ var ts; return !!(ts.getObjectFlags(type) & 4 /* Reference */) && !type.node; } function isTypeReferenceWithGenericArguments(type) { - return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return !!(t.flags & 262144 /* TypeParameter */) || isTypeReferenceWithGenericArguments(t); }); } /** * getTypeReferenceId(A) returns "111=0-12=1" @@ -61041,8 +62770,8 @@ var ts; } // Return true if the given class derives from each of the declaring classes of the protected // constituents of the given property. - function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) { + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p, writing) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons @@ -61060,23 +62789,26 @@ var ts; function isDeeplyNestedType(type, stack, depth) { if (depth >= 5) { var identity_1 = getRecursionIdentity(type); - if (identity_1) { - var count = 0; - for (var i = 0; i < depth; i++) { - if (getRecursionIdentity(stack[i]) === identity_1) { - count++; - if (count >= 5) { - return true; - } + var count = 0; + for (var i = 0; i < depth; i++) { + if (getRecursionIdentity(stack[i]) === identity_1) { + count++; + if (count >= 5) { + return true; } } } } return false; } - // Types with constituents that could circularly reference the type have a recursion identity. The recursion - // identity is some object that is common to instantiations of the type with the same origin. + // The recursion identity of a type is an object identity that is shared among multiple instantiations of the type. + // We track recursion identities in order to identify deeply nested and possibly infinite type instantiations with + // the same origin. For example, when type parameters are in scope in an object type such as { x: T }, all + // instantiations of that type have the same recursion identity. The default recursion identity is the object + // identity of the type, meaning that every type is unique. Generally, types with constituents that could circularly + // reference the type have a recursion identity that differs from the object identity. function getRecursionIdentity(type) { + // Object and array literals are known not to contain recursive references and don't need a recursion identity. if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) { if (ts.getObjectFlags(type) && 4 /* Reference */ && type.node) { // Deferred type references are tracked through their associated AST node. This gives us finer @@ -61094,6 +62826,9 @@ var ts; return type.target; } } + if (type.flags & 262144 /* TypeParameter */) { + return type.symbol; + } if (type.flags & 8388608 /* IndexedAccess */) { // Identity is the leftmost object type in a chain of indexed accesses, eg, in A[P][Q] it is A do { @@ -61105,7 +62840,7 @@ var ts; // The root object represents the origin of the conditional type return type.root; } - return undefined; + return type; } function isPropertyIdenticalTo(sourceProp, targetProp) { return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; @@ -61244,6 +62979,9 @@ var ts; // of those literal types. Otherwise, return the leftmost type for which no type to the // right is a supertype. function getSupertypeOrUnion(types) { + if (types.length === 1) { + return types[0]; + } return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); @@ -61278,9 +63016,32 @@ var ts; // or if it is not the undefined or null type and if it is assignable to ReadonlyArray return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } + function getSingleBaseForNonAugmentingSubtype(type) { + if (!(ts.getObjectFlags(type) & 4 /* Reference */) || !(ts.getObjectFlags(type.target) & 3 /* ClassOrInterface */)) { + return undefined; + } + if (ts.getObjectFlags(type) & 33554432 /* IdenticalBaseTypeCalculated */) { + return ts.getObjectFlags(type) & 67108864 /* IdenticalBaseTypeExists */ ? type.cachedEquivalentBaseType : undefined; + } + type.objectFlags |= 33554432 /* IdenticalBaseTypeCalculated */; + var target = type.target; + var bases = getBaseTypes(target); + if (bases.length !== 1) { + return undefined; + } + if (getMembersOfSymbol(type.symbol).size) { + return undefined; // If the interface has any members, they may subtype members in the base, so we should do a full structural comparison + } + var instantiatedBase = !ts.length(target.typeParameters) ? bases[0] : instantiateType(bases[0], createTypeMapper(target.typeParameters, getTypeArguments(type).slice(0, target.typeParameters.length))); + if (ts.length(getTypeArguments(type)) > ts.length(target.typeParameters)) { + instantiatedBase = getTypeWithThisArgument(instantiatedBase, ts.last(getTypeArguments(type))); + } + type.objectFlags |= 67108864 /* IdenticalBaseTypeExists */; + return type.cachedEquivalentBaseType = instantiatedBase; + } function isEmptyArrayLiteralType(type) { - var elementType = isArrayType(type) ? getTypeArguments(type)[0] : undefined; - return elementType === undefinedWideningType || elementType === implicitNeverType; + var elementType = getElementTypeOfArrayType(type); + return strictNullChecks ? elementType === implicitNeverType : elementType === undefinedWideningType; } function isTupleLikeType(type) { return isTupleType(type) || !!getPropertyOfType(type, "0"); @@ -61304,6 +63065,13 @@ var ts; function isUnitType(type) { return !!(type.flags & 109440 /* Unit */); } + function isUnitLikeType(type) { + return type.flags & 2097152 /* Intersection */ ? ts.some(type.types, isUnitType) : + !!(type.flags & 109440 /* Unit */); + } + function extractUnitType(type) { + return type.flags & 2097152 /* Intersection */ ? ts.find(type.types, isUnitType) || type : type; + } function isLiteralType(type) { return type.flags & 16 /* Boolean */ ? true : type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : @@ -61311,7 +63079,7 @@ var ts; } function getBaseTypeOfLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ ? stringType : + type.flags & 128 /* StringLiteral */ ? stringType : type.flags & 256 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : @@ -61320,7 +63088,7 @@ var ts; } function getWidenedLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : @@ -61454,14 +63222,17 @@ var ts; return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { + // First reduce away any constituents that are assignable to 'undefined' or 'null'. This not only eliminates + // 'undefined' and 'null', but also higher-order types such as a type parameter 'U extends undefined | null' + // that isn't eliminated by a NonNullable instantiation. + var reducedType = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); if (!deferredGlobalNonNullableTypeAlias) { deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; } - // Use NonNullable global type alias if available to improve quick info/declaration emit - if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { - return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); - } - return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior + // If the NonNullable type is available, return an instantiation. Otherwise just return the reduced type. + return deferredGlobalNonNullableTypeAlias !== unknownSymbol ? + getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [reducedType]) : + reducedType; } function getNonNullableType(type) { return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; @@ -61514,7 +63285,7 @@ var ts; function isObjectTypeWithInferableIndex(type) { return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 && - !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */); @@ -61547,7 +63318,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 16384 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -61558,7 +63329,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags; - regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */; + regularNew.objectFlags |= resolved.objectFlags & ~16384 /* FreshLiteral */; type.regularType = regularNew; return regularNew; } @@ -61588,7 +63359,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { var t = _a[_i]; - if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 4194304 /* ContainsSpread */)) { for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { var prop = _c[_b]; names.set(prop.escapedName, prop); @@ -61637,14 +63408,14 @@ var ts; var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); - result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening + result.objectFlags |= (ts.getObjectFlags(type) & (8192 /* JSLiteral */ | 524288 /* NonInferrableType */)); // Retain js literal flag through widening return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, /*context*/ undefined); } function getWidenedTypeWithContext(type, context) { - if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) { + if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) { if (context === undefined && type.widened) { return type.widened; } @@ -61689,7 +63460,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) { if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -61715,7 +63486,7 @@ var ts; for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -61734,12 +63505,12 @@ var ts; } var diagnostic; switch (declaration.kind) { - case 216 /* BinaryExpression */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 217 /* BinaryExpression */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 160 /* Parameter */: + case 161 /* Parameter */: var param = declaration; if (ts.isIdentifier(param.name) && (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && @@ -61754,23 +63525,23 @@ var ts; noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; if (!noImplicitAny) { // Don't issue a suggestion for binding elements since the codefix doesn't yet support them. return; } break; - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: if (noImplicitAny && !declaration.name) { if (wideningKind === 3 /* GeneratorYield */) { error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString); @@ -61784,7 +63555,7 @@ var ts; wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; - case 190 /* MappedType */: + case 191 /* MappedType */: if (noImplicitAny) { error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); } @@ -61795,7 +63566,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -61911,23 +63682,23 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) { - return !!(objectFlags & 134217728 /* CouldContainTypeVariables */); + if (objectFlags & 1048576 /* CouldContainTypeVariablesComputed */) { + return !!(objectFlags & 2097152 /* CouldContainTypeVariables */); } var result = !!(type.flags & 465829888 /* Instantiable */ || type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || - objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) || + objectFlags & (32 /* Mapped */ | 1024 /* ReverseMapped */ | 8388608 /* ObjectRestType */)) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables)); if (type.flags & 3899393 /* ObjectFlagsType */) { - type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0); + type.objectFlags |= 1048576 /* CouldContainTypeVariablesComputed */ | (result ? 2097152 /* CouldContainTypeVariables */ : 0); } return result; } function isNonGenericTopLevelType(type) { if (type.aliasSymbol && !type.aliasTypeArguments) { - var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 254 /* TypeAliasDeclaration */); - return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 297 /* SourceFile */ ? true : n.kind === 256 /* ModuleDeclaration */ ? false : "quit"; })); + var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 255 /* TypeAliasDeclaration */); + return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 298 /* SourceFile */ ? true : n.kind === 257 /* ModuleDeclaration */ ? false : "quit"; })); } return false; } @@ -61980,7 +63751,7 @@ var ts; // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive // arrow function, but is considered partially inferable because property 'a' has an inferable type. function isPartiallyInferableType(type) { - return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) || + return !(ts.getObjectFlags(type) & 524288 /* NonInferrableType */) || isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }) || isTupleType(type) && ts.some(getTypeArguments(type), isPartiallyInferableType); } @@ -62004,14 +63775,18 @@ var ts; } // For all other object types we infer a new object type where the reverse mapping has been // applied to the type of each property. - var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); + var reversed = createObjectType(1024 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + return links.type; } function inferReverseMappedType(sourceType, target, constraint) { var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); @@ -62103,51 +63878,113 @@ var ts; // * it does not contain a numeric seperator (the `BigInt` constructor does not accept a numeric seperator in its input) return success && result === 9 /* BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* ContainsSeparator */); } - function isStringLiteralTypeValueParsableAsType(s, target) { - if (target.flags & 1048576 /* Union */) { - return !!forEachType(target, function (t) { return isStringLiteralTypeValueParsableAsType(s, t); }); - } - switch (target) { - case stringType: return true; - case numberType: return s.value !== "" && isFinite(+(s.value)); - case bigintType: return s.value !== "" && isValidBigIntString(s.value); - // the next 4 should be handled in `getTemplateLiteralType`, as they are all exactly one value, but are here for completeness, just in case - // this function is ever used on types which don't come from template literal holes - case trueType: return s.value === "true"; - case falseType: return s.value === "false"; - case undefinedType: return s.value === "undefined"; - case nullType: return s.value === "null"; - default: return !!(target.flags & 1 /* Any */); - } - } - function inferLiteralsFromTemplateLiteralType(source, target) { - var value = source.value; - var texts = target.texts; - var lastIndex = texts.length - 1; - var startText = texts[0]; - var endText = texts[lastIndex]; - if (!(value.startsWith(startText) && value.slice(startText.length).endsWith(endText))) + function isValidTypeForTemplateLiteralPlaceholder(source, target) { + if (source === target || target.flags & (1 /* Any */ | 4 /* String */)) { + return true; + } + if (source.flags & 128 /* StringLiteral */) { + var value = source.value; + return !!(target.flags & 8 /* Number */ && value !== "" && isFinite(+value) || + target.flags & 64 /* BigInt */ && value !== "" && isValidBigIntString(value) || + target.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) && value === target.intrinsicName); + } + if (source.flags & 134217728 /* TemplateLiteral */) { + var texts = source.texts; + return texts.length === 2 && texts[0] === "" && texts[1] === "" && isTypeAssignableTo(source.types[0], target); + } + return isTypeAssignableTo(source, target); + } + function inferTypesFromTemplateLiteralType(source, target) { + return source.flags & 128 /* StringLiteral */ ? inferFromLiteralPartsToTemplateLiteral([source.value], ts.emptyArray, target) : + source.flags & 134217728 /* TemplateLiteral */ ? + ts.arraysEqual(source.texts, target.texts) ? ts.map(source.types, getStringLikeTypeForType) : + inferFromLiteralPartsToTemplateLiteral(source.texts, source.types, target) : + undefined; + } + function getStringLikeTypeForType(type) { + return type.flags & (1 /* Any */ | 402653316 /* StringLike */) ? type : getTemplateLiteralType(["", ""], [type]); + } + // This function infers from the text parts and type parts of a source literal to a target template literal. The number + // of text parts is always one more than the number of type parts, and a source string literal is treated as a source + // with one text part and zero type parts. The function returns an array of inferred string or template literal types + // corresponding to the placeholders in the target template literal, or undefined if the source doesn't match the target. + // + // We first check that the starting source text part matches the starting target text part, and that the ending source + // text part ends matches the ending target text part. We then iterate through the remaining target text parts, finding + // a match for each in the source and inferring string or template literal types created from the segments of the source + // that occur between the matches. During this iteration, seg holds the index of the current text part in the sourceTexts + // array and pos holds the current character position in the current text part. + // + // Consider inference from type `<<${string}>.<${number}-${number}>>` to type `<${string}.${string}>`, i.e. + // sourceTexts = ['<<', '>.<', '-', '>>'] + // sourceTypes = [string, number, number] + // target.texts = ['<', '.', '>'] + // We first match '<' in the target to the start of '<<' in the source and '>' in the target to the end of '>>' in + // the source. The first match for the '.' in target occurs at character 1 in the source text part at index 1, and thus + // the first inference is the template literal type `<${string}>`. The remainder of the source makes up the second + // inference, the template literal type `<${number}-${number}>`. + function inferFromLiteralPartsToTemplateLiteral(sourceTexts, sourceTypes, target) { + var lastSourceIndex = sourceTexts.length - 1; + var sourceStartText = sourceTexts[0]; + var sourceEndText = sourceTexts[lastSourceIndex]; + var targetTexts = target.texts; + var lastTargetIndex = targetTexts.length - 1; + var targetStartText = targetTexts[0]; + var targetEndText = targetTexts[lastTargetIndex]; + if (lastSourceIndex === 0 && sourceStartText.length < targetStartText.length + targetEndText.length || + !sourceStartText.startsWith(targetStartText) || !sourceEndText.endsWith(targetEndText)) return undefined; + var remainingEndText = sourceEndText.slice(0, sourceEndText.length - targetEndText.length); var matches = []; - var str = value.slice(startText.length, value.length - endText.length); - var pos = 0; - for (var i = 1; i < lastIndex; i++) { - var delim = texts[i]; - var delimPos = delim.length > 0 ? str.indexOf(delim, pos) : pos < str.length ? pos + 1 : -1; - if (delimPos < 0) + var seg = 0; + var pos = targetStartText.length; + for (var i = 1; i < lastTargetIndex; i++) { + var delim = targetTexts[i]; + if (delim.length > 0) { + var s = seg; + var p = pos; + while (true) { + p = getSourceText(s).indexOf(delim, p); + if (p >= 0) + break; + s++; + if (s === sourceTexts.length) + return undefined; + p = 0; + } + addMatch(s, p); + pos += delim.length; + } + else if (pos < getSourceText(seg).length) { + addMatch(seg, pos + 1); + } + else if (seg < lastSourceIndex) { + addMatch(seg + 1, 0); + } + else { return undefined; - matches.push(getLiteralType(str.slice(pos, delimPos))); - pos = delimPos + delim.length; + } } - matches.push(getLiteralType(str.slice(pos))); + addMatch(lastSourceIndex, getSourceText(lastSourceIndex).length); return matches; + function getSourceText(index) { + return index < lastSourceIndex ? sourceTexts[index] : remainingEndText; + } + function addMatch(s, p) { + var matchType = s === seg ? + getLiteralType(getSourceText(s).slice(pos, p)) : + getTemplateLiteralType(__spreadArray(__spreadArray([sourceTexts[seg].slice(pos)], sourceTexts.slice(seg + 1, s)), [getSourceText(s).slice(0, p)]), sourceTypes.slice(seg, s)); + matches.push(matchType); + seg = s; + pos = p; + } } function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) { if (priority === void 0) { priority = 0; } if (contravariant === void 0) { contravariant = false; } var bivariant = false; var propagationType; - var inferencePriority = 1024 /* MaxValue */; + var inferencePriority = 2048 /* MaxValue */; var allowComplexConstraintInference = true; var visited; var sourceStack; @@ -62234,8 +64071,8 @@ var ts; // not contain anyFunctionType when we come back to this argument for its second round // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard // when constructing types from type parameters that had no inference candidates). - if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || - (priority & 64 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || + (priority & 128 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); @@ -62262,7 +64099,7 @@ var ts; clearCachedInferences(inferences); } } - if (!(priority & 64 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 128 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; clearCachedInferences(inferences); } @@ -62302,7 +64139,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - inferWithPriority(empty, target.type, 128 /* LiteralKeyof */); + inferWithPriority(empty, target.type, 256 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -62314,6 +64151,13 @@ var ts; inferFromTypes(source.type, target.type); } } + else if (source.flags & 33554432 /* Substitution */) { + inferFromTypes(source.baseType, target); + var oldPriority = priority; + priority |= 4 /* SubstituteSource */; + inferFromTypes(source.substitute, target); // Make substitute inference at a lower priority + priority = oldPriority; + } else if (target.flags & 16777216 /* Conditional */) { invokeOnce(source, target, inferToConditionalType); } @@ -62333,7 +64177,7 @@ var ts; } else { source = getReducedType(source); - if (!(priority & 256 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { + if (!(priority & 512 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { var apparentSource = getApparentType(source); // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` @@ -62371,26 +64215,22 @@ var ts; } (visited || (visited = new ts.Map())).set(key, -1 /* Circularity */); var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; // We stop inferring and report a circularity if we encounter duplicate recursion identities on both // the source side and the target side. var saveExpandingFlags = expandingFlags; - var sourceIdentity = getRecursionIdentity(source) || source; - var targetIdentity = getRecursionIdentity(target) || target; - if (sourceIdentity && ts.contains(sourceStack, sourceIdentity)) + var sourceIdentity = getRecursionIdentity(source); + var targetIdentity = getRecursionIdentity(target); + if (ts.contains(sourceStack, sourceIdentity)) expandingFlags |= 1 /* Source */; - if (targetIdentity && ts.contains(targetStack, targetIdentity)) + if (ts.contains(targetStack, targetIdentity)) expandingFlags |= 2 /* Target */; if (expandingFlags !== 3 /* Both */) { - if (sourceIdentity) - (sourceStack || (sourceStack = [])).push(sourceIdentity); - if (targetIdentity) - (targetStack || (targetStack = [])).push(targetIdentity); + (sourceStack || (sourceStack = [])).push(sourceIdentity); + (targetStack || (targetStack = [])).push(targetIdentity); action(source, target); - if (targetIdentity) - targetStack.pop(); - if (sourceIdentity) - sourceStack.pop(); + targetStack.pop(); + sourceStack.pop(); } else { inferencePriority = -1 /* Circularity */; @@ -62430,7 +64270,7 @@ var ts; } } function inferFromContravariantTypes(source, target) { - if (strictFunctionTypes || priority & 512 /* AlwaysStrict */) { + if (strictFunctionTypes || priority & 1024 /* AlwaysStrict */) { contravariant = !contravariant; inferFromTypes(source, target); contravariant = !contravariant; @@ -62482,7 +64322,7 @@ var ts; else { for (var i = 0; i < sources.length; i++) { var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; inferFromTypes(sources[i], t); if (inferencePriority === priority) matched_1[i] = true; @@ -62561,9 +64401,9 @@ var ts; // We assign a lower priority to inferences made from types containing non-inferrable // types because we may only have a partial result (i.e. we may have failed to make // reverse inferences for some properties). - inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ? - 8 /* PartialHomomorphicMappedType */ : - 4 /* HomomorphicMappedType */); + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 524288 /* NonInferrableType */ ? + 16 /* PartialHomomorphicMappedType */ : + 8 /* HomomorphicMappedType */); } } return true; @@ -62571,7 +64411,7 @@ var ts; if (constraintType.flags & 262144 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type // parameter. First infer from 'keyof S' to K. - inferWithPriority(getIndexType(source), constraintType, 16 /* MappedTypeConstraint */); + inferWithPriority(getIndexType(source), constraintType, 32 /* MappedTypeConstraint */); // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X }, // where K extends keyof T, we make the same inferences as for a homomorphic mapped type // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a @@ -62600,16 +64440,14 @@ var ts; } else { var savePriority = priority; - priority |= contravariant ? 32 /* ContravariantConditional */ : 0; + priority |= contravariant ? 64 /* ContravariantConditional */ : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; inferToMultipleTypes(source, targetTypes, target.flags); priority = savePriority; } } function inferToTemplateLiteralType(source, target) { - var matches = source.flags & 128 /* StringLiteral */ ? inferLiteralsFromTemplateLiteralType(source, target) : - source.flags & 134217728 /* TemplateLiteral */ && ts.arraysEqual(source.texts, target.texts) ? source.types : - undefined; + var matches = inferTypesFromTemplateLiteralType(source, target); var types = target.types; for (var i = 0; i < types.length; i++) { inferFromTypes(matches ? matches[i] : neverType, types[i]); @@ -62725,7 +64563,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */); + var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* NonInferrableType */); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -62735,7 +64573,7 @@ var ts; 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 === 165 /* MethodDeclaration */ || kind === 164 /* MethodSignature */ || kind === 166 /* Constructor */; + bivariant = bivariant || kind === 166 /* MethodDeclaration */ || kind === 165 /* MethodSignature */ || kind === 167 /* Constructor */; applyToParameterTypes(source, target, inferFromContravariantTypes); bivariant = saveBivariant; } @@ -62762,7 +64600,7 @@ var ts; } } function isTypeOrBaseIdenticalTo(s, t) { - return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 134217856 /* StringLikeLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); + return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); } function isTypeCloselyMatchedBy(s, t) { return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol || @@ -62776,7 +64614,7 @@ var ts; return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); } function isObjectOrArrayLiteralType(type) { - return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */)); + return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 32768 /* ArrayLiteral */)); } function unionObjectAndArrayLiteralCandidates(candidates) { if (candidates.length > 1) { @@ -62789,7 +64627,7 @@ var ts; return candidates; } function getContravariantInference(inference) { - return inference.priority & 208 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + return inference.priority & 416 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } function getCovariantInference(inference, signature) { // Extract all object and array literal types and replace them with a single widened and normalized type. @@ -62806,7 +64644,7 @@ var ts; candidates; // If all inferences were made from a position that implies a combined result, infer a union type. // Otherwise, infer a common supertype. - var unwidenedType = inference.priority & 208 /* PriorityImpliesCombination */ ? + var unwidenedType = inference.priority & 416 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -62915,7 +64753,7 @@ var ts; case "BigUint64Array": return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later; default: - if (node.parent.kind === 289 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 290 /* ShorthandPropertyAssignment */) { return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer; } else { @@ -62936,26 +64774,24 @@ var ts; // TypeScript 1.0 spec (April 2014): 3.6.3 // A type query consists of the keyword typeof followed by an expression. // The expression is restricted to a single identifier or a sequence of identifiers separated by periods - return !!ts.findAncestor(node, function (n) { return n.kind === 176 /* TypeQuery */ ? true : n.kind === 78 /* Identifier */ || n.kind === 157 /* QualifiedName */ ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 177 /* TypeQuery */ ? true : n.kind === 78 /* Identifier */ || n.kind === 158 /* QualifiedName */ ? false : "quit"; }); } // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the // leftmost identifier followed by zero or more property names separated by dots. - // The result is undefined if the reference isn't a dotted name. We prefix nodes - // occurring in an apparent type position with '@' because the control flow type - // of such nodes may be based on the apparent type instead of the declared type. + // The result is undefined if the reference isn't a dotted name. function getFlowCacheKey(node, declaredType, initialType, flowContainer) { switch (node.kind) { case 78 /* Identifier */: var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; case 107 /* ThisKeyword */: return "0|" + (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType); - case 225 /* NonNullExpression */: - case 207 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: var propName = getAccessedPropertyName(node); if (propName !== undefined) { var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); @@ -62966,32 +64802,40 @@ var ts; } function isMatchingReference(source, target) { switch (target.kind) { - case 207 /* ParenthesizedExpression */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: return isMatchingReference(source, target.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return (ts.isAssignmentExpression(target) && isMatchingReference(source, target.left)) || (ts.isBinaryExpression(target) && target.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source, target.right)); } switch (source.kind) { + case 227 /* MetaProperty */: + return target.kind === 227 /* MetaProperty */ + && source.keywordToken === target.keywordToken + && source.name.escapedText === target.name.escapedText; case 78 /* Identifier */: case 79 /* PrivateIdentifier */: return target.kind === 78 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 249 /* VariableDeclaration */ || target.kind === 198 /* BindingElement */) && + (target.kind === 250 /* VariableDeclaration */ || target.kind === 199 /* BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); case 107 /* ThisKeyword */: return target.kind === 107 /* ThisKeyword */; case 105 /* SuperKeyword */: return target.kind === 105 /* SuperKeyword */; - case 225 /* NonNullExpression */: - case 207 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: return isMatchingReference(source.expression, target); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return ts.isAccessExpression(target) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 216 /* BinaryExpression */: + case 158 /* QualifiedName */: + return ts.isAccessExpression(target) && + source.right.escapedText === getAccessedPropertyName(target) && + isMatchingReference(source.left, target.expression); + case 217 /* BinaryExpression */: return (ts.isBinaryExpression(source) && source.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source.right, target)); } return false; @@ -62999,11 +64843,11 @@ var ts; // Given a source x, check if target matches x or is an && operation with an operand that matches x. function containsTruthyCheck(source, target) { return isMatchingReference(source, target) || - (target.kind === 216 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && + (target.kind === 217 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (containsTruthyCheck(source, target.left) || containsTruthyCheck(source, target.right))); } function getAccessedPropertyName(access) { - return access.kind === 201 /* PropertyAccessExpression */ ? access.name.escapedText : + return access.kind === 202 /* PropertyAccessExpression */ ? access.name.escapedText : ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : undefined; } @@ -63053,6 +64897,86 @@ var ts; } return result; } + // Given a set of constituent types and a property name, create and return a map keyed by the literal + // types of the property by that name in each constituent type. No map is returned if some key property + // has a non-literal type or if less than 10 or less than 50% of the constituents have a unique key. + // Entries with duplicate keys have unknownType as the value. + function mapTypesByKeyProperty(types, name) { + var map = new ts.Map(); + var count = 0; + var _loop_20 = function (type) { + if (type.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */)) { + var discriminant = getTypeOfPropertyOfType(type, name); + if (discriminant) { + if (!isLiteralType(discriminant)) { + return { value: undefined }; + } + var duplicate_1 = false; + forEachType(discriminant, function (t) { + var id = getTypeId(getRegularTypeOfLiteralType(t)); + var existing = map.get(id); + if (!existing) { + map.set(id, type); + } + else if (existing !== unknownType) { + map.set(id, unknownType); + duplicate_1 = true; + } + }); + if (!duplicate_1) + count++; + } + } + }; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; + var state_8 = _loop_20(type); + if (typeof state_8 === "object") + return state_8.value; + } + return count >= 10 && count * 2 >= types.length ? map : undefined; + } + // Return the name of a discriminant property for which it was possible and feasible to construct a map of + // constituent types keyed by the literal types of the property by that name in each constituent type. + function getKeyPropertyName(unionType) { + var types = unionType.types; + // We only construct maps for large unions with non-primitive constituents. + if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */) { + return undefined; + } + if (unionType.keyPropertyName === undefined) { + // The candidate key property name is the name of the first property with a unit type in one of the + // constituent types. + var keyPropertyName = ts.forEach(types, function (t) { + return t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ? + ts.forEach(getPropertiesOfType(t), function (p) { return isUnitType(getTypeOfSymbol(p)) ? p.escapedName : undefined; }) : + undefined; + }); + var mapByKeyProperty = keyPropertyName && mapTypesByKeyProperty(types, keyPropertyName); + unionType.keyPropertyName = mapByKeyProperty ? keyPropertyName : ""; + unionType.constituentMap = mapByKeyProperty; + } + return unionType.keyPropertyName.length ? unionType.keyPropertyName : undefined; + } + // Given a union type for which getKeyPropertyName returned a non-undefined result, return the constituent + // that corresponds to the given key type for that property name. + function getConstituentTypeForKeyType(unionType, keyType) { + var _a; + var result = (_a = unionType.constituentMap) === null || _a === void 0 ? void 0 : _a.get(getTypeId(getRegularTypeOfLiteralType(keyType))); + return result !== unknownType ? result : undefined; + } + function getMatchingUnionConstituentForType(unionType, type) { + var keyPropertyName = getKeyPropertyName(unionType); + var propType = keyPropertyName && getTypeOfPropertyOfType(type, keyPropertyName); + return propType && getConstituentTypeForKeyType(unionType, propType); + } + function getMatchingUnionConstituentForObjectLiteral(unionType, node) { + var keyPropertyName = getKeyPropertyName(unionType); + var propNode = keyPropertyName && ts.find(node.properties, function (p) { return p.symbol && p.kind === 289 /* PropertyAssignment */ && + p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer); }); + var propType = propNode && getTypeOfExpression(propNode.initializer); + return propType && getConstituentTypeForKeyType(unionType, propType); + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -63065,7 +64989,7 @@ var ts; } } } - if (expression.expression.kind === 201 /* PropertyAccessExpression */ && + if (expression.expression.kind === 202 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, expression.expression.expression)) { return true; } @@ -63112,14 +65036,6 @@ var ts; } return declaredType; } - function getTypeFactsOfTypes(types) { - var result = 0 /* None */; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; - result |= getTypeFacts(t); - } - return result; - } function isFunctionObjectType(type) { // We do a quick check for a "bind" property before performing the more expensive subtype // check. This gives us a quicker out in the common case where an object type is not a function. @@ -63127,7 +65043,8 @@ var ts; return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type) { + function getTypeFacts(type, ignoreObjects) { + if (ignoreObjects === void 0) { ignoreObjects = false; } var flags = type.flags; if (flags & 4 /* String */) { return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; @@ -63164,7 +65081,7 @@ var ts; (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } - if (flags & 524288 /* Object */) { + if (flags & 524288 /* Object */ && !ignoreObjects) { return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : isFunctionObjectType(type) ? @@ -63187,11 +65104,17 @@ var ts; return 0 /* None */; } if (flags & 465829888 /* Instantiable */) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType) : + return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : strictNullChecks ? 7929345 /* NonEmptyStringStrictFacts */ : 16776705 /* NonEmptyStringFacts */; } - if (flags & 3145728 /* UnionOrIntersection */) { - return getTypeFactsOfTypes(type.types); + if (flags & 1048576 /* Union */) { + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0 /* None */); + } + if (flags & 2097152 /* Intersection */) { + // When an intersection contains a primitive type we ignore object type constituents as they are + // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. + ignoreObjects || (ignoreObjects = maybeTypeOfKind(type, 131068 /* Primitive */)); + return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t, ignoreObjects); }, 16777215 /* All */); } return 16777215 /* All */; } @@ -63199,18 +65122,16 @@ var ts; return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { - if (defaultExpression) { - var defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]); - } - return type; + return defaultExpression ? + getUnionType([getNonUndefinedType(type), getTypeOfExpression(defaultExpression)]) : + type; } function getTypeOfDestructuredProperty(type, name) { var nameType = getLiteralTypeFromPropertyName(name); if (!isTypeUsableAsPropertyName(nameType)) return errorType; var text = getPropertyNameFromType(nameType); - return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || + return getTypeOfPropertyOfType(type, text) || isNumericLiteralName(text) && includeUndefinedInIndexSignature(getIndexTypeOfType(type, 1 /* Number */)) || includeUndefinedInIndexSignature(getIndexTypeOfType(type, 0 /* String */)) || errorType; @@ -63231,15 +65152,15 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) || errorType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 199 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 288 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 200 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 289 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 216 /* BinaryExpression */ && parent.parent.left === parent || - parent.parent.kind === 239 /* ForOfStatement */ && parent.parent.initializer === parent; + return parent.parent.kind === 217 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 240 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); @@ -63256,21 +65177,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return stringType; - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return checkRightHandSideOfForOf(parent) || errorType; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return undefinedType; - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return getAssignedTypeOfSpreadExpression(parent); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return errorType; @@ -63278,7 +65199,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 196 /* ObjectBindingPattern */ ? + var type = pattern.kind === 197 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : @@ -63296,30 +65217,30 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 238 /* ForInStatement */) { + if (node.parent.parent.kind === 239 /* ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 239 /* ForOfStatement */) { + if (node.parent.parent.kind === 240 /* ForOfStatement */) { return checkRightHandSideOfForOf(node.parent.parent) || errorType; } return errorType; } function getInitialType(node) { - return node.kind === 249 /* VariableDeclaration */ ? + return node.kind === 250 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function isEmptyArrayAssignment(node) { - return node.kind === 249 /* VariableDeclaration */ && node.initializer && + return node.kind === 250 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 198 /* BindingElement */ && node.parent.kind === 216 /* BinaryExpression */ && + node.kind !== 199 /* BindingElement */ && node.parent.kind === 217 /* BinaryExpression */ && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (node.operatorToken.kind) { case 62 /* EqualsToken */: case 74 /* BarBarEqualsToken */: @@ -63334,13 +65255,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 207 /* ParenthesizedExpression */ || - parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node || - parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? + return parent.kind === 208 /* ParenthesizedExpression */ || + parent.kind === 217 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node || + parent.kind === 217 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 284 /* CaseClause */) { + if (clause.kind === 285 /* CaseClause */) { return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); } return neverType; @@ -63360,7 +65281,7 @@ var ts; var witnesses = []; for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { var clause = _a[_i]; - if (clause.kind === 284 /* CaseClause */) { + if (clause.kind === 285 /* CaseClause */) { if (ts.isStringLiteralLike(clause.expression)) { witnesses.push(clause.expression.text); continue; @@ -63396,14 +65317,40 @@ var ts; function forEachType(type, f) { return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type); } + function someType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.some(type.types, f) : f(type); + } function everyType(type, f) { return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); } + function everyContainedType(type, f) { + return type.flags & 3145728 /* UnionOrIntersection */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 1048576 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); + if (filtered === types) { + return type; + } + var origin = type.origin; + var newOrigin = void 0; + if (origin && origin.flags & 1048576 /* Union */) { + // If the origin type is a (denormalized) union type, filter its non-union constituents. If that ends + // up removing a smaller number of types than in the normalized constituent set (meaning some of the + // filtered types are within nested unions in the origin), then we can't construct a new origin type. + // Otherwise, if we have exactly one type left in the origin set, return that as the filtered type. + // Otherwise, construct a new filtered origin type. + var originTypes = origin.types; + var originFiltered = ts.filter(originTypes, function (t) { return !!(t.flags & 1048576 /* Union */) || f(t); }); + if (originTypes.length - originFiltered.length === types.length - filtered.length) { + if (originFiltered.length === 1) { + return originFiltered[0]; + } + newOrigin = createOriginUnionOrIntersectionType(1048576 /* Union */, originFiltered); + } + } + return getUnionTypeFromSortedList(filtered, type.objectFlags, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, newOrigin); } return type.flags & 131072 /* Never */ || f(type) ? type : neverType; } @@ -63436,6 +65383,11 @@ var ts; } return changed ? mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : type; } + function mapTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) { + return type.flags & 1048576 /* Union */ && aliasSymbol ? + getUnionType(ts.map(type.types, mapper), 1 /* Literal */, aliasSymbol, aliasTypeArguments) : + mapType(type, mapper); + } function getConstituentCount(type) { return type.flags & 3145728 /* UnionOrIntersection */ ? type.types.length : 1; } @@ -63521,12 +65473,12 @@ var ts; var root = getReferenceRoot(node); var parent = root.parent; var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" || - parent.parent.kind === 203 /* CallExpression */ + parent.parent.kind === 204 /* CallExpression */ && ts.isIdentifier(parent.name) && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 202 /* ElementAccessExpression */ && + var isElementAssignment = parent.kind === 203 /* ElementAccessExpression */ && parent.expression === root && - parent.parent.kind === 216 /* BinaryExpression */ && + parent.parent.kind === 217 /* BinaryExpression */ && parent.parent.operatorToken.kind === 62 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && @@ -63534,8 +65486,8 @@ var ts; return isLengthPushOrUnshift || isElementAssignment; } function isDeclarationWithExplicitTypeAnnotation(declaration) { - return (declaration.kind === 249 /* VariableDeclaration */ || declaration.kind === 160 /* Parameter */ || - declaration.kind === 163 /* PropertyDeclaration */ || declaration.kind === 162 /* PropertySignature */) && + return (declaration.kind === 250 /* VariableDeclaration */ || declaration.kind === 161 /* Parameter */ || + declaration.kind === 164 /* PropertyDeclaration */ || declaration.kind === 163 /* PropertySignature */) && !!ts.getEffectiveTypeAnnotationNode(declaration); } function getExplicitTypeOfSymbol(symbol, diagnostic) { @@ -63554,7 +65506,7 @@ var ts; if (isDeclarationWithExplicitTypeAnnotation(declaration)) { return getTypeOfSymbol(symbol); } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 240 /* ForOfStatement */) { var statement = declaration.parent.parent; var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined); if (expressionType) { @@ -63582,11 +65534,25 @@ var ts; return getExplicitThisType(node); case 105 /* SuperKeyword */: return checkSuperExpression(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: { var type = getTypeOfDottedName(node.expression, diagnostic); - var prop = type && getPropertyOfType(type, node.name.escapedText); - return prop && getExplicitTypeOfSymbol(prop, diagnostic); - case 207 /* ParenthesizedExpression */: + if (type) { + var name = node.name; + var prop = void 0; + if (ts.isPrivateIdentifier(name)) { + if (!type.symbol) { + return undefined; + } + prop = getPropertyOfType(type, ts.getSymbolNameForPrivateIdentifier(type.symbol, name.escapedText)); + } + else { + prop = getPropertyOfType(type, name.escapedText); + } + return prop && getExplicitTypeOfSymbol(prop, diagnostic); + } + return undefined; + } + case 208 /* ParenthesizedExpression */: return getTypeOfDottedName(node.expression, diagnostic); } } @@ -63600,7 +65566,7 @@ var ts; // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call // target expression of an assertion. var funcType = void 0; - if (node.parent.kind === 233 /* ExpressionStatement */) { + if (node.parent.kind === 234 /* ExpressionStatement */) { funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined); } else if (node.expression.kind !== 105 /* SuperKeyword */) { @@ -63644,7 +65610,7 @@ var ts; } function isFalseExpression(expr) { var node = ts.skipParentheses(expr); - return node.kind === 94 /* FalseKeyword */ || node.kind === 216 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + return node.kind === 94 /* FalseKeyword */ || node.kind === 217 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); } function isReachableFlowNodeWorker(flow, noCacheCheck) { @@ -63779,7 +65745,7 @@ var ts; // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); - if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 225 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { + if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 226 /* NonNullExpression */ && !(resultType.flags & 131072 /* Never */) && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { return declaredType; } return resultType; @@ -63794,7 +65760,7 @@ var ts; 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. - ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); flowAnalysisDisabled = true; reportFlowControlError(reference); return errorType; @@ -63863,8 +65829,8 @@ var ts; // Check if we should continue with the control flow of the containing function. var container = flow.node; if (container && container !== flowContainer && - reference.kind !== 201 /* PropertyAccessExpression */ && - reference.kind !== 202 /* ElementAccessExpression */ && + reference.kind !== 202 /* PropertyAccessExpression */ && + reference.kind !== 203 /* ElementAccessExpression */ && reference.kind !== 107 /* ThisKeyword */) { flow = container.flowNode; continue; @@ -63889,7 +65855,7 @@ var ts; } function getInitialOrAssignedType(flow) { var node = flow.node; - return getConstraintForLocation(node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */ ? + return getNarrowableTypeForReference(node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */ ? getInitialType(node) : getAssignedType(node), reference); } @@ -63929,14 +65895,14 @@ var ts; // 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 === 208 /* FunctionExpression */ || init.kind === 209 /* ArrowFunction */)) { + if (init && (init.kind === 209 /* FunctionExpression */ || init.kind === 210 /* ArrowFunction */)) { return getTypeAtFlowNode(flow.antecedent); } } return declaredType; } // for (const _ in ref) acts as a nonnull on ref - if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 238 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 239 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); } // Assignment doesn't affect reference @@ -63947,7 +65913,7 @@ var ts; if (node.kind === 94 /* FalseKeyword */) { return unreachableNeverType; } - if (node.kind === 216 /* BinaryExpression */) { + if (node.kind === 217 /* BinaryExpression */) { if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); } @@ -63978,7 +65944,7 @@ var ts; function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 203 /* CallExpression */ ? + var expr = node.kind === 204 /* CallExpression */ ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { @@ -63986,7 +65952,7 @@ var ts; var type = getTypeFromFlowType(flowType); if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { var evolvedType_1 = type; - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); @@ -64034,7 +66000,7 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (expr.kind === 211 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + else if (expr.kind === 212 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else { @@ -64042,12 +66008,12 @@ var ts; if (optionalChainContainsReference(expr, reference)) { type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); }); } - else if (expr.kind === 211 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { + else if (expr.kind === 212 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); }); } } if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + type = narrowTypeBySwitchOnDiscriminantProperty(type, expr, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } } return createFlowType(type, isIncomplete(flowType)); @@ -64218,16 +66184,42 @@ var ts; if (propName === undefined) { return type; } - var propType = getTypeOfPropertyOfType(type, propName); + var removeNullable = strictNullChecks && ts.isOptionalChain(access) && maybeTypeOfKind(type, 98304 /* Nullable */); + var propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type, propName); if (!propType) { return type; } + propType = removeNullable ? getOptionalType(propType) : propType; var narrowedPropType = narrowType(propType); return filterType(type, function (t) { var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName); return !(discriminantType.flags & 131072 /* Never */) && isTypeComparableTo(discriminantType, narrowedPropType); }); } + function narrowTypeByDiscriminantProperty(type, access, operator, value, assumeTrue) { + if ((operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) && type.flags & 1048576 /* Union */) { + var keyPropertyName = getKeyPropertyName(type); + if (keyPropertyName && keyPropertyName === getAccessedPropertyName(access)) { + var candidate_2 = getConstituentTypeForKeyType(type, getTypeOfExpression(value)); + if (candidate_2) { + return operator === (assumeTrue ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */) ? candidate_2 : + isUnitType(getTypeOfPropertyOfType(candidate_2, keyPropertyName) || unknownType) ? filterType(type, function (t) { return t !== candidate_2; }) : + type; + } + } + } + return narrowTypeByDiscriminant(type, access, function (t) { return narrowTypeByEquality(t, operator, value, assumeTrue); }); + } + function narrowTypeBySwitchOnDiscriminantProperty(type, access, switchStatement, clauseStart, clauseEnd) { + if (clauseStart < clauseEnd && type.flags & 1048576 /* Union */ && getKeyPropertyName(type) === getAccessedPropertyName(access)) { + var clauseTypes = getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd); + var candidate = getUnionType(ts.map(clauseTypes, function (t) { return getConstituentTypeForKeyType(type, t) || unknownType; })); + if (candidate !== unknownType) { + return candidate; + } + } + return narrowTypeByDiscriminant(type, access, function (t) { return narrowTypeBySwitchOnDiscriminant(t, switchStatement, clauseStart, clauseEnd); }); + } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); @@ -64251,7 +66243,8 @@ var ts; return !assumeTrue; } function narrowByInKeyword(type, literal, assumeTrue) { - if (type.flags & (1048576 /* Union */ | 524288 /* Object */) + if (type.flags & 1048576 /* Union */ + || type.flags & 524288 /* Object */ && declaredType !== type || isThisTypeParameter(type) || type.flags & 2097152 /* Intersection */ && ts.every(type.types, function (t) { return t.symbol !== globalThisSymbol; })) { var propName_1 = ts.escapeLeadingUnderscores(literal.text); @@ -64270,40 +66263,40 @@ var ts; case 35 /* ExclamationEqualsToken */: case 36 /* EqualsEqualsEqualsToken */: case 37 /* ExclamationEqualsEqualsToken */: - var operator_1 = expr.operatorToken.kind; - var left_1 = getReferenceCandidate(expr.left); - var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 211 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { - return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + var operator = expr.operatorToken.kind; + var left = getReferenceCandidate(expr.left); + var right = getReferenceCandidate(expr.right); + if (left.kind === 212 /* TypeOfExpression */ && ts.isStringLiteralLike(right)) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); } - if (right_1.kind === 211 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { - return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + if (right.kind === 212 /* TypeOfExpression */ && ts.isStringLiteralLike(left)) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); } - if (isMatchingReference(reference, left_1)) { - return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + if (isMatchingReference(reference, left)) { + return narrowTypeByEquality(type, operator, right, assumeTrue); } - if (isMatchingReference(reference, right_1)) { - return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + if (isMatchingReference(reference, right)) { + return narrowTypeByEquality(type, operator, left, assumeTrue); } if (strictNullChecks) { - if (optionalChainContainsReference(left_1, reference)) { - type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue); + if (optionalChainContainsReference(left, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator, right, assumeTrue); } - else if (optionalChainContainsReference(right_1, reference)) { - type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); + else if (optionalChainContainsReference(right, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator, left, assumeTrue); } } - if (isMatchingReferenceDiscriminant(left_1, type)) { - return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + if (isMatchingReferenceDiscriminant(left, type)) { + return narrowTypeByDiscriminantProperty(type, left, operator, right, assumeTrue); } - if (isMatchingReferenceDiscriminant(right_1, type)) { - return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + if (isMatchingReferenceDiscriminant(right, type)) { + return narrowTypeByDiscriminantProperty(type, right, operator, left, assumeTrue); } - if (isMatchingConstructorReference(left_1)) { - return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue); + if (isMatchingConstructorReference(left)) { + return narrowTypeByConstructor(type, operator, right, assumeTrue); } - if (isMatchingConstructorReference(right_1)) { - return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue); + if (isMatchingConstructorReference(right)) { + return narrowTypeByConstructor(type, operator, left, assumeTrue); } break; case 101 /* InstanceOfKeyword */: @@ -64368,13 +66361,12 @@ var ts; } if (assumeTrue) { var filterFn = operator === 34 /* EqualsEqualsToken */ ? - (function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); }) : + function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); } : function (t) { return areTypesComparable(t, valueType); }; return replacePrimitivesWithLiterals(filterType(type, filterFn), valueType); } if (isUnitType(valueType)) { - var regularType_1 = getRegularTypeOfLiteralType(valueType); - return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; }); + return filterType(type, function (t) { return !(isUnitLikeType(t) && areTypesComparable(t, valueType)); }); } return type; } @@ -64396,7 +66388,7 @@ var ts; if (assumeTrue && type.flags & 2 /* Unknown */ && literal.text === "object") { // The pattern x && typeof x === 'object', where x is of type unknown, narrows x to type object. We don't // need to check for the reverse typeof x === 'object' && x since that already narrows correctly. - if (typeOfExpr.parent.parent.kind === 216 /* BinaryExpression */) { + if (typeOfExpr.parent.parent.kind === 217 /* BinaryExpression */) { var expr = typeOfExpr.parent.parent; if (expr.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && expr.right === typeOfExpr.parent && containsTruthyCheck(reference, expr.left)) { return nonPrimitiveType; @@ -64452,7 +66444,7 @@ var ts; if (!hasDefaultClause) { return caseType; } - var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + var defaultType = filterType(type, function (t) { return !(isUnitLikeType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(extractUnitType(t)))); }); return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } function getImpliedTypeFromTypeofGuard(type, text) { @@ -64634,7 +66626,16 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { - return filterType(type, function (t) { return !isRelated(t, candidate); }); + return filterType(type, function (t) { + if (!isRelated(t, candidate)) { + return true; + } + var constraint = getBaseConstraintOfType(t); + if (constraint && constraint !== t) { + return !isRelated(constraint, candidate); + } + return false; + }); } // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. @@ -64644,10 +66645,15 @@ var ts; return assignableType; } } - // If the candidate type is a subtype of the target type, narrow to the candidate type, - // if the target type is a subtype of the candidate type, narrow to the target type, - // otherwise, narrow to an intersection of the two types. - return isTypeSubtypeOf(candidate, type) ? candidate : isTypeSubtypeOf(type, candidate) ? type : getIntersectionType([type, candidate]); + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -64690,17 +66696,17 @@ var ts; case 78 /* Identifier */: case 107 /* ThisKeyword */: case 105 /* SuperKeyword */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return narrowTypeByCallExpression(type, expr, assumeTrue); - case 207 /* ParenthesizedExpression */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: return narrowType(type, expr.expression, assumeTrue); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: if (expr.operator === 53 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } @@ -64724,17 +66730,20 @@ var ts; // an dotted name expression, and if the location is not an assignment target, obtain the type // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. - if (location.kind === 78 /* Identifier */) { + if (location.kind === 78 /* Identifier */ || location.kind === 79 /* PrivateIdentifier */) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { + if (ts.isExpressionNode(location) && (!ts.isAssignmentTarget(location) || ts.isWriteAccess(location))) { var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } } } + if (ts.isDeclarationName(location) && ts.isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) { + return resolveTypeOfAccessors(location.parent.symbol, /*writing*/ true); + } // The location isn't a reference to the given symbol, meaning we're being asked // a hypothetical question of what type the symbol would have if there was a reference // to it at the given location. Since we have no control flow information for the @@ -64745,13 +66754,16 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 257 /* ModuleBlock */ || - node.kind === 297 /* SourceFile */ || - node.kind === 163 /* PropertyDeclaration */; + node.kind === 258 /* ModuleBlock */ || + node.kind === 298 /* SourceFile */ || + node.kind === 164 /* PropertyDeclaration */; }); } // Check if a parameter is assigned anywhere within its declaring function. function isParameterAssigned(symbol) { + if (!symbol.valueDeclaration) { + return false; + } var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); if (!(links.flags & 8388608 /* AssignmentsMarked */)) { @@ -64769,7 +66781,7 @@ var ts; if (node.kind === 78 /* Identifier */) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 160 /* Parameter */) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 161 /* Parameter */) { symbol.isAssigned = true; } } @@ -64785,7 +66797,7 @@ var ts; function removeOptionalityFromDeclaredType(declaredType, declaration) { if (pushTypeResolution(declaration.symbol, 2 /* DeclaredType */)) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 160 /* Parameter */ && + declaration.kind === 161 /* Parameter */ && declaration.initializer && getFalsyFlags(declaredType) & 32768 /* Undefined */ && !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */); @@ -64799,23 +66811,40 @@ var ts; } function isConstraintPosition(node) { var parent = node.parent; - return parent.kind === 201 /* PropertyAccessExpression */ || - parent.kind === 203 /* CallExpression */ && parent.expression === node || - parent.kind === 202 /* ElementAccessExpression */ && parent.expression === node || - parent.kind === 198 /* BindingElement */ && parent.name === node && !!parent.initializer; - } - function typeHasNullableConstraint(type) { - return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 98304 /* Nullable */); - } - function getConstraintForLocation(type, node) { - // When a node is the left hand expression of a property access, element access, or call expression, - // and the type of the node includes type variables with constraints that are nullable, we fetch the - // apparent type of the node *before* performing control flow analysis such that narrowings apply to - // the constraint type. - if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { - return mapType(getWidenedType(type), getBaseConstraintOrType); - } - return type; + // In an element access obj[x], we consider obj to be in a constraint position only when x is not + // of a generic type. This is because when both obj and x are of generic types T and K, we want + // the resulting type to be T[K]. + return parent.kind === 202 /* PropertyAccessExpression */ || + parent.kind === 204 /* CallExpression */ && parent.expression === node || + parent.kind === 203 /* ElementAccessExpression */ && parent.expression === node && + !isGenericIndexType(getTypeOfExpression(parent.argumentExpression)); + } + function isGenericTypeWithUnionConstraint(type) { + return !!(type.flags & 465829888 /* Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* Nullable */ | 1048576 /* Union */)); + } + function containsGenericType(type) { + return !!(type.flags & 465829888 /* Instantiable */ || type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, containsGenericType)); + } + function hasContextualTypeWithNoGenericTypes(node) { + // Computing the contextual type for a child of a JSX element involves resolving the type of the + // element's tag name, so we exclude that here to avoid circularities. + var contextualType = (ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && + !((ts.isJsxOpeningElement(node.parent) || ts.isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && + getContextualType(node); + return contextualType && !someType(contextualType, containsGenericType); + } + function getNarrowableTypeForReference(type, reference, checkMode) { + // When the type of a reference is or contains an instantiable type with a union type constraint, and + // when the reference is in a constraint position (where it is known we'll obtain the apparent type) or + // has a contextual type containing no top-level instantiables (meaning constraints will determine + // assignability), we substitute constraints for all instantiables in the type of the reference to give + // control flow analysis an opportunity to narrow it further. For example, for a reference of a type + // parameter type 'T extends string | undefined' with a contextual type 'string', we substitute + // 'string | undefined' to give control flow analysis the opportunity to narrow to type 'string'. + var substituteConstraints = !(checkMode && checkMode & 2 /* Inferential */) && + someType(type, isGenericTypeWithUnionConstraint) && + (isConstraintPosition(reference) || hasContextualTypeWithNoGenericTypes(reference)); + return substituteConstraints ? mapType(type, function (t) { return t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type; } function isExportOrExportExpression(location) { return !!ts.findAncestor(location, function (e) { return e.parent && ts.isExportAssignment(e.parent) && e.parent.expression === e && ts.isEntityNameExpression(e); }); @@ -64824,7 +66853,12 @@ var ts; if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { var target = resolveAlias(symbol); if (target.flags & 111551 /* Value */) { - if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(target)) { + // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled + // (because the const enum value will not be inlined), or if (2) the alias is an export + // of a const enum declaration that will be preserved. + if (compilerOptions.isolatedModules || + ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || + !isConstEnumOrConstEnumOnlyModule(target)) { markAliasSymbolAsReferenced(symbol); } else { @@ -64833,7 +66867,7 @@ var ts; } } } - function checkIdentifier(node) { + function checkIdentifier(node, checkMode) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { return errorType; @@ -64847,7 +66881,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2 /* ES2015 */) { - if (container.kind === 209 /* ArrowFunction */) { + if (container.kind === 210 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasSyntacticModifier(container, 256 /* Async */)) { @@ -64864,15 +66898,15 @@ var ts; } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var sourceSymbol = localOrExportSymbol.flags & 2097152 /* Alias */ ? resolveAlias(localOrExportSymbol) : localOrExportSymbol; - if (getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) { - errorOrSuggestion(/* isError */ false, node, ts.Diagnostics._0_is_deprecated, node.escapedText); + if (sourceSymbol.declarations && getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) { + addDeprecatedSuggestion(node, sourceSymbol.declarations, node.escapedText); } var declaration = localOrExportSymbol.valueDeclaration; - if (localOrExportSymbol.flags & 32 /* Class */) { + if (declaration && localOrExportSymbol.flags & 32 /* Class */) { // 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. - if (declaration.kind === 252 /* ClassDeclaration */ + if (declaration.kind === 253 /* ClassDeclaration */ && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -64884,14 +66918,14 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration.kind === 221 /* ClassExpression */) { + else if (declaration.kind === 222 /* ClassExpression */) { // When we emit a class expression with static members that contain a reference // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container.kind !== 297 /* SourceFile */) { + while (container.kind !== 298 /* SourceFile */) { if (container.parent === declaration) { - if (container.kind === 163 /* PropertyDeclaration */ && ts.hasSyntacticModifier(container, 32 /* Static */)) { + if (container.kind === 164 /* PropertyDeclaration */ && ts.hasSyntacticModifier(container, 32 /* Static */)) { getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } @@ -64902,12 +66936,18 @@ var ts; } } checkNestedBlockScopedBinding(node, symbol); - var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); + var type = getTypeOfSymbol(localOrExportSymbol); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + var assignmentError = localOrExportSymbol.flags & 384 /* Enum */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_an_enum + : localOrExportSymbol.flags & 32 /* Class */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_class + : localOrExportSymbol.flags & 1536 /* Module */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_namespace + : localOrExportSymbol.flags & 16 /* Function */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_function + : localOrExportSymbol.flags & 2097152 /* Alias */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_an_import + : ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable; + error(node, assignmentError, symbolToString(symbol)); return errorType; } if (isReadonlySymbol(localOrExportSymbol)) { @@ -64929,7 +66969,7 @@ var ts; } } else if (isAlias) { - declaration = ts.find(symbol.declarations, isSomeImportDeclaration); + declaration = getDeclarationOfAliasSymbol(symbol); } else { return type; @@ -64937,10 +66977,11 @@ var ts; if (!declaration) { return type; } + type = getNarrowableTypeForReference(type, node, checkMode); // The declaration container is the innermost function that encloses the declaration of the variable // or parameter. The flow container is the innermost function starting with which we analyze the control // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 160 /* Parameter */; + var isParameter = ts.getRootDeclaration(declaration).kind === 161 /* Parameter */; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; @@ -64949,8 +66990,8 @@ var ts; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === 208 /* FunctionExpression */ || - flowContainer.kind === 209 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 209 /* FunctionExpression */ || + flowContainer.kind === 210 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } @@ -64959,9 +67000,9 @@ var ts; // declaration container are the same). var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 || - isInTypeQuery(node) || node.parent.kind === 270 /* ExportSpecifier */) || - node.parent.kind === 225 /* NonNullExpression */ || - declaration.kind === 249 /* VariableDeclaration */ && declaration.exclamationToken || + isInTypeQuery(node) || node.parent.kind === 271 /* ExportSpecifier */) || + node.parent.kind === 226 /* NonNullExpression */ || + declaration.kind === 250 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 8388608 /* Ambient */; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : type === autoType || type === autoArrayType ? undefinedType : @@ -64986,17 +67027,21 @@ var ts; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } - function isInsideFunction(node, threshold) { - return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); + function isInsideFunctionOrInstancePropertyInitializer(node, threshold) { + return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n) || (n.parent && ts.isPropertyDeclaration(n.parent) && !ts.hasStaticModifier(n.parent) && n.parent.initializer === n); }); } 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 getEnclosingIterationStatement(node) { + return ts.findAncestor(node, function (n) { return (!n || ts.nodeStartsNewLexicalEnvironment(n)) ? "quit" : ts.isIterationStatement(n, /*lookInLabeledStatements*/ false); }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || + !symbol.valueDeclaration || ts.isSourceFile(symbol.valueDeclaration) || - symbol.valueDeclaration.parent.kind === 287 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 288 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -65004,22 +67049,14 @@ var ts; // 2. walk from the declaration up to the boundary of lexical environment and check // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - var usedInFunction = isInsideFunction(node.parent, container); - var current = container; - var containedInIterationStatement = false; - while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { - if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) { - containedInIterationStatement = true; - break; - } - current = current.parent; - } - if (containedInIterationStatement) { - if (usedInFunction) { + var isCaptured = isInsideFunctionOrInstancePropertyInitializer(node, container); + var enclosingIterationStatement = getEnclosingIterationStatement(container); + if (enclosingIterationStatement) { + if (isCaptured) { // mark iteration statement as containing block-scoped binding captured in some function var capturesBlockScopeBindingInLoopBody = true; if (ts.isForStatement(container)) { - var varDeclList = ts.getAncestor(symbol.valueDeclaration, 250 /* VariableDeclarationList */); + var varDeclList = ts.getAncestor(symbol.valueDeclaration, 251 /* VariableDeclarationList */); if (varDeclList && varDeclList.parent === container) { var part = getPartOfForStatementContainingNode(node.parent, container); if (part) { @@ -65034,13 +67071,13 @@ var ts; } } if (capturesBlockScopeBindingInLoopBody) { - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + getNodeLinks(enclosingIterationStatement).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 (ts.isForStatement(container)) { - var varDeclList = ts.getAncestor(symbol.valueDeclaration, 250 /* VariableDeclarationList */); + var varDeclList = ts.getAncestor(symbol.valueDeclaration, 251 /* VariableDeclarationList */); if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } @@ -65048,7 +67085,7 @@ var ts; // set 'declared inside loop' bit on the block-scoped binding getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } - if (usedInFunction) { + if (isCaptured) { getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } @@ -65059,7 +67096,7 @@ var ts; function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; - while (current.parent.kind === 207 /* ParenthesizedExpression */) { + while (current.parent.kind === 208 /* ParenthesizedExpression */) { current = current.parent; } // check if node is used as LHS in some assignment expression @@ -65067,7 +67104,7 @@ var ts; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 214 /* PrefixUnaryExpression */ || current.parent.kind === 215 /* PostfixUnaryExpression */)) { + else if ((current.parent.kind === 215 /* PrefixUnaryExpression */ || current.parent.kind === 216 /* PostfixUnaryExpression */)) { var expr = current.parent; isAssigned = expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */; } @@ -65080,7 +67117,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 163 /* PropertyDeclaration */ || container.kind === 166 /* Constructor */) { + if (container.kind === 164 /* PropertyDeclaration */ || container.kind === 167 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -65120,37 +67157,37 @@ var ts; // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var capturedByArrowFunction = false; - if (container.kind === 166 /* Constructor */) { + if (container.kind === 167 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 209 /* ArrowFunction */) { + if (container.kind === 210 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); capturedByArrowFunction = true; } switch (container.kind) { - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 166 /* Constructor */: + case 167 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -65238,7 +67275,7 @@ var ts; } function getClassNameFromPrototypeMethod(container) { // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 208 /* FunctionExpression */ && + if (container.kind === 209 /* FunctionExpression */ && ts.isBinaryExpression(container.parent) && ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { // Get the 'x' of 'x.prototype.y = container' @@ -65248,16 +67285,16 @@ var ts; .expression; // x } // x.prototype = { method() { } } - else if (container.kind === 165 /* MethodDeclaration */ && - container.parent.kind === 200 /* ObjectLiteralExpression */ && + else if (container.kind === 166 /* MethodDeclaration */ && + container.parent.kind === 201 /* 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 === 208 /* FunctionExpression */ && - container.parent.kind === 288 /* PropertyAssignment */ && - container.parent.parent.kind === 200 /* ObjectLiteralExpression */ && + else if (container.kind === 209 /* FunctionExpression */ && + container.parent.kind === 289 /* PropertyAssignment */ && + container.parent.parent.kind === 201 /* ObjectLiteralExpression */ && ts.isBinaryExpression(container.parent.parent.parent) && ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { return container.parent.parent.parent.left.expression; @@ -65265,7 +67302,7 @@ var ts; // Object.defineProperty(x, "method", { value: function() { } }); // Object.defineProperty(x, "method", { set: (x: () => void) => void }); // Object.defineProperty(x, "method", { get: () => function() { }) }); - else if (container.kind === 208 /* FunctionExpression */ && + else if (container.kind === 209 /* FunctionExpression */ && ts.isPropertyAssignment(container.parent) && ts.isIdentifier(container.parent.name) && (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && @@ -65290,7 +67327,7 @@ var ts; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 308 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 309 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -65304,16 +67341,16 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 160 /* Parameter */ && n.parent === constructorDecl; }); + return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 161 /* Parameter */ && n.parent === constructorDecl; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 203 /* CallExpression */ && node.parent.expression === node; + var isCallExpression = node.parent.kind === 204 /* CallExpression */ && node.parent.expression === node; var immediateContainer = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var container = immediateContainer; var needToCaptureLexicalThis = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - while (container && container.kind === 209 /* ArrowFunction */) { + while (container && container.kind === 210 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } @@ -65326,14 +67363,14 @@ var ts; // class B { // [super.foo()]() {} // } - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 158 /* ComputedPropertyName */; }); - if (current && current.kind === 158 /* ComputedPropertyName */) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 159 /* ComputedPropertyName */; }); + if (current && current.kind === 159 /* ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 200 /* ObjectLiteralExpression */)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 201 /* ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -65341,7 +67378,7 @@ var ts; } return errorType; } - if (!isCallExpression && immediateContainer.kind === 166 /* Constructor */) { + if (!isCallExpression && immediateContainer.kind === 167 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } if (ts.hasSyntacticModifier(container, 32 /* Static */) || isCallExpression) { @@ -65410,7 +67447,7 @@ var ts; // 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 === 165 /* MethodDeclaration */ && ts.hasSyntacticModifier(container, 256 /* Async */)) { + if (container.kind === 166 /* MethodDeclaration */ && ts.hasSyntacticModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } @@ -65424,7 +67461,7 @@ var ts; // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 200 /* ObjectLiteralExpression */) { + if (container.parent.kind === 201 /* ObjectLiteralExpression */) { if (languageVersion < 2 /* ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return errorType; @@ -65445,7 +67482,7 @@ var ts; if (!baseClassType) { return errorType; } - if (container.kind === 166 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 167 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return errorType; @@ -65460,7 +67497,7 @@ var ts; if (isCallExpression) { // TS 1.0 SPEC (April 2014): 4.8.1 // Super calls are only permitted in constructors of derived classes - return container.kind === 166 /* Constructor */; + return container.kind === 167 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -65468,21 +67505,21 @@ var ts; // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance // - In a static member function or static member accessor // topmost container must be something that is directly nested in the class declaration\object literal expression - if (ts.isClassLike(container.parent) || container.parent.kind === 200 /* ObjectLiteralExpression */) { + if (ts.isClassLike(container.parent) || container.parent.kind === 201 /* ObjectLiteralExpression */) { if (ts.hasSyntacticModifier(container, 32 /* Static */)) { - return container.kind === 165 /* MethodDeclaration */ || - container.kind === 164 /* MethodSignature */ || - container.kind === 167 /* GetAccessor */ || - container.kind === 168 /* SetAccessor */; + return container.kind === 166 /* MethodDeclaration */ || + container.kind === 165 /* MethodSignature */ || + container.kind === 168 /* GetAccessor */ || + container.kind === 169 /* SetAccessor */; } else { - return container.kind === 165 /* MethodDeclaration */ || - container.kind === 164 /* MethodSignature */ || - container.kind === 167 /* GetAccessor */ || - container.kind === 168 /* SetAccessor */ || - container.kind === 163 /* PropertyDeclaration */ || - container.kind === 162 /* PropertySignature */ || - container.kind === 166 /* Constructor */; + return container.kind === 166 /* MethodDeclaration */ || + container.kind === 165 /* MethodSignature */ || + container.kind === 168 /* GetAccessor */ || + container.kind === 169 /* SetAccessor */ || + container.kind === 164 /* PropertyDeclaration */ || + container.kind === 163 /* PropertySignature */ || + container.kind === 167 /* Constructor */; } } } @@ -65490,10 +67527,10 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 165 /* MethodDeclaration */ || - func.kind === 167 /* GetAccessor */ || - func.kind === 168 /* SetAccessor */) && func.parent.kind === 200 /* ObjectLiteralExpression */ ? func.parent : - func.kind === 208 /* FunctionExpression */ && func.parent.kind === 288 /* PropertyAssignment */ ? func.parent.parent : + return (func.kind === 166 /* MethodDeclaration */ || + func.kind === 168 /* GetAccessor */ || + func.kind === 169 /* SetAccessor */) && func.parent.kind === 201 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 209 /* FunctionExpression */ && func.parent.kind === 289 /* PropertyAssignment */ ? func.parent.parent : undefined; } function getThisTypeArgument(type) { @@ -65505,7 +67542,7 @@ var ts; }); } function getContextualThisParameterType(func) { - if (func.kind === 209 /* ArrowFunction */) { + if (func.kind === 210 /* ArrowFunction */) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -65532,7 +67569,7 @@ var ts; if (thisType) { return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral))); } - if (literal.parent.kind !== 288 /* PropertyAssignment */) { + if (literal.parent.kind !== 289 /* PropertyAssignment */) { break; } literal = literal.parent.parent; @@ -65546,7 +67583,7 @@ var ts; // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. var parent = ts.walkUpParenthesizedExpressions(func.parent); - if (parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) { + if (parent.kind === 217 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) { var target = parent.left; if (ts.isAccessExpression(target)) { var expression = target.expression; @@ -65599,11 +67636,11 @@ var ts; return getTypeFromTypeNode(typeNode); } switch (declaration.kind) { - case 160 /* Parameter */: + case 161 /* Parameter */: return getContextuallyTypedParameterType(declaration); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return getContextualTypeForBindingElement(declaration); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: if (ts.hasSyntacticModifier(declaration, 32 /* Static */)) { return getContextualTypeForStaticPropertyDeclaration(declaration); } @@ -65614,10 +67651,10 @@ var ts; var parent = declaration.parent.parent; var name = declaration.propertyName || declaration.name; var parentType = getContextualTypeForVariableLikeDeclaration(parent) || - parent.kind !== 198 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent); + parent.kind !== 199 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent); if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name)) return undefined; - if (parent.name.kind === 197 /* ArrayBindingPattern */) { + if (parent.name.kind === 198 /* ArrayBindingPattern */) { var index = ts.indexOfNode(declaration.parent.elements, declaration); if (index < 0) return undefined; @@ -65754,7 +67791,7 @@ var ts; return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 205 /* TaggedTemplateExpression */) { + if (template.parent.kind === 206 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -65788,16 +67825,16 @@ var ts; // In an assignment expression, the right operand is contextually typed by the type of the left operand. // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. function getContextualTypeForAssignmentDeclaration(binaryExpression) { + var _a, _b; var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return getTypeOfExpression(binaryExpression.left); + case 4 /* ThisProperty */: + return getContextualTypeForThisPropertyAssignment(binaryExpression); case 5 /* Property */: - case 1 /* ExportsProperty */: - case 6 /* Prototype */: - case 3 /* PrototypeProperty */: if (isPossiblyAliasedThisProperty(binaryExpression, kind)) { - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + return getContextualTypeForThisPropertyAssignment(binaryExpression); } // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. // See `bindStaticPropertyAssignment` in `binder.ts`. @@ -65818,11 +67855,11 @@ var ts; var id = lhs.expression; var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true); if (parentSymbol) { - var annotated = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); - if (annotated) { + var annotated_1 = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated_1) { var nameStr = ts.getElementOrPropertyAccessName(lhs); if (nameStr !== undefined) { - return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr); + return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated_1), nameStr); } } return undefined; @@ -65830,9 +67867,15 @@ var ts; } return ts.isInJSFile(decl) ? undefined : getTypeOfExpression(binaryExpression.left); } + case 1 /* ExportsProperty */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + var valueDeclaration = (_a = binaryExpression.left.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration; + // falls through case 2 /* ModuleExports */: - case 4 /* ThisProperty */: - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + valueDeclaration || (valueDeclaration = (_b = binaryExpression.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration); + var annotated = valueDeclaration && ts.getEffectiveTypeAnnotationNode(valueDeclaration); + return annotated ? getTypeFromTypeNode(annotated) : undefined; case 7 /* ObjectDefinePropertyValue */: case 8 /* ObjectDefinePropertyExports */: case 9 /* ObjectDefinePrototypeProperty */: @@ -65853,7 +67896,7 @@ var ts; var symbol = resolveName(declaration.left, name, 111551 /* Value */, undefined, undefined, /*isUse*/ true, /*excludeGlobals*/ true); return ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration); } - function getContextualTypeForThisPropertyAssignment(binaryExpression, kind) { + function getContextualTypeForThisPropertyAssignment(binaryExpression) { if (!binaryExpression.symbol) return getTypeOfExpression(binaryExpression.left); if (binaryExpression.symbol.valueDeclaration) { @@ -65865,8 +67908,6 @@ var ts; } } } - if (kind === 2 /* ModuleExports */) - return undefined; var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression); if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { return undefined; @@ -65921,9 +67962,13 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + if (propertyAssignmentType) { + return propertyAssignmentType; + } var type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { - if (!hasNonBindableDynamicName(element)) { + if (hasBindableName(element)) { // 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. @@ -66009,19 +68054,19 @@ var ts; case 78 /* Identifier */: case 150 /* UndefinedKeyword */: return true; - case 201 /* PropertyAccessExpression */: - case 207 /* ParenthesizedExpression */: + case 202 /* PropertyAccessExpression */: + case 208 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); - case 283 /* JsxExpression */: + case 284 /* 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 === 288 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 289 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 280 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. @@ -66032,15 +68077,9 @@ var ts; var instantiatedType = instantiateContextualType(contextualType, node, contextFlags); if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) { var apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true); - if (apparentType.flags & 1048576 /* Union */) { - if (ts.isObjectLiteralExpression(node)) { - return discriminateContextualTypeByObjectMembers(node, apparentType); - } - else if (ts.isJsxAttributes(node)) { - return discriminateContextualTypeByJSXAttributes(node, apparentType); - } - } - return apparentType; + return apparentType.flags & 1048576 /* Union */ && ts.isObjectLiteralExpression(node) ? discriminateContextualTypeByObjectMembers(node, apparentType) : + apparentType.flags & 1048576 /* Union */ && ts.isJsxAttributes(node) ? discriminateContextualTypeByJSXAttributes(node, apparentType) : + apparentType; } } // If the given contextual type contains instantiable types and if a mapper representing @@ -66107,58 +68146,60 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 198 /* BindingElement */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 199 /* BindingElement */: return getContextualTypeForInitializerExpression(node, contextFlags); - case 209 /* ArrowFunction */: - case 242 /* ReturnStatement */: + case 210 /* ArrowFunction */: + case 243 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return getContextualTypeForAwaitOperand(parent, contextFlags); - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (parent.expression.kind === 99 /* ImportKeyword */) { return stringType; } /* falls through */ - case 204 /* NewExpression */: + case 205 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return ts.isConstTypeReference(parent.type) ? tryFindWhenConstTypeReference(parent) : getTypeFromTypeNode(parent.type); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node, contextFlags); - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent, contextFlags); - case 290 /* SpreadAssignment */: - return getApparentTypeOfContextualType(parent.parent, contextFlags); - case 199 /* ArrayLiteralExpression */: { + case 291 /* SpreadAssignment */: + return getContextualType(parent.parent, contextFlags); + case 200 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node, contextFlags); - case 228 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 218 /* TemplateExpression */); + case 229 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 219 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 207 /* ParenthesizedExpression */: { + case 208 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags); } - case 283 /* JsxExpression */: + case 226 /* NonNullExpression */: + return getContextualType(parent, contextFlags); + case 284 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); - case 280 /* JsxAttribute */: - case 282 /* JsxSpreadAttribute */: + case 281 /* JsxAttribute */: + case 283 /* JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent); - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent, contextFlags); } return undefined; @@ -66194,14 +68235,14 @@ var ts; return propsType; } function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { - if (sig.unionSignatures) { + if (sig.compositeSignatures) { // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature, // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur // for a union signature). It's an unfortunate quirk of looking in the output of the signature for the type we want to use for the input. // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane. var results = []; - for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) { + for (var _i = 0, _a = sig.compositeSignatures; _i < _a.length; _i++) { var signature = _a[_i]; var instance = getReturnTypeOfSignature(signature); if (isTypeAny(instance)) { @@ -66213,7 +68254,7 @@ var ts; } results.push(propType); } - return getIntersectionType(results); + return getIntersectionType(results); // Same result for both union and intersection signatures } var instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); @@ -66238,16 +68279,19 @@ var ts; function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { var managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { - var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); // fetches interface type, or initializes symbol links type parmaeters var ctorType = getStaticTypeOfReferencedJsxConstructor(context); + if (managedSym.flags & 524288 /* TypeAlias */) { + var params = getSymbolLinks(managedSym).typeParameters; + if (ts.length(params) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], params, 2, ts.isInJSFile(context)); + return getTypeAliasInstantiation(managedSym, args); + } + } if (ts.length(declaredManagedType.typeParameters) >= 2) { var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } - else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); - return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); - } } return attributesType; } @@ -66292,16 +68336,93 @@ var ts; return apparentAttributesType; } } + function getIntersectedSignatures(signatures) { + return ts.getStrictOptionValue(compilerOptions, "noImplicitAny") + ? ts.reduceLeft(signatures, function (left, right) { + return left === right || !left ? left + : compareTypeParametersIdentical(left.typeParameters, right.typeParameters) ? combineSignaturesOfIntersectionMembers(left, right) + : undefined; + }) + : undefined; + } + function combineIntersectionThisParam(left, right, mapper) { + if (!left || !right) { + return left || right; + } + // A signature `this` type might be a read or a write position... It's very possible that it should be invariant + // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be + // pessimistic when contextual typing, for now, we'll union the `this` types. + var thisType = getUnionType([getTypeOfSymbol(left), instantiateType(getTypeOfSymbol(right), mapper)]); + return createSymbolWithType(left, thisType); + } + function combineIntersectionParameters(left, right, mapper) { + var leftCount = getParameterCount(left); + var rightCount = getParameterCount(right); + var longest = leftCount >= rightCount ? left : right; + var shorter = longest === left ? right : left; + var longestCount = longest === left ? leftCount : rightCount; + var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right)); + var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest); + var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0)); + for (var i = 0; i < longestCount; i++) { + var longestParamType = tryGetTypeAtPosition(longest, i); + if (longest === right) { + longestParamType = instantiateType(longestParamType, mapper); + } + var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType; + if (shorter === right) { + shorterParamType = instantiateType(shorterParamType, mapper); + } + var unionParamType = getUnionType([longestParamType, shorterParamType]); + var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1); + var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter); + var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i); + var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i); + var paramName = leftName === rightName ? leftName : + !leftName ? rightName : + !rightName ? leftName : + undefined; + var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg" + i); + paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType; + params[i] = paramSymbol; + } + if (needsExtraRestElement) { + var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args"); + restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount)); + if (shorter === right) { + restParamSymbol.type = instantiateType(restParamSymbol.type, mapper); + } + params[longestCount] = restParamSymbol; + } + return params; + } + function combineSignaturesOfIntersectionMembers(left, right) { + var typeParams = left.typeParameters || right.typeParameters; + var paramMapper; + if (left.typeParameters && right.typeParameters) { + paramMapper = createTypeMapper(right.typeParameters, left.typeParameters); + // We just use the type parameter defaults from the first signature + } + var declaration = left.declaration; + var params = combineIntersectionParameters(left, right, paramMapper); + var thisParam = combineIntersectionThisParam(left.thisParameter, right.thisParameter, paramMapper); + var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); + var result = createSignature(declaration, typeParams, thisParam, params, + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 39 /* PropagatingFlags */); + result.compositeKind = 2097152 /* Intersection */; + result.compositeSignatures = ts.concatenate(left.compositeKind === 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); + if (paramMapper) { + result.mapper = left.compositeKind === 2097152 /* Intersection */ && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; + } + return result; + } // If the given type is an object or union type with a single signature, and if that signature has at // least as many parameters as the given function, return the signature. Otherwise return undefined. function getContextualCallSignature(type, node) { var signatures = getSignaturesOfType(type, 0 /* Call */); - if (signatures.length === 1) { - var signature = signatures[0]; - if (!isAritySmaller(signature, node)) { - return signature; - } - } + var applicableByArity = ts.filter(signatures, function (s) { return !isAritySmaller(s, node); }); + return applicableByArity.length === 1 ? applicableByArity[0] : getIntersectedSignatures(applicableByArity); } /** If the contextual signature has fewer parameters than the function expression, do not use it */ function isAritySmaller(signature, target) { @@ -66318,7 +68439,7 @@ var ts; return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 208 /* FunctionExpression */ || node.kind === 209 /* ArrowFunction */; + return node.kind === 209 /* FunctionExpression */ || node.kind === 210 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -66332,7 +68453,7 @@ var ts; // all identical ignoring their return type, the result is same signature but with return type as // union type of return types from these signatures function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var typeTagSignature = getSignatureOfTypeTag(node); if (typeTagSignature) { return typeTagSignature; @@ -66380,8 +68501,8 @@ var ts; return node.isSpread ? getIndexedAccessType(node.type, numberType) : node.type; } function hasDefaultValue(node) { - return (node.kind === 198 /* BindingElement */ && !!node.initializer) || - (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */); + return (node.kind === 199 /* BindingElement */ && !!node.initializer) || + (node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */); } function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; @@ -66393,7 +68514,7 @@ var ts; var inConstContext = isConstContext(node); for (var i = 0; i < elementCount; i++) { var e = elements[i]; - if (e.kind === 220 /* SpreadElement */) { + if (e.kind === 221 /* SpreadElement */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */); } @@ -66436,7 +68557,7 @@ var ts; if (inDestructuringPattern) { return createTupleType(elementTypes, elementFlags); } - if (forceTuple || inConstContext || contextualType && forEachType(contextualType, isTupleLikeType)) { + if (forceTuple || inConstContext || contextualType && someType(contextualType, isTupleLikeType)) { return createArrayLiteralType(createTupleType(elementTypes, elementFlags, /*readonly*/ inConstContext)); } return createArrayLiteralType(createArrayType(elementTypes.length ? @@ -66450,13 +68571,13 @@ var ts; var literalType = type.literalType; if (!literalType) { literalType = type.literalType = cloneTypeReference(type); - literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + literalType.objectFlags |= 32768 /* ArrayLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; } return literalType; } function isNumericName(name) { switch (name.kind) { - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return isNumericComputedName(name); case 78 /* Identifier */: return isNumericLiteralName(name.escapedText); @@ -66503,6 +68624,20 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); + // The computed property name of a non-static class field within a loop must be stored in a block-scoped binding. + // (It needs to be bound at class evaluation time.) + if (ts.isPropertyDeclaration(node.parent) && !ts.hasStaticModifier(node.parent) && ts.isClassExpression(node.parent.parent)) { + var container = ts.getEnclosingBlockScopeContainer(node.parent.parent); + var enclosingIterationStatement = getEnclosingIterationStatement(container); + if (enclosingIterationStatement) { + // The computed field name will use a block scoped binding which can be unique for each iteration of the loop. + getNodeLinks(enclosingIterationStatement).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + // The generated variable which stores the computed field name must be block-scoped. + getNodeLinks(node).flags |= 524288 /* BlockScopedBindingInLoop */; + // The generated variable which stores the class must be block-scoped. + getNodeLinks(node.parent.parent).flags |= 524288 /* BlockScopedBindingInLoop */; + } + } // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). if (links.resolvedType.flags & 98304 /* Nullable */ || @@ -66510,9 +68645,6 @@ var ts; !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } - else { - checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true); - } } return links.resolvedType; } @@ -66552,7 +68684,7 @@ var ts; var spread = emptyObjectType; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 196 /* ObjectBindingPattern */ || contextualType.pattern.kind === 200 /* ObjectLiteralExpression */); + (contextualType.pattern.kind === 197 /* ObjectBindingPattern */ || contextualType.pattern.kind === 201 /* ObjectLiteralExpression */); var inConstContext = isConstContext(node); var checkFlags = inConstContext ? 8 /* Readonly */ : 0; var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); @@ -66567,7 +68699,7 @@ var ts; // which may never occur. for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; - if (elem.name && ts.isComputedPropertyName(elem.name) && !ts.isWellKnownSymbolSyntactically(elem.name)) { + if (elem.name && ts.isComputedPropertyName(elem.name)) { checkComputedPropertyName(elem.name); } } @@ -66575,16 +68707,16 @@ var ts; for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var memberDecl = _c[_b]; var member = getSymbolOfNode(memberDecl); - var computedNameType = memberDecl.name && memberDecl.name.kind === 158 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + var computedNameType = memberDecl.name && memberDecl.name.kind === 159 /* ComputedPropertyName */ ? checkComputedPropertyName(memberDecl.name) : undefined; - if (memberDecl.kind === 288 /* PropertyAssignment */ || - memberDecl.kind === 289 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 289 /* PropertyAssignment */ || + memberDecl.kind === 290 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { - var type = memberDecl.kind === 288 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + var type = memberDecl.kind === 289 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`. // we don't want to say "could not find 'a'". - memberDecl.kind === 289 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : + memberDecl.kind === 290 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); @@ -66596,7 +68728,7 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) : @@ -66607,8 +68739,8 @@ var ts; if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. - var isOptional = (memberDecl.kind === 288 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 289 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 289 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 290 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216 /* Optional */; } @@ -66634,7 +68766,7 @@ var ts; member = prop; allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop); } - else if (memberDecl.kind === 290 /* SpreadAssignment */) { + else if (memberDecl.kind === 291 /* SpreadAssignment */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } @@ -66646,15 +68778,20 @@ var ts; hasComputedNumberProperty = false; } var type = getReducedType(checkExpression(memberDecl.expression)); - if (!isValidSpreadType(type)) { - error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return errorType; + if (isValidSpreadType(type)) { + if (allPropertiesTable) { + checkSpreadPropOverrides(type, allPropertiesTable, memberDecl); + } + offset = propertiesArray.length; + if (spread === errorType) { + continue; + } + spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext); } - if (allPropertiesTable) { - checkSpreadPropOverrides(type, allPropertiesTable, memberDecl); + else { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + spread = errorType; } - spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext); - offset = propertiesArray.length; continue; } else { @@ -66663,7 +68800,7 @@ var ts; // an ordinary function declaration(section 6.1) with no parameters. // A set accessor declaration is processed in the same manner // as an ordinary function declaration with a single parameter and a Void return type. - ts.Debug.assert(memberDecl.kind === 167 /* GetAccessor */ || memberDecl.kind === 168 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 168 /* GetAccessor */ || memberDecl.kind === 169 /* SetAccessor */); checkNodeDeferred(memberDecl); } if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) { @@ -66688,7 +68825,7 @@ var ts; // type with those properties for which the binding pattern specifies a default value. // If the object literal is spread into another object literal, skip this step and let the top-level object // literal handle it instead. - if (contextualTypeHasPattern && node.parent.kind !== 290 /* SpreadAssignment */) { + if (contextualTypeHasPattern && node.parent.kind !== 291 /* SpreadAssignment */) { for (var _d = 0, _e = getPropertiesOfType(contextualType); _d < _e.length; _d++) { var prop = _e[_d]; if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) { @@ -66700,6 +68837,9 @@ var ts; } } } + if (spread === errorType) { + return errorType; + } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext); @@ -66716,9 +68856,9 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; if (isJSObjectLiteral) { - result.objectFlags |= 16384 /* JSLiteral */; + result.objectFlags |= 8192 /* JSLiteral */; } if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; @@ -66808,14 +68948,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var objectFlags = 4096 /* JsxAttributes */; + var objectFlags = 2048 /* JsxAttributes */; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -66831,7 +68971,7 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 282 /* JsxSpreadAttribute */); + ts.Debug.assert(attributeDecl.kind === 283 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false); attributesTable = ts.createSymbolTable(); @@ -66857,7 +68997,7 @@ var ts; } } // Handle children attribute - var parent = openingLikeElement.parent.kind === 273 /* JsxElement */ ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 274 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = checkJsxChildren(parent, checkMode); @@ -66873,7 +69013,7 @@ var ts; // 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 */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - childrenContextualType && forEachType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : + childrenContextualType && someType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : createArrayType(getUnionType(childrenTypes)); // Fake up a property declaration for the children childrenPropSymbol.valueDeclaration = ts.factory.createPropertySignature(/*modifiers*/ undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined); @@ -66899,7 +69039,7 @@ var ts; function createJsxAttributesType() { objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return result; } } @@ -66914,7 +69054,7 @@ var ts; childrenTypes.push(stringType); } } - else if (child.kind === 283 /* JsxExpression */ && !child.expression) { + else if (child.kind === 284 /* JsxExpression */ && !child.expression) { continue; // empty jsx expressions don't *really* count as present children } else { @@ -67065,7 +69205,7 @@ var ts; else if (propertiesOfJsxElementAttribPropInterface.length === 1) { return propertiesOfJsxElementAttribPropInterface[0].escapedName; } - else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + else if (propertiesOfJsxElementAttribPropInterface.length > 1 && jsxElementAttribPropInterfaceSym.declarations) { // More than one property on ElementAttributesProperty is an error error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer)); } @@ -67175,11 +69315,11 @@ var ts; if (!links.resolvedJsxElementAttributesType) { var symbol = getIntrinsicTagSymbol(node); if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { - return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol) || errorType; } else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { return links.resolvedJsxElementAttributesType = - getIndexTypeOfType(getDeclaredTypeOfSymbol(symbol), 0 /* String */); + getIndexTypeOfType(getJsxType(JsxNames.IntrinsicElements, node), 0 /* String */) || errorType; } else { return links.resolvedJsxElementAttributesType = errorType; @@ -67332,9 +69472,12 @@ var ts; * @param type The type of the object whose property is being accessed. (Not the type of the property.) * @param prop The symbol for the property being accessed. */ - function checkPropertyAccessibility(node, isSuper, type, prop) { - var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 157 /* QualifiedName */ ? node.right : node.kind === 195 /* ImportType */ ? node : node.name; + function checkPropertyAccessibility(node, isSuper, writing, type, prop, reportError) { + if (reportError === void 0) { reportError = true; } + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop, writing); + var errorNode = node.kind === 158 /* QualifiedName */ ? node.right : + node.kind === 196 /* ImportType */ ? node : + node.kind === 199 /* BindingElement */ && node.propertyName ? node.propertyName : node.name; if (isSuper) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or @@ -67345,7 +69488,9 @@ var ts; // a super property access is permitted and must specify a public static member function of the base class. if (languageVersion < 2 /* ES2015 */) { if (symbolHasNonMethodDeclaration(prop)) { - error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + if (reportError) { + error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + } return false; } } @@ -67354,24 +69499,22 @@ var ts; // This error could mask a private property access error. But, a member // cannot simultaneously be private and abstract, so this will trigger an // additional error elsewhere. - error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + if (reportError) { + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + } return false; } } // Referencing abstract properties within their own constructors is not allowed - if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { + if ((flags & 128 /* Abstract */) && symbolHasNonMethodDeclaration(prop) && + (ts.isThisProperty(node) || ts.isThisInitializedObjectBindingExpression(node) || ts.isObjectBindingPattern(node.parent) && ts.isThisInitializedDeclaration(node.parent.parent))) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); 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; - } - } - if (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name)) { - if (!ts.getContainingClass(node)) { - error(errorNode, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + if (reportError) { + 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; } - return true; } // Public properties are otherwise accessible. if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { @@ -67382,7 +69525,9 @@ var ts; if (flags & 8 /* Private */) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + if (reportError) { + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + } return false; } return true; @@ -67396,7 +69541,7 @@ var ts; // of the property as base classes var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + return isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing) ? enclosingClass : undefined; }); // A protected property is accessible if the property is within the declaring class or classes derived from it if (!enclosingClass) { @@ -67404,7 +69549,9 @@ var ts; // static member access is disallow var thisParameter = void 0; if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + if (reportError) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + } return false; } var thisType = getTypeFromTypeNode(thisParameter.type); @@ -67419,7 +69566,9 @@ var ts; type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined } if (!type || !hasBaseType(type, enclosingClass)) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + if (reportError) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2, symbolToString(prop), typeToString(enclosingClass), typeToString(type)); + } return false; } return true; @@ -67475,20 +69624,20 @@ var ts; } return nonNullType; } - function checkPropertyAccessExpression(node) { - return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) : - checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + function checkPropertyAccessExpression(node, checkMode) { + return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node, checkMode) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name, checkMode); } - function checkPropertyAccessChain(node) { + function checkPropertyAccessChain(node, checkMode) { var leftType = checkExpression(node.expression); var nonOptionalType = getOptionalExpressionType(leftType, node.expression); - return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name, checkMode), node, nonOptionalType !== leftType); } - function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); + function checkQualifiedName(node, checkMode) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right, checkMode); } function isMethodAccessForCall(node) { - while (node.parent.kind === 207 /* ParenthesizedExpression */) { + while (node.parent.kind === 208 /* ParenthesizedExpression */) { node = node.parent; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; @@ -67523,14 +69672,13 @@ var ts; } var diagName = diagnosticName(right); if (propertyOnType) { - var typeValueDecl = propertyOnType.valueDeclaration; - var typeClass_1 = ts.getContainingClass(typeValueDecl); - ts.Debug.assert(!!typeClass_1); + var typeValueDecl = ts.Debug.checkDefined(propertyOnType.valueDeclaration); + var typeClass_1 = ts.Debug.checkDefined(ts.getContainingClass(typeValueDecl)); // We found a private identifier property with the same description. // Either: // - There is a lexically scoped private identifier AND it shadows the one we found on the type. // - It is an attempt to access the private identifier outside of the class. - if (lexicallyScopedIdentifier) { + if (lexicallyScopedIdentifier === null || lexicallyScopedIdentifier === void 0 ? void 0 : lexicallyScopedIdentifier.valueDeclaration) { var lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration; var lexicalClass = ts.getContainingClass(lexicalValueDecl); ts.Debug.assert(!!lexicalClass); @@ -67549,17 +69697,42 @@ var ts; return (isConstructorDeclaredProperty(prop) || ts.isThisProperty(node) && isAutoTypedProperty(prop)) && ts.getThisContainer(node, /*includeArrowFunctions*/ true) === getDeclaringConstructor(prop); } - function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right, checkMode) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); - if (ts.isPrivateIdentifier(right)) { - checkExternalEmitHelpers(node, 524288 /* ClassPrivateFieldGet */); - } var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType; var prop; if (ts.isPrivateIdentifier(right)) { + if (languageVersion < 99 /* ESNext */) { + if (assignmentKind !== 0 /* None */) { + checkExternalEmitHelpers(node, 1048576 /* ClassPrivateFieldSet */); + } + if (assignmentKind !== 1 /* Definite */) { + checkExternalEmitHelpers(node, 524288 /* ClassPrivateFieldGet */); + } + } var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right); + if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && ts.isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) { + grammarErrorOnNode(right, ts.Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, ts.idText(right)); + } + if ((lexicallyScopedSymbol === null || lexicallyScopedSymbol === void 0 ? void 0 : lexicallyScopedSymbol.valueDeclaration) && (compilerOptions.target === 99 /* ESNext */ && !useDefineForClassFields)) { + var lexicalClass_1 = ts.getContainingClass(lexicallyScopedSymbol.valueDeclaration); + var parentStaticFieldInitializer = ts.findAncestor(node, function (n) { + if (n === lexicalClass_1) + return "quit"; + if (ts.isPropertyDeclaration(n.parent) && ts.hasStaticModifier(n.parent) && n.parent.initializer === n && n.parent.parent === lexicalClass_1) { + return true; + } + return false; + }); + if (parentStaticFieldInitializer) { + var parentStaticFieldInitializerSymbol = getSymbolOfNode(parentStaticFieldInitializer.parent); + ts.Debug.assert(parentStaticFieldInitializerSymbol, "Initializer without declaration symbol"); + var diagnostic = error(node, ts.Diagnostics.Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false, ts.symbolName(lexicallyScopedSymbol)); + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(parentStaticFieldInitializer.parent, ts.Diagnostics.Initializer_for_property_0, ts.symbolName(parentStaticFieldInitializerSymbol))); + } + } if (isAnyLike) { if (lexicallyScopedSymbol) { return apparentType; @@ -67574,6 +69747,12 @@ var ts; if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) { return errorType; } + else { + var isSetonlyAccessor = prop && prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (isSetonlyAccessor && assignmentKind !== 1 /* Definite */) { + error(node, ts.Diagnostics.Private_accessor_was_defined_without_a_getter); + } + } } else { if (isAnyLike) { @@ -67584,7 +69763,11 @@ var ts; } prop = getPropertyOfType(apparentType, right.escapedText); } - if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums. + // The exceptions are: + // 1. if 'isolatedModules' is enabled, because the const enum value will not be inlined, and + // 2. if 'preserveConstEnums' is enabled and the expression is itself an export, e.g. `export = Foo.Bar.Baz`. + if (ts.isIdentifier(left) && parentSymbol && (compilerOptions.isolatedModules || !(prop && isConstEnumOrConstEnumOnlyModule(prop)) || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) { markAliasReferenced(parentSymbol, node); } var propType; @@ -67617,44 +69800,48 @@ var ts; } } else { - if (getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) { - errorOrSuggestion(/* isError */ false, right, ts.Diagnostics._0_is_deprecated, right.escapedText); + if (prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) { + addDeprecatedSuggestion(right, prop.declarations, right.escapedText); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node, left.kind === 107 /* ThisKeyword */); + markPropertyAsReferenced(prop, node, isSelfTypeAccess(left, parentSymbol)); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left.kind === 105 /* SuperKeyword */, apparentType, prop); + var writing = ts.isWriteAccess(node); + checkPropertyAccessibility(node, left.kind === 105 /* SuperKeyword */, writing, apparentType, prop); if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) { error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } - propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : getConstraintForLocation(getTypeOfSymbol(prop), node); + propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : writing ? getSetAccessorTypeOfSymbol(prop) : getTypeOfSymbol(prop); } - return getFlowTypeOfAccessExpression(node, prop, propType, right); + return getFlowTypeOfAccessExpression(node, prop, propType, right, checkMode); } - function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { + function getFlowTypeOfAccessExpression(node, prop, propType, errorNode, checkMode) { // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. var assignmentKind = ts.getAssignmentTargetKind(node); - if (!ts.isAccessExpression(node) || - assignmentKind === 1 /* Definite */ || - prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { + if (assignmentKind === 1 /* Definite */ || + prop && + !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) + && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */) + && !isDuplicatedCommonJSExport(prop.declarations)) { return propType; } if (propType === autoType) { return getFlowTypeOfProperty(node, prop); } + propType = getNarrowableTypeForReference(propType, node, checkMode); // If strict null checks and strict property initialization checks are enabled, if we have // a this.xxx property access, if the property is an instance property without an initializer, // and if we are in a constructor of the same class as the property declaration, assume that // the property is uninitialized at the top of the control flow. var assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 107 /* ThisKeyword */) { + if (strictNullChecks && strictPropertyInitialization && ts.isAccessExpression(node) && node.expression.kind === 107 /* ThisKeyword */) { var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); - if (flowContainer.kind === 166 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) { + if (flowContainer.kind === 167 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) { assumeUninitialized = true; } } @@ -67681,13 +69868,14 @@ var ts; var diagnosticMessage; var declarationName = ts.idText(right); if (isInPropertyInitializer(node) + && !isOptionalPropertyDeclaration(valueDeclaration) && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) - && !isPropertyDeclaredInAncestorClass(prop)) { + && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } - else if (valueDeclaration.kind === 252 /* ClassDeclaration */ && - node.parent.kind !== 173 /* TypeReference */ && + else if (valueDeclaration.kind === 253 /* ClassDeclaration */ && + node.parent.kind !== 174 /* TypeReference */ && !(valueDeclaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); @@ -67699,22 +69887,22 @@ var ts; function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return true; - case 288 /* PropertyAssignment */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 290 /* SpreadAssignment */: - case 158 /* ComputedPropertyName */: - case 228 /* TemplateSpan */: - case 283 /* JsxExpression */: - case 280 /* JsxAttribute */: - case 281 /* JsxAttributes */: - case 282 /* JsxSpreadAttribute */: - case 275 /* JsxOpeningElement */: - case 223 /* ExpressionWithTypeArguments */: - case 286 /* HeritageClause */: + case 289 /* PropertyAssignment */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 291 /* SpreadAssignment */: + case 159 /* ComputedPropertyName */: + case 229 /* TemplateSpan */: + case 284 /* JsxExpression */: + case 281 /* JsxAttribute */: + case 282 /* JsxAttributes */: + case 283 /* JsxSpreadAttribute */: + case 276 /* JsxOpeningElement */: + case 224 /* ExpressionWithTypeArguments */: + case 287 /* HeritageClause */: return false; default: return ts.isExpressionNode(node) ? false : "quit"; @@ -67786,7 +69974,10 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, missingProperty, container); + var diagnostic = containerSeemsToBeEmptyDomElement(containingType) + ? ts.Diagnostics.Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom + : ts.Diagnostics.Property_0_does_not_exist_on_type_1; + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), diagnostic, missingProperty, container); } } } @@ -67797,9 +69988,14 @@ var ts; } diagnostics.add(resultDiagnostic); } + function containerSeemsToBeEmptyDomElement(containingType) { + return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && + everyContainedType(containingType, function (type) { return type.symbol && /^(EventTarget|Node|((HTML[a-zA-Z]*)?Element))$/.test(ts.unescapeLeadingUnderscores(type.symbol.escapedName)); }) && + isEmptyObjectType(containingType); + } function typeHasStaticProperty(propName, containingType) { var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); - return prop !== undefined && prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */); + return prop !== undefined && !!prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedLibForNonExistentName(name) { var missingName = diagnosticName(name); @@ -67830,7 +70026,15 @@ var ts; } } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 111551 /* Value */); + var props = getPropertiesOfType(containingType); + if (typeof name !== "string") { + var parent_2 = name.parent; + if (ts.isPropertyAccessExpression(parent_2)) { + props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_2, containingType, prop); }); + } + name = ts.idText(name); + } + return getSpellingSuggestionForName(name, props, 111551 /* Value */); } function getSuggestedSymbolForNonexistentJSXAttribute(name, containingType) { var strName = ts.isString(name) ? name : ts.idText(name); @@ -67925,20 +70129,20 @@ var ts; return undefined; } } - function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isSelfTypeAccess) { var valueDeclaration = prop && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration; if (!valueDeclaration) { return; } var hasPrivateModifier = ts.hasEffectiveModifier(valueDeclaration, 8 /* Private */); - var hasPrivateIdentifier = ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name); + var hasPrivateIdentifier = prop.valueDeclaration && ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name); if (!hasPrivateModifier && !hasPrivateIdentifier) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) { return; } - if (isThisAccess) { + if (isSelfTypeAccess) { // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); if (containingMethod && containingMethod.symbol === prop) { @@ -67947,18 +70151,22 @@ var ts; } (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */; } + function isSelfTypeAccess(name, parent) { + return name.kind === 107 /* ThisKeyword */ + || !!parent && ts.isEntityNameExpression(name) && parent === getResolvedSymbol(ts.getFirstIdentifier(name)); + } function isValidPropertyAccess(node, propertyName) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return isValidPropertyAccessWithType(node, node.expression.kind === 105 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); - case 195 /* ImportType */: + case 196 /* ImportType */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind === 201 /* PropertyAccessExpression */ && node.expression.kind === 105 /* SuperKeyword */, property.escapedName, type); + return isValidPropertyAccessWithType(node, node.kind === 202 /* PropertyAccessExpression */ && node.expression.kind === 105 /* SuperKeyword */, property.escapedName, type); // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context. } function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { @@ -67967,11 +70175,11 @@ var ts; } var prop = getPropertyOfType(type, propertyName); if (prop) { - if (ts.isPropertyAccessExpression(node) && prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)) { + if (prop.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration)) { var declClass_1 = ts.getContainingClass(prop.valueDeclaration); return !ts.isOptionalChain(node) && !!ts.findAncestor(node, function (parent) { return parent === declClass_1; }); } - return checkPropertyAccessibility(node, isSuper, type, prop); + return checkPropertyAccessibility(node, isSuper, /*writing*/ false, type, prop, /* reportError */ false); } // In js files properties of unions are allowed in completion return ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); @@ -67981,7 +70189,7 @@ var ts; */ function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 250 /* VariableDeclarationList */) { + if (initializer.kind === 251 /* VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); @@ -68010,7 +70218,7 @@ var ts; var child = expr; var node = expr.parent; while (node) { - if (node.kind === 238 /* ForInStatement */ && + if (node.kind === 239 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -68023,16 +70231,16 @@ var ts; } return false; } - function checkIndexedAccess(node) { - return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) : - checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + function checkIndexedAccess(node, checkMode) { + return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node, checkMode) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression), checkMode); } - function checkElementAccessChain(node) { + function checkElementAccessChain(node, checkMode) { var exprType = checkExpression(node.expression); var nonOptionalType = getOptionalExpressionType(exprType, node.expression); - return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression), checkMode), node, nonOptionalType !== exprType); } - function checkElementAccessExpression(node, exprType) { + function checkElementAccessExpression(node, exprType, checkMode) { var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; var indexExpression = node.argumentExpression; var indexType = checkExpression(indexExpression); @@ -68048,42 +70256,7 @@ var ts; 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) : 0 /* None */; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, /*noUncheckedIndexedAccessCandidate*/ undefined, node, accessFlags | 16 /* ExpressionPosition */) || errorType; - return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); - } - function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { - if (expressionType === errorType) { - // There is already an error, so no need to report one. - return false; - } - if (!ts.isWellKnownSymbolSyntactically(expression)) { - return false; - } - // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) { - if (reportError) { - error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); - } - return false; - } - // The name is Symbol., so make sure Symbol actually resolves to the - // global Symbol object - var leftHandSide = expression.expression; - var leftHandSideSymbol = getResolvedSymbol(leftHandSide); - if (!leftHandSideSymbol) { - return false; - } - var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true); - if (!globalESSymbol) { - // Already errored when we tried to look up the symbol - return false; - } - if (leftHandSideSymbol !== globalESSymbol) { - if (reportError) { - error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); - } - return false; - } - return true; + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, getNodeLinks(node).resolvedSymbol, indexedAccessType, indexExpression, checkMode), node); } function callLikeExpressionMayHaveTypeArguments(node) { return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node); @@ -68094,13 +70267,13 @@ var ts; // This gets us diagnostics for the type arguments and marks them as referenced. ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 205 /* TaggedTemplateExpression */) { + if (node.kind === 206 /* TaggedTemplateExpression */) { checkExpression(node.template); } else if (ts.isJsxOpeningLikeElement(node)) { checkExpression(node.attributes); } - else if (node.kind !== 161 /* Decorator */) { + else if (node.kind !== 162 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -68164,7 +70337,7 @@ var ts; } } function isSpreadArgument(arg) { - return !!arg && (arg.kind === 220 /* SpreadElement */ || arg.kind === 227 /* SyntheticExpression */ && arg.isSpread); + return !!arg && (arg.kind === 221 /* SpreadElement */ || arg.kind === 228 /* SyntheticExpression */ && arg.isSpread); } function getSpreadArgumentIndex(args) { return ts.findIndex(args, isSpreadArgument); @@ -68181,9 +70354,9 @@ var ts; var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments var effectiveParameterCount = getParameterCount(signature); var effectiveMinimumArguments = getMinArgumentCount(signature); - if (node.kind === 205 /* TaggedTemplateExpression */) { + if (node.kind === 206 /* TaggedTemplateExpression */) { argCount = args.length; - if (node.template.kind === 218 /* TemplateExpression */) { + if (node.template.kind === 219 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. @@ -68198,7 +70371,7 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 161 /* Decorator */) { + else if (node.kind === 162 /* Decorator */) { argCount = getDecoratorArgumentCount(node, signature); } else if (ts.isJsxOpeningLikeElement(node)) { @@ -68212,7 +70385,7 @@ var ts; } else if (!node.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(node.kind === 204 /* NewExpression */); + ts.Debug.assert(node.kind === 205 /* NewExpression */); return getMinArgumentCount(signature) === 0; } else { @@ -68287,7 +70460,7 @@ var ts; }); if (!inferenceContext) { applyToReturnTypes(contextualSignature, signature, function (source, target) { - inferTypes(context.inferences, source, target, 64 /* ReturnType */); + inferTypes(context.inferences, source, target, 128 /* ReturnType */); }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); @@ -68298,6 +70471,15 @@ var ts; inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } + function getThisArgumentType(thisArgumentNode) { + if (!thisArgumentNode) { + return voidType; + } + var thisArgumentType = checkExpression(thisArgumentNode); + return ts.isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) : + ts.isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) : + thisArgumentType; + } function inferTypeArguments(node, signature, args, checkMode, context) { if (ts.isJsxOpeningLikeElement(node)) { return inferJsxTypeArguments(node, signature, checkMode, context); @@ -68306,7 +70488,7 @@ var ts; // 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 // return type of 'wrap'. - if (node.kind !== 161 /* Decorator */) { + if (node.kind !== 162 /* Decorator */) { var contextualType = getContextualType(node, ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }) ? 8 /* SkipBindingPatterns */ : 0 /* None */); if (contextualType) { // We clone the inference context to avoid disturbing a resolution in progress for an @@ -68328,7 +70510,7 @@ var ts; instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 64 /* ReturnType */); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* ReturnType */); // Create a type mapper for instantiating generic contextual types using the inferences made // from the return type. We need a separate inference pass here because (a) instantiation of // the source type uses the outer context's return mapper (which excludes inferences made from @@ -68350,12 +70532,11 @@ var ts; var thisType = getThisTypeOfSignature(signature); if (thisType) { var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context.inferences, thisArgumentType, thisType); + inferTypes(context.inferences, getThisArgumentType(thisArgumentNode), thisType); } for (var i = 0; i < argCount; i++) { var arg = args[i]; - if (arg.kind !== 222 /* OmittedExpression */) { + if (arg.kind !== 223 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode); inferTypes(context.inferences, argType, paramType); @@ -68379,7 +70560,7 @@ var ts; 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 getMutableArrayOrTupleType(arg.kind === 227 /* SyntheticExpression */ ? arg.type : + return getMutableArrayOrTupleType(arg.kind === 228 /* SyntheticExpression */ ? arg.type : checkExpressionWithContextualType(arg.expression, restType, context, checkMode)); } } @@ -68389,13 +70570,13 @@ var ts; for (var i = index; i < argCount; i++) { var arg = args[i]; if (isSpreadArgument(arg)) { - var spreadType = arg.kind === 227 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression); + var spreadType = arg.kind === 228 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression); if (isArrayLikeType(spreadType)) { types.push(spreadType); flags.push(8 /* Variadic */); } else { - types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 220 /* SpreadElement */ ? arg.expression : arg)); + types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 221 /* SpreadElement */ ? arg.expression : arg)); flags.push(4 /* Rest */); } } @@ -68406,7 +70587,7 @@ var ts; types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); flags.push(1 /* Required */); } - if (arg.kind === 227 /* SyntheticExpression */ && arg.tupleNameSource) { + if (arg.kind === 228 /* SyntheticExpression */ && arg.tupleNameSource) { names.push(arg.tupleNameSource); } } @@ -68550,24 +70731,12 @@ var ts; return undefined; } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 204 /* NewExpression */) { + if (thisType && thisType !== voidType && node.kind !== 205 /* NewExpression */) { // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = void 0; - if (thisArgumentNode) { - thisArgumentType = checkExpression(thisArgumentNode); - if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { - thisArgumentType = getNonNullableType(thisArgumentType); - } - else if (ts.isOptionalChain(thisArgumentNode.parent)) { - thisArgumentType = removeOptionalTypeMarker(thisArgumentType); - } - } - else { - thisArgumentType = voidType; - } + var thisArgumentType = getThisArgumentType(thisArgumentNode); var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -68580,7 +70749,7 @@ var ts; var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { var arg = args[i]; - if (arg.kind !== 222 /* OmittedExpression */) { + if (arg.kind !== 223 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode); // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive), @@ -68625,7 +70794,7 @@ var ts; * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. */ function getThisArgumentOfCall(node) { - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { var callee = ts.skipOuterExpressions(node.expression); if (ts.isAccessExpression(callee)) { return callee.expression; @@ -68642,17 +70811,17 @@ var ts; * Returns the effective arguments for an expression that works like a function invocation. */ function getEffectiveCallArguments(node) { - if (node.kind === 205 /* TaggedTemplateExpression */) { + if (node.kind === 206 /* TaggedTemplateExpression */) { var template = node.template; var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; - if (template.kind === 218 /* TemplateExpression */) { + if (template.kind === 219 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_3.push(span.expression); }); } return args_3; } - if (node.kind === 161 /* Decorator */) { + if (node.kind === 162 /* Decorator */) { return getEffectiveDecoratorArguments(node); } if (ts.isJsxOpeningLikeElement(node)) { @@ -68663,10 +70832,10 @@ var ts; if (spreadIndex >= 0) { // Create synthetic arguments from spreads of tuple types. var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_20 = function (i) { + var _loop_21 = function (i) { var arg = args[i]; // We can call checkExpressionCached because spread expressions never have a contextual type. - var spreadType = arg.kind === 220 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); + var spreadType = arg.kind === 221 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); if (spreadType && isTupleType(spreadType)) { ts.forEach(getTypeArguments(spreadType), function (t, i) { var _a; @@ -68680,7 +70849,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_20(i); + _loop_21(i); } return effectiveArgs_1; } @@ -68693,30 +70862,30 @@ var ts; var parent = node.parent; var expr = node.expression; switch (parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* 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 160 /* Parameter */: + case 161 /* 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 === 166 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, parent.parent.kind === 167 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), createSyntheticExpression(expr, anyType), createSyntheticExpression(expr, numberType) ]; - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* 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 !== 163 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + var hasPropDesc = parent.kind !== 164 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; return [ createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), @@ -68730,17 +70899,17 @@ var ts; */ function getDecoratorArgumentCount(node, signature) { switch (node.parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return 1; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return 2; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* 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 160 /* Parameter */: + case 161 /* Parameter */: return 3; default: return ts.Debug.fail(); @@ -68786,77 +70955,66 @@ var ts; return constructorSymbol === globalPromiseSymbol; } function getArgumentArityError(node, signatures, args) { - var min = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - var belowArgCount = Number.NEGATIVE_INFINITY; - var aboveArgCount = Number.POSITIVE_INFINITY; - var argCount = args.length; + var _a; + var spreadIndex = getSpreadArgumentIndex(args); + if (spreadIndex > -1) { + return ts.createDiagnosticForNode(args[spreadIndex], ts.Diagnostics.A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter); + } + var min = Number.POSITIVE_INFINITY; // smallest parameter count + var max = Number.NEGATIVE_INFINITY; // largest parameter count + var maxBelow = Number.NEGATIVE_INFINITY; // largest parameter count that is smaller than the number of arguments + var minAbove = Number.POSITIVE_INFINITY; // smallest parameter count that is larger than the number of arguments var closestSignature; for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { var sig = signatures_8[_i]; - var minCount = getMinArgumentCount(sig); - var maxCount = getParameterCount(sig); - if (minCount < argCount && minCount > belowArgCount) - belowArgCount = minCount; - if (argCount < maxCount && maxCount < aboveArgCount) - aboveArgCount = maxCount; - if (minCount < min) { - min = minCount; + var minParameter = getMinArgumentCount(sig); + var maxParameter = getParameterCount(sig); + // smallest/largest parameter counts + if (minParameter < min) { + min = minParameter; closestSignature = sig; } - max = Math.max(max, maxCount); + max = Math.max(max, maxParameter); + // shortest parameter count *longer than the call*/longest parameter count *shorter than the call* + if (minParameter < args.length && minParameter > maxBelow) + maxBelow = minParameter; + if (args.length < maxParameter && maxParameter < minAbove) + minAbove = maxParameter; } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); - var paramRange = hasRestParameter ? min : - min < max ? min + "-" + max : - min; - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var spanArray; - var related; - var error = hasRestParameter || hasSpreadArgument ? - hasRestParameter && hasSpreadArgument ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - paramRange === 1 && argCount === 0 && isPromiseResolveArityError(node) ? - ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : - ts.Diagnostics.Expected_0_arguments_but_got_1; - if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { - var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; - if (paramDecl) { - related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : - ts.isRestParameter(paramDecl) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined); - } - } - if (min < argCount && argCount < max) { - return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); - } - if (!hasSpreadArgument && argCount < min) { - var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1; - } - if (hasRestParameter || hasSpreadArgument) { - spanArray = ts.factory.createNodeArray(args); - if (hasSpreadArgument && argCount) { - var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined; - spanArray = ts.factory.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1))); + var parameterRange = hasRestParameter ? min + : min < max ? min + "-" + max + : min; + var error = hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 + : parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node) ? ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise + : ts.Diagnostics.Expected_0_arguments_but_got_1; + if (min < args.length && args.length < max) { + // between min and max, but with no matching overload + return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove); + } + else if (args.length < min) { + // too short: put the error span on the call expression, not any of the args + var diagnostic = getDiagnosticForCallNode(node, error, parameterRange, args.length); + var parameter = (_a = closestSignature === null || closestSignature === void 0 ? void 0 : closestSignature.declaration) === null || _a === void 0 ? void 0 : _a.parameters[closestSignature.thisParameter ? args.length + 1 : args.length]; + if (parameter) { + var parameterError = ts.createDiagnosticForNode(parameter, ts.isBindingPattern(parameter.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided + : ts.isRestParameter(parameter) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided + : ts.Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : !ts.isBindingPattern(parameter.name) ? ts.idText(ts.getFirstIdentifier(parameter.name)) : undefined); + return ts.addRelatedInfo(diagnostic, parameterError); } + return diagnostic; } else { - spanArray = ts.factory.createNodeArray(args.slice(max)); - } - var pos = ts.first(spanArray).pos; - var end = ts.last(spanArray).end; - if (end === pos) { - end++; + // too long; error goes on the excess parameters + var errorSpan = ts.factory.createNodeArray(args.slice(max)); + var pos = ts.first(errorSpan).pos; + var end = ts.last(errorSpan).end; + if (end === pos) { + end++; + } + ts.setTextRangePosEnd(errorSpan, pos, end); + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), errorSpan, error, parameterRange, args.length); } - ts.setTextRangePosEnd(spanArray, pos, end); - var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var argCount = typeArguments.length; @@ -68887,8 +71045,8 @@ var ts; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) { - var isTaggedTemplate = node.kind === 205 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 161 /* Decorator */; + var isTaggedTemplate = node.kind === 206 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 162 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var reportErrors = !candidatesOutArray && produceDiagnostics; var typeArguments; @@ -68950,7 +71108,7 @@ var ts; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 203 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 204 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -69004,7 +71162,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_21 = function (c) { + var _loop_22 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2); if (diags_2) { @@ -69022,7 +71180,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_21(c); + _loop_22(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); @@ -69180,7 +71338,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_22 = function (i) { + var _loop_23 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -69188,7 +71346,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_22(i); + _loop_23(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* None */; @@ -69380,7 +71538,7 @@ var ts; function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have no common signatures. return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) || - !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & 1048576 /* Union */) && !(getReducedType(apparentFuncType).flags & 131072 /* Never */) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray, checkMode) { if (node.arguments && languageVersion < 1 /* ES5 */) { @@ -69495,7 +71653,7 @@ var ts; var declaration = signature.declaration; var modifiers = ts.getSelectedEffectiveModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */); // (1) Public constructors and (2) constructor functions are always accessible. - if (!modifiers || declaration.kind !== 166 /* Constructor */) { + if (!modifiers || declaration.kind !== 167 /* Constructor */) { return true; } var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol); @@ -69639,16 +71797,16 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 160 /* Parameter */: + case 161 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; default: return ts.Debug.fail(); @@ -69743,16 +71901,16 @@ var ts; } function resolveSignature(node, candidatesOutArray, checkMode) { switch (node.kind) { - case 203 /* CallExpression */: + case 204 /* CallExpression */: return resolveCallExpression(node, candidatesOutArray, checkMode); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return resolveNewExpression(node, candidatesOutArray, checkMode); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode); - case 161 /* Decorator */: + case 162 /* Decorator */: return resolveDecorator(node, candidatesOutArray, checkMode); - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode); } throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); @@ -69884,7 +72042,7 @@ var ts; return false; } var parent = node.parent; - while (parent && parent.kind === 201 /* PropertyAccessExpression */) { + while (parent && parent.kind === 202 /* PropertyAccessExpression */) { parent = parent.parent; } if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 62 /* EqualsToken */) { @@ -69911,12 +72069,12 @@ var ts; if (node.expression.kind === 105 /* SuperKeyword */) { return voidType; } - if (node.kind === 204 /* NewExpression */) { + if (node.kind === 205 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 166 /* Constructor */ && - declaration.kind !== 170 /* ConstructSignature */ && - declaration.kind !== 175 /* ConstructorType */ && + declaration.kind !== 167 /* Constructor */ && + declaration.kind !== 171 /* ConstructSignature */ && + declaration.kind !== 176 /* ConstructorType */ && !ts.isJSDocConstructSignature(declaration) && !isJSConstructor(declaration)) { // When resolved signature is a call signature (and not a construct signature) the result type is any @@ -69936,7 +72094,7 @@ var ts; if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } - if (node.kind === 203 /* CallExpression */ && node.parent.kind === 233 /* ExpressionStatement */ && + if (node.kind === 204 /* CallExpression */ && !node.questionDotToken && node.parent.kind === 234 /* ExpressionStatement */ && returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) { if (!ts.isDottedName(node.expression)) { error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name); @@ -69950,7 +72108,7 @@ var ts; var jsSymbol = getSymbolOfExpando(node, /*allowDeclaration*/ false); if ((_a = jsSymbol === null || jsSymbol === void 0 ? void 0 : jsSymbol.exports) === null || _a === void 0 ? void 0 : _a.size) { var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; + jsAssignmentType.objectFlags |= 8192 /* JSLiteral */; return getIntersectionType([returnType, jsAssignmentType]); } } @@ -69959,26 +72117,27 @@ var ts; function checkDeprecatedSignature(signature, node) { if (signature.declaration && signature.declaration.flags & 134217728 /* Deprecated */) { var suggestionNode = getDeprecatedSuggestionNode(node); - errorOrSuggestion(/*isError*/ false, suggestionNode, ts.Diagnostics._0_is_deprecated, signatureToString(signature)); + var name = ts.tryGetPropertyAccessOrIdentifierToString(ts.getInvokedExpression(node)); + addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature)); } } function getDeprecatedSuggestionNode(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 203 /* CallExpression */: - case 161 /* Decorator */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 162 /* Decorator */: + case 205 /* NewExpression */: return getDeprecatedSuggestionNode(node.expression); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return getDeprecatedSuggestionNode(node.tag); - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return getDeprecatedSuggestionNode(node.tagName); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return node.argumentExpression; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return node.name; - case 173 /* TypeReference */: + case 174 /* TypeReference */: var typeReference = node; return ts.isQualifiedName(typeReference.typeName) ? typeReference.typeName.right : typeReference; default: @@ -70029,10 +72188,11 @@ var ts; return createPromiseReturnType(node, anyType); } function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { + var _a; if (allowSyntheticDefaultImports && type && type !== errorType) { var synthType = type; if (!synthType.syntheticType) { - var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var file = (_a = originalSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); @@ -70070,9 +72230,9 @@ var ts; return false; } var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ - ? 251 /* FunctionDeclaration */ + ? 252 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ - ? 249 /* VariableDeclaration */ + ? 250 /* VariableDeclaration */ : 0 /* Unknown */; if (targetDeclarationKind !== 0 /* Unknown */) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); @@ -70102,19 +72262,19 @@ var ts; case 9 /* BigIntLiteral */: case 109 /* TrueKeyword */: case 94 /* FalseKeyword */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 218 /* TemplateExpression */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 219 /* TemplateExpression */: return true; - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isValidConstAssertionArgument(node.expression); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: var op = node.operator; var arg = node.operand; return op === 40 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) || op === 39 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: var expr = node.expression; if (ts.isIdentifier(expr)) { var symbol = getSymbolAtLocation(expr); @@ -70170,7 +72330,7 @@ var ts; error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return errorType; } - else if (container.kind === 166 /* Constructor */) { + else if (container.kind === 167 /* Constructor */) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -70217,7 +72377,7 @@ var ts; return restParameter.escapedName; } function isValidDeclarationForTupleLabel(d) { - return d.kind === 192 /* NamedTupleMember */ || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name)); + return d.kind === 193 /* NamedTupleMember */ || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name)); } function getNameableDeclarationAtPosition(signature, pos) { var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); @@ -70382,7 +72542,14 @@ var ts; } } function assignContextualParameterTypes(signature, context) { - signature.typeParameters = context.typeParameters; + if (context.typeParameters) { + if (!signature.typeParameters) { + signature.typeParameters = context.typeParameters; + } + else { + return; // This signature has already has a contextual inference performed and cached on it! + } + } if (context.thisParameter) { var parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { @@ -70493,7 +72660,7 @@ var ts; var yieldType; var nextType; var fallbackReturnType = voidType; - if (func.body.kind !== 230 /* Block */) { // Async or normal arrow function + if (func.body.kind !== 231 /* Block */) { // Async or normal arrow function returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */); if (isAsync) { // From within an async function you can return either a non-promise value or a promise. Any @@ -70678,7 +72845,7 @@ var ts; return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node)); } function computeExhaustiveSwitchStatement(node) { - if (node.expression.kind === 211 /* TypeOfExpression */) { + if (node.expression.kind === 212 /* TypeOfExpression */) { var operandType = getTypeOfExpression(node.expression.expression); var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); // notEqualFacts states that the type of the switched value is not equal to every type in the switch. @@ -70741,11 +72908,11 @@ var ts; } function mayReturnNever(func) { switch (func.kind) { - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; - case 165 /* MethodDeclaration */: - return func.parent.kind === 200 /* ObjectLiteralExpression */; + case 166 /* MethodDeclaration */: + return func.parent.kind === 201 /* ObjectLiteralExpression */; default: return false; } @@ -70771,21 +72938,21 @@ var ts; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (func.kind === 164 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 230 /* Block */ || !functionHasImplicitReturn(func)) { + if (func.kind === 165 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 231 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */; + var errorNode = ts.getEffectiveReturnTypeNode(func) || func; if (type && type.flags & 131072 /* Never */) { - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + error(errorNode, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (type && !hasExplicitReturn) { // minimal check: function has syntactic return type annotation and no explicit return statements in the body // this function does not conform to the specification. - // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + error(errorNode, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) { - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + error(errorNode, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); } else if (compilerOptions.noImplicitReturns) { if (!type) { @@ -70800,11 +72967,11 @@ var ts; return; } } - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + error(errorNode, ts.Diagnostics.Not_all_code_paths_return_a_value); } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) { @@ -70820,7 +72987,7 @@ var ts; var returnType = getReturnTypeFromBody(node, checkMode); var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); - returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */; + returnOnlyType.objectFlags |= 524288 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; } } @@ -70828,7 +72995,7 @@ var ts; } // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 208 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 209 /* FunctionExpression */) { checkGrammarForGenerator(node); } contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -70874,7 +73041,7 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnType = getReturnTypeFromAnnotation(node); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); @@ -70887,7 +73054,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 230 /* Block */) { + if (node.body.kind === 231 /* Block */) { checkSourceElement(node.body); } else { @@ -70977,7 +73144,7 @@ var ts; expr.expression.kind === 107 /* ThisKeyword */) { // Look for if this is the constructor for the class that `symbol` is a property of. var ctor = ts.getContainingFunction(expr); - if (!(ctor && (ctor.kind === 166 /* Constructor */ || isJSConstructor(ctor)))) { + if (!(ctor && (ctor.kind === 167 /* Constructor */ || isJSConstructor(ctor)))) { return true; } if (symbol.valueDeclaration) { @@ -71002,7 +73169,7 @@ var ts; var symbol_2 = getNodeLinks(node).resolvedSymbol; if (symbol_2.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol_2); - return !!declaration && declaration.kind === 263 /* NamespaceImport */; + return !!declaration && declaration.kind === 264 /* NamespaceImport */; } } } @@ -71083,7 +73250,7 @@ var ts; var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); var func = ts.getContainingFunction(node); - if (func && func.kind !== 166 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { + if (func && func.kind !== 167 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); ts.addRelatedInfo(diagnostic, relatedInfo); } @@ -71250,14 +73417,33 @@ var ts; rightType = checkNonNullType(rightType, right); // TypeScript 1.0 spec (April 2014): 4.15.5 // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, - // and the right operand to be of type Any, an object type, or a type parameter type. + // and the right operand to be + // + // 1. assignable to the non-primitive type, + // 2. an unconstrained type parameter, + // 3. a union or intersection including one or more type parameters, whose constituents are all assignable to the + // the non-primitive type, or are unconstrainted type parameters, or have constraints assignable to the + // non-primitive type, or + // 4. a type parameter whose constraint is + // i. an object type, + // ii. the non-primitive type, or + // iii. a union or intersection with at least one constituent assignable to an object or non-primitive type. + // + // The divergent behavior for type parameters and unions containing type parameters is a workaround for type + // parameters not being narrowable. If the right operand is a concrete type, we can error if there is any chance + // it is a primitive. But if the operand is a type parameter, it cannot be narrowed, so we don't issue an error + // unless *all* instantiations would result in an error. + // // The result is always of the Boolean primitive type. if (!(allTypesAssignableToKind(leftType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) || isTypeAssignableToKind(leftType, 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */ | 262144 /* TypeParameter */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { - error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + var rightTypeConstraint = getConstraintOfType(rightType); + if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */) || + rightTypeConstraint && (isTypeAssignableToKind(rightType, 3145728 /* UnionOrIntersection */) && !allTypesAssignableToKind(rightTypeConstraint, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */) || + !maybeTypeOfKind(rightTypeConstraint, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */))) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_not_be_a_primitive); } return booleanType; } @@ -71276,7 +73462,7 @@ var ts; if (rightIsThis === void 0) { rightIsThis = false; } var properties = node.properties; var property = properties[propertyIndex]; - if (property.kind === 288 /* PropertyAssignment */ || property.kind === 289 /* ShorthandPropertyAssignment */) { + if (property.kind === 289 /* PropertyAssignment */ || property.kind === 290 /* ShorthandPropertyAssignment */) { var name = property.name; var exprType = getLiteralTypeFromPropertyName(name); if (isTypeUsableAsPropertyName(exprType)) { @@ -71284,14 +73470,14 @@ var ts; var prop = getPropertyOfType(objectLiteralType, text); if (prop) { markPropertyAsReferenced(prop, property, rightIsThis); - checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + checkPropertyAccessibility(property, /*isSuper*/ false, /*writing*/ true, objectLiteralType, prop); } } var elementType = getIndexedAccessType(objectLiteralType, exprType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */); var type = getFlowTypeOfDestructuring(property, elementType); - return checkDestructuringAssignment(property.kind === 289 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); + return checkDestructuringAssignment(property.kind === 290 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } - else if (property.kind === 290 /* SpreadAssignment */) { + else if (property.kind === 291 /* SpreadAssignment */) { if (propertyIndex < properties.length - 1) { error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } @@ -71329,7 +73515,7 @@ var ts; var inBoundsType = compilerOptions.noUncheckedIndexedAccess ? undefined : possiblyOutOfBoundsType; for (var i = 0; i < elements.length; i++) { var type = possiblyOutOfBoundsType; - if (node.elements[i].kind === 220 /* SpreadElement */) { + if (node.elements[i].kind === 221 /* SpreadElement */) { type = inBoundsType = inBoundsType !== null && inBoundsType !== void 0 ? inBoundsType : (checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType); } checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, type, checkMode); @@ -71339,8 +73525,8 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 222 /* OmittedExpression */) { - if (element.kind !== 220 /* SpreadElement */) { + if (element.kind !== 223 /* OmittedExpression */) { + if (element.kind !== 221 /* SpreadElement */) { var indexType = getLiteralType(elementIndex); if (isArrayLikeType(sourceType)) { // We create a synthetic expression so that getIndexedAccessType doesn't get confused @@ -71358,7 +73544,7 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 216 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) { + if (restExpression.kind === 217 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -71374,7 +73560,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; - if (exprOrAssignment.kind === 289 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 290 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove @@ -71390,24 +73576,24 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 216 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) { + if (target.kind === 217 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 200 /* ObjectLiteralExpression */) { + if (target.kind === 201 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } - if (target.kind === 199 /* ArrayLiteralExpression */) { + if (target.kind === 200 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 290 /* SpreadAssignment */ ? + var error = target.parent.kind === 291 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; - var optionalError = target.parent.kind === 290 /* SpreadAssignment */ ? + var optionalError = target.parent.kind === 291 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access; if (checkReferenceExpression(target, error, optionalError)) { @@ -71432,8 +73618,8 @@ var ts; case 78 /* Identifier */: case 10 /* StringLiteral */: case 13 /* RegularExpressionLiteral */: - case 205 /* TaggedTemplateExpression */: - case 218 /* TemplateExpression */: + case 206 /* TaggedTemplateExpression */: + case 219 /* TemplateExpression */: case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: case 9 /* BigIntLiteral */: @@ -71441,27 +73627,27 @@ var ts; case 94 /* FalseKeyword */: case 103 /* NullKeyword */: case 150 /* UndefinedKeyword */: - case 208 /* FunctionExpression */: - case 221 /* ClassExpression */: - case 209 /* ArrowFunction */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 211 /* TypeOfExpression */: - case 225 /* NonNullExpression */: - case 274 /* JsxSelfClosingElement */: - case 273 /* JsxElement */: + case 209 /* FunctionExpression */: + case 222 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 212 /* TypeOfExpression */: + case 226 /* NonNullExpression */: + case 275 /* JsxSelfClosingElement */: + case 274 /* JsxElement */: return true; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: // Unary operators ~, !, +, and - have no side effects. // The rest do. switch (node.operator) { @@ -71473,9 +73659,9 @@ var ts; } return false; // Some forms listed here for clarity - case 212 /* VoidExpression */: // Explicit opt-out - case 206 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 224 /* AsExpression */: // Not SEF, but can produce useful type warnings + case 213 /* VoidExpression */: // Explicit opt-out + case 207 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 225 /* AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } @@ -71483,84 +73669,111 @@ var ts; function isTypeEqualityComparableTo(source, target) { return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } - var CheckBinaryExpressionState; - (function (CheckBinaryExpressionState) { - CheckBinaryExpressionState[CheckBinaryExpressionState["MaybeCheckLeft"] = 0] = "MaybeCheckLeft"; - CheckBinaryExpressionState[CheckBinaryExpressionState["CheckRight"] = 1] = "CheckRight"; - CheckBinaryExpressionState[CheckBinaryExpressionState["FinishCheck"] = 2] = "FinishCheck"; - })(CheckBinaryExpressionState || (CheckBinaryExpressionState = {})); - function checkBinaryExpression(node, checkMode) { - var workStacks = { - expr: [node], - state: [0 /* MaybeCheckLeft */], - leftType: [undefined] + function createCheckBinaryExpression() { + var trampoline = ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState); + return function (node, checkMode) { + var result = trampoline(node, checkMode); + ts.Debug.assertIsDefined(result); + return result; }; - var stackIndex = 0; - var lastResult; - while (stackIndex >= 0) { - node = workStacks.expr[stackIndex]; - switch (workStacks.state[stackIndex]) { - case 0 /* MaybeCheckLeft */: { - if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { - finishInvocation(checkExpression(node.right, checkMode)); - break; - } - checkGrammarNullishCoalesceWithLogicalExpression(node); - var operator = node.operatorToken.kind; - if (operator === 62 /* EqualsToken */ && (node.left.kind === 200 /* ObjectLiteralExpression */ || node.left.kind === 199 /* ArrayLiteralExpression */)) { - finishInvocation(checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 107 /* ThisKeyword */)); - break; - } - advanceState(1 /* CheckRight */); - maybeCheckExpression(node.left); - break; - } - case 1 /* CheckRight */: { - var leftType = lastResult; - workStacks.leftType[stackIndex] = leftType; - var operator = node.operatorToken.kind; - if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) { - if (operator === 55 /* AmpersandAmpersandToken */) { - var parent = ts.walkUpParenthesizedExpressions(node.parent); - checkTestingKnownTruthyCallableType(node.left, leftType, ts.isIfStatement(parent) ? parent.thenStatement : undefined); - } - checkTruthinessOfType(leftType, node.left); + function onEnter(node, state, checkMode) { + if (state) { + state.stackIndex++; + state.skip = false; + setLeftType(state, /*type*/ undefined); + setLastResult(state, /*type*/ undefined); + } + else { + state = { + checkMode: checkMode, + skip: false, + stackIndex: 0, + typeStack: [undefined, undefined], + }; + } + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { + state.skip = true; + setLastResult(state, checkExpression(node.right, checkMode)); + return state; + } + checkGrammarNullishCoalesceWithLogicalExpression(node); + var operator = node.operatorToken.kind; + if (operator === 62 /* EqualsToken */ && (node.left.kind === 201 /* ObjectLiteralExpression */ || node.left.kind === 200 /* ArrayLiteralExpression */)) { + state.skip = true; + setLastResult(state, checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 107 /* ThisKeyword */)); + return state; + } + return state; + } + function onLeft(left, state, _node) { + if (!state.skip) { + return maybeCheckExpression(state, left); + } + } + function onOperator(operatorToken, state, node) { + if (!state.skip) { + var leftType = getLastResult(state); + ts.Debug.assertIsDefined(leftType); + setLeftType(state, leftType); + setLastResult(state, /*type*/ undefined); + var operator = operatorToken.kind; + if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) { + if (operator === 55 /* AmpersandAmpersandToken */) { + var parent = ts.walkUpParenthesizedExpressions(node.parent); + checkTestingKnownTruthyCallableOrAwaitableType(node.left, leftType, ts.isIfStatement(parent) ? parent.thenStatement : undefined); } - advanceState(2 /* FinishCheck */); - maybeCheckExpression(node.right); - break; - } - case 2 /* FinishCheck */: { - var leftType = workStacks.leftType[stackIndex]; - var rightType = lastResult; - finishInvocation(checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node)); - break; + checkTruthinessOfType(leftType, node.left); } - default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for checkBinaryExpression"); } } - return lastResult; - function finishInvocation(result) { - lastResult = result; - stackIndex--; - } - /** - * Note that `advanceState` sets the _current_ head state, and that `maybeCheckExpression` potentially pushes on a new - * head state; so `advanceState` must be called before any `maybeCheckExpression` during a state's execution. - */ - function advanceState(nextState) { - workStacks.state[stackIndex] = nextState; + function onRight(right, state, _node) { + if (!state.skip) { + return maybeCheckExpression(state, right); + } } - function maybeCheckExpression(node) { - if (ts.isBinaryExpression(node)) { - stackIndex++; - workStacks.expr[stackIndex] = node; - workStacks.state[stackIndex] = 0 /* MaybeCheckLeft */; - workStacks.leftType[stackIndex] = undefined; + function onExit(node, state) { + var result; + if (state.skip) { + result = getLastResult(state); } else { - lastResult = checkExpression(node, checkMode); + var leftType = getLeftType(state); + ts.Debug.assertIsDefined(leftType); + var rightType = getLastResult(state); + ts.Debug.assertIsDefined(rightType); + result = checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node); + } + state.skip = false; + setLeftType(state, /*type*/ undefined); + setLastResult(state, /*type*/ undefined); + state.stackIndex--; + return result; + } + function foldState(state, result, _side) { + setLastResult(state, result); + return state; + } + function maybeCheckExpression(state, node) { + if (ts.isBinaryExpression(node)) { + return node; } + setLastResult(state, checkExpression(node, state.checkMode)); + } + function getLeftType(state) { + return state.typeStack[state.stackIndex]; + } + function setLeftType(state, type) { + state.typeStack[state.stackIndex] = type; + } + function getLastResult(state) { + return state.typeStack[state.stackIndex + 1]; + } + function setLastResult(state, type) { + // To reduce overhead, reuse the next stack entry to store the + // last result. This avoids the overhead of an additional property + // on `WorkArea` and reuses empty stack entries as we walk back up + // the stack. + state.typeStack[state.stackIndex + 1] = type; } } function checkGrammarNullishCoalesceWithLogicalExpression(node) { @@ -71578,7 +73791,7 @@ var ts; // expression-wide checks and does not use a work stack to fold nested binary expressions into the same callstack frame function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 62 /* EqualsToken */ && (left.kind === 200 /* ObjectLiteralExpression */ || left.kind === 199 /* ArrayLiteralExpression */)) { + if (operator === 62 /* EqualsToken */ && (left.kind === 201 /* ObjectLiteralExpression */ || left.kind === 200 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 107 /* ThisKeyword */); } var leftType; @@ -71813,7 +74026,7 @@ var ts; if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false); - if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { + if ((symbol === null || symbol === void 0 ? void 0 : symbol.declarations) && symbol.declarations.some(ts.isJSDocTypedefTag)) { addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop); addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol); } @@ -72008,7 +74221,7 @@ var ts; } function checkConditionalExpression(node, checkMode) { var type = checkTruthinessExpression(node.condition); - checkTestingKnownTruthyCallableType(node.condition, type, node.whenTrue); + checkTestingKnownTruthyCallableOrAwaitableType(node.condition, type, node.whenTrue); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); return getUnionType([type1, type2], 2 /* Subtype */); @@ -72025,10 +74238,14 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return getFreshTypeOfLiteralType(getTemplateLiteralType(texts, types)); + return isConstContext(node) || someType(getContextualType(node) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; + } + function isTemplateLiteralContextualType(type) { + return !!(type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */) || + type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 402653316 /* StringLike */)); } function getContextNode(node) { - if (node.kind === 281 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { + if (node.kind === 282 /* 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; @@ -72044,7 +74261,7 @@ var ts; // We strip literal freshness when an appropriate contextual type is present such that contextually typed // literals always preserve their literal types (otherwise they might widen during type inference). An alternative // here would be to not mark contextually typed literals as fresh in the first place. - var result = maybeTypeOfKind(type, 134220672 /* FreshableLiteral */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -72077,13 +74294,13 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 206 /* TypeAssertionExpression */ || node.kind === 224 /* AsExpression */; + return node.kind === 207 /* TypeAssertionExpression */ || node.kind === 225 /* AsExpression */; } function checkDeclarationInitializer(declaration, contextualType) { var initializer = ts.getEffectiveInitializer(declaration); var type = getQuickTypeOfExpression(initializer) || (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer)); - return ts.isParameter(declaration) && declaration.name.kind === 197 /* ArrayBindingPattern */ && + return ts.isParameter(declaration) && declaration.name.kind === 198 /* ArrayBindingPattern */ && isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ? padTupleType(type, declaration.name) : type; } @@ -72093,7 +74310,7 @@ var ts; var elementFlags = type.target.elementFlags.slice(); for (var i = getTypeReferenceArity(type); i < patternElements.length; i++) { var e = patternElements[i]; - if (i < patternElements.length - 1 || !(e.kind === 198 /* BindingElement */ && e.dotDotDotToken)) { + if (i < patternElements.length - 1 || !(e.kind === 199 /* BindingElement */ && e.dotDotDotToken)) { elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType); elementFlags.push(2 /* Optional */); if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) { @@ -72128,7 +74345,7 @@ var ts; // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || unknownType; - return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || @@ -72136,7 +74353,7 @@ var ts; } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return !!(contextualType.flags & (134217856 /* StringLikeLiteral */ | 4194304 /* Index */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || @@ -72160,7 +74377,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); @@ -72171,7 +74388,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -72389,7 +74606,7 @@ var ts; } } function checkExpression(node, checkMode, forceTuple) { - ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -72399,7 +74616,7 @@ var ts; checkConstEnumAccess(node, type); } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return type; } function checkConstEnumAccess(node, type) { @@ -72407,11 +74624,11 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 202 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 78 /* Identifier */ || node.kind === 157 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || - (node.parent.kind === 176 /* TypeQuery */ && node.parent.exprName === node)) || - (node.parent.kind === 270 /* ExportSpecifier */); // We allow reexporting const enums + var ok = (node.parent.kind === 202 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 203 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 78 /* Identifier */ || node.kind === 158 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 177 /* TypeQuery */ && node.parent.exprName === node)) || + (node.parent.kind === 271 /* ExportSpecifier */); // We allow reexporting const enums if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } @@ -72436,15 +74653,15 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { case 78 /* Identifier */: - return checkIdentifier(node); + return checkIdentifier(node, checkMode); case 107 /* ThisKeyword */: return checkThisExpression(node); case 105 /* SuperKeyword */: @@ -72464,78 +74681,78 @@ var ts; return trueType; case 94 /* FalseKeyword */: return falseType; - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return checkTemplateExpression(node); case 13 /* RegularExpressionLiteral */: return globalRegExpType; - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return checkArrayLiteral(node, checkMode, forceTuple); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); - case 201 /* PropertyAccessExpression */: - return checkPropertyAccessExpression(node); - case 157 /* QualifiedName */: - return checkQualifiedName(node); - case 202 /* ElementAccessExpression */: - return checkIndexedAccess(node); - case 203 /* CallExpression */: + case 202 /* PropertyAccessExpression */: + return checkPropertyAccessExpression(node, checkMode); + case 158 /* QualifiedName */: + return checkQualifiedName(node, checkMode); + case 203 /* ElementAccessExpression */: + return checkIndexedAccess(node, checkMode); + case 204 /* CallExpression */: if (node.expression.kind === 99 /* ImportKeyword */) { return checkImportCallExpression(node); } // falls through - case 204 /* NewExpression */: + case 205 /* NewExpression */: return checkCallExpression(node, checkMode); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return checkParenthesizedExpression(node, checkMode); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return checkClassExpression(node); - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return checkAssertion(node); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return checkNonNullAssertion(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return checkMetaProperty(node); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return checkDeleteExpression(node); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return checkVoidExpression(node); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return checkAwaitExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return checkBinaryExpression(node, checkMode); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return checkConditionalExpression(node, checkMode); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return checkSpreadExpression(node, checkMode); - case 222 /* OmittedExpression */: + case 223 /* OmittedExpression */: return undefinedWideningType; - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return checkYieldExpression(node); - case 227 /* SyntheticExpression */: + case 228 /* SyntheticExpression */: return checkSyntheticExpression(node); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return checkJsxExpression(node, checkMode); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return checkJsxElement(node, checkMode); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node, checkMode); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return checkJsxFragment(node); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return errorType; @@ -72571,11 +74788,11 @@ var ts; checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) { - if (!(func.kind === 166 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { + if (!(func.kind === 167 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } - if (func.kind === 166 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") { + if (func.kind === 167 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") { error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name); } } @@ -72586,13 +74803,13 @@ var ts; if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 166 /* Constructor */ || func.kind === 170 /* ConstructSignature */ || func.kind === 175 /* ConstructorType */) { + if (func.kind === 167 /* Constructor */ || func.kind === 171 /* ConstructSignature */ || func.kind === 176 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } - if (func.kind === 209 /* ArrowFunction */) { + if (func.kind === 210 /* ArrowFunction */) { error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); } - if (func.kind === 167 /* GetAccessor */ || func.kind === 168 /* SetAccessor */) { + if (func.kind === 168 /* GetAccessor */ || func.kind === 169 /* SetAccessor */) { error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters); } } @@ -72650,13 +74867,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 209 /* ArrowFunction */: - case 169 /* CallSignature */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 174 /* FunctionType */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 210 /* ArrowFunction */: + case 170 /* CallSignature */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 175 /* FunctionType */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: var parent = node.parent; if (node === parent.type) { return parent; @@ -72674,7 +74891,7 @@ var ts; error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 197 /* ArrayBindingPattern */ || name.kind === 196 /* ObjectBindingPattern */) { + else if (name.kind === 198 /* ArrayBindingPattern */ || name.kind === 197 /* ObjectBindingPattern */) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -72683,13 +74900,13 @@ var ts; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 171 /* IndexSignature */) { + if (node.kind === 172 /* IndexSignature */) { checkGrammarIndexSignature(node); } // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled - else if (node.kind === 174 /* FunctionType */ || node.kind === 251 /* FunctionDeclaration */ || node.kind === 175 /* ConstructorType */ || - node.kind === 169 /* CallSignature */ || node.kind === 166 /* Constructor */ || - node.kind === 170 /* ConstructSignature */) { + else if (node.kind === 175 /* FunctionType */ || node.kind === 252 /* FunctionDeclaration */ || node.kind === 176 /* ConstructorType */ || + node.kind === 170 /* CallSignature */ || node.kind === 167 /* Constructor */ || + node.kind === 171 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); @@ -72719,10 +74936,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 169 /* CallSignature */: + case 170 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -72752,7 +74969,7 @@ var ts; checkAsyncFunctionReturnType(node, returnTypeNode); } } - if (node.kind !== 171 /* IndexSignature */ && node.kind !== 308 /* JSDocFunctionType */) { + if (node.kind !== 172 /* IndexSignature */ && node.kind !== 309 /* JSDocFunctionType */) { registerForUnusedIdentifiersCheck(node); } } @@ -72764,7 +74981,7 @@ var ts; var privateIdentifiers = new ts.Map(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 166 /* Constructor */) { + if (member.kind === 167 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) { @@ -72776,25 +74993,27 @@ var ts; var isStatic = ts.hasSyntacticModifier(member, 32 /* Static */); var name = member.name; if (!name) { - return; + continue; } - var names = ts.isPrivateIdentifier(name) ? privateIdentifiers : + var isPrivate = ts.isPrivateIdentifier(name); + var privateStaticFlags = isPrivate && isStatic ? 16 /* PrivateStatic */ : 0; + var names = isPrivate ? privateIdentifiers : isStatic ? staticNames : instanceNames; var memberName = name && ts.getPropertyNameForPropertyNameNode(name); if (memberName) { switch (member.kind) { - case 167 /* GetAccessor */: - addName(names, name, memberName, 1 /* GetAccessor */); + case 168 /* GetAccessor */: + addName(names, name, memberName, 1 /* GetAccessor */ | privateStaticFlags); break; - case 168 /* SetAccessor */: - addName(names, name, memberName, 2 /* SetAccessor */); + case 169 /* SetAccessor */: + addName(names, name, memberName, 2 /* SetAccessor */ | privateStaticFlags); break; - case 163 /* PropertyDeclaration */: - addName(names, name, memberName, 3 /* GetOrSetAccessor */); + case 164 /* PropertyDeclaration */: + addName(names, name, memberName, 3 /* GetOrSetAccessor */ | privateStaticFlags); break; - case 165 /* MethodDeclaration */: - addName(names, name, memberName, 8 /* Method */); + case 166 /* MethodDeclaration */: + addName(names, name, memberName, 8 /* Method */ | privateStaticFlags); break; } } @@ -72803,16 +75022,25 @@ var ts; function addName(names, location, name, meaning) { var prev = names.get(name); if (prev) { - if (prev & 8 /* Method */) { - if (meaning !== 8 /* Method */) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); - } - } - else if (prev & meaning) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + // For private identifiers, do not allow mixing of static and instance members with the same name + if ((prev & 16 /* PrivateStatic */) !== (meaning & 16 /* PrivateStatic */)) { + error(location, ts.Diagnostics.Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name, ts.getTextOfNode(location)); } else { - names.set(name, prev | meaning); + var prevIsMethod = !!(prev & 8 /* Method */); + var isMethod = !!(meaning & 8 /* Method */); + if (prevIsMethod || isMethod) { + if (prevIsMethod !== isMethod) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + // If this is a method/method duplication is might be an overload, so this will be handled when overloads are considered + } + else if (prev & meaning & ~16 /* PrivateStatic */) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names.set(name, prev | meaning); + } } } else { @@ -72856,7 +75084,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 162 /* PropertySignature */) { + if (member.kind === 163 /* PropertySignature */) { var memberName = void 0; var name = member.name; switch (name.kind) { @@ -72881,11 +75109,11 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 253 /* InterfaceDeclaration */) { + if (node.kind === 254 /* InterfaceDeclaration */) { var nodeSymbol = getSymbolOfNode(node); // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration // to prevent this run check only for the first declaration of a given kind - if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + if (nodeSymbol.declarations && nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; } } @@ -72893,7 +75121,7 @@ var ts; // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); - if (indexSymbol) { + if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { var seenNumericIndexer = false; var seenStringIndexer = false; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -72927,11 +75155,9 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); - // Private class fields transformation relies on WeakMaps. - if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) { - for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) { - getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */; - } + setNodeLinksForPrivateIdentifierScope(node); + if (ts.isPrivateIdentifier(node.name) && ts.hasStaticModifier(node) && node.initializer && languageVersion === 99 /* ESNext */ && !compilerOptions.useDefineForClassFields) { + error(node.initializer, ts.Diagnostics.Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag); } } function checkPropertySignature(node) { @@ -72944,16 +75170,35 @@ var ts; // Grammar checking if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); - if (ts.isPrivateIdentifier(node.name)) { - error(node, ts.Diagnostics.A_method_cannot_be_named_with_a_private_identifier); - } // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (ts.hasSyntacticModifier(node, 128 /* Abstract */) && node.kind === 165 /* MethodDeclaration */ && node.body) { + if (ts.hasSyntacticModifier(node, 128 /* Abstract */) && node.kind === 166 /* MethodDeclaration */ && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } + // Private named methods are only allowed in class declarations + if (ts.isPrivateIdentifier(node.name) && !ts.getContainingClass(node)) { + error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + } + setNodeLinksForPrivateIdentifierScope(node); + } + function setNodeLinksForPrivateIdentifierScope(node) { + if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) { + for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) { + getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */; + } + // If this is a private element in a class expression inside the body of a loop, + // then we must use a block-scoped binding to store the additional variables required + // to transform private elements. + if (ts.isClassExpression(node.parent)) { + var enclosingIterationStatement = getEnclosingIterationStatement(node.parent); + if (enclosingIterationStatement) { + getNodeLinks(node.name).flags |= 524288 /* BlockScopedBindingInLoop */; + getNodeLinks(enclosingIterationStatement).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } + } + } } function checkConstructorDeclaration(node) { // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. @@ -72976,10 +75221,10 @@ var ts; return; } function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) { - if (ts.isPrivateIdentifierPropertyDeclaration(n)) { + if (ts.isPrivateIdentifierClassElementDeclaration(n)) { return true; } - return n.kind === 163 /* PropertyDeclaration */ && + return n.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(n, 32 /* Static */) && !!n.initializer; } @@ -73000,9 +75245,9 @@ var ts; // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) && + var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !useDefineForClassFields) && (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 92 /* ParameterPropertyModifier */); })); + ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */); })); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -73010,7 +75255,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) { var statement = statements_4[_i]; - if (statement.kind === 233 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 234 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -73035,7 +75280,7 @@ var ts; checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 167 /* GetAccessor */) { + if (node.kind === 168 /* GetAccessor */) { if (!(node.flags & 8388608 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 256 /* HasImplicitReturn */)) { if (!(node.flags & 512 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); @@ -73045,45 +75290,42 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } - if (ts.isPrivateIdentifier(node.name)) { - error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier); - } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. - var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; - var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); - if (otherAccessor) { - var nodeFlags = ts.getEffectiveModifierFlags(node); - var otherFlags = ts.getEffectiveModifierFlags(otherAccessor); - if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) { - error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + var symbol = getSymbolOfNode(node); + var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); + if (getter && setter && !(getNodeCheckFlags(getter) & 1 /* TypeChecked */)) { + getNodeLinks(getter).flags |= 1 /* TypeChecked */; + var getterFlags = ts.getEffectiveModifierFlags(getter); + var setterFlags = ts.getEffectiveModifierFlags(setter); + if ((getterFlags & 128 /* Abstract */) !== (setterFlags & 128 /* Abstract */)) { + error(getter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(setter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } + if (((getterFlags & 16 /* Protected */) && !(setterFlags & (16 /* Protected */ | 8 /* Private */))) || + ((getterFlags & 8 /* Private */) && !(setterFlags & 8 /* Private */))) { + error(getter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(setter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); } - if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) { - error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + var getterType = getAnnotatedAccessorType(getter); + var setterType = getAnnotatedAccessorType(setter); + if (getterType && setterType) { + checkTypeAssignableTo(getterType, setterType, getter, ts.Diagnostics.The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type); } - // TypeScript 1.0 spec (April 2014): 4.5 - // If both accessors include type annotations, the specified types must be identical. - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 167 /* GetAccessor */) { + if (node.kind === 168 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } checkSourceElement(node.body); - } - function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { - var firstType = getAnnotatedType(first); - var secondType = getAnnotatedType(second); - if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { - error(first, message); - } + setNodeLinksForPrivateIdentifierScope(node); } function checkMissingDeclaration(node) { checkDecorators(node); @@ -73120,7 +75362,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 173 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 174 /* 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); } ts.forEach(node.typeArguments, checkSourceElement); @@ -73135,7 +75377,7 @@ var ts; var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, getDeprecatedSuggestionNode(node), ts.Diagnostics._0_is_deprecated, symbol.escapedName); + addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 /* Enum */ && symbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); @@ -73173,7 +75415,7 @@ var ts; var hasNamedElement = ts.some(elementTypes, ts.isNamedTupleMember); for (var _i = 0, elementTypes_1 = elementTypes; _i < elementTypes_1.length; _i++) { var e = elementTypes_1[_i]; - if (e.kind !== 192 /* NamedTupleMember */ && hasNamedElement) { + if (e.kind !== 193 /* NamedTupleMember */ && hasNamedElement) { grammarErrorOnNode(e, ts.Diagnostics.Tuple_members_must_all_have_names_or_all_not_have_names); break; } @@ -73222,7 +75464,7 @@ var ts; var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { - if (accessNode.kind === 202 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + if (accessNode.kind === 203 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } @@ -73280,7 +75522,7 @@ var ts; ts.forEachChild(node, checkSourceElement); } function checkInferType(node) { - if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 184 /* ConditionalType */ && n.parent.extendsType === n; })) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 185 /* ConditionalType */ && n.parent.extendsType === n; })) { grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); @@ -73303,25 +75545,25 @@ var ts; if (node.dotDotDotToken && node.questionToken) { grammarErrorOnNode(node, ts.Diagnostics.A_tuple_member_cannot_be_both_optional_and_rest); } - if (node.type.kind === 180 /* OptionalType */) { + if (node.type.kind === 181 /* OptionalType */) { grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type); } - if (node.type.kind === 181 /* RestType */) { + if (node.type.kind === 182 /* RestType */) { grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type); } checkSourceElement(node.type); getTypeFromTypeNode(node); } function isPrivateWithinAmbient(node) { - return (ts.hasEffectiveModifier(node, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */); + return (ts.hasEffectiveModifier(node, 8 /* Private */) || ts.isPrivateIdentifierClassElementDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 253 /* InterfaceDeclaration */ && - n.parent.kind !== 252 /* ClassDeclaration */ && - n.parent.kind !== 221 /* ClassExpression */ && + if (n.parent.kind !== 254 /* InterfaceDeclaration */ && + n.parent.kind !== 253 /* ClassDeclaration */ && + n.parent.kind !== 222 /* ClassExpression */ && n.flags & 8388608 /* Ambient */) { if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { // It is nested in an ambient context, which means it is automatically exported @@ -73417,7 +75659,7 @@ var ts; // Both are literal property names that are the same. ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - var reportError = (node.kind === 165 /* MethodDeclaration */ || node.kind === 164 /* MethodSignature */) && + var reportError = (node.kind === 166 /* MethodDeclaration */ || node.kind === 165 /* MethodSignature */) && ts.hasSyntacticModifier(node, 32 /* Static */) !== ts.hasSyntacticModifier(subsequentNode, 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members @@ -73454,55 +75696,57 @@ var ts; var multipleConstructorImplementation = false; var hasNonAmbientClass = false; var functionDeclarations = []; - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var current = declarations_4[_i]; - var node = current; - var inAmbientContext = node.flags & 8388608 /* Ambient */; - var inAmbientContextOrInterface = node.parent && (node.parent.kind === 253 /* InterfaceDeclaration */ || node.parent.kind === 177 /* TypeLiteral */) || inAmbientContext; - if (inAmbientContextOrInterface) { - // check if declarations are consecutive only if they are non-ambient - // 1. ambient declarations can be interleaved - // i.e. this is legal - // declare function foo(); - // declare function bar(); - // declare function foo(); - // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one - previousDeclaration = undefined; - } - if ((node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */) && !inAmbientContext) { - hasNonAmbientClass = true; - } - if (node.kind === 251 /* FunctionDeclaration */ || node.kind === 165 /* MethodDeclaration */ || node.kind === 164 /* MethodSignature */ || node.kind === 166 /* Constructor */) { - functionDeclarations.push(node); - var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); - someNodeFlags |= currentNodeFlags; - allNodeFlags &= currentNodeFlags; - someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); - allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); - var bodyIsPresent = ts.nodeIsPresent(node.body); - if (bodyIsPresent && bodyDeclaration) { - if (isConstructor) { - multipleConstructorImplementation = true; + if (declarations) { + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; + var node = current; + var inAmbientContext = node.flags & 8388608 /* Ambient */; + var inAmbientContextOrInterface = node.parent && (node.parent.kind === 254 /* InterfaceDeclaration */ || node.parent.kind === 178 /* TypeLiteral */) || inAmbientContext; + if (inAmbientContextOrInterface) { + // check if declarations are consecutive only if they are non-ambient + // 1. ambient declarations can be interleaved + // i.e. this is legal + // declare function foo(); + // declare function bar(); + // declare function foo(); + // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one + previousDeclaration = undefined; + } + if ((node.kind === 253 /* ClassDeclaration */ || node.kind === 222 /* ClassExpression */) && !inAmbientContext) { + hasNonAmbientClass = true; + } + if (node.kind === 252 /* FunctionDeclaration */ || node.kind === 166 /* MethodDeclaration */ || node.kind === 165 /* MethodSignature */ || node.kind === 167 /* Constructor */) { + functionDeclarations.push(node); + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); + var bodyIsPresent = ts.nodeIsPresent(node.body); + if (bodyIsPresent && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } + } + else if ((previousDeclaration === null || previousDeclaration === void 0 ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (bodyIsPresent) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } } else { - duplicateFunctionDeclaration = true; + hasOverloads = true; } - } - else if ((previousDeclaration === null || previousDeclaration === void 0 ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) { - reportImplementationExpectedError(previousDeclaration); - } - if (bodyIsPresent) { - if (!bodyDeclaration) { - bodyDeclaration = node; + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; } } - else { - hasOverloads = true; - } - previousDeclaration = node; - if (!inAmbientContextOrInterface) { - lastSeenNonAmbientDeclaration = node; - } } } if (multipleConstructorImplementation) { @@ -73530,8 +75774,10 @@ var ts; reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { - checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); - checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (declarations) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + } if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); @@ -73605,43 +75851,46 @@ var ts; function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: // A jsdoc typedef and callback are, by definition, type aliases. // falls through - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return 2 /* ExportType */; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4 /* ExportNamespace */ | 1 /* ExportValue */ : 4 /* ExportNamespace */; - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: return 2 /* ExportType */ | 1 /* ExportValue */; - case 297 /* SourceFile */: + case 298 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: + case 217 /* BinaryExpression */: + var node_2 = d; + var expression = ts.isExportAssignment(node_2) ? node_2.expression : node_2.right; // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values - if (!ts.isEntityNameExpression(d.expression)) { + if (!ts.isEntityNameExpression(expression)) { return 1 /* ExportValue */; } - d = d.expression; + d = expression; // The below options all declare an Alias, which is allowed to merge with other values within the importing module. // falls through - case 260 /* ImportEqualsDeclaration */: - case 263 /* NamespaceImport */: - case 262 /* ImportClause */: - var result_12 = 0 /* None */; + case 261 /* ImportEqualsDeclaration */: + case 264 /* NamespaceImport */: + case 263 /* ImportClause */: + var result_13 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_12 |= getDeclarationSpaces(d); }); - return result_12; - case 249 /* VariableDeclaration */: - case 198 /* BindingElement */: - case 251 /* FunctionDeclaration */: - case 265 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + ts.forEach(target.declarations, function (d) { result_13 |= getDeclarationSpaces(d); }); + return result_13; + case 250 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 252 /* FunctionDeclaration */: + case 266 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 case 78 /* Identifier */: // https://github.com/microsoft/TypeScript/issues/36098 // Identifiers are used as declarations of assignment declarations whose parents may be // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});` @@ -73934,24 +76183,24 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 160 /* Parameter */: + case 161 /* Parameter */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -73998,15 +76247,15 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { - case 183 /* IntersectionType */: - case 182 /* UnionType */: + case 184 /* IntersectionType */: + case 183 /* UnionType */: return getEntityNameForDecoratorMetadataFromTypeList(node.types); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); - case 186 /* ParenthesizedType */: - case 192 /* NamedTupleMember */: + case 187 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: return getEntityNameForDecoratorMetadata(node.type); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return node.typeName; } } @@ -74015,13 +76264,13 @@ var ts; var commonEntityName; for (var _i = 0, types_23 = types; _i < types_23.length; _i++) { var typeNode = types_23[_i]; - while (typeNode.kind === 186 /* ParenthesizedType */ || typeNode.kind === 192 /* NamedTupleMember */) { + while (typeNode.kind === 187 /* ParenthesizedType */ || typeNode.kind === 193 /* NamedTupleMember */) { typeNode = typeNode.type; // Skip parens if need be } if (typeNode.kind === 141 /* NeverKeyword */) { continue; // Always elide `never` from the union/intersection if possible } - if (!strictNullChecks && (typeNode.kind === 191 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { + if (!strictNullChecks && (typeNode.kind === 192 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); @@ -74067,14 +76316,14 @@ var ts; } var firstDecorator = node.decorators[0]; checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); - if (node.kind === 160 /* Parameter */) { + if (node.kind === 161 /* Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* Param */); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -74083,23 +76332,23 @@ var ts; } } break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + var otherKind = node.kind === 168 /* GetAccessor */ ? 169 /* SetAccessor */ : 168 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 160 /* Parameter */: + case 161 /* Parameter */: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); var containingSignature = node.parent; for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { @@ -74162,7 +76411,7 @@ var ts; else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 157 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 158 /* QualifiedName */ ? node.name.right : node.name)); } } } @@ -74206,25 +76455,26 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return node.name; default: return undefined; } } function checkFunctionOrMethodDeclaration(node) { + var _a; checkDecorators(node); checkSignatureDeclaration(node); var functionFlags = ts.getFunctionFlags(node); // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name && node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 159 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // first we want to check the local symbol that contain this declaration // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode @@ -74233,7 +76483,7 @@ var ts; // Since the javascript won't do semantic analysis like typescript, // if the javascript file comes before the typescript file and both contain same name functions, // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. - var firstDeclaration = ts.find(localSymbol.declarations, + var firstDeclaration = (_a = localSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find( // Get first non javascript function declaration function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072 /* JavaScriptFile */); }); // Only type check the symbol once @@ -74245,7 +76495,7 @@ var ts; checkFunctionOrConstructorSymbol(symbol); } } - var body = node.kind === 164 /* MethodSignature */ ? undefined : node.body; + var body = node.kind === 165 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node)); if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { @@ -74287,42 +76537,42 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: checkUnusedClassMembers(node, addDiagnostic); checkUnusedTypeParameters(node, addDiagnostic); break; - case 297 /* SourceFile */: - case 256 /* ModuleDeclaration */: - case 230 /* Block */: - case 258 /* CaseBlock */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 298 /* SourceFile */: + case 257 /* ModuleDeclaration */: + case 231 /* Block */: + case 259 /* CaseBlock */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: checkUnusedLocalsAndParameters(node, addDiagnostic); break; - case 166 /* Constructor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 167 /* Constructor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: if (node.body) { // Don't report unused parameters in overloads checkUnusedLocalsAndParameters(node, addDiagnostic); } checkUnusedTypeParameters(node, addDiagnostic); break; - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: checkUnusedTypeParameters(node, addDiagnostic); break; - case 185 /* InferType */: + case 186 /* InferType */: checkUnusedInferTypeParameter(node, addDiagnostic); break; default: @@ -74342,11 +76592,11 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 165 /* MethodDeclaration */: - case 163 /* PropertyDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - if (member.kind === 168 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + case 166 /* MethodDeclaration */: + case 164 /* PropertyDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + if (member.kind === 169 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { // Already would have reported an error on the getter. break; } @@ -74357,7 +76607,7 @@ var ts; addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; - case 166 /* Constructor */: + case 167 /* Constructor */: for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasSyntacticModifier(parameter, 8 /* Private */)) { @@ -74365,8 +76615,8 @@ var ts; } } break; - case 171 /* IndexSignature */: - case 229 /* SemicolonClassElement */: + case 172 /* IndexSignature */: + case 230 /* SemicolonClassElement */: // Can't be private break; default: @@ -74383,7 +76633,8 @@ var ts; function checkUnusedTypeParameters(node, addDiagnostic) { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. - if (ts.last(getSymbolOfNode(node).declarations) !== node) + var declarations = getSymbolOfNode(node).declarations; + if (!declarations || ts.last(declarations) !== node) return; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); var seenParentsWithEveryUnused = new ts.Set(); @@ -74393,7 +76644,7 @@ var ts; continue; var name = ts.idText(typeParameter.name); var parent = typeParameter.parent; - if (parent.kind !== 185 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (parent.kind !== 186 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { if (ts.tryAddToSet(seenParentsWithEveryUnused, parent)) { var sourceFile = ts.getSourceFileOfNode(parent); var range = ts.isJSDocTemplateTag(parent) @@ -74429,11 +76680,15 @@ var ts; return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } function isValidUnusedLocalDeclaration(declaration) { - if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { - return !!ts.findAncestor(declaration.parent, function (ancestor) { - return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : - ts.isForOfStatement(ancestor) ? true : "quit"; - }); + if (ts.isBindingElement(declaration)) { + if (ts.isObjectBindingPattern(declaration.parent)) { + /** + * ignore starts with underscore names _ + * const { a: _a } = { a: 1 } + */ + return !!(declaration.propertyName && isIdentifierThatStartsWithUnderscore(declaration.name)); + } + return isIdentifierThatStartsWithUnderscore(declaration.name); } return ts.isAmbientModule(declaration) || (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); @@ -74449,39 +76704,41 @@ var ts; if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) { return; } - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (isValidUnusedLocalDeclaration(declaration)) { - continue; - } - if (isImportedDeclaration(declaration)) { - addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); - } - else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { - // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. - var lastElement = ts.last(declaration.parent.elements); - if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { - addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + if (local.declarations) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (isValidUnusedLocalDeclaration(declaration)) { + continue; } - } - else if (ts.isVariableDeclaration(declaration)) { - addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); - } - else { - var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); - var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); - if (parameter && name) { - if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { - if (ts.isBindingElement(declaration) && ts.isArrayBindingPattern(declaration.parent)) { - addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); - } - else { - addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); - } + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); } } + else if (ts.isVariableDeclaration(declaration)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } else { - errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); + if (parameter && name) { + if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { + if (ts.isBindingElement(declaration) && ts.isArrayBindingPattern(declaration.parent)) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + else { + addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); + } + } + } + else { + errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); + } } } } @@ -74491,7 +76748,7 @@ var ts; var importDecl = importClause.parent; var nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? - (importClause.namedBindings.kind === 263 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + (importClause.namedBindings.kind === 264 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 @@ -74509,7 +76766,7 @@ var ts; var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; if (bindingPattern.elements.length === bindingElements.length) { - if (bindingElements.length === 1 && bindingPattern.parent.kind === 249 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 250 /* VariableDeclarationList */) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 250 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 251 /* VariableDeclarationList */) { addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { @@ -74530,7 +76787,7 @@ var ts; if (declarationList.declarations.length === declarations.length) { addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) - : ts.createDiagnosticForNode(declarationList.parent.kind === 232 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + : ts.createDiagnosticForNode(declarationList.parent.kind === 233 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { @@ -74544,22 +76801,22 @@ var ts; switch (name.kind) { case 78 /* Identifier */: return ts.idText(name); - case 197 /* ArrayBindingPattern */: - case 196 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); default: return ts.Debug.assertNever(name); } } function isImportedDeclaration(node) { - return node.kind === 262 /* ImportClause */ || node.kind === 265 /* ImportSpecifier */ || node.kind === 263 /* NamespaceImport */; + return node.kind === 263 /* ImportClause */ || node.kind === 266 /* ImportSpecifier */ || node.kind === 264 /* NamespaceImport */; } function importClauseFromImported(decl) { - return decl.kind === 262 /* ImportClause */ ? decl : decl.kind === 263 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + return decl.kind === 263 /* ImportClause */ ? decl : decl.kind === 264 /* NamespaceImport */ ? decl.parent : decl.parent.parent; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 230 /* Block */) { + if (node.kind === 231 /* Block */) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -74589,12 +76846,12 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 163 /* PropertyDeclaration */ || - node.kind === 162 /* PropertySignature */ || - node.kind === 165 /* MethodDeclaration */ || - node.kind === 164 /* MethodSignature */ || - node.kind === 167 /* GetAccessor */ || - node.kind === 168 /* SetAccessor */) { + if (node.kind === 164 /* PropertyDeclaration */ || + node.kind === 163 /* PropertySignature */ || + node.kind === 166 /* MethodDeclaration */ || + node.kind === 165 /* MethodSignature */ || + node.kind === 168 /* GetAccessor */ || + node.kind === 169 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } @@ -74603,7 +76860,7 @@ var ts; return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 160 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 161 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -74640,10 +76897,11 @@ var ts; return false; }); } - function checkWeakMapCollision(node) { + function checkWeakMapSetCollision(node) { var enclosingBlockScope = ts.getEnclosingBlockScopeContainer(node); if (getNodeCheckFlags(enclosingBlockScope) & 67108864 /* ContainsClassWithPrivateIdentifiers */) { - errorSkippedOn("noEmit", node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, "WeakMap"); + ts.Debug.assert(ts.isNamedDeclaration(node) && ts.isIdentifier(node.name) && typeof node.name.escapedText === "string", "The target of a WeakMap/WeakSet collision check should be an identifier"); + errorSkippedOn("noEmit", node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, node.name.escapedText); } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { @@ -74660,7 +76918,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords errorSkippedOn("noEmit", name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -74675,7 +76933,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) { + if (parent.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. errorSkippedOn("noEmit", name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -74710,7 +76968,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 249 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 250 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -74722,17 +76980,17 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 250 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 232 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 251 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 233 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) var namesShareScope = container && - (container.kind === 230 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 257 /* ModuleBlock */ || - container.kind === 256 /* ModuleDeclaration */ || - container.kind === 297 /* SourceFile */); + (container.kind === 231 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 258 /* ModuleBlock */ || + container.kind === 257 /* ModuleDeclaration */ || + container.kind === 298 /* SourceFile */); // here we know that function scoped variable is shadowed by block scoped one // if they are defined in the same scope - binder has already reported redeclaration error // otherwise if variable has an initializer - show error that initialization will fail @@ -74763,18 +77021,18 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 198 /* BindingElement */) { - if (node.parent.kind === 196 /* ObjectBindingPattern */ && languageVersion < 99 /* ESNext */) { + if (ts.isBindingElement(node)) { + if (ts.isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < 5 /* ES2018 */) { checkExternalEmitHelpers(node, 4 /* Rest */); } // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 158 /* ComputedPropertyName */) { + if (node.propertyName && node.propertyName.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } // check private/protected variable access @@ -74787,15 +77045,15 @@ var ts; var nameText = getPropertyNameFromType(exprType); var property = getPropertyOfType(parentType, nameText); if (property) { - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 105 /* SuperKeyword */, parentType, property); + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isSelfTypeAccess*/ false); // A destructuring is never a write-only reference. + checkPropertyAccessibility(node, !!parent.initializer && parent.initializer.kind === 105 /* SuperKeyword */, /*writing*/ false, parentType, property); } } } } // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 197 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + if (node.name.kind === 198 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } ts.forEach(node.name.elements, checkSourceElement); @@ -74807,7 +77065,7 @@ var ts; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { - var needCheckInitializer = node.initializer && node.parent.parent.kind !== 238 /* ForInStatement */; + var needCheckInitializer = node.initializer && node.parent.parent.kind !== 239 /* ForInStatement */; var needCheckWidenedType = node.name.elements.length === 0; if (needCheckInitializer || needCheckWidenedType) { // Don't validate for-in initializer as it is already an error @@ -74835,7 +77093,7 @@ var ts; } // For a commonjs `const x = require`, validate the alias and exit var symbol = getSymbolOfNode(node); - if (symbol.flags & 2097152 /* Alias */ && ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true)) { + if (symbol.flags & 2097152 /* Alias */ && ts.isRequireVariableDeclaration(node)) { checkAliasSymbol(node); return; } @@ -74849,11 +77107,11 @@ var ts; ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && !!((_a = symbol.exports) === null || _a === void 0 ? void 0 : _a.size); - if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 238 /* ForInStatement */) { + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 239 /* ForInStatement */) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); } } - if (symbol.declarations.length > 1) { + if (symbol.declarations && symbol.declarations.length > 1) { if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) { error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } @@ -74871,26 +77129,27 @@ var ts; if (node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } - if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 163 /* PropertyDeclaration */ && node.kind !== 162 /* PropertySignature */) { + if (node.kind !== 164 /* PropertyDeclaration */ && node.kind !== 163 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) { + if (node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - if (languageVersion < 99 /* ESNext */ && needCollisionCheckForIdentifier(node, node.name, "WeakMap")) { - potentialWeakMapCollisions.push(node); + if (languageVersion < 99 /* ESNext */ + && (needCollisionCheckForIdentifier(node, node.name, "WeakMap") || needCollisionCheckForIdentifier(node, node.name, "WeakSet"))) { + potentialWeakMapSetCollisions.push(node); } } } function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) { var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); - var message = nextDeclaration.kind === 163 /* PropertyDeclaration */ || nextDeclaration.kind === 162 /* PropertySignature */ + var message = nextDeclaration.kind === 164 /* PropertyDeclaration */ || nextDeclaration.kind === 163 /* PropertySignature */ ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; var declName = ts.declarationNameToString(nextDeclarationName); @@ -74900,8 +77159,8 @@ var ts; } } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 160 /* Parameter */ && right.kind === 249 /* VariableDeclaration */) || - (left.kind === 249 /* VariableDeclaration */ && right.kind === 160 /* Parameter */)) { + if ((left.kind === 161 /* Parameter */ && right.kind === 250 /* VariableDeclaration */) || + (left.kind === 250 /* VariableDeclaration */ && right.kind === 161 /* Parameter */)) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -74917,10 +77176,10 @@ var ts; return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { - ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); checkGrammarVariableDeclaration(node); checkVariableLikeDeclaration(node); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkBindingElement(node) { checkGrammarBindingElement(node); @@ -74941,49 +77200,55 @@ var ts; // Grammar checking checkGrammarStatementInAmbientContext(node); var type = checkTruthinessExpression(node.expression); - checkTestingKnownTruthyCallableType(node.expression, type, node.thenStatement); + checkTestingKnownTruthyCallableOrAwaitableType(node.expression, type, node.thenStatement); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 231 /* EmptyStatement */) { + if (node.thenStatement.kind === 232 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); } - function checkTestingKnownTruthyCallableType(condExpr, type, body) { - if (!strictNullChecks) { + function checkTestingKnownTruthyCallableOrAwaitableType(condExpr, type, body) { + if (!strictNullChecks) + return; + if (getFalsyFlags(type)) return; - } var location = ts.isBinaryExpression(condExpr) ? condExpr.right : condExpr; var testedNode = ts.isIdentifier(location) ? location : ts.isPropertyAccessExpression(location) ? location.name : ts.isBinaryExpression(location) && ts.isIdentifier(location.right) ? location.right : undefined; - if (!testedNode) { - return; - } - var possiblyFalsy = getFalsyFlags(type); - if (possiblyFalsy) { + var isPropertyExpressionCast = ts.isPropertyAccessExpression(location) + && ts.isAssertionExpression(ts.skipParentheses(location.expression)); + if (!testedNode || isPropertyExpressionCast) { return; } // While it technically should be invalid for any known-truthy value - // to be tested, we de-scope to functions unrefenced in the block as a - // heuristic to identify the most common bugs. There are too many - // false positives for values sourced from type definitions without - // strictNullChecks otherwise. + // to be tested, we de-scope to functions and Promises unreferenced in + // the block as a heuristic to identify the most common bugs. There + // are too many false positives for values sourced from type + // definitions without strictNullChecks otherwise. var callSignatures = getSignaturesOfType(type, 0 /* Call */); - if (callSignatures.length === 0) { + var isPromise = !!getAwaitedTypeOfPromise(type); + if (callSignatures.length === 0 && !isPromise) { return; } var testedSymbol = getSymbolAtLocation(testedNode); if (!testedSymbol) { return; } - var isUsed = ts.isBinaryExpression(condExpr.parent) && isFunctionUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) - || body && isFunctionUsedInConditionBody(condExpr, body, testedNode, testedSymbol); + var isUsed = ts.isBinaryExpression(condExpr.parent) && isSymbolUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) + || body && isSymbolUsedInConditionBody(condExpr, body, testedNode, testedSymbol); if (!isUsed) { - error(location, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead); + if (isPromise) { + errorAndMaybeSuggestAwait(location, + /*maybeMissingAwait*/ true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, getTypeNameForErrorDisplay(type)); + } + else { + error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead); + } } } - function isFunctionUsedInConditionBody(expr, body, testedNode, testedSymbol) { + function isSymbolUsedInConditionBody(expr, body, testedNode, testedSymbol) { return !!ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); @@ -75020,7 +77285,7 @@ var ts; return ts.forEachChild(childNode, check); }); } - function isFunctionUsedInBinaryExpressionChain(node, testedSymbol) { + function isSymbolUsedInBinaryExpressionChain(node, testedSymbol) { while (ts.isBinaryExpression(node) && node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { var isUsed = ts.forEachChild(node.right, function visit(child) { if (ts.isIdentifier(child)) { @@ -75062,12 +77327,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 251 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer.kind === 251 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -75101,14 +77366,14 @@ var ts; // via checkRightHandSideOfForOf. // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. // Then check that the RHS is assignable to it. - if (node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer.kind === 251 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node); // There may be a destructuring assignment on the left side - if (varExpr.kind === 199 /* ArrayLiteralExpression */ || varExpr.kind === 200 /* ObjectLiteralExpression */) { + if (varExpr.kind === 200 /* ArrayLiteralExpression */ || varExpr.kind === 201 /* ObjectLiteralExpression */) { // iteratedType may be undefined. In this case, we still want to check the structure of // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like // to short circuit the type relation checking as much as possible, so we pass the unknownType. @@ -75140,7 +77405,7 @@ var ts; // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer.kind === 251 /* VariableDeclarationList */) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -75154,7 +77419,7 @@ var ts; // and Expr must be an expression of type Any, an object type, or a type parameter type. var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 199 /* ArrayLiteralExpression */ || varExpr.kind === 200 /* ObjectLiteralExpression */) { + if (varExpr.kind === 200 /* ArrayLiteralExpression */ || varExpr.kind === 201 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -75270,18 +77535,8 @@ var ts; // want to say that number is not an array type. But if the input was just // number and string input is allowed, we want to say that number is not an // array type or a string type. - var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined); - var _a = !(use & 4 /* AllowsStringInputFlag */) || hasStringConstituent - ? downlevelIteration - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] - : yieldType - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false] - : [ts.Diagnostics.Type_0_is_not_an_array_type, true] - : downlevelIteration - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] - : yieldType - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false] - : [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true], defaultDiagnostic = _a[0], maybeMissingAwait = _a[1]; + var allowsStrings = !!(use & 4 /* AllowsStringInputFlag */) && !hasStringConstituent; + var _a = getIterationDiagnosticDetails(allowsStrings, downlevelIteration), defaultDiagnostic = _a[0], maybeMissingAwait = _a[1]; errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType)); } return hasStringConstituent ? possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType : undefined; @@ -75295,6 +77550,40 @@ var ts; return getUnionType(possibleOutOfBounds ? [arrayElementType, stringType, undefinedType] : [arrayElementType, stringType], 2 /* Subtype */); } return (use & 128 /* PossiblyOutOfBounds */) ? includeUndefinedInIndexSignature(arrayElementType) : arrayElementType; + function getIterationDiagnosticDetails(allowsStrings, downlevelIteration) { + var _a; + if (downlevelIteration) { + return allowsStrings + ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] + : [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]; + } + var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined); + if (yieldType) { + return [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]; + } + if (isES2015OrLaterIterable((_a = inputType.symbol) === null || _a === void 0 ? void 0 : _a.escapedName)) { + return [ts.Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, true]; + } + return allowsStrings + ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true] + : [ts.Diagnostics.Type_0_is_not_an_array_type, true]; + } + } + function isES2015OrLaterIterable(n) { + switch (n) { + case "Float32Array": + case "Float64Array": + case "Int16Array": + case "Int32Array": + case "Int8Array": + case "NodeList": + case "Uint16Array": + case "Uint32Array": + case "Uint8Array": + case "Uint8ClampedArray": + return true; + } + return false; } /** * Gets the requested "iteration type" from an `Iterable`-like or `AsyncIterable`-like type. @@ -75538,6 +77827,11 @@ var ts; return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType)); } } + function getPropertyNameForKnownSymbolName(symbolName) { + var ctorType = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false); + var uniqueType = ctorType && getTypeOfPropertyOfType(getTypeOfSymbol(ctorType), ts.escapeLeadingUnderscores(symbolName)); + return uniqueType && isTypeUsableAsPropertyName(uniqueType) ? getPropertyNameFromType(uniqueType) : "__@" + symbolName; + } /** * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like * type from its members. @@ -75550,7 +77844,7 @@ var ts; */ function getIterationTypesOfIterableSlow(type, resolver, errorNode) { var _a; - var method = getPropertyOfType(type, ts.getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); + var method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); var methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : undefined; if (isTypeAny(methodType)) { return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); @@ -75849,12 +78143,12 @@ var ts; var functionFlags = ts.getFunctionFlags(func); if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - if (func.kind === 168 /* SetAccessor */) { + if (func.kind === 169 /* SetAccessor */) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 166 /* Constructor */) { + else if (func.kind === 167 /* Constructor */) { if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -75872,7 +78166,7 @@ var ts; } } } - else if (func.kind !== 166 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + else if (func.kind !== 167 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { // The function has a return type, but the return statement doesn't have an expression. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -75901,7 +78195,7 @@ var ts; var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 285 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 286 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -75910,7 +78204,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 284 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 285 /* CaseClause */) { // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable // to or from the type of the 'switch' expression. @@ -75942,7 +78236,7 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 245 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + if (current.kind === 246 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } @@ -75972,10 +78266,11 @@ var ts; // Grammar checking if (catchClause.variableDeclaration) { var declaration = catchClause.variableDeclaration; - if (declaration.type) { + var typeNode = ts.getEffectiveTypeAnnotationNode(ts.getRootDeclaration(declaration)); + if (typeNode) { var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ false); if (type && !(type.flags & 3 /* AnyOrUnknown */)) { - grammarErrorOnFirstToken(declaration.type, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified); + grammarErrorOnFirstToken(typeNode, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified); } } else if (declaration.initializer) { @@ -75986,7 +78281,7 @@ var ts; if (blockLocals_1) { ts.forEachKey(catchClause.locals, function (caughtName) { var blockLocal = blockLocals_1.get(caughtName); - if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { + if ((blockLocal === null || blockLocal === void 0 ? void 0 : blockLocal.valueDeclaration) && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); } }); @@ -75999,25 +78294,28 @@ var ts; checkBlock(node.finallyBlock); } } - function checkIndexConstraints(type) { - var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); - var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); + function checkIndexConstraints(type, isStatic) { + var _a, _b, _c, _d; + var declaredNumberIndexer = getIndexDeclarationOfSymbolTable(isStatic ? (_a = type.symbol) === null || _a === void 0 ? void 0 : _a.exports : (_b = type.symbol) === null || _b === void 0 ? void 0 : _b.members, 1 /* Number */); + var declaredStringIndexer = getIndexDeclarationOfSymbolTable(isStatic ? (_c = type.symbol) === null || _c === void 0 ? void 0 : _c.exports : (_d = type.symbol) === null || _d === void 0 ? void 0 : _d.members, 0 /* String */); var stringIndexType = getIndexTypeOfType(type, 0 /* String */); var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); if (stringIndexType || numberIndexType) { ts.forEach(getPropertiesOfObjectType(type), function (prop) { + if (isStatic && prop.flags & 4194304 /* Prototype */) + return; var propType = getTypeOfSymbol(prop); checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); var classDeclaration = type.symbol.valueDeclaration; - if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) { - for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { - var member = _a[_i]; + if (ts.getObjectFlags(type) & 1 /* Class */ && classDeclaration && ts.isClassLike(classDeclaration)) { + for (var _i = 0, _e = classDeclaration.members; _i < _e.length; _i++) { + var member = _e[_i]; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!ts.hasSyntacticModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) { + if (!ts.hasSyntacticModifier(member, 32 /* Static */) && !hasBindableName(member)) { var symbol = getSymbolOfNode(member); var propType = getTypeOfSymbol(symbol); checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); @@ -76032,7 +78330,7 @@ var ts; // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); - errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + errorNode = someBaseTypeHasBothIndexers || !type.symbol.declarations ? undefined : type.symbol.declarations[0]; } } if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217 @@ -76056,8 +78354,8 @@ var ts; // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; if (propDeclaration && name && - (propDeclaration.kind === 216 /* BinaryExpression */ || - name.kind === 158 /* ComputedPropertyName */ || + (propDeclaration.kind === 217 /* BinaryExpression */ || + name.kind === 159 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } @@ -76069,7 +78367,7 @@ var ts; // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); - errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + errorNode = someBaseClassHasBothPropertyAndIndexer || !containingType.symbol.declarations ? undefined : containingType.symbol.declarations[0]; } if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { var errorMessage = indexKind === 0 /* String */ @@ -76085,6 +78383,7 @@ var ts; switch (name.escapedText) { case "any": case "unknown": + case "never": case "number": case "bigint": case "boolean": @@ -76134,7 +78433,7 @@ var ts; function checkTypeParametersNotReferenced(root, typeParameters, index) { visit(root); function visit(node) { - if (node.kind === 173 /* TypeReference */) { + if (node.kind === 174 /* TypeReference */) { var type = getTypeFromTypeReference(node); if (type.flags & 262144 /* TypeParameter */) { for (var i = index; i < typeParameters.length; i++) { @@ -76149,14 +78448,14 @@ var ts; } /** Check that type parameter lists are identical across multiple declarations */ function checkTypeParameterListsIdentical(symbol) { - if (symbol.declarations.length === 1) { + if (symbol.declarations && symbol.declarations.length === 1) { return; } var links = getSymbolLinks(symbol); if (!links.typeParametersChecked) { links.typeParametersChecked = true; var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); - if (declarations.length <= 1) { + if (!declarations || declarations.length <= 1) { return; } var type = getDeclaredTypeOfSymbol(symbol); @@ -76220,6 +78519,9 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { + if (ts.some(node.decorators) && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { + grammarErrorOnNode(node.decorators[0], ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); + } if (!node.name && !ts.hasSyntacticModifier(node, 512 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } @@ -76248,7 +78550,8 @@ var ts; checkFunctionOrConstructorSymbol(symbol); checkClassForDuplicateDeclarations(node); // Only check for reserved static identifiers on non-ambient context. - if (!(node.flags & 8388608 /* Ambient */)) { + var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + if (!nodeInAmbientContext) { checkClassForStaticPropertyNameConflicts(node); } var baseTypeNode = ts.getEffectiveBaseTypeNode(node); @@ -76308,6 +78611,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } + checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { @@ -76337,14 +78641,76 @@ var ts; } if (produceDiagnostics) { checkIndexConstraints(type); + checkIndexConstraints(staticType, /*isStatic*/ true); checkTypeForDuplicateIndexSignatures(node); checkPropertyInitialization(node); } } + function checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType) { + var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); + var baseTypes = baseTypeNode && getBaseTypes(type); + var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; + var baseStaticType = getBaseConstructorTypeOfClass(type); + var _loop_24 = function (member) { + if (ts.hasAmbientModifier(member)) { + return "continue"; + } + if (ts.isConstructorDeclaration(member)) { + ts.forEach(member.parameters, function (param) { + if (ts.isParameterPropertyDeclaration(param, member)) { + checkClassMember(param, /*memberIsParameterProperty*/ true); + } + }); + } + checkClassMember(member); + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_24(member); + } + function checkClassMember(member, memberIsParameterProperty) { + var hasOverride = ts.hasOverrideModifier(member); + var hasStatic = ts.hasStaticModifier(member); + if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (!declaredProp) { + return; + } + var thisType = hasStatic ? staticType : typeWithThis; + var baseType = hasStatic ? baseStaticType : baseWithThis; + var prop = getPropertyOfType(thisType, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseType, declaredProp.escapedName); + var baseClassName = typeToString(baseWithThis); + if (prop && !baseProp && hasOverride) { + error(member, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); + } + else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.valueDeclaration) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { + var baseHasAbstract = ts.hasAbstractModifier(baseProp.valueDeclaration); + if (hasOverride) { + return; + } + if (!baseHasAbstract) { + var diag = memberIsParameterProperty ? + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : + ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; + error(member, diag, baseClassName); + } + else if (ts.hasAbstractModifier(member) && baseHasAbstract) { + error(member, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); + } + } + } + else if (hasOverride) { + var className = typeToString(type); + error(member, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, className); + } + } + } 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_23 = function (member) { + var _loop_25 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -76363,7 +78729,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_23(member); + _loop_25(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -76389,7 +78755,7 @@ var ts; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 252 /* ClassDeclaration */ || d.kind === 253 /* InterfaceDeclaration */; + return d.kind === 253 /* ClassDeclaration */ || d.kind === 254 /* InterfaceDeclaration */; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -76406,6 +78772,7 @@ var ts; // but not by other kinds of members. // Base class instance member variables and accessors can be overridden by // derived class instance member variables and accessors, but not by other kinds of members. + var _a, _b; // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfType(baseType); basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { @@ -76434,8 +78801,8 @@ var ts; // Searches other base types for a declaration that would satisfy the inherited abstract member. // (The class may have more than one base type via declaration merging with an interface with the // same name.) - for (var _a = 0, _b = getBaseTypes(type); _a < _b.length; _a++) { - var otherBaseType = _b[_a]; + for (var _c = 0, _d = getBaseTypes(type); _c < _d.length; _c++) { + var otherBaseType = _d[_c]; if (otherBaseType === baseType) continue; var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName); @@ -76444,7 +78811,7 @@ var ts; continue basePropertyCheck; } } - if (derivedClassDecl.kind === 221 /* ClassExpression */) { + if (derivedClassDecl.kind === 222 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -76465,7 +78832,7 @@ var ts; if (basePropertyFlags && derivedPropertyFlags) { // property/accessor is overridden with property/accessor if (baseDeclarationFlags & 128 /* Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer) - || base.valueDeclaration && base.valueDeclaration.parent.kind === 253 /* InterfaceDeclaration */ + || base.valueDeclaration && base.valueDeclaration.parent.kind === 254 /* InterfaceDeclaration */ || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) { // when the base property is abstract or from an interface, base/derived flags don't need to match // same when the derived property is from an assignment @@ -76479,13 +78846,13 @@ var ts; ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } - else if (compilerOptions.useDefineForClassFields) { - var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 163 /* PropertyDeclaration */ && !d.initializer; }); + else if (useDefineForClassFields) { + var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 164 /* PropertyDeclaration */ && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432 /* Transient */) && !(baseDeclarationFlags & 128 /* Abstract */) && !(derivedDeclarationFlags & 128 /* Abstract */) - && !derived.declarations.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); })) { + && !((_b = derived.declarations) === null || _b === void 0 ? void 0 : _b.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); }))) { var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol)); var propName = uninitialized.name; if (uninitialized.exclamationToken @@ -76596,7 +78963,7 @@ var ts; } } function isInstancePropertyWithoutInitializer(node) { - return node.kind === 163 /* PropertyDeclaration */ && + return node.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(node, 32 /* Static */ | 128 /* Abstract */) && !node.exclamationToken && !node.initializer; @@ -76620,7 +78987,7 @@ var ts; var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 253 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 254 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -76739,7 +79106,7 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: var value_2 = evaluate(expr.operand); if (typeof value_2 === "number") { switch (expr.operator) { @@ -76749,7 +79116,7 @@ var ts; } } break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { @@ -76778,7 +79145,7 @@ var ts; case 8 /* NumericLiteral */: checkGrammarNumericLiteral(expr); return +expr.text; - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return evaluate(expr.expression); case 78 /* Identifier */: var identifier = expr; @@ -76786,14 +79153,14 @@ var ts; return +(identifier.escapedText); } return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); - case 202 /* ElementAccessExpression */: - case 201 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384 /* Enum */) { var name = void 0; - if (ex.kind === 201 /* PropertyAccessExpression */) { + if (ex.kind === 202 /* PropertyAccessExpression */) { name = ex.name.escapedText; } else { @@ -76811,7 +79178,7 @@ var ts; if (memberSymbol) { var declaration = memberSymbol.valueDeclaration; if (declaration !== member) { - if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + if (declaration && isBlockScopedNameDeclaredBeforeUse(declaration, member)) { return getEnumMemberValue(declaration); } error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); @@ -76826,8 +79193,8 @@ var ts; } function isConstantMemberAccess(node) { return node.kind === 78 /* Identifier */ || - node.kind === 201 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || - node.kind === 202 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.kind === 202 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 203 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && ts.isStringLiteralLike(node.argumentExpression); } function checkEnumDeclaration(node) { @@ -76851,7 +79218,7 @@ var ts; var enumSymbol = getSymbolOfNode(node); var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); if (node === firstDeclaration) { - if (enumSymbol.declarations.length > 1) { + if (enumSymbol.declarations && enumSymbol.declarations.length > 1) { var enumIsConst_1 = ts.isEnumConst(node); // check that const is placed\omitted on all enum declarations ts.forEach(enumSymbol.declarations, function (decl) { @@ -76863,7 +79230,7 @@ var ts; var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 255 /* EnumDeclaration */) { + if (declaration.kind !== 256 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -76889,12 +79256,14 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; - if ((declaration.kind === 252 /* ClassDeclaration */ || - (declaration.kind === 251 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && - !(declaration.flags & 8388608 /* Ambient */)) { - return declaration; + if (declarations) { + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 253 /* ClassDeclaration */ || + (declaration.kind === 252 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 8388608 /* Ambient */)) { + return declaration; + } } } return undefined; @@ -76942,8 +79311,9 @@ var ts; // The following checks only apply on a non-ambient instantiated module declaration. if (symbol.flags & 512 /* ValueModule */ && !inAmbientContext + && symbol.declarations && symbol.declarations.length > 1 - && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions))) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -76955,7 +79325,7 @@ var ts; } // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. - var mergedClass = ts.getDeclarationOfKind(symbol, 252 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 253 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -77004,40 +79374,41 @@ var ts; } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { + var _a; switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // error each individual name in variable statement instead of marking the entire variable statement - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; + for (var _i = 0, _b = node.declarationList.declarations; _i < _b.length; _i++) { + var decl = _b[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 266 /* ExportAssignment */: - case 267 /* ExportDeclaration */: + case 267 /* ExportAssignment */: + case 268 /* ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 260 /* ImportEqualsDeclaration */: - case 261 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 198 /* BindingElement */: - case 249 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 250 /* VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { - for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { - var el = _c[_b]; + for (var _c = 0, _d = name.elements; _c < _d.length; _c++) { + var el = _d[_c]; // mark individual names in binding pattern checkModuleAugmentationElement(el, isGlobalAugmentation); } break; } // falls through - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 251 /* FunctionDeclaration */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 252 /* FunctionDeclaration */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } @@ -77050,7 +79421,7 @@ var ts; var reportError = !(symbol.flags & 33554432 /* Transient */); if (!reportError) { // symbol should not originate in augmentation - reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + reportError = !!((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.declarations) && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); } } break; @@ -77060,12 +79431,12 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: do { node = node.left; } while (node.kind !== 78 /* Identifier */); return node; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: do { if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) { return node.name; @@ -77085,9 +79456,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 257 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 297 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 267 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 258 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 298 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 268 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -77107,6 +79478,7 @@ var ts; return true; } function checkAliasSymbol(node) { + var _a; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { @@ -77121,21 +79493,21 @@ var ts; (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 270 /* ExportSpecifier */ ? + var message = node.kind === 271 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules - && node.kind === 270 /* ExportSpecifier */ + && node.kind === 271 /* ExportSpecifier */ && !node.parent.parent.isTypeOnly && !(target.flags & 111551 /* Value */) && !(node.flags & 8388608 /* Ambient */)) { error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type); } - if (ts.isImportSpecifier(node) && ts.every(target.declarations, function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, node.name, ts.Diagnostics._0_is_deprecated, symbol.escapedName); + if (ts.isImportSpecifier(node) && ((_a = target.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); }))) { + addDeprecatedSuggestion(node.name, target.declarations, symbol.escapedName); } } } @@ -77143,7 +79515,7 @@ var ts; checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkAliasSymbol(node); - if (node.kind === 265 /* ImportSpecifier */ && + if (node.kind === 266 /* ImportSpecifier */ && ts.idText(node.propertyName || node.name) === "default" && compilerOptions.esModuleInterop && moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) { @@ -77165,7 +79537,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 263 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 264 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015 && compilerOptions.esModuleInterop) { // import * as ns from "foo"; @@ -77193,7 +79565,7 @@ var ts; if (ts.hasSyntacticModifier(node, 1 /* Export */)) { markExportAsReferenced(node); } - if (node.moduleReference.kind !== 272 /* ExternalModuleReference */) { + if (node.moduleReference.kind !== 273 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { if (target.flags & 111551 /* Value */) { @@ -77236,10 +79608,10 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 257 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 257 /* ModuleBlock */ && + var inAmbientExternalModule = node.parent.kind === 258 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 258 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 8388608 /* Ambient */; - if (node.parent.kind !== 297 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + if (node.parent.kind !== 298 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -77272,14 +79644,14 @@ var ts; } function checkGrammarExportDeclaration(node) { var _a; - var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 268 /* NamedExports */; + var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 269 /* NamedExports */; if (isTypeOnlyExportStar) { grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type); } return !isTypeOnlyExportStar; } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 297 /* SourceFile */ || node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 256 /* ModuleDeclaration */; + var isInAppropriateContext = node.parent.kind === 298 /* SourceFile */ || node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 257 /* ModuleDeclaration */; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -77329,7 +79701,7 @@ var ts; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { @@ -77350,12 +79722,15 @@ var ts; } } function checkExportAssignment(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + var illegalContextMessage = node.isExportEquals + ? ts.Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration + : ts.Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration; + if (checkGrammarModuleElementContext(node, illegalContextMessage)) { // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 297 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 256 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 298 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 257 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -77415,7 +79790,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { + if (declaration && !isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -77439,10 +79814,12 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + if (!isDuplicatedCommonJSExport(declarations)) { + for (var _i = 0, _b = declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } } } } @@ -77451,6 +79828,11 @@ var ts; links.exportsChecked = true; } } + function isDuplicatedCommonJSExport(declarations) { + return declarations + && declarations.length > 1 + && declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && (ts.isExportsIdentifier(d.expression) || ts.isModuleExportsAccessExpression(d.expression)); }); + } function checkSourceElement(node) { if (node) { var saveCurrentNode = currentNode; @@ -77472,171 +79854,171 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 251 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } - if (kind >= 232 /* FirstStatement */ && kind <= 248 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) { + if (kind >= 233 /* FirstStatement */ && kind <= 249 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) { errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected); } switch (kind) { - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return checkTypeParameter(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return checkParameter(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return checkPropertyDeclaration(node); - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: return checkPropertySignature(node); - case 175 /* ConstructorType */: - case 174 /* FunctionType */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 176 /* ConstructorType */: + case 175 /* FunctionType */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return checkSignatureDeclaration(node); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: return checkMethodDeclaration(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return checkConstructorDeclaration(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return checkAccessorDeclaration(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return checkTypeReferenceNode(node); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return checkTypePredicate(node); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return checkTypeQuery(node); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return checkTypeLiteral(node); - case 178 /* ArrayType */: + case 179 /* ArrayType */: return checkArrayType(node); - case 179 /* TupleType */: + case 180 /* TupleType */: return checkTupleType(node); - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 186 /* ParenthesizedType */: - case 180 /* OptionalType */: - case 181 /* RestType */: + case 187 /* ParenthesizedType */: + case 181 /* OptionalType */: + case 182 /* RestType */: return checkSourceElement(node.type); - case 187 /* ThisType */: + case 188 /* ThisType */: return checkThisType(node); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return checkTypeOperator(node); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return checkConditionalType(node); - case 185 /* InferType */: + case 186 /* InferType */: return checkInferType(node); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: return checkTemplateLiteralType(node); - case 195 /* ImportType */: + case 196 /* ImportType */: return checkImportType(node); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return checkNamedTupleMember(node); - case 315 /* JSDocAugmentsTag */: + case 318 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 316 /* JSDocImplementsTag */: + case 319 /* JSDocImplementsTag */: return checkJSDocImplementsTag(node); - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return checkJSDocTypeAliasTag(node); - case 330 /* JSDocTemplateTag */: + case 334 /* JSDocTemplateTag */: return checkJSDocTemplateTag(node); - case 329 /* JSDocTypeTag */: + case 333 /* JSDocTypeTag */: return checkJSDocTypeTag(node); - case 326 /* JSDocParameterTag */: + case 330 /* JSDocParameterTag */: return checkJSDocParameterTag(node); - case 333 /* JSDocPropertyTag */: + case 337 /* JSDocPropertyTag */: return checkJSDocPropertyTag(node); - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: checkJSDocFunctionType(node); // falls through - case 306 /* JSDocNonNullableType */: - case 305 /* JSDocNullableType */: - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: - case 312 /* JSDocTypeLiteral */: + case 307 /* JSDocNonNullableType */: + case 306 /* JSDocNullableType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: + case 314 /* JSDocTypeLiteral */: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 309 /* JSDocVariadicType */: + case 310 /* JSDocVariadicType */: checkJSDocVariadicType(node); return; - case 301 /* JSDocTypeExpression */: + case 302 /* JSDocTypeExpression */: return checkSourceElement(node.type); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return checkIndexedAccessType(node); - case 190 /* MappedType */: + case 191 /* MappedType */: return checkMappedType(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 230 /* Block */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 258 /* ModuleBlock */: return checkBlock(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return checkVariableStatement(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return checkExpressionStatement(node); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return checkIfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return checkDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return checkWhileStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return checkForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return checkForInStatement(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return checkForOfStatement(node); - case 240 /* ContinueStatement */: - case 241 /* BreakStatement */: + case 241 /* ContinueStatement */: + case 242 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return checkReturnStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return checkWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return checkSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return checkLabeledStatement(node); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return checkThrowStatement(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return checkTryStatement(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return checkBindingElement(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return checkClassDeclaration(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return checkImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return checkExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return checkExportAssignment(node); - case 231 /* EmptyStatement */: - case 248 /* DebuggerStatement */: + case 232 /* EmptyStatement */: + case 249 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 271 /* MissingDeclaration */: + case 272 /* MissingDeclaration */: return checkMissingDeclaration(node); } } @@ -77681,7 +80063,8 @@ var ts; if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. var host_1 = ts.getHostSignatureFromJSDoc(paramTag); - if (host_1) { + var isCallbackTag = ts.isJSDocCallbackTag(paramTag.parent.parent); + if (host_1 || isCallbackTag) { /* Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. So in the following situation we will not create an array type: @@ -77689,7 +80072,9 @@ var ts; function f(a) {} Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. */ - var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var lastParamDeclaration = isCallbackTag + ? ts.lastOrUndefined(paramTag.parent.parent.typeExpression.parameters) + : ts.lastOrUndefined(host_1.parameters); var symbol = ts.getParameterSymbolFromJSDoc(paramTag); if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { @@ -77727,51 +80112,51 @@ var ts; } } function checkDeferredNode(node) { - ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; switch (node.kind) { - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 205 /* TaggedTemplateExpression */: - case 161 /* Decorator */: - case 275 /* JsxOpeningElement */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 206 /* TaggedTemplateExpression */: + case 162 /* Decorator */: + case 276 /* JsxOpeningElement */: // These node kinds are deferred checked when overload resolution fails // To save on work, we ensure the arguments are checked just once, in // a deferred way resolveUntypedCall(node); break; - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: checkAccessorDeclaration(node); break; - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: checkClassExpressionDeferred(node); break; - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: checkJsxSelfClosingElementDeferred(node); break; - case 273 /* JsxElement */: + case 274 /* JsxElement */: checkJsxElementDeferred(node); break; } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkSourceFile(node) { - ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeCheck"); checkSourceFileWorker(node); ts.performance.mark("afterCheck"); ts.performance.measure("Check", "beforeCheck", "afterCheck"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function unusedIsError(kind, isAmbient) { if (isAmbient) { @@ -77800,7 +80185,7 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - ts.clear(potentialWeakMapCollisions); + ts.clear(potentialWeakMapSetCollisions); ts.forEach(node.statements, checkSourceElement); checkSourceElement(node.endOfFileToken); checkDeferredNodes(node); @@ -77830,9 +80215,9 @@ var ts; ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); ts.clear(potentialNewTargetCollisions); } - if (potentialWeakMapCollisions.length) { - ts.forEach(potentialWeakMapCollisions, checkWeakMapCollision); - ts.clear(potentialWeakMapCollisions); + if (potentialWeakMapSetCollisions.length) { + ts.forEach(potentialWeakMapSetCollisions, checkWeakMapSetCollision); + ts.clear(potentialWeakMapSetCollisions); } links.flags |= 1 /* TypeChecked */; } @@ -77904,17 +80289,17 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 297 /* SourceFile */: - if (!ts.isExternalOrCommonJsModule(location)) + case 298 /* SourceFile */: + if (!ts.isExternalModule(location)) break; // falls through - case 256 /* ModuleDeclaration */: - copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); + case 257 /* ModuleDeclaration */: + copyLocallyVisibleExportSymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); @@ -77922,8 +80307,8 @@ var ts; // this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration. // falls through - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: // If we didn't come from static member of class or interface, // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. @@ -77932,7 +80317,7 @@ var ts; copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968 /* Type */); } break; - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -77972,6 +80357,16 @@ var ts; }); } } + function copyLocallyVisibleExportSymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + // Similar condition as in `resolveNameHelper` + if (!ts.getDeclarationOfKind(symbol, 271 /* ExportSpecifier */) && !ts.getDeclarationOfKind(symbol, 270 /* NamespaceExport */)) { + copySymbol(symbol, meaning); + } + }); + } + } } function isTypeDeclarationName(name) { return name.kind === 78 /* Identifier */ && @@ -77980,19 +80375,19 @@ var ts; } function isTypeDeclaration(node) { switch (node.kind) { - case 159 /* TypeParameter */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 160 /* TypeParameter */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return true; - case 262 /* ImportClause */: + case 263 /* ImportClause */: return node.isTypeOnly; - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return node.parent.parent.isTypeOnly; default: return false; @@ -78000,25 +80395,25 @@ var ts; } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(node) { - while (node.parent.kind === 157 /* QualifiedName */) { + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 173 /* TypeReference */; + return node.parent.kind === 174 /* TypeReference */; } function isHeritageClauseElementIdentifier(node) { - while (node.parent.kind === 201 /* PropertyAccessExpression */) { + while (node.parent.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 223 /* ExpressionWithTypeArguments */; + return node.parent.kind === 224 /* ExpressionWithTypeArguments */; } - function isJSDocEntryNameReference(node) { - while (node.parent.kind === 157 /* QualifiedName */) { + function getJSDocEntryNameReference(node) { + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } - while (node.parent.kind === 201 /* PropertyAccessExpression */) { + while (node.parent.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 302 /* JSDocNameReference */; + return ts.isJSDocNameReference(node.parent) ? node.parent : undefined; } function forEachEnclosingClass(node, callback) { var result; @@ -78046,13 +80441,13 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 157 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 158 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 260 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 261 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } - if (nodeOnRightSide.parent.kind === 266 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 267 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; @@ -78078,7 +80473,7 @@ var ts; node = parent; parent = parent.parent; } - if (parent && parent.kind === 195 /* ImportType */ && parent.qualifier === node) { + if (parent && parent.kind === 196 /* ImportType */ && parent.qualifier === node) { return parent; } return undefined; @@ -78088,7 +80483,7 @@ var ts; return getSymbolOfNode(name.parent); } if (ts.isInJSFile(name) && - name.parent.kind === 201 /* PropertyAccessExpression */ && + name.parent.kind === 202 /* PropertyAccessExpression */ && name.parent === name.parent.parent.left) { // Check if this is a special property assignment if (!ts.isPrivateIdentifier(name)) { @@ -78098,7 +80493,7 @@ var ts; } } } - if (name.parent.kind === 266 /* ExportAssignment */ && ts.isEntityNameExpression(name)) { + if (name.parent.kind === 267 /* ExportAssignment */ && ts.isEntityNameExpression(name)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(name, /*all meanings*/ 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); @@ -78108,7 +80503,7 @@ var ts; } else if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name) && isInRightSideOfImportOrExportAssignment(name)) { // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(name, 260 /* ImportEqualsDeclaration */); + var importEqualsDeclaration = ts.getAncestor(name, 261 /* ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true); } @@ -78126,7 +80521,7 @@ var ts; if (isHeritageClauseElementIdentifier(name)) { var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. - if (name.parent.kind === 223 /* ExpressionWithTypeArguments */) { + if (name.parent.kind === 224 /* ExpressionWithTypeArguments */) { meaning = 788968 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) { @@ -78142,10 +80537,10 @@ var ts; return entityNameSymbol; } } - if (name.parent.kind === 326 /* JSDocParameterTag */) { + if (name.parent.kind === 330 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(name.parent); } - if (name.parent.kind === 159 /* TypeParameter */ && name.parent.parent.kind === 330 /* JSDocTemplateTag */) { + if (name.parent.kind === 160 /* TypeParameter */ && name.parent.parent.kind === 334 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(name.parent); return typeParameter && typeParameter.symbol; @@ -78162,36 +80557,56 @@ var ts; } return resolveEntityName(name, 111551 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (name.kind === 201 /* PropertyAccessExpression */ || name.kind === 157 /* QualifiedName */) { + else if (name.kind === 202 /* PropertyAccessExpression */ || name.kind === 158 /* QualifiedName */) { var links = getNodeLinks(name); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (name.kind === 201 /* PropertyAccessExpression */) { - checkPropertyAccessExpression(name); + if (name.kind === 202 /* PropertyAccessExpression */) { + checkPropertyAccessExpression(name, 0 /* Normal */); } else { - checkQualifiedName(name); + checkQualifiedName(name, 0 /* Normal */); } return links.resolvedSymbol; } } else if (isTypeReferenceIdentifier(name)) { - var meaning = name.parent.kind === 173 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */; + var meaning = name.parent.kind === 174 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */; return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (isJSDocEntryNameReference(name)) { + var jsdocReference = getJSDocEntryNameReference(name); + if (jsdocReference || ts.isJSDocLink(name.parent)) { var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */; - return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); + var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ false, ts.getHostSignatureFromJSDoc(name)); + if (symbol) { + return symbol; + } + else if (ts.isQualifiedName(name) && ts.isIdentifier(name.left)) { + // resolve C.m as a static member first + var links = getNodeLinks(name); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + checkQualifiedName(name, 0 /* Normal */); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + // then resolve it as an instance member + var s = resolveEntityName(name.left, meaning, /*ignoreErrors*/ false); + if (s) { + var t = getDeclaredTypeOfSymbol(s); + return getPropertyOfType(t, name.right.escapedText); + } + } } - if (name.parent.kind === 172 /* TypePredicate */) { + if (name.parent.kind === 173 /* TypePredicate */) { return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */); } - // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node, ignoreErrors) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } var parent = node.parent; @@ -78214,8 +80629,8 @@ var ts; if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfNameOrPropertyAccessExpression(node); } - else if (parent.kind === 198 /* BindingElement */ && - grandParent.kind === 196 /* ObjectBindingPattern */ && + else if (parent.kind === 199 /* BindingElement */ && + grandParent.kind === 197 /* ObjectBindingPattern */ && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); @@ -78227,8 +80642,8 @@ var ts; switch (node.kind) { case 78 /* Identifier */: case 79 /* PrivateIdentifier */: - case 201 /* PropertyAccessExpression */: - case 157 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: return getSymbolOfNameOrPropertyAccessExpression(node); case 107 /* ThisKeyword */: var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); @@ -78242,14 +80657,14 @@ var ts; return checkExpression(node).symbol; } // falls through - case 187 /* ThisType */: + case 188 /* ThisType */: return getTypeFromThisTypeNode(node).symbol; case 105 /* SuperKeyword */: return checkExpression(node).symbol; case 132 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 166 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 167 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; @@ -78260,7 +80675,7 @@ var ts; // 3). Dynamic import call or require in javascript // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 261 /* ImportDeclaration */ || node.parent.kind === 267 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((node.parent.kind === 262 /* ImportDeclaration */ || node.parent.kind === 268 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || ((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, ignoreErrors); @@ -78282,7 +80697,7 @@ var ts; case 38 /* EqualsGreaterThanToken */: case 83 /* ClassKeyword */: return getSymbolOfNode(node.parent); - case 195 /* ImportType */: + case 196 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined; case 92 /* ExportKeyword */: return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined; @@ -78291,7 +80706,7 @@ var ts; } } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 289 /* ShorthandPropertyAssignment */) { + if (location && location.kind === 290 /* ShorthandPropertyAssignment */) { return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */); } return undefined; @@ -78370,27 +80785,27 @@ var ts; // [ a ] from // [a] = [ some array ...] function getTypeOfAssignmentPattern(expr) { - ts.Debug.assert(expr.kind === 200 /* ObjectLiteralExpression */ || expr.kind === 199 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.kind === 201 /* ObjectLiteralExpression */ || expr.kind === 200 /* ArrayLiteralExpression */); // If this is from "for of" // for ( { a } of elems) { // } - if (expr.parent.kind === 239 /* ForOfStatement */) { + if (expr.parent.kind === 240 /* ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 216 /* BinaryExpression */) { + if (expr.parent.kind === 217 /* BinaryExpression */) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 288 /* PropertyAssignment */) { - var node_2 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); - var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_2) || errorType; - var propertyIndex = ts.indexOfNode(node_2.properties, expr.parent); - return checkObjectLiteralDestructuringPropertyAssignment(node_2, typeOfParentObjectLiteral, propertyIndex); + if (expr.parent.kind === 289 /* PropertyAssignment */) { + var node_3 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); + var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_3) || errorType; + var propertyIndex = ts.indexOfNode(node_3.properties, expr.parent); + return checkObjectLiteralDestructuringPropertyAssignment(node_3, typeOfParentObjectLiteral, propertyIndex); } // Array literal assignment - array destructuring pattern var node = ts.cast(expr.parent, ts.isArrayLiteralExpression); @@ -78434,7 +80849,7 @@ var ts; case 8 /* NumericLiteral */: case 10 /* StringLiteral */: return getLiteralType(name.text); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(name); return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType; default: @@ -78531,6 +80946,7 @@ var ts; // When resolved as an expression identifier, if the given node references an exported entity, return the declaration // node of the exported entity's container. Otherwise, return undefined. function getReferencedExportContainer(nodeIn, prefixLocals) { + var _a; var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { // When resolving the export container for the name of a module or enum @@ -78551,7 +80967,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 297 /* SourceFile */) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && ((_a = parentSymbol_1.valueDeclaration) === null || _a === void 0 ? void 0 : _a.kind) === 298 /* SourceFile */) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -78581,11 +80997,12 @@ var ts; return undefined; } function isSymbolOfDestructuredElementOfCatchBinding(symbol) { - return ts.isBindingElement(symbol.valueDeclaration) - && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 287 /* CatchClause */; + return symbol.valueDeclaration + && ts.isBindingElement(symbol.valueDeclaration) + && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 288 /* CatchClause */; } function isSymbolOfDeclarationWithCollidingName(symbol) { - if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) { + if (symbol.flags & 418 /* BlockScoped */ && symbol.valueDeclaration && !ts.isSourceFile(symbol.valueDeclaration)) { var links = getSymbolLinks(symbol); if (links.isDeclarationWithCollidingName === undefined) { var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); @@ -78613,7 +81030,7 @@ var ts; // they will not collide with anything var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 230 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 231 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -78654,19 +81071,19 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: var symbol = getSymbolOfNode(node) || unknownSymbol; return isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: var exportClause = node.exportClause; return !!exportClause && (ts.isNamespaceExport(exportClause) || ts.some(exportClause.elements, isValueAliasDeclaration)); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return node.expression && node.expression.kind === 78 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; @@ -78675,7 +81092,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 297 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 298 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -78690,7 +81107,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 & 111551 /* Value */) && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; @@ -78698,13 +81115,14 @@ var ts; function isReferencedAliasDeclaration(node, checkChildren) { if (isAliasSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); - if (symbol && getSymbolLinks(symbol).referenced) { + var links = symbol && getSymbolLinks(symbol); + if (links === null || links === void 0 ? void 0 : links.referenced) { return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 if (target && ts.getEffectiveModifierFlags(node) & 1 /* Export */ && target.flags & 111551 /* Value */ && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -78741,13 +81159,13 @@ var ts; !isOptionalParameter(parameter) && !ts.isJSDocParameterTag(parameter) && !!parameter.initializer && - !ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + !ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && - ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameter(parameter) { return !!strictNullChecks && @@ -78782,15 +81200,15 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 291 /* EnumMember */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 292 /* EnumMember */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return true; } return false; } function getConstantValue(node) { - if (node.kind === 291 /* EnumMember */) { + if (node.kind === 292 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -78943,8 +81361,7 @@ var ts; } function isLiteralConstDeclaration(node) { if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 2944 /* Literal */) && isFreshLiteralType(type); + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } @@ -79063,12 +81480,12 @@ var ts; getJsxFragmentFactoryEntity: getJsxFragmentFactoryEntity, getAllAccessorDeclarations: function (accessor) { accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 - var otherKind = accessor.kind === 168 /* SetAccessor */ ? 167 /* GetAccessor */ : 168 /* SetAccessor */; + var otherKind = accessor.kind === 169 /* SetAccessor */ ? 168 /* GetAccessor */ : 169 /* SetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; - var setAccessor = accessor.kind === 168 /* SetAccessor */ ? accessor : otherAccessor; - var getAccessor = accessor.kind === 167 /* GetAccessor */ ? accessor : otherAccessor; + var setAccessor = accessor.kind === 169 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 168 /* GetAccessor */ ? accessor : otherAccessor; return { firstAccessor: firstAccessor, secondAccessor: secondAccessor, @@ -79084,7 +81501,7 @@ var ts; }, getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) { var n = ts.getParseTreeNode(node); - ts.Debug.assert(n && n.kind === 297 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile"); + ts.Debug.assert(n && n.kind === 298 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile"); var sym = getSymbolOfNode(node); if (!sym) { return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled); @@ -79107,11 +81524,13 @@ var ts; var s = _a[_i]; if (s.mergeId) { var merged = getMergedSymbol(s); - for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { - var d = _c[_b]; - var declFile = ts.getSourceFileOfNode(d); - if (declFile === importTarget) { - return true; + if (merged.declarations) { + for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declFile = ts.getSourceFileOfNode(d); + if (declFile === importTarget) { + return true; + } } } } @@ -79119,7 +81538,7 @@ var ts; return false; } function isInHeritageClause(node) { - return node.parent && node.parent.kind === 223 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 286 /* HeritageClause */; + return node.parent && node.parent.kind === 224 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 287 /* HeritageClause */; } // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -79131,7 +81550,7 @@ var ts; // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries var meaning = 788968 /* Type */ | 1920 /* Namespace */; - if ((node.kind === 78 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 201 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { + if ((node.kind === 78 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 202 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { meaning = 111551 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); @@ -79140,10 +81559,7 @@ var ts; // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForSymbol(symbol, meaning) { // program does not have any files with type reference directives - bail out - if (!fileToDirective) { - return undefined; - } - if (!isSymbolFromTypeDeclarationFile(symbol)) { + if (!fileToDirective || !isSymbolFromTypeDeclarationFile(symbol)) { return undefined; } // check what declarations in the symbol can contribute to the target meaning @@ -79182,7 +81598,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 297 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 298 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -79210,12 +81626,12 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = declaration.kind === 256 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 257 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 297 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 298 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -79235,7 +81651,7 @@ var ts; // It is an error for a non-external-module (i.e. script) to declare its own `globalThis`. // We can't use `builtinGlobals` for this due to synthetic expando-namespace generation in JS files. var fileGlobalThisSymbol = file.locals.get("globalThis"); - if (fileGlobalThisSymbol) { + if (fileGlobalThisSymbol === null || fileGlobalThisSymbol === void 0 ? void 0 : fileGlobalThisSymbol.declarations) { for (var _d = 0, _e = fileGlobalThisSymbol.declarations; _d < _e.length; _d++) { var declaration = _e[_d]; diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis")); @@ -79359,6 +81775,16 @@ var ts; if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name); } + else if (helper & 524288 /* ClassPrivateFieldGet */) { + if (!ts.some(getSignaturesOfSymbol(symbol), function (signature) { return getParameterCount(signature) > 3; })) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name, 4); + } + } + else if (helper & 1048576 /* ClassPrivateFieldSet */) { + if (!ts.some(getSignaturesOfSymbol(symbol), function (signature) { return getParameterCount(signature) > 4; })) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name, 5); + } + } } } } @@ -79408,14 +81834,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { - if (node.kind === 165 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + if (node.kind === 166 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 167 /* GetAccessor */ || node.kind === 168 /* SetAccessor */) { + else if (node.kind === 168 /* GetAccessor */ || node.kind === 169 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -79428,24 +81854,41 @@ var ts; if (quickResult !== undefined) { return quickResult; } - var lastStatic, lastDeclare, lastAsync, lastReadonly; + var lastStatic, lastDeclare, lastAsync, lastReadonly, lastOverride; var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; if (modifier.kind !== 142 /* ReadonlyKeyword */) { - if (node.kind === 162 /* PropertySignature */ || node.kind === 164 /* MethodSignature */) { + if (node.kind === 163 /* PropertySignature */ || node.kind === 165 /* MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 171 /* IndexSignature */) { + if (node.kind === 172 /* IndexSignature */ && (modifier.kind !== 123 /* StaticKeyword */ || !ts.isClassLike(node.parent))) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { case 84 /* ConstKeyword */: - if (node.kind !== 255 /* EnumDeclaration */) { + if (node.kind !== 256 /* EnumDeclaration */) { return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(84 /* ConstKeyword */)); } break; + case 156 /* OverrideKeyword */: + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "override"); + } + else if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "async"); + } + flags |= 16384 /* Override */; + lastOverride = modifier; + break; case 122 /* PublicKeyword */: case 121 /* ProtectedKeyword */: case 120 /* PrivateKeyword */: @@ -79453,6 +81896,9 @@ var ts; if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "override"); + } else if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } @@ -79462,7 +81908,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + else if (node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { @@ -79473,7 +81919,7 @@ var ts; return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); } } - else if (ts.isPrivateIdentifierPropertyDeclaration(node)) { + else if (ts.isPrivateIdentifierClassElementDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier); } flags |= ts.modifierToFlag(modifier.kind); @@ -79488,17 +81934,17 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + else if (node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - else if (ts.isPrivateIdentifierPropertyDeclaration(node)) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "static"); + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "override"); } flags |= 32 /* Static */; lastStatic = modifier; @@ -79507,8 +81953,8 @@ var ts; if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 163 /* PropertyDeclaration */ && node.kind !== 162 /* PropertySignature */ && node.kind !== 171 /* IndexSignature */ && node.kind !== 160 /* Parameter */) { - // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. + else if (node.kind !== 164 /* PropertyDeclaration */ && node.kind !== 163 /* PropertySignature */ && node.kind !== 172 /* IndexSignature */ && node.kind !== 161 /* Parameter */) { + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; @@ -79530,14 +81976,14 @@ var ts; else if (ts.isClassLike(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "export"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* Export */; break; case 87 /* DefaultKeyword */: - var container = node.parent.kind === 297 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 256 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 298 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 257 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512 /* Default */; @@ -79549,16 +81995,19 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override"); + } else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 257 /* ModuleBlock */) { + else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 258 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } - else if (ts.isPrivateIdentifierPropertyDeclaration(node)) { + else if (ts.isPrivateIdentifierClassElementDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare"); } flags |= 2 /* Ambient */; @@ -79568,15 +82017,15 @@ var ts; if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 252 /* ClassDeclaration */ && - node.kind !== 175 /* ConstructorType */) { - if (node.kind !== 165 /* MethodDeclaration */ && - node.kind !== 163 /* PropertyDeclaration */ && - node.kind !== 167 /* GetAccessor */ && - node.kind !== 168 /* SetAccessor */) { + if (node.kind !== 253 /* ClassDeclaration */ && + node.kind !== 176 /* ConstructorType */) { + if (node.kind !== 166 /* MethodDeclaration */ && + node.kind !== 164 /* PropertyDeclaration */ && + node.kind !== 168 /* GetAccessor */ && + node.kind !== 169 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 252 /* ClassDeclaration */ && ts.hasSyntacticModifier(node.parent, 128 /* Abstract */))) { + if (!(node.parent.kind === 253 /* ClassDeclaration */ && ts.hasSyntacticModifier(node.parent, 128 /* Abstract */))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -79588,6 +82037,9 @@ var ts; if (flags & 256 /* Async */ && lastAsync) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); } + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override"); + } } if (ts.isNamedDeclaration(node) && node.name.kind === 79 /* PrivateIdentifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract"); @@ -79601,7 +82053,7 @@ var ts; else if (flags & 2 /* Ambient */ || node.parent.flags & 8388608 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } if (flags & 128 /* Abstract */) { @@ -79612,13 +82064,16 @@ var ts; break; } } - if (node.kind === 166 /* Constructor */) { + if (node.kind === 167 /* Constructor */) { if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } if (flags & 128 /* Abstract */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 } + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(lastOverride, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); // TODO: GH#18217 + } else if (flags & 256 /* Async */) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } @@ -79627,13 +82082,13 @@ var ts; } return false; } - else if ((node.kind === 261 /* ImportDeclaration */ || node.kind === 260 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 262 /* ImportDeclaration */ || node.kind === 261 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 160 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 160 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { @@ -79654,38 +82109,38 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 166 /* Constructor */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 171 /* IndexSignature */: - case 256 /* ModuleDeclaration */: - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 160 /* Parameter */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 167 /* Constructor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 172 /* IndexSignature */: + case 257 /* ModuleDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 161 /* Parameter */: return false; default: - if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + if (node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { return false; } switch (node.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return nodeHasAnyModifiersExcept(node, 129 /* AsyncKeyword */); - case 252 /* ClassDeclaration */: - case 175 /* ConstructorType */: + case 253 /* ClassDeclaration */: + case 176 /* ConstructorType */: return nodeHasAnyModifiersExcept(node, 125 /* AbstractKeyword */); - case 253 /* InterfaceDeclaration */: - case 232 /* VariableStatement */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 233 /* VariableStatement */: + case 255 /* TypeAliasDeclaration */: return true; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return nodeHasAnyModifiersExcept(node, 84 /* ConstKeyword */); default: ts.Debug.fail(); @@ -79697,10 +82152,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -79861,7 +82316,7 @@ var ts; if (args) { for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { var arg = args_4[_i]; - if (arg.kind === 222 /* OmittedExpression */) { + if (arg.kind === 223 /* OmittedExpression */) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -79938,20 +82393,20 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 158 /* ComputedPropertyName */) { + if (node.kind !== 159 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 216 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { + if (computedPropertyName.expression.kind === 217 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 251 /* FunctionDeclaration */ || - node.kind === 208 /* FunctionExpression */ || - node.kind === 165 /* MethodDeclaration */); + ts.Debug.assert(node.kind === 252 /* FunctionDeclaration */ || + node.kind === 209 /* FunctionExpression */ || + node.kind === 166 /* MethodDeclaration */); if (node.flags & 8388608 /* Ambient */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -79970,7 +82425,7 @@ var ts; var seen = new ts.Map(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 290 /* SpreadAssignment */) { + if (prop.kind === 291 /* SpreadAssignment */) { if (inDestructuring) { // a rest property cannot be destructured any further var expression = ts.skipParentheses(prop.expression); @@ -79981,24 +82436,24 @@ var ts; continue; } var name = prop.name; - if (name.kind === 158 /* ComputedPropertyName */) { + if (name.kind === 159 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name); } - if (prop.kind === 289 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 290 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern); } if (name.kind === 79 /* PrivateIdentifier */) { - return grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); } // Modifiers are never allowed on properties except for 'async' on a method declaration if (prop.modifiers) { // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 var mod = _c[_b]; - if (mod.kind !== 129 /* AsyncKeyword */ || prop.kind !== 165 /* MethodDeclaration */) { + if (mod.kind !== 129 /* AsyncKeyword */ || prop.kind !== 166 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } @@ -80013,10 +82468,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 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); // falls through - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -80024,13 +82479,13 @@ var ts; } currentKind = 4 /* PropertyAssignment */; break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: currentKind = 8 /* Method */; break; - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: currentKind = 1 /* GetAccessor */; break; - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: currentKind = 2 /* SetAccessor */; break; default: @@ -80065,11 +82520,12 @@ var ts; } } function checkGrammarJsxElement(node) { + checkGrammarJsxName(node.tagName); checkGrammarTypeArguments(node, node.typeArguments); var seen = new ts.Map(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 282 /* JsxSpreadAttribute */) { + if (attr.kind === 283 /* JsxSpreadAttribute */) { continue; } var name = attr.name, initializer = attr.initializer; @@ -80079,11 +82535,32 @@ var ts; else { return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - if (initializer && initializer.kind === 283 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 284 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } } + function checkGrammarJsxName(node) { + if (ts.isPropertyAccessExpression(node)) { + var propName = node; + do { + var check_1 = checkGrammarJsxNestedIdentifier(propName.name); + if (check_1) { + return check_1; + } + propName = propName.expression; + } while (ts.isPropertyAccessExpression(propName)); + var check = checkGrammarJsxNestedIdentifier(propName); + if (check) { + return check; + } + } + function checkGrammarJsxNestedIdentifier(name) { + if (ts.isIdentifier(name) && ts.idText(name).indexOf(":") !== -1) { + return grammarErrorOnNode(name, ts.Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names); + } + } + } function checkGrammarJsxExpression(node) { if (node.expression && ts.isCommaSequence(node.expression)) { return grammarErrorOnNode(node.expression, ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array); @@ -80093,25 +82570,37 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 239 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { - if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) { - // use of 'for-await-of' in non-async function + if (forInOrOfStatement.kind === 240 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if (!(forInOrOfStatement.flags & 32768 /* AwaitContext */)) { var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement); - if (!hasParseDiagnostics(sourceFile)) { - var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); - var func = ts.getContainingFunction(forInOrOfStatement); - if (func && func.kind !== 166 /* Constructor */) { - ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); - var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); - ts.addRelatedInfo(diagnostic, relatedInfo); - } - diagnostics.add(diagnostic); - return true; + if (ts.isInTopLevelContext(forInOrOfStatement)) { + if (!hasParseDiagnostics(sourceFile)) { + if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module)); + } + if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher)); + } + } + } + else { + // use of 'for-await-of' in non-async function + if (!hasParseDiagnostics(sourceFile)) { + var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); + var func = ts.getContainingFunction(forInOrOfStatement); + if (func && func.kind !== 167 /* Constructor */) { + ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); + var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); + ts.addRelatedInfo(diagnostic, relatedInfo); + } + diagnostics.add(diagnostic); + return true; + } } return false; } } - if (forInOrOfStatement.initializer.kind === 250 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 251 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -80126,20 +82615,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 239 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 239 /* ForInStatement */ ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 239 /* ForInStatement */ ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -80149,26 +82638,34 @@ var ts; return false; } function checkGrammarAccessor(accessor) { - if (!(accessor.flags & 8388608 /* Ambient */)) { + if (!(accessor.flags & 8388608 /* Ambient */) && (accessor.parent.kind !== 178 /* TypeLiteral */) && (accessor.parent.kind !== 254 /* InterfaceDeclaration */)) { if (languageVersion < 1 /* ES5 */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } + if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(accessor.name)) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } if (accessor.body === undefined && !ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) { return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } - if (accessor.body && ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) { - return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + if (accessor.body) { + if (ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + if (accessor.parent.kind === 178 /* TypeLiteral */ || accessor.parent.kind === 254 /* InterfaceDeclaration */) { + return grammarErrorOnNode(accessor.body, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } } if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, accessor.kind === 167 /* GetAccessor */ ? + return grammarErrorOnNode(accessor.name, accessor.kind === 168 /* GetAccessor */ ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - if (accessor.kind === 168 /* SetAccessor */) { + if (accessor.kind === 169 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -80190,10 +82687,10 @@ var ts; * A set accessor has one parameter or a `this` parameter and one more parameter. */ function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 167 /* GetAccessor */ ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 168 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 167 /* GetAccessor */ ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 168 /* GetAccessor */ ? 1 : 2)) { return ts.getThisParameter(accessor); } } @@ -80211,7 +82708,7 @@ var ts; } } switch (parent.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: var decl = parent; if (decl.name.kind !== 78 /* Identifier */) { return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); @@ -80223,13 +82720,13 @@ var ts; return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); } break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: if (!ts.hasSyntacticModifier(parent, 32 /* Static */) || !ts.hasEffectiveModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: if (!ts.hasSyntacticModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } @@ -80239,7 +82736,7 @@ var ts; } } else if (node.operator === 142 /* ReadonlyKeyword */) { - if (node.type.kind !== 178 /* ArrayType */ && node.type.kind !== 179 /* TupleType */) { + if (node.type.kind !== 179 /* ArrayType */ && node.type.kind !== 180 /* TupleType */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(148 /* SymbolKeyword */)); } } @@ -80253,8 +82750,8 @@ var ts; if (checkGrammarFunctionLikeDeclaration(node)) { return true; } - if (node.kind === 165 /* MethodDeclaration */) { - if (node.parent.kind === 200 /* ObjectLiteralExpression */) { + if (node.kind === 166 /* MethodDeclaration */) { + if (node.parent.kind === 201 /* ObjectLiteralExpression */) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 129 /* AsyncKeyword */)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -80274,6 +82771,9 @@ var ts; } } if (ts.isClassLike(node.parent)) { + if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) { + return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } // Technically, computed properties in ambient contexts is disallowed // for property declarations and accessors too, not just methods. // However, property declarations disallow computed names in general, @@ -80282,14 +82782,14 @@ var ts; if (node.flags & 8388608 /* Ambient */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.kind === 165 /* MethodDeclaration */ && !node.body) { + else if (node.kind === 166 /* MethodDeclaration */ && !node.body) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 253 /* InterfaceDeclaration */) { + else if (node.parent.kind === 254 /* InterfaceDeclaration */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 177 /* TypeLiteral */) { + else if (node.parent.kind === 178 /* TypeLiteral */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } @@ -80300,11 +82800,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: if (node.label && current.label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 240 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 241 /* ContinueStatement */ && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -80312,8 +82812,8 @@ var ts; return false; } break; - case 244 /* SwitchStatement */: - if (node.kind === 241 /* BreakStatement */ && !node.label) { + case 245 /* SwitchStatement */: + if (node.kind === 242 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -80328,13 +82828,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 241 /* BreakStatement */ + var message = node.kind === 242 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 241 /* BreakStatement */ + var message = node.kind === 242 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -80358,12 +82858,12 @@ var ts; } function isStringOrNumberLiteralExpression(expr) { return ts.isStringOrNumericLiteralLike(expr) || - expr.kind === 214 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && + expr.kind === 215 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } function isBigIntLiteralExpression(expr) { return expr.kind === 9 /* BigIntLiteral */ || - expr.kind === 214 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && + expr.kind === 215 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && expr.operand.kind === 9 /* BigIntLiteral */; } function isSimpleLiteralEnumReference(expr) { @@ -80394,7 +82894,7 @@ var ts; } } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 238 /* ForInStatement */ && node.parent.parent.kind !== 239 /* ForOfStatement */) { + if (node.parent.parent.kind !== 239 /* ForInStatement */ && node.parent.parent.kind !== 240 /* ForOfStatement */) { if (node.flags & 8388608 /* Ambient */) { checkAmbientInitializer(node); } @@ -80407,7 +82907,7 @@ var ts; } } } - if (node.exclamationToken && (node.parent.parent.kind !== 232 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) { + if (node.exclamationToken && (node.parent.parent.kind !== 233 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) { var message = node.initializer ? ts.Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type @@ -80475,15 +82975,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 234 /* IfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 243 /* WithStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 235 /* IfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 244 /* WithStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: return false; - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -80568,14 +83068,14 @@ var ts; if (ts.isStringLiteral(node.name) && node.name.text === "constructor") { return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor); } - if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type)) { return true; } if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) { return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); } } - else if (node.parent.kind === 253 /* InterfaceDeclaration */) { + else if (node.parent.kind === 254 /* InterfaceDeclaration */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -80583,7 +83083,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 177 /* TypeLiteral */) { + else if (node.parent.kind === 178 /* TypeLiteral */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -80617,13 +83117,13 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 253 /* InterfaceDeclaration */ || - node.kind === 254 /* TypeAliasDeclaration */ || - node.kind === 261 /* ImportDeclaration */ || - node.kind === 260 /* ImportEqualsDeclaration */ || - node.kind === 267 /* ExportDeclaration */ || - node.kind === 266 /* ExportAssignment */ || - node.kind === 259 /* NamespaceExportDeclaration */ || + if (node.kind === 254 /* InterfaceDeclaration */ || + node.kind === 255 /* TypeAliasDeclaration */ || + node.kind === 262 /* ImportDeclaration */ || + node.kind === 261 /* ImportEqualsDeclaration */ || + node.kind === 268 /* ExportDeclaration */ || + node.kind === 267 /* ExportAssignment */ || + node.kind === 260 /* NamespaceExportDeclaration */ || ts.hasSyntacticModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } @@ -80632,7 +83132,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 232 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 233 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -80655,7 +83155,7 @@ var ts; // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if (node.parent.kind === 230 /* Block */ || node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + if (node.parent.kind === 231 /* Block */ || node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { var links_2 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_2.hasReportedStatementInAmbientContext) { @@ -80677,10 +83177,10 @@ var ts; if (languageVersion >= 1 /* ES5 */) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 191 /* LiteralType */)) { + else if (ts.isChildOfNodeWithKind(node, 192 /* LiteralType */)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 291 /* EnumMember */)) { + else if (ts.isChildOfNodeWithKind(node, 292 /* EnumMember */)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { @@ -80786,7 +83286,7 @@ var ts; } } function findBestTypeForObjectLiteral(source, unionTarget) { - if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) { + if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && someType(unionTarget, isArrayLikeType)) { return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } @@ -80838,6 +83338,10 @@ var ts; // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) { if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) { + var match = getMatchingUnionConstituentForType(target, source); + if (match) { + return match; + } var sourceProperties = getPropertiesOfType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); @@ -80855,33 +83359,19 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 251 /* FunctionDeclaration */ && declaration.kind !== 165 /* MethodDeclaration */) || + return (declaration.kind !== 252 /* FunctionDeclaration */ && declaration.kind !== 166 /* MethodDeclaration */) || !!declaration.body; } /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return ts.isIdentifier(name); default: return ts.isDeclarationName(name); } } - function isSomeImportDeclaration(decl) { - switch (decl.kind) { - case 262 /* ImportClause */: // For default import - case 260 /* ImportEqualsDeclaration */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: // For rename import `x as y` - return true; - case 78 /* Identifier */: - // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 265 /* ImportSpecifier */; - default: - return false; - } - } var JsxNames; (function (JsxNames) { JsxNames.JSX = "JSX"; @@ -80912,7 +83402,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); function visitNode(node, visitor, test, lift) { if (node === undefined || visitor === undefined) { return node; @@ -81101,6 +83590,24 @@ var ts; return updated; } ts.visitFunctionBody = visitFunctionBody; + /** + * Visits an iteration body, adding any block-scoped variables required by the transformation. + */ + function visitIterationBody(body, visitor, context) { + context.startBlockScope(); + var updated = visitNode(body, visitor, ts.isStatement, context.factory.liftToBlock); + var declarations = context.endBlockScope(); + if (ts.some(declarations)) { + if (ts.isBlock(updated)) { + declarations.push.apply(declarations, updated.statements); + return context.factory.updateBlock(updated, declarations); + } + declarations.push(updated); + return context.factory.createBlock(declarations); + } + return updated; + } + ts.visitIterationBody = visitIterationBody; function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor, nodeVisitor) { if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } if (nodeVisitor === void 0) { nodeVisitor = visitNode; } @@ -81109,299 +83616,433 @@ var ts; } var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 156 /* LastToken */) || kind === 187 /* ThisType */) { + if ((kind > 0 /* FirstToken */ && kind <= 157 /* LastToken */) || kind === 188 /* ThisType */) { return node; } var factory = context.factory; switch (kind) { // Names case 78 /* Identifier */: - return factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); - case 157 /* QualifiedName */: + ts.Debug.type(node); + return factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNodeOrTypeParameterDeclaration)); + case 158 /* QualifiedName */: + ts.Debug.type(node); return factory.updateQualifiedName(node, nodeVisitor(node.left, visitor, ts.isEntityName), nodeVisitor(node.right, visitor, ts.isIdentifier)); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: + ts.Debug.type(node); return factory.updateComputedPropertyName(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Signature elements - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: + ts.Debug.type(node); return factory.updateTypeParameterDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode)); - case 160 /* Parameter */: - return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 161 /* Decorator */: + case 161 /* Parameter */: + ts.Debug.type(node); + return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 162 /* Decorator */: + ts.Debug.type(node); return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Type elements - case 162 /* PropertySignature */: - return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 163 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + ts.Debug.type(node); + return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 164 /* PropertyDeclaration */: + ts.Debug.type(node); return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too - nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 164 /* MethodSignature */: - return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 165 /* MethodDeclaration */: - return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 166 /* Constructor */: + nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isQuestionOrExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 165 /* MethodSignature */: + ts.Debug.type(node); + return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 166 /* MethodDeclaration */: + ts.Debug.type(node); + return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 167 /* Constructor */: + ts.Debug.type(node); return factory.updateConstructorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: + ts.Debug.type(node); return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: + ts.Debug.type(node); return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 169 /* CallSignature */: + case 170 /* CallSignature */: + ts.Debug.type(node); return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: + ts.Debug.type(node); return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: + ts.Debug.type(node); return factory.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); // Types - case 172 /* TypePredicate */: - return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor), nodeVisitor(node.parameterName, visitor), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 173 /* TypeReference */: + case 173 /* TypePredicate */: + ts.Debug.type(node); + return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor, ts.isAssertsKeyword), nodeVisitor(node.parameterName, visitor, ts.isIdentifierOrThisTypeNode), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 174 /* TypeReference */: + ts.Debug.type(node); return factory.updateTypeReferenceNode(node, nodeVisitor(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 174 /* FunctionType */: + case 175 /* FunctionType */: + ts.Debug.type(node); return factory.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 175 /* ConstructorType */: + case 176 /* ConstructorType */: + ts.Debug.type(node); return factory.updateConstructorTypeNode(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: + ts.Debug.type(node); return factory.updateTypeQueryNode(node, nodeVisitor(node.exprName, visitor, ts.isEntityName)); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: + ts.Debug.type(node); return factory.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 178 /* ArrayType */: + case 179 /* ArrayType */: + ts.Debug.type(node); return factory.updateArrayTypeNode(node, nodeVisitor(node.elementType, visitor, ts.isTypeNode)); - case 179 /* TupleType */: + case 180 /* TupleType */: + ts.Debug.type(node); return factory.updateTupleTypeNode(node, nodesVisitor(node.elements, visitor, ts.isTypeNode)); - case 180 /* OptionalType */: + case 181 /* OptionalType */: + ts.Debug.type(node); return factory.updateOptionalTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 181 /* RestType */: + case 182 /* RestType */: + ts.Debug.type(node); return factory.updateRestTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 182 /* UnionType */: + case 183 /* UnionType */: + ts.Debug.type(node); return factory.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 183 /* IntersectionType */: + case 184 /* IntersectionType */: + ts.Debug.type(node); return factory.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: + ts.Debug.type(node); return factory.updateConditionalTypeNode(node, nodeVisitor(node.checkType, visitor, ts.isTypeNode), nodeVisitor(node.extendsType, visitor, ts.isTypeNode), nodeVisitor(node.trueType, visitor, ts.isTypeNode), nodeVisitor(node.falseType, visitor, ts.isTypeNode)); - case 185 /* InferType */: + case 186 /* InferType */: + ts.Debug.type(node); return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); - case 195 /* ImportType */: + case 196 /* ImportType */: + ts.Debug.type(node); return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); - case 192 /* NamedTupleMember */: - return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); - case 186 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: + ts.Debug.type(node); + return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isDotDotDotToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isQuestionToken), visitNode(node.type, visitor, ts.isTypeNode)); + case 187 /* ParenthesizedType */: + ts.Debug.type(node); return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: + ts.Debug.type(node); return factory.updateTypeOperatorNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: + ts.Debug.type(node); return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode)); - case 190 /* MappedType */: - return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 191 /* LiteralType */: + case 191 /* MappedType */: + ts.Debug.type(node); + return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 192 /* LiteralType */: + ts.Debug.type(node); return factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression)); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: + ts.Debug.type(node); return factory.updateTemplateLiteralType(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateLiteralTypeSpan)); - case 194 /* TemplateLiteralTypeSpan */: + case 195 /* TemplateLiteralTypeSpan */: + ts.Debug.type(node); return factory.updateTemplateLiteralTypeSpan(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Binding patterns - case 196 /* ObjectBindingPattern */: + case 197 /* ObjectBindingPattern */: + ts.Debug.type(node); return factory.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: + ts.Debug.type(node); return factory.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); - case 198 /* BindingElement */: - return factory.updateBindingElement(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.propertyName, visitor, ts.isPropertyName), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 199 /* BindingElement */: + ts.Debug.type(node); + return factory.updateBindingElement(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.propertyName, visitor, ts.isPropertyName), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.initializer, visitor, ts.isExpression)); // Expression - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: + ts.Debug.type(node); return factory.updateArrayLiteralExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression)); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + ts.Debug.type(node); return factory.updateObjectLiteralExpression(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (node.flags & 32 /* OptionalChain */) { - return factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier)); + ts.Debug.type(node); + return factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodeVisitor(node.name, visitor, ts.isMemberName)); } - return factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isIdentifierOrPrivateIdentifier)); - case 202 /* ElementAccessExpression */: + ts.Debug.type(node); + return factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isMemberName)); + case 203 /* ElementAccessExpression */: if (node.flags & 32 /* OptionalChain */) { - return factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); } + ts.Debug.type(node); return factory.updateElementAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (node.flags & 32 /* OptionalChain */) { - return factory.updateCallChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateCallChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); } + ts.Debug.type(node); return factory.updateCallExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 204 /* NewExpression */: + case 205 /* NewExpression */: + ts.Debug.type(node); return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 205 /* TaggedTemplateExpression */: - return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); - case 206 /* TypeAssertionExpression */: + case 206 /* TaggedTemplateExpression */: + ts.Debug.type(node); + return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); + case 207 /* TypeAssertionExpression */: + ts.Debug.type(node); return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: + ts.Debug.type(node); return factory.updateParenthesizedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 208 /* FunctionExpression */: - return factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 209 /* ArrowFunction */: - return factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, ts.isToken), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 210 /* DeleteExpression */: + case 209 /* FunctionExpression */: + ts.Debug.type(node); + return factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 210 /* ArrowFunction */: + ts.Debug.type(node); + return factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, ts.isEqualsGreaterThanToken), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 211 /* DeleteExpression */: + ts.Debug.type(node); return factory.updateDeleteExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: + ts.Debug.type(node); return factory.updateTypeOfExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: + ts.Debug.type(node); return factory.updateVoidExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: + ts.Debug.type(node); return factory.updateAwaitExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + ts.Debug.type(node); return factory.updatePrefixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression)); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + ts.Debug.type(node); return factory.updatePostfixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression)); - case 216 /* BinaryExpression */: - return factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isToken), nodeVisitor(node.right, visitor, ts.isExpression)); - case 217 /* ConditionalExpression */: - return factory.updateConditionalExpression(node, nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.whenTrue, visitor, ts.isExpression), nodeVisitor(node.colonToken, tokenVisitor, ts.isToken), nodeVisitor(node.whenFalse, visitor, ts.isExpression)); - case 218 /* TemplateExpression */: + case 217 /* BinaryExpression */: + ts.Debug.type(node); + return factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isBinaryOperatorToken), nodeVisitor(node.right, visitor, ts.isExpression)); + case 218 /* ConditionalExpression */: + ts.Debug.type(node); + return factory.updateConditionalExpression(node, nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.whenTrue, visitor, ts.isExpression), nodeVisitor(node.colonToken, tokenVisitor, ts.isColonToken), nodeVisitor(node.whenFalse, visitor, ts.isExpression)); + case 219 /* TemplateExpression */: + ts.Debug.type(node); return factory.updateTemplateExpression(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); - case 219 /* YieldExpression */: - return factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 220 /* SpreadElement */: + case 220 /* YieldExpression */: + ts.Debug.type(node); + return factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.expression, visitor, ts.isExpression)); + case 221 /* SpreadElement */: + ts.Debug.type(node); return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: + ts.Debug.type(node); return factory.updateClassExpression(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: + ts.Debug.type(node); return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 224 /* AsExpression */: + case 225 /* AsExpression */: + ts.Debug.type(node); return factory.updateAsExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: if (node.flags & 32 /* OptionalChain */) { + ts.Debug.type(node); return factory.updateNonNullChain(node, nodeVisitor(node.expression, visitor, ts.isExpression)); } + ts.Debug.type(node); return factory.updateNonNullExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: + ts.Debug.type(node); return factory.updateMetaProperty(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); // Misc - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: + ts.Debug.type(node); return factory.updateTemplateSpan(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element - case 230 /* Block */: + case 231 /* Block */: + ts.Debug.type(node); return factory.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: + ts.Debug.type(node); return factory.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: + ts.Debug.type(node); return factory.updateExpressionStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 234 /* IfStatement */: + case 235 /* IfStatement */: + ts.Debug.type(node); return factory.updateIfStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.thenStatement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.elseStatement, visitor, ts.isStatement, factory.liftToBlock)); - case 235 /* DoStatement */: - return factory.updateDoStatement(node, nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 236 /* WhileStatement */: - return factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 237 /* ForStatement */: - return factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.incrementor, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 238 /* ForInStatement */: - return factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 239 /* ForOfStatement */: - return factory.updateForOfStatement(node, nodeVisitor(node.awaitModifier, tokenVisitor, ts.isToken), nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 240 /* ContinueStatement */: + case 236 /* DoStatement */: + ts.Debug.type(node); + return factory.updateDoStatement(node, visitIterationBody(node.statement, visitor, context), nodeVisitor(node.expression, visitor, ts.isExpression)); + case 237 /* WhileStatement */: + ts.Debug.type(node); + return factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 238 /* ForStatement */: + ts.Debug.type(node); + return factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.incrementor, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 239 /* ForInStatement */: + ts.Debug.type(node); + return factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 240 /* ForOfStatement */: + ts.Debug.type(node); + return factory.updateForOfStatement(node, nodeVisitor(node.awaitModifier, tokenVisitor, ts.isAwaitKeyword), nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 241 /* ContinueStatement */: + ts.Debug.type(node); return factory.updateContinueStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier)); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: + ts.Debug.type(node); return factory.updateBreakStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier)); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: + ts.Debug.type(node); return factory.updateReturnStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 243 /* WithStatement */: + case 244 /* WithStatement */: + ts.Debug.type(node); return factory.updateWithStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: + ts.Debug.type(node); return factory.updateSwitchStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.caseBlock, visitor, ts.isCaseBlock)); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: + ts.Debug.type(node); return factory.updateLabeledStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: + ts.Debug.type(node); return factory.updateThrowStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 247 /* TryStatement */: + case 248 /* TryStatement */: + ts.Debug.type(node); return factory.updateTryStatement(node, nodeVisitor(node.tryBlock, visitor, ts.isBlock), nodeVisitor(node.catchClause, visitor, ts.isCatchClause), nodeVisitor(node.finallyBlock, visitor, ts.isBlock)); - case 249 /* VariableDeclaration */: - return factory.updateVariableDeclaration(node, nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 250 /* VariableDeclarationList */: + case 250 /* VariableDeclaration */: + ts.Debug.type(node); + return factory.updateVariableDeclaration(node, nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.exclamationToken, tokenVisitor, ts.isExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 251 /* VariableDeclarationList */: + ts.Debug.type(node); return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); - case 251 /* FunctionDeclaration */: - return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 252 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: + ts.Debug.type(node); + return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 253 /* ClassDeclaration */: + ts.Debug.type(node); return factory.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: + ts.Debug.type(node); return factory.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: + ts.Debug.type(node); return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: + ts.Debug.type(node); return factory.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); - case 256 /* ModuleDeclaration */: - return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.body, visitor, ts.isModuleBody)); - case 257 /* ModuleBlock */: + case 257 /* ModuleDeclaration */: + ts.Debug.type(node); + return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); + case 258 /* ModuleBlock */: + ts.Debug.type(node); return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: + ts.Debug.type(node); return factory.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: + ts.Debug.type(node); return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: + ts.Debug.type(node); return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: + ts.Debug.type(node); return factory.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression)); - case 262 /* ImportClause */: + case 263 /* ImportClause */: + ts.Debug.type(node); return factory.updateImportClause(node, node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.namedBindings, visitor, ts.isNamedImportBindings)); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: + ts.Debug.type(node); return factory.updateNamespaceImport(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: + ts.Debug.type(node); return factory.updateNamespaceExport(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 264 /* NamedImports */: + case 265 /* NamedImports */: + ts.Debug.type(node); return factory.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: + ts.Debug.type(node); return factory.updateImportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: + ts.Debug.type(node); return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: + ts.Debug.type(node); return factory.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression)); - case 268 /* NamedExports */: + case 269 /* NamedExports */: + ts.Debug.type(node); return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: + ts.Debug.type(node); return factory.updateExportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); // Module references - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: + ts.Debug.type(node); return factory.updateExternalModuleReference(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // JSX - case 273 /* JsxElement */: + case 274 /* JsxElement */: + ts.Debug.type(node); return factory.updateJsxElement(node, nodeVisitor(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingElement, visitor, ts.isJsxClosingElement)); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: + ts.Debug.type(node); return factory.updateJsxSelfClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes)); - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: + ts.Debug.type(node); return factory.updateJsxOpeningElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes)); - case 276 /* JsxClosingElement */: + case 277 /* JsxClosingElement */: + ts.Debug.type(node); return factory.updateJsxClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: + ts.Debug.type(node); return factory.updateJsxFragment(node, nodeVisitor(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingFragment, visitor, ts.isJsxClosingFragment)); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: + ts.Debug.type(node); return factory.updateJsxAttribute(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: + ts.Debug.type(node); return factory.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 282 /* JsxSpreadAttribute */: + case 283 /* JsxSpreadAttribute */: + ts.Debug.type(node); return factory.updateJsxSpreadAttribute(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: + ts.Debug.type(node); return factory.updateJsxExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Clauses - case 284 /* CaseClause */: + case 285 /* CaseClause */: + ts.Debug.type(node); return factory.updateCaseClause(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: + ts.Debug.type(node); return factory.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: + ts.Debug.type(node); return factory.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 287 /* CatchClause */: + case 288 /* CatchClause */: + ts.Debug.type(node); return factory.updateCatchClause(node, nodeVisitor(node.variableDeclaration, visitor, ts.isVariableDeclaration), nodeVisitor(node.block, visitor, ts.isBlock)); // Property assignments - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: + ts.Debug.type(node); return factory.updatePropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + ts.Debug.type(node); return factory.updateShorthandPropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: + ts.Debug.type(node); return factory.updateSpreadAssignment(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Enum - case 291 /* EnumMember */: + case 292 /* EnumMember */: + ts.Debug.type(node); return factory.updateEnumMember(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression)); // Top-level nodes - case 297 /* SourceFile */: + case 298 /* SourceFile */: + ts.Debug.type(node); return factory.updateSourceFile(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 336 /* PartiallyEmittedExpression */: + case 340 /* PartiallyEmittedExpression */: + ts.Debug.type(node); return factory.updatePartiallyEmittedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: + ts.Debug.type(node); return factory.updateCommaListExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -82076,7 +84717,7 @@ var ts; function chainBundle(context, transformSourceFile) { return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - return node.kind === 297 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + return node.kind === 298 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); } function transformBundle(node) { return context.factory.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); @@ -82127,7 +84768,7 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: // import "mod" // import x from "mod" // import * as x from "mod" @@ -82140,13 +84781,13 @@ var ts; hasImportDefault = true; } break; - case 260 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 272 /* ExternalModuleReference */) { + case 261 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 273 /* ExternalModuleReference */) { // import x = require("mod") externalImports.push(node); } break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" @@ -82177,13 +84818,13 @@ var ts; addExportedNamesForExportDeclaration(node); } break; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; } break; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: if (ts.hasSyntacticModifier(node, 1 /* Export */)) { for (var _b = 0, _c = node.declarationList.declarations; _b < _c.length; _b++) { var decl = _c[_b]; @@ -82191,7 +84832,7 @@ var ts; } } break; - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: if (ts.hasSyntacticModifier(node, 1 /* Export */)) { if (ts.hasSyntacticModifier(node, 512 /* Default */)) { // export default function() { } @@ -82211,7 +84852,7 @@ var ts; } } break; - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: if (ts.hasSyntacticModifier(node, 1 /* Export */)) { if (ts.hasSyntacticModifier(node, 512 /* Default */)) { // export default class { } @@ -82305,8 +84946,7 @@ var ts; * any such locations */ function isSimpleInlineableExpression(expression) { - return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression) || - ts.isWellKnownSymbolSyntactically(expression); + return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression); } ts.isSimpleInlineableExpression = isSimpleInlineableExpression; function isCompoundAssignment(kind) { @@ -82385,10 +85025,19 @@ var ts; * @param isStatic A value indicating whether the member should be a static or instance member. */ function isInitializedProperty(member) { - return member.kind === 163 /* PropertyDeclaration */ + return member.kind === 164 /* PropertyDeclaration */ && member.initializer !== undefined; } ts.isInitializedProperty = isInitializedProperty; + /** + * Gets a value indicating whether a class element is a private instance method or accessor. + * + * @param member The class element node. + */ + function isNonStaticMethodOrAccessorWithPrivateName(member) { + return !ts.hasStaticModifier(member) && ts.isMethodOrAccessor(member) && ts.isPrivateIdentifier(member.name); + } + ts.isNonStaticMethodOrAccessorWithPrivateName = isNonStaticMethodOrAccessorWithPrivateName; })(ts || (ts = {})); /*@internal*/ var ts; @@ -82662,8 +85311,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */)) + && !(element.transformFlags & (16384 /* ContainsRestOrSpread */ | 32768 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (16384 /* ContainsRestOrSpread */ | 32768 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor)); } @@ -82729,7 +85378,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 & 16384 /* ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { + if (element.transformFlags & 32768 /* ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { flattenContext.hasTransformedPriorElement = true; var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { @@ -82987,8 +85636,8 @@ var ts; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; // Enable substitution for property/element access to emit const enum values. - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(202 /* ElementAccessExpression */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(203 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; @@ -83014,14 +85663,14 @@ var ts; var applicableSubstitutions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - if (node.kind === 298 /* Bundle */) { + if (node.kind === 299 /* Bundle */) { return transformBundle(node); } return transformSourceFile(node); } function transformBundle(node) { return factory.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 300 /* InputFiles */) { + if (prepend.kind === 301 /* InputFiles */) { return ts.createUnparsedSourceFile(prepend, "js"); } return prepend; @@ -83072,16 +85721,16 @@ var ts; */ function onBeforeVisitNode(node) { switch (node.kind) { - case 297 /* SourceFile */: - case 258 /* CaseBlock */: - case 257 /* ModuleBlock */: - case 230 /* Block */: + case 298 /* SourceFile */: + case 259 /* CaseBlock */: + case 258 /* ModuleBlock */: + case 231 /* Block */: currentLexicalScope = node; currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; - case 252 /* ClassDeclaration */: - case 251 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: if (ts.hasSyntacticModifier(node, 2 /* Ambient */)) { break; } @@ -83093,7 +85742,7 @@ var ts; // These nodes should always have names unless they are default-exports; // however, class declaration parsing allows for undefined names, so syntactically invalid // programs may also have an undefined name. - ts.Debug.assert(node.kind === 252 /* ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* Default */)); + ts.Debug.assert(node.kind === 253 /* ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* Default */)); } if (ts.isClassDeclaration(node)) { // XXX: should probably also cover interfaces and type aliases that can have type variables? @@ -83136,10 +85785,10 @@ var ts; */ function sourceElementVisitorWorker(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 266 /* ExportAssignment */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 267 /* ExportAssignment */: + case 268 /* ExportDeclaration */: return visitElidableStatement(node); default: return visitorWorker(node); @@ -83160,13 +85809,13 @@ var ts; return node; } switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -83186,11 +85835,11 @@ var ts; * @param node The node to visit. */ function namespaceElementVisitorWorker(node) { - if (node.kind === 267 /* ExportDeclaration */ || - node.kind === 261 /* ImportDeclaration */ || - node.kind === 262 /* ImportClause */ || - (node.kind === 260 /* ImportEqualsDeclaration */ && - node.moduleReference.kind === 272 /* ExternalModuleReference */)) { + if (node.kind === 268 /* ExportDeclaration */ || + node.kind === 262 /* ImportDeclaration */ || + node.kind === 263 /* ImportClause */ || + (node.kind === 261 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 273 /* ExternalModuleReference */)) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -83214,26 +85863,26 @@ var ts; */ function classElementVisitorWorker(node) { switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return visitConstructor(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // Property declarations are not TypeScript syntax, but they must be visited // for the decorator transformation. return visitPropertyDeclaration(node); - case 171 /* IndexSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: + case 172 /* IndexSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: // Fallback to the default visit behavior. return visitorWorker(node); - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: return node; default: return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { - if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) { + if (ts.modifierToFlag(node.kind) & 18654 /* TypeScriptModifier */) { return undefined; } else if (currentNamespace && node.kind === 92 /* ExportKeyword */) { @@ -83266,13 +85915,13 @@ var ts; case 142 /* ReadonlyKeyword */: // TypeScript accessibility and readonly modifiers are elided // falls through - case 178 /* ArrayType */: - case 179 /* TupleType */: - case 180 /* OptionalType */: - case 181 /* RestType */: - case 177 /* TypeLiteral */: - case 172 /* TypePredicate */: - case 159 /* TypeParameter */: + case 179 /* ArrayType */: + case 180 /* TupleType */: + case 181 /* OptionalType */: + case 182 /* RestType */: + case 178 /* TypeLiteral */: + case 173 /* TypePredicate */: + case 160 /* TypeParameter */: case 128 /* AnyKeyword */: case 152 /* UnknownKeyword */: case 131 /* BooleanKeyword */: @@ -83281,43 +85930,43 @@ var ts; case 141 /* NeverKeyword */: case 113 /* VoidKeyword */: case 148 /* SymbolKeyword */: - case 175 /* ConstructorType */: - case 174 /* FunctionType */: - case 176 /* TypeQuery */: - case 173 /* TypeReference */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 184 /* ConditionalType */: - case 186 /* ParenthesizedType */: - case 187 /* ThisType */: - case 188 /* TypeOperator */: - case 189 /* IndexedAccessType */: - case 190 /* MappedType */: - case 191 /* LiteralType */: + case 176 /* ConstructorType */: + case 175 /* FunctionType */: + case 177 /* TypeQuery */: + case 174 /* TypeReference */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 185 /* ConditionalType */: + case 187 /* ParenthesizedType */: + case 188 /* ThisType */: + case 189 /* TypeOperator */: + case 190 /* IndexedAccessType */: + case 191 /* MappedType */: + case 192 /* LiteralType */: // TypeScript type nodes are elided. // falls through - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: // TypeScript index signatures are elided. // falls through - case 161 /* Decorator */: + case 162 /* Decorator */: // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. // falls through - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return undefined; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects return visitPropertyDeclaration(node); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 166 /* Constructor */: + case 167 /* Constructor */: return visitConstructor(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return factory.createNotEmittedStatement(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: // This may be a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -83327,7 +85976,7 @@ var ts; // - index signatures // - method overload signatures return visitClassDeclaration(node); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: // This may be a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -83337,35 +85986,35 @@ var ts; // - index signatures // - method overload signatures return visitClassExpression(node); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: // This may be a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause return visitHeritageClause(node); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); - case 160 /* Parameter */: + case 161 /* Parameter */: // This may be a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: @@ -83375,40 +86024,40 @@ var ts; // - type annotations // - this parameters return visitParameter(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: // ParenthesizedExpressions are TypeScript if their expression is a // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return visitNewExpression(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node); - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: return visitJsxJsxOpeningElement(node); default: // node contains some other TypeScript syntax @@ -83462,7 +86111,7 @@ var ts; return facts; } function hasTypeScriptClassSyntax(node) { - return !!(node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */); + return !!(node.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */); } function isClassLikeDeclarationWithTypeScriptSyntax(node) { return ts.some(node.decorators) @@ -83817,12 +86466,12 @@ var ts; */ function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return getAllDecoratorsOfAccessors(node, member); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return getAllDecoratorsOfMethod(member); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -83975,7 +86624,7 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); var descriptor = languageVersion > 0 /* ES3 */ - ? member.kind === 163 /* PropertyDeclaration */ + ? member.kind === 164 /* PropertyDeclaration */ // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it // should not invoke `Object.getOwnPropertyDescriptor`. ? factory.createVoidZero() @@ -84099,10 +86748,10 @@ var ts; */ function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 163 /* PropertyDeclaration */; + return kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 164 /* PropertyDeclaration */; } /** * Determines whether to emit the "design:returntype" metadata based on the node's kind. @@ -84112,7 +86761,7 @@ var ts; * @param node The node to test. */ function shouldAddReturnTypeMetadata(node) { - return node.kind === 165 /* MethodDeclaration */; + return node.kind === 166 /* MethodDeclaration */; } /** * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. @@ -84123,12 +86772,12 @@ var ts; */ function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return ts.getFirstConstructorWithBody(node) !== undefined; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return true; } return false; @@ -84145,15 +86794,15 @@ var ts; */ function serializeTypeOfNode(node) { switch (node.kind) { - case 163 /* PropertyDeclaration */: - case 160 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 161 /* Parameter */: return serializeTypeNode(node.type); - case 168 /* SetAccessor */: - case 167 /* GetAccessor */: + case 169 /* SetAccessor */: + case 168 /* GetAccessor */: return serializeTypeNode(getAccessorTypeNode(node)); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 165 /* MethodDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 166 /* MethodDeclaration */: return factory.createIdentifier("Function"); default: return factory.createVoidZero(); @@ -84190,7 +86839,7 @@ var ts; return factory.createArrayLiteralExpression(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 167 /* GetAccessor */) { + if (container && node.kind === 168 /* GetAccessor */) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -84239,27 +86888,27 @@ var ts; case 150 /* UndefinedKeyword */: case 141 /* NeverKeyword */: return factory.createVoidZero(); - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return serializeTypeNode(node.type); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return factory.createIdentifier("Function"); - case 178 /* ArrayType */: - case 179 /* TupleType */: + case 179 /* ArrayType */: + case 180 /* TupleType */: return factory.createIdentifier("Array"); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: case 131 /* BooleanKeyword */: return factory.createIdentifier("Boolean"); case 147 /* StringKeyword */: return factory.createIdentifier("String"); case 145 /* ObjectKeyword */: return factory.createIdentifier("Object"); - case 191 /* LiteralType */: + case 192 /* LiteralType */: switch (node.literal.kind) { case 10 /* StringLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: return factory.createIdentifier("String"); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: case 8 /* NumericLiteral */: return factory.createIdentifier("Number"); case 9 /* BigIntLiteral */: @@ -84280,37 +86929,37 @@ var ts; return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : factory.createIdentifier("Symbol"); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return serializeTypeReferenceNode(node); - case 183 /* IntersectionType */: - case 182 /* UnionType */: + case 184 /* IntersectionType */: + case 183 /* UnionType */: return serializeTypeList(node.types); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return serializeTypeList([node.trueType, node.falseType]); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: if (node.operator === 142 /* ReadonlyKeyword */) { return serializeTypeNode(node.type); } break; - case 176 /* TypeQuery */: - case 189 /* IndexedAccessType */: - case 190 /* MappedType */: - case 177 /* TypeLiteral */: + case 177 /* TypeQuery */: + case 190 /* IndexedAccessType */: + case 191 /* MappedType */: + case 178 /* TypeLiteral */: case 128 /* AnyKeyword */: case 152 /* UnknownKeyword */: - case 187 /* ThisType */: - case 195 /* ImportType */: + case 188 /* ThisType */: + case 196 /* ImportType */: break; // handle JSDoc types from an invalid parse - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: - case 308 /* JSDocFunctionType */: - case 309 /* JSDocVariadicType */: - case 310 /* JSDocNamepathType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: + case 309 /* JSDocFunctionType */: + case 310 /* JSDocVariadicType */: + case 311 /* JSDocNamepathType */: break; - case 305 /* JSDocNullableType */: - case 306 /* JSDocNonNullableType */: - case 307 /* JSDocOptionalType */: + case 306 /* JSDocNullableType */: + case 307 /* JSDocNonNullableType */: + case 308 /* JSDocOptionalType */: return serializeTypeNode(node.type); default: return ts.Debug.failBadSyntaxKind(node); @@ -84323,13 +86972,13 @@ var ts; var serializedUnion; for (var _i = 0, types_24 = types; _i < types_24.length; _i++) { var typeNode = types_24[_i]; - while (typeNode.kind === 186 /* ParenthesizedType */) { + while (typeNode.kind === 187 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } if (typeNode.kind === 141 /* NeverKeyword */) { continue; // Always elide `never` from the union/intersection if possible } - if (!strictNullChecks && (typeNode.kind === 191 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { + if (!strictNullChecks && (typeNode.kind === 192 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } var serializedIndividual = serializeTypeNode(typeNode); @@ -84439,7 +87088,7 @@ var ts; name.original = undefined; ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node. return name; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return serializeQualifiedNameAsExpression(node); } } @@ -84827,8 +87476,7 @@ var ts; */ function shouldEmitEnumDeclaration(node) { return !ts.isEnumConst(node) - || compilerOptions.preserveConstEnums - || compilerOptions.isolatedModules; + || ts.shouldPreserveConstEnums(compilerOptions); } /** * Visits an enum declaration. @@ -84962,7 +87610,7 @@ var ts; // If we can't find a parse tree node, assume the node is instantiated. return true; } - return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions)); } /** * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` @@ -85013,12 +87661,12 @@ var ts; // enums in any other scope are emitted as a `let` declaration. var statement = factory.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.createVariableDeclarationList([ factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ], currentLexicalScope.kind === 297 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ], currentLexicalScope.kind === 298 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { // Adjust the source map emit to match the old emitter. - if (node.kind === 255 /* EnumDeclaration */) { + if (node.kind === 256 /* EnumDeclaration */) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -85143,7 +87791,7 @@ var ts; var statementsLocation; var blockLocation; if (node.body) { - if (node.body.kind === 257 /* ModuleBlock */) { + if (node.body.kind === 258 /* ModuleBlock */) { saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = node.body.statements; blockLocation = node.body; @@ -85190,13 +87838,13 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (!node.body || node.body.kind !== 257 /* ModuleBlock */) { + if (!node.body || node.body.kind !== 258 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 256 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 257 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -85246,7 +87894,7 @@ var ts; * @param node The named import bindings node. */ function visitNamedImportBindings(node) { - if (node.kind === 263 /* NamespaceImport */) { + if (node.kind === 264 /* NamespaceImport */) { // Elide a namespace import if it is not referenced. return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } @@ -85499,16 +88147,16 @@ var ts; // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to // substitute the names of exported members of a namespace. context.enableSubstitution(78 /* Identifier */); - context.enableSubstitution(289 /* ShorthandPropertyAssignment */); + context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // We need to be notified when entering and exiting namespaces. - context.enableEmitNotification(256 /* ModuleDeclaration */); + context.enableEmitNotification(257 /* ModuleDeclaration */); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 256 /* ModuleDeclaration */; + return ts.getOriginalNode(node).kind === 257 /* ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 255 /* EnumDeclaration */; + return ts.getOriginalNode(node).kind === 256 /* EnumDeclaration */; } /** * Hook for node emit. @@ -85569,9 +88217,9 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return substituteExpressionIdentifier(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return substituteElementAccessExpression(node); } return node; @@ -85593,10 +88241,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_1 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_1, node); - ts.setCommentRange(clone_1, node); - return clone_1; + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -85609,9 +88257,9 @@ var ts; // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container && container.kind !== 297 /* SourceFile */) { - var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 256 /* ModuleDeclaration */) || - (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 255 /* EnumDeclaration */); + if (container && container.kind !== 298 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 257 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 256 /* EnumDeclaration */); if (substitute) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(container), node), /*location*/ node); @@ -85663,10 +88311,12 @@ var ts; */ ClassPropertySubstitutionFlags[ClassPropertySubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; })(ClassPropertySubstitutionFlags || (ClassPropertySubstitutionFlags = {})); - var PrivateIdentifierPlacement; - (function (PrivateIdentifierPlacement) { - PrivateIdentifierPlacement[PrivateIdentifierPlacement["InstanceField"] = 0] = "InstanceField"; - })(PrivateIdentifierPlacement || (PrivateIdentifierPlacement = {})); + var PrivateIdentifierKind; + (function (PrivateIdentifierKind) { + PrivateIdentifierKind["Field"] = "f"; + PrivateIdentifierKind["Method"] = "m"; + PrivateIdentifierKind["Accessor"] = "a"; + })(PrivateIdentifierKind = ts.PrivateIdentifierKind || (ts.PrivateIdentifierKind = {})); /** * Transforms ECMAScript Class Syntax. * TypeScript parameter property syntax is transformed in the TypeScript transformer. @@ -85675,11 +88325,12 @@ var ts; * When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty. */ function transformClassFields(context) { - var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment; + var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, addBlockScopedVariable = context.addBlockScopedVariable; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var shouldTransformPrivateFields = languageVersion < 99 /* ESNext */; + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); + var shouldTransformPrivateElements = languageVersion < 99 /* ESNext */; var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; var enabledSubstitutions; @@ -85700,7 +88351,7 @@ var ts; function transformSourceFile(node) { var options = context.getCompilerOptions(); if (node.isDeclarationFile - || options.useDefineForClassFields && options.target === 99 /* ESNext */) { + || useDefineForClassFields && options.target === 99 /* ESNext */) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -85708,41 +88359,41 @@ var ts; return visited; } function visitor(node) { - if (!(node.transformFlags & 4194304 /* ContainsClassFields */)) + if (!(node.transformFlags & 8388608 /* ContainsClassFields */)) return node; switch (node.kind) { - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: return visitClassLike(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return visitPropertyDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return visitPropertyAccessExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return visitPrefixUnaryExpression(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return visitPostfixUnaryExpression(node, /*valueIsDiscarded*/ false); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node); case 79 /* PrivateIdentifier */: return visitPrivateIdentifier(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitExpressionStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); } return ts.visitEachChild(node, visitor, context); } function visitorDestructuringTarget(node) { switch (node.kind) { - case 200 /* ObjectLiteralExpression */: - case 199 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitAssignmentPattern(node); default: return visitor(node); @@ -85753,7 +88404,7 @@ var ts; * Replace it with an empty identifier to indicate a problem with the code. */ function visitPrivateIdentifier(node) { - if (!shouldTransformPrivateFields) { + if (!shouldTransformPrivateElements) { return node; } return ts.setOriginalNode(factory.createIdentifier(""), node); @@ -85765,20 +88416,19 @@ var ts; */ function classElementVisitor(node) { switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: // Constructors for classes using class fields are transformed in // `visitClassDeclaration` or `visitClassExpression`. return undefined; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: - // Visit the name of the member (if it's a computed property name). - return ts.visitEachChild(node, classElementVisitor, context); - case 163 /* PropertyDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + return visitMethodOrAccessorDeclaration(node); + case 164 /* PropertyDeclaration */: return visitPropertyDeclaration(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: return node; default: return visitor(node); @@ -85803,44 +88453,96 @@ var ts; } return node; } + function visitMethodOrAccessorDeclaration(node) { + ts.Debug.assert(!ts.some(node.decorators)); + if (!shouldTransformPrivateElements || !ts.isPrivateIdentifier(node.name)) { + return ts.visitEachChild(node, classElementVisitor, context); + } + // leave invalid code untransformed + var info = accessPrivateIdentifier(node.name); + ts.Debug.assert(info, "Undeclared private name for property declaration."); + if (!info.isValid) { + return node; + } + var functionName = getHoistedFunctionName(node); + if (functionName) { + getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return !ts.isStaticModifier(m); }), node.asteriskToken, functionName, + /* typeParameters */ undefined, ts.visitParameterList(node.parameters, classElementVisitor, context), + /* type */ undefined, ts.visitFunctionBody(node.body, classElementVisitor, context)))); + } + // remove method declaration from class + return undefined; + } + function getHoistedFunctionName(node) { + ts.Debug.assert(ts.isPrivateIdentifier(node.name)); + var info = accessPrivateIdentifier(node.name); + ts.Debug.assert(info, "Undeclared private name for property declaration."); + if (info.kind === "m" /* Method */) { + return info.methodName; + } + if (info.kind === "a" /* Accessor */) { + if (ts.isGetAccessor(node)) { + return info.getterName; + } + if (ts.isSetAccessor(node)) { + return info.setterName; + } + } + } function visitPropertyDeclaration(node) { ts.Debug.assert(!ts.some(node.decorators)); - if (!shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) { - // Initializer is elided as the field is initialized in transformConstructor. - return factory.updatePropertyDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, - /*questionOrExclamationToken*/ undefined, - /*type*/ undefined, - /*initializer*/ undefined); + if (ts.isPrivateIdentifier(node.name)) { + if (!shouldTransformPrivateElements) { + // Initializer is elided as the field is initialized in transformConstructor. + return factory.updatePropertyDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined); + } + // leave invalid code untransformed + var info = accessPrivateIdentifier(node.name); + ts.Debug.assert(info, "Undeclared private name for property declaration."); + if (!info.isValid) { + return node; + } } // Create a temporary variable to store a computed property name (if necessary). // If it's not inlineable, then we emit an expression after the class which assigns // the property name to the temporary variable. - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { getPendingExpressions().push(expr); } return undefined; } function createPrivateIdentifierAccess(info, receiver) { - receiver = ts.visitNode(receiver, visitor, ts.isExpression); - switch (info.placement) { - case 0 /* InstanceField */: - return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(ts.nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver), info.weakMapName); - default: return ts.Debug.fail("Unexpected private identifier placement"); + return createPrivateIdentifierAccessHelper(info, ts.visitNode(receiver, visitor, ts.isExpression)); + } + function createPrivateIdentifierAccessHelper(info, receiver) { + ts.setCommentRange(receiver, ts.moveRangePos(receiver, -1)); + switch (info.kind) { + case "a" /* Accessor */: + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.getterName); + case "m" /* Method */: + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.methodName); + case "f" /* Field */: + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.variableName); + default: + ts.Debug.assertNever(info, "Unknown private element type"); } } function visitPropertyAccessExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifier(node.name)) { var privateIdentifierInfo = accessPrivateIdentifier(node.name); if (privateIdentifierInfo) { - return ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node); + return ts.setTextRange(ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node), node); } } return ts.visitEachChild(node, visitor, context); } function visitPrefixUnaryExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { var operator = node.operator === 45 /* PlusPlusToken */ ? 39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ? 40 /* MinusToken */ : undefined; @@ -85855,7 +88557,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitPostfixUnaryExpression(node, valueIsDiscarded) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { var operator = node.operator === 45 /* PlusPlusToken */ ? 39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ? 40 /* MinusToken */ : undefined; @@ -85876,7 +88578,7 @@ var ts; } function visitForStatement(node) { if (node.incrementor && ts.isPostfixUnaryExpression(node.incrementor)) { - return factory.updateForStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), visitPostfixUnaryExpression(node.incrementor, /*valueIsDiscarded*/ true), ts.visitNode(node.statement, visitor, ts.isStatement)); + return factory.updateForStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), visitPostfixUnaryExpression(node.incrementor, /*valueIsDiscarded*/ true), ts.visitIterationBody(node.statement, visitor, context)); } return ts.visitEachChild(node, visitor, context); } @@ -85896,16 +88598,21 @@ var ts; return { readExpression: readExpression, initializeExpression: initializeExpression }; } function visitCallExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { // Transform call expressions of private names to properly bind the `this` parameter. var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; + if (ts.isCallChain(node)) { + return factory.updateCallChain(node, factory.createPropertyAccessChain(ts.visitNode(target, visitor), node.questionDotToken, "call"), + /*questionDotToken*/ undefined, + /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); + } return factory.updateCallExpression(node, factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "call"), /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); } return ts.visitEachChild(node, visitor, context); } function visitTaggedTemplateExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) { // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access. var _a = factory.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; return factory.updateTaggedTemplateExpression(node, factory.createCallExpression(factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "bind"), @@ -85915,7 +88622,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitBinaryExpression(node) { - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { if (ts.isDestructuringAssignment(node)) { var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; @@ -85929,29 +88636,31 @@ var ts; if (ts.isAssignmentExpression(node) && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) { var info = accessPrivateIdentifier(node.left.name); if (info) { - return ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node); + return ts.setTextRange(ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node), node); } } } return ts.visitEachChild(node, visitor, context); } function createPrivateIdentifierAssignment(info, receiver, right, operator) { - switch (info.placement) { - case 0 /* InstanceField */: { - return createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator); - } - default: return ts.Debug.fail("Unexpected private identifier placement"); - } - } - function createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator) { receiver = ts.visitNode(receiver, visitor, ts.isExpression); right = ts.visitNode(right, visitor, ts.isExpression); if (ts.isCompoundAssignment(operator)) { var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression; - return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(initializeExpression || readExpression, info.weakMapName, factory.createBinaryExpression(context.getEmitHelperFactory().createClassPrivateFieldGetHelper(readExpression, info.weakMapName), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right)); - } - else { - return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.weakMapName, right); + receiver = initializeExpression || readExpression; + right = factory.createBinaryExpression(createPrivateIdentifierAccessHelper(info, readExpression), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right); + } + ts.setCommentRange(receiver, ts.moveRangePos(receiver, -1)); + switch (info.kind) { + case "a" /* Accessor */: + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, info.setterName); + case "m" /* Method */: + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, + /* f */ undefined); + case "f" /* Field */: + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, info.variableName); + default: + ts.Debug.assertNever(info, "Unknown private element type"); } } /** @@ -85960,25 +88669,43 @@ var ts; function visitClassLike(node) { var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { startPrivateIdentifierEnvironment(); + var name = ts.getNameOfDeclaration(node); + if (name && ts.isIdentifier(name)) { + getPrivateIdentifierEnvironment().className = ts.idText(name); + } + var privateInstanceMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); + if (ts.some(privateInstanceMethodsAndAccessors)) { + getPrivateIdentifierEnvironment().weakSetName = createHoistedVariableForClass("instances", privateInstanceMethodsAndAccessors[0].name); + } } var result = ts.isClassDeclaration(node) ? visitClassDeclaration(node) : visitClassExpression(node); - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { endPrivateIdentifierEnvironment(); } pendingExpressions = savedPendingExpressions; return result; } function doesClassElementNeedTransform(node) { - return ts.isPropertyDeclaration(node) || (shouldTransformPrivateFields && node.name && ts.isPrivateIdentifier(node.name)); + return ts.isPropertyDeclaration(node) || (shouldTransformPrivateElements && node.name && ts.isPrivateIdentifier(node.name)); + } + function getPrivateInstanceMethodsAndAccessors(node) { + return ts.filter(node.members, ts.isNonStaticMethodOrAccessorWithPrivateName); } function visitClassDeclaration(node) { if (!ts.forEach(node.members, doesClassElementNeedTransform)) { return ts.visitEachChild(node, visitor, context); } + var staticProperties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ true); + var pendingPrivateStateAssignment; + if (shouldTransformPrivateElements && ts.some(node.members, function (m) { return ts.hasStaticModifier(m) && !!m.name && ts.isPrivateIdentifier(m.name); })) { + var temp = factory.createTempVariable(hoistVariableDeclaration, /* reservedInNestedScopes */ true); + getPrivateIdentifierEnvironment().classConstructor = factory.cloneNode(temp); + pendingPrivateStateAssignment = factory.createAssignment(temp, factory.getInternalName(node)); + } var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */); var statements = [ @@ -85986,6 +88713,9 @@ var ts; /*decorators*/ undefined, node.modifiers, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)) ]; + if (pendingPrivateStateAssignment) { + getPendingExpressions().unshift(pendingPrivateStateAssignment); + } // Write any pending expressions from elided or moved computed property names if (ts.some(pendingExpressions)) { statements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))); @@ -85995,7 +88725,6 @@ var ts; // From ES6 specification: // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. - var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); if (ts.some(staticProperties)) { addPropertyStatements(statements, staticProperties, factory.getInternalName(node)); } @@ -86013,12 +88742,25 @@ var ts; // class declaration transformation. The VariableStatement visitor will insert // these statements after the class expression variable statement. var isDecoratedClassDeclaration = ts.isClassDeclaration(ts.getOriginalNode(node)); - var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); + var staticProperties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ true); var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */); + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; + var temp; + function createClassTempVar() { + var classCheckFlags = resolver.getNodeCheckFlags(node); + var isClassWithConstructorReference = classCheckFlags & 16777216 /* ClassWithConstructorReference */; + var requiresBlockScopedVar = classCheckFlags & 524288 /* BlockScopedBindingInLoop */; + return factory.createTempVariable(requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, !!isClassWithConstructorReference); + } + if (shouldTransformPrivateElements && ts.some(node.members, function (m) { return ts.hasStaticModifier(m) && !!m.name && ts.isPrivateIdentifier(m.name); })) { + temp = createClassTempVar(); + getPrivateIdentifierEnvironment().classConstructor = factory.cloneNode(temp); + } var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)); - if (ts.some(staticProperties) || ts.some(pendingExpressions)) { + var hasTransformableStatics = ts.some(staticProperties, function (p) { return !!p.initializer || (shouldTransformPrivateElements && ts.isPrivateIdentifier(p.name)); }); + if (hasTransformableStatics || ts.some(pendingExpressions)) { if (isDecoratedClassDeclaration) { ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration."); // Write any pending expressions from elided or moved computed property names @@ -86028,12 +88770,14 @@ var ts; if (pendingStatements && ts.some(staticProperties)) { addPropertyStatements(pendingStatements, staticProperties, factory.getInternalName(node)); } + if (temp) { + return factory.inlineExpressions([factory.createAssignment(temp, classExpression), temp]); + } return classExpression; } else { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; - var temp = factory.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + temp || (temp = createClassTempVar()); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); @@ -86055,14 +88799,17 @@ var ts; return classExpression; } function transformClassMembers(node, isDerivedClass) { - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { // Declare private names. for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (ts.isPrivateIdentifierPropertyDeclaration(member)) { - addPrivateIdentifierToEnvironment(member.name); + if (ts.isPrivateIdentifierClassElementDeclaration(member)) { + addPrivateIdentifierToEnvironment(member); } } + if (ts.some(getPrivateInstanceMethodsAndAccessors(node))) { + createBrandCheckWeakSetForPrivateMethods(); + } } var members = []; var constructor = transformConstructor(node, isDerivedClass); @@ -86072,21 +88819,27 @@ var ts; ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members); } - function isPropertyDeclarationThatRequiresConstructorStatement(member) { - if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* Abstract */)) { + function createBrandCheckWeakSetForPrivateMethods() { + var weakSetName = getPrivateIdentifierEnvironment().weakSetName; + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + getPendingExpressions().push(factory.createAssignment(weakSetName, factory.createNewExpression(factory.createIdentifier("WeakSet"), + /*typeArguments*/ undefined, []))); + } + function isClassElementThatRequiresConstructorStatement(member) { + if (ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* Abstract */)) { return false; } - if (context.getCompilerOptions().useDefineForClassFields) { + if (useDefineForClassFields) { // If we are using define semantics and targeting ESNext or higher, // then we don't need to transform any class properties. return languageVersion < 99 /* ESNext */; } - return ts.isInitializedProperty(member) || shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyDeclaration(member); + return ts.isInitializedProperty(member) || shouldTransformPrivateElements && ts.isPrivateIdentifierClassElementDeclaration(member); } function transformConstructor(node, isDerivedClass) { var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration); - var properties = node.members.filter(isPropertyDeclarationThatRequiresConstructorStatement); - if (!ts.some(properties)) { + var elements = node.members.filter(isClassElementThatRequiresConstructorStatement); + if (!ts.some(elements)) { return constructor; } var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context); @@ -86099,13 +88852,14 @@ var ts; /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { - var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false); if (!useDefineForClassFields) { properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); }); } + var privateMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); + var needsConstructorBody = ts.some(properties) || ts.some(privateMethodsAndAccessors); // Only generate synthetic constructor when there are property initializers to move. - if (!constructor && !ts.some(properties)) { + if (!constructor && !needsConstructorBody) { return ts.visitFunctionBody(/*node*/ undefined, visitor, context); } resumeLexicalEnvironment(); @@ -86144,7 +88898,10 @@ var ts; indexOfFirstStatement = afterParameterProperties; } } - addPropertyStatements(statements, properties, factory.createThis()); + var receiver = factory.createThis(); + // private methods can be called in property initializers, they should execute first. + addMethodStatements(statements, privateMethodsAndAccessors, receiver); + addPropertyStatements(statements, properties, receiver); // Add existing statements, skipping the initial super call. if (constructor) { ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); @@ -86206,27 +88963,30 @@ var ts; function transformProperty(property, receiver) { var _a; // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) - var emitAssignment = !context.getCompilerOptions().useDefineForClassFields; + var emitAssignment = !useDefineForClassFields; var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression) ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name)) : property.name; - if (shouldTransformPrivateFields && ts.isPrivateIdentifier(propertyName)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifier(propertyName)) { var privateIdentifierInfo = accessPrivateIdentifier(propertyName); if (privateIdentifierInfo) { - switch (privateIdentifierInfo.placement) { - case 0 /* InstanceField */: { - return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.weakMapName); + if (privateIdentifierInfo.kind === "f" /* Field */) { + if (!privateIdentifierInfo.isStatic) { + return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.brandCheckIdentifier); } + else { + return createPrivateStaticFieldInitializer(privateIdentifierInfo.variableName, ts.visitNode(property.initializer, visitor, ts.isExpression)); + } + } + else { + return undefined; } } else { ts.Debug.fail("Undeclared private name for property declaration."); } } - if (ts.isPrivateIdentifier(propertyName) && !property.initializer) { - return undefined; - } - if (ts.isPrivateIdentifier(propertyName) && !property.initializer) { + if ((ts.isPrivateIdentifier(propertyName) || ts.hasStaticModifier(property)) && !property.initializer) { return undefined; } var propertyOriginalNode = ts.getOriginalNode(property); @@ -86258,6 +89018,21 @@ var ts; classAliases = []; } } + /** + * Generates brand-check initializer for private methods. + * + * @param statements Statement list that should be used to append new statements. + * @param methods An array of method declarations. + * @param receiver The receiver on which each method should be assigned. + */ + function addMethodStatements(statements, methods, receiver) { + if (!shouldTransformPrivateElements || !ts.some(methods)) { + return; + } + var weakSetName = getPrivateIdentifierEnvironment().weakSetName; + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + statements.push(factory.createExpressionStatement(createPrivateInstanceMethodInitializer(receiver, weakSetName))); + } /** * Hooks node substitutions. * @@ -86293,10 +89068,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_2 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_2, node); - ts.setCommentRange(clone_2, node); - return clone_2; + var clone_3 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_3, node); + ts.setCommentRange(clone_3, node); + return clone_3; } } } @@ -86316,7 +89091,12 @@ var ts; var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left); if (!alreadyTransformed && !inlinable && shouldHoist) { var generatedName = factory.getGeneratedNameForNode(name); - hoistVariableDeclaration(generatedName); + if (resolver.getNodeCheckFlags(name) & 524288 /* BlockScopedBindingInLoop */) { + addBlockScopedVariable(generatedName); + } + else { + hoistVariableDeclaration(generatedName); + } return factory.createAssignment(generatedName, expression); } return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression; @@ -86330,22 +89110,164 @@ var ts; currentPrivateIdentifierEnvironment = privateIdentifierEnvironmentStack.pop(); } function getPrivateIdentifierEnvironment() { - return currentPrivateIdentifierEnvironment || (currentPrivateIdentifierEnvironment = new ts.Map()); + if (!currentPrivateIdentifierEnvironment) { + currentPrivateIdentifierEnvironment = { + className: "", + identifiers: new ts.Map() + }; + } + return currentPrivateIdentifierEnvironment; } function getPendingExpressions() { return pendingExpressions || (pendingExpressions = []); } - function addPrivateIdentifierToEnvironment(name) { - var text = ts.getTextOfPropertyName(name); - var weakMapName = factory.createUniqueName("_" + text.substring(1), 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */); - hoistVariableDeclaration(weakMapName); - getPrivateIdentifierEnvironment().set(name.escapedText, { placement: 0 /* InstanceField */, weakMapName: weakMapName }); - getPendingExpressions().push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), - /*typeArguments*/ undefined, []))); + function addPrivateIdentifierToEnvironment(node) { + var _a; + var text = ts.getTextOfPropertyName(node.name); + var env = getPrivateIdentifierEnvironment(); + var weakSetName = env.weakSetName, classConstructor = env.classConstructor; + var assignmentExpressions = []; + var privateName = node.name.escapedText; + var previousInfo = env.identifiers.get(privateName); + var isValid = !isReservedPrivateName(node.name) && previousInfo === undefined; + if (ts.hasStaticModifier(node)) { + ts.Debug.assert(classConstructor, "weakSetName should be set in private identifier environment"); + if (ts.isPropertyDeclaration(node)) { + var variableName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: "f" /* Field */, + variableName: variableName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + else if (ts.isMethodDeclaration(node)) { + var functionName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: "m" /* Method */, + methodName: functionName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + else if (ts.isGetAccessorDeclaration(node)) { + var getterName = createHoistedVariableForPrivateName(text + "_get", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic && !previousInfo.getterName) { + previousInfo.getterName = getterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: getterName, + setterName: undefined, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + } + else if (ts.isSetAccessorDeclaration(node)) { + var setterName = createHoistedVariableForPrivateName(text + "_set", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic && !previousInfo.setterName) { + previousInfo.setterName = setterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: undefined, + setterName: setterName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + } + else { + ts.Debug.assertNever(node, "Unknown class element type."); + } + } + else if (ts.isPropertyDeclaration(node)) { + var weakMapName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: "f" /* Field */, + brandCheckIdentifier: weakMapName, + isStatic: false, + variableName: undefined, + isValid: isValid, + }); + assignmentExpressions.push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), + /*typeArguments*/ undefined, []))); + } + else if (ts.isMethodDeclaration(node)) { + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + env.identifiers.set(privateName, { + kind: "m" /* Method */, + methodName: createHoistedVariableForPrivateName(text, node), + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + else if (ts.isAccessor(node)) { + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + if (ts.isGetAccessor(node)) { + var getterName = createHoistedVariableForPrivateName(text + "_get", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && !previousInfo.isStatic && !previousInfo.getterName) { + previousInfo.getterName = getterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: getterName, + setterName: undefined, + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + } + else { + var setterName = createHoistedVariableForPrivateName(text + "_set", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && !previousInfo.isStatic && !previousInfo.setterName) { + previousInfo.setterName = setterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: undefined, + setterName: setterName, + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + } + } + else { + ts.Debug.assertNever(node, "Unknown class element type."); + } + (_a = getPendingExpressions()).push.apply(_a, assignmentExpressions); + } + function createHoistedVariableForClass(name, node) { + var className = getPrivateIdentifierEnvironment().className; + var prefix = className ? "_" + className : ""; + var identifier = factory.createUniqueName(prefix + "_" + name, 16 /* Optimistic */); + if (resolver.getNodeCheckFlags(node) & 524288 /* BlockScopedBindingInLoop */) { + addBlockScopedVariable(identifier); + } + else { + hoistVariableDeclaration(identifier); + } + return identifier; + } + function createHoistedVariableForPrivateName(privateName, node) { + return createHoistedVariableForClass(privateName.substring(1), node.name); } function accessPrivateIdentifier(name) { if (currentPrivateIdentifierEnvironment) { - var info = currentPrivateIdentifierEnvironment.get(name.escapedText); + var info = currentPrivateIdentifierEnvironment.identifiers.get(name.escapedText); if (info) { return info; } @@ -86355,7 +89277,7 @@ var ts; if (!env) { continue; } - var info = env.get(name.escapedText); + var info = env.identifiers.get(name.escapedText); if (info) { return info; } @@ -86441,10 +89363,22 @@ var ts; } } ts.transformClassFields = transformClassFields; + function createPrivateStaticFieldInitializer(variableName, initializer) { + return ts.factory.createAssignment(variableName, ts.factory.createObjectLiteralExpression([ + ts.factory.createPropertyAssignment("value", initializer || ts.factory.createVoidZero()) + ])); + } function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) { return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakMapName, "set"), /*typeArguments*/ undefined, [receiver, initializer || ts.factory.createVoidZero()]); } + function createPrivateInstanceMethodInitializer(receiver, weakSetName) { + return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakSetName, "add"), + /*typeArguments*/ undefined, [receiver]); + } + function isReservedPrivateName(node) { + return node.escapedText === "#constructor"; + } })(ts || (ts = {})); /*@internal*/ var ts; @@ -86527,38 +89461,38 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 64 /* ContainsES2017 */) === 0) { + if ((node.transformFlags & 128 /* ContainsES2017 */) === 0) { return node; } switch (node.kind) { case 129 /* AsyncKeyword */: // ES2017 async modifier should be elided for targets < ES2017 return undefined; - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return visitAwaitExpression(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105 /* SuperKeyword */) { capturedSuperProperties.add(node.name.escapedText); } return ts.visitEachChild(node, visitor, context); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: if (capturedSuperProperties && node.expression.kind === 105 /* SuperKeyword */) { hasSuperElementAccess = true; } return ts.visitEachChild(node, visitor, context); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 166 /* Constructor */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 167 /* Constructor */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node); default: return ts.visitEachChild(node, visitor, context); @@ -86567,27 +89501,27 @@ var ts; function asyncBodyVisitor(node) { if (ts.isNodeWithPossibleHoistedDeclaration(node)) { switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatementInAsyncBody(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatementInAsyncBody(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatementInAsyncBody(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatementInAsyncBody(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClauseInAsyncBody(node); - case 230 /* Block */: - case 244 /* SwitchStatement */: - case 258 /* CaseBlock */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: - case 247 /* TryStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 234 /* IfStatement */: - case 243 /* WithStatement */: - case 245 /* LabeledStatement */: + case 231 /* Block */: + case 245 /* SwitchStatement */: + case 259 /* CaseBlock */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 248 /* TryStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 235 /* IfStatement */: + case 244 /* WithStatement */: + case 246 /* LabeledStatement */: return ts.visitEachChild(node, asyncBodyVisitor, context); default: return ts.Debug.assertNever(node, "Unhandled node."); @@ -86629,18 +89563,18 @@ var ts; function visitForInStatementInAsyncBody(node) { return factory.updateForInStatement(node, isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) - : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock)); + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context)); } function visitForOfStatementInAsyncBody(node) { return factory.updateForOfStatement(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) - : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock)); + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context)); } function visitForStatementInAsyncBody(node) { var initializer = node.initializer; // TODO: GH#18217 return factory.updateForStatement(node, isVariableDeclarationListWithCollidingName(initializer) ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false) - : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock)); + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context)); } /** * Visits an AwaitExpression node. @@ -86792,7 +89726,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 209 /* ArrowFunction */; + var isArrowFunction = node.kind === 210 /* ArrowFunction */; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current @@ -86883,17 +89817,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(203 /* CallExpression */); - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(202 /* ElementAccessExpression */); + context.enableSubstitution(204 /* CallExpression */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(203 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(252 /* ClassDeclaration */); - context.enableEmitNotification(165 /* MethodDeclaration */); - context.enableEmitNotification(167 /* GetAccessor */); - context.enableEmitNotification(168 /* SetAccessor */); - context.enableEmitNotification(166 /* Constructor */); + context.enableEmitNotification(253 /* ClassDeclaration */); + context.enableEmitNotification(166 /* MethodDeclaration */); + context.enableEmitNotification(168 /* GetAccessor */); + context.enableEmitNotification(169 /* SetAccessor */); + context.enableEmitNotification(167 /* Constructor */); // We need to be notified when entering the generated accessor arrow functions. - context.enableEmitNotification(232 /* VariableStatement */); + context.enableEmitNotification(233 /* VariableStatement */); } } /** @@ -86941,11 +89875,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return substituteCallExpression(node); } return node; @@ -86977,11 +89911,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 252 /* ClassDeclaration */ - || kind === 166 /* Constructor */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 253 /* ClassDeclaration */ + || kind === 167 /* Constructor */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { @@ -87160,74 +90094,74 @@ var ts; * expression of an `ExpressionStatement`). */ function visitorWorker(node, expressionResultIsUnused) { - if ((node.transformFlags & 32 /* ContainsES2018 */) === 0) { + if ((node.transformFlags & 64 /* ContainsES2018 */) === 0) { return node; } switch (node.kind) { - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return visitAwaitExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitYieldExpression(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitReturnStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node, expressionResultIsUnused); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitCommaListExpression(node, expressionResultIsUnused); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 238 /* ForInStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 239 /* ForInStatement */: return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return visitVoidExpression(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */); - case 160 /* Parameter */: + case 161 /* Parameter */: return visitParameter(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitExpressionStatement(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, expressionResultIsUnused); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105 /* SuperKeyword */) { capturedSuperProperties.add(node.name.escapedText); } return ts.visitEachChild(node, visitor, context); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: if (capturedSuperProperties && node.expression.kind === 105 /* SuperKeyword */) { hasSuperElementAccess = true; } return ts.visitEachChild(node, visitor, context); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); default: return ts.visitEachChild(node, visitor, context); @@ -87263,7 +90197,7 @@ var ts; function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 239 /* ForOfStatement */ && statement.awaitModifier) { + if (statement.kind === 240 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } return factory.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, factory.liftToBlock), node); @@ -87275,7 +90209,7 @@ var ts; var objects = []; for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { var e = elements_4[_i]; - if (e.kind === 290 /* SpreadAssignment */) { + if (e.kind === 291 /* SpreadAssignment */) { if (chunkObject) { objects.push(factory.createObjectLiteralExpression(chunkObject)); chunkObject = undefined; @@ -87284,7 +90218,7 @@ var ts; objects.push(ts.visitNode(target, visitor, ts.isExpression)); } else { - chunkObject = ts.append(chunkObject, e.kind === 288 /* PropertyAssignment */ + chunkObject = ts.append(chunkObject, e.kind === 289 /* PropertyAssignment */ ? factory.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } @@ -87295,7 +90229,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign(__assign({a}, o), {b}); @@ -87318,7 +90252,7 @@ var ts; // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we // end up with `{ a: 1, b: 2, c: 3 }` var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 200 /* ObjectLiteralExpression */) { + if (objects.length && objects[0].kind !== 201 /* ObjectLiteralExpression */) { objects.unshift(factory.createObjectLiteralExpression()); } var expression = objects[0]; @@ -87368,7 +90302,7 @@ var ts; * expression of an `ExpressionStatement`). */ function visitBinaryExpression(node, expressionResultIsUnused) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !expressionResultIsUnused); } if (node.operatorToken.kind === 27 /* CommaToken */) { @@ -87399,7 +90333,7 @@ var ts; function visitCatchClause(node) { if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name) && - node.variableDeclaration.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + node.variableDeclaration.name.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { var name = factory.getGeneratedNameForNode(node.variableDeclaration.name); var updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name); var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */); @@ -87440,14 +90374,14 @@ var ts; } function visitVariableDeclarationWorker(node, exportedVariableStatement) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */, /*rval*/ undefined, exportedVariableStatement); } return ts.visitEachChild(node, visitor, context); } function visitForStatement(node) { - return factory.updateForStatement(node, ts.visitNode(node.initializer, visitorWithUnusedExpressionResult, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitorWithUnusedExpressionResult, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement)); + return factory.updateForStatement(node, ts.visitNode(node.initializer, visitorWithUnusedExpressionResult, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitorWithUnusedExpressionResult, ts.isExpression), ts.visitIterationBody(node.statement, visitor, context)); } function visitVoidExpression(node) { return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context); @@ -87459,7 +90393,7 @@ var ts; */ function visitForOfStatement(node, outermostLabeledStatement) { var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); - if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (node.initializer.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } var result = node.awaitModifier ? @@ -87497,7 +90431,7 @@ var ts; var bodyLocation; var statementsLocation; var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; - var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + var statement = ts.visitIterationBody(node.statement, visitor, context); if (ts.isBlock(statement)) { ts.addRange(statements, statement.statements); bodyLocation = statement; @@ -87559,7 +90493,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return factory.updateParameterDeclaration(node, @@ -87711,7 +90645,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 & 16384 /* ContainsObjectRestOrSpread */) { + if (parameter.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { var temp = factory.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -87731,17 +90665,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(203 /* CallExpression */); - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(202 /* ElementAccessExpression */); + context.enableSubstitution(204 /* CallExpression */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(203 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(252 /* ClassDeclaration */); - context.enableEmitNotification(165 /* MethodDeclaration */); - context.enableEmitNotification(167 /* GetAccessor */); - context.enableEmitNotification(168 /* SetAccessor */); - context.enableEmitNotification(166 /* Constructor */); + context.enableEmitNotification(253 /* ClassDeclaration */); + context.enableEmitNotification(166 /* MethodDeclaration */); + context.enableEmitNotification(168 /* GetAccessor */); + context.enableEmitNotification(169 /* SetAccessor */); + context.enableEmitNotification(167 /* Constructor */); // We need to be notified when entering the generated accessor arrow functions. - context.enableEmitNotification(232 /* VariableStatement */); + context.enableEmitNotification(233 /* VariableStatement */); } } /** @@ -87789,11 +90723,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return substituteCallExpression(node); } return node; @@ -87825,11 +90759,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 252 /* ClassDeclaration */ - || kind === 166 /* Constructor */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 253 /* ClassDeclaration */ + || kind === 167 /* Constructor */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { @@ -87857,11 +90791,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 16 /* ContainsES2019 */) === 0) { + if ((node.transformFlags & 32 /* ContainsES2019 */) === 0) { return node; } switch (node.kind) { - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); @@ -87889,25 +90823,29 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 8 /* ContainsES2020 */) === 0) { + if ((node.transformFlags & 16 /* ContainsES2020 */) === 0) { return node; } switch (node.kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: - case 203 /* CallExpression */: - if (node.flags & 32 /* OptionalChain */) { + case 204 /* CallExpression */: { + var updated = visitNonOptionalCallExpression(node, /*captureThisArg*/ false); + ts.Debug.assertNotNode(updated, ts.isSyntheticReference); + return updated; + } + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + if (ts.isOptionalChain(node)) { var updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false); ts.Debug.assertNotNode(updated, ts.isSyntheticReference); return updated; } return ts.visitEachChild(node, visitor, context); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (node.operatorToken.kind === 60 /* QuestionQuestionToken */) { return transformNullishCoalescingExpression(node); } return ts.visitEachChild(node, visitor, context); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return visitDeleteExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -87949,7 +90887,7 @@ var ts; thisArg = expression; } } - expression = node.kind === 201 /* PropertyAccessExpression */ + expression = node.kind === 202 /* PropertyAccessExpression */ ? factory.updatePropertyAccessExpression(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)) : factory.updateElementAccessExpression(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); return thisArg ? factory.createSyntheticReferenceExpression(expression, thisArg) : expression; @@ -87959,14 +90897,23 @@ var ts; // If `node` is an optional chain, then it is the outermost chain of an optional expression. return visitOptionalExpression(node, captureThisArg, /*isDelete*/ false); } + if (ts.isParenthesizedExpression(node.expression) && ts.isOptionalChain(ts.skipParentheses(node.expression))) { + // capture thisArg for calls of parenthesized optional chains like `(foo?.bar)()` + var expression = visitNonOptionalParenthesizedExpression(node.expression, /*captureThisArg*/ true, /*isDelete*/ false); + var args = ts.visitNodes(node.arguments, visitor, ts.isExpression); + if (ts.isSyntheticReference(expression)) { + return ts.setTextRange(factory.createFunctionCallCall(expression.expression, expression.thisArg, args), node); + } + return factory.updateCallExpression(node, expression, /*typeArguments*/ undefined, args); + } return ts.visitEachChild(node, visitor, context); } function visitNonOptionalExpression(node, captureThisArg, isDelete) { switch (node.kind) { - case 207 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete); - case 203 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg); + case 208 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete); + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete); + case 204 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg); default: return ts.visitNode(node, visitor, ts.isExpression); } } @@ -87985,8 +90932,8 @@ var ts; for (var i = 0; i < chain.length; i++) { var segment = chain[i]; switch (segment.kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: if (i === chain.length - 1 && captureThisArg) { if (!ts.isSimpleCopiableExpression(rightExpression)) { thisArg = factory.createTempVariable(hoistVariableDeclaration); @@ -87996,11 +90943,11 @@ var ts; thisArg = rightExpression; } } - rightExpression = segment.kind === 201 /* PropertyAccessExpression */ + rightExpression = segment.kind === 202 /* PropertyAccessExpression */ ? factory.createPropertyAccessExpression(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)) : factory.createElementAccessExpression(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (i === 0 && leftThisArg) { rightExpression = factory.createFunctionCallCall(rightExpression, leftThisArg.kind === 105 /* SuperKeyword */ ? factory.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); } @@ -88043,7 +90990,7 @@ var ts; /*@internal*/ var ts; (function (ts) { - function transformESNext(context) { + function transformES2021(context) { var hoistVariableDeclaration = context.hoistVariableDeclaration, factory = context.factory; return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { @@ -88053,11 +91000,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 4 /* ContainsESNext */) === 0) { + if ((node.transformFlags & 8 /* ContainsES2021 */) === 0) { return node; } switch (node.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var binaryExpression = node; if (ts.isLogicalOrCoalescingAssignmentExpression(binaryExpression)) { return transformLogicalAssignment(binaryExpression); @@ -88093,6 +91040,29 @@ var ts; return factory.createBinaryExpression(left, nonAssignmentOperator, factory.createParenthesizedExpression(factory.createAssignment(assignmentTarget, right))); } } + ts.transformES2021 = transformES2021; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformESNext(context) { + return ts.chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if ((node.transformFlags & 4 /* ContainsESNext */) === 0) { + return node; + } + switch (node.kind) { + default: + return ts.visitEachChild(node, visitor, context); + } + } + } ts.transformESNext = transformESNext; })(ts || (ts = {})); /*@internal*/ @@ -88203,13 +91173,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 273 /* JsxElement */: + case 274 /* JsxElement */: return visitJsxElement(node, /*isChild*/ false); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ false); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -88219,13 +91189,13 @@ var ts; switch (node.kind) { case 11 /* JsxText */: return visitJsxText(node); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return visitJsxExpression(node); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return visitJsxElement(node, /*isChild*/ true); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ true); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ true); default: return ts.Debug.failBadSyntaxKind(node); @@ -88265,9 +91235,9 @@ var ts; function convertJsxChildrenToChildrenPropObject(children) { var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); if (ts.length(nonWhitespaceChildren) === 1) { - var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]); - return result_13 && factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", result_13) + var result_14 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result_14 && factory.createObjectLiteralExpression([ + factory.createPropertyAssignment("children", result_14) ]); } var result = ts.mapDefined(children, transformJsxChildToExpression); @@ -88343,21 +91313,29 @@ var ts; // When there are no attributes, React wants "null" } else { - // Map spans of JsxAttribute nodes into object literals and spans - // of JsxSpreadAttribute nodes into expressions. - var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread - ? ts.map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); - if (ts.isJsxSpreadAttribute(attrs[0])) { - // We must always emit at least one object literal before a spread - // argument.factory.createObjectLiteral - segments.unshift(factory.createObjectLiteralExpression()); + var target = compilerOptions.target; + if (target && target >= 5 /* ES2018 */) { + objectProperties = factory.createObjectLiteralExpression(ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { + return isSpread ? ts.map(attrs, transformJsxSpreadAttributeToSpreadAssignment) : ts.map(attrs, transformJsxAttributeToObjectLiteralElement); + }))); } - // Either emit one big object literal (no spread attribs), or - // a call to the __assign helper. - objectProperties = ts.singleOrUndefined(segments); - if (!objectProperties) { - objectProperties = emitHelpers().createAssignHelper(segments); + else { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. + var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument.factory.createObjectLiteral + segments.unshift(factory.createObjectLiteralExpression()); + } + // Either emit one big object literal (no spread attribs), or + // a call to the __assign helper. + objectProperties = ts.singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = emitHelpers().createAssignHelper(segments); + } } } var callee = currentFileState.importSpecifier === undefined @@ -88389,6 +91367,9 @@ var ts; } return element; } + function transformJsxSpreadAttributeToSpreadAssignment(node) { + return factory.createSpreadAssignment(ts.visitNode(node.expression, visitor, ts.isExpression)); + } function transformJsxSpreadAttributeToExpression(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } @@ -88408,7 +91389,7 @@ var ts; var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote); return ts.setTextRange(literal, node); } - else if (node.kind === 283 /* JsxExpression */) { + else if (node.kind === 284 /* JsxExpression */) { if (node.expression === undefined) { return factory.createTrue(); } @@ -88502,7 +91483,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 273 /* JsxElement */) { + if (node.kind === 274 /* JsxElement */) { return getTagName(node.openingElement); } else { @@ -88804,11 +91785,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 128 /* ContainsES2016 */) === 0) { + if ((node.transformFlags & 256 /* ContainsES2016 */) === 0) { return node; } switch (node.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -89021,11 +92002,11 @@ var ts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0 - && node.kind === 242 /* ReturnStatement */ + && node.kind === 243 /* ReturnStatement */ && !node.expression; } function isOrMayContainReturnCompletion(node) { - return node.transformFlags & 1048576 /* ContainsHoistedDeclarationOrCompletion */ + return node.transformFlags & 2097152 /* ContainsHoistedDeclarationOrCompletion */ && (ts.isReturnStatement(node) || ts.isIfStatement(node) || ts.isWithStatement(node) @@ -89040,7 +92021,7 @@ var ts; || ts.isBlock(node)); } function shouldVisitNode(node) { - return (node.transformFlags & 256 /* ContainsES2015 */) !== 0 + return (node.transformFlags & 512 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && isOrMayContainReturnCompletion(node)) || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) @@ -89062,65 +92043,65 @@ var ts; switch (node.kind) { case 123 /* StaticKeyword */: return undefined; // elide static keyword - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return visitClassDeclaration(node); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return visitClassExpression(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return visitParameter(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return visitArrowFunction(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return visitFunctionExpression(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitVariableDeclaration(node); case 78 /* Identifier */: return visitIdentifier(node); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return visitVariableDeclarationList(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitSwitchStatement(node); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return visitCaseBlock(node); - case 230 /* Block */: + case 231 /* Block */: return visitBlock(node, /*isFunctionBody*/ false); - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: return visitBreakOrContinueStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node, /*outermostLabeledStatement*/ undefined); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitExpressionStatement(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return visitShorthandPropertyAssignment(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return visitNewExpression(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, expressionResultIsUnused); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node, expressionResultIsUnused); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitCommaListExpression(node, expressionResultIsUnused); case 14 /* NoSubstitutionTemplateLiteral */: case 15 /* TemplateHead */: @@ -89131,30 +92112,30 @@ var ts; return visitStringLiteral(node); case 8 /* NumericLiteral */: return visitNumericLiteral(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return visitTemplateExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitYieldExpression(node); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return visitSpreadElement(node); case 105 /* SuperKeyword */: return visitSuperKeyword(/*isExpressionOfCall*/ false); case 107 /* ThisKeyword */: return visitThisKeyword(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return visitMetaProperty(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return visitAccessorDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitReturnStatement(node); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return visitVoidExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -89244,14 +92225,14 @@ var ts; // it is possible if either // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement - var jump = node.kind === 241 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var jump = node.kind === 242 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; var label = node.label; if (!label) { - if (node.kind === 241 /* BreakStatement */) { + if (node.kind === 242 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; } @@ -89262,7 +92243,7 @@ var ts; } } else { - if (node.kind === 241 /* BreakStatement */) { + if (node.kind === 242 /* BreakStatement */) { labelMarker = "break-" + label.escapedText; setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); } @@ -89574,7 +92555,7 @@ var ts; factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); if (isDerivedClass) { - if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 4096 /* ContainsLexicalThis */)) { + if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 8192 /* ContainsLexicalThis */)) { // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the // following representation: // @@ -89660,11 +92641,11 @@ var ts; */ function isSufficientlyCoveredByReturnStatements(statement) { // A return statement is considered covered. - if (statement.kind === 242 /* ReturnStatement */) { + if (statement.kind === 243 /* ReturnStatement */) { return true; } // An if-statement with two covered branches is covered. - else if (statement.kind === 234 /* IfStatement */) { + else if (statement.kind === 235 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && @@ -89672,7 +92653,7 @@ var ts; } } // A block is covered if it has a last statement which is covered. - else if (statement.kind === 230 /* Block */) { + else if (statement.kind === 231 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -89874,7 +92855,7 @@ var ts; * @param node A node. */ function insertCaptureThisForNodeIfNeeded(statements, node) { - if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 209 /* ArrowFunction */) { + if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 210 /* ArrowFunction */) { insertCaptureThisForNode(statements, node, factory.createThis()); return true; } @@ -89896,22 +92877,22 @@ var ts; if (hierarchyFacts & 16384 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return statements; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // Methods and accessors cannot be constructors, so 'new.target' will // always return 'undefined'. newTarget = factory.createVoidZero(); break; - case 166 /* Constructor */: + case 167 /* Constructor */: // Class constructors can only be called with `new`, so `this.constructor` // should be relatively safe to use. newTarget = factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), "constructor"); break; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: // Functions can be called or constructed, and may have a `this` due to // being a member or when calling an imported function via `other_1.f()`. newTarget = factory.createConditionalExpression(factory.createLogicalAnd(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), factory.createBinaryExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), 101 /* InstanceOfKeyword */, factory.getLocalName(node))), @@ -89946,20 +92927,20 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 166 /* Constructor */: + case 167 /* Constructor */: // Constructors are handled in visitClassExpression/visitClassDeclaration break; default: @@ -89988,7 +92969,7 @@ var ts; var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName); var e; - if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) { + if (!ts.isPrivateIdentifier(propertyName) && ts.getUseDefineForClassFields(context.getCompilerOptions())) { var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName; @@ -90080,7 +93061,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 4096 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { hierarchyFacts |= 32768 /* CapturedLexicalThis */; } var savedConvertedLoopState = convertedLoopState; @@ -90162,7 +93143,7 @@ var ts; : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */)) { + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 252 /* FunctionDeclaration */ || node.kind === 209 /* FunctionExpression */)) { name = factory.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */); @@ -90208,7 +93189,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 209 /* ArrowFunction */); + ts.Debug.assert(node.kind === 210 /* ArrowFunction */); // To align with the old emitter, we use a synthetic end position on the location // for the statement list we synthesize when we down-level an arrow function with // an expression function body. This prevents both comments and source maps from @@ -90369,7 +93350,7 @@ var ts; * @param node A VariableDeclarationList node. */ function visitVariableDeclarationList(node) { - if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 131072 /* ContainsBindingPattern */) { + if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 262144 /* ContainsBindingPattern */) { if (node.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } @@ -90382,7 +93363,7 @@ var ts; ts.setCommentRange(declarationList, node); // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. - if (node.transformFlags & 131072 /* ContainsBindingPattern */ + if (node.transformFlags & 262144 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -90394,8 +93375,8 @@ var ts; // 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]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var node = declarations_9[_i]; pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); end = Math.max(end, node.end); } @@ -90515,14 +93496,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return visitDoOrWhileStatement(node, outermostLabeledStatement); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node, outermostLabeledStatement); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node, outermostLabeledStatement); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -90706,9 +93687,9 @@ var ts; var numInitialProperties = -1, hasComputed = false; for (var i = 0; i < properties.length; i++) { var property = properties[i]; - if ((property.transformFlags & 262144 /* ContainsYield */ && + if ((property.transformFlags & 524288 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) - || (hasComputed = ts.Debug.checkDefined(property.name).kind === 158 /* ComputedPropertyName */)) { + || (hasComputed = ts.Debug.checkDefined(property.name).kind === 159 /* ComputedPropertyName */)) { numInitialProperties = i; break; } @@ -90811,24 +93792,24 @@ var ts; loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts); } else { - var clone_3 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); - loop = factory.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_4 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); + loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); } } else { - var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + loop = factory.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel); } statements.push(loop); return statements; } function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { switch (node.kind) { - case 237 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); - case 238 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); - case 239 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); - case 235 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); - case 236 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + case 238 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 239 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 240 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 236 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 237 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); } } @@ -90853,11 +93834,11 @@ var ts; function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: var initializer = node.initializer; - if (initializer && initializer.kind === 250 /* VariableDeclarationList */) { + if (initializer && initializer.kind === 251 /* VariableDeclarationList */) { loopInitializer = initializer; } break; @@ -90977,7 +93958,7 @@ var ts; */ function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = factory.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 262144 /* ContainsYield */) !== 0; + var containsYield = (node.initializer.transformFlags & 524288 /* ContainsYield */) !== 0; var emitFlags = 0 /* None */; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -91092,7 +94073,7 @@ var ts; var loopBody = factory.createBlock(statements, /*multiLine*/ true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 262144 /* ContainsYield */) !== 0; + var containsYield = (node.statement.transformFlags & 524288 /* ContainsYield */) !== 0; var emitFlags = 524288 /* ReuseTempVariableScope */; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -91265,20 +94246,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -91385,7 +94366,7 @@ var ts; var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (node.kind === 167 /* GetAccessor */) { + if (node.kind === 168 /* GetAccessor */) { updated = factory.updateGetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { @@ -91565,7 +94546,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 & 8192 /* ContainsRestOrSpread */ || + if (node.transformFlags & 16384 /* ContainsRestOrSpread */ || node.expression.kind === 105 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -91573,7 +94554,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 8192 /* ContainsRestOrSpread */) { + if (node.transformFlags & 16384 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -91891,13 +94872,13 @@ var ts; if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { enabledSubstitutions |= 1 /* CapturedThis */; context.enableSubstitution(107 /* ThisKeyword */); - context.enableEmitNotification(166 /* Constructor */); - context.enableEmitNotification(165 /* MethodDeclaration */); - context.enableEmitNotification(167 /* GetAccessor */); - context.enableEmitNotification(168 /* SetAccessor */); - context.enableEmitNotification(209 /* ArrowFunction */); - context.enableEmitNotification(208 /* FunctionExpression */); - context.enableEmitNotification(251 /* FunctionDeclaration */); + context.enableEmitNotification(167 /* Constructor */); + context.enableEmitNotification(166 /* MethodDeclaration */); + context.enableEmitNotification(168 /* GetAccessor */); + context.enableEmitNotification(169 /* SetAccessor */); + context.enableEmitNotification(210 /* ArrowFunction */); + context.enableEmitNotification(209 /* FunctionExpression */); + context.enableEmitNotification(252 /* FunctionDeclaration */); } } /** @@ -91938,10 +94919,10 @@ var ts; */ function isNameOfDeclarationWithCollidingName(node) { switch (node.parent.kind) { - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 249 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 250 /* VariableDeclaration */: return node.parent.name === node && resolver.isDeclarationWithCollidingName(node.parent); } @@ -92023,11 +95004,11 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 233 /* ExpressionStatement */) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 234 /* ExpressionStatement */) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 203 /* CallExpression */) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 204 /* CallExpression */) { return false; } var callTarget = statementExpression.expression; @@ -92035,7 +95016,7 @@ var ts; return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 220 /* SpreadElement */) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 221 /* SpreadElement */) { return false; } var expression = callArgument.expression; @@ -92061,15 +95042,15 @@ var ts; if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(275 /* JsxOpeningElement */); - context.enableEmitNotification(276 /* JsxClosingElement */); - context.enableEmitNotification(274 /* JsxSelfClosingElement */); + context.enableEmitNotification(276 /* JsxOpeningElement */); + context.enableEmitNotification(277 /* JsxClosingElement */); + context.enableEmitNotification(275 /* JsxSelfClosingElement */); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(288 /* PropertyAssignment */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(289 /* PropertyAssignment */); return ts.chainBundle(context, transformSourceFile); /** * Transforms an ES5 source file to ES3. @@ -92088,9 +95069,9 @@ var ts; */ function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 275 /* JsxOpeningElement */: - case 276 /* JsxClosingElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 277 /* JsxClosingElement */: + case 275 /* JsxSelfClosingElement */: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -92388,7 +95369,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 1024 /* ContainsGenerator */) === 0) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -92411,7 +95392,7 @@ var ts; else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) { return visitGenerator(node); } - else if (transformFlags & 512 /* ContainsGenerator */) { + else if (transformFlags & 1024 /* ContainsGenerator */) { return ts.visitEachChild(node, visitor, context); } else { @@ -92425,13 +95406,13 @@ var ts; */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 235 /* DoStatement */: + case 236 /* DoStatement */: return visitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return visitWhileStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -92444,30 +95425,30 @@ var ts; */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return visitFunctionExpression(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return visitAccessorDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: return visitBreakStatement(node); - case 240 /* ContinueStatement */: + case 241 /* ContinueStatement */: return visitContinueStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 262144 /* ContainsYield */) { + if (node.transformFlags & 524288 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 1048576 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (1024 /* ContainsGenerator */ | 2097152 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -92482,23 +95463,23 @@ var ts; */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitCommaListExpression(node); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return visitConditionalExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitYieldExpression(node); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return visitElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -92511,9 +95492,9 @@ var ts; */ function visitGenerator(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return visitFunctionExpression(node); default: return ts.Debug.failBadSyntaxKind(node); @@ -92672,7 +95653,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 262144 /* ContainsYield */) { + if (node.transformFlags & 524288 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -92721,7 +95702,7 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: // [source] // a.b = yield; // @@ -92733,7 +95714,7 @@ var ts; // _a.b = %sent%; target = factory.updatePropertyAccessExpression(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: // [source] // a[b] = yield; // @@ -93127,35 +96108,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 230 /* Block */: + case 231 /* Block */: return transformAndEmitBlock(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return transformAndEmitIfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return transformAndEmitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return transformAndEmitWhileStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return transformAndEmitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return transformAndEmitForInStatement(node); - case 240 /* ContinueStatement */: + case 241 /* ContinueStatement */: return transformAndEmitContinueStatement(node); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: return transformAndEmitBreakStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return transformAndEmitReturnStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return transformAndEmitWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return transformAndEmitThrowStatement(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -93375,7 +96356,7 @@ var ts; var variables = ts.getInitializedVariables(initializer); node = factory.updateForStatement(node, variables.length > 0 ? factory.inlineExpressions(ts.map(variables, transformInitializedVariable)) - : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitIterationBody(node.statement, visitor, context)); } else { node = ts.visitEachChild(node, visitor, context); @@ -93585,7 +96566,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 285 /* DefaultClause */ && defaultClauseIndex === -1) { + if (clause.kind === 286 /* DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -93598,7 +96579,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 284 /* CaseClause */) { + if (clause.kind === 285 /* CaseClause */) { if (containsYield(clause.expression) && pendingClauses.length > 0) { break; } @@ -93730,7 +96711,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 262144 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 524288 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -93763,10 +96744,10 @@ var ts; var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { // TODO(rbuckton): Does this need to be parented? - var clone_5 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); - ts.setSourceMapRange(clone_5, node); - ts.setCommentRange(clone_5, node); - return clone_5; + var clone_6 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -94759,11 +97740,11 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(216 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(214 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(215 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(289 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. - context.enableEmitNotification(297 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(217 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(215 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(216 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(298 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var currentSourceFile; // The current file. @@ -94779,7 +97760,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 2097152 /* ContainsDynamicImport */ || + node.transformFlags & 4194304 /* ContainsDynamicImport */ || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && ts.outFile(compilerOptions)))) { return node; } @@ -95091,23 +98072,23 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return visitClassDeclaration(node); - case 338 /* MergeDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 339 /* EndOfDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); @@ -95116,7 +98097,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 & 2097152 /* ContainsDynamicImport */) && !(node.transformFlags & 1024 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 4194304 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -95134,24 +98115,24 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; switch (elem.kind) { - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: if (destructuringNeedsFlattening(elem.initializer)) { return true; } break; - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: if (destructuringNeedsFlattening(elem.name)) { return true; } break; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: if (destructuringNeedsFlattening(elem.expression)) { return true; } break; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return false; default: ts.Debug.assertNever(elem, "Unhandled object member kind"); } @@ -95186,7 +98167,7 @@ var ts; var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); // Only use the external module name if it differs from the first argument. This allows us to preserve the quote style of the argument on output. var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument; - var containsLexicalThis = !!(node.transformFlags & 4096 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -95679,7 +98660,7 @@ var ts; // // To balance the declaration, add the exports of the elided variable // statement. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 232 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 233 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -95734,10 +98715,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true); @@ -95950,7 +98931,7 @@ var ts; * @param emit A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -96014,10 +98995,10 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return substituteExpressionIdentifier(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return substituteBinaryExpression(node); - case 215 /* PostfixUnaryExpression */: - case 214 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -96037,9 +99018,9 @@ var ts; } return node; } - if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) { + else if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 297 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 298 /* SourceFile */) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), /*location*/ node); } @@ -96114,8 +99095,8 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 215 /* PostfixUnaryExpression */ - ? ts.setTextRange(factory.createBinaryExpression(node.operand, factory.createToken(node.operator === 45 /* PlusPlusToken */ ? 63 /* PlusEqualsToken */ : 64 /* MinusEqualsToken */), factory.createNumericLiteral(1)), + var expression = node.kind === 216 /* PostfixUnaryExpression */ + ? ts.setTextRange(factory.createPrefixUnaryExpression(node.operator, node.operand), /*location*/ node) : node; for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { @@ -96124,6 +99105,12 @@ var ts; noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression); } + if (node.kind === 216 /* PostfixUnaryExpression */) { + noSubstitution[ts.getNodeId(expression)] = true; + expression = node.operator === 45 /* PlusPlusToken */ + ? factory.createSubtract(expression, factory.createNumericLiteral(1)) + : factory.createAdd(expression, factory.createNumericLiteral(1)); + } return expression; } } @@ -96166,12 +99153,12 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers for imported symbols. - context.enableSubstitution(289 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols - context.enableSubstitution(216 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(214 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(215 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(226 /* MetaProperty */); // Substitutes 'import.meta' - context.enableEmitNotification(297 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(217 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(215 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(216 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(227 /* MetaProperty */); // Substitutes 'import.meta' + context.enableEmitNotification(298 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var exportFunctionsMap = []; // The export function associated with a source file. @@ -96191,7 +99178,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 2097152 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 4194304 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -96360,7 +99347,7 @@ var ts; // - Temporary variables will appear at the top rather than at the bottom of the file ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 - var modifiers = node.transformFlags & 524288 /* ContainsAwait */ ? + var modifiers = node.transformFlags & 1048576 /* ContainsAwait */ ? factory.createModifiersFromModifierFlags(256 /* Async */) : undefined; var moduleObject = factory.createObjectLiteralExpression([ @@ -96395,7 +99382,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 267 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 268 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -96485,19 +99472,19 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(factory, entry, currentSourceFile); // TODO: GH#18217 switch (entry.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // falls through - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== undefined); // save import into the local statements.push(factory.createExpressionStatement(factory.createAssignment(importVariableName, parameterName))); break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { if (ts.isNamedExports(entry.exportClause)) { @@ -96556,13 +99543,13 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -96742,7 +99729,7 @@ var ts; function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 - && (enclosingBlockScopedContainer.kind === 297 /* SourceFile */ + && (enclosingBlockScopedContainer.kind === 298 /* SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); } /** @@ -96806,7 +99793,7 @@ var ts; // // To balance the declaration, we defer the exports of the elided variable // statement until we visit this declaration's `EndOfDeclarationMarker`. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 232 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 233 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasSyntacticModifier(node.original, 1 /* Export */); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -96868,10 +99855,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -97051,43 +100038,43 @@ var ts; */ function nestedElementVisitor(node) { switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return visitClassDeclaration(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return visitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return visitWhileStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return visitWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitSwitchStatement(node); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return visitCaseBlock(node); - case 284 /* CaseClause */: + case 285 /* CaseClause */: return visitCaseClause(node); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: return visitDefaultClause(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return visitTryStatement(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); - case 230 /* Block */: + case 231 /* Block */: return visitBlock(node); - case 338 /* MergeDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 339 /* EndOfDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -97101,7 +100088,7 @@ var ts; function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory.updateForStatement(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + node = factory.updateForStatement(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -97113,7 +100100,7 @@ var ts; function visitForInStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory.updateForInStatement(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); + node = factory.updateForInStatement(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -97125,7 +100112,7 @@ var ts; function visitForOfStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory.updateForOfStatement(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); + node = factory.updateForOfStatement(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -97166,7 +100153,7 @@ var ts; * @param node The node to visit. */ function visitDoStatement(node) { - return factory.updateDoStatement(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); + return factory.updateDoStatement(node, ts.visitIterationBody(node.statement, nestedElementVisitor, context), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); } /** * Visits the body of a WhileStatement to hoist declarations. @@ -97174,7 +100161,7 @@ var ts; * @param node The node to visit. */ function visitWhileStatement(node) { - return factory.updateWhileStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); + return factory.updateWhileStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); } /** * Visits the body of a LabeledStatement to hoist declarations. @@ -97275,7 +100262,7 @@ var ts; else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 1024 /* ContainsDestructuringAssignment */) || (node.transformFlags & 2097152 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 4194304 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -97313,7 +100300,7 @@ var ts; return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } /** - * Determines whether the target of a destructuring assigment refers to an exported symbol. + * Determines whether the target of a destructuring assignment refers to an exported symbol. * * @param node The destructuring target. */ @@ -97338,7 +100325,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 297 /* SourceFile */; + return container !== undefined && container.kind === 298 /* SourceFile */; } else { return false; @@ -97371,7 +100358,7 @@ var ts; * @param emitCallback A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -97421,7 +100408,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -97458,12 +100445,12 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return substituteExpressionIdentifier(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return substituteBinaryExpression(node); - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return substituteUnaryExpression(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return substituteMetaProperty(node); } return node; @@ -97557,14 +100544,14 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 215 /* PostfixUnaryExpression */ + var expression = node.kind === 216 /* PostfixUnaryExpression */ ? ts.setTextRange(factory.createPrefixUnaryExpression(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 215 /* PostfixUnaryExpression */) { + if (node.kind === 216 /* PostfixUnaryExpression */) { expression = node.operator === 45 /* PlusPlusToken */ ? factory.createSubtract(preventSubstitution(expression), factory.createNumericLiteral(1)) : factory.createAdd(preventSubstitution(expression), factory.createNumericLiteral(1)); @@ -97592,7 +100579,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); - if (exportContainer && exportContainer.kind === 297 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 298 /* SourceFile */) { exportedNames = ts.append(exportedNames, factory.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -97632,7 +100619,7 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(297 /* SourceFile */); + context.enableEmitNotification(298 /* SourceFile */); context.enableSubstitution(78 /* Identifier */); var helperNameSubstitutions; return ts.chainBundle(context, transformSourceFile); @@ -97664,12 +100651,12 @@ var ts; } function visitor(node) { switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // Elide `import=` as it is not legal with --module ES6 return undefined; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: var exportDecl = node; return visitExportDeclaration(exportDecl); } @@ -97774,7 +100761,8 @@ var ts; ts.isTypeAliasDeclaration(node) || ts.isConstructorDeclaration(node) || ts.isIndexSignatureDeclaration(node) || - ts.isPropertyAccessExpression(node); + ts.isPropertyAccessExpression(node) || + ts.isJSDocTypeAlias(node); } ts.canProduceDiagnostics = canProduceDiagnostics; function createGetSymbolAccessibilityDiagnosticForNodeName(node) { @@ -97803,7 +100791,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.kind === 253 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -97832,7 +100820,7 @@ var ts; ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.kind === 253 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -97872,14 +100860,14 @@ var ts; else if (ts.isImportEqualsDeclaration(node)) { return getImportEntityNameVisibilityError; } - else if (ts.isTypeAliasDeclaration(node)) { + else if (ts.isTypeAliasDeclaration(node) || ts.isJSDocTypeAlias(node)) { return getTypeAliasDeclarationVisibilityError; } else { return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) { + if (node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -97888,8 +100876,8 @@ var ts; } // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. - else if (node.kind === 163 /* PropertyDeclaration */ || node.kind === 201 /* PropertyAccessExpression */ || node.kind === 162 /* PropertySignature */ || - (node.kind === 160 /* Parameter */ && ts.hasSyntacticModifier(node.parent, 8 /* Private */))) { + else if (node.kind === 164 /* PropertyDeclaration */ || node.kind === 202 /* PropertyAccessExpression */ || node.kind === 163 /* PropertySignature */ || + (node.kind === 161 /* Parameter */ && ts.hasSyntacticModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasSyntacticModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -97898,7 +100886,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 252 /* ClassDeclaration */ || node.kind === 160 /* Parameter */) { + else if (node.parent.kind === 253 /* ClassDeclaration */ || node.kind === 161 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -97923,7 +100911,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (node.kind === 168 /* SetAccessor */) { + if (node.kind === 169 /* SetAccessor */) { // Getters can infer the return type from the returned expression, but setters cannot, so the // "_from_external_module_1_but_cannot_be_named" case cannot occur. if (ts.hasSyntacticModifier(node, 32 /* Static */)) { @@ -97962,26 +100950,26 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 169 /* CallSignature */: + case 170 /* CallSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasSyntacticModifier(node, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -97989,7 +100977,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.kind === 253 /* ClassDeclaration */) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -98003,7 +100991,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -98028,30 +101016,30 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 170 /* ConstructSignature */: - case 175 /* ConstructorType */: + case 171 /* ConstructSignature */: + case 176 /* ConstructorType */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 169 /* CallSignature */: + case 170 /* CallSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasSyntacticModifier(node.parent, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -98059,7 +101047,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 253 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98072,15 +101060,15 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 251 /* FunctionDeclaration */: - case 174 /* FunctionType */: + case 252 /* FunctionDeclaration */: + case 175 /* FunctionType */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; - case 168 /* SetAccessor */: - case 167 /* GetAccessor */: + case 169 /* SetAccessor */: + case 168 /* GetAccessor */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98094,39 +101082,39 @@ var ts; // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 190 /* MappedType */: + case 191 /* MappedType */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1; break; - case 175 /* ConstructorType */: - case 170 /* ConstructSignature */: + case 176 /* ConstructorType */: + case 171 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 169 /* CallSignature */: + case 170 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasSyntacticModifier(node.parent, 32 /* Static */)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 253 /* ClassDeclaration */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 174 /* FunctionType */: - case 251 /* FunctionDeclaration */: + case 175 /* FunctionType */: + case 252 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -98165,11 +101153,13 @@ var ts; typeName: node.name }; } - function getTypeAliasDeclarationVisibilityError() { + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name + diagnosticMessage: symbolAccessibilityResult.errorModuleName + ? ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2 + : ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: ts.isJSDocTypeAlias(node) ? ts.Debug.checkDefined(node.typeExpression) : node.type, + typeName: ts.isJSDocTypeAlias(node) ? ts.getNameOfDeclaration(node) : node.name, }; } } @@ -98190,7 +101180,7 @@ var ts; } function isInternalDeclaration(node, currentSourceFile) { var parseTreeNode = ts.getParseTreeNode(node); - if (parseTreeNode && parseTreeNode.kind === 160 /* Parameter */) { + if (parseTreeNode && parseTreeNode.kind === 161 /* Parameter */) { var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode); var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined; var text = currentSourceFile.text; @@ -98252,6 +101242,7 @@ var ts; reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; + var errorFallbackNode; var currentSourceFile; var refs; var libs; @@ -98321,8 +101312,8 @@ var ts; recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } function reportInaccessibleUniqueSymbolError() { @@ -98346,35 +101337,38 @@ var ts; } } function reportTruncationError() { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); } } function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { - var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); + var _a; + var primaryDeclaration = (_a = parentSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; }); - for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { - var augmentations = augmentingDeclarations_1[_i]; - context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + if (augmentingDeclarations) { + for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { + var augmentations = augmentingDeclarations_1[_i]; + context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + } } } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; - getSymbolAccessibilityDiagnostic = function (s) { return ({ + getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ diagnosticMessage: s.errorModuleName ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit, errorNode: s.errorNode || sourceFile - }); }; + })); }; var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled); getSymbolAccessibilityDiagnostic = oldDiag; return result; } function transformRoot(node) { - if (node.kind === 297 /* SourceFile */ && node.isDeclarationFile) { + if (node.kind === 298 /* SourceFile */ && node.isDeclarationFile) { return node; } - if (node.kind === 298 /* Bundle */) { + if (node.kind === 299 /* Bundle */) { isBundledEmit = true; refs = new ts.Map(); libs = new ts.Map(); @@ -98404,7 +101398,7 @@ var ts; var updated = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements); return factory.updateSourceFile(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); }), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 300 /* InputFiles */) { + if (prepend.kind === 301 /* InputFiles */) { var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal); hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib; collectReferences(sourceFile, refs); @@ -98496,7 +101490,7 @@ var ts; declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { - var specifier = ts.moduleSpecifiers.getModuleSpecifier(__assign(__assign({}, options), { baseUrl: options.baseUrl && ts.toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }), currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, + var specifier = ts.moduleSpecifiers.getModuleSpecifier(options, currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, /*preferences*/ undefined); if (!ts.pathIsRelative(specifier)) { // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration @@ -98545,7 +101539,7 @@ var ts; return name; } else { - if (name.kind === 197 /* ArrayBindingPattern */) { + if (name.kind === 198 /* ArrayBindingPattern */) { return factory.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); } else { @@ -98553,7 +101547,7 @@ var ts; } } function visitBindingElement(elem) { - if (elem.kind === 222 /* OmittedExpression */) { + if (elem.kind === 223 /* OmittedExpression */) { return elem; } return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); @@ -98591,7 +101585,7 @@ var ts; // Literal const declarations will have an initializer ensured rather than a type return; } - var shouldUseResolverType = node.kind === 160 /* Parameter */ && + var shouldUseResolverType = node.kind === 161 /* Parameter */ && (resolver.isRequiredInitializedParameter(node) || resolver.isOptionalUninitializedParameterProperty(node)); if (type && !shouldUseResolverType) { @@ -98600,7 +101594,7 @@ var ts; if (!ts.getParseTreeNode(node)) { return type ? ts.visitNode(type, visitDeclarationSubtree) : factory.createKeywordTypeNode(128 /* AnyKeyword */); } - if (node.kind === 168 /* SetAccessor */) { + if (node.kind === 169 /* SetAccessor */) { // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) return factory.createKeywordTypeNode(128 /* AnyKeyword */); @@ -98611,12 +101605,12 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); } - if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) { + if (node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */) { return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } - if (node.kind === 160 /* Parameter */ - || node.kind === 163 /* PropertyDeclaration */ - || node.kind === 162 /* PropertySignature */) { + if (node.kind === 161 /* Parameter */ + || node.kind === 164 /* PropertyDeclaration */ + || node.kind === 163 /* PropertySignature */) { if (!node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); @@ -98633,20 +101627,20 @@ var ts; function isDeclarationAndNotVisible(node) { node = ts.getParseTreeNode(node); switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 256 /* ModuleDeclaration */: - case 253 /* InterfaceDeclaration */: - case 252 /* ClassDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: + case 252 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 254 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: return !resolver.isDeclarationVisible(node); // The following should be doing their own visibility checks based on filtering their members - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return !getBindingNameVisible(node); - case 260 /* ImportEqualsDeclaration */: - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: + case 261 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: return false; } return false; @@ -98727,7 +101721,7 @@ var ts; function rewriteModuleSpecifier(parent, input) { if (!input) return undefined; // TODO: GH#18217 - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 256 /* ModuleDeclaration */ && parent.kind !== 195 /* ImportType */); + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 257 /* ModuleDeclaration */ && parent.kind !== 196 /* ImportType */); if (ts.isStringLiteralLike(input)) { if (isBundledEmit) { var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); @@ -98747,7 +101741,7 @@ var ts; function transformImportEqualsDeclaration(decl) { if (!resolver.isDeclarationVisible(decl)) return; - if (decl.moduleReference.kind === 272 /* ExternalModuleReference */) { + if (decl.moduleReference.kind === 273 /* ExternalModuleReference */) { // Rewrite external module names if necessary var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); return factory.updateImportEqualsDeclaration(decl, @@ -98774,7 +101768,7 @@ var ts; return visibleDefaultBinding && factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } - if (decl.importClause.namedBindings.kind === 263 /* NamespaceImport */) { + if (decl.importClause.namedBindings.kind === 264 /* NamespaceImport */) { // Namespace import (optionally with visible default) var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; @@ -98869,7 +101863,7 @@ var ts; // We'd see a TDZ violation at runtime var canProduceDiagnostic = ts.canProduceDiagnostics(input); var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; - var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 177 /* TypeLiteral */ || input.kind === 190 /* MappedType */) && input.parent.kind !== 254 /* TypeAliasDeclaration */); + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 178 /* TypeLiteral */ || input.kind === 191 /* MappedType */) && input.parent.kind !== 255 /* TypeAliasDeclaration */); // Emit methods which are private as properties with no type information if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { if (ts.hasEffectiveModifier(input, 8 /* Private */)) { @@ -98890,21 +101884,21 @@ var ts; } if (isProcessedComponent(input)) { switch (input.kind) { - case 223 /* ExpressionWithTypeArguments */: { + case 224 /* ExpressionWithTypeArguments */: { if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { checkEntityNameVisibility(input.expression, enclosingDeclaration); } var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(factory.updateExpressionWithTypeArguments(node, node.expression, node.typeArguments)); } - case 173 /* TypeReference */: { + case 174 /* TypeReference */: { checkEntityNameVisibility(input.typeName, enclosingDeclaration); var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(factory.updateTypeReferenceNode(node, node.typeName, node.typeArguments)); } - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: return cleanup(factory.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); - case 166 /* Constructor */: { + case 167 /* Constructor */: { // A constructor declaration may not have a type annotation var ctor = factory.createConstructorDeclaration( /*decorators*/ undefined, @@ -98912,7 +101906,7 @@ var ts; /*body*/ undefined); return cleanup(ctor); } - case 165 /* MethodDeclaration */: { + case 166 /* MethodDeclaration */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } @@ -98922,7 +101916,7 @@ var ts; /*body*/ undefined); return cleanup(sig); } - case 167 /* GetAccessor */: { + case 168 /* GetAccessor */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } @@ -98931,7 +101925,7 @@ var ts; /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), ensureType(input, accessorType), /*body*/ undefined)); } - case 168 /* SetAccessor */: { + case 169 /* SetAccessor */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } @@ -98939,31 +101933,31 @@ var ts; /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), /*body*/ undefined)); } - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updatePropertyDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type))); - case 164 /* MethodSignature */: { + case 165 /* MethodSignature */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updateMethodSignature(input, ensureModifiers(input), input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 169 /* CallSignature */: { + case 170 /* CallSignature */: { return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 171 /* IndexSignature */: { + case 172 /* IndexSignature */: { return cleanup(factory.updateIndexSignature(input, /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(128 /* AnyKeyword */))); } - case 249 /* VariableDeclaration */: { + case 250 /* VariableDeclaration */: { if (ts.isBindingPattern(input.name)) { return recreateBindingPattern(input.name); } @@ -98971,13 +101965,13 @@ var ts; suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types return cleanup(factory.updateVariableDeclaration(input, input.name, /*exclamationToken*/ undefined, ensureType(input, input.type), ensureNoInitializer(input))); } - case 159 /* TypeParameter */: { + case 160 /* TypeParameter */: { if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { return cleanup(factory.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); } return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); } - case 184 /* ConditionalType */: { + case 185 /* ConditionalType */: { // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); @@ -98989,13 +101983,13 @@ var ts; var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); return cleanup(factory.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); } - case 174 /* FunctionType */: { + case 175 /* FunctionType */: { return cleanup(factory.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 175 /* ConstructorType */: { + case 176 /* ConstructorType */: { return cleanup(factory.updateConstructorTypeNode(input, ensureModifiers(input), ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 195 /* ImportType */: { + case 196 /* ImportType */: { if (!ts.isLiteralImportTypeNode(input)) return cleanup(input); return cleanup(factory.updateImportTypeNode(input, factory.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); @@ -99027,7 +102021,7 @@ var ts; } } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 165 /* MethodDeclaration */ && ts.hasEffectiveModifier(node.parent, 8 /* Private */); + return node.parent.kind === 166 /* MethodDeclaration */ && ts.hasEffectiveModifier(node.parent, 8 /* Private */); } function visitDeclarationStatements(input) { if (!isPreservedDeclarationStatement(input)) { @@ -99037,7 +102031,7 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 267 /* ExportDeclaration */: { + case 268 /* ExportDeclaration */: { if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; } @@ -99047,7 +102041,7 @@ var ts; return factory.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); } - case 266 /* ExportAssignment */: { + case 267 /* ExportAssignment */: { // Always visible if the parent node isn't dropped for being not visible if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; @@ -99062,7 +102056,9 @@ var ts; diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: input }); }; + errorFallbackNode = input; var varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + errorFallbackNode = undefined; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */)); return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } @@ -99079,17 +102075,17 @@ var ts; // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too return statement; } - var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (11263 /* All */ ^ 1 /* Export */)); + var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (27647 /* All */ ^ 1 /* Export */)); return factory.updateModifiers(statement, modifiers); } function transformTopLevelDeclaration(input) { if (shouldStripInternal(input)) return; switch (input.kind) { - case 260 /* ImportEqualsDeclaration */: { + case 261 /* ImportEqualsDeclaration */: { return transformImportEqualsDeclaration(input); } - case 261 /* ImportDeclaration */: { + case 262 /* ImportDeclaration */: { return transformImportDeclaration(input); } } @@ -99110,14 +102106,14 @@ var ts; } var previousNeedsDeclare = needsDeclare; switch (input.kind) { - case 254 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + case 255 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all return cleanup(factory.updateTypeAliasDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); - case 253 /* InterfaceDeclaration */: { + case 254 /* InterfaceDeclaration */: { return cleanup(factory.updateInterfaceDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } - case 251 /* FunctionDeclaration */: { + case 252 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type var clean = cleanup(factory.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), @@ -99132,7 +102128,7 @@ var ts; fakespace_1.symbol = props[0].parent; var exportMappings_1 = []; var declarations = ts.mapDefined(props, function (p) { - if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + if (!p.valueDeclaration || !ts.isPropertyAccessExpression(p.valueDeclaration)) { return undefined; // TODO GH#33569: Handle element access expressions that created late bound names (rather than silently omitting them) } getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration); @@ -99184,10 +102180,10 @@ var ts; return clean; } } - case 256 /* ModuleDeclaration */: { + case 257 /* ModuleDeclaration */: { needsDeclare = false; var inner = input.body; - if (inner && inner.kind === 257 /* ModuleBlock */) { + if (inner && inner.kind === 258 /* ModuleBlock */) { var oldNeedsScopeFix = needsScopeFixMarker; var oldHasScopeFix = resultHasScopeMarker; resultHasScopeMarker = false; @@ -99230,7 +102226,9 @@ var ts; /*decorators*/ undefined, mods, input.name, body)); } } - case 252 /* ClassDeclaration */: { + case 253 /* ClassDeclaration */: { + errorNameNode = input.name; + errorFallbackNode = input; var modifiers = factory.createNodeArray(ensureModifiers(input)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -99238,7 +102236,7 @@ var ts; if (ctor) { var oldDiag_1 = getSymbolAccessibilityDiagnostic; parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { - if (!ts.hasSyntacticModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param)) + if (!ts.hasSyntacticModifier(param, 16476 /* ParameterPropertyModifier */) || shouldStripInternal(param)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 78 /* Identifier */) { @@ -99313,10 +102311,10 @@ var ts; /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); } } - case 232 /* VariableStatement */: { + case 233 /* VariableStatement */: { return cleanup(transformVariableStatement(input)); } - case 255 /* EnumDeclaration */: { + case 256 /* EnumDeclaration */: { return cleanup(factory.updateEnumDeclaration(input, /*decorators*/ undefined, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; @@ -99335,12 +102333,14 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 256 /* ModuleDeclaration */) { + if (input.kind === 257 /* ModuleDeclaration */) { needsDeclare = previousNeedsDeclare; } if (node === input) { return node; } + errorFallbackNode = undefined; + errorNameNode = undefined; return node && ts.setOriginalNode(preserveJsDoc(node, input), input); } } @@ -99356,7 +102356,7 @@ var ts; return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); } function recreateBindingElement(e) { - if (e.kind === 222 /* OmittedExpression */) { + if (e.kind === 223 /* OmittedExpression */) { return; } if (e.name) { @@ -99404,9 +102404,9 @@ var ts; return factory.createModifiersFromModifierFlags(newFlags); } function ensureModifierFlags(node) { - var mask = 11263 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files + var mask = 27647 /* All */ ^ (4 /* Public */ | 256 /* Async */ | 16384 /* Override */); // No async and override modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; - var parentIsFile = node.parent.kind === 297 /* SourceFile */; + var parentIsFile = node.parent.kind === 298 /* SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { mask ^= 2 /* Ambient */; additions = 0 /* None */; @@ -99435,7 +102435,7 @@ var ts; } ts.transformDeclarations = transformDeclarations; function isAlwaysType(node) { - if (node.kind === 253 /* InterfaceDeclaration */) { + if (node.kind === 254 /* InterfaceDeclaration */) { return true; } return false; @@ -99445,7 +102445,7 @@ var ts; return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); } function maskModifierFlags(node, modifierMask, modifierAdditions) { - if (modifierMask === void 0) { modifierMask = 11263 /* All */ ^ 4 /* Public */; } + if (modifierMask === void 0) { modifierMask = 27647 /* All */ ^ 4 /* Public */; } if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions; if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) { @@ -99460,7 +102460,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 167 /* GetAccessor */ + return accessor.kind === 168 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type @@ -99469,52 +102469,52 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return !ts.hasEffectiveModifier(node, 8 /* Private */); - case 160 /* Parameter */: - case 249 /* VariableDeclaration */: + case 161 /* Parameter */: + case 250 /* VariableDeclaration */: return true; } return false; } function isPreservedDeclarationStatement(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 256 /* ModuleDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 253 /* InterfaceDeclaration */: - case 252 /* ClassDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: - case 232 /* VariableStatement */: - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: + case 252 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 254 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 233 /* VariableStatement */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: return true; } return false; } function isProcessedComponent(node) { switch (node.kind) { - case 170 /* ConstructSignature */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 171 /* IndexSignature */: - case 249 /* VariableDeclaration */: - case 159 /* TypeParameter */: - case 223 /* ExpressionWithTypeArguments */: - case 173 /* TypeReference */: - case 184 /* ConditionalType */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 195 /* ImportType */: + case 171 /* ConstructSignature */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 172 /* IndexSignature */: + case 250 /* VariableDeclaration */: + case 160 /* TypeParameter */: + case 224 /* ExpressionWithTypeArguments */: + case 174 /* TypeReference */: + case 185 /* ConditionalType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 196 /* ImportType */: return true; } return false; @@ -99570,6 +102570,9 @@ var ts; if (languageVersion < 99 /* ESNext */) { transformers.push(ts.transformESNext); } + if (languageVersion < 8 /* ES2021 */) { + transformers.push(ts.transformES2021); + } if (languageVersion < 7 /* ES2020 */) { transformers.push(ts.transformES2020); } @@ -99646,7 +102649,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, factory, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(341 /* Count */); + var enabledSyntaxKindFeatures = new Array(345 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentStatements; @@ -99657,6 +102660,9 @@ var ts; var lexicalEnvironmentFlagsStack = []; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; + var blockScopedVariableDeclarationsStack = []; + var blockScopeStackOffset = 0; + var blockScopedVariableDeclarations; var emitHelpers; var onSubstituteNode = noEmitSubstitution; var onEmitNode = noEmitNotification; @@ -99679,6 +102685,9 @@ var ts; hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, addInitializationStatement: addInitializationStatement, + startBlockScope: startBlockScope, + endBlockScope: endBlockScope, + addBlockScopedVariable: addBlockScopedVariable, requestEmitHelper: requestEmitHelper, readEmitHelpers: readEmitHelpers, enableSubstitution: enableSubstitution, @@ -99722,9 +102731,9 @@ var ts; var transformed = []; for (var _a = 0, nodes_3 = nodes; _a < nodes_3.length; _a++) { var node = nodes_3[_a]; - ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 298 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); transformed.push((allowDtsFiles ? transformation : transformRoot)(node)); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // prevent modification of the lexical environment. state = 2 /* Completed */; @@ -99939,6 +102948,38 @@ var ts; function getLexicalEnvironmentFlags() { return lexicalEnvironmentFlags; } + /** + * Starts a block scope. Any existing block hoisted variables are pushed onto the stack and the related storage variables are reset. + */ + function startBlockScope() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot start a block scope during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot start a block scope after transformation has completed."); + blockScopedVariableDeclarationsStack[blockScopeStackOffset] = blockScopedVariableDeclarations; + blockScopeStackOffset++; + blockScopedVariableDeclarations = undefined; + } + /** + * Ends a block scope. The previous set of block hoisted variables are restored. Any hoisted declarations are returned. + */ + function endBlockScope() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot end a block scope during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot end a block scope after transformation has completed."); + var statements = ts.some(blockScopedVariableDeclarations) ? + [ + factory.createVariableStatement( + /*modifiers*/ undefined, factory.createVariableDeclarationList(blockScopedVariableDeclarations.map(function (identifier) { return factory.createVariableDeclaration(identifier); }), 1 /* Let */)) + ] : undefined; + blockScopeStackOffset--; + blockScopedVariableDeclarations = blockScopedVariableDeclarationsStack[blockScopeStackOffset]; + if (blockScopeStackOffset === 0) { + blockScopedVariableDeclarationsStack = []; + } + return statements; + } + function addBlockScopedVariable(name) { + ts.Debug.assert(blockScopeStackOffset > 0, "Cannot add a block scoped variable outside of an iteration body."); + (blockScopedVariableDeclarations || (blockScopedVariableDeclarations = [])).push(name); + } function requestEmitHelper(helper) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); @@ -99980,35 +103021,37 @@ var ts; } ts.transformNodes = transformNodes; ts.nullTransformationContext = { - get factory() { return ts.factory; }, - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: ts.returnUndefined, + factory: ts.factory, getCompilerOptions: function () { return ({}); }, - getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + getEmitHost: ts.notImplemented, getEmitHelperFactory: ts.notImplemented, + startLexicalEnvironment: ts.noop, + resumeLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop, + endLexicalEnvironment: ts.returnUndefined, setLexicalEnvironmentFlags: ts.noop, getLexicalEnvironmentFlags: function () { return 0; }, - hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + hoistFunctionDeclaration: ts.noop, addInitializationStatement: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, + startBlockScope: ts.noop, + endBlockScope: ts.returnUndefined, + addBlockScopedVariable: ts.noop, requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop, + readEmitHelpers: ts.notImplemented, + enableSubstitution: ts.noop, + enableEmitNotification: ts.noop, + isSubstitutionEnabled: ts.notImplemented, + isEmitNotificationEnabled: ts.notImplemented, + onSubstituteNode: noEmitSubstitution, + onEmitNode: noEmitNotification, addDiagnostic: ts.noop, }; })(ts || (ts = {})); var ts; (function (ts) { var brackets = createBracketsMap(); - var syntheticParent = { pos: -1, end: -1 }; /*@internal*/ function isBuildInfoFile(file) { return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */); @@ -100094,7 +103137,7 @@ var ts; /*@internal*/ function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); - if (sourceFile.kind === 298 /* Bundle */) { + if (sourceFile.kind === 299 /* Bundle */) { return getOutputPathsForBundle(options, forceDtsPaths); } else { @@ -100320,15 +103363,15 @@ var ts; sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); }) }; } - ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); emitBuildInfo(bundleBuildInfo, buildInfoPath); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { if (jsFilePath) { @@ -100455,13 +103498,13 @@ var ts; if (!declBlocked || forceDtsEmit) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, { - sourceMap: compilerOptions.declarationMap, + sourceMap: !forceDtsEmit && compilerOptions.declarationMap, sourceRoot: compilerOptions.sourceRoot, mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, // Explicitly do not passthru either `inline` option }); - if (forceDtsEmit && declarationTransform.transformed[0].kind === 297 /* SourceFile */) { + if (forceDtsEmit && declarationTransform.transformed[0].kind === 298 /* SourceFile */) { var sourceFile = declarationTransform.transformed[0]; exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; } @@ -100484,8 +103527,8 @@ var ts; ts.forEachChild(node, collectLinkedAliases); } function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) { - var bundle = sourceFileOrBundle.kind === 298 /* Bundle */ ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 297 /* SourceFile */ ? sourceFileOrBundle : undefined; + var bundle = sourceFileOrBundle.kind === 299 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 298 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; var sourceMapGenerator; if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { @@ -100526,7 +103569,7 @@ var ts; } function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { return (mapOptions.sourceMap || mapOptions.inlineSourceMap) - && (sourceFileOrBundle.kind !== 297 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); + && (sourceFileOrBundle.kind !== 298 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); } function getSourceRoot(mapOptions) { // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the @@ -100585,7 +103628,7 @@ var ts; ts.emitFiles = emitFiles; /*@internal*/ function getBuildInfoText(buildInfo) { - return JSON.stringify(buildInfo, undefined, 2); + return JSON.stringify(buildInfo); } ts.getBuildInfoText = getBuildInfoText; /*@internal*/ @@ -100766,7 +103809,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = ts.getNewLineCharacter(printerOptions); var moduleKind = ts.getEmitModuleKind(printerOptions); @@ -100805,9 +103848,11 @@ var ts; var detachedCommentsInfo; var hasWrittenComment = false; var commentsDisabled = !!printerOptions.removeComments; - var lastNode; var lastSubstitution; + var currentParenthesizerRule; var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; + var parenthesizer = ts.factory.parenthesizer; + var emitBinaryExpression = createEmitBinaryExpression(); reset(); return { // public API @@ -100835,9 +103880,9 @@ var ts; break; } switch (node.kind) { - case 297 /* SourceFile */: return printFile(node); - case 298 /* Bundle */: return printBundle(node); - case 299 /* UnparsedSource */: return printUnparsedSource(node); + case 298 /* SourceFile */: return printFile(node); + case 299 /* Bundle */: return printBundle(node); + case 300 /* UnparsedSource */: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -100871,7 +103916,7 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - emitList(syntheticParent, nodes, format); + emitList(/*parentNode*/ undefined, nodes, format); reset(); writer = previousWriter; } @@ -101006,7 +104051,7 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - pipelineEmit(hint, node); + pipelineEmit(hint, node, /*parenthesizerRule*/ undefined); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -101034,51 +104079,54 @@ var ts; currentSourceFile = undefined; currentLineMap = undefined; detachedCommentsInfo = undefined; - lastNode = undefined; - lastSubstitution = undefined; setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined); } function getCurrentLineMap() { return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); } - function emit(node) { + function emit(node, parenthesizerRule) { if (node === undefined) return; var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node); - var substitute = pipelineEmit(4 /* Unspecified */, node); + pipelineEmit(4 /* Unspecified */, node, parenthesizerRule); recordBundleFileInternalSectionEnd(prevSourceFileTextKind); - return substitute; } function emitIdentifierName(node) { if (node === undefined) return; - return pipelineEmit(2 /* IdentifierName */, node); + pipelineEmit(2 /* IdentifierName */, node, /*parenthesizerRule*/ undefined); } - function emitExpression(node) { + function emitExpression(node, parenthesizerRule) { if (node === undefined) return; - return pipelineEmit(1 /* Expression */, node); + pipelineEmit(1 /* Expression */, node, parenthesizerRule); } function emitJsxAttributeValue(node) { - return pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); + pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); } - function pipelineEmit(emitHint, node) { - var savedLastNode = lastNode; - var savedLastSubstitution = lastSubstitution; - var savedPreserveSourceNewlines = preserveSourceNewlines; - lastNode = node; - lastSubstitution = undefined; - if (preserveSourceNewlines && !!(ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) { + function beforeEmitNode(node) { + if (preserveSourceNewlines && (ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) { preserveSourceNewlines = false; } + } + function afterEmitNode(savedPreserveSourceNewlines) { + preserveSourceNewlines = savedPreserveSourceNewlines; + } + function pipelineEmit(emitHint, node, parenthesizerRule) { + currentParenthesizerRule = parenthesizerRule; var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node); pipelinePhase(emitHint, node); - ts.Debug.assert(lastNode === node); - var substitute = lastSubstitution; - lastNode = savedLastNode; - lastSubstitution = savedLastSubstitution; - preserveSourceNewlines = savedPreserveSourceNewlines; - return substitute || node; + currentParenthesizerRule = undefined; + } + function shouldEmitComments(node) { + return !commentsDisabled && !ts.isSourceFile(node); + } + function shouldEmitSourceMaps(node) { + return !sourceMapsDisabled && + !ts.isSourceFile(node) && + !ts.isInJsonFile(node) && + !ts.isUnparsedSource(node) && + !ts.isUnparsedPrepend(node); } function getPipelinePhase(phase, emitHint, node) { switch (phase) { @@ -101088,18 +104136,21 @@ var ts; } // falls through case 1 /* Substitution */: - if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) { + if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) { + if (currentParenthesizerRule) { + lastSubstitution = currentParenthesizerRule(lastSubstitution); + } return pipelineEmitWithSubstitution; } // falls through case 2 /* Comments */: - if (!commentsDisabled && node.kind !== 297 /* SourceFile */) { + if (shouldEmitComments(node)) { return pipelineEmitWithComments; } // falls through case 3 /* SourceMaps */: - if (!sourceMapsDisabled && node.kind !== 297 /* SourceFile */ && !ts.isInJsonFile(node)) { - return pipelineEmitWithSourceMap; + if (shouldEmitSourceMaps(node)) { + return pipelineEmitWithSourceMaps; } // falls through case 4 /* Emit */: @@ -101112,13 +104163,25 @@ var ts; return getPipelinePhase(currentPhase + 1, emitHint, node); } function pipelineEmitWithNotification(hint, node) { - ts.Debug.assert(lastNode === node); var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node); onEmitNode(hint, node, pipelinePhase); - ts.Debug.assert(lastNode === node); } function pipelineEmitWithHint(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (preserveSourceNewlines) { + var savedPreserveSourceNewlines = preserveSourceNewlines; + beforeEmitNode(node); + pipelineEmitWithHintWorker(hint, node); + afterEmitNode(savedPreserveSourceNewlines); + } + else { + pipelineEmitWithHintWorker(hint, node); + } + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); + // clear the parenthesizer rule as we ascend + currentParenthesizerRule = undefined; + } + function pipelineEmitWithHintWorker(hint, node) { if (hint === 0 /* SourceFile */) return emitSourceFile(ts.cast(node, ts.isSourceFile)); if (hint === 2 /* IdentifierName */) @@ -101132,24 +104195,12 @@ var ts; return emitEmptyStatement(/*isEmbeddedStatement*/ true); } if (hint === 4 /* Unspecified */) { - if (ts.isKeyword(node.kind)) - return writeTokenNode(node, writeKeyword); switch (node.kind) { // Pseudo-literals case 15 /* TemplateHead */: case 16 /* TemplateMiddle */: case 17 /* TemplateTail */: return emitLiteral(node, /*jsxAttributeEscape*/ false); - case 299 /* UnparsedSource */: - case 293 /* UnparsedPrepend */: - return emitUnparsedSourceOrPrepend(node); - case 292 /* UnparsedPrologue */: - return writeUnparsedNode(node); - case 294 /* UnparsedText */: - case 295 /* UnparsedInternalText */: - return emitUnparsedTextLike(node); - case 296 /* UnparsedSyntheticReference */: - return emitUnparsedSyntheticReference(node); // Identifiers case 78 /* Identifier */: return emitIdentifier(node); @@ -101158,282 +104209,323 @@ var ts; return emitPrivateIdentifier(node); // Parse tree nodes // Names - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return emitQualifiedName(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return emitComputedPropertyName(node); // Signature elements - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return emitTypeParameter(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return emitParameter(node); - case 161 /* Decorator */: + case 162 /* Decorator */: return emitDecorator(node); // Type members - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: return emitPropertySignature(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return emitPropertyDeclaration(node); - case 164 /* MethodSignature */: + case 165 /* MethodSignature */: return emitMethodSignature(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return emitMethodDeclaration(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return emitConstructor(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return emitAccessorDeclaration(node); - case 169 /* CallSignature */: + case 170 /* CallSignature */: return emitCallSignature(node); - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: return emitConstructSignature(node); - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: return emitIndexSignature(node); - case 194 /* TemplateLiteralTypeSpan */: - return emitTemplateTypeSpan(node); // Types - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return emitTypePredicate(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return emitTypeReference(node); - case 174 /* FunctionType */: + case 175 /* FunctionType */: return emitFunctionType(node); - case 308 /* JSDocFunctionType */: - return emitJSDocFunctionType(node); - case 175 /* ConstructorType */: + case 176 /* ConstructorType */: return emitConstructorType(node); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return emitTypeQuery(node); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return emitTypeLiteral(node); - case 178 /* ArrayType */: + case 179 /* ArrayType */: return emitArrayType(node); - case 179 /* TupleType */: + case 180 /* TupleType */: return emitTupleType(node); - case 180 /* OptionalType */: + case 181 /* OptionalType */: return emitOptionalType(node); - case 182 /* UnionType */: + // SyntaxKind.RestType is handled below + case 183 /* UnionType */: return emitUnionType(node); - case 183 /* IntersectionType */: + case 184 /* IntersectionType */: return emitIntersectionType(node); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return emitConditionalType(node); - case 185 /* InferType */: + case 186 /* InferType */: return emitInferType(node); - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return emitParenthesizedType(node); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(node); - case 187 /* ThisType */: + case 188 /* ThisType */: return emitThisType(); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return emitTypeOperator(node); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return emitIndexedAccessType(node); - case 190 /* MappedType */: + case 191 /* MappedType */: return emitMappedType(node); - case 191 /* LiteralType */: + case 192 /* LiteralType */: return emitLiteralType(node); - case 193 /* TemplateLiteralType */: + case 193 /* NamedTupleMember */: + return emitNamedTupleMember(node); + case 194 /* TemplateLiteralType */: return emitTemplateType(node); - case 195 /* ImportType */: + case 195 /* TemplateLiteralTypeSpan */: + return emitTemplateTypeSpan(node); + case 196 /* ImportType */: return emitImportTypeNode(node); - case 303 /* JSDocAllType */: - writePunctuation("*"); - return; - case 304 /* JSDocUnknownType */: - writePunctuation("?"); - return; - case 305 /* JSDocNullableType */: - return emitJSDocNullableType(node); - case 306 /* JSDocNonNullableType */: - return emitJSDocNonNullableType(node); - case 307 /* JSDocOptionalType */: - return emitJSDocOptionalType(node); - case 181 /* RestType */: - case 309 /* JSDocVariadicType */: - return emitRestOrJSDocVariadicType(node); - case 192 /* NamedTupleMember */: - return emitNamedTupleMember(node); // Binding patterns - case 196 /* ObjectBindingPattern */: + case 197 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return emitBindingElement(node); // Misc - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return emitTemplateSpan(node); - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: return emitSemicolonClassElement(); // Statements - case 230 /* Block */: + case 231 /* Block */: return emitBlock(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return emitVariableStatement(node); - case 231 /* EmptyStatement */: + case 232 /* EmptyStatement */: return emitEmptyStatement(/*isEmbeddedStatement*/ false); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return emitExpressionStatement(node); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return emitIfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return emitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return emitWhileStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return emitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return emitForInStatement(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return emitForOfStatement(node); - case 240 /* ContinueStatement */: + case 241 /* ContinueStatement */: return emitContinueStatement(node); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: return emitBreakStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return emitReturnStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return emitWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return emitSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return emitLabeledStatement(node); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return emitThrowStatement(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return emitTryStatement(node); - case 248 /* DebuggerStatement */: + case 249 /* DebuggerStatement */: return emitDebuggerStatement(node); // Declarations - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return emitVariableDeclarationList(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return emitFunctionDeclaration(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return emitClassDeclaration(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return emitTypeAliasDeclaration(node); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return emitModuleBlock(node); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return emitCaseBlock(node); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return emitNamespaceExportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return emitImportDeclaration(node); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return emitImportClause(node); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return emitNamespaceImport(node); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: return emitNamespaceExport(node); - case 264 /* NamedImports */: + case 265 /* NamedImports */: return emitNamedImports(node); - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: return emitImportSpecifier(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return emitExportAssignment(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return emitExportDeclaration(node); - case 268 /* NamedExports */: + case 269 /* NamedExports */: return emitNamedExports(node); - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: return emitExportSpecifier(node); - case 271 /* MissingDeclaration */: + case 272 /* MissingDeclaration */: return; // Module references - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: return emitExternalModuleReference(node); // JSX (non-expression) case 11 /* JsxText */: return emitJsxText(node); - case 275 /* JsxOpeningElement */: - case 278 /* JsxOpeningFragment */: + case 276 /* JsxOpeningElement */: + case 279 /* JsxOpeningFragment */: return emitJsxOpeningElementOrFragment(node); - case 276 /* JsxClosingElement */: - case 279 /* JsxClosingFragment */: + case 277 /* JsxClosingElement */: + case 280 /* JsxClosingFragment */: return emitJsxClosingElementOrFragment(node); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return emitJsxAttribute(node); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return emitJsxAttributes(node); - case 282 /* JsxSpreadAttribute */: + case 283 /* JsxSpreadAttribute */: return emitJsxSpreadAttribute(node); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return emitJsxExpression(node); // Clauses - case 284 /* CaseClause */: + case 285 /* CaseClause */: return emitCaseClause(node); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: return emitDefaultClause(node); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: return emitHeritageClause(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return emitCatchClause(node); // Property assignments - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: return emitSpreadAssignment(node); // Enum - case 291 /* EnumMember */: + case 292 /* EnumMember */: return emitEnumMember(node); + // Unparsed + case 293 /* UnparsedPrologue */: + return writeUnparsedNode(node); + case 300 /* UnparsedSource */: + case 294 /* UnparsedPrepend */: + return emitUnparsedSourceOrPrepend(node); + case 295 /* UnparsedText */: + case 296 /* UnparsedInternalText */: + return emitUnparsedTextLike(node); + case 297 /* UnparsedSyntheticReference */: + return emitUnparsedSyntheticReference(node); + // Top-level nodes + case 298 /* SourceFile */: + return emitSourceFile(node); + case 299 /* Bundle */: + return ts.Debug.fail("Bundles should be printed using printBundle"); + // SyntaxKind.UnparsedSource (handled above) + case 301 /* InputFiles */: + return ts.Debug.fail("InputFiles should not be printed"); // JSDoc nodes (only used in codefixes currently) - case 326 /* JSDocParameterTag */: - case 333 /* JSDocPropertyTag */: + case 302 /* JSDocTypeExpression */: + return emitJSDocTypeExpression(node); + case 303 /* JSDocNameReference */: + return emitJSDocNameReference(node); + case 304 /* JSDocAllType */: + return writePunctuation("*"); + case 305 /* JSDocUnknownType */: + return writePunctuation("?"); + case 306 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 307 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 308 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 309 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 182 /* RestType */: + case 310 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + case 311 /* JSDocNamepathType */: + return; + case 312 /* JSDocComment */: + return emitJSDoc(node); + case 314 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 315 /* JSDocSignature */: + return emitJSDocSignature(node); + case 317 /* JSDocTag */: + case 322 /* JSDocClassTag */: + return emitJSDocSimpleTag(node); + case 318 /* JSDocAugmentsTag */: + case 319 /* JSDocImplementsTag */: + return emitJSDocHeritageTag(node); + case 320 /* JSDocAuthorTag */: + case 321 /* JSDocDeprecatedTag */: + return; + // SyntaxKind.JSDocClassTag (see JSDocTag, above) + case 323 /* JSDocPublicTag */: + case 324 /* JSDocPrivateTag */: + case 325 /* JSDocProtectedTag */: + case 326 /* JSDocReadonlyTag */: + case 327 /* JSDocOverrideTag */: + return; + case 328 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + // SyntaxKind.JSDocEnumTag (see below) + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: return emitJSDocPropertyLikeTag(node); - case 327 /* JSDocReturnTag */: - case 329 /* JSDocTypeTag */: - case 328 /* JSDocThisTag */: - case 325 /* JSDocEnumTag */: + case 329 /* JSDocEnumTag */: + case 331 /* JSDocReturnTag */: + case 332 /* JSDocThisTag */: + case 333 /* JSDocTypeTag */: return emitJSDocSimpleTypedTag(node); - case 316 /* JSDocImplementsTag */: - case 315 /* JSDocAugmentsTag */: - return emitJSDocHeritageTag(node); - case 330 /* JSDocTemplateTag */: + case 334 /* JSDocTemplateTag */: return emitJSDocTemplateTag(node); - case 331 /* JSDocTypedefTag */: + case 335 /* JSDocTypedefTag */: return emitJSDocTypedefTag(node); - case 324 /* JSDocCallbackTag */: - return emitJSDocCallbackTag(node); - case 313 /* JSDocSignature */: - return emitJSDocSignature(node); - case 312 /* JSDocTypeLiteral */: - return emitJSDocTypeLiteral(node); - case 319 /* JSDocClassTag */: - case 314 /* JSDocTag */: - return emitJSDocSimpleTag(node); - case 332 /* JSDocSeeTag */: + case 336 /* JSDocSeeTag */: return emitJSDocSeeTag(node); - case 302 /* JSDocNameReference */: - return emitJSDocNameReference(node); - case 311 /* JSDocComment */: - return emitJSDoc(node); - // Transformation nodes (ignored) + // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) + // Transformation nodes + case 339 /* NotEmittedStatement */: + case 343 /* EndOfDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: + return; } if (ts.isExpression(node)) { hint = 1 /* Expression */; if (substituteNode !== ts.noEmitSubstitution) { - lastSubstitution = node = substituteNode(hint, node); + var substitute = substituteNode(hint, node) || node; + if (substitute !== node) { + node = substitute; + if (currentParenthesizerRule) { + node = currentParenthesizerRule(node); + } + } } } - else if (ts.isToken(node)) { - return writeTokenNode(node, writePunctuation); - } } if (hint === 1 /* Expression */) { switch (node.kind) { @@ -101448,84 +104540,92 @@ var ts; // Identifiers case 78 /* Identifier */: return emitIdentifier(node); - // Reserved words - case 94 /* FalseKeyword */: - case 103 /* NullKeyword */: - case 105 /* SuperKeyword */: - case 109 /* TrueKeyword */: - case 107 /* ThisKeyword */: - case 99 /* ImportKeyword */: - writeTokenNode(node, writeKeyword); - return; // Expressions - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return emitObjectLiteralExpression(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return emitPropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return emitElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return emitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return emitNewExpression(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: return emitTypeAssertionExpression(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return emitParenthesizedExpression(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return emitFunctionExpression(node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return emitArrowFunction(node); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return emitDeleteExpression(node); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return emitVoidExpression(node); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return emitAwaitExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return emitBinaryExpression(node); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return emitConditionalExpression(node); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return emitTemplateExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return emitYieldExpression(node); - case 220 /* SpreadElement */: - return emitSpreadExpression(node); - case 221 /* ClassExpression */: + case 221 /* SpreadElement */: + return emitSpreadElement(node); + case 222 /* ClassExpression */: return emitClassExpression(node); - case 222 /* OmittedExpression */: + case 223 /* OmittedExpression */: return; - case 224 /* AsExpression */: + case 225 /* AsExpression */: return emitAsExpression(node); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return emitNonNullExpression(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return emitMetaProperty(node); + case 228 /* SyntheticExpression */: + return ts.Debug.fail("SyntheticExpression should never be printed."); // JSX - case 273 /* JsxElement */: + case 274 /* JsxElement */: return emitJsxElement(node); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return emitJsxFragment(node); + // Synthesized list + case 338 /* SyntaxList */: + return ts.Debug.fail("SyntaxList should not be printed"); // Transformation nodes - case 336 /* PartiallyEmittedExpression */: + case 339 /* NotEmittedStatement */: + return; + case 340 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return emitCommaList(node); + case 342 /* MergeDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: + return; + case 344 /* SyntheticReferenceExpression */: + return ts.Debug.fail("SyntheticReferenceExpression should not be printed"); } } + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + if (ts.isTokenKind(node.kind)) + return writeTokenNode(node, writePunctuation); + ts.Debug.fail("Unhandled SyntaxKind: " + ts.Debug.formatSyntaxKind(node.kind) + "."); } function emitMappedTypeParameter(node) { emit(node.name); @@ -101535,10 +104635,11 @@ var ts; emit(node.constraint); } function pipelineEmitWithSubstitution(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node); - pipelinePhase(hint, lastSubstitution); - ts.Debug.assert(lastNode === node || lastSubstitution === node); + ts.Debug.assertIsDefined(lastSubstitution); + node = lastSubstitution; + lastSubstitution = undefined; + pipelinePhase(hint, node); } function getHelpersFromBundledSourceFiles(bundle) { var result; @@ -101564,7 +104665,7 @@ var ts; } function emitHelpers(node) { var helpersEmitted = false; - var bundle = node.kind === 298 /* Bundle */ ? node : undefined; + var bundle = node.kind === 299 /* Bundle */ ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -101664,7 +104765,7 @@ var ts; var pos = getTextPosWithWriteLine(); writeUnparsedNode(unparsed); if (bundleFileInfo) { - updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 294 /* UnparsedText */ ? + updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 295 /* UnparsedText */ ? "text" /* Text */ : "internal" /* Internal */); } @@ -101710,7 +104811,7 @@ var ts; } function emitComputedPropertyName(node) { writePunctuation("["); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName); writePunctuation("]"); } // @@ -101737,18 +104838,18 @@ var ts; emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); - if (node.parent && node.parent.kind === 308 /* JSDocFunctionType */ && !node.name) { + if (node.parent && node.parent.kind === 309 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { emitTypeAnnotation(node.type); } // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. - emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitDecorator(decorator) { writePunctuation("@"); - emitExpression(decorator.expression); + emitExpression(decorator.expression, parenthesizer.parenthesizeLeftSideOfAccess); } // // Type members @@ -101799,7 +104900,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeKeyword(node.kind === 167 /* GetAccessor */ ? "get" : "set"); + writeKeyword(node.kind === 168 /* GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); @@ -101913,7 +105014,7 @@ var ts; writePunctuation("}"); } function emitArrayType(node) { - emit(node.elementType); + emit(node.elementType, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("["); writePunctuation("]"); } @@ -101936,21 +105037,21 @@ var ts; emit(node.type); } function emitOptionalType(node) { - emit(node.type); + emit(node.type, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("?"); } function emitUnionType(node) { - emitList(node, node.types, 516 /* UnionTypeConstituents */); + emitList(node, node.types, 516 /* UnionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitIntersectionType(node) { - emitList(node, node.types, 520 /* IntersectionTypeConstituents */); + emitList(node, node.types, 520 /* IntersectionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitConditionalType(node) { - emit(node.checkType); + emit(node.checkType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writeKeyword("extends"); writeSpace(); - emit(node.extendsType); + emit(node.extendsType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writePunctuation("?"); writeSpace(); @@ -101976,10 +105077,10 @@ var ts; function emitTypeOperator(node) { writeTokenText(node.operator, writeKeyword); writeSpace(); - emit(node.type); + emit(node.type, parenthesizer.parenthesizeMemberOfElementType); } function emitIndexedAccessType(node) { - emit(node.objectType); + emit(node.objectType, parenthesizer.parenthesizeMemberOfElementType); writePunctuation("["); emit(node.indexType); writePunctuation("]"); @@ -102072,7 +105173,7 @@ var ts; writeSpace(); } emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // Expressions @@ -102080,7 +105181,7 @@ var ts; function emitArrayLiteralExpression(node) { var elements = node.elements; var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; - emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitObjectLiteralExpression(node) { ts.forEach(node.properties, generateMemberNames); @@ -102096,13 +105197,13 @@ var ts; } } function emitPropertyAccessExpression(node) { - var expression = ts.cast(emitExpression(node.expression), ts.isExpression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); var token = node.questionDotToken || ts.setTextRangePosEnd(ts.factory.createToken(24 /* DotToken */), node.expression.end, node.name.pos); var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token); var linesAfterDot = getLinesBetweenNodes(node, token, node.name); writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false); var shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ && - mayNeedDotDotForPropertyAccess(expression) && + mayNeedDotDotForPropertyAccess(node.expression) && !writer.hasTrailingComment() && !writer.hasTrailingWhitespace(); if (shouldEmitDotDot) { @@ -102138,27 +105239,27 @@ var ts; } } function emitElementAccessExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitNewExpression(node) { emitTokenWithComment(102 /* NewKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfNew); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitTaggedTemplateExpression(node) { - emitExpression(node.tag); + emitExpression(node.tag, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); writeSpace(); emitExpression(node.template); @@ -102167,12 +105268,12 @@ var ts; writePunctuation("<"); emit(node.type); writePunctuation(">"); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); - emitExpression(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); writeLineSeparatorsAfter(node.expression, node); decreaseIndentIf(indented); emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); @@ -102196,29 +105297,29 @@ var ts; function emitDeleteExpression(node) { emitTokenWithComment(88 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitTypeOfExpression(node) { emitTokenWithComment(111 /* TypeOfKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitVoidExpression(node) { emitTokenWithComment(113 /* VoidKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitAwaitExpression(node) { emitTokenWithComment(130 /* AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitPrefixUnaryExpression(node) { writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { writeSpace(); } - emitExpression(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPrefixUnary); } function shouldEmitWhitespaceBeforeOperand(node) { // In some cases, we need to emit a space between the operator and the operand. One obvious case @@ -102234,84 +105335,101 @@ var ts; // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. var operand = node.operand; - return operand.kind === 214 /* PrefixUnaryExpression */ + return operand.kind === 215 /* PrefixUnaryExpression */ && ((node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */)) || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */))); } function emitPostfixUnaryExpression(node) { - emitExpression(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary); writeTokenText(node.operator, writeOperator); } - var EmitBinaryExpressionState; - (function (EmitBinaryExpressionState) { - EmitBinaryExpressionState[EmitBinaryExpressionState["EmitLeft"] = 0] = "EmitLeft"; - EmitBinaryExpressionState[EmitBinaryExpressionState["EmitRight"] = 1] = "EmitRight"; - EmitBinaryExpressionState[EmitBinaryExpressionState["FinishEmit"] = 2] = "FinishEmit"; - })(EmitBinaryExpressionState || (EmitBinaryExpressionState = {})); - /** - * emitBinaryExpression includes an embedded work stack to attempt to handle as many nested binary expressions - * as possible without creating any additional stack frames. This can only be done when the emit pipeline does - * not require notification/substitution/comment/sourcemap decorations. - */ - function emitBinaryExpression(node) { - var nodeStack = [node]; - var stateStack = [0 /* EmitLeft */]; - var stackIndex = 0; - while (stackIndex >= 0) { - node = nodeStack[stackIndex]; - switch (stateStack[stackIndex]) { - case 0 /* EmitLeft */: { - maybePipelineEmitExpression(node.left); - break; - } - case 1 /* EmitRight */: { - var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */; - var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); - var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); - writeLinesAndIndent(linesBeforeOperator, isCommaOperator); - emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken, node.operatorToken.kind === 100 /* InKeyword */ ? writeKeyword : writeOperator); - emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts - writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); - maybePipelineEmitExpression(node.right); - break; - } - case 2 /* FinishEmit */: { - var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); - var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); - decreaseIndentIf(linesBeforeOperator, linesAfterOperator); - stackIndex--; - break; - } - default: return ts.Debug.fail("Invalid state " + stateStack[stackIndex] + " for emitBinaryExpressionWorker"); + function createEmitBinaryExpression() { + return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined); + function onEnter(node, state) { + if (state) { + state.stackIndex++; + state.preserveSourceNewlinesStack[state.stackIndex] = preserveSourceNewlines; + state.containerPosStack[state.stackIndex] = containerPos; + state.containerEndStack[state.stackIndex] = containerEnd; + state.declarationListContainerEndStack[state.stackIndex] = declarationListContainerEnd; + var emitComments_1 = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node); + var emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node); + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (emitComments_1) + emitCommentsBeforeNode(node); + if (emitSourceMaps) + emitSourceMapsBeforeNode(node); + beforeEmitNode(node); } - } - function maybePipelineEmitExpression(next) { - // Advance the state of this unit of work, - stateStack[stackIndex]++; - // Then actually do the work of emitting the node `next` returned by the prior state - // The following section should be identical to `pipelineEmit` save it assumes EmitHint.Expression and offloads - // binary expression handling, where possible, to the contained work queue - // #region trampolinePipelineEmit - var savedLastNode = lastNode; - var savedLastSubstitution = lastSubstitution; - lastNode = next; - lastSubstitution = undefined; + else { + state = { + stackIndex: 0, + preserveSourceNewlinesStack: [undefined], + containerPosStack: [-1], + containerEndStack: [-1], + declarationListContainerEndStack: [-1], + shouldEmitCommentsStack: [false], + shouldEmitSourceMapsStack: [false], + }; + } + return state; + } + function onLeft(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "left"); + } + function onOperator(operatorToken, _state, node) { + var isCommaOperator = operatorToken.kind !== 27 /* CommaToken */; + var linesBeforeOperator = getLinesBetweenNodes(node, node.left, operatorToken); + var linesAfterOperator = getLinesBetweenNodes(node, operatorToken, node.right); + writeLinesAndIndent(linesBeforeOperator, isCommaOperator); + emitLeadingCommentsOfPosition(operatorToken.pos); + writeTokenNode(operatorToken, operatorToken.kind === 100 /* InKeyword */ ? writeKeyword : writeOperator); + emitTrailingCommentsOfPosition(operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts + writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); + } + function onRight(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "right"); + } + function onExit(node, state) { + var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); + var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); + decreaseIndentIf(linesBeforeOperator, linesAfterOperator); + if (state.stackIndex > 0) { + var savedPreserveSourceNewlines = state.preserveSourceNewlinesStack[state.stackIndex]; + var savedContainerPos = state.containerPosStack[state.stackIndex]; + var savedContainerEnd = state.containerEndStack[state.stackIndex]; + var savedDeclarationListContainerEnd = state.declarationListContainerEndStack[state.stackIndex]; + var shouldEmitComments_1 = state.shouldEmitCommentsStack[state.stackIndex]; + var shouldEmitSourceMaps_1 = state.shouldEmitSourceMapsStack[state.stackIndex]; + afterEmitNode(savedPreserveSourceNewlines); + if (shouldEmitSourceMaps_1) + emitSourceMapsAfterNode(node); + if (shouldEmitComments_1) + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); + state.stackIndex--; + } + } + function maybeEmitExpression(next, parent, side) { + var parenthesizerRule = side === "left" ? + parenthesizer.getParenthesizeLeftSideOfBinaryForOperator(parent.operatorToken.kind) : + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(parent.operatorToken.kind); var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next); - if (pipelinePhase === pipelineEmitWithHint && ts.isBinaryExpression(next)) { - // If the target pipeline phase is emit directly, and the next node's also a binary expression, - // skip all the intermediate indirection and push the expression directly onto the work stack - stackIndex++; - stateStack[stackIndex] = 0 /* EmitLeft */; - nodeStack[stackIndex] = next; + if (pipelinePhase === pipelineEmitWithSubstitution) { + ts.Debug.assertIsDefined(lastSubstitution); + next = parenthesizerRule(ts.cast(lastSubstitution, ts.isExpression)); + pipelinePhase = getNextPipelinePhase(1 /* Substitution */, 1 /* Expression */, next); + lastSubstitution = undefined; } - else { - pipelinePhase(1 /* Expression */, next); + if (pipelinePhase === pipelineEmitWithComments || + pipelinePhase === pipelineEmitWithSourceMaps || + pipelinePhase === pipelineEmitWithHint) { + if (ts.isBinaryExpression(next)) { + return next; + } } - ts.Debug.assert(lastNode === next); - lastNode = savedLastNode; - lastSubstitution = savedLastSubstitution; - // #endregion trampolinePipelineEmit + currentParenthesizerRule = parenthesizerRule; + pipelinePhase(1 /* Expression */, next); } } function emitConditionalExpression(node) { @@ -102319,16 +105437,16 @@ var ts; var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue); var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken); var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse); - emitExpression(node.condition); + emitExpression(node.condition, parenthesizer.parenthesizeConditionOfConditionalExpression); writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); emit(node.questionToken); writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true); - emitExpression(node.whenTrue); + emitExpression(node.whenTrue, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion); writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true); emit(node.colonToken); writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true); - emitExpression(node.whenFalse); + emitExpression(node.whenFalse, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeColon, linesAfterColon); } function emitTemplateExpression(node) { @@ -102338,22 +105456,22 @@ var ts; function emitYieldExpression(node) { emitTokenWithComment(124 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); - emitExpressionWithLeadingSpace(node.expression); + emitExpressionWithLeadingSpace(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } - function emitSpreadExpression(node) { + function emitSpreadElement(node) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitClassExpression(node) { generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); } function emitAsExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); if (node.type) { writeSpace(); writeKeyword("as"); @@ -102362,7 +105480,7 @@ var ts; } } function emitNonNullExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); writeOperator("!"); } function emitMetaProperty(node) { @@ -102405,7 +105523,7 @@ var ts; } } function emitExpressionStatement(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfExpressionStatement); // Emit semicolon in non json files // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { @@ -102422,7 +105540,7 @@ var ts; if (node.elseStatement) { writeLineOrSpace(node, node.thenStatement, node.elseStatement); emitTokenWithComment(90 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); - if (node.elseStatement.kind === 234 /* IfStatement */) { + if (node.elseStatement.kind === 235 /* IfStatement */) { writeSpace(); emit(node.elseStatement); } @@ -102485,7 +105603,7 @@ var ts; emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(156 /* OfKeyword */, node.initializer.end, writeKeyword, node); + emitTokenWithComment(157 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); @@ -102493,7 +105611,7 @@ var ts; } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 250 /* VariableDeclarationList */) { + if (node.kind === 251 /* VariableDeclarationList */) { emit(node); } else { @@ -102530,7 +105648,7 @@ var ts; } pos = writeTokenText(token, writer, pos); if (isSimilarNode && contextNode.end !== pos) { - var isJsxExprContext = contextNode.kind === 283 /* JsxExpression */; + var isJsxExprContext = contextNode.kind === 284 /* JsxExpression */; emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ !isJsxExprContext, /*forceNoNewline*/ isJsxExprContext); } return pos; @@ -102594,7 +105712,7 @@ var ts; emit(node.name); emit(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); @@ -102613,9 +105731,6 @@ var ts; emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } - function emitBlockCallback(_hint, body) { - emitBlockFunctionBody(body); - } function emitSignatureAndBody(node, emitSignatureHead) { var body = node.body; if (body) { @@ -102628,12 +105743,7 @@ var ts; ts.forEach(node.parameters, generateNames); generateNames(node.body); emitSignatureHead(node); - if (onEmitNode) { - onEmitNode(4 /* Unspecified */, body, emitBlockCallback); - } - else { - emitBlockFunctionBody(body); - } + emitBlockFunctionBody(body); popNameGenerationScope(node); if (indentedFlag) { decreaseIndent(); @@ -102642,7 +105752,7 @@ var ts; else { emitSignatureHead(node); writeSpace(); - emitExpression(body); + emitExpression(body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); } } else { @@ -102686,6 +105796,7 @@ var ts; return true; } function emitBlockFunctionBody(body) { + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(body); writeSpace(); writePunctuation("{"); increaseIndent(); @@ -102700,6 +105811,7 @@ var ts; } decreaseIndent(); writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body); + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); @@ -102715,7 +105827,7 @@ var ts; increaseIndent(); } else { - emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset); + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, /*parenthesizerRule*/ undefined, statementOffset); } } function emitClassDeclaration(node) { @@ -102790,7 +105902,7 @@ var ts; var body = node.body; if (!body) return writeTrailingSemicolon(); - while (body.kind === 256 /* ModuleDeclaration */) { + while (body && ts.isModuleDeclaration(body)) { writePunctuation("."); emit(body.name); body = body.body; @@ -102880,7 +105992,9 @@ var ts; emitTokenWithComment(87 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, node.isExportEquals ? + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(62 /* EqualsToken */) : + parenthesizer.parenthesizeExpressionOfExportDefault); writeTrailingSemicolon(); } function emitExportDeclaration(node) { @@ -103052,7 +106166,7 @@ var ts; function emitCaseClause(node) { emitTokenWithComment(81 /* CaseKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { @@ -103113,7 +106227,7 @@ var ts; var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } - emitExpression(initializer); + emitExpression(initializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitShorthandPropertyAssignment(node) { emit(node.name); @@ -103121,13 +106235,13 @@ var ts; writeSpace(); writePunctuation("="); writeSpace(); - emitExpression(node.objectAssignmentInitializer); + emitExpression(node.objectAssignmentInitializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } } function emitSpreadAssignment(node) { if (node.expression) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } } // @@ -103135,7 +106249,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // JSDoc @@ -103143,18 +106257,21 @@ var ts; function emitJSDoc(node) { write("/**"); if (node.comment) { - var lines = node.comment.split(/\r\n?|\n/g); - for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { - var line = lines_2[_a]; - writeLine(); - writeSpace(); - writePunctuation("*"); - writeSpace(); - write(line); + var text = ts.getTextOfJSDocComment(node.comment); + if (text) { + var lines = text.split(/\r\n?|\n/g); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } } } if (node.tags) { - if (node.tags.length === 1 && node.tags[0].kind === 329 /* JSDocTypeTag */ && !node.comment) { + if (node.tags.length === 1 && node.tags[0].kind === 333 /* JSDocTypeTag */ && !node.comment) { writeSpace(); emit(node.tags[0]); } @@ -103199,7 +106316,7 @@ var ts; function emitJSDocTypedefTag(tag) { emitJSDocTagName(tag.tagName); if (tag.typeExpression) { - if (tag.typeExpression.kind === 301 /* JSDocTypeExpression */) { + if (tag.typeExpression.kind === 302 /* JSDocTypeExpression */) { emitJSDocTypeExpression(tag.typeExpression); } else { @@ -103218,7 +106335,7 @@ var ts; emit(tag.fullName); } emitJSDocComment(tag.comment); - if (tag.typeExpression && tag.typeExpression.kind === 312 /* JSDocTypeLiteral */) { + if (tag.typeExpression && tag.typeExpression.kind === 314 /* JSDocTypeLiteral */) { emitJSDocTypeLiteral(tag.typeExpression); } } @@ -103271,9 +106388,10 @@ var ts; emit(tagName); } function emitJSDocComment(comment) { - if (comment) { + var text = ts.getTextOfJSDocComment(comment); + if (text) { writeSpace(); - write(comment); + write(text); } } function emitJSDocTypeExpression(typeExpression) { @@ -103376,7 +106494,7 @@ var ts; emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitTripleSlashDirectivesIfNeeded(node); - emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); + emitList(node, statements, 1 /* MultiLine */, /*parenthesizerRule*/ undefined, index === -1 ? statements.length : index); popNameGenerationScope(node); } // Transformation nodes @@ -103384,7 +106502,7 @@ var ts; emitExpression(node.expression); } function emitCommaList(node) { - emitExpressionList(node, node.elements, 528 /* CommaListElements */); + emitExpressionList(node, node.elements, 528 /* CommaListElements */, /*parenthesizerRule*/ undefined); } /** * Emits any prologue directives at the start of a Statement list, returning the @@ -103530,12 +106648,12 @@ var ts; emit(node); } } - function emitInitializer(node, equalCommentStartPos, container) { + function emitInitializer(node, equalCommentStartPos, container, parenthesizerRule) { if (node) { writeSpace(); emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container); writeSpace(); - emitExpression(node); + emitExpression(node, parenthesizerRule); } } function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { @@ -103550,10 +106668,10 @@ var ts; emit(node); } } - function emitExpressionWithLeadingSpace(node) { + function emitExpressionWithLeadingSpace(node, parenthesizerRule) { if (node) { writeSpace(); - emitExpression(node); + emitExpression(node, parenthesizerRule); } } function emitWithTrailingSpace(node) { @@ -103583,7 +106701,7 @@ var ts; emitList(parentNode, decorators, 2146305 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 53776 /* TypeArguments */); + emitList(parentNode, typeArguments, 53776 /* TypeArguments */, parenthesizer.parenthesizeMemberOfElementType); } function emitTypeParameters(parentNode, typeParameters) { if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures @@ -103622,12 +106740,6 @@ var ts; function emitParametersForIndexSignature(parentNode, parameters) { emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */); } - function emitList(parentNode, children, format, start, count) { - emitNodeList(emit, parentNode, children, format, start, count); - } - function emitExpressionList(parentNode, children, format, start, count) { - emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 - } function writeDelimiter(format) { switch (format & 60 /* DelimitersMask */) { case 0 /* None */: @@ -103650,7 +106762,13 @@ var ts; break; } } - function emitNodeList(emit, parentNode, children, format, start, count) { + function emitList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count); + } + function emitExpressionList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emitExpression, parentNode, children, format, parenthesizerRule, start, count); + } + function emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; @@ -103669,8 +106787,7 @@ var ts; } if (format & 15360 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); - if (isEmpty && !isUndefined) { - // TODO: GH#18217 + if (isEmpty && children) { emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists } } @@ -103679,7 +106796,7 @@ var ts; } if (isEmpty) { // Write a line terminator if the parent node was multi-line - if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && ts.rangeIsOnSingleLine(parentNode, currentSourceFile))) { + if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && (!parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile)))) { writeLine(); } else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) { @@ -103687,6 +106804,7 @@ var ts; } } else { + ts.Debug.type(children); // Write the opening line terminator or leading whitespace. var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; @@ -103721,7 +106839,7 @@ var ts; // a // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline // , - if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { + if (format & 60 /* DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { emitLeadingCommentsOfPosition(previousSibling.end); } writeDelimiter(format); @@ -103754,7 +106872,12 @@ var ts; shouldEmitInterveningComments = mayEmitInterveningComments; } nextListElementPos = child.pos; - emit(child); + if (emit.length === 1) { + emit(child); + } + else { + emit(child, parenthesizerRule); + } if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); shouldDecreaseIndentAfterEmit = false; @@ -103779,7 +106902,7 @@ var ts; // 2 // /* end of element 2 */ // ]; - if (previousSibling && parentNode.end !== previousSibling.end && (format & 60 /* DelimitersMask */) && !skipTrailingComments) { + if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60 /* DelimitersMask */) && !skipTrailingComments) { emitLeadingCommentsOfPosition(hasTrailingComma && (children === null || children === void 0 ? void 0 : children.end) ? children.end : previousSibling.end); } // Decrease the indent, if requested. @@ -103800,8 +106923,7 @@ var ts; onAfterEmitNodeArray(children); } if (format & 15360 /* BracketsMask */) { - if (isEmpty && !isUndefined) { - // TODO: GH#18217 + if (isEmpty && children) { emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists } writePunctuation(getClosingBracket(format)); @@ -103932,7 +107054,7 @@ var ts; } var firstChild_1 = children[0]; if (firstChild_1 === undefined) { - return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; + return !parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } if (firstChild_1.pos === nextListElementPos) { // If this child starts at the beginning of a list item in a parent list, its leading @@ -103956,7 +107078,8 @@ var ts; // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } - if (!ts.positionIsSynthesized(parentNode.pos) && + if (parentNode && + !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || ts.getOriginalNode(firstChild_1.parent) === ts.getOriginalNode(parentNode))) { if (preserveSourceNewlines) { @@ -103979,10 +107102,10 @@ var ts; // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } - else if (!ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode) && previousNode.parent === nextNode.parent) { - if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); }); - } + else if (preserveSourceNewlines && siblingNodePositionsAreComparable(previousNode, nextNode)) { + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); }); + } + else if (!preserveSourceNewlines && !ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode)) { return ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1; } else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) { @@ -104001,9 +107124,9 @@ var ts; } var lastChild = ts.lastOrUndefined(children); if (lastChild === undefined) { - return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; + return !parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } - if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { + if (parentNode && !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { if (preserveSourceNewlines) { var end_1 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end; return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_1, parentNode.end, currentSourceFile, includeComments); }); @@ -104089,7 +107212,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 207 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + while (node.kind === 208 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -104159,84 +107282,84 @@ var ts; if (!node) return; switch (node.kind) { - case 230 /* Block */: + case 231 /* Block */: ts.forEach(node.statements, generateNames); break; - case 245 /* LabeledStatement */: - case 243 /* WithStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 246 /* LabeledStatement */: + case 244 /* WithStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: generateNames(node.statement); break; - case 234 /* IfStatement */: + case 235 /* IfStatement */: generateNames(node.thenStatement); generateNames(node.elseStatement); break; - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: - case 238 /* ForInStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: + case 239 /* ForInStatement */: generateNames(node.initializer); generateNames(node.statement); break; - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: generateNames(node.caseBlock); break; - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: ts.forEach(node.clauses, generateNames); break; - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: ts.forEach(node.statements, generateNames); break; - case 247 /* TryStatement */: + case 248 /* TryStatement */: generateNames(node.tryBlock); generateNames(node.catchClause); generateNames(node.finallyBlock); break; - case 287 /* CatchClause */: + case 288 /* CatchClause */: generateNames(node.variableDeclaration); generateNames(node.block); break; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: generateNames(node.declarationList); break; - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: ts.forEach(node.declarations, generateNames); break; - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: generateNameIfNeeded(node.name); break; - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: generateNameIfNeeded(node.name); if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { ts.forEach(node.parameters, generateNames); generateNames(node.body); } break; - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: ts.forEach(node.elements, generateNames); break; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: generateNames(node.importClause); break; - case 262 /* ImportClause */: + case 263 /* ImportClause */: generateNameIfNeeded(node.name); generateNames(node.namedBindings); break; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: generateNameIfNeeded(node.name); break; - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: generateNameIfNeeded(node.name); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: ts.forEach(node.elements, generateNames); break; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: generateNameIfNeeded(node.propertyName || node.name); break; } @@ -104245,12 +107368,12 @@ var ts; if (!node) return; switch (node.kind) { - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: generateNameIfNeeded(node.name); break; } @@ -104432,23 +107555,23 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 266 /* ExportAssignment */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 267 /* ExportAssignment */: return generateNameForExportDefault(); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return generateNameForClassExpression(); - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return generateNameForMethodOrAccessor(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return makeTempVariableName(0 /* Auto */, /*reserveInNestedScopes*/ true); default: return makeTempVariableName(0 /* Auto */); @@ -104491,25 +107614,45 @@ var ts; } // Comments function pipelineEmitWithComments(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node); + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + emitCommentsBeforeNode(node); + pipelinePhase(hint, node); + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitCommentsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit leading comments + emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + } + } + function emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit trailing comments + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = false; + } + emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitLeadingCommentsOfNode(node, emitFlags, pos, end) { enterComment(); hasWrittenComment = false; - var emitFlags = ts.getEmitFlags(node); - var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; - var isEmittedNode = node.kind !== 335 /* NotEmittedStatement */; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */; var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; // Save current container state on the stack. - var savedContainerPos = containerPos; - var savedContainerEnd = containerEnd; - var savedDeclarationListContainerEnd = declarationListContainerEnd; if ((pos > 0 || end > 0) && pos !== end) { // Emit leading comments if the position is not synthesized and the node // has not opted out from emitting leading comments. if (!skipLeadingComments) { - emitLeadingComments(pos, isEmittedNode); + emitLeadingComments(pos, /*isEmittedNode*/ node.kind !== 339 /* NotEmittedStatement */); } if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments. @@ -104520,23 +107663,17 @@ var ts; containerEnd = end; // To avoid invalid comment emit in a down-level binding pattern, we // keep track of the last declaration list container's end - if (node.kind === 250 /* VariableDeclarationList */) { + if (node.kind === 251 /* VariableDeclarationList */) { declarationListContainerEnd = end; } } } ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); exitComment(); - var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node); - if (emitFlags & 2048 /* NoNestedComments */) { - commentsDisabled = true; - pipelinePhase(hint, node); - commentsDisabled = false; - } - else { - pipelinePhase(hint, node); - } + } + function emitTrailingCommentsOfNode(node, emitFlags, pos, end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { enterComment(); + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); if ((pos > 0 || end > 0) && pos !== end) { // Restore previous container state. @@ -104545,12 +107682,11 @@ var ts; declarationListContainerEnd = savedDeclarationListContainerEnd; // Emit trailing comments if the position is not synthesized and the node // has not opted out from emitting leading comments and is an emitted node. - if (!skipTrailingComments && isEmittedNode) { + if (!skipTrailingComments && node.kind !== 339 /* NotEmittedStatement */) { emitTrailingComments(end); } } exitComment(); - ts.Debug.assert(lastNode === node || lastSubstitution === node); } function emitLeadingSynthesizedComment(comment) { if (comment.hasLeadingNewline || comment.kind === 2 /* SingleLineCommentTrivia */) { @@ -104610,6 +107746,23 @@ var ts; } exitComment(); } + function siblingNodePositionsAreComparable(previousNode, nextNode) { + if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) { + return false; + } + if (nextNode.pos < previousNode.end) { + return false; + } + previousNode = ts.getOriginalNode(previousNode); + nextNode = ts.getOriginalNode(nextNode); + var parent = previousNode.parent; + if (!parent || parent !== nextNode.parent) { + return false; + } + var parentNodeArray = ts.getContainingNodeArray(previousNode); + var prevNodeIndex = parentNodeArray === null || parentNodeArray === void 0 ? void 0 : parentNodeArray.indexOf(previousNode); + return prevNodeIndex !== undefined && prevNodeIndex > -1 && parentNodeArray.indexOf(nextNode) === prevNodeIndex + 1; + } function emitLeadingComments(pos, isEmittedNode) { hasWrittenComment = false; if (isEmittedNode) { @@ -104782,42 +107935,49 @@ var ts; } return node.parsedSourceMap || undefined; } - function pipelineEmitWithSourceMap(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); + function pipelineEmitWithSourceMaps(hint, node) { var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node); - if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) { - pipelinePhase(hint, node); - } - else if (ts.isUnparsedNode(node)) { + emitSourceMapsBeforeNode(node); + pipelinePhase(hint, node); + emitSourceMapsAfterNode(node); + } + function emitSourceMapsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit leading sourcemap + if (ts.isUnparsedNode(node)) { + ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); var parsed = getParsedSourceMap(node.parent); if (parsed && sourceMapGenerator) { sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); } - pipelinePhase(hint, node); } else { - var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; - var emitFlags = ts.getEmitFlags(node); - if (node.kind !== 335 /* NotEmittedStatement */ + var source = sourceMapRange.source || sourceMapSource; + if (node.kind !== 339 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 - && pos >= 0) { - emitSourcePos(source, skipSourceTrivia(source, pos)); + && sourceMapRange.pos >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); } if (emitFlags & 64 /* NoNestedSourceMaps */) { sourceMapsDisabled = true; - pipelinePhase(hint, node); - sourceMapsDisabled = false; } - else { - pipelinePhase(hint, node); + } + } + function emitSourceMapsAfterNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit trailing sourcemap + if (!ts.isUnparsedNode(node)) { + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = false; } - if (node.kind !== 335 /* NotEmittedStatement */ + if (node.kind !== 339 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 - && end >= 0) { - emitSourcePos(source, end); + && sourceMapRange.end >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); } } - ts.Debug.assert(lastNode === node || lastSubstitution === node); } /** * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source @@ -104969,12 +108129,22 @@ var ts; return ts.getBaseFileName(ts.normalizePath(fileName)); } function createCachedFileSystemEntries(rootDir, rootDirPath) { - var resultFromHost = { - files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories(rootDir) || [] - }; - cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); - return resultFromHost; + var _a; + if (!host.realpath || ts.ensureTrailingDirectorySeparator(toPath(host.realpath(rootDir))) === rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); + return resultFromHost; + } + // If the directory is symlink do not cache the result + if ((_a = host.directoryExists) === null || _a === void 0 ? void 0 : _a.call(host, rootDir)) { + cachedReadDirectoryResult.set(rootDirPath, false); + return false; + } + // Non existing directory + return undefined; } /** * If the readDirectory result was already cached, it returns that @@ -105049,17 +108219,32 @@ var ts; } function readDirectory(rootDir, extensions, excludes, includes, depth) { var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { + var rootResult = tryReadDirectory(rootDir, rootDirPath); + var rootSymLinkResult; + if (rootResult !== undefined) { return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir) { var path = toPath(dir); if (path === rootDirPath) { - return result; + return rootResult || getFileSystemEntriesFromHost(dir, path); } - return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + var result = tryReadDirectory(dir, path); + return result !== undefined ? + result || getFileSystemEntriesFromHost(dir, path) : + ts.emptyFileSystemEntries; + } + function getFileSystemEntriesFromHost(dir, path) { + if (rootSymLinkResult && path === rootDirPath) + return rootSymLinkResult; + var result = { + files: ts.map(host.readDirectory(dir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || ts.emptyArray, + directories: host.getDirectories(dir) || ts.emptyArray + }; + if (path === rootDirPath) + rootSymLinkResult = result; + return result; } } function realpath(s) { @@ -105067,7 +108252,7 @@ var ts; } function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { + if (existingResult !== undefined) { // Just clear the cache for now // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated clearCache(); @@ -105127,9 +108312,9 @@ var ts; /** * Updates the map of shared extended config file watches with a new set of extended config files from a base config file of the project */ - function updateSharedExtendedConfigFileWatcher(projectPath, parsed, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath) { + function updateSharedExtendedConfigFileWatcher(projectPath, options, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath) { var _a; - var extendedConfigs = ts.arrayToMap(((_a = parsed === null || parsed === void 0 ? void 0 : parsed.options.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath); + var extendedConfigs = ts.arrayToMap(((_a = options === null || options === void 0 ? void 0 : options.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath); // remove project from all unrelated watchers extendedConfigFilesMap.forEach(function (watcher, extendedConfigFilePath) { if (!extendedConfigs.has(extendedConfigFilePath)) { @@ -105147,12 +108332,12 @@ var ts; // start watching previously unseen extended config extendedConfigFilesMap.set(extendedConfigFilePath, { projects: new ts.Set([projectPath]), - fileWatcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath), + watcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath), close: function () { var existing = extendedConfigFilesMap.get(extendedConfigFilePath); if (!existing || existing.projects.size !== 0) return; - existing.fileWatcher.close(); + existing.watcher.close(); extendedConfigFilesMap.delete(extendedConfigFilePath); }, }); @@ -105160,6 +108345,31 @@ var ts; }); } ts.updateSharedExtendedConfigFileWatcher = updateSharedExtendedConfigFileWatcher; + /** + * Remove the project from the extended config file watchers and close not needed watches + */ + function clearSharedExtendedConfigFileWatcher(projectPath, extendedConfigFilesMap) { + extendedConfigFilesMap.forEach(function (watcher) { + if (watcher.projects.delete(projectPath)) + watcher.close(); + }); + } + ts.clearSharedExtendedConfigFileWatcher = clearSharedExtendedConfigFileWatcher; + /** + * Clean the extendsConfigCache when extended config file has changed + */ + function cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath) { + if (!extendedConfigCache.delete(extendedConfigFilePath)) + return; + extendedConfigCache.forEach(function (_a, key) { + var _b; + var extendedResult = _a.extendedResult; + if ((_b = extendedResult.extendedSourceFiles) === null || _b === void 0 ? void 0 : _b.some(function (extendedFile) { return toPath(extendedFile) === extendedConfigFilePath; })) { + cleanExtendedConfigCache(extendedConfigCache, key, toPath); + } + }); + } + ts.cleanExtendedConfigCache = cleanExtendedConfigCache; /** * Updates the existing missing file watches with the new set of missing files after new program is created */ @@ -105211,7 +108421,7 @@ var ts; ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; /* @internal */ function isIgnoredFileFromWildCardWatching(_a) { - var watchedDirPath = _a.watchedDirPath, fileOrDirectory = _a.fileOrDirectory, fileOrDirectoryPath = _a.fileOrDirectoryPath, configFileName = _a.configFileName, options = _a.options, program = _a.program, extraFileExtensions = _a.extraFileExtensions, currentDirectory = _a.currentDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, writeLog = _a.writeLog; + var watchedDirPath = _a.watchedDirPath, fileOrDirectory = _a.fileOrDirectory, fileOrDirectoryPath = _a.fileOrDirectoryPath, configFileName = _a.configFileName, options = _a.options, program = _a.program, extraFileExtensions = _a.extraFileExtensions, currentDirectory = _a.currentDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, writeLog = _a.writeLog, toPath = _a.toPath; var newPath = ts.removeIgnoredPath(fileOrDirectoryPath); if (!newPath) { writeLog("Project: " + configFileName + " Detected ignored path: " + fileOrDirectory); @@ -105247,7 +108457,8 @@ var ts; } // just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(fileOrDirectoryPath); - var realProgram = isBuilderProgram(program) ? program.getProgramOrUndefined() : program; + var realProgram = ts.isArray(program) ? undefined : isBuilderProgram(program) ? program.getProgramOrUndefined() : program; + var builderProgram = !realProgram && !ts.isArray(program) ? program : undefined; if (hasSourceFile((filePathWithoutExtension + ".ts" /* Ts */)) || hasSourceFile((filePathWithoutExtension + ".tsx" /* Tsx */))) { writeLog("Project: " + configFileName + " Detected output file: " + fileOrDirectory); @@ -105257,7 +108468,9 @@ var ts; function hasSourceFile(file) { return realProgram ? !!realProgram.getSourceFileByPath(file) : - program.getState().fileInfos.has(file); + builderProgram ? + builderProgram.getState().fileInfos.has(file) : + !!ts.find(program, function (rootFile) { return toPath(rootFile) === file; }); } } ts.isIgnoredFileFromWildCardWatching = isIgnoredFileFromWildCardWatching; @@ -105731,7 +108944,7 @@ var ts; var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; var lineContent = file.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); // trim from end - lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + lineContent = lineContent.replace(/\t/g, " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); @@ -105936,38 +109149,31 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, 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 === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames())) { + if (!program || (hasChangedAutomaticTypeDirectiveNames === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames())) return false; - } // If root file names don't match - if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) { + if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) return false; - } var seenResolvedRefs; // If project references don't match - if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + 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)) { + if (program.getSourceFiles().some(sourceFileNotUptoDate)) return false; - } // If any of the missing file paths are now created - if (program.getMissingFilePaths().some(fileExists)) { + if (program.getMissingFilePaths().some(fileExists)) return false; - } var currentOptions = program.getCompilerOptions(); // If the compilation settings do no match, then the program is not up-to-date - if (!ts.compareDataObjects(currentOptions, newOptions)) { + if (!ts.compareDataObjects(currentOptions, newOptions)) return false; - } // If everything matches but the text of config file is changed, // error locations can change for program options, so update the program - if (currentOptions.configFile && newOptions.configFile) { + if (currentOptions.configFile && newOptions.configFile) return currentOptions.configFile.text === newOptions.configFile.text; - } return true; function sourceFileNotUptoDate(sourceFile) { return !sourceFileVersionUptoDate(sourceFile) || @@ -105977,21 +109183,25 @@ var ts; return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName); } function projectReferenceUptoDate(oldRef, newRef, index) { - if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { - return false; - } - return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + return ts.projectReferenceIsEqualTo(oldRef, newRef) && + resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); } function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { if (oldResolvedRef) { - if (ts.contains(seenResolvedRefs, oldResolvedRef)) { - // Assume true + // Assume true + if (ts.contains(seenResolvedRefs, oldResolvedRef)) return true; - } - // If sourceFile for the oldResolvedRef existed, check the version for uptodate - if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + var refPath_1 = resolveProjectReferencePath(oldRef); + var newParsedCommandLine = getParsedCommandLine(refPath_1); + // Check if config file exists + if (!newParsedCommandLine) + return false; + // If change in source file + if (oldResolvedRef.commandLine.options.configFile !== newParsedCommandLine.options.configFile) + return false; + // check file names + if (!ts.arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newParsedCommandLine.fileNames)) return false; - } // Add to seen before checking the referenced paths of this config file (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); // If child project references are upto date, this project reference is uptodate @@ -106001,7 +109211,8 @@ var ts; } // In old program, not able to resolve project reference path, // so if config file doesnt exist, it is uptodate. - return !fileExists(resolveProjectReferencePath(oldRef)); + var refPath = resolveProjectReferencePath(oldRef); + return !getParsedCommandLine(refPath); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -106065,7 +109276,7 @@ var ts; var modulesWithElidedImports = new ts.Map(); // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. var sourceFilesFoundSearchingNodeModules = new ts.Map(); - ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeProgram"); var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHostLike(host); @@ -106080,6 +109291,7 @@ var ts; var hasEmitBlockingDiagnostics = new ts.Map(); var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; + var typeReferenceDirectiveResolutionCache; var actualResolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { @@ -106094,7 +109306,7 @@ var ts; }); }; } else { - moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options); + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName, options); var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } @@ -106103,7 +109315,8 @@ var ts; actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); }; } else { - var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; // TODO: GH#18217 actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } // Map from a stringified PackageId to the source file with that id. @@ -106141,15 +109354,15 @@ var ts; getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect, forEachResolvedProjectReference: forEachResolvedProjectReference }), onProgramCreateComplete = _d.onProgramCreateComplete, fileExists = _d.fileExists, directoryExists = _d.directoryExists; - ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`. var structureIsReused; - ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); structureIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (structureIsReused !== 2 /* Completely */) { processingDefaultLibFiles = []; processingOtherFiles = []; @@ -106187,13 +109400,13 @@ var ts; }); } } - ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); ts.forEach(rootNames, function (name, index) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.RootFile, index: index }); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { - ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile); @@ -106201,7 +109414,7 @@ var ts; for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i], { kind: ts.FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: (_b = resolutions[i]) === null || _b === void 0 ? void 0 : _b.packageId }); } - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // Do not process the default library if: // - The '--noLib' flag is used. @@ -106242,12 +109455,25 @@ var ts; host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); } } - oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference) { - if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { - host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + if (!host.getParsedCommandLine) { + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference) { + if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + } + }); + } + } + // Release commandlines that new program does not use + if (oldProgram && host.onReleaseParsedCommandLine) { + forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, parent, index) { + var oldReference = (parent === null || parent === void 0 ? void 0 : parent.commandLine.projectReferences[index]) || oldProgram.getProjectReferences()[index]; + var oldRefPath = resolveProjectReferencePath(oldReference); + if (!(projectReferenceRedirects === null || projectReferenceRedirects === void 0 ? void 0 : projectReferenceRedirects.has(toPath(oldRefPath)))) { + host.onReleaseParsedCommandLine(oldRefPath, oldResolvedRef, oldProgram.getCompilerOptions()); } }); } + typeReferenceDirectiveResolutionCache = undefined; // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; var program = { @@ -106276,7 +109502,6 @@ var ts; getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, - getTypeCatalog: function () { return getDiagnosticsProducingTypeChecker().getTypeCatalog(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getInstantiationCount: function () { return getDiagnosticsProducingTypeChecker().getInstantiationCount(); }, getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); }, @@ -106324,19 +109549,19 @@ var ts; verifyCompilerOptions(); ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return program; function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) { if (!moduleNames.length) return ts.emptyArray; var containingFileName = ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); var redirectedReference = getRedirectReferenceForResolution(containingFile); - ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveModule"); var result = actualResolveModuleNamesWorker(moduleNames, containingFileName, reusedNames, redirectedReference); ts.performance.mark("afterResolveModule"); ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile) { @@ -106344,12 +109569,12 @@ var ts; return []; var containingFileName = !ts.isString(containingFile) ? ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile; var redirectedReference = !ts.isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined; - ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveTypeReference"); var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference); ts.performance.mark("afterResolveTypeReference"); ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function getRedirectReferenceForResolution(file) { @@ -106442,13 +109667,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_14 = []; + var result_15 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_14.push(resolvedModule); + result_15.push(resolvedModule); } - return result_14; + return result_15; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -106559,7 +109784,9 @@ var ts; var newResolvedRef = parseProjectReferenceConfigFile(newRef); if (oldResolvedRef) { // Resolved project reference has gone missing or changed - return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + return !newResolvedRef || + newResolvedRef.sourceFile !== oldResolvedRef.sourceFile || + !ts.arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newResolvedRef.commandLine.fileNames); } else { // A previously-unresolved reference may be resolved now @@ -106821,7 +110048,7 @@ var ts; } function emitBuildInfo(writeFileCallback) { ts.Debug.assert(!ts.outFile(options)); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeEmit"); var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), /*targetSourceFile*/ undefined, @@ -106830,7 +110057,7 @@ var ts; /*onlyBuildInfo*/ true); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return emitResult; } function getResolvedProjectReferences() { @@ -106876,9 +110103,9 @@ var ts; return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) { - ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); var result = runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function isEmitBlocked(emitFileName) { @@ -107082,22 +110309,22 @@ var ts; // Return directly from the case if the given node doesnt want to visit each child // Otherwise break to visit each child switch (parent.kind) { - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?")); return "skip"; } // falls through - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: - case 249 /* VariableDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: + case 250 /* VariableDeclaration */: // type annotation if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files)); @@ -107105,58 +110332,58 @@ var ts; } } switch (node.kind) { - case 262 /* ImportClause */: + case 263 /* ImportClause */: if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type")); return "skip"; } break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type")); return "skip"; } break; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files)); return "skip"; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: var heritageClause = node; if (heritageClause.token === 116 /* ImplementsKeyword */) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: var interfaceKeyword = ts.tokenToString(117 /* InterfaceKeyword */); ts.Debug.assertIsDefined(interfaceKeyword); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword)); return "skip"; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var moduleKeyword = node.flags & 16 /* Namespace */ ? ts.tokenToString(140 /* NamespaceKeyword */) : ts.tokenToString(139 /* ModuleKeyword */); ts.Debug.assertIsDefined(moduleKeyword); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword)); return "skip"; - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files)); return "skip"; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(91 /* EnumKeyword */)); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword)); return "skip"; - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files)); return "skip"; - case 224 /* AsExpression */: + case 225 /* AsExpression */: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files)); return "skip"; - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } } @@ -107165,29 +110392,29 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning)); } switch (parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: // Check type parameters if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files)); return "skip"; } // falls through - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // Check modifiers if (nodes === parent.modifiers) { - checkModifiers(parent.modifiers, parent.kind === 232 /* VariableStatement */); + checkModifiers(parent.modifiers, parent.kind === 233 /* VariableStatement */); return "skip"; } break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // Check modifiers of property declaration if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { @@ -107199,19 +110426,19 @@ var ts; return "skip"; } break; - case 160 /* Parameter */: + case 161 /* Parameter */: // Check modifiers of parameter declaration if (nodes === parent.modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 223 /* ExpressionWithTypeArguments */: - case 274 /* JsxSelfClosingElement */: - case 275 /* JsxOpeningElement */: - case 205 /* TaggedTemplateExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 224 /* ExpressionWithTypeArguments */: + case 275 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 206 /* TaggedTemplateExpression */: // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files)); @@ -107236,6 +110463,7 @@ var ts; case 142 /* ReadonlyKeyword */: case 133 /* DeclareKeyword */: case 125 /* AbstractKeyword */: + case 156 /* OverrideKeyword */: diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind))); break; // These are all legal modifiers. @@ -107539,13 +110767,13 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { - ts.tracing.push("program" /* Program */, "findSourceFile", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "findSourceFile", { fileName: fileName, isDefaultLib: isDefaultLib || undefined, fileIncludeKind: ts.FileIncludeKind[reason.kind], }); var result = findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { @@ -107804,9 +111032,9 @@ var ts; } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { - ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { // If we already found this library as a primary reference - nothing to do @@ -107877,12 +111105,14 @@ var ts; return host.getCanonicalFileName(fileName); } function processImportedModules(file) { + var _a; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var resolutions = resolveModuleNamesReusingOldState(moduleNames, file); ts.Debug.assert(resolutions.length === moduleNames.length); + var optionsForFile = (useSourceOfProjectReferenceRedirect ? (_a = getRedirectReferenceForResolution(file)) === null || _a === void 0 ? void 0 : _a.commandLine.options : undefined) || options; for (var index = 0; index < moduleNames.length; index++) { var resolution = resolutions[index]; ts.setResolvedModule(file, moduleNames[index], resolution); @@ -107905,11 +111135,11 @@ var ts; // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') // This may still end up being an untyped module -- the file won't be included but imports will be allowed. var shouldAddFile = resolvedFileName - && !getResolutionDiagnostic(options, resolution) - && !options.noResolve + && !getResolutionDiagnostic(optionsForFile, resolution) + && !optionsForFile.noResolve && index < file.imports.length && !elideImport - && !(isJsFile && !ts.getAllowJSCompilerOption(options)) + && !(isJsFile && !ts.getAllowJSCompilerOption(optionsForFile)) && (ts.isInJSFile(file.imports[index]) || !(file.imports[index].flags & 4194304 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); @@ -108112,6 +111342,9 @@ var ts; if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } + if (options.preserveConstEnums === false) { + createDiagnosticForOptionName(ts.Diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled, "preserveConstEnums", "isolatedModules"); + } var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); @@ -108142,9 +111375,10 @@ var ts; 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 + // there has to be common source directory if user specified --outdir || --rootDir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted if (options.outDir || // there is --outDir specified + options.rootDir || // there is --rootDir specified options.sourceRoot || // there is --sourceRoot specified options.mapRoot) { // there is --mapRoot specified // Precalculate and cache the common source directory @@ -108641,7 +111875,7 @@ var ts; } function handleDirectoryCouldBeSymlink(directory) { var _a; - if (!host.getResolvedProjectReferences()) + if (!host.getResolvedProjectReferences() || ts.containsIgnoredPath(directory)) return; // Because we already watch node_modules, handle symlinks in there if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart)) @@ -108658,7 +111892,7 @@ var ts; symlinkCache.setSymlinkedDirectory(directoryPath, false); return; } - symlinkCache.setSymlinkedDirectory(directoryPath, { + symlinkCache.setSymlinkedDirectory(directory, { real: ts.ensureTrailingDirectorySeparator(real), realPath: realPath }); @@ -108934,12 +112168,15 @@ var ts; // From ambient modules for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { var ambientModule = _g[_f]; - if (ambientModule.declarations.length > 1) { + if (ambientModule.declarations && ambientModule.declarations.length > 1) { addReferenceFromAmbientModule(ambientModule); } } return referencedFiles; function addReferenceFromAmbientModule(symbol) { + if (!symbol.declarations) { + return; + } // Add any file other than our own as reference for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; @@ -108964,7 +112201,7 @@ var ts; /** * Creates the state of file references and signature for the new program from oldState if it is safe */ - function create(newProgram, getCanonicalFileName, oldState) { + function create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { var fileInfos = new ts.Map(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? new ts.Map() : undefined; var exportedModulesMap = referencedMap ? new ts.Map() : undefined; @@ -108990,13 +112227,14 @@ var ts; } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) }); + fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined }); } return { fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState }; } BuilderState.create = create; @@ -109018,6 +112256,7 @@ var ts; referencedMap: state.referencedMap && new ts.Map(state.referencedMap), exportedModulesMap: state.exportedModulesMap && new ts.Map(state.exportedModulesMap), hasCalledUpdateShapeSignature: new ts.Set(state.hasCalledUpdateShapeSignature), + useFileVersionAsSignature: state.useFileVersionAsSignature, }; } BuilderState.clone = clone; @@ -109073,23 +112312,12 @@ var ts; return ts.Debug.fail(); var prevSignature = info.signature; var latestSignature; - if (sourceFile.isDeclarationFile) { - latestSignature = sourceFile.version; - if (exportedModulesMapCache && latestSignature !== prevSignature) { - // All the references in this file are exported - var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined; - exportedModulesMapCache.set(sourceFile.resolvedPath, references || false); - } - } - else { + if (!sourceFile.isDeclarationFile && !state.useFileVersionAsSignature) { var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken, /*customTransformers*/ undefined, /*forceDtsEmit*/ true); - var firstDts_1 = emitOutput_1.outputFiles && - programOfThisState.getCompilerOptions().declarationMap ? - emitOutput_1.outputFiles.length > 1 ? emitOutput_1.outputFiles[1] : undefined : - emitOutput_1.outputFiles.length > 0 ? emitOutput_1.outputFiles[0] : undefined; + var firstDts_1 = ts.firstOrUndefined(emitOutput_1.outputFiles); if (firstDts_1) { ts.Debug.assert(ts.fileExtensionIs(firstDts_1.name, ".d.ts" /* Dts */), "File extension for signature expected to be dts", function () { return "Found: " + ts.getAnyExtensionFromPath(firstDts_1.name) + " for " + firstDts_1.name + ":: All output files: " + JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; })); }); latestSignature = (computeHash || ts.generateDjb2Hash)(firstDts_1.text); @@ -109097,12 +112325,18 @@ var ts; updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache); } } - else { - latestSignature = prevSignature; // TODO: GH#18217 + } + // Default is to use file version as signature + if (latestSignature === undefined) { + latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + // All the references in this file are exported + var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined; + exportedModulesMapCache.set(sourceFile.resolvedPath, references || false); } } cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature); - return !prevSignature || latestSignature !== prevSignature; + return latestSignature !== prevSignature; } BuilderState.updateShapeSignature = updateShapeSignature; /** @@ -109222,7 +112456,7 @@ var ts; */ function isFileAffectingGlobalScope(sourceFile) { return containsGlobalScopeAugmentation(sourceFile) || - !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + !ts.isExternalOrCommonJsModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); } /** * Gets all files of the program excluding the default library file @@ -109310,8 +112544,8 @@ var ts; /** * Create the state so that we can iterate on changedFiles/affected files */ - function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { - var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); state.compilerOptions = compilerOptions; @@ -109549,6 +112783,7 @@ var ts; * This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change */ function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash) { + var _a; removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath); // If affected files is everything except default library, then nothing more to do if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) { @@ -109562,8 +112797,15 @@ var ts; removeSemanticDiagnosticsOf(state, f.resolvedPath); }); } + // When a change affects the global scope, all files are considered to be affected without updating their signature + // That means when affected file is handled, its signature can be out of date + // To avoid this, ensure that we update the signature for any affected file in this scenario. + ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap); return; } + else { + ts.Debug.assert(state.hasCalledUpdateShapeSignature.has(affectedFile.resolvedPath) || ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.has(affectedFile.resolvedPath)), "Signature not updated for affected file: " + affectedFile.fileName); + } if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) { forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); }); } @@ -109775,83 +113017,116 @@ var ts; return undefined; var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory(); var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); - var fileInfos = {}; - state.fileInfos.forEach(function (value, key) { + var fileNames = []; + var fileNameToFileId = new ts.Map(); + var fileIdsList; + var fileNamesToFileIdListId; + var fileInfos = ts.arrayFrom(state.fileInfos.entries(), function (_a) { + var key = _a[0], value = _a[1]; + // Ensure fileId + var fileId = toFileId(key); + ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope }; + var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + return value.version === actualSignature ? + value.affectsGlobalScope ? + { version: value.version, signature: undefined, affectsGlobalScope: true } : + value.version : + actualSignature !== undefined ? + signature === undefined ? + value : + { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope } : + { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope }; }); - var result = { - fileInfos: fileInfos, - options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath) - }; + var referencedMap; if (state.referencedMap) { - var referencedMap = {}; - for (var _i = 0, _a = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { - var key = _a[_i]; - referencedMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.referencedMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); - } - result.referencedMap = referencedMap; + referencedMap = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive).map(function (key) { return [ + toFileId(key), + toFileIdListId(state.referencedMap.get(key)) + ]; }); } + var exportedModulesMap; if (state.exportedModulesMap) { - var exportedModulesMap = {}; - for (var _b = 0, _c = ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) { - var key = _c[_b]; + exportedModulesMap = ts.mapDefined(ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive), function (key) { var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key); // Not in temporary cache, use existing value if (newValue === undefined) - exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.exportedModulesMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); + return [toFileId(key), toFileIdListId(state.exportedModulesMap.get(key))]; // Value in cache and has updated value map, use that else if (newValue) - exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); - } - result.exportedModulesMap = exportedModulesMap; + return [toFileId(key), toFileIdListId(newValue)]; + }); } + var semanticDiagnosticsPerFile; if (state.semanticDiagnosticsPerFile) { - var semanticDiagnosticsPerFile = []; - for (var _d = 0, _e = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) { - var key = _e[_d]; + for (var _i = 0, _a = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var key = _a[_i]; var value = state.semanticDiagnosticsPerFile.get(key); - semanticDiagnosticsPerFile.push(value.length ? + (semanticDiagnosticsPerFile || (semanticDiagnosticsPerFile = [])).push(value.length ? [ - relativeToBuildInfo(key), + toFileId(key), state.hasReusableDiagnostic ? value : convertToReusableDiagnostics(value, relativeToBuildInfo) ] : - relativeToBuildInfo(key)); + toFileId(key)); } - result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile; } + var affectedFilesPendingEmit; if (state.affectedFilesPendingEmit) { - var affectedFilesPendingEmit = []; var seenFiles = new ts.Set(); - for (var _f = 0, _g = state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(ts.compareStringsCaseSensitive); _f < _g.length; _f++) { - var path = _g[_f]; + for (var _b = 0, _c = state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) { + var path = _c[_b]; if (ts.tryAddToSet(seenFiles, path)) { - affectedFilesPendingEmit.push([relativeToBuildInfo(path), state.affectedFilesPendingEmitKind.get(path)]); + (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push([toFileId(path), state.affectedFilesPendingEmitKind.get(path)]); } } - result.affectedFilesPendingEmit = affectedFilesPendingEmit; } - return result; + return { + fileNames: fileNames, + fileInfos: fileInfos, + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + fileIdsList: fileIdsList, + referencedMap: referencedMap, + exportedModulesMap: exportedModulesMap, + semanticDiagnosticsPerFile: semanticDiagnosticsPerFile, + affectedFilesPendingEmit: affectedFilesPendingEmit, + }; function relativeToBuildInfoEnsuringAbsolutePath(path) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory)); } function relativeToBuildInfo(path) { return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName)); } + function toFileId(path) { + var fileId = fileNameToFileId.get(path); + if (fileId === undefined) { + fileNames.push(relativeToBuildInfo(path)); + fileNameToFileId.set(path, fileId = fileNames.length); + } + return fileId; + } + function toFileIdListId(set) { + var fileIds = ts.arrayFrom(set.keys(), toFileId).sort(ts.compareValues); + var key = fileIds.join(); + var fileIdListId = fileNamesToFileIdListId === null || fileNamesToFileIdListId === void 0 ? void 0 : fileNamesToFileIdListId.get(key); + if (fileIdListId === undefined) { + (fileIdsList || (fileIdsList = [])).push(fileIds); + (fileNamesToFileIdListId || (fileNamesToFileIdListId = new ts.Map())).set(key, fileIdListId = fileIdsList.length); + } + return fileIdListId; + } } - function convertToReusableCompilerOptions(options, relativeToBuildInfo) { - var result = {}; + function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { + var result; var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo); + for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var name = _a[_i]; + var optionInfo = optionsNameMap.get(name.toLowerCase()); + if ((optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || name === "skipLibCheck" || name === "skipDefaultLibCheck") { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); } } - if (result.configFilePath) { - result.configFilePath = relativeToBuildInfo(result.configFilePath); - } return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { @@ -109943,7 +113218,7 @@ var ts; * Computing hash to for signature verification */ var computeHash = ts.maybeBind(host, host.createHash); - var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState, host.disableUseFileVersionAsSignature); var backupState; newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); }; // To ensure that we arent storing any references to old program or new program without state @@ -110167,37 +113442,31 @@ var ts; state.affectedFilesPendingEmitIndex = 0; } } - function getMapOfReferencedSet(mapLike, toPath) { - if (!mapLike) - return undefined; - var map = new ts.Map(); - // Copies keys/values from template. Note that for..in will not throw if - // template is undefined, and instead will just exit the loop. - for (var key in mapLike) { - if (ts.hasProperty(mapLike, key)) { - map.set(toPath(key), new ts.Set(mapLike[key].map(toPath))); - } - } - return map; + function toBuilderStateFileInfo(fileInfo) { + return ts.isString(fileInfo) ? + { version: fileInfo, signature: fileInfo, affectsGlobalScope: undefined } : + ts.isString(fileInfo.signature) ? + fileInfo : + { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope }; } + ts.toBuilderStateFileInfo = toBuilderStateFileInfo; function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { + var _a; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var filePaths = program.fileNames.map(toPath); + var filePathsSetList = (_a = program.fileIdsList) === null || _a === void 0 ? void 0 : _a.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); var fileInfos = new ts.Map(); - for (var key in program.fileInfos) { - if (ts.hasProperty(program.fileInfos, key)) { - fileInfos.set(toPath(key), program.fileInfos[key]); - } - } + program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); var state = { fileInfos: fileInfos, - compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), - referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), - exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), - semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + referencedMap: toMapOfReferencedSet(program.referencedMap), + exportedModulesMap: toMapOfReferencedSet(program.exportedModulesMap), + semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), hasReusableDiagnostic: true, - affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }), - affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }, function (value) { return value[1]; }), + affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), + affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, }; return { @@ -110230,6 +113499,15 @@ var ts; function toAbsolutePath(path) { return ts.getNormalizedAbsolutePath(path, buildInfoDirectory); } + function toFilePath(fileId) { + return filePaths[fileId - 1]; + } + function toFilePathsSet(fileIdsListId) { + return filePathsSetList[fileIdsListId - 1]; + } + function toMapOfReferencedSet(referenceMap) { + return referenceMap && ts.arrayToMap(referenceMap, function (value) { return toFilePath(value[0]); }, function (value) { return toFilePathsSet(value[1]); }); + } } ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { @@ -110342,9 +113620,9 @@ var ts; var resolutionsWithFailedLookups = []; var resolvedFileToResolution = ts.createMultiMap(); var hasChangedAutomaticTypeDirectiveNames = false; - var failedLookupChecks = []; - var startsWithPathChecks = []; - var isInDirectoryChecks = []; + var failedLookupChecks; + var startsWithPathChecks; + var isInDirectoryChecks; var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. @@ -110353,9 +113631,12 @@ var ts; var resolvedModuleNames = new ts.Map(); var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); - var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var moduleResolutionCache = ts.createModuleResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, perDirectoryResolvedModuleNames, nonRelativeModuleNameCache); var resolvedTypeReferenceDirectives = new ts.Map(); var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); + var typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, moduleResolutionCache.getPackageJsonInfoCache(), perDirectoryResolvedTypeReferenceDirectives); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -110387,6 +113668,7 @@ var ts; invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, createHasInvalidatedResolution: createHasInvalidatedResolution, + isFileWithInvalidatedNonRelativeUnresolvedImports: isFileWithInvalidatedNonRelativeUnresolvedImports, updateTypeRootsWatch: updateTypeRootsWatch, closeTypeRootsWatch: closeTypeRootsWatch, clear: clear @@ -110412,9 +113694,9 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) clearPerDirectoryResolutions(); @@ -110450,9 +113732,8 @@ var ts; isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { - perDirectoryResolvedModuleNames.clear(); - nonRelativeModuleNameCache.clear(); - perDirectoryResolvedTypeReferenceDirectives.clear(); + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } @@ -110479,7 +113760,7 @@ var ts; if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results - var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; if (resolvedModule) { // Modify existing resolution so its saved in the directory cache as well primaryResult.resolvedModule = resolvedModule; @@ -110490,6 +113771,9 @@ var ts; // Default return the result from the first pass return primaryResult; } + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + return ts.resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache); + } function resolveNamesWithLocalCache(_a) { var _b; var names = _a.names, containingFile = _a.containingFile, redirectedReference = _a.redirectedReference, cache = _a.cache, perDirectoryCacheWithRedirects = _a.perDirectoryCacheWithRedirects, loader = _a.loader, getResolutionWithResolvedFileName = _a.getResolutionWithResolvedFileName, shouldRetryResolution = _a.shouldRetryResolution, reusedNames = _a.reusedNames, logChanges = _a.logChanges; @@ -110577,7 +113861,7 @@ var ts; redirectedReference: redirectedReference, cache: resolvedTypeReferenceDirectives, perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives, - loader: ts.resolveTypeReferenceDirective, + loader: resolveTypeReferenceDirective, getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective, shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, }); @@ -110852,7 +114136,7 @@ var ts; if (isCreatingWatchedDirectory) { // Watching directory is created // Invalidate any resolution has failed lookup in this directory - isInDirectoryChecks.push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); } else { // If something to do with folder/file starting with "." in node_modules folder, skip it @@ -110870,8 +114154,8 @@ var ts; if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory - failedLookupChecks.push(fileOrDirectoryPath); - startsWithPathChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { @@ -110882,27 +114166,33 @@ var ts; return false; } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created - failedLookupChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + // If the invalidated file is from a node_modules package, invalidate everything else + // in the package since we might not get notifications for other files in the package. + // This hardens our logic against unreliable file watchers. + var packagePath = ts.parseNodeModuleFromPath(fileOrDirectoryPath); + if (packagePath) + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks.length && !startsWithPathChecks.length && !isInDirectoryChecks.length) { + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { return false; } var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { return resolution.failedLookupLocations.some(function (location) { var locationPath = resolutionHost.toPath(location); return ts.contains(failedLookupChecks, locationPath) || - startsWithPathChecks.some(function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath); }) || - isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); }); + ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || + (isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); })); }); } function closeTypeRootsWatch() { @@ -111053,6 +114343,9 @@ var ts; return [ambient]; var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); + if (!moduleSourceFile) { + return []; + } var modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host); var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); var existingSpecifier = ts.forEach(modulePaths, function (modulePath) { return ts.forEach(host.getFileIncludeReasons().get(ts.toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)), function (reason) { @@ -111123,7 +114416,7 @@ var ts; if (!baseUrl && !paths || relativePreference === 0 /* Relative */) { return relativePath; } - var baseDirectory = ts.getPathsBasePath(compilerOptions, host) || baseUrl; + var baseDirectory = ts.getNormalizedAbsolutePath(ts.getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory()); var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName); if (!relativeToBaseUrl) { return relativePath; @@ -111138,7 +114431,9 @@ var ts; return nonRelative; } if (relativePreference === 3 /* ExternalNonRelative */) { - var projectDirectory = host.getCurrentDirectory(); + var projectDirectory = compilerOptions.configFilePath ? + ts.toPath(ts.getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) : + info.getCanonicalFileName(host.getCurrentDirectory()); var modulePath = ts.toPath(moduleFileName, projectDirectory, getCanonicalFileName); var sourceIsInternal = ts.startsWith(sourceDirectory, projectDirectory); var targetIsInternal = ts.startsWith(modulePath, projectDirectory); @@ -111190,12 +114485,8 @@ var ts; return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined; }) || false; } - function numberOfDirectorySeparators(str) { - var match = str.match(/\//g); - return match ? match.length : 0; - } function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) { - return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareValues(numberOfDirectorySeparators(a.path), numberOfDirectorySeparators(b.path)); + return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareNumberOfDirectorySeparators(a.path, b.path); } function getNearestAncestorDirectoryWithPackageJson(host, fileName) { if (host.getNearestAncestorDirectoryWithPackageJson) { @@ -111209,40 +114500,49 @@ var ts; var getCanonicalFileName = ts.hostGetCanonicalFileName(host); var cwd = host.getCurrentDirectory(); var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined; - var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray; + var importedPath = ts.toPath(importedFileName, cwd, getCanonicalFileName); + var redirects = host.redirectTargetsMap.get(importedPath) || ts.emptyArray; var importedFileNames = __spreadArray(__spreadArray(__spreadArray([], (referenceRedirect ? [referenceRedirect] : ts.emptyArray)), [importedFileName]), redirects); var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + var shouldFilterIgnoredPaths = !ts.every(targets, ts.containsIgnoredPath); if (!preferSymlinks) { - var result_15 = ts.forEach(targets, function (p) { return cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + // Symlinks inside ignored paths are already filtered out of the symlink cache, + // so we only need to remove them from the realpath filenames. + var result_16 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_16) + return result_16; } var links = host.getSymlinkCache ? host.getSymlinkCache() : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd); - var symlinkedDirectories = links.getSymlinkedDirectories(); - var useCaseSensitiveFileNames = !host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames(); - var result = symlinkedDirectories && ts.forEachEntry(symlinkedDirectories, function (resolved, path) { - if (resolved === false) - return undefined; - if (ts.startsWithDirectory(importingFileName, resolved.realPath, getCanonicalFileName)) { - return undefined; // Don't want to a package to globally import from itself + var symlinkedDirectories = links.getSymlinkedDirectoriesByRealpath(); + var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); + var result = symlinkedDirectories && ts.forEachAncestorDirectory(ts.getDirectoryPath(fullImportedFileName), function (realPathDirectory) { + var symlinkDirectories = symlinkedDirectories.get(ts.ensureTrailingDirectorySeparator(ts.toPath(realPathDirectory, cwd, getCanonicalFileName))); + if (!symlinkDirectories) + return undefined; // Continue to ancestor directory + // Don't want to a package to globally import from itself (importNameCodeFix_symlink_own_package.ts) + if (ts.startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) { + return false; // Stop search, each ancestor directory will also hit this condition } return ts.forEach(targets, function (target) { - if (!ts.containsPath(resolved.real, target, !useCaseSensitiveFileNames)) { + if (!ts.startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) { return; } - var relative = ts.getRelativePathFromDirectory(resolved.real, target, getCanonicalFileName); - var option = ts.resolvePath(path, relative); - if (!host.fileExists || host.fileExists(option)) { - var result_16 = cb(option, target === referenceRedirect); - if (result_16) - return result_16; + var relative = ts.getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName); + for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { + var symlinkDirectory = symlinkDirectories_1[_i]; + var option = ts.resolvePath(symlinkDirectory, relative); + var result_17 = cb(option, target === referenceRedirect); + shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths + if (result_17) + return result_17; } }); }); - return result || - (preferSymlinks ? ts.forEach(targets, function (p) { return cb(p, p === referenceRedirect); }) : undefined); + return result || (preferSymlinks + ? ts.forEach(targets, function (p) { return shouldFilterIgnoredPaths && ts.containsIgnoredPath(p) ? undefined : cb(p, p === referenceRedirect); }) + : undefined); } moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule; /** @@ -111250,8 +114550,14 @@ var ts; * Symlinks will be returned first so they are preferred over the real path. */ function getAllModulePaths(importingFileName, importedFileName, host) { - var cwd = host.getCurrentDirectory(); + var _a; + var cache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + if (cache) { + var cached = cache.get(importingFileName, ts.toPath(importedFileName, host.getCurrentDirectory(), getCanonicalFileName)); + if (typeof cached === "object") + return cached; + } var allFileNames = new ts.Map(); var importedFileFromNodeModules = false; forEachFileNameOfModule(importingFileName, importedFileName, host, @@ -111263,7 +114569,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_24 = function (directory) { + var _loop_26 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -111286,10 +114592,10 @@ var ts; out_directory_1 = directory; }; var out_directory_1; - for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_7 = _loop_24(directory); + for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { + var state_9 = _loop_26(directory); directory = out_directory_1; - if (state_7 === "break") + if (state_9 === "break") break; } if (allFileNames.size) { @@ -111298,10 +114604,14 @@ var ts; remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators); sortedPaths.push.apply(sortedPaths, remainingPaths); } + if (cache) { + cache.set(importingFileName, ts.toPath(importedFileName, host.getCurrentDirectory(), getCanonicalFileName), sortedPaths); + } return sortedPaths; } function tryGetModuleNameFromAmbientModule(moduleSymbol, checker) { - var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); + var _a; + var decl = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { return decl.name.text; } @@ -111357,7 +114667,7 @@ var ts; ts.startsWith(relativeToBaseUrl, prefix) && ts.endsWith(relativeToBaseUrl, suffix) || !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); return key.replace("*", matchedStar); } } @@ -111661,10 +114971,10 @@ var ts; } ts.createWatchStatusReporter = createWatchStatusReporter; /** Parses config file using System interface */ - function parseConfigFileWithSystem(configFileName, optionsToExtend, watchOptionsToExtend, system, reportDiagnostic) { + function parseConfigFileWithSystem(configFileName, optionsToExtend, extendedConfigCache, watchOptionsToExtend, system, reportDiagnostic) { var host = system; host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; - var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, /*extendedConfigCache*/ undefined, watchOptionsToExtend); + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend); host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; } @@ -111932,7 +115242,10 @@ var ts; MissingFile: "Missing file", WildcardDirectory: "Wild card directory", FailedLookupLocations: "Failed Lookup Locations", - TypeRoots: "Type roots" + TypeRoots: "Type roots", + ConfigFileOfReferencedProject: "Config file of referened project", + ExtendedConfigOfReferencedProject: "Extended config file of referenced project", + WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project", }; function createWatchFactory(host, options) { var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; @@ -111979,6 +115292,7 @@ var ts; getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }), createHash: ts.maybeBind(host, host.createHash), readDirectory: ts.maybeBind(host, host.readDirectory), + disableUseFileVersionAsSignature: host.disableUseFileVersionAsSignature, }; function writeFile(fileName, text, writeByteOrderMark, onError) { try { @@ -112036,7 +115350,8 @@ var ts; createDirectory: function (path) { return system.createDirectory(path); }, writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, createHash: ts.maybeBind(system, system.createHash), - createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram + createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, + disableUseFileVersionAsSignature: system.disableUseFileVersionAsSignature, }; } ts.createProgramHost = createProgramHost; @@ -112124,6 +115439,7 @@ var ts; if (system === void 0) { system = ts.sys; } var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system); host.createHash = ts.maybeBind(system, system.createHash); + host.disableUseFileVersionAsSignature = system.disableUseFileVersionAsSignature; ts.setGetSourceFileAsHashVersioned(host, system); ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); }); return host; @@ -112167,11 +115483,13 @@ var ts; function createWatchProgram(host) { var builderProgram; var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc - var extendedConfigFilesMap; // Map of file watchers for the extended config files var missingFilesMap; // Map of file watchers for the missing files var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file var timerToUpdateProgram; // timer callback to recompile the program var timerToInvalidateFailedLookupResolutions; // timer callback to invalidate resolutions for changes in failed lookup locations + var parsedConfigs; // Parsed commandline and watching cached for referenced projects + var sharedExtendedConfigFileWatchers; // Map of file watchers for extended files, shared between different referenced projects + var extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info var missingFilePathsRequestedForRelease; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations @@ -112221,6 +115539,7 @@ var ts; compilerHost.getNewLine = function () { return newLine; }; compilerHost.fileExists = fileExists; compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile; + compilerHost.onReleaseParsedCommandLine = onReleaseParsedCommandLine; // Members for ResolutionCacheHost compilerHost.toPath = toPath; compilerHost.getCompilationSettings = function () { return compilerOptions; }; @@ -112234,6 +115553,7 @@ var ts; compilerHost.fileIsOpen = ts.returnFalse; compilerHost.getCurrentProgram = getCurrentProgram; compilerHost.writeLog = writeLog; + compilerHost.getParsedCommandLine = getParsedCommandLine; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : @@ -112264,7 +115584,8 @@ var ts; // Update the wild card directory watch watchConfigFileWildCardDirectories(); // Update extended config file watch - watchExtendedConfigFiles(); + if (configFileName) + updateExtendedConfigFilesWatches(toPath(configFileName), compilerOptions, watchOptions, ts.WatchType.ExtendedConfigFile); return configFileName ? { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } : { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close }; @@ -112281,9 +115602,11 @@ var ts; configFileWatcher.close(); configFileWatcher = undefined; } - if (extendedConfigFilesMap) { - ts.clearMap(extendedConfigFilesMap, ts.closeFileWatcher); - extendedConfigFilesMap = undefined; + extendedConfigCache === null || extendedConfigCache === void 0 ? void 0 : extendedConfigCache.clear(); + extendedConfigCache = undefined; + if (sharedExtendedConfigFileWatchers) { + ts.clearMap(sharedExtendedConfigFileWatchers, ts.closeFileWatcherOf); + sharedExtendedConfigFileWatchers = undefined; } if (watchedWildcardDirectories) { ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); @@ -112293,6 +115616,17 @@ var ts; ts.clearMap(missingFilesMap, ts.closeFileWatcher); missingFilesMap = undefined; } + if (parsedConfigs) { + ts.clearMap(parsedConfigs, function (config) { + var _a; + (_a = config.watcher) === null || _a === void 0 ? void 0 : _a.close(); + config.watcher = undefined; + if (config.watchedDirectories) + ts.clearMap(config.watchedDirectories, ts.closeFileWatcherOf); + config.watchedDirectories = undefined; + }); + parsedConfigs = undefined; + } } function getCurrentBuilderProgram() { return builderProgram; @@ -112312,7 +115646,7 @@ 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, projectReferences)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; @@ -112331,6 +115665,8 @@ var ts; writeLog("CreatingProgramWith::"); writeLog(" roots: " + JSON.stringify(rootFileNames)); writeLog(" options: " + JSON.stringify(compilerOptions)); + if (projectReferences) + writeLog(" projectReferences: " + JSON.stringify(projectReferences)); var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; @@ -112553,10 +115889,10 @@ var ts; // Update the wild card directory watch watchConfigFileWildCardDirectories(); // Update extended config file watch - watchExtendedConfigFiles(); + updateExtendedConfigFilesWatches(toPath(configFileName), compilerOptions, watchOptions, ts.WatchType.ExtendedConfigFile); } function parseConfigFile() { - setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217 + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, extendedConfigCache || (extendedConfigCache = new ts.Map()), watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217 } function setConfigFileParsingResult(configFileParseResult) { rootFileNames = configFileParseResult.fileNames; @@ -112568,6 +115904,56 @@ var ts; canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInputFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } + function getParsedCommandLine(configFileName) { + var configPath = toPath(configFileName); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath); + if (config) { + if (!config.reloadLevel) + return config.parsedCommandLine; + // With host implementing getParsedCommandLine we cant just update file names + if (config.parsedCommandLine && config.reloadLevel === ts.ConfigFileProgramReloadLevel.Partial && !host.getParsedCommandLine) { + writeLog("Reloading new file names and options"); + var fileNames = ts.getFileNamesFromConfigSpecs(config.parsedCommandLine.options.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost); + config.parsedCommandLine = __assign(__assign({}, config.parsedCommandLine), { fileNames: fileNames }); + config.reloadLevel = undefined; + return config.parsedCommandLine; + } + } + writeLog("Loading config file: " + configFileName); + var parsedCommandLine = host.getParsedCommandLine ? + host.getParsedCommandLine(configFileName) : + getParsedCommandLineFromConfigFileHost(configFileName); + if (config) { + config.parsedCommandLine = parsedCommandLine; + config.reloadLevel = undefined; + } + else { + (parsedConfigs || (parsedConfigs = new ts.Map())).set(configPath, config = { parsedCommandLine: parsedCommandLine }); + } + watchReferencedProject(configFileName, configPath, config); + return parsedCommandLine; + } + function getParsedCommandLineFromConfigFileHost(configFileName) { + // Ignore the file absent errors + var onUnRecoverableConfigFileDiagnostic = parseConfigFileHost.onUnRecoverableConfigFileDiagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + var parsedCommandLine = ts.getParsedCommandLineOfConfigFile(configFileName, + /*optionsToExtend*/ undefined, parseConfigFileHost, extendedConfigCache || (extendedConfigCache = new ts.Map()), watchOptionsToExtend); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = onUnRecoverableConfigFileDiagnostic; + return parsedCommandLine; + } + function onReleaseParsedCommandLine(fileName) { + var _a; + var path = toPath(fileName); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(path); + if (!config) + return; + parsedConfigs.delete(path); + if (config.watchedDirectories) + ts.clearMap(config.watchedDirectories, ts.closeFileWatcherOf); + (_a = config.watcher) === null || _a === void 0 ? void 0 : _a.close(); + ts.clearSharedExtendedConfigFileWatcher(path, sharedExtendedConfigFileWatchers); + } function watchFilePath(path, file, callback, pollingInterval, options, watchType) { return watchFile(file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options, watchType); } @@ -112577,7 +115963,6 @@ var ts; if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) { resolutionCache.invalidateResolutionOfFile(path); } - resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); nextSourceFileVersion(path); // Update the program scheduleProgramUpdate(); @@ -112588,7 +115973,10 @@ var ts; } } function watchMissingFilePath(missingFilePath) { - return watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); + // If watching missing referenced config file, we are already watching it so no need for separate watcher + return (parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.has(missingFilePath)) ? + ts.noopFileWatcher : + watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); @@ -112625,10 +116013,11 @@ var ts; configFileName: configFileName, extraFileExtensions: extraFileExtensions, options: compilerOptions, - program: getCurrentBuilderProgram(), + program: getCurrentBuilderProgram() || rootFileNames, currentDirectory: currentDirectory, useCaseSensitiveFileNames: useCaseSensitiveFileNames, - writeLog: writeLog + writeLog: writeLog, + toPath: toPath, })) return; // Reload is pending, do the reload @@ -112639,18 +116028,87 @@ var ts; } }, flags, watchOptions, ts.WatchType.WildcardDirectory); } - function watchExtendedConfigFiles() { - var _a; - // Update the extended config files watcher - ts.mutateMap(extendedConfigFilesMap || (extendedConfigFilesMap = new ts.Map()), ts.arrayToMap(((_a = compilerOptions.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath), { - // Watch the extended config files - createNewValue: watchExtendedConfigFile, - // Config files that are no longer extended should no longer be watched. - onDeleteValue: ts.closeFileWatcher - }); + function updateExtendedConfigFilesWatches(forProjectPath, options, watchOptions, watchType) { + ts.updateSharedExtendedConfigFileWatcher(forProjectPath, options, sharedExtendedConfigFileWatchers || (sharedExtendedConfigFileWatchers = new ts.Map()), function (extendedConfigFileName, extendedConfigFilePath) { return watchFile(extendedConfigFileName, function (_fileName, eventKind) { + var _a; + updateCachedSystemWithFile(extendedConfigFileName, extendedConfigFilePath, eventKind); + // Update extended config cache + if (extendedConfigCache) + ts.cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath); + // Update projects + var projects = (_a = sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects; + // If there are no referenced projects this extended config file watcher depend on ignore + if (!(projects === null || projects === void 0 ? void 0 : projects.size)) + return; + projects.forEach(function (projectPath) { + if (toPath(configFileName) === projectPath) { + // If this is the config file of the project, reload completely + reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + } + else { + // Reload config for the referenced projects and remove the resolutions from referenced projects since the config file changed + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(projectPath); + if (config) + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(projectPath); + } + scheduleProgramUpdate(); + }); + }, ts.PollingInterval.High, watchOptions, watchType); }, toPath); } - function watchExtendedConfigFile(extendedConfigFile) { - return watchFile(extendedConfigFile, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ExtendedConfigFile); + function watchReferencedProject(configFileName, configPath, commandLine) { + var _a, _b, _c, _d, _e; + // Watch file + commandLine.watcher || (commandLine.watcher = watchFile(configFileName, function (_fileName, eventKind) { + updateCachedSystemWithFile(configFileName, configPath, eventKind); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath); + if (config) + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(configPath); + scheduleProgramUpdate(); + }, ts.PollingInterval.High, ((_a = commandLine.parsedCommandLine) === null || _a === void 0 ? void 0 : _a.watchOptions) || watchOptions, ts.WatchType.ConfigFileOfReferencedProject)); + // Watch Wild card + if ((_b = commandLine.parsedCommandLine) === null || _b === void 0 ? void 0 : _b.wildcardDirectories) { + ts.updateWatchingWildcardDirectories(commandLine.watchedDirectories || (commandLine.watchedDirectories = new ts.Map()), new ts.Map(ts.getEntries((_c = commandLine.parsedCommandLine) === null || _c === void 0 ? void 0 : _c.wildcardDirectories)), function (directory, flags) { + var _a; + return watchDirectory(directory, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + // Since the file existence changed, update the sourceFiles cache + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + nextSourceFileVersion(fileOrDirectoryPath); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath); + if (!(config === null || config === void 0 ? void 0 : config.parsedCommandLine)) + return; + if (ts.isIgnoredFileFromWildCardWatching({ + watchedDirPath: toPath(directory), + fileOrDirectory: fileOrDirectory, + fileOrDirectoryPath: fileOrDirectoryPath, + configFileName: configFileName, + options: config.parsedCommandLine.options, + program: config.parsedCommandLine.fileNames, + currentDirectory: currentDirectory, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + writeLog: writeLog, + toPath: toPath, + })) + return; + // Reload is pending, do the reload + if (config.reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) { + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + // Schedule Update the program + scheduleProgramUpdate(); + } + }, flags, ((_a = commandLine.parsedCommandLine) === null || _a === void 0 ? void 0 : _a.watchOptions) || watchOptions, ts.WatchType.WildcardDirectoryOfReferencedProject); + }); + } + else if (commandLine.watchedDirectories) { + ts.clearMap(commandLine.watchedDirectories, ts.closeFileWatcherOf); + commandLine.watchedDirectories = undefined; + } + // Watch extended config files + updateExtendedConfigFilesWatches(configPath, (_d = commandLine.parsedCommandLine) === null || _d === void 0 ? void 0 : _d.options, ((_e = commandLine.parsedCommandLine) === null || _e === void 0 ? void 0 : _e.watchOptions) || watchOptions, ts.WatchType.ExtendedConfigOfReferencedProject); } } ts.createWatchProgram = createWatchProgram; @@ -112810,12 +116268,19 @@ var ts; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined; + var typeReferenceDirectiveResolutionCache = !compilerHost.resolveTypeReferenceDirectives ? ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()) : undefined; if (!compilerHost.resolveModuleNames) { var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; }; compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3); }; } + if (!compilerHost.resolveTypeReferenceDirectives) { + var loader_4 = function (moduleName, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(moduleName, containingFile, state.projectCompilerOptions, compilerHost, redirectedReference, state.typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return ts.loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_4); + }; + } var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -112840,6 +116305,7 @@ var ts; projectErrorsReported: new ts.Map(), compilerHost: compilerHost, moduleResolutionCache: moduleResolutionCache, + typeReferenceDirectiveResolutionCache: typeReferenceDirectiveResolutionCache, // Mutable state buildOrder: undefined, readFileWithCache: function (f) { return host.readFile(f); }, @@ -112878,6 +116344,10 @@ var ts; function isParsedCommandLine(entry) { return !!entry.options; } + function getCachedParsedConfigFile(state, configFilePath) { + var value = state.configFileCache.get(configFilePath); + return value && isParsedCommandLine(value) ? value : undefined; + } function parseConfigFile(state, configFileName, configFilePath) { var configFileCache = state.configFileCache; var value = configFileCache.get(configFilePath); @@ -113023,7 +116493,7 @@ var ts; function disableCache(state) { if (!state.cache) return; - var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache; + var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache, typeReferenceDirectiveResolutionCache = state.typeReferenceDirectiveResolutionCache; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; host.directoryExists = cache.originalDirectoryExists; @@ -113032,10 +116502,8 @@ var ts; compilerHost.getSourceFile = cache.originalGetSourceFile; state.readFileWithCache = cache.originalReadFileWithCache; extendedConfigCache.clear(); - if (moduleResolutionCache) { - moduleResolutionCache.directoryToModuleNameMap.clear(); - moduleResolutionCache.moduleNameToDirectoryMap.clear(); - } + moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache === null || typeReferenceDirectiveResolutionCache === void 0 ? void 0 : typeReferenceDirectiveResolutionCache.clear(); state.cache = undefined; } function clearProjectStatus(state, resolved) { @@ -113202,6 +116670,7 @@ var ts; return withProgramOrUndefined(action) || ts.emptyArray; } function createProgram() { + var _a, _b; ts.Debug.assert(program === undefined); if (state.options.dry) { reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project); @@ -113221,7 +116690,8 @@ var ts; var host = state.host, compilerHost = state.compilerHost; state.projectCompilerOptions = config.options; // Update module resolution cache if needed - updateModuleResolutionCache(state, project, config); + (_a = state.moduleResolutionCache) === null || _a === void 0 ? void 0 : _a.update(config.options); + (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options); // Create program program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences); if (state.watch) { @@ -113396,7 +116866,7 @@ var ts; emitBundle(writeFile, customTransformers); break; case BuildStep.BuildInvalidatedProjectOfBundle: - ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken); + ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken, writeFile, customTransformers); step = BuildStep.Done; break; case BuildStep.QueueReferencingProjects: @@ -113538,34 +117008,9 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } - function updateModuleResolutionCache(state, proj, config) { - if (!state.moduleResolutionCache) - return; - // Update module resolution cache if needed - var moduleResolutionCache = state.moduleResolutionCache; - var projPath = toPath(state, proj); - if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) { - // The own map will be for projectCompilerOptions - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0); - moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap); - moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap); - } - else { - // Set correct own map - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0); - var ref = { - sourceFile: config.options.configFile, - commandLine: config - }; - moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); - } - moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options); - } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { // Check tsconfig time - var tsconfigTime = state.host.getModifiedTime(configFile) || ts.missingFileModifiedTime; + var tsconfigTime = ts.getModifiedTime(state.host, configFile); if (oldestOutputFileTime < tsconfigTime) { return { type: ts.UpToDateStatusType.OutOfDateWithSelf, @@ -113575,6 +117020,7 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { + var force = !!state.options.force; var newestInputFileName = undefined; var newestInputFileTime = minimumDate; var host = state.host; @@ -113587,10 +117033,13 @@ var ts; reason: inputFile + " does not exist" }; } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; + if (!force) { + var inputTime = ts.getModifiedTime(host, inputFile); + host.getModifiedTime(inputFile); + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } } // Container if no files are specified in the project @@ -113609,36 +117058,38 @@ var ts; var missingOutputFileName; var newestDeclarationFileContentChangedTime = minimumDate; var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { - var output = outputs_1[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = 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 outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + if (!force) { + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = ts.getModifiedTime(host, output); + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var outputModifiedTime = ts.getModifiedTime(host, output); + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } } } var pseudoUpToDate = false; @@ -113674,7 +117125,8 @@ var ts; }; } // Check oldest output file name only if there is no missing output file name - if (!missingOutputFileName) { + // (a check we will have skipped if this is a forced build) + if (!force && !missingOutputFileName) { // If the upstream project's newest file is older than our oldest output, we // can't be out of date because of it if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { @@ -113720,7 +117172,7 @@ var ts; if (extendedConfigStatus) return extendedConfigStatus; } - if (!state.buildInfoChecked.has(resolvedPath)) { + if (!force && !state.buildInfoChecked.has(resolvedPath)) { state.buildInfoChecked.set(resolvedPath, true); var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); if (buildInfoPath) { @@ -113780,7 +117232,7 @@ var ts; reportStatus(state, verboseMessage, proj.options.configFilePath); } if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, ts.getModifiedTime(host, file)); } host.setModifiedTime(file, now); } @@ -113862,7 +117314,7 @@ var ts; } } } - function build(state, project, cancellationToken, onlyReferences) { + function build(state, project, cancellationToken, writeFile, getCustomTransformers, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); if (!buildOrder) return ts.ExitStatus.InvalidProject_OutputsSkipped; @@ -113874,7 +117326,7 @@ var ts; if (!invalidatedProject) break; reportQueue = false; - invalidatedProject.done(cancellationToken); + invalidatedProject.done(cancellationToken, writeFile, getCustomTransformers === null || getCustomTransformers === void 0 ? void 0 : getCustomTransformers(invalidatedProject.project)); if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; } @@ -113909,8 +117361,14 @@ var ts; continue; } var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames()); + if (!outputs.length) + continue; + var inputFileNames = new ts.Set(parsed.fileNames.map(function (f) { return toPath(state, f); })); for (var _a = 0, outputs_3 = outputs; _a < outputs_3.length; _a++) { var output = outputs_3[_a]; + // If output name is same as input file name, do not delete and ignore the error + if (inputFileNames.has(toPath(state, output))) + continue; if (host.fileExists(output)) { if (filesToDelete) { filesToDelete.push(output); @@ -113986,7 +117444,7 @@ var ts; }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); } function watchExtendedConfigFiles(state, resolvedPath, parsed) { - ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { + ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { var _a; return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (projectConfigFilePath) { return invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ts.ConfigFileProgramReloadLevel.Full); @@ -113997,6 +117455,7 @@ var ts; if (!state.watch) return; ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), new ts.Map(ts.getEntries(parsed.wildcardDirectories)), function (dir, flags) { return state.watchDirectory(dir, function (fileOrDirectory) { + var _a; if (ts.isIgnoredFileFromWildCardWatching({ watchedDirPath: toPath(state, dir), fileOrDirectory: fileOrDirectory, @@ -114004,9 +117463,10 @@ var ts; configFileName: resolved, currentDirectory: state.currentDirectory, options: parsed.options, - program: state.builderPrograms.get(resolvedPath), + program: state.builderPrograms.get(resolvedPath) || ((_a = getCachedParsedConfigFile(state, resolvedPath)) === null || _a === void 0 ? void 0 : _a.fileNames), useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames, - writeLog: function (s) { return state.writeLog(s); } + writeLog: function (s) { return state.writeLog(s); }, + toPath: function (fileName) { return toPath(state, fileName); } })) return; invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Partial); @@ -114041,19 +117501,16 @@ var ts; } function stopWatching(state) { ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher); - ts.clearMap(state.allWatchedExtendedConfigFiles, function (watcher) { - watcher.projects.clear(); - watcher.close(); - }); + ts.clearMap(state.allWatchedExtendedConfigFiles, ts.closeFileWatcherOf); ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); }); ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); }); } function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) { var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions); return { - build: function (project, cancellationToken) { return build(state, project, cancellationToken); }, + build: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers); }, clean: function (project) { return clean(state, project); }, - buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); }, + buildReferences: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers, /*onlyReferences*/ true); }, cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); }, getNextInvalidatedProject: function (cancellationToken) { setupInitialBuild(state, cancellationToken); @@ -114143,6 +117600,9 @@ var ts; } } function reportUpToDateStatus(state, configFileName, status) { + if (state.options.force && (status.type === ts.UpToDateStatusType.UpToDate || status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes)) { + return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); + } switch (status.type) { case ts.UpToDateStatusType.OutOfDateWithSelf: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); @@ -114317,6 +117777,9 @@ var ts; SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["link"] = 22] = "link"; + SymbolDisplayPartKind[SymbolDisplayPartKind["linkName"] = 23] = "linkName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["linkText"] = 24] = "linkText"; })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); var OutliningSpanKind; (function (OutliningSpanKind) { @@ -114427,6 +117890,12 @@ var ts; ScriptElementKind["jsxAttribute"] = "JSX attribute"; /** String literal */ ScriptElementKind["string"] = "string"; + /** Jsdoc @link: in `{@link C link text}`, the before and after text "{@link " and "}" */ + ScriptElementKind["link"] = "link"; + /** Jsdoc @link: in `{@link C link text}`, the entity name "C" */ + ScriptElementKind["linkName"] = "link name"; + /** Jsdoc @link: in `{@link C link text}`, the link text "link text" */ + ScriptElementKind["linkText"] = "link text"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; (function (ScriptElementKindModifier) { @@ -114519,37 +117988,37 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; - case 160 /* Parameter */: - case 198 /* BindingElement */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 287 /* CatchClause */: - case 280 /* JsxAttribute */: + case 161 /* Parameter */: + case 199 /* BindingElement */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 288 /* CatchClause */: + case 281 /* JsxAttribute */: return 1 /* Value */; - case 159 /* TypeParameter */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 177 /* TypeLiteral */: + case 160 /* TypeParameter */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 178 /* TypeLiteral */: return 2 /* Type */; - case 331 /* JSDocTypedefTag */: + case 335 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; - case 291 /* EnumMember */: - case 252 /* ClassDeclaration */: + case 292 /* EnumMember */: + case 253 /* ClassDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; } @@ -114559,16 +118028,16 @@ var ts; else { return 4 /* Namespace */; } - case 255 /* EnumDeclaration */: - case 264 /* NamedImports */: - case 265 /* ImportSpecifier */: - case 260 /* ImportEqualsDeclaration */: - case 261 /* ImportDeclaration */: - case 266 /* ExportAssignment */: - case 267 /* ExportDeclaration */: + case 256 /* EnumDeclaration */: + case 265 /* NamedImports */: + case 266 /* ImportSpecifier */: + case 261 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 267 /* ExportAssignment */: + case 268 /* ExportDeclaration */: return 7 /* All */; // An external module can be a Value - case 297 /* SourceFile */: + case 298 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 7 /* All */; @@ -114576,13 +118045,13 @@ var ts; ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { node = getAdjustedReferenceLocation(node); - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 266 /* ExportAssignment */ - || node.parent.kind === 272 /* ExternalModuleReference */ - || node.parent.kind === 265 /* ImportSpecifier */ - || node.parent.kind === 262 /* ImportClause */ + else if (node.parent.kind === 267 /* ExportAssignment */ + || node.parent.kind === 273 /* ExternalModuleReference */ + || node.parent.kind === 266 /* ImportSpecifier */ + || node.parent.kind === 263 /* ImportClause */ || ts.isImportEqualsDeclaration(node.parent) && node === node.parent.name) { return 7 /* All */; } @@ -114592,7 +118061,7 @@ var ts; else if (ts.isDeclarationName(node)) { return getMeaningFromDeclaration(node.parent); } - else if (ts.isEntityName(node) && ts.isJSDocNameReference(node.parent)) { + else if (ts.isEntityName(node) && (ts.isJSDocNameReference(node.parent) || ts.isJSDocLink(node.parent))) { return 7 /* All */; } else if (isTypeReference(node)) { @@ -114618,11 +118087,11 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - var name = node.kind === 157 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; - return name && name.parent.kind === 260 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; + var name = node.kind === 158 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; + return name && name.parent.kind === 261 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; } function isInRightSideOfInternalImportEqualsDeclaration(node) { - while (node.parent.kind === 157 /* QualifiedName */) { + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -114634,27 +118103,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 157 /* QualifiedName */) { - while (root.parent && root.parent.kind === 157 /* QualifiedName */) { + if (root.parent.kind === 158 /* QualifiedName */) { + while (root.parent && root.parent.kind === 158 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 173 /* TypeReference */ && !isLastClause; + return root.parent.kind === 174 /* TypeReference */ && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 201 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 201 /* PropertyAccessExpression */) { + if (root.parent.kind === 202 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 202 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 223 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 286 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 224 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 287 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 252 /* ClassDeclaration */ && root.parent.parent.token === 116 /* ImplementsKeyword */) || - (decl.kind === 253 /* InterfaceDeclaration */ && root.parent.parent.token === 93 /* ExtendsKeyword */); + return (decl.kind === 253 /* ClassDeclaration */ && root.parent.parent.token === 116 /* ImplementsKeyword */) || + (decl.kind === 254 /* InterfaceDeclaration */ && root.parent.parent.token === 93 /* ExtendsKeyword */); } return false; } @@ -114665,15 +118134,15 @@ var ts; switch (node.kind) { case 107 /* ThisKeyword */: return !ts.isExpressionNode(node); - case 187 /* ThisType */: + case 188 /* ThisType */: return true; } switch (node.parent.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return true; - case 195 /* ImportType */: + case 196 /* ImportType */: return !node.parent.isTypeOf; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } return false; @@ -114740,7 +118209,7 @@ var ts; ts.climbPastPropertyOrElementAccess = climbPastPropertyOrElementAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 245 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { + if (referenceNode.kind === 246 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -114801,22 +118270,22 @@ var ts; ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { switch (node.parent.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 288 /* PropertyAssignment */: - case 291 /* EnumMember */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 256 /* ModuleDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 289 /* PropertyAssignment */: + case 292 /* EnumMember */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 257 /* ModuleDeclaration */: return ts.getNameOfDeclaration(node.parent) === node; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return node.parent.argumentExpression === node; - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return true; - case 191 /* LiteralType */: - return node.parent.parent.kind === 189 /* IndexedAccessType */; + case 192 /* LiteralType */: + return node.parent.parent.kind === 190 /* IndexedAccessType */; default: return false; } @@ -114840,17 +118309,17 @@ var ts; return undefined; } switch (node.kind) { - case 297 /* SourceFile */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 256 /* ModuleDeclaration */: + case 298 /* SourceFile */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 257 /* ModuleDeclaration */: return node; } } @@ -114858,54 +118327,54 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return "module" /* moduleElement */; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return "class" /* classElement */; - case 253 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; - case 254 /* TypeAliasDeclaration */: - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: + case 254 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 255 /* TypeAliasDeclaration */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: return "type" /* typeElement */; - case 255 /* EnumDeclaration */: return "enum" /* enumElement */; - case 249 /* VariableDeclaration */: + case 256 /* EnumDeclaration */: return "enum" /* enumElement */; + case 250 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 209 /* ArrowFunction */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return "function" /* functionElement */; - case 167 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; - case 168 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 168 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 169 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: return "method" /* memberFunctionElement */; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: var initializer = node.initializer; return ts.isFunctionLike(initializer) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 289 /* ShorthandPropertyAssignment */: - case 290 /* SpreadAssignment */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 290 /* ShorthandPropertyAssignment */: + case 291 /* SpreadAssignment */: return "property" /* memberVariableElement */; - case 171 /* IndexSignature */: return "index" /* indexSignatureElement */; - case 170 /* ConstructSignature */: return "construct" /* constructSignatureElement */; - case 169 /* CallSignature */: return "call" /* callSignatureElement */; - case 166 /* Constructor */: return "constructor" /* constructorImplementationElement */; - case 159 /* TypeParameter */: return "type parameter" /* typeParameterElement */; - case 291 /* EnumMember */: return "enum member" /* enumMemberElement */; - case 160 /* Parameter */: return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; - case 260 /* ImportEqualsDeclaration */: - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: - case 263 /* NamespaceImport */: - case 269 /* NamespaceExport */: + case 172 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 171 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 170 /* CallSignature */: return "call" /* callSignatureElement */; + case 167 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 160 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 292 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 161 /* Parameter */: return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 261 /* ImportEqualsDeclaration */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: + case 264 /* NamespaceImport */: + case 270 /* NamespaceExport */: return "alias" /* alias */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { @@ -114934,7 +118403,7 @@ var ts; } case 78 /* Identifier */: return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: var scriptKind = getNodeKind(node.expression); // If the expression didn't come back with something (like it does for an identifiers) return scriptKind === "" /* unknown */ ? "const" /* constElement */ : scriptKind; @@ -114957,7 +118426,7 @@ var ts; return true; case 78 /* Identifier */: // 'this' as a parameter - return ts.identifierIsThisKeyword(node) && node.parent.kind === 160 /* Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 161 /* Parameter */; default: return false; } @@ -115022,42 +118491,42 @@ var ts; return false; } switch (n.kind) { - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 200 /* ObjectLiteralExpression */: - case 196 /* ObjectBindingPattern */: - case 177 /* TypeLiteral */: - case 230 /* Block */: - case 257 /* ModuleBlock */: - case 258 /* CaseBlock */: - case 264 /* NamedImports */: - case 268 /* NamedExports */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 201 /* ObjectLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 178 /* TypeLiteral */: + case 231 /* Block */: + case 258 /* ModuleBlock */: + case 259 /* CaseBlock */: + case 265 /* NamedImports */: + case 269 /* NamedExports */: return nodeEndsWith(n, 19 /* CloseBraceToken */, sourceFile); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 204 /* NewExpression */: + case 205 /* NewExpression */: if (!n.arguments) { return true; } // falls through - case 203 /* CallExpression */: - case 207 /* ParenthesizedExpression */: - case 186 /* ParenthesizedType */: + case 204 /* CallExpression */: + case 208 /* ParenthesizedExpression */: + case 187 /* ParenthesizedType */: return nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 170 /* ConstructSignature */: - case 169 /* CallSignature */: - case 209 /* ArrowFunction */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 171 /* ConstructSignature */: + case 170 /* CallSignature */: + case 210 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -115067,65 +118536,65 @@ var ts; // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. return hasChildOfKind(n, 21 /* CloseParenToken */, sourceFile); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return !!n.body && isCompletedNode(n.body, sourceFile); - case 234 /* IfStatement */: + case 235 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 26 /* SemicolonToken */, sourceFile); - case 199 /* ArrayLiteralExpression */: - case 197 /* ArrayBindingPattern */: - case 202 /* ElementAccessExpression */: - case 158 /* ComputedPropertyName */: - case 179 /* TupleType */: + case 200 /* ArrayLiteralExpression */: + case 198 /* ArrayBindingPattern */: + case 203 /* ElementAccessExpression */: + case 159 /* ComputedPropertyName */: + case 180 /* TupleType */: return nodeEndsWith(n, 23 /* CloseBracketToken */, sourceFile); - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 23 /* CloseBracketToken */, sourceFile); - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed return false; - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 236 /* WhileStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 237 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 235 /* DoStatement */: + case 236 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; return hasChildOfKind(n, 114 /* WhileKeyword */, sourceFile) ? nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile) : isCompletedNode(n.statement, sourceFile); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 211 /* TypeOfExpression */: - case 210 /* DeleteExpression */: - case 212 /* VoidExpression */: - case 219 /* YieldExpression */: - case 220 /* SpreadElement */: + case 212 /* TypeOfExpression */: + case 211 /* DeleteExpression */: + case 213 /* VoidExpression */: + case 220 /* YieldExpression */: + case 221 /* SpreadElement */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 267 /* ExportDeclaration */: - case 261 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: return ts.nodeIsPresent(n.moduleSpecifier); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -115251,11 +118720,11 @@ var ts; function getAdjustedLocationForDeclaration(node, forRename) { if (!forRename) { switch (node.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return getAdjustedLocationForClass(node); - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return getAdjustedLocationForFunction(node); } } @@ -115515,7 +118984,7 @@ var ts; // for (... /**/in [|name|]) // for (... /**/of [|name|]) if (node.kind === 100 /* InKeyword */ && ts.isForInStatement(parent) || - node.kind === 156 /* OfKeyword */ && ts.isForOfStatement(parent)) { + node.kind === 157 /* OfKeyword */ && ts.isForOfStatement(parent)) { return ts.skipOuterExpressions(parent.expression); } } @@ -115584,6 +119053,21 @@ var ts; return current; } } + /** + * Returns the first token where position is in [start, end), + * excluding `JsxText` tokens containing only whitespace. + */ + function findFirstNonJsxWhitespaceToken(sourceFile, position) { + var tokenAtPosition = getTokenAtPosition(sourceFile, position); + while (isWhiteSpaceOnlyJsxText(tokenAtPosition)) { + var nextToken = findNextToken(tokenAtPosition, tokenAtPosition.parent, sourceFile); + if (!nextToken) + return; + tokenAtPosition = nextToken; + } + return tokenAtPosition; + } + ts.findFirstNonJsxWhitespaceToken = findFirstNonJsxWhitespaceToken; /** * The token on the left of the position is the token that strictly includes the position * or sits to the left of the cursor if it is on a boundary. For example @@ -115670,7 +119154,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 297 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 298 /* 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. @@ -115743,17 +119227,17 @@ var ts; return true; } //
{ |
or
- if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 283 /* JsxExpression */) { + if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 284 /* JsxExpression */) { return true; } //
{ // | // } < /div> - if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 283 /* JsxExpression */) { + if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 284 /* JsxExpression */) { return true; } //
|
- if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 276 /* JsxClosingElement */) { + if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 277 /* JsxClosingElement */) { return true; } return false; @@ -115784,7 +119268,7 @@ var ts; function isInsideJsxElement(sourceFile, position) { function isInsideJsxElementTraversal(node) { while (node) { - if (node.kind >= 274 /* JsxSelfClosingElement */ && node.kind <= 283 /* JsxExpression */ + if (node.kind >= 275 /* JsxSelfClosingElement */ && node.kind <= 284 /* JsxExpression */ || node.kind === 11 /* JsxText */ || node.kind === 29 /* LessThanToken */ || node.kind === 31 /* GreaterThanToken */ @@ -115794,7 +119278,7 @@ var ts; || node.kind === 43 /* SlashToken */) { node = node.parent; } - else if (node.kind === 273 /* JsxElement */) { + else if (node.kind === 274 /* JsxElement */) { if (position > node.getStart(sourceFile)) return true; node = node.parent; @@ -116002,16 +119486,16 @@ var ts; result.push("deprecated" /* deprecatedModifier */); if (node.flags & 8388608 /* Ambient */) result.push("declare" /* ambientModifier */); - if (node.kind === 266 /* ExportAssignment */) + if (node.kind === 267 /* ExportAssignment */) result.push("export" /* exportedModifier */); return result.length > 0 ? result.join(",") : "" /* none */; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 173 /* TypeReference */ || node.kind === 203 /* CallExpression */) { + if (node.kind === 174 /* TypeReference */ || node.kind === 204 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 252 /* ClassDeclaration */ || node.kind === 253 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 253 /* ClassDeclaration */ || node.kind === 254 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; @@ -116056,18 +119540,18 @@ var ts; } ts.cloneCompilerOptions = cloneCompilerOptions; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 199 /* ArrayLiteralExpression */ || - node.kind === 200 /* ObjectLiteralExpression */) { + if (node.kind === 200 /* ArrayLiteralExpression */ || + node.kind === 201 /* ObjectLiteralExpression */) { // [a,b,c] from: // [a, b, c] = someExpression; - if (node.parent.kind === 216 /* BinaryExpression */ && + if (node.parent.kind === 217 /* BinaryExpression */ && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */) { return true; } // [a, b, c] from: // for([a, b, c] of expression) - if (node.parent.kind === 239 /* ForOfStatement */ && + if (node.parent.kind === 240 /* ForOfStatement */ && node.parent.initializer === node) { return true; } @@ -116075,7 +119559,7 @@ var ts; // [x, [a, b, c] ] = someExpression // or // {x, a: {a, b, c} } = someExpression - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 288 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 289 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { return true; } } @@ -116195,7 +119679,7 @@ var ts; } ts.skipConstraint = skipConstraint; function getNameFromPropertyName(name) { - return name.kind === 158 /* ComputedPropertyName */ + return name.kind === 159 /* ComputedPropertyName */ // treat computed property names where expression is string/numeric literal as just string/numeric literal ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined : ts.isPrivateIdentifier(name) ? ts.idText(name) : ts.getTextOfIdentifierOrLiteral(name); @@ -116214,7 +119698,7 @@ var ts; } ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules; function createModuleSpecifierResolutionHost(program, host) { - // Mix in `getProbableSymlinks` from Program when host doesn't have it + // Mix in `getSymlinkCache` from Program when host doesn't have it // in order for non-Project hosts to have a symlinks cache. return { fileExists: function (fileName) { return program.fileExists(fileName); }, @@ -116222,6 +119706,7 @@ var ts; readFile: ts.maybeBind(host, host.readFile), useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), getSymlinkCache: ts.maybeBind(host, host.getSymlinkCache) || program.getSymlinkCache, + getModuleSpecifierCache: ts.maybeBind(host, host.getModuleSpecifierCache), getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation), getSourceFiles: function () { return program.getSourceFiles(); }, redirectTargetsMap: program.redirectTargetsMap, @@ -116296,6 +119781,13 @@ var ts; }); } ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isModuleSpecifierLike(node) { + return ts.isStringLiteralLike(node) && (ts.isExternalModuleReference(node.parent) || + ts.isImportDeclaration(node.parent) || + ts.isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ false) && node.parent.arguments[0] === node || + ts.isImportCall(node.parent) && node.parent.arguments[0] === node); + } + ts.isModuleSpecifierLike = isModuleSpecifierLike; function isObjectBindingElementWithoutPropertyName(bindingElement) { return ts.isBindingElement(bindingElement) && ts.isObjectBindingPattern(bindingElement.parent) && @@ -116329,7 +119821,7 @@ var ts; ts.findModifier = findModifier; function insertImports(changes, sourceFile, imports, blankLineBetween) { var decl = ts.isArray(imports) ? imports[0] : imports; - var importKindPredicate = decl.kind === 232 /* VariableStatement */ ? ts.isRequireVariableStatement : ts.isAnyImportSyntax; + var importKindPredicate = decl.kind === 233 /* VariableStatement */ ? ts.isRequireVariableStatement : ts.isAnyImportSyntax; var existingImportStatements = ts.filter(sourceFile.statements, importKindPredicate); var sortedNewImports = ts.isArray(imports) ? ts.stableSort(imports, ts.OrganizeImports.compareImportsOrRequireStatements) : [imports]; if (!existingImportStatements.length) { @@ -116407,7 +119899,7 @@ var ts; // Display-part writer helpers // #region function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 160 /* Parameter */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 161 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -116570,6 +120062,14 @@ var ts; return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); } ts.operatorPart = operatorPart; + function parameterNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.parameterName); + } + ts.parameterNamePart = parameterNamePart; + function propertyNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.propertyName); + } + ts.propertyNamePart = propertyNamePart; function textOrKeywordPart(text) { var kind = ts.stringToToken(text); return kind === undefined @@ -116581,6 +120081,58 @@ var ts; return displayPart(text, ts.SymbolDisplayPartKind.text); } ts.textPart = textPart; + function typeAliasNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.aliasName); + } + ts.typeAliasNamePart = typeAliasNamePart; + function typeParameterNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.typeParameterName); + } + ts.typeParameterNamePart = typeParameterNamePart; + function linkTextPart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.linkText); + } + ts.linkTextPart = linkTextPart; + function linkNamePart(name, target) { + return { + text: ts.getTextOfNode(name), + kind: ts.SymbolDisplayPartKind[ts.SymbolDisplayPartKind.linkName], + target: { + fileName: ts.getSourceFileOfNode(target).fileName, + textSpan: createTextSpanFromNode(target), + }, + }; + } + ts.linkNamePart = linkNamePart; + function linkPart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.link); + } + ts.linkPart = linkPart; + function buildLinkParts(link, checker) { + var _a; + var parts = [linkPart("{@link ")]; + if (!link.name) { + if (link.text) { + parts.push(linkTextPart(link.text)); + } + } + else { + var symbol = checker === null || checker === void 0 ? void 0 : checker.getSymbolAtLocation(link.name); + var decl = (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) || ((_a = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]); + if (decl) { + parts.push(linkNamePart(link.name, decl)); + if (link.text) { + parts.push(linkTextPart(link.text)); + } + } + else { + parts.push(linkTextPart(ts.getTextOfNode(link.name) + link.text)); + } + } + parts.push(linkPart("}")); + return parts; + } + ts.buildLinkParts = buildLinkParts; var carriageReturnLineFeed = "\r\n"; /** * The default is CRLF. @@ -116866,21 +120418,23 @@ var ts; } /* @internal */ function needsParentheses(expression) { - return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ + || ts.isObjectLiteralExpression(expression) + || ts.isAsExpression(expression) && ts.isObjectLiteralExpression(expression.expression); } ts.needsParentheses = needsParentheses; function getContextualTypeFromParent(node, checker) { var parent = node.parent; switch (parent.kind) { - case 204 /* NewExpression */: + case 205 /* NewExpression */: return checker.getContextualType(parent); - case 216 /* BinaryExpression */: { + case 217 /* BinaryExpression */: { var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; return isEqualityOperatorKind(operatorToken.kind) ? checker.getTypeAtLocation(node === right ? left : right) : checker.getContextualType(node); } - case 284 /* CaseClause */: + case 285 /* CaseClause */: return parent.expression === node ? getSwitchedType(parent, checker) : undefined; default: return checker.getContextualType(node); @@ -116891,7 +120445,7 @@ var ts; // Editors can pass in undefined or empty string - we want to infer the preference in those cases. var quotePreference = getQuotePreference(sourceFile, preferences); var quoted = JSON.stringify(text); - return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'" : quoted; + return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace(/'/g, "\\'").replace(/\\"/g, '"') + "'" : quoted; } ts.quote = quote; function isEqualityOperatorKind(kind) { @@ -116910,8 +120464,8 @@ var ts; switch (node.kind) { case 10 /* StringLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: - case 218 /* TemplateExpression */: - case 205 /* TaggedTemplateExpression */: + case 219 /* TemplateExpression */: + case 206 /* TaggedTemplateExpression */: return true; default: return false; @@ -116944,41 +120498,41 @@ var ts; } ts.getTypeNodeIfAccessible = getTypeNodeIfAccessible; function syntaxRequiresTrailingCommaOrSemicolonOrASI(kind) { - return kind === 169 /* CallSignature */ - || kind === 170 /* ConstructSignature */ - || kind === 171 /* IndexSignature */ - || kind === 162 /* PropertySignature */ - || kind === 164 /* MethodSignature */; + return kind === 170 /* CallSignature */ + || kind === 171 /* ConstructSignature */ + || kind === 172 /* IndexSignature */ + || kind === 163 /* PropertySignature */ + || kind === 165 /* MethodSignature */; } ts.syntaxRequiresTrailingCommaOrSemicolonOrASI = syntaxRequiresTrailingCommaOrSemicolonOrASI; function syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(kind) { - return kind === 251 /* FunctionDeclaration */ - || kind === 166 /* Constructor */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 252 /* FunctionDeclaration */ + || kind === 167 /* Constructor */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } ts.syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI = syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI; function syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(kind) { - return kind === 256 /* ModuleDeclaration */; + return kind === 257 /* ModuleDeclaration */; } ts.syntaxRequiresTrailingModuleBlockOrSemicolonOrASI = syntaxRequiresTrailingModuleBlockOrSemicolonOrASI; function syntaxRequiresTrailingSemicolonOrASI(kind) { - return kind === 232 /* VariableStatement */ - || kind === 233 /* ExpressionStatement */ - || kind === 235 /* DoStatement */ - || kind === 240 /* ContinueStatement */ - || kind === 241 /* BreakStatement */ - || kind === 242 /* ReturnStatement */ - || kind === 246 /* ThrowStatement */ - || kind === 248 /* DebuggerStatement */ - || kind === 163 /* PropertyDeclaration */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 261 /* ImportDeclaration */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 267 /* ExportDeclaration */ - || kind === 259 /* NamespaceExportDeclaration */ - || kind === 266 /* ExportAssignment */; + return kind === 233 /* VariableStatement */ + || kind === 234 /* ExpressionStatement */ + || kind === 236 /* DoStatement */ + || kind === 241 /* ContinueStatement */ + || kind === 242 /* BreakStatement */ + || kind === 243 /* ReturnStatement */ + || kind === 247 /* ThrowStatement */ + || kind === 249 /* DebuggerStatement */ + || kind === 164 /* PropertyDeclaration */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 262 /* ImportDeclaration */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 268 /* ExportDeclaration */ + || kind === 260 /* NamespaceExportDeclaration */ + || kind === 267 /* ExportAssignment */; } ts.syntaxRequiresTrailingSemicolonOrASI = syntaxRequiresTrailingSemicolonOrASI; ts.syntaxMayBeASICandidate = ts.or(syntaxRequiresTrailingCommaOrSemicolonOrASI, syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI, syntaxRequiresTrailingModuleBlockOrSemicolonOrASI, syntaxRequiresTrailingSemicolonOrASI); @@ -117008,7 +120562,7 @@ var ts; return false; } // See comment in parser’s `parseDoStatement` - if (node.kind === 235 /* DoStatement */) { + if (node.kind === 236 /* DoStatement */) { return true; } var topNode = ts.findAncestor(node, function (ancestor) { return !ancestor.parent; }); @@ -117182,6 +120736,94 @@ var ts; } } ts.createPackageJsonInfo = createPackageJsonInfo; + function createPackageJsonImportFilter(fromFile, host) { + var packageJsons = ((host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName)) || getPackageJsonsVisibleToFile(fromFile.fileName, host)).filter(function (p) { return p.parseable; }); + var usesNodeCoreModules; + return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier }; + function moduleSpecifierIsCoveredByPackageJson(specifier) { + var packageName = getNodeModuleRootSpecifier(specifier); + for (var _i = 0, packageJsons_1 = packageJsons; _i < packageJsons_1.length; _i++) { + var packageJson = packageJsons_1[_i]; + if (packageJson.has(packageName) || packageJson.has(ts.getTypesPackageName(packageName))) { + return true; + } + } + return false; + } + function allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost) { + if (!packageJsons.length || !moduleSymbol.valueDeclaration) { + return true; + } + var declaringSourceFile = moduleSymbol.valueDeclaration.getSourceFile(); + var declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName, moduleSpecifierResolutionHost); + if (typeof declaringNodeModuleName === "undefined") { + return true; + } + var declaredModuleSpecifier = ts.stripQuotes(moduleSymbol.getName()); + if (isAllowedCoreNodeModulesImport(declaredModuleSpecifier)) { + return true; + } + return moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName) + || moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier); + } + function allowsImportingSourceFile(sourceFile, moduleSpecifierResolutionHost) { + if (!packageJsons.length) { + return true; + } + var moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName, moduleSpecifierResolutionHost); + if (!moduleSpecifier) { + return true; + } + return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); + } + function allowsImportingSpecifier(moduleSpecifier) { + if (!packageJsons.length || isAllowedCoreNodeModulesImport(moduleSpecifier)) { + return true; + } + if (ts.pathIsRelative(moduleSpecifier) || ts.isRootedDiskPath(moduleSpecifier)) { + return true; + } + return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); + } + function isAllowedCoreNodeModulesImport(moduleSpecifier) { + // If we’re in JavaScript, it can be difficult to tell whether the user wants to import + // from Node core modules or not. We can start by seeing if the user is actually using + // any node core modules, as opposed to simply having @types/node accidentally as a + // dependency of a dependency. + if (ts.isSourceFileJS(fromFile) && ts.JsTyping.nodeCoreModules.has(moduleSpecifier)) { + if (usesNodeCoreModules === undefined) { + usesNodeCoreModules = consumesNodeCoreModules(fromFile); + } + if (usesNodeCoreModules) { + return true; + } + } + return false; + } + function getNodeModulesPackageNameFromFileName(importedFileName, moduleSpecifierResolutionHost) { + if (!ts.stringContains(importedFileName, "node_modules")) { + return undefined; + } + var specifier = ts.moduleSpecifiers.getNodeModulesPackageName(host.getCompilationSettings(), fromFile.path, importedFileName, moduleSpecifierResolutionHost); + if (!specifier) { + return undefined; + } + // Paths here are not node_modules, so we don’t care about them; + // returning anything will trigger a lookup in package.json. + if (!ts.pathIsRelative(specifier) && !ts.isRootedDiskPath(specifier)) { + return getNodeModuleRootSpecifier(specifier); + } + } + function getNodeModuleRootSpecifier(fullSpecifier) { + var components = ts.getPathComponents(ts.getPackageNameFromTypesPackageName(fullSpecifier)).slice(1); + // Scoped packages + if (ts.startsWith(components[0], "@")) { + return components[0] + "/" + components[1]; + } + return components[0]; + } + } + ts.createPackageJsonImportFilter = createPackageJsonImportFilter; function tryParseJson(text) { try { return JSON.parse(text); @@ -117258,9 +120900,9 @@ var ts; } ts.firstOrOnly = firstOrOnly; function getNameForExportedSymbol(symbol, scriptTarget) { - if (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */) { + if (!(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */)) { // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. - return ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) + return ts.firstDefined(symbol.declarations, function (d) { var _a; return ts.isExportAssignment(d) ? (_a = ts.tryCast(ts.skipOuterExpressions(d.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget); } return symbol.name; @@ -117324,6 +120966,184 @@ var ts; return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation); } ts.isNonGlobalDeclaration = isNonGlobalDeclaration; + var ImportKind; + (function (ImportKind) { + ImportKind[ImportKind["Named"] = 0] = "Named"; + ImportKind[ImportKind["Default"] = 1] = "Default"; + ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; + ImportKind[ImportKind["CommonJS"] = 3] = "CommonJS"; + })(ImportKind = ts.ImportKind || (ts.ImportKind = {})); + var ExportKind; + (function (ExportKind) { + ExportKind[ExportKind["Named"] = 0] = "Named"; + ExportKind[ExportKind["Default"] = 1] = "Default"; + ExportKind[ExportKind["ExportEquals"] = 2] = "ExportEquals"; + ExportKind[ExportKind["UMD"] = 3] = "UMD"; + })(ExportKind = ts.ExportKind || (ts.ExportKind = {})); + function createExportMapCache() { + var cache; + var projectVersion; + var usableByFileName; + var wrapped = { + isEmpty: function () { + return !cache; + }, + clear: function () { + cache = undefined; + projectVersion = undefined; + }, + set: function (suggestions, version) { + cache = suggestions; + if (version) { + projectVersion = version; + } + }, + get: function (file, checker, version) { + if (usableByFileName && file !== usableByFileName) { + return undefined; + } + if (version && projectVersion === version) { + return cache; + } + cache === null || cache === void 0 ? void 0 : cache.forEach(function (infos) { + var _a, _b, _c; + for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { + var info = infos_1[_i]; + // If the symbol/moduleSymbol was a merged symbol, it will have a new identity + // in the checker, even though the symbols to merge are the same (guaranteed by + // cache invalidation in synchronizeHostData). + if ((_a = info.symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) { + info.symbol = checker.getMergedSymbol(info.exportKind === 1 /* Default */ + ? (_b = info.symbol.declarations[0].localSymbol) !== null && _b !== void 0 ? _b : info.symbol.declarations[0].symbol + : info.symbol.declarations[0].symbol); + } + if ((_c = info.moduleSymbol.declarations) === null || _c === void 0 ? void 0 : _c.length) { + info.moduleSymbol = checker.getMergedSymbol(info.moduleSymbol.declarations[0].symbol); + } + } + }); + return cache; + }, + onFileChanged: function (oldSourceFile, newSourceFile, typeAcquisitionEnabled) { + if (fileIsGlobalOnly(oldSourceFile) && fileIsGlobalOnly(newSourceFile)) { + // File is purely global; doesn't affect export map + return false; + } + if (usableByFileName && usableByFileName !== newSourceFile.path || + // If ATA is enabled, auto-imports uses existing imports to guess whether you want auto-imports from node. + // Adding or removing imports from node could change the outcome of that guess, so could change the suggestions list. + typeAcquisitionEnabled && consumesNodeCoreModules(oldSourceFile) !== consumesNodeCoreModules(newSourceFile) || + // Module agumentation and ambient module changes can add or remove exports available to be auto-imported. + // Changes elsewhere in the file can change the *type* of an export in a module augmentation, + // but type info is gathered in getCompletionEntryDetails, which doesn’t use the cache. + !ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations) || + !ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile)) { + this.clear(); + return true; + } + usableByFileName = newSourceFile.path; + return false; + }, + }; + if (ts.Debug.isDebugging) { + Object.defineProperty(wrapped, "__cache", { get: function () { return cache; } }); + } + return wrapped; + function fileIsGlobalOnly(file) { + return !file.commonJsModuleIndicator && !file.externalModuleIndicator && !file.moduleAugmentations && !file.ambientModuleNames; + } + function ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile) { + if (!ts.arrayIsEqualTo(oldSourceFile.ambientModuleNames, newSourceFile.ambientModuleNames)) { + return false; + } + var oldFileStatementIndex = -1; + var newFileStatementIndex = -1; + var _loop_1 = function (ambientModuleName) { + var isMatchingModuleDeclaration = function (node) { return ts.isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName; }; + oldFileStatementIndex = ts.findIndex(oldSourceFile.statements, isMatchingModuleDeclaration, oldFileStatementIndex + 1); + newFileStatementIndex = ts.findIndex(newSourceFile.statements, isMatchingModuleDeclaration, newFileStatementIndex + 1); + if (oldSourceFile.statements[oldFileStatementIndex] !== newSourceFile.statements[newFileStatementIndex]) { + return { value: false }; + } + }; + for (var _i = 0, _a = newSourceFile.ambientModuleNames; _i < _a.length; _i++) { + var ambientModuleName = _a[_i]; + var state_1 = _loop_1(ambientModuleName); + if (typeof state_1 === "object") + return state_1.value; + } + return true; + } + } + ts.createExportMapCache = createExportMapCache; + function createModuleSpecifierCache() { + var cache; + var importingFileName; + var wrapped = { + get: function (fromFileName, toFileName) { + if (!cache || fromFileName !== importingFileName) + return undefined; + return cache.get(toFileName); + }, + set: function (fromFileName, toFileName, moduleSpecifiers) { + if (cache && fromFileName !== importingFileName) { + cache.clear(); + } + importingFileName = fromFileName; + (cache || (cache = new ts.Map())).set(toFileName, moduleSpecifiers); + }, + clear: function () { + cache = undefined; + importingFileName = undefined; + }, + count: function () { + return cache ? cache.size : 0; + } + }; + if (ts.Debug.isDebugging) { + Object.defineProperty(wrapped, "__cache", { get: function () { return cache; } }); + } + return wrapped; + } + ts.createModuleSpecifierCache = createModuleSpecifierCache; + function isImportableFile(program, from, to, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) { + var _a; + if (from === to) + return false; + var cachedResult = moduleSpecifierCache === null || moduleSpecifierCache === void 0 ? void 0 : moduleSpecifierCache.get(from.path, to.path); + if (cachedResult !== undefined) { + return !!cachedResult; + } + var getCanonicalFileName = ts.hostGetCanonicalFileName(moduleSpecifierResolutionHost); + var globalTypingsCache = (_a = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation) === null || _a === void 0 ? void 0 : _a.call(moduleSpecifierResolutionHost); + var hasImportablePath = !!ts.moduleSpecifiers.forEachFileNameOfModule(from.fileName, to.fileName, moduleSpecifierResolutionHost, + /*preferSymlinks*/ false, function (toPath) { + var toFile = program.getSourceFile(toPath); + // Determine to import using toPath only if toPath is what we were looking at + // or there doesnt exist the file in the program by the symlink + return (toFile === to || !toFile) && + isImportablePath(from.fileName, toPath, getCanonicalFileName, globalTypingsCache); + }); + if (packageJsonFilter) { + var isImportable = hasImportablePath && packageJsonFilter.allowsImportingSourceFile(to, moduleSpecifierResolutionHost); + moduleSpecifierCache === null || moduleSpecifierCache === void 0 ? void 0 : moduleSpecifierCache.set(from.path, to.path, isImportable); + return isImportable; + } + return hasImportablePath; + } + ts.isImportableFile = isImportableFile; + /** + * Don't include something from a `node_modules` that isn't actually reachable by a global import. + * A relative import to node_modules is usually a bad idea. + */ + function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) { + // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. + var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); + var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules)); + return toNodeModulesParent === undefined + || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) + || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); + } // #endregion })(ts || (ts = {})); var ts; @@ -117765,13 +121585,13 @@ var ts; // That means we're calling back into the host around every 1.2k of the file we process. // Lib.d.ts has similar numbers. switch (kind) { - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 251 /* FunctionDeclaration */: - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: cancellationToken.throwIfCancellationRequested(); } } @@ -117978,10 +121798,11 @@ var ts; pushClassification(start, width, 1 /* comment */); } function classifyJSDocComment(docComment) { + var _a, _b, _c, _d, _e, _f, _g; var pos = docComment.pos; if (docComment.tags) { - for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { - var tag = _a[_i]; + for (var _i = 0, _h = docComment.tags; _i < _h.length; _i++) { + var tag = _h[_i]; // As we walk through each tag, classify the portion of text from the end of // the last tag (or the start of the entire doc comment) as 'comment'. if (tag.pos !== pos) { @@ -117990,22 +121811,56 @@ var ts; pushClassification(tag.pos, 1, 10 /* punctuation */); // "@" pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; + var commentStart = tag.tagName.end; switch (tag.kind) { - case 326 /* JSDocParameterTag */: - processJSDocParameterTag(tag); + case 330 /* JSDocParameterTag */: + var param = tag; + processJSDocParameterTag(param); + commentStart = param.isNameFirst && ((_a = param.typeExpression) === null || _a === void 0 ? void 0 : _a.end) || param.name.end; + break; + case 337 /* JSDocPropertyTag */: + var prop = tag; + commentStart = prop.isNameFirst && ((_b = prop.typeExpression) === null || _b === void 0 ? void 0 : _b.end) || prop.name.end; break; - case 330 /* JSDocTemplateTag */: + case 334 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); pos = tag.end; + commentStart = tag.typeParameters.end; + break; + case 335 /* JSDocTypedefTag */: + var type = tag; + commentStart = ((_c = type.typeExpression) === null || _c === void 0 ? void 0 : _c.kind) === 302 /* JSDocTypeExpression */ && ((_d = type.fullName) === null || _d === void 0 ? void 0 : _d.end) || ((_e = type.typeExpression) === null || _e === void 0 ? void 0 : _e.end) || commentStart; + break; + case 328 /* JSDocCallbackTag */: + commentStart = tag.typeExpression.end; break; - case 329 /* JSDocTypeTag */: + case 333 /* JSDocTypeTag */: processElement(tag.typeExpression); pos = tag.end; + commentStart = tag.typeExpression.end; break; - case 327 /* JSDocReturnTag */: + case 332 /* JSDocThisTag */: + case 329 /* JSDocEnumTag */: + commentStart = tag.typeExpression.end; + break; + case 331 /* JSDocReturnTag */: processElement(tag.typeExpression); pos = tag.end; + commentStart = ((_f = tag.typeExpression) === null || _f === void 0 ? void 0 : _f.end) || commentStart; + break; + case 336 /* JSDocSeeTag */: + commentStart = ((_g = tag.name) === null || _g === void 0 ? void 0 : _g.end) || commentStart; break; + case 318 /* JSDocAugmentsTag */: + case 319 /* JSDocImplementsTag */: + commentStart = tag.class.end; + break; + } + if (typeof tag.comment === "object") { + pushCommentRange(tag.comment.pos, tag.comment.end - tag.comment.pos); + } + else if (typeof tag.comment === "string") { + pushCommentRange(commentStart, tag.end - commentStart); } } } @@ -118153,22 +122008,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } break; - case 276 /* JsxClosingElement */: + case 277 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } break; - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } break; - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: if (token.parent.name === token) { return 22 /* jsxAttribute */; } @@ -118197,17 +122052,17 @@ var ts; var parent = token.parent; if (tokenKind === 62 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (parent.kind === 249 /* VariableDeclaration */ || - parent.kind === 163 /* PropertyDeclaration */ || - parent.kind === 160 /* Parameter */ || - parent.kind === 280 /* JsxAttribute */) { + if (parent.kind === 250 /* VariableDeclaration */ || + parent.kind === 164 /* PropertyDeclaration */ || + parent.kind === 161 /* Parameter */ || + parent.kind === 281 /* JsxAttribute */) { return 5 /* operator */; } } - if (parent.kind === 216 /* BinaryExpression */ || - parent.kind === 214 /* PrefixUnaryExpression */ || - parent.kind === 215 /* PostfixUnaryExpression */ || - parent.kind === 217 /* ConditionalExpression */) { + if (parent.kind === 217 /* BinaryExpression */ || + parent.kind === 215 /* PrefixUnaryExpression */ || + parent.kind === 216 /* PostfixUnaryExpression */ || + parent.kind === 218 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -118220,7 +122075,7 @@ var ts; return 25 /* bigintLiteral */; } else if (tokenKind === 10 /* StringLiteral */) { - return token && token.parent.kind === 280 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + return token && token.parent.kind === 281 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 13 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -118236,32 +122091,32 @@ var ts; else if (tokenKind === 78 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 160 /* Parameter */: + case 161 /* Parameter */: if (token.parent.name === token) { return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } @@ -118363,13 +122218,13 @@ var ts; var inJSXElement = false; function visit(node) { switch (node.kind) { - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 251 /* FunctionDeclaration */: - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: cancellationToken.throwIfCancellationRequested(); } if (!node || !ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth()) || node.getFullWidth() === 0) { @@ -118515,25 +122370,25 @@ var ts; return (ts.isQualifiedName(node.parent) && node.parent.right === node) || (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node); } var tokenFromDeclarationMapping = new ts.Map([ - [249 /* VariableDeclaration */, 7 /* variable */], - [160 /* Parameter */, 6 /* parameter */], - [163 /* PropertyDeclaration */, 9 /* property */], - [256 /* ModuleDeclaration */, 3 /* namespace */], - [255 /* EnumDeclaration */, 1 /* enum */], - [291 /* EnumMember */, 8 /* enumMember */], - [252 /* ClassDeclaration */, 0 /* class */], - [165 /* MethodDeclaration */, 11 /* member */], - [251 /* FunctionDeclaration */, 10 /* function */], - [208 /* FunctionExpression */, 10 /* function */], - [164 /* MethodSignature */, 11 /* member */], - [167 /* GetAccessor */, 9 /* property */], - [168 /* SetAccessor */, 9 /* property */], - [162 /* PropertySignature */, 9 /* property */], - [253 /* InterfaceDeclaration */, 2 /* interface */], - [254 /* TypeAliasDeclaration */, 5 /* type */], - [159 /* TypeParameter */, 4 /* typeParameter */], - [288 /* PropertyAssignment */, 9 /* property */], - [289 /* ShorthandPropertyAssignment */, 9 /* property */] + [250 /* VariableDeclaration */, 7 /* variable */], + [161 /* Parameter */, 6 /* parameter */], + [164 /* PropertyDeclaration */, 9 /* property */], + [257 /* ModuleDeclaration */, 3 /* namespace */], + [256 /* EnumDeclaration */, 1 /* enum */], + [292 /* EnumMember */, 8 /* enumMember */], + [253 /* ClassDeclaration */, 0 /* class */], + [166 /* MethodDeclaration */, 11 /* member */], + [252 /* FunctionDeclaration */, 10 /* function */], + [209 /* FunctionExpression */, 10 /* function */], + [165 /* MethodSignature */, 11 /* member */], + [168 /* GetAccessor */, 9 /* property */], + [169 /* SetAccessor */, 9 /* property */], + [163 /* PropertySignature */, 9 /* property */], + [254 /* InterfaceDeclaration */, 2 /* interface */], + [255 /* TypeAliasDeclaration */, 5 /* type */], + [160 /* TypeParameter */, 4 /* typeParameter */], + [289 /* PropertyAssignment */, 9 /* property */], + [290 /* ShorthandPropertyAssignment */, 9 /* property */] ]); })(v2020 = classifier.v2020 || (classifier.v2020 = {})); })(classifier = ts.classifier || (ts.classifier = {})); @@ -118553,12 +122408,12 @@ var ts; if (ts.isInString(sourceFile, position, contextToken)) { if (!contextToken || !ts.isStringLiteralLike(contextToken)) return undefined; - var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); - return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, preferences); + var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); + return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, options, preferences); } } StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; - function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, preferences) { + function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, options, preferences) { if (completion === undefined) { return undefined; } @@ -118568,7 +122423,7 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences, options); // Target will not be used, so arbitrary return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, optionalReplacementSpan: optionalReplacementSpan, entries: entries }; } case 2 /* Types */: { @@ -118585,10 +122440,10 @@ var ts; return ts.Debug.assertNever(completion); } } - function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken) { + function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken, preferences) { if (!contextToken || !ts.isStringLiteralLike(contextToken)) return undefined; - var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); + var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken); } StringCompletions.getStringLiteralCompletionDetails = getStringLiteralCompletionDetails; @@ -118637,13 +122492,13 @@ var ts; StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties"; StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); - function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host, preferences) { var parent = walkUpParentheses(node.parent); switch (parent.kind) { - case 191 /* LiteralType */: { + case 192 /* LiteralType */: { var grandParent = walkUpParentheses(parent.parent); switch (grandParent.kind) { - case 173 /* TypeReference */: { + case 174 /* TypeReference */: { var typeReference_1 = grandParent; var typeArgument = ts.findAncestor(parent, function (n) { return n.parent === typeReference_1; }); if (typeArgument) { @@ -118651,7 +122506,7 @@ var ts; } return undefined; } - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { // foo: string; @@ -118663,9 +122518,9 @@ var ts; return undefined; } return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(objectType)); - case 195 /* ImportType */: - return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 182 /* UnionType */: { + case 196 /* ImportType */: + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; + case 183 /* UnionType */: { if (!ts.isTypeReferenceNode(grandParent.parent)) { return undefined; } @@ -118677,7 +122532,7 @@ var ts; return undefined; } } - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { @@ -118694,7 +122549,7 @@ var ts; return stringLiteralCompletionsForObjectLiteral(typeChecker, parent.parent); } return fromContextualType(); - case 202 /* ElementAccessExpression */: { + case 203 /* ElementAccessExpression */: { var _b = parent, expression = _b.expression, argumentExpression = _b.argumentExpression; if (node === ts.skipParentheses(argumentExpression)) { // Get all names of properties on the expression @@ -118707,8 +122562,8 @@ var ts; } return undefined; } - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: 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 @@ -118717,16 +122572,16 @@ var ts; return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); } // falls through (is `require("")` or `import("")`) - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: - case 272 /* ExternalModuleReference */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 273 /* ExternalModuleReference */: // Get all known external module names or complete a path to a module // i.e. import * as ns from "/*completion position*/"; // var y = import("/*completion position*/"); // import x = require("/*completion position*/"); // var y = require("/*completion position*/"); // export * from "/*completion position*/"; - return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; default: return fromContextualType(); } @@ -118738,9 +122593,9 @@ var ts; } function walkUpParentheses(node) { switch (node.kind) { - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return ts.walkUpParenthesizedTypes(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return ts.walkUpParenthesizedExpressions(node); default: return node; @@ -118768,7 +122623,7 @@ var ts; function stringLiteralCompletionsFromProperties(type) { return type && { kind: 1 /* Properties */, - symbols: ts.filter(type.getApparentProperties(), function (prop) { return !(prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)); }), + symbols: ts.filter(type.getApparentProperties(), function (prop) { return !(prop.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration)); }), hasIndexSignature: ts.hasIndexSignature(type) }; } @@ -118806,23 +122661,23 @@ var ts; return Math.max(name.indexOf(ts.directorySeparator), name.indexOf(ts.altDirectorySeparator)) !== -1 ? { name: name, kind: kind, extension: extension, span: wholeSpan } : { name: name, kind: kind, extension: extension, span: span }; }); } - function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { - return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); + function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) { + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences)); } - function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) { + function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = sourceFile.path; var scriptDirectory = ts.getDirectoryPath(scriptPath); return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue)) - ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) + ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, preferences) : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); } function getExtensionOptions(compilerOptions, includeExtensions) { if (includeExtensions === void 0) { includeExtensions = false; } return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions: includeExtensions }; } - function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) { - var extensionOptions = getExtensionOptions(compilerOptions); + function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, preferences) { + var extensionOptions = getExtensionOptions(compilerOptions, preferences.importModuleSpecifierEnding === "js"); if (compilerOptions.rootDirs) { return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); } @@ -118939,7 +122794,7 @@ var ts; continue; var patterns = paths[path]; if (patterns) { - var _loop_1 = function (name, kind, extension) { + var _loop_2 = function (name, kind, extension) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(function (entry) { return entry.name === name; })) { result.push(nameAndKind(name, kind, extension)); @@ -118947,7 +122802,7 @@ var ts; }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; - _loop_1(name, kind, extension); + _loop_2(name, kind, extension); } } } @@ -118982,7 +122837,7 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_2 = function (moduleName) { + var _loop_3 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); @@ -118990,7 +122845,7 @@ var ts; }; for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { var moduleName = _c[_b]; - _loop_2(moduleName); + _loop_3(moduleName); } } if (!foundGlobal) { @@ -119237,6 +123092,7 @@ var ts; SymbolOriginInfoKind[SymbolOriginInfoKind["Export"] = 4] = "Export"; SymbolOriginInfoKind[SymbolOriginInfoKind["Promise"] = 8] = "Promise"; SymbolOriginInfoKind[SymbolOriginInfoKind["Nullable"] = 16] = "Nullable"; + SymbolOriginInfoKind[SymbolOriginInfoKind["ResolvedExport"] = 32] = "ResolvedExport"; SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberNoExport"] = 2] = "SymbolMemberNoExport"; SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberExport"] = 6] = "SymbolMemberExport"; })(SymbolOriginInfoKind || (SymbolOriginInfoKind = {})); @@ -119249,8 +123105,14 @@ var ts; function originIsExport(origin) { return !!(origin && origin.kind & 4 /* Export */); } + function originIsResolvedExport(origin) { + return !!(origin && origin.kind === 32 /* ResolvedExport */); + } + function originIncludesSymbolName(origin) { + return originIsExport(origin) || originIsResolvedExport(origin); + } function originIsPackageJsonImport(origin) { - return originIsExport(origin) && !!origin.isFromPackageJson; + return (originIsExport(origin) || originIsResolvedExport(origin)) && !!origin.isFromPackageJson; } function originIsPromise(origin) { return !!(origin.kind & 8 /* Promise */); @@ -119276,52 +123138,6 @@ var ts; GlobalsSearch[GlobalsSearch["Success"] = 1] = "Success"; GlobalsSearch[GlobalsSearch["Fail"] = 2] = "Fail"; })(GlobalsSearch || (GlobalsSearch = {})); - function createImportSuggestionsForFileCache() { - var cache; - var projectVersion; - var fileName; - return { - isEmpty: function () { - return !cache; - }, - clear: function () { - cache = undefined; - fileName = undefined; - projectVersion = undefined; - }, - set: function (file, suggestions, version) { - cache = suggestions; - fileName = file; - if (version) { - projectVersion = version; - } - }, - get: function (file, checker, version) { - if (file !== fileName) { - return undefined; - } - if (version) { - return projectVersion === version ? cache : undefined; - } - ts.forEach(cache, function (suggestion) { - var _a, _b, _c; - // If the symbol/moduleSymbol was a merged symbol, it will have a new identity - // in the checker, even though the symbols to merge are the same (guaranteed by - // cache invalidation in synchronizeHostData). - if ((_a = suggestion.symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) { - suggestion.symbol = checker.getMergedSymbol(suggestion.origin.isDefaultExport - ? (_b = suggestion.symbol.declarations[0].localSymbol) !== null && _b !== void 0 ? _b : suggestion.symbol.declarations[0].symbol - : suggestion.symbol.declarations[0].symbol); - } - if ((_c = suggestion.origin.moduleSymbol.declarations) === null || _c === void 0 ? void 0 : _c.length) { - suggestion.origin.moduleSymbol = checker.getMergedSymbol(suggestion.origin.moduleSymbol.declarations[0].symbol); - } - }); - return cache; - }, - }; - } - Completions.createImportSuggestionsForFileCache = createImportSuggestionsForFileCache; function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); @@ -119329,6 +123145,13 @@ var ts; if (triggerCharacter && !ts.isInString(sourceFile, position, contextToken) && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) { return undefined; } + if (triggerCharacter === " ") { + // `isValidTrigger` ensures we are at `import |` + if (preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) { + return { isGlobalCompletion: true, isMemberCompletion: false, isNewIdentifierLocation: true, isIncomplete: true, entries: [] }; + } + return undefined; + } var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, contextToken, typeChecker, compilerOptions, host, log, preferences); if (stringCompletions) { return stringCompletions; @@ -119352,6 +123175,8 @@ var ts; return jsdocCompletionInfo(ts.JsDoc.getJSDocTagCompletions()); case 3 /* JsDocParameterName */: return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag)); + case 4 /* Keywords */: + return specificKeywordCompletionInfo(completionData.keywords); default: return ts.Debug.assertNever(completionData); } @@ -119360,33 +123185,36 @@ var ts; function jsdocCompletionInfo(entries) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } + function specificKeywordCompletionInfo(keywords) { + return { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: false, + entries: keywords.map(function (k) { return ({ + name: ts.tokenToString(k), + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, + sortText: SortText.GlobalsOrKeywords, + }); }), + }; + } function getOptionalReplacementSpan(location) { // StringLiteralLike locations are handled separately in stringCompletions.ts return (location === null || location === void 0 ? void 0 : location.kind) === 78 /* Identifier */ ? ts.createTextSpanFromNode(location) : undefined; } function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { - var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextMap = completionData.symbolToSortTextMap; - if (location && location.parent && ts.isJsxClosingElement(location.parent)) { - // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, - // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. - // For example: - // var x =
" with type any - // And at `
` (with a closing `>`), the completion list will contain "div". - var tagName = location.parent.parent.openingElement.tagName; - var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 31 /* GreaterThanToken */, sourceFile); - var entry = { - name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), - kind: "class" /* classElement */, - kindModifiers: undefined, - sortText: SortText.LocationPriority, - }; - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, optionalReplacementSpan: getOptionalReplacementSpan(location), entries: [entry] }; + var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation, isJsxIdentifierExpected = completionData.isJsxIdentifierExpected, importCompletionNode = completionData.importCompletionNode, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextMap = completionData.symbolToSortTextMap; + // Verify if the file is JSX language variant + if (ts.getLanguageVariant(sourceFile.scriptKind) === 1 /* JSX */) { + var completionInfo = getJsxClosingTagCompletion(location, sourceFile); + if (completionInfo) { + return completionInfo; + } } var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, - /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); + /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { @@ -119394,7 +123222,7 @@ var ts; return undefined; } getCompletionEntriesFromSymbols(symbols, entries, - /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); + /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); } if (keywordFilters !== 0 /* None */) { var entryNames = new ts.Set(entries.map(function (e) { return e.name; })); @@ -119430,6 +123258,49 @@ var ts; return false; } } + function getJsxClosingTagCompletion(location, sourceFile) { + // We wanna walk up the tree till we find a JSX closing element + var jsxClosingElement = ts.findAncestor(location, function (node) { + switch (node.kind) { + case 277 /* JsxClosingElement */: + return true; + case 43 /* SlashToken */: + case 31 /* GreaterThanToken */: + case 78 /* Identifier */: + case 202 /* PropertyAccessExpression */: + return false; + default: + return "quit"; + } + }); + if (jsxClosingElement) { + // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, + // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. + // For example: + // var x =
" with type any + // And at `
` (with a closing `>`), the completion list will contain "div". + // And at property access expressions ` ` the completion will + // return full closing tag with an optional replacement span + // For example: + // var x = + // var y = + // the completion list at "1" and "2" will contain "MainComponent.Child" with a replacement span of closing tag name + var hasClosingAngleBracket = !!ts.findChildOfKind(jsxClosingElement, 31 /* GreaterThanToken */, sourceFile); + var tagName = jsxClosingElement.parent.openingElement.tagName; + var closingTag = tagName.getText(sourceFile); + var fullClosingTag = closingTag + (hasClosingAngleBracket ? "" : ">"); + var replacementSpan = ts.createTextSpanFromNode(jsxClosingElement.tagName); + var entry = { + name: fullClosingTag, + kind: "class" /* classElement */, + kindModifiers: undefined, + sortText: SortText.LocationPriority, + }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, optionalReplacementSpan: replacementSpan, entries: [entry] }; + } + return; + } function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location @@ -119456,9 +123327,13 @@ var ts; function createCompletionEntryForLiteral(sourceFile, preferences, literal) { return { name: completionNameForLiteral(sourceFile, preferences, literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority }; } - function createCompletionEntry(symbol, sortText, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { + function createCompletionEntry(symbol, sortText, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, options, preferences) { + var _a; var insertText; var replacementSpan = ts.getReplacementSpanForContextToken(contextToken); + var data; + var isSnippet; + var sourceDisplay; var insertQuestionDot = origin && originIsNullableMember(origin); var useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; if (origin && originIsThisType(origin)) { @@ -119502,9 +123377,24 @@ var ts; insertText = needsConvertPropertyAccess ? "" + awaitText + insertText : "" + awaitText + (insertQuestionDot ? "?." : ".") + insertText; replacementSpan = ts.createTextSpanFromBounds(propertyAccessToConvert.getStart(sourceFile), propertyAccessToConvert.end); } + if (originIsResolvedExport(origin)) { + ts.Debug.assertIsDefined(importCompletionNode); + (_a = getInsertTextAndReplacementSpanForImportCompletion(name, importCompletionNode, origin, useSemicolons, options, preferences), insertText = _a.insertText, replacementSpan = _a.replacementSpan); + sourceDisplay = [ts.textPart(origin.moduleSpecifier)]; + isSnippet = preferences.includeCompletionsWithSnippetText ? true : undefined; + } if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { return undefined; } + if (originIsExport(origin) || originIsResolvedExport(origin)) { + data = { + exportName: origin.exportName, + fileName: origin.fileName, + ambientModuleName: origin.fileName ? undefined : ts.stripQuotes(origin.moduleSymbol.name), + isPackageJsonImport: origin.isFromPackageJson ? true : undefined, + moduleSpecifier: originIsResolvedExport(origin) ? origin.moduleSpecifier : undefined, + }; + } // TODO(drosen): Right now we just permit *all* semantic meanings when calling // 'getSymbolKind' which is permissible given that it is backwards compatible; but // really we should consider passing the meaning for the node so that we don't report @@ -119522,8 +123412,29 @@ var ts; isRecommended: isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker) || undefined, insertText: insertText, replacementSpan: replacementSpan, + sourceDisplay: sourceDisplay, + isSnippet: isSnippet, isPackageJsonImport: originIsPackageJsonImport(origin) || undefined, - }; + isImportStatementCompletion: originIsResolvedExport(origin) || undefined, + data: data, + }; + } + function getInsertTextAndReplacementSpanForImportCompletion(name, importCompletionNode, origin, useSemicolons, options, preferences) { + var sourceFile = importCompletionNode.getSourceFile(); + var replacementSpan = ts.createTextSpanFromNode(importCompletionNode, sourceFile); + var quotedModuleSpecifier = ts.quote(sourceFile, preferences, origin.moduleSpecifier); + var exportKind = origin.isDefaultExport ? 1 /* Default */ : + origin.exportName === "export=" /* ExportEquals */ ? 2 /* ExportEquals */ : + 0 /* Named */; + var tabStop = preferences.includeCompletionsWithSnippetText ? "$1" : ""; + var importKind = ts.codefix.getImportKind(sourceFile, exportKind, options); + var suffix = useSemicolons ? ";" : ""; + switch (importKind) { + case 3 /* CommonJS */: return { replacementSpan: replacementSpan, insertText: "import " + name + tabStop + " = require(" + quotedModuleSpecifier + ")" + suffix }; + case 1 /* Default */: return { replacementSpan: replacementSpan, insertText: "import " + name + tabStop + " from " + quotedModuleSpecifier + suffix }; + case 2 /* Namespace */: return { replacementSpan: replacementSpan, insertText: "import * as " + name + tabStop + " from " + quotedModuleSpecifier + suffix }; + case 0 /* Named */: return { replacementSpan: replacementSpan, insertText: "import { " + name + tabStop + " } from " + quotedModuleSpecifier + suffix }; + } } function quotePropertyName(sourceFile, preferences, name) { if (/^\d+$/.test(name)) { @@ -119539,29 +123450,31 @@ var ts; if (originIsExport(origin)) { return ts.stripQuotes(origin.moduleSymbol.name); } + if (originIsResolvedExport(origin)) { + return origin.moduleSpecifier; + } if ((origin === null || origin === void 0 ? void 0 : origin.kind) === 1 /* ThisType */) { return CompletionSource.ThisProperty; } } - function getCompletionEntriesFromSymbols(symbols, entries, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) { + function getCompletionEntriesFromSymbols(symbols, entries, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) { var start = ts.timestamp(); + var variableDeclaration = getVariableDeclaration(location); + var useSemicolons = ts.probablyUsesSemicolons(sourceFile); // Tracks unique names. // Value is set to false for global variables or completions from external module exports, because we can have multiple of those; // true otherwise. Based on the order we add things we will always see locals first, then globals, then module exports. // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. var uniques = new ts.Map(); - for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { - var symbol = symbols_1[_i]; - var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; + for (var i = 0; i < symbols.length; i++) { + var symbol = symbols[i]; + var origin = symbolToOriginInfoMap === null || symbolToOriginInfoMap === void 0 ? void 0 : symbolToOriginInfoMap[i]; var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, !!jsxIdentifierExpected); - if (!info) { + if (!info || uniques.get(info.name) || kind === 1 /* Global */ && symbolToSortTextMap && !shouldIncludeSymbol(symbol, symbolToSortTextMap)) { continue; } var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; - if (uniques.get(name)) { - continue; - } - var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); + var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, compilerOptions, preferences); if (!entry) { continue; } @@ -119578,6 +123491,46 @@ var ts; has: function (name) { return uniques.has(name); }, add: function (name) { return uniques.set(name, true); }, }; + function shouldIncludeSymbol(symbol, symbolToSortTextMap) { + if (!ts.isSourceFile(location)) { + // export = /**/ here we want to get all meanings, so any symbol is ok + if (ts.isExportAssignment(location.parent)) { + return true; + } + // Filter out variables from their own initializers + // `const a = /* no 'a' here */` + if (variableDeclaration && symbol.valueDeclaration === variableDeclaration) { + return false; + } + // External modules can have global export declarations that will be + // available as global keywords in all scopes. But if the external module + // already has an explicit export and user only wants to user explicit + // module imports then the global keywords will be filtered out so auto + // import suggestions will win in the completion + var symbolOrigin = ts.skipAlias(symbol, typeChecker); + // We only want to filter out the global keywords + // Auto Imports are not available for scripts so this conditional is always false + if (!!sourceFile.externalModuleIndicator + && !compilerOptions.allowUmdGlobalAccess + && symbolToSortTextMap[ts.getSymbolId(symbol)] === SortText.GlobalsOrKeywords + && (symbolToSortTextMap[ts.getSymbolId(symbolOrigin)] === SortText.AutoImportSuggestions + || symbolToSortTextMap[ts.getSymbolId(symbolOrigin)] === SortText.LocationPriority)) { + return false; + } + // Continue with origin symbol + symbol = symbolOrigin; + // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) + if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { + return !!(symbol.flags & 1920 /* Namespace */); + } + if (isTypeOnlyLocation) { + // It's a type, but you can reach it by namespace.type as well + return symbolCanBeReferencedAtTypeLocation(symbol, typeChecker); + } + } + // expressions are value space (which includes the value namespaces) + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 111551 /* Value */); + } } Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; function getLabelCompletionAtPosition(node) { @@ -119611,6 +123564,20 @@ var ts; return entries; } function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences) { + if (entryId.data) { + var autoImport = getAutoImportSymbolFromCompletionEntryData(entryId.name, entryId.data, program, host); + if (autoImport) { + return { + type: "symbol", + symbol: autoImport.symbol, + location: ts.getTouchingPropertyName(sourceFile, position), + previousToken: ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined), + isJsxInitializer: false, + isTypeOnlyLocation: false, + origin: autoImport.origin, + }; + } + } var compilerOptions = program.getCompilerOptions(); var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId, host); if (!completionData) { @@ -119627,11 +123594,11 @@ var ts; // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - return ts.firstDefined(symbols, function (symbol) { - var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + return ts.firstDefined(symbols, function (symbol, index) { + var origin = symbolToOriginInfoMap[index]; var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind, completionData.isJsxIdentifierExpected); return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source - ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation } + ? { type: "symbol", symbol: symbol, location: location, origin: origin, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation } : undefined; }) || { type: "none" }; } @@ -119641,7 +123608,7 @@ var ts; var name = entryId.name; var contextToken = ts.findPrecedingToken(position, sourceFile); if (ts.isInString(sourceFile, position, contextToken)) { - return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken); + return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken, preferences); } // Compute all the completion symbols again. var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences); @@ -119655,13 +123622,15 @@ var ts; return ts.JsDoc.getJSDocTagCompletionDetails(name); case 3 /* JsDocParameterName */: return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); + case 4 /* Keywords */: + return request.keywords.indexOf(ts.stringToToken(name)) > -1 ? createSimpleDetails(name, "keyword" /* keyword */, ts.SymbolDisplayPartKind.keyword) : undefined; default: return ts.Debug.assertNever(request); } } case "symbol": { - var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, origin = symbolCompletion.origin, previousToken = symbolCompletion.previousToken; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(origin, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, entryId.data), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } case "literal": { @@ -119687,15 +123656,17 @@ var ts; } Completions.createCompletionDetailsForSymbol = createCompletionDetailsForSymbol; function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { - return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; + return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source, sourceDisplay: source }; } Completions.createCompletionDetails = createCompletionDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) { - var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { + function getCompletionEntryCodeActionsAndSourceDisplay(origin, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data) { + if (data === null || data === void 0 ? void 0 : data.moduleSpecifier) { + return { codeActions: undefined, sourceDisplay: [ts.textPart(data.moduleSpecifier)] }; + } + if (!origin || !originIsExport(origin)) { return { codeActions: undefined, sourceDisplay: undefined }; } - var moduleSymbol = symbolOriginInfo.moduleSymbol; + var moduleSymbol = origin.moduleSymbol; var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, compilerOptions.target), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; @@ -119711,6 +123682,7 @@ var ts; CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName"; CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag"; CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName"; + CompletionDataKind[CompletionDataKind["Keywords"] = 4] = "Keywords"; })(CompletionDataKind || (CompletionDataKind = {})); var CompletionKind; (function (CompletionKind) { @@ -119738,11 +123710,11 @@ var ts; return ts.getContextualTypeFromParent(previousToken, checker); case 62 /* EqualsToken */: switch (parent.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return checker.getContextualType(parent.initializer); // TODO: GH#18217 - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return checker.getTypeAtLocation(parent.left); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return checker.getContextualTypeForJsxAttribute(parent); default: return undefined; @@ -119752,7 +123724,7 @@ var ts; case 81 /* CaseKeyword */: return ts.getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); case 18 /* OpenBraceToken */: - return ts.isJsxExpression(parent) && parent.parent.kind !== 273 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; + return ts.isJsxExpression(parent) && parent.parent.kind !== 274 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; default: var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile); return argInfo ? @@ -119771,7 +123743,8 @@ var ts; return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); } function isModuleSymbol(symbol) { - return symbol.declarations.some(function (d) { return d.kind === 297 /* SourceFile */; }); + var _a; + return !!((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d.kind === 298 /* SourceFile */; })); } function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId, host) { var typeChecker = program.getTypeChecker(); @@ -119822,11 +123795,11 @@ var ts; if (tag.tagName.pos <= position && position <= tag.tagName.end) { return { kind: 1 /* JsDocTagName */ }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 301 /* JSDocTypeExpression */) { + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 302 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 333 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 337 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -119851,7 +123824,7 @@ var ts; var contextToken = previousToken; // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. - if (contextToken && position <= contextToken.end && (ts.isIdentifierOrPrivateIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { + if (contextToken && position <= contextToken.end && (ts.isMemberName(contextToken) || ts.isKeyword(contextToken.kind))) { var start_1 = ts.timestamp(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1)); @@ -119867,10 +123840,22 @@ var ts; var isStartingCloseTag = false; var isJsxInitializer = false; var isJsxIdentifierExpected = false; + var importCompletionNode; var location = ts.getTouchingPropertyName(sourceFile, position); if (contextToken) { + var importCompletionCandidate = getImportCompletionNode(contextToken); + if (importCompletionCandidate === 153 /* FromKeyword */) { + return { kind: 4 /* Keywords */, keywords: [153 /* FromKeyword */] }; + } + // Import statement completions use `insertText`, and also require the `data` property of `CompletionEntryIdentifier` + // added in TypeScript 4.3 to be sent back from the client during `getCompletionEntryDetails`. Since this feature + // is not backward compatible with older clients, the language service defaults to disabling it, allowing newer clients + // to opt in with the `includeCompletionsForImportStatements` user preference. + if (importCompletionCandidate && preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) { + importCompletionNode = importCompletionCandidate; + } // Bail out if this is a known invalid completion location - if (isCompletionListBlocker(contextToken)) { + if (!importCompletionNode && isCompletionListBlocker(contextToken)) { log("Returning an empty list because completion was requested in an invalid position."); return undefined; } @@ -119879,7 +123864,7 @@ var ts; isRightOfDot = contextToken.kind === 24 /* DotToken */; isRightOfQuestionDot = contextToken.kind === 28 /* QuestionDotToken */; switch (parent.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: propertyAccessToConvert = parent; node = propertyAccessToConvert.expression; if ((ts.isCallExpression(node) || ts.isFunctionLike(node)) && @@ -119892,14 +123877,14 @@ var ts; return undefined; } break; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: node = parent.left; break; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: node = parent.name; break; - case 195 /* ImportType */: - case 226 /* MetaProperty */: + case 196 /* ImportType */: + case 227 /* MetaProperty */: node = parent; break; default: @@ -119908,11 +123893,11 @@ var ts; return undefined; } } - else if (sourceFile.languageVariant === 1 /* JSX */) { + else if (!importCompletionNode && sourceFile.languageVariant === 1 /* JSX */) { // // If the tagname is a property access expression, we will then walk up to the top most of property access expression. // Then, try to get a JSX container and its associated attributes type. - if (parent && parent.kind === 201 /* PropertyAccessExpression */) { + if (parent && parent.kind === 202 /* PropertyAccessExpression */) { contextToken = parent; parent = parent.parent; } @@ -119920,45 +123905,45 @@ var ts; if (currentToken.parent === location) { switch (currentToken.kind) { case 31 /* GreaterThanToken */: - if (currentToken.parent.kind === 273 /* JsxElement */ || currentToken.parent.kind === 275 /* JsxOpeningElement */) { + if (currentToken.parent.kind === 274 /* JsxElement */ || currentToken.parent.kind === 276 /* JsxOpeningElement */) { location = currentToken; } break; case 43 /* SlashToken */: - if (currentToken.parent.kind === 274 /* JsxSelfClosingElement */) { + if (currentToken.parent.kind === 275 /* JsxSelfClosingElement */) { location = currentToken; } break; } } switch (parent.kind) { - case 276 /* JsxClosingElement */: + case 277 /* JsxClosingElement */: if (contextToken.kind === 43 /* SlashToken */) { isStartingCloseTag = true; location = contextToken; } break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (!binaryExpressionMayBeOpenTag(parent)) { break; } // falls through - case 274 /* JsxSelfClosingElement */: - case 273 /* JsxElement */: - case 275 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + case 274 /* JsxElement */: + case 276 /* JsxOpeningElement */: isJsxIdentifierExpected = true; if (contextToken.kind === 29 /* LessThanToken */) { isRightOfOpenTag = true; location = contextToken; } break; - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: // For `
`, `parent` will be `{true}` and `previousToken` will be `}` if (previousToken.kind === 19 /* CloseBraceToken */ && currentToken.kind === 31 /* GreaterThanToken */) { isJsxIdentifierExpected = true; } break; - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: // For `
`, `parent` will be JsxAttribute and `previousToken` will be its initializer if (parent.initializer === previousToken && previousToken.end < position) { @@ -119992,8 +123977,11 @@ var ts; var symbols = []; var symbolToOriginInfoMap = []; var symbolToSortTextMap = []; - var importSuggestionsCache = host.getImportSuggestionsCache && host.getImportSuggestionsCache(); + var seenPropertySymbols = new ts.Map(); var isTypeOnly = isTypeOnlyCompletion(); + var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { + return ts.createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); + }); if (isRightOfDot || isRightOfQuestionDot) { getTypeScriptMemberSymbols(); } @@ -120002,7 +123990,7 @@ var ts; ts.Debug.assertEachIsDefined(tagSymbols, "getJsxIntrinsicTagNames() should all be defined"); tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); - completionKind = 3 /* MemberLike */; + completionKind = 1 /* Global */; keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { @@ -120011,7 +123999,7 @@ var ts; if (tagSymbol) { symbols = [tagSymbol]; } - completionKind = 3 /* MemberLike */; + completionKind = 1 /* Global */; keywordFilters = 0 /* None */; } else { @@ -120044,14 +124032,15 @@ var ts; symbolToSortTextMap: symbolToSortTextMap, isTypeOnlyLocation: isTypeOnly, isJsxIdentifierExpected: isJsxIdentifierExpected, + importCompletionNode: importCompletionNode, }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 326 /* JSDocParameterTag */: - case 333 /* JSDocPropertyTag */: - case 327 /* JSDocReturnTag */: - case 329 /* JSDocTypeTag */: - case 331 /* JSDocTypedefTag */: + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: + case 331 /* JSDocReturnTag */: + case 333 /* JSDocTypeTag */: + case 335 /* JSDocTypedefTag */: return true; default: return false; @@ -120079,10 +124068,10 @@ var ts; var exportedSymbols = typeChecker.getExportsOfModule(symbol); ts.Debug.assertEachIsDefined(exportedSymbols, "getExportsOfModule() should all be defined"); var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess(isImportType ? node : (node.parent), symbol.name); }; - var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; + var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol, typeChecker); }; var isValidAccess = isNamespaceName // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion. - ? function (symbol) { return !!(symbol.flags & 1920 /* Namespace */) && !symbol.declarations.every(function (d) { return d.parent === node.parent; }); } + ? function (symbol) { var _a; return !!(symbol.flags & 1920 /* Namespace */) && !((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return d.parent === node.parent; })); } : isRhsOfImportDeclaration ? // Any kind is allowed when dotting off namespace in internal import equals declaration function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : @@ -120096,7 +124085,7 @@ var ts; // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). if (!isTypeLocation && symbol.declarations && - symbol.declarations.some(function (d) { return d.kind !== 297 /* SourceFile */ && d.kind !== 256 /* ModuleDeclaration */ && d.kind !== 255 /* EnumDeclaration */; })) { + symbol.declarations.some(function (d) { return d.kind !== 298 /* SourceFile */ && d.kind !== 257 /* ModuleDeclaration */ && d.kind !== 256 /* EnumDeclaration */; })) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { @@ -120143,7 +124132,7 @@ var ts; if (isRightOfQuestionDot && ts.some(type.getCallSignatures())) { isNewIdentifierLocation = true; } - var propertyAccess = node.kind === 195 /* ImportType */ ? node : node.parent; + var propertyAccess = node.kind === 196 /* ImportType */ ? node : node.parent; if (isUncheckedFile) { // In javascript files, for union types, we don't just get the members that // the individual types have in common, we also include all the members that @@ -120182,13 +124171,24 @@ var ts; var nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName); // If this is nested like for `namespace N { export const sym = Symbol(); }`, we'll add the completion for `N`. var firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker); - if (firstAccessibleSymbol && !symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)]) { + if (firstAccessibleSymbol && ts.addToSeen(seenPropertySymbols, ts.getSymbolId(firstAccessibleSymbol))) { + var index = symbols.length; symbols.push(firstAccessibleSymbol); var moduleSymbol = firstAccessibleSymbol.parent; - symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] = - !moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol) - ? { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) } - : { kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), moduleSymbol: moduleSymbol, isDefaultExport: false }; + if (!moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol)) { + symbolToOriginInfoMap[index] = { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) }; + } + else { + var origin = { + kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), + moduleSymbol: moduleSymbol, + isDefaultExport: false, + symbolName: firstAccessibleSymbol.name, + exportName: firstAccessibleSymbol.name, + fileName: ts.isExternalModuleNameRelative(ts.stripQuotes(moduleSymbol.name)) ? ts.cast(moduleSymbol.valueDeclaration, ts.isSourceFile).fileName : undefined, + }; + symbolToOriginInfoMap[index] = origin; + } } else if (preferences.includeCompletionsWithInsertText) { addSymbolOriginInfo(symbol); @@ -120208,11 +124208,11 @@ var ts; } function addSymbolOriginInfo(symbol) { if (preferences.includeCompletionsWithInsertText) { - if (insertAwait && !symbolToOriginInfoMap[ts.getSymbolId(symbol)]) { - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: getNullableSymbolOriginInfoKind(8 /* Promise */) }; + if (insertAwait && ts.addToSeen(seenPropertySymbols, ts.getSymbolId(symbol))) { + symbolToOriginInfoMap[symbols.length] = { kind: getNullableSymbolOriginInfoKind(8 /* Promise */) }; } else if (insertQuestionDot) { - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 16 /* Nullable */ }; + symbolToOriginInfoMap[symbols.length] = { kind: 16 /* Nullable */ }; } } } @@ -120225,7 +124225,9 @@ var ts; return ts.isIdentifier(e) ? e : ts.isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : undefined; } function tryGetGlobalSymbols() { - var result = tryGetObjectLikeCompletionSymbols() + var result = tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() + || tryGetObjectLikeCompletionSymbols() + || tryGetImportCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() || tryGetLocalNamedExportCompletionSymbols() || tryGetConstructorCompletion() @@ -120258,11 +124260,17 @@ var ts; isNewIdentifierLocation = false; return 1 /* Success */; } + function tryGetImportCompletionSymbols() { + if (!importCompletionNode) + return 0 /* Continue */; + collectAutoImports(/*resolveModuleSpecifiers*/ true); + return 1 /* Success */; + } function getGlobalCompletions() { keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; - isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); + isNewIdentifierLocation = isNewIdentifierDefinitionLocation(); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); } @@ -120299,50 +124307,36 @@ var ts; var symbolMeanings = (isTypeOnly ? 0 /* None */ : 111551 /* Value */) | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); ts.Debug.assertEachIsDefined(symbols, "getSymbolsInScope() should all be defined"); - for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { - var symbol = symbols_2[_i]; + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; if (!typeChecker.isArgumentsSymbol(symbol) && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === sourceFile; })) { symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.GlobalsOrKeywords; } } // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` - if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 297 /* SourceFile */) { + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 298 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { for (var _a = 0, _b = getPropertiesForCompletion(thisType, typeChecker); _a < _b.length; _a++) { var symbol = _b[_a]; - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 1 /* ThisType */ }; + symbolToOriginInfoMap[symbols.length] = { kind: 1 /* ThisType */ }; symbols.push(symbol); symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.SuggestedClassMembers; } } } - if (shouldOfferImportCompletions()) { - var lowerCaseTokenText_1 = previousToken && ts.isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; - var autoImportSuggestions = getSymbolsFromOtherSourceFileExports(program.getCompilerOptions().target, host); - if (!detailsEntryId && importSuggestionsCache) { - importSuggestionsCache.set(sourceFile.fileName, autoImportSuggestions, host.getProjectVersion && host.getProjectVersion()); - } - autoImportSuggestions.forEach(function (_a) { - var symbol = _a.symbol, symbolName = _a.symbolName, skipFilter = _a.skipFilter, origin = _a.origin; - if (detailsEntryId) { - if (detailsEntryId.source && ts.stripQuotes(origin.moduleSymbol.name) !== detailsEntryId.source) { - return; - } - } - else if (!skipFilter && !stringContainsCharactersInOrder(symbolName.toLowerCase(), lowerCaseTokenText_1)) { - return; - } - var symbolId = ts.getSymbolId(symbol); - symbols.push(symbol); - symbolToOriginInfoMap[symbolId] = origin; - symbolToSortTextMap[symbolId] = SortText.AutoImportSuggestions; - }); + collectAutoImports(/*resolveModuleSpecifier*/ false); + if (isTypeOnly) { + keywordFilters = contextToken && ts.isAssertionExpression(contextToken.parent) + ? 6 /* TypeAssertionKeywords */ + : 7 /* TypeKeywords */; } - filterGlobalCompletion(symbols); } function shouldOfferImportCompletions() { + // If already typing an import statement, provide completions for it. + if (importCompletionNode) + return true; // If current completion is for non-contextual Object literal shortahands, ignore auto-import symbols if (isNonContextualObjectLiteral) return false; @@ -120360,42 +124354,15 @@ var ts; } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { - case 297 /* SourceFile */: - case 218 /* TemplateExpression */: - case 283 /* JsxExpression */: - case 230 /* Block */: + case 298 /* SourceFile */: + case 219 /* TemplateExpression */: + case 284 /* JsxExpression */: + case 231 /* Block */: return true; default: return ts.isStatement(scopeNode); } } - function filterGlobalCompletion(symbols) { - var isTypeOnly = isTypeOnlyCompletion(); - if (isTypeOnly) { - keywordFilters = contextToken && ts.isAssertionExpression(contextToken.parent) - ? 6 /* TypeAssertionKeywords */ - : 7 /* TypeKeywords */; - } - ts.filterMutate(symbols, function (symbol) { - if (!ts.isSourceFile(location)) { - // export = /**/ here we want to get all meanings, so any symbol is ok - if (ts.isExportAssignment(location.parent)) { - return true; - } - symbol = ts.skipAlias(symbol, typeChecker); - // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) - if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { - return !!(symbol.flags & 1920 /* Namespace */); - } - if (isTypeOnly) { - // It's a type, but you can reach it by namespace.type as well - return symbolCanBeReferencedAtTypeLocation(symbol); - } - } - // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 111551 /* Value */); - }); - } function isTypeOnlyCompletion() { return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && @@ -120405,191 +124372,105 @@ var ts; } function isContextTokenValueLocation(contextToken) { return contextToken && - contextToken.kind === 111 /* TypeOfKeyword */ && - (contextToken.parent.kind === 176 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); + ((contextToken.kind === 111 /* TypeOfKeyword */ && + (contextToken.parent.kind === 177 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent))) || + (contextToken.kind === 127 /* AssertsKeyword */ && contextToken.parent.kind === 173 /* TypePredicate */)); } function isContextTokenTypeLocation(contextToken) { if (contextToken) { var parentKind = contextToken.parent.kind; switch (contextToken.kind) { case 58 /* ColonToken */: - return parentKind === 163 /* PropertyDeclaration */ || - parentKind === 162 /* PropertySignature */ || - parentKind === 160 /* Parameter */ || - parentKind === 249 /* VariableDeclaration */ || + return parentKind === 164 /* PropertyDeclaration */ || + parentKind === 163 /* PropertySignature */ || + parentKind === 161 /* Parameter */ || + parentKind === 250 /* VariableDeclaration */ || ts.isFunctionLikeKind(parentKind); case 62 /* EqualsToken */: - return parentKind === 254 /* TypeAliasDeclaration */; + return parentKind === 255 /* TypeAliasDeclaration */; case 126 /* AsKeyword */: - return parentKind === 224 /* AsExpression */; + return parentKind === 225 /* AsExpression */; case 29 /* LessThanToken */: - return parentKind === 173 /* TypeReference */ || - parentKind === 206 /* TypeAssertionExpression */; + return parentKind === 174 /* TypeReference */ || + parentKind === 207 /* TypeAssertionExpression */; case 93 /* ExtendsKeyword */: - return parentKind === 159 /* TypeParameter */; + return parentKind === 160 /* TypeParameter */; } } return false; } - /** True if symbol is a type or a module containing at least one type. */ - function symbolCanBeReferencedAtTypeLocation(symbol, seenModules) { - if (seenModules === void 0) { seenModules = new ts.Map(); } - var sym = ts.skipAlias(symbol.exportSymbol || symbol, typeChecker); - return !!(sym.flags & 788968 /* Type */) || - !!(sym.flags & 1536 /* Module */) && - ts.addToSeen(seenModules, ts.getSymbolId(sym)) && - typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); - } - /** - * Gathers symbols that can be imported from other files, de-duplicating along the way. Symbols can be "duplicates" - * if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but - * it’s just an alias to the first, and both have the same name, so we generally want to filter those aliases out, - * if and only if the the first can be imported (it may be excluded due to package.json filtering in - * `codefix.forEachExternalModuleToImportFrom`). - * - * Example. Imagine a chain of node_modules re-exporting one original symbol: - * - * ```js - * node_modules/x/index.js node_modules/y/index.js node_modules/z/index.js - * +-----------------------+ +--------------------------+ +--------------------------+ - * | | | | | | - * | export const foo = 0; | <--- | export { foo } from 'x'; | <--- | export { foo } from 'y'; | - * | | | | | | - * +-----------------------+ +--------------------------+ +--------------------------+ - * ``` - * - * Also imagine three buckets, which we’ll reference soon: - * - * ```md - * | | | | | | - * | **Bucket A** | | **Bucket B** | | **Bucket C** | - * | Symbols to | | Aliases to symbols | | Symbols to return | - * | definitely | | in Buckets A or C | | if nothing better | - * | return | | (don’t return these) | | comes along | - * |__________________| |______________________| |___________________| - * ``` - * - * We _probably_ want to show `foo` from 'x', but not from 'y' or 'z'. However, if 'x' is not in a package.json, it - * will not appear in a `forEachExternalModuleToImportFrom` iteration. Furthermore, the order of iterations is not - * guaranteed, as it is host-dependent. Therefore, when presented with the symbol `foo` from module 'y' alone, we - * may not be sure whether or not it should go in the list. So, we’ll take the following steps: - * - * 1. Resolve alias `foo` from 'y' to the export declaration in 'x', get the symbol there, and see if that symbol is - * already in Bucket A (symbols we already know will be returned). If it is, put `foo` from 'y' in Bucket B - * (symbols that are aliases to symbols in Bucket A). If it’s not, put it in Bucket C. - * 2. Next, imagine we see `foo` from module 'z'. Again, we resolve the alias to the nearest export, which is in 'y'. - * At this point, if that nearest export from 'y' is in _any_ of the three buckets, we know the symbol in 'z' - * should never be returned in the final list, so put it in Bucket B. - * 3. Next, imagine we see `foo` from module 'x', the original. Syntactically, it doesn’t look like a re-export, so - * we can just check Bucket C to see if we put any aliases to the original in there. If they exist, throw them out. - * Put this symbol in Bucket A. - * 4. After we’ve iterated through every symbol of every module, any symbol left in Bucket C means that step 3 didn’t - * occur for that symbol---that is, the original symbol is not in Bucket A, so we should include the alias. Move - * everything from Bucket C to Bucket A. - */ - function getSymbolsFromOtherSourceFileExports(target, host) { - var cached = importSuggestionsCache && importSuggestionsCache.get(sourceFile.fileName, typeChecker, detailsEntryId && host.getProjectVersion ? host.getProjectVersion() : undefined); - if (cached) { - log("getSymbolsFromOtherSourceFileExports: Using cached list"); - return cached; - } - var startTime = ts.timestamp(); - log("getSymbolsFromOtherSourceFileExports: Recomputing list" + (detailsEntryId ? " for details entry" : "")); - var seenResolvedModules = new ts.Map(); - var seenExports = new ts.Map(); - /** Bucket B */ - var aliasesToAlreadyIncludedSymbols = new ts.Map(); - /** Bucket C */ - var aliasesToReturnIfOriginalsAreMissing = new ts.Map(); - /** Bucket A */ - var results = []; - /** Ids present in `results` for faster lookup */ - var resultSymbolIds = new ts.Map(); - ts.codefix.forEachExternalModuleToImportFrom(program, host, sourceFile, !detailsEntryId, /*useAutoImportProvider*/ true, function (moduleSymbol, _, program, isFromPackageJson) { - // Perf -- ignore other modules if this is a request for details - if (detailsEntryId && detailsEntryId.source && ts.stripQuotes(moduleSymbol.name) !== detailsEntryId.source) { - return; - } - var typeChecker = program.getTypeChecker(); - var resolvedModuleSymbol = typeChecker.resolveExternalModuleSymbol(moduleSymbol); - // resolvedModuleSymbol may be a namespace. A namespace may be `export =` by multiple module declarations, but only keep the first one. - if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { + /** Mutates `symbols`, `symbolToOriginInfoMap`, and `symbolToSortTextMap` */ + function collectAutoImports(resolveModuleSpecifiers) { + var _a, _b, _c, _d, _e; + if (!shouldOfferImportCompletions()) + return; + ts.Debug.assert(!(detailsEntryId === null || detailsEntryId === void 0 ? void 0 : detailsEntryId.data)); + var start = ts.timestamp(); + var moduleSpecifierCache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); + (_b = host.log) === null || _b === void 0 ? void 0 : _b.call(host, "collectAutoImports: starting, " + (resolveModuleSpecifiers ? "" : "not ") + "resolving module specifiers"); + if (moduleSpecifierCache) { + (_c = host.log) === null || _c === void 0 ? void 0 : _c.call(host, "collectAutoImports: module specifier cache size: " + moduleSpecifierCache.count()); + } + var lowerCaseTokenText = previousToken && ts.isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; + var exportInfo = ts.codefix.getSymbolToExportInfoMap(sourceFile, host, program); + var packageJsonAutoImportProvider = (_d = host.getPackageJsonAutoImportProvider) === null || _d === void 0 ? void 0 : _d.call(host); + var packageJsonFilter = detailsEntryId ? undefined : ts.createPackageJsonImportFilter(sourceFile, host); + exportInfo.forEach(function (info, key) { + var symbolName = key.substring(0, key.indexOf("|")); + if (!detailsEntryId && ts.isStringANonContextualKeyword(symbolName)) return; + var isCompletionDetailsMatch = detailsEntryId && ts.some(info, function (i) { return detailsEntryId.source === ts.stripQuotes(i.moduleSymbol.name); }); + if (isCompletionDetailsMatch || isNameMatch(symbolName)) { + // If we don't need to resolve module specifiers, we can use any re-export that is importable at all + // (We need to ensure that at least one is importable to show a completion.) + var _a = resolveModuleSpecifiers + ? ts.codefix.getModuleSpecifierForBestExportInfo(info, sourceFile, program, host, preferences) + : { moduleSpecifier: undefined, exportInfo: ts.find(info, isImportableExportInfo) }, moduleSpecifier = _a.moduleSpecifier, exportInfo_1 = _a.exportInfo; + if (!exportInfo_1) + return; + var moduleFile = ts.tryCast(exportInfo_1.moduleSymbol.valueDeclaration, ts.isSourceFile); + var isDefaultExport = exportInfo_1.exportKind === 1 /* Default */; + var symbol = isDefaultExport && ts.getLocalSymbolForExportDefault(exportInfo_1.symbol) || exportInfo_1.symbol; + pushAutoImportSymbol(symbol, { + kind: resolveModuleSpecifiers ? 32 /* ResolvedExport */ : 4 /* Export */, + moduleSpecifier: moduleSpecifier, + symbolName: symbolName, + exportName: exportInfo_1.exportKind === 2 /* ExportEquals */ ? "export=" /* ExportEquals */ : exportInfo_1.symbol.name, + fileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, + isDefaultExport: isDefaultExport, + moduleSymbol: exportInfo_1.moduleSymbol, + isFromPackageJson: exportInfo_1.isFromPackageJson, + }); } - // Don't add another completion for `export =` of a symbol that's already global. - // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. - if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, ts.isNonGlobalDeclaration)) { - pushSymbol(resolvedModuleSymbol, moduleSymbol, isFromPackageJson, /*skipFilter*/ true); - } - for (var _i = 0, _a = typeChecker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { - var symbol = _a[_i]; - var symbolId = ts.getSymbolId(symbol).toString(); - // `getExportsAndPropertiesOfModule` can include duplicates - if (!ts.addToSeen(seenExports, symbolId)) { - continue; - } - // If this is `export { _break as break };` (a keyword) -- skip this and prefer the keyword completion. - if (ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.propertyName && ts.isIdentifierANonContextualKeyword(d.name); })) { - continue; - } - // If `symbol.parent !== moduleSymbol`, this is an `export * from "foo"` re-export. Those don't create new symbols. - var isExportStarFromReExport = typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol; - // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). - if (isExportStarFromReExport || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !d.propertyName && !!d.parent.parent.moduleSpecifier; })) { - // Walk the export chain back one module (step 1 or 2 in diagrammed example). - // Or, in the case of `export * from "foo"`, `symbol` already points to the original export, so just use that. - var nearestExportSymbol = isExportStarFromReExport ? symbol : getNearestExportSymbol(symbol); - if (!nearestExportSymbol) - continue; - var nearestExportSymbolId = ts.getSymbolId(nearestExportSymbol).toString(); - var symbolHasBeenSeen = resultSymbolIds.has(nearestExportSymbolId) || aliasesToAlreadyIncludedSymbols.has(nearestExportSymbolId); - if (!symbolHasBeenSeen) { - aliasesToReturnIfOriginalsAreMissing.set(nearestExportSymbolId, { alias: symbol, moduleSymbol: moduleSymbol, isFromPackageJson: isFromPackageJson }); - aliasesToAlreadyIncludedSymbols.set(symbolId, true); - } - else { - // Perf - we know this symbol is an alias to one that’s already covered in `symbols`, so store it here - // in case another symbol re-exports this one; that way we can short-circuit as soon as we see this symbol id. - ts.addToSeen(aliasesToAlreadyIncludedSymbols, symbolId); - } - } - else { - // This is not a re-export, so see if we have any aliases pending and remove them (step 3 in diagrammed example) - aliasesToReturnIfOriginalsAreMissing.delete(symbolId); - pushSymbol(symbol, moduleSymbol, isFromPackageJson, /*skipFilter*/ false); - } - } - }); - // By this point, any potential duplicates that were actually duplicates have been - // removed, so the rest need to be added. (Step 4 in diagrammed example) - aliasesToReturnIfOriginalsAreMissing.forEach(function (_a) { - var alias = _a.alias, moduleSymbol = _a.moduleSymbol, isFromPackageJson = _a.isFromPackageJson; - return pushSymbol(alias, moduleSymbol, isFromPackageJson, /*skipFilter*/ false); }); - log("getSymbolsFromOtherSourceFileExports: " + (ts.timestamp() - startTime)); - return results; - function pushSymbol(symbol, moduleSymbol, isFromPackageJson, skipFilter) { - var isDefaultExport = symbol.escapedName === "default" /* Default */; - if (isDefaultExport) { - symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; + (_e = host.log) === null || _e === void 0 ? void 0 : _e.call(host, "collectAutoImports: done in " + (ts.timestamp() - start) + " ms"); + function isNameMatch(symbolName) { + var lowerCaseSymbolName = symbolName.toLowerCase(); + if (resolveModuleSpecifiers && lowerCaseTokenText) { + // Use a more restrictive filter if resolving module specifiers since resolving module specifiers is expensive. + return lowerCaseTokenText[0] === lowerCaseSymbolName[0] && stringContainsCharactersInOrder(lowerCaseSymbolName, lowerCaseTokenText); } - if (typeChecker.isUndefinedSymbol(symbol)) { - return; + return stringContainsCharactersInOrder(lowerCaseSymbolName, lowerCaseTokenText); + } + function isImportableExportInfo(info) { + var moduleFile = ts.tryCast(info.moduleSymbol.valueDeclaration, ts.isSourceFile); + if (!moduleFile) { + return packageJsonFilter + ? packageJsonFilter.allowsImportingAmbientModule(info.moduleSymbol, getModuleSpecifierResolutionHost(info.isFromPackageJson)) + : true; } - ts.addToSeen(resultSymbolIds, ts.getSymbolId(symbol)); - var origin = { kind: 4 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport, isFromPackageJson: isFromPackageJson }; - results.push({ - symbol: symbol, - symbolName: ts.getNameForExportedSymbol(symbol, target), - origin: origin, - skipFilter: skipFilter, - }); + return ts.isImportableFile(info.isFromPackageJson ? packageJsonAutoImportProvider : program, sourceFile, moduleFile, packageJsonFilter, getModuleSpecifierResolutionHost(info.isFromPackageJson), moduleSpecifierCache); } } - function getNearestExportSymbol(fromSymbol) { - return findAlias(typeChecker, fromSymbol, function (alias) { - return ts.some(alias.declarations, function (d) { return ts.isExportSpecifier(d) || !!d.localSymbol; }); - }); + function pushAutoImportSymbol(symbol, origin) { + var symbolId = ts.getSymbolId(symbol); + if (symbolToSortTextMap[symbolId] === SortText.GlobalsOrKeywords) { + // If an auto-importable symbol is available as a global, don't add the auto import + return; + } + symbolToOriginInfoMap[symbols.length] = origin; + symbolToSortTextMap[symbolId] = importCompletionNode ? SortText.LocationPriority : SortText.AutoImportSuggestions; + symbols.push(symbol); } /** * True if you could remove some characters in `a` to get `b`. @@ -120601,7 +124482,8 @@ var ts; return true; } var characterIndex = 0; - for (var strIndex = 0; strIndex < str.length; strIndex++) { + var len = str.length; + for (var strIndex = 0; strIndex < len; strIndex++) { if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) { characterIndex++; if (characterIndex === characters.length) { @@ -120637,7 +124519,7 @@ var ts; return true; } if (contextToken.kind === 31 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 275 /* JsxOpeningElement */) { + if (contextToken.parent.kind === 276 /* JsxOpeningElement */) { // Two possibilities: // 1.
/**/ // - contextToken: GreaterThanToken (before cursor) @@ -120647,54 +124529,56 @@ var ts; // - contextToken: GreaterThanToken (before cursor) // - location: GreaterThanToken (after cursor) // - same parent (JSXOpeningElement) - return location.parent.kind !== 275 /* JsxOpeningElement */; + return location.parent.kind !== 276 /* JsxOpeningElement */; } - if (contextToken.parent.kind === 276 /* JsxClosingElement */ || contextToken.parent.kind === 274 /* JsxSelfClosingElement */) { - return !!contextToken.parent.parent && contextToken.parent.parent.kind === 273 /* JsxElement */; + if (contextToken.parent.kind === 277 /* JsxClosingElement */ || contextToken.parent.kind === 275 /* JsxSelfClosingElement */) { + return !!contextToken.parent.parent && contextToken.parent.parent.kind === 274 /* JsxElement */; } } return false; } - function isNewIdentifierDefinitionLocation(previousToken) { - if (previousToken) { - var containingNodeKind = previousToken.parent.kind; + function isNewIdentifierDefinitionLocation() { + if (contextToken) { + var containingNodeKind = contextToken.parent.kind; // Previous token may have been a keyword that was converted to an identifier. - switch (keywordForNode(previousToken)) { + switch (keywordForNode(contextToken)) { case 27 /* CommaToken */: - return containingNodeKind === 203 /* CallExpression */ // func( a, | - || containingNodeKind === 166 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 204 /* NewExpression */ // new C(a, | - || containingNodeKind === 199 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 216 /* BinaryExpression */ // const x = (a, | - || containingNodeKind === 174 /* FunctionType */; // var x: (s: string, list| + return containingNodeKind === 204 /* CallExpression */ // func( a, | + || containingNodeKind === 167 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 205 /* NewExpression */ // new C(a, | + || containingNodeKind === 200 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 217 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 175 /* FunctionType */ // var x: (s: string, list| + || containingNodeKind === 201 /* ObjectLiteralExpression */; // const obj = { x, | case 20 /* OpenParenToken */: - return containingNodeKind === 203 /* CallExpression */ // func( | - || containingNodeKind === 166 /* Constructor */ // constructor( | - || containingNodeKind === 204 /* NewExpression */ // new C(a| - || containingNodeKind === 207 /* ParenthesizedExpression */ // const x = (a| - || containingNodeKind === 186 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + return containingNodeKind === 204 /* CallExpression */ // func( | + || containingNodeKind === 167 /* Constructor */ // constructor( | + || containingNodeKind === 205 /* NewExpression */ // new C(a| + || containingNodeKind === 208 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 187 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ case 22 /* OpenBracketToken */: - return containingNodeKind === 199 /* ArrayLiteralExpression */ // [ | - || containingNodeKind === 171 /* IndexSignature */ // [ | : string ] - || containingNodeKind === 158 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + return containingNodeKind === 200 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 172 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 159 /* ComputedPropertyName */; // [ | /* this can become an index signature */ case 139 /* ModuleKeyword */: // module | case 140 /* NamespaceKeyword */: // namespace | return true; case 24 /* DotToken */: - return containingNodeKind === 256 /* ModuleDeclaration */; // module A.| + return containingNodeKind === 257 /* ModuleDeclaration */; // module A.| case 18 /* OpenBraceToken */: - return containingNodeKind === 252 /* ClassDeclaration */; // class A{ | + return containingNodeKind === 253 /* ClassDeclaration */ // class A { | + || containingNodeKind === 201 /* ObjectLiteralExpression */; // const obj = { | case 62 /* EqualsToken */: - return containingNodeKind === 249 /* VariableDeclaration */ // const x = a| - || containingNodeKind === 216 /* BinaryExpression */; // x = a| + return containingNodeKind === 250 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 217 /* BinaryExpression */; // x = a| case 15 /* TemplateHead */: - return containingNodeKind === 218 /* TemplateExpression */; // `aa ${| + return containingNodeKind === 219 /* TemplateExpression */; // `aa ${| case 16 /* TemplateMiddle */: - return containingNodeKind === 228 /* TemplateSpan */; // `aa ${10} dd ${| + return containingNodeKind === 229 /* TemplateSpan */; // `aa ${10} dd ${| case 122 /* PublicKeyword */: case 120 /* PrivateKeyword */: case 121 /* ProtectedKeyword */: - return containingNodeKind === 163 /* PropertyDeclaration */; // class A{ public | + return containingNodeKind === 164 /* PropertyDeclaration */; // class A{ public | } } return false; @@ -120707,6 +124591,25 @@ var ts; return (ts.isRegularExpressionLiteral(contextToken) || ts.isStringTextContainingNode(contextToken)) && (ts.rangeContainsPositionExclusive(ts.createTextRangeFromSpan(ts.createTextSpanFromNode(contextToken)), position) || position === contextToken.end && (!!contextToken.isUnterminated || ts.isRegularExpressionLiteral(contextToken))); } + function tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() { + var typeLiteralNode = tryGetTypeLiteralNode(contextToken); + if (!typeLiteralNode) + return 0 /* Continue */; + var intersectionTypeNode = ts.isIntersectionTypeNode(typeLiteralNode.parent) ? typeLiteralNode.parent : undefined; + var containerTypeNode = intersectionTypeNode || typeLiteralNode; + var containerExpectedType = getConstraintOfTypeArgumentProperty(containerTypeNode, typeChecker); + if (!containerExpectedType) + return 0 /* Continue */; + var containerActualType = typeChecker.getTypeFromTypeNode(containerTypeNode); + var members = getPropertiesForCompletion(containerExpectedType, typeChecker); + var existingMembers = getPropertiesForCompletion(containerActualType, typeChecker); + var existingMemberEscapedNames = new ts.Set(); + existingMembers.forEach(function (s) { return existingMemberEscapedNames.add(s.escapedName); }); + symbols = ts.filter(members, function (s) { return !existingMemberEscapedNames.has(s.escapedName); }); + completionKind = 0 /* ObjectPropertyDeclaration */; + isNewIdentifierLocation = true; + return 1 /* Success */; + } /** * Aggregates relevant symbols for completion in object literals and object binding patterns. * Relevant symbols are stored in the captured 'symbols' variable. @@ -120721,7 +124624,7 @@ var ts; completionKind = 0 /* ObjectPropertyDeclaration */; var typeMembers; var existingMembers; - if (objectLikeContainer.kind === 200 /* ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 201 /* ObjectLiteralExpression */) { var instantiatedType = tryGetObjectLiteralContextualType(objectLikeContainer, typeChecker); // Check completions for Object property value shorthand if (instantiatedType === undefined) { @@ -120746,7 +124649,7 @@ var ts; } } else { - ts.Debug.assert(objectLikeContainer.kind === 196 /* ObjectBindingPattern */); + ts.Debug.assert(objectLikeContainer.kind === 197 /* ObjectBindingPattern */); // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -120757,12 +124660,12 @@ var ts; // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function - var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 239 /* ForOfStatement */; - if (!canGetType && rootDeclaration.kind === 160 /* Parameter */) { + var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 240 /* ForOfStatement */; + if (!canGetType && rootDeclaration.kind === 161 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - else if (rootDeclaration.parent.kind === 165 /* MethodDeclaration */ || rootDeclaration.parent.kind === 168 /* SetAccessor */) { + else if (rootDeclaration.parent.kind === 166 /* MethodDeclaration */ || rootDeclaration.parent.kind === 169 /* SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } @@ -120809,9 +124712,9 @@ var ts; if (!namedImportsOrExports) return 0 /* Continue */; // try to show exported member for imported/re-exported module - var moduleSpecifier = (namedImportsOrExports.kind === 264 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + var moduleSpecifier = (namedImportsOrExports.kind === 265 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; if (!moduleSpecifier) - return namedImportsOrExports.kind === 264 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */; + return namedImportsOrExports.kind === 265 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 if (!moduleSpecifierSymbol) return 2 /* Fail */; @@ -120879,12 +124782,16 @@ var ts; case "static": classElementModifierFlags = classElementModifierFlags | 32 /* Static */; break; + case "override": + classElementModifierFlags = classElementModifierFlags | 16384 /* Override */; + break; } } // No member list for private methods if (!(classElementModifierFlags & 8 /* Private */)) { // List of property symbols of base type that are not private and already implemented - var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) { + var baseTypeNodes = ts.isClassLike(decl) && classElementModifierFlags & 16384 /* Override */ ? ts.singleElementArray(ts.getEffectiveBaseTypeNode(decl)) : ts.getAllSuperTypeNodes(decl); + var baseSymbols = ts.flatMap(baseTypeNodes, function (baseTypeNode) { var type = typeChecker.getTypeAtLocation(baseTypeNode); return classElementModifierFlags & 32 /* Static */ ? (type === null || type === void 0 ? void 0 : type.symbol) && typeChecker.getPropertiesOfType(typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl)) : @@ -120964,11 +124871,11 @@ var ts; case 30 /* LessThanSlashToken */: case 43 /* SlashToken */: case 78 /* Identifier */: - case 201 /* PropertyAccessExpression */: - case 281 /* JsxAttributes */: - case 280 /* JsxAttribute */: - case 282 /* JsxSpreadAttribute */: - if (parent && (parent.kind === 274 /* JsxSelfClosingElement */ || parent.kind === 275 /* JsxOpeningElement */)) { + case 202 /* PropertyAccessExpression */: + case 282 /* JsxAttributes */: + case 281 /* JsxAttribute */: + case 283 /* JsxSpreadAttribute */: + if (parent && (parent.kind === 275 /* JsxSelfClosingElement */ || parent.kind === 276 /* JsxOpeningElement */)) { if (contextToken.kind === 31 /* GreaterThanToken */) { var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined); if (!parent.typeArguments || (precedingToken && precedingToken.kind === 43 /* SlashToken */)) @@ -120976,7 +124883,7 @@ var ts; } return parent; } - else if (parent.kind === 280 /* JsxAttribute */) { + else if (parent.kind === 281 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -120988,7 +124895,7 @@ var ts; // its parent is a JsxExpression, whose parent is a JsxAttribute, // whose parent is a JsxOpeningLikeElement case 10 /* StringLiteral */: - if (parent && ((parent.kind === 280 /* JsxAttribute */) || (parent.kind === 282 /* JsxSpreadAttribute */))) { + if (parent && ((parent.kind === 281 /* JsxAttribute */) || (parent.kind === 283 /* JsxSpreadAttribute */))) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -120998,8 +124905,8 @@ var ts; break; case 19 /* CloseBraceToken */: if (parent && - parent.kind === 283 /* JsxExpression */ && - parent.parent && parent.parent.kind === 280 /* JsxAttribute */) { + parent.kind === 284 /* JsxExpression */ && + parent.parent && parent.parent.kind === 281 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -121007,7 +124914,7 @@ var ts; // each JsxAttribute can have initializer as JsxExpression return parent.parent.parent.parent; } - if (parent && parent.kind === 282 /* JsxSpreadAttribute */) { + if (parent && parent.kind === 283 /* JsxSpreadAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -121027,49 +124934,49 @@ var ts; var containingNodeKind = parent.kind; switch (contextToken.kind) { case 27 /* CommaToken */: - return containingNodeKind === 249 /* VariableDeclaration */ || + return containingNodeKind === 250 /* VariableDeclaration */ || isVariableDeclarationListButNotTypeArgument(contextToken) || - containingNodeKind === 232 /* VariableStatement */ || - containingNodeKind === 255 /* EnumDeclaration */ || // enum a { foo, | + containingNodeKind === 233 /* VariableStatement */ || + containingNodeKind === 256 /* EnumDeclaration */ || // enum a { foo, | isFunctionLikeButNotConstructor(containingNodeKind) || - containingNodeKind === 253 /* InterfaceDeclaration */ || // interface A= contextToken.pos); case 24 /* DotToken */: - return containingNodeKind === 197 /* ArrayBindingPattern */; // var [.| + return containingNodeKind === 198 /* ArrayBindingPattern */; // var [.| case 58 /* ColonToken */: - return containingNodeKind === 198 /* BindingElement */; // var {x :html| + return containingNodeKind === 199 /* BindingElement */; // var {x :html| case 22 /* OpenBracketToken */: - return containingNodeKind === 197 /* ArrayBindingPattern */; // var [x| + return containingNodeKind === 198 /* ArrayBindingPattern */; // var [x| case 20 /* OpenParenToken */: - return containingNodeKind === 287 /* CatchClause */ || + return containingNodeKind === 288 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); case 18 /* OpenBraceToken */: - return containingNodeKind === 255 /* EnumDeclaration */; // enum a { | + return containingNodeKind === 256 /* EnumDeclaration */; // enum a { | case 29 /* LessThanToken */: - return containingNodeKind === 252 /* ClassDeclaration */ || // class A< | - containingNodeKind === 221 /* ClassExpression */ || // var C = class D< | - containingNodeKind === 253 /* InterfaceDeclaration */ || // interface A< | - containingNodeKind === 254 /* TypeAliasDeclaration */ || // type List< | + return containingNodeKind === 253 /* ClassDeclaration */ || // class A< | + containingNodeKind === 222 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 254 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 255 /* TypeAliasDeclaration */ || // type List< | ts.isFunctionLikeKind(containingNodeKind); case 123 /* StaticKeyword */: - return containingNodeKind === 163 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); + return containingNodeKind === 164 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); case 25 /* DotDotDotToken */: - return containingNodeKind === 160 /* Parameter */ || - (!!parent.parent && parent.parent.kind === 197 /* ArrayBindingPattern */); // var [...z| + return containingNodeKind === 161 /* Parameter */ || + (!!parent.parent && parent.parent.kind === 198 /* ArrayBindingPattern */); // var [...z| case 122 /* PublicKeyword */: case 120 /* PrivateKeyword */: case 121 /* ProtectedKeyword */: - return containingNodeKind === 160 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); + return containingNodeKind === 161 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); case 126 /* AsKeyword */: - return containingNodeKind === 265 /* ImportSpecifier */ || - containingNodeKind === 270 /* ExportSpecifier */ || - containingNodeKind === 263 /* NamespaceImport */; + return containingNodeKind === 266 /* ImportSpecifier */ || + containingNodeKind === 271 /* ExportSpecifier */ || + containingNodeKind === 264 /* NamespaceImport */; case 134 /* GetKeyword */: case 146 /* SetKeyword */: return !isFromObjectTypeDeclaration(contextToken); @@ -121087,7 +124994,7 @@ var ts; case 41 /* AsteriskToken */: return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } - // If the previous token is keyword correspoding to class member completion keyword + // If the previous token is keyword corresponding to class member completion keyword // there will be completion available here if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { return false; @@ -121122,6 +125029,31 @@ var ts; case 129 /* AsyncKeyword */: return ts.isPropertyDeclaration(contextToken.parent); } + // If we are inside a class declaration, and `constructor` is totally not present, + // but we request a completion manually at a whitespace... + var ancestorClassLike = ts.findAncestor(contextToken.parent, ts.isClassLike); + if (ancestorClassLike && contextToken === previousToken && isPreviousPropertyDeclarationTerminated(contextToken, position)) { + return false; // Don't block completions. + } + var ancestorPropertyDeclaraion = ts.getAncestor(contextToken.parent, 164 /* PropertyDeclaration */); + // If we are inside a class declaration and typing `constructor` after property declaration... + if (ancestorPropertyDeclaraion + && contextToken !== previousToken + && ts.isClassLike(previousToken.parent.parent) + // And the cursor is at the token... + && position <= previousToken.end) { + // If we are sure that the previous property declaration is terminated according to newline or semicolon... + if (isPreviousPropertyDeclarationTerminated(contextToken, previousToken.end)) { + return false; // Don't block completions. + } + else if (contextToken.kind !== 62 /* EqualsToken */ + // Should not block: `class C { blah = c/**/ }` + // But should block: `class C { blah = somewhat c/**/ }` and `class C { blah: SomeType c/**/ }` + && (ts.isInitializedProperty(ancestorPropertyDeclaraion) + || ts.hasType(ancestorPropertyDeclaraion))) { + return true; + } + } return ts.isDeclarationName(contextToken) && !ts.isShorthandPropertyAssignment(contextToken.parent) && !ts.isJsxAttribute(contextToken.parent) @@ -121129,8 +125061,13 @@ var ts; // If `contextToken !== previousToken`, this is `class C ex/**/`. && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } + function isPreviousPropertyDeclarationTerminated(contextToken, position) { + return contextToken.kind !== 62 /* EqualsToken */ && + (contextToken.kind === 26 /* SemicolonToken */ + || !ts.positionsAreOnSameLine(contextToken.end, position, sourceFile)); + } function isFunctionLikeButNotConstructor(kind) { - return ts.isFunctionLikeKind(kind) && kind !== 166 /* Constructor */; + return ts.isFunctionLikeKind(kind) && kind !== 167 /* Constructor */; } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8 /* NumericLiteral */) { @@ -121140,7 +125077,7 @@ var ts; return false; } function isVariableDeclarationListButNotTypeArgument(node) { - return node.parent.kind === 250 /* VariableDeclarationList */ + return node.parent.kind === 251 /* VariableDeclarationList */ && !ts.isPossiblyTypeArgumentPosition(node, sourceFile, typeChecker); } /** @@ -121158,13 +125095,13 @@ var ts; for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 288 /* PropertyAssignment */ && - m.kind !== 289 /* ShorthandPropertyAssignment */ && - m.kind !== 198 /* BindingElement */ && - m.kind !== 165 /* MethodDeclaration */ && - m.kind !== 167 /* GetAccessor */ && - m.kind !== 168 /* SetAccessor */ && - m.kind !== 290 /* SpreadAssignment */) { + if (m.kind !== 289 /* PropertyAssignment */ && + m.kind !== 290 /* ShorthandPropertyAssignment */ && + m.kind !== 199 /* BindingElement */ && + m.kind !== 166 /* MethodDeclaration */ && + m.kind !== 168 /* GetAccessor */ && + m.kind !== 169 /* SetAccessor */ && + m.kind !== 291 /* SpreadAssignment */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -121237,10 +125174,10 @@ var ts; for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 163 /* PropertyDeclaration */ && - m.kind !== 165 /* MethodDeclaration */ && - m.kind !== 167 /* GetAccessor */ && - m.kind !== 168 /* SetAccessor */) { + if (m.kind !== 164 /* PropertyDeclaration */ && + m.kind !== 166 /* MethodDeclaration */ && + m.kind !== 168 /* GetAccessor */ && + m.kind !== 169 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -121264,7 +125201,7 @@ var ts; return !existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */) && - !(propertySymbol.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(propertySymbol.valueDeclaration)); + !(propertySymbol.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(propertySymbol.valueDeclaration)); }); } /** @@ -121282,7 +125219,7 @@ var ts; if (isCurrentlyEditingNode(attr)) { continue; } - if (attr.kind === 280 /* JsxAttribute */) { + if (attr.kind === 281 /* JsxAttribute */) { seenNames.add(attr.name.escapedText); } else if (ts.isJsxSpreadAttribute(attr)) { @@ -121297,8 +125234,35 @@ var ts; return node.getStart(sourceFile) <= position && position <= node.getEnd(); } } + function getAutoImportSymbolFromCompletionEntryData(name, data, program, host) { + var containingProgram = data.isPackageJsonImport ? host.getPackageJsonAutoImportProvider() : program; + var checker = containingProgram.getTypeChecker(); + var moduleSymbol = data.ambientModuleName ? checker.tryFindAmbientModule(data.ambientModuleName) : + data.fileName ? checker.getMergedSymbol(ts.Debug.checkDefined(containingProgram.getSourceFile(data.fileName)).symbol) : + undefined; + if (!moduleSymbol) + return undefined; + var symbol = data.exportName === "export=" /* ExportEquals */ + ? checker.resolveExternalModuleSymbol(moduleSymbol) + : checker.tryGetMemberInModuleExportsAndProperties(data.exportName, moduleSymbol); + if (!symbol) + return undefined; + var isDefaultExport = data.exportName === "default" /* Default */; + symbol = isDefaultExport && ts.getLocalSymbolForExportDefault(symbol) || symbol; + return { + symbol: symbol, + origin: { + kind: data.moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */, + moduleSymbol: moduleSymbol, + symbolName: name, + isDefaultExport: isDefaultExport, + exportName: data.exportName, + fileName: data.fileName, + } + }; + } function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, jsxIdentifierExpected) { - var name = originIsExport(origin) ? ts.getNameForExportedSymbol(symbol, target) : symbol.name; + var name = originIncludesSymbolName(origin) ? origin.symbolName : symbol.name; if (name === undefined // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) @@ -121308,7 +125272,7 @@ var ts; return undefined; } var validNameResult = { name: name, needsConvertPropertyAccess: false }; - if (ts.isIdentifierText(name, target, jsxIdentifierExpected ? 1 /* JSX */ : 0 /* Standard */) || symbol.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) { + if (ts.isIdentifierText(name, target, jsxIdentifierExpected ? 1 /* JSX */ : 0 /* Standard */) || symbol.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) { return validNameResult; } switch (kind) { @@ -121332,7 +125296,7 @@ var ts; var _keywordCompletions = []; var allKeywordsCompletions = ts.memoize(function () { var res = []; - for (var i = 80 /* FirstKeyword */; i <= 156 /* LastKeyword */; i++) { + for (var i = 80 /* FirstKeyword */; i <= 157 /* LastKeyword */; i++) { res.push({ name: ts.tokenToString(i), kind: "keyword" /* keyword */, @@ -121399,6 +125363,7 @@ var ts; case 141 /* NeverKeyword */: case 144 /* NumberKeyword */: case 145 /* ObjectKeyword */: + case 156 /* OverrideKeyword */: case 120 /* PrivateKeyword */: case 121 /* ProtectedKeyword */: case 122 /* PublicKeyword */: @@ -121424,6 +125389,7 @@ var ts; case 146 /* SetKeyword */: case 129 /* AsyncKeyword */: case 133 /* DeclareKeyword */: + case 156 /* OverrideKeyword */: return true; default: return ts.isClassMemberModifier(kind); @@ -121484,7 +125450,7 @@ var ts; function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position) { // class c { method() { } | method2() { } } switch (location.kind) { - case 334 /* SyntaxList */: + case 338 /* SyntaxList */: return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); case 1 /* EndOfFileToken */: var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); @@ -121505,6 +125471,12 @@ var ts; } if (!contextToken) return undefined; + // class C { blah; constructor/**/ } and so on + if (location.kind === 132 /* ConstructorKeyword */ + // class C { blah \n constructor/**/ } + || (ts.isIdentifier(contextToken) && ts.isPropertyDeclaration(contextToken.parent) && ts.isClassLike(location))) { + return ts.findAncestor(contextToken, ts.isClassLike); + } switch (contextToken.kind) { case 62 /* EqualsToken */: // class c { public prop = | /* global completions */ } return undefined; @@ -121530,6 +125502,44 @@ var ts; ? contextToken.parent.parent : undefined; } } + function tryGetTypeLiteralNode(node) { + if (!node) + return undefined; + var parent = node.parent; + switch (node.kind) { + case 18 /* OpenBraceToken */: + if (ts.isTypeLiteralNode(parent)) { + return parent; + } + break; + case 26 /* SemicolonToken */: + case 27 /* CommaToken */: + case 78 /* Identifier */: + if (parent.kind === 163 /* PropertySignature */ && ts.isTypeLiteralNode(parent.parent)) { + return parent.parent; + } + break; + } + return undefined; + } + function getConstraintOfTypeArgumentProperty(node, checker) { + if (!node) + return undefined; + if (ts.isTypeNode(node) && ts.isTypeReferenceType(node.parent)) { + return checker.getTypeArgumentConstraint(node); + } + var t = getConstraintOfTypeArgumentProperty(node.parent, checker); + if (!t) + return undefined; + switch (node.kind) { + case 163 /* PropertySignature */: + return checker.getTypeOfPropertyOfContextualType(t, node.symbol.escapedName); + case 184 /* IntersectionType */: + case 178 /* TypeLiteral */: + case 183 /* UnionType */: + return t; + } + } // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes function isFromObjectTypeDeclaration(node) { return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent); @@ -121553,6 +125563,8 @@ var ts; return !!contextToken && (ts.isStringLiteralLike(contextToken) ? !!ts.tryGetImportFromModuleSpecifier(contextToken) : contextToken.kind === 43 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); + case " ": + return !!contextToken && ts.isImportKeyword(contextToken) && contextToken.parent.kind === 298 /* SourceFile */; default: return ts.Debug.assertNever(triggerCharacter); } @@ -121561,14 +125573,6 @@ var ts; var left = _a.left; return ts.nodeIsMissing(left); } - function findAlias(typeChecker, symbol, predicate) { - var currentAlias = symbol; - while (currentAlias.flags & 2097152 /* Alias */ && (currentAlias = typeChecker.getImmediateAliasedSymbol(currentAlias))) { - if (predicate(currentAlias)) { - return currentAlias; - } - } - } /** Determines if a type is exactly the same type resolved by the global 'self', 'global', or 'globalThis'. */ function isProbablyGlobalType(type, sourceFile, checker) { // The type of `self` and `window` is the same in lib.dom.d.ts, but `window` does not exist in @@ -121595,11 +125599,67 @@ var ts; if (type) { return type; } - if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) { + if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ && node === node.parent.left) { + // Object literal is assignment pattern: ({ | } = x) return typeChecker.getTypeAtLocation(node.parent); } return undefined; } + function getImportCompletionNode(contextToken) { + var candidate = getCandidate(); + return candidate === 153 /* FromKeyword */ || candidate && ts.rangeIsOnSingleLine(candidate, candidate.getSourceFile()) ? candidate : undefined; + function getCandidate() { + var parent = contextToken.parent; + if (ts.isImportEqualsDeclaration(parent)) { + return isModuleSpecifierMissingOrEmpty(parent.moduleReference) ? parent : undefined; + } + if (ts.isNamedImports(parent) || ts.isNamespaceImport(parent)) { + if (isModuleSpecifierMissingOrEmpty(parent.parent.parent.moduleSpecifier) && (ts.isNamespaceImport(parent) || parent.elements.length < 2) && !parent.parent.name) { + // At `import { ... } |` or `import * as Foo |`, the only possible completion is `from` + return contextToken.kind === 19 /* CloseBraceToken */ || contextToken.kind === 78 /* Identifier */ + ? 153 /* FromKeyword */ + : parent.parent.parent; + } + return undefined; + } + if (ts.isImportKeyword(contextToken) && ts.isSourceFile(parent)) { + // A lone import keyword with nothing following it does not parse as a statement at all + return contextToken; + } + if (ts.isImportKeyword(contextToken) && ts.isImportDeclaration(parent)) { + // `import s| from` + return isModuleSpecifierMissingOrEmpty(parent.moduleSpecifier) ? parent : undefined; + } + return undefined; + } + } + function isModuleSpecifierMissingOrEmpty(specifier) { + var _a; + if (ts.nodeIsMissing(specifier)) + return true; + return !((_a = ts.tryCast(ts.isExternalModuleReference(specifier) ? specifier.expression : specifier, ts.isStringLiteralLike)) === null || _a === void 0 ? void 0 : _a.text); + } + function getVariableDeclaration(property) { + var variableDeclaration = ts.findAncestor(property, function (node) { + return ts.isFunctionBlock(node) || isArrowFunctionBody(node) || ts.isBindingPattern(node) + ? "quit" + : ts.isVariableDeclaration(node); + }); + return variableDeclaration; + } + function isArrowFunctionBody(node) { + return node.parent && ts.isArrowFunction(node.parent) && node.parent.body === node; + } + ; + /** True if symbol is a type or a module containing at least one type. */ + function symbolCanBeReferencedAtTypeLocation(symbol, checker, seenModules) { + if (seenModules === void 0) { seenModules = new ts.Map(); } + var sym = ts.skipAlias(symbol.exportSymbol || symbol, checker); + return !!(sym.flags & 788968 /* Type */) || + !!(sym.flags & 1536 /* Module */) && + ts.addToSeen(seenModules, ts.getSymbolId(sym)) && + checker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, checker, seenModules); }); + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); var ts; @@ -121634,10 +125694,12 @@ var ts; if (!referenceEntries) return undefined; var map = ts.arrayToMultiMap(referenceEntries.map(ts.FindAllReferences.toHighlightSpan), function (e) { return e.fileName; }, function (e) { return e.span; }); - return ts.arrayFrom(map.entries(), function (_a) { + return ts.mapDefined(ts.arrayFrom(map.entries()), function (_a) { var fileName = _a[0], highlightSpans = _a[1]; if (!sourceFilesSet.has(fileName)) { - ts.Debug.assert(program.redirectTargetsMap.has(fileName)); + if (!program.redirectTargetsMap.has(fileName)) { + return undefined; + } var redirectTarget_1 = program.getSourceFile(fileName); var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); fileName = redirect.fileName; @@ -121732,7 +125794,7 @@ var ts; var child = throwStatement; while (child.parent) { var parent = child.parent; - if (ts.isFunctionBlock(parent) || parent.kind === 297 /* SourceFile */) { + if (ts.isFunctionBlock(parent) || parent.kind === 298 /* SourceFile */) { return parent; } // A throw-statement is only owned by a try-statement if the try-statement has @@ -121764,16 +125826,16 @@ var ts; function getBreakOrContinueOwner(statement) { return ts.findAncestor(statement, function (node) { switch (node.kind) { - case 244 /* SwitchStatement */: - if (statement.kind === 240 /* ContinueStatement */) { + case 245 /* SwitchStatement */: + if (statement.kind === 241 /* ContinueStatement */) { return false; } // falls through - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 236 /* WhileStatement */: - case 235 /* DoStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 237 /* WhileStatement */: + case 236 /* DoStatement */: return !statement.label || isLabeledBy(node, statement.label.escapedText); default: // Don't cross function boundaries. @@ -121789,11 +125851,11 @@ var ts; // Types of node whose children might have modifiers. var container = declaration.parent; switch (container.kind) { - case 257 /* ModuleBlock */: - case 297 /* SourceFile */: - case 230 /* Block */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 258 /* ModuleBlock */: + case 298 /* SourceFile */: + case 231 /* Block */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) { return __spreadArray(__spreadArray([], declaration.members), [declaration]); @@ -121801,14 +125863,14 @@ var ts; else { return container.statements; } - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 251 /* FunctionDeclaration */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: return __spreadArray(__spreadArray([], container.parameters), (ts.isClassLike(container.parent) ? container.parent.members : [])); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 177 /* TypeLiteral */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 178 /* TypeLiteral */: var nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. @@ -121823,7 +125885,7 @@ var ts; } return nodes; // Syntactically invalid positions that the parser might produce anyway - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return undefined; default: ts.Debug.assertNever(container, "Invalid container kind."); @@ -121844,7 +125906,7 @@ var ts; var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 96 /* ForKeyword */, 114 /* WhileKeyword */, 89 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 235 /* DoStatement */) { + if (loopNode.kind === 236 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 114 /* WhileKeyword */)) { @@ -121864,13 +125926,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -122043,6 +126105,9 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + function isDocumentRegistryEntry(entry) { + return !!entry.sourceFile; + } function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); } @@ -122059,10 +126124,16 @@ var ts; var entries = buckets.get(name); var sourceFiles = []; entries.forEach(function (entry, name) { - sourceFiles.push({ - name: name, - refCount: entry.languageServiceRefCount - }); + if (isDocumentRegistryEntry(entry)) { + sourceFiles.push({ + name: name, + scriptKind: entry.sourceFile.scriptKind, + refCount: entry.languageServiceRefCount + }); + } + else { + entry.forEach(function (value, scriptKind) { return sourceFiles.push({ name: name, scriptKind: scriptKind, refCount: value.languageServiceRefCount }); }); + } }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); return { @@ -122088,10 +126159,17 @@ var ts; function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); } + function getDocumentRegistryEntry(bucketEntry, scriptKind) { + var entry = isDocumentRegistryEntry(bucketEntry) ? bucketEntry : bucketEntry.get(ts.Debug.checkDefined(scriptKind, "If there are more than one scriptKind's for same document the scriptKind should be provided")); + ts.Debug.assert(scriptKind === undefined || !entry || entry.sourceFile.scriptKind === scriptKind, "Script kind should match provided ScriptKind:" + scriptKind + " and sourceFile.scriptKind: " + (entry === null || entry === void 0 ? void 0 : entry.sourceFile.scriptKind) + ", !entry: " + !entry); + return entry; + } function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { - var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); - var entry = bucket.get(path); + scriptKind = ts.ensureScriptKind(fileName, scriptKind); var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; + var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); + var bucketEntry = bucket.get(path); + var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -122100,7 +126178,7 @@ var ts; sourceFile: sourceFile, languageServiceRefCount: 0 }; - bucket.set(path, entry); + setBucketEntry(); } } if (!entry) { @@ -122113,7 +126191,7 @@ var ts; sourceFile: sourceFile, languageServiceRefCount: 1, }; - bucket.set(path, entry); + setBucketEntry(); } else { // We have an entry for this file. However, it may be for a different version of @@ -122136,25 +126214,49 @@ var ts; } ts.Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; + function setBucketEntry() { + if (!bucketEntry) { + bucket.set(path, entry); + } + else if (isDocumentRegistryEntry(bucketEntry)) { + var scriptKindMap = new ts.Map(); + scriptKindMap.set(bucketEntry.sourceFile.scriptKind, bucketEntry); + scriptKindMap.set(scriptKind, entry); + bucket.set(path, scriptKindMap); + } + else { + bucketEntry.set(scriptKind, entry); + } + } } - function releaseDocument(fileName, compilationSettings) { + function releaseDocument(fileName, compilationSettings, scriptKind) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(compilationSettings); - return releaseDocumentWithKey(path, key); + return releaseDocumentWithKey(path, key, scriptKind); } - function releaseDocumentWithKey(path, key) { + function releaseDocumentWithKey(path, key, scriptKind) { var bucket = ts.Debug.checkDefined(buckets.get(key)); - var entry = bucket.get(path); + var bucketEntry = bucket.get(path); + var entry = getDocumentRegistryEntry(bucketEntry, scriptKind); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - bucket.delete(path); + if (isDocumentRegistryEntry(bucketEntry)) { + bucket.delete(path); + } + else { + bucketEntry.delete(scriptKind); + if (bucketEntry.size === 1) { + bucket.set(path, ts.firstDefinedIterator(bucketEntry.values(), ts.identity)); + } + } } } - function getLanguageServiceRefCounts(path) { + function getLanguageServiceRefCounts(path, scriptKind) { return ts.arrayFrom(buckets.entries(), function (_a) { var key = _a[0], bucket = _a[1]; - var entry = bucket.get(path); + var bucketEntry = bucket.get(path); + var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); return [key, entry && entry.languageServiceRefCount]; }); } @@ -122217,10 +126319,12 @@ var ts; return sourceFiles; } // Module augmentations may use this module's exports without importing it. - for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (ts.isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) { - addIndirectUser(decl); + if (exportingModuleSymbol.declarations) { + for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) { + addIndirectUser(decl); + } } } // This may return duplicates (if there are multiple module declarations in a single source file, all importing the same thing as a namespace), but `State.markSearchedSymbol` will handle that. @@ -122237,14 +126341,14 @@ var ts; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); switch (direct.kind) { - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (ts.isImportCall(direct)) { handleImportCall(direct); break; } if (!isAvailableThroughGlobal) { var parent = direct.parent; - if (exportKind === 2 /* ExportEquals */ && parent.kind === 249 /* VariableDeclaration */) { + if (exportKind === 2 /* ExportEquals */ && parent.kind === 250 /* VariableDeclaration */) { var name = parent.name; if (name.kind === 78 /* Identifier */) { directImports.push(name); @@ -122255,25 +126359,25 @@ var ts; break; case 78 /* Identifier */: // for 'const x = require("y"); break; // TODO: GH#23879 - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: handleNamespaceImport(direct, direct.name, ts.hasSyntacticModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false); break; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: directImports.push(direct); var namedBindings = direct.importClause && direct.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 263 /* NamespaceImport */) { + if (namedBindings && namedBindings.kind === 264 /* NamespaceImport */) { handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true); } else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) { addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports } break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: if (!direct.exportClause) { // This is `export * from "foo"`, so imports of this module may import the export too. handleDirectImports(getContainingModuleSymbol(direct, checker)); } - else if (direct.exportClause.kind === 269 /* NamespaceExport */) { + else if (direct.exportClause.kind === 270 /* NamespaceExport */) { // `export * as foo from "foo"` add to indirect uses addIndirectUser(getSourceFileLikeForImportDeclaration(direct), /** addTransitiveDependencies */ true); } @@ -122282,7 +126386,7 @@ var ts; directImports.push(direct); } break; - case 195 /* ImportType */: + case 196 /* ImportType */: // Only check for typeof import('xyz') if (direct.isTypeOf && !direct.qualifier && isExported(direct)) { addIndirectUser(direct.getSourceFile(), /** addTransitiveDependencies */ true); @@ -122315,7 +126419,7 @@ var ts; } else if (!isAvailableThroughGlobal) { var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); - ts.Debug.assert(sourceFileLike.kind === 297 /* SourceFile */ || sourceFileLike.kind === 256 /* ModuleDeclaration */); + ts.Debug.assert(sourceFileLike.kind === 298 /* SourceFile */ || sourceFileLike.kind === 257 /* ModuleDeclaration */); if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { addIndirectUser(sourceFileLike, /** addTransitiveDependencies */ true); } @@ -122371,7 +126475,7 @@ var ts; } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { - if (decl.kind === 260 /* ImportEqualsDeclaration */) { + if (decl.kind === 261 /* ImportEqualsDeclaration */) { if (isExternalModuleImportEquals(decl)) { handleNamespaceImportLike(decl.name); } @@ -122381,7 +126485,7 @@ var ts; handleNamespaceImportLike(decl); return; } - if (decl.kind === 195 /* ImportType */) { + if (decl.kind === 196 /* ImportType */) { if (decl.qualifier) { var firstIdentifier = ts.getFirstIdentifier(decl.qualifier); if (firstIdentifier.escapedText === ts.symbolName(exportSymbol)) { @@ -122397,7 +126501,7 @@ var ts; if (decl.moduleSpecifier.kind !== 10 /* StringLiteral */) { return; } - if (decl.kind === 267 /* ExportDeclaration */) { + if (decl.kind === 268 /* ExportDeclaration */) { if (decl.exportClause && ts.isNamedExports(decl.exportClause)) { searchForNamedImport(decl.exportClause); } @@ -122406,10 +126510,10 @@ var ts; var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: handleNamespaceImportLike(namedBindings.name); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: // 'default' might be accessed as a named import `{ default as foo }`. if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) { searchForNamedImport(namedBindings); @@ -122459,7 +126563,7 @@ var ts; } } else { - var localSymbol = element.kind === 270 /* ExportSpecifier */ && element.propertyName + var localSymbol = element.kind === 271 /* ExportSpecifier */ && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. : checker.getSymbolAtLocation(name); addSearch(name, localSymbol); @@ -122488,7 +126592,7 @@ var ts; for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { var referencingFile = sourceFiles_1[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; - if (searchSourceFile.kind === 297 /* SourceFile */) { + if ((searchSourceFile === null || searchSourceFile === void 0 ? void 0 : searchSourceFile.kind) === 298 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { var ref = _b[_a]; if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { @@ -122536,7 +126640,7 @@ var ts; } /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return ts.forEach(sourceFileLike.kind === 297 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return ts.forEach(sourceFileLike.kind === 298 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); }); } @@ -122551,15 +126655,15 @@ var ts; else { forEachPossibleImportOrExportStatement(sourceFile, function (statement) { switch (statement.kind) { - case 267 /* ExportDeclaration */: - case 261 /* ImportDeclaration */: { + case 268 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: { var decl = statement; if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) { action(decl, decl.moduleSpecifier); } break; } - case 260 /* ImportEqualsDeclaration */: { + case 261 /* ImportEqualsDeclaration */: { var decl = statement; if (isExternalModuleImportEquals(decl)) { action(decl, decl.moduleReference.expression); @@ -122580,14 +126684,15 @@ var ts; function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { return comingFromExport ? getExport() : getExport() || getImport(); function getExport() { + var _a; var parent = node.parent; - var grandParent = parent.parent; + var grandparent = parent.parent; if (symbol.exportSymbol) { - if (parent.kind === 201 /* PropertyAccessExpression */) { + if (parent.kind === 202 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. - return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) - ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false) + return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === parent; })) && ts.isBinaryExpression(grandparent) + ? getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ false) : undefined; } else { @@ -122617,15 +126722,15 @@ var ts; return getExportAssignmentExport(parent); } // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. - else if (ts.isExportAssignment(grandParent)) { - return getExportAssignmentExport(grandParent); + else if (ts.isExportAssignment(grandparent)) { + return getExportAssignmentExport(grandparent); } // Similar for `module.exports =` and `exports.A =`. else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } - else if (ts.isBinaryExpression(grandParent)) { - return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true); + else if (ts.isBinaryExpression(grandparent)) { + return getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ true); } else if (ts.isJSDocTypedefTag(parent)) { return exportInfo(symbol, 0 /* Named */); @@ -122633,9 +126738,10 @@ var ts; } function getExportAssignmentExport(ex) { // Get the symbol for the `export =` node; its parent is the module it's the export of. - var exportingModuleSymbol = ts.Debug.checkDefined(ex.symbol.parent, "Expected export symbol to have a parent"); + if (!ex.symbol.parent) + return undefined; var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */; - return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; + return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: ex.symbol.parent, exportKind: exportKind } }; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; @@ -122689,7 +126795,7 @@ var ts; if (importedSymbol.flags & 2097152 /* Alias */) { return ts.Debug.checkDefined(checker.getImmediateAliasedSymbol(importedSymbol)); } - var decl = importedSymbol.valueDeclaration; + var decl = ts.Debug.checkDefined(importedSymbol.valueDeclaration); if (ts.isExportAssignment(decl)) { // `export = class {}` return ts.Debug.checkDefined(decl.expression.symbol); } @@ -122716,17 +126822,17 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return parent.name === node && isExternalModuleImportEquals(parent); - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. return !parent.propertyName; - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: ts.Debug.assert(parent.name === node); return true; - case 198 /* BindingElement */: - return ts.isInJSFile(node) && ts.isRequireVariableDeclaration(parent, /*requireStringLiteralLikeArgument*/ true); + case 199 /* BindingElement */: + return ts.isInJSFile(node) && ts.isRequireVariableDeclaration(parent); default: return false; } @@ -122750,7 +126856,8 @@ var ts; return checker.getExportSpecifierLocalTargetSymbol(declaration); } else if (ts.isPropertyAccessExpression(declaration) && ts.isModuleExportsAccessExpression(declaration.expression) && !ts.isPrivateIdentifier(declaration.name)) { - return checker.getExportSpecifierLocalTargetSymbol(declaration.name); + // Export of form 'module.exports.propName = expr'; + return checker.getSymbolAtLocation(declaration); } else if (ts.isShorthandPropertyAssignment(declaration) && ts.isBinaryExpression(declaration.parent.parent) @@ -122765,21 +126872,21 @@ var ts; return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); } function getSourceFileLikeForImportDeclaration(node) { - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { return node.getSourceFile(); } var parent = node.parent; - if (parent.kind === 297 /* SourceFile */) { + if (parent.kind === 298 /* SourceFile */) { return parent; } - ts.Debug.assert(parent.kind === 257 /* ModuleBlock */); + ts.Debug.assert(parent.kind === 258 /* ModuleBlock */); return ts.cast(parent.parent, isAmbientModuleDeclaration); } function isAmbientModuleDeclaration(node) { - return node.kind === 256 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */; + return node.kind === 257 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */; } function isExternalModuleImportEquals(eq) { - return eq.moduleReference.kind === 272 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */; + return eq.moduleReference.kind === 273 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -122882,7 +126989,7 @@ var ts; if (!node) return undefined; switch (node.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return !ts.isVariableDeclarationList(node.parent) || node.parent.declarations.length !== 1 ? node : ts.isVariableStatement(node.parent.parent) ? @@ -122890,28 +126997,28 @@ var ts; ts.isForInOrOfStatement(node.parent.parent) ? getContextNode(node.parent.parent) : node.parent; - case 198 /* BindingElement */: + case 199 /* BindingElement */: return getContextNode(node.parent.parent); - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: return node.parent.parent.parent; - case 270 /* ExportSpecifier */: - case 263 /* NamespaceImport */: + case 271 /* ExportSpecifier */: + case 264 /* NamespaceImport */: return node.parent.parent; - case 262 /* ImportClause */: - case 269 /* NamespaceExport */: + case 263 /* ImportClause */: + case 270 /* NamespaceExport */: return node.parent; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return ts.isExpressionStatement(node.parent) ? node.parent : node; - case 239 /* ForOfStatement */: - case 238 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 239 /* ForInStatement */: return { start: node.initializer, end: node.expression }; - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent) ? getContextNode(ts.findAncestor(node.parent, function (node) { return ts.isBinaryExpression(node) || ts.isForInOrOfStatement(node); @@ -122968,9 +127075,9 @@ var ts; var node = ts.getTouchingPropertyName(sourceFile, position); var referenceEntries; var entries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); - if (node.parent.kind === 201 /* PropertyAccessExpression */ - || node.parent.kind === 198 /* BindingElement */ - || node.parent.kind === 202 /* ElementAccessExpression */ + if (node.parent.kind === 202 /* PropertyAccessExpression */ + || node.parent.kind === 199 /* BindingElement */ + || node.parent.kind === 203 /* ElementAccessExpression */ || node.kind === 105 /* SuperKeyword */) { referenceEntries = entries && __spreadArray([], entries); } @@ -122994,13 +127101,13 @@ var ts; } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { return undefined; } var checker = program.getTypeChecker(); // 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 === 289 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 290 /* ShorthandPropertyAssignment */) { var result_1 = []; Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_1.push(nodeEntry(node)); }); return result_1; @@ -123175,13 +127282,13 @@ var ts; if (symbol) { return getDefinitionKindAndDisplayParts(symbol, checker, node); } - else if (node.kind === 200 /* ObjectLiteralExpression */) { + else if (node.kind === 201 /* ObjectLiteralExpression */) { return { kind: "interface" /* interfaceElement */, displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(21 /* CloseParenToken */)] }; } - else if (node.kind === 221 /* ClassExpression */) { + else if (node.kind === 222 /* ClassExpression */) { return { kind: "local class" /* localClassElement */, displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(21 /* CloseParenToken */)] @@ -123242,47 +127349,47 @@ var ts; if (!!(decl.flags & 8388608 /* Ambient */)) return true; switch (decl.kind) { - case 216 /* BinaryExpression */: - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 217 /* BinaryExpression */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: case 87 /* DefaultKeyword */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: - case 270 /* ExportSpecifier */: - case 262 /* ImportClause */: // default import - case 260 /* ImportEqualsDeclaration */: - case 265 /* ImportSpecifier */: - case 253 /* InterfaceDeclaration */: - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: - case 280 /* JsxAttribute */: - case 256 /* ModuleDeclaration */: - case 259 /* NamespaceExportDeclaration */: - case 263 /* NamespaceImport */: - case 269 /* NamespaceExport */: - case 160 /* Parameter */: - case 289 /* ShorthandPropertyAssignment */: - case 254 /* TypeAliasDeclaration */: - case 159 /* TypeParameter */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: + case 271 /* ExportSpecifier */: + case 263 /* ImportClause */: // default import + case 261 /* ImportEqualsDeclaration */: + case 266 /* ImportSpecifier */: + case 254 /* InterfaceDeclaration */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: + case 281 /* JsxAttribute */: + case 257 /* ModuleDeclaration */: + case 260 /* NamespaceExportDeclaration */: + case 264 /* NamespaceImport */: + case 270 /* NamespaceExport */: + case 161 /* Parameter */: + case 290 /* ShorthandPropertyAssignment */: + case 255 /* TypeAliasDeclaration */: + case 160 /* TypeParameter */: return true; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return !!decl.body; - case 249 /* VariableDeclaration */: - case 163 /* PropertyDeclaration */: + case 250 /* VariableDeclaration */: + case 164 /* PropertyDeclaration */: return !!decl.initializer || ts.isCatchClause(decl.parent); - case 164 /* MethodSignature */: - case 162 /* PropertySignature */: - case 333 /* JSDocPropertyTag */: - case 326 /* JSDocParameterTag */: + case 165 /* MethodSignature */: + case 163 /* PropertySignature */: + case 337 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: return false; default: return ts.Debug.failBadSyntaxKind(decl); @@ -123304,7 +127411,7 @@ var ts; } if (ts.isSourceFile(node)) { var resolvedRef = ts.GoToDefinition.getReferenceAtPosition(node, position, program); - if (!resolvedRef) { + if (!(resolvedRef === null || resolvedRef === void 0 ? void 0 : resolvedRef.file)) { return undefined; } var moduleSymbol = program.getTypeChecker().getMergedSymbol(resolvedRef.file.symbol); @@ -123333,7 +127440,7 @@ var ts; if (!symbol) { // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. if (!options.implementations && ts.isStringLiteralLike(node)) { - if (ts.isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ true) || ts.isExternalModuleReference(node.parent) || ts.isImportDeclaration(node.parent) || ts.isImportCall(node.parent)) { + if (ts.isModuleSpecifierLike(node)) { var fileIncludeReasons = program.getFileIncludeReasons(); var referencedFileName = (_b = (_a = node.getSourceFile().resolvedModules) === null || _a === void 0 ? void 0 : _a.get(node.text)) === null || _b === void 0 ? void 0 : _b.resolvedFileName; var referencedFile = referencedFileName ? program.getSourceFile(referencedFileName) : undefined; @@ -123434,7 +127541,7 @@ var ts; result = references; continue; } - var _loop_3 = function (entry) { + var _loop_4 = function (entry) { if (!entry.definition || entry.definition.type !== 0 /* Symbol */) { result.push(entry); return "continue"; @@ -123466,7 +127573,7 @@ var ts; }; for (var _b = 0, references_2 = references; _b < references_2.length; _b++) { var entry = references_2[_b]; - _loop_3(entry); + _loop_4(entry); } } return result; @@ -123503,10 +127610,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; switch (decl.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) break; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { references.push(nodeEntry(decl.name)); } @@ -123518,7 +127625,7 @@ var ts; } } var exported = symbol.exports.get("export=" /* ExportEquals */); - if (exported) { + if (exported === null || exported === void 0 ? void 0 : exported.declarations) { for (var _b = 0, _c = exported.declarations; _b < _c.length; _b++) { var decl = _c[_b]; var sourceFile = decl.getSourceFile(); @@ -123581,14 +127688,14 @@ var ts; var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); - var exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); + var exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) || !symbol.declarations ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); if (exportSpecifier) { // When renaming at an export specifier, rename the export and not the thing being exported. getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); } - else if (node && node.kind === 87 /* DefaultKeyword */) { + else if (node && node.kind === 87 /* DefaultKeyword */ && symbol.escapedName === "default" /* Default */ && symbol.parent) { addReference(node, symbol, state); - searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.checkDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state); } else { var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === 2 /* Rename */, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); @@ -123614,7 +127721,7 @@ var ts; } function getSpecialSearchKind(node) { switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: case 132 /* ConstructorKeyword */: return 1 /* Constructor */; case 78 /* Identifier */: @@ -123745,8 +127852,8 @@ var ts; var sourceId = ts.getNodeId(sourceFile); var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = new ts.Set()); var anyNewSymbols = false; - for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { - var sym = symbols_3[_i]; + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var sym = symbols_2[_i]; anyNewSymbols = ts.tryAddToSet(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols; } return anyNewSymbols; @@ -123803,7 +127910,9 @@ var ts; for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { var node = _d[_c]; // Import specifiers should be handled by importSearches - if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) { + var symbol = checker.getSymbolAtLocation(node); + var hasExportAssignmentDeclaration = ts.some(symbol === null || symbol === void 0 ? void 0 : symbol.declarations, function (d) { return ts.tryCast(d, ts.isExportAssignment) ? true : false; }); + if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && (symbol === exportSymbol || hasExportAssignmentDeclaration)) { cb(node); } } @@ -123855,7 +127964,7 @@ var ts; // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 208 /* FunctionExpression */ || valueDeclaration.kind === 221 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 209 /* FunctionExpression */ || valueDeclaration.kind === 222 /* ClassExpression */)) { return valueDeclaration; } if (!declarations) { @@ -123863,9 +127972,9 @@ var ts; } // If this is private property or method, the scope is the containing class if (flags & (4 /* Property */ | 8192 /* Method */)) { - var privateDeclaration = ts.find(declarations, function (d) { return ts.hasEffectiveModifier(d, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(d); }); + var privateDeclaration = ts.find(declarations, function (d) { return ts.hasEffectiveModifier(d, 8 /* Private */) || ts.isPrivateIdentifierClassElementDeclaration(d); }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 252 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 253 /* ClassDeclaration */); } // Else this is a public property and could be accessed from anywhere. return undefined; @@ -123894,7 +128003,7 @@ var ts; // Different declarations have different containers, bail out return undefined; } - if (!container || container.kind === 297 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + if (!container || container.kind === 298 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -124110,6 +128219,10 @@ var ts; default: ts.Debug.assertNever(state.specialSearchKind); } + // Use the parent symbol if the location is commonjs require syntax on javascript files only. + referenceSymbol = ts.isInJSFile(referenceLocation) && referenceLocation.parent.kind === 199 /* BindingElement */ && ts.isRequireVariableDeclaration(referenceLocation.parent) + ? referenceLocation.parent.symbol + : referenceSymbol; getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { @@ -124272,14 +128385,14 @@ var ts; for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; var ctrKeyword = ts.findChildOfKind(decl, 132 /* ConstructorKeyword */, sourceFile); - ts.Debug.assert(decl.kind === 166 /* Constructor */ && !!ctrKeyword); + ts.Debug.assert(decl.kind === 167 /* Constructor */ && !!ctrKeyword); addNode(ctrKeyword); } } if (classSymbol.exports) { classSymbol.exports.forEach(function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 165 /* MethodDeclaration */) { + if (decl && decl.kind === 166 /* MethodDeclaration */) { var body = decl.body; if (body) { forEachDescendantOfKind(body, 107 /* ThisKeyword */, function (thisKeyword) { @@ -124303,7 +128416,7 @@ var ts; } for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 166 /* Constructor */); + ts.Debug.assert(decl.kind === 167 /* Constructor */); var body = decl.body; if (body) { forEachDescendantOfKind(body, 105 /* SuperKeyword */, function (node) { @@ -124333,7 +128446,7 @@ var ts; if (refNode.kind !== 78 /* Identifier */) { return; } - if (refNode.parent.kind === 289 /* ShorthandPropertyAssignment */) { + if (refNode.parent.kind === 290 /* ShorthandPropertyAssignment */) { // Go ahead and dereference the shorthand assignment by going to its definition getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); } @@ -124353,7 +128466,7 @@ var ts; } else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) { var body = typeHavingNode.body; - if (body.kind === 230 /* Block */) { + if (body.kind === 231 /* Block */) { ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression) addIfImplementation(returnStatement.expression); @@ -124381,13 +128494,13 @@ var ts; */ function isImplementationExpression(node) { switch (node.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isImplementationExpression(node.expression); - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: - case 200 /* ObjectLiteralExpression */: - case 221 /* ClassExpression */: - case 199 /* ArrayLiteralExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 201 /* ObjectLiteralExpression */: + case 222 /* ClassExpression */: + case 200 /* ArrayLiteralExpression */: return true; default: return false; @@ -124440,13 +128553,13 @@ var ts; // Whether 'super' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -124467,41 +128580,43 @@ var ts; return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function isParameterName(node) { - return node.kind === 78 /* Identifier */ && node.parent.kind === 160 /* Parameter */ && node.parent.name === node; + return node.kind === 78 /* Identifier */ && node.parent.kind === 161 /* Parameter */ && node.parent.name === node; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { + staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning object literals break; } // falls through - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) { return undefined; } // falls through - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: break; // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. default: return undefined; } - var references = ts.flatMap(searchSpaceNode.kind === 297 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { + var references = ts.flatMap(searchSpaceNode.kind === 298 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) { if (!ts.isThis(node)) { @@ -124509,19 +128624,20 @@ var ts; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: return searchSpaceNode.symbol === container.symbol; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: - // Make sure the container belongs to the same class + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 201 /* ObjectLiteralExpression */: + // Make sure the container belongs to the same class/object literals // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getSyntacticModifierFlags(container) & 32 /* Static */) === staticFlag; - case 297 /* SourceFile */: - return container.kind === 297 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node); + case 298 /* SourceFile */: + return container.kind === 298 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node); } }); }).map(function (n) { return nodeEntry(n); }); @@ -124631,7 +128747,7 @@ 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]); } - var exportSpecifier = ts.getDeclarationOfKind(symbol, 270 /* ExportSpecifier */); + var exportSpecifier = ts.getDeclarationOfKind(symbol, 271 /* ExportSpecifier */); if (!isForRenamePopulateSearchSymbolSet || exportSpecifier && !exportSpecifier.propertyName) { var localSymbol = exportSpecifier && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); if (localSymbol) { @@ -124676,7 +128792,7 @@ var ts; }); } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - var bindingElement = ts.getDeclarationOfKind(symbol, 198 /* BindingElement */); + var bindingElement = ts.getDeclarationOfKind(symbol, 199 /* BindingElement */); if (bindingElement && ts.isObjectBindingElementWithoutPropertyName(bindingElement)) { return ts.getPropertySymbolFromBindingElement(checker, bindingElement); } @@ -124929,16 +129045,16 @@ var ts; return; } switch (node.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: - if (node.parent.kind === 200 /* ObjectLiteralExpression */) { + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + if (node.parent.kind === 201 /* ObjectLiteralExpression */) { return (_a = ts.getAssignedName(node.parent)) === null || _a === void 0 ? void 0 : _a.getText(); } return (_b = ts.getNameOfDeclaration(node.parent)) === null || _b === void 0 ? void 0 : _b.getText(); - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: if (ts.isModuleBlock(node.parent) && ts.isIdentifier(node.parent.parent.name)) { return node.parent.parent.name.getText(); } @@ -125144,55 +129260,55 @@ var ts; } switch (node.kind) { case 78 /* Identifier */: - case 260 /* ImportEqualsDeclaration */: - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: // do not descend into nodes that cannot contain callable nodes return; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: // do not descend into the type side of an assertion collect(node.expression); return; - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: // do not descend into the type of a variable or parameter declaration collect(node.name); collect(node.initializer); return; - case 203 /* CallExpression */: + case 204 /* CallExpression */: // do not descend into the type arguments of a call expression recordCallSite(node); collect(node.expression); ts.forEach(node.arguments, collect); return; - case 204 /* NewExpression */: + case 205 /* NewExpression */: // do not descend into the type arguments of a new expression recordCallSite(node); collect(node.expression); ts.forEach(node.arguments, collect); return; - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: // do not descend into the type arguments of a tagged template expression recordCallSite(node); collect(node.tag); collect(node.template); return; - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: // do not descend into the type arguments of a JsxOpeningLikeElement recordCallSite(node); collect(node.tagName); collect(node.attributes); return; - case 161 /* Decorator */: + case 162 /* Decorator */: recordCallSite(node); collect(node.expression); return; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: recordCallSite(node); ts.forEachChild(node, collect); break; @@ -125242,22 +129358,22 @@ var ts; var callSites = []; var collect = createCallSiteCollector(program, callSites); switch (node.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: collectCallSitesOfSourceFile(node, collect); break; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: collectCallSitesOfModuleDeclaration(node, collect); break; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: collectCallSitesOfFunctionLikeDeclaration(program.getTypeChecker(), node, collect); break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: collectCallSitesOfClassLikeDeclaration(node, collect); break; default: @@ -125390,7 +129506,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_4 = function (sourceFile) { + var _loop_5 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.fileName); var newImportFromPath = newFromOld !== null && newFromOld !== void 0 ? newFromOld : sourceFile.fileName; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -125407,7 +129523,7 @@ var ts; }, function (importLiteral) { var importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); // No need to update if it's an ambient module^M - if (importedModuleSymbol && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) + if ((importedModuleSymbol === null || importedModuleSymbol === void 0 ? void 0 : importedModuleSymbol.declarations) && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) return undefined; var toImport = oldFromNew !== undefined // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. @@ -125422,7 +129538,7 @@ var ts; }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_4(sourceFile); + _loop_5(sourceFile); } } function combineNormal(pathA, pathB) { @@ -125513,8 +129629,10 @@ var ts; (function (GoToDefinition) { function getDefinitionAtPosition(program, sourceFile, position) { var resolvedRef = getReferenceAtPosition(sourceFile, position, program); - if (resolvedRef) { - return [getDefinitionInfoForFileReference(resolvedRef.reference.fileName, resolvedRef.file.fileName)]; + var fileReferenceDefinition = resolvedRef && [getDefinitionInfoForFileReference(resolvedRef.reference.fileName, resolvedRef.fileName, resolvedRef.unverified)] || ts.emptyArray; + if (resolvedRef === null || resolvedRef === void 0 ? void 0 : resolvedRef.file) { + // If `file` is missing, do a symbol-based lookup as well + return fileReferenceDefinition; } var node = ts.getTouchingPropertyName(sourceFile, position); if (node === sourceFile) { @@ -125531,7 +129649,7 @@ var ts; // Could not find a symbol e.g. node is string or number keyword, // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol if (!symbol) { - return getDefinitionInfoForIndexSignatures(node, typeChecker); + return ts.concatenate(fileReferenceDefinition, getDefinitionInfoForIndexSignatures(node, typeChecker)); } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. @@ -125553,9 +129671,10 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 289 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 290 /* ShorthandPropertyAssignment */) { var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); - return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : []; + var definitions = (shorthandSymbol_1 === null || shorthandSymbol_1 === void 0 ? void 0 : shorthandSymbol_1.declarations) ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : ts.emptyArray; + return ts.concatenate(definitions, getDefinitionFromObjectLiteralElement(typeChecker, node) || ts.emptyArray); } // If the node is the name of a BindingElement within an ObjectBindingPattern instead of just returning the // declaration the symbol (which is itself), we should try to get to the original type of the ObjectBindingPattern @@ -125577,25 +129696,7 @@ var ts; return prop && getDefinitionFromSymbol(typeChecker, prop, node); }); } - // If the current location we want to find its definition is in an object literal, try to get the contextual type for the - // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. - // For example - // interface Props{ - // /*first*/prop1: number - // prop2: boolean - // } - // function Foo(arg: Props) {} - // Foo( { pr/*1*/op1: 10, prop2: true }) - var element = ts.getContainingObjectLiteralElement(node); - if (element) { - var contextualType = element && typeChecker.getContextualType(element.parent); - if (contextualType) { - return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) { - return getDefinitionFromSymbol(typeChecker, propertySymbol, node); - }); - } - } - return getDefinitionFromSymbol(typeChecker, symbol, node); + return ts.concatenate(fileReferenceDefinition, getDefinitionFromObjectLiteralElement(typeChecker, node) || getDefinitionFromSymbol(typeChecker, symbol, node)); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; /** @@ -125609,22 +129710,60 @@ var ts; || ts.isAssignmentExpression(calledDeclaration.parent) || (!ts.isCallLikeExpression(calledDeclaration.parent) && s === calledDeclaration.parent.symbol); } + // If the current location we want to find its definition is in an object literal, try to get the contextual type for the + // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. + // For example + // interface Props{ + // /*first*/prop1: number + // prop2: boolean + // } + // function Foo(arg: Props) {} + // Foo( { pr/*1*/op1: 10, prop2: true }) + function getDefinitionFromObjectLiteralElement(typeChecker, node) { + var element = ts.getContainingObjectLiteralElement(node); + if (element) { + var contextualType = element && typeChecker.getContextualType(element.parent); + if (contextualType) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); + } + } + } function getReferenceAtPosition(sourceFile, position, program) { + var _a, _b; var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); if (referencePath) { var file = program.getSourceFileFromReference(sourceFile, referencePath); - return file && { reference: referencePath, file: file }; + return file && { reference: referencePath, fileName: file.fileName, file: file, unverified: false }; } var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); var file = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217 - return file && { reference: typeReferenceDirective, file: file }; + return file && { reference: typeReferenceDirective, fileName: file.fileName, file: file, unverified: false }; } var libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position); if (libReferenceDirective) { var file = program.getLibFileFromReference(libReferenceDirective); - return file && { reference: libReferenceDirective, file: file }; + return file && { reference: libReferenceDirective, fileName: file.fileName, file: file, unverified: false }; + } + if ((_a = sourceFile.resolvedModules) === null || _a === void 0 ? void 0 : _a.size) { + var node = ts.getTokenAtPosition(sourceFile, position); + if (ts.isModuleSpecifierLike(node) && ts.isExternalModuleNameRelative(node.text) && sourceFile.resolvedModules.has(node.text)) { + var verifiedFileName = (_b = sourceFile.resolvedModules.get(node.text)) === null || _b === void 0 ? void 0 : _b.resolvedFileName; + var fileName = verifiedFileName || ts.resolvePath(ts.getDirectoryPath(sourceFile.fileName), node.text); + return { + file: program.getSourceFile(fileName), + fileName: fileName, + reference: { + pos: node.getStart(), + end: node.getEnd(), + fileName: node.text + }, + unverified: !verifiedFileName, + }; + } } return undefined; } @@ -125695,7 +129834,7 @@ var ts; // get the aliased symbol instead. This allows for goto def on an import e.g. // import {A, B} from "mod"; // to jump to the implementation directly. - if (symbol && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { + if ((symbol === null || symbol === void 0 ? void 0 : symbol.declarations) && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { var aliased = checker.getAliasedSymbol(symbol); if (aliased.declarations) { return aliased; @@ -125716,14 +129855,14 @@ var ts; return true; } switch (declaration.kind) { - case 262 /* ImportClause */: - case 260 /* ImportEqualsDeclaration */: + case 263 /* ImportClause */: + case 261 /* ImportEqualsDeclaration */: return true; - case 265 /* ImportSpecifier */: - return declaration.parent.kind === 264 /* NamedImports */; - case 198 /* BindingElement */: - case 249 /* VariableDeclaration */: - return ts.isInJSFile(declaration) && ts.isRequireVariableDeclaration(declaration, /*requireStringLiteralLikeArgument*/ true); + case 266 /* ImportSpecifier */: + return declaration.parent.kind === 265 /* NamedImports */; + case 199 /* BindingElement */: + case 250 /* VariableDeclaration */: + return ts.isInJSFile(declaration) && ts.isRequireVariableDeclaration(declaration); default: return false; } @@ -125775,7 +129914,38 @@ var ts; var sourceFile = name.getSourceFile(); var textSpan = ts.createTextSpanFromNode(name, sourceFile); return __assign(__assign({ fileName: sourceFile.fileName, textSpan: textSpan, kind: symbolKind, name: symbolName, containerKind: undefined, // TODO: GH#18217 - containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !checker.isDeclarationVisible(declaration) }); + containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !isDefinitionVisible(checker, declaration) }); + } + function isDefinitionVisible(checker, declaration) { + if (checker.isDeclarationVisible(declaration)) + return true; + if (!declaration.parent) + return false; + // Variable initializers are visible if variable is visible + if (ts.hasInitializer(declaration.parent) && declaration.parent.initializer === declaration) + return isDefinitionVisible(checker, declaration.parent); + // Handle some exceptions here like arrow function, members of class and object literal expression which are technically not visible but we want the definition to be determined by its parent + switch (declaration.kind) { + case 164 /* PropertyDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + // Private/protected properties/methods are not visible + if (ts.hasEffectiveModifier(declaration, 8 /* Private */)) + return false; + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 167 /* Constructor */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 201 /* ObjectLiteralExpression */: + case 222 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + return isDefinitionVisible(checker, declaration.parent); + default: + return false; + } } function createDefinitionFromSignatureDeclaration(typeChecker, decl) { return createDefinitionInfo(decl, typeChecker, decl.symbol, decl); @@ -125784,14 +129954,15 @@ var ts; return ts.find(refs, function (ref) { return ts.textRangeContainsPositionInclusive(ref, pos); }); } GoToDefinition.findReferenceInPosition = findReferenceInPosition; - function getDefinitionInfoForFileReference(name, targetFileName) { + function getDefinitionInfoForFileReference(name, targetFileName, unverified) { return { fileName: targetFileName, textSpan: ts.createTextSpanFromBounds(0, 0), kind: "script" /* scriptElement */, name: name, containerName: undefined, - containerKind: undefined, // TODO: GH#18217 + containerKind: undefined, + unverified: unverified, }; } /** Returns a CallLikeExpression where `node` is the target being invoked. */ @@ -125808,9 +129979,9 @@ var ts; } function isConstructorLike(node) { switch (node.kind) { - case 166 /* Constructor */: - case 175 /* ConstructorType */: - case 170 /* ConstructSignature */: + case 167 /* Constructor */: + case 176 /* ConstructorType */: + case 171 /* ConstructSignature */: return true; default: return false; @@ -125867,6 +130038,7 @@ var ts; "kind", "lends", "license", + "link", "listens", "member", "memberof", @@ -125904,78 +130076,115 @@ var ts; ]; var jsDocTagNameCompletionEntries; var jsDocTagCompletionEntries; - function getJsDocCommentsFromDeclarations(declarations) { + function getJsDocCommentsFromDeclarations(declarations, checker) { // Only collect doc comments from duplicate declarations once: // In case of a union property there might be same declaration multiple times // which only varies in type parameter // Eg. const a: Array | Array; a.length // The property length will have two declarations of property length coming // from Array - Array and Array - var documentationComment = []; + var parts = []; ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { var comment = _a[_i].comment; if (comment === undefined) continue; - ts.pushIfUnique(documentationComment, comment); + var newparts = getDisplayPartsFromComment(comment, checker); + if (!ts.contains(parts, newparts, isIdenticalListOfDisplayParts)) { + parts.push(newparts); + } } }); - return ts.intersperse(ts.map(documentationComment, ts.textPart), ts.lineBreakPart()); + return ts.flatten(ts.intersperse(parts, [ts.lineBreakPart()])); } JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function isIdenticalListOfDisplayParts(parts1, parts2) { + return ts.arraysEqual(parts1, parts2, function (p1, p2) { return p1.kind === p2.kind && p1.text === p2.text; }); + } function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 326 /* JSDocParameterTag */: - case 333 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: return [declaration]; - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); } } - function getJsDocTagsFromDeclarations(declarations) { + function getJsDocTagsFromDeclarations(declarations, checker) { // Only collect doc comments from duplicate declarations once. var tags = []; ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { var tag = _a[_i]; - tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); + tags.push({ name: tag.tagName.text, text: getCommentDisplayParts(tag, checker) }); } }); return tags; } JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations; - function getCommentText(tag) { - var comment = tag.comment; - switch (tag.kind) { - case 316 /* JSDocImplementsTag */: + function getDisplayPartsFromComment(comment, checker) { + if (typeof comment === "string") { + return [ts.textPart(comment)]; + } + return ts.flatMap(comment, function (node) { return node.kind === 313 /* JSDocText */ ? [ts.textPart(node.text)] : ts.buildLinkParts(node, checker); }); + } + function getCommentDisplayParts(tag, checker) { + var comment = tag.comment, kind = tag.kind; + var namePart = getTagNameDisplayPart(kind); + switch (kind) { + case 319 /* JSDocImplementsTag */: return withNode(tag.class); - case 315 /* JSDocAugmentsTag */: + case 318 /* JSDocAugmentsTag */: return withNode(tag.class); - case 330 /* JSDocTemplateTag */: - return withList(tag.typeParameters); - case 329 /* JSDocTypeTag */: + case 334 /* JSDocTemplateTag */: + return addComment(tag.typeParameters.map(function (tp) { return tp.getText(); }).join(", ")); + case 333 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 333 /* JSDocPropertyTag */: - case 326 /* JSDocParameterTag */: - case 332 /* JSDocSeeTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 337 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: + case 336 /* JSDocSeeTag */: var name = tag.name; - return name ? withNode(name) : comment; + return name ? withNode(name) + : comment === undefined ? undefined + : getDisplayPartsFromComment(comment, checker); default: - return comment; + return comment === undefined ? undefined : getDisplayPartsFromComment(comment, checker); } function withNode(node) { return addComment(node.getText()); } - function withList(list) { - return addComment(list.map(function (x) { return x.getText(); }).join(", ")); - } function addComment(s) { - return comment === undefined ? s : s + " " + comment; + if (comment) { + if (s.match(/^https?$/)) { + return __spreadArray([ts.textPart(s)], getDisplayPartsFromComment(comment, checker)); + } + else { + return __spreadArray([namePart(s), ts.spacePart()], getDisplayPartsFromComment(comment, checker)); + } + } + else { + return [ts.textPart(s)]; + } + } + } + function getTagNameDisplayPart(kind) { + switch (kind) { + case 330 /* JSDocParameterTag */: + return ts.parameterNamePart; + case 337 /* JSDocPropertyTag */: + return ts.propertyNamePart; + case 334 /* JSDocTemplateTag */: + return ts.typeParameterNamePart; + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + return ts.typeAliasNamePart; + default: + return ts.textPart; } } function getJSDocTagNameCompletions() { @@ -126069,7 +130278,7 @@ var ts; * @param position The (character-indexed) position in the file where the check should * be performed. */ - function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { + function getDocCommentTemplateAtPosition(newLine, sourceFile, position, options) { var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc); if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) { @@ -126081,7 +130290,7 @@ var ts; if (!existingDocComment && tokenStart < position) { return undefined; } - var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); + var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos, options); if (!commentOwnerInfo) { return undefined; } @@ -126131,76 +130340,77 @@ var ts; function returnsDocComment(indentationStr, newLine) { return indentationStr + " * @returns" + newLine; } - function getCommentOwnerInfo(tokenAtPos) { - return ts.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker); + function getCommentOwnerInfo(tokenAtPos, options) { + return ts.forEachAncestor(tokenAtPos, function (n) { return getCommentOwnerInfoWorker(n, options); }); } - function getCommentOwnerInfoWorker(commentOwner) { + function getCommentOwnerInfoWorker(commentOwner, options) { switch (commentOwner.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 164 /* MethodSignature */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 165 /* MethodSignature */: + case 210 /* ArrowFunction */: var host = commentOwner; - return { commentOwner: commentOwner, parameters: host.parameters, hasReturn: hasReturn(host) }; - case 288 /* PropertyAssignment */: - return getCommentOwnerInfoWorker(commentOwner.initializer); - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 162 /* PropertySignature */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: - case 254 /* TypeAliasDeclaration */: + return { commentOwner: commentOwner, parameters: host.parameters, hasReturn: hasReturn(host, options) }; + case 289 /* PropertyAssignment */: + return getCommentOwnerInfoWorker(commentOwner.initializer, options); + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 163 /* PropertySignature */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: + case 255 /* TypeAliasDeclaration */: return { commentOwner: commentOwner }; - case 232 /* VariableStatement */: { + case 233 /* VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; var host_1 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; return host_1 - ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1) } + ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1, options) } : { commentOwner: commentOwner }; } - case 297 /* SourceFile */: + case 298 /* SourceFile */: return "quit"; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: // If in walking up the tree, we hit a a nested namespace declaration, // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - return commentOwner.parent.kind === 256 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; - case 233 /* ExpressionStatement */: - return getCommentOwnerInfoWorker(commentOwner.expression); - case 216 /* BinaryExpression */: { + return commentOwner.parent.kind === 257 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 234 /* ExpressionStatement */: + return getCommentOwnerInfoWorker(commentOwner.expression, options); + case 217 /* BinaryExpression */: { var be = commentOwner; if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } return ts.isFunctionLike(be.right) - ? { commentOwner: commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right) } + ? { commentOwner: commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right, options) } : { commentOwner: commentOwner }; } - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: var init = commentOwner.initializer; if (init && (ts.isFunctionExpression(init) || ts.isArrowFunction(init))) { - return { commentOwner: commentOwner, parameters: init.parameters, hasReturn: hasReturn(init) }; + return { commentOwner: commentOwner, parameters: init.parameters, hasReturn: hasReturn(init, options) }; } } } - function hasReturn(node) { - return ts.isArrowFunction(node) && ts.isExpression(node.body) - || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; }); + function hasReturn(node, options) { + return !!(options === null || options === void 0 ? void 0 : options.generateReturnInDocTemplate) && + (ts.isArrowFunction(node) && ts.isExpression(node.body) + || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; })); } function getRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 207 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 208 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return rightHandSide; - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return ts.find(rightHandSide.members, ts.isConstructorDeclaration); } } @@ -126216,7 +130426,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_5 = function (sourceFile) { + var _loop_6 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -126228,7 +130438,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var sourceFile = sourceFiles_4[_i]; - _loop_5(sourceFile); + _loop_6(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -126259,9 +130469,9 @@ var ts; } function shouldKeepItem(declaration, checker) { switch (declaration.kind) { - case 262 /* ImportClause */: - case 265 /* ImportSpecifier */: - case 260 /* ImportEqualsDeclaration */: + case 263 /* ImportClause */: + case 266 /* ImportSpecifier */: + case 261 /* ImportEqualsDeclaration */: var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217 var imported = checker.getAliasedSymbol(importer); return importer.escapedName !== imported.escapedName; @@ -126271,7 +130481,7 @@ var ts; } function tryAddSingleDeclarationName(declaration, containers) { var name = ts.getNameOfDeclaration(declaration); - return !!name && (pushLiteral(name, containers) || name.kind === 158 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); + return !!name && (pushLiteral(name, containers) || name.kind === 159 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); } // Only added the names of computed properties if they're simple dotted expressions, like: // @@ -126288,7 +130498,7 @@ var ts; // First, if we started with a computed property name, then add all but the last // portion into the container array. var name = ts.getNameOfDeclaration(declaration); - if (name && name.kind === 158 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { + if (name && name.kind === 159 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { return ts.emptyArray; } // Don't include the last portion. @@ -126488,6 +130698,28 @@ var ts; addChildrenRecursively(child); endNode(); } + function addNodeWithRecursiveInitializer(node) { + if (node.initializer && isFunctionOrClassExpression(node.initializer)) { + startNode(node); + ts.forEachChild(node.initializer, addChildrenRecursively); + endNode(); + } + else { + addNodeWithRecursiveChild(node, node.initializer); + } + } + /** + * Historically, we've elided dynamic names from the nav tree (including late bound names), + * but included certain "well known" symbol names. While we no longer distinguish those well-known + * symbols from other unique symbols, we do the below to retain those members in the nav tree. + */ + function hasNavigationBarName(node) { + return !ts.hasDynamicName(node) || + (node.kind !== 217 /* BinaryExpression */ && + ts.isPropertyAccessExpression(node.name.expression) && + ts.isIdentifier(node.name.expression.expression) && + ts.idText(node.name.expression.expression) === "Symbol"); + } /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ function addChildrenRecursively(node) { var _a; @@ -126496,7 +130728,7 @@ var ts; return; } switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. var ctr = node; addNodeWithRecursiveChild(ctr, ctr.body); @@ -126508,21 +130740,25 @@ var ts; } } break; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 164 /* MethodSignature */: - if (!ts.hasDynamicName(node)) { + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 165 /* MethodSignature */: + if (hasNavigationBarName(node)) { addNodeWithRecursiveChild(node, node.body); } break; - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - if (!ts.hasDynamicName(node)) { + case 164 /* PropertyDeclaration */: + if (hasNavigationBarName(node)) { + addNodeWithRecursiveInitializer(node); + } + break; + case 163 /* PropertySignature */: + if (hasNavigationBarName(node)) { addLeafNode(node); } break; - case 262 /* ImportClause */: + case 263 /* ImportClause */: var importClause = node; // Handle default import case e.g.: // import d from "mod"; @@ -126534,7 +130770,7 @@ var ts; // import {a, b as B} from "mod"; var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 263 /* NamespaceImport */) { + if (namedBindings.kind === 264 /* NamespaceImport */) { addLeafNode(namedBindings); } else { @@ -126545,32 +130781,27 @@ var ts; } } break; - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: addNodeWithRecursiveChild(node, node.name); break; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: var expression = node.expression; // Use the expression as the name of the SpreadAssignment, otherwise show as . ts.isIdentifier(expression) ? addLeafNode(node, expression) : addLeafNode(node); break; - case 198 /* BindingElement */: - case 288 /* PropertyAssignment */: - case 249 /* VariableDeclaration */: - var _e = node, name = _e.name, initializer = _e.initializer; - if (ts.isBindingPattern(name)) { - addChildrenRecursively(name); - } - else if (initializer && isFunctionOrClassExpression(initializer)) { - // Add a node for the VariableDeclaration, but not for the initializer. - startNode(node); - ts.forEachChild(initializer, addChildrenRecursively); - endNode(); + case 199 /* BindingElement */: + case 289 /* PropertyAssignment */: + case 250 /* VariableDeclaration */: { + var child = node; + if (ts.isBindingPattern(child.name)) { + addChildrenRecursively(child.name); } else { - addNodeWithRecursiveChild(node, initializer); + addNodeWithRecursiveInitializer(child); } break; - case 251 /* FunctionDeclaration */: + } + case 252 /* FunctionDeclaration */: var nameNode = node.name; // If we see a function declaration track as a possible ES5 class if (nameNode && ts.isIdentifier(nameNode)) { @@ -126578,34 +130809,34 @@ var ts; } addNodeWithRecursiveChild(node, node.body); break; - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: addNodeWithRecursiveChild(node, node.body); break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: startNode(node); - for (var _f = 0, _g = node.members; _f < _g.length; _f++) { - var member = _g[_f]; + for (var _e = 0, _f = node.members; _e < _f.length; _e++) { + var member = _f[_e]; if (!isComputedProperty(member)) { addLeafNode(member); } } endNode(); break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: startNode(node); - for (var _h = 0, _j = node.members; _h < _j.length; _h++) { - var member = _j[_h]; + for (var _g = 0, _h = node.members; _g < _h.length; _g++) { + var member = _h[_g]; addChildrenRecursively(member); } endNode(); break; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 266 /* ExportAssignment */: { + case 267 /* ExportAssignment */: { var expression_1 = node.expression; var child = ts.isObjectLiteralExpression(expression_1) || ts.isCallExpression(expression_1) ? expression_1 : ts.isArrowFunction(expression_1) || ts.isFunctionExpression(expression_1) ? expression_1.body : undefined; @@ -126619,16 +130850,16 @@ var ts; } break; } - case 270 /* ExportSpecifier */: - case 260 /* ImportEqualsDeclaration */: - case 171 /* IndexSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 254 /* TypeAliasDeclaration */: + case 271 /* ExportSpecifier */: + case 261 /* ImportEqualsDeclaration */: + case 172 /* IndexSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 255 /* TypeAliasDeclaration */: addLeafNode(node); break; - case 203 /* CallExpression */: - case 216 /* BinaryExpression */: { + case 204 /* CallExpression */: + case 217 /* BinaryExpression */: { var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: @@ -126680,7 +130911,7 @@ var ts; defineCall.arguments[0] : defineCall.arguments[0].expression; var memberName = defineCall.arguments[1]; - var _k = startNestedNodes(node, className), depth = _k[0], classNameIdentifier = _k[1]; + var _j = startNestedNodes(node, className), depth = _j[0], classNameIdentifier = _j[1]; startNode(node, classNameIdentifier); startNode(node, ts.setTextRange(ts.factory.createIdentifier(memberName.text), memberName)); addChildrenRecursively(node.arguments[2]); @@ -126870,13 +131101,14 @@ var ts; return false; } switch (a.kind) { - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return ts.hasSyntacticModifier(a, 32 /* Static */) === ts.hasSyntacticModifier(b, 32 /* Static */); - case 256 /* ModuleDeclaration */: - return areSameModule(a, b); + case 257 /* ModuleDeclaration */: + return areSameModule(a, b) + && getFullyQualifiedModuleName(a) === getFullyQualifiedModuleName(b); default: return true; } @@ -126893,8 +131125,7 @@ var ts; // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { - // TODO: GH#18217 - return a.body.kind === b.body.kind && (a.body.kind !== 256 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); + return a.body.kind === b.body.kind && (a.body.kind !== 257 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); } /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { @@ -126924,7 +131155,7 @@ var ts; * So `new()` can still come before an `aardvark` method. */ function tryGetName(node) { - if (node.kind === 256 /* ModuleDeclaration */) { + if (node.kind === 257 /* ModuleDeclaration */) { return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); @@ -126933,16 +131164,16 @@ var ts; return propertyName && ts.unescapeLeadingUnderscores(propertyName); } switch (node.kind) { - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 221 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 222 /* ClassExpression */: return getFunctionOrClassName(node); default: return undefined; } } function getItemName(node, name) { - if (node.kind === 256 /* ModuleDeclaration */) { + if (node.kind === 257 /* ModuleDeclaration */) { return cleanText(getModuleName(node)); } if (name) { @@ -126954,18 +131185,18 @@ var ts; } } switch (node.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: var sourceFile = node; return ts.isExternalModule(sourceFile) ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" : ""; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return ts.isExportAssignment(node) && node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; - case 209 /* ArrowFunction */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: if (ts.getSyntacticModifierFlags(node) & 512 /* Default */) { return "default"; } @@ -126973,13 +131204,13 @@ var ts; // (eg: "app\n.onactivated"), so we should remove the whitespace for readability in the // navigation bar. return getFunctionOrClassName(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return "constructor"; - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: return "new()"; - case 169 /* CallSignature */: + case 170 /* CallSignature */: return "()"; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: return "[]"; default: return ""; @@ -127012,19 +131243,19 @@ var ts; } // Some nodes are otherwise important enough to always include in the primary navigation menu. switch (navigationBarNodeKind(item)) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 255 /* EnumDeclaration */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 297 /* SourceFile */: - case 254 /* TypeAliasDeclaration */: - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 256 /* EnumDeclaration */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 298 /* SourceFile */: + case 255 /* TypeAliasDeclaration */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: return true; - case 209 /* ArrowFunction */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; @@ -127034,10 +131265,10 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 257 /* ModuleBlock */: - case 297 /* SourceFile */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: + case 258 /* ModuleBlock */: + case 298 /* SourceFile */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: return true; default: return false; @@ -127094,9 +131325,12 @@ var ts; if (ts.isAmbientModule(moduleDeclaration)) { return ts.getTextOfNode(moduleDeclaration.name); } + return getFullyQualifiedModuleName(moduleDeclaration); + } + function getFullyQualifiedModuleName(moduleDeclaration) { // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = [ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)]; - while (moduleDeclaration.body && moduleDeclaration.body.kind === 256 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 257 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } @@ -127110,13 +131344,13 @@ var ts; return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { - return !member.name || member.name.kind === 158 /* ComputedPropertyName */; + return !member.name || member.name.kind === 159 /* ComputedPropertyName */; } function getNodeSpan(node) { - return node.kind === 297 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); + return node.kind === 298 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); } function getModifiers(node) { - if (node.parent && node.parent.kind === 249 /* VariableDeclaration */) { + if (node.parent && node.parent.kind === 250 /* VariableDeclaration */) { node = node.parent; } return ts.getNodeModifiers(node); @@ -127174,9 +131408,9 @@ var ts; } function isFunctionOrClassExpression(node) { switch (node.kind) { - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: - case 221 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 222 /* ClassExpression */: return true; default: return false; @@ -127205,9 +131439,9 @@ var ts; * 2) Coalescing imports from the same module * 3) Sorting imports */ - function organizeImports(sourceFile, formatContext, host, program, preferences) { + function organizeImports(sourceFile, formatContext, host, program, preferences, skipDestructiveCodeActions) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext, preferences: preferences }); - var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; + var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program, skipDestructiveCodeActions)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; // All of the old ImportDeclarations in the file, in syntactic order. var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports); @@ -127242,26 +131476,35 @@ var ts; ? coalesce(importGroup) : importGroup; }); - // Delete or replace the first import. + // Delete all nodes if there are no imports. if (newImportDecls.length === 0) { - changeTracker.delete(sourceFile, oldImportDecls[0]); + // Consider the first node to have trailingTrivia as we want to exclude the + // "header" comment. + changeTracker.deleteNodes(sourceFile, oldImportDecls, { + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, + }, /*hasTrailingComment*/ true); } else { // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. - changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { + var replaceOptions = { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), - }); - } - // Delete any subsequent imports. - for (var i = 1; i < oldImportDecls.length; i++) { - changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + }; + changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, replaceOptions); + var hasTrailingComment = changeTracker.nodeHasTrailingComment(sourceFile, oldImportDecls[0], replaceOptions); + changeTracker.deleteNodes(sourceFile, oldImportDecls.slice(1), { + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, + }, hasTrailingComment); } } } OrganizeImports.organizeImports = organizeImports; - function removeUnusedImports(oldImports, sourceFile, program) { + function removeUnusedImports(oldImports, sourceFile, program, skipDestructiveCodeActions) { + // As a precaution, consider unused import detection to be destructive (GH #43051) + if (skipDestructiveCodeActions) { + return oldImports; + } var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); var jsxFragmentFactory = typeChecker.getJsxFragmentFactory(sourceFile); @@ -127532,11 +131775,11 @@ var ts; function getModuleSpecifierExpression(declaration) { var _a; switch (declaration.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return (_a = ts.tryCast(declaration.moduleReference, ts.isExternalModuleReference)) === null || _a === void 0 ? void 0 : _a.expression; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return declaration.moduleSpecifier; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return declaration.declarationList.declarations[0].initializer.arguments[0]; } } @@ -127575,19 +131818,19 @@ var ts; function getImportKindOrder(s1) { var _a; switch (s1.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: if (!s1.importClause) return 0; if (s1.importClause.isTypeOnly) return 1; - if (((_a = s1.importClause.namedBindings) === null || _a === void 0 ? void 0 : _a.kind) === 263 /* NamespaceImport */) + if (((_a = s1.importClause.namedBindings) === null || _a === void 0 ? void 0 : _a.kind) === 264 /* NamespaceImport */) return 2; if (s1.importClause.name) return 3; return 4; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return 5; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return 6; } } @@ -127743,7 +131986,7 @@ var ts; } function getOutliningSpanForNode(n, sourceFile) { switch (n.kind) { - case 230 /* Block */: + case 231 /* Block */: if (ts.isFunctionLike(n.parent)) { return functionSpan(n.parent, n, sourceFile); } @@ -127751,16 +131994,16 @@ var ts; // If the latter, we want to collapse the block, but consider its hint span // to be the entire span of the parent. switch (n.parent.kind) { - case 235 /* DoStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 237 /* ForStatement */: - case 234 /* IfStatement */: - case 236 /* WhileStatement */: - case 243 /* WithStatement */: - case 287 /* CatchClause */: + case 236 /* DoStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 238 /* ForStatement */: + case 235 /* IfStatement */: + case 237 /* WhileStatement */: + case 244 /* WithStatement */: + case 288 /* CatchClause */: return spanForNode(n.parent); - case 247 /* TryStatement */: + case 248 /* TryStatement */: // Could be the try-block, or the finally-block. var tryStatement = n.parent; if (tryStatement.tryBlock === n) { @@ -127777,40 +132020,40 @@ var ts; // the span of the block, independent of any parent span. return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */); } - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return spanForNode(n.parent); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 258 /* CaseBlock */: - case 177 /* TypeLiteral */: - case 196 /* ObjectBindingPattern */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 259 /* CaseBlock */: + case 178 /* TypeLiteral */: + case 197 /* ObjectBindingPattern */: return spanForNode(n); - case 179 /* TupleType */: + case 180 /* TupleType */: return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !ts.isTupleTypeNode(n.parent), 22 /* OpenBracketToken */); - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: return spanForNodeArray(n.statements); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return spanForObjectOrArrayLiteral(n); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return spanForObjectOrArrayLiteral(n, 22 /* OpenBracketToken */); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return spanForJSXElement(n); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return spanForJSXFragment(n); - case 274 /* JsxSelfClosingElement */: - case 275 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: return spanForJSXAttributes(n.attributes); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: case 14 /* NoSubstitutionTemplateLiteral */: return spanForTemplateLiteral(n); - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !ts.isBindingElement(n.parent), 22 /* OpenBracketToken */); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return spanForArrowFunction(n); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return spanForCallExpression(n); } function spanForCallExpression(node) { @@ -127877,7 +132120,7 @@ var ts; function functionSpan(node, body, sourceFile) { var openToken = tryGetFunctionOpenToken(node, body, sourceFile); var closeToken = ts.findChildOfKind(body, 19 /* CloseBraceToken */, sourceFile); - return openToken && closeToken && spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ node.kind !== 209 /* ArrowFunction */); + return openToken && closeToken && spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ node.kind !== 210 /* ArrowFunction */); } function spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse, useFullStart) { if (autoCollapse === void 0) { autoCollapse = false; } @@ -128180,15 +132423,15 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_6 = function (start) { + var _loop_7 = 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_1 = _loop_6(start); - if (typeof state_1 === "object") - return state_1.value; + var state_2 = _loop_7(start); + if (typeof state_2 === "object") + return state_2.value; } return -1; } @@ -128740,7 +132983,7 @@ var ts; function getRenameInfo(program, sourceFile, position, options) { var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position)); if (nodeIsEligibleForRename(node)) { - var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }, options); + var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, options); if (renameInfo) { return renameInfo; } @@ -128748,7 +132991,7 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); } Rename.getRenameInfo = getRenameInfo; - function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile, options) { + function getRenameInfoForNode(node, typeChecker, sourceFile, program, options) { var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) { if (ts.isStringLiteralLike(node)) { @@ -128768,7 +133011,7 @@ var ts; if (!declarations || declarations.length === 0) return; // Disallow rename for elements that are defined in the standard TypeScript library. - if (declarations.some(isDefinedInLibraryFile)) { + if (declarations.some(function (declaration) { return isDefinedInLibraryFile(program, declaration); })) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } // Cannot rename `default` as in `import { default as foo } from "./someModule"; @@ -128779,18 +133022,22 @@ var ts; return options && options.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 158 /* ComputedPropertyName */) + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 159 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) : undefined; var displayName = specifierName || typeChecker.symbolToString(symbol); var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(typeChecker, symbol), node, sourceFile); } + function isDefinedInLibraryFile(program, declaration) { + var sourceFile = declaration.getSourceFile(); + return program.isSourceFileDefaultLibrary(sourceFile) && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */); + } function getRenameInfoForModule(node, sourceFile, moduleSymbol) { if (!ts.isExternalModuleNameRelative(node.text)) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); } - var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var moduleSourceFile = moduleSymbol.declarations && ts.find(moduleSymbol.declarations, ts.isSourceFile); if (!moduleSourceFile) return undefined; var withoutIndex = ts.endsWith(node.text, "/index") || ts.endsWith(node.text, "/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); @@ -128871,6 +133118,10 @@ var ts; if (ts.getTokenPosOfNode(node, sourceFile, /*includeJsDoc*/ true) > pos) { break outer; } + var comment = ts.singleOrUndefined(ts.getTrailingCommentRanges(sourceFile.text, node.end)); + if (comment && comment.kind === 2 /* SingleLineCommentTrivia */) { + pushSelectionCommentRange(comment.pos, comment.end); + } if (positionShouldSnapToNode(sourceFile, pos, node)) { // 1. Blocks are effectively redundant with SyntaxLists. // 2. TemplateSpans, along with the SyntaxLists containing them, are a somewhat unintuitive grouping @@ -128933,6 +133184,14 @@ var ts; } } } + function pushSelectionCommentRange(start, end) { + pushSelectionRange(start, end); + var pos = start; + while (sourceFile.text.charCodeAt(pos) === 47 /* slash */) { + pos++; + } + pushSelectionRange(pos, end); + } } SmartSelectionRange.getSmartSelectionRange = getSmartSelectionRange; /** @@ -128996,7 +133255,7 @@ var ts; var groupedWithBrackets = groupChildren(groupedWithPlusMinusTokens, function (_a) { var kind = _a.kind; return kind === 22 /* OpenBracketToken */ || - kind === 159 /* TypeParameter */ || + kind === 160 /* TypeParameter */ || kind === 23 /* CloseBracketToken */; }); return [ @@ -129110,22 +133369,22 @@ var ts; return kind === 18 /* OpenBraceToken */ || kind === 22 /* OpenBracketToken */ || kind === 20 /* OpenParenToken */ - || kind === 275 /* JsxOpeningElement */; + || kind === 276 /* JsxOpeningElement */; } function isListCloser(token) { var kind = token && token.kind; return kind === 19 /* CloseBraceToken */ || kind === 23 /* CloseBracketToken */ || kind === 21 /* CloseParenToken */ - || kind === 276 /* JsxClosingElement */; + || kind === 277 /* JsxClosingElement */; } function getEndPos(sourceFile, node) { switch (node.kind) { - case 326 /* JSDocParameterTag */: - case 324 /* JSDocCallbackTag */: - case 333 /* JSDocPropertyTag */: - case 331 /* JSDocTypedefTag */: - case 328 /* JSDocThisTag */: + case 330 /* JSDocParameterTag */: + case 328 /* JSDocCallbackTag */: + case 337 /* JSDocPropertyTag */: + case 335 /* JSDocTypedefTag */: + case 332 /* JSDocThisTag */: return sourceFile.getLineEndOfPosition(node.getStart()); default: return node.getEnd(); @@ -129335,10 +133594,10 @@ var ts; } return undefined; } - else if (ts.isTemplateHead(node) && parent.parent.kind === 205 /* TaggedTemplateExpression */) { + else if (ts.isTemplateHead(node) && parent.parent.kind === 206 /* TaggedTemplateExpression */) { var templateExpression = parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 218 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 219 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } @@ -129407,17 +133666,17 @@ var ts; return undefined; var parent = startingToken.parent; switch (parent.kind) { - case 207 /* ParenthesizedExpression */: - case 165 /* MethodDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 208 /* ParenthesizedExpression */: + case 166 /* MethodDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: var info = getArgumentOrParameterListInfo(startingToken, sourceFile); if (!info) return undefined; var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; var contextualType = ts.isMethodDeclaration(parent) ? checker.getContextualTypeForObjectLiteralElement(parent) : checker.getContextualType(parent); return contextualType && { contextualType: contextualType, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; - case 216 /* BinaryExpression */: { + case 217 /* BinaryExpression */: { var highestBinary = getHighestBinary(parent); var contextualType_1 = checker.getContextualType(highestBinary); var argumentIndex_1 = startingToken.kind === 20 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1; @@ -129541,7 +133800,7 @@ var ts; // | | // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. - if (template.kind === 218 /* TemplateExpression */) { + if (template.kind === 219 /* TemplateExpression */) { var lastSpan = ts.last(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -129550,7 +133809,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { - var _loop_7 = function (n) { + var _loop_8 = 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.formatSyntaxKind(n.kind) + ", parent: " + ts.Debug.formatSyntaxKind(n.parent.kind); }); @@ -129560,9 +133819,9 @@ var ts; } }; for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) { - var state_2 = _loop_7(n); - if (typeof state_2 === "object") - return state_2.value; + var state_3 = _loop_8(n); + if (typeof state_3 === "object") + return state_3.value; } return undefined; } @@ -129612,7 +133871,19 @@ var ts; itemsSeen += item.length; } 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: ts.flatMapToMutable(items, ts.identity), applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var help = { items: ts.flatMapToMutable(items, ts.identity), applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var selected = help.items[selectedItemIndex]; + if (selected.isVariadic) { + var firstRest = ts.findIndex(selected.parameters, function (p) { return !!p.isRest; }); + if (-1 < firstRest && firstRest < selected.parameters.length - 1) { + // We don't have any code to get this correct; instead, don't highlight a current parameter AT ALL + help.argumentIndex = selected.parameters.length; + } + else { + help.argumentIndex = Math.min(help.argumentIndex, selected.parameters.length - 1); + } + } + return help; } function createTypeHelpItems(symbol, _a, sourceFile, checker) { var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; @@ -129627,7 +133898,7 @@ var ts; 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 tags = symbol.getJsDocTags(checker); var prefixDisplayParts = __spreadArray(__spreadArray([], typeSymbolDisplay), [ts.punctuationPart(29 /* LessThanToken */)]); return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(31 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; } @@ -129694,14 +133965,15 @@ var ts; printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); var isOptional = checker.isOptionalParameter(parameter.valueDeclaration); - return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional }; + var isRest = !!(parameter.checkFlags & 32768 /* RestParameter */); + return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional, isRest: isRest }; } function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { var displayParts = ts.mapToDisplayParts(function (writer) { var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false, isRest: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -129911,7 +134183,7 @@ var ts; diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); } } - if (ts.isFunctionLikeDeclaration(node)) { + if (canBeConvertedToAsync(node)) { addConvertToAsyncFunctionDiagnostics(node, checker, diags); } node.forEachChild(check); @@ -129922,11 +134194,11 @@ var ts; function containsTopLevelCommonjs(sourceFile) { return sourceFile.statements.some(function (statement) { switch (statement.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); }); - case 233 /* ExpressionStatement */: { + case 234 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); @@ -129943,12 +134215,12 @@ var ts; } function importNameForConvertToDefaultImport(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; - return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 263 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 264 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : undefined; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return node.name; default: return undefined; @@ -129964,35 +134236,35 @@ var ts; return !ts.isAsyncFunction(node) && node.body && ts.isBlock(node.body) && - hasReturnStatementWithPromiseHandler(node.body) && + hasReturnStatementWithPromiseHandler(node.body, checker) && returnsPromise(node, checker); } function returnsPromise(node, checker) { - var functionType = checker.getTypeAtLocation(node); - var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); - var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; + var signature = checker.getSignatureFromDeclaration(node); + var returnType = signature ? checker.getReturnTypeOfSignature(signature) : undefined; return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); } + ts.returnsPromise = returnsPromise; function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } - function hasReturnStatementWithPromiseHandler(body) { - return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); + function hasReturnStatementWithPromiseHandler(body, checker) { + return !!ts.forEachReturnStatement(body, function (statement) { return isReturnStatementWithFixablePromiseHandler(statement, checker); }); } - function isReturnStatementWithFixablePromiseHandler(node) { - return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); + function isReturnStatementWithFixablePromiseHandler(node, checker) { + return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression, checker); } ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler; // Should be kept up to date with transformExpression in convertToAsyncFunction.ts - function isFixablePromiseHandler(node) { + function isFixablePromiseHandler(node, checker) { // ensure outermost call exists and is a promise handler - if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + if (!isPromiseHandler(node) || !node.arguments.every(function (arg) { return isFixablePromiseArgument(arg, checker); })) { 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)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(function (arg) { return isFixablePromiseArgument(arg, checker); })) { return false; } currentNode = currentNode.expression; @@ -130015,16 +134287,24 @@ var ts; }); } // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts - function isFixablePromiseArgument(arg) { + function isFixablePromiseArgument(arg, checker) { switch (arg.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true); // falls through case 103 /* NullKeyword */: - case 78 /* Identifier */: // identifier includes undefined return true; + case 78 /* Identifier */: + case 202 /* PropertyAccessExpression */: { + var symbol = checker.getSymbolAtLocation(arg); + if (!symbol) { + return false; + } + return checker.isUndefinedSymbol(symbol) || + ts.some(ts.skipAlias(symbol, checker).declarations, function (d) { return ts.isFunctionLike(d) || ts.hasInitializer(d) && !!d.initializer && ts.isFunctionLike(d.initializer); }); + } default: return false; } @@ -130034,18 +134314,30 @@ var ts; } function canBeConvertedToClass(node, checker) { var _a, _b, _c, _d; - if (node.kind === 208 /* FunctionExpression */) { + if (node.kind === 209 /* FunctionExpression */) { if (ts.isVariableDeclaration(node.parent) && ((_a = node.symbol.members) === null || _a === void 0 ? void 0 : _a.size)) { return true; } var symbol = checker.getSymbolOfExpando(node, /*allowDeclaration*/ false); return !!(symbol && (((_b = symbol.exports) === null || _b === void 0 ? void 0 : _b.size) || ((_c = symbol.members) === null || _c === void 0 ? void 0 : _c.size))); } - if (node.kind === 251 /* FunctionDeclaration */) { + if (node.kind === 252 /* FunctionDeclaration */) { return !!((_d = node.symbol.members) === null || _d === void 0 ? void 0 : _d.size); } return false; } + function canBeConvertedToAsync(node) { + switch (node.kind) { + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + return true; + default: + return false; + } + } + ts.canBeConvertedToAsync = canBeConvertedToAsync; })(ts || (ts = {})); /* @internal */ var ts; @@ -130061,7 +134353,7 @@ var ts; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32 /* Class */) { - return ts.getDeclarationOfKind(symbol, 221 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 222 /* ClassExpression */) ? "local class" /* localClassElement */ : "class" /* classElement */; } if (flags & 384 /* Enum */) @@ -130145,11 +134437,11 @@ var ts; // If we requested completions after `x.` at the top-level, we may be at a source file location. switch (location.parent && location.parent.kind) { // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. - case 275 /* JsxOpeningElement */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: return location.kind === 78 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return "JSX attribute" /* jsxAttribute */; default: return "property" /* memberVariableElement */; @@ -130195,6 +134487,7 @@ var ts; SymbolDisplay.getSymbolModifiers = getSymbolModifiers; // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) { + var _a; if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } var displayParts = []; var documentation = []; @@ -130218,8 +134511,8 @@ var ts; symbolKind = "property" /* memberVariableElement */; } var signature = void 0; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (location.parent && location.parent.kind === 201 /* PropertyAccessExpression */) { + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (location.parent && location.parent.kind === 202 /* PropertyAccessExpression */) { var right = location.parent.name; // Either the location is on the right of a property access, or on the left and the right is missing if (right === location || (right && right.getFullWidth() === 0)) { @@ -130239,9 +134532,9 @@ var ts; } if (callExpressionLike) { signature = typeChecker.getResolvedSignature(callExpressionLike); // TODO: GH#18217 - var useConstructSignatures = callExpressionLike.kind === 204 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 105 /* SuperKeyword */); + var useConstructSignatures = callExpressionLike.kind === 205 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 105 /* SuperKeyword */); var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); - if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { + if (signature && !ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { // Get the first signature if there is one -- allSignatures may contain // either the original signature or its target, so check for either signature = allSignatures.length ? allSignatures[0] : undefined; @@ -130303,7 +134596,7 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration - (location.kind === 132 /* ConstructorKeyword */ && location.parent.kind === 166 /* Constructor */)) { // At constructor keyword of constructor declaration + (location.kind === 132 /* ConstructorKeyword */ && location.parent.kind === 167 /* Constructor */)) { // At constructor keyword of constructor declaration // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; // Use function declaration to write the signatures only if the symbol corresponding to this declaration @@ -130311,24 +134604,26 @@ var ts; return declaration === (location.kind === 132 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { - var allSignatures = functionDeclaration_1.kind === 166 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration_1.kind === 167 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217 } else { signature = allSignatures[0]; } - if (functionDeclaration_1.kind === 166 /* Constructor */) { + if (functionDeclaration_1.kind === 167 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 169 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 170 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } - addSignatureDisplayParts(signature, allSignatures); + if (signature) { + addSignatureDisplayParts(signature, allSignatures); + } hasAddedSymbolInfo = true; hasMultipleSignatures = allSignatures.length > 1; } @@ -130336,7 +134631,7 @@ var ts; } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { addAliasPrefixIfNecessary(); - if (ts.getDeclarationOfKind(symbol, 221 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 222 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) // (local class) class @@ -130380,7 +134675,7 @@ var ts; } if (symbolFlags & 1536 /* Module */ && !isThisExpression) { prefixNextMeaning(); - var declaration = ts.getDeclarationOfKind(symbol, 256 /* ModuleDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 257 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 78 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 140 /* NamespaceKeyword */ : 139 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); @@ -130401,7 +134696,7 @@ var ts; } else { // Method/function type parameter - var decl = ts.getDeclarationOfKind(symbol, 159 /* TypeParameter */); + var decl = ts.getDeclarationOfKind(symbol, 160 /* TypeParameter */); if (decl === undefined) return ts.Debug.fail(); var declaration = decl.parent; @@ -130409,16 +134704,16 @@ var ts; if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217 - if (declaration.kind === 170 /* ConstructSignature */) { + if (declaration.kind === 171 /* ConstructSignature */) { displayParts.push(ts.keywordPart(102 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 169 /* CallSignature */ && declaration.name) { + else if (declaration.kind !== 170 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } - else if (declaration.kind === 254 /* TypeAliasDeclaration */) { + else if (declaration.kind === 255 /* TypeAliasDeclaration */) { // Type alias type parameter // For example // type list = T[]; // Both T will go through same code path @@ -130434,8 +134729,8 @@ var ts; if (symbolFlags & 8 /* EnumMember */) { symbolKind = "enum member" /* enumMemberElement */; addPrefixForAnyFunctionOrVar(symbol, "enum member"); - var declaration = symbol.declarations[0]; - if (declaration.kind === 291 /* EnumMember */) { + var declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]; + if ((declaration === null || declaration === void 0 ? void 0 : declaration.kind) === 292 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -130465,31 +134760,33 @@ var ts; } else { documentationFromAlias = resolvedSymbol.getContextualDocumentationComment(resolvedNode, typeChecker); - tagsFromAlias = resolvedSymbol.getJsDocTags(); + tagsFromAlias = resolvedSymbol.getJsDocTags(typeChecker); } } } - switch (symbol.declarations[0].kind) { - case 259 /* NamespaceExportDeclaration */: - displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(140 /* NamespaceKeyword */)); - break; - case 266 /* ExportAssignment */: - displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 62 /* EqualsToken */ : 87 /* DefaultKeyword */)); - break; - case 270 /* ExportSpecifier */: - displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); - break; - default: - displayParts.push(ts.keywordPart(99 /* ImportKeyword */)); + if (symbol.declarations) { + switch (symbol.declarations[0].kind) { + case 260 /* NamespaceExportDeclaration */: + displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(140 /* NamespaceKeyword */)); + break; + case 267 /* ExportAssignment */: + displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 62 /* EqualsToken */ : 87 /* DefaultKeyword */)); + break; + case 271 /* ExportSpecifier */: + displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); + break; + default: + displayParts.push(ts.keywordPart(99 /* ImportKeyword */)); + } } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 260 /* ImportEqualsDeclaration */) { + if (declaration.kind === 261 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); @@ -130576,10 +134873,10 @@ var ts; // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 297 /* SourceFile */; })) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 216 /* BinaryExpression */) { + if (symbol.parent && symbol.declarations && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 298 /* SourceFile */; })) { + for (var _i = 0, _b = symbol.declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (!declaration.parent || declaration.parent.kind !== 217 /* BinaryExpression */) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); @@ -130587,7 +134884,7 @@ var ts; continue; } documentation = rhsSymbol.getDocumentationComment(typeChecker); - tags = rhsSymbol.getJsDocTags(); + tags = rhsSymbol.getJsDocTags(typeChecker); if (documentation.length > 0) { break; } @@ -130595,7 +134892,7 @@ var ts; } } if (tags.length === 0 && !hasMultipleSignatures) { - tags = symbol.getJsDocTags(); + tags = symbol.getJsDocTags(typeChecker); } if (documentation.length === 0 && documentationFromAlias) { documentation = documentationFromAlias; @@ -130697,16 +134994,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 208 /* FunctionExpression */) { + if (declaration.kind === 209 /* FunctionExpression */) { return true; } - if (declaration.kind !== 249 /* VariableDeclaration */ && declaration.kind !== 251 /* FunctionDeclaration */) { + if (declaration.kind !== 250 /* VariableDeclaration */ && declaration.kind !== 252 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { // Reached source file or module block - if (parent.kind === 297 /* SourceFile */ || parent.kind === 257 /* ModuleBlock */) { + if (parent.kind === 298 /* SourceFile */ || parent.kind === 258 /* ModuleBlock */) { return false; } } @@ -130812,7 +135109,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_8 = function (opt) { + var _loop_9 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -130831,7 +135128,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_8(opt); + _loop_9(opt); } return options; } @@ -131007,10 +135304,10 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 280 /* JsxAttribute */: - case 275 /* JsxOpeningElement */: - case 276 /* JsxClosingElement */: - case 274 /* JsxSelfClosingElement */: + case 281 /* JsxAttribute */: + case 276 /* JsxOpeningElement */: + case 277 /* JsxClosingElement */: + case 275 /* JsxSelfClosingElement */: // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. return ts.isKeyword(node.kind) || node.kind === 78 /* Identifier */; } @@ -131018,14 +135315,7 @@ var ts; return false; } function shouldRescanJsxText(node) { - var isJSXText = ts.isJsxText(node); - if (isJSXText) { - var containingElement = ts.findAncestor(node.parent, function (p) { return ts.isJsxElement(p); }); - if (!containingElement) - return false; // should never happen - return !ts.isParenthesizedExpression(containingElement.parent); - } - return false; + return ts.isJsxText(node); } function shouldRescanSlashToken(container) { return container.kind === 13 /* RegularExpressionLiteral */; @@ -131122,7 +135412,7 @@ var ts; return scanner.scanJsxIdentifier(); case 5 /* RescanJsxText */: lastScanAction = 5 /* RescanJsxText */; - return scanner.reScanJsxToken(); + return scanner.reScanJsxToken(/* allowMultilineJsxText */ false); case 6 /* RescanJsxAttributeValue */: lastScanAction = 6 /* RescanJsxAttributeValue */; return scanner.reScanJsxAttributeValue(); @@ -131211,7 +135501,7 @@ var ts; (function (formatting) { function getAllRules() { var allTokens = []; - for (var token = 0 /* FirstToken */; token <= 156 /* LastToken */; token++) { + for (var token = 0 /* FirstToken */; token <= 157 /* LastToken */; token++) { if (token !== 1 /* EndOfFileToken */) { allTokens.push(token); } @@ -131226,9 +135516,9 @@ var ts; var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(__spreadArray(__spreadArray([], allTokens), [3 /* MultiLineCommentTrivia */])); var anyTokenIncludingEOF = tokenRangeFrom(__spreadArray(__spreadArray([], allTokens), [1 /* EndOfFileToken */])); - var keywords = tokenRangeFromRange(80 /* FirstKeyword */, 156 /* LastKeyword */); + var keywords = tokenRangeFromRange(80 /* FirstKeyword */, 157 /* LastKeyword */); var binaryOperators = tokenRangeFromRange(29 /* FirstBinaryOperator */, 77 /* LastBinaryOperator */); - var binaryKeywordOperators = [100 /* InKeyword */, 101 /* InstanceOfKeyword */, 156 /* OfKeyword */, 126 /* AsKeyword */, 137 /* IsKeyword */]; + var binaryKeywordOperators = [100 /* InKeyword */, 101 /* InstanceOfKeyword */, 157 /* OfKeyword */, 126 /* AsKeyword */, 137 /* IsKeyword */]; var unaryPrefixOperators = [45 /* PlusPlusToken */, 46 /* MinusMinusToken */, 54 /* TildeToken */, 53 /* ExclamationToken */]; var unaryPrefixExpressions = [ 8 /* NumericLiteral */, 9 /* BigIntLiteral */, 78 /* Identifier */, 20 /* OpenParenToken */, @@ -131539,51 +135829,51 @@ var ts; return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; } function isForContext(context) { - return context.contextNode.kind === 237 /* ForStatement */; + return context.contextNode.kind === 238 /* ForStatement */; } function isNotForContext(context) { return !isForContext(context); } function isBinaryOpContext(context) { switch (context.contextNode.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return context.contextNode.operatorToken.kind !== 27 /* CommaToken */; - case 217 /* ConditionalExpression */: - case 184 /* ConditionalType */: - case 224 /* AsExpression */: - case 270 /* ExportSpecifier */: - case 265 /* ImportSpecifier */: - case 172 /* TypePredicate */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 218 /* ConditionalExpression */: + case 185 /* ConditionalType */: + case 225 /* AsExpression */: + case 271 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 173 /* TypePredicate */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 198 /* BindingElement */: + case 199 /* BindingElement */: // equals in type X = ... // falls through - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: // equal in import a = module('a'); // falls through - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // equal in let a = 0 // falls through - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: // equal in p = 0 // falls through - case 160 /* Parameter */: - case 291 /* EnumMember */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 161 /* Parameter */: + case 292 /* EnumMember */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return context.currentTokenSpan.kind === 62 /* EqualsToken */ || context.nextTokenSpan.kind === 62 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: // "in" keyword in [P in keyof T]: T[P] // falls through - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return context.currentTokenSpan.kind === 100 /* InKeyword */ || context.nextTokenSpan.kind === 100 /* InKeyword */ || context.currentTokenSpan.kind === 62 /* EqualsToken */ || context.nextTokenSpan.kind === 62 /* EqualsToken */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 239 /* ForOfStatement */: - return context.currentTokenSpan.kind === 156 /* OfKeyword */ || context.nextTokenSpan.kind === 156 /* OfKeyword */; + case 240 /* ForOfStatement */: + return context.currentTokenSpan.kind === 157 /* OfKeyword */ || context.nextTokenSpan.kind === 157 /* OfKeyword */; } return false; } @@ -131595,22 +135885,22 @@ var ts; } function isTypeAnnotationContext(context) { var contextKind = context.contextNode.kind; - return contextKind === 163 /* PropertyDeclaration */ || - contextKind === 162 /* PropertySignature */ || - contextKind === 160 /* Parameter */ || - contextKind === 249 /* VariableDeclaration */ || + return contextKind === 164 /* PropertyDeclaration */ || + contextKind === 163 /* PropertySignature */ || + contextKind === 161 /* Parameter */ || + contextKind === 250 /* VariableDeclaration */ || ts.isFunctionLikeKind(contextKind); } function isConditionalOperatorContext(context) { - return context.contextNode.kind === 217 /* ConditionalExpression */ || - context.contextNode.kind === 184 /* ConditionalType */; + return context.contextNode.kind === 218 /* ConditionalExpression */ || + context.contextNode.kind === 185 /* ConditionalType */; } function isSameLineTokenOrBeforeBlockContext(context) { return context.TokensAreOnSameLine() || isBeforeBlockContext(context); } function isBraceWrappedContext(context) { - return context.contextNode.kind === 196 /* ObjectBindingPattern */ || - context.contextNode.kind === 190 /* MappedType */ || + return context.contextNode.kind === 197 /* ObjectBindingPattern */ || + context.contextNode.kind === 191 /* MappedType */ || isSingleLineBlockContext(context); } // This check is done before an open brace in a control construct, a function, or a typescript block declaration @@ -131636,34 +135926,34 @@ var ts; return true; } switch (node.kind) { - case 230 /* Block */: - case 258 /* CaseBlock */: - case 200 /* ObjectLiteralExpression */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 259 /* CaseBlock */: + case 201 /* ObjectLiteralExpression */: + case 258 /* ModuleBlock */: return true; } return false; } function isFunctionDeclContext(context) { switch (context.contextNode.kind) { - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: // case SyntaxKind.MemberFunctionDeclaration: // falls through - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // case SyntaxKind.MethodSignature: // falls through - case 169 /* CallSignature */: - case 208 /* FunctionExpression */: - case 166 /* Constructor */: - case 209 /* ArrowFunction */: + case 170 /* CallSignature */: + case 209 /* FunctionExpression */: + case 167 /* Constructor */: + case 210 /* ArrowFunction */: // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: // falls through - case 253 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one + case 254 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one return true; } return false; @@ -131672,40 +135962,40 @@ var ts; return !isFunctionDeclContext(context); } function isFunctionDeclarationOrFunctionExpressionContext(context) { - return context.contextNode.kind === 251 /* FunctionDeclaration */ || context.contextNode.kind === 208 /* FunctionExpression */; + return context.contextNode.kind === 252 /* FunctionDeclaration */ || context.contextNode.kind === 209 /* FunctionExpression */; } function isTypeScriptDeclWithBlockContext(context) { return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); } function nodeIsTypeScriptDeclWithBlockContext(node) { switch (node.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 177 /* TypeLiteral */: - case 256 /* ModuleDeclaration */: - case 267 /* ExportDeclaration */: - case 268 /* NamedExports */: - case 261 /* ImportDeclaration */: - case 264 /* NamedImports */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 178 /* TypeLiteral */: + case 257 /* ModuleDeclaration */: + case 268 /* ExportDeclaration */: + case 269 /* NamedExports */: + case 262 /* ImportDeclaration */: + case 265 /* NamedImports */: return true; } return false; } function isAfterCodeBlockContext(context) { switch (context.currentTokenParent.kind) { - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 287 /* CatchClause */: - case 257 /* ModuleBlock */: - case 244 /* SwitchStatement */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 288 /* CatchClause */: + case 258 /* ModuleBlock */: + case 245 /* SwitchStatement */: return true; - case 230 /* Block */: { + case 231 /* Block */: { var blockParent = context.currentTokenParent.parent; // In a codefix scenario, we can't rely on parents being set. So just always return true. - if (!blockParent || blockParent.kind !== 209 /* ArrowFunction */ && blockParent.kind !== 208 /* FunctionExpression */) { + if (!blockParent || blockParent.kind !== 210 /* ArrowFunction */ && blockParent.kind !== 209 /* FunctionExpression */) { return true; } } @@ -131714,32 +136004,32 @@ var ts; } function isControlDeclContext(context) { switch (context.contextNode.kind) { - case 234 /* IfStatement */: - case 244 /* SwitchStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 236 /* WhileStatement */: - case 247 /* TryStatement */: - case 235 /* DoStatement */: - case 243 /* WithStatement */: + case 235 /* IfStatement */: + case 245 /* SwitchStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 237 /* WhileStatement */: + case 248 /* TryStatement */: + case 236 /* DoStatement */: + case 244 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: // falls through - case 287 /* CatchClause */: + case 288 /* CatchClause */: return true; default: return false; } } function isObjectContext(context) { - return context.contextNode.kind === 200 /* ObjectLiteralExpression */; + return context.contextNode.kind === 201 /* ObjectLiteralExpression */; } function isFunctionCallContext(context) { - return context.contextNode.kind === 203 /* CallExpression */; + return context.contextNode.kind === 204 /* CallExpression */; } function isNewContext(context) { - return context.contextNode.kind === 204 /* NewExpression */; + return context.contextNode.kind === 205 /* NewExpression */; } function isFunctionCallOrNewContext(context) { return isFunctionCallContext(context) || isNewContext(context); @@ -131754,10 +136044,10 @@ var ts; return context.nextTokenSpan.kind !== 21 /* CloseParenToken */; } function isArrowFunctionContext(context) { - return context.contextNode.kind === 209 /* ArrowFunction */; + return context.contextNode.kind === 210 /* ArrowFunction */; } function isImportTypeContext(context) { - return context.contextNode.kind === 195 /* ImportType */; + return context.contextNode.kind === 196 /* ImportType */; } function isNonJsxSameLineTokenContext(context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 11 /* JsxText */; @@ -131766,19 +136056,19 @@ var ts; return context.contextNode.kind !== 11 /* JsxText */; } function isNonJsxElementOrFragmentContext(context) { - return context.contextNode.kind !== 273 /* JsxElement */ && context.contextNode.kind !== 277 /* JsxFragment */; + return context.contextNode.kind !== 274 /* JsxElement */ && context.contextNode.kind !== 278 /* JsxFragment */; } function isJsxExpressionContext(context) { - return context.contextNode.kind === 283 /* JsxExpression */ || context.contextNode.kind === 282 /* JsxSpreadAttribute */; + return context.contextNode.kind === 284 /* JsxExpression */ || context.contextNode.kind === 283 /* JsxSpreadAttribute */; } function isNextTokenParentJsxAttribute(context) { - return context.nextTokenParent.kind === 280 /* JsxAttribute */; + return context.nextTokenParent.kind === 281 /* JsxAttribute */; } function isJsxAttributeContext(context) { - return context.contextNode.kind === 280 /* JsxAttribute */; + return context.contextNode.kind === 281 /* JsxAttribute */; } function isJsxSelfClosingElementContext(context) { - return context.contextNode.kind === 274 /* JsxSelfClosingElement */; + return context.contextNode.kind === 275 /* JsxSelfClosingElement */; } function isNotBeforeBlockInFunctionDeclarationContext(context) { return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); @@ -131793,45 +136083,45 @@ var ts; while (ts.isExpressionNode(node)) { node = node.parent; } - return node.kind === 161 /* Decorator */; + return node.kind === 162 /* Decorator */; } function isStartOfVariableDeclarationList(context) { - return context.currentTokenParent.kind === 250 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 251 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; } function isNotFormatOnEnter(context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */; } function isModuleDeclContext(context) { - return context.contextNode.kind === 256 /* ModuleDeclaration */; + return context.contextNode.kind === 257 /* ModuleDeclaration */; } function isObjectTypeContext(context) { - return context.contextNode.kind === 177 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === 178 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; } function isConstructorSignatureContext(context) { - return context.contextNode.kind === 170 /* ConstructSignature */; + return context.contextNode.kind === 171 /* ConstructSignature */; } function isTypeArgumentOrParameterOrAssertion(token, parent) { if (token.kind !== 29 /* LessThanToken */ && token.kind !== 31 /* GreaterThanToken */) { return false; } switch (parent.kind) { - case 173 /* TypeReference */: - case 206 /* TypeAssertionExpression */: - case 254 /* TypeAliasDeclaration */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 223 /* ExpressionWithTypeArguments */: + case 174 /* TypeReference */: + case 207 /* TypeAssertionExpression */: + case 255 /* TypeAliasDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 224 /* ExpressionWithTypeArguments */: return true; default: return false; @@ -131842,28 +136132,28 @@ var ts; isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); } function isTypeAssertionContext(context) { - return context.contextNode.kind === 206 /* TypeAssertionExpression */; + return context.contextNode.kind === 207 /* TypeAssertionExpression */; } function isVoidOpContext(context) { - return context.currentTokenSpan.kind === 113 /* VoidKeyword */ && context.currentTokenParent.kind === 212 /* VoidExpression */; + return context.currentTokenSpan.kind === 113 /* VoidKeyword */ && context.currentTokenParent.kind === 213 /* VoidExpression */; } function isYieldOrYieldStarWithOperand(context) { - return context.contextNode.kind === 219 /* YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 220 /* YieldExpression */ && context.contextNode.expression !== undefined; } function isNonNullAssertionContext(context) { - return context.contextNode.kind === 225 /* NonNullExpression */; + return context.contextNode.kind === 226 /* NonNullExpression */; } function isNotStatementConditionContext(context) { return !isStatementConditionContext(context); } function isStatementConditionContext(context) { switch (context.contextNode.kind) { - case 234 /* IfStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 235 /* IfStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return true; default: return false; @@ -131888,12 +136178,12 @@ var ts; return nextTokenKind === 19 /* CloseBraceToken */ || nextTokenKind === 1 /* EndOfFileToken */; } - if (nextTokenKind === 229 /* SemicolonClassElement */ || + if (nextTokenKind === 230 /* SemicolonClassElement */ || nextTokenKind === 26 /* SemicolonToken */) { return false; } - if (context.contextNode.kind === 253 /* InterfaceDeclaration */ || - context.contextNode.kind === 254 /* TypeAliasDeclaration */) { + if (context.contextNode.kind === 254 /* InterfaceDeclaration */ || + context.contextNode.kind === 255 /* TypeAliasDeclaration */) { // Can’t remove semicolon after `foo`; it would parse as a method declaration: // // interface I { @@ -131907,9 +136197,9 @@ var ts; if (ts.isPropertyDeclaration(context.currentTokenParent)) { return !context.currentTokenParent.initializer; } - return context.currentTokenParent.kind !== 237 /* ForStatement */ - && context.currentTokenParent.kind !== 231 /* EmptyStatement */ - && context.currentTokenParent.kind !== 229 /* SemicolonClassElement */ + return context.currentTokenParent.kind !== 238 /* ForStatement */ + && context.currentTokenParent.kind !== 232 /* EmptyStatement */ + && context.currentTokenParent.kind !== 230 /* SemicolonClassElement */ && nextTokenKind !== 22 /* OpenBracketToken */ && nextTokenKind !== 20 /* OpenParenToken */ && nextTokenKind !== 39 /* PlusToken */ @@ -131917,7 +136207,7 @@ var ts; && nextTokenKind !== 43 /* SlashToken */ && nextTokenKind !== 13 /* RegularExpressionLiteral */ && nextTokenKind !== 27 /* CommaToken */ - && nextTokenKind !== 218 /* TemplateExpression */ + && nextTokenKind !== 219 /* TemplateExpression */ && nextTokenKind !== 15 /* TemplateHead */ && nextTokenKind !== 14 /* NoSubstitutionTemplateLiteral */ && nextTokenKind !== 24 /* DotToken */; @@ -132008,12 +136298,12 @@ var ts; return map; } function getRuleBucketIndex(row, column) { - ts.Debug.assert(row <= 156 /* LastKeyword */ && column <= 156 /* LastKeyword */, "Must compute formatting context from tokens"); + ts.Debug.assert(row <= 157 /* LastKeyword */ && column <= 157 /* LastKeyword */, "Must compute formatting context from tokens"); return (row * mapRowLength) + column; } var maskBitSize = 5; var mask = 31; // MaskBitSize bits - var mapRowLength = 156 /* LastToken */ + 1; + var mapRowLength = 157 /* LastToken */ + 1; var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["StopRulesSpecific"] = 0] = "StopRulesSpecific"; @@ -132201,17 +136491,17 @@ var ts; // i.e. parent is class declaration with the list of members and node is one of members. function isListElement(parent, node) { switch (parent.kind) { - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var body = parent.body; - return !!body && body.kind === 257 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); - case 297 /* SourceFile */: - case 230 /* Block */: - case 257 /* ModuleBlock */: + return !!body && body.kind === 258 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 298 /* SourceFile */: + case 231 /* Block */: + case 258 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -132365,14 +136655,17 @@ var ts; processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); } if (!formattingScanner.isOnToken()) { + var indentation = formatting.SmartIndenter.nodeWillIndentChild(options, enclosingNode, /*child*/ undefined, sourceFile, /*indentByDefault*/ false) + ? initialIndentation + options.indentSize + : initialIndentation; var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); - if (options.trimTrailingWhitespace !== false) { - trimTrailingWhitespacesForRemainingRange(); - } + indentTriviaItems(leadingTrivia, indentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); } } + if (options.trimTrailingWhitespace !== false) { + trimTrailingWhitespacesForRemainingRange(); + } return edits; // local functions /** Tries to compute the indentation for a list element. @@ -132419,10 +136712,9 @@ var ts; // - we need to get the indentation on last line and the delta of parent return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; } - else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; - } - else if (formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) { + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile) || + formatting.SmartIndenter.childIsUnindentedBranchOfConditionalExpression(parent, node, startLine, sourceFile) || + formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) { return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; } else { @@ -132438,19 +136730,19 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 252 /* ClassDeclaration */: return 83 /* ClassKeyword */; - case 253 /* InterfaceDeclaration */: return 117 /* InterfaceKeyword */; - case 251 /* FunctionDeclaration */: return 97 /* FunctionKeyword */; - case 255 /* EnumDeclaration */: return 255 /* EnumDeclaration */; - case 167 /* GetAccessor */: return 134 /* GetKeyword */; - case 168 /* SetAccessor */: return 146 /* SetKeyword */; - case 165 /* MethodDeclaration */: + case 253 /* ClassDeclaration */: return 83 /* ClassKeyword */; + case 254 /* InterfaceDeclaration */: return 117 /* InterfaceKeyword */; + case 252 /* FunctionDeclaration */: return 97 /* FunctionKeyword */; + case 256 /* EnumDeclaration */: return 256 /* EnumDeclaration */; + case 168 /* GetAccessor */: return 134 /* GetKeyword */; + case 169 /* SetAccessor */: return 146 /* SetKeyword */; + case 166 /* MethodDeclaration */: if (node.asteriskToken) { return 41 /* AsteriskToken */; } // falls through - case 163 /* PropertyDeclaration */: - case 160 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 161 /* Parameter */: var name = ts.getNameOfDeclaration(node); if (name) { return name.kind; @@ -132507,15 +136799,16 @@ var ts; case 43 /* SlashToken */: case 31 /* GreaterThanToken */: switch (container.kind) { - case 275 /* JsxOpeningElement */: - case 276 /* JsxClosingElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 277 /* JsxClosingElement */: + case 275 /* JsxSelfClosingElement */: + case 224 /* ExpressionWithTypeArguments */: return false; } break; case 22 /* OpenBracketToken */: case 23 /* CloseBracketToken */: - if (container.kind !== 190 /* MappedType */) { + if (container.kind !== 191 /* MappedType */) { return false; } break; @@ -132560,11 +136853,6 @@ var ts; if (tokenInfo.token.end > node.end) { break; } - if (node.kind === 11 /* JsxText */) { - // Intentation rules for jsx text are handled by `indentMultilineCommentOrJsxText` inside `processChildNode`; just fastforward past it here - formattingScanner.advance(); - continue; - } consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node); } if (!node.parent && formattingScanner.isOnEOF()) { @@ -132623,27 +136911,11 @@ var ts; return inheritedIndentation; } } - var effectiveParentStartLine = child.kind === 161 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 162 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); - if (child.kind === 11 /* JsxText */) { - var range = { pos: child.getStart(), end: child.getEnd() }; - if (range.pos !== range.end) { // don't indent zero-width jsx text - var siblings = parent.getChildren(sourceFile); - var currentIndex = ts.findIndex(siblings, function (arg) { return arg.pos === child.pos; }); - var previousNode = siblings[currentIndex - 1]; - if (previousNode) { - // The jsx text needs no indentation whatsoever if it ends on the same line the previous sibling ends on - if (sourceFile.getLineAndCharacterOfPosition(range.end).line !== sourceFile.getLineAndCharacterOfPosition(previousNode.end).line) { - // The first line is (already) "indented" if the text starts on the same line as the previous sibling element ends on - var firstLineIsIndented = sourceFile.getLineAndCharacterOfPosition(range.pos).line === sourceFile.getLineAndCharacterOfPosition(previousNode.end).line; - indentMultilineCommentOrJsxText(range, childIndentation.indentation, firstLineIsIndented, /*indentFinalLine*/ false, /*jsxStyle*/ true); - } - } - } - } childContextNode = node; - if (isFirstListItem && parent.kind === 199 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + if (isFirstListItem && parent.kind === 200 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -132767,7 +137039,7 @@ var ts; switch (triviaItem.kind) { case 3 /* MultiLineCommentTrivia */: if (triviaInRange) { - indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); + indentMultilineComment(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); } indentNextTokenOrTrivia = false; break; @@ -132884,7 +137156,7 @@ var ts; function indentationIsDifferent(indentationString, startLinePosition) { return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length); } - function indentMultilineCommentOrJsxText(commentRange, indentation, firstLineIsIndented, indentFinalLine, jsxTextStyleIndent) { + function indentMultilineComment(commentRange, indentation, firstLineIsIndented, indentFinalLine) { if (indentFinalLine === void 0) { indentFinalLine = true; } // split comment in lines var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; @@ -132922,13 +137194,6 @@ var ts; var nonWhitespaceCharacterAndColumn = i === 0 ? nonWhitespaceColumnInFirstPart : formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options); - if (jsxTextStyleIndent) { - // skip adding indentation to blank lines - if (ts.isLineBreak(sourceFile.text.charCodeAt(ts.getStartPositionOfLine(startLine, sourceFile)))) - continue; - // reset delta on every line - delta = indentation - nonWhitespaceCharacterAndColumn.column; - } var newIndentation = nonWhitespaceCharacterAndColumn.column + delta; if (newIndentation > 0) { var indentationString = getIndentationString(newIndentation, options); @@ -133083,12 +137348,12 @@ var ts; formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { - case 166 /* Constructor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 209 /* ArrowFunction */: + case 167 /* Constructor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 210 /* ArrowFunction */: if (node.typeParameters === list) { return 29 /* LessThanToken */; } @@ -133096,8 +137361,8 @@ var ts; return 20 /* OpenParenToken */; } break; - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: if (node.typeArguments === list) { return 29 /* LessThanToken */; } @@ -133105,12 +137370,12 @@ var ts; return 20 /* OpenParenToken */; } break; - case 173 /* TypeReference */: + case 174 /* TypeReference */: if (node.typeArguments === list) { return 29 /* LessThanToken */; } break; - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return 18 /* OpenBraceToken */; } return 0 /* Unknown */; @@ -133228,7 +137493,7 @@ var ts; if (options.indentStyle === ts.IndentStyle.Block) { return getBlockIndent(sourceFile, position, options); } - if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 216 /* BinaryExpression */) { + if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 217 /* BinaryExpression */) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { @@ -133311,6 +137576,7 @@ var ts; } SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) { + var _a; var parent = current.parent; // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if // * parent and child nodes start on the same line, or @@ -133326,7 +137592,25 @@ var ts; childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { // check if current node is a list item - if yes, take indentation from it - var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine); + var firstListChild = (_a = getContainingList(current, sourceFile)) === null || _a === void 0 ? void 0 : _a[0]; + // A list indents its children if the children begin on a later line than the list itself: + // + // f1( L0 - List start + // { L1 - First child start: indented, along with all other children + // prop: 0 + // }, + // { + // prop: 1 + // } + // ) + // + // f2({ L0 - List start and first child start: children are not indented. + // prop: 0 Object properties are indented only one level, because the list + // }, { itself contributes nothing. + // prop: 1 L3 - The indentation of the second object literal is best understood by + // }) looking at the relationship between the list and *first* list item. + var listIndentsChild = !!firstListChild && getStartLineAndCharacterForNode(firstListChild, sourceFile).line > containingListOrParentStart.line; + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, listIndentsChild); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } @@ -133382,7 +137666,7 @@ var ts; // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && - (parent.kind === 297 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 298 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -133430,7 +137714,7 @@ var ts; } SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 234 /* IfStatement */ && parent.elseStatement === child) { + if (parent.kind === 235 /* IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 90 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -133439,6 +137723,49 @@ var ts; return false; } SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement; + // A multiline conditional typically increases the indentation of its whenTrue and whenFalse children: + // + // condition + // ? whenTrue + // : whenFalse; + // + // However, that indentation does not apply if the subexpressions themselves span multiple lines, + // applying their own indentation: + // + // (() => { + // return complexCalculationForCondition(); + // })() ? { + // whenTrue: 'multiline object literal' + // } : ( + // whenFalse('multiline parenthesized expression') + // ); + // + // In these cases, we must discard the indentation increase that would otherwise be applied to the + // whenTrue and whenFalse children to avoid double-indenting their contents. To identify this scenario, + // we check for the whenTrue branch beginning on the line that the condition ends, and the whenFalse + // branch beginning on the line that the whenTrue branch ends. + function childIsUnindentedBranchOfConditionalExpression(parent, child, childStartLine, sourceFile) { + if (ts.isConditionalExpression(parent) && (child === parent.whenTrue || child === parent.whenFalse)) { + var conditionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, parent.condition.end).line; + if (child === parent.whenTrue) { + return childStartLine === conditionEndLine; + } + else { + // On the whenFalse side, we have to look at the whenTrue side, because if that one was + // indented, whenFalse must also be indented: + // + // const y = true + // ? 1 : ( L1: whenTrue indented because it's on a new line + // 0 L2: indented two stops, one because whenTrue was indented + // ); and one because of the parentheses spanning multiple lines + var trueStartLine = getStartLineAndCharacterForNode(parent.whenTrue, sourceFile).line; + var trueEndLine = ts.getLineAndCharacterOfPosition(sourceFile, parent.whenTrue.end).line; + return conditionEndLine === trueStartLine && trueEndLine === childStartLine; + } + } + return false; + } + SmartIndenter.childIsUnindentedBranchOfConditionalExpression = childIsUnindentedBranchOfConditionalExpression; function argumentStartsOnSameLineAsPreviousArgument(parent, child, childStartLine, sourceFile) { if (ts.isCallOrNewExpression(parent)) { if (!parent.arguments) @@ -133468,40 +137795,40 @@ var ts; } function getListByRange(start, end, node, sourceFile) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return getList(node.typeArguments); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return getList(node.properties); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return getList(node.elements); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return getList(node.members); - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 166 /* Constructor */: - case 175 /* ConstructorType */: - case 170 /* ConstructSignature */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 167 /* Constructor */: + case 176 /* ConstructorType */: + case 171 /* ConstructSignature */: return getList(node.typeParameters) || getList(node.parameters); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 330 /* JSDocTemplateTag */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 334 /* JSDocTemplateTag */: return getList(node.typeParameters); - case 204 /* NewExpression */: - case 203 /* CallExpression */: + case 205 /* NewExpression */: + case 204 /* CallExpression */: return getList(node.typeArguments) || getList(node.arguments); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return getList(node.declarations); - case 264 /* NamedImports */: - case 268 /* NamedExports */: + case 265 /* NamedImports */: + case 269 /* NamedExports */: return getList(node.elements); - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: return getList(node.elements); } function getList(list) { @@ -133524,7 +137851,7 @@ var ts; return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options); } function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) { - if (node.parent && node.parent.kind === 250 /* VariableDeclarationList */) { + if (node.parent && node.parent.kind === 251 /* VariableDeclarationList */) { // VariableDeclarationList has no wrapping tokens return -1 /* Unknown */; } @@ -133597,94 +137924,94 @@ var ts; function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { var childKind = child ? child.kind : 0 /* Unknown */; switch (parent.kind) { - case 233 /* ExpressionStatement */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 199 /* ArrayLiteralExpression */: - case 230 /* Block */: - case 257 /* ModuleBlock */: - case 200 /* ObjectLiteralExpression */: - case 177 /* TypeLiteral */: - case 190 /* MappedType */: - case 179 /* TupleType */: - case 258 /* CaseBlock */: - case 285 /* DefaultClause */: - case 284 /* CaseClause */: - case 207 /* ParenthesizedExpression */: - case 201 /* PropertyAccessExpression */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 232 /* VariableStatement */: - case 266 /* ExportAssignment */: - case 242 /* ReturnStatement */: - case 217 /* ConditionalExpression */: - case 197 /* ArrayBindingPattern */: - case 196 /* ObjectBindingPattern */: - case 275 /* JsxOpeningElement */: - case 278 /* JsxOpeningFragment */: - case 274 /* JsxSelfClosingElement */: - case 283 /* JsxExpression */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 160 /* Parameter */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 186 /* ParenthesizedType */: - case 205 /* TaggedTemplateExpression */: - case 213 /* AwaitExpression */: - case 268 /* NamedExports */: - case 264 /* NamedImports */: - case 270 /* ExportSpecifier */: - case 265 /* ImportSpecifier */: - case 163 /* PropertyDeclaration */: + case 234 /* ExpressionStatement */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 200 /* ArrayLiteralExpression */: + case 231 /* Block */: + case 258 /* ModuleBlock */: + case 201 /* ObjectLiteralExpression */: + case 178 /* TypeLiteral */: + case 191 /* MappedType */: + case 180 /* TupleType */: + case 259 /* CaseBlock */: + case 286 /* DefaultClause */: + case 285 /* CaseClause */: + case 208 /* ParenthesizedExpression */: + case 202 /* PropertyAccessExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 233 /* VariableStatement */: + case 267 /* ExportAssignment */: + case 243 /* ReturnStatement */: + case 218 /* ConditionalExpression */: + case 198 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 276 /* JsxOpeningElement */: + case 279 /* JsxOpeningFragment */: + case 275 /* JsxSelfClosingElement */: + case 284 /* JsxExpression */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 161 /* Parameter */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 187 /* ParenthesizedType */: + case 206 /* TaggedTemplateExpression */: + case 214 /* AwaitExpression */: + case 269 /* NamedExports */: + case 265 /* NamedImports */: + case 271 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 164 /* PropertyDeclaration */: return true; - case 249 /* VariableDeclaration */: - case 288 /* PropertyAssignment */: - case 216 /* BinaryExpression */: - if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 200 /* ObjectLiteralExpression */) { // TODO: GH#18217 + case 250 /* VariableDeclaration */: + case 289 /* PropertyAssignment */: + case 217 /* BinaryExpression */: + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 201 /* ObjectLiteralExpression */) { // TODO: GH#18217 return rangeIsOnOneLine(sourceFile, child); } - if (parent.kind !== 216 /* BinaryExpression */) { + if (parent.kind !== 217 /* BinaryExpression */) { return true; } break; - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 237 /* ForStatement */: - case 234 /* IfStatement */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - return childKind !== 230 /* Block */; - case 209 /* ArrowFunction */: - if (sourceFile && childKind === 207 /* ParenthesizedExpression */) { + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 238 /* ForStatement */: + case 235 /* IfStatement */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return childKind !== 231 /* Block */; + case 210 /* ArrowFunction */: + if (sourceFile && childKind === 208 /* ParenthesizedExpression */) { return rangeIsOnOneLine(sourceFile, child); } - return childKind !== 230 /* Block */; - case 267 /* ExportDeclaration */: - return childKind !== 268 /* NamedExports */; - case 261 /* ImportDeclaration */: - return childKind !== 262 /* ImportClause */ || - (!!child.namedBindings && child.namedBindings.kind !== 264 /* NamedImports */); - case 273 /* JsxElement */: - return childKind !== 276 /* JsxClosingElement */; - case 277 /* JsxFragment */: - return childKind !== 279 /* JsxClosingFragment */; - case 183 /* IntersectionType */: - case 182 /* UnionType */: - if (childKind === 177 /* TypeLiteral */ || childKind === 179 /* TupleType */) { + return childKind !== 231 /* Block */; + case 268 /* ExportDeclaration */: + return childKind !== 269 /* NamedExports */; + case 262 /* ImportDeclaration */: + return childKind !== 263 /* ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 265 /* NamedImports */); + case 274 /* JsxElement */: + return childKind !== 277 /* JsxClosingElement */; + case 278 /* JsxFragment */: + return childKind !== 280 /* JsxClosingFragment */; + case 184 /* IntersectionType */: + case 183 /* UnionType */: + if (childKind === 178 /* TypeLiteral */ || childKind === 180 /* TupleType */) { return false; } - // falls through + break; } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -133692,11 +138019,11 @@ var ts; SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; function isControlFlowEndingStatement(kind, parent) { switch (kind) { - case 242 /* ReturnStatement */: - case 246 /* ThrowStatement */: - case 240 /* ContinueStatement */: - case 241 /* BreakStatement */: - return parent.kind !== 230 /* Block */; + case 243 /* ReturnStatement */: + case 247 /* ThrowStatement */: + case 241 /* ContinueStatement */: + case 242 /* BreakStatement */: + return parent.kind !== 231 /* Block */; default: return false; } @@ -133804,7 +138131,9 @@ var ts; function getAdjustedRange(sourceFile, startNode, endNode, options) { return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) }; } - function getAdjustedStartPosition(sourceFile, node, options) { + function getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment) { + var _a, _b; + if (hasTrailingComment === void 0) { hasTrailingComment = false; } var leadingTriviaOption = options.leadingTriviaOption; if (leadingTriviaOption === LeadingTriviaOption.Exclude) { return node.getStart(sourceFile); @@ -133835,6 +138164,15 @@ var ts; // when b is deleted - we delete it return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start; } + // if node has a trailing comments, use comment end position as the text has already been included. + if (hasTrailingComment) { + // Check first for leading comments as if the node is the first import, we want to exclude the trivia; + // otherwise we get the trailing comments. + var comment = ((_a = ts.getLeadingCommentRanges(sourceFile.text, fullStart)) === null || _a === void 0 ? void 0 : _a[0]) || ((_b = ts.getTrailingCommentRanges(sourceFile.text, fullStart)) === null || _b === void 0 ? void 0 : _b[0]); + if (comment) { + return ts.skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + } + } // get start position of the line following the line that contains fullstart position // (but only if the fullstart isn't the very beginning of the file) var nextLineStart = fullStart > 0 ? 1 : 0; @@ -133843,6 +138181,35 @@ var ts; adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } + /** Return the end position of a multiline comment of it is on another line; otherwise returns `undefined`; */ + function getEndPositionOfMultilineTrailingComment(sourceFile, node, options) { + var end = node.end; + var trailingTriviaOption = options.trailingTriviaOption; + if (trailingTriviaOption === TrailingTriviaOption.Include) { + // If the trailing comment is a multiline comment that extends to the next lines, + // return the end of the comment and track it for the next nodes to adjust. + var comments = ts.getTrailingCommentRanges(sourceFile.text, end); + if (comments) { + var nodeEndLine = ts.getLineOfLocalPosition(sourceFile, node.end); + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + // Single line can break the loop as trivia will only be this line. + // Comments on subsequest lines are also ignored. + if (comment.kind === 2 /* SingleLineCommentTrivia */ || ts.getLineOfLocalPosition(sourceFile, comment.pos) > nodeEndLine) { + break; + } + // Get the end line of the comment and compare against the end line of the node. + // If the comment end line position and the multiline comment extends to multiple lines, + // then is safe to return the end position. + var commentEndLine = ts.getLineOfLocalPosition(sourceFile, comment.end); + if (commentEndLine > nodeEndLine) { + return ts.skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + } + } + } + } + return undefined; + } function getAdjustedEndPosition(sourceFile, node, options) { var _a; var end = node.end; @@ -133858,6 +138225,10 @@ var ts; } return end; } + var multilineEndPosition = getEndPositionOfMultilineTrailingComment(sourceFile, node, options); + if (multilineEndPosition) { + return multilineEndPosition; + } var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))) ? newEnd @@ -133867,14 +138238,7 @@ var ts; * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ function isSeparator(node, candidate) { - return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 200 /* ObjectLiteralExpression */)); - } - function spaces(count) { - var s = ""; - for (var i = 0; i < count; i++) { - s += " "; - } - return s; + return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 201 /* ObjectLiteralExpression */)); } function isThisTypeAnnotatable(containingFunction) { return ts.isFunctionExpression(containingFunction) || ts.isFunctionDeclaration(containingFunction); @@ -133920,6 +138284,17 @@ var ts; if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options)); }; + ChangeTracker.prototype.deleteNodes = function (sourceFile, nodes, options, hasTrailingComment) { + if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } + // When deleting multiple nodes we need to track if the end position is including multiline trailing comments. + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var pos = getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment); + var end = getAdjustedEndPosition(sourceFile, node, options); + this.deleteRange(sourceFile, { pos: pos, end: end }); + hasTrailingComment = !!getEndPositionOfMultilineTrailingComment(sourceFile, node, options); + } + }; ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); }; @@ -133962,6 +138337,10 @@ var ts; if (options === void 0) { options = useNonAdjustedPositions; } this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; + ChangeTracker.prototype.nodeHasTrailingComment = function (sourceFile, oldNode, configurableEnd) { + if (configurableEnd === void 0) { configurableEnd = useNonAdjustedPositions; } + return !!getEndPositionOfMultilineTrailingComment(sourceFile, oldNode, configurableEnd); + }; ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { var next = ts.findNextToken(node, node.parent, sourceFile); return next && next.kind === 27 /* CommaToken */ ? next : undefined; @@ -134066,7 +138445,7 @@ var ts; } } else { - endNode = (_a = (node.kind === 249 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken)) !== null && _a !== void 0 ? _a : node.name; + endNode = (_a = (node.kind === 250 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken)) !== null && _a !== void 0 ? _a : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); return true; @@ -134108,6 +138487,15 @@ var ts; this.insertNodeBefore(sourceFile, firstStatement, newStatement); } }; + ChangeTracker.prototype.insertNodeAtConstructorStartAfterSuperCall = function (sourceFile, ctr, newStatement) { + var superCallStatement = ts.find(ctr.body.statements, function (stmt) { return ts.isExpressionStatement(stmt) && ts.isSuperCall(stmt.expression); }); + if (!superCallStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, __spreadArray(__spreadArray([], ctr.body.statements), [newStatement])); + } + else { + this.insertNodeAfter(sourceFile, superCallStatement, newStatement); + } + }; ChangeTracker.prototype.insertNodeAtConstructorEnd = function (sourceFile, ctr, newStatement) { var lastStatement = ts.lastOrUndefined(ctr.body.statements); if (!lastStatement || !ctr.body.multiLine) { @@ -134223,18 +138611,18 @@ var ts; }; ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { switch (node.kind) { - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: case 10 /* StringLiteral */: case 78 /* Identifier */: return { prefix: ", " }; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return { suffix: "," + this.newLineCharacter }; case 92 /* ExportKeyword */: return { prefix: " " }; - case 160 /* Parameter */: + case 161 /* Parameter */: return {}; default: ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it @@ -134243,7 +138631,7 @@ var ts; }; ChangeTracker.prototype.insertName = function (sourceFile, node, name) { ts.Debug.assert(!node.name); - if (node.kind === 209 /* ArrowFunction */) { + if (node.kind === 210 /* ArrowFunction */) { var arrow = ts.findChildOfKind(node, 38 /* EqualsGreaterThanToken */, sourceFile); var lparen = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile); if (lparen) { @@ -134257,14 +138645,14 @@ var ts; // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)` this.replaceRange(sourceFile, arrow, ts.factory.createToken(21 /* CloseParenToken */)); } - if (node.body.kind !== 230 /* Block */) { + if (node.body.kind !== 231 /* Block */) { // `() => 0` => `function f() { return 0; }` this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.factory.createToken(18 /* OpenBraceToken */), ts.factory.createToken(104 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); this.insertNodesAt(sourceFile, node.body.end, [ts.factory.createToken(26 /* SemicolonToken */), ts.factory.createToken(19 /* CloseBraceToken */)], { joiner: " " }); } } else { - var pos = ts.findChildOfKind(node, node.kind === 208 /* FunctionExpression */ ? 97 /* FunctionKeyword */ : 83 /* ClassKeyword */, sourceFile).end; + var pos = ts.findChildOfKind(node, node.kind === 209 /* FunctionExpression */ ? 97 /* FunctionKeyword */ : 83 /* ClassKeyword */, sourceFile).end; this.insertNodeAt(sourceFile, pos, ts.factory.createIdentifier(name), { prefix: " " }); } }; @@ -134296,47 +138684,22 @@ var ts; // a, b, c // create change for adding 'e' after 'a' as // - find start of next element after a (it is b) - // - use this start as start and end position in final change - // - build text of change by formatting the text of node + separator + whitespace trivia of b + // - use next element start as start and end position in final change + // - build text of change by formatting the text of node + whitespace trivia of b // in multiline case it will work as // a, // b, // c, // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#') - // a,* - // ***insertedtext# + // a, + // insertedtext# // ###b, // c, - // find line and character of the next element - var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart())); - // find line and character of the token that precedes next element (usually it is separator) - var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end); - var prefix = void 0; - var startPos = void 0; - if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) { - // next element is located on the same line with separator: - // a,$$$$b - // ^ ^ - // | |-next element - // |-separator - // where $$$ is some leading trivia - // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces - // a, x,$$$$b - // ^ ^ ^ - // | | |-next element - // | |-new inserted node padded with spaces - // |-separator - startPos = nextToken.end; - prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character); - } - else { - // next element is located on different line that separator - // let insert position be the beginning of the line that contains next element - startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); - } + var nextNode = containingList[index + 1]; + var startPos = skipWhitespacesAndLineBreaks(sourceFile.text, nextNode.getFullStart()); // write separator and leading trivia of the next element as suffix - var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, startPos); + this.insertNodesAt(sourceFile, startPos, [newNode], { suffix: suffix }); } } else { @@ -134408,7 +138771,7 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.Set(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_9 = function (sourceFile, node) { + var _loop_10 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(sourceFile, node)); @@ -134421,7 +138784,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_9(sourceFile, node); + _loop_10(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -134480,14 +138843,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_10 = function (i) { + var _loop_11 = 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_10(i); + _loop_11(i); } var textChanges = ts.mapDefined(normalized, function (c) { var span = ts.createTextSpanFromRange(c.range); @@ -134601,11 +138964,12 @@ var ts; function createWriter(newLine) { var lastNonTriviaPosition = 0; var writer = ts.createTextWriter(newLine); - var onEmitNode = function (hint, node, printCallback) { + var onBeforeEmitNode = function (node) { if (node) { setPos(node, lastNonTriviaPosition); } - printCallback(hint, node); + }; + var onAfterEmitNode = function (node) { if (node) { setEnd(node, lastNonTriviaPosition); } @@ -134724,7 +139088,8 @@ var ts; lastNonTriviaPosition = 0; } return { - onEmitNode: onEmitNode, + onBeforeEmitNode: onBeforeEmitNode, + onAfterEmitNode: onAfterEmitNode, onBeforeEmitNodeArray: onBeforeEmitNodeArray, onAfterEmitNodeArray: onAfterEmitNodeArray, onBeforeEmitToken: onBeforeEmitToken, @@ -134839,14 +139204,14 @@ var ts; } textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment; function needSemicolonBetween(a, b) { - return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 158 /* ComputedPropertyName */ + return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 159 /* ComputedPropertyName */ || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[` } var deleteDeclaration; (function (deleteDeclaration_1) { function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) { switch (node.kind) { - case 160 /* Parameter */: { + case 161 /* Parameter */: { var oldFunction = node.parent; if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1 && @@ -134861,15 +139226,17 @@ var ts; } break; } - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isAnyImportSyntax); // For first import, leave header comment in place, otherwise only delete JSDoc comments - deleteNode(changes, sourceFile, node, { leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); + deleteNode(changes, sourceFile, node, { + leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine, + }); break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: var pattern = node.parent; - var preserveComma = pattern.kind === 197 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); + var preserveComma = pattern.kind === 198 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); if (preserveComma) { deleteNode(changes, sourceFile, node); } @@ -134877,13 +139244,13 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); break; - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); break; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: var namedImports = node.parent; if (namedImports.elements.length === 1) { deleteImportBinding(changes, sourceFile, namedImports); @@ -134892,7 +139259,7 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: deleteImportBinding(changes, sourceFile, node); break; case 26 /* SemicolonToken */: @@ -134901,12 +139268,16 @@ var ts; case 97 /* FunctionKeyword */: deleteNode(changes, sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.Exclude }); break; - case 252 /* ClassDeclaration */: - case 251 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: deleteNode(changes, sourceFile, node, { leadingTriviaOption: ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; default: - if (ts.isImportClause(node.parent) && node.parent.name === node) { + if (!node.parent) { + // a misbehaving client can reach here with the SourceFile node + deleteNode(changes, sourceFile, node); + } + else if (ts.isImportClause(node.parent) && node.parent.name === node) { deleteDefaultImport(changes, sourceFile, node.parent); } else if (ts.isCallExpression(node.parent) && ts.contains(node.parent.arguments, node)) { @@ -134949,13 +139320,13 @@ var ts; // Delete the entire import declaration // |import * as ns from './file'| // |import { a } from './file'| - var importDecl = ts.getAncestor(node, 261 /* ImportDeclaration */); + var importDecl = ts.getAncestor(node, 262 /* ImportDeclaration */); deleteNode(changes, sourceFile, importDecl); } } function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) { var parent = node.parent; - if (parent.kind === 287 /* CatchClause */) { + if (parent.kind === 288 /* CatchClause */) { // TODO: There's currently no unused diagnostic for this, could be a suggestion changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 20 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 21 /* CloseParenToken */, sourceFile)); return; @@ -134966,14 +139337,14 @@ var ts; } var gp = parent.parent; switch (gp.kind) { - case 239 /* ForOfStatement */: - case 238 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 239 /* ForInStatement */: changes.replaceNode(sourceFile, node, ts.factory.createObjectLiteralExpression()); break; - case 237 /* ForStatement */: + case 238 /* ForStatement */: deleteNode(changes, sourceFile, parent); break; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: deleteNode(changes, sourceFile, gp, { leadingTriviaOption: ts.hasJSDocNodes(gp) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; default: @@ -135029,6 +139400,10 @@ var ts; return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); } codefix.createCodeFixAction = createCodeFixAction; + function createCodeFixActionMaybeFixAll(fixName, changes, description, fixId, fixAllDescription, command) { + return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, fixAllDescription && diagnosticToString(fixAllDescription), command); + } + codefix.createCodeFixActionMaybeFixAll = createCodeFixActionMaybeFixAll; function createCodeFixActionWorker(fixName, description, changes, fixId, fixAllDescription, command) { return { fixName: fixName, description: description, changes: changes, fixId: fixId, fixAllDescription: fixAllDescription, commands: command ? [command] : undefined }; } @@ -135167,7 +139542,10 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code], + errorCodes: [ + ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + ], getCodeActions: function (context) { var sourceFile = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { @@ -135280,6 +139658,7 @@ var ts; ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1.code, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap.code, + ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined.code, ts.Diagnostics.Type_0_is_not_an_array_type.code, ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code, ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators.code, @@ -135378,14 +139757,14 @@ var ts; } var isCompleteFix = identifiers.isCompleteFix; var initializers; - var _loop_11 = function (identifier) { + var _loop_12 = function (identifier) { var symbol = checker.getSymbolAtLocation(identifier); if (!symbol) { return "continue"; } var declaration = ts.tryCast(symbol.valueDeclaration, ts.isVariableDeclaration); var variableName = declaration && ts.tryCast(declaration.name, ts.isIdentifier); - var variableStatement = ts.getAncestor(declaration, 232 /* VariableStatement */); + var variableStatement = ts.getAncestor(declaration, 233 /* VariableStatement */); if (!declaration || !variableStatement || declaration.type || !declaration.initializer || @@ -135411,7 +139790,7 @@ var ts; }; for (var _i = 0, _a = identifiers.identifiers; _i < _a.length; _i++) { var identifier = _a[_i]; - _loop_11(identifier); + _loop_12(identifier); } return initializers && { initializers: initializers, @@ -135463,10 +139842,10 @@ var ts; function isInsideAwaitableBody(node) { return node.kind & 32768 /* AwaitContext */ || !!ts.findAncestor(node, function (ancestor) { return ancestor.parent && ts.isArrowFunction(ancestor.parent) && ancestor.parent.body === ancestor || - ts.isBlock(ancestor) && (ancestor.parent.kind === 251 /* FunctionDeclaration */ || - ancestor.parent.kind === 208 /* FunctionExpression */ || - ancestor.parent.kind === 209 /* ArrowFunction */ || - ancestor.parent.kind === 165 /* MethodDeclaration */); + ts.isBlock(ancestor) && (ancestor.parent.kind === 252 /* FunctionDeclaration */ || + ancestor.parent.kind === 209 /* FunctionExpression */ || + ancestor.parent.kind === 210 /* ArrowFunction */ || + ancestor.parent.kind === 166 /* MethodDeclaration */); }); } function makeChange(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) { @@ -135585,10 +139964,10 @@ var ts; function isPossiblyPartOfDestructuring(node) { switch (node.kind) { case 78 /* Identifier */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return true; default: return false; @@ -135603,7 +139982,7 @@ var ts; function isPossiblyPartOfCommaSeperatedInitializer(node) { switch (node.kind) { case 78 /* Identifier */: - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: case 27 /* CommaToken */: return true; default: @@ -135652,7 +140031,7 @@ var ts; return; } var declaration = token.parent; - if (declaration.kind === 163 /* PropertyDeclaration */ && + if (declaration.kind === 164 /* PropertyDeclaration */ && (!fixedNodes || ts.tryAddToSet(fixedNodes, declaration))) { changeTracker.insertModifierBefore(sourceFile, 133 /* DeclareKeyword */, declaration); } @@ -135789,26 +140168,26 @@ var ts; } function isDeclarationWithType(node) { return ts.isFunctionLikeDeclaration(node) || - node.kind === 249 /* VariableDeclaration */ || - node.kind === 162 /* PropertySignature */ || - node.kind === 163 /* PropertyDeclaration */; + node.kind === 250 /* VariableDeclaration */ || + node.kind === 163 /* PropertySignature */ || + node.kind === 164 /* PropertyDeclaration */; } function transformJSDocType(node) { switch (node.kind) { - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: return ts.factory.createTypeReferenceNode("any", ts.emptyArray); - case 307 /* JSDocOptionalType */: + case 308 /* JSDocOptionalType */: return transformJSDocOptionalType(node); - case 306 /* JSDocNonNullableType */: + case 307 /* JSDocNonNullableType */: return transformJSDocType(node.type); - case 305 /* JSDocNullableType */: + case 306 /* JSDocNullableType */: return transformJSDocNullableType(node); - case 309 /* JSDocVariadicType */: + case 310 /* JSDocVariadicType */: return transformJSDocVariadicType(node); - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: return transformJSDocFunctionType(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return transformJSDocTypeReference(node); default: var visited = ts.visitEachChild(node, transformJSDocType, ts.nullTransformationContext); @@ -135833,7 +140212,7 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 309 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 + var isRest = node.type.kind === 310 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 var name = node.name || (isRest ? "rest" : "arg" + index); var dotdotdot = isRest ? ts.factory.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken; return ts.factory.createParameterDeclaration(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); @@ -135904,7 +140283,7 @@ var ts; }); function doChange(changes, sourceFile, position, checker, preferences, compilerOptions) { var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position)); - if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + if (!ctorSymbol || !ctorSymbol.valueDeclaration || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { // Bad input return undefined; } @@ -135931,7 +140310,7 @@ var ts; // all instance members are stored in the "member" array of symbol if (symbol.members) { symbol.members.forEach(function (member, key) { - if (key === "constructor") { + if (key === "constructor" && member.valueDeclaration) { // fn.prototype.constructor = fn changes.delete(sourceFile, member.valueDeclaration.parent); return; @@ -135945,7 +140324,7 @@ var ts; // all static members are stored in the "exports" array of symbol if (symbol.exports) { symbol.exports.forEach(function (member) { - if (member.name === "prototype") { + if (member.name === "prototype" && member.declarations) { var firstDeclaration = member.declarations[0]; // only one "x.prototype = { ... }" will pass if (member.declarations.length === 1 && @@ -136007,7 +140386,7 @@ var ts; return members; } // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end - var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 233 /* ExpressionStatement */ + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 234 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); if (!assignmentExpr) { @@ -136068,7 +140447,7 @@ var ts; var arrowFunctionBody = arrowFunction.body; var bodyBlock; // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 230 /* Block */) { + if (arrowFunctionBody.kind === 231 /* Block */) { bodyBlock = arrowFunctionBody; } // case 2: () => [1,2,3] @@ -136170,7 +140549,7 @@ var ts; functionToConvert = tokenAtPosition.parent.initializer; } else { - functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.canBeConvertedToAsync); } if (!functionToConvert) { return; @@ -136179,7 +140558,10 @@ var ts; var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap); - var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray; + if (!ts.returnsPromise(functionToConvertRenamed, checker)) { + return; + } + var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : ts.emptyArray; var transformer = { checker: checker, synthNamesMap: synthNamesMap, setOfExpressionsToReturn: setOfExpressionsToReturn, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; @@ -136189,7 +140571,7 @@ var ts; functionToConvert.getStart(sourceFile); var options = functionToConvert.modifiers ? { prefix: " " } : { suffix: " " }; changes.insertModifierAt(sourceFile, pos, 129 /* AsyncKeyword */, options); - var _loop_12 = function (returnStatement) { + var _loop_13 = function (returnStatement) { ts.forEachChild(returnStatement, function visit(node) { if (ts.isCallExpression(node)) { var newNodes = transformExpression(node, transformer); @@ -136202,13 +140584,13 @@ var ts; }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var returnStatement = returnStatements_1[_i]; - _loop_12(returnStatement); + _loop_13(returnStatement); } } - function getReturnStatementsWithPromiseHandlers(body) { + function getReturnStatementsWithPromiseHandlers(body, checker) { var res = []; ts.forEachReturnStatement(body, function (ret) { - if (ts.isReturnStatementWithFixablePromiseHandler(ret)) + if (ts.isReturnStatementWithFixablePromiseHandler(ret, checker)) res.push(ret); }); return res; @@ -136279,7 +140661,10 @@ var ts; // so we push an entry for 'response'. if (lastCallSignature && !ts.isParameter(node.parent) && !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.factory.createUniqueName("result", 16 /* Optimistic */); + var ident = (firstParameter === null || firstParameter === void 0 ? void 0 : firstParameter.valueDeclaration) + && ts.isParameter(firstParameter.valueDeclaration) + && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) + || ts.factory.createUniqueName("result", 16 /* Optimistic */); var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); collidingSymbolMap.add(ident.text, symbol); @@ -136457,6 +140842,7 @@ var ts; case 103 /* NullKeyword */: // do not produce a transformed statement for a null argument break; + case 202 /* PropertyAccessExpression */: case 78 /* Identifier */: // identifier includes undefined if (!argName) { // undefined was argument passed to promise handler @@ -136478,8 +140864,8 @@ var ts; prevArgName.types.push(returnType); } return varDeclOrAssignment; - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: { + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: { var funcBody = func.body; var returnType_1 = (_c = getLastCallSignature(transformer.checker.getTypeAtLocation(func), transformer.checker)) === null || _c === void 0 ? void 0 : _c.getReturnType(); // Arrow functions with block bodies { } will enter this control flow @@ -136490,7 +140876,7 @@ var ts; var statement = _f[_i]; if (ts.isReturnStatement(statement)) { seenReturnStatement = true; - if (ts.isReturnStatementWithFixablePromiseHandler(statement)) { + if (ts.isReturnStatementWithFixablePromiseHandler(statement, transformer.checker)) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } else { @@ -136507,7 +140893,7 @@ var ts; : removeReturns(refactoredStmts, prevArgName, transformer, seenReturnStatement); } else { - var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.factory.createReturnStatement(funcBody)] : ts.emptyArray; + var innerRetStmts = ts.isFixablePromiseHandler(funcBody, transformer.checker) ? [ts.factory.createReturnStatement(funcBody)] : ts.emptyArray; var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { return innerCbBody; @@ -136600,6 +140986,9 @@ var ts; else if (ts.isIdentifier(funcNode)) { name = getMapEntryOrDefault(funcNode); } + else if (ts.isPropertyAccessExpression(funcNode) && ts.isIdentifier(funcNode.name)) { + name = getMapEntryOrDefault(funcNode.name); + } // return undefined argName when arg is null or undefined // eslint-disable-next-line no-in-operator if (!name || "identifier" in name && name.identifier.text === "undefined") { @@ -136695,10 +141084,10 @@ var ts; } var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { changes.replaceNode(importingFile, importNode, ts.factory.createPropertyAccessExpression(ts.getSynthesizedDeepClone(importNode), "default")); } @@ -136765,20 +141154,20 @@ var ts; } function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, useSitesToUnqualify, quotePreference) { switch (statement.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); return false; - case 233 /* ExpressionStatement */: { + case 234 /* ExpressionStatement */: { var expression = statement.expression; switch (expression.kind) { - case 203 /* CallExpression */: { + case 204 /* CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); } return false; } - case 216 /* BinaryExpression */: { + case 217 /* BinaryExpression */: { var operatorToken = expression.operatorToken; return operatorToken.kind === 62 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports, useSitesToUnqualify); } @@ -136827,8 +141216,8 @@ var ts; /** Converts `const name = require("moduleSpecifier").propertyName` */ function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { switch (name.kind) { - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: { + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` var tmp = makeUniqueName(propertyName, identifiers); return convertedImports([ @@ -136879,16 +141268,16 @@ var ts; function tryChangeModuleExportsObject(object, useSitesToUnqualify) { var statements = ts.mapAllOrFail(object.properties, function (prop) { switch (prop.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. // falls through - case 289 /* ShorthandPropertyAssignment */: - case 290 /* SpreadAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 291 /* SpreadAssignment */: return undefined; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer, useSitesToUnqualify); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.factory.createToken(92 /* ExportKeyword */)], prop, useSitesToUnqualify); default: ts.Debug.assertNever(prop, "Convert to ES6 got invalid prop kind " + prop.kind); @@ -136952,7 +141341,7 @@ var ts; function convertExportsDotXEquals_replaceNode(name, exported, useSitesToUnqualify) { var modifiers = [ts.factory.createToken(92 /* ExportKeyword */)]; switch (exported.kind) { - case 208 /* FunctionExpression */: { + case 209 /* FunctionExpression */: { var expressionName = exported.name; if (expressionName && expressionName.text !== name) { // `exports.f = function g() {}` -> `export const f = function g() {}` @@ -136960,10 +141349,10 @@ var ts; } } // falls through - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: // `exports.f = function() {}` --> `export function f() {}` return functionExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: // `exports.C = class {}` --> `export class C {}` return classExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify); default: @@ -136983,7 +141372,7 @@ var ts; : ts.getSynthesizedDeepCloneWithReplacements(nodeOrNodes, /*includeTrivia*/ true, replaceNode); function replaceNode(original) { // We are replacing `mod.SomeExport` wih `SomeExport`, so we only need to look at PropertyAccessExpressions - if (original.kind === 201 /* PropertyAccessExpression */) { + if (original.kind === 202 /* PropertyAccessExpression */) { var replacement = useSitesToUnqualify.get(original); // Remove entry from `useSitesToUnqualify` so the refactor knows it's taken care of by the parent statement we're replacing useSitesToUnqualify.delete(original); @@ -136998,7 +141387,7 @@ var ts; */ function convertSingleImport(name, moduleSpecifier, checker, identifiers, target, quotePreference) { switch (name.kind) { - case 196 /* ObjectBindingPattern */: { + case 197 /* ObjectBindingPattern */: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) ? undefined @@ -137011,7 +141400,7 @@ var ts; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration - case 197 /* ArrayBindingPattern */: { + case 198 /* ArrayBindingPattern */: { /* import x from "x"; const [a, b, c] = x; @@ -137030,7 +141419,9 @@ var ts; } /** * Convert `import x = require("x").` - * Also converts uses like `x.y()` to `y()` and uses a named import. + * Also: + * - Convert `x.default()` to `x()` to handle ES6 default export + * - Converts uses like `x.y()` to `y()` and uses a named import. */ function convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference) { var nameSymbol = checker.getSymbolAtLocation(name); @@ -137047,14 +141438,21 @@ var ts; } var parent = use.parent; if (ts.isPropertyAccessExpression(parent)) { - var expression = parent.expression, propertyName = parent.name.text; - ts.Debug.assert(expression === use, "Didn't expect expression === use"); // Else shouldn't have been in `collectIdentifiers` - var idName = namedBindingsNames.get(propertyName); - if (idName === undefined) { - idName = makeUniqueName(propertyName, identifiers); - namedBindingsNames.set(propertyName, idName); + var propertyName = parent.name.text; + if (propertyName === "default") { + needDefaultImport = true; + var importDefaultName = use.getText(); + (useSitesToUnqualify !== null && useSitesToUnqualify !== void 0 ? useSitesToUnqualify : (useSitesToUnqualify = new ts.Map())).set(parent, ts.factory.createIdentifier(importDefaultName)); + } + else { + ts.Debug.assert(parent.expression === use, "Didn't expect expression === use"); // Else shouldn't have been in `collectIdentifiers` + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + (useSitesToUnqualify !== null && useSitesToUnqualify !== void 0 ? useSitesToUnqualify : (useSitesToUnqualify = new ts.Map())).set(parent, ts.factory.createIdentifier(idName)); } - (useSitesToUnqualify !== null && useSitesToUnqualify !== void 0 ? useSitesToUnqualify : (useSitesToUnqualify = new ts.Map())).set(parent, ts.factory.createIdentifier(idName)); } else { needDefaultImport = true; @@ -137095,11 +141493,11 @@ var ts; function isFreeIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return parent.name !== node; - case 198 /* BindingElement */: + case 199 /* BindingElement */: return parent.propertyName !== node; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: return parent.propertyName !== node; default: return true; @@ -137576,87 +141974,138 @@ var ts; ImportFixKind[ImportFixKind["AddToExisting"] = 2] = "AddToExisting"; ImportFixKind[ImportFixKind["AddNew"] = 3] = "AddNew"; })(ImportFixKind || (ImportFixKind = {})); - var ImportKind; - (function (ImportKind) { - ImportKind[ImportKind["Named"] = 0] = "Named"; - ImportKind[ImportKind["Default"] = 1] = "Default"; - ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; - ImportKind[ImportKind["CommonJS"] = 3] = "CommonJS"; - })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { var compilerOptions = program.getCompilerOptions(); var exportInfos = ts.pathIsBareSpecifier(ts.stripQuotes(moduleSymbol.name)) - ? [getSymbolExportInfoForSymbol(exportedSymbol, moduleSymbol, sourceFile, program, host)] + ? [getSymbolExportInfoForSymbol(exportedSymbol, moduleSymbol, program, host)] : getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, host, program, /*useAutoImportProvider*/ true); var useRequire = shouldUseRequire(sourceFile, program); var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && !ts.isSourceFileJS(sourceFile) && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences)).moduleSpecifier; var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences); - return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; + return { moduleSpecifier: fix.moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences) { ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol"); - // We sort the best codefixes first, so taking `first` is best. - return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences)); + return getBestFix(getImportFixes(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences), sourceFile, host); } function codeFixActionToCodeAction(_a) { var description = _a.description, changes = _a.changes, commands = _a.commands; return { description: description, changes: changes, commands: commands }; } - function getSymbolExportInfoForSymbol(symbol, moduleSymbol, importingFile, program, host) { + function getSymbolExportInfoForSymbol(symbol, moduleSymbol, program, host) { var _a, _b; var compilerOptions = program.getCompilerOptions(); - var mainProgramInfo = getInfoWithChecker(program.getTypeChecker()); + var mainProgramInfo = getInfoWithChecker(program.getTypeChecker(), /*isFromPackageJson*/ false); if (mainProgramInfo) { return mainProgramInfo; } var autoImportProvider = (_b = (_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getTypeChecker(); - return ts.Debug.checkDefined(autoImportProvider && getInfoWithChecker(autoImportProvider), "Could not find symbol in specified module for code actions"); - function getInfoWithChecker(checker) { - var defaultInfo = getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions); + return ts.Debug.checkDefined(autoImportProvider && getInfoWithChecker(autoImportProvider, /*isFromPackageJson*/ true), "Could not find symbol in specified module for code actions"); + function getInfoWithChecker(checker, isFromPackageJson) { + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); if (defaultInfo && ts.skipAlias(defaultInfo.symbol, checker) === symbol) { - return { moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker) }; + return { symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, exportKind: defaultInfo.exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker), isFromPackageJson: isFromPackageJson }; } var named = checker.tryGetMemberInModuleExportsAndProperties(symbol.name, moduleSymbol); if (named && ts.skipAlias(named, checker) === symbol) { - return { moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker) }; + return { symbol: named, moduleSymbol: moduleSymbol, exportKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker), isFromPackageJson: isFromPackageJson }; } } } function getAllReExportingModules(importingFile, exportedSymbol, exportingModuleSymbol, symbolName, host, program, useAutoImportProvider) { var result = []; var compilerOptions = program.getCompilerOptions(); - forEachExternalModuleToImportFrom(program, host, importingFile, /*filterByPackageJson*/ false, useAutoImportProvider, function (moduleSymbol, moduleFile, program) { + var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { + return ts.createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); + }); + forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, function (moduleSymbol, moduleFile, program, isFromPackageJson) { var checker = program.getTypeChecker(); // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(importingFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } - var defaultInfo = getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions); - if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { - result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + result.push({ symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, exportKind: defaultInfo.exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker), isFromPackageJson: isFromPackageJson }); } for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { - result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + result.push({ symbol: exported, moduleSymbol: moduleSymbol, exportKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker), isFromPackageJson: isFromPackageJson }); } } }); return result; + function isImportable(program, moduleFile, isFromPackageJson) { + var _a; + return !moduleFile || ts.isImportableFile(program, importingFile, moduleFile, /*packageJsonFilter*/ undefined, getModuleSpecifierResolutionHost(isFromPackageJson), (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host)); + } + } + function getModuleSpecifierForBestExportInfo(exportInfo, importingFile, program, host, preferences) { + return getBestFix(getNewImportFixes(program, importingFile, /*position*/ undefined, /*preferTypeOnlyImport*/ false, /*useRequire*/ false, exportInfo, host, preferences), importingFile, host); } + codefix.getModuleSpecifierForBestExportInfo = getModuleSpecifierForBestExportInfo; + function getSymbolToExportInfoMap(importingFile, host, program) { + var _a, _b, _c, _d, _e, _f, _g, _h; + var start = ts.timestamp(); + // Pulling the AutoImportProvider project will trigger its updateGraph if pending, + // which will invalidate the export map cache if things change, so pull it before + // checking the cache. + (_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host); + var cache = (_b = host.getExportMapCache) === null || _b === void 0 ? void 0 : _b.call(host); + if (cache) { + var cached = cache.get(importingFile.path, program.getTypeChecker(), (_c = host.getProjectVersion) === null || _c === void 0 ? void 0 : _c.call(host)); + if (cached) { + (_d = host.log) === null || _d === void 0 ? void 0 : _d.call(host, "getSymbolToExportInfoMap: cache hit"); + return cached; + } + else { + (_e = host.log) === null || _e === void 0 ? void 0 : _e.call(host, "getSymbolToExportInfoMap: cache miss or empty; calculating new results"); + } + } + var result = ts.createMultiMap(); + var compilerOptions = program.getCompilerOptions(); + var target = ts.getEmitScriptTarget(compilerOptions); + forEachExternalModuleToImportFrom(program, host, /*useAutoImportProvider*/ true, function (moduleSymbol, _moduleFile, program, isFromPackageJson) { + var checker = program.getTypeChecker(); + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo) { + var name = ts.getNameForExportedSymbol(ts.getLocalSymbolForExportDefault(defaultInfo.symbol) || defaultInfo.symbol, target); + result.add(key(name, defaultInfo.symbol, moduleSymbol, checker), { symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, exportKind: defaultInfo.exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker), isFromPackageJson: isFromPackageJson }); + } + var seenExports = new ts.Map(); + for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { + var exported = _a[_i]; + if (exported !== (defaultInfo === null || defaultInfo === void 0 ? void 0 : defaultInfo.symbol) && ts.addToSeen(seenExports, exported)) { + result.add(key(ts.getNameForExportedSymbol(exported, target), exported, moduleSymbol, checker), { symbol: exported, moduleSymbol: moduleSymbol, exportKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker), isFromPackageJson: isFromPackageJson }); + } + } + }); + if (cache) { + (_f = host.log) === null || _f === void 0 ? void 0 : _f.call(host, "getSymbolToExportInfoMap: caching results"); + cache.set(result, (_g = host.getProjectVersion) === null || _g === void 0 ? void 0 : _g.call(host)); + } + (_h = host.log) === null || _h === void 0 ? void 0 : _h.call(host, "getSymbolToExportInfoMap: done in " + (ts.timestamp() - start) + " ms"); + return result; + function key(name, alias, moduleSymbol, checker) { + var moduleName = ts.stripQuotes(moduleSymbol.name); + var moduleKey = ts.isExternalModuleNameRelative(moduleName) ? "/" : moduleName; + return name + "|" + ts.getSymbolId(ts.skipAlias(alias, checker)) + "|" + moduleKey; + } + } + codefix.getSymbolToExportInfoMap = getSymbolToExportInfoMap; function isTypeOnlySymbol(s, checker) { return !(ts.skipAlias(s, checker).flags & 111551 /* Value */); } function isTypeOnlyPosition(sourceFile, position) { return ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); } - function getFixForImport(exportInfos, symbolName, + function getImportFixes(exportInfos, symbolName, /** undefined only for missing JSX namespace */ position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); - var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); + var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile, program.getCompilerOptions()); }); var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); var addToExisting = tryAddToExistingImport(existingImports, position !== undefined && isTypeOnlyPosition(sourceFile, position)); // Don't bother providing an action to add a new import if we can add to an existing one. @@ -137679,10 +142128,11 @@ var ts; return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration; var namespacePrefix = getNamespaceLikeImportText(declaration); - if (namespacePrefix) { + var moduleSpecifier = ts.tryGetModuleSpecifierFromDeclaration(declaration); + if (namespacePrefix && moduleSpecifier) { var moduleSymbol = getTargetModuleFromNamespaceLikeImport(declaration, checker); if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { - return { kind: 0 /* UseNamespace */, namespacePrefix: namespacePrefix, position: position }; + return { kind: 0 /* UseNamespace */, namespacePrefix: namespacePrefix, position: position, moduleSpecifier: moduleSpecifier }; } } }); @@ -137690,11 +142140,11 @@ var ts; function getTargetModuleFromNamespaceLikeImport(declaration, checker) { var _a; switch (declaration.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return checker.resolveExternalModuleName(declaration.initializer.arguments[0]); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return checker.getAliasedSymbol(declaration.symbol); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: var namespaceImport = ts.tryCast((_a = declaration.importClause) === null || _a === void 0 ? void 0 : _a.namedBindings, ts.isNamespaceImport); return namespaceImport && checker.getAliasedSymbol(namespaceImport.symbol); default: @@ -137704,11 +142154,11 @@ var ts; function getNamespaceLikeImportText(declaration) { var _a, _b, _c; switch (declaration.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return (_a = ts.tryCast(declaration.name, ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return declaration.name.text; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return (_c = ts.tryCast((_b = declaration.importClause) === null || _b === void 0 ? void 0 : _b.namedBindings, ts.isNamespaceImport)) === null || _c === void 0 ? void 0 : _c.name.text; default: return ts.Debug.assertNever(declaration); @@ -137717,31 +142167,38 @@ var ts; function tryAddToExistingImport(existingImports, canUseTypeOnlyImport) { return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind === 260 /* ImportEqualsDeclaration */) + if (declaration.kind === 261 /* ImportEqualsDeclaration */) return undefined; - if (declaration.kind === 249 /* VariableDeclaration */) { - return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 196 /* ObjectBindingPattern */ + if (declaration.kind === 250 /* VariableDeclaration */) { + return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 197 /* ObjectBindingPattern */ ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: declaration.name, importKind: importKind, moduleSpecifier: declaration.initializer.arguments[0].text, canUseTypeOnlyImport: false } : undefined; } var importClause = declaration.importClause; - if (!importClause) + if (!importClause || !ts.isStringLiteralLike(declaration.moduleSpecifier)) return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; - return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 264 /* NamedImports */) - ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.getText(), canUseTypeOnlyImport: canUseTypeOnlyImport } + // A type-only import may not have both a default and named imports, so the only way a name can + // be added to an existing type-only import is adding a named import to existing named bindings. + if (importClause.isTypeOnly && !(importKind === 0 /* Named */ && namedBindings)) + return undefined; + return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 265 /* NamedImports */) + ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.text, canUseTypeOnlyImport: canUseTypeOnlyImport } : undefined; }); } - function getExistingImportDeclarations(_a, checker, sourceFile) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + function getExistingImportDeclarations(_a, checker, importingFile, compilerOptions) { + var moduleSymbol = _a.moduleSymbol, exportKind = _a.exportKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + if (exportedSymbolIsTypeOnly && ts.isSourceFileJS(importingFile)) + return ts.emptyArray; + var importKind = getImportKind(importingFile, exportKind, compilerOptions); + return ts.mapDefined(importingFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); - if (ts.isRequireVariableDeclaration(i.parent, /*requireStringLiteralLikeArgument*/ true)) { + if (ts.isRequireVariableDeclaration(i.parent)) { return checker.resolveExternalModuleName(moduleSpecifier) === moduleSymbol ? { declaration: i.parent, importKind: importKind } : undefined; } - if (i.kind === 261 /* ImportDeclaration */ || i.kind === 260 /* ImportEqualsDeclaration */) { + if (i.kind === 262 /* ImportDeclaration */ || i.kind === 261 /* ImportEqualsDeclaration */) { return checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; } }); @@ -137774,45 +142231,29 @@ var ts; // 5. Literally nothing to go on return true; } - function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) { + function getNewImportFixes(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) { var isJs = ts.isSourceFileJS(sourceFile); var compilerOptions = program.getCompilerOptions(); - var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; - var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getTypeChecker(), compilerOptions, sourceFile, ts.createModuleSpecifierResolutionHost(program, host), preferences) + var moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); + return ts.flatMap(moduleSymbols, function (exportInfo) { + return ts.moduleSpecifiers.getModuleSpecifiers(exportInfo.moduleSymbol, program.getTypeChecker(), compilerOptions, sourceFile, moduleSpecifierResolutionHost, preferences) .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.checkDefined(position, "position should be defined") } - : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, useRequire: useRequire, typeOnly: preferTypeOnlyImport }; + return exportInfo.exportedSymbolIsTypeOnly && isJs && position !== undefined + ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: position, exportInfo: exportInfo } + : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: getImportKind(sourceFile, exportInfo.exportKind, compilerOptions), useRequire: useRequire, typeOnly: preferTypeOnlyImport, exportInfo: exportInfo }; }); }); - // Sort by presence in package.json, then shortest paths first - return ts.sort(choicesForEachExportingModule, function (a, b) { - var allowsImportingA = allowsImportingSpecifier(a.moduleSpecifier); - var allowsImportingB = allowsImportingSpecifier(b.moduleSpecifier); - if (allowsImportingA && !allowsImportingB) { - return -1; - } - if (allowsImportingB && !allowsImportingA) { - return 1; - } - return a.moduleSpecifier.length - b.moduleSpecifier.length; - }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport, useRequire); }); - return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences); + return existingDeclaration ? [existingDeclaration] : getNewImportFixes(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences); } function newImportInfoFromExistingSpecifier(_a, preferTypeOnlyImport, useRequire) { var declaration = _a.declaration, importKind = _a.importKind; - var moduleSpecifier = declaration.kind === 261 /* ImportDeclaration */ ? declaration.moduleSpecifier : - declaration.kind === 249 /* VariableDeclaration */ ? declaration.initializer.arguments[0] : - declaration.moduleReference.kind === 272 /* ExternalModuleReference */ ? declaration.moduleReference.expression : - undefined; - return moduleSpecifier && ts.isStringLiteral(moduleSpecifier) - ? { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier.text, importKind: importKind, typeOnly: preferTypeOnlyImport, useRequire: useRequire } + var moduleSpecifier = ts.tryGetModuleSpecifierFromDeclaration(declaration); + return moduleSpecifier + ? { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, typeOnly: preferTypeOnlyImport, useRequire: useRequire } : undefined; } function getFixesInfo(context, errorCode, pos, useAutoImportProvider) { @@ -137820,7 +142261,28 @@ var ts; var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ? getFixesInfoForUMDImport(context, symbolToken) : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider) : undefined; - return info && __assign(__assign({}, info), { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) }); + return info && __assign(__assign({}, info), { fixes: sortFixes(info.fixes, context.sourceFile, context.host) }); + } + function sortFixes(fixes, sourceFile, host) { + var allowsImportingSpecifier = ts.createPackageJsonImportFilter(sourceFile, host).allowsImportingSpecifier; + return ts.sort(fixes, function (a, b) { return ts.compareValues(a.kind, b.kind) || compareModuleSpecifiers(a, b, allowsImportingSpecifier); }); + } + function getBestFix(fixes, sourceFile, host) { + // These will always be placed first if available, and are better than other kinds + if (fixes[0].kind === 0 /* UseNamespace */ || fixes[0].kind === 2 /* AddToExisting */) { + return fixes[0]; + } + var allowsImportingSpecifier = ts.createPackageJsonImportFilter(sourceFile, host).allowsImportingSpecifier; + return fixes.reduce(function (best, fix) { + return compareModuleSpecifiers(fix, best, allowsImportingSpecifier) === -1 /* LessThan */ ? fix : best; + }); + } + function compareModuleSpecifiers(a, b, allowsImportingSpecifier) { + if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) { + return ts.compareBooleans(allowsImportingSpecifier(a.moduleSpecifier), allowsImportingSpecifier(b.moduleSpecifier)) + || ts.compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); + } + return 0 /* EqualTo */; } function getFixesInfoForUMDImport(_a, token) { var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences; @@ -137830,9 +142292,9 @@ var ts; return undefined; var symbol = checker.getAliasedSymbol(umdSymbol); var symbolName = umdSymbol.name; - var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(sourceFile, program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; + var exportInfos = [{ symbol: umdSymbol, moduleSymbol: symbol, exportKind: 3 /* UMD */, exportedSymbolIsTypeOnly: false, isFromPackageJson: false }]; var useRequire = shouldUseRequire(sourceFile, program); - var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, useRequire, program, sourceFile, host, preferences); + var fixes = getImportFixes(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, useRequire, program, sourceFile, host, preferences); return { fixes: fixes, symbolName: symbolName }; } function getUmdSymbol(token, checker) { @@ -137846,6 +142308,16 @@ var ts; ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 111551 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } + function getImportKind(importingFile, exportKind, compilerOptions) { + switch (exportKind) { + case 0 /* Named */: return 0 /* Named */; + case 1 /* Default */: return 1 /* Default */; + case 2 /* ExportEquals */: return getExportEqualsImportKind(importingFile, compilerOptions); + case 3 /* UMD */: return getUmdImportKind(importingFile, compilerOptions); + default: return ts.Debug.assertNever(exportKind); + } + } + codefix.getImportKind = getImportKind; function getUmdImportKind(importingFile, compilerOptions) { // Import a synthetic `default` if enabled. if (ts.getAllowSyntheticDefaultImports(compilerOptions)) { @@ -137875,22 +142347,22 @@ var ts; function getFixesInfoForNonUMDImport(_a, symbolToken, useAutoImportProvider) { var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences; var checker = program.getTypeChecker(); - var symbolName = getSymbolName(sourceFile, checker, symbolToken); + var compilerOptions = program.getCompilerOptions(); + var symbolName = getSymbolName(sourceFile, checker, symbolToken, compilerOptions); // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default" /* Default */, "'default' isn't a legal identifier and couldn't occur here"); - var compilerOptions = program.getCompilerOptions(); var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(symbolToken); var useRequire = shouldUseRequire(sourceFile, program); var exportInfos = getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host); var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfos.entries(), function (_a) { var _ = _a[0], exportInfos = _a[1]; - return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences); + return getImportFixes(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences); })); return { fixes: fixes, symbolName: symbolName }; } - function getSymbolName(sourceFile, checker, symbolToken) { + function getSymbolName(sourceFile, checker, symbolToken, compilerOptions) { var parent = symbolToken.parent; - if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken) { + if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken && compilerOptions.jsx !== 4 /* ReactJSX */ && compilerOptions.jsx !== 5 /* ReactJSXDev */) { var jsxNamespace = checker.getJsxNamespace(sourceFile); if (ts.isIntrinsicJsxName(symbolToken.text) || !checker.resolveName(jsxNamespace, parent, 111551 /* Value */, /*excludeGlobals*/ true)) { return jsxNamespace; @@ -137899,43 +142371,55 @@ var ts; return symbolToken.text; } // Returns a map from an exported symbol's ID to a list of every way it's (re-)exported. - function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, program, useAutoImportProvider, host) { + function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, fromFile, program, useAutoImportProvider, host) { + var _a; // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); - function addSymbol(moduleSymbol, exportedSymbol, importKind, checker) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); + var packageJsonFilter = ts.createPackageJsonImportFilter(fromFile, host); + var moduleSpecifierCache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); + var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { + return ts.createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); + }); + function addSymbol(moduleSymbol, toFile, exportedSymbol, exportKind, program, isFromPackageJson) { + var moduleSpecifierResolutionHost = getModuleSpecifierResolutionHost(isFromPackageJson); + if (toFile && ts.isImportableFile(program, fromFile, toFile, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) || + !toFile && packageJsonFilter.allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost)) { + var checker = program.getTypeChecker(); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { symbol: exportedSymbol, moduleSymbol: moduleSymbol, exportKind: exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker), isFromPackageJson: isFromPackageJson }); + } } - forEachExternalModuleToImportFrom(program, host, sourceFile, /*filterByPackageJson*/ true, useAutoImportProvider, function (moduleSymbol, _, program) { + forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, function (moduleSymbol, sourceFile, program, isFromPackageJson) { var checker = program.getTypeChecker(); cancellationToken.throwIfCancellationRequested(); var compilerOptions = program.getCompilerOptions(); - var defaultInfo = getDefaultLikeExportInfo(sourceFile, moduleSymbol, checker, compilerOptions); + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind, checker); + addSymbol(moduleSymbol, sourceFile, defaultInfo.symbol, defaultInfo.exportKind, program, isFromPackageJson); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */, checker); + addSymbol(moduleSymbol, sourceFile, exportSymbolWithIdenticalName, 0 /* Named */, program, isFromPackageJson); } }); return originalSymbolToExportInfos; } - function getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions) { - var exported = getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions); + 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); + var symbol = exported.symbol, exportKind = exported.exportKind; + var info = getDefaultExportInfoWorker(symbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, exportKind: exportKind }, info); } - function getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions) { + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) + return { symbol: exportEquals, exportKind: 2 /* ExportEquals */ }; 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: getExportEqualsImportKind(importingFile, compilerOptions) }; + return { symbol: defaultExport, exportKind: 1 /* Default */ }; } function getExportEqualsImportKind(importingFile, compilerOptions) { var allowSyntheticDefaults = ts.getAllowSyntheticDefaultImports(compilerOptions); @@ -137954,7 +142438,8 @@ var ts; // on how to handle it. for (var _i = 0, _a = importingFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - if (ts.isImportEqualsDeclaration(statement)) { + // `import foo` parses as an ImportEqualsDeclaration even though it could be an ImportDeclaration + if (ts.isImportEqualsDeclaration(statement) && !ts.nodeIsMissing(statement.moduleReference)) { return 3 /* CommonJS */; } } @@ -137962,7 +142447,7 @@ var ts; // allowSyntheticDefaultImports/esModuleInterop is enabled. return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */; } - function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { + function getDefaultExportInfoWorker(defaultExport, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -137976,21 +142461,20 @@ var ts; // but we can still offer completions for it. // - `aliased.parent` will be undefined if the module is exporting `globalThis.something`, // or another expression that resolves to a global. - return getDefaultExportInfoWorker(aliased, aliased.parent, checker, compilerOptions); + return getDefaultExportInfoWorker(aliased, checker, compilerOptions); } } if (defaultExport.escapedName !== "default" /* Default */ && defaultExport.escapedName !== "export=" /* ExportEquals */) { return { symbolForMeaning: defaultExport, name: defaultExport.getName() }; } - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; + return { symbolForMeaning: defaultExport, name: ts.getNameForExportedSymbol(defaultExport, compilerOptions.target) }; } function getNameForExportDefault(symbol) { return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { + var _a; if (ts.isExportAssignment(declaration)) { - if (ts.isIdentifier(declaration.expression)) { - return declaration.expression.text; - } + return (_a = ts.tryCast(ts.skipOuterExpressions(declaration.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text; } else if (ts.isExportSpecifier(declaration)) { ts.Debug.assert(declaration.name.text === "default" /* Default */, "Expected the specifier to be a default export"); @@ -138033,7 +142517,7 @@ var ts; } } function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, canUseTypeOnlyImport) { - if (clause.kind === 196 /* ObjectBindingPattern */) { + if (clause.kind === 197 /* ObjectBindingPattern */) { if (defaultImport) { addElementToBindingPattern(clause, defaultImport, "default"); } @@ -138160,48 +142644,23 @@ var ts; var declarations = _a.declarations; return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); } - function forEachExternalModuleToImportFrom(program, host, from, filterByPackageJson, useAutoImportProvider, cb) { + function forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, cb) { var _a, _b; - forEachExternalModuleToImportFromInProgram(program, host, from, filterByPackageJson, function (module, file) { return cb(module, file, program, /*isFromPackageJson*/ false); }); + forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), function (module, file) { return cb(module, file, program, /*isFromPackageJson*/ false); }); var autoImportProvider = useAutoImportProvider && ((_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host)); if (autoImportProvider) { var start = ts.timestamp(); - forEachExternalModuleToImportFromInProgram(autoImportProvider, host, from, filterByPackageJson, function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); + forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); (_b = host.log) === null || _b === void 0 ? void 0 : _b.call(host, "forEachExternalModuleToImportFrom autoImportProvider: " + (ts.timestamp() - start)); } } codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; - function forEachExternalModuleToImportFromInProgram(program, host, from, filterByPackageJson, cb) { - var _a; - var filteredCount = 0; - var moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); - var packageJson = filterByPackageJson && createAutoImportFilter(from, program, host, moduleSpecifierResolutionHost); - forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), function (module, sourceFile) { - if (sourceFile === undefined) { - if (!packageJson || packageJson.allowsImportingAmbientModule(module)) { - cb(module, sourceFile); - } - else if (packageJson) { - filteredCount++; - } - } - else if (sourceFile && - sourceFile !== from && - isImportableFile(program, from, sourceFile, moduleSpecifierResolutionHost)) { - if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile)) { - cb(module, sourceFile); - } - else if (packageJson) { - filteredCount++; - } - } - }); - (_a = host.log) === null || _a === void 0 ? void 0 : _a.call(host, "forEachExternalModuleToImportFrom: filtered out " + filteredCount + " modules by package.json contents"); - } function forEachExternalModule(checker, allSourceFiles, cb) { for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { var ambient = _a[_i]; - cb(ambient, /*sourceFile*/ undefined); + if (!ts.stringContains(ambient.name, "*")) { + cb(ambient, /*sourceFile*/ undefined); + } } for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { var sourceFile = allSourceFiles_1[_b]; @@ -138210,31 +142669,6 @@ var ts; } } } - function isImportableFile(program, from, to, moduleSpecifierResolutionHost) { - var _a; - var getCanonicalFileName = ts.hostGetCanonicalFileName(moduleSpecifierResolutionHost); - var globalTypingsCache = (_a = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation) === null || _a === void 0 ? void 0 : _a.call(moduleSpecifierResolutionHost); - return !!ts.moduleSpecifiers.forEachFileNameOfModule(from.fileName, to.fileName, moduleSpecifierResolutionHost, - /*preferSymlinks*/ false, function (toPath) { - var toFile = program.getSourceFile(toPath); - // Determine to import using toPath only if toPath is what we were looking at - // or there doesnt exist the file in the program by the symlink - return (toFile === to || !toFile) && - isImportablePath(from.fileName, toPath, getCanonicalFileName, globalTypingsCache); - }); - } - /** - * Don't include something from a `node_modules` that isn't actually reachable by a global import. - * A relative import to node_modules is usually a bad idea. - */ - function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) { - // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. - var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); - var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules)); - return toNodeModulesParent === undefined - || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) - || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); - } function moduleSymbolToValidIdentifier(moduleSymbol, target) { return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); } @@ -138266,99 +142700,122 @@ var ts; return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; } codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; - function createAutoImportFilter(fromFile, program, host, moduleSpecifierResolutionHost) { - if (moduleSpecifierResolutionHost === void 0) { moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); } - var packageJsons = ((host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName)) || ts.getPackageJsonsVisibleToFile(fromFile.fileName, host)).filter(function (p) { return p.parseable; }); - var usesNodeCoreModules; - return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier, moduleSpecifierResolutionHost: moduleSpecifierResolutionHost }; - function moduleSpecifierIsCoveredByPackageJson(specifier) { - var packageName = getNodeModuleRootSpecifier(specifier); - for (var _i = 0, packageJsons_1 = packageJsons; _i < packageJsons_1.length; _i++) { - var packageJson = packageJsons_1[_i]; - if (packageJson.has(packageName) || packageJson.has(ts.getTypesPackageName(packageName))) { - return true; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var _a; + var fixName = "fixOverrideModifier"; + var fixAddOverrideId = "fixAddOverrideModifier"; + var fixRemoveOverrideId = "fixRemoveOverrideModifier"; + var errorCodes = [ + ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code, + ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code, + ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code, + ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code, + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code + ]; + var errorCodeFixIdMap = (_a = {}, + _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code] = [ + ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Add_all_missing_override_modifiers, + ], + _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code] = [ + ts.Diagnostics.Remove_override_modifier, fixRemoveOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers + ], + _a[ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code] = [ + ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Add_all_missing_override_modifiers, + ], + _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code] = [ + ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers + ], + _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code] = [ + ts.Diagnostics.Remove_override_modifier, fixRemoveOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers + ], + _a); + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var errorCode = context.errorCode, span = context.span, sourceFile = context.sourceFile; + var info = errorCodeFixIdMap[errorCode]; + if (!info) + return ts.emptyArray; + var descriptions = info[0], fixId = info[1], fixAllDescriptions = info[2]; + if (ts.isSourceFileJS(sourceFile)) + return ts.emptyArray; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { return dispatchChanges(changes, context, errorCode, span.start); }); + return [ + codefix.createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId, fixAllDescriptions) + ]; + }, + fixIds: [fixName, fixAddOverrideId, fixRemoveOverrideId], + getAllCodeActions: function (context) { + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var code = diag.code, start = diag.start, file = diag.file; + var info = errorCodeFixIdMap[code]; + if (!info || info[1] !== context.fixId || ts.isSourceFileJS(file)) { + return; } - } - return false; - } - function allowsImportingAmbientModule(moduleSymbol) { - if (!packageJsons.length) { - return true; - } - var declaringSourceFile = moduleSymbol.valueDeclaration.getSourceFile(); - var declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName); - if (typeof declaringNodeModuleName === "undefined") { - return true; - } - var declaredModuleSpecifier = ts.stripQuotes(moduleSymbol.getName()); - if (isAllowedCoreNodeModulesImport(declaredModuleSpecifier)) { - return true; - } - return moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName) - || moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier); - } - function allowsImportingSourceFile(sourceFile) { - if (!packageJsons.length) { - return true; - } - var moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName); - if (!moduleSpecifier) { - return true; - } - return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); + dispatchChanges(changes, context, code, start); + }); } - /** - * Use for a specific module specifier that has already been resolved. - * Use `allowsImportingAmbientModule` or `allowsImportingSourceFile` to resolve - * the best module specifier for a given module _and_ determine if it’s importable. - */ - function allowsImportingSpecifier(moduleSpecifier) { - if (!packageJsons.length || isAllowedCoreNodeModulesImport(moduleSpecifier)) { - return true; - } - if (ts.pathIsRelative(moduleSpecifier) || ts.isRootedDiskPath(moduleSpecifier)) { + }); + function dispatchChanges(changeTracker, context, errorCode, pos) { + switch (errorCode) { + case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code: + case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code: + case ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code: + return doAddOverrideModifierChange(changeTracker, context.sourceFile, pos); + case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code: + case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code: + return doRemoveOverrideModifierChange(changeTracker, context.sourceFile, pos); + default: + ts.Debug.fail("Unexpected error code: " + errorCode); + } + } + function doAddOverrideModifierChange(changeTracker, sourceFile, pos) { + var classElement = findContainerClassElementLike(sourceFile, pos); + var modifiers = classElement.modifiers || ts.emptyArray; + var staticModifier = ts.find(modifiers, ts.isStaticModifier); + var accessibilityModifier = ts.find(modifiers, function (m) { return ts.isAccessibilityModifier(m.kind); }); + var modifierPos = staticModifier ? staticModifier.end : + accessibilityModifier ? accessibilityModifier.end : + classElement.decorators ? ts.skipTrivia(sourceFile.text, classElement.decorators.end) : classElement.getStart(sourceFile); + var options = accessibilityModifier || staticModifier ? { prefix: " " } : { suffix: " " }; + changeTracker.insertModifierAt(sourceFile, modifierPos, 156 /* OverrideKeyword */, options); + } + function doRemoveOverrideModifierChange(changeTracker, sourceFile, pos) { + var classElement = findContainerClassElementLike(sourceFile, pos); + var overrideModifier = classElement.modifiers && ts.find(classElement.modifiers, function (modifier) { return modifier.kind === 156 /* OverrideKeyword */; }); + ts.Debug.assertIsDefined(overrideModifier); + changeTracker.deleteModifier(sourceFile, overrideModifier); + } + function isClassElementLikeHasJSDoc(node) { + switch (node.kind) { + case 167 /* Constructor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return true; - } - return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); - } - function isAllowedCoreNodeModulesImport(moduleSpecifier) { - // If we’re in JavaScript, it can be difficult to tell whether the user wants to import - // from Node core modules or not. We can start by seeing if the user is actually using - // any node core modules, as opposed to simply having @types/node accidentally as a - // dependency of a dependency. - if (ts.isSourceFileJS(fromFile) && ts.JsTyping.nodeCoreModules.has(moduleSpecifier)) { - if (usesNodeCoreModules === undefined) { - usesNodeCoreModules = ts.consumesNodeCoreModules(fromFile); - } - if (usesNodeCoreModules) { - return true; - } - } - return false; - } - function getNodeModulesPackageNameFromFileName(importedFileName) { - if (!ts.stringContains(importedFileName, "node_modules")) { - return undefined; - } - var specifier = ts.moduleSpecifiers.getNodeModulesPackageName(host.getCompilationSettings(), fromFile.path, importedFileName, moduleSpecifierResolutionHost); - if (!specifier) { - return undefined; - } - // Paths here are not node_modules, so we don’t care about them; - // returning anything will trigger a lookup in package.json. - if (!ts.pathIsRelative(specifier) && !ts.isRootedDiskPath(specifier)) { - return getNodeModuleRootSpecifier(specifier); - } - } - function getNodeModuleRootSpecifier(fullSpecifier) { - var components = ts.getPathComponents(ts.getPackageNameFromTypesPackageName(fullSpecifier)).slice(1); - // Scoped packages - if (ts.startsWith(components[0], "@")) { - return components[0] + "/" + components[1]; - } - return components[0]; + case 161 /* Parameter */: + return ts.isParameterPropertyDeclaration(node, node.parent); + default: + return false; } } + function findContainerClassElementLike(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var classElement = ts.findAncestor(token, function (node) { + if (ts.isClassLike(node)) + return "quit"; + return isClassElementLikeHasJSDoc(node); + }); + ts.Debug.assert(classElement && isClassElementLikeHasJSDoc(classElement)); + return classElement; + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -138474,7 +142931,7 @@ var ts; }); function getNamedTupleMember(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - return ts.findAncestor(token, function (t) { return t.kind === 192 /* NamedTupleMember */; }); + return ts.findAncestor(token, function (t) { return t.kind === 193 /* NamedTupleMember */; }); } function doChange(changes, sourceFile, namedTupleMember) { if (!namedTupleMember) { @@ -138483,11 +142940,11 @@ var ts; var unwrappedType = namedTupleMember.type; var sawOptional = false; var sawRest = false; - while (unwrappedType.kind === 180 /* OptionalType */ || unwrappedType.kind === 181 /* RestType */ || unwrappedType.kind === 186 /* ParenthesizedType */) { - if (unwrappedType.kind === 180 /* OptionalType */) { + while (unwrappedType.kind === 181 /* OptionalType */ || unwrappedType.kind === 182 /* RestType */ || unwrappedType.kind === 187 /* ParenthesizedType */) { + if (unwrappedType.kind === 181 /* OptionalType */) { sawOptional = true; } - else if (unwrappedType.kind === 181 /* RestType */) { + else if (unwrappedType.kind === 182 /* RestType */) { sawRest = true; } unwrappedType = unwrappedType.type; @@ -138551,7 +143008,7 @@ var ts; var checker = context.program.getTypeChecker(); var suggestedSymbol; if (ts.isPropertyAccessExpression(parent) && parent.name === node) { - ts.Debug.assert(ts.isIdentifierOrPrivateIdentifier(node), "Expected an identifier for spelling (property access)"); + ts.Debug.assert(ts.isMemberName(node), "Expected an identifier for spelling (property access)"); var containingType = checker.getTypeAtLocation(parent.expression); if (parent.flags & 32 /* OptionalChain */) { containingType = checker.getNonNullableType(containingType); @@ -138590,7 +143047,7 @@ var ts; var suggestion = ts.symbolName(suggestedSymbol); if (!ts.isIdentifierText(suggestion, target) && ts.isPropertyAccessExpression(node.parent)) { var valDecl = suggestedSymbol.valueDeclaration; - if (ts.isNamedDeclaration(valDecl) && ts.isPrivateIdentifier(valDecl.name)) { + if (valDecl && ts.isNamedDeclaration(valDecl) && ts.isPrivateIdentifier(valDecl.name)) { changes.replaceNode(sourceFile, node, ts.factory.createIdentifier(suggestion)); } else { @@ -138787,19 +143244,19 @@ var ts; } function getVariableLikeInitializer(declaration) { switch (declaration.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: - case 163 /* PropertyDeclaration */: - case 288 /* PropertyAssignment */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: + case 164 /* PropertyDeclaration */: + case 289 /* PropertyAssignment */: return declaration.initializer; - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return declaration.initializer && (ts.isJsxExpression(declaration.initializer) ? declaration.initializer.expression : undefined); - case 289 /* ShorthandPropertyAssignment */: - case 162 /* PropertySignature */: - case 291 /* EnumMember */: - case 333 /* JSDocPropertyTag */: - case 326 /* JSDocParameterTag */: + case 290 /* ShorthandPropertyAssignment */: + case 163 /* PropertySignature */: + case 292 /* EnumMember */: + case 337 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: return undefined; } } @@ -138900,7 +143357,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = codefix.getAllSupers(classDeclaration, checker); - var _loop_13 = function (info) { + var _loop_14 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -138925,9 +143382,9 @@ var ts; } } }; - for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { - var info = infos_1[_i]; - _loop_13(info); + for (var _i = 0, infos_2 = infos; _i < infos_2.length; _i++) { + var info = infos_2[_i]; + _loop_14(info); } }); })); @@ -139017,7 +143474,7 @@ var ts; function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, token, makeStatic) { var tokenName = token.text; if (makeStatic) { - if (classDeclaration.kind === 221 /* ClassExpression */) { + if (classDeclaration.kind === 222 /* ClassExpression */) { return; } var className = classDeclaration.name.getText(); @@ -139069,15 +143526,15 @@ var ts; } function getTypeNode(checker, classDeclaration, token) { var typeNode; - if (token.parent.parent.kind === 216 /* BinaryExpression */) { + if (token.parent.parent.kind === 217 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration, /*flags*/ undefined); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration, 1 /* NoTruncation */); } else { var contextualType = checker.getContextualType(token.parent); - typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined) : undefined; + typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, 1 /* NoTruncation */) : undefined; } return typeNode || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } @@ -139141,7 +143598,7 @@ var ts; } function addMethodDeclaration(context, changes, callExpression, name, modifierFlags, parentDeclaration, sourceFile) { var importAdder = codefix.createImportAdder(sourceFile, context.program, context.preferences, context.host); - var methodDeclaration = codefix.createSignatureDeclarationFromCallExpression(165 /* MethodDeclaration */, context, importAdder, callExpression, name, modifierFlags, parentDeclaration); + var methodDeclaration = codefix.createSignatureDeclarationFromCallExpression(166 /* MethodDeclaration */, context, importAdder, callExpression, name, modifierFlags, parentDeclaration); var containingMethodDeclaration = ts.findAncestor(callExpression, function (n) { return ts.isMethodDeclaration(n) || ts.isConstructorDeclaration(n); }); if (containingMethodDeclaration && containingMethodDeclaration.parent === parentDeclaration) { changes.insertNodeAfter(sourceFile, containingMethodDeclaration, methodDeclaration); @@ -139170,7 +143627,7 @@ var ts; } function addFunctionDeclaration(changes, context, info) { var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); - var functionDeclaration = codefix.createSignatureDeclarationFromCallExpression(251 /* FunctionDeclaration */, context, importAdder, info.call, info.token, info.modifierFlags, info.parentDeclaration); + var functionDeclaration = codefix.createSignatureDeclarationFromCallExpression(252 /* FunctionDeclaration */, context, importAdder, info.call, ts.idText(info.token), info.modifierFlags, info.parentDeclaration); changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -139257,7 +143714,10 @@ var ts; return { type: "install package", file: fileName, packageName: packageName }; } function tryGetImportedPackageName(sourceFile, pos) { - var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; + var moduleSpecifierText = ts.tryCast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral); + if (!moduleSpecifierText) + return undefined; + var moduleName = moduleSpecifierText.text; var packageName = ts.parsePackageName(moduleName).packageName; return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; } @@ -139487,7 +143947,10 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code], + errorCodes: [ + ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code, + ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code, + ], getCodeActions: function (context) { var compilerOptions = context.program.getCompilerOptions(); var configFile = compilerOptions.configFile; @@ -139858,7 +144321,7 @@ var ts; } function isImport(token) { return token.kind === 99 /* ImportKeyword */ - || token.kind === 78 /* Identifier */ && (token.parent.kind === 265 /* ImportSpecifier */ || token.parent.kind === 262 /* ImportClause */); + || token.kind === 78 /* Identifier */ && (token.parent.kind === 266 /* ImportSpecifier */ || token.parent.kind === 263 /* ImportClause */); } /** Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. */ function tryGetFullImport(token) { @@ -139868,7 +144331,7 @@ var ts; return ts.isVariableDeclarationList(token.parent) && ts.first(token.parent.getChildren(sourceFile)) === token; } function deleteEntireVariableStatement(changes, sourceFile, node) { - changes.delete(sourceFile, node.parent.kind === 232 /* VariableStatement */ ? node.parent : node); + changes.delete(sourceFile, node.parent.kind === 233 /* VariableStatement */ ? node.parent : node); } function deleteDestructuringElements(changes, sourceFile, node) { ts.forEach(node.elements, function (n) { return changes.delete(sourceFile, n); }); @@ -139893,14 +144356,14 @@ var ts; } function canPrefix(token) { switch (token.parent.kind) { - case 160 /* Parameter */: - case 159 /* TypeParameter */: + case 161 /* Parameter */: + case 160 /* TypeParameter */: return true; - case 249 /* VariableDeclaration */: { + case 250 /* VariableDeclaration */: { var varDecl = token.parent; switch (varDecl.parent.parent.kind) { - case 239 /* ForOfStatement */: - case 238 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 239 /* ForInStatement */: return true; } } @@ -139924,8 +144387,10 @@ var ts; if (ts.isParameter(parent)) { tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, program, cancellationToken, isFixAll); } - else if (!isFixAll || !(ts.isIdentifier(token) && ts.FindAllReferences.Core.isSymbolReferencedInFile(token, checker, sourceFile))) { - changes.delete(sourceFile, ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent); + else if (!(isFixAll && ts.isIdentifier(token) && ts.FindAllReferences.Core.isSymbolReferencedInFile(token, checker, sourceFile))) { + var node = ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent; + ts.Debug.assert(node !== sourceFile, "should not delete whole source file"); + changes.delete(sourceFile, node); } } function tryDeleteParameter(changes, sourceFile, parameter, checker, sourceFiles, program, cancellationToken, isFixAll) { @@ -139948,8 +144413,8 @@ var ts; function mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll) { var parent = parameter.parent; switch (parent.kind) { - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: var index = parent.parameters.indexOf(parameter); var referent = ts.isMethodDeclaration(parent) ? parent.name : parent; var entries = ts.FindAllReferences.Core.getReferencedSymbolsForNode(parent.pos, referent, program, sourceFiles, cancellationToken); @@ -139979,17 +144444,17 @@ var ts; } } return true; - case 251 /* FunctionDeclaration */: { + case 252 /* FunctionDeclaration */: { if (parent.name && isCallbackLike(checker, sourceFile, parent.name)) { return isLastParameter(parent, parameter, isFixAll); } return true; } - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused. return isLastParameter(parent, parameter, isFixAll); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: // Setter must have a parameter return false; default: @@ -140047,7 +144512,7 @@ var ts; var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { switch (container.kind) { - case 234 /* IfStatement */: + case 235 /* IfStatement */: if (container.elseStatement) { if (ts.isBlock(statement.parent)) { break; @@ -140058,8 +144523,8 @@ var ts; return; } // falls through - case 236 /* WhileStatement */: - case 237 /* ForStatement */: + case 237 /* WhileStatement */: + case 238 /* ForStatement */: changes.delete(sourceFile, container); return; } @@ -140132,7 +144597,7 @@ var ts; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; - if (typeNode.kind === 305 /* JSDocNullableType */) { + if (typeNode.kind === 306 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); @@ -140152,7 +144617,7 @@ var ts; if (!info) return; var typeNode = info.typeNode, type = info.type; - var fixedType = typeNode.kind === 305 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; + var fixedType = typeNode.kind === 306 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; doChange(changes, sourceFile, typeNode, fixedType, checker); }); } @@ -140169,22 +144634,22 @@ var ts; // NOTE: Some locations are not handled yet: // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments switch (node.kind) { - case 224 /* AsExpression */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 251 /* FunctionDeclaration */: - case 167 /* GetAccessor */: - case 171 /* IndexSignature */: - case 190 /* MappedType */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 168 /* SetAccessor */: - case 254 /* TypeAliasDeclaration */: - case 206 /* TypeAssertionExpression */: - case 249 /* VariableDeclaration */: + case 225 /* AsExpression */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 252 /* FunctionDeclaration */: + case 168 /* GetAccessor */: + case 172 /* IndexSignature */: + case 191 /* MappedType */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 169 /* SetAccessor */: + case 255 /* TypeAliasDeclaration */: + case 207 /* TypeAssertionExpression */: + case 250 /* VariableDeclaration */: return true; default: return false; @@ -140199,7 +144664,7 @@ var ts; (function (codefix) { var fixId = "fixMissingCallParentheses"; var errorCodes = [ - ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead.code, + ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -140245,7 +144710,7 @@ var ts; var fixId = "fixAwaitInSyncFunction"; var errorCodes = [ ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, - ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -140286,14 +144751,14 @@ var ts; } var insertBefore; switch (containingFunction.kind) { - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: insertBefore = containingFunction.name; break; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: insertBefore = ts.findChildOfKind(containingFunction, 97 /* FunctionKeyword */, sourceFile); break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); break; default: @@ -140492,7 +144957,7 @@ var ts; var typeNode = ts.getTypeNodeIfAccessible(type, parent, program, host); if (typeNode) { // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags - var typeTag = ts.factory.createJSDocTypeTag(/*tagName*/ undefined, ts.factory.createJSDocTypeExpression(typeNode), /*comment*/ ""); + var typeTag = ts.factory.createJSDocTypeTag(/*tagName*/ undefined, ts.factory.createJSDocTypeExpression(typeNode), /*comment*/ undefined); addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]); } importAdder.writeFixes(changes); @@ -140626,13 +145091,13 @@ var ts; function annotate(changes, importAdder, sourceFile, declaration, type, program, host) { var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { - if (ts.isInJSFile(sourceFile) && declaration.kind !== 162 /* PropertySignature */) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 163 /* PropertySignature */) { var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration; if (!parent) { return; } var typeExpression = ts.factory.createJSDocTypeExpression(typeNode); - var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.factory.createJSDocReturnTag(/*tagName*/ undefined, typeExpression, "") : ts.factory.createJSDocTypeTag(/*tagName*/ undefined, typeExpression, ""); + var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.factory.createJSDocReturnTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined) : ts.factory.createJSDocTypeTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined); addJSDocTags(changes, sourceFile, parent, [typeTag]); } else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, ts.getEmitScriptTarget(program.getCompilerOptions()))) { @@ -140687,13 +145152,13 @@ var ts; else { var paramTags = ts.map(inferences, function (_a) { var name = _a.name, typeNode = _a.typeNode, isOptional = _a.isOptional; - return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!isOptional, ts.factory.createJSDocTypeExpression(typeNode), /* isNameFirst */ false, ""); + return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!isOptional, ts.factory.createJSDocTypeExpression(typeNode), /* isNameFirst */ false, /*comment*/ undefined); }); addJSDocTags(changes, sourceFile, signature, paramTags); } } function addJSDocTags(changes, sourceFile, parent, newTags) { - var comments = ts.mapDefined(parent.jsDoc, function (j) { return j.comment; }); + var comments = ts.flatMap(parent.jsDoc, function (j) { return typeof j.comment === "string" ? ts.factory.createJSDocText(j.comment) : j.comment; }); var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }); var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) { var merged = tryMergeJsdocTags(tag, newTag); @@ -140701,15 +145166,15 @@ var ts; oldTags[i] = merged; return !!merged; }); }); - var tag = ts.factory.createJSDocComment(comments.join("\n"), ts.factory.createNodeArray(__spreadArray(__spreadArray([], (oldTags || ts.emptyArray)), unmergedNewTags))); - var jsDocNode = parent.kind === 209 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent; + var tag = ts.factory.createJSDocComment(ts.factory.createNodeArray(ts.intersperse(comments, ts.factory.createJSDocText("\n"))), ts.factory.createNodeArray(__spreadArray(__spreadArray([], (oldTags || ts.emptyArray)), unmergedNewTags))); + var jsDocNode = parent.kind === 210 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent; jsDocNode.jsDoc = parent.jsDoc; jsDocNode.jsDocCache = parent.jsDocCache; changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag); } codefix.addJSDocTags = addJSDocTags; function getJsDocNodeForArrowFunction(signature) { - if (signature.parent.kind === 163 /* PropertyDeclaration */) { + if (signature.parent.kind === 164 /* PropertyDeclaration */) { return signature.parent; } return signature.parent.parent; @@ -140719,14 +145184,14 @@ var ts; return undefined; } switch (oldTag.kind) { - case 326 /* JSDocParameterTag */: { + case 330 /* JSDocParameterTag */: { var oldParam = oldTag; var newParam = newTag; return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText ? ts.factory.createJSDocParameterTag(/*tagName*/ undefined, newParam.name, /*isBracketed*/ false, newParam.typeExpression, newParam.isNameFirst, oldParam.comment) : undefined; } - case 327 /* JSDocReturnTag */: + case 331 /* JSDocReturnTag */: return ts.factory.createJSDocReturnTag(/*tagName*/ undefined, newTag.typeExpression, oldTag.comment); } } @@ -140751,19 +145216,19 @@ var ts; function getFunctionReferences(containingFunction, sourceFile, program, cancellationToken) { var searchToken; switch (containingFunction.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: searchToken = ts.findChildOfKind(containingFunction, 132 /* ConstructorKeyword */, sourceFile); break; - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: var parent = containingFunction.parent; searchToken = (ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent)) && ts.isIdentifier(parent.name) ? parent.name : containingFunction.name; break; - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: searchToken = containingFunction.name; break; } @@ -140905,24 +145370,24 @@ var ts; node = node.parent; } switch (node.parent.kind) { - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: inferTypeFromExpressionStatement(node, usage); break; - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: usage.isNumber = true; break; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: inferTypeFromPrefixUnaryExpression(node.parent, usage); break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: inferTypeFromBinaryExpression(node, node.parent, usage); break; - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: inferTypeFromSwitchStatementLabel(node.parent, usage); break; - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: if (node.parent.expression === node) { inferTypeFromCallExpression(node.parent, usage); } @@ -140930,20 +145395,20 @@ var ts; inferTypeFromContextualType(node, usage); } break; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: inferTypeFromPropertyAccessExpression(node.parent, usage); break; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: inferTypeFromPropertyElementExpression(node.parent, node, usage); break; - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: inferTypeFromPropertyAssignment(node.parent, usage); break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: inferTypeFromPropertyDeclaration(node.parent, usage); break; - case 249 /* VariableDeclaration */: { + case 250 /* VariableDeclaration */: { var _a = node.parent, name = _a.name, initializer = _a.initializer; if (node === name) { if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. @@ -141065,7 +145530,7 @@ var ts; case 56 /* BarBarToken */: case 60 /* QuestionQuestionToken */: if (node === parent.left && - (node.parent.parent.kind === 249 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + (node.parent.parent.kind === 250 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { // var x = x || {}; // TODO: use getFalsyflagsOfType addCandidateType(usage, checker.getTypeAtLocation(parent.right)); @@ -141093,7 +145558,7 @@ var ts; } } calculateUsageOfNode(parent, call.return_); - if (parent.kind === 203 /* CallExpression */) { + if (parent.kind === 204 /* CallExpression */) { (usage.calls || (usage.calls = [])).push(call); } else { @@ -141196,7 +145661,7 @@ var ts; var anon = anons_1[_i]; for (var _a = 0, _b = checker.getPropertiesOfType(anon); _a < _b.length; _a++) { var p = _b[_a]; - props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration)); + props.add(p.name, p.valueDeclaration ? checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration) : checker.getAnyType()); } calls.push.apply(calls, checker.getSignaturesOfType(anon, 0 /* Call */)); constructs.push.apply(constructs, checker.getSignaturesOfType(anon, 1 /* Construct */)); @@ -141337,12 +145802,13 @@ var ts; if (!usageParam) { break; } - var genericParamType = checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration); + var genericParamType = genericParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration) : checker.getAnyType(); var elementType = isRest && checker.getElementTypeOfArrayType(genericParamType); if (elementType) { genericParamType = elementType; } - var targetType = usageParam.type || checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration); + var targetType = usageParam.type + || (usageParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration) : checker.getAnyType()); types.push.apply(types, inferTypeParameters(genericParamType, targetType, typeParameter)); } var genericReturn = checker.getReturnTypeOfSignature(genericSig); @@ -141356,7 +145822,7 @@ var ts; function getSignatureFromCalls(calls) { var parameters = []; var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; })); - var _loop_14 = function (i) { + var _loop_15 = function (i) { var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); })); if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) { @@ -141365,7 +145831,7 @@ var ts; parameters.push(symbol); }; for (var i = 0; i < length; i++) { - _loop_14(i); + _loop_15(i); } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); // TODO: GH#18217 @@ -141536,8 +146002,8 @@ var ts; var ambient = !!(enclosingDeclaration.flags & 8388608 /* Ambient */); var quotePreference = ts.getQuotePreference(sourceFile, preferences); switch (declaration.kind) { - case 162 /* PropertySignature */: - case 163 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 164 /* PropertyDeclaration */: var flags = quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : undefined; var typeNode = checker.typeToTypeNode(type, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); if (importAdder) { @@ -141551,8 +146017,8 @@ var ts; /*decorators*/ undefined, modifiers, name, optional ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: { + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: { var typeNode_1 = checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); var allAccessors = ts.getAllAccessorDeclarations(declarations, declaration); var orderedAccessors = allAccessors.secondAccessor @@ -141581,8 +146047,8 @@ var ts; } break; } - case 164 /* MethodSignature */: - case 165 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 166 /* MethodDeclaration */: // The signature for the implementation appears as an entry in `signatures` iff // there is only one signature. // If there are overloads and an implementation signature, it appears as an @@ -141612,7 +146078,7 @@ var ts; } else { ts.Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count"); - addClassElement(createMethodImplementingSignatures(signatures, name, optional, modifiers, quotePreference)); + addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference)); } } break; @@ -141628,7 +146094,7 @@ var ts; var checker = program.getTypeChecker(); var scriptTarget = ts.getEmitScriptTarget(program.getCompilerOptions()); var flags = 1 /* NoTruncation */ | 1073741824 /* NoUndefinedOptionalParameterType */ | 256 /* SuppressAnyReturnType */ | (quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0); - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 165 /* MethodDeclaration */, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 166 /* MethodDeclaration */, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); if (!signatureDeclaration) { return undefined; } @@ -141712,7 +146178,7 @@ var ts; var type = isJs || contextualType === undefined ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker); - if (kind === 165 /* MethodDeclaration */) { + if (kind === 166 /* MethodDeclaration */) { return ts.factory.createMethodDeclaration( /*decorators*/ undefined, modifiers, asteriskToken, name, /*questionToken*/ undefined, typeParameters, parameters, type, ts.isInterfaceDeclaration(contextNode) ? undefined : createStubbedMethodBody(quotePreference)); @@ -141748,7 +146214,7 @@ var ts; } return parameters; } - function createMethodImplementingSignatures(signatures, name, optional, modifiers, quotePreference) { + function createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference) { /** This is *a* signature with the maximal number of arguments, * such that if there is a "maximal" signature without rest arguments, * this is one of them. @@ -141779,8 +146245,13 @@ var ts; parameters.push(restParameter); } return createStubbedMethod(modifiers, name, optional, - /*typeParameters*/ undefined, parameters, - /*returnType*/ undefined, quotePreference); + /*typeParameters*/ undefined, parameters, getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), quotePreference); + } + function getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration) { + if (ts.length(signatures)) { + var type = checker.getUnionType(ts.map(signatures, checker.getReturnTypeOfSignature)); + return checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); + } } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference) { return ts.factory.createMethodDeclaration( @@ -141907,13 +146378,13 @@ var ts; if (ts.isClassLike(container)) { var modifierFlags = ts.getEffectiveModifierFlags(declaration); if (ts.isSourceFileJS(file)) { - var modifiers = createModifiers(modifierFlags); + var modifiers = ts.createModifiers(modifierFlags); accessorModifiers = modifiers; fieldModifiers = modifiers; } else { - accessorModifiers = createModifiers(prepareModifierFlagsForAccessor(modifierFlags)); - fieldModifiers = createModifiers(prepareModifierFlagsForField(modifierFlags)); + accessorModifiers = ts.createModifiers(prepareModifierFlagsForAccessor(modifierFlags)); + fieldModifiers = ts.createModifiers(prepareModifierFlagsForField(modifierFlags)); } } updateFieldDeclaration(changeTracker, file, declaration, type, fieldName, fieldModifiers); @@ -141948,9 +146419,6 @@ var ts; var leftHead = isStatic ? container.name : ts.factory.createThis(); // TODO: GH#18217 return ts.isIdentifier(fieldName) ? ts.factory.createPropertyAccessExpression(leftHead, fieldName) : ts.factory.createElementAccessExpression(leftHead, ts.factory.createStringLiteralFromNode(fieldName)); } - function createModifiers(modifierFlags) { - return modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; - } function prepareModifierFlagsForAccessor(modifierFlags) { modifierFlags &= ~64 /* Readonly */; // avoid Readonly modifier because it will convert to get accessor modifierFlags &= ~8 /* Private */; @@ -141995,7 +146463,7 @@ var ts; isStatic: ts.hasStaticModifier(declaration), isReadonly: ts.hasEffectiveReadonlyModifier(declaration), type: getDeclarationType(declaration, program), - container: declaration.kind === 160 /* Parameter */ ? declaration.parent.parent : declaration.parent, + container: declaration.kind === 161 /* Parameter */ ? declaration.parent.parent : declaration.parent, originalName: declaration.name.text, declaration: declaration, fieldName: fieldName, @@ -142085,7 +146553,7 @@ var ts; if (!superSymbol) break; var symbol = superSymbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(superSymbol) : superSymbol; - var superDecl = ts.find(symbol.declarations, ts.isClassLike); + var superDecl = symbol.declarations && ts.find(symbol.declarations, ts.isClassLike); if (!superDecl) break; res.push(superDecl); @@ -142131,7 +146599,7 @@ var ts; }); function getActionsForUsageOfInvalidImport(context) { var sourceFile = context.sourceFile; - var targetKind = ts.Diagnostics.This_expression_is_not_callable.code === context.errorCode ? 203 /* CallExpression */ : 204 /* NewExpression */; + var targetKind = ts.Diagnostics.This_expression_is_not_callable.code === context.errorCode ? 204 /* CallExpression */ : 205 /* NewExpression */; var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind; }); if (!node) { return []; @@ -142465,7 +146933,7 @@ var ts; function getImportTypeNode(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); ts.Debug.assert(token.kind === 99 /* ImportKeyword */, "This token should be an ImportKeyword"); - ts.Debug.assert(token.parent.kind === 195 /* ImportType */, "Token parent should be an ImportType"); + ts.Debug.assert(token.parent.kind === 196 /* ImportType */, "Token parent should be an ImportType"); return token.parent; } function doChange(changes, sourceFile, importType) { @@ -142732,7 +147200,7 @@ var ts; var token = ts.getTokenAtPosition(sourceFile, pos); var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(token); - if (symbol) { + if (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) { return symbol.valueDeclaration.parent.parent; } } @@ -142927,23 +147395,23 @@ var ts; return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_find_export_statement) }; } var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol; - var flags = ts.getSyntacticModifierFlags(exportNode); + var flags = ts.getSyntacticModifierFlags(exportNode) || ((ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) ? 513 /* ExportDefault */ : 0 /* None */); var wasDefault = !!(flags & 512 /* Default */); // If source file already has a default export, don't offer refactor. if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.This_file_already_has_a_default_export) }; } switch (exportNode.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 256 /* ModuleDeclaration */: { + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 257 /* ModuleDeclaration */: { var node = exportNode; return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; } - case 232 /* VariableStatement */: { + case 233 /* VariableStatement */: { var vs = exportNode; // Must be `export const x = something;`. if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { @@ -142955,6 +147423,11 @@ var ts; ts.Debug.assert(!wasDefault, "Can't have a default flag here"); return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; } + case 267 /* ExportAssignment */: { + var node = exportNode; + var exp = node.expression; + return node.isExportEquals ? undefined : { exportNode: node, exportName: exp, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol }; + } default: return undefined; } @@ -142966,17 +147439,24 @@ var ts; function changeExport(exportingSourceFile, _a, changes, checker) { var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; if (wasDefault) { - changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 87 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + if (ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) { + var exp = exportNode.expression; + var spec = makeExportSpecifier(exp.text, exp.text); + changes.replaceNode(exportingSourceFile, exportNode, ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([spec]))); + } + else { + changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 87 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + } } else { var exportKeyword = ts.Debug.checkDefined(ts.findModifier(exportNode, 92 /* ExportKeyword */), "Should find an export keyword in modifier list"); switch (exportNode.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.factory.createToken(87 /* DefaultKeyword */)); break; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // If 'x' isn't used in this file and doesn't have type definition, `export const x = 0;` --> `export default 0;` var decl = ts.first(exportNode.declarationList.declarations); if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile) && !decl.type) { @@ -142985,15 +147465,15 @@ var ts; break; } // falls through - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 256 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 257 /* ModuleDeclaration */: // `export type T = number;` -> `type T = number; export default T;` changes.deleteModifier(exportingSourceFile, exportKeyword); changes.insertNodeAfter(exportingSourceFile, exportNode, ts.factory.createExportDefault(ts.factory.createIdentifier(exportName.text))); break; default: - ts.Debug.assertNever(exportNode, "Unexpected exportNode kind " + exportNode.kind); + ts.Debug.fail("Unexpected exportNode kind " + exportNode.kind); } } } @@ -143014,18 +147494,18 @@ var ts; function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { var parent = ref.parent; switch (parent.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: // `a.default` --> `a.foo` changes.replaceNode(importingSourceFile, ref, ts.factory.createIdentifier(exportName)); break; - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: { + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: { var spec = parent; // `default as foo` --> `foo`, `default as bar` --> `foo as bar` changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); break; } - case 262 /* ImportClause */: { + case 263 /* ImportClause */: { var clause = parent; ts.Debug.assert(clause.name === ref, "Import clause name should match provided ref"); var spec = makeImportSpecifier(exportName, ref.text); @@ -143034,7 +147514,7 @@ var ts; // `import foo from "./a";` --> `import { foo } from "./a";` changes.replaceNode(importingSourceFile, ref, ts.factory.createNamedImports([spec])); } - else if (namedBindings.kind === 263 /* NamespaceImport */) { + else if (namedBindings.kind === 264 /* NamespaceImport */) { // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";` changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; @@ -143055,11 +147535,11 @@ var ts; function changeNamedToDefaultImport(importingSourceFile, ref, changes) { var parent = ref.parent; switch (parent.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: // `a.foo` --> `a.default` changes.replaceNode(importingSourceFile, ref, ts.factory.createIdentifier("default")); break; - case 265 /* ImportSpecifier */: { + case 266 /* ImportSpecifier */: { // `import { foo } from "./a";` --> `import foo from "./a";` // `import { foo as bar } from "./a";` --> `import bar from "./a";` var defaultImport = ts.factory.createIdentifier(parent.name.text); @@ -143072,7 +147552,7 @@ var ts; } break; } - case 270 /* ExportSpecifier */: { + case 271 /* ExportSpecifier */: { // `export { foo } from "./a";` --> `export { default as foo } from "./a";` // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` // `export { foo as default } from "./a";` --> `export { default } from "./a";` @@ -143118,14 +147598,16 @@ var ts; if (!info) return ts.emptyArray; if (!refactor.isRefactorErrorInfo(info)) { - var namespaceImport = info.kind === 263 /* NamespaceImport */; + var namespaceImport = info.kind === 264 /* NamespaceImport */; var action = namespaceImport ? namespaceToNamedAction : namedToNamespaceAction; return [{ name: refactorName, description: action.description, actions: [action] }]; } if (context.preferences.provideRefactorNotApplicableReason) { return [ - { name: refactorName, description: namespaceToNamedAction.description, actions: [__assign(__assign({}, namespaceToNamedAction), { notApplicableReason: info.error })] }, - { name: refactorName, description: namedToNamespaceAction.description, actions: [__assign(__assign({}, namedToNamespaceAction), { notApplicableReason: info.error })] } + { name: refactorName, description: namespaceToNamedAction.description, + actions: [__assign(__assign({}, namespaceToNamedAction), { notApplicableReason: info.error })] }, + { name: refactorName, description: namedToNamespaceAction.description, + actions: [__assign(__assign({}, namedToNamespaceAction), { notApplicableReason: info.error })] } ]; } return ts.emptyArray; @@ -143160,7 +147642,7 @@ var ts; } function doChange(sourceFile, program, changes, toConvert) { var checker = program.getTypeChecker(); - if (toConvert.kind === 263 /* NamespaceImport */) { + if (toConvert.kind === 264 /* NamespaceImport */) { doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); } else { @@ -143225,7 +147707,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_15 = function (element) { + var _loop_16 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(namespaceImportName), propertyName); @@ -143244,7 +147726,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_15(element); + _loop_16(element); } changes.replaceNode(sourceFile, toConvert, ts.factory.createNamespaceImport(ts.factory.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -143561,27 +148043,27 @@ var ts; var lastDeclaration = signatureDecls[signatureDecls.length - 1]; var updated = lastDeclaration; switch (lastDeclaration.kind) { - case 164 /* MethodSignature */: { + case 165 /* MethodSignature */: { updated = ts.factory.updateMethodSignature(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); break; } - case 165 /* MethodDeclaration */: { + case 166 /* MethodDeclaration */: { updated = ts.factory.updateMethodDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } - case 169 /* CallSignature */: { + case 170 /* CallSignature */: { updated = ts.factory.updateCallSignature(lastDeclaration, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); break; } - case 166 /* Constructor */: { + case 167 /* Constructor */: { updated = ts.factory.updateConstructorDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.body); break; } - case 170 /* ConstructSignature */: { + case 171 /* ConstructSignature */: { updated = ts.factory.updateConstructSignature(lastDeclaration, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); break; } - case 251 /* FunctionDeclaration */: { + case 252 /* FunctionDeclaration */: { updated = ts.factory.updateFunctionDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } @@ -143633,12 +148115,12 @@ var ts; } function isConvertableSignatureDeclaration(d) { switch (d.kind) { - case 164 /* MethodSignature */: - case 165 /* MethodDeclaration */: - case 169 /* CallSignature */: - case 166 /* Constructor */: - case 170 /* ConstructSignature */: - case 251 /* FunctionDeclaration */: + case 165 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 170 /* CallSignature */: + case 167 /* Constructor */: + case 171 /* ConstructSignature */: + case 252 /* FunctionDeclaration */: return true; } return false; @@ -143778,7 +148260,6 @@ var ts; }; } } - // Skip these since we don't have a way to report errors yet if (refactor.refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { if (constantExtraction.errors.length === 0) { // Don't issue refactorings with duplicated names. @@ -143910,24 +148391,28 @@ var ts; /** * getRangeToExtract takes a span inside a text file and returns either an expression or an array * of statements representing the minimum set of nodes needed to extract the entire span. This - * process may fail, in which case a set of errors is returned instead (these are currently - * not shown to the user, but can be used by us diagnostically) + * process may fail, in which case a set of errors is returned instead. These errors are shown to + * users if they have the provideRefactorNotApplicableReason option set. */ // exported only for tests - function getRangeToExtract(sourceFile, span, considerEmptySpans) { - if (considerEmptySpans === void 0) { considerEmptySpans = true; } + function getRangeToExtract(sourceFile, span, invoked) { + if (invoked === void 0) { invoked = true; } var length = span.length; - if (length === 0 && !considerEmptySpans) { + if (length === 0 && !invoked) { return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] }; } - var cursorRequest = length === 0 && considerEmptySpans; + var cursorRequest = length === 0 && invoked; + var startToken = ts.findFirstNonJsxWhitespaceToken(sourceFile, span.start); + var endToken = ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)); + /* If the refactoring command is invoked through a keyboard action it's safe to assume that the user is actively looking for + refactoring actions at the span location. As they may not know the exact range that will trigger a refactoring, we expand the + searched span to cover a real node range making it more likely that something useful will show up. */ + var adjustedSpan = startToken && endToken && invoked ? getAdjustedSpanFromNodes(startToken, endToken, sourceFile) : span; // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span. // This may fail (e.g. you select two statements in the root of a source file) - var startToken = ts.getTokenAtPosition(sourceFile, span.start); - var start = cursorRequest ? getExtractableParent(startToken) : ts.getParentNodeInSpan(startToken, sourceFile, span); + var start = cursorRequest ? getExtractableParent(startToken) : ts.getParentNodeInSpan(startToken, sourceFile, adjustedSpan); // Do the same for the ending position - var endToken = ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)); - var end = cursorRequest ? start : ts.getParentNodeInSpan(endToken, sourceFile, span); + var end = cursorRequest ? start : ts.getParentNodeInSpan(endToken, sourceFile, adjustedSpan); var declarations = []; // We'll modify these flags as we walk the tree to collect data // about what things need to be done as part of the extraction. @@ -143936,6 +148421,9 @@ var ts; // cannot find either start or end node return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } + if (ts.isJSDoc(start)) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractJSDoc)] }; + } if (start.parent !== end.parent) { // start and end nodes belong to different subtrees return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; @@ -143970,9 +148458,6 @@ var ts; } return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; } - if (ts.isJSDoc(start)) { - return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractJSDoc)] }; - } if (ts.isReturnStatement(start) && !start.expression) { // Makes no sense to extract an expression-less return statement. return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; @@ -144025,20 +148510,20 @@ var ts; function checkForStaticContext(nodeToCheck, containingClass) { var current = nodeToCheck; while (current !== containingClass) { - if (current.kind === 163 /* PropertyDeclaration */) { + if (current.kind === 164 /* PropertyDeclaration */) { if (ts.hasSyntacticModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 160 /* Parameter */) { + else if (current.kind === 161 /* Parameter */) { var ctorOrMethod = ts.getContainingFunction(current); - if (ctorOrMethod.kind === 166 /* Constructor */) { + if (ctorOrMethod.kind === 167 /* Constructor */) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 165 /* MethodDeclaration */) { + else if (current.kind === 166 /* MethodDeclaration */) { if (ts.hasSyntacticModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } @@ -144081,7 +148566,7 @@ var ts; return true; } if (ts.isDeclaration(node)) { - var declaringNode = (node.kind === 249 /* VariableDeclaration */) ? node.parent.parent : node; + var declaringNode = (node.kind === 250 /* VariableDeclaration */) ? node.parent.parent : node; if (ts.hasSyntacticModifier(declaringNode, 1 /* Export */)) { // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! @@ -144093,16 +148578,16 @@ var ts; } // Some things can't be extracted in certain situations switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); return true; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; case 105 /* SuperKeyword */: // For a super *constructor call*, we have to be extracting the entire class, // but a super *method call* simply implies a 'this' reference - if (node.parent.kind === 203 /* CallExpression */) { + if (node.parent.kind === 204 /* CallExpression */) { // Super constructor call var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { @@ -144114,7 +148599,7 @@ var ts; rangeFacts |= RangeFacts.UsesThis; } break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: // check if arrow function uses this ts.forEachChild(node, function check(n) { if (ts.isThis(n)) { @@ -144128,39 +148613,39 @@ var ts; } }); // falls through - case 252 /* ClassDeclaration */: - case 251 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { // You cannot extract global declarations (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); } // falls through - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // do not dive into functions or classes return false; } var savedPermittedJumps = permittedJumps; switch (node.kind) { - case 234 /* IfStatement */: + case 235 /* IfStatement */: permittedJumps = 0 /* None */; break; - case 247 /* TryStatement */: + case 248 /* TryStatement */: // forbid all jumps inside try blocks permittedJumps = 0 /* None */; break; - case 230 /* Block */: - if (node.parent && node.parent.kind === 247 /* TryStatement */ && node.parent.finallyBlock === node) { + case 231 /* Block */: + if (node.parent && node.parent.kind === 248 /* TryStatement */ && node.parent.finallyBlock === node) { // allow unconditional returns from finally blocks permittedJumps = 4 /* Return */; } break; - case 285 /* DefaultClause */: - case 284 /* CaseClause */: + case 286 /* DefaultClause */: + case 285 /* CaseClause */: // allow unlabeled break inside case clauses permittedJumps |= 1 /* Break */; break; @@ -144172,19 +148657,19 @@ var ts; break; } switch (node.kind) { - case 187 /* ThisType */: + case 188 /* ThisType */: case 107 /* ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; break; - case 245 /* LabeledStatement */: { + case 246 /* LabeledStatement */: { var label = node.label; (seenLabels || (seenLabels = [])).push(label.escapedText); ts.forEachChild(node, visit); seenLabels.pop(); break; } - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: { + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: { var label = node.label; if (label) { if (!ts.contains(seenLabels, label.escapedText)) { @@ -144193,20 +148678,20 @@ var ts; } } else { - if (!(permittedJumps & (node.kind === 241 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + if (!(permittedJumps & (node.kind === 242 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { // attempt to break or continue in a forbidden context (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); } } break; } - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: rangeFacts |= RangeFacts.IsGenerator; break; - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: if (permittedJumps & 4 /* Return */) { rangeFacts |= RangeFacts.HasReturn; } @@ -144223,6 +148708,18 @@ var ts; } } extractSymbol.getRangeToExtract = getRangeToExtract; + /** + * Includes the final semicolon so that the span covers statements in cases where it would otherwise + * only cover the declaration list. + */ + function getAdjustedSpanFromNodes(startNode, endNode, sourceFile) { + var start = startNode.getStart(sourceFile); + var end = endNode.getEnd(); + if (sourceFile.text.charCodeAt(end) === 59 /* semicolon */) { + end++; + } + return { start: start, length: end - start }; + } function getStatementOrExpressionRange(node) { if (ts.isStatement(node)) { return [node]; @@ -144260,7 +148757,7 @@ var ts; while (true) { current = current.parent; // A function parameter's initializer is actually in the outer scope, not the function declaration - if (current.kind === 160 /* Parameter */) { + if (current.kind === 161 /* Parameter */) { // Skip all the way to the outer scope of the function that declared this parameter current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; } @@ -144271,7 +148768,7 @@ var ts; // * Module/namespace or source file if (isScope(current)) { scopes.push(current); - if (current.kind === 297 /* SourceFile */) { + if (current.kind === 298 /* SourceFile */) { return scopes; } } @@ -144361,32 +148858,32 @@ var ts; } function getDescriptionForFunctionLikeDeclaration(scope) { switch (scope.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return "constructor"; - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: return scope.name ? "function '" + scope.name.text + "'" : ts.ANONYMOUS; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return "arrow function"; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return "method '" + scope.name.getText() + "'"; - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: return "'get " + scope.name.getText() + "'"; - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: return "'set " + scope.name.getText() + "'"; default: throw ts.Debug.assertNever(scope, "Unexpected scope kind " + scope.kind); } } function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 252 /* ClassDeclaration */ + return scope.kind === 253 /* ClassDeclaration */ ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration" : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; } function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 257 /* ModuleBlock */ + return scope.kind === 258 /* ModuleBlock */ ? "namespace '" + scope.parent.name.getText() + "'" : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; } @@ -144675,7 +149172,7 @@ var ts; var localReference = ts.factory.createIdentifier(localNameText); changeTracker.replaceNode(context.file, node, localReference); } - else if (node.parent.kind === 233 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + else if (node.parent.kind === 234 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { // If the parent is an expression statement and the target scope is the immediately enclosing one, // replace the statement with the declaration. var newVariableStatement = ts.factory.createVariableStatement( @@ -144694,7 +149191,7 @@ var ts; changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); } // Consume - if (node.parent.kind === 233 /* ExpressionStatement */) { + if (node.parent.kind === 234 /* ExpressionStatement */) { // If the parent is an expression statement, delete it. changeTracker.delete(context.file, node.parent); } @@ -145021,7 +149518,7 @@ var ts; var scope = scopes_1[_i]; usagesPerScope.push({ usages: new ts.Map(), typeParameterUsages: new ts.Map(), substitutions: new ts.Map() }); substitutionsPerScope.push(new ts.Map()); - functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 251 /* FunctionDeclaration */ + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 252 /* FunctionDeclaration */ ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] : []); var constantErrors = []; @@ -145084,7 +149581,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_16 = function (i) { + var _loop_17 = 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 @@ -145124,7 +149621,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_16(i); + _loop_17(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -145340,30 +149837,30 @@ var ts; function isExtractableExpression(node) { var parent = node.parent; switch (parent.kind) { - case 291 /* EnumMember */: + case 292 /* EnumMember */: return false; } switch (node.kind) { case 10 /* StringLiteral */: - return parent.kind !== 261 /* ImportDeclaration */ && - parent.kind !== 265 /* ImportSpecifier */; - case 220 /* SpreadElement */: - case 196 /* ObjectBindingPattern */: - case 198 /* BindingElement */: + return parent.kind !== 262 /* ImportDeclaration */ && + parent.kind !== 266 /* ImportSpecifier */; + case 221 /* SpreadElement */: + case 197 /* ObjectBindingPattern */: + case 199 /* BindingElement */: return false; case 78 /* Identifier */: - return parent.kind !== 198 /* BindingElement */ && - parent.kind !== 265 /* ImportSpecifier */ && - parent.kind !== 270 /* ExportSpecifier */; + return parent.kind !== 199 /* BindingElement */ && + parent.kind !== 266 /* ImportSpecifier */ && + parent.kind !== 271 /* ExportSpecifier */; } return true; } function isBlockLike(node) { switch (node.kind) { - case 230 /* Block */: - case 297 /* SourceFile */: - case 257 /* ModuleBlock */: - case 284 /* CaseClause */: + case 231 /* Block */: + case 298 /* SourceFile */: + case 258 /* ModuleBlock */: + case 285 /* CaseClause */: return true; default: return false; @@ -145505,7 +150002,7 @@ var ts; if (ts.isTypeReferenceNode(node)) { if (ts.isIdentifier(node.typeName)) { var symbol = checker.resolveName(node.typeName.text, node.typeName, 262144 /* TypeParameter */, /* excludeGlobals */ true); - if (symbol) { + if (symbol === null || symbol === void 0 ? void 0 : symbol.declarations) { var declaration = ts.cast(ts.first(symbol.declarations), ts.isTypeParameterDeclaration); if (rangeContainsSkipTrivia(statement, declaration, file) && !rangeContainsSkipTrivia(selection, declaration, file)) { ts.pushIfUnique(result, declaration); @@ -145528,7 +150025,7 @@ var ts; else if (ts.isTypeQueryNode(node)) { if (ts.isIdentifier(node.exprName)) { var symbol = checker.resolveName(node.exprName.text, node.exprName, 111551 /* Value */, /* excludeGlobals */ false); - if (symbol && rangeContainsSkipTrivia(statement, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) { + if ((symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) && rangeContainsSkipTrivia(statement, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) { return true; } } @@ -145748,11 +150245,11 @@ var ts; } function isPureImport(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return true; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return !ts.hasSyntacticModifier(node, 1 /* Export */); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); default: return false; @@ -145813,10 +150310,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_17 = function (sourceFile) { + var _loop_18 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_18 = function (statement) { + var _loop_19 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -145838,22 +150335,22 @@ var ts; }; for (var _b = 0, _c = sourceFile.statements; _b < _c.length; _b++) { var statement = _c[_b]; - _loop_18(statement); + _loop_19(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_17(sourceFile); + _loop_18(sourceFile); } } function getNamespaceLikeImport(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 263 /* NamespaceImport */ ? + case 262 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 264 /* NamespaceImport */ ? node.importClause.namedBindings.name : undefined; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return node.name; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return ts.tryCast(node.name, ts.isIdentifier); default: return ts.Debug.assertNever(node, "Unexpected node kind " + node.kind); @@ -145884,20 +150381,20 @@ var ts; var newNamespaceId = ts.factory.createIdentifier(newNamespaceName); var newModuleString = ts.factory.createStringLiteral(newModuleSpecifier); switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamespaceImport(newNamespaceId)), newModuleString); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return ts.factory.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, newNamespaceId, ts.factory.createExternalModuleReference(newModuleString)); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return ts.factory.createVariableDeclaration(newNamespaceId, /*exclamationToken*/ undefined, /*type*/ undefined, createRequireCall(newModuleString)); default: return ts.Debug.assertNever(node, "Unexpected node kind " + node.kind); } } function moduleSpecifierFromImport(i) { - return (i.kind === 261 /* ImportDeclaration */ ? i.moduleSpecifier - : i.kind === 260 /* ImportEqualsDeclaration */ ? i.moduleReference.expression + return (i.kind === 262 /* ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 261 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]); } function forEachImportInStatement(statement, cb) { @@ -145967,15 +150464,15 @@ var ts; } function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { switch (importDecl.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); break; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: if (isUnused(importDecl.name)) { changes.delete(sourceFile, importDecl); } break; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); break; default: @@ -145988,7 +150485,7 @@ var ts; var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; var defaultUnused = !name || isUnused(name); var namedBindingsUnused = !namedBindings || - (namedBindings.kind === 263 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); + (namedBindings.kind === 264 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); if (defaultUnused && namedBindingsUnused) { changes.delete(sourceFile, importDecl); } @@ -146000,7 +150497,7 @@ var ts; if (namedBindingsUnused) { changes.replaceNode(sourceFile, importDecl.importClause, ts.factory.updateImportClause(importDecl.importClause, importDecl.importClause.isTypeOnly, name, /*namedBindings*/ undefined)); } - else if (namedBindings.kind === 264 /* NamedImports */) { + else if (namedBindings.kind === 265 /* NamedImports */) { for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { var element = _b[_i]; if (isUnused(element.name)) @@ -146018,9 +150515,9 @@ var ts; changes.delete(sourceFile, name); } break; - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: break; - case 196 /* ObjectBindingPattern */: + case 197 /* ObjectBindingPattern */: if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); } @@ -146048,6 +150545,9 @@ var ts; var oldFileNamedImports = []; var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`. newFileImportsFromOldFile.forEach(function (symbol) { + if (!symbol.declarations) { + return; + } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; if (!isTopLevelDeclaration(decl)) @@ -146147,14 +150647,14 @@ var ts; // Below should all be utilities function isInImport(decl) { switch (decl.kind) { - case 260 /* ImportEqualsDeclaration */: - case 265 /* ImportSpecifier */: - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: + case 261 /* ImportEqualsDeclaration */: + case 266 /* ImportSpecifier */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: return true; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return isVariableDeclarationInImport(decl); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); default: return false; @@ -146166,7 +150666,7 @@ var ts; } function filterImport(i, moduleSpecifier, keep) { switch (i.kind) { - case 261 /* ImportDeclaration */: { + case 262 /* ImportDeclaration */: { var clause = i.importClause; if (!clause) return undefined; @@ -146176,9 +150676,9 @@ var ts; ? ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImport, namedBindings), moduleSpecifier) : undefined; } - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return keep(i.name) ? i : undefined; - case 249 /* VariableDeclaration */: { + case 250 /* VariableDeclaration */: { var name = filterBindingName(i.name, keep); return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; } @@ -146187,7 +150687,7 @@ var ts; } } function filterNamedBindings(namedBindings, keep) { - if (namedBindings.kind === 263 /* NamespaceImport */) { + if (namedBindings.kind === 264 /* NamespaceImport */) { return keep(namedBindings.name) ? namedBindings : undefined; } else { @@ -146199,9 +150699,9 @@ var ts; switch (name.kind) { case 78 /* Identifier */: return keep(name) ? name : undefined; - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: return name; - case 196 /* ObjectBindingPattern */: { + case 197 /* ObjectBindingPattern */: { // We can't handle nested destructurings or property names well here, so just copy them all. var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); return newElements.length ? ts.factory.createObjectBindingPattern(newElements) : undefined; @@ -146258,13 +150758,13 @@ var ts; } function isNonVariableTopLevelDeclaration(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 261 /* ImportEqualsDeclaration */: return true; default: return false; @@ -146272,17 +150772,17 @@ var ts; } function forEachTopLevelDeclaration(statement, cb) { switch (statement.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 261 /* ImportEqualsDeclaration */: return cb(statement); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return ts.firstDefined(statement.declarationList.declarations, function (decl) { return forEachTopLevelDeclarationInBindingName(decl.name, cb); }); - case 233 /* ExpressionStatement */: { + case 234 /* ExpressionStatement */: { var expression = statement.expression; return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) @@ -146294,8 +150794,8 @@ var ts; switch (name.kind) { case 78 /* Identifier */: return cb(ts.cast(name.parent, function (x) { return ts.isVariableDeclaration(x) || ts.isBindingElement(x); })); - case 197 /* ArrayBindingPattern */: - case 196 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: return ts.firstDefined(name.elements, function (em) { return ts.isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb); }); default: return ts.Debug.assertNever(name, "Unexpected name kind " + name.kind); @@ -146306,9 +150806,9 @@ var ts; } function getTopLevelDeclarationStatement(d) { switch (d.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return d.parent.parent; - case 198 /* BindingElement */: + case 199 /* BindingElement */: return getTopLevelDeclarationStatement(ts.cast(d.parent.parent, function (p) { return ts.isVariableDeclaration(p) || ts.isBindingElement(p); })); default: return d; @@ -146341,23 +150841,23 @@ var ts; function addEs6Export(d) { var modifiers = ts.concatenate([ts.factory.createModifier(92 /* ExportKeyword */)], d.modifiers); switch (d.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return ts.factory.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return ts.factory.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return ts.factory.updateVariableStatement(d, modifiers, d.declarationList); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return ts.factory.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return ts.factory.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return ts.factory.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return ts.factory.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return ts.factory.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.isTypeOnly, d.name, d.moduleReference); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(d, "Unexpected declaration kind " + d.kind); @@ -146368,18 +150868,18 @@ var ts; } function getNamesToExportInCommonJS(decl) { switch (decl.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: return [decl.name.text]; // TODO: GH#18217 - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 261 /* ImportEqualsDeclaration */: return ts.emptyArray; - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return ts.Debug.fail("Can't export an ExpressionStatement"); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(decl, "Unexpected decl kind " + decl.kind); @@ -146548,13 +151048,13 @@ var ts; return { edits: [] }; // TODO: GH#30113 } function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) { - var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); - changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ", - // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter - indentation: 0, - leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include - }); + var signature = groupedReferences.signature; + var newFunctionDeclarationParams = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); + if (signature) { + var newSignatureParams = ts.map(createNewParameters(signature, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); + replaceParameters(signature, newSignatureParams); + } + replaceParameters(functionDeclaration, newFunctionDeclarationParams); var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); }); for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) { var call = functionCalls_1[_i]; @@ -146563,6 +151063,15 @@ var ts; changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include }); } } + function replaceParameters(declarationOrSignature, parameterDeclarations) { + changes.replaceNodeRangeWithNodes(sourceFile, ts.first(declarationOrSignature.parameters), ts.last(declarationOrSignature.parameters), parameterDeclarations, { + joiner: ", ", + // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter + indentation: 0, + leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include + }); + } } function getGroupedReferences(functionDeclaration, program, cancellationToken) { var functionNames = getFunctionNames(functionDeclaration); @@ -146581,12 +151090,38 @@ var ts; var functionSymbols = ts.map(functionNames, getSymbolTargetAtLocation); var classSymbols = ts.map(classNames, getSymbolTargetAtLocation); var isConstructor = ts.isConstructorDeclaration(functionDeclaration); + var contextualSymbols = ts.map(functionNames, function (name) { return getSymbolForContextualType(name, checker); }); for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) { var entry = referenceEntries_1[_i]; - if (entry.kind !== 1 /* Node */) { + if (entry.kind === 0 /* Span */) { groupedReferences.valid = false; continue; } + /* Declarations in object literals may be implementations of method signatures which have a different symbol from the declaration + For example: + interface IFoo { m(a: number): void } + const foo: IFoo = { m(a: number): void {} } + In these cases we get the symbol for the signature from the contextual type. + */ + if (ts.contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) { + if (isValidMethodSignature(entry.node.parent)) { + groupedReferences.signature = entry.node.parent; + continue; + } + var call = entryToFunctionCall(entry); + if (call) { + groupedReferences.functionCalls.push(call); + continue; + } + } + var contextualSymbol = getSymbolForContextualType(entry.node, checker); + if (contextualSymbol && ts.contains(contextualSymbols, contextualSymbol)) { + var decl = entryToDeclaration(entry); + if (decl) { + groupedReferences.declarations.push(decl); + continue; + } + } /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function. Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test: class A { foo(a: number, b: number) { return a + b; } } @@ -146649,6 +151184,19 @@ var ts; return symbol && ts.getSymbolTarget(symbol, checker); } } + /** + * Gets the symbol for the contextual type of the node if it is not a union or intersection. + */ + function getSymbolForContextualType(node, checker) { + var element = ts.getContainingObjectLiteralElement(node); + if (element) { + var contextualType = checker.getContextualTypeForObjectLiteralElement(element); + var symbol = contextualType === null || contextualType === void 0 ? void 0 : contextualType.getSymbol(); + if (symbol && !(ts.getCheckFlags(symbol) & 6 /* Synthetic */)) { + return symbol; + } + } + } function entryToImportOrExport(entry) { var node = entry.node; if (ts.isImportSpecifier(node.parent) @@ -146674,15 +151222,15 @@ var ts; var parent = functionReference.parent; switch (parent.kind) { // foo(...) or super(...) or new Foo(...) - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: var callOrNewExpression = ts.tryCast(parent, ts.isCallOrNewExpression); if (callOrNewExpression && callOrNewExpression.expression === functionReference) { return callOrNewExpression; } break; // x.foo(...) - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression); if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { var callOrNewExpression_1 = ts.tryCast(propertyAccessExpression.parent, ts.isCallOrNewExpression); @@ -146692,7 +151240,7 @@ var ts; } break; // x["foo"](...) - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression); if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { var callOrNewExpression_2 = ts.tryCast(elementAccessExpression.parent, ts.isCallOrNewExpression); @@ -146711,14 +151259,14 @@ var ts; var parent = reference.parent; switch (parent.kind) { // `C.foo` - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression); if (propertyAccessExpression && propertyAccessExpression.expression === reference) { return propertyAccessExpression; } break; // `C["foo"]` - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression); if (elementAccessExpression && elementAccessExpression.expression === reference) { return elementAccessExpression; @@ -146756,15 +151304,24 @@ var ts; } return false; } + function isValidMethodSignature(node) { + return ts.isMethodSignature(node) && (ts.isInterfaceDeclaration(node.parent) || ts.isTypeLiteralNode(node.parent)); + } function isValidFunctionDeclaration(functionDeclaration, checker) { + var _a; if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false; switch (functionDeclaration.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: + if (ts.isObjectLiteralExpression(functionDeclaration.parent)) { + var contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker); + // don't offer the refactor when there are multiple signatures since we won't know which ones the user wants to change + return ((_a = contextualSymbol === null || contextualSymbol === void 0 ? void 0 : contextualSymbol.declarations) === null || _a === void 0 ? void 0 : _a.length) === 1 && isSingleImplementation(functionDeclaration, checker); + } return isSingleImplementation(functionDeclaration, checker); - case 166 /* Constructor */: + case 167 /* Constructor */: if (ts.isClassDeclaration(functionDeclaration.parent)) { return hasNameOrDefault(functionDeclaration.parent) && isSingleImplementation(functionDeclaration, checker); } @@ -146772,8 +151329,8 @@ var ts; return isValidVariableDeclaration(functionDeclaration.parent.parent) && isSingleImplementation(functionDeclaration, checker); } - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return isValidVariableDeclaration(functionDeclaration.parent); } return false; @@ -146923,7 +151480,7 @@ var ts; } function getClassNames(constructorDeclaration) { switch (constructorDeclaration.parent.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: var classDeclaration = constructorDeclaration.parent; if (classDeclaration.name) return [classDeclaration.name]; @@ -146931,7 +151488,7 @@ var ts; // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault` var defaultModifier = ts.Debug.checkDefined(ts.findModifier(classDeclaration, 87 /* DefaultKeyword */), "Nameless class declaration should be a default export"); return [defaultModifier]; - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: var classExpression = constructorDeclaration.parent; var variableDeclaration = constructorDeclaration.parent.parent; var className = classExpression.name; @@ -146942,25 +151499,25 @@ var ts; } function getFunctionNames(functionDeclaration) { switch (functionDeclaration.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: if (functionDeclaration.name) return [functionDeclaration.name]; // If the function declaration doesn't have a name, it should have a default modifier. // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault` var defaultModifier = ts.Debug.checkDefined(ts.findModifier(functionDeclaration, 87 /* DefaultKeyword */), "Nameless function declaration should be a default export"); return [defaultModifier]; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return [functionDeclaration.name]; - case 166 /* Constructor */: + case 167 /* Constructor */: var ctrKeyword = ts.Debug.checkDefined(ts.findChildOfKind(functionDeclaration, 132 /* ConstructorKeyword */, functionDeclaration.getSourceFile()), "Constructor declaration should have constructor keyword"); - if (functionDeclaration.parent.kind === 221 /* ClassExpression */) { + if (functionDeclaration.parent.kind === 222 /* ClassExpression */) { var variableDeclaration = functionDeclaration.parent.parent; return [variableDeclaration.name, ctrKeyword]; } return [ctrKeyword]; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return [functionDeclaration.parent.name]; - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: if (functionDeclaration.name) return [functionDeclaration.name, functionDeclaration.parent.name]; return [functionDeclaration.parent.name]; @@ -147051,11 +151608,11 @@ var ts; function getParentBinaryExpression(expr) { var container = ts.findAncestor(expr.parent, function (n) { switch (n.kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return false; - case 218 /* TemplateExpression */: - case 216 /* BinaryExpression */: + case 219 /* TemplateExpression */: + case 217 /* BinaryExpression */: return !(ts.isBinaryExpression(n.parent) && isNotEqualsOperator(n.parent)); default: return "quit"; @@ -147132,7 +151689,7 @@ var ts; var templateSpans = []; var templateHead = ts.factory.createTemplateHead(headText); copyCommentFromStringLiterals(headIndexes, templateHead); - var _loop_19 = function (i) { + var _loop_20 = function (i) { var currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); copyOperatorComments(i, currentNode); var _c = concatConsecutiveString(i + 1, nodes), newIndex = _c[0], subsequentText = _c[1], stringIndexes = _c[2]; @@ -147156,7 +151713,7 @@ var ts; }; var out_i_1; for (var i = begin; i < nodes.length; i++) { - _loop_19(i); + _loop_20(i); i = out_i_1; } return ts.factory.createTemplateExpression(templateHead, templateSpans); @@ -147356,7 +151913,9 @@ var ts; var body = convertToBlock(func.body); var variableDeclaration = variableInfo.variableDeclaration, variableDeclarationList = variableInfo.variableDeclarationList, statement = variableInfo.statement, name = variableInfo.name; ts.suppressLeadingTrivia(statement); - var newNode = ts.factory.createFunctionDeclaration(func.decorators, statement.modifiers, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); + var modifiersFlags = (ts.getCombinedModifierFlags(variableDeclaration) & 1 /* Export */) | ts.getEffectiveModifierFlags(func); + var modifiers = ts.factory.createModifiersFromModifierFlags(modifiersFlags); + var newNode = ts.factory.createFunctionDeclaration(func.decorators, ts.length(modifiers) ? modifiers : undefined, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); if (variableDeclarationList.declarations.length === 1) { return ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, statement, newNode); }); } @@ -147414,9 +151973,7 @@ var ts; function getEditsForAction(context) { var info = getInfo(context); if (info && !refactor.isRefactorErrorInfo(info)) { - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { - return t.tryInsertTypeAnnotation(context.file, info.declaration, info.returnTypeNode); - }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, t, info.declaration, info.returnTypeNode); }); return { renameFilename: undefined, renameLocation: undefined, edits: edits }; } return undefined; @@ -147441,11 +151998,26 @@ var ts; } return ts.emptyArray; } + function doChange(sourceFile, changes, declaration, typeNode) { + var closeParen = ts.findChildOfKind(declaration, 21 /* CloseParenToken */, sourceFile); + var needParens = ts.isArrowFunction(declaration) && closeParen === undefined; + var endNode = needParens ? ts.first(declaration.parameters) : closeParen; + if (endNode) { + if (needParens) { + changes.insertNodeBefore(sourceFile, endNode, ts.factory.createToken(20 /* OpenParenToken */)); + changes.insertNodeAfter(sourceFile, endNode, ts.factory.createToken(21 /* CloseParenToken */)); + } + changes.insertNodeAt(sourceFile, endNode.end, typeNode, { prefix: ": " }); + } + } function getInfo(context) { if (ts.isInJSFile(context.file) || !refactor.refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind)) return; var token = ts.getTokenAtPosition(context.file, context.startPosition); - var declaration = ts.findAncestor(token, isConvertibleDeclaration); + var declaration = ts.findAncestor(token, function (n) { + return ts.isBlock(n) || n.parent && ts.isArrowFunction(n.parent) && (n.kind === 38 /* EqualsGreaterThanToken */ || n.parent.body === n) ? "quit" : + isConvertibleDeclaration(n); + }); if (!declaration || !declaration.body || declaration.type) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Return_type_must_be_inferred_from_a_function) }; } @@ -147454,7 +152026,6 @@ var ts; if (!returnType) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_determine_function_return_type) }; } - ; var returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, 1 /* NoTruncation */); if (returnTypeNode) { return { declaration: declaration, returnTypeNode: returnTypeNode }; @@ -147462,10 +152033,10 @@ var ts; } function isConvertibleDeclaration(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: return true; default: return false; @@ -147567,8 +152138,8 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 301 /* FirstJSDocNode */ || kid.kind > 333 /* LastJSDocNode */; }); - return child.kind < 157 /* FirstNode */ ? + var child = ts.find(children, function (kid) { return kid.kind < 302 /* FirstJSDocNode */ || kid.kind > 337 /* LastJSDocNode */; }); + return child.kind < 158 /* FirstNode */ ? child : child.getFirstToken(sourceFile); }; @@ -147579,7 +152150,7 @@ var ts; if (!child) { return undefined; } - return child.kind < 157 /* FirstNode */ ? child : child.getLastToken(sourceFile); + return child.kind < 158 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { return ts.forEachChild(this, cbNode, cbNodeArray); @@ -147637,11 +152208,11 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(334 /* SyntaxList */, nodes.pos, nodes.end, parent); + var list = createNode(338 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { - var node = nodes_1[_i]; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; addSyntheticNodes(list._children, pos, node.pos, parent); list._children.push(node); pos = node.end; @@ -147748,13 +152319,13 @@ var ts; }; SymbolObject.prototype.getContextualDocumentationComment = function (context, checker) { switch (context === null || context === void 0 ? void 0 : context.kind) { - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: if (!this.contextualGetAccessorDocumentationComment) { this.contextualGetAccessorDocumentationComment = ts.emptyArray; this.contextualGetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isGetAccessor), checker); } return this.contextualGetAccessorDocumentationComment; - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: if (!this.contextualSetAccessorDocumentationComment) { this.contextualSetAccessorDocumentationComment = ts.emptyArray; this.contextualSetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isSetAccessor), checker); @@ -147764,9 +152335,9 @@ var ts; return this.getDocumentationComment(checker); } }; - SymbolObject.prototype.getJsDocTags = function () { + SymbolObject.prototype.getJsDocTags = function (checker) { if (this.tags === undefined) { - this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations); + this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations, checker); } return this.tags; }; @@ -147927,7 +152498,7 @@ var ts; }; SignatureObject.prototype.getJsDocTags = function () { if (this.jsDocTags === undefined) { - this.jsDocTags = this.declaration ? getJsDocTags([this.declaration], this.checker) : []; + this.jsDocTags = this.declaration ? getJsDocTagsOfSignature(this.declaration, this.checker) : []; } return this.jsDocTags; }; @@ -147941,29 +152512,34 @@ var ts; function hasJSDocInheritDocTag(node) { return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); } - function getJsDocTags(declarations, checker) { - var tags = ts.JsDoc.getJsDocTagsFromDeclarations(declarations); - if (tags.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - ts.forEachUnique(declarations, function (declaration) { - var inheritedTags = findBaseOfDeclaration(checker, declaration, function (symbol) { return symbol.getJsDocTags(); }); - if (inheritedTags) { - tags = __spreadArray(__spreadArray([], inheritedTags), tags); - } - }); + function getJsDocTagsOfSignature(declaration, checker) { + var tags = ts.JsDoc.getJsDocTagsFromDeclarations([declaration], checker); + if (tags.length === 0 || hasJSDocInheritDocTag(declaration)) { + var inheritedTags = findBaseOfDeclaration(checker, declaration, function (symbol) { var _a; return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) === 1 ? symbol.getJsDocTags() : undefined; }); + if (inheritedTags) { + tags = __spreadArray(__spreadArray([], inheritedTags), tags); + } } return tags; } function getDocumentationComment(declarations, checker) { if (!declarations) return ts.emptyArray; - var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); + var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations, checker); if (checker && (doc.length === 0 || declarations.some(hasJSDocInheritDocTag))) { - ts.forEachUnique(declarations, function (declaration) { - var inheritedDocs = findBaseOfDeclaration(checker, declaration, function (symbol) { return symbol.getDocumentationComment(checker); }); + var seenSymbols_1 = new ts.Set(); + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; + var inheritedDocs = findBaseOfDeclaration(checker, declaration, function (symbol) { + if (!seenSymbols_1.has(symbol)) { + seenSymbols_1.add(symbol); + return symbol.getDocumentationComment(checker); + } + }); // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); - }); + } } return doc; } @@ -147977,7 +152553,7 @@ var ts; __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { var _this = _super.call(this, kind, pos, end) || this; - _this.kind = 297 /* SourceFile */; + _this.kind = 298 /* SourceFile */; return _this; } SourceFileObject.prototype.update = function (newText, textChangeRange) { @@ -148036,10 +152612,10 @@ var ts; } function visit(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -148059,31 +152635,31 @@ var ts; } ts.forEachChild(node, visit); break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: - case 256 /* ModuleDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 270 /* ExportSpecifier */: - case 265 /* ImportSpecifier */: - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 177 /* TypeLiteral */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 257 /* ModuleDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 271 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 178 /* TypeLiteral */: addDeclaration(node); ts.forEachChild(node, visit); break; - case 160 /* Parameter */: + case 161 /* Parameter */: // Only consider parameter properties - if (!ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) { + if (!ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { break; } // falls through - case 249 /* VariableDeclaration */: - case 198 /* BindingElement */: { + case 250 /* VariableDeclaration */: + case 199 /* BindingElement */: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -148094,12 +152670,12 @@ var ts; } } // falls through - case 291 /* EnumMember */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 292 /* EnumMember */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: addDeclaration(node); break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; var exportDeclaration = node; @@ -148112,7 +152688,7 @@ var ts; } } break; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -148124,7 +152700,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 263 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 264 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -148133,7 +152709,7 @@ var ts; } } break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } @@ -148227,15 +152803,7 @@ var ts; var fileName = rootFileNames_1[_i]; this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName)); } - // store the compilation settings - this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); } - HostCache.prototype.compilationSettings = function () { - return this._compilationSettings; - }; - HostCache.prototype.getProjectReferences = function () { - return this.host.getProjectReferences && this.host.getProjectReferences(); - }; HostCache.prototype.createEntry = function (fileName, path) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); @@ -148385,7 +152953,7 @@ var ts; }; CancellationTokenObject.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { - ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "CancellationTokenObject" }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "CancellationTokenObject" }); throw new ts.OperationCanceledException(); } }; @@ -148415,7 +152983,7 @@ var ts; }; ThrottledCancellationToken.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { - ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "ThrottledCancellationToken" }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "ThrottledCancellationToken" }); throw new ts.OperationCanceledException(); } }; @@ -148515,7 +153083,7 @@ var ts; return sourceFile; } function synchronizeHostData() { - var _a, _b; + var _a, _b, _c; ts.Debug.assert(languageServiceMode !== ts.LanguageServiceMode.Syntactic); // perform fast check if host supports it if (host.getProjectVersion) { @@ -148536,11 +153104,22 @@ var ts; // Get a fresh cache of the host information var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); + var newSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; var hasChangedAutomaticTypeDirectiveNames = ts.maybeBind(host, host.hasChangedAutomaticTypeDirectiveNames); - var projectReferences = hostCache.getProjectReferences(); + var projectReferences = (_b = host.getProjectReferences) === null || _b === void 0 ? void 0 : _b.call(host); + var parsedCommandLines; + var parseConfigHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: readFile, + readDirectory: readDirectory, + trace: ts.maybeBind(host, host.trace), + getCurrentDirectory: function () { return currentDirectory; }, + onUnRecoverableConfigFileDiagnostic: ts.noop, + }; // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (_path, fileName) { return host.getScriptVersion(fileName); }, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { + if (ts.isProgramUptoDate(program, rootFileNames, newSettings, function (_path, fileName) { return host.getScriptVersion(fileName); }, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -148548,7 +153127,6 @@ var ts; // instance. If we cancel midway through, we may end up in an inconsistent state where // the program points to old source files that have been invalidated because of // incremental parsing. - var newSettings = hostCache.compilationSettings(); // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -148570,19 +153148,18 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, - readDirectory: function (path, extensions, exclude, include, depth) { - ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); - return host.readDirectory(path, extensions, exclude, include, depth); - }, + readDirectory: readDirectory, onReleaseOldSourceFile: onReleaseOldSourceFile, + onReleaseParsedCommandLine: onReleaseParsedCommandLine, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: hasChangedAutomaticTypeDirectiveNames, - trace: ts.maybeBind(host, host.trace), + trace: parseConfigHost.trace, resolveModuleNames: ts.maybeBind(host, host.resolveModuleNames), resolveTypeReferenceDirectives: ts.maybeBind(host, host.resolveTypeReferenceDirectives), useSourceOfProjectReferenceRedirect: ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect), + getParsedCommandLine: getParsedCommandLine, }; - (_b = host.setCompilerHost) === null || _b === void 0 ? void 0 : _b.call(host, compilerHost); + (_c = host.setCompilerHost) === null || _c === void 0 ? void 0 : _c.call(host, compilerHost); var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); var options = { rootNames: rootFileNames, @@ -148595,6 +153172,7 @@ var ts; // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. // It needs to be cleared to allow all collected snapshots to be released hostCache = undefined; + parsedCommandLines = undefined; // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during // the course of whatever called `synchronizeHostData` @@ -148603,6 +153181,36 @@ var ts; // pointers set property. program.getTypeChecker(); return; + function getParsedCommandLine(fileName) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var existing = parsedCommandLines === null || parsedCommandLines === void 0 ? void 0 : parsedCommandLines.get(path); + if (existing !== undefined) + return existing || undefined; + var result = host.getParsedCommandLine ? + host.getParsedCommandLine(fileName) : + getParsedCommandLineOfConfigFileUsingSourceFile(fileName); + (parsedCommandLines || (parsedCommandLines = new ts.Map())).set(path, result || false); + return result; + } + function getParsedCommandLineOfConfigFileUsingSourceFile(configFileName) { + var result = getOrCreateSourceFile(configFileName, 100 /* JSON */); + if (!result) + return undefined; + result.path = ts.toPath(configFileName, currentDirectory, getCanonicalFileName); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; + return ts.parseJsonSourceFileConfigFileContent(result, parseConfigHost, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), + /*optionsToExtend*/ undefined, ts.getNormalizedAbsolutePath(configFileName, currentDirectory)); + } + function onReleaseParsedCommandLine(configFileName, oldResolvedRef, oldOptions) { + var _a; + if (host.getParsedCommandLine) { + (_a = host.onReleaseParsedCommandLine) === null || _a === void 0 ? void 0 : _a.call(host, configFileName, oldResolvedRef, oldOptions); + } + else if (oldResolvedRef) { + onReleaseOldSourceFile(oldResolvedRef.sourceFile, oldOptions); + } + } function fileExists(fileName) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = hostCache && hostCache.getEntryByPath(path); @@ -148619,11 +153227,15 @@ var ts; } return host.readFile && host.readFile(fileName); } + function readDirectory(path, extensions, exclude, include, depth) { + ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + } // Release any files we have acquired in the old program but are // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind); } function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); @@ -148668,8 +153280,13 @@ var ts; // We do not support the scenario where a host can modify a registered // file's script kind, i.e. in one project some file is treated as ".ts" // and in another as ".js" - ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind."); - return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + if (hostFileInformation.scriptKind === oldSourceFile.scriptKind) { + return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + } + else { + // Release old source file and fall through to aquire new file with new script kind + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind); + } } // We didn't already have the file. Fall through and acquire it from the registry. } @@ -148698,7 +153315,7 @@ var ts; // Use paths to ensure we are using correct key and paths as document registry could be created with different current directory than host var key_1 = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()); ts.forEach(program.getSourceFiles(), function (f) { - return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1); + return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1, f.scriptKind); }); program = undefined; // TODO: GH#18217 } @@ -148741,10 +153358,10 @@ var ts; synchronizeHostData(); return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter); } - function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { + function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences, data) { if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions, host)), // TODO: GH#18217 + return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source, data: data }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions, host)), // TODO: GH#18217 preferences, cancellationToken); } function getCompletionEntrySymbol(fileName, position, name, source, preferences) { @@ -148771,7 +153388,7 @@ var ts; textSpan: ts.createTextSpanFromNode(nodeForQuickInfo, sourceFile), displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_2, ts.getContainerNode(nodeForQuickInfo)); }), documentation: type_2.symbol ? type_2.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_2.symbol ? type_2.symbol.getJsDocTags() : undefined + tags: type_2.symbol ? type_2.symbol.getJsDocTags(typeChecker) : undefined }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { @@ -148790,19 +153407,23 @@ var ts; if (ts.isNewExpression(node.parent) && node.pos === node.parent.pos) { return node.parent.expression; } + if (ts.isNamedTupleMember(node.parent) && node.pos === node.parent.pos) { + return node.parent; + } return node; } function shouldGetType(sourceFile, node, position) { switch (node.kind) { case 78 /* Identifier */: - return !ts.isLabelName(node) && !ts.isTagName(node); - case 201 /* PropertyAccessExpression */: - case 157 /* QualifiedName */: + return !ts.isLabelName(node) && !ts.isTagName(node) && !ts.isConstTypeReference(node.parent); + case 202 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: // Don't return quickInfo if inside the comment in `a/**/.b` return !ts.isInComment(sourceFile, position); case 107 /* ThisKeyword */: - case 187 /* ThisType */: + case 188 /* ThisType */: case 105 /* SuperKeyword */: + case 193 /* NamedTupleMember */: return true; default: return false; @@ -148907,15 +153528,15 @@ var ts; return undefined; } switch (node.kind) { - case 201 /* PropertyAccessExpression */: - case 157 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: case 10 /* StringLiteral */: case 94 /* FalseKeyword */: case 109 /* TrueKeyword */: case 103 /* NullKeyword */: case 105 /* SuperKeyword */: case 107 /* ThisKeyword */: - case 187 /* ThisType */: + case 188 /* ThisType */: case 78 /* Identifier */: break; // Cant create the text span @@ -148932,7 +153553,7 @@ var ts; // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module - if (nodeForStartPos.parent.parent.kind === 256 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 257 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -148960,15 +153581,7 @@ var ts; function getNavigationTree(fileName) { return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); } - function isTsOrTsxFile(fileName) { - var kind = ts.getScriptKind(fileName, host); - return kind === 3 /* TS */ || kind === 4 /* TSX */; - } function getSemanticClassifications(fileName, span, format) { - if (!isTsOrTsxFile(fileName)) { - // do not run semantic classification on non-ts-or-tsx files - return []; - } synchronizeHostData(); var responseFormat = format || "original" /* Original */; if (responseFormat === "2020" /* TwentyTwenty */) { @@ -148979,10 +153592,6 @@ var ts; } } function getEncodedSemanticClassifications(fileName, span, format) { - if (!isTsOrTsxFile(fileName)) { - // do not run semantic classification on non-ts-or-tsx files - return { spans: [], endOfLineState: 0 /* None */ }; - } synchronizeHostData(); var responseFormat = format || "original" /* Original */; if (responseFormat === "original" /* Original */) { @@ -149073,13 +153682,13 @@ var ts; var formatContext = ts.formatting.getFormatContext(formatOptions, host); return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } - function organizeImports(scope, formatOptions, preferences) { + function organizeImports(args, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); - ts.Debug.assert(scope.type === "file"); - var sourceFile = getValidSourceFile(scope.fileName); + ts.Debug.assert(args.type === "file"); + var sourceFile = getValidSourceFile(args.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions, host); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, args.skipDestructiveCodeActions); } function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } @@ -149096,8 +153705,8 @@ var ts; ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); } - function getDocCommentTemplateAtPosition(fileName, position) { - return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); + function getDocCommentTemplateAtPosition(fileName, position, options) { + return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position, options); } function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too @@ -149512,6 +154121,16 @@ var ts; var file = getValidSourceFile(fileName); return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName); } + function toLineColumnOffset(fileName, position) { + // Go to Definition supports returning a zero-length span at position 0 for + // non-existent files. We need to special-case the conversion of position 0 + // to avoid a crash trying to get the text for that file, since this function + // otherwise assumes that 'fileName' is the name of a file that exists. + if (position === 0) { + return { line: 0, character: 0 }; + } + return sourceMapper.toLineColumnOffset(fileName, position); + } function prepareCallHierarchy(fileName, position) { synchronizeHostData(); var declarations = ts.CallHierarchy.resolveCallHierarchyDeclaration(program, ts.getTouchingPropertyName(getValidSourceFile(fileName), position)); @@ -149584,7 +154203,7 @@ var ts; getAutoImportProvider: getAutoImportProvider, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, - toLineColumnOffset: sourceMapper.toLineColumnOffset, + toLineColumnOffset: toLineColumnOffset, getSourceMapper: function () { return sourceMapper; }, clearSourceMapperCache: function () { return sourceMapper.clearCache(); }, prepareCallHierarchy: prepareCallHierarchy, @@ -149655,7 +154274,7 @@ var ts; */ function literalIsName(node) { return ts.isDeclarationName(node) || - node.parent.kind === 272 /* ExternalModuleReference */ || + node.parent.kind === 273 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } @@ -149673,13 +154292,13 @@ var ts; case 10 /* StringLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: - if (node.parent.kind === 158 /* ComputedPropertyName */) { + if (node.parent.kind === 159 /* ComputedPropertyName */) { return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through case 78 /* Identifier */: return ts.isObjectLiteralElement(node.parent) && - (node.parent.parent.kind === 200 /* ObjectLiteralExpression */ || node.parent.parent.kind === 281 /* JsxAttributes */) && + (node.parent.parent.kind === 201 /* ObjectLiteralExpression */ || node.parent.parent.kind === 282 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } return undefined; @@ -149721,7 +154340,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 202 /* ElementAccessExpression */ && + node.parent.kind === 203 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /** @@ -149801,114 +154420,114 @@ var ts; if (node) { var parent = node.parent; switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 249 /* VariableDeclaration */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 250 /* VariableDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return spanInVariableDeclaration(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return spanInParameterDeclaration(node); - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 166 /* Constructor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 167 /* Constructor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 230 /* Block */: + case 231 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // falls through - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return spanInBlock(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return spanInBlock(node.block); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: // Span on while(...) return textSpanEndingAtNextToken(node, node.expression); - case 235 /* DoStatement */: + case 236 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 248 /* DebuggerStatement */: + case 249 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 234 /* IfStatement */: + case 235 /* IfStatement */: // set on if(..) span return textSpanEndingAtNextToken(node, node.expression); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return spanInForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: // span of for (a in ...) return textSpanEndingAtNextToken(node, node.expression); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: // span in initializer return spanInInitializerOfForLike(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: // span on switch(...) return textSpanEndingAtNextToken(node, node.expression); - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 247 /* TryStatement */: + case 248 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } // falls through - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: - case 198 /* BindingElement */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: + case 199 /* BindingElement */: // span on complete node return textSpan(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: // span in statement return spanInNode(node.statement); - case 161 /* Decorator */: + case 162 /* Decorator */: return spanInNodeArray(parent.decorators); - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return undefined; // Tokens: case 26 /* SemicolonToken */: @@ -149938,7 +154557,7 @@ var ts; case 82 /* CatchKeyword */: case 95 /* FinallyKeyword */: return spanInNextNode(node); - case 156 /* OfKeyword */: + case 157 /* OfKeyword */: return spanInOfKeyword(node); default: // Destructuring pattern in destructuring assignment @@ -149951,13 +154570,13 @@ var ts; // `a` or `...c` or `d: x` from // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern if ((node.kind === 78 /* Identifier */ || - node.kind === 220 /* SpreadElement */ || - node.kind === 288 /* PropertyAssignment */ || - node.kind === 289 /* ShorthandPropertyAssignment */) && + node.kind === 221 /* SpreadElement */ || + node.kind === 289 /* PropertyAssignment */ || + node.kind === 290 /* ShorthandPropertyAssignment */) && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { return textSpan(node); } - if (node.kind === 216 /* BinaryExpression */) { + if (node.kind === 217 /* BinaryExpression */) { var _a = node, left = _a.left, operatorToken = _a.operatorToken; // Set breakpoint in destructuring pattern if its destructuring assignment // [a, b, c] or {a, b, c} of @@ -149979,22 +154598,22 @@ var ts; } if (ts.isExpressionNode(node)) { switch (parent.kind) { - case 235 /* DoStatement */: + case 236 /* DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); - case 161 /* Decorator */: + case 162 /* Decorator */: // Set breakpoint on the decorator emit return spanInNode(node.parent); - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: return textSpan(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (node.parent.operatorToken.kind === 27 /* CommaToken */) { // If this is a comma expression, the breakpoint is possible in this expression return textSpan(node); } break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: if (node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); @@ -150003,21 +154622,21 @@ var ts; } } switch (node.parent.kind) { - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // If this is name of property assignment, set breakpoint in the initializer if (node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } break; - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: // Breakpoint in type assertion goes to its operand if (node.parent.type === node) { return spanInNextNode(node.parent.type); } break; - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: { + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: { // initializer of variable/parameter declaration go to previous node var _b = node.parent, initializer = _b.initializer, type = _b.type; if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { @@ -150025,7 +154644,7 @@ var ts; } break; } - case 216 /* BinaryExpression */: { + case 217 /* BinaryExpression */: { var left = node.parent.left; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { // If initializer of destructuring assignment move to previous token @@ -150055,7 +154674,7 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 238 /* ForInStatement */) { + if (variableDeclaration.parent.parent.kind === 239 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } var parent = variableDeclaration.parent; @@ -150067,7 +154686,7 @@ var ts; // or its declaration from 'for of' if (variableDeclaration.initializer || ts.hasSyntacticModifier(variableDeclaration, 1 /* Export */) || - parent.parent.kind === 239 /* ForOfStatement */) { + parent.parent.kind === 240 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } if (ts.isVariableDeclarationList(variableDeclaration.parent) && @@ -150108,7 +154727,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasSyntacticModifier(functionDeclaration, 1 /* Export */) || - (functionDeclaration.parent.kind === 252 /* ClassDeclaration */ && functionDeclaration.kind !== 166 /* Constructor */); + (functionDeclaration.parent.kind === 253 /* ClassDeclaration */ && functionDeclaration.kind !== 167 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -150131,26 +154750,26 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // Set on parent if on same line otherwise on first statement // falls through - case 236 /* WhileStatement */: - case 234 /* IfStatement */: - case 238 /* ForInStatement */: + case 237 /* WhileStatement */: + case 235 /* IfStatement */: + case 239 /* ForInStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); // Set span on previous token if it starts on same line otherwise on the first statement of the block - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement return spanInNode(block.statements[0]); } function spanInInitializerOfForLike(forLikeStatement) { - if (forLikeStatement.initializer.kind === 250 /* VariableDeclarationList */) { + if (forLikeStatement.initializer.kind === 251 /* VariableDeclarationList */) { // Declaration list - set breakpoint in first declaration var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -150175,21 +154794,21 @@ var ts; } function spanInBindingPattern(bindingPattern) { // Set breakpoint in first binding element - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 222 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 223 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } // Empty binding pattern of binding element, set breakpoint on binding element - if (bindingPattern.parent.kind === 198 /* BindingElement */) { + if (bindingPattern.parent.kind === 199 /* BindingElement */) { return textSpan(bindingPattern.parent); } // Variable declaration is used as the span return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 197 /* ArrayBindingPattern */ && node.kind !== 196 /* ObjectBindingPattern */); - var elements = node.kind === 199 /* ArrayLiteralExpression */ ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 222 /* OmittedExpression */ ? element : undefined; }); + ts.Debug.assert(node.kind !== 198 /* ArrayBindingPattern */ && node.kind !== 197 /* ObjectBindingPattern */); + var elements = node.kind === 200 /* ArrayLiteralExpression */ ? node.elements : node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 223 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -150197,18 +154816,18 @@ var ts; // just nested element in another destructuring assignment // set breakpoint on assignment when parent is destructuring assignment // Otherwise set breakpoint for this element - return textSpan(node.parent.kind === 216 /* BinaryExpression */ ? node.parent : node); + return textSpan(node.parent.kind === 217 /* BinaryExpression */ ? node.parent : node); } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -150216,25 +154835,25 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: // If this is not an instantiated module block, no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } // falls through - case 255 /* EnumDeclaration */: - case 252 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 253 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 230 /* Block */: + case 231 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // falls through - case 287 /* CatchClause */: + case 288 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -150242,7 +154861,7 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 196 /* ObjectBindingPattern */: + case 197 /* ObjectBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -150258,7 +154877,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -150273,12 +154892,12 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 235 /* DoStatement */ || // Go to while keyword and do action instead - node.parent.kind === 203 /* CallExpression */ || - node.parent.kind === 204 /* NewExpression */) { + if (node.parent.kind === 236 /* DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 204 /* CallExpression */ || + node.parent.kind === 205 /* NewExpression */) { return spanInPreviousNode(node); } - if (node.parent.kind === 207 /* ParenthesizedExpression */) { + if (node.parent.kind === 208 /* ParenthesizedExpression */) { return spanInNextNode(node); } // Default to parent node @@ -150287,21 +154906,21 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 166 /* Constructor */: - case 236 /* WhileStatement */: - case 235 /* DoStatement */: - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 207 /* ParenthesizedExpression */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 167 /* Constructor */: + case 237 /* WhileStatement */: + case 236 /* DoStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 208 /* ParenthesizedExpression */: return spanInPreviousNode(node); // Default to parent node default: @@ -150311,20 +154930,20 @@ var ts; function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration if (ts.isFunctionLike(node.parent) || - node.parent.kind === 288 /* PropertyAssignment */ || - node.parent.kind === 160 /* Parameter */) { + node.parent.kind === 289 /* PropertyAssignment */ || + node.parent.kind === 161 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 206 /* TypeAssertionExpression */) { + if (node.parent.kind === 207 /* TypeAssertionExpression */) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 235 /* DoStatement */) { + if (node.parent.kind === 236 /* DoStatement */) { // Set span on while expression return textSpanEndingAtNextToken(node, node.parent.expression); } @@ -150332,7 +154951,7 @@ var ts; return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 239 /* ForOfStatement */) { + if (node.parent.kind === 240 /* ForOfStatement */) { // Set using next token return spanInNextNode(node); } @@ -150873,11 +155492,11 @@ var ts; return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); }); }; /** Get a string based representation of a completion list entry details */ - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences, data) { var _this = this; return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions); - return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences, data); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { @@ -150901,9 +155520,9 @@ var ts; return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); }); }; - LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { + LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); }); + return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position, options); }); }; /// NAVIGATE TO /** Return a list of symbols that are interesting to navigate to */ @@ -151985,6 +156604,7 @@ var ts; WatchFileKind["FixedPollingInterval"] = "FixedPollingInterval"; WatchFileKind["PriorityPollingInterval"] = "PriorityPollingInterval"; WatchFileKind["DynamicPriorityPolling"] = "DynamicPriorityPolling"; + WatchFileKind["FixedChunkSizePolling"] = "FixedChunkSizePolling"; WatchFileKind["UseFsEvents"] = "UseFsEvents"; WatchFileKind["UseFsEventsOnParentDirectory"] = "UseFsEventsOnParentDirectory"; })(WatchFileKind = protocol.WatchFileKind || (protocol.WatchFileKind = {})); @@ -151993,12 +156613,14 @@ var ts; WatchDirectoryKind["UseFsEvents"] = "UseFsEvents"; WatchDirectoryKind["FixedPollingInterval"] = "FixedPollingInterval"; WatchDirectoryKind["DynamicPriorityPolling"] = "DynamicPriorityPolling"; + WatchDirectoryKind["FixedChunkSizePolling"] = "FixedChunkSizePolling"; })(WatchDirectoryKind = protocol.WatchDirectoryKind || (protocol.WatchDirectoryKind = {})); var PollingWatchKind; (function (PollingWatchKind) { PollingWatchKind["FixedInterval"] = "FixedInterval"; PollingWatchKind["PriorityInterval"] = "PriorityInterval"; PollingWatchKind["DynamicPriority"] = "DynamicPriority"; + PollingWatchKind["FixedChunkSize"] = "FixedChunkSize"; })(PollingWatchKind = protocol.PollingWatchKind || (protocol.PollingWatchKind = {})); var IndentStyle; (function (IndentStyle) { @@ -152051,8 +156673,37 @@ var ts; ScriptTarget["ES2018"] = "ES2018"; ScriptTarget["ES2019"] = "ES2019"; ScriptTarget["ES2020"] = "ES2020"; + ScriptTarget["ES2021"] = "ES2021"; ScriptTarget["ESNext"] = "ESNext"; })(ScriptTarget = protocol.ScriptTarget || (protocol.ScriptTarget = {})); + var ClassificationType; + (function (ClassificationType) { + ClassificationType[ClassificationType["comment"] = 1] = "comment"; + ClassificationType[ClassificationType["identifier"] = 2] = "identifier"; + ClassificationType[ClassificationType["keyword"] = 3] = "keyword"; + ClassificationType[ClassificationType["numericLiteral"] = 4] = "numericLiteral"; + ClassificationType[ClassificationType["operator"] = 5] = "operator"; + ClassificationType[ClassificationType["stringLiteral"] = 6] = "stringLiteral"; + ClassificationType[ClassificationType["regularExpressionLiteral"] = 7] = "regularExpressionLiteral"; + ClassificationType[ClassificationType["whiteSpace"] = 8] = "whiteSpace"; + ClassificationType[ClassificationType["text"] = 9] = "text"; + ClassificationType[ClassificationType["punctuation"] = 10] = "punctuation"; + ClassificationType[ClassificationType["className"] = 11] = "className"; + ClassificationType[ClassificationType["enumName"] = 12] = "enumName"; + ClassificationType[ClassificationType["interfaceName"] = 13] = "interfaceName"; + ClassificationType[ClassificationType["moduleName"] = 14] = "moduleName"; + ClassificationType[ClassificationType["typeParameterName"] = 15] = "typeParameterName"; + ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName"; + ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName"; + ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName"; + ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName"; + ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName"; + ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName"; + ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; + ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; + ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; + ClassificationType[ClassificationType["bigintLiteral"] = 25] = "bigintLiteral"; + })(ClassificationType = protocol.ClassificationType || (protocol.ClassificationType = {})); })(protocol = server.protocol || (server.protocol = {})); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); @@ -152248,7 +156899,7 @@ var ts; if (this.pendingReloadFromDisk) { this.reloadWithFileText(); } - // At this point if svc is present its valid + // At this point if svc is present it's valid return this.svc; }; TextStorage.prototype.getOrLoadText = function () { @@ -152364,16 +157015,24 @@ var ts; ScriptInfo.prototype.getRealpathIfDifferent = function () { return this.realpath && this.realpath !== this.path ? this.realpath : undefined; }; + /** + * @internal + * Does not compute realpath; uses precomputed result. Use `ensureRealPath` + * first if a definite result is needed. + */ + ScriptInfo.prototype.isSymlink = function () { + return this.realpath && this.realpath !== this.path; + }; ScriptInfo.prototype.getFormatCodeSettings = function () { return this.formatSettings; }; ScriptInfo.prototype.getPreferences = function () { return this.preferences; }; ScriptInfo.prototype.attachToProject = function (project) { var isNew = !this.isAttached(project); if (isNew) { this.containingProjects.push(project); - project.onFileAddedOrRemoved(); if (!project.getCompilerOptions().preserveSymlinks) { this.ensureRealPath(); } + project.onFileAddedOrRemoved(this.isSymlink()); } return isNew; }; @@ -152393,23 +157052,23 @@ var ts; return; case 1: if (this.containingProjects[0] === project) { - project.onFileAddedOrRemoved(); + project.onFileAddedOrRemoved(this.isSymlink()); this.containingProjects.pop(); } break; case 2: if (this.containingProjects[0] === project) { - project.onFileAddedOrRemoved(); + project.onFileAddedOrRemoved(this.isSymlink()); this.containingProjects[0] = this.containingProjects.pop(); } else if (this.containingProjects[1] === project) { - project.onFileAddedOrRemoved(); + project.onFileAddedOrRemoved(this.isSymlink()); this.containingProjects.pop(); } break; default: if (ts.unorderedRemoveItem(this.containingProjects, project)) { - project.onFileAddedOrRemoved(); + project.onFileAddedOrRemoved(this.isSymlink()); } break; } @@ -152423,6 +157082,7 @@ var ts; var existingRoot = p.getRootFilesMap().get(this.path); // detach is unnecessary since we'll clean the list of containing projects anyways p.removeFile(this, /*fileExists*/ false, /*detachFromProjects*/ false); + p.onFileAddedOrRemoved(this.isSymlink()); // If the info was for the external or configured project's root, // add missing file as the root if (existingRoot && !server.isInferredProject(p)) { @@ -152819,6 +157479,8 @@ var ts; this.cachedUnresolvedImportsPerFile = new ts.Map(); /*@internal*/ this.hasAddedorRemovedFiles = false; + /*@internal*/ + this.hasAddedOrRemovedSymlinks = false; /** * Last version that was reported. */ @@ -152841,7 +157503,9 @@ var ts; /*@internal*/ this.typingFiles = server.emptyArray; /*@internal*/ - this.importSuggestionsCache = ts.Completions.createImportSuggestionsForFileCache(); + this.exportMapCache = ts.createExportMapCache(); + /*@internal*/ + this.moduleSpecifierCache = ts.createModuleSpecifierCache(); /*@internal*/ this.globalCacheResolutionModuleName = ts.JsTyping.nonRelativeModuleNameForTypingCache; this.directoryStructureHost = directoryStructureHost; @@ -153164,7 +157828,7 @@ var ts; return []; } server.updateProjectIfDirty(this); - this.builderState = ts.BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState); + this.builderState = ts.BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState, /*disableUseFileVersionAsSignature*/ true); return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, ts.maybeBind(this.projectService.host, this.projectService.host.createHash)), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); }; /** @@ -153467,8 +158131,8 @@ var ts; /*@internal*/ Project.prototype.markFileAsDirty = function (changedFile) { this.markAsDirty(); - if (!this.importSuggestionsCache.isEmpty()) { - (this.dirtyFilesForSuggestions || (this.dirtyFilesForSuggestions = new ts.Set())).add(changedFile); + if (!this.exportMapCache.isEmpty()) { + (this.changedFilesForExportMapCache || (this.changedFilesForExportMapCache = new ts.Set())).add(changedFile); } }; Project.prototype.markAsDirty = function () { @@ -153478,17 +158142,31 @@ var ts; } }; /*@internal*/ - Project.prototype.markAutoImportProviderAsDirty = function () { + Project.prototype.onAutoImportProviderSettingsChanged = function () { var _a; if (this.autoImportProviderHost === false) { this.autoImportProviderHost = undefined; } - (_a = this.autoImportProviderHost) === null || _a === void 0 ? void 0 : _a.markAsDirty(); - this.importSuggestionsCache.clear(); + else { + (_a = this.autoImportProviderHost) === null || _a === void 0 ? void 0 : _a.markAsDirty(); + } + }; + /*@internal*/ + Project.prototype.onPackageJsonChange = function (packageJsonPath) { + var _a; + if ((_a = this.packageJsonsForAutoImport) === null || _a === void 0 ? void 0 : _a.has(packageJsonPath)) { + this.moduleSpecifierCache.clear(); + if (this.autoImportProviderHost) { + this.autoImportProviderHost.markAsDirty(); + } + } }; /* @internal */ - Project.prototype.onFileAddedOrRemoved = function () { + Project.prototype.onFileAddedOrRemoved = function (isSymlink) { this.hasAddedorRemovedFiles = true; + if (isSymlink) { + this.hasAddedOrRemovedSymlinks = true; + } }; /** * Updates set of files that contribute to this project @@ -153501,6 +158179,7 @@ var ts; var hasNewProgram = this.updateGraphWorker(); var hasAddedorRemovedFiles = this.hasAddedorRemovedFiles; this.hasAddedorRemovedFiles = false; + this.hasAddedOrRemovedSymlinks = false; var changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || server.emptyArray; for (var _i = 0, changedFiles_1 = changedFiles; _i < changedFiles_1.length; _i++) { var file = changedFiles_1[_i]; @@ -153543,11 +158222,14 @@ var ts; /*@internal*/ Project.prototype.updateTypingFiles = function (typingFiles) { var _this = this; - ts.enumerateInsertsAndDeletes(typingFiles, this.typingFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), - /*inserted*/ ts.noop, function (removed) { return _this.detachScriptInfoFromProject(removed); }); - this.typingFiles = typingFiles; - // Invalidate files with unresolved imports - this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile); + if (ts.enumerateInsertsAndDeletes(typingFiles, this.typingFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), + /*inserted*/ ts.noop, function (removed) { return _this.detachScriptInfoFromProject(removed); })) { + // If typing files changed, then only schedule project update + this.typingFiles = typingFiles; + // Invalidate files with unresolved imports + this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile); + this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); + } }; /* @internal */ Project.prototype.getCurrentProgram = function () { @@ -153559,6 +158241,7 @@ var ts; }; Project.prototype.updateGraphWorker = function () { var _this = this; + var _a; var oldProgram = this.program; ts.Debug.assert(!this.isClosed(), "Called update graph worker of closed project"); this.writeLog("Starting updateGraphWorker: Project: " + this.getProjectName()); @@ -153572,11 +158255,12 @@ var ts; // bump up the version if // - oldProgram is not set - this is a first time updateGraph is called // - newProgram is different from the old program and structure of the old program was not reused. - var hasNewProgram = this.program && (!oldProgram || (this.program !== oldProgram && !(this.program.structureIsReused & 2 /* Completely */))); - if (hasNewProgram) { + var hasNewProgram = false; + if (this.program && (!oldProgram || (this.program !== oldProgram && this.program.structureIsReused !== 2 /* Completely */))) { + hasNewProgram = true; if (oldProgram) { - for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { - var f = _a[_i]; + for (var _i = 0, _b = oldProgram.getSourceFiles(); _i < _b.length; _i++) { + var f = _b[_i]; var newFile = this.program.getSourceFileByPath(f.resolvedPath); if (!newFile || (f.resolvedPath === f.path && newFile.resolvedPath !== f.path)) { // new program does not contain this file - detach it from the project @@ -153625,26 +158309,29 @@ var ts; this.resolutionCache.updateTypeRootsWatch(); } } - if (!this.importSuggestionsCache.isEmpty()) { + if (!this.exportMapCache.isEmpty()) { if (this.hasAddedorRemovedFiles || oldProgram && !this.program.structureIsReused) { - this.importSuggestionsCache.clear(); - } - else if (this.dirtyFilesForSuggestions && oldProgram && this.program) { - ts.forEachKey(this.dirtyFilesForSuggestions, function (fileName) { - var oldSourceFile = oldProgram.getSourceFile(fileName); - var sourceFile = _this.program.getSourceFile(fileName); - if (_this.sourceFileHasChangedOwnImportSuggestions(oldSourceFile, sourceFile)) { - _this.importSuggestionsCache.clear(); + this.exportMapCache.clear(); + } + else if (this.changedFilesForExportMapCache && oldProgram && this.program) { + ts.forEachKey(this.changedFilesForExportMapCache, function (fileName) { + var oldSourceFile = oldProgram.getSourceFileByPath(fileName); + var sourceFile = _this.program.getSourceFileByPath(fileName); + if (!oldSourceFile || !sourceFile) { + _this.exportMapCache.clear(); return true; } + return _this.exportMapCache.onFileChanged(oldSourceFile, sourceFile, !!_this.getTypeAcquisition().enable); }); } } - if (this.dirtyFilesForSuggestions) { - this.dirtyFilesForSuggestions.clear(); + if (this.changedFilesForExportMapCache) { + this.changedFilesForExportMapCache.clear(); } - if (this.hasAddedorRemovedFiles) { + if (this.hasAddedOrRemovedSymlinks || this.program && !this.program.structureIsReused && this.getCompilerOptions().preserveSymlinks) { + // With --preserveSymlinks, we may not determine that a file is a symlink, so we never set `hasAddedOrRemovedSymlinks` this.symlinks = undefined; + this.moduleSpecifierCache.clear(); } var oldExternalFiles = this.externalFiles || server.emptyArray; this.externalFiles = this.getExternalFiles(); @@ -153663,7 +158350,7 @@ var ts; this.print(/*writeProjectFileNames*/ true); } else if (this.program !== oldProgram) { - this.writeLog("Different program with same set of files:: structureIsReused:: " + this.program.structureIsReused); + this.writeLog("Different program with same set of files:: structureIsReused:: " + ((_a = this.program) === null || _a === void 0 ? void 0 : _a.structureIsReused)); } return hasNewProgram; }; @@ -153671,54 +158358,6 @@ var ts; Project.prototype.sendPerformanceEvent = function (kind, durationMs) { this.projectService.sendPerformanceEvent(kind, durationMs); }; - /*@internal*/ - Project.prototype.sourceFileHasChangedOwnImportSuggestions = function (oldSourceFile, newSourceFile) { - if (!oldSourceFile && !newSourceFile) { - return false; - } - // Probably shouldn’t get this far, but on the off chance the file was added or removed, - // we can’t reliably tell anything about it. - if (!oldSourceFile || !newSourceFile) { - return true; - } - ts.Debug.assertEqual(oldSourceFile.fileName, newSourceFile.fileName); - // If ATA is enabled, auto-imports uses existing imports to guess whether you want auto-imports from node. - // Adding or removing imports from node could change the outcome of that guess, so could change the suggestions list. - if (this.getTypeAcquisition().enable && ts.consumesNodeCoreModules(oldSourceFile) !== ts.consumesNodeCoreModules(newSourceFile)) { - return true; - } - // Module agumentation and ambient module changes can add or remove exports available to be auto-imported. - // Changes elsewhere in the file can change the *type* of an export in a module augmentation, - // but type info is gathered in getCompletionEntryDetails, which doesn’t use the cache. - if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations) || - !this.ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile)) { - return true; - } - return false; - }; - /*@internal*/ - Project.prototype.ambientModuleDeclarationsAreEqual = function (oldSourceFile, newSourceFile) { - if (!ts.arrayIsEqualTo(oldSourceFile.ambientModuleNames, newSourceFile.ambientModuleNames)) { - return false; - } - var oldFileStatementIndex = -1; - var newFileStatementIndex = -1; - var _loop_1 = function (ambientModuleName) { - var isMatchingModuleDeclaration = function (node) { return ts.isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName; }; - oldFileStatementIndex = ts.findIndex(oldSourceFile.statements, isMatchingModuleDeclaration, oldFileStatementIndex + 1); - newFileStatementIndex = ts.findIndex(newSourceFile.statements, isMatchingModuleDeclaration, newFileStatementIndex + 1); - if (oldSourceFile.statements[oldFileStatementIndex] !== newSourceFile.statements[newFileStatementIndex]) { - return { value: false }; - } - }; - for (var _i = 0, _a = newSourceFile.ambientModuleNames; _i < _a.length; _i++) { - var ambientModuleName = _a[_i]; - var state_1 = _loop_1(ambientModuleName); - if (typeof state_1 === "object") - return state_1.value; - } - return true; - }; Project.prototype.detachScriptInfoFromProject = function (uncheckedFileName, noRemoveResolution) { var scriptInfoToDetach = this.projectService.getScriptInfo(uncheckedFileName); if (scriptInfoToDetach) { @@ -153730,6 +158369,13 @@ var ts; }; Project.prototype.addMissingFileWatcher = function (missingFilePath) { var _this = this; + var _a; + if (isConfiguredProject(this)) { + // If this file is referenced config file, we are already watching it, no need to watch again + var configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(missingFilePath); + if ((_a = configFileExistenceInfo === null || configFileExistenceInfo === void 0 ? void 0 : configFileExistenceInfo.config) === null || _a === void 0 ? void 0 : _a.projects.has(this.canonicalConfigFilePath)) + return ts.noopFileWatcher; + } var fileWatcher = this.projectService.watchFactory.watchFile(missingFilePath, function (fileName, eventKind) { if (isConfiguredProject(_this)) { _this.getCachedDirectoryStructureHost().addOrDeleteFile(fileName, missingFilePath, eventKind); @@ -153977,7 +158623,7 @@ var ts; ts.combinePaths(this.projectService.getExecutingFilePath(), "../../.."), ]); if (this.projectService.globalPlugins) { - var _loop_2 = function (globalPluginName) { + var _loop_1 = function (globalPluginName) { // Skip empty names from odd commandline parses if (!globalPluginName) return "continue"; @@ -153992,13 +158638,17 @@ 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_2(globalPluginName); + _loop_1(globalPluginName); } } }; Project.prototype.enablePlugin = function (pluginConfigEntry, searchPaths, pluginConfigOverrides) { var _this = this; this.projectService.logger.info("Enabling plugin " + pluginConfigEntry.name + " from candidate paths: " + searchPaths.join(",")); + if (!pluginConfigEntry.name || ts.parsePackageName(pluginConfigEntry.name).rest) { + this.projectService.logger.info("Skipped loading plugin " + (pluginConfigEntry.name || JSON.stringify(pluginConfigEntry)) + " because only package name is allowed plugin name"); + return; + } var log = function (message) { return _this.projectService.logger.info(message); }; var errorLogs; var logError = function (message) { (errorLogs || (errorLogs = [])).push(message); }; @@ -154043,7 +158693,7 @@ var ts; newLS[k] = this.languageService[k]; } } - this.projectService.logger.info("Plugin validation succeded"); + this.projectService.logger.info("Plugin validation succeeded"); this.languageService = newLS; this.plugins.push({ name: configEntry.name, module: pluginModule }); } @@ -154080,8 +158730,12 @@ var ts; return packageJsons; }; /*@internal*/ - Project.prototype.getImportSuggestionsCache = function () { - return this.importSuggestionsCache; + Project.prototype.getExportMapCache = function () { + return this.exportMapCache; + }; + /*@internal*/ + Project.prototype.getModuleSpecifierCache = function () { + return this.moduleSpecifierCache; }; /*@internal*/ Project.prototype.includePackageJsonAutoImports = function () { @@ -154269,11 +158923,13 @@ var ts; /*compileOnSaveEnabled*/ false, hostProject.getWatchOptions(), hostProject.projectService.host, hostProject.currentDirectory) || this; _this.hostProject = hostProject; _this.rootFileNames = initialRootNames; + _this.useSourceOfProjectReferenceRedirect = ts.maybeBind(_this.hostProject, _this.hostProject.useSourceOfProjectReferenceRedirect); + _this.getParsedCommandLine = ts.maybeBind(_this.hostProject, _this.hostProject.getParsedCommandLine); return _this; } /*@internal*/ AutoImportProviderProject.getRootFileNames = function (dependencySelection, hostProject, moduleResolutionHost, compilerOptions) { - var _a, _b, _c, _d; + var _a, _b, _c; if (!dependencySelection) { return ts.emptyArray; } @@ -154288,18 +158944,22 @@ var ts; } if (dependencyNames) { var resolutions = ts.map(ts.arrayFrom(dependencyNames.keys()), function (name) { return ts.resolveTypeReferenceDirective(name, rootFileName, compilerOptions, moduleResolutionHost); }); - for (var _e = 0, resolutions_1 = resolutions; _e < resolutions_1.length; _e++) { - var resolution = resolutions_1[_e]; + var program = hostProject.getCurrentProgram(); + var symlinkCache = hostProject.getSymlinkCache(); + for (var _d = 0, resolutions_1 = resolutions; _d < resolutions_1.length; _d++) { + var resolution = resolutions_1[_d]; if (!((_c = resolution.resolvedTypeReferenceDirective) === null || _c === void 0 ? void 0 : _c.resolvedFileName)) continue; - var resolvedFileName = resolution.resolvedTypeReferenceDirective.resolvedFileName; - var fileName = ((_d = moduleResolutionHost.realpath) === null || _d === void 0 ? void 0 : _d.call(moduleResolutionHost, resolvedFileName)) || resolvedFileName; - if (!hostProject.getCurrentProgram().getSourceFile(fileName) && !hostProject.getCurrentProgram().getSourceFile(resolvedFileName)) { - rootNames = ts.append(rootNames, fileName); + var _e = resolution.resolvedTypeReferenceDirective, resolvedFileName = _e.resolvedFileName, originalPath = _e.originalPath; + if (!program.getSourceFile(resolvedFileName) && (!originalPath || !program.getSourceFile(originalPath))) { + rootNames = ts.append(rootNames, resolvedFileName); // Avoid creating a large project that would significantly slow down time to editor interactivity if (dependencySelection === 2 /* Auto */ && rootNames.length > this.maxDependencies) { return ts.emptyArray; } + if (originalPath) { + symlinkCache.setSymlinkedDirectoryFromSymlinkedFile(originalPath, resolvedFileName); + } } } } @@ -154336,8 +158996,12 @@ var ts; } this.projectService.setFileNamesOfAutoImportProviderProject(this, rootFileNames); this.rootFileNames = rootFileNames; - this.hostProject.getImportSuggestionsCache().clear(); - return _super.prototype.updateGraph.call(this); + var oldProgram = this.getCurrentProgram(); + var hasSameSetOfFiles = _super.prototype.updateGraph.call(this); + if (oldProgram && oldProgram !== this.getCurrentProgram()) { + this.hostProject.getExportMapCache().clear(); + } + return hasSameSetOfFiles; }; AutoImportProviderProject.prototype.hasRoots = function () { var _a; @@ -154353,18 +159017,20 @@ var ts; AutoImportProviderProject.prototype.getLanguageService = function () { throw new Error("AutoImportProviderProject language service should never be used. To get the program, use `project.getCurrentProgram()`."); }; - AutoImportProviderProject.prototype.markAutoImportProviderAsDirty = function () { + /*@internal*/ + AutoImportProviderProject.prototype.onAutoImportProviderSettingsChanged = function () { throw new Error("AutoImportProviderProject is an auto import provider; use `markAsDirty()` instead."); }; + /*@internal*/ + AutoImportProviderProject.prototype.onPackageJsonChange = function () { + throw new Error("package.json changes should be notified on an AutoImportProvider's host project"); + }; AutoImportProviderProject.prototype.getModuleResolutionHostForAutoImportProvider = function () { throw new Error("AutoImportProviderProject cannot provide its own host; use `hostProject.getModuleResolutionHostForAutomImportProvider()` instead."); }; AutoImportProviderProject.prototype.getProjectReferences = function () { return this.hostProject.getProjectReferences(); }; - AutoImportProviderProject.prototype.useSourceOfProjectReferenceRedirect = function () { - return true; - }; /*@internal*/ AutoImportProviderProject.prototype.includePackageJsonAutoImports = function () { return 0 /* Off */; @@ -154390,13 +159056,14 @@ var ts; var ConfiguredProject = /** @class */ (function (_super) { __extends(ConfiguredProject, _super); /*@internal*/ - function ConfiguredProject(configFileName, projectService, documentRegistry, cachedDirectoryStructureHost) { + function ConfiguredProject(configFileName, canonicalConfigFilePath, projectService, documentRegistry, cachedDirectoryStructureHost) { var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, /*hasExplicitListOfFiles*/ false, /*lastFileExceededProgramSize*/ undefined, /*compilerOptions*/ {}, /*compileOnSaveEnabled*/ false, /*watchOptions*/ undefined, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; + _this.canonicalConfigFilePath = canonicalConfigFilePath; /* @internal */ _this.openFileWatchTriggered = new ts.Map(); /*@internal*/ @@ -154407,7 +159074,6 @@ var ts; _this.isInitialLoadPending = ts.returnTrue; /*@internal*/ _this.sendLoadingProjectFinish = false; - _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); return _this; } /* @internal */ @@ -154423,22 +159089,30 @@ var ts; return this.languageServiceEnabled; }; /* @internal */ - ConfiguredProject.prototype.setWatchOptions = function (watchOptions) { - var oldOptions = this.getWatchOptions(); - _super.prototype.setWatchOptions.call(this, watchOptions); - // If watch options different than older options - if (this.isInitialLoadPending() && - !ts.isJsonEqual(oldOptions, this.getWatchOptions())) { - var oldWatcher = this.configFileWatcher; - this.createConfigFileWatcher(); - if (oldWatcher) - oldWatcher.close(); + ConfiguredProject.prototype.getParsedCommandLine = function (fileName) { + var configFileName = server.asNormalizedPath(ts.normalizePath(fileName)); + var canonicalConfigFilePath = server.asNormalizedPath(this.projectService.toCanonicalFileName(configFileName)); + // Ensure the config file existience info is cached + var configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!configFileExistenceInfo) { + this.projectService.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo = { exists: this.projectService.host.fileExists(configFileName) }); + } + // Ensure we have upto date parsed command line + this.projectService.ensureParsedConfigUptoDate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, this); + // Watch wild cards if LS is enabled + if (this.languageServiceEnabled && this.projectService.serverMode === ts.LanguageServiceMode.Semantic) { + this.projectService.watchWildcards(configFileName, configFileExistenceInfo, this); } + return configFileExistenceInfo.exists ? configFileExistenceInfo.config.parsedCommandLine : undefined; }; /* @internal */ - ConfiguredProject.prototype.createConfigFileWatcher = function () { - var _this = this; - this.configFileWatcher = this.projectService.watchFactory.watchFile(this.getConfigFilePath(), function (_fileName, eventKind) { return _this.projectService.onConfigChangedForConfiguredProject(_this, eventKind); }, ts.PollingInterval.High, this.projectService.getWatchOptions(this), ts.WatchType.ConfigFile, this); + ConfiguredProject.prototype.onReleaseParsedCommandLine = function (fileName) { + this.releaseParsedConfig(server.asNormalizedPath(this.projectService.toCanonicalFileName(server.asNormalizedPath(ts.normalizePath(fileName))))); + }; + /* @internal */ + ConfiguredProject.prototype.releaseParsedConfig = function (canonicalConfigFilePath) { + this.projectService.stopWatchingWildCards(canonicalConfigFilePath, this); + this.projectService.releaseParsedConfig(canonicalConfigFilePath, this); }; /** * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph @@ -154538,27 +159212,11 @@ var ts; ConfiguredProject.prototype.setProjectErrors = function (projectErrors) { this.projectErrors = projectErrors; }; - /*@internal*/ - ConfiguredProject.prototype.watchWildcards = function (wildcardDirectories) { - var _this = this; - ts.updateWatchingWildcardDirectories(this.directoriesWatchedForWildcards || (this.directoriesWatchedForWildcards = new ts.Map()), wildcardDirectories, - // Create new directory watcher - function (directory, flags) { return _this.projectService.watchWildcardDirectory(directory, flags, _this); }); - }; - /*@internal*/ - ConfiguredProject.prototype.stopWatchingWildCards = function () { - if (this.directoriesWatchedForWildcards) { - ts.clearMap(this.directoriesWatchedForWildcards, ts.closeFileWatcherOf); - this.directoriesWatchedForWildcards = undefined; - } - }; ConfiguredProject.prototype.close = function () { - if (this.configFileWatcher) { - this.configFileWatcher.close(); - this.configFileWatcher = undefined; - } - this.stopWatchingWildCards(); - this.projectService.removeProjectFromSharedExtendedConfigFileMap(this); + var _this = this; + this.projectService.configFileExistenceInfoCache.forEach(function (_configFileExistenceInfo, canonicalConfigFilePath) { + return _this.releaseParsedConfig(canonicalConfigFilePath); + }); this.projectErrors = undefined; this.openFileWatchTriggered.clear(); this.compilerHost = undefined; @@ -154588,6 +159246,7 @@ var ts; /* @internal */ ConfiguredProject.prototype.hasOpenRef = function () { var _this = this; + var _a; if (!!this.externalProjectRefCount) { return true; } @@ -154595,17 +159254,17 @@ var ts; if (this.isClosed()) { return false; } - var configFileExistenceInfo = this.projectService.getConfigFileExistenceInfo(this); + var configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(this.canonicalConfigFilePath); if (this.projectService.hasPendingProjectUpdate(this)) { // If there is pending update for this project, // we dont know if this project would be needed by any of the open files impacted by this config file // In that case keep the project alive if there are open files impacted by this project - return !!configFileExistenceInfo.openFilesImpactedByConfigFile.size; + return !!((_a = configFileExistenceInfo.openFilesImpactedByConfigFile) === null || _a === void 0 ? void 0 : _a.size); } // If there is no pending update for this project, // We know exact set of open files that get impacted by this configured project as the files in the project // 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 !!configFileExistenceInfo.openFilesImpactedByConfigFile && ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { var info = _this.projectService.getScriptInfoForPath(infoPath); return _this.containsScriptInfo(info) || !!server.forEachResolvedProjectReferenceProject(_this, info.path, function (child) { return child.containsScriptInfo(info); }, server.ProjectReferenceProjectLoadKind.Find); @@ -154728,7 +159387,7 @@ var ts; var defaultTypeSafeList = { "jquery": { // jquery files can have names like "jquery-1.10.2.min.js" (or "jquery.intellisense.js") - match: /jquery(-(\.?\d+)+)?(\.intellisense)?(\.min)?\.js$/i, + match: /jquery(-[\d\.]+)?(\.intellisense)?(\.min)?\.js$/i, types: ["jquery"] }, "WinJS": { @@ -154856,16 +159515,7 @@ var ts; } } } - var ConfigFileWatcherStatus; - (function (ConfigFileWatcherStatus) { - ConfigFileWatcherStatus["ReloadingFiles"] = "Reloading configured projects for files"; - ConfigFileWatcherStatus["ReloadingInferredRootFiles"] = "Reloading configured projects for only inferred root files"; - ConfigFileWatcherStatus["UpdatedCallback"] = "Updated the callback"; - ConfigFileWatcherStatus["OpenFilesImpactedByConfigFileAdd"] = "File added to open files impacted by this config file"; - ConfigFileWatcherStatus["OpenFilesImpactedByConfigFileRemove"] = "File removed from open files impacted by this config file"; - ConfigFileWatcherStatus["RootOfInferredProjectTrue"] = "Open file was set as Inferred root"; - ConfigFileWatcherStatus["RootOfInferredProjectFalse"] = "Open file was set as not inferred root"; - })(ConfigFileWatcherStatus || (ConfigFileWatcherStatus = {})); + var noopConfigFileWatcher = { close: ts.noop }; function isOpenScriptInfo(infoOrFileNameOrConfig) { return !!infoOrFileNameOrConfig.containingProjects; } @@ -154961,7 +159611,7 @@ var ts; return forEachAnyProjectReferenceKind(project, function (resolvedRef) { return callbackRefProject(project, cb, resolvedRef.sourceFile.path); }, function (projectRef) { return callbackRefProject(project, cb, project.toPath(ts.resolveProjectReferencePath(projectRef))); }, function (potentialProjectRef) { return callbackRefProject(project, cb, potentialProjectRef); }); } function getDetailWatchInfo(watchType, project) { - return "Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType; + return (ts.isString(project) ? "Config: " + project + " " : project ? "Project: " + project.getProjectName() + " " : "") + "WatchType: " + watchType; } function isScriptInfoWatchedFromNodeModules(info) { return !info.isScriptOpen() && info.mTime !== undefined; @@ -155041,7 +159691,7 @@ var ts; * - Or it is present if we have configured project open with config file at that location * In this case the exists property is always true */ - this.configFileExistenceInfoCache = new ts.Map(); + /*@internal*/ this.configFileExistenceInfoCache = new ts.Map(); this.safelist = defaultTypeSafeList; this.legacySafelist = new ts.Map(); this.pendingProjectUpdates = new ts.Map(); @@ -155051,6 +159701,8 @@ var ts; this.seenProjects = new ts.Map(); /*@internal*/ this.sharedExtendedConfigFileWatchers = new ts.Map(); + /*@internal*/ + this.extendedConfigCache = new ts.Map(); this.host = opts.host; this.logger = opts.logger; this.cancellationToken = opts.cancellationToken; @@ -155187,13 +159839,12 @@ var ts; case server.ActionSet: // Update the typing files and update the project project.updateTypingFiles(this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings)); - break; + return; case server.ActionInvalidate: // Do not clear resolution cache, there was changes detected in typings, so enque typing request and let it get us correct results this.typingsCache.enqueueInstallTypingsForProject(project, project.lastCachedUnresolvedImportsList, /*forceRefresh*/ true); return; } - this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); }; /*@internal*/ ProjectService.prototype.delayEnsureProjectForOpenFiles = function () { @@ -155424,9 +160075,6 @@ var ts; return this.hostConfiguration.preferences; }; ProjectService.prototype.onSourceFileChanged = function (info, eventKind) { - if (info.containingProjects) { - info.containingProjects.forEach(function (project) { return project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(info.path); }); - } if (eventKind === ts.FileWatcherEventKind.Deleted) { // File was deleted this.handleDeletedFile(info); @@ -155492,18 +160140,17 @@ var ts; * This is to watch whenever files are added or removed to the wildcard directories */ /*@internal*/ - ProjectService.prototype.watchWildcardDirectory = function (directory, flags, project) { + ProjectService.prototype.watchWildcardDirectory = function (directory, flags, configFileName, config) { var _this = this; - var watchOptions = this.getWatchOptions(project); return this.watchFactory.watchDirectory(directory, function (fileOrDirectory) { var fileOrDirectoryPath = _this.toPath(fileOrDirectory); - var fsResult = project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); - var configFileName = project.getConfigFilePath(); + var fsResult = config.cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); if (ts.getBaseFileName(fileOrDirectoryPath) === "package.json" && !ts.isInsideNodeModules(fileOrDirectoryPath) && (fsResult && fsResult.fileExists || !fsResult && _this.host.fileExists(fileOrDirectoryPath))) { - _this.logger.info("Project: " + configFileName + " Detected new package.json: " + fileOrDirectory); + _this.logger.info("Config: " + configFileName + " Detected new package.json: " + fileOrDirectory); _this.onAddPackageJson(fileOrDirectoryPath); } + var configuredProjectForConfig = _this.findConfiguredProjectByProjectName(configFileName); if (ts.isIgnoredFileFromWildCardWatching({ watchedDirPath: directory, fileOrDirectory: fileOrDirectory, @@ -155511,109 +160158,111 @@ var ts; configFileName: configFileName, extraFileExtensions: _this.hostConfiguration.extraFileExtensions, currentDirectory: _this.currentDirectory, - options: project.getCompilationSettings(), - program: project.getCurrentProgram(), + options: config.parsedCommandLine.options, + program: (configuredProjectForConfig === null || configuredProjectForConfig === void 0 ? void 0 : configuredProjectForConfig.getCurrentProgram()) || config.parsedCommandLine.fileNames, useCaseSensitiveFileNames: _this.host.useCaseSensitiveFileNames, - writeLog: function (s) { return _this.logger.info(s); } + writeLog: function (s) { return _this.logger.info(s); }, + toPath: function (s) { return _this.toPath(s); } })) return; - // don't trigger callback on open, existing files - if (project.fileIsOpen(fileOrDirectoryPath)) { - if (project.pendingReload !== ts.ConfigFileProgramReloadLevel.Full) { + // Reload is pending, do the reload + if (config.reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + config.projects.forEach(function (watchWildcardDirectories, projectCanonicalPath) { + if (!watchWildcardDirectories) + return; + var project = _this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath); + if (!project) + return; + // Load root file names for configured project with the config file name + // But only schedule update if project references this config file + var reloadLevel = configuredProjectForConfig === project ? ts.ConfigFileProgramReloadLevel.Partial : ts.ConfigFileProgramReloadLevel.None; + if (project.pendingReload !== undefined && project.pendingReload > reloadLevel) + return; + // don't trigger callback on open, existing files + if (_this.openFiles.has(fileOrDirectoryPath)) { var info = ts.Debug.checkDefined(_this.getScriptInfoForPath(fileOrDirectoryPath)); if (info.isAttached(project)) { - project.openFileWatchTriggered.set(fileOrDirectoryPath, true); + var loadLevelToSet = Math.max(reloadLevel, project.openFileWatchTriggered.get(fileOrDirectoryPath) || ts.ConfigFileProgramReloadLevel.None); + project.openFileWatchTriggered.set(fileOrDirectoryPath, loadLevelToSet); } else { - project.pendingReload = ts.ConfigFileProgramReloadLevel.Partial; + project.pendingReload = reloadLevel; _this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); } } + else { + project.pendingReload = reloadLevel; + _this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); + } + }); + }, flags, this.getWatchOptionsFromProjectWatchOptions(config.parsedCommandLine.watchOptions), ts.WatchType.WildcardDirectory, configFileName); + }; + /*@internal*/ + ProjectService.prototype.delayUpdateProjectsFromParsedConfigOnConfigFileChange = function (canonicalConfigFilePath, reloadReason) { + var _this = this; + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!(configFileExistenceInfo === null || configFileExistenceInfo === void 0 ? void 0 : configFileExistenceInfo.config)) + return false; + var scheduledAnyProjectUpdate = false; + // Update projects watching cached config + configFileExistenceInfo.config.reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + configFileExistenceInfo.config.projects.forEach(function (_watchWildcardDirectories, projectCanonicalPath) { + var project = _this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath); + if (!project) return; + scheduledAnyProjectUpdate = true; + if (projectCanonicalPath === canonicalConfigFilePath) { + // Skip refresh if project is not yet loaded + if (project.isInitialLoadPending()) + return; + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reloadReason; + _this.delayUpdateProjectGraph(project); } - // Reload is pending, do the reload - if (project.pendingReload !== ts.ConfigFileProgramReloadLevel.Full) { - project.pendingReload = ts.ConfigFileProgramReloadLevel.Partial; - _this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); + else { + // Change in referenced project config file + project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(_this.toPath(canonicalConfigFilePath)); + _this.delayUpdateProjectGraph(project); } - }, flags, watchOptions, ts.WatchType.WildcardDirectory, project); - }; - /** Gets the config file existence info for the configured project */ - /*@internal*/ - ProjectService.prototype.getConfigFileExistenceInfo = function (project) { - return this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath); + }); + return scheduledAnyProjectUpdate; }; /*@internal*/ - ProjectService.prototype.onConfigChangedForConfiguredProject = function (project, eventKind) { - var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); + ProjectService.prototype.onConfigFileChanged = function (canonicalConfigFilePath, eventKind) { + var _a; + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (eventKind === ts.FileWatcherEventKind.Deleted) { // Update the cached status // We arent updating or removing the cached config file presence info as that will be taken care of by - // setConfigFilePresenceByClosedConfigFile when the project is closed (depending on tracking open files) + // releaseParsedConfig when the project is closed or doesnt need this config any more (depending on tracking open files) configFileExistenceInfo.exists = false; - this.removeProject(project); - // Reload the configured projects for the open files in the map as they are affected by this config file - // Since the configured project was deleted, we want to reload projects for all the open files including files - // that are not root of the inferred project - this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for files" /* ReloadingFiles */); - this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false); + // Remove the configured project for this config file + var project = ((_a = configFileExistenceInfo.config) === null || _a === void 0 ? void 0 : _a.projects.has(canonicalConfigFilePath)) ? + this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath) : + undefined; + if (project) + this.removeProject(project); } else { - this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files" /* ReloadingInferredRootFiles */); - // Skip refresh if project is not yet loaded - if (project.isInitialLoadPending()) - return; - 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 - this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ true); + // Update the cached status + configFileExistenceInfo.exists = true; } - }; - /*@internal*/ - ProjectService.prototype.updateSharedExtendedConfigFileMap = function (_a, parsedCommandLine) { - var _this = this; - var canonicalConfigFilePath = _a.canonicalConfigFilePath; - ts.updateSharedExtendedConfigFileWatcher(canonicalConfigFilePath, parsedCommandLine, this.sharedExtendedConfigFileWatchers, function (extendedConfigFileName, extendedConfigFilePath) { return _this.watchFactory.watchFile(extendedConfigFileName, function () { - var _a; - var ensureProjectsForOpenFiles = false; - (_a = _this.sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (canonicalPath) { - var project = _this.configuredProjects.get(canonicalPath); - // Skip refresh if project is not yet loaded - if (!project || project.isInitialLoadPending()) - return; - project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; - project.pendingReloadReason = "Change in extended config file " + extendedConfigFileName + " detected"; - _this.delayUpdateProjectGraph(project); - ensureProjectsForOpenFiles = true; - }); - if (ensureProjectsForOpenFiles) - _this.delayEnsureProjectForOpenFiles(); - }, ts.PollingInterval.High, _this.hostConfiguration.watchOptions, ts.WatchType.ExtendedConfigFile); }, function (fileName) { return _this.toPath(fileName); }); - }; - /*@internal*/ - ProjectService.prototype.removeProjectFromSharedExtendedConfigFileMap = function (project) { - this.sharedExtendedConfigFileWatchers.forEach(function (watcher) { - watcher.projects.delete(project.canonicalConfigFilePath); - watcher.close(); - }); - }; - /** - * This is the callback function for the config file add/remove/change at any location - * that matters to open script info but doesnt have configured project open - * for the config file - */ - ProjectService.prototype.onConfigFileChangeForOpenScriptInfo = function (configFileName, eventKind) { - // This callback is called only if we dont have config file project for this config file - var canonicalConfigPath = server.normalizedPathToPath(configFileName, this.currentDirectory, this.toCanonicalFileName); - var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigPath); - configFileExistenceInfo.exists = (eventKind !== ts.FileWatcherEventKind.Deleted); - this.logConfigFileWatchUpdate(configFileName, canonicalConfigPath, configFileExistenceInfo, "Reloading configured projects for files" /* ReloadingFiles */); - // Because there is no configured project open for the config file, the tracking open files map - // will only have open files that need the re-detection of the project and hence - // reload projects for all the tracking open files in the map - this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false); + // Update projects watching config + this.delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalConfigFilePath, "Change in config file detected"); + // Reload the configured projects for the open files in the map as they are affected by this config file + // If the configured project was deleted, we want to reload projects for all the open files including files + // that are not root of the inferred project + // Otherwise, we scheduled the update on configured project graph, + // we would need to schedule the project reload for only the root of inferred projects + // Get open files to reload projects for + this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, + /*clearSemanticCache*/ false, + /*delayReload*/ true, eventKind !== ts.FileWatcherEventKind.Deleted ? + ts.identity : // Reload open files if they are root of inferred project + ts.returnTrue, // Reload all the open files impacted by config file + "Change in config file detected"); + this.delayEnsureProjectForOpenFiles(); }; ProjectService.prototype.removeProject = function (project) { var _this = this; @@ -155639,7 +160288,6 @@ var ts; case server.ProjectKind.Configured: this.configuredProjects.delete(project.canonicalConfigFilePath); this.projectToSizeMap.delete(project.canonicalConfigFilePath); - this.setConfigFileExistenceInfoByClosedConfiguredProject(project); break; case server.ProjectKind.Inferred: ts.unorderedRemoveItem(this.inferredProjects, project); @@ -155666,7 +160314,7 @@ var ts; } project.updateGraph(); if (!this.useSingleInferredProject && !project.projectRootPath) { - var _loop_3 = function (inferredProject) { + var _loop_2 = function (inferredProject) { if (inferredProject === project || inferredProject.isOrphan()) { return "continue"; } @@ -155687,7 +160335,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_3(inferredProject); + _loop_2(inferredProject); } } return project; @@ -155730,10 +160378,11 @@ var ts; // if it would need to be re-created with next file open // If project had open file affecting // Reload the root Files from config if its not already scheduled - if (p.openFileWatchTriggered.has(info.path)) { + var reloadLevel = p.openFileWatchTriggered.get(info.path); + if (reloadLevel !== undefined) { p.openFileWatchTriggered.delete(info.path); - if (!p.pendingReload) { - p.pendingReload = ts.ConfigFileProgramReloadLevel.Partial; + if (p.pendingReload !== undefined && p.pendingReload < reloadLevel) { + p.pendingReload = reloadLevel; p.markFileAsDirty(info.path); } } @@ -155781,13 +160430,13 @@ var ts; } }; ProjectService.prototype.configFileExists = function (configFileName, canonicalConfigFilePath, info) { + var _a; var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (configFileExistenceInfo) { // By default the info would get impacted by presence of config file since its in the detection path // Only adding the info as a root to inferred project will need the existence to be watched by file watcher - if (isOpenScriptInfo(info) && !configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { - configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); - this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file" /* OpenFilesImpactedByConfigFileAdd */); + if (isOpenScriptInfo(info) && !((_a = configFileExistenceInfo.openFilesImpactedByConfigFile) === null || _a === void 0 ? void 0 : _a.has(info.path))) { + (configFileExistenceInfo.openFilesImpactedByConfigFile || (configFileExistenceInfo.openFilesImpactedByConfigFile = new ts.Map())).set(info.path, false); } return configFileExistenceInfo.exists; } @@ -155800,104 +160449,82 @@ var ts; // Or the whole chain of config files for the roots of the inferred projects // Cache the host value of file exists and add the info to map of open files impacted by this config file var exists = this.host.fileExists(configFileName); - var openFilesImpactedByConfigFile = new ts.Map(); + var openFilesImpactedByConfigFile; if (isOpenScriptInfo(info)) { - openFilesImpactedByConfigFile.set(info.path, false); + (openFilesImpactedByConfigFile || (openFilesImpactedByConfigFile = new ts.Map())).set(info.path, false); } configFileExistenceInfo = { exists: exists, openFilesImpactedByConfigFile: openFilesImpactedByConfigFile }; this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); - this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file" /* OpenFilesImpactedByConfigFileAdd */); return exists; }; - ProjectService.prototype.setConfigFileExistenceByNewConfiguredProject = function (project) { - var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); - if (configFileExistenceInfo) { - // The existence might not be set if the file watcher is not invoked by the time config project is created by external project - configFileExistenceInfo.exists = true; - // close existing watcher - if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { - var configFileName = project.getConfigFilePath(); - configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close(); - configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined; - this.logConfigFileWatchUpdate(configFileName, project.canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback" /* UpdatedCallback */); - } - } - else { - // We could be in this scenario if project is the configured project tracked by external project - // Since that route doesnt check if the config file is present or not - this.configFileExistenceInfoCache.set(project.canonicalConfigFilePath, { - exists: true, - openFilesImpactedByConfigFile: new ts.Map() - }); + /*@internal*/ + ProjectService.prototype.createConfigFileWatcherForParsedConfig = function (configFileName, canonicalConfigFilePath, forProject) { + var _this = this; + var _a, _b; + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + // When watching config file for parsed config, remove the noopFileWatcher that can be created for open files impacted by config file and watch for real + if (!configFileExistenceInfo.watcher || configFileExistenceInfo.watcher === noopConfigFileWatcher) { + configFileExistenceInfo.watcher = this.watchFactory.watchFile(configFileName, function (_fileName, eventKind) { return _this.onConfigFileChanged(canonicalConfigFilePath, eventKind); }, ts.PollingInterval.High, this.getWatchOptionsFromProjectWatchOptions((_b = (_a = configFileExistenceInfo === null || configFileExistenceInfo === void 0 ? void 0 : configFileExistenceInfo.config) === null || _a === void 0 ? void 0 : _a.parsedCommandLine) === null || _b === void 0 ? void 0 : _b.watchOptions), ts.WatchType.ConfigFile, forProject); } + // Watching config file for project, update the map + var projects = configFileExistenceInfo.config.projects; + projects.set(forProject.canonicalConfigFilePath, projects.get(forProject.canonicalConfigFilePath) || false); }; /** * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project */ ProjectService.prototype.configFileExistenceImpactsRootOfInferredProject = function (configFileExistenceInfo) { - return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (isRootOfInferredProject) { return isRootOfInferredProject; }); + return configFileExistenceInfo.openFilesImpactedByConfigFile && + ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, ts.identity); }; - ProjectService.prototype.setConfigFileExistenceInfoByClosedConfiguredProject = function (closedProject) { - var configFileExistenceInfo = this.getConfigFileExistenceInfo(closedProject); - ts.Debug.assert(!!configFileExistenceInfo); - if (configFileExistenceInfo.openFilesImpactedByConfigFile.size) { - var configFileName = closedProject.getConfigFilePath(); + /* @internal */ + ProjectService.prototype.releaseParsedConfig = function (canonicalConfigFilePath, forProject) { + var _a, _b, _c; + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!((_a = configFileExistenceInfo.config) === null || _a === void 0 ? void 0 : _a.projects.delete(forProject.canonicalConfigFilePath))) + return; + // If there are still projects watching this config file existence and config, there is nothing to do + if ((_b = configFileExistenceInfo.config) === null || _b === void 0 ? void 0 : _b.projects.size) + return; + configFileExistenceInfo.config = undefined; + ts.clearSharedExtendedConfigFileWatcher(canonicalConfigFilePath, this.sharedExtendedConfigFileWatchers); + ts.Debug.checkDefined(configFileExistenceInfo.watcher); + if ((_c = configFileExistenceInfo.openFilesImpactedByConfigFile) === null || _c === void 0 ? void 0 : _c.size) { // If there are open files that are impacted by this config file existence // but none of them are root of inferred project, the config file watcher will be // created when any of the script infos are added as root of inferred project if (this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { - ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject); - this.createConfigFileWatcherOfConfigFileExistence(configFileName, closedProject.canonicalConfigFilePath, configFileExistenceInfo); + // If we cannot watch config file existence without configured project, close the configured file watcher + if (!ts.canWatchDirectory(ts.getDirectoryPath(canonicalConfigFilePath))) { + configFileExistenceInfo.watcher.close(); + configFileExistenceInfo.watcher = noopConfigFileWatcher; + } + } + else { + // Close existing watcher + configFileExistenceInfo.watcher.close(); + configFileExistenceInfo.watcher = undefined; } } else { // There is not a single file open thats tracking the status of this config file. Remove from cache - this.configFileExistenceInfoCache.delete(closedProject.canonicalConfigFilePath); + configFileExistenceInfo.watcher.close(); + this.configFileExistenceInfoCache.delete(canonicalConfigFilePath); } }; - ProjectService.prototype.logConfigFileWatchUpdate = function (configFileName, canonicalConfigFilePath, configFileExistenceInfo, status) { - var _this = this; - if (!this.logger.hasLevel(server.LogLevel.verbose)) { - return; - } - var inferredRoots = []; - var otherFiles = []; - configFileExistenceInfo.openFilesImpactedByConfigFile.forEach(function (isRootOfInferredProject, key) { - var info = _this.getScriptInfoForPath(key); - (isRootOfInferredProject ? inferredRoots : otherFiles).push(info.fileName); - }); - var watches = []; - if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { - watches.push(configFileExistenceInfo.configFileWatcherForRootOfInferredProject === ts.noopFileWatcher ? - ts.WatchType.NoopConfigFileForInferredRoot : - ts.WatchType.ConfigFileForInferredRoot); - } - if (this.configuredProjects.has(canonicalConfigFilePath)) { - watches.push(ts.WatchType.ConfigFile); - } - this.logger.info("ConfigFilePresence:: Current Watches: " + watches + ":: File: " + configFileName + " Currently impacted open files: RootsOfInferredProjects: " + inferredRoots + " OtherOpenFiles: " + otherFiles + " Status: " + status); - }; - /** - * Create the watcher for the configFileExistenceInfo - */ - ProjectService.prototype.createConfigFileWatcherOfConfigFileExistence = function (configFileName, canonicalConfigFilePath, configFileExistenceInfo) { - var _this = this; - configFileExistenceInfo.configFileWatcherForRootOfInferredProject = - ts.canWatchDirectory(ts.getDirectoryPath(canonicalConfigFilePath)) ? - this.watchFactory.watchFile(configFileName, function (_filename, eventKind) { return _this.onConfigFileChangeForOpenScriptInfo(configFileName, eventKind); }, ts.PollingInterval.High, this.hostConfiguration.watchOptions, ts.WatchType.ConfigFileForInferredRoot) : - ts.noopFileWatcher; - this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback" /* UpdatedCallback */); - }; /** * Close the config file watcher in the cached ConfigFileExistenceInfo - * if there arent any open files that are root of inferred project + * if there arent any open files that are root of inferred project and there is no parsed config held by any project */ - ProjectService.prototype.closeConfigFileWatcherOfConfigFileExistenceInfo = function (configFileExistenceInfo) { + /*@internal*/ + ProjectService.prototype.closeConfigFileWatcherOnReleaseOfOpenFile = function (configFileExistenceInfo) { // Close the config file watcher if there are no more open files that are root of inferred project - if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject && + // or if there are no projects that need to watch this config file existence info + if (configFileExistenceInfo.watcher && + !configFileExistenceInfo.config && !this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { - configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close(); - configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined; + configFileExistenceInfo.watcher.close(); + configFileExistenceInfo.watcher = undefined; } }; /** @@ -155906,25 +160533,26 @@ var ts; ProjectService.prototype.stopWatchingConfigFilesForClosedScriptInfo = function (info) { var _this = this; ts.Debug.assert(!info.isScriptOpen()); - this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + this.forEachConfigFileLocation(info, function (canonicalConfigFilePath) { + var _a, _b, _c; var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (configFileExistenceInfo) { - var infoIsRootOfInferredProject = configFileExistenceInfo.openFilesImpactedByConfigFile.get(info.path); + var infoIsRootOfInferredProject = (_a = configFileExistenceInfo.openFilesImpactedByConfigFile) === null || _a === void 0 ? void 0 : _a.get(info.path); // Delete the info from map, since this file is no more open - configFileExistenceInfo.openFilesImpactedByConfigFile.delete(info.path); - _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File removed from open files impacted by this config file" /* OpenFilesImpactedByConfigFileRemove */); + (_b = configFileExistenceInfo.openFilesImpactedByConfigFile) === null || _b === void 0 ? void 0 : _b.delete(info.path); // If the script info was not root of inferred project, // there wont be config file watch open because of this script info if (infoIsRootOfInferredProject) { // But if it is a root, it could be the last script info that is root of inferred project // and hence we would need to close the config file watcher - _this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); + _this.closeConfigFileWatcherOnReleaseOfOpenFile(configFileExistenceInfo); } // If there are no open files that are impacted by configFileExistenceInfo after closing this script info - // there is no configured project present, remove the cached existence info - if (!configFileExistenceInfo.openFilesImpactedByConfigFile.size && - !_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) { - ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject); + // and there is are no projects that need the config file existence or parsed config, + // remove the cached existence info + if (!((_c = configFileExistenceInfo.openFilesImpactedByConfigFile) === null || _c === void 0 ? void 0 : _c.size) && + !configFileExistenceInfo.config) { + ts.Debug.assert(!configFileExistenceInfo.watcher); _this.configFileExistenceInfoCache.delete(canonicalConfigFilePath); } } @@ -155937,24 +160565,19 @@ var ts; ProjectService.prototype.startWatchingConfigFilesForInferredProjectRoot = function (info) { var _this = this; ts.Debug.assert(info.isScriptOpen()); - this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + this.forEachConfigFileLocation(info, function (canonicalConfigFilePath, configFileName) { var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (!configFileExistenceInfo) { // Create the cache - configFileExistenceInfo = { - exists: _this.host.fileExists(configFileName), - openFilesImpactedByConfigFile: new ts.Map() - }; + configFileExistenceInfo = { exists: _this.host.fileExists(configFileName) }; _this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); } // Set this file as the root of inferred project - configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, true); - _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as Inferred root" /* RootOfInferredProjectTrue */); + (configFileExistenceInfo.openFilesImpactedByConfigFile || (configFileExistenceInfo.openFilesImpactedByConfigFile = new ts.Map())).set(info.path, true); // If there is no configured project for this config file, add the file watcher - if (!configFileExistenceInfo.configFileWatcherForRootOfInferredProject && - !_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) { - _this.createConfigFileWatcherOfConfigFileExistence(configFileName, canonicalConfigFilePath, configFileExistenceInfo); - } + configFileExistenceInfo.watcher || (configFileExistenceInfo.watcher = ts.canWatchDirectory(ts.getDirectoryPath(canonicalConfigFilePath)) ? + _this.watchFactory.watchFile(configFileName, function (_filename, eventKind) { return _this.onConfigFileChanged(canonicalConfigFilePath, eventKind); }, ts.PollingInterval.High, _this.hostConfiguration.watchOptions, ts.WatchType.ConfigFileForInferredRoot) : + noopConfigFileWatcher); }); }; /** @@ -155963,15 +160586,15 @@ var ts; /* @internal */ ProjectService.prototype.stopWatchingConfigFilesForInferredProjectRoot = function (info) { var _this = this; - this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + this.forEachConfigFileLocation(info, function (canonicalConfigFilePath) { + var _a; var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); - if (configFileExistenceInfo && configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { + if ((_a = configFileExistenceInfo === null || configFileExistenceInfo === void 0 ? void 0 : configFileExistenceInfo.openFilesImpactedByConfigFile) === null || _a === void 0 ? void 0 : _a.has(info.path)) { ts.Debug.assert(info.isScriptOpen()); // Info is not root of inferred project any more configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); - _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as not inferred root" /* RootOfInferredProjectFalse */); // Close the config file watcher - _this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); + _this.closeConfigFileWatcherOnReleaseOfOpenFile(configFileExistenceInfo); } }); }; @@ -156003,11 +160626,11 @@ var ts; if (searchInDirectory) { var canonicalSearchPath = server.normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName); var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json")); - var result = action(tsconfigFileName, ts.combinePaths(canonicalSearchPath, "tsconfig.json")); + var result = action(ts.combinePaths(canonicalSearchPath, "tsconfig.json"), tsconfigFileName); if (result) return tsconfigFileName; var jsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "jsconfig.json")); - result = action(jsconfigFileName, ts.combinePaths(canonicalSearchPath, "jsconfig.json")); + result = action(ts.combinePaths(canonicalSearchPath, "jsconfig.json"), jsconfigFileName); if (result) return jsconfigFileName; // If we started within node_modules, don't look outside node_modules. @@ -156055,7 +160678,7 @@ var ts; return result || undefined; } this.logger.info("Search path: " + ts.getDirectoryPath(info.fileName)); - var configFileName = this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + var configFileName = this.forEachConfigFileLocation(info, function (canonicalConfigFilePath, configFileName) { return _this.configFileExists(configFileName, canonicalConfigFilePath, info); }); if (configFileName) { @@ -156100,6 +160723,7 @@ var ts; }; /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ ProjectService.prototype.getFilenameForExceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) { + var _this = this; if (options && options.disableSizeLimit || !this.host.getFileSize) { return; } @@ -156115,25 +160739,17 @@ var ts; } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { - this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTSFileExtension: ts.hasTSFileExtension, host: this.host }, totalNonTsFileSize)); // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier + var top5LargestFiles = fileNames.map(function (f) { return propertyReader.getFileName(f); }) + .filter(function (name) { return !ts.hasTSFileExtension(name); }) + .map(function (name) { return ({ name: name, size: _this.host.getFileSize(name) }); }) + .sort(function (a, b) { return b.size - a.size; }) + .slice(0, 5); + this.logger.info("Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + top5LargestFiles.map(function (file) { return file.name + ":" + file.size; }).join(", ")); // Keep the size as zero since it's disabled return fileName; } } this.projectToSizeMap.set(name, totalNonTsFileSize); - return; - function getExceedLimitMessage(context, totalNonTsFileSize) { - var files = getTop5LargestFiles(context); - 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, hasTSFileExtension = _a.hasTSFileExtension, host = _a.host; - return fileNames.map(function (f) { return propertyReader.getFileName(f); }) - .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); - } }; ProjectService.prototype.createExternalProject = function (projectFileName, files, options, typeAcquisition, excludedFiles) { var compilerOptions = convertCompilerOptions(options); @@ -156197,12 +160813,27 @@ var ts; }; /* @internal */ ProjectService.prototype.createConfiguredProject = function (configFileName) { - var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); // TODO: GH#18217 - this.logger.info("Opened configuration file " + configFileName); - var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, cachedDirectoryStructureHost); - project.createConfigFileWatcher(); - this.configuredProjects.set(project.canonicalConfigFilePath, project); - this.setConfigFileExistenceByNewConfiguredProject(project); + this.logger.info("Creating configuration project " + configFileName); + var canonicalConfigFilePath = server.asNormalizedPath(this.toCanonicalFileName(configFileName)); + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + // We could be in this scenario if project is the configured project tracked by external project + // Since that route doesnt check if the config file is present or not + if (!configFileExistenceInfo) { + this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo = { exists: true }); + } + else { + configFileExistenceInfo.exists = true; + } + if (!configFileExistenceInfo.config) { + configFileExistenceInfo.config = { + cachedDirectoryStructureHost: ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames), + projects: new ts.Map(), + reloadLevel: ts.ConfigFileProgramReloadLevel.Full + }; + } + var project = new server.ConfiguredProject(configFileName, canonicalConfigFilePath, this, this.documentRegistry, configFileExistenceInfo.config.cachedDirectoryStructureHost); + this.configuredProjects.set(canonicalConfigFilePath, project); + this.createConfigFileWatcherForParsedConfig(configFileName, canonicalConfigFilePath, project); return project; }; /* @internal */ @@ -156232,24 +160863,9 @@ var ts; var _this = this; this.sendProjectLoadingStartEvent(project, reason); // Read updated contents from disk - var configFilename = ts.normalizePath(project.getConfigFilePath()); - var configFileContent = ts.tryReadFile(configFilename, function (fileName) { return _this.host.readFile(fileName); }); - var result = ts.parseJsonText(configFilename, ts.isString(configFileContent) ? configFileContent : ""); - var configFileErrors = result.parseDiagnostics; - if (!ts.isString(configFileContent)) - configFileErrors.push(configFileContent); - var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename), - /*existingOptions*/ {}, configFilename, - /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions, - /*extendedConfigCache*/ undefined); - if (parsedCommandLine.errors.length) { - configFileErrors.push.apply(configFileErrors, parsedCommandLine.errors); - } - this.logger.info("Config: " + configFilename + " : " + JSON.stringify({ - rootNames: parsedCommandLine.fileNames, - options: parsedCommandLine.options, - projectReferences: parsedCommandLine.projectReferences - }, /*replacer*/ undefined, " ")); + var configFilename = server.asNormalizedPath(ts.normalizePath(project.getConfigFilePath())); + var configFileExistenceInfo = this.ensureParsedConfigUptoDate(configFilename, project.canonicalConfigFilePath, this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath), project); + var parsedCommandLine = configFileExistenceInfo.config.parsedCommandLine; ts.Debug.assert(!!parsedCommandLine.fileNames); var compilerOptions = parsedCommandLine.options; // Update the project @@ -156262,25 +160878,131 @@ var ts; }; } project.canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInputFiles(parsedCommandLine.raw); - project.setProjectErrors(configFileErrors); + project.setProjectErrors(parsedCommandLine.options.configFile.parseDiagnostics); project.updateReferences(parsedCommandLine.projectReferences); var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); if (lastFileExceededProgramSize) { project.disableLanguageService(lastFileExceededProgramSize); - project.stopWatchingWildCards(); - this.removeProjectFromSharedExtendedConfigFileMap(project); + this.configFileExistenceInfoCache.forEach(function (_configFileExistenceInfo, canonicalConfigFilePath) { + return _this.stopWatchingWildCards(canonicalConfigFilePath, project); + }); } else { project.setCompilerOptions(compilerOptions); project.setWatchOptions(parsedCommandLine.watchOptions); project.enableLanguageService(); - project.watchWildcards(new ts.Map(ts.getEntries(parsedCommandLine.wildcardDirectories))); // TODO: GH#18217 - this.updateSharedExtendedConfigFileMap(project, parsedCommandLine); + this.watchWildcards(configFilename, configFileExistenceInfo, project); } project.enablePluginsWithOptions(compilerOptions, this.currentPluginConfigOverrides); var filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave, parsedCommandLine.watchOptions); }; + /*@internal*/ + ProjectService.prototype.ensureParsedConfigUptoDate = function (configFilename, canonicalConfigFilePath, configFileExistenceInfo, forProject) { + var _this = this; + var _a, _b, _c; + if (configFileExistenceInfo.config) { + if (!configFileExistenceInfo.config.reloadLevel) + return configFileExistenceInfo; + if (configFileExistenceInfo.config.reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + this.reloadFileNamesOfParsedConfig(configFilename, configFileExistenceInfo.config); + return configFileExistenceInfo; + } + } + // Parse the config file and ensure its cached + var cachedDirectoryStructureHost = ((_a = configFileExistenceInfo.config) === null || _a === void 0 ? void 0 : _a.cachedDirectoryStructureHost) || + ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); + // Read updated contents from disk + var configFileContent = ts.tryReadFile(configFilename, function (fileName) { return _this.host.readFile(fileName); }); + var configFile = ts.parseJsonText(configFilename, ts.isString(configFileContent) ? configFileContent : ""); + var configFileErrors = configFile.parseDiagnostics; + if (!ts.isString(configFileContent)) + configFileErrors.push(configFileContent); + var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(configFile, cachedDirectoryStructureHost, ts.getDirectoryPath(configFilename), + /*existingOptions*/ {}, configFilename, + /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions, this.extendedConfigCache); + if (parsedCommandLine.errors.length) { + configFileErrors.push.apply(configFileErrors, parsedCommandLine.errors); + } + this.logger.info("Config: " + configFilename + " : " + JSON.stringify({ + rootNames: parsedCommandLine.fileNames, + options: parsedCommandLine.options, + watchOptions: parsedCommandLine.watchOptions, + projectReferences: parsedCommandLine.projectReferences + }, /*replacer*/ undefined, " ")); + var oldCommandLine = (_b = configFileExistenceInfo.config) === null || _b === void 0 ? void 0 : _b.parsedCommandLine; + if (!configFileExistenceInfo.config) { + configFileExistenceInfo.config = { parsedCommandLine: parsedCommandLine, cachedDirectoryStructureHost: cachedDirectoryStructureHost, projects: new ts.Map() }; + } + else { + configFileExistenceInfo.config.parsedCommandLine = parsedCommandLine; + configFileExistenceInfo.config.watchedDirectoriesStale = true; + configFileExistenceInfo.config.reloadLevel = undefined; + } + // If watch options different than older options when setting for the first time, update the config file watcher + if (!oldCommandLine && !ts.isJsonEqual( + // Old options + this.getWatchOptionsFromProjectWatchOptions(/*projectOptions*/ undefined), + // New options + this.getWatchOptionsFromProjectWatchOptions(parsedCommandLine.watchOptions))) { + // Reset the config file watcher + (_c = configFileExistenceInfo.watcher) === null || _c === void 0 ? void 0 : _c.close(); + configFileExistenceInfo.watcher = undefined; + } + // Ensure there is watcher for this config file + this.createConfigFileWatcherForParsedConfig(configFilename, canonicalConfigFilePath, forProject); + // Watch extended config files + ts.updateSharedExtendedConfigFileWatcher(canonicalConfigFilePath, parsedCommandLine.options, this.sharedExtendedConfigFileWatchers, function (extendedConfigFileName, extendedConfigFilePath) { return _this.watchFactory.watchFile(extendedConfigFileName, function () { + var _a; + // Update extended config cache + ts.cleanExtendedConfigCache(_this.extendedConfigCache, extendedConfigFilePath, function (fileName) { return _this.toPath(fileName); }); + // Update projects + var ensureProjectsForOpenFiles = false; + (_a = _this.sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (canonicalPath) { + ensureProjectsForOpenFiles = _this.delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalPath, "Change in extended config file " + extendedConfigFileName + " detected") || ensureProjectsForOpenFiles; + }); + if (ensureProjectsForOpenFiles) + _this.delayEnsureProjectForOpenFiles(); + }, ts.PollingInterval.High, _this.hostConfiguration.watchOptions, ts.WatchType.ExtendedConfigFile, configFilename); }, function (fileName) { return _this.toPath(fileName); }); + return configFileExistenceInfo; + }; + /*@internal*/ + ProjectService.prototype.watchWildcards = function (configFileName, _a, forProject) { + var _this = this; + var _b; + var exists = _a.exists, config = _a.config; + config.projects.set(forProject.canonicalConfigFilePath, true); + if (exists) { + if (config.watchedDirectories && !config.watchedDirectoriesStale) + return; + config.watchedDirectoriesStale = false; + ts.updateWatchingWildcardDirectories((_b = config).watchedDirectories || (_b.watchedDirectories = new ts.Map()), new ts.Map(ts.getEntries(config.parsedCommandLine.wildcardDirectories)), + // Create new directory watcher + function (directory, flags) { return _this.watchWildcardDirectory(directory, flags, configFileName, config); }); + } + else { + config.watchedDirectoriesStale = false; + if (!config.watchedDirectories) + return; + ts.clearMap(config.watchedDirectories, ts.closeFileWatcherOf); + config.watchedDirectories = undefined; + } + }; + /*@internal*/ + ProjectService.prototype.stopWatchingWildCards = function (canonicalConfigFilePath, forProject) { + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!configFileExistenceInfo.config || + !configFileExistenceInfo.config.projects.get(forProject.canonicalConfigFilePath)) { + return; + } + configFileExistenceInfo.config.projects.set(forProject.canonicalConfigFilePath, false); + // If any of the project is still watching wild cards dont close the watcher + if (ts.forEachEntry(configFileExistenceInfo.config.projects, ts.identity)) + return; + ts.clearMap(configFileExistenceInfo.config.watchedDirectories, ts.closeFileWatcherOf); + configFileExistenceInfo.config.watchedDirectories = undefined; + configFileExistenceInfo.config.watchedDirectoriesStale = undefined; + }; ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) { var projectRootFilesMap = project.getRootFilesMap(); var newRootScriptInfoMap = new ts.Map(); @@ -156360,14 +161082,22 @@ var ts; */ /*@internal*/ ProjectService.prototype.reloadFileNamesOfConfiguredProject = function (project) { - var configFileSpecs = project.getCompilerOptions().configFile.configFileSpecs; - var configFileName = project.getConfigFilePath(); - var fileNames = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); + var fileNames = this.reloadFileNamesOfParsedConfig(project.getConfigFilePath(), this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath).config); project.updateErrorOnNoInputFiles(fileNames); this.updateNonInferredProjectFiles(project, fileNames.concat(project.getExternalFiles()), fileNamePropertyReader); return project.updateGraph(); }; /*@internal*/ + ProjectService.prototype.reloadFileNamesOfParsedConfig = function (configFileName, config) { + if (config.reloadLevel === undefined) + return config.parsedCommandLine.fileNames; + ts.Debug.assert(config.reloadLevel === ts.ConfigFileProgramReloadLevel.Partial); + var configFileSpecs = config.parsedCommandLine.options.configFile.configFileSpecs; + var fileNames = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), config.parsedCommandLine.options, config.cachedDirectoryStructureHost, this.hostConfiguration.extraFileExtensions); + config.parsedCommandLine = __assign(__assign({}, config.parsedCommandLine), { fileNames: fileNames }); + return fileNames; + }; + /*@internal*/ ProjectService.prototype.setFileNamesOfAutoImportProviderProject = function (project, fileNames) { this.updateNonInferredProjectFiles(project, fileNames, fileNamePropertyReader); }; @@ -156541,7 +161271,7 @@ var ts; return projects; function combineProjects(toAddInfo) { if (toAddInfo !== info) { - var _loop_4 = function (project) { + var _loop_3 = function (project) { // Add the projects only if they can use symLink targets and not already in the list if (project.languageServiceEnabled && !project.isOrphan() && @@ -156558,7 +161288,7 @@ var ts; }; for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { var project = _a[_i]; - _loop_4(project); + _loop_3(project); } } } @@ -156766,7 +161496,7 @@ var ts; var snap = mapInfo.getSnapshot(); if (mapInfo.documentPositionMapper !== undefined) return mapInfo.documentPositionMapper; - return snap.getText(0, snap.getLength()); + return ts.getSnapshotText(snap); }; var projectName = project.projectName; var documentPositionMapper = ts.getDocumentPositionMapper({ getCanonicalFileName: this.toCanonicalFileName, log: function (s) { return _this.logger.info(s); }, getSourceFileLike: function (f) { return _this.getSourceFileLike(f, projectName, declarationInfo); } }, declarationInfo.fileName, declarationInfo.getLineInfo(), readMapFile); @@ -156887,7 +161617,7 @@ var ts; }); } if (includePackageJsonAutoImports !== args.preferences.includePackageJsonAutoImports) { - this.invalidateProjectAutoImports(/*packageJsonPath*/ undefined); + this.invalidateProjectPackageJson(/*packageJsonPath*/ undefined); } } if (args.extraFileExtensions) { @@ -156905,7 +161635,10 @@ var ts; }; /*@internal*/ ProjectService.prototype.getWatchOptions = function (project) { - var projectOptions = project.getWatchOptions(); + return this.getWatchOptionsFromProjectWatchOptions(project.getWatchOptions()); + }; + /*@internal*/ + ProjectService.prototype.getWatchOptionsFromProjectWatchOptions = function (projectOptions) { return projectOptions && this.hostConfiguration.watchOptions ? __assign(__assign({}, this.hostConfiguration.watchOptions), projectOptions) : projectOptions || this.hostConfiguration.watchOptions; }; @@ -156939,6 +161672,11 @@ var ts; }); this.throttledOperations.cancel(ensureProjectForOpenFileSchedule); this.pendingEnsureProjectForOpenFiles = false; + // Ensure everything is reloaded for cached configs + this.configFileExistenceInfoCache.forEach(function (info) { + if (info.config) + info.config.reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + }); // Reload Projects this.reloadConfiguredProjectForFiles(this.openFiles, /*clearSemanticCache*/ true, /*delayReload*/ false, ts.returnTrue, "User requested reload projects"); this.externalProjects.forEach(function (project) { @@ -156948,21 +161686,11 @@ var ts; this.inferredProjects.forEach(function (project) { return _this.clearSemanticCache(project); }); this.ensureProjectForOpenFiles(); }; - ProjectService.prototype.delayReloadConfiguredProjectForFiles = function (configFileExistenceInfo, ignoreIfNotRootOfInferredProject) { - // Get open files to reload projects for - this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, - /*clearSemanticCache*/ false, - /*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 - "Change in config file detected"); - this.delayEnsureProjectForOpenFiles(); - }; /** * This function goes through all the openFiles and tries to file the config file for them. * If the config file is found and it refers to existing project, it reloads it either immediately * or schedules it for reload depending on delayReload option - * If the there is no existing project it just opens the configured project for the config file + * If 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, clearSemanticCache, delayReload, shouldReloadProjectFor, reason) { @@ -156975,7 +161703,7 @@ var ts; } }; // try to reload config file for all open files - openFiles.forEach(function (openFileValue, path) { + openFiles === null || openFiles === void 0 ? void 0 : openFiles.forEach(function (openFileValue, path) { // Invalidate default config file name for open file _this.configFileForOpenFiles.delete(path); // Filter out the files that need to be ignored @@ -157447,13 +162175,13 @@ var ts; return result; }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, includeProjectReferenceRedirectInfo, result) { - var _loop_5 = function (proj) { + var _loop_4 = function (proj) { var knownProject = ts.find(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName(); }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version, includeProjectReferenceRedirectInfo)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_5(proj); + _loop_4(proj); } }; /* @internal */ @@ -157593,7 +162321,7 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_6 = function (name) { + var _loop_5 = function (name) { var rule = this_2.safelist[name]; for (var _b = 0, normalizedNames_1 = normalizedNames; _b < normalizedNames_1.length; _b++) { var root = normalizedNames_1[_b]; @@ -157611,7 +162339,7 @@ var ts; } } if (rule.exclude) { - var _loop_8 = function (exclude) { + var _loop_7 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -157638,7 +162366,7 @@ var ts; }; for (var _e = 0, _f = rule.exclude; _e < _f.length; _e++) { var exclude = _f[_e]; - _loop_8(exclude); + _loop_7(exclude); } } else { @@ -157654,11 +162382,11 @@ var ts; var this_2 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_6(name); + _loop_5(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_7 = function (i) { + var _loop_6 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -157696,7 +162424,7 @@ var ts; }; var this_3 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_7(i); + _loop_6(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -157883,7 +162611,7 @@ var ts; var _this = this; var watchers = this.packageJsonFilesMap || (this.packageJsonFilesMap = new ts.Map()); if (!watchers.has(path)) { - this.invalidateProjectAutoImports(path); + this.invalidateProjectPackageJson(path); watchers.set(path, this.watchFactory.watchFile(path, function (fileName, eventKind) { var path = _this.toPath(fileName); switch (eventKind) { @@ -157891,11 +162619,11 @@ var ts; return ts.Debug.fail(); case ts.FileWatcherEventKind.Changed: _this.packageJsonCache.addOrUpdate(path); - _this.invalidateProjectAutoImports(path); + _this.invalidateProjectPackageJson(path); break; case ts.FileWatcherEventKind.Deleted: _this.packageJsonCache.delete(path); - _this.invalidateProjectAutoImports(path); + _this.invalidateProjectPackageJson(path); watchers.get(path).close(); watchers.delete(path); } @@ -157916,16 +162644,16 @@ var ts; } }; /*@internal*/ - ProjectService.prototype.invalidateProjectAutoImports = function (packageJsonPath) { - if (this.includePackageJsonAutoImports()) { - this.configuredProjects.forEach(invalidate); - this.inferredProjects.forEach(invalidate); - this.externalProjects.forEach(invalidate); - } + ProjectService.prototype.invalidateProjectPackageJson = function (packageJsonPath) { + this.configuredProjects.forEach(invalidate); + this.inferredProjects.forEach(invalidate); + this.externalProjects.forEach(invalidate); function invalidate(project) { - var _a; - if (!packageJsonPath || ((_a = project.packageJsonsForAutoImport) === null || _a === void 0 ? void 0 : _a.has(packageJsonPath))) { - project.markAutoImportProviderAsDirty(); + if (packageJsonPath) { + project.onPackageJsonChange(packageJsonPath); + } + else { + project.onAutoImportProviderSettingsChanged(); } } }; @@ -158144,24 +162872,24 @@ var ts; try { if (this.operationHost.isCancellationRequested()) { stop = true; - ts.tracing.instant("session" /* Session */, "stepCanceled", { seq: this.requestId, early: true }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "stepCanceled", { seq: this.requestId, early: true }); } else { - ts.tracing.push("session" /* Session */, "stepAction", { seq: this.requestId }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("session" /* Session */, "stepAction", { seq: this.requestId }); action(this); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } } catch (e) { // Cancellation or an error may have left incomplete events on the tracing stack. - ts.tracing.popAll(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.popAll(); stop = true; // ignore cancellation request if (e instanceof ts.OperationCanceledException) { - ts.tracing.instant("session" /* Session */, "stepCanceled", { seq: this.requestId }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "stepCanceled", { seq: this.requestId }); } else { - ts.tracing.instant("session" /* Session */, "stepError", { seq: this.requestId, message: e.message }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "stepError", { seq: this.requestId, message: e.message }); this.operationHost.logError(e, "delayed processing of request " + this.requestId); } } @@ -158263,7 +162991,7 @@ var ts; function combineProjectOutputForReferences(projects, defaultProject, initialLocation) { var outputs = []; combineProjectOutputWorker(projects, defaultProject, initialLocation, function (project, location, getMappedLocation) { - var _loop_9 = function (outputReferencedSymbol) { + var _loop_8 = function (outputReferencedSymbol) { var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); var definition = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : __assign(__assign({}, outputReferencedSymbol.definition), { textSpan: ts.createTextSpan(mappedDefinitionFile.pos, outputReferencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName, contextSpan: getMappedContextSpan(outputReferencedSymbol.definition, project) }); @@ -158282,7 +163010,7 @@ var ts; }; for (var _i = 0, _a = project.getLanguageService().findReferences(location.fileName, location.pos) || server.emptyArray; _i < _a.length; _i++) { var outputReferencedSymbol = _a[_i]; - _loop_9(outputReferencedSymbol); + _loop_8(outputReferencedSymbol); } }); return outputs.filter(function (o) { return o.references.length !== 0; }); @@ -158695,10 +163423,10 @@ var ts; return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.CompletionsFull)); }, _a[server.CommandNames.CompletionDetails] = function (request) { - return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*simplifiedResult*/ true)); + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*fullResult*/ false)); }, _a[server.CommandNames.CompletionDetailsFull] = function (request) { - return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*simplifiedResult*/ false)); + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*fullResult*/ true)); }, _a[server.CommandNames.CompileOnSaveAffectedFileList] = function (request) { return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments)); @@ -159091,7 +163819,7 @@ var ts; this.host.write(msgText); }; Session.prototype.event = function (body, eventName) { - ts.tracing.instant("session" /* Session */, "event", { eventName: eventName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "event", { eventName: eventName }); this.send(toEvent(eventName, body)); }; // For backwards-compatibility only. @@ -159242,7 +163970,8 @@ var ts; }; Session.prototype.getEncodedSemanticClassifications = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - return project.getLanguageService().getEncodedSemanticClassifications(file, args); + var format = args.format === "2020" ? "2020" /* TwentyTwenty */ : "original" /* Original */; + return project.getLanguageService().getEncodedSemanticClassifications(file, args, format); }; Session.prototype.getProject = function (projectFileName) { return projectFileName === undefined ? undefined : this.projectService.findProject(projectFileName); @@ -159323,7 +164052,7 @@ var ts; Session.prototype.mapDefinitionInfoLocations = function (definitions, project) { return definitions.map(function (info) { var newDocumentSpan = getMappedDocumentSpan(info, project); - return !newDocumentSpan ? info : __assign(__assign({}, newDocumentSpan), { containerKind: info.containerKind, containerName: info.containerName, kind: info.kind, name: info.name }); + return !newDocumentSpan ? info : __assign(__assign(__assign({}, newDocumentSpan), { containerKind: info.containerKind, containerName: info.containerName, kind: info.kind, name: info.name }), info.unverified && { unverified: info.unverified }); }); }; Session.prototype.getDefinitionAndBoundSpan = function (args, simplifiedResult) { @@ -159361,9 +164090,27 @@ var ts; result.diagnostics.map(function (d) { return formatDiagnosticToProtocol(d, /*includeFileName*/ true); }) }) : result; }; + Session.prototype.mapJSDocTagInfo = function (tags, project, richResponse) { + var _this = this; + return tags ? tags.map(function (tag) { + var _a; + return (__assign(__assign({}, tag), { text: richResponse ? _this.mapDisplayParts(tag.text, project) : (_a = tag.text) === null || _a === void 0 ? void 0 : _a.map(function (part) { return part.text; }).join("") })); + }) : []; + }; + Session.prototype.mapDisplayParts = function (parts, project) { + var _this = this; + if (!parts) { + return []; + } + return parts.map(function (part) { return part.kind !== "linkName" ? part : __assign(__assign({}, part), { target: _this.toFileSpan(part.target.fileName, part.target.textSpan, project) }); }); + }; + Session.prototype.mapSignatureHelpItems = function (items, project, richResponse) { + var _this = this; + return items.map(function (item) { return (__assign(__assign({}, item), { documentation: _this.mapDisplayParts(item.documentation, project), parameters: item.parameters.map(function (p) { return (__assign(__assign({}, p), { documentation: _this.mapDisplayParts(p.documentation, project) })); }), tags: _this.mapJSDocTagInfo(item.tags, project, richResponse) })); }); + }; Session.prototype.mapDefinitionInfo = function (definitions, project) { var _this = this; - return definitions.map(function (def) { return _this.toFileSpanWithContext(def.fileName, def.textSpan, def.contextSpan, project); }); + return definitions.map(function (def) { return (__assign(__assign({}, _this.toFileSpanWithContext(def.fileName, def.textSpan, def.contextSpan, project)), def.unverified && { unverified: def.unverified })); }); }; /* * When we map a .d.ts location to .ts, Visual Studio gets confused because there's no associated Roslyn Document in @@ -159670,7 +164417,7 @@ var ts; Session.prototype.getDocCommentTemplate = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; var position = this.getPositionInFile(args, file); - return languageService.getDocCommentTemplateAtPosition(file, position); + return languageService.getDocCommentTemplateAtPosition(file, position, this.getPreferences(file)); }; Session.prototype.getSpanOfEnclosingComment = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; @@ -159707,21 +164454,21 @@ var ts; if (!quickInfo) { return undefined; } + var useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc; if (simplifiedResult) { var displayString = ts.displayPartsToString(quickInfo.displayParts); - var docString = ts.displayPartsToString(quickInfo.documentation); return { kind: quickInfo.kind, kindModifiers: quickInfo.kindModifiers, start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start), end: scriptInfo.positionToLineOffset(ts.textSpanEnd(quickInfo.textSpan)), displayString: displayString, - documentation: docString, - tags: quickInfo.tags || [] + documentation: useDisplayParts ? this.mapDisplayParts(quickInfo.documentation, project) : ts.displayPartsToString(quickInfo.documentation), + tags: this.mapJSDocTagInfo(quickInfo.tags, project, useDisplayParts), }; } else { - return quickInfo; + return useDisplayParts ? quickInfo : __assign(__assign({}, quickInfo), { tags: this.mapJSDocTagInfo(quickInfo.tags, project, /*useDisplayParts*/ false) }); } }; Session.prototype.getFormattingEditsForRange = function (args) { @@ -159812,14 +164559,14 @@ var ts; if (kind === "completions-full" /* CompletionsFull */) return completions; var prefix = args.prefix || ""; - var entries = ts.mapDefined(completions.entries, function (entry) { + var entries = ts.stableSort(ts.mapDefined(completions.entries, function (entry) { if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { - var name = entry.name, kind_1 = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended, isPackageJsonImport = entry.isPackageJsonImport; + var name = entry.name, kind_1 = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, sourceDisplay = entry.sourceDisplay, isSnippet = entry.isSnippet, isRecommended = entry.isRecommended, isPackageJsonImport = entry.isPackageJsonImport, isImportStatementCompletion = entry.isImportStatementCompletion, data = entry.data; var convertedSpan = replacementSpan ? toProtocolTextSpan(replacementSpan, scriptInfo) : undefined; // Use `hasAction || undefined` to avoid serializing `false`. - return { name: name, kind: kind_1, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended, isPackageJsonImport: isPackageJsonImport }; + return { name: name, kind: kind_1, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, isSnippet: isSnippet, hasAction: hasAction || undefined, source: source, sourceDisplay: sourceDisplay, isRecommended: isRecommended, isPackageJsonImport: isPackageJsonImport, isImportStatementCompletion: isImportStatementCompletion, data: data }; } - }).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); + }), function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); if (kind === "completions" /* Completions */) { if (completions.metadata) entries.metadata = completions.metadata; @@ -159828,19 +164575,20 @@ var ts; var res = __assign(__assign({}, completions), { optionalReplacementSpan: completions.optionalReplacementSpan && toProtocolTextSpan(completions.optionalReplacementSpan, scriptInfo), entries: entries }); return res; }; - Session.prototype.getCompletionEntryDetails = function (args, simplifiedResult) { + Session.prototype.getCompletionEntryDetails = function (args, fullResult) { var _this = this; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); var formattingOptions = project.projectService.getFormatCodeOptions(file); + var useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc; var result = ts.mapDefined(args.entryNames, function (entryName) { - var _a = typeof entryName === "string" ? { name: entryName, source: undefined } : entryName, name = _a.name, source = _a.source; - return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source, _this.getPreferences(file)); + var _a = typeof entryName === "string" ? { name: entryName, source: undefined, data: undefined } : entryName, name = _a.name, source = _a.source, data = _a.data; + return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source, _this.getPreferences(file), data ? ts.cast(data, isCompletionEntryData) : undefined); }); - return simplifiedResult - ? result.map(function (details) { return (__assign(__assign({}, details), { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(action); }) })); }) - : result; + return fullResult + ? (useDisplayParts ? result : result.map(function (details) { return (__assign(__assign({}, details), { tags: _this.mapJSDocTagInfo(details.tags, project, /*richResponse*/ false) })); })) + : result.map(function (details) { return (__assign(__assign({}, details), { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(action); }), documentation: _this.mapDisplayParts(details.documentation, project), tags: _this.mapJSDocTagInfo(details.tags, project, useDisplayParts) })); }); }; Session.prototype.getCompileOnSaveAffectedFileList = function (args) { var _this = this; @@ -159886,29 +164634,25 @@ var ts; !emitSkipped; }; Session.prototype.getSignatureHelpItems = function (args, simplifiedResult) { + var _this = this; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); var helpItems = project.getLanguageService().getSignatureHelpItems(file, position, args); - if (!helpItems) { - return undefined; - } - if (simplifiedResult) { + var useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc; + if (helpItems && simplifiedResult) { var span = helpItems.applicableSpan; - return { - items: helpItems.items, - applicableSpan: { + return __assign(__assign({}, helpItems), { applicableSpan: { start: scriptInfo.positionToLineOffset(span.start), end: scriptInfo.positionToLineOffset(span.start + span.length) - }, - selectedItemIndex: helpItems.selectedItemIndex, - argumentIndex: helpItems.argumentIndex, - argumentCount: helpItems.argumentCount, - }; + }, items: this.mapSignatureHelpItems(helpItems.items, project, useDisplayParts) }); } - else { + else if (useDisplayParts || !helpItems) { return helpItems; } + else { + return __assign(__assign({}, helpItems), { items: helpItems.items.map(function (item) { return (__assign(__assign({}, item), { tags: _this.mapJSDocTagInfo(item.tags, project, /*richResponse*/ false) })); }) }); + } }; Session.prototype.toPendingErrorCheck = function (uncheckedFileName) { var fileName = server.toNormalizedPath(uncheckedFileName); @@ -160114,11 +164858,14 @@ var ts; return result; } }; - Session.prototype.organizeImports = function (_a, simplifiedResult) { - var scope = _a.scope; - ts.Debug.assert(scope.type === "file"); - var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project; - var changes = project.getLanguageService().organizeImports({ type: "file", fileName: file }, this.getFormatOptions(file), this.getPreferences(file)); + Session.prototype.organizeImports = function (args, simplifiedResult) { + ts.Debug.assert(args.scope.type === "file"); + var _a = this.getFileAndProject(args.scope.args), file = _a.file, project = _a.project; + var changes = project.getLanguageService().organizeImports({ + fileName: file, + skipDestructiveCodeActions: args.skipDestructiveCodeActions, + type: "file", + }, this.getFormatOptions(file), this.getPreferences(file)); if (simplifiedResult) { return this.mapTextChangesToCodeEdits(changes); } @@ -160140,7 +164887,22 @@ var ts; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var _b = this.getStartAndEndPosition(args, scriptInfo), startPosition = _b.startPosition, endPosition = _b.endPosition; - var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file)); + var codeActions; + try { + codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file)); + } + catch (e) { + var ls = project.getLanguageService(); + var existingDiagCodes_1 = __spreadArray(__spreadArray(__spreadArray([], ls.getSyntacticDiagnostics(file)), ls.getSemanticDiagnostics(file)), ls.getSuggestionDiagnostics(file)).map(function (d) { + return ts.decodedTextSpanIntersectsWith(startPosition, endPosition - startPosition, d.start, d.length) + && d.code; + }); + var badCode = args.errorCodes.find(function (c) { return !existingDiagCodes_1.includes(c); }); + if (badCode !== undefined) { + e.message = "BADCLIENT: Bad error code, " + badCode + " not found in range " + startPosition + ".." + endPosition + " (found: " + existingDiagCodes_1.join(", ") + "); could have caused this error:\n" + e.message; + } + throw e; + } return simplifiedResult ? codeActions.map(function (codeAction) { return _this.mapCodeFixAction(codeAction); }) : codeActions; }; Session.prototype.getCombinedCodeFix = function (_a, simplifiedResult) { @@ -160463,11 +165225,11 @@ var ts; try { request = this.parseMessage(message); relevantFile = request.arguments && request.arguments.file ? request.arguments : undefined; - ts.tracing.instant("session" /* Session */, "request", { seq: request.seq, command: request.command }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "request", { seq: request.seq, command: request.command }); ts.perfLogger.logStartCommand("" + request.command, this.toStringMessage(message).substring(0, 100)); - ts.tracing.push("session" /* Session */, "executeCommand", { seq: request.seq, command: request.command }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("session" /* Session */, "executeCommand", { seq: request.seq, command: request.command }, /*separateBeginAndEnd*/ true); var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (this.logger.hasLevel(server.LogLevel.requestTime)) { var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); if (responseRequired) { @@ -160479,7 +165241,7 @@ var ts; } // Note: Log before writing the response, else the editor can complete its activity before the server does ts.perfLogger.logStopCommand("" + request.command, "Success"); - ts.tracing.instant("session" /* Session */, "response", { seq: request.seq, command: request.command, success: !!response }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "response", { seq: request.seq, command: request.command, success: !!response }); if (response) { this.doOutput(response, request.command, request.seq, /*success*/ true); } @@ -160489,17 +165251,17 @@ var ts; } catch (err) { // Cancellation or an error may have left incomplete events on the tracing stack. - ts.tracing.popAll(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.popAll(); if (err instanceof ts.OperationCanceledException) { // Handle cancellation exceptions ts.perfLogger.logStopCommand("" + (request && request.command), "Canceled: " + err); - ts.tracing.instant("session" /* Session */, "commandCanceled", { seq: request === null || request === void 0 ? void 0 : request.seq, command: request === null || request === void 0 ? void 0 : request.command }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "commandCanceled", { seq: request === null || request === void 0 ? void 0 : request.seq, command: request === null || request === void 0 ? void 0 : request.command }); this.doOutput({ canceled: true }, request.command, request.seq, /*success*/ true); return; } this.logErrorWorker(err, this.toStringMessage(message), relevantFile); ts.perfLogger.logStopCommand("" + (request && request.command), "Error: " + err); - ts.tracing.instant("session" /* Session */, "commandError", { seq: request === null || request === void 0 ? void 0 : request.seq, command: request === null || request === void 0 ? void 0 : request.command, message: err.message }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "commandError", { seq: request === null || request === void 0 ? void 0 : request.seq, command: request === null || request === void 0 ? void 0 : request.command, message: err.message }); this.doOutput( /*info*/ undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, /*success*/ false, "Error processing request. " + err.message + "\n" + err.stack); @@ -160583,6 +165345,13 @@ var ts; isWriteAccess: isWriteAccess, isDefinition: isDefinition }); } + function isCompletionEntryData(data) { + return data === undefined || data && typeof data === "object" + && typeof data.exportName === "string" + && (data.fileName === undefined || typeof data.fileName === "string") + && (data.ambientModuleName === undefined || typeof data.ambientModuleName === "string" + && (data.isPackageJsonImport === undefined || typeof data.isPackageJsonImport === "boolean")); + } })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); /*@internal*/ @@ -162352,7 +167121,7 @@ var ts; }, factoryDeprecation); /** @deprecated Use `factory.createJSDocParameterTag` or the factory supplied by your transformation context instead. */ ts.createJSDocParamTag = ts.Debug.deprecate(function createJSDocParamTag(name, isBracketed, typeExpression, comment) { - return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, isBracketed, typeExpression, /*isNameFirst*/ false, comment); + return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, isBracketed, typeExpression, /*isNameFirst*/ false, comment ? ts.factory.createNodeArray([ts.factory.createJSDocText(comment)]) : undefined); }, factoryDeprecation); /** @deprecated Use `factory.createComma` or the factory supplied by your transformation context instead. */ ts.createComma = ts.Debug.deprecate(function createComma(left, right) { @@ -162402,7 +167171,7 @@ var ts; ts.createNode = ts.Debug.deprecate(function createNode(kind, pos, end) { if (pos === void 0) { pos = 0; } if (end === void 0) { end = 0; } - return ts.setTextRangePosEnd(kind === 297 /* SourceFile */ ? ts.parseBaseNodeFactory.createBaseSourceFileNode(kind) : + return ts.setTextRangePosEnd(kind === 298 /* SourceFile */ ? ts.parseBaseNodeFactory.createBaseSourceFileNode(kind) : kind === 78 /* Identifier */ ? ts.parseBaseNodeFactory.createBaseIdentifierNode(kind) : kind === 79 /* PrivateIdentifier */ ? ts.parseBaseNodeFactory.createBasePrivateIdentifierNode(kind) : !ts.isNodeKind(kind) ? ts.parseBaseNodeFactory.createBaseTokenNode(kind) : @@ -162431,13 +167200,30 @@ var ts; // #region Renamed node Tests /** @deprecated Use `isTypeAssertionExpression` instead. */ ts.isTypeAssertion = ts.Debug.deprecate(function isTypeAssertion(node) { - return node.kind === 206 /* TypeAssertionExpression */; + return node.kind === 207 /* TypeAssertionExpression */; }, { since: "4.0", warnAfter: "4.1", message: "Use `isTypeAssertionExpression` instead." }); // #endregion + // DEPRECATION: Renamed node tests + // DEPRECATION PLAN: + // - soft: 4.2 + // - warn: 4.3 + // - error: TBD + // #region Renamed node Tests + /** + * @deprecated Use `isMemberName` instead. + */ + ts.isIdentifierOrPrivateIdentifier = ts.Debug.deprecate(function isIdentifierOrPrivateIdentifier(node) { + return ts.isMemberName(node); + }, { + since: "4.2", + warnAfter: "4.3", + message: "Use `isMemberName` instead." + }); + // #endregion Renamed node Tests })(ts || (ts = {})); /*@internal*/ var ts; @@ -162557,20 +167343,6 @@ var ts; var useWatchGuard = process.platform === "win32" && nodeVersion >= 4; var originalWatchDirectory = sys.watchDirectory.bind(sys); var logger = createLogger(); - // REVIEW: for now this implementation uses polling. - // The advantage of polling is that it works reliably - // on all os and with network mounted files. - // For 90 referenced files, the average time to detect - // changes is 2*msInterval (by default 5 seconds). - // The overhead of this is .04 percent (1/2500) with - // average pause of < 1 millisecond (and max - // pause less than 1.5 milliseconds); question is - // do we anticipate reference sets in the 100s and - // do we care about waiting 10-20 seconds to detect - // changes for large reference sets? If so, do we want - // to increase the chunk size or decrease the interval - // time dynamically to match the large reference set? - var pollingWatchedFileSet = createPollingWatchedFileSet(); var pending = []; var canWrite = true; if (useWatchGuard) { @@ -162622,12 +167394,20 @@ var ts; } // Override sys.write because fs.writeSync is not reliable on Node 4 sys.write = function (s) { return writeMessage(sys.bufferFrom(s, "utf8")); }; - sys.watchFile = function (fileName, callback) { - var watchedFile = pollingWatchedFileSet.addFile(fileName, callback); - return { - close: function () { return pollingWatchedFileSet.removeFile(watchedFile); } - }; - }; + // REVIEW: for now this implementation uses polling. + // The advantage of polling is that it works reliably + // on all os and with network mounted files. + // For 90 referenced files, the average time to detect + // changes is 2*msInterval (by default 5 seconds). + // The overhead of this is .04 percent (1/2500) with + // average pause of < 1 millisecond (and max + // pause less than 1.5 milliseconds); question is + // do we anticipate reference sets in the 100s and + // do we care about waiting 10-20 seconds to detect + // changes for large reference sets? If so, do we want + // to increase the chunk size or decrease the interval + // time dynamically to match the large reference set? + sys.defaultWatchFileKind = function () { return ts.WatchFileKind.FixedChunkSizePolling; }; /* eslint-disable no-restricted-globals */ sys.setTimeout = setTimeout; sys.clearTimeout = clearTimeout; @@ -162690,83 +167470,6 @@ var ts; var logVerbosity = cmdLineVerbosity || envLogOptions.detailLevel; 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 - // average async stat takes about 30 microseconds - // set chunk size to do 30 files in < 1 millisecond - function createPollingWatchedFileSet(interval, chunkSize) { - if (interval === void 0) { interval = 2500; } - if (chunkSize === void 0) { chunkSize = 30; } - var watchedFiles = []; - var nextFileToCheck = 0; - return { getModifiedTime: getModifiedTime, poll: poll, startWatchTimer: startWatchTimer, addFile: addFile, removeFile: removeFile }; - function getModifiedTime(fileName) { - // Caller guarantees that `fileName` exists, so there'd be no benefit from throwIfNoEntry - return fs.statSync(fileName).mtime; - } - function poll(checkedIndex) { - var watchedFile = watchedFiles[checkedIndex]; - if (!watchedFile) { - return; - } - fs.stat(watchedFile.fileName, function (err, stats) { - if (err) { - if (err.code === "ENOENT") { - if (watchedFile.mtime.getTime() !== 0) { - watchedFile.mtime = ts.missingFileModifiedTime; - watchedFile.callback(watchedFile.fileName, ts.FileWatcherEventKind.Deleted); - } - } - else { - watchedFile.callback(watchedFile.fileName, ts.FileWatcherEventKind.Changed); - } - } - else { - ts.onWatchedFileStat(watchedFile, stats.mtime); - } - }); - } - // this implementation uses polling and - // stat due to inconsistencies of fs.watch - // and efficiency of stat on modern filesystems - function startWatchTimer() { - // eslint-disable-next-line no-restricted-globals - setInterval(function () { - var count = 0; - var nextToCheck = nextFileToCheck; - var firstCheck = -1; - while ((count < chunkSize) && (nextToCheck !== firstCheck)) { - poll(nextToCheck); - if (firstCheck < 0) { - firstCheck = nextToCheck; - } - nextToCheck++; - if (nextToCheck === watchedFiles.length) { - nextToCheck = 0; - } - count++; - } - nextFileToCheck = nextToCheck; - }, interval); - } - function addFile(fileName, callback) { - var file = { - fileName: fileName, - callback: callback, - mtime: sys.fileExists(fileName) - ? getModifiedTime(fileName) - : ts.missingFileModifiedTime // Any subsequent modification will occur after this time - }; - watchedFiles.push(file); - if (watchedFiles.length === 1) { - startWatchTimer(); - } - return file; - } - function removeFile(file) { - ts.unorderedRemoveItem(watchedFiles, file); - } - } function writeMessage(buf) { if (!canWrite) { pending.push(buf); @@ -163120,9 +167823,7 @@ var ts; IOSession.prototype.exit = function () { this.logger.info("Exiting..."); this.projectService.closeLog(); - if (traceDir) { - ts.tracing.stopTracing(ts.emptyArray); - } + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.stopTracing(); process.exit(0); }; IOSession.prototype.listen = function () { @@ -163149,7 +167850,7 @@ var ts; ? ts.stripQuotes(commandLineTraceDir) : process.env.TSS_TRACE; if (traceDir) { - ts.tracing.startTracing(2 /* Server */, traceDir); + ts.startTracing("server", traceDir); } var ioSession = new IOSession(); process.on("uncaughtException", function (err) { diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index be9c82b1e1d9f..6195d669a8306 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 = "4.2"; + const versionMajorMinor = "4.3"; /** The version of the TypeScript compiler release */ const version: string; /** @@ -260,192 +260,196 @@ declare namespace ts { FromKeyword = 153, GlobalKeyword = 154, BigIntKeyword = 155, - OfKeyword = 156, - QualifiedName = 157, - ComputedPropertyName = 158, - TypeParameter = 159, - Parameter = 160, - Decorator = 161, - PropertySignature = 162, - PropertyDeclaration = 163, - MethodSignature = 164, - MethodDeclaration = 165, - Constructor = 166, - GetAccessor = 167, - SetAccessor = 168, - CallSignature = 169, - ConstructSignature = 170, - IndexSignature = 171, - TypePredicate = 172, - TypeReference = 173, - FunctionType = 174, - ConstructorType = 175, - TypeQuery = 176, - TypeLiteral = 177, - ArrayType = 178, - TupleType = 179, - OptionalType = 180, - RestType = 181, - UnionType = 182, - IntersectionType = 183, - ConditionalType = 184, - InferType = 185, - ParenthesizedType = 186, - ThisType = 187, - TypeOperator = 188, - IndexedAccessType = 189, - MappedType = 190, - LiteralType = 191, - NamedTupleMember = 192, - TemplateLiteralType = 193, - TemplateLiteralTypeSpan = 194, - ImportType = 195, - ObjectBindingPattern = 196, - ArrayBindingPattern = 197, - BindingElement = 198, - ArrayLiteralExpression = 199, - ObjectLiteralExpression = 200, - PropertyAccessExpression = 201, - ElementAccessExpression = 202, - CallExpression = 203, - NewExpression = 204, - TaggedTemplateExpression = 205, - TypeAssertionExpression = 206, - ParenthesizedExpression = 207, - FunctionExpression = 208, - ArrowFunction = 209, - DeleteExpression = 210, - TypeOfExpression = 211, - VoidExpression = 212, - AwaitExpression = 213, - PrefixUnaryExpression = 214, - PostfixUnaryExpression = 215, - BinaryExpression = 216, - ConditionalExpression = 217, - TemplateExpression = 218, - YieldExpression = 219, - SpreadElement = 220, - ClassExpression = 221, - OmittedExpression = 222, - ExpressionWithTypeArguments = 223, - AsExpression = 224, - NonNullExpression = 225, - MetaProperty = 226, - SyntheticExpression = 227, - TemplateSpan = 228, - SemicolonClassElement = 229, - Block = 230, - EmptyStatement = 231, - VariableStatement = 232, - ExpressionStatement = 233, - IfStatement = 234, - DoStatement = 235, - WhileStatement = 236, - ForStatement = 237, - ForInStatement = 238, - ForOfStatement = 239, - ContinueStatement = 240, - BreakStatement = 241, - ReturnStatement = 242, - WithStatement = 243, - SwitchStatement = 244, - LabeledStatement = 245, - ThrowStatement = 246, - TryStatement = 247, - DebuggerStatement = 248, - VariableDeclaration = 249, - VariableDeclarationList = 250, - FunctionDeclaration = 251, - ClassDeclaration = 252, - InterfaceDeclaration = 253, - TypeAliasDeclaration = 254, - EnumDeclaration = 255, - ModuleDeclaration = 256, - ModuleBlock = 257, - CaseBlock = 258, - NamespaceExportDeclaration = 259, - ImportEqualsDeclaration = 260, - ImportDeclaration = 261, - ImportClause = 262, - NamespaceImport = 263, - NamedImports = 264, - ImportSpecifier = 265, - ExportAssignment = 266, - ExportDeclaration = 267, - NamedExports = 268, - NamespaceExport = 269, - ExportSpecifier = 270, - MissingDeclaration = 271, - ExternalModuleReference = 272, - JsxElement = 273, - JsxSelfClosingElement = 274, - JsxOpeningElement = 275, - JsxClosingElement = 276, - JsxFragment = 277, - JsxOpeningFragment = 278, - JsxClosingFragment = 279, - JsxAttribute = 280, - JsxAttributes = 281, - JsxSpreadAttribute = 282, - JsxExpression = 283, - CaseClause = 284, - DefaultClause = 285, - HeritageClause = 286, - CatchClause = 287, - PropertyAssignment = 288, - ShorthandPropertyAssignment = 289, - SpreadAssignment = 290, - EnumMember = 291, - UnparsedPrologue = 292, - UnparsedPrepend = 293, - UnparsedText = 294, - UnparsedInternalText = 295, - UnparsedSyntheticReference = 296, - SourceFile = 297, - Bundle = 298, - UnparsedSource = 299, - InputFiles = 300, - JSDocTypeExpression = 301, - JSDocNameReference = 302, - JSDocAllType = 303, - JSDocUnknownType = 304, - JSDocNullableType = 305, - JSDocNonNullableType = 306, - JSDocOptionalType = 307, - JSDocFunctionType = 308, - JSDocVariadicType = 309, - JSDocNamepathType = 310, - JSDocComment = 311, - JSDocTypeLiteral = 312, - JSDocSignature = 313, - JSDocTag = 314, - JSDocAugmentsTag = 315, - JSDocImplementsTag = 316, - JSDocAuthorTag = 317, - JSDocDeprecatedTag = 318, - JSDocClassTag = 319, - JSDocPublicTag = 320, - JSDocPrivateTag = 321, - JSDocProtectedTag = 322, - JSDocReadonlyTag = 323, - JSDocCallbackTag = 324, - JSDocEnumTag = 325, - JSDocParameterTag = 326, - JSDocReturnTag = 327, - JSDocThisTag = 328, - JSDocTypeTag = 329, - JSDocTemplateTag = 330, - JSDocTypedefTag = 331, - JSDocSeeTag = 332, - JSDocPropertyTag = 333, - SyntaxList = 334, - NotEmittedStatement = 335, - PartiallyEmittedExpression = 336, - CommaListExpression = 337, - MergeDeclarationMarker = 338, - EndOfDeclarationMarker = 339, - SyntheticReferenceExpression = 340, - Count = 341, + OverrideKeyword = 156, + OfKeyword = 157, + QualifiedName = 158, + ComputedPropertyName = 159, + TypeParameter = 160, + Parameter = 161, + Decorator = 162, + PropertySignature = 163, + PropertyDeclaration = 164, + MethodSignature = 165, + MethodDeclaration = 166, + Constructor = 167, + GetAccessor = 168, + SetAccessor = 169, + CallSignature = 170, + ConstructSignature = 171, + IndexSignature = 172, + TypePredicate = 173, + TypeReference = 174, + FunctionType = 175, + ConstructorType = 176, + TypeQuery = 177, + TypeLiteral = 178, + ArrayType = 179, + TupleType = 180, + OptionalType = 181, + RestType = 182, + UnionType = 183, + IntersectionType = 184, + ConditionalType = 185, + InferType = 186, + ParenthesizedType = 187, + ThisType = 188, + TypeOperator = 189, + IndexedAccessType = 190, + MappedType = 191, + LiteralType = 192, + NamedTupleMember = 193, + TemplateLiteralType = 194, + TemplateLiteralTypeSpan = 195, + ImportType = 196, + ObjectBindingPattern = 197, + ArrayBindingPattern = 198, + BindingElement = 199, + ArrayLiteralExpression = 200, + ObjectLiteralExpression = 201, + PropertyAccessExpression = 202, + ElementAccessExpression = 203, + CallExpression = 204, + NewExpression = 205, + TaggedTemplateExpression = 206, + TypeAssertionExpression = 207, + ParenthesizedExpression = 208, + FunctionExpression = 209, + ArrowFunction = 210, + DeleteExpression = 211, + TypeOfExpression = 212, + VoidExpression = 213, + AwaitExpression = 214, + PrefixUnaryExpression = 215, + PostfixUnaryExpression = 216, + BinaryExpression = 217, + ConditionalExpression = 218, + TemplateExpression = 219, + YieldExpression = 220, + SpreadElement = 221, + ClassExpression = 222, + OmittedExpression = 223, + ExpressionWithTypeArguments = 224, + AsExpression = 225, + NonNullExpression = 226, + MetaProperty = 227, + SyntheticExpression = 228, + TemplateSpan = 229, + SemicolonClassElement = 230, + Block = 231, + EmptyStatement = 232, + VariableStatement = 233, + ExpressionStatement = 234, + IfStatement = 235, + DoStatement = 236, + WhileStatement = 237, + ForStatement = 238, + ForInStatement = 239, + ForOfStatement = 240, + ContinueStatement = 241, + BreakStatement = 242, + ReturnStatement = 243, + WithStatement = 244, + SwitchStatement = 245, + LabeledStatement = 246, + ThrowStatement = 247, + TryStatement = 248, + DebuggerStatement = 249, + VariableDeclaration = 250, + VariableDeclarationList = 251, + FunctionDeclaration = 252, + ClassDeclaration = 253, + InterfaceDeclaration = 254, + TypeAliasDeclaration = 255, + EnumDeclaration = 256, + ModuleDeclaration = 257, + ModuleBlock = 258, + CaseBlock = 259, + NamespaceExportDeclaration = 260, + ImportEqualsDeclaration = 261, + ImportDeclaration = 262, + ImportClause = 263, + NamespaceImport = 264, + NamedImports = 265, + ImportSpecifier = 266, + ExportAssignment = 267, + ExportDeclaration = 268, + NamedExports = 269, + NamespaceExport = 270, + ExportSpecifier = 271, + MissingDeclaration = 272, + ExternalModuleReference = 273, + JsxElement = 274, + JsxSelfClosingElement = 275, + JsxOpeningElement = 276, + JsxClosingElement = 277, + JsxFragment = 278, + JsxOpeningFragment = 279, + JsxClosingFragment = 280, + JsxAttribute = 281, + JsxAttributes = 282, + JsxSpreadAttribute = 283, + JsxExpression = 284, + CaseClause = 285, + DefaultClause = 286, + HeritageClause = 287, + CatchClause = 288, + PropertyAssignment = 289, + ShorthandPropertyAssignment = 290, + SpreadAssignment = 291, + EnumMember = 292, + UnparsedPrologue = 293, + UnparsedPrepend = 294, + UnparsedText = 295, + UnparsedInternalText = 296, + UnparsedSyntheticReference = 297, + SourceFile = 298, + Bundle = 299, + UnparsedSource = 300, + InputFiles = 301, + JSDocTypeExpression = 302, + JSDocNameReference = 303, + JSDocAllType = 304, + JSDocUnknownType = 305, + JSDocNullableType = 306, + JSDocNonNullableType = 307, + JSDocOptionalType = 308, + JSDocFunctionType = 309, + JSDocVariadicType = 310, + JSDocNamepathType = 311, + JSDocComment = 312, + JSDocText = 313, + JSDocTypeLiteral = 314, + JSDocSignature = 315, + JSDocLink = 316, + JSDocTag = 317, + JSDocAugmentsTag = 318, + JSDocImplementsTag = 319, + JSDocAuthorTag = 320, + JSDocDeprecatedTag = 321, + JSDocClassTag = 322, + JSDocPublicTag = 323, + JSDocPrivateTag = 324, + JSDocProtectedTag = 325, + JSDocReadonlyTag = 326, + JSDocOverrideTag = 327, + JSDocCallbackTag = 328, + JSDocEnumTag = 329, + JSDocParameterTag = 330, + JSDocReturnTag = 331, + JSDocThisTag = 332, + JSDocTypeTag = 333, + JSDocTemplateTag = 334, + JSDocTypedefTag = 335, + JSDocSeeTag = 336, + JSDocPropertyTag = 337, + SyntaxList = 338, + NotEmittedStatement = 339, + PartiallyEmittedExpression = 340, + CommaListExpression = 341, + MergeDeclarationMarker = 342, + EndOfDeclarationMarker = 343, + SyntheticReferenceExpression = 344, + Count = 345, FirstAssignment = 62, LastAssignment = 77, FirstCompoundAssignment = 63, @@ -453,15 +457,15 @@ declare namespace ts { FirstReservedWord = 80, LastReservedWord = 115, FirstKeyword = 80, - LastKeyword = 156, + LastKeyword = 157, FirstFutureReservedWord = 116, LastFutureReservedWord = 124, - FirstTypeNode = 172, - LastTypeNode = 195, + FirstTypeNode = 173, + LastTypeNode = 196, FirstPunctuation = 18, LastPunctuation = 77, FirstToken = 0, - LastToken = 156, + LastToken = 157, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, @@ -470,20 +474,20 @@ declare namespace ts { LastTemplateToken = 17, FirstBinaryOperator = 29, LastBinaryOperator = 77, - FirstStatement = 232, - LastStatement = 248, - FirstNode = 157, - FirstJSDocNode = 301, - LastJSDocNode = 333, - FirstJSDocTagNode = 314, - LastJSDocTagNode = 333, + FirstStatement = 233, + LastStatement = 249, + FirstNode = 158, + FirstJSDocNode = 302, + LastJSDocNode = 337, + FirstJSDocTagNode = 317, + LastJSDocTagNode = 337, } export type TriviaSyntaxKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; export type LiteralSyntaxKind = SyntaxKind.NumericLiteral | SyntaxKind.BigIntLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral; export type PseudoLiteralSyntaxKind = SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle | SyntaxKind.TemplateTail; export type PunctuationSyntaxKind = SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.CloseParenToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.DotToken | SyntaxKind.DotDotDotToken | SyntaxKind.SemicolonToken | SyntaxKind.CommaToken | SyntaxKind.QuestionDotToken | SyntaxKind.LessThanToken | SyntaxKind.LessThanSlashToken | SyntaxKind.GreaterThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.EqualsEqualsToken | SyntaxKind.ExclamationEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.EqualsGreaterThanToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.AsteriskToken | SyntaxKind.AsteriskAsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken | SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken | SyntaxKind.ExclamationToken | SyntaxKind.TildeToken | SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken | SyntaxKind.QuestionQuestionToken | SyntaxKind.QuestionToken | SyntaxKind.ColonToken | SyntaxKind.AtToken | SyntaxKind.BacktickToken | SyntaxKind.EqualsToken | SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken; - export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | 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.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | 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; - export type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.StaticKeyword; + export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | 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.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | 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; + export type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword; export type KeywordTypeSyntaxKind = SyntaxKind.AnyKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VoidKeyword; export type TokenSyntaxKind = SyntaxKind.Unknown | SyntaxKind.EndOfFileToken | TriviaSyntaxKind | LiteralSyntaxKind | PseudoLiteralSyntaxKind | PunctuationSyntaxKind | SyntaxKind.Identifier | KeywordSyntaxKind; export type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; @@ -533,13 +537,14 @@ declare namespace ts { Const = 2048, HasComputedJSDocModifiers = 4096, Deprecated = 8192, + Override = 16384, HasComputedFlags = 536870912, AccessibilityModifier = 28, - ParameterPropertyModifier = 92, + ParameterPropertyModifier = 16476, NonPublicAccessibilityModifier = 24, - TypeScriptModifier = 2270, + TypeScriptModifier = 18654, ExportDefault = 513, - All = 11263 + All = 27647 } export enum JsxFlags { None = 0, @@ -558,7 +563,7 @@ declare namespace ts { } export interface JSDocContainer { } - export type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | NamespaceExportDeclaration | ExportAssignment | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | NamedTupleMember | EndOfFileToken; + export type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | EmptyStatement | DebuggerStatement | Block | VariableStatement | ExpressionStatement | IfStatement | DoStatement | WhileStatement | ForStatement | ForInStatement | ForOfStatement | BreakStatement | ContinueStatement | ReturnStatement | WithStatement | SwitchStatement | LabeledStatement | ThrowStatement | TryStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | VariableDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | NamespaceExportDeclaration | ExportAssignment | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | NamedTupleMember | EndOfFileToken; export type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; export type HasTypeArguments = CallExpression | NewExpression | TaggedTemplateExpression | JsxOpeningElement | JsxSelfClosingElement; export type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; @@ -603,10 +608,11 @@ declare namespace ts { export type ProtectedKeyword = ModifierToken; export type PublicKeyword = ModifierToken; export type ReadonlyKeyword = ModifierToken; + export type OverrideKeyword = ModifierToken; export type StaticKeyword = ModifierToken; /** @deprecated Use `ReadonlyKeyword` instead. */ export type ReadonlyToken = ReadonlyKeyword; - export type Modifier = AbstractKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | ReadonlyKeyword | StaticKeyword; + export type Modifier = AbstractKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | OverrideKeyword | ReadonlyKeyword | StaticKeyword; export type AccessibilityModifier = PublicKeyword | PrivateKeyword | ProtectedKeyword; export type ParameterPropertyModifier = AccessibilityModifier | ReadonlyKeyword; export type ClassMemberModifier = AccessibilityModifier | ReadonlyKeyword | StaticKeyword; @@ -638,6 +644,7 @@ declare namespace ts { } export type EntityName = Identifier | QualifiedName; export type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | PrivateIdentifier; + export type MemberName = Identifier | PrivateIdentifier; export type DeclarationName = Identifier | PrivateIdentifier | StringLiteralLike | NumericLiteral | ComputedPropertyName | ElementAccessExpression | BindingPattern | EntityNameExpression; export interface Declaration extends Node { _declarationBrand: any; @@ -686,7 +693,7 @@ declare namespace ts { readonly kind: SyntaxKind.ConstructSignature; } export type BindingName = Identifier | BindingPattern; - export interface VariableDeclaration extends NamedDeclaration { + export interface VariableDeclaration extends NamedDeclaration, JSDocContainer { readonly kind: SyntaxKind.VariableDeclaration; readonly parent: VariableDeclarationList | CatchClause; readonly name: BindingName; @@ -820,15 +827,15 @@ declare namespace ts { readonly kind: SyntaxKind.SemicolonClassElement; readonly parent: ClassLikeDeclaration; } - export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.GetAccessor; - readonly parent: ClassLikeDeclaration | ObjectLiteralExpression; + readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; readonly name: PropertyName; readonly body?: FunctionBody; } - export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.SetAccessor; - readonly parent: ClassLikeDeclaration | ObjectLiteralExpression; + readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; readonly name: PropertyName; readonly body?: FunctionBody; } @@ -1216,11 +1223,11 @@ declare namespace ts { readonly kind: SyntaxKind.PropertyAccessExpression; readonly expression: LeftHandSideExpression; readonly questionDotToken?: QuestionDotToken; - readonly name: Identifier | PrivateIdentifier; + readonly name: MemberName; } export interface PropertyAccessChain extends PropertyAccessExpression { _optionalChainBrand: any; - readonly name: Identifier | PrivateIdentifier; + readonly name: MemberName; } export interface SuperPropertyAccessExpression extends PropertyAccessExpression { readonly expression: SuperExpression; @@ -1373,7 +1380,7 @@ declare namespace ts { readonly containsOnlyTriviaWhiteSpaces: boolean; } export type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; - export interface Statement extends Node { + export interface Statement extends Node, JSDocContainer { _statementBrand: any; } export interface NotEmittedStatement extends Statement { @@ -1401,11 +1408,11 @@ declare namespace ts { readonly kind: SyntaxKind.Block; readonly statements: NodeArray; } - export interface VariableStatement extends Statement, JSDocContainer { + export interface VariableStatement extends Statement { readonly kind: SyntaxKind.VariableStatement; readonly declarationList: VariableDeclarationList; } - export interface ExpressionStatement extends Statement, JSDocContainer { + export interface ExpressionStatement extends Statement { readonly kind: SyntaxKind.ExpressionStatement; readonly expression: Expression; } @@ -1486,7 +1493,7 @@ declare namespace ts { readonly statements: NodeArray; } export type CaseOrDefaultClause = CaseClause | DefaultClause; - export interface LabeledStatement extends Statement, JSDocContainer { + export interface LabeledStatement extends Statement { readonly kind: SyntaxKind.LabeledStatement; readonly label: Identifier; readonly statement: Statement; @@ -1606,7 +1613,7 @@ declare namespace ts { readonly parent: ImportEqualsDeclaration; readonly expression: Expression; } - export interface ImportDeclaration extends Statement, JSDocContainer { + export interface ImportDeclaration extends Statement { readonly kind: SyntaxKind.ImportDeclaration; readonly parent: SourceFile | ModuleBlock; readonly importClause?: ImportClause; @@ -1742,12 +1749,21 @@ declare namespace ts { readonly kind: SyntaxKind.JSDocComment; readonly parent: HasJSDoc; readonly tags?: NodeArray; - readonly comment?: string; + readonly comment?: string | NodeArray; } export interface JSDocTag extends Node { readonly parent: JSDoc | JSDocTypeLiteral; readonly tagName: Identifier; - readonly comment?: string; + readonly comment?: string | NodeArray; + } + export interface JSDocLink extends Node { + readonly kind: SyntaxKind.JSDocLink; + readonly name?: EntityName; + text: string; + } + export interface JSDocText extends Node { + readonly kind: SyntaxKind.JSDocText; + text: string; } export interface JSDocUnknownTag extends JSDocTag { readonly kind: SyntaxKind.JSDocTag; @@ -1789,6 +1805,9 @@ declare namespace ts { export interface JSDocReadonlyTag extends JSDocTag { readonly kind: SyntaxKind.JSDocReadonlyTag; } + export interface JSDocOverrideTag extends JSDocTag { + readonly kind: SyntaxKind.JSDocOverrideTag; + } export interface JSDocEnumTag extends JSDocTag, Declaration { readonly kind: SyntaxKind.JSDocEnumTag; readonly parent: JSDoc; @@ -2080,7 +2099,6 @@ declare namespace ts { * Gets a type checker that can be used to semantically analyze source files in the program. */ getTypeChecker(): TypeChecker; - getTypeCatalog(): readonly Type[]; getNodeCount(): number; getIdentifierCount(): number; getSymbolCount(): number; @@ -2186,7 +2204,7 @@ declare namespace ts { * The function returns the value (local variable) symbol of an identifier in the short-hand property assignment. * This is necessary as an identifier in short-hand property assignment can contains two meaning: property name and property value. */ - getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getShorthandAssignmentValueSymbol(location: Node | undefined): Symbol | undefined; getExportSpecifierLocalTargetSymbol(location: ExportSpecifier | Identifier): Symbol | undefined; /** * If a symbol is a local symbol with an associated exported symbol, returns the exported symbol. @@ -2261,6 +2279,8 @@ declare namespace ts { NoTypeReduction = 536870912, NoUndefinedOptionalParameterType = 1073741824, AllowThisInObjectLiteral = 32768, + AllowQualifiedNameInPlaceOfIdentifier = 65536, + /** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */ AllowQualifedNameInPlaceOfIdentifier = 65536, AllowAnonymousIdentifier = 131072, AllowEmptyUnionOrIntersection = 262144, @@ -2271,8 +2291,7 @@ declare namespace ts { IgnoreErrors = 70221824, InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, - InInitialEntityName = 16777216, - InReverseMappedType = 33554432 + InInitialEntityName = 16777216 } export enum TypeFormatFlags { None = 0, @@ -2405,8 +2424,8 @@ declare namespace ts { export interface Symbol { flags: SymbolFlags; escapedName: __String; - declarations: Declaration[]; - valueDeclaration: Declaration; + declarations?: Declaration[]; + valueDeclaration?: Declaration; members?: SymbolTable; exports?: SymbolTable; globalExports?: SymbolTable; @@ -2540,15 +2559,15 @@ declare namespace ts { ObjectLiteral = 128, EvolvingArray = 256, ObjectLiteralPatternWithComputedProperties = 512, - ContainsSpread = 1024, - ReverseMapped = 2048, - JsxAttributes = 4096, - MarkerType = 8192, - JSLiteral = 16384, - FreshLiteral = 32768, - ArrayLiteral = 65536, - ObjectRestType = 131072, + ReverseMapped = 1024, + JsxAttributes = 2048, + MarkerType = 4096, + JSLiteral = 8192, + FreshLiteral = 16384, + ArrayLiteral = 32768, ClassOrInterface = 3, + ContainsSpread = 4194304, + ObjectRestType = 8388608, } export interface ObjectType extends Type { objectFlags: ObjectFlags; @@ -2656,14 +2675,13 @@ declare namespace ts { export interface TemplateLiteralType extends InstantiableType { texts: readonly string[]; types: readonly Type[]; - freshType: TemplateLiteralType; - regularType: TemplateLiteralType; } export interface StringMappingType extends InstantiableType { symbol: Symbol; type: Type; } export interface SubstitutionType extends InstantiableType { + objectFlags: ObjectFlags; baseType: Type; substitute: Type; } @@ -2688,16 +2706,17 @@ declare namespace ts { export enum InferencePriority { NakedTypeVariable = 1, SpeculativeTuple = 2, - HomomorphicMappedType = 4, - PartialHomomorphicMappedType = 8, - MappedTypeConstraint = 16, - ContravariantConditional = 32, - ReturnType = 64, - LiteralKeyof = 128, - NoConstraints = 256, - AlwaysStrict = 512, - MaxValue = 1024, - PriorityImpliesCombination = 208, + SubstituteSource = 4, + HomomorphicMappedType = 8, + PartialHomomorphicMappedType = 16, + MappedTypeConstraint = 32, + ContravariantConditional = 64, + ReturnType = 128, + LiteralKeyof = 256, + NoConstraints = 512, + AlwaysStrict = 1024, + MaxValue = 2048, + PriorityImpliesCombination = 416, Circularity = -1 } /** @deprecated Use FileExtensionInfo instead. */ @@ -2774,18 +2793,21 @@ declare namespace ts { FixedPollingInterval = 0, PriorityPollingInterval = 1, DynamicPriorityPolling = 2, - UseFsEvents = 3, - UseFsEventsOnParentDirectory = 4 + FixedChunkSizePolling = 3, + UseFsEvents = 4, + UseFsEventsOnParentDirectory = 5 } export enum WatchDirectoryKind { UseFsEvents = 0, FixedPollingInterval = 1, - DynamicPriorityPolling = 2 + DynamicPriorityPolling = 2, + FixedChunkSizePolling = 3 } export enum PollingWatchKind { FixedInterval = 0, PriorityInterval = 1, - DynamicPriority = 2 + DynamicPriority = 2, + FixedChunkSize = 3 } export type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; export interface CompilerOptions { @@ -2847,6 +2869,7 @@ declare namespace ts { outFile?: string; paths?: MapLike; preserveConstEnums?: boolean; + noImplicitOverride?: boolean; preserveSymlinks?: boolean; project?: string; reactNamespace?: string; @@ -2957,6 +2980,7 @@ declare namespace ts { ES2018 = 5, ES2019 = 6, ES2020 = 7, + ES2021 = 8, ESNext = 99, JSON = 100, Latest = 99 @@ -3130,17 +3154,21 @@ declare namespace ts { Iterator = 8388608, NoAsciiEscaping = 16777216, } - export interface EmitHelper { + export interface EmitHelperBase { readonly name: string; readonly scoped: boolean; readonly text: string | ((node: EmitHelperUniqueNameCallback) => string); readonly priority?: number; readonly dependencies?: EmitHelper[]; } - export interface UnscopedEmitHelper extends EmitHelper { + export interface ScopedEmitHelper extends EmitHelperBase { + readonly scoped: true; + } + export interface UnscopedEmitHelper extends EmitHelperBase { readonly scoped: false; readonly text: string; } + export type EmitHelper = ScopedEmitHelper | UnscopedEmitHelper; export type EmitHelperUniqueNameCallback = (name: string) => string; export enum EmitHint { SourceFile = 0, @@ -3168,14 +3196,27 @@ declare namespace ts { createStringLiteralFromNode(sourceNode: PropertyNameLiteral, isSingleQuote?: boolean): StringLiteral; createRegularExpressionLiteral(text: string): RegularExpressionLiteral; createIdentifier(text: string): Identifier; - /** Create a unique temporary variable. */ - createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; - /** Create a unique temporary variable for use in a loop. */ - createLoopVariable(): Identifier; + /** + * Create a unique temporary variable. + * @param recordTempVariable An optional callback used to record the temporary variable name. This + * should usually be a reference to `hoistVariableDeclaration` from a `TransformationContext`, but + * can be `undefined` if you plan to record the temporary variable manually. + * @param reservedInNestedScopes When `true`, reserves the temporary variable name in all nested scopes + * during emit so that the variable can be referenced in a nested function body. This is an alternative to + * setting `EmitFlags.ReuseTempVariableScope` on the nested function itself. + */ + createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, reservedInNestedScopes?: boolean): Identifier; + /** + * Create a unique temporary variable for use in a loop. + * @param reservedInNestedScopes When `true`, reserves the temporary variable name in all nested scopes + * during emit so that the variable can be referenced in a nested function body. This is an alternative to + * setting `EmitFlags.ReuseTempVariableScope` on the nested function itself. + */ + createLoopVariable(reservedInNestedScopes?: boolean): Identifier; /** Create a unique name based on the supplied text. */ createUniqueName(text: string, flags?: GeneratedIdentifierFlags): Identifier; /** Create a unique name generated for a node. */ - getGeneratedNameForNode(node: Node | undefined): Identifier; + getGeneratedNameForNode(node: Node | undefined, flags?: GeneratedIdentifierFlags): Identifier; createPrivateIdentifier(text: string): PrivateIdentifier; createToken(token: SyntaxKind.SuperKeyword): SuperExpression; createToken(token: SyntaxKind.ThisKeyword): ThisExpression; @@ -3286,10 +3327,10 @@ declare namespace ts { updateArrayLiteralExpression(node: ArrayLiteralExpression, elements: readonly Expression[]): ArrayLiteralExpression; createObjectLiteralExpression(properties?: readonly ObjectLiteralElementLike[], multiLine?: boolean): ObjectLiteralExpression; updateObjectLiteralExpression(node: ObjectLiteralExpression, properties: readonly ObjectLiteralElementLike[]): ObjectLiteralExpression; - createPropertyAccessExpression(expression: Expression, name: string | Identifier | PrivateIdentifier): PropertyAccessExpression; - updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: Identifier | PrivateIdentifier): PropertyAccessExpression; - createPropertyAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | Identifier | PrivateIdentifier): PropertyAccessChain; - updatePropertyAccessChain(node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: Identifier | PrivateIdentifier): PropertyAccessChain; + createPropertyAccessExpression(expression: Expression, name: string | MemberName): PropertyAccessExpression; + updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: MemberName): PropertyAccessExpression; + createPropertyAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | MemberName): PropertyAccessChain; + updatePropertyAccessChain(node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: MemberName): PropertyAccessChain; createElementAccessExpression(expression: Expression, index: number | Expression): ElementAccessExpression; updateElementAccessExpression(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; createElementAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, index: number | Expression): ElementAccessChain; @@ -3457,52 +3498,58 @@ declare namespace ts { updateJSDocTypeExpression(node: JSDocTypeExpression, type: TypeNode): JSDocTypeExpression; createJSDocNameReference(name: EntityName): JSDocNameReference; updateJSDocNameReference(node: JSDocNameReference, name: EntityName): JSDocNameReference; + createJSDocLink(name: EntityName | undefined, text: string): JSDocLink; + updateJSDocLink(node: JSDocLink, name: EntityName | undefined, text: string): JSDocLink; createJSDocTypeLiteral(jsDocPropertyTags?: readonly JSDocPropertyLikeTag[], isArrayType?: boolean): JSDocTypeLiteral; updateJSDocTypeLiteral(node: JSDocTypeLiteral, jsDocPropertyTags: readonly JSDocPropertyLikeTag[] | undefined, isArrayType: boolean | undefined): JSDocTypeLiteral; createJSDocSignature(typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag): JSDocSignature; updateJSDocSignature(node: JSDocSignature, typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type: JSDocReturnTag | undefined): JSDocSignature; - createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string): JSDocTemplateTag; - updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | undefined): JSDocTemplateTag; - createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string): JSDocTypedefTag; - updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | undefined): JSDocTypedefTag; - createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string): JSDocParameterTag; - updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | undefined): JSDocParameterTag; - createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string): JSDocPropertyTag; - updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | undefined): JSDocPropertyTag; - createJSDocTypeTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string): JSDocTypeTag; - updateJSDocTypeTag(node: JSDocTypeTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | undefined): JSDocTypeTag; - createJSDocSeeTag(tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string): JSDocSeeTag; - updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string): JSDocSeeTag; - createJSDocReturnTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string): JSDocReturnTag; - updateJSDocReturnTag(node: JSDocReturnTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | undefined): JSDocReturnTag; - createJSDocThisTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string): JSDocThisTag; - updateJSDocThisTag(node: JSDocThisTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | undefined): JSDocThisTag; - createJSDocEnumTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string): JSDocEnumTag; - updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | undefined): JSDocEnumTag; - createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string): JSDocCallbackTag; - updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | undefined): JSDocCallbackTag; - createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string): JSDocAugmentsTag; - updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment: string | undefined): JSDocAugmentsTag; - createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string): JSDocImplementsTag; - updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment: string | undefined): JSDocImplementsTag; - createJSDocAuthorTag(tagName: Identifier | undefined, comment?: string): JSDocAuthorTag; - updateJSDocAuthorTag(node: JSDocAuthorTag, tagName: Identifier | undefined, comment: string | undefined): JSDocAuthorTag; - createJSDocClassTag(tagName: Identifier | undefined, comment?: string): JSDocClassTag; - updateJSDocClassTag(node: JSDocClassTag, tagName: Identifier | undefined, comment: string | undefined): JSDocClassTag; - createJSDocPublicTag(tagName: Identifier | undefined, comment?: string): JSDocPublicTag; - updateJSDocPublicTag(node: JSDocPublicTag, tagName: Identifier | undefined, comment: string | undefined): JSDocPublicTag; - createJSDocPrivateTag(tagName: Identifier | undefined, comment?: string): JSDocPrivateTag; - updateJSDocPrivateTag(node: JSDocPrivateTag, tagName: Identifier | undefined, comment: string | undefined): JSDocPrivateTag; - createJSDocProtectedTag(tagName: Identifier | undefined, comment?: string): JSDocProtectedTag; - updateJSDocProtectedTag(node: JSDocProtectedTag, tagName: Identifier | undefined, comment: string | undefined): JSDocProtectedTag; - createJSDocReadonlyTag(tagName: Identifier | undefined, comment?: string): JSDocReadonlyTag; - updateJSDocReadonlyTag(node: JSDocReadonlyTag, tagName: Identifier | undefined, comment: string | undefined): JSDocReadonlyTag; - createJSDocUnknownTag(tagName: Identifier, comment?: string): JSDocUnknownTag; - updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | undefined): JSDocUnknownTag; - createJSDocDeprecatedTag(tagName: Identifier, comment?: string): JSDocDeprecatedTag; - updateJSDocDeprecatedTag(node: JSDocDeprecatedTag, tagName: Identifier, comment?: string): JSDocDeprecatedTag; - createJSDocComment(comment?: string | undefined, tags?: readonly JSDocTag[] | undefined): JSDoc; - updateJSDocComment(node: JSDoc, comment: string | undefined, tags: readonly JSDocTag[] | undefined): JSDoc; + createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray): JSDocTemplateTag; + updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | NodeArray | undefined): JSDocTemplateTag; + createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocTypedefTag; + updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocTypedefTag; + createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocParameterTag; + updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocParameterTag; + createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocPropertyTag; + updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocPropertyTag; + createJSDocTypeTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocTypeTag; + updateJSDocTypeTag(node: JSDocTypeTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined): JSDocTypeTag; + createJSDocSeeTag(tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag; + updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag; + createJSDocReturnTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray): JSDocReturnTag; + updateJSDocReturnTag(node: JSDocReturnTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined): JSDocReturnTag; + createJSDocThisTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocThisTag; + updateJSDocThisTag(node: JSDocThisTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined): JSDocThisTag; + createJSDocEnumTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocEnumTag; + updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined): JSDocEnumTag; + createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocCallbackTag; + updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocCallbackTag; + createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string | NodeArray): JSDocAugmentsTag; + updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment: string | NodeArray | undefined): JSDocAugmentsTag; + createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string | NodeArray): JSDocImplementsTag; + updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment: string | NodeArray | undefined): JSDocImplementsTag; + createJSDocAuthorTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocAuthorTag; + updateJSDocAuthorTag(node: JSDocAuthorTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocAuthorTag; + createJSDocClassTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocClassTag; + updateJSDocClassTag(node: JSDocClassTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocClassTag; + createJSDocPublicTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocPublicTag; + updateJSDocPublicTag(node: JSDocPublicTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocPublicTag; + createJSDocPrivateTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocPrivateTag; + updateJSDocPrivateTag(node: JSDocPrivateTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocPrivateTag; + createJSDocProtectedTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocProtectedTag; + updateJSDocProtectedTag(node: JSDocProtectedTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocProtectedTag; + createJSDocReadonlyTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocReadonlyTag; + updateJSDocReadonlyTag(node: JSDocReadonlyTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocReadonlyTag; + createJSDocUnknownTag(tagName: Identifier, comment?: string | NodeArray): JSDocUnknownTag; + updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | NodeArray | undefined): JSDocUnknownTag; + createJSDocDeprecatedTag(tagName: Identifier, comment?: string | NodeArray): JSDocDeprecatedTag; + updateJSDocDeprecatedTag(node: JSDocDeprecatedTag, tagName: Identifier, comment?: string | NodeArray): JSDocDeprecatedTag; + createJSDocOverrideTag(tagName: Identifier, comment?: string | NodeArray): JSDocOverrideTag; + updateJSDocOverrideTag(node: JSDocOverrideTag, tagName: Identifier, comment?: string | NodeArray): JSDocOverrideTag; + createJSDocText(text: string): JSDocText; + updateJSDocText(node: JSDocText, text: string): JSDocText; + createJSDocComment(comment?: string | NodeArray | undefined, tags?: readonly JSDocTag[] | undefined): JSDoc; + updateJSDocComment(node: JSDoc, comment: string | NodeArray | undefined, tags: readonly JSDocTag[] | undefined): JSDoc; createJsxElement(openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement; updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement; createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxSelfClosingElement; @@ -3750,12 +3797,12 @@ declare namespace ts { * }); * ``` */ - onEmitNode?(hint: EmitHint, node: Node | undefined, emitCallback: (hint: EmitHint, node: Node | undefined) => void): void; + onEmitNode?(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; /** * A hook used to check if an emit notification is required for a node. * @param node The node to emit. */ - isEmitNotificationEnabled?(node: Node | undefined): boolean; + isEmitNotificationEnabled?(node: Node): boolean; /** * A hook used by the Printer to perform just-in-time substitution of a node. This is * primarily used by node transformations that need to substitute one node for another, @@ -3869,6 +3916,8 @@ declare namespace ts { readonly disableSuggestions?: boolean; readonly quotePreference?: "auto" | "double" | "single"; readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsForImportStatements?: boolean; + readonly includeCompletionsWithSnippetText?: boolean; readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; @@ -3967,9 +4016,10 @@ declare namespace ts { scanJsxIdentifier(): SyntaxKind; scanJsxAttributeValue(): SyntaxKind; reScanJsxAttributeValue(): SyntaxKind; - reScanJsxToken(): JsxTokenSyntaxKind; + reScanJsxToken(allowMultilineJsxText?: boolean): JsxTokenSyntaxKind; reScanLessThanToken(): SyntaxKind; reScanQuestionToken(): SyntaxKind; + reScanInvalidIdentifier(): SyntaxKind; scanJsxToken(): JsxTokenSyntaxKind; scanJsDocToken(): JSDocSyntaxKind; scan(): SyntaxKind; @@ -4101,7 +4151,7 @@ declare namespace ts { function idText(identifierOrPrivateName: Identifier | PrivateIdentifier): string; function symbolName(symbol: Symbol): string; function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | PrivateIdentifier | undefined; - function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined; + function getNameOfDeclaration(declaration: Declaration | Expression | undefined): DeclarationName | undefined; /** * Gets the JSDoc parameter tags for the node if present. * @@ -4147,6 +4197,7 @@ declare namespace ts { function getJSDocProtectedTag(node: Node): JSDocProtectedTag | undefined; /** Gets the JSDoc protected tag for the node if present */ function getJSDocReadonlyTag(node: Node): JSDocReadonlyTag | undefined; + function getJSDocOverrideTagNoCache(node: Node): JSDocOverrideTag | undefined; /** Gets the JSDoc deprecated tag for the node if present */ function getJSDocDeprecatedTag(node: Node): JSDocDeprecatedTag | undefined; /** Gets the JSDoc enum tag for the node if present */ @@ -4184,13 +4235,15 @@ declare namespace ts { function getAllJSDocTags(node: Node, predicate: (tag: JSDocTag) => tag is T): readonly T[]; /** Gets all JSDoc tags of a specified kind */ function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): readonly JSDocTag[]; + /** Gets the text of a jsdoc comment, flattening links to their text. */ + function getTextOfJSDocComment(comment?: string | NodeArray): string | undefined; /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. */ function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): readonly TypeParameterDeclaration[]; function getEffectiveConstraintOfTypeParameter(node: TypeParameterDeclaration): TypeNode | undefined; - function isIdentifierOrPrivateIdentifier(node: Node): node is Identifier | PrivateIdentifier; + function isMemberName(node: Node): node is MemberName; function isPropertyAccessChain(node: Node): node is PropertyAccessChain; function isElementAccessChain(node: Node): node is ElementAccessChain; function isCallChain(node: Node): node is CallChain; @@ -4205,6 +4258,12 @@ declare namespace ts { function isUnparsedTextLike(node: Node): node is UnparsedTextLike; function isUnparsedNode(node: Node): node is UnparsedNode; function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag; + /** + * True if kind is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + function isTokenKind(kind: SyntaxKind): boolean; /** * True if node is of some token syntax kind. * For example, this is true for an IfKeyword but not for an IfStatement. @@ -4221,7 +4280,7 @@ declare namespace ts { function isEntityName(node: Node): node is EntityName; function isPropertyName(node: Node): node is PropertyName; function isBindingName(node: Node): node is BindingName; - function isFunctionLike(node: Node): node is SignatureDeclaration; + function isFunctionLike(node: Node | undefined): node is SignatureDeclaration; function isClassElement(node: Node): node is ClassElement; function isClassLike(node: Node): node is ClassLikeDeclaration; function isAccessor(node: Node): node is AccessorDeclaration; @@ -4347,10 +4406,14 @@ declare namespace ts { function isTemplateHead(node: Node): node is TemplateHead; function isTemplateMiddle(node: Node): node is TemplateMiddle; function isTemplateTail(node: Node): node is TemplateTail; + function isDotDotDotToken(node: Node): node is DotDotDotToken; + function isPlusToken(node: Node): node is PlusToken; + function isMinusToken(node: Node): node is MinusToken; + function isAsteriskToken(node: Node): node is AsteriskToken; function isIdentifier(node: Node): node is Identifier; + function isPrivateIdentifier(node: Node): node is PrivateIdentifier; function isQualifiedName(node: Node): node is QualifiedName; function isComputedPropertyName(node: Node): node is ComputedPropertyName; - function isPrivateIdentifier(node: Node): node is PrivateIdentifier; function isTypeParameterDeclaration(node: Node): node is TypeParameterDeclaration; function isParameter(node: Node): node is ParameterDeclaration; function isDecorator(node: Node): node is Decorator; @@ -4493,6 +4556,7 @@ declare namespace ts { function isUnparsedSource(node: Node): node is UnparsedSource; function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression; function isJSDocNameReference(node: Node): node is JSDocNameReference; + function isJSDocLink(node: Node): node is JSDocLink; function isJSDocAllType(node: Node): node is JSDocAllType; function isJSDocUnknownType(node: Node): node is JSDocUnknownType; function isJSDocNullableType(node: Node): node is JSDocNullableType; @@ -4512,6 +4576,7 @@ declare namespace ts { function isJSDocPrivateTag(node: Node): node is JSDocPrivateTag; function isJSDocProtectedTag(node: Node): node is JSDocProtectedTag; function isJSDocReadonlyTag(node: Node): node is JSDocReadonlyTag; + function isJSDocOverrideTag(node: Node): node is JSDocOverrideTag; function isJSDocDeprecatedTag(node: Node): node is JSDocDeprecatedTag; function isJSDocSeeTag(node: Node): node is JSDocSeeTag; function isJSDocEnumTag(node: Node): node is JSDocEnumTag; @@ -4576,7 +4641,7 @@ declare namespace ts { /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ - export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): ParsedCommandLine | undefined; + export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions | undefined, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): ParsedCommandLine | undefined; /** * Read tsconfig.json file * @param fileName The path to the config file @@ -4644,13 +4709,13 @@ declare namespace ts { export {}; } declare namespace ts { - function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; + export function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, cache?: TypeReferenceDirectiveResolutionCache): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -4659,30 +4724,46 @@ declare namespace ts { * More type directives might appear in the program later as a result of loading actual source files; * this list is only the set of defaults that are implicitly included. */ - function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + export function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + export interface TypeReferenceDirectiveResolutionCache extends PerDirectoryResolutionCache, PackageJsonInfoCache { + } /** - * Cached module resolutions per containing directory. + * Cached resolutions per containing directory. * This assumes that any module id will have the same resolution for sibling files located in the same folder. */ - interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { - getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + export interface PerDirectoryResolutionCache { + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + clear(): void; + /** + * Updates with the current compilerOptions the cache will operate with. + * This updates the redirects map as well if needed so module resolutions are cached if they can across the projects + */ + update(options: CompilerOptions): void; + } + export interface ModuleResolutionCache extends PerDirectoryResolutionCache, NonRelativeModuleNameResolutionCache, PackageJsonInfoCache { + getPackageJsonInfoCache(): PackageJsonInfoCache; } /** * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. */ - interface NonRelativeModuleNameResolutionCache { + export interface NonRelativeModuleNameResolutionCache extends PackageJsonInfoCache { getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; } - interface PerModuleNameCache { + export interface PackageJsonInfoCache { + clear(): void; + } + export interface PerModuleNameCache { get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; } - function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions): ModuleResolutionCache; - function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions): ModuleResolutionCache; + export function createTypeReferenceDirectiveResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions, packageJsonInfoCache?: PackageJsonInfoCache): TypeReferenceDirectiveResolutionCache; + export function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; + export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export {}; } declare namespace ts { /** @@ -4749,6 +4830,10 @@ declare namespace ts { * environment and merging hoisted declarations upon completion. */ function visitFunctionBody(node: ConciseBody, visitor: Visitor, context: TransformationContext): ConciseBody; + /** + * Visits an iteration body, adding any block-scoped variables required by the transformation. + */ + function visitIterationBody(body: Statement, visitor: Visitor, context: TransformationContext): Statement; /** * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place. * @@ -5037,6 +5122,8 @@ declare namespace ts { interface WatchCompilerHost extends ProgramHost, WatchHost { /** Instead of using output d.ts file from project reference, use its source file */ useSourceOfProjectReferenceRedirect?(): boolean; + /** If provided, use this method to get parsed command lines for referenced projects */ + getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; } @@ -5132,9 +5219,9 @@ declare namespace ts { interface SolutionBuilderWithWatchHost extends SolutionBuilderHostBase, WatchHost { } interface SolutionBuilder { - build(project?: string, cancellationToken?: CancellationToken): ExitStatus; + build(project?: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; clean(project?: string): ExitStatus; - buildReferences(project: string, cancellationToken?: CancellationToken): ExitStatus; + buildReferences(project: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; cleanReferences(project?: string): ExitStatus; getNextInvalidatedProject(cancellationToken?: CancellationToken): InvalidatedProject | undefined; } @@ -5292,7 +5379,7 @@ declare namespace ts { getName(): string; getDeclarations(): Declaration[] | undefined; getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; - getJsDocTags(): JSDocTagInfo[]; + getJsDocTags(checker?: TypeChecker): JSDocTagInfo[]; } interface Type { getFlags(): TypeFlags; @@ -5423,6 +5510,7 @@ declare namespace ts { isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; writeFile?(fileName: string, content: string): void; + getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; } type WithMetadata = T & { metadata?: unknown; @@ -5512,12 +5600,13 @@ declare namespace ts { * * @param fileName The path to the file * @param position A zero based index of the character where you want the entries - * @param entryName The name from an existing completion which came from `getCompletionsAtPosition` + * @param entryName The `name` from an existing completion which came from `getCompletionsAtPosition` * @param formatOptions How should code samples in the completions be formatted, can be undefined for backwards compatibility - * @param source Source code for the current file, can be undefined for backwards compatibility + * @param source `source` property from the completion entry * @param preferences User settings, can be undefined for backwards compatibility + * @param data `data` property from the completion entry */ - getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; + getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined, data: CompletionEntryData | undefined): CompletionEntryDetails | undefined; getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; /** * Gets semantic information about the identifier at a particular position in a @@ -5556,7 +5645,7 @@ declare namespace ts { getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; - getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion | undefined; + getDocCommentTemplateAtPosition(fileName: string, position: number, options?: DocCommentTemplateOptions): TextInsertion | undefined; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; /** * This will return a defined result if the position is after the `>` of the opening tag, or somewhere in the text, of a JSXElement with no closing tag. @@ -5578,7 +5667,7 @@ declare namespace ts { applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise; getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined, triggerReason?: RefactorTriggerReason, kind?: string): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; - organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; + organizeImports(args: OrganizeImportsArgs, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; getProgram(): Program | undefined; @@ -5595,8 +5684,10 @@ declare namespace ts { type: "file"; fileName: string; } - type OrganizeImportsScope = CombinedCodeFixScope; - type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#"; + interface OrganizeImportsArgs extends CombinedCodeFixScope { + skipDestructiveCodeActions?: boolean; + } + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; interface GetCompletionsAtPositionOptions extends UserPreferences { /** * If the editor is asking for completions because a certain character was typed @@ -5948,6 +6039,7 @@ declare namespace ts { name: string; containerKind: ScriptElementKind; containerName: string; + unverified?: boolean; } interface DefinitionInfoAndBoundSpan { definitions?: readonly DefinitionInfo[]; @@ -5982,15 +6074,21 @@ declare namespace ts { typeParameterName = 18, enumMemberName = 19, functionName = 20, - regularExpressionLiteral = 21 + regularExpressionLiteral = 21, + link = 22, + linkName = 23, + linkText = 24 } interface SymbolDisplayPart { text: string; kind: string; } + interface JSDocLinkDisplayPart extends SymbolDisplayPart { + target: DocumentSpan; + } interface JSDocTagInfo { name: string; - text?: string; + text?: SymbolDisplayPart[]; } interface QuickInfo { kind: ScriptElementKind; @@ -6021,11 +6119,15 @@ declare namespace ts { interface RenameInfoOptions { readonly allowRenameOfImportPath?: boolean; } + interface DocCommentTemplateOptions { + readonly generateReturnInDocTemplate?: boolean; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; displayParts: SymbolDisplayPart[]; isOptional: boolean; + isRest?: boolean; } interface SelectionRange { textSpan: TextSpan; @@ -6071,14 +6173,36 @@ declare namespace ts { * true when the current location also allows for a new identifier */ isNewIdentifierLocation: boolean; + /** + * Indicates to client to continue requesting completions on subsequent keystrokes. + */ + isIncomplete?: true; entries: CompletionEntry[]; } + interface CompletionEntryData { + /** The file name declaring the export's module symbol, if it was an external module */ + fileName?: string; + /** The module name (with quotes stripped) of the export's module symbol, if it was an ambient module */ + ambientModuleName?: string; + /** True if the export was found in the package.json AutoImportProvider */ + isPackageJsonImport?: true; + /** + * The name of the property or export in the module's symbol table. Differs from the completion name + * in the case of InternalSymbolName.ExportEquals and InternalSymbolName.Default. + */ + exportName: string; + /** + * Set for auto imports with eagerly resolved module specifiers. + */ + moduleSpecifier?: string; + } interface CompletionEntry { name: string; kind: ScriptElementKind; kindModifiers?: string; sortText: string; insertText?: string; + isSnippet?: true; /** * An optional span that indicates the text to be replaced by this completion item. * If present, this span should be used instead of the default one. @@ -6087,9 +6211,20 @@ declare namespace ts { replacementSpan?: TextSpan; hasAction?: true; source?: string; + sourceDisplay?: SymbolDisplayPart[]; isRecommended?: true; isFromUncheckedFile?: true; isPackageJsonImport?: true; + isImportStatementCompletion?: true; + /** + * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, + * that allows TS Server to look up the symbol represented by the completion item, disambiguating + * items with the same name. Currently only defined for auto-import completions, but the type is + * `unknown` in the protocol, so it can be changed as needed to support other kinds of completions. + * The presence of this property should generally not be used to assume that this completion entry + * is an auto-import. + */ + data?: CompletionEntryData; } interface CompletionEntryDetails { name: string; @@ -6099,7 +6234,9 @@ declare namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; codeActions?: CodeAction[]; + /** @deprecated Use `sourceDisplay` instead. */ source?: SymbolDisplayPart[]; + sourceDisplay?: SymbolDisplayPart[]; } interface OutliningSpan { /** The span of the document to actually collapse. */ @@ -6253,7 +6390,13 @@ declare namespace ts { */ jsxAttribute = "JSX attribute", /** String literal */ - string = "string" + string = "string", + /** Jsdoc @link: in `{@link C link text}`, the before and after text "{@link " and "}" */ + link = "link", + /** Jsdoc @link: in `{@link C link text}`, the entity name "C" */ + linkName = "link name", + /** Jsdoc @link: in `{@link C link text}`, the link text "link text" */ + linkText = "link text" } enum ScriptElementKindModifier { none = "", @@ -6394,8 +6537,23 @@ declare namespace ts { * @param fileName The name of the file to be released * @param compilationSettings The compilation settings used to acquire the file */ + /**@deprecated pass scriptKind for correctness */ releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + /** + * Informs the DocumentRegistry that a file is not needed any longer. + * + * Note: It is not allowed to call release on a SourceFile that was not acquired from + * this registry originally. + * + * @param fileName The name of the file to be released + * @param compilationSettings The compilation settings used to acquire the file + * @param scriptKind The script kind of the file to be released + */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind: ScriptKind): void; + /** + * @deprecated pass scriptKind for correctness */ releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind: ScriptKind): void; reportStats(): string; } type DocumentRegistryBucketKey = string & { @@ -7031,6 +7189,7 @@ declare namespace ts.server.protocol { type OrganizeImportsScope = GetCombinedCodeFixScope; interface OrganizeImportsRequestArgs { scope: OrganizeImportsScope; + skipDestructiveCodeActions?: boolean; } interface OrganizeImportsResponse extends Response { body: readonly FileCodeEdits[]; @@ -7133,6 +7292,41 @@ declare namespace ts.server.protocol { */ body?: string[]; } + /** + * A request to get encoded semantic classifications for a span in the file + */ + interface EncodedSemanticClassificationsRequest extends FileRequest { + arguments: EncodedSemanticClassificationsRequestArgs; + } + /** + * Arguments for EncodedSemanticClassificationsRequest request. + */ + interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { + /** + * Start position of the span. + */ + start: number; + /** + * Length of the span. + */ + length: number; + /** + * Optional parameter for the semantic highlighting response, if absent it + * defaults to "original". + */ + format?: "original" | "2020"; + } + /** The response for a EncodedSemanticClassificationsRequest */ + interface EncodedSemanticClassificationsResponse extends Response { + body?: EncodedSemanticClassificationsResponseBody; + } + /** + * Implementation response message. Gives series of text spans depending on the format ar. + */ + interface EncodedSemanticClassificationsResponseBody { + endOfLineState: EndOfLineState; + spans: number[]; + } /** * Arguments in document highlight request; include: filesToSearch, file, * line, offset. @@ -7202,21 +7396,36 @@ declare namespace ts.server.protocol { */ file: string; } + interface JSDocTagInfo { + /** Name of the JSDoc tag */ + name: string; + /** + * Comment text after the JSDoc tag -- the text after the tag name until the next tag or end of comment + * Display parts when UserPreferences.displayPartsForJSDoc is true, flattened to string otherwise. + */ + text?: string | SymbolDisplayPart[]; + } interface TextSpanWithContext extends TextSpan { contextStart?: Location; contextEnd?: Location; } interface FileSpanWithContext extends FileSpan, TextSpanWithContext { } + interface DefinitionInfo extends FileSpanWithContext { + /** + * When true, the file may or may not exist. + */ + unverified?: boolean; + } interface DefinitionInfoAndBoundSpan { - definitions: readonly FileSpanWithContext[]; + definitions: readonly DefinitionInfo[]; textSpan: TextSpan; } /** * Definition response message. Gives text range for definition. */ interface DefinitionResponse extends Response { - body?: FileSpanWithContext[]; + body?: DefinitionInfo[]; } interface DefinitionInfoAndBoundSpanResponse extends Response { body?: DefinitionInfoAndBoundSpan; @@ -7600,18 +7809,21 @@ declare namespace ts.server.protocol { FixedPollingInterval = "FixedPollingInterval", PriorityPollingInterval = "PriorityPollingInterval", DynamicPriorityPolling = "DynamicPriorityPolling", + FixedChunkSizePolling = "FixedChunkSizePolling", UseFsEvents = "UseFsEvents", UseFsEventsOnParentDirectory = "UseFsEventsOnParentDirectory" } enum WatchDirectoryKind { UseFsEvents = "UseFsEvents", FixedPollingInterval = "FixedPollingInterval", - DynamicPriorityPolling = "DynamicPriorityPolling" + DynamicPriorityPolling = "DynamicPriorityPolling", + FixedChunkSizePolling = "FixedChunkSizePolling" } enum PollingWatchKind { FixedInterval = "FixedInterval", PriorityInterval = "PriorityInterval", - DynamicPriority = "DynamicPriority" + DynamicPriority = "DynamicPriority", + FixedChunkSize = "FixedChunkSize" } interface WatchOptions { watchFile?: WatchFileKind | ts.WatchFileKind; @@ -7913,6 +8125,7 @@ declare namespace ts.server.protocol { */ interface QuickInfoRequest extends FileLocationRequest { command: CommandTypes.Quickinfo; + arguments: FileLocationRequestArgs; } /** * Body of QuickInfoResponse. @@ -7940,8 +8153,9 @@ declare namespace ts.server.protocol { displayString: string; /** * Documentation associated with symbol. + * Display parts when UserPreferences.displayPartsForJSDoc is true, flattened to string otherwise. */ - documentation: string; + documentation: string | SymbolDisplayPart[]; /** * JSDoc tags associated with symbol. */ @@ -8062,7 +8276,7 @@ declare namespace ts.server.protocol { command: CommandTypes.Formatonkey; arguments: FormatOnKeyRequestArgs; } - type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#"; + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; /** * Arguments for completions messages. */ @@ -8107,6 +8321,7 @@ declare namespace ts.server.protocol { interface CompletionEntryIdentifier { name: string; source?: string; + data?: unknown; } /** * Completion entry details request; value of command field is @@ -8131,6 +8346,11 @@ declare namespace ts.server.protocol { */ kind: string; } + /** A part of a symbol description that links from a jsdoc @link tag to a declaration */ + interface JSDocLinkDisplayPart extends SymbolDisplayPart { + /** The location of the declaration that the @link tag links to. */ + target: FileSpan; + } /** * An item found in a completion response. */ @@ -8158,6 +8378,10 @@ declare namespace ts.server.protocol { * coupled with `replacementSpan` to replace a dotted access with a bracket access. */ insertText?: string; + /** + * `insertText` should be interpreted as a snippet if true. + */ + isSnippet?: true; /** * An optional span that indicates the text to be replaced by this completion item. * If present, this span should be used instead of the default one. @@ -8173,6 +8397,10 @@ declare namespace ts.server.protocol { * Identifier (not necessarily human-readable) identifying where this completion came from. */ source?: string; + /** + * Human-readable description of the `source`. + */ + sourceDisplay?: SymbolDisplayPart[]; /** * If true, this completion should be highlighted as recommended. There will only be one of these. * This will be set when we know the user should write an expression with a certain type and that type is an enum or constructable class. @@ -8186,9 +8414,20 @@ declare namespace ts.server.protocol { isFromUncheckedFile?: true; /** * If true, this completion was for an auto-import of a module not yet in the program, but listed - * in the project package.json. + * in the project package.json. Used for telemetry reporting. */ isPackageJsonImport?: true; + /** + * If true, this completion was an auto-import-style completion of an import statement (i.e., the + * module specifier was inserted along with the imported identifier). Used for telemetry reporting. + */ + isImportStatementCompletion?: true; + /** + * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, + * that allows TS Server to look up the symbol represented by the completion item, disambiguating + * items with the same name. + */ + data?: unknown; } /** * Additional completion entry details, available on demand @@ -8223,9 +8462,13 @@ declare namespace ts.server.protocol { */ codeActions?: CodeAction[]; /** - * Human-readable description of the `source` from the CompletionEntry. + * @deprecated Use `sourceDisplay` instead. */ source?: SymbolDisplayPart[]; + /** + * Human-readable description of the `source` from the CompletionEntry. + */ + sourceDisplay?: SymbolDisplayPart[]; } /** @deprecated Prefer CompletionInfoResponse, which supports several top-level fields in addition to the array of entries. */ interface CompletionsResponse extends Response { @@ -8244,6 +8487,7 @@ declare namespace ts.server.protocol { * must be used to commit that completion entry. */ readonly optionalReplacementSpan?: TextSpan; + readonly isIncomplete?: boolean; readonly entries: readonly CompletionEntry[]; } interface CompletionDetailsResponse extends Response { @@ -9026,6 +9270,15 @@ declare namespace ts.server.protocol { * This affects lone identifier completions but not completions on the right hand side of `obj.`. */ readonly includeCompletionsForModuleExports?: boolean; + /** + * Enables auto-import-style completions on partially-typed import statements. E.g., allows + * `import write|` to be completed to `import { writeFile } from "fs"`. + */ + readonly includeCompletionsForImportStatements?: boolean; + /** + * Allows completions to be formatted with snippet text, indicated by `CompletionItem["isSnippet"]`. + */ + readonly includeCompletionsWithSnippetText?: boolean; /** * If enabled, the completion list will include completions with invalid identifier names. * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. @@ -9046,6 +9299,8 @@ declare namespace ts.server.protocol { readonly provideRefactorNotApplicableReason?: boolean; readonly allowRenameOfImportPath?: boolean; readonly includePackageJsonAutoImports?: "auto" | "on" | "off"; + readonly displayPartsForJSDoc?: boolean; + readonly generateReturnInDocTemplate?: boolean; } interface CompilerOptions { allowJs?: boolean; @@ -9153,8 +9408,36 @@ declare namespace ts.server.protocol { ES2018 = "ES2018", ES2019 = "ES2019", ES2020 = "ES2020", + ES2021 = "ES2021", ESNext = "ESNext" } + enum ClassificationType { + comment = 1, + identifier = 2, + keyword = 3, + numericLiteral = 4, + operator = 5, + stringLiteral = 6, + regularExpressionLiteral = 7, + whiteSpace = 8, + text = 9, + punctuation = 10, + className = 11, + enumName = 12, + interfaceName = 13, + moduleName = 14, + typeParameterName = 15, + typeAliasName = 16, + parameterName = 17, + docCommentTagName = 18, + jsxOpenTagName = 19, + jsxCloseTagName = 20, + jsxSelfClosingTagName = 21, + jsxAttribute = 22, + jsxText = 23, + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25 + } } declare namespace ts.server { interface ScriptInfoVersion { @@ -9267,7 +9550,6 @@ declare namespace ts.server { private missingFilesMap; private generatedFilesMap; private plugins; - private lastFileExceededProgramSize; protected languageService: LanguageService; languageServiceEnabled: boolean; readonly trace?: (s: string) => void; @@ -9424,10 +9706,8 @@ declare namespace ts.server { markAsDirty(): void; getScriptFileNames(): string[]; getLanguageService(): never; - markAutoImportProviderAsDirty(): never; getModuleResolutionHostForAutoImportProvider(): never; getProjectReferences(): readonly ProjectReference[] | undefined; - useSourceOfProjectReferenceRedirect(): boolean; getTypeAcquisition(): TypeAcquisition; } /** @@ -9436,7 +9716,6 @@ declare namespace ts.server { * Otherwise it will create an InferredProject. */ class ConfiguredProject extends Project { - private directoriesWatchedForWildcards; readonly canonicalConfigFilePath: NormalizedPath; /** Ref count to the project when opened from external project */ private externalProjectRefCount; @@ -9683,14 +9962,6 @@ declare namespace ts.server { * Project size for configured or external projects */ private readonly projectToSizeMap; - /** - * This is a map of config file paths existence that doesnt need query to disk - * - The entry can be present because there is inferred project that needs to watch addition of config file to directory - * In this case the exists could be true/false based on config file is present or not - * - Or it is present if we have configured project open with config file at that location - * In this case the exists property is always true - */ - private readonly configFileExistenceInfoCache; private readonly hostConfiguration; private safelist; private readonly legacySafelist; @@ -9746,12 +10017,6 @@ declare namespace ts.server { private delayUpdateSourceInfoProjects; private delayUpdateProjectsOfScriptInfoPath; private handleDeletedFile; - /** - * This is the callback function for the config file add/remove/change at any location - * that matters to open script info but doesnt have configured project open - * for the config file - */ - private onConfigFileChangeForOpenScriptInfo; private removeProject; private assignOrphanScriptInfosToInferredProject; /** @@ -9761,22 +10026,10 @@ declare namespace ts.server { private closeOpenFile; private deleteScriptInfo; private configFileExists; - private setConfigFileExistenceByNewConfiguredProject; /** * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project */ private configFileExistenceImpactsRootOfInferredProject; - private setConfigFileExistenceInfoByClosedConfiguredProject; - private logConfigFileWatchUpdate; - /** - * Create the watcher for the configFileExistenceInfo - */ - private createConfigFileWatcherOfConfigFileExistence; - /** - * Close the config file watcher in the cached ConfigFileExistenceInfo - * if there arent any open files that are root of inferred project - */ - private closeConfigFileWatcherOfConfigFileExistenceInfo; /** * This is called on file close, so that we stop watching the config file for this script info */ @@ -9842,12 +10095,11 @@ declare namespace ts.server { * This does not reload contents of open files from disk. But we could do that if needed */ reloadProjects(): void; - private delayReloadConfiguredProjectForFiles; /** * This function goes through all the openFiles and tries to file the config file for them. * If the config file is found and it refers to existing project, it reloads it either immediately * or schedules it for reload depending on delayReload option - * If the there is no existing project it just opens the configured project for the config file + * If 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; @@ -9993,6 +10245,9 @@ declare namespace ts.server { private mapDefinitionInfoLocations; private getDefinitionAndBoundSpan; private getEmitOutput; + private mapJSDocTagInfo; + private mapDisplayParts; + private mapSignatureHelpItems; private mapDefinitionInfo; private static mapToOriginalLocation; private toFileSpan; @@ -10131,7 +10386,7 @@ declare namespace ts { /** @deprecated Use `factory.createRegularExpressionLiteral` or the factory supplied by your transformation context instead. */ const createRegularExpressionLiteral: (text: string) => RegularExpressionLiteral; /** @deprecated Use `factory.createLoopVariable` or the factory supplied by your transformation context instead. */ - const createLoopVariable: () => Identifier; + const createLoopVariable: (reservedInNestedScopes?: boolean | undefined) => Identifier; /** @deprecated Use `factory.createUniqueName` or the factory supplied by your transformation context instead. */ const createUniqueName: (text: string, flags?: GeneratedIdentifierFlags | undefined) => Identifier; /** @deprecated Use `factory.createPrivateIdentifier` or the factory supplied by your transformation context instead. */ @@ -10303,13 +10558,13 @@ declare namespace ts { /** @deprecated Use `factory.updateObjectLiteralExpression` or the factory supplied by your transformation context instead. */ const updateObjectLiteral: (node: ObjectLiteralExpression, properties: readonly ObjectLiteralElementLike[]) => ObjectLiteralExpression; /** @deprecated Use `factory.createPropertyAccessExpression` or the factory supplied by your transformation context instead. */ - const createPropertyAccess: (expression: Expression, name: string | Identifier | PrivateIdentifier) => PropertyAccessExpression; + const createPropertyAccess: (expression: Expression, name: string | MemberName) => PropertyAccessExpression; /** @deprecated Use `factory.updatePropertyAccessExpression` or the factory supplied by your transformation context instead. */ - const updatePropertyAccess: (node: PropertyAccessExpression, expression: Expression, name: Identifier | PrivateIdentifier) => PropertyAccessExpression; + const updatePropertyAccess: (node: PropertyAccessExpression, expression: Expression, name: MemberName) => PropertyAccessExpression; /** @deprecated Use `factory.createPropertyAccessChain` or the factory supplied by your transformation context instead. */ - const createPropertyAccessChain: (expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | Identifier | PrivateIdentifier) => PropertyAccessChain; + const createPropertyAccessChain: (expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | MemberName) => PropertyAccessChain; /** @deprecated Use `factory.updatePropertyAccessChain` or the factory supplied by your transformation context instead. */ - const updatePropertyAccessChain: (node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: Identifier | PrivateIdentifier) => PropertyAccessChain; + const updatePropertyAccessChain: (node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: MemberName) => PropertyAccessChain; /** @deprecated Use `factory.createElementAccessExpression` or the factory supplied by your transformation context instead. */ const createElementAccess: (expression: Expression, index: number | Expression) => ElementAccessExpression; /** @deprecated Use `factory.updateElementAccessExpression` or the factory supplied by your transformation context instead. */ @@ -10579,51 +10834,51 @@ declare namespace ts { /** @deprecated Use `factory.createJSDocTypeExpression` or the factory supplied by your transformation context instead. */ const createJSDocTypeExpression: (type: TypeNode) => JSDocTypeExpression; /** @deprecated Use `factory.createJSDocTypeTag` or the factory supplied by your transformation context instead. */ - const createJSDocTypeTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | undefined) => JSDocTypeTag; + const createJSDocTypeTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray | undefined) => JSDocTypeTag; /** @deprecated Use `factory.createJSDocReturnTag` or the factory supplied by your transformation context instead. */ - const createJSDocReturnTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | undefined, comment?: string | undefined) => JSDocReturnTag; + const createJSDocReturnTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | undefined, comment?: string | NodeArray | undefined) => JSDocReturnTag; /** @deprecated Use `factory.createJSDocThisTag` or the factory supplied by your transformation context instead. */ - const createJSDocThisTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | undefined) => JSDocThisTag; + const createJSDocThisTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray | undefined) => JSDocThisTag; /** @deprecated Use `factory.createJSDocComment` or the factory supplied by your transformation context instead. */ - const createJSDocComment: (comment?: string | undefined, tags?: readonly JSDocTag[] | undefined) => JSDoc; + const createJSDocComment: (comment?: string | NodeArray | undefined, tags?: readonly JSDocTag[] | undefined) => JSDoc; /** @deprecated Use `factory.createJSDocParameterTag` or the factory supplied by your transformation context instead. */ - const createJSDocParameterTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | undefined) => JSDocParameterTag; + const createJSDocParameterTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | NodeArray | undefined) => JSDocParameterTag; /** @deprecated Use `factory.createJSDocClassTag` or the factory supplied by your transformation context instead. */ - const createJSDocClassTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocClassTag; + const createJSDocClassTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocClassTag; /** @deprecated Use `factory.createJSDocAugmentsTag` or the factory supplied by your transformation context instead. */ const createJSDocAugmentsTag: (tagName: Identifier | undefined, className: ExpressionWithTypeArguments & { readonly expression: Identifier | PropertyAccessEntityNameExpression; - }, comment?: string | undefined) => JSDocAugmentsTag; + }, comment?: string | NodeArray | undefined) => JSDocAugmentsTag; /** @deprecated Use `factory.createJSDocEnumTag` or the factory supplied by your transformation context instead. */ - const createJSDocEnumTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | undefined) => JSDocEnumTag; + const createJSDocEnumTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray | undefined) => JSDocEnumTag; /** @deprecated Use `factory.createJSDocTemplateTag` or the factory supplied by your transformation context instead. */ - const createJSDocTemplateTag: (tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | undefined) => JSDocTemplateTag; + const createJSDocTemplateTag: (tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray | undefined) => JSDocTemplateTag; /** @deprecated Use `factory.createJSDocTypedefTag` or the factory supplied by your transformation context instead. */ - const createJSDocTypedefTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeLiteral | JSDocTypeExpression | undefined, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | undefined) => JSDocTypedefTag; + const createJSDocTypedefTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeLiteral | JSDocTypeExpression | undefined, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | NodeArray | undefined) => JSDocTypedefTag; /** @deprecated Use `factory.createJSDocCallbackTag` or the factory supplied by your transformation context instead. */ - const createJSDocCallbackTag: (tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | undefined) => JSDocCallbackTag; + const createJSDocCallbackTag: (tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | NodeArray | undefined) => JSDocCallbackTag; /** @deprecated Use `factory.createJSDocSignature` or the factory supplied by your transformation context instead. */ const createJSDocSignature: (typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag | undefined) => JSDocSignature; /** @deprecated Use `factory.createJSDocPropertyTag` or the factory supplied by your transformation context instead. */ - const createJSDocPropertyTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | undefined) => JSDocPropertyTag; + const createJSDocPropertyTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | NodeArray | undefined) => JSDocPropertyTag; /** @deprecated Use `factory.createJSDocTypeLiteral` or the factory supplied by your transformation context instead. */ const createJSDocTypeLiteral: (jsDocPropertyTags?: readonly JSDocPropertyLikeTag[] | undefined, isArrayType?: boolean | undefined) => JSDocTypeLiteral; /** @deprecated Use `factory.createJSDocImplementsTag` or the factory supplied by your transformation context instead. */ const createJSDocImplementsTag: (tagName: Identifier | undefined, className: ExpressionWithTypeArguments & { readonly expression: Identifier | PropertyAccessEntityNameExpression; - }, comment?: string | undefined) => JSDocImplementsTag; + }, comment?: string | NodeArray | undefined) => JSDocImplementsTag; /** @deprecated Use `factory.createJSDocAuthorTag` or the factory supplied by your transformation context instead. */ - const createJSDocAuthorTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocAuthorTag; + const createJSDocAuthorTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocAuthorTag; /** @deprecated Use `factory.createJSDocPublicTag` or the factory supplied by your transformation context instead. */ - const createJSDocPublicTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocPublicTag; + const createJSDocPublicTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocPublicTag; /** @deprecated Use `factory.createJSDocPrivateTag` or the factory supplied by your transformation context instead. */ - const createJSDocPrivateTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocPrivateTag; + const createJSDocPrivateTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocPrivateTag; /** @deprecated Use `factory.createJSDocProtectedTag` or the factory supplied by your transformation context instead. */ - const createJSDocProtectedTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocProtectedTag; + const createJSDocProtectedTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocProtectedTag; /** @deprecated Use `factory.createJSDocReadonlyTag` or the factory supplied by your transformation context instead. */ - const createJSDocReadonlyTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocReadonlyTag; + const createJSDocReadonlyTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocReadonlyTag; /** @deprecated Use `factory.createJSDocUnknownTag` or the factory supplied by your transformation context instead. */ - const createJSDocTag: (tagName: Identifier, comment?: string | undefined) => JSDocUnknownTag; + const createJSDocTag: (tagName: Identifier, comment?: string | NodeArray | undefined) => JSDocUnknownTag; /** @deprecated Use `factory.createJsxElement` or the factory supplied by your transformation context instead. */ const createJsxElement: (openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement) => JsxElement; /** @deprecated Use `factory.updateJsxElement` or the factory supplied by your transformation context instead. */ @@ -10879,6 +11134,10 @@ declare namespace ts { */ interface Map extends ESMap { } + /** + * @deprecated Use `isMemberName` instead. + */ + const isIdentifierOrPrivateIdentifier: (node: Node) => node is MemberName; } export = ts; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 871fc59961b13..ee78ce982fd11 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -286,11 +286,11 @@ var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "4.2"; + ts.versionMajorMinor = "4.3"; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = ts.versionMajorMinor + ".0-dev"; + ts.version = "4.3.2"; /* @internal */ var Comparison; (function (Comparison) { @@ -2594,6 +2594,8 @@ var ts; } } Debug.assertMissingNode = assertMissingNode; + function type(_value) { } + Debug.type = type; function getFunctionName(func) { if (typeof func !== "function") { return ""; @@ -2855,11 +2857,11 @@ var ts; this.objectFlags & 8 /* Tuple */ ? "TupleType" : this.objectFlags & 16 /* Anonymous */ ? "AnonymousType" : this.objectFlags & 32 /* Mapped */ ? "MappedType" : - this.objectFlags & 2048 /* ReverseMapped */ ? "ReverseMappedType" : + this.objectFlags & 1024 /* ReverseMapped */ ? "ReverseMappedType" : this.objectFlags & 256 /* EvolvingArray */ ? "EvolvingArrayType" : "ObjectType" : "Type"; - var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~2367 /* ObjectTypeKindMask */ : 0; + var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~1343 /* ObjectTypeKindMask */ : 0; return "" + typeHeader + (this.symbol ? " '" + ts.symbolName(this.symbol) + "'" : "") + (remainingObjectFlags ? " (" + formatObjectFlags(remainingObjectFlags) + ")" : ""); } }, @@ -3405,16 +3407,22 @@ var ts; typeof PerformanceObserver === "function" && hasRequiredAPI(performance, PerformanceObserver)) { return { + // For now we always write native performance events when running in the browser. We may + // make this conditional in the future if we find that native web performance hooks + // in the browser also slow down compilation. + shouldWriteNativeEvents: true, performance: performance, PerformanceObserver: PerformanceObserver }; } } function tryGetNodePerformanceHooks() { - if (typeof module === "object" && typeof require === "function") { + if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof module === "object" && typeof require === "function") { try { - var _a = require("perf_hooks"), performance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; - if (hasRequiredAPI(performance_1, PerformanceObserver_1)) { + var performance_1; + var _a = require("perf_hooks"), nodePerformance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; + if (hasRequiredAPI(nodePerformance_1, PerformanceObserver_1)) { + performance_1 = nodePerformance_1; // There is a bug in Node's performance.measure prior to 12.16.3/13.13.0 that does not // match the Web Performance API specification. Node's implementation did not allow // optional `start` and `end` arguments for `performance.measure`. @@ -3422,27 +3430,26 @@ var ts; var version_1 = new ts.Version(process.versions.node); var range = new ts.VersionRange("<12.16.3 || 13 <13.13"); if (range.test(version_1)) { - return { - performance: { - get timeOrigin() { return performance_1.timeOrigin; }, - now: function () { return performance_1.now(); }, - mark: function (name) { return performance_1.mark(name); }, - measure: function (name, start, end) { - if (start === void 0) { start = "nodeStart"; } - if (end === undefined) { - end = "__performance.measure-fix__"; - performance_1.mark(end); - } - performance_1.measure(name, start, end); - if (end === "__performance.measure-fix__") { - performance_1.clearMarks("__performance.measure-fix__"); - } + performance_1 = { + get timeOrigin() { return nodePerformance_1.timeOrigin; }, + now: function () { return nodePerformance_1.now(); }, + mark: function (name) { return nodePerformance_1.mark(name); }, + measure: function (name, start, end) { + if (start === void 0) { start = "nodeStart"; } + if (end === undefined) { + end = "__performance.measure-fix__"; + nodePerformance_1.mark(end); } - }, - PerformanceObserver: PerformanceObserver_1 + nodePerformance_1.measure(name, start, end); + if (end === "__performance.measure-fix__") { + nodePerformance_1.clearMarks("__performance.measure-fix__"); + } + } }; } return { + // By default, only write native events when generating a cpu profile or using the v8 profiler. + shouldWriteNativeEvents: false, performance: performance_1, PerformanceObserver: PerformanceObserver_1 }; @@ -3473,7 +3480,6 @@ var ts; var performance; (function (performance) { var perfHooks; - var perfObserver; // when set, indicates the implementation of `Performance` to use for user timing. // when unset, indicates user timing is unavailable or disabled. var performanceImpl; @@ -3504,6 +3510,9 @@ var ts; } performance.createTimer = createTimer; performance.nullTimer = { enter: ts.noop, exit: ts.noop }; + var enabled = false; + var timeorigin = ts.timestamp(); + var marks = new ts.Map(); var counts = new ts.Map(); var durations = new ts.Map(); /** @@ -3512,7 +3521,13 @@ var ts; * @param markName The name of the mark. */ function mark(markName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + var _a; + if (enabled) { + var count = (_a = counts.get(markName)) !== null && _a !== void 0 ? _a : 0; + counts.set(markName, count + 1); + marks.set(markName, ts.timestamp()); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + } } performance.mark = mark; /** @@ -3525,7 +3540,14 @@ var ts; * used. */ function measure(measureName, startMarkName, endMarkName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + var _a, _b; + if (enabled) { + var end = (_a = (endMarkName !== undefined ? marks.get(endMarkName) : undefined)) !== null && _a !== void 0 ? _a : ts.timestamp(); + var start = (_b = (startMarkName !== undefined ? marks.get(startMarkName) : undefined)) !== null && _b !== void 0 ? _b : timeorigin; + var previousDuration = durations.get(measureName) || 0; + durations.set(measureName, previousDuration + (end - start)); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + } } performance.measure = measure; /** @@ -3559,40 +3581,41 @@ var ts; * Indicates whether the performance API is enabled. */ function isEnabled() { - return !!performanceImpl; + return enabled; } performance.isEnabled = isEnabled; /** Enables (and resets) performance measurements for the compiler. */ - function enable() { - if (!performanceImpl) { + function enable(system) { + var _a; + if (system === void 0) { system = ts.sys; } + if (!enabled) { + enabled = true; perfHooks || (perfHooks = ts.tryGetNativePerformanceHooks()); - if (!perfHooks) - return false; - perfObserver || (perfObserver = new perfHooks.PerformanceObserver(updateStatisticsFromList)); - perfObserver.observe({ entryTypes: ["mark", "measure"] }); - performanceImpl = perfHooks.performance; + if (perfHooks) { + timeorigin = perfHooks.performance.timeOrigin; + // NodeJS's Web Performance API is currently slower than expected, but we'd still like + // to be able to leverage native trace events when node is run with either `--cpu-prof` + // or `--prof`, if we're running with our own `--generateCpuProfile` flag, or when + // running in debug mode (since its possible to generate a cpu profile while debugging). + if (perfHooks.shouldWriteNativeEvents || ((_a = system === null || system === void 0 ? void 0 : system.cpuProfilingEnabled) === null || _a === void 0 ? void 0 : _a.call(system)) || (system === null || system === void 0 ? void 0 : system.debugMode)) { + performanceImpl = perfHooks.performance; + } + } } return true; } performance.enable = enable; /** Disables performance measurements for the compiler. */ function disable() { - perfObserver === null || perfObserver === void 0 ? void 0 : perfObserver.disconnect(); - performanceImpl = undefined; - counts.clear(); - durations.clear(); - } - performance.disable = disable; - function updateStatisticsFromList(list) { - for (var _i = 0, _a = list.getEntriesByType("mark"); _i < _a.length; _i++) { - var mark_1 = _a[_i]; - counts.set(mark_1.name, (counts.get(mark_1.name) || 0) + 1); - } - for (var _b = 0, _c = list.getEntriesByType("measure"); _b < _c.length; _b++) { - var measure_1 = _c[_b]; - durations.set(measure_1.name, (durations.get(measure_1.name) || 0) + measure_1.duration); + if (enabled) { + marks.clear(); + counts.clear(); + durations.clear(); + performanceImpl = undefined; + enabled = false; } } + performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); /* @internal */ @@ -3636,40 +3659,35 @@ var ts; /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; })(ts || (ts = {})); +/* Tracing events for the compiler. */ /*@internal*/ -/** Tracing events for the compiler. */ var ts; (function (ts) { - var tracing; - (function (tracing) { - var Mode; - (function (Mode) { - Mode[Mode["Project"] = 0] = "Project"; - Mode[Mode["Build"] = 1] = "Build"; - Mode[Mode["Server"] = 2] = "Server"; - })(Mode = tracing.Mode || (tracing.Mode = {})); + // enable the above using startTracing() + // `tracingEnabled` should never be used directly, only through the above + var tracingEnabled; + (function (tracingEnabled) { var fs; var traceCount = 0; - var traceFd; + var traceFd = 0; var mode; + var typeCatalog = []; // NB: id is index + 1 var legendPath; var legend = []; ; - /** Starts tracing for the given project (unless the `fs` module is unavailable). */ + /** Starts tracing for the given project. */ function startTracing(tracingMode, traceDir, configFilePath) { - ts.Debug.assert(!traceFd, "Tracing already started"); + ts.Debug.assert(!ts.tracing, "Tracing already started"); if (fs === undefined) { try { fs = require("fs"); } - catch (_a) { - fs = false; + catch (e) { + throw new Error("tracing requires having fs\n(original error: " + (e.message || e) + ")"); } } - if (!fs) { - return; - } mode = tracingMode; + typeCatalog.length = 0; if (legendPath === undefined) { legendPath = ts.combinePaths(traceDir, "legend.json"); } @@ -3677,9 +3695,9 @@ var ts; if (!fs.existsSync(traceDir)) { fs.mkdirSync(traceDir, { recursive: true }); } - var countPart = mode === 1 /* Build */ ? "." + process.pid + "-" + ++traceCount : - mode === 2 /* Server */ ? "." + process.pid : - ""; + var countPart = mode === "build" ? "." + process.pid + "-" + ++traceCount + : mode === "server" ? "." + process.pid + : ""; var tracePath = ts.combinePaths(traceDir, "trace" + countPart + ".json"); var typesPath = ts.combinePaths(traceDir, "types" + countPart + ".json"); legend.push({ @@ -3688,25 +3706,22 @@ var ts; typesPath: typesPath, }); traceFd = fs.openSync(tracePath, "w"); + ts.tracing = tracingEnabled; // only when traceFd is properly set // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import) var meta = { cat: "__metadata", ph: "M", ts: 1000 * ts.timestamp(), pid: 1, tid: 1 }; fs.writeSync(traceFd, "[\n" + [__assign({ name: "process_name", args: { name: "tsc" } }, meta), __assign({ name: "thread_name", args: { name: "Main" } }, meta), __assign(__assign({ name: "TracingStartedInBrowser" }, meta), { cat: "disabled-by-default-devtools.timeline" })] .map(function (v) { return JSON.stringify(v); }).join(",\n")); } - tracing.startTracing = startTracing; - /** Stops tracing for the in-progress project and dumps the type catalog (unless the `fs` module is unavailable). */ - function stopTracing(typeCatalog) { - if (!traceFd) { - ts.Debug.assert(!fs, "Tracing is not in progress"); - return; - } - ts.Debug.assert(fs); - ts.Debug.assert(!!typeCatalog === (mode !== 2 /* Server */)); // Have a type catalog iff not in server mode + tracingEnabled.startTracing = startTracing; + /** Stops tracing for the in-progress project and dumps the type catalog. */ + function stopTracing() { + ts.Debug.assert(ts.tracing, "Tracing is not in progress"); + ts.Debug.assert(!!typeCatalog.length === (mode !== "server")); // Have a type catalog iff not in server mode fs.writeSync(traceFd, "\n]\n"); fs.closeSync(traceFd); - traceFd = undefined; - if (typeCatalog) { + ts.tracing = undefined; + if (typeCatalog.length) { dumpTypes(typeCatalog); } else { @@ -3715,11 +3730,13 @@ var ts; legend[legend.length - 1].typesPath = undefined; } } - tracing.stopTracing = stopTracing; - function isTracing() { - return !!traceFd; + tracingEnabled.stopTracing = stopTracing; + function recordType(type) { + if (mode !== "server") { + typeCatalog.push(type); + } } - tracing.isTracing = isTracing; + tracingEnabled.recordType = recordType; var Phase; (function (Phase) { Phase["Parse"] = "parse"; @@ -3729,13 +3746,11 @@ var ts; Phase["CheckTypes"] = "checkTypes"; Phase["Emit"] = "emit"; Phase["Session"] = "session"; - })(Phase = tracing.Phase || (tracing.Phase = {})); + })(Phase = tracingEnabled.Phase || (tracingEnabled.Phase = {})); function instant(phase, name, args) { - if (!traceFd) - return; writeEvent("I", phase, name, args, "\"s\":\"g\""); } - tracing.instant = instant; + tracingEnabled.instant = instant; var eventStack = []; /** * @param separateBeginAndEnd - used for special cases where we need the trace point even if the event @@ -3745,47 +3760,42 @@ var ts; */ function push(phase, name, args, separateBeginAndEnd) { if (separateBeginAndEnd === void 0) { separateBeginAndEnd = false; } - if (!traceFd) - return; if (separateBeginAndEnd) { writeEvent("B", phase, name, args); } eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } - tracing.push = push; + tracingEnabled.push = push; function pop() { - if (!traceFd) - return; ts.Debug.assert(eventStack.length > 0); writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); eventStack.length--; } - tracing.pop = pop; + tracingEnabled.pop = pop; function popAll() { - if (!traceFd) - return; var endTime = 1000 * ts.timestamp(); for (var i = eventStack.length - 1; i >= 0; i--) { writeStackEvent(i, endTime); } eventStack.length = 0; } - tracing.popAll = popAll; + tracingEnabled.popAll = popAll; + // sample every 10ms + var sampleInterval = 1000 * 10; function writeStackEvent(index, endTime) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); } - else { + // test if [time,endTime) straddles a sampling point + else if (sampleInterval - (time % sampleInterval) <= endTime - time) { writeEvent("X", phase, name, args, "\"dur\":" + (endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { if (time === void 0) { time = 1000 * ts.timestamp(); } - ts.Debug.assert(traceFd); - ts.Debug.assert(fs); // In server mode, there's no easy way to dump type information, so we drop events that would require it. - if (mode === 2 /* Server */ && phase === "checkTypes" /* CheckTypes */) + if (mode === "server" && phase === "checkTypes" /* CheckTypes */) return; ts.performance.mark("beginTracing"); fs.writeSync(traceFd, ",\n{\"pid\":1,\"tid\":1,\"ph\":\"" + eventType + "\",\"cat\":\"" + phase + "\",\"ts\":" + time + ",\"name\":\"" + name + "\""); @@ -3797,15 +3807,24 @@ var ts; ts.performance.mark("endTracing"); ts.performance.measure("Tracing", "beginTracing", "endTracing"); } - function indexFromOne(lc) { - return { - line: lc.line + 1, - character: lc.character + 1, - }; + function getLocation(node) { + var file = ts.getSourceFileOfNode(node); + return !file + ? undefined + : { + path: file.path, + start: indexFromOne(ts.getLineAndCharacterOfPosition(file, node.pos)), + end: indexFromOne(ts.getLineAndCharacterOfPosition(file, node.end)), + }; + function indexFromOne(lc) { + return { + line: lc.line + 1, + character: lc.character + 1, + }; + } } function dumpTypes(types) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; - ts.Debug.assert(fs); + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x; ts.performance.mark("beginDumpTypes"); var typesPath = legend[legend.length - 1].typesPath; var typesFd = fs.openSync(typesPath, "w"); @@ -3817,15 +3836,13 @@ var ts; var type = types[i]; var objectFlags = type.objectFlags; var symbol = (_a = type.aliasSymbol) !== null && _a !== void 0 ? _a : type.symbol; - var firstDeclaration = (_b = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _b === void 0 ? void 0 : _b[0]; - var firstFile = firstDeclaration && ts.getSourceFileOfNode(firstDeclaration); // It's slow to compute the display text, so skip it unless it's really valuable (or cheap) var display = void 0; if ((objectFlags & 16 /* Anonymous */) | (type.flags & 2944 /* Literal */)) { try { - display = (_c = type.checker) === null || _c === void 0 ? void 0 : _c.typeToString(type); + display = (_b = type.checker) === null || _b === void 0 ? void 0 : _b.typeToString(type); } - catch (_s) { + catch (_y) { display = undefined; } } @@ -3833,26 +3850,52 @@ var ts; if (type.flags & 8388608 /* IndexedAccess */) { var indexedAccessType = type; indexedAccessProperties = { - indexedAccessObjectType: (_d = indexedAccessType.objectType) === null || _d === void 0 ? void 0 : _d.id, - indexedAccessIndexType: (_e = indexedAccessType.indexType) === null || _e === void 0 ? void 0 : _e.id, + indexedAccessObjectType: (_c = indexedAccessType.objectType) === null || _c === void 0 ? void 0 : _c.id, + indexedAccessIndexType: (_d = indexedAccessType.indexType) === null || _d === void 0 ? void 0 : _d.id, }; } var referenceProperties = {}; if (objectFlags & 4 /* Reference */) { var referenceType = type; referenceProperties = { - instantiatedType: (_f = referenceType.target) === null || _f === void 0 ? void 0 : _f.id, - typeArguments: (_g = referenceType.resolvedTypeArguments) === null || _g === void 0 ? void 0 : _g.map(function (t) { return t.id; }), + instantiatedType: (_e = referenceType.target) === null || _e === void 0 ? void 0 : _e.id, + typeArguments: (_f = referenceType.resolvedTypeArguments) === null || _f === void 0 ? void 0 : _f.map(function (t) { return t.id; }), + referenceLocation: getLocation(referenceType.node), }; } var conditionalProperties = {}; if (type.flags & 16777216 /* Conditional */) { var conditionalType = type; conditionalProperties = { - conditionalCheckType: (_h = conditionalType.checkType) === null || _h === void 0 ? void 0 : _h.id, - conditionalExtendsType: (_j = conditionalType.extendsType) === null || _j === void 0 ? void 0 : _j.id, - conditionalTrueType: (_l = (_k = conditionalType.resolvedTrueType) === null || _k === void 0 ? void 0 : _k.id) !== null && _l !== void 0 ? _l : -1, - conditionalFalseType: (_o = (_m = conditionalType.resolvedFalseType) === null || _m === void 0 ? void 0 : _m.id) !== null && _o !== void 0 ? _o : -1, + conditionalCheckType: (_g = conditionalType.checkType) === null || _g === void 0 ? void 0 : _g.id, + conditionalExtendsType: (_h = conditionalType.extendsType) === null || _h === void 0 ? void 0 : _h.id, + conditionalTrueType: (_k = (_j = conditionalType.resolvedTrueType) === null || _j === void 0 ? void 0 : _j.id) !== null && _k !== void 0 ? _k : -1, + conditionalFalseType: (_m = (_l = conditionalType.resolvedFalseType) === null || _l === void 0 ? void 0 : _l.id) !== null && _m !== void 0 ? _m : -1, + }; + } + var substitutionProperties = {}; + if (type.flags & 33554432 /* Substitution */) { + var substitutionType = type; + substitutionProperties = { + substitutionBaseType: (_o = substitutionType.baseType) === null || _o === void 0 ? void 0 : _o.id, + substituteType: (_p = substitutionType.substitute) === null || _p === void 0 ? void 0 : _p.id, + }; + } + var reverseMappedProperties = {}; + if (objectFlags & 1024 /* ReverseMapped */) { + var reverseMappedType = type; + reverseMappedProperties = { + reverseMappedSourceType: (_q = reverseMappedType.source) === null || _q === void 0 ? void 0 : _q.id, + reverseMappedMappedType: (_r = reverseMappedType.mappedType) === null || _r === void 0 ? void 0 : _r.id, + reverseMappedConstraintType: (_s = reverseMappedType.constraintType) === null || _s === void 0 ? void 0 : _s.id, + }; + } + var evolvingArrayProperties = {}; + if (objectFlags & 256 /* EvolvingArray */) { + var evolvingArrayType = type; + evolvingArrayProperties = { + evolvingArrayElementType: evolvingArrayType.elementType.id, + evolvingArrayFinalType: (_t = evolvingArrayType.finalArrayType) === null || _t === void 0 ? void 0 : _t.id, }; } // We can't print out an arbitrary object, so just assign each one a unique number. @@ -3866,11 +3909,7 @@ var ts; recursionIdentityMap.set(recursionIdentity, recursionToken); } } - var descriptor = __assign(__assign(__assign(__assign({ id: type.id, intrinsicName: type.intrinsicName, symbolName: (symbol === null || symbol === void 0 ? void 0 : symbol.escapedName) && ts.unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, unionTypes: (type.flags & 1048576 /* Union */) ? (_p = type.types) === null || _p === void 0 ? void 0 : _p.map(function (t) { return t.id; }) : undefined, intersectionTypes: (type.flags & 2097152 /* Intersection */) ? type.types.map(function (t) { return t.id; }) : undefined, aliasTypeArguments: (_q = type.aliasTypeArguments) === null || _q === void 0 ? void 0 : _q.map(function (t) { return t.id; }), keyofType: (type.flags & 4194304 /* Index */) ? (_r = type.type) === null || _r === void 0 ? void 0 : _r.id : undefined }, indexedAccessProperties), referenceProperties), conditionalProperties), { firstDeclaration: firstDeclaration && { - path: firstFile.path, - start: indexFromOne(ts.getLineAndCharacterOfPosition(firstFile, firstDeclaration.pos)), - end: indexFromOne(ts.getLineAndCharacterOfPosition(ts.getSourceFileOfNode(firstDeclaration), firstDeclaration.end)), - }, flags: ts.Debug.formatTypeFlags(type.flags).split("|"), display: display }); + var descriptor = __assign(__assign(__assign(__assign(__assign(__assign(__assign({ id: type.id, intrinsicName: type.intrinsicName, symbolName: (symbol === null || symbol === void 0 ? void 0 : symbol.escapedName) && ts.unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, isTuple: objectFlags & 8 /* Tuple */ ? true : undefined, unionTypes: (type.flags & 1048576 /* Union */) ? (_u = type.types) === null || _u === void 0 ? void 0 : _u.map(function (t) { return t.id; }) : undefined, intersectionTypes: (type.flags & 2097152 /* Intersection */) ? type.types.map(function (t) { return t.id; }) : undefined, aliasTypeArguments: (_v = type.aliasTypeArguments) === null || _v === void 0 ? void 0 : _v.map(function (t) { return t.id; }), keyofType: (type.flags & 4194304 /* Index */) ? (_w = type.type) === null || _w === void 0 ? void 0 : _w.id : undefined }, indexedAccessProperties), referenceProperties), conditionalProperties), substitutionProperties), reverseMappedProperties), evolvingArrayProperties), { destructuringPattern: getLocation(type.pattern), firstDeclaration: getLocation((_x = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _x === void 0 ? void 0 : _x[0]), flags: ts.Debug.formatTypeFlags(type.flags).split("|"), display: display }); fs.writeSync(typesFd, JSON.stringify(descriptor)); if (i < numTypes - 1) { fs.writeSync(typesFd, ",\n"); @@ -3885,11 +3924,13 @@ var ts; if (!legendPath) { return; } - ts.Debug.assert(fs); fs.writeFileSync(legendPath, JSON.stringify(legend)); } - tracing.dumpLegend = dumpLegend; - })(tracing = ts.tracing || (ts.tracing = {})); + tracingEnabled.dumpLegend = dumpLegend; + })(tracingEnabled || (tracingEnabled = {})); + // define after tracingEnabled is initialized + ts.startTracing = tracingEnabled.startTracing; + ts.dumpTracingLegend = tracingEnabled.dumpLegend; })(ts || (ts = {})); var ts; (function (ts) { @@ -4065,215 +4106,216 @@ var ts; SyntaxKind[SyntaxKind["FromKeyword"] = 153] = "FromKeyword"; SyntaxKind[SyntaxKind["GlobalKeyword"] = 154] = "GlobalKeyword"; SyntaxKind[SyntaxKind["BigIntKeyword"] = 155] = "BigIntKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 156] = "OfKeyword"; + SyntaxKind[SyntaxKind["OverrideKeyword"] = 156] = "OverrideKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 157] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 157] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 158] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 158] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 159] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 159] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 160] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 161] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 160] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 161] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 162] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 162] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 163] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 164] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 165] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 166] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 167] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 168] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 169] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 170] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 171] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 163] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 164] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 165] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 166] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 167] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 168] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 169] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 170] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 171] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 172] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 172] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 173] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 174] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 175] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 176] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 177] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 178] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 179] = "TupleType"; - SyntaxKind[SyntaxKind["OptionalType"] = 180] = "OptionalType"; - SyntaxKind[SyntaxKind["RestType"] = 181] = "RestType"; - SyntaxKind[SyntaxKind["UnionType"] = 182] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 183] = "IntersectionType"; - SyntaxKind[SyntaxKind["ConditionalType"] = 184] = "ConditionalType"; - SyntaxKind[SyntaxKind["InferType"] = 185] = "InferType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 186] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 187] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 188] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 189] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 190] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 191] = "LiteralType"; - SyntaxKind[SyntaxKind["NamedTupleMember"] = 192] = "NamedTupleMember"; - SyntaxKind[SyntaxKind["TemplateLiteralType"] = 193] = "TemplateLiteralType"; - SyntaxKind[SyntaxKind["TemplateLiteralTypeSpan"] = 194] = "TemplateLiteralTypeSpan"; - SyntaxKind[SyntaxKind["ImportType"] = 195] = "ImportType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 173] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 174] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 175] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 176] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 177] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 178] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 179] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 180] = "TupleType"; + SyntaxKind[SyntaxKind["OptionalType"] = 181] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 182] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 183] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 184] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 185] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 186] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 187] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 188] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 189] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 190] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 191] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 192] = "LiteralType"; + SyntaxKind[SyntaxKind["NamedTupleMember"] = 193] = "NamedTupleMember"; + SyntaxKind[SyntaxKind["TemplateLiteralType"] = 194] = "TemplateLiteralType"; + SyntaxKind[SyntaxKind["TemplateLiteralTypeSpan"] = 195] = "TemplateLiteralTypeSpan"; + SyntaxKind[SyntaxKind["ImportType"] = 196] = "ImportType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 196] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 197] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 198] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 197] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 198] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 199] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 199] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 200] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 201] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 202] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 203] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 204] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 205] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 206] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 207] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 208] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 209] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 210] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 211] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 212] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 213] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 214] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 215] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 216] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 217] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 218] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 219] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 220] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 221] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 222] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 223] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 224] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 225] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 226] = "MetaProperty"; - SyntaxKind[SyntaxKind["SyntheticExpression"] = 227] = "SyntheticExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 200] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 201] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 202] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 203] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 204] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 205] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 206] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 207] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 208] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 209] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 210] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 211] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 212] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 213] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 214] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 215] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 216] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 217] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 218] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 219] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 220] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 221] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 222] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 223] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 224] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 225] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 226] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 227] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 228] = "SyntheticExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 228] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 229] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 229] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 230] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 230] = "Block"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 231] = "EmptyStatement"; - SyntaxKind[SyntaxKind["VariableStatement"] = 232] = "VariableStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 233] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 234] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 235] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 236] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 237] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 238] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 239] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 240] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 241] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 242] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 243] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 244] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 245] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 246] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 247] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 248] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 249] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 250] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 251] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 252] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 253] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 254] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 255] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 256] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 257] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 258] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 259] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 260] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 261] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 262] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 263] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 264] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 265] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 266] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 267] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 268] = "NamedExports"; - SyntaxKind[SyntaxKind["NamespaceExport"] = 269] = "NamespaceExport"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 270] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 271] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 231] = "Block"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 232] = "EmptyStatement"; + SyntaxKind[SyntaxKind["VariableStatement"] = 233] = "VariableStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 234] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 235] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 236] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 237] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 238] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 239] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 240] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 241] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 242] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 243] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 244] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 245] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 246] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 247] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 248] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 249] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 250] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 251] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 252] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 253] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 254] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 255] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 256] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 257] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 258] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 259] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 260] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 261] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 262] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 263] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 264] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 265] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 266] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 267] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 268] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 269] = "NamedExports"; + SyntaxKind[SyntaxKind["NamespaceExport"] = 270] = "NamespaceExport"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 271] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 272] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 272] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 273] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 273] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 274] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 275] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 276] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxFragment"] = 277] = "JsxFragment"; - SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 278] = "JsxOpeningFragment"; - SyntaxKind[SyntaxKind["JsxClosingFragment"] = 279] = "JsxClosingFragment"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 280] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 281] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 282] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 283] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 274] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 275] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 276] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 277] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 278] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 279] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 280] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 281] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 282] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 283] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 284] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 284] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 285] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 286] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 287] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 285] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 286] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 287] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 288] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 288] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 289] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 290] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 289] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 290] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 291] = "SpreadAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 291] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 292] = "EnumMember"; // Unparsed - SyntaxKind[SyntaxKind["UnparsedPrologue"] = 292] = "UnparsedPrologue"; - SyntaxKind[SyntaxKind["UnparsedPrepend"] = 293] = "UnparsedPrepend"; - SyntaxKind[SyntaxKind["UnparsedText"] = 294] = "UnparsedText"; - SyntaxKind[SyntaxKind["UnparsedInternalText"] = 295] = "UnparsedInternalText"; - SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 296] = "UnparsedSyntheticReference"; + SyntaxKind[SyntaxKind["UnparsedPrologue"] = 293] = "UnparsedPrologue"; + SyntaxKind[SyntaxKind["UnparsedPrepend"] = 294] = "UnparsedPrepend"; + SyntaxKind[SyntaxKind["UnparsedText"] = 295] = "UnparsedText"; + SyntaxKind[SyntaxKind["UnparsedInternalText"] = 296] = "UnparsedInternalText"; + SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 297] = "UnparsedSyntheticReference"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 297] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 298] = "Bundle"; - SyntaxKind[SyntaxKind["UnparsedSource"] = 299] = "UnparsedSource"; - SyntaxKind[SyntaxKind["InputFiles"] = 300] = "InputFiles"; + SyntaxKind[SyntaxKind["SourceFile"] = 298] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 299] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 300] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 301] = "InputFiles"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 301] = "JSDocTypeExpression"; - SyntaxKind[SyntaxKind["JSDocNameReference"] = 302] = "JSDocNameReference"; - // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 303] = "JSDocAllType"; - // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 304] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 305] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 306] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 307] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 308] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 309] = "JSDocVariadicType"; - // https://jsdoc.app/about-namepaths.html - SyntaxKind[SyntaxKind["JSDocNamepathType"] = 310] = "JSDocNamepathType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 311] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 312] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocSignature"] = 313] = "JSDocSignature"; - SyntaxKind[SyntaxKind["JSDocTag"] = 314] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 315] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 316] = "JSDocImplementsTag"; - SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 317] = "JSDocAuthorTag"; - SyntaxKind[SyntaxKind["JSDocDeprecatedTag"] = 318] = "JSDocDeprecatedTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 319] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocPublicTag"] = 320] = "JSDocPublicTag"; - SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 321] = "JSDocPrivateTag"; - SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 322] = "JSDocProtectedTag"; - SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 323] = "JSDocReadonlyTag"; - SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 324] = "JSDocCallbackTag"; - SyntaxKind[SyntaxKind["JSDocEnumTag"] = 325] = "JSDocEnumTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 326] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 327] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocThisTag"] = 328] = "JSDocThisTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 329] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 330] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 331] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocSeeTag"] = 332] = "JSDocSeeTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 333] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 302] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocNameReference"] = 303] = "JSDocNameReference"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 304] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 305] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 306] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 307] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 308] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 309] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 310] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocNamepathType"] = 311] = "JSDocNamepathType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 312] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocText"] = 313] = "JSDocText"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 314] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 315] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocLink"] = 316] = "JSDocLink"; + SyntaxKind[SyntaxKind["JSDocTag"] = 317] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 318] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 319] = "JSDocImplementsTag"; + SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 320] = "JSDocAuthorTag"; + SyntaxKind[SyntaxKind["JSDocDeprecatedTag"] = 321] = "JSDocDeprecatedTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 322] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocPublicTag"] = 323] = "JSDocPublicTag"; + SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 324] = "JSDocPrivateTag"; + SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 325] = "JSDocProtectedTag"; + SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 326] = "JSDocReadonlyTag"; + SyntaxKind[SyntaxKind["JSDocOverrideTag"] = 327] = "JSDocOverrideTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 328] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 329] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 330] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 331] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 332] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 333] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 334] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 335] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocSeeTag"] = 336] = "JSDocSeeTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 337] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 334] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 338] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 335] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 336] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 337] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 338] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 339] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 340] = "SyntheticReferenceExpression"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 339] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 340] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 341] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 342] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 343] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 344] = "SyntheticReferenceExpression"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 341] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 345] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 62] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 77] = "LastAssignment"; @@ -4282,15 +4324,15 @@ var ts; SyntaxKind[SyntaxKind["FirstReservedWord"] = 80] = "FirstReservedWord"; SyntaxKind[SyntaxKind["LastReservedWord"] = 115] = "LastReservedWord"; SyntaxKind[SyntaxKind["FirstKeyword"] = 80] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 156] = "LastKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 157] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 116] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 124] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 172] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 195] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 173] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 196] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 77] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 156] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 157] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; @@ -4299,15 +4341,15 @@ var ts; SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken"; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 29] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 77] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstStatement"] = 232] = "FirstStatement"; - SyntaxKind[SyntaxKind["LastStatement"] = 248] = "LastStatement"; - SyntaxKind[SyntaxKind["FirstNode"] = 157] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 301] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 333] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 314] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 333] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstStatement"] = 233] = "FirstStatement"; + SyntaxKind[SyntaxKind["LastStatement"] = 249] = "LastStatement"; + SyntaxKind[SyntaxKind["FirstNode"] = 158] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 302] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 337] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 317] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 337] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 125] = "FirstContextualKeyword"; - /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 156] = "LastContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 157] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -4377,14 +4419,15 @@ var ts; ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; ModifierFlags[ModifierFlags["HasComputedJSDocModifiers"] = 4096] = "HasComputedJSDocModifiers"; ModifierFlags[ModifierFlags["Deprecated"] = 8192] = "Deprecated"; + ModifierFlags[ModifierFlags["Override"] = 16384] = "Override"; ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. - ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 16476] = "ParameterPropertyModifier"; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; - ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; + ModifierFlags[ModifierFlags["TypeScriptModifier"] = 18654] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; - ModifierFlags[ModifierFlags["All"] = 11263] = "All"; + ModifierFlags[ModifierFlags["All"] = 27647] = "All"; })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); var JsxFlags; (function (JsxFlags) { @@ -4565,6 +4608,8 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["NoUndefinedOptionalParameterType"] = 1073741824] = "NoUndefinedOptionalParameterType"; // Error handling NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifiedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifiedNameInPlaceOfIdentifier"; + /** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */ NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier"; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection"; @@ -4579,7 +4624,6 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; - NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -4884,10 +4928,6 @@ var ts; TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["StringLikeLiteral"] = 134217856] = "StringLikeLiteral"; - /* @internal */ - TypeFlags[TypeFlags["FreshableLiteral"] = 134220672] = "FreshableLiteral"; - /* @internal */ TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; /* @internal */ TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; @@ -4936,6 +4976,9 @@ var ts; /* @internal */ TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags + // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check + // for a certain TypeFlags value to determine their meaning. var ObjectFlags; (function (ObjectFlags) { ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; @@ -4948,50 +4991,59 @@ var ts; ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; - ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; - ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; - ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; - ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; - ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; - ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral"; - ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 1024] = "ReverseMapped"; + ObjectFlags[ObjectFlags["JsxAttributes"] = 2048] = "JsxAttributes"; + ObjectFlags[ObjectFlags["MarkerType"] = 4096] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 8192] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 16384] = "FreshLiteral"; + ObjectFlags[ObjectFlags["ArrayLiteral"] = 32768] = "ArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion"; + ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType"; + ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral"; + ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 262144] = "ContainsObjectOrArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType"; + ObjectFlags[ObjectFlags["NonInferrableType"] = 524288] = "NonInferrableType"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; + ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 1048576] = "CouldContainTypeVariablesComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; + ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 2097152] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; + ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags"; + // Object flags that uniquely identify the kind of ObjectType /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed"; + ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 1343] = "ObjectTypeKindMask"; + // Flags that require TypeFlags.Object + ObjectFlags[ObjectFlags["ContainsSpread"] = 4194304] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ObjectRestType"] = 8388608] = "ObjectRestType"; /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 16777216] = "IsClassInstanceClone"; + // Flags that require TypeFlags.Object and ObjectFlags.Reference /* @internal */ - ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeCalculated"] = 33554432] = "IdenticalBaseTypeCalculated"; /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeExists"] = 67108864] = "IdenticalBaseTypeExists"; + // Flags that require TypeFlags.UnionOrIntersection or TypeFlags.Substitution /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection"; + ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 1073741824] = "IsClassInstanceClone"; - ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; /* @internal */ - ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; + ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags"; - // Object flags that uniquely identify the kind of ObjectType + ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + // Flags that require TypeFlags.Union + /* @internal */ + ObjectFlags[ObjectFlags["ContainsIntersections"] = 67108864] = "ContainsIntersections"; + // Flags that require TypeFlags.Intersection /* @internal */ - ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 2367] = "ObjectTypeKindMask"; + ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 67108864] = "IsNeverIntersectionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersection"] = 134217728] = "IsNeverIntersection"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ var VarianceFlags; @@ -5065,16 +5117,17 @@ var ts; (function (InferencePriority) { InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; InferencePriority[InferencePriority["SpeculativeTuple"] = 2] = "SpeculativeTuple"; - InferencePriority[InferencePriority["HomomorphicMappedType"] = 4] = "HomomorphicMappedType"; - InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 8] = "PartialHomomorphicMappedType"; - InferencePriority[InferencePriority["MappedTypeConstraint"] = 16] = "MappedTypeConstraint"; - InferencePriority[InferencePriority["ContravariantConditional"] = 32] = "ContravariantConditional"; - InferencePriority[InferencePriority["ReturnType"] = 64] = "ReturnType"; - InferencePriority[InferencePriority["LiteralKeyof"] = 128] = "LiteralKeyof"; - InferencePriority[InferencePriority["NoConstraints"] = 256] = "NoConstraints"; - InferencePriority[InferencePriority["AlwaysStrict"] = 512] = "AlwaysStrict"; - InferencePriority[InferencePriority["MaxValue"] = 1024] = "MaxValue"; - InferencePriority[InferencePriority["PriorityImpliesCombination"] = 208] = "PriorityImpliesCombination"; + InferencePriority[InferencePriority["SubstituteSource"] = 4] = "SubstituteSource"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 8] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 16] = "PartialHomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 32] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ContravariantConditional"] = 64] = "ContravariantConditional"; + InferencePriority[InferencePriority["ReturnType"] = 128] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 256] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 512] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 1024] = "AlwaysStrict"; + InferencePriority[InferencePriority["MaxValue"] = 2048] = "MaxValue"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 416] = "PriorityImpliesCombination"; InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); /* @internal */ @@ -5152,20 +5205,23 @@ var ts; WatchFileKind[WatchFileKind["FixedPollingInterval"] = 0] = "FixedPollingInterval"; WatchFileKind[WatchFileKind["PriorityPollingInterval"] = 1] = "PriorityPollingInterval"; WatchFileKind[WatchFileKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; - WatchFileKind[WatchFileKind["UseFsEvents"] = 3] = "UseFsEvents"; - WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 4] = "UseFsEventsOnParentDirectory"; + WatchFileKind[WatchFileKind["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; + WatchFileKind[WatchFileKind["UseFsEvents"] = 4] = "UseFsEvents"; + WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 5] = "UseFsEventsOnParentDirectory"; })(WatchFileKind = ts.WatchFileKind || (ts.WatchFileKind = {})); var WatchDirectoryKind; (function (WatchDirectoryKind) { WatchDirectoryKind[WatchDirectoryKind["UseFsEvents"] = 0] = "UseFsEvents"; WatchDirectoryKind[WatchDirectoryKind["FixedPollingInterval"] = 1] = "FixedPollingInterval"; WatchDirectoryKind[WatchDirectoryKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; + WatchDirectoryKind[WatchDirectoryKind["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; })(WatchDirectoryKind = ts.WatchDirectoryKind || (ts.WatchDirectoryKind = {})); var PollingWatchKind; (function (PollingWatchKind) { PollingWatchKind[PollingWatchKind["FixedInterval"] = 0] = "FixedInterval"; PollingWatchKind[PollingWatchKind["PriorityInterval"] = 1] = "PriorityInterval"; PollingWatchKind[PollingWatchKind["DynamicPriority"] = 2] = "DynamicPriority"; + PollingWatchKind[PollingWatchKind["FixedChunkSize"] = 3] = "FixedChunkSize"; })(PollingWatchKind = ts.PollingWatchKind || (ts.PollingWatchKind = {})); var ModuleKind; (function (ModuleKind) { @@ -5226,6 +5282,7 @@ var ts; ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019"; ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020"; + ScriptTarget[ScriptTarget["ES2021"] = 8] = "ES2021"; ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext"; ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest"; @@ -5388,29 +5445,30 @@ var ts; TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript"; TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx"; TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext"; - TransformFlags[TransformFlags["ContainsES2020"] = 8] = "ContainsES2020"; - TransformFlags[TransformFlags["ContainsES2019"] = 16] = "ContainsES2019"; - TransformFlags[TransformFlags["ContainsES2018"] = 32] = "ContainsES2018"; - TransformFlags[TransformFlags["ContainsES2017"] = 64] = "ContainsES2017"; - TransformFlags[TransformFlags["ContainsES2016"] = 128] = "ContainsES2016"; - TransformFlags[TransformFlags["ContainsES2015"] = 256] = "ContainsES2015"; - TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; - TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 1024] = "ContainsDestructuringAssignment"; + TransformFlags[TransformFlags["ContainsES2021"] = 8] = "ContainsES2021"; + TransformFlags[TransformFlags["ContainsES2020"] = 16] = "ContainsES2020"; + TransformFlags[TransformFlags["ContainsES2019"] = 32] = "ContainsES2019"; + TransformFlags[TransformFlags["ContainsES2018"] = 64] = "ContainsES2018"; + TransformFlags[TransformFlags["ContainsES2017"] = 128] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 256] = "ContainsES2016"; + TransformFlags[TransformFlags["ContainsES2015"] = 512] = "ContainsES2015"; + TransformFlags[TransformFlags["ContainsGenerator"] = 1024] = "ContainsGenerator"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 2048] = "ContainsTypeScriptClassSyntax"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 4096] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsRestOrSpread"] = 8192] = "ContainsRestOrSpread"; - TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 16384] = "ContainsObjectRestOrSpread"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 32768] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 65536] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 131072] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 262144] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsAwait"] = 524288] = "ContainsAwait"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 1048576] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 2097152] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["ContainsClassFields"] = 4194304] = "ContainsClassFields"; - TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 8388608] = "ContainsPossibleTopLevelAwait"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 16384] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 32768] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 65536] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 131072] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 262144] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 524288] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsAwait"] = 1048576] = "ContainsAwait"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 2097152] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 4194304] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["ContainsClassFields"] = 8388608] = "ContainsClassFields"; + TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 16777216] = "ContainsPossibleTopLevelAwait"; // 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 @@ -5420,37 +5478,38 @@ var ts; TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript"; TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx"; TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext"; - TransformFlags[TransformFlags["AssertES2020"] = 8] = "AssertES2020"; - TransformFlags[TransformFlags["AssertES2019"] = 16] = "AssertES2019"; - TransformFlags[TransformFlags["AssertES2018"] = 32] = "AssertES2018"; - TransformFlags[TransformFlags["AssertES2017"] = 64] = "AssertES2017"; - TransformFlags[TransformFlags["AssertES2016"] = 128] = "AssertES2016"; - TransformFlags[TransformFlags["AssertES2015"] = 256] = "AssertES2015"; - TransformFlags[TransformFlags["AssertGenerator"] = 512] = "AssertGenerator"; - TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 1024] = "AssertDestructuringAssignment"; + TransformFlags[TransformFlags["AssertES2021"] = 8] = "AssertES2021"; + TransformFlags[TransformFlags["AssertES2020"] = 16] = "AssertES2020"; + TransformFlags[TransformFlags["AssertES2019"] = 32] = "AssertES2019"; + TransformFlags[TransformFlags["AssertES2018"] = 64] = "AssertES2018"; + TransformFlags[TransformFlags["AssertES2017"] = 128] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 256] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 512] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 1024] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 2048] = "AssertDestructuringAssignment"; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes"; TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes"; TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 547309568] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 547313664] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 547311616] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 538923008] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["PropertyExcludes"] = 536875008] = "PropertyExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 536905728] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 546379776] = "ModuleExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 557748224] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 557756416] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 557752320] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 540975104] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["PropertyExcludes"] = 536879104] = "PropertyExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 536940544] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 555888640] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536922112] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536879104] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537018368] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536973312] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536887296] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537165824] = "VariableDeclarationListExcludes"; TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 536887296] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 536879104] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 536903680] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 536887296] = "BindingPatternExcludes"; // Propagating flags // - Bitmasks for flags that should propagate from a child - TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 4096] = "PropertyNamePropagatingFlags"; + TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 8192] = "PropertyNamePropagatingFlags"; // Masks // - Additional bitmasks })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); @@ -6318,7 +6377,7 @@ var ts; * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. * Comparison is case-sensitive between the canonical paths. * - * @deprecated Use `containsPath` if possible. + * Use `containsPath` if file names are not already reduced and absolute. */ function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { var canonicalFileName = getCanonicalFileName(fileName); @@ -6438,6 +6497,11 @@ var ts; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time + /* @internal */ + function getModifiedTime(host, fileName) { + return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; + } + ts.getModifiedTime = getModifiedTime; function createPollingIntervalBasedLevels(levels) { var _a; return _a = {}, @@ -6494,6 +6558,51 @@ var ts; } } ts.setCustomPollingValues = setCustomPollingValues; + function pollWatchedFileQueue(host, queue, pollIndex, chunkSize, callbackOnWatchFileStat) { + var definedValueCopyToIndex = pollIndex; + // Max visit would be all elements of the queue + for (var canVisit = queue.length; chunkSize && canVisit; nextPollIndex(), canVisit--) { + var watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + // Only files polled count towards chunkSize + chunkSize--; + var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(host, watchedFile.fileName)); + if (watchedFile.isClosed) { + // Closed watcher as part of callback + queue[pollIndex] = undefined; + continue; + } + callbackOnWatchFileStat === null || callbackOnWatchFileStat === void 0 ? void 0 : callbackOnWatchFileStat(watchedFile, pollIndex, fileChanged); + // Defragment the queue while we are at it + if (queue[pollIndex]) { + // Copy this file to the non hole location + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + // Return next poll index + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + // There are holes from definedValueCopyToIndex to end of queue, change queue size + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } /* @internal */ function createDynamicPriorityPollingWatchFile(host) { var watchedFiles = []; @@ -6507,7 +6616,7 @@ var ts; fileName: fileName, callback: callback, unchangedPolls: 0, - mtime: getModifiedTime(fileName) + mtime: getModifiedTime(host, fileName) }; watchedFiles.push(file); addToPollingIntervalQueue(file, defaultPollingInterval); @@ -6550,25 +6659,9 @@ var ts; } } function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { - // Max visit would be all elements of the queue - var needsVisit = queue.length; - var definedValueCopyToIndex = pollIndex; - for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { - var watchedFile = queue[pollIndex]; - if (!watchedFile) { - continue; - } - else if (watchedFile.isClosed) { - queue[pollIndex] = undefined; - continue; - } - polled++; - var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); - if (watchedFile.isClosed) { - // Closed watcher as part of callback - queue[pollIndex] = undefined; - } - else if (fileChanged) { + return pollWatchedFileQueue(host, queue, pollIndex, chunkSize, onWatchFileStat); + function onWatchFileStat(watchedFile, pollIndex, fileChanged) { + if (fileChanged) { watchedFile.unchangedPolls = 0; // Changed files go to changedFilesInLastPoll queue if (queue !== changedFilesInLastPoll) { @@ -6590,27 +6683,6 @@ var ts; queue[pollIndex] = undefined; addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); } - if (queue[pollIndex]) { - // Copy this file to the non hole location - if (definedValueCopyToIndex < pollIndex) { - queue[definedValueCopyToIndex] = watchedFile; - queue[pollIndex] = undefined; - } - definedValueCopyToIndex++; - } - } - // Return next poll index - return pollIndex; - function nextPollIndex() { - pollIndex++; - if (pollIndex === queue.length) { - if (definedValueCopyToIndex < pollIndex) { - // There are holes from nextDefinedValueIndex to end of queue, change queue size - queue.length = definedValueCopyToIndex; - } - pollIndex = 0; - definedValueCopyToIndex = 0; - } } } function pollingIntervalQueue(pollingInterval) { @@ -6639,9 +6711,6 @@ var ts; function scheduleNextPoll(pollingInterval) { pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); } - function getModifiedTime(fileName) { - return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; - } } ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) { @@ -6692,6 +6761,37 @@ var ts; return watcher; } } + function createFixedChunkSizePollingWatchFile(host) { + var watchedFiles = []; + var pollIndex = 0; + var pollScheduled; + return watchFile; + function watchFile(fileName, callback) { + var file = { + fileName: fileName, + callback: callback, + mtime: getModifiedTime(host, fileName) + }; + watchedFiles.push(file); + scheduleNextPoll(); + return { + close: function () { + file.isClosed = true; + ts.unorderedRemoveItem(watchedFiles, file); + } + }; + } + function pollQueue() { + pollScheduled = undefined; + pollIndex = pollWatchedFileQueue(host, watchedFiles, pollIndex, pollingChunkSize[PollingInterval.Low]); + scheduleNextPoll(); + } + function scheduleNextPoll() { + if (!watchedFiles.length || pollScheduled) + return; + pollScheduled = host.setTimeout(pollQueue, PollingInterval.High); + } + } /* @internal */ function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) { var cache = new ts.Map(); @@ -7014,8 +7114,9 @@ var ts; } /*@internal*/ function createSystemWatchFunctions(_a) { - var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory; + var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind; var dynamicPollingWatchFile; + var fixedChunkSizePollingWatchFile; var nonPollingWatchFile; var hostRecursiveDirectoryWatcher; return { @@ -7032,6 +7133,8 @@ var ts; return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined); case ts.WatchFileKind.DynamicPriorityPolling: return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined); + case ts.WatchFileKind.FixedChunkSizePolling: + return ensureFixedChunkSizePollingWatchFile()(fileName, callback, /* pollingInterval */ undefined, /*options*/ undefined); case ts.WatchFileKind.UseFsEvents: return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options)); @@ -7045,8 +7148,10 @@ var ts; } } function ensureDynamicPollingWatchFile() { - return dynamicPollingWatchFile || - (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })); + return dynamicPollingWatchFile || (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })); + } + function ensureFixedChunkSizePollingWatchFile() { + return fixedChunkSizePollingWatchFile || (fixedChunkSizePollingWatchFile = createFixedChunkSizePollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })); } function updateOptionsForWatchFile(options, useNonPollingWatchers) { if (options && options.watchFile !== undefined) @@ -7072,7 +7177,7 @@ var ts; // Use notifications from FS to watch with falling back to fs.watchFile generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) : // Default to do not use fixed polling interval - { watchFile: ts.WatchFileKind.FixedPollingInterval }; + { watchFile: (defaultWatchFileKind === null || defaultWatchFileKind === void 0 ? void 0 : defaultWatchFileKind()) || ts.WatchFileKind.FixedPollingInterval }; } } function generateWatchFileOptions(watchFile, fallbackPolling, options) { @@ -7113,6 +7218,10 @@ var ts; case ts.WatchDirectoryKind.DynamicPriorityPolling: return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, /*options*/ undefined); + case ts.WatchDirectoryKind.FixedChunkSizePolling: + return ensureFixedChunkSizePollingWatchFile()(directoryName, function () { return callback(directoryName); }, + /* pollingInterval */ undefined, + /*options*/ undefined); case ts.WatchDirectoryKind.UseFsEvents: return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), recursive, PollingInterval.Medium, ts.getFallbackOptions(watchDirectoryOptions)); default: @@ -7191,13 +7300,13 @@ var ts; } var activeSession; var profilePath = "./profile.cpuprofile"; - var realpathSync = (_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync; var Buffer = require("buffer").Buffer; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + var realpathSync = useCaseSensitiveFileNames ? ((_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync) : _fs.realpathSync; var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); var getCurrentDirectory = ts.memoize(function () { return process.cwd(); }); var _c = createSystemWatchFunctions({ @@ -7218,6 +7327,7 @@ var ts; tscWatchFile: process.env.TSC_WATCHFILE, useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER, tscWatchDirectory: process.env.TSC_WATCHDIRECTORY, + defaultWatchFileKind: function () { var _a, _b; return (_b = (_a = sys).defaultWatchFileKind) === null || _b === void 0 ? void 0 : _b.call(_a); }, }), watchFile = _c.watchFile, watchDirectory = _c.watchDirectory; var nodeSystem = { args: process.argv.slice(2), @@ -7286,6 +7396,7 @@ var ts; }, enableCPUProfiler: enableCPUProfiler, disableCPUProfiler: disableCPUProfiler, + cpuProfilingEnabled: function () { return !!activeSession || ts.contains(process.execArgv, "--cpu-prof") || ts.contains(process.execArgv, "--prof"); }, realpath: realpath, debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -7535,7 +7646,7 @@ var ts; return event === "rename" && (!relativeName || relativeName === lastDirectoryPart || - relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) && + (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && !fileSystemEntryExists(fileOrDirectory, entryKind) ? invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : callback(event, relativeName); @@ -7845,7 +7956,7 @@ var ts; Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1103, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103", "'for await' loops are only allowed within async functions and at the top levels of modules."), A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), @@ -7894,7 +8005,7 @@ var ts; A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), - A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_1166", "A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type."), A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), @@ -7954,7 +8065,7 @@ var ts; A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), - An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231", "An export assignment must be at the top level of a file or module declaration."), An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), @@ -7980,6 +8091,7 @@ var ts; A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1258, ts.DiagnosticCategory.Error, "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258", "A default export must be at the top level of a file or module declaration."), Module_0_can_only_be_default_imported_using_the_1_flag: diag(1259, ts.DiagnosticCategory.Error, "Module_0_can_only_be_default_imported_using_the_1_flag_1259", "Module '{0}' can only be default-imported using the '{1}' flag"), Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), @@ -8066,7 +8178,7 @@ var ts; Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), Provides_a_root_package_name_when_using_outFile_with_declarations: diag(1390, ts.DiagnosticCategory.Message, "Provides_a_root_package_name_when_using_outFile_with_declarations_1390", "Provides a root package name when using outFile with declarations."), - The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The `bundledPackageName` option must be provided when using outFile and node module resolution with declaration emit."), + The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The 'bundledPackageName' option must be provided when using outFile and node module resolution with declaration emit."), An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), @@ -8106,6 +8218,9 @@ var ts; File_is_output_of_project_reference_source_0: diag(1428, ts.DiagnosticCategory.Message, "File_is_output_of_project_reference_source_0_1428", "File is output of project reference source '{0}'"), File_redirects_to_file_0: diag(1429, ts.DiagnosticCategory.Message, "File_redirects_to_file_0_1429", "File redirects to file '{0}'"), The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), + for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), + Decorators_may_not_be_applied_to_this_parameters: diag(1433, ts.DiagnosticCategory.Error, "Decorators_may_not_be_applied_to_this_parameters_1433", "Decorators may not be applied to 'this' parameters."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -8173,7 +8288,7 @@ var ts; The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), - The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_in_expression_must_not_be_a_primitive: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_not_be_a_primitive_2361", "The right-hand side of an 'in' expression must not be a primitive."), The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), @@ -8191,8 +8306,7 @@ var ts; A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers."), Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), - Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."), - get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."), + The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type: diag(2380, ts.DiagnosticCategory.Error, "The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type_2380", "The return type of a 'get' accessor must be assignable to its 'set' accessor type"), A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."), Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."), Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), @@ -8255,7 +8369,7 @@ var ts; Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), - Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_cl_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'. This is an instance of class '{2}'."), The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), @@ -8355,14 +8469,13 @@ var ts; The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the `lib` compiler option to '{2}' or later."), + Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{2}' or later."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), - Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), - Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), + A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter: diag(2556, ts.DiagnosticCategory.Error, "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556", "A spread argument must either have a tuple type or be passed to a rest parameter."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), @@ -8385,17 +8498,17 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to '{1}' or later."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{1}' or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later."), Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."), Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add `node` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add `jquery` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add 'jquery' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), @@ -8428,6 +8541,12 @@ var ts; Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target: diag(2625, ts.DiagnosticCategory.Error, "Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target_2625", "Variadic element at position {0} in source does not match element at position {1} in target."), Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target: diag(2626, ts.DiagnosticCategory.Error, "Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target_2626", "Type at position {0} in source is not compatible with type at position {1} in target."), Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target: diag(2627, ts.DiagnosticCategory.Error, "Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target_2627", "Type at positions {0} through {1} in source is not compatible with type at position {2} in target."), + Cannot_assign_to_0_because_it_is_an_enum: diag(2628, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_an_enum_2628", "Cannot assign to '{0}' because it is an enum."), + Cannot_assign_to_0_because_it_is_a_class: diag(2629, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_class_2629", "Cannot assign to '{0}' because it is a class."), + Cannot_assign_to_0_because_it_is_a_function: diag(2630, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_function_2630", "Cannot assign to '{0}' because it is a function."), + Cannot_assign_to_0_because_it_is_a_namespace: diag(2631, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_namespace_2631", "Cannot assign to '{0}' because it is a namespace."), + Cannot_assign_to_0_because_it_is_an_import: diag(2632, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_an_import_2632", "Cannot assign to '{0}' because it is an import."), + JSX_property_access_expressions_cannot_include_JSX_namespace_names: diag(2633, ts.DiagnosticCategory.Error, "JSX_property_access_expressions_cannot_include_JSX_namespace_names_2633", "JSX property access expressions cannot include JSX namespace names"), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -8474,7 +8593,7 @@ var ts; Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), @@ -8482,14 +8601,14 @@ var ts; _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a 'delete' operator must be a property reference."), The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a 'delete' operator cannot be a read-only property."), - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), - A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), - A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), @@ -8551,7 +8670,7 @@ var ts; The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."), Overload_0_of_1_2_gave_the_following_error: diag(2772, ts.DiagnosticCategory.Error, "Overload_0_of_1_2_gave_the_following_error_2772", "Overload {0} of {1}, '{2}', gave the following error."), Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"), - This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it__2774", "This condition will always return true since the function is always defined. Did you mean to call it instead?"), + This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774", "This condition will always return true since this function is always defined. Did you mean to call it instead?"), Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation: diag(2775, ts.DiagnosticCategory.Error, "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775", "Assertions require every name in the call target to be declared with an explicit type annotation."), Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name: diag(2776, ts.DiagnosticCategory.Error, "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776", "Assertions require the call target to be an identifier or qualified name."), The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access: diag(2777, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777", "The operand of an increment or decrement operator may not be an optional property access."), @@ -8575,6 +8694,21 @@ var ts; The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types: diag(2795, ts.DiagnosticCategory.Error, "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795", "The 'intrinsic' keyword can only be used to declare compiler provided intrinsic types."), It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked: diag(2796, ts.DiagnosticCategory.Error, "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796", "It is likely that you are missing a comma to separate these two template expressions. They form a tagged template expression which cannot be invoked."), A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract: diag(2797, ts.DiagnosticCategory.Error, "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797", "A mixin class that extends from a type variable containing an abstract construct signature must also be declared 'abstract'."), + The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), + Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), + Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), + This_condition_will_always_return_true_since_this_0_is_always_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_is_always_defined_2801", "This condition will always return true since this '{0}' is always defined."), + Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher: diag(2802, ts.DiagnosticCategory.Error, "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802", "Type '{0}' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher."), + Cannot_assign_to_private_method_0_Private_methods_are_not_writable: diag(2803, ts.DiagnosticCategory.Error, "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803", "Cannot assign to private method '{0}'. Private methods are not writable."), + Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name: diag(2804, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804", "Duplicate identifier '{0}'. Static and instance elements cannot share the same private name."), + Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag: diag(2805, ts.DiagnosticCategory.Error, "Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_no_2805", "Static fields with private names can't have initializers when the '--useDefineForClassFields' flag is not specified with a '--target' of 'esnext'. Consider adding the '--useDefineForClassFields' flag."), + Private_accessor_was_defined_without_a_getter: diag(2806, ts.DiagnosticCategory.Error, "Private_accessor_was_defined_without_a_getter_2806", "Private accessor was defined without a getter."), + This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0: diag(2807, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807", "This syntax requires an imported helper named '{1}' with {2} parameters, which is not compatible with the one in '{0}'. Consider upgrading your version of '{0}'."), + A_get_accessor_must_be_at_least_as_accessible_as_the_setter: diag(2808, ts.DiagnosticCategory.Error, "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808", "A get accessor must be at least as accessible as the setter"), + Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses: diag(2809, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809", "Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses."), + Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false: diag(2810, ts.DiagnosticCategory.Error, "Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnex_2810", "Property '{0}' may not be used in a static property's initializer in the same class when 'target' is 'esnext' and 'useDefineForClassFields' is 'false'."), + Initializer_for_property_0: diag(2811, ts.DiagnosticCategory.Error, "Initializer_for_property_0_2811", "Initializer for property '{0}'"), + Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom: diag(2812, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812", "Property '{0}' does not exist on type '{1}'. Try changing the 'lib' compiler option to include 'dom'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -8647,6 +8781,7 @@ var ts; Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2: diag(4084, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084", "Exported type alias '{0}' has or is using private name '{1}' from module {2}."), Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), @@ -8668,6 +8803,11 @@ var ts; Type_arguments_for_0_circularly_reference_themselves: diag(4109, ts.DiagnosticCategory.Error, "Type_arguments_for_0_circularly_reference_themselves_4109", "Type arguments for '{0}' circularly reference themselves."), Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."), Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0: diag(4111, ts.DiagnosticCategory.Error, "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111", "Property '{0}' comes from an index signature, so it must be accessed with ['{0}']."), + This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class: diag(4112, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112", "This member cannot have an 'override' modifier because its containing class '{0}' does not extend another class."), + This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0: diag(4113, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113", "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'."), + This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0: diag(4114, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114", "This member must have an 'override' modifier because it overrides a member in the base class '{0}'."), + This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115", "This parameter property must have an 'override' modifier because it overrides a member in base class '{0}'."), + This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0: diag(4116, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116", "This member must have an 'override' modifier because it overrides an abstract method that is declared in the base class '{0}'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -8702,7 +8842,7 @@ var ts; Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), - Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option `--tsBuildInfoFile` is specified."), + Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option '--tsBuildInfoFile' is specified."), _0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2: diag(5075, ts.DiagnosticCategory.Error, "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075", "'{0}' is assignable to the constraint of type '{1}', but '{1}' could be instantiated with a different subtype of constraint '{2}'."), _0_and_1_operations_cannot_be_mixed_without_parentheses: diag(5076, ts.DiagnosticCategory.Error, "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076", "'{0}' and '{1}' operations cannot be mixed without parentheses."), Unknown_build_option_0_Did_you_mean_1: diag(5077, ts.DiagnosticCategory.Error, "Unknown_build_option_0_Did_you_mean_1_5077", "Unknown build option '{0}'. Did you mean '{1}'?"), @@ -8715,10 +8855,14 @@ var ts; Tuple_members_must_all_have_names_or_all_not_have_names: diag(5084, ts.DiagnosticCategory.Error, "Tuple_members_must_all_have_names_or_all_not_have_names_5084", "Tuple members must all have names or all not have names."), A_tuple_member_cannot_be_both_optional_and_rest: diag(5085, ts.DiagnosticCategory.Error, "A_tuple_member_cannot_be_both_optional_and_rest_5085", "A tuple member cannot be both optional and rest."), A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type: diag(5086, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086", "A labeled tuple element is declared as optional with a question mark after the name and before the colon, rather than after the type."), - A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a `...` before the name, rather than before the type."), + A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a '...' before the name, rather than before the type."), The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), + Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."), + The_root_value_of_a_0_file_must_be_an_object: diag(5092, ts.DiagnosticCategory.Error, "The_root_value_of_a_0_file_must_be_an_object_5092", "The root value of a '{0}' file must be an object."), + Compiler_option_0_may_only_be_used_with_build: diag(5093, ts.DiagnosticCategory.Error, "Compiler_option_0_may_only_be_used_with_build_5093", "Compiler option '--{0}' may only be used with '--build'."), + Compiler_option_0_may_not_be_used_with_build: diag(5094, ts.DiagnosticCategory.Error, "Compiler_option_0_may_not_be_used_with_build_5094", "Compiler option '--{0}' may not be used with '--build'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -8734,7 +8878,7 @@ var ts; Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), @@ -8929,9 +9073,9 @@ var ts; Emit_class_fields_with_Define_instead_of_Set: diag(6222, ts.DiagnosticCategory.Message, "Emit_class_fields_with_Define_instead_of_Set_6222", "Emit class fields with Define instead of Set."), Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."), Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."), - Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."), - Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling'."), - Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority'."), + Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."), + Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling'."), + Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority_FixedChunkSize: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority', 'FixedChunkSize'."), Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively: diag(6228, ts.DiagnosticCategory.Message, "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6228", "Synchronously call callbacks and update the state of directory watchers on platforms that don't support recursive watching natively."), Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3: diag(6229, ts.DiagnosticCategory.Error, "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229", "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'."), Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."), @@ -8942,7 +9086,11 @@ var ts; Disable_loading_referenced_projects: diag(6235, ts.DiagnosticCategory.Message, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."), Arguments_for_the_rest_parameter_0_were_not_provided: diag(6236, ts.DiagnosticCategory.Error, "Arguments_for_the_rest_parameter_0_were_not_provided_6236", "Arguments for the rest parameter '{0}' were not provided."), Generates_an_event_trace_and_a_list_of_types: diag(6237, ts.DiagnosticCategory.Message, "Generates_an_event_trace_and_a_list_of_types_6237", "Generates an event trace and a list of types."), - Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the `jsx` and `jsxs` factory functions from. eg, react"), + Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the 'jsx' and 'jsxs' factory functions from. eg, react"), + File_0_exists_according_to_earlier_cached_lookups: diag(6239, ts.DiagnosticCategory.Message, "File_0_exists_according_to_earlier_cached_lookups_6239", "File '{0}' exists according to earlier cached lookups."), + File_0_does_not_exist_according_to_earlier_cached_lookups: diag(6240, ts.DiagnosticCategory.Message, "File_0_does_not_exist_according_to_earlier_cached_lookups_6240", "File '{0}' does not exist according to earlier cached lookups."), + Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1: diag(6241, ts.DiagnosticCategory.Message, "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241", "Resolution for type reference directive '{0}' was found in cache from location '{1}'."), + Resolving_type_reference_directive_0_containing_file_1: diag(6242, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_6242", "======== Resolving type reference directive '{0}', containing file '{1}'. ========"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -8987,16 +9135,19 @@ var ts; Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382", "Skipping build of project '{0}' because its dependency '{1}' was not built"), Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383", "Project '{0}' can't be built because its dependency '{1}' was not built"), Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, ts.DiagnosticCategory.Message, "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384", "Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it."), - _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), + The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + Project_0_is_being_forcibly_rebuilt: diag(6388, ts.DiagnosticCategory.Message, "Project_0_is_being_forcibly_rebuilt_6388", "Project '{0}' is being forcibly rebuilt"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option: diag(6504, ts.DiagnosticCategory.Error, "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504", "File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?"), Print_names_of_files_and_the_reason_they_are_part_of_the_compilation: diag(6505, ts.DiagnosticCategory.Message, "Print_names_of_files_and_the_reason_they_are_part_of_the_compilation_6505", "Print names of files and the reason they are part of the compilation."), - Require_undeclared_properties_from_index_signatures_to_use_element_accesses: diag(6803, ts.DiagnosticCategory.Error, "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803", "Require undeclared properties from index signatures to use element accesses."), Include_undefined_in_index_signature_results: diag(6800, ts.DiagnosticCategory.Message, "Include_undefined_in_index_signature_results_6800", "Include 'undefined' in index signature results"), + Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier: diag(6801, ts.DiagnosticCategory.Message, "Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier_6801", "Ensure overriding members in derived classes are marked with an 'override' modifier."), + Require_undeclared_properties_from_index_signatures_to_use_element_accesses: diag(6802, ts.DiagnosticCategory.Message, "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6802", "Require undeclared properties from index signatures to use element accesses."), 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."), @@ -9029,7 +9180,7 @@ var ts; Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), - If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'"), The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), @@ -9069,7 +9220,7 @@ var ts; JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), - Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one '@augments' or '@extends' tag."), Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), @@ -9314,6 +9465,10 @@ var ts; Add_all_missing_function_declarations: diag(95157, ts.DiagnosticCategory.Message, "Add_all_missing_function_declarations_95157", "Add all missing function declarations"), Method_not_implemented: diag(95158, ts.DiagnosticCategory.Message, "Method_not_implemented_95158", "Method not implemented."), Function_not_implemented: diag(95159, ts.DiagnosticCategory.Message, "Function_not_implemented_95159", "Function not implemented."), + Add_override_modifier: diag(95160, ts.DiagnosticCategory.Message, "Add_override_modifier_95160", "Add 'override' modifier"), + Remove_override_modifier: diag(95161, ts.DiagnosticCategory.Message, "Remove_override_modifier_95161", "Remove 'override' modifier"), + Add_all_missing_override_modifiers: diag(95162, ts.DiagnosticCategory.Message, "Add_all_missing_override_modifiers_95162", "Add all missing 'override' modifiers"), + Remove_all_unnecessary_override_modifiers: diag(95163, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_override_modifiers_95163", "Remove all unnecessary 'override' modifiers"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -9328,8 +9483,6 @@ var ts; The_shadowing_declaration_of_0_is_defined_here: diag(18017, ts.DiagnosticCategory.Error, "The_shadowing_declaration_of_0_is_defined_here_18017", "The shadowing declaration of '{0}' is defined here"), The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here: diag(18018, ts.DiagnosticCategory.Error, "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018", "The declaration of '{0}' that you probably intended to use is defined here"), _0_modifier_cannot_be_used_with_a_private_identifier: diag(18019, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_private_identifier_18019", "'{0}' modifier cannot be used with a private identifier."), - A_method_cannot_be_named_with_a_private_identifier: diag(18022, ts.DiagnosticCategory.Error, "A_method_cannot_be_named_with_a_private_identifier_18022", "A method cannot be named with a private identifier."), - An_accessor_cannot_be_named_with_a_private_identifier: diag(18023, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_named_with_a_private_identifier_18023", "An accessor cannot be named with a private identifier."), An_enum_member_cannot_be_named_with_a_private_identifier: diag(18024, ts.DiagnosticCategory.Error, "An_enum_member_cannot_be_named_with_a_private_identifier_18024", "An enum member cannot be named with a private identifier."), can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), Compiler_reserves_name_0_when_emitting_private_identifier_downlevel: diag(18027, ts.DiagnosticCategory.Error, "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027", "Compiler reserves name '{0}' when emitting private identifier downlevel."), @@ -9341,6 +9494,7 @@ var ts; Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead: diag(18033, ts.DiagnosticCategory.Error, "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033", "Only numeric enums can have computed members, but this expression has type '{0}'. If you do not need exhaustiveness checks, consider using an object literal instead."), Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compiler_option_is_specified_e_g_Fragment: diag(18034, ts.DiagnosticCategory.Message, "Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compi_18034", "Specify the JSX fragment factory function to use when targeting 'react' JSX emit with 'jsxFactory' compiler option is specified, e.g. 'Fragment'."), Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(18035, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name_18035", "Invalid value for 'jsxFragmentFactory'. '{0}' is not a valid identifier or qualified-name."), + Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator: diag(18036, ts.DiagnosticCategory.Error, "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036", "Class decorators can't be used with static private identifier. Consider removing the experimental decorator."), }; })(ts || (ts = {})); var ts; @@ -9408,6 +9562,7 @@ var ts; _a.private = 120 /* PrivateKeyword */, _a.protected = 121 /* ProtectedKeyword */, _a.public = 122 /* PublicKeyword */, + _a.override = 156 /* OverrideKeyword */, _a.readonly = 142 /* ReadonlyKeyword */, _a.require = 143 /* RequireKeyword */, _a.global = 154 /* GlobalKeyword */, @@ -9434,7 +9589,7 @@ var ts; _a.yield = 124 /* YieldKeyword */, _a.async = 129 /* AsyncKeyword */, _a.await = 130 /* AwaitKeyword */, - _a.of = 156 /* OfKeyword */, + _a.of = 157 /* OfKeyword */, _a); var textToKeyword = new ts.Map(ts.getEntries(textToKeywordObj)); var textToToken = new ts.Map(ts.getEntries(__assign(__assign({}, textToKeywordObj), { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 29 /* LessThanToken */, ">": 31 /* GreaterThanToken */, "<=": 32 /* LessThanEqualsToken */, ">=": 33 /* GreaterThanEqualsToken */, "==": 34 /* EqualsEqualsToken */, "!=": 35 /* ExclamationEqualsToken */, "===": 36 /* EqualsEqualsEqualsToken */, "!==": 37 /* ExclamationEqualsEqualsToken */, "=>": 38 /* EqualsGreaterThanToken */, "+": 39 /* PlusToken */, "-": 40 /* MinusToken */, "**": 42 /* AsteriskAsteriskToken */, "*": 41 /* AsteriskToken */, "/": 43 /* SlashToken */, "%": 44 /* PercentToken */, "++": 45 /* PlusPlusToken */, "--": 46 /* MinusMinusToken */, "<<": 47 /* LessThanLessThanToken */, ">": 48 /* GreaterThanGreaterThanToken */, ">>>": 49 /* GreaterThanGreaterThanGreaterThanToken */, "&": 50 /* AmpersandToken */, "|": 51 /* BarToken */, "^": 52 /* CaretToken */, "!": 53 /* ExclamationToken */, "~": 54 /* TildeToken */, "&&": 55 /* AmpersandAmpersandToken */, "||": 56 /* BarBarToken */, "?": 57 /* QuestionToken */, "??": 60 /* QuestionQuestionToken */, "?.": 28 /* QuestionDotToken */, ":": 58 /* ColonToken */, "=": 62 /* EqualsToken */, "+=": 63 /* PlusEqualsToken */, "-=": 64 /* MinusEqualsToken */, "*=": 65 /* AsteriskEqualsToken */, "**=": 66 /* AsteriskAsteriskEqualsToken */, "/=": 67 /* SlashEqualsToken */, "%=": 68 /* PercentEqualsToken */, "<<=": 69 /* LessThanLessThanEqualsToken */, ">>=": 70 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 72 /* AmpersandEqualsToken */, "|=": 73 /* BarEqualsToken */, "^=": 77 /* CaretEqualsToken */, "||=": 74 /* BarBarEqualsToken */, "&&=": 75 /* AmpersandAmpersandEqualsToken */, "??=": 76 /* QuestionQuestionEqualsToken */, "@": 59 /* AtToken */, "`": 61 /* BacktickToken */ }))); @@ -9750,11 +9905,11 @@ var ts; } ts.couldStartTrivia = couldStartTrivia; /* @internal */ - function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { - if (stopAtComments === void 0) { stopAtComments = false; } + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments, inJSDoc) { if (ts.positionIsSynthesized(pos)) { return pos; } + var canConsumeStar = false; // Keep in sync with couldStartTrivia while (true) { var ch = text.charCodeAt(pos); @@ -9769,6 +9924,7 @@ var ts; if (stopAfterLineBreak) { return pos; } + canConsumeStar = !!inJSDoc; continue; case 9 /* tab */: case 11 /* verticalTab */: @@ -9788,6 +9944,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { @@ -9799,6 +9956,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } break; @@ -9808,12 +9966,21 @@ var ts; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos); + canConsumeStar = false; continue; } break; case 35 /* hash */: if (pos === 0 && isShebangTrivia(text, pos)) { pos = scanShebangTrivia(text, pos); + canConsumeStar = false; + continue; + } + break; + case 42 /* asterisk */: + if (canConsumeStar) { + pos++; + canConsumeStar = false; continue; } break; @@ -10118,6 +10285,7 @@ var ts; reScanJsxToken: reScanJsxToken, reScanLessThanToken: reScanLessThanToken, reScanQuestionToken: reScanQuestionToken, + reScanInvalidIdentifier: reScanInvalidIdentifier, scanJsxToken: scanJsxToken, scanJsDocToken: scanJsDocToken, scan: scan, @@ -11120,15 +11288,9 @@ var ts; } return token = 79 /* PrivateIdentifier */; default: - if (isIdentifierStart(ch, languageVersion)) { - pos += charSize(ch); - while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) - pos += charSize(ch); - tokenValue = text.substring(tokenPos, pos); - if (ch === 92 /* backslash */) { - tokenValue += scanIdentifierParts(); - } - return token = getIdentifierToken(); + var identifierKind = scanIdentifier(ch, languageVersion); + if (identifierKind) { + return token = identifierKind; } else if (isWhiteSpaceSingleLine(ch)) { pos += charSize(ch); @@ -11145,6 +11307,31 @@ var ts; } } } + function reScanInvalidIdentifier() { + ts.Debug.assert(token === 0 /* Unknown */, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'."); + pos = tokenPos = startPos; + tokenFlags = 0; + var ch = codePointAt(text, pos); + var identifierKind = scanIdentifier(ch, 99 /* ESNext */); + if (identifierKind) { + return token = identifierKind; + } + pos += charSize(ch); + return token; // Still `SyntaKind.Unknown` + } + function scanIdentifier(startCharacter, languageVersion) { + var ch = startCharacter; + if (isIdentifierStart(ch, languageVersion)) { + pos += charSize(ch); + while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) + pos += charSize(ch); + tokenValue = text.substring(tokenPos, pos); + if (ch === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return getIdentifierToken(); + } + } function reScanGreaterToken() { if (token === 31 /* GreaterThanToken */) { if (text.charCodeAt(pos) === 62 /* greaterThan */) { @@ -11257,9 +11444,10 @@ var ts; pos = tokenPos; return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true); } - function reScanJsxToken() { + function reScanJsxToken(allowMultilineJsxText) { + if (allowMultilineJsxText === void 0) { allowMultilineJsxText = true; } pos = tokenPos = startPos; - return token = scanJsxToken(); + return token = scanJsxToken(allowMultilineJsxText); } function reScanLessThanToken() { if (token === 47 /* LessThanLessThanToken */) { @@ -11273,7 +11461,8 @@ var ts; pos = tokenPos + 1; return token = 57 /* QuestionToken */; } - function scanJsxToken() { + function scanJsxToken(allowMultilineJsxText) { + if (allowMultilineJsxText === void 0) { allowMultilineJsxText = true; } startPos = tokenPos = pos; if (pos >= end) { return token = 1 /* EndOfFileToken */; @@ -11293,15 +11482,9 @@ var ts; } // First non-whitespace character on this line. var firstNonWhitespace = 0; - var lastNonWhitespace = -1; // These initial values are special because the first line is: // firstNonWhitespace = 0 to indicate that we want leading whitespace, while (pos < end) { - // We want to keep track of the last non-whitespace (but including - // newlines character for hitting the end of the JSX Text region) - if (!isWhiteSpaceSingleLine(char)) { - lastNonWhitespace = pos; - } char = text.charCodeAt(pos); if (char === 123 /* openBrace */) { break; @@ -11319,8 +11502,6 @@ var ts; if (char === 125 /* closeBrace */) { error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1); } - if (lastNonWhitespace > 0) - lastNonWhitespace++; // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces. // i.e (- : whitespace) //
---- @@ -11330,13 +11511,17 @@ var ts; if (isLineBreak(char) && firstNonWhitespace === 0) { firstNonWhitespace = -1; } + else if (!allowMultilineJsxText && isLineBreak(char) && firstNonWhitespace > 0) { + // Stop JsxText on each line during formatting. This allows the formatter to + // indent each line correctly. + break; + } else if (!isWhiteSpaceLike(char)) { firstNonWhitespace = pos; } pos++; } - var endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace; - tokenValue = text.substring(startPos, endPosition); + tokenValue = text.substring(startPos, pos); return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */; } // Scans a JSX identifier; these differ from normal identifiers in that @@ -11359,6 +11544,7 @@ var ts; tokenValue += ":"; pos++; namespaceSeparator = true; + token = 78 /* Identifier */; // swap from keyword kind to identifier kind continue; } var oldPos = pos; @@ -11615,6 +11801,8 @@ var ts; switch (options.target) { case 99 /* ESNext */: return "lib.esnext.full.d.ts"; + case 8 /* ES2021 */: + return "lib.es2021.full.d.ts"; case 7 /* ES2020 */: return "lib.es2020.full.d.ts"; case 6 /* ES2019 */: @@ -11833,9 +12021,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 159 /* TypeParameter */) { + if (d && d.kind === 160 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (isFunctionLike(current) || isClassLike(current) || current.kind === 253 /* InterfaceDeclaration */) { + if (isFunctionLike(current) || isClassLike(current) || current.kind === 254 /* InterfaceDeclaration */) { return current; } } @@ -11843,7 +12031,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node, parent) { - return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 166 /* Constructor */; + return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) && parent.kind === 167 /* Constructor */; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -11873,14 +12061,14 @@ var ts; node = walkUpBindingElementsAndPatterns(node); } var flags = getFlags(node); - if (node.kind === 249 /* VariableDeclaration */) { + if (node.kind === 250 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 250 /* VariableDeclarationList */) { + if (node && node.kind === 251 /* VariableDeclarationList */) { flags |= getFlags(node); node = node.parent; } - if (node && node.kind === 232 /* VariableStatement */) { + if (node && node.kind === 233 /* VariableStatement */) { flags |= getFlags(node); } return flags; @@ -11898,19 +12086,22 @@ var ts; // nodes like variable declarations and binding elements can returned a view of their flags // that includes the modifiers from their container. i.e. flags like export/declare aren't // stored on the variable declaration directly, but on the containing variable statement - // (if it has one). Similarly, flags for let/const are store on the variable declaration + // (if it has one). Similarly, flags for let/const are stored on the variable declaration // list. By calling this function, all those flags are combined so that the client can treat // the node as if it actually had those flags. function getCombinedNodeFlags(node) { return getCombinedFlags(node, function (n) { return n.flags; }); } ts.getCombinedNodeFlags = getCombinedNodeFlags; + /* @internal */ + ts.supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; /** * Checks to see if the locale is in the appropriate format, * and if it is, attempts to set the appropriate language. */ function validateLocaleAndSetLanguage(locale, sys, errors) { - var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + var lowerCaseLocale = locale.toLowerCase(); + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale); if (!matchResult) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); @@ -11921,7 +12112,7 @@ var ts; var territory = matchResult[3]; // First try the entire locale, then fall back to just language if that's all we have. // Either ways do not fail, and fallback to the English diagnostic strings. - if (!trySetLanguageAndTerritory(language, territory, errors)) { + if (ts.contains(ts.supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) { trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); } // Set the UI locale for string collation @@ -12028,7 +12219,7 @@ var ts; } ts.idText = idText; function symbolName(symbol) { - if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) { + if (symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) { return idText(symbol.valueDeclaration.name); } return unescapeLeadingUnderscores(symbol.escapedName); @@ -12050,30 +12241,30 @@ var ts; } // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } break; - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: var expr = hostNode.expression; - if (expr.kind === 216 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) { + if (expr.kind === 217 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) { expr = expr.left; } switch (expr.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return expr.name; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; } } break; - case 207 /* ParenthesizedExpression */: { + case 208 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } - case 245 /* LabeledStatement */: { + case 246 /* LabeledStatement */: { if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } @@ -12110,16 +12301,16 @@ var ts; switch (declaration.kind) { case 78 /* Identifier */: return declaration; - case 333 /* JSDocPropertyTag */: - case 326 /* JSDocParameterTag */: { + case 337 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: { var name = declaration.name; - if (name.kind === 157 /* QualifiedName */) { + if (name.kind === 158 /* QualifiedName */) { return name.right; } break; } - case 203 /* CallExpression */: - case 216 /* BinaryExpression */: { + case 204 /* CallExpression */: + case 217 /* BinaryExpression */: { var expr_1 = declaration; switch (ts.getAssignmentDeclarationKind(expr_1)) { case 1 /* ExportsProperty */: @@ -12135,15 +12326,15 @@ var ts; return undefined; } } - case 331 /* JSDocTypedefTag */: + case 335 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); - case 325 /* JSDocEnumTag */: + case 329 /* JSDocEnumTag */: return nameForNamelessJSDocTypedef(declaration); - case 266 /* ExportAssignment */: { + case 267 /* ExportAssignment */: { var expression = declaration.expression; return ts.isIdentifier(expression) ? expression : undefined; } - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: var expr = declaration; if (ts.isBindableStaticElementAccessExpression(expr)) { return expr.argumentExpression; @@ -12156,7 +12347,7 @@ var ts; if (declaration === undefined) return undefined; return getNonAssignedNameOfDeclaration(declaration) || - (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + (ts.isFunctionExpression(declaration) || ts.isArrowFunction(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); } ts.getNameOfDeclaration = getNameOfDeclaration; /*@internal*/ @@ -12309,6 +12500,10 @@ var ts; return getFirstJSDocTag(node, ts.isJSDocReadonlyTag, /*noCache*/ true); } ts.getJSDocReadonlyTagNoCache = getJSDocReadonlyTagNoCache; + function getJSDocOverrideTagNoCache(node) { + return getFirstJSDocTag(node, ts.isJSDocOverrideTag, /*noCache*/ true); + } + ts.getJSDocOverrideTagNoCache = getJSDocOverrideTagNoCache; /** Gets the JSDoc deprecated tag for the node if present */ function getJSDocDeprecatedTag(node) { return getFirstJSDocTag(node, ts.isJSDocDeprecatedTag); @@ -12429,6 +12624,14 @@ var ts; return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + /** Gets the text of a jsdoc comment, flattening links to their text. */ + function getTextOfJSDocComment(comment) { + return typeof comment === "string" ? comment + : comment === null || comment === void 0 ? void 0 : comment.map(function (c) { + return c.kind === 313 /* JSDocText */ ? c.text : "{@link " + (c.name ? ts.entityNameToString(c.name) + " " : "") + c.text + "}"; + }).join(""); + } + ts.getTextOfJSDocComment = getTextOfJSDocComment; /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. @@ -12438,7 +12641,7 @@ var ts; return ts.emptyArray; } if (ts.isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 311 /* JSDocComment */); + ts.Debug.assert(node.parent.kind === 312 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } if (node.typeParameters) { @@ -12464,13 +12667,13 @@ var ts; } ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter; // #region - function isIdentifierOrPrivateIdentifier(node) { + function isMemberName(node) { return node.kind === 78 /* Identifier */ || node.kind === 79 /* PrivateIdentifier */; } - ts.isIdentifierOrPrivateIdentifier = isIdentifierOrPrivateIdentifier; + ts.isMemberName = isMemberName; /* @internal */ function isGetOrSetAccessorDeclaration(node) { - return node.kind === 168 /* SetAccessor */ || node.kind === 167 /* GetAccessor */; + return node.kind === 169 /* SetAccessor */ || node.kind === 168 /* GetAccessor */; } ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; function isPropertyAccessChain(node) { @@ -12488,10 +12691,10 @@ var ts; function isOptionalChain(node) { var kind = node.kind; return !!(node.flags & 32 /* OptionalChain */) && - (kind === 201 /* PropertyAccessExpression */ - || kind === 202 /* ElementAccessExpression */ - || kind === 203 /* CallExpression */ - || kind === 225 /* NonNullExpression */); + (kind === 202 /* PropertyAccessExpression */ + || kind === 203 /* ElementAccessExpression */ + || kind === 204 /* CallExpression */ + || kind === 226 /* NonNullExpression */); } ts.isOptionalChain = isOptionalChain; /* @internal */ @@ -12526,7 +12729,7 @@ var ts; } ts.isOutermostOptionalChain = isOutermostOptionalChain; function isNullishCoalesce(node) { - return node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */; + return node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */; } ts.isNullishCoalesce = isNullishCoalesce; function isConstTypeReference(node) { @@ -12543,17 +12746,17 @@ var ts; } ts.isNonNullChain = isNonNullChain; function isBreakOrContinueStatement(node) { - return node.kind === 241 /* BreakStatement */ || node.kind === 240 /* ContinueStatement */; + return node.kind === 242 /* BreakStatement */ || node.kind === 241 /* ContinueStatement */; } ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isNamedExportBindings(node) { - return node.kind === 269 /* NamespaceExport */ || node.kind === 268 /* NamedExports */; + return node.kind === 270 /* NamespaceExport */ || node.kind === 269 /* NamedExports */; } ts.isNamedExportBindings = isNamedExportBindings; function isUnparsedTextLike(node) { switch (node.kind) { - case 294 /* UnparsedText */: - case 295 /* UnparsedInternalText */: + case 295 /* UnparsedText */: + case 296 /* UnparsedInternalText */: return true; default: return false; @@ -12562,12 +12765,12 @@ var ts; ts.isUnparsedTextLike = isUnparsedTextLike; function isUnparsedNode(node) { return isUnparsedTextLike(node) || - node.kind === 292 /* UnparsedPrologue */ || - node.kind === 296 /* UnparsedSyntheticReference */; + node.kind === 293 /* UnparsedPrologue */ || + node.kind === 297 /* UnparsedSyntheticReference */; } ts.isUnparsedNode = isUnparsedNode; function isJSDocPropertyLikeTag(node) { - return node.kind === 333 /* JSDocPropertyTag */ || node.kind === 326 /* JSDocParameterTag */; + return node.kind === 337 /* JSDocPropertyTag */ || node.kind === 330 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; // #endregion @@ -12583,16 +12786,25 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 157 /* FirstNode */; + return kind >= 158 /* FirstNode */; } ts.isNodeKind = isNodeKind; + /** + * True if kind is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + function isTokenKind(kind) { + return kind >= 0 /* FirstToken */ && kind <= 157 /* LastToken */; + } + ts.isTokenKind = isTokenKind; /** * True if node is of some token syntax kind. * For example, this is true for an IfKeyword but not for an IfStatement. * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. */ function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 156 /* LastToken */; + return isTokenKind(n.kind); } ts.isToken = isToken; // Node Arrays @@ -12633,13 +12845,13 @@ var ts; ts.isImportOrExportSpecifier = isImportOrExportSpecifier; function isTypeOnlyImportOrExportDeclaration(node) { switch (node.kind) { - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return node.parent.parent.isTypeOnly; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return node.parent.isTypeOnly; - case 262 /* ImportClause */: - case 260 /* ImportEqualsDeclaration */: + case 263 /* ImportClause */: + case 261 /* ImportEqualsDeclaration */: return node.isTypeOnly; default: return false; @@ -12658,10 +12870,10 @@ var ts; ts.isGeneratedIdentifier = isGeneratedIdentifier; // Private Identifiers /*@internal*/ - function isPrivateIdentifierPropertyDeclaration(node) { - return ts.isPropertyDeclaration(node) && ts.isPrivateIdentifier(node.name); + function isPrivateIdentifierClassElementDeclaration(node) { + return (ts.isPropertyDeclaration(node) || isMethodOrAccessor(node)) && ts.isPrivateIdentifier(node.name); } - ts.isPrivateIdentifierPropertyDeclaration = isPrivateIdentifierPropertyDeclaration; + ts.isPrivateIdentifierClassElementDeclaration = isPrivateIdentifierClassElementDeclaration; /*@internal*/ function isPrivateIdentifierPropertyAccessExpression(node) { return ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name); @@ -12682,6 +12894,7 @@ var ts; case 121 /* ProtectedKeyword */: case 142 /* ReadonlyKeyword */: case 123 /* StaticKeyword */: + case 156 /* OverrideKeyword */: return true; } return false; @@ -12689,12 +12902,12 @@ var ts; ts.isModifierKind = isModifierKind; /* @internal */ function isParameterPropertyModifier(kind) { - return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + return !!(ts.modifierToFlag(kind) & 16476 /* ParameterPropertyModifier */); } ts.isParameterPropertyModifier = isParameterPropertyModifier; /* @internal */ function isClassMemberModifier(idToken) { - return isParameterPropertyModifier(idToken) || idToken === 123 /* StaticKeyword */; + return isParameterPropertyModifier(idToken) || idToken === 123 /* StaticKeyword */ || idToken === 156 /* OverrideKeyword */; } ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { @@ -12703,7 +12916,7 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 157 /* QualifiedName */ + return kind === 158 /* QualifiedName */ || kind === 78 /* Identifier */; } ts.isEntityName = isEntityName; @@ -12713,19 +12926,19 @@ var ts; || kind === 79 /* PrivateIdentifier */ || kind === 10 /* StringLiteral */ || kind === 8 /* NumericLiteral */ - || kind === 158 /* ComputedPropertyName */; + || kind === 159 /* ComputedPropertyName */; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; return kind === 78 /* Identifier */ - || kind === 196 /* ObjectBindingPattern */ - || kind === 197 /* ArrayBindingPattern */; + || kind === 197 /* ObjectBindingPattern */ + || kind === 198 /* ArrayBindingPattern */; } ts.isBindingName = isBindingName; // Functions function isFunctionLike(node) { - return node && isFunctionLikeKind(node.kind); + return !!node && isFunctionLikeKind(node.kind); } ts.isFunctionLike = isFunctionLike; /* @internal */ @@ -12735,13 +12948,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; default: return false; @@ -12750,14 +12963,14 @@ var ts; /* @internal */ function isFunctionLikeKind(kind) { switch (kind) { - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 313 /* JSDocSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 174 /* FunctionType */: - case 308 /* JSDocFunctionType */: - case 175 /* ConstructorType */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 315 /* JSDocSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 175 /* FunctionType */: + case 309 /* JSDocFunctionType */: + case 176 /* ConstructorType */: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -12772,29 +12985,29 @@ var ts; // Classes function isClassElement(node) { var kind = node.kind; - return kind === 166 /* Constructor */ - || kind === 163 /* PropertyDeclaration */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 171 /* IndexSignature */ - || kind === 229 /* SemicolonClassElement */; + return kind === 167 /* Constructor */ + || kind === 164 /* PropertyDeclaration */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 172 /* IndexSignature */ + || kind === 230 /* SemicolonClassElement */; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */); + return node && (node.kind === 253 /* ClassDeclaration */ || node.kind === 222 /* ClassExpression */); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 167 /* GetAccessor */ || node.kind === 168 /* SetAccessor */); + return node && (node.kind === 168 /* GetAccessor */ || node.kind === 169 /* SetAccessor */); } ts.isAccessor = isAccessor; /* @internal */ function isMethodOrAccessor(node) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return true; default: return false; @@ -12804,11 +13017,11 @@ var ts; // Type members function isTypeElement(node) { var kind = node.kind; - return kind === 170 /* ConstructSignature */ - || kind === 169 /* CallSignature */ - || kind === 162 /* PropertySignature */ - || kind === 164 /* MethodSignature */ - || kind === 171 /* IndexSignature */; + return kind === 171 /* ConstructSignature */ + || kind === 170 /* CallSignature */ + || kind === 163 /* PropertySignature */ + || kind === 165 /* MethodSignature */ + || kind === 172 /* IndexSignature */; } ts.isTypeElement = isTypeElement; function isClassOrTypeElement(node) { @@ -12817,12 +13030,12 @@ var ts; ts.isClassOrTypeElement = isClassOrTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 288 /* PropertyAssignment */ - || kind === 289 /* ShorthandPropertyAssignment */ - || kind === 290 /* SpreadAssignment */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 289 /* PropertyAssignment */ + || kind === 290 /* ShorthandPropertyAssignment */ + || kind === 291 /* SpreadAssignment */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; // Type @@ -12837,8 +13050,8 @@ var ts; ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return true; } return false; @@ -12849,8 +13062,8 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 197 /* ArrayBindingPattern */ - || kind === 196 /* ObjectBindingPattern */; + return kind === 198 /* ArrayBindingPattern */ + || kind === 197 /* ObjectBindingPattern */; } return false; } @@ -12858,15 +13071,15 @@ var ts; /* @internal */ function isAssignmentPattern(node) { var kind = node.kind; - return kind === 199 /* ArrayLiteralExpression */ - || kind === 200 /* ObjectLiteralExpression */; + return kind === 200 /* ArrayLiteralExpression */ + || kind === 201 /* ObjectLiteralExpression */; } ts.isAssignmentPattern = isAssignmentPattern; /* @internal */ function isArrayBindingElement(node) { var kind = node.kind; - return kind === 198 /* BindingElement */ - || kind === 222 /* OmittedExpression */; + return kind === 199 /* BindingElement */ + || kind === 223 /* OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; /** @@ -12875,9 +13088,9 @@ var ts; /* @internal */ function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: return true; } return false; @@ -12898,8 +13111,8 @@ var ts; /* @internal */ function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 196 /* ObjectBindingPattern */: - case 200 /* ObjectLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 201 /* ObjectLiteralExpression */: return true; } return false; @@ -12911,8 +13124,8 @@ var ts; /* @internal */ function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 197 /* ArrayBindingPattern */: - case 199 /* ArrayLiteralExpression */: + case 198 /* ArrayBindingPattern */: + case 200 /* ArrayLiteralExpression */: return true; } return false; @@ -12921,26 +13134,26 @@ var ts; /* @internal */ function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { var kind = node.kind; - return kind === 201 /* PropertyAccessExpression */ - || kind === 157 /* QualifiedName */ - || kind === 195 /* ImportType */; + return kind === 202 /* PropertyAccessExpression */ + || kind === 158 /* QualifiedName */ + || kind === 196 /* ImportType */; } ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; // Expression function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 201 /* PropertyAccessExpression */ - || kind === 157 /* QualifiedName */; + return kind === 202 /* PropertyAccessExpression */ + || kind === 158 /* QualifiedName */; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 205 /* TaggedTemplateExpression */: - case 161 /* Decorator */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 206 /* TaggedTemplateExpression */: + case 162 /* Decorator */: return true; default: return false; @@ -12948,12 +13161,12 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 203 /* CallExpression */ || node.kind === 204 /* NewExpression */; + return node.kind === 204 /* CallExpression */ || node.kind === 205 /* NewExpression */; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 218 /* TemplateExpression */ + return kind === 219 /* TemplateExpression */ || kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; @@ -12964,33 +13177,33 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: - case 204 /* NewExpression */: - case 203 /* CallExpression */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: - case 205 /* TaggedTemplateExpression */: - case 199 /* ArrayLiteralExpression */: - case 207 /* ParenthesizedExpression */: - case 200 /* ObjectLiteralExpression */: - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 205 /* NewExpression */: + case 204 /* CallExpression */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: + case 206 /* TaggedTemplateExpression */: + case 200 /* ArrayLiteralExpression */: + case 208 /* ParenthesizedExpression */: + case 201 /* ObjectLiteralExpression */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: case 78 /* Identifier */: case 13 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: case 9 /* BigIntLiteral */: case 10 /* StringLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: case 94 /* FalseKeyword */: case 103 /* NullKeyword */: case 107 /* ThisKeyword */: case 109 /* TrueKeyword */: case 105 /* SuperKeyword */: - case 225 /* NonNullExpression */: - case 226 /* MetaProperty */: + case 226 /* NonNullExpression */: + case 227 /* MetaProperty */: case 99 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression return true; default: @@ -13004,13 +13217,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: - case 210 /* DeleteExpression */: - case 211 /* TypeOfExpression */: - case 212 /* VoidExpression */: - case 213 /* AwaitExpression */: - case 206 /* TypeAssertionExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 211 /* DeleteExpression */: + case 212 /* TypeOfExpression */: + case 213 /* VoidExpression */: + case 214 /* AwaitExpression */: + case 207 /* TypeAssertionExpression */: return true; default: return isLeftHandSideExpressionKind(kind); @@ -13019,9 +13232,9 @@ var ts; /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return true; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */; default: @@ -13040,15 +13253,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 217 /* ConditionalExpression */: - case 219 /* YieldExpression */: - case 209 /* ArrowFunction */: - case 216 /* BinaryExpression */: - case 220 /* SpreadElement */: - case 224 /* AsExpression */: - case 222 /* OmittedExpression */: - case 337 /* CommaListExpression */: - case 336 /* PartiallyEmittedExpression */: + case 218 /* ConditionalExpression */: + case 220 /* YieldExpression */: + case 210 /* ArrowFunction */: + case 217 /* BinaryExpression */: + case 221 /* SpreadElement */: + case 225 /* AsExpression */: + case 223 /* OmittedExpression */: + case 341 /* CommaListExpression */: + case 340 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -13056,8 +13269,8 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 206 /* TypeAssertionExpression */ - || kind === 224 /* AsExpression */; + return kind === 207 /* TypeAssertionExpression */ + || kind === 225 /* AsExpression */; } ts.isAssertionExpression = isAssertionExpression; /* @internal */ @@ -13068,13 +13281,13 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return true; - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -13103,7 +13316,7 @@ var ts; ts.isExternalModuleIndicator = isExternalModuleIndicator; /* @internal */ function isForInOrOfStatement(node) { - return node.kind === 238 /* ForInStatement */ || node.kind === 239 /* ForOfStatement */; + return node.kind === 239 /* ForInStatement */ || node.kind === 240 /* ForOfStatement */; } ts.isForInOrOfStatement = isForInOrOfStatement; // Element @@ -13127,114 +13340,114 @@ var ts; /* @internal */ function isModuleBody(node) { var kind = node.kind; - return kind === 257 /* ModuleBlock */ - || kind === 256 /* ModuleDeclaration */ + return kind === 258 /* ModuleBlock */ + || kind === 257 /* ModuleDeclaration */ || kind === 78 /* Identifier */; } ts.isModuleBody = isModuleBody; /* @internal */ function isNamespaceBody(node) { var kind = node.kind; - return kind === 257 /* ModuleBlock */ - || kind === 256 /* ModuleDeclaration */; + return kind === 258 /* ModuleBlock */ + || kind === 257 /* ModuleDeclaration */; } ts.isNamespaceBody = isNamespaceBody; /* @internal */ function isJSDocNamespaceBody(node) { var kind = node.kind; return kind === 78 /* Identifier */ - || kind === 256 /* ModuleDeclaration */; + || kind === 257 /* ModuleDeclaration */; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; /* @internal */ function isNamedImportBindings(node) { var kind = node.kind; - return kind === 264 /* NamedImports */ - || kind === 263 /* NamespaceImport */; + return kind === 265 /* NamedImports */ + || kind === 264 /* NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; /* @internal */ function isModuleOrEnumDeclaration(node) { - return node.kind === 256 /* ModuleDeclaration */ || node.kind === 255 /* EnumDeclaration */; + return node.kind === 257 /* ModuleDeclaration */ || node.kind === 256 /* EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 209 /* ArrowFunction */ - || kind === 198 /* BindingElement */ - || kind === 252 /* ClassDeclaration */ - || kind === 221 /* ClassExpression */ - || kind === 166 /* Constructor */ - || kind === 255 /* EnumDeclaration */ - || kind === 291 /* EnumMember */ - || kind === 270 /* ExportSpecifier */ - || kind === 251 /* FunctionDeclaration */ - || kind === 208 /* FunctionExpression */ - || kind === 167 /* GetAccessor */ - || kind === 262 /* ImportClause */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 265 /* ImportSpecifier */ - || kind === 253 /* InterfaceDeclaration */ - || kind === 280 /* JsxAttribute */ - || kind === 165 /* MethodDeclaration */ - || kind === 164 /* MethodSignature */ - || kind === 256 /* ModuleDeclaration */ - || kind === 259 /* NamespaceExportDeclaration */ - || kind === 263 /* NamespaceImport */ - || kind === 269 /* NamespaceExport */ - || kind === 160 /* Parameter */ - || kind === 288 /* PropertyAssignment */ - || kind === 163 /* PropertyDeclaration */ - || kind === 162 /* PropertySignature */ - || kind === 168 /* SetAccessor */ - || kind === 289 /* ShorthandPropertyAssignment */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 159 /* TypeParameter */ - || kind === 249 /* VariableDeclaration */ - || kind === 331 /* JSDocTypedefTag */ - || kind === 324 /* JSDocCallbackTag */ - || kind === 333 /* JSDocPropertyTag */; + return kind === 210 /* ArrowFunction */ + || kind === 199 /* BindingElement */ + || kind === 253 /* ClassDeclaration */ + || kind === 222 /* ClassExpression */ + || kind === 167 /* Constructor */ + || kind === 256 /* EnumDeclaration */ + || kind === 292 /* EnumMember */ + || kind === 271 /* ExportSpecifier */ + || kind === 252 /* FunctionDeclaration */ + || kind === 209 /* FunctionExpression */ + || kind === 168 /* GetAccessor */ + || kind === 263 /* ImportClause */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 266 /* ImportSpecifier */ + || kind === 254 /* InterfaceDeclaration */ + || kind === 281 /* JsxAttribute */ + || kind === 166 /* MethodDeclaration */ + || kind === 165 /* MethodSignature */ + || kind === 257 /* ModuleDeclaration */ + || kind === 260 /* NamespaceExportDeclaration */ + || kind === 264 /* NamespaceImport */ + || kind === 270 /* NamespaceExport */ + || kind === 161 /* Parameter */ + || kind === 289 /* PropertyAssignment */ + || kind === 164 /* PropertyDeclaration */ + || kind === 163 /* PropertySignature */ + || kind === 169 /* SetAccessor */ + || kind === 290 /* ShorthandPropertyAssignment */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 160 /* TypeParameter */ + || kind === 250 /* VariableDeclaration */ + || kind === 335 /* JSDocTypedefTag */ + || kind === 328 /* JSDocCallbackTag */ + || kind === 337 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { - return kind === 251 /* FunctionDeclaration */ - || kind === 271 /* MissingDeclaration */ - || kind === 252 /* ClassDeclaration */ - || kind === 253 /* InterfaceDeclaration */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 255 /* EnumDeclaration */ - || kind === 256 /* ModuleDeclaration */ - || kind === 261 /* ImportDeclaration */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 267 /* ExportDeclaration */ - || kind === 266 /* ExportAssignment */ - || kind === 259 /* NamespaceExportDeclaration */; + return kind === 252 /* FunctionDeclaration */ + || kind === 272 /* MissingDeclaration */ + || kind === 253 /* ClassDeclaration */ + || kind === 254 /* InterfaceDeclaration */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 256 /* EnumDeclaration */ + || kind === 257 /* ModuleDeclaration */ + || kind === 262 /* ImportDeclaration */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 268 /* ExportDeclaration */ + || kind === 267 /* ExportAssignment */ + || kind === 260 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 241 /* BreakStatement */ - || kind === 240 /* ContinueStatement */ - || kind === 248 /* DebuggerStatement */ - || kind === 235 /* DoStatement */ - || kind === 233 /* ExpressionStatement */ - || kind === 231 /* EmptyStatement */ - || kind === 238 /* ForInStatement */ - || kind === 239 /* ForOfStatement */ - || kind === 237 /* ForStatement */ - || kind === 234 /* IfStatement */ - || kind === 245 /* LabeledStatement */ - || kind === 242 /* ReturnStatement */ - || kind === 244 /* SwitchStatement */ - || kind === 246 /* ThrowStatement */ - || kind === 247 /* TryStatement */ - || kind === 232 /* VariableStatement */ - || kind === 236 /* WhileStatement */ - || kind === 243 /* WithStatement */ - || kind === 335 /* NotEmittedStatement */ - || kind === 339 /* EndOfDeclarationMarker */ - || kind === 338 /* MergeDeclarationMarker */; + return kind === 242 /* BreakStatement */ + || kind === 241 /* ContinueStatement */ + || kind === 249 /* DebuggerStatement */ + || kind === 236 /* DoStatement */ + || kind === 234 /* ExpressionStatement */ + || kind === 232 /* EmptyStatement */ + || kind === 239 /* ForInStatement */ + || kind === 240 /* ForOfStatement */ + || kind === 238 /* ForStatement */ + || kind === 235 /* IfStatement */ + || kind === 246 /* LabeledStatement */ + || kind === 243 /* ReturnStatement */ + || kind === 245 /* SwitchStatement */ + || kind === 247 /* ThrowStatement */ + || kind === 248 /* TryStatement */ + || kind === 233 /* VariableStatement */ + || kind === 237 /* WhileStatement */ + || kind === 244 /* WithStatement */ + || kind === 339 /* NotEmittedStatement */ + || kind === 343 /* EndOfDeclarationMarker */ + || kind === 342 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { - if (node.kind === 159 /* TypeParameter */) { - return (node.parent && node.parent.kind !== 330 /* JSDocTemplateTag */) || ts.isInJSFile(node); + if (node.kind === 160 /* TypeParameter */) { + return (node.parent && node.parent.kind !== 334 /* JSDocTemplateTag */) || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -13261,10 +13474,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 230 /* Block */) + if (node.kind !== 231 /* Block */) return false; if (node.parent !== undefined) { - if (node.parent.kind === 247 /* TryStatement */ || node.parent.kind === 287 /* CatchClause */) { + if (node.parent.kind === 248 /* TryStatement */ || node.parent.kind === 288 /* CatchClause */) { return false; } } @@ -13278,15 +13491,15 @@ var ts; var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) - || kind === 230 /* Block */; + || kind === 231 /* Block */; } ts.isStatementOrBlock = isStatementOrBlock; // Module references /* @internal */ function isModuleReference(node) { var kind = node.kind; - return kind === 272 /* ExternalModuleReference */ - || kind === 157 /* QualifiedName */ + return kind === 273 /* ExternalModuleReference */ + || kind === 158 /* QualifiedName */ || kind === 78 /* Identifier */; } ts.isModuleReference = isModuleReference; @@ -13296,70 +13509,76 @@ var ts; var kind = node.kind; return kind === 107 /* ThisKeyword */ || kind === 78 /* Identifier */ - || kind === 201 /* PropertyAccessExpression */; + || kind === 202 /* PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; /* @internal */ function isJsxChild(node) { var kind = node.kind; - return kind === 273 /* JsxElement */ - || kind === 283 /* JsxExpression */ - || kind === 274 /* JsxSelfClosingElement */ + return kind === 274 /* JsxElement */ + || kind === 284 /* JsxExpression */ + || kind === 275 /* JsxSelfClosingElement */ || kind === 11 /* JsxText */ - || kind === 277 /* JsxFragment */; + || kind === 278 /* JsxFragment */; } ts.isJsxChild = isJsxChild; /* @internal */ function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 280 /* JsxAttribute */ - || kind === 282 /* JsxSpreadAttribute */; + return kind === 281 /* JsxAttribute */ + || kind === 283 /* JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; /* @internal */ function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 10 /* StringLiteral */ - || kind === 283 /* JsxExpression */; + || kind === 284 /* JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 275 /* JsxOpeningElement */ - || kind === 274 /* JsxSelfClosingElement */; + return kind === 276 /* JsxOpeningElement */ + || kind === 275 /* JsxSelfClosingElement */; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 284 /* CaseClause */ - || kind === 285 /* DefaultClause */; + return kind === 285 /* CaseClause */ + || kind === 286 /* DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; // JSDoc /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 301 /* FirstJSDocNode */ && node.kind <= 333 /* LastJSDocNode */; + return node.kind >= 302 /* FirstJSDocNode */ && node.kind <= 337 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 311 /* JSDocComment */ || node.kind === 310 /* JSDocNamepathType */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + return node.kind === 312 /* JSDocComment */ + || node.kind === 311 /* JSDocNamepathType */ + || node.kind === 313 /* JSDocText */ + || node.kind === 316 /* JSDocLink */ + || isJSDocTag(node) + || ts.isJSDocTypeLiteral(node) + || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 314 /* FirstJSDocTagNode */ && node.kind <= 333 /* LastJSDocTagNode */; + return node.kind >= 317 /* FirstJSDocTagNode */ && node.kind <= 337 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { - return node.kind === 168 /* SetAccessor */; + return node.kind === 169 /* SetAccessor */; } ts.isSetAccessor = isSetAccessor; function isGetAccessor(node) { - return node.kind === 167 /* GetAccessor */; + return node.kind === 168 /* GetAccessor */; } ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ @@ -13385,13 +13604,13 @@ var ts; /** True if has initializer node attached to it. */ function hasOnlyExpressionInitializer(node) { switch (node.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: - case 162 /* PropertySignature */: - case 163 /* PropertyDeclaration */: - case 288 /* PropertyAssignment */: - case 291 /* EnumMember */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: + case 163 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 289 /* PropertyAssignment */: + case 292 /* EnumMember */: return true; default: return false; @@ -13399,12 +13618,12 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - return node.kind === 280 /* JsxAttribute */ || node.kind === 282 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); + return node.kind === 281 /* JsxAttribute */ || node.kind === 283 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; /* @internal */ function isTypeReferenceType(node) { - return node.kind === 173 /* TypeReference */ || node.kind === 223 /* ExpressionWithTypeArguments */; + return node.kind === 174 /* TypeReference */ || node.kind === 224 /* ExpressionWithTypeArguments */; } ts.isTypeReferenceType = isTypeReferenceType; var MAX_SMI_X86 = 1073741823; @@ -13643,7 +13862,9 @@ var ts; } ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + return oldResolution.resolvedFileName === newResolution.resolvedFileName + && oldResolution.primary === newResolution.primary + && oldResolution.originalPath === newResolution.originalPath; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { @@ -13685,7 +13906,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 297 /* SourceFile */) { + while (node && node.kind !== 298 /* SourceFile */) { node = node.parent; } return node; @@ -13693,11 +13914,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 230 /* Block */: - case 258 /* CaseBlock */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 231 /* Block */: + case 259 /* CaseBlock */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: return true; } return false; @@ -13893,10 +14114,12 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 334 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 338 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, + /*stopAfterLineBreak*/ false, + /*stopAtComments*/ false, isInJSDoc(node)); } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { @@ -14015,9 +14238,11 @@ var ts; DataView: ["setBigInt64", "setBigUint64", "getBigInt64", "getBigUint64"], RelativeTimeFormat: ["format", "formatToParts", "resolvedOptions"] }, - esnext: { + es2021: { PromiseConstructor: ["any"], - String: ["replaceAll"], + String: ["replaceAll"] + }, + esnext: { NumberFormat: ["formatToParts"] } }; @@ -14110,7 +14335,7 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 249 /* VariableDeclaration */ && node.parent.kind === 287 /* CatchClause */; + return node.kind === 250 /* VariableDeclaration */ && node.parent.kind === 288 /* CatchClause */; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { @@ -14142,11 +14367,11 @@ var ts; ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. - return node && node.kind === 256 /* ModuleDeclaration */ && (!node.body); + return !!node && node.kind === 257 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 297 /* SourceFile */ || - node.kind === 256 /* ModuleDeclaration */ || + return node.kind === 298 /* SourceFile */ || + node.kind === 257 /* ModuleDeclaration */ || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -14163,16 +14388,17 @@ var ts; // - defined in the top level scope and source file is an external module // - defined inside ambient module declaration located in the top level scope and source file not an external module switch (node.parent.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: return ts.isExternalModule(node.parent); - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } ts.isModuleAugmentationExternal = isModuleAugmentationExternal; function getNonAugmentationDeclaration(symbol) { - return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); + var _a; + return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); } ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration; function isEffectiveExternalModule(node, compilerOptions) { @@ -14218,22 +14444,22 @@ var ts; ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile; function isBlockScope(node, parentNode) { switch (node.kind) { - case 297 /* SourceFile */: - case 258 /* CaseBlock */: - case 287 /* CatchClause */: - case 256 /* ModuleDeclaration */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 298 /* SourceFile */: + case 259 /* CaseBlock */: + case 288 /* CatchClause */: + case 257 /* ModuleDeclaration */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; - case 230 /* Block */: + case 231 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block return !ts.isFunctionLike(parentNode); @@ -14243,9 +14469,9 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: - case 313 /* JSDocSignature */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: + case 315 /* JSDocSignature */: return true; default: ts.assertType(node); @@ -14255,25 +14481,25 @@ var ts; ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 164 /* MethodSignature */: - case 171 /* IndexSignature */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 308 /* JSDocFunctionType */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 330 /* JSDocTemplateTag */: - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 165 /* MethodSignature */: + case 172 /* IndexSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 309 /* JSDocFunctionType */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 334 /* JSDocTemplateTag */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; default: ts.assertType(node); @@ -14283,8 +14509,8 @@ var ts; ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: return true; default: return false; @@ -14293,15 +14519,15 @@ var ts; ts.isAnyImportSyntax = isAnyImportSyntax; function isLateVisibilityPaintedStatement(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 232 /* VariableStatement */: - case 252 /* ClassDeclaration */: - case 251 /* FunctionDeclaration */: - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 233 /* VariableStatement */: + case 253 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: return true; default: return false; @@ -14334,7 +14560,7 @@ var ts; } ts.getNameFromIndexInfo = getNameFromIndexInfo; function isComputedNonLiteralName(name) { - return name.kind === 158 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); + return name.kind === 159 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); } ts.isComputedNonLiteralName = isComputedNonLiteralName; function getTextOfPropertyName(name) { @@ -14346,7 +14572,7 @@ var ts; case 8 /* NumericLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: if (isStringOrNumericLiteralLike(name.expression)) return ts.escapeLeadingUnderscores(name.expression.text); return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames"); @@ -14362,9 +14588,9 @@ var ts; case 79 /* PrivateIdentifier */: case 78 /* Identifier */: return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) { return entityNameToString(name.expression) + "." + entityNameToString(name.name); } @@ -14450,7 +14676,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 230 /* Block */) { + if (node.body && node.body.kind === 231 /* Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -14464,7 +14690,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -14473,28 +14699,28 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 249 /* VariableDeclaration */: - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 254 /* TypeAliasDeclaration */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 250 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 255 /* TypeAliasDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: errorNode = node.name; break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: var start = ts.skipTrivia(sourceFile.text, node.pos); var end = node.statements.length > 0 ? node.statements[0].pos : node.end; return ts.createTextSpanFromBounds(start, end); @@ -14546,11 +14772,11 @@ var ts; } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 203 /* CallExpression */ && n.expression.kind === 105 /* SuperKeyword */; + return n.kind === 204 /* CallExpression */ && n.expression.kind === 105 /* SuperKeyword */; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 203 /* CallExpression */ && n.expression.kind === 99 /* ImportKeyword */; + return n.kind === 204 /* CallExpression */ && n.expression.kind === 99 /* ImportKeyword */; } ts.isImportCall = isImportCall; function isImportMeta(n) { @@ -14564,7 +14790,7 @@ var ts; } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { - return node.kind === 233 /* ExpressionStatement */ + return node.kind === 234 /* ExpressionStatement */ && node.expression.kind === 10 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; @@ -14592,11 +14818,12 @@ var ts; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 160 /* Parameter */ || - node.kind === 159 /* TypeParameter */ || - node.kind === 208 /* FunctionExpression */ || - node.kind === 209 /* ArrowFunction */ || - node.kind === 207 /* ParenthesizedExpression */) ? + var commentRanges = (node.kind === 161 /* Parameter */ || + node.kind === 160 /* TypeParameter */ || + node.kind === 209 /* FunctionExpression */ || + node.kind === 210 /* ArrowFunction */ || + node.kind === 208 /* ParenthesizedExpression */ || + node.kind === 250 /* VariableDeclaration */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -14612,7 +14839,7 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (172 /* FirstTypeNode */ <= node.kind && node.kind <= 195 /* LastTypeNode */) { + if (173 /* FirstTypeNode */ <= node.kind && node.kind <= 196 /* LastTypeNode */) { return true; } switch (node.kind) { @@ -14628,32 +14855,32 @@ var ts; case 141 /* NeverKeyword */: return true; case 113 /* VoidKeyword */: - return node.parent.kind !== 212 /* VoidExpression */; - case 223 /* ExpressionWithTypeArguments */: + return node.parent.kind !== 213 /* VoidExpression */; + case 224 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 159 /* TypeParameter */: - return node.parent.kind === 190 /* MappedType */ || node.parent.kind === 185 /* InferType */; + case 160 /* TypeParameter */: + return node.parent.kind === 191 /* MappedType */ || node.parent.kind === 186 /* InferType */; // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container case 78 /* Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 157 /* QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 158 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 202 /* PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 78 /* Identifier */ || node.kind === 157 /* QualifiedName */ || node.kind === 201 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + ts.Debug.assert(node.kind === 78 /* Identifier */ || node.kind === 158 /* QualifiedName */ || node.kind === 202 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); // falls through - case 157 /* QualifiedName */: - case 201 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: case 107 /* ThisKeyword */: { var parent = node.parent; - if (parent.kind === 176 /* TypeQuery */) { + if (parent.kind === 177 /* TypeQuery */) { return false; } - if (parent.kind === 195 /* ImportType */) { + if (parent.kind === 196 /* ImportType */) { return !parent.isTypeOf; } // Do not recursively call isPartOfTypeNode on the parent. In the example: @@ -14662,40 +14889,40 @@ var ts; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. // Only C and A.B.C are type nodes. - if (172 /* FirstTypeNode */ <= parent.kind && parent.kind <= 195 /* LastTypeNode */) { + if (173 /* FirstTypeNode */ <= parent.kind && parent.kind <= 196 /* LastTypeNode */) { return true; } switch (parent.kind) { - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return node === parent.constraint; - case 330 /* JSDocTemplateTag */: + case 334 /* JSDocTemplateTag */: return node === parent.constraint; - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 160 /* Parameter */: - case 249 /* VariableDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 161 /* Parameter */: + case 250 /* VariableDeclaration */: return node === parent.type; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return node === parent.type; - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return node === parent.type; - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: return node === parent.type; - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: return ts.contains(parent.typeArguments, node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -14720,23 +14947,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitor(node); - case 258 /* CaseBlock */: - case 230 /* Block */: - case 234 /* IfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 243 /* WithStatement */: - case 244 /* SwitchStatement */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: - case 245 /* LabeledStatement */: - case 247 /* TryStatement */: - case 287 /* CatchClause */: + case 259 /* CaseBlock */: + case 231 /* Block */: + case 235 /* IfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 244 /* WithStatement */: + case 245 /* SwitchStatement */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 246 /* LabeledStatement */: + case 248 /* TryStatement */: + case 288 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -14746,23 +14973,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 255 /* EnumDeclaration */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: // These are not allowed inside a generator now, but eventually they may be allowed // as local types. Regardless, skip them to avoid the work. return; default: if (ts.isFunctionLike(node)) { - if (node.name && node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 159 /* ComputedPropertyName */) { // Note that we will not include methods/accessors of a class because they would require // first descending into the class. This is by design. traverse(node.name.expression); @@ -14785,10 +15012,10 @@ var ts; * @param node The type node. */ function getRestParameterElementType(node) { - if (node && node.kind === 178 /* ArrayType */) { + if (node && node.kind === 179 /* ArrayType */) { return node.elementType; } - else if (node && node.kind === 173 /* TypeReference */) { + else if (node && node.kind === 174 /* TypeReference */) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -14798,12 +15025,12 @@ var ts; ts.getRestParameterElementType = getRestParameterElementType; function getMembersOfDeclaration(node) { switch (node.kind) { - case 253 /* InterfaceDeclaration */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 177 /* TypeLiteral */: + case 254 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 178 /* TypeLiteral */: return node.members; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return node.properties; } } @@ -14811,14 +15038,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 198 /* BindingElement */: - case 291 /* EnumMember */: - case 160 /* Parameter */: - case 288 /* PropertyAssignment */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 289 /* ShorthandPropertyAssignment */: - case 249 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 292 /* EnumMember */: + case 161 /* Parameter */: + case 289 /* PropertyAssignment */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 290 /* ShorthandPropertyAssignment */: + case 250 /* VariableDeclaration */: return true; } } @@ -14830,8 +15057,8 @@ var ts; } ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { - return node.parent.kind === 250 /* VariableDeclarationList */ - && node.parent.parent.kind === 232 /* VariableStatement */; + return node.parent.kind === 251 /* VariableDeclarationList */ + && node.parent.parent.kind === 233 /* VariableStatement */; } ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; function isValidESSymbolDeclaration(node) { @@ -14842,13 +15069,13 @@ var ts; ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return true; } return false; @@ -14859,7 +15086,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 245 /* LabeledStatement */) { + if (node.statement.kind !== 246 /* LabeledStatement */) { return node.statement; } node = node.statement; @@ -14867,17 +15094,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 230 /* Block */ && ts.isFunctionLike(node.parent); + return node && node.kind === 231 /* Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 165 /* MethodDeclaration */ && node.parent.kind === 200 /* ObjectLiteralExpression */; + return node && node.kind === 166 /* MethodDeclaration */ && node.parent.kind === 201 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 165 /* MethodDeclaration */ && - (node.parent.kind === 200 /* ObjectLiteralExpression */ || - node.parent.kind === 221 /* ClassExpression */); + return node.kind === 166 /* MethodDeclaration */ && + (node.parent.kind === 201 /* ObjectLiteralExpression */ || + node.parent.kind === 222 /* ClassExpression */); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -14890,7 +15117,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return objectLiteral.properties.filter(function (property) { - if (property.kind === 288 /* PropertyAssignment */) { + if (property.kind === 289 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); return key === propName || (!!key2 && key2 === propName); } @@ -14939,14 +15166,14 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { - ts.Debug.assert(node.kind !== 297 /* SourceFile */); + ts.Debug.assert(node.kind !== 298 /* SourceFile */); while (true) { node = node.parent; if (!node) { return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. } switch (node.kind) { - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: // If the grandparent node is an object literal (as opposed to a class), // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container @@ -14961,9 +15188,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 161 /* Decorator */: + case 162 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 160 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 161 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -14974,26 +15201,26 @@ var ts; node = node.parent; } break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // falls through - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 256 /* ModuleDeclaration */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 255 /* EnumDeclaration */: - case 297 /* SourceFile */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 257 /* ModuleDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 256 /* EnumDeclaration */: + case 298 /* SourceFile */: return node; } } @@ -15012,9 +15239,9 @@ var ts; var container = getThisContainer(node, /*includeArrowFunctions*/ false); if (container) { switch (container.kind) { - case 166 /* Constructor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 167 /* Constructor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return container; } } @@ -15036,27 +15263,27 @@ var ts; return node; } switch (node.kind) { - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: node = node.parent; break; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: if (!stopOnFunctions) { continue; } // falls through - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return node; - case 161 /* Decorator */: + case 162 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 160 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 161 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -15072,14 +15299,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 208 /* FunctionExpression */ || func.kind === 209 /* ArrowFunction */) { + if (func.kind === 209 /* FunctionExpression */ || func.kind === 210 /* ArrowFunction */) { var prev = func; var parent = func.parent; - while (parent.kind === 207 /* ParenthesizedExpression */) { + while (parent.kind === 208 /* ParenthesizedExpression */) { prev = parent; parent = parent.parent; } - if (parent.kind === 203 /* CallExpression */ && parent.expression === prev) { + if (parent.kind === 204 /* CallExpression */ && parent.expression === prev) { return parent; } } @@ -15095,7 +15322,7 @@ var ts; */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 201 /* PropertyAccessExpression */ || kind === 202 /* ElementAccessExpression */) + return (kind === 202 /* PropertyAccessExpression */ || kind === 203 /* ElementAccessExpression */) && node.expression.kind === 105 /* SuperKeyword */; } ts.isSuperProperty = isSuperProperty; @@ -15104,7 +15331,7 @@ var ts; */ function isThisProperty(node) { var kind = node.kind; - return (kind === 201 /* PropertyAccessExpression */ || kind === 202 /* ElementAccessExpression */) + return (kind === 202 /* PropertyAccessExpression */ || kind === 203 /* ElementAccessExpression */) && node.expression.kind === 107 /* ThisKeyword */; } ts.isThisProperty = isThisProperty; @@ -15113,17 +15340,25 @@ var ts; return !!node && ts.isVariableDeclaration(node) && ((_a = node.initializer) === null || _a === void 0 ? void 0 : _a.kind) === 107 /* ThisKeyword */; } ts.isThisInitializedDeclaration = isThisInitializedDeclaration; + function isThisInitializedObjectBindingExpression(node) { + return !!node + && (ts.isShorthandPropertyAssignment(node) || ts.isPropertyAssignment(node)) + && ts.isBinaryExpression(node.parent.parent) + && node.parent.parent.operatorToken.kind === 62 /* EqualsToken */ + && node.parent.parent.right.kind === 107 /* ThisKeyword */; + } + ts.isThisInitializedObjectBindingExpression = isThisInitializedObjectBindingExpression; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return node.typeName; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) ? node.expression : undefined; // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s. case 78 /* Identifier */: - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return node; } return undefined; @@ -15131,10 +15366,10 @@ var ts; ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { switch (node.kind) { - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return node.tag; - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return node.tagName; default: return node.expression; @@ -15147,25 +15382,25 @@ var ts; return false; } switch (node.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: // classes are valid targets return true; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return parent.kind === 252 /* ClassDeclaration */; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: + return parent.kind === 253 /* ClassDeclaration */; + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && parent.kind === 252 /* ClassDeclaration */; - case 160 /* Parameter */: + && parent.kind === 253 /* ClassDeclaration */; + case 161 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; return parent.body !== undefined - && (parent.kind === 166 /* Constructor */ - || parent.kind === 165 /* MethodDeclaration */ - || parent.kind === 168 /* SetAccessor */) - && grandparent.kind === 252 /* ClassDeclaration */; + && (parent.kind === 167 /* Constructor */ + || parent.kind === 166 /* MethodDeclaration */ + || parent.kind === 169 /* SetAccessor */) + && grandparent.kind === 253 /* ClassDeclaration */; } return false; } @@ -15181,10 +15416,10 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 - case 165 /* MethodDeclaration */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 169 /* SetAccessor */: return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 default: return false; @@ -15193,9 +15428,9 @@ var ts; ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 275 /* JsxOpeningElement */ || - parent.kind === 274 /* JsxSelfClosingElement */ || - parent.kind === 276 /* JsxClosingElement */) { + if (parent.kind === 276 /* JsxOpeningElement */ || + parent.kind === 275 /* JsxSelfClosingElement */ || + parent.kind === 277 /* JsxClosingElement */) { return parent.tagName === node; } return false; @@ -15208,44 +15443,44 @@ var ts; case 109 /* TrueKeyword */: case 94 /* FalseKeyword */: case 13 /* RegularExpressionLiteral */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 205 /* TaggedTemplateExpression */: - case 224 /* AsExpression */: - case 206 /* TypeAssertionExpression */: - case 225 /* NonNullExpression */: - case 207 /* ParenthesizedExpression */: - case 208 /* FunctionExpression */: - case 221 /* ClassExpression */: - case 209 /* ArrowFunction */: - case 212 /* VoidExpression */: - case 210 /* DeleteExpression */: - case 211 /* TypeOfExpression */: - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: - case 216 /* BinaryExpression */: - case 217 /* ConditionalExpression */: - case 220 /* SpreadElement */: - case 218 /* TemplateExpression */: - case 222 /* OmittedExpression */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: - case 219 /* YieldExpression */: - case 213 /* AwaitExpression */: - case 226 /* MetaProperty */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 206 /* TaggedTemplateExpression */: + case 225 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 226 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 209 /* FunctionExpression */: + case 222 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 213 /* VoidExpression */: + case 211 /* DeleteExpression */: + case 212 /* TypeOfExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 217 /* BinaryExpression */: + case 218 /* ConditionalExpression */: + case 221 /* SpreadElement */: + case 219 /* TemplateExpression */: + case 223 /* OmittedExpression */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: + case 220 /* YieldExpression */: + case 214 /* AwaitExpression */: + case 227 /* MetaProperty */: return true; - case 157 /* QualifiedName */: - while (node.parent.kind === 157 /* QualifiedName */) { + case 158 /* QualifiedName */: + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 176 /* TypeQuery */ || isJSXTagName(node); + return node.parent.kind === 177 /* TypeQuery */ || isJSXTagName(node); case 78 /* Identifier */: - if (node.parent.kind === 176 /* TypeQuery */ || isJSXTagName(node)) { + if (node.parent.kind === 177 /* TypeQuery */ || isJSXTagName(node)) { return true; } // falls through @@ -15263,49 +15498,49 @@ var ts; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 291 /* EnumMember */: - case 288 /* PropertyAssignment */: - case 198 /* BindingElement */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 292 /* EnumMember */: + case 289 /* PropertyAssignment */: + case 199 /* BindingElement */: return parent.initializer === node; - case 233 /* ExpressionStatement */: - case 234 /* IfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 242 /* ReturnStatement */: - case 243 /* WithStatement */: - case 244 /* SwitchStatement */: - case 284 /* CaseClause */: - case 246 /* ThrowStatement */: + case 234 /* ExpressionStatement */: + case 235 /* IfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 243 /* ReturnStatement */: + case 244 /* WithStatement */: + case 245 /* SwitchStatement */: + case 285 /* CaseClause */: + case 247 /* ThrowStatement */: return parent.expression === node; - case 237 /* ForStatement */: + case 238 /* ForStatement */: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 250 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 251 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 250 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 251 /* VariableDeclarationList */) || forInStatement.expression === node; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return node === parent.expression; - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return node === parent.expression; - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return node === parent.expression; - case 161 /* Decorator */: - case 283 /* JsxExpression */: - case 282 /* JsxSpreadAttribute */: - case 290 /* SpreadAssignment */: + case 162 /* Decorator */: + case 284 /* JsxExpression */: + case 283 /* JsxSpreadAttribute */: + case 291 /* SpreadAssignment */: return true; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return parent.objectAssignmentInitializer === node; default: return isExpressionNode(parent); @@ -15313,14 +15548,18 @@ var ts; } ts.isInExpressionContext = isInExpressionContext; function isPartOfTypeQuery(node) { - while (node.kind === 157 /* QualifiedName */ || node.kind === 78 /* Identifier */) { + while (node.kind === 158 /* QualifiedName */ || node.kind === 78 /* Identifier */) { node = node.parent; } - return node.kind === 176 /* TypeQuery */; + return node.kind === 177 /* TypeQuery */; } ts.isPartOfTypeQuery = isPartOfTypeQuery; + function isNamespaceReexportDeclaration(node) { + return ts.isNamespaceExport(node) && !!node.parent.moduleSpecifier; + } + ts.isNamespaceReexportDeclaration = isNamespaceReexportDeclaration; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 272 /* ExternalModuleReference */; + return node.kind === 261 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 273 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -15329,12 +15568,11 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function getExternalModuleRequireArgument(node) { - return isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true) - && getLeftmostAccessExpression(node.initializer).arguments[0]; + return isRequireVariableDeclaration(node) && getLeftmostAccessExpression(node.initializer).arguments[0]; } ts.getExternalModuleRequireArgument = getExternalModuleRequireArgument; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 272 /* ExternalModuleReference */; + return node.kind === 261 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 273 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJS(file) { @@ -15370,7 +15608,7 @@ var ts; } ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, requireStringLiteralLikeArgument) { - if (callExpression.kind !== 203 /* CallExpression */) { + if (callExpression.kind !== 204 /* CallExpression */) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; @@ -15384,18 +15622,21 @@ var ts; return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; - function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) { - if (node.kind === 198 /* BindingElement */) { + /** + * Returns true if the node is a VariableDeclaration initialized to a require call (see `isRequireCall`). + * This function does not test if the node is in a JavaScript file or not. + */ + function isRequireVariableDeclaration(node) { + if (node.kind === 199 /* BindingElement */) { node = node.parent.parent; } - return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), requireStringLiteralLikeArgument); + return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), /*requireStringLiteralLikeArgument*/ true); } ts.isRequireVariableDeclaration = isRequireVariableDeclaration; - function isRequireVariableStatement(node, requireStringLiteralLikeArgument) { - if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; } + function isRequireVariableStatement(node) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 - && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); }); + && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl); }); } ts.isRequireVariableStatement = isRequireVariableStatement; function isSingleOrDoubleQuote(charCode) { @@ -15467,11 +15708,11 @@ var ts; function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); - return e.kind === 208 /* FunctionExpression */ || e.kind === 209 /* ArrowFunction */ ? initializer : undefined; + return e.kind === 209 /* FunctionExpression */ || e.kind === 210 /* ArrowFunction */ ? initializer : undefined; } - if (initializer.kind === 208 /* FunctionExpression */ || - initializer.kind === 221 /* ClassExpression */ || - initializer.kind === 209 /* ArrowFunction */) { + if (initializer.kind === 209 /* FunctionExpression */ || + initializer.kind === 222 /* ClassExpression */ || + initializer.kind === 210 /* ArrowFunction */) { return initializer; } if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { @@ -15592,8 +15833,7 @@ var ts; ts.isLiteralLikeAccess = isLiteralLikeAccess; /** x[0] OR x['a'] OR x[Symbol.y] */ function isLiteralLikeElementAccess(node) { - return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) || - isWellKnownSymbolSyntactically(node.argumentExpression)); + return ts.isElementAccessExpression(node) && isStringOrNumericLiteralLike(node.argumentExpression); } ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess; /** Any series of property and element accesses. */ @@ -15673,9 +15913,6 @@ var ts; return ts.escapeLeadingUnderscores(name.text); } } - if (ts.isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) { - return getPropertyNameForKnownSymbolName(ts.idText(node.argumentExpression.name)); - } return undefined; } ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName; @@ -15725,7 +15962,7 @@ var ts; ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { return isInJSFile(expr) && - expr.parent && expr.parent.kind === 233 /* ExpressionStatement */ && + expr.parent && expr.parent.kind === 234 /* ExpressionStatement */ && (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) && !!ts.getJSDocTypeTag(expr.parent); } @@ -15746,23 +15983,37 @@ var ts; return false; } var decl = symbol.valueDeclaration; - return decl.kind === 251 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + return decl.kind === 252 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); } ts.isFunctionSymbol = isFunctionSymbol; + function tryGetModuleSpecifierFromDeclaration(node) { + var _a, _b, _c; + switch (node.kind) { + case 250 /* VariableDeclaration */: + return node.initializer.arguments[0].text; + case 262 /* ImportDeclaration */: + return (_a = ts.tryCast(node.moduleSpecifier, ts.isStringLiteralLike)) === null || _a === void 0 ? void 0 : _a.text; + case 261 /* ImportEqualsDeclaration */: + return (_c = ts.tryCast((_b = ts.tryCast(node.moduleReference, ts.isExternalModuleReference)) === null || _b === void 0 ? void 0 : _b.expression, ts.isStringLiteralLike)) === null || _c === void 0 ? void 0 : _c.text; + default: + ts.Debug.assertNever(node); + } + } + ts.tryGetModuleSpecifierFromDeclaration = tryGetModuleSpecifierFromDeclaration; function importFromModuleSpecifier(node) { return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent); } ts.importFromModuleSpecifier = importFromModuleSpecifier; function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: return node.parent; - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: return node.parent.parent; - case 203 /* CallExpression */: + case 204 /* CallExpression */: return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined; - case 191 /* LiteralType */: + case 192 /* LiteralType */: ts.Debug.assert(ts.isStringLiteral(node)); return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: @@ -15772,15 +16023,17 @@ var ts; ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: return node.moduleSpecifier; - case 260 /* ImportEqualsDeclaration */: - return node.moduleReference.kind === 272 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; - case 195 /* ImportType */: + case 261 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 273 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 196 /* ImportType */: return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; - case 203 /* CallExpression */: + case 204 /* CallExpression */: return node.arguments[0]; + case 257 /* ModuleDeclaration */: + return node.name.kind === 10 /* StringLiteral */ ? node.name : undefined; default: return ts.Debug.assertNever(node); } @@ -15788,11 +16041,11 @@ var ts; ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return node; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport); default: return ts.Debug.assertNever(node); @@ -15800,7 +16053,7 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 261 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; + return node.kind === 262 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function forEachImportClauseDeclaration(node, action) { @@ -15821,13 +16074,13 @@ var ts; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 160 /* Parameter */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 289 /* ShorthandPropertyAssignment */: - case 288 /* PropertyAssignment */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 161 /* Parameter */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 290 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -15841,7 +16094,7 @@ var ts; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 331 /* JSDocTypedefTag */ || node.kind === 324 /* JSDocCallbackTag */ || node.kind === 325 /* JSDocEnumTag */; + return node.kind === 335 /* JSDocTypedefTag */ || node.kind === 328 /* JSDocCallbackTag */ || node.kind === 329 /* JSDocEnumTag */; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -15866,12 +16119,12 @@ var ts; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: var v = getSingleVariableOfVariableStatement(node); return v && v.initializer; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return node.initializer; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return node.initializer; } } @@ -15883,7 +16136,7 @@ var ts; function getNestedModuleDeclaration(node) { return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 256 /* ModuleDeclaration */ + node.body.kind === 257 /* ModuleDeclaration */ ? node.body : undefined; } @@ -15898,11 +16151,11 @@ var ts; if (ts.hasJSDocNodes(node)) { result = ts.append(result, ts.last(node.jsDoc)); } - if (node.kind === 160 /* Parameter */) { + if (node.kind === 161 /* Parameter */) { result = ts.addRange(result, (noCache ? ts.getJSDocParameterTagsNoCache : ts.getJSDocParameterTags)(node)); break; } - if (node.kind === 159 /* TypeParameter */) { + if (node.kind === 160 /* TypeParameter */) { result = ts.addRange(result, (noCache ? ts.getJSDocTypeParameterTagsNoCache : ts.getJSDocTypeParameterTags)(node)); break; } @@ -15913,10 +16166,11 @@ var ts; ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; function getNextJSDocCommentLocation(node) { var parent = node.parent; - if (parent.kind === 288 /* PropertyAssignment */ || - parent.kind === 266 /* ExportAssignment */ || - parent.kind === 163 /* PropertyDeclaration */ || - parent.kind === 233 /* ExpressionStatement */ && node.kind === 201 /* PropertyAccessExpression */ || + if (parent.kind === 289 /* PropertyAssignment */ || + parent.kind === 267 /* ExportAssignment */ || + parent.kind === 164 /* PropertyDeclaration */ || + parent.kind === 234 /* ExpressionStatement */ && node.kind === 202 /* PropertyAccessExpression */ || + parent.kind === 243 /* ReturnStatement */ || getNestedModuleDeclaration(parent) || ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) { return parent; @@ -16003,7 +16257,7 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 309 /* JSDocVariadicType */; + return node.dotDotDotToken !== undefined || !!type && type.kind === 310 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; function hasTypeArguments(node) { @@ -16020,31 +16274,34 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? binaryOperator === 62 /* EqualsToken */ || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? 1 /* Definite */ : 2 /* Compound */ : 0 /* None */; - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: var unaryOperator = parent.operator; return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; - case 207 /* ParenthesizedExpression */: - case 199 /* ArrayLiteralExpression */: - case 220 /* SpreadElement */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 200 /* ArrayLiteralExpression */: + case 221 /* SpreadElement */: + case 226 /* NonNullExpression */: node = parent; break; - case 289 /* ShorthandPropertyAssignment */: + case 291 /* SpreadAssignment */: + node = parent.parent; + break; + case 290 /* ShorthandPropertyAssignment */: if (parent.name !== node) { return 0 /* None */; } node = parent.parent; break; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: if (parent.name === node) { return 0 /* None */; } @@ -16071,22 +16328,22 @@ var ts; */ function isNodeWithPossibleHoistedDeclaration(node) { switch (node.kind) { - case 230 /* Block */: - case 232 /* VariableStatement */: - case 243 /* WithStatement */: - case 234 /* IfStatement */: - case 244 /* SwitchStatement */: - case 258 /* CaseBlock */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: - case 245 /* LabeledStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 247 /* TryStatement */: - case 287 /* CatchClause */: + case 231 /* Block */: + case 233 /* VariableStatement */: + case 244 /* WithStatement */: + case 235 /* IfStatement */: + case 245 /* SwitchStatement */: + case 259 /* CaseBlock */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 246 /* LabeledStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 248 /* TryStatement */: + case 288 /* CatchClause */: return true; } return false; @@ -16103,11 +16360,11 @@ var ts; return node; } function walkUpParenthesizedTypes(node) { - return walkUp(node, 186 /* ParenthesizedType */); + return walkUp(node, 187 /* ParenthesizedType */); } ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; function walkUpParenthesizedExpressions(node) { - return walkUp(node, 207 /* ParenthesizedExpression */); + return walkUp(node, 208 /* ParenthesizedExpression */); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; /** @@ -16117,7 +16374,7 @@ var ts; */ function walkUpParenthesizedTypesAndGetParentAndChild(node) { var child; - while (node && node.kind === 186 /* ParenthesizedType */) { + while (node && node.kind === 187 /* ParenthesizedType */) { child = node; node = node.parent; } @@ -16129,18 +16386,18 @@ var ts; } ts.skipParentheses = skipParentheses; function skipParenthesesUp(node) { - while (node.kind === 207 /* ParenthesizedExpression */) { + while (node.kind === 208 /* 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 !== 201 /* PropertyAccessExpression */ && node.kind !== 202 /* ElementAccessExpression */) { + if (node.kind !== 202 /* PropertyAccessExpression */ && node.kind !== 203 /* ElementAccessExpression */) { return false; } node = walkUpParenthesizedExpressions(node.parent); - return node && node.kind === 210 /* DeleteExpression */; + return node && node.kind === 211 /* DeleteExpression */; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -16193,7 +16450,7 @@ var ts; ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return isStringOrNumericLiteralLike(node) && - node.parent.kind === 158 /* ComputedPropertyName */ && + node.parent.kind === 159 /* ComputedPropertyName */ && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; @@ -16201,26 +16458,26 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 291 /* EnumMember */: - case 288 /* PropertyAssignment */: - case 201 /* PropertyAccessExpression */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 292 /* EnumMember */: + case 289 /* PropertyAssignment */: + case 202 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: // Name on right hand side of dot in a type query or type reference return parent.right === node; - case 198 /* BindingElement */: - case 265 /* ImportSpecifier */: + case 199 /* BindingElement */: + case 266 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 270 /* ExportSpecifier */: - case 280 /* JsxAttribute */: + case 271 /* ExportSpecifier */: + case 281 /* JsxAttribute */: // Any name in an export specifier or JSX Attribute return true; } @@ -16240,33 +16497,33 @@ var ts; // {} // {name: } function isAliasSymbolDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ || - node.kind === 259 /* NamespaceExportDeclaration */ || - node.kind === 262 /* ImportClause */ && !!node.name || - node.kind === 263 /* NamespaceImport */ || - node.kind === 269 /* NamespaceExport */ || - node.kind === 265 /* ImportSpecifier */ || - node.kind === 270 /* ExportSpecifier */ || - node.kind === 266 /* ExportAssignment */ && exportAssignmentIsAlias(node) || + return node.kind === 261 /* ImportEqualsDeclaration */ || + node.kind === 260 /* NamespaceExportDeclaration */ || + node.kind === 263 /* ImportClause */ && !!node.name || + node.kind === 264 /* NamespaceImport */ || + node.kind === 270 /* NamespaceExport */ || + node.kind === 266 /* ImportSpecifier */ || + node.kind === 271 /* ExportSpecifier */ || + node.kind === 267 /* ExportAssignment */ && exportAssignmentIsAlias(node) || ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) || ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableExpression(node.parent.right) || - node.kind === 289 /* ShorthandPropertyAssignment */ || - node.kind === 288 /* PropertyAssignment */ && isAliasableExpression(node.initializer); + node.kind === 290 /* ShorthandPropertyAssignment */ || + node.kind === 289 /* PropertyAssignment */ && isAliasableExpression(node.initializer); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getAliasDeclarationFromName(node) { switch (node.parent.kind) { - case 262 /* ImportClause */: - case 265 /* ImportSpecifier */: - case 263 /* NamespaceImport */: - case 270 /* ExportSpecifier */: - case 266 /* ExportAssignment */: - case 260 /* ImportEqualsDeclaration */: + case 263 /* ImportClause */: + case 266 /* ImportSpecifier */: + case 264 /* NamespaceImport */: + case 271 /* ExportSpecifier */: + case 267 /* ExportAssignment */: + case 261 /* ImportEqualsDeclaration */: return node.parent; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: do { node = node.parent; - } while (node.parent.kind === 157 /* QualifiedName */); + } while (node.parent.kind === 158 /* QualifiedName */); return getAliasDeclarationFromName(node); } } @@ -16285,7 +16542,7 @@ var ts; } ts.getExportAssignmentExpression = getExportAssignmentExpression; function getPropertyAssignmentAliasLikeExpression(node) { - return node.kind === 289 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 288 /* PropertyAssignment */ ? node.initializer : + return node.kind === 290 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 289 /* PropertyAssignment */ ? node.initializer : node.parent.right; } ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression; @@ -16351,11 +16608,11 @@ var ts; } ts.getAncestor = getAncestor; function isKeyword(token) { - return 80 /* FirstKeyword */ <= token && token <= 156 /* LastKeyword */; + return 80 /* FirstKeyword */ <= token && token <= 157 /* LastKeyword */; } ts.isKeyword = isKeyword; function isContextualKeyword(token) { - return 125 /* FirstContextualKeyword */ <= token && token <= 156 /* LastContextualKeyword */; + return 125 /* FirstContextualKeyword */ <= token && token <= 157 /* LastContextualKeyword */; } ts.isContextualKeyword = isContextualKeyword; function isNonContextualKeyword(token) { @@ -16399,14 +16656,14 @@ var ts; } var flags = 0 /* Normal */; switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: if (node.asteriskToken) { flags |= 1 /* Generator */; } // falls through - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: if (hasSyntacticModifier(node, 256 /* Async */)) { flags |= 2 /* Async */; } @@ -16420,10 +16677,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: return node.body !== undefined && node.asteriskToken === undefined && hasSyntacticModifier(node, 256 /* Async */); @@ -16446,9 +16703,6 @@ var ts; * 3. The computed name is *not* expressed as a NumericLiteral. * 4. The computed name is *not* expressed as a PlusToken or MinusToken * immediately followed by a NumericLiteral. - * 5. The computed name is *not* expressed as `Symbol.`, where `` - * is a property of the Symbol constructor that denotes a built-in - * Symbol. */ function hasDynamicName(declaration) { var name = ts.getNameOfDeclaration(declaration); @@ -16456,24 +16710,14 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - if (!(name.kind === 158 /* ComputedPropertyName */ || name.kind === 202 /* ElementAccessExpression */)) { + if (!(name.kind === 159 /* ComputedPropertyName */ || name.kind === 203 /* ElementAccessExpression */)) { return false; } var expr = ts.isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression; return !isStringOrNumericLiteralLike(expr) && - !isSignedNumericLiteral(expr) && - !isWellKnownSymbolSyntactically(expr); + !isSignedNumericLiteral(expr); } ts.isDynamicName = isDynamicName; - /** - * Checks if the expression is of the form: - * Symbol.name - * where Symbol is literally the word "Symbol", and name is any identifierName - */ - function isWellKnownSymbolSyntactically(node) { - return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); - } - ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { switch (name.kind) { case 78 /* Identifier */: @@ -16482,12 +16726,9 @@ var ts; case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: var nameExpression = name.expression; - if (isWellKnownSymbolSyntactically(nameExpression)) { - return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - else if (isStringOrNumericLiteralLike(nameExpression)) { + if (isStringOrNumericLiteralLike(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); } else if (isSignedNumericLiteral(nameExpression)) { @@ -16515,21 +16756,17 @@ var ts; } ts.isPropertyNameLiteral = isPropertyNameLiteral; function getTextOfIdentifierOrLiteral(node) { - return ts.isIdentifierOrPrivateIdentifier(node) ? ts.idText(node) : node.text; + return ts.isMemberName(node) ? ts.idText(node) : node.text; } ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { - return ts.isIdentifierOrPrivateIdentifier(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text); + return ts.isMemberName(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForUniqueESSymbol(symbol) { return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName; } ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol; - function getPropertyNameForKnownSymbolName(symbolName) { - return "__@" + symbolName; - } - ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) { return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description; } @@ -16551,11 +16788,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 160 /* Parameter */; + return root.kind === 161 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 198 /* BindingElement */) { + while (node.kind === 199 /* BindingElement */) { node = node.parent.parent; } return node; @@ -16563,15 +16800,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 166 /* Constructor */ - || kind === 208 /* FunctionExpression */ - || kind === 251 /* FunctionDeclaration */ - || kind === 209 /* ArrowFunction */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 256 /* ModuleDeclaration */ - || kind === 297 /* SourceFile */; + return kind === 167 /* Constructor */ + || kind === 209 /* FunctionExpression */ + || kind === 252 /* FunctionDeclaration */ + || kind === 210 /* ArrowFunction */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 257 /* ModuleDeclaration */ + || kind === 298 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -16590,23 +16827,23 @@ var ts; })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 204 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 205 /* NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 204 /* NewExpression */: + case 205 /* NewExpression */: return hasArguments ? 0 /* Left */ : 1 /* Right */; - case 214 /* PrefixUnaryExpression */: - case 211 /* TypeOfExpression */: - case 212 /* VoidExpression */: - case 210 /* DeleteExpression */: - case 213 /* AwaitExpression */: - case 217 /* ConditionalExpression */: - case 219 /* YieldExpression */: + case 215 /* PrefixUnaryExpression */: + case 212 /* TypeOfExpression */: + case 213 /* VoidExpression */: + case 211 /* DeleteExpression */: + case 214 /* AwaitExpression */: + case 218 /* ConditionalExpression */: + case 220 /* YieldExpression */: return 1 /* Right */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (operator) { case 42 /* AsteriskAsteriskToken */: case 62 /* EqualsToken */: @@ -16633,15 +16870,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 204 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 205 /* NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 216 /* BinaryExpression */) { + if (expression.kind === 217 /* BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 214 /* PrefixUnaryExpression */ || expression.kind === 215 /* PostfixUnaryExpression */) { + else if (expression.kind === 215 /* PrefixUnaryExpression */ || expression.kind === 216 /* PostfixUnaryExpression */) { return expression.operator; } else { @@ -16820,15 +17057,15 @@ var ts; })(OperatorPrecedence = ts.OperatorPrecedence || (ts.OperatorPrecedence = {})); function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return 0 /* Comma */; - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return 1 /* Spread */; - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return 2 /* Yield */; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return 4 /* Conditional */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (operatorKind) { case 27 /* CommaToken */: return 0 /* Comma */; @@ -16853,25 +17090,26 @@ var ts; return getBinaryOperatorPrecedence(operatorKind); } // TODO: Should prefix `++` and `--` be moved to the `Update` precedence? - case 206 /* TypeAssertionExpression */: - case 225 /* NonNullExpression */: - case 214 /* PrefixUnaryExpression */: - case 211 /* TypeOfExpression */: - case 212 /* VoidExpression */: - case 210 /* DeleteExpression */: - case 213 /* AwaitExpression */: + case 207 /* TypeAssertionExpression */: + case 226 /* NonNullExpression */: + case 215 /* PrefixUnaryExpression */: + case 212 /* TypeOfExpression */: + case 213 /* VoidExpression */: + case 211 /* DeleteExpression */: + case 214 /* AwaitExpression */: return 16 /* Unary */; - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return 17 /* Update */; - case 203 /* CallExpression */: + case 204 /* CallExpression */: return 18 /* LeftHandSide */; - case 204 /* NewExpression */: + case 205 /* NewExpression */: return hasArguments ? 19 /* Member */ : 18 /* LeftHandSide */; - case 205 /* TaggedTemplateExpression */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 206 /* TaggedTemplateExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 227 /* MetaProperty */: return 19 /* Member */; - case 224 /* AsExpression */: + case 225 /* AsExpression */: return 11 /* Relational */; case 107 /* ThisKeyword */: case 105 /* SuperKeyword */: @@ -16882,19 +17120,19 @@ var ts; case 8 /* NumericLiteral */: case 9 /* BigIntLiteral */: case 10 /* StringLiteral */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 221 /* ClassExpression */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 222 /* ClassExpression */: case 13 /* RegularExpressionLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: - case 218 /* TemplateExpression */: - case 207 /* ParenthesizedExpression */: - case 222 /* OmittedExpression */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: + case 219 /* TemplateExpression */: + case 208 /* ParenthesizedExpression */: + case 223 /* OmittedExpression */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: return 20 /* Primary */; default: return -1 /* Invalid */; @@ -16950,7 +17188,7 @@ var ts; function getSemanticJsxChildren(children) { return ts.filter(children, function (i) { switch (i.kind) { - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return !!i.expression; case 11 /* JsxText */: return !i.containsOnlyTriviaWhiteSpaces; @@ -17344,11 +17582,20 @@ var ts; return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getCanonicalAbsolutePath(host, path) { + return host.getCanonicalFileName(ts.getNormalizedAbsolutePath(path, host.getCurrentDirectory())); + } function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); if (!file || file.isDeclarationFile) { return undefined; } + // If the declaration already uses a non-relative name, and is outside the common source directory, continue to use it + var specifier = getExternalModuleName(declaration); + if (specifier && ts.isStringLiteralLike(specifier) && !ts.pathIsRelative(specifier.text) && + getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ts.ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1) { + return undefined; + } return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; @@ -17432,8 +17679,8 @@ var ts; return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !host.isSourceFileFromExternalLibrary(sourceFile) && - !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) && - (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName)); + (forceDtsEmit || (!(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) && + !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName))); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -17528,10 +17775,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 167 /* GetAccessor */) { + if (accessor.kind === 168 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 168 /* SetAccessor */) { + else if (accessor.kind === 169 /* SetAccessor */) { setAccessor = accessor; } else { @@ -17551,10 +17798,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 167 /* GetAccessor */ && !getAccessor) { + if (member.kind === 168 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 168 /* SetAccessor */ && !setAccessor) { + if (member.kind === 169 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -17603,7 +17850,7 @@ var ts; ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** template tags are only available when a typedef isn't already using them */ function isNonTypeAliasTemplate(tag) { - return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 311 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 312 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); } /** * Gets the effective type annotation of the value parameter of a set accessor. If the node @@ -17826,6 +18073,18 @@ var ts; return hasSyntacticModifier(node, 32 /* Static */); } ts.hasStaticModifier = hasStaticModifier; + function hasOverrideModifier(node) { + return hasEffectiveModifier(node, 16384 /* Override */); + } + ts.hasOverrideModifier = hasOverrideModifier; + function hasAbstractModifier(node) { + return hasSyntacticModifier(node, 128 /* Abstract */); + } + ts.hasAbstractModifier = hasAbstractModifier; + function hasAmbientModifier(node) { + return hasSyntacticModifier(node, 2 /* Ambient */); + } + ts.hasAmbientModifier = hasAmbientModifier; function hasEffectiveReadonlyModifier(node) { return hasEffectiveModifier(node, 64 /* Readonly */); } @@ -17839,7 +18098,7 @@ var ts; } ts.getSelectedSyntacticModifierFlags = getSelectedSyntacticModifierFlags; function getModifierFlagsWorker(node, includeJSDoc, alwaysIncludeJSDoc) { - if (node.kind >= 0 /* FirstToken */ && node.kind <= 156 /* LastToken */) { + if (node.kind >= 0 /* FirstToken */ && node.kind <= 157 /* LastToken */) { return 0 /* None */; } if (!(node.modifierFlagsCache & 536870912 /* HasComputedFlags */)) { @@ -17884,6 +18143,8 @@ var ts; flags |= 16 /* Protected */; if (ts.getJSDocReadonlyTagNoCache(node)) flags |= 64 /* Readonly */; + if (ts.getJSDocOverrideTagNoCache(node)) + flags |= 16384 /* Override */; } if (ts.getJSDocDeprecatedTagNoCache(node)) flags |= 8192 /* Deprecated */; @@ -17936,10 +18197,15 @@ var ts; case 87 /* DefaultKeyword */: return 512 /* Default */; case 129 /* AsyncKeyword */: return 256 /* Async */; case 142 /* ReadonlyKeyword */: return 64 /* Readonly */; + case 156 /* OverrideKeyword */: return 16384 /* Override */; } return 0 /* None */; } ts.modifierToFlag = modifierToFlag; + function createModifiers(modifierFlags) { + return modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; + } + ts.createModifiers = createModifiers; function isLogicalOperator(token) { return token === 56 /* BarBarToken */ || token === 55 /* AmpersandAmpersandToken */ @@ -17982,11 +18248,15 @@ var ts; && ts.isLeftHandSideExpression(node.left); } ts.isAssignmentExpression = isAssignmentExpression; + function isLeftHandSideOfAssignment(node) { + return isAssignmentExpression(node.parent) && node.parent.left === node; + } + ts.isLeftHandSideOfAssignment = isLeftHandSideOfAssignment; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { var kind = node.left.kind; - return kind === 200 /* ObjectLiteralExpression */ - || kind === 199 /* ArrayLiteralExpression */; + return kind === 201 /* ObjectLiteralExpression */ + || kind === 200 /* ArrayLiteralExpression */; } return false; } @@ -18003,12 +18273,12 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: do { node = node.left; } while (node.kind !== 78 /* Identifier */); return node; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: do { node = node.expression; } while (node.kind !== 78 /* Identifier */); @@ -18017,9 +18287,12 @@ var ts; } ts.getFirstIdentifier = getFirstIdentifier; function isDottedName(node) { - return node.kind === 78 /* Identifier */ || node.kind === 107 /* ThisKeyword */ || node.kind === 105 /* SuperKeyword */ || - node.kind === 201 /* PropertyAccessExpression */ && isDottedName(node.expression) || - node.kind === 207 /* ParenthesizedExpression */ && isDottedName(node.expression); + return node.kind === 78 /* Identifier */ + || node.kind === 107 /* ThisKeyword */ + || node.kind === 105 /* SuperKeyword */ + || node.kind === 227 /* MetaProperty */ + || node.kind === 202 /* PropertyAccessExpression */ && isDottedName(node.expression) + || node.kind === 208 /* ParenthesizedExpression */ && isDottedName(node.expression); } ts.isDottedName = isDottedName; function isPropertyAccessEntityNameExpression(node) { @@ -18033,6 +18306,12 @@ var ts; return baseStr + "." + entityNameToString(expr.name); } } + else if (ts.isElementAccessExpression(expr)) { + var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); + if (baseStr !== undefined && ts.isPropertyName(expr.argumentExpression)) { + return baseStr + "." + getPropertyNameForPropertyNameNode(expr.argumentExpression); + } + } else if (ts.isIdentifier(expr)) { return ts.unescapeLeadingUnderscores(expr.escapedText); } @@ -18044,22 +18323,22 @@ var ts; } ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 157 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 158 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 202 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 200 /* ObjectLiteralExpression */ && + return expression.kind === 201 /* ObjectLiteralExpression */ && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 199 /* ArrayLiteralExpression */ && + return expression.kind === 200 /* ArrayLiteralExpression */ && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - if (!isExportDefaultSymbol(symbol)) + if (!isExportDefaultSymbol(symbol) || !symbol.declarations) return undefined; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; @@ -18386,8 +18665,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 255 /* EnumDeclaration */: - case 256 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 257 /* ModuleDeclaration */: return parseNode === parseNode.parent.name; } } @@ -18414,9 +18693,11 @@ var ts; return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0; } ts.getCheckFlags = getCheckFlags; - function getDeclarationModifierFlagsFromSymbol(s) { + function getDeclarationModifierFlagsFromSymbol(s, isWrite) { + if (isWrite === void 0) { isWrite = false; } if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + var declaration = (isWrite && s.declarations && ts.find(s.declarations, function (d) { return d.kind === 169 /* SetAccessor */; })) || s.valueDeclaration; + var flags = ts.getCombinedModifierFlags(declaration); return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; } if (getCheckFlags(s) & 6 /* Synthetic */) { @@ -18464,35 +18745,35 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return accessKind(parent); - case 215 /* PostfixUnaryExpression */: - case 214 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: var operator = parent.operator; return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? operatorToken.kind === 62 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() : 0 /* Read */; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); - case 288 /* PropertyAssignment */: { + case 289 /* 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 289 /* ShorthandPropertyAssignment */: + case 290 /* 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 199 /* ArrayLiteralExpression */: + case 200 /* 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 && skipParenthesesUp(parent.parent).kind === 233 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 234 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; } } function reverseAccessKind(a) { @@ -18580,7 +18861,8 @@ var ts; } ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol; function getClassLikeDeclarationOfSymbol(symbol) { - return ts.find(symbol.declarations, ts.isClassLike); + var _a; + return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isClassLike); } ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; function getObjectFlags(type) { @@ -18623,7 +18905,6 @@ var ts; ts.getLastChild = getLastChild; function addToSeen(seen, key, value) { if (value === void 0) { value = true; } - key = String(key); if (seen.has(key)) { return false; } @@ -18636,7 +18917,7 @@ var ts; } ts.isObjectTypeDeclaration = isObjectTypeDeclaration; function isTypeNodeKind(kind) { - return (kind >= 172 /* FirstTypeNode */ && kind <= 195 /* LastTypeNode */) + return (kind >= 173 /* FirstTypeNode */ && kind <= 196 /* LastTypeNode */) || kind === 128 /* AnyKeyword */ || kind === 152 /* UnknownKeyword */ || kind === 144 /* NumberKeyword */ @@ -18648,25 +18929,25 @@ var ts; || kind === 113 /* VoidKeyword */ || kind === 150 /* UndefinedKeyword */ || kind === 141 /* NeverKeyword */ - || kind === 223 /* ExpressionWithTypeArguments */ - || kind === 303 /* JSDocAllType */ - || kind === 304 /* JSDocUnknownType */ - || kind === 305 /* JSDocNullableType */ - || kind === 306 /* JSDocNonNullableType */ - || kind === 307 /* JSDocOptionalType */ - || kind === 308 /* JSDocFunctionType */ - || kind === 309 /* JSDocVariadicType */; + || kind === 224 /* ExpressionWithTypeArguments */ + || kind === 304 /* JSDocAllType */ + || kind === 305 /* JSDocUnknownType */ + || kind === 306 /* JSDocNullableType */ + || kind === 307 /* JSDocNonNullableType */ + || kind === 308 /* JSDocOptionalType */ + || kind === 309 /* JSDocFunctionType */ + || kind === 310 /* JSDocVariadicType */; } ts.isTypeNodeKind = isTypeNodeKind; function isAccessExpression(node) { - return node.kind === 201 /* PropertyAccessExpression */ || node.kind === 202 /* ElementAccessExpression */; + return node.kind === 202 /* PropertyAccessExpression */ || node.kind === 203 /* ElementAccessExpression */; } ts.isAccessExpression = isAccessExpression; function getNameOfAccessExpression(node) { - if (node.kind === 201 /* PropertyAccessExpression */) { + if (node.kind === 202 /* PropertyAccessExpression */) { return node.name; } - ts.Debug.assert(node.kind === 202 /* ElementAccessExpression */); + ts.Debug.assert(node.kind === 203 /* ElementAccessExpression */); return node.argumentExpression; } ts.getNameOfAccessExpression = getNameOfAccessExpression; @@ -18681,7 +18962,7 @@ var ts; } ts.isBundleFileTextLike = isBundleFileTextLike; function isNamedImportsOrExports(node) { - return node.kind === 264 /* NamedImports */ || node.kind === 268 /* NamedExports */; + return node.kind === 265 /* NamedImports */ || node.kind === 269 /* NamedExports */; } ts.isNamedImportsOrExports = isNamedImportsOrExports; function getLeftmostAccessExpression(expr) { @@ -18694,28 +18975,28 @@ var ts; function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: node = node.operand; continue; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: node = node.left; continue; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: node = node.condition; continue; - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: node = node.tag; continue; - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (stopAtCallExpressions) { return node; } // falls through - case 224 /* AsExpression */: - case 202 /* ElementAccessExpression */: - case 201 /* PropertyAccessExpression */: - case 225 /* NonNullExpression */: - case 336 /* PartiallyEmittedExpression */: + case 225 /* AsExpression */: + case 203 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 226 /* NonNullExpression */: + case 340 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -18734,7 +19015,7 @@ var ts; } function Type(checker, flags) { this.flags = flags; - if (ts.Debug.isDebugging || ts.tracing.isTracing()) { + if (ts.Debug.isDebugging || ts.tracing) { this.checker = checker; } } @@ -19078,6 +19359,10 @@ var ts; return !!(compilerOptions.declaration || compilerOptions.composite); } ts.getEmitDeclarations = getEmitDeclarations; + function shouldPreserveConstEnums(compilerOptions) { + return !!(compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + } + ts.shouldPreserveConstEnums = shouldPreserveConstEnums; function isIncrementalCompilation(options) { return !!(options.incremental || options.composite); } @@ -19090,6 +19375,10 @@ var ts; return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs; } ts.getAllowJSCompilerOption = getAllowJSCompilerOption; + function getUseDefineForClassFields(compilerOptions) { + return compilerOptions.useDefineForClassFields === undefined ? compilerOptions.target === 99 /* ESNext */ : compilerOptions.useDefineForClassFields; + } + ts.getUseDefineForClassFields = getUseDefineForClassFields; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { return oldOptions !== newOptions && ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); @@ -19111,7 +19400,7 @@ var ts; ts.getJSXTransformEnabled = getJSXTransformEnabled; function getJSXImplicitImportBase(compilerOptions, file) { var jsxImportSourcePragmas = file === null || file === void 0 ? void 0 : file.pragmas.get("jsximportsource"); - var jsxImportSourcePragma = ts.isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[0] : jsxImportSourcePragmas; + var jsxImportSourcePragma = ts.isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[jsxImportSourcePragmas.length - 1] : jsxImportSourcePragmas; return compilerOptions.jsx === 4 /* ReactJSX */ || compilerOptions.jsx === 5 /* ReactJSXDev */ || compilerOptions.jsxImportSource || @@ -19140,37 +19429,65 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createSymlinkCache() { + function createSymlinkCache(cwd, getCanonicalFileName) { var symlinkedDirectories; + var symlinkedDirectoriesByRealpath; var symlinkedFiles; return { getSymlinkedFiles: function () { return symlinkedFiles; }, getSymlinkedDirectories: function () { return symlinkedDirectories; }, + getSymlinkedDirectoriesByRealpath: function () { return symlinkedDirectoriesByRealpath; }, setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); }, - setSymlinkedDirectory: function (path, directory) { return (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(path, directory); }, + setSymlinkedDirectory: function (symlink, real) { + // Large, interconnected dependency graphs in pnpm will have a huge number of symlinks + // where both the realpath and the symlink path are inside node_modules/.pnpm. Since + // this path is never a candidate for a module specifier, we can ignore it entirely. + var symlinkPath = ts.toPath(symlink, cwd, getCanonicalFileName); + if (!containsIgnoredPath(symlinkPath)) { + symlinkPath = ts.ensureTrailingDirectorySeparator(symlinkPath); + if (real !== false && !(symlinkedDirectories === null || symlinkedDirectories === void 0 ? void 0 : symlinkedDirectories.has(symlinkPath))) { + (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = ts.createMultiMap())).add(ts.ensureTrailingDirectorySeparator(real.realPath), symlink); + } + (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); + } + }, + setSymlinkedDirectoryFromSymlinkedFile: function (symlink, real) { + this.setSymlinkedFile(ts.toPath(symlink, cwd, getCanonicalFileName), real); + var _a = guessDirectorySymlink(real, symlink, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _a[0], commonOriginal = _a[1]; + if (commonResolved && commonOriginal) { + this.setSymlinkedDirectory(commonOriginal, { + real: commonResolved, + realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName), + }); + } + }, }; } ts.createSymlinkCache = createSymlinkCache; function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { - var cache = createSymlinkCache(); - var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { - return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) { - return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + var cache = createSymlinkCache(cwd, getCanonicalFileName); + var symlinks = ts.flatMap(files, function (sf) { + var pairs = sf.resolvedModules && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedModules.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) ? [res.resolvedFileName, res.originalPath] : undefined; + })); + return ts.concatenate(pairs, sf.resolvedTypeReferenceDirectiveNames && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedTypeReferenceDirectiveNames.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) && res.resolvedFileName ? [res.resolvedFileName, res.originalPath] : undefined; }))); - })); + }); for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + cache.setSymlinkedFile(ts.toPath(originalPath, cwd, getCanonicalFileName), resolvedPath); var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1]; if (commonResolved && commonOriginal) { - cache.setSymlinkedDirectory(ts.toPath(commonOriginal, cwd, getCanonicalFileName), { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); + cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); } } return cache; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(a, cwd)); + var bParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(b, cwd)); var isDirectory = false; while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && @@ -19554,6 +19871,14 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + function numberOfDirectorySeparators(str) { + var match = str.match(/\//g); + return match ? match.length : 0; + } + function compareNumberOfDirectorySeparators(path1, path2) { + return ts.compareValues(numberOfDirectorySeparators(path1), numberOfDirectorySeparators(path2)); + } + ts.compareNumberOfDirectorySeparators = compareNumberOfDirectorySeparators; /** * Extension boundaries by priority. Lower numbers indicate higher priorities, and are * aligned to the offset of the highest priority extension in the @@ -19850,21 +20175,21 @@ var ts; } ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite; function typeOnlyDeclarationIsExport(typeOnlyDeclaration) { - return typeOnlyDeclaration.kind === 270 /* ExportSpecifier */; + return typeOnlyDeclaration.kind === 271 /* ExportSpecifier */; } ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport; function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) { - while (node.kind === 78 /* Identifier */ || node.kind === 201 /* PropertyAccessExpression */) { + while (node.kind === 78 /* Identifier */ || node.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - if (node.kind !== 158 /* ComputedPropertyName */) { + if (node.kind !== 159 /* ComputedPropertyName */) { return false; } if (hasSyntacticModifier(node.parent, 128 /* Abstract */)) { return true; } var containerKind = node.parent.parent.kind; - return containerKind === 253 /* InterfaceDeclaration */ || containerKind === 177 /* TypeLiteral */; + return containerKind === 254 /* InterfaceDeclaration */ || containerKind === 178 /* TypeLiteral */; } /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */ function isIdentifierInNonEmittingHeritageClause(node) { @@ -19872,16 +20197,16 @@ var ts; return false; var heritageClause = ts.findAncestor(node.parent, function (parent) { switch (parent.kind) { - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: return true; - case 201 /* PropertyAccessExpression */: - case 223 /* ExpressionWithTypeArguments */: + case 202 /* PropertyAccessExpression */: + case 224 /* ExpressionWithTypeArguments */: return false; default: return "quit"; } }); - return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 116 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 253 /* InterfaceDeclaration */; + return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 116 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 254 /* InterfaceDeclaration */; } function isIdentifierTypeReference(node) { return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName); @@ -20034,6 +20359,76 @@ var ts; } } ts.expressionResultIsUnused = expressionResultIsUnused; + function containsIgnoredPath(path) { + return ts.some(ts.ignoredPaths, function (p) { return ts.stringContains(path, p); }); + } + ts.containsIgnoredPath = containsIgnoredPath; + function getContainingNodeArray(node) { + if (!node.parent) + return undefined; + switch (node.kind) { + case 160 /* TypeParameter */: + var parent_1 = node.parent; + return parent_1.kind === 186 /* InferType */ ? undefined : parent_1.typeParameters; + case 161 /* Parameter */: + return node.parent.parameters; + case 195 /* TemplateLiteralTypeSpan */: + return node.parent.templateSpans; + case 229 /* TemplateSpan */: + return node.parent.templateSpans; + case 162 /* Decorator */: + return node.parent.decorators; + case 287 /* HeritageClause */: + return node.parent.heritageClauses; + } + var parent = node.parent; + if (ts.isJSDocTag(node)) { + return ts.isJSDocTypeLiteral(node.parent) ? undefined : node.parent.tags; + } + switch (parent.kind) { + case 178 /* TypeLiteral */: + case 254 /* InterfaceDeclaration */: + return ts.isTypeElement(node) ? parent.members : undefined; + case 183 /* UnionType */: + case 184 /* IntersectionType */: + return parent.types; + case 180 /* TupleType */: + case 200 /* ArrayLiteralExpression */: + case 341 /* CommaListExpression */: + case 265 /* NamedImports */: + case 269 /* NamedExports */: + return parent.elements; + case 201 /* ObjectLiteralExpression */: + case 282 /* JsxAttributes */: + return parent.properties; + case 204 /* CallExpression */: + case 205 /* NewExpression */: + return ts.isTypeNode(node) ? parent.typeArguments : + parent.expression === node ? undefined : + parent.arguments; + case 274 /* JsxElement */: + case 278 /* JsxFragment */: + return ts.isJsxChild(node) ? parent.children : undefined; + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + return ts.isTypeNode(node) ? parent.typeArguments : undefined; + case 231 /* Block */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 258 /* ModuleBlock */: + return parent.statements; + case 259 /* CaseBlock */: + return parent.clauses; + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + return ts.isClassElement(node) ? parent.members : undefined; + case 256 /* EnumDeclaration */: + return ts.isEnumMember(node) ? parent.members : undefined; + case 298 /* SourceFile */: + return parent.statements; + } + } + ts.getContainingNodeArray = getContainingNodeArray; })(ts || (ts = {})); /* @internal */ var ts; @@ -20078,7 +20473,11 @@ var ts; var ts; (function (ts) { function createParenthesizerRules(factory) { + var binaryLeftOperandParenthesizerCache; + var binaryRightOperandParenthesizerCache; return { + getParenthesizeLeftSideOfBinaryForOperator: getParenthesizeLeftSideOfBinaryForOperator, + getParenthesizeRightSideOfBinaryForOperator: getParenthesizeRightSideOfBinaryForOperator, parenthesizeLeftSideOfBinary: parenthesizeLeftSideOfBinary, parenthesizeRightSideOfBinary: parenthesizeRightSideOfBinary, parenthesizeExpressionOfComputedPropertyName: parenthesizeExpressionOfComputedPropertyName, @@ -20099,6 +20498,24 @@ var ts; parenthesizeConstituentTypesOfUnionOrIntersectionType: parenthesizeConstituentTypesOfUnionOrIntersectionType, parenthesizeTypeArguments: parenthesizeTypeArguments, }; + function getParenthesizeLeftSideOfBinaryForOperator(operatorKind) { + binaryLeftOperandParenthesizerCache || (binaryLeftOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeLeftSideOfBinary(operatorKind, node); }; + binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } + function getParenthesizeRightSideOfBinaryForOperator(operatorKind) { + binaryRightOperandParenthesizerCache || (binaryRightOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeRightSideOfBinary(operatorKind, /*leftSide*/ undefined, node); }; + binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } /** * Determines whether the operand to a BinaryExpression needs to be parenthesized. * @@ -20125,10 +20542,10 @@ var ts; // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - var binaryOperatorPrecedence = ts.getOperatorPrecedence(216 /* BinaryExpression */, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(216 /* BinaryExpression */, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(217 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(217 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); - if (!isLeftSideOfBinary && operand.kind === 209 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */) { + if (!isLeftSideOfBinary && operand.kind === 210 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */) { // We need to parenthesize arrow functions on the right side to avoid it being // parsed as parenthesized expression: `a && (() => {})` return true; @@ -20140,7 +20557,7 @@ var ts; // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ - && operand.kind === 219 /* YieldExpression */) { + && operand.kind === 220 /* YieldExpression */) { return false; } return true; @@ -20228,7 +20645,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) { + if (node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -20254,7 +20671,7 @@ var ts; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. - if (skipped.kind === 207 /* ParenthesizedExpression */) { + if (skipped.kind === 208 /* ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -20271,7 +20688,7 @@ var ts; return ts.isCommaSequence(expression) ? factory.createParenthesizedExpression(expression) : expression; } function parenthesizeConditionOfConditionalExpression(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(217 /* ConditionalExpression */, 57 /* QuestionToken */); + var conditionalPrecedence = ts.getOperatorPrecedence(218 /* ConditionalExpression */, 57 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) { @@ -20304,8 +20721,8 @@ var ts; var needsParens = ts.isCommaSequence(check); if (!needsParens) { switch (ts.getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: needsParens = true; } } @@ -20318,9 +20735,9 @@ var ts; function parenthesizeExpressionOfNew(expression) { var leftmostExpr = ts.getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); switch (leftmostExpr.kind) { - case 203 /* CallExpression */: + case 204 /* CallExpression */: return factory.createParenthesizedExpression(expression); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return !leftmostExpr.arguments ? factory.createParenthesizedExpression(expression) : expression; // TODO(rbuckton): Verify this assertion holds @@ -20340,7 +20757,7 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 204 /* NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 205 /* NewExpression */ || emittedExpression.arguments)) { // TODO(rbuckton): Verify whether this assertion holds. return expression; } @@ -20362,7 +20779,7 @@ var ts; function parenthesizeExpressionForDisallowedComma(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(216 /* BinaryExpression */, 27 /* CommaToken */); + var commaPrecedence = ts.getOperatorPrecedence(217 /* BinaryExpression */, 27 /* CommaToken */); // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(factory.createParenthesizedExpression(expression), expression); } @@ -20371,44 +20788,44 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 208 /* FunctionExpression */ || kind === 209 /* ArrowFunction */) { + if (kind === 209 /* FunctionExpression */ || kind === 210 /* ArrowFunction */) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. var updated = factory.updateCallExpression(emittedExpression, ts.setTextRange(factory.createParenthesizedExpression(callee), callee), emittedExpression.typeArguments, emittedExpression.arguments); return factory.restoreOuterExpressions(expression, updated, 8 /* PartiallyEmittedExpressions */); } } var leftmostExpressionKind = ts.getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; - if (leftmostExpressionKind === 200 /* ObjectLiteralExpression */ || leftmostExpressionKind === 208 /* FunctionExpression */) { + if (leftmostExpressionKind === 201 /* ObjectLiteralExpression */ || leftmostExpressionKind === 209 /* FunctionExpression */) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return ts.setTextRange(factory.createParenthesizedExpression(expression), expression); } return expression; } function parenthesizeConciseBodyOfArrowFunction(body) { - if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 200 /* ObjectLiteralExpression */)) { + if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 201 /* ObjectLiteralExpression */)) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return ts.setTextRange(factory.createParenthesizedExpression(body), body); } return body; } function parenthesizeMemberOfConditionalType(member) { - return member.kind === 184 /* ConditionalType */ ? factory.createParenthesizedType(member) : member; + return member.kind === 185 /* ConditionalType */ ? factory.createParenthesizedType(member) : member; } function parenthesizeMemberOfElementType(member) { switch (member.kind) { - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return factory.createParenthesizedType(member); } return parenthesizeMemberOfConditionalType(member); } function parenthesizeElementTypeOfArrayType(member) { switch (member.kind) { - case 176 /* TypeQuery */: - case 188 /* TypeOperator */: - case 185 /* InferType */: + case 177 /* TypeQuery */: + case 189 /* TypeOperator */: + case 186 /* InferType */: return factory.createParenthesizedType(member); } return parenthesizeMemberOfElementType(member); @@ -20427,6 +20844,8 @@ var ts; } ts.createParenthesizerRules = createParenthesizerRules; ts.nullParenthesizerRules = { + getParenthesizeLeftSideOfBinaryForOperator: function (_) { return ts.identity; }, + getParenthesizeRightSideOfBinaryForOperator: function (_) { return ts.identity; }, parenthesizeLeftSideOfBinary: function (_binaryOperator, leftSide) { return leftSide; }, parenthesizeRightSideOfBinary: function (_binaryOperator, _leftSide, rightSide) { return rightSide; }, parenthesizeExpressionOfComputedPropertyName: ts.identity, @@ -20512,11 +20931,11 @@ var ts; } function convertToAssignmentPattern(node) { switch (node.kind) { - case 197 /* ArrayBindingPattern */: - case 199 /* ArrayLiteralExpression */: + case 198 /* ArrayBindingPattern */: + case 200 /* ArrayLiteralExpression */: return convertToArrayAssignmentPattern(node); - case 196 /* ObjectBindingPattern */: - case 200 /* ObjectLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 201 /* ObjectLiteralExpression */: return convertToObjectAssignmentPattern(node); } } @@ -20857,18 +21276,18 @@ var ts; createExternalModuleReference: createExternalModuleReference, updateExternalModuleReference: updateExternalModuleReference, // lazily load factory members for JSDoc types with similar structure - get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(303 /* JSDocAllType */); }, - get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(304 /* JSDocUnknownType */); }, - get createJSDocNonNullableType() { return getJSDocUnaryTypeCreateFunction(306 /* JSDocNonNullableType */); }, - get updateJSDocNonNullableType() { return getJSDocUnaryTypeUpdateFunction(306 /* JSDocNonNullableType */); }, - get createJSDocNullableType() { return getJSDocUnaryTypeCreateFunction(305 /* JSDocNullableType */); }, - get updateJSDocNullableType() { return getJSDocUnaryTypeUpdateFunction(305 /* JSDocNullableType */); }, - get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(307 /* JSDocOptionalType */); }, - get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(307 /* JSDocOptionalType */); }, - get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(309 /* JSDocVariadicType */); }, - get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(309 /* JSDocVariadicType */); }, - get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(310 /* JSDocNamepathType */); }, - get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(310 /* JSDocNamepathType */); }, + get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(304 /* JSDocAllType */); }, + get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(305 /* JSDocUnknownType */); }, + get createJSDocNonNullableType() { return getJSDocUnaryTypeCreateFunction(307 /* JSDocNonNullableType */); }, + get updateJSDocNonNullableType() { return getJSDocUnaryTypeUpdateFunction(307 /* JSDocNonNullableType */); }, + get createJSDocNullableType() { return getJSDocUnaryTypeCreateFunction(306 /* JSDocNullableType */); }, + get updateJSDocNullableType() { return getJSDocUnaryTypeUpdateFunction(306 /* JSDocNullableType */); }, + get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(308 /* JSDocOptionalType */); }, + get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(308 /* JSDocOptionalType */); }, + get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(310 /* JSDocVariadicType */); }, + get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(310 /* JSDocVariadicType */); }, + get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(311 /* JSDocNamepathType */); }, + get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(311 /* JSDocNamepathType */); }, createJSDocFunctionType: createJSDocFunctionType, updateJSDocFunctionType: updateJSDocFunctionType, createJSDocTypeLiteral: createJSDocTypeLiteral, @@ -20895,31 +21314,37 @@ var ts; updateJSDocSeeTag: updateJSDocSeeTag, createJSDocNameReference: createJSDocNameReference, updateJSDocNameReference: updateJSDocNameReference, + createJSDocLink: createJSDocLink, + updateJSDocLink: updateJSDocLink, // lazily load factory members for JSDoc tags with similar structure - get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(329 /* JSDocTypeTag */); }, - get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(329 /* JSDocTypeTag */); }, - get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(327 /* JSDocReturnTag */); }, - get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(327 /* JSDocReturnTag */); }, - get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(328 /* JSDocThisTag */); }, - get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(328 /* JSDocThisTag */); }, - get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(325 /* JSDocEnumTag */); }, - get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(325 /* JSDocEnumTag */); }, - get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(317 /* JSDocAuthorTag */); }, - get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(317 /* JSDocAuthorTag */); }, - get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(319 /* JSDocClassTag */); }, - get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(319 /* JSDocClassTag */); }, - get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(320 /* JSDocPublicTag */); }, - get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(320 /* JSDocPublicTag */); }, - get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(321 /* JSDocPrivateTag */); }, - get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(321 /* JSDocPrivateTag */); }, - get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(322 /* JSDocProtectedTag */); }, - get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(322 /* JSDocProtectedTag */); }, - get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(323 /* JSDocReadonlyTag */); }, - get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(323 /* JSDocReadonlyTag */); }, - get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(318 /* JSDocDeprecatedTag */); }, - get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(318 /* JSDocDeprecatedTag */); }, + get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(333 /* JSDocTypeTag */); }, + get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(333 /* JSDocTypeTag */); }, + get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(331 /* JSDocReturnTag */); }, + get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(331 /* JSDocReturnTag */); }, + get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(332 /* JSDocThisTag */); }, + get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(332 /* JSDocThisTag */); }, + get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(329 /* JSDocEnumTag */); }, + get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(329 /* JSDocEnumTag */); }, + get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(320 /* JSDocAuthorTag */); }, + get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(320 /* JSDocAuthorTag */); }, + get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(322 /* JSDocClassTag */); }, + get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(322 /* JSDocClassTag */); }, + get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(323 /* JSDocPublicTag */); }, + get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(323 /* JSDocPublicTag */); }, + get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(324 /* JSDocPrivateTag */); }, + get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(324 /* JSDocPrivateTag */); }, + get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(325 /* JSDocProtectedTag */); }, + get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(325 /* JSDocProtectedTag */); }, + get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(326 /* JSDocReadonlyTag */); }, + get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(326 /* JSDocReadonlyTag */); }, + get createJSDocOverrideTag() { return getJSDocSimpleTagCreateFunction(327 /* JSDocOverrideTag */); }, + get updateJSDocOverrideTag() { return getJSDocSimpleTagUpdateFunction(327 /* JSDocOverrideTag */); }, + get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(321 /* JSDocDeprecatedTag */); }, + get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(321 /* JSDocDeprecatedTag */); }, createJSDocUnknownTag: createJSDocUnknownTag, updateJSDocUnknownTag: updateJSDocUnknownTag, + createJSDocText: createJSDocText, + updateJSDocText: updateJSDocText, createJSDocComment: createJSDocComment, updateJSDocComment: updateJSDocComment, createJsxElement: createJsxElement, @@ -21103,11 +21528,11 @@ var ts; // don't propagate child flags. if (name) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 163 /* PropertyDeclaration */: - case 288 /* PropertyAssignment */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 289 /* PropertyAssignment */: if (ts.isIdentifier(name)) { node.transformFlags |= propagateIdentifierNameFlags(name); break; @@ -21148,7 +21573,7 @@ var ts; function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) { var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type); node.body = body; - node.transformFlags |= propagateChildFlags(node.body) & ~8388608 /* ContainsPossibleTopLevelAwait */; + node.transformFlags |= propagateChildFlags(node.body) & ~16777216 /* ContainsPossibleTopLevelAwait */; if (!body) node.transformFlags |= 1 /* ContainsTypeScript */; return node; @@ -21201,7 +21626,7 @@ var ts; var node = createBaseLiteral(8 /* NumericLiteral */, typeof value === "number" ? value + "" : value); node.numericLiteralFlags = numericLiteralFlags; if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -21220,7 +21645,7 @@ var ts; var node = createBaseStringLiteral(text, isSingleQuote); node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; if (hasExtendedUnicodeEscape) - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -21276,7 +21701,7 @@ var ts; node.typeArguments = createNodeArray(typeArguments); } if (node.originalKeywordKind === 130 /* AwaitKeyword */) { - node.transformFlags |= 8388608 /* ContainsPossibleTopLevelAwait */; + node.transformFlags |= 16777216 /* ContainsPossibleTopLevelAwait */; } return node; } @@ -21299,8 +21724,11 @@ var ts; } /** Create a unique temporary variable for use in a loop. */ // @api - function createLoopVariable() { - return createBaseGeneratedIdentifier("", 2 /* Loop */); + function createLoopVariable(reservedInNestedScopes) { + var flags = 2 /* Loop */; + if (reservedInNestedScopes) + flags |= 8 /* ReservedInNestedScopes */; + return createBaseGeneratedIdentifier("", flags); } /** Create a unique name based on the supplied text. */ // @api @@ -21325,7 +21753,7 @@ var ts; ts.Debug.fail("First character of private identifier must be #: " + text); var node = baseFactory.createBasePrivateIdentifierNode(79 /* PrivateIdentifier */); node.escapedText = ts.escapeLeadingUnderscores(text); - node.transformFlags |= 4194304 /* ContainsClassFields */; + node.transformFlags |= 8388608 /* ContainsClassFields */; return node; } // @@ -21335,7 +21763,7 @@ var ts; return baseFactory.createBaseTokenNode(kind); } function createToken(token) { - ts.Debug.assert(token >= 0 /* FirstToken */ && token <= 156 /* LastToken */, "Invalid token"); + ts.Debug.assert(token >= 0 /* FirstToken */ && token <= 157 /* LastToken */, "Invalid token"); ts.Debug.assert(token <= 14 /* FirstTemplateToken */ || token >= 17 /* LastTemplateToken */, "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals."); ts.Debug.assert(token <= 8 /* FirstLiteralToken */ || token >= 14 /* LastLiteralToken */, "Invalid token. Use 'createLiteralLikeNode' to create literals."); ts.Debug.assert(token !== 78 /* Identifier */, "Invalid token. Use 'createIdentifier' to create identifiers"); @@ -21345,8 +21773,8 @@ var ts; case 129 /* AsyncKeyword */: // 'async' modifier is ES2017 (async functions) or ES2018 (async generators) transformFlags = - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */; break; case 122 /* PublicKeyword */: case 120 /* PrivateKeyword */: @@ -21360,6 +21788,7 @@ var ts; case 155 /* BigIntKeyword */: case 141 /* NeverKeyword */: case 145 /* ObjectKeyword */: + case 156 /* OverrideKeyword */: case 147 /* StringKeyword */: case 131 /* BooleanKeyword */: case 148 /* SymbolKeyword */: @@ -21370,11 +21799,11 @@ var ts; break; case 123 /* StaticKeyword */: case 105 /* SuperKeyword */: - transformFlags = 256 /* ContainsES2015 */; + transformFlags = 512 /* ContainsES2015 */; break; case 107 /* ThisKeyword */: // 'this' indicates a lexical 'this' - transformFlags = 4096 /* ContainsLexicalThis */; + transformFlags = 8192 /* ContainsLexicalThis */; break; } if (transformFlags) { @@ -21442,6 +21871,9 @@ var ts; if (flags & 32 /* Static */) { result.push(createModifier(123 /* StaticKeyword */)); } + if (flags & 16384 /* Override */) { + result.push(createModifier(156 /* OverrideKeyword */)); + } if (flags & 64 /* Readonly */) { result.push(createModifier(142 /* ReadonlyKeyword */)); } @@ -21455,7 +21887,7 @@ var ts; // // @api function createQualifiedName(left, right) { - var node = createBaseNode(157 /* QualifiedName */); + var node = createBaseNode(158 /* QualifiedName */); node.left = left; node.right = asName(right); node.transformFlags |= @@ -21472,12 +21904,12 @@ var ts; } // @api function createComputedPropertyName(expression) { - var node = createBaseNode(158 /* ComputedPropertyName */); + var node = createBaseNode(159 /* ComputedPropertyName */); node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 256 /* ContainsES2015 */ | - 32768 /* ContainsComputedPropertyName */; + 512 /* ContainsES2015 */ | + 65536 /* ContainsComputedPropertyName */; return node; } // @api @@ -21491,7 +21923,7 @@ var ts; // // @api function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createBaseNamedDeclaration(159 /* TypeParameter */, + var node = createBaseNamedDeclaration(160 /* TypeParameter */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.constraint = constraint; @@ -21509,7 +21941,7 @@ var ts; } // @api function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(160 /* Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); + var node = createBaseVariableLikeDeclaration(161 /* Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.dotDotDotToken = dotDotDotToken; node.questionToken = questionToken; if (ts.isThisIdentifier(node.name)) { @@ -21521,10 +21953,10 @@ var ts; propagateChildFlags(node.questionToken); if (questionToken) node.transformFlags |= 1 /* ContainsTypeScript */; - if (ts.modifiersToFlags(node.modifiers) & 92 /* ParameterPropertyModifier */) - node.transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */; + if (ts.modifiersToFlags(node.modifiers) & 16476 /* ParameterPropertyModifier */) + node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; if (initializer || dotDotDotToken) - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; } return node; } @@ -21542,12 +21974,12 @@ var ts; } // @api function createDecorator(expression) { - var node = createBaseNode(161 /* Decorator */); + var node = createBaseNode(162 /* Decorator */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */ | - 2048 /* ContainsTypeScriptClassSyntax */; + 4096 /* ContainsTypeScriptClassSyntax */; return node; } // @api @@ -21561,7 +21993,7 @@ var ts; // // @api function createPropertySignature(modifiers, name, questionToken, type) { - var node = createBaseNamedDeclaration(162 /* PropertySignature */, + var node = createBaseNamedDeclaration(163 /* PropertySignature */, /*decorators*/ undefined, modifiers, name); node.type = type; node.questionToken = questionToken; @@ -21579,15 +22011,15 @@ var ts; } // @api function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(163 /* PropertyDeclaration */, decorators, modifiers, name, type, initializer); + var node = createBaseVariableLikeDeclaration(164 /* PropertyDeclaration */, decorators, modifiers, name, type, initializer); node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.transformFlags |= propagateChildFlags(node.questionToken) | propagateChildFlags(node.exclamationToken) | - 4194304 /* ContainsClassFields */; + 8388608 /* ContainsClassFields */; if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) { - node.transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */; + node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) { node.transformFlags |= 1 /* ContainsTypeScript */; @@ -21608,7 +22040,7 @@ var ts; } // @api function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(164 /* MethodSignature */, + var node = createBaseSignatureDeclaration(165 /* MethodSignature */, /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type); node.questionToken = questionToken; node.transformFlags = 1 /* ContainsTypeScript */; @@ -21627,26 +22059,26 @@ var ts; } // @api function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(165 /* MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(166 /* MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.questionToken = questionToken; node.transformFlags |= propagateChildFlags(node.asteriskToken) | propagateChildFlags(node.questionToken) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (questionToken) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (asteriskToken) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } else { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } } else if (asteriskToken) { - node.transformFlags |= 512 /* ContainsGenerator */; + node.transformFlags |= 1024 /* ContainsGenerator */; } return node; } @@ -21666,11 +22098,11 @@ var ts; } // @api function createConstructorDeclaration(decorators, modifiers, parameters, body) { - var node = createBaseFunctionLikeDeclaration(166 /* Constructor */, decorators, modifiers, + var node = createBaseFunctionLikeDeclaration(167 /* Constructor */, decorators, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -21684,7 +22116,7 @@ var ts; } // @api function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) { - return createBaseFunctionLikeDeclaration(167 /* GetAccessor */, decorators, modifiers, name, + return createBaseFunctionLikeDeclaration(168 /* GetAccessor */, decorators, modifiers, name, /*typeParameters*/ undefined, parameters, type, body); } // @api @@ -21700,7 +22132,7 @@ var ts; } // @api function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) { - return createBaseFunctionLikeDeclaration(168 /* SetAccessor */, decorators, modifiers, name, + return createBaseFunctionLikeDeclaration(169 /* SetAccessor */, decorators, modifiers, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); } @@ -21716,7 +22148,7 @@ var ts; } // @api function createCallSignature(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(169 /* CallSignature */, + var node = createBaseSignatureDeclaration(170 /* CallSignature */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); @@ -21733,7 +22165,7 @@ var ts; } // @api function createConstructSignature(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(170 /* ConstructSignature */, + var node = createBaseSignatureDeclaration(171 /* ConstructSignature */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); @@ -21750,7 +22182,7 @@ var ts; } // @api function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createBaseSignatureDeclaration(171 /* IndexSignature */, decorators, modifiers, + var node = createBaseSignatureDeclaration(172 /* IndexSignature */, decorators, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21767,7 +22199,7 @@ var ts; } // @api function createTemplateLiteralTypeSpan(type, literal) { - var node = createBaseNode(194 /* TemplateLiteralTypeSpan */); + var node = createBaseNode(195 /* TemplateLiteralTypeSpan */); node.type = type; node.literal = literal; node.transformFlags = 1 /* ContainsTypeScript */; @@ -21789,7 +22221,7 @@ var ts; } // @api function createTypePredicateNode(assertsModifier, parameterName, type) { - var node = createBaseNode(172 /* TypePredicate */); + var node = createBaseNode(173 /* TypePredicate */); node.assertsModifier = assertsModifier; node.parameterName = asName(parameterName); node.type = type; @@ -21806,7 +22238,7 @@ var ts; } // @api function createTypeReferenceNode(typeName, typeArguments) { - var node = createBaseNode(173 /* TypeReference */); + var node = createBaseNode(174 /* TypeReference */); node.typeName = asName(typeName); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(createNodeArray(typeArguments)); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21821,7 +22253,7 @@ var ts; } // @api function createFunctionTypeNode(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(174 /* FunctionType */, + var node = createBaseSignatureDeclaration(175 /* FunctionType */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); @@ -21847,7 +22279,7 @@ var ts; ts.Debug.fail("Incorrect number of arguments specified."); } function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(175 /* ConstructorType */, + var node = createBaseSignatureDeclaration(176 /* ConstructorType */, /*decorators*/ undefined, modifiers, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21881,7 +22313,7 @@ var ts; } // @api function createTypeQueryNode(exprName) { - var node = createBaseNode(176 /* TypeQuery */); + var node = createBaseNode(177 /* TypeQuery */); node.exprName = exprName; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21894,7 +22326,7 @@ var ts; } // @api function createTypeLiteralNode(members) { - var node = createBaseNode(177 /* TypeLiteral */); + var node = createBaseNode(178 /* TypeLiteral */); node.members = createNodeArray(members); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21907,7 +22339,7 @@ var ts; } // @api function createArrayTypeNode(elementType) { - var node = createBaseNode(178 /* ArrayType */); + var node = createBaseNode(179 /* ArrayType */); node.elementType = parenthesizerRules().parenthesizeElementTypeOfArrayType(elementType); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21920,7 +22352,7 @@ var ts; } // @api function createTupleTypeNode(elements) { - var node = createBaseNode(179 /* TupleType */); + var node = createBaseNode(180 /* TupleType */); node.elements = createNodeArray(elements); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21933,7 +22365,7 @@ var ts; } // @api function createNamedTupleMember(dotDotDotToken, name, questionToken, type) { - var node = createBaseNode(192 /* NamedTupleMember */); + var node = createBaseNode(193 /* NamedTupleMember */); node.dotDotDotToken = dotDotDotToken; node.name = name; node.questionToken = questionToken; @@ -21952,7 +22384,7 @@ var ts; } // @api function createOptionalTypeNode(type) { - var node = createBaseNode(180 /* OptionalType */); + var node = createBaseNode(181 /* OptionalType */); node.type = parenthesizerRules().parenthesizeElementTypeOfArrayType(type); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21965,7 +22397,7 @@ var ts; } // @api function createRestTypeNode(type) { - var node = createBaseNode(181 /* RestType */); + var node = createBaseNode(182 /* RestType */); node.type = type; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21989,7 +22421,7 @@ var ts; } // @api function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(182 /* UnionType */, types); + return createUnionOrIntersectionTypeNode(183 /* UnionType */, types); } // @api function updateUnionTypeNode(node, types) { @@ -21997,7 +22429,7 @@ var ts; } // @api function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(183 /* IntersectionType */, types); + return createUnionOrIntersectionTypeNode(184 /* IntersectionType */, types); } // @api function updateIntersectionTypeNode(node, types) { @@ -22005,7 +22437,7 @@ var ts; } // @api function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { - var node = createBaseNode(184 /* ConditionalType */); + var node = createBaseNode(185 /* ConditionalType */); node.checkType = parenthesizerRules().parenthesizeMemberOfConditionalType(checkType); node.extendsType = parenthesizerRules().parenthesizeMemberOfConditionalType(extendsType); node.trueType = trueType; @@ -22024,7 +22456,7 @@ var ts; } // @api function createInferTypeNode(typeParameter) { - var node = createBaseNode(185 /* InferType */); + var node = createBaseNode(186 /* InferType */); node.typeParameter = typeParameter; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -22037,7 +22469,7 @@ var ts; } // @api function createTemplateLiteralType(head, templateSpans) { - var node = createBaseNode(193 /* TemplateLiteralType */); + var node = createBaseNode(194 /* TemplateLiteralType */); node.head = head; node.templateSpans = createNodeArray(templateSpans); node.transformFlags = 1 /* ContainsTypeScript */; @@ -22053,7 +22485,7 @@ var ts; // @api function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { if (isTypeOf === void 0) { isTypeOf = false; } - var node = createBaseNode(195 /* ImportType */); + var node = createBaseNode(196 /* ImportType */); node.argument = argument; node.qualifier = qualifier; node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); @@ -22073,7 +22505,7 @@ var ts; } // @api function createParenthesizedType(type) { - var node = createBaseNode(186 /* ParenthesizedType */); + var node = createBaseNode(187 /* ParenthesizedType */); node.type = type; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -22086,13 +22518,13 @@ var ts; } // @api function createThisTypeNode() { - var node = createBaseNode(187 /* ThisType */); + var node = createBaseNode(188 /* ThisType */); node.transformFlags = 1 /* ContainsTypeScript */; return node; } // @api function createTypeOperatorNode(operator, type) { - var node = createBaseNode(188 /* TypeOperator */); + var node = createBaseNode(189 /* TypeOperator */); node.operator = operator; node.type = parenthesizerRules().parenthesizeMemberOfElementType(type); node.transformFlags = 1 /* ContainsTypeScript */; @@ -22106,7 +22538,7 @@ var ts; } // @api function createIndexedAccessTypeNode(objectType, indexType) { - var node = createBaseNode(189 /* IndexedAccessType */); + var node = createBaseNode(190 /* IndexedAccessType */); node.objectType = parenthesizerRules().parenthesizeMemberOfElementType(objectType); node.indexType = indexType; node.transformFlags = 1 /* ContainsTypeScript */; @@ -22121,7 +22553,7 @@ var ts; } // @api function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type) { - var node = createBaseNode(190 /* MappedType */); + var node = createBaseNode(191 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.nameType = nameType; @@ -22142,7 +22574,7 @@ var ts; } // @api function createLiteralTypeNode(literal) { - var node = createBaseNode(191 /* LiteralType */); + var node = createBaseNode(192 /* LiteralType */); node.literal = literal; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -22158,16 +22590,16 @@ var ts; // // @api function createObjectBindingPattern(elements) { - var node = createBaseNode(196 /* ObjectBindingPattern */); + var node = createBaseNode(197 /* ObjectBindingPattern */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | - 256 /* ContainsES2015 */ | - 131072 /* ContainsBindingPattern */; - if (node.transformFlags & 8192 /* ContainsRestOrSpread */) { + 512 /* ContainsES2015 */ | + 262144 /* ContainsBindingPattern */; + if (node.transformFlags & 16384 /* ContainsRestOrSpread */) { node.transformFlags |= - 32 /* ContainsES2018 */ | - 16384 /* ContainsObjectRestOrSpread */; + 64 /* ContainsES2018 */ | + 32768 /* ContainsObjectRestOrSpread */; } return node; } @@ -22179,12 +22611,12 @@ var ts; } // @api function createArrayBindingPattern(elements) { - var node = createBaseNode(197 /* ArrayBindingPattern */); + var node = createBaseNode(198 /* ArrayBindingPattern */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | - 256 /* ContainsES2015 */ | - 131072 /* ContainsBindingPattern */; + 512 /* ContainsES2015 */ | + 262144 /* ContainsBindingPattern */; return node; } // @api @@ -22195,21 +22627,21 @@ var ts; } // @api function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createBaseBindingLikeDeclaration(198 /* BindingElement */, + var node = createBaseBindingLikeDeclaration(199 /* BindingElement */, /*decorators*/ undefined, - /*modifiers*/ undefined, name, initializer); + /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; node.transformFlags |= propagateChildFlags(node.dotDotDotToken) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (node.propertyName) { node.transformFlags |= ts.isIdentifier(node.propertyName) ? propagateIdentifierNameFlags(node.propertyName) : propagateChildFlags(node.propertyName); } if (dotDotDotToken) - node.transformFlags |= 8192 /* ContainsRestOrSpread */; + node.transformFlags |= 16384 /* ContainsRestOrSpread */; return node; } // @api @@ -22231,7 +22663,7 @@ var ts; } // @api function createArrayLiteralExpression(elements, multiLine) { - var node = createBaseExpression(199 /* ArrayLiteralExpression */); + var node = createBaseExpression(200 /* ArrayLiteralExpression */); node.elements = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(elements)); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.elements); @@ -22245,7 +22677,7 @@ var ts; } // @api function createObjectLiteralExpression(properties, multiLine) { - var node = createBaseExpression(200 /* ObjectLiteralExpression */); + var node = createBaseExpression(201 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.properties); @@ -22259,7 +22691,7 @@ var ts; } // @api function createPropertyAccessExpression(expression, name) { - var node = createBaseExpression(201 /* PropertyAccessExpression */); + var node = createBaseExpression(202 /* PropertyAccessExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.name = asName(name); node.transformFlags = @@ -22271,8 +22703,8 @@ var ts; // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators node.transformFlags |= - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */; } return node; } @@ -22288,13 +22720,13 @@ var ts; } // @api function createPropertyAccessChain(expression, questionDotToken, name) { - var node = createBaseExpression(201 /* PropertyAccessExpression */); + var node = createBaseExpression(202 /* PropertyAccessExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.questionDotToken = questionDotToken; node.name = asName(name); node.transformFlags |= - 8 /* ContainsES2020 */ | + 16 /* ContainsES2020 */ | propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | (ts.isIdentifier(node.name) ? @@ -22315,7 +22747,7 @@ var ts; } // @api function createElementAccessExpression(expression, index) { - var node = createBaseExpression(202 /* ElementAccessExpression */); + var node = createBaseExpression(203 /* ElementAccessExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.argumentExpression = asExpression(index); node.transformFlags |= @@ -22325,8 +22757,8 @@ var ts; // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators node.transformFlags |= - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */; } return node; } @@ -22342,7 +22774,7 @@ var ts; } // @api function createElementAccessChain(expression, questionDotToken, index) { - var node = createBaseExpression(202 /* ElementAccessExpression */); + var node = createBaseExpression(203 /* ElementAccessExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.questionDotToken = questionDotToken; @@ -22351,7 +22783,7 @@ var ts; propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | propagateChildFlags(node.argumentExpression) | - 8 /* ContainsES2020 */; + 16 /* ContainsES2020 */; return node; } // @api @@ -22367,7 +22799,7 @@ var ts; } // @api function createCallExpression(expression, typeArguments, argumentsArray) { - var node = createBaseExpression(203 /* CallExpression */); + var node = createBaseExpression(204 /* CallExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); @@ -22379,10 +22811,10 @@ var ts; node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.isImportKeyword(node.expression)) { - node.transformFlags |= 2097152 /* ContainsDynamicImport */; + node.transformFlags |= 4194304 /* ContainsDynamicImport */; } else if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 4096 /* ContainsLexicalThis */; + node.transformFlags |= 8192 /* ContainsLexicalThis */; } return node; } @@ -22399,7 +22831,7 @@ var ts; } // @api function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) { - var node = createBaseExpression(203 /* CallExpression */); + var node = createBaseExpression(204 /* CallExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.questionDotToken = questionDotToken; @@ -22410,12 +22842,12 @@ var ts; propagateChildFlags(node.questionDotToken) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | - 8 /* ContainsES2020 */; + 16 /* ContainsES2020 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 4096 /* ContainsLexicalThis */; + node.transformFlags |= 8192 /* ContainsLexicalThis */; } return node; } @@ -22431,7 +22863,7 @@ var ts; } // @api function createNewExpression(expression, typeArguments, argumentsArray) { - var node = createBaseExpression(204 /* NewExpression */); + var node = createBaseExpression(205 /* NewExpression */); node.expression = parenthesizerRules().parenthesizeExpressionOfNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(argumentsArray) : undefined; @@ -22439,7 +22871,7 @@ var ts; propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | - 8 /* ContainsES2020 */; + 16 /* ContainsES2020 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } @@ -22455,7 +22887,7 @@ var ts; } // @api function createTaggedTemplateExpression(tag, typeArguments, template) { - var node = createBaseExpression(205 /* TaggedTemplateExpression */); + var node = createBaseExpression(206 /* TaggedTemplateExpression */); node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag); node.typeArguments = asNodeArray(typeArguments); node.template = template; @@ -22463,12 +22895,12 @@ var ts; propagateChildFlags(node.tag) | propagateChildrenFlags(node.typeArguments) | propagateChildFlags(node.template) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.hasInvalidEscape(node.template)) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } return node; } @@ -22482,7 +22914,7 @@ var ts; } // @api function createTypeAssertion(type, expression) { - var node = createBaseExpression(206 /* TypeAssertionExpression */); + var node = createBaseExpression(207 /* TypeAssertionExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.type = type; node.transformFlags |= @@ -22500,7 +22932,7 @@ var ts; } // @api function createParenthesizedExpression(expression) { - var node = createBaseExpression(207 /* ParenthesizedExpression */); + var node = createBaseExpression(208 /* ParenthesizedExpression */); node.expression = expression; node.transformFlags = propagateChildFlags(node.expression); return node; @@ -22513,7 +22945,7 @@ var ts; } // @api function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(208 /* FunctionExpression */, + var node = createBaseFunctionLikeDeclaration(209 /* FunctionExpression */, /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.asteriskToken); @@ -22522,14 +22954,14 @@ var ts; } if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (node.asteriskToken) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } else { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } } else if (node.asteriskToken) { - node.transformFlags |= 512 /* ContainsGenerator */; + node.transformFlags |= 1024 /* ContainsGenerator */; } return node; } @@ -22547,15 +22979,15 @@ var ts; } // @api function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createBaseFunctionLikeDeclaration(209 /* ArrowFunction */, + var node = createBaseFunctionLikeDeclaration(210 /* ArrowFunction */, /*decorators*/ undefined, modifiers, /*name*/ undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body)); node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* EqualsGreaterThanToken */); node.transformFlags |= propagateChildFlags(node.equalsGreaterThanToken) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } return node; } @@ -22572,7 +23004,7 @@ var ts; } // @api function createDeleteExpression(expression) { - var node = createBaseExpression(210 /* DeleteExpression */); + var node = createBaseExpression(211 /* DeleteExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -22585,7 +23017,7 @@ var ts; } // @api function createTypeOfExpression(expression) { - var node = createBaseExpression(211 /* TypeOfExpression */); + var node = createBaseExpression(212 /* TypeOfExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -22598,7 +23030,7 @@ var ts; } // @api function createVoidExpression(expression) { - var node = createBaseExpression(212 /* VoidExpression */); + var node = createBaseExpression(213 /* VoidExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -22611,13 +23043,13 @@ var ts; } // @api function createAwaitExpression(expression) { - var node = createBaseExpression(213 /* AwaitExpression */); + var node = createBaseExpression(214 /* AwaitExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */ | - 524288 /* ContainsAwait */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */ | + 1048576 /* ContainsAwait */; return node; } // @api @@ -22628,7 +23060,7 @@ var ts; } // @api function createPrefixUnaryExpression(operator, operand) { - var node = createBaseExpression(214 /* PrefixUnaryExpression */); + var node = createBaseExpression(215 /* PrefixUnaryExpression */); node.operator = operator; node.operand = parenthesizerRules().parenthesizeOperandOfPrefixUnary(operand); node.transformFlags |= propagateChildFlags(node.operand); @@ -22642,7 +23074,7 @@ var ts; } // @api function createPostfixUnaryExpression(operand, operator) { - var node = createBaseExpression(215 /* PostfixUnaryExpression */); + var node = createBaseExpression(216 /* PostfixUnaryExpression */); node.operator = operator; node.operand = parenthesizerRules().parenthesizeOperandOfPostfixUnary(operand); node.transformFlags = propagateChildFlags(node.operand); @@ -22656,7 +23088,7 @@ var ts; } // @api function createBinaryExpression(left, operator, right) { - var node = createBaseExpression(216 /* BinaryExpression */); + var node = createBaseExpression(217 /* BinaryExpression */); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = parenthesizerRules().parenthesizeLeftSideOfBinary(operatorKind, left); @@ -22667,45 +23099,45 @@ var ts; propagateChildFlags(node.operatorToken) | propagateChildFlags(node.right); if (operatorKind === 60 /* QuestionQuestionToken */) { - node.transformFlags |= 8 /* ContainsES2020 */; + node.transformFlags |= 16 /* ContainsES2020 */; } else if (operatorKind === 62 /* EqualsToken */) { if (ts.isObjectLiteralExpression(node.left)) { node.transformFlags |= - 256 /* ContainsES2015 */ | - 32 /* ContainsES2018 */ | - 1024 /* ContainsDestructuringAssignment */ | + 512 /* ContainsES2015 */ | + 64 /* ContainsES2018 */ | + 2048 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left); } else if (ts.isArrayLiteralExpression(node.left)) { node.transformFlags |= - 256 /* ContainsES2015 */ | - 1024 /* ContainsDestructuringAssignment */ | + 512 /* ContainsES2015 */ | + 2048 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left); } } else if (operatorKind === 42 /* AsteriskAsteriskToken */ || operatorKind === 66 /* AsteriskAsteriskEqualsToken */) { - node.transformFlags |= 128 /* ContainsES2016 */; + node.transformFlags |= 256 /* ContainsES2016 */; } else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) { - node.transformFlags |= 4 /* ContainsESNext */; + node.transformFlags |= 8 /* ContainsES2021 */; } return node; } function propagateAssignmentPatternFlags(node) { - if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) - return 16384 /* ContainsObjectRestOrSpread */; - if (node.transformFlags & 32 /* ContainsES2018 */) { + if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) + return 32768 /* ContainsObjectRestOrSpread */; + if (node.transformFlags & 64 /* ContainsES2018 */) { // check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c' // will not be correctly interpreted by the ES2018 transformer for (var _i = 0, _a = ts.getElementsOfBindingOrAssignmentPattern(node); _i < _a.length; _i++) { var element = _a[_i]; var target = ts.getTargetOfBindingOrAssignmentElement(element); if (target && ts.isAssignmentPattern(target)) { - if (target.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { - return 16384 /* ContainsObjectRestOrSpread */; + if (target.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { + return 32768 /* ContainsObjectRestOrSpread */; } - if (target.transformFlags & 32 /* ContainsES2018 */) { + if (target.transformFlags & 64 /* ContainsES2018 */) { var flags_1 = propagateAssignmentPatternFlags(target); if (flags_1) return flags_1; @@ -22725,7 +23157,7 @@ var ts; } // @api function createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse) { - var node = createBaseExpression(217 /* ConditionalExpression */); + var node = createBaseExpression(218 /* ConditionalExpression */); node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression(condition); node.questionToken = questionToken !== null && questionToken !== void 0 ? questionToken : createToken(57 /* QuestionToken */); node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue); @@ -22751,13 +23183,13 @@ var ts; } // @api function createTemplateExpression(head, templateSpans) { - var node = createBaseExpression(218 /* TemplateExpression */); + var node = createBaseExpression(219 /* TemplateExpression */); node.head = head; node.templateSpans = createNodeArray(templateSpans); node.transformFlags |= propagateChildFlags(node.head) | propagateChildrenFlags(node.templateSpans) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } // @api @@ -22796,9 +23228,9 @@ var ts; node.text = text; node.rawText = rawText; node.templateFlags = templateFlags & 2048 /* TemplateLiteralLikeFlags */; - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; if (node.templateFlags) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } return node; } @@ -22821,15 +23253,15 @@ var ts; // @api function createYieldExpression(asteriskToken, expression) { ts.Debug.assert(!asteriskToken || !!expression, "A `YieldExpression` with an asteriskToken must have an expression."); - var node = createBaseExpression(219 /* YieldExpression */); + var node = createBaseExpression(220 /* YieldExpression */); node.expression = expression && parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.asteriskToken) | - 256 /* ContainsES2015 */ | - 32 /* ContainsES2018 */ | - 262144 /* ContainsYield */; + 512 /* ContainsES2015 */ | + 64 /* ContainsES2018 */ | + 524288 /* ContainsYield */; return node; } // @api @@ -22841,12 +23273,12 @@ var ts; } // @api function createSpreadElement(expression) { - var node = createBaseExpression(220 /* SpreadElement */); + var node = createBaseExpression(221 /* SpreadElement */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 256 /* ContainsES2015 */ | - 8192 /* ContainsRestOrSpread */; + 512 /* ContainsES2015 */ | + 16384 /* ContainsRestOrSpread */; return node; } // @api @@ -22857,8 +23289,8 @@ var ts; } // @api function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(221 /* ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members); - node.transformFlags |= 256 /* ContainsES2015 */; + var node = createBaseClassLikeDeclaration(222 /* ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members); + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -22874,17 +23306,17 @@ var ts; } // @api function createOmittedExpression() { - return createBaseExpression(222 /* OmittedExpression */); + return createBaseExpression(223 /* OmittedExpression */); } // @api function createExpressionWithTypeArguments(expression, typeArguments) { - var node = createBaseNode(223 /* ExpressionWithTypeArguments */); + var node = createBaseNode(224 /* ExpressionWithTypeArguments */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } // @api @@ -22896,7 +23328,7 @@ var ts; } // @api function createAsExpression(expression, type) { - var node = createBaseExpression(224 /* AsExpression */); + var node = createBaseExpression(225 /* AsExpression */); node.expression = expression; node.type = type; node.transformFlags |= @@ -22914,7 +23346,7 @@ var ts; } // @api function createNonNullExpression(expression) { - var node = createBaseExpression(225 /* NonNullExpression */); + var node = createBaseExpression(226 /* NonNullExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.transformFlags |= propagateChildFlags(node.expression) | @@ -22932,7 +23364,7 @@ var ts; } // @api function createNonNullChain(expression) { - var node = createBaseExpression(225 /* NonNullExpression */); + var node = createBaseExpression(226 /* NonNullExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.transformFlags |= @@ -22949,13 +23381,13 @@ var ts; } // @api function createMetaProperty(keywordToken, name) { - var node = createBaseExpression(226 /* MetaProperty */); + var node = createBaseExpression(227 /* MetaProperty */); node.keywordToken = keywordToken; node.name = name; node.transformFlags |= propagateChildFlags(node.name); switch (keywordToken) { case 102 /* NewKeyword */: - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; break; case 99 /* ImportKeyword */: node.transformFlags |= 4 /* ContainsESNext */; @@ -22976,13 +23408,13 @@ var ts; // // @api function createTemplateSpan(expression, literal) { - var node = createBaseNode(228 /* TemplateSpan */); + var node = createBaseNode(229 /* TemplateSpan */); node.expression = expression; node.literal = literal; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.literal) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } // @api @@ -22994,8 +23426,8 @@ var ts; } // @api function createSemicolonClassElement() { - var node = createBaseNode(229 /* SemicolonClassElement */); - node.transformFlags |= 256 /* ContainsES2015 */; + var node = createBaseNode(230 /* SemicolonClassElement */); + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @@ -23003,7 +23435,7 @@ var ts; // // @api function createBlock(statements, multiLine) { - var node = createBaseNode(230 /* Block */); + var node = createBaseNode(231 /* Block */); node.statements = createNodeArray(statements); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.statements); @@ -23017,7 +23449,7 @@ var ts; } // @api function createVariableStatement(modifiers, declarationList) { - var node = createBaseDeclaration(232 /* VariableStatement */, /*decorators*/ undefined, modifiers); + var node = createBaseDeclaration(233 /* VariableStatement */, /*decorators*/ undefined, modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; node.transformFlags |= propagateChildFlags(node.declarationList); @@ -23035,11 +23467,11 @@ var ts; } // @api function createEmptyStatement() { - return createBaseNode(231 /* EmptyStatement */); + return createBaseNode(232 /* EmptyStatement */); } // @api function createExpressionStatement(expression) { - var node = createBaseNode(233 /* ExpressionStatement */); + var node = createBaseNode(234 /* ExpressionStatement */); node.expression = parenthesizerRules().parenthesizeExpressionOfExpressionStatement(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -23052,7 +23484,7 @@ var ts; } // @api function createIfStatement(expression, thenStatement, elseStatement) { - var node = createBaseNode(234 /* IfStatement */); + var node = createBaseNode(235 /* IfStatement */); node.expression = expression; node.thenStatement = asEmbeddedStatement(thenStatement); node.elseStatement = asEmbeddedStatement(elseStatement); @@ -23072,7 +23504,7 @@ var ts; } // @api function createDoStatement(statement, expression) { - var node = createBaseNode(235 /* DoStatement */); + var node = createBaseNode(236 /* DoStatement */); node.statement = asEmbeddedStatement(statement); node.expression = expression; node.transformFlags |= @@ -23089,7 +23521,7 @@ var ts; } // @api function createWhileStatement(expression, statement) { - var node = createBaseNode(236 /* WhileStatement */); + var node = createBaseNode(237 /* WhileStatement */); node.expression = expression; node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -23106,7 +23538,7 @@ var ts; } // @api function createForStatement(initializer, condition, incrementor, statement) { - var node = createBaseNode(237 /* ForStatement */); + var node = createBaseNode(238 /* ForStatement */); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -23129,7 +23561,7 @@ var ts; } // @api function createForInStatement(initializer, expression, statement) { - var node = createBaseNode(238 /* ForInStatement */); + var node = createBaseNode(239 /* ForInStatement */); node.initializer = initializer; node.expression = expression; node.statement = asEmbeddedStatement(statement); @@ -23149,7 +23581,7 @@ var ts; } // @api function createForOfStatement(awaitModifier, initializer, expression, statement) { - var node = createBaseNode(239 /* ForOfStatement */); + var node = createBaseNode(240 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); @@ -23159,9 +23591,9 @@ var ts; propagateChildFlags(node.initializer) | propagateChildFlags(node.expression) | propagateChildFlags(node.statement) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (awaitModifier) - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; return node; } // @api @@ -23175,11 +23607,11 @@ var ts; } // @api function createContinueStatement(label) { - var node = createBaseNode(240 /* ContinueStatement */); + var node = createBaseNode(241 /* ContinueStatement */); node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -23190,11 +23622,11 @@ var ts; } // @api function createBreakStatement(label) { - var node = createBaseNode(241 /* BreakStatement */); + var node = createBaseNode(242 /* BreakStatement */); node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -23205,13 +23637,13 @@ var ts; } // @api function createReturnStatement(expression) { - var node = createBaseNode(242 /* ReturnStatement */); + var node = createBaseNode(243 /* ReturnStatement */); node.expression = expression; // return in an ES2018 async generator must be awaited node.transformFlags |= propagateChildFlags(node.expression) | - 32 /* ContainsES2018 */ | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 64 /* ContainsES2018 */ | + 2097152 /* ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -23222,7 +23654,7 @@ var ts; } // @api function createWithStatement(expression, statement) { - var node = createBaseNode(243 /* WithStatement */); + var node = createBaseNode(244 /* WithStatement */); node.expression = expression; node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -23239,7 +23671,7 @@ var ts; } // @api function createSwitchStatement(expression, caseBlock) { - var node = createBaseNode(244 /* SwitchStatement */); + var node = createBaseNode(245 /* SwitchStatement */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.caseBlock = caseBlock; node.transformFlags |= @@ -23256,7 +23688,7 @@ var ts; } // @api function createLabeledStatement(label, statement) { - var node = createBaseNode(245 /* LabeledStatement */); + var node = createBaseNode(246 /* LabeledStatement */); node.label = asName(label); node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -23273,7 +23705,7 @@ var ts; } // @api function createThrowStatement(expression) { - var node = createBaseNode(246 /* ThrowStatement */); + var node = createBaseNode(247 /* ThrowStatement */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -23286,7 +23718,7 @@ var ts; } // @api function createTryStatement(tryBlock, catchClause, finallyBlock) { - var node = createBaseNode(247 /* TryStatement */); + var node = createBaseNode(248 /* TryStatement */); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -23306,11 +23738,11 @@ var ts; } // @api function createDebuggerStatement() { - return createBaseNode(248 /* DebuggerStatement */); + return createBaseNode(249 /* DebuggerStatement */); } // @api function createVariableDeclaration(name, exclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(249 /* VariableDeclaration */, + var node = createBaseVariableLikeDeclaration(250 /* VariableDeclaration */, /*decorators*/ undefined, /*modifiers*/ undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.exclamationToken = exclamationToken; @@ -23332,16 +23764,16 @@ var ts; // @api function createVariableDeclarationList(declarations, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createBaseNode(250 /* VariableDeclarationList */); + var node = createBaseNode(251 /* VariableDeclarationList */); node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); node.transformFlags |= propagateChildrenFlags(node.declarations) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; if (flags & 3 /* BlockScoped */) { node.transformFlags |= - 256 /* ContainsES2015 */ | - 65536 /* ContainsBlockScopedBinding */; + 512 /* ContainsES2015 */ | + 131072 /* ContainsBlockScopedBinding */; } return node; } @@ -23353,7 +23785,7 @@ var ts; } // @api function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(251 /* FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(252 /* FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; if (!node.body || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) { node.transformFlags = 1 /* ContainsTypeScript */; @@ -23361,17 +23793,17 @@ var ts; else { node.transformFlags |= propagateChildFlags(node.asteriskToken) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (node.asteriskToken) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } else { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } } else if (node.asteriskToken) { - node.transformFlags |= 512 /* ContainsGenerator */; + node.transformFlags |= 1024 /* ContainsGenerator */; } } return node; @@ -23391,13 +23823,13 @@ var ts; } // @api function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(252 /* ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members); + var node = createBaseClassLikeDeclaration(253 /* ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members); if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) { node.transformFlags = 1 /* ContainsTypeScript */; } else { - node.transformFlags |= 256 /* ContainsES2015 */; - if (node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */) { + node.transformFlags |= 512 /* ContainsES2015 */; + if (node.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */) { node.transformFlags |= 1 /* ContainsTypeScript */; } } @@ -23416,7 +23848,7 @@ var ts; } // @api function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(253 /* InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses); + var node = createBaseInterfaceOrClassLikeDeclaration(254 /* InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -23434,7 +23866,7 @@ var ts; } // @api function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createBaseGenericNamedDeclaration(254 /* TypeAliasDeclaration */, decorators, modifiers, name, typeParameters); + var node = createBaseGenericNamedDeclaration(255 /* TypeAliasDeclaration */, decorators, modifiers, name, typeParameters); node.type = type; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -23451,12 +23883,12 @@ var ts; } // @api function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createBaseNamedDeclaration(255 /* EnumDeclaration */, decorators, modifiers, name); + var node = createBaseNamedDeclaration(256 /* EnumDeclaration */, decorators, modifiers, name); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members) | 1 /* ContainsTypeScript */; - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` return node; } // @api @@ -23471,7 +23903,7 @@ var ts; // @api function createModuleDeclaration(decorators, modifiers, name, body, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createBaseDeclaration(256 /* ModuleDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(257 /* ModuleDeclaration */, decorators, modifiers); node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 1024 /* GlobalAugmentation */); node.name = name; node.body = body; @@ -23484,7 +23916,7 @@ var ts; propagateChildFlags(node.body) | 1 /* ContainsTypeScript */; } - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. return node; } // @api @@ -23498,7 +23930,7 @@ var ts; } // @api function createModuleBlock(statements) { - var node = createBaseNode(257 /* ModuleBlock */); + var node = createBaseNode(258 /* ModuleBlock */); node.statements = createNodeArray(statements); node.transformFlags |= propagateChildrenFlags(node.statements); return node; @@ -23511,7 +23943,7 @@ var ts; } // @api function createCaseBlock(clauses) { - var node = createBaseNode(258 /* CaseBlock */); + var node = createBaseNode(259 /* CaseBlock */); node.clauses = createNodeArray(clauses); node.transformFlags |= propagateChildrenFlags(node.clauses); return node; @@ -23524,7 +23956,7 @@ var ts; } // @api function createNamespaceExportDeclaration(name) { - var node = createBaseNamedDeclaration(259 /* NamespaceExportDeclaration */, + var node = createBaseNamedDeclaration(260 /* NamespaceExportDeclaration */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.transformFlags = 1 /* ContainsTypeScript */; @@ -23538,13 +23970,13 @@ var ts; } // @api function createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference) { - var node = createBaseNamedDeclaration(260 /* ImportEqualsDeclaration */, decorators, modifiers, name); + var node = createBaseNamedDeclaration(261 /* ImportEqualsDeclaration */, decorators, modifiers, name); node.isTypeOnly = isTypeOnly; node.moduleReference = moduleReference; node.transformFlags |= propagateChildFlags(node.moduleReference); if (!ts.isExternalModuleReference(node.moduleReference)) node.transformFlags |= 1 /* ContainsTypeScript */; - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context return node; } // @api @@ -23559,13 +23991,13 @@ var ts; } // @api function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createBaseDeclaration(261 /* ImportDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(262 /* ImportDeclaration */, decorators, modifiers); node.importClause = importClause; node.moduleSpecifier = moduleSpecifier; node.transformFlags |= propagateChildFlags(node.importClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23579,7 +24011,7 @@ var ts; } // @api function createImportClause(isTypeOnly, name, namedBindings) { - var node = createBaseNode(262 /* ImportClause */); + var node = createBaseNode(263 /* ImportClause */); node.isTypeOnly = isTypeOnly; node.name = name; node.namedBindings = namedBindings; @@ -23589,7 +24021,7 @@ var ts; if (isTypeOnly) { node.transformFlags |= 1 /* ContainsTypeScript */; } - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23602,10 +24034,10 @@ var ts; } // @api function createNamespaceImport(name) { - var node = createBaseNode(263 /* NamespaceImport */); + var node = createBaseNode(264 /* NamespaceImport */); node.name = name; node.transformFlags |= propagateChildFlags(node.name); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23616,12 +24048,12 @@ var ts; } // @api function createNamespaceExport(name) { - var node = createBaseNode(269 /* NamespaceExport */); + var node = createBaseNode(270 /* NamespaceExport */); node.name = name; node.transformFlags |= propagateChildFlags(node.name) | 4 /* ContainsESNext */; - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23632,10 +24064,10 @@ var ts; } // @api function createNamedImports(elements) { - var node = createBaseNode(264 /* NamedImports */); + var node = createBaseNode(265 /* NamedImports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23646,13 +24078,13 @@ var ts; } // @api function createImportSpecifier(propertyName, name) { - var node = createBaseNode(265 /* ImportSpecifier */); + var node = createBaseNode(266 /* ImportSpecifier */); node.propertyName = propertyName; node.name = name; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23664,13 +24096,13 @@ var ts; } // @api function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createBaseDeclaration(266 /* ExportAssignment */, decorators, modifiers); + var node = createBaseDeclaration(267 /* ExportAssignment */, decorators, modifiers); node.isExportEquals = isExportEquals; node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary(62 /* EqualsToken */, /*leftSide*/ undefined, expression) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23683,14 +24115,14 @@ var ts; } // @api function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier) { - var node = createBaseDeclaration(267 /* ExportDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(268 /* ExportDeclaration */, decorators, modifiers); node.isTypeOnly = isTypeOnly; node.exportClause = exportClause; node.moduleSpecifier = moduleSpecifier; node.transformFlags |= propagateChildFlags(node.exportClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23705,10 +24137,10 @@ var ts; } // @api function createNamedExports(elements) { - var node = createBaseNode(268 /* NamedExports */); + var node = createBaseNode(269 /* NamedExports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23719,13 +24151,13 @@ var ts; } // @api function createExportSpecifier(propertyName, name) { - var node = createBaseNode(270 /* ExportSpecifier */); + var node = createBaseNode(271 /* ExportSpecifier */); node.propertyName = asName(propertyName); node.name = asName(name); node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23737,7 +24169,7 @@ var ts; } // @api function createMissingDeclaration() { - var node = createBaseDeclaration(271 /* MissingDeclaration */, + var node = createBaseDeclaration(272 /* MissingDeclaration */, /*decorators*/ undefined, /*modifiers*/ undefined); return node; @@ -23747,10 +24179,10 @@ var ts; // // @api function createExternalModuleReference(expression) { - var node = createBaseNode(272 /* ExternalModuleReference */); + var node = createBaseNode(273 /* ExternalModuleReference */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23792,7 +24224,7 @@ var ts; } // @api function createJSDocFunctionType(parameters, type) { - var node = createBaseSignatureDeclaration(308 /* JSDocFunctionType */, + var node = createBaseSignatureDeclaration(309 /* JSDocFunctionType */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, @@ -23809,7 +24241,7 @@ var ts; // @api function createJSDocTypeLiteral(propertyTags, isArrayType) { if (isArrayType === void 0) { isArrayType = false; } - var node = createBaseNode(312 /* JSDocTypeLiteral */); + var node = createBaseNode(314 /* JSDocTypeLiteral */); node.jsDocPropertyTags = asNodeArray(propertyTags); node.isArrayType = isArrayType; return node; @@ -23823,7 +24255,7 @@ var ts; } // @api function createJSDocTypeExpression(type) { - var node = createBaseNode(301 /* JSDocTypeExpression */); + var node = createBaseNode(302 /* JSDocTypeExpression */); node.type = type; return node; } @@ -23835,7 +24267,7 @@ var ts; } // @api function createJSDocSignature(typeParameters, parameters, type) { - var node = createBaseNode(313 /* JSDocSignature */); + var node = createBaseNode(315 /* JSDocSignature */); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; @@ -23864,7 +24296,7 @@ var ts; } // @api function createJSDocTemplateTag(tagName, constraint, typeParameters, comment) { - var node = createBaseJSDocTag(330 /* JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment); + var node = createBaseJSDocTag(334 /* JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment); node.constraint = constraint; node.typeParameters = createNodeArray(typeParameters); return node; @@ -23881,7 +24313,7 @@ var ts; } // @api function createJSDocTypedefTag(tagName, typeExpression, fullName, comment) { - var node = createBaseJSDocTag(331 /* JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment); + var node = createBaseJSDocTag(335 /* JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment); node.typeExpression = typeExpression; node.fullName = fullName; node.name = ts.getJSDocTypeAliasName(fullName); @@ -23899,7 +24331,7 @@ var ts; } // @api function createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { - var node = createBaseJSDocTag(326 /* JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment); + var node = createBaseJSDocTag(330 /* JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -23920,7 +24352,7 @@ var ts; } // @api function createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { - var node = createBaseJSDocTag(333 /* JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment); + var node = createBaseJSDocTag(337 /* JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -23941,7 +24373,7 @@ var ts; } // @api function createJSDocCallbackTag(tagName, typeExpression, fullName, comment) { - var node = createBaseJSDocTag(324 /* JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment); + var node = createBaseJSDocTag(328 /* JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment); node.typeExpression = typeExpression; node.fullName = fullName; node.name = ts.getJSDocTypeAliasName(fullName); @@ -23959,7 +24391,7 @@ var ts; } // @api function createJSDocAugmentsTag(tagName, className, comment) { - var node = createBaseJSDocTag(315 /* JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment); + var node = createBaseJSDocTag(318 /* JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment); node.class = className; return node; } @@ -23974,13 +24406,13 @@ var ts; } // @api function createJSDocImplementsTag(tagName, className, comment) { - var node = createBaseJSDocTag(316 /* JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment); + var node = createBaseJSDocTag(319 /* JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment); node.class = className; return node; } // @api function createJSDocSeeTag(tagName, name, comment) { - var node = createBaseJSDocTag(332 /* JSDocSeeTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment); + var node = createBaseJSDocTag(336 /* JSDocSeeTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment); node.name = name; return node; } @@ -23994,7 +24426,7 @@ var ts; } // @api function createJSDocNameReference(name) { - var node = createBaseNode(302 /* JSDocNameReference */); + var node = createBaseNode(303 /* JSDocNameReference */); node.name = name; return node; } @@ -24005,6 +24437,19 @@ var ts; : node; } // @api + function createJSDocLink(name, text) { + var node = createBaseNode(316 /* JSDocLink */); + node.name = name; + node.text = text; + return node; + } + // @api + function updateJSDocLink(node, name, text) { + return node.name !== name + ? update(createJSDocLink(name, text), node) + : node; + } + // @api function updateJSDocImplementsTag(node, tagName, className, comment) { if (tagName === void 0) { tagName = getDefaultTagName(node); } return node.tagName !== tagName @@ -24065,7 +24510,7 @@ var ts; } // @api function createJSDocUnknownTag(tagName, comment) { - var node = createBaseJSDocTag(314 /* JSDocTag */, tagName, comment); + var node = createBaseJSDocTag(317 /* JSDocTag */, tagName, comment); return node; } // @api @@ -24076,8 +24521,20 @@ var ts; : node; } // @api + function createJSDocText(text) { + var node = createBaseNode(313 /* JSDocText */); + node.text = text; + return node; + } + // @api + function updateJSDocText(node, text) { + return node.text !== text + ? update(createJSDocText(text), node) + : node; + } + // @api function createJSDocComment(comment, tags) { - var node = createBaseNode(311 /* JSDocComment */); + var node = createBaseNode(312 /* JSDocComment */); node.comment = comment; node.tags = asNodeArray(tags); return node; @@ -24094,7 +24551,7 @@ var ts; // // @api function createJsxElement(openingElement, children, closingElement) { - var node = createBaseNode(273 /* JsxElement */); + var node = createBaseNode(274 /* JsxElement */); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -24115,7 +24572,7 @@ var ts; } // @api function createJsxSelfClosingElement(tagName, typeArguments, attributes) { - var node = createBaseNode(274 /* JsxSelfClosingElement */); + var node = createBaseNode(275 /* JsxSelfClosingElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -24139,7 +24596,7 @@ var ts; } // @api function createJsxOpeningElement(tagName, typeArguments, attributes) { - var node = createBaseNode(275 /* JsxOpeningElement */); + var node = createBaseNode(276 /* JsxOpeningElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -24163,7 +24620,7 @@ var ts; } // @api function createJsxClosingElement(tagName) { - var node = createBaseNode(276 /* JsxClosingElement */); + var node = createBaseNode(277 /* JsxClosingElement */); node.tagName = tagName; node.transformFlags |= propagateChildFlags(node.tagName) | @@ -24178,7 +24635,7 @@ var ts; } // @api function createJsxFragment(openingFragment, children, closingFragment) { - var node = createBaseNode(277 /* JsxFragment */); + var node = createBaseNode(278 /* JsxFragment */); node.openingFragment = openingFragment; node.children = createNodeArray(children); node.closingFragment = closingFragment; @@ -24214,19 +24671,19 @@ var ts; } // @api function createJsxOpeningFragment() { - var node = createBaseNode(278 /* JsxOpeningFragment */); + var node = createBaseNode(279 /* JsxOpeningFragment */); node.transformFlags |= 2 /* ContainsJsx */; return node; } // @api function createJsxJsxClosingFragment() { - var node = createBaseNode(279 /* JsxClosingFragment */); + var node = createBaseNode(280 /* JsxClosingFragment */); node.transformFlags |= 2 /* ContainsJsx */; return node; } // @api function createJsxAttribute(name, initializer) { - var node = createBaseNode(280 /* JsxAttribute */); + var node = createBaseNode(281 /* JsxAttribute */); node.name = name; node.initializer = initializer; node.transformFlags |= @@ -24244,7 +24701,7 @@ var ts; } // @api function createJsxAttributes(properties) { - var node = createBaseNode(281 /* JsxAttributes */); + var node = createBaseNode(282 /* JsxAttributes */); node.properties = createNodeArray(properties); node.transformFlags |= propagateChildrenFlags(node.properties) | @@ -24259,7 +24716,7 @@ var ts; } // @api function createJsxSpreadAttribute(expression) { - var node = createBaseNode(282 /* JsxSpreadAttribute */); + var node = createBaseNode(283 /* JsxSpreadAttribute */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression) | @@ -24274,7 +24731,7 @@ var ts; } // @api function createJsxExpression(dotDotDotToken, expression) { - var node = createBaseNode(283 /* JsxExpression */); + var node = createBaseNode(284 /* JsxExpression */); node.dotDotDotToken = dotDotDotToken; node.expression = expression; node.transformFlags |= @@ -24294,7 +24751,7 @@ var ts; // // @api function createCaseClause(expression, statements) { - var node = createBaseNode(284 /* CaseClause */); + var node = createBaseNode(285 /* CaseClause */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.statements = createNodeArray(statements); node.transformFlags |= @@ -24311,7 +24768,7 @@ var ts; } // @api function createDefaultClause(statements) { - var node = createBaseNode(285 /* DefaultClause */); + var node = createBaseNode(286 /* DefaultClause */); node.statements = createNodeArray(statements); node.transformFlags = propagateChildrenFlags(node.statements); return node; @@ -24324,13 +24781,13 @@ var ts; } // @api function createHeritageClause(token, types) { - var node = createBaseNode(286 /* HeritageClause */); + var node = createBaseNode(287 /* HeritageClause */); node.token = token; node.types = createNodeArray(types); node.transformFlags |= propagateChildrenFlags(node.types); switch (token) { case 93 /* ExtendsKeyword */: - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; break; case 116 /* ImplementsKeyword */: node.transformFlags |= 1 /* ContainsTypeScript */; @@ -24348,7 +24805,7 @@ var ts; } // @api function createCatchClause(variableDeclaration, block) { - var node = createBaseNode(287 /* CatchClause */); + var node = createBaseNode(288 /* CatchClause */); variableDeclaration = !ts.isString(variableDeclaration) ? variableDeclaration : createVariableDeclaration(variableDeclaration, /*exclamationToken*/ undefined, /*type*/ undefined, @@ -24359,7 +24816,7 @@ var ts; propagateChildFlags(node.variableDeclaration) | propagateChildFlags(node.block); if (!variableDeclaration) - node.transformFlags |= 16 /* ContainsES2019 */; + node.transformFlags |= 32 /* ContainsES2019 */; return node; } // @api @@ -24374,7 +24831,7 @@ var ts; // // @api function createPropertyAssignment(name, initializer) { - var node = createBaseNamedDeclaration(288 /* PropertyAssignment */, + var node = createBaseNamedDeclaration(289 /* PropertyAssignment */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); @@ -24404,13 +24861,13 @@ var ts; } // @api function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createBaseNamedDeclaration(289 /* ShorthandPropertyAssignment */, + var node = createBaseNamedDeclaration(290 /* ShorthandPropertyAssignment */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); node.transformFlags |= propagateChildFlags(node.objectAssignmentInitializer) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } function finishUpdateShorthandPropertyAssignment(updated, original) { @@ -24436,12 +24893,12 @@ var ts; } // @api function createSpreadAssignment(expression) { - var node = createBaseNode(290 /* SpreadAssignment */); + var node = createBaseNode(291 /* SpreadAssignment */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 32 /* ContainsES2018 */ | - 16384 /* ContainsObjectRestOrSpread */; + 64 /* ContainsES2018 */ | + 32768 /* ContainsObjectRestOrSpread */; return node; } // @api @@ -24455,7 +24912,7 @@ var ts; // // @api function createEnumMember(name, initializer) { - var node = createBaseNode(291 /* EnumMember */); + var node = createBaseNode(292 /* EnumMember */); node.name = asName(name); node.initializer = initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); node.transformFlags |= @@ -24476,7 +24933,7 @@ var ts; // // @api function createSourceFile(statements, endOfFileToken, flags) { - var node = baseFactory.createBaseSourceFileNode(297 /* SourceFile */); + var node = baseFactory.createBaseSourceFileNode(298 /* SourceFile */); node.statements = createNodeArray(statements); node.endOfFileToken = endOfFileToken; node.flags |= flags; @@ -24493,7 +24950,7 @@ var ts; return node; } function cloneSourceFileWithChanges(source, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) { - var node = baseFactory.createBaseSourceFileNode(297 /* SourceFile */); + var node = baseFactory.createBaseSourceFileNode(298 /* SourceFile */); for (var p in source) { if (p === "emitNode" || ts.hasProperty(node, p) || !ts.hasProperty(source, p)) continue; @@ -24531,7 +24988,7 @@ var ts; // @api function createBundle(sourceFiles, prepends) { if (prepends === void 0) { prepends = ts.emptyArray; } - var node = createBaseNode(298 /* Bundle */); + var node = createBaseNode(299 /* Bundle */); node.prepends = prepends; node.sourceFiles = sourceFiles; return node; @@ -24546,7 +25003,7 @@ var ts; } // @api function createUnparsedSource(prologues, syntheticReferences, texts) { - var node = createBaseNode(299 /* UnparsedSource */); + var node = createBaseNode(300 /* UnparsedSource */); node.prologues = prologues; node.syntheticReferences = syntheticReferences; node.texts = texts; @@ -24564,28 +25021,28 @@ var ts; } // @api function createUnparsedPrologue(data) { - return createBaseUnparsedNode(292 /* UnparsedPrologue */, data); + return createBaseUnparsedNode(293 /* UnparsedPrologue */, data); } // @api function createUnparsedPrepend(data, texts) { - var node = createBaseUnparsedNode(293 /* UnparsedPrepend */, data); + var node = createBaseUnparsedNode(294 /* UnparsedPrepend */, data); node.texts = texts; return node; } // @api function createUnparsedTextLike(data, internal) { - return createBaseUnparsedNode(internal ? 295 /* UnparsedInternalText */ : 294 /* UnparsedText */, data); + return createBaseUnparsedNode(internal ? 296 /* UnparsedInternalText */ : 295 /* UnparsedText */, data); } // @api function createUnparsedSyntheticReference(section) { - var node = createBaseNode(296 /* UnparsedSyntheticReference */); + var node = createBaseNode(297 /* UnparsedSyntheticReference */); node.data = section.data; node.section = section; return node; } // @api function createInputFiles() { - var node = createBaseNode(300 /* InputFiles */); + var node = createBaseNode(301 /* InputFiles */); node.javascriptText = ""; node.declarationText = ""; return node; @@ -24596,7 +25053,7 @@ var ts; // @api function createSyntheticExpression(type, isSpread, tupleNameSource) { if (isSpread === void 0) { isSpread = false; } - var node = createBaseNode(227 /* SyntheticExpression */); + var node = createBaseNode(228 /* SyntheticExpression */); node.type = type; node.isSpread = isSpread; node.tupleNameSource = tupleNameSource; @@ -24604,7 +25061,7 @@ var ts; } // @api function createSyntaxList(children) { - var node = createBaseNode(334 /* SyntaxList */); + var node = createBaseNode(338 /* SyntaxList */); node._children = children; return node; } @@ -24619,7 +25076,7 @@ var ts; */ // @api function createNotEmittedStatement(original) { - var node = createBaseNode(335 /* NotEmittedStatement */); + var node = createBaseNode(339 /* NotEmittedStatement */); node.original = original; ts.setTextRange(node, original); return node; @@ -24633,7 +25090,7 @@ var ts; */ // @api function createPartiallyEmittedExpression(expression, original) { - var node = createBaseNode(336 /* PartiallyEmittedExpression */); + var node = createBaseNode(340 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; node.transformFlags |= @@ -24661,7 +25118,7 @@ var ts; } // @api function createCommaListExpression(elements) { - var node = createBaseNode(337 /* CommaListExpression */); + var node = createBaseNode(341 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); node.transformFlags |= propagateChildrenFlags(node.elements); return node; @@ -24678,7 +25135,7 @@ var ts; */ // @api function createEndOfDeclarationMarker(original) { - var node = createBaseNode(339 /* EndOfDeclarationMarker */); + var node = createBaseNode(343 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -24689,14 +25146,14 @@ var ts; */ // @api function createMergeDeclarationMarker(original) { - var node = createBaseNode(338 /* MergeDeclarationMarker */); + var node = createBaseNode(342 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; } // @api function createSyntheticReferenceExpression(expression, thisArg) { - var node = createBaseNode(340 /* SyntheticReferenceExpression */); + var node = createBaseNode(344 /* SyntheticReferenceExpression */); node.expression = expression; node.thisArg = thisArg; node.transformFlags |= @@ -24718,7 +25175,7 @@ var ts; if (node === undefined) { return node; } - var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(297 /* SourceFile */) : + var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(298 /* SourceFile */) : ts.isIdentifier(node) ? baseFactory.createBaseIdentifierNode(78 /* Identifier */) : ts.isPrivateIdentifier(node) ? baseFactory.createBasePrivateIdentifierNode(79 /* PrivateIdentifier */) : !ts.isNodeKind(node.kind) ? baseFactory.createBaseTokenNode(node.kind) : @@ -24825,11 +25282,11 @@ var ts; } function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 207 /* ParenthesizedExpression */: return updateParenthesizedExpression(outerExpression, expression); - case 206 /* TypeAssertionExpression */: return updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 224 /* AsExpression */: return updateAsExpression(outerExpression, expression, outerExpression.type); - case 225 /* NonNullExpression */: return updateNonNullExpression(outerExpression, expression); - case 336 /* PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression); + case 208 /* ParenthesizedExpression */: return updateParenthesizedExpression(outerExpression, expression); + case 207 /* TypeAssertionExpression */: return updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 225 /* AsExpression */: return updateAsExpression(outerExpression, expression, outerExpression.type); + case 226 /* NonNullExpression */: return updateNonNullExpression(outerExpression, expression); + case 340 /* PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -24883,13 +25340,13 @@ var ts; case 9 /* BigIntLiteral */: case 10 /* StringLiteral */: return false; - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return target.properties.length > 0; default: return true; @@ -25292,23 +25749,24 @@ var ts; } function getDefaultTagNameForKind(kind) { switch (kind) { - case 329 /* JSDocTypeTag */: return "type"; - case 327 /* JSDocReturnTag */: return "returns"; - case 328 /* JSDocThisTag */: return "this"; - case 325 /* JSDocEnumTag */: return "enum"; - case 317 /* JSDocAuthorTag */: return "author"; - case 319 /* JSDocClassTag */: return "class"; - case 320 /* JSDocPublicTag */: return "public"; - case 321 /* JSDocPrivateTag */: return "private"; - case 322 /* JSDocProtectedTag */: return "protected"; - case 323 /* JSDocReadonlyTag */: return "readonly"; - case 330 /* JSDocTemplateTag */: return "template"; - case 331 /* JSDocTypedefTag */: return "typedef"; - case 326 /* JSDocParameterTag */: return "param"; - case 333 /* JSDocPropertyTag */: return "prop"; - case 324 /* JSDocCallbackTag */: return "callback"; - case 315 /* JSDocAugmentsTag */: return "augments"; - case 316 /* JSDocImplementsTag */: return "implements"; + case 333 /* JSDocTypeTag */: return "type"; + case 331 /* JSDocReturnTag */: return "returns"; + case 332 /* JSDocThisTag */: return "this"; + case 329 /* JSDocEnumTag */: return "enum"; + case 320 /* JSDocAuthorTag */: return "author"; + case 322 /* JSDocClassTag */: return "class"; + case 323 /* JSDocPublicTag */: return "public"; + case 324 /* JSDocPrivateTag */: return "private"; + case 325 /* JSDocProtectedTag */: return "protected"; + case 326 /* JSDocReadonlyTag */: return "readonly"; + case 327 /* JSDocOverrideTag */: return "override"; + case 334 /* JSDocTemplateTag */: return "template"; + case 335 /* JSDocTypedefTag */: return "typedef"; + case 330 /* JSDocParameterTag */: return "param"; + case 337 /* JSDocPropertyTag */: return "prop"; + case 328 /* JSDocCallbackTag */: return "callback"; + case 318 /* JSDocAugmentsTag */: return "augments"; + case 319 /* JSDocImplementsTag */: return "implements"; default: return ts.Debug.fail("Unsupported kind: " + ts.Debug.formatSyntaxKind(kind)); } @@ -25361,10 +25819,10 @@ var ts; } function propagateIdentifierNameFlags(node) { // An IdentifierName is allowed to be `await` - return propagateChildFlags(node) & ~8388608 /* ContainsPossibleTopLevelAwait */; + return propagateChildFlags(node) & ~16777216 /* ContainsPossibleTopLevelAwait */; } function propagatePropertyNameFlagsOfChild(node, transformFlags) { - return transformFlags | (node.transformFlags & 4096 /* PropertyNamePropagatingFlags */); + return transformFlags | (node.transformFlags & 8192 /* PropertyNamePropagatingFlags */); } function propagateChildFlags(child) { if (!child) @@ -25388,36 +25846,36 @@ var ts; */ /* @internal */ function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 172 /* FirstTypeNode */ && kind <= 195 /* LastTypeNode */) { + if (kind >= 173 /* FirstTypeNode */ && kind <= 196 /* LastTypeNode */) { return -2 /* TypeExcludes */; } switch (kind) { - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 199 /* ArrayLiteralExpression */: - return 536879104 /* ArrayLiteralOrCallOrNewExcludes */; - case 256 /* ModuleDeclaration */: - return 546379776 /* ModuleExcludes */; - case 160 /* Parameter */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 200 /* ArrayLiteralExpression */: + return 536887296 /* ArrayLiteralOrCallOrNewExcludes */; + case 257 /* ModuleDeclaration */: + return 555888640 /* ModuleExcludes */; + case 161 /* Parameter */: return 536870912 /* ParameterExcludes */; - case 209 /* ArrowFunction */: - return 547309568 /* ArrowFunctionExcludes */; - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - return 547313664 /* FunctionExcludes */; - case 250 /* VariableDeclarationList */: - return 537018368 /* VariableDeclarationListExcludes */; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - return 536905728 /* ClassExcludes */; - case 166 /* Constructor */: - return 547311616 /* ConstructorExcludes */; - case 163 /* PropertyDeclaration */: - return 536875008 /* PropertyExcludes */; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - return 538923008 /* MethodOrAccessorExcludes */; + case 210 /* ArrowFunction */: + return 557748224 /* ArrowFunctionExcludes */; + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + return 557756416 /* FunctionExcludes */; + case 251 /* VariableDeclarationList */: + return 537165824 /* VariableDeclarationListExcludes */; + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + return 536940544 /* ClassExcludes */; + case 167 /* Constructor */: + return 557752320 /* ConstructorExcludes */; + case 164 /* PropertyDeclaration */: + return 536879104 /* PropertyExcludes */; + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return 540975104 /* MethodOrAccessorExcludes */; case 128 /* AnyKeyword */: case 144 /* NumberKeyword */: case 155 /* BigIntKeyword */: @@ -25427,30 +25885,30 @@ var ts; case 131 /* BooleanKeyword */: case 148 /* SymbolKeyword */: case 113 /* VoidKeyword */: - case 159 /* TypeParameter */: - case 162 /* PropertySignature */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 160 /* TypeParameter */: + case 163 /* PropertySignature */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return -2 /* TypeExcludes */; - case 200 /* ObjectLiteralExpression */: - return 536922112 /* ObjectLiteralExcludes */; - case 287 /* CatchClause */: - return 536887296 /* CatchClauseExcludes */; - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: - return 536879104 /* BindingPatternExcludes */; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: - case 336 /* PartiallyEmittedExpression */: - case 207 /* ParenthesizedExpression */: + case 201 /* ObjectLiteralExpression */: + return 536973312 /* ObjectLiteralExcludes */; + case 288 /* CatchClause */: + return 536903680 /* CatchClauseExcludes */; + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + return 536887296 /* BindingPatternExcludes */; + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: + case 340 /* PartiallyEmittedExpression */: + case 208 /* ParenthesizedExpression */: case 105 /* SuperKeyword */: return 536870912 /* OuterExpressionExcludes */; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return 536870912 /* PropertyAccessExcludes */; default: return 536870912 /* NodeExcludes */; @@ -25749,7 +26207,7 @@ var ts; // To avoid holding onto transformation artifacts, we keep track of any // parse tree node we are annotating. This allows us to clean them up after // all transformations have completed. - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = (_a = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)))) !== null && _a !== void 0 ? _a : ts.Debug.fail("Could not determine parsed source file."); @@ -26236,13 +26694,27 @@ var ts; /*typeArguments*/ undefined, [moduleExpression, exportsExpression]); } // Class Fields Helpers - function createClassPrivateFieldGetHelper(receiver, privateField) { + function createClassPrivateFieldGetHelper(receiver, state, kind, f) { context.requestEmitHelper(ts.classPrivateFieldGetHelper); - return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ undefined, [receiver, privateField]); + var args; + if (!f) { + args = [receiver, state, factory.createStringLiteral(kind)]; + } + else { + args = [receiver, state, factory.createStringLiteral(kind), f]; + } + return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ undefined, args); } - function createClassPrivateFieldSetHelper(receiver, privateField, value) { + function createClassPrivateFieldSetHelper(receiver, state, value, kind, f) { context.requestEmitHelper(ts.classPrivateFieldSetHelper); - return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, [receiver, privateField, value]); + var args; + if (!f) { + args = [receiver, state, value, factory.createStringLiteral(kind)]; + } + else { + args = [receiver, state, value, factory.createStringLiteral(kind), f]; + } + return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, args); } } ts.createEmitHelperFactory = createEmitHelperFactory; @@ -26482,7 +26954,6 @@ var ts; scoped: false, text: "\n var __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n };" }; - // emit output for the __export helper function ts.exportStarHelper = { name: "typescript:export-star", importName: "__exportStar", @@ -26491,18 +26962,116 @@ var ts; priority: 2, text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n };" }; - // Class fields helpers + /** + * Parameters: + * @param receiver — The object from which the private member will be read. + * @param state — One of the following: + * - A WeakMap used to read a private instance field. + * - A WeakSet used as an instance brand for private instance methods and accessors. + * - A function value that should be the undecorated class constructor used to brand check private static fields, methods, and accessors. + * @param kind — (optional pre TS 4.3, required for TS 4.3+) One of the following values: + * - undefined — Indicates a private instance field (pre TS 4.3). + * - "f" — Indicates a private field (instance or static). + * - "m" — Indicates a private method (instance or static). + * - "a" — Indicates a private accessor (instance or static). + * @param f — (optional pre TS 4.3) Depends on the arguments for state and kind: + * - If kind is "m", this should be the function corresponding to the static or instance method. + * - If kind is "a", this should be the function corresponding to the getter method, or undefined if the getter was not defined. + * - If kind is "f" and state is a function, this should be an object holding the value of a static field, or undefined if the static field declaration has not yet been evaluated. + * Usage: + * This helper will only ever be used by the compiler in the following ways: + * + * Reading from a private instance field (pre TS 4.3): + * __classPrivateFieldGet(, ) + * + * Reading from a private instance field (TS 4.3+): + * __classPrivateFieldGet(, , "f") + * + * Reading from a private instance get accessor (when defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", ) + * + * Reading from a private instance get accessor (when not defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Reading from a private instance method (TS 4.3+): + * __classPrivateFieldGet(, , "m", ) + * + * Reading from a private static field (TS 4.3+): + * __classPrivateFieldGet(, , "f", <{ value: any }>) + * + * Reading from a private static get accessor (when defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", ) + * + * Reading from a private static get accessor (when not defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Reading from a private static method (TS 4.3+): + * __classPrivateFieldGet(, , "m", ) + */ ts.classPrivateFieldGetHelper = { name: "typescript:classPrivateFieldGet", importName: "__classPrivateFieldGet", scoped: false, - text: "\n var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, privateMap) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to get private field on non-instance\");\n }\n return privateMap.get(receiver);\n };" + text: "\n var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n };" }; + /** + * Parameters: + * @param receiver — The object on which the private member will be set. + * @param state — One of the following: + * - A WeakMap used to store a private instance field. + * - A WeakSet used as an instance brand for private instance methods and accessors. + * - A function value that should be the undecorated class constructor used to brand check private static fields, methods, and accessors. + * @param value — The value to set. + * @param kind — (optional pre TS 4.3, required for TS 4.3+) One of the following values: + * - undefined — Indicates a private instance field (pre TS 4.3). + * - "f" — Indicates a private field (instance or static). + * - "m" — Indicates a private method (instance or static). + * - "a" — Indicates a private accessor (instance or static). + * @param f — (optional pre TS 4.3) Depends on the arguments for state and kind: + * - If kind is "m", this should be the function corresponding to the static or instance method. + * - If kind is "a", this should be the function corresponding to the setter method, or undefined if the setter was not defined. + * - If kind is "f" and state is a function, this should be an object holding the value of a static field, or undefined if the static field declaration has not yet been evaluated. + * Usage: + * This helper will only ever be used by the compiler in the following ways: + * + * Writing to a private instance field (pre TS 4.3): + * __classPrivateFieldSet(, , ) + * + * Writing to a private instance field (TS 4.3+): + * __classPrivateFieldSet(, , , "f") + * + * Writing to a private instance set accessor (when defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", ) + * + * Writing to a private instance set accessor (when not defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Writing to a private instance method (TS 4.3+): + * __classPrivateFieldSet(, , , "m", ) + * NOTE: This always results in a runtime error. + * + * Writing to a private static field (TS 4.3+): + * __classPrivateFieldSet(, , , "f", <{ value: any }>) + * + * Writing to a private static set accessor (when defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", ) + * + * Writing to a private static set accessor (when not defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Writing to a private static method (TS 4.3+): + * __classPrivateFieldSet(, , , "m", ) + * NOTE: This always results in a runtime error. + */ ts.classPrivateFieldSetHelper = { name: "typescript:classPrivateFieldSet", importName: "__classPrivateFieldSet", scoped: false, - text: "\n var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, privateMap, value) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to set private field on non-instance\");\n }\n privateMap.set(receiver, value);\n return value;\n };" + text: "\n var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n };" }; var allUnscopedEmitHelpers; function getAllUnscopedEmitHelpers() { @@ -26591,25 +27160,93 @@ var ts; return node.kind === 17 /* TemplateTail */; } ts.isTemplateTail = isTemplateTail; + // Punctuation + function isDotDotDotToken(node) { + return node.kind === 25 /* DotDotDotToken */; + } + ts.isDotDotDotToken = isDotDotDotToken; + /*@internal*/ + function isCommaToken(node) { + return node.kind === 27 /* CommaToken */; + } + ts.isCommaToken = isCommaToken; + function isPlusToken(node) { + return node.kind === 39 /* PlusToken */; + } + ts.isPlusToken = isPlusToken; + function isMinusToken(node) { + return node.kind === 40 /* MinusToken */; + } + ts.isMinusToken = isMinusToken; + function isAsteriskToken(node) { + return node.kind === 41 /* AsteriskToken */; + } + ts.isAsteriskToken = isAsteriskToken; + /*@internal*/ + function isExclamationToken(node) { + return node.kind === 53 /* ExclamationToken */; + } + ts.isExclamationToken = isExclamationToken; + /*@internal*/ + function isQuestionToken(node) { + return node.kind === 57 /* QuestionToken */; + } + ts.isQuestionToken = isQuestionToken; + /*@internal*/ + function isColonToken(node) { + return node.kind === 58 /* ColonToken */; + } + ts.isColonToken = isColonToken; + /*@internal*/ + function isQuestionDotToken(node) { + return node.kind === 28 /* QuestionDotToken */; + } + ts.isQuestionDotToken = isQuestionDotToken; + /*@internal*/ + function isEqualsGreaterThanToken(node) { + return node.kind === 38 /* EqualsGreaterThanToken */; + } + ts.isEqualsGreaterThanToken = isEqualsGreaterThanToken; // Identifiers function isIdentifier(node) { return node.kind === 78 /* Identifier */; } ts.isIdentifier = isIdentifier; - // Names - function isQualifiedName(node) { - return node.kind === 157 /* QualifiedName */; - } - ts.isQualifiedName = isQualifiedName; - function isComputedPropertyName(node) { - return node.kind === 158 /* ComputedPropertyName */; - } - ts.isComputedPropertyName = isComputedPropertyName; function isPrivateIdentifier(node) { return node.kind === 79 /* PrivateIdentifier */; } ts.isPrivateIdentifier = isPrivateIdentifier; - // Tokens + // Reserved Words + /* @internal */ + function isExportModifier(node) { + return node.kind === 92 /* ExportKeyword */; + } + ts.isExportModifier = isExportModifier; + /* @internal */ + function isAsyncModifier(node) { + return node.kind === 129 /* AsyncKeyword */; + } + ts.isAsyncModifier = isAsyncModifier; + /* @internal */ + function isAssertsKeyword(node) { + return node.kind === 127 /* AssertsKeyword */; + } + ts.isAssertsKeyword = isAssertsKeyword; + /* @internal */ + function isAwaitKeyword(node) { + return node.kind === 130 /* AwaitKeyword */; + } + ts.isAwaitKeyword = isAwaitKeyword; + /* @internal */ + function isReadonlyKeyword(node) { + return node.kind === 142 /* ReadonlyKeyword */; + } + ts.isReadonlyKeyword = isReadonlyKeyword; + /* @internal */ + function isStaticModifier(node) { + return node.kind === 123 /* StaticKeyword */; + } + ts.isStaticModifier = isStaticModifier; /*@internal*/ function isSuperKeyword(node) { return node.kind === 105 /* SuperKeyword */; @@ -26620,597 +27257,591 @@ var ts; return node.kind === 99 /* ImportKeyword */; } ts.isImportKeyword = isImportKeyword; - /*@internal*/ - function isCommaToken(node) { - return node.kind === 27 /* CommaToken */; - } - ts.isCommaToken = isCommaToken; - /*@internal*/ - function isQuestionToken(node) { - return node.kind === 57 /* QuestionToken */; + // Names + function isQualifiedName(node) { + return node.kind === 158 /* QualifiedName */; } - ts.isQuestionToken = isQuestionToken; - /*@internal*/ - function isExclamationToken(node) { - return node.kind === 53 /* ExclamationToken */; + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 159 /* ComputedPropertyName */; } - ts.isExclamationToken = isExclamationToken; + ts.isComputedPropertyName = isComputedPropertyName; // Signature elements function isTypeParameterDeclaration(node) { - return node.kind === 159 /* TypeParameter */; + return node.kind === 160 /* TypeParameter */; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; // TODO(rbuckton): Rename to 'isParameterDeclaration' function isParameter(node) { - return node.kind === 160 /* Parameter */; + return node.kind === 161 /* Parameter */; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 161 /* Decorator */; + return node.kind === 162 /* Decorator */; } ts.isDecorator = isDecorator; // TypeMember function isPropertySignature(node) { - return node.kind === 162 /* PropertySignature */; + return node.kind === 163 /* PropertySignature */; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 163 /* PropertyDeclaration */; + return node.kind === 164 /* PropertyDeclaration */; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 164 /* MethodSignature */; + return node.kind === 165 /* MethodSignature */; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 165 /* MethodDeclaration */; + return node.kind === 166 /* MethodDeclaration */; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 166 /* Constructor */; + return node.kind === 167 /* Constructor */; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 167 /* GetAccessor */; + return node.kind === 168 /* GetAccessor */; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 168 /* SetAccessor */; + return node.kind === 169 /* SetAccessor */; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 169 /* CallSignature */; + return node.kind === 170 /* CallSignature */; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 170 /* ConstructSignature */; + return node.kind === 171 /* ConstructSignature */; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 171 /* IndexSignature */; + return node.kind === 172 /* IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; // Type function isTypePredicateNode(node) { - return node.kind === 172 /* TypePredicate */; + return node.kind === 173 /* TypePredicate */; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 173 /* TypeReference */; + return node.kind === 174 /* TypeReference */; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 174 /* FunctionType */; + return node.kind === 175 /* FunctionType */; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 175 /* ConstructorType */; + return node.kind === 176 /* ConstructorType */; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 176 /* TypeQuery */; + return node.kind === 177 /* TypeQuery */; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 177 /* TypeLiteral */; + return node.kind === 178 /* TypeLiteral */; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 178 /* ArrayType */; + return node.kind === 179 /* ArrayType */; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 179 /* TupleType */; + return node.kind === 180 /* TupleType */; } ts.isTupleTypeNode = isTupleTypeNode; function isNamedTupleMember(node) { - return node.kind === 192 /* NamedTupleMember */; + return node.kind === 193 /* NamedTupleMember */; } ts.isNamedTupleMember = isNamedTupleMember; function isOptionalTypeNode(node) { - return node.kind === 180 /* OptionalType */; + return node.kind === 181 /* OptionalType */; } ts.isOptionalTypeNode = isOptionalTypeNode; function isRestTypeNode(node) { - return node.kind === 181 /* RestType */; + return node.kind === 182 /* RestType */; } ts.isRestTypeNode = isRestTypeNode; function isUnionTypeNode(node) { - return node.kind === 182 /* UnionType */; + return node.kind === 183 /* UnionType */; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 183 /* IntersectionType */; + return node.kind === 184 /* IntersectionType */; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isConditionalTypeNode(node) { - return node.kind === 184 /* ConditionalType */; + return node.kind === 185 /* ConditionalType */; } ts.isConditionalTypeNode = isConditionalTypeNode; function isInferTypeNode(node) { - return node.kind === 185 /* InferType */; + return node.kind === 186 /* InferType */; } ts.isInferTypeNode = isInferTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 186 /* ParenthesizedType */; + return node.kind === 187 /* ParenthesizedType */; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 187 /* ThisType */; + return node.kind === 188 /* ThisType */; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 188 /* TypeOperator */; + return node.kind === 189 /* TypeOperator */; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 189 /* IndexedAccessType */; + return node.kind === 190 /* IndexedAccessType */; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 190 /* MappedType */; + return node.kind === 191 /* MappedType */; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 191 /* LiteralType */; + return node.kind === 192 /* LiteralType */; } ts.isLiteralTypeNode = isLiteralTypeNode; function isImportTypeNode(node) { - return node.kind === 195 /* ImportType */; + return node.kind === 196 /* ImportType */; } ts.isImportTypeNode = isImportTypeNode; function isTemplateLiteralTypeSpan(node) { - return node.kind === 194 /* TemplateLiteralTypeSpan */; + return node.kind === 195 /* TemplateLiteralTypeSpan */; } ts.isTemplateLiteralTypeSpan = isTemplateLiteralTypeSpan; function isTemplateLiteralTypeNode(node) { - return node.kind === 193 /* TemplateLiteralType */; + return node.kind === 194 /* TemplateLiteralType */; } ts.isTemplateLiteralTypeNode = isTemplateLiteralTypeNode; // Binding patterns function isObjectBindingPattern(node) { - return node.kind === 196 /* ObjectBindingPattern */; + return node.kind === 197 /* ObjectBindingPattern */; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 197 /* ArrayBindingPattern */; + return node.kind === 198 /* ArrayBindingPattern */; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 198 /* BindingElement */; + return node.kind === 199 /* BindingElement */; } ts.isBindingElement = isBindingElement; // Expression function isArrayLiteralExpression(node) { - return node.kind === 199 /* ArrayLiteralExpression */; + return node.kind === 200 /* ArrayLiteralExpression */; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 200 /* ObjectLiteralExpression */; + return node.kind === 201 /* ObjectLiteralExpression */; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 201 /* PropertyAccessExpression */; + return node.kind === 202 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 202 /* ElementAccessExpression */; + return node.kind === 203 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 203 /* CallExpression */; + return node.kind === 204 /* CallExpression */; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 204 /* NewExpression */; + return node.kind === 205 /* NewExpression */; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 205 /* TaggedTemplateExpression */; + return node.kind === 206 /* TaggedTemplateExpression */; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertionExpression(node) { - return node.kind === 206 /* TypeAssertionExpression */; + return node.kind === 207 /* TypeAssertionExpression */; } ts.isTypeAssertionExpression = isTypeAssertionExpression; function isParenthesizedExpression(node) { - return node.kind === 207 /* ParenthesizedExpression */; + return node.kind === 208 /* ParenthesizedExpression */; } ts.isParenthesizedExpression = isParenthesizedExpression; function isFunctionExpression(node) { - return node.kind === 208 /* FunctionExpression */; + return node.kind === 209 /* FunctionExpression */; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 209 /* ArrowFunction */; + return node.kind === 210 /* ArrowFunction */; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 210 /* DeleteExpression */; + return node.kind === 211 /* DeleteExpression */; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 211 /* TypeOfExpression */; + return node.kind === 212 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 212 /* VoidExpression */; + return node.kind === 213 /* VoidExpression */; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 213 /* AwaitExpression */; + return node.kind === 214 /* AwaitExpression */; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 214 /* PrefixUnaryExpression */; + return node.kind === 215 /* PrefixUnaryExpression */; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 215 /* PostfixUnaryExpression */; + return node.kind === 216 /* PostfixUnaryExpression */; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 216 /* BinaryExpression */; + return node.kind === 217 /* BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 217 /* ConditionalExpression */; + return node.kind === 218 /* ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 218 /* TemplateExpression */; + return node.kind === 219 /* TemplateExpression */; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 219 /* YieldExpression */; + return node.kind === 220 /* YieldExpression */; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 220 /* SpreadElement */; + return node.kind === 221 /* SpreadElement */; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 221 /* ClassExpression */; + return node.kind === 222 /* ClassExpression */; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 222 /* OmittedExpression */; + return node.kind === 223 /* OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 223 /* ExpressionWithTypeArguments */; + return node.kind === 224 /* ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 224 /* AsExpression */; + return node.kind === 225 /* AsExpression */; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 225 /* NonNullExpression */; + return node.kind === 226 /* NonNullExpression */; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 226 /* MetaProperty */; + return node.kind === 227 /* MetaProperty */; } ts.isMetaProperty = isMetaProperty; function isSyntheticExpression(node) { - return node.kind === 227 /* SyntheticExpression */; + return node.kind === 228 /* SyntheticExpression */; } ts.isSyntheticExpression = isSyntheticExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 336 /* PartiallyEmittedExpression */; + return node.kind === 340 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isCommaListExpression(node) { - return node.kind === 337 /* CommaListExpression */; + return node.kind === 341 /* CommaListExpression */; } ts.isCommaListExpression = isCommaListExpression; // Misc function isTemplateSpan(node) { - return node.kind === 228 /* TemplateSpan */; + return node.kind === 229 /* TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 229 /* SemicolonClassElement */; + return node.kind === 230 /* SemicolonClassElement */; } ts.isSemicolonClassElement = isSemicolonClassElement; // Elements function isBlock(node) { - return node.kind === 230 /* Block */; + return node.kind === 231 /* Block */; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 232 /* VariableStatement */; + return node.kind === 233 /* VariableStatement */; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 231 /* EmptyStatement */; + return node.kind === 232 /* EmptyStatement */; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 233 /* ExpressionStatement */; + return node.kind === 234 /* ExpressionStatement */; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 234 /* IfStatement */; + return node.kind === 235 /* IfStatement */; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 235 /* DoStatement */; + return node.kind === 236 /* DoStatement */; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 236 /* WhileStatement */; + return node.kind === 237 /* WhileStatement */; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 237 /* ForStatement */; + return node.kind === 238 /* ForStatement */; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 238 /* ForInStatement */; + return node.kind === 239 /* ForInStatement */; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 239 /* ForOfStatement */; + return node.kind === 240 /* ForOfStatement */; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 240 /* ContinueStatement */; + return node.kind === 241 /* ContinueStatement */; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 241 /* BreakStatement */; + return node.kind === 242 /* BreakStatement */; } ts.isBreakStatement = isBreakStatement; function isReturnStatement(node) { - return node.kind === 242 /* ReturnStatement */; + return node.kind === 243 /* ReturnStatement */; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 243 /* WithStatement */; + return node.kind === 244 /* WithStatement */; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 244 /* SwitchStatement */; + return node.kind === 245 /* SwitchStatement */; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 245 /* LabeledStatement */; + return node.kind === 246 /* LabeledStatement */; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 246 /* ThrowStatement */; + return node.kind === 247 /* ThrowStatement */; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 247 /* TryStatement */; + return node.kind === 248 /* TryStatement */; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 248 /* DebuggerStatement */; + return node.kind === 249 /* DebuggerStatement */; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 249 /* VariableDeclaration */; + return node.kind === 250 /* VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 250 /* VariableDeclarationList */; + return node.kind === 251 /* VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 251 /* FunctionDeclaration */; + return node.kind === 252 /* FunctionDeclaration */; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 252 /* ClassDeclaration */; + return node.kind === 253 /* ClassDeclaration */; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 253 /* InterfaceDeclaration */; + return node.kind === 254 /* InterfaceDeclaration */; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 254 /* TypeAliasDeclaration */; + return node.kind === 255 /* TypeAliasDeclaration */; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 255 /* EnumDeclaration */; + return node.kind === 256 /* EnumDeclaration */; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 256 /* ModuleDeclaration */; + return node.kind === 257 /* ModuleDeclaration */; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 257 /* ModuleBlock */; + return node.kind === 258 /* ModuleBlock */; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 258 /* CaseBlock */; + return node.kind === 259 /* CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 259 /* NamespaceExportDeclaration */; + return node.kind === 260 /* NamespaceExportDeclaration */; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */; + return node.kind === 261 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 261 /* ImportDeclaration */; + return node.kind === 262 /* ImportDeclaration */; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 262 /* ImportClause */; + return node.kind === 263 /* ImportClause */; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 263 /* NamespaceImport */; + return node.kind === 264 /* NamespaceImport */; } ts.isNamespaceImport = isNamespaceImport; function isNamespaceExport(node) { - return node.kind === 269 /* NamespaceExport */; + return node.kind === 270 /* NamespaceExport */; } ts.isNamespaceExport = isNamespaceExport; function isNamedImports(node) { - return node.kind === 264 /* NamedImports */; + return node.kind === 265 /* NamedImports */; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 265 /* ImportSpecifier */; + return node.kind === 266 /* ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 266 /* ExportAssignment */; + return node.kind === 267 /* ExportAssignment */; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 267 /* ExportDeclaration */; + return node.kind === 268 /* ExportDeclaration */; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 268 /* NamedExports */; + return node.kind === 269 /* NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 270 /* ExportSpecifier */; + return node.kind === 271 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 271 /* MissingDeclaration */; + return node.kind === 272 /* MissingDeclaration */; } ts.isMissingDeclaration = isMissingDeclaration; function isNotEmittedStatement(node) { - return node.kind === 335 /* NotEmittedStatement */; + return node.kind === 339 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ function isSyntheticReference(node) { - return node.kind === 340 /* SyntheticReferenceExpression */; + return node.kind === 344 /* SyntheticReferenceExpression */; } ts.isSyntheticReference = isSyntheticReference; /* @internal */ function isMergeDeclarationMarker(node) { - return node.kind === 338 /* MergeDeclarationMarker */; + return node.kind === 342 /* MergeDeclarationMarker */; } ts.isMergeDeclarationMarker = isMergeDeclarationMarker; /* @internal */ function isEndOfDeclarationMarker(node) { - return node.kind === 339 /* EndOfDeclarationMarker */; + return node.kind === 343 /* EndOfDeclarationMarker */; } ts.isEndOfDeclarationMarker = isEndOfDeclarationMarker; // Module References function isExternalModuleReference(node) { - return node.kind === 272 /* ExternalModuleReference */; + return node.kind === 273 /* ExternalModuleReference */; } ts.isExternalModuleReference = isExternalModuleReference; // JSX function isJsxElement(node) { - return node.kind === 273 /* JsxElement */; + return node.kind === 274 /* JsxElement */; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 274 /* JsxSelfClosingElement */; + return node.kind === 275 /* JsxSelfClosingElement */; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 275 /* JsxOpeningElement */; + return node.kind === 276 /* JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 276 /* JsxClosingElement */; + return node.kind === 277 /* JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxFragment(node) { - return node.kind === 277 /* JsxFragment */; + return node.kind === 278 /* JsxFragment */; } ts.isJsxFragment = isJsxFragment; function isJsxOpeningFragment(node) { - return node.kind === 278 /* JsxOpeningFragment */; + return node.kind === 279 /* JsxOpeningFragment */; } ts.isJsxOpeningFragment = isJsxOpeningFragment; function isJsxClosingFragment(node) { - return node.kind === 279 /* JsxClosingFragment */; + return node.kind === 280 /* JsxClosingFragment */; } ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 280 /* JsxAttribute */; + return node.kind === 281 /* JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 281 /* JsxAttributes */; + return node.kind === 282 /* JsxAttributes */; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 282 /* JsxSpreadAttribute */; + return node.kind === 283 /* JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 283 /* JsxExpression */; + return node.kind === 284 /* JsxExpression */; } ts.isJsxExpression = isJsxExpression; // Clauses function isCaseClause(node) { - return node.kind === 284 /* CaseClause */; + return node.kind === 285 /* CaseClause */; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 285 /* DefaultClause */; + return node.kind === 286 /* DefaultClause */; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 286 /* HeritageClause */; + return node.kind === 287 /* HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 287 /* CatchClause */; + return node.kind === 288 /* CatchClause */; } ts.isCatchClause = isCatchClause; // Property assignments function isPropertyAssignment(node) { - return node.kind === 288 /* PropertyAssignment */; + return node.kind === 289 /* PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 289 /* ShorthandPropertyAssignment */; + return node.kind === 290 /* ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 290 /* SpreadAssignment */; + return node.kind === 291 /* SpreadAssignment */; } ts.isSpreadAssignment = isSpreadAssignment; // Enum function isEnumMember(node) { - return node.kind === 291 /* EnumMember */; + return node.kind === 292 /* EnumMember */; } ts.isEnumMember = isEnumMember; // Unparsed // TODO(rbuckton): isUnparsedPrologue function isUnparsedPrepend(node) { - return node.kind === 293 /* UnparsedPrepend */; + return node.kind === 294 /* UnparsedPrepend */; } ts.isUnparsedPrepend = isUnparsedPrepend; // TODO(rbuckton): isUnparsedText @@ -27218,156 +27849,164 @@ var ts; // TODO(rbuckton): isUnparsedSyntheticReference // Top-level nodes function isSourceFile(node) { - return node.kind === 297 /* SourceFile */; + return node.kind === 298 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 298 /* Bundle */; + return node.kind === 299 /* Bundle */; } ts.isBundle = isBundle; function isUnparsedSource(node) { - return node.kind === 299 /* UnparsedSource */; + return node.kind === 300 /* UnparsedSource */; } ts.isUnparsedSource = isUnparsedSource; // TODO(rbuckton): isInputFiles // JSDoc Elements function isJSDocTypeExpression(node) { - return node.kind === 301 /* JSDocTypeExpression */; + return node.kind === 302 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocNameReference(node) { - return node.kind === 302 /* JSDocNameReference */; + return node.kind === 303 /* JSDocNameReference */; } ts.isJSDocNameReference = isJSDocNameReference; + function isJSDocLink(node) { + return node.kind === 316 /* JSDocLink */; + } + ts.isJSDocLink = isJSDocLink; function isJSDocAllType(node) { - return node.kind === 303 /* JSDocAllType */; + return node.kind === 304 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 304 /* JSDocUnknownType */; + return node.kind === 305 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 305 /* JSDocNullableType */; + return node.kind === 306 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 306 /* JSDocNonNullableType */; + return node.kind === 307 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 307 /* JSDocOptionalType */; + return node.kind === 308 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 308 /* JSDocFunctionType */; + return node.kind === 309 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 309 /* JSDocVariadicType */; + return node.kind === 310 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDocNamepathType(node) { - return node.kind === 310 /* JSDocNamepathType */; + return node.kind === 311 /* JSDocNamepathType */; } ts.isJSDocNamepathType = isJSDocNamepathType; function isJSDoc(node) { - return node.kind === 311 /* JSDocComment */; + return node.kind === 312 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocTypeLiteral(node) { - return node.kind === 312 /* JSDocTypeLiteral */; + return node.kind === 314 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; function isJSDocSignature(node) { - return node.kind === 313 /* JSDocSignature */; + return node.kind === 315 /* JSDocSignature */; } ts.isJSDocSignature = isJSDocSignature; // JSDoc Tags function isJSDocAugmentsTag(node) { - return node.kind === 315 /* JSDocAugmentsTag */; + return node.kind === 318 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocAuthorTag(node) { - return node.kind === 317 /* JSDocAuthorTag */; + return node.kind === 320 /* JSDocAuthorTag */; } ts.isJSDocAuthorTag = isJSDocAuthorTag; function isJSDocClassTag(node) { - return node.kind === 319 /* JSDocClassTag */; + return node.kind === 322 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocCallbackTag(node) { - return node.kind === 324 /* JSDocCallbackTag */; + return node.kind === 328 /* JSDocCallbackTag */; } ts.isJSDocCallbackTag = isJSDocCallbackTag; function isJSDocPublicTag(node) { - return node.kind === 320 /* JSDocPublicTag */; + return node.kind === 323 /* JSDocPublicTag */; } ts.isJSDocPublicTag = isJSDocPublicTag; function isJSDocPrivateTag(node) { - return node.kind === 321 /* JSDocPrivateTag */; + return node.kind === 324 /* JSDocPrivateTag */; } ts.isJSDocPrivateTag = isJSDocPrivateTag; function isJSDocProtectedTag(node) { - return node.kind === 322 /* JSDocProtectedTag */; + return node.kind === 325 /* JSDocProtectedTag */; } ts.isJSDocProtectedTag = isJSDocProtectedTag; function isJSDocReadonlyTag(node) { - return node.kind === 323 /* JSDocReadonlyTag */; + return node.kind === 326 /* JSDocReadonlyTag */; } ts.isJSDocReadonlyTag = isJSDocReadonlyTag; + function isJSDocOverrideTag(node) { + return node.kind === 327 /* JSDocOverrideTag */; + } + ts.isJSDocOverrideTag = isJSDocOverrideTag; function isJSDocDeprecatedTag(node) { - return node.kind === 318 /* JSDocDeprecatedTag */; + return node.kind === 321 /* JSDocDeprecatedTag */; } ts.isJSDocDeprecatedTag = isJSDocDeprecatedTag; function isJSDocSeeTag(node) { - return node.kind === 332 /* JSDocSeeTag */; + return node.kind === 336 /* JSDocSeeTag */; } ts.isJSDocSeeTag = isJSDocSeeTag; function isJSDocEnumTag(node) { - return node.kind === 325 /* JSDocEnumTag */; + return node.kind === 329 /* JSDocEnumTag */; } ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocParameterTag(node) { - return node.kind === 326 /* JSDocParameterTag */; + return node.kind === 330 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 327 /* JSDocReturnTag */; + return node.kind === 331 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocThisTag(node) { - return node.kind === 328 /* JSDocThisTag */; + return node.kind === 332 /* JSDocThisTag */; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocTypeTag(node) { - return node.kind === 329 /* JSDocTypeTag */; + return node.kind === 333 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 330 /* JSDocTemplateTag */; + return node.kind === 334 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 331 /* JSDocTypedefTag */; + return node.kind === 335 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocUnknownTag(node) { - return node.kind === 314 /* JSDocTag */; + return node.kind === 317 /* JSDocTag */; } ts.isJSDocUnknownTag = isJSDocUnknownTag; function isJSDocPropertyTag(node) { - return node.kind === 333 /* JSDocPropertyTag */; + return node.kind === 337 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocImplementsTag(node) { - return node.kind === 316 /* JSDocImplementsTag */; + return node.kind === 319 /* JSDocImplementsTag */; } ts.isJSDocImplementsTag = isJSDocImplementsTag; // Synthesized list /* @internal */ function isSyntaxList(n) { - return n.kind === 334 /* SyntaxList */; + return n.kind === 338 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; })(ts || (ts = {})); @@ -27384,7 +28023,7 @@ var ts; return ts.setTextRange(factory.createElementAccessExpression(target, memberName.expression), location); } else { - var expression = ts.setTextRange(ts.isIdentifierOrPrivateIdentifier(memberName) + var expression = ts.setTextRange(ts.isMemberName(memberName) ? factory.createPropertyAccessExpression(target, memberName) : factory.createElementAccessExpression(target, memberName), memberName); ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */; @@ -27566,14 +28205,14 @@ var ts; ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals."); } switch (property.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return createExpressionForAccessorDeclaration(factory, node.properties, property, receiver, !!node.multiLine); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return createExpressionForPropertyAssignment(factory, property, receiver); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(factory, property, receiver); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return createExpressionForMethodDeclaration(factory, property, receiver); } } @@ -27626,21 +28265,21 @@ var ts; } ts.startsWithUseStrict = startsWithUseStrict; function isCommaSequence(node) { - return node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || - node.kind === 337 /* CommaListExpression */; + return node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || + node.kind === 341 /* CommaListExpression */; } ts.isCommaSequence = isCommaSequence; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 15 /* All */; } switch (node.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return (kinds & 1 /* Parentheses */) !== 0; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return (kinds & 2 /* TypeAssertions */) !== 0; - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return (kinds & 4 /* NonNullAssertions */) !== 0; - case 336 /* PartiallyEmittedExpression */: + case 340 /* PartiallyEmittedExpression */: return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -27761,10 +28400,10 @@ var ts; var name = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name) ? name : factory.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 261 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 262 /* ImportDeclaration */ && node.importClause) { return factory.getGeneratedNameForNode(node); } - if (node.kind === 267 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 268 /* ExportDeclaration */ && node.moduleSpecifier) { return factory.getGeneratedNameForNode(node); } return undefined; @@ -27883,7 +28522,7 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // `b` in `({ a: b } = ...)` // `b` in `({ a: b = 1 } = ...)` // `{b}` in `({ a: {b} } = ...)` @@ -27895,11 +28534,11 @@ var ts; // `b[0]` in `({ a: b[0] } = ...)` // `b[0]` in `({ a: b[0] = 1 } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: // `a` in `({ a } = ...)` // `a` in `({ a = 1 } = ...)` return bindingElement.name; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } @@ -27931,12 +28570,12 @@ var ts; */ function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 160 /* Parameter */: - case 198 /* BindingElement */: + case 161 /* Parameter */: + case 199 /* BindingElement */: // `...` in `let [...a] = ...` return bindingElement.dotDotDotToken; - case 220 /* SpreadElement */: - case 290 /* SpreadAssignment */: + case 221 /* SpreadElement */: + case 291 /* SpreadAssignment */: // `...` in `[...a] = ...` return bindingElement; } @@ -27954,7 +28593,7 @@ var ts; ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 198 /* BindingElement */: + case 199 /* BindingElement */: // `a` in `let { a: b } = ...` // `[a]` in `let { [a]: b } = ...` // `"a"` in `let { "a": b } = ...` @@ -27969,7 +28608,7 @@ var ts; : propertyName; } break; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // `a` in `({ a: b } = ...)` // `[a]` in `({ [a]: b } = ...)` // `"a"` in `({ "a": b } = ...)` @@ -27984,7 +28623,7 @@ var ts; : propertyName; } break; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) { return ts.Debug.failBadSyntaxKind(bindingElement.name); @@ -28007,13 +28646,13 @@ var ts; */ function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: - case 199 /* ArrayLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + case 200 /* ArrayLiteralExpression */: // `a` in `{a}` // `a` in `[a]` return name.elements; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: // `a` in `{a}` return name.properties; } @@ -28034,46 +28673,294 @@ var ts; ts.getJSDocTypeAliasName = getJSDocTypeAliasName; function canHaveModifiers(node) { var kind = node.kind; - return kind === 160 /* Parameter */ - || kind === 162 /* PropertySignature */ - || kind === 163 /* PropertyDeclaration */ - || kind === 164 /* MethodSignature */ - || kind === 165 /* MethodDeclaration */ - || kind === 166 /* Constructor */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 171 /* IndexSignature */ - || kind === 208 /* FunctionExpression */ - || kind === 209 /* ArrowFunction */ - || kind === 221 /* ClassExpression */ - || kind === 232 /* VariableStatement */ - || kind === 251 /* FunctionDeclaration */ - || kind === 252 /* ClassDeclaration */ - || kind === 253 /* InterfaceDeclaration */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 255 /* EnumDeclaration */ - || kind === 256 /* ModuleDeclaration */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 261 /* ImportDeclaration */ - || kind === 266 /* ExportAssignment */ - || kind === 267 /* ExportDeclaration */; + return kind === 161 /* Parameter */ + || kind === 163 /* PropertySignature */ + || kind === 164 /* PropertyDeclaration */ + || kind === 165 /* MethodSignature */ + || kind === 166 /* MethodDeclaration */ + || kind === 167 /* Constructor */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 172 /* IndexSignature */ + || kind === 209 /* FunctionExpression */ + || kind === 210 /* ArrowFunction */ + || kind === 222 /* ClassExpression */ + || kind === 233 /* VariableStatement */ + || kind === 252 /* FunctionDeclaration */ + || kind === 253 /* ClassDeclaration */ + || kind === 254 /* InterfaceDeclaration */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 256 /* EnumDeclaration */ + || kind === 257 /* ModuleDeclaration */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 262 /* ImportDeclaration */ + || kind === 267 /* ExportAssignment */ + || kind === 268 /* ExportDeclaration */; } ts.canHaveModifiers = canHaveModifiers; - /* @internal */ - function isExportModifier(node) { - return node.kind === 92 /* ExportKeyword */; - } - ts.isExportModifier = isExportModifier; - /* @internal */ - function isAsyncModifier(node) { - return node.kind === 129 /* AsyncKeyword */; - } - ts.isAsyncModifier = isAsyncModifier; - /* @internal */ - function isStaticModifier(node) { - return node.kind === 123 /* StaticKeyword */; + ts.isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); + ts.isQuestionOrExclamationToken = ts.or(ts.isQuestionToken, ts.isExclamationToken); + ts.isIdentifierOrThisTypeNode = ts.or(ts.isIdentifier, ts.isThisTypeNode); + ts.isReadonlyKeywordOrPlusOrMinusToken = ts.or(ts.isReadonlyKeyword, ts.isPlusToken, ts.isMinusToken); + ts.isQuestionOrPlusOrMinusToken = ts.or(ts.isQuestionToken, ts.isPlusToken, ts.isMinusToken); + ts.isModuleName = ts.or(ts.isIdentifier, ts.isStringLiteral); + function isLiteralTypeLikeExpression(node) { + var kind = node.kind; + return kind === 103 /* NullKeyword */ + || kind === 109 /* TrueKeyword */ + || kind === 94 /* FalseKeyword */ + || ts.isLiteralExpression(node) + || ts.isPrefixUnaryExpression(node); + } + ts.isLiteralTypeLikeExpression = isLiteralTypeLikeExpression; + function isExponentiationOperator(kind) { + return kind === 42 /* AsteriskAsteriskToken */; + } + function isMultiplicativeOperator(kind) { + return kind === 41 /* AsteriskToken */ + || kind === 43 /* SlashToken */ + || kind === 44 /* PercentToken */; + } + function isMultiplicativeOperatorOrHigher(kind) { + return isExponentiationOperator(kind) + || isMultiplicativeOperator(kind); + } + function isAdditiveOperator(kind) { + return kind === 39 /* PlusToken */ + || kind === 40 /* MinusToken */; + } + function isAdditiveOperatorOrHigher(kind) { + return isAdditiveOperator(kind) + || isMultiplicativeOperatorOrHigher(kind); + } + function isShiftOperator(kind) { + return kind === 47 /* LessThanLessThanToken */ + || kind === 48 /* GreaterThanGreaterThanToken */ + || kind === 49 /* GreaterThanGreaterThanGreaterThanToken */; + } + function isShiftOperatorOrHigher(kind) { + return isShiftOperator(kind) + || isAdditiveOperatorOrHigher(kind); + } + function isRelationalOperator(kind) { + return kind === 29 /* LessThanToken */ + || kind === 32 /* LessThanEqualsToken */ + || kind === 31 /* GreaterThanToken */ + || kind === 33 /* GreaterThanEqualsToken */ + || kind === 101 /* InstanceOfKeyword */ + || kind === 100 /* InKeyword */; + } + function isRelationalOperatorOrHigher(kind) { + return isRelationalOperator(kind) + || isShiftOperatorOrHigher(kind); + } + function isEqualityOperator(kind) { + return kind === 34 /* EqualsEqualsToken */ + || kind === 36 /* EqualsEqualsEqualsToken */ + || kind === 35 /* ExclamationEqualsToken */ + || kind === 37 /* ExclamationEqualsEqualsToken */; + } + function isEqualityOperatorOrHigher(kind) { + return isEqualityOperator(kind) + || isRelationalOperatorOrHigher(kind); + } + function isBitwiseOperator(kind) { + return kind === 50 /* AmpersandToken */ + || kind === 51 /* BarToken */ + || kind === 52 /* CaretToken */; + } + function isBitwiseOperatorOrHigher(kind) { + return isBitwiseOperator(kind) + || isEqualityOperatorOrHigher(kind); + } + // NOTE: The version in utilities includes ExclamationToken, which is not a binary operator. + function isLogicalOperator(kind) { + return kind === 55 /* AmpersandAmpersandToken */ + || kind === 56 /* BarBarToken */; + } + function isLogicalOperatorOrHigher(kind) { + return isLogicalOperator(kind) + || isBitwiseOperatorOrHigher(kind); + } + function isAssignmentOperatorOrHigher(kind) { + return kind === 60 /* QuestionQuestionToken */ + || isLogicalOperatorOrHigher(kind) + || ts.isAssignmentOperator(kind); + } + function isBinaryOperator(kind) { + return isAssignmentOperatorOrHigher(kind) + || kind === 27 /* CommaToken */; + } + function isBinaryOperatorToken(node) { + return isBinaryOperator(node.kind); + } + ts.isBinaryOperatorToken = isBinaryOperatorToken; + var BinaryExpressionState; + (function (BinaryExpressionState) { + /** + * Handles walking into a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function enter(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, outerState) { + var prevUserState = stackIndex > 0 ? userStateStack[stackIndex - 1] : undefined; + ts.Debug.assertEqual(stateStack[stackIndex], enter); + userStateStack[stackIndex] = machine.onEnter(nodeStack[stackIndex], prevUserState, outerState); + stateStack[stackIndex] = nextState(machine, enter); + return stackIndex; + } + BinaryExpressionState.enter = enter; + /** + * Handles walking the `left` side of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function left(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], left); + ts.Debug.assertIsDefined(machine.onLeft); + stateStack[stackIndex] = nextState(machine, left); + var nextNode = machine.onLeft(nodeStack[stackIndex].left, userStateStack[stackIndex], nodeStack[stackIndex]); + if (nextNode) { + checkCircularity(stackIndex, nodeStack, nextNode); + return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode); + } + return stackIndex; + } + BinaryExpressionState.left = left; + /** + * Handles walking the `operatorToken` of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function operator(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], operator); + ts.Debug.assertIsDefined(machine.onOperator); + stateStack[stackIndex] = nextState(machine, operator); + machine.onOperator(nodeStack[stackIndex].operatorToken, userStateStack[stackIndex], nodeStack[stackIndex]); + return stackIndex; + } + BinaryExpressionState.operator = operator; + /** + * Handles walking the `right` side of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function right(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], right); + ts.Debug.assertIsDefined(machine.onRight); + stateStack[stackIndex] = nextState(machine, right); + var nextNode = machine.onRight(nodeStack[stackIndex].right, userStateStack[stackIndex], nodeStack[stackIndex]); + if (nextNode) { + checkCircularity(stackIndex, nodeStack, nextNode); + return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode); + } + return stackIndex; + } + BinaryExpressionState.right = right; + /** + * Handles walking out of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function exit(machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], exit); + stateStack[stackIndex] = nextState(machine, exit); + var result = machine.onExit(nodeStack[stackIndex], userStateStack[stackIndex]); + if (stackIndex > 0) { + stackIndex--; + if (machine.foldState) { + var side = stateStack[stackIndex] === exit ? "right" : "left"; + userStateStack[stackIndex] = machine.foldState(userStateStack[stackIndex], result, side); + } + } + else { + resultHolder.value = result; + } + return stackIndex; + } + BinaryExpressionState.exit = exit; + /** + * Handles a frame that is already done. + * @returns The `done` state. + */ + function done(_machine, stackIndex, stateStack, _nodeStack, _userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], done); + return stackIndex; + } + BinaryExpressionState.done = done; + function nextState(machine, currentState) { + switch (currentState) { + case enter: + if (machine.onLeft) + return left; + // falls through + case left: + if (machine.onOperator) + return operator; + // falls through + case operator: + if (machine.onRight) + return right; + // falls through + case right: return exit; + case exit: return done; + case done: return done; + default: ts.Debug.fail("Invalid state"); + } + } + BinaryExpressionState.nextState = nextState; + function pushStack(stackIndex, stateStack, nodeStack, userStateStack, node) { + stackIndex++; + stateStack[stackIndex] = enter; + nodeStack[stackIndex] = node; + userStateStack[stackIndex] = undefined; + return stackIndex; + } + function checkCircularity(stackIndex, nodeStack, node) { + if (ts.Debug.shouldAssert(2 /* Aggressive */)) { + while (stackIndex >= 0) { + ts.Debug.assert(nodeStack[stackIndex] !== node, "Circular traversal detected."); + stackIndex--; + } + } + } + })(BinaryExpressionState || (BinaryExpressionState = {})); + /** + * Holds state machine handler functions + */ + var BinaryExpressionStateMachine = /** @class */ (function () { + function BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState) { + this.onEnter = onEnter; + this.onLeft = onLeft; + this.onOperator = onOperator; + this.onRight = onRight; + this.onExit = onExit; + this.foldState = foldState; + } + return BinaryExpressionStateMachine; + }()); + function createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState) { + var machine = new BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState); + return trampoline; + function trampoline(node, outerState) { + var resultHolder = { value: undefined }; + var stateStack = [BinaryExpressionState.enter]; + var nodeStack = [node]; + var userStateStack = [undefined]; + var stackIndex = 0; + while (stateStack[stackIndex] !== BinaryExpressionState.done) { + stackIndex = stateStack[stackIndex](machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, outerState); + } + ts.Debug.assertEqual(stackIndex, 0); + return resultHolder.value; + } } - ts.isStaticModifier = isStaticModifier; + ts.createBinaryExpressionTrampoline = createBinaryExpressionTrampoline; })(ts || (ts = {})); var ts; (function (ts) { @@ -28155,19 +29042,19 @@ var ts; * that they appear in the source code. The language service depends on this property to locate nodes by position. */ function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 156 /* LastToken */) { + if (!node || node.kind <= 157 /* LastToken */) { return; } switch (node.kind) { - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -28175,9 +29062,9 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: return visitNode(cbNode, node.expression); - case 160 /* Parameter */: + case 161 /* Parameter */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || @@ -28185,7 +29072,7 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -28193,51 +29080,51 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.initializer); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -28249,374 +29136,390 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return visitNode(cbNode, node.assertsModifier) || visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return visitNodes(cbNode, cbNodes, node.members); - case 178 /* ArrayType */: + case 179 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 179 /* TupleType */: + case 180 /* TupleType */: return visitNodes(cbNode, cbNodes, node.elements); - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: return visitNodes(cbNode, cbNodes, node.types); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return visitNode(cbNode, node.checkType) || visitNode(cbNode, node.extendsType) || visitNode(cbNode, node.trueType) || visitNode(cbNode, node.falseType); - case 185 /* InferType */: + case 186 /* InferType */: return visitNode(cbNode, node.typeParameter); - case 195 /* ImportType */: + case 196 /* ImportType */: return visitNode(cbNode, node.argument) || visitNode(cbNode, node.qualifier) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 186 /* ParenthesizedType */: - case 188 /* TypeOperator */: + case 187 /* ParenthesizedType */: + case 189 /* TypeOperator */: return visitNode(cbNode, node.type); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 190 /* MappedType */: + case 191 /* MappedType */: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.nameType) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 191 /* LiteralType */: + case 192 /* LiteralType */: return visitNode(cbNode, node.literal); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: return visitNodes(cbNode, cbNodes, node.elements); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitNodes(cbNode, cbNodes, node.properties); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || visitNode(cbNode, node.name); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || visitNode(cbNode, node.argumentExpression); - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.template); - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 224 /* AsExpression */: + case 225 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return visitNode(cbNode, node.expression); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return visitNode(cbNode, node.name); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return visitNode(cbNode, node.expression); - case 230 /* Block */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 258 /* ModuleBlock */: return visitNodes(cbNode, cbNodes, node.statements); - case 297 /* SourceFile */: + case 298 /* SourceFile */: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return visitNodes(cbNode, cbNodes, node.declarations); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 240 /* ContinueStatement */: - case 241 /* BreakStatement */: + case 241 /* ContinueStatement */: + case 242 /* BreakStatement */: return visitNode(cbNode, node.label); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return visitNodes(cbNode, cbNodes, node.clauses); - case 284 /* CaseClause */: + case 285 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: return visitNodes(cbNode, cbNodes, node.statements); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 161 /* Decorator */: + case 162 /* Decorator */: return visitNode(cbNode, node.expression); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 291 /* EnumMember */: + case 292 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: return visitNode(cbNode, node.name); - case 264 /* NamedImports */: - case 268 /* NamedExports */: + case 265 /* NamedImports */: + case 269 /* NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 194 /* TemplateLiteralTypeSpan */: + case 195 /* TemplateLiteralTypeSpan */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.literal); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: return visitNodes(cbNode, cbNodes, node.types); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 271 /* MissingDeclaration */: + case 272 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return visitNode(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingFragment); - case 274 /* JsxSelfClosingElement */: - case 275 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 282 /* JsxSpreadAttribute */: + case 283 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 276 /* JsxClosingElement */: + case 277 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 180 /* OptionalType */: - case 181 /* RestType */: - case 301 /* JSDocTypeExpression */: - case 306 /* JSDocNonNullableType */: - case 305 /* JSDocNullableType */: - case 307 /* JSDocOptionalType */: - case 309 /* JSDocVariadicType */: + case 181 /* OptionalType */: + case 182 /* RestType */: + case 302 /* JSDocTypeExpression */: + case 307 /* JSDocNonNullableType */: + case 306 /* JSDocNullableType */: + case 308 /* JSDocOptionalType */: + case 310 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 311 /* JSDocComment */: - return visitNodes(cbNode, cbNodes, node.tags); - case 332 /* JSDocSeeTag */: + case 312 /* JSDocComment */: + return (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) + || visitNodes(cbNode, cbNodes, node.tags); + case 336 /* JSDocSeeTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.name); - case 302 /* JSDocNameReference */: + visitNode(cbNode, node.name) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 303 /* JSDocNameReference */: return visitNode(cbNode, node.name); - case 326 /* JSDocParameterTag */: - case 333 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: return visitNode(cbNode, node.tagName) || (node.isNameFirst ? visitNode(cbNode, node.name) || - visitNode(cbNode, node.typeExpression) + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) : visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.name)); - case 317 /* JSDocAuthorTag */: - return visitNode(cbNode, node.tagName); - case 316 /* JSDocImplementsTag */: + visitNode(cbNode, node.name)) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 320 /* JSDocAuthorTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.class); - case 315 /* JSDocAugmentsTag */: + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 319 /* JSDocImplementsTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.class); - case 330 /* JSDocTemplateTag */: + visitNode(cbNode, node.class) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 318 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 334 /* JSDocTemplateTag */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.constraint) || - visitNodes(cbNode, cbNodes, node.typeParameters); - case 331 /* JSDocTypedefTag */: + visitNodes(cbNode, cbNodes, node.typeParameters) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 335 /* JSDocTypedefTag */: return visitNode(cbNode, node.tagName) || (node.typeExpression && - node.typeExpression.kind === 301 /* JSDocTypeExpression */ + node.typeExpression.kind === 302 /* JSDocTypeExpression */ ? visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName) + visitNode(cbNode, node.fullName) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) : visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression)); - case 324 /* JSDocCallbackTag */: + visitNode(cbNode, node.typeExpression)) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 328 /* JSDocCallbackTag */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression); - case 327 /* JSDocReturnTag */: - case 329 /* JSDocTypeTag */: - case 328 /* JSDocThisTag */: - case 325 /* JSDocEnumTag */: + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 331 /* JSDocReturnTag */: + case 333 /* JSDocTypeTag */: + case 332 /* JSDocThisTag */: + case 329 /* JSDocEnumTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.typeExpression); - case 313 /* JSDocSignature */: + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 315 /* JSDocSignature */: return ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 312 /* JSDocTypeLiteral */: + case 316 /* JSDocLink */: + return visitNode(cbNode, node.name); + case 314 /* JSDocTypeLiteral */: return ts.forEach(node.jsDocPropertyTags, cbNode); - case 314 /* JSDocTag */: - case 319 /* JSDocClassTag */: - case 320 /* JSDocPublicTag */: - case 321 /* JSDocPrivateTag */: - case 322 /* JSDocProtectedTag */: - case 323 /* JSDocReadonlyTag */: - return visitNode(cbNode, node.tagName); - case 336 /* PartiallyEmittedExpression */: + case 317 /* JSDocTag */: + case 322 /* JSDocClassTag */: + case 323 /* JSDocPublicTag */: + case 324 /* JSDocPrivateTag */: + case 325 /* JSDocProtectedTag */: + case 326 /* JSDocReadonlyTag */: + case 321 /* JSDocDeprecatedTag */: + return visitNode(cbNode, node.tagName) + || (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 340 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -28636,62 +29539,58 @@ var ts; * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure. */ function forEachChildRecursively(rootNode, cbNode, cbNodes) { - var stack = [rootNode]; - while (stack.length) { - var parent = stack.pop(); - var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent)); - if (res) { - return res; - } - } - return; - function gatherPossibleChildren(node) { - var children = []; - forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal - return children; - function addWorkItem(n) { - children.unshift(n); - } - } - function visitAllPossibleChildren(parent, children) { - for (var _i = 0, children_5 = children; _i < children_5.length; _i++) { - var child = children_5[_i]; - if (ts.isArray(child)) { - if (cbNodes) { - var res = cbNodes(child, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - } - for (var i = child.length - 1; i >= 0; i--) { - var realChild = child[i]; - var res = cbNode(realChild, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - stack.push(realChild); - } - } - else { - stack.push(child); - var res = cbNode(child, parent); + var queue = gatherPossibleChildren(rootNode); + var parents = []; // tracks parent references for elements in queue + while (parents.length < queue.length) { + parents.push(rootNode); + } + while (queue.length !== 0) { + var current = queue.pop(); + var parent = parents.pop(); + if (ts.isArray(current)) { + if (cbNodes) { + var res = cbNodes(current, parent); if (res) { if (res === "skip") continue; return res; } } + for (var i = current.length - 1; i >= 0; --i) { + queue.push(current[i]); + parents.push(parent); + } + } + else { + var res = cbNode(current, parent); + if (res) { + if (res === "skip") + continue; + return res; + } + if (current.kind >= 158 /* FirstNode */) { + // add children in reverse order to the queue, so popping gives the first child + for (var _i = 0, _a = gatherPossibleChildren(current); _i < _a.length; _i++) { + var child = _a[_i]; + queue.push(child); + parents.push(current); + } + } } } } ts.forEachChildRecursively = forEachChildRecursively; + function gatherPossibleChildren(node) { + var children = []; + forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal + return children; + function addWorkItem(n) { + children.unshift(n); + } + } function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeParse"); var result; ts.perfLogger.logStartParseSourceFile(fileName); @@ -28704,7 +29603,7 @@ var ts; ts.perfLogger.logStopParseSourceFile(); ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } ts.createSourceFile = createSourceFile; @@ -28886,11 +29785,12 @@ var ts; // attached to the EOF token. var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + var _a; if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); if (scriptKind === 6 /* JSON */) { var result_3 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); - ts.convertToObjectWorker(result_3, result_3.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + ts.convertToObjectWorker(result_3, (_a = result_3.statements[0]) === null || _a === void 0 ? void 0 : _a.expression, result_3.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); result_3.referencedFiles = ts.emptyArray; result_3.typeReferenceDirectives = ts.emptyArray; result_3.libReferenceDirectives = ts.emptyArray; @@ -28930,35 +29830,54 @@ var ts; endOfFileToken = parseTokenNode(); } else { - var expression = void 0; - switch (token()) { - case 22 /* OpenBracketToken */: - expression = parseArrayLiteralExpression(); - break; - case 109 /* TrueKeyword */: - case 94 /* FalseKeyword */: - case 103 /* NullKeyword */: - expression = parseTokenNode(); - break; - case 40 /* MinusToken */: - if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) { - expression = parsePrefixUnaryExpression(); - } - else { - expression = parseObjectLiteralExpression(); - } - break; - case 8 /* NumericLiteral */: - case 10 /* StringLiteral */: - if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) { - expression = parseLiteralNode(); + // Loop and synthesize an ArrayLiteralExpression if there are more than + // one top-level expressions to ensure all input text is consumed. + var expressions = void 0; + while (token() !== 1 /* EndOfFileToken */) { + var expression_1 = void 0; + switch (token()) { + case 22 /* OpenBracketToken */: + expression_1 = parseArrayLiteralExpression(); + break; + case 109 /* TrueKeyword */: + case 94 /* FalseKeyword */: + case 103 /* NullKeyword */: + expression_1 = parseTokenNode(); + break; + case 40 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) { + expression_1 = parsePrefixUnaryExpression(); + } + else { + expression_1 = parseObjectLiteralExpression(); + } + break; + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) { + expression_1 = parseLiteralNode(); + break; + } + // falls through + default: + expression_1 = parseObjectLiteralExpression(); break; + } + // Error recovery: collect multiple top-level expressions + if (expressions && ts.isArray(expressions)) { + expressions.push(expression_1); + } + else if (expressions) { + expressions = [expressions, expression_1]; + } + else { + expressions = expression_1; + if (token() !== 1 /* EndOfFileToken */) { + parseErrorAtCurrentToken(ts.Diagnostics.Unexpected_token); } - // falls through - default: - expression = parseObjectLiteralExpression(); - break; + } } + var expression = ts.isArray(expressions) ? finishNode(factory.createArrayLiteralExpression(expressions), pos) : ts.Debug.checkDefined(expressions); var statement = factory.createExpressionStatement(expression); finishNode(statement, pos); statements = createNodeArray([statement], pos); @@ -29153,7 +30072,7 @@ var ts; return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements)); function containsPossibleTopLevelAwait(node) { return !(node.flags & 32768 /* AwaitContext */) - && !!(node.transformFlags & 8388608 /* ContainsPossibleTopLevelAwait */); + && !!(node.transformFlags & 16777216 /* ContainsPossibleTopLevelAwait */); } function findNextStatementWithAwait(statements, start) { for (var i = start; i < statements.length; i++) { @@ -29194,7 +30113,7 @@ var ts; ts.setTextRangePosWidth(sourceFile, 0, sourceText.length); setExternalModuleIndicator(sourceFile); // If we parsed this as an external module, it may contain top-level await - if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 8388608 /* ContainsPossibleTopLevelAwait */) { + if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 16777216 /* ContainsPossibleTopLevelAwait */) { sourceFile = reparseTopLevelAwait(sourceFile); } sourceFile.text = sourceText; @@ -29565,7 +30484,7 @@ var ts; ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, "", "", /*templateFlags*/ undefined) : kind === 8 /* NumericLiteral */ ? factory.createNumericLiteral("", /*numericLiteralFlags*/ undefined) : kind === 10 /* StringLiteral */ ? factory.createStringLiteral("", /*isSingleQuote*/ undefined) : - kind === 271 /* MissingDeclaration */ ? factory.createMissingDeclaration() : + kind === 272 /* MissingDeclaration */ ? factory.createMissingDeclaration() : factory.createToken(kind); return finishNode(result, pos); } @@ -29580,8 +30499,8 @@ var ts; // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for // each identifier in order to reduce memory consumption. function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) { - identifierCount++; if (isIdentifier) { + identifierCount++; var pos = getNodePos(); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker var originalKeywordKind = token(); @@ -29593,6 +30512,11 @@ var ts; parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); return createIdentifier(/*isIdentifier*/ true); } + if (token() === 0 /* Unknown */ && scanner.tryScan(function () { return scanner.reScanInvalidIdentifier() === 78 /* Identifier */; })) { + // Scanner has already recorded an 'Invalid character' error, so no need to add another from the parser. + return createIdentifier(/*isIdentifier*/ true); + } + identifierCount++; // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; var isReservedWord = scanner.isReservedWord(); @@ -29947,8 +30871,7 @@ var ts; var listPos = getNodePos(); while (!isListTerminator(kind)) { if (isListElement(kind, /*inErrorRecovery*/ false)) { - var element = parseListElement(kind, parseElement); - list.push(element); + list.push(parseListElement(kind, parseElement)); continue; } if (abortParsingListOrMoveToNextToken(kind)) { @@ -30098,14 +31021,14 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 166 /* Constructor */: - case 171 /* IndexSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 163 /* PropertyDeclaration */: - case 229 /* SemicolonClassElement */: + case 167 /* Constructor */: + case 172 /* IndexSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 230 /* SemicolonClassElement */: return true; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. @@ -30120,8 +31043,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: return true; } } @@ -30130,58 +31053,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 232 /* VariableStatement */: - case 230 /* Block */: - case 234 /* IfStatement */: - case 233 /* ExpressionStatement */: - case 246 /* ThrowStatement */: - case 242 /* ReturnStatement */: - case 244 /* SwitchStatement */: - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 237 /* ForStatement */: - case 236 /* WhileStatement */: - case 243 /* WithStatement */: - case 231 /* EmptyStatement */: - case 247 /* TryStatement */: - case 245 /* LabeledStatement */: - case 235 /* DoStatement */: - case 248 /* DebuggerStatement */: - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 252 /* FunctionDeclaration */: + case 233 /* VariableStatement */: + case 231 /* Block */: + case 235 /* IfStatement */: + case 234 /* ExpressionStatement */: + case 247 /* ThrowStatement */: + case 243 /* ReturnStatement */: + case 245 /* SwitchStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 238 /* ForStatement */: + case 237 /* WhileStatement */: + case 244 /* WithStatement */: + case 232 /* EmptyStatement */: + case 248 /* TryStatement */: + case 246 /* LabeledStatement */: + case 236 /* DoStatement */: + case 249 /* DebuggerStatement */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 291 /* EnumMember */; + return node.kind === 292 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 170 /* ConstructSignature */: - case 164 /* MethodSignature */: - case 171 /* IndexSignature */: - case 162 /* PropertySignature */: - case 169 /* CallSignature */: + case 171 /* ConstructSignature */: + case 165 /* MethodSignature */: + case 172 /* IndexSignature */: + case 163 /* PropertySignature */: + case 170 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 249 /* VariableDeclaration */) { + if (node.kind !== 250 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -30202,7 +31125,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 160 /* Parameter */) { + if (node.kind !== 161 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -30483,14 +31406,14 @@ var ts; // If true, we should abort parsing an error function. function typeHasArrowFunctionBlockingParseError(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return ts.nodeIsMissing(node.typeName); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: { + case 175 /* FunctionType */: + case 176 /* ConstructorType */: { var _a = node, parameters = _a.parameters, type = _a.type; return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); } - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return typeHasArrowFunctionBlockingParseError(node.type); default: return false; @@ -30671,19 +31594,21 @@ var ts; function parseParameterWorker(inOuterAwaitContext) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); + // FormalParameter [Yield,Await]: + // BindingElement[?Yield,?Await] + // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. + var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); if (token() === 107 /* ThisKeyword */) { - var node_1 = factory.createParameterDeclaration( - /*decorators*/ undefined, + var node_1 = factory.createParameterDeclaration(decorators, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), /*questionToken*/ undefined, parseTypeAnnotation(), /*initializer*/ undefined); + if (decorators) { + parseErrorAtRange(decorators[0], ts.Diagnostics.Decorators_may_not_be_applied_to_this_parameters); + } return withJSDoc(finishNode(node_1, pos), hasJSDoc); } - // FormalParameter [Yield,Await]: - // BindingElement[?Yield,?Await] - // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. - var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); var savedTopLevel = topLevel; topLevel = false; var modifiers = parseModifiers(); @@ -30770,14 +31695,14 @@ var ts; function parseSignatureMember(kind) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); - if (kind === 170 /* ConstructSignature */) { + if (kind === 171 /* ConstructSignature */) { parseExpected(102 /* NewKeyword */); } var typeParameters = parseTypeParameters(); var parameters = parseParameters(4 /* Type */); var type = parseReturnType(58 /* ColonToken */, /*isType*/ true); parseTypeMemberSemicolon(); - var node = kind === 169 /* CallSignature */ + var node = kind === 170 /* CallSignature */ ? factory.createCallSignature(typeParameters, parameters, type) : factory.createConstructSignature(typeParameters, parameters, type); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -30868,7 +31793,10 @@ var ts; } function isTypeMemberStart() { // Return true if we have the start of a signature member - if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) { + if (token() === 20 /* OpenParenToken */ || + token() === 29 /* LessThanToken */ || + token() === 134 /* GetKeyword */ || + token() === 146 /* SetKeyword */) { return true; } var idToken = false; @@ -30900,14 +31828,20 @@ var ts; } function parseTypeMember() { if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) { - return parseSignatureMember(169 /* CallSignature */); + return parseSignatureMember(170 /* CallSignature */); } if (token() === 102 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(170 /* ConstructSignature */); + return parseSignatureMember(171 /* ConstructSignature */); } var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiers(); + if (parseContextualModifier(134 /* GetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 168 /* GetAccessor */); + } + if (parseContextualModifier(146 /* SetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 169 /* SetAccessor */); + } if (isIndexSignature()) { return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers); } @@ -31940,7 +32874,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand, pos); } function isInOrOfKeyword(t) { - return t === 100 /* InKeyword */ || t === 156 /* OfKeyword */; + return t === 100 /* InKeyword */ || t === 157 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand, pos) { while (true) { @@ -32080,7 +33014,7 @@ var ts; if (token() === 42 /* AsteriskAsteriskToken */) { var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); var end = simpleUnaryExpression.end; - if (simpleUnaryExpression.kind === 206 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 207 /* TypeAssertionExpression */) { parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -32331,7 +33265,7 @@ var ts; var pos = getNodePos(); var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 275 /* JsxOpeningElement */) { + if (opening.kind === 276 /* JsxOpeningElement */) { var children = parseJsxChildren(opening); var closingElement = parseJsxClosingElement(inExpressionContext); if (!tagNamesAreEquivalent(opening.tagName, closingElement.tagName)) { @@ -32339,11 +33273,11 @@ var ts; } result = finishNode(factory.createJsxElement(opening, children, closingElement), pos); } - else if (opening.kind === 278 /* JsxOpeningFragment */) { + else if (opening.kind === 279 /* JsxOpeningFragment */) { result = finishNode(factory.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos); } else { - ts.Debug.assert(opening.kind === 274 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 275 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -32843,10 +33777,10 @@ var ts; var decorators = parseDecorators(); var modifiers = parseModifiers(); if (parseContextualModifier(134 /* GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167 /* GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* GetAccessor */); } if (parseContextualModifier(146 /* SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 169 /* SetAccessor */); } var asteriskToken = parseOptionalToken(41 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); @@ -32964,6 +33898,7 @@ var ts; // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); var openBracePosition = scanner.getTokenPos(); if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { var multiLine = scanner.hasPrecedingLineBreak(); @@ -32974,11 +33909,16 @@ var ts; ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); } } - return finishNode(factory.createBlock(statements, multiLine), pos); + var result = withJSDoc(finishNode(factory.createBlock(statements, multiLine), pos), hasJSDoc); + if (token() === 62 /* EqualsToken */) { + parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses); + nextToken(); + } + return result; } else { var statements = createMissingList(); - return finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos); + return withJSDoc(finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos), hasJSDoc); } } function parseFunctionBlock(flags, diagnosticMessage) { @@ -33005,21 +33945,24 @@ var ts; } function parseEmptyStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(26 /* SemicolonToken */); - return finishNode(factory.createEmptyStatement(), pos); + return withJSDoc(finishNode(factory.createEmptyStatement(), pos), hasJSDoc); } function parseIfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(98 /* IfKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var thenStatement = parseStatement(); var elseStatement = parseOptional(90 /* ElseKeyword */) ? parseStatement() : undefined; - return finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos); + return withJSDoc(finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc); } function parseDoStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(89 /* DoKeyword */); var statement = parseStatement(); parseExpected(114 /* WhileKeyword */); @@ -33031,19 +33974,21 @@ var ts; // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. parseOptional(26 /* SemicolonToken */); - return finishNode(factory.createDoStatement(statement, expression), pos); + return withJSDoc(finishNode(factory.createDoStatement(statement, expression), pos), hasJSDoc); } function parseWhileStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(114 /* WhileKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var statement = parseStatement(); - return finishNode(factory.createWhileStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWhileStatement(expression, statement), pos), hasJSDoc); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(96 /* ForKeyword */); var awaitToken = parseOptionalToken(130 /* AwaitKeyword */); parseExpected(20 /* OpenParenToken */); @@ -33057,7 +34002,7 @@ var ts; } } var node; - if (awaitToken ? parseExpected(156 /* OfKeyword */) : parseOptional(156 /* OfKeyword */)) { + if (awaitToken ? parseExpected(157 /* OfKeyword */) : parseOptional(157 /* OfKeyword */)) { var expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(21 /* CloseParenToken */); node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement()); @@ -33079,33 +34024,36 @@ var ts; parseExpected(21 /* CloseParenToken */); node = factory.createForStatement(initializer, condition, incrementor, parseStatement()); } - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseBreakOrContinueStatement(kind) { var pos = getNodePos(); - parseExpected(kind === 241 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */); + var hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(kind === 242 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */); var label = canParseSemicolon() ? undefined : parseIdentifier(); parseSemicolon(); - var node = kind === 241 /* BreakStatement */ + var node = kind === 242 /* BreakStatement */ ? factory.createBreakStatement(label) : factory.createContinueStatement(label); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseReturnStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(104 /* ReturnKeyword */); var expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression); parseSemicolon(); - return finishNode(factory.createReturnStatement(expression), pos); + return withJSDoc(finishNode(factory.createReturnStatement(expression), pos), hasJSDoc); } function parseWithStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(115 /* WithKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement); - return finishNode(factory.createWithStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWithStatement(expression, statement), pos), hasJSDoc); } function parseCaseClause() { var pos = getNodePos(); @@ -33134,17 +34082,19 @@ var ts; } function parseSwitchStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(106 /* SwitchKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var caseBlock = parseCaseBlock(); - return finishNode(factory.createSwitchStatement(expression, caseBlock), pos); + return withJSDoc(finishNode(factory.createSwitchStatement(expression, caseBlock), pos), hasJSDoc); } function parseThrowStatement() { // ThrowStatement[Yield] : // throw [no LineTerminator here]Expression[In, ?Yield]; var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(108 /* ThrowKeyword */); // Because of automatic semicolon insertion, we need to report error if this // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' @@ -33157,11 +34107,12 @@ var ts; expression = finishNode(factory.createIdentifier(""), getNodePos()); } parseSemicolon(); - return finishNode(factory.createThrowStatement(expression), pos); + return withJSDoc(finishNode(factory.createThrowStatement(expression), pos), hasJSDoc); } // TODO: Review for error recovery function parseTryStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(110 /* TryKeyword */); var tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); var catchClause = token() === 82 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -33172,7 +34123,7 @@ var ts; parseExpected(95 /* FinallyKeyword */); finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } - return finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos); + return withJSDoc(finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); } function parseCatchClause() { var pos = getNodePos(); @@ -33191,9 +34142,10 @@ var ts; } function parseDebuggerStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(86 /* DebuggerKeyword */); parseSemicolon(); - return finishNode(factory.createDebuggerStatement(), pos); + return withJSDoc(finishNode(factory.createDebuggerStatement(), pos), hasJSDoc); } function parseExpressionOrLabeledStatement() { // Avoiding having to do the lookahead for a labeled statement by just trying to parse @@ -33401,9 +34353,9 @@ var ts; case 96 /* ForKeyword */: return parseForOrForInOrForOfStatement(); case 85 /* ContinueKeyword */: - return parseBreakOrContinueStatement(240 /* ContinueStatement */); + return parseBreakOrContinueStatement(241 /* ContinueStatement */); case 80 /* BreakKeyword */: - return parseBreakOrContinueStatement(241 /* BreakStatement */); + return parseBreakOrContinueStatement(242 /* BreakStatement */); case 104 /* ReturnKeyword */: return parseReturnStatement(); case 115 /* WithKeyword */: @@ -33523,7 +34475,7 @@ var ts; if (decorators || modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - var missing = createMissingNode(271 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var missing = createMissingNode(272 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); ts.setTextRangePos(missing, pos); missing.decorators = decorators; missing.modifiers = modifiers; @@ -33605,6 +34557,7 @@ var ts; } function parseVariableDeclaration(allowExclamation) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); var name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations); var exclamationToken; if (allowExclamation && name.kind === 78 /* Identifier */ && @@ -33614,7 +34567,7 @@ var ts; var type = parseTypeAnnotation(); var initializer = isInOrOfKeyword(token()) ? undefined : parseInitializer(); var node = factory.createVariableDeclaration(name, exclamationToken, type, initializer); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseVariableDeclarationList(inForStatementInitializer) { var pos = getNodePos(); @@ -33642,7 +34595,7 @@ var ts; // this context. // The checker will then give an error that there is an empty declaration list. var declarations; - if (token() === 156 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 157 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { declarations = createMissingList(); } else { @@ -33746,12 +34699,12 @@ var ts; var parameters = parseParameters(0 /* None */); var type = parseReturnType(58 /* ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(0 /* None */); - var node = kind === 167 /* GetAccessor */ + var node = kind === 168 /* GetAccessor */ ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body); // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors node.typeParameters = typeParameters; - if (type && node.kind === 168 /* SetAccessor */) + if (type && node.kind === 169 /* SetAccessor */) node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -33894,10 +34847,10 @@ var ts; var decorators = parseDecorators(); var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); if (parseContextualModifier(134 /* GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167 /* GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* GetAccessor */); } if (parseContextualModifier(146 /* SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 169 /* SetAccessor */); } if (token() === 132 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) { var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers); @@ -33936,10 +34889,10 @@ var ts; return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, 221 /* ClassExpression */); + return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, 222 /* ClassExpression */); } function parseClassDeclaration(pos, hasJSDoc, decorators, modifiers) { - return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 252 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 253 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, kind) { var savedAwaitContext = inAwaitContext(); @@ -33961,7 +34914,7 @@ var ts; members = createMissingList(); } setAwaitContext(savedAwaitContext); - var node = kind === 252 /* ClassDeclaration */ + var node = kind === 253 /* ClassDeclaration */ ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -34200,7 +35153,7 @@ var ts; var namedBindings; if (!identifier || parseOptional(27 /* CommaToken */)) { - namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(264 /* NamedImports */); + namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(265 /* NamedImports */); } return finishNode(factory.createImportClause(isTypeOnly, identifier, namedBindings), pos); } @@ -34248,16 +35201,16 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - var node = kind === 264 /* NamedImports */ + var node = kind === 265 /* NamedImports */ ? factory.createNamedImports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseImportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */)) : factory.createNamedExports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */)); return finishNode(node, pos); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(270 /* ExportSpecifier */); + return parseImportOrExportSpecifier(271 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(265 /* ImportSpecifier */); + return parseImportOrExportSpecifier(266 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var pos = getNodePos(); @@ -34284,10 +35237,10 @@ var ts; else { name = identifierName; } - if (kind === 265 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 266 /* ImportSpecifier */ && checkIdentifierIsKeyword) { parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } - var node = kind === 265 /* ImportSpecifier */ + var node = kind === 266 /* ImportSpecifier */ ? factory.createImportSpecifier(propertyName, name) : factory.createExportSpecifier(propertyName, name); return finishNode(node, pos); @@ -34310,7 +35263,7 @@ var ts; moduleSpecifier = parseModuleSpecifier(); } else { - exportClause = parseNamedImportsOrExports(268 /* NamedExports */); + exportClause = parseNamedImportsOrExports(269 /* NamedExports */); // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. @@ -34499,7 +35452,10 @@ var ts; var tags; var tagsPos; var tagsEnd; + var linkEnd; + var commentsPos; var comments = []; + var parts = []; // + 3 for leading /**, - 5 in total for /** */ return scanner.scanRange(start + 3, length - 5, function () { // Initially we can parse out a tag. We also have seen a starting asterisk. @@ -34528,6 +35484,8 @@ var ts; case 59 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingWhitespace(comments); + if (!commentsPos) + commentsPos = getNodePos(); addTag(parseTag(indent)); // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning @@ -34570,6 +35528,22 @@ var ts; break; case 1 /* EndOfFileToken */: break loop; + case 18 /* OpenBraceToken */: + state = 2 /* SavingComments */; + var commentEnd = scanner.getStartPos(); + var linkStart = scanner.getTextPos() - 1; + var link = parseJSDocLink(linkStart); + if (link) { + if (!linkEnd) { + removeLeadingNewlines(comments); + } + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : start, commentEnd)); + parts.push(link); + comments = []; + linkEnd = scanner.getTextPos(); + break; + } + // fallthrough if it's not a {@link sequence default: // 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 @@ -34580,9 +35554,14 @@ var ts; } nextTokenJSDoc(); } - removeLeadingNewlines(comments); removeTrailingWhitespace(comments); - return createJSDocComment(); + if (parts.length && comments.length) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : start, commentsPos)); + } + if (parts.length && tags) + ts.Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); + var tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); + return finishNode(factory.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : comments.length ? comments.join("") : undefined, tagsArray), start, end); }); function removeLeadingNewlines(comments) { while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { @@ -34594,11 +35573,6 @@ var ts; comments.pop(); } } - function createJSDocComment() { - var comment = comments.length ? comments.join("") : undefined; - var tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); - return finishNode(factory.createJSDocComment(comment, tagsArray), start, end); - } function isNextNonwhitespaceTokenEndOfFile() { // We must use infinite lookahead, as there could be any number of newlines :( while (true) { @@ -34678,6 +35652,9 @@ var ts; case "readonly": tag = parseSimpleTag(start, factory.createJSDocReadonlyTag, tagName, margin, indentText); break; + case "override": + tag = parseSimpleTag(start, factory.createJSDocOverrideTag, tagName, margin, indentText); + break; case "deprecated": hasDeprecatedTag = true; tag = parseSimpleTag(start, factory.createJSDocDeprecatedTag, tagName, margin, indentText); @@ -34725,8 +35702,12 @@ var ts; return parseTagComments(margin, indentText.slice(margin)); } function parseTagComments(indent, initialMargin) { + var commentsPos = getNodePos(); var comments = []; + var parts = []; + var linkEnd; var state = 0 /* BeginningOfLine */; + var previousWhitespace = true; var margin; function pushComment(text) { if (!margin) { @@ -34752,7 +35733,9 @@ var ts; indent = 0; break; case 59 /* AtToken */: - if (state === 3 /* SavingBackticks */) { + if (state === 3 /* SavingBackticks */ + || state === 2 /* SavingComments */ && (!previousWhitespace || lookAhead(isNextJSDocTokenWhitespace))) { + // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace or not before whitespace comments.push(scanner.getTokenText()); break; } @@ -34776,13 +35759,18 @@ var ts; break; case 18 /* OpenBraceToken */: state = 2 /* SavingComments */; - if (lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) { - pushComment(scanner.getTokenText()); - nextTokenJSDoc(); + var commentEnd = scanner.getStartPos(); + var linkStart = scanner.getTextPos() - 1; + var link = parseJSDocLink(linkStart); + if (link) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : commentsPos, commentEnd)); + parts.push(link); + comments = []; + linkEnd = scanner.getTextPos(); + } + else { pushComment(scanner.getTokenText()); - nextTokenJSDoc(); } - pushComment(scanner.getTokenText()); break; case 61 /* BacktickToken */: if (state === 3 /* SavingBackticks */) { @@ -34809,15 +35797,51 @@ var ts; pushComment(scanner.getTokenText()); break; } + previousWhitespace = token() === 5 /* WhitespaceTrivia */; tok = nextTokenJSDoc(); } removeLeadingNewlines(comments); removeTrailingWhitespace(comments); - return comments.length === 0 ? undefined : comments.join(""); + if (parts.length) { + if (comments.length) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : commentsPos)); + } + return createNodeArray(parts, commentsPos, scanner.getTextPos()); + } + else if (comments.length) { + return comments.join(""); + } + } + function isNextJSDocTokenWhitespace() { + var next = nextTokenJSDoc(); + return next === 5 /* WhitespaceTrivia */ || next === 4 /* NewLineTrivia */; + } + function parseJSDocLink(start) { + if (!tryParse(parseJSDocLinkPrefix)) { + return undefined; + } + nextTokenJSDoc(); // start at token after link, then skip any whitespace + skipWhitespace(); + // parseEntityName logs an error for non-identifier, so create a MissingNode ourselves to avoid the error + var name = ts.tokenIsIdentifierOrKeyword(token()) + ? parseEntityName(/*allowReservedWords*/ true) + : undefined; + var text = []; + while (token() !== 19 /* CloseBraceToken */ && token() !== 4 /* NewLineTrivia */ && token() !== 1 /* EndOfFileToken */) { + text.push(scanner.getTokenText()); + nextTokenJSDoc(); + } + return finishNode(factory.createJSDocLink(name, text.join("")), start, scanner.getTextPos()); + } + function parseJSDocLinkPrefix() { + skipWhitespaceOrAsterisk(); + return token() === 18 /* OpenBraceToken */ + && nextTokenJSDoc() === 59 /* AtToken */ + && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) + && scanner.getTokenValue() === "link"; } function parseUnknownTag(start, tagName, indent, indentText) { - var end = getNodePos(); - return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function addTag(tag) { if (!tag) { @@ -34862,7 +35886,7 @@ var ts; switch (node.kind) { case 145 /* ObjectKeyword */: return true; - case 178 /* ArrayType */: + case 179 /* ArrayType */: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments; @@ -34873,11 +35897,11 @@ var ts; var isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; - skipWhitespace(); - if (isNameFirst) { + var indentText = skipWhitespaceOrAsterisk(); + if (isNameFirst && !lookAhead(parseJSDocLinkPrefix)) { typeExpression = tryParseTypeExpression(); } - var comment = parseTagComments(indent + scanner.getStartPos() - start); + var comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; @@ -34894,12 +35918,12 @@ var ts; var child = void 0; var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { - if (child.kind === 326 /* JSDocParameterTag */ || child.kind === 333 /* JSDocPropertyTag */) { + if (child.kind === 330 /* JSDocParameterTag */ || child.kind === 337 /* JSDocPropertyTag */) { children = ts.append(children, child); } } if (children) { - var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 178 /* ArrayType */), pos); + var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 179 /* ArrayType */), pos); return finishNode(factory.createJSDocTypeExpression(literal), pos); } } @@ -34909,27 +35933,34 @@ var ts; parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeExpression = tryParseTypeExpression(); - var end = getNodePos(); - return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function parseTypeTag(start, tagName, indent, indentText) { if (ts.some(tags, ts.isJSDocTypeTag)) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); - var end = getNodePos(); - var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined; - return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start, end); + var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; + return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start); } function parseSeeTag(start, tagName, indent, indentText) { - var nameExpression = parseJSDocNameReference(); - var end = getNodePos(); - var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined; - return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start, end); + var isLink = lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; }); + var nameExpression = isLink ? undefined : parseJSDocNameReference(); + var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; + return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start); } function parseAuthorTag(start, tagName, indent, indentText) { - var comments = parseAuthorNameAndEmail() + (parseTrailingTagComments(start, end, indent, indentText) || ""); - return finishNode(factory.createJSDocAuthorTag(tagName, comments || undefined), start); + var commentStart = getNodePos(); + var textOnly = parseAuthorNameAndEmail(); + var commentEnd = scanner.getStartPos(); + var comments = parseTrailingTagComments(start, commentEnd, indent, indentText); + if (!comments) { + commentEnd = scanner.getStartPos(); + } + var allParts = typeof comments !== "string" + ? createNodeArray(ts.concatenate([finishNode(textOnly, commentStart, commentEnd)], comments), commentStart) // cast away readonly + : textOnly.text + comments; + return finishNode(factory.createJSDocAuthorTag(tagName, allParts), start); } function parseAuthorNameAndEmail() { var comments = []; @@ -34950,17 +35981,15 @@ var ts; comments.push(scanner.getTokenText()); token = nextTokenJSDoc(); } - return comments.join(""); + return factory.createJSDocText(comments.join("")); } function parseImplementsTag(start, tagName, margin, indentText) { var className = parseExpressionWithTypeArgumentsForAugments(); - var end = getNodePos(); - return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseAugmentsTag(start, tagName, margin, indentText) { var className = parseExpressionWithTypeArgumentsForAugments(); - var end = getNodePos(); - return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseExpressionWithTypeArgumentsForAugments() { var usedBrace = parseOptional(18 /* OpenBraceToken */); @@ -34984,20 +36013,17 @@ var ts; return node; } function parseSimpleTag(start, createTag, tagName, margin, indentText) { - var end = getNodePos(); - return finishNode(createTag(tagName, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(createTag(tagName, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseThisTag(start, tagName, margin, indentText) { var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); - var end = getNodePos(); - return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseEnumTag(start, tagName, margin, indentText) { var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); - var end = getNodePos(); - return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseTypedefTag(start, tagName, indent, indentText) { var _a; @@ -35014,7 +36040,7 @@ var ts; var hasChildren = false; while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { hasChildren = true; - if (child.kind === 329 /* JSDocTypeTag */) { + if (child.kind === 333 /* JSDocTypeTag */) { if (childTypeTag) { parseErrorAtCurrentToken(ts.Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags); var lastError = ts.lastOrUndefined(parseDiagnostics); @@ -35032,7 +36058,7 @@ var ts; } } if (hasChildren) { - var isArrayType = typeExpression && typeExpression.type.kind === 178 /* ArrayType */; + var isArrayType = typeExpression && typeExpression.type.kind === 179 /* ArrayType */; var jsdocTypeLiteral = factory.createJSDocTypeLiteral(jsDocPropertyTags, isArrayType); typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : @@ -35085,17 +36111,16 @@ var ts; var returnTag = tryParse(function () { if (parseOptionalJsdoc(59 /* AtToken */)) { var tag = parseTag(indent); - if (tag && tag.kind === 327 /* JSDocReturnTag */) { + if (tag && tag.kind === 331 /* JSDocReturnTag */) { return tag; } } }); var typeExpression = finishNode(factory.createJSDocSignature(/*typeParameters*/ undefined, parameters, returnTag), start); - var end = getNodePos(); if (!comment) { - comment = parseTrailingTagComments(start, end, indent, indentText); + comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); } - return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start, end); + return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start); } function escapedTextsEqual(a, b) { while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { @@ -35120,7 +36145,7 @@ var ts; case 59 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target, indent); - if (child && (child.kind === 326 /* JSDocParameterTag */ || child.kind === 333 /* JSDocPropertyTag */) && + if (child && (child.kind === 330 /* JSDocParameterTag */ || child.kind === 337 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -35177,6 +36202,9 @@ var ts; function parseTemplateTagTypeParameter() { var typeParameterPos = getNodePos(); var name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); + if (ts.nodeIsMissing(name)) { + return undefined; + } return finishNode(factory.createTypeParameterDeclaration(name, /*constraint*/ undefined, /*defaultType*/ undefined), typeParameterPos); } function parseTemplateTagTypeParameters() { @@ -35184,7 +36212,10 @@ var ts; var typeParameters = []; do { skipWhitespace(); - typeParameters.push(parseTemplateTagTypeParameter()); + var node = parseTemplateTagTypeParameter(); + if (node !== undefined) { + typeParameters.push(node); + } skipWhitespaceOrAsterisk(); } while (parseOptionalJsdoc(27 /* CommaToken */)); return createNodeArray(typeParameters, pos); @@ -35203,8 +36234,7 @@ var ts; // TODO: Consider only parsing a single type parameter if there is a constraint. var constraint = token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; var typeParameters = parseTemplateTagTypeParameters(); - var end = getNodePos(); - return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function parseOptionalJsdoc(t) { if (token() === t) { @@ -36019,6 +37049,7 @@ var ts; ["es2018", "lib.es2018.d.ts"], ["es2019", "lib.es2019.d.ts"], ["es2020", "lib.es2020.d.ts"], + ["es2021", "lib.es2021.d.ts"], ["esnext", "lib.esnext.d.ts"], // Host only ["dom", "lib.dom.d.ts"], @@ -36058,14 +37089,17 @@ var ts; ["es2020.string", "lib.es2020.string.d.ts"], ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"], ["es2020.intl", "lib.es2020.intl.d.ts"], + ["es2021.promise", "lib.es2021.promise.d.ts"], + ["es2021.string", "lib.es2021.string.d.ts"], + ["es2021.weakref", "lib.es2021.weakref.d.ts"], ["esnext.array", "lib.es2019.array.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"], ["esnext.intl", "lib.esnext.intl.d.ts"], ["esnext.bigint", "lib.es2020.bigint.d.ts"], - ["esnext.string", "lib.esnext.string.d.ts"], - ["esnext.promise", "lib.esnext.promise.d.ts"], - ["esnext.weakref", "lib.esnext.weakref.d.ts"] + ["esnext.string", "lib.es2021.string.d.ts"], + ["esnext.promise", "lib.es2021.promise.d.ts"], + ["esnext.weakref", "lib.es2021.weakref.d.ts"] ]; /** * An array of supported "lib" reference file names used to determine the order for inclusion @@ -36089,11 +37123,12 @@ var ts; fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval, prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval, dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling, + fixedchunksizepolling: ts.WatchFileKind.FixedChunkSizePolling, usefsevents: ts.WatchFileKind.UseFsEvents, usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory, })), category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory, + description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling_UseFsEvents_UseFsEventsOnParentDirectory, }, { name: "watchDirectory", @@ -36101,9 +37136,10 @@ var ts; usefsevents: ts.WatchDirectoryKind.UseFsEvents, fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval, dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling, + fixedchunksizepolling: ts.WatchDirectoryKind.FixedChunkSizePolling, })), category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling, + description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling, }, { name: "fallbackPolling", @@ -36111,9 +37147,10 @@ var ts; fixedinterval: ts.PollingWatchKind.FixedInterval, priorityinterval: ts.PollingWatchKind.PriorityInterval, dynamicpriority: ts.PollingWatchKind.DynamicPriority, + fixedchunksize: ts.PollingWatchKind.FixedChunkSize, })), category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority, + description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority_FixedChunkSize, }, { name: "synchronousWatchDirectory", @@ -36272,6 +37309,7 @@ var ts; es2018: 5 /* ES2018 */, es2019: 6 /* ES2019 */, es2020: 7 /* ES2020 */, + es2021: 8 /* ES2021 */, esnext: 99 /* ESNext */, })), affectsSourceFile: true, @@ -36280,10 +37318,10 @@ var ts; paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT, }; - /* @internal */ - ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsWithoutBuild = [ + // CommandLine only options { name: "all", type: "boolean", @@ -36646,6 +37684,14 @@ var ts; category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Include_undefined_in_index_signature_results }, + { + name: "noImplicitOverride", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier + }, { name: "noPropertyAccessFromIndexSignature", type: "boolean", @@ -37061,7 +38107,9 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins }, - ]); + ]; + /* @internal */ + ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsWithoutBuild); /* @internal */ ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); /* @internal */ @@ -37076,8 +38124,7 @@ var ts; ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) { return ts.hasProperty(option, "transpileOptionValue"); }); - /* @internal */ - ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsOnlyBuild = [ { name: "verbose", shortName: "v", @@ -37105,7 +38152,9 @@ var ts; description: ts.Diagnostics.Delete_the_outputs_of_all_projects, type: "boolean" } - ]); + ]; + /* @internal */ + ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsOnlyBuild); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -37159,6 +38208,10 @@ var ts; return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations)); } ts.getOptionsNameMap = getOptionsNameMap; + var compilerOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_only_be_used_with_build, + getOptionsNameMap: getBuildOptionsNameMap + }; /* @internal */ ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, @@ -37220,6 +38273,10 @@ var ts; return option.name; } function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) { + var _a; + if ((_a = diagnostics.alternateMode) === null || _a === void 0 ? void 0 : _a.getOptionsNameMap().optionsNameMap.has(unknownOption.toLowerCase())) { + return createDiagnostics(diagnostics.alternateMode.diagnostic, unknownOption); + } var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName); return possibleOption ? createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : @@ -37374,6 +38431,7 @@ var ts; } /*@internal*/ ts.compilerOptionsDidYouMeanDiagnostics = { + alternateMode: compilerOptionsAlternateMode, getOptionsNameMap: getOptionsNameMap, optionDeclarations: ts.optionDeclarations, unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, @@ -37406,7 +38464,12 @@ var ts; function getBuildOptionsNameMap() { return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts)); } + var buildOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_not_be_used_with_build, + getOptionsNameMap: getOptionsNameMap + }; var buildOptionsDidYouMeanDiagnostics = { + alternateMode: buildOptionsAlternateMode, getOptionsNameMap: getBuildOptionsNameMap, optionDeclarations: ts.buildOpts, unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0, @@ -37482,7 +38545,7 @@ var ts; function parseConfigFileTextToJson(fileName, jsonText) { var jsonSourceFile = ts.parseJsonText(fileName, jsonText); return { - config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + config: convertConfigFileToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics, /*reportOptionsErrors*/ false, /*optionsIterator*/ undefined), error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined }; } @@ -37612,11 +38675,31 @@ var ts; } return _tsconfigRootOptions; } + function convertConfigFileToObject(sourceFile, errors, reportOptionsErrors, optionsIterator) { + var _a; + var rootExpression = (_a = sourceFile.statements[0]) === null || _a === void 0 ? void 0 : _a.expression; + var knownRootOptions = reportOptionsErrors ? getTsconfigRootOptionsMap() : undefined; + if (rootExpression && rootExpression.kind !== 201 /* ObjectLiteralExpression */) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, rootExpression, ts.Diagnostics.The_root_value_of_a_0_file_must_be_an_object, ts.getBaseFileName(sourceFile.fileName) === "jsconfig.json" ? "jsconfig.json" : "tsconfig.json")); + // Last-ditch error recovery. Somewhat useful because the JSON parser will recover from some parse errors by + // synthesizing a top-level array literal expression. There's a reasonable chance the first element of that + // array is a well-formed configuration object, made into an array element by stray characters. + if (ts.isArrayLiteralExpression(rootExpression)) { + var firstObject = ts.find(rootExpression.elements, ts.isObjectLiteralExpression); + if (firstObject) { + return convertToObjectWorker(sourceFile, firstObject, errors, /*returnValue*/ true, knownRootOptions, optionsIterator); + } + } + return {}; + } + return convertToObjectWorker(sourceFile, rootExpression, errors, /*returnValue*/ true, knownRootOptions, optionsIterator); + } /** * Convert the json syntax tree into the json value */ function convertToObject(sourceFile, errors) { - return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + var _a; + return convertToObjectWorker(sourceFile, (_a = sourceFile.statements[0]) === null || _a === void 0 ? void 0 : _a.expression, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); } ts.convertToObject = convertToObject; /** @@ -37625,18 +38708,18 @@ var ts; * Otherwise it just checks the errors and returns undefined */ /*@internal*/ - function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { - if (!sourceFile.statements.length) { + function convertToObjectWorker(sourceFile, rootExpression, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!rootExpression) { return returnValue ? {} : undefined; } - return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + return convertPropertyValueToJson(rootExpression, knownRootOptions); function isRootOptionMap(knownOptions) { return knownRootOptions && knownRootOptions.elementOptions === knownOptions; } function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) { var result = returnValue ? {} : undefined; var _loop_4 = function (element) { - if (element.kind !== 288 /* PropertyAssignment */) { + if (element.kind !== 289 /* PropertyAssignment */) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); return "continue"; } @@ -37730,13 +38813,13 @@ var ts; case 8 /* NumericLiteral */: reportInvalidOptionValue(option && option.type !== "number"); return validateValue(Number(valueExpression.text)); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { break; // not valid JSON syntax } reportInvalidOptionValue(option && option.type !== "number"); return validateValue(-Number(valueExpression.operand.text)); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; // Currently having element option declaration in the tsconfig with type "object" @@ -37753,7 +38836,7 @@ var ts; return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined)); } - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: reportInvalidOptionValue(option && option.type !== "list"); return validateValue(convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element)); } @@ -38301,14 +39384,14 @@ var ts; if (ownConfig.extendedConfigPath) { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, resolutionStack, errors, extendedConfigCache); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { var baseRaw_1 = extendedConfig.raw; var raw_1 = ownConfig.raw; + var relativeDifference_1; var setPropertyInRawIfNotUndefined = function (propertyName) { - var value = raw_1[propertyName] || baseRaw_1[propertyName]; - if (value) { - raw_1[propertyName] = value; + if (!raw_1[propertyName] && baseRaw_1[propertyName]) { + raw_1[propertyName] = ts.map(baseRaw_1[propertyName], function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1 || (relativeDifference_1 = ts.convertToRelativePath(ts.getDirectoryPath(ownConfig.extendedConfigPath), basePath, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames))), path); }); } }; setPropertyInRawIfNotUndefined("include"); @@ -38390,7 +39473,7 @@ var ts; } } }; - var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); + var json = convertConfigFileToObject(sourceFile, errors, /*reportOptionsErrors*/ true, optionsIterator); if (!typeAcquisition) { if (typingOptionstypeAcquisition) { typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? @@ -38428,7 +39511,7 @@ var ts; errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig)); return undefined; } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) { + function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache) { var _a; var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath); var value; @@ -38440,22 +39523,7 @@ var ts; else { extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (!extendedResult.parseDiagnostics.length) { - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); - if (isSuccessfulParsedTsconfig(extendedConfig)) { - // Update the paths to reflect base path - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); - var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; - var mapPropertiesInRawIfNotUndefined = function (propertyName) { - if (raw_2[propertyName]) { - raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); - } - }; - var raw_2 = extendedConfig.raw; - mapPropertiesInRawIfNotUndefined("include"); - mapPropertiesInRawIfNotUndefined("exclude"); - mapPropertiesInRawIfNotUndefined("files"); - } + extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, ts.getDirectoryPath(extendedConfigPath), ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); } if (extendedConfigCache) { extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig }); @@ -39152,13 +40220,24 @@ var ts; * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache) { var traceEnabled = isTraceEnabled(options, host); if (redirectedReference) { options = redirectedReference.commandLine.options; } - var failedLookupLocations = []; - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var containingDirectory = containingFile ? ts.getDirectoryPath(containingFile) : undefined; + var perFolderCache = containingDirectory ? cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference) : undefined; + var result = perFolderCache && perFolderCache.get(typeReferenceDirectiveName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile); + if (redirectedReference) + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + trace(host, ts.Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory); + traceResult(result); + } + return result; + } var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -39181,6 +40260,8 @@ var ts; trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); } } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -39191,17 +40272,31 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); - if (traceEnabled) { - if (packageId) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, ts.packageIdToString(packageId), primary); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); - } + resolvedTypeReferenceDirective = { + primary: primary, + resolvedFileName: resolvedFileName, + originalPath: fileName === resolvedFileName ? undefined : fileName, + packageId: packageId, + isExternalLibraryImport: pathContainsNodeModules(fileName), + }; + } + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, result); + if (traceEnabled) + traceResult(result); + return result; + function traceResult(result) { + var _a; + if (!((_a = result.resolvedTypeReferenceDirective) === null || _a === void 0 ? void 0 : _a.resolvedFileName)) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + else if (result.resolvedTypeReferenceDirective.packageId) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, ts.packageIdToString(result.resolvedTypeReferenceDirective.packageId), result.resolvedTypeReferenceDirective.primary); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, result.resolvedTypeReferenceDirective.primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } - return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { // Check primary library paths if (typeRoots && typeRoots.length) { @@ -39231,20 +40326,16 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = void 0; + var result_4; if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); - result = searchResult && searchResult.value; + result_4 = searchResult && searchResult.value; } else { var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; - result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); - } - var resolvedFile = resolvedTypeScriptOnly(result); - if (!resolvedFile && traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + result_4 = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); } - return resolvedFile; + return resolvedTypeScriptOnly(result_4); } else { if (traceEnabled) { @@ -39299,22 +40390,21 @@ var ts; return result; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; - function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) { - return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName); - } - ts.createModuleResolutionCache = createModuleResolutionCache; /*@internal*/ function createCacheWithRedirects(options) { var ownMap = new ts.Map(); var redirectsMap = new ts.Map(); return { - ownMap: ownMap, + getOwnMap: getOwnMap, redirectsMap: redirectsMap, getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, clear: clear, setOwnOptions: setOwnOptions, setOwnMap: setOwnMap }; + function getOwnMap() { + return ownMap; + } function setOwnOptions(newOptions) { options = newOptions; } @@ -39340,26 +40430,88 @@ var ts; } } ts.createCacheWithRedirects = createCacheWithRedirects; - /*@internal*/ - function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { - return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap }; + function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { + var cache; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear }; + function getPackageJsonInfo(packageJsonPath) { + return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); + } + function setPackageJsonInfo(packageJsonPath, info) { + (cache || (cache = new ts.Map())).set(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info); + } + function clear() { + cache = undefined; + } + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + function updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + if (!options.configFile) + return; + if (directoryToModuleNameMap.redirectsMap.size === 0) { + // The own map will be for projectCompilerOptions + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size === 0); + ts.Debug.assert(directoryToModuleNameMap.getOwnMap().size === 0); + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.getOwnMap().size === 0); + directoryToModuleNameMap.redirectsMap.set(options.configFile.path, directoryToModuleNameMap.getOwnMap()); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.redirectsMap.set(options.configFile.path, moduleNameToDirectoryMap.getOwnMap()); + } + else { + // Set correct own map + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size > 0); + var ref = { + sourceFile: options.configFile, + commandLine: { options: options } + }; + directoryToModuleNameMap.setOwnMap(directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnMap(moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); + } + directoryToModuleNameMap.setOwnOptions(options); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnOptions(options); + } + function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap) { + return { + getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, + clear: clear, + update: update, + }; + function clear() { + directoryToModuleNameMap.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap); + } function getOrCreateCacheForDirectory(directoryName, redirectedReference) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, function () { return new ts.Map(); }); } + } + function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + moduleNameToDirectoryMap || (moduleNameToDirectoryMap = createCacheWithRedirects(options)); + var packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName); + return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, + clear: clear, + update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; } }); + function clear() { + preDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + packageJsonInfoCache.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); + } function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); } - function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { - var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); - var result = cache.get(key); - if (!result) { - result = create(); - cache.set(key, result); - } - return result; - } function createPerModuleNameCache() { var directoryPathMap = new ts.Map(); return { get: get, set: set }; @@ -39426,7 +40578,17 @@ var ts; } } } - ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + ts.createModuleResolutionCache = createModuleResolutionCache; + function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { + var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); + return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + function clear() { + preDirectoryResolutionCache.clear(); + packageJsonInfoCache.clear(); + } + } + ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache) { var containingDirectory = ts.getDirectoryPath(containingFile); var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); @@ -39704,7 +40866,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, state.resultFromCache); function tryResolve(extensions) { @@ -39764,7 +40926,7 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { - var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined; return withPackageId(packageInfo, resolvedFromFile); } @@ -39797,8 +40959,9 @@ var ts; * For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo" * For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo" */ + /* @internal */ function parseNodeModuleFromPath(resolved) { - var path = ts.normalizePath(resolved.path); + var path = ts.normalizePath(resolved); var idx = path.lastIndexOf(ts.nodeModulesPathPart); if (idx === -1) { return undefined; @@ -39810,6 +40973,7 @@ var ts; } return path.slice(0, indexAfterPackageName); } + ts.parseNodeModuleFromPath = parseNodeModuleFromPath; function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; @@ -39893,21 +41057,43 @@ var ts; return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { + var _a, _b, _c; var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); + if (onlyRecordFailures) { + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + var existing = (_a = state.packageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfo(packageJsonPath); + if (existing !== undefined) { + if (typeof existing !== "boolean") { + if (traceEnabled) + trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + return existing; + } + else { + if (existing && traceEnabled) + trace(host, ts.Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + } + var directoryExists = ts.directoryProbablyExists(packageDirectory, host); if (directoryExists && host.fileExists(packageJsonPath)) { var packageJsonContent = ts.readJson(packageJsonPath, host); if (traceEnabled) { trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); - return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + return result; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + (_c = state.packageJsonInfoCache) === null || _c === void 0 ? void 0 : _c.setPackageJsonInfo(packageJsonPath, directoryExists); // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results state.failedLookupLocations.push(packageJsonPath); } @@ -40156,7 +41342,7 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath @@ -40197,13 +41383,13 @@ var ts; * This is the minumum code needed to expose that functionality; the rest is in the host. */ /* @internal */ - function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache, packageJsonInfoCache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache); } @@ -40249,26 +41435,26 @@ var ts; // A module is uninstantiated if it contains only switch (node.kind) { // 1. interface declarations, type alias declarations - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return 0 /* NonInstantiated */; // 2. const enum declarations - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: if (ts.isEnumConst(node)) { return 2 /* ConstEnumOnly */; } break; // 3. non-exported import declarations - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: if (!(ts.hasSyntacticModifier(node, 1 /* Export */))) { return 0 /* NonInstantiated */; } break; // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: var exportDeclaration = node; - if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 268 /* NamedExports */) { + if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 269 /* NamedExports */) { var state = 0 /* NonInstantiated */; for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; @@ -40284,7 +41470,7 @@ var ts; } break; // 5. other uninstantiated module declarations. - case 257 /* ModuleBlock */: { + case 258 /* ModuleBlock */: { var state_1 = 0 /* NonInstantiated */; ts.forEachChild(node, function (n) { var childState = getModuleInstanceStateCached(n, visited); @@ -40306,7 +41492,7 @@ var ts; }); return state_1; } - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return getModuleInstanceState(node, visited); case 78 /* Identifier */: // Only jsdoc typedef definition can exist in jsdoc namespace, and it should @@ -40378,14 +41564,14 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { - ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); ts.performance.measure("Bind", "beforeBind", "afterBind"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -40424,6 +41610,7 @@ var ts; var classifiableNames; var unreachableFlow = { flags: 1 /* Unreachable */ }; var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; + var bindBinaryExpressionFlow = createBindBinaryExpressionFlow(); /** * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) @@ -40506,7 +41693,7 @@ var ts; // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { - if (node.kind === 266 /* ExportAssignment */) { + if (node.kind === 267 /* ExportAssignment */) { return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; } var name = ts.getNameOfDeclaration(node); @@ -40515,7 +41702,7 @@ var ts; var moduleName = ts.getTextOfIdentifierOrLiteral(name); return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); } - if (name.kind === 158 /* ComputedPropertyName */) { + if (name.kind === 159 /* ComputedPropertyName */) { var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteralLike(nameExpression)) { @@ -40524,11 +41711,9 @@ var ts; if (ts.isSignedNumericLiteral(nameExpression)) { return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text; } - ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); - return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - if (ts.isWellKnownSymbolSyntactically(name)) { - return ts.getPropertyNameForKnownSymbolName(ts.idText(name.name)); + else { + ts.Debug.fail("Only computed properties with literal names have declaration names"); + } } if (ts.isPrivateIdentifier(name)) { // containingClass exists because private names only allowed inside classes @@ -40543,36 +41728,36 @@ var ts; return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return "__constructor" /* Constructor */; - case 174 /* FunctionType */: - case 169 /* CallSignature */: - case 313 /* JSDocSignature */: + case 175 /* FunctionType */: + case 170 /* CallSignature */: + case 315 /* JSDocSignature */: return "__call" /* Call */; - case 175 /* ConstructorType */: - case 170 /* ConstructSignature */: + case 176 /* ConstructorType */: + case 171 /* ConstructSignature */: return "__new" /* New */; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: return "__index" /* Index */; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return "__export" /* ExportStar */; - case 297 /* SourceFile */: + case 298 /* SourceFile */: // json file should behave as // module.exports = ... return "export=" /* ExportEquals */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); - case 160 /* Parameter */: + case 161 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 308 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + ts.Debug.assert(node.parent.kind === 309 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -40672,7 +41857,7 @@ var ts; // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if (symbol.declarations && symbol.declarations.length && - (node.kind === 266 /* ExportAssignment */ && !node.isExportEquals)) { + (node.kind === 267 /* ExportAssignment */ && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName_1 = false; multipleDefaultExports_1 = true; @@ -40711,7 +41896,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = !!(ts.getCombinedModifierFlags(node) & 1 /* Export */) || jsdocTreatAsExported(node); if (symbolFlags & 2097152 /* Alias */) { - if (node.kind === 270 /* ExportSpecifier */ || (node.kind === 260 /* ImportEqualsDeclaration */ && hasExportModifier)) { + if (node.kind === 271 /* ExportSpecifier */ || (node.kind === 261 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -40800,7 +41985,7 @@ var ts; // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. if (containerFlags & 1 /* IsContainer */) { - if (node.kind !== 209 /* ArrowFunction */) { + if (node.kind !== 210 /* ArrowFunction */) { thisParentContainer = container; } container = blockScopeContainer = node; @@ -40833,7 +42018,7 @@ var ts; } // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property initialization checks. - currentReturnTarget = isIIFE || node.kind === 166 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */)) ? createBranchLabel() : undefined; + currentReturnTarget = isIIFE || node.kind === 167 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 252 /* FunctionDeclaration */ || node.kind === 209 /* FunctionExpression */)) ? createBranchLabel() : undefined; currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; @@ -40848,13 +42033,14 @@ var ts; node.flags |= 512 /* HasExplicitReturn */; node.endFlowNode = currentFlow; } - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { node.flags |= emitFlags; + node.endFlowNode = currentFlow; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 166 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */))) { + if (node.kind === 167 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 252 /* FunctionDeclaration */ || node.kind === 209 /* FunctionExpression */))) { node.returnFlowNode = currentFlow; } } @@ -40881,8 +42067,8 @@ var ts; blockScopeContainer = savedBlockScopeContainer; } function bindEachFunctionsFirst(nodes) { - bindEach(nodes, function (n) { return n.kind === 251 /* FunctionDeclaration */ ? bind(n) : undefined; }); - bindEach(nodes, function (n) { return n.kind !== 251 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind === 252 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 252 /* FunctionDeclaration */ ? bind(n) : undefined; }); } function bindEach(nodes, bindFunction) { if (bindFunction === void 0) { bindFunction = bind; } @@ -40905,59 +42091,59 @@ var ts; inAssignmentPattern = saveInAssignmentPattern; return; } - if (node.kind >= 232 /* FirstStatement */ && node.kind <= 248 /* LastStatement */ && !options.allowUnreachableCode) { + if (node.kind >= 233 /* FirstStatement */ && node.kind <= 249 /* LastStatement */ && !options.allowUnreachableCode) { node.flowNode = currentFlow; } switch (node.kind) { - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: bindWhileStatement(node); break; - case 235 /* DoStatement */: + case 236 /* DoStatement */: bindDoStatement(node); break; - case 237 /* ForStatement */: + case 238 /* ForStatement */: bindForStatement(node); break; - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: bindForInOrForOfStatement(node); break; - case 234 /* IfStatement */: + case 235 /* IfStatement */: bindIfStatement(node); break; - case 242 /* ReturnStatement */: - case 246 /* ThrowStatement */: + case 243 /* ReturnStatement */: + case 247 /* ThrowStatement */: bindReturnOrThrow(node); break; - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 247 /* TryStatement */: + case 248 /* TryStatement */: bindTryStatement(node); break; - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: bindSwitchStatement(node); break; - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: bindCaseBlock(node); break; - case 284 /* CaseClause */: + case 285 /* CaseClause */: bindCaseClause(node); break; - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: bindExpressionStatement(node); break; - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: bindLabeledStatement(node); break; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: bindPostfixUnaryExpressionFlow(node); break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.isDestructuringAssignment(node)) { // Carry over whether we are in an assignment pattern to // binary expressions that could actually be an initializer @@ -40967,47 +42153,47 @@ var ts; } bindBinaryExpressionFlow(node); break; - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: bindDeleteExpressionFlow(node); break; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: bindConditionalExpressionFlow(node); break; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: bindVariableDeclarationFlow(node); break; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: bindAccessExpressionFlow(node); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: bindCallExpressionFlow(node); break; - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: bindNonNullExpressionFlow(node); break; - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: bindJSDocTypeAlias(node); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime - case 297 /* SourceFile */: { + case 298 /* SourceFile */: { bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); break; } - case 230 /* Block */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 258 /* ModuleBlock */: bindEachFunctionsFirst(node.statements); break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: bindBindingElementFlow(node); break; - case 200 /* ObjectLiteralExpression */: - case 199 /* ArrayLiteralExpression */: - case 288 /* PropertyAssignment */: - case 220 /* SpreadElement */: + case 201 /* ObjectLiteralExpression */: + case 200 /* ArrayLiteralExpression */: + case 289 /* PropertyAssignment */: + case 221 /* SpreadElement */: // Carry over whether we are in an assignment pattern of Object and Array literals // as well as their children that are valid assignment targets. inAssignmentPattern = saveInAssignmentPattern; @@ -41024,29 +42210,29 @@ var ts; case 78 /* Identifier */: case 79 /* PrivateIdentifier */: case 107 /* ThisKeyword */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return containsNarrowableReference(expr); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return hasNarrowableArgument(expr); - case 207 /* ParenthesizedExpression */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: return isNarrowingExpression(expr.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return isNarrowingBinaryExpression(expr); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return isNarrowingExpression(expr.expression); } return false; } function isNarrowableReference(expr) { - return expr.kind === 78 /* Identifier */ || expr.kind === 79 /* PrivateIdentifier */ || expr.kind === 107 /* ThisKeyword */ || expr.kind === 105 /* SuperKeyword */ || - (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isBinaryExpression(expr) && expr.operatorToken.kind === 27 /* CommaToken */ && isNarrowableReference(expr.right) || - ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || - ts.isAssignmentExpression(expr) && isNarrowableReference(expr.left); + return ts.isDottedName(expr) + || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) + || ts.isBinaryExpression(expr) && expr.operatorToken.kind === 27 /* CommaToken */ && isNarrowableReference(expr.right) + || ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) + || ts.isAssignmentExpression(expr) && isNarrowableReference(expr.left); } function containsNarrowableReference(expr) { return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression); @@ -41060,7 +42246,7 @@ var ts; } } } - if (expr.expression.kind === 201 /* PropertyAccessExpression */ && + if (expr.expression.kind === 202 /* PropertyAccessExpression */ && containsNarrowableReference(expr.expression.expression)) { return true; } @@ -41096,9 +42282,9 @@ var ts; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isNarrowableOperand(expr.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (expr.operatorToken.kind) { case 62 /* EqualsToken */: return isNarrowableOperand(expr.left); @@ -41174,26 +42360,26 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 234 /* IfStatement */: - case 236 /* WhileStatement */: - case 235 /* DoStatement */: + case 235 /* IfStatement */: + case 237 /* WhileStatement */: + case 236 /* DoStatement */: return parent.expression === node; - case 237 /* ForStatement */: - case 217 /* ConditionalExpression */: + case 238 /* ForStatement */: + case 218 /* ConditionalExpression */: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 207 /* ParenthesizedExpression */) { + if (node.kind === 208 /* ParenthesizedExpression */) { node = node.expression; } - else if (node.kind === 214 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) { + else if (node.kind === 215 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) { node = node.operand; } else { - return node.kind === 216 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ || + return node.kind === 217 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */); } @@ -41240,7 +42426,7 @@ var ts; } function setContinueTarget(node, target) { var label = activeLabelList; - while (label && node.parent.kind === 245 /* LabeledStatement */) { + while (label && node.parent.kind === 246 /* LabeledStatement */) { label.continueTarget = target; label = label.next; node = node.parent; @@ -41291,12 +42477,12 @@ var ts; bind(node.expression); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 239 /* ForOfStatement */) { + if (node.kind === 240 /* ForOfStatement */) { bind(node.awaitModifier); } addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 250 /* VariableDeclarationList */) { + if (node.initializer.kind !== 251 /* VariableDeclarationList */) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -41318,7 +42504,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 242 /* ReturnStatement */) { + if (node.kind === 243 /* ReturnStatement */) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -41335,7 +42521,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 241 /* BreakStatement */ ? breakTarget : continueTarget; + var flowLabel = node.kind === 242 /* BreakStatement */ ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -41440,7 +42626,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 285 /* DefaultClause */; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 286 /* DefaultClause */; }); // We mark a switch statement as possibly exhaustive if it has no default clause and if all // case clauses have unreachable end points (e.g. they all return). Note, we no longer need // this property in control flow analysis, it's there only for backwards compatibility. @@ -41488,9 +42674,9 @@ var ts; function maybeBindExpressionFlowIfCall(node) { // A top level or LHS of comma expression call expression with a dotted function name and at least one argument // is potentially an assertion and is therefore included in the control flow. - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { var call = node; - if (ts.isDottedName(call.expression) && call.expression.kind !== 105 /* SuperKeyword */) { + if (call.expression.kind !== 105 /* SuperKeyword */ && ts.isDottedName(call.expression)) { currentFlow = createFlowCall(currentFlow, call); } } @@ -41514,7 +42700,7 @@ var ts; currentFlow = finishFlowLabel(postStatementLabel); } function bindDestructuringTargetFlow(node) { - if (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) { + if (node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) { bindAssignmentTargetFlow(node.left); } else { @@ -41525,10 +42711,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node); } - else if (node.kind === 199 /* ArrayLiteralExpression */) { + else if (node.kind === 200 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 220 /* SpreadElement */) { + if (e.kind === 221 /* SpreadElement */) { bindAssignmentTargetFlow(e.expression); } else { @@ -41536,16 +42722,16 @@ var ts; } } } - else if (node.kind === 200 /* ObjectLiteralExpression */) { + else if (node.kind === 201 /* ObjectLiteralExpression */) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 288 /* PropertyAssignment */) { + if (p.kind === 289 /* PropertyAssignment */) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 289 /* ShorthandPropertyAssignment */) { + else if (p.kind === 290 /* ShorthandPropertyAssignment */) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 290 /* SpreadAssignment */) { + else if (p.kind === 291 /* SpreadAssignment */) { bindAssignmentTargetFlow(p.expression); } } @@ -41610,128 +42796,102 @@ var ts; } bindAssignmentTargetFlow(node.left); } - var BindBinaryExpressionFlowState; - (function (BindBinaryExpressionFlowState) { - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindThenBindChildren"] = 0] = "BindThenBindChildren"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["MaybeBindLeft"] = 1] = "MaybeBindLeft"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindToken"] = 2] = "BindToken"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindRight"] = 3] = "BindRight"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["FinishBind"] = 4] = "FinishBind"; - })(BindBinaryExpressionFlowState || (BindBinaryExpressionFlowState = {})); - function bindBinaryExpressionFlow(node) { - var workStacks = { - expr: [node], - state: [1 /* MaybeBindLeft */], - inStrictMode: [undefined], - parent: [undefined], - }; - var stackIndex = 0; - while (stackIndex >= 0) { - node = workStacks.expr[stackIndex]; - switch (workStacks.state[stackIndex]) { - case 0 /* BindThenBindChildren */: { - // This state is used only when recuring, to emulate the work that `bind` does before - // reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work. - ts.setParent(node, parent); - var saveInStrictMode = inStrictMode; - bindWorker(node); - var saveParent = parent; - parent = node; - advanceState(1 /* MaybeBindLeft */, saveInStrictMode, saveParent); - break; - } - case 1 /* MaybeBindLeft */: { - var operator = node.operatorToken.kind; - // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions - // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too - // For now, though, since the common cases are chained `+`, leaving it recursive is fine - if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */ || - ts.isLogicalOrCoalescingAssignmentOperator(operator)) { - if (isTopLevelLogicalExpression(node)) { - var postExpressionLabel = createBranchLabel(); - bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel); - currentFlow = finishFlowLabel(postExpressionLabel); - } - else { - bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget); - } - completeNode(); - } - else { - advanceState(2 /* BindToken */); - maybeBind(node.left); - } - break; + function createBindBinaryExpressionFlow() { + return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined); + function onEnter(node, state) { + if (state) { + state.stackIndex++; + // Emulate the work that `bind` does before reaching `bindChildren`. A normal call to + // `bindBinaryExpressionFlow` will already have done this work. + ts.setParent(node, parent); + var saveInStrictMode = inStrictMode; + bindWorker(node); + var saveParent = parent; + parent = node; + state.skip = false; + state.inStrictModeStack[state.stackIndex] = saveInStrictMode; + state.parentStack[state.stackIndex] = saveParent; + } + else { + state = { + stackIndex: 0, + skip: false, + inStrictModeStack: [undefined], + parentStack: [undefined] + }; + } + // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions + // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too + // For now, though, since the common cases are chained `+`, leaving it recursive is fine + var operator = node.operatorToken.kind; + if (operator === 55 /* AmpersandAmpersandToken */ || + operator === 56 /* BarBarToken */ || + operator === 60 /* QuestionQuestionToken */ || + ts.isLogicalOrCoalescingAssignmentOperator(operator)) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); } - case 2 /* BindToken */: { - if (node.operatorToken.kind === 27 /* CommaToken */) { - maybeBindExpressionFlowIfCall(node.left); - } - advanceState(3 /* BindRight */); - maybeBind(node.operatorToken); - break; + else { + bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget); } - case 3 /* BindRight */: { - advanceState(4 /* FinishBind */); - maybeBind(node.right); - break; + state.skip = true; + } + return state; + } + function onLeft(left, state, _node) { + if (!state.skip) { + return maybeBind(left); + } + } + function onOperator(operatorToken, state, node) { + if (!state.skip) { + if (operatorToken.kind === 27 /* CommaToken */) { + maybeBindExpressionFlowIfCall(node.left); } - case 4 /* FinishBind */: { - var operator = node.operatorToken.kind; - if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { - bindAssignmentTargetFlow(node.left); - if (operator === 62 /* EqualsToken */ && node.left.kind === 202 /* ElementAccessExpression */) { - var elementAccess = node.left; - if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); - } + bind(operatorToken); + } + } + function onRight(right, state, _node) { + if (!state.skip) { + return maybeBind(right); + } + } + function onExit(node, state) { + if (!state.skip) { + var operator = node.operatorToken.kind; + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 62 /* EqualsToken */ && node.left.kind === 203 /* ElementAccessExpression */) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); } } - completeNode(); - break; } - default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for bindBinaryExpressionFlow"); } - } - /** - * Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new - * head state; so `advanceState` must be called before any `maybeBind` during a state's execution. - */ - function advanceState(state, isInStrictMode, parent) { - workStacks.state[stackIndex] = state; - if (isInStrictMode !== undefined) { - workStacks.inStrictMode[stackIndex] = isInStrictMode; + var savedInStrictMode = state.inStrictModeStack[state.stackIndex]; + var savedParent = state.parentStack[state.stackIndex]; + if (savedInStrictMode !== undefined) { + inStrictMode = savedInStrictMode; } - if (parent !== undefined) { - workStacks.parent[stackIndex] = parent; + if (savedParent !== undefined) { + parent = savedParent; } + state.skip = false; + state.stackIndex--; } - function completeNode() { - if (workStacks.inStrictMode[stackIndex] !== undefined) { - inStrictMode = workStacks.inStrictMode[stackIndex]; - parent = workStacks.parent[stackIndex]; - } - stackIndex--; - } - /** - * If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it - */ function maybeBind(node) { if (node && ts.isBinaryExpression(node) && !ts.isDestructuringAssignment(node)) { - stackIndex++; - workStacks.expr[stackIndex] = node; - workStacks.state[stackIndex] = 0 /* BindThenBindChildren */; - workStacks.inStrictMode[stackIndex] = undefined; - workStacks.parent[stackIndex] = undefined; - } - else { - bind(node); + return node; } + bind(node); } } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 201 /* PropertyAccessExpression */) { + if (node.expression.kind === 202 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -41788,7 +42948,7 @@ var ts; } function bindJSDocTypeAlias(node) { ts.setParent(node.tagName, node); - if (node.kind !== 325 /* JSDocEnumTag */ && node.fullName) { + if (node.kind !== 329 /* JSDocEnumTag */ && node.fullName) { ts.setParent(node.fullName, node); ts.setParentRecursive(node.fullName, /*incremental*/ false); } @@ -41796,7 +42956,7 @@ var ts; function bindJSDocClassTag(node) { bindEachChild(node); var host = ts.getHostSignatureFromJSDoc(node); - if (host && host.kind !== 165 /* MethodDeclaration */) { + if (host && host.kind !== 166 /* MethodDeclaration */) { addDeclarationToSymbol(host.symbol, host, 32 /* Class */); } } @@ -41809,15 +42969,15 @@ var ts; } function bindOptionalChainRest(node) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: bind(node.questionDotToken); bind(node.name); break; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: bind(node.questionDotToken); bind(node.argumentExpression); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: bind(node.questionDotToken); bindEach(node.typeArguments); bindEach(node.arguments); @@ -41882,7 +43042,7 @@ var ts; // an immediately invoked function expression (IIFE). Initialize the flowNode property to // the current control flow (which includes evaluation of the IIFE arguments). var expr = ts.skipParentheses(node.expression); - if (expr.kind === 208 /* FunctionExpression */ || expr.kind === 209 /* ArrowFunction */) { + if (expr.kind === 209 /* FunctionExpression */ || expr.kind === 210 /* ArrowFunction */) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -41894,7 +43054,7 @@ var ts; } } } - if (node.expression.kind === 201 /* PropertyAccessExpression */) { + if (node.expression.kind === 202 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); @@ -41903,54 +43063,54 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 200 /* ObjectLiteralExpression */: - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 281 /* JsxAttributes */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 201 /* ObjectLiteralExpression */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 282 /* JsxAttributes */: return 1 /* IsContainer */; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return 1 /* IsContainer */ | 64 /* IsInterface */; - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 190 /* MappedType */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 191 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 297 /* SourceFile */: + case 298 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; } // falls through - case 166 /* Constructor */: - case 251 /* FunctionDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 169 /* CallSignature */: - case 313 /* JSDocSignature */: - case 308 /* JSDocFunctionType */: - case 174 /* FunctionType */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 175 /* ConstructorType */: + case 167 /* Constructor */: + case 252 /* FunctionDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 170 /* CallSignature */: + case 315 /* JSDocSignature */: + case 309 /* JSDocFunctionType */: + case 175 /* FunctionType */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 176 /* ConstructorType */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return 4 /* IsControlFlowContainer */; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 287 /* CatchClause */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 258 /* CaseBlock */: + case 288 /* CatchClause */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 259 /* CaseBlock */: return 2 /* IsBlockScopedContainer */; - case 230 /* Block */: + case 231 /* Block */: // do not treat blocks directly inside a function as a block-scoped-container. // Locals that reside in this block should go to the function locals. Otherwise 'x' // would not appear to be a redeclaration of a block scoped local in the following @@ -41983,45 +43143,45 @@ var ts; // members are declared (for example, a member of a class will go into a specific // symbol table depending on if it is static or not). We defer to specialized // handlers to take care of declaring these child members. - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 297 /* SourceFile */: + case 298 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 200 /* ObjectLiteralExpression */: - case 253 /* InterfaceDeclaration */: - case 281 /* JsxAttributes */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 201 /* ObjectLiteralExpression */: + case 254 /* InterfaceDeclaration */: + case 282 /* JsxAttributes */: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the // object / type / interface declaring them). An exception is type parameters, // which are in scope without qualification (similar to 'locals'). return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 313 /* JSDocSignature */: - case 171 /* IndexSignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 308 /* JSDocFunctionType */: - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 254 /* TypeAliasDeclaration */: - case 190 /* MappedType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 315 /* JSDocSignature */: + case 172 /* IndexSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 309 /* JSDocFunctionType */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 255 /* TypeAliasDeclaration */: + case 191 /* MappedType */: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -42122,7 +43282,7 @@ var ts; var seen = new ts.Map(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 290 /* SpreadAssignment */ || prop.name.kind !== 78 /* Identifier */) { + if (prop.kind === 291 /* SpreadAssignment */ || prop.name.kind !== 78 /* Identifier */) { continue; } var identifier = prop.name; @@ -42134,7 +43294,7 @@ var ts; // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 288 /* PropertyAssignment */ || prop.kind === 289 /* ShorthandPropertyAssignment */ || prop.kind === 165 /* MethodDeclaration */ + var currentKind = prop.kind === 289 /* PropertyAssignment */ || prop.kind === 290 /* ShorthandPropertyAssignment */ || prop.kind === 166 /* MethodDeclaration */ ? 1 /* Property */ : 2 /* Accessor */; var existingKind = seen.get(identifier.escapedText); @@ -42166,10 +43326,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (ts.isExternalOrCommonJsModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -42194,9 +43354,9 @@ var ts; var saveCurrentFlow = currentFlow; for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { var typeAlias = delayedTypeAliases_1[_i]; - var host = ts.getJSDocHost(typeAlias); - container = (host && ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); })) || file; - blockScopeContainer = (host && ts.getEnclosingBlockScopeContainer(host)) || file; + var host = typeAlias.parent.parent; + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); @@ -42368,8 +43528,8 @@ var ts; function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2 /* ES2015 */) { // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 297 /* SourceFile */ && - blockScopeContainer.kind !== 256 /* ModuleDeclaration */ && + if (blockScopeContainer.kind !== 298 /* SourceFile */ && + blockScopeContainer.kind !== 257 /* ModuleDeclaration */ && !ts.isFunctionLike(blockScopeContainer)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. @@ -42464,7 +43624,7 @@ var ts; // the current 'container' node when it changes. This helps us know which symbol table // a local should go into for example. Since terminal nodes are known not to have // children, as an optimization we don't process those. - if (node.kind > 156 /* LastToken */) { + if (node.kind > 157 /* LastToken */) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -42540,17 +43700,23 @@ var ts; } // falls through case 107 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 289 /* ShorthandPropertyAssignment */)) { + if (currentFlow && (ts.isExpression(node) || parent.kind === 290 /* ShorthandPropertyAssignment */)) { node.flowNode = currentFlow; } return checkContextualIdentifier(node); + case 158 /* QualifiedName */: + if (currentFlow && parent.kind === 177 /* TypeQuery */) { + node.flowNode = currentFlow; + } + break; + case 227 /* MetaProperty */: case 105 /* SuperKeyword */: node.flowNode = currentFlow; break; case 79 /* PrivateIdentifier */: return checkPrivateIdentifier(node); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: var expr = node; if (currentFlow && isNarrowableReference(expr)) { expr.flowNode = currentFlow; @@ -42565,7 +43731,7 @@ var ts; declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */); } break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: @@ -42601,78 +43767,78 @@ var ts; ts.Debug.fail("Unknown binary expression special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return checkStrictModeCatchClause(node); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return checkStrictModeDeleteExpression(node); case 8 /* NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return checkStrictModeWithStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return checkStrictModeLabeledStatement(node); - case 187 /* ThisType */: + case 188 /* ThisType */: seenThisKeyword = true; return; - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: break; // Binding the children will handle everything - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return bindTypeParameter(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return bindParameter(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return bindVariableDeclarationOrBindingElement(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return bindPropertyWorker(node); - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 291 /* EnumMember */: + case 292 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: // If this is an ObjectLiteralExpression method, then it sits in the same space // 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 */ : 103359 /* MethodExcludes */); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return bindFunctionDeclaration(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */); - case 174 /* FunctionType */: - case 308 /* JSDocFunctionType */: - case 313 /* JSDocSignature */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 309 /* JSDocFunctionType */: + case 315 /* JSDocSignature */: + case 176 /* ConstructorType */: return bindFunctionOrConstructorType(node); - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 190 /* MappedType */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 191 /* MappedType */: return bindAnonymousTypeWorker(node); - case 319 /* JSDocClassTag */: + case 322 /* JSDocClassTag */: return bindJSDocClassTag(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return bindFunctionExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: var assignmentKind = ts.getAssignmentDeclarationKind(node); switch (assignmentKind) { case 7 /* ObjectDefinePropertyValue */: @@ -42691,65 +43857,65 @@ var ts; } break; // Members of classes, interfaces, and modules - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: // All classes are automatically in strict mode in ES6. inStrictMode = true; return bindClassLikeDeclaration(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return bindEnumDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return bindModuleDeclaration(node); // Jsx-attributes - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return bindJsxAttributes(node); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); // Imports and exports - case 260 /* ImportEqualsDeclaration */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 261 /* ImportEqualsDeclaration */: + case 264 /* NamespaceImport */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return bindNamespaceExportDeclaration(node); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return bindImportClause(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return bindExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return bindExportAssignment(node); - case 297 /* SourceFile */: + case 298 /* SourceFile */: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 230 /* Block */: + case 231 /* Block */: if (!ts.isFunctionLike(node.parent)) { return; } // falls through - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 326 /* JSDocParameterTag */: - if (node.parent.kind === 313 /* JSDocSignature */) { + case 330 /* JSDocParameterTag */: + if (node.parent.kind === 315 /* JSDocSignature */) { return bindParameter(node); } - if (node.parent.kind !== 312 /* JSDocTypeLiteral */) { + if (node.parent.kind !== 314 /* JSDocTypeLiteral */) { break; } // falls through - case 333 /* JSDocPropertyTag */: + case 337 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 307 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 308 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } @@ -42777,8 +43943,8 @@ var ts; } function bindExportAssignment(node) { if (!container.symbol || !container.symbol.exports) { - // Export assignment in some sort of block construct - bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + // Incorrect export assignment in some sort of block construct + bindAnonymousDeclaration(node, 111551 /* Value */, getDeclarationName(node)); } else { var flags = ts.exportAssignmentIsAlias(node) @@ -42912,8 +44078,8 @@ var ts; } var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: var constructorSymbol = thisContainer.symbol; // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 62 /* EqualsToken */) { @@ -42935,11 +44101,11 @@ var ts; addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */); } break; - case 166 /* Constructor */: - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 167 /* Constructor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // this.foo assignment in a JavaScript class // Bind this property to the containing class var containingClass = thisContainer.parent; @@ -42951,7 +44117,7 @@ var ts; declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true); } break; - case 297 /* SourceFile */: + case 298 /* SourceFile */: // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script if (ts.hasDynamicName(node)) { break; @@ -42980,7 +44146,7 @@ var ts; if (node.expression.kind === 107 /* ThisKeyword */) { bindThisPropertyAssignment(node); } - else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 297 /* SourceFile */) { + else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 298 /* SourceFile */) { if (ts.isPrototypeAccess(node.expression)) { bindPrototypePropertyAssignment(node, node.parent); } @@ -43020,7 +44186,7 @@ var ts; } function bindObjectDefinePropertyAssignment(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); - var isToplevel = node.parent.parent.kind === 297 /* SourceFile */; + var isToplevel = node.parent.parent.kind === 298 /* SourceFile */; namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false); bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); } @@ -43129,8 +44295,8 @@ var ts; } function isTopLevelNamespaceAssignment(propertyAccess) { return ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 297 /* SourceFile */ - : propertyAccess.parent.parent.kind === 297 /* SourceFile */; + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 298 /* SourceFile */ + : propertyAccess.parent.parent.kind === 298 /* SourceFile */; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) { var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer); @@ -43209,7 +44375,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 252 /* ClassDeclaration */) { + if (node.kind === 253 /* ClassDeclaration */) { bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */); } else { @@ -43251,7 +44417,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { - if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true) && !ts.getJSDocTypeTag(node)) { + if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node) && !ts.getJSDocTypeTag(node)) { declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } else if (ts.isBlockOrCatchScoped(node)) { @@ -43275,7 +44441,7 @@ var ts; } } function bindParameter(node) { - if (node.kind === 326 /* JSDocParameterTag */ && container.kind !== 313 /* JSDocSignature */) { + if (node.kind === 330 /* JSDocParameterTag */ && container.kind !== 315 /* JSDocSignature */) { return; } if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) { @@ -43352,7 +44518,7 @@ var ts; declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */); } } - else if (node.parent.kind === 185 /* InferType */) { + else if (node.parent.kind === 186 /* InferType */) { var container_2 = getInferTypeContainer(node.parent); if (container_2) { if (!container_2.locals) { @@ -43371,7 +44537,7 @@ var ts; // reachability checks function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && ts.shouldPreserveConstEnums(options)); } function checkUnreachable(node) { if (!(currentFlow.flags & 1 /* Unreachable */)) { @@ -43380,11 +44546,11 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 231 /* EmptyStatement */) || + (ts.isStatementButNotDeclaration(node) && node.kind !== 232 /* EmptyStatement */) || // report error on class declarations - node.kind === 252 /* ClassDeclaration */ || + node.kind === 253 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 256 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); + (node.kind === 257 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -43428,12 +44594,12 @@ var ts; } function isPurelyTypeDeclaration(s) { switch (s.kind) { - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return true; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return getModuleInstanceState(s) !== 1 /* Instantiated */; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return ts.hasSyntacticModifier(s, 2048 /* Const */); default: return false; @@ -43633,7 +44799,7 @@ var ts; // (their type resolved directly to the member deeply referenced) // So to get the intervening symbols, we need to check if there's a type // query node on any of the symbol's declarations and get symbols there - if (d.type && d.type.kind === 176 /* TypeQuery */) { + if (d.type && d.type.kind === 177 /* TypeQuery */) { var query = d.type; var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); visitSymbol(entity); @@ -43860,6 +45026,7 @@ var ts; DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor"; DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment"; DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method"; + DeclarationMeaning[DeclarationMeaning["PrivateStatic"] = 16] = "PrivateStatic"; DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor"; DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod"; })(DeclarationMeaning || (DeclarationMeaning = {})); @@ -43951,12 +45118,12 @@ var ts; var instantiationCount = 0; var instantiationDepth = 0; var currentNode; - var typeCatalog = []; // NB: id is index + 1 var emptySymbols = ts.createSymbolTable(); var arrayVariances = [1 /* Covariant */]; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); @@ -43965,7 +45132,8 @@ var ts; var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16384 /* FreshLiteral */; + var checkBinaryExpression = createCheckBinaryExpression(); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); var globals = ts.createSymbolTable(); @@ -43988,7 +45156,6 @@ var ts; getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, - getTypeCatalog: function () { return typeCatalog; }, getTypeCount: function () { return typeCount; }, getInstantiationCount: function () { return totalInstantiationCount; }, getRelationCacheSizes: function () { return ({ @@ -44152,6 +45319,7 @@ var ts; return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, + getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: function (node, candidatesOutArray, argumentCount) { return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */); @@ -44195,6 +45363,7 @@ var ts; }, tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); }, + tryFindAmbientModule: function (moduleName) { return tryFindAmbientModule(moduleName, /*withAugmentations*/ true); }, tryFindAmbientModuleWithoutAugmentations: function (moduleName) { // we deliberately exclude augmentations // since we are only interested in declarations of the module itself @@ -44313,6 +45482,7 @@ var ts; var templateLiteralTypes = new ts.Map(); var stringMappingTypes = new ts.Map(); var substitutionTypes = new ts.Map(); + var subtypeReductionCache = new ts.Map(); var evolvingArrayTypes = []; var undefinedProperties = new ts.Map(); var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -44321,14 +45491,14 @@ var ts; var autoType = createIntrinsicType(1 /* Any */, "any"); var wildcardType = createIntrinsicType(1 /* Any */, "any"); var errorType = createIntrinsicType(1 /* Any */, "error"); - var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */); + var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 131072 /* ContainsWideningType */); var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */); var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined"); var nullType = createIntrinsicType(65536 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 131072 /* ContainsWideningType */); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); @@ -44354,7 +45524,7 @@ var ts; var voidType = createIntrinsicType(16384 /* Void */, "void"); var neverType = createIntrinsicType(131072 /* Never */, "never"); var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); - var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */); + var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 524288 /* NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); @@ -44366,7 +45536,7 @@ var ts; var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; + emptyJsxObjectType.objectFlags |= 2048 /* JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -44375,7 +45545,7 @@ var ts; var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */; + anyFunctionType.objectFlags |= 524288 /* NonInferrableType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -44455,6 +45625,7 @@ var ts; // This allows users to just specify library files they want to used through --lib // and they will not get an error from not having unrelated library files var deferredGlobalESSymbolConstructorSymbol; + var deferredGlobalESSymbolConstructorTypeSymbol; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; @@ -44506,7 +45677,7 @@ var ts; var flowNodePostSuper = []; var potentialThisCollisions = []; var potentialNewTargetCollisions = []; - var potentialWeakMapCollisions = []; + var potentialWeakMapSetCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); var suggestionDiagnostics = ts.createDiagnosticCollection(); @@ -44653,6 +45824,25 @@ var ts; } return diagnostic; } + function addDeprecatedSuggestionWorker(declarations, diagnostic) { + var deprecatedTag = Array.isArray(declarations) ? ts.forEach(declarations, ts.getJSDocDeprecatedTag) : ts.getJSDocDeprecatedTag(declarations); + if (deprecatedTag) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(deprecatedTag, ts.Diagnostics.The_declaration_was_marked_as_deprecated_here)); + } + // We call `addRelatedInfo()` before adding the diagnostic to prevent duplicates. + suggestionDiagnostics.add(diagnostic); + return diagnostic; + } + function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { + var diagnostic = ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, deprecatedEntity); + return addDeprecatedSuggestionWorker(declarations, diagnostic); + } + function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) { + var diagnostic = deprecatedEntity + ? ts.createDiagnosticForNode(location, ts.Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity) + : ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, signatureString); + return addDeprecatedSuggestionWorker(declaration, diagnostic); + } function createSymbol(flags, name, checkFlags) { symbolCount++; var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); @@ -44766,7 +45956,7 @@ var ts; // as we will already report a "Declaration name conflicts..." error, and this error // won't make much sense. if (target !== globalThisSymbol) { - error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(source.declarations && ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } } else { // error @@ -44800,9 +45990,11 @@ var ts; } return target; function addDuplicateLocations(locs, symbol) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - ts.pushIfUnique(locs, decl); + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, decl); + } } } } @@ -44848,9 +46040,9 @@ var ts; }); } function mergeModuleAugmentation(moduleName) { - var _a, _b; + var _a, _b, _c; var moduleAugmentation = moduleName.parent; - if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + if (((_a = moduleAugmentation.symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]) !== moduleAugmentation) { // this is a combined symbol for multiple augmentations within the same file. // its symbol already has accumulated information for all declarations // so we need to add it just once - do the work only for first declaration @@ -44887,11 +46079,11 @@ var ts; patternAmbientModuleAugmentations.set(moduleName.text, merged); } else { - if (((_a = mainModule_1.exports) === null || _a === void 0 ? void 0 : _a.get("__export" /* ExportStar */)) && ((_b = moduleAugmentation.symbol.exports) === null || _b === void 0 ? void 0 : _b.size)) { + if (((_b = mainModule_1.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */)) && ((_c = moduleAugmentation.symbol.exports) === null || _c === void 0 ? void 0 : _c.size)) { // We may need to merge the module augmentation's exports into the target symbols of the resolved exports var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */); - for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) { - var _d = _c[_i], key = _d[0], value = _d[1]; + for (var _i = 0, _d = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _d.length; _i++) { + var _e = _d[_i], key = _e[0], value = _e[1]; if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) { mergeSymbol(resolvedExports.get(key), value); } @@ -44932,7 +46124,7 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks()); } function isGlobalSourceFile(node) { - return node.kind === 297 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 298 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -44991,17 +46183,17 @@ var ts; } if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) { // declaration is before usage - if (declaration.kind === 198 /* BindingElement */) { + if (declaration.kind === 199 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) - var errorBindingElement = ts.getAncestor(usage, 198 /* BindingElement */); + var errorBindingElement = ts.getAncestor(usage, 199 /* BindingElement */); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 249 /* VariableDeclaration */), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 250 /* VariableDeclaration */), usage); } - else if (declaration.kind === 249 /* VariableDeclaration */) { + else if (declaration.kind === 250 /* VariableDeclaration */) { // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } @@ -45015,7 +46207,7 @@ var ts; } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property - return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + return !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); } @@ -45031,19 +46223,19 @@ var ts; // or if usage is in a type context: // 1. inside a type query (typeof in type position) // 2. inside a jsdoc comment - if (usage.parent.kind === 270 /* ExportSpecifier */ || (usage.parent.kind === 266 /* ExportAssignment */ && usage.parent.isExportEquals)) { + if (usage.parent.kind === 271 /* ExportSpecifier */ || (usage.parent.kind === 267 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; } // When resolving symbols for exports, the `usage` location passed in can be the export site directly - if (usage.kind === 266 /* ExportAssignment */ && usage.isExportEquals) { + if (usage.kind === 267 /* ExportAssignment */ && usage.isExportEquals) { return true; } if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + if (compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); @@ -45058,9 +46250,9 @@ var ts; } function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { switch (declaration.parent.parent.kind) { - case 232 /* VariableStatement */: - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: + case 233 /* VariableStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, declContainer)) { @@ -45081,16 +46273,16 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 163 /* PropertyDeclaration */ && + current.parent.kind === 164 /* PropertyDeclaration */ && current.parent.initializer === current; if (initializerOfProperty) { if (ts.hasSyntacticModifier(current.parent, 32 /* Static */)) { - if (declaration.kind === 165 /* MethodDeclaration */) { + if (declaration.kind === 166 /* MethodDeclaration */) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 163 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(declaration, 32 /* Static */); + var isDeclarationInstanceProperty = declaration.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(declaration, 32 /* Static */); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -45112,19 +46304,19 @@ var ts; return "quit"; } switch (node.kind) { - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return true; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // even when stopping at any property declaration, they need to come from the same class return stopAtAnyPropertyDeclaration && (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent) ? "quit" : true; - case 230 /* Block */: + case 231 /* Block */: switch (node.parent.kind) { - case 167 /* GetAccessor */: - case 165 /* MethodDeclaration */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 166 /* MethodDeclaration */: + case 169 /* SetAccessor */: return true; default: return false; @@ -45139,7 +46331,11 @@ var ts; function useOuterVariableScopeInParameter(result, location, lastLocation) { var target = ts.getEmitScriptTarget(compilerOptions); var functionLocation = location; - if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + if (ts.isParameter(lastLocation) + && functionLocation.body + && result.valueDeclaration + && result.valueDeclaration.pos >= functionLocation.body.pos + && result.valueDeclaration.end <= functionLocation.body.end) { // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body // - static field in a class expression // - optional chaining pre-es2020 @@ -45160,21 +46356,21 @@ var ts; } function requiresScopeChangeWorker(node) { switch (node.kind) { - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 166 /* Constructor */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 167 /* Constructor */: // do not descend into these return false; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 288 /* PropertyAssignment */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 289 /* PropertyAssignment */: return requiresScopeChangeWorker(node.name); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // static properties in classes introduce temporary variables if (ts.hasStaticModifier(node)) { - return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields; + return target < 99 /* ESNext */ || !useDefineForClassFields; } return requiresScopeChangeWorker(node.name); default: @@ -45203,6 +46399,7 @@ var ts; return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); } function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { + var _a; var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; @@ -45225,12 +46422,12 @@ 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 & 788968 /* Type */ && lastLocation.kind !== 311 /* JSDocComment */) { + if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 312 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || - lastLocation.kind === 160 /* Parameter */ || - lastLocation.kind === 159 /* TypeParameter */ + lastLocation.kind === 161 /* Parameter */ || + lastLocation.kind === 160 /* TypeParameter */ // local types not visible outside the function body : false; } @@ -45245,13 +46442,13 @@ var ts; // however it is detected separately when checking initializers of parameters // to make sure that they reference no variables declared after them. useResult = - lastLocation.kind === 160 /* Parameter */ || + lastLocation.kind === 161 /* Parameter */ || (lastLocation === location.type && !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); } } } - else if (location.kind === 184 /* ConditionalType */) { + else if (location.kind === 185 /* ConditionalType */) { // A type parameter declared using 'infer T' in a conditional type is visible only in // the true branch of the conditional type. useResult = lastLocation === location.trueType; @@ -45266,14 +46463,14 @@ var ts; } withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation); switch (location.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; // falls through - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports || emptySymbols; - if (location.kind === 297 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) { + if (location.kind === 298 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports.get("default" /* Default */)) { @@ -45297,13 +46494,13 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && - (ts.getDeclarationOfKind(moduleExport, 270 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 269 /* NamespaceExport */))) { + (ts.getDeclarationOfKind(moduleExport, 271 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 270 /* NamespaceExport */))) { break; } } // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs) if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) { - if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !((_a = result.declarations) === null || _a === void 0 ? void 0 : _a.some(ts.isJSDocTypeAlias))) { result = undefined; } else { @@ -45311,12 +46508,12 @@ var ts; } } break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // TypeScript 1.0 spec (April 2014): 8.4.1 // Initializer expressions for instance member variables are evaluated in the scope // of the class constructor body but are not permitted to reference parameters or @@ -45333,9 +46530,9 @@ var ts; } } break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: // 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! @@ -45354,7 +46551,7 @@ var ts; } break loop; } - if (location.kind === 221 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 222 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -45362,7 +46559,7 @@ var ts; } } break; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 93 /* ExtendsKeyword */) { var container = location.parent.parent; @@ -45382,9 +46579,9 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 253 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 254 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -45392,24 +46589,24 @@ var ts; } } break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: // when targeting ES6 or higher there is no 'arguments' in an arrow function // for lower compile targets the resolved symbol is used to emit an error if (compilerOptions.target >= 2 /* ES2015 */) { break; } // falls through - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -45422,7 +46619,7 @@ var ts; } } break; - case 161 /* Decorator */: + case 162 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -45431,7 +46628,7 @@ var ts; // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. // } // - if (location.parent && location.parent.kind === 160 /* Parameter */) { + if (location.parent && location.parent.kind === 161 /* Parameter */) { location = location.parent; } // @@ -45446,20 +46643,20 @@ var ts; // declare function y(x: T): any; // @param(1 as T) // <-- T should resolve to the type alias outside of class C // class C {} - if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 252 /* ClassDeclaration */)) { + if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 253 /* ClassDeclaration */)) { location = location.parent; } break; - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: // js type aliases do not resolve names from their host, so skip past it var root = ts.getJSDocRoot(location); if (root) { location = root.parent; } break; - case 160 /* Parameter */: + case 161 /* Parameter */: if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && ts.isBindingPattern(lastLocation))) { if (!associatedDeclarationForContainingInitializerOrBindingName) { @@ -45467,7 +46664,7 @@ var ts; } } break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && ts.isBindingPattern(lastLocation))) { if (ts.isParameterDeclaration(location) && !associatedDeclarationForContainingInitializerOrBindingName) { @@ -45475,7 +46672,7 @@ var ts; } } break; - case 185 /* InferType */: + case 186 /* InferType */: if (meaning & 262144 /* TypeParameter */) { var parameterName = location.typeParameter.name; if (parameterName && name === parameterName.escapedText) { @@ -45499,7 +46696,7 @@ var ts; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 297 /* SourceFile */); + ts.Debug.assert(lastLocation.kind === 298 /* SourceFile */); if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } @@ -45528,6 +46725,10 @@ var ts; var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + var isGlobalScopeAugmentationDeclaration = suggestion && suggestion.valueDeclaration && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); + if (isGlobalScopeAugmentationDeclaration) { + suggestion = undefined; + } if (suggestion) { var suggestionName = symbolToString(suggestion); var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); @@ -45554,7 +46755,7 @@ var ts; } // Perform extra checks only if error reporting was requested if (nameNotFoundMessage) { - if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields)) { // We have a match, but the reference occurred within a property initializer and the identifier also binds // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed // with ESNext+useDefineForClassFields because the scope semantics are different. @@ -45624,10 +46825,10 @@ var ts; } } function getIsDeferredContext(location, lastLocation) { - if (location.kind !== 209 /* ArrowFunction */ && location.kind !== 208 /* FunctionExpression */) { + if (location.kind !== 210 /* ArrowFunction */ && location.kind !== 209 /* FunctionExpression */) { // initializers in instance property declaration of class like entities are executed in constructor and thus deferred return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) || - (location.kind === 163 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(location, 32 /* Static */))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred + (location.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(location, 32 /* Static */))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred } if (lastLocation && lastLocation === location.name) { return false; @@ -45640,12 +46841,12 @@ var ts; } function isSelfReferenceLocation(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 256 /* ModuleDeclaration */: // For `namespace N { N; }` + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 257 /* ModuleDeclaration */: // For `namespace N { N; }` return true; default: return false; @@ -45655,12 +46856,14 @@ var ts; return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } function isTypeParameterSymbolDeclaredInContainer(symbol, container) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (decl.kind === 159 /* TypeParameter */) { - var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; - if (parent === container) { - return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.kind === 160 /* TypeParameter */) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + } } } } @@ -45713,9 +46916,9 @@ var ts; function getEntityNameForExtendingInterface(node) { switch (node.kind) { case 78 /* Identifier */: - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: if (ts.isEntityNameExpression(node.expression)) { return node.expression; } @@ -45759,7 +46962,7 @@ var ts; return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown"; } function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) { - if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 270 /* ExportSpecifier */) { + if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 271 /* ExportSpecifier */) { error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name); return true; } @@ -45828,13 +47031,14 @@ var ts; return false; } function checkResolvedBlockScopedVariable(result, errorLocation) { + var _a; ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) { // constructor functions aren't block scoped return; } // Block-scoped variables cannot be used before their definition - var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 255 /* EnumDeclaration */); }); + var declaration = (_a = result.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 256 /* EnumDeclaration */); }); if (declaration === undefined) return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration"); if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -45851,7 +47055,7 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); - if (compilerOptions.preserveConstEnums) { + if (ts.shouldPreserveConstEnums(compilerOptions)) { diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); } } @@ -45869,20 +47073,20 @@ var ts; } function getAnyImportSyntax(node) { switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return node; - case 262 /* ImportClause */: + case 263 /* ImportClause */: return node.parent; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return node.parent.parent; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: return node.parent.parent.parent; default: return undefined; } } function getDeclarationOfAliasSymbol(symbol) { - return ts.find(symbol.declarations, isAliasSymbolDeclaration); + return symbol.declarations && ts.findLast(symbol.declarations, isAliasSymbolDeclaration); } /** * An alias symbol is created by one of the following declarations: @@ -45897,25 +47101,26 @@ var ts; * module.exports = * {} * {name: } + * const { x } = require ... */ function isAliasSymbolDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ - || node.kind === 259 /* NamespaceExportDeclaration */ - || node.kind === 262 /* ImportClause */ && !!node.name - || node.kind === 263 /* NamespaceImport */ - || node.kind === 269 /* NamespaceExport */ - || node.kind === 265 /* ImportSpecifier */ - || node.kind === 270 /* ExportSpecifier */ - || node.kind === 266 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + return node.kind === 261 /* ImportEqualsDeclaration */ + || node.kind === 260 /* NamespaceExportDeclaration */ + || node.kind === 263 /* ImportClause */ && !!node.name + || node.kind === 264 /* NamespaceImport */ + || node.kind === 270 /* NamespaceExport */ + || node.kind === 266 /* ImportSpecifier */ + || node.kind === 271 /* ExportSpecifier */ + || node.kind === 267 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) || ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && ts.exportAssignmentIsAlias(node) || ts.isAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableOrJsExpression(node.parent.right) - || node.kind === 289 /* ShorthandPropertyAssignment */ - || node.kind === 288 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) - || ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true); + || node.kind === 290 /* ShorthandPropertyAssignment */ + || node.kind === 289 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) + || ts.isRequireVariableDeclaration(node); } function isAliasableOrJsExpression(e) { return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e); @@ -45928,7 +47133,7 @@ var ts; ? resolveSymbol(getPropertyOfType(resolveExternalModuleTypeByLiteral(name), commonJSPropertyAccess.name.escapedText)) : undefined; } - if (ts.isVariableDeclaration(node) || node.moduleReference.kind === 272 /* ExternalModuleReference */) { + if (ts.isVariableDeclaration(node) || node.moduleReference.kind === 273 /* ExternalModuleReference */) { var immediate = resolveExternalModuleName(node, ts.getExternalModuleRequireArgument(node) || ts.getExternalModuleImportEqualsDeclarationExpression(node)); var resolved_4 = resolveExternalModuleSymbol(immediate); markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false); @@ -45995,6 +47200,7 @@ var ts; return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias); } function getTargetOfImportClause(node, dontResolveAlias) { + var _a; var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { var exportDefaultSymbol = void 0; @@ -46004,7 +47210,7 @@ var ts; else { exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias); } - var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); if (!exportDefaultSymbol && !hasSyntheticDefault) { if (hasExportAssignmentSymbol(moduleSymbol)) { @@ -46012,7 +47218,9 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */); var exportAssignment = exportEqualsSymbol.valueDeclaration; var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName); - ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); + if (exportAssignment) { + ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); + } } else { reportNonDefaultExport(moduleSymbol, node); @@ -46029,7 +47237,7 @@ var ts; } } function reportNonDefaultExport(moduleSymbol, node) { - var _a, _b; + var _a, _b, _c; if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); } @@ -46037,7 +47245,7 @@ var ts; var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */); if (exportStar) { - var defaultExport = ts.find(exportStar.declarations, function (decl) { + var defaultExport = (_c = exportStar.declarations) === null || _c === void 0 ? void 0 : _c.find(function (decl) { var _a, _b; return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier && ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */))); @@ -46115,7 +47323,7 @@ var ts; } } function getExternalModuleMember(node, specifier, dontResolveAlias) { - var _a; + var _a, _b; if (dontResolveAlias === void 0) { dontResolveAlias = false; } var moduleSpecifier = ts.getExternalModuleRequireArgument(node) || node.moduleSpecifier; var moduleSymbol = resolveExternalModuleName(node, moduleSpecifier); // TODO: GH#18217 @@ -46124,7 +47332,7 @@ var ts; return undefined; } var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop); - var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, dontResolveAlias, suppressInteropError); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, /*dontResolveAlias*/ false, suppressInteropError); if (targetSymbol) { if (name.escapedText) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { @@ -46142,7 +47350,7 @@ var ts; symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); var symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias); if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) { - var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } @@ -46162,7 +47370,7 @@ var ts; } } else { - if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default" /* Default */)) { + if ((_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */)) { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); } else { @@ -46175,8 +47383,8 @@ var ts; } } function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) { - var _a; - var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText); + var _a, _b; + var localSymbol = (_b = (_a = moduleSymbol.valueDeclaration) === null || _a === void 0 ? void 0 : _a.locals) === null || _b === void 0 ? void 0 : _b.get(name.escapedText); var exports = moduleSymbol.exports; if (localSymbol) { var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */); @@ -46188,9 +47396,11 @@ var ts; var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined; var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); - ts.addRelatedInfo.apply(void 0, __spreadArray([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { - return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); - }))); + if (localSymbol.declarations) { + ts.addRelatedInfo.apply(void 0, __spreadArray([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { + return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); + }))); + } } } else { @@ -46277,31 +47487,31 @@ var ts; function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: - case 249 /* VariableDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 250 /* VariableDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return getTargetOfImportClause(node, dontRecursivelyResolve); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: return getTargetOfNamespaceExport(node, dontRecursivelyResolve); - case 265 /* ImportSpecifier */: - case 198 /* BindingElement */: + case 266 /* ImportSpecifier */: + case 199 /* BindingElement */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); - case 266 /* ExportAssignment */: - case 216 /* BinaryExpression */: + case 267 /* ExportAssignment */: + case 217 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return getTargetOfPropertyAssignment(node, dontRecursivelyResolve); - case 202 /* ElementAccessExpression */: - case 201 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: return getTargetOfAccessExpression(node, dontRecursivelyResolve); default: return ts.Debug.fail(); @@ -46453,13 +47663,13 @@ var ts; entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 78 /* Identifier */ || entityName.parent.kind === 157 /* QualifiedName */) { + if (entityName.kind === 78 /* Identifier */ || entityName.parent.kind === 158 /* QualifiedName */) { return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 260 /* ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 261 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } @@ -46483,9 +47693,9 @@ var ts; return getMergedSymbol(symbolFromJSPrototype); } } - else if (name.kind === 157 /* QualifiedName */ || name.kind === 201 /* PropertyAccessExpression */) { - var left = name.kind === 157 /* QualifiedName */ ? name.left : name.expression; - var right = name.kind === 157 /* QualifiedName */ ? name.right : name.name; + else if (name.kind === 158 /* QualifiedName */ || name.kind === 202 /* PropertyAccessExpression */) { + var left = name.kind === 158 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 158 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -46493,18 +47703,17 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJSFile(name)) { - if (namespace.valueDeclaration && - ts.isVariableDeclaration(namespace.valueDeclaration) && - namespace.valueDeclaration.initializer && - isCommonJsRequire(namespace.valueDeclaration.initializer)) { - var moduleName = namespace.valueDeclaration.initializer.arguments[0]; - var moduleSym = resolveExternalModuleName(moduleName, moduleName); - if (moduleSym) { - var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); - if (resolvedModuleSymbol) { - namespace = resolvedModuleSymbol; - } + if (namespace.valueDeclaration && + ts.isInJSFile(namespace.valueDeclaration) && + ts.isVariableDeclaration(namespace.valueDeclaration) && + namespace.valueDeclaration.initializer && + isCommonJsRequire(namespace.valueDeclaration.initializer)) { + var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + var moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; } } } @@ -46525,7 +47734,7 @@ var ts; throw ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); - if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 266 /* ExportAssignment */)) { + if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 267 /* ExportAssignment */)) { markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true); } return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); @@ -46762,7 +47971,7 @@ var ts; function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { - if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 297 /* SourceFile */)) { + if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 298 /* SourceFile */)) { var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop"; @@ -46813,7 +48022,10 @@ var ts; var exports = getExportsOfModuleAsArray(moduleSymbol); var exportEquals = resolveExternalModuleSymbol(moduleSymbol); if (exportEquals !== moduleSymbol) { - ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); + var type = getTypeOfSymbol(exportEquals); + if (shouldTreatPropertiesOfExternalModuleAsExports(type)) { + ts.addRange(exports, getPropertiesOfType(type)); + } } return exports; } @@ -46833,11 +48045,14 @@ var ts; return undefined; } var type = getTypeOfSymbol(exportEquals); - return type.flags & 131068 /* Primitive */ || - ts.getObjectFlags(type) & 1 /* Class */ || - isArrayOrTupleLikeType(type) - ? undefined - : getPropertyOfType(type, memberName); + return shouldTreatPropertiesOfExternalModuleAsExports(type) ? getPropertyOfType(type, memberName) : undefined; + } + function shouldTreatPropertiesOfExternalModuleAsExports(resolvedExternalModuleType) { + return !(resolvedExternalModuleType.flags & 131068 /* Primitive */ || + ts.getObjectFlags(resolvedExternalModuleType) & 1 /* Class */ || + // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path + isArrayType(resolvedExternalModuleType) || + isTupleType(resolvedExternalModuleType)); } function getExportsOfSymbol(symbol) { return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : @@ -46895,11 +48110,13 @@ var ts; if (exportStars) { var nestedSymbols = ts.createSymbolTable(); var lookupTable_1 = new ts.Map(); - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - var exportedSymbols = visit(resolvedModule); - extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + if (exportStars.declarations) { + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + } } lookupTable_1.forEach(function (_a, id) { var exportsWithDuplicate = _a.exportsWithDuplicate; @@ -46982,11 +48199,28 @@ var ts; var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); var objectLiteralContainer = getVariableDeclarationOfObjectLiteral(container, meaning); - if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { + if (enclosingDeclaration && + container.flags & getQualifiedLeftMeaning(meaning) && + getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { return ts.append(ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers), objectLiteralContainer); // This order expresses a preference for the real container if it is in scope } - var res = ts.append(ts.append(additionalContainers, container), objectLiteralContainer); - return ts.concatenate(res, reexportContainers); + // we potentially have a symbol which is a member of the instance side of something - look for a variable in scope with the container's type + // which may be acting like a namespace (eg, `Symbol` acts like a namespace when looking up `Symbol.toStringTag`) + var firstVariableMatch = !(container.flags & getQualifiedLeftMeaning(meaning)) + && container.flags & 788968 /* Type */ + && getDeclaredTypeOfSymbol(container).flags & 524288 /* Object */ + && meaning === 111551 /* Value */ + ? forEachSymbolTableInScope(enclosingDeclaration, function (t) { + return ts.forEachEntry(t, function (s) { + if (s.flags & getQualifiedLeftMeaning(meaning) && getTypeOfSymbol(s) === getDeclaredTypeOfSymbol(container)) { + return s; + } + }); + }) : undefined; + var res = firstVariableMatch ? __spreadArray(__spreadArray([firstVariableMatch], additionalContainers), [container]) : __spreadArray(__spreadArray([], additionalContainers), [container]); + res = ts.append(res, objectLiteralContainer); + res = ts.addRange(res, reexportContainers); + return res; } var candidates = ts.mapDefined(symbol.declarations, function (d) { if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) { @@ -47064,7 +48298,7 @@ var ts; var members = node.members; for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { var member = members_3[_i]; - if (member.kind === 166 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 167 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -47073,7 +48307,9 @@ var ts; var result = new Type(checker, flags); typeCount++; result.id = typeCount; - typeCatalog.push(result); + if (produceDiagnostics) { // Only record types from one checker + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.recordType(result); + } return result; } function createOriginType(flags) { @@ -47133,14 +48369,23 @@ var ts; }); return result || ts.emptyArray; } + function getNamedOrIndexSignatureMembers(members) { + var result = getNamedMembers(members); + var index = getIndexSymbolFromSymbolTable(members); + return index ? ts.concatenate(result, [index]) : result; + } function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - type.members = members; - type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members); - type.callSignatures = callSignatures; - type.constructSignatures = constructSignatures; - type.stringIndexInfo = stringIndexInfo; - type.numberIndexInfo = numberIndexInfo; - return type; + var resolved = type; + resolved.members = members; + resolved.properties = ts.emptyArray; + resolved.callSignatures = callSignatures; + resolved.constructSignatures = constructSignatures; + resolved.stringIndexInfo = stringIndexInfo; + resolved.numberIndexInfo = numberIndexInfo; + // This can loop back to getPropertyOfType() which would crash if `callSignatures` & `constructSignatures` are not initialized. + if (members !== emptySymbols) + resolved.properties = getNamedMembers(members); + return resolved; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); @@ -47163,28 +48408,28 @@ var ts; var _loop_8 = function (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { - if (result = callback(location.locals)) { + if (result = callback(location.locals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } } switch (location.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } // falls through - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var sym = getSymbolOfNode(location); // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred // to one another anyway) - if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) { + if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: // Type parameters are bound into `members` lists so they can merge across declarations // This is troublesome, since in all other respects, they behave like locals :cries: // TODO: the below is shared with similar code in `resolveName` - in fact, rephrasing all this symbol @@ -47210,7 +48455,7 @@ var ts; if (typeof state_2 === "object") return state_2.value; } - return callback(globals); + return callback(globals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true); } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace @@ -47230,11 +48475,11 @@ var ts; /** * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) */ - function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification, isLocalNameLookup) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - var result = trySymbolTable(symbols, ignoreQualification); + var result = trySymbolTable(symbols, ignoreQualification, isLocalNameLookup); visitedSymbolTables.pop(); return result; } @@ -47252,7 +48497,7 @@ var ts; !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning)); } - function trySymbolTable(symbols, ignoreQualification) { + function trySymbolTable(symbols, ignoreQualification, isLocalNameLookup) { // If symbol is directly available by its name in the symbol table if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { return [symbol]; @@ -47265,9 +48510,11 @@ var ts; && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // If we're looking up a local name to reference directly, omit namespace reexports, otherwise when we're trawling through an export list to make a dotted name, we can keep it + && (isLocalNameLookup ? !ts.some(symbolFromSymbolTable.declarations, ts.isNamespaceReexportDeclaration) : true) // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ // See similar comment in `resolveName` for details - && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 270 /* ExportSpecifier */))) { + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 271 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification); if (candidate) { @@ -47311,7 +48558,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 270 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 271 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -47326,10 +48573,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: continue; default: return false; @@ -47367,7 +48614,7 @@ var ts; return hasAccessibleDeclarations; } } - else if (allowModules) { + if (allowModules) { if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { if (shouldComputeAliasesToMakeVisible) { earlyModuleBail = true; @@ -47441,7 +48688,8 @@ var ts; return { accessibility: 2 /* CannotBeNamed */, errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), - errorModuleName: symbolToString(symbolExternalModule) + errorModuleName: symbolToString(symbolExternalModule), + errorNode: ts.isInJSFile(enclosingDeclaration) ? enclosingDeclaration : undefined, }; } } @@ -47458,10 +48706,10 @@ var ts; return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { - return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -47517,14 +48765,14 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 176 /* TypeQuery */ || + if (entityName.parent.kind === 177 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || - entityName.parent.kind === 158 /* ComputedPropertyName */) { + entityName.parent.kind === 159 /* ComputedPropertyName */) { // Typeof value meaning = 111551 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 157 /* QualifiedName */ || entityName.kind === 201 /* PropertyAccessExpression */ || - entityName.parent.kind === 260 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 158 /* QualifiedName */ || entityName.kind === 202 /* PropertyAccessExpression */ || + entityName.parent.kind === 261 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1920 /* Namespace */; @@ -47565,7 +48813,7 @@ var ts; function symbolToStringWorker(writer) { var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217 // add neverAsciiEscape for GH#39027 - var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 297 /* SourceFile */ ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true }); + var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 298 /* SourceFile */ ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); return writer; @@ -47577,10 +48825,10 @@ var ts; function signatureToStringWorker(writer) { var sigOutput; if (flags & 262144 /* WriteArrowStyleSignature */) { - sigOutput = kind === 1 /* Construct */ ? 175 /* ConstructorType */ : 174 /* FunctionType */; + sigOutput = kind === 1 /* Construct */ ? 176 /* ConstructorType */ : 175 /* FunctionType */; } else { - sigOutput = kind === 1 /* Construct */ ? 170 /* ConstructSignature */ : 169 /* CallSignature */; + sigOutput = kind === 1 /* Construct */ ? 171 /* ConstructSignature */ : 170 /* CallSignature */; } var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); @@ -47620,14 +48868,14 @@ var ts; return typeToString(type, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); } function symbolValueDeclarationIsContextSensitive(symbol) { - return symbol && symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration); + return symbol && !!symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration); } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0 /* None */; } return flags & 814775659 /* NodeBuilderFlagsMask */; } function isClassInstanceSide(type) { - return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(ts.getObjectFlags(type) & 1073741824 /* IsClassInstanceClone */)); + return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288 /* Object */) && !!(ts.getObjectFlags(type) & 16777216 /* IsClassInstanceClone */))); } function createNodeBuilder() { return { @@ -47961,7 +49209,9 @@ var ts; 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 === 221 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || + else if (symbol.flags & 32 /* Class */ + && !getBaseTypeVariableOfClass(symbol) + && !(symbol.valueDeclaration && symbol.valueDeclaration.kind === 222 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, isInstanceType); @@ -47992,7 +49242,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 297 /* SourceFile */ || declaration.parent.kind === 257 /* ModuleBlock */; + return declaration.parent.kind === 298 /* SourceFile */ || declaration.parent.kind === 258 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -48043,12 +49293,12 @@ var ts; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 174 /* FunctionType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 175 /* FunctionType */, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 175 /* ConstructorType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 176 /* ConstructorType */, context); return signatureNode; } } @@ -48228,17 +49478,17 @@ var ts; var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 169 /* CallSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 170 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; if (signature.flags & 4 /* Abstract */) continue; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 170 /* ConstructSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 171 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { var indexSignature = void 0; - if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + if (resolvedType.objectFlags & 1024 /* ReverseMapped */) { indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context, createElidedInformationPlaceholder(context)); } else { @@ -48282,15 +49532,29 @@ var ts; } return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } + function shouldUsePlaceholderForProperty(propertySymbol, context) { + var _a; + // Use placeholders for reverse mapped types we've either already descended into, or which + // are nested reverse mappings within a mapping over a non-anonymous type. The later is a restriction mostly just to + // reduce the blowup in printback size from doing, eg, a deep reverse mapping over `Window`. + // Since anonymous types usually come from expressions, this allows us to preserve the output + // for deep mappings which likely come from expressions, while truncating those parts which + // come from mappings over library functions. + return !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */) + && (ts.contains(context.reverseMappedStack, propertySymbol) + || (((_a = context.reverseMappedStack) === null || _a === void 0 ? void 0 : _a[0]) + && !(ts.getObjectFlags(ts.last(context.reverseMappedStack).propertyType) & 16 /* Anonymous */))); + } function addPropertyToElementList(propertySymbol, context, typeElements) { + var _a; var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */); - var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? + var propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */ && isLateBoundName(propertySymbol.escapedName)) { var decl = ts.first(propertySymbol.declarations); - if (hasLateBindableName(decl)) { + if (propertySymbol.declarations && hasLateBindableName(decl)) { if (ts.isBinaryExpression(decl)) { var name = ts.getNameOfDeclaration(decl); if (name && ts.isElementAccessExpression(name) && ts.isPropertyAccessEntityNameExpression(name.argumentExpression)) { @@ -48302,29 +49566,34 @@ var ts; } } } - context.enclosingDeclaration = saveEnclosingDeclaration; + context.enclosingDeclaration = propertySymbol.valueDeclaration || ((_a = propertySymbol.declarations) === null || _a === void 0 ? void 0 : _a[0]) || saveEnclosingDeclaration; var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context); + context.enclosingDeclaration = saveEnclosingDeclaration; context.approximateLength += (ts.symbolName(propertySymbol).length + 1); var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */); for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { var signature = signatures_1[_i]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 164 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken }); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 165 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken }); typeElements.push(preserveCommentsOn(methodDeclaration)); } } else { - var savedFlags = context.flags; - context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; var propertyTypeNode = void 0; - if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + if (shouldUsePlaceholderForProperty(propertySymbol, context)) { propertyTypeNode = createElidedInformationPlaceholder(context); } else { + if (propertyIsReverseMapped) { + context.reverseMappedStack || (context.reverseMappedStack = []); + context.reverseMappedStack.push(propertySymbol); + } propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); + if (propertyIsReverseMapped) { + context.reverseMappedStack.pop(); + } } - context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(142 /* ReadonlyKeyword */)] : undefined; if (modifiers) { context.approximateLength += 9; @@ -48333,9 +49602,10 @@ var ts; typeElements.push(preserveCommentsOn(propertySignature)); } function preserveCommentsOn(node) { - if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 333 /* JSDocPropertyTag */; })) { - var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 333 /* JSDocPropertyTag */; }); - var commentText = d.comment; + var _a; + if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 337 /* JSDocPropertyTag */; })) { + var d = (_a = propertySymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 337 /* JSDocPropertyTag */; }); + var commentText = ts.getTextOfJSDocComment(d.comment); if (commentText) { ts.setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]); } @@ -48364,25 +49634,25 @@ var ts; var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */); /** Map from type reference identifier text to [type, index in `result` where the type node is] */ var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; - var result_4 = []; + var result_5 = []; var i = 0; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var type = types_2[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result_4.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + result_5.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result_4.push(typeNode_1); + result_5.push(typeNode_1); } break; } context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result_4.push(typeNode); + result_5.push(typeNode); if (seenNames && ts.isIdentifierTypeReference(typeNode)) { - seenNames.add(typeNode.typeName.escapedText, [type, result_4.length - 1]); + seenNames.add(typeNode.typeName.escapedText, [type, result_5.length - 1]); } } } @@ -48404,13 +49674,13 @@ var ts; })) { for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { var _a = types_3[_i], type = _a[0], resultIndex = _a[1]; - result_4[resultIndex] = typeToTypeNodeHelper(type, context); + result_5[resultIndex] = typeToTypeNodeHelper(type, context); } } }); context.flags = saveContextFlags; } - return result_4; + return result_5; } } function typesAreSameReference(a, b) { @@ -48452,7 +49722,7 @@ var ts; } var expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0]; // If the expanded parameter list had a variadic in a non-trailing position, don't expand it - var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 166 /* Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); + var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 167 /* Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -48479,25 +49749,25 @@ var ts; } } var modifiers = options === null || options === void 0 ? void 0 : options.modifiers; - if ((kind === 175 /* ConstructorType */) && signature.flags & 4 /* Abstract */) { + if ((kind === 176 /* ConstructorType */) && signature.flags & 4 /* Abstract */) { var flags = ts.modifiersToFlags(modifiers); modifiers = ts.factory.createModifiersFromModifierFlags(flags | 128 /* Abstract */); } context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum - var node = kind === 169 /* CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : - kind === 170 /* ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : - kind === 164 /* MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : - kind === 165 /* MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === 166 /* Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) : - kind === 167 /* GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : - kind === 168 /* SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : - kind === 171 /* IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) : - kind === 308 /* JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : - kind === 174 /* FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 175 /* ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 251 /* FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === 208 /* FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : - kind === 209 /* ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) : + var node = kind === 170 /* CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : + kind === 171 /* ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : + kind === 165 /* MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : + kind === 166 /* MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 167 /* Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) : + kind === 168 /* GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : + kind === 169 /* SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : + kind === 172 /* IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) : + kind === 309 /* JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : + kind === 175 /* FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : + kind === 176 /* ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : + kind === 252 /* FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 209 /* FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : + kind === 210 /* ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) : ts.Debug.assertNever(kind); if (typeArguments) { node.typeArguments = ts.factory.createNodeArray(typeArguments); @@ -48519,9 +49789,9 @@ var ts; return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 160 /* Parameter */); + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 161 /* Parameter */); if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 326 /* JSDocParameterTag */); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 330 /* JSDocParameterTag */); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -48536,7 +49806,7 @@ var ts; var dotDotDotToken = isRest ? ts.factory.createToken(25 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 78 /* Identifier */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : - parameterDeclaration.name.kind === 157 /* QualifiedName */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 158 /* QualifiedName */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); @@ -48701,11 +49971,11 @@ var ts; } function getSpecifierForModuleSymbol(symbol, context) { var _a; - var file = ts.getDeclarationOfKind(symbol, 297 /* SourceFile */); + var file = ts.getDeclarationOfKind(symbol, 298 /* SourceFile */); if (!file) { var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); }); if (equivalentFileSymbol) { - file = ts.getDeclarationOfKind(equivalentFileSymbol, 297 /* SourceFile */); + file = ts.getDeclarationOfKind(equivalentFileSymbol, 298 /* SourceFile */); } } if (file && file.moduleName !== undefined) { @@ -48716,8 +49986,8 @@ var ts; if (context.tracker.trackReferencedAmbientModule) { var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); if (ts.length(ambientDecls)) { - for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { - var decl = ambientDecls_1[_i]; + for (var _i = 0, _b = ambientDecls; _i < _b.length; _i++) { + var decl = _b[_i]; context.tracker.trackReferencedAmbientModule(decl, symbol); } } @@ -48744,7 +50014,7 @@ var ts; // specifier preference var moduleResolverHost = context.tracker.moduleResolverHost; var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; - specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "project-relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); (_a = links.specifierCache) !== null && _a !== void 0 ? _a : (links.specifierCache = new ts.Map()); links.specifierCache.set(contextFile.path, specifier); } @@ -48888,7 +50158,7 @@ var ts; var chain = lookupSymbolChain(symbol, context, meaning); if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) { + && !(context.flags & 65536 /* AllowQualifiedNameInPlaceOfIdentifier */)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); @@ -48968,9 +50238,6 @@ var ts; if (fromNameType) { return fromNameType; } - if (ts.isKnownSymbol(symbol)) { - return ts.factory.createComputedPropertyName(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("Symbol"), symbol.escapedName.substr(3))); - } var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName); var stringNamed = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isStringNamed); return createPropertyNameNodeForIdentifierOrLiteral(rawName, stringNamed, singleQuote); @@ -49037,13 +50304,13 @@ var ts; function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { if (type !== errorType && enclosingDeclaration) { var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation) && !ts.isGetAccessorDeclaration(declWithExistingAnnotation)) { // try to reuse the existing annotation var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { - var result_5 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); - if (result_5) { - return result_5; + var result_6 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_6) { + return result_6; } } } @@ -49060,10 +50327,14 @@ var ts; function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { if (type !== errorType && context.enclosingDeclaration) { var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); - if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { - var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); - if (result) { - return result; + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation) { + var annotated = getTypeFromTypeNode(annotation); + var thisInstantiated = annotated.flags & 262144 /* TypeParameter */ && annotated.isThisType ? instantiateType(annotated, signature.mapper) : annotated; + if (thisInstantiated === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } } } } @@ -49107,7 +50378,7 @@ var ts; return transformed === existing ? ts.setTextRange(ts.factory.cloneNode(existing), existing) : transformed; function visitExistingNodeTreeSymbols(node) { // We don't _actually_ support jsdoc namepath types, emit `any` instead - if (ts.isJSDocAllType(node) || node.kind === 310 /* JSDocNamepathType */) { + if (ts.isJSDocAllType(node) || node.kind === 311 /* JSDocNamepathType */) { return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } if (ts.isJSDocUnknownType(node)) { @@ -49226,8 +50497,8 @@ var ts; } } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { - var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 165 /* MethodDeclaration */, /*useAcessors*/ true); - var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 164 /* MethodSignature */, /*useAcessors*/ false); + var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 166 /* MethodDeclaration */, /*useAcessors*/ true); + var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 165 /* MethodSignature */, /*useAcessors*/ false); // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of // declaration mapping // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration @@ -49239,7 +50510,7 @@ var ts; var deferredPrivatesStack = []; var oldcontext = context; context = __assign(__assign({}, oldcontext), { usedSymbolNames: new ts.Set(oldcontext.usedSymbolNames), remappedSymbolNames: new ts.Map(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { - var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false); + var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeAliases*/ false); if (accessibleResult.accessibility === 0 /* Accessible */) { // Lookup the root symbol of the chain of refs we'll use to access it and serialize it var chain = lookupSymbolChainWorker(sym, context, meaning); @@ -49448,6 +50719,7 @@ var ts; // If it's a class/interface/function: emit a class/interface/function with a `default` modifier // These forms can merge, eg (`export default 12; export default interface A {}`) function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) { + var _a, _b; var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName); var isDefault = symbol.escapedName === "default" /* Default */; if (isPrivate && !(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) { @@ -49506,9 +50778,9 @@ var ts; if (textRange && ts.isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) { textRange = textRange.parent.parent; } - var propertyAccessRequire = ts.find(symbol.declarations, ts.isPropertyAccessExpression); + var propertyAccessRequire = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isPropertyAccessExpression); if (propertyAccessRequire && ts.isBinaryExpression(propertyAccessRequire.parent) && ts.isIdentifier(propertyAccessRequire.parent.right) - && type.symbol && ts.isSourceFile(type.symbol.valueDeclaration)) { + && ((_b = type.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration) && ts.isSourceFile(type.symbol.valueDeclaration)) { var alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right; addResult(ts.factory.createExportDeclaration( /*decorators*/ undefined, @@ -49558,7 +50830,10 @@ var ts; serializeEnum(symbol, symbolName, modifierFlags); } if (symbol.flags & 32 /* Class */) { - if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { + if (symbol.flags & 4 /* Property */ + && symbol.valueDeclaration + && ts.isBinaryExpression(symbol.valueDeclaration.parent) + && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members, // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today. @@ -49584,12 +50859,14 @@ var ts; if (symbol.flags & 8388608 /* ExportStar */) { // synthesize export * from "moduleReference" // Straightforward - only one thing to do - make an export declaration - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - if (!resolvedModule) - continue; - addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */); + if (symbol.declarations) { + for (var _i = 0, _c = symbol.declarations; _i < _c.length; _i++) { + var node = _c[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + if (!resolvedModule) + continue; + addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */); + } } } if (needsPostExportDefault) { @@ -49627,15 +50904,16 @@ var ts; function addResult(node, additionalModifierFlags) { if (ts.canHaveModifiers(node)) { var newModifierFlags = 0 /* None */; + var enclosingDeclaration_1 = context.enclosingDeclaration && + (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 /* Export */ && - context.enclosingDeclaration && - (isExportingScope(context.enclosingDeclaration) || ts.isModuleDeclaration(context.enclosingDeclaration)) && + enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && canHaveExportModifier(node)) { // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private newModifierFlags |= 1 /* Export */; } if (addingDeclare && !(newModifierFlags & 1 /* Export */) && - (!context.enclosingDeclaration || !(context.enclosingDeclaration.flags & 8388608 /* Ambient */)) && + (!enclosingDeclaration_1 || !(enclosingDeclaration_1.flags & 8388608 /* Ambient */)) && (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) { // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope newModifierFlags |= 2 /* Ambient */; @@ -49650,19 +50928,23 @@ var ts; results.push(node); } function serializeTypeAlias(symbol, symbolName, modifierFlags) { + var _a; var aliasType = getDeclaredTypeOfTypeAlias(symbol); var typeParams = getSymbolLinks(symbol).typeParameters; var typeParamDecls = ts.map(typeParams, function (p) { return typeParameterToDeclaration(p, context); }); - var jsdocAliasDecl = ts.find(symbol.declarations, ts.isJSDocTypeAlias); - var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined; + var jsdocAliasDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isJSDocTypeAlias); + var commentText = ts.getTextOfJSDocComment(jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined); var oldFlags = context.flags; context.flags |= 8388608 /* InTypeAlias */; + var oldEnclosingDecl = context.enclosingDeclaration; + context.enclosingDeclaration = jsdocAliasDecl; var typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; + context.enclosingDeclaration = oldEnclosingDecl; } function serializeInterface(symbol, symbolName, modifierFlags) { var interfaceType = getDeclaredTypeOfClassOrInterface(symbol); @@ -49671,8 +50953,8 @@ var ts; var baseTypes = getBaseTypes(interfaceType); var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined; var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); }); - var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 169 /* CallSignature */); - var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 170 /* ConstructSignature */); + var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 170 /* CallSignature */); + var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 171 /* ConstructSignature */); var indexSignatures = serializeIndexSignatures(interfaceType, baseType); var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(93 /* ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551 /* Value */); }))]; addResult(ts.factory.createInterfaceDeclaration( @@ -49741,9 +51023,8 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; // Each overload becomes a separate function declaration, in order - var decl = signatureToSignatureDeclarationHelper(sig, 251 /* FunctionDeclaration */, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled }); - // for expressions assigned to `var`s, use the `var` as the text range - addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags); + var decl = signatureToSignatureDeclarationHelper(sig, 252 /* FunctionDeclaration */, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled }); + addResult(ts.setTextRange(decl, getSignatureTextRangeLocation(sig)), modifierFlags); } // Module symbol emit will take care of module-y members, provided it has exports if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) { @@ -49751,6 +51032,18 @@ var ts; serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true); } } + function getSignatureTextRangeLocation(signature) { + if (signature.declaration && signature.declaration.parent) { + if (ts.isBinaryExpression(signature.declaration.parent) && ts.getAssignmentDeclarationKind(signature.declaration.parent) === 5 /* Property */) { + return signature.declaration.parent; + } + // for expressions assigned to `var`s, use the `var` as the text range + if (ts.isVariableDeclaration(signature.declaration.parent) && signature.declaration.parent.parent) { + return signature.declaration.parent.parent; + } + } + return signature.declaration; + } function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) { if (ts.length(props)) { var localVsRemoteMap = ts.arrayToMultiMap(props, function (p) { @@ -49837,8 +51130,8 @@ var ts; return undefined; } function serializeAsClass(symbol, localName, modifierFlags) { - var _a; - var originalDecl = ts.find(symbol.declarations, ts.isClassLike); + var _a, _b; + var originalDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isClassLike); var oldEnclosing = context.enclosingDeclaration; context.enclosingDeclaration = originalDecl || oldEnclosing; var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -49849,7 +51142,7 @@ var ts; var implementsExpressions = originalImplements && sanitizeJSDocImplements(originalImplements) || ts.mapDefined(getImplementsTypes(classType), serializeImplementedType); var staticType = getTypeOfSymbol(symbol); - var isClass = !!((_a = staticType.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration) && ts.isClassLike(staticType.symbol.valueDeclaration); + var isClass = !!((_b = staticType.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration) && ts.isClassLike(staticType.symbol.valueDeclaration); var staticBaseType = isClass ? getBaseConstructorTypeOfClass(staticType) : anyType; @@ -49860,14 +51153,14 @@ var ts; // a union/intersection base type, but inherited properties // don't matter here. var valueDecl = s.valueDeclaration; - return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); + return !!valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); }); var hasPrivateIdentifier = ts.some(symbolProps, function (s) { // `valueDeclaration` could be undefined if inherited from // a union/intersection base type, but inherited properties // don't matter here. var valueDecl = s.valueDeclaration; - return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); + return !!valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); }); // Boil down all private properties into a single one. var privateProperties = hasPrivateIdentifier ? @@ -49890,7 +51183,7 @@ var ts; !ts.some(getSignaturesOfType(staticType, 1 /* Construct */)); var constructors = isNonConstructableClassLikeInJsFile ? [ts.factory.createConstructorDeclaration(/*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(8 /* Private */), [], /*body*/ undefined)] : - serializeSignatures(1 /* Construct */, staticType, staticBaseType, 166 /* Constructor */); + serializeSignatures(1 /* Construct */, staticType, staticBaseType, 167 /* Constructor */); var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); context.enclosingDeclaration = oldEnclosing; addResult(ts.setTextRange(ts.factory.createClassDeclaration( @@ -49917,8 +51210,8 @@ var ts; var targetName = getInternalSymbolName(target, verbatimTargetName); includePrivateSymbol(target); // the target may be within the same scope - attempt to serialize it first switch (node.kind) { - case 198 /* BindingElement */: - if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 249 /* VariableDeclaration */) { + case 199 /* BindingElement */: + if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 250 /* VariableDeclaration */) { // const { SomeClass } = require('./lib'); var specifier_1 = getSpecifierForModuleSymbol(target.parent || target, context); // './lib' var propertyName = node.propertyName; @@ -49930,13 +51223,13 @@ var ts; // We don't know how to serialize this (nested?) binding element ts.Debug.failBadSyntaxKind(((_c = node.parent) === null || _c === void 0 ? void 0 : _c.parent) || node, "Unhandled binding element grandparent kind in declaration serialization"); break; - case 289 /* ShorthandPropertyAssignment */: - if (((_e = (_d = node.parent) === null || _d === void 0 ? void 0 : _d.parent) === null || _e === void 0 ? void 0 : _e.kind) === 216 /* BinaryExpression */) { + case 290 /* ShorthandPropertyAssignment */: + if (((_e = (_d = node.parent) === null || _d === void 0 ? void 0 : _d.parent) === null || _e === void 0 ? void 0 : _e.kind) === 217 /* BinaryExpression */) { // module.exports = { SomeClass } serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), targetName); } break; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: // commonjs require: const x = require('y') if (ts.isPropertyAccessExpression(node.initializer)) { // const x = require('y').z @@ -49956,7 +51249,7 @@ var ts; break; } // else fall through and treat commonjs require just like import= - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // This _specifically_ only exists to handle json declarations - where we make aliases, but since // we emit no declarations for the json document, must not refer to it in the declarations if (target.escapedName === "export=" /* ExportEquals */ && ts.some(target.declarations, ts.isJsonSourceFile)) { @@ -49973,13 +51266,13 @@ var ts; ? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false) : ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)))), isLocalImport ? modifierFlags : 0 /* None */); break; - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: // export as namespace foo // TODO: Not part of a file's local or export symbol tables // Is bound into file.symbol.globalExports instead, which we don't currently traverse addResult(ts.factory.createNamespaceExportDeclaration(ts.idText(node.name)), 0 /* None */); break; - case 262 /* ImportClause */: + case 263 /* ImportClause */: addResult(ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, ts.factory.createIdentifier(localName), /*namedBindings*/ undefined), @@ -49988,18 +51281,18 @@ var ts; // In such cases, the `target` refers to the module itself already ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: addResult(ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */); break; - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: addResult(ts.factory.createExportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */); break; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: addResult(ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause( @@ -50008,7 +51301,7 @@ var ts; ts.factory.createImportSpecifier(localName !== verbatimTargetName ? ts.factory.createIdentifier(verbatimTargetName) : undefined, ts.factory.createIdentifier(localName)) ])), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: // does not use localName because the symbol name in this case refers to the name in the exports table, // which we must exactly preserve var specifier = node.parent.parent.moduleSpecifier; @@ -50016,12 +51309,12 @@ var ts; // another file serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.factory.createStringLiteral(specifier.text) : undefined); break; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: serializeMaybeAliasAssignment(symbol); break; - case 216 /* BinaryExpression */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 217 /* BinaryExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: // Could be best encoded as though an export specifier or as though an export assignment // If name is default or export=, do an export assignment // Otherwise do an export specifier @@ -50155,6 +51448,7 @@ var ts; } function makeSerializePropertySymbol(createProperty, methodKind, useAccessors) { return function serializePropertySymbol(p, isStatic, baseType) { + var _a, _b, _c, _d, _e; var modifierFlags = ts.getDeclarationModifierFlagsFromSymbol(p); var isPrivate = !!(modifierFlags & 8 /* Private */); if (isStatic && (p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */))) { @@ -50171,7 +51465,7 @@ var ts; } var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0); var name = getPropertyNameNodeForSymbol(p, context); - var firstPropertyLikeDecl = ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression)); + var firstPropertyLikeDecl = (_a = p.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression)); if (p.flags & 98304 /* Accessor */ && useAccessors) { var result = []; if (p.flags & 65536 /* SetAccessor */) { @@ -50181,13 +51475,13 @@ var ts; /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "arg", /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], - /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl)); + /*body*/ undefined), ((_b = p.declarations) === null || _b === void 0 ? void 0 : _b.find(ts.isSetAccessor)) || firstPropertyLikeDecl)); } if (p.flags & 32768 /* GetAccessor */) { var isPrivate_1 = modifierFlags & 8 /* Private */; result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration( /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), - /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl)); + /*body*/ undefined), ((_c = p.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isGetAccessor)) || firstPropertyLikeDecl)); } return result; } @@ -50198,7 +51492,7 @@ var ts; /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ - /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl); + /*initializer*/ undefined), ((_d = p.declarations) === null || _d === void 0 ? void 0 : _d.find(ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration))) || firstPropertyLikeDecl); } if (p.flags & (8192 /* Method */ | 16 /* Function */)) { var type = getTypeOfSymbol(p); @@ -50207,7 +51501,7 @@ var ts; return ts.setTextRange(createProperty( /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, /*type*/ undefined, - /*initializer*/ undefined), ts.find(p.declarations, ts.isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations[0]); + /*initializer*/ undefined), ((_e = p.declarations) === null || _e === void 0 ? void 0 : _e.find(ts.isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); } var results_1 = []; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { @@ -50218,7 +51512,8 @@ var ts; questionToken: p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, modifiers: flag ? ts.factory.createModifiersFromModifierFlags(flag) : undefined }); - results_1.push(ts.setTextRange(decl, sig.declaration)); + var location = sig.declaration && ts.isPrototypePropertyAssignment(sig.declaration.parent) ? sig.declaration.parent : sig.declaration; + results_1.push(ts.setTextRange(decl, location)); } return results_1; } @@ -50434,9 +51729,9 @@ var ts; return "public"; } function getTypeAliasForTypeLiteral(type) { - if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { + if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */ && type.symbol.declarations) { var node = ts.walkUpParenthesizedTypes(type.symbol.declarations[0].parent); - if (node.kind === 254 /* TypeAliasDeclaration */) { + if (node.kind === 255 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -50444,11 +51739,11 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 257 /* ModuleBlock */ && + node.parent.kind === 258 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } function isDefaultBindingContext(location) { - return location.kind === 297 /* SourceFile */ || ts.isAmbientModule(location); + return location.kind === 298 /* SourceFile */ || ts.isAmbientModule(location); } function getNameOfSymbolFromNameType(symbol, context) { var nameType = getSymbolLinks(symbol).nameType; @@ -50507,17 +51802,17 @@ var ts; if (!declaration) { declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway } - if (declaration.parent && declaration.parent.kind === 249 /* VariableDeclaration */) { + if (declaration.parent && declaration.parent.kind === 250 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } switch (declaration.kind) { - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { context.encounteredError = true; } - return declaration.kind === 221 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; + return declaration.kind === 222 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } var name = getNameOfSymbolFromNameType(symbol, context); @@ -50534,28 +51829,28 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: - case 325 /* JSDocEnumTag */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: + case 329 /* JSDocEnumTag */: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // falls through - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 251 /* FunctionDeclaration */: - case 255 /* EnumDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 252 /* FunctionDeclaration */: + case 256 /* EnumDeclaration */: + case 261 /* ImportEqualsDeclaration */: // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; @@ -50563,55 +51858,55 @@ var ts; var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 260 /* ImportEqualsDeclaration */ && parent.kind !== 297 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) { + !(node.kind !== 261 /* ImportEqualsDeclaration */ && parent.kind !== 298 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible return isDeclarationVisible(parent); - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasEffectiveModifier(node, 8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so: // falls through - case 166 /* Constructor */: - case 170 /* ConstructSignature */: - case 169 /* CallSignature */: - case 171 /* IndexSignature */: - case 160 /* Parameter */: - case 257 /* ModuleBlock */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 177 /* TypeLiteral */: - case 173 /* TypeReference */: - case 178 /* ArrayType */: - case 179 /* TupleType */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 186 /* ParenthesizedType */: - case 192 /* NamedTupleMember */: + case 167 /* Constructor */: + case 171 /* ConstructSignature */: + case 170 /* CallSignature */: + case 172 /* IndexSignature */: + case 161 /* Parameter */: + case 258 /* ModuleBlock */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 178 /* TypeLiteral */: + case 174 /* TypeReference */: + case 179 /* ArrayType */: + case 180 /* TupleType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 187 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: return isDeclarationVisible(node.parent); // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: + case 266 /* ImportSpecifier */: return false; // Type parameters are always visible - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: // Source file and namespace export are always visible // falls through - case 297 /* SourceFile */: - case 259 /* NamespaceExportDeclaration */: + case 298 /* SourceFile */: + case 260 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return false; default: return false; @@ -50620,10 +51915,10 @@ var ts; } function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 266 /* ExportAssignment */) { + if (node.parent && node.parent.kind === 267 /* ExportAssignment */) { exportSymbol = resolveName(node, node.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } - else if (node.parent.kind === 270 /* ExportSpecifier */) { + else if (node.parent.kind === 271 /* ExportSpecifier */) { exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; @@ -50728,12 +52023,12 @@ var ts; function getDeclarationContainer(node) { return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 249 /* VariableDeclaration */: - case 250 /* VariableDeclarationList */: - case 265 /* ImportSpecifier */: - case 264 /* NamedImports */: - case 263 /* NamespaceImport */: - case 262 /* ImportClause */: + case 250 /* VariableDeclaration */: + case 251 /* VariableDeclarationList */: + case 266 /* ImportSpecifier */: + case 265 /* NamedImports */: + case 264 /* NamespaceImport */: + case 263 /* ImportClause */: return false; default: return true; @@ -50796,9 +52091,16 @@ var ts; var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= 131072 /* ObjectRestType */; + result.objectFlags |= 8388608 /* ObjectRestType */; return result; } + function isGenericTypeWithUndefinedConstraint(type) { + return !!(type.flags & 465829888 /* Instantiable */) && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 32768 /* Undefined */); + } + function getNonUndefinedType(type) { + var typeOrConstraint = someType(type, isGenericTypeWithUndefinedConstraint) ? mapType(type, function (t) { return t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type; + return getTypeWithFacts(typeOrConstraint, 524288 /* NEUndefined */); + } // Determine the control flow type associated with a destructuring declaration or assignment. The following // forms of destructuring are possible: // let { x } = obj; // BindingElement @@ -50833,23 +52135,23 @@ var ts; function getParentElementAccess(node) { var ancestor = node.parent.parent; switch (ancestor.kind) { - case 198 /* BindingElement */: - case 288 /* PropertyAssignment */: + case 199 /* BindingElement */: + case 289 /* PropertyAssignment */: return getSyntheticElementAccess(ancestor); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return getSyntheticElementAccess(node.parent); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return ancestor.initializer; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return ancestor.right; } } function getDestructuringPropertyName(node) { var parent = node.parent; - if (node.kind === 198 /* BindingElement */ && parent.kind === 196 /* ObjectBindingPattern */) { + if (node.kind === 199 /* BindingElement */ && parent.kind === 197 /* ObjectBindingPattern */) { return getLiteralPropertyNameText(node.propertyName || node.name); } - if (node.kind === 288 /* PropertyAssignment */ || node.kind === 289 /* ShorthandPropertyAssignment */) { + if (node.kind === 289 /* PropertyAssignment */ || node.kind === 290 /* ShorthandPropertyAssignment */) { return getLiteralPropertyNameText(node.name); } return "" + parent.elements.indexOf(node); @@ -50875,7 +52177,7 @@ var ts; parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */); } var type; - if (pattern.kind === 196 /* ObjectBindingPattern */) { + if (pattern.kind === 197 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { parentType = getReducedType(parentType); if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { @@ -50895,7 +52197,7 @@ var ts; // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name = declaration.propertyName || declaration.name; var indexType = getLiteralTypeFromPropertyName(name); - var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */), declaration.name); + var declaredType = getIndexedAccessType(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */); type = getFlowTypeOfDestructuring(declaration, declaredType); } } @@ -50916,7 +52218,7 @@ var ts; else if (isArrayLikeType(parentType)) { var indexType = getLiteralType(index_2); var accessFlags = hasDefaultValue(declaration) ? 8 /* NoTupleBoundsCheck */ : 0; - var declaredType = getConstraintForLocation(getIndexedAccessTypeOrUndefined(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, declaration.name, accessFlags | 16 /* ExpressionPosition */) || errorType, declaration.name); + var declaredType = getIndexedAccessTypeOrUndefined(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, declaration.name, accessFlags | 16 /* ExpressionPosition */) || errorType; type = getFlowTypeOfDestructuring(declaration, declaredType); } else { @@ -50929,11 +52231,9 @@ var ts; if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ? - getTypeWithFacts(type, 524288 /* NEUndefined */) : - type; + return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ? getNonUndefinedType(type) : type; } - return widenTypeInferredFromInitializer(declaration, getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), checkDeclarationInitializer(declaration)], 2 /* Subtype */)); + return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration)], 2 /* Subtype */)); } function getTypeForDeclarationFromJSDocComment(declaration) { var jsdocType = ts.getJSDocType(declaration); @@ -50948,7 +52248,7 @@ var ts; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 199 /* ArrayLiteralExpression */ && expr.elements.length === 0; + return expr.kind === 200 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { if (optional === void 0) { optional = true; } @@ -50958,11 +52258,11 @@ var ts; function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 238 /* ForInStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForInStatement */) { var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 240 /* ForOfStatement */) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -50999,8 +52299,8 @@ var ts; if (ts.isParameter(declaration)) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 168 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { - var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 167 /* GetAccessor */); + if (func.kind === 169 /* SetAccessor */ && hasBindableName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 168 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -51071,7 +52371,7 @@ var ts; links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && ts.every(symbol.declarations, function (declaration) { return ts.isBinaryExpression(declaration) && isPossiblyAliasedThisProperty(declaration) && - (declaration.left.kind !== 202 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && + (declaration.left.kind !== 203 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ undefined, declaration, symbol, declaration); }); } @@ -51087,13 +52387,33 @@ var ts; !declaration.initializer && (noImplicitAny || ts.isInJSFile(declaration)); } function getDeclaringConstructor(symbol) { + if (!symbol.declarations) { + return; + } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var container = ts.getThisContainer(declaration, /*includeArrowFunctions*/ false); - if (container && (container.kind === 166 /* Constructor */ || isJSConstructor(container))) { + if (container && (container.kind === 167 /* Constructor */ || isJSConstructor(container))) { return container; } } + ; + } + /** Create a synthetic property access flow node after the last statement of the file */ + function getFlowTypeFromCommonJSExport(symbol) { + var file = ts.getSourceFileOfNode(symbol.declarations[0]); + var accessName = ts.unescapeLeadingUnderscores(symbol.escapedName); + var areAllModuleExports = symbol.declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && ts.isModuleExportsAccessExpression(d.expression); }); + var reference = areAllModuleExports + ? ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("module"), ts.factory.createIdentifier("exports")), accessName) + : ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("exports"), accessName); + if (areAllModuleExports) { + ts.setParent(reference.expression.expression, reference.expression); + } + ts.setParent(reference.expression, reference); + ts.setParent(reference, file); + reference.flowNode = file.endFlowNode; + return getFlowTypeOfReference(reference, autoType, undefinedType); } function getFlowTypeInConstructor(symbol, constructor) { var accessName = ts.startsWith(symbol.escapedName, "__#") @@ -51111,7 +52431,10 @@ var ts; return everyType(flowType, isNullableType) ? undefined : convertAutoToAny(flowType); } function getFlowTypeOfProperty(reference, prop) { - var initialType = prop && (!isAutoTypedProperty(prop) || ts.getEffectiveModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType; + var initialType = (prop === null || prop === void 0 ? void 0 : prop.valueDeclaration) + && (!isAutoTypedProperty(prop) || ts.getEffectiveModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) + && getTypeOfPropertyInBaseClass(prop) + || undefinedType; return getFlowTypeOfReference(reference, autoType, initialType); } function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) { @@ -51122,7 +52445,7 @@ var ts; if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + var containerObjectType = symbol.valueDeclaration && getJSContainerObjectType(symbol.valueDeclaration, symbol, container); return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var type; @@ -51134,40 +52457,42 @@ var ts; type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol)); } if (!type) { - var jsdocType = void 0; var types = void 0; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : - ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : - undefined; - if (!expression) { - continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere - } - var kind = ts.isAccessExpression(expression) - ? ts.getAssignmentDeclarationPropertyAccessKind(expression) - : ts.getAssignmentDeclarationKind(expression); - if (kind === 4 /* ThisProperty */ || ts.isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) { - if (isDeclarationInConstructor(expression)) { - definedInConstructor = true; + if (symbol.declarations) { + var jsdocType = void 0; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : + ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere } - else { - definedInMethod = true; + var kind = ts.isAccessExpression(expression) + ? ts.getAssignmentDeclarationPropertyAccessKind(expression) + : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */ || ts.isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + if (!ts.isCallExpression(expression)) { + jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } - if (!ts.isCallExpression(expression)) { - jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); - } - if (!jsdocType) { - (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); - } + type = jsdocType; } - type = jsdocType; if (!type) { if (!ts.length(types)) { return errorType; // No types from any declarations :( } - var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; + var constructorTypes = definedInConstructor && symbol.declarations ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { var propType = getTypeOfPropertyInBaseClass(symbol); @@ -51181,7 +52506,7 @@ var ts; } } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); - if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { + if (symbol.valueDeclaration && filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } @@ -51205,10 +52530,11 @@ var ts; mergeSymbolTable(exports, s.exports); } var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - type.objectFlags |= 16384 /* JSLiteral */; + type.objectFlags |= 8192 /* JSLiteral */; return type; } function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) { + var _a; var typeNode = ts.getEffectiveTypeAnnotationNode(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -51219,7 +52545,7 @@ var ts; errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type); } } - if (symbol.parent) { + if ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) { var typeNode_2 = ts.getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration); if (typeNode_2) { return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode_2), symbol.escapedName); @@ -51283,7 +52609,7 @@ var ts; // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because // it's unclear what that's supposed to mean, so it's probably a mistake. - if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { + if (s.valueDeclaration && exportedMember.valueDeclaration && ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName); var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration; ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName)); @@ -51305,9 +52631,9 @@ var ts; }); var result = createAnonymousType(initialSize !== members_4.size ? undefined : exportedType.symbol, // Only set the type's symbol if it looks to be the same as the original type members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo); - result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + result.objectFlags |= (ts.getObjectFlags(type) & 8192 /* JSLiteral */); // Propagate JSLiteral flag if (result.symbol && result.symbol.flags & 32 /* Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { - result.objectFlags |= 1073741824 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type + result.objectFlags |= 16777216 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type } return result; } @@ -51326,9 +52652,9 @@ var ts; var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. // Function expressions that are assigned to the prototype count as methods. - return thisContainer.kind === 166 /* Constructor */ || - thisContainer.kind === 251 /* FunctionDeclaration */ || - (thisContainer.kind === 208 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + return thisContainer.kind === 167 /* Constructor */ || + thisContainer.kind === 252 /* FunctionDeclaration */ || + (thisContainer.kind === 209 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); } function getConstructorDefinedThisAssignmentTypes(types, declarations) { ts.Debug.assert(types.length === declarations.length); @@ -51366,7 +52692,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -51390,7 +52716,7 @@ var ts; result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -51398,7 +52724,7 @@ var ts; function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - var restElement = lastElement && lastElement.kind === 198 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : undefined; + var restElement = lastElement && lastElement.kind === 199 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : undefined; if (elements.length === 0 || elements.length === 1 && restElement) { return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } @@ -51409,7 +52735,7 @@ var ts; if (includePatternInType) { result = cloneTypeReference(result); result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -51423,7 +52749,7 @@ var ts; function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { if (includePatternInType === void 0) { includePatternInType = false; } if (reportErrors === void 0) { reportErrors = false; } - return pattern.kind === 196 /* ObjectBindingPattern */ + return pattern.kind === 197 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -51439,8 +52765,17 @@ var ts; function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors); } + function isGlobalSymbolConstructor(node) { + var symbol = getSymbolOfNode(node); + var globalSymbol = getGlobalESSymbolConstructorTypeSymbol(/*reportErrors*/ false); + return globalSymbol && symbol && symbol === globalSymbol; + } function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) { if (type) { + // TODO: If back compat with pre-3.0/4.0 libs isn't required, remove the following SymbolConstructor special case transforming `symbol` into `unique symbol` + if (type.flags & 4096 /* ESSymbol */ && isGlobalSymbolConstructor(declaration.parent)) { + type = getESSymbolLikeTypeForNode(declaration); + } if (reportErrors) { reportErrorsFromWidening(declaration, type); } @@ -51462,7 +52797,7 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 160 /* Parameter */ ? root.parent : root; + var memberDeclaration = root.kind === 161 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function tryGetTypeFromEffectiveTypeNode(declaration) { @@ -51493,19 +52828,31 @@ var ts; if (symbol === requireSymbol) { return anyType; } - if (symbol.flags & 134217728 /* ModuleExports */) { + if (symbol.flags & 134217728 /* ModuleExports */ && symbol.valueDeclaration) { var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var result = createSymbol(fileSymbol.flags, "exports"); + result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : []; + result.parent = symbol; + result.target = fileSymbol; + if (fileSymbol.valueDeclaration) + result.valueDeclaration = fileSymbol.valueDeclaration; + if (fileSymbol.members) + result.members = new ts.Map(fileSymbol.members); + if (fileSymbol.exports) + result.exports = new ts.Map(fileSymbol.exports); var members = ts.createSymbolTable(); - members.set("exports", fileSymbol); + members.set("exports", result); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); } // Handle catch clause variables + ts.Debug.assertIsDefined(symbol.valueDeclaration); var declaration = symbol.valueDeclaration; if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { - var decl = declaration; - if (!decl.type) + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode === undefined) { return anyType; - var type_1 = getTypeOfNode(decl.type); + } + var type_1 = getTypeOfNode(typeNode); // an errorType will make `checkTryStatement` issue an error return isTypeAny(type_1) || type_1 === unknownType ? type_1 : errorType; } @@ -51525,7 +52872,7 @@ var ts; return reportCircularityError(symbol); } var type; - if (declaration.kind === 266 /* ExportAssignment */) { + if (declaration.kind === 267 /* ExportAssignment */) { type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } else if (ts.isBinaryExpression(declaration) || @@ -51580,7 +52927,7 @@ var ts; type = getTypeOfEnumMember(symbol); } else if (ts.isAccessor(declaration)) { - type = resolveTypeOfAccessors(symbol); + type = resolveTypeOfAccessors(symbol) || ts.Debug.fail("Non-write accessor resolution must always produce a type"); } else { return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol)); @@ -51596,7 +52943,7 @@ var ts; } function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { - if (accessor.kind === 167 /* GetAccessor */) { + if (accessor.kind === 168 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation; } @@ -51620,63 +52967,78 @@ var ts; } function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); - return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + return links.type || (links.type = getTypeOfAccessorsWorker(symbol) || ts.Debug.fail("Read type of accessor must always produce a type")); + } + function getTypeOfSetAccessor(symbol) { + var links = getSymbolLinks(symbol); + return links.writeType || (links.writeType = getTypeOfAccessorsWorker(symbol, /*writing*/ true)); } - function getTypeOfAccessorsWorker(symbol) { + function getTypeOfAccessorsWorker(symbol, writing) { + if (writing === void 0) { writing = false; } if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } - var type = resolveTypeOfAccessors(symbol); + var type = resolveTypeOfAccessors(symbol, writing); if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter = ts.getDeclarationOfKind(symbol, 167 /* GetAccessor */); + var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); error(getter, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } return type; } - function resolveTypeOfAccessors(symbol) { - var getter = ts.getDeclarationOfKind(symbol, 167 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 168 /* SetAccessor */); + function resolveTypeOfAccessors(symbol, writing) { + if (writing === void 0) { writing = false; } + var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); + // For write operations, prioritize type annotations on the setter + if (writing && setterType) { + return instantiateTypeIfNeeded(setterType, symbol); + } + // Else defer to the getter type if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { - return jsDocType; + return instantiateTypeIfNeeded(jsDocType, symbol); } } - // First try to see if the user specified a return type on the get-accessor. - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - return getterReturnType; + // Try to see if the user specified a return type on the get-accessor. + var getterType = getAnnotatedAccessorType(getter); + if (getterType) { + return instantiateTypeIfNeeded(getterType, symbol); } - else { - // If the user didn't specify a return type, try to use the set-accessor's parameter type. - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - return setterParameterType; + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + if (setterType) { + return setterType; + } + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + var returnTypeFromBody = getReturnTypeFromBody(getter); + return instantiateTypeIfNeeded(returnTypeFromBody, symbol); + } + // Otherwise, fall back to 'any'. + if (setter) { + if (!isPrivateWithinAmbient(setter)) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); } - else { - // If there are no specified types, try to infer it from the body of the get accessor if it exists. - if (getter && getter.body) { - return getReturnTypeFromBody(getter); - } - // Otherwise, fall back to 'any'. - else { - if (setter) { - if (!isPrivateWithinAmbient(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 exist a getter as we are current checking either setter or getter in this function"); - if (!isPrivateWithinAmbient(getter)) { - errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } - } - return anyType; - } + return anyType; + } + else if (getter) { + ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } + return anyType; + } + return undefined; + function instantiateTypeIfNeeded(type, symbol) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + var links = getSymbolLinks(symbol); + return instantiateType(type, links.mapper); + } + return type; } } function getBaseTypeVariableOfClass(symbol) { @@ -51706,9 +53068,9 @@ var ts; if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration && (declaration.kind === 216 /* BinaryExpression */ || + else if (declaration && (declaration.kind === 217 /* BinaryExpression */ || ts.isAccessExpression(declaration) && - declaration.parent.kind === 216 /* BinaryExpression */)) { + declaration.parent.kind === 217 /* BinaryExpression */)) { return getWidenedTypeForAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { @@ -51742,14 +53104,16 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); + var exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(getDeclarationOfAliasSymbol(symbol), /*dontResolveAlias*/ true); // It only makes sense to get the type of a value symbol. If the result of resolving // the alias is not a value, then it has no type. To get the type associated with a // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 111551 /* Value */ - ? getTypeOfSymbol(targetSymbol) - : errorType; + links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) + : isDuplicatedCommonJSExport(symbol.declarations) ? autoType + : targetSymbol.flags & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) + : errorType; } return links.type; } @@ -51775,7 +53139,7 @@ var ts; return errorType; } // Check if variable has initializer that circularly references the variable itself - if (noImplicitAny && (declaration.kind !== 160 /* Parameter */ || declaration.initializer)) { + if (noImplicitAny && (declaration.kind !== 161 /* Parameter */ || declaration.initializer)) { error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); } // Circularities could also result from parameters in function expressions that end up @@ -51792,6 +53156,15 @@ var ts; } return links.type; } + function getSetAccessorTypeOfSymbol(symbol) { + if (symbol.flags & 98304 /* Accessor */) { + var type = getTypeOfSetAccessor(symbol); + if (type) { + return type; + } + } + return getTypeOfSymbol(symbol); + } function getTypeOfSymbol(symbol) { var checkFlags = ts.getCheckFlags(symbol); if (checkFlags & 65536 /* DeferredType */) { @@ -51874,66 +53247,72 @@ var ts; return undefined; } switch (node.kind) { - case 232 /* VariableStatement */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 164 /* MethodSignature */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 308 /* JSDocFunctionType */: - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 254 /* TypeAliasDeclaration */: - case 330 /* JSDocTemplateTag */: - case 331 /* JSDocTypedefTag */: - case 325 /* JSDocEnumTag */: - case 324 /* JSDocCallbackTag */: - case 190 /* MappedType */: - case 184 /* ConditionalType */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 165 /* MethodSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 309 /* JSDocFunctionType */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 255 /* TypeAliasDeclaration */: + case 334 /* JSDocTemplateTag */: + case 335 /* JSDocTypedefTag */: + case 329 /* JSDocEnumTag */: + case 328 /* JSDocCallbackTag */: + case 191 /* MappedType */: + case 185 /* ConditionalType */: { var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 190 /* MappedType */) { + if (node.kind === 191 /* MappedType */) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } - else if (node.kind === 184 /* ConditionalType */) { + else if (node.kind === 185 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } - else if (node.kind === 232 /* VariableStatement */ && !ts.isInJSFile(node)) { - break; - } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && - (node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */ || node.kind === 253 /* InterfaceDeclaration */ || isJSConstructor(node)) && + (node.kind === 253 /* ClassDeclaration */ || node.kind === 222 /* ClassExpression */ || node.kind === 254 /* InterfaceDeclaration */ || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; - case 326 /* JSDocParameterTag */: + } + case 330 /* JSDocParameterTag */: var paramSymbol = ts.getParameterSymbolFromJSDoc(node); if (paramSymbol) { node = paramSymbol.valueDeclaration; } break; + case 312 /* JSDocComment */: { + var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + return node.tags + ? appendTypeParameters(outerTypeParameters, ts.flatMap(node.tags, function (t) { return ts.isJSDocTemplateTag(t) ? t.typeParameters : undefined; })) + : outerTypeParameters; + } } } } // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 253 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 254 /* InterfaceDeclaration */); ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, // interface, or type alias. function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + if (!symbol.declarations) { + return; + } var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 253 /* InterfaceDeclaration */ || - node.kind === 252 /* ClassDeclaration */ || - node.kind === 221 /* ClassExpression */ || + if (node.kind === 254 /* InterfaceDeclaration */ || + node.kind === 253 /* ClassDeclaration */ || + node.kind === 222 /* ClassExpression */ || isJSConstructor(node) || ts.isTypeAlias(node)) { var declaration = node; @@ -52027,7 +53406,9 @@ var ts; ctorReturn = getReturnTypeOfSignature(ctorSig[0]); } } - ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + if (baseConstructorType.symbol.declarations) { + ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } } return type.resolvedBaseConstructorType = errorType; } @@ -52037,20 +53418,22 @@ var ts; } function getImplementsTypes(type) { var resolvedImplementsTypes = ts.emptyArray; - for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration); - if (!implementsTypeNodes) - continue; - for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) { - var node = implementsTypeNodes_1[_b]; - var implementsType = getTypeFromTypeNode(node); - if (implementsType !== errorType) { - if (resolvedImplementsTypes === ts.emptyArray) { - resolvedImplementsTypes = [implementsType]; - } - else { - resolvedImplementsTypes.push(implementsType); + if (type.symbol.declarations) { + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration); + if (!implementsTypeNodes) + continue; + for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) { + var node = implementsTypeNodes_1[_b]; + var implementsType = getTypeFromTypeNode(node); + if (implementsType !== errorType) { + if (resolvedImplementsTypes === ts.emptyArray) { + resolvedImplementsTypes = [implementsType]; + } + else { + resolvedImplementsTypes.push(implementsType); + } } } } @@ -52077,10 +53460,10 @@ var ts; else { ts.Debug.fail("type must be class or interface"); } - if (!popTypeResolution()) { + if (!popTypeResolution() && type.symbol.declarations) { for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 252 /* ClassDeclaration */ || declaration.kind === 253 /* InterfaceDeclaration */) { + if (declaration.kind === 253 /* ClassDeclaration */ || declaration.kind === 254 /* InterfaceDeclaration */) { reportCircularBaseType(declaration, type); } } @@ -52173,29 +53556,31 @@ var ts; } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; - for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 253 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { - for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { - var node = _c[_b]; - var baseType = getReducedType(getTypeFromTypeNode(node)); - if (baseType !== errorType) { - if (isValidBaseType(baseType)) { - if (type !== baseType && !hasBaseType(baseType, type)) { - if (type.resolvedBaseTypes === ts.emptyArray) { - type.resolvedBaseTypes = [baseType]; + if (type.symbol.declarations) { + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 254 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { + var node = _c[_b]; + var baseType = getReducedType(getTypeFromTypeNode(node)); + if (baseType !== errorType) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } } else { - type.resolvedBaseTypes.push(baseType); + reportCircularBaseType(declaration, type); } } else { - reportCircularBaseType(declaration, type); + error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } - else { - error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); - } } } } @@ -52209,9 +53594,12 @@ var ts; * and if none of the base interfaces have a "this" type. */ function isThislessInterface(symbol) { + if (!symbol.declarations) { + return true; + } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 253 /* InterfaceDeclaration */) { + if (declaration.kind === 254 /* InterfaceDeclaration */) { if (declaration.flags & 128 /* ContainsThis */) { return false; } @@ -52236,7 +53624,7 @@ var ts; var originalLinks = links; if (!links.declaredType) { var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */; - var merged = mergeJSSymbols(symbol, getAssignedClassSymbol(symbol.valueDeclaration)); + var merged = mergeJSSymbols(symbol, symbol.valueDeclaration && getAssignedClassSymbol(symbol.valueDeclaration)); if (merged) { // note:we overwrite links because we just cloned the symbol symbol = links = merged; @@ -52266,6 +53654,7 @@ var ts; return links.declaredType; } function getDeclaredTypeOfTypeAlias(symbol) { + var _a; var links = getSymbolLinks(symbol); if (!links.declaredType) { // Note that we use the links object as the target here because the symbol object is used as the unique @@ -52273,7 +53662,7 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return errorType; } - var declaration = ts.Debug.checkDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found"); + var declaration = ts.Debug.checkDefined((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias), "Type alias symbol with no valid declaration found"); var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; @@ -52299,7 +53688,7 @@ var ts; if (ts.isStringLiteralLike(expr)) { return true; } - else if (expr.kind === 216 /* BinaryExpression */) { + else if (expr.kind === 217 /* BinaryExpression */) { return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); } return false; @@ -52314,12 +53703,12 @@ var ts; case 8 /* NumericLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: return true; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return expr.operator === 40 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; case 78 /* Identifier */: return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return isStringConcatExpression(expr); default: return false; @@ -52331,16 +53720,18 @@ var ts; return links.enumKind; } var hasNonLiteralMember = false; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 255 /* EnumDeclaration */) { - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - if (member.initializer && ts.isStringLiteralLike(member.initializer)) { - return links.enumKind = 1 /* Literal */; - } - if (!isLiteralEnumMember(member)) { - hasNonLiteralMember = true; + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 256 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + if (member.initializer && ts.isStringLiteralLike(member.initializer)) { + return links.enumKind = 1 /* Literal */; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; + } } } } @@ -52358,15 +53749,17 @@ var ts; if (getEnumKind(symbol) === 1 /* Literal */) { enumCount++; var memberTypeList = []; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 255 /* EnumDeclaration */) { - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var value = getEnumMemberValue(member); - var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member))); - getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 256 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var value = getEnumMemberValue(member); + var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member))); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + } } } } @@ -52443,11 +53836,11 @@ var ts; case 113 /* VoidKeyword */: case 150 /* UndefinedKeyword */: case 141 /* NeverKeyword */: - case 191 /* LiteralType */: + case 192 /* LiteralType */: return true; - case 178 /* ArrayType */: + case 179 /* ArrayType */: return isThislessType(node.elementType); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; @@ -52473,7 +53866,7 @@ var ts; function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - return (node.kind === 166 /* Constructor */ || (!!returnType && isThislessType(returnType))) && + return (node.kind === 167 /* Constructor */ || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } @@ -52489,14 +53882,14 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return isThislessVariableLikeDeclaration(declaration); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return isThislessFunctionLikeDeclaration(declaration); } } @@ -52522,7 +53915,7 @@ var ts; } } function isStaticPrivateIdentifierProperty(s) { - return !!s.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(s.valueDeclaration) && ts.hasSyntacticModifier(s.valueDeclaration, 32 /* Static */); + return !!s.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(s.valueDeclaration) && ts.hasSyntacticModifier(s.valueDeclaration, 32 /* Static */); } function resolveDeclaredMembers(type) { if (!type.declaredProperties) { @@ -52574,10 +53967,10 @@ var ts; return !!name && isLateBindableName(name); } /** - * Indicates whether a declaration has a dynamic name that cannot be late-bound. + * Indicates whether a declaration has an early-bound name or a dynamic name that can be late-bound. */ - function hasNonBindableDynamicName(node) { - return ts.hasDynamicName(node) && !hasLateBindableName(node); + function hasBindableName(node) { + return !ts.hasDynamicName(node) || hasLateBindableName(node); } /** * Indicates whether a declaration name is a dynamic name that cannot be late-bound. @@ -52847,7 +54240,8 @@ var ts; sig.resolvedMinArgumentCount = undefined; sig.target = undefined; sig.mapper = undefined; - sig.unionSignatures = undefined; + sig.compositeSignatures = undefined; + sig.compositeKind = undefined; return sig; } function cloneSignature(sig) { @@ -52855,12 +54249,14 @@ var ts; /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 39 /* PropagatingFlags */); result.target = sig.target; result.mapper = sig.mapper; - result.unionSignatures = sig.unionSignatures; + result.compositeSignatures = sig.compositeSignatures; + result.compositeKind = sig.compositeKind; return result; } function createUnionSignature(signature, unionSignatures) { var result = cloneSignature(signature); - result.unionSignatures = unionSignatures; + result.compositeSignatures = unionSignatures; + result.compositeKind = 1048576 /* Union */; result.target = undefined; result.mapper = undefined; return result; @@ -53019,7 +54415,7 @@ var ts; if (signatures !== masterList) { var signature_1 = signatures[0]; ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); - results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters && !compareTypeParametersIdentical(signature_1.typeParameters, s.typeParameters); }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); }); + results = !!signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters && !compareTypeParametersIdentical(signature_1.typeParameters, s.typeParameters); }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); }); if (!results) { return "break"; } @@ -53036,9 +54432,12 @@ var ts; return result || ts.emptyArray; } function compareTypeParametersIdentical(sourceParams, targetParams) { - if (sourceParams.length !== targetParams.length) { + if (ts.length(sourceParams) !== ts.length(targetParams)) { return false; } + if (!sourceParams || !targetParams) { + return true; + } var mapper = createTypeMapper(targetParams, sourceParams); for (var i = 0; i < sourceParams.length; i++) { var source = sourceParams[i]; @@ -53120,9 +54519,10 @@ var ts; var result = createSignature(declaration, typeParams, thisParam, params, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 39 /* PropagatingFlags */); - result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); + result.compositeKind = 1048576 /* Union */; + result.compositeSignatures = ts.concatenate(left.compositeKind !== 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); if (paramMapper) { - result.mapper = left.mapper && left.unionSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; + result.mapper = left.compositeKind !== 2097152 /* Intersection */ && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; } return result; } @@ -53255,6 +54655,7 @@ var ts; // Combinations of function, class, enum and module var members = emptySymbols; var stringIndexInfo = void 0; + var numberIndexInfo = void 0; if (symbol.exports) { members = getExportsOfSymbol(symbol); if (symbol === globalThisSymbol) { @@ -53267,20 +54668,31 @@ var ts; members = varsOnly_1; } } + var baseConstructorIndexInfo = void 0; setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) { - members = ts.createSymbolTable(getNamedMembers(members)); + members = ts.createSymbolTable(getNamedOrIndexSignatureMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } else if (baseConstructorType === anyType) { - stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + baseConstructorIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + } + } + var indexSymbol = getIndexSymbolFromSymbolTable(members); + if (indexSymbol) { + stringIndexInfo = getIndexInfoOfIndexSymbol(indexSymbol, 0 /* String */); + numberIndexInfo = getIndexInfoOfIndexSymbol(indexSymbol, 1 /* Number */); + } + else { + stringIndexInfo = baseConstructorIndexInfo; + if (symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ || + ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); }))) { + numberIndexInfo = enumNumberIndexInfo; } } - var numberIndexInfo = symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ || - ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); })) ? enumNumberIndexInfo : undefined; setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); // We resolve the members before computing the signatures because a signature may use // typeof with a qualified name expression that circularly references the type we are @@ -53305,6 +54717,18 @@ var ts; } } } + function replaceIndexedAccess(instantiable, type, replacement) { + // map type.indexType to 0 + // map type.objectType to `[TReplacement]` + // thus making the indexed access `[TReplacement][0]` or `TReplacement` + return instantiateType(instantiable, createTypeMapper([type.indexType, type.objectType], [getLiteralType(0), createTupleType([replacement])])); + } + function getIndexInfoOfIndexSymbol(indexSymbol, indexKind) { + var declaration = getIndexDeclarationOfIndexSymbol(indexSymbol, indexKind); + if (!declaration) + return undefined; + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasEffectiveModifier(declaration, 64 /* Readonly */), declaration); + } function resolveReverseMappedTypeMembers(type) { var indexInfo = getIndexInfoOfType(type.source, 0 /* String */); var modifiers = getMappedTypeModifiers(type.mappedType); @@ -53319,8 +54743,21 @@ var ts; inferredProp.declarations = prop.declarations; inferredProp.nameType = getSymbolLinks(prop).nameType; inferredProp.propertyType = getTypeOfSymbol(prop); - inferredProp.mappedType = type.mappedType; - inferredProp.constraintType = type.constraintType; + if (type.constraintType.type.flags & 8388608 /* IndexedAccess */ + && type.constraintType.type.objectType.flags & 262144 /* TypeParameter */ + && type.constraintType.type.indexType.flags & 262144 /* TypeParameter */) { + // A reverse mapping of `{[K in keyof T[K_1]]: T[K_1]}` is the same as that of `{[K in keyof T]: T}`, since all we care about is + // inferring to the "type parameter" (or indexed access) shared by the constraint and template. So, to reduce the number of + // type identities produced, we simplify such indexed access occurences + var newTypeParam = type.constraintType.type.objectType; + var newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type, newTypeParam); + inferredProp.mappedType = newMappedType; + inferredProp.constraintType = getIndexType(newTypeParam); + } + else { + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + } members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -53482,7 +54919,7 @@ var ts; } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 - return constraintDeclaration.kind === 188 /* TypeOperator */ && + return constraintDeclaration.kind === 189 /* TypeOperator */ && constraintDeclaration.operator === 138 /* KeyOfKeyword */; } function getModifiersTypeFromMappedType(type) { @@ -53534,7 +54971,7 @@ var ts; else if (type.objectFlags & 3 /* ClassOrInterface */) { resolveClassOrInterfaceMembers(type); } - else if (type.objectFlags & 2048 /* ReverseMapped */) { + else if (type.objectFlags & 1024 /* ReverseMapped */) { resolveReverseMappedTypeMembers(type); } else if (type.objectFlags & 16 /* Anonymous */) { @@ -53818,12 +55255,22 @@ var ts; if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; + var different = false; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type_3 = types_8[_i]; var baseType = getBaseConstraint(type_3); if (baseType) { + if (baseType !== type_3) { + different = true; + } baseTypes.push(baseType); } + else { + different = true; + } + } + if (!different) { + return t; } return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : @@ -53943,6 +55390,7 @@ var ts; return getReducedType(getApparentType(getReducedType(type))); } function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) { + var _a, _b; var singleProp; var propSet; var indexTypes; @@ -53951,8 +55399,9 @@ var ts; var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var current = _a[_i]; + var mergedInstantiations = false; + for (var _i = 0, _c = containingType.types; _i < _c.length; _i++) { + var current = _c[_i]; var type = getApparentType(current); if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); @@ -53968,13 +55417,25 @@ var ts; singleProp = prop; } else if (prop !== singleProp) { - if (!propSet) { - propSet = new ts.Map(); - propSet.set(getSymbolId(singleProp), singleProp); + var isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp); + // If the symbols are instances of one another with identical types - consider the symbols + // equivalent and just use the first one, which thus allows us to avoid eliding private + // members when intersecting a (this-)instantiations of a class with it's raw base or another instance + if (isInstantiation && compareProperties(singleProp, prop, function (a, b) { return a === b ? -1 /* True */ : 0 /* False */; }) === -1 /* True */) { + // If we merged instantiations of a generic type, we replicate the symbol parent resetting behavior we used + // to do when we recorded multiple distinct symbols so that we still get, eg, `Array.length` printed + // back and not `Array.length` when we're looking at a `.length` access on a `string[] | number[]` + mergedInstantiations = !!singleProp.parent && !!ts.length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent)); } - var id = getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + else { + if (!propSet) { + propSet = new ts.Map(); + propSet.set(getSymbolId(singleProp), singleProp); + } + var id = getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | @@ -53992,7 +55453,7 @@ var ts; checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0); indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } - else if (isObjectLiteralType(type)) { + else if (isObjectLiteralType(type) && !(ts.getObjectFlags(type) & 4194304 /* ContainsSpread */)) { checkFlags |= 32 /* WritePartial */; indexTypes = ts.append(indexTypes, undefinedType); } @@ -54008,7 +55469,19 @@ var ts; return undefined; } if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { - return singleProp; + if (mergedInstantiations) { + // No symbol from a union/intersection should have a `.parent` set (since unions/intersections don't act as symbol parents) + // Unless that parent is "reconstituted" from the "first value declaration" on the symbol (which is likely different than its instantiated parent!) + // They also have a `.containingType` set, which affects some services endpoints behavior, like `getRootSymbol` + var clone_1 = createSymbolWithType(singleProp, singleProp.type); + clone_1.parent = (_b = (_a = singleProp.valueDeclaration) === null || _a === void 0 ? void 0 : _a.symbol) === null || _b === void 0 ? void 0 : _b.parent; + clone_1.containingType = containingType; + clone_1.mapper = singleProp.mapper; + return clone_1; + } + else { + return singleProp; + } } var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; @@ -54017,8 +55490,8 @@ var ts; var propTypes = []; var firstValueDeclaration; var hasNonUniformValueDeclaration = false; - for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { - var prop = props_1[_b]; + for (var _d = 0, props_1 = props; _d < props_1.length; _d++) { + var prop = props_1[_d]; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } @@ -54095,15 +55568,15 @@ var ts; * no constituent property has type 'never', but the intersection of the constituent property types is 'never'. */ function getReducedType(type) { - if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) { + if (type.flags & 1048576 /* Union */ && type.objectFlags & 67108864 /* ContainsIntersections */) { return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); } else if (type.flags & 2097152 /* Intersection */) { - if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { - type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | - (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0); + if (!(type.objectFlags & 67108864 /* IsNeverIntersectionComputed */)) { + type.objectFlags |= 67108864 /* IsNeverIntersectionComputed */ | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 134217728 /* IsNeverIntersection */ : 0); } - return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; + return type.objectFlags & 134217728 /* IsNeverIntersection */ ? neverType : type; } return type; } @@ -54133,7 +55606,7 @@ var ts; return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */); } function elaborateNeverIntersection(errorInfo, type) { - if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) { + if (type.flags & 2097152 /* Intersection */ && ts.getObjectFlags(type) & 134217728 /* IsNeverIntersection */) { var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); if (neverProp) { return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(neverProp)); @@ -54220,7 +55693,8 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var prop = _a[_i]; if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { - propTypes.push(getTypeOfSymbol(prop)); + var propType = getTypeOfSymbol(prop); + propTypes.push(prop.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType); } } if (kind === 0 /* String */) { @@ -54254,10 +55728,10 @@ var ts; function isJSDocOptionalParameter(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 === 307 /* JSDocOptionalType */ + node.type && node.type.kind === 308 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 307 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 308 /* JSDocOptionalType */; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -54289,12 +55763,15 @@ var ts; } return false; } + function isOptionalPropertyDeclaration(node) { + return ts.isPropertyDeclaration(node) && node.questionToken; + } function isOptionalJSDocPropertyLikeTag(node) { if (!ts.isJSDocPropertyLikeTag(node)) { return false; } var isBracketed = node.isBracketed, typeExpression = node.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 307 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 308 /* JSDocOptionalType */; } function createTypePredicate(kind, parameterName, parameterIndex, type) { return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; @@ -54376,7 +55853,7 @@ var ts; else { parameters.push(paramSymbol); } - if (type && type.kind === 191 /* LiteralType */) { + if (type && type.kind === 192 /* LiteralType */) { flags |= 2 /* HasLiteralTypes */; } // Record a new minimum argument count if this is not an optional parameter @@ -54389,16 +55866,16 @@ var ts; } } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 167 /* GetAccessor */ || declaration.kind === 168 /* SetAccessor */) && - !hasNonBindableDynamicName(declaration) && + if ((declaration.kind === 168 /* GetAccessor */ || declaration.kind === 169 /* SetAccessor */) && + hasBindableName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; + var otherKind = declaration.kind === 168 /* GetAccessor */ ? 169 /* SetAccessor */ : 168 /* GetAccessor */; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 166 /* Constructor */ ? + var classType = declaration.kind === 167 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); @@ -54443,8 +55920,7 @@ var ts; if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node))) return undefined; var typeTag = ts.getJSDocTypeTag(node); - var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); - return signature && getErasedSignature(signature); + return (typeTag === null || typeTag === void 0 ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); } function getReturnTypeOfTypeTag(node) { var signature = getSignatureOfTypeTag(node); @@ -54467,14 +55943,14 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node.escapedText === argumentsSymbol.escapedName && getResolvedSymbol(node) === argumentsSymbol; - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - return node.name.kind === 158 /* ComputedPropertyName */ + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return node.name.kind === 159 /* ComputedPropertyName */ && traverse(node.name); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return traverse(node.expression); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); @@ -54482,7 +55958,7 @@ var ts; } } function getSignaturesOfSymbol(symbol) { - if (!symbol) + if (!symbol || !symbol.declarations) return ts.emptyArray; var result = []; for (var i = 0; i < symbol.declarations.length; i++) { @@ -54523,8 +55999,8 @@ var ts; var targetTypePredicate = getTypePredicateOfSignature(signature.target); signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; } - else if (signature.unionSignatures) { - signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + else if (signature.compositeSignatures) { + signature.resolvedTypePredicate = getUnionOrIntersectionTypePredicate(signature.compositeSignatures, signature.compositeKind) || noTypePredicate; } else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); @@ -54546,17 +56022,20 @@ var ts; function createTypePredicateFromTypePredicateNode(node, signature) { var parameterName = node.parameterName; var type = node.type && getTypeFromTypeNode(node.type); - return parameterName.kind === 187 /* ThisType */ ? + return parameterName.kind === 188 /* ThisType */ ? createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) : createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type); } + function getUnionOrIntersectionType(types, kind, unionReduction) { + return kind !== 2097152 /* Intersection */ ? getUnionType(types, unionReduction) : getIntersectionType(types); + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { return errorType; } var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : - signature.unionSignatures ? instantiateType(getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */), signature.mapper) : + signature.compositeSignatures ? instantiateType(getUnionOrIntersectionType(ts.map(signature.compositeSignatures, getReturnTypeOfSignature), signature.compositeKind, 2 /* Subtype */), signature.mapper) : getReturnTypeFromAnnotation(signature.declaration) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (signature.flags & 8 /* IsInnerCallChain */) { @@ -54589,7 +56068,7 @@ var ts; return signature.resolvedReturnType; } function getReturnTypeFromAnnotation(declaration) { - if (declaration.kind === 166 /* Constructor */) { + if (declaration.kind === 167 /* Constructor */) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); } if (ts.isJSDocConstructSignature(declaration)) { @@ -54599,12 +56078,12 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 167 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + if (declaration.kind === 168 /* GetAccessor */ && hasBindableName(declaration)) { var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 168 /* SetAccessor */); + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 169 /* SetAccessor */); var setterType = getAnnotatedAccessorType(setter); if (setterType) { return setterType; @@ -54681,9 +56160,20 @@ var ts; function getBaseSignature(signature) { var typeParameters = signature.typeParameters; if (typeParameters) { - var typeEraser_1 = createTypeEraser(typeParameters); - var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || unknownType; }); - return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); + if (signature.baseSignatureCache) { + return signature.baseSignatureCache; + } + var typeEraser = createTypeEraser(typeParameters); + var baseConstraintMapper_1 = createTypeMapper(typeParameters, ts.map(typeParameters, function (tp) { return getConstraintOfTypeParameter(tp) || unknownType; })); + var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(tp, baseConstraintMapper_1) || unknownType; }); + // Run N type params thru the immediate constraint mapper up to N times + // This way any noncircular interdependent type parameters are definitely resolved to their external dependencies + for (var i = 0; i < typeParameters.length - 1; i++) { + baseConstraints = instantiateTypes(baseConstraints, baseConstraintMapper_1); + } + // and then apply a type eraser to remove any remaining circularly dependent type parameters + baseConstraints = instantiateTypes(baseConstraints, typeEraser); + return signature.baseSignatureCache = instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); } return signature; } @@ -54694,7 +56184,7 @@ var ts; // will result in a different declaration kind. if (!signature.isolatedSignatureType) { var kind = signature.declaration ? signature.declaration.kind : 0 /* Unknown */; - var isConstructor = kind === 166 /* Constructor */ || kind === 170 /* ConstructSignature */ || kind === 175 /* ConstructorType */; + var isConstructor = kind === 167 /* Constructor */ || kind === 171 /* ConstructSignature */ || kind === 176 /* ConstructorType */; var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -54705,12 +56195,22 @@ var ts; return signature.isolatedSignatureType; } function getIndexSymbol(symbol) { - return symbol.members.get("__index" /* Index */); + return symbol.members ? getIndexSymbolFromSymbolTable(symbol.members) : undefined; + } + function getIndexSymbolFromSymbolTable(symbolTable) { + return symbolTable.get("__index" /* Index */); } function getIndexDeclarationOfSymbol(symbol, kind) { + var indexSymbol = symbol && getIndexSymbol(symbol); + return indexSymbol && getIndexDeclarationOfIndexSymbol(indexSymbol, kind); + } + function getIndexDeclarationOfSymbolTable(symbolTable, kind) { + var indexSymbol = symbolTable && getIndexSymbolFromSymbolTable(symbolTable); + return indexSymbol && getIndexDeclarationOfIndexSymbol(indexSymbol, kind); + } + function getIndexDeclarationOfIndexSymbol(indexSymbol, kind) { var syntaxKind = kind === 1 /* Number */ ? 144 /* NumberKeyword */ : 147 /* StringKeyword */; - var indexSymbol = getIndexSymbol(symbol); - if (indexSymbol) { + if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; var node = ts.cast(decl, ts.isIndexSignatureDeclaration); @@ -54738,17 +56238,18 @@ var ts; return ts.mapDefined(ts.filter(type.symbol && type.symbol.declarations, ts.isTypeParameterDeclaration), ts.getEffectiveConstraintOfTypeParameter)[0]; } function getInferredTypeParameterConstraint(typeParameter) { + var _a; var inferences; - if (typeParameter.symbol) { - for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.parent.kind === 185 /* InferType */) { + if ((_a = typeParameter.symbol) === null || _a === void 0 ? void 0 : _a.declarations) { + for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (declaration.parent.kind === 186 /* InferType */) { // When an 'infer T' declaration is immediately contained in a type reference node // (such as 'Foo'), T's constraint is inferred from the constraint of the // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are // present, we form an intersection of the inferred constraint types. - var _b = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _c = _b[0], childTypeParameter = _c === void 0 ? declaration.parent : _c, grandParent = _b[1]; - if (grandParent.kind === 173 /* TypeReference */) { + var _c = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _d = _c[0], childTypeParameter = _d === void 0 ? declaration.parent : _d, grandParent = _c[1]; + if (grandParent.kind === 174 /* TypeReference */) { var typeReference = grandParent; var typeParameters = getTypeParametersForTypeReference(typeReference); if (typeParameters) { @@ -54773,21 +56274,32 @@ var ts; } // When an 'infer T' declaration is immediately contained in a rest parameter declaration, a rest type // or a named rest tuple element, we infer an 'unknown[]' constraint. - else if (grandParent.kind === 160 /* Parameter */ && grandParent.dotDotDotToken || - grandParent.kind === 181 /* RestType */ || - grandParent.kind === 192 /* NamedTupleMember */ && grandParent.dotDotDotToken) { + else if (grandParent.kind === 161 /* Parameter */ && grandParent.dotDotDotToken || + grandParent.kind === 182 /* RestType */ || + grandParent.kind === 193 /* NamedTupleMember */ && grandParent.dotDotDotToken) { inferences = ts.append(inferences, createArrayType(unknownType)); } // When an 'infer T' declaration is immediately contained in a string template type, we infer a 'string' // constraint. - else if (grandParent.kind === 194 /* TemplateLiteralTypeSpan */) { + else if (grandParent.kind === 195 /* TemplateLiteralTypeSpan */) { inferences = ts.append(inferences, stringType); } // When an 'infer T' declaration is in the constraint position of a mapped type, we infer a 'keyof any' // constraint. - else if (grandParent.kind === 159 /* TypeParameter */ && grandParent.parent.kind === 190 /* MappedType */) { + else if (grandParent.kind === 160 /* TypeParameter */ && grandParent.parent.kind === 191 /* MappedType */) { inferences = ts.append(inferences, keyofConstraintType); } + // When an 'infer T' declaration is the template of a mapped type, and that mapped type is the extends + // clause of a conditional whose check type is also a mapped type, give it a constraint equal to the template + // of the check type's mapped type + else if (grandParent.kind === 191 /* MappedType */ && grandParent.type && + ts.skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 185 /* ConditionalType */ && + grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 191 /* MappedType */ && + grandParent.parent.checkType.type) { + var checkMappedType_1 = grandParent.parent.checkType; + var nodeType = getTypeFromTypeNode(checkMappedType_1.type); + inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); + } } } } @@ -54810,7 +56322,7 @@ var ts; if (type.flags & 1 /* Any */ && type !== errorType) { // Allow errorType to propegate to keep downstream errors suppressed // use keyofConstraintType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was), // use unknown otherwise - type = constraintDeclaration.parent.parent.kind === 190 /* MappedType */ ? keyofConstraintType : unknownType; + type = constraintDeclaration.parent.parent.kind === 191 /* MappedType */ ? keyofConstraintType : unknownType; } typeParameter.constraint = type; } @@ -54819,7 +56331,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - var tp = ts.getDeclarationOfKind(typeParameter.symbol, 159 /* TypeParameter */); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 160 /* TypeParameter */); var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; return host && getSymbolOfNode(host); } @@ -54846,6 +56358,9 @@ var ts; } return result; } + function getAliasId(aliasSymbol, aliasTypeArguments) { + return aliasSymbol ? "@" + getSymbolId(aliasSymbol) + (aliasTypeArguments ? ":" + getTypeListId(aliasTypeArguments) : "") : ""; + } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type // of an object literal or the anyFunctionType. This is because there are operations in the type checker @@ -54858,7 +56373,7 @@ var ts; result |= ts.getObjectFlags(type); } } - return result & 3670016 /* PropagatingFlags */; + return result & 917504 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -54880,15 +56395,18 @@ var ts; type.resolvedTypeArguments = source.resolvedTypeArguments; return type; } - function createDeferredTypeReference(target, node, mapper) { - var aliasSymbol = getAliasSymbolForTypeNode(node); - var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + function createDeferredTypeReference(target, node, mapper, aliasSymbol, aliasTypeArguments) { + if (!aliasSymbol) { + aliasSymbol = getAliasSymbolForTypeNode(node); + var localAliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + aliasTypeArguments = mapper ? instantiateTypes(localAliasTypeArguments, mapper) : localAliasTypeArguments; + } var type = createObjectType(4 /* Reference */, target.symbol); type.target = target; type.node = node; type.mapper = mapper; type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = mapper ? instantiateTypes(aliasTypeArguments, mapper) : aliasTypeArguments; + type.aliasTypeArguments = aliasTypeArguments; return type; } function getTypeArguments(type) { @@ -54899,8 +56417,8 @@ var ts; } var node = type.node; var typeArguments = !node ? ts.emptyArray : - node.kind === 173 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : - node.kind === 178 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : + node.kind === 174 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : + node.kind === 179 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); if (popTypeResolution()) { type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; @@ -54942,7 +56460,7 @@ var ts; return errorType; } } - if (node.kind === 173 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) { + if (node.kind === 174 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) { return createDeferredTypeReference(type, node, /*mapper*/ undefined); } // In a type reference, the outer type parameters of the referenced class or interface are automatically @@ -54953,17 +56471,17 @@ var ts; } return checkNoTypeArguments(node, symbol) ? type : errorType; } - function getTypeAliasInstantiation(symbol, typeArguments) { + function getTypeAliasInstantiation(symbol, typeArguments, aliasSymbol, aliasTypeArguments) { var type = getDeclaredTypeOfSymbol(symbol); if (type === intrinsicMarkerType && intrinsicTypeKinds.has(symbol.escapedName) && typeArguments && typeArguments.length === 1) { return getStringMappingType(symbol, typeArguments[0]); } var links = getSymbolLinks(symbol); var typeParameters = links.typeParameters; - var id = getTypeListId(typeArguments); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments)); } return instantiation; } @@ -54984,15 +56502,26 @@ var ts; ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return errorType; } - return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node)); + // We refrain from associating a local type alias with an instantiation of a top-level type alias + // because the local alias may end up being referenced in an inferred return type where it is not + // accessible--which in turn may lead to a large structural expansion of the type when generating + // a .d.ts file. See #43622 for an example. + var aliasSymbol = getAliasSymbolForTypeNode(node); + var newAliasSymbol = aliasSymbol && (isLocalTypeAlias(symbol) || !isLocalTypeAlias(aliasSymbol)) ? aliasSymbol : undefined; + return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), newAliasSymbol, getTypeArgumentsForAliasSymbol(newAliasSymbol)); } return checkNoTypeArguments(node, symbol) ? type : errorType; } + function isLocalTypeAlias(symbol) { + var _a; + var declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias); + return !!(declaration && ts.getContainingFunction(declaration)); + } function getTypeReferenceName(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return node.typeName; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. var expr = node.expression; @@ -55048,7 +56577,7 @@ var ts; var valueType = getTypeOfSymbol(symbol); var typeType = valueType; if (symbol.valueDeclaration) { - var isImportTypeWithQualifier = node.kind === 195 /* ImportType */ && node.qualifier; + var isImportTypeWithQualifier = node.kind === 196 /* ImportType */ && node.qualifier; // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL} if (valueType.symbol && valueType.symbol !== symbol && isImportTypeWithQualifier) { typeType = getTypeReferenceType(node, valueType.symbol); @@ -55074,7 +56603,7 @@ var ts; return result; } function isUnaryTupleTypeNode(node) { - return node.kind === 179 /* TupleType */ && node.elements.length === 1; + return node.kind === 180 /* TupleType */ && node.elements.length === 1; } function getImpliedConstraint(type, checkNode, extendsNode) { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elements[0], extendsNode.elements[0]) : @@ -55083,9 +56612,17 @@ var ts; } function getConditionalFlowTypeOfType(type, node) { var constraints; - while (node && !ts.isStatement(node) && node.kind !== 311 /* JSDocComment */) { + var covariant = true; + while (node && !ts.isStatement(node) && node.kind !== 312 /* JSDocComment */) { var parent = node.parent; - if (parent.kind === 184 /* ConditionalType */ && node === parent.trueType) { + // only consider variance flipped by parameter locations - `keyof` types would usually be considered variance inverting, but + // often get used in indexed accesses where they behave sortof invariantly, but our checking is lax + if (parent.kind === 161 /* Parameter */) { + covariant = !covariant; + } + // Always substitute on type parameters, regardless of variance, since even + // in contravariant positions, they may rely on substituted constraints to be valid + if ((covariant || type.flags & 8650752 /* TypeVariable */) && parent.kind === 185 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -55096,7 +56633,7 @@ var ts; return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type; } function isJSDocTypeReference(node) { - return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 173 /* TypeReference */ || node.kind === 195 /* ImportType */); + return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 174 /* TypeReference */ || node.kind === 196 /* ImportType */); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -55206,13 +56743,15 @@ var ts; function getTypeOfGlobalSymbol(symbol, arity) { function getTypeDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { - var declaration = declarations_3[_i]; - switch (declaration.kind) { - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - return declaration; + if (declarations) { + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; + switch (declaration.kind) { + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + return declaration; + } } } } @@ -55256,6 +56795,9 @@ var ts; function getGlobalESSymbolConstructorSymbol(reportErrors) { return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); } + function getGlobalESSymbolConstructorTypeSymbol(reportErrors) { + return deferredGlobalESSymbolConstructorTypeSymbol || (deferredGlobalESSymbolConstructorTypeSymbol = getGlobalTypeSymbol("SymbolConstructor", reportErrors)); + } function getGlobalESSymbolType(reportErrors) { return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType; } @@ -55332,11 +56874,11 @@ var ts; } function getTupleElementFlags(node) { switch (node.kind) { - case 180 /* OptionalType */: + case 181 /* OptionalType */: return 2 /* Optional */; - case 181 /* RestType */: + case 182 /* RestType */: return getRestTypeElementFlags(node); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return node.questionToken ? 2 /* Optional */ : node.dotDotDotToken ? getRestTypeElementFlags(node) : 1 /* Required */; @@ -55354,14 +56896,14 @@ var ts; return readonly ? globalReadonlyArrayType : globalArrayType; } var elementFlags = ts.map(node.elements, getTupleElementFlags); - var missingName = ts.some(node.elements, function (e) { return e.kind !== 192 /* NamedTupleMember */; }); + var missingName = ts.some(node.elements, function (e) { return e.kind !== 193 /* NamedTupleMember */; }); return getTupleTargetType(elementFlags, readonly, /*associatedNames*/ missingName ? undefined : node.elements); } // Return true if the given type reference node is directly aliased or if it needs to be deferred // because it is possibly contained in a circular chain of eagerly resolved types. function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) { - return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 178 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) : - node.kind === 179 /* TupleType */ ? ts.some(node.elements, mayResolveTypeAlias) : + return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 179 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) : + node.kind === 180 /* TupleType */ ? ts.some(node.elements, mayResolveTypeAlias) : hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias)); } // Return true when the given node is transitively contained in type constructs that eagerly @@ -55370,18 +56912,18 @@ var ts; function isResolvedByTypeAlias(node) { var parent = node.parent; switch (parent.kind) { - case 186 /* ParenthesizedType */: - case 192 /* NamedTupleMember */: - case 173 /* TypeReference */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 189 /* IndexedAccessType */: - case 184 /* ConditionalType */: - case 188 /* TypeOperator */: - case 178 /* ArrayType */: - case 179 /* TupleType */: + case 187 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: + case 174 /* TypeReference */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 190 /* IndexedAccessType */: + case 185 /* ConditionalType */: + case 189 /* TypeOperator */: + case 179 /* ArrayType */: + case 180 /* TupleType */: return isResolvedByTypeAlias(parent); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return true; } return false; @@ -55390,28 +56932,28 @@ var ts; // of a type alias. function mayResolveTypeAlias(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node.typeName, 788968 /* Type */).flags & 524288 /* TypeAlias */); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return true; - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return node.operator !== 151 /* UniqueKeyword */ && mayResolveTypeAlias(node.type); - case 186 /* ParenthesizedType */: - case 180 /* OptionalType */: - case 192 /* NamedTupleMember */: - case 307 /* JSDocOptionalType */: - case 305 /* JSDocNullableType */: - case 306 /* JSDocNonNullableType */: - case 301 /* JSDocTypeExpression */: + case 187 /* ParenthesizedType */: + case 181 /* OptionalType */: + case 193 /* NamedTupleMember */: + case 308 /* JSDocOptionalType */: + case 306 /* JSDocNullableType */: + case 307 /* JSDocNonNullableType */: + case 302 /* JSDocTypeExpression */: return mayResolveTypeAlias(node.type); - case 181 /* RestType */: - return node.type.kind !== 178 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType); - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 182 /* RestType */: + return node.type.kind !== 179 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType); + case 183 /* UnionType */: + case 184 /* IntersectionType */: return ts.some(node.types, mayResolveTypeAlias); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) || mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType); } @@ -55424,12 +56966,12 @@ var ts; if (target === emptyGenericType) { links.resolvedType = emptyObjectType; } - else if (!(node.kind === 179 /* TupleType */ && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8 /* Variadic */); })) && isDeferredTypeReferenceNode(node)) { - links.resolvedType = node.kind === 179 /* TupleType */ && node.elements.length === 0 ? target : + else if (!(node.kind === 180 /* TupleType */ && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8 /* Variadic */); })) && isDeferredTypeReferenceNode(node)) { + links.resolvedType = node.kind === 180 /* TupleType */ && node.elements.length === 0 ? target : createDeferredTypeReference(target, node, /*mapper*/ undefined); } else { - var elementTypes = node.kind === 178 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); + var elementTypes = node.kind === 179 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); links.resolvedType = createNormalizedTypeReference(target, elementTypes); } } @@ -55561,8 +57103,15 @@ var ts; addElement(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]); } else if (isTupleType(type)) { + var elements = getTypeArguments(type); + if (elements.length + expandedTypes.length >= 10000) { + error(currentNode, ts.isPartOfTypeNode(currentNode) + ? ts.Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent + : ts.Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent); + return { value: errorType }; + } // Spread variadic elements with tuple types into the resulting tuple. - ts.forEach(getTypeArguments(type), function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); + ts.forEach(elements, function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); } else { // Treat everything else as an array type and create a rest element. @@ -55575,7 +57124,9 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - _loop_13(i); + var state_4 = _loop_13(i); + if (typeof state_4 === "object") + return state_4.value; } // Turn optional elements preceding the last required element into required elements for (var i = 0; i < lastRequiredIndex; i++) { @@ -55664,7 +57215,7 @@ var ts; if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { - if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) + if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */)) includes |= 4194304 /* IncludesNonWideningType */; } else { @@ -55686,67 +57237,76 @@ var ts; } return includes; } - function isSetOfLiteralsFromSameEnum(types) { - var first = types[0]; - if (first.flags & 1024 /* EnumLiteral */) { - var firstEnum = getParentOfSymbol(first.symbol); - for (var i = 1; i < types.length; i++) { - var other = types[i]; - if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { - return false; - } - } - return true; + function removeSubtypes(types, hasObjectTypes) { + var id = getTypeListId(types); + var match = subtypeReductionCache.get(id); + if (match) { + return match; } - return false; - } - function removeSubtypes(types, primitivesOnly) { + // We assume that redundant primitive types have already been removed from the types array and that there + // are no any and unknown types in the array. Thus, the only possible supertypes for primitive types are empty + // object types, and if none of those are present we can exclude primitive types from the subtype check. + var hasEmptyObject = hasObjectTypes && ts.some(types, function (t) { return !!(t.flags & 524288 /* Object */) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t)); }); var len = types.length; - if (len === 0 || isSetOfLiteralsFromSameEnum(types)) { - return true; - } var i = len; var count = 0; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var target = types_11[_i]; - if (source !== target) { - if (count === 100000) { - // After 100000 subtype checks we estimate the remaining amount of work by assuming the - // same ratio of checks per element. If the estimated number of remaining type checks is - // greater than an upper limit we deem the union type too complex to represent. The - // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example - // caps union types at 5000 unique literal types and 1000 unique object types. - var estimatedCount = (count / (len - i)) * len; - if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); - error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); - return false; + if (hasEmptyObject || source.flags & 469499904 /* StructuredOrInstantiable */) { + // Find the first property with a unit type, if any. When constituents have a property by the same name + // but of a different unit type, we can quickly disqualify them from subtype checks. This helps subtype + // reduction of large discriminated union types. + var keyProperty = source.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */) ? + ts.find(getPropertiesOfType(source), function (p) { return isUnitType(getTypeOfSymbol(p)); }) : + undefined; + var keyPropertyType = keyProperty && getRegularTypeOfLiteralType(getTypeOfSymbol(keyProperty)); + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var target = types_11[_i]; + if (source !== target) { + if (count === 100000) { + // After 100000 subtype checks we estimate the remaining amount of work by assuming the + // same ratio of checks per element. If the estimated number of remaining type checks is + // greater than 1M we deem the union type too complex to represent. This for example + // caps union types at 1000 unique object types. + var estimatedCount = (count / (len - i)) * len; + if (estimatedCount > 1000000) { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); + error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); + return undefined; + } + } + count++; + if (keyProperty && target.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */)) { + var t = getTypeOfPropertyOfType(target, keyProperty.escapedName); + if (t && isUnitType(t) && getRegularTypeOfLiteralType(t) !== keyPropertyType) { + continue; + } + } + if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { + ts.orderedRemoveItemAt(types, i); + break; } - } - count++; - if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || - !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || - isTypeDerivedFrom(source, target))) { - ts.orderedRemoveItemAt(types, i); - break; } } } } - return true; + subtypeReductionCache.set(id, types); + return types; } - function removeRedundantLiteralTypes(types, includes) { + function removeRedundantLiteralTypes(types, includes, reduceVoidUndefined) { var i = types.length; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 134217856 /* StringLikeLiteral */ && includes & 4 /* String */ || - t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || - t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || - t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + var flags = t.flags; + var remove = flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + reduceVoidUndefined && flags & 32768 /* Undefined */ && includes & 16384 /* Void */ || isFreshLiteralType(t) && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); @@ -55778,7 +57338,7 @@ var ts; if (t.flags & 1048576 /* Union */) { var origin = t.origin; if (t.aliasSymbol || origin && !(origin.flags & 1048576 /* Union */)) { - namedUnions.push(t); + ts.pushIfUnique(namedUnions, t); } else if (origin && origin.flags & 1048576 /* Union */) { addNamedUnions(namedUnions, origin.types); @@ -55812,20 +57372,17 @@ var ts; if (includes & 3 /* AnyOrUnknown */) { return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; } - switch (unionReduction) { - case 1 /* Literal */: - if (includes & (134220672 /* FreshableLiteral */ | 8192 /* UniqueESSymbol */)) { - removeRedundantLiteralTypes(typeSet, includes); - } - if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { - removeStringLiteralsMatchedByTemplateLiterals(typeSet); - } - break; - case 2 /* Subtype */: - if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) { - return errorType; - } - break; + if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */) || includes & 16384 /* Void */ && includes & 32768 /* Undefined */) { + removeRedundantLiteralTypes(typeSet, includes, !!(unionReduction & 2 /* Subtype */)); + } + if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { + removeStringLiteralsMatchedByTemplateLiterals(typeSet); + } + if (unionReduction === 2 /* Subtype */) { + typeSet = removeSubtypes(typeSet, !!(includes & 524288 /* Object */)); + if (!typeSet) { + return errorType; + } } if (typeSet.length === 0) { return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType : @@ -55860,18 +57417,23 @@ var ts; origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes); } } - var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) | - (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0); + var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | + (includes & 2097152 /* Intersection */ ? 67108864 /* ContainsIntersections */ : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } - function getUnionTypePredicate(signatures) { + function getUnionOrIntersectionTypePredicate(signatures, kind) { var first; var types = []; for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { var sig = signatures_6[_i]; var pred = getTypePredicateOfSignature(sig); if (!pred || pred.kind === 2 /* AssertsThis */ || pred.kind === 3 /* AssertsIdentifier */) { - continue; + if (kind !== 2097152 /* Intersection */) { + continue; + } + else { + return; // intersections demand all members be type predicates for the result to have a predicate + } } if (first) { if (!typePredicateKindsMatch(first, pred)) { @@ -55885,11 +57447,11 @@ var ts; types.push(pred.type); } if (!first) { - // No union signatures had a type predicate. + // No signatures had a type predicate. return undefined; } - var unionType = getUnionType(types); - return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, unionType); + var compositeType = getUnionOrIntersectionType(types, kind); + return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, compositeType); } function typePredicateKindsMatch(a, b) { return a.kind === b.kind && a.parameterIndex === b.parameterIndex; @@ -55914,8 +57476,8 @@ var ts; var typeKey = !origin ? getTypeListId(types) : origin.flags & 1048576 /* Union */ ? "|" + getTypeListId(origin.types) : origin.flags & 2097152 /* Intersection */ ? "&" + getTypeListId(origin.types) : - "#" + origin.type.id; - var id = typeKey + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + "#" + origin.type.id + "|" + getTypeListId(types); // origin type id alone is insufficient, as `keyof x` may resolve to multiple WIP values while `x` is still resolving + var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { type = createUnionType(types, aliasSymbol, aliasTypeArguments, origin); @@ -56041,7 +57603,7 @@ var ts; // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); }); if (index < 0) { return false; } @@ -56050,7 +57612,7 @@ var ts; // the unionTypes array. while (i < types.length) { var t = types[i]; - if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) { + if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -56079,14 +57641,14 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */); + types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */); return true; } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { var result = createType(2097152 /* Intersection */); result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */); result.types = types; - result.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. + result.aliasSymbol = aliasSymbol; result.aliasTypeArguments = aliasTypeArguments; return result; } @@ -56147,7 +57709,7 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } - var id = getTypeListId(typeSet) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeSet) + getAliasId(aliasSymbol, aliasTypeArguments); var result = intersectionTypes.get(id); if (!result) { if (includes & 1048576 /* Union */) { @@ -56190,7 +57752,7 @@ var ts; function checkCrossProductUnion(types) { var size = getCrossProductUnionSize(types); if (size >= 100000) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); return false; } @@ -56240,11 +57802,17 @@ var ts; type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } + function instantiateTypeAsMappedNameType(nameType, type, t) { + return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); + } function getIndexTypeForMappedType(type, noIndexSignatures) { var constraint = filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); }); var nameType = type.declaration.nameType && getTypeFromTypeNode(type.declaration.nameType); + // If the constraint is exclusively string/number/never type(s), we need to pull the property names from the modified type and run them through the `nameType` mapper as well + // since they won't appear in the constraint, due to subtype reducing with the string/number index types + var properties = nameType && everyType(constraint, function (t) { return !!(t.flags & (4 /* String */ | 8 /* Number */ | 131072 /* Never */)); }) && getPropertiesOfType(getApparentType(getModifiersTypeFromMappedType(type))); return nameType ? - mapType(constraint, function (t) { return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); }) : + getUnionType([mapType(constraint, function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); }), mapType(getUnionType(ts.map(properties || ts.emptyArray, function (p) { return getLiteralTypeFromProperty(p, 8576 /* StringOrNumberLiteralOrUnique */); })), function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); })]) : constraint; } // Ordinarily we reduce a keyof M, where M is a mapped type { [P in K as N

]: X }, to simply N. This however presumes @@ -56274,13 +57842,13 @@ var ts; function getLiteralTypeFromProperty(prop, include) { if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { var type = getSymbolLinks(getLateBoundSymbol(prop)).nameType; - if (!type && !ts.isKnownSymbol(prop)) { + if (!type) { if (prop.escapedName === "default" /* Default */) { type = getLiteralType("default"); } else { var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); - type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + type = name && getLiteralTypeFromPropertyName(name) || (!ts.isKnownSymbol(prop) ? getLiteralType(ts.symbolName(prop)) : undefined); } } if (type && type.flags & include) { @@ -56380,7 +57948,6 @@ var ts; var type = templateLiteralTypes.get(id); if (!type) { templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes)); - type.regularType = type; } return type; function addSpans(texts, types) { @@ -56412,10 +57979,8 @@ var ts; return type.flags & 128 /* StringLiteral */ ? type.value : type.flags & 256 /* NumberLiteral */ ? "" + type.value : type.flags & 2048 /* BigIntLiteral */ ? ts.pseudoBigIntToString(type.value) : - type.flags & 512 /* BooleanLiteral */ ? type.intrinsicName : - type.flags & 65536 /* Null */ ? "null" : - type.flags & 32768 /* Undefined */ ? "undefined" : - undefined; + type.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) ? type.intrinsicName : + undefined; } function createTemplateLiteralType(texts, types) { var type = createType(134217728 /* TemplateLiteral */); @@ -56474,7 +58039,7 @@ var ts; if (noImplicitAny) { return false; // Flag is meaningless under `noImplicitAny` mode } - if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + if (ts.getObjectFlags(type) & 8192 /* JSLiteral */) { return true; } if (type.flags & 1048576 /* Union */) { @@ -56484,20 +58049,18 @@ var ts; return ts.some(type.types, isJSLiteralType); } if (type.flags & 465829888 /* Instantiable */) { - return isJSLiteralType(getResolvedBaseConstraint(type)); + var constraint = getResolvedBaseConstraint(type); + return constraint !== type && isJSLiteralType(constraint); } return false; } function getPropertyNameFromIndex(indexType, accessNode) { - var accessExpression = accessNode && accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode : undefined; return isTypeUsableAsPropertyName(indexType) ? getPropertyNameFromType(indexType) : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : - accessNode && ts.isPropertyName(accessNode) ? - // late bound names are handled in the first branch, so here we only need to handle normal names - ts.getPropertyNameForPropertyNameNode(accessNode) : - undefined; + accessNode && ts.isPropertyName(accessNode) ? + // late bound names are handled in the first branch, so here we only need to handle normal names + ts.getPropertyNameForPropertyNameNode(accessNode) : + undefined; } function isUncalledFunctionReference(node, symbol) { if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { @@ -56511,17 +58074,17 @@ var ts; } function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, suppressNoImplicitAnyError, accessNode, accessFlags, noUncheckedIndexedAccessCandidate, reportDeprecated) { var _a; - var accessExpression = accessNode && accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode : undefined; + var accessExpression = accessNode && accessNode.kind === 203 /* ElementAccessExpression */ ? accessNode : undefined; var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode); if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { - if (reportDeprecated && accessNode && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) { + if (reportDeprecated && accessNode && prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) { var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); - errorOrSuggestion(/* isError */ false, deprecatedNode, ts.Diagnostics._0_is_deprecated, propName); + addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName); } if (accessExpression) { - markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 107 /* ThisKeyword */); + markPropertyAsReferenced(prop, accessExpression, isSelfTypeAccess(accessExpression.expression, objectType.symbol)); if (isAssignmentToReadonlyEntity(accessExpression, prop, ts.getAssignmentTargetKind(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); return undefined; @@ -56671,13 +58234,13 @@ var ts; } } function getIndexNodeForAccessExpression(accessNode) { - return accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode.argumentExpression : - accessNode.kind === 189 /* IndexedAccessType */ ? accessNode.indexType : - accessNode.kind === 158 /* ComputedPropertyName */ ? accessNode.expression : + return accessNode.kind === 203 /* ElementAccessExpression */ ? accessNode.argumentExpression : + accessNode.kind === 190 /* IndexedAccessType */ ? accessNode.indexType : + accessNode.kind === 159 /* ComputedPropertyName */ ? accessNode.expression : accessNode; } function isPatternLiteralPlaceholderType(type) { - return templateConstraintType.types.indexOf(type) !== -1 || !!(type.flags & 1 /* Any */); + return !!(type.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 64 /* BigInt */)); } function isPatternLiteralType(type) { return !!(type.flags & 134217728 /* TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType); @@ -56690,6 +58253,13 @@ var ts; } return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) { + type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ | + (isGenericObjectType(type.substitute) || isGenericObjectType(type.baseType) ? 8388608 /* IsGenericObjectType */ : 0); + } + return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); + } return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type) || isGenericTupleType(type); } function isGenericIndexType(type) { @@ -56700,6 +58270,13 @@ var ts; } return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) { + type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ | + (isGenericIndexType(type.substitute) || isGenericIndexType(type.baseType) ? 33554432 /* IsGenericIndexType */ : 0); + } + return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); + } return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) && !isPatternLiteralType(type); } function isThisTypeParameter(type) { @@ -56775,6 +58352,12 @@ var ts; } return type[cache] = type; } + function isConditionalTypeAlwaysTrueDisregardingInferTypes(type) { + var extendsInferParamMapper = type.root.inferTypeParameters && createTypeMapper(type.root.inferTypeParameters, ts.map(type.root.inferTypeParameters, function () { return wildcardType; })); + var checkType = type.checkType; + var extendsType = type.extendsType; + return isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(instantiateType(extendsType, extendsInferParamMapper))); + } function getSimplifiedConditionalType(type, writing) { var checkType = type.checkType; var extendsType = type.extendsType; @@ -56845,14 +58428,14 @@ var ts; // for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved // eagerly using the constraint type of 'this' at the given location. - if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 189 /* IndexedAccessType */ ? + if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 190 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, objectType.target.fixedLength) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, objectType.target.fixedLength)))) { if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; } // Defer the operation by creating an indexed access type. - var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + getAliasId(aliasSymbol, aliasTypeArguments); var type = indexedAccessTypes.get(id); if (!type) { indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined)); @@ -56928,16 +58511,32 @@ var ts; } return type; } - function getConditionalType(root, mapper) { + function isTypicalNondistributiveConditional(root) { + return !root.isDistributive + && root.node.checkType.kind === 180 /* TupleType */ + && ts.length(root.node.checkType.elements) === 1 + && root.node.extendsType.kind === 180 /* TupleType */ + && ts.length(root.node.extendsType.elements) === 1; + } + /** + * We syntactually check for common nondistributive conditional shapes and unwrap them into + * the intended comparison - we do this so we can check if the unwrapped types are generic or + * not and appropriately defer condition calculation + */ + function unwrapNondistributiveConditionalTuple(root, type) { + return isTypicalNondistributiveConditional(root) && isTupleType(type) ? getTypeArguments(type)[0] : type; + } + function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { var result; var extraTypes; // We loop here for an immediately nested conditional type in the false position, effectively treating // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { - var checkType = instantiateType(root.checkType, mapper); + var isUnwrapped = isTypicalNondistributiveConditional(root); + var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); - var extendsType = instantiateType(root.extendsType, mapper); + var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } @@ -56948,21 +58547,24 @@ var ts; // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. - inferTypes(context.inferences, checkType, extendsType, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(context.inferences, checkType, extendsType, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); } - combinedMapper = mergeTypeMappers(mapper, context.mapper); + // It's possible for 'infer T' type paramteters to be given uninstantiated constraints when the + // those type parameters are used in type references (see getInferredTypeParameterConstraint). For + // that reason we need context.mapper to be first in the combined mapper. See #42636 for examples. + combinedMapper = mapper ? combineTypeMappers(context.mapper, mapper) : context.mapper; } // Instantiate the extends type including inferences for 'infer T' type parameters - var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + var inferredExtendsType = combinedMapper ? instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), combinedMapper) : extendsType; // We attempt to resolve the conditional type only when the check and extends types are non-generic if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) { // Return falseType for a definitely false extends check. We check an instantiations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instantiations will be and we can just return the false branch type. - if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { + if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && ((checkType.flags & 1 /* Any */ && !isUnwrapped) || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { // Return union of trueType and falseType for 'any' since it matches anything - if (checkType.flags & 1 /* Any */) { + if (checkType.flags & 1 /* Any */ && !isUnwrapped) { (extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper)); } // If falseType is an immediately nested conditional type that isn't distributive or has an @@ -56991,12 +58593,12 @@ var ts; // Return a deferred type for a check that is neither definitely true nor definitely false result = createType(16777216 /* Conditional */); result.root = root; - result.checkType = checkType; - result.extendsType = extendsType; + result.checkType = instantiateType(root.checkType, mapper); + result.extendsType = instantiateType(root.extendsType, mapper); result.mapper = mapper; result.combinedMapper = combinedMapper; - result.aliasSymbol = root.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 + result.aliasSymbol = aliasSymbol || root.aliasSymbol; + result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 break; } return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result; @@ -57202,7 +58804,7 @@ var ts; } } var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return spread; } } @@ -57308,14 +58910,15 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */ | 4194304 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ function isSpreadableProperty(prop) { - return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) && + var _a; + return !ts.some(prop.declarations, ts.isPrivateIdentifierClassElementDeclaration) && (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || - !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); })); + !((_a = prop.declarations) === null || _a === void 0 ? void 0 : _a.some(function (decl) { return ts.isClassLike(decl.parent); }))); } function getSpreadSymbol(prop, readonly) { var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); @@ -57340,11 +58943,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 134220672 /* FreshableLiteral */) { + if (type.flags & 2944 /* Literal */) { if (!type.freshType) { - var freshType = type.flags & 134217728 /* TemplateLiteral */ ? - createTemplateLiteralType(type.texts, type.types) : - createLiteralType(type.flags, type.value, type.symbol); + var freshType = createLiteralType(type.flags, type.value, type.symbol); freshType.regularType = type; freshType.freshType = freshType; type.freshType = freshType; @@ -57354,12 +58955,12 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 134220672 /* FreshableLiteral */ ? type.regularType : + return type.flags & 2944 /* Literal */ ? type.regularType : type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = mapType(type, getRegularTypeOfLiteralType))) : type; } function isFreshLiteralType(type) { - return !!(type.flags & 134220672 /* FreshableLiteral */) && type.freshType === type; + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -57405,7 +59006,7 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 253 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 254 /* InterfaceDeclaration */)) { if (!ts.hasSyntacticModifier(container, 32 /* Static */) && (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; @@ -57440,17 +59041,17 @@ var ts; } function getArrayElementTypeNode(node) { switch (node.kind) { - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return getArrayElementTypeNode(node.type); - case 179 /* TupleType */: + case 180 /* TupleType */: if (node.elements.length === 1) { node = node.elements[0]; - if (node.kind === 181 /* RestType */ || node.kind === 192 /* NamedTupleMember */ && node.dotDotDotToken) { + if (node.kind === 182 /* RestType */ || node.kind === 193 /* NamedTupleMember */ && node.dotDotDotToken) { return getArrayElementTypeNode(node.type); } } break; - case 178 /* ArrayType */: + case 179 /* ArrayType */: return node.elementType; } return undefined; @@ -57468,8 +59069,8 @@ var ts; function getTypeFromTypeNodeWorker(node) { switch (node.kind) { case 128 /* AnyKeyword */: - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: return anyType; case 152 /* UnknownKeyword */: return unknownType; @@ -57496,70 +59097,70 @@ var ts; return node.flags & 131072 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType; case 136 /* IntrinsicKeyword */: return intrinsicMarkerType; - case 187 /* ThisType */: + case 188 /* ThisType */: case 107 /* ThisKeyword */: // TODO(rbuckton): `ThisKeyword` is no longer a `TypeNode`, but we defensively allow it here because of incorrect casts in the Language Service and because of `isPartOfTypeNode`. return getTypeFromThisTypeNode(node); - case 191 /* LiteralType */: + case 192 /* LiteralType */: return getTypeFromLiteralTypeNode(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return getTypeFromTypeReference(node); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return node.assertsModifier ? voidType : booleanType; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 178 /* ArrayType */: - case 179 /* TupleType */: + case 179 /* ArrayType */: + case 180 /* TupleType */: return getTypeFromArrayOrTupleTypeNode(node); - case 180 /* OptionalType */: + case 181 /* OptionalType */: return getTypeFromOptionalTypeNode(node); - case 182 /* UnionType */: + case 183 /* UnionType */: return getTypeFromUnionTypeNode(node); - case 183 /* IntersectionType */: + case 184 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 305 /* JSDocNullableType */: + case 306 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 307 /* JSDocOptionalType */: + case 308 /* JSDocOptionalType */: return addOptionality(getTypeFromTypeNode(node.type)); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return getTypeFromNamedTupleTypeNode(node); - case 186 /* ParenthesizedType */: - case 306 /* JSDocNonNullableType */: - case 301 /* JSDocTypeExpression */: + case 187 /* ParenthesizedType */: + case 307 /* JSDocNonNullableType */: + case 302 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 181 /* RestType */: + case 182 /* RestType */: return getTypeFromRestTypeNode(node); - case 309 /* JSDocVariadicType */: + case 310 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 308 /* JSDocFunctionType */: - case 313 /* JSDocSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 309 /* JSDocFunctionType */: + case 315 /* JSDocSignature */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return getTypeFromIndexedAccessTypeNode(node); - case 190 /* MappedType */: + case 191 /* MappedType */: return getTypeFromMappedTypeNode(node); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return getTypeFromConditionalTypeNode(node); - case 185 /* InferType */: + case 186 /* InferType */: return getTypeFromInferTypeNode(node); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: return getTypeFromTemplateTypeNode(node); - case 195 /* ImportType */: + case 196 /* ImportType */: return getTypeFromImportTypeNode(node); // This function assumes that an identifier, qualified name, or property access expression is a type expression // Callers should first ensure this by calling `isPartOfTypeNode` // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s. case 78 /* Identifier */: - case 157 /* QualifiedName */: - case 201 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: var symbol = getSymbolAtLocation(node); return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: @@ -57712,7 +59313,7 @@ var ts; } return result; } - function getObjectTypeInstantiation(type, mapper) { + function getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { var declaration = type.objectFlags & 4 /* Reference */ ? type.node : type.symbol.declarations[0]; var links = getNodeLinks(declaration); var target = type.objectFlags & 4 /* Reference */ ? links.resolvedType : @@ -57729,8 +59330,9 @@ var ts; outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } typeParameters = outerTypeParameters || ts.emptyArray; - typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? - ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration); }) : + var allDeclarations_1 = type.objectFlags & 4 /* Reference */ ? [declaration] : type.symbol.declarations; + typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 8192 /* Method */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? + ts.filter(typeParameters, function (tp) { return ts.some(allDeclarations_1, function (d) { return isTypeParameterPossiblyReferenced(tp, d); }); }) : typeParameters; links.outerTypeParameters = typeParameters; } @@ -57740,17 +59342,19 @@ var ts; // instantiation cache key from the type IDs of the type arguments. var combinedMapper_1 = combineTypeMappers(type.mapper, mapper); var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); }); - var id = getTypeListId(typeArguments); + var newAliasSymbol = aliasSymbol || type.aliasSymbol; + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + var id = getTypeListId(typeArguments) + getAliasId(newAliasSymbol, newAliasTypeArguments); if (!target.instantiations) { target.instantiations = new ts.Map(); - target.instantiations.set(getTypeListId(typeParameters), target); + target.instantiations.set(getTypeListId(typeParameters) + getAliasId(target.aliasSymbol, target.aliasTypeArguments), target); } var result = target.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(typeParameters, typeArguments); - result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper) : - target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) : - instantiateAnonymousType(target, newMapper); + result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) : + target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) : + instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments); target.instantiations.set(id, result); } return result; @@ -57758,9 +59362,9 @@ var ts; return type; } function maybeTypeParameterReference(node) { - return !(node.kind === 157 /* QualifiedName */ || - node.parent.kind === 173 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName || - node.parent.kind === 195 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier); + return !(node.kind === 158 /* QualifiedName */ || + node.parent.kind === 174 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName || + node.parent.kind === 196 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier); } function isTypeParameterPossiblyReferenced(tp, node) { // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks @@ -57769,22 +59373,25 @@ var ts; if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container = tp.symbol.declarations[0].parent; for (var n = node; n !== container; n = n.parent) { - if (!n || n.kind === 230 /* Block */ || n.kind === 184 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) { + if (!n || n.kind === 231 /* Block */ || n.kind === 185 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) { return true; } } - return !!ts.forEachChild(node, containsReference); + return containsReference(node); } return true; function containsReference(node) { switch (node.kind) { - case 187 /* ThisType */: + case 188 /* ThisType */: return !!tp.isThisType; case 78 /* Identifier */: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return true; + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + return (!node.type && !!node.body) || !!ts.forEachChild(node, containsReference); } return !!ts.forEachChild(node, containsReference); } @@ -57799,7 +59406,7 @@ var ts; } return undefined; } - function instantiateMappedType(type, mapper) { + function instantiateMappedType(type, mapper, aliasSymbol, aliasTypeArguments) { // 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. @@ -57814,7 +59421,7 @@ var ts; if (typeVariable) { var mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapType(getReducedType(mappedTypeVariable), function (t) { + return mapTypeWithAlias(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) { if (!type.declaration.nameType) { if (isArrayType(t)) { @@ -57830,11 +59437,11 @@ var ts; return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper)); } return t; - }); + }, aliasSymbol, aliasTypeArguments); } } // If the constraint type of the instantiation is the wildcard type, return the wildcard type. - return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper); + return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments); } function getModifiedReadonlyState(state, modifiers) { return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state; @@ -57881,7 +59488,7 @@ var ts; strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; } - function instantiateAnonymousType(type, mapper) { + function instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; @@ -57894,29 +59501,29 @@ var ts; } result.target = type; result.mapper = mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + result.aliasSymbol = aliasSymbol || type.aliasSymbol; + result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); return result; } - function getConditionalTypeInstantiation(type, mapper) { + function getConditionalTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { var root = type.root; if (root.outerTypeParameters) { // We are instantiating a conditional type that has one or more type parameters in scope. Apply the // mapper to the type parameters to produce the effective list of type arguments, and compute the // instantiation cache key from the type IDs of the type arguments. var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); }); - var id = getTypeListId(typeArguments); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var result = root.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); - result = instantiateConditionalType(root, newMapper); + result = instantiateConditionalType(root, newMapper, aliasSymbol, aliasTypeArguments); root.instantiations.set(id, result); } return result; } return type; } - function instantiateConditionalType(root, mapper) { + function instantiateConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { // Check if we have a conditional type where the check type is a naked type parameter. If so, // the conditional type is distributive over union types and when T is instantiated to a union // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y). @@ -57924,31 +59531,34 @@ var ts; var checkType_1 = root.checkType; var instantiatedType = getMappedType(checkType_1, mapper); if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) { - return mapType(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); }); + return mapTypeWithAlias(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); }, aliasSymbol, aliasTypeArguments); } } - return getConditionalType(root, mapper); + return getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments); } function instantiateType(type, mapper) { - if (!(type && mapper && couldContainTypeVariables(type))) { + return type && mapper ? instantiateTypeWithAlias(type, mapper, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined) : type; + } + function instantiateTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) { + if (!couldContainTypeVariables(type)) { return type; } if (instantiationDepth === 50 || instantiationCount >= 5000000) { // 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. - ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); return errorType; } totalInstantiationCount++; instantiationCount++; instantiationDepth++; - var result = instantiateTypeWorker(type, mapper); + var result = instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments); instantiationDepth--; return result; } - function instantiateTypeWorker(type, mapper) { + function instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments) { var flags = type.flags; if (flags & 262144 /* TypeParameter */) { return getMappedType(type, mapper); @@ -57956,12 +59566,15 @@ var ts; if (flags & 524288 /* Object */) { var objectFlags = type.objectFlags; if (objectFlags & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */)) { - if (objectFlags & 4 /* Reference */ && !(type.node)) { + if (objectFlags & 4 /* Reference */ && !type.node) { var resolvedTypeArguments = type.resolvedTypeArguments; var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type; } - return getObjectTypeInstantiation(type, mapper); + if (objectFlags & 1024 /* ReverseMapped */) { + return instantiateReverseMappedType(type, mapper); + } + return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments); } return type; } @@ -57969,10 +59582,14 @@ var ts; var origin = type.flags & 1048576 /* Union */ ? type.origin : undefined; var types = origin && origin.flags & 3145728 /* UnionOrIntersection */ ? origin.types : type.types; var newTypes = instantiateTypes(types, mapper); - return newTypes === types ? type : - flags & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ? - getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : - getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + if (newTypes === types && aliasSymbol === type.aliasSymbol) { + return type; + } + var newAliasSymbol = aliasSymbol || type.aliasSymbol; + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + return flags & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ? + getIntersectionType(newTypes, newAliasSymbol, newAliasTypeArguments) : + getUnionType(newTypes, 1 /* Literal */, newAliasSymbol, newAliasTypeArguments); } if (flags & 4194304 /* Index */) { return getIndexType(instantiateType(type.type, mapper)); @@ -57984,10 +59601,12 @@ var ts; return getStringMappingType(type.symbol, instantiateType(type.type, mapper)); } if (flags & 8388608 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + var newAliasSymbol = aliasSymbol || type.aliasSymbol; + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, newAliasSymbol, newAliasTypeArguments); } if (flags & 16777216 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper), aliasSymbol, aliasTypeArguments); } if (flags & 33554432 /* Substitution */) { var maybeVariable = instantiateType(type.baseType, mapper); @@ -58004,6 +59623,21 @@ var ts; } return type; } + function instantiateReverseMappedType(type, mapper) { + var innerMappedType = instantiateType(type.mappedType, mapper); + if (!(ts.getObjectFlags(innerMappedType) & 32 /* Mapped */)) { + return type; + } + var innerIndexType = instantiateType(type.constraintType, mapper); + if (!(innerIndexType.flags & 4194304 /* Index */)) { + return type; + } + var instantiated = inferTypeForHomomorphicMappedType(instantiateType(type.source, mapper), innerMappedType, innerIndexType); + if (instantiated) { + return instantiated; + } + return type; // Nested invocation of `inferTypeForHomomorphicMappedType` or the `source` instantiated into something unmappable + } function getPermissiveInstantiation(type) { return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); @@ -58030,35 +59664,35 @@ var 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) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 251 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type return isContextSensitiveFunctionLikeDeclaration(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return ts.some(node.properties, isContextSensitive); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return ts.some(node.elements, isContextSensitive); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return (node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */) && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isContextSensitive(node.expression); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); - case 280 /* JsxAttribute */: { + case 281 /* JsxAttribute */: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. var initializer = node.initializer; return !!initializer && isContextSensitive(initializer); } - case 283 /* JsxExpression */: { + case 284 /* JsxExpression */: { // It is possible to that node.expression is undefined (e.g

) var expression = node.expression; return !!expression && isContextSensitive(expression); @@ -58077,7 +59711,7 @@ var ts; if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 209 /* ArrowFunction */) { + if (node.kind !== 210 /* ArrowFunction */) { // If the first parameter is not an explicit 'this' parameter, then the function has // an implicit 'this' parameter which is subject to contextual typing. var parameter = ts.firstOrUndefined(node.parameters); @@ -58090,7 +59724,7 @@ var ts; } function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 230 /* Block */ && isContextSensitive(node.body); + return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 231 /* Block */ && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -58193,23 +59827,23 @@ var ts; return true; } switch (node.kind) { - case 283 /* JsxExpression */: - case 207 /* ParenthesizedExpression */: + case 284 /* JsxExpression */: + case 208 /* ParenthesizedExpression */: return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (node.operatorToken.kind) { case 62 /* EqualsToken */: case 27 /* CommaToken */: return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); } break; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer); } return false; @@ -58409,7 +60043,7 @@ var ts; } function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) { switch (child.kind) { - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: // child is of the type of the expression return { errorNode: child, innerExpression: child.expression, nameType: nameType }; case 11 /* JsxText */: @@ -58418,9 +60052,9 @@ var ts; } // child is a string return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() }; - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: // child is of type JSX.Element return { errorNode: child, innerExpression: child, nameType: nameType }; default: @@ -58568,11 +60202,11 @@ var ts; } _b = prop.kind; switch (_b) { - case 168 /* SetAccessor */: return [3 /*break*/, 2]; - case 167 /* GetAccessor */: return [3 /*break*/, 2]; - case 165 /* MethodDeclaration */: return [3 /*break*/, 2]; - case 289 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; - case 288 /* PropertyAssignment */: return [3 /*break*/, 4]; + case 169 /* SetAccessor */: return [3 /*break*/, 2]; + case 168 /* GetAccessor */: return [3 /*break*/, 2]; + case 166 /* MethodDeclaration */: return [3 /*break*/, 2]; + case 290 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 289 /* PropertyAssignment */: return [3 /*break*/, 4]; } return [3 /*break*/, 6]; case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; @@ -58649,8 +60283,8 @@ var ts; return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; - var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 165 /* MethodDeclaration */ && - kind !== 164 /* MethodSignature */ && kind !== 166 /* Constructor */; + var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 166 /* MethodDeclaration */ && + kind !== 165 /* MethodSignature */ && kind !== 167 /* Constructor */; var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { @@ -58883,7 +60517,7 @@ var ts; // Type number or any numeric literal type is assignable to any numeric enum type or any // numeric enum literal type. This rule exists for backwards compatibility reasons because // bit-flag enum types sometimes look like literal enum types with numeric literal values. - if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) + if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || relation === assignableRelation && t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) return true; } return false; @@ -58920,7 +60554,7 @@ var ts; return false; } function isIgnoredJsxProperty(source, sourceProp) { - return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); + return ts.getObjectFlags(source) & 2048 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { while (true) { @@ -58930,6 +60564,7 @@ var ts; type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute : type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : type; + t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) break; type = t; @@ -58967,7 +60602,7 @@ var ts; reportIncompatibleStack(); } if (overflow) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); @@ -59103,6 +60738,14 @@ var ts; } break; } + case ts.Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target.code: { + secondaryRootErrors.unshift([ts.Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target, args[0], args[1]]); + break; + } + case ts.Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target.code: { + secondaryRootErrors.unshift([ts.Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target, args[0], args[1], args[2]]); + break; + } default: return ts.Debug.fail("Unhandled Diagnostic: " + msg.code); } @@ -59163,6 +60806,7 @@ var ts; reportError(ts.Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2, needsOriginalSource ? sourceType : generalizedSourceType, targetType, typeToString(constraint)); } else { + errorInfo = undefined; reportError(ts.Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, generalizedSourceType); } } @@ -59238,7 +60882,7 @@ var ts; if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { return -1 /* True */; } - reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */)); + reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 2048 /* JsxAttributes */)); return 0 /* False */; } // Normalize the source and target types: Turn fresh literal types into regular literal types, @@ -59273,16 +60917,16 @@ var ts; target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) { var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */); if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) { - if (source === nullStrippedTarget) - return -1 /* True */; - target = nullStrippedTarget; + target = getNormalizedType(nullStrippedTarget, /*writing*/ true); } + if (source === nullStrippedTarget) + return -1 /* True */; } if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); + var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384 /* FreshLiteral */); if (isPerformingExcessPropertyChecks) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -59367,7 +61011,7 @@ var ts; // We suppress recursive intersection property checks because they can generate lots of work when relating // recursive intersections that are structurally similar but not exactly identical. See #37854. if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) { + isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 524288 /* NonInferrableType */); }))) { inPropertyCheck = true; result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */); inPropertyCheck = false; @@ -59376,8 +61020,10 @@ var ts; return result; function reportErrorResults(source, target, result, isComparingJsxAttributes) { if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; + var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); + var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); + source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; + target = (originalTarget.aliasSymbol || targetHasBase) ? originalTarget : target; var maybeSuppress = overrideNextErrorInfo > 0; if (maybeSuppress) { overrideNextErrorInfo--; @@ -59418,13 +61064,13 @@ var ts; } } function traceUnionsOrIntersectionsTooLarge(source, target) { - if (!ts.tracing.isTracing()) { + if (!ts.tracing) { return; } if ((source.flags & 3145728 /* UnionOrIntersection */) && (target.flags & 3145728 /* UnionOrIntersection */)) { var sourceUnionOrIntersection = source; var targetUnionOrIntersection = target; - if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 262144 /* PrimitiveUnion */) { + if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 65536 /* PrimitiveUnion */) { // There's a fast path for comparing primitive unions return; } @@ -59449,11 +61095,11 @@ var ts; } traceUnionsOrIntersectionsTooLarge(source, target); if (flags & 3145728 /* UnionOrIntersection */) { - var result_6 = eachTypeRelatedToSomeType(source, target); - if (result_6) { - result_6 &= eachTypeRelatedToSomeType(target, source); + var result_7 = eachTypeRelatedToSomeType(source, target); + if (result_7) { + result_7 &= eachTypeRelatedToSomeType(target, source); } - return result_6; + return result_7; } return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */); } @@ -59467,10 +61113,11 @@ var ts; return getUnionType(ts.reduceLeft(types, appendPropType, /*initial*/ undefined) || ts.emptyArray); } function hasExcessProperties(source, target, reportErrors) { - if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + var _a; + if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 8192 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; @@ -59513,7 +61160,7 @@ var ts; } else { // use the property's value declaration if the property is assigned inside the literal itself - var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + var objectLiteralDeclaration_1 = ((_a = source.symbol) === null || _a === void 0 ? void 0 : _a.declarations) && ts.firstOrUndefined(source.symbol.declarations); var suggestion = void 0; if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) { var propDeclaration = prop.valueDeclaration; @@ -59542,11 +61189,11 @@ var ts; } } }; - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - var state_4 = _loop_16(prop); - if (typeof state_4 === "object") - return state_4.value; + for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { + var prop = _b[_i]; + var state_5 = _loop_16(prop); + if (typeof state_5 === "object") + return state_5.value; } return false; } @@ -59568,8 +61215,17 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) { - return -1 /* True */; + if (target.flags & 1048576 /* Union */) { + if (containsType(targetTypes, source)) { + return -1 /* True */; + } + var match = getMatchingUnionConstituentForType(target, source); + if (match) { + var related = isRelatedTo(source, match, /*reportErrors*/ false); + if (related) { + return related; + } + } } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { var type = targetTypes_1[_i]; @@ -59743,9 +61399,16 @@ var ts; targetStack = []; } else { + // generate a key where all type parameter id positions are replaced with unconstrained type parameter ids + // this isn't perfect - nested type references passed as type arguments will muck up the indexes and thus + // prevent finding matches- but it should hit up the common cases + var broadestEquivalentId = id.split(",").map(function (i) { return i.replace(/-\d+/g, function (_match, offset) { + var index = ts.length(id.slice(0, offset).match(/[-=]/g) || undefined); + return "=" + index; + }); }).join(","); for (var i = 0; i < maybeCount; i++) { // If source and target are already being compared, consider them related with assumptions - if (id === maybeKeys[i]) { + if (id === maybeKeys[i] || broadestEquivalentId === maybeKeys[i]) { return 3 /* Maybe */; } } @@ -59775,7 +61438,7 @@ var ts; }; } if (expandingFlags === 3 /* Both */) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { sourceId: source.id, sourceIdStack: sourceStack.map(function (t) { return t.id; }), targetId: target.id, @@ -59810,9 +61473,9 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { - ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) { @@ -59834,8 +61497,21 @@ var ts; if (target.flags & 2097152 /* Intersection */) { return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */); } - // Source is an intersection. Check to see if any constituents of the intersection are immediately related - // to the target. + // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the + // constraints of all non-primitive types in the source into a new intersection. We do this because the + // intersection may further constrain the constraints of the non-primitive types. For example, given a type + // parameter 'T extends 1 | 2', the intersection 'T & 1' should be reduced to '1' such that it doesn't + // appear to be comparable to '2'. + if (relation === comparableRelation && target.flags & 131068 /* Primitive */) { + var constraints = ts.sameMap(source.types, function (t) { return t.flags & 131068 /* Primitive */ ? t : getBaseConstraintOfType(t) || unknownType; }); + if (constraints !== source.types) { + source = getIntersectionType(constraints); + if (!(source.flags & 2097152 /* Intersection */)) { + return isRelatedTo(source, target, /*reportErrors*/ false); + } + } + } + // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually // useful and leads to some confusing error messages. Instead it is better to let the below checks @@ -59855,21 +61531,21 @@ var ts; if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_7 = 0 /* False */; + var result_8 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_7 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_8; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_7 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_8; } } } @@ -59949,6 +61625,20 @@ var ts; } } else if (target.flags & 8388608 /* IndexedAccess */) { + if (source.flags & 8388608 /* IndexedAccess */) { + // Relate components directly before falling back to constraint relationships + // A type S[K] is related to a type T[J] if S is related to T and K is related to J. + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + if (reportErrors) { + originalErrorInfo = errorInfo; + } + } // A type S is related to a type T[K] if S is related to C, where C is the base // constraint of T[K] for writing. if (relation === assignableRelation || relation === comparableRelation) { @@ -59959,11 +61649,24 @@ var ts; if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) { var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0); var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, target.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, accessFlags); - if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) { - return result; + if (constraint) { + if (reportErrors && originalErrorInfo) { + // create a new chain for the constraint error + resetErrorInfo(saveErrorInfo); + } + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + // prefer the shorter chain of the constraint comparison chain, and the direct comparison chain + if (reportErrors && originalErrorInfo && errorInfo) { + errorInfo = countMessageChainBreadth([originalErrorInfo]) <= countMessageChainBreadth([errorInfo]) ? originalErrorInfo : errorInfo; + } } } } + if (reportErrors) { + originalErrorInfo = undefined; + } } else if (isGenericMappedType(target) && !target.declaration.nameType) { // A source type T is related to a target type { [P in X]: T[P] } @@ -60007,27 +61710,48 @@ var ts; } } } - else if (target.flags & 134217728 /* TemplateLiteral */ && source.flags & 128 /* StringLiteral */) { - if (isPatternLiteralType(target)) { - // match all non-`string` segments - var result_8 = inferLiteralsFromTemplateLiteralType(source, target); - if (result_8 && ts.every(result_8, function (r, i) { return isStringLiteralTypeValueParsableAsType(r, target.types[i]); })) { - return -1 /* True */; - } + else if (target.flags & 16777216 /* Conditional */) { + var c = target; + // Check if the conditional is always true or always false but still deferred for distribution purposes + var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); + var skipFalse = !skipTrue && isConditionalTypeAlwaysTrueDisregardingInferTypes(c); + // Instantiate with a replacement mapper if the conditional is distributive, replacing the check type with a clone of itself, + // this way {x: string | number, y: string | number} -> (T extends T ? { x: T, y: T } : never) appropriately _fails_ when + // T = string | number (since that will end up distributing and producing `{x: string, y: string} | {x: number, y: number}`, + // to which `{x: string | number, y: string | number}` isn't assignable) + var distributionMapper = void 0; + var checkVar = getActualTypeVariable(c.root.checkType); + if (c.root.isDistributive && checkVar.flags & 262144 /* TypeParameter */) { + var newParam = cloneTypeParameter(checkVar); + distributionMapper = prependTypeMapping(checkVar, newParam, c.mapper); + newParam.mapper = distributionMapper; + } + // TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't) + var localResult = void 0; + if (skipTrue || (localResult = isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.trueType), distributionMapper) : getTrueTypeFromConditionalType(c), /*reportErrors*/ false))) { + if (!skipFalse) { + localResult = (localResult || 3 /* Maybe */) & isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.falseType), distributionMapper) : getFalseTypeFromConditionalType(c), /*reportErrors*/ false); + } + } + if (localResult) { + resetErrorInfo(saveErrorInfo); + return localResult; } } - if (source.flags & 8650752 /* TypeVariable */) { - if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { - // A type S[K] is related to a type T[J] if S is related to T and K is related to J. - if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { - result &= isRelatedTo(source.indexType, target.indexType, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } + else if (target.flags & 134217728 /* TemplateLiteral */) { + if (source.flags & 134217728 /* TemplateLiteral */) { + // Report unreliable variance for type variables referenced in template literal type placeholders. + // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. + instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } - else { + var result_9 = inferTypesFromTemplateLiteralType(source, target); + if (result_9 && ts.every(result_9, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { + return -1 /* True */; + } + } + if (source.flags & 8650752 /* TypeVariable */) { + // IndexedAccess comparisons are handled above in the `target.flags & TypeFlage.IndexedAccess` branch + if (!(source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */)) { var constraint = getConstraintOfType(source); if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. @@ -60042,7 +61766,7 @@ var ts; return result; } // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example - else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, intersectionState)) { + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors && !(target.flags & source.flags & 262144 /* TypeParameter */), /*headMessage*/ undefined, intersectionState)) { resetErrorInfo(saveErrorInfo); return result; } @@ -60055,17 +61779,10 @@ var ts; } } else if (source.flags & 134217728 /* TemplateLiteral */) { - if (target.flags & 134217728 /* TemplateLiteral */) { - if (source.texts.length === target.texts.length && - source.types.length === target.types.length && - ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) && - ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 /* Any */ | 4 /* String */)) || !!isRelatedTo(t, target.types[i], /*reportErrors*/ false); })) { - return -1 /* True */; - } - } - else { - var constraint = getBaseConstraintOfType(source); - if (result = isRelatedTo(constraint && constraint !== source ? constraint : stringType, target, reportErrors)) { + if (!(target.flags & 134217728 /* TemplateLiteral */)) { + var baseConstraint = getBaseConstraintOfType(source); + var constraint = baseConstraint && baseConstraint !== source ? baseConstraint : stringType; + if (result = isRelatedTo(constraint, target, reportErrors)) { resetErrorInfo(saveErrorInfo); return result; } @@ -60097,7 +61814,7 @@ var ts; if (sourceParams) { // If the source has infer type parameters, we instantiate them in the context of the target var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo); - inferTypes(ctx.inferences, target.extendsType, sourceExtends, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); sourceExtends = instantiateType(sourceExtends, ctx.mapper); mapper = ctx.mapper; } @@ -60155,7 +61872,7 @@ var ts; return 0 /* False */; } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && - !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { + !(ts.getObjectFlags(source) & 4096 /* MarkerType */ || ts.getObjectFlags(target) & 4096 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. @@ -60183,7 +61900,7 @@ var ts; } // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})` // and not `{} <- fresh({}) <- {[idx: string]: any}` - else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) { + else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 16384 /* FreshLiteral */ && !isEmptyObjectType(source)) { return 0 /* False */; } // Even if relationship doesn't hold for unions, intersections, or generic type references, @@ -60221,14 +61938,19 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_9) { - return result_9; + var result_10 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_10) { + return result_10; } } } } return 0 /* False */; + function countMessageChainBreadth(info) { + if (!info) + return 0; + return ts.reduceLeft(info, function (value, chain) { return value + 1 + countMessageChainBreadth(chain.next); }, 0); + } function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) { if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) { return result; @@ -60290,13 +62012,13 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_10; + var result_11; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + if (result_11 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { - return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_11 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } } @@ -60327,7 +62049,7 @@ var ts; numCombinations *= countTypes(getTypeOfSymbol(sourceProperty)); if (numCombinations > 25) { // We've reached the complexity limit. - ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); return 0 /* False */; } } @@ -60366,8 +62088,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_6 = _loop_18(i); - switch (state_6) { + var state_7 = _loop_18(i); + switch (state_7) { case "continue-outer": continue outer; } } @@ -60380,9 +62102,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_5 = _loop_17(combination); - if (typeof state_5 === "object") - return state_5.value; + var state_6 = _loop_17(combination); + if (typeof state_6 === "object") + return state_6.value; } // Compare the remaining non-discriminant properties of each match. var result = -1 /* True */; @@ -60436,7 +62158,7 @@ var ts; ts.Debug.assertIsDefined(links.deferralParent); ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */); - var result_11 = unionParent ? 0 /* False */ : -1 /* True */; + var result_12 = unionParent ? 0 /* False */ : -1 /* True */; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -60446,7 +62168,7 @@ var ts; // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_11 &= related; + result_12 &= related; } else { if (related) { @@ -60454,17 +62176,17 @@ var ts; } } } - if (unionParent && !result_11 && targetIsOptional) { - result_11 = isRelatedTo(source, undefinedType); + if (unionParent && !result_12 && targetIsOptional) { + result_12 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_11 && reportErrors) { + if (unionParent && !result_12 && reportErrors) { // The easiest way to get the right errors here is to un-defer (which may be costly) // If it turns out this is too costly too often, we can replicate the error handling logic within // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union // type on which to hand discriminable properties, which we are expressly trying to avoid here) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_11; + return result_12; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState); @@ -60795,7 +62517,7 @@ var ts; var targetSignature = ts.first(targetSignatures); result = signatureRelatedTo(sourceSignature, targetSignature, eraseGenerics, reportErrors, incompatibleReporter(sourceSignature, targetSignature)); if (!result && reportErrors && kind === 1 /* Construct */ && (sourceObjectFlags & targetObjectFlags) && - (((_a = targetSignature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 166 /* Constructor */ || ((_b = sourceSignature.declaration) === null || _b === void 0 ? void 0 : _b.kind) === 166 /* Constructor */)) { + (((_a = targetSignature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 167 /* Constructor */ || ((_b = sourceSignature.declaration) === null || _b === void 0 ? void 0 : _b.kind) === 167 /* Constructor */)) { var constructSignatureToString = function (signature) { return signatureToString(signature, /*enclosingDeclaration*/ undefined, 262144 /* WriteArrowStyleSignature */, kind); }; @@ -60903,10 +62625,17 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetType = getIndexTypeOfType(target, kind); - if (!targetType || targetType.flags & 1 /* Any */ && !sourceIsPrimitive) { - // Index signature of type any permits assignment from everything but primitives + if (!targetType) { return -1 /* True */; } + if (targetType.flags & 1 /* Any */ && !sourceIsPrimitive) { + // An index signature of type `any` permits assignment from everything but primitives, + // provided that there is also a `string` index signature of type `any`. + var stringIndexType = kind === 0 /* String */ ? targetType : getIndexTypeOfType(target, 0 /* String */); + if (stringIndexType && stringIndexType.flags & 1 /* Any */) { + return -1 /* True */; + } + } if (isGenericMappedType(source)) { // A generic mapped type { [P in K]: T } is related to a type with an index signature // { [x: string]: U }, and optionally with an index signature { [x: number]: V }, @@ -61061,7 +62790,7 @@ var ts; // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); - result.objectFlags |= 8192 /* MarkerType */; + result.objectFlags |= 4096 /* MarkerType */; return result; } function getAliasVariances(symbol) { @@ -61082,7 +62811,7 @@ var ts; if (typeParameters === void 0) { typeParameters = ts.emptyArray; } var variances = cache.variances; if (!variances) { - ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); // The emptyArray singleton is used to signal a recursive invocation. cache.variances = ts.emptyArray; variances = []; @@ -61121,7 +62850,7 @@ var ts; _loop_19(tp); } cache.variances = variances; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } return variances; } @@ -61149,7 +62878,7 @@ var ts; return !!(ts.getObjectFlags(type) & 4 /* Reference */) && !type.node; } function isTypeReferenceWithGenericArguments(type) { - return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return !!(t.flags & 262144 /* TypeParameter */) || isTypeReferenceWithGenericArguments(t); }); } /** * getTypeReferenceId(A) returns "111=0-12=1" @@ -61235,8 +62964,8 @@ var ts; } // Return true if the given class derives from each of the declaring classes of the protected // constituents of the given property. - function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) { + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p, writing) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons @@ -61254,23 +62983,26 @@ var ts; function isDeeplyNestedType(type, stack, depth) { if (depth >= 5) { var identity_1 = getRecursionIdentity(type); - if (identity_1) { - var count = 0; - for (var i = 0; i < depth; i++) { - if (getRecursionIdentity(stack[i]) === identity_1) { - count++; - if (count >= 5) { - return true; - } + var count = 0; + for (var i = 0; i < depth; i++) { + if (getRecursionIdentity(stack[i]) === identity_1) { + count++; + if (count >= 5) { + return true; } } } } return false; } - // Types with constituents that could circularly reference the type have a recursion identity. The recursion - // identity is some object that is common to instantiations of the type with the same origin. + // The recursion identity of a type is an object identity that is shared among multiple instantiations of the type. + // We track recursion identities in order to identify deeply nested and possibly infinite type instantiations with + // the same origin. For example, when type parameters are in scope in an object type such as { x: T }, all + // instantiations of that type have the same recursion identity. The default recursion identity is the object + // identity of the type, meaning that every type is unique. Generally, types with constituents that could circularly + // reference the type have a recursion identity that differs from the object identity. function getRecursionIdentity(type) { + // Object and array literals are known not to contain recursive references and don't need a recursion identity. if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) { if (ts.getObjectFlags(type) && 4 /* Reference */ && type.node) { // Deferred type references are tracked through their associated AST node. This gives us finer @@ -61288,6 +63020,9 @@ var ts; return type.target; } } + if (type.flags & 262144 /* TypeParameter */) { + return type.symbol; + } if (type.flags & 8388608 /* IndexedAccess */) { // Identity is the leftmost object type in a chain of indexed accesses, eg, in A[P][Q] it is A do { @@ -61299,7 +63034,7 @@ var ts; // The root object represents the origin of the conditional type return type.root; } - return undefined; + return type; } function isPropertyIdenticalTo(sourceProp, targetProp) { return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; @@ -61438,6 +63173,9 @@ var ts; // of those literal types. Otherwise, return the leftmost type for which no type to the // right is a supertype. function getSupertypeOrUnion(types) { + if (types.length === 1) { + return types[0]; + } return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); @@ -61472,9 +63210,32 @@ var ts; // or if it is not the undefined or null type and if it is assignable to ReadonlyArray return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } + function getSingleBaseForNonAugmentingSubtype(type) { + if (!(ts.getObjectFlags(type) & 4 /* Reference */) || !(ts.getObjectFlags(type.target) & 3 /* ClassOrInterface */)) { + return undefined; + } + if (ts.getObjectFlags(type) & 33554432 /* IdenticalBaseTypeCalculated */) { + return ts.getObjectFlags(type) & 67108864 /* IdenticalBaseTypeExists */ ? type.cachedEquivalentBaseType : undefined; + } + type.objectFlags |= 33554432 /* IdenticalBaseTypeCalculated */; + var target = type.target; + var bases = getBaseTypes(target); + if (bases.length !== 1) { + return undefined; + } + if (getMembersOfSymbol(type.symbol).size) { + return undefined; // If the interface has any members, they may subtype members in the base, so we should do a full structural comparison + } + var instantiatedBase = !ts.length(target.typeParameters) ? bases[0] : instantiateType(bases[0], createTypeMapper(target.typeParameters, getTypeArguments(type).slice(0, target.typeParameters.length))); + if (ts.length(getTypeArguments(type)) > ts.length(target.typeParameters)) { + instantiatedBase = getTypeWithThisArgument(instantiatedBase, ts.last(getTypeArguments(type))); + } + type.objectFlags |= 67108864 /* IdenticalBaseTypeExists */; + return type.cachedEquivalentBaseType = instantiatedBase; + } function isEmptyArrayLiteralType(type) { - var elementType = isArrayType(type) ? getTypeArguments(type)[0] : undefined; - return elementType === undefinedWideningType || elementType === implicitNeverType; + var elementType = getElementTypeOfArrayType(type); + return strictNullChecks ? elementType === implicitNeverType : elementType === undefinedWideningType; } function isTupleLikeType(type) { return isTupleType(type) || !!getPropertyOfType(type, "0"); @@ -61498,6 +63259,13 @@ var ts; function isUnitType(type) { return !!(type.flags & 109440 /* Unit */); } + function isUnitLikeType(type) { + return type.flags & 2097152 /* Intersection */ ? ts.some(type.types, isUnitType) : + !!(type.flags & 109440 /* Unit */); + } + function extractUnitType(type) { + return type.flags & 2097152 /* Intersection */ ? ts.find(type.types, isUnitType) || type : type; + } function isLiteralType(type) { return type.flags & 16 /* Boolean */ ? true : type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : @@ -61505,7 +63273,7 @@ var ts; } function getBaseTypeOfLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ ? stringType : + type.flags & 128 /* StringLiteral */ ? stringType : type.flags & 256 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : @@ -61514,7 +63282,7 @@ var ts; } function getWidenedLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : @@ -61648,14 +63416,17 @@ var ts; return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { + // First reduce away any constituents that are assignable to 'undefined' or 'null'. This not only eliminates + // 'undefined' and 'null', but also higher-order types such as a type parameter 'U extends undefined | null' + // that isn't eliminated by a NonNullable instantiation. + var reducedType = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); if (!deferredGlobalNonNullableTypeAlias) { deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; } - // Use NonNullable global type alias if available to improve quick info/declaration emit - if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { - return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); - } - return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior + // If the NonNullable type is available, return an instantiation. Otherwise just return the reduced type. + return deferredGlobalNonNullableTypeAlias !== unknownSymbol ? + getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [reducedType]) : + reducedType; } function getNonNullableType(type) { return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; @@ -61708,7 +63479,7 @@ var ts; function isObjectTypeWithInferableIndex(type) { return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 && - !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */); @@ -61741,7 +63512,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 16384 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -61752,7 +63523,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags; - regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */; + regularNew.objectFlags |= resolved.objectFlags & ~16384 /* FreshLiteral */; type.regularType = regularNew; return regularNew; } @@ -61782,7 +63553,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { var t = _a[_i]; - if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 4194304 /* ContainsSpread */)) { for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { var prop = _c[_b]; names.set(prop.escapedName, prop); @@ -61831,14 +63602,14 @@ var ts; var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); - result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening + result.objectFlags |= (ts.getObjectFlags(type) & (8192 /* JSLiteral */ | 524288 /* NonInferrableType */)); // Retain js literal flag through widening return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, /*context*/ undefined); } function getWidenedTypeWithContext(type, context) { - if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) { + if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) { if (context === undefined && type.widened) { return type.widened; } @@ -61883,7 +63654,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) { if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -61909,7 +63680,7 @@ var ts; for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -61928,12 +63699,12 @@ var ts; } var diagnostic; switch (declaration.kind) { - case 216 /* BinaryExpression */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 217 /* BinaryExpression */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 160 /* Parameter */: + case 161 /* Parameter */: var param = declaration; if (ts.isIdentifier(param.name) && (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && @@ -61948,23 +63719,23 @@ var ts; noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; if (!noImplicitAny) { // Don't issue a suggestion for binding elements since the codefix doesn't yet support them. return; } break; - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: if (noImplicitAny && !declaration.name) { if (wideningKind === 3 /* GeneratorYield */) { error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString); @@ -61978,7 +63749,7 @@ var ts; wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; - case 190 /* MappedType */: + case 191 /* MappedType */: if (noImplicitAny) { error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); } @@ -61989,7 +63760,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -62105,23 +63876,23 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) { - return !!(objectFlags & 134217728 /* CouldContainTypeVariables */); + if (objectFlags & 1048576 /* CouldContainTypeVariablesComputed */) { + return !!(objectFlags & 2097152 /* CouldContainTypeVariables */); } var result = !!(type.flags & 465829888 /* Instantiable */ || type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || - objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) || + objectFlags & (32 /* Mapped */ | 1024 /* ReverseMapped */ | 8388608 /* ObjectRestType */)) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables)); if (type.flags & 3899393 /* ObjectFlagsType */) { - type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0); + type.objectFlags |= 1048576 /* CouldContainTypeVariablesComputed */ | (result ? 2097152 /* CouldContainTypeVariables */ : 0); } return result; } function isNonGenericTopLevelType(type) { if (type.aliasSymbol && !type.aliasTypeArguments) { - var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 254 /* TypeAliasDeclaration */); - return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 297 /* SourceFile */ ? true : n.kind === 256 /* ModuleDeclaration */ ? false : "quit"; })); + var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 255 /* TypeAliasDeclaration */); + return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 298 /* SourceFile */ ? true : n.kind === 257 /* ModuleDeclaration */ ? false : "quit"; })); } return false; } @@ -62174,7 +63945,7 @@ var ts; // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive // arrow function, but is considered partially inferable because property 'a' has an inferable type. function isPartiallyInferableType(type) { - return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) || + return !(ts.getObjectFlags(type) & 524288 /* NonInferrableType */) || isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }) || isTupleType(type) && ts.some(getTypeArguments(type), isPartiallyInferableType); } @@ -62198,14 +63969,18 @@ var ts; } // For all other object types we infer a new object type where the reverse mapping has been // applied to the type of each property. - var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); + var reversed = createObjectType(1024 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + return links.type; } function inferReverseMappedType(sourceType, target, constraint) { var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); @@ -62297,51 +64072,113 @@ var ts; // * it does not contain a numeric seperator (the `BigInt` constructor does not accept a numeric seperator in its input) return success && result === 9 /* BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* ContainsSeparator */); } - function isStringLiteralTypeValueParsableAsType(s, target) { - if (target.flags & 1048576 /* Union */) { - return !!forEachType(target, function (t) { return isStringLiteralTypeValueParsableAsType(s, t); }); - } - switch (target) { - case stringType: return true; - case numberType: return s.value !== "" && isFinite(+(s.value)); - case bigintType: return s.value !== "" && isValidBigIntString(s.value); - // the next 4 should be handled in `getTemplateLiteralType`, as they are all exactly one value, but are here for completeness, just in case - // this function is ever used on types which don't come from template literal holes - case trueType: return s.value === "true"; - case falseType: return s.value === "false"; - case undefinedType: return s.value === "undefined"; - case nullType: return s.value === "null"; - default: return !!(target.flags & 1 /* Any */); - } - } - function inferLiteralsFromTemplateLiteralType(source, target) { - var value = source.value; - var texts = target.texts; - var lastIndex = texts.length - 1; - var startText = texts[0]; - var endText = texts[lastIndex]; - if (!(value.startsWith(startText) && value.slice(startText.length).endsWith(endText))) + function isValidTypeForTemplateLiteralPlaceholder(source, target) { + if (source === target || target.flags & (1 /* Any */ | 4 /* String */)) { + return true; + } + if (source.flags & 128 /* StringLiteral */) { + var value = source.value; + return !!(target.flags & 8 /* Number */ && value !== "" && isFinite(+value) || + target.flags & 64 /* BigInt */ && value !== "" && isValidBigIntString(value) || + target.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) && value === target.intrinsicName); + } + if (source.flags & 134217728 /* TemplateLiteral */) { + var texts = source.texts; + return texts.length === 2 && texts[0] === "" && texts[1] === "" && isTypeAssignableTo(source.types[0], target); + } + return isTypeAssignableTo(source, target); + } + function inferTypesFromTemplateLiteralType(source, target) { + return source.flags & 128 /* StringLiteral */ ? inferFromLiteralPartsToTemplateLiteral([source.value], ts.emptyArray, target) : + source.flags & 134217728 /* TemplateLiteral */ ? + ts.arraysEqual(source.texts, target.texts) ? ts.map(source.types, getStringLikeTypeForType) : + inferFromLiteralPartsToTemplateLiteral(source.texts, source.types, target) : + undefined; + } + function getStringLikeTypeForType(type) { + return type.flags & (1 /* Any */ | 402653316 /* StringLike */) ? type : getTemplateLiteralType(["", ""], [type]); + } + // This function infers from the text parts and type parts of a source literal to a target template literal. The number + // of text parts is always one more than the number of type parts, and a source string literal is treated as a source + // with one text part and zero type parts. The function returns an array of inferred string or template literal types + // corresponding to the placeholders in the target template literal, or undefined if the source doesn't match the target. + // + // We first check that the starting source text part matches the starting target text part, and that the ending source + // text part ends matches the ending target text part. We then iterate through the remaining target text parts, finding + // a match for each in the source and inferring string or template literal types created from the segments of the source + // that occur between the matches. During this iteration, seg holds the index of the current text part in the sourceTexts + // array and pos holds the current character position in the current text part. + // + // Consider inference from type `<<${string}>.<${number}-${number}>>` to type `<${string}.${string}>`, i.e. + // sourceTexts = ['<<', '>.<', '-', '>>'] + // sourceTypes = [string, number, number] + // target.texts = ['<', '.', '>'] + // We first match '<' in the target to the start of '<<' in the source and '>' in the target to the end of '>>' in + // the source. The first match for the '.' in target occurs at character 1 in the source text part at index 1, and thus + // the first inference is the template literal type `<${string}>`. The remainder of the source makes up the second + // inference, the template literal type `<${number}-${number}>`. + function inferFromLiteralPartsToTemplateLiteral(sourceTexts, sourceTypes, target) { + var lastSourceIndex = sourceTexts.length - 1; + var sourceStartText = sourceTexts[0]; + var sourceEndText = sourceTexts[lastSourceIndex]; + var targetTexts = target.texts; + var lastTargetIndex = targetTexts.length - 1; + var targetStartText = targetTexts[0]; + var targetEndText = targetTexts[lastTargetIndex]; + if (lastSourceIndex === 0 && sourceStartText.length < targetStartText.length + targetEndText.length || + !sourceStartText.startsWith(targetStartText) || !sourceEndText.endsWith(targetEndText)) return undefined; + var remainingEndText = sourceEndText.slice(0, sourceEndText.length - targetEndText.length); var matches = []; - var str = value.slice(startText.length, value.length - endText.length); - var pos = 0; - for (var i = 1; i < lastIndex; i++) { - var delim = texts[i]; - var delimPos = delim.length > 0 ? str.indexOf(delim, pos) : pos < str.length ? pos + 1 : -1; - if (delimPos < 0) + var seg = 0; + var pos = targetStartText.length; + for (var i = 1; i < lastTargetIndex; i++) { + var delim = targetTexts[i]; + if (delim.length > 0) { + var s = seg; + var p = pos; + while (true) { + p = getSourceText(s).indexOf(delim, p); + if (p >= 0) + break; + s++; + if (s === sourceTexts.length) + return undefined; + p = 0; + } + addMatch(s, p); + pos += delim.length; + } + else if (pos < getSourceText(seg).length) { + addMatch(seg, pos + 1); + } + else if (seg < lastSourceIndex) { + addMatch(seg + 1, 0); + } + else { return undefined; - matches.push(getLiteralType(str.slice(pos, delimPos))); - pos = delimPos + delim.length; + } } - matches.push(getLiteralType(str.slice(pos))); + addMatch(lastSourceIndex, getSourceText(lastSourceIndex).length); return matches; + function getSourceText(index) { + return index < lastSourceIndex ? sourceTexts[index] : remainingEndText; + } + function addMatch(s, p) { + var matchType = s === seg ? + getLiteralType(getSourceText(s).slice(pos, p)) : + getTemplateLiteralType(__spreadArray(__spreadArray([sourceTexts[seg].slice(pos)], sourceTexts.slice(seg + 1, s)), [getSourceText(s).slice(0, p)]), sourceTypes.slice(seg, s)); + matches.push(matchType); + seg = s; + pos = p; + } } function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) { if (priority === void 0) { priority = 0; } if (contravariant === void 0) { contravariant = false; } var bivariant = false; var propagationType; - var inferencePriority = 1024 /* MaxValue */; + var inferencePriority = 2048 /* MaxValue */; var allowComplexConstraintInference = true; var visited; var sourceStack; @@ -62428,8 +64265,8 @@ var ts; // not contain anyFunctionType when we come back to this argument for its second round // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard // when constructing types from type parameters that had no inference candidates). - if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || - (priority & 64 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || + (priority & 128 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); @@ -62456,7 +64293,7 @@ var ts; clearCachedInferences(inferences); } } - if (!(priority & 64 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 128 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; clearCachedInferences(inferences); } @@ -62496,7 +64333,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - inferWithPriority(empty, target.type, 128 /* LiteralKeyof */); + inferWithPriority(empty, target.type, 256 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -62508,6 +64345,13 @@ var ts; inferFromTypes(source.type, target.type); } } + else if (source.flags & 33554432 /* Substitution */) { + inferFromTypes(source.baseType, target); + var oldPriority = priority; + priority |= 4 /* SubstituteSource */; + inferFromTypes(source.substitute, target); // Make substitute inference at a lower priority + priority = oldPriority; + } else if (target.flags & 16777216 /* Conditional */) { invokeOnce(source, target, inferToConditionalType); } @@ -62527,7 +64371,7 @@ var ts; } else { source = getReducedType(source); - if (!(priority & 256 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { + if (!(priority & 512 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { var apparentSource = getApparentType(source); // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` @@ -62565,26 +64409,22 @@ var ts; } (visited || (visited = new ts.Map())).set(key, -1 /* Circularity */); var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; // We stop inferring and report a circularity if we encounter duplicate recursion identities on both // the source side and the target side. var saveExpandingFlags = expandingFlags; - var sourceIdentity = getRecursionIdentity(source) || source; - var targetIdentity = getRecursionIdentity(target) || target; - if (sourceIdentity && ts.contains(sourceStack, sourceIdentity)) + var sourceIdentity = getRecursionIdentity(source); + var targetIdentity = getRecursionIdentity(target); + if (ts.contains(sourceStack, sourceIdentity)) expandingFlags |= 1 /* Source */; - if (targetIdentity && ts.contains(targetStack, targetIdentity)) + if (ts.contains(targetStack, targetIdentity)) expandingFlags |= 2 /* Target */; if (expandingFlags !== 3 /* Both */) { - if (sourceIdentity) - (sourceStack || (sourceStack = [])).push(sourceIdentity); - if (targetIdentity) - (targetStack || (targetStack = [])).push(targetIdentity); + (sourceStack || (sourceStack = [])).push(sourceIdentity); + (targetStack || (targetStack = [])).push(targetIdentity); action(source, target); - if (targetIdentity) - targetStack.pop(); - if (sourceIdentity) - sourceStack.pop(); + targetStack.pop(); + sourceStack.pop(); } else { inferencePriority = -1 /* Circularity */; @@ -62624,7 +64464,7 @@ var ts; } } function inferFromContravariantTypes(source, target) { - if (strictFunctionTypes || priority & 512 /* AlwaysStrict */) { + if (strictFunctionTypes || priority & 1024 /* AlwaysStrict */) { contravariant = !contravariant; inferFromTypes(source, target); contravariant = !contravariant; @@ -62676,7 +64516,7 @@ var ts; else { for (var i = 0; i < sources.length; i++) { var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; inferFromTypes(sources[i], t); if (inferencePriority === priority) matched_1[i] = true; @@ -62755,9 +64595,9 @@ var ts; // We assign a lower priority to inferences made from types containing non-inferrable // types because we may only have a partial result (i.e. we may have failed to make // reverse inferences for some properties). - inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ? - 8 /* PartialHomomorphicMappedType */ : - 4 /* HomomorphicMappedType */); + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 524288 /* NonInferrableType */ ? + 16 /* PartialHomomorphicMappedType */ : + 8 /* HomomorphicMappedType */); } } return true; @@ -62765,7 +64605,7 @@ var ts; if (constraintType.flags & 262144 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type // parameter. First infer from 'keyof S' to K. - inferWithPriority(getIndexType(source), constraintType, 16 /* MappedTypeConstraint */); + inferWithPriority(getIndexType(source), constraintType, 32 /* MappedTypeConstraint */); // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X }, // where K extends keyof T, we make the same inferences as for a homomorphic mapped type // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a @@ -62794,16 +64634,14 @@ var ts; } else { var savePriority = priority; - priority |= contravariant ? 32 /* ContravariantConditional */ : 0; + priority |= contravariant ? 64 /* ContravariantConditional */ : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; inferToMultipleTypes(source, targetTypes, target.flags); priority = savePriority; } } function inferToTemplateLiteralType(source, target) { - var matches = source.flags & 128 /* StringLiteral */ ? inferLiteralsFromTemplateLiteralType(source, target) : - source.flags & 134217728 /* TemplateLiteral */ && ts.arraysEqual(source.texts, target.texts) ? source.types : - undefined; + var matches = inferTypesFromTemplateLiteralType(source, target); var types = target.types; for (var i = 0; i < types.length; i++) { inferFromTypes(matches ? matches[i] : neverType, types[i]); @@ -62919,7 +64757,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */); + var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* NonInferrableType */); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -62929,7 +64767,7 @@ var ts; 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 === 165 /* MethodDeclaration */ || kind === 164 /* MethodSignature */ || kind === 166 /* Constructor */; + bivariant = bivariant || kind === 166 /* MethodDeclaration */ || kind === 165 /* MethodSignature */ || kind === 167 /* Constructor */; applyToParameterTypes(source, target, inferFromContravariantTypes); bivariant = saveBivariant; } @@ -62956,7 +64794,7 @@ var ts; } } function isTypeOrBaseIdenticalTo(s, t) { - return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 134217856 /* StringLikeLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); + return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); } function isTypeCloselyMatchedBy(s, t) { return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol || @@ -62970,7 +64808,7 @@ var ts; return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); } function isObjectOrArrayLiteralType(type) { - return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */)); + return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 32768 /* ArrayLiteral */)); } function unionObjectAndArrayLiteralCandidates(candidates) { if (candidates.length > 1) { @@ -62983,7 +64821,7 @@ var ts; return candidates; } function getContravariantInference(inference) { - return inference.priority & 208 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + return inference.priority & 416 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } function getCovariantInference(inference, signature) { // Extract all object and array literal types and replace them with a single widened and normalized type. @@ -63000,7 +64838,7 @@ var ts; candidates; // If all inferences were made from a position that implies a combined result, infer a union type. // Otherwise, infer a common supertype. - var unwidenedType = inference.priority & 208 /* PriorityImpliesCombination */ ? + var unwidenedType = inference.priority & 416 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -63109,7 +64947,7 @@ var ts; case "BigUint64Array": return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later; default: - if (node.parent.kind === 289 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 290 /* ShorthandPropertyAssignment */) { return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer; } else { @@ -63130,26 +64968,24 @@ var ts; // TypeScript 1.0 spec (April 2014): 3.6.3 // A type query consists of the keyword typeof followed by an expression. // The expression is restricted to a single identifier or a sequence of identifiers separated by periods - return !!ts.findAncestor(node, function (n) { return n.kind === 176 /* TypeQuery */ ? true : n.kind === 78 /* Identifier */ || n.kind === 157 /* QualifiedName */ ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 177 /* TypeQuery */ ? true : n.kind === 78 /* Identifier */ || n.kind === 158 /* QualifiedName */ ? false : "quit"; }); } // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the // leftmost identifier followed by zero or more property names separated by dots. - // The result is undefined if the reference isn't a dotted name. We prefix nodes - // occurring in an apparent type position with '@' because the control flow type - // of such nodes may be based on the apparent type instead of the declared type. + // The result is undefined if the reference isn't a dotted name. function getFlowCacheKey(node, declaredType, initialType, flowContainer) { switch (node.kind) { case 78 /* Identifier */: var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; case 107 /* ThisKeyword */: return "0|" + (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType); - case 225 /* NonNullExpression */: - case 207 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: var propName = getAccessedPropertyName(node); if (propName !== undefined) { var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); @@ -63160,32 +64996,40 @@ var ts; } function isMatchingReference(source, target) { switch (target.kind) { - case 207 /* ParenthesizedExpression */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: return isMatchingReference(source, target.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return (ts.isAssignmentExpression(target) && isMatchingReference(source, target.left)) || (ts.isBinaryExpression(target) && target.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source, target.right)); } switch (source.kind) { + case 227 /* MetaProperty */: + return target.kind === 227 /* MetaProperty */ + && source.keywordToken === target.keywordToken + && source.name.escapedText === target.name.escapedText; case 78 /* Identifier */: case 79 /* PrivateIdentifier */: return target.kind === 78 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 249 /* VariableDeclaration */ || target.kind === 198 /* BindingElement */) && + (target.kind === 250 /* VariableDeclaration */ || target.kind === 199 /* BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); case 107 /* ThisKeyword */: return target.kind === 107 /* ThisKeyword */; case 105 /* SuperKeyword */: return target.kind === 105 /* SuperKeyword */; - case 225 /* NonNullExpression */: - case 207 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: return isMatchingReference(source.expression, target); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return ts.isAccessExpression(target) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 216 /* BinaryExpression */: + case 158 /* QualifiedName */: + return ts.isAccessExpression(target) && + source.right.escapedText === getAccessedPropertyName(target) && + isMatchingReference(source.left, target.expression); + case 217 /* BinaryExpression */: return (ts.isBinaryExpression(source) && source.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source.right, target)); } return false; @@ -63193,11 +65037,11 @@ var ts; // Given a source x, check if target matches x or is an && operation with an operand that matches x. function containsTruthyCheck(source, target) { return isMatchingReference(source, target) || - (target.kind === 216 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && + (target.kind === 217 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (containsTruthyCheck(source, target.left) || containsTruthyCheck(source, target.right))); } function getAccessedPropertyName(access) { - return access.kind === 201 /* PropertyAccessExpression */ ? access.name.escapedText : + return access.kind === 202 /* PropertyAccessExpression */ ? access.name.escapedText : ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : undefined; } @@ -63247,6 +65091,86 @@ var ts; } return result; } + // Given a set of constituent types and a property name, create and return a map keyed by the literal + // types of the property by that name in each constituent type. No map is returned if some key property + // has a non-literal type or if less than 10 or less than 50% of the constituents have a unique key. + // Entries with duplicate keys have unknownType as the value. + function mapTypesByKeyProperty(types, name) { + var map = new ts.Map(); + var count = 0; + var _loop_20 = function (type) { + if (type.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */)) { + var discriminant = getTypeOfPropertyOfType(type, name); + if (discriminant) { + if (!isLiteralType(discriminant)) { + return { value: undefined }; + } + var duplicate_1 = false; + forEachType(discriminant, function (t) { + var id = getTypeId(getRegularTypeOfLiteralType(t)); + var existing = map.get(id); + if (!existing) { + map.set(id, type); + } + else if (existing !== unknownType) { + map.set(id, unknownType); + duplicate_1 = true; + } + }); + if (!duplicate_1) + count++; + } + } + }; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; + var state_8 = _loop_20(type); + if (typeof state_8 === "object") + return state_8.value; + } + return count >= 10 && count * 2 >= types.length ? map : undefined; + } + // Return the name of a discriminant property for which it was possible and feasible to construct a map of + // constituent types keyed by the literal types of the property by that name in each constituent type. + function getKeyPropertyName(unionType) { + var types = unionType.types; + // We only construct maps for large unions with non-primitive constituents. + if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */) { + return undefined; + } + if (unionType.keyPropertyName === undefined) { + // The candidate key property name is the name of the first property with a unit type in one of the + // constituent types. + var keyPropertyName = ts.forEach(types, function (t) { + return t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ? + ts.forEach(getPropertiesOfType(t), function (p) { return isUnitType(getTypeOfSymbol(p)) ? p.escapedName : undefined; }) : + undefined; + }); + var mapByKeyProperty = keyPropertyName && mapTypesByKeyProperty(types, keyPropertyName); + unionType.keyPropertyName = mapByKeyProperty ? keyPropertyName : ""; + unionType.constituentMap = mapByKeyProperty; + } + return unionType.keyPropertyName.length ? unionType.keyPropertyName : undefined; + } + // Given a union type for which getKeyPropertyName returned a non-undefined result, return the constituent + // that corresponds to the given key type for that property name. + function getConstituentTypeForKeyType(unionType, keyType) { + var _a; + var result = (_a = unionType.constituentMap) === null || _a === void 0 ? void 0 : _a.get(getTypeId(getRegularTypeOfLiteralType(keyType))); + return result !== unknownType ? result : undefined; + } + function getMatchingUnionConstituentForType(unionType, type) { + var keyPropertyName = getKeyPropertyName(unionType); + var propType = keyPropertyName && getTypeOfPropertyOfType(type, keyPropertyName); + return propType && getConstituentTypeForKeyType(unionType, propType); + } + function getMatchingUnionConstituentForObjectLiteral(unionType, node) { + var keyPropertyName = getKeyPropertyName(unionType); + var propNode = keyPropertyName && ts.find(node.properties, function (p) { return p.symbol && p.kind === 289 /* PropertyAssignment */ && + p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer); }); + var propType = propNode && getTypeOfExpression(propNode.initializer); + return propType && getConstituentTypeForKeyType(unionType, propType); + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -63259,7 +65183,7 @@ var ts; } } } - if (expression.expression.kind === 201 /* PropertyAccessExpression */ && + if (expression.expression.kind === 202 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, expression.expression.expression)) { return true; } @@ -63306,14 +65230,6 @@ var ts; } return declaredType; } - function getTypeFactsOfTypes(types) { - var result = 0 /* None */; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; - result |= getTypeFacts(t); - } - return result; - } function isFunctionObjectType(type) { // We do a quick check for a "bind" property before performing the more expensive subtype // check. This gives us a quicker out in the common case where an object type is not a function. @@ -63321,7 +65237,8 @@ var ts; return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type) { + function getTypeFacts(type, ignoreObjects) { + if (ignoreObjects === void 0) { ignoreObjects = false; } var flags = type.flags; if (flags & 4 /* String */) { return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; @@ -63358,7 +65275,7 @@ var ts; (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } - if (flags & 524288 /* Object */) { + if (flags & 524288 /* Object */ && !ignoreObjects) { return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : isFunctionObjectType(type) ? @@ -63381,11 +65298,17 @@ var ts; return 0 /* None */; } if (flags & 465829888 /* Instantiable */) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType) : + return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : strictNullChecks ? 7929345 /* NonEmptyStringStrictFacts */ : 16776705 /* NonEmptyStringFacts */; } - if (flags & 3145728 /* UnionOrIntersection */) { - return getTypeFactsOfTypes(type.types); + if (flags & 1048576 /* Union */) { + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0 /* None */); + } + if (flags & 2097152 /* Intersection */) { + // When an intersection contains a primitive type we ignore object type constituents as they are + // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. + ignoreObjects || (ignoreObjects = maybeTypeOfKind(type, 131068 /* Primitive */)); + return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t, ignoreObjects); }, 16777215 /* All */); } return 16777215 /* All */; } @@ -63393,18 +65316,16 @@ var ts; return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { - if (defaultExpression) { - var defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]); - } - return type; + return defaultExpression ? + getUnionType([getNonUndefinedType(type), getTypeOfExpression(defaultExpression)]) : + type; } function getTypeOfDestructuredProperty(type, name) { var nameType = getLiteralTypeFromPropertyName(name); if (!isTypeUsableAsPropertyName(nameType)) return errorType; var text = getPropertyNameFromType(nameType); - return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || + return getTypeOfPropertyOfType(type, text) || isNumericLiteralName(text) && includeUndefinedInIndexSignature(getIndexTypeOfType(type, 1 /* Number */)) || includeUndefinedInIndexSignature(getIndexTypeOfType(type, 0 /* String */)) || errorType; @@ -63425,15 +65346,15 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) || errorType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 199 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 288 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 200 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 289 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 216 /* BinaryExpression */ && parent.parent.left === parent || - parent.parent.kind === 239 /* ForOfStatement */ && parent.parent.initializer === parent; + return parent.parent.kind === 217 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 240 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); @@ -63450,21 +65371,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return stringType; - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return checkRightHandSideOfForOf(parent) || errorType; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return undefinedType; - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return getAssignedTypeOfSpreadExpression(parent); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return errorType; @@ -63472,7 +65393,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 196 /* ObjectBindingPattern */ ? + var type = pattern.kind === 197 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : @@ -63490,30 +65411,30 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 238 /* ForInStatement */) { + if (node.parent.parent.kind === 239 /* ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 239 /* ForOfStatement */) { + if (node.parent.parent.kind === 240 /* ForOfStatement */) { return checkRightHandSideOfForOf(node.parent.parent) || errorType; } return errorType; } function getInitialType(node) { - return node.kind === 249 /* VariableDeclaration */ ? + return node.kind === 250 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function isEmptyArrayAssignment(node) { - return node.kind === 249 /* VariableDeclaration */ && node.initializer && + return node.kind === 250 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 198 /* BindingElement */ && node.parent.kind === 216 /* BinaryExpression */ && + node.kind !== 199 /* BindingElement */ && node.parent.kind === 217 /* BinaryExpression */ && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (node.operatorToken.kind) { case 62 /* EqualsToken */: case 74 /* BarBarEqualsToken */: @@ -63528,13 +65449,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 207 /* ParenthesizedExpression */ || - parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node || - parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? + return parent.kind === 208 /* ParenthesizedExpression */ || + parent.kind === 217 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node || + parent.kind === 217 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 284 /* CaseClause */) { + if (clause.kind === 285 /* CaseClause */) { return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); } return neverType; @@ -63554,7 +65475,7 @@ var ts; var witnesses = []; for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { var clause = _a[_i]; - if (clause.kind === 284 /* CaseClause */) { + if (clause.kind === 285 /* CaseClause */) { if (ts.isStringLiteralLike(clause.expression)) { witnesses.push(clause.expression.text); continue; @@ -63590,14 +65511,40 @@ var ts; function forEachType(type, f) { return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type); } + function someType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.some(type.types, f) : f(type); + } function everyType(type, f) { return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); } + function everyContainedType(type, f) { + return type.flags & 3145728 /* UnionOrIntersection */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 1048576 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); + if (filtered === types) { + return type; + } + var origin = type.origin; + var newOrigin = void 0; + if (origin && origin.flags & 1048576 /* Union */) { + // If the origin type is a (denormalized) union type, filter its non-union constituents. If that ends + // up removing a smaller number of types than in the normalized constituent set (meaning some of the + // filtered types are within nested unions in the origin), then we can't construct a new origin type. + // Otherwise, if we have exactly one type left in the origin set, return that as the filtered type. + // Otherwise, construct a new filtered origin type. + var originTypes = origin.types; + var originFiltered = ts.filter(originTypes, function (t) { return !!(t.flags & 1048576 /* Union */) || f(t); }); + if (originTypes.length - originFiltered.length === types.length - filtered.length) { + if (originFiltered.length === 1) { + return originFiltered[0]; + } + newOrigin = createOriginUnionOrIntersectionType(1048576 /* Union */, originFiltered); + } + } + return getUnionTypeFromSortedList(filtered, type.objectFlags, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, newOrigin); } return type.flags & 131072 /* Never */ || f(type) ? type : neverType; } @@ -63630,6 +65577,11 @@ var ts; } return changed ? mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : type; } + function mapTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) { + return type.flags & 1048576 /* Union */ && aliasSymbol ? + getUnionType(ts.map(type.types, mapper), 1 /* Literal */, aliasSymbol, aliasTypeArguments) : + mapType(type, mapper); + } function getConstituentCount(type) { return type.flags & 3145728 /* UnionOrIntersection */ ? type.types.length : 1; } @@ -63715,12 +65667,12 @@ var ts; var root = getReferenceRoot(node); var parent = root.parent; var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" || - parent.parent.kind === 203 /* CallExpression */ + parent.parent.kind === 204 /* CallExpression */ && ts.isIdentifier(parent.name) && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 202 /* ElementAccessExpression */ && + var isElementAssignment = parent.kind === 203 /* ElementAccessExpression */ && parent.expression === root && - parent.parent.kind === 216 /* BinaryExpression */ && + parent.parent.kind === 217 /* BinaryExpression */ && parent.parent.operatorToken.kind === 62 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && @@ -63728,8 +65680,8 @@ var ts; return isLengthPushOrUnshift || isElementAssignment; } function isDeclarationWithExplicitTypeAnnotation(declaration) { - return (declaration.kind === 249 /* VariableDeclaration */ || declaration.kind === 160 /* Parameter */ || - declaration.kind === 163 /* PropertyDeclaration */ || declaration.kind === 162 /* PropertySignature */) && + return (declaration.kind === 250 /* VariableDeclaration */ || declaration.kind === 161 /* Parameter */ || + declaration.kind === 164 /* PropertyDeclaration */ || declaration.kind === 163 /* PropertySignature */) && !!ts.getEffectiveTypeAnnotationNode(declaration); } function getExplicitTypeOfSymbol(symbol, diagnostic) { @@ -63748,7 +65700,7 @@ var ts; if (isDeclarationWithExplicitTypeAnnotation(declaration)) { return getTypeOfSymbol(symbol); } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 240 /* ForOfStatement */) { var statement = declaration.parent.parent; var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined); if (expressionType) { @@ -63776,11 +65728,25 @@ var ts; return getExplicitThisType(node); case 105 /* SuperKeyword */: return checkSuperExpression(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: { var type = getTypeOfDottedName(node.expression, diagnostic); - var prop = type && getPropertyOfType(type, node.name.escapedText); - return prop && getExplicitTypeOfSymbol(prop, diagnostic); - case 207 /* ParenthesizedExpression */: + if (type) { + var name = node.name; + var prop = void 0; + if (ts.isPrivateIdentifier(name)) { + if (!type.symbol) { + return undefined; + } + prop = getPropertyOfType(type, ts.getSymbolNameForPrivateIdentifier(type.symbol, name.escapedText)); + } + else { + prop = getPropertyOfType(type, name.escapedText); + } + return prop && getExplicitTypeOfSymbol(prop, diagnostic); + } + return undefined; + } + case 208 /* ParenthesizedExpression */: return getTypeOfDottedName(node.expression, diagnostic); } } @@ -63794,7 +65760,7 @@ var ts; // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call // target expression of an assertion. var funcType = void 0; - if (node.parent.kind === 233 /* ExpressionStatement */) { + if (node.parent.kind === 234 /* ExpressionStatement */) { funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined); } else if (node.expression.kind !== 105 /* SuperKeyword */) { @@ -63838,7 +65804,7 @@ var ts; } function isFalseExpression(expr) { var node = ts.skipParentheses(expr); - return node.kind === 94 /* FalseKeyword */ || node.kind === 216 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + return node.kind === 94 /* FalseKeyword */ || node.kind === 217 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); } function isReachableFlowNodeWorker(flow, noCacheCheck) { @@ -63973,7 +65939,7 @@ var ts; // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); - if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 225 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { + if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 226 /* NonNullExpression */ && !(resultType.flags & 131072 /* Never */) && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { return declaredType; } return resultType; @@ -63988,7 +65954,7 @@ var ts; 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. - ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); flowAnalysisDisabled = true; reportFlowControlError(reference); return errorType; @@ -64057,8 +66023,8 @@ var ts; // Check if we should continue with the control flow of the containing function. var container = flow.node; if (container && container !== flowContainer && - reference.kind !== 201 /* PropertyAccessExpression */ && - reference.kind !== 202 /* ElementAccessExpression */ && + reference.kind !== 202 /* PropertyAccessExpression */ && + reference.kind !== 203 /* ElementAccessExpression */ && reference.kind !== 107 /* ThisKeyword */) { flow = container.flowNode; continue; @@ -64083,7 +66049,7 @@ var ts; } function getInitialOrAssignedType(flow) { var node = flow.node; - return getConstraintForLocation(node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */ ? + return getNarrowableTypeForReference(node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */ ? getInitialType(node) : getAssignedType(node), reference); } @@ -64123,14 +66089,14 @@ var ts; // 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 === 208 /* FunctionExpression */ || init.kind === 209 /* ArrowFunction */)) { + if (init && (init.kind === 209 /* FunctionExpression */ || init.kind === 210 /* ArrowFunction */)) { return getTypeAtFlowNode(flow.antecedent); } } return declaredType; } // for (const _ in ref) acts as a nonnull on ref - if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 238 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 239 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); } // Assignment doesn't affect reference @@ -64141,7 +66107,7 @@ var ts; if (node.kind === 94 /* FalseKeyword */) { return unreachableNeverType; } - if (node.kind === 216 /* BinaryExpression */) { + if (node.kind === 217 /* BinaryExpression */) { if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); } @@ -64172,7 +66138,7 @@ var ts; function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 203 /* CallExpression */ ? + var expr = node.kind === 204 /* CallExpression */ ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { @@ -64180,7 +66146,7 @@ var ts; var type = getTypeFromFlowType(flowType); if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { var evolvedType_1 = type; - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); @@ -64228,7 +66194,7 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (expr.kind === 211 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + else if (expr.kind === 212 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else { @@ -64236,12 +66202,12 @@ var ts; if (optionalChainContainsReference(expr, reference)) { type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); }); } - else if (expr.kind === 211 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { + else if (expr.kind === 212 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); }); } } if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + type = narrowTypeBySwitchOnDiscriminantProperty(type, expr, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } } return createFlowType(type, isIncomplete(flowType)); @@ -64412,16 +66378,42 @@ var ts; if (propName === undefined) { return type; } - var propType = getTypeOfPropertyOfType(type, propName); + var removeNullable = strictNullChecks && ts.isOptionalChain(access) && maybeTypeOfKind(type, 98304 /* Nullable */); + var propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type, propName); if (!propType) { return type; } + propType = removeNullable ? getOptionalType(propType) : propType; var narrowedPropType = narrowType(propType); return filterType(type, function (t) { var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName); return !(discriminantType.flags & 131072 /* Never */) && isTypeComparableTo(discriminantType, narrowedPropType); }); } + function narrowTypeByDiscriminantProperty(type, access, operator, value, assumeTrue) { + if ((operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) && type.flags & 1048576 /* Union */) { + var keyPropertyName = getKeyPropertyName(type); + if (keyPropertyName && keyPropertyName === getAccessedPropertyName(access)) { + var candidate_2 = getConstituentTypeForKeyType(type, getTypeOfExpression(value)); + if (candidate_2) { + return operator === (assumeTrue ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */) ? candidate_2 : + isUnitType(getTypeOfPropertyOfType(candidate_2, keyPropertyName) || unknownType) ? filterType(type, function (t) { return t !== candidate_2; }) : + type; + } + } + } + return narrowTypeByDiscriminant(type, access, function (t) { return narrowTypeByEquality(t, operator, value, assumeTrue); }); + } + function narrowTypeBySwitchOnDiscriminantProperty(type, access, switchStatement, clauseStart, clauseEnd) { + if (clauseStart < clauseEnd && type.flags & 1048576 /* Union */ && getKeyPropertyName(type) === getAccessedPropertyName(access)) { + var clauseTypes = getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd); + var candidate = getUnionType(ts.map(clauseTypes, function (t) { return getConstituentTypeForKeyType(type, t) || unknownType; })); + if (candidate !== unknownType) { + return candidate; + } + } + return narrowTypeByDiscriminant(type, access, function (t) { return narrowTypeBySwitchOnDiscriminant(t, switchStatement, clauseStart, clauseEnd); }); + } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); @@ -64445,7 +66437,8 @@ var ts; return !assumeTrue; } function narrowByInKeyword(type, literal, assumeTrue) { - if (type.flags & (1048576 /* Union */ | 524288 /* Object */) + if (type.flags & 1048576 /* Union */ + || type.flags & 524288 /* Object */ && declaredType !== type || isThisTypeParameter(type) || type.flags & 2097152 /* Intersection */ && ts.every(type.types, function (t) { return t.symbol !== globalThisSymbol; })) { var propName_1 = ts.escapeLeadingUnderscores(literal.text); @@ -64464,40 +66457,40 @@ var ts; case 35 /* ExclamationEqualsToken */: case 36 /* EqualsEqualsEqualsToken */: case 37 /* ExclamationEqualsEqualsToken */: - var operator_1 = expr.operatorToken.kind; - var left_1 = getReferenceCandidate(expr.left); - var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 211 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { - return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + var operator = expr.operatorToken.kind; + var left = getReferenceCandidate(expr.left); + var right = getReferenceCandidate(expr.right); + if (left.kind === 212 /* TypeOfExpression */ && ts.isStringLiteralLike(right)) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); } - if (right_1.kind === 211 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { - return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + if (right.kind === 212 /* TypeOfExpression */ && ts.isStringLiteralLike(left)) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); } - if (isMatchingReference(reference, left_1)) { - return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + if (isMatchingReference(reference, left)) { + return narrowTypeByEquality(type, operator, right, assumeTrue); } - if (isMatchingReference(reference, right_1)) { - return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + if (isMatchingReference(reference, right)) { + return narrowTypeByEquality(type, operator, left, assumeTrue); } if (strictNullChecks) { - if (optionalChainContainsReference(left_1, reference)) { - type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue); + if (optionalChainContainsReference(left, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator, right, assumeTrue); } - else if (optionalChainContainsReference(right_1, reference)) { - type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); + else if (optionalChainContainsReference(right, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator, left, assumeTrue); } } - if (isMatchingReferenceDiscriminant(left_1, type)) { - return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + if (isMatchingReferenceDiscriminant(left, type)) { + return narrowTypeByDiscriminantProperty(type, left, operator, right, assumeTrue); } - if (isMatchingReferenceDiscriminant(right_1, type)) { - return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + if (isMatchingReferenceDiscriminant(right, type)) { + return narrowTypeByDiscriminantProperty(type, right, operator, left, assumeTrue); } - if (isMatchingConstructorReference(left_1)) { - return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue); + if (isMatchingConstructorReference(left)) { + return narrowTypeByConstructor(type, operator, right, assumeTrue); } - if (isMatchingConstructorReference(right_1)) { - return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue); + if (isMatchingConstructorReference(right)) { + return narrowTypeByConstructor(type, operator, left, assumeTrue); } break; case 101 /* InstanceOfKeyword */: @@ -64562,13 +66555,12 @@ var ts; } if (assumeTrue) { var filterFn = operator === 34 /* EqualsEqualsToken */ ? - (function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); }) : + function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); } : function (t) { return areTypesComparable(t, valueType); }; return replacePrimitivesWithLiterals(filterType(type, filterFn), valueType); } if (isUnitType(valueType)) { - var regularType_1 = getRegularTypeOfLiteralType(valueType); - return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; }); + return filterType(type, function (t) { return !(isUnitLikeType(t) && areTypesComparable(t, valueType)); }); } return type; } @@ -64590,7 +66582,7 @@ var ts; if (assumeTrue && type.flags & 2 /* Unknown */ && literal.text === "object") { // The pattern x && typeof x === 'object', where x is of type unknown, narrows x to type object. We don't // need to check for the reverse typeof x === 'object' && x since that already narrows correctly. - if (typeOfExpr.parent.parent.kind === 216 /* BinaryExpression */) { + if (typeOfExpr.parent.parent.kind === 217 /* BinaryExpression */) { var expr = typeOfExpr.parent.parent; if (expr.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && expr.right === typeOfExpr.parent && containsTruthyCheck(reference, expr.left)) { return nonPrimitiveType; @@ -64646,7 +66638,7 @@ var ts; if (!hasDefaultClause) { return caseType; } - var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + var defaultType = filterType(type, function (t) { return !(isUnitLikeType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(extractUnitType(t)))); }); return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } function getImpliedTypeFromTypeofGuard(type, text) { @@ -64828,7 +66820,16 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { - return filterType(type, function (t) { return !isRelated(t, candidate); }); + return filterType(type, function (t) { + if (!isRelated(t, candidate)) { + return true; + } + var constraint = getBaseConstraintOfType(t); + if (constraint && constraint !== t) { + return !isRelated(constraint, candidate); + } + return false; + }); } // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. @@ -64838,10 +66839,15 @@ var ts; return assignableType; } } - // If the candidate type is a subtype of the target type, narrow to the candidate type, - // if the target type is a subtype of the candidate type, narrow to the target type, - // otherwise, narrow to an intersection of the two types. - return isTypeSubtypeOf(candidate, type) ? candidate : isTypeSubtypeOf(type, candidate) ? type : getIntersectionType([type, candidate]); + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -64884,17 +66890,17 @@ var ts; case 78 /* Identifier */: case 107 /* ThisKeyword */: case 105 /* SuperKeyword */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return narrowTypeByCallExpression(type, expr, assumeTrue); - case 207 /* ParenthesizedExpression */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: return narrowType(type, expr.expression, assumeTrue); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: if (expr.operator === 53 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } @@ -64918,17 +66924,20 @@ var ts; // an dotted name expression, and if the location is not an assignment target, obtain the type // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. - if (location.kind === 78 /* Identifier */) { + if (location.kind === 78 /* Identifier */ || location.kind === 79 /* PrivateIdentifier */) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { + if (ts.isExpressionNode(location) && (!ts.isAssignmentTarget(location) || ts.isWriteAccess(location))) { var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } } } + if (ts.isDeclarationName(location) && ts.isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) { + return resolveTypeOfAccessors(location.parent.symbol, /*writing*/ true); + } // The location isn't a reference to the given symbol, meaning we're being asked // a hypothetical question of what type the symbol would have if there was a reference // to it at the given location. Since we have no control flow information for the @@ -64939,13 +66948,16 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 257 /* ModuleBlock */ || - node.kind === 297 /* SourceFile */ || - node.kind === 163 /* PropertyDeclaration */; + node.kind === 258 /* ModuleBlock */ || + node.kind === 298 /* SourceFile */ || + node.kind === 164 /* PropertyDeclaration */; }); } // Check if a parameter is assigned anywhere within its declaring function. function isParameterAssigned(symbol) { + if (!symbol.valueDeclaration) { + return false; + } var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); if (!(links.flags & 8388608 /* AssignmentsMarked */)) { @@ -64963,7 +66975,7 @@ var ts; if (node.kind === 78 /* Identifier */) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 160 /* Parameter */) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 161 /* Parameter */) { symbol.isAssigned = true; } } @@ -64979,7 +66991,7 @@ var ts; function removeOptionalityFromDeclaredType(declaredType, declaration) { if (pushTypeResolution(declaration.symbol, 2 /* DeclaredType */)) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 160 /* Parameter */ && + declaration.kind === 161 /* Parameter */ && declaration.initializer && getFalsyFlags(declaredType) & 32768 /* Undefined */ && !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */); @@ -64993,23 +67005,40 @@ var ts; } function isConstraintPosition(node) { var parent = node.parent; - return parent.kind === 201 /* PropertyAccessExpression */ || - parent.kind === 203 /* CallExpression */ && parent.expression === node || - parent.kind === 202 /* ElementAccessExpression */ && parent.expression === node || - parent.kind === 198 /* BindingElement */ && parent.name === node && !!parent.initializer; - } - function typeHasNullableConstraint(type) { - return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 98304 /* Nullable */); - } - function getConstraintForLocation(type, node) { - // When a node is the left hand expression of a property access, element access, or call expression, - // and the type of the node includes type variables with constraints that are nullable, we fetch the - // apparent type of the node *before* performing control flow analysis such that narrowings apply to - // the constraint type. - if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { - return mapType(getWidenedType(type), getBaseConstraintOrType); - } - return type; + // In an element access obj[x], we consider obj to be in a constraint position only when x is not + // of a generic type. This is because when both obj and x are of generic types T and K, we want + // the resulting type to be T[K]. + return parent.kind === 202 /* PropertyAccessExpression */ || + parent.kind === 204 /* CallExpression */ && parent.expression === node || + parent.kind === 203 /* ElementAccessExpression */ && parent.expression === node && + !isGenericIndexType(getTypeOfExpression(parent.argumentExpression)); + } + function isGenericTypeWithUnionConstraint(type) { + return !!(type.flags & 465829888 /* Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* Nullable */ | 1048576 /* Union */)); + } + function containsGenericType(type) { + return !!(type.flags & 465829888 /* Instantiable */ || type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, containsGenericType)); + } + function hasContextualTypeWithNoGenericTypes(node) { + // Computing the contextual type for a child of a JSX element involves resolving the type of the + // element's tag name, so we exclude that here to avoid circularities. + var contextualType = (ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && + !((ts.isJsxOpeningElement(node.parent) || ts.isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && + getContextualType(node); + return contextualType && !someType(contextualType, containsGenericType); + } + function getNarrowableTypeForReference(type, reference, checkMode) { + // When the type of a reference is or contains an instantiable type with a union type constraint, and + // when the reference is in a constraint position (where it is known we'll obtain the apparent type) or + // has a contextual type containing no top-level instantiables (meaning constraints will determine + // assignability), we substitute constraints for all instantiables in the type of the reference to give + // control flow analysis an opportunity to narrow it further. For example, for a reference of a type + // parameter type 'T extends string | undefined' with a contextual type 'string', we substitute + // 'string | undefined' to give control flow analysis the opportunity to narrow to type 'string'. + var substituteConstraints = !(checkMode && checkMode & 2 /* Inferential */) && + someType(type, isGenericTypeWithUnionConstraint) && + (isConstraintPosition(reference) || hasContextualTypeWithNoGenericTypes(reference)); + return substituteConstraints ? mapType(type, function (t) { return t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type; } function isExportOrExportExpression(location) { return !!ts.findAncestor(location, function (e) { return e.parent && ts.isExportAssignment(e.parent) && e.parent.expression === e && ts.isEntityNameExpression(e); }); @@ -65018,7 +67047,12 @@ var ts; if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { var target = resolveAlias(symbol); if (target.flags & 111551 /* Value */) { - if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(target)) { + // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled + // (because the const enum value will not be inlined), or if (2) the alias is an export + // of a const enum declaration that will be preserved. + if (compilerOptions.isolatedModules || + ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || + !isConstEnumOrConstEnumOnlyModule(target)) { markAliasSymbolAsReferenced(symbol); } else { @@ -65027,7 +67061,7 @@ var ts; } } } - function checkIdentifier(node) { + function checkIdentifier(node, checkMode) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { return errorType; @@ -65041,7 +67075,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2 /* ES2015 */) { - if (container.kind === 209 /* ArrowFunction */) { + if (container.kind === 210 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasSyntacticModifier(container, 256 /* Async */)) { @@ -65058,15 +67092,15 @@ var ts; } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var sourceSymbol = localOrExportSymbol.flags & 2097152 /* Alias */ ? resolveAlias(localOrExportSymbol) : localOrExportSymbol; - if (getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) { - errorOrSuggestion(/* isError */ false, node, ts.Diagnostics._0_is_deprecated, node.escapedText); + if (sourceSymbol.declarations && getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) { + addDeprecatedSuggestion(node, sourceSymbol.declarations, node.escapedText); } var declaration = localOrExportSymbol.valueDeclaration; - if (localOrExportSymbol.flags & 32 /* Class */) { + if (declaration && localOrExportSymbol.flags & 32 /* Class */) { // 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. - if (declaration.kind === 252 /* ClassDeclaration */ + if (declaration.kind === 253 /* ClassDeclaration */ && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -65078,14 +67112,14 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration.kind === 221 /* ClassExpression */) { + else if (declaration.kind === 222 /* ClassExpression */) { // When we emit a class expression with static members that contain a reference // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container.kind !== 297 /* SourceFile */) { + while (container.kind !== 298 /* SourceFile */) { if (container.parent === declaration) { - if (container.kind === 163 /* PropertyDeclaration */ && ts.hasSyntacticModifier(container, 32 /* Static */)) { + if (container.kind === 164 /* PropertyDeclaration */ && ts.hasSyntacticModifier(container, 32 /* Static */)) { getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } @@ -65096,12 +67130,18 @@ var ts; } } checkNestedBlockScopedBinding(node, symbol); - var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); + var type = getTypeOfSymbol(localOrExportSymbol); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + var assignmentError = localOrExportSymbol.flags & 384 /* Enum */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_an_enum + : localOrExportSymbol.flags & 32 /* Class */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_class + : localOrExportSymbol.flags & 1536 /* Module */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_namespace + : localOrExportSymbol.flags & 16 /* Function */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_function + : localOrExportSymbol.flags & 2097152 /* Alias */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_an_import + : ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable; + error(node, assignmentError, symbolToString(symbol)); return errorType; } if (isReadonlySymbol(localOrExportSymbol)) { @@ -65123,7 +67163,7 @@ var ts; } } else if (isAlias) { - declaration = ts.find(symbol.declarations, isSomeImportDeclaration); + declaration = getDeclarationOfAliasSymbol(symbol); } else { return type; @@ -65131,10 +67171,11 @@ var ts; if (!declaration) { return type; } + type = getNarrowableTypeForReference(type, node, checkMode); // The declaration container is the innermost function that encloses the declaration of the variable // or parameter. The flow container is the innermost function starting with which we analyze the control // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 160 /* Parameter */; + var isParameter = ts.getRootDeclaration(declaration).kind === 161 /* Parameter */; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; @@ -65143,8 +67184,8 @@ var ts; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === 208 /* FunctionExpression */ || - flowContainer.kind === 209 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 209 /* FunctionExpression */ || + flowContainer.kind === 210 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } @@ -65153,9 +67194,9 @@ var ts; // declaration container are the same). var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 || - isInTypeQuery(node) || node.parent.kind === 270 /* ExportSpecifier */) || - node.parent.kind === 225 /* NonNullExpression */ || - declaration.kind === 249 /* VariableDeclaration */ && declaration.exclamationToken || + isInTypeQuery(node) || node.parent.kind === 271 /* ExportSpecifier */) || + node.parent.kind === 226 /* NonNullExpression */ || + declaration.kind === 250 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 8388608 /* Ambient */; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : type === autoType || type === autoArrayType ? undefinedType : @@ -65180,17 +67221,21 @@ var ts; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } - function isInsideFunction(node, threshold) { - return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); + function isInsideFunctionOrInstancePropertyInitializer(node, threshold) { + return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n) || (n.parent && ts.isPropertyDeclaration(n.parent) && !ts.hasStaticModifier(n.parent) && n.parent.initializer === n); }); } 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 getEnclosingIterationStatement(node) { + return ts.findAncestor(node, function (n) { return (!n || ts.nodeStartsNewLexicalEnvironment(n)) ? "quit" : ts.isIterationStatement(n, /*lookInLabeledStatements*/ false); }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || + !symbol.valueDeclaration || ts.isSourceFile(symbol.valueDeclaration) || - symbol.valueDeclaration.parent.kind === 287 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 288 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -65198,22 +67243,14 @@ var ts; // 2. walk from the declaration up to the boundary of lexical environment and check // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - var usedInFunction = isInsideFunction(node.parent, container); - var current = container; - var containedInIterationStatement = false; - while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { - if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) { - containedInIterationStatement = true; - break; - } - current = current.parent; - } - if (containedInIterationStatement) { - if (usedInFunction) { + var isCaptured = isInsideFunctionOrInstancePropertyInitializer(node, container); + var enclosingIterationStatement = getEnclosingIterationStatement(container); + if (enclosingIterationStatement) { + if (isCaptured) { // mark iteration statement as containing block-scoped binding captured in some function var capturesBlockScopeBindingInLoopBody = true; if (ts.isForStatement(container)) { - var varDeclList = ts.getAncestor(symbol.valueDeclaration, 250 /* VariableDeclarationList */); + var varDeclList = ts.getAncestor(symbol.valueDeclaration, 251 /* VariableDeclarationList */); if (varDeclList && varDeclList.parent === container) { var part = getPartOfForStatementContainingNode(node.parent, container); if (part) { @@ -65228,13 +67265,13 @@ var ts; } } if (capturesBlockScopeBindingInLoopBody) { - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + getNodeLinks(enclosingIterationStatement).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 (ts.isForStatement(container)) { - var varDeclList = ts.getAncestor(symbol.valueDeclaration, 250 /* VariableDeclarationList */); + var varDeclList = ts.getAncestor(symbol.valueDeclaration, 251 /* VariableDeclarationList */); if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } @@ -65242,7 +67279,7 @@ var ts; // set 'declared inside loop' bit on the block-scoped binding getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } - if (usedInFunction) { + if (isCaptured) { getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } @@ -65253,7 +67290,7 @@ var ts; function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; - while (current.parent.kind === 207 /* ParenthesizedExpression */) { + while (current.parent.kind === 208 /* ParenthesizedExpression */) { current = current.parent; } // check if node is used as LHS in some assignment expression @@ -65261,7 +67298,7 @@ var ts; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 214 /* PrefixUnaryExpression */ || current.parent.kind === 215 /* PostfixUnaryExpression */)) { + else if ((current.parent.kind === 215 /* PrefixUnaryExpression */ || current.parent.kind === 216 /* PostfixUnaryExpression */)) { var expr = current.parent; isAssigned = expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */; } @@ -65274,7 +67311,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 163 /* PropertyDeclaration */ || container.kind === 166 /* Constructor */) { + if (container.kind === 164 /* PropertyDeclaration */ || container.kind === 167 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -65314,37 +67351,37 @@ var ts; // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var capturedByArrowFunction = false; - if (container.kind === 166 /* Constructor */) { + if (container.kind === 167 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 209 /* ArrowFunction */) { + if (container.kind === 210 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); capturedByArrowFunction = true; } switch (container.kind) { - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 166 /* Constructor */: + case 167 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -65432,7 +67469,7 @@ var ts; } function getClassNameFromPrototypeMethod(container) { // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 208 /* FunctionExpression */ && + if (container.kind === 209 /* FunctionExpression */ && ts.isBinaryExpression(container.parent) && ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { // Get the 'x' of 'x.prototype.y = container' @@ -65442,16 +67479,16 @@ var ts; .expression; // x } // x.prototype = { method() { } } - else if (container.kind === 165 /* MethodDeclaration */ && - container.parent.kind === 200 /* ObjectLiteralExpression */ && + else if (container.kind === 166 /* MethodDeclaration */ && + container.parent.kind === 201 /* 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 === 208 /* FunctionExpression */ && - container.parent.kind === 288 /* PropertyAssignment */ && - container.parent.parent.kind === 200 /* ObjectLiteralExpression */ && + else if (container.kind === 209 /* FunctionExpression */ && + container.parent.kind === 289 /* PropertyAssignment */ && + container.parent.parent.kind === 201 /* ObjectLiteralExpression */ && ts.isBinaryExpression(container.parent.parent.parent) && ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { return container.parent.parent.parent.left.expression; @@ -65459,7 +67496,7 @@ var ts; // Object.defineProperty(x, "method", { value: function() { } }); // Object.defineProperty(x, "method", { set: (x: () => void) => void }); // Object.defineProperty(x, "method", { get: () => function() { }) }); - else if (container.kind === 208 /* FunctionExpression */ && + else if (container.kind === 209 /* FunctionExpression */ && ts.isPropertyAssignment(container.parent) && ts.isIdentifier(container.parent.name) && (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && @@ -65484,7 +67521,7 @@ var ts; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 308 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 309 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -65498,16 +67535,16 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 160 /* Parameter */ && n.parent === constructorDecl; }); + return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 161 /* Parameter */ && n.parent === constructorDecl; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 203 /* CallExpression */ && node.parent.expression === node; + var isCallExpression = node.parent.kind === 204 /* CallExpression */ && node.parent.expression === node; var immediateContainer = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var container = immediateContainer; var needToCaptureLexicalThis = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - while (container && container.kind === 209 /* ArrowFunction */) { + while (container && container.kind === 210 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } @@ -65520,14 +67557,14 @@ var ts; // class B { // [super.foo()]() {} // } - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 158 /* ComputedPropertyName */; }); - if (current && current.kind === 158 /* ComputedPropertyName */) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 159 /* ComputedPropertyName */; }); + if (current && current.kind === 159 /* ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 200 /* ObjectLiteralExpression */)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 201 /* ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -65535,7 +67572,7 @@ var ts; } return errorType; } - if (!isCallExpression && immediateContainer.kind === 166 /* Constructor */) { + if (!isCallExpression && immediateContainer.kind === 167 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } if (ts.hasSyntacticModifier(container, 32 /* Static */) || isCallExpression) { @@ -65604,7 +67641,7 @@ var ts; // 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 === 165 /* MethodDeclaration */ && ts.hasSyntacticModifier(container, 256 /* Async */)) { + if (container.kind === 166 /* MethodDeclaration */ && ts.hasSyntacticModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } @@ -65618,7 +67655,7 @@ var ts; // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 200 /* ObjectLiteralExpression */) { + if (container.parent.kind === 201 /* ObjectLiteralExpression */) { if (languageVersion < 2 /* ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return errorType; @@ -65639,7 +67676,7 @@ var ts; if (!baseClassType) { return errorType; } - if (container.kind === 166 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 167 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return errorType; @@ -65654,7 +67691,7 @@ var ts; if (isCallExpression) { // TS 1.0 SPEC (April 2014): 4.8.1 // Super calls are only permitted in constructors of derived classes - return container.kind === 166 /* Constructor */; + return container.kind === 167 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -65662,21 +67699,21 @@ var ts; // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance // - In a static member function or static member accessor // topmost container must be something that is directly nested in the class declaration\object literal expression - if (ts.isClassLike(container.parent) || container.parent.kind === 200 /* ObjectLiteralExpression */) { + if (ts.isClassLike(container.parent) || container.parent.kind === 201 /* ObjectLiteralExpression */) { if (ts.hasSyntacticModifier(container, 32 /* Static */)) { - return container.kind === 165 /* MethodDeclaration */ || - container.kind === 164 /* MethodSignature */ || - container.kind === 167 /* GetAccessor */ || - container.kind === 168 /* SetAccessor */; + return container.kind === 166 /* MethodDeclaration */ || + container.kind === 165 /* MethodSignature */ || + container.kind === 168 /* GetAccessor */ || + container.kind === 169 /* SetAccessor */; } else { - return container.kind === 165 /* MethodDeclaration */ || - container.kind === 164 /* MethodSignature */ || - container.kind === 167 /* GetAccessor */ || - container.kind === 168 /* SetAccessor */ || - container.kind === 163 /* PropertyDeclaration */ || - container.kind === 162 /* PropertySignature */ || - container.kind === 166 /* Constructor */; + return container.kind === 166 /* MethodDeclaration */ || + container.kind === 165 /* MethodSignature */ || + container.kind === 168 /* GetAccessor */ || + container.kind === 169 /* SetAccessor */ || + container.kind === 164 /* PropertyDeclaration */ || + container.kind === 163 /* PropertySignature */ || + container.kind === 167 /* Constructor */; } } } @@ -65684,10 +67721,10 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 165 /* MethodDeclaration */ || - func.kind === 167 /* GetAccessor */ || - func.kind === 168 /* SetAccessor */) && func.parent.kind === 200 /* ObjectLiteralExpression */ ? func.parent : - func.kind === 208 /* FunctionExpression */ && func.parent.kind === 288 /* PropertyAssignment */ ? func.parent.parent : + return (func.kind === 166 /* MethodDeclaration */ || + func.kind === 168 /* GetAccessor */ || + func.kind === 169 /* SetAccessor */) && func.parent.kind === 201 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 209 /* FunctionExpression */ && func.parent.kind === 289 /* PropertyAssignment */ ? func.parent.parent : undefined; } function getThisTypeArgument(type) { @@ -65699,7 +67736,7 @@ var ts; }); } function getContextualThisParameterType(func) { - if (func.kind === 209 /* ArrowFunction */) { + if (func.kind === 210 /* ArrowFunction */) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -65726,7 +67763,7 @@ var ts; if (thisType) { return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral))); } - if (literal.parent.kind !== 288 /* PropertyAssignment */) { + if (literal.parent.kind !== 289 /* PropertyAssignment */) { break; } literal = literal.parent.parent; @@ -65740,7 +67777,7 @@ var ts; // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. var parent = ts.walkUpParenthesizedExpressions(func.parent); - if (parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) { + if (parent.kind === 217 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) { var target = parent.left; if (ts.isAccessExpression(target)) { var expression = target.expression; @@ -65793,11 +67830,11 @@ var ts; return getTypeFromTypeNode(typeNode); } switch (declaration.kind) { - case 160 /* Parameter */: + case 161 /* Parameter */: return getContextuallyTypedParameterType(declaration); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return getContextualTypeForBindingElement(declaration); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: if (ts.hasSyntacticModifier(declaration, 32 /* Static */)) { return getContextualTypeForStaticPropertyDeclaration(declaration); } @@ -65808,10 +67845,10 @@ var ts; var parent = declaration.parent.parent; var name = declaration.propertyName || declaration.name; var parentType = getContextualTypeForVariableLikeDeclaration(parent) || - parent.kind !== 198 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent); + parent.kind !== 199 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent); if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name)) return undefined; - if (parent.name.kind === 197 /* ArrayBindingPattern */) { + if (parent.name.kind === 198 /* ArrayBindingPattern */) { var index = ts.indexOfNode(declaration.parent.elements, declaration); if (index < 0) return undefined; @@ -65948,7 +67985,7 @@ var ts; return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 205 /* TaggedTemplateExpression */) { + if (template.parent.kind === 206 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -65982,16 +68019,16 @@ var ts; // In an assignment expression, the right operand is contextually typed by the type of the left operand. // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. function getContextualTypeForAssignmentDeclaration(binaryExpression) { + var _a, _b; var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return getTypeOfExpression(binaryExpression.left); + case 4 /* ThisProperty */: + return getContextualTypeForThisPropertyAssignment(binaryExpression); case 5 /* Property */: - case 1 /* ExportsProperty */: - case 6 /* Prototype */: - case 3 /* PrototypeProperty */: if (isPossiblyAliasedThisProperty(binaryExpression, kind)) { - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + return getContextualTypeForThisPropertyAssignment(binaryExpression); } // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. // See `bindStaticPropertyAssignment` in `binder.ts`. @@ -66012,11 +68049,11 @@ var ts; var id = lhs.expression; var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true); if (parentSymbol) { - var annotated = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); - if (annotated) { + var annotated_1 = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated_1) { var nameStr = ts.getElementOrPropertyAccessName(lhs); if (nameStr !== undefined) { - return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr); + return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated_1), nameStr); } } return undefined; @@ -66024,9 +68061,15 @@ var ts; } return ts.isInJSFile(decl) ? undefined : getTypeOfExpression(binaryExpression.left); } + case 1 /* ExportsProperty */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + var valueDeclaration = (_a = binaryExpression.left.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration; + // falls through case 2 /* ModuleExports */: - case 4 /* ThisProperty */: - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + valueDeclaration || (valueDeclaration = (_b = binaryExpression.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration); + var annotated = valueDeclaration && ts.getEffectiveTypeAnnotationNode(valueDeclaration); + return annotated ? getTypeFromTypeNode(annotated) : undefined; case 7 /* ObjectDefinePropertyValue */: case 8 /* ObjectDefinePropertyExports */: case 9 /* ObjectDefinePrototypeProperty */: @@ -66047,7 +68090,7 @@ var ts; var symbol = resolveName(declaration.left, name, 111551 /* Value */, undefined, undefined, /*isUse*/ true, /*excludeGlobals*/ true); return ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration); } - function getContextualTypeForThisPropertyAssignment(binaryExpression, kind) { + function getContextualTypeForThisPropertyAssignment(binaryExpression) { if (!binaryExpression.symbol) return getTypeOfExpression(binaryExpression.left); if (binaryExpression.symbol.valueDeclaration) { @@ -66059,8 +68102,6 @@ var ts; } } } - if (kind === 2 /* ModuleExports */) - return undefined; var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression); if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { return undefined; @@ -66115,9 +68156,13 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + if (propertyAssignmentType) { + return propertyAssignmentType; + } var type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { - if (!hasNonBindableDynamicName(element)) { + if (hasBindableName(element)) { // 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. @@ -66203,19 +68248,19 @@ var ts; case 78 /* Identifier */: case 150 /* UndefinedKeyword */: return true; - case 201 /* PropertyAccessExpression */: - case 207 /* ParenthesizedExpression */: + case 202 /* PropertyAccessExpression */: + case 208 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); - case 283 /* JsxExpression */: + case 284 /* 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 === 288 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 289 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 280 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. @@ -66226,15 +68271,9 @@ var ts; var instantiatedType = instantiateContextualType(contextualType, node, contextFlags); if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) { var apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true); - if (apparentType.flags & 1048576 /* Union */) { - if (ts.isObjectLiteralExpression(node)) { - return discriminateContextualTypeByObjectMembers(node, apparentType); - } - else if (ts.isJsxAttributes(node)) { - return discriminateContextualTypeByJSXAttributes(node, apparentType); - } - } - return apparentType; + return apparentType.flags & 1048576 /* Union */ && ts.isObjectLiteralExpression(node) ? discriminateContextualTypeByObjectMembers(node, apparentType) : + apparentType.flags & 1048576 /* Union */ && ts.isJsxAttributes(node) ? discriminateContextualTypeByJSXAttributes(node, apparentType) : + apparentType; } } // If the given contextual type contains instantiable types and if a mapper representing @@ -66301,58 +68340,60 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 198 /* BindingElement */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 199 /* BindingElement */: return getContextualTypeForInitializerExpression(node, contextFlags); - case 209 /* ArrowFunction */: - case 242 /* ReturnStatement */: + case 210 /* ArrowFunction */: + case 243 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return getContextualTypeForAwaitOperand(parent, contextFlags); - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (parent.expression.kind === 99 /* ImportKeyword */) { return stringType; } /* falls through */ - case 204 /* NewExpression */: + case 205 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return ts.isConstTypeReference(parent.type) ? tryFindWhenConstTypeReference(parent) : getTypeFromTypeNode(parent.type); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node, contextFlags); - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent, contextFlags); - case 290 /* SpreadAssignment */: - return getApparentTypeOfContextualType(parent.parent, contextFlags); - case 199 /* ArrayLiteralExpression */: { + case 291 /* SpreadAssignment */: + return getContextualType(parent.parent, contextFlags); + case 200 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node, contextFlags); - case 228 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 218 /* TemplateExpression */); + case 229 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 219 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 207 /* ParenthesizedExpression */: { + case 208 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags); } - case 283 /* JsxExpression */: + case 226 /* NonNullExpression */: + return getContextualType(parent, contextFlags); + case 284 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); - case 280 /* JsxAttribute */: - case 282 /* JsxSpreadAttribute */: + case 281 /* JsxAttribute */: + case 283 /* JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent); - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent, contextFlags); } return undefined; @@ -66388,14 +68429,14 @@ var ts; return propsType; } function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { - if (sig.unionSignatures) { + if (sig.compositeSignatures) { // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature, // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur // for a union signature). It's an unfortunate quirk of looking in the output of the signature for the type we want to use for the input. // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane. var results = []; - for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) { + for (var _i = 0, _a = sig.compositeSignatures; _i < _a.length; _i++) { var signature = _a[_i]; var instance = getReturnTypeOfSignature(signature); if (isTypeAny(instance)) { @@ -66407,7 +68448,7 @@ var ts; } results.push(propType); } - return getIntersectionType(results); + return getIntersectionType(results); // Same result for both union and intersection signatures } var instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); @@ -66432,16 +68473,19 @@ var ts; function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { var managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { - var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); // fetches interface type, or initializes symbol links type parmaeters var ctorType = getStaticTypeOfReferencedJsxConstructor(context); + if (managedSym.flags & 524288 /* TypeAlias */) { + var params = getSymbolLinks(managedSym).typeParameters; + if (ts.length(params) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], params, 2, ts.isInJSFile(context)); + return getTypeAliasInstantiation(managedSym, args); + } + } if (ts.length(declaredManagedType.typeParameters) >= 2) { var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } - else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); - return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); - } } return attributesType; } @@ -66486,16 +68530,93 @@ var ts; return apparentAttributesType; } } + function getIntersectedSignatures(signatures) { + return ts.getStrictOptionValue(compilerOptions, "noImplicitAny") + ? ts.reduceLeft(signatures, function (left, right) { + return left === right || !left ? left + : compareTypeParametersIdentical(left.typeParameters, right.typeParameters) ? combineSignaturesOfIntersectionMembers(left, right) + : undefined; + }) + : undefined; + } + function combineIntersectionThisParam(left, right, mapper) { + if (!left || !right) { + return left || right; + } + // A signature `this` type might be a read or a write position... It's very possible that it should be invariant + // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be + // pessimistic when contextual typing, for now, we'll union the `this` types. + var thisType = getUnionType([getTypeOfSymbol(left), instantiateType(getTypeOfSymbol(right), mapper)]); + return createSymbolWithType(left, thisType); + } + function combineIntersectionParameters(left, right, mapper) { + var leftCount = getParameterCount(left); + var rightCount = getParameterCount(right); + var longest = leftCount >= rightCount ? left : right; + var shorter = longest === left ? right : left; + var longestCount = longest === left ? leftCount : rightCount; + var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right)); + var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest); + var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0)); + for (var i = 0; i < longestCount; i++) { + var longestParamType = tryGetTypeAtPosition(longest, i); + if (longest === right) { + longestParamType = instantiateType(longestParamType, mapper); + } + var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType; + if (shorter === right) { + shorterParamType = instantiateType(shorterParamType, mapper); + } + var unionParamType = getUnionType([longestParamType, shorterParamType]); + var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1); + var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter); + var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i); + var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i); + var paramName = leftName === rightName ? leftName : + !leftName ? rightName : + !rightName ? leftName : + undefined; + var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg" + i); + paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType; + params[i] = paramSymbol; + } + if (needsExtraRestElement) { + var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args"); + restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount)); + if (shorter === right) { + restParamSymbol.type = instantiateType(restParamSymbol.type, mapper); + } + params[longestCount] = restParamSymbol; + } + return params; + } + function combineSignaturesOfIntersectionMembers(left, right) { + var typeParams = left.typeParameters || right.typeParameters; + var paramMapper; + if (left.typeParameters && right.typeParameters) { + paramMapper = createTypeMapper(right.typeParameters, left.typeParameters); + // We just use the type parameter defaults from the first signature + } + var declaration = left.declaration; + var params = combineIntersectionParameters(left, right, paramMapper); + var thisParam = combineIntersectionThisParam(left.thisParameter, right.thisParameter, paramMapper); + var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); + var result = createSignature(declaration, typeParams, thisParam, params, + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 39 /* PropagatingFlags */); + result.compositeKind = 2097152 /* Intersection */; + result.compositeSignatures = ts.concatenate(left.compositeKind === 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); + if (paramMapper) { + result.mapper = left.compositeKind === 2097152 /* Intersection */ && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; + } + return result; + } // If the given type is an object or union type with a single signature, and if that signature has at // least as many parameters as the given function, return the signature. Otherwise return undefined. function getContextualCallSignature(type, node) { var signatures = getSignaturesOfType(type, 0 /* Call */); - if (signatures.length === 1) { - var signature = signatures[0]; - if (!isAritySmaller(signature, node)) { - return signature; - } - } + var applicableByArity = ts.filter(signatures, function (s) { return !isAritySmaller(s, node); }); + return applicableByArity.length === 1 ? applicableByArity[0] : getIntersectedSignatures(applicableByArity); } /** If the contextual signature has fewer parameters than the function expression, do not use it */ function isAritySmaller(signature, target) { @@ -66512,7 +68633,7 @@ var ts; return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 208 /* FunctionExpression */ || node.kind === 209 /* ArrowFunction */; + return node.kind === 209 /* FunctionExpression */ || node.kind === 210 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -66526,7 +68647,7 @@ var ts; // all identical ignoring their return type, the result is same signature but with return type as // union type of return types from these signatures function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var typeTagSignature = getSignatureOfTypeTag(node); if (typeTagSignature) { return typeTagSignature; @@ -66574,8 +68695,8 @@ var ts; return node.isSpread ? getIndexedAccessType(node.type, numberType) : node.type; } function hasDefaultValue(node) { - return (node.kind === 198 /* BindingElement */ && !!node.initializer) || - (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */); + return (node.kind === 199 /* BindingElement */ && !!node.initializer) || + (node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */); } function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; @@ -66587,7 +68708,7 @@ var ts; var inConstContext = isConstContext(node); for (var i = 0; i < elementCount; i++) { var e = elements[i]; - if (e.kind === 220 /* SpreadElement */) { + if (e.kind === 221 /* SpreadElement */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */); } @@ -66630,7 +68751,7 @@ var ts; if (inDestructuringPattern) { return createTupleType(elementTypes, elementFlags); } - if (forceTuple || inConstContext || contextualType && forEachType(contextualType, isTupleLikeType)) { + if (forceTuple || inConstContext || contextualType && someType(contextualType, isTupleLikeType)) { return createArrayLiteralType(createTupleType(elementTypes, elementFlags, /*readonly*/ inConstContext)); } return createArrayLiteralType(createArrayType(elementTypes.length ? @@ -66644,13 +68765,13 @@ var ts; var literalType = type.literalType; if (!literalType) { literalType = type.literalType = cloneTypeReference(type); - literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + literalType.objectFlags |= 32768 /* ArrayLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; } return literalType; } function isNumericName(name) { switch (name.kind) { - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return isNumericComputedName(name); case 78 /* Identifier */: return isNumericLiteralName(name.escapedText); @@ -66697,6 +68818,20 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); + // The computed property name of a non-static class field within a loop must be stored in a block-scoped binding. + // (It needs to be bound at class evaluation time.) + if (ts.isPropertyDeclaration(node.parent) && !ts.hasStaticModifier(node.parent) && ts.isClassExpression(node.parent.parent)) { + var container = ts.getEnclosingBlockScopeContainer(node.parent.parent); + var enclosingIterationStatement = getEnclosingIterationStatement(container); + if (enclosingIterationStatement) { + // The computed field name will use a block scoped binding which can be unique for each iteration of the loop. + getNodeLinks(enclosingIterationStatement).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + // The generated variable which stores the computed field name must be block-scoped. + getNodeLinks(node).flags |= 524288 /* BlockScopedBindingInLoop */; + // The generated variable which stores the class must be block-scoped. + getNodeLinks(node.parent.parent).flags |= 524288 /* BlockScopedBindingInLoop */; + } + } // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). if (links.resolvedType.flags & 98304 /* Nullable */ || @@ -66704,9 +68839,6 @@ var ts; !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } - else { - checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true); - } } return links.resolvedType; } @@ -66746,7 +68878,7 @@ var ts; var spread = emptyObjectType; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 196 /* ObjectBindingPattern */ || contextualType.pattern.kind === 200 /* ObjectLiteralExpression */); + (contextualType.pattern.kind === 197 /* ObjectBindingPattern */ || contextualType.pattern.kind === 201 /* ObjectLiteralExpression */); var inConstContext = isConstContext(node); var checkFlags = inConstContext ? 8 /* Readonly */ : 0; var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); @@ -66761,7 +68893,7 @@ var ts; // which may never occur. for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; - if (elem.name && ts.isComputedPropertyName(elem.name) && !ts.isWellKnownSymbolSyntactically(elem.name)) { + if (elem.name && ts.isComputedPropertyName(elem.name)) { checkComputedPropertyName(elem.name); } } @@ -66769,16 +68901,16 @@ var ts; for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var memberDecl = _c[_b]; var member = getSymbolOfNode(memberDecl); - var computedNameType = memberDecl.name && memberDecl.name.kind === 158 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + var computedNameType = memberDecl.name && memberDecl.name.kind === 159 /* ComputedPropertyName */ ? checkComputedPropertyName(memberDecl.name) : undefined; - if (memberDecl.kind === 288 /* PropertyAssignment */ || - memberDecl.kind === 289 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 289 /* PropertyAssignment */ || + memberDecl.kind === 290 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { - var type = memberDecl.kind === 288 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + var type = memberDecl.kind === 289 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`. // we don't want to say "could not find 'a'". - memberDecl.kind === 289 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : + memberDecl.kind === 290 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); @@ -66790,7 +68922,7 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) : @@ -66801,8 +68933,8 @@ var ts; if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. - var isOptional = (memberDecl.kind === 288 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 289 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 289 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 290 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216 /* Optional */; } @@ -66828,7 +68960,7 @@ var ts; member = prop; allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop); } - else if (memberDecl.kind === 290 /* SpreadAssignment */) { + else if (memberDecl.kind === 291 /* SpreadAssignment */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } @@ -66840,15 +68972,20 @@ var ts; hasComputedNumberProperty = false; } var type = getReducedType(checkExpression(memberDecl.expression)); - if (!isValidSpreadType(type)) { - error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return errorType; + if (isValidSpreadType(type)) { + if (allPropertiesTable) { + checkSpreadPropOverrides(type, allPropertiesTable, memberDecl); + } + offset = propertiesArray.length; + if (spread === errorType) { + continue; + } + spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext); } - if (allPropertiesTable) { - checkSpreadPropOverrides(type, allPropertiesTable, memberDecl); + else { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + spread = errorType; } - spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext); - offset = propertiesArray.length; continue; } else { @@ -66857,7 +68994,7 @@ var ts; // an ordinary function declaration(section 6.1) with no parameters. // A set accessor declaration is processed in the same manner // as an ordinary function declaration with a single parameter and a Void return type. - ts.Debug.assert(memberDecl.kind === 167 /* GetAccessor */ || memberDecl.kind === 168 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 168 /* GetAccessor */ || memberDecl.kind === 169 /* SetAccessor */); checkNodeDeferred(memberDecl); } if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) { @@ -66882,7 +69019,7 @@ var ts; // type with those properties for which the binding pattern specifies a default value. // If the object literal is spread into another object literal, skip this step and let the top-level object // literal handle it instead. - if (contextualTypeHasPattern && node.parent.kind !== 290 /* SpreadAssignment */) { + if (contextualTypeHasPattern && node.parent.kind !== 291 /* SpreadAssignment */) { for (var _d = 0, _e = getPropertiesOfType(contextualType); _d < _e.length; _d++) { var prop = _e[_d]; if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) { @@ -66894,6 +69031,9 @@ var ts; } } } + if (spread === errorType) { + return errorType; + } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext); @@ -66910,9 +69050,9 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; if (isJSObjectLiteral) { - result.objectFlags |= 16384 /* JSLiteral */; + result.objectFlags |= 8192 /* JSLiteral */; } if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; @@ -67002,14 +69142,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var objectFlags = 4096 /* JsxAttributes */; + var objectFlags = 2048 /* JsxAttributes */; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -67025,7 +69165,7 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 282 /* JsxSpreadAttribute */); + ts.Debug.assert(attributeDecl.kind === 283 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false); attributesTable = ts.createSymbolTable(); @@ -67051,7 +69191,7 @@ var ts; } } // Handle children attribute - var parent = openingLikeElement.parent.kind === 273 /* JsxElement */ ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 274 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = checkJsxChildren(parent, checkMode); @@ -67067,7 +69207,7 @@ var ts; // 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 */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - childrenContextualType && forEachType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : + childrenContextualType && someType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : createArrayType(getUnionType(childrenTypes)); // Fake up a property declaration for the children childrenPropSymbol.valueDeclaration = ts.factory.createPropertySignature(/*modifiers*/ undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined); @@ -67093,7 +69233,7 @@ var ts; function createJsxAttributesType() { objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return result; } } @@ -67108,7 +69248,7 @@ var ts; childrenTypes.push(stringType); } } - else if (child.kind === 283 /* JsxExpression */ && !child.expression) { + else if (child.kind === 284 /* JsxExpression */ && !child.expression) { continue; // empty jsx expressions don't *really* count as present children } else { @@ -67259,7 +69399,7 @@ var ts; else if (propertiesOfJsxElementAttribPropInterface.length === 1) { return propertiesOfJsxElementAttribPropInterface[0].escapedName; } - else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + else if (propertiesOfJsxElementAttribPropInterface.length > 1 && jsxElementAttribPropInterfaceSym.declarations) { // More than one property on ElementAttributesProperty is an error error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer)); } @@ -67369,11 +69509,11 @@ var ts; if (!links.resolvedJsxElementAttributesType) { var symbol = getIntrinsicTagSymbol(node); if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { - return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol) || errorType; } else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { return links.resolvedJsxElementAttributesType = - getIndexTypeOfType(getDeclaredTypeOfSymbol(symbol), 0 /* String */); + getIndexTypeOfType(getJsxType(JsxNames.IntrinsicElements, node), 0 /* String */) || errorType; } else { return links.resolvedJsxElementAttributesType = errorType; @@ -67526,9 +69666,12 @@ var ts; * @param type The type of the object whose property is being accessed. (Not the type of the property.) * @param prop The symbol for the property being accessed. */ - function checkPropertyAccessibility(node, isSuper, type, prop) { - var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 157 /* QualifiedName */ ? node.right : node.kind === 195 /* ImportType */ ? node : node.name; + function checkPropertyAccessibility(node, isSuper, writing, type, prop, reportError) { + if (reportError === void 0) { reportError = true; } + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop, writing); + var errorNode = node.kind === 158 /* QualifiedName */ ? node.right : + node.kind === 196 /* ImportType */ ? node : + node.kind === 199 /* BindingElement */ && node.propertyName ? node.propertyName : node.name; if (isSuper) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or @@ -67539,7 +69682,9 @@ var ts; // a super property access is permitted and must specify a public static member function of the base class. if (languageVersion < 2 /* ES2015 */) { if (symbolHasNonMethodDeclaration(prop)) { - error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + if (reportError) { + error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + } return false; } } @@ -67548,24 +69693,22 @@ var ts; // This error could mask a private property access error. But, a member // cannot simultaneously be private and abstract, so this will trigger an // additional error elsewhere. - error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + if (reportError) { + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + } return false; } } // Referencing abstract properties within their own constructors is not allowed - if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { + if ((flags & 128 /* Abstract */) && symbolHasNonMethodDeclaration(prop) && + (ts.isThisProperty(node) || ts.isThisInitializedObjectBindingExpression(node) || ts.isObjectBindingPattern(node.parent) && ts.isThisInitializedDeclaration(node.parent.parent))) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); 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; - } - } - if (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name)) { - if (!ts.getContainingClass(node)) { - error(errorNode, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + if (reportError) { + 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; } - return true; } // Public properties are otherwise accessible. if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { @@ -67576,7 +69719,9 @@ var ts; if (flags & 8 /* Private */) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + if (reportError) { + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + } return false; } return true; @@ -67590,7 +69735,7 @@ var ts; // of the property as base classes var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + return isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing) ? enclosingClass : undefined; }); // A protected property is accessible if the property is within the declaring class or classes derived from it if (!enclosingClass) { @@ -67598,7 +69743,9 @@ var ts; // static member access is disallow var thisParameter = void 0; if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + if (reportError) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + } return false; } var thisType = getTypeFromTypeNode(thisParameter.type); @@ -67613,7 +69760,9 @@ var ts; type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined } if (!type || !hasBaseType(type, enclosingClass)) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + if (reportError) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2, symbolToString(prop), typeToString(enclosingClass), typeToString(type)); + } return false; } return true; @@ -67669,20 +69818,20 @@ var ts; } return nonNullType; } - function checkPropertyAccessExpression(node) { - return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) : - checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + function checkPropertyAccessExpression(node, checkMode) { + return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node, checkMode) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name, checkMode); } - function checkPropertyAccessChain(node) { + function checkPropertyAccessChain(node, checkMode) { var leftType = checkExpression(node.expression); var nonOptionalType = getOptionalExpressionType(leftType, node.expression); - return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name, checkMode), node, nonOptionalType !== leftType); } - function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); + function checkQualifiedName(node, checkMode) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right, checkMode); } function isMethodAccessForCall(node) { - while (node.parent.kind === 207 /* ParenthesizedExpression */) { + while (node.parent.kind === 208 /* ParenthesizedExpression */) { node = node.parent; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; @@ -67717,14 +69866,13 @@ var ts; } var diagName = diagnosticName(right); if (propertyOnType) { - var typeValueDecl = propertyOnType.valueDeclaration; - var typeClass_1 = ts.getContainingClass(typeValueDecl); - ts.Debug.assert(!!typeClass_1); + var typeValueDecl = ts.Debug.checkDefined(propertyOnType.valueDeclaration); + var typeClass_1 = ts.Debug.checkDefined(ts.getContainingClass(typeValueDecl)); // We found a private identifier property with the same description. // Either: // - There is a lexically scoped private identifier AND it shadows the one we found on the type. // - It is an attempt to access the private identifier outside of the class. - if (lexicallyScopedIdentifier) { + if (lexicallyScopedIdentifier === null || lexicallyScopedIdentifier === void 0 ? void 0 : lexicallyScopedIdentifier.valueDeclaration) { var lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration; var lexicalClass = ts.getContainingClass(lexicalValueDecl); ts.Debug.assert(!!lexicalClass); @@ -67743,17 +69891,42 @@ var ts; return (isConstructorDeclaredProperty(prop) || ts.isThisProperty(node) && isAutoTypedProperty(prop)) && ts.getThisContainer(node, /*includeArrowFunctions*/ true) === getDeclaringConstructor(prop); } - function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right, checkMode) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); - if (ts.isPrivateIdentifier(right)) { - checkExternalEmitHelpers(node, 524288 /* ClassPrivateFieldGet */); - } var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType; var prop; if (ts.isPrivateIdentifier(right)) { + if (languageVersion < 99 /* ESNext */) { + if (assignmentKind !== 0 /* None */) { + checkExternalEmitHelpers(node, 1048576 /* ClassPrivateFieldSet */); + } + if (assignmentKind !== 1 /* Definite */) { + checkExternalEmitHelpers(node, 524288 /* ClassPrivateFieldGet */); + } + } var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right); + if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && ts.isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) { + grammarErrorOnNode(right, ts.Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, ts.idText(right)); + } + if ((lexicallyScopedSymbol === null || lexicallyScopedSymbol === void 0 ? void 0 : lexicallyScopedSymbol.valueDeclaration) && (compilerOptions.target === 99 /* ESNext */ && !useDefineForClassFields)) { + var lexicalClass_1 = ts.getContainingClass(lexicallyScopedSymbol.valueDeclaration); + var parentStaticFieldInitializer = ts.findAncestor(node, function (n) { + if (n === lexicalClass_1) + return "quit"; + if (ts.isPropertyDeclaration(n.parent) && ts.hasStaticModifier(n.parent) && n.parent.initializer === n && n.parent.parent === lexicalClass_1) { + return true; + } + return false; + }); + if (parentStaticFieldInitializer) { + var parentStaticFieldInitializerSymbol = getSymbolOfNode(parentStaticFieldInitializer.parent); + ts.Debug.assert(parentStaticFieldInitializerSymbol, "Initializer without declaration symbol"); + var diagnostic = error(node, ts.Diagnostics.Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false, ts.symbolName(lexicallyScopedSymbol)); + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(parentStaticFieldInitializer.parent, ts.Diagnostics.Initializer_for_property_0, ts.symbolName(parentStaticFieldInitializerSymbol))); + } + } if (isAnyLike) { if (lexicallyScopedSymbol) { return apparentType; @@ -67768,6 +69941,12 @@ var ts; if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) { return errorType; } + else { + var isSetonlyAccessor = prop && prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (isSetonlyAccessor && assignmentKind !== 1 /* Definite */) { + error(node, ts.Diagnostics.Private_accessor_was_defined_without_a_getter); + } + } } else { if (isAnyLike) { @@ -67778,7 +69957,11 @@ var ts; } prop = getPropertyOfType(apparentType, right.escapedText); } - if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums. + // The exceptions are: + // 1. if 'isolatedModules' is enabled, because the const enum value will not be inlined, and + // 2. if 'preserveConstEnums' is enabled and the expression is itself an export, e.g. `export = Foo.Bar.Baz`. + if (ts.isIdentifier(left) && parentSymbol && (compilerOptions.isolatedModules || !(prop && isConstEnumOrConstEnumOnlyModule(prop)) || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) { markAliasReferenced(parentSymbol, node); } var propType; @@ -67811,44 +69994,48 @@ var ts; } } else { - if (getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) { - errorOrSuggestion(/* isError */ false, right, ts.Diagnostics._0_is_deprecated, right.escapedText); + if (prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) { + addDeprecatedSuggestion(right, prop.declarations, right.escapedText); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node, left.kind === 107 /* ThisKeyword */); + markPropertyAsReferenced(prop, node, isSelfTypeAccess(left, parentSymbol)); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left.kind === 105 /* SuperKeyword */, apparentType, prop); + var writing = ts.isWriteAccess(node); + checkPropertyAccessibility(node, left.kind === 105 /* SuperKeyword */, writing, apparentType, prop); if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) { error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } - propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : getConstraintForLocation(getTypeOfSymbol(prop), node); + propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : writing ? getSetAccessorTypeOfSymbol(prop) : getTypeOfSymbol(prop); } - return getFlowTypeOfAccessExpression(node, prop, propType, right); + return getFlowTypeOfAccessExpression(node, prop, propType, right, checkMode); } - function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { + function getFlowTypeOfAccessExpression(node, prop, propType, errorNode, checkMode) { // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. var assignmentKind = ts.getAssignmentTargetKind(node); - if (!ts.isAccessExpression(node) || - assignmentKind === 1 /* Definite */ || - prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { + if (assignmentKind === 1 /* Definite */ || + prop && + !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) + && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */) + && !isDuplicatedCommonJSExport(prop.declarations)) { return propType; } if (propType === autoType) { return getFlowTypeOfProperty(node, prop); } + propType = getNarrowableTypeForReference(propType, node, checkMode); // If strict null checks and strict property initialization checks are enabled, if we have // a this.xxx property access, if the property is an instance property without an initializer, // and if we are in a constructor of the same class as the property declaration, assume that // the property is uninitialized at the top of the control flow. var assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 107 /* ThisKeyword */) { + if (strictNullChecks && strictPropertyInitialization && ts.isAccessExpression(node) && node.expression.kind === 107 /* ThisKeyword */) { var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); - if (flowContainer.kind === 166 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) { + if (flowContainer.kind === 167 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) { assumeUninitialized = true; } } @@ -67875,13 +70062,14 @@ var ts; var diagnosticMessage; var declarationName = ts.idText(right); if (isInPropertyInitializer(node) + && !isOptionalPropertyDeclaration(valueDeclaration) && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) - && !isPropertyDeclaredInAncestorClass(prop)) { + && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } - else if (valueDeclaration.kind === 252 /* ClassDeclaration */ && - node.parent.kind !== 173 /* TypeReference */ && + else if (valueDeclaration.kind === 253 /* ClassDeclaration */ && + node.parent.kind !== 174 /* TypeReference */ && !(valueDeclaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); @@ -67893,22 +70081,22 @@ var ts; function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return true; - case 288 /* PropertyAssignment */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 290 /* SpreadAssignment */: - case 158 /* ComputedPropertyName */: - case 228 /* TemplateSpan */: - case 283 /* JsxExpression */: - case 280 /* JsxAttribute */: - case 281 /* JsxAttributes */: - case 282 /* JsxSpreadAttribute */: - case 275 /* JsxOpeningElement */: - case 223 /* ExpressionWithTypeArguments */: - case 286 /* HeritageClause */: + case 289 /* PropertyAssignment */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 291 /* SpreadAssignment */: + case 159 /* ComputedPropertyName */: + case 229 /* TemplateSpan */: + case 284 /* JsxExpression */: + case 281 /* JsxAttribute */: + case 282 /* JsxAttributes */: + case 283 /* JsxSpreadAttribute */: + case 276 /* JsxOpeningElement */: + case 224 /* ExpressionWithTypeArguments */: + case 287 /* HeritageClause */: return false; default: return ts.isExpressionNode(node) ? false : "quit"; @@ -67980,7 +70168,10 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, missingProperty, container); + var diagnostic = containerSeemsToBeEmptyDomElement(containingType) + ? ts.Diagnostics.Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom + : ts.Diagnostics.Property_0_does_not_exist_on_type_1; + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), diagnostic, missingProperty, container); } } } @@ -67991,9 +70182,14 @@ var ts; } diagnostics.add(resultDiagnostic); } + function containerSeemsToBeEmptyDomElement(containingType) { + return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && + everyContainedType(containingType, function (type) { return type.symbol && /^(EventTarget|Node|((HTML[a-zA-Z]*)?Element))$/.test(ts.unescapeLeadingUnderscores(type.symbol.escapedName)); }) && + isEmptyObjectType(containingType); + } function typeHasStaticProperty(propName, containingType) { var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); - return prop !== undefined && prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */); + return prop !== undefined && !!prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedLibForNonExistentName(name) { var missingName = diagnosticName(name); @@ -68024,7 +70220,15 @@ var ts; } } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 111551 /* Value */); + var props = getPropertiesOfType(containingType); + if (typeof name !== "string") { + var parent_2 = name.parent; + if (ts.isPropertyAccessExpression(parent_2)) { + props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_2, containingType, prop); }); + } + name = ts.idText(name); + } + return getSpellingSuggestionForName(name, props, 111551 /* Value */); } function getSuggestedSymbolForNonexistentJSXAttribute(name, containingType) { var strName = ts.isString(name) ? name : ts.idText(name); @@ -68119,20 +70323,20 @@ var ts; return undefined; } } - function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isSelfTypeAccess) { var valueDeclaration = prop && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration; if (!valueDeclaration) { return; } var hasPrivateModifier = ts.hasEffectiveModifier(valueDeclaration, 8 /* Private */); - var hasPrivateIdentifier = ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name); + var hasPrivateIdentifier = prop.valueDeclaration && ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name); if (!hasPrivateModifier && !hasPrivateIdentifier) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) { return; } - if (isThisAccess) { + if (isSelfTypeAccess) { // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); if (containingMethod && containingMethod.symbol === prop) { @@ -68141,18 +70345,22 @@ var ts; } (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */; } + function isSelfTypeAccess(name, parent) { + return name.kind === 107 /* ThisKeyword */ + || !!parent && ts.isEntityNameExpression(name) && parent === getResolvedSymbol(ts.getFirstIdentifier(name)); + } function isValidPropertyAccess(node, propertyName) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return isValidPropertyAccessWithType(node, node.expression.kind === 105 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); - case 195 /* ImportType */: + case 196 /* ImportType */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind === 201 /* PropertyAccessExpression */ && node.expression.kind === 105 /* SuperKeyword */, property.escapedName, type); + return isValidPropertyAccessWithType(node, node.kind === 202 /* PropertyAccessExpression */ && node.expression.kind === 105 /* SuperKeyword */, property.escapedName, type); // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context. } function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { @@ -68161,11 +70369,11 @@ var ts; } var prop = getPropertyOfType(type, propertyName); if (prop) { - if (ts.isPropertyAccessExpression(node) && prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)) { + if (prop.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration)) { var declClass_1 = ts.getContainingClass(prop.valueDeclaration); return !ts.isOptionalChain(node) && !!ts.findAncestor(node, function (parent) { return parent === declClass_1; }); } - return checkPropertyAccessibility(node, isSuper, type, prop); + return checkPropertyAccessibility(node, isSuper, /*writing*/ false, type, prop, /* reportError */ false); } // In js files properties of unions are allowed in completion return ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); @@ -68175,7 +70383,7 @@ var ts; */ function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 250 /* VariableDeclarationList */) { + if (initializer.kind === 251 /* VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); @@ -68204,7 +70412,7 @@ var ts; var child = expr; var node = expr.parent; while (node) { - if (node.kind === 238 /* ForInStatement */ && + if (node.kind === 239 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -68217,16 +70425,16 @@ var ts; } return false; } - function checkIndexedAccess(node) { - return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) : - checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + function checkIndexedAccess(node, checkMode) { + return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node, checkMode) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression), checkMode); } - function checkElementAccessChain(node) { + function checkElementAccessChain(node, checkMode) { var exprType = checkExpression(node.expression); var nonOptionalType = getOptionalExpressionType(exprType, node.expression); - return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression), checkMode), node, nonOptionalType !== exprType); } - function checkElementAccessExpression(node, exprType) { + function checkElementAccessExpression(node, exprType, checkMode) { var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; var indexExpression = node.argumentExpression; var indexType = checkExpression(indexExpression); @@ -68242,42 +70450,7 @@ var ts; 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) : 0 /* None */; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, /*noUncheckedIndexedAccessCandidate*/ undefined, node, accessFlags | 16 /* ExpressionPosition */) || errorType; - return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); - } - function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { - if (expressionType === errorType) { - // There is already an error, so no need to report one. - return false; - } - if (!ts.isWellKnownSymbolSyntactically(expression)) { - return false; - } - // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) { - if (reportError) { - error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); - } - return false; - } - // The name is Symbol., so make sure Symbol actually resolves to the - // global Symbol object - var leftHandSide = expression.expression; - var leftHandSideSymbol = getResolvedSymbol(leftHandSide); - if (!leftHandSideSymbol) { - return false; - } - var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true); - if (!globalESSymbol) { - // Already errored when we tried to look up the symbol - return false; - } - if (leftHandSideSymbol !== globalESSymbol) { - if (reportError) { - error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); - } - return false; - } - return true; + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, getNodeLinks(node).resolvedSymbol, indexedAccessType, indexExpression, checkMode), node); } function callLikeExpressionMayHaveTypeArguments(node) { return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node); @@ -68288,13 +70461,13 @@ var ts; // This gets us diagnostics for the type arguments and marks them as referenced. ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 205 /* TaggedTemplateExpression */) { + if (node.kind === 206 /* TaggedTemplateExpression */) { checkExpression(node.template); } else if (ts.isJsxOpeningLikeElement(node)) { checkExpression(node.attributes); } - else if (node.kind !== 161 /* Decorator */) { + else if (node.kind !== 162 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -68358,7 +70531,7 @@ var ts; } } function isSpreadArgument(arg) { - return !!arg && (arg.kind === 220 /* SpreadElement */ || arg.kind === 227 /* SyntheticExpression */ && arg.isSpread); + return !!arg && (arg.kind === 221 /* SpreadElement */ || arg.kind === 228 /* SyntheticExpression */ && arg.isSpread); } function getSpreadArgumentIndex(args) { return ts.findIndex(args, isSpreadArgument); @@ -68375,9 +70548,9 @@ var ts; var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments var effectiveParameterCount = getParameterCount(signature); var effectiveMinimumArguments = getMinArgumentCount(signature); - if (node.kind === 205 /* TaggedTemplateExpression */) { + if (node.kind === 206 /* TaggedTemplateExpression */) { argCount = args.length; - if (node.template.kind === 218 /* TemplateExpression */) { + if (node.template.kind === 219 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. @@ -68392,7 +70565,7 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 161 /* Decorator */) { + else if (node.kind === 162 /* Decorator */) { argCount = getDecoratorArgumentCount(node, signature); } else if (ts.isJsxOpeningLikeElement(node)) { @@ -68406,7 +70579,7 @@ var ts; } else if (!node.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(node.kind === 204 /* NewExpression */); + ts.Debug.assert(node.kind === 205 /* NewExpression */); return getMinArgumentCount(signature) === 0; } else { @@ -68481,7 +70654,7 @@ var ts; }); if (!inferenceContext) { applyToReturnTypes(contextualSignature, signature, function (source, target) { - inferTypes(context.inferences, source, target, 64 /* ReturnType */); + inferTypes(context.inferences, source, target, 128 /* ReturnType */); }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); @@ -68492,6 +70665,15 @@ var ts; inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } + function getThisArgumentType(thisArgumentNode) { + if (!thisArgumentNode) { + return voidType; + } + var thisArgumentType = checkExpression(thisArgumentNode); + return ts.isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) : + ts.isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) : + thisArgumentType; + } function inferTypeArguments(node, signature, args, checkMode, context) { if (ts.isJsxOpeningLikeElement(node)) { return inferJsxTypeArguments(node, signature, checkMode, context); @@ -68500,7 +70682,7 @@ var ts; // 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 // return type of 'wrap'. - if (node.kind !== 161 /* Decorator */) { + if (node.kind !== 162 /* Decorator */) { var contextualType = getContextualType(node, ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }) ? 8 /* SkipBindingPatterns */ : 0 /* None */); if (contextualType) { // We clone the inference context to avoid disturbing a resolution in progress for an @@ -68522,7 +70704,7 @@ var ts; instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 64 /* ReturnType */); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* ReturnType */); // Create a type mapper for instantiating generic contextual types using the inferences made // from the return type. We need a separate inference pass here because (a) instantiation of // the source type uses the outer context's return mapper (which excludes inferences made from @@ -68544,12 +70726,11 @@ var ts; var thisType = getThisTypeOfSignature(signature); if (thisType) { var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context.inferences, thisArgumentType, thisType); + inferTypes(context.inferences, getThisArgumentType(thisArgumentNode), thisType); } for (var i = 0; i < argCount; i++) { var arg = args[i]; - if (arg.kind !== 222 /* OmittedExpression */) { + if (arg.kind !== 223 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode); inferTypes(context.inferences, argType, paramType); @@ -68573,7 +70754,7 @@ var ts; 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 getMutableArrayOrTupleType(arg.kind === 227 /* SyntheticExpression */ ? arg.type : + return getMutableArrayOrTupleType(arg.kind === 228 /* SyntheticExpression */ ? arg.type : checkExpressionWithContextualType(arg.expression, restType, context, checkMode)); } } @@ -68583,13 +70764,13 @@ var ts; for (var i = index; i < argCount; i++) { var arg = args[i]; if (isSpreadArgument(arg)) { - var spreadType = arg.kind === 227 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression); + var spreadType = arg.kind === 228 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression); if (isArrayLikeType(spreadType)) { types.push(spreadType); flags.push(8 /* Variadic */); } else { - types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 220 /* SpreadElement */ ? arg.expression : arg)); + types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 221 /* SpreadElement */ ? arg.expression : arg)); flags.push(4 /* Rest */); } } @@ -68600,7 +70781,7 @@ var ts; types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); flags.push(1 /* Required */); } - if (arg.kind === 227 /* SyntheticExpression */ && arg.tupleNameSource) { + if (arg.kind === 228 /* SyntheticExpression */ && arg.tupleNameSource) { names.push(arg.tupleNameSource); } } @@ -68744,24 +70925,12 @@ var ts; return undefined; } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 204 /* NewExpression */) { + if (thisType && thisType !== voidType && node.kind !== 205 /* NewExpression */) { // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = void 0; - if (thisArgumentNode) { - thisArgumentType = checkExpression(thisArgumentNode); - if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { - thisArgumentType = getNonNullableType(thisArgumentType); - } - else if (ts.isOptionalChain(thisArgumentNode.parent)) { - thisArgumentType = removeOptionalTypeMarker(thisArgumentType); - } - } - else { - thisArgumentType = voidType; - } + var thisArgumentType = getThisArgumentType(thisArgumentNode); var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -68774,7 +70943,7 @@ var ts; var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { var arg = args[i]; - if (arg.kind !== 222 /* OmittedExpression */) { + if (arg.kind !== 223 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode); // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive), @@ -68819,7 +70988,7 @@ var ts; * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. */ function getThisArgumentOfCall(node) { - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { var callee = ts.skipOuterExpressions(node.expression); if (ts.isAccessExpression(callee)) { return callee.expression; @@ -68836,17 +71005,17 @@ var ts; * Returns the effective arguments for an expression that works like a function invocation. */ function getEffectiveCallArguments(node) { - if (node.kind === 205 /* TaggedTemplateExpression */) { + if (node.kind === 206 /* TaggedTemplateExpression */) { var template = node.template; var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; - if (template.kind === 218 /* TemplateExpression */) { + if (template.kind === 219 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_3.push(span.expression); }); } return args_3; } - if (node.kind === 161 /* Decorator */) { + if (node.kind === 162 /* Decorator */) { return getEffectiveDecoratorArguments(node); } if (ts.isJsxOpeningLikeElement(node)) { @@ -68857,10 +71026,10 @@ var ts; if (spreadIndex >= 0) { // Create synthetic arguments from spreads of tuple types. var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_20 = function (i) { + var _loop_21 = function (i) { var arg = args[i]; // We can call checkExpressionCached because spread expressions never have a contextual type. - var spreadType = arg.kind === 220 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); + var spreadType = arg.kind === 221 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); if (spreadType && isTupleType(spreadType)) { ts.forEach(getTypeArguments(spreadType), function (t, i) { var _a; @@ -68874,7 +71043,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_20(i); + _loop_21(i); } return effectiveArgs_1; } @@ -68887,30 +71056,30 @@ var ts; var parent = node.parent; var expr = node.expression; switch (parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* 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 160 /* Parameter */: + case 161 /* 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 === 166 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, parent.parent.kind === 167 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), createSyntheticExpression(expr, anyType), createSyntheticExpression(expr, numberType) ]; - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* 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 !== 163 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + var hasPropDesc = parent.kind !== 164 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; return [ createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), @@ -68924,17 +71093,17 @@ var ts; */ function getDecoratorArgumentCount(node, signature) { switch (node.parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return 1; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return 2; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* 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 160 /* Parameter */: + case 161 /* Parameter */: return 3; default: return ts.Debug.fail(); @@ -68980,77 +71149,66 @@ var ts; return constructorSymbol === globalPromiseSymbol; } function getArgumentArityError(node, signatures, args) { - var min = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - var belowArgCount = Number.NEGATIVE_INFINITY; - var aboveArgCount = Number.POSITIVE_INFINITY; - var argCount = args.length; + var _a; + var spreadIndex = getSpreadArgumentIndex(args); + if (spreadIndex > -1) { + return ts.createDiagnosticForNode(args[spreadIndex], ts.Diagnostics.A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter); + } + var min = Number.POSITIVE_INFINITY; // smallest parameter count + var max = Number.NEGATIVE_INFINITY; // largest parameter count + var maxBelow = Number.NEGATIVE_INFINITY; // largest parameter count that is smaller than the number of arguments + var minAbove = Number.POSITIVE_INFINITY; // smallest parameter count that is larger than the number of arguments var closestSignature; for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { var sig = signatures_8[_i]; - var minCount = getMinArgumentCount(sig); - var maxCount = getParameterCount(sig); - if (minCount < argCount && minCount > belowArgCount) - belowArgCount = minCount; - if (argCount < maxCount && maxCount < aboveArgCount) - aboveArgCount = maxCount; - if (minCount < min) { - min = minCount; + var minParameter = getMinArgumentCount(sig); + var maxParameter = getParameterCount(sig); + // smallest/largest parameter counts + if (minParameter < min) { + min = minParameter; closestSignature = sig; } - max = Math.max(max, maxCount); + max = Math.max(max, maxParameter); + // shortest parameter count *longer than the call*/longest parameter count *shorter than the call* + if (minParameter < args.length && minParameter > maxBelow) + maxBelow = minParameter; + if (args.length < maxParameter && maxParameter < minAbove) + minAbove = maxParameter; } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); - var paramRange = hasRestParameter ? min : - min < max ? min + "-" + max : - min; - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var spanArray; - var related; - var error = hasRestParameter || hasSpreadArgument ? - hasRestParameter && hasSpreadArgument ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - paramRange === 1 && argCount === 0 && isPromiseResolveArityError(node) ? - ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : - ts.Diagnostics.Expected_0_arguments_but_got_1; - if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { - var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; - if (paramDecl) { - related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : - ts.isRestParameter(paramDecl) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined); - } - } - if (min < argCount && argCount < max) { - return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); - } - if (!hasSpreadArgument && argCount < min) { - var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1; - } - if (hasRestParameter || hasSpreadArgument) { - spanArray = ts.factory.createNodeArray(args); - if (hasSpreadArgument && argCount) { - var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined; - spanArray = ts.factory.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1))); + var parameterRange = hasRestParameter ? min + : min < max ? min + "-" + max + : min; + var error = hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 + : parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node) ? ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise + : ts.Diagnostics.Expected_0_arguments_but_got_1; + if (min < args.length && args.length < max) { + // between min and max, but with no matching overload + return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove); + } + else if (args.length < min) { + // too short: put the error span on the call expression, not any of the args + var diagnostic = getDiagnosticForCallNode(node, error, parameterRange, args.length); + var parameter = (_a = closestSignature === null || closestSignature === void 0 ? void 0 : closestSignature.declaration) === null || _a === void 0 ? void 0 : _a.parameters[closestSignature.thisParameter ? args.length + 1 : args.length]; + if (parameter) { + var parameterError = ts.createDiagnosticForNode(parameter, ts.isBindingPattern(parameter.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided + : ts.isRestParameter(parameter) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided + : ts.Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : !ts.isBindingPattern(parameter.name) ? ts.idText(ts.getFirstIdentifier(parameter.name)) : undefined); + return ts.addRelatedInfo(diagnostic, parameterError); } + return diagnostic; } else { - spanArray = ts.factory.createNodeArray(args.slice(max)); - } - var pos = ts.first(spanArray).pos; - var end = ts.last(spanArray).end; - if (end === pos) { - end++; + // too long; error goes on the excess parameters + var errorSpan = ts.factory.createNodeArray(args.slice(max)); + var pos = ts.first(errorSpan).pos; + var end = ts.last(errorSpan).end; + if (end === pos) { + end++; + } + ts.setTextRangePosEnd(errorSpan, pos, end); + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), errorSpan, error, parameterRange, args.length); } - ts.setTextRangePosEnd(spanArray, pos, end); - var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var argCount = typeArguments.length; @@ -69081,8 +71239,8 @@ var ts; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) { - var isTaggedTemplate = node.kind === 205 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 161 /* Decorator */; + var isTaggedTemplate = node.kind === 206 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 162 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var reportErrors = !candidatesOutArray && produceDiagnostics; var typeArguments; @@ -69144,7 +71302,7 @@ var ts; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 203 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 204 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -69198,7 +71356,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_21 = function (c) { + var _loop_22 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2); if (diags_2) { @@ -69216,7 +71374,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_21(c); + _loop_22(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); @@ -69374,7 +71532,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_22 = function (i) { + var _loop_23 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -69382,7 +71540,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_22(i); + _loop_23(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* None */; @@ -69574,7 +71732,7 @@ var ts; function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have no common signatures. return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) || - !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & 1048576 /* Union */) && !(getReducedType(apparentFuncType).flags & 131072 /* Never */) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray, checkMode) { if (node.arguments && languageVersion < 1 /* ES5 */) { @@ -69689,7 +71847,7 @@ var ts; var declaration = signature.declaration; var modifiers = ts.getSelectedEffectiveModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */); // (1) Public constructors and (2) constructor functions are always accessible. - if (!modifiers || declaration.kind !== 166 /* Constructor */) { + if (!modifiers || declaration.kind !== 167 /* Constructor */) { return true; } var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol); @@ -69833,16 +71991,16 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 160 /* Parameter */: + case 161 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; default: return ts.Debug.fail(); @@ -69937,16 +72095,16 @@ var ts; } function resolveSignature(node, candidatesOutArray, checkMode) { switch (node.kind) { - case 203 /* CallExpression */: + case 204 /* CallExpression */: return resolveCallExpression(node, candidatesOutArray, checkMode); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return resolveNewExpression(node, candidatesOutArray, checkMode); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode); - case 161 /* Decorator */: + case 162 /* Decorator */: return resolveDecorator(node, candidatesOutArray, checkMode); - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode); } throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); @@ -70078,7 +72236,7 @@ var ts; return false; } var parent = node.parent; - while (parent && parent.kind === 201 /* PropertyAccessExpression */) { + while (parent && parent.kind === 202 /* PropertyAccessExpression */) { parent = parent.parent; } if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 62 /* EqualsToken */) { @@ -70105,12 +72263,12 @@ var ts; if (node.expression.kind === 105 /* SuperKeyword */) { return voidType; } - if (node.kind === 204 /* NewExpression */) { + if (node.kind === 205 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 166 /* Constructor */ && - declaration.kind !== 170 /* ConstructSignature */ && - declaration.kind !== 175 /* ConstructorType */ && + declaration.kind !== 167 /* Constructor */ && + declaration.kind !== 171 /* ConstructSignature */ && + declaration.kind !== 176 /* ConstructorType */ && !ts.isJSDocConstructSignature(declaration) && !isJSConstructor(declaration)) { // When resolved signature is a call signature (and not a construct signature) the result type is any @@ -70130,7 +72288,7 @@ var ts; if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } - if (node.kind === 203 /* CallExpression */ && node.parent.kind === 233 /* ExpressionStatement */ && + if (node.kind === 204 /* CallExpression */ && !node.questionDotToken && node.parent.kind === 234 /* ExpressionStatement */ && returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) { if (!ts.isDottedName(node.expression)) { error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name); @@ -70144,7 +72302,7 @@ var ts; var jsSymbol = getSymbolOfExpando(node, /*allowDeclaration*/ false); if ((_a = jsSymbol === null || jsSymbol === void 0 ? void 0 : jsSymbol.exports) === null || _a === void 0 ? void 0 : _a.size) { var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; + jsAssignmentType.objectFlags |= 8192 /* JSLiteral */; return getIntersectionType([returnType, jsAssignmentType]); } } @@ -70153,26 +72311,27 @@ var ts; function checkDeprecatedSignature(signature, node) { if (signature.declaration && signature.declaration.flags & 134217728 /* Deprecated */) { var suggestionNode = getDeprecatedSuggestionNode(node); - errorOrSuggestion(/*isError*/ false, suggestionNode, ts.Diagnostics._0_is_deprecated, signatureToString(signature)); + var name = ts.tryGetPropertyAccessOrIdentifierToString(ts.getInvokedExpression(node)); + addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature)); } } function getDeprecatedSuggestionNode(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 203 /* CallExpression */: - case 161 /* Decorator */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 162 /* Decorator */: + case 205 /* NewExpression */: return getDeprecatedSuggestionNode(node.expression); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return getDeprecatedSuggestionNode(node.tag); - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return getDeprecatedSuggestionNode(node.tagName); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return node.argumentExpression; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return node.name; - case 173 /* TypeReference */: + case 174 /* TypeReference */: var typeReference = node; return ts.isQualifiedName(typeReference.typeName) ? typeReference.typeName.right : typeReference; default: @@ -70223,10 +72382,11 @@ var ts; return createPromiseReturnType(node, anyType); } function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { + var _a; if (allowSyntheticDefaultImports && type && type !== errorType) { var synthType = type; if (!synthType.syntheticType) { - var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var file = (_a = originalSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); @@ -70264,9 +72424,9 @@ var ts; return false; } var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ - ? 251 /* FunctionDeclaration */ + ? 252 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ - ? 249 /* VariableDeclaration */ + ? 250 /* VariableDeclaration */ : 0 /* Unknown */; if (targetDeclarationKind !== 0 /* Unknown */) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); @@ -70296,19 +72456,19 @@ var ts; case 9 /* BigIntLiteral */: case 109 /* TrueKeyword */: case 94 /* FalseKeyword */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 218 /* TemplateExpression */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 219 /* TemplateExpression */: return true; - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isValidConstAssertionArgument(node.expression); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: var op = node.operator; var arg = node.operand; return op === 40 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) || op === 39 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: var expr = node.expression; if (ts.isIdentifier(expr)) { var symbol = getSymbolAtLocation(expr); @@ -70364,7 +72524,7 @@ var ts; error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return errorType; } - else if (container.kind === 166 /* Constructor */) { + else if (container.kind === 167 /* Constructor */) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -70411,7 +72571,7 @@ var ts; return restParameter.escapedName; } function isValidDeclarationForTupleLabel(d) { - return d.kind === 192 /* NamedTupleMember */ || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name)); + return d.kind === 193 /* NamedTupleMember */ || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name)); } function getNameableDeclarationAtPosition(signature, pos) { var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); @@ -70576,7 +72736,14 @@ var ts; } } function assignContextualParameterTypes(signature, context) { - signature.typeParameters = context.typeParameters; + if (context.typeParameters) { + if (!signature.typeParameters) { + signature.typeParameters = context.typeParameters; + } + else { + return; // This signature has already has a contextual inference performed and cached on it! + } + } if (context.thisParameter) { var parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { @@ -70687,7 +72854,7 @@ var ts; var yieldType; var nextType; var fallbackReturnType = voidType; - if (func.body.kind !== 230 /* Block */) { // Async or normal arrow function + if (func.body.kind !== 231 /* Block */) { // Async or normal arrow function returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */); if (isAsync) { // From within an async function you can return either a non-promise value or a promise. Any @@ -70872,7 +73039,7 @@ var ts; return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node)); } function computeExhaustiveSwitchStatement(node) { - if (node.expression.kind === 211 /* TypeOfExpression */) { + if (node.expression.kind === 212 /* TypeOfExpression */) { var operandType = getTypeOfExpression(node.expression.expression); var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); // notEqualFacts states that the type of the switched value is not equal to every type in the switch. @@ -70935,11 +73102,11 @@ var ts; } function mayReturnNever(func) { switch (func.kind) { - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; - case 165 /* MethodDeclaration */: - return func.parent.kind === 200 /* ObjectLiteralExpression */; + case 166 /* MethodDeclaration */: + return func.parent.kind === 201 /* ObjectLiteralExpression */; default: return false; } @@ -70965,21 +73132,21 @@ var ts; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (func.kind === 164 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 230 /* Block */ || !functionHasImplicitReturn(func)) { + if (func.kind === 165 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 231 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */; + var errorNode = ts.getEffectiveReturnTypeNode(func) || func; if (type && type.flags & 131072 /* Never */) { - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + error(errorNode, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (type && !hasExplicitReturn) { // minimal check: function has syntactic return type annotation and no explicit return statements in the body // this function does not conform to the specification. - // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + error(errorNode, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) { - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + error(errorNode, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); } else if (compilerOptions.noImplicitReturns) { if (!type) { @@ -70994,11 +73161,11 @@ var ts; return; } } - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + error(errorNode, ts.Diagnostics.Not_all_code_paths_return_a_value); } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) { @@ -71014,7 +73181,7 @@ var ts; var returnType = getReturnTypeFromBody(node, checkMode); var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); - returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */; + returnOnlyType.objectFlags |= 524288 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; } } @@ -71022,7 +73189,7 @@ var ts; } // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 208 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 209 /* FunctionExpression */) { checkGrammarForGenerator(node); } contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -71068,7 +73235,7 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnType = getReturnTypeFromAnnotation(node); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); @@ -71081,7 +73248,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 230 /* Block */) { + if (node.body.kind === 231 /* Block */) { checkSourceElement(node.body); } else { @@ -71171,7 +73338,7 @@ var ts; expr.expression.kind === 107 /* ThisKeyword */) { // Look for if this is the constructor for the class that `symbol` is a property of. var ctor = ts.getContainingFunction(expr); - if (!(ctor && (ctor.kind === 166 /* Constructor */ || isJSConstructor(ctor)))) { + if (!(ctor && (ctor.kind === 167 /* Constructor */ || isJSConstructor(ctor)))) { return true; } if (symbol.valueDeclaration) { @@ -71196,7 +73363,7 @@ var ts; var symbol_2 = getNodeLinks(node).resolvedSymbol; if (symbol_2.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol_2); - return !!declaration && declaration.kind === 263 /* NamespaceImport */; + return !!declaration && declaration.kind === 264 /* NamespaceImport */; } } } @@ -71277,7 +73444,7 @@ var ts; var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); var func = ts.getContainingFunction(node); - if (func && func.kind !== 166 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { + if (func && func.kind !== 167 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); ts.addRelatedInfo(diagnostic, relatedInfo); } @@ -71444,14 +73611,33 @@ var ts; rightType = checkNonNullType(rightType, right); // TypeScript 1.0 spec (April 2014): 4.15.5 // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, - // and the right operand to be of type Any, an object type, or a type parameter type. + // and the right operand to be + // + // 1. assignable to the non-primitive type, + // 2. an unconstrained type parameter, + // 3. a union or intersection including one or more type parameters, whose constituents are all assignable to the + // the non-primitive type, or are unconstrainted type parameters, or have constraints assignable to the + // non-primitive type, or + // 4. a type parameter whose constraint is + // i. an object type, + // ii. the non-primitive type, or + // iii. a union or intersection with at least one constituent assignable to an object or non-primitive type. + // + // The divergent behavior for type parameters and unions containing type parameters is a workaround for type + // parameters not being narrowable. If the right operand is a concrete type, we can error if there is any chance + // it is a primitive. But if the operand is a type parameter, it cannot be narrowed, so we don't issue an error + // unless *all* instantiations would result in an error. + // // The result is always of the Boolean primitive type. if (!(allTypesAssignableToKind(leftType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) || isTypeAssignableToKind(leftType, 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */ | 262144 /* TypeParameter */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { - error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + var rightTypeConstraint = getConstraintOfType(rightType); + if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */) || + rightTypeConstraint && (isTypeAssignableToKind(rightType, 3145728 /* UnionOrIntersection */) && !allTypesAssignableToKind(rightTypeConstraint, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */) || + !maybeTypeOfKind(rightTypeConstraint, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */))) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_not_be_a_primitive); } return booleanType; } @@ -71470,7 +73656,7 @@ var ts; if (rightIsThis === void 0) { rightIsThis = false; } var properties = node.properties; var property = properties[propertyIndex]; - if (property.kind === 288 /* PropertyAssignment */ || property.kind === 289 /* ShorthandPropertyAssignment */) { + if (property.kind === 289 /* PropertyAssignment */ || property.kind === 290 /* ShorthandPropertyAssignment */) { var name = property.name; var exprType = getLiteralTypeFromPropertyName(name); if (isTypeUsableAsPropertyName(exprType)) { @@ -71478,14 +73664,14 @@ var ts; var prop = getPropertyOfType(objectLiteralType, text); if (prop) { markPropertyAsReferenced(prop, property, rightIsThis); - checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + checkPropertyAccessibility(property, /*isSuper*/ false, /*writing*/ true, objectLiteralType, prop); } } var elementType = getIndexedAccessType(objectLiteralType, exprType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */); var type = getFlowTypeOfDestructuring(property, elementType); - return checkDestructuringAssignment(property.kind === 289 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); + return checkDestructuringAssignment(property.kind === 290 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } - else if (property.kind === 290 /* SpreadAssignment */) { + else if (property.kind === 291 /* SpreadAssignment */) { if (propertyIndex < properties.length - 1) { error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } @@ -71523,7 +73709,7 @@ var ts; var inBoundsType = compilerOptions.noUncheckedIndexedAccess ? undefined : possiblyOutOfBoundsType; for (var i = 0; i < elements.length; i++) { var type = possiblyOutOfBoundsType; - if (node.elements[i].kind === 220 /* SpreadElement */) { + if (node.elements[i].kind === 221 /* SpreadElement */) { type = inBoundsType = inBoundsType !== null && inBoundsType !== void 0 ? inBoundsType : (checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType); } checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, type, checkMode); @@ -71533,8 +73719,8 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 222 /* OmittedExpression */) { - if (element.kind !== 220 /* SpreadElement */) { + if (element.kind !== 223 /* OmittedExpression */) { + if (element.kind !== 221 /* SpreadElement */) { var indexType = getLiteralType(elementIndex); if (isArrayLikeType(sourceType)) { // We create a synthetic expression so that getIndexedAccessType doesn't get confused @@ -71552,7 +73738,7 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 216 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) { + if (restExpression.kind === 217 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -71568,7 +73754,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; - if (exprOrAssignment.kind === 289 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 290 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove @@ -71584,24 +73770,24 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 216 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) { + if (target.kind === 217 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 200 /* ObjectLiteralExpression */) { + if (target.kind === 201 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } - if (target.kind === 199 /* ArrayLiteralExpression */) { + if (target.kind === 200 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 290 /* SpreadAssignment */ ? + var error = target.parent.kind === 291 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; - var optionalError = target.parent.kind === 290 /* SpreadAssignment */ ? + var optionalError = target.parent.kind === 291 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access; if (checkReferenceExpression(target, error, optionalError)) { @@ -71626,8 +73812,8 @@ var ts; case 78 /* Identifier */: case 10 /* StringLiteral */: case 13 /* RegularExpressionLiteral */: - case 205 /* TaggedTemplateExpression */: - case 218 /* TemplateExpression */: + case 206 /* TaggedTemplateExpression */: + case 219 /* TemplateExpression */: case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: case 9 /* BigIntLiteral */: @@ -71635,27 +73821,27 @@ var ts; case 94 /* FalseKeyword */: case 103 /* NullKeyword */: case 150 /* UndefinedKeyword */: - case 208 /* FunctionExpression */: - case 221 /* ClassExpression */: - case 209 /* ArrowFunction */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 211 /* TypeOfExpression */: - case 225 /* NonNullExpression */: - case 274 /* JsxSelfClosingElement */: - case 273 /* JsxElement */: + case 209 /* FunctionExpression */: + case 222 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 212 /* TypeOfExpression */: + case 226 /* NonNullExpression */: + case 275 /* JsxSelfClosingElement */: + case 274 /* JsxElement */: return true; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: // Unary operators ~, !, +, and - have no side effects. // The rest do. switch (node.operator) { @@ -71667,9 +73853,9 @@ var ts; } return false; // Some forms listed here for clarity - case 212 /* VoidExpression */: // Explicit opt-out - case 206 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 224 /* AsExpression */: // Not SEF, but can produce useful type warnings + case 213 /* VoidExpression */: // Explicit opt-out + case 207 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 225 /* AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } @@ -71677,84 +73863,111 @@ var ts; function isTypeEqualityComparableTo(source, target) { return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } - var CheckBinaryExpressionState; - (function (CheckBinaryExpressionState) { - CheckBinaryExpressionState[CheckBinaryExpressionState["MaybeCheckLeft"] = 0] = "MaybeCheckLeft"; - CheckBinaryExpressionState[CheckBinaryExpressionState["CheckRight"] = 1] = "CheckRight"; - CheckBinaryExpressionState[CheckBinaryExpressionState["FinishCheck"] = 2] = "FinishCheck"; - })(CheckBinaryExpressionState || (CheckBinaryExpressionState = {})); - function checkBinaryExpression(node, checkMode) { - var workStacks = { - expr: [node], - state: [0 /* MaybeCheckLeft */], - leftType: [undefined] + function createCheckBinaryExpression() { + var trampoline = ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState); + return function (node, checkMode) { + var result = trampoline(node, checkMode); + ts.Debug.assertIsDefined(result); + return result; }; - var stackIndex = 0; - var lastResult; - while (stackIndex >= 0) { - node = workStacks.expr[stackIndex]; - switch (workStacks.state[stackIndex]) { - case 0 /* MaybeCheckLeft */: { - if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { - finishInvocation(checkExpression(node.right, checkMode)); - break; - } - checkGrammarNullishCoalesceWithLogicalExpression(node); - var operator = node.operatorToken.kind; - if (operator === 62 /* EqualsToken */ && (node.left.kind === 200 /* ObjectLiteralExpression */ || node.left.kind === 199 /* ArrayLiteralExpression */)) { - finishInvocation(checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 107 /* ThisKeyword */)); - break; - } - advanceState(1 /* CheckRight */); - maybeCheckExpression(node.left); - break; - } - case 1 /* CheckRight */: { - var leftType = lastResult; - workStacks.leftType[stackIndex] = leftType; - var operator = node.operatorToken.kind; - if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) { - if (operator === 55 /* AmpersandAmpersandToken */) { - var parent = ts.walkUpParenthesizedExpressions(node.parent); - checkTestingKnownTruthyCallableType(node.left, leftType, ts.isIfStatement(parent) ? parent.thenStatement : undefined); - } - checkTruthinessOfType(leftType, node.left); + function onEnter(node, state, checkMode) { + if (state) { + state.stackIndex++; + state.skip = false; + setLeftType(state, /*type*/ undefined); + setLastResult(state, /*type*/ undefined); + } + else { + state = { + checkMode: checkMode, + skip: false, + stackIndex: 0, + typeStack: [undefined, undefined], + }; + } + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { + state.skip = true; + setLastResult(state, checkExpression(node.right, checkMode)); + return state; + } + checkGrammarNullishCoalesceWithLogicalExpression(node); + var operator = node.operatorToken.kind; + if (operator === 62 /* EqualsToken */ && (node.left.kind === 201 /* ObjectLiteralExpression */ || node.left.kind === 200 /* ArrayLiteralExpression */)) { + state.skip = true; + setLastResult(state, checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 107 /* ThisKeyword */)); + return state; + } + return state; + } + function onLeft(left, state, _node) { + if (!state.skip) { + return maybeCheckExpression(state, left); + } + } + function onOperator(operatorToken, state, node) { + if (!state.skip) { + var leftType = getLastResult(state); + ts.Debug.assertIsDefined(leftType); + setLeftType(state, leftType); + setLastResult(state, /*type*/ undefined); + var operator = operatorToken.kind; + if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) { + if (operator === 55 /* AmpersandAmpersandToken */) { + var parent = ts.walkUpParenthesizedExpressions(node.parent); + checkTestingKnownTruthyCallableOrAwaitableType(node.left, leftType, ts.isIfStatement(parent) ? parent.thenStatement : undefined); } - advanceState(2 /* FinishCheck */); - maybeCheckExpression(node.right); - break; - } - case 2 /* FinishCheck */: { - var leftType = workStacks.leftType[stackIndex]; - var rightType = lastResult; - finishInvocation(checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node)); - break; + checkTruthinessOfType(leftType, node.left); } - default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for checkBinaryExpression"); } } - return lastResult; - function finishInvocation(result) { - lastResult = result; - stackIndex--; - } - /** - * Note that `advanceState` sets the _current_ head state, and that `maybeCheckExpression` potentially pushes on a new - * head state; so `advanceState` must be called before any `maybeCheckExpression` during a state's execution. - */ - function advanceState(nextState) { - workStacks.state[stackIndex] = nextState; + function onRight(right, state, _node) { + if (!state.skip) { + return maybeCheckExpression(state, right); + } } - function maybeCheckExpression(node) { - if (ts.isBinaryExpression(node)) { - stackIndex++; - workStacks.expr[stackIndex] = node; - workStacks.state[stackIndex] = 0 /* MaybeCheckLeft */; - workStacks.leftType[stackIndex] = undefined; + function onExit(node, state) { + var result; + if (state.skip) { + result = getLastResult(state); } else { - lastResult = checkExpression(node, checkMode); + var leftType = getLeftType(state); + ts.Debug.assertIsDefined(leftType); + var rightType = getLastResult(state); + ts.Debug.assertIsDefined(rightType); + result = checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node); + } + state.skip = false; + setLeftType(state, /*type*/ undefined); + setLastResult(state, /*type*/ undefined); + state.stackIndex--; + return result; + } + function foldState(state, result, _side) { + setLastResult(state, result); + return state; + } + function maybeCheckExpression(state, node) { + if (ts.isBinaryExpression(node)) { + return node; } + setLastResult(state, checkExpression(node, state.checkMode)); + } + function getLeftType(state) { + return state.typeStack[state.stackIndex]; + } + function setLeftType(state, type) { + state.typeStack[state.stackIndex] = type; + } + function getLastResult(state) { + return state.typeStack[state.stackIndex + 1]; + } + function setLastResult(state, type) { + // To reduce overhead, reuse the next stack entry to store the + // last result. This avoids the overhead of an additional property + // on `WorkArea` and reuses empty stack entries as we walk back up + // the stack. + state.typeStack[state.stackIndex + 1] = type; } } function checkGrammarNullishCoalesceWithLogicalExpression(node) { @@ -71772,7 +73985,7 @@ var ts; // expression-wide checks and does not use a work stack to fold nested binary expressions into the same callstack frame function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 62 /* EqualsToken */ && (left.kind === 200 /* ObjectLiteralExpression */ || left.kind === 199 /* ArrayLiteralExpression */)) { + if (operator === 62 /* EqualsToken */ && (left.kind === 201 /* ObjectLiteralExpression */ || left.kind === 200 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 107 /* ThisKeyword */); } var leftType; @@ -72007,7 +74220,7 @@ var ts; if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false); - if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { + if ((symbol === null || symbol === void 0 ? void 0 : symbol.declarations) && symbol.declarations.some(ts.isJSDocTypedefTag)) { addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop); addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol); } @@ -72202,7 +74415,7 @@ var ts; } function checkConditionalExpression(node, checkMode) { var type = checkTruthinessExpression(node.condition); - checkTestingKnownTruthyCallableType(node.condition, type, node.whenTrue); + checkTestingKnownTruthyCallableOrAwaitableType(node.condition, type, node.whenTrue); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); return getUnionType([type1, type2], 2 /* Subtype */); @@ -72219,10 +74432,14 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return getFreshTypeOfLiteralType(getTemplateLiteralType(texts, types)); + return isConstContext(node) || someType(getContextualType(node) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; + } + function isTemplateLiteralContextualType(type) { + return !!(type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */) || + type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 402653316 /* StringLike */)); } function getContextNode(node) { - if (node.kind === 281 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { + if (node.kind === 282 /* 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; @@ -72238,7 +74455,7 @@ var ts; // We strip literal freshness when an appropriate contextual type is present such that contextually typed // literals always preserve their literal types (otherwise they might widen during type inference). An alternative // here would be to not mark contextually typed literals as fresh in the first place. - var result = maybeTypeOfKind(type, 134220672 /* FreshableLiteral */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -72271,13 +74488,13 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 206 /* TypeAssertionExpression */ || node.kind === 224 /* AsExpression */; + return node.kind === 207 /* TypeAssertionExpression */ || node.kind === 225 /* AsExpression */; } function checkDeclarationInitializer(declaration, contextualType) { var initializer = ts.getEffectiveInitializer(declaration); var type = getQuickTypeOfExpression(initializer) || (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer)); - return ts.isParameter(declaration) && declaration.name.kind === 197 /* ArrayBindingPattern */ && + return ts.isParameter(declaration) && declaration.name.kind === 198 /* ArrayBindingPattern */ && isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ? padTupleType(type, declaration.name) : type; } @@ -72287,7 +74504,7 @@ var ts; var elementFlags = type.target.elementFlags.slice(); for (var i = getTypeReferenceArity(type); i < patternElements.length; i++) { var e = patternElements[i]; - if (i < patternElements.length - 1 || !(e.kind === 198 /* BindingElement */ && e.dotDotDotToken)) { + if (i < patternElements.length - 1 || !(e.kind === 199 /* BindingElement */ && e.dotDotDotToken)) { elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType); elementFlags.push(2 /* Optional */); if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) { @@ -72322,7 +74539,7 @@ var ts; // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || unknownType; - return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || @@ -72330,7 +74547,7 @@ var ts; } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return !!(contextualType.flags & (134217856 /* StringLikeLiteral */ | 4194304 /* Index */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || @@ -72354,7 +74571,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); @@ -72365,7 +74582,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -72583,7 +74800,7 @@ var ts; } } function checkExpression(node, checkMode, forceTuple) { - ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -72593,7 +74810,7 @@ var ts; checkConstEnumAccess(node, type); } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return type; } function checkConstEnumAccess(node, type) { @@ -72601,11 +74818,11 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 202 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 78 /* Identifier */ || node.kind === 157 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || - (node.parent.kind === 176 /* TypeQuery */ && node.parent.exprName === node)) || - (node.parent.kind === 270 /* ExportSpecifier */); // We allow reexporting const enums + var ok = (node.parent.kind === 202 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 203 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 78 /* Identifier */ || node.kind === 158 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 177 /* TypeQuery */ && node.parent.exprName === node)) || + (node.parent.kind === 271 /* ExportSpecifier */); // We allow reexporting const enums if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } @@ -72630,15 +74847,15 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { case 78 /* Identifier */: - return checkIdentifier(node); + return checkIdentifier(node, checkMode); case 107 /* ThisKeyword */: return checkThisExpression(node); case 105 /* SuperKeyword */: @@ -72658,78 +74875,78 @@ var ts; return trueType; case 94 /* FalseKeyword */: return falseType; - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return checkTemplateExpression(node); case 13 /* RegularExpressionLiteral */: return globalRegExpType; - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return checkArrayLiteral(node, checkMode, forceTuple); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); - case 201 /* PropertyAccessExpression */: - return checkPropertyAccessExpression(node); - case 157 /* QualifiedName */: - return checkQualifiedName(node); - case 202 /* ElementAccessExpression */: - return checkIndexedAccess(node); - case 203 /* CallExpression */: + case 202 /* PropertyAccessExpression */: + return checkPropertyAccessExpression(node, checkMode); + case 158 /* QualifiedName */: + return checkQualifiedName(node, checkMode); + case 203 /* ElementAccessExpression */: + return checkIndexedAccess(node, checkMode); + case 204 /* CallExpression */: if (node.expression.kind === 99 /* ImportKeyword */) { return checkImportCallExpression(node); } // falls through - case 204 /* NewExpression */: + case 205 /* NewExpression */: return checkCallExpression(node, checkMode); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return checkParenthesizedExpression(node, checkMode); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return checkClassExpression(node); - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return checkAssertion(node); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return checkNonNullAssertion(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return checkMetaProperty(node); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return checkDeleteExpression(node); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return checkVoidExpression(node); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return checkAwaitExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return checkBinaryExpression(node, checkMode); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return checkConditionalExpression(node, checkMode); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return checkSpreadExpression(node, checkMode); - case 222 /* OmittedExpression */: + case 223 /* OmittedExpression */: return undefinedWideningType; - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return checkYieldExpression(node); - case 227 /* SyntheticExpression */: + case 228 /* SyntheticExpression */: return checkSyntheticExpression(node); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return checkJsxExpression(node, checkMode); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return checkJsxElement(node, checkMode); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node, checkMode); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return checkJsxFragment(node); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return errorType; @@ -72765,11 +74982,11 @@ var ts; checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) { - if (!(func.kind === 166 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { + if (!(func.kind === 167 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } - if (func.kind === 166 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") { + if (func.kind === 167 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") { error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name); } } @@ -72780,13 +74997,13 @@ var ts; if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 166 /* Constructor */ || func.kind === 170 /* ConstructSignature */ || func.kind === 175 /* ConstructorType */) { + if (func.kind === 167 /* Constructor */ || func.kind === 171 /* ConstructSignature */ || func.kind === 176 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } - if (func.kind === 209 /* ArrowFunction */) { + if (func.kind === 210 /* ArrowFunction */) { error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); } - if (func.kind === 167 /* GetAccessor */ || func.kind === 168 /* SetAccessor */) { + if (func.kind === 168 /* GetAccessor */ || func.kind === 169 /* SetAccessor */) { error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters); } } @@ -72844,13 +75061,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 209 /* ArrowFunction */: - case 169 /* CallSignature */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 174 /* FunctionType */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 210 /* ArrowFunction */: + case 170 /* CallSignature */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 175 /* FunctionType */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: var parent = node.parent; if (node === parent.type) { return parent; @@ -72868,7 +75085,7 @@ var ts; error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 197 /* ArrayBindingPattern */ || name.kind === 196 /* ObjectBindingPattern */) { + else if (name.kind === 198 /* ArrayBindingPattern */ || name.kind === 197 /* ObjectBindingPattern */) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -72877,13 +75094,13 @@ var ts; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 171 /* IndexSignature */) { + if (node.kind === 172 /* IndexSignature */) { checkGrammarIndexSignature(node); } // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled - else if (node.kind === 174 /* FunctionType */ || node.kind === 251 /* FunctionDeclaration */ || node.kind === 175 /* ConstructorType */ || - node.kind === 169 /* CallSignature */ || node.kind === 166 /* Constructor */ || - node.kind === 170 /* ConstructSignature */) { + else if (node.kind === 175 /* FunctionType */ || node.kind === 252 /* FunctionDeclaration */ || node.kind === 176 /* ConstructorType */ || + node.kind === 170 /* CallSignature */ || node.kind === 167 /* Constructor */ || + node.kind === 171 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); @@ -72913,10 +75130,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 169 /* CallSignature */: + case 170 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -72946,7 +75163,7 @@ var ts; checkAsyncFunctionReturnType(node, returnTypeNode); } } - if (node.kind !== 171 /* IndexSignature */ && node.kind !== 308 /* JSDocFunctionType */) { + if (node.kind !== 172 /* IndexSignature */ && node.kind !== 309 /* JSDocFunctionType */) { registerForUnusedIdentifiersCheck(node); } } @@ -72958,7 +75175,7 @@ var ts; var privateIdentifiers = new ts.Map(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 166 /* Constructor */) { + if (member.kind === 167 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) { @@ -72970,25 +75187,27 @@ var ts; var isStatic = ts.hasSyntacticModifier(member, 32 /* Static */); var name = member.name; if (!name) { - return; + continue; } - var names = ts.isPrivateIdentifier(name) ? privateIdentifiers : + var isPrivate = ts.isPrivateIdentifier(name); + var privateStaticFlags = isPrivate && isStatic ? 16 /* PrivateStatic */ : 0; + var names = isPrivate ? privateIdentifiers : isStatic ? staticNames : instanceNames; var memberName = name && ts.getPropertyNameForPropertyNameNode(name); if (memberName) { switch (member.kind) { - case 167 /* GetAccessor */: - addName(names, name, memberName, 1 /* GetAccessor */); + case 168 /* GetAccessor */: + addName(names, name, memberName, 1 /* GetAccessor */ | privateStaticFlags); break; - case 168 /* SetAccessor */: - addName(names, name, memberName, 2 /* SetAccessor */); + case 169 /* SetAccessor */: + addName(names, name, memberName, 2 /* SetAccessor */ | privateStaticFlags); break; - case 163 /* PropertyDeclaration */: - addName(names, name, memberName, 3 /* GetOrSetAccessor */); + case 164 /* PropertyDeclaration */: + addName(names, name, memberName, 3 /* GetOrSetAccessor */ | privateStaticFlags); break; - case 165 /* MethodDeclaration */: - addName(names, name, memberName, 8 /* Method */); + case 166 /* MethodDeclaration */: + addName(names, name, memberName, 8 /* Method */ | privateStaticFlags); break; } } @@ -72997,16 +75216,25 @@ var ts; function addName(names, location, name, meaning) { var prev = names.get(name); if (prev) { - if (prev & 8 /* Method */) { - if (meaning !== 8 /* Method */) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); - } - } - else if (prev & meaning) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + // For private identifiers, do not allow mixing of static and instance members with the same name + if ((prev & 16 /* PrivateStatic */) !== (meaning & 16 /* PrivateStatic */)) { + error(location, ts.Diagnostics.Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name, ts.getTextOfNode(location)); } else { - names.set(name, prev | meaning); + var prevIsMethod = !!(prev & 8 /* Method */); + var isMethod = !!(meaning & 8 /* Method */); + if (prevIsMethod || isMethod) { + if (prevIsMethod !== isMethod) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + // If this is a method/method duplication is might be an overload, so this will be handled when overloads are considered + } + else if (prev & meaning & ~16 /* PrivateStatic */) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names.set(name, prev | meaning); + } } } else { @@ -73050,7 +75278,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 162 /* PropertySignature */) { + if (member.kind === 163 /* PropertySignature */) { var memberName = void 0; var name = member.name; switch (name.kind) { @@ -73075,11 +75303,11 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 253 /* InterfaceDeclaration */) { + if (node.kind === 254 /* InterfaceDeclaration */) { var nodeSymbol = getSymbolOfNode(node); // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration // to prevent this run check only for the first declaration of a given kind - if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + if (nodeSymbol.declarations && nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; } } @@ -73087,7 +75315,7 @@ var ts; // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); - if (indexSymbol) { + if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { var seenNumericIndexer = false; var seenStringIndexer = false; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -73121,11 +75349,9 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); - // Private class fields transformation relies on WeakMaps. - if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) { - for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) { - getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */; - } + setNodeLinksForPrivateIdentifierScope(node); + if (ts.isPrivateIdentifier(node.name) && ts.hasStaticModifier(node) && node.initializer && languageVersion === 99 /* ESNext */ && !compilerOptions.useDefineForClassFields) { + error(node.initializer, ts.Diagnostics.Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag); } } function checkPropertySignature(node) { @@ -73138,16 +75364,35 @@ var ts; // Grammar checking if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); - if (ts.isPrivateIdentifier(node.name)) { - error(node, ts.Diagnostics.A_method_cannot_be_named_with_a_private_identifier); - } // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (ts.hasSyntacticModifier(node, 128 /* Abstract */) && node.kind === 165 /* MethodDeclaration */ && node.body) { + if (ts.hasSyntacticModifier(node, 128 /* Abstract */) && node.kind === 166 /* MethodDeclaration */ && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } + // Private named methods are only allowed in class declarations + if (ts.isPrivateIdentifier(node.name) && !ts.getContainingClass(node)) { + error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + } + setNodeLinksForPrivateIdentifierScope(node); + } + function setNodeLinksForPrivateIdentifierScope(node) { + if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) { + for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) { + getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */; + } + // If this is a private element in a class expression inside the body of a loop, + // then we must use a block-scoped binding to store the additional variables required + // to transform private elements. + if (ts.isClassExpression(node.parent)) { + var enclosingIterationStatement = getEnclosingIterationStatement(node.parent); + if (enclosingIterationStatement) { + getNodeLinks(node.name).flags |= 524288 /* BlockScopedBindingInLoop */; + getNodeLinks(enclosingIterationStatement).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } + } + } } function checkConstructorDeclaration(node) { // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. @@ -73170,10 +75415,10 @@ var ts; return; } function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) { - if (ts.isPrivateIdentifierPropertyDeclaration(n)) { + if (ts.isPrivateIdentifierClassElementDeclaration(n)) { return true; } - return n.kind === 163 /* PropertyDeclaration */ && + return n.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(n, 32 /* Static */) && !!n.initializer; } @@ -73194,9 +75439,9 @@ var ts; // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) && + var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !useDefineForClassFields) && (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 92 /* ParameterPropertyModifier */); })); + ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */); })); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -73204,7 +75449,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) { var statement = statements_4[_i]; - if (statement.kind === 233 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 234 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -73229,7 +75474,7 @@ var ts; checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 167 /* GetAccessor */) { + if (node.kind === 168 /* GetAccessor */) { if (!(node.flags & 8388608 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 256 /* HasImplicitReturn */)) { if (!(node.flags & 512 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); @@ -73239,45 +75484,42 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } - if (ts.isPrivateIdentifier(node.name)) { - error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier); - } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. - var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; - var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); - if (otherAccessor) { - var nodeFlags = ts.getEffectiveModifierFlags(node); - var otherFlags = ts.getEffectiveModifierFlags(otherAccessor); - if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) { - error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + var symbol = getSymbolOfNode(node); + var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); + if (getter && setter && !(getNodeCheckFlags(getter) & 1 /* TypeChecked */)) { + getNodeLinks(getter).flags |= 1 /* TypeChecked */; + var getterFlags = ts.getEffectiveModifierFlags(getter); + var setterFlags = ts.getEffectiveModifierFlags(setter); + if ((getterFlags & 128 /* Abstract */) !== (setterFlags & 128 /* Abstract */)) { + error(getter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(setter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } + if (((getterFlags & 16 /* Protected */) && !(setterFlags & (16 /* Protected */ | 8 /* Private */))) || + ((getterFlags & 8 /* Private */) && !(setterFlags & 8 /* Private */))) { + error(getter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(setter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); } - if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) { - error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + var getterType = getAnnotatedAccessorType(getter); + var setterType = getAnnotatedAccessorType(setter); + if (getterType && setterType) { + checkTypeAssignableTo(getterType, setterType, getter, ts.Diagnostics.The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type); } - // TypeScript 1.0 spec (April 2014): 4.5 - // If both accessors include type annotations, the specified types must be identical. - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 167 /* GetAccessor */) { + if (node.kind === 168 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } checkSourceElement(node.body); - } - function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { - var firstType = getAnnotatedType(first); - var secondType = getAnnotatedType(second); - if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { - error(first, message); - } + setNodeLinksForPrivateIdentifierScope(node); } function checkMissingDeclaration(node) { checkDecorators(node); @@ -73314,7 +75556,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 173 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 174 /* 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); } ts.forEach(node.typeArguments, checkSourceElement); @@ -73329,7 +75571,7 @@ var ts; var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, getDeprecatedSuggestionNode(node), ts.Diagnostics._0_is_deprecated, symbol.escapedName); + addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 /* Enum */ && symbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); @@ -73367,7 +75609,7 @@ var ts; var hasNamedElement = ts.some(elementTypes, ts.isNamedTupleMember); for (var _i = 0, elementTypes_1 = elementTypes; _i < elementTypes_1.length; _i++) { var e = elementTypes_1[_i]; - if (e.kind !== 192 /* NamedTupleMember */ && hasNamedElement) { + if (e.kind !== 193 /* NamedTupleMember */ && hasNamedElement) { grammarErrorOnNode(e, ts.Diagnostics.Tuple_members_must_all_have_names_or_all_not_have_names); break; } @@ -73416,7 +75658,7 @@ var ts; var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { - if (accessNode.kind === 202 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + if (accessNode.kind === 203 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } @@ -73474,7 +75716,7 @@ var ts; ts.forEachChild(node, checkSourceElement); } function checkInferType(node) { - if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 184 /* ConditionalType */ && n.parent.extendsType === n; })) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 185 /* ConditionalType */ && n.parent.extendsType === n; })) { grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); @@ -73497,25 +75739,25 @@ var ts; if (node.dotDotDotToken && node.questionToken) { grammarErrorOnNode(node, ts.Diagnostics.A_tuple_member_cannot_be_both_optional_and_rest); } - if (node.type.kind === 180 /* OptionalType */) { + if (node.type.kind === 181 /* OptionalType */) { grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type); } - if (node.type.kind === 181 /* RestType */) { + if (node.type.kind === 182 /* RestType */) { grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type); } checkSourceElement(node.type); getTypeFromTypeNode(node); } function isPrivateWithinAmbient(node) { - return (ts.hasEffectiveModifier(node, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */); + return (ts.hasEffectiveModifier(node, 8 /* Private */) || ts.isPrivateIdentifierClassElementDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 253 /* InterfaceDeclaration */ && - n.parent.kind !== 252 /* ClassDeclaration */ && - n.parent.kind !== 221 /* ClassExpression */ && + if (n.parent.kind !== 254 /* InterfaceDeclaration */ && + n.parent.kind !== 253 /* ClassDeclaration */ && + n.parent.kind !== 222 /* ClassExpression */ && n.flags & 8388608 /* Ambient */) { if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { // It is nested in an ambient context, which means it is automatically exported @@ -73611,7 +75853,7 @@ var ts; // Both are literal property names that are the same. ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - var reportError = (node.kind === 165 /* MethodDeclaration */ || node.kind === 164 /* MethodSignature */) && + var reportError = (node.kind === 166 /* MethodDeclaration */ || node.kind === 165 /* MethodSignature */) && ts.hasSyntacticModifier(node, 32 /* Static */) !== ts.hasSyntacticModifier(subsequentNode, 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members @@ -73648,55 +75890,57 @@ var ts; var multipleConstructorImplementation = false; var hasNonAmbientClass = false; var functionDeclarations = []; - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var current = declarations_4[_i]; - var node = current; - var inAmbientContext = node.flags & 8388608 /* Ambient */; - var inAmbientContextOrInterface = node.parent && (node.parent.kind === 253 /* InterfaceDeclaration */ || node.parent.kind === 177 /* TypeLiteral */) || inAmbientContext; - if (inAmbientContextOrInterface) { - // check if declarations are consecutive only if they are non-ambient - // 1. ambient declarations can be interleaved - // i.e. this is legal - // declare function foo(); - // declare function bar(); - // declare function foo(); - // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one - previousDeclaration = undefined; - } - if ((node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */) && !inAmbientContext) { - hasNonAmbientClass = true; - } - if (node.kind === 251 /* FunctionDeclaration */ || node.kind === 165 /* MethodDeclaration */ || node.kind === 164 /* MethodSignature */ || node.kind === 166 /* Constructor */) { - functionDeclarations.push(node); - var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); - someNodeFlags |= currentNodeFlags; - allNodeFlags &= currentNodeFlags; - someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); - allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); - var bodyIsPresent = ts.nodeIsPresent(node.body); - if (bodyIsPresent && bodyDeclaration) { - if (isConstructor) { - multipleConstructorImplementation = true; + if (declarations) { + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; + var node = current; + var inAmbientContext = node.flags & 8388608 /* Ambient */; + var inAmbientContextOrInterface = node.parent && (node.parent.kind === 254 /* InterfaceDeclaration */ || node.parent.kind === 178 /* TypeLiteral */) || inAmbientContext; + if (inAmbientContextOrInterface) { + // check if declarations are consecutive only if they are non-ambient + // 1. ambient declarations can be interleaved + // i.e. this is legal + // declare function foo(); + // declare function bar(); + // declare function foo(); + // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one + previousDeclaration = undefined; + } + if ((node.kind === 253 /* ClassDeclaration */ || node.kind === 222 /* ClassExpression */) && !inAmbientContext) { + hasNonAmbientClass = true; + } + if (node.kind === 252 /* FunctionDeclaration */ || node.kind === 166 /* MethodDeclaration */ || node.kind === 165 /* MethodSignature */ || node.kind === 167 /* Constructor */) { + functionDeclarations.push(node); + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); + var bodyIsPresent = ts.nodeIsPresent(node.body); + if (bodyIsPresent && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } + } + else if ((previousDeclaration === null || previousDeclaration === void 0 ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (bodyIsPresent) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } } else { - duplicateFunctionDeclaration = true; + hasOverloads = true; } - } - else if ((previousDeclaration === null || previousDeclaration === void 0 ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) { - reportImplementationExpectedError(previousDeclaration); - } - if (bodyIsPresent) { - if (!bodyDeclaration) { - bodyDeclaration = node; + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; } } - else { - hasOverloads = true; - } - previousDeclaration = node; - if (!inAmbientContextOrInterface) { - lastSeenNonAmbientDeclaration = node; - } } } if (multipleConstructorImplementation) { @@ -73724,8 +75968,10 @@ var ts; reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { - checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); - checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (declarations) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + } if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); @@ -73799,43 +76045,46 @@ var ts; function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: // A jsdoc typedef and callback are, by definition, type aliases. // falls through - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return 2 /* ExportType */; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4 /* ExportNamespace */ | 1 /* ExportValue */ : 4 /* ExportNamespace */; - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: return 2 /* ExportType */ | 1 /* ExportValue */; - case 297 /* SourceFile */: + case 298 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: + case 217 /* BinaryExpression */: + var node_2 = d; + var expression = ts.isExportAssignment(node_2) ? node_2.expression : node_2.right; // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values - if (!ts.isEntityNameExpression(d.expression)) { + if (!ts.isEntityNameExpression(expression)) { return 1 /* ExportValue */; } - d = d.expression; + d = expression; // The below options all declare an Alias, which is allowed to merge with other values within the importing module. // falls through - case 260 /* ImportEqualsDeclaration */: - case 263 /* NamespaceImport */: - case 262 /* ImportClause */: - var result_12 = 0 /* None */; + case 261 /* ImportEqualsDeclaration */: + case 264 /* NamespaceImport */: + case 263 /* ImportClause */: + var result_13 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_12 |= getDeclarationSpaces(d); }); - return result_12; - case 249 /* VariableDeclaration */: - case 198 /* BindingElement */: - case 251 /* FunctionDeclaration */: - case 265 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + ts.forEach(target.declarations, function (d) { result_13 |= getDeclarationSpaces(d); }); + return result_13; + case 250 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 252 /* FunctionDeclaration */: + case 266 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 case 78 /* Identifier */: // https://github.com/microsoft/TypeScript/issues/36098 // Identifiers are used as declarations of assignment declarations whose parents may be // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});` @@ -74128,24 +76377,24 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 160 /* Parameter */: + case 161 /* Parameter */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -74192,15 +76441,15 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { - case 183 /* IntersectionType */: - case 182 /* UnionType */: + case 184 /* IntersectionType */: + case 183 /* UnionType */: return getEntityNameForDecoratorMetadataFromTypeList(node.types); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); - case 186 /* ParenthesizedType */: - case 192 /* NamedTupleMember */: + case 187 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: return getEntityNameForDecoratorMetadata(node.type); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return node.typeName; } } @@ -74209,13 +76458,13 @@ var ts; var commonEntityName; for (var _i = 0, types_23 = types; _i < types_23.length; _i++) { var typeNode = types_23[_i]; - while (typeNode.kind === 186 /* ParenthesizedType */ || typeNode.kind === 192 /* NamedTupleMember */) { + while (typeNode.kind === 187 /* ParenthesizedType */ || typeNode.kind === 193 /* NamedTupleMember */) { typeNode = typeNode.type; // Skip parens if need be } if (typeNode.kind === 141 /* NeverKeyword */) { continue; // Always elide `never` from the union/intersection if possible } - if (!strictNullChecks && (typeNode.kind === 191 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { + if (!strictNullChecks && (typeNode.kind === 192 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); @@ -74261,14 +76510,14 @@ var ts; } var firstDecorator = node.decorators[0]; checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); - if (node.kind === 160 /* Parameter */) { + if (node.kind === 161 /* Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* Param */); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -74277,23 +76526,23 @@ var ts; } } break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + var otherKind = node.kind === 168 /* GetAccessor */ ? 169 /* SetAccessor */ : 168 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 160 /* Parameter */: + case 161 /* Parameter */: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); var containingSignature = node.parent; for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { @@ -74356,7 +76605,7 @@ var ts; else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 157 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 158 /* QualifiedName */ ? node.name.right : node.name)); } } } @@ -74400,25 +76649,26 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return node.name; default: return undefined; } } function checkFunctionOrMethodDeclaration(node) { + var _a; checkDecorators(node); checkSignatureDeclaration(node); var functionFlags = ts.getFunctionFlags(node); // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name && node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 159 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // first we want to check the local symbol that contain this declaration // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode @@ -74427,7 +76677,7 @@ var ts; // Since the javascript won't do semantic analysis like typescript, // if the javascript file comes before the typescript file and both contain same name functions, // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. - var firstDeclaration = ts.find(localSymbol.declarations, + var firstDeclaration = (_a = localSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find( // Get first non javascript function declaration function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072 /* JavaScriptFile */); }); // Only type check the symbol once @@ -74439,7 +76689,7 @@ var ts; checkFunctionOrConstructorSymbol(symbol); } } - var body = node.kind === 164 /* MethodSignature */ ? undefined : node.body; + var body = node.kind === 165 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node)); if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { @@ -74481,42 +76731,42 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: checkUnusedClassMembers(node, addDiagnostic); checkUnusedTypeParameters(node, addDiagnostic); break; - case 297 /* SourceFile */: - case 256 /* ModuleDeclaration */: - case 230 /* Block */: - case 258 /* CaseBlock */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 298 /* SourceFile */: + case 257 /* ModuleDeclaration */: + case 231 /* Block */: + case 259 /* CaseBlock */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: checkUnusedLocalsAndParameters(node, addDiagnostic); break; - case 166 /* Constructor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 167 /* Constructor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: if (node.body) { // Don't report unused parameters in overloads checkUnusedLocalsAndParameters(node, addDiagnostic); } checkUnusedTypeParameters(node, addDiagnostic); break; - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: checkUnusedTypeParameters(node, addDiagnostic); break; - case 185 /* InferType */: + case 186 /* InferType */: checkUnusedInferTypeParameter(node, addDiagnostic); break; default: @@ -74536,11 +76786,11 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 165 /* MethodDeclaration */: - case 163 /* PropertyDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - if (member.kind === 168 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + case 166 /* MethodDeclaration */: + case 164 /* PropertyDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + if (member.kind === 169 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { // Already would have reported an error on the getter. break; } @@ -74551,7 +76801,7 @@ var ts; addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; - case 166 /* Constructor */: + case 167 /* Constructor */: for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasSyntacticModifier(parameter, 8 /* Private */)) { @@ -74559,8 +76809,8 @@ var ts; } } break; - case 171 /* IndexSignature */: - case 229 /* SemicolonClassElement */: + case 172 /* IndexSignature */: + case 230 /* SemicolonClassElement */: // Can't be private break; default: @@ -74577,7 +76827,8 @@ var ts; function checkUnusedTypeParameters(node, addDiagnostic) { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. - if (ts.last(getSymbolOfNode(node).declarations) !== node) + var declarations = getSymbolOfNode(node).declarations; + if (!declarations || ts.last(declarations) !== node) return; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); var seenParentsWithEveryUnused = new ts.Set(); @@ -74587,7 +76838,7 @@ var ts; continue; var name = ts.idText(typeParameter.name); var parent = typeParameter.parent; - if (parent.kind !== 185 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (parent.kind !== 186 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { if (ts.tryAddToSet(seenParentsWithEveryUnused, parent)) { var sourceFile = ts.getSourceFileOfNode(parent); var range = ts.isJSDocTemplateTag(parent) @@ -74623,11 +76874,15 @@ var ts; return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } function isValidUnusedLocalDeclaration(declaration) { - if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { - return !!ts.findAncestor(declaration.parent, function (ancestor) { - return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : - ts.isForOfStatement(ancestor) ? true : "quit"; - }); + if (ts.isBindingElement(declaration)) { + if (ts.isObjectBindingPattern(declaration.parent)) { + /** + * ignore starts with underscore names _ + * const { a: _a } = { a: 1 } + */ + return !!(declaration.propertyName && isIdentifierThatStartsWithUnderscore(declaration.name)); + } + return isIdentifierThatStartsWithUnderscore(declaration.name); } return ts.isAmbientModule(declaration) || (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); @@ -74643,39 +76898,41 @@ var ts; if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) { return; } - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (isValidUnusedLocalDeclaration(declaration)) { - continue; - } - if (isImportedDeclaration(declaration)) { - addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); - } - else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { - // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. - var lastElement = ts.last(declaration.parent.elements); - if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { - addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + if (local.declarations) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (isValidUnusedLocalDeclaration(declaration)) { + continue; } - } - else if (ts.isVariableDeclaration(declaration)) { - addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); - } - else { - var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); - var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); - if (parameter && name) { - if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { - if (ts.isBindingElement(declaration) && ts.isArrayBindingPattern(declaration.parent)) { - addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); - } - else { - addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); - } + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); } } + else if (ts.isVariableDeclaration(declaration)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } else { - errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); + if (parameter && name) { + if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { + if (ts.isBindingElement(declaration) && ts.isArrayBindingPattern(declaration.parent)) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + else { + addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); + } + } + } + else { + errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); + } } } } @@ -74685,7 +76942,7 @@ var ts; var importDecl = importClause.parent; var nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? - (importClause.namedBindings.kind === 263 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + (importClause.namedBindings.kind === 264 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 @@ -74703,7 +76960,7 @@ var ts; var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; if (bindingPattern.elements.length === bindingElements.length) { - if (bindingElements.length === 1 && bindingPattern.parent.kind === 249 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 250 /* VariableDeclarationList */) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 250 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 251 /* VariableDeclarationList */) { addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { @@ -74724,7 +76981,7 @@ var ts; if (declarationList.declarations.length === declarations.length) { addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) - : ts.createDiagnosticForNode(declarationList.parent.kind === 232 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + : ts.createDiagnosticForNode(declarationList.parent.kind === 233 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { @@ -74738,22 +76995,22 @@ var ts; switch (name.kind) { case 78 /* Identifier */: return ts.idText(name); - case 197 /* ArrayBindingPattern */: - case 196 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); default: return ts.Debug.assertNever(name); } } function isImportedDeclaration(node) { - return node.kind === 262 /* ImportClause */ || node.kind === 265 /* ImportSpecifier */ || node.kind === 263 /* NamespaceImport */; + return node.kind === 263 /* ImportClause */ || node.kind === 266 /* ImportSpecifier */ || node.kind === 264 /* NamespaceImport */; } function importClauseFromImported(decl) { - return decl.kind === 262 /* ImportClause */ ? decl : decl.kind === 263 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + return decl.kind === 263 /* ImportClause */ ? decl : decl.kind === 264 /* NamespaceImport */ ? decl.parent : decl.parent.parent; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 230 /* Block */) { + if (node.kind === 231 /* Block */) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -74783,12 +77040,12 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 163 /* PropertyDeclaration */ || - node.kind === 162 /* PropertySignature */ || - node.kind === 165 /* MethodDeclaration */ || - node.kind === 164 /* MethodSignature */ || - node.kind === 167 /* GetAccessor */ || - node.kind === 168 /* SetAccessor */) { + if (node.kind === 164 /* PropertyDeclaration */ || + node.kind === 163 /* PropertySignature */ || + node.kind === 166 /* MethodDeclaration */ || + node.kind === 165 /* MethodSignature */ || + node.kind === 168 /* GetAccessor */ || + node.kind === 169 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } @@ -74797,7 +77054,7 @@ var ts; return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 160 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 161 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -74834,10 +77091,11 @@ var ts; return false; }); } - function checkWeakMapCollision(node) { + function checkWeakMapSetCollision(node) { var enclosingBlockScope = ts.getEnclosingBlockScopeContainer(node); if (getNodeCheckFlags(enclosingBlockScope) & 67108864 /* ContainsClassWithPrivateIdentifiers */) { - errorSkippedOn("noEmit", node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, "WeakMap"); + ts.Debug.assert(ts.isNamedDeclaration(node) && ts.isIdentifier(node.name) && typeof node.name.escapedText === "string", "The target of a WeakMap/WeakSet collision check should be an identifier"); + errorSkippedOn("noEmit", node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, node.name.escapedText); } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { @@ -74854,7 +77112,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords errorSkippedOn("noEmit", name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -74869,7 +77127,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) { + if (parent.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. errorSkippedOn("noEmit", name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -74904,7 +77162,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 249 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 250 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -74916,17 +77174,17 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 250 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 232 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 251 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 233 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) var namesShareScope = container && - (container.kind === 230 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 257 /* ModuleBlock */ || - container.kind === 256 /* ModuleDeclaration */ || - container.kind === 297 /* SourceFile */); + (container.kind === 231 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 258 /* ModuleBlock */ || + container.kind === 257 /* ModuleDeclaration */ || + container.kind === 298 /* SourceFile */); // here we know that function scoped variable is shadowed by block scoped one // if they are defined in the same scope - binder has already reported redeclaration error // otherwise if variable has an initializer - show error that initialization will fail @@ -74957,18 +77215,18 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 198 /* BindingElement */) { - if (node.parent.kind === 196 /* ObjectBindingPattern */ && languageVersion < 99 /* ESNext */) { + if (ts.isBindingElement(node)) { + if (ts.isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < 5 /* ES2018 */) { checkExternalEmitHelpers(node, 4 /* Rest */); } // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 158 /* ComputedPropertyName */) { + if (node.propertyName && node.propertyName.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } // check private/protected variable access @@ -74981,15 +77239,15 @@ var ts; var nameText = getPropertyNameFromType(exprType); var property = getPropertyOfType(parentType, nameText); if (property) { - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 105 /* SuperKeyword */, parentType, property); + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isSelfTypeAccess*/ false); // A destructuring is never a write-only reference. + checkPropertyAccessibility(node, !!parent.initializer && parent.initializer.kind === 105 /* SuperKeyword */, /*writing*/ false, parentType, property); } } } } // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 197 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + if (node.name.kind === 198 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } ts.forEach(node.name.elements, checkSourceElement); @@ -75001,7 +77259,7 @@ var ts; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { - var needCheckInitializer = node.initializer && node.parent.parent.kind !== 238 /* ForInStatement */; + var needCheckInitializer = node.initializer && node.parent.parent.kind !== 239 /* ForInStatement */; var needCheckWidenedType = node.name.elements.length === 0; if (needCheckInitializer || needCheckWidenedType) { // Don't validate for-in initializer as it is already an error @@ -75029,7 +77287,7 @@ var ts; } // For a commonjs `const x = require`, validate the alias and exit var symbol = getSymbolOfNode(node); - if (symbol.flags & 2097152 /* Alias */ && ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true)) { + if (symbol.flags & 2097152 /* Alias */ && ts.isRequireVariableDeclaration(node)) { checkAliasSymbol(node); return; } @@ -75043,11 +77301,11 @@ var ts; ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && !!((_a = symbol.exports) === null || _a === void 0 ? void 0 : _a.size); - if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 238 /* ForInStatement */) { + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 239 /* ForInStatement */) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); } } - if (symbol.declarations.length > 1) { + if (symbol.declarations && symbol.declarations.length > 1) { if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) { error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } @@ -75065,26 +77323,27 @@ var ts; if (node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } - if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 163 /* PropertyDeclaration */ && node.kind !== 162 /* PropertySignature */) { + if (node.kind !== 164 /* PropertyDeclaration */ && node.kind !== 163 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) { + if (node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - if (languageVersion < 99 /* ESNext */ && needCollisionCheckForIdentifier(node, node.name, "WeakMap")) { - potentialWeakMapCollisions.push(node); + if (languageVersion < 99 /* ESNext */ + && (needCollisionCheckForIdentifier(node, node.name, "WeakMap") || needCollisionCheckForIdentifier(node, node.name, "WeakSet"))) { + potentialWeakMapSetCollisions.push(node); } } } function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) { var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); - var message = nextDeclaration.kind === 163 /* PropertyDeclaration */ || nextDeclaration.kind === 162 /* PropertySignature */ + var message = nextDeclaration.kind === 164 /* PropertyDeclaration */ || nextDeclaration.kind === 163 /* PropertySignature */ ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; var declName = ts.declarationNameToString(nextDeclarationName); @@ -75094,8 +77353,8 @@ var ts; } } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 160 /* Parameter */ && right.kind === 249 /* VariableDeclaration */) || - (left.kind === 249 /* VariableDeclaration */ && right.kind === 160 /* Parameter */)) { + if ((left.kind === 161 /* Parameter */ && right.kind === 250 /* VariableDeclaration */) || + (left.kind === 250 /* VariableDeclaration */ && right.kind === 161 /* Parameter */)) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -75111,10 +77370,10 @@ var ts; return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { - ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); checkGrammarVariableDeclaration(node); checkVariableLikeDeclaration(node); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkBindingElement(node) { checkGrammarBindingElement(node); @@ -75135,49 +77394,55 @@ var ts; // Grammar checking checkGrammarStatementInAmbientContext(node); var type = checkTruthinessExpression(node.expression); - checkTestingKnownTruthyCallableType(node.expression, type, node.thenStatement); + checkTestingKnownTruthyCallableOrAwaitableType(node.expression, type, node.thenStatement); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 231 /* EmptyStatement */) { + if (node.thenStatement.kind === 232 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); } - function checkTestingKnownTruthyCallableType(condExpr, type, body) { - if (!strictNullChecks) { + function checkTestingKnownTruthyCallableOrAwaitableType(condExpr, type, body) { + if (!strictNullChecks) + return; + if (getFalsyFlags(type)) return; - } var location = ts.isBinaryExpression(condExpr) ? condExpr.right : condExpr; var testedNode = ts.isIdentifier(location) ? location : ts.isPropertyAccessExpression(location) ? location.name : ts.isBinaryExpression(location) && ts.isIdentifier(location.right) ? location.right : undefined; - if (!testedNode) { - return; - } - var possiblyFalsy = getFalsyFlags(type); - if (possiblyFalsy) { + var isPropertyExpressionCast = ts.isPropertyAccessExpression(location) + && ts.isAssertionExpression(ts.skipParentheses(location.expression)); + if (!testedNode || isPropertyExpressionCast) { return; } // While it technically should be invalid for any known-truthy value - // to be tested, we de-scope to functions unrefenced in the block as a - // heuristic to identify the most common bugs. There are too many - // false positives for values sourced from type definitions without - // strictNullChecks otherwise. + // to be tested, we de-scope to functions and Promises unreferenced in + // the block as a heuristic to identify the most common bugs. There + // are too many false positives for values sourced from type + // definitions without strictNullChecks otherwise. var callSignatures = getSignaturesOfType(type, 0 /* Call */); - if (callSignatures.length === 0) { + var isPromise = !!getAwaitedTypeOfPromise(type); + if (callSignatures.length === 0 && !isPromise) { return; } var testedSymbol = getSymbolAtLocation(testedNode); if (!testedSymbol) { return; } - var isUsed = ts.isBinaryExpression(condExpr.parent) && isFunctionUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) - || body && isFunctionUsedInConditionBody(condExpr, body, testedNode, testedSymbol); + var isUsed = ts.isBinaryExpression(condExpr.parent) && isSymbolUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) + || body && isSymbolUsedInConditionBody(condExpr, body, testedNode, testedSymbol); if (!isUsed) { - error(location, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead); + if (isPromise) { + errorAndMaybeSuggestAwait(location, + /*maybeMissingAwait*/ true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, getTypeNameForErrorDisplay(type)); + } + else { + error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead); + } } } - function isFunctionUsedInConditionBody(expr, body, testedNode, testedSymbol) { + function isSymbolUsedInConditionBody(expr, body, testedNode, testedSymbol) { return !!ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); @@ -75214,7 +77479,7 @@ var ts; return ts.forEachChild(childNode, check); }); } - function isFunctionUsedInBinaryExpressionChain(node, testedSymbol) { + function isSymbolUsedInBinaryExpressionChain(node, testedSymbol) { while (ts.isBinaryExpression(node) && node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { var isUsed = ts.forEachChild(node.right, function visit(child) { if (ts.isIdentifier(child)) { @@ -75256,12 +77521,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 251 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer.kind === 251 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -75295,14 +77560,14 @@ var ts; // via checkRightHandSideOfForOf. // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. // Then check that the RHS is assignable to it. - if (node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer.kind === 251 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node); // There may be a destructuring assignment on the left side - if (varExpr.kind === 199 /* ArrayLiteralExpression */ || varExpr.kind === 200 /* ObjectLiteralExpression */) { + if (varExpr.kind === 200 /* ArrayLiteralExpression */ || varExpr.kind === 201 /* ObjectLiteralExpression */) { // iteratedType may be undefined. In this case, we still want to check the structure of // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like // to short circuit the type relation checking as much as possible, so we pass the unknownType. @@ -75334,7 +77599,7 @@ var ts; // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer.kind === 251 /* VariableDeclarationList */) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -75348,7 +77613,7 @@ var ts; // and Expr must be an expression of type Any, an object type, or a type parameter type. var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 199 /* ArrayLiteralExpression */ || varExpr.kind === 200 /* ObjectLiteralExpression */) { + if (varExpr.kind === 200 /* ArrayLiteralExpression */ || varExpr.kind === 201 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -75464,18 +77729,8 @@ var ts; // want to say that number is not an array type. But if the input was just // number and string input is allowed, we want to say that number is not an // array type or a string type. - var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined); - var _a = !(use & 4 /* AllowsStringInputFlag */) || hasStringConstituent - ? downlevelIteration - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] - : yieldType - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false] - : [ts.Diagnostics.Type_0_is_not_an_array_type, true] - : downlevelIteration - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] - : yieldType - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false] - : [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true], defaultDiagnostic = _a[0], maybeMissingAwait = _a[1]; + var allowsStrings = !!(use & 4 /* AllowsStringInputFlag */) && !hasStringConstituent; + var _a = getIterationDiagnosticDetails(allowsStrings, downlevelIteration), defaultDiagnostic = _a[0], maybeMissingAwait = _a[1]; errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType)); } return hasStringConstituent ? possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType : undefined; @@ -75489,6 +77744,40 @@ var ts; return getUnionType(possibleOutOfBounds ? [arrayElementType, stringType, undefinedType] : [arrayElementType, stringType], 2 /* Subtype */); } return (use & 128 /* PossiblyOutOfBounds */) ? includeUndefinedInIndexSignature(arrayElementType) : arrayElementType; + function getIterationDiagnosticDetails(allowsStrings, downlevelIteration) { + var _a; + if (downlevelIteration) { + return allowsStrings + ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] + : [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]; + } + var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined); + if (yieldType) { + return [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]; + } + if (isES2015OrLaterIterable((_a = inputType.symbol) === null || _a === void 0 ? void 0 : _a.escapedName)) { + return [ts.Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, true]; + } + return allowsStrings + ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true] + : [ts.Diagnostics.Type_0_is_not_an_array_type, true]; + } + } + function isES2015OrLaterIterable(n) { + switch (n) { + case "Float32Array": + case "Float64Array": + case "Int16Array": + case "Int32Array": + case "Int8Array": + case "NodeList": + case "Uint16Array": + case "Uint32Array": + case "Uint8Array": + case "Uint8ClampedArray": + return true; + } + return false; } /** * Gets the requested "iteration type" from an `Iterable`-like or `AsyncIterable`-like type. @@ -75732,6 +78021,11 @@ var ts; return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType)); } } + function getPropertyNameForKnownSymbolName(symbolName) { + var ctorType = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false); + var uniqueType = ctorType && getTypeOfPropertyOfType(getTypeOfSymbol(ctorType), ts.escapeLeadingUnderscores(symbolName)); + return uniqueType && isTypeUsableAsPropertyName(uniqueType) ? getPropertyNameFromType(uniqueType) : "__@" + symbolName; + } /** * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like * type from its members. @@ -75744,7 +78038,7 @@ var ts; */ function getIterationTypesOfIterableSlow(type, resolver, errorNode) { var _a; - var method = getPropertyOfType(type, ts.getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); + var method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); var methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : undefined; if (isTypeAny(methodType)) { return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); @@ -76043,12 +78337,12 @@ var ts; var functionFlags = ts.getFunctionFlags(func); if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - if (func.kind === 168 /* SetAccessor */) { + if (func.kind === 169 /* SetAccessor */) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 166 /* Constructor */) { + else if (func.kind === 167 /* Constructor */) { if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -76066,7 +78360,7 @@ var ts; } } } - else if (func.kind !== 166 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + else if (func.kind !== 167 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { // The function has a return type, but the return statement doesn't have an expression. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -76095,7 +78389,7 @@ var ts; var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 285 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 286 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -76104,7 +78398,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 284 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 285 /* CaseClause */) { // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable // to or from the type of the 'switch' expression. @@ -76136,7 +78430,7 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 245 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + if (current.kind === 246 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } @@ -76166,10 +78460,11 @@ var ts; // Grammar checking if (catchClause.variableDeclaration) { var declaration = catchClause.variableDeclaration; - if (declaration.type) { + var typeNode = ts.getEffectiveTypeAnnotationNode(ts.getRootDeclaration(declaration)); + if (typeNode) { var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ false); if (type && !(type.flags & 3 /* AnyOrUnknown */)) { - grammarErrorOnFirstToken(declaration.type, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified); + grammarErrorOnFirstToken(typeNode, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified); } } else if (declaration.initializer) { @@ -76180,7 +78475,7 @@ var ts; if (blockLocals_1) { ts.forEachKey(catchClause.locals, function (caughtName) { var blockLocal = blockLocals_1.get(caughtName); - if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { + if ((blockLocal === null || blockLocal === void 0 ? void 0 : blockLocal.valueDeclaration) && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); } }); @@ -76193,25 +78488,28 @@ var ts; checkBlock(node.finallyBlock); } } - function checkIndexConstraints(type) { - var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); - var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); + function checkIndexConstraints(type, isStatic) { + var _a, _b, _c, _d; + var declaredNumberIndexer = getIndexDeclarationOfSymbolTable(isStatic ? (_a = type.symbol) === null || _a === void 0 ? void 0 : _a.exports : (_b = type.symbol) === null || _b === void 0 ? void 0 : _b.members, 1 /* Number */); + var declaredStringIndexer = getIndexDeclarationOfSymbolTable(isStatic ? (_c = type.symbol) === null || _c === void 0 ? void 0 : _c.exports : (_d = type.symbol) === null || _d === void 0 ? void 0 : _d.members, 0 /* String */); var stringIndexType = getIndexTypeOfType(type, 0 /* String */); var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); if (stringIndexType || numberIndexType) { ts.forEach(getPropertiesOfObjectType(type), function (prop) { + if (isStatic && prop.flags & 4194304 /* Prototype */) + return; var propType = getTypeOfSymbol(prop); checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); var classDeclaration = type.symbol.valueDeclaration; - if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) { - for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { - var member = _a[_i]; + if (ts.getObjectFlags(type) & 1 /* Class */ && classDeclaration && ts.isClassLike(classDeclaration)) { + for (var _i = 0, _e = classDeclaration.members; _i < _e.length; _i++) { + var member = _e[_i]; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!ts.hasSyntacticModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) { + if (!ts.hasSyntacticModifier(member, 32 /* Static */) && !hasBindableName(member)) { var symbol = getSymbolOfNode(member); var propType = getTypeOfSymbol(symbol); checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); @@ -76226,7 +78524,7 @@ var ts; // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); - errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + errorNode = someBaseTypeHasBothIndexers || !type.symbol.declarations ? undefined : type.symbol.declarations[0]; } } if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217 @@ -76250,8 +78548,8 @@ var ts; // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; if (propDeclaration && name && - (propDeclaration.kind === 216 /* BinaryExpression */ || - name.kind === 158 /* ComputedPropertyName */ || + (propDeclaration.kind === 217 /* BinaryExpression */ || + name.kind === 159 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } @@ -76263,7 +78561,7 @@ var ts; // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); - errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + errorNode = someBaseClassHasBothPropertyAndIndexer || !containingType.symbol.declarations ? undefined : containingType.symbol.declarations[0]; } if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { var errorMessage = indexKind === 0 /* String */ @@ -76279,6 +78577,7 @@ var ts; switch (name.escapedText) { case "any": case "unknown": + case "never": case "number": case "bigint": case "boolean": @@ -76328,7 +78627,7 @@ var ts; function checkTypeParametersNotReferenced(root, typeParameters, index) { visit(root); function visit(node) { - if (node.kind === 173 /* TypeReference */) { + if (node.kind === 174 /* TypeReference */) { var type = getTypeFromTypeReference(node); if (type.flags & 262144 /* TypeParameter */) { for (var i = index; i < typeParameters.length; i++) { @@ -76343,14 +78642,14 @@ var ts; } /** Check that type parameter lists are identical across multiple declarations */ function checkTypeParameterListsIdentical(symbol) { - if (symbol.declarations.length === 1) { + if (symbol.declarations && symbol.declarations.length === 1) { return; } var links = getSymbolLinks(symbol); if (!links.typeParametersChecked) { links.typeParametersChecked = true; var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); - if (declarations.length <= 1) { + if (!declarations || declarations.length <= 1) { return; } var type = getDeclaredTypeOfSymbol(symbol); @@ -76414,6 +78713,9 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { + if (ts.some(node.decorators) && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { + grammarErrorOnNode(node.decorators[0], ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); + } if (!node.name && !ts.hasSyntacticModifier(node, 512 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } @@ -76442,7 +78744,8 @@ var ts; checkFunctionOrConstructorSymbol(symbol); checkClassForDuplicateDeclarations(node); // Only check for reserved static identifiers on non-ambient context. - if (!(node.flags & 8388608 /* Ambient */)) { + var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + if (!nodeInAmbientContext) { checkClassForStaticPropertyNameConflicts(node); } var baseTypeNode = ts.getEffectiveBaseTypeNode(node); @@ -76502,6 +78805,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } + checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { @@ -76531,14 +78835,76 @@ var ts; } if (produceDiagnostics) { checkIndexConstraints(type); + checkIndexConstraints(staticType, /*isStatic*/ true); checkTypeForDuplicateIndexSignatures(node); checkPropertyInitialization(node); } } + function checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType) { + var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); + var baseTypes = baseTypeNode && getBaseTypes(type); + var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; + var baseStaticType = getBaseConstructorTypeOfClass(type); + var _loop_24 = function (member) { + if (ts.hasAmbientModifier(member)) { + return "continue"; + } + if (ts.isConstructorDeclaration(member)) { + ts.forEach(member.parameters, function (param) { + if (ts.isParameterPropertyDeclaration(param, member)) { + checkClassMember(param, /*memberIsParameterProperty*/ true); + } + }); + } + checkClassMember(member); + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_24(member); + } + function checkClassMember(member, memberIsParameterProperty) { + var hasOverride = ts.hasOverrideModifier(member); + var hasStatic = ts.hasStaticModifier(member); + if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (!declaredProp) { + return; + } + var thisType = hasStatic ? staticType : typeWithThis; + var baseType = hasStatic ? baseStaticType : baseWithThis; + var prop = getPropertyOfType(thisType, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseType, declaredProp.escapedName); + var baseClassName = typeToString(baseWithThis); + if (prop && !baseProp && hasOverride) { + error(member, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); + } + else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.valueDeclaration) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { + var baseHasAbstract = ts.hasAbstractModifier(baseProp.valueDeclaration); + if (hasOverride) { + return; + } + if (!baseHasAbstract) { + var diag = memberIsParameterProperty ? + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : + ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; + error(member, diag, baseClassName); + } + else if (ts.hasAbstractModifier(member) && baseHasAbstract) { + error(member, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); + } + } + } + else if (hasOverride) { + var className = typeToString(type); + error(member, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, className); + } + } + } 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_23 = function (member) { + var _loop_25 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -76557,7 +78923,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_23(member); + _loop_25(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -76583,7 +78949,7 @@ var ts; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 252 /* ClassDeclaration */ || d.kind === 253 /* InterfaceDeclaration */; + return d.kind === 253 /* ClassDeclaration */ || d.kind === 254 /* InterfaceDeclaration */; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -76600,6 +78966,7 @@ var ts; // but not by other kinds of members. // Base class instance member variables and accessors can be overridden by // derived class instance member variables and accessors, but not by other kinds of members. + var _a, _b; // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfType(baseType); basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { @@ -76628,8 +78995,8 @@ var ts; // Searches other base types for a declaration that would satisfy the inherited abstract member. // (The class may have more than one base type via declaration merging with an interface with the // same name.) - for (var _a = 0, _b = getBaseTypes(type); _a < _b.length; _a++) { - var otherBaseType = _b[_a]; + for (var _c = 0, _d = getBaseTypes(type); _c < _d.length; _c++) { + var otherBaseType = _d[_c]; if (otherBaseType === baseType) continue; var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName); @@ -76638,7 +79005,7 @@ var ts; continue basePropertyCheck; } } - if (derivedClassDecl.kind === 221 /* ClassExpression */) { + if (derivedClassDecl.kind === 222 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -76659,7 +79026,7 @@ var ts; if (basePropertyFlags && derivedPropertyFlags) { // property/accessor is overridden with property/accessor if (baseDeclarationFlags & 128 /* Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer) - || base.valueDeclaration && base.valueDeclaration.parent.kind === 253 /* InterfaceDeclaration */ + || base.valueDeclaration && base.valueDeclaration.parent.kind === 254 /* InterfaceDeclaration */ || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) { // when the base property is abstract or from an interface, base/derived flags don't need to match // same when the derived property is from an assignment @@ -76673,13 +79040,13 @@ var ts; ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } - else if (compilerOptions.useDefineForClassFields) { - var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 163 /* PropertyDeclaration */ && !d.initializer; }); + else if (useDefineForClassFields) { + var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 164 /* PropertyDeclaration */ && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432 /* Transient */) && !(baseDeclarationFlags & 128 /* Abstract */) && !(derivedDeclarationFlags & 128 /* Abstract */) - && !derived.declarations.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); })) { + && !((_b = derived.declarations) === null || _b === void 0 ? void 0 : _b.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); }))) { var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol)); var propName = uninitialized.name; if (uninitialized.exclamationToken @@ -76790,7 +79157,7 @@ var ts; } } function isInstancePropertyWithoutInitializer(node) { - return node.kind === 163 /* PropertyDeclaration */ && + return node.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(node, 32 /* Static */ | 128 /* Abstract */) && !node.exclamationToken && !node.initializer; @@ -76814,7 +79181,7 @@ var ts; var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 253 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 254 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -76933,7 +79300,7 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: var value_2 = evaluate(expr.operand); if (typeof value_2 === "number") { switch (expr.operator) { @@ -76943,7 +79310,7 @@ var ts; } } break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { @@ -76972,7 +79339,7 @@ var ts; case 8 /* NumericLiteral */: checkGrammarNumericLiteral(expr); return +expr.text; - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return evaluate(expr.expression); case 78 /* Identifier */: var identifier = expr; @@ -76980,14 +79347,14 @@ var ts; return +(identifier.escapedText); } return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); - case 202 /* ElementAccessExpression */: - case 201 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384 /* Enum */) { var name = void 0; - if (ex.kind === 201 /* PropertyAccessExpression */) { + if (ex.kind === 202 /* PropertyAccessExpression */) { name = ex.name.escapedText; } else { @@ -77005,7 +79372,7 @@ var ts; if (memberSymbol) { var declaration = memberSymbol.valueDeclaration; if (declaration !== member) { - if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + if (declaration && isBlockScopedNameDeclaredBeforeUse(declaration, member)) { return getEnumMemberValue(declaration); } error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); @@ -77020,8 +79387,8 @@ var ts; } function isConstantMemberAccess(node) { return node.kind === 78 /* Identifier */ || - node.kind === 201 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || - node.kind === 202 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.kind === 202 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 203 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && ts.isStringLiteralLike(node.argumentExpression); } function checkEnumDeclaration(node) { @@ -77045,7 +79412,7 @@ var ts; var enumSymbol = getSymbolOfNode(node); var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); if (node === firstDeclaration) { - if (enumSymbol.declarations.length > 1) { + if (enumSymbol.declarations && enumSymbol.declarations.length > 1) { var enumIsConst_1 = ts.isEnumConst(node); // check that const is placed\omitted on all enum declarations ts.forEach(enumSymbol.declarations, function (decl) { @@ -77057,7 +79424,7 @@ var ts; var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 255 /* EnumDeclaration */) { + if (declaration.kind !== 256 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -77083,12 +79450,14 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; - if ((declaration.kind === 252 /* ClassDeclaration */ || - (declaration.kind === 251 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && - !(declaration.flags & 8388608 /* Ambient */)) { - return declaration; + if (declarations) { + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 253 /* ClassDeclaration */ || + (declaration.kind === 252 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 8388608 /* Ambient */)) { + return declaration; + } } } return undefined; @@ -77136,8 +79505,9 @@ var ts; // The following checks only apply on a non-ambient instantiated module declaration. if (symbol.flags & 512 /* ValueModule */ && !inAmbientContext + && symbol.declarations && symbol.declarations.length > 1 - && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions))) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -77149,7 +79519,7 @@ var ts; } // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. - var mergedClass = ts.getDeclarationOfKind(symbol, 252 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 253 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -77198,40 +79568,41 @@ var ts; } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { + var _a; switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // error each individual name in variable statement instead of marking the entire variable statement - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; + for (var _i = 0, _b = node.declarationList.declarations; _i < _b.length; _i++) { + var decl = _b[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 266 /* ExportAssignment */: - case 267 /* ExportDeclaration */: + case 267 /* ExportAssignment */: + case 268 /* ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 260 /* ImportEqualsDeclaration */: - case 261 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 198 /* BindingElement */: - case 249 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 250 /* VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { - for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { - var el = _c[_b]; + for (var _c = 0, _d = name.elements; _c < _d.length; _c++) { + var el = _d[_c]; // mark individual names in binding pattern checkModuleAugmentationElement(el, isGlobalAugmentation); } break; } // falls through - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 251 /* FunctionDeclaration */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 252 /* FunctionDeclaration */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } @@ -77244,7 +79615,7 @@ var ts; var reportError = !(symbol.flags & 33554432 /* Transient */); if (!reportError) { // symbol should not originate in augmentation - reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + reportError = !!((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.declarations) && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); } } break; @@ -77254,12 +79625,12 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: do { node = node.left; } while (node.kind !== 78 /* Identifier */); return node; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: do { if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) { return node.name; @@ -77279,9 +79650,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 257 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 297 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 267 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 258 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 298 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 268 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -77301,6 +79672,7 @@ var ts; return true; } function checkAliasSymbol(node) { + var _a; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { @@ -77315,21 +79687,21 @@ var ts; (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 270 /* ExportSpecifier */ ? + var message = node.kind === 271 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules - && node.kind === 270 /* ExportSpecifier */ + && node.kind === 271 /* ExportSpecifier */ && !node.parent.parent.isTypeOnly && !(target.flags & 111551 /* Value */) && !(node.flags & 8388608 /* Ambient */)) { error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type); } - if (ts.isImportSpecifier(node) && ts.every(target.declarations, function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, node.name, ts.Diagnostics._0_is_deprecated, symbol.escapedName); + if (ts.isImportSpecifier(node) && ((_a = target.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); }))) { + addDeprecatedSuggestion(node.name, target.declarations, symbol.escapedName); } } } @@ -77337,7 +79709,7 @@ var ts; checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkAliasSymbol(node); - if (node.kind === 265 /* ImportSpecifier */ && + if (node.kind === 266 /* ImportSpecifier */ && ts.idText(node.propertyName || node.name) === "default" && compilerOptions.esModuleInterop && moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) { @@ -77359,7 +79731,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 263 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 264 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015 && compilerOptions.esModuleInterop) { // import * as ns from "foo"; @@ -77387,7 +79759,7 @@ var ts; if (ts.hasSyntacticModifier(node, 1 /* Export */)) { markExportAsReferenced(node); } - if (node.moduleReference.kind !== 272 /* ExternalModuleReference */) { + if (node.moduleReference.kind !== 273 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { if (target.flags & 111551 /* Value */) { @@ -77430,10 +79802,10 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 257 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 257 /* ModuleBlock */ && + var inAmbientExternalModule = node.parent.kind === 258 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 258 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 8388608 /* Ambient */; - if (node.parent.kind !== 297 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + if (node.parent.kind !== 298 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -77466,14 +79838,14 @@ var ts; } function checkGrammarExportDeclaration(node) { var _a; - var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 268 /* NamedExports */; + var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 269 /* NamedExports */; if (isTypeOnlyExportStar) { grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type); } return !isTypeOnlyExportStar; } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 297 /* SourceFile */ || node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 256 /* ModuleDeclaration */; + var isInAppropriateContext = node.parent.kind === 298 /* SourceFile */ || node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 257 /* ModuleDeclaration */; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -77523,7 +79895,7 @@ var ts; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { @@ -77544,12 +79916,15 @@ var ts; } } function checkExportAssignment(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + var illegalContextMessage = node.isExportEquals + ? ts.Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration + : ts.Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration; + if (checkGrammarModuleElementContext(node, illegalContextMessage)) { // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 297 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 256 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 298 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 257 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -77609,7 +79984,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { + if (declaration && !isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -77633,10 +80008,12 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + if (!isDuplicatedCommonJSExport(declarations)) { + for (var _i = 0, _b = declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } } } } @@ -77645,6 +80022,11 @@ var ts; links.exportsChecked = true; } } + function isDuplicatedCommonJSExport(declarations) { + return declarations + && declarations.length > 1 + && declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && (ts.isExportsIdentifier(d.expression) || ts.isModuleExportsAccessExpression(d.expression)); }); + } function checkSourceElement(node) { if (node) { var saveCurrentNode = currentNode; @@ -77666,171 +80048,171 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 251 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } - if (kind >= 232 /* FirstStatement */ && kind <= 248 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) { + if (kind >= 233 /* FirstStatement */ && kind <= 249 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) { errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected); } switch (kind) { - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return checkTypeParameter(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return checkParameter(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return checkPropertyDeclaration(node); - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: return checkPropertySignature(node); - case 175 /* ConstructorType */: - case 174 /* FunctionType */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 176 /* ConstructorType */: + case 175 /* FunctionType */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return checkSignatureDeclaration(node); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: return checkMethodDeclaration(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return checkConstructorDeclaration(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return checkAccessorDeclaration(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return checkTypeReferenceNode(node); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return checkTypePredicate(node); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return checkTypeQuery(node); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return checkTypeLiteral(node); - case 178 /* ArrayType */: + case 179 /* ArrayType */: return checkArrayType(node); - case 179 /* TupleType */: + case 180 /* TupleType */: return checkTupleType(node); - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 186 /* ParenthesizedType */: - case 180 /* OptionalType */: - case 181 /* RestType */: + case 187 /* ParenthesizedType */: + case 181 /* OptionalType */: + case 182 /* RestType */: return checkSourceElement(node.type); - case 187 /* ThisType */: + case 188 /* ThisType */: return checkThisType(node); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return checkTypeOperator(node); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return checkConditionalType(node); - case 185 /* InferType */: + case 186 /* InferType */: return checkInferType(node); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: return checkTemplateLiteralType(node); - case 195 /* ImportType */: + case 196 /* ImportType */: return checkImportType(node); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return checkNamedTupleMember(node); - case 315 /* JSDocAugmentsTag */: + case 318 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 316 /* JSDocImplementsTag */: + case 319 /* JSDocImplementsTag */: return checkJSDocImplementsTag(node); - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return checkJSDocTypeAliasTag(node); - case 330 /* JSDocTemplateTag */: + case 334 /* JSDocTemplateTag */: return checkJSDocTemplateTag(node); - case 329 /* JSDocTypeTag */: + case 333 /* JSDocTypeTag */: return checkJSDocTypeTag(node); - case 326 /* JSDocParameterTag */: + case 330 /* JSDocParameterTag */: return checkJSDocParameterTag(node); - case 333 /* JSDocPropertyTag */: + case 337 /* JSDocPropertyTag */: return checkJSDocPropertyTag(node); - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: checkJSDocFunctionType(node); // falls through - case 306 /* JSDocNonNullableType */: - case 305 /* JSDocNullableType */: - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: - case 312 /* JSDocTypeLiteral */: + case 307 /* JSDocNonNullableType */: + case 306 /* JSDocNullableType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: + case 314 /* JSDocTypeLiteral */: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 309 /* JSDocVariadicType */: + case 310 /* JSDocVariadicType */: checkJSDocVariadicType(node); return; - case 301 /* JSDocTypeExpression */: + case 302 /* JSDocTypeExpression */: return checkSourceElement(node.type); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return checkIndexedAccessType(node); - case 190 /* MappedType */: + case 191 /* MappedType */: return checkMappedType(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 230 /* Block */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 258 /* ModuleBlock */: return checkBlock(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return checkVariableStatement(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return checkExpressionStatement(node); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return checkIfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return checkDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return checkWhileStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return checkForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return checkForInStatement(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return checkForOfStatement(node); - case 240 /* ContinueStatement */: - case 241 /* BreakStatement */: + case 241 /* ContinueStatement */: + case 242 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return checkReturnStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return checkWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return checkSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return checkLabeledStatement(node); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return checkThrowStatement(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return checkTryStatement(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return checkBindingElement(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return checkClassDeclaration(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return checkImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return checkExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return checkExportAssignment(node); - case 231 /* EmptyStatement */: - case 248 /* DebuggerStatement */: + case 232 /* EmptyStatement */: + case 249 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 271 /* MissingDeclaration */: + case 272 /* MissingDeclaration */: return checkMissingDeclaration(node); } } @@ -77875,7 +80257,8 @@ var ts; if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. var host_1 = ts.getHostSignatureFromJSDoc(paramTag); - if (host_1) { + var isCallbackTag = ts.isJSDocCallbackTag(paramTag.parent.parent); + if (host_1 || isCallbackTag) { /* Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. So in the following situation we will not create an array type: @@ -77883,7 +80266,9 @@ var ts; function f(a) {} Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. */ - var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var lastParamDeclaration = isCallbackTag + ? ts.lastOrUndefined(paramTag.parent.parent.typeExpression.parameters) + : ts.lastOrUndefined(host_1.parameters); var symbol = ts.getParameterSymbolFromJSDoc(paramTag); if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { @@ -77921,51 +80306,51 @@ var ts; } } function checkDeferredNode(node) { - ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; switch (node.kind) { - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 205 /* TaggedTemplateExpression */: - case 161 /* Decorator */: - case 275 /* JsxOpeningElement */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 206 /* TaggedTemplateExpression */: + case 162 /* Decorator */: + case 276 /* JsxOpeningElement */: // These node kinds are deferred checked when overload resolution fails // To save on work, we ensure the arguments are checked just once, in // a deferred way resolveUntypedCall(node); break; - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: checkAccessorDeclaration(node); break; - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: checkClassExpressionDeferred(node); break; - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: checkJsxSelfClosingElementDeferred(node); break; - case 273 /* JsxElement */: + case 274 /* JsxElement */: checkJsxElementDeferred(node); break; } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkSourceFile(node) { - ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeCheck"); checkSourceFileWorker(node); ts.performance.mark("afterCheck"); ts.performance.measure("Check", "beforeCheck", "afterCheck"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function unusedIsError(kind, isAmbient) { if (isAmbient) { @@ -77994,7 +80379,7 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - ts.clear(potentialWeakMapCollisions); + ts.clear(potentialWeakMapSetCollisions); ts.forEach(node.statements, checkSourceElement); checkSourceElement(node.endOfFileToken); checkDeferredNodes(node); @@ -78024,9 +80409,9 @@ var ts; ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); ts.clear(potentialNewTargetCollisions); } - if (potentialWeakMapCollisions.length) { - ts.forEach(potentialWeakMapCollisions, checkWeakMapCollision); - ts.clear(potentialWeakMapCollisions); + if (potentialWeakMapSetCollisions.length) { + ts.forEach(potentialWeakMapSetCollisions, checkWeakMapSetCollision); + ts.clear(potentialWeakMapSetCollisions); } links.flags |= 1 /* TypeChecked */; } @@ -78098,17 +80483,17 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 297 /* SourceFile */: - if (!ts.isExternalOrCommonJsModule(location)) + case 298 /* SourceFile */: + if (!ts.isExternalModule(location)) break; // falls through - case 256 /* ModuleDeclaration */: - copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); + case 257 /* ModuleDeclaration */: + copyLocallyVisibleExportSymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); @@ -78116,8 +80501,8 @@ var ts; // this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration. // falls through - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: // If we didn't come from static member of class or interface, // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. @@ -78126,7 +80511,7 @@ var ts; copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968 /* Type */); } break; - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -78166,6 +80551,16 @@ var ts; }); } } + function copyLocallyVisibleExportSymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + // Similar condition as in `resolveNameHelper` + if (!ts.getDeclarationOfKind(symbol, 271 /* ExportSpecifier */) && !ts.getDeclarationOfKind(symbol, 270 /* NamespaceExport */)) { + copySymbol(symbol, meaning); + } + }); + } + } } function isTypeDeclarationName(name) { return name.kind === 78 /* Identifier */ && @@ -78174,19 +80569,19 @@ var ts; } function isTypeDeclaration(node) { switch (node.kind) { - case 159 /* TypeParameter */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 160 /* TypeParameter */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return true; - case 262 /* ImportClause */: + case 263 /* ImportClause */: return node.isTypeOnly; - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return node.parent.parent.isTypeOnly; default: return false; @@ -78194,25 +80589,25 @@ var ts; } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(node) { - while (node.parent.kind === 157 /* QualifiedName */) { + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 173 /* TypeReference */; + return node.parent.kind === 174 /* TypeReference */; } function isHeritageClauseElementIdentifier(node) { - while (node.parent.kind === 201 /* PropertyAccessExpression */) { + while (node.parent.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 223 /* ExpressionWithTypeArguments */; + return node.parent.kind === 224 /* ExpressionWithTypeArguments */; } - function isJSDocEntryNameReference(node) { - while (node.parent.kind === 157 /* QualifiedName */) { + function getJSDocEntryNameReference(node) { + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } - while (node.parent.kind === 201 /* PropertyAccessExpression */) { + while (node.parent.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 302 /* JSDocNameReference */; + return ts.isJSDocNameReference(node.parent) ? node.parent : undefined; } function forEachEnclosingClass(node, callback) { var result; @@ -78240,13 +80635,13 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 157 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 158 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 260 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 261 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } - if (nodeOnRightSide.parent.kind === 266 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 267 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; @@ -78272,7 +80667,7 @@ var ts; node = parent; parent = parent.parent; } - if (parent && parent.kind === 195 /* ImportType */ && parent.qualifier === node) { + if (parent && parent.kind === 196 /* ImportType */ && parent.qualifier === node) { return parent; } return undefined; @@ -78282,7 +80677,7 @@ var ts; return getSymbolOfNode(name.parent); } if (ts.isInJSFile(name) && - name.parent.kind === 201 /* PropertyAccessExpression */ && + name.parent.kind === 202 /* PropertyAccessExpression */ && name.parent === name.parent.parent.left) { // Check if this is a special property assignment if (!ts.isPrivateIdentifier(name)) { @@ -78292,7 +80687,7 @@ var ts; } } } - if (name.parent.kind === 266 /* ExportAssignment */ && ts.isEntityNameExpression(name)) { + if (name.parent.kind === 267 /* ExportAssignment */ && ts.isEntityNameExpression(name)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(name, /*all meanings*/ 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); @@ -78302,7 +80697,7 @@ var ts; } else if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name) && isInRightSideOfImportOrExportAssignment(name)) { // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(name, 260 /* ImportEqualsDeclaration */); + var importEqualsDeclaration = ts.getAncestor(name, 261 /* ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true); } @@ -78320,7 +80715,7 @@ var ts; if (isHeritageClauseElementIdentifier(name)) { var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. - if (name.parent.kind === 223 /* ExpressionWithTypeArguments */) { + if (name.parent.kind === 224 /* ExpressionWithTypeArguments */) { meaning = 788968 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) { @@ -78336,10 +80731,10 @@ var ts; return entityNameSymbol; } } - if (name.parent.kind === 326 /* JSDocParameterTag */) { + if (name.parent.kind === 330 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(name.parent); } - if (name.parent.kind === 159 /* TypeParameter */ && name.parent.parent.kind === 330 /* JSDocTemplateTag */) { + if (name.parent.kind === 160 /* TypeParameter */ && name.parent.parent.kind === 334 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(name.parent); return typeParameter && typeParameter.symbol; @@ -78356,36 +80751,56 @@ var ts; } return resolveEntityName(name, 111551 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (name.kind === 201 /* PropertyAccessExpression */ || name.kind === 157 /* QualifiedName */) { + else if (name.kind === 202 /* PropertyAccessExpression */ || name.kind === 158 /* QualifiedName */) { var links = getNodeLinks(name); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (name.kind === 201 /* PropertyAccessExpression */) { - checkPropertyAccessExpression(name); + if (name.kind === 202 /* PropertyAccessExpression */) { + checkPropertyAccessExpression(name, 0 /* Normal */); } else { - checkQualifiedName(name); + checkQualifiedName(name, 0 /* Normal */); } return links.resolvedSymbol; } } else if (isTypeReferenceIdentifier(name)) { - var meaning = name.parent.kind === 173 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */; + var meaning = name.parent.kind === 174 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */; return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (isJSDocEntryNameReference(name)) { + var jsdocReference = getJSDocEntryNameReference(name); + if (jsdocReference || ts.isJSDocLink(name.parent)) { var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */; - return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); + var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ false, ts.getHostSignatureFromJSDoc(name)); + if (symbol) { + return symbol; + } + else if (ts.isQualifiedName(name) && ts.isIdentifier(name.left)) { + // resolve C.m as a static member first + var links = getNodeLinks(name); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + checkQualifiedName(name, 0 /* Normal */); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + // then resolve it as an instance member + var s = resolveEntityName(name.left, meaning, /*ignoreErrors*/ false); + if (s) { + var t = getDeclaredTypeOfSymbol(s); + return getPropertyOfType(t, name.right.escapedText); + } + } } - if (name.parent.kind === 172 /* TypePredicate */) { + if (name.parent.kind === 173 /* TypePredicate */) { return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */); } - // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node, ignoreErrors) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } var parent = node.parent; @@ -78408,8 +80823,8 @@ var ts; if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfNameOrPropertyAccessExpression(node); } - else if (parent.kind === 198 /* BindingElement */ && - grandParent.kind === 196 /* ObjectBindingPattern */ && + else if (parent.kind === 199 /* BindingElement */ && + grandParent.kind === 197 /* ObjectBindingPattern */ && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); @@ -78421,8 +80836,8 @@ var ts; switch (node.kind) { case 78 /* Identifier */: case 79 /* PrivateIdentifier */: - case 201 /* PropertyAccessExpression */: - case 157 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: return getSymbolOfNameOrPropertyAccessExpression(node); case 107 /* ThisKeyword */: var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); @@ -78436,14 +80851,14 @@ var ts; return checkExpression(node).symbol; } // falls through - case 187 /* ThisType */: + case 188 /* ThisType */: return getTypeFromThisTypeNode(node).symbol; case 105 /* SuperKeyword */: return checkExpression(node).symbol; case 132 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 166 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 167 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; @@ -78454,7 +80869,7 @@ var ts; // 3). Dynamic import call or require in javascript // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 261 /* ImportDeclaration */ || node.parent.kind === 267 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((node.parent.kind === 262 /* ImportDeclaration */ || node.parent.kind === 268 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || ((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, ignoreErrors); @@ -78476,7 +80891,7 @@ var ts; case 38 /* EqualsGreaterThanToken */: case 83 /* ClassKeyword */: return getSymbolOfNode(node.parent); - case 195 /* ImportType */: + case 196 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined; case 92 /* ExportKeyword */: return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined; @@ -78485,7 +80900,7 @@ var ts; } } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 289 /* ShorthandPropertyAssignment */) { + if (location && location.kind === 290 /* ShorthandPropertyAssignment */) { return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */); } return undefined; @@ -78564,27 +80979,27 @@ var ts; // [ a ] from // [a] = [ some array ...] function getTypeOfAssignmentPattern(expr) { - ts.Debug.assert(expr.kind === 200 /* ObjectLiteralExpression */ || expr.kind === 199 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.kind === 201 /* ObjectLiteralExpression */ || expr.kind === 200 /* ArrayLiteralExpression */); // If this is from "for of" // for ( { a } of elems) { // } - if (expr.parent.kind === 239 /* ForOfStatement */) { + if (expr.parent.kind === 240 /* ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 216 /* BinaryExpression */) { + if (expr.parent.kind === 217 /* BinaryExpression */) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 288 /* PropertyAssignment */) { - var node_2 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); - var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_2) || errorType; - var propertyIndex = ts.indexOfNode(node_2.properties, expr.parent); - return checkObjectLiteralDestructuringPropertyAssignment(node_2, typeOfParentObjectLiteral, propertyIndex); + if (expr.parent.kind === 289 /* PropertyAssignment */) { + var node_3 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); + var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_3) || errorType; + var propertyIndex = ts.indexOfNode(node_3.properties, expr.parent); + return checkObjectLiteralDestructuringPropertyAssignment(node_3, typeOfParentObjectLiteral, propertyIndex); } // Array literal assignment - array destructuring pattern var node = ts.cast(expr.parent, ts.isArrayLiteralExpression); @@ -78628,7 +81043,7 @@ var ts; case 8 /* NumericLiteral */: case 10 /* StringLiteral */: return getLiteralType(name.text); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(name); return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType; default: @@ -78725,6 +81140,7 @@ var ts; // When resolved as an expression identifier, if the given node references an exported entity, return the declaration // node of the exported entity's container. Otherwise, return undefined. function getReferencedExportContainer(nodeIn, prefixLocals) { + var _a; var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { // When resolving the export container for the name of a module or enum @@ -78745,7 +81161,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 297 /* SourceFile */) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && ((_a = parentSymbol_1.valueDeclaration) === null || _a === void 0 ? void 0 : _a.kind) === 298 /* SourceFile */) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -78775,11 +81191,12 @@ var ts; return undefined; } function isSymbolOfDestructuredElementOfCatchBinding(symbol) { - return ts.isBindingElement(symbol.valueDeclaration) - && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 287 /* CatchClause */; + return symbol.valueDeclaration + && ts.isBindingElement(symbol.valueDeclaration) + && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 288 /* CatchClause */; } function isSymbolOfDeclarationWithCollidingName(symbol) { - if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) { + if (symbol.flags & 418 /* BlockScoped */ && symbol.valueDeclaration && !ts.isSourceFile(symbol.valueDeclaration)) { var links = getSymbolLinks(symbol); if (links.isDeclarationWithCollidingName === undefined) { var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); @@ -78807,7 +81224,7 @@ var ts; // they will not collide with anything var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 230 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 231 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -78848,19 +81265,19 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: var symbol = getSymbolOfNode(node) || unknownSymbol; return isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: var exportClause = node.exportClause; return !!exportClause && (ts.isNamespaceExport(exportClause) || ts.some(exportClause.elements, isValueAliasDeclaration)); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return node.expression && node.expression.kind === 78 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; @@ -78869,7 +81286,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 297 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 298 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -78884,7 +81301,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 & 111551 /* Value */) && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; @@ -78892,13 +81309,14 @@ var ts; function isReferencedAliasDeclaration(node, checkChildren) { if (isAliasSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); - if (symbol && getSymbolLinks(symbol).referenced) { + var links = symbol && getSymbolLinks(symbol); + if (links === null || links === void 0 ? void 0 : links.referenced) { return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 if (target && ts.getEffectiveModifierFlags(node) & 1 /* Export */ && target.flags & 111551 /* Value */ && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -78935,13 +81353,13 @@ var ts; !isOptionalParameter(parameter) && !ts.isJSDocParameterTag(parameter) && !!parameter.initializer && - !ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + !ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && - ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameter(parameter) { return !!strictNullChecks && @@ -78976,15 +81394,15 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 291 /* EnumMember */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 292 /* EnumMember */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return true; } return false; } function getConstantValue(node) { - if (node.kind === 291 /* EnumMember */) { + if (node.kind === 292 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -79137,8 +81555,7 @@ var ts; } function isLiteralConstDeclaration(node) { if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 2944 /* Literal */) && isFreshLiteralType(type); + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } @@ -79257,12 +81674,12 @@ var ts; getJsxFragmentFactoryEntity: getJsxFragmentFactoryEntity, getAllAccessorDeclarations: function (accessor) { accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 - var otherKind = accessor.kind === 168 /* SetAccessor */ ? 167 /* GetAccessor */ : 168 /* SetAccessor */; + var otherKind = accessor.kind === 169 /* SetAccessor */ ? 168 /* GetAccessor */ : 169 /* SetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; - var setAccessor = accessor.kind === 168 /* SetAccessor */ ? accessor : otherAccessor; - var getAccessor = accessor.kind === 167 /* GetAccessor */ ? accessor : otherAccessor; + var setAccessor = accessor.kind === 169 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 168 /* GetAccessor */ ? accessor : otherAccessor; return { firstAccessor: firstAccessor, secondAccessor: secondAccessor, @@ -79278,7 +81695,7 @@ var ts; }, getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) { var n = ts.getParseTreeNode(node); - ts.Debug.assert(n && n.kind === 297 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile"); + ts.Debug.assert(n && n.kind === 298 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile"); var sym = getSymbolOfNode(node); if (!sym) { return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled); @@ -79301,11 +81718,13 @@ var ts; var s = _a[_i]; if (s.mergeId) { var merged = getMergedSymbol(s); - for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { - var d = _c[_b]; - var declFile = ts.getSourceFileOfNode(d); - if (declFile === importTarget) { - return true; + if (merged.declarations) { + for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declFile = ts.getSourceFileOfNode(d); + if (declFile === importTarget) { + return true; + } } } } @@ -79313,7 +81732,7 @@ var ts; return false; } function isInHeritageClause(node) { - return node.parent && node.parent.kind === 223 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 286 /* HeritageClause */; + return node.parent && node.parent.kind === 224 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 287 /* HeritageClause */; } // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -79325,7 +81744,7 @@ var ts; // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries var meaning = 788968 /* Type */ | 1920 /* Namespace */; - if ((node.kind === 78 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 201 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { + if ((node.kind === 78 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 202 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { meaning = 111551 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); @@ -79334,10 +81753,7 @@ var ts; // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForSymbol(symbol, meaning) { // program does not have any files with type reference directives - bail out - if (!fileToDirective) { - return undefined; - } - if (!isSymbolFromTypeDeclarationFile(symbol)) { + if (!fileToDirective || !isSymbolFromTypeDeclarationFile(symbol)) { return undefined; } // check what declarations in the symbol can contribute to the target meaning @@ -79376,7 +81792,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 297 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 298 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -79404,12 +81820,12 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = declaration.kind === 256 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 257 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 297 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 298 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -79429,7 +81845,7 @@ var ts; // It is an error for a non-external-module (i.e. script) to declare its own `globalThis`. // We can't use `builtinGlobals` for this due to synthetic expando-namespace generation in JS files. var fileGlobalThisSymbol = file.locals.get("globalThis"); - if (fileGlobalThisSymbol) { + if (fileGlobalThisSymbol === null || fileGlobalThisSymbol === void 0 ? void 0 : fileGlobalThisSymbol.declarations) { for (var _d = 0, _e = fileGlobalThisSymbol.declarations; _d < _e.length; _d++) { var declaration = _e[_d]; diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis")); @@ -79553,6 +81969,16 @@ var ts; if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name); } + else if (helper & 524288 /* ClassPrivateFieldGet */) { + if (!ts.some(getSignaturesOfSymbol(symbol), function (signature) { return getParameterCount(signature) > 3; })) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name, 4); + } + } + else if (helper & 1048576 /* ClassPrivateFieldSet */) { + if (!ts.some(getSignaturesOfSymbol(symbol), function (signature) { return getParameterCount(signature) > 4; })) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name, 5); + } + } } } } @@ -79602,14 +82028,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { - if (node.kind === 165 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + if (node.kind === 166 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 167 /* GetAccessor */ || node.kind === 168 /* SetAccessor */) { + else if (node.kind === 168 /* GetAccessor */ || node.kind === 169 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -79622,24 +82048,41 @@ var ts; if (quickResult !== undefined) { return quickResult; } - var lastStatic, lastDeclare, lastAsync, lastReadonly; + var lastStatic, lastDeclare, lastAsync, lastReadonly, lastOverride; var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; if (modifier.kind !== 142 /* ReadonlyKeyword */) { - if (node.kind === 162 /* PropertySignature */ || node.kind === 164 /* MethodSignature */) { + if (node.kind === 163 /* PropertySignature */ || node.kind === 165 /* MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 171 /* IndexSignature */) { + if (node.kind === 172 /* IndexSignature */ && (modifier.kind !== 123 /* StaticKeyword */ || !ts.isClassLike(node.parent))) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { case 84 /* ConstKeyword */: - if (node.kind !== 255 /* EnumDeclaration */) { + if (node.kind !== 256 /* EnumDeclaration */) { return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(84 /* ConstKeyword */)); } break; + case 156 /* OverrideKeyword */: + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "override"); + } + else if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "async"); + } + flags |= 16384 /* Override */; + lastOverride = modifier; + break; case 122 /* PublicKeyword */: case 121 /* ProtectedKeyword */: case 120 /* PrivateKeyword */: @@ -79647,6 +82090,9 @@ var ts; if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "override"); + } else if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } @@ -79656,7 +82102,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + else if (node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { @@ -79667,7 +82113,7 @@ var ts; return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); } } - else if (ts.isPrivateIdentifierPropertyDeclaration(node)) { + else if (ts.isPrivateIdentifierClassElementDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier); } flags |= ts.modifierToFlag(modifier.kind); @@ -79682,17 +82128,17 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + else if (node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - else if (ts.isPrivateIdentifierPropertyDeclaration(node)) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "static"); + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "override"); } flags |= 32 /* Static */; lastStatic = modifier; @@ -79701,8 +82147,8 @@ var ts; if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 163 /* PropertyDeclaration */ && node.kind !== 162 /* PropertySignature */ && node.kind !== 171 /* IndexSignature */ && node.kind !== 160 /* Parameter */) { - // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. + else if (node.kind !== 164 /* PropertyDeclaration */ && node.kind !== 163 /* PropertySignature */ && node.kind !== 172 /* IndexSignature */ && node.kind !== 161 /* Parameter */) { + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; @@ -79724,14 +82170,14 @@ var ts; else if (ts.isClassLike(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "export"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* Export */; break; case 87 /* DefaultKeyword */: - var container = node.parent.kind === 297 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 256 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 298 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 257 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512 /* Default */; @@ -79743,16 +82189,19 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override"); + } else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 257 /* ModuleBlock */) { + else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 258 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } - else if (ts.isPrivateIdentifierPropertyDeclaration(node)) { + else if (ts.isPrivateIdentifierClassElementDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare"); } flags |= 2 /* Ambient */; @@ -79762,15 +82211,15 @@ var ts; if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 252 /* ClassDeclaration */ && - node.kind !== 175 /* ConstructorType */) { - if (node.kind !== 165 /* MethodDeclaration */ && - node.kind !== 163 /* PropertyDeclaration */ && - node.kind !== 167 /* GetAccessor */ && - node.kind !== 168 /* SetAccessor */) { + if (node.kind !== 253 /* ClassDeclaration */ && + node.kind !== 176 /* ConstructorType */) { + if (node.kind !== 166 /* MethodDeclaration */ && + node.kind !== 164 /* PropertyDeclaration */ && + node.kind !== 168 /* GetAccessor */ && + node.kind !== 169 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 252 /* ClassDeclaration */ && ts.hasSyntacticModifier(node.parent, 128 /* Abstract */))) { + if (!(node.parent.kind === 253 /* ClassDeclaration */ && ts.hasSyntacticModifier(node.parent, 128 /* Abstract */))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -79782,6 +82231,9 @@ var ts; if (flags & 256 /* Async */ && lastAsync) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); } + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override"); + } } if (ts.isNamedDeclaration(node) && node.name.kind === 79 /* PrivateIdentifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract"); @@ -79795,7 +82247,7 @@ var ts; else if (flags & 2 /* Ambient */ || node.parent.flags & 8388608 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } if (flags & 128 /* Abstract */) { @@ -79806,13 +82258,16 @@ var ts; break; } } - if (node.kind === 166 /* Constructor */) { + if (node.kind === 167 /* Constructor */) { if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } if (flags & 128 /* Abstract */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 } + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(lastOverride, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); // TODO: GH#18217 + } else if (flags & 256 /* Async */) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } @@ -79821,13 +82276,13 @@ var ts; } return false; } - else if ((node.kind === 261 /* ImportDeclaration */ || node.kind === 260 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 262 /* ImportDeclaration */ || node.kind === 261 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 160 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 160 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { @@ -79848,38 +82303,38 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 166 /* Constructor */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 171 /* IndexSignature */: - case 256 /* ModuleDeclaration */: - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 160 /* Parameter */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 167 /* Constructor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 172 /* IndexSignature */: + case 257 /* ModuleDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 161 /* Parameter */: return false; default: - if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + if (node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { return false; } switch (node.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return nodeHasAnyModifiersExcept(node, 129 /* AsyncKeyword */); - case 252 /* ClassDeclaration */: - case 175 /* ConstructorType */: + case 253 /* ClassDeclaration */: + case 176 /* ConstructorType */: return nodeHasAnyModifiersExcept(node, 125 /* AbstractKeyword */); - case 253 /* InterfaceDeclaration */: - case 232 /* VariableStatement */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 233 /* VariableStatement */: + case 255 /* TypeAliasDeclaration */: return true; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return nodeHasAnyModifiersExcept(node, 84 /* ConstKeyword */); default: ts.Debug.fail(); @@ -79891,10 +82346,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -80055,7 +82510,7 @@ var ts; if (args) { for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { var arg = args_4[_i]; - if (arg.kind === 222 /* OmittedExpression */) { + if (arg.kind === 223 /* OmittedExpression */) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -80132,20 +82587,20 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 158 /* ComputedPropertyName */) { + if (node.kind !== 159 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 216 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { + if (computedPropertyName.expression.kind === 217 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 251 /* FunctionDeclaration */ || - node.kind === 208 /* FunctionExpression */ || - node.kind === 165 /* MethodDeclaration */); + ts.Debug.assert(node.kind === 252 /* FunctionDeclaration */ || + node.kind === 209 /* FunctionExpression */ || + node.kind === 166 /* MethodDeclaration */); if (node.flags & 8388608 /* Ambient */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -80164,7 +82619,7 @@ var ts; var seen = new ts.Map(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 290 /* SpreadAssignment */) { + if (prop.kind === 291 /* SpreadAssignment */) { if (inDestructuring) { // a rest property cannot be destructured any further var expression = ts.skipParentheses(prop.expression); @@ -80175,24 +82630,24 @@ var ts; continue; } var name = prop.name; - if (name.kind === 158 /* ComputedPropertyName */) { + if (name.kind === 159 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name); } - if (prop.kind === 289 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 290 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern); } if (name.kind === 79 /* PrivateIdentifier */) { - return grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); } // Modifiers are never allowed on properties except for 'async' on a method declaration if (prop.modifiers) { // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 var mod = _c[_b]; - if (mod.kind !== 129 /* AsyncKeyword */ || prop.kind !== 165 /* MethodDeclaration */) { + if (mod.kind !== 129 /* AsyncKeyword */ || prop.kind !== 166 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } @@ -80207,10 +82662,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 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); // falls through - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -80218,13 +82673,13 @@ var ts; } currentKind = 4 /* PropertyAssignment */; break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: currentKind = 8 /* Method */; break; - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: currentKind = 1 /* GetAccessor */; break; - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: currentKind = 2 /* SetAccessor */; break; default: @@ -80259,11 +82714,12 @@ var ts; } } function checkGrammarJsxElement(node) { + checkGrammarJsxName(node.tagName); checkGrammarTypeArguments(node, node.typeArguments); var seen = new ts.Map(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 282 /* JsxSpreadAttribute */) { + if (attr.kind === 283 /* JsxSpreadAttribute */) { continue; } var name = attr.name, initializer = attr.initializer; @@ -80273,11 +82729,32 @@ var ts; else { return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - if (initializer && initializer.kind === 283 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 284 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } } + function checkGrammarJsxName(node) { + if (ts.isPropertyAccessExpression(node)) { + var propName = node; + do { + var check_1 = checkGrammarJsxNestedIdentifier(propName.name); + if (check_1) { + return check_1; + } + propName = propName.expression; + } while (ts.isPropertyAccessExpression(propName)); + var check = checkGrammarJsxNestedIdentifier(propName); + if (check) { + return check; + } + } + function checkGrammarJsxNestedIdentifier(name) { + if (ts.isIdentifier(name) && ts.idText(name).indexOf(":") !== -1) { + return grammarErrorOnNode(name, ts.Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names); + } + } + } function checkGrammarJsxExpression(node) { if (node.expression && ts.isCommaSequence(node.expression)) { return grammarErrorOnNode(node.expression, ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array); @@ -80287,25 +82764,37 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 239 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { - if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) { - // use of 'for-await-of' in non-async function + if (forInOrOfStatement.kind === 240 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if (!(forInOrOfStatement.flags & 32768 /* AwaitContext */)) { var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement); - if (!hasParseDiagnostics(sourceFile)) { - var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); - var func = ts.getContainingFunction(forInOrOfStatement); - if (func && func.kind !== 166 /* Constructor */) { - ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); - var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); - ts.addRelatedInfo(diagnostic, relatedInfo); - } - diagnostics.add(diagnostic); - return true; + if (ts.isInTopLevelContext(forInOrOfStatement)) { + if (!hasParseDiagnostics(sourceFile)) { + if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module)); + } + if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher)); + } + } + } + else { + // use of 'for-await-of' in non-async function + if (!hasParseDiagnostics(sourceFile)) { + var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); + var func = ts.getContainingFunction(forInOrOfStatement); + if (func && func.kind !== 167 /* Constructor */) { + ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); + var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); + ts.addRelatedInfo(diagnostic, relatedInfo); + } + diagnostics.add(diagnostic); + return true; + } } return false; } } - if (forInOrOfStatement.initializer.kind === 250 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 251 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -80320,20 +82809,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 239 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 239 /* ForInStatement */ ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 239 /* ForInStatement */ ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -80343,26 +82832,34 @@ var ts; return false; } function checkGrammarAccessor(accessor) { - if (!(accessor.flags & 8388608 /* Ambient */)) { + if (!(accessor.flags & 8388608 /* Ambient */) && (accessor.parent.kind !== 178 /* TypeLiteral */) && (accessor.parent.kind !== 254 /* InterfaceDeclaration */)) { if (languageVersion < 1 /* ES5 */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } + if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(accessor.name)) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } if (accessor.body === undefined && !ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) { return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } - if (accessor.body && ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) { - return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + if (accessor.body) { + if (ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + if (accessor.parent.kind === 178 /* TypeLiteral */ || accessor.parent.kind === 254 /* InterfaceDeclaration */) { + return grammarErrorOnNode(accessor.body, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } } if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, accessor.kind === 167 /* GetAccessor */ ? + return grammarErrorOnNode(accessor.name, accessor.kind === 168 /* GetAccessor */ ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - if (accessor.kind === 168 /* SetAccessor */) { + if (accessor.kind === 169 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -80384,10 +82881,10 @@ var ts; * A set accessor has one parameter or a `this` parameter and one more parameter. */ function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 167 /* GetAccessor */ ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 168 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 167 /* GetAccessor */ ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 168 /* GetAccessor */ ? 1 : 2)) { return ts.getThisParameter(accessor); } } @@ -80405,7 +82902,7 @@ var ts; } } switch (parent.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: var decl = parent; if (decl.name.kind !== 78 /* Identifier */) { return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); @@ -80417,13 +82914,13 @@ var ts; return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); } break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: if (!ts.hasSyntacticModifier(parent, 32 /* Static */) || !ts.hasEffectiveModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: if (!ts.hasSyntacticModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } @@ -80433,7 +82930,7 @@ var ts; } } else if (node.operator === 142 /* ReadonlyKeyword */) { - if (node.type.kind !== 178 /* ArrayType */ && node.type.kind !== 179 /* TupleType */) { + if (node.type.kind !== 179 /* ArrayType */ && node.type.kind !== 180 /* TupleType */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(148 /* SymbolKeyword */)); } } @@ -80447,8 +82944,8 @@ var ts; if (checkGrammarFunctionLikeDeclaration(node)) { return true; } - if (node.kind === 165 /* MethodDeclaration */) { - if (node.parent.kind === 200 /* ObjectLiteralExpression */) { + if (node.kind === 166 /* MethodDeclaration */) { + if (node.parent.kind === 201 /* ObjectLiteralExpression */) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 129 /* AsyncKeyword */)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -80468,6 +82965,9 @@ var ts; } } if (ts.isClassLike(node.parent)) { + if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) { + return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } // Technically, computed properties in ambient contexts is disallowed // for property declarations and accessors too, not just methods. // However, property declarations disallow computed names in general, @@ -80476,14 +82976,14 @@ var ts; if (node.flags & 8388608 /* Ambient */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.kind === 165 /* MethodDeclaration */ && !node.body) { + else if (node.kind === 166 /* MethodDeclaration */ && !node.body) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 253 /* InterfaceDeclaration */) { + else if (node.parent.kind === 254 /* InterfaceDeclaration */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 177 /* TypeLiteral */) { + else if (node.parent.kind === 178 /* TypeLiteral */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } @@ -80494,11 +82994,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: if (node.label && current.label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 240 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 241 /* ContinueStatement */ && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -80506,8 +83006,8 @@ var ts; return false; } break; - case 244 /* SwitchStatement */: - if (node.kind === 241 /* BreakStatement */ && !node.label) { + case 245 /* SwitchStatement */: + if (node.kind === 242 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -80522,13 +83022,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 241 /* BreakStatement */ + var message = node.kind === 242 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 241 /* BreakStatement */ + var message = node.kind === 242 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -80552,12 +83052,12 @@ var ts; } function isStringOrNumberLiteralExpression(expr) { return ts.isStringOrNumericLiteralLike(expr) || - expr.kind === 214 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && + expr.kind === 215 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } function isBigIntLiteralExpression(expr) { return expr.kind === 9 /* BigIntLiteral */ || - expr.kind === 214 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && + expr.kind === 215 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && expr.operand.kind === 9 /* BigIntLiteral */; } function isSimpleLiteralEnumReference(expr) { @@ -80588,7 +83088,7 @@ var ts; } } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 238 /* ForInStatement */ && node.parent.parent.kind !== 239 /* ForOfStatement */) { + if (node.parent.parent.kind !== 239 /* ForInStatement */ && node.parent.parent.kind !== 240 /* ForOfStatement */) { if (node.flags & 8388608 /* Ambient */) { checkAmbientInitializer(node); } @@ -80601,7 +83101,7 @@ var ts; } } } - if (node.exclamationToken && (node.parent.parent.kind !== 232 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) { + if (node.exclamationToken && (node.parent.parent.kind !== 233 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) { var message = node.initializer ? ts.Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type @@ -80669,15 +83169,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 234 /* IfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 243 /* WithStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 235 /* IfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 244 /* WithStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: return false; - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -80762,14 +83262,14 @@ var ts; if (ts.isStringLiteral(node.name) && node.name.text === "constructor") { return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor); } - if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type)) { return true; } if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) { return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); } } - else if (node.parent.kind === 253 /* InterfaceDeclaration */) { + else if (node.parent.kind === 254 /* InterfaceDeclaration */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -80777,7 +83277,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 177 /* TypeLiteral */) { + else if (node.parent.kind === 178 /* TypeLiteral */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -80811,13 +83311,13 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 253 /* InterfaceDeclaration */ || - node.kind === 254 /* TypeAliasDeclaration */ || - node.kind === 261 /* ImportDeclaration */ || - node.kind === 260 /* ImportEqualsDeclaration */ || - node.kind === 267 /* ExportDeclaration */ || - node.kind === 266 /* ExportAssignment */ || - node.kind === 259 /* NamespaceExportDeclaration */ || + if (node.kind === 254 /* InterfaceDeclaration */ || + node.kind === 255 /* TypeAliasDeclaration */ || + node.kind === 262 /* ImportDeclaration */ || + node.kind === 261 /* ImportEqualsDeclaration */ || + node.kind === 268 /* ExportDeclaration */ || + node.kind === 267 /* ExportAssignment */ || + node.kind === 260 /* NamespaceExportDeclaration */ || ts.hasSyntacticModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } @@ -80826,7 +83326,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 232 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 233 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -80849,7 +83349,7 @@ var ts; // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if (node.parent.kind === 230 /* Block */ || node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + if (node.parent.kind === 231 /* Block */ || node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { var links_2 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_2.hasReportedStatementInAmbientContext) { @@ -80871,10 +83371,10 @@ var ts; if (languageVersion >= 1 /* ES5 */) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 191 /* LiteralType */)) { + else if (ts.isChildOfNodeWithKind(node, 192 /* LiteralType */)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 291 /* EnumMember */)) { + else if (ts.isChildOfNodeWithKind(node, 292 /* EnumMember */)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { @@ -80980,7 +83480,7 @@ var ts; } } function findBestTypeForObjectLiteral(source, unionTarget) { - if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) { + if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && someType(unionTarget, isArrayLikeType)) { return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } @@ -81032,6 +83532,10 @@ var ts; // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) { if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) { + var match = getMatchingUnionConstituentForType(target, source); + if (match) { + return match; + } var sourceProperties = getPropertiesOfType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); @@ -81049,33 +83553,19 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 251 /* FunctionDeclaration */ && declaration.kind !== 165 /* MethodDeclaration */) || + return (declaration.kind !== 252 /* FunctionDeclaration */ && declaration.kind !== 166 /* MethodDeclaration */) || !!declaration.body; } /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return ts.isIdentifier(name); default: return ts.isDeclarationName(name); } } - function isSomeImportDeclaration(decl) { - switch (decl.kind) { - case 262 /* ImportClause */: // For default import - case 260 /* ImportEqualsDeclaration */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: // For rename import `x as y` - return true; - case 78 /* Identifier */: - // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 265 /* ImportSpecifier */; - default: - return false; - } - } var JsxNames; (function (JsxNames) { JsxNames.JSX = "JSX"; @@ -81106,7 +83596,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); function visitNode(node, visitor, test, lift) { if (node === undefined || visitor === undefined) { return node; @@ -81295,6 +83784,24 @@ var ts; return updated; } ts.visitFunctionBody = visitFunctionBody; + /** + * Visits an iteration body, adding any block-scoped variables required by the transformation. + */ + function visitIterationBody(body, visitor, context) { + context.startBlockScope(); + var updated = visitNode(body, visitor, ts.isStatement, context.factory.liftToBlock); + var declarations = context.endBlockScope(); + if (ts.some(declarations)) { + if (ts.isBlock(updated)) { + declarations.push.apply(declarations, updated.statements); + return context.factory.updateBlock(updated, declarations); + } + declarations.push(updated); + return context.factory.createBlock(declarations); + } + return updated; + } + ts.visitIterationBody = visitIterationBody; function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor, nodeVisitor) { if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } if (nodeVisitor === void 0) { nodeVisitor = visitNode; } @@ -81303,299 +83810,433 @@ var ts; } var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 156 /* LastToken */) || kind === 187 /* ThisType */) { + if ((kind > 0 /* FirstToken */ && kind <= 157 /* LastToken */) || kind === 188 /* ThisType */) { return node; } var factory = context.factory; switch (kind) { // Names case 78 /* Identifier */: - return factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); - case 157 /* QualifiedName */: + ts.Debug.type(node); + return factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNodeOrTypeParameterDeclaration)); + case 158 /* QualifiedName */: + ts.Debug.type(node); return factory.updateQualifiedName(node, nodeVisitor(node.left, visitor, ts.isEntityName), nodeVisitor(node.right, visitor, ts.isIdentifier)); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: + ts.Debug.type(node); return factory.updateComputedPropertyName(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Signature elements - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: + ts.Debug.type(node); return factory.updateTypeParameterDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode)); - case 160 /* Parameter */: - return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 161 /* Decorator */: + case 161 /* Parameter */: + ts.Debug.type(node); + return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 162 /* Decorator */: + ts.Debug.type(node); return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Type elements - case 162 /* PropertySignature */: - return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 163 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + ts.Debug.type(node); + return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 164 /* PropertyDeclaration */: + ts.Debug.type(node); return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too - nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 164 /* MethodSignature */: - return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 165 /* MethodDeclaration */: - return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 166 /* Constructor */: + nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isQuestionOrExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 165 /* MethodSignature */: + ts.Debug.type(node); + return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 166 /* MethodDeclaration */: + ts.Debug.type(node); + return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 167 /* Constructor */: + ts.Debug.type(node); return factory.updateConstructorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: + ts.Debug.type(node); return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: + ts.Debug.type(node); return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 169 /* CallSignature */: + case 170 /* CallSignature */: + ts.Debug.type(node); return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: + ts.Debug.type(node); return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: + ts.Debug.type(node); return factory.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); // Types - case 172 /* TypePredicate */: - return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor), nodeVisitor(node.parameterName, visitor), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 173 /* TypeReference */: + case 173 /* TypePredicate */: + ts.Debug.type(node); + return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor, ts.isAssertsKeyword), nodeVisitor(node.parameterName, visitor, ts.isIdentifierOrThisTypeNode), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 174 /* TypeReference */: + ts.Debug.type(node); return factory.updateTypeReferenceNode(node, nodeVisitor(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 174 /* FunctionType */: + case 175 /* FunctionType */: + ts.Debug.type(node); return factory.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 175 /* ConstructorType */: + case 176 /* ConstructorType */: + ts.Debug.type(node); return factory.updateConstructorTypeNode(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: + ts.Debug.type(node); return factory.updateTypeQueryNode(node, nodeVisitor(node.exprName, visitor, ts.isEntityName)); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: + ts.Debug.type(node); return factory.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 178 /* ArrayType */: + case 179 /* ArrayType */: + ts.Debug.type(node); return factory.updateArrayTypeNode(node, nodeVisitor(node.elementType, visitor, ts.isTypeNode)); - case 179 /* TupleType */: + case 180 /* TupleType */: + ts.Debug.type(node); return factory.updateTupleTypeNode(node, nodesVisitor(node.elements, visitor, ts.isTypeNode)); - case 180 /* OptionalType */: + case 181 /* OptionalType */: + ts.Debug.type(node); return factory.updateOptionalTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 181 /* RestType */: + case 182 /* RestType */: + ts.Debug.type(node); return factory.updateRestTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 182 /* UnionType */: + case 183 /* UnionType */: + ts.Debug.type(node); return factory.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 183 /* IntersectionType */: + case 184 /* IntersectionType */: + ts.Debug.type(node); return factory.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: + ts.Debug.type(node); return factory.updateConditionalTypeNode(node, nodeVisitor(node.checkType, visitor, ts.isTypeNode), nodeVisitor(node.extendsType, visitor, ts.isTypeNode), nodeVisitor(node.trueType, visitor, ts.isTypeNode), nodeVisitor(node.falseType, visitor, ts.isTypeNode)); - case 185 /* InferType */: + case 186 /* InferType */: + ts.Debug.type(node); return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); - case 195 /* ImportType */: + case 196 /* ImportType */: + ts.Debug.type(node); return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); - case 192 /* NamedTupleMember */: - return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); - case 186 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: + ts.Debug.type(node); + return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isDotDotDotToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isQuestionToken), visitNode(node.type, visitor, ts.isTypeNode)); + case 187 /* ParenthesizedType */: + ts.Debug.type(node); return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: + ts.Debug.type(node); return factory.updateTypeOperatorNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: + ts.Debug.type(node); return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode)); - case 190 /* MappedType */: - return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 191 /* LiteralType */: + case 191 /* MappedType */: + ts.Debug.type(node); + return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 192 /* LiteralType */: + ts.Debug.type(node); return factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression)); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: + ts.Debug.type(node); return factory.updateTemplateLiteralType(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateLiteralTypeSpan)); - case 194 /* TemplateLiteralTypeSpan */: + case 195 /* TemplateLiteralTypeSpan */: + ts.Debug.type(node); return factory.updateTemplateLiteralTypeSpan(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Binding patterns - case 196 /* ObjectBindingPattern */: + case 197 /* ObjectBindingPattern */: + ts.Debug.type(node); return factory.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: + ts.Debug.type(node); return factory.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); - case 198 /* BindingElement */: - return factory.updateBindingElement(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.propertyName, visitor, ts.isPropertyName), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 199 /* BindingElement */: + ts.Debug.type(node); + return factory.updateBindingElement(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.propertyName, visitor, ts.isPropertyName), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.initializer, visitor, ts.isExpression)); // Expression - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: + ts.Debug.type(node); return factory.updateArrayLiteralExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression)); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + ts.Debug.type(node); return factory.updateObjectLiteralExpression(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (node.flags & 32 /* OptionalChain */) { - return factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier)); + ts.Debug.type(node); + return factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodeVisitor(node.name, visitor, ts.isMemberName)); } - return factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isIdentifierOrPrivateIdentifier)); - case 202 /* ElementAccessExpression */: + ts.Debug.type(node); + return factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isMemberName)); + case 203 /* ElementAccessExpression */: if (node.flags & 32 /* OptionalChain */) { - return factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); } + ts.Debug.type(node); return factory.updateElementAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (node.flags & 32 /* OptionalChain */) { - return factory.updateCallChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateCallChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); } + ts.Debug.type(node); return factory.updateCallExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 204 /* NewExpression */: + case 205 /* NewExpression */: + ts.Debug.type(node); return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 205 /* TaggedTemplateExpression */: - return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); - case 206 /* TypeAssertionExpression */: + case 206 /* TaggedTemplateExpression */: + ts.Debug.type(node); + return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); + case 207 /* TypeAssertionExpression */: + ts.Debug.type(node); return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: + ts.Debug.type(node); return factory.updateParenthesizedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 208 /* FunctionExpression */: - return factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 209 /* ArrowFunction */: - return factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, ts.isToken), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 210 /* DeleteExpression */: + case 209 /* FunctionExpression */: + ts.Debug.type(node); + return factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 210 /* ArrowFunction */: + ts.Debug.type(node); + return factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, ts.isEqualsGreaterThanToken), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 211 /* DeleteExpression */: + ts.Debug.type(node); return factory.updateDeleteExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: + ts.Debug.type(node); return factory.updateTypeOfExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: + ts.Debug.type(node); return factory.updateVoidExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: + ts.Debug.type(node); return factory.updateAwaitExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + ts.Debug.type(node); return factory.updatePrefixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression)); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + ts.Debug.type(node); return factory.updatePostfixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression)); - case 216 /* BinaryExpression */: - return factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isToken), nodeVisitor(node.right, visitor, ts.isExpression)); - case 217 /* ConditionalExpression */: - return factory.updateConditionalExpression(node, nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.whenTrue, visitor, ts.isExpression), nodeVisitor(node.colonToken, tokenVisitor, ts.isToken), nodeVisitor(node.whenFalse, visitor, ts.isExpression)); - case 218 /* TemplateExpression */: + case 217 /* BinaryExpression */: + ts.Debug.type(node); + return factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isBinaryOperatorToken), nodeVisitor(node.right, visitor, ts.isExpression)); + case 218 /* ConditionalExpression */: + ts.Debug.type(node); + return factory.updateConditionalExpression(node, nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.whenTrue, visitor, ts.isExpression), nodeVisitor(node.colonToken, tokenVisitor, ts.isColonToken), nodeVisitor(node.whenFalse, visitor, ts.isExpression)); + case 219 /* TemplateExpression */: + ts.Debug.type(node); return factory.updateTemplateExpression(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); - case 219 /* YieldExpression */: - return factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 220 /* SpreadElement */: + case 220 /* YieldExpression */: + ts.Debug.type(node); + return factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.expression, visitor, ts.isExpression)); + case 221 /* SpreadElement */: + ts.Debug.type(node); return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: + ts.Debug.type(node); return factory.updateClassExpression(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: + ts.Debug.type(node); return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 224 /* AsExpression */: + case 225 /* AsExpression */: + ts.Debug.type(node); return factory.updateAsExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: if (node.flags & 32 /* OptionalChain */) { + ts.Debug.type(node); return factory.updateNonNullChain(node, nodeVisitor(node.expression, visitor, ts.isExpression)); } + ts.Debug.type(node); return factory.updateNonNullExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: + ts.Debug.type(node); return factory.updateMetaProperty(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); // Misc - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: + ts.Debug.type(node); return factory.updateTemplateSpan(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element - case 230 /* Block */: + case 231 /* Block */: + ts.Debug.type(node); return factory.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: + ts.Debug.type(node); return factory.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: + ts.Debug.type(node); return factory.updateExpressionStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 234 /* IfStatement */: + case 235 /* IfStatement */: + ts.Debug.type(node); return factory.updateIfStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.thenStatement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.elseStatement, visitor, ts.isStatement, factory.liftToBlock)); - case 235 /* DoStatement */: - return factory.updateDoStatement(node, nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 236 /* WhileStatement */: - return factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 237 /* ForStatement */: - return factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.incrementor, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 238 /* ForInStatement */: - return factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 239 /* ForOfStatement */: - return factory.updateForOfStatement(node, nodeVisitor(node.awaitModifier, tokenVisitor, ts.isToken), nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 240 /* ContinueStatement */: + case 236 /* DoStatement */: + ts.Debug.type(node); + return factory.updateDoStatement(node, visitIterationBody(node.statement, visitor, context), nodeVisitor(node.expression, visitor, ts.isExpression)); + case 237 /* WhileStatement */: + ts.Debug.type(node); + return factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 238 /* ForStatement */: + ts.Debug.type(node); + return factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.incrementor, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 239 /* ForInStatement */: + ts.Debug.type(node); + return factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 240 /* ForOfStatement */: + ts.Debug.type(node); + return factory.updateForOfStatement(node, nodeVisitor(node.awaitModifier, tokenVisitor, ts.isAwaitKeyword), nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 241 /* ContinueStatement */: + ts.Debug.type(node); return factory.updateContinueStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier)); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: + ts.Debug.type(node); return factory.updateBreakStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier)); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: + ts.Debug.type(node); return factory.updateReturnStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 243 /* WithStatement */: + case 244 /* WithStatement */: + ts.Debug.type(node); return factory.updateWithStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: + ts.Debug.type(node); return factory.updateSwitchStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.caseBlock, visitor, ts.isCaseBlock)); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: + ts.Debug.type(node); return factory.updateLabeledStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: + ts.Debug.type(node); return factory.updateThrowStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 247 /* TryStatement */: + case 248 /* TryStatement */: + ts.Debug.type(node); return factory.updateTryStatement(node, nodeVisitor(node.tryBlock, visitor, ts.isBlock), nodeVisitor(node.catchClause, visitor, ts.isCatchClause), nodeVisitor(node.finallyBlock, visitor, ts.isBlock)); - case 249 /* VariableDeclaration */: - return factory.updateVariableDeclaration(node, nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 250 /* VariableDeclarationList */: + case 250 /* VariableDeclaration */: + ts.Debug.type(node); + return factory.updateVariableDeclaration(node, nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.exclamationToken, tokenVisitor, ts.isExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 251 /* VariableDeclarationList */: + ts.Debug.type(node); return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); - case 251 /* FunctionDeclaration */: - return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 252 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: + ts.Debug.type(node); + return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 253 /* ClassDeclaration */: + ts.Debug.type(node); return factory.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: + ts.Debug.type(node); return factory.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: + ts.Debug.type(node); return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: + ts.Debug.type(node); return factory.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); - case 256 /* ModuleDeclaration */: - return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.body, visitor, ts.isModuleBody)); - case 257 /* ModuleBlock */: + case 257 /* ModuleDeclaration */: + ts.Debug.type(node); + return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); + case 258 /* ModuleBlock */: + ts.Debug.type(node); return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: + ts.Debug.type(node); return factory.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: + ts.Debug.type(node); return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: + ts.Debug.type(node); return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: + ts.Debug.type(node); return factory.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression)); - case 262 /* ImportClause */: + case 263 /* ImportClause */: + ts.Debug.type(node); return factory.updateImportClause(node, node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.namedBindings, visitor, ts.isNamedImportBindings)); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: + ts.Debug.type(node); return factory.updateNamespaceImport(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: + ts.Debug.type(node); return factory.updateNamespaceExport(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 264 /* NamedImports */: + case 265 /* NamedImports */: + ts.Debug.type(node); return factory.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: + ts.Debug.type(node); return factory.updateImportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: + ts.Debug.type(node); return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: + ts.Debug.type(node); return factory.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression)); - case 268 /* NamedExports */: + case 269 /* NamedExports */: + ts.Debug.type(node); return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: + ts.Debug.type(node); return factory.updateExportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); // Module references - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: + ts.Debug.type(node); return factory.updateExternalModuleReference(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // JSX - case 273 /* JsxElement */: + case 274 /* JsxElement */: + ts.Debug.type(node); return factory.updateJsxElement(node, nodeVisitor(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingElement, visitor, ts.isJsxClosingElement)); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: + ts.Debug.type(node); return factory.updateJsxSelfClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes)); - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: + ts.Debug.type(node); return factory.updateJsxOpeningElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes)); - case 276 /* JsxClosingElement */: + case 277 /* JsxClosingElement */: + ts.Debug.type(node); return factory.updateJsxClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: + ts.Debug.type(node); return factory.updateJsxFragment(node, nodeVisitor(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingFragment, visitor, ts.isJsxClosingFragment)); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: + ts.Debug.type(node); return factory.updateJsxAttribute(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: + ts.Debug.type(node); return factory.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 282 /* JsxSpreadAttribute */: + case 283 /* JsxSpreadAttribute */: + ts.Debug.type(node); return factory.updateJsxSpreadAttribute(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: + ts.Debug.type(node); return factory.updateJsxExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Clauses - case 284 /* CaseClause */: + case 285 /* CaseClause */: + ts.Debug.type(node); return factory.updateCaseClause(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: + ts.Debug.type(node); return factory.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: + ts.Debug.type(node); return factory.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 287 /* CatchClause */: + case 288 /* CatchClause */: + ts.Debug.type(node); return factory.updateCatchClause(node, nodeVisitor(node.variableDeclaration, visitor, ts.isVariableDeclaration), nodeVisitor(node.block, visitor, ts.isBlock)); // Property assignments - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: + ts.Debug.type(node); return factory.updatePropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + ts.Debug.type(node); return factory.updateShorthandPropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: + ts.Debug.type(node); return factory.updateSpreadAssignment(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Enum - case 291 /* EnumMember */: + case 292 /* EnumMember */: + ts.Debug.type(node); return factory.updateEnumMember(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression)); // Top-level nodes - case 297 /* SourceFile */: + case 298 /* SourceFile */: + ts.Debug.type(node); return factory.updateSourceFile(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 336 /* PartiallyEmittedExpression */: + case 340 /* PartiallyEmittedExpression */: + ts.Debug.type(node); return factory.updatePartiallyEmittedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: + ts.Debug.type(node); return factory.updateCommaListExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -82270,7 +84911,7 @@ var ts; function chainBundle(context, transformSourceFile) { return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - return node.kind === 297 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + return node.kind === 298 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); } function transformBundle(node) { return context.factory.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); @@ -82321,7 +84962,7 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: // import "mod" // import x from "mod" // import * as x from "mod" @@ -82334,13 +84975,13 @@ var ts; hasImportDefault = true; } break; - case 260 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 272 /* ExternalModuleReference */) { + case 261 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 273 /* ExternalModuleReference */) { // import x = require("mod") externalImports.push(node); } break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" @@ -82371,13 +85012,13 @@ var ts; addExportedNamesForExportDeclaration(node); } break; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; } break; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: if (ts.hasSyntacticModifier(node, 1 /* Export */)) { for (var _b = 0, _c = node.declarationList.declarations; _b < _c.length; _b++) { var decl = _c[_b]; @@ -82385,7 +85026,7 @@ var ts; } } break; - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: if (ts.hasSyntacticModifier(node, 1 /* Export */)) { if (ts.hasSyntacticModifier(node, 512 /* Default */)) { // export default function() { } @@ -82405,7 +85046,7 @@ var ts; } } break; - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: if (ts.hasSyntacticModifier(node, 1 /* Export */)) { if (ts.hasSyntacticModifier(node, 512 /* Default */)) { // export default class { } @@ -82499,8 +85140,7 @@ var ts; * any such locations */ function isSimpleInlineableExpression(expression) { - return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression) || - ts.isWellKnownSymbolSyntactically(expression); + return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression); } ts.isSimpleInlineableExpression = isSimpleInlineableExpression; function isCompoundAssignment(kind) { @@ -82579,10 +85219,19 @@ var ts; * @param isStatic A value indicating whether the member should be a static or instance member. */ function isInitializedProperty(member) { - return member.kind === 163 /* PropertyDeclaration */ + return member.kind === 164 /* PropertyDeclaration */ && member.initializer !== undefined; } ts.isInitializedProperty = isInitializedProperty; + /** + * Gets a value indicating whether a class element is a private instance method or accessor. + * + * @param member The class element node. + */ + function isNonStaticMethodOrAccessorWithPrivateName(member) { + return !ts.hasStaticModifier(member) && ts.isMethodOrAccessor(member) && ts.isPrivateIdentifier(member.name); + } + ts.isNonStaticMethodOrAccessorWithPrivateName = isNonStaticMethodOrAccessorWithPrivateName; })(ts || (ts = {})); /*@internal*/ var ts; @@ -82856,8 +85505,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */)) + && !(element.transformFlags & (16384 /* ContainsRestOrSpread */ | 32768 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (16384 /* ContainsRestOrSpread */ | 32768 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor)); } @@ -82923,7 +85572,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 & 16384 /* ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { + if (element.transformFlags & 32768 /* ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { flattenContext.hasTransformedPriorElement = true; var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { @@ -83181,8 +85830,8 @@ var ts; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; // Enable substitution for property/element access to emit const enum values. - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(202 /* ElementAccessExpression */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(203 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; @@ -83208,14 +85857,14 @@ var ts; var applicableSubstitutions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - if (node.kind === 298 /* Bundle */) { + if (node.kind === 299 /* Bundle */) { return transformBundle(node); } return transformSourceFile(node); } function transformBundle(node) { return factory.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 300 /* InputFiles */) { + if (prepend.kind === 301 /* InputFiles */) { return ts.createUnparsedSourceFile(prepend, "js"); } return prepend; @@ -83266,16 +85915,16 @@ var ts; */ function onBeforeVisitNode(node) { switch (node.kind) { - case 297 /* SourceFile */: - case 258 /* CaseBlock */: - case 257 /* ModuleBlock */: - case 230 /* Block */: + case 298 /* SourceFile */: + case 259 /* CaseBlock */: + case 258 /* ModuleBlock */: + case 231 /* Block */: currentLexicalScope = node; currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; - case 252 /* ClassDeclaration */: - case 251 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: if (ts.hasSyntacticModifier(node, 2 /* Ambient */)) { break; } @@ -83287,7 +85936,7 @@ var ts; // These nodes should always have names unless they are default-exports; // however, class declaration parsing allows for undefined names, so syntactically invalid // programs may also have an undefined name. - ts.Debug.assert(node.kind === 252 /* ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* Default */)); + ts.Debug.assert(node.kind === 253 /* ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* Default */)); } if (ts.isClassDeclaration(node)) { // XXX: should probably also cover interfaces and type aliases that can have type variables? @@ -83330,10 +85979,10 @@ var ts; */ function sourceElementVisitorWorker(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 266 /* ExportAssignment */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 267 /* ExportAssignment */: + case 268 /* ExportDeclaration */: return visitElidableStatement(node); default: return visitorWorker(node); @@ -83354,13 +86003,13 @@ var ts; return node; } switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -83380,11 +86029,11 @@ var ts; * @param node The node to visit. */ function namespaceElementVisitorWorker(node) { - if (node.kind === 267 /* ExportDeclaration */ || - node.kind === 261 /* ImportDeclaration */ || - node.kind === 262 /* ImportClause */ || - (node.kind === 260 /* ImportEqualsDeclaration */ && - node.moduleReference.kind === 272 /* ExternalModuleReference */)) { + if (node.kind === 268 /* ExportDeclaration */ || + node.kind === 262 /* ImportDeclaration */ || + node.kind === 263 /* ImportClause */ || + (node.kind === 261 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 273 /* ExternalModuleReference */)) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -83408,26 +86057,26 @@ var ts; */ function classElementVisitorWorker(node) { switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return visitConstructor(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // Property declarations are not TypeScript syntax, but they must be visited // for the decorator transformation. return visitPropertyDeclaration(node); - case 171 /* IndexSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: + case 172 /* IndexSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: // Fallback to the default visit behavior. return visitorWorker(node); - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: return node; default: return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { - if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) { + if (ts.modifierToFlag(node.kind) & 18654 /* TypeScriptModifier */) { return undefined; } else if (currentNamespace && node.kind === 92 /* ExportKeyword */) { @@ -83460,13 +86109,13 @@ var ts; case 142 /* ReadonlyKeyword */: // TypeScript accessibility and readonly modifiers are elided // falls through - case 178 /* ArrayType */: - case 179 /* TupleType */: - case 180 /* OptionalType */: - case 181 /* RestType */: - case 177 /* TypeLiteral */: - case 172 /* TypePredicate */: - case 159 /* TypeParameter */: + case 179 /* ArrayType */: + case 180 /* TupleType */: + case 181 /* OptionalType */: + case 182 /* RestType */: + case 178 /* TypeLiteral */: + case 173 /* TypePredicate */: + case 160 /* TypeParameter */: case 128 /* AnyKeyword */: case 152 /* UnknownKeyword */: case 131 /* BooleanKeyword */: @@ -83475,43 +86124,43 @@ var ts; case 141 /* NeverKeyword */: case 113 /* VoidKeyword */: case 148 /* SymbolKeyword */: - case 175 /* ConstructorType */: - case 174 /* FunctionType */: - case 176 /* TypeQuery */: - case 173 /* TypeReference */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 184 /* ConditionalType */: - case 186 /* ParenthesizedType */: - case 187 /* ThisType */: - case 188 /* TypeOperator */: - case 189 /* IndexedAccessType */: - case 190 /* MappedType */: - case 191 /* LiteralType */: + case 176 /* ConstructorType */: + case 175 /* FunctionType */: + case 177 /* TypeQuery */: + case 174 /* TypeReference */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 185 /* ConditionalType */: + case 187 /* ParenthesizedType */: + case 188 /* ThisType */: + case 189 /* TypeOperator */: + case 190 /* IndexedAccessType */: + case 191 /* MappedType */: + case 192 /* LiteralType */: // TypeScript type nodes are elided. // falls through - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: // TypeScript index signatures are elided. // falls through - case 161 /* Decorator */: + case 162 /* Decorator */: // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. // falls through - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return undefined; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects return visitPropertyDeclaration(node); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 166 /* Constructor */: + case 167 /* Constructor */: return visitConstructor(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return factory.createNotEmittedStatement(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: // This may be a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -83521,7 +86170,7 @@ var ts; // - index signatures // - method overload signatures return visitClassDeclaration(node); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: // This may be a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -83531,35 +86180,35 @@ var ts; // - index signatures // - method overload signatures return visitClassExpression(node); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: // This may be a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause return visitHeritageClause(node); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); - case 160 /* Parameter */: + case 161 /* Parameter */: // This may be a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: @@ -83569,40 +86218,40 @@ var ts; // - type annotations // - this parameters return visitParameter(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: // ParenthesizedExpressions are TypeScript if their expression is a // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return visitNewExpression(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node); - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: return visitJsxJsxOpeningElement(node); default: // node contains some other TypeScript syntax @@ -83656,7 +86305,7 @@ var ts; return facts; } function hasTypeScriptClassSyntax(node) { - return !!(node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */); + return !!(node.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */); } function isClassLikeDeclarationWithTypeScriptSyntax(node) { return ts.some(node.decorators) @@ -84011,12 +86660,12 @@ var ts; */ function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return getAllDecoratorsOfAccessors(node, member); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return getAllDecoratorsOfMethod(member); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -84169,7 +86818,7 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); var descriptor = languageVersion > 0 /* ES3 */ - ? member.kind === 163 /* PropertyDeclaration */ + ? member.kind === 164 /* PropertyDeclaration */ // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it // should not invoke `Object.getOwnPropertyDescriptor`. ? factory.createVoidZero() @@ -84293,10 +86942,10 @@ var ts; */ function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 163 /* PropertyDeclaration */; + return kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 164 /* PropertyDeclaration */; } /** * Determines whether to emit the "design:returntype" metadata based on the node's kind. @@ -84306,7 +86955,7 @@ var ts; * @param node The node to test. */ function shouldAddReturnTypeMetadata(node) { - return node.kind === 165 /* MethodDeclaration */; + return node.kind === 166 /* MethodDeclaration */; } /** * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. @@ -84317,12 +86966,12 @@ var ts; */ function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return ts.getFirstConstructorWithBody(node) !== undefined; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return true; } return false; @@ -84339,15 +86988,15 @@ var ts; */ function serializeTypeOfNode(node) { switch (node.kind) { - case 163 /* PropertyDeclaration */: - case 160 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 161 /* Parameter */: return serializeTypeNode(node.type); - case 168 /* SetAccessor */: - case 167 /* GetAccessor */: + case 169 /* SetAccessor */: + case 168 /* GetAccessor */: return serializeTypeNode(getAccessorTypeNode(node)); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 165 /* MethodDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 166 /* MethodDeclaration */: return factory.createIdentifier("Function"); default: return factory.createVoidZero(); @@ -84384,7 +87033,7 @@ var ts; return factory.createArrayLiteralExpression(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 167 /* GetAccessor */) { + if (container && node.kind === 168 /* GetAccessor */) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -84433,27 +87082,27 @@ var ts; case 150 /* UndefinedKeyword */: case 141 /* NeverKeyword */: return factory.createVoidZero(); - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return serializeTypeNode(node.type); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return factory.createIdentifier("Function"); - case 178 /* ArrayType */: - case 179 /* TupleType */: + case 179 /* ArrayType */: + case 180 /* TupleType */: return factory.createIdentifier("Array"); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: case 131 /* BooleanKeyword */: return factory.createIdentifier("Boolean"); case 147 /* StringKeyword */: return factory.createIdentifier("String"); case 145 /* ObjectKeyword */: return factory.createIdentifier("Object"); - case 191 /* LiteralType */: + case 192 /* LiteralType */: switch (node.literal.kind) { case 10 /* StringLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: return factory.createIdentifier("String"); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: case 8 /* NumericLiteral */: return factory.createIdentifier("Number"); case 9 /* BigIntLiteral */: @@ -84474,37 +87123,37 @@ var ts; return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : factory.createIdentifier("Symbol"); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return serializeTypeReferenceNode(node); - case 183 /* IntersectionType */: - case 182 /* UnionType */: + case 184 /* IntersectionType */: + case 183 /* UnionType */: return serializeTypeList(node.types); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return serializeTypeList([node.trueType, node.falseType]); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: if (node.operator === 142 /* ReadonlyKeyword */) { return serializeTypeNode(node.type); } break; - case 176 /* TypeQuery */: - case 189 /* IndexedAccessType */: - case 190 /* MappedType */: - case 177 /* TypeLiteral */: + case 177 /* TypeQuery */: + case 190 /* IndexedAccessType */: + case 191 /* MappedType */: + case 178 /* TypeLiteral */: case 128 /* AnyKeyword */: case 152 /* UnknownKeyword */: - case 187 /* ThisType */: - case 195 /* ImportType */: + case 188 /* ThisType */: + case 196 /* ImportType */: break; // handle JSDoc types from an invalid parse - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: - case 308 /* JSDocFunctionType */: - case 309 /* JSDocVariadicType */: - case 310 /* JSDocNamepathType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: + case 309 /* JSDocFunctionType */: + case 310 /* JSDocVariadicType */: + case 311 /* JSDocNamepathType */: break; - case 305 /* JSDocNullableType */: - case 306 /* JSDocNonNullableType */: - case 307 /* JSDocOptionalType */: + case 306 /* JSDocNullableType */: + case 307 /* JSDocNonNullableType */: + case 308 /* JSDocOptionalType */: return serializeTypeNode(node.type); default: return ts.Debug.failBadSyntaxKind(node); @@ -84517,13 +87166,13 @@ var ts; var serializedUnion; for (var _i = 0, types_24 = types; _i < types_24.length; _i++) { var typeNode = types_24[_i]; - while (typeNode.kind === 186 /* ParenthesizedType */) { + while (typeNode.kind === 187 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } if (typeNode.kind === 141 /* NeverKeyword */) { continue; // Always elide `never` from the union/intersection if possible } - if (!strictNullChecks && (typeNode.kind === 191 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { + if (!strictNullChecks && (typeNode.kind === 192 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } var serializedIndividual = serializeTypeNode(typeNode); @@ -84633,7 +87282,7 @@ var ts; name.original = undefined; ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node. return name; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return serializeQualifiedNameAsExpression(node); } } @@ -85021,8 +87670,7 @@ var ts; */ function shouldEmitEnumDeclaration(node) { return !ts.isEnumConst(node) - || compilerOptions.preserveConstEnums - || compilerOptions.isolatedModules; + || ts.shouldPreserveConstEnums(compilerOptions); } /** * Visits an enum declaration. @@ -85156,7 +87804,7 @@ var ts; // If we can't find a parse tree node, assume the node is instantiated. return true; } - return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions)); } /** * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` @@ -85207,12 +87855,12 @@ var ts; // enums in any other scope are emitted as a `let` declaration. var statement = factory.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.createVariableDeclarationList([ factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ], currentLexicalScope.kind === 297 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ], currentLexicalScope.kind === 298 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { // Adjust the source map emit to match the old emitter. - if (node.kind === 255 /* EnumDeclaration */) { + if (node.kind === 256 /* EnumDeclaration */) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -85337,7 +87985,7 @@ var ts; var statementsLocation; var blockLocation; if (node.body) { - if (node.body.kind === 257 /* ModuleBlock */) { + if (node.body.kind === 258 /* ModuleBlock */) { saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = node.body.statements; blockLocation = node.body; @@ -85384,13 +88032,13 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (!node.body || node.body.kind !== 257 /* ModuleBlock */) { + if (!node.body || node.body.kind !== 258 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 256 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 257 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -85440,7 +88088,7 @@ var ts; * @param node The named import bindings node. */ function visitNamedImportBindings(node) { - if (node.kind === 263 /* NamespaceImport */) { + if (node.kind === 264 /* NamespaceImport */) { // Elide a namespace import if it is not referenced. return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } @@ -85693,16 +88341,16 @@ var ts; // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to // substitute the names of exported members of a namespace. context.enableSubstitution(78 /* Identifier */); - context.enableSubstitution(289 /* ShorthandPropertyAssignment */); + context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // We need to be notified when entering and exiting namespaces. - context.enableEmitNotification(256 /* ModuleDeclaration */); + context.enableEmitNotification(257 /* ModuleDeclaration */); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 256 /* ModuleDeclaration */; + return ts.getOriginalNode(node).kind === 257 /* ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 255 /* EnumDeclaration */; + return ts.getOriginalNode(node).kind === 256 /* EnumDeclaration */; } /** * Hook for node emit. @@ -85763,9 +88411,9 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return substituteExpressionIdentifier(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return substituteElementAccessExpression(node); } return node; @@ -85787,10 +88435,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_1 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_1, node); - ts.setCommentRange(clone_1, node); - return clone_1; + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -85803,9 +88451,9 @@ var ts; // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container && container.kind !== 297 /* SourceFile */) { - var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 256 /* ModuleDeclaration */) || - (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 255 /* EnumDeclaration */); + if (container && container.kind !== 298 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 257 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 256 /* EnumDeclaration */); if (substitute) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(container), node), /*location*/ node); @@ -85857,10 +88505,12 @@ var ts; */ ClassPropertySubstitutionFlags[ClassPropertySubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; })(ClassPropertySubstitutionFlags || (ClassPropertySubstitutionFlags = {})); - var PrivateIdentifierPlacement; - (function (PrivateIdentifierPlacement) { - PrivateIdentifierPlacement[PrivateIdentifierPlacement["InstanceField"] = 0] = "InstanceField"; - })(PrivateIdentifierPlacement || (PrivateIdentifierPlacement = {})); + var PrivateIdentifierKind; + (function (PrivateIdentifierKind) { + PrivateIdentifierKind["Field"] = "f"; + PrivateIdentifierKind["Method"] = "m"; + PrivateIdentifierKind["Accessor"] = "a"; + })(PrivateIdentifierKind = ts.PrivateIdentifierKind || (ts.PrivateIdentifierKind = {})); /** * Transforms ECMAScript Class Syntax. * TypeScript parameter property syntax is transformed in the TypeScript transformer. @@ -85869,11 +88519,12 @@ var ts; * When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty. */ function transformClassFields(context) { - var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment; + var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, addBlockScopedVariable = context.addBlockScopedVariable; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var shouldTransformPrivateFields = languageVersion < 99 /* ESNext */; + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); + var shouldTransformPrivateElements = languageVersion < 99 /* ESNext */; var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; var enabledSubstitutions; @@ -85894,7 +88545,7 @@ var ts; function transformSourceFile(node) { var options = context.getCompilerOptions(); if (node.isDeclarationFile - || options.useDefineForClassFields && options.target === 99 /* ESNext */) { + || useDefineForClassFields && options.target === 99 /* ESNext */) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -85902,41 +88553,41 @@ var ts; return visited; } function visitor(node) { - if (!(node.transformFlags & 4194304 /* ContainsClassFields */)) + if (!(node.transformFlags & 8388608 /* ContainsClassFields */)) return node; switch (node.kind) { - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: return visitClassLike(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return visitPropertyDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return visitPropertyAccessExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return visitPrefixUnaryExpression(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return visitPostfixUnaryExpression(node, /*valueIsDiscarded*/ false); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node); case 79 /* PrivateIdentifier */: return visitPrivateIdentifier(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitExpressionStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); } return ts.visitEachChild(node, visitor, context); } function visitorDestructuringTarget(node) { switch (node.kind) { - case 200 /* ObjectLiteralExpression */: - case 199 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitAssignmentPattern(node); default: return visitor(node); @@ -85947,7 +88598,7 @@ var ts; * Replace it with an empty identifier to indicate a problem with the code. */ function visitPrivateIdentifier(node) { - if (!shouldTransformPrivateFields) { + if (!shouldTransformPrivateElements) { return node; } return ts.setOriginalNode(factory.createIdentifier(""), node); @@ -85959,20 +88610,19 @@ var ts; */ function classElementVisitor(node) { switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: // Constructors for classes using class fields are transformed in // `visitClassDeclaration` or `visitClassExpression`. return undefined; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: - // Visit the name of the member (if it's a computed property name). - return ts.visitEachChild(node, classElementVisitor, context); - case 163 /* PropertyDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + return visitMethodOrAccessorDeclaration(node); + case 164 /* PropertyDeclaration */: return visitPropertyDeclaration(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: return node; default: return visitor(node); @@ -85997,44 +88647,96 @@ var ts; } return node; } + function visitMethodOrAccessorDeclaration(node) { + ts.Debug.assert(!ts.some(node.decorators)); + if (!shouldTransformPrivateElements || !ts.isPrivateIdentifier(node.name)) { + return ts.visitEachChild(node, classElementVisitor, context); + } + // leave invalid code untransformed + var info = accessPrivateIdentifier(node.name); + ts.Debug.assert(info, "Undeclared private name for property declaration."); + if (!info.isValid) { + return node; + } + var functionName = getHoistedFunctionName(node); + if (functionName) { + getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return !ts.isStaticModifier(m); }), node.asteriskToken, functionName, + /* typeParameters */ undefined, ts.visitParameterList(node.parameters, classElementVisitor, context), + /* type */ undefined, ts.visitFunctionBody(node.body, classElementVisitor, context)))); + } + // remove method declaration from class + return undefined; + } + function getHoistedFunctionName(node) { + ts.Debug.assert(ts.isPrivateIdentifier(node.name)); + var info = accessPrivateIdentifier(node.name); + ts.Debug.assert(info, "Undeclared private name for property declaration."); + if (info.kind === "m" /* Method */) { + return info.methodName; + } + if (info.kind === "a" /* Accessor */) { + if (ts.isGetAccessor(node)) { + return info.getterName; + } + if (ts.isSetAccessor(node)) { + return info.setterName; + } + } + } function visitPropertyDeclaration(node) { ts.Debug.assert(!ts.some(node.decorators)); - if (!shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) { - // Initializer is elided as the field is initialized in transformConstructor. - return factory.updatePropertyDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, - /*questionOrExclamationToken*/ undefined, - /*type*/ undefined, - /*initializer*/ undefined); + if (ts.isPrivateIdentifier(node.name)) { + if (!shouldTransformPrivateElements) { + // Initializer is elided as the field is initialized in transformConstructor. + return factory.updatePropertyDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined); + } + // leave invalid code untransformed + var info = accessPrivateIdentifier(node.name); + ts.Debug.assert(info, "Undeclared private name for property declaration."); + if (!info.isValid) { + return node; + } } // Create a temporary variable to store a computed property name (if necessary). // If it's not inlineable, then we emit an expression after the class which assigns // the property name to the temporary variable. - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { getPendingExpressions().push(expr); } return undefined; } function createPrivateIdentifierAccess(info, receiver) { - receiver = ts.visitNode(receiver, visitor, ts.isExpression); - switch (info.placement) { - case 0 /* InstanceField */: - return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(ts.nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver), info.weakMapName); - default: return ts.Debug.fail("Unexpected private identifier placement"); + return createPrivateIdentifierAccessHelper(info, ts.visitNode(receiver, visitor, ts.isExpression)); + } + function createPrivateIdentifierAccessHelper(info, receiver) { + ts.setCommentRange(receiver, ts.moveRangePos(receiver, -1)); + switch (info.kind) { + case "a" /* Accessor */: + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.getterName); + case "m" /* Method */: + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.methodName); + case "f" /* Field */: + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.variableName); + default: + ts.Debug.assertNever(info, "Unknown private element type"); } } function visitPropertyAccessExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifier(node.name)) { var privateIdentifierInfo = accessPrivateIdentifier(node.name); if (privateIdentifierInfo) { - return ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node); + return ts.setTextRange(ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node), node); } } return ts.visitEachChild(node, visitor, context); } function visitPrefixUnaryExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { var operator = node.operator === 45 /* PlusPlusToken */ ? 39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ? 40 /* MinusToken */ : undefined; @@ -86049,7 +88751,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitPostfixUnaryExpression(node, valueIsDiscarded) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { var operator = node.operator === 45 /* PlusPlusToken */ ? 39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ? 40 /* MinusToken */ : undefined; @@ -86070,7 +88772,7 @@ var ts; } function visitForStatement(node) { if (node.incrementor && ts.isPostfixUnaryExpression(node.incrementor)) { - return factory.updateForStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), visitPostfixUnaryExpression(node.incrementor, /*valueIsDiscarded*/ true), ts.visitNode(node.statement, visitor, ts.isStatement)); + return factory.updateForStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), visitPostfixUnaryExpression(node.incrementor, /*valueIsDiscarded*/ true), ts.visitIterationBody(node.statement, visitor, context)); } return ts.visitEachChild(node, visitor, context); } @@ -86090,16 +88792,21 @@ var ts; return { readExpression: readExpression, initializeExpression: initializeExpression }; } function visitCallExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { // Transform call expressions of private names to properly bind the `this` parameter. var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; + if (ts.isCallChain(node)) { + return factory.updateCallChain(node, factory.createPropertyAccessChain(ts.visitNode(target, visitor), node.questionDotToken, "call"), + /*questionDotToken*/ undefined, + /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); + } return factory.updateCallExpression(node, factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "call"), /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); } return ts.visitEachChild(node, visitor, context); } function visitTaggedTemplateExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) { // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access. var _a = factory.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; return factory.updateTaggedTemplateExpression(node, factory.createCallExpression(factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "bind"), @@ -86109,7 +88816,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitBinaryExpression(node) { - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { if (ts.isDestructuringAssignment(node)) { var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; @@ -86123,29 +88830,31 @@ var ts; if (ts.isAssignmentExpression(node) && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) { var info = accessPrivateIdentifier(node.left.name); if (info) { - return ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node); + return ts.setTextRange(ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node), node); } } } return ts.visitEachChild(node, visitor, context); } function createPrivateIdentifierAssignment(info, receiver, right, operator) { - switch (info.placement) { - case 0 /* InstanceField */: { - return createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator); - } - default: return ts.Debug.fail("Unexpected private identifier placement"); - } - } - function createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator) { receiver = ts.visitNode(receiver, visitor, ts.isExpression); right = ts.visitNode(right, visitor, ts.isExpression); if (ts.isCompoundAssignment(operator)) { var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression; - return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(initializeExpression || readExpression, info.weakMapName, factory.createBinaryExpression(context.getEmitHelperFactory().createClassPrivateFieldGetHelper(readExpression, info.weakMapName), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right)); - } - else { - return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.weakMapName, right); + receiver = initializeExpression || readExpression; + right = factory.createBinaryExpression(createPrivateIdentifierAccessHelper(info, readExpression), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right); + } + ts.setCommentRange(receiver, ts.moveRangePos(receiver, -1)); + switch (info.kind) { + case "a" /* Accessor */: + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, info.setterName); + case "m" /* Method */: + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, + /* f */ undefined); + case "f" /* Field */: + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, info.variableName); + default: + ts.Debug.assertNever(info, "Unknown private element type"); } } /** @@ -86154,25 +88863,43 @@ var ts; function visitClassLike(node) { var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { startPrivateIdentifierEnvironment(); + var name = ts.getNameOfDeclaration(node); + if (name && ts.isIdentifier(name)) { + getPrivateIdentifierEnvironment().className = ts.idText(name); + } + var privateInstanceMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); + if (ts.some(privateInstanceMethodsAndAccessors)) { + getPrivateIdentifierEnvironment().weakSetName = createHoistedVariableForClass("instances", privateInstanceMethodsAndAccessors[0].name); + } } var result = ts.isClassDeclaration(node) ? visitClassDeclaration(node) : visitClassExpression(node); - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { endPrivateIdentifierEnvironment(); } pendingExpressions = savedPendingExpressions; return result; } function doesClassElementNeedTransform(node) { - return ts.isPropertyDeclaration(node) || (shouldTransformPrivateFields && node.name && ts.isPrivateIdentifier(node.name)); + return ts.isPropertyDeclaration(node) || (shouldTransformPrivateElements && node.name && ts.isPrivateIdentifier(node.name)); + } + function getPrivateInstanceMethodsAndAccessors(node) { + return ts.filter(node.members, ts.isNonStaticMethodOrAccessorWithPrivateName); } function visitClassDeclaration(node) { if (!ts.forEach(node.members, doesClassElementNeedTransform)) { return ts.visitEachChild(node, visitor, context); } + var staticProperties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ true); + var pendingPrivateStateAssignment; + if (shouldTransformPrivateElements && ts.some(node.members, function (m) { return ts.hasStaticModifier(m) && !!m.name && ts.isPrivateIdentifier(m.name); })) { + var temp = factory.createTempVariable(hoistVariableDeclaration, /* reservedInNestedScopes */ true); + getPrivateIdentifierEnvironment().classConstructor = factory.cloneNode(temp); + pendingPrivateStateAssignment = factory.createAssignment(temp, factory.getInternalName(node)); + } var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */); var statements = [ @@ -86180,6 +88907,9 @@ var ts; /*decorators*/ undefined, node.modifiers, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)) ]; + if (pendingPrivateStateAssignment) { + getPendingExpressions().unshift(pendingPrivateStateAssignment); + } // Write any pending expressions from elided or moved computed property names if (ts.some(pendingExpressions)) { statements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))); @@ -86189,7 +88919,6 @@ var ts; // From ES6 specification: // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. - var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); if (ts.some(staticProperties)) { addPropertyStatements(statements, staticProperties, factory.getInternalName(node)); } @@ -86207,12 +88936,25 @@ var ts; // class declaration transformation. The VariableStatement visitor will insert // these statements after the class expression variable statement. var isDecoratedClassDeclaration = ts.isClassDeclaration(ts.getOriginalNode(node)); - var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); + var staticProperties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ true); var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */); + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; + var temp; + function createClassTempVar() { + var classCheckFlags = resolver.getNodeCheckFlags(node); + var isClassWithConstructorReference = classCheckFlags & 16777216 /* ClassWithConstructorReference */; + var requiresBlockScopedVar = classCheckFlags & 524288 /* BlockScopedBindingInLoop */; + return factory.createTempVariable(requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, !!isClassWithConstructorReference); + } + if (shouldTransformPrivateElements && ts.some(node.members, function (m) { return ts.hasStaticModifier(m) && !!m.name && ts.isPrivateIdentifier(m.name); })) { + temp = createClassTempVar(); + getPrivateIdentifierEnvironment().classConstructor = factory.cloneNode(temp); + } var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)); - if (ts.some(staticProperties) || ts.some(pendingExpressions)) { + var hasTransformableStatics = ts.some(staticProperties, function (p) { return !!p.initializer || (shouldTransformPrivateElements && ts.isPrivateIdentifier(p.name)); }); + if (hasTransformableStatics || ts.some(pendingExpressions)) { if (isDecoratedClassDeclaration) { ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration."); // Write any pending expressions from elided or moved computed property names @@ -86222,12 +88964,14 @@ var ts; if (pendingStatements && ts.some(staticProperties)) { addPropertyStatements(pendingStatements, staticProperties, factory.getInternalName(node)); } + if (temp) { + return factory.inlineExpressions([factory.createAssignment(temp, classExpression), temp]); + } return classExpression; } else { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; - var temp = factory.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + temp || (temp = createClassTempVar()); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); @@ -86249,14 +88993,17 @@ var ts; return classExpression; } function transformClassMembers(node, isDerivedClass) { - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { // Declare private names. for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (ts.isPrivateIdentifierPropertyDeclaration(member)) { - addPrivateIdentifierToEnvironment(member.name); + if (ts.isPrivateIdentifierClassElementDeclaration(member)) { + addPrivateIdentifierToEnvironment(member); } } + if (ts.some(getPrivateInstanceMethodsAndAccessors(node))) { + createBrandCheckWeakSetForPrivateMethods(); + } } var members = []; var constructor = transformConstructor(node, isDerivedClass); @@ -86266,21 +89013,27 @@ var ts; ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members); } - function isPropertyDeclarationThatRequiresConstructorStatement(member) { - if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* Abstract */)) { + function createBrandCheckWeakSetForPrivateMethods() { + var weakSetName = getPrivateIdentifierEnvironment().weakSetName; + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + getPendingExpressions().push(factory.createAssignment(weakSetName, factory.createNewExpression(factory.createIdentifier("WeakSet"), + /*typeArguments*/ undefined, []))); + } + function isClassElementThatRequiresConstructorStatement(member) { + if (ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* Abstract */)) { return false; } - if (context.getCompilerOptions().useDefineForClassFields) { + if (useDefineForClassFields) { // If we are using define semantics and targeting ESNext or higher, // then we don't need to transform any class properties. return languageVersion < 99 /* ESNext */; } - return ts.isInitializedProperty(member) || shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyDeclaration(member); + return ts.isInitializedProperty(member) || shouldTransformPrivateElements && ts.isPrivateIdentifierClassElementDeclaration(member); } function transformConstructor(node, isDerivedClass) { var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration); - var properties = node.members.filter(isPropertyDeclarationThatRequiresConstructorStatement); - if (!ts.some(properties)) { + var elements = node.members.filter(isClassElementThatRequiresConstructorStatement); + if (!ts.some(elements)) { return constructor; } var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context); @@ -86293,13 +89046,14 @@ var ts; /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { - var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false); if (!useDefineForClassFields) { properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); }); } + var privateMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); + var needsConstructorBody = ts.some(properties) || ts.some(privateMethodsAndAccessors); // Only generate synthetic constructor when there are property initializers to move. - if (!constructor && !ts.some(properties)) { + if (!constructor && !needsConstructorBody) { return ts.visitFunctionBody(/*node*/ undefined, visitor, context); } resumeLexicalEnvironment(); @@ -86338,7 +89092,10 @@ var ts; indexOfFirstStatement = afterParameterProperties; } } - addPropertyStatements(statements, properties, factory.createThis()); + var receiver = factory.createThis(); + // private methods can be called in property initializers, they should execute first. + addMethodStatements(statements, privateMethodsAndAccessors, receiver); + addPropertyStatements(statements, properties, receiver); // Add existing statements, skipping the initial super call. if (constructor) { ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); @@ -86400,27 +89157,30 @@ var ts; function transformProperty(property, receiver) { var _a; // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) - var emitAssignment = !context.getCompilerOptions().useDefineForClassFields; + var emitAssignment = !useDefineForClassFields; var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression) ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name)) : property.name; - if (shouldTransformPrivateFields && ts.isPrivateIdentifier(propertyName)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifier(propertyName)) { var privateIdentifierInfo = accessPrivateIdentifier(propertyName); if (privateIdentifierInfo) { - switch (privateIdentifierInfo.placement) { - case 0 /* InstanceField */: { - return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.weakMapName); + if (privateIdentifierInfo.kind === "f" /* Field */) { + if (!privateIdentifierInfo.isStatic) { + return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.brandCheckIdentifier); + } + else { + return createPrivateStaticFieldInitializer(privateIdentifierInfo.variableName, ts.visitNode(property.initializer, visitor, ts.isExpression)); } } + else { + return undefined; + } } else { ts.Debug.fail("Undeclared private name for property declaration."); } } - if (ts.isPrivateIdentifier(propertyName) && !property.initializer) { - return undefined; - } - if (ts.isPrivateIdentifier(propertyName) && !property.initializer) { + if ((ts.isPrivateIdentifier(propertyName) || ts.hasStaticModifier(property)) && !property.initializer) { return undefined; } var propertyOriginalNode = ts.getOriginalNode(property); @@ -86452,6 +89212,21 @@ var ts; classAliases = []; } } + /** + * Generates brand-check initializer for private methods. + * + * @param statements Statement list that should be used to append new statements. + * @param methods An array of method declarations. + * @param receiver The receiver on which each method should be assigned. + */ + function addMethodStatements(statements, methods, receiver) { + if (!shouldTransformPrivateElements || !ts.some(methods)) { + return; + } + var weakSetName = getPrivateIdentifierEnvironment().weakSetName; + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + statements.push(factory.createExpressionStatement(createPrivateInstanceMethodInitializer(receiver, weakSetName))); + } /** * Hooks node substitutions. * @@ -86487,10 +89262,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_2 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_2, node); - ts.setCommentRange(clone_2, node); - return clone_2; + var clone_3 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_3, node); + ts.setCommentRange(clone_3, node); + return clone_3; } } } @@ -86510,7 +89285,12 @@ var ts; var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left); if (!alreadyTransformed && !inlinable && shouldHoist) { var generatedName = factory.getGeneratedNameForNode(name); - hoistVariableDeclaration(generatedName); + if (resolver.getNodeCheckFlags(name) & 524288 /* BlockScopedBindingInLoop */) { + addBlockScopedVariable(generatedName); + } + else { + hoistVariableDeclaration(generatedName); + } return factory.createAssignment(generatedName, expression); } return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression; @@ -86524,22 +89304,164 @@ var ts; currentPrivateIdentifierEnvironment = privateIdentifierEnvironmentStack.pop(); } function getPrivateIdentifierEnvironment() { - return currentPrivateIdentifierEnvironment || (currentPrivateIdentifierEnvironment = new ts.Map()); + if (!currentPrivateIdentifierEnvironment) { + currentPrivateIdentifierEnvironment = { + className: "", + identifiers: new ts.Map() + }; + } + return currentPrivateIdentifierEnvironment; } function getPendingExpressions() { return pendingExpressions || (pendingExpressions = []); } - function addPrivateIdentifierToEnvironment(name) { - var text = ts.getTextOfPropertyName(name); - var weakMapName = factory.createUniqueName("_" + text.substring(1), 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */); - hoistVariableDeclaration(weakMapName); - getPrivateIdentifierEnvironment().set(name.escapedText, { placement: 0 /* InstanceField */, weakMapName: weakMapName }); - getPendingExpressions().push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), - /*typeArguments*/ undefined, []))); + function addPrivateIdentifierToEnvironment(node) { + var _a; + var text = ts.getTextOfPropertyName(node.name); + var env = getPrivateIdentifierEnvironment(); + var weakSetName = env.weakSetName, classConstructor = env.classConstructor; + var assignmentExpressions = []; + var privateName = node.name.escapedText; + var previousInfo = env.identifiers.get(privateName); + var isValid = !isReservedPrivateName(node.name) && previousInfo === undefined; + if (ts.hasStaticModifier(node)) { + ts.Debug.assert(classConstructor, "weakSetName should be set in private identifier environment"); + if (ts.isPropertyDeclaration(node)) { + var variableName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: "f" /* Field */, + variableName: variableName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + else if (ts.isMethodDeclaration(node)) { + var functionName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: "m" /* Method */, + methodName: functionName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + else if (ts.isGetAccessorDeclaration(node)) { + var getterName = createHoistedVariableForPrivateName(text + "_get", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic && !previousInfo.getterName) { + previousInfo.getterName = getterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: getterName, + setterName: undefined, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + } + else if (ts.isSetAccessorDeclaration(node)) { + var setterName = createHoistedVariableForPrivateName(text + "_set", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic && !previousInfo.setterName) { + previousInfo.setterName = setterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: undefined, + setterName: setterName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + } + else { + ts.Debug.assertNever(node, "Unknown class element type."); + } + } + else if (ts.isPropertyDeclaration(node)) { + var weakMapName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: "f" /* Field */, + brandCheckIdentifier: weakMapName, + isStatic: false, + variableName: undefined, + isValid: isValid, + }); + assignmentExpressions.push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), + /*typeArguments*/ undefined, []))); + } + else if (ts.isMethodDeclaration(node)) { + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + env.identifiers.set(privateName, { + kind: "m" /* Method */, + methodName: createHoistedVariableForPrivateName(text, node), + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + else if (ts.isAccessor(node)) { + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + if (ts.isGetAccessor(node)) { + var getterName = createHoistedVariableForPrivateName(text + "_get", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && !previousInfo.isStatic && !previousInfo.getterName) { + previousInfo.getterName = getterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: getterName, + setterName: undefined, + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + } + else { + var setterName = createHoistedVariableForPrivateName(text + "_set", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && !previousInfo.isStatic && !previousInfo.setterName) { + previousInfo.setterName = setterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: undefined, + setterName: setterName, + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + } + } + else { + ts.Debug.assertNever(node, "Unknown class element type."); + } + (_a = getPendingExpressions()).push.apply(_a, assignmentExpressions); + } + function createHoistedVariableForClass(name, node) { + var className = getPrivateIdentifierEnvironment().className; + var prefix = className ? "_" + className : ""; + var identifier = factory.createUniqueName(prefix + "_" + name, 16 /* Optimistic */); + if (resolver.getNodeCheckFlags(node) & 524288 /* BlockScopedBindingInLoop */) { + addBlockScopedVariable(identifier); + } + else { + hoistVariableDeclaration(identifier); + } + return identifier; + } + function createHoistedVariableForPrivateName(privateName, node) { + return createHoistedVariableForClass(privateName.substring(1), node.name); } function accessPrivateIdentifier(name) { if (currentPrivateIdentifierEnvironment) { - var info = currentPrivateIdentifierEnvironment.get(name.escapedText); + var info = currentPrivateIdentifierEnvironment.identifiers.get(name.escapedText); if (info) { return info; } @@ -86549,7 +89471,7 @@ var ts; if (!env) { continue; } - var info = env.get(name.escapedText); + var info = env.identifiers.get(name.escapedText); if (info) { return info; } @@ -86635,10 +89557,22 @@ var ts; } } ts.transformClassFields = transformClassFields; + function createPrivateStaticFieldInitializer(variableName, initializer) { + return ts.factory.createAssignment(variableName, ts.factory.createObjectLiteralExpression([ + ts.factory.createPropertyAssignment("value", initializer || ts.factory.createVoidZero()) + ])); + } function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) { return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakMapName, "set"), /*typeArguments*/ undefined, [receiver, initializer || ts.factory.createVoidZero()]); } + function createPrivateInstanceMethodInitializer(receiver, weakSetName) { + return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakSetName, "add"), + /*typeArguments*/ undefined, [receiver]); + } + function isReservedPrivateName(node) { + return node.escapedText === "#constructor"; + } })(ts || (ts = {})); /*@internal*/ var ts; @@ -86721,38 +89655,38 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 64 /* ContainsES2017 */) === 0) { + if ((node.transformFlags & 128 /* ContainsES2017 */) === 0) { return node; } switch (node.kind) { case 129 /* AsyncKeyword */: // ES2017 async modifier should be elided for targets < ES2017 return undefined; - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return visitAwaitExpression(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105 /* SuperKeyword */) { capturedSuperProperties.add(node.name.escapedText); } return ts.visitEachChild(node, visitor, context); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: if (capturedSuperProperties && node.expression.kind === 105 /* SuperKeyword */) { hasSuperElementAccess = true; } return ts.visitEachChild(node, visitor, context); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 166 /* Constructor */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 167 /* Constructor */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node); default: return ts.visitEachChild(node, visitor, context); @@ -86761,27 +89695,27 @@ var ts; function asyncBodyVisitor(node) { if (ts.isNodeWithPossibleHoistedDeclaration(node)) { switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatementInAsyncBody(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatementInAsyncBody(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatementInAsyncBody(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatementInAsyncBody(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClauseInAsyncBody(node); - case 230 /* Block */: - case 244 /* SwitchStatement */: - case 258 /* CaseBlock */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: - case 247 /* TryStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 234 /* IfStatement */: - case 243 /* WithStatement */: - case 245 /* LabeledStatement */: + case 231 /* Block */: + case 245 /* SwitchStatement */: + case 259 /* CaseBlock */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 248 /* TryStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 235 /* IfStatement */: + case 244 /* WithStatement */: + case 246 /* LabeledStatement */: return ts.visitEachChild(node, asyncBodyVisitor, context); default: return ts.Debug.assertNever(node, "Unhandled node."); @@ -86823,18 +89757,18 @@ var ts; function visitForInStatementInAsyncBody(node) { return factory.updateForInStatement(node, isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) - : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock)); + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context)); } function visitForOfStatementInAsyncBody(node) { return factory.updateForOfStatement(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) - : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock)); + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context)); } function visitForStatementInAsyncBody(node) { var initializer = node.initializer; // TODO: GH#18217 return factory.updateForStatement(node, isVariableDeclarationListWithCollidingName(initializer) ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false) - : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock)); + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context)); } /** * Visits an AwaitExpression node. @@ -86986,7 +89920,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 209 /* ArrowFunction */; + var isArrowFunction = node.kind === 210 /* ArrowFunction */; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current @@ -87077,17 +90011,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(203 /* CallExpression */); - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(202 /* ElementAccessExpression */); + context.enableSubstitution(204 /* CallExpression */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(203 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(252 /* ClassDeclaration */); - context.enableEmitNotification(165 /* MethodDeclaration */); - context.enableEmitNotification(167 /* GetAccessor */); - context.enableEmitNotification(168 /* SetAccessor */); - context.enableEmitNotification(166 /* Constructor */); + context.enableEmitNotification(253 /* ClassDeclaration */); + context.enableEmitNotification(166 /* MethodDeclaration */); + context.enableEmitNotification(168 /* GetAccessor */); + context.enableEmitNotification(169 /* SetAccessor */); + context.enableEmitNotification(167 /* Constructor */); // We need to be notified when entering the generated accessor arrow functions. - context.enableEmitNotification(232 /* VariableStatement */); + context.enableEmitNotification(233 /* VariableStatement */); } } /** @@ -87135,11 +90069,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return substituteCallExpression(node); } return node; @@ -87171,11 +90105,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 252 /* ClassDeclaration */ - || kind === 166 /* Constructor */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 253 /* ClassDeclaration */ + || kind === 167 /* Constructor */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { @@ -87354,74 +90288,74 @@ var ts; * expression of an `ExpressionStatement`). */ function visitorWorker(node, expressionResultIsUnused) { - if ((node.transformFlags & 32 /* ContainsES2018 */) === 0) { + if ((node.transformFlags & 64 /* ContainsES2018 */) === 0) { return node; } switch (node.kind) { - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return visitAwaitExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitYieldExpression(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitReturnStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node, expressionResultIsUnused); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitCommaListExpression(node, expressionResultIsUnused); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 238 /* ForInStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 239 /* ForInStatement */: return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return visitVoidExpression(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */); - case 160 /* Parameter */: + case 161 /* Parameter */: return visitParameter(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitExpressionStatement(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, expressionResultIsUnused); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105 /* SuperKeyword */) { capturedSuperProperties.add(node.name.escapedText); } return ts.visitEachChild(node, visitor, context); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: if (capturedSuperProperties && node.expression.kind === 105 /* SuperKeyword */) { hasSuperElementAccess = true; } return ts.visitEachChild(node, visitor, context); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); default: return ts.visitEachChild(node, visitor, context); @@ -87457,7 +90391,7 @@ var ts; function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 239 /* ForOfStatement */ && statement.awaitModifier) { + if (statement.kind === 240 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } return factory.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, factory.liftToBlock), node); @@ -87469,7 +90403,7 @@ var ts; var objects = []; for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { var e = elements_4[_i]; - if (e.kind === 290 /* SpreadAssignment */) { + if (e.kind === 291 /* SpreadAssignment */) { if (chunkObject) { objects.push(factory.createObjectLiteralExpression(chunkObject)); chunkObject = undefined; @@ -87478,7 +90412,7 @@ var ts; objects.push(ts.visitNode(target, visitor, ts.isExpression)); } else { - chunkObject = ts.append(chunkObject, e.kind === 288 /* PropertyAssignment */ + chunkObject = ts.append(chunkObject, e.kind === 289 /* PropertyAssignment */ ? factory.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } @@ -87489,7 +90423,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign(__assign({a}, o), {b}); @@ -87512,7 +90446,7 @@ var ts; // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we // end up with `{ a: 1, b: 2, c: 3 }` var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 200 /* ObjectLiteralExpression */) { + if (objects.length && objects[0].kind !== 201 /* ObjectLiteralExpression */) { objects.unshift(factory.createObjectLiteralExpression()); } var expression = objects[0]; @@ -87562,7 +90496,7 @@ var ts; * expression of an `ExpressionStatement`). */ function visitBinaryExpression(node, expressionResultIsUnused) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !expressionResultIsUnused); } if (node.operatorToken.kind === 27 /* CommaToken */) { @@ -87593,7 +90527,7 @@ var ts; function visitCatchClause(node) { if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name) && - node.variableDeclaration.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + node.variableDeclaration.name.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { var name = factory.getGeneratedNameForNode(node.variableDeclaration.name); var updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name); var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */); @@ -87634,14 +90568,14 @@ var ts; } function visitVariableDeclarationWorker(node, exportedVariableStatement) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */, /*rval*/ undefined, exportedVariableStatement); } return ts.visitEachChild(node, visitor, context); } function visitForStatement(node) { - return factory.updateForStatement(node, ts.visitNode(node.initializer, visitorWithUnusedExpressionResult, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitorWithUnusedExpressionResult, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement)); + return factory.updateForStatement(node, ts.visitNode(node.initializer, visitorWithUnusedExpressionResult, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitorWithUnusedExpressionResult, ts.isExpression), ts.visitIterationBody(node.statement, visitor, context)); } function visitVoidExpression(node) { return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context); @@ -87653,7 +90587,7 @@ var ts; */ function visitForOfStatement(node, outermostLabeledStatement) { var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); - if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (node.initializer.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } var result = node.awaitModifier ? @@ -87691,7 +90625,7 @@ var ts; var bodyLocation; var statementsLocation; var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; - var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + var statement = ts.visitIterationBody(node.statement, visitor, context); if (ts.isBlock(statement)) { ts.addRange(statements, statement.statements); bodyLocation = statement; @@ -87753,7 +90687,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return factory.updateParameterDeclaration(node, @@ -87905,7 +90839,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 & 16384 /* ContainsObjectRestOrSpread */) { + if (parameter.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { var temp = factory.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -87925,17 +90859,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(203 /* CallExpression */); - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(202 /* ElementAccessExpression */); + context.enableSubstitution(204 /* CallExpression */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(203 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(252 /* ClassDeclaration */); - context.enableEmitNotification(165 /* MethodDeclaration */); - context.enableEmitNotification(167 /* GetAccessor */); - context.enableEmitNotification(168 /* SetAccessor */); - context.enableEmitNotification(166 /* Constructor */); + context.enableEmitNotification(253 /* ClassDeclaration */); + context.enableEmitNotification(166 /* MethodDeclaration */); + context.enableEmitNotification(168 /* GetAccessor */); + context.enableEmitNotification(169 /* SetAccessor */); + context.enableEmitNotification(167 /* Constructor */); // We need to be notified when entering the generated accessor arrow functions. - context.enableEmitNotification(232 /* VariableStatement */); + context.enableEmitNotification(233 /* VariableStatement */); } } /** @@ -87983,11 +90917,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return substituteCallExpression(node); } return node; @@ -88019,11 +90953,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 252 /* ClassDeclaration */ - || kind === 166 /* Constructor */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 253 /* ClassDeclaration */ + || kind === 167 /* Constructor */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { @@ -88051,11 +90985,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 16 /* ContainsES2019 */) === 0) { + if ((node.transformFlags & 32 /* ContainsES2019 */) === 0) { return node; } switch (node.kind) { - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); @@ -88083,25 +91017,29 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 8 /* ContainsES2020 */) === 0) { + if ((node.transformFlags & 16 /* ContainsES2020 */) === 0) { return node; } switch (node.kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: - case 203 /* CallExpression */: - if (node.flags & 32 /* OptionalChain */) { + case 204 /* CallExpression */: { + var updated = visitNonOptionalCallExpression(node, /*captureThisArg*/ false); + ts.Debug.assertNotNode(updated, ts.isSyntheticReference); + return updated; + } + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + if (ts.isOptionalChain(node)) { var updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false); ts.Debug.assertNotNode(updated, ts.isSyntheticReference); return updated; } return ts.visitEachChild(node, visitor, context); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (node.operatorToken.kind === 60 /* QuestionQuestionToken */) { return transformNullishCoalescingExpression(node); } return ts.visitEachChild(node, visitor, context); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return visitDeleteExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -88143,7 +91081,7 @@ var ts; thisArg = expression; } } - expression = node.kind === 201 /* PropertyAccessExpression */ + expression = node.kind === 202 /* PropertyAccessExpression */ ? factory.updatePropertyAccessExpression(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)) : factory.updateElementAccessExpression(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); return thisArg ? factory.createSyntheticReferenceExpression(expression, thisArg) : expression; @@ -88153,14 +91091,23 @@ var ts; // If `node` is an optional chain, then it is the outermost chain of an optional expression. return visitOptionalExpression(node, captureThisArg, /*isDelete*/ false); } + if (ts.isParenthesizedExpression(node.expression) && ts.isOptionalChain(ts.skipParentheses(node.expression))) { + // capture thisArg for calls of parenthesized optional chains like `(foo?.bar)()` + var expression = visitNonOptionalParenthesizedExpression(node.expression, /*captureThisArg*/ true, /*isDelete*/ false); + var args = ts.visitNodes(node.arguments, visitor, ts.isExpression); + if (ts.isSyntheticReference(expression)) { + return ts.setTextRange(factory.createFunctionCallCall(expression.expression, expression.thisArg, args), node); + } + return factory.updateCallExpression(node, expression, /*typeArguments*/ undefined, args); + } return ts.visitEachChild(node, visitor, context); } function visitNonOptionalExpression(node, captureThisArg, isDelete) { switch (node.kind) { - case 207 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete); - case 203 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg); + case 208 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete); + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete); + case 204 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg); default: return ts.visitNode(node, visitor, ts.isExpression); } } @@ -88179,8 +91126,8 @@ var ts; for (var i = 0; i < chain.length; i++) { var segment = chain[i]; switch (segment.kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: if (i === chain.length - 1 && captureThisArg) { if (!ts.isSimpleCopiableExpression(rightExpression)) { thisArg = factory.createTempVariable(hoistVariableDeclaration); @@ -88190,11 +91137,11 @@ var ts; thisArg = rightExpression; } } - rightExpression = segment.kind === 201 /* PropertyAccessExpression */ + rightExpression = segment.kind === 202 /* PropertyAccessExpression */ ? factory.createPropertyAccessExpression(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)) : factory.createElementAccessExpression(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (i === 0 && leftThisArg) { rightExpression = factory.createFunctionCallCall(rightExpression, leftThisArg.kind === 105 /* SuperKeyword */ ? factory.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); } @@ -88237,7 +91184,7 @@ var ts; /*@internal*/ var ts; (function (ts) { - function transformESNext(context) { + function transformES2021(context) { var hoistVariableDeclaration = context.hoistVariableDeclaration, factory = context.factory; return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { @@ -88247,11 +91194,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 4 /* ContainsESNext */) === 0) { + if ((node.transformFlags & 8 /* ContainsES2021 */) === 0) { return node; } switch (node.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var binaryExpression = node; if (ts.isLogicalOrCoalescingAssignmentExpression(binaryExpression)) { return transformLogicalAssignment(binaryExpression); @@ -88287,6 +91234,29 @@ var ts; return factory.createBinaryExpression(left, nonAssignmentOperator, factory.createParenthesizedExpression(factory.createAssignment(assignmentTarget, right))); } } + ts.transformES2021 = transformES2021; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformESNext(context) { + return ts.chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if ((node.transformFlags & 4 /* ContainsESNext */) === 0) { + return node; + } + switch (node.kind) { + default: + return ts.visitEachChild(node, visitor, context); + } + } + } ts.transformESNext = transformESNext; })(ts || (ts = {})); /*@internal*/ @@ -88397,13 +91367,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 273 /* JsxElement */: + case 274 /* JsxElement */: return visitJsxElement(node, /*isChild*/ false); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ false); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -88413,13 +91383,13 @@ var ts; switch (node.kind) { case 11 /* JsxText */: return visitJsxText(node); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return visitJsxExpression(node); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return visitJsxElement(node, /*isChild*/ true); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ true); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ true); default: return ts.Debug.failBadSyntaxKind(node); @@ -88459,9 +91429,9 @@ var ts; function convertJsxChildrenToChildrenPropObject(children) { var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); if (ts.length(nonWhitespaceChildren) === 1) { - var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]); - return result_13 && factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", result_13) + var result_14 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result_14 && factory.createObjectLiteralExpression([ + factory.createPropertyAssignment("children", result_14) ]); } var result = ts.mapDefined(children, transformJsxChildToExpression); @@ -88537,21 +91507,29 @@ var ts; // When there are no attributes, React wants "null" } else { - // Map spans of JsxAttribute nodes into object literals and spans - // of JsxSpreadAttribute nodes into expressions. - var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread - ? ts.map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); - if (ts.isJsxSpreadAttribute(attrs[0])) { - // We must always emit at least one object literal before a spread - // argument.factory.createObjectLiteral - segments.unshift(factory.createObjectLiteralExpression()); + var target = compilerOptions.target; + if (target && target >= 5 /* ES2018 */) { + objectProperties = factory.createObjectLiteralExpression(ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { + return isSpread ? ts.map(attrs, transformJsxSpreadAttributeToSpreadAssignment) : ts.map(attrs, transformJsxAttributeToObjectLiteralElement); + }))); } - // Either emit one big object literal (no spread attribs), or - // a call to the __assign helper. - objectProperties = ts.singleOrUndefined(segments); - if (!objectProperties) { - objectProperties = emitHelpers().createAssignHelper(segments); + else { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. + var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument.factory.createObjectLiteral + segments.unshift(factory.createObjectLiteralExpression()); + } + // Either emit one big object literal (no spread attribs), or + // a call to the __assign helper. + objectProperties = ts.singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = emitHelpers().createAssignHelper(segments); + } } } var callee = currentFileState.importSpecifier === undefined @@ -88583,6 +91561,9 @@ var ts; } return element; } + function transformJsxSpreadAttributeToSpreadAssignment(node) { + return factory.createSpreadAssignment(ts.visitNode(node.expression, visitor, ts.isExpression)); + } function transformJsxSpreadAttributeToExpression(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } @@ -88602,7 +91583,7 @@ var ts; var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote); return ts.setTextRange(literal, node); } - else if (node.kind === 283 /* JsxExpression */) { + else if (node.kind === 284 /* JsxExpression */) { if (node.expression === undefined) { return factory.createTrue(); } @@ -88696,7 +91677,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 273 /* JsxElement */) { + if (node.kind === 274 /* JsxElement */) { return getTagName(node.openingElement); } else { @@ -88998,11 +91979,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 128 /* ContainsES2016 */) === 0) { + if ((node.transformFlags & 256 /* ContainsES2016 */) === 0) { return node; } switch (node.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -89215,11 +92196,11 @@ var ts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0 - && node.kind === 242 /* ReturnStatement */ + && node.kind === 243 /* ReturnStatement */ && !node.expression; } function isOrMayContainReturnCompletion(node) { - return node.transformFlags & 1048576 /* ContainsHoistedDeclarationOrCompletion */ + return node.transformFlags & 2097152 /* ContainsHoistedDeclarationOrCompletion */ && (ts.isReturnStatement(node) || ts.isIfStatement(node) || ts.isWithStatement(node) @@ -89234,7 +92215,7 @@ var ts; || ts.isBlock(node)); } function shouldVisitNode(node) { - return (node.transformFlags & 256 /* ContainsES2015 */) !== 0 + return (node.transformFlags & 512 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && isOrMayContainReturnCompletion(node)) || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) @@ -89256,65 +92237,65 @@ var ts; switch (node.kind) { case 123 /* StaticKeyword */: return undefined; // elide static keyword - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return visitClassDeclaration(node); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return visitClassExpression(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return visitParameter(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return visitArrowFunction(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return visitFunctionExpression(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitVariableDeclaration(node); case 78 /* Identifier */: return visitIdentifier(node); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return visitVariableDeclarationList(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitSwitchStatement(node); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return visitCaseBlock(node); - case 230 /* Block */: + case 231 /* Block */: return visitBlock(node, /*isFunctionBody*/ false); - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: return visitBreakOrContinueStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node, /*outermostLabeledStatement*/ undefined); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitExpressionStatement(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return visitShorthandPropertyAssignment(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return visitNewExpression(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, expressionResultIsUnused); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node, expressionResultIsUnused); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitCommaListExpression(node, expressionResultIsUnused); case 14 /* NoSubstitutionTemplateLiteral */: case 15 /* TemplateHead */: @@ -89325,30 +92306,30 @@ var ts; return visitStringLiteral(node); case 8 /* NumericLiteral */: return visitNumericLiteral(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return visitTemplateExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitYieldExpression(node); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return visitSpreadElement(node); case 105 /* SuperKeyword */: return visitSuperKeyword(/*isExpressionOfCall*/ false); case 107 /* ThisKeyword */: return visitThisKeyword(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return visitMetaProperty(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return visitAccessorDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitReturnStatement(node); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return visitVoidExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -89438,14 +92419,14 @@ var ts; // it is possible if either // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement - var jump = node.kind === 241 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var jump = node.kind === 242 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; var label = node.label; if (!label) { - if (node.kind === 241 /* BreakStatement */) { + if (node.kind === 242 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; } @@ -89456,7 +92437,7 @@ var ts; } } else { - if (node.kind === 241 /* BreakStatement */) { + if (node.kind === 242 /* BreakStatement */) { labelMarker = "break-" + label.escapedText; setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); } @@ -89768,7 +92749,7 @@ var ts; factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); if (isDerivedClass) { - if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 4096 /* ContainsLexicalThis */)) { + if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 8192 /* ContainsLexicalThis */)) { // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the // following representation: // @@ -89854,11 +92835,11 @@ var ts; */ function isSufficientlyCoveredByReturnStatements(statement) { // A return statement is considered covered. - if (statement.kind === 242 /* ReturnStatement */) { + if (statement.kind === 243 /* ReturnStatement */) { return true; } // An if-statement with two covered branches is covered. - else if (statement.kind === 234 /* IfStatement */) { + else if (statement.kind === 235 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && @@ -89866,7 +92847,7 @@ var ts; } } // A block is covered if it has a last statement which is covered. - else if (statement.kind === 230 /* Block */) { + else if (statement.kind === 231 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -90068,7 +93049,7 @@ var ts; * @param node A node. */ function insertCaptureThisForNodeIfNeeded(statements, node) { - if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 209 /* ArrowFunction */) { + if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 210 /* ArrowFunction */) { insertCaptureThisForNode(statements, node, factory.createThis()); return true; } @@ -90090,22 +93071,22 @@ var ts; if (hierarchyFacts & 16384 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return statements; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // Methods and accessors cannot be constructors, so 'new.target' will // always return 'undefined'. newTarget = factory.createVoidZero(); break; - case 166 /* Constructor */: + case 167 /* Constructor */: // Class constructors can only be called with `new`, so `this.constructor` // should be relatively safe to use. newTarget = factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), "constructor"); break; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: // Functions can be called or constructed, and may have a `this` due to // being a member or when calling an imported function via `other_1.f()`. newTarget = factory.createConditionalExpression(factory.createLogicalAnd(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), factory.createBinaryExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), 101 /* InstanceOfKeyword */, factory.getLocalName(node))), @@ -90140,20 +93121,20 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 166 /* Constructor */: + case 167 /* Constructor */: // Constructors are handled in visitClassExpression/visitClassDeclaration break; default: @@ -90182,7 +93163,7 @@ var ts; var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName); var e; - if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) { + if (!ts.isPrivateIdentifier(propertyName) && ts.getUseDefineForClassFields(context.getCompilerOptions())) { var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName; @@ -90274,7 +93255,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 4096 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { hierarchyFacts |= 32768 /* CapturedLexicalThis */; } var savedConvertedLoopState = convertedLoopState; @@ -90356,7 +93337,7 @@ var ts; : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */)) { + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 252 /* FunctionDeclaration */ || node.kind === 209 /* FunctionExpression */)) { name = factory.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */); @@ -90402,7 +93383,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 209 /* ArrowFunction */); + ts.Debug.assert(node.kind === 210 /* ArrowFunction */); // To align with the old emitter, we use a synthetic end position on the location // for the statement list we synthesize when we down-level an arrow function with // an expression function body. This prevents both comments and source maps from @@ -90563,7 +93544,7 @@ var ts; * @param node A VariableDeclarationList node. */ function visitVariableDeclarationList(node) { - if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 131072 /* ContainsBindingPattern */) { + if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 262144 /* ContainsBindingPattern */) { if (node.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } @@ -90576,7 +93557,7 @@ var ts; ts.setCommentRange(declarationList, node); // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. - if (node.transformFlags & 131072 /* ContainsBindingPattern */ + if (node.transformFlags & 262144 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -90588,8 +93569,8 @@ var ts; // 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]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var node = declarations_9[_i]; pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); end = Math.max(end, node.end); } @@ -90709,14 +93690,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return visitDoOrWhileStatement(node, outermostLabeledStatement); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node, outermostLabeledStatement); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node, outermostLabeledStatement); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -90900,9 +93881,9 @@ var ts; var numInitialProperties = -1, hasComputed = false; for (var i = 0; i < properties.length; i++) { var property = properties[i]; - if ((property.transformFlags & 262144 /* ContainsYield */ && + if ((property.transformFlags & 524288 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) - || (hasComputed = ts.Debug.checkDefined(property.name).kind === 158 /* ComputedPropertyName */)) { + || (hasComputed = ts.Debug.checkDefined(property.name).kind === 159 /* ComputedPropertyName */)) { numInitialProperties = i; break; } @@ -91005,24 +93986,24 @@ var ts; loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts); } else { - var clone_3 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); - loop = factory.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_4 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); + loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); } } else { - var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + loop = factory.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel); } statements.push(loop); return statements; } function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { switch (node.kind) { - case 237 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); - case 238 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); - case 239 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); - case 235 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); - case 236 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + case 238 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 239 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 240 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 236 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 237 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); } } @@ -91047,11 +94028,11 @@ var ts; function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: var initializer = node.initializer; - if (initializer && initializer.kind === 250 /* VariableDeclarationList */) { + if (initializer && initializer.kind === 251 /* VariableDeclarationList */) { loopInitializer = initializer; } break; @@ -91171,7 +94152,7 @@ var ts; */ function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = factory.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 262144 /* ContainsYield */) !== 0; + var containsYield = (node.initializer.transformFlags & 524288 /* ContainsYield */) !== 0; var emitFlags = 0 /* None */; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -91286,7 +94267,7 @@ var ts; var loopBody = factory.createBlock(statements, /*multiLine*/ true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 262144 /* ContainsYield */) !== 0; + var containsYield = (node.statement.transformFlags & 524288 /* ContainsYield */) !== 0; var emitFlags = 524288 /* ReuseTempVariableScope */; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -91459,20 +94440,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -91579,7 +94560,7 @@ var ts; var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (node.kind === 167 /* GetAccessor */) { + if (node.kind === 168 /* GetAccessor */) { updated = factory.updateGetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { @@ -91759,7 +94740,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 & 8192 /* ContainsRestOrSpread */ || + if (node.transformFlags & 16384 /* ContainsRestOrSpread */ || node.expression.kind === 105 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -91767,7 +94748,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 8192 /* ContainsRestOrSpread */) { + if (node.transformFlags & 16384 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -92085,13 +95066,13 @@ var ts; if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { enabledSubstitutions |= 1 /* CapturedThis */; context.enableSubstitution(107 /* ThisKeyword */); - context.enableEmitNotification(166 /* Constructor */); - context.enableEmitNotification(165 /* MethodDeclaration */); - context.enableEmitNotification(167 /* GetAccessor */); - context.enableEmitNotification(168 /* SetAccessor */); - context.enableEmitNotification(209 /* ArrowFunction */); - context.enableEmitNotification(208 /* FunctionExpression */); - context.enableEmitNotification(251 /* FunctionDeclaration */); + context.enableEmitNotification(167 /* Constructor */); + context.enableEmitNotification(166 /* MethodDeclaration */); + context.enableEmitNotification(168 /* GetAccessor */); + context.enableEmitNotification(169 /* SetAccessor */); + context.enableEmitNotification(210 /* ArrowFunction */); + context.enableEmitNotification(209 /* FunctionExpression */); + context.enableEmitNotification(252 /* FunctionDeclaration */); } } /** @@ -92132,10 +95113,10 @@ var ts; */ function isNameOfDeclarationWithCollidingName(node) { switch (node.parent.kind) { - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 249 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 250 /* VariableDeclaration */: return node.parent.name === node && resolver.isDeclarationWithCollidingName(node.parent); } @@ -92217,11 +95198,11 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 233 /* ExpressionStatement */) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 234 /* ExpressionStatement */) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 203 /* CallExpression */) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 204 /* CallExpression */) { return false; } var callTarget = statementExpression.expression; @@ -92229,7 +95210,7 @@ var ts; return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 220 /* SpreadElement */) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 221 /* SpreadElement */) { return false; } var expression = callArgument.expression; @@ -92255,15 +95236,15 @@ var ts; if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(275 /* JsxOpeningElement */); - context.enableEmitNotification(276 /* JsxClosingElement */); - context.enableEmitNotification(274 /* JsxSelfClosingElement */); + context.enableEmitNotification(276 /* JsxOpeningElement */); + context.enableEmitNotification(277 /* JsxClosingElement */); + context.enableEmitNotification(275 /* JsxSelfClosingElement */); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(288 /* PropertyAssignment */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(289 /* PropertyAssignment */); return ts.chainBundle(context, transformSourceFile); /** * Transforms an ES5 source file to ES3. @@ -92282,9 +95263,9 @@ var ts; */ function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 275 /* JsxOpeningElement */: - case 276 /* JsxClosingElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 277 /* JsxClosingElement */: + case 275 /* JsxSelfClosingElement */: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -92582,7 +95563,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 1024 /* ContainsGenerator */) === 0) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -92605,7 +95586,7 @@ var ts; else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) { return visitGenerator(node); } - else if (transformFlags & 512 /* ContainsGenerator */) { + else if (transformFlags & 1024 /* ContainsGenerator */) { return ts.visitEachChild(node, visitor, context); } else { @@ -92619,13 +95600,13 @@ var ts; */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 235 /* DoStatement */: + case 236 /* DoStatement */: return visitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return visitWhileStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -92638,30 +95619,30 @@ var ts; */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return visitFunctionExpression(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return visitAccessorDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: return visitBreakStatement(node); - case 240 /* ContinueStatement */: + case 241 /* ContinueStatement */: return visitContinueStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 262144 /* ContainsYield */) { + if (node.transformFlags & 524288 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 1048576 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (1024 /* ContainsGenerator */ | 2097152 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -92676,23 +95657,23 @@ var ts; */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitCommaListExpression(node); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return visitConditionalExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitYieldExpression(node); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return visitElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -92705,9 +95686,9 @@ var ts; */ function visitGenerator(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return visitFunctionExpression(node); default: return ts.Debug.failBadSyntaxKind(node); @@ -92866,7 +95847,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 262144 /* ContainsYield */) { + if (node.transformFlags & 524288 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -92915,7 +95896,7 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: // [source] // a.b = yield; // @@ -92927,7 +95908,7 @@ var ts; // _a.b = %sent%; target = factory.updatePropertyAccessExpression(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: // [source] // a[b] = yield; // @@ -93321,35 +96302,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 230 /* Block */: + case 231 /* Block */: return transformAndEmitBlock(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return transformAndEmitIfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return transformAndEmitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return transformAndEmitWhileStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return transformAndEmitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return transformAndEmitForInStatement(node); - case 240 /* ContinueStatement */: + case 241 /* ContinueStatement */: return transformAndEmitContinueStatement(node); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: return transformAndEmitBreakStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return transformAndEmitReturnStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return transformAndEmitWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return transformAndEmitThrowStatement(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -93569,7 +96550,7 @@ var ts; var variables = ts.getInitializedVariables(initializer); node = factory.updateForStatement(node, variables.length > 0 ? factory.inlineExpressions(ts.map(variables, transformInitializedVariable)) - : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitIterationBody(node.statement, visitor, context)); } else { node = ts.visitEachChild(node, visitor, context); @@ -93779,7 +96760,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 285 /* DefaultClause */ && defaultClauseIndex === -1) { + if (clause.kind === 286 /* DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -93792,7 +96773,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 284 /* CaseClause */) { + if (clause.kind === 285 /* CaseClause */) { if (containsYield(clause.expression) && pendingClauses.length > 0) { break; } @@ -93924,7 +96905,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 262144 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 524288 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -93957,10 +96938,10 @@ var ts; var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { // TODO(rbuckton): Does this need to be parented? - var clone_5 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); - ts.setSourceMapRange(clone_5, node); - ts.setCommentRange(clone_5, node); - return clone_5; + var clone_6 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -94953,11 +97934,11 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(216 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(214 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(215 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(289 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. - context.enableEmitNotification(297 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(217 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(215 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(216 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(298 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var currentSourceFile; // The current file. @@ -94973,7 +97954,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 2097152 /* ContainsDynamicImport */ || + node.transformFlags & 4194304 /* ContainsDynamicImport */ || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && ts.outFile(compilerOptions)))) { return node; } @@ -95285,23 +98266,23 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return visitClassDeclaration(node); - case 338 /* MergeDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 339 /* EndOfDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); @@ -95310,7 +98291,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 & 2097152 /* ContainsDynamicImport */) && !(node.transformFlags & 1024 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 4194304 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -95328,24 +98309,24 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; switch (elem.kind) { - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: if (destructuringNeedsFlattening(elem.initializer)) { return true; } break; - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: if (destructuringNeedsFlattening(elem.name)) { return true; } break; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: if (destructuringNeedsFlattening(elem.expression)) { return true; } break; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return false; default: ts.Debug.assertNever(elem, "Unhandled object member kind"); } @@ -95380,7 +98361,7 @@ var ts; var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); // Only use the external module name if it differs from the first argument. This allows us to preserve the quote style of the argument on output. var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument; - var containsLexicalThis = !!(node.transformFlags & 4096 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -95873,7 +98854,7 @@ var ts; // // To balance the declaration, add the exports of the elided variable // statement. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 232 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 233 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -95928,10 +98909,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true); @@ -96144,7 +99125,7 @@ var ts; * @param emit A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -96208,10 +99189,10 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return substituteExpressionIdentifier(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return substituteBinaryExpression(node); - case 215 /* PostfixUnaryExpression */: - case 214 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -96231,9 +99212,9 @@ var ts; } return node; } - if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) { + else if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 297 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 298 /* SourceFile */) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), /*location*/ node); } @@ -96308,8 +99289,8 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 215 /* PostfixUnaryExpression */ - ? ts.setTextRange(factory.createBinaryExpression(node.operand, factory.createToken(node.operator === 45 /* PlusPlusToken */ ? 63 /* PlusEqualsToken */ : 64 /* MinusEqualsToken */), factory.createNumericLiteral(1)), + var expression = node.kind === 216 /* PostfixUnaryExpression */ + ? ts.setTextRange(factory.createPrefixUnaryExpression(node.operator, node.operand), /*location*/ node) : node; for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { @@ -96318,6 +99299,12 @@ var ts; noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression); } + if (node.kind === 216 /* PostfixUnaryExpression */) { + noSubstitution[ts.getNodeId(expression)] = true; + expression = node.operator === 45 /* PlusPlusToken */ + ? factory.createSubtract(expression, factory.createNumericLiteral(1)) + : factory.createAdd(expression, factory.createNumericLiteral(1)); + } return expression; } } @@ -96360,12 +99347,12 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers for imported symbols. - context.enableSubstitution(289 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols - context.enableSubstitution(216 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(214 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(215 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(226 /* MetaProperty */); // Substitutes 'import.meta' - context.enableEmitNotification(297 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(217 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(215 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(216 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(227 /* MetaProperty */); // Substitutes 'import.meta' + context.enableEmitNotification(298 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var exportFunctionsMap = []; // The export function associated with a source file. @@ -96385,7 +99372,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 2097152 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 4194304 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -96554,7 +99541,7 @@ var ts; // - Temporary variables will appear at the top rather than at the bottom of the file ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 - var modifiers = node.transformFlags & 524288 /* ContainsAwait */ ? + var modifiers = node.transformFlags & 1048576 /* ContainsAwait */ ? factory.createModifiersFromModifierFlags(256 /* Async */) : undefined; var moduleObject = factory.createObjectLiteralExpression([ @@ -96589,7 +99576,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 267 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 268 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -96679,19 +99666,19 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(factory, entry, currentSourceFile); // TODO: GH#18217 switch (entry.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // falls through - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== undefined); // save import into the local statements.push(factory.createExpressionStatement(factory.createAssignment(importVariableName, parameterName))); break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { if (ts.isNamedExports(entry.exportClause)) { @@ -96750,13 +99737,13 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -96936,7 +99923,7 @@ var ts; function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 - && (enclosingBlockScopedContainer.kind === 297 /* SourceFile */ + && (enclosingBlockScopedContainer.kind === 298 /* SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); } /** @@ -97000,7 +99987,7 @@ var ts; // // To balance the declaration, we defer the exports of the elided variable // statement until we visit this declaration's `EndOfDeclarationMarker`. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 232 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 233 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasSyntacticModifier(node.original, 1 /* Export */); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -97062,10 +100049,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -97245,43 +100232,43 @@ var ts; */ function nestedElementVisitor(node) { switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return visitClassDeclaration(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return visitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return visitWhileStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return visitWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitSwitchStatement(node); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return visitCaseBlock(node); - case 284 /* CaseClause */: + case 285 /* CaseClause */: return visitCaseClause(node); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: return visitDefaultClause(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return visitTryStatement(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); - case 230 /* Block */: + case 231 /* Block */: return visitBlock(node); - case 338 /* MergeDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 339 /* EndOfDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -97295,7 +100282,7 @@ var ts; function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory.updateForStatement(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + node = factory.updateForStatement(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -97307,7 +100294,7 @@ var ts; function visitForInStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory.updateForInStatement(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); + node = factory.updateForInStatement(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -97319,7 +100306,7 @@ var ts; function visitForOfStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory.updateForOfStatement(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); + node = factory.updateForOfStatement(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -97360,7 +100347,7 @@ var ts; * @param node The node to visit. */ function visitDoStatement(node) { - return factory.updateDoStatement(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); + return factory.updateDoStatement(node, ts.visitIterationBody(node.statement, nestedElementVisitor, context), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); } /** * Visits the body of a WhileStatement to hoist declarations. @@ -97368,7 +100355,7 @@ var ts; * @param node The node to visit. */ function visitWhileStatement(node) { - return factory.updateWhileStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); + return factory.updateWhileStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); } /** * Visits the body of a LabeledStatement to hoist declarations. @@ -97469,7 +100456,7 @@ var ts; else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 1024 /* ContainsDestructuringAssignment */) || (node.transformFlags & 2097152 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 4194304 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -97507,7 +100494,7 @@ var ts; return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } /** - * Determines whether the target of a destructuring assigment refers to an exported symbol. + * Determines whether the target of a destructuring assignment refers to an exported symbol. * * @param node The destructuring target. */ @@ -97532,7 +100519,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 297 /* SourceFile */; + return container !== undefined && container.kind === 298 /* SourceFile */; } else { return false; @@ -97565,7 +100552,7 @@ var ts; * @param emitCallback A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -97615,7 +100602,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -97652,12 +100639,12 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return substituteExpressionIdentifier(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return substituteBinaryExpression(node); - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return substituteUnaryExpression(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return substituteMetaProperty(node); } return node; @@ -97751,14 +100738,14 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 215 /* PostfixUnaryExpression */ + var expression = node.kind === 216 /* PostfixUnaryExpression */ ? ts.setTextRange(factory.createPrefixUnaryExpression(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 215 /* PostfixUnaryExpression */) { + if (node.kind === 216 /* PostfixUnaryExpression */) { expression = node.operator === 45 /* PlusPlusToken */ ? factory.createSubtract(preventSubstitution(expression), factory.createNumericLiteral(1)) : factory.createAdd(preventSubstitution(expression), factory.createNumericLiteral(1)); @@ -97786,7 +100773,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); - if (exportContainer && exportContainer.kind === 297 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 298 /* SourceFile */) { exportedNames = ts.append(exportedNames, factory.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -97826,7 +100813,7 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(297 /* SourceFile */); + context.enableEmitNotification(298 /* SourceFile */); context.enableSubstitution(78 /* Identifier */); var helperNameSubstitutions; return ts.chainBundle(context, transformSourceFile); @@ -97858,12 +100845,12 @@ var ts; } function visitor(node) { switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // Elide `import=` as it is not legal with --module ES6 return undefined; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: var exportDecl = node; return visitExportDeclaration(exportDecl); } @@ -97968,7 +100955,8 @@ var ts; ts.isTypeAliasDeclaration(node) || ts.isConstructorDeclaration(node) || ts.isIndexSignatureDeclaration(node) || - ts.isPropertyAccessExpression(node); + ts.isPropertyAccessExpression(node) || + ts.isJSDocTypeAlias(node); } ts.canProduceDiagnostics = canProduceDiagnostics; function createGetSymbolAccessibilityDiagnosticForNodeName(node) { @@ -97997,7 +100985,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.kind === 253 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98026,7 +101014,7 @@ var ts; ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.kind === 253 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98066,14 +101054,14 @@ var ts; else if (ts.isImportEqualsDeclaration(node)) { return getImportEntityNameVisibilityError; } - else if (ts.isTypeAliasDeclaration(node)) { + else if (ts.isTypeAliasDeclaration(node) || ts.isJSDocTypeAlias(node)) { return getTypeAliasDeclarationVisibilityError; } else { return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) { + if (node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98082,8 +101070,8 @@ var ts; } // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. - else if (node.kind === 163 /* PropertyDeclaration */ || node.kind === 201 /* PropertyAccessExpression */ || node.kind === 162 /* PropertySignature */ || - (node.kind === 160 /* Parameter */ && ts.hasSyntacticModifier(node.parent, 8 /* Private */))) { + else if (node.kind === 164 /* PropertyDeclaration */ || node.kind === 202 /* PropertyAccessExpression */ || node.kind === 163 /* PropertySignature */ || + (node.kind === 161 /* Parameter */ && ts.hasSyntacticModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasSyntacticModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -98092,7 +101080,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 252 /* ClassDeclaration */ || node.kind === 160 /* Parameter */) { + else if (node.parent.kind === 253 /* ClassDeclaration */ || node.kind === 161 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98117,7 +101105,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (node.kind === 168 /* SetAccessor */) { + if (node.kind === 169 /* SetAccessor */) { // Getters can infer the return type from the returned expression, but setters cannot, so the // "_from_external_module_1_but_cannot_be_named" case cannot occur. if (ts.hasSyntacticModifier(node, 32 /* Static */)) { @@ -98156,26 +101144,26 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 169 /* CallSignature */: + case 170 /* CallSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasSyntacticModifier(node, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -98183,7 +101171,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.kind === 253 /* ClassDeclaration */) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -98197,7 +101185,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -98222,30 +101210,30 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 170 /* ConstructSignature */: - case 175 /* ConstructorType */: + case 171 /* ConstructSignature */: + case 176 /* ConstructorType */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 169 /* CallSignature */: + case 170 /* CallSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasSyntacticModifier(node.parent, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -98253,7 +101241,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 253 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98266,15 +101254,15 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 251 /* FunctionDeclaration */: - case 174 /* FunctionType */: + case 252 /* FunctionDeclaration */: + case 175 /* FunctionType */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; - case 168 /* SetAccessor */: - case 167 /* GetAccessor */: + case 169 /* SetAccessor */: + case 168 /* GetAccessor */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98288,39 +101276,39 @@ var ts; // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 190 /* MappedType */: + case 191 /* MappedType */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1; break; - case 175 /* ConstructorType */: - case 170 /* ConstructSignature */: + case 176 /* ConstructorType */: + case 171 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 169 /* CallSignature */: + case 170 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasSyntacticModifier(node.parent, 32 /* Static */)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 253 /* ClassDeclaration */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 174 /* FunctionType */: - case 251 /* FunctionDeclaration */: + case 175 /* FunctionType */: + case 252 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -98359,11 +101347,13 @@ var ts; typeName: node.name }; } - function getTypeAliasDeclarationVisibilityError() { + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name + diagnosticMessage: symbolAccessibilityResult.errorModuleName + ? ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2 + : ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: ts.isJSDocTypeAlias(node) ? ts.Debug.checkDefined(node.typeExpression) : node.type, + typeName: ts.isJSDocTypeAlias(node) ? ts.getNameOfDeclaration(node) : node.name, }; } } @@ -98384,7 +101374,7 @@ var ts; } function isInternalDeclaration(node, currentSourceFile) { var parseTreeNode = ts.getParseTreeNode(node); - if (parseTreeNode && parseTreeNode.kind === 160 /* Parameter */) { + if (parseTreeNode && parseTreeNode.kind === 161 /* Parameter */) { var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode); var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined; var text = currentSourceFile.text; @@ -98446,6 +101436,7 @@ var ts; reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; + var errorFallbackNode; var currentSourceFile; var refs; var libs; @@ -98515,8 +101506,8 @@ var ts; recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } function reportInaccessibleUniqueSymbolError() { @@ -98540,35 +101531,38 @@ var ts; } } function reportTruncationError() { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); } } function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { - var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); + var _a; + var primaryDeclaration = (_a = parentSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; }); - for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { - var augmentations = augmentingDeclarations_1[_i]; - context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + if (augmentingDeclarations) { + for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { + var augmentations = augmentingDeclarations_1[_i]; + context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + } } } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; - getSymbolAccessibilityDiagnostic = function (s) { return ({ + getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ diagnosticMessage: s.errorModuleName ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit, errorNode: s.errorNode || sourceFile - }); }; + })); }; var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled); getSymbolAccessibilityDiagnostic = oldDiag; return result; } function transformRoot(node) { - if (node.kind === 297 /* SourceFile */ && node.isDeclarationFile) { + if (node.kind === 298 /* SourceFile */ && node.isDeclarationFile) { return node; } - if (node.kind === 298 /* Bundle */) { + if (node.kind === 299 /* Bundle */) { isBundledEmit = true; refs = new ts.Map(); libs = new ts.Map(); @@ -98598,7 +101592,7 @@ var ts; var updated = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements); return factory.updateSourceFile(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); }), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 300 /* InputFiles */) { + if (prepend.kind === 301 /* InputFiles */) { var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal); hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib; collectReferences(sourceFile, refs); @@ -98690,7 +101684,7 @@ var ts; declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { - var specifier = ts.moduleSpecifiers.getModuleSpecifier(__assign(__assign({}, options), { baseUrl: options.baseUrl && ts.toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }), currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, + var specifier = ts.moduleSpecifiers.getModuleSpecifier(options, currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, /*preferences*/ undefined); if (!ts.pathIsRelative(specifier)) { // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration @@ -98739,7 +101733,7 @@ var ts; return name; } else { - if (name.kind === 197 /* ArrayBindingPattern */) { + if (name.kind === 198 /* ArrayBindingPattern */) { return factory.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); } else { @@ -98747,7 +101741,7 @@ var ts; } } function visitBindingElement(elem) { - if (elem.kind === 222 /* OmittedExpression */) { + if (elem.kind === 223 /* OmittedExpression */) { return elem; } return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); @@ -98785,7 +101779,7 @@ var ts; // Literal const declarations will have an initializer ensured rather than a type return; } - var shouldUseResolverType = node.kind === 160 /* Parameter */ && + var shouldUseResolverType = node.kind === 161 /* Parameter */ && (resolver.isRequiredInitializedParameter(node) || resolver.isOptionalUninitializedParameterProperty(node)); if (type && !shouldUseResolverType) { @@ -98794,7 +101788,7 @@ var ts; if (!ts.getParseTreeNode(node)) { return type ? ts.visitNode(type, visitDeclarationSubtree) : factory.createKeywordTypeNode(128 /* AnyKeyword */); } - if (node.kind === 168 /* SetAccessor */) { + if (node.kind === 169 /* SetAccessor */) { // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) return factory.createKeywordTypeNode(128 /* AnyKeyword */); @@ -98805,12 +101799,12 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); } - if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) { + if (node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */) { return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } - if (node.kind === 160 /* Parameter */ - || node.kind === 163 /* PropertyDeclaration */ - || node.kind === 162 /* PropertySignature */) { + if (node.kind === 161 /* Parameter */ + || node.kind === 164 /* PropertyDeclaration */ + || node.kind === 163 /* PropertySignature */) { if (!node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); @@ -98827,20 +101821,20 @@ var ts; function isDeclarationAndNotVisible(node) { node = ts.getParseTreeNode(node); switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 256 /* ModuleDeclaration */: - case 253 /* InterfaceDeclaration */: - case 252 /* ClassDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: + case 252 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 254 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: return !resolver.isDeclarationVisible(node); // The following should be doing their own visibility checks based on filtering their members - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return !getBindingNameVisible(node); - case 260 /* ImportEqualsDeclaration */: - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: + case 261 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: return false; } return false; @@ -98921,7 +101915,7 @@ var ts; function rewriteModuleSpecifier(parent, input) { if (!input) return undefined; // TODO: GH#18217 - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 256 /* ModuleDeclaration */ && parent.kind !== 195 /* ImportType */); + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 257 /* ModuleDeclaration */ && parent.kind !== 196 /* ImportType */); if (ts.isStringLiteralLike(input)) { if (isBundledEmit) { var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); @@ -98941,7 +101935,7 @@ var ts; function transformImportEqualsDeclaration(decl) { if (!resolver.isDeclarationVisible(decl)) return; - if (decl.moduleReference.kind === 272 /* ExternalModuleReference */) { + if (decl.moduleReference.kind === 273 /* ExternalModuleReference */) { // Rewrite external module names if necessary var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); return factory.updateImportEqualsDeclaration(decl, @@ -98968,7 +101962,7 @@ var ts; return visibleDefaultBinding && factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } - if (decl.importClause.namedBindings.kind === 263 /* NamespaceImport */) { + if (decl.importClause.namedBindings.kind === 264 /* NamespaceImport */) { // Namespace import (optionally with visible default) var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; @@ -99063,7 +102057,7 @@ var ts; // We'd see a TDZ violation at runtime var canProduceDiagnostic = ts.canProduceDiagnostics(input); var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; - var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 177 /* TypeLiteral */ || input.kind === 190 /* MappedType */) && input.parent.kind !== 254 /* TypeAliasDeclaration */); + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 178 /* TypeLiteral */ || input.kind === 191 /* MappedType */) && input.parent.kind !== 255 /* TypeAliasDeclaration */); // Emit methods which are private as properties with no type information if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { if (ts.hasEffectiveModifier(input, 8 /* Private */)) { @@ -99084,21 +102078,21 @@ var ts; } if (isProcessedComponent(input)) { switch (input.kind) { - case 223 /* ExpressionWithTypeArguments */: { + case 224 /* ExpressionWithTypeArguments */: { if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { checkEntityNameVisibility(input.expression, enclosingDeclaration); } var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(factory.updateExpressionWithTypeArguments(node, node.expression, node.typeArguments)); } - case 173 /* TypeReference */: { + case 174 /* TypeReference */: { checkEntityNameVisibility(input.typeName, enclosingDeclaration); var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(factory.updateTypeReferenceNode(node, node.typeName, node.typeArguments)); } - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: return cleanup(factory.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); - case 166 /* Constructor */: { + case 167 /* Constructor */: { // A constructor declaration may not have a type annotation var ctor = factory.createConstructorDeclaration( /*decorators*/ undefined, @@ -99106,7 +102100,7 @@ var ts; /*body*/ undefined); return cleanup(ctor); } - case 165 /* MethodDeclaration */: { + case 166 /* MethodDeclaration */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } @@ -99116,7 +102110,7 @@ var ts; /*body*/ undefined); return cleanup(sig); } - case 167 /* GetAccessor */: { + case 168 /* GetAccessor */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } @@ -99125,7 +102119,7 @@ var ts; /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), ensureType(input, accessorType), /*body*/ undefined)); } - case 168 /* SetAccessor */: { + case 169 /* SetAccessor */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } @@ -99133,31 +102127,31 @@ var ts; /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), /*body*/ undefined)); } - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updatePropertyDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type))); - case 164 /* MethodSignature */: { + case 165 /* MethodSignature */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updateMethodSignature(input, ensureModifiers(input), input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 169 /* CallSignature */: { + case 170 /* CallSignature */: { return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 171 /* IndexSignature */: { + case 172 /* IndexSignature */: { return cleanup(factory.updateIndexSignature(input, /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(128 /* AnyKeyword */))); } - case 249 /* VariableDeclaration */: { + case 250 /* VariableDeclaration */: { if (ts.isBindingPattern(input.name)) { return recreateBindingPattern(input.name); } @@ -99165,13 +102159,13 @@ var ts; suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types return cleanup(factory.updateVariableDeclaration(input, input.name, /*exclamationToken*/ undefined, ensureType(input, input.type), ensureNoInitializer(input))); } - case 159 /* TypeParameter */: { + case 160 /* TypeParameter */: { if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { return cleanup(factory.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); } return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); } - case 184 /* ConditionalType */: { + case 185 /* ConditionalType */: { // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); @@ -99183,13 +102177,13 @@ var ts; var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); return cleanup(factory.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); } - case 174 /* FunctionType */: { + case 175 /* FunctionType */: { return cleanup(factory.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 175 /* ConstructorType */: { + case 176 /* ConstructorType */: { return cleanup(factory.updateConstructorTypeNode(input, ensureModifiers(input), ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 195 /* ImportType */: { + case 196 /* ImportType */: { if (!ts.isLiteralImportTypeNode(input)) return cleanup(input); return cleanup(factory.updateImportTypeNode(input, factory.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); @@ -99221,7 +102215,7 @@ var ts; } } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 165 /* MethodDeclaration */ && ts.hasEffectiveModifier(node.parent, 8 /* Private */); + return node.parent.kind === 166 /* MethodDeclaration */ && ts.hasEffectiveModifier(node.parent, 8 /* Private */); } function visitDeclarationStatements(input) { if (!isPreservedDeclarationStatement(input)) { @@ -99231,7 +102225,7 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 267 /* ExportDeclaration */: { + case 268 /* ExportDeclaration */: { if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; } @@ -99241,7 +102235,7 @@ var ts; return factory.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); } - case 266 /* ExportAssignment */: { + case 267 /* ExportAssignment */: { // Always visible if the parent node isn't dropped for being not visible if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; @@ -99256,7 +102250,9 @@ var ts; diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: input }); }; + errorFallbackNode = input; var varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + errorFallbackNode = undefined; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */)); return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } @@ -99273,17 +102269,17 @@ var ts; // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too return statement; } - var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (11263 /* All */ ^ 1 /* Export */)); + var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (27647 /* All */ ^ 1 /* Export */)); return factory.updateModifiers(statement, modifiers); } function transformTopLevelDeclaration(input) { if (shouldStripInternal(input)) return; switch (input.kind) { - case 260 /* ImportEqualsDeclaration */: { + case 261 /* ImportEqualsDeclaration */: { return transformImportEqualsDeclaration(input); } - case 261 /* ImportDeclaration */: { + case 262 /* ImportDeclaration */: { return transformImportDeclaration(input); } } @@ -99304,14 +102300,14 @@ var ts; } var previousNeedsDeclare = needsDeclare; switch (input.kind) { - case 254 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + case 255 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all return cleanup(factory.updateTypeAliasDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); - case 253 /* InterfaceDeclaration */: { + case 254 /* InterfaceDeclaration */: { return cleanup(factory.updateInterfaceDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } - case 251 /* FunctionDeclaration */: { + case 252 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type var clean = cleanup(factory.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), @@ -99326,7 +102322,7 @@ var ts; fakespace_1.symbol = props[0].parent; var exportMappings_1 = []; var declarations = ts.mapDefined(props, function (p) { - if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + if (!p.valueDeclaration || !ts.isPropertyAccessExpression(p.valueDeclaration)) { return undefined; // TODO GH#33569: Handle element access expressions that created late bound names (rather than silently omitting them) } getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration); @@ -99378,10 +102374,10 @@ var ts; return clean; } } - case 256 /* ModuleDeclaration */: { + case 257 /* ModuleDeclaration */: { needsDeclare = false; var inner = input.body; - if (inner && inner.kind === 257 /* ModuleBlock */) { + if (inner && inner.kind === 258 /* ModuleBlock */) { var oldNeedsScopeFix = needsScopeFixMarker; var oldHasScopeFix = resultHasScopeMarker; resultHasScopeMarker = false; @@ -99424,7 +102420,9 @@ var ts; /*decorators*/ undefined, mods, input.name, body)); } } - case 252 /* ClassDeclaration */: { + case 253 /* ClassDeclaration */: { + errorNameNode = input.name; + errorFallbackNode = input; var modifiers = factory.createNodeArray(ensureModifiers(input)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -99432,7 +102430,7 @@ var ts; if (ctor) { var oldDiag_1 = getSymbolAccessibilityDiagnostic; parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { - if (!ts.hasSyntacticModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param)) + if (!ts.hasSyntacticModifier(param, 16476 /* ParameterPropertyModifier */) || shouldStripInternal(param)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 78 /* Identifier */) { @@ -99507,10 +102505,10 @@ var ts; /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); } } - case 232 /* VariableStatement */: { + case 233 /* VariableStatement */: { return cleanup(transformVariableStatement(input)); } - case 255 /* EnumDeclaration */: { + case 256 /* EnumDeclaration */: { return cleanup(factory.updateEnumDeclaration(input, /*decorators*/ undefined, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; @@ -99529,12 +102527,14 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 256 /* ModuleDeclaration */) { + if (input.kind === 257 /* ModuleDeclaration */) { needsDeclare = previousNeedsDeclare; } if (node === input) { return node; } + errorFallbackNode = undefined; + errorNameNode = undefined; return node && ts.setOriginalNode(preserveJsDoc(node, input), input); } } @@ -99550,7 +102550,7 @@ var ts; return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); } function recreateBindingElement(e) { - if (e.kind === 222 /* OmittedExpression */) { + if (e.kind === 223 /* OmittedExpression */) { return; } if (e.name) { @@ -99598,9 +102598,9 @@ var ts; return factory.createModifiersFromModifierFlags(newFlags); } function ensureModifierFlags(node) { - var mask = 11263 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files + var mask = 27647 /* All */ ^ (4 /* Public */ | 256 /* Async */ | 16384 /* Override */); // No async and override modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; - var parentIsFile = node.parent.kind === 297 /* SourceFile */; + var parentIsFile = node.parent.kind === 298 /* SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { mask ^= 2 /* Ambient */; additions = 0 /* None */; @@ -99629,7 +102629,7 @@ var ts; } ts.transformDeclarations = transformDeclarations; function isAlwaysType(node) { - if (node.kind === 253 /* InterfaceDeclaration */) { + if (node.kind === 254 /* InterfaceDeclaration */) { return true; } return false; @@ -99639,7 +102639,7 @@ var ts; return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); } function maskModifierFlags(node, modifierMask, modifierAdditions) { - if (modifierMask === void 0) { modifierMask = 11263 /* All */ ^ 4 /* Public */; } + if (modifierMask === void 0) { modifierMask = 27647 /* All */ ^ 4 /* Public */; } if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions; if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) { @@ -99654,7 +102654,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 167 /* GetAccessor */ + return accessor.kind === 168 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type @@ -99663,52 +102663,52 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return !ts.hasEffectiveModifier(node, 8 /* Private */); - case 160 /* Parameter */: - case 249 /* VariableDeclaration */: + case 161 /* Parameter */: + case 250 /* VariableDeclaration */: return true; } return false; } function isPreservedDeclarationStatement(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 256 /* ModuleDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 253 /* InterfaceDeclaration */: - case 252 /* ClassDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: - case 232 /* VariableStatement */: - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: + case 252 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 254 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 233 /* VariableStatement */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: return true; } return false; } function isProcessedComponent(node) { switch (node.kind) { - case 170 /* ConstructSignature */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 171 /* IndexSignature */: - case 249 /* VariableDeclaration */: - case 159 /* TypeParameter */: - case 223 /* ExpressionWithTypeArguments */: - case 173 /* TypeReference */: - case 184 /* ConditionalType */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 195 /* ImportType */: + case 171 /* ConstructSignature */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 172 /* IndexSignature */: + case 250 /* VariableDeclaration */: + case 160 /* TypeParameter */: + case 224 /* ExpressionWithTypeArguments */: + case 174 /* TypeReference */: + case 185 /* ConditionalType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 196 /* ImportType */: return true; } return false; @@ -99764,6 +102764,9 @@ var ts; if (languageVersion < 99 /* ESNext */) { transformers.push(ts.transformESNext); } + if (languageVersion < 8 /* ES2021 */) { + transformers.push(ts.transformES2021); + } if (languageVersion < 7 /* ES2020 */) { transformers.push(ts.transformES2020); } @@ -99840,7 +102843,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, factory, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(341 /* Count */); + var enabledSyntaxKindFeatures = new Array(345 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentStatements; @@ -99851,6 +102854,9 @@ var ts; var lexicalEnvironmentFlagsStack = []; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; + var blockScopedVariableDeclarationsStack = []; + var blockScopeStackOffset = 0; + var blockScopedVariableDeclarations; var emitHelpers; var onSubstituteNode = noEmitSubstitution; var onEmitNode = noEmitNotification; @@ -99873,6 +102879,9 @@ var ts; hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, addInitializationStatement: addInitializationStatement, + startBlockScope: startBlockScope, + endBlockScope: endBlockScope, + addBlockScopedVariable: addBlockScopedVariable, requestEmitHelper: requestEmitHelper, readEmitHelpers: readEmitHelpers, enableSubstitution: enableSubstitution, @@ -99916,9 +102925,9 @@ var ts; var transformed = []; for (var _a = 0, nodes_3 = nodes; _a < nodes_3.length; _a++) { var node = nodes_3[_a]; - ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 298 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); transformed.push((allowDtsFiles ? transformation : transformRoot)(node)); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // prevent modification of the lexical environment. state = 2 /* Completed */; @@ -100133,6 +103142,38 @@ var ts; function getLexicalEnvironmentFlags() { return lexicalEnvironmentFlags; } + /** + * Starts a block scope. Any existing block hoisted variables are pushed onto the stack and the related storage variables are reset. + */ + function startBlockScope() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot start a block scope during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot start a block scope after transformation has completed."); + blockScopedVariableDeclarationsStack[blockScopeStackOffset] = blockScopedVariableDeclarations; + blockScopeStackOffset++; + blockScopedVariableDeclarations = undefined; + } + /** + * Ends a block scope. The previous set of block hoisted variables are restored. Any hoisted declarations are returned. + */ + function endBlockScope() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot end a block scope during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot end a block scope after transformation has completed."); + var statements = ts.some(blockScopedVariableDeclarations) ? + [ + factory.createVariableStatement( + /*modifiers*/ undefined, factory.createVariableDeclarationList(blockScopedVariableDeclarations.map(function (identifier) { return factory.createVariableDeclaration(identifier); }), 1 /* Let */)) + ] : undefined; + blockScopeStackOffset--; + blockScopedVariableDeclarations = blockScopedVariableDeclarationsStack[blockScopeStackOffset]; + if (blockScopeStackOffset === 0) { + blockScopedVariableDeclarationsStack = []; + } + return statements; + } + function addBlockScopedVariable(name) { + ts.Debug.assert(blockScopeStackOffset > 0, "Cannot add a block scoped variable outside of an iteration body."); + (blockScopedVariableDeclarations || (blockScopedVariableDeclarations = [])).push(name); + } function requestEmitHelper(helper) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); @@ -100174,35 +103215,37 @@ var ts; } ts.transformNodes = transformNodes; ts.nullTransformationContext = { - get factory() { return ts.factory; }, - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: ts.returnUndefined, + factory: ts.factory, getCompilerOptions: function () { return ({}); }, - getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + getEmitHost: ts.notImplemented, getEmitHelperFactory: ts.notImplemented, + startLexicalEnvironment: ts.noop, + resumeLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop, + endLexicalEnvironment: ts.returnUndefined, setLexicalEnvironmentFlags: ts.noop, getLexicalEnvironmentFlags: function () { return 0; }, - hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + hoistFunctionDeclaration: ts.noop, addInitializationStatement: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, + startBlockScope: ts.noop, + endBlockScope: ts.returnUndefined, + addBlockScopedVariable: ts.noop, requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop, + readEmitHelpers: ts.notImplemented, + enableSubstitution: ts.noop, + enableEmitNotification: ts.noop, + isSubstitutionEnabled: ts.notImplemented, + isEmitNotificationEnabled: ts.notImplemented, + onSubstituteNode: noEmitSubstitution, + onEmitNode: noEmitNotification, addDiagnostic: ts.noop, }; })(ts || (ts = {})); var ts; (function (ts) { var brackets = createBracketsMap(); - var syntheticParent = { pos: -1, end: -1 }; /*@internal*/ function isBuildInfoFile(file) { return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */); @@ -100288,7 +103331,7 @@ var ts; /*@internal*/ function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); - if (sourceFile.kind === 298 /* Bundle */) { + if (sourceFile.kind === 299 /* Bundle */) { return getOutputPathsForBundle(options, forceDtsPaths); } else { @@ -100514,15 +103557,15 @@ var ts; sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); }) }; } - ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); emitBuildInfo(bundleBuildInfo, buildInfoPath); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { if (jsFilePath) { @@ -100649,13 +103692,13 @@ var ts; if (!declBlocked || forceDtsEmit) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, { - sourceMap: compilerOptions.declarationMap, + sourceMap: !forceDtsEmit && compilerOptions.declarationMap, sourceRoot: compilerOptions.sourceRoot, mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, // Explicitly do not passthru either `inline` option }); - if (forceDtsEmit && declarationTransform.transformed[0].kind === 297 /* SourceFile */) { + if (forceDtsEmit && declarationTransform.transformed[0].kind === 298 /* SourceFile */) { var sourceFile = declarationTransform.transformed[0]; exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; } @@ -100678,8 +103721,8 @@ var ts; ts.forEachChild(node, collectLinkedAliases); } function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) { - var bundle = sourceFileOrBundle.kind === 298 /* Bundle */ ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 297 /* SourceFile */ ? sourceFileOrBundle : undefined; + var bundle = sourceFileOrBundle.kind === 299 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 298 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; var sourceMapGenerator; if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { @@ -100720,7 +103763,7 @@ var ts; } function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { return (mapOptions.sourceMap || mapOptions.inlineSourceMap) - && (sourceFileOrBundle.kind !== 297 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); + && (sourceFileOrBundle.kind !== 298 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); } function getSourceRoot(mapOptions) { // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the @@ -100779,7 +103822,7 @@ var ts; ts.emitFiles = emitFiles; /*@internal*/ function getBuildInfoText(buildInfo) { - return JSON.stringify(buildInfo, undefined, 2); + return JSON.stringify(buildInfo); } ts.getBuildInfoText = getBuildInfoText; /*@internal*/ @@ -100960,7 +104003,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = ts.getNewLineCharacter(printerOptions); var moduleKind = ts.getEmitModuleKind(printerOptions); @@ -100999,9 +104042,11 @@ var ts; var detachedCommentsInfo; var hasWrittenComment = false; var commentsDisabled = !!printerOptions.removeComments; - var lastNode; var lastSubstitution; + var currentParenthesizerRule; var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; + var parenthesizer = ts.factory.parenthesizer; + var emitBinaryExpression = createEmitBinaryExpression(); reset(); return { // public API @@ -101029,9 +104074,9 @@ var ts; break; } switch (node.kind) { - case 297 /* SourceFile */: return printFile(node); - case 298 /* Bundle */: return printBundle(node); - case 299 /* UnparsedSource */: return printUnparsedSource(node); + case 298 /* SourceFile */: return printFile(node); + case 299 /* Bundle */: return printBundle(node); + case 300 /* UnparsedSource */: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -101065,7 +104110,7 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - emitList(syntheticParent, nodes, format); + emitList(/*parentNode*/ undefined, nodes, format); reset(); writer = previousWriter; } @@ -101200,7 +104245,7 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - pipelineEmit(hint, node); + pipelineEmit(hint, node, /*parenthesizerRule*/ undefined); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -101228,51 +104273,54 @@ var ts; currentSourceFile = undefined; currentLineMap = undefined; detachedCommentsInfo = undefined; - lastNode = undefined; - lastSubstitution = undefined; setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined); } function getCurrentLineMap() { return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); } - function emit(node) { + function emit(node, parenthesizerRule) { if (node === undefined) return; var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node); - var substitute = pipelineEmit(4 /* Unspecified */, node); + pipelineEmit(4 /* Unspecified */, node, parenthesizerRule); recordBundleFileInternalSectionEnd(prevSourceFileTextKind); - return substitute; } function emitIdentifierName(node) { if (node === undefined) return; - return pipelineEmit(2 /* IdentifierName */, node); + pipelineEmit(2 /* IdentifierName */, node, /*parenthesizerRule*/ undefined); } - function emitExpression(node) { + function emitExpression(node, parenthesizerRule) { if (node === undefined) return; - return pipelineEmit(1 /* Expression */, node); + pipelineEmit(1 /* Expression */, node, parenthesizerRule); } function emitJsxAttributeValue(node) { - return pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); + pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); } - function pipelineEmit(emitHint, node) { - var savedLastNode = lastNode; - var savedLastSubstitution = lastSubstitution; - var savedPreserveSourceNewlines = preserveSourceNewlines; - lastNode = node; - lastSubstitution = undefined; - if (preserveSourceNewlines && !!(ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) { + function beforeEmitNode(node) { + if (preserveSourceNewlines && (ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) { preserveSourceNewlines = false; } + } + function afterEmitNode(savedPreserveSourceNewlines) { + preserveSourceNewlines = savedPreserveSourceNewlines; + } + function pipelineEmit(emitHint, node, parenthesizerRule) { + currentParenthesizerRule = parenthesizerRule; var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node); pipelinePhase(emitHint, node); - ts.Debug.assert(lastNode === node); - var substitute = lastSubstitution; - lastNode = savedLastNode; - lastSubstitution = savedLastSubstitution; - preserveSourceNewlines = savedPreserveSourceNewlines; - return substitute || node; + currentParenthesizerRule = undefined; + } + function shouldEmitComments(node) { + return !commentsDisabled && !ts.isSourceFile(node); + } + function shouldEmitSourceMaps(node) { + return !sourceMapsDisabled && + !ts.isSourceFile(node) && + !ts.isInJsonFile(node) && + !ts.isUnparsedSource(node) && + !ts.isUnparsedPrepend(node); } function getPipelinePhase(phase, emitHint, node) { switch (phase) { @@ -101282,18 +104330,21 @@ var ts; } // falls through case 1 /* Substitution */: - if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) { + if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) { + if (currentParenthesizerRule) { + lastSubstitution = currentParenthesizerRule(lastSubstitution); + } return pipelineEmitWithSubstitution; } // falls through case 2 /* Comments */: - if (!commentsDisabled && node.kind !== 297 /* SourceFile */) { + if (shouldEmitComments(node)) { return pipelineEmitWithComments; } // falls through case 3 /* SourceMaps */: - if (!sourceMapsDisabled && node.kind !== 297 /* SourceFile */ && !ts.isInJsonFile(node)) { - return pipelineEmitWithSourceMap; + if (shouldEmitSourceMaps(node)) { + return pipelineEmitWithSourceMaps; } // falls through case 4 /* Emit */: @@ -101306,13 +104357,25 @@ var ts; return getPipelinePhase(currentPhase + 1, emitHint, node); } function pipelineEmitWithNotification(hint, node) { - ts.Debug.assert(lastNode === node); var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node); onEmitNode(hint, node, pipelinePhase); - ts.Debug.assert(lastNode === node); } function pipelineEmitWithHint(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (preserveSourceNewlines) { + var savedPreserveSourceNewlines = preserveSourceNewlines; + beforeEmitNode(node); + pipelineEmitWithHintWorker(hint, node); + afterEmitNode(savedPreserveSourceNewlines); + } + else { + pipelineEmitWithHintWorker(hint, node); + } + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); + // clear the parenthesizer rule as we ascend + currentParenthesizerRule = undefined; + } + function pipelineEmitWithHintWorker(hint, node) { if (hint === 0 /* SourceFile */) return emitSourceFile(ts.cast(node, ts.isSourceFile)); if (hint === 2 /* IdentifierName */) @@ -101326,24 +104389,12 @@ var ts; return emitEmptyStatement(/*isEmbeddedStatement*/ true); } if (hint === 4 /* Unspecified */) { - if (ts.isKeyword(node.kind)) - return writeTokenNode(node, writeKeyword); switch (node.kind) { // Pseudo-literals case 15 /* TemplateHead */: case 16 /* TemplateMiddle */: case 17 /* TemplateTail */: return emitLiteral(node, /*jsxAttributeEscape*/ false); - case 299 /* UnparsedSource */: - case 293 /* UnparsedPrepend */: - return emitUnparsedSourceOrPrepend(node); - case 292 /* UnparsedPrologue */: - return writeUnparsedNode(node); - case 294 /* UnparsedText */: - case 295 /* UnparsedInternalText */: - return emitUnparsedTextLike(node); - case 296 /* UnparsedSyntheticReference */: - return emitUnparsedSyntheticReference(node); // Identifiers case 78 /* Identifier */: return emitIdentifier(node); @@ -101352,282 +104403,323 @@ var ts; return emitPrivateIdentifier(node); // Parse tree nodes // Names - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return emitQualifiedName(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return emitComputedPropertyName(node); // Signature elements - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return emitTypeParameter(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return emitParameter(node); - case 161 /* Decorator */: + case 162 /* Decorator */: return emitDecorator(node); // Type members - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: return emitPropertySignature(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return emitPropertyDeclaration(node); - case 164 /* MethodSignature */: + case 165 /* MethodSignature */: return emitMethodSignature(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return emitMethodDeclaration(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return emitConstructor(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return emitAccessorDeclaration(node); - case 169 /* CallSignature */: + case 170 /* CallSignature */: return emitCallSignature(node); - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: return emitConstructSignature(node); - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: return emitIndexSignature(node); - case 194 /* TemplateLiteralTypeSpan */: - return emitTemplateTypeSpan(node); // Types - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return emitTypePredicate(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return emitTypeReference(node); - case 174 /* FunctionType */: + case 175 /* FunctionType */: return emitFunctionType(node); - case 308 /* JSDocFunctionType */: - return emitJSDocFunctionType(node); - case 175 /* ConstructorType */: + case 176 /* ConstructorType */: return emitConstructorType(node); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return emitTypeQuery(node); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return emitTypeLiteral(node); - case 178 /* ArrayType */: + case 179 /* ArrayType */: return emitArrayType(node); - case 179 /* TupleType */: + case 180 /* TupleType */: return emitTupleType(node); - case 180 /* OptionalType */: + case 181 /* OptionalType */: return emitOptionalType(node); - case 182 /* UnionType */: + // SyntaxKind.RestType is handled below + case 183 /* UnionType */: return emitUnionType(node); - case 183 /* IntersectionType */: + case 184 /* IntersectionType */: return emitIntersectionType(node); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return emitConditionalType(node); - case 185 /* InferType */: + case 186 /* InferType */: return emitInferType(node); - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return emitParenthesizedType(node); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(node); - case 187 /* ThisType */: + case 188 /* ThisType */: return emitThisType(); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return emitTypeOperator(node); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return emitIndexedAccessType(node); - case 190 /* MappedType */: + case 191 /* MappedType */: return emitMappedType(node); - case 191 /* LiteralType */: + case 192 /* LiteralType */: return emitLiteralType(node); - case 193 /* TemplateLiteralType */: + case 193 /* NamedTupleMember */: + return emitNamedTupleMember(node); + case 194 /* TemplateLiteralType */: return emitTemplateType(node); - case 195 /* ImportType */: + case 195 /* TemplateLiteralTypeSpan */: + return emitTemplateTypeSpan(node); + case 196 /* ImportType */: return emitImportTypeNode(node); - case 303 /* JSDocAllType */: - writePunctuation("*"); - return; - case 304 /* JSDocUnknownType */: - writePunctuation("?"); - return; - case 305 /* JSDocNullableType */: - return emitJSDocNullableType(node); - case 306 /* JSDocNonNullableType */: - return emitJSDocNonNullableType(node); - case 307 /* JSDocOptionalType */: - return emitJSDocOptionalType(node); - case 181 /* RestType */: - case 309 /* JSDocVariadicType */: - return emitRestOrJSDocVariadicType(node); - case 192 /* NamedTupleMember */: - return emitNamedTupleMember(node); // Binding patterns - case 196 /* ObjectBindingPattern */: + case 197 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return emitBindingElement(node); // Misc - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return emitTemplateSpan(node); - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: return emitSemicolonClassElement(); // Statements - case 230 /* Block */: + case 231 /* Block */: return emitBlock(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return emitVariableStatement(node); - case 231 /* EmptyStatement */: + case 232 /* EmptyStatement */: return emitEmptyStatement(/*isEmbeddedStatement*/ false); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return emitExpressionStatement(node); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return emitIfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return emitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return emitWhileStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return emitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return emitForInStatement(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return emitForOfStatement(node); - case 240 /* ContinueStatement */: + case 241 /* ContinueStatement */: return emitContinueStatement(node); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: return emitBreakStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return emitReturnStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return emitWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return emitSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return emitLabeledStatement(node); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return emitThrowStatement(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return emitTryStatement(node); - case 248 /* DebuggerStatement */: + case 249 /* DebuggerStatement */: return emitDebuggerStatement(node); // Declarations - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return emitVariableDeclarationList(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return emitFunctionDeclaration(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return emitClassDeclaration(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return emitTypeAliasDeclaration(node); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return emitModuleBlock(node); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return emitCaseBlock(node); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return emitNamespaceExportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return emitImportDeclaration(node); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return emitImportClause(node); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return emitNamespaceImport(node); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: return emitNamespaceExport(node); - case 264 /* NamedImports */: + case 265 /* NamedImports */: return emitNamedImports(node); - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: return emitImportSpecifier(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return emitExportAssignment(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return emitExportDeclaration(node); - case 268 /* NamedExports */: + case 269 /* NamedExports */: return emitNamedExports(node); - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: return emitExportSpecifier(node); - case 271 /* MissingDeclaration */: + case 272 /* MissingDeclaration */: return; // Module references - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: return emitExternalModuleReference(node); // JSX (non-expression) case 11 /* JsxText */: return emitJsxText(node); - case 275 /* JsxOpeningElement */: - case 278 /* JsxOpeningFragment */: + case 276 /* JsxOpeningElement */: + case 279 /* JsxOpeningFragment */: return emitJsxOpeningElementOrFragment(node); - case 276 /* JsxClosingElement */: - case 279 /* JsxClosingFragment */: + case 277 /* JsxClosingElement */: + case 280 /* JsxClosingFragment */: return emitJsxClosingElementOrFragment(node); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return emitJsxAttribute(node); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return emitJsxAttributes(node); - case 282 /* JsxSpreadAttribute */: + case 283 /* JsxSpreadAttribute */: return emitJsxSpreadAttribute(node); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return emitJsxExpression(node); // Clauses - case 284 /* CaseClause */: + case 285 /* CaseClause */: return emitCaseClause(node); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: return emitDefaultClause(node); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: return emitHeritageClause(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return emitCatchClause(node); // Property assignments - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: return emitSpreadAssignment(node); // Enum - case 291 /* EnumMember */: + case 292 /* EnumMember */: return emitEnumMember(node); + // Unparsed + case 293 /* UnparsedPrologue */: + return writeUnparsedNode(node); + case 300 /* UnparsedSource */: + case 294 /* UnparsedPrepend */: + return emitUnparsedSourceOrPrepend(node); + case 295 /* UnparsedText */: + case 296 /* UnparsedInternalText */: + return emitUnparsedTextLike(node); + case 297 /* UnparsedSyntheticReference */: + return emitUnparsedSyntheticReference(node); + // Top-level nodes + case 298 /* SourceFile */: + return emitSourceFile(node); + case 299 /* Bundle */: + return ts.Debug.fail("Bundles should be printed using printBundle"); + // SyntaxKind.UnparsedSource (handled above) + case 301 /* InputFiles */: + return ts.Debug.fail("InputFiles should not be printed"); // JSDoc nodes (only used in codefixes currently) - case 326 /* JSDocParameterTag */: - case 333 /* JSDocPropertyTag */: + case 302 /* JSDocTypeExpression */: + return emitJSDocTypeExpression(node); + case 303 /* JSDocNameReference */: + return emitJSDocNameReference(node); + case 304 /* JSDocAllType */: + return writePunctuation("*"); + case 305 /* JSDocUnknownType */: + return writePunctuation("?"); + case 306 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 307 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 308 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 309 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 182 /* RestType */: + case 310 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + case 311 /* JSDocNamepathType */: + return; + case 312 /* JSDocComment */: + return emitJSDoc(node); + case 314 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 315 /* JSDocSignature */: + return emitJSDocSignature(node); + case 317 /* JSDocTag */: + case 322 /* JSDocClassTag */: + return emitJSDocSimpleTag(node); + case 318 /* JSDocAugmentsTag */: + case 319 /* JSDocImplementsTag */: + return emitJSDocHeritageTag(node); + case 320 /* JSDocAuthorTag */: + case 321 /* JSDocDeprecatedTag */: + return; + // SyntaxKind.JSDocClassTag (see JSDocTag, above) + case 323 /* JSDocPublicTag */: + case 324 /* JSDocPrivateTag */: + case 325 /* JSDocProtectedTag */: + case 326 /* JSDocReadonlyTag */: + case 327 /* JSDocOverrideTag */: + return; + case 328 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + // SyntaxKind.JSDocEnumTag (see below) + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: return emitJSDocPropertyLikeTag(node); - case 327 /* JSDocReturnTag */: - case 329 /* JSDocTypeTag */: - case 328 /* JSDocThisTag */: - case 325 /* JSDocEnumTag */: + case 329 /* JSDocEnumTag */: + case 331 /* JSDocReturnTag */: + case 332 /* JSDocThisTag */: + case 333 /* JSDocTypeTag */: return emitJSDocSimpleTypedTag(node); - case 316 /* JSDocImplementsTag */: - case 315 /* JSDocAugmentsTag */: - return emitJSDocHeritageTag(node); - case 330 /* JSDocTemplateTag */: + case 334 /* JSDocTemplateTag */: return emitJSDocTemplateTag(node); - case 331 /* JSDocTypedefTag */: + case 335 /* JSDocTypedefTag */: return emitJSDocTypedefTag(node); - case 324 /* JSDocCallbackTag */: - return emitJSDocCallbackTag(node); - case 313 /* JSDocSignature */: - return emitJSDocSignature(node); - case 312 /* JSDocTypeLiteral */: - return emitJSDocTypeLiteral(node); - case 319 /* JSDocClassTag */: - case 314 /* JSDocTag */: - return emitJSDocSimpleTag(node); - case 332 /* JSDocSeeTag */: + case 336 /* JSDocSeeTag */: return emitJSDocSeeTag(node); - case 302 /* JSDocNameReference */: - return emitJSDocNameReference(node); - case 311 /* JSDocComment */: - return emitJSDoc(node); - // Transformation nodes (ignored) + // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) + // Transformation nodes + case 339 /* NotEmittedStatement */: + case 343 /* EndOfDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: + return; } if (ts.isExpression(node)) { hint = 1 /* Expression */; if (substituteNode !== ts.noEmitSubstitution) { - lastSubstitution = node = substituteNode(hint, node); + var substitute = substituteNode(hint, node) || node; + if (substitute !== node) { + node = substitute; + if (currentParenthesizerRule) { + node = currentParenthesizerRule(node); + } + } } } - else if (ts.isToken(node)) { - return writeTokenNode(node, writePunctuation); - } } if (hint === 1 /* Expression */) { switch (node.kind) { @@ -101642,84 +104734,92 @@ var ts; // Identifiers case 78 /* Identifier */: return emitIdentifier(node); - // Reserved words - case 94 /* FalseKeyword */: - case 103 /* NullKeyword */: - case 105 /* SuperKeyword */: - case 109 /* TrueKeyword */: - case 107 /* ThisKeyword */: - case 99 /* ImportKeyword */: - writeTokenNode(node, writeKeyword); - return; // Expressions - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return emitObjectLiteralExpression(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return emitPropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return emitElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return emitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return emitNewExpression(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: return emitTypeAssertionExpression(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return emitParenthesizedExpression(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return emitFunctionExpression(node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return emitArrowFunction(node); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return emitDeleteExpression(node); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return emitVoidExpression(node); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return emitAwaitExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return emitBinaryExpression(node); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return emitConditionalExpression(node); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return emitTemplateExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return emitYieldExpression(node); - case 220 /* SpreadElement */: - return emitSpreadExpression(node); - case 221 /* ClassExpression */: + case 221 /* SpreadElement */: + return emitSpreadElement(node); + case 222 /* ClassExpression */: return emitClassExpression(node); - case 222 /* OmittedExpression */: + case 223 /* OmittedExpression */: return; - case 224 /* AsExpression */: + case 225 /* AsExpression */: return emitAsExpression(node); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return emitNonNullExpression(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return emitMetaProperty(node); + case 228 /* SyntheticExpression */: + return ts.Debug.fail("SyntheticExpression should never be printed."); // JSX - case 273 /* JsxElement */: + case 274 /* JsxElement */: return emitJsxElement(node); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return emitJsxFragment(node); + // Synthesized list + case 338 /* SyntaxList */: + return ts.Debug.fail("SyntaxList should not be printed"); // Transformation nodes - case 336 /* PartiallyEmittedExpression */: + case 339 /* NotEmittedStatement */: + return; + case 340 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return emitCommaList(node); + case 342 /* MergeDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: + return; + case 344 /* SyntheticReferenceExpression */: + return ts.Debug.fail("SyntheticReferenceExpression should not be printed"); } } + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + if (ts.isTokenKind(node.kind)) + return writeTokenNode(node, writePunctuation); + ts.Debug.fail("Unhandled SyntaxKind: " + ts.Debug.formatSyntaxKind(node.kind) + "."); } function emitMappedTypeParameter(node) { emit(node.name); @@ -101729,10 +104829,11 @@ var ts; emit(node.constraint); } function pipelineEmitWithSubstitution(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node); - pipelinePhase(hint, lastSubstitution); - ts.Debug.assert(lastNode === node || lastSubstitution === node); + ts.Debug.assertIsDefined(lastSubstitution); + node = lastSubstitution; + lastSubstitution = undefined; + pipelinePhase(hint, node); } function getHelpersFromBundledSourceFiles(bundle) { var result; @@ -101758,7 +104859,7 @@ var ts; } function emitHelpers(node) { var helpersEmitted = false; - var bundle = node.kind === 298 /* Bundle */ ? node : undefined; + var bundle = node.kind === 299 /* Bundle */ ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -101858,7 +104959,7 @@ var ts; var pos = getTextPosWithWriteLine(); writeUnparsedNode(unparsed); if (bundleFileInfo) { - updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 294 /* UnparsedText */ ? + updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 295 /* UnparsedText */ ? "text" /* Text */ : "internal" /* Internal */); } @@ -101904,7 +105005,7 @@ var ts; } function emitComputedPropertyName(node) { writePunctuation("["); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName); writePunctuation("]"); } // @@ -101931,18 +105032,18 @@ var ts; emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); - if (node.parent && node.parent.kind === 308 /* JSDocFunctionType */ && !node.name) { + if (node.parent && node.parent.kind === 309 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { emitTypeAnnotation(node.type); } // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. - emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitDecorator(decorator) { writePunctuation("@"); - emitExpression(decorator.expression); + emitExpression(decorator.expression, parenthesizer.parenthesizeLeftSideOfAccess); } // // Type members @@ -101993,7 +105094,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeKeyword(node.kind === 167 /* GetAccessor */ ? "get" : "set"); + writeKeyword(node.kind === 168 /* GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); @@ -102107,7 +105208,7 @@ var ts; writePunctuation("}"); } function emitArrayType(node) { - emit(node.elementType); + emit(node.elementType, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("["); writePunctuation("]"); } @@ -102130,21 +105231,21 @@ var ts; emit(node.type); } function emitOptionalType(node) { - emit(node.type); + emit(node.type, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("?"); } function emitUnionType(node) { - emitList(node, node.types, 516 /* UnionTypeConstituents */); + emitList(node, node.types, 516 /* UnionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitIntersectionType(node) { - emitList(node, node.types, 520 /* IntersectionTypeConstituents */); + emitList(node, node.types, 520 /* IntersectionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitConditionalType(node) { - emit(node.checkType); + emit(node.checkType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writeKeyword("extends"); writeSpace(); - emit(node.extendsType); + emit(node.extendsType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writePunctuation("?"); writeSpace(); @@ -102170,10 +105271,10 @@ var ts; function emitTypeOperator(node) { writeTokenText(node.operator, writeKeyword); writeSpace(); - emit(node.type); + emit(node.type, parenthesizer.parenthesizeMemberOfElementType); } function emitIndexedAccessType(node) { - emit(node.objectType); + emit(node.objectType, parenthesizer.parenthesizeMemberOfElementType); writePunctuation("["); emit(node.indexType); writePunctuation("]"); @@ -102266,7 +105367,7 @@ var ts; writeSpace(); } emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // Expressions @@ -102274,7 +105375,7 @@ var ts; function emitArrayLiteralExpression(node) { var elements = node.elements; var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; - emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitObjectLiteralExpression(node) { ts.forEach(node.properties, generateMemberNames); @@ -102290,13 +105391,13 @@ var ts; } } function emitPropertyAccessExpression(node) { - var expression = ts.cast(emitExpression(node.expression), ts.isExpression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); var token = node.questionDotToken || ts.setTextRangePosEnd(ts.factory.createToken(24 /* DotToken */), node.expression.end, node.name.pos); var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token); var linesAfterDot = getLinesBetweenNodes(node, token, node.name); writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false); var shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ && - mayNeedDotDotForPropertyAccess(expression) && + mayNeedDotDotForPropertyAccess(node.expression) && !writer.hasTrailingComment() && !writer.hasTrailingWhitespace(); if (shouldEmitDotDot) { @@ -102332,27 +105433,27 @@ var ts; } } function emitElementAccessExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitNewExpression(node) { emitTokenWithComment(102 /* NewKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfNew); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitTaggedTemplateExpression(node) { - emitExpression(node.tag); + emitExpression(node.tag, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); writeSpace(); emitExpression(node.template); @@ -102361,12 +105462,12 @@ var ts; writePunctuation("<"); emit(node.type); writePunctuation(">"); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); - emitExpression(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); writeLineSeparatorsAfter(node.expression, node); decreaseIndentIf(indented); emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); @@ -102390,29 +105491,29 @@ var ts; function emitDeleteExpression(node) { emitTokenWithComment(88 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitTypeOfExpression(node) { emitTokenWithComment(111 /* TypeOfKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitVoidExpression(node) { emitTokenWithComment(113 /* VoidKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitAwaitExpression(node) { emitTokenWithComment(130 /* AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitPrefixUnaryExpression(node) { writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { writeSpace(); } - emitExpression(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPrefixUnary); } function shouldEmitWhitespaceBeforeOperand(node) { // In some cases, we need to emit a space between the operator and the operand. One obvious case @@ -102428,84 +105529,101 @@ var ts; // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. var operand = node.operand; - return operand.kind === 214 /* PrefixUnaryExpression */ + return operand.kind === 215 /* PrefixUnaryExpression */ && ((node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */)) || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */))); } function emitPostfixUnaryExpression(node) { - emitExpression(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary); writeTokenText(node.operator, writeOperator); } - var EmitBinaryExpressionState; - (function (EmitBinaryExpressionState) { - EmitBinaryExpressionState[EmitBinaryExpressionState["EmitLeft"] = 0] = "EmitLeft"; - EmitBinaryExpressionState[EmitBinaryExpressionState["EmitRight"] = 1] = "EmitRight"; - EmitBinaryExpressionState[EmitBinaryExpressionState["FinishEmit"] = 2] = "FinishEmit"; - })(EmitBinaryExpressionState || (EmitBinaryExpressionState = {})); - /** - * emitBinaryExpression includes an embedded work stack to attempt to handle as many nested binary expressions - * as possible without creating any additional stack frames. This can only be done when the emit pipeline does - * not require notification/substitution/comment/sourcemap decorations. - */ - function emitBinaryExpression(node) { - var nodeStack = [node]; - var stateStack = [0 /* EmitLeft */]; - var stackIndex = 0; - while (stackIndex >= 0) { - node = nodeStack[stackIndex]; - switch (stateStack[stackIndex]) { - case 0 /* EmitLeft */: { - maybePipelineEmitExpression(node.left); - break; - } - case 1 /* EmitRight */: { - var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */; - var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); - var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); - writeLinesAndIndent(linesBeforeOperator, isCommaOperator); - emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken, node.operatorToken.kind === 100 /* InKeyword */ ? writeKeyword : writeOperator); - emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts - writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); - maybePipelineEmitExpression(node.right); - break; - } - case 2 /* FinishEmit */: { - var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); - var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); - decreaseIndentIf(linesBeforeOperator, linesAfterOperator); - stackIndex--; - break; - } - default: return ts.Debug.fail("Invalid state " + stateStack[stackIndex] + " for emitBinaryExpressionWorker"); + function createEmitBinaryExpression() { + return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined); + function onEnter(node, state) { + if (state) { + state.stackIndex++; + state.preserveSourceNewlinesStack[state.stackIndex] = preserveSourceNewlines; + state.containerPosStack[state.stackIndex] = containerPos; + state.containerEndStack[state.stackIndex] = containerEnd; + state.declarationListContainerEndStack[state.stackIndex] = declarationListContainerEnd; + var emitComments_1 = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node); + var emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node); + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (emitComments_1) + emitCommentsBeforeNode(node); + if (emitSourceMaps) + emitSourceMapsBeforeNode(node); + beforeEmitNode(node); } - } - function maybePipelineEmitExpression(next) { - // Advance the state of this unit of work, - stateStack[stackIndex]++; - // Then actually do the work of emitting the node `next` returned by the prior state - // The following section should be identical to `pipelineEmit` save it assumes EmitHint.Expression and offloads - // binary expression handling, where possible, to the contained work queue - // #region trampolinePipelineEmit - var savedLastNode = lastNode; - var savedLastSubstitution = lastSubstitution; - lastNode = next; - lastSubstitution = undefined; + else { + state = { + stackIndex: 0, + preserveSourceNewlinesStack: [undefined], + containerPosStack: [-1], + containerEndStack: [-1], + declarationListContainerEndStack: [-1], + shouldEmitCommentsStack: [false], + shouldEmitSourceMapsStack: [false], + }; + } + return state; + } + function onLeft(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "left"); + } + function onOperator(operatorToken, _state, node) { + var isCommaOperator = operatorToken.kind !== 27 /* CommaToken */; + var linesBeforeOperator = getLinesBetweenNodes(node, node.left, operatorToken); + var linesAfterOperator = getLinesBetweenNodes(node, operatorToken, node.right); + writeLinesAndIndent(linesBeforeOperator, isCommaOperator); + emitLeadingCommentsOfPosition(operatorToken.pos); + writeTokenNode(operatorToken, operatorToken.kind === 100 /* InKeyword */ ? writeKeyword : writeOperator); + emitTrailingCommentsOfPosition(operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts + writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); + } + function onRight(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "right"); + } + function onExit(node, state) { + var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); + var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); + decreaseIndentIf(linesBeforeOperator, linesAfterOperator); + if (state.stackIndex > 0) { + var savedPreserveSourceNewlines = state.preserveSourceNewlinesStack[state.stackIndex]; + var savedContainerPos = state.containerPosStack[state.stackIndex]; + var savedContainerEnd = state.containerEndStack[state.stackIndex]; + var savedDeclarationListContainerEnd = state.declarationListContainerEndStack[state.stackIndex]; + var shouldEmitComments_1 = state.shouldEmitCommentsStack[state.stackIndex]; + var shouldEmitSourceMaps_1 = state.shouldEmitSourceMapsStack[state.stackIndex]; + afterEmitNode(savedPreserveSourceNewlines); + if (shouldEmitSourceMaps_1) + emitSourceMapsAfterNode(node); + if (shouldEmitComments_1) + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); + state.stackIndex--; + } + } + function maybeEmitExpression(next, parent, side) { + var parenthesizerRule = side === "left" ? + parenthesizer.getParenthesizeLeftSideOfBinaryForOperator(parent.operatorToken.kind) : + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(parent.operatorToken.kind); var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next); - if (pipelinePhase === pipelineEmitWithHint && ts.isBinaryExpression(next)) { - // If the target pipeline phase is emit directly, and the next node's also a binary expression, - // skip all the intermediate indirection and push the expression directly onto the work stack - stackIndex++; - stateStack[stackIndex] = 0 /* EmitLeft */; - nodeStack[stackIndex] = next; + if (pipelinePhase === pipelineEmitWithSubstitution) { + ts.Debug.assertIsDefined(lastSubstitution); + next = parenthesizerRule(ts.cast(lastSubstitution, ts.isExpression)); + pipelinePhase = getNextPipelinePhase(1 /* Substitution */, 1 /* Expression */, next); + lastSubstitution = undefined; } - else { - pipelinePhase(1 /* Expression */, next); + if (pipelinePhase === pipelineEmitWithComments || + pipelinePhase === pipelineEmitWithSourceMaps || + pipelinePhase === pipelineEmitWithHint) { + if (ts.isBinaryExpression(next)) { + return next; + } } - ts.Debug.assert(lastNode === next); - lastNode = savedLastNode; - lastSubstitution = savedLastSubstitution; - // #endregion trampolinePipelineEmit + currentParenthesizerRule = parenthesizerRule; + pipelinePhase(1 /* Expression */, next); } } function emitConditionalExpression(node) { @@ -102513,16 +105631,16 @@ var ts; var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue); var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken); var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse); - emitExpression(node.condition); + emitExpression(node.condition, parenthesizer.parenthesizeConditionOfConditionalExpression); writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); emit(node.questionToken); writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true); - emitExpression(node.whenTrue); + emitExpression(node.whenTrue, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion); writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true); emit(node.colonToken); writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true); - emitExpression(node.whenFalse); + emitExpression(node.whenFalse, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeColon, linesAfterColon); } function emitTemplateExpression(node) { @@ -102532,22 +105650,22 @@ var ts; function emitYieldExpression(node) { emitTokenWithComment(124 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); - emitExpressionWithLeadingSpace(node.expression); + emitExpressionWithLeadingSpace(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } - function emitSpreadExpression(node) { + function emitSpreadElement(node) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitClassExpression(node) { generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); } function emitAsExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); if (node.type) { writeSpace(); writeKeyword("as"); @@ -102556,7 +105674,7 @@ var ts; } } function emitNonNullExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); writeOperator("!"); } function emitMetaProperty(node) { @@ -102599,7 +105717,7 @@ var ts; } } function emitExpressionStatement(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfExpressionStatement); // Emit semicolon in non json files // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { @@ -102616,7 +105734,7 @@ var ts; if (node.elseStatement) { writeLineOrSpace(node, node.thenStatement, node.elseStatement); emitTokenWithComment(90 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); - if (node.elseStatement.kind === 234 /* IfStatement */) { + if (node.elseStatement.kind === 235 /* IfStatement */) { writeSpace(); emit(node.elseStatement); } @@ -102679,7 +105797,7 @@ var ts; emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(156 /* OfKeyword */, node.initializer.end, writeKeyword, node); + emitTokenWithComment(157 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); @@ -102687,7 +105805,7 @@ var ts; } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 250 /* VariableDeclarationList */) { + if (node.kind === 251 /* VariableDeclarationList */) { emit(node); } else { @@ -102724,7 +105842,7 @@ var ts; } pos = writeTokenText(token, writer, pos); if (isSimilarNode && contextNode.end !== pos) { - var isJsxExprContext = contextNode.kind === 283 /* JsxExpression */; + var isJsxExprContext = contextNode.kind === 284 /* JsxExpression */; emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ !isJsxExprContext, /*forceNoNewline*/ isJsxExprContext); } return pos; @@ -102788,7 +105906,7 @@ var ts; emit(node.name); emit(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); @@ -102807,9 +105925,6 @@ var ts; emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } - function emitBlockCallback(_hint, body) { - emitBlockFunctionBody(body); - } function emitSignatureAndBody(node, emitSignatureHead) { var body = node.body; if (body) { @@ -102822,12 +105937,7 @@ var ts; ts.forEach(node.parameters, generateNames); generateNames(node.body); emitSignatureHead(node); - if (onEmitNode) { - onEmitNode(4 /* Unspecified */, body, emitBlockCallback); - } - else { - emitBlockFunctionBody(body); - } + emitBlockFunctionBody(body); popNameGenerationScope(node); if (indentedFlag) { decreaseIndent(); @@ -102836,7 +105946,7 @@ var ts; else { emitSignatureHead(node); writeSpace(); - emitExpression(body); + emitExpression(body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); } } else { @@ -102880,6 +105990,7 @@ var ts; return true; } function emitBlockFunctionBody(body) { + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(body); writeSpace(); writePunctuation("{"); increaseIndent(); @@ -102894,6 +106005,7 @@ var ts; } decreaseIndent(); writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body); + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); @@ -102909,7 +106021,7 @@ var ts; increaseIndent(); } else { - emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset); + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, /*parenthesizerRule*/ undefined, statementOffset); } } function emitClassDeclaration(node) { @@ -102984,7 +106096,7 @@ var ts; var body = node.body; if (!body) return writeTrailingSemicolon(); - while (body.kind === 256 /* ModuleDeclaration */) { + while (body && ts.isModuleDeclaration(body)) { writePunctuation("."); emit(body.name); body = body.body; @@ -103074,7 +106186,9 @@ var ts; emitTokenWithComment(87 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, node.isExportEquals ? + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(62 /* EqualsToken */) : + parenthesizer.parenthesizeExpressionOfExportDefault); writeTrailingSemicolon(); } function emitExportDeclaration(node) { @@ -103246,7 +106360,7 @@ var ts; function emitCaseClause(node) { emitTokenWithComment(81 /* CaseKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { @@ -103307,7 +106421,7 @@ var ts; var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } - emitExpression(initializer); + emitExpression(initializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitShorthandPropertyAssignment(node) { emit(node.name); @@ -103315,13 +106429,13 @@ var ts; writeSpace(); writePunctuation("="); writeSpace(); - emitExpression(node.objectAssignmentInitializer); + emitExpression(node.objectAssignmentInitializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } } function emitSpreadAssignment(node) { if (node.expression) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } } // @@ -103329,7 +106443,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // JSDoc @@ -103337,18 +106451,21 @@ var ts; function emitJSDoc(node) { write("/**"); if (node.comment) { - var lines = node.comment.split(/\r\n?|\n/g); - for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { - var line = lines_2[_a]; - writeLine(); - writeSpace(); - writePunctuation("*"); - writeSpace(); - write(line); + var text = ts.getTextOfJSDocComment(node.comment); + if (text) { + var lines = text.split(/\r\n?|\n/g); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } } } if (node.tags) { - if (node.tags.length === 1 && node.tags[0].kind === 329 /* JSDocTypeTag */ && !node.comment) { + if (node.tags.length === 1 && node.tags[0].kind === 333 /* JSDocTypeTag */ && !node.comment) { writeSpace(); emit(node.tags[0]); } @@ -103393,7 +106510,7 @@ var ts; function emitJSDocTypedefTag(tag) { emitJSDocTagName(tag.tagName); if (tag.typeExpression) { - if (tag.typeExpression.kind === 301 /* JSDocTypeExpression */) { + if (tag.typeExpression.kind === 302 /* JSDocTypeExpression */) { emitJSDocTypeExpression(tag.typeExpression); } else { @@ -103412,7 +106529,7 @@ var ts; emit(tag.fullName); } emitJSDocComment(tag.comment); - if (tag.typeExpression && tag.typeExpression.kind === 312 /* JSDocTypeLiteral */) { + if (tag.typeExpression && tag.typeExpression.kind === 314 /* JSDocTypeLiteral */) { emitJSDocTypeLiteral(tag.typeExpression); } } @@ -103465,9 +106582,10 @@ var ts; emit(tagName); } function emitJSDocComment(comment) { - if (comment) { + var text = ts.getTextOfJSDocComment(comment); + if (text) { writeSpace(); - write(comment); + write(text); } } function emitJSDocTypeExpression(typeExpression) { @@ -103570,7 +106688,7 @@ var ts; emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitTripleSlashDirectivesIfNeeded(node); - emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); + emitList(node, statements, 1 /* MultiLine */, /*parenthesizerRule*/ undefined, index === -1 ? statements.length : index); popNameGenerationScope(node); } // Transformation nodes @@ -103578,7 +106696,7 @@ var ts; emitExpression(node.expression); } function emitCommaList(node) { - emitExpressionList(node, node.elements, 528 /* CommaListElements */); + emitExpressionList(node, node.elements, 528 /* CommaListElements */, /*parenthesizerRule*/ undefined); } /** * Emits any prologue directives at the start of a Statement list, returning the @@ -103724,12 +106842,12 @@ var ts; emit(node); } } - function emitInitializer(node, equalCommentStartPos, container) { + function emitInitializer(node, equalCommentStartPos, container, parenthesizerRule) { if (node) { writeSpace(); emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container); writeSpace(); - emitExpression(node); + emitExpression(node, parenthesizerRule); } } function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { @@ -103744,10 +106862,10 @@ var ts; emit(node); } } - function emitExpressionWithLeadingSpace(node) { + function emitExpressionWithLeadingSpace(node, parenthesizerRule) { if (node) { writeSpace(); - emitExpression(node); + emitExpression(node, parenthesizerRule); } } function emitWithTrailingSpace(node) { @@ -103777,7 +106895,7 @@ var ts; emitList(parentNode, decorators, 2146305 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 53776 /* TypeArguments */); + emitList(parentNode, typeArguments, 53776 /* TypeArguments */, parenthesizer.parenthesizeMemberOfElementType); } function emitTypeParameters(parentNode, typeParameters) { if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures @@ -103816,12 +106934,6 @@ var ts; function emitParametersForIndexSignature(parentNode, parameters) { emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */); } - function emitList(parentNode, children, format, start, count) { - emitNodeList(emit, parentNode, children, format, start, count); - } - function emitExpressionList(parentNode, children, format, start, count) { - emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 - } function writeDelimiter(format) { switch (format & 60 /* DelimitersMask */) { case 0 /* None */: @@ -103844,7 +106956,13 @@ var ts; break; } } - function emitNodeList(emit, parentNode, children, format, start, count) { + function emitList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count); + } + function emitExpressionList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emitExpression, parentNode, children, format, parenthesizerRule, start, count); + } + function emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; @@ -103863,8 +106981,7 @@ var ts; } if (format & 15360 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); - if (isEmpty && !isUndefined) { - // TODO: GH#18217 + if (isEmpty && children) { emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists } } @@ -103873,7 +106990,7 @@ var ts; } if (isEmpty) { // Write a line terminator if the parent node was multi-line - if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && ts.rangeIsOnSingleLine(parentNode, currentSourceFile))) { + if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && (!parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile)))) { writeLine(); } else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) { @@ -103881,6 +106998,7 @@ var ts; } } else { + ts.Debug.type(children); // Write the opening line terminator or leading whitespace. var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; @@ -103915,7 +107033,7 @@ var ts; // a // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline // , - if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { + if (format & 60 /* DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { emitLeadingCommentsOfPosition(previousSibling.end); } writeDelimiter(format); @@ -103948,7 +107066,12 @@ var ts; shouldEmitInterveningComments = mayEmitInterveningComments; } nextListElementPos = child.pos; - emit(child); + if (emit.length === 1) { + emit(child); + } + else { + emit(child, parenthesizerRule); + } if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); shouldDecreaseIndentAfterEmit = false; @@ -103973,7 +107096,7 @@ var ts; // 2 // /* end of element 2 */ // ]; - if (previousSibling && parentNode.end !== previousSibling.end && (format & 60 /* DelimitersMask */) && !skipTrailingComments) { + if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60 /* DelimitersMask */) && !skipTrailingComments) { emitLeadingCommentsOfPosition(hasTrailingComma && (children === null || children === void 0 ? void 0 : children.end) ? children.end : previousSibling.end); } // Decrease the indent, if requested. @@ -103994,8 +107117,7 @@ var ts; onAfterEmitNodeArray(children); } if (format & 15360 /* BracketsMask */) { - if (isEmpty && !isUndefined) { - // TODO: GH#18217 + if (isEmpty && children) { emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists } writePunctuation(getClosingBracket(format)); @@ -104126,7 +107248,7 @@ var ts; } var firstChild_1 = children[0]; if (firstChild_1 === undefined) { - return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; + return !parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } if (firstChild_1.pos === nextListElementPos) { // If this child starts at the beginning of a list item in a parent list, its leading @@ -104150,7 +107272,8 @@ var ts; // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } - if (!ts.positionIsSynthesized(parentNode.pos) && + if (parentNode && + !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || ts.getOriginalNode(firstChild_1.parent) === ts.getOriginalNode(parentNode))) { if (preserveSourceNewlines) { @@ -104173,10 +107296,10 @@ var ts; // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } - else if (!ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode) && previousNode.parent === nextNode.parent) { - if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); }); - } + else if (preserveSourceNewlines && siblingNodePositionsAreComparable(previousNode, nextNode)) { + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); }); + } + else if (!preserveSourceNewlines && !ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode)) { return ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1; } else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) { @@ -104195,9 +107318,9 @@ var ts; } var lastChild = ts.lastOrUndefined(children); if (lastChild === undefined) { - return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; + return !parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } - if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { + if (parentNode && !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { if (preserveSourceNewlines) { var end_1 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end; return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_1, parentNode.end, currentSourceFile, includeComments); }); @@ -104283,7 +107406,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 207 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + while (node.kind === 208 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -104353,84 +107476,84 @@ var ts; if (!node) return; switch (node.kind) { - case 230 /* Block */: + case 231 /* Block */: ts.forEach(node.statements, generateNames); break; - case 245 /* LabeledStatement */: - case 243 /* WithStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 246 /* LabeledStatement */: + case 244 /* WithStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: generateNames(node.statement); break; - case 234 /* IfStatement */: + case 235 /* IfStatement */: generateNames(node.thenStatement); generateNames(node.elseStatement); break; - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: - case 238 /* ForInStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: + case 239 /* ForInStatement */: generateNames(node.initializer); generateNames(node.statement); break; - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: generateNames(node.caseBlock); break; - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: ts.forEach(node.clauses, generateNames); break; - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: ts.forEach(node.statements, generateNames); break; - case 247 /* TryStatement */: + case 248 /* TryStatement */: generateNames(node.tryBlock); generateNames(node.catchClause); generateNames(node.finallyBlock); break; - case 287 /* CatchClause */: + case 288 /* CatchClause */: generateNames(node.variableDeclaration); generateNames(node.block); break; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: generateNames(node.declarationList); break; - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: ts.forEach(node.declarations, generateNames); break; - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: generateNameIfNeeded(node.name); break; - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: generateNameIfNeeded(node.name); if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { ts.forEach(node.parameters, generateNames); generateNames(node.body); } break; - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: ts.forEach(node.elements, generateNames); break; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: generateNames(node.importClause); break; - case 262 /* ImportClause */: + case 263 /* ImportClause */: generateNameIfNeeded(node.name); generateNames(node.namedBindings); break; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: generateNameIfNeeded(node.name); break; - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: generateNameIfNeeded(node.name); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: ts.forEach(node.elements, generateNames); break; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: generateNameIfNeeded(node.propertyName || node.name); break; } @@ -104439,12 +107562,12 @@ var ts; if (!node) return; switch (node.kind) { - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: generateNameIfNeeded(node.name); break; } @@ -104626,23 +107749,23 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 266 /* ExportAssignment */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 267 /* ExportAssignment */: return generateNameForExportDefault(); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return generateNameForClassExpression(); - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return generateNameForMethodOrAccessor(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return makeTempVariableName(0 /* Auto */, /*reserveInNestedScopes*/ true); default: return makeTempVariableName(0 /* Auto */); @@ -104685,25 +107808,45 @@ var ts; } // Comments function pipelineEmitWithComments(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node); + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + emitCommentsBeforeNode(node); + pipelinePhase(hint, node); + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitCommentsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit leading comments + emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + } + } + function emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit trailing comments + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = false; + } + emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitLeadingCommentsOfNode(node, emitFlags, pos, end) { enterComment(); hasWrittenComment = false; - var emitFlags = ts.getEmitFlags(node); - var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; - var isEmittedNode = node.kind !== 335 /* NotEmittedStatement */; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */; var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; // Save current container state on the stack. - var savedContainerPos = containerPos; - var savedContainerEnd = containerEnd; - var savedDeclarationListContainerEnd = declarationListContainerEnd; if ((pos > 0 || end > 0) && pos !== end) { // Emit leading comments if the position is not synthesized and the node // has not opted out from emitting leading comments. if (!skipLeadingComments) { - emitLeadingComments(pos, isEmittedNode); + emitLeadingComments(pos, /*isEmittedNode*/ node.kind !== 339 /* NotEmittedStatement */); } if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments. @@ -104714,23 +107857,17 @@ var ts; containerEnd = end; // To avoid invalid comment emit in a down-level binding pattern, we // keep track of the last declaration list container's end - if (node.kind === 250 /* VariableDeclarationList */) { + if (node.kind === 251 /* VariableDeclarationList */) { declarationListContainerEnd = end; } } } ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); exitComment(); - var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node); - if (emitFlags & 2048 /* NoNestedComments */) { - commentsDisabled = true; - pipelinePhase(hint, node); - commentsDisabled = false; - } - else { - pipelinePhase(hint, node); - } + } + function emitTrailingCommentsOfNode(node, emitFlags, pos, end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { enterComment(); + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); if ((pos > 0 || end > 0) && pos !== end) { // Restore previous container state. @@ -104739,12 +107876,11 @@ var ts; declarationListContainerEnd = savedDeclarationListContainerEnd; // Emit trailing comments if the position is not synthesized and the node // has not opted out from emitting leading comments and is an emitted node. - if (!skipTrailingComments && isEmittedNode) { + if (!skipTrailingComments && node.kind !== 339 /* NotEmittedStatement */) { emitTrailingComments(end); } } exitComment(); - ts.Debug.assert(lastNode === node || lastSubstitution === node); } function emitLeadingSynthesizedComment(comment) { if (comment.hasLeadingNewline || comment.kind === 2 /* SingleLineCommentTrivia */) { @@ -104804,6 +107940,23 @@ var ts; } exitComment(); } + function siblingNodePositionsAreComparable(previousNode, nextNode) { + if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) { + return false; + } + if (nextNode.pos < previousNode.end) { + return false; + } + previousNode = ts.getOriginalNode(previousNode); + nextNode = ts.getOriginalNode(nextNode); + var parent = previousNode.parent; + if (!parent || parent !== nextNode.parent) { + return false; + } + var parentNodeArray = ts.getContainingNodeArray(previousNode); + var prevNodeIndex = parentNodeArray === null || parentNodeArray === void 0 ? void 0 : parentNodeArray.indexOf(previousNode); + return prevNodeIndex !== undefined && prevNodeIndex > -1 && parentNodeArray.indexOf(nextNode) === prevNodeIndex + 1; + } function emitLeadingComments(pos, isEmittedNode) { hasWrittenComment = false; if (isEmittedNode) { @@ -104976,42 +108129,49 @@ var ts; } return node.parsedSourceMap || undefined; } - function pipelineEmitWithSourceMap(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); + function pipelineEmitWithSourceMaps(hint, node) { var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node); - if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) { - pipelinePhase(hint, node); - } - else if (ts.isUnparsedNode(node)) { + emitSourceMapsBeforeNode(node); + pipelinePhase(hint, node); + emitSourceMapsAfterNode(node); + } + function emitSourceMapsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit leading sourcemap + if (ts.isUnparsedNode(node)) { + ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); var parsed = getParsedSourceMap(node.parent); if (parsed && sourceMapGenerator) { sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); } - pipelinePhase(hint, node); } else { - var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; - var emitFlags = ts.getEmitFlags(node); - if (node.kind !== 335 /* NotEmittedStatement */ + var source = sourceMapRange.source || sourceMapSource; + if (node.kind !== 339 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 - && pos >= 0) { - emitSourcePos(source, skipSourceTrivia(source, pos)); + && sourceMapRange.pos >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); } if (emitFlags & 64 /* NoNestedSourceMaps */) { sourceMapsDisabled = true; - pipelinePhase(hint, node); - sourceMapsDisabled = false; } - else { - pipelinePhase(hint, node); + } + } + function emitSourceMapsAfterNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit trailing sourcemap + if (!ts.isUnparsedNode(node)) { + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = false; } - if (node.kind !== 335 /* NotEmittedStatement */ + if (node.kind !== 339 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 - && end >= 0) { - emitSourcePos(source, end); + && sourceMapRange.end >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); } } - ts.Debug.assert(lastNode === node || lastSubstitution === node); } /** * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source @@ -105163,12 +108323,22 @@ var ts; return ts.getBaseFileName(ts.normalizePath(fileName)); } function createCachedFileSystemEntries(rootDir, rootDirPath) { - var resultFromHost = { - files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories(rootDir) || [] - }; - cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); - return resultFromHost; + var _a; + if (!host.realpath || ts.ensureTrailingDirectorySeparator(toPath(host.realpath(rootDir))) === rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); + return resultFromHost; + } + // If the directory is symlink do not cache the result + if ((_a = host.directoryExists) === null || _a === void 0 ? void 0 : _a.call(host, rootDir)) { + cachedReadDirectoryResult.set(rootDirPath, false); + return false; + } + // Non existing directory + return undefined; } /** * If the readDirectory result was already cached, it returns that @@ -105243,17 +108413,32 @@ var ts; } function readDirectory(rootDir, extensions, excludes, includes, depth) { var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { + var rootResult = tryReadDirectory(rootDir, rootDirPath); + var rootSymLinkResult; + if (rootResult !== undefined) { return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir) { var path = toPath(dir); if (path === rootDirPath) { - return result; + return rootResult || getFileSystemEntriesFromHost(dir, path); } - return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + var result = tryReadDirectory(dir, path); + return result !== undefined ? + result || getFileSystemEntriesFromHost(dir, path) : + ts.emptyFileSystemEntries; + } + function getFileSystemEntriesFromHost(dir, path) { + if (rootSymLinkResult && path === rootDirPath) + return rootSymLinkResult; + var result = { + files: ts.map(host.readDirectory(dir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || ts.emptyArray, + directories: host.getDirectories(dir) || ts.emptyArray + }; + if (path === rootDirPath) + rootSymLinkResult = result; + return result; } } function realpath(s) { @@ -105261,7 +108446,7 @@ var ts; } function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { + if (existingResult !== undefined) { // Just clear the cache for now // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated clearCache(); @@ -105321,9 +108506,9 @@ var ts; /** * Updates the map of shared extended config file watches with a new set of extended config files from a base config file of the project */ - function updateSharedExtendedConfigFileWatcher(projectPath, parsed, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath) { + function updateSharedExtendedConfigFileWatcher(projectPath, options, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath) { var _a; - var extendedConfigs = ts.arrayToMap(((_a = parsed === null || parsed === void 0 ? void 0 : parsed.options.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath); + var extendedConfigs = ts.arrayToMap(((_a = options === null || options === void 0 ? void 0 : options.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath); // remove project from all unrelated watchers extendedConfigFilesMap.forEach(function (watcher, extendedConfigFilePath) { if (!extendedConfigs.has(extendedConfigFilePath)) { @@ -105341,12 +108526,12 @@ var ts; // start watching previously unseen extended config extendedConfigFilesMap.set(extendedConfigFilePath, { projects: new ts.Set([projectPath]), - fileWatcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath), + watcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath), close: function () { var existing = extendedConfigFilesMap.get(extendedConfigFilePath); if (!existing || existing.projects.size !== 0) return; - existing.fileWatcher.close(); + existing.watcher.close(); extendedConfigFilesMap.delete(extendedConfigFilePath); }, }); @@ -105354,6 +108539,31 @@ var ts; }); } ts.updateSharedExtendedConfigFileWatcher = updateSharedExtendedConfigFileWatcher; + /** + * Remove the project from the extended config file watchers and close not needed watches + */ + function clearSharedExtendedConfigFileWatcher(projectPath, extendedConfigFilesMap) { + extendedConfigFilesMap.forEach(function (watcher) { + if (watcher.projects.delete(projectPath)) + watcher.close(); + }); + } + ts.clearSharedExtendedConfigFileWatcher = clearSharedExtendedConfigFileWatcher; + /** + * Clean the extendsConfigCache when extended config file has changed + */ + function cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath) { + if (!extendedConfigCache.delete(extendedConfigFilePath)) + return; + extendedConfigCache.forEach(function (_a, key) { + var _b; + var extendedResult = _a.extendedResult; + if ((_b = extendedResult.extendedSourceFiles) === null || _b === void 0 ? void 0 : _b.some(function (extendedFile) { return toPath(extendedFile) === extendedConfigFilePath; })) { + cleanExtendedConfigCache(extendedConfigCache, key, toPath); + } + }); + } + ts.cleanExtendedConfigCache = cleanExtendedConfigCache; /** * Updates the existing missing file watches with the new set of missing files after new program is created */ @@ -105405,7 +108615,7 @@ var ts; ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; /* @internal */ function isIgnoredFileFromWildCardWatching(_a) { - var watchedDirPath = _a.watchedDirPath, fileOrDirectory = _a.fileOrDirectory, fileOrDirectoryPath = _a.fileOrDirectoryPath, configFileName = _a.configFileName, options = _a.options, program = _a.program, extraFileExtensions = _a.extraFileExtensions, currentDirectory = _a.currentDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, writeLog = _a.writeLog; + var watchedDirPath = _a.watchedDirPath, fileOrDirectory = _a.fileOrDirectory, fileOrDirectoryPath = _a.fileOrDirectoryPath, configFileName = _a.configFileName, options = _a.options, program = _a.program, extraFileExtensions = _a.extraFileExtensions, currentDirectory = _a.currentDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, writeLog = _a.writeLog, toPath = _a.toPath; var newPath = ts.removeIgnoredPath(fileOrDirectoryPath); if (!newPath) { writeLog("Project: " + configFileName + " Detected ignored path: " + fileOrDirectory); @@ -105441,7 +108651,8 @@ var ts; } // just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(fileOrDirectoryPath); - var realProgram = isBuilderProgram(program) ? program.getProgramOrUndefined() : program; + var realProgram = ts.isArray(program) ? undefined : isBuilderProgram(program) ? program.getProgramOrUndefined() : program; + var builderProgram = !realProgram && !ts.isArray(program) ? program : undefined; if (hasSourceFile((filePathWithoutExtension + ".ts" /* Ts */)) || hasSourceFile((filePathWithoutExtension + ".tsx" /* Tsx */))) { writeLog("Project: " + configFileName + " Detected output file: " + fileOrDirectory); @@ -105451,7 +108662,9 @@ var ts; function hasSourceFile(file) { return realProgram ? !!realProgram.getSourceFileByPath(file) : - program.getState().fileInfos.has(file); + builderProgram ? + builderProgram.getState().fileInfos.has(file) : + !!ts.find(program, function (rootFile) { return toPath(rootFile) === file; }); } } ts.isIgnoredFileFromWildCardWatching = isIgnoredFileFromWildCardWatching; @@ -105925,7 +109138,7 @@ var ts; var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; var lineContent = file.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); // trim from end - lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + lineContent = lineContent.replace(/\t/g, " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); @@ -106130,38 +109343,31 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, 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 === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames())) { + if (!program || (hasChangedAutomaticTypeDirectiveNames === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames())) return false; - } // If root file names don't match - if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) { + if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) return false; - } var seenResolvedRefs; // If project references don't match - if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + 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)) { + if (program.getSourceFiles().some(sourceFileNotUptoDate)) return false; - } // If any of the missing file paths are now created - if (program.getMissingFilePaths().some(fileExists)) { + if (program.getMissingFilePaths().some(fileExists)) return false; - } var currentOptions = program.getCompilerOptions(); // If the compilation settings do no match, then the program is not up-to-date - if (!ts.compareDataObjects(currentOptions, newOptions)) { + if (!ts.compareDataObjects(currentOptions, newOptions)) return false; - } // If everything matches but the text of config file is changed, // error locations can change for program options, so update the program - if (currentOptions.configFile && newOptions.configFile) { + if (currentOptions.configFile && newOptions.configFile) return currentOptions.configFile.text === newOptions.configFile.text; - } return true; function sourceFileNotUptoDate(sourceFile) { return !sourceFileVersionUptoDate(sourceFile) || @@ -106171,21 +109377,25 @@ var ts; return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName); } function projectReferenceUptoDate(oldRef, newRef, index) { - if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { - return false; - } - return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + return ts.projectReferenceIsEqualTo(oldRef, newRef) && + resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); } function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { if (oldResolvedRef) { - if (ts.contains(seenResolvedRefs, oldResolvedRef)) { - // Assume true + // Assume true + if (ts.contains(seenResolvedRefs, oldResolvedRef)) return true; - } - // If sourceFile for the oldResolvedRef existed, check the version for uptodate - if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + var refPath_1 = resolveProjectReferencePath(oldRef); + var newParsedCommandLine = getParsedCommandLine(refPath_1); + // Check if config file exists + if (!newParsedCommandLine) + return false; + // If change in source file + if (oldResolvedRef.commandLine.options.configFile !== newParsedCommandLine.options.configFile) + return false; + // check file names + if (!ts.arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newParsedCommandLine.fileNames)) return false; - } // Add to seen before checking the referenced paths of this config file (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); // If child project references are upto date, this project reference is uptodate @@ -106195,7 +109405,8 @@ var ts; } // In old program, not able to resolve project reference path, // so if config file doesnt exist, it is uptodate. - return !fileExists(resolveProjectReferencePath(oldRef)); + var refPath = resolveProjectReferencePath(oldRef); + return !getParsedCommandLine(refPath); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -106259,7 +109470,7 @@ var ts; var modulesWithElidedImports = new ts.Map(); // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. var sourceFilesFoundSearchingNodeModules = new ts.Map(); - ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeProgram"); var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHostLike(host); @@ -106274,6 +109485,7 @@ var ts; var hasEmitBlockingDiagnostics = new ts.Map(); var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; + var typeReferenceDirectiveResolutionCache; var actualResolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { @@ -106288,7 +109500,7 @@ var ts; }); }; } else { - moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options); + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName, options); var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } @@ -106297,7 +109509,8 @@ var ts; actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); }; } else { - var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; // TODO: GH#18217 actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } // Map from a stringified PackageId to the source file with that id. @@ -106335,15 +109548,15 @@ var ts; getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect, forEachResolvedProjectReference: forEachResolvedProjectReference }), onProgramCreateComplete = _d.onProgramCreateComplete, fileExists = _d.fileExists, directoryExists = _d.directoryExists; - ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`. var structureIsReused; - ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); structureIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (structureIsReused !== 2 /* Completely */) { processingDefaultLibFiles = []; processingOtherFiles = []; @@ -106381,13 +109594,13 @@ var ts; }); } } - ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); ts.forEach(rootNames, function (name, index) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.RootFile, index: index }); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { - ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile); @@ -106395,7 +109608,7 @@ var ts; for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i], { kind: ts.FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: (_b = resolutions[i]) === null || _b === void 0 ? void 0 : _b.packageId }); } - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // Do not process the default library if: // - The '--noLib' flag is used. @@ -106436,12 +109649,25 @@ var ts; host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); } } - oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference) { - if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { - host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + if (!host.getParsedCommandLine) { + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference) { + if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + } + }); + } + } + // Release commandlines that new program does not use + if (oldProgram && host.onReleaseParsedCommandLine) { + forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, parent, index) { + var oldReference = (parent === null || parent === void 0 ? void 0 : parent.commandLine.projectReferences[index]) || oldProgram.getProjectReferences()[index]; + var oldRefPath = resolveProjectReferencePath(oldReference); + if (!(projectReferenceRedirects === null || projectReferenceRedirects === void 0 ? void 0 : projectReferenceRedirects.has(toPath(oldRefPath)))) { + host.onReleaseParsedCommandLine(oldRefPath, oldResolvedRef, oldProgram.getCompilerOptions()); } }); } + typeReferenceDirectiveResolutionCache = undefined; // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; var program = { @@ -106470,7 +109696,6 @@ var ts; getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, - getTypeCatalog: function () { return getDiagnosticsProducingTypeChecker().getTypeCatalog(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getInstantiationCount: function () { return getDiagnosticsProducingTypeChecker().getInstantiationCount(); }, getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); }, @@ -106518,19 +109743,19 @@ var ts; verifyCompilerOptions(); ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return program; function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) { if (!moduleNames.length) return ts.emptyArray; var containingFileName = ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); var redirectedReference = getRedirectReferenceForResolution(containingFile); - ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveModule"); var result = actualResolveModuleNamesWorker(moduleNames, containingFileName, reusedNames, redirectedReference); ts.performance.mark("afterResolveModule"); ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile) { @@ -106538,12 +109763,12 @@ var ts; return []; var containingFileName = !ts.isString(containingFile) ? ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile; var redirectedReference = !ts.isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined; - ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveTypeReference"); var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference); ts.performance.mark("afterResolveTypeReference"); ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function getRedirectReferenceForResolution(file) { @@ -106636,13 +109861,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_14 = []; + var result_15 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_14.push(resolvedModule); + result_15.push(resolvedModule); } - return result_14; + return result_15; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -106753,7 +109978,9 @@ var ts; var newResolvedRef = parseProjectReferenceConfigFile(newRef); if (oldResolvedRef) { // Resolved project reference has gone missing or changed - return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + return !newResolvedRef || + newResolvedRef.sourceFile !== oldResolvedRef.sourceFile || + !ts.arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newResolvedRef.commandLine.fileNames); } else { // A previously-unresolved reference may be resolved now @@ -107015,7 +110242,7 @@ var ts; } function emitBuildInfo(writeFileCallback) { ts.Debug.assert(!ts.outFile(options)); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeEmit"); var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), /*targetSourceFile*/ undefined, @@ -107024,7 +110251,7 @@ var ts; /*onlyBuildInfo*/ true); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return emitResult; } function getResolvedProjectReferences() { @@ -107070,9 +110297,9 @@ var ts; return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) { - ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); var result = runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function isEmitBlocked(emitFileName) { @@ -107276,22 +110503,22 @@ var ts; // Return directly from the case if the given node doesnt want to visit each child // Otherwise break to visit each child switch (parent.kind) { - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?")); return "skip"; } // falls through - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: - case 249 /* VariableDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: + case 250 /* VariableDeclaration */: // type annotation if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files)); @@ -107299,58 +110526,58 @@ var ts; } } switch (node.kind) { - case 262 /* ImportClause */: + case 263 /* ImportClause */: if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type")); return "skip"; } break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type")); return "skip"; } break; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files)); return "skip"; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: var heritageClause = node; if (heritageClause.token === 116 /* ImplementsKeyword */) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: var interfaceKeyword = ts.tokenToString(117 /* InterfaceKeyword */); ts.Debug.assertIsDefined(interfaceKeyword); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword)); return "skip"; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var moduleKeyword = node.flags & 16 /* Namespace */ ? ts.tokenToString(140 /* NamespaceKeyword */) : ts.tokenToString(139 /* ModuleKeyword */); ts.Debug.assertIsDefined(moduleKeyword); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword)); return "skip"; - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files)); return "skip"; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(91 /* EnumKeyword */)); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword)); return "skip"; - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files)); return "skip"; - case 224 /* AsExpression */: + case 225 /* AsExpression */: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files)); return "skip"; - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } } @@ -107359,29 +110586,29 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning)); } switch (parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: // Check type parameters if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files)); return "skip"; } // falls through - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // Check modifiers if (nodes === parent.modifiers) { - checkModifiers(parent.modifiers, parent.kind === 232 /* VariableStatement */); + checkModifiers(parent.modifiers, parent.kind === 233 /* VariableStatement */); return "skip"; } break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // Check modifiers of property declaration if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { @@ -107393,19 +110620,19 @@ var ts; return "skip"; } break; - case 160 /* Parameter */: + case 161 /* Parameter */: // Check modifiers of parameter declaration if (nodes === parent.modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 223 /* ExpressionWithTypeArguments */: - case 274 /* JsxSelfClosingElement */: - case 275 /* JsxOpeningElement */: - case 205 /* TaggedTemplateExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 224 /* ExpressionWithTypeArguments */: + case 275 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 206 /* TaggedTemplateExpression */: // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files)); @@ -107430,6 +110657,7 @@ var ts; case 142 /* ReadonlyKeyword */: case 133 /* DeclareKeyword */: case 125 /* AbstractKeyword */: + case 156 /* OverrideKeyword */: diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind))); break; // These are all legal modifiers. @@ -107733,13 +110961,13 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { - ts.tracing.push("program" /* Program */, "findSourceFile", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "findSourceFile", { fileName: fileName, isDefaultLib: isDefaultLib || undefined, fileIncludeKind: ts.FileIncludeKind[reason.kind], }); var result = findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { @@ -107998,9 +111226,9 @@ var ts; } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { - ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { // If we already found this library as a primary reference - nothing to do @@ -108071,12 +111299,14 @@ var ts; return host.getCanonicalFileName(fileName); } function processImportedModules(file) { + var _a; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var resolutions = resolveModuleNamesReusingOldState(moduleNames, file); ts.Debug.assert(resolutions.length === moduleNames.length); + var optionsForFile = (useSourceOfProjectReferenceRedirect ? (_a = getRedirectReferenceForResolution(file)) === null || _a === void 0 ? void 0 : _a.commandLine.options : undefined) || options; for (var index = 0; index < moduleNames.length; index++) { var resolution = resolutions[index]; ts.setResolvedModule(file, moduleNames[index], resolution); @@ -108099,11 +111329,11 @@ var ts; // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') // This may still end up being an untyped module -- the file won't be included but imports will be allowed. var shouldAddFile = resolvedFileName - && !getResolutionDiagnostic(options, resolution) - && !options.noResolve + && !getResolutionDiagnostic(optionsForFile, resolution) + && !optionsForFile.noResolve && index < file.imports.length && !elideImport - && !(isJsFile && !ts.getAllowJSCompilerOption(options)) + && !(isJsFile && !ts.getAllowJSCompilerOption(optionsForFile)) && (ts.isInJSFile(file.imports[index]) || !(file.imports[index].flags & 4194304 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); @@ -108306,6 +111536,9 @@ var ts; if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } + if (options.preserveConstEnums === false) { + createDiagnosticForOptionName(ts.Diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled, "preserveConstEnums", "isolatedModules"); + } var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); @@ -108336,9 +111569,10 @@ var ts; 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 + // there has to be common source directory if user specified --outdir || --rootDir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted if (options.outDir || // there is --outDir specified + options.rootDir || // there is --rootDir specified options.sourceRoot || // there is --sourceRoot specified options.mapRoot) { // there is --mapRoot specified // Precalculate and cache the common source directory @@ -108835,7 +112069,7 @@ var ts; } function handleDirectoryCouldBeSymlink(directory) { var _a; - if (!host.getResolvedProjectReferences()) + if (!host.getResolvedProjectReferences() || ts.containsIgnoredPath(directory)) return; // Because we already watch node_modules, handle symlinks in there if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart)) @@ -108852,7 +112086,7 @@ var ts; symlinkCache.setSymlinkedDirectory(directoryPath, false); return; } - symlinkCache.setSymlinkedDirectory(directoryPath, { + symlinkCache.setSymlinkedDirectory(directory, { real: ts.ensureTrailingDirectorySeparator(real), realPath: realPath }); @@ -109128,12 +112362,15 @@ var ts; // From ambient modules for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { var ambientModule = _g[_f]; - if (ambientModule.declarations.length > 1) { + if (ambientModule.declarations && ambientModule.declarations.length > 1) { addReferenceFromAmbientModule(ambientModule); } } return referencedFiles; function addReferenceFromAmbientModule(symbol) { + if (!symbol.declarations) { + return; + } // Add any file other than our own as reference for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; @@ -109158,7 +112395,7 @@ var ts; /** * Creates the state of file references and signature for the new program from oldState if it is safe */ - function create(newProgram, getCanonicalFileName, oldState) { + function create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { var fileInfos = new ts.Map(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? new ts.Map() : undefined; var exportedModulesMap = referencedMap ? new ts.Map() : undefined; @@ -109184,13 +112421,14 @@ var ts; } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) }); + fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined }); } return { fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState }; } BuilderState.create = create; @@ -109212,6 +112450,7 @@ var ts; referencedMap: state.referencedMap && new ts.Map(state.referencedMap), exportedModulesMap: state.exportedModulesMap && new ts.Map(state.exportedModulesMap), hasCalledUpdateShapeSignature: new ts.Set(state.hasCalledUpdateShapeSignature), + useFileVersionAsSignature: state.useFileVersionAsSignature, }; } BuilderState.clone = clone; @@ -109267,23 +112506,12 @@ var ts; return ts.Debug.fail(); var prevSignature = info.signature; var latestSignature; - if (sourceFile.isDeclarationFile) { - latestSignature = sourceFile.version; - if (exportedModulesMapCache && latestSignature !== prevSignature) { - // All the references in this file are exported - var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined; - exportedModulesMapCache.set(sourceFile.resolvedPath, references || false); - } - } - else { + if (!sourceFile.isDeclarationFile && !state.useFileVersionAsSignature) { var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken, /*customTransformers*/ undefined, /*forceDtsEmit*/ true); - var firstDts_1 = emitOutput_1.outputFiles && - programOfThisState.getCompilerOptions().declarationMap ? - emitOutput_1.outputFiles.length > 1 ? emitOutput_1.outputFiles[1] : undefined : - emitOutput_1.outputFiles.length > 0 ? emitOutput_1.outputFiles[0] : undefined; + var firstDts_1 = ts.firstOrUndefined(emitOutput_1.outputFiles); if (firstDts_1) { ts.Debug.assert(ts.fileExtensionIs(firstDts_1.name, ".d.ts" /* Dts */), "File extension for signature expected to be dts", function () { return "Found: " + ts.getAnyExtensionFromPath(firstDts_1.name) + " for " + firstDts_1.name + ":: All output files: " + JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; })); }); latestSignature = (computeHash || ts.generateDjb2Hash)(firstDts_1.text); @@ -109291,12 +112519,18 @@ var ts; updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache); } } - else { - latestSignature = prevSignature; // TODO: GH#18217 + } + // Default is to use file version as signature + if (latestSignature === undefined) { + latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + // All the references in this file are exported + var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined; + exportedModulesMapCache.set(sourceFile.resolvedPath, references || false); } } cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature); - return !prevSignature || latestSignature !== prevSignature; + return latestSignature !== prevSignature; } BuilderState.updateShapeSignature = updateShapeSignature; /** @@ -109416,7 +112650,7 @@ var ts; */ function isFileAffectingGlobalScope(sourceFile) { return containsGlobalScopeAugmentation(sourceFile) || - !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + !ts.isExternalOrCommonJsModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); } /** * Gets all files of the program excluding the default library file @@ -109504,8 +112738,8 @@ var ts; /** * Create the state so that we can iterate on changedFiles/affected files */ - function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { - var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); state.compilerOptions = compilerOptions; @@ -109743,6 +112977,7 @@ var ts; * This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change */ function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash) { + var _a; removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath); // If affected files is everything except default library, then nothing more to do if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) { @@ -109756,8 +112991,15 @@ var ts; removeSemanticDiagnosticsOf(state, f.resolvedPath); }); } + // When a change affects the global scope, all files are considered to be affected without updating their signature + // That means when affected file is handled, its signature can be out of date + // To avoid this, ensure that we update the signature for any affected file in this scenario. + ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap); return; } + else { + ts.Debug.assert(state.hasCalledUpdateShapeSignature.has(affectedFile.resolvedPath) || ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.has(affectedFile.resolvedPath)), "Signature not updated for affected file: " + affectedFile.fileName); + } if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) { forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); }); } @@ -109969,83 +113211,116 @@ var ts; return undefined; var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory(); var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); - var fileInfos = {}; - state.fileInfos.forEach(function (value, key) { + var fileNames = []; + var fileNameToFileId = new ts.Map(); + var fileIdsList; + var fileNamesToFileIdListId; + var fileInfos = ts.arrayFrom(state.fileInfos.entries(), function (_a) { + var key = _a[0], value = _a[1]; + // Ensure fileId + var fileId = toFileId(key); + ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope }; + var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + return value.version === actualSignature ? + value.affectsGlobalScope ? + { version: value.version, signature: undefined, affectsGlobalScope: true } : + value.version : + actualSignature !== undefined ? + signature === undefined ? + value : + { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope } : + { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope }; }); - var result = { - fileInfos: fileInfos, - options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath) - }; + var referencedMap; if (state.referencedMap) { - var referencedMap = {}; - for (var _i = 0, _a = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { - var key = _a[_i]; - referencedMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.referencedMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); - } - result.referencedMap = referencedMap; + referencedMap = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive).map(function (key) { return [ + toFileId(key), + toFileIdListId(state.referencedMap.get(key)) + ]; }); } + var exportedModulesMap; if (state.exportedModulesMap) { - var exportedModulesMap = {}; - for (var _b = 0, _c = ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) { - var key = _c[_b]; + exportedModulesMap = ts.mapDefined(ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive), function (key) { var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key); // Not in temporary cache, use existing value if (newValue === undefined) - exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.exportedModulesMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); + return [toFileId(key), toFileIdListId(state.exportedModulesMap.get(key))]; // Value in cache and has updated value map, use that else if (newValue) - exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); - } - result.exportedModulesMap = exportedModulesMap; + return [toFileId(key), toFileIdListId(newValue)]; + }); } + var semanticDiagnosticsPerFile; if (state.semanticDiagnosticsPerFile) { - var semanticDiagnosticsPerFile = []; - for (var _d = 0, _e = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) { - var key = _e[_d]; + for (var _i = 0, _a = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var key = _a[_i]; var value = state.semanticDiagnosticsPerFile.get(key); - semanticDiagnosticsPerFile.push(value.length ? + (semanticDiagnosticsPerFile || (semanticDiagnosticsPerFile = [])).push(value.length ? [ - relativeToBuildInfo(key), + toFileId(key), state.hasReusableDiagnostic ? value : convertToReusableDiagnostics(value, relativeToBuildInfo) ] : - relativeToBuildInfo(key)); + toFileId(key)); } - result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile; } + var affectedFilesPendingEmit; if (state.affectedFilesPendingEmit) { - var affectedFilesPendingEmit = []; var seenFiles = new ts.Set(); - for (var _f = 0, _g = state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(ts.compareStringsCaseSensitive); _f < _g.length; _f++) { - var path = _g[_f]; + for (var _b = 0, _c = state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) { + var path = _c[_b]; if (ts.tryAddToSet(seenFiles, path)) { - affectedFilesPendingEmit.push([relativeToBuildInfo(path), state.affectedFilesPendingEmitKind.get(path)]); + (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push([toFileId(path), state.affectedFilesPendingEmitKind.get(path)]); } } - result.affectedFilesPendingEmit = affectedFilesPendingEmit; } - return result; + return { + fileNames: fileNames, + fileInfos: fileInfos, + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + fileIdsList: fileIdsList, + referencedMap: referencedMap, + exportedModulesMap: exportedModulesMap, + semanticDiagnosticsPerFile: semanticDiagnosticsPerFile, + affectedFilesPendingEmit: affectedFilesPendingEmit, + }; function relativeToBuildInfoEnsuringAbsolutePath(path) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory)); } function relativeToBuildInfo(path) { return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName)); } + function toFileId(path) { + var fileId = fileNameToFileId.get(path); + if (fileId === undefined) { + fileNames.push(relativeToBuildInfo(path)); + fileNameToFileId.set(path, fileId = fileNames.length); + } + return fileId; + } + function toFileIdListId(set) { + var fileIds = ts.arrayFrom(set.keys(), toFileId).sort(ts.compareValues); + var key = fileIds.join(); + var fileIdListId = fileNamesToFileIdListId === null || fileNamesToFileIdListId === void 0 ? void 0 : fileNamesToFileIdListId.get(key); + if (fileIdListId === undefined) { + (fileIdsList || (fileIdsList = [])).push(fileIds); + (fileNamesToFileIdListId || (fileNamesToFileIdListId = new ts.Map())).set(key, fileIdListId = fileIdsList.length); + } + return fileIdListId; + } } - function convertToReusableCompilerOptions(options, relativeToBuildInfo) { - var result = {}; + function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { + var result; var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo); + for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var name = _a[_i]; + var optionInfo = optionsNameMap.get(name.toLowerCase()); + if ((optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || name === "skipLibCheck" || name === "skipDefaultLibCheck") { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); } } - if (result.configFilePath) { - result.configFilePath = relativeToBuildInfo(result.configFilePath); - } return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { @@ -110137,7 +113412,7 @@ var ts; * Computing hash to for signature verification */ var computeHash = ts.maybeBind(host, host.createHash); - var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState, host.disableUseFileVersionAsSignature); var backupState; newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); }; // To ensure that we arent storing any references to old program or new program without state @@ -110361,37 +113636,31 @@ var ts; state.affectedFilesPendingEmitIndex = 0; } } - function getMapOfReferencedSet(mapLike, toPath) { - if (!mapLike) - return undefined; - var map = new ts.Map(); - // Copies keys/values from template. Note that for..in will not throw if - // template is undefined, and instead will just exit the loop. - for (var key in mapLike) { - if (ts.hasProperty(mapLike, key)) { - map.set(toPath(key), new ts.Set(mapLike[key].map(toPath))); - } - } - return map; + function toBuilderStateFileInfo(fileInfo) { + return ts.isString(fileInfo) ? + { version: fileInfo, signature: fileInfo, affectsGlobalScope: undefined } : + ts.isString(fileInfo.signature) ? + fileInfo : + { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope }; } + ts.toBuilderStateFileInfo = toBuilderStateFileInfo; function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { + var _a; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var filePaths = program.fileNames.map(toPath); + var filePathsSetList = (_a = program.fileIdsList) === null || _a === void 0 ? void 0 : _a.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); var fileInfos = new ts.Map(); - for (var key in program.fileInfos) { - if (ts.hasProperty(program.fileInfos, key)) { - fileInfos.set(toPath(key), program.fileInfos[key]); - } - } + program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); var state = { fileInfos: fileInfos, - compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), - referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), - exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), - semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + referencedMap: toMapOfReferencedSet(program.referencedMap), + exportedModulesMap: toMapOfReferencedSet(program.exportedModulesMap), + semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), hasReusableDiagnostic: true, - affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }), - affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }, function (value) { return value[1]; }), + affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), + affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, }; return { @@ -110424,6 +113693,15 @@ var ts; function toAbsolutePath(path) { return ts.getNormalizedAbsolutePath(path, buildInfoDirectory); } + function toFilePath(fileId) { + return filePaths[fileId - 1]; + } + function toFilePathsSet(fileIdsListId) { + return filePathsSetList[fileIdsListId - 1]; + } + function toMapOfReferencedSet(referenceMap) { + return referenceMap && ts.arrayToMap(referenceMap, function (value) { return toFilePath(value[0]); }, function (value) { return toFilePathsSet(value[1]); }); + } } ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { @@ -110536,9 +113814,9 @@ var ts; var resolutionsWithFailedLookups = []; var resolvedFileToResolution = ts.createMultiMap(); var hasChangedAutomaticTypeDirectiveNames = false; - var failedLookupChecks = []; - var startsWithPathChecks = []; - var isInDirectoryChecks = []; + var failedLookupChecks; + var startsWithPathChecks; + var isInDirectoryChecks; var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. @@ -110547,9 +113825,12 @@ var ts; var resolvedModuleNames = new ts.Map(); var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); - var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var moduleResolutionCache = ts.createModuleResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, perDirectoryResolvedModuleNames, nonRelativeModuleNameCache); var resolvedTypeReferenceDirectives = new ts.Map(); var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); + var typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, moduleResolutionCache.getPackageJsonInfoCache(), perDirectoryResolvedTypeReferenceDirectives); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -110581,6 +113862,7 @@ var ts; invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, createHasInvalidatedResolution: createHasInvalidatedResolution, + isFileWithInvalidatedNonRelativeUnresolvedImports: isFileWithInvalidatedNonRelativeUnresolvedImports, updateTypeRootsWatch: updateTypeRootsWatch, closeTypeRootsWatch: closeTypeRootsWatch, clear: clear @@ -110606,9 +113888,9 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) clearPerDirectoryResolutions(); @@ -110644,9 +113926,8 @@ var ts; isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { - perDirectoryResolvedModuleNames.clear(); - nonRelativeModuleNameCache.clear(); - perDirectoryResolvedTypeReferenceDirectives.clear(); + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } @@ -110673,7 +113954,7 @@ var ts; if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results - var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; if (resolvedModule) { // Modify existing resolution so its saved in the directory cache as well primaryResult.resolvedModule = resolvedModule; @@ -110684,6 +113965,9 @@ var ts; // Default return the result from the first pass return primaryResult; } + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + return ts.resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache); + } function resolveNamesWithLocalCache(_a) { var _b; var names = _a.names, containingFile = _a.containingFile, redirectedReference = _a.redirectedReference, cache = _a.cache, perDirectoryCacheWithRedirects = _a.perDirectoryCacheWithRedirects, loader = _a.loader, getResolutionWithResolvedFileName = _a.getResolutionWithResolvedFileName, shouldRetryResolution = _a.shouldRetryResolution, reusedNames = _a.reusedNames, logChanges = _a.logChanges; @@ -110771,7 +114055,7 @@ var ts; redirectedReference: redirectedReference, cache: resolvedTypeReferenceDirectives, perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives, - loader: ts.resolveTypeReferenceDirective, + loader: resolveTypeReferenceDirective, getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective, shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, }); @@ -111046,7 +114330,7 @@ var ts; if (isCreatingWatchedDirectory) { // Watching directory is created // Invalidate any resolution has failed lookup in this directory - isInDirectoryChecks.push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); } else { // If something to do with folder/file starting with "." in node_modules folder, skip it @@ -111064,8 +114348,8 @@ var ts; if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory - failedLookupChecks.push(fileOrDirectoryPath); - startsWithPathChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { @@ -111076,27 +114360,33 @@ var ts; return false; } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created - failedLookupChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + // If the invalidated file is from a node_modules package, invalidate everything else + // in the package since we might not get notifications for other files in the package. + // This hardens our logic against unreliable file watchers. + var packagePath = ts.parseNodeModuleFromPath(fileOrDirectoryPath); + if (packagePath) + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks.length && !startsWithPathChecks.length && !isInDirectoryChecks.length) { + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { return false; } var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { return resolution.failedLookupLocations.some(function (location) { var locationPath = resolutionHost.toPath(location); return ts.contains(failedLookupChecks, locationPath) || - startsWithPathChecks.some(function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath); }) || - isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); }); + ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || + (isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); })); }); } function closeTypeRootsWatch() { @@ -111247,6 +114537,9 @@ var ts; return [ambient]; var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); + if (!moduleSourceFile) { + return []; + } var modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host); var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); var existingSpecifier = ts.forEach(modulePaths, function (modulePath) { return ts.forEach(host.getFileIncludeReasons().get(ts.toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)), function (reason) { @@ -111317,7 +114610,7 @@ var ts; if (!baseUrl && !paths || relativePreference === 0 /* Relative */) { return relativePath; } - var baseDirectory = ts.getPathsBasePath(compilerOptions, host) || baseUrl; + var baseDirectory = ts.getNormalizedAbsolutePath(ts.getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory()); var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName); if (!relativeToBaseUrl) { return relativePath; @@ -111332,7 +114625,9 @@ var ts; return nonRelative; } if (relativePreference === 3 /* ExternalNonRelative */) { - var projectDirectory = host.getCurrentDirectory(); + var projectDirectory = compilerOptions.configFilePath ? + ts.toPath(ts.getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) : + info.getCanonicalFileName(host.getCurrentDirectory()); var modulePath = ts.toPath(moduleFileName, projectDirectory, getCanonicalFileName); var sourceIsInternal = ts.startsWith(sourceDirectory, projectDirectory); var targetIsInternal = ts.startsWith(modulePath, projectDirectory); @@ -111384,12 +114679,8 @@ var ts; return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined; }) || false; } - function numberOfDirectorySeparators(str) { - var match = str.match(/\//g); - return match ? match.length : 0; - } function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) { - return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareValues(numberOfDirectorySeparators(a.path), numberOfDirectorySeparators(b.path)); + return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareNumberOfDirectorySeparators(a.path, b.path); } function getNearestAncestorDirectoryWithPackageJson(host, fileName) { if (host.getNearestAncestorDirectoryWithPackageJson) { @@ -111403,40 +114694,49 @@ var ts; var getCanonicalFileName = ts.hostGetCanonicalFileName(host); var cwd = host.getCurrentDirectory(); var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined; - var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray; + var importedPath = ts.toPath(importedFileName, cwd, getCanonicalFileName); + var redirects = host.redirectTargetsMap.get(importedPath) || ts.emptyArray; var importedFileNames = __spreadArray(__spreadArray(__spreadArray([], (referenceRedirect ? [referenceRedirect] : ts.emptyArray)), [importedFileName]), redirects); var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + var shouldFilterIgnoredPaths = !ts.every(targets, ts.containsIgnoredPath); if (!preferSymlinks) { - var result_15 = ts.forEach(targets, function (p) { return cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + // Symlinks inside ignored paths are already filtered out of the symlink cache, + // so we only need to remove them from the realpath filenames. + var result_16 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_16) + return result_16; } var links = host.getSymlinkCache ? host.getSymlinkCache() : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd); - var symlinkedDirectories = links.getSymlinkedDirectories(); - var useCaseSensitiveFileNames = !host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames(); - var result = symlinkedDirectories && ts.forEachEntry(symlinkedDirectories, function (resolved, path) { - if (resolved === false) - return undefined; - if (ts.startsWithDirectory(importingFileName, resolved.realPath, getCanonicalFileName)) { - return undefined; // Don't want to a package to globally import from itself + var symlinkedDirectories = links.getSymlinkedDirectoriesByRealpath(); + var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); + var result = symlinkedDirectories && ts.forEachAncestorDirectory(ts.getDirectoryPath(fullImportedFileName), function (realPathDirectory) { + var symlinkDirectories = symlinkedDirectories.get(ts.ensureTrailingDirectorySeparator(ts.toPath(realPathDirectory, cwd, getCanonicalFileName))); + if (!symlinkDirectories) + return undefined; // Continue to ancestor directory + // Don't want to a package to globally import from itself (importNameCodeFix_symlink_own_package.ts) + if (ts.startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) { + return false; // Stop search, each ancestor directory will also hit this condition } return ts.forEach(targets, function (target) { - if (!ts.containsPath(resolved.real, target, !useCaseSensitiveFileNames)) { + if (!ts.startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) { return; } - var relative = ts.getRelativePathFromDirectory(resolved.real, target, getCanonicalFileName); - var option = ts.resolvePath(path, relative); - if (!host.fileExists || host.fileExists(option)) { - var result_16 = cb(option, target === referenceRedirect); - if (result_16) - return result_16; + var relative = ts.getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName); + for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { + var symlinkDirectory = symlinkDirectories_1[_i]; + var option = ts.resolvePath(symlinkDirectory, relative); + var result_17 = cb(option, target === referenceRedirect); + shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths + if (result_17) + return result_17; } }); }); - return result || - (preferSymlinks ? ts.forEach(targets, function (p) { return cb(p, p === referenceRedirect); }) : undefined); + return result || (preferSymlinks + ? ts.forEach(targets, function (p) { return shouldFilterIgnoredPaths && ts.containsIgnoredPath(p) ? undefined : cb(p, p === referenceRedirect); }) + : undefined); } moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule; /** @@ -111444,8 +114744,14 @@ var ts; * Symlinks will be returned first so they are preferred over the real path. */ function getAllModulePaths(importingFileName, importedFileName, host) { - var cwd = host.getCurrentDirectory(); + var _a; + var cache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + if (cache) { + var cached = cache.get(importingFileName, ts.toPath(importedFileName, host.getCurrentDirectory(), getCanonicalFileName)); + if (typeof cached === "object") + return cached; + } var allFileNames = new ts.Map(); var importedFileFromNodeModules = false; forEachFileNameOfModule(importingFileName, importedFileName, host, @@ -111457,7 +114763,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_24 = function (directory) { + var _loop_26 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -111480,10 +114786,10 @@ var ts; out_directory_1 = directory; }; var out_directory_1; - for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_7 = _loop_24(directory); + for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { + var state_9 = _loop_26(directory); directory = out_directory_1; - if (state_7 === "break") + if (state_9 === "break") break; } if (allFileNames.size) { @@ -111492,10 +114798,14 @@ var ts; remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators); sortedPaths.push.apply(sortedPaths, remainingPaths); } + if (cache) { + cache.set(importingFileName, ts.toPath(importedFileName, host.getCurrentDirectory(), getCanonicalFileName), sortedPaths); + } return sortedPaths; } function tryGetModuleNameFromAmbientModule(moduleSymbol, checker) { - var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); + var _a; + var decl = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { return decl.name.text; } @@ -111551,7 +114861,7 @@ var ts; ts.startsWith(relativeToBaseUrl, prefix) && ts.endsWith(relativeToBaseUrl, suffix) || !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); return key.replace("*", matchedStar); } } @@ -111855,10 +115165,10 @@ var ts; } ts.createWatchStatusReporter = createWatchStatusReporter; /** Parses config file using System interface */ - function parseConfigFileWithSystem(configFileName, optionsToExtend, watchOptionsToExtend, system, reportDiagnostic) { + function parseConfigFileWithSystem(configFileName, optionsToExtend, extendedConfigCache, watchOptionsToExtend, system, reportDiagnostic) { var host = system; host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; - var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, /*extendedConfigCache*/ undefined, watchOptionsToExtend); + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend); host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; } @@ -112126,7 +115436,10 @@ var ts; MissingFile: "Missing file", WildcardDirectory: "Wild card directory", FailedLookupLocations: "Failed Lookup Locations", - TypeRoots: "Type roots" + TypeRoots: "Type roots", + ConfigFileOfReferencedProject: "Config file of referened project", + ExtendedConfigOfReferencedProject: "Extended config file of referenced project", + WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project", }; function createWatchFactory(host, options) { var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; @@ -112173,6 +115486,7 @@ var ts; getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }), createHash: ts.maybeBind(host, host.createHash), readDirectory: ts.maybeBind(host, host.readDirectory), + disableUseFileVersionAsSignature: host.disableUseFileVersionAsSignature, }; function writeFile(fileName, text, writeByteOrderMark, onError) { try { @@ -112230,7 +115544,8 @@ var ts; createDirectory: function (path) { return system.createDirectory(path); }, writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, createHash: ts.maybeBind(system, system.createHash), - createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram + createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, + disableUseFileVersionAsSignature: system.disableUseFileVersionAsSignature, }; } ts.createProgramHost = createProgramHost; @@ -112318,6 +115633,7 @@ var ts; if (system === void 0) { system = ts.sys; } var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system); host.createHash = ts.maybeBind(system, system.createHash); + host.disableUseFileVersionAsSignature = system.disableUseFileVersionAsSignature; ts.setGetSourceFileAsHashVersioned(host, system); ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); }); return host; @@ -112361,11 +115677,13 @@ var ts; function createWatchProgram(host) { var builderProgram; var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc - var extendedConfigFilesMap; // Map of file watchers for the extended config files var missingFilesMap; // Map of file watchers for the missing files var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file var timerToUpdateProgram; // timer callback to recompile the program var timerToInvalidateFailedLookupResolutions; // timer callback to invalidate resolutions for changes in failed lookup locations + var parsedConfigs; // Parsed commandline and watching cached for referenced projects + var sharedExtendedConfigFileWatchers; // Map of file watchers for extended files, shared between different referenced projects + var extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info var missingFilePathsRequestedForRelease; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations @@ -112415,6 +115733,7 @@ var ts; compilerHost.getNewLine = function () { return newLine; }; compilerHost.fileExists = fileExists; compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile; + compilerHost.onReleaseParsedCommandLine = onReleaseParsedCommandLine; // Members for ResolutionCacheHost compilerHost.toPath = toPath; compilerHost.getCompilationSettings = function () { return compilerOptions; }; @@ -112428,6 +115747,7 @@ var ts; compilerHost.fileIsOpen = ts.returnFalse; compilerHost.getCurrentProgram = getCurrentProgram; compilerHost.writeLog = writeLog; + compilerHost.getParsedCommandLine = getParsedCommandLine; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : @@ -112458,7 +115778,8 @@ var ts; // Update the wild card directory watch watchConfigFileWildCardDirectories(); // Update extended config file watch - watchExtendedConfigFiles(); + if (configFileName) + updateExtendedConfigFilesWatches(toPath(configFileName), compilerOptions, watchOptions, ts.WatchType.ExtendedConfigFile); return configFileName ? { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } : { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close }; @@ -112475,9 +115796,11 @@ var ts; configFileWatcher.close(); configFileWatcher = undefined; } - if (extendedConfigFilesMap) { - ts.clearMap(extendedConfigFilesMap, ts.closeFileWatcher); - extendedConfigFilesMap = undefined; + extendedConfigCache === null || extendedConfigCache === void 0 ? void 0 : extendedConfigCache.clear(); + extendedConfigCache = undefined; + if (sharedExtendedConfigFileWatchers) { + ts.clearMap(sharedExtendedConfigFileWatchers, ts.closeFileWatcherOf); + sharedExtendedConfigFileWatchers = undefined; } if (watchedWildcardDirectories) { ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); @@ -112487,6 +115810,17 @@ var ts; ts.clearMap(missingFilesMap, ts.closeFileWatcher); missingFilesMap = undefined; } + if (parsedConfigs) { + ts.clearMap(parsedConfigs, function (config) { + var _a; + (_a = config.watcher) === null || _a === void 0 ? void 0 : _a.close(); + config.watcher = undefined; + if (config.watchedDirectories) + ts.clearMap(config.watchedDirectories, ts.closeFileWatcherOf); + config.watchedDirectories = undefined; + }); + parsedConfigs = undefined; + } } function getCurrentBuilderProgram() { return builderProgram; @@ -112506,7 +115840,7 @@ 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, projectReferences)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; @@ -112525,6 +115859,8 @@ var ts; writeLog("CreatingProgramWith::"); writeLog(" roots: " + JSON.stringify(rootFileNames)); writeLog(" options: " + JSON.stringify(compilerOptions)); + if (projectReferences) + writeLog(" projectReferences: " + JSON.stringify(projectReferences)); var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; @@ -112747,10 +116083,10 @@ var ts; // Update the wild card directory watch watchConfigFileWildCardDirectories(); // Update extended config file watch - watchExtendedConfigFiles(); + updateExtendedConfigFilesWatches(toPath(configFileName), compilerOptions, watchOptions, ts.WatchType.ExtendedConfigFile); } function parseConfigFile() { - setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217 + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, extendedConfigCache || (extendedConfigCache = new ts.Map()), watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217 } function setConfigFileParsingResult(configFileParseResult) { rootFileNames = configFileParseResult.fileNames; @@ -112762,6 +116098,56 @@ var ts; canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInputFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } + function getParsedCommandLine(configFileName) { + var configPath = toPath(configFileName); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath); + if (config) { + if (!config.reloadLevel) + return config.parsedCommandLine; + // With host implementing getParsedCommandLine we cant just update file names + if (config.parsedCommandLine && config.reloadLevel === ts.ConfigFileProgramReloadLevel.Partial && !host.getParsedCommandLine) { + writeLog("Reloading new file names and options"); + var fileNames = ts.getFileNamesFromConfigSpecs(config.parsedCommandLine.options.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost); + config.parsedCommandLine = __assign(__assign({}, config.parsedCommandLine), { fileNames: fileNames }); + config.reloadLevel = undefined; + return config.parsedCommandLine; + } + } + writeLog("Loading config file: " + configFileName); + var parsedCommandLine = host.getParsedCommandLine ? + host.getParsedCommandLine(configFileName) : + getParsedCommandLineFromConfigFileHost(configFileName); + if (config) { + config.parsedCommandLine = parsedCommandLine; + config.reloadLevel = undefined; + } + else { + (parsedConfigs || (parsedConfigs = new ts.Map())).set(configPath, config = { parsedCommandLine: parsedCommandLine }); + } + watchReferencedProject(configFileName, configPath, config); + return parsedCommandLine; + } + function getParsedCommandLineFromConfigFileHost(configFileName) { + // Ignore the file absent errors + var onUnRecoverableConfigFileDiagnostic = parseConfigFileHost.onUnRecoverableConfigFileDiagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + var parsedCommandLine = ts.getParsedCommandLineOfConfigFile(configFileName, + /*optionsToExtend*/ undefined, parseConfigFileHost, extendedConfigCache || (extendedConfigCache = new ts.Map()), watchOptionsToExtend); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = onUnRecoverableConfigFileDiagnostic; + return parsedCommandLine; + } + function onReleaseParsedCommandLine(fileName) { + var _a; + var path = toPath(fileName); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(path); + if (!config) + return; + parsedConfigs.delete(path); + if (config.watchedDirectories) + ts.clearMap(config.watchedDirectories, ts.closeFileWatcherOf); + (_a = config.watcher) === null || _a === void 0 ? void 0 : _a.close(); + ts.clearSharedExtendedConfigFileWatcher(path, sharedExtendedConfigFileWatchers); + } function watchFilePath(path, file, callback, pollingInterval, options, watchType) { return watchFile(file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options, watchType); } @@ -112771,7 +116157,6 @@ var ts; if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) { resolutionCache.invalidateResolutionOfFile(path); } - resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); nextSourceFileVersion(path); // Update the program scheduleProgramUpdate(); @@ -112782,7 +116167,10 @@ var ts; } } function watchMissingFilePath(missingFilePath) { - return watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); + // If watching missing referenced config file, we are already watching it so no need for separate watcher + return (parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.has(missingFilePath)) ? + ts.noopFileWatcher : + watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); @@ -112819,10 +116207,11 @@ var ts; configFileName: configFileName, extraFileExtensions: extraFileExtensions, options: compilerOptions, - program: getCurrentBuilderProgram(), + program: getCurrentBuilderProgram() || rootFileNames, currentDirectory: currentDirectory, useCaseSensitiveFileNames: useCaseSensitiveFileNames, - writeLog: writeLog + writeLog: writeLog, + toPath: toPath, })) return; // Reload is pending, do the reload @@ -112833,18 +116222,87 @@ var ts; } }, flags, watchOptions, ts.WatchType.WildcardDirectory); } - function watchExtendedConfigFiles() { - var _a; - // Update the extended config files watcher - ts.mutateMap(extendedConfigFilesMap || (extendedConfigFilesMap = new ts.Map()), ts.arrayToMap(((_a = compilerOptions.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath), { - // Watch the extended config files - createNewValue: watchExtendedConfigFile, - // Config files that are no longer extended should no longer be watched. - onDeleteValue: ts.closeFileWatcher - }); + function updateExtendedConfigFilesWatches(forProjectPath, options, watchOptions, watchType) { + ts.updateSharedExtendedConfigFileWatcher(forProjectPath, options, sharedExtendedConfigFileWatchers || (sharedExtendedConfigFileWatchers = new ts.Map()), function (extendedConfigFileName, extendedConfigFilePath) { return watchFile(extendedConfigFileName, function (_fileName, eventKind) { + var _a; + updateCachedSystemWithFile(extendedConfigFileName, extendedConfigFilePath, eventKind); + // Update extended config cache + if (extendedConfigCache) + ts.cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath); + // Update projects + var projects = (_a = sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects; + // If there are no referenced projects this extended config file watcher depend on ignore + if (!(projects === null || projects === void 0 ? void 0 : projects.size)) + return; + projects.forEach(function (projectPath) { + if (toPath(configFileName) === projectPath) { + // If this is the config file of the project, reload completely + reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + } + else { + // Reload config for the referenced projects and remove the resolutions from referenced projects since the config file changed + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(projectPath); + if (config) + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(projectPath); + } + scheduleProgramUpdate(); + }); + }, ts.PollingInterval.High, watchOptions, watchType); }, toPath); } - function watchExtendedConfigFile(extendedConfigFile) { - return watchFile(extendedConfigFile, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ExtendedConfigFile); + function watchReferencedProject(configFileName, configPath, commandLine) { + var _a, _b, _c, _d, _e; + // Watch file + commandLine.watcher || (commandLine.watcher = watchFile(configFileName, function (_fileName, eventKind) { + updateCachedSystemWithFile(configFileName, configPath, eventKind); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath); + if (config) + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(configPath); + scheduleProgramUpdate(); + }, ts.PollingInterval.High, ((_a = commandLine.parsedCommandLine) === null || _a === void 0 ? void 0 : _a.watchOptions) || watchOptions, ts.WatchType.ConfigFileOfReferencedProject)); + // Watch Wild card + if ((_b = commandLine.parsedCommandLine) === null || _b === void 0 ? void 0 : _b.wildcardDirectories) { + ts.updateWatchingWildcardDirectories(commandLine.watchedDirectories || (commandLine.watchedDirectories = new ts.Map()), new ts.Map(ts.getEntries((_c = commandLine.parsedCommandLine) === null || _c === void 0 ? void 0 : _c.wildcardDirectories)), function (directory, flags) { + var _a; + return watchDirectory(directory, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + // Since the file existence changed, update the sourceFiles cache + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + nextSourceFileVersion(fileOrDirectoryPath); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath); + if (!(config === null || config === void 0 ? void 0 : config.parsedCommandLine)) + return; + if (ts.isIgnoredFileFromWildCardWatching({ + watchedDirPath: toPath(directory), + fileOrDirectory: fileOrDirectory, + fileOrDirectoryPath: fileOrDirectoryPath, + configFileName: configFileName, + options: config.parsedCommandLine.options, + program: config.parsedCommandLine.fileNames, + currentDirectory: currentDirectory, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + writeLog: writeLog, + toPath: toPath, + })) + return; + // Reload is pending, do the reload + if (config.reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) { + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + // Schedule Update the program + scheduleProgramUpdate(); + } + }, flags, ((_a = commandLine.parsedCommandLine) === null || _a === void 0 ? void 0 : _a.watchOptions) || watchOptions, ts.WatchType.WildcardDirectoryOfReferencedProject); + }); + } + else if (commandLine.watchedDirectories) { + ts.clearMap(commandLine.watchedDirectories, ts.closeFileWatcherOf); + commandLine.watchedDirectories = undefined; + } + // Watch extended config files + updateExtendedConfigFilesWatches(configPath, (_d = commandLine.parsedCommandLine) === null || _d === void 0 ? void 0 : _d.options, ((_e = commandLine.parsedCommandLine) === null || _e === void 0 ? void 0 : _e.watchOptions) || watchOptions, ts.WatchType.ExtendedConfigOfReferencedProject); } } ts.createWatchProgram = createWatchProgram; @@ -113004,12 +116462,19 @@ var ts; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined; + var typeReferenceDirectiveResolutionCache = !compilerHost.resolveTypeReferenceDirectives ? ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()) : undefined; if (!compilerHost.resolveModuleNames) { var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; }; compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3); }; } + if (!compilerHost.resolveTypeReferenceDirectives) { + var loader_4 = function (moduleName, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(moduleName, containingFile, state.projectCompilerOptions, compilerHost, redirectedReference, state.typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return ts.loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_4); + }; + } var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -113034,6 +116499,7 @@ var ts; projectErrorsReported: new ts.Map(), compilerHost: compilerHost, moduleResolutionCache: moduleResolutionCache, + typeReferenceDirectiveResolutionCache: typeReferenceDirectiveResolutionCache, // Mutable state buildOrder: undefined, readFileWithCache: function (f) { return host.readFile(f); }, @@ -113072,6 +116538,10 @@ var ts; function isParsedCommandLine(entry) { return !!entry.options; } + function getCachedParsedConfigFile(state, configFilePath) { + var value = state.configFileCache.get(configFilePath); + return value && isParsedCommandLine(value) ? value : undefined; + } function parseConfigFile(state, configFileName, configFilePath) { var configFileCache = state.configFileCache; var value = configFileCache.get(configFilePath); @@ -113217,7 +116687,7 @@ var ts; function disableCache(state) { if (!state.cache) return; - var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache; + var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache, typeReferenceDirectiveResolutionCache = state.typeReferenceDirectiveResolutionCache; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; host.directoryExists = cache.originalDirectoryExists; @@ -113226,10 +116696,8 @@ var ts; compilerHost.getSourceFile = cache.originalGetSourceFile; state.readFileWithCache = cache.originalReadFileWithCache; extendedConfigCache.clear(); - if (moduleResolutionCache) { - moduleResolutionCache.directoryToModuleNameMap.clear(); - moduleResolutionCache.moduleNameToDirectoryMap.clear(); - } + moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache === null || typeReferenceDirectiveResolutionCache === void 0 ? void 0 : typeReferenceDirectiveResolutionCache.clear(); state.cache = undefined; } function clearProjectStatus(state, resolved) { @@ -113396,6 +116864,7 @@ var ts; return withProgramOrUndefined(action) || ts.emptyArray; } function createProgram() { + var _a, _b; ts.Debug.assert(program === undefined); if (state.options.dry) { reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project); @@ -113415,7 +116884,8 @@ var ts; var host = state.host, compilerHost = state.compilerHost; state.projectCompilerOptions = config.options; // Update module resolution cache if needed - updateModuleResolutionCache(state, project, config); + (_a = state.moduleResolutionCache) === null || _a === void 0 ? void 0 : _a.update(config.options); + (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options); // Create program program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences); if (state.watch) { @@ -113590,7 +117060,7 @@ var ts; emitBundle(writeFile, customTransformers); break; case BuildStep.BuildInvalidatedProjectOfBundle: - ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken); + ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken, writeFile, customTransformers); step = BuildStep.Done; break; case BuildStep.QueueReferencingProjects: @@ -113732,34 +117202,9 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } - function updateModuleResolutionCache(state, proj, config) { - if (!state.moduleResolutionCache) - return; - // Update module resolution cache if needed - var moduleResolutionCache = state.moduleResolutionCache; - var projPath = toPath(state, proj); - if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) { - // The own map will be for projectCompilerOptions - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0); - moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap); - moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap); - } - else { - // Set correct own map - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0); - var ref = { - sourceFile: config.options.configFile, - commandLine: config - }; - moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); - } - moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options); - } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { // Check tsconfig time - var tsconfigTime = state.host.getModifiedTime(configFile) || ts.missingFileModifiedTime; + var tsconfigTime = ts.getModifiedTime(state.host, configFile); if (oldestOutputFileTime < tsconfigTime) { return { type: ts.UpToDateStatusType.OutOfDateWithSelf, @@ -113769,6 +117214,7 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { + var force = !!state.options.force; var newestInputFileName = undefined; var newestInputFileTime = minimumDate; var host = state.host; @@ -113781,10 +117227,13 @@ var ts; reason: inputFile + " does not exist" }; } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; + if (!force) { + var inputTime = ts.getModifiedTime(host, inputFile); + host.getModifiedTime(inputFile); + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } } // Container if no files are specified in the project @@ -113803,36 +117252,38 @@ var ts; var missingOutputFileName; var newestDeclarationFileContentChangedTime = minimumDate; var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { - var output = outputs_1[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = 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 outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + if (!force) { + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = ts.getModifiedTime(host, output); + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var outputModifiedTime = ts.getModifiedTime(host, output); + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } } } var pseudoUpToDate = false; @@ -113868,7 +117319,8 @@ var ts; }; } // Check oldest output file name only if there is no missing output file name - if (!missingOutputFileName) { + // (a check we will have skipped if this is a forced build) + if (!force && !missingOutputFileName) { // If the upstream project's newest file is older than our oldest output, we // can't be out of date because of it if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { @@ -113914,7 +117366,7 @@ var ts; if (extendedConfigStatus) return extendedConfigStatus; } - if (!state.buildInfoChecked.has(resolvedPath)) { + if (!force && !state.buildInfoChecked.has(resolvedPath)) { state.buildInfoChecked.set(resolvedPath, true); var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); if (buildInfoPath) { @@ -113974,7 +117426,7 @@ var ts; reportStatus(state, verboseMessage, proj.options.configFilePath); } if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, ts.getModifiedTime(host, file)); } host.setModifiedTime(file, now); } @@ -114056,7 +117508,7 @@ var ts; } } } - function build(state, project, cancellationToken, onlyReferences) { + function build(state, project, cancellationToken, writeFile, getCustomTransformers, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); if (!buildOrder) return ts.ExitStatus.InvalidProject_OutputsSkipped; @@ -114068,7 +117520,7 @@ var ts; if (!invalidatedProject) break; reportQueue = false; - invalidatedProject.done(cancellationToken); + invalidatedProject.done(cancellationToken, writeFile, getCustomTransformers === null || getCustomTransformers === void 0 ? void 0 : getCustomTransformers(invalidatedProject.project)); if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; } @@ -114103,8 +117555,14 @@ var ts; continue; } var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames()); + if (!outputs.length) + continue; + var inputFileNames = new ts.Set(parsed.fileNames.map(function (f) { return toPath(state, f); })); for (var _a = 0, outputs_3 = outputs; _a < outputs_3.length; _a++) { var output = outputs_3[_a]; + // If output name is same as input file name, do not delete and ignore the error + if (inputFileNames.has(toPath(state, output))) + continue; if (host.fileExists(output)) { if (filesToDelete) { filesToDelete.push(output); @@ -114180,7 +117638,7 @@ var ts; }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); } function watchExtendedConfigFiles(state, resolvedPath, parsed) { - ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { + ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { var _a; return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (projectConfigFilePath) { return invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ts.ConfigFileProgramReloadLevel.Full); @@ -114191,6 +117649,7 @@ var ts; if (!state.watch) return; ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), new ts.Map(ts.getEntries(parsed.wildcardDirectories)), function (dir, flags) { return state.watchDirectory(dir, function (fileOrDirectory) { + var _a; if (ts.isIgnoredFileFromWildCardWatching({ watchedDirPath: toPath(state, dir), fileOrDirectory: fileOrDirectory, @@ -114198,9 +117657,10 @@ var ts; configFileName: resolved, currentDirectory: state.currentDirectory, options: parsed.options, - program: state.builderPrograms.get(resolvedPath), + program: state.builderPrograms.get(resolvedPath) || ((_a = getCachedParsedConfigFile(state, resolvedPath)) === null || _a === void 0 ? void 0 : _a.fileNames), useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames, - writeLog: function (s) { return state.writeLog(s); } + writeLog: function (s) { return state.writeLog(s); }, + toPath: function (fileName) { return toPath(state, fileName); } })) return; invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Partial); @@ -114235,19 +117695,16 @@ var ts; } function stopWatching(state) { ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher); - ts.clearMap(state.allWatchedExtendedConfigFiles, function (watcher) { - watcher.projects.clear(); - watcher.close(); - }); + ts.clearMap(state.allWatchedExtendedConfigFiles, ts.closeFileWatcherOf); ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); }); ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); }); } function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) { var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions); return { - build: function (project, cancellationToken) { return build(state, project, cancellationToken); }, + build: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers); }, clean: function (project) { return clean(state, project); }, - buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); }, + buildReferences: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers, /*onlyReferences*/ true); }, cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); }, getNextInvalidatedProject: function (cancellationToken) { setupInitialBuild(state, cancellationToken); @@ -114337,6 +117794,9 @@ var ts; } } function reportUpToDateStatus(state, configFileName, status) { + if (state.options.force && (status.type === ts.UpToDateStatusType.UpToDate || status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes)) { + return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); + } switch (status.type) { case ts.UpToDateStatusType.OutOfDateWithSelf: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); @@ -114886,6 +118346,9 @@ var ts; SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["link"] = 22] = "link"; + SymbolDisplayPartKind[SymbolDisplayPartKind["linkName"] = 23] = "linkName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["linkText"] = 24] = "linkText"; })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); var OutliningSpanKind; (function (OutliningSpanKind) { @@ -114996,6 +118459,12 @@ var ts; ScriptElementKind["jsxAttribute"] = "JSX attribute"; /** String literal */ ScriptElementKind["string"] = "string"; + /** Jsdoc @link: in `{@link C link text}`, the before and after text "{@link " and "}" */ + ScriptElementKind["link"] = "link"; + /** Jsdoc @link: in `{@link C link text}`, the entity name "C" */ + ScriptElementKind["linkName"] = "link name"; + /** Jsdoc @link: in `{@link C link text}`, the link text "link text" */ + ScriptElementKind["linkText"] = "link text"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; (function (ScriptElementKindModifier) { @@ -115088,37 +118557,37 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; - case 160 /* Parameter */: - case 198 /* BindingElement */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 287 /* CatchClause */: - case 280 /* JsxAttribute */: + case 161 /* Parameter */: + case 199 /* BindingElement */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 288 /* CatchClause */: + case 281 /* JsxAttribute */: return 1 /* Value */; - case 159 /* TypeParameter */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 177 /* TypeLiteral */: + case 160 /* TypeParameter */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 178 /* TypeLiteral */: return 2 /* Type */; - case 331 /* JSDocTypedefTag */: + case 335 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; - case 291 /* EnumMember */: - case 252 /* ClassDeclaration */: + case 292 /* EnumMember */: + case 253 /* ClassDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; } @@ -115128,16 +118597,16 @@ var ts; else { return 4 /* Namespace */; } - case 255 /* EnumDeclaration */: - case 264 /* NamedImports */: - case 265 /* ImportSpecifier */: - case 260 /* ImportEqualsDeclaration */: - case 261 /* ImportDeclaration */: - case 266 /* ExportAssignment */: - case 267 /* ExportDeclaration */: + case 256 /* EnumDeclaration */: + case 265 /* NamedImports */: + case 266 /* ImportSpecifier */: + case 261 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 267 /* ExportAssignment */: + case 268 /* ExportDeclaration */: return 7 /* All */; // An external module can be a Value - case 297 /* SourceFile */: + case 298 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 7 /* All */; @@ -115145,13 +118614,13 @@ var ts; ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { node = getAdjustedReferenceLocation(node); - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 266 /* ExportAssignment */ - || node.parent.kind === 272 /* ExternalModuleReference */ - || node.parent.kind === 265 /* ImportSpecifier */ - || node.parent.kind === 262 /* ImportClause */ + else if (node.parent.kind === 267 /* ExportAssignment */ + || node.parent.kind === 273 /* ExternalModuleReference */ + || node.parent.kind === 266 /* ImportSpecifier */ + || node.parent.kind === 263 /* ImportClause */ || ts.isImportEqualsDeclaration(node.parent) && node === node.parent.name) { return 7 /* All */; } @@ -115161,7 +118630,7 @@ var ts; else if (ts.isDeclarationName(node)) { return getMeaningFromDeclaration(node.parent); } - else if (ts.isEntityName(node) && ts.isJSDocNameReference(node.parent)) { + else if (ts.isEntityName(node) && (ts.isJSDocNameReference(node.parent) || ts.isJSDocLink(node.parent))) { return 7 /* All */; } else if (isTypeReference(node)) { @@ -115187,11 +118656,11 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - var name = node.kind === 157 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; - return name && name.parent.kind === 260 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; + var name = node.kind === 158 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; + return name && name.parent.kind === 261 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; } function isInRightSideOfInternalImportEqualsDeclaration(node) { - while (node.parent.kind === 157 /* QualifiedName */) { + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -115203,27 +118672,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 157 /* QualifiedName */) { - while (root.parent && root.parent.kind === 157 /* QualifiedName */) { + if (root.parent.kind === 158 /* QualifiedName */) { + while (root.parent && root.parent.kind === 158 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 173 /* TypeReference */ && !isLastClause; + return root.parent.kind === 174 /* TypeReference */ && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 201 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 201 /* PropertyAccessExpression */) { + if (root.parent.kind === 202 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 202 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 223 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 286 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 224 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 287 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 252 /* ClassDeclaration */ && root.parent.parent.token === 116 /* ImplementsKeyword */) || - (decl.kind === 253 /* InterfaceDeclaration */ && root.parent.parent.token === 93 /* ExtendsKeyword */); + return (decl.kind === 253 /* ClassDeclaration */ && root.parent.parent.token === 116 /* ImplementsKeyword */) || + (decl.kind === 254 /* InterfaceDeclaration */ && root.parent.parent.token === 93 /* ExtendsKeyword */); } return false; } @@ -115234,15 +118703,15 @@ var ts; switch (node.kind) { case 107 /* ThisKeyword */: return !ts.isExpressionNode(node); - case 187 /* ThisType */: + case 188 /* ThisType */: return true; } switch (node.parent.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return true; - case 195 /* ImportType */: + case 196 /* ImportType */: return !node.parent.isTypeOf; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } return false; @@ -115309,7 +118778,7 @@ var ts; ts.climbPastPropertyOrElementAccess = climbPastPropertyOrElementAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 245 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { + if (referenceNode.kind === 246 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -115370,22 +118839,22 @@ var ts; ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { switch (node.parent.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 288 /* PropertyAssignment */: - case 291 /* EnumMember */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 256 /* ModuleDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 289 /* PropertyAssignment */: + case 292 /* EnumMember */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 257 /* ModuleDeclaration */: return ts.getNameOfDeclaration(node.parent) === node; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return node.parent.argumentExpression === node; - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return true; - case 191 /* LiteralType */: - return node.parent.parent.kind === 189 /* IndexedAccessType */; + case 192 /* LiteralType */: + return node.parent.parent.kind === 190 /* IndexedAccessType */; default: return false; } @@ -115409,17 +118878,17 @@ var ts; return undefined; } switch (node.kind) { - case 297 /* SourceFile */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 256 /* ModuleDeclaration */: + case 298 /* SourceFile */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 257 /* ModuleDeclaration */: return node; } } @@ -115427,54 +118896,54 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return "module" /* moduleElement */; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return "class" /* classElement */; - case 253 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; - case 254 /* TypeAliasDeclaration */: - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: + case 254 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 255 /* TypeAliasDeclaration */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: return "type" /* typeElement */; - case 255 /* EnumDeclaration */: return "enum" /* enumElement */; - case 249 /* VariableDeclaration */: + case 256 /* EnumDeclaration */: return "enum" /* enumElement */; + case 250 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 209 /* ArrowFunction */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return "function" /* functionElement */; - case 167 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; - case 168 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 168 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 169 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: return "method" /* memberFunctionElement */; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: var initializer = node.initializer; return ts.isFunctionLike(initializer) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 289 /* ShorthandPropertyAssignment */: - case 290 /* SpreadAssignment */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 290 /* ShorthandPropertyAssignment */: + case 291 /* SpreadAssignment */: return "property" /* memberVariableElement */; - case 171 /* IndexSignature */: return "index" /* indexSignatureElement */; - case 170 /* ConstructSignature */: return "construct" /* constructSignatureElement */; - case 169 /* CallSignature */: return "call" /* callSignatureElement */; - case 166 /* Constructor */: return "constructor" /* constructorImplementationElement */; - case 159 /* TypeParameter */: return "type parameter" /* typeParameterElement */; - case 291 /* EnumMember */: return "enum member" /* enumMemberElement */; - case 160 /* Parameter */: return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; - case 260 /* ImportEqualsDeclaration */: - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: - case 263 /* NamespaceImport */: - case 269 /* NamespaceExport */: + case 172 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 171 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 170 /* CallSignature */: return "call" /* callSignatureElement */; + case 167 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 160 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 292 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 161 /* Parameter */: return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 261 /* ImportEqualsDeclaration */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: + case 264 /* NamespaceImport */: + case 270 /* NamespaceExport */: return "alias" /* alias */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { @@ -115503,7 +118972,7 @@ var ts; } case 78 /* Identifier */: return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: var scriptKind = getNodeKind(node.expression); // If the expression didn't come back with something (like it does for an identifiers) return scriptKind === "" /* unknown */ ? "const" /* constElement */ : scriptKind; @@ -115526,7 +118995,7 @@ var ts; return true; case 78 /* Identifier */: // 'this' as a parameter - return ts.identifierIsThisKeyword(node) && node.parent.kind === 160 /* Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 161 /* Parameter */; default: return false; } @@ -115591,42 +119060,42 @@ var ts; return false; } switch (n.kind) { - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 200 /* ObjectLiteralExpression */: - case 196 /* ObjectBindingPattern */: - case 177 /* TypeLiteral */: - case 230 /* Block */: - case 257 /* ModuleBlock */: - case 258 /* CaseBlock */: - case 264 /* NamedImports */: - case 268 /* NamedExports */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 201 /* ObjectLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 178 /* TypeLiteral */: + case 231 /* Block */: + case 258 /* ModuleBlock */: + case 259 /* CaseBlock */: + case 265 /* NamedImports */: + case 269 /* NamedExports */: return nodeEndsWith(n, 19 /* CloseBraceToken */, sourceFile); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 204 /* NewExpression */: + case 205 /* NewExpression */: if (!n.arguments) { return true; } // falls through - case 203 /* CallExpression */: - case 207 /* ParenthesizedExpression */: - case 186 /* ParenthesizedType */: + case 204 /* CallExpression */: + case 208 /* ParenthesizedExpression */: + case 187 /* ParenthesizedType */: return nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 170 /* ConstructSignature */: - case 169 /* CallSignature */: - case 209 /* ArrowFunction */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 171 /* ConstructSignature */: + case 170 /* CallSignature */: + case 210 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -115636,65 +119105,65 @@ var ts; // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. return hasChildOfKind(n, 21 /* CloseParenToken */, sourceFile); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return !!n.body && isCompletedNode(n.body, sourceFile); - case 234 /* IfStatement */: + case 235 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 26 /* SemicolonToken */, sourceFile); - case 199 /* ArrayLiteralExpression */: - case 197 /* ArrayBindingPattern */: - case 202 /* ElementAccessExpression */: - case 158 /* ComputedPropertyName */: - case 179 /* TupleType */: + case 200 /* ArrayLiteralExpression */: + case 198 /* ArrayBindingPattern */: + case 203 /* ElementAccessExpression */: + case 159 /* ComputedPropertyName */: + case 180 /* TupleType */: return nodeEndsWith(n, 23 /* CloseBracketToken */, sourceFile); - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 23 /* CloseBracketToken */, sourceFile); - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed return false; - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 236 /* WhileStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 237 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 235 /* DoStatement */: + case 236 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; return hasChildOfKind(n, 114 /* WhileKeyword */, sourceFile) ? nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile) : isCompletedNode(n.statement, sourceFile); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 211 /* TypeOfExpression */: - case 210 /* DeleteExpression */: - case 212 /* VoidExpression */: - case 219 /* YieldExpression */: - case 220 /* SpreadElement */: + case 212 /* TypeOfExpression */: + case 211 /* DeleteExpression */: + case 213 /* VoidExpression */: + case 220 /* YieldExpression */: + case 221 /* SpreadElement */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 267 /* ExportDeclaration */: - case 261 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: return ts.nodeIsPresent(n.moduleSpecifier); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -115820,11 +119289,11 @@ var ts; function getAdjustedLocationForDeclaration(node, forRename) { if (!forRename) { switch (node.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return getAdjustedLocationForClass(node); - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return getAdjustedLocationForFunction(node); } } @@ -116084,7 +119553,7 @@ var ts; // for (... /**/in [|name|]) // for (... /**/of [|name|]) if (node.kind === 100 /* InKeyword */ && ts.isForInStatement(parent) || - node.kind === 156 /* OfKeyword */ && ts.isForOfStatement(parent)) { + node.kind === 157 /* OfKeyword */ && ts.isForOfStatement(parent)) { return ts.skipOuterExpressions(parent.expression); } } @@ -116153,6 +119622,21 @@ var ts; return current; } } + /** + * Returns the first token where position is in [start, end), + * excluding `JsxText` tokens containing only whitespace. + */ + function findFirstNonJsxWhitespaceToken(sourceFile, position) { + var tokenAtPosition = getTokenAtPosition(sourceFile, position); + while (isWhiteSpaceOnlyJsxText(tokenAtPosition)) { + var nextToken = findNextToken(tokenAtPosition, tokenAtPosition.parent, sourceFile); + if (!nextToken) + return; + tokenAtPosition = nextToken; + } + return tokenAtPosition; + } + ts.findFirstNonJsxWhitespaceToken = findFirstNonJsxWhitespaceToken; /** * The token on the left of the position is the token that strictly includes the position * or sits to the left of the cursor if it is on a boundary. For example @@ -116239,7 +119723,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 297 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 298 /* 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. @@ -116312,17 +119796,17 @@ var ts; return true; } //
{ |
or
- if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 283 /* JsxExpression */) { + if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 284 /* JsxExpression */) { return true; } //
{ // | // } < /div> - if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 283 /* JsxExpression */) { + if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 284 /* JsxExpression */) { return true; } //
|
- if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 276 /* JsxClosingElement */) { + if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 277 /* JsxClosingElement */) { return true; } return false; @@ -116353,7 +119837,7 @@ var ts; function isInsideJsxElement(sourceFile, position) { function isInsideJsxElementTraversal(node) { while (node) { - if (node.kind >= 274 /* JsxSelfClosingElement */ && node.kind <= 283 /* JsxExpression */ + if (node.kind >= 275 /* JsxSelfClosingElement */ && node.kind <= 284 /* JsxExpression */ || node.kind === 11 /* JsxText */ || node.kind === 29 /* LessThanToken */ || node.kind === 31 /* GreaterThanToken */ @@ -116363,7 +119847,7 @@ var ts; || node.kind === 43 /* SlashToken */) { node = node.parent; } - else if (node.kind === 273 /* JsxElement */) { + else if (node.kind === 274 /* JsxElement */) { if (position > node.getStart(sourceFile)) return true; node = node.parent; @@ -116571,16 +120055,16 @@ var ts; result.push("deprecated" /* deprecatedModifier */); if (node.flags & 8388608 /* Ambient */) result.push("declare" /* ambientModifier */); - if (node.kind === 266 /* ExportAssignment */) + if (node.kind === 267 /* ExportAssignment */) result.push("export" /* exportedModifier */); return result.length > 0 ? result.join(",") : "" /* none */; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 173 /* TypeReference */ || node.kind === 203 /* CallExpression */) { + if (node.kind === 174 /* TypeReference */ || node.kind === 204 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 252 /* ClassDeclaration */ || node.kind === 253 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 253 /* ClassDeclaration */ || node.kind === 254 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; @@ -116625,18 +120109,18 @@ var ts; } ts.cloneCompilerOptions = cloneCompilerOptions; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 199 /* ArrayLiteralExpression */ || - node.kind === 200 /* ObjectLiteralExpression */) { + if (node.kind === 200 /* ArrayLiteralExpression */ || + node.kind === 201 /* ObjectLiteralExpression */) { // [a,b,c] from: // [a, b, c] = someExpression; - if (node.parent.kind === 216 /* BinaryExpression */ && + if (node.parent.kind === 217 /* BinaryExpression */ && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */) { return true; } // [a, b, c] from: // for([a, b, c] of expression) - if (node.parent.kind === 239 /* ForOfStatement */ && + if (node.parent.kind === 240 /* ForOfStatement */ && node.parent.initializer === node) { return true; } @@ -116644,7 +120128,7 @@ var ts; // [x, [a, b, c] ] = someExpression // or // {x, a: {a, b, c} } = someExpression - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 288 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 289 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { return true; } } @@ -116764,7 +120248,7 @@ var ts; } ts.skipConstraint = skipConstraint; function getNameFromPropertyName(name) { - return name.kind === 158 /* ComputedPropertyName */ + return name.kind === 159 /* ComputedPropertyName */ // treat computed property names where expression is string/numeric literal as just string/numeric literal ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined : ts.isPrivateIdentifier(name) ? ts.idText(name) : ts.getTextOfIdentifierOrLiteral(name); @@ -116783,7 +120267,7 @@ var ts; } ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules; function createModuleSpecifierResolutionHost(program, host) { - // Mix in `getProbableSymlinks` from Program when host doesn't have it + // Mix in `getSymlinkCache` from Program when host doesn't have it // in order for non-Project hosts to have a symlinks cache. return { fileExists: function (fileName) { return program.fileExists(fileName); }, @@ -116791,6 +120275,7 @@ var ts; readFile: ts.maybeBind(host, host.readFile), useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), getSymlinkCache: ts.maybeBind(host, host.getSymlinkCache) || program.getSymlinkCache, + getModuleSpecifierCache: ts.maybeBind(host, host.getModuleSpecifierCache), getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation), getSourceFiles: function () { return program.getSourceFiles(); }, redirectTargetsMap: program.redirectTargetsMap, @@ -116865,6 +120350,13 @@ var ts; }); } ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isModuleSpecifierLike(node) { + return ts.isStringLiteralLike(node) && (ts.isExternalModuleReference(node.parent) || + ts.isImportDeclaration(node.parent) || + ts.isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ false) && node.parent.arguments[0] === node || + ts.isImportCall(node.parent) && node.parent.arguments[0] === node); + } + ts.isModuleSpecifierLike = isModuleSpecifierLike; function isObjectBindingElementWithoutPropertyName(bindingElement) { return ts.isBindingElement(bindingElement) && ts.isObjectBindingPattern(bindingElement.parent) && @@ -116898,7 +120390,7 @@ var ts; ts.findModifier = findModifier; function insertImports(changes, sourceFile, imports, blankLineBetween) { var decl = ts.isArray(imports) ? imports[0] : imports; - var importKindPredicate = decl.kind === 232 /* VariableStatement */ ? ts.isRequireVariableStatement : ts.isAnyImportSyntax; + var importKindPredicate = decl.kind === 233 /* VariableStatement */ ? ts.isRequireVariableStatement : ts.isAnyImportSyntax; var existingImportStatements = ts.filter(sourceFile.statements, importKindPredicate); var sortedNewImports = ts.isArray(imports) ? ts.stableSort(imports, ts.OrganizeImports.compareImportsOrRequireStatements) : [imports]; if (!existingImportStatements.length) { @@ -116976,7 +120468,7 @@ var ts; // Display-part writer helpers // #region function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 160 /* Parameter */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 161 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -117139,6 +120631,14 @@ var ts; return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); } ts.operatorPart = operatorPart; + function parameterNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.parameterName); + } + ts.parameterNamePart = parameterNamePart; + function propertyNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.propertyName); + } + ts.propertyNamePart = propertyNamePart; function textOrKeywordPart(text) { var kind = ts.stringToToken(text); return kind === undefined @@ -117150,6 +120650,58 @@ var ts; return displayPart(text, ts.SymbolDisplayPartKind.text); } ts.textPart = textPart; + function typeAliasNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.aliasName); + } + ts.typeAliasNamePart = typeAliasNamePart; + function typeParameterNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.typeParameterName); + } + ts.typeParameterNamePart = typeParameterNamePart; + function linkTextPart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.linkText); + } + ts.linkTextPart = linkTextPart; + function linkNamePart(name, target) { + return { + text: ts.getTextOfNode(name), + kind: ts.SymbolDisplayPartKind[ts.SymbolDisplayPartKind.linkName], + target: { + fileName: ts.getSourceFileOfNode(target).fileName, + textSpan: createTextSpanFromNode(target), + }, + }; + } + ts.linkNamePart = linkNamePart; + function linkPart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.link); + } + ts.linkPart = linkPart; + function buildLinkParts(link, checker) { + var _a; + var parts = [linkPart("{@link ")]; + if (!link.name) { + if (link.text) { + parts.push(linkTextPart(link.text)); + } + } + else { + var symbol = checker === null || checker === void 0 ? void 0 : checker.getSymbolAtLocation(link.name); + var decl = (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) || ((_a = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]); + if (decl) { + parts.push(linkNamePart(link.name, decl)); + if (link.text) { + parts.push(linkTextPart(link.text)); + } + } + else { + parts.push(linkTextPart(ts.getTextOfNode(link.name) + link.text)); + } + } + parts.push(linkPart("}")); + return parts; + } + ts.buildLinkParts = buildLinkParts; var carriageReturnLineFeed = "\r\n"; /** * The default is CRLF. @@ -117435,21 +120987,23 @@ var ts; } /* @internal */ function needsParentheses(expression) { - return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ + || ts.isObjectLiteralExpression(expression) + || ts.isAsExpression(expression) && ts.isObjectLiteralExpression(expression.expression); } ts.needsParentheses = needsParentheses; function getContextualTypeFromParent(node, checker) { var parent = node.parent; switch (parent.kind) { - case 204 /* NewExpression */: + case 205 /* NewExpression */: return checker.getContextualType(parent); - case 216 /* BinaryExpression */: { + case 217 /* BinaryExpression */: { var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; return isEqualityOperatorKind(operatorToken.kind) ? checker.getTypeAtLocation(node === right ? left : right) : checker.getContextualType(node); } - case 284 /* CaseClause */: + case 285 /* CaseClause */: return parent.expression === node ? getSwitchedType(parent, checker) : undefined; default: return checker.getContextualType(node); @@ -117460,7 +121014,7 @@ var ts; // Editors can pass in undefined or empty string - we want to infer the preference in those cases. var quotePreference = getQuotePreference(sourceFile, preferences); var quoted = JSON.stringify(text); - return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'" : quoted; + return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace(/'/g, "\\'").replace(/\\"/g, '"') + "'" : quoted; } ts.quote = quote; function isEqualityOperatorKind(kind) { @@ -117479,8 +121033,8 @@ var ts; switch (node.kind) { case 10 /* StringLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: - case 218 /* TemplateExpression */: - case 205 /* TaggedTemplateExpression */: + case 219 /* TemplateExpression */: + case 206 /* TaggedTemplateExpression */: return true; default: return false; @@ -117513,41 +121067,41 @@ var ts; } ts.getTypeNodeIfAccessible = getTypeNodeIfAccessible; function syntaxRequiresTrailingCommaOrSemicolonOrASI(kind) { - return kind === 169 /* CallSignature */ - || kind === 170 /* ConstructSignature */ - || kind === 171 /* IndexSignature */ - || kind === 162 /* PropertySignature */ - || kind === 164 /* MethodSignature */; + return kind === 170 /* CallSignature */ + || kind === 171 /* ConstructSignature */ + || kind === 172 /* IndexSignature */ + || kind === 163 /* PropertySignature */ + || kind === 165 /* MethodSignature */; } ts.syntaxRequiresTrailingCommaOrSemicolonOrASI = syntaxRequiresTrailingCommaOrSemicolonOrASI; function syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(kind) { - return kind === 251 /* FunctionDeclaration */ - || kind === 166 /* Constructor */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 252 /* FunctionDeclaration */ + || kind === 167 /* Constructor */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } ts.syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI = syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI; function syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(kind) { - return kind === 256 /* ModuleDeclaration */; + return kind === 257 /* ModuleDeclaration */; } ts.syntaxRequiresTrailingModuleBlockOrSemicolonOrASI = syntaxRequiresTrailingModuleBlockOrSemicolonOrASI; function syntaxRequiresTrailingSemicolonOrASI(kind) { - return kind === 232 /* VariableStatement */ - || kind === 233 /* ExpressionStatement */ - || kind === 235 /* DoStatement */ - || kind === 240 /* ContinueStatement */ - || kind === 241 /* BreakStatement */ - || kind === 242 /* ReturnStatement */ - || kind === 246 /* ThrowStatement */ - || kind === 248 /* DebuggerStatement */ - || kind === 163 /* PropertyDeclaration */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 261 /* ImportDeclaration */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 267 /* ExportDeclaration */ - || kind === 259 /* NamespaceExportDeclaration */ - || kind === 266 /* ExportAssignment */; + return kind === 233 /* VariableStatement */ + || kind === 234 /* ExpressionStatement */ + || kind === 236 /* DoStatement */ + || kind === 241 /* ContinueStatement */ + || kind === 242 /* BreakStatement */ + || kind === 243 /* ReturnStatement */ + || kind === 247 /* ThrowStatement */ + || kind === 249 /* DebuggerStatement */ + || kind === 164 /* PropertyDeclaration */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 262 /* ImportDeclaration */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 268 /* ExportDeclaration */ + || kind === 260 /* NamespaceExportDeclaration */ + || kind === 267 /* ExportAssignment */; } ts.syntaxRequiresTrailingSemicolonOrASI = syntaxRequiresTrailingSemicolonOrASI; ts.syntaxMayBeASICandidate = ts.or(syntaxRequiresTrailingCommaOrSemicolonOrASI, syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI, syntaxRequiresTrailingModuleBlockOrSemicolonOrASI, syntaxRequiresTrailingSemicolonOrASI); @@ -117577,7 +121131,7 @@ var ts; return false; } // See comment in parser’s `parseDoStatement` - if (node.kind === 235 /* DoStatement */) { + if (node.kind === 236 /* DoStatement */) { return true; } var topNode = ts.findAncestor(node, function (ancestor) { return !ancestor.parent; }); @@ -117751,6 +121305,94 @@ var ts; } } ts.createPackageJsonInfo = createPackageJsonInfo; + function createPackageJsonImportFilter(fromFile, host) { + var packageJsons = ((host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName)) || getPackageJsonsVisibleToFile(fromFile.fileName, host)).filter(function (p) { return p.parseable; }); + var usesNodeCoreModules; + return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier }; + function moduleSpecifierIsCoveredByPackageJson(specifier) { + var packageName = getNodeModuleRootSpecifier(specifier); + for (var _i = 0, packageJsons_1 = packageJsons; _i < packageJsons_1.length; _i++) { + var packageJson = packageJsons_1[_i]; + if (packageJson.has(packageName) || packageJson.has(ts.getTypesPackageName(packageName))) { + return true; + } + } + return false; + } + function allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost) { + if (!packageJsons.length || !moduleSymbol.valueDeclaration) { + return true; + } + var declaringSourceFile = moduleSymbol.valueDeclaration.getSourceFile(); + var declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName, moduleSpecifierResolutionHost); + if (typeof declaringNodeModuleName === "undefined") { + return true; + } + var declaredModuleSpecifier = ts.stripQuotes(moduleSymbol.getName()); + if (isAllowedCoreNodeModulesImport(declaredModuleSpecifier)) { + return true; + } + return moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName) + || moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier); + } + function allowsImportingSourceFile(sourceFile, moduleSpecifierResolutionHost) { + if (!packageJsons.length) { + return true; + } + var moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName, moduleSpecifierResolutionHost); + if (!moduleSpecifier) { + return true; + } + return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); + } + function allowsImportingSpecifier(moduleSpecifier) { + if (!packageJsons.length || isAllowedCoreNodeModulesImport(moduleSpecifier)) { + return true; + } + if (ts.pathIsRelative(moduleSpecifier) || ts.isRootedDiskPath(moduleSpecifier)) { + return true; + } + return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); + } + function isAllowedCoreNodeModulesImport(moduleSpecifier) { + // If we’re in JavaScript, it can be difficult to tell whether the user wants to import + // from Node core modules or not. We can start by seeing if the user is actually using + // any node core modules, as opposed to simply having @types/node accidentally as a + // dependency of a dependency. + if (ts.isSourceFileJS(fromFile) && ts.JsTyping.nodeCoreModules.has(moduleSpecifier)) { + if (usesNodeCoreModules === undefined) { + usesNodeCoreModules = consumesNodeCoreModules(fromFile); + } + if (usesNodeCoreModules) { + return true; + } + } + return false; + } + function getNodeModulesPackageNameFromFileName(importedFileName, moduleSpecifierResolutionHost) { + if (!ts.stringContains(importedFileName, "node_modules")) { + return undefined; + } + var specifier = ts.moduleSpecifiers.getNodeModulesPackageName(host.getCompilationSettings(), fromFile.path, importedFileName, moduleSpecifierResolutionHost); + if (!specifier) { + return undefined; + } + // Paths here are not node_modules, so we don’t care about them; + // returning anything will trigger a lookup in package.json. + if (!ts.pathIsRelative(specifier) && !ts.isRootedDiskPath(specifier)) { + return getNodeModuleRootSpecifier(specifier); + } + } + function getNodeModuleRootSpecifier(fullSpecifier) { + var components = ts.getPathComponents(ts.getPackageNameFromTypesPackageName(fullSpecifier)).slice(1); + // Scoped packages + if (ts.startsWith(components[0], "@")) { + return components[0] + "/" + components[1]; + } + return components[0]; + } + } + ts.createPackageJsonImportFilter = createPackageJsonImportFilter; function tryParseJson(text) { try { return JSON.parse(text); @@ -117827,9 +121469,9 @@ var ts; } ts.firstOrOnly = firstOrOnly; function getNameForExportedSymbol(symbol, scriptTarget) { - if (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */) { + if (!(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */)) { // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. - return ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) + return ts.firstDefined(symbol.declarations, function (d) { var _a; return ts.isExportAssignment(d) ? (_a = ts.tryCast(ts.skipOuterExpressions(d.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget); } return symbol.name; @@ -117893,6 +121535,184 @@ var ts; return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation); } ts.isNonGlobalDeclaration = isNonGlobalDeclaration; + var ImportKind; + (function (ImportKind) { + ImportKind[ImportKind["Named"] = 0] = "Named"; + ImportKind[ImportKind["Default"] = 1] = "Default"; + ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; + ImportKind[ImportKind["CommonJS"] = 3] = "CommonJS"; + })(ImportKind = ts.ImportKind || (ts.ImportKind = {})); + var ExportKind; + (function (ExportKind) { + ExportKind[ExportKind["Named"] = 0] = "Named"; + ExportKind[ExportKind["Default"] = 1] = "Default"; + ExportKind[ExportKind["ExportEquals"] = 2] = "ExportEquals"; + ExportKind[ExportKind["UMD"] = 3] = "UMD"; + })(ExportKind = ts.ExportKind || (ts.ExportKind = {})); + function createExportMapCache() { + var cache; + var projectVersion; + var usableByFileName; + var wrapped = { + isEmpty: function () { + return !cache; + }, + clear: function () { + cache = undefined; + projectVersion = undefined; + }, + set: function (suggestions, version) { + cache = suggestions; + if (version) { + projectVersion = version; + } + }, + get: function (file, checker, version) { + if (usableByFileName && file !== usableByFileName) { + return undefined; + } + if (version && projectVersion === version) { + return cache; + } + cache === null || cache === void 0 ? void 0 : cache.forEach(function (infos) { + var _a, _b, _c; + for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { + var info = infos_1[_i]; + // If the symbol/moduleSymbol was a merged symbol, it will have a new identity + // in the checker, even though the symbols to merge are the same (guaranteed by + // cache invalidation in synchronizeHostData). + if ((_a = info.symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) { + info.symbol = checker.getMergedSymbol(info.exportKind === 1 /* Default */ + ? (_b = info.symbol.declarations[0].localSymbol) !== null && _b !== void 0 ? _b : info.symbol.declarations[0].symbol + : info.symbol.declarations[0].symbol); + } + if ((_c = info.moduleSymbol.declarations) === null || _c === void 0 ? void 0 : _c.length) { + info.moduleSymbol = checker.getMergedSymbol(info.moduleSymbol.declarations[0].symbol); + } + } + }); + return cache; + }, + onFileChanged: function (oldSourceFile, newSourceFile, typeAcquisitionEnabled) { + if (fileIsGlobalOnly(oldSourceFile) && fileIsGlobalOnly(newSourceFile)) { + // File is purely global; doesn't affect export map + return false; + } + if (usableByFileName && usableByFileName !== newSourceFile.path || + // If ATA is enabled, auto-imports uses existing imports to guess whether you want auto-imports from node. + // Adding or removing imports from node could change the outcome of that guess, so could change the suggestions list. + typeAcquisitionEnabled && consumesNodeCoreModules(oldSourceFile) !== consumesNodeCoreModules(newSourceFile) || + // Module agumentation and ambient module changes can add or remove exports available to be auto-imported. + // Changes elsewhere in the file can change the *type* of an export in a module augmentation, + // but type info is gathered in getCompletionEntryDetails, which doesn’t use the cache. + !ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations) || + !ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile)) { + this.clear(); + return true; + } + usableByFileName = newSourceFile.path; + return false; + }, + }; + if (ts.Debug.isDebugging) { + Object.defineProperty(wrapped, "__cache", { get: function () { return cache; } }); + } + return wrapped; + function fileIsGlobalOnly(file) { + return !file.commonJsModuleIndicator && !file.externalModuleIndicator && !file.moduleAugmentations && !file.ambientModuleNames; + } + function ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile) { + if (!ts.arrayIsEqualTo(oldSourceFile.ambientModuleNames, newSourceFile.ambientModuleNames)) { + return false; + } + var oldFileStatementIndex = -1; + var newFileStatementIndex = -1; + var _loop_1 = function (ambientModuleName) { + var isMatchingModuleDeclaration = function (node) { return ts.isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName; }; + oldFileStatementIndex = ts.findIndex(oldSourceFile.statements, isMatchingModuleDeclaration, oldFileStatementIndex + 1); + newFileStatementIndex = ts.findIndex(newSourceFile.statements, isMatchingModuleDeclaration, newFileStatementIndex + 1); + if (oldSourceFile.statements[oldFileStatementIndex] !== newSourceFile.statements[newFileStatementIndex]) { + return { value: false }; + } + }; + for (var _i = 0, _a = newSourceFile.ambientModuleNames; _i < _a.length; _i++) { + var ambientModuleName = _a[_i]; + var state_1 = _loop_1(ambientModuleName); + if (typeof state_1 === "object") + return state_1.value; + } + return true; + } + } + ts.createExportMapCache = createExportMapCache; + function createModuleSpecifierCache() { + var cache; + var importingFileName; + var wrapped = { + get: function (fromFileName, toFileName) { + if (!cache || fromFileName !== importingFileName) + return undefined; + return cache.get(toFileName); + }, + set: function (fromFileName, toFileName, moduleSpecifiers) { + if (cache && fromFileName !== importingFileName) { + cache.clear(); + } + importingFileName = fromFileName; + (cache || (cache = new ts.Map())).set(toFileName, moduleSpecifiers); + }, + clear: function () { + cache = undefined; + importingFileName = undefined; + }, + count: function () { + return cache ? cache.size : 0; + } + }; + if (ts.Debug.isDebugging) { + Object.defineProperty(wrapped, "__cache", { get: function () { return cache; } }); + } + return wrapped; + } + ts.createModuleSpecifierCache = createModuleSpecifierCache; + function isImportableFile(program, from, to, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) { + var _a; + if (from === to) + return false; + var cachedResult = moduleSpecifierCache === null || moduleSpecifierCache === void 0 ? void 0 : moduleSpecifierCache.get(from.path, to.path); + if (cachedResult !== undefined) { + return !!cachedResult; + } + var getCanonicalFileName = ts.hostGetCanonicalFileName(moduleSpecifierResolutionHost); + var globalTypingsCache = (_a = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation) === null || _a === void 0 ? void 0 : _a.call(moduleSpecifierResolutionHost); + var hasImportablePath = !!ts.moduleSpecifiers.forEachFileNameOfModule(from.fileName, to.fileName, moduleSpecifierResolutionHost, + /*preferSymlinks*/ false, function (toPath) { + var toFile = program.getSourceFile(toPath); + // Determine to import using toPath only if toPath is what we were looking at + // or there doesnt exist the file in the program by the symlink + return (toFile === to || !toFile) && + isImportablePath(from.fileName, toPath, getCanonicalFileName, globalTypingsCache); + }); + if (packageJsonFilter) { + var isImportable = hasImportablePath && packageJsonFilter.allowsImportingSourceFile(to, moduleSpecifierResolutionHost); + moduleSpecifierCache === null || moduleSpecifierCache === void 0 ? void 0 : moduleSpecifierCache.set(from.path, to.path, isImportable); + return isImportable; + } + return hasImportablePath; + } + ts.isImportableFile = isImportableFile; + /** + * Don't include something from a `node_modules` that isn't actually reachable by a global import. + * A relative import to node_modules is usually a bad idea. + */ + function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) { + // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. + var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); + var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules)); + return toNodeModulesParent === undefined + || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) + || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); + } // #endregion })(ts || (ts = {})); var ts; @@ -118334,13 +122154,13 @@ var ts; // That means we're calling back into the host around every 1.2k of the file we process. // Lib.d.ts has similar numbers. switch (kind) { - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 251 /* FunctionDeclaration */: - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: cancellationToken.throwIfCancellationRequested(); } } @@ -118547,10 +122367,11 @@ var ts; pushClassification(start, width, 1 /* comment */); } function classifyJSDocComment(docComment) { + var _a, _b, _c, _d, _e, _f, _g; var pos = docComment.pos; if (docComment.tags) { - for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { - var tag = _a[_i]; + for (var _i = 0, _h = docComment.tags; _i < _h.length; _i++) { + var tag = _h[_i]; // As we walk through each tag, classify the portion of text from the end of // the last tag (or the start of the entire doc comment) as 'comment'. if (tag.pos !== pos) { @@ -118559,23 +122380,57 @@ var ts; pushClassification(tag.pos, 1, 10 /* punctuation */); // "@" pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; + var commentStart = tag.tagName.end; switch (tag.kind) { - case 326 /* JSDocParameterTag */: - processJSDocParameterTag(tag); + case 330 /* JSDocParameterTag */: + var param = tag; + processJSDocParameterTag(param); + commentStart = param.isNameFirst && ((_a = param.typeExpression) === null || _a === void 0 ? void 0 : _a.end) || param.name.end; + break; + case 337 /* JSDocPropertyTag */: + var prop = tag; + commentStart = prop.isNameFirst && ((_b = prop.typeExpression) === null || _b === void 0 ? void 0 : _b.end) || prop.name.end; break; - case 330 /* JSDocTemplateTag */: + case 334 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); pos = tag.end; + commentStart = tag.typeParameters.end; break; - case 329 /* JSDocTypeTag */: + case 335 /* JSDocTypedefTag */: + var type = tag; + commentStart = ((_c = type.typeExpression) === null || _c === void 0 ? void 0 : _c.kind) === 302 /* JSDocTypeExpression */ && ((_d = type.fullName) === null || _d === void 0 ? void 0 : _d.end) || ((_e = type.typeExpression) === null || _e === void 0 ? void 0 : _e.end) || commentStart; + break; + case 328 /* JSDocCallbackTag */: + commentStart = tag.typeExpression.end; + break; + case 333 /* JSDocTypeTag */: processElement(tag.typeExpression); pos = tag.end; + commentStart = tag.typeExpression.end; + break; + case 332 /* JSDocThisTag */: + case 329 /* JSDocEnumTag */: + commentStart = tag.typeExpression.end; break; - case 327 /* JSDocReturnTag */: + case 331 /* JSDocReturnTag */: processElement(tag.typeExpression); pos = tag.end; + commentStart = ((_f = tag.typeExpression) === null || _f === void 0 ? void 0 : _f.end) || commentStart; + break; + case 336 /* JSDocSeeTag */: + commentStart = ((_g = tag.name) === null || _g === void 0 ? void 0 : _g.end) || commentStart; + break; + case 318 /* JSDocAugmentsTag */: + case 319 /* JSDocImplementsTag */: + commentStart = tag.class.end; break; } + if (typeof tag.comment === "object") { + pushCommentRange(tag.comment.pos, tag.comment.end - tag.comment.pos); + } + else if (typeof tag.comment === "string") { + pushCommentRange(commentStart, tag.end - commentStart); + } } } if (pos !== docComment.end) { @@ -118722,22 +122577,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } break; - case 276 /* JsxClosingElement */: + case 277 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } break; - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } break; - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: if (token.parent.name === token) { return 22 /* jsxAttribute */; } @@ -118766,17 +122621,17 @@ var ts; var parent = token.parent; if (tokenKind === 62 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (parent.kind === 249 /* VariableDeclaration */ || - parent.kind === 163 /* PropertyDeclaration */ || - parent.kind === 160 /* Parameter */ || - parent.kind === 280 /* JsxAttribute */) { + if (parent.kind === 250 /* VariableDeclaration */ || + parent.kind === 164 /* PropertyDeclaration */ || + parent.kind === 161 /* Parameter */ || + parent.kind === 281 /* JsxAttribute */) { return 5 /* operator */; } } - if (parent.kind === 216 /* BinaryExpression */ || - parent.kind === 214 /* PrefixUnaryExpression */ || - parent.kind === 215 /* PostfixUnaryExpression */ || - parent.kind === 217 /* ConditionalExpression */) { + if (parent.kind === 217 /* BinaryExpression */ || + parent.kind === 215 /* PrefixUnaryExpression */ || + parent.kind === 216 /* PostfixUnaryExpression */ || + parent.kind === 218 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -118789,7 +122644,7 @@ var ts; return 25 /* bigintLiteral */; } else if (tokenKind === 10 /* StringLiteral */) { - return token && token.parent.kind === 280 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + return token && token.parent.kind === 281 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 13 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -118805,32 +122660,32 @@ var ts; else if (tokenKind === 78 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 160 /* Parameter */: + case 161 /* Parameter */: if (token.parent.name === token) { return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } @@ -118932,13 +122787,13 @@ var ts; var inJSXElement = false; function visit(node) { switch (node.kind) { - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 251 /* FunctionDeclaration */: - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: cancellationToken.throwIfCancellationRequested(); } if (!node || !ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth()) || node.getFullWidth() === 0) { @@ -119084,25 +122939,25 @@ var ts; return (ts.isQualifiedName(node.parent) && node.parent.right === node) || (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node); } var tokenFromDeclarationMapping = new ts.Map([ - [249 /* VariableDeclaration */, 7 /* variable */], - [160 /* Parameter */, 6 /* parameter */], - [163 /* PropertyDeclaration */, 9 /* property */], - [256 /* ModuleDeclaration */, 3 /* namespace */], - [255 /* EnumDeclaration */, 1 /* enum */], - [291 /* EnumMember */, 8 /* enumMember */], - [252 /* ClassDeclaration */, 0 /* class */], - [165 /* MethodDeclaration */, 11 /* member */], - [251 /* FunctionDeclaration */, 10 /* function */], - [208 /* FunctionExpression */, 10 /* function */], - [164 /* MethodSignature */, 11 /* member */], - [167 /* GetAccessor */, 9 /* property */], - [168 /* SetAccessor */, 9 /* property */], - [162 /* PropertySignature */, 9 /* property */], - [253 /* InterfaceDeclaration */, 2 /* interface */], - [254 /* TypeAliasDeclaration */, 5 /* type */], - [159 /* TypeParameter */, 4 /* typeParameter */], - [288 /* PropertyAssignment */, 9 /* property */], - [289 /* ShorthandPropertyAssignment */, 9 /* property */] + [250 /* VariableDeclaration */, 7 /* variable */], + [161 /* Parameter */, 6 /* parameter */], + [164 /* PropertyDeclaration */, 9 /* property */], + [257 /* ModuleDeclaration */, 3 /* namespace */], + [256 /* EnumDeclaration */, 1 /* enum */], + [292 /* EnumMember */, 8 /* enumMember */], + [253 /* ClassDeclaration */, 0 /* class */], + [166 /* MethodDeclaration */, 11 /* member */], + [252 /* FunctionDeclaration */, 10 /* function */], + [209 /* FunctionExpression */, 10 /* function */], + [165 /* MethodSignature */, 11 /* member */], + [168 /* GetAccessor */, 9 /* property */], + [169 /* SetAccessor */, 9 /* property */], + [163 /* PropertySignature */, 9 /* property */], + [254 /* InterfaceDeclaration */, 2 /* interface */], + [255 /* TypeAliasDeclaration */, 5 /* type */], + [160 /* TypeParameter */, 4 /* typeParameter */], + [289 /* PropertyAssignment */, 9 /* property */], + [290 /* ShorthandPropertyAssignment */, 9 /* property */] ]); })(v2020 = classifier.v2020 || (classifier.v2020 = {})); })(classifier = ts.classifier || (ts.classifier = {})); @@ -119122,12 +122977,12 @@ var ts; if (ts.isInString(sourceFile, position, contextToken)) { if (!contextToken || !ts.isStringLiteralLike(contextToken)) return undefined; - var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); - return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, preferences); + var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); + return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, options, preferences); } } StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; - function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, preferences) { + function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, options, preferences) { if (completion === undefined) { return undefined; } @@ -119137,7 +122992,7 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences, options); // Target will not be used, so arbitrary return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, optionalReplacementSpan: optionalReplacementSpan, entries: entries }; } case 2 /* Types */: { @@ -119154,10 +123009,10 @@ var ts; return ts.Debug.assertNever(completion); } } - function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken) { + function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken, preferences) { if (!contextToken || !ts.isStringLiteralLike(contextToken)) return undefined; - var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); + var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken); } StringCompletions.getStringLiteralCompletionDetails = getStringLiteralCompletionDetails; @@ -119206,13 +123061,13 @@ var ts; StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties"; StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); - function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host, preferences) { var parent = walkUpParentheses(node.parent); switch (parent.kind) { - case 191 /* LiteralType */: { + case 192 /* LiteralType */: { var grandParent = walkUpParentheses(parent.parent); switch (grandParent.kind) { - case 173 /* TypeReference */: { + case 174 /* TypeReference */: { var typeReference_1 = grandParent; var typeArgument = ts.findAncestor(parent, function (n) { return n.parent === typeReference_1; }); if (typeArgument) { @@ -119220,7 +123075,7 @@ var ts; } return undefined; } - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { // foo: string; @@ -119232,9 +123087,9 @@ var ts; return undefined; } return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(objectType)); - case 195 /* ImportType */: - return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 182 /* UnionType */: { + case 196 /* ImportType */: + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; + case 183 /* UnionType */: { if (!ts.isTypeReferenceNode(grandParent.parent)) { return undefined; } @@ -119246,7 +123101,7 @@ var ts; return undefined; } } - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { @@ -119263,7 +123118,7 @@ var ts; return stringLiteralCompletionsForObjectLiteral(typeChecker, parent.parent); } return fromContextualType(); - case 202 /* ElementAccessExpression */: { + case 203 /* ElementAccessExpression */: { var _b = parent, expression = _b.expression, argumentExpression = _b.argumentExpression; if (node === ts.skipParentheses(argumentExpression)) { // Get all names of properties on the expression @@ -119276,8 +123131,8 @@ var ts; } return undefined; } - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: 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 @@ -119286,16 +123141,16 @@ var ts; return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); } // falls through (is `require("")` or `import("")`) - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: - case 272 /* ExternalModuleReference */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 273 /* ExternalModuleReference */: // Get all known external module names or complete a path to a module // i.e. import * as ns from "/*completion position*/"; // var y = import("/*completion position*/"); // import x = require("/*completion position*/"); // var y = require("/*completion position*/"); // export * from "/*completion position*/"; - return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; default: return fromContextualType(); } @@ -119307,9 +123162,9 @@ var ts; } function walkUpParentheses(node) { switch (node.kind) { - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return ts.walkUpParenthesizedTypes(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return ts.walkUpParenthesizedExpressions(node); default: return node; @@ -119337,7 +123192,7 @@ var ts; function stringLiteralCompletionsFromProperties(type) { return type && { kind: 1 /* Properties */, - symbols: ts.filter(type.getApparentProperties(), function (prop) { return !(prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)); }), + symbols: ts.filter(type.getApparentProperties(), function (prop) { return !(prop.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration)); }), hasIndexSignature: ts.hasIndexSignature(type) }; } @@ -119375,23 +123230,23 @@ var ts; return Math.max(name.indexOf(ts.directorySeparator), name.indexOf(ts.altDirectorySeparator)) !== -1 ? { name: name, kind: kind, extension: extension, span: wholeSpan } : { name: name, kind: kind, extension: extension, span: span }; }); } - function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { - return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); + function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) { + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences)); } - function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) { + function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = sourceFile.path; var scriptDirectory = ts.getDirectoryPath(scriptPath); return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue)) - ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) + ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, preferences) : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); } function getExtensionOptions(compilerOptions, includeExtensions) { if (includeExtensions === void 0) { includeExtensions = false; } return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions: includeExtensions }; } - function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) { - var extensionOptions = getExtensionOptions(compilerOptions); + function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, preferences) { + var extensionOptions = getExtensionOptions(compilerOptions, preferences.importModuleSpecifierEnding === "js"); if (compilerOptions.rootDirs) { return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); } @@ -119508,7 +123363,7 @@ var ts; continue; var patterns = paths[path]; if (patterns) { - var _loop_1 = function (name, kind, extension) { + var _loop_2 = function (name, kind, extension) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(function (entry) { return entry.name === name; })) { result.push(nameAndKind(name, kind, extension)); @@ -119516,7 +123371,7 @@ var ts; }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; - _loop_1(name, kind, extension); + _loop_2(name, kind, extension); } } } @@ -119551,7 +123406,7 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_2 = function (moduleName) { + var _loop_3 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); @@ -119559,7 +123414,7 @@ var ts; }; for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { var moduleName = _c[_b]; - _loop_2(moduleName); + _loop_3(moduleName); } } if (!foundGlobal) { @@ -119806,6 +123661,7 @@ var ts; SymbolOriginInfoKind[SymbolOriginInfoKind["Export"] = 4] = "Export"; SymbolOriginInfoKind[SymbolOriginInfoKind["Promise"] = 8] = "Promise"; SymbolOriginInfoKind[SymbolOriginInfoKind["Nullable"] = 16] = "Nullable"; + SymbolOriginInfoKind[SymbolOriginInfoKind["ResolvedExport"] = 32] = "ResolvedExport"; SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberNoExport"] = 2] = "SymbolMemberNoExport"; SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberExport"] = 6] = "SymbolMemberExport"; })(SymbolOriginInfoKind || (SymbolOriginInfoKind = {})); @@ -119818,8 +123674,14 @@ var ts; function originIsExport(origin) { return !!(origin && origin.kind & 4 /* Export */); } + function originIsResolvedExport(origin) { + return !!(origin && origin.kind === 32 /* ResolvedExport */); + } + function originIncludesSymbolName(origin) { + return originIsExport(origin) || originIsResolvedExport(origin); + } function originIsPackageJsonImport(origin) { - return originIsExport(origin) && !!origin.isFromPackageJson; + return (originIsExport(origin) || originIsResolvedExport(origin)) && !!origin.isFromPackageJson; } function originIsPromise(origin) { return !!(origin.kind & 8 /* Promise */); @@ -119845,52 +123707,6 @@ var ts; GlobalsSearch[GlobalsSearch["Success"] = 1] = "Success"; GlobalsSearch[GlobalsSearch["Fail"] = 2] = "Fail"; })(GlobalsSearch || (GlobalsSearch = {})); - function createImportSuggestionsForFileCache() { - var cache; - var projectVersion; - var fileName; - return { - isEmpty: function () { - return !cache; - }, - clear: function () { - cache = undefined; - fileName = undefined; - projectVersion = undefined; - }, - set: function (file, suggestions, version) { - cache = suggestions; - fileName = file; - if (version) { - projectVersion = version; - } - }, - get: function (file, checker, version) { - if (file !== fileName) { - return undefined; - } - if (version) { - return projectVersion === version ? cache : undefined; - } - ts.forEach(cache, function (suggestion) { - var _a, _b, _c; - // If the symbol/moduleSymbol was a merged symbol, it will have a new identity - // in the checker, even though the symbols to merge are the same (guaranteed by - // cache invalidation in synchronizeHostData). - if ((_a = suggestion.symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) { - suggestion.symbol = checker.getMergedSymbol(suggestion.origin.isDefaultExport - ? (_b = suggestion.symbol.declarations[0].localSymbol) !== null && _b !== void 0 ? _b : suggestion.symbol.declarations[0].symbol - : suggestion.symbol.declarations[0].symbol); - } - if ((_c = suggestion.origin.moduleSymbol.declarations) === null || _c === void 0 ? void 0 : _c.length) { - suggestion.origin.moduleSymbol = checker.getMergedSymbol(suggestion.origin.moduleSymbol.declarations[0].symbol); - } - }); - return cache; - }, - }; - } - Completions.createImportSuggestionsForFileCache = createImportSuggestionsForFileCache; function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); @@ -119898,6 +123714,13 @@ var ts; if (triggerCharacter && !ts.isInString(sourceFile, position, contextToken) && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) { return undefined; } + if (triggerCharacter === " ") { + // `isValidTrigger` ensures we are at `import |` + if (preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) { + return { isGlobalCompletion: true, isMemberCompletion: false, isNewIdentifierLocation: true, isIncomplete: true, entries: [] }; + } + return undefined; + } var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, contextToken, typeChecker, compilerOptions, host, log, preferences); if (stringCompletions) { return stringCompletions; @@ -119921,6 +123744,8 @@ var ts; return jsdocCompletionInfo(ts.JsDoc.getJSDocTagCompletions()); case 3 /* JsDocParameterName */: return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag)); + case 4 /* Keywords */: + return specificKeywordCompletionInfo(completionData.keywords); default: return ts.Debug.assertNever(completionData); } @@ -119929,33 +123754,36 @@ var ts; function jsdocCompletionInfo(entries) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } + function specificKeywordCompletionInfo(keywords) { + return { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: false, + entries: keywords.map(function (k) { return ({ + name: ts.tokenToString(k), + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, + sortText: SortText.GlobalsOrKeywords, + }); }), + }; + } function getOptionalReplacementSpan(location) { // StringLiteralLike locations are handled separately in stringCompletions.ts return (location === null || location === void 0 ? void 0 : location.kind) === 78 /* Identifier */ ? ts.createTextSpanFromNode(location) : undefined; } function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { - var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextMap = completionData.symbolToSortTextMap; - if (location && location.parent && ts.isJsxClosingElement(location.parent)) { - // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, - // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. - // For example: - // var x =
" with type any - // And at `
` (with a closing `>`), the completion list will contain "div". - var tagName = location.parent.parent.openingElement.tagName; - var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 31 /* GreaterThanToken */, sourceFile); - var entry = { - name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), - kind: "class" /* classElement */, - kindModifiers: undefined, - sortText: SortText.LocationPriority, - }; - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, optionalReplacementSpan: getOptionalReplacementSpan(location), entries: [entry] }; + var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation, isJsxIdentifierExpected = completionData.isJsxIdentifierExpected, importCompletionNode = completionData.importCompletionNode, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextMap = completionData.symbolToSortTextMap; + // Verify if the file is JSX language variant + if (ts.getLanguageVariant(sourceFile.scriptKind) === 1 /* JSX */) { + var completionInfo = getJsxClosingTagCompletion(location, sourceFile); + if (completionInfo) { + return completionInfo; + } } var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, - /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); + /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { @@ -119963,7 +123791,7 @@ var ts; return undefined; } getCompletionEntriesFromSymbols(symbols, entries, - /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); + /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); } if (keywordFilters !== 0 /* None */) { var entryNames = new ts.Set(entries.map(function (e) { return e.name; })); @@ -119999,6 +123827,49 @@ var ts; return false; } } + function getJsxClosingTagCompletion(location, sourceFile) { + // We wanna walk up the tree till we find a JSX closing element + var jsxClosingElement = ts.findAncestor(location, function (node) { + switch (node.kind) { + case 277 /* JsxClosingElement */: + return true; + case 43 /* SlashToken */: + case 31 /* GreaterThanToken */: + case 78 /* Identifier */: + case 202 /* PropertyAccessExpression */: + return false; + default: + return "quit"; + } + }); + if (jsxClosingElement) { + // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, + // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. + // For example: + // var x =
" with type any + // And at `
` (with a closing `>`), the completion list will contain "div". + // And at property access expressions ` ` the completion will + // return full closing tag with an optional replacement span + // For example: + // var x = + // var y = + // the completion list at "1" and "2" will contain "MainComponent.Child" with a replacement span of closing tag name + var hasClosingAngleBracket = !!ts.findChildOfKind(jsxClosingElement, 31 /* GreaterThanToken */, sourceFile); + var tagName = jsxClosingElement.parent.openingElement.tagName; + var closingTag = tagName.getText(sourceFile); + var fullClosingTag = closingTag + (hasClosingAngleBracket ? "" : ">"); + var replacementSpan = ts.createTextSpanFromNode(jsxClosingElement.tagName); + var entry = { + name: fullClosingTag, + kind: "class" /* classElement */, + kindModifiers: undefined, + sortText: SortText.LocationPriority, + }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, optionalReplacementSpan: replacementSpan, entries: [entry] }; + } + return; + } function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location @@ -120025,9 +123896,13 @@ var ts; function createCompletionEntryForLiteral(sourceFile, preferences, literal) { return { name: completionNameForLiteral(sourceFile, preferences, literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority }; } - function createCompletionEntry(symbol, sortText, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { + function createCompletionEntry(symbol, sortText, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, options, preferences) { + var _a; var insertText; var replacementSpan = ts.getReplacementSpanForContextToken(contextToken); + var data; + var isSnippet; + var sourceDisplay; var insertQuestionDot = origin && originIsNullableMember(origin); var useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; if (origin && originIsThisType(origin)) { @@ -120071,9 +123946,24 @@ var ts; insertText = needsConvertPropertyAccess ? "" + awaitText + insertText : "" + awaitText + (insertQuestionDot ? "?." : ".") + insertText; replacementSpan = ts.createTextSpanFromBounds(propertyAccessToConvert.getStart(sourceFile), propertyAccessToConvert.end); } + if (originIsResolvedExport(origin)) { + ts.Debug.assertIsDefined(importCompletionNode); + (_a = getInsertTextAndReplacementSpanForImportCompletion(name, importCompletionNode, origin, useSemicolons, options, preferences), insertText = _a.insertText, replacementSpan = _a.replacementSpan); + sourceDisplay = [ts.textPart(origin.moduleSpecifier)]; + isSnippet = preferences.includeCompletionsWithSnippetText ? true : undefined; + } if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { return undefined; } + if (originIsExport(origin) || originIsResolvedExport(origin)) { + data = { + exportName: origin.exportName, + fileName: origin.fileName, + ambientModuleName: origin.fileName ? undefined : ts.stripQuotes(origin.moduleSymbol.name), + isPackageJsonImport: origin.isFromPackageJson ? true : undefined, + moduleSpecifier: originIsResolvedExport(origin) ? origin.moduleSpecifier : undefined, + }; + } // TODO(drosen): Right now we just permit *all* semantic meanings when calling // 'getSymbolKind' which is permissible given that it is backwards compatible; but // really we should consider passing the meaning for the node so that we don't report @@ -120091,8 +123981,29 @@ var ts; isRecommended: isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker) || undefined, insertText: insertText, replacementSpan: replacementSpan, + sourceDisplay: sourceDisplay, + isSnippet: isSnippet, isPackageJsonImport: originIsPackageJsonImport(origin) || undefined, - }; + isImportStatementCompletion: originIsResolvedExport(origin) || undefined, + data: data, + }; + } + function getInsertTextAndReplacementSpanForImportCompletion(name, importCompletionNode, origin, useSemicolons, options, preferences) { + var sourceFile = importCompletionNode.getSourceFile(); + var replacementSpan = ts.createTextSpanFromNode(importCompletionNode, sourceFile); + var quotedModuleSpecifier = ts.quote(sourceFile, preferences, origin.moduleSpecifier); + var exportKind = origin.isDefaultExport ? 1 /* Default */ : + origin.exportName === "export=" /* ExportEquals */ ? 2 /* ExportEquals */ : + 0 /* Named */; + var tabStop = preferences.includeCompletionsWithSnippetText ? "$1" : ""; + var importKind = ts.codefix.getImportKind(sourceFile, exportKind, options); + var suffix = useSemicolons ? ";" : ""; + switch (importKind) { + case 3 /* CommonJS */: return { replacementSpan: replacementSpan, insertText: "import " + name + tabStop + " = require(" + quotedModuleSpecifier + ")" + suffix }; + case 1 /* Default */: return { replacementSpan: replacementSpan, insertText: "import " + name + tabStop + " from " + quotedModuleSpecifier + suffix }; + case 2 /* Namespace */: return { replacementSpan: replacementSpan, insertText: "import * as " + name + tabStop + " from " + quotedModuleSpecifier + suffix }; + case 0 /* Named */: return { replacementSpan: replacementSpan, insertText: "import { " + name + tabStop + " } from " + quotedModuleSpecifier + suffix }; + } } function quotePropertyName(sourceFile, preferences, name) { if (/^\d+$/.test(name)) { @@ -120108,29 +124019,31 @@ var ts; if (originIsExport(origin)) { return ts.stripQuotes(origin.moduleSymbol.name); } + if (originIsResolvedExport(origin)) { + return origin.moduleSpecifier; + } if ((origin === null || origin === void 0 ? void 0 : origin.kind) === 1 /* ThisType */) { return CompletionSource.ThisProperty; } } - function getCompletionEntriesFromSymbols(symbols, entries, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) { + function getCompletionEntriesFromSymbols(symbols, entries, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) { var start = ts.timestamp(); + var variableDeclaration = getVariableDeclaration(location); + var useSemicolons = ts.probablyUsesSemicolons(sourceFile); // Tracks unique names. // Value is set to false for global variables or completions from external module exports, because we can have multiple of those; // true otherwise. Based on the order we add things we will always see locals first, then globals, then module exports. // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. var uniques = new ts.Map(); - for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { - var symbol = symbols_1[_i]; - var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; + for (var i = 0; i < symbols.length; i++) { + var symbol = symbols[i]; + var origin = symbolToOriginInfoMap === null || symbolToOriginInfoMap === void 0 ? void 0 : symbolToOriginInfoMap[i]; var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, !!jsxIdentifierExpected); - if (!info) { + if (!info || uniques.get(info.name) || kind === 1 /* Global */ && symbolToSortTextMap && !shouldIncludeSymbol(symbol, symbolToSortTextMap)) { continue; } var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; - if (uniques.get(name)) { - continue; - } - var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); + var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, compilerOptions, preferences); if (!entry) { continue; } @@ -120147,6 +124060,46 @@ var ts; has: function (name) { return uniques.has(name); }, add: function (name) { return uniques.set(name, true); }, }; + function shouldIncludeSymbol(symbol, symbolToSortTextMap) { + if (!ts.isSourceFile(location)) { + // export = /**/ here we want to get all meanings, so any symbol is ok + if (ts.isExportAssignment(location.parent)) { + return true; + } + // Filter out variables from their own initializers + // `const a = /* no 'a' here */` + if (variableDeclaration && symbol.valueDeclaration === variableDeclaration) { + return false; + } + // External modules can have global export declarations that will be + // available as global keywords in all scopes. But if the external module + // already has an explicit export and user only wants to user explicit + // module imports then the global keywords will be filtered out so auto + // import suggestions will win in the completion + var symbolOrigin = ts.skipAlias(symbol, typeChecker); + // We only want to filter out the global keywords + // Auto Imports are not available for scripts so this conditional is always false + if (!!sourceFile.externalModuleIndicator + && !compilerOptions.allowUmdGlobalAccess + && symbolToSortTextMap[ts.getSymbolId(symbol)] === SortText.GlobalsOrKeywords + && (symbolToSortTextMap[ts.getSymbolId(symbolOrigin)] === SortText.AutoImportSuggestions + || symbolToSortTextMap[ts.getSymbolId(symbolOrigin)] === SortText.LocationPriority)) { + return false; + } + // Continue with origin symbol + symbol = symbolOrigin; + // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) + if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { + return !!(symbol.flags & 1920 /* Namespace */); + } + if (isTypeOnlyLocation) { + // It's a type, but you can reach it by namespace.type as well + return symbolCanBeReferencedAtTypeLocation(symbol, typeChecker); + } + } + // expressions are value space (which includes the value namespaces) + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 111551 /* Value */); + } } Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; function getLabelCompletionAtPosition(node) { @@ -120180,6 +124133,20 @@ var ts; return entries; } function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences) { + if (entryId.data) { + var autoImport = getAutoImportSymbolFromCompletionEntryData(entryId.name, entryId.data, program, host); + if (autoImport) { + return { + type: "symbol", + symbol: autoImport.symbol, + location: ts.getTouchingPropertyName(sourceFile, position), + previousToken: ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined), + isJsxInitializer: false, + isTypeOnlyLocation: false, + origin: autoImport.origin, + }; + } + } var compilerOptions = program.getCompilerOptions(); var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId, host); if (!completionData) { @@ -120196,11 +124163,11 @@ var ts; // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - return ts.firstDefined(symbols, function (symbol) { - var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + return ts.firstDefined(symbols, function (symbol, index) { + var origin = symbolToOriginInfoMap[index]; var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind, completionData.isJsxIdentifierExpected); return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source - ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation } + ? { type: "symbol", symbol: symbol, location: location, origin: origin, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation } : undefined; }) || { type: "none" }; } @@ -120210,7 +124177,7 @@ var ts; var name = entryId.name; var contextToken = ts.findPrecedingToken(position, sourceFile); if (ts.isInString(sourceFile, position, contextToken)) { - return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken); + return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken, preferences); } // Compute all the completion symbols again. var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences); @@ -120224,13 +124191,15 @@ var ts; return ts.JsDoc.getJSDocTagCompletionDetails(name); case 3 /* JsDocParameterName */: return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); + case 4 /* Keywords */: + return request.keywords.indexOf(ts.stringToToken(name)) > -1 ? createSimpleDetails(name, "keyword" /* keyword */, ts.SymbolDisplayPartKind.keyword) : undefined; default: return ts.Debug.assertNever(request); } } case "symbol": { - var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, origin = symbolCompletion.origin, previousToken = symbolCompletion.previousToken; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(origin, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, entryId.data), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } case "literal": { @@ -120256,15 +124225,17 @@ var ts; } Completions.createCompletionDetailsForSymbol = createCompletionDetailsForSymbol; function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { - return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; + return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source, sourceDisplay: source }; } Completions.createCompletionDetails = createCompletionDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) { - var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { + function getCompletionEntryCodeActionsAndSourceDisplay(origin, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data) { + if (data === null || data === void 0 ? void 0 : data.moduleSpecifier) { + return { codeActions: undefined, sourceDisplay: [ts.textPart(data.moduleSpecifier)] }; + } + if (!origin || !originIsExport(origin)) { return { codeActions: undefined, sourceDisplay: undefined }; } - var moduleSymbol = symbolOriginInfo.moduleSymbol; + var moduleSymbol = origin.moduleSymbol; var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, compilerOptions.target), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; @@ -120280,6 +124251,7 @@ var ts; CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName"; CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag"; CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName"; + CompletionDataKind[CompletionDataKind["Keywords"] = 4] = "Keywords"; })(CompletionDataKind || (CompletionDataKind = {})); var CompletionKind; (function (CompletionKind) { @@ -120307,11 +124279,11 @@ var ts; return ts.getContextualTypeFromParent(previousToken, checker); case 62 /* EqualsToken */: switch (parent.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return checker.getContextualType(parent.initializer); // TODO: GH#18217 - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return checker.getTypeAtLocation(parent.left); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return checker.getContextualTypeForJsxAttribute(parent); default: return undefined; @@ -120321,7 +124293,7 @@ var ts; case 81 /* CaseKeyword */: return ts.getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); case 18 /* OpenBraceToken */: - return ts.isJsxExpression(parent) && parent.parent.kind !== 273 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; + return ts.isJsxExpression(parent) && parent.parent.kind !== 274 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; default: var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile); return argInfo ? @@ -120340,7 +124312,8 @@ var ts; return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); } function isModuleSymbol(symbol) { - return symbol.declarations.some(function (d) { return d.kind === 297 /* SourceFile */; }); + var _a; + return !!((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d.kind === 298 /* SourceFile */; })); } function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId, host) { var typeChecker = program.getTypeChecker(); @@ -120391,11 +124364,11 @@ var ts; if (tag.tagName.pos <= position && position <= tag.tagName.end) { return { kind: 1 /* JsDocTagName */ }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 301 /* JSDocTypeExpression */) { + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 302 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 333 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 337 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -120420,7 +124393,7 @@ var ts; var contextToken = previousToken; // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. - if (contextToken && position <= contextToken.end && (ts.isIdentifierOrPrivateIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { + if (contextToken && position <= contextToken.end && (ts.isMemberName(contextToken) || ts.isKeyword(contextToken.kind))) { var start_1 = ts.timestamp(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1)); @@ -120436,10 +124409,22 @@ var ts; var isStartingCloseTag = false; var isJsxInitializer = false; var isJsxIdentifierExpected = false; + var importCompletionNode; var location = ts.getTouchingPropertyName(sourceFile, position); if (contextToken) { + var importCompletionCandidate = getImportCompletionNode(contextToken); + if (importCompletionCandidate === 153 /* FromKeyword */) { + return { kind: 4 /* Keywords */, keywords: [153 /* FromKeyword */] }; + } + // Import statement completions use `insertText`, and also require the `data` property of `CompletionEntryIdentifier` + // added in TypeScript 4.3 to be sent back from the client during `getCompletionEntryDetails`. Since this feature + // is not backward compatible with older clients, the language service defaults to disabling it, allowing newer clients + // to opt in with the `includeCompletionsForImportStatements` user preference. + if (importCompletionCandidate && preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) { + importCompletionNode = importCompletionCandidate; + } // Bail out if this is a known invalid completion location - if (isCompletionListBlocker(contextToken)) { + if (!importCompletionNode && isCompletionListBlocker(contextToken)) { log("Returning an empty list because completion was requested in an invalid position."); return undefined; } @@ -120448,7 +124433,7 @@ var ts; isRightOfDot = contextToken.kind === 24 /* DotToken */; isRightOfQuestionDot = contextToken.kind === 28 /* QuestionDotToken */; switch (parent.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: propertyAccessToConvert = parent; node = propertyAccessToConvert.expression; if ((ts.isCallExpression(node) || ts.isFunctionLike(node)) && @@ -120461,14 +124446,14 @@ var ts; return undefined; } break; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: node = parent.left; break; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: node = parent.name; break; - case 195 /* ImportType */: - case 226 /* MetaProperty */: + case 196 /* ImportType */: + case 227 /* MetaProperty */: node = parent; break; default: @@ -120477,11 +124462,11 @@ var ts; return undefined; } } - else if (sourceFile.languageVariant === 1 /* JSX */) { + else if (!importCompletionNode && sourceFile.languageVariant === 1 /* JSX */) { // // If the tagname is a property access expression, we will then walk up to the top most of property access expression. // Then, try to get a JSX container and its associated attributes type. - if (parent && parent.kind === 201 /* PropertyAccessExpression */) { + if (parent && parent.kind === 202 /* PropertyAccessExpression */) { contextToken = parent; parent = parent.parent; } @@ -120489,45 +124474,45 @@ var ts; if (currentToken.parent === location) { switch (currentToken.kind) { case 31 /* GreaterThanToken */: - if (currentToken.parent.kind === 273 /* JsxElement */ || currentToken.parent.kind === 275 /* JsxOpeningElement */) { + if (currentToken.parent.kind === 274 /* JsxElement */ || currentToken.parent.kind === 276 /* JsxOpeningElement */) { location = currentToken; } break; case 43 /* SlashToken */: - if (currentToken.parent.kind === 274 /* JsxSelfClosingElement */) { + if (currentToken.parent.kind === 275 /* JsxSelfClosingElement */) { location = currentToken; } break; } } switch (parent.kind) { - case 276 /* JsxClosingElement */: + case 277 /* JsxClosingElement */: if (contextToken.kind === 43 /* SlashToken */) { isStartingCloseTag = true; location = contextToken; } break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (!binaryExpressionMayBeOpenTag(parent)) { break; } // falls through - case 274 /* JsxSelfClosingElement */: - case 273 /* JsxElement */: - case 275 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + case 274 /* JsxElement */: + case 276 /* JsxOpeningElement */: isJsxIdentifierExpected = true; if (contextToken.kind === 29 /* LessThanToken */) { isRightOfOpenTag = true; location = contextToken; } break; - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: // For `
`, `parent` will be `{true}` and `previousToken` will be `}` if (previousToken.kind === 19 /* CloseBraceToken */ && currentToken.kind === 31 /* GreaterThanToken */) { isJsxIdentifierExpected = true; } break; - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: // For `
`, `parent` will be JsxAttribute and `previousToken` will be its initializer if (parent.initializer === previousToken && previousToken.end < position) { @@ -120561,8 +124546,11 @@ var ts; var symbols = []; var symbolToOriginInfoMap = []; var symbolToSortTextMap = []; - var importSuggestionsCache = host.getImportSuggestionsCache && host.getImportSuggestionsCache(); + var seenPropertySymbols = new ts.Map(); var isTypeOnly = isTypeOnlyCompletion(); + var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { + return ts.createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); + }); if (isRightOfDot || isRightOfQuestionDot) { getTypeScriptMemberSymbols(); } @@ -120571,7 +124559,7 @@ var ts; ts.Debug.assertEachIsDefined(tagSymbols, "getJsxIntrinsicTagNames() should all be defined"); tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); - completionKind = 3 /* MemberLike */; + completionKind = 1 /* Global */; keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { @@ -120580,7 +124568,7 @@ var ts; if (tagSymbol) { symbols = [tagSymbol]; } - completionKind = 3 /* MemberLike */; + completionKind = 1 /* Global */; keywordFilters = 0 /* None */; } else { @@ -120613,14 +124601,15 @@ var ts; symbolToSortTextMap: symbolToSortTextMap, isTypeOnlyLocation: isTypeOnly, isJsxIdentifierExpected: isJsxIdentifierExpected, + importCompletionNode: importCompletionNode, }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 326 /* JSDocParameterTag */: - case 333 /* JSDocPropertyTag */: - case 327 /* JSDocReturnTag */: - case 329 /* JSDocTypeTag */: - case 331 /* JSDocTypedefTag */: + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: + case 331 /* JSDocReturnTag */: + case 333 /* JSDocTypeTag */: + case 335 /* JSDocTypedefTag */: return true; default: return false; @@ -120648,10 +124637,10 @@ var ts; var exportedSymbols = typeChecker.getExportsOfModule(symbol); ts.Debug.assertEachIsDefined(exportedSymbols, "getExportsOfModule() should all be defined"); var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess(isImportType ? node : (node.parent), symbol.name); }; - var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; + var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol, typeChecker); }; var isValidAccess = isNamespaceName // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion. - ? function (symbol) { return !!(symbol.flags & 1920 /* Namespace */) && !symbol.declarations.every(function (d) { return d.parent === node.parent; }); } + ? function (symbol) { var _a; return !!(symbol.flags & 1920 /* Namespace */) && !((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return d.parent === node.parent; })); } : isRhsOfImportDeclaration ? // Any kind is allowed when dotting off namespace in internal import equals declaration function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : @@ -120665,7 +124654,7 @@ var ts; // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). if (!isTypeLocation && symbol.declarations && - symbol.declarations.some(function (d) { return d.kind !== 297 /* SourceFile */ && d.kind !== 256 /* ModuleDeclaration */ && d.kind !== 255 /* EnumDeclaration */; })) { + symbol.declarations.some(function (d) { return d.kind !== 298 /* SourceFile */ && d.kind !== 257 /* ModuleDeclaration */ && d.kind !== 256 /* EnumDeclaration */; })) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { @@ -120712,7 +124701,7 @@ var ts; if (isRightOfQuestionDot && ts.some(type.getCallSignatures())) { isNewIdentifierLocation = true; } - var propertyAccess = node.kind === 195 /* ImportType */ ? node : node.parent; + var propertyAccess = node.kind === 196 /* ImportType */ ? node : node.parent; if (isUncheckedFile) { // In javascript files, for union types, we don't just get the members that // the individual types have in common, we also include all the members that @@ -120751,13 +124740,24 @@ var ts; var nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName); // If this is nested like for `namespace N { export const sym = Symbol(); }`, we'll add the completion for `N`. var firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker); - if (firstAccessibleSymbol && !symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)]) { + if (firstAccessibleSymbol && ts.addToSeen(seenPropertySymbols, ts.getSymbolId(firstAccessibleSymbol))) { + var index = symbols.length; symbols.push(firstAccessibleSymbol); var moduleSymbol = firstAccessibleSymbol.parent; - symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] = - !moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol) - ? { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) } - : { kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), moduleSymbol: moduleSymbol, isDefaultExport: false }; + if (!moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol)) { + symbolToOriginInfoMap[index] = { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) }; + } + else { + var origin = { + kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), + moduleSymbol: moduleSymbol, + isDefaultExport: false, + symbolName: firstAccessibleSymbol.name, + exportName: firstAccessibleSymbol.name, + fileName: ts.isExternalModuleNameRelative(ts.stripQuotes(moduleSymbol.name)) ? ts.cast(moduleSymbol.valueDeclaration, ts.isSourceFile).fileName : undefined, + }; + symbolToOriginInfoMap[index] = origin; + } } else if (preferences.includeCompletionsWithInsertText) { addSymbolOriginInfo(symbol); @@ -120777,11 +124777,11 @@ var ts; } function addSymbolOriginInfo(symbol) { if (preferences.includeCompletionsWithInsertText) { - if (insertAwait && !symbolToOriginInfoMap[ts.getSymbolId(symbol)]) { - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: getNullableSymbolOriginInfoKind(8 /* Promise */) }; + if (insertAwait && ts.addToSeen(seenPropertySymbols, ts.getSymbolId(symbol))) { + symbolToOriginInfoMap[symbols.length] = { kind: getNullableSymbolOriginInfoKind(8 /* Promise */) }; } else if (insertQuestionDot) { - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 16 /* Nullable */ }; + symbolToOriginInfoMap[symbols.length] = { kind: 16 /* Nullable */ }; } } } @@ -120794,7 +124794,9 @@ var ts; return ts.isIdentifier(e) ? e : ts.isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : undefined; } function tryGetGlobalSymbols() { - var result = tryGetObjectLikeCompletionSymbols() + var result = tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() + || tryGetObjectLikeCompletionSymbols() + || tryGetImportCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() || tryGetLocalNamedExportCompletionSymbols() || tryGetConstructorCompletion() @@ -120827,11 +124829,17 @@ var ts; isNewIdentifierLocation = false; return 1 /* Success */; } + function tryGetImportCompletionSymbols() { + if (!importCompletionNode) + return 0 /* Continue */; + collectAutoImports(/*resolveModuleSpecifiers*/ true); + return 1 /* Success */; + } function getGlobalCompletions() { keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; - isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); + isNewIdentifierLocation = isNewIdentifierDefinitionLocation(); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); } @@ -120868,50 +124876,36 @@ var ts; var symbolMeanings = (isTypeOnly ? 0 /* None */ : 111551 /* Value */) | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); ts.Debug.assertEachIsDefined(symbols, "getSymbolsInScope() should all be defined"); - for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { - var symbol = symbols_2[_i]; + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; if (!typeChecker.isArgumentsSymbol(symbol) && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === sourceFile; })) { symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.GlobalsOrKeywords; } } // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` - if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 297 /* SourceFile */) { + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 298 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { for (var _a = 0, _b = getPropertiesForCompletion(thisType, typeChecker); _a < _b.length; _a++) { var symbol = _b[_a]; - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 1 /* ThisType */ }; + symbolToOriginInfoMap[symbols.length] = { kind: 1 /* ThisType */ }; symbols.push(symbol); symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.SuggestedClassMembers; } } } - if (shouldOfferImportCompletions()) { - var lowerCaseTokenText_1 = previousToken && ts.isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; - var autoImportSuggestions = getSymbolsFromOtherSourceFileExports(program.getCompilerOptions().target, host); - if (!detailsEntryId && importSuggestionsCache) { - importSuggestionsCache.set(sourceFile.fileName, autoImportSuggestions, host.getProjectVersion && host.getProjectVersion()); - } - autoImportSuggestions.forEach(function (_a) { - var symbol = _a.symbol, symbolName = _a.symbolName, skipFilter = _a.skipFilter, origin = _a.origin; - if (detailsEntryId) { - if (detailsEntryId.source && ts.stripQuotes(origin.moduleSymbol.name) !== detailsEntryId.source) { - return; - } - } - else if (!skipFilter && !stringContainsCharactersInOrder(symbolName.toLowerCase(), lowerCaseTokenText_1)) { - return; - } - var symbolId = ts.getSymbolId(symbol); - symbols.push(symbol); - symbolToOriginInfoMap[symbolId] = origin; - symbolToSortTextMap[symbolId] = SortText.AutoImportSuggestions; - }); + collectAutoImports(/*resolveModuleSpecifier*/ false); + if (isTypeOnly) { + keywordFilters = contextToken && ts.isAssertionExpression(contextToken.parent) + ? 6 /* TypeAssertionKeywords */ + : 7 /* TypeKeywords */; } - filterGlobalCompletion(symbols); } function shouldOfferImportCompletions() { + // If already typing an import statement, provide completions for it. + if (importCompletionNode) + return true; // If current completion is for non-contextual Object literal shortahands, ignore auto-import symbols if (isNonContextualObjectLiteral) return false; @@ -120929,42 +124923,15 @@ var ts; } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { - case 297 /* SourceFile */: - case 218 /* TemplateExpression */: - case 283 /* JsxExpression */: - case 230 /* Block */: + case 298 /* SourceFile */: + case 219 /* TemplateExpression */: + case 284 /* JsxExpression */: + case 231 /* Block */: return true; default: return ts.isStatement(scopeNode); } } - function filterGlobalCompletion(symbols) { - var isTypeOnly = isTypeOnlyCompletion(); - if (isTypeOnly) { - keywordFilters = contextToken && ts.isAssertionExpression(contextToken.parent) - ? 6 /* TypeAssertionKeywords */ - : 7 /* TypeKeywords */; - } - ts.filterMutate(symbols, function (symbol) { - if (!ts.isSourceFile(location)) { - // export = /**/ here we want to get all meanings, so any symbol is ok - if (ts.isExportAssignment(location.parent)) { - return true; - } - symbol = ts.skipAlias(symbol, typeChecker); - // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) - if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { - return !!(symbol.flags & 1920 /* Namespace */); - } - if (isTypeOnly) { - // It's a type, but you can reach it by namespace.type as well - return symbolCanBeReferencedAtTypeLocation(symbol); - } - } - // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 111551 /* Value */); - }); - } function isTypeOnlyCompletion() { return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && @@ -120974,191 +124941,105 @@ var ts; } function isContextTokenValueLocation(contextToken) { return contextToken && - contextToken.kind === 111 /* TypeOfKeyword */ && - (contextToken.parent.kind === 176 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); + ((contextToken.kind === 111 /* TypeOfKeyword */ && + (contextToken.parent.kind === 177 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent))) || + (contextToken.kind === 127 /* AssertsKeyword */ && contextToken.parent.kind === 173 /* TypePredicate */)); } function isContextTokenTypeLocation(contextToken) { if (contextToken) { var parentKind = contextToken.parent.kind; switch (contextToken.kind) { case 58 /* ColonToken */: - return parentKind === 163 /* PropertyDeclaration */ || - parentKind === 162 /* PropertySignature */ || - parentKind === 160 /* Parameter */ || - parentKind === 249 /* VariableDeclaration */ || + return parentKind === 164 /* PropertyDeclaration */ || + parentKind === 163 /* PropertySignature */ || + parentKind === 161 /* Parameter */ || + parentKind === 250 /* VariableDeclaration */ || ts.isFunctionLikeKind(parentKind); case 62 /* EqualsToken */: - return parentKind === 254 /* TypeAliasDeclaration */; + return parentKind === 255 /* TypeAliasDeclaration */; case 126 /* AsKeyword */: - return parentKind === 224 /* AsExpression */; + return parentKind === 225 /* AsExpression */; case 29 /* LessThanToken */: - return parentKind === 173 /* TypeReference */ || - parentKind === 206 /* TypeAssertionExpression */; + return parentKind === 174 /* TypeReference */ || + parentKind === 207 /* TypeAssertionExpression */; case 93 /* ExtendsKeyword */: - return parentKind === 159 /* TypeParameter */; + return parentKind === 160 /* TypeParameter */; } } return false; } - /** True if symbol is a type or a module containing at least one type. */ - function symbolCanBeReferencedAtTypeLocation(symbol, seenModules) { - if (seenModules === void 0) { seenModules = new ts.Map(); } - var sym = ts.skipAlias(symbol.exportSymbol || symbol, typeChecker); - return !!(sym.flags & 788968 /* Type */) || - !!(sym.flags & 1536 /* Module */) && - ts.addToSeen(seenModules, ts.getSymbolId(sym)) && - typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); - } - /** - * Gathers symbols that can be imported from other files, de-duplicating along the way. Symbols can be "duplicates" - * if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but - * it’s just an alias to the first, and both have the same name, so we generally want to filter those aliases out, - * if and only if the the first can be imported (it may be excluded due to package.json filtering in - * `codefix.forEachExternalModuleToImportFrom`). - * - * Example. Imagine a chain of node_modules re-exporting one original symbol: - * - * ```js - * node_modules/x/index.js node_modules/y/index.js node_modules/z/index.js - * +-----------------------+ +--------------------------+ +--------------------------+ - * | | | | | | - * | export const foo = 0; | <--- | export { foo } from 'x'; | <--- | export { foo } from 'y'; | - * | | | | | | - * +-----------------------+ +--------------------------+ +--------------------------+ - * ``` - * - * Also imagine three buckets, which we’ll reference soon: - * - * ```md - * | | | | | | - * | **Bucket A** | | **Bucket B** | | **Bucket C** | - * | Symbols to | | Aliases to symbols | | Symbols to return | - * | definitely | | in Buckets A or C | | if nothing better | - * | return | | (don’t return these) | | comes along | - * |__________________| |______________________| |___________________| - * ``` - * - * We _probably_ want to show `foo` from 'x', but not from 'y' or 'z'. However, if 'x' is not in a package.json, it - * will not appear in a `forEachExternalModuleToImportFrom` iteration. Furthermore, the order of iterations is not - * guaranteed, as it is host-dependent. Therefore, when presented with the symbol `foo` from module 'y' alone, we - * may not be sure whether or not it should go in the list. So, we’ll take the following steps: - * - * 1. Resolve alias `foo` from 'y' to the export declaration in 'x', get the symbol there, and see if that symbol is - * already in Bucket A (symbols we already know will be returned). If it is, put `foo` from 'y' in Bucket B - * (symbols that are aliases to symbols in Bucket A). If it’s not, put it in Bucket C. - * 2. Next, imagine we see `foo` from module 'z'. Again, we resolve the alias to the nearest export, which is in 'y'. - * At this point, if that nearest export from 'y' is in _any_ of the three buckets, we know the symbol in 'z' - * should never be returned in the final list, so put it in Bucket B. - * 3. Next, imagine we see `foo` from module 'x', the original. Syntactically, it doesn’t look like a re-export, so - * we can just check Bucket C to see if we put any aliases to the original in there. If they exist, throw them out. - * Put this symbol in Bucket A. - * 4. After we’ve iterated through every symbol of every module, any symbol left in Bucket C means that step 3 didn’t - * occur for that symbol---that is, the original symbol is not in Bucket A, so we should include the alias. Move - * everything from Bucket C to Bucket A. - */ - function getSymbolsFromOtherSourceFileExports(target, host) { - var cached = importSuggestionsCache && importSuggestionsCache.get(sourceFile.fileName, typeChecker, detailsEntryId && host.getProjectVersion ? host.getProjectVersion() : undefined); - if (cached) { - log("getSymbolsFromOtherSourceFileExports: Using cached list"); - return cached; - } - var startTime = ts.timestamp(); - log("getSymbolsFromOtherSourceFileExports: Recomputing list" + (detailsEntryId ? " for details entry" : "")); - var seenResolvedModules = new ts.Map(); - var seenExports = new ts.Map(); - /** Bucket B */ - var aliasesToAlreadyIncludedSymbols = new ts.Map(); - /** Bucket C */ - var aliasesToReturnIfOriginalsAreMissing = new ts.Map(); - /** Bucket A */ - var results = []; - /** Ids present in `results` for faster lookup */ - var resultSymbolIds = new ts.Map(); - ts.codefix.forEachExternalModuleToImportFrom(program, host, sourceFile, !detailsEntryId, /*useAutoImportProvider*/ true, function (moduleSymbol, _, program, isFromPackageJson) { - // Perf -- ignore other modules if this is a request for details - if (detailsEntryId && detailsEntryId.source && ts.stripQuotes(moduleSymbol.name) !== detailsEntryId.source) { - return; - } - var typeChecker = program.getTypeChecker(); - var resolvedModuleSymbol = typeChecker.resolveExternalModuleSymbol(moduleSymbol); - // resolvedModuleSymbol may be a namespace. A namespace may be `export =` by multiple module declarations, but only keep the first one. - if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { + /** Mutates `symbols`, `symbolToOriginInfoMap`, and `symbolToSortTextMap` */ + function collectAutoImports(resolveModuleSpecifiers) { + var _a, _b, _c, _d, _e; + if (!shouldOfferImportCompletions()) + return; + ts.Debug.assert(!(detailsEntryId === null || detailsEntryId === void 0 ? void 0 : detailsEntryId.data)); + var start = ts.timestamp(); + var moduleSpecifierCache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); + (_b = host.log) === null || _b === void 0 ? void 0 : _b.call(host, "collectAutoImports: starting, " + (resolveModuleSpecifiers ? "" : "not ") + "resolving module specifiers"); + if (moduleSpecifierCache) { + (_c = host.log) === null || _c === void 0 ? void 0 : _c.call(host, "collectAutoImports: module specifier cache size: " + moduleSpecifierCache.count()); + } + var lowerCaseTokenText = previousToken && ts.isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; + var exportInfo = ts.codefix.getSymbolToExportInfoMap(sourceFile, host, program); + var packageJsonAutoImportProvider = (_d = host.getPackageJsonAutoImportProvider) === null || _d === void 0 ? void 0 : _d.call(host); + var packageJsonFilter = detailsEntryId ? undefined : ts.createPackageJsonImportFilter(sourceFile, host); + exportInfo.forEach(function (info, key) { + var symbolName = key.substring(0, key.indexOf("|")); + if (!detailsEntryId && ts.isStringANonContextualKeyword(symbolName)) return; - } - // Don't add another completion for `export =` of a symbol that's already global. - // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. - if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, ts.isNonGlobalDeclaration)) { - pushSymbol(resolvedModuleSymbol, moduleSymbol, isFromPackageJson, /*skipFilter*/ true); - } - for (var _i = 0, _a = typeChecker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { - var symbol = _a[_i]; - var symbolId = ts.getSymbolId(symbol).toString(); - // `getExportsAndPropertiesOfModule` can include duplicates - if (!ts.addToSeen(seenExports, symbolId)) { - continue; - } - // If this is `export { _break as break };` (a keyword) -- skip this and prefer the keyword completion. - if (ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.propertyName && ts.isIdentifierANonContextualKeyword(d.name); })) { - continue; - } - // If `symbol.parent !== moduleSymbol`, this is an `export * from "foo"` re-export. Those don't create new symbols. - var isExportStarFromReExport = typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol; - // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). - if (isExportStarFromReExport || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !d.propertyName && !!d.parent.parent.moduleSpecifier; })) { - // Walk the export chain back one module (step 1 or 2 in diagrammed example). - // Or, in the case of `export * from "foo"`, `symbol` already points to the original export, so just use that. - var nearestExportSymbol = isExportStarFromReExport ? symbol : getNearestExportSymbol(symbol); - if (!nearestExportSymbol) - continue; - var nearestExportSymbolId = ts.getSymbolId(nearestExportSymbol).toString(); - var symbolHasBeenSeen = resultSymbolIds.has(nearestExportSymbolId) || aliasesToAlreadyIncludedSymbols.has(nearestExportSymbolId); - if (!symbolHasBeenSeen) { - aliasesToReturnIfOriginalsAreMissing.set(nearestExportSymbolId, { alias: symbol, moduleSymbol: moduleSymbol, isFromPackageJson: isFromPackageJson }); - aliasesToAlreadyIncludedSymbols.set(symbolId, true); - } - else { - // Perf - we know this symbol is an alias to one that’s already covered in `symbols`, so store it here - // in case another symbol re-exports this one; that way we can short-circuit as soon as we see this symbol id. - ts.addToSeen(aliasesToAlreadyIncludedSymbols, symbolId); - } - } - else { - // This is not a re-export, so see if we have any aliases pending and remove them (step 3 in diagrammed example) - aliasesToReturnIfOriginalsAreMissing.delete(symbolId); - pushSymbol(symbol, moduleSymbol, isFromPackageJson, /*skipFilter*/ false); - } + var isCompletionDetailsMatch = detailsEntryId && ts.some(info, function (i) { return detailsEntryId.source === ts.stripQuotes(i.moduleSymbol.name); }); + if (isCompletionDetailsMatch || isNameMatch(symbolName)) { + // If we don't need to resolve module specifiers, we can use any re-export that is importable at all + // (We need to ensure that at least one is importable to show a completion.) + var _a = resolveModuleSpecifiers + ? ts.codefix.getModuleSpecifierForBestExportInfo(info, sourceFile, program, host, preferences) + : { moduleSpecifier: undefined, exportInfo: ts.find(info, isImportableExportInfo) }, moduleSpecifier = _a.moduleSpecifier, exportInfo_1 = _a.exportInfo; + if (!exportInfo_1) + return; + var moduleFile = ts.tryCast(exportInfo_1.moduleSymbol.valueDeclaration, ts.isSourceFile); + var isDefaultExport = exportInfo_1.exportKind === 1 /* Default */; + var symbol = isDefaultExport && ts.getLocalSymbolForExportDefault(exportInfo_1.symbol) || exportInfo_1.symbol; + pushAutoImportSymbol(symbol, { + kind: resolveModuleSpecifiers ? 32 /* ResolvedExport */ : 4 /* Export */, + moduleSpecifier: moduleSpecifier, + symbolName: symbolName, + exportName: exportInfo_1.exportKind === 2 /* ExportEquals */ ? "export=" /* ExportEquals */ : exportInfo_1.symbol.name, + fileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, + isDefaultExport: isDefaultExport, + moduleSymbol: exportInfo_1.moduleSymbol, + isFromPackageJson: exportInfo_1.isFromPackageJson, + }); } }); - // By this point, any potential duplicates that were actually duplicates have been - // removed, so the rest need to be added. (Step 4 in diagrammed example) - aliasesToReturnIfOriginalsAreMissing.forEach(function (_a) { - var alias = _a.alias, moduleSymbol = _a.moduleSymbol, isFromPackageJson = _a.isFromPackageJson; - return pushSymbol(alias, moduleSymbol, isFromPackageJson, /*skipFilter*/ false); - }); - log("getSymbolsFromOtherSourceFileExports: " + (ts.timestamp() - startTime)); - return results; - function pushSymbol(symbol, moduleSymbol, isFromPackageJson, skipFilter) { - var isDefaultExport = symbol.escapedName === "default" /* Default */; - if (isDefaultExport) { - symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; + (_e = host.log) === null || _e === void 0 ? void 0 : _e.call(host, "collectAutoImports: done in " + (ts.timestamp() - start) + " ms"); + function isNameMatch(symbolName) { + var lowerCaseSymbolName = symbolName.toLowerCase(); + if (resolveModuleSpecifiers && lowerCaseTokenText) { + // Use a more restrictive filter if resolving module specifiers since resolving module specifiers is expensive. + return lowerCaseTokenText[0] === lowerCaseSymbolName[0] && stringContainsCharactersInOrder(lowerCaseSymbolName, lowerCaseTokenText); } - if (typeChecker.isUndefinedSymbol(symbol)) { - return; + return stringContainsCharactersInOrder(lowerCaseSymbolName, lowerCaseTokenText); + } + function isImportableExportInfo(info) { + var moduleFile = ts.tryCast(info.moduleSymbol.valueDeclaration, ts.isSourceFile); + if (!moduleFile) { + return packageJsonFilter + ? packageJsonFilter.allowsImportingAmbientModule(info.moduleSymbol, getModuleSpecifierResolutionHost(info.isFromPackageJson)) + : true; } - ts.addToSeen(resultSymbolIds, ts.getSymbolId(symbol)); - var origin = { kind: 4 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport, isFromPackageJson: isFromPackageJson }; - results.push({ - symbol: symbol, - symbolName: ts.getNameForExportedSymbol(symbol, target), - origin: origin, - skipFilter: skipFilter, - }); + return ts.isImportableFile(info.isFromPackageJson ? packageJsonAutoImportProvider : program, sourceFile, moduleFile, packageJsonFilter, getModuleSpecifierResolutionHost(info.isFromPackageJson), moduleSpecifierCache); } } - function getNearestExportSymbol(fromSymbol) { - return findAlias(typeChecker, fromSymbol, function (alias) { - return ts.some(alias.declarations, function (d) { return ts.isExportSpecifier(d) || !!d.localSymbol; }); - }); + function pushAutoImportSymbol(symbol, origin) { + var symbolId = ts.getSymbolId(symbol); + if (symbolToSortTextMap[symbolId] === SortText.GlobalsOrKeywords) { + // If an auto-importable symbol is available as a global, don't add the auto import + return; + } + symbolToOriginInfoMap[symbols.length] = origin; + symbolToSortTextMap[symbolId] = importCompletionNode ? SortText.LocationPriority : SortText.AutoImportSuggestions; + symbols.push(symbol); } /** * True if you could remove some characters in `a` to get `b`. @@ -121170,7 +125051,8 @@ var ts; return true; } var characterIndex = 0; - for (var strIndex = 0; strIndex < str.length; strIndex++) { + var len = str.length; + for (var strIndex = 0; strIndex < len; strIndex++) { if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) { characterIndex++; if (characterIndex === characters.length) { @@ -121206,7 +125088,7 @@ var ts; return true; } if (contextToken.kind === 31 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 275 /* JsxOpeningElement */) { + if (contextToken.parent.kind === 276 /* JsxOpeningElement */) { // Two possibilities: // 1.
/**/ // - contextToken: GreaterThanToken (before cursor) @@ -121216,54 +125098,56 @@ var ts; // - contextToken: GreaterThanToken (before cursor) // - location: GreaterThanToken (after cursor) // - same parent (JSXOpeningElement) - return location.parent.kind !== 275 /* JsxOpeningElement */; + return location.parent.kind !== 276 /* JsxOpeningElement */; } - if (contextToken.parent.kind === 276 /* JsxClosingElement */ || contextToken.parent.kind === 274 /* JsxSelfClosingElement */) { - return !!contextToken.parent.parent && contextToken.parent.parent.kind === 273 /* JsxElement */; + if (contextToken.parent.kind === 277 /* JsxClosingElement */ || contextToken.parent.kind === 275 /* JsxSelfClosingElement */) { + return !!contextToken.parent.parent && contextToken.parent.parent.kind === 274 /* JsxElement */; } } return false; } - function isNewIdentifierDefinitionLocation(previousToken) { - if (previousToken) { - var containingNodeKind = previousToken.parent.kind; + function isNewIdentifierDefinitionLocation() { + if (contextToken) { + var containingNodeKind = contextToken.parent.kind; // Previous token may have been a keyword that was converted to an identifier. - switch (keywordForNode(previousToken)) { + switch (keywordForNode(contextToken)) { case 27 /* CommaToken */: - return containingNodeKind === 203 /* CallExpression */ // func( a, | - || containingNodeKind === 166 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 204 /* NewExpression */ // new C(a, | - || containingNodeKind === 199 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 216 /* BinaryExpression */ // const x = (a, | - || containingNodeKind === 174 /* FunctionType */; // var x: (s: string, list| + return containingNodeKind === 204 /* CallExpression */ // func( a, | + || containingNodeKind === 167 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 205 /* NewExpression */ // new C(a, | + || containingNodeKind === 200 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 217 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 175 /* FunctionType */ // var x: (s: string, list| + || containingNodeKind === 201 /* ObjectLiteralExpression */; // const obj = { x, | case 20 /* OpenParenToken */: - return containingNodeKind === 203 /* CallExpression */ // func( | - || containingNodeKind === 166 /* Constructor */ // constructor( | - || containingNodeKind === 204 /* NewExpression */ // new C(a| - || containingNodeKind === 207 /* ParenthesizedExpression */ // const x = (a| - || containingNodeKind === 186 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + return containingNodeKind === 204 /* CallExpression */ // func( | + || containingNodeKind === 167 /* Constructor */ // constructor( | + || containingNodeKind === 205 /* NewExpression */ // new C(a| + || containingNodeKind === 208 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 187 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ case 22 /* OpenBracketToken */: - return containingNodeKind === 199 /* ArrayLiteralExpression */ // [ | - || containingNodeKind === 171 /* IndexSignature */ // [ | : string ] - || containingNodeKind === 158 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + return containingNodeKind === 200 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 172 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 159 /* ComputedPropertyName */; // [ | /* this can become an index signature */ case 139 /* ModuleKeyword */: // module | case 140 /* NamespaceKeyword */: // namespace | return true; case 24 /* DotToken */: - return containingNodeKind === 256 /* ModuleDeclaration */; // module A.| + return containingNodeKind === 257 /* ModuleDeclaration */; // module A.| case 18 /* OpenBraceToken */: - return containingNodeKind === 252 /* ClassDeclaration */; // class A{ | + return containingNodeKind === 253 /* ClassDeclaration */ // class A { | + || containingNodeKind === 201 /* ObjectLiteralExpression */; // const obj = { | case 62 /* EqualsToken */: - return containingNodeKind === 249 /* VariableDeclaration */ // const x = a| - || containingNodeKind === 216 /* BinaryExpression */; // x = a| + return containingNodeKind === 250 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 217 /* BinaryExpression */; // x = a| case 15 /* TemplateHead */: - return containingNodeKind === 218 /* TemplateExpression */; // `aa ${| + return containingNodeKind === 219 /* TemplateExpression */; // `aa ${| case 16 /* TemplateMiddle */: - return containingNodeKind === 228 /* TemplateSpan */; // `aa ${10} dd ${| + return containingNodeKind === 229 /* TemplateSpan */; // `aa ${10} dd ${| case 122 /* PublicKeyword */: case 120 /* PrivateKeyword */: case 121 /* ProtectedKeyword */: - return containingNodeKind === 163 /* PropertyDeclaration */; // class A{ public | + return containingNodeKind === 164 /* PropertyDeclaration */; // class A{ public | } } return false; @@ -121276,6 +125160,25 @@ var ts; return (ts.isRegularExpressionLiteral(contextToken) || ts.isStringTextContainingNode(contextToken)) && (ts.rangeContainsPositionExclusive(ts.createTextRangeFromSpan(ts.createTextSpanFromNode(contextToken)), position) || position === contextToken.end && (!!contextToken.isUnterminated || ts.isRegularExpressionLiteral(contextToken))); } + function tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() { + var typeLiteralNode = tryGetTypeLiteralNode(contextToken); + if (!typeLiteralNode) + return 0 /* Continue */; + var intersectionTypeNode = ts.isIntersectionTypeNode(typeLiteralNode.parent) ? typeLiteralNode.parent : undefined; + var containerTypeNode = intersectionTypeNode || typeLiteralNode; + var containerExpectedType = getConstraintOfTypeArgumentProperty(containerTypeNode, typeChecker); + if (!containerExpectedType) + return 0 /* Continue */; + var containerActualType = typeChecker.getTypeFromTypeNode(containerTypeNode); + var members = getPropertiesForCompletion(containerExpectedType, typeChecker); + var existingMembers = getPropertiesForCompletion(containerActualType, typeChecker); + var existingMemberEscapedNames = new ts.Set(); + existingMembers.forEach(function (s) { return existingMemberEscapedNames.add(s.escapedName); }); + symbols = ts.filter(members, function (s) { return !existingMemberEscapedNames.has(s.escapedName); }); + completionKind = 0 /* ObjectPropertyDeclaration */; + isNewIdentifierLocation = true; + return 1 /* Success */; + } /** * Aggregates relevant symbols for completion in object literals and object binding patterns. * Relevant symbols are stored in the captured 'symbols' variable. @@ -121290,7 +125193,7 @@ var ts; completionKind = 0 /* ObjectPropertyDeclaration */; var typeMembers; var existingMembers; - if (objectLikeContainer.kind === 200 /* ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 201 /* ObjectLiteralExpression */) { var instantiatedType = tryGetObjectLiteralContextualType(objectLikeContainer, typeChecker); // Check completions for Object property value shorthand if (instantiatedType === undefined) { @@ -121315,7 +125218,7 @@ var ts; } } else { - ts.Debug.assert(objectLikeContainer.kind === 196 /* ObjectBindingPattern */); + ts.Debug.assert(objectLikeContainer.kind === 197 /* ObjectBindingPattern */); // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -121326,12 +125229,12 @@ var ts; // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function - var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 239 /* ForOfStatement */; - if (!canGetType && rootDeclaration.kind === 160 /* Parameter */) { + var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 240 /* ForOfStatement */; + if (!canGetType && rootDeclaration.kind === 161 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - else if (rootDeclaration.parent.kind === 165 /* MethodDeclaration */ || rootDeclaration.parent.kind === 168 /* SetAccessor */) { + else if (rootDeclaration.parent.kind === 166 /* MethodDeclaration */ || rootDeclaration.parent.kind === 169 /* SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } @@ -121378,9 +125281,9 @@ var ts; if (!namedImportsOrExports) return 0 /* Continue */; // try to show exported member for imported/re-exported module - var moduleSpecifier = (namedImportsOrExports.kind === 264 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + var moduleSpecifier = (namedImportsOrExports.kind === 265 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; if (!moduleSpecifier) - return namedImportsOrExports.kind === 264 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */; + return namedImportsOrExports.kind === 265 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 if (!moduleSpecifierSymbol) return 2 /* Fail */; @@ -121448,12 +125351,16 @@ var ts; case "static": classElementModifierFlags = classElementModifierFlags | 32 /* Static */; break; + case "override": + classElementModifierFlags = classElementModifierFlags | 16384 /* Override */; + break; } } // No member list for private methods if (!(classElementModifierFlags & 8 /* Private */)) { // List of property symbols of base type that are not private and already implemented - var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) { + var baseTypeNodes = ts.isClassLike(decl) && classElementModifierFlags & 16384 /* Override */ ? ts.singleElementArray(ts.getEffectiveBaseTypeNode(decl)) : ts.getAllSuperTypeNodes(decl); + var baseSymbols = ts.flatMap(baseTypeNodes, function (baseTypeNode) { var type = typeChecker.getTypeAtLocation(baseTypeNode); return classElementModifierFlags & 32 /* Static */ ? (type === null || type === void 0 ? void 0 : type.symbol) && typeChecker.getPropertiesOfType(typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl)) : @@ -121533,11 +125440,11 @@ var ts; case 30 /* LessThanSlashToken */: case 43 /* SlashToken */: case 78 /* Identifier */: - case 201 /* PropertyAccessExpression */: - case 281 /* JsxAttributes */: - case 280 /* JsxAttribute */: - case 282 /* JsxSpreadAttribute */: - if (parent && (parent.kind === 274 /* JsxSelfClosingElement */ || parent.kind === 275 /* JsxOpeningElement */)) { + case 202 /* PropertyAccessExpression */: + case 282 /* JsxAttributes */: + case 281 /* JsxAttribute */: + case 283 /* JsxSpreadAttribute */: + if (parent && (parent.kind === 275 /* JsxSelfClosingElement */ || parent.kind === 276 /* JsxOpeningElement */)) { if (contextToken.kind === 31 /* GreaterThanToken */) { var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined); if (!parent.typeArguments || (precedingToken && precedingToken.kind === 43 /* SlashToken */)) @@ -121545,7 +125452,7 @@ var ts; } return parent; } - else if (parent.kind === 280 /* JsxAttribute */) { + else if (parent.kind === 281 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -121557,7 +125464,7 @@ var ts; // its parent is a JsxExpression, whose parent is a JsxAttribute, // whose parent is a JsxOpeningLikeElement case 10 /* StringLiteral */: - if (parent && ((parent.kind === 280 /* JsxAttribute */) || (parent.kind === 282 /* JsxSpreadAttribute */))) { + if (parent && ((parent.kind === 281 /* JsxAttribute */) || (parent.kind === 283 /* JsxSpreadAttribute */))) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -121567,8 +125474,8 @@ var ts; break; case 19 /* CloseBraceToken */: if (parent && - parent.kind === 283 /* JsxExpression */ && - parent.parent && parent.parent.kind === 280 /* JsxAttribute */) { + parent.kind === 284 /* JsxExpression */ && + parent.parent && parent.parent.kind === 281 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -121576,7 +125483,7 @@ var ts; // each JsxAttribute can have initializer as JsxExpression return parent.parent.parent.parent; } - if (parent && parent.kind === 282 /* JsxSpreadAttribute */) { + if (parent && parent.kind === 283 /* JsxSpreadAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -121596,49 +125503,49 @@ var ts; var containingNodeKind = parent.kind; switch (contextToken.kind) { case 27 /* CommaToken */: - return containingNodeKind === 249 /* VariableDeclaration */ || + return containingNodeKind === 250 /* VariableDeclaration */ || isVariableDeclarationListButNotTypeArgument(contextToken) || - containingNodeKind === 232 /* VariableStatement */ || - containingNodeKind === 255 /* EnumDeclaration */ || // enum a { foo, | + containingNodeKind === 233 /* VariableStatement */ || + containingNodeKind === 256 /* EnumDeclaration */ || // enum a { foo, | isFunctionLikeButNotConstructor(containingNodeKind) || - containingNodeKind === 253 /* InterfaceDeclaration */ || // interface A= contextToken.pos); case 24 /* DotToken */: - return containingNodeKind === 197 /* ArrayBindingPattern */; // var [.| + return containingNodeKind === 198 /* ArrayBindingPattern */; // var [.| case 58 /* ColonToken */: - return containingNodeKind === 198 /* BindingElement */; // var {x :html| + return containingNodeKind === 199 /* BindingElement */; // var {x :html| case 22 /* OpenBracketToken */: - return containingNodeKind === 197 /* ArrayBindingPattern */; // var [x| + return containingNodeKind === 198 /* ArrayBindingPattern */; // var [x| case 20 /* OpenParenToken */: - return containingNodeKind === 287 /* CatchClause */ || + return containingNodeKind === 288 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); case 18 /* OpenBraceToken */: - return containingNodeKind === 255 /* EnumDeclaration */; // enum a { | + return containingNodeKind === 256 /* EnumDeclaration */; // enum a { | case 29 /* LessThanToken */: - return containingNodeKind === 252 /* ClassDeclaration */ || // class A< | - containingNodeKind === 221 /* ClassExpression */ || // var C = class D< | - containingNodeKind === 253 /* InterfaceDeclaration */ || // interface A< | - containingNodeKind === 254 /* TypeAliasDeclaration */ || // type List< | + return containingNodeKind === 253 /* ClassDeclaration */ || // class A< | + containingNodeKind === 222 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 254 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 255 /* TypeAliasDeclaration */ || // type List< | ts.isFunctionLikeKind(containingNodeKind); case 123 /* StaticKeyword */: - return containingNodeKind === 163 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); + return containingNodeKind === 164 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); case 25 /* DotDotDotToken */: - return containingNodeKind === 160 /* Parameter */ || - (!!parent.parent && parent.parent.kind === 197 /* ArrayBindingPattern */); // var [...z| + return containingNodeKind === 161 /* Parameter */ || + (!!parent.parent && parent.parent.kind === 198 /* ArrayBindingPattern */); // var [...z| case 122 /* PublicKeyword */: case 120 /* PrivateKeyword */: case 121 /* ProtectedKeyword */: - return containingNodeKind === 160 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); + return containingNodeKind === 161 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); case 126 /* AsKeyword */: - return containingNodeKind === 265 /* ImportSpecifier */ || - containingNodeKind === 270 /* ExportSpecifier */ || - containingNodeKind === 263 /* NamespaceImport */; + return containingNodeKind === 266 /* ImportSpecifier */ || + containingNodeKind === 271 /* ExportSpecifier */ || + containingNodeKind === 264 /* NamespaceImport */; case 134 /* GetKeyword */: case 146 /* SetKeyword */: return !isFromObjectTypeDeclaration(contextToken); @@ -121656,7 +125563,7 @@ var ts; case 41 /* AsteriskToken */: return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } - // If the previous token is keyword correspoding to class member completion keyword + // If the previous token is keyword corresponding to class member completion keyword // there will be completion available here if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { return false; @@ -121691,6 +125598,31 @@ var ts; case 129 /* AsyncKeyword */: return ts.isPropertyDeclaration(contextToken.parent); } + // If we are inside a class declaration, and `constructor` is totally not present, + // but we request a completion manually at a whitespace... + var ancestorClassLike = ts.findAncestor(contextToken.parent, ts.isClassLike); + if (ancestorClassLike && contextToken === previousToken && isPreviousPropertyDeclarationTerminated(contextToken, position)) { + return false; // Don't block completions. + } + var ancestorPropertyDeclaraion = ts.getAncestor(contextToken.parent, 164 /* PropertyDeclaration */); + // If we are inside a class declaration and typing `constructor` after property declaration... + if (ancestorPropertyDeclaraion + && contextToken !== previousToken + && ts.isClassLike(previousToken.parent.parent) + // And the cursor is at the token... + && position <= previousToken.end) { + // If we are sure that the previous property declaration is terminated according to newline or semicolon... + if (isPreviousPropertyDeclarationTerminated(contextToken, previousToken.end)) { + return false; // Don't block completions. + } + else if (contextToken.kind !== 62 /* EqualsToken */ + // Should not block: `class C { blah = c/**/ }` + // But should block: `class C { blah = somewhat c/**/ }` and `class C { blah: SomeType c/**/ }` + && (ts.isInitializedProperty(ancestorPropertyDeclaraion) + || ts.hasType(ancestorPropertyDeclaraion))) { + return true; + } + } return ts.isDeclarationName(contextToken) && !ts.isShorthandPropertyAssignment(contextToken.parent) && !ts.isJsxAttribute(contextToken.parent) @@ -121698,8 +125630,13 @@ var ts; // If `contextToken !== previousToken`, this is `class C ex/**/`. && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } + function isPreviousPropertyDeclarationTerminated(contextToken, position) { + return contextToken.kind !== 62 /* EqualsToken */ && + (contextToken.kind === 26 /* SemicolonToken */ + || !ts.positionsAreOnSameLine(contextToken.end, position, sourceFile)); + } function isFunctionLikeButNotConstructor(kind) { - return ts.isFunctionLikeKind(kind) && kind !== 166 /* Constructor */; + return ts.isFunctionLikeKind(kind) && kind !== 167 /* Constructor */; } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8 /* NumericLiteral */) { @@ -121709,7 +125646,7 @@ var ts; return false; } function isVariableDeclarationListButNotTypeArgument(node) { - return node.parent.kind === 250 /* VariableDeclarationList */ + return node.parent.kind === 251 /* VariableDeclarationList */ && !ts.isPossiblyTypeArgumentPosition(node, sourceFile, typeChecker); } /** @@ -121727,13 +125664,13 @@ var ts; for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 288 /* PropertyAssignment */ && - m.kind !== 289 /* ShorthandPropertyAssignment */ && - m.kind !== 198 /* BindingElement */ && - m.kind !== 165 /* MethodDeclaration */ && - m.kind !== 167 /* GetAccessor */ && - m.kind !== 168 /* SetAccessor */ && - m.kind !== 290 /* SpreadAssignment */) { + if (m.kind !== 289 /* PropertyAssignment */ && + m.kind !== 290 /* ShorthandPropertyAssignment */ && + m.kind !== 199 /* BindingElement */ && + m.kind !== 166 /* MethodDeclaration */ && + m.kind !== 168 /* GetAccessor */ && + m.kind !== 169 /* SetAccessor */ && + m.kind !== 291 /* SpreadAssignment */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -121806,10 +125743,10 @@ var ts; for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 163 /* PropertyDeclaration */ && - m.kind !== 165 /* MethodDeclaration */ && - m.kind !== 167 /* GetAccessor */ && - m.kind !== 168 /* SetAccessor */) { + if (m.kind !== 164 /* PropertyDeclaration */ && + m.kind !== 166 /* MethodDeclaration */ && + m.kind !== 168 /* GetAccessor */ && + m.kind !== 169 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -121833,7 +125770,7 @@ var ts; return !existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */) && - !(propertySymbol.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(propertySymbol.valueDeclaration)); + !(propertySymbol.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(propertySymbol.valueDeclaration)); }); } /** @@ -121851,7 +125788,7 @@ var ts; if (isCurrentlyEditingNode(attr)) { continue; } - if (attr.kind === 280 /* JsxAttribute */) { + if (attr.kind === 281 /* JsxAttribute */) { seenNames.add(attr.name.escapedText); } else if (ts.isJsxSpreadAttribute(attr)) { @@ -121866,8 +125803,35 @@ var ts; return node.getStart(sourceFile) <= position && position <= node.getEnd(); } } + function getAutoImportSymbolFromCompletionEntryData(name, data, program, host) { + var containingProgram = data.isPackageJsonImport ? host.getPackageJsonAutoImportProvider() : program; + var checker = containingProgram.getTypeChecker(); + var moduleSymbol = data.ambientModuleName ? checker.tryFindAmbientModule(data.ambientModuleName) : + data.fileName ? checker.getMergedSymbol(ts.Debug.checkDefined(containingProgram.getSourceFile(data.fileName)).symbol) : + undefined; + if (!moduleSymbol) + return undefined; + var symbol = data.exportName === "export=" /* ExportEquals */ + ? checker.resolveExternalModuleSymbol(moduleSymbol) + : checker.tryGetMemberInModuleExportsAndProperties(data.exportName, moduleSymbol); + if (!symbol) + return undefined; + var isDefaultExport = data.exportName === "default" /* Default */; + symbol = isDefaultExport && ts.getLocalSymbolForExportDefault(symbol) || symbol; + return { + symbol: symbol, + origin: { + kind: data.moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */, + moduleSymbol: moduleSymbol, + symbolName: name, + isDefaultExport: isDefaultExport, + exportName: data.exportName, + fileName: data.fileName, + } + }; + } function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, jsxIdentifierExpected) { - var name = originIsExport(origin) ? ts.getNameForExportedSymbol(symbol, target) : symbol.name; + var name = originIncludesSymbolName(origin) ? origin.symbolName : symbol.name; if (name === undefined // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) @@ -121877,7 +125841,7 @@ var ts; return undefined; } var validNameResult = { name: name, needsConvertPropertyAccess: false }; - if (ts.isIdentifierText(name, target, jsxIdentifierExpected ? 1 /* JSX */ : 0 /* Standard */) || symbol.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) { + if (ts.isIdentifierText(name, target, jsxIdentifierExpected ? 1 /* JSX */ : 0 /* Standard */) || symbol.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) { return validNameResult; } switch (kind) { @@ -121901,7 +125865,7 @@ var ts; var _keywordCompletions = []; var allKeywordsCompletions = ts.memoize(function () { var res = []; - for (var i = 80 /* FirstKeyword */; i <= 156 /* LastKeyword */; i++) { + for (var i = 80 /* FirstKeyword */; i <= 157 /* LastKeyword */; i++) { res.push({ name: ts.tokenToString(i), kind: "keyword" /* keyword */, @@ -121968,6 +125932,7 @@ var ts; case 141 /* NeverKeyword */: case 144 /* NumberKeyword */: case 145 /* ObjectKeyword */: + case 156 /* OverrideKeyword */: case 120 /* PrivateKeyword */: case 121 /* ProtectedKeyword */: case 122 /* PublicKeyword */: @@ -121993,6 +125958,7 @@ var ts; case 146 /* SetKeyword */: case 129 /* AsyncKeyword */: case 133 /* DeclareKeyword */: + case 156 /* OverrideKeyword */: return true; default: return ts.isClassMemberModifier(kind); @@ -122053,7 +126019,7 @@ var ts; function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position) { // class c { method() { } | method2() { } } switch (location.kind) { - case 334 /* SyntaxList */: + case 338 /* SyntaxList */: return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); case 1 /* EndOfFileToken */: var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); @@ -122074,6 +126040,12 @@ var ts; } if (!contextToken) return undefined; + // class C { blah; constructor/**/ } and so on + if (location.kind === 132 /* ConstructorKeyword */ + // class C { blah \n constructor/**/ } + || (ts.isIdentifier(contextToken) && ts.isPropertyDeclaration(contextToken.parent) && ts.isClassLike(location))) { + return ts.findAncestor(contextToken, ts.isClassLike); + } switch (contextToken.kind) { case 62 /* EqualsToken */: // class c { public prop = | /* global completions */ } return undefined; @@ -122099,6 +126071,44 @@ var ts; ? contextToken.parent.parent : undefined; } } + function tryGetTypeLiteralNode(node) { + if (!node) + return undefined; + var parent = node.parent; + switch (node.kind) { + case 18 /* OpenBraceToken */: + if (ts.isTypeLiteralNode(parent)) { + return parent; + } + break; + case 26 /* SemicolonToken */: + case 27 /* CommaToken */: + case 78 /* Identifier */: + if (parent.kind === 163 /* PropertySignature */ && ts.isTypeLiteralNode(parent.parent)) { + return parent.parent; + } + break; + } + return undefined; + } + function getConstraintOfTypeArgumentProperty(node, checker) { + if (!node) + return undefined; + if (ts.isTypeNode(node) && ts.isTypeReferenceType(node.parent)) { + return checker.getTypeArgumentConstraint(node); + } + var t = getConstraintOfTypeArgumentProperty(node.parent, checker); + if (!t) + return undefined; + switch (node.kind) { + case 163 /* PropertySignature */: + return checker.getTypeOfPropertyOfContextualType(t, node.symbol.escapedName); + case 184 /* IntersectionType */: + case 178 /* TypeLiteral */: + case 183 /* UnionType */: + return t; + } + } // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes function isFromObjectTypeDeclaration(node) { return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent); @@ -122122,6 +126132,8 @@ var ts; return !!contextToken && (ts.isStringLiteralLike(contextToken) ? !!ts.tryGetImportFromModuleSpecifier(contextToken) : contextToken.kind === 43 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); + case " ": + return !!contextToken && ts.isImportKeyword(contextToken) && contextToken.parent.kind === 298 /* SourceFile */; default: return ts.Debug.assertNever(triggerCharacter); } @@ -122130,14 +126142,6 @@ var ts; var left = _a.left; return ts.nodeIsMissing(left); } - function findAlias(typeChecker, symbol, predicate) { - var currentAlias = symbol; - while (currentAlias.flags & 2097152 /* Alias */ && (currentAlias = typeChecker.getImmediateAliasedSymbol(currentAlias))) { - if (predicate(currentAlias)) { - return currentAlias; - } - } - } /** Determines if a type is exactly the same type resolved by the global 'self', 'global', or 'globalThis'. */ function isProbablyGlobalType(type, sourceFile, checker) { // The type of `self` and `window` is the same in lib.dom.d.ts, but `window` does not exist in @@ -122164,11 +126168,67 @@ var ts; if (type) { return type; } - if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) { + if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ && node === node.parent.left) { + // Object literal is assignment pattern: ({ | } = x) return typeChecker.getTypeAtLocation(node.parent); } return undefined; } + function getImportCompletionNode(contextToken) { + var candidate = getCandidate(); + return candidate === 153 /* FromKeyword */ || candidate && ts.rangeIsOnSingleLine(candidate, candidate.getSourceFile()) ? candidate : undefined; + function getCandidate() { + var parent = contextToken.parent; + if (ts.isImportEqualsDeclaration(parent)) { + return isModuleSpecifierMissingOrEmpty(parent.moduleReference) ? parent : undefined; + } + if (ts.isNamedImports(parent) || ts.isNamespaceImport(parent)) { + if (isModuleSpecifierMissingOrEmpty(parent.parent.parent.moduleSpecifier) && (ts.isNamespaceImport(parent) || parent.elements.length < 2) && !parent.parent.name) { + // At `import { ... } |` or `import * as Foo |`, the only possible completion is `from` + return contextToken.kind === 19 /* CloseBraceToken */ || contextToken.kind === 78 /* Identifier */ + ? 153 /* FromKeyword */ + : parent.parent.parent; + } + return undefined; + } + if (ts.isImportKeyword(contextToken) && ts.isSourceFile(parent)) { + // A lone import keyword with nothing following it does not parse as a statement at all + return contextToken; + } + if (ts.isImportKeyword(contextToken) && ts.isImportDeclaration(parent)) { + // `import s| from` + return isModuleSpecifierMissingOrEmpty(parent.moduleSpecifier) ? parent : undefined; + } + return undefined; + } + } + function isModuleSpecifierMissingOrEmpty(specifier) { + var _a; + if (ts.nodeIsMissing(specifier)) + return true; + return !((_a = ts.tryCast(ts.isExternalModuleReference(specifier) ? specifier.expression : specifier, ts.isStringLiteralLike)) === null || _a === void 0 ? void 0 : _a.text); + } + function getVariableDeclaration(property) { + var variableDeclaration = ts.findAncestor(property, function (node) { + return ts.isFunctionBlock(node) || isArrowFunctionBody(node) || ts.isBindingPattern(node) + ? "quit" + : ts.isVariableDeclaration(node); + }); + return variableDeclaration; + } + function isArrowFunctionBody(node) { + return node.parent && ts.isArrowFunction(node.parent) && node.parent.body === node; + } + ; + /** True if symbol is a type or a module containing at least one type. */ + function symbolCanBeReferencedAtTypeLocation(symbol, checker, seenModules) { + if (seenModules === void 0) { seenModules = new ts.Map(); } + var sym = ts.skipAlias(symbol.exportSymbol || symbol, checker); + return !!(sym.flags & 788968 /* Type */) || + !!(sym.flags & 1536 /* Module */) && + ts.addToSeen(seenModules, ts.getSymbolId(sym)) && + checker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, checker, seenModules); }); + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); var ts; @@ -122203,10 +126263,12 @@ var ts; if (!referenceEntries) return undefined; var map = ts.arrayToMultiMap(referenceEntries.map(ts.FindAllReferences.toHighlightSpan), function (e) { return e.fileName; }, function (e) { return e.span; }); - return ts.arrayFrom(map.entries(), function (_a) { + return ts.mapDefined(ts.arrayFrom(map.entries()), function (_a) { var fileName = _a[0], highlightSpans = _a[1]; if (!sourceFilesSet.has(fileName)) { - ts.Debug.assert(program.redirectTargetsMap.has(fileName)); + if (!program.redirectTargetsMap.has(fileName)) { + return undefined; + } var redirectTarget_1 = program.getSourceFile(fileName); var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); fileName = redirect.fileName; @@ -122301,7 +126363,7 @@ var ts; var child = throwStatement; while (child.parent) { var parent = child.parent; - if (ts.isFunctionBlock(parent) || parent.kind === 297 /* SourceFile */) { + if (ts.isFunctionBlock(parent) || parent.kind === 298 /* SourceFile */) { return parent; } // A throw-statement is only owned by a try-statement if the try-statement has @@ -122333,16 +126395,16 @@ var ts; function getBreakOrContinueOwner(statement) { return ts.findAncestor(statement, function (node) { switch (node.kind) { - case 244 /* SwitchStatement */: - if (statement.kind === 240 /* ContinueStatement */) { + case 245 /* SwitchStatement */: + if (statement.kind === 241 /* ContinueStatement */) { return false; } // falls through - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 236 /* WhileStatement */: - case 235 /* DoStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 237 /* WhileStatement */: + case 236 /* DoStatement */: return !statement.label || isLabeledBy(node, statement.label.escapedText); default: // Don't cross function boundaries. @@ -122358,11 +126420,11 @@ var ts; // Types of node whose children might have modifiers. var container = declaration.parent; switch (container.kind) { - case 257 /* ModuleBlock */: - case 297 /* SourceFile */: - case 230 /* Block */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 258 /* ModuleBlock */: + case 298 /* SourceFile */: + case 231 /* Block */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) { return __spreadArray(__spreadArray([], declaration.members), [declaration]); @@ -122370,14 +126432,14 @@ var ts; else { return container.statements; } - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 251 /* FunctionDeclaration */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: return __spreadArray(__spreadArray([], container.parameters), (ts.isClassLike(container.parent) ? container.parent.members : [])); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 177 /* TypeLiteral */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 178 /* TypeLiteral */: var nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. @@ -122392,7 +126454,7 @@ var ts; } return nodes; // Syntactically invalid positions that the parser might produce anyway - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return undefined; default: ts.Debug.assertNever(container, "Invalid container kind."); @@ -122413,7 +126475,7 @@ var ts; var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 96 /* ForKeyword */, 114 /* WhileKeyword */, 89 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 235 /* DoStatement */) { + if (loopNode.kind === 236 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 114 /* WhileKeyword */)) { @@ -122433,13 +126495,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -122612,6 +126674,9 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + function isDocumentRegistryEntry(entry) { + return !!entry.sourceFile; + } function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); } @@ -122628,10 +126693,16 @@ var ts; var entries = buckets.get(name); var sourceFiles = []; entries.forEach(function (entry, name) { - sourceFiles.push({ - name: name, - refCount: entry.languageServiceRefCount - }); + if (isDocumentRegistryEntry(entry)) { + sourceFiles.push({ + name: name, + scriptKind: entry.sourceFile.scriptKind, + refCount: entry.languageServiceRefCount + }); + } + else { + entry.forEach(function (value, scriptKind) { return sourceFiles.push({ name: name, scriptKind: scriptKind, refCount: value.languageServiceRefCount }); }); + } }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); return { @@ -122657,10 +126728,17 @@ var ts; function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); } + function getDocumentRegistryEntry(bucketEntry, scriptKind) { + var entry = isDocumentRegistryEntry(bucketEntry) ? bucketEntry : bucketEntry.get(ts.Debug.checkDefined(scriptKind, "If there are more than one scriptKind's for same document the scriptKind should be provided")); + ts.Debug.assert(scriptKind === undefined || !entry || entry.sourceFile.scriptKind === scriptKind, "Script kind should match provided ScriptKind:" + scriptKind + " and sourceFile.scriptKind: " + (entry === null || entry === void 0 ? void 0 : entry.sourceFile.scriptKind) + ", !entry: " + !entry); + return entry; + } function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { - var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); - var entry = bucket.get(path); + scriptKind = ts.ensureScriptKind(fileName, scriptKind); var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; + var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); + var bucketEntry = bucket.get(path); + var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -122669,7 +126747,7 @@ var ts; sourceFile: sourceFile, languageServiceRefCount: 0 }; - bucket.set(path, entry); + setBucketEntry(); } } if (!entry) { @@ -122682,7 +126760,7 @@ var ts; sourceFile: sourceFile, languageServiceRefCount: 1, }; - bucket.set(path, entry); + setBucketEntry(); } else { // We have an entry for this file. However, it may be for a different version of @@ -122705,25 +126783,49 @@ var ts; } ts.Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; + function setBucketEntry() { + if (!bucketEntry) { + bucket.set(path, entry); + } + else if (isDocumentRegistryEntry(bucketEntry)) { + var scriptKindMap = new ts.Map(); + scriptKindMap.set(bucketEntry.sourceFile.scriptKind, bucketEntry); + scriptKindMap.set(scriptKind, entry); + bucket.set(path, scriptKindMap); + } + else { + bucketEntry.set(scriptKind, entry); + } + } } - function releaseDocument(fileName, compilationSettings) { + function releaseDocument(fileName, compilationSettings, scriptKind) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(compilationSettings); - return releaseDocumentWithKey(path, key); + return releaseDocumentWithKey(path, key, scriptKind); } - function releaseDocumentWithKey(path, key) { + function releaseDocumentWithKey(path, key, scriptKind) { var bucket = ts.Debug.checkDefined(buckets.get(key)); - var entry = bucket.get(path); + var bucketEntry = bucket.get(path); + var entry = getDocumentRegistryEntry(bucketEntry, scriptKind); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - bucket.delete(path); + if (isDocumentRegistryEntry(bucketEntry)) { + bucket.delete(path); + } + else { + bucketEntry.delete(scriptKind); + if (bucketEntry.size === 1) { + bucket.set(path, ts.firstDefinedIterator(bucketEntry.values(), ts.identity)); + } + } } } - function getLanguageServiceRefCounts(path) { + function getLanguageServiceRefCounts(path, scriptKind) { return ts.arrayFrom(buckets.entries(), function (_a) { var key = _a[0], bucket = _a[1]; - var entry = bucket.get(path); + var bucketEntry = bucket.get(path); + var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); return [key, entry && entry.languageServiceRefCount]; }); } @@ -122786,10 +126888,12 @@ var ts; return sourceFiles; } // Module augmentations may use this module's exports without importing it. - for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (ts.isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) { - addIndirectUser(decl); + if (exportingModuleSymbol.declarations) { + for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) { + addIndirectUser(decl); + } } } // This may return duplicates (if there are multiple module declarations in a single source file, all importing the same thing as a namespace), but `State.markSearchedSymbol` will handle that. @@ -122806,14 +126910,14 @@ var ts; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); switch (direct.kind) { - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (ts.isImportCall(direct)) { handleImportCall(direct); break; } if (!isAvailableThroughGlobal) { var parent = direct.parent; - if (exportKind === 2 /* ExportEquals */ && parent.kind === 249 /* VariableDeclaration */) { + if (exportKind === 2 /* ExportEquals */ && parent.kind === 250 /* VariableDeclaration */) { var name = parent.name; if (name.kind === 78 /* Identifier */) { directImports.push(name); @@ -122824,25 +126928,25 @@ var ts; break; case 78 /* Identifier */: // for 'const x = require("y"); break; // TODO: GH#23879 - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: handleNamespaceImport(direct, direct.name, ts.hasSyntacticModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false); break; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: directImports.push(direct); var namedBindings = direct.importClause && direct.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 263 /* NamespaceImport */) { + if (namedBindings && namedBindings.kind === 264 /* NamespaceImport */) { handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true); } else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) { addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports } break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: if (!direct.exportClause) { // This is `export * from "foo"`, so imports of this module may import the export too. handleDirectImports(getContainingModuleSymbol(direct, checker)); } - else if (direct.exportClause.kind === 269 /* NamespaceExport */) { + else if (direct.exportClause.kind === 270 /* NamespaceExport */) { // `export * as foo from "foo"` add to indirect uses addIndirectUser(getSourceFileLikeForImportDeclaration(direct), /** addTransitiveDependencies */ true); } @@ -122851,7 +126955,7 @@ var ts; directImports.push(direct); } break; - case 195 /* ImportType */: + case 196 /* ImportType */: // Only check for typeof import('xyz') if (direct.isTypeOf && !direct.qualifier && isExported(direct)) { addIndirectUser(direct.getSourceFile(), /** addTransitiveDependencies */ true); @@ -122884,7 +126988,7 @@ var ts; } else if (!isAvailableThroughGlobal) { var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); - ts.Debug.assert(sourceFileLike.kind === 297 /* SourceFile */ || sourceFileLike.kind === 256 /* ModuleDeclaration */); + ts.Debug.assert(sourceFileLike.kind === 298 /* SourceFile */ || sourceFileLike.kind === 257 /* ModuleDeclaration */); if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { addIndirectUser(sourceFileLike, /** addTransitiveDependencies */ true); } @@ -122940,7 +127044,7 @@ var ts; } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { - if (decl.kind === 260 /* ImportEqualsDeclaration */) { + if (decl.kind === 261 /* ImportEqualsDeclaration */) { if (isExternalModuleImportEquals(decl)) { handleNamespaceImportLike(decl.name); } @@ -122950,7 +127054,7 @@ var ts; handleNamespaceImportLike(decl); return; } - if (decl.kind === 195 /* ImportType */) { + if (decl.kind === 196 /* ImportType */) { if (decl.qualifier) { var firstIdentifier = ts.getFirstIdentifier(decl.qualifier); if (firstIdentifier.escapedText === ts.symbolName(exportSymbol)) { @@ -122966,7 +127070,7 @@ var ts; if (decl.moduleSpecifier.kind !== 10 /* StringLiteral */) { return; } - if (decl.kind === 267 /* ExportDeclaration */) { + if (decl.kind === 268 /* ExportDeclaration */) { if (decl.exportClause && ts.isNamedExports(decl.exportClause)) { searchForNamedImport(decl.exportClause); } @@ -122975,10 +127079,10 @@ var ts; var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: handleNamespaceImportLike(namedBindings.name); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: // 'default' might be accessed as a named import `{ default as foo }`. if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) { searchForNamedImport(namedBindings); @@ -123028,7 +127132,7 @@ var ts; } } else { - var localSymbol = element.kind === 270 /* ExportSpecifier */ && element.propertyName + var localSymbol = element.kind === 271 /* ExportSpecifier */ && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. : checker.getSymbolAtLocation(name); addSearch(name, localSymbol); @@ -123057,7 +127161,7 @@ var ts; for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { var referencingFile = sourceFiles_1[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; - if (searchSourceFile.kind === 297 /* SourceFile */) { + if ((searchSourceFile === null || searchSourceFile === void 0 ? void 0 : searchSourceFile.kind) === 298 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { var ref = _b[_a]; if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { @@ -123105,7 +127209,7 @@ var ts; } /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return ts.forEach(sourceFileLike.kind === 297 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return ts.forEach(sourceFileLike.kind === 298 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); }); } @@ -123120,15 +127224,15 @@ var ts; else { forEachPossibleImportOrExportStatement(sourceFile, function (statement) { switch (statement.kind) { - case 267 /* ExportDeclaration */: - case 261 /* ImportDeclaration */: { + case 268 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: { var decl = statement; if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) { action(decl, decl.moduleSpecifier); } break; } - case 260 /* ImportEqualsDeclaration */: { + case 261 /* ImportEqualsDeclaration */: { var decl = statement; if (isExternalModuleImportEquals(decl)) { action(decl, decl.moduleReference.expression); @@ -123149,14 +127253,15 @@ var ts; function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { return comingFromExport ? getExport() : getExport() || getImport(); function getExport() { + var _a; var parent = node.parent; - var grandParent = parent.parent; + var grandparent = parent.parent; if (symbol.exportSymbol) { - if (parent.kind === 201 /* PropertyAccessExpression */) { + if (parent.kind === 202 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. - return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) - ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false) + return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === parent; })) && ts.isBinaryExpression(grandparent) + ? getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ false) : undefined; } else { @@ -123186,15 +127291,15 @@ var ts; return getExportAssignmentExport(parent); } // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. - else if (ts.isExportAssignment(grandParent)) { - return getExportAssignmentExport(grandParent); + else if (ts.isExportAssignment(grandparent)) { + return getExportAssignmentExport(grandparent); } // Similar for `module.exports =` and `exports.A =`. else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } - else if (ts.isBinaryExpression(grandParent)) { - return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true); + else if (ts.isBinaryExpression(grandparent)) { + return getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ true); } else if (ts.isJSDocTypedefTag(parent)) { return exportInfo(symbol, 0 /* Named */); @@ -123202,9 +127307,10 @@ var ts; } function getExportAssignmentExport(ex) { // Get the symbol for the `export =` node; its parent is the module it's the export of. - var exportingModuleSymbol = ts.Debug.checkDefined(ex.symbol.parent, "Expected export symbol to have a parent"); + if (!ex.symbol.parent) + return undefined; var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */; - return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; + return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: ex.symbol.parent, exportKind: exportKind } }; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; @@ -123258,7 +127364,7 @@ var ts; if (importedSymbol.flags & 2097152 /* Alias */) { return ts.Debug.checkDefined(checker.getImmediateAliasedSymbol(importedSymbol)); } - var decl = importedSymbol.valueDeclaration; + var decl = ts.Debug.checkDefined(importedSymbol.valueDeclaration); if (ts.isExportAssignment(decl)) { // `export = class {}` return ts.Debug.checkDefined(decl.expression.symbol); } @@ -123285,17 +127391,17 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return parent.name === node && isExternalModuleImportEquals(parent); - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. return !parent.propertyName; - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: ts.Debug.assert(parent.name === node); return true; - case 198 /* BindingElement */: - return ts.isInJSFile(node) && ts.isRequireVariableDeclaration(parent, /*requireStringLiteralLikeArgument*/ true); + case 199 /* BindingElement */: + return ts.isInJSFile(node) && ts.isRequireVariableDeclaration(parent); default: return false; } @@ -123319,7 +127425,8 @@ var ts; return checker.getExportSpecifierLocalTargetSymbol(declaration); } else if (ts.isPropertyAccessExpression(declaration) && ts.isModuleExportsAccessExpression(declaration.expression) && !ts.isPrivateIdentifier(declaration.name)) { - return checker.getExportSpecifierLocalTargetSymbol(declaration.name); + // Export of form 'module.exports.propName = expr'; + return checker.getSymbolAtLocation(declaration); } else if (ts.isShorthandPropertyAssignment(declaration) && ts.isBinaryExpression(declaration.parent.parent) @@ -123334,21 +127441,21 @@ var ts; return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); } function getSourceFileLikeForImportDeclaration(node) { - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { return node.getSourceFile(); } var parent = node.parent; - if (parent.kind === 297 /* SourceFile */) { + if (parent.kind === 298 /* SourceFile */) { return parent; } - ts.Debug.assert(parent.kind === 257 /* ModuleBlock */); + ts.Debug.assert(parent.kind === 258 /* ModuleBlock */); return ts.cast(parent.parent, isAmbientModuleDeclaration); } function isAmbientModuleDeclaration(node) { - return node.kind === 256 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */; + return node.kind === 257 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */; } function isExternalModuleImportEquals(eq) { - return eq.moduleReference.kind === 272 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */; + return eq.moduleReference.kind === 273 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -123451,7 +127558,7 @@ var ts; if (!node) return undefined; switch (node.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return !ts.isVariableDeclarationList(node.parent) || node.parent.declarations.length !== 1 ? node : ts.isVariableStatement(node.parent.parent) ? @@ -123459,28 +127566,28 @@ var ts; ts.isForInOrOfStatement(node.parent.parent) ? getContextNode(node.parent.parent) : node.parent; - case 198 /* BindingElement */: + case 199 /* BindingElement */: return getContextNode(node.parent.parent); - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: return node.parent.parent.parent; - case 270 /* ExportSpecifier */: - case 263 /* NamespaceImport */: + case 271 /* ExportSpecifier */: + case 264 /* NamespaceImport */: return node.parent.parent; - case 262 /* ImportClause */: - case 269 /* NamespaceExport */: + case 263 /* ImportClause */: + case 270 /* NamespaceExport */: return node.parent; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return ts.isExpressionStatement(node.parent) ? node.parent : node; - case 239 /* ForOfStatement */: - case 238 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 239 /* ForInStatement */: return { start: node.initializer, end: node.expression }; - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent) ? getContextNode(ts.findAncestor(node.parent, function (node) { return ts.isBinaryExpression(node) || ts.isForInOrOfStatement(node); @@ -123537,9 +127644,9 @@ var ts; var node = ts.getTouchingPropertyName(sourceFile, position); var referenceEntries; var entries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); - if (node.parent.kind === 201 /* PropertyAccessExpression */ - || node.parent.kind === 198 /* BindingElement */ - || node.parent.kind === 202 /* ElementAccessExpression */ + if (node.parent.kind === 202 /* PropertyAccessExpression */ + || node.parent.kind === 199 /* BindingElement */ + || node.parent.kind === 203 /* ElementAccessExpression */ || node.kind === 105 /* SuperKeyword */) { referenceEntries = entries && __spreadArray([], entries); } @@ -123563,13 +127670,13 @@ var ts; } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { return undefined; } var checker = program.getTypeChecker(); // 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 === 289 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 290 /* ShorthandPropertyAssignment */) { var result_1 = []; Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_1.push(nodeEntry(node)); }); return result_1; @@ -123744,13 +127851,13 @@ var ts; if (symbol) { return getDefinitionKindAndDisplayParts(symbol, checker, node); } - else if (node.kind === 200 /* ObjectLiteralExpression */) { + else if (node.kind === 201 /* ObjectLiteralExpression */) { return { kind: "interface" /* interfaceElement */, displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(21 /* CloseParenToken */)] }; } - else if (node.kind === 221 /* ClassExpression */) { + else if (node.kind === 222 /* ClassExpression */) { return { kind: "local class" /* localClassElement */, displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(21 /* CloseParenToken */)] @@ -123811,47 +127918,47 @@ var ts; if (!!(decl.flags & 8388608 /* Ambient */)) return true; switch (decl.kind) { - case 216 /* BinaryExpression */: - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 217 /* BinaryExpression */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: case 87 /* DefaultKeyword */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: - case 270 /* ExportSpecifier */: - case 262 /* ImportClause */: // default import - case 260 /* ImportEqualsDeclaration */: - case 265 /* ImportSpecifier */: - case 253 /* InterfaceDeclaration */: - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: - case 280 /* JsxAttribute */: - case 256 /* ModuleDeclaration */: - case 259 /* NamespaceExportDeclaration */: - case 263 /* NamespaceImport */: - case 269 /* NamespaceExport */: - case 160 /* Parameter */: - case 289 /* ShorthandPropertyAssignment */: - case 254 /* TypeAliasDeclaration */: - case 159 /* TypeParameter */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: + case 271 /* ExportSpecifier */: + case 263 /* ImportClause */: // default import + case 261 /* ImportEqualsDeclaration */: + case 266 /* ImportSpecifier */: + case 254 /* InterfaceDeclaration */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: + case 281 /* JsxAttribute */: + case 257 /* ModuleDeclaration */: + case 260 /* NamespaceExportDeclaration */: + case 264 /* NamespaceImport */: + case 270 /* NamespaceExport */: + case 161 /* Parameter */: + case 290 /* ShorthandPropertyAssignment */: + case 255 /* TypeAliasDeclaration */: + case 160 /* TypeParameter */: return true; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return !!decl.body; - case 249 /* VariableDeclaration */: - case 163 /* PropertyDeclaration */: + case 250 /* VariableDeclaration */: + case 164 /* PropertyDeclaration */: return !!decl.initializer || ts.isCatchClause(decl.parent); - case 164 /* MethodSignature */: - case 162 /* PropertySignature */: - case 333 /* JSDocPropertyTag */: - case 326 /* JSDocParameterTag */: + case 165 /* MethodSignature */: + case 163 /* PropertySignature */: + case 337 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: return false; default: return ts.Debug.failBadSyntaxKind(decl); @@ -123873,7 +127980,7 @@ var ts; } if (ts.isSourceFile(node)) { var resolvedRef = ts.GoToDefinition.getReferenceAtPosition(node, position, program); - if (!resolvedRef) { + if (!(resolvedRef === null || resolvedRef === void 0 ? void 0 : resolvedRef.file)) { return undefined; } var moduleSymbol = program.getTypeChecker().getMergedSymbol(resolvedRef.file.symbol); @@ -123902,7 +128009,7 @@ var ts; if (!symbol) { // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. if (!options.implementations && ts.isStringLiteralLike(node)) { - if (ts.isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ true) || ts.isExternalModuleReference(node.parent) || ts.isImportDeclaration(node.parent) || ts.isImportCall(node.parent)) { + if (ts.isModuleSpecifierLike(node)) { var fileIncludeReasons = program.getFileIncludeReasons(); var referencedFileName = (_b = (_a = node.getSourceFile().resolvedModules) === null || _a === void 0 ? void 0 : _a.get(node.text)) === null || _b === void 0 ? void 0 : _b.resolvedFileName; var referencedFile = referencedFileName ? program.getSourceFile(referencedFileName) : undefined; @@ -124003,7 +128110,7 @@ var ts; result = references; continue; } - var _loop_3 = function (entry) { + var _loop_4 = function (entry) { if (!entry.definition || entry.definition.type !== 0 /* Symbol */) { result.push(entry); return "continue"; @@ -124035,7 +128142,7 @@ var ts; }; for (var _b = 0, references_2 = references; _b < references_2.length; _b++) { var entry = references_2[_b]; - _loop_3(entry); + _loop_4(entry); } } return result; @@ -124072,10 +128179,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; switch (decl.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) break; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { references.push(nodeEntry(decl.name)); } @@ -124087,7 +128194,7 @@ var ts; } } var exported = symbol.exports.get("export=" /* ExportEquals */); - if (exported) { + if (exported === null || exported === void 0 ? void 0 : exported.declarations) { for (var _b = 0, _c = exported.declarations; _b < _c.length; _b++) { var decl = _c[_b]; var sourceFile = decl.getSourceFile(); @@ -124150,14 +128257,14 @@ var ts; var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); - var exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); + var exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) || !symbol.declarations ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); if (exportSpecifier) { // When renaming at an export specifier, rename the export and not the thing being exported. getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); } - else if (node && node.kind === 87 /* DefaultKeyword */) { + else if (node && node.kind === 87 /* DefaultKeyword */ && symbol.escapedName === "default" /* Default */ && symbol.parent) { addReference(node, symbol, state); - searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.checkDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state); } else { var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === 2 /* Rename */, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); @@ -124183,7 +128290,7 @@ var ts; } function getSpecialSearchKind(node) { switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: case 132 /* ConstructorKeyword */: return 1 /* Constructor */; case 78 /* Identifier */: @@ -124314,8 +128421,8 @@ var ts; var sourceId = ts.getNodeId(sourceFile); var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = new ts.Set()); var anyNewSymbols = false; - for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { - var sym = symbols_3[_i]; + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var sym = symbols_2[_i]; anyNewSymbols = ts.tryAddToSet(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols; } return anyNewSymbols; @@ -124372,7 +128479,9 @@ var ts; for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { var node = _d[_c]; // Import specifiers should be handled by importSearches - if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) { + var symbol = checker.getSymbolAtLocation(node); + var hasExportAssignmentDeclaration = ts.some(symbol === null || symbol === void 0 ? void 0 : symbol.declarations, function (d) { return ts.tryCast(d, ts.isExportAssignment) ? true : false; }); + if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && (symbol === exportSymbol || hasExportAssignmentDeclaration)) { cb(node); } } @@ -124424,7 +128533,7 @@ var ts; // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 208 /* FunctionExpression */ || valueDeclaration.kind === 221 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 209 /* FunctionExpression */ || valueDeclaration.kind === 222 /* ClassExpression */)) { return valueDeclaration; } if (!declarations) { @@ -124432,9 +128541,9 @@ var ts; } // If this is private property or method, the scope is the containing class if (flags & (4 /* Property */ | 8192 /* Method */)) { - var privateDeclaration = ts.find(declarations, function (d) { return ts.hasEffectiveModifier(d, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(d); }); + var privateDeclaration = ts.find(declarations, function (d) { return ts.hasEffectiveModifier(d, 8 /* Private */) || ts.isPrivateIdentifierClassElementDeclaration(d); }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 252 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 253 /* ClassDeclaration */); } // Else this is a public property and could be accessed from anywhere. return undefined; @@ -124463,7 +128572,7 @@ var ts; // Different declarations have different containers, bail out return undefined; } - if (!container || container.kind === 297 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + if (!container || container.kind === 298 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -124679,6 +128788,10 @@ var ts; default: ts.Debug.assertNever(state.specialSearchKind); } + // Use the parent symbol if the location is commonjs require syntax on javascript files only. + referenceSymbol = ts.isInJSFile(referenceLocation) && referenceLocation.parent.kind === 199 /* BindingElement */ && ts.isRequireVariableDeclaration(referenceLocation.parent) + ? referenceLocation.parent.symbol + : referenceSymbol; getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { @@ -124841,14 +128954,14 @@ var ts; for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; var ctrKeyword = ts.findChildOfKind(decl, 132 /* ConstructorKeyword */, sourceFile); - ts.Debug.assert(decl.kind === 166 /* Constructor */ && !!ctrKeyword); + ts.Debug.assert(decl.kind === 167 /* Constructor */ && !!ctrKeyword); addNode(ctrKeyword); } } if (classSymbol.exports) { classSymbol.exports.forEach(function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 165 /* MethodDeclaration */) { + if (decl && decl.kind === 166 /* MethodDeclaration */) { var body = decl.body; if (body) { forEachDescendantOfKind(body, 107 /* ThisKeyword */, function (thisKeyword) { @@ -124872,7 +128985,7 @@ var ts; } for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 166 /* Constructor */); + ts.Debug.assert(decl.kind === 167 /* Constructor */); var body = decl.body; if (body) { forEachDescendantOfKind(body, 105 /* SuperKeyword */, function (node) { @@ -124902,7 +129015,7 @@ var ts; if (refNode.kind !== 78 /* Identifier */) { return; } - if (refNode.parent.kind === 289 /* ShorthandPropertyAssignment */) { + if (refNode.parent.kind === 290 /* ShorthandPropertyAssignment */) { // Go ahead and dereference the shorthand assignment by going to its definition getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); } @@ -124922,7 +129035,7 @@ var ts; } else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) { var body = typeHavingNode.body; - if (body.kind === 230 /* Block */) { + if (body.kind === 231 /* Block */) { ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression) addIfImplementation(returnStatement.expression); @@ -124950,13 +129063,13 @@ var ts; */ function isImplementationExpression(node) { switch (node.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isImplementationExpression(node.expression); - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: - case 200 /* ObjectLiteralExpression */: - case 221 /* ClassExpression */: - case 199 /* ArrayLiteralExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 201 /* ObjectLiteralExpression */: + case 222 /* ClassExpression */: + case 200 /* ArrayLiteralExpression */: return true; default: return false; @@ -125009,13 +129122,13 @@ var ts; // Whether 'super' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -125036,41 +129149,43 @@ var ts; return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function isParameterName(node) { - return node.kind === 78 /* Identifier */ && node.parent.kind === 160 /* Parameter */ && node.parent.name === node; + return node.kind === 78 /* Identifier */ && node.parent.kind === 161 /* Parameter */ && node.parent.name === node; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { + staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning object literals break; } // falls through - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) { return undefined; } // falls through - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: break; // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. default: return undefined; } - var references = ts.flatMap(searchSpaceNode.kind === 297 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { + var references = ts.flatMap(searchSpaceNode.kind === 298 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) { if (!ts.isThis(node)) { @@ -125078,19 +129193,20 @@ var ts; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: return searchSpaceNode.symbol === container.symbol; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: - // Make sure the container belongs to the same class + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 201 /* ObjectLiteralExpression */: + // Make sure the container belongs to the same class/object literals // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getSyntacticModifierFlags(container) & 32 /* Static */) === staticFlag; - case 297 /* SourceFile */: - return container.kind === 297 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node); + case 298 /* SourceFile */: + return container.kind === 298 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node); } }); }).map(function (n) { return nodeEntry(n); }); @@ -125200,7 +129316,7 @@ 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]); } - var exportSpecifier = ts.getDeclarationOfKind(symbol, 270 /* ExportSpecifier */); + var exportSpecifier = ts.getDeclarationOfKind(symbol, 271 /* ExportSpecifier */); if (!isForRenamePopulateSearchSymbolSet || exportSpecifier && !exportSpecifier.propertyName) { var localSymbol = exportSpecifier && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); if (localSymbol) { @@ -125245,7 +129361,7 @@ var ts; }); } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - var bindingElement = ts.getDeclarationOfKind(symbol, 198 /* BindingElement */); + var bindingElement = ts.getDeclarationOfKind(symbol, 199 /* BindingElement */); if (bindingElement && ts.isObjectBindingElementWithoutPropertyName(bindingElement)) { return ts.getPropertySymbolFromBindingElement(checker, bindingElement); } @@ -125498,16 +129614,16 @@ var ts; return; } switch (node.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: - if (node.parent.kind === 200 /* ObjectLiteralExpression */) { + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + if (node.parent.kind === 201 /* ObjectLiteralExpression */) { return (_a = ts.getAssignedName(node.parent)) === null || _a === void 0 ? void 0 : _a.getText(); } return (_b = ts.getNameOfDeclaration(node.parent)) === null || _b === void 0 ? void 0 : _b.getText(); - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: if (ts.isModuleBlock(node.parent) && ts.isIdentifier(node.parent.parent.name)) { return node.parent.parent.name.getText(); } @@ -125713,55 +129829,55 @@ var ts; } switch (node.kind) { case 78 /* Identifier */: - case 260 /* ImportEqualsDeclaration */: - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: // do not descend into nodes that cannot contain callable nodes return; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: // do not descend into the type side of an assertion collect(node.expression); return; - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: // do not descend into the type of a variable or parameter declaration collect(node.name); collect(node.initializer); return; - case 203 /* CallExpression */: + case 204 /* CallExpression */: // do not descend into the type arguments of a call expression recordCallSite(node); collect(node.expression); ts.forEach(node.arguments, collect); return; - case 204 /* NewExpression */: + case 205 /* NewExpression */: // do not descend into the type arguments of a new expression recordCallSite(node); collect(node.expression); ts.forEach(node.arguments, collect); return; - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: // do not descend into the type arguments of a tagged template expression recordCallSite(node); collect(node.tag); collect(node.template); return; - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: // do not descend into the type arguments of a JsxOpeningLikeElement recordCallSite(node); collect(node.tagName); collect(node.attributes); return; - case 161 /* Decorator */: + case 162 /* Decorator */: recordCallSite(node); collect(node.expression); return; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: recordCallSite(node); ts.forEachChild(node, collect); break; @@ -125811,22 +129927,22 @@ var ts; var callSites = []; var collect = createCallSiteCollector(program, callSites); switch (node.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: collectCallSitesOfSourceFile(node, collect); break; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: collectCallSitesOfModuleDeclaration(node, collect); break; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: collectCallSitesOfFunctionLikeDeclaration(program.getTypeChecker(), node, collect); break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: collectCallSitesOfClassLikeDeclaration(node, collect); break; default: @@ -125959,7 +130075,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_4 = function (sourceFile) { + var _loop_5 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.fileName); var newImportFromPath = newFromOld !== null && newFromOld !== void 0 ? newFromOld : sourceFile.fileName; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -125976,7 +130092,7 @@ var ts; }, function (importLiteral) { var importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); // No need to update if it's an ambient module^M - if (importedModuleSymbol && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) + if ((importedModuleSymbol === null || importedModuleSymbol === void 0 ? void 0 : importedModuleSymbol.declarations) && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) return undefined; var toImport = oldFromNew !== undefined // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. @@ -125991,7 +130107,7 @@ var ts; }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_4(sourceFile); + _loop_5(sourceFile); } } function combineNormal(pathA, pathB) { @@ -126082,8 +130198,10 @@ var ts; (function (GoToDefinition) { function getDefinitionAtPosition(program, sourceFile, position) { var resolvedRef = getReferenceAtPosition(sourceFile, position, program); - if (resolvedRef) { - return [getDefinitionInfoForFileReference(resolvedRef.reference.fileName, resolvedRef.file.fileName)]; + var fileReferenceDefinition = resolvedRef && [getDefinitionInfoForFileReference(resolvedRef.reference.fileName, resolvedRef.fileName, resolvedRef.unverified)] || ts.emptyArray; + if (resolvedRef === null || resolvedRef === void 0 ? void 0 : resolvedRef.file) { + // If `file` is missing, do a symbol-based lookup as well + return fileReferenceDefinition; } var node = ts.getTouchingPropertyName(sourceFile, position); if (node === sourceFile) { @@ -126100,7 +130218,7 @@ var ts; // Could not find a symbol e.g. node is string or number keyword, // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol if (!symbol) { - return getDefinitionInfoForIndexSignatures(node, typeChecker); + return ts.concatenate(fileReferenceDefinition, getDefinitionInfoForIndexSignatures(node, typeChecker)); } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. @@ -126122,9 +130240,10 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 289 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 290 /* ShorthandPropertyAssignment */) { var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); - return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : []; + var definitions = (shorthandSymbol_1 === null || shorthandSymbol_1 === void 0 ? void 0 : shorthandSymbol_1.declarations) ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : ts.emptyArray; + return ts.concatenate(definitions, getDefinitionFromObjectLiteralElement(typeChecker, node) || ts.emptyArray); } // If the node is the name of a BindingElement within an ObjectBindingPattern instead of just returning the // declaration the symbol (which is itself), we should try to get to the original type of the ObjectBindingPattern @@ -126146,25 +130265,7 @@ var ts; return prop && getDefinitionFromSymbol(typeChecker, prop, node); }); } - // If the current location we want to find its definition is in an object literal, try to get the contextual type for the - // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. - // For example - // interface Props{ - // /*first*/prop1: number - // prop2: boolean - // } - // function Foo(arg: Props) {} - // Foo( { pr/*1*/op1: 10, prop2: true }) - var element = ts.getContainingObjectLiteralElement(node); - if (element) { - var contextualType = element && typeChecker.getContextualType(element.parent); - if (contextualType) { - return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) { - return getDefinitionFromSymbol(typeChecker, propertySymbol, node); - }); - } - } - return getDefinitionFromSymbol(typeChecker, symbol, node); + return ts.concatenate(fileReferenceDefinition, getDefinitionFromObjectLiteralElement(typeChecker, node) || getDefinitionFromSymbol(typeChecker, symbol, node)); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; /** @@ -126178,22 +130279,60 @@ var ts; || ts.isAssignmentExpression(calledDeclaration.parent) || (!ts.isCallLikeExpression(calledDeclaration.parent) && s === calledDeclaration.parent.symbol); } + // If the current location we want to find its definition is in an object literal, try to get the contextual type for the + // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. + // For example + // interface Props{ + // /*first*/prop1: number + // prop2: boolean + // } + // function Foo(arg: Props) {} + // Foo( { pr/*1*/op1: 10, prop2: true }) + function getDefinitionFromObjectLiteralElement(typeChecker, node) { + var element = ts.getContainingObjectLiteralElement(node); + if (element) { + var contextualType = element && typeChecker.getContextualType(element.parent); + if (contextualType) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); + } + } + } function getReferenceAtPosition(sourceFile, position, program) { + var _a, _b; var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); if (referencePath) { var file = program.getSourceFileFromReference(sourceFile, referencePath); - return file && { reference: referencePath, file: file }; + return file && { reference: referencePath, fileName: file.fileName, file: file, unverified: false }; } var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); var file = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217 - return file && { reference: typeReferenceDirective, file: file }; + return file && { reference: typeReferenceDirective, fileName: file.fileName, file: file, unverified: false }; } var libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position); if (libReferenceDirective) { var file = program.getLibFileFromReference(libReferenceDirective); - return file && { reference: libReferenceDirective, file: file }; + return file && { reference: libReferenceDirective, fileName: file.fileName, file: file, unverified: false }; + } + if ((_a = sourceFile.resolvedModules) === null || _a === void 0 ? void 0 : _a.size) { + var node = ts.getTokenAtPosition(sourceFile, position); + if (ts.isModuleSpecifierLike(node) && ts.isExternalModuleNameRelative(node.text) && sourceFile.resolvedModules.has(node.text)) { + var verifiedFileName = (_b = sourceFile.resolvedModules.get(node.text)) === null || _b === void 0 ? void 0 : _b.resolvedFileName; + var fileName = verifiedFileName || ts.resolvePath(ts.getDirectoryPath(sourceFile.fileName), node.text); + return { + file: program.getSourceFile(fileName), + fileName: fileName, + reference: { + pos: node.getStart(), + end: node.getEnd(), + fileName: node.text + }, + unverified: !verifiedFileName, + }; + } } return undefined; } @@ -126264,7 +130403,7 @@ var ts; // get the aliased symbol instead. This allows for goto def on an import e.g. // import {A, B} from "mod"; // to jump to the implementation directly. - if (symbol && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { + if ((symbol === null || symbol === void 0 ? void 0 : symbol.declarations) && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { var aliased = checker.getAliasedSymbol(symbol); if (aliased.declarations) { return aliased; @@ -126285,14 +130424,14 @@ var ts; return true; } switch (declaration.kind) { - case 262 /* ImportClause */: - case 260 /* ImportEqualsDeclaration */: + case 263 /* ImportClause */: + case 261 /* ImportEqualsDeclaration */: return true; - case 265 /* ImportSpecifier */: - return declaration.parent.kind === 264 /* NamedImports */; - case 198 /* BindingElement */: - case 249 /* VariableDeclaration */: - return ts.isInJSFile(declaration) && ts.isRequireVariableDeclaration(declaration, /*requireStringLiteralLikeArgument*/ true); + case 266 /* ImportSpecifier */: + return declaration.parent.kind === 265 /* NamedImports */; + case 199 /* BindingElement */: + case 250 /* VariableDeclaration */: + return ts.isInJSFile(declaration) && ts.isRequireVariableDeclaration(declaration); default: return false; } @@ -126344,7 +130483,38 @@ var ts; var sourceFile = name.getSourceFile(); var textSpan = ts.createTextSpanFromNode(name, sourceFile); return __assign(__assign({ fileName: sourceFile.fileName, textSpan: textSpan, kind: symbolKind, name: symbolName, containerKind: undefined, // TODO: GH#18217 - containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !checker.isDeclarationVisible(declaration) }); + containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !isDefinitionVisible(checker, declaration) }); + } + function isDefinitionVisible(checker, declaration) { + if (checker.isDeclarationVisible(declaration)) + return true; + if (!declaration.parent) + return false; + // Variable initializers are visible if variable is visible + if (ts.hasInitializer(declaration.parent) && declaration.parent.initializer === declaration) + return isDefinitionVisible(checker, declaration.parent); + // Handle some exceptions here like arrow function, members of class and object literal expression which are technically not visible but we want the definition to be determined by its parent + switch (declaration.kind) { + case 164 /* PropertyDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + // Private/protected properties/methods are not visible + if (ts.hasEffectiveModifier(declaration, 8 /* Private */)) + return false; + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 167 /* Constructor */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 201 /* ObjectLiteralExpression */: + case 222 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + return isDefinitionVisible(checker, declaration.parent); + default: + return false; + } } function createDefinitionFromSignatureDeclaration(typeChecker, decl) { return createDefinitionInfo(decl, typeChecker, decl.symbol, decl); @@ -126353,14 +130523,15 @@ var ts; return ts.find(refs, function (ref) { return ts.textRangeContainsPositionInclusive(ref, pos); }); } GoToDefinition.findReferenceInPosition = findReferenceInPosition; - function getDefinitionInfoForFileReference(name, targetFileName) { + function getDefinitionInfoForFileReference(name, targetFileName, unverified) { return { fileName: targetFileName, textSpan: ts.createTextSpanFromBounds(0, 0), kind: "script" /* scriptElement */, name: name, containerName: undefined, - containerKind: undefined, // TODO: GH#18217 + containerKind: undefined, + unverified: unverified, }; } /** Returns a CallLikeExpression where `node` is the target being invoked. */ @@ -126377,9 +130548,9 @@ var ts; } function isConstructorLike(node) { switch (node.kind) { - case 166 /* Constructor */: - case 175 /* ConstructorType */: - case 170 /* ConstructSignature */: + case 167 /* Constructor */: + case 176 /* ConstructorType */: + case 171 /* ConstructSignature */: return true; default: return false; @@ -126436,6 +130607,7 @@ var ts; "kind", "lends", "license", + "link", "listens", "member", "memberof", @@ -126473,78 +130645,115 @@ var ts; ]; var jsDocTagNameCompletionEntries; var jsDocTagCompletionEntries; - function getJsDocCommentsFromDeclarations(declarations) { + function getJsDocCommentsFromDeclarations(declarations, checker) { // Only collect doc comments from duplicate declarations once: // In case of a union property there might be same declaration multiple times // which only varies in type parameter // Eg. const a: Array | Array; a.length // The property length will have two declarations of property length coming // from Array - Array and Array - var documentationComment = []; + var parts = []; ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { var comment = _a[_i].comment; if (comment === undefined) continue; - ts.pushIfUnique(documentationComment, comment); + var newparts = getDisplayPartsFromComment(comment, checker); + if (!ts.contains(parts, newparts, isIdenticalListOfDisplayParts)) { + parts.push(newparts); + } } }); - return ts.intersperse(ts.map(documentationComment, ts.textPart), ts.lineBreakPart()); + return ts.flatten(ts.intersperse(parts, [ts.lineBreakPart()])); } JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function isIdenticalListOfDisplayParts(parts1, parts2) { + return ts.arraysEqual(parts1, parts2, function (p1, p2) { return p1.kind === p2.kind && p1.text === p2.text; }); + } function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 326 /* JSDocParameterTag */: - case 333 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: return [declaration]; - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); } } - function getJsDocTagsFromDeclarations(declarations) { + function getJsDocTagsFromDeclarations(declarations, checker) { // Only collect doc comments from duplicate declarations once. var tags = []; ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { var tag = _a[_i]; - tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); + tags.push({ name: tag.tagName.text, text: getCommentDisplayParts(tag, checker) }); } }); return tags; } JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations; - function getCommentText(tag) { - var comment = tag.comment; - switch (tag.kind) { - case 316 /* JSDocImplementsTag */: + function getDisplayPartsFromComment(comment, checker) { + if (typeof comment === "string") { + return [ts.textPart(comment)]; + } + return ts.flatMap(comment, function (node) { return node.kind === 313 /* JSDocText */ ? [ts.textPart(node.text)] : ts.buildLinkParts(node, checker); }); + } + function getCommentDisplayParts(tag, checker) { + var comment = tag.comment, kind = tag.kind; + var namePart = getTagNameDisplayPart(kind); + switch (kind) { + case 319 /* JSDocImplementsTag */: return withNode(tag.class); - case 315 /* JSDocAugmentsTag */: + case 318 /* JSDocAugmentsTag */: return withNode(tag.class); - case 330 /* JSDocTemplateTag */: - return withList(tag.typeParameters); - case 329 /* JSDocTypeTag */: + case 334 /* JSDocTemplateTag */: + return addComment(tag.typeParameters.map(function (tp) { return tp.getText(); }).join(", ")); + case 333 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 333 /* JSDocPropertyTag */: - case 326 /* JSDocParameterTag */: - case 332 /* JSDocSeeTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 337 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: + case 336 /* JSDocSeeTag */: var name = tag.name; - return name ? withNode(name) : comment; + return name ? withNode(name) + : comment === undefined ? undefined + : getDisplayPartsFromComment(comment, checker); default: - return comment; + return comment === undefined ? undefined : getDisplayPartsFromComment(comment, checker); } function withNode(node) { return addComment(node.getText()); } - function withList(list) { - return addComment(list.map(function (x) { return x.getText(); }).join(", ")); - } function addComment(s) { - return comment === undefined ? s : s + " " + comment; + if (comment) { + if (s.match(/^https?$/)) { + return __spreadArray([ts.textPart(s)], getDisplayPartsFromComment(comment, checker)); + } + else { + return __spreadArray([namePart(s), ts.spacePart()], getDisplayPartsFromComment(comment, checker)); + } + } + else { + return [ts.textPart(s)]; + } + } + } + function getTagNameDisplayPart(kind) { + switch (kind) { + case 330 /* JSDocParameterTag */: + return ts.parameterNamePart; + case 337 /* JSDocPropertyTag */: + return ts.propertyNamePart; + case 334 /* JSDocTemplateTag */: + return ts.typeParameterNamePart; + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + return ts.typeAliasNamePart; + default: + return ts.textPart; } } function getJSDocTagNameCompletions() { @@ -126638,7 +130847,7 @@ var ts; * @param position The (character-indexed) position in the file where the check should * be performed. */ - function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { + function getDocCommentTemplateAtPosition(newLine, sourceFile, position, options) { var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc); if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) { @@ -126650,7 +130859,7 @@ var ts; if (!existingDocComment && tokenStart < position) { return undefined; } - var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); + var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos, options); if (!commentOwnerInfo) { return undefined; } @@ -126700,76 +130909,77 @@ var ts; function returnsDocComment(indentationStr, newLine) { return indentationStr + " * @returns" + newLine; } - function getCommentOwnerInfo(tokenAtPos) { - return ts.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker); + function getCommentOwnerInfo(tokenAtPos, options) { + return ts.forEachAncestor(tokenAtPos, function (n) { return getCommentOwnerInfoWorker(n, options); }); } - function getCommentOwnerInfoWorker(commentOwner) { + function getCommentOwnerInfoWorker(commentOwner, options) { switch (commentOwner.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 164 /* MethodSignature */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 165 /* MethodSignature */: + case 210 /* ArrowFunction */: var host = commentOwner; - return { commentOwner: commentOwner, parameters: host.parameters, hasReturn: hasReturn(host) }; - case 288 /* PropertyAssignment */: - return getCommentOwnerInfoWorker(commentOwner.initializer); - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 162 /* PropertySignature */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: - case 254 /* TypeAliasDeclaration */: + return { commentOwner: commentOwner, parameters: host.parameters, hasReturn: hasReturn(host, options) }; + case 289 /* PropertyAssignment */: + return getCommentOwnerInfoWorker(commentOwner.initializer, options); + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 163 /* PropertySignature */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: + case 255 /* TypeAliasDeclaration */: return { commentOwner: commentOwner }; - case 232 /* VariableStatement */: { + case 233 /* VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; var host_1 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; return host_1 - ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1) } + ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1, options) } : { commentOwner: commentOwner }; } - case 297 /* SourceFile */: + case 298 /* SourceFile */: return "quit"; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: // If in walking up the tree, we hit a a nested namespace declaration, // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - return commentOwner.parent.kind === 256 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; - case 233 /* ExpressionStatement */: - return getCommentOwnerInfoWorker(commentOwner.expression); - case 216 /* BinaryExpression */: { + return commentOwner.parent.kind === 257 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 234 /* ExpressionStatement */: + return getCommentOwnerInfoWorker(commentOwner.expression, options); + case 217 /* BinaryExpression */: { var be = commentOwner; if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } return ts.isFunctionLike(be.right) - ? { commentOwner: commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right) } + ? { commentOwner: commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right, options) } : { commentOwner: commentOwner }; } - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: var init = commentOwner.initializer; if (init && (ts.isFunctionExpression(init) || ts.isArrowFunction(init))) { - return { commentOwner: commentOwner, parameters: init.parameters, hasReturn: hasReturn(init) }; + return { commentOwner: commentOwner, parameters: init.parameters, hasReturn: hasReturn(init, options) }; } } } - function hasReturn(node) { - return ts.isArrowFunction(node) && ts.isExpression(node.body) - || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; }); + function hasReturn(node, options) { + return !!(options === null || options === void 0 ? void 0 : options.generateReturnInDocTemplate) && + (ts.isArrowFunction(node) && ts.isExpression(node.body) + || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; })); } function getRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 207 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 208 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return rightHandSide; - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return ts.find(rightHandSide.members, ts.isConstructorDeclaration); } } @@ -126785,7 +130995,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_5 = function (sourceFile) { + var _loop_6 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -126797,7 +131007,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var sourceFile = sourceFiles_4[_i]; - _loop_5(sourceFile); + _loop_6(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -126828,9 +131038,9 @@ var ts; } function shouldKeepItem(declaration, checker) { switch (declaration.kind) { - case 262 /* ImportClause */: - case 265 /* ImportSpecifier */: - case 260 /* ImportEqualsDeclaration */: + case 263 /* ImportClause */: + case 266 /* ImportSpecifier */: + case 261 /* ImportEqualsDeclaration */: var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217 var imported = checker.getAliasedSymbol(importer); return importer.escapedName !== imported.escapedName; @@ -126840,7 +131050,7 @@ var ts; } function tryAddSingleDeclarationName(declaration, containers) { var name = ts.getNameOfDeclaration(declaration); - return !!name && (pushLiteral(name, containers) || name.kind === 158 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); + return !!name && (pushLiteral(name, containers) || name.kind === 159 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); } // Only added the names of computed properties if they're simple dotted expressions, like: // @@ -126857,7 +131067,7 @@ var ts; // First, if we started with a computed property name, then add all but the last // portion into the container array. var name = ts.getNameOfDeclaration(declaration); - if (name && name.kind === 158 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { + if (name && name.kind === 159 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { return ts.emptyArray; } // Don't include the last portion. @@ -127057,6 +131267,28 @@ var ts; addChildrenRecursively(child); endNode(); } + function addNodeWithRecursiveInitializer(node) { + if (node.initializer && isFunctionOrClassExpression(node.initializer)) { + startNode(node); + ts.forEachChild(node.initializer, addChildrenRecursively); + endNode(); + } + else { + addNodeWithRecursiveChild(node, node.initializer); + } + } + /** + * Historically, we've elided dynamic names from the nav tree (including late bound names), + * but included certain "well known" symbol names. While we no longer distinguish those well-known + * symbols from other unique symbols, we do the below to retain those members in the nav tree. + */ + function hasNavigationBarName(node) { + return !ts.hasDynamicName(node) || + (node.kind !== 217 /* BinaryExpression */ && + ts.isPropertyAccessExpression(node.name.expression) && + ts.isIdentifier(node.name.expression.expression) && + ts.idText(node.name.expression.expression) === "Symbol"); + } /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ function addChildrenRecursively(node) { var _a; @@ -127065,7 +131297,7 @@ var ts; return; } switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. var ctr = node; addNodeWithRecursiveChild(ctr, ctr.body); @@ -127077,21 +131309,25 @@ var ts; } } break; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 164 /* MethodSignature */: - if (!ts.hasDynamicName(node)) { + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 165 /* MethodSignature */: + if (hasNavigationBarName(node)) { addNodeWithRecursiveChild(node, node.body); } break; - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - if (!ts.hasDynamicName(node)) { + case 164 /* PropertyDeclaration */: + if (hasNavigationBarName(node)) { + addNodeWithRecursiveInitializer(node); + } + break; + case 163 /* PropertySignature */: + if (hasNavigationBarName(node)) { addLeafNode(node); } break; - case 262 /* ImportClause */: + case 263 /* ImportClause */: var importClause = node; // Handle default import case e.g.: // import d from "mod"; @@ -127103,7 +131339,7 @@ var ts; // import {a, b as B} from "mod"; var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 263 /* NamespaceImport */) { + if (namedBindings.kind === 264 /* NamespaceImport */) { addLeafNode(namedBindings); } else { @@ -127114,32 +131350,27 @@ var ts; } } break; - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: addNodeWithRecursiveChild(node, node.name); break; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: var expression = node.expression; // Use the expression as the name of the SpreadAssignment, otherwise show as . ts.isIdentifier(expression) ? addLeafNode(node, expression) : addLeafNode(node); break; - case 198 /* BindingElement */: - case 288 /* PropertyAssignment */: - case 249 /* VariableDeclaration */: - var _e = node, name = _e.name, initializer = _e.initializer; - if (ts.isBindingPattern(name)) { - addChildrenRecursively(name); - } - else if (initializer && isFunctionOrClassExpression(initializer)) { - // Add a node for the VariableDeclaration, but not for the initializer. - startNode(node); - ts.forEachChild(initializer, addChildrenRecursively); - endNode(); + case 199 /* BindingElement */: + case 289 /* PropertyAssignment */: + case 250 /* VariableDeclaration */: { + var child = node; + if (ts.isBindingPattern(child.name)) { + addChildrenRecursively(child.name); } else { - addNodeWithRecursiveChild(node, initializer); + addNodeWithRecursiveInitializer(child); } break; - case 251 /* FunctionDeclaration */: + } + case 252 /* FunctionDeclaration */: var nameNode = node.name; // If we see a function declaration track as a possible ES5 class if (nameNode && ts.isIdentifier(nameNode)) { @@ -127147,34 +131378,34 @@ var ts; } addNodeWithRecursiveChild(node, node.body); break; - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: addNodeWithRecursiveChild(node, node.body); break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: startNode(node); - for (var _f = 0, _g = node.members; _f < _g.length; _f++) { - var member = _g[_f]; + for (var _e = 0, _f = node.members; _e < _f.length; _e++) { + var member = _f[_e]; if (!isComputedProperty(member)) { addLeafNode(member); } } endNode(); break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: startNode(node); - for (var _h = 0, _j = node.members; _h < _j.length; _h++) { - var member = _j[_h]; + for (var _g = 0, _h = node.members; _g < _h.length; _g++) { + var member = _h[_g]; addChildrenRecursively(member); } endNode(); break; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 266 /* ExportAssignment */: { + case 267 /* ExportAssignment */: { var expression_1 = node.expression; var child = ts.isObjectLiteralExpression(expression_1) || ts.isCallExpression(expression_1) ? expression_1 : ts.isArrowFunction(expression_1) || ts.isFunctionExpression(expression_1) ? expression_1.body : undefined; @@ -127188,16 +131419,16 @@ var ts; } break; } - case 270 /* ExportSpecifier */: - case 260 /* ImportEqualsDeclaration */: - case 171 /* IndexSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 254 /* TypeAliasDeclaration */: + case 271 /* ExportSpecifier */: + case 261 /* ImportEqualsDeclaration */: + case 172 /* IndexSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 255 /* TypeAliasDeclaration */: addLeafNode(node); break; - case 203 /* CallExpression */: - case 216 /* BinaryExpression */: { + case 204 /* CallExpression */: + case 217 /* BinaryExpression */: { var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: @@ -127249,7 +131480,7 @@ var ts; defineCall.arguments[0] : defineCall.arguments[0].expression; var memberName = defineCall.arguments[1]; - var _k = startNestedNodes(node, className), depth = _k[0], classNameIdentifier = _k[1]; + var _j = startNestedNodes(node, className), depth = _j[0], classNameIdentifier = _j[1]; startNode(node, classNameIdentifier); startNode(node, ts.setTextRange(ts.factory.createIdentifier(memberName.text), memberName)); addChildrenRecursively(node.arguments[2]); @@ -127439,13 +131670,14 @@ var ts; return false; } switch (a.kind) { - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return ts.hasSyntacticModifier(a, 32 /* Static */) === ts.hasSyntacticModifier(b, 32 /* Static */); - case 256 /* ModuleDeclaration */: - return areSameModule(a, b); + case 257 /* ModuleDeclaration */: + return areSameModule(a, b) + && getFullyQualifiedModuleName(a) === getFullyQualifiedModuleName(b); default: return true; } @@ -127462,8 +131694,7 @@ var ts; // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { - // TODO: GH#18217 - return a.body.kind === b.body.kind && (a.body.kind !== 256 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); + return a.body.kind === b.body.kind && (a.body.kind !== 257 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); } /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { @@ -127493,7 +131724,7 @@ var ts; * So `new()` can still come before an `aardvark` method. */ function tryGetName(node) { - if (node.kind === 256 /* ModuleDeclaration */) { + if (node.kind === 257 /* ModuleDeclaration */) { return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); @@ -127502,16 +131733,16 @@ var ts; return propertyName && ts.unescapeLeadingUnderscores(propertyName); } switch (node.kind) { - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 221 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 222 /* ClassExpression */: return getFunctionOrClassName(node); default: return undefined; } } function getItemName(node, name) { - if (node.kind === 256 /* ModuleDeclaration */) { + if (node.kind === 257 /* ModuleDeclaration */) { return cleanText(getModuleName(node)); } if (name) { @@ -127523,18 +131754,18 @@ var ts; } } switch (node.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: var sourceFile = node; return ts.isExternalModule(sourceFile) ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" : ""; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return ts.isExportAssignment(node) && node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; - case 209 /* ArrowFunction */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: if (ts.getSyntacticModifierFlags(node) & 512 /* Default */) { return "default"; } @@ -127542,13 +131773,13 @@ var ts; // (eg: "app\n.onactivated"), so we should remove the whitespace for readability in the // navigation bar. return getFunctionOrClassName(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return "constructor"; - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: return "new()"; - case 169 /* CallSignature */: + case 170 /* CallSignature */: return "()"; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: return "[]"; default: return ""; @@ -127581,19 +131812,19 @@ var ts; } // Some nodes are otherwise important enough to always include in the primary navigation menu. switch (navigationBarNodeKind(item)) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 255 /* EnumDeclaration */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 297 /* SourceFile */: - case 254 /* TypeAliasDeclaration */: - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 256 /* EnumDeclaration */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 298 /* SourceFile */: + case 255 /* TypeAliasDeclaration */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: return true; - case 209 /* ArrowFunction */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; @@ -127603,10 +131834,10 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 257 /* ModuleBlock */: - case 297 /* SourceFile */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: + case 258 /* ModuleBlock */: + case 298 /* SourceFile */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: return true; default: return false; @@ -127663,9 +131894,12 @@ var ts; if (ts.isAmbientModule(moduleDeclaration)) { return ts.getTextOfNode(moduleDeclaration.name); } + return getFullyQualifiedModuleName(moduleDeclaration); + } + function getFullyQualifiedModuleName(moduleDeclaration) { // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = [ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)]; - while (moduleDeclaration.body && moduleDeclaration.body.kind === 256 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 257 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } @@ -127679,13 +131913,13 @@ var ts; return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { - return !member.name || member.name.kind === 158 /* ComputedPropertyName */; + return !member.name || member.name.kind === 159 /* ComputedPropertyName */; } function getNodeSpan(node) { - return node.kind === 297 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); + return node.kind === 298 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); } function getModifiers(node) { - if (node.parent && node.parent.kind === 249 /* VariableDeclaration */) { + if (node.parent && node.parent.kind === 250 /* VariableDeclaration */) { node = node.parent; } return ts.getNodeModifiers(node); @@ -127743,9 +131977,9 @@ var ts; } function isFunctionOrClassExpression(node) { switch (node.kind) { - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: - case 221 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 222 /* ClassExpression */: return true; default: return false; @@ -127774,9 +132008,9 @@ var ts; * 2) Coalescing imports from the same module * 3) Sorting imports */ - function organizeImports(sourceFile, formatContext, host, program, preferences) { + function organizeImports(sourceFile, formatContext, host, program, preferences, skipDestructiveCodeActions) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext, preferences: preferences }); - var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; + var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program, skipDestructiveCodeActions)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; // All of the old ImportDeclarations in the file, in syntactic order. var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports); @@ -127811,26 +132045,35 @@ var ts; ? coalesce(importGroup) : importGroup; }); - // Delete or replace the first import. + // Delete all nodes if there are no imports. if (newImportDecls.length === 0) { - changeTracker.delete(sourceFile, oldImportDecls[0]); + // Consider the first node to have trailingTrivia as we want to exclude the + // "header" comment. + changeTracker.deleteNodes(sourceFile, oldImportDecls, { + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, + }, /*hasTrailingComment*/ true); } else { // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. - changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { + var replaceOptions = { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), - }); - } - // Delete any subsequent imports. - for (var i = 1; i < oldImportDecls.length; i++) { - changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + }; + changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, replaceOptions); + var hasTrailingComment = changeTracker.nodeHasTrailingComment(sourceFile, oldImportDecls[0], replaceOptions); + changeTracker.deleteNodes(sourceFile, oldImportDecls.slice(1), { + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, + }, hasTrailingComment); } } } OrganizeImports.organizeImports = organizeImports; - function removeUnusedImports(oldImports, sourceFile, program) { + function removeUnusedImports(oldImports, sourceFile, program, skipDestructiveCodeActions) { + // As a precaution, consider unused import detection to be destructive (GH #43051) + if (skipDestructiveCodeActions) { + return oldImports; + } var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); var jsxFragmentFactory = typeChecker.getJsxFragmentFactory(sourceFile); @@ -128101,11 +132344,11 @@ var ts; function getModuleSpecifierExpression(declaration) { var _a; switch (declaration.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return (_a = ts.tryCast(declaration.moduleReference, ts.isExternalModuleReference)) === null || _a === void 0 ? void 0 : _a.expression; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return declaration.moduleSpecifier; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return declaration.declarationList.declarations[0].initializer.arguments[0]; } } @@ -128144,19 +132387,19 @@ var ts; function getImportKindOrder(s1) { var _a; switch (s1.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: if (!s1.importClause) return 0; if (s1.importClause.isTypeOnly) return 1; - if (((_a = s1.importClause.namedBindings) === null || _a === void 0 ? void 0 : _a.kind) === 263 /* NamespaceImport */) + if (((_a = s1.importClause.namedBindings) === null || _a === void 0 ? void 0 : _a.kind) === 264 /* NamespaceImport */) return 2; if (s1.importClause.name) return 3; return 4; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return 5; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return 6; } } @@ -128312,7 +132555,7 @@ var ts; } function getOutliningSpanForNode(n, sourceFile) { switch (n.kind) { - case 230 /* Block */: + case 231 /* Block */: if (ts.isFunctionLike(n.parent)) { return functionSpan(n.parent, n, sourceFile); } @@ -128320,16 +132563,16 @@ var ts; // If the latter, we want to collapse the block, but consider its hint span // to be the entire span of the parent. switch (n.parent.kind) { - case 235 /* DoStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 237 /* ForStatement */: - case 234 /* IfStatement */: - case 236 /* WhileStatement */: - case 243 /* WithStatement */: - case 287 /* CatchClause */: + case 236 /* DoStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 238 /* ForStatement */: + case 235 /* IfStatement */: + case 237 /* WhileStatement */: + case 244 /* WithStatement */: + case 288 /* CatchClause */: return spanForNode(n.parent); - case 247 /* TryStatement */: + case 248 /* TryStatement */: // Could be the try-block, or the finally-block. var tryStatement = n.parent; if (tryStatement.tryBlock === n) { @@ -128346,40 +132589,40 @@ var ts; // the span of the block, independent of any parent span. return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */); } - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return spanForNode(n.parent); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 258 /* CaseBlock */: - case 177 /* TypeLiteral */: - case 196 /* ObjectBindingPattern */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 259 /* CaseBlock */: + case 178 /* TypeLiteral */: + case 197 /* ObjectBindingPattern */: return spanForNode(n); - case 179 /* TupleType */: + case 180 /* TupleType */: return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !ts.isTupleTypeNode(n.parent), 22 /* OpenBracketToken */); - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: return spanForNodeArray(n.statements); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return spanForObjectOrArrayLiteral(n); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return spanForObjectOrArrayLiteral(n, 22 /* OpenBracketToken */); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return spanForJSXElement(n); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return spanForJSXFragment(n); - case 274 /* JsxSelfClosingElement */: - case 275 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: return spanForJSXAttributes(n.attributes); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: case 14 /* NoSubstitutionTemplateLiteral */: return spanForTemplateLiteral(n); - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !ts.isBindingElement(n.parent), 22 /* OpenBracketToken */); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return spanForArrowFunction(n); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return spanForCallExpression(n); } function spanForCallExpression(node) { @@ -128446,7 +132689,7 @@ var ts; function functionSpan(node, body, sourceFile) { var openToken = tryGetFunctionOpenToken(node, body, sourceFile); var closeToken = ts.findChildOfKind(body, 19 /* CloseBraceToken */, sourceFile); - return openToken && closeToken && spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ node.kind !== 209 /* ArrowFunction */); + return openToken && closeToken && spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ node.kind !== 210 /* ArrowFunction */); } function spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse, useFullStart) { if (autoCollapse === void 0) { autoCollapse = false; } @@ -128749,15 +132992,15 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_6 = function (start) { + var _loop_7 = 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_1 = _loop_6(start); - if (typeof state_1 === "object") - return state_1.value; + var state_2 = _loop_7(start); + if (typeof state_2 === "object") + return state_2.value; } return -1; } @@ -129309,7 +133552,7 @@ var ts; function getRenameInfo(program, sourceFile, position, options) { var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position)); if (nodeIsEligibleForRename(node)) { - var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }, options); + var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, options); if (renameInfo) { return renameInfo; } @@ -129317,7 +133560,7 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); } Rename.getRenameInfo = getRenameInfo; - function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile, options) { + function getRenameInfoForNode(node, typeChecker, sourceFile, program, options) { var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) { if (ts.isStringLiteralLike(node)) { @@ -129337,7 +133580,7 @@ var ts; if (!declarations || declarations.length === 0) return; // Disallow rename for elements that are defined in the standard TypeScript library. - if (declarations.some(isDefinedInLibraryFile)) { + if (declarations.some(function (declaration) { return isDefinedInLibraryFile(program, declaration); })) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } // Cannot rename `default` as in `import { default as foo } from "./someModule"; @@ -129348,18 +133591,22 @@ var ts; return options && options.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 158 /* ComputedPropertyName */) + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 159 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) : undefined; var displayName = specifierName || typeChecker.symbolToString(symbol); var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(typeChecker, symbol), node, sourceFile); } + function isDefinedInLibraryFile(program, declaration) { + var sourceFile = declaration.getSourceFile(); + return program.isSourceFileDefaultLibrary(sourceFile) && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */); + } function getRenameInfoForModule(node, sourceFile, moduleSymbol) { if (!ts.isExternalModuleNameRelative(node.text)) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); } - var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var moduleSourceFile = moduleSymbol.declarations && ts.find(moduleSymbol.declarations, ts.isSourceFile); if (!moduleSourceFile) return undefined; var withoutIndex = ts.endsWith(node.text, "/index") || ts.endsWith(node.text, "/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); @@ -129440,6 +133687,10 @@ var ts; if (ts.getTokenPosOfNode(node, sourceFile, /*includeJsDoc*/ true) > pos) { break outer; } + var comment = ts.singleOrUndefined(ts.getTrailingCommentRanges(sourceFile.text, node.end)); + if (comment && comment.kind === 2 /* SingleLineCommentTrivia */) { + pushSelectionCommentRange(comment.pos, comment.end); + } if (positionShouldSnapToNode(sourceFile, pos, node)) { // 1. Blocks are effectively redundant with SyntaxLists. // 2. TemplateSpans, along with the SyntaxLists containing them, are a somewhat unintuitive grouping @@ -129502,6 +133753,14 @@ var ts; } } } + function pushSelectionCommentRange(start, end) { + pushSelectionRange(start, end); + var pos = start; + while (sourceFile.text.charCodeAt(pos) === 47 /* slash */) { + pos++; + } + pushSelectionRange(pos, end); + } } SmartSelectionRange.getSmartSelectionRange = getSmartSelectionRange; /** @@ -129565,7 +133824,7 @@ var ts; var groupedWithBrackets = groupChildren(groupedWithPlusMinusTokens, function (_a) { var kind = _a.kind; return kind === 22 /* OpenBracketToken */ || - kind === 159 /* TypeParameter */ || + kind === 160 /* TypeParameter */ || kind === 23 /* CloseBracketToken */; }); return [ @@ -129679,22 +133938,22 @@ var ts; return kind === 18 /* OpenBraceToken */ || kind === 22 /* OpenBracketToken */ || kind === 20 /* OpenParenToken */ - || kind === 275 /* JsxOpeningElement */; + || kind === 276 /* JsxOpeningElement */; } function isListCloser(token) { var kind = token && token.kind; return kind === 19 /* CloseBraceToken */ || kind === 23 /* CloseBracketToken */ || kind === 21 /* CloseParenToken */ - || kind === 276 /* JsxClosingElement */; + || kind === 277 /* JsxClosingElement */; } function getEndPos(sourceFile, node) { switch (node.kind) { - case 326 /* JSDocParameterTag */: - case 324 /* JSDocCallbackTag */: - case 333 /* JSDocPropertyTag */: - case 331 /* JSDocTypedefTag */: - case 328 /* JSDocThisTag */: + case 330 /* JSDocParameterTag */: + case 328 /* JSDocCallbackTag */: + case 337 /* JSDocPropertyTag */: + case 335 /* JSDocTypedefTag */: + case 332 /* JSDocThisTag */: return sourceFile.getLineEndOfPosition(node.getStart()); default: return node.getEnd(); @@ -129904,10 +134163,10 @@ var ts; } return undefined; } - else if (ts.isTemplateHead(node) && parent.parent.kind === 205 /* TaggedTemplateExpression */) { + else if (ts.isTemplateHead(node) && parent.parent.kind === 206 /* TaggedTemplateExpression */) { var templateExpression = parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 218 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 219 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } @@ -129976,17 +134235,17 @@ var ts; return undefined; var parent = startingToken.parent; switch (parent.kind) { - case 207 /* ParenthesizedExpression */: - case 165 /* MethodDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 208 /* ParenthesizedExpression */: + case 166 /* MethodDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: var info = getArgumentOrParameterListInfo(startingToken, sourceFile); if (!info) return undefined; var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; var contextualType = ts.isMethodDeclaration(parent) ? checker.getContextualTypeForObjectLiteralElement(parent) : checker.getContextualType(parent); return contextualType && { contextualType: contextualType, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; - case 216 /* BinaryExpression */: { + case 217 /* BinaryExpression */: { var highestBinary = getHighestBinary(parent); var contextualType_1 = checker.getContextualType(highestBinary); var argumentIndex_1 = startingToken.kind === 20 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1; @@ -130110,7 +134369,7 @@ var ts; // | | // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. - if (template.kind === 218 /* TemplateExpression */) { + if (template.kind === 219 /* TemplateExpression */) { var lastSpan = ts.last(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -130119,7 +134378,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { - var _loop_7 = function (n) { + var _loop_8 = 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.formatSyntaxKind(n.kind) + ", parent: " + ts.Debug.formatSyntaxKind(n.parent.kind); }); @@ -130129,9 +134388,9 @@ var ts; } }; for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) { - var state_2 = _loop_7(n); - if (typeof state_2 === "object") - return state_2.value; + var state_3 = _loop_8(n); + if (typeof state_3 === "object") + return state_3.value; } return undefined; } @@ -130181,7 +134440,19 @@ var ts; itemsSeen += item.length; } 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: ts.flatMapToMutable(items, ts.identity), applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var help = { items: ts.flatMapToMutable(items, ts.identity), applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var selected = help.items[selectedItemIndex]; + if (selected.isVariadic) { + var firstRest = ts.findIndex(selected.parameters, function (p) { return !!p.isRest; }); + if (-1 < firstRest && firstRest < selected.parameters.length - 1) { + // We don't have any code to get this correct; instead, don't highlight a current parameter AT ALL + help.argumentIndex = selected.parameters.length; + } + else { + help.argumentIndex = Math.min(help.argumentIndex, selected.parameters.length - 1); + } + } + return help; } function createTypeHelpItems(symbol, _a, sourceFile, checker) { var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; @@ -130196,7 +134467,7 @@ var ts; 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 tags = symbol.getJsDocTags(checker); var prefixDisplayParts = __spreadArray(__spreadArray([], typeSymbolDisplay), [ts.punctuationPart(29 /* LessThanToken */)]); return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(31 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; } @@ -130263,14 +134534,15 @@ var ts; printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); var isOptional = checker.isOptionalParameter(parameter.valueDeclaration); - return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional }; + var isRest = !!(parameter.checkFlags & 32768 /* RestParameter */); + return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional, isRest: isRest }; } function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { var displayParts = ts.mapToDisplayParts(function (writer) { var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false, isRest: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -130480,7 +134752,7 @@ var ts; diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); } } - if (ts.isFunctionLikeDeclaration(node)) { + if (canBeConvertedToAsync(node)) { addConvertToAsyncFunctionDiagnostics(node, checker, diags); } node.forEachChild(check); @@ -130491,11 +134763,11 @@ var ts; function containsTopLevelCommonjs(sourceFile) { return sourceFile.statements.some(function (statement) { switch (statement.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); }); - case 233 /* ExpressionStatement */: { + case 234 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); @@ -130512,12 +134784,12 @@ var ts; } function importNameForConvertToDefaultImport(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; - return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 263 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 264 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : undefined; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return node.name; default: return undefined; @@ -130533,35 +134805,35 @@ var ts; return !ts.isAsyncFunction(node) && node.body && ts.isBlock(node.body) && - hasReturnStatementWithPromiseHandler(node.body) && + hasReturnStatementWithPromiseHandler(node.body, checker) && returnsPromise(node, checker); } function returnsPromise(node, checker) { - var functionType = checker.getTypeAtLocation(node); - var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); - var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; + var signature = checker.getSignatureFromDeclaration(node); + var returnType = signature ? checker.getReturnTypeOfSignature(signature) : undefined; return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); } + ts.returnsPromise = returnsPromise; function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } - function hasReturnStatementWithPromiseHandler(body) { - return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); + function hasReturnStatementWithPromiseHandler(body, checker) { + return !!ts.forEachReturnStatement(body, function (statement) { return isReturnStatementWithFixablePromiseHandler(statement, checker); }); } - function isReturnStatementWithFixablePromiseHandler(node) { - return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); + function isReturnStatementWithFixablePromiseHandler(node, checker) { + return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression, checker); } ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler; // Should be kept up to date with transformExpression in convertToAsyncFunction.ts - function isFixablePromiseHandler(node) { + function isFixablePromiseHandler(node, checker) { // ensure outermost call exists and is a promise handler - if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + if (!isPromiseHandler(node) || !node.arguments.every(function (arg) { return isFixablePromiseArgument(arg, checker); })) { 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)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(function (arg) { return isFixablePromiseArgument(arg, checker); })) { return false; } currentNode = currentNode.expression; @@ -130584,16 +134856,24 @@ var ts; }); } // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts - function isFixablePromiseArgument(arg) { + function isFixablePromiseArgument(arg, checker) { switch (arg.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true); // falls through case 103 /* NullKeyword */: - case 78 /* Identifier */: // identifier includes undefined return true; + case 78 /* Identifier */: + case 202 /* PropertyAccessExpression */: { + var symbol = checker.getSymbolAtLocation(arg); + if (!symbol) { + return false; + } + return checker.isUndefinedSymbol(symbol) || + ts.some(ts.skipAlias(symbol, checker).declarations, function (d) { return ts.isFunctionLike(d) || ts.hasInitializer(d) && !!d.initializer && ts.isFunctionLike(d.initializer); }); + } default: return false; } @@ -130603,18 +134883,30 @@ var ts; } function canBeConvertedToClass(node, checker) { var _a, _b, _c, _d; - if (node.kind === 208 /* FunctionExpression */) { + if (node.kind === 209 /* FunctionExpression */) { if (ts.isVariableDeclaration(node.parent) && ((_a = node.symbol.members) === null || _a === void 0 ? void 0 : _a.size)) { return true; } var symbol = checker.getSymbolOfExpando(node, /*allowDeclaration*/ false); return !!(symbol && (((_b = symbol.exports) === null || _b === void 0 ? void 0 : _b.size) || ((_c = symbol.members) === null || _c === void 0 ? void 0 : _c.size))); } - if (node.kind === 251 /* FunctionDeclaration */) { + if (node.kind === 252 /* FunctionDeclaration */) { return !!((_d = node.symbol.members) === null || _d === void 0 ? void 0 : _d.size); } return false; } + function canBeConvertedToAsync(node) { + switch (node.kind) { + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + return true; + default: + return false; + } + } + ts.canBeConvertedToAsync = canBeConvertedToAsync; })(ts || (ts = {})); /* @internal */ var ts; @@ -130630,7 +134922,7 @@ var ts; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32 /* Class */) { - return ts.getDeclarationOfKind(symbol, 221 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 222 /* ClassExpression */) ? "local class" /* localClassElement */ : "class" /* classElement */; } if (flags & 384 /* Enum */) @@ -130714,11 +135006,11 @@ var ts; // If we requested completions after `x.` at the top-level, we may be at a source file location. switch (location.parent && location.parent.kind) { // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. - case 275 /* JsxOpeningElement */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: return location.kind === 78 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return "JSX attribute" /* jsxAttribute */; default: return "property" /* memberVariableElement */; @@ -130764,6 +135056,7 @@ var ts; SymbolDisplay.getSymbolModifiers = getSymbolModifiers; // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) { + var _a; if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } var displayParts = []; var documentation = []; @@ -130787,8 +135080,8 @@ var ts; symbolKind = "property" /* memberVariableElement */; } var signature = void 0; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (location.parent && location.parent.kind === 201 /* PropertyAccessExpression */) { + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (location.parent && location.parent.kind === 202 /* PropertyAccessExpression */) { var right = location.parent.name; // Either the location is on the right of a property access, or on the left and the right is missing if (right === location || (right && right.getFullWidth() === 0)) { @@ -130808,9 +135101,9 @@ var ts; } if (callExpressionLike) { signature = typeChecker.getResolvedSignature(callExpressionLike); // TODO: GH#18217 - var useConstructSignatures = callExpressionLike.kind === 204 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 105 /* SuperKeyword */); + var useConstructSignatures = callExpressionLike.kind === 205 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 105 /* SuperKeyword */); var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); - if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { + if (signature && !ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { // Get the first signature if there is one -- allSignatures may contain // either the original signature or its target, so check for either signature = allSignatures.length ? allSignatures[0] : undefined; @@ -130872,7 +135165,7 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration - (location.kind === 132 /* ConstructorKeyword */ && location.parent.kind === 166 /* Constructor */)) { // At constructor keyword of constructor declaration + (location.kind === 132 /* ConstructorKeyword */ && location.parent.kind === 167 /* Constructor */)) { // At constructor keyword of constructor declaration // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; // Use function declaration to write the signatures only if the symbol corresponding to this declaration @@ -130880,24 +135173,26 @@ var ts; return declaration === (location.kind === 132 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { - var allSignatures = functionDeclaration_1.kind === 166 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration_1.kind === 167 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217 } else { signature = allSignatures[0]; } - if (functionDeclaration_1.kind === 166 /* Constructor */) { + if (functionDeclaration_1.kind === 167 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 169 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 170 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } - addSignatureDisplayParts(signature, allSignatures); + if (signature) { + addSignatureDisplayParts(signature, allSignatures); + } hasAddedSymbolInfo = true; hasMultipleSignatures = allSignatures.length > 1; } @@ -130905,7 +135200,7 @@ var ts; } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { addAliasPrefixIfNecessary(); - if (ts.getDeclarationOfKind(symbol, 221 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 222 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) // (local class) class @@ -130949,7 +135244,7 @@ var ts; } if (symbolFlags & 1536 /* Module */ && !isThisExpression) { prefixNextMeaning(); - var declaration = ts.getDeclarationOfKind(symbol, 256 /* ModuleDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 257 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 78 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 140 /* NamespaceKeyword */ : 139 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); @@ -130970,7 +135265,7 @@ var ts; } else { // Method/function type parameter - var decl = ts.getDeclarationOfKind(symbol, 159 /* TypeParameter */); + var decl = ts.getDeclarationOfKind(symbol, 160 /* TypeParameter */); if (decl === undefined) return ts.Debug.fail(); var declaration = decl.parent; @@ -130978,16 +135273,16 @@ var ts; if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217 - if (declaration.kind === 170 /* ConstructSignature */) { + if (declaration.kind === 171 /* ConstructSignature */) { displayParts.push(ts.keywordPart(102 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 169 /* CallSignature */ && declaration.name) { + else if (declaration.kind !== 170 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } - else if (declaration.kind === 254 /* TypeAliasDeclaration */) { + else if (declaration.kind === 255 /* TypeAliasDeclaration */) { // Type alias type parameter // For example // type list = T[]; // Both T will go through same code path @@ -131003,8 +135298,8 @@ var ts; if (symbolFlags & 8 /* EnumMember */) { symbolKind = "enum member" /* enumMemberElement */; addPrefixForAnyFunctionOrVar(symbol, "enum member"); - var declaration = symbol.declarations[0]; - if (declaration.kind === 291 /* EnumMember */) { + var declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]; + if ((declaration === null || declaration === void 0 ? void 0 : declaration.kind) === 292 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -131034,31 +135329,33 @@ var ts; } else { documentationFromAlias = resolvedSymbol.getContextualDocumentationComment(resolvedNode, typeChecker); - tagsFromAlias = resolvedSymbol.getJsDocTags(); + tagsFromAlias = resolvedSymbol.getJsDocTags(typeChecker); } } } - switch (symbol.declarations[0].kind) { - case 259 /* NamespaceExportDeclaration */: - displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(140 /* NamespaceKeyword */)); - break; - case 266 /* ExportAssignment */: - displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 62 /* EqualsToken */ : 87 /* DefaultKeyword */)); - break; - case 270 /* ExportSpecifier */: - displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); - break; - default: - displayParts.push(ts.keywordPart(99 /* ImportKeyword */)); + if (symbol.declarations) { + switch (symbol.declarations[0].kind) { + case 260 /* NamespaceExportDeclaration */: + displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(140 /* NamespaceKeyword */)); + break; + case 267 /* ExportAssignment */: + displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 62 /* EqualsToken */ : 87 /* DefaultKeyword */)); + break; + case 271 /* ExportSpecifier */: + displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); + break; + default: + displayParts.push(ts.keywordPart(99 /* ImportKeyword */)); + } } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 260 /* ImportEqualsDeclaration */) { + if (declaration.kind === 261 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); @@ -131145,10 +135442,10 @@ var ts; // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 297 /* SourceFile */; })) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 216 /* BinaryExpression */) { + if (symbol.parent && symbol.declarations && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 298 /* SourceFile */; })) { + for (var _i = 0, _b = symbol.declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (!declaration.parent || declaration.parent.kind !== 217 /* BinaryExpression */) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); @@ -131156,7 +135453,7 @@ var ts; continue; } documentation = rhsSymbol.getDocumentationComment(typeChecker); - tags = rhsSymbol.getJsDocTags(); + tags = rhsSymbol.getJsDocTags(typeChecker); if (documentation.length > 0) { break; } @@ -131164,7 +135461,7 @@ var ts; } } if (tags.length === 0 && !hasMultipleSignatures) { - tags = symbol.getJsDocTags(); + tags = symbol.getJsDocTags(typeChecker); } if (documentation.length === 0 && documentationFromAlias) { documentation = documentationFromAlias; @@ -131266,16 +135563,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 208 /* FunctionExpression */) { + if (declaration.kind === 209 /* FunctionExpression */) { return true; } - if (declaration.kind !== 249 /* VariableDeclaration */ && declaration.kind !== 251 /* FunctionDeclaration */) { + if (declaration.kind !== 250 /* VariableDeclaration */ && declaration.kind !== 252 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { // Reached source file or module block - if (parent.kind === 297 /* SourceFile */ || parent.kind === 257 /* ModuleBlock */) { + if (parent.kind === 298 /* SourceFile */ || parent.kind === 258 /* ModuleBlock */) { return false; } } @@ -131381,7 +135678,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_8 = function (opt) { + var _loop_9 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -131400,7 +135697,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_8(opt); + _loop_9(opt); } return options; } @@ -131576,10 +135873,10 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 280 /* JsxAttribute */: - case 275 /* JsxOpeningElement */: - case 276 /* JsxClosingElement */: - case 274 /* JsxSelfClosingElement */: + case 281 /* JsxAttribute */: + case 276 /* JsxOpeningElement */: + case 277 /* JsxClosingElement */: + case 275 /* JsxSelfClosingElement */: // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. return ts.isKeyword(node.kind) || node.kind === 78 /* Identifier */; } @@ -131587,14 +135884,7 @@ var ts; return false; } function shouldRescanJsxText(node) { - var isJSXText = ts.isJsxText(node); - if (isJSXText) { - var containingElement = ts.findAncestor(node.parent, function (p) { return ts.isJsxElement(p); }); - if (!containingElement) - return false; // should never happen - return !ts.isParenthesizedExpression(containingElement.parent); - } - return false; + return ts.isJsxText(node); } function shouldRescanSlashToken(container) { return container.kind === 13 /* RegularExpressionLiteral */; @@ -131691,7 +135981,7 @@ var ts; return scanner.scanJsxIdentifier(); case 5 /* RescanJsxText */: lastScanAction = 5 /* RescanJsxText */; - return scanner.reScanJsxToken(); + return scanner.reScanJsxToken(/* allowMultilineJsxText */ false); case 6 /* RescanJsxAttributeValue */: lastScanAction = 6 /* RescanJsxAttributeValue */; return scanner.reScanJsxAttributeValue(); @@ -131780,7 +136070,7 @@ var ts; (function (formatting) { function getAllRules() { var allTokens = []; - for (var token = 0 /* FirstToken */; token <= 156 /* LastToken */; token++) { + for (var token = 0 /* FirstToken */; token <= 157 /* LastToken */; token++) { if (token !== 1 /* EndOfFileToken */) { allTokens.push(token); } @@ -131795,9 +136085,9 @@ var ts; var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(__spreadArray(__spreadArray([], allTokens), [3 /* MultiLineCommentTrivia */])); var anyTokenIncludingEOF = tokenRangeFrom(__spreadArray(__spreadArray([], allTokens), [1 /* EndOfFileToken */])); - var keywords = tokenRangeFromRange(80 /* FirstKeyword */, 156 /* LastKeyword */); + var keywords = tokenRangeFromRange(80 /* FirstKeyword */, 157 /* LastKeyword */); var binaryOperators = tokenRangeFromRange(29 /* FirstBinaryOperator */, 77 /* LastBinaryOperator */); - var binaryKeywordOperators = [100 /* InKeyword */, 101 /* InstanceOfKeyword */, 156 /* OfKeyword */, 126 /* AsKeyword */, 137 /* IsKeyword */]; + var binaryKeywordOperators = [100 /* InKeyword */, 101 /* InstanceOfKeyword */, 157 /* OfKeyword */, 126 /* AsKeyword */, 137 /* IsKeyword */]; var unaryPrefixOperators = [45 /* PlusPlusToken */, 46 /* MinusMinusToken */, 54 /* TildeToken */, 53 /* ExclamationToken */]; var unaryPrefixExpressions = [ 8 /* NumericLiteral */, 9 /* BigIntLiteral */, 78 /* Identifier */, 20 /* OpenParenToken */, @@ -132108,51 +136398,51 @@ var ts; return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; } function isForContext(context) { - return context.contextNode.kind === 237 /* ForStatement */; + return context.contextNode.kind === 238 /* ForStatement */; } function isNotForContext(context) { return !isForContext(context); } function isBinaryOpContext(context) { switch (context.contextNode.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return context.contextNode.operatorToken.kind !== 27 /* CommaToken */; - case 217 /* ConditionalExpression */: - case 184 /* ConditionalType */: - case 224 /* AsExpression */: - case 270 /* ExportSpecifier */: - case 265 /* ImportSpecifier */: - case 172 /* TypePredicate */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 218 /* ConditionalExpression */: + case 185 /* ConditionalType */: + case 225 /* AsExpression */: + case 271 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 173 /* TypePredicate */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 198 /* BindingElement */: + case 199 /* BindingElement */: // equals in type X = ... // falls through - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: // equal in import a = module('a'); // falls through - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // equal in let a = 0 // falls through - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: // equal in p = 0 // falls through - case 160 /* Parameter */: - case 291 /* EnumMember */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 161 /* Parameter */: + case 292 /* EnumMember */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return context.currentTokenSpan.kind === 62 /* EqualsToken */ || context.nextTokenSpan.kind === 62 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: // "in" keyword in [P in keyof T]: T[P] // falls through - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return context.currentTokenSpan.kind === 100 /* InKeyword */ || context.nextTokenSpan.kind === 100 /* InKeyword */ || context.currentTokenSpan.kind === 62 /* EqualsToken */ || context.nextTokenSpan.kind === 62 /* EqualsToken */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 239 /* ForOfStatement */: - return context.currentTokenSpan.kind === 156 /* OfKeyword */ || context.nextTokenSpan.kind === 156 /* OfKeyword */; + case 240 /* ForOfStatement */: + return context.currentTokenSpan.kind === 157 /* OfKeyword */ || context.nextTokenSpan.kind === 157 /* OfKeyword */; } return false; } @@ -132164,22 +136454,22 @@ var ts; } function isTypeAnnotationContext(context) { var contextKind = context.contextNode.kind; - return contextKind === 163 /* PropertyDeclaration */ || - contextKind === 162 /* PropertySignature */ || - contextKind === 160 /* Parameter */ || - contextKind === 249 /* VariableDeclaration */ || + return contextKind === 164 /* PropertyDeclaration */ || + contextKind === 163 /* PropertySignature */ || + contextKind === 161 /* Parameter */ || + contextKind === 250 /* VariableDeclaration */ || ts.isFunctionLikeKind(contextKind); } function isConditionalOperatorContext(context) { - return context.contextNode.kind === 217 /* ConditionalExpression */ || - context.contextNode.kind === 184 /* ConditionalType */; + return context.contextNode.kind === 218 /* ConditionalExpression */ || + context.contextNode.kind === 185 /* ConditionalType */; } function isSameLineTokenOrBeforeBlockContext(context) { return context.TokensAreOnSameLine() || isBeforeBlockContext(context); } function isBraceWrappedContext(context) { - return context.contextNode.kind === 196 /* ObjectBindingPattern */ || - context.contextNode.kind === 190 /* MappedType */ || + return context.contextNode.kind === 197 /* ObjectBindingPattern */ || + context.contextNode.kind === 191 /* MappedType */ || isSingleLineBlockContext(context); } // This check is done before an open brace in a control construct, a function, or a typescript block declaration @@ -132205,34 +136495,34 @@ var ts; return true; } switch (node.kind) { - case 230 /* Block */: - case 258 /* CaseBlock */: - case 200 /* ObjectLiteralExpression */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 259 /* CaseBlock */: + case 201 /* ObjectLiteralExpression */: + case 258 /* ModuleBlock */: return true; } return false; } function isFunctionDeclContext(context) { switch (context.contextNode.kind) { - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: // case SyntaxKind.MemberFunctionDeclaration: // falls through - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // case SyntaxKind.MethodSignature: // falls through - case 169 /* CallSignature */: - case 208 /* FunctionExpression */: - case 166 /* Constructor */: - case 209 /* ArrowFunction */: + case 170 /* CallSignature */: + case 209 /* FunctionExpression */: + case 167 /* Constructor */: + case 210 /* ArrowFunction */: // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: // falls through - case 253 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one + case 254 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one return true; } return false; @@ -132241,40 +136531,40 @@ var ts; return !isFunctionDeclContext(context); } function isFunctionDeclarationOrFunctionExpressionContext(context) { - return context.contextNode.kind === 251 /* FunctionDeclaration */ || context.contextNode.kind === 208 /* FunctionExpression */; + return context.contextNode.kind === 252 /* FunctionDeclaration */ || context.contextNode.kind === 209 /* FunctionExpression */; } function isTypeScriptDeclWithBlockContext(context) { return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); } function nodeIsTypeScriptDeclWithBlockContext(node) { switch (node.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 177 /* TypeLiteral */: - case 256 /* ModuleDeclaration */: - case 267 /* ExportDeclaration */: - case 268 /* NamedExports */: - case 261 /* ImportDeclaration */: - case 264 /* NamedImports */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 178 /* TypeLiteral */: + case 257 /* ModuleDeclaration */: + case 268 /* ExportDeclaration */: + case 269 /* NamedExports */: + case 262 /* ImportDeclaration */: + case 265 /* NamedImports */: return true; } return false; } function isAfterCodeBlockContext(context) { switch (context.currentTokenParent.kind) { - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 287 /* CatchClause */: - case 257 /* ModuleBlock */: - case 244 /* SwitchStatement */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 288 /* CatchClause */: + case 258 /* ModuleBlock */: + case 245 /* SwitchStatement */: return true; - case 230 /* Block */: { + case 231 /* Block */: { var blockParent = context.currentTokenParent.parent; // In a codefix scenario, we can't rely on parents being set. So just always return true. - if (!blockParent || blockParent.kind !== 209 /* ArrowFunction */ && blockParent.kind !== 208 /* FunctionExpression */) { + if (!blockParent || blockParent.kind !== 210 /* ArrowFunction */ && blockParent.kind !== 209 /* FunctionExpression */) { return true; } } @@ -132283,32 +136573,32 @@ var ts; } function isControlDeclContext(context) { switch (context.contextNode.kind) { - case 234 /* IfStatement */: - case 244 /* SwitchStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 236 /* WhileStatement */: - case 247 /* TryStatement */: - case 235 /* DoStatement */: - case 243 /* WithStatement */: + case 235 /* IfStatement */: + case 245 /* SwitchStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 237 /* WhileStatement */: + case 248 /* TryStatement */: + case 236 /* DoStatement */: + case 244 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: // falls through - case 287 /* CatchClause */: + case 288 /* CatchClause */: return true; default: return false; } } function isObjectContext(context) { - return context.contextNode.kind === 200 /* ObjectLiteralExpression */; + return context.contextNode.kind === 201 /* ObjectLiteralExpression */; } function isFunctionCallContext(context) { - return context.contextNode.kind === 203 /* CallExpression */; + return context.contextNode.kind === 204 /* CallExpression */; } function isNewContext(context) { - return context.contextNode.kind === 204 /* NewExpression */; + return context.contextNode.kind === 205 /* NewExpression */; } function isFunctionCallOrNewContext(context) { return isFunctionCallContext(context) || isNewContext(context); @@ -132323,10 +136613,10 @@ var ts; return context.nextTokenSpan.kind !== 21 /* CloseParenToken */; } function isArrowFunctionContext(context) { - return context.contextNode.kind === 209 /* ArrowFunction */; + return context.contextNode.kind === 210 /* ArrowFunction */; } function isImportTypeContext(context) { - return context.contextNode.kind === 195 /* ImportType */; + return context.contextNode.kind === 196 /* ImportType */; } function isNonJsxSameLineTokenContext(context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 11 /* JsxText */; @@ -132335,19 +136625,19 @@ var ts; return context.contextNode.kind !== 11 /* JsxText */; } function isNonJsxElementOrFragmentContext(context) { - return context.contextNode.kind !== 273 /* JsxElement */ && context.contextNode.kind !== 277 /* JsxFragment */; + return context.contextNode.kind !== 274 /* JsxElement */ && context.contextNode.kind !== 278 /* JsxFragment */; } function isJsxExpressionContext(context) { - return context.contextNode.kind === 283 /* JsxExpression */ || context.contextNode.kind === 282 /* JsxSpreadAttribute */; + return context.contextNode.kind === 284 /* JsxExpression */ || context.contextNode.kind === 283 /* JsxSpreadAttribute */; } function isNextTokenParentJsxAttribute(context) { - return context.nextTokenParent.kind === 280 /* JsxAttribute */; + return context.nextTokenParent.kind === 281 /* JsxAttribute */; } function isJsxAttributeContext(context) { - return context.contextNode.kind === 280 /* JsxAttribute */; + return context.contextNode.kind === 281 /* JsxAttribute */; } function isJsxSelfClosingElementContext(context) { - return context.contextNode.kind === 274 /* JsxSelfClosingElement */; + return context.contextNode.kind === 275 /* JsxSelfClosingElement */; } function isNotBeforeBlockInFunctionDeclarationContext(context) { return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); @@ -132362,45 +136652,45 @@ var ts; while (ts.isExpressionNode(node)) { node = node.parent; } - return node.kind === 161 /* Decorator */; + return node.kind === 162 /* Decorator */; } function isStartOfVariableDeclarationList(context) { - return context.currentTokenParent.kind === 250 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 251 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; } function isNotFormatOnEnter(context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */; } function isModuleDeclContext(context) { - return context.contextNode.kind === 256 /* ModuleDeclaration */; + return context.contextNode.kind === 257 /* ModuleDeclaration */; } function isObjectTypeContext(context) { - return context.contextNode.kind === 177 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === 178 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; } function isConstructorSignatureContext(context) { - return context.contextNode.kind === 170 /* ConstructSignature */; + return context.contextNode.kind === 171 /* ConstructSignature */; } function isTypeArgumentOrParameterOrAssertion(token, parent) { if (token.kind !== 29 /* LessThanToken */ && token.kind !== 31 /* GreaterThanToken */) { return false; } switch (parent.kind) { - case 173 /* TypeReference */: - case 206 /* TypeAssertionExpression */: - case 254 /* TypeAliasDeclaration */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 223 /* ExpressionWithTypeArguments */: + case 174 /* TypeReference */: + case 207 /* TypeAssertionExpression */: + case 255 /* TypeAliasDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 224 /* ExpressionWithTypeArguments */: return true; default: return false; @@ -132411,28 +136701,28 @@ var ts; isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); } function isTypeAssertionContext(context) { - return context.contextNode.kind === 206 /* TypeAssertionExpression */; + return context.contextNode.kind === 207 /* TypeAssertionExpression */; } function isVoidOpContext(context) { - return context.currentTokenSpan.kind === 113 /* VoidKeyword */ && context.currentTokenParent.kind === 212 /* VoidExpression */; + return context.currentTokenSpan.kind === 113 /* VoidKeyword */ && context.currentTokenParent.kind === 213 /* VoidExpression */; } function isYieldOrYieldStarWithOperand(context) { - return context.contextNode.kind === 219 /* YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 220 /* YieldExpression */ && context.contextNode.expression !== undefined; } function isNonNullAssertionContext(context) { - return context.contextNode.kind === 225 /* NonNullExpression */; + return context.contextNode.kind === 226 /* NonNullExpression */; } function isNotStatementConditionContext(context) { return !isStatementConditionContext(context); } function isStatementConditionContext(context) { switch (context.contextNode.kind) { - case 234 /* IfStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 235 /* IfStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return true; default: return false; @@ -132457,12 +136747,12 @@ var ts; return nextTokenKind === 19 /* CloseBraceToken */ || nextTokenKind === 1 /* EndOfFileToken */; } - if (nextTokenKind === 229 /* SemicolonClassElement */ || + if (nextTokenKind === 230 /* SemicolonClassElement */ || nextTokenKind === 26 /* SemicolonToken */) { return false; } - if (context.contextNode.kind === 253 /* InterfaceDeclaration */ || - context.contextNode.kind === 254 /* TypeAliasDeclaration */) { + if (context.contextNode.kind === 254 /* InterfaceDeclaration */ || + context.contextNode.kind === 255 /* TypeAliasDeclaration */) { // Can’t remove semicolon after `foo`; it would parse as a method declaration: // // interface I { @@ -132476,9 +136766,9 @@ var ts; if (ts.isPropertyDeclaration(context.currentTokenParent)) { return !context.currentTokenParent.initializer; } - return context.currentTokenParent.kind !== 237 /* ForStatement */ - && context.currentTokenParent.kind !== 231 /* EmptyStatement */ - && context.currentTokenParent.kind !== 229 /* SemicolonClassElement */ + return context.currentTokenParent.kind !== 238 /* ForStatement */ + && context.currentTokenParent.kind !== 232 /* EmptyStatement */ + && context.currentTokenParent.kind !== 230 /* SemicolonClassElement */ && nextTokenKind !== 22 /* OpenBracketToken */ && nextTokenKind !== 20 /* OpenParenToken */ && nextTokenKind !== 39 /* PlusToken */ @@ -132486,7 +136776,7 @@ var ts; && nextTokenKind !== 43 /* SlashToken */ && nextTokenKind !== 13 /* RegularExpressionLiteral */ && nextTokenKind !== 27 /* CommaToken */ - && nextTokenKind !== 218 /* TemplateExpression */ + && nextTokenKind !== 219 /* TemplateExpression */ && nextTokenKind !== 15 /* TemplateHead */ && nextTokenKind !== 14 /* NoSubstitutionTemplateLiteral */ && nextTokenKind !== 24 /* DotToken */; @@ -132577,12 +136867,12 @@ var ts; return map; } function getRuleBucketIndex(row, column) { - ts.Debug.assert(row <= 156 /* LastKeyword */ && column <= 156 /* LastKeyword */, "Must compute formatting context from tokens"); + ts.Debug.assert(row <= 157 /* LastKeyword */ && column <= 157 /* LastKeyword */, "Must compute formatting context from tokens"); return (row * mapRowLength) + column; } var maskBitSize = 5; var mask = 31; // MaskBitSize bits - var mapRowLength = 156 /* LastToken */ + 1; + var mapRowLength = 157 /* LastToken */ + 1; var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["StopRulesSpecific"] = 0] = "StopRulesSpecific"; @@ -132770,17 +137060,17 @@ var ts; // i.e. parent is class declaration with the list of members and node is one of members. function isListElement(parent, node) { switch (parent.kind) { - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var body = parent.body; - return !!body && body.kind === 257 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); - case 297 /* SourceFile */: - case 230 /* Block */: - case 257 /* ModuleBlock */: + return !!body && body.kind === 258 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 298 /* SourceFile */: + case 231 /* Block */: + case 258 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -132934,14 +137224,17 @@ var ts; processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); } if (!formattingScanner.isOnToken()) { + var indentation = formatting.SmartIndenter.nodeWillIndentChild(options, enclosingNode, /*child*/ undefined, sourceFile, /*indentByDefault*/ false) + ? initialIndentation + options.indentSize + : initialIndentation; var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); - if (options.trimTrailingWhitespace !== false) { - trimTrailingWhitespacesForRemainingRange(); - } + indentTriviaItems(leadingTrivia, indentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); } } + if (options.trimTrailingWhitespace !== false) { + trimTrailingWhitespacesForRemainingRange(); + } return edits; // local functions /** Tries to compute the indentation for a list element. @@ -132988,10 +137281,9 @@ var ts; // - we need to get the indentation on last line and the delta of parent return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; } - else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; - } - else if (formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) { + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile) || + formatting.SmartIndenter.childIsUnindentedBranchOfConditionalExpression(parent, node, startLine, sourceFile) || + formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) { return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; } else { @@ -133007,19 +137299,19 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 252 /* ClassDeclaration */: return 83 /* ClassKeyword */; - case 253 /* InterfaceDeclaration */: return 117 /* InterfaceKeyword */; - case 251 /* FunctionDeclaration */: return 97 /* FunctionKeyword */; - case 255 /* EnumDeclaration */: return 255 /* EnumDeclaration */; - case 167 /* GetAccessor */: return 134 /* GetKeyword */; - case 168 /* SetAccessor */: return 146 /* SetKeyword */; - case 165 /* MethodDeclaration */: + case 253 /* ClassDeclaration */: return 83 /* ClassKeyword */; + case 254 /* InterfaceDeclaration */: return 117 /* InterfaceKeyword */; + case 252 /* FunctionDeclaration */: return 97 /* FunctionKeyword */; + case 256 /* EnumDeclaration */: return 256 /* EnumDeclaration */; + case 168 /* GetAccessor */: return 134 /* GetKeyword */; + case 169 /* SetAccessor */: return 146 /* SetKeyword */; + case 166 /* MethodDeclaration */: if (node.asteriskToken) { return 41 /* AsteriskToken */; } // falls through - case 163 /* PropertyDeclaration */: - case 160 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 161 /* Parameter */: var name = ts.getNameOfDeclaration(node); if (name) { return name.kind; @@ -133076,15 +137368,16 @@ var ts; case 43 /* SlashToken */: case 31 /* GreaterThanToken */: switch (container.kind) { - case 275 /* JsxOpeningElement */: - case 276 /* JsxClosingElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 277 /* JsxClosingElement */: + case 275 /* JsxSelfClosingElement */: + case 224 /* ExpressionWithTypeArguments */: return false; } break; case 22 /* OpenBracketToken */: case 23 /* CloseBracketToken */: - if (container.kind !== 190 /* MappedType */) { + if (container.kind !== 191 /* MappedType */) { return false; } break; @@ -133129,11 +137422,6 @@ var ts; if (tokenInfo.token.end > node.end) { break; } - if (node.kind === 11 /* JsxText */) { - // Intentation rules for jsx text are handled by `indentMultilineCommentOrJsxText` inside `processChildNode`; just fastforward past it here - formattingScanner.advance(); - continue; - } consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node); } if (!node.parent && formattingScanner.isOnEOF()) { @@ -133192,27 +137480,11 @@ var ts; return inheritedIndentation; } } - var effectiveParentStartLine = child.kind === 161 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 162 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); - if (child.kind === 11 /* JsxText */) { - var range = { pos: child.getStart(), end: child.getEnd() }; - if (range.pos !== range.end) { // don't indent zero-width jsx text - var siblings = parent.getChildren(sourceFile); - var currentIndex = ts.findIndex(siblings, function (arg) { return arg.pos === child.pos; }); - var previousNode = siblings[currentIndex - 1]; - if (previousNode) { - // The jsx text needs no indentation whatsoever if it ends on the same line the previous sibling ends on - if (sourceFile.getLineAndCharacterOfPosition(range.end).line !== sourceFile.getLineAndCharacterOfPosition(previousNode.end).line) { - // The first line is (already) "indented" if the text starts on the same line as the previous sibling element ends on - var firstLineIsIndented = sourceFile.getLineAndCharacterOfPosition(range.pos).line === sourceFile.getLineAndCharacterOfPosition(previousNode.end).line; - indentMultilineCommentOrJsxText(range, childIndentation.indentation, firstLineIsIndented, /*indentFinalLine*/ false, /*jsxStyle*/ true); - } - } - } - } childContextNode = node; - if (isFirstListItem && parent.kind === 199 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + if (isFirstListItem && parent.kind === 200 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -133336,7 +137608,7 @@ var ts; switch (triviaItem.kind) { case 3 /* MultiLineCommentTrivia */: if (triviaInRange) { - indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); + indentMultilineComment(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); } indentNextTokenOrTrivia = false; break; @@ -133453,7 +137725,7 @@ var ts; function indentationIsDifferent(indentationString, startLinePosition) { return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length); } - function indentMultilineCommentOrJsxText(commentRange, indentation, firstLineIsIndented, indentFinalLine, jsxTextStyleIndent) { + function indentMultilineComment(commentRange, indentation, firstLineIsIndented, indentFinalLine) { if (indentFinalLine === void 0) { indentFinalLine = true; } // split comment in lines var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; @@ -133491,13 +137763,6 @@ var ts; var nonWhitespaceCharacterAndColumn = i === 0 ? nonWhitespaceColumnInFirstPart : formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options); - if (jsxTextStyleIndent) { - // skip adding indentation to blank lines - if (ts.isLineBreak(sourceFile.text.charCodeAt(ts.getStartPositionOfLine(startLine, sourceFile)))) - continue; - // reset delta on every line - delta = indentation - nonWhitespaceCharacterAndColumn.column; - } var newIndentation = nonWhitespaceCharacterAndColumn.column + delta; if (newIndentation > 0) { var indentationString = getIndentationString(newIndentation, options); @@ -133652,12 +137917,12 @@ var ts; formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { - case 166 /* Constructor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 209 /* ArrowFunction */: + case 167 /* Constructor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 210 /* ArrowFunction */: if (node.typeParameters === list) { return 29 /* LessThanToken */; } @@ -133665,8 +137930,8 @@ var ts; return 20 /* OpenParenToken */; } break; - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: if (node.typeArguments === list) { return 29 /* LessThanToken */; } @@ -133674,12 +137939,12 @@ var ts; return 20 /* OpenParenToken */; } break; - case 173 /* TypeReference */: + case 174 /* TypeReference */: if (node.typeArguments === list) { return 29 /* LessThanToken */; } break; - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return 18 /* OpenBraceToken */; } return 0 /* Unknown */; @@ -133797,7 +138062,7 @@ var ts; if (options.indentStyle === ts.IndentStyle.Block) { return getBlockIndent(sourceFile, position, options); } - if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 216 /* BinaryExpression */) { + if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 217 /* BinaryExpression */) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { @@ -133880,6 +138145,7 @@ var ts; } SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) { + var _a; var parent = current.parent; // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if // * parent and child nodes start on the same line, or @@ -133895,7 +138161,25 @@ var ts; childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { // check if current node is a list item - if yes, take indentation from it - var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine); + var firstListChild = (_a = getContainingList(current, sourceFile)) === null || _a === void 0 ? void 0 : _a[0]; + // A list indents its children if the children begin on a later line than the list itself: + // + // f1( L0 - List start + // { L1 - First child start: indented, along with all other children + // prop: 0 + // }, + // { + // prop: 1 + // } + // ) + // + // f2({ L0 - List start and first child start: children are not indented. + // prop: 0 Object properties are indented only one level, because the list + // }, { itself contributes nothing. + // prop: 1 L3 - The indentation of the second object literal is best understood by + // }) looking at the relationship between the list and *first* list item. + var listIndentsChild = !!firstListChild && getStartLineAndCharacterForNode(firstListChild, sourceFile).line > containingListOrParentStart.line; + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, listIndentsChild); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } @@ -133951,7 +138235,7 @@ var ts; // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && - (parent.kind === 297 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 298 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -133999,7 +138283,7 @@ var ts; } SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 234 /* IfStatement */ && parent.elseStatement === child) { + if (parent.kind === 235 /* IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 90 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -134008,6 +138292,49 @@ var ts; return false; } SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement; + // A multiline conditional typically increases the indentation of its whenTrue and whenFalse children: + // + // condition + // ? whenTrue + // : whenFalse; + // + // However, that indentation does not apply if the subexpressions themselves span multiple lines, + // applying their own indentation: + // + // (() => { + // return complexCalculationForCondition(); + // })() ? { + // whenTrue: 'multiline object literal' + // } : ( + // whenFalse('multiline parenthesized expression') + // ); + // + // In these cases, we must discard the indentation increase that would otherwise be applied to the + // whenTrue and whenFalse children to avoid double-indenting their contents. To identify this scenario, + // we check for the whenTrue branch beginning on the line that the condition ends, and the whenFalse + // branch beginning on the line that the whenTrue branch ends. + function childIsUnindentedBranchOfConditionalExpression(parent, child, childStartLine, sourceFile) { + if (ts.isConditionalExpression(parent) && (child === parent.whenTrue || child === parent.whenFalse)) { + var conditionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, parent.condition.end).line; + if (child === parent.whenTrue) { + return childStartLine === conditionEndLine; + } + else { + // On the whenFalse side, we have to look at the whenTrue side, because if that one was + // indented, whenFalse must also be indented: + // + // const y = true + // ? 1 : ( L1: whenTrue indented because it's on a new line + // 0 L2: indented two stops, one because whenTrue was indented + // ); and one because of the parentheses spanning multiple lines + var trueStartLine = getStartLineAndCharacterForNode(parent.whenTrue, sourceFile).line; + var trueEndLine = ts.getLineAndCharacterOfPosition(sourceFile, parent.whenTrue.end).line; + return conditionEndLine === trueStartLine && trueEndLine === childStartLine; + } + } + return false; + } + SmartIndenter.childIsUnindentedBranchOfConditionalExpression = childIsUnindentedBranchOfConditionalExpression; function argumentStartsOnSameLineAsPreviousArgument(parent, child, childStartLine, sourceFile) { if (ts.isCallOrNewExpression(parent)) { if (!parent.arguments) @@ -134037,40 +138364,40 @@ var ts; } function getListByRange(start, end, node, sourceFile) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return getList(node.typeArguments); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return getList(node.properties); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return getList(node.elements); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return getList(node.members); - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 166 /* Constructor */: - case 175 /* ConstructorType */: - case 170 /* ConstructSignature */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 167 /* Constructor */: + case 176 /* ConstructorType */: + case 171 /* ConstructSignature */: return getList(node.typeParameters) || getList(node.parameters); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 330 /* JSDocTemplateTag */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 334 /* JSDocTemplateTag */: return getList(node.typeParameters); - case 204 /* NewExpression */: - case 203 /* CallExpression */: + case 205 /* NewExpression */: + case 204 /* CallExpression */: return getList(node.typeArguments) || getList(node.arguments); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return getList(node.declarations); - case 264 /* NamedImports */: - case 268 /* NamedExports */: + case 265 /* NamedImports */: + case 269 /* NamedExports */: return getList(node.elements); - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: return getList(node.elements); } function getList(list) { @@ -134093,7 +138420,7 @@ var ts; return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options); } function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) { - if (node.parent && node.parent.kind === 250 /* VariableDeclarationList */) { + if (node.parent && node.parent.kind === 251 /* VariableDeclarationList */) { // VariableDeclarationList has no wrapping tokens return -1 /* Unknown */; } @@ -134166,94 +138493,94 @@ var ts; function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { var childKind = child ? child.kind : 0 /* Unknown */; switch (parent.kind) { - case 233 /* ExpressionStatement */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 199 /* ArrayLiteralExpression */: - case 230 /* Block */: - case 257 /* ModuleBlock */: - case 200 /* ObjectLiteralExpression */: - case 177 /* TypeLiteral */: - case 190 /* MappedType */: - case 179 /* TupleType */: - case 258 /* CaseBlock */: - case 285 /* DefaultClause */: - case 284 /* CaseClause */: - case 207 /* ParenthesizedExpression */: - case 201 /* PropertyAccessExpression */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 232 /* VariableStatement */: - case 266 /* ExportAssignment */: - case 242 /* ReturnStatement */: - case 217 /* ConditionalExpression */: - case 197 /* ArrayBindingPattern */: - case 196 /* ObjectBindingPattern */: - case 275 /* JsxOpeningElement */: - case 278 /* JsxOpeningFragment */: - case 274 /* JsxSelfClosingElement */: - case 283 /* JsxExpression */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 160 /* Parameter */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 186 /* ParenthesizedType */: - case 205 /* TaggedTemplateExpression */: - case 213 /* AwaitExpression */: - case 268 /* NamedExports */: - case 264 /* NamedImports */: - case 270 /* ExportSpecifier */: - case 265 /* ImportSpecifier */: - case 163 /* PropertyDeclaration */: + case 234 /* ExpressionStatement */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 200 /* ArrayLiteralExpression */: + case 231 /* Block */: + case 258 /* ModuleBlock */: + case 201 /* ObjectLiteralExpression */: + case 178 /* TypeLiteral */: + case 191 /* MappedType */: + case 180 /* TupleType */: + case 259 /* CaseBlock */: + case 286 /* DefaultClause */: + case 285 /* CaseClause */: + case 208 /* ParenthesizedExpression */: + case 202 /* PropertyAccessExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 233 /* VariableStatement */: + case 267 /* ExportAssignment */: + case 243 /* ReturnStatement */: + case 218 /* ConditionalExpression */: + case 198 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 276 /* JsxOpeningElement */: + case 279 /* JsxOpeningFragment */: + case 275 /* JsxSelfClosingElement */: + case 284 /* JsxExpression */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 161 /* Parameter */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 187 /* ParenthesizedType */: + case 206 /* TaggedTemplateExpression */: + case 214 /* AwaitExpression */: + case 269 /* NamedExports */: + case 265 /* NamedImports */: + case 271 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 164 /* PropertyDeclaration */: return true; - case 249 /* VariableDeclaration */: - case 288 /* PropertyAssignment */: - case 216 /* BinaryExpression */: - if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 200 /* ObjectLiteralExpression */) { // TODO: GH#18217 + case 250 /* VariableDeclaration */: + case 289 /* PropertyAssignment */: + case 217 /* BinaryExpression */: + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 201 /* ObjectLiteralExpression */) { // TODO: GH#18217 return rangeIsOnOneLine(sourceFile, child); } - if (parent.kind !== 216 /* BinaryExpression */) { + if (parent.kind !== 217 /* BinaryExpression */) { return true; } break; - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 237 /* ForStatement */: - case 234 /* IfStatement */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - return childKind !== 230 /* Block */; - case 209 /* ArrowFunction */: - if (sourceFile && childKind === 207 /* ParenthesizedExpression */) { + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 238 /* ForStatement */: + case 235 /* IfStatement */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return childKind !== 231 /* Block */; + case 210 /* ArrowFunction */: + if (sourceFile && childKind === 208 /* ParenthesizedExpression */) { return rangeIsOnOneLine(sourceFile, child); } - return childKind !== 230 /* Block */; - case 267 /* ExportDeclaration */: - return childKind !== 268 /* NamedExports */; - case 261 /* ImportDeclaration */: - return childKind !== 262 /* ImportClause */ || - (!!child.namedBindings && child.namedBindings.kind !== 264 /* NamedImports */); - case 273 /* JsxElement */: - return childKind !== 276 /* JsxClosingElement */; - case 277 /* JsxFragment */: - return childKind !== 279 /* JsxClosingFragment */; - case 183 /* IntersectionType */: - case 182 /* UnionType */: - if (childKind === 177 /* TypeLiteral */ || childKind === 179 /* TupleType */) { + return childKind !== 231 /* Block */; + case 268 /* ExportDeclaration */: + return childKind !== 269 /* NamedExports */; + case 262 /* ImportDeclaration */: + return childKind !== 263 /* ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 265 /* NamedImports */); + case 274 /* JsxElement */: + return childKind !== 277 /* JsxClosingElement */; + case 278 /* JsxFragment */: + return childKind !== 280 /* JsxClosingFragment */; + case 184 /* IntersectionType */: + case 183 /* UnionType */: + if (childKind === 178 /* TypeLiteral */ || childKind === 180 /* TupleType */) { return false; } - // falls through + break; } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -134261,11 +138588,11 @@ var ts; SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; function isControlFlowEndingStatement(kind, parent) { switch (kind) { - case 242 /* ReturnStatement */: - case 246 /* ThrowStatement */: - case 240 /* ContinueStatement */: - case 241 /* BreakStatement */: - return parent.kind !== 230 /* Block */; + case 243 /* ReturnStatement */: + case 247 /* ThrowStatement */: + case 241 /* ContinueStatement */: + case 242 /* BreakStatement */: + return parent.kind !== 231 /* Block */; default: return false; } @@ -134373,7 +138700,9 @@ var ts; function getAdjustedRange(sourceFile, startNode, endNode, options) { return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) }; } - function getAdjustedStartPosition(sourceFile, node, options) { + function getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment) { + var _a, _b; + if (hasTrailingComment === void 0) { hasTrailingComment = false; } var leadingTriviaOption = options.leadingTriviaOption; if (leadingTriviaOption === LeadingTriviaOption.Exclude) { return node.getStart(sourceFile); @@ -134404,6 +138733,15 @@ var ts; // when b is deleted - we delete it return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start; } + // if node has a trailing comments, use comment end position as the text has already been included. + if (hasTrailingComment) { + // Check first for leading comments as if the node is the first import, we want to exclude the trivia; + // otherwise we get the trailing comments. + var comment = ((_a = ts.getLeadingCommentRanges(sourceFile.text, fullStart)) === null || _a === void 0 ? void 0 : _a[0]) || ((_b = ts.getTrailingCommentRanges(sourceFile.text, fullStart)) === null || _b === void 0 ? void 0 : _b[0]); + if (comment) { + return ts.skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + } + } // get start position of the line following the line that contains fullstart position // (but only if the fullstart isn't the very beginning of the file) var nextLineStart = fullStart > 0 ? 1 : 0; @@ -134412,6 +138750,35 @@ var ts; adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } + /** Return the end position of a multiline comment of it is on another line; otherwise returns `undefined`; */ + function getEndPositionOfMultilineTrailingComment(sourceFile, node, options) { + var end = node.end; + var trailingTriviaOption = options.trailingTriviaOption; + if (trailingTriviaOption === TrailingTriviaOption.Include) { + // If the trailing comment is a multiline comment that extends to the next lines, + // return the end of the comment and track it for the next nodes to adjust. + var comments = ts.getTrailingCommentRanges(sourceFile.text, end); + if (comments) { + var nodeEndLine = ts.getLineOfLocalPosition(sourceFile, node.end); + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + // Single line can break the loop as trivia will only be this line. + // Comments on subsequest lines are also ignored. + if (comment.kind === 2 /* SingleLineCommentTrivia */ || ts.getLineOfLocalPosition(sourceFile, comment.pos) > nodeEndLine) { + break; + } + // Get the end line of the comment and compare against the end line of the node. + // If the comment end line position and the multiline comment extends to multiple lines, + // then is safe to return the end position. + var commentEndLine = ts.getLineOfLocalPosition(sourceFile, comment.end); + if (commentEndLine > nodeEndLine) { + return ts.skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + } + } + } + } + return undefined; + } function getAdjustedEndPosition(sourceFile, node, options) { var _a; var end = node.end; @@ -134427,6 +138794,10 @@ var ts; } return end; } + var multilineEndPosition = getEndPositionOfMultilineTrailingComment(sourceFile, node, options); + if (multilineEndPosition) { + return multilineEndPosition; + } var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))) ? newEnd @@ -134436,14 +138807,7 @@ var ts; * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ function isSeparator(node, candidate) { - return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 200 /* ObjectLiteralExpression */)); - } - function spaces(count) { - var s = ""; - for (var i = 0; i < count; i++) { - s += " "; - } - return s; + return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 201 /* ObjectLiteralExpression */)); } function isThisTypeAnnotatable(containingFunction) { return ts.isFunctionExpression(containingFunction) || ts.isFunctionDeclaration(containingFunction); @@ -134489,6 +138853,17 @@ var ts; if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options)); }; + ChangeTracker.prototype.deleteNodes = function (sourceFile, nodes, options, hasTrailingComment) { + if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } + // When deleting multiple nodes we need to track if the end position is including multiline trailing comments. + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var pos = getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment); + var end = getAdjustedEndPosition(sourceFile, node, options); + this.deleteRange(sourceFile, { pos: pos, end: end }); + hasTrailingComment = !!getEndPositionOfMultilineTrailingComment(sourceFile, node, options); + } + }; ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); }; @@ -134531,6 +138906,10 @@ var ts; if (options === void 0) { options = useNonAdjustedPositions; } this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; + ChangeTracker.prototype.nodeHasTrailingComment = function (sourceFile, oldNode, configurableEnd) { + if (configurableEnd === void 0) { configurableEnd = useNonAdjustedPositions; } + return !!getEndPositionOfMultilineTrailingComment(sourceFile, oldNode, configurableEnd); + }; ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { var next = ts.findNextToken(node, node.parent, sourceFile); return next && next.kind === 27 /* CommaToken */ ? next : undefined; @@ -134635,7 +139014,7 @@ var ts; } } else { - endNode = (_a = (node.kind === 249 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken)) !== null && _a !== void 0 ? _a : node.name; + endNode = (_a = (node.kind === 250 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken)) !== null && _a !== void 0 ? _a : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); return true; @@ -134677,6 +139056,15 @@ var ts; this.insertNodeBefore(sourceFile, firstStatement, newStatement); } }; + ChangeTracker.prototype.insertNodeAtConstructorStartAfterSuperCall = function (sourceFile, ctr, newStatement) { + var superCallStatement = ts.find(ctr.body.statements, function (stmt) { return ts.isExpressionStatement(stmt) && ts.isSuperCall(stmt.expression); }); + if (!superCallStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, __spreadArray(__spreadArray([], ctr.body.statements), [newStatement])); + } + else { + this.insertNodeAfter(sourceFile, superCallStatement, newStatement); + } + }; ChangeTracker.prototype.insertNodeAtConstructorEnd = function (sourceFile, ctr, newStatement) { var lastStatement = ts.lastOrUndefined(ctr.body.statements); if (!lastStatement || !ctr.body.multiLine) { @@ -134792,18 +139180,18 @@ var ts; }; ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { switch (node.kind) { - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: case 10 /* StringLiteral */: case 78 /* Identifier */: return { prefix: ", " }; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return { suffix: "," + this.newLineCharacter }; case 92 /* ExportKeyword */: return { prefix: " " }; - case 160 /* Parameter */: + case 161 /* Parameter */: return {}; default: ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it @@ -134812,7 +139200,7 @@ var ts; }; ChangeTracker.prototype.insertName = function (sourceFile, node, name) { ts.Debug.assert(!node.name); - if (node.kind === 209 /* ArrowFunction */) { + if (node.kind === 210 /* ArrowFunction */) { var arrow = ts.findChildOfKind(node, 38 /* EqualsGreaterThanToken */, sourceFile); var lparen = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile); if (lparen) { @@ -134826,14 +139214,14 @@ var ts; // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)` this.replaceRange(sourceFile, arrow, ts.factory.createToken(21 /* CloseParenToken */)); } - if (node.body.kind !== 230 /* Block */) { + if (node.body.kind !== 231 /* Block */) { // `() => 0` => `function f() { return 0; }` this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.factory.createToken(18 /* OpenBraceToken */), ts.factory.createToken(104 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); this.insertNodesAt(sourceFile, node.body.end, [ts.factory.createToken(26 /* SemicolonToken */), ts.factory.createToken(19 /* CloseBraceToken */)], { joiner: " " }); } } else { - var pos = ts.findChildOfKind(node, node.kind === 208 /* FunctionExpression */ ? 97 /* FunctionKeyword */ : 83 /* ClassKeyword */, sourceFile).end; + var pos = ts.findChildOfKind(node, node.kind === 209 /* FunctionExpression */ ? 97 /* FunctionKeyword */ : 83 /* ClassKeyword */, sourceFile).end; this.insertNodeAt(sourceFile, pos, ts.factory.createIdentifier(name), { prefix: " " }); } }; @@ -134865,47 +139253,22 @@ var ts; // a, b, c // create change for adding 'e' after 'a' as // - find start of next element after a (it is b) - // - use this start as start and end position in final change - // - build text of change by formatting the text of node + separator + whitespace trivia of b + // - use next element start as start and end position in final change + // - build text of change by formatting the text of node + whitespace trivia of b // in multiline case it will work as // a, // b, // c, // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#') - // a,* - // ***insertedtext# + // a, + // insertedtext# // ###b, // c, - // find line and character of the next element - var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart())); - // find line and character of the token that precedes next element (usually it is separator) - var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end); - var prefix = void 0; - var startPos = void 0; - if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) { - // next element is located on the same line with separator: - // a,$$$$b - // ^ ^ - // | |-next element - // |-separator - // where $$$ is some leading trivia - // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces - // a, x,$$$$b - // ^ ^ ^ - // | | |-next element - // | |-new inserted node padded with spaces - // |-separator - startPos = nextToken.end; - prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character); - } - else { - // next element is located on different line that separator - // let insert position be the beginning of the line that contains next element - startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); - } + var nextNode = containingList[index + 1]; + var startPos = skipWhitespacesAndLineBreaks(sourceFile.text, nextNode.getFullStart()); // write separator and leading trivia of the next element as suffix - var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, startPos); + this.insertNodesAt(sourceFile, startPos, [newNode], { suffix: suffix }); } } else { @@ -134977,7 +139340,7 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.Set(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_9 = function (sourceFile, node) { + var _loop_10 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(sourceFile, node)); @@ -134990,7 +139353,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_9(sourceFile, node); + _loop_10(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -135049,14 +139412,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_10 = function (i) { + var _loop_11 = 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_10(i); + _loop_11(i); } var textChanges = ts.mapDefined(normalized, function (c) { var span = ts.createTextSpanFromRange(c.range); @@ -135170,11 +139533,12 @@ var ts; function createWriter(newLine) { var lastNonTriviaPosition = 0; var writer = ts.createTextWriter(newLine); - var onEmitNode = function (hint, node, printCallback) { + var onBeforeEmitNode = function (node) { if (node) { setPos(node, lastNonTriviaPosition); } - printCallback(hint, node); + }; + var onAfterEmitNode = function (node) { if (node) { setEnd(node, lastNonTriviaPosition); } @@ -135293,7 +139657,8 @@ var ts; lastNonTriviaPosition = 0; } return { - onEmitNode: onEmitNode, + onBeforeEmitNode: onBeforeEmitNode, + onAfterEmitNode: onAfterEmitNode, onBeforeEmitNodeArray: onBeforeEmitNodeArray, onAfterEmitNodeArray: onAfterEmitNodeArray, onBeforeEmitToken: onBeforeEmitToken, @@ -135408,14 +139773,14 @@ var ts; } textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment; function needSemicolonBetween(a, b) { - return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 158 /* ComputedPropertyName */ + return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 159 /* ComputedPropertyName */ || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[` } var deleteDeclaration; (function (deleteDeclaration_1) { function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) { switch (node.kind) { - case 160 /* Parameter */: { + case 161 /* Parameter */: { var oldFunction = node.parent; if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1 && @@ -135430,15 +139795,17 @@ var ts; } break; } - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isAnyImportSyntax); // For first import, leave header comment in place, otherwise only delete JSDoc comments - deleteNode(changes, sourceFile, node, { leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); + deleteNode(changes, sourceFile, node, { + leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine, + }); break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: var pattern = node.parent; - var preserveComma = pattern.kind === 197 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); + var preserveComma = pattern.kind === 198 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); if (preserveComma) { deleteNode(changes, sourceFile, node); } @@ -135446,13 +139813,13 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); break; - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); break; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: var namedImports = node.parent; if (namedImports.elements.length === 1) { deleteImportBinding(changes, sourceFile, namedImports); @@ -135461,7 +139828,7 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: deleteImportBinding(changes, sourceFile, node); break; case 26 /* SemicolonToken */: @@ -135470,12 +139837,16 @@ var ts; case 97 /* FunctionKeyword */: deleteNode(changes, sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.Exclude }); break; - case 252 /* ClassDeclaration */: - case 251 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: deleteNode(changes, sourceFile, node, { leadingTriviaOption: ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; default: - if (ts.isImportClause(node.parent) && node.parent.name === node) { + if (!node.parent) { + // a misbehaving client can reach here with the SourceFile node + deleteNode(changes, sourceFile, node); + } + else if (ts.isImportClause(node.parent) && node.parent.name === node) { deleteDefaultImport(changes, sourceFile, node.parent); } else if (ts.isCallExpression(node.parent) && ts.contains(node.parent.arguments, node)) { @@ -135518,13 +139889,13 @@ var ts; // Delete the entire import declaration // |import * as ns from './file'| // |import { a } from './file'| - var importDecl = ts.getAncestor(node, 261 /* ImportDeclaration */); + var importDecl = ts.getAncestor(node, 262 /* ImportDeclaration */); deleteNode(changes, sourceFile, importDecl); } } function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) { var parent = node.parent; - if (parent.kind === 287 /* CatchClause */) { + if (parent.kind === 288 /* CatchClause */) { // TODO: There's currently no unused diagnostic for this, could be a suggestion changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 20 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 21 /* CloseParenToken */, sourceFile)); return; @@ -135535,14 +139906,14 @@ var ts; } var gp = parent.parent; switch (gp.kind) { - case 239 /* ForOfStatement */: - case 238 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 239 /* ForInStatement */: changes.replaceNode(sourceFile, node, ts.factory.createObjectLiteralExpression()); break; - case 237 /* ForStatement */: + case 238 /* ForStatement */: deleteNode(changes, sourceFile, parent); break; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: deleteNode(changes, sourceFile, gp, { leadingTriviaOption: ts.hasJSDocNodes(gp) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; default: @@ -135598,6 +139969,10 @@ var ts; return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); } codefix.createCodeFixAction = createCodeFixAction; + function createCodeFixActionMaybeFixAll(fixName, changes, description, fixId, fixAllDescription, command) { + return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, fixAllDescription && diagnosticToString(fixAllDescription), command); + } + codefix.createCodeFixActionMaybeFixAll = createCodeFixActionMaybeFixAll; function createCodeFixActionWorker(fixName, description, changes, fixId, fixAllDescription, command) { return { fixName: fixName, description: description, changes: changes, fixId: fixId, fixAllDescription: fixAllDescription, commands: command ? [command] : undefined }; } @@ -135736,7 +140111,10 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code], + errorCodes: [ + ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + ], getCodeActions: function (context) { var sourceFile = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { @@ -135849,6 +140227,7 @@ var ts; ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1.code, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap.code, + ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined.code, ts.Diagnostics.Type_0_is_not_an_array_type.code, ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code, ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators.code, @@ -135947,14 +140326,14 @@ var ts; } var isCompleteFix = identifiers.isCompleteFix; var initializers; - var _loop_11 = function (identifier) { + var _loop_12 = function (identifier) { var symbol = checker.getSymbolAtLocation(identifier); if (!symbol) { return "continue"; } var declaration = ts.tryCast(symbol.valueDeclaration, ts.isVariableDeclaration); var variableName = declaration && ts.tryCast(declaration.name, ts.isIdentifier); - var variableStatement = ts.getAncestor(declaration, 232 /* VariableStatement */); + var variableStatement = ts.getAncestor(declaration, 233 /* VariableStatement */); if (!declaration || !variableStatement || declaration.type || !declaration.initializer || @@ -135980,7 +140359,7 @@ var ts; }; for (var _i = 0, _a = identifiers.identifiers; _i < _a.length; _i++) { var identifier = _a[_i]; - _loop_11(identifier); + _loop_12(identifier); } return initializers && { initializers: initializers, @@ -136032,10 +140411,10 @@ var ts; function isInsideAwaitableBody(node) { return node.kind & 32768 /* AwaitContext */ || !!ts.findAncestor(node, function (ancestor) { return ancestor.parent && ts.isArrowFunction(ancestor.parent) && ancestor.parent.body === ancestor || - ts.isBlock(ancestor) && (ancestor.parent.kind === 251 /* FunctionDeclaration */ || - ancestor.parent.kind === 208 /* FunctionExpression */ || - ancestor.parent.kind === 209 /* ArrowFunction */ || - ancestor.parent.kind === 165 /* MethodDeclaration */); + ts.isBlock(ancestor) && (ancestor.parent.kind === 252 /* FunctionDeclaration */ || + ancestor.parent.kind === 209 /* FunctionExpression */ || + ancestor.parent.kind === 210 /* ArrowFunction */ || + ancestor.parent.kind === 166 /* MethodDeclaration */); }); } function makeChange(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) { @@ -136154,10 +140533,10 @@ var ts; function isPossiblyPartOfDestructuring(node) { switch (node.kind) { case 78 /* Identifier */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return true; default: return false; @@ -136172,7 +140551,7 @@ var ts; function isPossiblyPartOfCommaSeperatedInitializer(node) { switch (node.kind) { case 78 /* Identifier */: - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: case 27 /* CommaToken */: return true; default: @@ -136221,7 +140600,7 @@ var ts; return; } var declaration = token.parent; - if (declaration.kind === 163 /* PropertyDeclaration */ && + if (declaration.kind === 164 /* PropertyDeclaration */ && (!fixedNodes || ts.tryAddToSet(fixedNodes, declaration))) { changeTracker.insertModifierBefore(sourceFile, 133 /* DeclareKeyword */, declaration); } @@ -136358,26 +140737,26 @@ var ts; } function isDeclarationWithType(node) { return ts.isFunctionLikeDeclaration(node) || - node.kind === 249 /* VariableDeclaration */ || - node.kind === 162 /* PropertySignature */ || - node.kind === 163 /* PropertyDeclaration */; + node.kind === 250 /* VariableDeclaration */ || + node.kind === 163 /* PropertySignature */ || + node.kind === 164 /* PropertyDeclaration */; } function transformJSDocType(node) { switch (node.kind) { - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: return ts.factory.createTypeReferenceNode("any", ts.emptyArray); - case 307 /* JSDocOptionalType */: + case 308 /* JSDocOptionalType */: return transformJSDocOptionalType(node); - case 306 /* JSDocNonNullableType */: + case 307 /* JSDocNonNullableType */: return transformJSDocType(node.type); - case 305 /* JSDocNullableType */: + case 306 /* JSDocNullableType */: return transformJSDocNullableType(node); - case 309 /* JSDocVariadicType */: + case 310 /* JSDocVariadicType */: return transformJSDocVariadicType(node); - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: return transformJSDocFunctionType(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return transformJSDocTypeReference(node); default: var visited = ts.visitEachChild(node, transformJSDocType, ts.nullTransformationContext); @@ -136402,7 +140781,7 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 309 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 + var isRest = node.type.kind === 310 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 var name = node.name || (isRest ? "rest" : "arg" + index); var dotdotdot = isRest ? ts.factory.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken; return ts.factory.createParameterDeclaration(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); @@ -136473,7 +140852,7 @@ var ts; }); function doChange(changes, sourceFile, position, checker, preferences, compilerOptions) { var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position)); - if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + if (!ctorSymbol || !ctorSymbol.valueDeclaration || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { // Bad input return undefined; } @@ -136500,7 +140879,7 @@ var ts; // all instance members are stored in the "member" array of symbol if (symbol.members) { symbol.members.forEach(function (member, key) { - if (key === "constructor") { + if (key === "constructor" && member.valueDeclaration) { // fn.prototype.constructor = fn changes.delete(sourceFile, member.valueDeclaration.parent); return; @@ -136514,7 +140893,7 @@ var ts; // all static members are stored in the "exports" array of symbol if (symbol.exports) { symbol.exports.forEach(function (member) { - if (member.name === "prototype") { + if (member.name === "prototype" && member.declarations) { var firstDeclaration = member.declarations[0]; // only one "x.prototype = { ... }" will pass if (member.declarations.length === 1 && @@ -136576,7 +140955,7 @@ var ts; return members; } // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end - var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 233 /* ExpressionStatement */ + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 234 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); if (!assignmentExpr) { @@ -136637,7 +141016,7 @@ var ts; var arrowFunctionBody = arrowFunction.body; var bodyBlock; // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 230 /* Block */) { + if (arrowFunctionBody.kind === 231 /* Block */) { bodyBlock = arrowFunctionBody; } // case 2: () => [1,2,3] @@ -136739,7 +141118,7 @@ var ts; functionToConvert = tokenAtPosition.parent.initializer; } else { - functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.canBeConvertedToAsync); } if (!functionToConvert) { return; @@ -136748,7 +141127,10 @@ var ts; var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap); - var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray; + if (!ts.returnsPromise(functionToConvertRenamed, checker)) { + return; + } + var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : ts.emptyArray; var transformer = { checker: checker, synthNamesMap: synthNamesMap, setOfExpressionsToReturn: setOfExpressionsToReturn, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; @@ -136758,7 +141140,7 @@ var ts; functionToConvert.getStart(sourceFile); var options = functionToConvert.modifiers ? { prefix: " " } : { suffix: " " }; changes.insertModifierAt(sourceFile, pos, 129 /* AsyncKeyword */, options); - var _loop_12 = function (returnStatement) { + var _loop_13 = function (returnStatement) { ts.forEachChild(returnStatement, function visit(node) { if (ts.isCallExpression(node)) { var newNodes = transformExpression(node, transformer); @@ -136771,13 +141153,13 @@ var ts; }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var returnStatement = returnStatements_1[_i]; - _loop_12(returnStatement); + _loop_13(returnStatement); } } - function getReturnStatementsWithPromiseHandlers(body) { + function getReturnStatementsWithPromiseHandlers(body, checker) { var res = []; ts.forEachReturnStatement(body, function (ret) { - if (ts.isReturnStatementWithFixablePromiseHandler(ret)) + if (ts.isReturnStatementWithFixablePromiseHandler(ret, checker)) res.push(ret); }); return res; @@ -136848,7 +141230,10 @@ var ts; // so we push an entry for 'response'. if (lastCallSignature && !ts.isParameter(node.parent) && !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.factory.createUniqueName("result", 16 /* Optimistic */); + var ident = (firstParameter === null || firstParameter === void 0 ? void 0 : firstParameter.valueDeclaration) + && ts.isParameter(firstParameter.valueDeclaration) + && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) + || ts.factory.createUniqueName("result", 16 /* Optimistic */); var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); collidingSymbolMap.add(ident.text, symbol); @@ -137026,6 +141411,7 @@ var ts; case 103 /* NullKeyword */: // do not produce a transformed statement for a null argument break; + case 202 /* PropertyAccessExpression */: case 78 /* Identifier */: // identifier includes undefined if (!argName) { // undefined was argument passed to promise handler @@ -137047,8 +141433,8 @@ var ts; prevArgName.types.push(returnType); } return varDeclOrAssignment; - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: { + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: { var funcBody = func.body; var returnType_1 = (_c = getLastCallSignature(transformer.checker.getTypeAtLocation(func), transformer.checker)) === null || _c === void 0 ? void 0 : _c.getReturnType(); // Arrow functions with block bodies { } will enter this control flow @@ -137059,7 +141445,7 @@ var ts; var statement = _f[_i]; if (ts.isReturnStatement(statement)) { seenReturnStatement = true; - if (ts.isReturnStatementWithFixablePromiseHandler(statement)) { + if (ts.isReturnStatementWithFixablePromiseHandler(statement, transformer.checker)) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } else { @@ -137076,7 +141462,7 @@ var ts; : removeReturns(refactoredStmts, prevArgName, transformer, seenReturnStatement); } else { - var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.factory.createReturnStatement(funcBody)] : ts.emptyArray; + var innerRetStmts = ts.isFixablePromiseHandler(funcBody, transformer.checker) ? [ts.factory.createReturnStatement(funcBody)] : ts.emptyArray; var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { return innerCbBody; @@ -137169,6 +141555,9 @@ var ts; else if (ts.isIdentifier(funcNode)) { name = getMapEntryOrDefault(funcNode); } + else if (ts.isPropertyAccessExpression(funcNode) && ts.isIdentifier(funcNode.name)) { + name = getMapEntryOrDefault(funcNode.name); + } // return undefined argName when arg is null or undefined // eslint-disable-next-line no-in-operator if (!name || "identifier" in name && name.identifier.text === "undefined") { @@ -137264,10 +141653,10 @@ var ts; } var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { changes.replaceNode(importingFile, importNode, ts.factory.createPropertyAccessExpression(ts.getSynthesizedDeepClone(importNode), "default")); } @@ -137334,20 +141723,20 @@ var ts; } function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, useSitesToUnqualify, quotePreference) { switch (statement.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); return false; - case 233 /* ExpressionStatement */: { + case 234 /* ExpressionStatement */: { var expression = statement.expression; switch (expression.kind) { - case 203 /* CallExpression */: { + case 204 /* CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); } return false; } - case 216 /* BinaryExpression */: { + case 217 /* BinaryExpression */: { var operatorToken = expression.operatorToken; return operatorToken.kind === 62 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports, useSitesToUnqualify); } @@ -137396,8 +141785,8 @@ var ts; /** Converts `const name = require("moduleSpecifier").propertyName` */ function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { switch (name.kind) { - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: { + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` var tmp = makeUniqueName(propertyName, identifiers); return convertedImports([ @@ -137448,16 +141837,16 @@ var ts; function tryChangeModuleExportsObject(object, useSitesToUnqualify) { var statements = ts.mapAllOrFail(object.properties, function (prop) { switch (prop.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. // falls through - case 289 /* ShorthandPropertyAssignment */: - case 290 /* SpreadAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 291 /* SpreadAssignment */: return undefined; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer, useSitesToUnqualify); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.factory.createToken(92 /* ExportKeyword */)], prop, useSitesToUnqualify); default: ts.Debug.assertNever(prop, "Convert to ES6 got invalid prop kind " + prop.kind); @@ -137521,7 +141910,7 @@ var ts; function convertExportsDotXEquals_replaceNode(name, exported, useSitesToUnqualify) { var modifiers = [ts.factory.createToken(92 /* ExportKeyword */)]; switch (exported.kind) { - case 208 /* FunctionExpression */: { + case 209 /* FunctionExpression */: { var expressionName = exported.name; if (expressionName && expressionName.text !== name) { // `exports.f = function g() {}` -> `export const f = function g() {}` @@ -137529,10 +141918,10 @@ var ts; } } // falls through - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: // `exports.f = function() {}` --> `export function f() {}` return functionExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: // `exports.C = class {}` --> `export class C {}` return classExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify); default: @@ -137552,7 +141941,7 @@ var ts; : ts.getSynthesizedDeepCloneWithReplacements(nodeOrNodes, /*includeTrivia*/ true, replaceNode); function replaceNode(original) { // We are replacing `mod.SomeExport` wih `SomeExport`, so we only need to look at PropertyAccessExpressions - if (original.kind === 201 /* PropertyAccessExpression */) { + if (original.kind === 202 /* PropertyAccessExpression */) { var replacement = useSitesToUnqualify.get(original); // Remove entry from `useSitesToUnqualify` so the refactor knows it's taken care of by the parent statement we're replacing useSitesToUnqualify.delete(original); @@ -137567,7 +141956,7 @@ var ts; */ function convertSingleImport(name, moduleSpecifier, checker, identifiers, target, quotePreference) { switch (name.kind) { - case 196 /* ObjectBindingPattern */: { + case 197 /* ObjectBindingPattern */: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) ? undefined @@ -137580,7 +141969,7 @@ var ts; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration - case 197 /* ArrayBindingPattern */: { + case 198 /* ArrayBindingPattern */: { /* import x from "x"; const [a, b, c] = x; @@ -137599,7 +141988,9 @@ var ts; } /** * Convert `import x = require("x").` - * Also converts uses like `x.y()` to `y()` and uses a named import. + * Also: + * - Convert `x.default()` to `x()` to handle ES6 default export + * - Converts uses like `x.y()` to `y()` and uses a named import. */ function convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference) { var nameSymbol = checker.getSymbolAtLocation(name); @@ -137616,14 +142007,21 @@ var ts; } var parent = use.parent; if (ts.isPropertyAccessExpression(parent)) { - var expression = parent.expression, propertyName = parent.name.text; - ts.Debug.assert(expression === use, "Didn't expect expression === use"); // Else shouldn't have been in `collectIdentifiers` - var idName = namedBindingsNames.get(propertyName); - if (idName === undefined) { - idName = makeUniqueName(propertyName, identifiers); - namedBindingsNames.set(propertyName, idName); + var propertyName = parent.name.text; + if (propertyName === "default") { + needDefaultImport = true; + var importDefaultName = use.getText(); + (useSitesToUnqualify !== null && useSitesToUnqualify !== void 0 ? useSitesToUnqualify : (useSitesToUnqualify = new ts.Map())).set(parent, ts.factory.createIdentifier(importDefaultName)); + } + else { + ts.Debug.assert(parent.expression === use, "Didn't expect expression === use"); // Else shouldn't have been in `collectIdentifiers` + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + (useSitesToUnqualify !== null && useSitesToUnqualify !== void 0 ? useSitesToUnqualify : (useSitesToUnqualify = new ts.Map())).set(parent, ts.factory.createIdentifier(idName)); } - (useSitesToUnqualify !== null && useSitesToUnqualify !== void 0 ? useSitesToUnqualify : (useSitesToUnqualify = new ts.Map())).set(parent, ts.factory.createIdentifier(idName)); } else { needDefaultImport = true; @@ -137664,11 +142062,11 @@ var ts; function isFreeIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return parent.name !== node; - case 198 /* BindingElement */: + case 199 /* BindingElement */: return parent.propertyName !== node; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: return parent.propertyName !== node; default: return true; @@ -138145,87 +142543,138 @@ var ts; ImportFixKind[ImportFixKind["AddToExisting"] = 2] = "AddToExisting"; ImportFixKind[ImportFixKind["AddNew"] = 3] = "AddNew"; })(ImportFixKind || (ImportFixKind = {})); - var ImportKind; - (function (ImportKind) { - ImportKind[ImportKind["Named"] = 0] = "Named"; - ImportKind[ImportKind["Default"] = 1] = "Default"; - ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; - ImportKind[ImportKind["CommonJS"] = 3] = "CommonJS"; - })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { var compilerOptions = program.getCompilerOptions(); var exportInfos = ts.pathIsBareSpecifier(ts.stripQuotes(moduleSymbol.name)) - ? [getSymbolExportInfoForSymbol(exportedSymbol, moduleSymbol, sourceFile, program, host)] + ? [getSymbolExportInfoForSymbol(exportedSymbol, moduleSymbol, program, host)] : getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, host, program, /*useAutoImportProvider*/ true); var useRequire = shouldUseRequire(sourceFile, program); var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && !ts.isSourceFileJS(sourceFile) && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences)).moduleSpecifier; var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences); - return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; + return { moduleSpecifier: fix.moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences) { ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol"); - // We sort the best codefixes first, so taking `first` is best. - return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences)); + return getBestFix(getImportFixes(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences), sourceFile, host); } function codeFixActionToCodeAction(_a) { var description = _a.description, changes = _a.changes, commands = _a.commands; return { description: description, changes: changes, commands: commands }; } - function getSymbolExportInfoForSymbol(symbol, moduleSymbol, importingFile, program, host) { + function getSymbolExportInfoForSymbol(symbol, moduleSymbol, program, host) { var _a, _b; var compilerOptions = program.getCompilerOptions(); - var mainProgramInfo = getInfoWithChecker(program.getTypeChecker()); + var mainProgramInfo = getInfoWithChecker(program.getTypeChecker(), /*isFromPackageJson*/ false); if (mainProgramInfo) { return mainProgramInfo; } var autoImportProvider = (_b = (_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getTypeChecker(); - return ts.Debug.checkDefined(autoImportProvider && getInfoWithChecker(autoImportProvider), "Could not find symbol in specified module for code actions"); - function getInfoWithChecker(checker) { - var defaultInfo = getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions); + return ts.Debug.checkDefined(autoImportProvider && getInfoWithChecker(autoImportProvider, /*isFromPackageJson*/ true), "Could not find symbol in specified module for code actions"); + function getInfoWithChecker(checker, isFromPackageJson) { + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); if (defaultInfo && ts.skipAlias(defaultInfo.symbol, checker) === symbol) { - return { moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker) }; + return { symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, exportKind: defaultInfo.exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker), isFromPackageJson: isFromPackageJson }; } var named = checker.tryGetMemberInModuleExportsAndProperties(symbol.name, moduleSymbol); if (named && ts.skipAlias(named, checker) === symbol) { - return { moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker) }; + return { symbol: named, moduleSymbol: moduleSymbol, exportKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker), isFromPackageJson: isFromPackageJson }; } } } function getAllReExportingModules(importingFile, exportedSymbol, exportingModuleSymbol, symbolName, host, program, useAutoImportProvider) { var result = []; var compilerOptions = program.getCompilerOptions(); - forEachExternalModuleToImportFrom(program, host, importingFile, /*filterByPackageJson*/ false, useAutoImportProvider, function (moduleSymbol, moduleFile, program) { + var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { + return ts.createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); + }); + forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, function (moduleSymbol, moduleFile, program, isFromPackageJson) { var checker = program.getTypeChecker(); // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(importingFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } - var defaultInfo = getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions); - if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { - result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + result.push({ symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, exportKind: defaultInfo.exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker), isFromPackageJson: isFromPackageJson }); } for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { - result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + result.push({ symbol: exported, moduleSymbol: moduleSymbol, exportKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker), isFromPackageJson: isFromPackageJson }); } } }); return result; + function isImportable(program, moduleFile, isFromPackageJson) { + var _a; + return !moduleFile || ts.isImportableFile(program, importingFile, moduleFile, /*packageJsonFilter*/ undefined, getModuleSpecifierResolutionHost(isFromPackageJson), (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host)); + } + } + function getModuleSpecifierForBestExportInfo(exportInfo, importingFile, program, host, preferences) { + return getBestFix(getNewImportFixes(program, importingFile, /*position*/ undefined, /*preferTypeOnlyImport*/ false, /*useRequire*/ false, exportInfo, host, preferences), importingFile, host); } + codefix.getModuleSpecifierForBestExportInfo = getModuleSpecifierForBestExportInfo; + function getSymbolToExportInfoMap(importingFile, host, program) { + var _a, _b, _c, _d, _e, _f, _g, _h; + var start = ts.timestamp(); + // Pulling the AutoImportProvider project will trigger its updateGraph if pending, + // which will invalidate the export map cache if things change, so pull it before + // checking the cache. + (_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host); + var cache = (_b = host.getExportMapCache) === null || _b === void 0 ? void 0 : _b.call(host); + if (cache) { + var cached = cache.get(importingFile.path, program.getTypeChecker(), (_c = host.getProjectVersion) === null || _c === void 0 ? void 0 : _c.call(host)); + if (cached) { + (_d = host.log) === null || _d === void 0 ? void 0 : _d.call(host, "getSymbolToExportInfoMap: cache hit"); + return cached; + } + else { + (_e = host.log) === null || _e === void 0 ? void 0 : _e.call(host, "getSymbolToExportInfoMap: cache miss or empty; calculating new results"); + } + } + var result = ts.createMultiMap(); + var compilerOptions = program.getCompilerOptions(); + var target = ts.getEmitScriptTarget(compilerOptions); + forEachExternalModuleToImportFrom(program, host, /*useAutoImportProvider*/ true, function (moduleSymbol, _moduleFile, program, isFromPackageJson) { + var checker = program.getTypeChecker(); + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo) { + var name = ts.getNameForExportedSymbol(ts.getLocalSymbolForExportDefault(defaultInfo.symbol) || defaultInfo.symbol, target); + result.add(key(name, defaultInfo.symbol, moduleSymbol, checker), { symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, exportKind: defaultInfo.exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker), isFromPackageJson: isFromPackageJson }); + } + var seenExports = new ts.Map(); + for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { + var exported = _a[_i]; + if (exported !== (defaultInfo === null || defaultInfo === void 0 ? void 0 : defaultInfo.symbol) && ts.addToSeen(seenExports, exported)) { + result.add(key(ts.getNameForExportedSymbol(exported, target), exported, moduleSymbol, checker), { symbol: exported, moduleSymbol: moduleSymbol, exportKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker), isFromPackageJson: isFromPackageJson }); + } + } + }); + if (cache) { + (_f = host.log) === null || _f === void 0 ? void 0 : _f.call(host, "getSymbolToExportInfoMap: caching results"); + cache.set(result, (_g = host.getProjectVersion) === null || _g === void 0 ? void 0 : _g.call(host)); + } + (_h = host.log) === null || _h === void 0 ? void 0 : _h.call(host, "getSymbolToExportInfoMap: done in " + (ts.timestamp() - start) + " ms"); + return result; + function key(name, alias, moduleSymbol, checker) { + var moduleName = ts.stripQuotes(moduleSymbol.name); + var moduleKey = ts.isExternalModuleNameRelative(moduleName) ? "/" : moduleName; + return name + "|" + ts.getSymbolId(ts.skipAlias(alias, checker)) + "|" + moduleKey; + } + } + codefix.getSymbolToExportInfoMap = getSymbolToExportInfoMap; function isTypeOnlySymbol(s, checker) { return !(ts.skipAlias(s, checker).flags & 111551 /* Value */); } function isTypeOnlyPosition(sourceFile, position) { return ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); } - function getFixForImport(exportInfos, symbolName, + function getImportFixes(exportInfos, symbolName, /** undefined only for missing JSX namespace */ position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); - var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); + var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile, program.getCompilerOptions()); }); var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); var addToExisting = tryAddToExistingImport(existingImports, position !== undefined && isTypeOnlyPosition(sourceFile, position)); // Don't bother providing an action to add a new import if we can add to an existing one. @@ -138248,10 +142697,11 @@ var ts; return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration; var namespacePrefix = getNamespaceLikeImportText(declaration); - if (namespacePrefix) { + var moduleSpecifier = ts.tryGetModuleSpecifierFromDeclaration(declaration); + if (namespacePrefix && moduleSpecifier) { var moduleSymbol = getTargetModuleFromNamespaceLikeImport(declaration, checker); if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { - return { kind: 0 /* UseNamespace */, namespacePrefix: namespacePrefix, position: position }; + return { kind: 0 /* UseNamespace */, namespacePrefix: namespacePrefix, position: position, moduleSpecifier: moduleSpecifier }; } } }); @@ -138259,11 +142709,11 @@ var ts; function getTargetModuleFromNamespaceLikeImport(declaration, checker) { var _a; switch (declaration.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return checker.resolveExternalModuleName(declaration.initializer.arguments[0]); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return checker.getAliasedSymbol(declaration.symbol); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: var namespaceImport = ts.tryCast((_a = declaration.importClause) === null || _a === void 0 ? void 0 : _a.namedBindings, ts.isNamespaceImport); return namespaceImport && checker.getAliasedSymbol(namespaceImport.symbol); default: @@ -138273,11 +142723,11 @@ var ts; function getNamespaceLikeImportText(declaration) { var _a, _b, _c; switch (declaration.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return (_a = ts.tryCast(declaration.name, ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return declaration.name.text; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return (_c = ts.tryCast((_b = declaration.importClause) === null || _b === void 0 ? void 0 : _b.namedBindings, ts.isNamespaceImport)) === null || _c === void 0 ? void 0 : _c.name.text; default: return ts.Debug.assertNever(declaration); @@ -138286,31 +142736,38 @@ var ts; function tryAddToExistingImport(existingImports, canUseTypeOnlyImport) { return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind === 260 /* ImportEqualsDeclaration */) + if (declaration.kind === 261 /* ImportEqualsDeclaration */) return undefined; - if (declaration.kind === 249 /* VariableDeclaration */) { - return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 196 /* ObjectBindingPattern */ + if (declaration.kind === 250 /* VariableDeclaration */) { + return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 197 /* ObjectBindingPattern */ ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: declaration.name, importKind: importKind, moduleSpecifier: declaration.initializer.arguments[0].text, canUseTypeOnlyImport: false } : undefined; } var importClause = declaration.importClause; - if (!importClause) + if (!importClause || !ts.isStringLiteralLike(declaration.moduleSpecifier)) return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; - return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 264 /* NamedImports */) - ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.getText(), canUseTypeOnlyImport: canUseTypeOnlyImport } + // A type-only import may not have both a default and named imports, so the only way a name can + // be added to an existing type-only import is adding a named import to existing named bindings. + if (importClause.isTypeOnly && !(importKind === 0 /* Named */ && namedBindings)) + return undefined; + return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 265 /* NamedImports */) + ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.text, canUseTypeOnlyImport: canUseTypeOnlyImport } : undefined; }); } - function getExistingImportDeclarations(_a, checker, sourceFile) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + function getExistingImportDeclarations(_a, checker, importingFile, compilerOptions) { + var moduleSymbol = _a.moduleSymbol, exportKind = _a.exportKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + if (exportedSymbolIsTypeOnly && ts.isSourceFileJS(importingFile)) + return ts.emptyArray; + var importKind = getImportKind(importingFile, exportKind, compilerOptions); + return ts.mapDefined(importingFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); - if (ts.isRequireVariableDeclaration(i.parent, /*requireStringLiteralLikeArgument*/ true)) { + if (ts.isRequireVariableDeclaration(i.parent)) { return checker.resolveExternalModuleName(moduleSpecifier) === moduleSymbol ? { declaration: i.parent, importKind: importKind } : undefined; } - if (i.kind === 261 /* ImportDeclaration */ || i.kind === 260 /* ImportEqualsDeclaration */) { + if (i.kind === 262 /* ImportDeclaration */ || i.kind === 261 /* ImportEqualsDeclaration */) { return checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; } }); @@ -138343,45 +142800,29 @@ var ts; // 5. Literally nothing to go on return true; } - function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) { + function getNewImportFixes(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) { var isJs = ts.isSourceFileJS(sourceFile); var compilerOptions = program.getCompilerOptions(); - var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; - var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getTypeChecker(), compilerOptions, sourceFile, ts.createModuleSpecifierResolutionHost(program, host), preferences) + var moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); + return ts.flatMap(moduleSymbols, function (exportInfo) { + return ts.moduleSpecifiers.getModuleSpecifiers(exportInfo.moduleSymbol, program.getTypeChecker(), compilerOptions, sourceFile, moduleSpecifierResolutionHost, preferences) .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.checkDefined(position, "position should be defined") } - : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, useRequire: useRequire, typeOnly: preferTypeOnlyImport }; + return exportInfo.exportedSymbolIsTypeOnly && isJs && position !== undefined + ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: position, exportInfo: exportInfo } + : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: getImportKind(sourceFile, exportInfo.exportKind, compilerOptions), useRequire: useRequire, typeOnly: preferTypeOnlyImport, exportInfo: exportInfo }; }); }); - // Sort by presence in package.json, then shortest paths first - return ts.sort(choicesForEachExportingModule, function (a, b) { - var allowsImportingA = allowsImportingSpecifier(a.moduleSpecifier); - var allowsImportingB = allowsImportingSpecifier(b.moduleSpecifier); - if (allowsImportingA && !allowsImportingB) { - return -1; - } - if (allowsImportingB && !allowsImportingA) { - return 1; - } - return a.moduleSpecifier.length - b.moduleSpecifier.length; - }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport, useRequire); }); - return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences); + return existingDeclaration ? [existingDeclaration] : getNewImportFixes(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences); } function newImportInfoFromExistingSpecifier(_a, preferTypeOnlyImport, useRequire) { var declaration = _a.declaration, importKind = _a.importKind; - var moduleSpecifier = declaration.kind === 261 /* ImportDeclaration */ ? declaration.moduleSpecifier : - declaration.kind === 249 /* VariableDeclaration */ ? declaration.initializer.arguments[0] : - declaration.moduleReference.kind === 272 /* ExternalModuleReference */ ? declaration.moduleReference.expression : - undefined; - return moduleSpecifier && ts.isStringLiteral(moduleSpecifier) - ? { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier.text, importKind: importKind, typeOnly: preferTypeOnlyImport, useRequire: useRequire } + var moduleSpecifier = ts.tryGetModuleSpecifierFromDeclaration(declaration); + return moduleSpecifier + ? { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, typeOnly: preferTypeOnlyImport, useRequire: useRequire } : undefined; } function getFixesInfo(context, errorCode, pos, useAutoImportProvider) { @@ -138389,7 +142830,28 @@ var ts; var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ? getFixesInfoForUMDImport(context, symbolToken) : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider) : undefined; - return info && __assign(__assign({}, info), { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) }); + return info && __assign(__assign({}, info), { fixes: sortFixes(info.fixes, context.sourceFile, context.host) }); + } + function sortFixes(fixes, sourceFile, host) { + var allowsImportingSpecifier = ts.createPackageJsonImportFilter(sourceFile, host).allowsImportingSpecifier; + return ts.sort(fixes, function (a, b) { return ts.compareValues(a.kind, b.kind) || compareModuleSpecifiers(a, b, allowsImportingSpecifier); }); + } + function getBestFix(fixes, sourceFile, host) { + // These will always be placed first if available, and are better than other kinds + if (fixes[0].kind === 0 /* UseNamespace */ || fixes[0].kind === 2 /* AddToExisting */) { + return fixes[0]; + } + var allowsImportingSpecifier = ts.createPackageJsonImportFilter(sourceFile, host).allowsImportingSpecifier; + return fixes.reduce(function (best, fix) { + return compareModuleSpecifiers(fix, best, allowsImportingSpecifier) === -1 /* LessThan */ ? fix : best; + }); + } + function compareModuleSpecifiers(a, b, allowsImportingSpecifier) { + if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) { + return ts.compareBooleans(allowsImportingSpecifier(a.moduleSpecifier), allowsImportingSpecifier(b.moduleSpecifier)) + || ts.compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); + } + return 0 /* EqualTo */; } function getFixesInfoForUMDImport(_a, token) { var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences; @@ -138399,9 +142861,9 @@ var ts; return undefined; var symbol = checker.getAliasedSymbol(umdSymbol); var symbolName = umdSymbol.name; - var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(sourceFile, program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; + var exportInfos = [{ symbol: umdSymbol, moduleSymbol: symbol, exportKind: 3 /* UMD */, exportedSymbolIsTypeOnly: false, isFromPackageJson: false }]; var useRequire = shouldUseRequire(sourceFile, program); - var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, useRequire, program, sourceFile, host, preferences); + var fixes = getImportFixes(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, useRequire, program, sourceFile, host, preferences); return { fixes: fixes, symbolName: symbolName }; } function getUmdSymbol(token, checker) { @@ -138415,6 +142877,16 @@ var ts; ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 111551 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } + function getImportKind(importingFile, exportKind, compilerOptions) { + switch (exportKind) { + case 0 /* Named */: return 0 /* Named */; + case 1 /* Default */: return 1 /* Default */; + case 2 /* ExportEquals */: return getExportEqualsImportKind(importingFile, compilerOptions); + case 3 /* UMD */: return getUmdImportKind(importingFile, compilerOptions); + default: return ts.Debug.assertNever(exportKind); + } + } + codefix.getImportKind = getImportKind; function getUmdImportKind(importingFile, compilerOptions) { // Import a synthetic `default` if enabled. if (ts.getAllowSyntheticDefaultImports(compilerOptions)) { @@ -138444,22 +142916,22 @@ var ts; function getFixesInfoForNonUMDImport(_a, symbolToken, useAutoImportProvider) { var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences; var checker = program.getTypeChecker(); - var symbolName = getSymbolName(sourceFile, checker, symbolToken); + var compilerOptions = program.getCompilerOptions(); + var symbolName = getSymbolName(sourceFile, checker, symbolToken, compilerOptions); // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default" /* Default */, "'default' isn't a legal identifier and couldn't occur here"); - var compilerOptions = program.getCompilerOptions(); var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(symbolToken); var useRequire = shouldUseRequire(sourceFile, program); var exportInfos = getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host); var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfos.entries(), function (_a) { var _ = _a[0], exportInfos = _a[1]; - return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences); + return getImportFixes(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences); })); return { fixes: fixes, symbolName: symbolName }; } - function getSymbolName(sourceFile, checker, symbolToken) { + function getSymbolName(sourceFile, checker, symbolToken, compilerOptions) { var parent = symbolToken.parent; - if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken) { + if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken && compilerOptions.jsx !== 4 /* ReactJSX */ && compilerOptions.jsx !== 5 /* ReactJSXDev */) { var jsxNamespace = checker.getJsxNamespace(sourceFile); if (ts.isIntrinsicJsxName(symbolToken.text) || !checker.resolveName(jsxNamespace, parent, 111551 /* Value */, /*excludeGlobals*/ true)) { return jsxNamespace; @@ -138468,43 +142940,55 @@ var ts; return symbolToken.text; } // Returns a map from an exported symbol's ID to a list of every way it's (re-)exported. - function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, program, useAutoImportProvider, host) { + function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, fromFile, program, useAutoImportProvider, host) { + var _a; // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); - function addSymbol(moduleSymbol, exportedSymbol, importKind, checker) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); + var packageJsonFilter = ts.createPackageJsonImportFilter(fromFile, host); + var moduleSpecifierCache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); + var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { + return ts.createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); + }); + function addSymbol(moduleSymbol, toFile, exportedSymbol, exportKind, program, isFromPackageJson) { + var moduleSpecifierResolutionHost = getModuleSpecifierResolutionHost(isFromPackageJson); + if (toFile && ts.isImportableFile(program, fromFile, toFile, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) || + !toFile && packageJsonFilter.allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost)) { + var checker = program.getTypeChecker(); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { symbol: exportedSymbol, moduleSymbol: moduleSymbol, exportKind: exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker), isFromPackageJson: isFromPackageJson }); + } } - forEachExternalModuleToImportFrom(program, host, sourceFile, /*filterByPackageJson*/ true, useAutoImportProvider, function (moduleSymbol, _, program) { + forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, function (moduleSymbol, sourceFile, program, isFromPackageJson) { var checker = program.getTypeChecker(); cancellationToken.throwIfCancellationRequested(); var compilerOptions = program.getCompilerOptions(); - var defaultInfo = getDefaultLikeExportInfo(sourceFile, moduleSymbol, checker, compilerOptions); + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind, checker); + addSymbol(moduleSymbol, sourceFile, defaultInfo.symbol, defaultInfo.exportKind, program, isFromPackageJson); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */, checker); + addSymbol(moduleSymbol, sourceFile, exportSymbolWithIdenticalName, 0 /* Named */, program, isFromPackageJson); } }); return originalSymbolToExportInfos; } - function getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions) { - var exported = getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions); + 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); + var symbol = exported.symbol, exportKind = exported.exportKind; + var info = getDefaultExportInfoWorker(symbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, exportKind: exportKind }, info); } - function getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions) { + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) + return { symbol: exportEquals, exportKind: 2 /* ExportEquals */ }; 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: getExportEqualsImportKind(importingFile, compilerOptions) }; + return { symbol: defaultExport, exportKind: 1 /* Default */ }; } function getExportEqualsImportKind(importingFile, compilerOptions) { var allowSyntheticDefaults = ts.getAllowSyntheticDefaultImports(compilerOptions); @@ -138523,7 +143007,8 @@ var ts; // on how to handle it. for (var _i = 0, _a = importingFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - if (ts.isImportEqualsDeclaration(statement)) { + // `import foo` parses as an ImportEqualsDeclaration even though it could be an ImportDeclaration + if (ts.isImportEqualsDeclaration(statement) && !ts.nodeIsMissing(statement.moduleReference)) { return 3 /* CommonJS */; } } @@ -138531,7 +143016,7 @@ var ts; // allowSyntheticDefaultImports/esModuleInterop is enabled. return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */; } - function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { + function getDefaultExportInfoWorker(defaultExport, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -138545,21 +143030,20 @@ var ts; // but we can still offer completions for it. // - `aliased.parent` will be undefined if the module is exporting `globalThis.something`, // or another expression that resolves to a global. - return getDefaultExportInfoWorker(aliased, aliased.parent, checker, compilerOptions); + return getDefaultExportInfoWorker(aliased, checker, compilerOptions); } } if (defaultExport.escapedName !== "default" /* Default */ && defaultExport.escapedName !== "export=" /* ExportEquals */) { return { symbolForMeaning: defaultExport, name: defaultExport.getName() }; } - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; + return { symbolForMeaning: defaultExport, name: ts.getNameForExportedSymbol(defaultExport, compilerOptions.target) }; } function getNameForExportDefault(symbol) { return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { + var _a; if (ts.isExportAssignment(declaration)) { - if (ts.isIdentifier(declaration.expression)) { - return declaration.expression.text; - } + return (_a = ts.tryCast(ts.skipOuterExpressions(declaration.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text; } else if (ts.isExportSpecifier(declaration)) { ts.Debug.assert(declaration.name.text === "default" /* Default */, "Expected the specifier to be a default export"); @@ -138602,7 +143086,7 @@ var ts; } } function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, canUseTypeOnlyImport) { - if (clause.kind === 196 /* ObjectBindingPattern */) { + if (clause.kind === 197 /* ObjectBindingPattern */) { if (defaultImport) { addElementToBindingPattern(clause, defaultImport, "default"); } @@ -138729,48 +143213,23 @@ var ts; var declarations = _a.declarations; return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); } - function forEachExternalModuleToImportFrom(program, host, from, filterByPackageJson, useAutoImportProvider, cb) { + function forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, cb) { var _a, _b; - forEachExternalModuleToImportFromInProgram(program, host, from, filterByPackageJson, function (module, file) { return cb(module, file, program, /*isFromPackageJson*/ false); }); + forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), function (module, file) { return cb(module, file, program, /*isFromPackageJson*/ false); }); var autoImportProvider = useAutoImportProvider && ((_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host)); if (autoImportProvider) { var start = ts.timestamp(); - forEachExternalModuleToImportFromInProgram(autoImportProvider, host, from, filterByPackageJson, function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); + forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); (_b = host.log) === null || _b === void 0 ? void 0 : _b.call(host, "forEachExternalModuleToImportFrom autoImportProvider: " + (ts.timestamp() - start)); } } codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; - function forEachExternalModuleToImportFromInProgram(program, host, from, filterByPackageJson, cb) { - var _a; - var filteredCount = 0; - var moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); - var packageJson = filterByPackageJson && createAutoImportFilter(from, program, host, moduleSpecifierResolutionHost); - forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), function (module, sourceFile) { - if (sourceFile === undefined) { - if (!packageJson || packageJson.allowsImportingAmbientModule(module)) { - cb(module, sourceFile); - } - else if (packageJson) { - filteredCount++; - } - } - else if (sourceFile && - sourceFile !== from && - isImportableFile(program, from, sourceFile, moduleSpecifierResolutionHost)) { - if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile)) { - cb(module, sourceFile); - } - else if (packageJson) { - filteredCount++; - } - } - }); - (_a = host.log) === null || _a === void 0 ? void 0 : _a.call(host, "forEachExternalModuleToImportFrom: filtered out " + filteredCount + " modules by package.json contents"); - } function forEachExternalModule(checker, allSourceFiles, cb) { for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { var ambient = _a[_i]; - cb(ambient, /*sourceFile*/ undefined); + if (!ts.stringContains(ambient.name, "*")) { + cb(ambient, /*sourceFile*/ undefined); + } } for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { var sourceFile = allSourceFiles_1[_b]; @@ -138779,31 +143238,6 @@ var ts; } } } - function isImportableFile(program, from, to, moduleSpecifierResolutionHost) { - var _a; - var getCanonicalFileName = ts.hostGetCanonicalFileName(moduleSpecifierResolutionHost); - var globalTypingsCache = (_a = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation) === null || _a === void 0 ? void 0 : _a.call(moduleSpecifierResolutionHost); - return !!ts.moduleSpecifiers.forEachFileNameOfModule(from.fileName, to.fileName, moduleSpecifierResolutionHost, - /*preferSymlinks*/ false, function (toPath) { - var toFile = program.getSourceFile(toPath); - // Determine to import using toPath only if toPath is what we were looking at - // or there doesnt exist the file in the program by the symlink - return (toFile === to || !toFile) && - isImportablePath(from.fileName, toPath, getCanonicalFileName, globalTypingsCache); - }); - } - /** - * Don't include something from a `node_modules` that isn't actually reachable by a global import. - * A relative import to node_modules is usually a bad idea. - */ - function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) { - // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. - var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); - var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules)); - return toNodeModulesParent === undefined - || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) - || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); - } function moduleSymbolToValidIdentifier(moduleSymbol, target) { return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); } @@ -138835,99 +143269,122 @@ var ts; return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; } codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; - function createAutoImportFilter(fromFile, program, host, moduleSpecifierResolutionHost) { - if (moduleSpecifierResolutionHost === void 0) { moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); } - var packageJsons = ((host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName)) || ts.getPackageJsonsVisibleToFile(fromFile.fileName, host)).filter(function (p) { return p.parseable; }); - var usesNodeCoreModules; - return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier, moduleSpecifierResolutionHost: moduleSpecifierResolutionHost }; - function moduleSpecifierIsCoveredByPackageJson(specifier) { - var packageName = getNodeModuleRootSpecifier(specifier); - for (var _i = 0, packageJsons_1 = packageJsons; _i < packageJsons_1.length; _i++) { - var packageJson = packageJsons_1[_i]; - if (packageJson.has(packageName) || packageJson.has(ts.getTypesPackageName(packageName))) { - return true; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var _a; + var fixName = "fixOverrideModifier"; + var fixAddOverrideId = "fixAddOverrideModifier"; + var fixRemoveOverrideId = "fixRemoveOverrideModifier"; + var errorCodes = [ + ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code, + ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code, + ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code, + ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code, + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code + ]; + var errorCodeFixIdMap = (_a = {}, + _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code] = [ + ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Add_all_missing_override_modifiers, + ], + _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code] = [ + ts.Diagnostics.Remove_override_modifier, fixRemoveOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers + ], + _a[ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code] = [ + ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Add_all_missing_override_modifiers, + ], + _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code] = [ + ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers + ], + _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code] = [ + ts.Diagnostics.Remove_override_modifier, fixRemoveOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers + ], + _a); + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var errorCode = context.errorCode, span = context.span, sourceFile = context.sourceFile; + var info = errorCodeFixIdMap[errorCode]; + if (!info) + return ts.emptyArray; + var descriptions = info[0], fixId = info[1], fixAllDescriptions = info[2]; + if (ts.isSourceFileJS(sourceFile)) + return ts.emptyArray; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { return dispatchChanges(changes, context, errorCode, span.start); }); + return [ + codefix.createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId, fixAllDescriptions) + ]; + }, + fixIds: [fixName, fixAddOverrideId, fixRemoveOverrideId], + getAllCodeActions: function (context) { + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var code = diag.code, start = diag.start, file = diag.file; + var info = errorCodeFixIdMap[code]; + if (!info || info[1] !== context.fixId || ts.isSourceFileJS(file)) { + return; } - } - return false; - } - function allowsImportingAmbientModule(moduleSymbol) { - if (!packageJsons.length) { - return true; - } - var declaringSourceFile = moduleSymbol.valueDeclaration.getSourceFile(); - var declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName); - if (typeof declaringNodeModuleName === "undefined") { - return true; - } - var declaredModuleSpecifier = ts.stripQuotes(moduleSymbol.getName()); - if (isAllowedCoreNodeModulesImport(declaredModuleSpecifier)) { - return true; - } - return moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName) - || moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier); - } - function allowsImportingSourceFile(sourceFile) { - if (!packageJsons.length) { - return true; - } - var moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName); - if (!moduleSpecifier) { - return true; - } - return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); + dispatchChanges(changes, context, code, start); + }); } - /** - * Use for a specific module specifier that has already been resolved. - * Use `allowsImportingAmbientModule` or `allowsImportingSourceFile` to resolve - * the best module specifier for a given module _and_ determine if it’s importable. - */ - function allowsImportingSpecifier(moduleSpecifier) { - if (!packageJsons.length || isAllowedCoreNodeModulesImport(moduleSpecifier)) { - return true; - } - if (ts.pathIsRelative(moduleSpecifier) || ts.isRootedDiskPath(moduleSpecifier)) { + }); + function dispatchChanges(changeTracker, context, errorCode, pos) { + switch (errorCode) { + case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code: + case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code: + case ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code: + return doAddOverrideModifierChange(changeTracker, context.sourceFile, pos); + case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code: + case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code: + return doRemoveOverrideModifierChange(changeTracker, context.sourceFile, pos); + default: + ts.Debug.fail("Unexpected error code: " + errorCode); + } + } + function doAddOverrideModifierChange(changeTracker, sourceFile, pos) { + var classElement = findContainerClassElementLike(sourceFile, pos); + var modifiers = classElement.modifiers || ts.emptyArray; + var staticModifier = ts.find(modifiers, ts.isStaticModifier); + var accessibilityModifier = ts.find(modifiers, function (m) { return ts.isAccessibilityModifier(m.kind); }); + var modifierPos = staticModifier ? staticModifier.end : + accessibilityModifier ? accessibilityModifier.end : + classElement.decorators ? ts.skipTrivia(sourceFile.text, classElement.decorators.end) : classElement.getStart(sourceFile); + var options = accessibilityModifier || staticModifier ? { prefix: " " } : { suffix: " " }; + changeTracker.insertModifierAt(sourceFile, modifierPos, 156 /* OverrideKeyword */, options); + } + function doRemoveOverrideModifierChange(changeTracker, sourceFile, pos) { + var classElement = findContainerClassElementLike(sourceFile, pos); + var overrideModifier = classElement.modifiers && ts.find(classElement.modifiers, function (modifier) { return modifier.kind === 156 /* OverrideKeyword */; }); + ts.Debug.assertIsDefined(overrideModifier); + changeTracker.deleteModifier(sourceFile, overrideModifier); + } + function isClassElementLikeHasJSDoc(node) { + switch (node.kind) { + case 167 /* Constructor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return true; - } - return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); - } - function isAllowedCoreNodeModulesImport(moduleSpecifier) { - // If we’re in JavaScript, it can be difficult to tell whether the user wants to import - // from Node core modules or not. We can start by seeing if the user is actually using - // any node core modules, as opposed to simply having @types/node accidentally as a - // dependency of a dependency. - if (ts.isSourceFileJS(fromFile) && ts.JsTyping.nodeCoreModules.has(moduleSpecifier)) { - if (usesNodeCoreModules === undefined) { - usesNodeCoreModules = ts.consumesNodeCoreModules(fromFile); - } - if (usesNodeCoreModules) { - return true; - } - } - return false; - } - function getNodeModulesPackageNameFromFileName(importedFileName) { - if (!ts.stringContains(importedFileName, "node_modules")) { - return undefined; - } - var specifier = ts.moduleSpecifiers.getNodeModulesPackageName(host.getCompilationSettings(), fromFile.path, importedFileName, moduleSpecifierResolutionHost); - if (!specifier) { - return undefined; - } - // Paths here are not node_modules, so we don’t care about them; - // returning anything will trigger a lookup in package.json. - if (!ts.pathIsRelative(specifier) && !ts.isRootedDiskPath(specifier)) { - return getNodeModuleRootSpecifier(specifier); - } - } - function getNodeModuleRootSpecifier(fullSpecifier) { - var components = ts.getPathComponents(ts.getPackageNameFromTypesPackageName(fullSpecifier)).slice(1); - // Scoped packages - if (ts.startsWith(components[0], "@")) { - return components[0] + "/" + components[1]; - } - return components[0]; + case 161 /* Parameter */: + return ts.isParameterPropertyDeclaration(node, node.parent); + default: + return false; } } + function findContainerClassElementLike(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var classElement = ts.findAncestor(token, function (node) { + if (ts.isClassLike(node)) + return "quit"; + return isClassElementLikeHasJSDoc(node); + }); + ts.Debug.assert(classElement && isClassElementLikeHasJSDoc(classElement)); + return classElement; + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -139043,7 +143500,7 @@ var ts; }); function getNamedTupleMember(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - return ts.findAncestor(token, function (t) { return t.kind === 192 /* NamedTupleMember */; }); + return ts.findAncestor(token, function (t) { return t.kind === 193 /* NamedTupleMember */; }); } function doChange(changes, sourceFile, namedTupleMember) { if (!namedTupleMember) { @@ -139052,11 +143509,11 @@ var ts; var unwrappedType = namedTupleMember.type; var sawOptional = false; var sawRest = false; - while (unwrappedType.kind === 180 /* OptionalType */ || unwrappedType.kind === 181 /* RestType */ || unwrappedType.kind === 186 /* ParenthesizedType */) { - if (unwrappedType.kind === 180 /* OptionalType */) { + while (unwrappedType.kind === 181 /* OptionalType */ || unwrappedType.kind === 182 /* RestType */ || unwrappedType.kind === 187 /* ParenthesizedType */) { + if (unwrappedType.kind === 181 /* OptionalType */) { sawOptional = true; } - else if (unwrappedType.kind === 181 /* RestType */) { + else if (unwrappedType.kind === 182 /* RestType */) { sawRest = true; } unwrappedType = unwrappedType.type; @@ -139120,7 +143577,7 @@ var ts; var checker = context.program.getTypeChecker(); var suggestedSymbol; if (ts.isPropertyAccessExpression(parent) && parent.name === node) { - ts.Debug.assert(ts.isIdentifierOrPrivateIdentifier(node), "Expected an identifier for spelling (property access)"); + ts.Debug.assert(ts.isMemberName(node), "Expected an identifier for spelling (property access)"); var containingType = checker.getTypeAtLocation(parent.expression); if (parent.flags & 32 /* OptionalChain */) { containingType = checker.getNonNullableType(containingType); @@ -139159,7 +143616,7 @@ var ts; var suggestion = ts.symbolName(suggestedSymbol); if (!ts.isIdentifierText(suggestion, target) && ts.isPropertyAccessExpression(node.parent)) { var valDecl = suggestedSymbol.valueDeclaration; - if (ts.isNamedDeclaration(valDecl) && ts.isPrivateIdentifier(valDecl.name)) { + if (valDecl && ts.isNamedDeclaration(valDecl) && ts.isPrivateIdentifier(valDecl.name)) { changes.replaceNode(sourceFile, node, ts.factory.createIdentifier(suggestion)); } else { @@ -139356,19 +143813,19 @@ var ts; } function getVariableLikeInitializer(declaration) { switch (declaration.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: - case 163 /* PropertyDeclaration */: - case 288 /* PropertyAssignment */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: + case 164 /* PropertyDeclaration */: + case 289 /* PropertyAssignment */: return declaration.initializer; - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return declaration.initializer && (ts.isJsxExpression(declaration.initializer) ? declaration.initializer.expression : undefined); - case 289 /* ShorthandPropertyAssignment */: - case 162 /* PropertySignature */: - case 291 /* EnumMember */: - case 333 /* JSDocPropertyTag */: - case 326 /* JSDocParameterTag */: + case 290 /* ShorthandPropertyAssignment */: + case 163 /* PropertySignature */: + case 292 /* EnumMember */: + case 337 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: return undefined; } } @@ -139469,7 +143926,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = codefix.getAllSupers(classDeclaration, checker); - var _loop_13 = function (info) { + var _loop_14 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -139494,9 +143951,9 @@ var ts; } } }; - for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { - var info = infos_1[_i]; - _loop_13(info); + for (var _i = 0, infos_2 = infos; _i < infos_2.length; _i++) { + var info = infos_2[_i]; + _loop_14(info); } }); })); @@ -139586,7 +144043,7 @@ var ts; function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, token, makeStatic) { var tokenName = token.text; if (makeStatic) { - if (classDeclaration.kind === 221 /* ClassExpression */) { + if (classDeclaration.kind === 222 /* ClassExpression */) { return; } var className = classDeclaration.name.getText(); @@ -139638,15 +144095,15 @@ var ts; } function getTypeNode(checker, classDeclaration, token) { var typeNode; - if (token.parent.parent.kind === 216 /* BinaryExpression */) { + if (token.parent.parent.kind === 217 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration, /*flags*/ undefined); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration, 1 /* NoTruncation */); } else { var contextualType = checker.getContextualType(token.parent); - typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined) : undefined; + typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, 1 /* NoTruncation */) : undefined; } return typeNode || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } @@ -139710,7 +144167,7 @@ var ts; } function addMethodDeclaration(context, changes, callExpression, name, modifierFlags, parentDeclaration, sourceFile) { var importAdder = codefix.createImportAdder(sourceFile, context.program, context.preferences, context.host); - var methodDeclaration = codefix.createSignatureDeclarationFromCallExpression(165 /* MethodDeclaration */, context, importAdder, callExpression, name, modifierFlags, parentDeclaration); + var methodDeclaration = codefix.createSignatureDeclarationFromCallExpression(166 /* MethodDeclaration */, context, importAdder, callExpression, name, modifierFlags, parentDeclaration); var containingMethodDeclaration = ts.findAncestor(callExpression, function (n) { return ts.isMethodDeclaration(n) || ts.isConstructorDeclaration(n); }); if (containingMethodDeclaration && containingMethodDeclaration.parent === parentDeclaration) { changes.insertNodeAfter(sourceFile, containingMethodDeclaration, methodDeclaration); @@ -139739,7 +144196,7 @@ var ts; } function addFunctionDeclaration(changes, context, info) { var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); - var functionDeclaration = codefix.createSignatureDeclarationFromCallExpression(251 /* FunctionDeclaration */, context, importAdder, info.call, info.token, info.modifierFlags, info.parentDeclaration); + var functionDeclaration = codefix.createSignatureDeclarationFromCallExpression(252 /* FunctionDeclaration */, context, importAdder, info.call, ts.idText(info.token), info.modifierFlags, info.parentDeclaration); changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -139826,7 +144283,10 @@ var ts; return { type: "install package", file: fileName, packageName: packageName }; } function tryGetImportedPackageName(sourceFile, pos) { - var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; + var moduleSpecifierText = ts.tryCast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral); + if (!moduleSpecifierText) + return undefined; + var moduleName = moduleSpecifierText.text; var packageName = ts.parsePackageName(moduleName).packageName; return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; } @@ -140056,7 +144516,10 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code], + errorCodes: [ + ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code, + ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code, + ], getCodeActions: function (context) { var compilerOptions = context.program.getCompilerOptions(); var configFile = compilerOptions.configFile; @@ -140427,7 +144890,7 @@ var ts; } function isImport(token) { return token.kind === 99 /* ImportKeyword */ - || token.kind === 78 /* Identifier */ && (token.parent.kind === 265 /* ImportSpecifier */ || token.parent.kind === 262 /* ImportClause */); + || token.kind === 78 /* Identifier */ && (token.parent.kind === 266 /* ImportSpecifier */ || token.parent.kind === 263 /* ImportClause */); } /** Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. */ function tryGetFullImport(token) { @@ -140437,7 +144900,7 @@ var ts; return ts.isVariableDeclarationList(token.parent) && ts.first(token.parent.getChildren(sourceFile)) === token; } function deleteEntireVariableStatement(changes, sourceFile, node) { - changes.delete(sourceFile, node.parent.kind === 232 /* VariableStatement */ ? node.parent : node); + changes.delete(sourceFile, node.parent.kind === 233 /* VariableStatement */ ? node.parent : node); } function deleteDestructuringElements(changes, sourceFile, node) { ts.forEach(node.elements, function (n) { return changes.delete(sourceFile, n); }); @@ -140462,14 +144925,14 @@ var ts; } function canPrefix(token) { switch (token.parent.kind) { - case 160 /* Parameter */: - case 159 /* TypeParameter */: + case 161 /* Parameter */: + case 160 /* TypeParameter */: return true; - case 249 /* VariableDeclaration */: { + case 250 /* VariableDeclaration */: { var varDecl = token.parent; switch (varDecl.parent.parent.kind) { - case 239 /* ForOfStatement */: - case 238 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 239 /* ForInStatement */: return true; } } @@ -140493,8 +144956,10 @@ var ts; if (ts.isParameter(parent)) { tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, program, cancellationToken, isFixAll); } - else if (!isFixAll || !(ts.isIdentifier(token) && ts.FindAllReferences.Core.isSymbolReferencedInFile(token, checker, sourceFile))) { - changes.delete(sourceFile, ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent); + else if (!(isFixAll && ts.isIdentifier(token) && ts.FindAllReferences.Core.isSymbolReferencedInFile(token, checker, sourceFile))) { + var node = ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent; + ts.Debug.assert(node !== sourceFile, "should not delete whole source file"); + changes.delete(sourceFile, node); } } function tryDeleteParameter(changes, sourceFile, parameter, checker, sourceFiles, program, cancellationToken, isFixAll) { @@ -140517,8 +144982,8 @@ var ts; function mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll) { var parent = parameter.parent; switch (parent.kind) { - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: var index = parent.parameters.indexOf(parameter); var referent = ts.isMethodDeclaration(parent) ? parent.name : parent; var entries = ts.FindAllReferences.Core.getReferencedSymbolsForNode(parent.pos, referent, program, sourceFiles, cancellationToken); @@ -140548,17 +145013,17 @@ var ts; } } return true; - case 251 /* FunctionDeclaration */: { + case 252 /* FunctionDeclaration */: { if (parent.name && isCallbackLike(checker, sourceFile, parent.name)) { return isLastParameter(parent, parameter, isFixAll); } return true; } - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused. return isLastParameter(parent, parameter, isFixAll); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: // Setter must have a parameter return false; default: @@ -140616,7 +145081,7 @@ var ts; var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { switch (container.kind) { - case 234 /* IfStatement */: + case 235 /* IfStatement */: if (container.elseStatement) { if (ts.isBlock(statement.parent)) { break; @@ -140627,8 +145092,8 @@ var ts; return; } // falls through - case 236 /* WhileStatement */: - case 237 /* ForStatement */: + case 237 /* WhileStatement */: + case 238 /* ForStatement */: changes.delete(sourceFile, container); return; } @@ -140701,7 +145166,7 @@ var ts; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; - if (typeNode.kind === 305 /* JSDocNullableType */) { + if (typeNode.kind === 306 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); @@ -140721,7 +145186,7 @@ var ts; if (!info) return; var typeNode = info.typeNode, type = info.type; - var fixedType = typeNode.kind === 305 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; + var fixedType = typeNode.kind === 306 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; doChange(changes, sourceFile, typeNode, fixedType, checker); }); } @@ -140738,22 +145203,22 @@ var ts; // NOTE: Some locations are not handled yet: // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments switch (node.kind) { - case 224 /* AsExpression */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 251 /* FunctionDeclaration */: - case 167 /* GetAccessor */: - case 171 /* IndexSignature */: - case 190 /* MappedType */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 168 /* SetAccessor */: - case 254 /* TypeAliasDeclaration */: - case 206 /* TypeAssertionExpression */: - case 249 /* VariableDeclaration */: + case 225 /* AsExpression */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 252 /* FunctionDeclaration */: + case 168 /* GetAccessor */: + case 172 /* IndexSignature */: + case 191 /* MappedType */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 169 /* SetAccessor */: + case 255 /* TypeAliasDeclaration */: + case 207 /* TypeAssertionExpression */: + case 250 /* VariableDeclaration */: return true; default: return false; @@ -140768,7 +145233,7 @@ var ts; (function (codefix) { var fixId = "fixMissingCallParentheses"; var errorCodes = [ - ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead.code, + ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -140814,7 +145279,7 @@ var ts; var fixId = "fixAwaitInSyncFunction"; var errorCodes = [ ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, - ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -140855,14 +145320,14 @@ var ts; } var insertBefore; switch (containingFunction.kind) { - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: insertBefore = containingFunction.name; break; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: insertBefore = ts.findChildOfKind(containingFunction, 97 /* FunctionKeyword */, sourceFile); break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); break; default: @@ -141061,7 +145526,7 @@ var ts; var typeNode = ts.getTypeNodeIfAccessible(type, parent, program, host); if (typeNode) { // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags - var typeTag = ts.factory.createJSDocTypeTag(/*tagName*/ undefined, ts.factory.createJSDocTypeExpression(typeNode), /*comment*/ ""); + var typeTag = ts.factory.createJSDocTypeTag(/*tagName*/ undefined, ts.factory.createJSDocTypeExpression(typeNode), /*comment*/ undefined); addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]); } importAdder.writeFixes(changes); @@ -141195,13 +145660,13 @@ var ts; function annotate(changes, importAdder, sourceFile, declaration, type, program, host) { var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { - if (ts.isInJSFile(sourceFile) && declaration.kind !== 162 /* PropertySignature */) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 163 /* PropertySignature */) { var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration; if (!parent) { return; } var typeExpression = ts.factory.createJSDocTypeExpression(typeNode); - var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.factory.createJSDocReturnTag(/*tagName*/ undefined, typeExpression, "") : ts.factory.createJSDocTypeTag(/*tagName*/ undefined, typeExpression, ""); + var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.factory.createJSDocReturnTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined) : ts.factory.createJSDocTypeTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined); addJSDocTags(changes, sourceFile, parent, [typeTag]); } else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, ts.getEmitScriptTarget(program.getCompilerOptions()))) { @@ -141256,13 +145721,13 @@ var ts; else { var paramTags = ts.map(inferences, function (_a) { var name = _a.name, typeNode = _a.typeNode, isOptional = _a.isOptional; - return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!isOptional, ts.factory.createJSDocTypeExpression(typeNode), /* isNameFirst */ false, ""); + return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!isOptional, ts.factory.createJSDocTypeExpression(typeNode), /* isNameFirst */ false, /*comment*/ undefined); }); addJSDocTags(changes, sourceFile, signature, paramTags); } } function addJSDocTags(changes, sourceFile, parent, newTags) { - var comments = ts.mapDefined(parent.jsDoc, function (j) { return j.comment; }); + var comments = ts.flatMap(parent.jsDoc, function (j) { return typeof j.comment === "string" ? ts.factory.createJSDocText(j.comment) : j.comment; }); var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }); var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) { var merged = tryMergeJsdocTags(tag, newTag); @@ -141270,15 +145735,15 @@ var ts; oldTags[i] = merged; return !!merged; }); }); - var tag = ts.factory.createJSDocComment(comments.join("\n"), ts.factory.createNodeArray(__spreadArray(__spreadArray([], (oldTags || ts.emptyArray)), unmergedNewTags))); - var jsDocNode = parent.kind === 209 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent; + var tag = ts.factory.createJSDocComment(ts.factory.createNodeArray(ts.intersperse(comments, ts.factory.createJSDocText("\n"))), ts.factory.createNodeArray(__spreadArray(__spreadArray([], (oldTags || ts.emptyArray)), unmergedNewTags))); + var jsDocNode = parent.kind === 210 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent; jsDocNode.jsDoc = parent.jsDoc; jsDocNode.jsDocCache = parent.jsDocCache; changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag); } codefix.addJSDocTags = addJSDocTags; function getJsDocNodeForArrowFunction(signature) { - if (signature.parent.kind === 163 /* PropertyDeclaration */) { + if (signature.parent.kind === 164 /* PropertyDeclaration */) { return signature.parent; } return signature.parent.parent; @@ -141288,14 +145753,14 @@ var ts; return undefined; } switch (oldTag.kind) { - case 326 /* JSDocParameterTag */: { + case 330 /* JSDocParameterTag */: { var oldParam = oldTag; var newParam = newTag; return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText ? ts.factory.createJSDocParameterTag(/*tagName*/ undefined, newParam.name, /*isBracketed*/ false, newParam.typeExpression, newParam.isNameFirst, oldParam.comment) : undefined; } - case 327 /* JSDocReturnTag */: + case 331 /* JSDocReturnTag */: return ts.factory.createJSDocReturnTag(/*tagName*/ undefined, newTag.typeExpression, oldTag.comment); } } @@ -141320,19 +145785,19 @@ var ts; function getFunctionReferences(containingFunction, sourceFile, program, cancellationToken) { var searchToken; switch (containingFunction.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: searchToken = ts.findChildOfKind(containingFunction, 132 /* ConstructorKeyword */, sourceFile); break; - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: var parent = containingFunction.parent; searchToken = (ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent)) && ts.isIdentifier(parent.name) ? parent.name : containingFunction.name; break; - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: searchToken = containingFunction.name; break; } @@ -141474,24 +145939,24 @@ var ts; node = node.parent; } switch (node.parent.kind) { - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: inferTypeFromExpressionStatement(node, usage); break; - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: usage.isNumber = true; break; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: inferTypeFromPrefixUnaryExpression(node.parent, usage); break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: inferTypeFromBinaryExpression(node, node.parent, usage); break; - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: inferTypeFromSwitchStatementLabel(node.parent, usage); break; - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: if (node.parent.expression === node) { inferTypeFromCallExpression(node.parent, usage); } @@ -141499,20 +145964,20 @@ var ts; inferTypeFromContextualType(node, usage); } break; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: inferTypeFromPropertyAccessExpression(node.parent, usage); break; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: inferTypeFromPropertyElementExpression(node.parent, node, usage); break; - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: inferTypeFromPropertyAssignment(node.parent, usage); break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: inferTypeFromPropertyDeclaration(node.parent, usage); break; - case 249 /* VariableDeclaration */: { + case 250 /* VariableDeclaration */: { var _a = node.parent, name = _a.name, initializer = _a.initializer; if (node === name) { if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. @@ -141634,7 +146099,7 @@ var ts; case 56 /* BarBarToken */: case 60 /* QuestionQuestionToken */: if (node === parent.left && - (node.parent.parent.kind === 249 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + (node.parent.parent.kind === 250 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { // var x = x || {}; // TODO: use getFalsyflagsOfType addCandidateType(usage, checker.getTypeAtLocation(parent.right)); @@ -141662,7 +146127,7 @@ var ts; } } calculateUsageOfNode(parent, call.return_); - if (parent.kind === 203 /* CallExpression */) { + if (parent.kind === 204 /* CallExpression */) { (usage.calls || (usage.calls = [])).push(call); } else { @@ -141765,7 +146230,7 @@ var ts; var anon = anons_1[_i]; for (var _a = 0, _b = checker.getPropertiesOfType(anon); _a < _b.length; _a++) { var p = _b[_a]; - props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration)); + props.add(p.name, p.valueDeclaration ? checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration) : checker.getAnyType()); } calls.push.apply(calls, checker.getSignaturesOfType(anon, 0 /* Call */)); constructs.push.apply(constructs, checker.getSignaturesOfType(anon, 1 /* Construct */)); @@ -141906,12 +146371,13 @@ var ts; if (!usageParam) { break; } - var genericParamType = checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration); + var genericParamType = genericParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration) : checker.getAnyType(); var elementType = isRest && checker.getElementTypeOfArrayType(genericParamType); if (elementType) { genericParamType = elementType; } - var targetType = usageParam.type || checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration); + var targetType = usageParam.type + || (usageParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration) : checker.getAnyType()); types.push.apply(types, inferTypeParameters(genericParamType, targetType, typeParameter)); } var genericReturn = checker.getReturnTypeOfSignature(genericSig); @@ -141925,7 +146391,7 @@ var ts; function getSignatureFromCalls(calls) { var parameters = []; var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; })); - var _loop_14 = function (i) { + var _loop_15 = function (i) { var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); })); if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) { @@ -141934,7 +146400,7 @@ var ts; parameters.push(symbol); }; for (var i = 0; i < length; i++) { - _loop_14(i); + _loop_15(i); } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); // TODO: GH#18217 @@ -142105,8 +146571,8 @@ var ts; var ambient = !!(enclosingDeclaration.flags & 8388608 /* Ambient */); var quotePreference = ts.getQuotePreference(sourceFile, preferences); switch (declaration.kind) { - case 162 /* PropertySignature */: - case 163 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 164 /* PropertyDeclaration */: var flags = quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : undefined; var typeNode = checker.typeToTypeNode(type, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); if (importAdder) { @@ -142120,8 +146586,8 @@ var ts; /*decorators*/ undefined, modifiers, name, optional ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: { + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: { var typeNode_1 = checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); var allAccessors = ts.getAllAccessorDeclarations(declarations, declaration); var orderedAccessors = allAccessors.secondAccessor @@ -142150,8 +146616,8 @@ var ts; } break; } - case 164 /* MethodSignature */: - case 165 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 166 /* MethodDeclaration */: // The signature for the implementation appears as an entry in `signatures` iff // there is only one signature. // If there are overloads and an implementation signature, it appears as an @@ -142181,7 +146647,7 @@ var ts; } else { ts.Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count"); - addClassElement(createMethodImplementingSignatures(signatures, name, optional, modifiers, quotePreference)); + addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference)); } } break; @@ -142197,7 +146663,7 @@ var ts; var checker = program.getTypeChecker(); var scriptTarget = ts.getEmitScriptTarget(program.getCompilerOptions()); var flags = 1 /* NoTruncation */ | 1073741824 /* NoUndefinedOptionalParameterType */ | 256 /* SuppressAnyReturnType */ | (quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0); - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 165 /* MethodDeclaration */, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 166 /* MethodDeclaration */, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); if (!signatureDeclaration) { return undefined; } @@ -142281,7 +146747,7 @@ var ts; var type = isJs || contextualType === undefined ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker); - if (kind === 165 /* MethodDeclaration */) { + if (kind === 166 /* MethodDeclaration */) { return ts.factory.createMethodDeclaration( /*decorators*/ undefined, modifiers, asteriskToken, name, /*questionToken*/ undefined, typeParameters, parameters, type, ts.isInterfaceDeclaration(contextNode) ? undefined : createStubbedMethodBody(quotePreference)); @@ -142317,7 +146783,7 @@ var ts; } return parameters; } - function createMethodImplementingSignatures(signatures, name, optional, modifiers, quotePreference) { + function createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference) { /** This is *a* signature with the maximal number of arguments, * such that if there is a "maximal" signature without rest arguments, * this is one of them. @@ -142348,8 +146814,13 @@ var ts; parameters.push(restParameter); } return createStubbedMethod(modifiers, name, optional, - /*typeParameters*/ undefined, parameters, - /*returnType*/ undefined, quotePreference); + /*typeParameters*/ undefined, parameters, getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), quotePreference); + } + function getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration) { + if (ts.length(signatures)) { + var type = checker.getUnionType(ts.map(signatures, checker.getReturnTypeOfSignature)); + return checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); + } } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference) { return ts.factory.createMethodDeclaration( @@ -142476,13 +146947,13 @@ var ts; if (ts.isClassLike(container)) { var modifierFlags = ts.getEffectiveModifierFlags(declaration); if (ts.isSourceFileJS(file)) { - var modifiers = createModifiers(modifierFlags); + var modifiers = ts.createModifiers(modifierFlags); accessorModifiers = modifiers; fieldModifiers = modifiers; } else { - accessorModifiers = createModifiers(prepareModifierFlagsForAccessor(modifierFlags)); - fieldModifiers = createModifiers(prepareModifierFlagsForField(modifierFlags)); + accessorModifiers = ts.createModifiers(prepareModifierFlagsForAccessor(modifierFlags)); + fieldModifiers = ts.createModifiers(prepareModifierFlagsForField(modifierFlags)); } } updateFieldDeclaration(changeTracker, file, declaration, type, fieldName, fieldModifiers); @@ -142517,9 +146988,6 @@ var ts; var leftHead = isStatic ? container.name : ts.factory.createThis(); // TODO: GH#18217 return ts.isIdentifier(fieldName) ? ts.factory.createPropertyAccessExpression(leftHead, fieldName) : ts.factory.createElementAccessExpression(leftHead, ts.factory.createStringLiteralFromNode(fieldName)); } - function createModifiers(modifierFlags) { - return modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; - } function prepareModifierFlagsForAccessor(modifierFlags) { modifierFlags &= ~64 /* Readonly */; // avoid Readonly modifier because it will convert to get accessor modifierFlags &= ~8 /* Private */; @@ -142564,7 +147032,7 @@ var ts; isStatic: ts.hasStaticModifier(declaration), isReadonly: ts.hasEffectiveReadonlyModifier(declaration), type: getDeclarationType(declaration, program), - container: declaration.kind === 160 /* Parameter */ ? declaration.parent.parent : declaration.parent, + container: declaration.kind === 161 /* Parameter */ ? declaration.parent.parent : declaration.parent, originalName: declaration.name.text, declaration: declaration, fieldName: fieldName, @@ -142654,7 +147122,7 @@ var ts; if (!superSymbol) break; var symbol = superSymbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(superSymbol) : superSymbol; - var superDecl = ts.find(symbol.declarations, ts.isClassLike); + var superDecl = symbol.declarations && ts.find(symbol.declarations, ts.isClassLike); if (!superDecl) break; res.push(superDecl); @@ -142700,7 +147168,7 @@ var ts; }); function getActionsForUsageOfInvalidImport(context) { var sourceFile = context.sourceFile; - var targetKind = ts.Diagnostics.This_expression_is_not_callable.code === context.errorCode ? 203 /* CallExpression */ : 204 /* NewExpression */; + var targetKind = ts.Diagnostics.This_expression_is_not_callable.code === context.errorCode ? 204 /* CallExpression */ : 205 /* NewExpression */; var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind; }); if (!node) { return []; @@ -143034,7 +147502,7 @@ var ts; function getImportTypeNode(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); ts.Debug.assert(token.kind === 99 /* ImportKeyword */, "This token should be an ImportKeyword"); - ts.Debug.assert(token.parent.kind === 195 /* ImportType */, "Token parent should be an ImportType"); + ts.Debug.assert(token.parent.kind === 196 /* ImportType */, "Token parent should be an ImportType"); return token.parent; } function doChange(changes, sourceFile, importType) { @@ -143301,7 +147769,7 @@ var ts; var token = ts.getTokenAtPosition(sourceFile, pos); var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(token); - if (symbol) { + if (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) { return symbol.valueDeclaration.parent.parent; } } @@ -143496,23 +147964,23 @@ var ts; return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_find_export_statement) }; } var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol; - var flags = ts.getSyntacticModifierFlags(exportNode); + var flags = ts.getSyntacticModifierFlags(exportNode) || ((ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) ? 513 /* ExportDefault */ : 0 /* None */); var wasDefault = !!(flags & 512 /* Default */); // If source file already has a default export, don't offer refactor. if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.This_file_already_has_a_default_export) }; } switch (exportNode.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 256 /* ModuleDeclaration */: { + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 257 /* ModuleDeclaration */: { var node = exportNode; return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; } - case 232 /* VariableStatement */: { + case 233 /* VariableStatement */: { var vs = exportNode; // Must be `export const x = something;`. if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { @@ -143524,6 +147992,11 @@ var ts; ts.Debug.assert(!wasDefault, "Can't have a default flag here"); return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; } + case 267 /* ExportAssignment */: { + var node = exportNode; + var exp = node.expression; + return node.isExportEquals ? undefined : { exportNode: node, exportName: exp, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol }; + } default: return undefined; } @@ -143535,17 +148008,24 @@ var ts; function changeExport(exportingSourceFile, _a, changes, checker) { var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; if (wasDefault) { - changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 87 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + if (ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) { + var exp = exportNode.expression; + var spec = makeExportSpecifier(exp.text, exp.text); + changes.replaceNode(exportingSourceFile, exportNode, ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([spec]))); + } + else { + changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 87 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + } } else { var exportKeyword = ts.Debug.checkDefined(ts.findModifier(exportNode, 92 /* ExportKeyword */), "Should find an export keyword in modifier list"); switch (exportNode.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.factory.createToken(87 /* DefaultKeyword */)); break; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // If 'x' isn't used in this file and doesn't have type definition, `export const x = 0;` --> `export default 0;` var decl = ts.first(exportNode.declarationList.declarations); if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile) && !decl.type) { @@ -143554,15 +148034,15 @@ var ts; break; } // falls through - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 256 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 257 /* ModuleDeclaration */: // `export type T = number;` -> `type T = number; export default T;` changes.deleteModifier(exportingSourceFile, exportKeyword); changes.insertNodeAfter(exportingSourceFile, exportNode, ts.factory.createExportDefault(ts.factory.createIdentifier(exportName.text))); break; default: - ts.Debug.assertNever(exportNode, "Unexpected exportNode kind " + exportNode.kind); + ts.Debug.fail("Unexpected exportNode kind " + exportNode.kind); } } } @@ -143583,18 +148063,18 @@ var ts; function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { var parent = ref.parent; switch (parent.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: // `a.default` --> `a.foo` changes.replaceNode(importingSourceFile, ref, ts.factory.createIdentifier(exportName)); break; - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: { + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: { var spec = parent; // `default as foo` --> `foo`, `default as bar` --> `foo as bar` changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); break; } - case 262 /* ImportClause */: { + case 263 /* ImportClause */: { var clause = parent; ts.Debug.assert(clause.name === ref, "Import clause name should match provided ref"); var spec = makeImportSpecifier(exportName, ref.text); @@ -143603,7 +148083,7 @@ var ts; // `import foo from "./a";` --> `import { foo } from "./a";` changes.replaceNode(importingSourceFile, ref, ts.factory.createNamedImports([spec])); } - else if (namedBindings.kind === 263 /* NamespaceImport */) { + else if (namedBindings.kind === 264 /* NamespaceImport */) { // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";` changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; @@ -143624,11 +148104,11 @@ var ts; function changeNamedToDefaultImport(importingSourceFile, ref, changes) { var parent = ref.parent; switch (parent.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: // `a.foo` --> `a.default` changes.replaceNode(importingSourceFile, ref, ts.factory.createIdentifier("default")); break; - case 265 /* ImportSpecifier */: { + case 266 /* ImportSpecifier */: { // `import { foo } from "./a";` --> `import foo from "./a";` // `import { foo as bar } from "./a";` --> `import bar from "./a";` var defaultImport = ts.factory.createIdentifier(parent.name.text); @@ -143641,7 +148121,7 @@ var ts; } break; } - case 270 /* ExportSpecifier */: { + case 271 /* ExportSpecifier */: { // `export { foo } from "./a";` --> `export { default as foo } from "./a";` // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` // `export { foo as default } from "./a";` --> `export { default } from "./a";` @@ -143687,14 +148167,16 @@ var ts; if (!info) return ts.emptyArray; if (!refactor.isRefactorErrorInfo(info)) { - var namespaceImport = info.kind === 263 /* NamespaceImport */; + var namespaceImport = info.kind === 264 /* NamespaceImport */; var action = namespaceImport ? namespaceToNamedAction : namedToNamespaceAction; return [{ name: refactorName, description: action.description, actions: [action] }]; } if (context.preferences.provideRefactorNotApplicableReason) { return [ - { name: refactorName, description: namespaceToNamedAction.description, actions: [__assign(__assign({}, namespaceToNamedAction), { notApplicableReason: info.error })] }, - { name: refactorName, description: namedToNamespaceAction.description, actions: [__assign(__assign({}, namedToNamespaceAction), { notApplicableReason: info.error })] } + { name: refactorName, description: namespaceToNamedAction.description, + actions: [__assign(__assign({}, namespaceToNamedAction), { notApplicableReason: info.error })] }, + { name: refactorName, description: namedToNamespaceAction.description, + actions: [__assign(__assign({}, namedToNamespaceAction), { notApplicableReason: info.error })] } ]; } return ts.emptyArray; @@ -143729,7 +148211,7 @@ var ts; } function doChange(sourceFile, program, changes, toConvert) { var checker = program.getTypeChecker(); - if (toConvert.kind === 263 /* NamespaceImport */) { + if (toConvert.kind === 264 /* NamespaceImport */) { doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); } else { @@ -143794,7 +148276,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_15 = function (element) { + var _loop_16 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(namespaceImportName), propertyName); @@ -143813,7 +148295,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_15(element); + _loop_16(element); } changes.replaceNode(sourceFile, toConvert, ts.factory.createNamespaceImport(ts.factory.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -144130,27 +148612,27 @@ var ts; var lastDeclaration = signatureDecls[signatureDecls.length - 1]; var updated = lastDeclaration; switch (lastDeclaration.kind) { - case 164 /* MethodSignature */: { + case 165 /* MethodSignature */: { updated = ts.factory.updateMethodSignature(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); break; } - case 165 /* MethodDeclaration */: { + case 166 /* MethodDeclaration */: { updated = ts.factory.updateMethodDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } - case 169 /* CallSignature */: { + case 170 /* CallSignature */: { updated = ts.factory.updateCallSignature(lastDeclaration, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); break; } - case 166 /* Constructor */: { + case 167 /* Constructor */: { updated = ts.factory.updateConstructorDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.body); break; } - case 170 /* ConstructSignature */: { + case 171 /* ConstructSignature */: { updated = ts.factory.updateConstructSignature(lastDeclaration, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); break; } - case 251 /* FunctionDeclaration */: { + case 252 /* FunctionDeclaration */: { updated = ts.factory.updateFunctionDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } @@ -144202,12 +148684,12 @@ var ts; } function isConvertableSignatureDeclaration(d) { switch (d.kind) { - case 164 /* MethodSignature */: - case 165 /* MethodDeclaration */: - case 169 /* CallSignature */: - case 166 /* Constructor */: - case 170 /* ConstructSignature */: - case 251 /* FunctionDeclaration */: + case 165 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 170 /* CallSignature */: + case 167 /* Constructor */: + case 171 /* ConstructSignature */: + case 252 /* FunctionDeclaration */: return true; } return false; @@ -144347,7 +148829,6 @@ var ts; }; } } - // Skip these since we don't have a way to report errors yet if (refactor.refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { if (constantExtraction.errors.length === 0) { // Don't issue refactorings with duplicated names. @@ -144479,24 +148960,28 @@ var ts; /** * getRangeToExtract takes a span inside a text file and returns either an expression or an array * of statements representing the minimum set of nodes needed to extract the entire span. This - * process may fail, in which case a set of errors is returned instead (these are currently - * not shown to the user, but can be used by us diagnostically) + * process may fail, in which case a set of errors is returned instead. These errors are shown to + * users if they have the provideRefactorNotApplicableReason option set. */ // exported only for tests - function getRangeToExtract(sourceFile, span, considerEmptySpans) { - if (considerEmptySpans === void 0) { considerEmptySpans = true; } + function getRangeToExtract(sourceFile, span, invoked) { + if (invoked === void 0) { invoked = true; } var length = span.length; - if (length === 0 && !considerEmptySpans) { + if (length === 0 && !invoked) { return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] }; } - var cursorRequest = length === 0 && considerEmptySpans; + var cursorRequest = length === 0 && invoked; + var startToken = ts.findFirstNonJsxWhitespaceToken(sourceFile, span.start); + var endToken = ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)); + /* If the refactoring command is invoked through a keyboard action it's safe to assume that the user is actively looking for + refactoring actions at the span location. As they may not know the exact range that will trigger a refactoring, we expand the + searched span to cover a real node range making it more likely that something useful will show up. */ + var adjustedSpan = startToken && endToken && invoked ? getAdjustedSpanFromNodes(startToken, endToken, sourceFile) : span; // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span. // This may fail (e.g. you select two statements in the root of a source file) - var startToken = ts.getTokenAtPosition(sourceFile, span.start); - var start = cursorRequest ? getExtractableParent(startToken) : ts.getParentNodeInSpan(startToken, sourceFile, span); + var start = cursorRequest ? getExtractableParent(startToken) : ts.getParentNodeInSpan(startToken, sourceFile, adjustedSpan); // Do the same for the ending position - var endToken = ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)); - var end = cursorRequest ? start : ts.getParentNodeInSpan(endToken, sourceFile, span); + var end = cursorRequest ? start : ts.getParentNodeInSpan(endToken, sourceFile, adjustedSpan); var declarations = []; // We'll modify these flags as we walk the tree to collect data // about what things need to be done as part of the extraction. @@ -144505,6 +148990,9 @@ var ts; // cannot find either start or end node return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } + if (ts.isJSDoc(start)) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractJSDoc)] }; + } if (start.parent !== end.parent) { // start and end nodes belong to different subtrees return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; @@ -144539,9 +149027,6 @@ var ts; } return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; } - if (ts.isJSDoc(start)) { - return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractJSDoc)] }; - } if (ts.isReturnStatement(start) && !start.expression) { // Makes no sense to extract an expression-less return statement. return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; @@ -144594,20 +149079,20 @@ var ts; function checkForStaticContext(nodeToCheck, containingClass) { var current = nodeToCheck; while (current !== containingClass) { - if (current.kind === 163 /* PropertyDeclaration */) { + if (current.kind === 164 /* PropertyDeclaration */) { if (ts.hasSyntacticModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 160 /* Parameter */) { + else if (current.kind === 161 /* Parameter */) { var ctorOrMethod = ts.getContainingFunction(current); - if (ctorOrMethod.kind === 166 /* Constructor */) { + if (ctorOrMethod.kind === 167 /* Constructor */) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 165 /* MethodDeclaration */) { + else if (current.kind === 166 /* MethodDeclaration */) { if (ts.hasSyntacticModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } @@ -144650,7 +149135,7 @@ var ts; return true; } if (ts.isDeclaration(node)) { - var declaringNode = (node.kind === 249 /* VariableDeclaration */) ? node.parent.parent : node; + var declaringNode = (node.kind === 250 /* VariableDeclaration */) ? node.parent.parent : node; if (ts.hasSyntacticModifier(declaringNode, 1 /* Export */)) { // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! @@ -144662,16 +149147,16 @@ var ts; } // Some things can't be extracted in certain situations switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); return true; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; case 105 /* SuperKeyword */: // For a super *constructor call*, we have to be extracting the entire class, // but a super *method call* simply implies a 'this' reference - if (node.parent.kind === 203 /* CallExpression */) { + if (node.parent.kind === 204 /* CallExpression */) { // Super constructor call var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { @@ -144683,7 +149168,7 @@ var ts; rangeFacts |= RangeFacts.UsesThis; } break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: // check if arrow function uses this ts.forEachChild(node, function check(n) { if (ts.isThis(n)) { @@ -144697,39 +149182,39 @@ var ts; } }); // falls through - case 252 /* ClassDeclaration */: - case 251 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { // You cannot extract global declarations (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); } // falls through - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // do not dive into functions or classes return false; } var savedPermittedJumps = permittedJumps; switch (node.kind) { - case 234 /* IfStatement */: + case 235 /* IfStatement */: permittedJumps = 0 /* None */; break; - case 247 /* TryStatement */: + case 248 /* TryStatement */: // forbid all jumps inside try blocks permittedJumps = 0 /* None */; break; - case 230 /* Block */: - if (node.parent && node.parent.kind === 247 /* TryStatement */ && node.parent.finallyBlock === node) { + case 231 /* Block */: + if (node.parent && node.parent.kind === 248 /* TryStatement */ && node.parent.finallyBlock === node) { // allow unconditional returns from finally blocks permittedJumps = 4 /* Return */; } break; - case 285 /* DefaultClause */: - case 284 /* CaseClause */: + case 286 /* DefaultClause */: + case 285 /* CaseClause */: // allow unlabeled break inside case clauses permittedJumps |= 1 /* Break */; break; @@ -144741,19 +149226,19 @@ var ts; break; } switch (node.kind) { - case 187 /* ThisType */: + case 188 /* ThisType */: case 107 /* ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; break; - case 245 /* LabeledStatement */: { + case 246 /* LabeledStatement */: { var label = node.label; (seenLabels || (seenLabels = [])).push(label.escapedText); ts.forEachChild(node, visit); seenLabels.pop(); break; } - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: { + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: { var label = node.label; if (label) { if (!ts.contains(seenLabels, label.escapedText)) { @@ -144762,20 +149247,20 @@ var ts; } } else { - if (!(permittedJumps & (node.kind === 241 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + if (!(permittedJumps & (node.kind === 242 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { // attempt to break or continue in a forbidden context (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); } } break; } - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: rangeFacts |= RangeFacts.IsGenerator; break; - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: if (permittedJumps & 4 /* Return */) { rangeFacts |= RangeFacts.HasReturn; } @@ -144792,6 +149277,18 @@ var ts; } } extractSymbol.getRangeToExtract = getRangeToExtract; + /** + * Includes the final semicolon so that the span covers statements in cases where it would otherwise + * only cover the declaration list. + */ + function getAdjustedSpanFromNodes(startNode, endNode, sourceFile) { + var start = startNode.getStart(sourceFile); + var end = endNode.getEnd(); + if (sourceFile.text.charCodeAt(end) === 59 /* semicolon */) { + end++; + } + return { start: start, length: end - start }; + } function getStatementOrExpressionRange(node) { if (ts.isStatement(node)) { return [node]; @@ -144829,7 +149326,7 @@ var ts; while (true) { current = current.parent; // A function parameter's initializer is actually in the outer scope, not the function declaration - if (current.kind === 160 /* Parameter */) { + if (current.kind === 161 /* Parameter */) { // Skip all the way to the outer scope of the function that declared this parameter current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; } @@ -144840,7 +149337,7 @@ var ts; // * Module/namespace or source file if (isScope(current)) { scopes.push(current); - if (current.kind === 297 /* SourceFile */) { + if (current.kind === 298 /* SourceFile */) { return scopes; } } @@ -144930,32 +149427,32 @@ var ts; } function getDescriptionForFunctionLikeDeclaration(scope) { switch (scope.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return "constructor"; - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: return scope.name ? "function '" + scope.name.text + "'" : ts.ANONYMOUS; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return "arrow function"; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return "method '" + scope.name.getText() + "'"; - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: return "'get " + scope.name.getText() + "'"; - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: return "'set " + scope.name.getText() + "'"; default: throw ts.Debug.assertNever(scope, "Unexpected scope kind " + scope.kind); } } function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 252 /* ClassDeclaration */ + return scope.kind === 253 /* ClassDeclaration */ ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration" : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; } function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 257 /* ModuleBlock */ + return scope.kind === 258 /* ModuleBlock */ ? "namespace '" + scope.parent.name.getText() + "'" : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; } @@ -145244,7 +149741,7 @@ var ts; var localReference = ts.factory.createIdentifier(localNameText); changeTracker.replaceNode(context.file, node, localReference); } - else if (node.parent.kind === 233 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + else if (node.parent.kind === 234 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { // If the parent is an expression statement and the target scope is the immediately enclosing one, // replace the statement with the declaration. var newVariableStatement = ts.factory.createVariableStatement( @@ -145263,7 +149760,7 @@ var ts; changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); } // Consume - if (node.parent.kind === 233 /* ExpressionStatement */) { + if (node.parent.kind === 234 /* ExpressionStatement */) { // If the parent is an expression statement, delete it. changeTracker.delete(context.file, node.parent); } @@ -145590,7 +150087,7 @@ var ts; var scope = scopes_1[_i]; usagesPerScope.push({ usages: new ts.Map(), typeParameterUsages: new ts.Map(), substitutions: new ts.Map() }); substitutionsPerScope.push(new ts.Map()); - functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 251 /* FunctionDeclaration */ + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 252 /* FunctionDeclaration */ ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] : []); var constantErrors = []; @@ -145653,7 +150150,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_16 = function (i) { + var _loop_17 = 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 @@ -145693,7 +150190,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_16(i); + _loop_17(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -145909,30 +150406,30 @@ var ts; function isExtractableExpression(node) { var parent = node.parent; switch (parent.kind) { - case 291 /* EnumMember */: + case 292 /* EnumMember */: return false; } switch (node.kind) { case 10 /* StringLiteral */: - return parent.kind !== 261 /* ImportDeclaration */ && - parent.kind !== 265 /* ImportSpecifier */; - case 220 /* SpreadElement */: - case 196 /* ObjectBindingPattern */: - case 198 /* BindingElement */: + return parent.kind !== 262 /* ImportDeclaration */ && + parent.kind !== 266 /* ImportSpecifier */; + case 221 /* SpreadElement */: + case 197 /* ObjectBindingPattern */: + case 199 /* BindingElement */: return false; case 78 /* Identifier */: - return parent.kind !== 198 /* BindingElement */ && - parent.kind !== 265 /* ImportSpecifier */ && - parent.kind !== 270 /* ExportSpecifier */; + return parent.kind !== 199 /* BindingElement */ && + parent.kind !== 266 /* ImportSpecifier */ && + parent.kind !== 271 /* ExportSpecifier */; } return true; } function isBlockLike(node) { switch (node.kind) { - case 230 /* Block */: - case 297 /* SourceFile */: - case 257 /* ModuleBlock */: - case 284 /* CaseClause */: + case 231 /* Block */: + case 298 /* SourceFile */: + case 258 /* ModuleBlock */: + case 285 /* CaseClause */: return true; default: return false; @@ -146074,7 +150571,7 @@ var ts; if (ts.isTypeReferenceNode(node)) { if (ts.isIdentifier(node.typeName)) { var symbol = checker.resolveName(node.typeName.text, node.typeName, 262144 /* TypeParameter */, /* excludeGlobals */ true); - if (symbol) { + if (symbol === null || symbol === void 0 ? void 0 : symbol.declarations) { var declaration = ts.cast(ts.first(symbol.declarations), ts.isTypeParameterDeclaration); if (rangeContainsSkipTrivia(statement, declaration, file) && !rangeContainsSkipTrivia(selection, declaration, file)) { ts.pushIfUnique(result, declaration); @@ -146097,7 +150594,7 @@ var ts; else if (ts.isTypeQueryNode(node)) { if (ts.isIdentifier(node.exprName)) { var symbol = checker.resolveName(node.exprName.text, node.exprName, 111551 /* Value */, /* excludeGlobals */ false); - if (symbol && rangeContainsSkipTrivia(statement, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) { + if ((symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) && rangeContainsSkipTrivia(statement, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) { return true; } } @@ -146317,11 +150814,11 @@ var ts; } function isPureImport(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return true; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return !ts.hasSyntacticModifier(node, 1 /* Export */); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); default: return false; @@ -146382,10 +150879,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_17 = function (sourceFile) { + var _loop_18 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_18 = function (statement) { + var _loop_19 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -146407,22 +150904,22 @@ var ts; }; for (var _b = 0, _c = sourceFile.statements; _b < _c.length; _b++) { var statement = _c[_b]; - _loop_18(statement); + _loop_19(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_17(sourceFile); + _loop_18(sourceFile); } } function getNamespaceLikeImport(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 263 /* NamespaceImport */ ? + case 262 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 264 /* NamespaceImport */ ? node.importClause.namedBindings.name : undefined; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return node.name; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return ts.tryCast(node.name, ts.isIdentifier); default: return ts.Debug.assertNever(node, "Unexpected node kind " + node.kind); @@ -146453,20 +150950,20 @@ var ts; var newNamespaceId = ts.factory.createIdentifier(newNamespaceName); var newModuleString = ts.factory.createStringLiteral(newModuleSpecifier); switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamespaceImport(newNamespaceId)), newModuleString); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return ts.factory.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, newNamespaceId, ts.factory.createExternalModuleReference(newModuleString)); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return ts.factory.createVariableDeclaration(newNamespaceId, /*exclamationToken*/ undefined, /*type*/ undefined, createRequireCall(newModuleString)); default: return ts.Debug.assertNever(node, "Unexpected node kind " + node.kind); } } function moduleSpecifierFromImport(i) { - return (i.kind === 261 /* ImportDeclaration */ ? i.moduleSpecifier - : i.kind === 260 /* ImportEqualsDeclaration */ ? i.moduleReference.expression + return (i.kind === 262 /* ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 261 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]); } function forEachImportInStatement(statement, cb) { @@ -146536,15 +151033,15 @@ var ts; } function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { switch (importDecl.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); break; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: if (isUnused(importDecl.name)) { changes.delete(sourceFile, importDecl); } break; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); break; default: @@ -146557,7 +151054,7 @@ var ts; var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; var defaultUnused = !name || isUnused(name); var namedBindingsUnused = !namedBindings || - (namedBindings.kind === 263 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); + (namedBindings.kind === 264 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); if (defaultUnused && namedBindingsUnused) { changes.delete(sourceFile, importDecl); } @@ -146569,7 +151066,7 @@ var ts; if (namedBindingsUnused) { changes.replaceNode(sourceFile, importDecl.importClause, ts.factory.updateImportClause(importDecl.importClause, importDecl.importClause.isTypeOnly, name, /*namedBindings*/ undefined)); } - else if (namedBindings.kind === 264 /* NamedImports */) { + else if (namedBindings.kind === 265 /* NamedImports */) { for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { var element = _b[_i]; if (isUnused(element.name)) @@ -146587,9 +151084,9 @@ var ts; changes.delete(sourceFile, name); } break; - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: break; - case 196 /* ObjectBindingPattern */: + case 197 /* ObjectBindingPattern */: if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); } @@ -146617,6 +151114,9 @@ var ts; var oldFileNamedImports = []; var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`. newFileImportsFromOldFile.forEach(function (symbol) { + if (!symbol.declarations) { + return; + } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; if (!isTopLevelDeclaration(decl)) @@ -146716,14 +151216,14 @@ var ts; // Below should all be utilities function isInImport(decl) { switch (decl.kind) { - case 260 /* ImportEqualsDeclaration */: - case 265 /* ImportSpecifier */: - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: + case 261 /* ImportEqualsDeclaration */: + case 266 /* ImportSpecifier */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: return true; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return isVariableDeclarationInImport(decl); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); default: return false; @@ -146735,7 +151235,7 @@ var ts; } function filterImport(i, moduleSpecifier, keep) { switch (i.kind) { - case 261 /* ImportDeclaration */: { + case 262 /* ImportDeclaration */: { var clause = i.importClause; if (!clause) return undefined; @@ -146745,9 +151245,9 @@ var ts; ? ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImport, namedBindings), moduleSpecifier) : undefined; } - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return keep(i.name) ? i : undefined; - case 249 /* VariableDeclaration */: { + case 250 /* VariableDeclaration */: { var name = filterBindingName(i.name, keep); return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; } @@ -146756,7 +151256,7 @@ var ts; } } function filterNamedBindings(namedBindings, keep) { - if (namedBindings.kind === 263 /* NamespaceImport */) { + if (namedBindings.kind === 264 /* NamespaceImport */) { return keep(namedBindings.name) ? namedBindings : undefined; } else { @@ -146768,9 +151268,9 @@ var ts; switch (name.kind) { case 78 /* Identifier */: return keep(name) ? name : undefined; - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: return name; - case 196 /* ObjectBindingPattern */: { + case 197 /* ObjectBindingPattern */: { // We can't handle nested destructurings or property names well here, so just copy them all. var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); return newElements.length ? ts.factory.createObjectBindingPattern(newElements) : undefined; @@ -146827,13 +151327,13 @@ var ts; } function isNonVariableTopLevelDeclaration(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 261 /* ImportEqualsDeclaration */: return true; default: return false; @@ -146841,17 +151341,17 @@ var ts; } function forEachTopLevelDeclaration(statement, cb) { switch (statement.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 261 /* ImportEqualsDeclaration */: return cb(statement); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return ts.firstDefined(statement.declarationList.declarations, function (decl) { return forEachTopLevelDeclarationInBindingName(decl.name, cb); }); - case 233 /* ExpressionStatement */: { + case 234 /* ExpressionStatement */: { var expression = statement.expression; return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) @@ -146863,8 +151363,8 @@ var ts; switch (name.kind) { case 78 /* Identifier */: return cb(ts.cast(name.parent, function (x) { return ts.isVariableDeclaration(x) || ts.isBindingElement(x); })); - case 197 /* ArrayBindingPattern */: - case 196 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: return ts.firstDefined(name.elements, function (em) { return ts.isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb); }); default: return ts.Debug.assertNever(name, "Unexpected name kind " + name.kind); @@ -146875,9 +151375,9 @@ var ts; } function getTopLevelDeclarationStatement(d) { switch (d.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return d.parent.parent; - case 198 /* BindingElement */: + case 199 /* BindingElement */: return getTopLevelDeclarationStatement(ts.cast(d.parent.parent, function (p) { return ts.isVariableDeclaration(p) || ts.isBindingElement(p); })); default: return d; @@ -146910,23 +151410,23 @@ var ts; function addEs6Export(d) { var modifiers = ts.concatenate([ts.factory.createModifier(92 /* ExportKeyword */)], d.modifiers); switch (d.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return ts.factory.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return ts.factory.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return ts.factory.updateVariableStatement(d, modifiers, d.declarationList); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return ts.factory.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return ts.factory.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return ts.factory.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return ts.factory.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return ts.factory.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.isTypeOnly, d.name, d.moduleReference); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(d, "Unexpected declaration kind " + d.kind); @@ -146937,18 +151437,18 @@ var ts; } function getNamesToExportInCommonJS(decl) { switch (decl.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: return [decl.name.text]; // TODO: GH#18217 - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 261 /* ImportEqualsDeclaration */: return ts.emptyArray; - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return ts.Debug.fail("Can't export an ExpressionStatement"); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(decl, "Unexpected decl kind " + decl.kind); @@ -147117,13 +151617,13 @@ var ts; return { edits: [] }; // TODO: GH#30113 } function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) { - var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); - changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ", - // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter - indentation: 0, - leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include - }); + var signature = groupedReferences.signature; + var newFunctionDeclarationParams = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); + if (signature) { + var newSignatureParams = ts.map(createNewParameters(signature, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); + replaceParameters(signature, newSignatureParams); + } + replaceParameters(functionDeclaration, newFunctionDeclarationParams); var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); }); for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) { var call = functionCalls_1[_i]; @@ -147132,6 +151632,15 @@ var ts; changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include }); } } + function replaceParameters(declarationOrSignature, parameterDeclarations) { + changes.replaceNodeRangeWithNodes(sourceFile, ts.first(declarationOrSignature.parameters), ts.last(declarationOrSignature.parameters), parameterDeclarations, { + joiner: ", ", + // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter + indentation: 0, + leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include + }); + } } function getGroupedReferences(functionDeclaration, program, cancellationToken) { var functionNames = getFunctionNames(functionDeclaration); @@ -147150,12 +151659,38 @@ var ts; var functionSymbols = ts.map(functionNames, getSymbolTargetAtLocation); var classSymbols = ts.map(classNames, getSymbolTargetAtLocation); var isConstructor = ts.isConstructorDeclaration(functionDeclaration); + var contextualSymbols = ts.map(functionNames, function (name) { return getSymbolForContextualType(name, checker); }); for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) { var entry = referenceEntries_1[_i]; - if (entry.kind !== 1 /* Node */) { + if (entry.kind === 0 /* Span */) { groupedReferences.valid = false; continue; } + /* Declarations in object literals may be implementations of method signatures which have a different symbol from the declaration + For example: + interface IFoo { m(a: number): void } + const foo: IFoo = { m(a: number): void {} } + In these cases we get the symbol for the signature from the contextual type. + */ + if (ts.contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) { + if (isValidMethodSignature(entry.node.parent)) { + groupedReferences.signature = entry.node.parent; + continue; + } + var call = entryToFunctionCall(entry); + if (call) { + groupedReferences.functionCalls.push(call); + continue; + } + } + var contextualSymbol = getSymbolForContextualType(entry.node, checker); + if (contextualSymbol && ts.contains(contextualSymbols, contextualSymbol)) { + var decl = entryToDeclaration(entry); + if (decl) { + groupedReferences.declarations.push(decl); + continue; + } + } /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function. Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test: class A { foo(a: number, b: number) { return a + b; } } @@ -147218,6 +151753,19 @@ var ts; return symbol && ts.getSymbolTarget(symbol, checker); } } + /** + * Gets the symbol for the contextual type of the node if it is not a union or intersection. + */ + function getSymbolForContextualType(node, checker) { + var element = ts.getContainingObjectLiteralElement(node); + if (element) { + var contextualType = checker.getContextualTypeForObjectLiteralElement(element); + var symbol = contextualType === null || contextualType === void 0 ? void 0 : contextualType.getSymbol(); + if (symbol && !(ts.getCheckFlags(symbol) & 6 /* Synthetic */)) { + return symbol; + } + } + } function entryToImportOrExport(entry) { var node = entry.node; if (ts.isImportSpecifier(node.parent) @@ -147243,15 +151791,15 @@ var ts; var parent = functionReference.parent; switch (parent.kind) { // foo(...) or super(...) or new Foo(...) - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: var callOrNewExpression = ts.tryCast(parent, ts.isCallOrNewExpression); if (callOrNewExpression && callOrNewExpression.expression === functionReference) { return callOrNewExpression; } break; // x.foo(...) - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression); if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { var callOrNewExpression_1 = ts.tryCast(propertyAccessExpression.parent, ts.isCallOrNewExpression); @@ -147261,7 +151809,7 @@ var ts; } break; // x["foo"](...) - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression); if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { var callOrNewExpression_2 = ts.tryCast(elementAccessExpression.parent, ts.isCallOrNewExpression); @@ -147280,14 +151828,14 @@ var ts; var parent = reference.parent; switch (parent.kind) { // `C.foo` - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression); if (propertyAccessExpression && propertyAccessExpression.expression === reference) { return propertyAccessExpression; } break; // `C["foo"]` - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression); if (elementAccessExpression && elementAccessExpression.expression === reference) { return elementAccessExpression; @@ -147325,15 +151873,24 @@ var ts; } return false; } + function isValidMethodSignature(node) { + return ts.isMethodSignature(node) && (ts.isInterfaceDeclaration(node.parent) || ts.isTypeLiteralNode(node.parent)); + } function isValidFunctionDeclaration(functionDeclaration, checker) { + var _a; if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false; switch (functionDeclaration.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: + if (ts.isObjectLiteralExpression(functionDeclaration.parent)) { + var contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker); + // don't offer the refactor when there are multiple signatures since we won't know which ones the user wants to change + return ((_a = contextualSymbol === null || contextualSymbol === void 0 ? void 0 : contextualSymbol.declarations) === null || _a === void 0 ? void 0 : _a.length) === 1 && isSingleImplementation(functionDeclaration, checker); + } return isSingleImplementation(functionDeclaration, checker); - case 166 /* Constructor */: + case 167 /* Constructor */: if (ts.isClassDeclaration(functionDeclaration.parent)) { return hasNameOrDefault(functionDeclaration.parent) && isSingleImplementation(functionDeclaration, checker); } @@ -147341,8 +151898,8 @@ var ts; return isValidVariableDeclaration(functionDeclaration.parent.parent) && isSingleImplementation(functionDeclaration, checker); } - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return isValidVariableDeclaration(functionDeclaration.parent); } return false; @@ -147492,7 +152049,7 @@ var ts; } function getClassNames(constructorDeclaration) { switch (constructorDeclaration.parent.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: var classDeclaration = constructorDeclaration.parent; if (classDeclaration.name) return [classDeclaration.name]; @@ -147500,7 +152057,7 @@ var ts; // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault` var defaultModifier = ts.Debug.checkDefined(ts.findModifier(classDeclaration, 87 /* DefaultKeyword */), "Nameless class declaration should be a default export"); return [defaultModifier]; - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: var classExpression = constructorDeclaration.parent; var variableDeclaration = constructorDeclaration.parent.parent; var className = classExpression.name; @@ -147511,25 +152068,25 @@ var ts; } function getFunctionNames(functionDeclaration) { switch (functionDeclaration.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: if (functionDeclaration.name) return [functionDeclaration.name]; // If the function declaration doesn't have a name, it should have a default modifier. // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault` var defaultModifier = ts.Debug.checkDefined(ts.findModifier(functionDeclaration, 87 /* DefaultKeyword */), "Nameless function declaration should be a default export"); return [defaultModifier]; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return [functionDeclaration.name]; - case 166 /* Constructor */: + case 167 /* Constructor */: var ctrKeyword = ts.Debug.checkDefined(ts.findChildOfKind(functionDeclaration, 132 /* ConstructorKeyword */, functionDeclaration.getSourceFile()), "Constructor declaration should have constructor keyword"); - if (functionDeclaration.parent.kind === 221 /* ClassExpression */) { + if (functionDeclaration.parent.kind === 222 /* ClassExpression */) { var variableDeclaration = functionDeclaration.parent.parent; return [variableDeclaration.name, ctrKeyword]; } return [ctrKeyword]; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return [functionDeclaration.parent.name]; - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: if (functionDeclaration.name) return [functionDeclaration.name, functionDeclaration.parent.name]; return [functionDeclaration.parent.name]; @@ -147620,11 +152177,11 @@ var ts; function getParentBinaryExpression(expr) { var container = ts.findAncestor(expr.parent, function (n) { switch (n.kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return false; - case 218 /* TemplateExpression */: - case 216 /* BinaryExpression */: + case 219 /* TemplateExpression */: + case 217 /* BinaryExpression */: return !(ts.isBinaryExpression(n.parent) && isNotEqualsOperator(n.parent)); default: return "quit"; @@ -147701,7 +152258,7 @@ var ts; var templateSpans = []; var templateHead = ts.factory.createTemplateHead(headText); copyCommentFromStringLiterals(headIndexes, templateHead); - var _loop_19 = function (i) { + var _loop_20 = function (i) { var currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); copyOperatorComments(i, currentNode); var _c = concatConsecutiveString(i + 1, nodes), newIndex = _c[0], subsequentText = _c[1], stringIndexes = _c[2]; @@ -147725,7 +152282,7 @@ var ts; }; var out_i_1; for (var i = begin; i < nodes.length; i++) { - _loop_19(i); + _loop_20(i); i = out_i_1; } return ts.factory.createTemplateExpression(templateHead, templateSpans); @@ -147925,7 +152482,9 @@ var ts; var body = convertToBlock(func.body); var variableDeclaration = variableInfo.variableDeclaration, variableDeclarationList = variableInfo.variableDeclarationList, statement = variableInfo.statement, name = variableInfo.name; ts.suppressLeadingTrivia(statement); - var newNode = ts.factory.createFunctionDeclaration(func.decorators, statement.modifiers, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); + var modifiersFlags = (ts.getCombinedModifierFlags(variableDeclaration) & 1 /* Export */) | ts.getEffectiveModifierFlags(func); + var modifiers = ts.factory.createModifiersFromModifierFlags(modifiersFlags); + var newNode = ts.factory.createFunctionDeclaration(func.decorators, ts.length(modifiers) ? modifiers : undefined, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); if (variableDeclarationList.declarations.length === 1) { return ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, statement, newNode); }); } @@ -147983,9 +152542,7 @@ var ts; function getEditsForAction(context) { var info = getInfo(context); if (info && !refactor.isRefactorErrorInfo(info)) { - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { - return t.tryInsertTypeAnnotation(context.file, info.declaration, info.returnTypeNode); - }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, t, info.declaration, info.returnTypeNode); }); return { renameFilename: undefined, renameLocation: undefined, edits: edits }; } return undefined; @@ -148010,11 +152567,26 @@ var ts; } return ts.emptyArray; } + function doChange(sourceFile, changes, declaration, typeNode) { + var closeParen = ts.findChildOfKind(declaration, 21 /* CloseParenToken */, sourceFile); + var needParens = ts.isArrowFunction(declaration) && closeParen === undefined; + var endNode = needParens ? ts.first(declaration.parameters) : closeParen; + if (endNode) { + if (needParens) { + changes.insertNodeBefore(sourceFile, endNode, ts.factory.createToken(20 /* OpenParenToken */)); + changes.insertNodeAfter(sourceFile, endNode, ts.factory.createToken(21 /* CloseParenToken */)); + } + changes.insertNodeAt(sourceFile, endNode.end, typeNode, { prefix: ": " }); + } + } function getInfo(context) { if (ts.isInJSFile(context.file) || !refactor.refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind)) return; var token = ts.getTokenAtPosition(context.file, context.startPosition); - var declaration = ts.findAncestor(token, isConvertibleDeclaration); + var declaration = ts.findAncestor(token, function (n) { + return ts.isBlock(n) || n.parent && ts.isArrowFunction(n.parent) && (n.kind === 38 /* EqualsGreaterThanToken */ || n.parent.body === n) ? "quit" : + isConvertibleDeclaration(n); + }); if (!declaration || !declaration.body || declaration.type) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Return_type_must_be_inferred_from_a_function) }; } @@ -148023,7 +152595,6 @@ var ts; if (!returnType) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_determine_function_return_type) }; } - ; var returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, 1 /* NoTruncation */); if (returnTypeNode) { return { declaration: declaration, returnTypeNode: returnTypeNode }; @@ -148031,10 +152602,10 @@ var ts; } function isConvertibleDeclaration(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: return true; default: return false; @@ -148136,8 +152707,8 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 301 /* FirstJSDocNode */ || kid.kind > 333 /* LastJSDocNode */; }); - return child.kind < 157 /* FirstNode */ ? + var child = ts.find(children, function (kid) { return kid.kind < 302 /* FirstJSDocNode */ || kid.kind > 337 /* LastJSDocNode */; }); + return child.kind < 158 /* FirstNode */ ? child : child.getFirstToken(sourceFile); }; @@ -148148,7 +152719,7 @@ var ts; if (!child) { return undefined; } - return child.kind < 157 /* FirstNode */ ? child : child.getLastToken(sourceFile); + return child.kind < 158 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { return ts.forEachChild(this, cbNode, cbNodeArray); @@ -148206,11 +152777,11 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(334 /* SyntaxList */, nodes.pos, nodes.end, parent); + var list = createNode(338 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { - var node = nodes_1[_i]; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; addSyntheticNodes(list._children, pos, node.pos, parent); list._children.push(node); pos = node.end; @@ -148317,13 +152888,13 @@ var ts; }; SymbolObject.prototype.getContextualDocumentationComment = function (context, checker) { switch (context === null || context === void 0 ? void 0 : context.kind) { - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: if (!this.contextualGetAccessorDocumentationComment) { this.contextualGetAccessorDocumentationComment = ts.emptyArray; this.contextualGetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isGetAccessor), checker); } return this.contextualGetAccessorDocumentationComment; - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: if (!this.contextualSetAccessorDocumentationComment) { this.contextualSetAccessorDocumentationComment = ts.emptyArray; this.contextualSetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isSetAccessor), checker); @@ -148333,9 +152904,9 @@ var ts; return this.getDocumentationComment(checker); } }; - SymbolObject.prototype.getJsDocTags = function () { + SymbolObject.prototype.getJsDocTags = function (checker) { if (this.tags === undefined) { - this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations); + this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations, checker); } return this.tags; }; @@ -148496,7 +153067,7 @@ var ts; }; SignatureObject.prototype.getJsDocTags = function () { if (this.jsDocTags === undefined) { - this.jsDocTags = this.declaration ? getJsDocTags([this.declaration], this.checker) : []; + this.jsDocTags = this.declaration ? getJsDocTagsOfSignature(this.declaration, this.checker) : []; } return this.jsDocTags; }; @@ -148510,29 +153081,34 @@ var ts; function hasJSDocInheritDocTag(node) { return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); } - function getJsDocTags(declarations, checker) { - var tags = ts.JsDoc.getJsDocTagsFromDeclarations(declarations); - if (tags.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - ts.forEachUnique(declarations, function (declaration) { - var inheritedTags = findBaseOfDeclaration(checker, declaration, function (symbol) { return symbol.getJsDocTags(); }); - if (inheritedTags) { - tags = __spreadArray(__spreadArray([], inheritedTags), tags); - } - }); + function getJsDocTagsOfSignature(declaration, checker) { + var tags = ts.JsDoc.getJsDocTagsFromDeclarations([declaration], checker); + if (tags.length === 0 || hasJSDocInheritDocTag(declaration)) { + var inheritedTags = findBaseOfDeclaration(checker, declaration, function (symbol) { var _a; return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) === 1 ? symbol.getJsDocTags() : undefined; }); + if (inheritedTags) { + tags = __spreadArray(__spreadArray([], inheritedTags), tags); + } } return tags; } function getDocumentationComment(declarations, checker) { if (!declarations) return ts.emptyArray; - var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); + var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations, checker); if (checker && (doc.length === 0 || declarations.some(hasJSDocInheritDocTag))) { - ts.forEachUnique(declarations, function (declaration) { - var inheritedDocs = findBaseOfDeclaration(checker, declaration, function (symbol) { return symbol.getDocumentationComment(checker); }); + var seenSymbols_1 = new ts.Set(); + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; + var inheritedDocs = findBaseOfDeclaration(checker, declaration, function (symbol) { + if (!seenSymbols_1.has(symbol)) { + seenSymbols_1.add(symbol); + return symbol.getDocumentationComment(checker); + } + }); // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); - }); + } } return doc; } @@ -148546,7 +153122,7 @@ var ts; __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { var _this = _super.call(this, kind, pos, end) || this; - _this.kind = 297 /* SourceFile */; + _this.kind = 298 /* SourceFile */; return _this; } SourceFileObject.prototype.update = function (newText, textChangeRange) { @@ -148605,10 +153181,10 @@ var ts; } function visit(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -148628,31 +153204,31 @@ var ts; } ts.forEachChild(node, visit); break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: - case 256 /* ModuleDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 270 /* ExportSpecifier */: - case 265 /* ImportSpecifier */: - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 177 /* TypeLiteral */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 257 /* ModuleDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 271 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 178 /* TypeLiteral */: addDeclaration(node); ts.forEachChild(node, visit); break; - case 160 /* Parameter */: + case 161 /* Parameter */: // Only consider parameter properties - if (!ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) { + if (!ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { break; } // falls through - case 249 /* VariableDeclaration */: - case 198 /* BindingElement */: { + case 250 /* VariableDeclaration */: + case 199 /* BindingElement */: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -148663,12 +153239,12 @@ var ts; } } // falls through - case 291 /* EnumMember */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 292 /* EnumMember */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: addDeclaration(node); break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; var exportDeclaration = node; @@ -148681,7 +153257,7 @@ var ts; } } break; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -148693,7 +153269,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 263 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 264 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -148702,7 +153278,7 @@ var ts; } } break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } @@ -148796,15 +153372,7 @@ var ts; var fileName = rootFileNames_1[_i]; this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName)); } - // store the compilation settings - this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); } - HostCache.prototype.compilationSettings = function () { - return this._compilationSettings; - }; - HostCache.prototype.getProjectReferences = function () { - return this.host.getProjectReferences && this.host.getProjectReferences(); - }; HostCache.prototype.createEntry = function (fileName, path) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); @@ -148954,7 +153522,7 @@ var ts; }; CancellationTokenObject.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { - ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "CancellationTokenObject" }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "CancellationTokenObject" }); throw new ts.OperationCanceledException(); } }; @@ -148984,7 +153552,7 @@ var ts; }; ThrottledCancellationToken.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { - ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "ThrottledCancellationToken" }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "ThrottledCancellationToken" }); throw new ts.OperationCanceledException(); } }; @@ -149084,7 +153652,7 @@ var ts; return sourceFile; } function synchronizeHostData() { - var _a, _b; + var _a, _b, _c; ts.Debug.assert(languageServiceMode !== ts.LanguageServiceMode.Syntactic); // perform fast check if host supports it if (host.getProjectVersion) { @@ -149105,11 +153673,22 @@ var ts; // Get a fresh cache of the host information var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); + var newSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; var hasChangedAutomaticTypeDirectiveNames = ts.maybeBind(host, host.hasChangedAutomaticTypeDirectiveNames); - var projectReferences = hostCache.getProjectReferences(); + var projectReferences = (_b = host.getProjectReferences) === null || _b === void 0 ? void 0 : _b.call(host); + var parsedCommandLines; + var parseConfigHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: readFile, + readDirectory: readDirectory, + trace: ts.maybeBind(host, host.trace), + getCurrentDirectory: function () { return currentDirectory; }, + onUnRecoverableConfigFileDiagnostic: ts.noop, + }; // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (_path, fileName) { return host.getScriptVersion(fileName); }, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { + if (ts.isProgramUptoDate(program, rootFileNames, newSettings, function (_path, fileName) { return host.getScriptVersion(fileName); }, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -149117,7 +153696,6 @@ var ts; // instance. If we cancel midway through, we may end up in an inconsistent state where // the program points to old source files that have been invalidated because of // incremental parsing. - var newSettings = hostCache.compilationSettings(); // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -149139,19 +153717,18 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, - readDirectory: function (path, extensions, exclude, include, depth) { - ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); - return host.readDirectory(path, extensions, exclude, include, depth); - }, + readDirectory: readDirectory, onReleaseOldSourceFile: onReleaseOldSourceFile, + onReleaseParsedCommandLine: onReleaseParsedCommandLine, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: hasChangedAutomaticTypeDirectiveNames, - trace: ts.maybeBind(host, host.trace), + trace: parseConfigHost.trace, resolveModuleNames: ts.maybeBind(host, host.resolveModuleNames), resolveTypeReferenceDirectives: ts.maybeBind(host, host.resolveTypeReferenceDirectives), useSourceOfProjectReferenceRedirect: ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect), + getParsedCommandLine: getParsedCommandLine, }; - (_b = host.setCompilerHost) === null || _b === void 0 ? void 0 : _b.call(host, compilerHost); + (_c = host.setCompilerHost) === null || _c === void 0 ? void 0 : _c.call(host, compilerHost); var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); var options = { rootNames: rootFileNames, @@ -149164,6 +153741,7 @@ var ts; // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. // It needs to be cleared to allow all collected snapshots to be released hostCache = undefined; + parsedCommandLines = undefined; // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during // the course of whatever called `synchronizeHostData` @@ -149172,6 +153750,36 @@ var ts; // pointers set property. program.getTypeChecker(); return; + function getParsedCommandLine(fileName) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var existing = parsedCommandLines === null || parsedCommandLines === void 0 ? void 0 : parsedCommandLines.get(path); + if (existing !== undefined) + return existing || undefined; + var result = host.getParsedCommandLine ? + host.getParsedCommandLine(fileName) : + getParsedCommandLineOfConfigFileUsingSourceFile(fileName); + (parsedCommandLines || (parsedCommandLines = new ts.Map())).set(path, result || false); + return result; + } + function getParsedCommandLineOfConfigFileUsingSourceFile(configFileName) { + var result = getOrCreateSourceFile(configFileName, 100 /* JSON */); + if (!result) + return undefined; + result.path = ts.toPath(configFileName, currentDirectory, getCanonicalFileName); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; + return ts.parseJsonSourceFileConfigFileContent(result, parseConfigHost, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), + /*optionsToExtend*/ undefined, ts.getNormalizedAbsolutePath(configFileName, currentDirectory)); + } + function onReleaseParsedCommandLine(configFileName, oldResolvedRef, oldOptions) { + var _a; + if (host.getParsedCommandLine) { + (_a = host.onReleaseParsedCommandLine) === null || _a === void 0 ? void 0 : _a.call(host, configFileName, oldResolvedRef, oldOptions); + } + else if (oldResolvedRef) { + onReleaseOldSourceFile(oldResolvedRef.sourceFile, oldOptions); + } + } function fileExists(fileName) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = hostCache && hostCache.getEntryByPath(path); @@ -149188,11 +153796,15 @@ var ts; } return host.readFile && host.readFile(fileName); } + function readDirectory(path, extensions, exclude, include, depth) { + ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + } // Release any files we have acquired in the old program but are // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind); } function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); @@ -149237,8 +153849,13 @@ var ts; // We do not support the scenario where a host can modify a registered // file's script kind, i.e. in one project some file is treated as ".ts" // and in another as ".js" - ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind."); - return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + if (hostFileInformation.scriptKind === oldSourceFile.scriptKind) { + return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + } + else { + // Release old source file and fall through to aquire new file with new script kind + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind); + } } // We didn't already have the file. Fall through and acquire it from the registry. } @@ -149267,7 +153884,7 @@ var ts; // Use paths to ensure we are using correct key and paths as document registry could be created with different current directory than host var key_1 = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()); ts.forEach(program.getSourceFiles(), function (f) { - return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1); + return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1, f.scriptKind); }); program = undefined; // TODO: GH#18217 } @@ -149310,10 +153927,10 @@ var ts; synchronizeHostData(); return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter); } - function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { + function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences, data) { if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions, host)), // TODO: GH#18217 + return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source, data: data }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions, host)), // TODO: GH#18217 preferences, cancellationToken); } function getCompletionEntrySymbol(fileName, position, name, source, preferences) { @@ -149340,7 +153957,7 @@ var ts; textSpan: ts.createTextSpanFromNode(nodeForQuickInfo, sourceFile), displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_2, ts.getContainerNode(nodeForQuickInfo)); }), documentation: type_2.symbol ? type_2.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_2.symbol ? type_2.symbol.getJsDocTags() : undefined + tags: type_2.symbol ? type_2.symbol.getJsDocTags(typeChecker) : undefined }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { @@ -149359,19 +153976,23 @@ var ts; if (ts.isNewExpression(node.parent) && node.pos === node.parent.pos) { return node.parent.expression; } + if (ts.isNamedTupleMember(node.parent) && node.pos === node.parent.pos) { + return node.parent; + } return node; } function shouldGetType(sourceFile, node, position) { switch (node.kind) { case 78 /* Identifier */: - return !ts.isLabelName(node) && !ts.isTagName(node); - case 201 /* PropertyAccessExpression */: - case 157 /* QualifiedName */: + return !ts.isLabelName(node) && !ts.isTagName(node) && !ts.isConstTypeReference(node.parent); + case 202 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: // Don't return quickInfo if inside the comment in `a/**/.b` return !ts.isInComment(sourceFile, position); case 107 /* ThisKeyword */: - case 187 /* ThisType */: + case 188 /* ThisType */: case 105 /* SuperKeyword */: + case 193 /* NamedTupleMember */: return true; default: return false; @@ -149476,15 +154097,15 @@ var ts; return undefined; } switch (node.kind) { - case 201 /* PropertyAccessExpression */: - case 157 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: case 10 /* StringLiteral */: case 94 /* FalseKeyword */: case 109 /* TrueKeyword */: case 103 /* NullKeyword */: case 105 /* SuperKeyword */: case 107 /* ThisKeyword */: - case 187 /* ThisType */: + case 188 /* ThisType */: case 78 /* Identifier */: break; // Cant create the text span @@ -149501,7 +154122,7 @@ var ts; // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module - if (nodeForStartPos.parent.parent.kind === 256 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 257 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -149529,15 +154150,7 @@ var ts; function getNavigationTree(fileName) { return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); } - function isTsOrTsxFile(fileName) { - var kind = ts.getScriptKind(fileName, host); - return kind === 3 /* TS */ || kind === 4 /* TSX */; - } function getSemanticClassifications(fileName, span, format) { - if (!isTsOrTsxFile(fileName)) { - // do not run semantic classification on non-ts-or-tsx files - return []; - } synchronizeHostData(); var responseFormat = format || "original" /* Original */; if (responseFormat === "2020" /* TwentyTwenty */) { @@ -149548,10 +154161,6 @@ var ts; } } function getEncodedSemanticClassifications(fileName, span, format) { - if (!isTsOrTsxFile(fileName)) { - // do not run semantic classification on non-ts-or-tsx files - return { spans: [], endOfLineState: 0 /* None */ }; - } synchronizeHostData(); var responseFormat = format || "original" /* Original */; if (responseFormat === "original" /* Original */) { @@ -149642,13 +154251,13 @@ var ts; var formatContext = ts.formatting.getFormatContext(formatOptions, host); return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } - function organizeImports(scope, formatOptions, preferences) { + function organizeImports(args, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); - ts.Debug.assert(scope.type === "file"); - var sourceFile = getValidSourceFile(scope.fileName); + ts.Debug.assert(args.type === "file"); + var sourceFile = getValidSourceFile(args.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions, host); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, args.skipDestructiveCodeActions); } function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } @@ -149665,8 +154274,8 @@ var ts; ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); } - function getDocCommentTemplateAtPosition(fileName, position) { - return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); + function getDocCommentTemplateAtPosition(fileName, position, options) { + return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position, options); } function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too @@ -150081,6 +154690,16 @@ var ts; var file = getValidSourceFile(fileName); return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName); } + function toLineColumnOffset(fileName, position) { + // Go to Definition supports returning a zero-length span at position 0 for + // non-existent files. We need to special-case the conversion of position 0 + // to avoid a crash trying to get the text for that file, since this function + // otherwise assumes that 'fileName' is the name of a file that exists. + if (position === 0) { + return { line: 0, character: 0 }; + } + return sourceMapper.toLineColumnOffset(fileName, position); + } function prepareCallHierarchy(fileName, position) { synchronizeHostData(); var declarations = ts.CallHierarchy.resolveCallHierarchyDeclaration(program, ts.getTouchingPropertyName(getValidSourceFile(fileName), position)); @@ -150153,7 +154772,7 @@ var ts; getAutoImportProvider: getAutoImportProvider, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, - toLineColumnOffset: sourceMapper.toLineColumnOffset, + toLineColumnOffset: toLineColumnOffset, getSourceMapper: function () { return sourceMapper; }, clearSourceMapperCache: function () { return sourceMapper.clearCache(); }, prepareCallHierarchy: prepareCallHierarchy, @@ -150224,7 +154843,7 @@ var ts; */ function literalIsName(node) { return ts.isDeclarationName(node) || - node.parent.kind === 272 /* ExternalModuleReference */ || + node.parent.kind === 273 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } @@ -150242,13 +154861,13 @@ var ts; case 10 /* StringLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: - if (node.parent.kind === 158 /* ComputedPropertyName */) { + if (node.parent.kind === 159 /* ComputedPropertyName */) { return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through case 78 /* Identifier */: return ts.isObjectLiteralElement(node.parent) && - (node.parent.parent.kind === 200 /* ObjectLiteralExpression */ || node.parent.parent.kind === 281 /* JsxAttributes */) && + (node.parent.parent.kind === 201 /* ObjectLiteralExpression */ || node.parent.parent.kind === 282 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } return undefined; @@ -150290,7 +154909,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 202 /* ElementAccessExpression */ && + node.parent.kind === 203 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /** @@ -150370,114 +154989,114 @@ var ts; if (node) { var parent = node.parent; switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 249 /* VariableDeclaration */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 250 /* VariableDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return spanInVariableDeclaration(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return spanInParameterDeclaration(node); - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 166 /* Constructor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 167 /* Constructor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 230 /* Block */: + case 231 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // falls through - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return spanInBlock(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return spanInBlock(node.block); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: // Span on while(...) return textSpanEndingAtNextToken(node, node.expression); - case 235 /* DoStatement */: + case 236 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 248 /* DebuggerStatement */: + case 249 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 234 /* IfStatement */: + case 235 /* IfStatement */: // set on if(..) span return textSpanEndingAtNextToken(node, node.expression); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return spanInForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: // span of for (a in ...) return textSpanEndingAtNextToken(node, node.expression); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: // span in initializer return spanInInitializerOfForLike(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: // span on switch(...) return textSpanEndingAtNextToken(node, node.expression); - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 247 /* TryStatement */: + case 248 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } // falls through - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: - case 198 /* BindingElement */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: + case 199 /* BindingElement */: // span on complete node return textSpan(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: // span in statement return spanInNode(node.statement); - case 161 /* Decorator */: + case 162 /* Decorator */: return spanInNodeArray(parent.decorators); - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return undefined; // Tokens: case 26 /* SemicolonToken */: @@ -150507,7 +155126,7 @@ var ts; case 82 /* CatchKeyword */: case 95 /* FinallyKeyword */: return spanInNextNode(node); - case 156 /* OfKeyword */: + case 157 /* OfKeyword */: return spanInOfKeyword(node); default: // Destructuring pattern in destructuring assignment @@ -150520,13 +155139,13 @@ var ts; // `a` or `...c` or `d: x` from // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern if ((node.kind === 78 /* Identifier */ || - node.kind === 220 /* SpreadElement */ || - node.kind === 288 /* PropertyAssignment */ || - node.kind === 289 /* ShorthandPropertyAssignment */) && + node.kind === 221 /* SpreadElement */ || + node.kind === 289 /* PropertyAssignment */ || + node.kind === 290 /* ShorthandPropertyAssignment */) && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { return textSpan(node); } - if (node.kind === 216 /* BinaryExpression */) { + if (node.kind === 217 /* BinaryExpression */) { var _a = node, left = _a.left, operatorToken = _a.operatorToken; // Set breakpoint in destructuring pattern if its destructuring assignment // [a, b, c] or {a, b, c} of @@ -150548,22 +155167,22 @@ var ts; } if (ts.isExpressionNode(node)) { switch (parent.kind) { - case 235 /* DoStatement */: + case 236 /* DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); - case 161 /* Decorator */: + case 162 /* Decorator */: // Set breakpoint on the decorator emit return spanInNode(node.parent); - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: return textSpan(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (node.parent.operatorToken.kind === 27 /* CommaToken */) { // If this is a comma expression, the breakpoint is possible in this expression return textSpan(node); } break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: if (node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); @@ -150572,21 +155191,21 @@ var ts; } } switch (node.parent.kind) { - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // If this is name of property assignment, set breakpoint in the initializer if (node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } break; - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: // Breakpoint in type assertion goes to its operand if (node.parent.type === node) { return spanInNextNode(node.parent.type); } break; - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: { + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: { // initializer of variable/parameter declaration go to previous node var _b = node.parent, initializer = _b.initializer, type = _b.type; if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { @@ -150594,7 +155213,7 @@ var ts; } break; } - case 216 /* BinaryExpression */: { + case 217 /* BinaryExpression */: { var left = node.parent.left; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { // If initializer of destructuring assignment move to previous token @@ -150624,7 +155243,7 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 238 /* ForInStatement */) { + if (variableDeclaration.parent.parent.kind === 239 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } var parent = variableDeclaration.parent; @@ -150636,7 +155255,7 @@ var ts; // or its declaration from 'for of' if (variableDeclaration.initializer || ts.hasSyntacticModifier(variableDeclaration, 1 /* Export */) || - parent.parent.kind === 239 /* ForOfStatement */) { + parent.parent.kind === 240 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } if (ts.isVariableDeclarationList(variableDeclaration.parent) && @@ -150677,7 +155296,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasSyntacticModifier(functionDeclaration, 1 /* Export */) || - (functionDeclaration.parent.kind === 252 /* ClassDeclaration */ && functionDeclaration.kind !== 166 /* Constructor */); + (functionDeclaration.parent.kind === 253 /* ClassDeclaration */ && functionDeclaration.kind !== 167 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -150700,26 +155319,26 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // Set on parent if on same line otherwise on first statement // falls through - case 236 /* WhileStatement */: - case 234 /* IfStatement */: - case 238 /* ForInStatement */: + case 237 /* WhileStatement */: + case 235 /* IfStatement */: + case 239 /* ForInStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); // Set span on previous token if it starts on same line otherwise on the first statement of the block - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement return spanInNode(block.statements[0]); } function spanInInitializerOfForLike(forLikeStatement) { - if (forLikeStatement.initializer.kind === 250 /* VariableDeclarationList */) { + if (forLikeStatement.initializer.kind === 251 /* VariableDeclarationList */) { // Declaration list - set breakpoint in first declaration var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -150744,21 +155363,21 @@ var ts; } function spanInBindingPattern(bindingPattern) { // Set breakpoint in first binding element - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 222 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 223 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } // Empty binding pattern of binding element, set breakpoint on binding element - if (bindingPattern.parent.kind === 198 /* BindingElement */) { + if (bindingPattern.parent.kind === 199 /* BindingElement */) { return textSpan(bindingPattern.parent); } // Variable declaration is used as the span return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 197 /* ArrayBindingPattern */ && node.kind !== 196 /* ObjectBindingPattern */); - var elements = node.kind === 199 /* ArrayLiteralExpression */ ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 222 /* OmittedExpression */ ? element : undefined; }); + ts.Debug.assert(node.kind !== 198 /* ArrayBindingPattern */ && node.kind !== 197 /* ObjectBindingPattern */); + var elements = node.kind === 200 /* ArrayLiteralExpression */ ? node.elements : node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 223 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -150766,18 +155385,18 @@ var ts; // just nested element in another destructuring assignment // set breakpoint on assignment when parent is destructuring assignment // Otherwise set breakpoint for this element - return textSpan(node.parent.kind === 216 /* BinaryExpression */ ? node.parent : node); + return textSpan(node.parent.kind === 217 /* BinaryExpression */ ? node.parent : node); } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -150785,25 +155404,25 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: // If this is not an instantiated module block, no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } // falls through - case 255 /* EnumDeclaration */: - case 252 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 253 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 230 /* Block */: + case 231 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // falls through - case 287 /* CatchClause */: + case 288 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -150811,7 +155430,7 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 196 /* ObjectBindingPattern */: + case 197 /* ObjectBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -150827,7 +155446,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -150842,12 +155461,12 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 235 /* DoStatement */ || // Go to while keyword and do action instead - node.parent.kind === 203 /* CallExpression */ || - node.parent.kind === 204 /* NewExpression */) { + if (node.parent.kind === 236 /* DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 204 /* CallExpression */ || + node.parent.kind === 205 /* NewExpression */) { return spanInPreviousNode(node); } - if (node.parent.kind === 207 /* ParenthesizedExpression */) { + if (node.parent.kind === 208 /* ParenthesizedExpression */) { return spanInNextNode(node); } // Default to parent node @@ -150856,21 +155475,21 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 166 /* Constructor */: - case 236 /* WhileStatement */: - case 235 /* DoStatement */: - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 207 /* ParenthesizedExpression */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 167 /* Constructor */: + case 237 /* WhileStatement */: + case 236 /* DoStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 208 /* ParenthesizedExpression */: return spanInPreviousNode(node); // Default to parent node default: @@ -150880,20 +155499,20 @@ var ts; function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration if (ts.isFunctionLike(node.parent) || - node.parent.kind === 288 /* PropertyAssignment */ || - node.parent.kind === 160 /* Parameter */) { + node.parent.kind === 289 /* PropertyAssignment */ || + node.parent.kind === 161 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 206 /* TypeAssertionExpression */) { + if (node.parent.kind === 207 /* TypeAssertionExpression */) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 235 /* DoStatement */) { + if (node.parent.kind === 236 /* DoStatement */) { // Set span on while expression return textSpanEndingAtNextToken(node, node.parent.expression); } @@ -150901,7 +155520,7 @@ var ts; return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 239 /* ForOfStatement */) { + if (node.parent.kind === 240 /* ForOfStatement */) { // Set using next token return spanInNextNode(node); } @@ -151442,11 +156061,11 @@ var ts; return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); }); }; /** Get a string based representation of a completion list entry details */ - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences, data) { var _this = this; return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions); - return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences, data); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { @@ -151470,9 +156089,9 @@ var ts; return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); }); }; - LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { + LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); }); + return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position, options); }); }; /// NAVIGATE TO /** Return a list of symbols that are interesting to navigate to */ @@ -152179,6 +156798,7 @@ var ts; WatchFileKind["FixedPollingInterval"] = "FixedPollingInterval"; WatchFileKind["PriorityPollingInterval"] = "PriorityPollingInterval"; WatchFileKind["DynamicPriorityPolling"] = "DynamicPriorityPolling"; + WatchFileKind["FixedChunkSizePolling"] = "FixedChunkSizePolling"; WatchFileKind["UseFsEvents"] = "UseFsEvents"; WatchFileKind["UseFsEventsOnParentDirectory"] = "UseFsEventsOnParentDirectory"; })(WatchFileKind = protocol.WatchFileKind || (protocol.WatchFileKind = {})); @@ -152187,12 +156807,14 @@ var ts; WatchDirectoryKind["UseFsEvents"] = "UseFsEvents"; WatchDirectoryKind["FixedPollingInterval"] = "FixedPollingInterval"; WatchDirectoryKind["DynamicPriorityPolling"] = "DynamicPriorityPolling"; + WatchDirectoryKind["FixedChunkSizePolling"] = "FixedChunkSizePolling"; })(WatchDirectoryKind = protocol.WatchDirectoryKind || (protocol.WatchDirectoryKind = {})); var PollingWatchKind; (function (PollingWatchKind) { PollingWatchKind["FixedInterval"] = "FixedInterval"; PollingWatchKind["PriorityInterval"] = "PriorityInterval"; PollingWatchKind["DynamicPriority"] = "DynamicPriority"; + PollingWatchKind["FixedChunkSize"] = "FixedChunkSize"; })(PollingWatchKind = protocol.PollingWatchKind || (protocol.PollingWatchKind = {})); var IndentStyle; (function (IndentStyle) { @@ -152245,8 +156867,37 @@ var ts; ScriptTarget["ES2018"] = "ES2018"; ScriptTarget["ES2019"] = "ES2019"; ScriptTarget["ES2020"] = "ES2020"; + ScriptTarget["ES2021"] = "ES2021"; ScriptTarget["ESNext"] = "ESNext"; })(ScriptTarget = protocol.ScriptTarget || (protocol.ScriptTarget = {})); + var ClassificationType; + (function (ClassificationType) { + ClassificationType[ClassificationType["comment"] = 1] = "comment"; + ClassificationType[ClassificationType["identifier"] = 2] = "identifier"; + ClassificationType[ClassificationType["keyword"] = 3] = "keyword"; + ClassificationType[ClassificationType["numericLiteral"] = 4] = "numericLiteral"; + ClassificationType[ClassificationType["operator"] = 5] = "operator"; + ClassificationType[ClassificationType["stringLiteral"] = 6] = "stringLiteral"; + ClassificationType[ClassificationType["regularExpressionLiteral"] = 7] = "regularExpressionLiteral"; + ClassificationType[ClassificationType["whiteSpace"] = 8] = "whiteSpace"; + ClassificationType[ClassificationType["text"] = 9] = "text"; + ClassificationType[ClassificationType["punctuation"] = 10] = "punctuation"; + ClassificationType[ClassificationType["className"] = 11] = "className"; + ClassificationType[ClassificationType["enumName"] = 12] = "enumName"; + ClassificationType[ClassificationType["interfaceName"] = 13] = "interfaceName"; + ClassificationType[ClassificationType["moduleName"] = 14] = "moduleName"; + ClassificationType[ClassificationType["typeParameterName"] = 15] = "typeParameterName"; + ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName"; + ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName"; + ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName"; + ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName"; + ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName"; + ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName"; + ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; + ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; + ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; + ClassificationType[ClassificationType["bigintLiteral"] = 25] = "bigintLiteral"; + })(ClassificationType = protocol.ClassificationType || (protocol.ClassificationType = {})); })(protocol = server.protocol || (server.protocol = {})); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); @@ -152442,7 +157093,7 @@ var ts; if (this.pendingReloadFromDisk) { this.reloadWithFileText(); } - // At this point if svc is present its valid + // At this point if svc is present it's valid return this.svc; }; TextStorage.prototype.getOrLoadText = function () { @@ -152558,16 +157209,24 @@ var ts; ScriptInfo.prototype.getRealpathIfDifferent = function () { return this.realpath && this.realpath !== this.path ? this.realpath : undefined; }; + /** + * @internal + * Does not compute realpath; uses precomputed result. Use `ensureRealPath` + * first if a definite result is needed. + */ + ScriptInfo.prototype.isSymlink = function () { + return this.realpath && this.realpath !== this.path; + }; ScriptInfo.prototype.getFormatCodeSettings = function () { return this.formatSettings; }; ScriptInfo.prototype.getPreferences = function () { return this.preferences; }; ScriptInfo.prototype.attachToProject = function (project) { var isNew = !this.isAttached(project); if (isNew) { this.containingProjects.push(project); - project.onFileAddedOrRemoved(); if (!project.getCompilerOptions().preserveSymlinks) { this.ensureRealPath(); } + project.onFileAddedOrRemoved(this.isSymlink()); } return isNew; }; @@ -152587,23 +157246,23 @@ var ts; return; case 1: if (this.containingProjects[0] === project) { - project.onFileAddedOrRemoved(); + project.onFileAddedOrRemoved(this.isSymlink()); this.containingProjects.pop(); } break; case 2: if (this.containingProjects[0] === project) { - project.onFileAddedOrRemoved(); + project.onFileAddedOrRemoved(this.isSymlink()); this.containingProjects[0] = this.containingProjects.pop(); } else if (this.containingProjects[1] === project) { - project.onFileAddedOrRemoved(); + project.onFileAddedOrRemoved(this.isSymlink()); this.containingProjects.pop(); } break; default: if (ts.unorderedRemoveItem(this.containingProjects, project)) { - project.onFileAddedOrRemoved(); + project.onFileAddedOrRemoved(this.isSymlink()); } break; } @@ -152617,6 +157276,7 @@ var ts; var existingRoot = p.getRootFilesMap().get(this.path); // detach is unnecessary since we'll clean the list of containing projects anyways p.removeFile(this, /*fileExists*/ false, /*detachFromProjects*/ false); + p.onFileAddedOrRemoved(this.isSymlink()); // If the info was for the external or configured project's root, // add missing file as the root if (existingRoot && !server.isInferredProject(p)) { @@ -153013,6 +157673,8 @@ var ts; this.cachedUnresolvedImportsPerFile = new ts.Map(); /*@internal*/ this.hasAddedorRemovedFiles = false; + /*@internal*/ + this.hasAddedOrRemovedSymlinks = false; /** * Last version that was reported. */ @@ -153035,7 +157697,9 @@ var ts; /*@internal*/ this.typingFiles = server.emptyArray; /*@internal*/ - this.importSuggestionsCache = ts.Completions.createImportSuggestionsForFileCache(); + this.exportMapCache = ts.createExportMapCache(); + /*@internal*/ + this.moduleSpecifierCache = ts.createModuleSpecifierCache(); /*@internal*/ this.globalCacheResolutionModuleName = ts.JsTyping.nonRelativeModuleNameForTypingCache; this.directoryStructureHost = directoryStructureHost; @@ -153358,7 +158022,7 @@ var ts; return []; } server.updateProjectIfDirty(this); - this.builderState = ts.BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState); + this.builderState = ts.BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState, /*disableUseFileVersionAsSignature*/ true); return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, ts.maybeBind(this.projectService.host, this.projectService.host.createHash)), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); }; /** @@ -153661,8 +158325,8 @@ var ts; /*@internal*/ Project.prototype.markFileAsDirty = function (changedFile) { this.markAsDirty(); - if (!this.importSuggestionsCache.isEmpty()) { - (this.dirtyFilesForSuggestions || (this.dirtyFilesForSuggestions = new ts.Set())).add(changedFile); + if (!this.exportMapCache.isEmpty()) { + (this.changedFilesForExportMapCache || (this.changedFilesForExportMapCache = new ts.Set())).add(changedFile); } }; Project.prototype.markAsDirty = function () { @@ -153672,17 +158336,31 @@ var ts; } }; /*@internal*/ - Project.prototype.markAutoImportProviderAsDirty = function () { + Project.prototype.onAutoImportProviderSettingsChanged = function () { var _a; if (this.autoImportProviderHost === false) { this.autoImportProviderHost = undefined; } - (_a = this.autoImportProviderHost) === null || _a === void 0 ? void 0 : _a.markAsDirty(); - this.importSuggestionsCache.clear(); + else { + (_a = this.autoImportProviderHost) === null || _a === void 0 ? void 0 : _a.markAsDirty(); + } + }; + /*@internal*/ + Project.prototype.onPackageJsonChange = function (packageJsonPath) { + var _a; + if ((_a = this.packageJsonsForAutoImport) === null || _a === void 0 ? void 0 : _a.has(packageJsonPath)) { + this.moduleSpecifierCache.clear(); + if (this.autoImportProviderHost) { + this.autoImportProviderHost.markAsDirty(); + } + } }; /* @internal */ - Project.prototype.onFileAddedOrRemoved = function () { + Project.prototype.onFileAddedOrRemoved = function (isSymlink) { this.hasAddedorRemovedFiles = true; + if (isSymlink) { + this.hasAddedOrRemovedSymlinks = true; + } }; /** * Updates set of files that contribute to this project @@ -153695,6 +158373,7 @@ var ts; var hasNewProgram = this.updateGraphWorker(); var hasAddedorRemovedFiles = this.hasAddedorRemovedFiles; this.hasAddedorRemovedFiles = false; + this.hasAddedOrRemovedSymlinks = false; var changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || server.emptyArray; for (var _i = 0, changedFiles_1 = changedFiles; _i < changedFiles_1.length; _i++) { var file = changedFiles_1[_i]; @@ -153737,11 +158416,14 @@ var ts; /*@internal*/ Project.prototype.updateTypingFiles = function (typingFiles) { var _this = this; - ts.enumerateInsertsAndDeletes(typingFiles, this.typingFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), - /*inserted*/ ts.noop, function (removed) { return _this.detachScriptInfoFromProject(removed); }); - this.typingFiles = typingFiles; - // Invalidate files with unresolved imports - this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile); + if (ts.enumerateInsertsAndDeletes(typingFiles, this.typingFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), + /*inserted*/ ts.noop, function (removed) { return _this.detachScriptInfoFromProject(removed); })) { + // If typing files changed, then only schedule project update + this.typingFiles = typingFiles; + // Invalidate files with unresolved imports + this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile); + this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); + } }; /* @internal */ Project.prototype.getCurrentProgram = function () { @@ -153753,6 +158435,7 @@ var ts; }; Project.prototype.updateGraphWorker = function () { var _this = this; + var _a; var oldProgram = this.program; ts.Debug.assert(!this.isClosed(), "Called update graph worker of closed project"); this.writeLog("Starting updateGraphWorker: Project: " + this.getProjectName()); @@ -153766,11 +158449,12 @@ var ts; // bump up the version if // - oldProgram is not set - this is a first time updateGraph is called // - newProgram is different from the old program and structure of the old program was not reused. - var hasNewProgram = this.program && (!oldProgram || (this.program !== oldProgram && !(this.program.structureIsReused & 2 /* Completely */))); - if (hasNewProgram) { + var hasNewProgram = false; + if (this.program && (!oldProgram || (this.program !== oldProgram && this.program.structureIsReused !== 2 /* Completely */))) { + hasNewProgram = true; if (oldProgram) { - for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { - var f = _a[_i]; + for (var _i = 0, _b = oldProgram.getSourceFiles(); _i < _b.length; _i++) { + var f = _b[_i]; var newFile = this.program.getSourceFileByPath(f.resolvedPath); if (!newFile || (f.resolvedPath === f.path && newFile.resolvedPath !== f.path)) { // new program does not contain this file - detach it from the project @@ -153819,26 +158503,29 @@ var ts; this.resolutionCache.updateTypeRootsWatch(); } } - if (!this.importSuggestionsCache.isEmpty()) { + if (!this.exportMapCache.isEmpty()) { if (this.hasAddedorRemovedFiles || oldProgram && !this.program.structureIsReused) { - this.importSuggestionsCache.clear(); - } - else if (this.dirtyFilesForSuggestions && oldProgram && this.program) { - ts.forEachKey(this.dirtyFilesForSuggestions, function (fileName) { - var oldSourceFile = oldProgram.getSourceFile(fileName); - var sourceFile = _this.program.getSourceFile(fileName); - if (_this.sourceFileHasChangedOwnImportSuggestions(oldSourceFile, sourceFile)) { - _this.importSuggestionsCache.clear(); + this.exportMapCache.clear(); + } + else if (this.changedFilesForExportMapCache && oldProgram && this.program) { + ts.forEachKey(this.changedFilesForExportMapCache, function (fileName) { + var oldSourceFile = oldProgram.getSourceFileByPath(fileName); + var sourceFile = _this.program.getSourceFileByPath(fileName); + if (!oldSourceFile || !sourceFile) { + _this.exportMapCache.clear(); return true; } + return _this.exportMapCache.onFileChanged(oldSourceFile, sourceFile, !!_this.getTypeAcquisition().enable); }); } } - if (this.dirtyFilesForSuggestions) { - this.dirtyFilesForSuggestions.clear(); + if (this.changedFilesForExportMapCache) { + this.changedFilesForExportMapCache.clear(); } - if (this.hasAddedorRemovedFiles) { + if (this.hasAddedOrRemovedSymlinks || this.program && !this.program.structureIsReused && this.getCompilerOptions().preserveSymlinks) { + // With --preserveSymlinks, we may not determine that a file is a symlink, so we never set `hasAddedOrRemovedSymlinks` this.symlinks = undefined; + this.moduleSpecifierCache.clear(); } var oldExternalFiles = this.externalFiles || server.emptyArray; this.externalFiles = this.getExternalFiles(); @@ -153857,7 +158544,7 @@ var ts; this.print(/*writeProjectFileNames*/ true); } else if (this.program !== oldProgram) { - this.writeLog("Different program with same set of files:: structureIsReused:: " + this.program.structureIsReused); + this.writeLog("Different program with same set of files:: structureIsReused:: " + ((_a = this.program) === null || _a === void 0 ? void 0 : _a.structureIsReused)); } return hasNewProgram; }; @@ -153865,54 +158552,6 @@ var ts; Project.prototype.sendPerformanceEvent = function (kind, durationMs) { this.projectService.sendPerformanceEvent(kind, durationMs); }; - /*@internal*/ - Project.prototype.sourceFileHasChangedOwnImportSuggestions = function (oldSourceFile, newSourceFile) { - if (!oldSourceFile && !newSourceFile) { - return false; - } - // Probably shouldn’t get this far, but on the off chance the file was added or removed, - // we can’t reliably tell anything about it. - if (!oldSourceFile || !newSourceFile) { - return true; - } - ts.Debug.assertEqual(oldSourceFile.fileName, newSourceFile.fileName); - // If ATA is enabled, auto-imports uses existing imports to guess whether you want auto-imports from node. - // Adding or removing imports from node could change the outcome of that guess, so could change the suggestions list. - if (this.getTypeAcquisition().enable && ts.consumesNodeCoreModules(oldSourceFile) !== ts.consumesNodeCoreModules(newSourceFile)) { - return true; - } - // Module agumentation and ambient module changes can add or remove exports available to be auto-imported. - // Changes elsewhere in the file can change the *type* of an export in a module augmentation, - // but type info is gathered in getCompletionEntryDetails, which doesn’t use the cache. - if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations) || - !this.ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile)) { - return true; - } - return false; - }; - /*@internal*/ - Project.prototype.ambientModuleDeclarationsAreEqual = function (oldSourceFile, newSourceFile) { - if (!ts.arrayIsEqualTo(oldSourceFile.ambientModuleNames, newSourceFile.ambientModuleNames)) { - return false; - } - var oldFileStatementIndex = -1; - var newFileStatementIndex = -1; - var _loop_1 = function (ambientModuleName) { - var isMatchingModuleDeclaration = function (node) { return ts.isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName; }; - oldFileStatementIndex = ts.findIndex(oldSourceFile.statements, isMatchingModuleDeclaration, oldFileStatementIndex + 1); - newFileStatementIndex = ts.findIndex(newSourceFile.statements, isMatchingModuleDeclaration, newFileStatementIndex + 1); - if (oldSourceFile.statements[oldFileStatementIndex] !== newSourceFile.statements[newFileStatementIndex]) { - return { value: false }; - } - }; - for (var _i = 0, _a = newSourceFile.ambientModuleNames; _i < _a.length; _i++) { - var ambientModuleName = _a[_i]; - var state_1 = _loop_1(ambientModuleName); - if (typeof state_1 === "object") - return state_1.value; - } - return true; - }; Project.prototype.detachScriptInfoFromProject = function (uncheckedFileName, noRemoveResolution) { var scriptInfoToDetach = this.projectService.getScriptInfo(uncheckedFileName); if (scriptInfoToDetach) { @@ -153924,6 +158563,13 @@ var ts; }; Project.prototype.addMissingFileWatcher = function (missingFilePath) { var _this = this; + var _a; + if (isConfiguredProject(this)) { + // If this file is referenced config file, we are already watching it, no need to watch again + var configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(missingFilePath); + if ((_a = configFileExistenceInfo === null || configFileExistenceInfo === void 0 ? void 0 : configFileExistenceInfo.config) === null || _a === void 0 ? void 0 : _a.projects.has(this.canonicalConfigFilePath)) + return ts.noopFileWatcher; + } var fileWatcher = this.projectService.watchFactory.watchFile(missingFilePath, function (fileName, eventKind) { if (isConfiguredProject(_this)) { _this.getCachedDirectoryStructureHost().addOrDeleteFile(fileName, missingFilePath, eventKind); @@ -154171,7 +158817,7 @@ var ts; ts.combinePaths(this.projectService.getExecutingFilePath(), "../../.."), ]); if (this.projectService.globalPlugins) { - var _loop_2 = function (globalPluginName) { + var _loop_1 = function (globalPluginName) { // Skip empty names from odd commandline parses if (!globalPluginName) return "continue"; @@ -154186,13 +158832,17 @@ 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_2(globalPluginName); + _loop_1(globalPluginName); } } }; Project.prototype.enablePlugin = function (pluginConfigEntry, searchPaths, pluginConfigOverrides) { var _this = this; this.projectService.logger.info("Enabling plugin " + pluginConfigEntry.name + " from candidate paths: " + searchPaths.join(",")); + if (!pluginConfigEntry.name || ts.parsePackageName(pluginConfigEntry.name).rest) { + this.projectService.logger.info("Skipped loading plugin " + (pluginConfigEntry.name || JSON.stringify(pluginConfigEntry)) + " because only package name is allowed plugin name"); + return; + } var log = function (message) { return _this.projectService.logger.info(message); }; var errorLogs; var logError = function (message) { (errorLogs || (errorLogs = [])).push(message); }; @@ -154237,7 +158887,7 @@ var ts; newLS[k] = this.languageService[k]; } } - this.projectService.logger.info("Plugin validation succeded"); + this.projectService.logger.info("Plugin validation succeeded"); this.languageService = newLS; this.plugins.push({ name: configEntry.name, module: pluginModule }); } @@ -154274,8 +158924,12 @@ var ts; return packageJsons; }; /*@internal*/ - Project.prototype.getImportSuggestionsCache = function () { - return this.importSuggestionsCache; + Project.prototype.getExportMapCache = function () { + return this.exportMapCache; + }; + /*@internal*/ + Project.prototype.getModuleSpecifierCache = function () { + return this.moduleSpecifierCache; }; /*@internal*/ Project.prototype.includePackageJsonAutoImports = function () { @@ -154463,11 +159117,13 @@ var ts; /*compileOnSaveEnabled*/ false, hostProject.getWatchOptions(), hostProject.projectService.host, hostProject.currentDirectory) || this; _this.hostProject = hostProject; _this.rootFileNames = initialRootNames; + _this.useSourceOfProjectReferenceRedirect = ts.maybeBind(_this.hostProject, _this.hostProject.useSourceOfProjectReferenceRedirect); + _this.getParsedCommandLine = ts.maybeBind(_this.hostProject, _this.hostProject.getParsedCommandLine); return _this; } /*@internal*/ AutoImportProviderProject.getRootFileNames = function (dependencySelection, hostProject, moduleResolutionHost, compilerOptions) { - var _a, _b, _c, _d; + var _a, _b, _c; if (!dependencySelection) { return ts.emptyArray; } @@ -154482,18 +159138,22 @@ var ts; } if (dependencyNames) { var resolutions = ts.map(ts.arrayFrom(dependencyNames.keys()), function (name) { return ts.resolveTypeReferenceDirective(name, rootFileName, compilerOptions, moduleResolutionHost); }); - for (var _e = 0, resolutions_1 = resolutions; _e < resolutions_1.length; _e++) { - var resolution = resolutions_1[_e]; + var program = hostProject.getCurrentProgram(); + var symlinkCache = hostProject.getSymlinkCache(); + for (var _d = 0, resolutions_1 = resolutions; _d < resolutions_1.length; _d++) { + var resolution = resolutions_1[_d]; if (!((_c = resolution.resolvedTypeReferenceDirective) === null || _c === void 0 ? void 0 : _c.resolvedFileName)) continue; - var resolvedFileName = resolution.resolvedTypeReferenceDirective.resolvedFileName; - var fileName = ((_d = moduleResolutionHost.realpath) === null || _d === void 0 ? void 0 : _d.call(moduleResolutionHost, resolvedFileName)) || resolvedFileName; - if (!hostProject.getCurrentProgram().getSourceFile(fileName) && !hostProject.getCurrentProgram().getSourceFile(resolvedFileName)) { - rootNames = ts.append(rootNames, fileName); + var _e = resolution.resolvedTypeReferenceDirective, resolvedFileName = _e.resolvedFileName, originalPath = _e.originalPath; + if (!program.getSourceFile(resolvedFileName) && (!originalPath || !program.getSourceFile(originalPath))) { + rootNames = ts.append(rootNames, resolvedFileName); // Avoid creating a large project that would significantly slow down time to editor interactivity if (dependencySelection === 2 /* Auto */ && rootNames.length > this.maxDependencies) { return ts.emptyArray; } + if (originalPath) { + symlinkCache.setSymlinkedDirectoryFromSymlinkedFile(originalPath, resolvedFileName); + } } } } @@ -154530,8 +159190,12 @@ var ts; } this.projectService.setFileNamesOfAutoImportProviderProject(this, rootFileNames); this.rootFileNames = rootFileNames; - this.hostProject.getImportSuggestionsCache().clear(); - return _super.prototype.updateGraph.call(this); + var oldProgram = this.getCurrentProgram(); + var hasSameSetOfFiles = _super.prototype.updateGraph.call(this); + if (oldProgram && oldProgram !== this.getCurrentProgram()) { + this.hostProject.getExportMapCache().clear(); + } + return hasSameSetOfFiles; }; AutoImportProviderProject.prototype.hasRoots = function () { var _a; @@ -154547,18 +159211,20 @@ var ts; AutoImportProviderProject.prototype.getLanguageService = function () { throw new Error("AutoImportProviderProject language service should never be used. To get the program, use `project.getCurrentProgram()`."); }; - AutoImportProviderProject.prototype.markAutoImportProviderAsDirty = function () { + /*@internal*/ + AutoImportProviderProject.prototype.onAutoImportProviderSettingsChanged = function () { throw new Error("AutoImportProviderProject is an auto import provider; use `markAsDirty()` instead."); }; + /*@internal*/ + AutoImportProviderProject.prototype.onPackageJsonChange = function () { + throw new Error("package.json changes should be notified on an AutoImportProvider's host project"); + }; AutoImportProviderProject.prototype.getModuleResolutionHostForAutoImportProvider = function () { throw new Error("AutoImportProviderProject cannot provide its own host; use `hostProject.getModuleResolutionHostForAutomImportProvider()` instead."); }; AutoImportProviderProject.prototype.getProjectReferences = function () { return this.hostProject.getProjectReferences(); }; - AutoImportProviderProject.prototype.useSourceOfProjectReferenceRedirect = function () { - return true; - }; /*@internal*/ AutoImportProviderProject.prototype.includePackageJsonAutoImports = function () { return 0 /* Off */; @@ -154584,13 +159250,14 @@ var ts; var ConfiguredProject = /** @class */ (function (_super) { __extends(ConfiguredProject, _super); /*@internal*/ - function ConfiguredProject(configFileName, projectService, documentRegistry, cachedDirectoryStructureHost) { + function ConfiguredProject(configFileName, canonicalConfigFilePath, projectService, documentRegistry, cachedDirectoryStructureHost) { var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, /*hasExplicitListOfFiles*/ false, /*lastFileExceededProgramSize*/ undefined, /*compilerOptions*/ {}, /*compileOnSaveEnabled*/ false, /*watchOptions*/ undefined, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; + _this.canonicalConfigFilePath = canonicalConfigFilePath; /* @internal */ _this.openFileWatchTriggered = new ts.Map(); /*@internal*/ @@ -154601,7 +159268,6 @@ var ts; _this.isInitialLoadPending = ts.returnTrue; /*@internal*/ _this.sendLoadingProjectFinish = false; - _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); return _this; } /* @internal */ @@ -154617,22 +159283,30 @@ var ts; return this.languageServiceEnabled; }; /* @internal */ - ConfiguredProject.prototype.setWatchOptions = function (watchOptions) { - var oldOptions = this.getWatchOptions(); - _super.prototype.setWatchOptions.call(this, watchOptions); - // If watch options different than older options - if (this.isInitialLoadPending() && - !ts.isJsonEqual(oldOptions, this.getWatchOptions())) { - var oldWatcher = this.configFileWatcher; - this.createConfigFileWatcher(); - if (oldWatcher) - oldWatcher.close(); + ConfiguredProject.prototype.getParsedCommandLine = function (fileName) { + var configFileName = server.asNormalizedPath(ts.normalizePath(fileName)); + var canonicalConfigFilePath = server.asNormalizedPath(this.projectService.toCanonicalFileName(configFileName)); + // Ensure the config file existience info is cached + var configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!configFileExistenceInfo) { + this.projectService.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo = { exists: this.projectService.host.fileExists(configFileName) }); + } + // Ensure we have upto date parsed command line + this.projectService.ensureParsedConfigUptoDate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, this); + // Watch wild cards if LS is enabled + if (this.languageServiceEnabled && this.projectService.serverMode === ts.LanguageServiceMode.Semantic) { + this.projectService.watchWildcards(configFileName, configFileExistenceInfo, this); } + return configFileExistenceInfo.exists ? configFileExistenceInfo.config.parsedCommandLine : undefined; }; /* @internal */ - ConfiguredProject.prototype.createConfigFileWatcher = function () { - var _this = this; - this.configFileWatcher = this.projectService.watchFactory.watchFile(this.getConfigFilePath(), function (_fileName, eventKind) { return _this.projectService.onConfigChangedForConfiguredProject(_this, eventKind); }, ts.PollingInterval.High, this.projectService.getWatchOptions(this), ts.WatchType.ConfigFile, this); + ConfiguredProject.prototype.onReleaseParsedCommandLine = function (fileName) { + this.releaseParsedConfig(server.asNormalizedPath(this.projectService.toCanonicalFileName(server.asNormalizedPath(ts.normalizePath(fileName))))); + }; + /* @internal */ + ConfiguredProject.prototype.releaseParsedConfig = function (canonicalConfigFilePath) { + this.projectService.stopWatchingWildCards(canonicalConfigFilePath, this); + this.projectService.releaseParsedConfig(canonicalConfigFilePath, this); }; /** * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph @@ -154732,27 +159406,11 @@ var ts; ConfiguredProject.prototype.setProjectErrors = function (projectErrors) { this.projectErrors = projectErrors; }; - /*@internal*/ - ConfiguredProject.prototype.watchWildcards = function (wildcardDirectories) { - var _this = this; - ts.updateWatchingWildcardDirectories(this.directoriesWatchedForWildcards || (this.directoriesWatchedForWildcards = new ts.Map()), wildcardDirectories, - // Create new directory watcher - function (directory, flags) { return _this.projectService.watchWildcardDirectory(directory, flags, _this); }); - }; - /*@internal*/ - ConfiguredProject.prototype.stopWatchingWildCards = function () { - if (this.directoriesWatchedForWildcards) { - ts.clearMap(this.directoriesWatchedForWildcards, ts.closeFileWatcherOf); - this.directoriesWatchedForWildcards = undefined; - } - }; ConfiguredProject.prototype.close = function () { - if (this.configFileWatcher) { - this.configFileWatcher.close(); - this.configFileWatcher = undefined; - } - this.stopWatchingWildCards(); - this.projectService.removeProjectFromSharedExtendedConfigFileMap(this); + var _this = this; + this.projectService.configFileExistenceInfoCache.forEach(function (_configFileExistenceInfo, canonicalConfigFilePath) { + return _this.releaseParsedConfig(canonicalConfigFilePath); + }); this.projectErrors = undefined; this.openFileWatchTriggered.clear(); this.compilerHost = undefined; @@ -154782,6 +159440,7 @@ var ts; /* @internal */ ConfiguredProject.prototype.hasOpenRef = function () { var _this = this; + var _a; if (!!this.externalProjectRefCount) { return true; } @@ -154789,17 +159448,17 @@ var ts; if (this.isClosed()) { return false; } - var configFileExistenceInfo = this.projectService.getConfigFileExistenceInfo(this); + var configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(this.canonicalConfigFilePath); if (this.projectService.hasPendingProjectUpdate(this)) { // If there is pending update for this project, // we dont know if this project would be needed by any of the open files impacted by this config file // In that case keep the project alive if there are open files impacted by this project - return !!configFileExistenceInfo.openFilesImpactedByConfigFile.size; + return !!((_a = configFileExistenceInfo.openFilesImpactedByConfigFile) === null || _a === void 0 ? void 0 : _a.size); } // If there is no pending update for this project, // We know exact set of open files that get impacted by this configured project as the files in the project // 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 !!configFileExistenceInfo.openFilesImpactedByConfigFile && ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { var info = _this.projectService.getScriptInfoForPath(infoPath); return _this.containsScriptInfo(info) || !!server.forEachResolvedProjectReferenceProject(_this, info.path, function (child) { return child.containsScriptInfo(info); }, server.ProjectReferenceProjectLoadKind.Find); @@ -154922,7 +159581,7 @@ var ts; var defaultTypeSafeList = { "jquery": { // jquery files can have names like "jquery-1.10.2.min.js" (or "jquery.intellisense.js") - match: /jquery(-(\.?\d+)+)?(\.intellisense)?(\.min)?\.js$/i, + match: /jquery(-[\d\.]+)?(\.intellisense)?(\.min)?\.js$/i, types: ["jquery"] }, "WinJS": { @@ -155050,16 +159709,7 @@ var ts; } } } - var ConfigFileWatcherStatus; - (function (ConfigFileWatcherStatus) { - ConfigFileWatcherStatus["ReloadingFiles"] = "Reloading configured projects for files"; - ConfigFileWatcherStatus["ReloadingInferredRootFiles"] = "Reloading configured projects for only inferred root files"; - ConfigFileWatcherStatus["UpdatedCallback"] = "Updated the callback"; - ConfigFileWatcherStatus["OpenFilesImpactedByConfigFileAdd"] = "File added to open files impacted by this config file"; - ConfigFileWatcherStatus["OpenFilesImpactedByConfigFileRemove"] = "File removed from open files impacted by this config file"; - ConfigFileWatcherStatus["RootOfInferredProjectTrue"] = "Open file was set as Inferred root"; - ConfigFileWatcherStatus["RootOfInferredProjectFalse"] = "Open file was set as not inferred root"; - })(ConfigFileWatcherStatus || (ConfigFileWatcherStatus = {})); + var noopConfigFileWatcher = { close: ts.noop }; function isOpenScriptInfo(infoOrFileNameOrConfig) { return !!infoOrFileNameOrConfig.containingProjects; } @@ -155155,7 +159805,7 @@ var ts; return forEachAnyProjectReferenceKind(project, function (resolvedRef) { return callbackRefProject(project, cb, resolvedRef.sourceFile.path); }, function (projectRef) { return callbackRefProject(project, cb, project.toPath(ts.resolveProjectReferencePath(projectRef))); }, function (potentialProjectRef) { return callbackRefProject(project, cb, potentialProjectRef); }); } function getDetailWatchInfo(watchType, project) { - return "Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType; + return (ts.isString(project) ? "Config: " + project + " " : project ? "Project: " + project.getProjectName() + " " : "") + "WatchType: " + watchType; } function isScriptInfoWatchedFromNodeModules(info) { return !info.isScriptOpen() && info.mTime !== undefined; @@ -155235,7 +159885,7 @@ var ts; * - Or it is present if we have configured project open with config file at that location * In this case the exists property is always true */ - this.configFileExistenceInfoCache = new ts.Map(); + /*@internal*/ this.configFileExistenceInfoCache = new ts.Map(); this.safelist = defaultTypeSafeList; this.legacySafelist = new ts.Map(); this.pendingProjectUpdates = new ts.Map(); @@ -155245,6 +159895,8 @@ var ts; this.seenProjects = new ts.Map(); /*@internal*/ this.sharedExtendedConfigFileWatchers = new ts.Map(); + /*@internal*/ + this.extendedConfigCache = new ts.Map(); this.host = opts.host; this.logger = opts.logger; this.cancellationToken = opts.cancellationToken; @@ -155381,13 +160033,12 @@ var ts; case server.ActionSet: // Update the typing files and update the project project.updateTypingFiles(this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings)); - break; + return; case server.ActionInvalidate: // Do not clear resolution cache, there was changes detected in typings, so enque typing request and let it get us correct results this.typingsCache.enqueueInstallTypingsForProject(project, project.lastCachedUnresolvedImportsList, /*forceRefresh*/ true); return; } - this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); }; /*@internal*/ ProjectService.prototype.delayEnsureProjectForOpenFiles = function () { @@ -155618,9 +160269,6 @@ var ts; return this.hostConfiguration.preferences; }; ProjectService.prototype.onSourceFileChanged = function (info, eventKind) { - if (info.containingProjects) { - info.containingProjects.forEach(function (project) { return project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(info.path); }); - } if (eventKind === ts.FileWatcherEventKind.Deleted) { // File was deleted this.handleDeletedFile(info); @@ -155686,18 +160334,17 @@ var ts; * This is to watch whenever files are added or removed to the wildcard directories */ /*@internal*/ - ProjectService.prototype.watchWildcardDirectory = function (directory, flags, project) { + ProjectService.prototype.watchWildcardDirectory = function (directory, flags, configFileName, config) { var _this = this; - var watchOptions = this.getWatchOptions(project); return this.watchFactory.watchDirectory(directory, function (fileOrDirectory) { var fileOrDirectoryPath = _this.toPath(fileOrDirectory); - var fsResult = project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); - var configFileName = project.getConfigFilePath(); + var fsResult = config.cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); if (ts.getBaseFileName(fileOrDirectoryPath) === "package.json" && !ts.isInsideNodeModules(fileOrDirectoryPath) && (fsResult && fsResult.fileExists || !fsResult && _this.host.fileExists(fileOrDirectoryPath))) { - _this.logger.info("Project: " + configFileName + " Detected new package.json: " + fileOrDirectory); + _this.logger.info("Config: " + configFileName + " Detected new package.json: " + fileOrDirectory); _this.onAddPackageJson(fileOrDirectoryPath); } + var configuredProjectForConfig = _this.findConfiguredProjectByProjectName(configFileName); if (ts.isIgnoredFileFromWildCardWatching({ watchedDirPath: directory, fileOrDirectory: fileOrDirectory, @@ -155705,109 +160352,111 @@ var ts; configFileName: configFileName, extraFileExtensions: _this.hostConfiguration.extraFileExtensions, currentDirectory: _this.currentDirectory, - options: project.getCompilationSettings(), - program: project.getCurrentProgram(), + options: config.parsedCommandLine.options, + program: (configuredProjectForConfig === null || configuredProjectForConfig === void 0 ? void 0 : configuredProjectForConfig.getCurrentProgram()) || config.parsedCommandLine.fileNames, useCaseSensitiveFileNames: _this.host.useCaseSensitiveFileNames, - writeLog: function (s) { return _this.logger.info(s); } + writeLog: function (s) { return _this.logger.info(s); }, + toPath: function (s) { return _this.toPath(s); } })) return; - // don't trigger callback on open, existing files - if (project.fileIsOpen(fileOrDirectoryPath)) { - if (project.pendingReload !== ts.ConfigFileProgramReloadLevel.Full) { + // Reload is pending, do the reload + if (config.reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + config.projects.forEach(function (watchWildcardDirectories, projectCanonicalPath) { + if (!watchWildcardDirectories) + return; + var project = _this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath); + if (!project) + return; + // Load root file names for configured project with the config file name + // But only schedule update if project references this config file + var reloadLevel = configuredProjectForConfig === project ? ts.ConfigFileProgramReloadLevel.Partial : ts.ConfigFileProgramReloadLevel.None; + if (project.pendingReload !== undefined && project.pendingReload > reloadLevel) + return; + // don't trigger callback on open, existing files + if (_this.openFiles.has(fileOrDirectoryPath)) { var info = ts.Debug.checkDefined(_this.getScriptInfoForPath(fileOrDirectoryPath)); if (info.isAttached(project)) { - project.openFileWatchTriggered.set(fileOrDirectoryPath, true); + var loadLevelToSet = Math.max(reloadLevel, project.openFileWatchTriggered.get(fileOrDirectoryPath) || ts.ConfigFileProgramReloadLevel.None); + project.openFileWatchTriggered.set(fileOrDirectoryPath, loadLevelToSet); } else { - project.pendingReload = ts.ConfigFileProgramReloadLevel.Partial; + project.pendingReload = reloadLevel; _this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); } } + else { + project.pendingReload = reloadLevel; + _this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); + } + }); + }, flags, this.getWatchOptionsFromProjectWatchOptions(config.parsedCommandLine.watchOptions), ts.WatchType.WildcardDirectory, configFileName); + }; + /*@internal*/ + ProjectService.prototype.delayUpdateProjectsFromParsedConfigOnConfigFileChange = function (canonicalConfigFilePath, reloadReason) { + var _this = this; + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!(configFileExistenceInfo === null || configFileExistenceInfo === void 0 ? void 0 : configFileExistenceInfo.config)) + return false; + var scheduledAnyProjectUpdate = false; + // Update projects watching cached config + configFileExistenceInfo.config.reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + configFileExistenceInfo.config.projects.forEach(function (_watchWildcardDirectories, projectCanonicalPath) { + var project = _this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath); + if (!project) return; + scheduledAnyProjectUpdate = true; + if (projectCanonicalPath === canonicalConfigFilePath) { + // Skip refresh if project is not yet loaded + if (project.isInitialLoadPending()) + return; + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reloadReason; + _this.delayUpdateProjectGraph(project); } - // Reload is pending, do the reload - if (project.pendingReload !== ts.ConfigFileProgramReloadLevel.Full) { - project.pendingReload = ts.ConfigFileProgramReloadLevel.Partial; - _this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); + else { + // Change in referenced project config file + project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(_this.toPath(canonicalConfigFilePath)); + _this.delayUpdateProjectGraph(project); } - }, flags, watchOptions, ts.WatchType.WildcardDirectory, project); - }; - /** Gets the config file existence info for the configured project */ - /*@internal*/ - ProjectService.prototype.getConfigFileExistenceInfo = function (project) { - return this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath); + }); + return scheduledAnyProjectUpdate; }; /*@internal*/ - ProjectService.prototype.onConfigChangedForConfiguredProject = function (project, eventKind) { - var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); + ProjectService.prototype.onConfigFileChanged = function (canonicalConfigFilePath, eventKind) { + var _a; + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (eventKind === ts.FileWatcherEventKind.Deleted) { // Update the cached status // We arent updating or removing the cached config file presence info as that will be taken care of by - // setConfigFilePresenceByClosedConfigFile when the project is closed (depending on tracking open files) + // releaseParsedConfig when the project is closed or doesnt need this config any more (depending on tracking open files) configFileExistenceInfo.exists = false; - this.removeProject(project); - // Reload the configured projects for the open files in the map as they are affected by this config file - // Since the configured project was deleted, we want to reload projects for all the open files including files - // that are not root of the inferred project - this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for files" /* ReloadingFiles */); - this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false); + // Remove the configured project for this config file + var project = ((_a = configFileExistenceInfo.config) === null || _a === void 0 ? void 0 : _a.projects.has(canonicalConfigFilePath)) ? + this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath) : + undefined; + if (project) + this.removeProject(project); } else { - this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files" /* ReloadingInferredRootFiles */); - // Skip refresh if project is not yet loaded - if (project.isInitialLoadPending()) - return; - 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 - this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ true); + // Update the cached status + configFileExistenceInfo.exists = true; } - }; - /*@internal*/ - ProjectService.prototype.updateSharedExtendedConfigFileMap = function (_a, parsedCommandLine) { - var _this = this; - var canonicalConfigFilePath = _a.canonicalConfigFilePath; - ts.updateSharedExtendedConfigFileWatcher(canonicalConfigFilePath, parsedCommandLine, this.sharedExtendedConfigFileWatchers, function (extendedConfigFileName, extendedConfigFilePath) { return _this.watchFactory.watchFile(extendedConfigFileName, function () { - var _a; - var ensureProjectsForOpenFiles = false; - (_a = _this.sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (canonicalPath) { - var project = _this.configuredProjects.get(canonicalPath); - // Skip refresh if project is not yet loaded - if (!project || project.isInitialLoadPending()) - return; - project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; - project.pendingReloadReason = "Change in extended config file " + extendedConfigFileName + " detected"; - _this.delayUpdateProjectGraph(project); - ensureProjectsForOpenFiles = true; - }); - if (ensureProjectsForOpenFiles) - _this.delayEnsureProjectForOpenFiles(); - }, ts.PollingInterval.High, _this.hostConfiguration.watchOptions, ts.WatchType.ExtendedConfigFile); }, function (fileName) { return _this.toPath(fileName); }); - }; - /*@internal*/ - ProjectService.prototype.removeProjectFromSharedExtendedConfigFileMap = function (project) { - this.sharedExtendedConfigFileWatchers.forEach(function (watcher) { - watcher.projects.delete(project.canonicalConfigFilePath); - watcher.close(); - }); - }; - /** - * This is the callback function for the config file add/remove/change at any location - * that matters to open script info but doesnt have configured project open - * for the config file - */ - ProjectService.prototype.onConfigFileChangeForOpenScriptInfo = function (configFileName, eventKind) { - // This callback is called only if we dont have config file project for this config file - var canonicalConfigPath = server.normalizedPathToPath(configFileName, this.currentDirectory, this.toCanonicalFileName); - var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigPath); - configFileExistenceInfo.exists = (eventKind !== ts.FileWatcherEventKind.Deleted); - this.logConfigFileWatchUpdate(configFileName, canonicalConfigPath, configFileExistenceInfo, "Reloading configured projects for files" /* ReloadingFiles */); - // Because there is no configured project open for the config file, the tracking open files map - // will only have open files that need the re-detection of the project and hence - // reload projects for all the tracking open files in the map - this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false); + // Update projects watching config + this.delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalConfigFilePath, "Change in config file detected"); + // Reload the configured projects for the open files in the map as they are affected by this config file + // If the configured project was deleted, we want to reload projects for all the open files including files + // that are not root of the inferred project + // Otherwise, we scheduled the update on configured project graph, + // we would need to schedule the project reload for only the root of inferred projects + // Get open files to reload projects for + this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, + /*clearSemanticCache*/ false, + /*delayReload*/ true, eventKind !== ts.FileWatcherEventKind.Deleted ? + ts.identity : // Reload open files if they are root of inferred project + ts.returnTrue, // Reload all the open files impacted by config file + "Change in config file detected"); + this.delayEnsureProjectForOpenFiles(); }; ProjectService.prototype.removeProject = function (project) { var _this = this; @@ -155833,7 +160482,6 @@ var ts; case server.ProjectKind.Configured: this.configuredProjects.delete(project.canonicalConfigFilePath); this.projectToSizeMap.delete(project.canonicalConfigFilePath); - this.setConfigFileExistenceInfoByClosedConfiguredProject(project); break; case server.ProjectKind.Inferred: ts.unorderedRemoveItem(this.inferredProjects, project); @@ -155860,7 +160508,7 @@ var ts; } project.updateGraph(); if (!this.useSingleInferredProject && !project.projectRootPath) { - var _loop_3 = function (inferredProject) { + var _loop_2 = function (inferredProject) { if (inferredProject === project || inferredProject.isOrphan()) { return "continue"; } @@ -155881,7 +160529,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_3(inferredProject); + _loop_2(inferredProject); } } return project; @@ -155924,10 +160572,11 @@ var ts; // if it would need to be re-created with next file open // If project had open file affecting // Reload the root Files from config if its not already scheduled - if (p.openFileWatchTriggered.has(info.path)) { + var reloadLevel = p.openFileWatchTriggered.get(info.path); + if (reloadLevel !== undefined) { p.openFileWatchTriggered.delete(info.path); - if (!p.pendingReload) { - p.pendingReload = ts.ConfigFileProgramReloadLevel.Partial; + if (p.pendingReload !== undefined && p.pendingReload < reloadLevel) { + p.pendingReload = reloadLevel; p.markFileAsDirty(info.path); } } @@ -155975,13 +160624,13 @@ var ts; } }; ProjectService.prototype.configFileExists = function (configFileName, canonicalConfigFilePath, info) { + var _a; var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (configFileExistenceInfo) { // By default the info would get impacted by presence of config file since its in the detection path // Only adding the info as a root to inferred project will need the existence to be watched by file watcher - if (isOpenScriptInfo(info) && !configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { - configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); - this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file" /* OpenFilesImpactedByConfigFileAdd */); + if (isOpenScriptInfo(info) && !((_a = configFileExistenceInfo.openFilesImpactedByConfigFile) === null || _a === void 0 ? void 0 : _a.has(info.path))) { + (configFileExistenceInfo.openFilesImpactedByConfigFile || (configFileExistenceInfo.openFilesImpactedByConfigFile = new ts.Map())).set(info.path, false); } return configFileExistenceInfo.exists; } @@ -155994,104 +160643,82 @@ var ts; // Or the whole chain of config files for the roots of the inferred projects // Cache the host value of file exists and add the info to map of open files impacted by this config file var exists = this.host.fileExists(configFileName); - var openFilesImpactedByConfigFile = new ts.Map(); + var openFilesImpactedByConfigFile; if (isOpenScriptInfo(info)) { - openFilesImpactedByConfigFile.set(info.path, false); + (openFilesImpactedByConfigFile || (openFilesImpactedByConfigFile = new ts.Map())).set(info.path, false); } configFileExistenceInfo = { exists: exists, openFilesImpactedByConfigFile: openFilesImpactedByConfigFile }; this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); - this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file" /* OpenFilesImpactedByConfigFileAdd */); return exists; }; - ProjectService.prototype.setConfigFileExistenceByNewConfiguredProject = function (project) { - var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); - if (configFileExistenceInfo) { - // The existence might not be set if the file watcher is not invoked by the time config project is created by external project - configFileExistenceInfo.exists = true; - // close existing watcher - if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { - var configFileName = project.getConfigFilePath(); - configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close(); - configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined; - this.logConfigFileWatchUpdate(configFileName, project.canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback" /* UpdatedCallback */); - } - } - else { - // We could be in this scenario if project is the configured project tracked by external project - // Since that route doesnt check if the config file is present or not - this.configFileExistenceInfoCache.set(project.canonicalConfigFilePath, { - exists: true, - openFilesImpactedByConfigFile: new ts.Map() - }); + /*@internal*/ + ProjectService.prototype.createConfigFileWatcherForParsedConfig = function (configFileName, canonicalConfigFilePath, forProject) { + var _this = this; + var _a, _b; + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + // When watching config file for parsed config, remove the noopFileWatcher that can be created for open files impacted by config file and watch for real + if (!configFileExistenceInfo.watcher || configFileExistenceInfo.watcher === noopConfigFileWatcher) { + configFileExistenceInfo.watcher = this.watchFactory.watchFile(configFileName, function (_fileName, eventKind) { return _this.onConfigFileChanged(canonicalConfigFilePath, eventKind); }, ts.PollingInterval.High, this.getWatchOptionsFromProjectWatchOptions((_b = (_a = configFileExistenceInfo === null || configFileExistenceInfo === void 0 ? void 0 : configFileExistenceInfo.config) === null || _a === void 0 ? void 0 : _a.parsedCommandLine) === null || _b === void 0 ? void 0 : _b.watchOptions), ts.WatchType.ConfigFile, forProject); } + // Watching config file for project, update the map + var projects = configFileExistenceInfo.config.projects; + projects.set(forProject.canonicalConfigFilePath, projects.get(forProject.canonicalConfigFilePath) || false); }; /** * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project */ ProjectService.prototype.configFileExistenceImpactsRootOfInferredProject = function (configFileExistenceInfo) { - return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (isRootOfInferredProject) { return isRootOfInferredProject; }); + return configFileExistenceInfo.openFilesImpactedByConfigFile && + ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, ts.identity); }; - ProjectService.prototype.setConfigFileExistenceInfoByClosedConfiguredProject = function (closedProject) { - var configFileExistenceInfo = this.getConfigFileExistenceInfo(closedProject); - ts.Debug.assert(!!configFileExistenceInfo); - if (configFileExistenceInfo.openFilesImpactedByConfigFile.size) { - var configFileName = closedProject.getConfigFilePath(); + /* @internal */ + ProjectService.prototype.releaseParsedConfig = function (canonicalConfigFilePath, forProject) { + var _a, _b, _c; + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!((_a = configFileExistenceInfo.config) === null || _a === void 0 ? void 0 : _a.projects.delete(forProject.canonicalConfigFilePath))) + return; + // If there are still projects watching this config file existence and config, there is nothing to do + if ((_b = configFileExistenceInfo.config) === null || _b === void 0 ? void 0 : _b.projects.size) + return; + configFileExistenceInfo.config = undefined; + ts.clearSharedExtendedConfigFileWatcher(canonicalConfigFilePath, this.sharedExtendedConfigFileWatchers); + ts.Debug.checkDefined(configFileExistenceInfo.watcher); + if ((_c = configFileExistenceInfo.openFilesImpactedByConfigFile) === null || _c === void 0 ? void 0 : _c.size) { // If there are open files that are impacted by this config file existence // but none of them are root of inferred project, the config file watcher will be // created when any of the script infos are added as root of inferred project if (this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { - ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject); - this.createConfigFileWatcherOfConfigFileExistence(configFileName, closedProject.canonicalConfigFilePath, configFileExistenceInfo); + // If we cannot watch config file existence without configured project, close the configured file watcher + if (!ts.canWatchDirectory(ts.getDirectoryPath(canonicalConfigFilePath))) { + configFileExistenceInfo.watcher.close(); + configFileExistenceInfo.watcher = noopConfigFileWatcher; + } + } + else { + // Close existing watcher + configFileExistenceInfo.watcher.close(); + configFileExistenceInfo.watcher = undefined; } } else { // There is not a single file open thats tracking the status of this config file. Remove from cache - this.configFileExistenceInfoCache.delete(closedProject.canonicalConfigFilePath); - } - }; - ProjectService.prototype.logConfigFileWatchUpdate = function (configFileName, canonicalConfigFilePath, configFileExistenceInfo, status) { - var _this = this; - if (!this.logger.hasLevel(server.LogLevel.verbose)) { - return; - } - var inferredRoots = []; - var otherFiles = []; - configFileExistenceInfo.openFilesImpactedByConfigFile.forEach(function (isRootOfInferredProject, key) { - var info = _this.getScriptInfoForPath(key); - (isRootOfInferredProject ? inferredRoots : otherFiles).push(info.fileName); - }); - var watches = []; - if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { - watches.push(configFileExistenceInfo.configFileWatcherForRootOfInferredProject === ts.noopFileWatcher ? - ts.WatchType.NoopConfigFileForInferredRoot : - ts.WatchType.ConfigFileForInferredRoot); - } - if (this.configuredProjects.has(canonicalConfigFilePath)) { - watches.push(ts.WatchType.ConfigFile); + configFileExistenceInfo.watcher.close(); + this.configFileExistenceInfoCache.delete(canonicalConfigFilePath); } - this.logger.info("ConfigFilePresence:: Current Watches: " + watches + ":: File: " + configFileName + " Currently impacted open files: RootsOfInferredProjects: " + inferredRoots + " OtherOpenFiles: " + otherFiles + " Status: " + status); - }; - /** - * Create the watcher for the configFileExistenceInfo - */ - ProjectService.prototype.createConfigFileWatcherOfConfigFileExistence = function (configFileName, canonicalConfigFilePath, configFileExistenceInfo) { - var _this = this; - configFileExistenceInfo.configFileWatcherForRootOfInferredProject = - ts.canWatchDirectory(ts.getDirectoryPath(canonicalConfigFilePath)) ? - this.watchFactory.watchFile(configFileName, function (_filename, eventKind) { return _this.onConfigFileChangeForOpenScriptInfo(configFileName, eventKind); }, ts.PollingInterval.High, this.hostConfiguration.watchOptions, ts.WatchType.ConfigFileForInferredRoot) : - ts.noopFileWatcher; - this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback" /* UpdatedCallback */); }; /** * Close the config file watcher in the cached ConfigFileExistenceInfo - * if there arent any open files that are root of inferred project + * if there arent any open files that are root of inferred project and there is no parsed config held by any project */ - ProjectService.prototype.closeConfigFileWatcherOfConfigFileExistenceInfo = function (configFileExistenceInfo) { + /*@internal*/ + ProjectService.prototype.closeConfigFileWatcherOnReleaseOfOpenFile = function (configFileExistenceInfo) { // Close the config file watcher if there are no more open files that are root of inferred project - if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject && + // or if there are no projects that need to watch this config file existence info + if (configFileExistenceInfo.watcher && + !configFileExistenceInfo.config && !this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { - configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close(); - configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined; + configFileExistenceInfo.watcher.close(); + configFileExistenceInfo.watcher = undefined; } }; /** @@ -156100,25 +160727,26 @@ var ts; ProjectService.prototype.stopWatchingConfigFilesForClosedScriptInfo = function (info) { var _this = this; ts.Debug.assert(!info.isScriptOpen()); - this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + this.forEachConfigFileLocation(info, function (canonicalConfigFilePath) { + var _a, _b, _c; var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (configFileExistenceInfo) { - var infoIsRootOfInferredProject = configFileExistenceInfo.openFilesImpactedByConfigFile.get(info.path); + var infoIsRootOfInferredProject = (_a = configFileExistenceInfo.openFilesImpactedByConfigFile) === null || _a === void 0 ? void 0 : _a.get(info.path); // Delete the info from map, since this file is no more open - configFileExistenceInfo.openFilesImpactedByConfigFile.delete(info.path); - _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File removed from open files impacted by this config file" /* OpenFilesImpactedByConfigFileRemove */); + (_b = configFileExistenceInfo.openFilesImpactedByConfigFile) === null || _b === void 0 ? void 0 : _b.delete(info.path); // If the script info was not root of inferred project, // there wont be config file watch open because of this script info if (infoIsRootOfInferredProject) { // But if it is a root, it could be the last script info that is root of inferred project // and hence we would need to close the config file watcher - _this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); + _this.closeConfigFileWatcherOnReleaseOfOpenFile(configFileExistenceInfo); } // If there are no open files that are impacted by configFileExistenceInfo after closing this script info - // there is no configured project present, remove the cached existence info - if (!configFileExistenceInfo.openFilesImpactedByConfigFile.size && - !_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) { - ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject); + // and there is are no projects that need the config file existence or parsed config, + // remove the cached existence info + if (!((_c = configFileExistenceInfo.openFilesImpactedByConfigFile) === null || _c === void 0 ? void 0 : _c.size) && + !configFileExistenceInfo.config) { + ts.Debug.assert(!configFileExistenceInfo.watcher); _this.configFileExistenceInfoCache.delete(canonicalConfigFilePath); } } @@ -156131,24 +160759,19 @@ var ts; ProjectService.prototype.startWatchingConfigFilesForInferredProjectRoot = function (info) { var _this = this; ts.Debug.assert(info.isScriptOpen()); - this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + this.forEachConfigFileLocation(info, function (canonicalConfigFilePath, configFileName) { var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (!configFileExistenceInfo) { // Create the cache - configFileExistenceInfo = { - exists: _this.host.fileExists(configFileName), - openFilesImpactedByConfigFile: new ts.Map() - }; + configFileExistenceInfo = { exists: _this.host.fileExists(configFileName) }; _this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); } // Set this file as the root of inferred project - configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, true); - _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as Inferred root" /* RootOfInferredProjectTrue */); + (configFileExistenceInfo.openFilesImpactedByConfigFile || (configFileExistenceInfo.openFilesImpactedByConfigFile = new ts.Map())).set(info.path, true); // If there is no configured project for this config file, add the file watcher - if (!configFileExistenceInfo.configFileWatcherForRootOfInferredProject && - !_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) { - _this.createConfigFileWatcherOfConfigFileExistence(configFileName, canonicalConfigFilePath, configFileExistenceInfo); - } + configFileExistenceInfo.watcher || (configFileExistenceInfo.watcher = ts.canWatchDirectory(ts.getDirectoryPath(canonicalConfigFilePath)) ? + _this.watchFactory.watchFile(configFileName, function (_filename, eventKind) { return _this.onConfigFileChanged(canonicalConfigFilePath, eventKind); }, ts.PollingInterval.High, _this.hostConfiguration.watchOptions, ts.WatchType.ConfigFileForInferredRoot) : + noopConfigFileWatcher); }); }; /** @@ -156157,15 +160780,15 @@ var ts; /* @internal */ ProjectService.prototype.stopWatchingConfigFilesForInferredProjectRoot = function (info) { var _this = this; - this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + this.forEachConfigFileLocation(info, function (canonicalConfigFilePath) { + var _a; var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath); - if (configFileExistenceInfo && configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { + if ((_a = configFileExistenceInfo === null || configFileExistenceInfo === void 0 ? void 0 : configFileExistenceInfo.openFilesImpactedByConfigFile) === null || _a === void 0 ? void 0 : _a.has(info.path)) { ts.Debug.assert(info.isScriptOpen()); // Info is not root of inferred project any more configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); - _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as not inferred root" /* RootOfInferredProjectFalse */); // Close the config file watcher - _this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); + _this.closeConfigFileWatcherOnReleaseOfOpenFile(configFileExistenceInfo); } }); }; @@ -156197,11 +160820,11 @@ var ts; if (searchInDirectory) { var canonicalSearchPath = server.normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName); var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json")); - var result = action(tsconfigFileName, ts.combinePaths(canonicalSearchPath, "tsconfig.json")); + var result = action(ts.combinePaths(canonicalSearchPath, "tsconfig.json"), tsconfigFileName); if (result) return tsconfigFileName; var jsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "jsconfig.json")); - result = action(jsconfigFileName, ts.combinePaths(canonicalSearchPath, "jsconfig.json")); + result = action(ts.combinePaths(canonicalSearchPath, "jsconfig.json"), jsconfigFileName); if (result) return jsconfigFileName; // If we started within node_modules, don't look outside node_modules. @@ -156249,7 +160872,7 @@ var ts; return result || undefined; } this.logger.info("Search path: " + ts.getDirectoryPath(info.fileName)); - var configFileName = this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) { + var configFileName = this.forEachConfigFileLocation(info, function (canonicalConfigFilePath, configFileName) { return _this.configFileExists(configFileName, canonicalConfigFilePath, info); }); if (configFileName) { @@ -156294,6 +160917,7 @@ var ts; }; /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ ProjectService.prototype.getFilenameForExceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) { + var _this = this; if (options && options.disableSizeLimit || !this.host.getFileSize) { return; } @@ -156309,25 +160933,17 @@ var ts; } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { - this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTSFileExtension: ts.hasTSFileExtension, host: this.host }, totalNonTsFileSize)); // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier + var top5LargestFiles = fileNames.map(function (f) { return propertyReader.getFileName(f); }) + .filter(function (name) { return !ts.hasTSFileExtension(name); }) + .map(function (name) { return ({ name: name, size: _this.host.getFileSize(name) }); }) + .sort(function (a, b) { return b.size - a.size; }) + .slice(0, 5); + this.logger.info("Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + top5LargestFiles.map(function (file) { return file.name + ":" + file.size; }).join(", ")); // Keep the size as zero since it's disabled return fileName; } } this.projectToSizeMap.set(name, totalNonTsFileSize); - return; - function getExceedLimitMessage(context, totalNonTsFileSize) { - var files = getTop5LargestFiles(context); - 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, hasTSFileExtension = _a.hasTSFileExtension, host = _a.host; - return fileNames.map(function (f) { return propertyReader.getFileName(f); }) - .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); - } }; ProjectService.prototype.createExternalProject = function (projectFileName, files, options, typeAcquisition, excludedFiles) { var compilerOptions = convertCompilerOptions(options); @@ -156391,12 +161007,27 @@ var ts; }; /* @internal */ ProjectService.prototype.createConfiguredProject = function (configFileName) { - var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); // TODO: GH#18217 - this.logger.info("Opened configuration file " + configFileName); - var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, cachedDirectoryStructureHost); - project.createConfigFileWatcher(); - this.configuredProjects.set(project.canonicalConfigFilePath, project); - this.setConfigFileExistenceByNewConfiguredProject(project); + this.logger.info("Creating configuration project " + configFileName); + var canonicalConfigFilePath = server.asNormalizedPath(this.toCanonicalFileName(configFileName)); + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + // We could be in this scenario if project is the configured project tracked by external project + // Since that route doesnt check if the config file is present or not + if (!configFileExistenceInfo) { + this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo = { exists: true }); + } + else { + configFileExistenceInfo.exists = true; + } + if (!configFileExistenceInfo.config) { + configFileExistenceInfo.config = { + cachedDirectoryStructureHost: ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames), + projects: new ts.Map(), + reloadLevel: ts.ConfigFileProgramReloadLevel.Full + }; + } + var project = new server.ConfiguredProject(configFileName, canonicalConfigFilePath, this, this.documentRegistry, configFileExistenceInfo.config.cachedDirectoryStructureHost); + this.configuredProjects.set(canonicalConfigFilePath, project); + this.createConfigFileWatcherForParsedConfig(configFileName, canonicalConfigFilePath, project); return project; }; /* @internal */ @@ -156426,24 +161057,9 @@ var ts; var _this = this; this.sendProjectLoadingStartEvent(project, reason); // Read updated contents from disk - var configFilename = ts.normalizePath(project.getConfigFilePath()); - var configFileContent = ts.tryReadFile(configFilename, function (fileName) { return _this.host.readFile(fileName); }); - var result = ts.parseJsonText(configFilename, ts.isString(configFileContent) ? configFileContent : ""); - var configFileErrors = result.parseDiagnostics; - if (!ts.isString(configFileContent)) - configFileErrors.push(configFileContent); - var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename), - /*existingOptions*/ {}, configFilename, - /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions, - /*extendedConfigCache*/ undefined); - if (parsedCommandLine.errors.length) { - configFileErrors.push.apply(configFileErrors, parsedCommandLine.errors); - } - this.logger.info("Config: " + configFilename + " : " + JSON.stringify({ - rootNames: parsedCommandLine.fileNames, - options: parsedCommandLine.options, - projectReferences: parsedCommandLine.projectReferences - }, /*replacer*/ undefined, " ")); + var configFilename = server.asNormalizedPath(ts.normalizePath(project.getConfigFilePath())); + var configFileExistenceInfo = this.ensureParsedConfigUptoDate(configFilename, project.canonicalConfigFilePath, this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath), project); + var parsedCommandLine = configFileExistenceInfo.config.parsedCommandLine; ts.Debug.assert(!!parsedCommandLine.fileNames); var compilerOptions = parsedCommandLine.options; // Update the project @@ -156456,25 +161072,131 @@ var ts; }; } project.canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInputFiles(parsedCommandLine.raw); - project.setProjectErrors(configFileErrors); + project.setProjectErrors(parsedCommandLine.options.configFile.parseDiagnostics); project.updateReferences(parsedCommandLine.projectReferences); var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); if (lastFileExceededProgramSize) { project.disableLanguageService(lastFileExceededProgramSize); - project.stopWatchingWildCards(); - this.removeProjectFromSharedExtendedConfigFileMap(project); + this.configFileExistenceInfoCache.forEach(function (_configFileExistenceInfo, canonicalConfigFilePath) { + return _this.stopWatchingWildCards(canonicalConfigFilePath, project); + }); } else { project.setCompilerOptions(compilerOptions); project.setWatchOptions(parsedCommandLine.watchOptions); project.enableLanguageService(); - project.watchWildcards(new ts.Map(ts.getEntries(parsedCommandLine.wildcardDirectories))); // TODO: GH#18217 - this.updateSharedExtendedConfigFileMap(project, parsedCommandLine); + this.watchWildcards(configFilename, configFileExistenceInfo, project); } project.enablePluginsWithOptions(compilerOptions, this.currentPluginConfigOverrides); var filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave, parsedCommandLine.watchOptions); }; + /*@internal*/ + ProjectService.prototype.ensureParsedConfigUptoDate = function (configFilename, canonicalConfigFilePath, configFileExistenceInfo, forProject) { + var _this = this; + var _a, _b, _c; + if (configFileExistenceInfo.config) { + if (!configFileExistenceInfo.config.reloadLevel) + return configFileExistenceInfo; + if (configFileExistenceInfo.config.reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + this.reloadFileNamesOfParsedConfig(configFilename, configFileExistenceInfo.config); + return configFileExistenceInfo; + } + } + // Parse the config file and ensure its cached + var cachedDirectoryStructureHost = ((_a = configFileExistenceInfo.config) === null || _a === void 0 ? void 0 : _a.cachedDirectoryStructureHost) || + ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); + // Read updated contents from disk + var configFileContent = ts.tryReadFile(configFilename, function (fileName) { return _this.host.readFile(fileName); }); + var configFile = ts.parseJsonText(configFilename, ts.isString(configFileContent) ? configFileContent : ""); + var configFileErrors = configFile.parseDiagnostics; + if (!ts.isString(configFileContent)) + configFileErrors.push(configFileContent); + var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(configFile, cachedDirectoryStructureHost, ts.getDirectoryPath(configFilename), + /*existingOptions*/ {}, configFilename, + /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions, this.extendedConfigCache); + if (parsedCommandLine.errors.length) { + configFileErrors.push.apply(configFileErrors, parsedCommandLine.errors); + } + this.logger.info("Config: " + configFilename + " : " + JSON.stringify({ + rootNames: parsedCommandLine.fileNames, + options: parsedCommandLine.options, + watchOptions: parsedCommandLine.watchOptions, + projectReferences: parsedCommandLine.projectReferences + }, /*replacer*/ undefined, " ")); + var oldCommandLine = (_b = configFileExistenceInfo.config) === null || _b === void 0 ? void 0 : _b.parsedCommandLine; + if (!configFileExistenceInfo.config) { + configFileExistenceInfo.config = { parsedCommandLine: parsedCommandLine, cachedDirectoryStructureHost: cachedDirectoryStructureHost, projects: new ts.Map() }; + } + else { + configFileExistenceInfo.config.parsedCommandLine = parsedCommandLine; + configFileExistenceInfo.config.watchedDirectoriesStale = true; + configFileExistenceInfo.config.reloadLevel = undefined; + } + // If watch options different than older options when setting for the first time, update the config file watcher + if (!oldCommandLine && !ts.isJsonEqual( + // Old options + this.getWatchOptionsFromProjectWatchOptions(/*projectOptions*/ undefined), + // New options + this.getWatchOptionsFromProjectWatchOptions(parsedCommandLine.watchOptions))) { + // Reset the config file watcher + (_c = configFileExistenceInfo.watcher) === null || _c === void 0 ? void 0 : _c.close(); + configFileExistenceInfo.watcher = undefined; + } + // Ensure there is watcher for this config file + this.createConfigFileWatcherForParsedConfig(configFilename, canonicalConfigFilePath, forProject); + // Watch extended config files + ts.updateSharedExtendedConfigFileWatcher(canonicalConfigFilePath, parsedCommandLine.options, this.sharedExtendedConfigFileWatchers, function (extendedConfigFileName, extendedConfigFilePath) { return _this.watchFactory.watchFile(extendedConfigFileName, function () { + var _a; + // Update extended config cache + ts.cleanExtendedConfigCache(_this.extendedConfigCache, extendedConfigFilePath, function (fileName) { return _this.toPath(fileName); }); + // Update projects + var ensureProjectsForOpenFiles = false; + (_a = _this.sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (canonicalPath) { + ensureProjectsForOpenFiles = _this.delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalPath, "Change in extended config file " + extendedConfigFileName + " detected") || ensureProjectsForOpenFiles; + }); + if (ensureProjectsForOpenFiles) + _this.delayEnsureProjectForOpenFiles(); + }, ts.PollingInterval.High, _this.hostConfiguration.watchOptions, ts.WatchType.ExtendedConfigFile, configFilename); }, function (fileName) { return _this.toPath(fileName); }); + return configFileExistenceInfo; + }; + /*@internal*/ + ProjectService.prototype.watchWildcards = function (configFileName, _a, forProject) { + var _this = this; + var _b; + var exists = _a.exists, config = _a.config; + config.projects.set(forProject.canonicalConfigFilePath, true); + if (exists) { + if (config.watchedDirectories && !config.watchedDirectoriesStale) + return; + config.watchedDirectoriesStale = false; + ts.updateWatchingWildcardDirectories((_b = config).watchedDirectories || (_b.watchedDirectories = new ts.Map()), new ts.Map(ts.getEntries(config.parsedCommandLine.wildcardDirectories)), + // Create new directory watcher + function (directory, flags) { return _this.watchWildcardDirectory(directory, flags, configFileName, config); }); + } + else { + config.watchedDirectoriesStale = false; + if (!config.watchedDirectories) + return; + ts.clearMap(config.watchedDirectories, ts.closeFileWatcherOf); + config.watchedDirectories = undefined; + } + }; + /*@internal*/ + ProjectService.prototype.stopWatchingWildCards = function (canonicalConfigFilePath, forProject) { + var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!configFileExistenceInfo.config || + !configFileExistenceInfo.config.projects.get(forProject.canonicalConfigFilePath)) { + return; + } + configFileExistenceInfo.config.projects.set(forProject.canonicalConfigFilePath, false); + // If any of the project is still watching wild cards dont close the watcher + if (ts.forEachEntry(configFileExistenceInfo.config.projects, ts.identity)) + return; + ts.clearMap(configFileExistenceInfo.config.watchedDirectories, ts.closeFileWatcherOf); + configFileExistenceInfo.config.watchedDirectories = undefined; + configFileExistenceInfo.config.watchedDirectoriesStale = undefined; + }; ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) { var projectRootFilesMap = project.getRootFilesMap(); var newRootScriptInfoMap = new ts.Map(); @@ -156554,14 +161276,22 @@ var ts; */ /*@internal*/ ProjectService.prototype.reloadFileNamesOfConfiguredProject = function (project) { - var configFileSpecs = project.getCompilerOptions().configFile.configFileSpecs; - var configFileName = project.getConfigFilePath(); - var fileNames = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); + var fileNames = this.reloadFileNamesOfParsedConfig(project.getConfigFilePath(), this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath).config); project.updateErrorOnNoInputFiles(fileNames); this.updateNonInferredProjectFiles(project, fileNames.concat(project.getExternalFiles()), fileNamePropertyReader); return project.updateGraph(); }; /*@internal*/ + ProjectService.prototype.reloadFileNamesOfParsedConfig = function (configFileName, config) { + if (config.reloadLevel === undefined) + return config.parsedCommandLine.fileNames; + ts.Debug.assert(config.reloadLevel === ts.ConfigFileProgramReloadLevel.Partial); + var configFileSpecs = config.parsedCommandLine.options.configFile.configFileSpecs; + var fileNames = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), config.parsedCommandLine.options, config.cachedDirectoryStructureHost, this.hostConfiguration.extraFileExtensions); + config.parsedCommandLine = __assign(__assign({}, config.parsedCommandLine), { fileNames: fileNames }); + return fileNames; + }; + /*@internal*/ ProjectService.prototype.setFileNamesOfAutoImportProviderProject = function (project, fileNames) { this.updateNonInferredProjectFiles(project, fileNames, fileNamePropertyReader); }; @@ -156735,7 +161465,7 @@ var ts; return projects; function combineProjects(toAddInfo) { if (toAddInfo !== info) { - var _loop_4 = function (project) { + var _loop_3 = function (project) { // Add the projects only if they can use symLink targets and not already in the list if (project.languageServiceEnabled && !project.isOrphan() && @@ -156752,7 +161482,7 @@ var ts; }; for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { var project = _a[_i]; - _loop_4(project); + _loop_3(project); } } } @@ -156960,7 +161690,7 @@ var ts; var snap = mapInfo.getSnapshot(); if (mapInfo.documentPositionMapper !== undefined) return mapInfo.documentPositionMapper; - return snap.getText(0, snap.getLength()); + return ts.getSnapshotText(snap); }; var projectName = project.projectName; var documentPositionMapper = ts.getDocumentPositionMapper({ getCanonicalFileName: this.toCanonicalFileName, log: function (s) { return _this.logger.info(s); }, getSourceFileLike: function (f) { return _this.getSourceFileLike(f, projectName, declarationInfo); } }, declarationInfo.fileName, declarationInfo.getLineInfo(), readMapFile); @@ -157081,7 +161811,7 @@ var ts; }); } if (includePackageJsonAutoImports !== args.preferences.includePackageJsonAutoImports) { - this.invalidateProjectAutoImports(/*packageJsonPath*/ undefined); + this.invalidateProjectPackageJson(/*packageJsonPath*/ undefined); } } if (args.extraFileExtensions) { @@ -157099,7 +161829,10 @@ var ts; }; /*@internal*/ ProjectService.prototype.getWatchOptions = function (project) { - var projectOptions = project.getWatchOptions(); + return this.getWatchOptionsFromProjectWatchOptions(project.getWatchOptions()); + }; + /*@internal*/ + ProjectService.prototype.getWatchOptionsFromProjectWatchOptions = function (projectOptions) { return projectOptions && this.hostConfiguration.watchOptions ? __assign(__assign({}, this.hostConfiguration.watchOptions), projectOptions) : projectOptions || this.hostConfiguration.watchOptions; }; @@ -157133,6 +161866,11 @@ var ts; }); this.throttledOperations.cancel(ensureProjectForOpenFileSchedule); this.pendingEnsureProjectForOpenFiles = false; + // Ensure everything is reloaded for cached configs + this.configFileExistenceInfoCache.forEach(function (info) { + if (info.config) + info.config.reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + }); // Reload Projects this.reloadConfiguredProjectForFiles(this.openFiles, /*clearSemanticCache*/ true, /*delayReload*/ false, ts.returnTrue, "User requested reload projects"); this.externalProjects.forEach(function (project) { @@ -157142,21 +161880,11 @@ var ts; this.inferredProjects.forEach(function (project) { return _this.clearSemanticCache(project); }); this.ensureProjectForOpenFiles(); }; - ProjectService.prototype.delayReloadConfiguredProjectForFiles = function (configFileExistenceInfo, ignoreIfNotRootOfInferredProject) { - // Get open files to reload projects for - this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, - /*clearSemanticCache*/ false, - /*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 - "Change in config file detected"); - this.delayEnsureProjectForOpenFiles(); - }; /** * This function goes through all the openFiles and tries to file the config file for them. * If the config file is found and it refers to existing project, it reloads it either immediately * or schedules it for reload depending on delayReload option - * If the there is no existing project it just opens the configured project for the config file + * If 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, clearSemanticCache, delayReload, shouldReloadProjectFor, reason) { @@ -157169,7 +161897,7 @@ var ts; } }; // try to reload config file for all open files - openFiles.forEach(function (openFileValue, path) { + openFiles === null || openFiles === void 0 ? void 0 : openFiles.forEach(function (openFileValue, path) { // Invalidate default config file name for open file _this.configFileForOpenFiles.delete(path); // Filter out the files that need to be ignored @@ -157641,13 +162369,13 @@ var ts; return result; }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, includeProjectReferenceRedirectInfo, result) { - var _loop_5 = function (proj) { + var _loop_4 = function (proj) { var knownProject = ts.find(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName(); }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version, includeProjectReferenceRedirectInfo)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_5(proj); + _loop_4(proj); } }; /* @internal */ @@ -157787,7 +162515,7 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_6 = function (name) { + var _loop_5 = function (name) { var rule = this_2.safelist[name]; for (var _b = 0, normalizedNames_1 = normalizedNames; _b < normalizedNames_1.length; _b++) { var root = normalizedNames_1[_b]; @@ -157805,7 +162533,7 @@ var ts; } } if (rule.exclude) { - var _loop_8 = function (exclude) { + var _loop_7 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -157832,7 +162560,7 @@ var ts; }; for (var _e = 0, _f = rule.exclude; _e < _f.length; _e++) { var exclude = _f[_e]; - _loop_8(exclude); + _loop_7(exclude); } } else { @@ -157848,11 +162576,11 @@ var ts; var this_2 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_6(name); + _loop_5(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_7 = function (i) { + var _loop_6 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -157890,7 +162618,7 @@ var ts; }; var this_3 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_7(i); + _loop_6(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -158077,7 +162805,7 @@ var ts; var _this = this; var watchers = this.packageJsonFilesMap || (this.packageJsonFilesMap = new ts.Map()); if (!watchers.has(path)) { - this.invalidateProjectAutoImports(path); + this.invalidateProjectPackageJson(path); watchers.set(path, this.watchFactory.watchFile(path, function (fileName, eventKind) { var path = _this.toPath(fileName); switch (eventKind) { @@ -158085,11 +162813,11 @@ var ts; return ts.Debug.fail(); case ts.FileWatcherEventKind.Changed: _this.packageJsonCache.addOrUpdate(path); - _this.invalidateProjectAutoImports(path); + _this.invalidateProjectPackageJson(path); break; case ts.FileWatcherEventKind.Deleted: _this.packageJsonCache.delete(path); - _this.invalidateProjectAutoImports(path); + _this.invalidateProjectPackageJson(path); watchers.get(path).close(); watchers.delete(path); } @@ -158110,16 +162838,16 @@ var ts; } }; /*@internal*/ - ProjectService.prototype.invalidateProjectAutoImports = function (packageJsonPath) { - if (this.includePackageJsonAutoImports()) { - this.configuredProjects.forEach(invalidate); - this.inferredProjects.forEach(invalidate); - this.externalProjects.forEach(invalidate); - } + ProjectService.prototype.invalidateProjectPackageJson = function (packageJsonPath) { + this.configuredProjects.forEach(invalidate); + this.inferredProjects.forEach(invalidate); + this.externalProjects.forEach(invalidate); function invalidate(project) { - var _a; - if (!packageJsonPath || ((_a = project.packageJsonsForAutoImport) === null || _a === void 0 ? void 0 : _a.has(packageJsonPath))) { - project.markAutoImportProviderAsDirty(); + if (packageJsonPath) { + project.onPackageJsonChange(packageJsonPath); + } + else { + project.onAutoImportProviderSettingsChanged(); } } }; @@ -158338,24 +163066,24 @@ var ts; try { if (this.operationHost.isCancellationRequested()) { stop = true; - ts.tracing.instant("session" /* Session */, "stepCanceled", { seq: this.requestId, early: true }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "stepCanceled", { seq: this.requestId, early: true }); } else { - ts.tracing.push("session" /* Session */, "stepAction", { seq: this.requestId }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("session" /* Session */, "stepAction", { seq: this.requestId }); action(this); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } } catch (e) { // Cancellation or an error may have left incomplete events on the tracing stack. - ts.tracing.popAll(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.popAll(); stop = true; // ignore cancellation request if (e instanceof ts.OperationCanceledException) { - ts.tracing.instant("session" /* Session */, "stepCanceled", { seq: this.requestId }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "stepCanceled", { seq: this.requestId }); } else { - ts.tracing.instant("session" /* Session */, "stepError", { seq: this.requestId, message: e.message }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "stepError", { seq: this.requestId, message: e.message }); this.operationHost.logError(e, "delayed processing of request " + this.requestId); } } @@ -158457,7 +163185,7 @@ var ts; function combineProjectOutputForReferences(projects, defaultProject, initialLocation) { var outputs = []; combineProjectOutputWorker(projects, defaultProject, initialLocation, function (project, location, getMappedLocation) { - var _loop_9 = function (outputReferencedSymbol) { + var _loop_8 = function (outputReferencedSymbol) { var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); var definition = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : __assign(__assign({}, outputReferencedSymbol.definition), { textSpan: ts.createTextSpan(mappedDefinitionFile.pos, outputReferencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName, contextSpan: getMappedContextSpan(outputReferencedSymbol.definition, project) }); @@ -158476,7 +163204,7 @@ var ts; }; for (var _i = 0, _a = project.getLanguageService().findReferences(location.fileName, location.pos) || server.emptyArray; _i < _a.length; _i++) { var outputReferencedSymbol = _a[_i]; - _loop_9(outputReferencedSymbol); + _loop_8(outputReferencedSymbol); } }); return outputs.filter(function (o) { return o.references.length !== 0; }); @@ -158889,10 +163617,10 @@ var ts; return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.CompletionsFull)); }, _a[server.CommandNames.CompletionDetails] = function (request) { - return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*simplifiedResult*/ true)); + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*fullResult*/ false)); }, _a[server.CommandNames.CompletionDetailsFull] = function (request) { - return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*simplifiedResult*/ false)); + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*fullResult*/ true)); }, _a[server.CommandNames.CompileOnSaveAffectedFileList] = function (request) { return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments)); @@ -159285,7 +164013,7 @@ var ts; this.host.write(msgText); }; Session.prototype.event = function (body, eventName) { - ts.tracing.instant("session" /* Session */, "event", { eventName: eventName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "event", { eventName: eventName }); this.send(toEvent(eventName, body)); }; // For backwards-compatibility only. @@ -159436,7 +164164,8 @@ var ts; }; Session.prototype.getEncodedSemanticClassifications = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - return project.getLanguageService().getEncodedSemanticClassifications(file, args); + var format = args.format === "2020" ? "2020" /* TwentyTwenty */ : "original" /* Original */; + return project.getLanguageService().getEncodedSemanticClassifications(file, args, format); }; Session.prototype.getProject = function (projectFileName) { return projectFileName === undefined ? undefined : this.projectService.findProject(projectFileName); @@ -159517,7 +164246,7 @@ var ts; Session.prototype.mapDefinitionInfoLocations = function (definitions, project) { return definitions.map(function (info) { var newDocumentSpan = getMappedDocumentSpan(info, project); - return !newDocumentSpan ? info : __assign(__assign({}, newDocumentSpan), { containerKind: info.containerKind, containerName: info.containerName, kind: info.kind, name: info.name }); + return !newDocumentSpan ? info : __assign(__assign(__assign({}, newDocumentSpan), { containerKind: info.containerKind, containerName: info.containerName, kind: info.kind, name: info.name }), info.unverified && { unverified: info.unverified }); }); }; Session.prototype.getDefinitionAndBoundSpan = function (args, simplifiedResult) { @@ -159555,9 +164284,27 @@ var ts; result.diagnostics.map(function (d) { return formatDiagnosticToProtocol(d, /*includeFileName*/ true); }) }) : result; }; + Session.prototype.mapJSDocTagInfo = function (tags, project, richResponse) { + var _this = this; + return tags ? tags.map(function (tag) { + var _a; + return (__assign(__assign({}, tag), { text: richResponse ? _this.mapDisplayParts(tag.text, project) : (_a = tag.text) === null || _a === void 0 ? void 0 : _a.map(function (part) { return part.text; }).join("") })); + }) : []; + }; + Session.prototype.mapDisplayParts = function (parts, project) { + var _this = this; + if (!parts) { + return []; + } + return parts.map(function (part) { return part.kind !== "linkName" ? part : __assign(__assign({}, part), { target: _this.toFileSpan(part.target.fileName, part.target.textSpan, project) }); }); + }; + Session.prototype.mapSignatureHelpItems = function (items, project, richResponse) { + var _this = this; + return items.map(function (item) { return (__assign(__assign({}, item), { documentation: _this.mapDisplayParts(item.documentation, project), parameters: item.parameters.map(function (p) { return (__assign(__assign({}, p), { documentation: _this.mapDisplayParts(p.documentation, project) })); }), tags: _this.mapJSDocTagInfo(item.tags, project, richResponse) })); }); + }; Session.prototype.mapDefinitionInfo = function (definitions, project) { var _this = this; - return definitions.map(function (def) { return _this.toFileSpanWithContext(def.fileName, def.textSpan, def.contextSpan, project); }); + return definitions.map(function (def) { return (__assign(__assign({}, _this.toFileSpanWithContext(def.fileName, def.textSpan, def.contextSpan, project)), def.unverified && { unverified: def.unverified })); }); }; /* * When we map a .d.ts location to .ts, Visual Studio gets confused because there's no associated Roslyn Document in @@ -159864,7 +164611,7 @@ var ts; Session.prototype.getDocCommentTemplate = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; var position = this.getPositionInFile(args, file); - return languageService.getDocCommentTemplateAtPosition(file, position); + return languageService.getDocCommentTemplateAtPosition(file, position, this.getPreferences(file)); }; Session.prototype.getSpanOfEnclosingComment = function (args) { var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService; @@ -159901,21 +164648,21 @@ var ts; if (!quickInfo) { return undefined; } + var useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc; if (simplifiedResult) { var displayString = ts.displayPartsToString(quickInfo.displayParts); - var docString = ts.displayPartsToString(quickInfo.documentation); return { kind: quickInfo.kind, kindModifiers: quickInfo.kindModifiers, start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start), end: scriptInfo.positionToLineOffset(ts.textSpanEnd(quickInfo.textSpan)), displayString: displayString, - documentation: docString, - tags: quickInfo.tags || [] + documentation: useDisplayParts ? this.mapDisplayParts(quickInfo.documentation, project) : ts.displayPartsToString(quickInfo.documentation), + tags: this.mapJSDocTagInfo(quickInfo.tags, project, useDisplayParts), }; } else { - return quickInfo; + return useDisplayParts ? quickInfo : __assign(__assign({}, quickInfo), { tags: this.mapJSDocTagInfo(quickInfo.tags, project, /*useDisplayParts*/ false) }); } }; Session.prototype.getFormattingEditsForRange = function (args) { @@ -160006,14 +164753,14 @@ var ts; if (kind === "completions-full" /* CompletionsFull */) return completions; var prefix = args.prefix || ""; - var entries = ts.mapDefined(completions.entries, function (entry) { + var entries = ts.stableSort(ts.mapDefined(completions.entries, function (entry) { if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { - var name = entry.name, kind_1 = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended, isPackageJsonImport = entry.isPackageJsonImport; + var name = entry.name, kind_1 = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, sourceDisplay = entry.sourceDisplay, isSnippet = entry.isSnippet, isRecommended = entry.isRecommended, isPackageJsonImport = entry.isPackageJsonImport, isImportStatementCompletion = entry.isImportStatementCompletion, data = entry.data; var convertedSpan = replacementSpan ? toProtocolTextSpan(replacementSpan, scriptInfo) : undefined; // Use `hasAction || undefined` to avoid serializing `false`. - return { name: name, kind: kind_1, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended, isPackageJsonImport: isPackageJsonImport }; + return { name: name, kind: kind_1, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, isSnippet: isSnippet, hasAction: hasAction || undefined, source: source, sourceDisplay: sourceDisplay, isRecommended: isRecommended, isPackageJsonImport: isPackageJsonImport, isImportStatementCompletion: isImportStatementCompletion, data: data }; } - }).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); + }), function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); if (kind === "completions" /* Completions */) { if (completions.metadata) entries.metadata = completions.metadata; @@ -160022,19 +164769,20 @@ var ts; var res = __assign(__assign({}, completions), { optionalReplacementSpan: completions.optionalReplacementSpan && toProtocolTextSpan(completions.optionalReplacementSpan, scriptInfo), entries: entries }); return res; }; - Session.prototype.getCompletionEntryDetails = function (args, simplifiedResult) { + Session.prototype.getCompletionEntryDetails = function (args, fullResult) { var _this = this; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); var formattingOptions = project.projectService.getFormatCodeOptions(file); + var useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc; var result = ts.mapDefined(args.entryNames, function (entryName) { - var _a = typeof entryName === "string" ? { name: entryName, source: undefined } : entryName, name = _a.name, source = _a.source; - return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source, _this.getPreferences(file)); + var _a = typeof entryName === "string" ? { name: entryName, source: undefined, data: undefined } : entryName, name = _a.name, source = _a.source, data = _a.data; + return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source, _this.getPreferences(file), data ? ts.cast(data, isCompletionEntryData) : undefined); }); - return simplifiedResult - ? result.map(function (details) { return (__assign(__assign({}, details), { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(action); }) })); }) - : result; + return fullResult + ? (useDisplayParts ? result : result.map(function (details) { return (__assign(__assign({}, details), { tags: _this.mapJSDocTagInfo(details.tags, project, /*richResponse*/ false) })); })) + : result.map(function (details) { return (__assign(__assign({}, details), { codeActions: ts.map(details.codeActions, function (action) { return _this.mapCodeAction(action); }), documentation: _this.mapDisplayParts(details.documentation, project), tags: _this.mapJSDocTagInfo(details.tags, project, useDisplayParts) })); }); }; Session.prototype.getCompileOnSaveAffectedFileList = function (args) { var _this = this; @@ -160080,29 +164828,25 @@ var ts; !emitSkipped; }; Session.prototype.getSignatureHelpItems = function (args, simplifiedResult) { + var _this = this; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); var helpItems = project.getLanguageService().getSignatureHelpItems(file, position, args); - if (!helpItems) { - return undefined; - } - if (simplifiedResult) { + var useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc; + if (helpItems && simplifiedResult) { var span = helpItems.applicableSpan; - return { - items: helpItems.items, - applicableSpan: { + return __assign(__assign({}, helpItems), { applicableSpan: { start: scriptInfo.positionToLineOffset(span.start), end: scriptInfo.positionToLineOffset(span.start + span.length) - }, - selectedItemIndex: helpItems.selectedItemIndex, - argumentIndex: helpItems.argumentIndex, - argumentCount: helpItems.argumentCount, - }; + }, items: this.mapSignatureHelpItems(helpItems.items, project, useDisplayParts) }); } - else { + else if (useDisplayParts || !helpItems) { return helpItems; } + else { + return __assign(__assign({}, helpItems), { items: helpItems.items.map(function (item) { return (__assign(__assign({}, item), { tags: _this.mapJSDocTagInfo(item.tags, project, /*richResponse*/ false) })); }) }); + } }; Session.prototype.toPendingErrorCheck = function (uncheckedFileName) { var fileName = server.toNormalizedPath(uncheckedFileName); @@ -160308,11 +165052,14 @@ var ts; return result; } }; - Session.prototype.organizeImports = function (_a, simplifiedResult) { - var scope = _a.scope; - ts.Debug.assert(scope.type === "file"); - var _b = this.getFileAndProject(scope.args), file = _b.file, project = _b.project; - var changes = project.getLanguageService().organizeImports({ type: "file", fileName: file }, this.getFormatOptions(file), this.getPreferences(file)); + Session.prototype.organizeImports = function (args, simplifiedResult) { + ts.Debug.assert(args.scope.type === "file"); + var _a = this.getFileAndProject(args.scope.args), file = _a.file, project = _a.project; + var changes = project.getLanguageService().organizeImports({ + fileName: file, + skipDestructiveCodeActions: args.skipDestructiveCodeActions, + type: "file", + }, this.getFormatOptions(file), this.getPreferences(file)); if (simplifiedResult) { return this.mapTextChangesToCodeEdits(changes); } @@ -160334,7 +165081,22 @@ var ts; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var _b = this.getStartAndEndPosition(args, scriptInfo), startPosition = _b.startPosition, endPosition = _b.endPosition; - var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file)); + var codeActions; + try { + codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file)); + } + catch (e) { + var ls = project.getLanguageService(); + var existingDiagCodes_1 = __spreadArray(__spreadArray(__spreadArray([], ls.getSyntacticDiagnostics(file)), ls.getSemanticDiagnostics(file)), ls.getSuggestionDiagnostics(file)).map(function (d) { + return ts.decodedTextSpanIntersectsWith(startPosition, endPosition - startPosition, d.start, d.length) + && d.code; + }); + var badCode = args.errorCodes.find(function (c) { return !existingDiagCodes_1.includes(c); }); + if (badCode !== undefined) { + e.message = "BADCLIENT: Bad error code, " + badCode + " not found in range " + startPosition + ".." + endPosition + " (found: " + existingDiagCodes_1.join(", ") + "); could have caused this error:\n" + e.message; + } + throw e; + } return simplifiedResult ? codeActions.map(function (codeAction) { return _this.mapCodeFixAction(codeAction); }) : codeActions; }; Session.prototype.getCombinedCodeFix = function (_a, simplifiedResult) { @@ -160657,11 +165419,11 @@ var ts; try { request = this.parseMessage(message); relevantFile = request.arguments && request.arguments.file ? request.arguments : undefined; - ts.tracing.instant("session" /* Session */, "request", { seq: request.seq, command: request.command }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "request", { seq: request.seq, command: request.command }); ts.perfLogger.logStartCommand("" + request.command, this.toStringMessage(message).substring(0, 100)); - ts.tracing.push("session" /* Session */, "executeCommand", { seq: request.seq, command: request.command }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("session" /* Session */, "executeCommand", { seq: request.seq, command: request.command }, /*separateBeginAndEnd*/ true); var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (this.logger.hasLevel(server.LogLevel.requestTime)) { var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); if (responseRequired) { @@ -160673,7 +165435,7 @@ var ts; } // Note: Log before writing the response, else the editor can complete its activity before the server does ts.perfLogger.logStopCommand("" + request.command, "Success"); - ts.tracing.instant("session" /* Session */, "response", { seq: request.seq, command: request.command, success: !!response }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "response", { seq: request.seq, command: request.command, success: !!response }); if (response) { this.doOutput(response, request.command, request.seq, /*success*/ true); } @@ -160683,17 +165445,17 @@ var ts; } catch (err) { // Cancellation or an error may have left incomplete events on the tracing stack. - ts.tracing.popAll(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.popAll(); if (err instanceof ts.OperationCanceledException) { // Handle cancellation exceptions ts.perfLogger.logStopCommand("" + (request && request.command), "Canceled: " + err); - ts.tracing.instant("session" /* Session */, "commandCanceled", { seq: request === null || request === void 0 ? void 0 : request.seq, command: request === null || request === void 0 ? void 0 : request.command }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "commandCanceled", { seq: request === null || request === void 0 ? void 0 : request.seq, command: request === null || request === void 0 ? void 0 : request.command }); this.doOutput({ canceled: true }, request.command, request.seq, /*success*/ true); return; } this.logErrorWorker(err, this.toStringMessage(message), relevantFile); ts.perfLogger.logStopCommand("" + (request && request.command), "Error: " + err); - ts.tracing.instant("session" /* Session */, "commandError", { seq: request === null || request === void 0 ? void 0 : request.seq, command: request === null || request === void 0 ? void 0 : request.command, message: err.message }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "commandError", { seq: request === null || request === void 0 ? void 0 : request.seq, command: request === null || request === void 0 ? void 0 : request.command, message: err.message }); this.doOutput( /*info*/ undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, /*success*/ false, "Error processing request. " + err.message + "\n" + err.stack); @@ -160777,6 +165539,13 @@ var ts; isWriteAccess: isWriteAccess, isDefinition: isDefinition }); } + function isCompletionEntryData(data) { + return data === undefined || data && typeof data === "object" + && typeof data.exportName === "string" + && (data.fileName === undefined || typeof data.fileName === "string") + && (data.ambientModuleName === undefined || typeof data.ambientModuleName === "string" + && (data.isPackageJsonImport === undefined || typeof data.isPackageJsonImport === "boolean")); + } })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); /*@internal*/ @@ -162356,7 +167125,7 @@ var ts; }, factoryDeprecation); /** @deprecated Use `factory.createJSDocParameterTag` or the factory supplied by your transformation context instead. */ ts.createJSDocParamTag = ts.Debug.deprecate(function createJSDocParamTag(name, isBracketed, typeExpression, comment) { - return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, isBracketed, typeExpression, /*isNameFirst*/ false, comment); + return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, isBracketed, typeExpression, /*isNameFirst*/ false, comment ? ts.factory.createNodeArray([ts.factory.createJSDocText(comment)]) : undefined); }, factoryDeprecation); /** @deprecated Use `factory.createComma` or the factory supplied by your transformation context instead. */ ts.createComma = ts.Debug.deprecate(function createComma(left, right) { @@ -162406,7 +167175,7 @@ var ts; ts.createNode = ts.Debug.deprecate(function createNode(kind, pos, end) { if (pos === void 0) { pos = 0; } if (end === void 0) { end = 0; } - return ts.setTextRangePosEnd(kind === 297 /* SourceFile */ ? ts.parseBaseNodeFactory.createBaseSourceFileNode(kind) : + return ts.setTextRangePosEnd(kind === 298 /* SourceFile */ ? ts.parseBaseNodeFactory.createBaseSourceFileNode(kind) : kind === 78 /* Identifier */ ? ts.parseBaseNodeFactory.createBaseIdentifierNode(kind) : kind === 79 /* PrivateIdentifier */ ? ts.parseBaseNodeFactory.createBasePrivateIdentifierNode(kind) : !ts.isNodeKind(kind) ? ts.parseBaseNodeFactory.createBaseTokenNode(kind) : @@ -162435,13 +167204,30 @@ var ts; // #region Renamed node Tests /** @deprecated Use `isTypeAssertionExpression` instead. */ ts.isTypeAssertion = ts.Debug.deprecate(function isTypeAssertion(node) { - return node.kind === 206 /* TypeAssertionExpression */; + return node.kind === 207 /* TypeAssertionExpression */; }, { since: "4.0", warnAfter: "4.1", message: "Use `isTypeAssertionExpression` instead." }); // #endregion + // DEPRECATION: Renamed node tests + // DEPRECATION PLAN: + // - soft: 4.2 + // - warn: 4.3 + // - error: TBD + // #region Renamed node Tests + /** + * @deprecated Use `isMemberName` instead. + */ + ts.isIdentifierOrPrivateIdentifier = ts.Debug.deprecate(function isIdentifierOrPrivateIdentifier(node) { + return ts.isMemberName(node); + }, { + since: "4.2", + warnAfter: "4.3", + message: "Use `isMemberName` instead." + }); + // #endregion Renamed node Tests })(ts || (ts = {})); //# sourceMappingURL=tsserverlibrary.js.map diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index f8f86d5b88fb2..b86a3a29970a4 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 = "4.2"; + const versionMajorMinor = "4.3"; /** The version of the TypeScript compiler release */ const version: string; /** @@ -260,192 +260,196 @@ declare namespace ts { FromKeyword = 153, GlobalKeyword = 154, BigIntKeyword = 155, - OfKeyword = 156, - QualifiedName = 157, - ComputedPropertyName = 158, - TypeParameter = 159, - Parameter = 160, - Decorator = 161, - PropertySignature = 162, - PropertyDeclaration = 163, - MethodSignature = 164, - MethodDeclaration = 165, - Constructor = 166, - GetAccessor = 167, - SetAccessor = 168, - CallSignature = 169, - ConstructSignature = 170, - IndexSignature = 171, - TypePredicate = 172, - TypeReference = 173, - FunctionType = 174, - ConstructorType = 175, - TypeQuery = 176, - TypeLiteral = 177, - ArrayType = 178, - TupleType = 179, - OptionalType = 180, - RestType = 181, - UnionType = 182, - IntersectionType = 183, - ConditionalType = 184, - InferType = 185, - ParenthesizedType = 186, - ThisType = 187, - TypeOperator = 188, - IndexedAccessType = 189, - MappedType = 190, - LiteralType = 191, - NamedTupleMember = 192, - TemplateLiteralType = 193, - TemplateLiteralTypeSpan = 194, - ImportType = 195, - ObjectBindingPattern = 196, - ArrayBindingPattern = 197, - BindingElement = 198, - ArrayLiteralExpression = 199, - ObjectLiteralExpression = 200, - PropertyAccessExpression = 201, - ElementAccessExpression = 202, - CallExpression = 203, - NewExpression = 204, - TaggedTemplateExpression = 205, - TypeAssertionExpression = 206, - ParenthesizedExpression = 207, - FunctionExpression = 208, - ArrowFunction = 209, - DeleteExpression = 210, - TypeOfExpression = 211, - VoidExpression = 212, - AwaitExpression = 213, - PrefixUnaryExpression = 214, - PostfixUnaryExpression = 215, - BinaryExpression = 216, - ConditionalExpression = 217, - TemplateExpression = 218, - YieldExpression = 219, - SpreadElement = 220, - ClassExpression = 221, - OmittedExpression = 222, - ExpressionWithTypeArguments = 223, - AsExpression = 224, - NonNullExpression = 225, - MetaProperty = 226, - SyntheticExpression = 227, - TemplateSpan = 228, - SemicolonClassElement = 229, - Block = 230, - EmptyStatement = 231, - VariableStatement = 232, - ExpressionStatement = 233, - IfStatement = 234, - DoStatement = 235, - WhileStatement = 236, - ForStatement = 237, - ForInStatement = 238, - ForOfStatement = 239, - ContinueStatement = 240, - BreakStatement = 241, - ReturnStatement = 242, - WithStatement = 243, - SwitchStatement = 244, - LabeledStatement = 245, - ThrowStatement = 246, - TryStatement = 247, - DebuggerStatement = 248, - VariableDeclaration = 249, - VariableDeclarationList = 250, - FunctionDeclaration = 251, - ClassDeclaration = 252, - InterfaceDeclaration = 253, - TypeAliasDeclaration = 254, - EnumDeclaration = 255, - ModuleDeclaration = 256, - ModuleBlock = 257, - CaseBlock = 258, - NamespaceExportDeclaration = 259, - ImportEqualsDeclaration = 260, - ImportDeclaration = 261, - ImportClause = 262, - NamespaceImport = 263, - NamedImports = 264, - ImportSpecifier = 265, - ExportAssignment = 266, - ExportDeclaration = 267, - NamedExports = 268, - NamespaceExport = 269, - ExportSpecifier = 270, - MissingDeclaration = 271, - ExternalModuleReference = 272, - JsxElement = 273, - JsxSelfClosingElement = 274, - JsxOpeningElement = 275, - JsxClosingElement = 276, - JsxFragment = 277, - JsxOpeningFragment = 278, - JsxClosingFragment = 279, - JsxAttribute = 280, - JsxAttributes = 281, - JsxSpreadAttribute = 282, - JsxExpression = 283, - CaseClause = 284, - DefaultClause = 285, - HeritageClause = 286, - CatchClause = 287, - PropertyAssignment = 288, - ShorthandPropertyAssignment = 289, - SpreadAssignment = 290, - EnumMember = 291, - UnparsedPrologue = 292, - UnparsedPrepend = 293, - UnparsedText = 294, - UnparsedInternalText = 295, - UnparsedSyntheticReference = 296, - SourceFile = 297, - Bundle = 298, - UnparsedSource = 299, - InputFiles = 300, - JSDocTypeExpression = 301, - JSDocNameReference = 302, - JSDocAllType = 303, - JSDocUnknownType = 304, - JSDocNullableType = 305, - JSDocNonNullableType = 306, - JSDocOptionalType = 307, - JSDocFunctionType = 308, - JSDocVariadicType = 309, - JSDocNamepathType = 310, - JSDocComment = 311, - JSDocTypeLiteral = 312, - JSDocSignature = 313, - JSDocTag = 314, - JSDocAugmentsTag = 315, - JSDocImplementsTag = 316, - JSDocAuthorTag = 317, - JSDocDeprecatedTag = 318, - JSDocClassTag = 319, - JSDocPublicTag = 320, - JSDocPrivateTag = 321, - JSDocProtectedTag = 322, - JSDocReadonlyTag = 323, - JSDocCallbackTag = 324, - JSDocEnumTag = 325, - JSDocParameterTag = 326, - JSDocReturnTag = 327, - JSDocThisTag = 328, - JSDocTypeTag = 329, - JSDocTemplateTag = 330, - JSDocTypedefTag = 331, - JSDocSeeTag = 332, - JSDocPropertyTag = 333, - SyntaxList = 334, - NotEmittedStatement = 335, - PartiallyEmittedExpression = 336, - CommaListExpression = 337, - MergeDeclarationMarker = 338, - EndOfDeclarationMarker = 339, - SyntheticReferenceExpression = 340, - Count = 341, + OverrideKeyword = 156, + OfKeyword = 157, + QualifiedName = 158, + ComputedPropertyName = 159, + TypeParameter = 160, + Parameter = 161, + Decorator = 162, + PropertySignature = 163, + PropertyDeclaration = 164, + MethodSignature = 165, + MethodDeclaration = 166, + Constructor = 167, + GetAccessor = 168, + SetAccessor = 169, + CallSignature = 170, + ConstructSignature = 171, + IndexSignature = 172, + TypePredicate = 173, + TypeReference = 174, + FunctionType = 175, + ConstructorType = 176, + TypeQuery = 177, + TypeLiteral = 178, + ArrayType = 179, + TupleType = 180, + OptionalType = 181, + RestType = 182, + UnionType = 183, + IntersectionType = 184, + ConditionalType = 185, + InferType = 186, + ParenthesizedType = 187, + ThisType = 188, + TypeOperator = 189, + IndexedAccessType = 190, + MappedType = 191, + LiteralType = 192, + NamedTupleMember = 193, + TemplateLiteralType = 194, + TemplateLiteralTypeSpan = 195, + ImportType = 196, + ObjectBindingPattern = 197, + ArrayBindingPattern = 198, + BindingElement = 199, + ArrayLiteralExpression = 200, + ObjectLiteralExpression = 201, + PropertyAccessExpression = 202, + ElementAccessExpression = 203, + CallExpression = 204, + NewExpression = 205, + TaggedTemplateExpression = 206, + TypeAssertionExpression = 207, + ParenthesizedExpression = 208, + FunctionExpression = 209, + ArrowFunction = 210, + DeleteExpression = 211, + TypeOfExpression = 212, + VoidExpression = 213, + AwaitExpression = 214, + PrefixUnaryExpression = 215, + PostfixUnaryExpression = 216, + BinaryExpression = 217, + ConditionalExpression = 218, + TemplateExpression = 219, + YieldExpression = 220, + SpreadElement = 221, + ClassExpression = 222, + OmittedExpression = 223, + ExpressionWithTypeArguments = 224, + AsExpression = 225, + NonNullExpression = 226, + MetaProperty = 227, + SyntheticExpression = 228, + TemplateSpan = 229, + SemicolonClassElement = 230, + Block = 231, + EmptyStatement = 232, + VariableStatement = 233, + ExpressionStatement = 234, + IfStatement = 235, + DoStatement = 236, + WhileStatement = 237, + ForStatement = 238, + ForInStatement = 239, + ForOfStatement = 240, + ContinueStatement = 241, + BreakStatement = 242, + ReturnStatement = 243, + WithStatement = 244, + SwitchStatement = 245, + LabeledStatement = 246, + ThrowStatement = 247, + TryStatement = 248, + DebuggerStatement = 249, + VariableDeclaration = 250, + VariableDeclarationList = 251, + FunctionDeclaration = 252, + ClassDeclaration = 253, + InterfaceDeclaration = 254, + TypeAliasDeclaration = 255, + EnumDeclaration = 256, + ModuleDeclaration = 257, + ModuleBlock = 258, + CaseBlock = 259, + NamespaceExportDeclaration = 260, + ImportEqualsDeclaration = 261, + ImportDeclaration = 262, + ImportClause = 263, + NamespaceImport = 264, + NamedImports = 265, + ImportSpecifier = 266, + ExportAssignment = 267, + ExportDeclaration = 268, + NamedExports = 269, + NamespaceExport = 270, + ExportSpecifier = 271, + MissingDeclaration = 272, + ExternalModuleReference = 273, + JsxElement = 274, + JsxSelfClosingElement = 275, + JsxOpeningElement = 276, + JsxClosingElement = 277, + JsxFragment = 278, + JsxOpeningFragment = 279, + JsxClosingFragment = 280, + JsxAttribute = 281, + JsxAttributes = 282, + JsxSpreadAttribute = 283, + JsxExpression = 284, + CaseClause = 285, + DefaultClause = 286, + HeritageClause = 287, + CatchClause = 288, + PropertyAssignment = 289, + ShorthandPropertyAssignment = 290, + SpreadAssignment = 291, + EnumMember = 292, + UnparsedPrologue = 293, + UnparsedPrepend = 294, + UnparsedText = 295, + UnparsedInternalText = 296, + UnparsedSyntheticReference = 297, + SourceFile = 298, + Bundle = 299, + UnparsedSource = 300, + InputFiles = 301, + JSDocTypeExpression = 302, + JSDocNameReference = 303, + JSDocAllType = 304, + JSDocUnknownType = 305, + JSDocNullableType = 306, + JSDocNonNullableType = 307, + JSDocOptionalType = 308, + JSDocFunctionType = 309, + JSDocVariadicType = 310, + JSDocNamepathType = 311, + JSDocComment = 312, + JSDocText = 313, + JSDocTypeLiteral = 314, + JSDocSignature = 315, + JSDocLink = 316, + JSDocTag = 317, + JSDocAugmentsTag = 318, + JSDocImplementsTag = 319, + JSDocAuthorTag = 320, + JSDocDeprecatedTag = 321, + JSDocClassTag = 322, + JSDocPublicTag = 323, + JSDocPrivateTag = 324, + JSDocProtectedTag = 325, + JSDocReadonlyTag = 326, + JSDocOverrideTag = 327, + JSDocCallbackTag = 328, + JSDocEnumTag = 329, + JSDocParameterTag = 330, + JSDocReturnTag = 331, + JSDocThisTag = 332, + JSDocTypeTag = 333, + JSDocTemplateTag = 334, + JSDocTypedefTag = 335, + JSDocSeeTag = 336, + JSDocPropertyTag = 337, + SyntaxList = 338, + NotEmittedStatement = 339, + PartiallyEmittedExpression = 340, + CommaListExpression = 341, + MergeDeclarationMarker = 342, + EndOfDeclarationMarker = 343, + SyntheticReferenceExpression = 344, + Count = 345, FirstAssignment = 62, LastAssignment = 77, FirstCompoundAssignment = 63, @@ -453,15 +457,15 @@ declare namespace ts { FirstReservedWord = 80, LastReservedWord = 115, FirstKeyword = 80, - LastKeyword = 156, + LastKeyword = 157, FirstFutureReservedWord = 116, LastFutureReservedWord = 124, - FirstTypeNode = 172, - LastTypeNode = 195, + FirstTypeNode = 173, + LastTypeNode = 196, FirstPunctuation = 18, LastPunctuation = 77, FirstToken = 0, - LastToken = 156, + LastToken = 157, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, @@ -470,20 +474,20 @@ declare namespace ts { LastTemplateToken = 17, FirstBinaryOperator = 29, LastBinaryOperator = 77, - FirstStatement = 232, - LastStatement = 248, - FirstNode = 157, - FirstJSDocNode = 301, - LastJSDocNode = 333, - FirstJSDocTagNode = 314, - LastJSDocTagNode = 333, + FirstStatement = 233, + LastStatement = 249, + FirstNode = 158, + FirstJSDocNode = 302, + LastJSDocNode = 337, + FirstJSDocTagNode = 317, + LastJSDocTagNode = 337, } export type TriviaSyntaxKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; export type LiteralSyntaxKind = SyntaxKind.NumericLiteral | SyntaxKind.BigIntLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral; export type PseudoLiteralSyntaxKind = SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle | SyntaxKind.TemplateTail; export type PunctuationSyntaxKind = SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.CloseParenToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.DotToken | SyntaxKind.DotDotDotToken | SyntaxKind.SemicolonToken | SyntaxKind.CommaToken | SyntaxKind.QuestionDotToken | SyntaxKind.LessThanToken | SyntaxKind.LessThanSlashToken | SyntaxKind.GreaterThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.EqualsEqualsToken | SyntaxKind.ExclamationEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.EqualsGreaterThanToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.AsteriskToken | SyntaxKind.AsteriskAsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken | SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken | SyntaxKind.ExclamationToken | SyntaxKind.TildeToken | SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken | SyntaxKind.QuestionQuestionToken | SyntaxKind.QuestionToken | SyntaxKind.ColonToken | SyntaxKind.AtToken | SyntaxKind.BacktickToken | SyntaxKind.EqualsToken | SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken; - export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | 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.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | 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; - export type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.StaticKeyword; + export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | 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.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | 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; + export type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword; export type KeywordTypeSyntaxKind = SyntaxKind.AnyKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VoidKeyword; export type TokenSyntaxKind = SyntaxKind.Unknown | SyntaxKind.EndOfFileToken | TriviaSyntaxKind | LiteralSyntaxKind | PseudoLiteralSyntaxKind | PunctuationSyntaxKind | SyntaxKind.Identifier | KeywordSyntaxKind; export type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; @@ -533,13 +537,14 @@ declare namespace ts { Const = 2048, HasComputedJSDocModifiers = 4096, Deprecated = 8192, + Override = 16384, HasComputedFlags = 536870912, AccessibilityModifier = 28, - ParameterPropertyModifier = 92, + ParameterPropertyModifier = 16476, NonPublicAccessibilityModifier = 24, - TypeScriptModifier = 2270, + TypeScriptModifier = 18654, ExportDefault = 513, - All = 11263 + All = 27647 } export enum JsxFlags { None = 0, @@ -558,7 +563,7 @@ declare namespace ts { } export interface JSDocContainer { } - export type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | NamespaceExportDeclaration | ExportAssignment | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | NamedTupleMember | EndOfFileToken; + export type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | EmptyStatement | DebuggerStatement | Block | VariableStatement | ExpressionStatement | IfStatement | DoStatement | WhileStatement | ForStatement | ForInStatement | ForOfStatement | BreakStatement | ContinueStatement | ReturnStatement | WithStatement | SwitchStatement | LabeledStatement | ThrowStatement | TryStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | VariableDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | NamespaceExportDeclaration | ExportAssignment | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | NamedTupleMember | EndOfFileToken; export type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; export type HasTypeArguments = CallExpression | NewExpression | TaggedTemplateExpression | JsxOpeningElement | JsxSelfClosingElement; export type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; @@ -603,10 +608,11 @@ declare namespace ts { export type ProtectedKeyword = ModifierToken; export type PublicKeyword = ModifierToken; export type ReadonlyKeyword = ModifierToken; + export type OverrideKeyword = ModifierToken; export type StaticKeyword = ModifierToken; /** @deprecated Use `ReadonlyKeyword` instead. */ export type ReadonlyToken = ReadonlyKeyword; - export type Modifier = AbstractKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | ReadonlyKeyword | StaticKeyword; + export type Modifier = AbstractKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | OverrideKeyword | ReadonlyKeyword | StaticKeyword; export type AccessibilityModifier = PublicKeyword | PrivateKeyword | ProtectedKeyword; export type ParameterPropertyModifier = AccessibilityModifier | ReadonlyKeyword; export type ClassMemberModifier = AccessibilityModifier | ReadonlyKeyword | StaticKeyword; @@ -638,6 +644,7 @@ declare namespace ts { } export type EntityName = Identifier | QualifiedName; export type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | PrivateIdentifier; + export type MemberName = Identifier | PrivateIdentifier; export type DeclarationName = Identifier | PrivateIdentifier | StringLiteralLike | NumericLiteral | ComputedPropertyName | ElementAccessExpression | BindingPattern | EntityNameExpression; export interface Declaration extends Node { _declarationBrand: any; @@ -686,7 +693,7 @@ declare namespace ts { readonly kind: SyntaxKind.ConstructSignature; } export type BindingName = Identifier | BindingPattern; - export interface VariableDeclaration extends NamedDeclaration { + export interface VariableDeclaration extends NamedDeclaration, JSDocContainer { readonly kind: SyntaxKind.VariableDeclaration; readonly parent: VariableDeclarationList | CatchClause; readonly name: BindingName; @@ -820,15 +827,15 @@ declare namespace ts { readonly kind: SyntaxKind.SemicolonClassElement; readonly parent: ClassLikeDeclaration; } - export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.GetAccessor; - readonly parent: ClassLikeDeclaration | ObjectLiteralExpression; + readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; readonly name: PropertyName; readonly body?: FunctionBody; } - export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.SetAccessor; - readonly parent: ClassLikeDeclaration | ObjectLiteralExpression; + readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; readonly name: PropertyName; readonly body?: FunctionBody; } @@ -1216,11 +1223,11 @@ declare namespace ts { readonly kind: SyntaxKind.PropertyAccessExpression; readonly expression: LeftHandSideExpression; readonly questionDotToken?: QuestionDotToken; - readonly name: Identifier | PrivateIdentifier; + readonly name: MemberName; } export interface PropertyAccessChain extends PropertyAccessExpression { _optionalChainBrand: any; - readonly name: Identifier | PrivateIdentifier; + readonly name: MemberName; } export interface SuperPropertyAccessExpression extends PropertyAccessExpression { readonly expression: SuperExpression; @@ -1373,7 +1380,7 @@ declare namespace ts { readonly containsOnlyTriviaWhiteSpaces: boolean; } export type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; - export interface Statement extends Node { + export interface Statement extends Node, JSDocContainer { _statementBrand: any; } export interface NotEmittedStatement extends Statement { @@ -1401,11 +1408,11 @@ declare namespace ts { readonly kind: SyntaxKind.Block; readonly statements: NodeArray; } - export interface VariableStatement extends Statement, JSDocContainer { + export interface VariableStatement extends Statement { readonly kind: SyntaxKind.VariableStatement; readonly declarationList: VariableDeclarationList; } - export interface ExpressionStatement extends Statement, JSDocContainer { + export interface ExpressionStatement extends Statement { readonly kind: SyntaxKind.ExpressionStatement; readonly expression: Expression; } @@ -1486,7 +1493,7 @@ declare namespace ts { readonly statements: NodeArray; } export type CaseOrDefaultClause = CaseClause | DefaultClause; - export interface LabeledStatement extends Statement, JSDocContainer { + export interface LabeledStatement extends Statement { readonly kind: SyntaxKind.LabeledStatement; readonly label: Identifier; readonly statement: Statement; @@ -1606,7 +1613,7 @@ declare namespace ts { readonly parent: ImportEqualsDeclaration; readonly expression: Expression; } - export interface ImportDeclaration extends Statement, JSDocContainer { + export interface ImportDeclaration extends Statement { readonly kind: SyntaxKind.ImportDeclaration; readonly parent: SourceFile | ModuleBlock; readonly importClause?: ImportClause; @@ -1742,12 +1749,21 @@ declare namespace ts { readonly kind: SyntaxKind.JSDocComment; readonly parent: HasJSDoc; readonly tags?: NodeArray; - readonly comment?: string; + readonly comment?: string | NodeArray; } export interface JSDocTag extends Node { readonly parent: JSDoc | JSDocTypeLiteral; readonly tagName: Identifier; - readonly comment?: string; + readonly comment?: string | NodeArray; + } + export interface JSDocLink extends Node { + readonly kind: SyntaxKind.JSDocLink; + readonly name?: EntityName; + text: string; + } + export interface JSDocText extends Node { + readonly kind: SyntaxKind.JSDocText; + text: string; } export interface JSDocUnknownTag extends JSDocTag { readonly kind: SyntaxKind.JSDocTag; @@ -1789,6 +1805,9 @@ declare namespace ts { export interface JSDocReadonlyTag extends JSDocTag { readonly kind: SyntaxKind.JSDocReadonlyTag; } + export interface JSDocOverrideTag extends JSDocTag { + readonly kind: SyntaxKind.JSDocOverrideTag; + } export interface JSDocEnumTag extends JSDocTag, Declaration { readonly kind: SyntaxKind.JSDocEnumTag; readonly parent: JSDoc; @@ -2080,7 +2099,6 @@ declare namespace ts { * Gets a type checker that can be used to semantically analyze source files in the program. */ getTypeChecker(): TypeChecker; - getTypeCatalog(): readonly Type[]; getNodeCount(): number; getIdentifierCount(): number; getSymbolCount(): number; @@ -2186,7 +2204,7 @@ declare namespace ts { * The function returns the value (local variable) symbol of an identifier in the short-hand property assignment. * This is necessary as an identifier in short-hand property assignment can contains two meaning: property name and property value. */ - getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getShorthandAssignmentValueSymbol(location: Node | undefined): Symbol | undefined; getExportSpecifierLocalTargetSymbol(location: ExportSpecifier | Identifier): Symbol | undefined; /** * If a symbol is a local symbol with an associated exported symbol, returns the exported symbol. @@ -2261,6 +2279,8 @@ declare namespace ts { NoTypeReduction = 536870912, NoUndefinedOptionalParameterType = 1073741824, AllowThisInObjectLiteral = 32768, + AllowQualifiedNameInPlaceOfIdentifier = 65536, + /** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */ AllowQualifedNameInPlaceOfIdentifier = 65536, AllowAnonymousIdentifier = 131072, AllowEmptyUnionOrIntersection = 262144, @@ -2271,8 +2291,7 @@ declare namespace ts { IgnoreErrors = 70221824, InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, - InInitialEntityName = 16777216, - InReverseMappedType = 33554432 + InInitialEntityName = 16777216 } export enum TypeFormatFlags { None = 0, @@ -2405,8 +2424,8 @@ declare namespace ts { export interface Symbol { flags: SymbolFlags; escapedName: __String; - declarations: Declaration[]; - valueDeclaration: Declaration; + declarations?: Declaration[]; + valueDeclaration?: Declaration; members?: SymbolTable; exports?: SymbolTable; globalExports?: SymbolTable; @@ -2540,15 +2559,15 @@ declare namespace ts { ObjectLiteral = 128, EvolvingArray = 256, ObjectLiteralPatternWithComputedProperties = 512, - ContainsSpread = 1024, - ReverseMapped = 2048, - JsxAttributes = 4096, - MarkerType = 8192, - JSLiteral = 16384, - FreshLiteral = 32768, - ArrayLiteral = 65536, - ObjectRestType = 131072, + ReverseMapped = 1024, + JsxAttributes = 2048, + MarkerType = 4096, + JSLiteral = 8192, + FreshLiteral = 16384, + ArrayLiteral = 32768, ClassOrInterface = 3, + ContainsSpread = 4194304, + ObjectRestType = 8388608, } export interface ObjectType extends Type { objectFlags: ObjectFlags; @@ -2656,14 +2675,13 @@ declare namespace ts { export interface TemplateLiteralType extends InstantiableType { texts: readonly string[]; types: readonly Type[]; - freshType: TemplateLiteralType; - regularType: TemplateLiteralType; } export interface StringMappingType extends InstantiableType { symbol: Symbol; type: Type; } export interface SubstitutionType extends InstantiableType { + objectFlags: ObjectFlags; baseType: Type; substitute: Type; } @@ -2688,16 +2706,17 @@ declare namespace ts { export enum InferencePriority { NakedTypeVariable = 1, SpeculativeTuple = 2, - HomomorphicMappedType = 4, - PartialHomomorphicMappedType = 8, - MappedTypeConstraint = 16, - ContravariantConditional = 32, - ReturnType = 64, - LiteralKeyof = 128, - NoConstraints = 256, - AlwaysStrict = 512, - MaxValue = 1024, - PriorityImpliesCombination = 208, + SubstituteSource = 4, + HomomorphicMappedType = 8, + PartialHomomorphicMappedType = 16, + MappedTypeConstraint = 32, + ContravariantConditional = 64, + ReturnType = 128, + LiteralKeyof = 256, + NoConstraints = 512, + AlwaysStrict = 1024, + MaxValue = 2048, + PriorityImpliesCombination = 416, Circularity = -1 } /** @deprecated Use FileExtensionInfo instead. */ @@ -2774,18 +2793,21 @@ declare namespace ts { FixedPollingInterval = 0, PriorityPollingInterval = 1, DynamicPriorityPolling = 2, - UseFsEvents = 3, - UseFsEventsOnParentDirectory = 4 + FixedChunkSizePolling = 3, + UseFsEvents = 4, + UseFsEventsOnParentDirectory = 5 } export enum WatchDirectoryKind { UseFsEvents = 0, FixedPollingInterval = 1, - DynamicPriorityPolling = 2 + DynamicPriorityPolling = 2, + FixedChunkSizePolling = 3 } export enum PollingWatchKind { FixedInterval = 0, PriorityInterval = 1, - DynamicPriority = 2 + DynamicPriority = 2, + FixedChunkSize = 3 } export type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; export interface CompilerOptions { @@ -2847,6 +2869,7 @@ declare namespace ts { outFile?: string; paths?: MapLike; preserveConstEnums?: boolean; + noImplicitOverride?: boolean; preserveSymlinks?: boolean; project?: string; reactNamespace?: string; @@ -2957,6 +2980,7 @@ declare namespace ts { ES2018 = 5, ES2019 = 6, ES2020 = 7, + ES2021 = 8, ESNext = 99, JSON = 100, Latest = 99 @@ -3130,17 +3154,21 @@ declare namespace ts { Iterator = 8388608, NoAsciiEscaping = 16777216, } - export interface EmitHelper { + export interface EmitHelperBase { readonly name: string; readonly scoped: boolean; readonly text: string | ((node: EmitHelperUniqueNameCallback) => string); readonly priority?: number; readonly dependencies?: EmitHelper[]; } - export interface UnscopedEmitHelper extends EmitHelper { + export interface ScopedEmitHelper extends EmitHelperBase { + readonly scoped: true; + } + export interface UnscopedEmitHelper extends EmitHelperBase { readonly scoped: false; readonly text: string; } + export type EmitHelper = ScopedEmitHelper | UnscopedEmitHelper; export type EmitHelperUniqueNameCallback = (name: string) => string; export enum EmitHint { SourceFile = 0, @@ -3168,14 +3196,27 @@ declare namespace ts { createStringLiteralFromNode(sourceNode: PropertyNameLiteral, isSingleQuote?: boolean): StringLiteral; createRegularExpressionLiteral(text: string): RegularExpressionLiteral; createIdentifier(text: string): Identifier; - /** Create a unique temporary variable. */ - createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; - /** Create a unique temporary variable for use in a loop. */ - createLoopVariable(): Identifier; + /** + * Create a unique temporary variable. + * @param recordTempVariable An optional callback used to record the temporary variable name. This + * should usually be a reference to `hoistVariableDeclaration` from a `TransformationContext`, but + * can be `undefined` if you plan to record the temporary variable manually. + * @param reservedInNestedScopes When `true`, reserves the temporary variable name in all nested scopes + * during emit so that the variable can be referenced in a nested function body. This is an alternative to + * setting `EmitFlags.ReuseTempVariableScope` on the nested function itself. + */ + createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, reservedInNestedScopes?: boolean): Identifier; + /** + * Create a unique temporary variable for use in a loop. + * @param reservedInNestedScopes When `true`, reserves the temporary variable name in all nested scopes + * during emit so that the variable can be referenced in a nested function body. This is an alternative to + * setting `EmitFlags.ReuseTempVariableScope` on the nested function itself. + */ + createLoopVariable(reservedInNestedScopes?: boolean): Identifier; /** Create a unique name based on the supplied text. */ createUniqueName(text: string, flags?: GeneratedIdentifierFlags): Identifier; /** Create a unique name generated for a node. */ - getGeneratedNameForNode(node: Node | undefined): Identifier; + getGeneratedNameForNode(node: Node | undefined, flags?: GeneratedIdentifierFlags): Identifier; createPrivateIdentifier(text: string): PrivateIdentifier; createToken(token: SyntaxKind.SuperKeyword): SuperExpression; createToken(token: SyntaxKind.ThisKeyword): ThisExpression; @@ -3286,10 +3327,10 @@ declare namespace ts { updateArrayLiteralExpression(node: ArrayLiteralExpression, elements: readonly Expression[]): ArrayLiteralExpression; createObjectLiteralExpression(properties?: readonly ObjectLiteralElementLike[], multiLine?: boolean): ObjectLiteralExpression; updateObjectLiteralExpression(node: ObjectLiteralExpression, properties: readonly ObjectLiteralElementLike[]): ObjectLiteralExpression; - createPropertyAccessExpression(expression: Expression, name: string | Identifier | PrivateIdentifier): PropertyAccessExpression; - updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: Identifier | PrivateIdentifier): PropertyAccessExpression; - createPropertyAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | Identifier | PrivateIdentifier): PropertyAccessChain; - updatePropertyAccessChain(node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: Identifier | PrivateIdentifier): PropertyAccessChain; + createPropertyAccessExpression(expression: Expression, name: string | MemberName): PropertyAccessExpression; + updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: MemberName): PropertyAccessExpression; + createPropertyAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | MemberName): PropertyAccessChain; + updatePropertyAccessChain(node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: MemberName): PropertyAccessChain; createElementAccessExpression(expression: Expression, index: number | Expression): ElementAccessExpression; updateElementAccessExpression(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; createElementAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, index: number | Expression): ElementAccessChain; @@ -3457,52 +3498,58 @@ declare namespace ts { updateJSDocTypeExpression(node: JSDocTypeExpression, type: TypeNode): JSDocTypeExpression; createJSDocNameReference(name: EntityName): JSDocNameReference; updateJSDocNameReference(node: JSDocNameReference, name: EntityName): JSDocNameReference; + createJSDocLink(name: EntityName | undefined, text: string): JSDocLink; + updateJSDocLink(node: JSDocLink, name: EntityName | undefined, text: string): JSDocLink; createJSDocTypeLiteral(jsDocPropertyTags?: readonly JSDocPropertyLikeTag[], isArrayType?: boolean): JSDocTypeLiteral; updateJSDocTypeLiteral(node: JSDocTypeLiteral, jsDocPropertyTags: readonly JSDocPropertyLikeTag[] | undefined, isArrayType: boolean | undefined): JSDocTypeLiteral; createJSDocSignature(typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag): JSDocSignature; updateJSDocSignature(node: JSDocSignature, typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type: JSDocReturnTag | undefined): JSDocSignature; - createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string): JSDocTemplateTag; - updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | undefined): JSDocTemplateTag; - createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string): JSDocTypedefTag; - updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | undefined): JSDocTypedefTag; - createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string): JSDocParameterTag; - updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | undefined): JSDocParameterTag; - createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string): JSDocPropertyTag; - updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | undefined): JSDocPropertyTag; - createJSDocTypeTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string): JSDocTypeTag; - updateJSDocTypeTag(node: JSDocTypeTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | undefined): JSDocTypeTag; - createJSDocSeeTag(tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string): JSDocSeeTag; - updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string): JSDocSeeTag; - createJSDocReturnTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string): JSDocReturnTag; - updateJSDocReturnTag(node: JSDocReturnTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | undefined): JSDocReturnTag; - createJSDocThisTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string): JSDocThisTag; - updateJSDocThisTag(node: JSDocThisTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | undefined): JSDocThisTag; - createJSDocEnumTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string): JSDocEnumTag; - updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | undefined): JSDocEnumTag; - createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string): JSDocCallbackTag; - updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | undefined): JSDocCallbackTag; - createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string): JSDocAugmentsTag; - updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment: string | undefined): JSDocAugmentsTag; - createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string): JSDocImplementsTag; - updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment: string | undefined): JSDocImplementsTag; - createJSDocAuthorTag(tagName: Identifier | undefined, comment?: string): JSDocAuthorTag; - updateJSDocAuthorTag(node: JSDocAuthorTag, tagName: Identifier | undefined, comment: string | undefined): JSDocAuthorTag; - createJSDocClassTag(tagName: Identifier | undefined, comment?: string): JSDocClassTag; - updateJSDocClassTag(node: JSDocClassTag, tagName: Identifier | undefined, comment: string | undefined): JSDocClassTag; - createJSDocPublicTag(tagName: Identifier | undefined, comment?: string): JSDocPublicTag; - updateJSDocPublicTag(node: JSDocPublicTag, tagName: Identifier | undefined, comment: string | undefined): JSDocPublicTag; - createJSDocPrivateTag(tagName: Identifier | undefined, comment?: string): JSDocPrivateTag; - updateJSDocPrivateTag(node: JSDocPrivateTag, tagName: Identifier | undefined, comment: string | undefined): JSDocPrivateTag; - createJSDocProtectedTag(tagName: Identifier | undefined, comment?: string): JSDocProtectedTag; - updateJSDocProtectedTag(node: JSDocProtectedTag, tagName: Identifier | undefined, comment: string | undefined): JSDocProtectedTag; - createJSDocReadonlyTag(tagName: Identifier | undefined, comment?: string): JSDocReadonlyTag; - updateJSDocReadonlyTag(node: JSDocReadonlyTag, tagName: Identifier | undefined, comment: string | undefined): JSDocReadonlyTag; - createJSDocUnknownTag(tagName: Identifier, comment?: string): JSDocUnknownTag; - updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | undefined): JSDocUnknownTag; - createJSDocDeprecatedTag(tagName: Identifier, comment?: string): JSDocDeprecatedTag; - updateJSDocDeprecatedTag(node: JSDocDeprecatedTag, tagName: Identifier, comment?: string): JSDocDeprecatedTag; - createJSDocComment(comment?: string | undefined, tags?: readonly JSDocTag[] | undefined): JSDoc; - updateJSDocComment(node: JSDoc, comment: string | undefined, tags: readonly JSDocTag[] | undefined): JSDoc; + createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray): JSDocTemplateTag; + updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | NodeArray | undefined): JSDocTemplateTag; + createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocTypedefTag; + updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocTypedefTag; + createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocParameterTag; + updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocParameterTag; + createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocPropertyTag; + updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocPropertyTag; + createJSDocTypeTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocTypeTag; + updateJSDocTypeTag(node: JSDocTypeTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined): JSDocTypeTag; + createJSDocSeeTag(tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag; + updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag; + createJSDocReturnTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray): JSDocReturnTag; + updateJSDocReturnTag(node: JSDocReturnTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined): JSDocReturnTag; + createJSDocThisTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocThisTag; + updateJSDocThisTag(node: JSDocThisTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined): JSDocThisTag; + createJSDocEnumTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocEnumTag; + updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined): JSDocEnumTag; + createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocCallbackTag; + updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocCallbackTag; + createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string | NodeArray): JSDocAugmentsTag; + updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment: string | NodeArray | undefined): JSDocAugmentsTag; + createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string | NodeArray): JSDocImplementsTag; + updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment: string | NodeArray | undefined): JSDocImplementsTag; + createJSDocAuthorTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocAuthorTag; + updateJSDocAuthorTag(node: JSDocAuthorTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocAuthorTag; + createJSDocClassTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocClassTag; + updateJSDocClassTag(node: JSDocClassTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocClassTag; + createJSDocPublicTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocPublicTag; + updateJSDocPublicTag(node: JSDocPublicTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocPublicTag; + createJSDocPrivateTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocPrivateTag; + updateJSDocPrivateTag(node: JSDocPrivateTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocPrivateTag; + createJSDocProtectedTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocProtectedTag; + updateJSDocProtectedTag(node: JSDocProtectedTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocProtectedTag; + createJSDocReadonlyTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocReadonlyTag; + updateJSDocReadonlyTag(node: JSDocReadonlyTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocReadonlyTag; + createJSDocUnknownTag(tagName: Identifier, comment?: string | NodeArray): JSDocUnknownTag; + updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | NodeArray | undefined): JSDocUnknownTag; + createJSDocDeprecatedTag(tagName: Identifier, comment?: string | NodeArray): JSDocDeprecatedTag; + updateJSDocDeprecatedTag(node: JSDocDeprecatedTag, tagName: Identifier, comment?: string | NodeArray): JSDocDeprecatedTag; + createJSDocOverrideTag(tagName: Identifier, comment?: string | NodeArray): JSDocOverrideTag; + updateJSDocOverrideTag(node: JSDocOverrideTag, tagName: Identifier, comment?: string | NodeArray): JSDocOverrideTag; + createJSDocText(text: string): JSDocText; + updateJSDocText(node: JSDocText, text: string): JSDocText; + createJSDocComment(comment?: string | NodeArray | undefined, tags?: readonly JSDocTag[] | undefined): JSDoc; + updateJSDocComment(node: JSDoc, comment: string | NodeArray | undefined, tags: readonly JSDocTag[] | undefined): JSDoc; createJsxElement(openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement; updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement; createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxSelfClosingElement; @@ -3750,12 +3797,12 @@ declare namespace ts { * }); * ``` */ - onEmitNode?(hint: EmitHint, node: Node | undefined, emitCallback: (hint: EmitHint, node: Node | undefined) => void): void; + onEmitNode?(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; /** * A hook used to check if an emit notification is required for a node. * @param node The node to emit. */ - isEmitNotificationEnabled?(node: Node | undefined): boolean; + isEmitNotificationEnabled?(node: Node): boolean; /** * A hook used by the Printer to perform just-in-time substitution of a node. This is * primarily used by node transformations that need to substitute one node for another, @@ -3869,6 +3916,8 @@ declare namespace ts { readonly disableSuggestions?: boolean; readonly quotePreference?: "auto" | "double" | "single"; readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsForImportStatements?: boolean; + readonly includeCompletionsWithSnippetText?: boolean; readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; @@ -3967,9 +4016,10 @@ declare namespace ts { scanJsxIdentifier(): SyntaxKind; scanJsxAttributeValue(): SyntaxKind; reScanJsxAttributeValue(): SyntaxKind; - reScanJsxToken(): JsxTokenSyntaxKind; + reScanJsxToken(allowMultilineJsxText?: boolean): JsxTokenSyntaxKind; reScanLessThanToken(): SyntaxKind; reScanQuestionToken(): SyntaxKind; + reScanInvalidIdentifier(): SyntaxKind; scanJsxToken(): JsxTokenSyntaxKind; scanJsDocToken(): JSDocSyntaxKind; scan(): SyntaxKind; @@ -4101,7 +4151,7 @@ declare namespace ts { function idText(identifierOrPrivateName: Identifier | PrivateIdentifier): string; function symbolName(symbol: Symbol): string; function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | PrivateIdentifier | undefined; - function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined; + function getNameOfDeclaration(declaration: Declaration | Expression | undefined): DeclarationName | undefined; /** * Gets the JSDoc parameter tags for the node if present. * @@ -4147,6 +4197,7 @@ declare namespace ts { function getJSDocProtectedTag(node: Node): JSDocProtectedTag | undefined; /** Gets the JSDoc protected tag for the node if present */ function getJSDocReadonlyTag(node: Node): JSDocReadonlyTag | undefined; + function getJSDocOverrideTagNoCache(node: Node): JSDocOverrideTag | undefined; /** Gets the JSDoc deprecated tag for the node if present */ function getJSDocDeprecatedTag(node: Node): JSDocDeprecatedTag | undefined; /** Gets the JSDoc enum tag for the node if present */ @@ -4184,13 +4235,15 @@ declare namespace ts { function getAllJSDocTags(node: Node, predicate: (tag: JSDocTag) => tag is T): readonly T[]; /** Gets all JSDoc tags of a specified kind */ function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): readonly JSDocTag[]; + /** Gets the text of a jsdoc comment, flattening links to their text. */ + function getTextOfJSDocComment(comment?: string | NodeArray): string | undefined; /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. */ function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): readonly TypeParameterDeclaration[]; function getEffectiveConstraintOfTypeParameter(node: TypeParameterDeclaration): TypeNode | undefined; - function isIdentifierOrPrivateIdentifier(node: Node): node is Identifier | PrivateIdentifier; + function isMemberName(node: Node): node is MemberName; function isPropertyAccessChain(node: Node): node is PropertyAccessChain; function isElementAccessChain(node: Node): node is ElementAccessChain; function isCallChain(node: Node): node is CallChain; @@ -4205,6 +4258,12 @@ declare namespace ts { function isUnparsedTextLike(node: Node): node is UnparsedTextLike; function isUnparsedNode(node: Node): node is UnparsedNode; function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag; + /** + * True if kind is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + function isTokenKind(kind: SyntaxKind): boolean; /** * True if node is of some token syntax kind. * For example, this is true for an IfKeyword but not for an IfStatement. @@ -4221,7 +4280,7 @@ declare namespace ts { function isEntityName(node: Node): node is EntityName; function isPropertyName(node: Node): node is PropertyName; function isBindingName(node: Node): node is BindingName; - function isFunctionLike(node: Node): node is SignatureDeclaration; + function isFunctionLike(node: Node | undefined): node is SignatureDeclaration; function isClassElement(node: Node): node is ClassElement; function isClassLike(node: Node): node is ClassLikeDeclaration; function isAccessor(node: Node): node is AccessorDeclaration; @@ -4347,10 +4406,14 @@ declare namespace ts { function isTemplateHead(node: Node): node is TemplateHead; function isTemplateMiddle(node: Node): node is TemplateMiddle; function isTemplateTail(node: Node): node is TemplateTail; + function isDotDotDotToken(node: Node): node is DotDotDotToken; + function isPlusToken(node: Node): node is PlusToken; + function isMinusToken(node: Node): node is MinusToken; + function isAsteriskToken(node: Node): node is AsteriskToken; function isIdentifier(node: Node): node is Identifier; + function isPrivateIdentifier(node: Node): node is PrivateIdentifier; function isQualifiedName(node: Node): node is QualifiedName; function isComputedPropertyName(node: Node): node is ComputedPropertyName; - function isPrivateIdentifier(node: Node): node is PrivateIdentifier; function isTypeParameterDeclaration(node: Node): node is TypeParameterDeclaration; function isParameter(node: Node): node is ParameterDeclaration; function isDecorator(node: Node): node is Decorator; @@ -4493,6 +4556,7 @@ declare namespace ts { function isUnparsedSource(node: Node): node is UnparsedSource; function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression; function isJSDocNameReference(node: Node): node is JSDocNameReference; + function isJSDocLink(node: Node): node is JSDocLink; function isJSDocAllType(node: Node): node is JSDocAllType; function isJSDocUnknownType(node: Node): node is JSDocUnknownType; function isJSDocNullableType(node: Node): node is JSDocNullableType; @@ -4512,6 +4576,7 @@ declare namespace ts { function isJSDocPrivateTag(node: Node): node is JSDocPrivateTag; function isJSDocProtectedTag(node: Node): node is JSDocProtectedTag; function isJSDocReadonlyTag(node: Node): node is JSDocReadonlyTag; + function isJSDocOverrideTag(node: Node): node is JSDocOverrideTag; function isJSDocDeprecatedTag(node: Node): node is JSDocDeprecatedTag; function isJSDocSeeTag(node: Node): node is JSDocSeeTag; function isJSDocEnumTag(node: Node): node is JSDocEnumTag; @@ -4576,7 +4641,7 @@ declare namespace ts { /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ - export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): ParsedCommandLine | undefined; + export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions | undefined, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): ParsedCommandLine | undefined; /** * Read tsconfig.json file * @param fileName The path to the config file @@ -4644,13 +4709,13 @@ declare namespace ts { export {}; } declare namespace ts { - function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; + export function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, cache?: TypeReferenceDirectiveResolutionCache): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -4659,30 +4724,46 @@ declare namespace ts { * More type directives might appear in the program later as a result of loading actual source files; * this list is only the set of defaults that are implicitly included. */ - function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + export function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + export interface TypeReferenceDirectiveResolutionCache extends PerDirectoryResolutionCache, PackageJsonInfoCache { + } /** - * Cached module resolutions per containing directory. + * Cached resolutions per containing directory. * This assumes that any module id will have the same resolution for sibling files located in the same folder. */ - interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { - getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + export interface PerDirectoryResolutionCache { + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + clear(): void; + /** + * Updates with the current compilerOptions the cache will operate with. + * This updates the redirects map as well if needed so module resolutions are cached if they can across the projects + */ + update(options: CompilerOptions): void; + } + export interface ModuleResolutionCache extends PerDirectoryResolutionCache, NonRelativeModuleNameResolutionCache, PackageJsonInfoCache { + getPackageJsonInfoCache(): PackageJsonInfoCache; } /** * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. */ - interface NonRelativeModuleNameResolutionCache { + export interface NonRelativeModuleNameResolutionCache extends PackageJsonInfoCache { getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; } - interface PerModuleNameCache { + export interface PackageJsonInfoCache { + clear(): void; + } + export interface PerModuleNameCache { get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; } - function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions): ModuleResolutionCache; - function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions): ModuleResolutionCache; + export function createTypeReferenceDirectiveResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions, packageJsonInfoCache?: PackageJsonInfoCache): TypeReferenceDirectiveResolutionCache; + export function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; + export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export {}; } declare namespace ts { /** @@ -4749,6 +4830,10 @@ declare namespace ts { * environment and merging hoisted declarations upon completion. */ function visitFunctionBody(node: ConciseBody, visitor: Visitor, context: TransformationContext): ConciseBody; + /** + * Visits an iteration body, adding any block-scoped variables required by the transformation. + */ + function visitIterationBody(body: Statement, visitor: Visitor, context: TransformationContext): Statement; /** * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place. * @@ -5037,6 +5122,8 @@ declare namespace ts { interface WatchCompilerHost extends ProgramHost, WatchHost { /** Instead of using output d.ts file from project reference, use its source file */ useSourceOfProjectReferenceRedirect?(): boolean; + /** If provided, use this method to get parsed command lines for referenced projects */ + getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; } @@ -5132,9 +5219,9 @@ declare namespace ts { interface SolutionBuilderWithWatchHost extends SolutionBuilderHostBase, WatchHost { } interface SolutionBuilder { - build(project?: string, cancellationToken?: CancellationToken): ExitStatus; + build(project?: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; clean(project?: string): ExitStatus; - buildReferences(project: string, cancellationToken?: CancellationToken): ExitStatus; + buildReferences(project: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; cleanReferences(project?: string): ExitStatus; getNextInvalidatedProject(cancellationToken?: CancellationToken): InvalidatedProject | undefined; } @@ -5292,7 +5379,7 @@ declare namespace ts { getName(): string; getDeclarations(): Declaration[] | undefined; getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; - getJsDocTags(): JSDocTagInfo[]; + getJsDocTags(checker?: TypeChecker): JSDocTagInfo[]; } interface Type { getFlags(): TypeFlags; @@ -5423,6 +5510,7 @@ declare namespace ts { isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; writeFile?(fileName: string, content: string): void; + getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; } type WithMetadata = T & { metadata?: unknown; @@ -5512,12 +5600,13 @@ declare namespace ts { * * @param fileName The path to the file * @param position A zero based index of the character where you want the entries - * @param entryName The name from an existing completion which came from `getCompletionsAtPosition` + * @param entryName The `name` from an existing completion which came from `getCompletionsAtPosition` * @param formatOptions How should code samples in the completions be formatted, can be undefined for backwards compatibility - * @param source Source code for the current file, can be undefined for backwards compatibility + * @param source `source` property from the completion entry * @param preferences User settings, can be undefined for backwards compatibility + * @param data `data` property from the completion entry */ - getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; + getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined, data: CompletionEntryData | undefined): CompletionEntryDetails | undefined; getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; /** * Gets semantic information about the identifier at a particular position in a @@ -5556,7 +5645,7 @@ declare namespace ts { getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; - getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion | undefined; + getDocCommentTemplateAtPosition(fileName: string, position: number, options?: DocCommentTemplateOptions): TextInsertion | undefined; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; /** * This will return a defined result if the position is after the `>` of the opening tag, or somewhere in the text, of a JSXElement with no closing tag. @@ -5578,7 +5667,7 @@ declare namespace ts { applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise; getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined, triggerReason?: RefactorTriggerReason, kind?: string): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; - organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; + organizeImports(args: OrganizeImportsArgs, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; getProgram(): Program | undefined; @@ -5595,8 +5684,10 @@ declare namespace ts { type: "file"; fileName: string; } - type OrganizeImportsScope = CombinedCodeFixScope; - type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#"; + interface OrganizeImportsArgs extends CombinedCodeFixScope { + skipDestructiveCodeActions?: boolean; + } + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; interface GetCompletionsAtPositionOptions extends UserPreferences { /** * If the editor is asking for completions because a certain character was typed @@ -5948,6 +6039,7 @@ declare namespace ts { name: string; containerKind: ScriptElementKind; containerName: string; + unverified?: boolean; } interface DefinitionInfoAndBoundSpan { definitions?: readonly DefinitionInfo[]; @@ -5982,15 +6074,21 @@ declare namespace ts { typeParameterName = 18, enumMemberName = 19, functionName = 20, - regularExpressionLiteral = 21 + regularExpressionLiteral = 21, + link = 22, + linkName = 23, + linkText = 24 } interface SymbolDisplayPart { text: string; kind: string; } + interface JSDocLinkDisplayPart extends SymbolDisplayPart { + target: DocumentSpan; + } interface JSDocTagInfo { name: string; - text?: string; + text?: SymbolDisplayPart[]; } interface QuickInfo { kind: ScriptElementKind; @@ -6021,11 +6119,15 @@ declare namespace ts { interface RenameInfoOptions { readonly allowRenameOfImportPath?: boolean; } + interface DocCommentTemplateOptions { + readonly generateReturnInDocTemplate?: boolean; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; displayParts: SymbolDisplayPart[]; isOptional: boolean; + isRest?: boolean; } interface SelectionRange { textSpan: TextSpan; @@ -6071,14 +6173,36 @@ declare namespace ts { * true when the current location also allows for a new identifier */ isNewIdentifierLocation: boolean; + /** + * Indicates to client to continue requesting completions on subsequent keystrokes. + */ + isIncomplete?: true; entries: CompletionEntry[]; } + interface CompletionEntryData { + /** The file name declaring the export's module symbol, if it was an external module */ + fileName?: string; + /** The module name (with quotes stripped) of the export's module symbol, if it was an ambient module */ + ambientModuleName?: string; + /** True if the export was found in the package.json AutoImportProvider */ + isPackageJsonImport?: true; + /** + * The name of the property or export in the module's symbol table. Differs from the completion name + * in the case of InternalSymbolName.ExportEquals and InternalSymbolName.Default. + */ + exportName: string; + /** + * Set for auto imports with eagerly resolved module specifiers. + */ + moduleSpecifier?: string; + } interface CompletionEntry { name: string; kind: ScriptElementKind; kindModifiers?: string; sortText: string; insertText?: string; + isSnippet?: true; /** * An optional span that indicates the text to be replaced by this completion item. * If present, this span should be used instead of the default one. @@ -6087,9 +6211,20 @@ declare namespace ts { replacementSpan?: TextSpan; hasAction?: true; source?: string; + sourceDisplay?: SymbolDisplayPart[]; isRecommended?: true; isFromUncheckedFile?: true; isPackageJsonImport?: true; + isImportStatementCompletion?: true; + /** + * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, + * that allows TS Server to look up the symbol represented by the completion item, disambiguating + * items with the same name. Currently only defined for auto-import completions, but the type is + * `unknown` in the protocol, so it can be changed as needed to support other kinds of completions. + * The presence of this property should generally not be used to assume that this completion entry + * is an auto-import. + */ + data?: CompletionEntryData; } interface CompletionEntryDetails { name: string; @@ -6099,7 +6234,9 @@ declare namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; codeActions?: CodeAction[]; + /** @deprecated Use `sourceDisplay` instead. */ source?: SymbolDisplayPart[]; + sourceDisplay?: SymbolDisplayPart[]; } interface OutliningSpan { /** The span of the document to actually collapse. */ @@ -6253,7 +6390,13 @@ declare namespace ts { */ jsxAttribute = "JSX attribute", /** String literal */ - string = "string" + string = "string", + /** Jsdoc @link: in `{@link C link text}`, the before and after text "{@link " and "}" */ + link = "link", + /** Jsdoc @link: in `{@link C link text}`, the entity name "C" */ + linkName = "link name", + /** Jsdoc @link: in `{@link C link text}`, the link text "link text" */ + linkText = "link text" } enum ScriptElementKindModifier { none = "", @@ -6394,8 +6537,23 @@ declare namespace ts { * @param fileName The name of the file to be released * @param compilationSettings The compilation settings used to acquire the file */ + /**@deprecated pass scriptKind for correctness */ releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + /** + * Informs the DocumentRegistry that a file is not needed any longer. + * + * Note: It is not allowed to call release on a SourceFile that was not acquired from + * this registry originally. + * + * @param fileName The name of the file to be released + * @param compilationSettings The compilation settings used to acquire the file + * @param scriptKind The script kind of the file to be released + */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind: ScriptKind): void; + /** + * @deprecated pass scriptKind for correctness */ releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind: ScriptKind): void; reportStats(): string; } type DocumentRegistryBucketKey = string & { @@ -6466,7 +6624,7 @@ declare namespace ts { /** @deprecated Use `factory.createRegularExpressionLiteral` or the factory supplied by your transformation context instead. */ const createRegularExpressionLiteral: (text: string) => RegularExpressionLiteral; /** @deprecated Use `factory.createLoopVariable` or the factory supplied by your transformation context instead. */ - const createLoopVariable: () => Identifier; + const createLoopVariable: (reservedInNestedScopes?: boolean | undefined) => Identifier; /** @deprecated Use `factory.createUniqueName` or the factory supplied by your transformation context instead. */ const createUniqueName: (text: string, flags?: GeneratedIdentifierFlags | undefined) => Identifier; /** @deprecated Use `factory.createPrivateIdentifier` or the factory supplied by your transformation context instead. */ @@ -6638,13 +6796,13 @@ declare namespace ts { /** @deprecated Use `factory.updateObjectLiteralExpression` or the factory supplied by your transformation context instead. */ const updateObjectLiteral: (node: ObjectLiteralExpression, properties: readonly ObjectLiteralElementLike[]) => ObjectLiteralExpression; /** @deprecated Use `factory.createPropertyAccessExpression` or the factory supplied by your transformation context instead. */ - const createPropertyAccess: (expression: Expression, name: string | Identifier | PrivateIdentifier) => PropertyAccessExpression; + const createPropertyAccess: (expression: Expression, name: string | MemberName) => PropertyAccessExpression; /** @deprecated Use `factory.updatePropertyAccessExpression` or the factory supplied by your transformation context instead. */ - const updatePropertyAccess: (node: PropertyAccessExpression, expression: Expression, name: Identifier | PrivateIdentifier) => PropertyAccessExpression; + const updatePropertyAccess: (node: PropertyAccessExpression, expression: Expression, name: MemberName) => PropertyAccessExpression; /** @deprecated Use `factory.createPropertyAccessChain` or the factory supplied by your transformation context instead. */ - const createPropertyAccessChain: (expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | Identifier | PrivateIdentifier) => PropertyAccessChain; + const createPropertyAccessChain: (expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | MemberName) => PropertyAccessChain; /** @deprecated Use `factory.updatePropertyAccessChain` or the factory supplied by your transformation context instead. */ - const updatePropertyAccessChain: (node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: Identifier | PrivateIdentifier) => PropertyAccessChain; + const updatePropertyAccessChain: (node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: MemberName) => PropertyAccessChain; /** @deprecated Use `factory.createElementAccessExpression` or the factory supplied by your transformation context instead. */ const createElementAccess: (expression: Expression, index: number | Expression) => ElementAccessExpression; /** @deprecated Use `factory.updateElementAccessExpression` or the factory supplied by your transformation context instead. */ @@ -6914,51 +7072,51 @@ declare namespace ts { /** @deprecated Use `factory.createJSDocTypeExpression` or the factory supplied by your transformation context instead. */ const createJSDocTypeExpression: (type: TypeNode) => JSDocTypeExpression; /** @deprecated Use `factory.createJSDocTypeTag` or the factory supplied by your transformation context instead. */ - const createJSDocTypeTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | undefined) => JSDocTypeTag; + const createJSDocTypeTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray | undefined) => JSDocTypeTag; /** @deprecated Use `factory.createJSDocReturnTag` or the factory supplied by your transformation context instead. */ - const createJSDocReturnTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | undefined, comment?: string | undefined) => JSDocReturnTag; + const createJSDocReturnTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | undefined, comment?: string | NodeArray | undefined) => JSDocReturnTag; /** @deprecated Use `factory.createJSDocThisTag` or the factory supplied by your transformation context instead. */ - const createJSDocThisTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | undefined) => JSDocThisTag; + const createJSDocThisTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray | undefined) => JSDocThisTag; /** @deprecated Use `factory.createJSDocComment` or the factory supplied by your transformation context instead. */ - const createJSDocComment: (comment?: string | undefined, tags?: readonly JSDocTag[] | undefined) => JSDoc; + const createJSDocComment: (comment?: string | NodeArray | undefined, tags?: readonly JSDocTag[] | undefined) => JSDoc; /** @deprecated Use `factory.createJSDocParameterTag` or the factory supplied by your transformation context instead. */ - const createJSDocParameterTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | undefined) => JSDocParameterTag; + const createJSDocParameterTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | NodeArray | undefined) => JSDocParameterTag; /** @deprecated Use `factory.createJSDocClassTag` or the factory supplied by your transformation context instead. */ - const createJSDocClassTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocClassTag; + const createJSDocClassTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocClassTag; /** @deprecated Use `factory.createJSDocAugmentsTag` or the factory supplied by your transformation context instead. */ const createJSDocAugmentsTag: (tagName: Identifier | undefined, className: ExpressionWithTypeArguments & { readonly expression: Identifier | PropertyAccessEntityNameExpression; - }, comment?: string | undefined) => JSDocAugmentsTag; + }, comment?: string | NodeArray | undefined) => JSDocAugmentsTag; /** @deprecated Use `factory.createJSDocEnumTag` or the factory supplied by your transformation context instead. */ - const createJSDocEnumTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | undefined) => JSDocEnumTag; + const createJSDocEnumTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray | undefined) => JSDocEnumTag; /** @deprecated Use `factory.createJSDocTemplateTag` or the factory supplied by your transformation context instead. */ - const createJSDocTemplateTag: (tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | undefined) => JSDocTemplateTag; + const createJSDocTemplateTag: (tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray | undefined) => JSDocTemplateTag; /** @deprecated Use `factory.createJSDocTypedefTag` or the factory supplied by your transformation context instead. */ - const createJSDocTypedefTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeLiteral | JSDocTypeExpression | undefined, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | undefined) => JSDocTypedefTag; + const createJSDocTypedefTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeLiteral | JSDocTypeExpression | undefined, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | NodeArray | undefined) => JSDocTypedefTag; /** @deprecated Use `factory.createJSDocCallbackTag` or the factory supplied by your transformation context instead. */ - const createJSDocCallbackTag: (tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | undefined) => JSDocCallbackTag; + const createJSDocCallbackTag: (tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | NodeArray | undefined) => JSDocCallbackTag; /** @deprecated Use `factory.createJSDocSignature` or the factory supplied by your transformation context instead. */ const createJSDocSignature: (typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag | undefined) => JSDocSignature; /** @deprecated Use `factory.createJSDocPropertyTag` or the factory supplied by your transformation context instead. */ - const createJSDocPropertyTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | undefined) => JSDocPropertyTag; + const createJSDocPropertyTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | NodeArray | undefined) => JSDocPropertyTag; /** @deprecated Use `factory.createJSDocTypeLiteral` or the factory supplied by your transformation context instead. */ const createJSDocTypeLiteral: (jsDocPropertyTags?: readonly JSDocPropertyLikeTag[] | undefined, isArrayType?: boolean | undefined) => JSDocTypeLiteral; /** @deprecated Use `factory.createJSDocImplementsTag` or the factory supplied by your transformation context instead. */ const createJSDocImplementsTag: (tagName: Identifier | undefined, className: ExpressionWithTypeArguments & { readonly expression: Identifier | PropertyAccessEntityNameExpression; - }, comment?: string | undefined) => JSDocImplementsTag; + }, comment?: string | NodeArray | undefined) => JSDocImplementsTag; /** @deprecated Use `factory.createJSDocAuthorTag` or the factory supplied by your transformation context instead. */ - const createJSDocAuthorTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocAuthorTag; + const createJSDocAuthorTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocAuthorTag; /** @deprecated Use `factory.createJSDocPublicTag` or the factory supplied by your transformation context instead. */ - const createJSDocPublicTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocPublicTag; + const createJSDocPublicTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocPublicTag; /** @deprecated Use `factory.createJSDocPrivateTag` or the factory supplied by your transformation context instead. */ - const createJSDocPrivateTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocPrivateTag; + const createJSDocPrivateTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocPrivateTag; /** @deprecated Use `factory.createJSDocProtectedTag` or the factory supplied by your transformation context instead. */ - const createJSDocProtectedTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocProtectedTag; + const createJSDocProtectedTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocProtectedTag; /** @deprecated Use `factory.createJSDocReadonlyTag` or the factory supplied by your transformation context instead. */ - const createJSDocReadonlyTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocReadonlyTag; + const createJSDocReadonlyTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocReadonlyTag; /** @deprecated Use `factory.createJSDocUnknownTag` or the factory supplied by your transformation context instead. */ - const createJSDocTag: (tagName: Identifier, comment?: string | undefined) => JSDocUnknownTag; + const createJSDocTag: (tagName: Identifier, comment?: string | NodeArray | undefined) => JSDocUnknownTag; /** @deprecated Use `factory.createJsxElement` or the factory supplied by your transformation context instead. */ const createJsxElement: (openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement) => JsxElement; /** @deprecated Use `factory.updateJsxElement` or the factory supplied by your transformation context instead. */ @@ -7214,6 +7372,10 @@ declare namespace ts { */ interface Map extends ESMap { } + /** + * @deprecated Use `isMemberName` instead. + */ + const isIdentifierOrPrivateIdentifier: (node: Node) => node is MemberName; } export = ts; \ No newline at end of file diff --git a/lib/typescript.js b/lib/typescript.js index 48c2fc2c63cea..615ad27f3f7d9 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -286,11 +286,11 @@ var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "4.2"; + ts.versionMajorMinor = "4.3"; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = ts.versionMajorMinor + ".0-dev"; + ts.version = "4.3.2"; /* @internal */ var Comparison; (function (Comparison) { @@ -2594,6 +2594,8 @@ var ts; } } Debug.assertMissingNode = assertMissingNode; + function type(_value) { } + Debug.type = type; function getFunctionName(func) { if (typeof func !== "function") { return ""; @@ -2855,11 +2857,11 @@ var ts; this.objectFlags & 8 /* Tuple */ ? "TupleType" : this.objectFlags & 16 /* Anonymous */ ? "AnonymousType" : this.objectFlags & 32 /* Mapped */ ? "MappedType" : - this.objectFlags & 2048 /* ReverseMapped */ ? "ReverseMappedType" : + this.objectFlags & 1024 /* ReverseMapped */ ? "ReverseMappedType" : this.objectFlags & 256 /* EvolvingArray */ ? "EvolvingArrayType" : "ObjectType" : "Type"; - var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~2367 /* ObjectTypeKindMask */ : 0; + var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~1343 /* ObjectTypeKindMask */ : 0; return "" + typeHeader + (this.symbol ? " '" + ts.symbolName(this.symbol) + "'" : "") + (remainingObjectFlags ? " (" + formatObjectFlags(remainingObjectFlags) + ")" : ""); } }, @@ -3405,16 +3407,22 @@ var ts; typeof PerformanceObserver === "function" && hasRequiredAPI(performance, PerformanceObserver)) { return { + // For now we always write native performance events when running in the browser. We may + // make this conditional in the future if we find that native web performance hooks + // in the browser also slow down compilation. + shouldWriteNativeEvents: true, performance: performance, PerformanceObserver: PerformanceObserver }; } } function tryGetNodePerformanceHooks() { - if (typeof module === "object" && typeof require === "function") { + if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof module === "object" && typeof require === "function") { try { - var _a = require("perf_hooks"), performance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; - if (hasRequiredAPI(performance_1, PerformanceObserver_1)) { + var performance_1; + var _a = require("perf_hooks"), nodePerformance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; + if (hasRequiredAPI(nodePerformance_1, PerformanceObserver_1)) { + performance_1 = nodePerformance_1; // There is a bug in Node's performance.measure prior to 12.16.3/13.13.0 that does not // match the Web Performance API specification. Node's implementation did not allow // optional `start` and `end` arguments for `performance.measure`. @@ -3422,27 +3430,26 @@ var ts; var version_1 = new ts.Version(process.versions.node); var range = new ts.VersionRange("<12.16.3 || 13 <13.13"); if (range.test(version_1)) { - return { - performance: { - get timeOrigin() { return performance_1.timeOrigin; }, - now: function () { return performance_1.now(); }, - mark: function (name) { return performance_1.mark(name); }, - measure: function (name, start, end) { - if (start === void 0) { start = "nodeStart"; } - if (end === undefined) { - end = "__performance.measure-fix__"; - performance_1.mark(end); - } - performance_1.measure(name, start, end); - if (end === "__performance.measure-fix__") { - performance_1.clearMarks("__performance.measure-fix__"); - } + performance_1 = { + get timeOrigin() { return nodePerformance_1.timeOrigin; }, + now: function () { return nodePerformance_1.now(); }, + mark: function (name) { return nodePerformance_1.mark(name); }, + measure: function (name, start, end) { + if (start === void 0) { start = "nodeStart"; } + if (end === undefined) { + end = "__performance.measure-fix__"; + nodePerformance_1.mark(end); } - }, - PerformanceObserver: PerformanceObserver_1 + nodePerformance_1.measure(name, start, end); + if (end === "__performance.measure-fix__") { + nodePerformance_1.clearMarks("__performance.measure-fix__"); + } + } }; } return { + // By default, only write native events when generating a cpu profile or using the v8 profiler. + shouldWriteNativeEvents: false, performance: performance_1, PerformanceObserver: PerformanceObserver_1 }; @@ -3473,7 +3480,6 @@ var ts; var performance; (function (performance) { var perfHooks; - var perfObserver; // when set, indicates the implementation of `Performance` to use for user timing. // when unset, indicates user timing is unavailable or disabled. var performanceImpl; @@ -3504,6 +3510,9 @@ var ts; } performance.createTimer = createTimer; performance.nullTimer = { enter: ts.noop, exit: ts.noop }; + var enabled = false; + var timeorigin = ts.timestamp(); + var marks = new ts.Map(); var counts = new ts.Map(); var durations = new ts.Map(); /** @@ -3512,7 +3521,13 @@ var ts; * @param markName The name of the mark. */ function mark(markName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + var _a; + if (enabled) { + var count = (_a = counts.get(markName)) !== null && _a !== void 0 ? _a : 0; + counts.set(markName, count + 1); + marks.set(markName, ts.timestamp()); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + } } performance.mark = mark; /** @@ -3525,7 +3540,14 @@ var ts; * used. */ function measure(measureName, startMarkName, endMarkName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + var _a, _b; + if (enabled) { + var end = (_a = (endMarkName !== undefined ? marks.get(endMarkName) : undefined)) !== null && _a !== void 0 ? _a : ts.timestamp(); + var start = (_b = (startMarkName !== undefined ? marks.get(startMarkName) : undefined)) !== null && _b !== void 0 ? _b : timeorigin; + var previousDuration = durations.get(measureName) || 0; + durations.set(measureName, previousDuration + (end - start)); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + } } performance.measure = measure; /** @@ -3559,40 +3581,41 @@ var ts; * Indicates whether the performance API is enabled. */ function isEnabled() { - return !!performanceImpl; + return enabled; } performance.isEnabled = isEnabled; /** Enables (and resets) performance measurements for the compiler. */ - function enable() { - if (!performanceImpl) { + function enable(system) { + var _a; + if (system === void 0) { system = ts.sys; } + if (!enabled) { + enabled = true; perfHooks || (perfHooks = ts.tryGetNativePerformanceHooks()); - if (!perfHooks) - return false; - perfObserver || (perfObserver = new perfHooks.PerformanceObserver(updateStatisticsFromList)); - perfObserver.observe({ entryTypes: ["mark", "measure"] }); - performanceImpl = perfHooks.performance; + if (perfHooks) { + timeorigin = perfHooks.performance.timeOrigin; + // NodeJS's Web Performance API is currently slower than expected, but we'd still like + // to be able to leverage native trace events when node is run with either `--cpu-prof` + // or `--prof`, if we're running with our own `--generateCpuProfile` flag, or when + // running in debug mode (since its possible to generate a cpu profile while debugging). + if (perfHooks.shouldWriteNativeEvents || ((_a = system === null || system === void 0 ? void 0 : system.cpuProfilingEnabled) === null || _a === void 0 ? void 0 : _a.call(system)) || (system === null || system === void 0 ? void 0 : system.debugMode)) { + performanceImpl = perfHooks.performance; + } + } } return true; } performance.enable = enable; /** Disables performance measurements for the compiler. */ function disable() { - perfObserver === null || perfObserver === void 0 ? void 0 : perfObserver.disconnect(); - performanceImpl = undefined; - counts.clear(); - durations.clear(); - } - performance.disable = disable; - function updateStatisticsFromList(list) { - for (var _i = 0, _a = list.getEntriesByType("mark"); _i < _a.length; _i++) { - var mark_1 = _a[_i]; - counts.set(mark_1.name, (counts.get(mark_1.name) || 0) + 1); - } - for (var _b = 0, _c = list.getEntriesByType("measure"); _b < _c.length; _b++) { - var measure_1 = _c[_b]; - durations.set(measure_1.name, (durations.get(measure_1.name) || 0) + measure_1.duration); + if (enabled) { + marks.clear(); + counts.clear(); + durations.clear(); + performanceImpl = undefined; + enabled = false; } } + performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); /* @internal */ @@ -3636,40 +3659,35 @@ var ts; /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; })(ts || (ts = {})); +/* Tracing events for the compiler. */ /*@internal*/ -/** Tracing events for the compiler. */ var ts; (function (ts) { - var tracing; - (function (tracing) { - var Mode; - (function (Mode) { - Mode[Mode["Project"] = 0] = "Project"; - Mode[Mode["Build"] = 1] = "Build"; - Mode[Mode["Server"] = 2] = "Server"; - })(Mode = tracing.Mode || (tracing.Mode = {})); + // enable the above using startTracing() + // `tracingEnabled` should never be used directly, only through the above + var tracingEnabled; + (function (tracingEnabled) { var fs; var traceCount = 0; - var traceFd; + var traceFd = 0; var mode; + var typeCatalog = []; // NB: id is index + 1 var legendPath; var legend = []; ; - /** Starts tracing for the given project (unless the `fs` module is unavailable). */ + /** Starts tracing for the given project. */ function startTracing(tracingMode, traceDir, configFilePath) { - ts.Debug.assert(!traceFd, "Tracing already started"); + ts.Debug.assert(!ts.tracing, "Tracing already started"); if (fs === undefined) { try { fs = require("fs"); } - catch (_a) { - fs = false; + catch (e) { + throw new Error("tracing requires having fs\n(original error: " + (e.message || e) + ")"); } } - if (!fs) { - return; - } mode = tracingMode; + typeCatalog.length = 0; if (legendPath === undefined) { legendPath = ts.combinePaths(traceDir, "legend.json"); } @@ -3677,9 +3695,9 @@ var ts; if (!fs.existsSync(traceDir)) { fs.mkdirSync(traceDir, { recursive: true }); } - var countPart = mode === 1 /* Build */ ? "." + process.pid + "-" + ++traceCount : - mode === 2 /* Server */ ? "." + process.pid : - ""; + var countPart = mode === "build" ? "." + process.pid + "-" + ++traceCount + : mode === "server" ? "." + process.pid + : ""; var tracePath = ts.combinePaths(traceDir, "trace" + countPart + ".json"); var typesPath = ts.combinePaths(traceDir, "types" + countPart + ".json"); legend.push({ @@ -3688,25 +3706,22 @@ var ts; typesPath: typesPath, }); traceFd = fs.openSync(tracePath, "w"); + ts.tracing = tracingEnabled; // only when traceFd is properly set // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import) var meta = { cat: "__metadata", ph: "M", ts: 1000 * ts.timestamp(), pid: 1, tid: 1 }; fs.writeSync(traceFd, "[\n" + [__assign({ name: "process_name", args: { name: "tsc" } }, meta), __assign({ name: "thread_name", args: { name: "Main" } }, meta), __assign(__assign({ name: "TracingStartedInBrowser" }, meta), { cat: "disabled-by-default-devtools.timeline" })] .map(function (v) { return JSON.stringify(v); }).join(",\n")); } - tracing.startTracing = startTracing; - /** Stops tracing for the in-progress project and dumps the type catalog (unless the `fs` module is unavailable). */ - function stopTracing(typeCatalog) { - if (!traceFd) { - ts.Debug.assert(!fs, "Tracing is not in progress"); - return; - } - ts.Debug.assert(fs); - ts.Debug.assert(!!typeCatalog === (mode !== 2 /* Server */)); // Have a type catalog iff not in server mode + tracingEnabled.startTracing = startTracing; + /** Stops tracing for the in-progress project and dumps the type catalog. */ + function stopTracing() { + ts.Debug.assert(ts.tracing, "Tracing is not in progress"); + ts.Debug.assert(!!typeCatalog.length === (mode !== "server")); // Have a type catalog iff not in server mode fs.writeSync(traceFd, "\n]\n"); fs.closeSync(traceFd); - traceFd = undefined; - if (typeCatalog) { + ts.tracing = undefined; + if (typeCatalog.length) { dumpTypes(typeCatalog); } else { @@ -3715,11 +3730,13 @@ var ts; legend[legend.length - 1].typesPath = undefined; } } - tracing.stopTracing = stopTracing; - function isTracing() { - return !!traceFd; + tracingEnabled.stopTracing = stopTracing; + function recordType(type) { + if (mode !== "server") { + typeCatalog.push(type); + } } - tracing.isTracing = isTracing; + tracingEnabled.recordType = recordType; var Phase; (function (Phase) { Phase["Parse"] = "parse"; @@ -3729,13 +3746,11 @@ var ts; Phase["CheckTypes"] = "checkTypes"; Phase["Emit"] = "emit"; Phase["Session"] = "session"; - })(Phase = tracing.Phase || (tracing.Phase = {})); + })(Phase = tracingEnabled.Phase || (tracingEnabled.Phase = {})); function instant(phase, name, args) { - if (!traceFd) - return; writeEvent("I", phase, name, args, "\"s\":\"g\""); } - tracing.instant = instant; + tracingEnabled.instant = instant; var eventStack = []; /** * @param separateBeginAndEnd - used for special cases where we need the trace point even if the event @@ -3745,47 +3760,42 @@ var ts; */ function push(phase, name, args, separateBeginAndEnd) { if (separateBeginAndEnd === void 0) { separateBeginAndEnd = false; } - if (!traceFd) - return; if (separateBeginAndEnd) { writeEvent("B", phase, name, args); } eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } - tracing.push = push; + tracingEnabled.push = push; function pop() { - if (!traceFd) - return; ts.Debug.assert(eventStack.length > 0); writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); eventStack.length--; } - tracing.pop = pop; + tracingEnabled.pop = pop; function popAll() { - if (!traceFd) - return; var endTime = 1000 * ts.timestamp(); for (var i = eventStack.length - 1; i >= 0; i--) { writeStackEvent(i, endTime); } eventStack.length = 0; } - tracing.popAll = popAll; + tracingEnabled.popAll = popAll; + // sample every 10ms + var sampleInterval = 1000 * 10; function writeStackEvent(index, endTime) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); } - else { + // test if [time,endTime) straddles a sampling point + else if (sampleInterval - (time % sampleInterval) <= endTime - time) { writeEvent("X", phase, name, args, "\"dur\":" + (endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { if (time === void 0) { time = 1000 * ts.timestamp(); } - ts.Debug.assert(traceFd); - ts.Debug.assert(fs); // In server mode, there's no easy way to dump type information, so we drop events that would require it. - if (mode === 2 /* Server */ && phase === "checkTypes" /* CheckTypes */) + if (mode === "server" && phase === "checkTypes" /* CheckTypes */) return; ts.performance.mark("beginTracing"); fs.writeSync(traceFd, ",\n{\"pid\":1,\"tid\":1,\"ph\":\"" + eventType + "\",\"cat\":\"" + phase + "\",\"ts\":" + time + ",\"name\":\"" + name + "\""); @@ -3797,15 +3807,24 @@ var ts; ts.performance.mark("endTracing"); ts.performance.measure("Tracing", "beginTracing", "endTracing"); } - function indexFromOne(lc) { - return { - line: lc.line + 1, - character: lc.character + 1, - }; + function getLocation(node) { + var file = ts.getSourceFileOfNode(node); + return !file + ? undefined + : { + path: file.path, + start: indexFromOne(ts.getLineAndCharacterOfPosition(file, node.pos)), + end: indexFromOne(ts.getLineAndCharacterOfPosition(file, node.end)), + }; + function indexFromOne(lc) { + return { + line: lc.line + 1, + character: lc.character + 1, + }; + } } function dumpTypes(types) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; - ts.Debug.assert(fs); + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x; ts.performance.mark("beginDumpTypes"); var typesPath = legend[legend.length - 1].typesPath; var typesFd = fs.openSync(typesPath, "w"); @@ -3817,15 +3836,13 @@ var ts; var type = types[i]; var objectFlags = type.objectFlags; var symbol = (_a = type.aliasSymbol) !== null && _a !== void 0 ? _a : type.symbol; - var firstDeclaration = (_b = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _b === void 0 ? void 0 : _b[0]; - var firstFile = firstDeclaration && ts.getSourceFileOfNode(firstDeclaration); // It's slow to compute the display text, so skip it unless it's really valuable (or cheap) var display = void 0; if ((objectFlags & 16 /* Anonymous */) | (type.flags & 2944 /* Literal */)) { try { - display = (_c = type.checker) === null || _c === void 0 ? void 0 : _c.typeToString(type); + display = (_b = type.checker) === null || _b === void 0 ? void 0 : _b.typeToString(type); } - catch (_s) { + catch (_y) { display = undefined; } } @@ -3833,26 +3850,52 @@ var ts; if (type.flags & 8388608 /* IndexedAccess */) { var indexedAccessType = type; indexedAccessProperties = { - indexedAccessObjectType: (_d = indexedAccessType.objectType) === null || _d === void 0 ? void 0 : _d.id, - indexedAccessIndexType: (_e = indexedAccessType.indexType) === null || _e === void 0 ? void 0 : _e.id, + indexedAccessObjectType: (_c = indexedAccessType.objectType) === null || _c === void 0 ? void 0 : _c.id, + indexedAccessIndexType: (_d = indexedAccessType.indexType) === null || _d === void 0 ? void 0 : _d.id, }; } var referenceProperties = {}; if (objectFlags & 4 /* Reference */) { var referenceType = type; referenceProperties = { - instantiatedType: (_f = referenceType.target) === null || _f === void 0 ? void 0 : _f.id, - typeArguments: (_g = referenceType.resolvedTypeArguments) === null || _g === void 0 ? void 0 : _g.map(function (t) { return t.id; }), + instantiatedType: (_e = referenceType.target) === null || _e === void 0 ? void 0 : _e.id, + typeArguments: (_f = referenceType.resolvedTypeArguments) === null || _f === void 0 ? void 0 : _f.map(function (t) { return t.id; }), + referenceLocation: getLocation(referenceType.node), }; } var conditionalProperties = {}; if (type.flags & 16777216 /* Conditional */) { var conditionalType = type; conditionalProperties = { - conditionalCheckType: (_h = conditionalType.checkType) === null || _h === void 0 ? void 0 : _h.id, - conditionalExtendsType: (_j = conditionalType.extendsType) === null || _j === void 0 ? void 0 : _j.id, - conditionalTrueType: (_l = (_k = conditionalType.resolvedTrueType) === null || _k === void 0 ? void 0 : _k.id) !== null && _l !== void 0 ? _l : -1, - conditionalFalseType: (_o = (_m = conditionalType.resolvedFalseType) === null || _m === void 0 ? void 0 : _m.id) !== null && _o !== void 0 ? _o : -1, + conditionalCheckType: (_g = conditionalType.checkType) === null || _g === void 0 ? void 0 : _g.id, + conditionalExtendsType: (_h = conditionalType.extendsType) === null || _h === void 0 ? void 0 : _h.id, + conditionalTrueType: (_k = (_j = conditionalType.resolvedTrueType) === null || _j === void 0 ? void 0 : _j.id) !== null && _k !== void 0 ? _k : -1, + conditionalFalseType: (_m = (_l = conditionalType.resolvedFalseType) === null || _l === void 0 ? void 0 : _l.id) !== null && _m !== void 0 ? _m : -1, + }; + } + var substitutionProperties = {}; + if (type.flags & 33554432 /* Substitution */) { + var substitutionType = type; + substitutionProperties = { + substitutionBaseType: (_o = substitutionType.baseType) === null || _o === void 0 ? void 0 : _o.id, + substituteType: (_p = substitutionType.substitute) === null || _p === void 0 ? void 0 : _p.id, + }; + } + var reverseMappedProperties = {}; + if (objectFlags & 1024 /* ReverseMapped */) { + var reverseMappedType = type; + reverseMappedProperties = { + reverseMappedSourceType: (_q = reverseMappedType.source) === null || _q === void 0 ? void 0 : _q.id, + reverseMappedMappedType: (_r = reverseMappedType.mappedType) === null || _r === void 0 ? void 0 : _r.id, + reverseMappedConstraintType: (_s = reverseMappedType.constraintType) === null || _s === void 0 ? void 0 : _s.id, + }; + } + var evolvingArrayProperties = {}; + if (objectFlags & 256 /* EvolvingArray */) { + var evolvingArrayType = type; + evolvingArrayProperties = { + evolvingArrayElementType: evolvingArrayType.elementType.id, + evolvingArrayFinalType: (_t = evolvingArrayType.finalArrayType) === null || _t === void 0 ? void 0 : _t.id, }; } // We can't print out an arbitrary object, so just assign each one a unique number. @@ -3866,11 +3909,7 @@ var ts; recursionIdentityMap.set(recursionIdentity, recursionToken); } } - var descriptor = __assign(__assign(__assign(__assign({ id: type.id, intrinsicName: type.intrinsicName, symbolName: (symbol === null || symbol === void 0 ? void 0 : symbol.escapedName) && ts.unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, unionTypes: (type.flags & 1048576 /* Union */) ? (_p = type.types) === null || _p === void 0 ? void 0 : _p.map(function (t) { return t.id; }) : undefined, intersectionTypes: (type.flags & 2097152 /* Intersection */) ? type.types.map(function (t) { return t.id; }) : undefined, aliasTypeArguments: (_q = type.aliasTypeArguments) === null || _q === void 0 ? void 0 : _q.map(function (t) { return t.id; }), keyofType: (type.flags & 4194304 /* Index */) ? (_r = type.type) === null || _r === void 0 ? void 0 : _r.id : undefined }, indexedAccessProperties), referenceProperties), conditionalProperties), { firstDeclaration: firstDeclaration && { - path: firstFile.path, - start: indexFromOne(ts.getLineAndCharacterOfPosition(firstFile, firstDeclaration.pos)), - end: indexFromOne(ts.getLineAndCharacterOfPosition(ts.getSourceFileOfNode(firstDeclaration), firstDeclaration.end)), - }, flags: ts.Debug.formatTypeFlags(type.flags).split("|"), display: display }); + var descriptor = __assign(__assign(__assign(__assign(__assign(__assign(__assign({ id: type.id, intrinsicName: type.intrinsicName, symbolName: (symbol === null || symbol === void 0 ? void 0 : symbol.escapedName) && ts.unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, isTuple: objectFlags & 8 /* Tuple */ ? true : undefined, unionTypes: (type.flags & 1048576 /* Union */) ? (_u = type.types) === null || _u === void 0 ? void 0 : _u.map(function (t) { return t.id; }) : undefined, intersectionTypes: (type.flags & 2097152 /* Intersection */) ? type.types.map(function (t) { return t.id; }) : undefined, aliasTypeArguments: (_v = type.aliasTypeArguments) === null || _v === void 0 ? void 0 : _v.map(function (t) { return t.id; }), keyofType: (type.flags & 4194304 /* Index */) ? (_w = type.type) === null || _w === void 0 ? void 0 : _w.id : undefined }, indexedAccessProperties), referenceProperties), conditionalProperties), substitutionProperties), reverseMappedProperties), evolvingArrayProperties), { destructuringPattern: getLocation(type.pattern), firstDeclaration: getLocation((_x = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _x === void 0 ? void 0 : _x[0]), flags: ts.Debug.formatTypeFlags(type.flags).split("|"), display: display }); fs.writeSync(typesFd, JSON.stringify(descriptor)); if (i < numTypes - 1) { fs.writeSync(typesFd, ",\n"); @@ -3885,11 +3924,13 @@ var ts; if (!legendPath) { return; } - ts.Debug.assert(fs); fs.writeFileSync(legendPath, JSON.stringify(legend)); } - tracing.dumpLegend = dumpLegend; - })(tracing = ts.tracing || (ts.tracing = {})); + tracingEnabled.dumpLegend = dumpLegend; + })(tracingEnabled || (tracingEnabled = {})); + // define after tracingEnabled is initialized + ts.startTracing = tracingEnabled.startTracing; + ts.dumpTracingLegend = tracingEnabled.dumpLegend; })(ts || (ts = {})); var ts; (function (ts) { @@ -4065,215 +4106,216 @@ var ts; SyntaxKind[SyntaxKind["FromKeyword"] = 153] = "FromKeyword"; SyntaxKind[SyntaxKind["GlobalKeyword"] = 154] = "GlobalKeyword"; SyntaxKind[SyntaxKind["BigIntKeyword"] = 155] = "BigIntKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 156] = "OfKeyword"; + SyntaxKind[SyntaxKind["OverrideKeyword"] = 156] = "OverrideKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 157] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 157] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 158] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 158] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 159] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 159] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 160] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 161] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 160] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 161] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 162] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 162] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 163] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 164] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 165] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 166] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 167] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 168] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 169] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 170] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 171] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 163] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 164] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 165] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 166] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 167] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 168] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 169] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 170] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 171] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 172] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 172] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 173] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 174] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 175] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 176] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 177] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 178] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 179] = "TupleType"; - SyntaxKind[SyntaxKind["OptionalType"] = 180] = "OptionalType"; - SyntaxKind[SyntaxKind["RestType"] = 181] = "RestType"; - SyntaxKind[SyntaxKind["UnionType"] = 182] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 183] = "IntersectionType"; - SyntaxKind[SyntaxKind["ConditionalType"] = 184] = "ConditionalType"; - SyntaxKind[SyntaxKind["InferType"] = 185] = "InferType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 186] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 187] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 188] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 189] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 190] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 191] = "LiteralType"; - SyntaxKind[SyntaxKind["NamedTupleMember"] = 192] = "NamedTupleMember"; - SyntaxKind[SyntaxKind["TemplateLiteralType"] = 193] = "TemplateLiteralType"; - SyntaxKind[SyntaxKind["TemplateLiteralTypeSpan"] = 194] = "TemplateLiteralTypeSpan"; - SyntaxKind[SyntaxKind["ImportType"] = 195] = "ImportType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 173] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 174] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 175] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 176] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 177] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 178] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 179] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 180] = "TupleType"; + SyntaxKind[SyntaxKind["OptionalType"] = 181] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 182] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 183] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 184] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 185] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 186] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 187] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 188] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 189] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 190] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 191] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 192] = "LiteralType"; + SyntaxKind[SyntaxKind["NamedTupleMember"] = 193] = "NamedTupleMember"; + SyntaxKind[SyntaxKind["TemplateLiteralType"] = 194] = "TemplateLiteralType"; + SyntaxKind[SyntaxKind["TemplateLiteralTypeSpan"] = 195] = "TemplateLiteralTypeSpan"; + SyntaxKind[SyntaxKind["ImportType"] = 196] = "ImportType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 196] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 197] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 198] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 197] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 198] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 199] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 199] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 200] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 201] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 202] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 203] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 204] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 205] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 206] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 207] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 208] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 209] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 210] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 211] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 212] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 213] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 214] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 215] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 216] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 217] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 218] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 219] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 220] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 221] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 222] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 223] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 224] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 225] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 226] = "MetaProperty"; - SyntaxKind[SyntaxKind["SyntheticExpression"] = 227] = "SyntheticExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 200] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 201] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 202] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 203] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 204] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 205] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 206] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 207] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 208] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 209] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 210] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 211] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 212] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 213] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 214] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 215] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 216] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 217] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 218] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 219] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 220] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 221] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 222] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 223] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 224] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 225] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 226] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 227] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 228] = "SyntheticExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 228] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 229] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 229] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 230] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 230] = "Block"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 231] = "EmptyStatement"; - SyntaxKind[SyntaxKind["VariableStatement"] = 232] = "VariableStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 233] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 234] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 235] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 236] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 237] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 238] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 239] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 240] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 241] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 242] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 243] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 244] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 245] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 246] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 247] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 248] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 249] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 250] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 251] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 252] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 253] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 254] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 255] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 256] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 257] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 258] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 259] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 260] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 261] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 262] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 263] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 264] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 265] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 266] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 267] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 268] = "NamedExports"; - SyntaxKind[SyntaxKind["NamespaceExport"] = 269] = "NamespaceExport"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 270] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 271] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 231] = "Block"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 232] = "EmptyStatement"; + SyntaxKind[SyntaxKind["VariableStatement"] = 233] = "VariableStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 234] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 235] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 236] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 237] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 238] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 239] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 240] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 241] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 242] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 243] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 244] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 245] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 246] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 247] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 248] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 249] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 250] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 251] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 252] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 253] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 254] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 255] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 256] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 257] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 258] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 259] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 260] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 261] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 262] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 263] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 264] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 265] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 266] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 267] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 268] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 269] = "NamedExports"; + SyntaxKind[SyntaxKind["NamespaceExport"] = 270] = "NamespaceExport"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 271] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 272] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 272] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 273] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 273] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 274] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 275] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 276] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxFragment"] = 277] = "JsxFragment"; - SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 278] = "JsxOpeningFragment"; - SyntaxKind[SyntaxKind["JsxClosingFragment"] = 279] = "JsxClosingFragment"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 280] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 281] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 282] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 283] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 274] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 275] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 276] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 277] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 278] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 279] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 280] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 281] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 282] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 283] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 284] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 284] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 285] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 286] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 287] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 285] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 286] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 287] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 288] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 288] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 289] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 290] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 289] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 290] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 291] = "SpreadAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 291] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 292] = "EnumMember"; // Unparsed - SyntaxKind[SyntaxKind["UnparsedPrologue"] = 292] = "UnparsedPrologue"; - SyntaxKind[SyntaxKind["UnparsedPrepend"] = 293] = "UnparsedPrepend"; - SyntaxKind[SyntaxKind["UnparsedText"] = 294] = "UnparsedText"; - SyntaxKind[SyntaxKind["UnparsedInternalText"] = 295] = "UnparsedInternalText"; - SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 296] = "UnparsedSyntheticReference"; + SyntaxKind[SyntaxKind["UnparsedPrologue"] = 293] = "UnparsedPrologue"; + SyntaxKind[SyntaxKind["UnparsedPrepend"] = 294] = "UnparsedPrepend"; + SyntaxKind[SyntaxKind["UnparsedText"] = 295] = "UnparsedText"; + SyntaxKind[SyntaxKind["UnparsedInternalText"] = 296] = "UnparsedInternalText"; + SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 297] = "UnparsedSyntheticReference"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 297] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 298] = "Bundle"; - SyntaxKind[SyntaxKind["UnparsedSource"] = 299] = "UnparsedSource"; - SyntaxKind[SyntaxKind["InputFiles"] = 300] = "InputFiles"; + SyntaxKind[SyntaxKind["SourceFile"] = 298] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 299] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 300] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 301] = "InputFiles"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 301] = "JSDocTypeExpression"; - SyntaxKind[SyntaxKind["JSDocNameReference"] = 302] = "JSDocNameReference"; - // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 303] = "JSDocAllType"; - // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 304] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 305] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 306] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 307] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 308] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 309] = "JSDocVariadicType"; - // https://jsdoc.app/about-namepaths.html - SyntaxKind[SyntaxKind["JSDocNamepathType"] = 310] = "JSDocNamepathType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 311] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 312] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocSignature"] = 313] = "JSDocSignature"; - SyntaxKind[SyntaxKind["JSDocTag"] = 314] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 315] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 316] = "JSDocImplementsTag"; - SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 317] = "JSDocAuthorTag"; - SyntaxKind[SyntaxKind["JSDocDeprecatedTag"] = 318] = "JSDocDeprecatedTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 319] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocPublicTag"] = 320] = "JSDocPublicTag"; - SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 321] = "JSDocPrivateTag"; - SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 322] = "JSDocProtectedTag"; - SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 323] = "JSDocReadonlyTag"; - SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 324] = "JSDocCallbackTag"; - SyntaxKind[SyntaxKind["JSDocEnumTag"] = 325] = "JSDocEnumTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 326] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 327] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocThisTag"] = 328] = "JSDocThisTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 329] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 330] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 331] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocSeeTag"] = 332] = "JSDocSeeTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 333] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 302] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocNameReference"] = 303] = "JSDocNameReference"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 304] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 305] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 306] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 307] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 308] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 309] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 310] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocNamepathType"] = 311] = "JSDocNamepathType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 312] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocText"] = 313] = "JSDocText"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 314] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 315] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocLink"] = 316] = "JSDocLink"; + SyntaxKind[SyntaxKind["JSDocTag"] = 317] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 318] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 319] = "JSDocImplementsTag"; + SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 320] = "JSDocAuthorTag"; + SyntaxKind[SyntaxKind["JSDocDeprecatedTag"] = 321] = "JSDocDeprecatedTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 322] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocPublicTag"] = 323] = "JSDocPublicTag"; + SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 324] = "JSDocPrivateTag"; + SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 325] = "JSDocProtectedTag"; + SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 326] = "JSDocReadonlyTag"; + SyntaxKind[SyntaxKind["JSDocOverrideTag"] = 327] = "JSDocOverrideTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 328] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 329] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 330] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 331] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 332] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 333] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 334] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 335] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocSeeTag"] = 336] = "JSDocSeeTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 337] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 334] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 338] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 335] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 336] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 337] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 338] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 339] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 340] = "SyntheticReferenceExpression"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 339] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 340] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 341] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 342] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 343] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 344] = "SyntheticReferenceExpression"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 341] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 345] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 62] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 77] = "LastAssignment"; @@ -4282,15 +4324,15 @@ var ts; SyntaxKind[SyntaxKind["FirstReservedWord"] = 80] = "FirstReservedWord"; SyntaxKind[SyntaxKind["LastReservedWord"] = 115] = "LastReservedWord"; SyntaxKind[SyntaxKind["FirstKeyword"] = 80] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 156] = "LastKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 157] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 116] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 124] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 172] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 195] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 173] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 196] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 77] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 156] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 157] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; @@ -4299,15 +4341,15 @@ var ts; SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken"; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 29] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 77] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstStatement"] = 232] = "FirstStatement"; - SyntaxKind[SyntaxKind["LastStatement"] = 248] = "LastStatement"; - SyntaxKind[SyntaxKind["FirstNode"] = 157] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 301] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 333] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 314] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 333] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstStatement"] = 233] = "FirstStatement"; + SyntaxKind[SyntaxKind["LastStatement"] = 249] = "LastStatement"; + SyntaxKind[SyntaxKind["FirstNode"] = 158] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 302] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 337] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 317] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 337] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 125] = "FirstContextualKeyword"; - /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 156] = "LastContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 157] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -4377,14 +4419,15 @@ var ts; ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; ModifierFlags[ModifierFlags["HasComputedJSDocModifiers"] = 4096] = "HasComputedJSDocModifiers"; ModifierFlags[ModifierFlags["Deprecated"] = 8192] = "Deprecated"; + ModifierFlags[ModifierFlags["Override"] = 16384] = "Override"; ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. - ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 16476] = "ParameterPropertyModifier"; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; - ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; + ModifierFlags[ModifierFlags["TypeScriptModifier"] = 18654] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; - ModifierFlags[ModifierFlags["All"] = 11263] = "All"; + ModifierFlags[ModifierFlags["All"] = 27647] = "All"; })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); var JsxFlags; (function (JsxFlags) { @@ -4565,6 +4608,8 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["NoUndefinedOptionalParameterType"] = 1073741824] = "NoUndefinedOptionalParameterType"; // Error handling NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifiedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifiedNameInPlaceOfIdentifier"; + /** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */ NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier"; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection"; @@ -4579,7 +4624,6 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; - NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -4884,10 +4928,6 @@ var ts; TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["StringLikeLiteral"] = 134217856] = "StringLikeLiteral"; - /* @internal */ - TypeFlags[TypeFlags["FreshableLiteral"] = 134220672] = "FreshableLiteral"; - /* @internal */ TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; /* @internal */ TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; @@ -4936,6 +4976,9 @@ var ts; /* @internal */ TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags + // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check + // for a certain TypeFlags value to determine their meaning. var ObjectFlags; (function (ObjectFlags) { ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; @@ -4948,50 +4991,59 @@ var ts; ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; - ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; - ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; - ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; - ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; - ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; - ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral"; - ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 1024] = "ReverseMapped"; + ObjectFlags[ObjectFlags["JsxAttributes"] = 2048] = "JsxAttributes"; + ObjectFlags[ObjectFlags["MarkerType"] = 4096] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 8192] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 16384] = "FreshLiteral"; + ObjectFlags[ObjectFlags["ArrayLiteral"] = 32768] = "ArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion"; + ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType"; + ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral"; + ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 262144] = "ContainsObjectOrArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType"; + ObjectFlags[ObjectFlags["NonInferrableType"] = 524288] = "NonInferrableType"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; + ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 1048576] = "CouldContainTypeVariablesComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; + ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 2097152] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; + ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags"; + // Object flags that uniquely identify the kind of ObjectType /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed"; + ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 1343] = "ObjectTypeKindMask"; + // Flags that require TypeFlags.Object + ObjectFlags[ObjectFlags["ContainsSpread"] = 4194304] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ObjectRestType"] = 8388608] = "ObjectRestType"; /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 16777216] = "IsClassInstanceClone"; + // Flags that require TypeFlags.Object and ObjectFlags.Reference /* @internal */ - ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeCalculated"] = 33554432] = "IdenticalBaseTypeCalculated"; /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeExists"] = 67108864] = "IdenticalBaseTypeExists"; + // Flags that require TypeFlags.UnionOrIntersection or TypeFlags.Substitution /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection"; + ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 1073741824] = "IsClassInstanceClone"; - ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; /* @internal */ - ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; + ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags"; - // Object flags that uniquely identify the kind of ObjectType + ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + // Flags that require TypeFlags.Union + /* @internal */ + ObjectFlags[ObjectFlags["ContainsIntersections"] = 67108864] = "ContainsIntersections"; + // Flags that require TypeFlags.Intersection /* @internal */ - ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 2367] = "ObjectTypeKindMask"; + ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 67108864] = "IsNeverIntersectionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersection"] = 134217728] = "IsNeverIntersection"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ var VarianceFlags; @@ -5065,16 +5117,17 @@ var ts; (function (InferencePriority) { InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; InferencePriority[InferencePriority["SpeculativeTuple"] = 2] = "SpeculativeTuple"; - InferencePriority[InferencePriority["HomomorphicMappedType"] = 4] = "HomomorphicMappedType"; - InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 8] = "PartialHomomorphicMappedType"; - InferencePriority[InferencePriority["MappedTypeConstraint"] = 16] = "MappedTypeConstraint"; - InferencePriority[InferencePriority["ContravariantConditional"] = 32] = "ContravariantConditional"; - InferencePriority[InferencePriority["ReturnType"] = 64] = "ReturnType"; - InferencePriority[InferencePriority["LiteralKeyof"] = 128] = "LiteralKeyof"; - InferencePriority[InferencePriority["NoConstraints"] = 256] = "NoConstraints"; - InferencePriority[InferencePriority["AlwaysStrict"] = 512] = "AlwaysStrict"; - InferencePriority[InferencePriority["MaxValue"] = 1024] = "MaxValue"; - InferencePriority[InferencePriority["PriorityImpliesCombination"] = 208] = "PriorityImpliesCombination"; + InferencePriority[InferencePriority["SubstituteSource"] = 4] = "SubstituteSource"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 8] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 16] = "PartialHomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 32] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ContravariantConditional"] = 64] = "ContravariantConditional"; + InferencePriority[InferencePriority["ReturnType"] = 128] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 256] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 512] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 1024] = "AlwaysStrict"; + InferencePriority[InferencePriority["MaxValue"] = 2048] = "MaxValue"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 416] = "PriorityImpliesCombination"; InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); /* @internal */ @@ -5152,20 +5205,23 @@ var ts; WatchFileKind[WatchFileKind["FixedPollingInterval"] = 0] = "FixedPollingInterval"; WatchFileKind[WatchFileKind["PriorityPollingInterval"] = 1] = "PriorityPollingInterval"; WatchFileKind[WatchFileKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; - WatchFileKind[WatchFileKind["UseFsEvents"] = 3] = "UseFsEvents"; - WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 4] = "UseFsEventsOnParentDirectory"; + WatchFileKind[WatchFileKind["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; + WatchFileKind[WatchFileKind["UseFsEvents"] = 4] = "UseFsEvents"; + WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 5] = "UseFsEventsOnParentDirectory"; })(WatchFileKind = ts.WatchFileKind || (ts.WatchFileKind = {})); var WatchDirectoryKind; (function (WatchDirectoryKind) { WatchDirectoryKind[WatchDirectoryKind["UseFsEvents"] = 0] = "UseFsEvents"; WatchDirectoryKind[WatchDirectoryKind["FixedPollingInterval"] = 1] = "FixedPollingInterval"; WatchDirectoryKind[WatchDirectoryKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; + WatchDirectoryKind[WatchDirectoryKind["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; })(WatchDirectoryKind = ts.WatchDirectoryKind || (ts.WatchDirectoryKind = {})); var PollingWatchKind; (function (PollingWatchKind) { PollingWatchKind[PollingWatchKind["FixedInterval"] = 0] = "FixedInterval"; PollingWatchKind[PollingWatchKind["PriorityInterval"] = 1] = "PriorityInterval"; PollingWatchKind[PollingWatchKind["DynamicPriority"] = 2] = "DynamicPriority"; + PollingWatchKind[PollingWatchKind["FixedChunkSize"] = 3] = "FixedChunkSize"; })(PollingWatchKind = ts.PollingWatchKind || (ts.PollingWatchKind = {})); var ModuleKind; (function (ModuleKind) { @@ -5226,6 +5282,7 @@ var ts; ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019"; ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020"; + ScriptTarget[ScriptTarget["ES2021"] = 8] = "ES2021"; ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext"; ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest"; @@ -5388,29 +5445,30 @@ var ts; TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript"; TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx"; TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext"; - TransformFlags[TransformFlags["ContainsES2020"] = 8] = "ContainsES2020"; - TransformFlags[TransformFlags["ContainsES2019"] = 16] = "ContainsES2019"; - TransformFlags[TransformFlags["ContainsES2018"] = 32] = "ContainsES2018"; - TransformFlags[TransformFlags["ContainsES2017"] = 64] = "ContainsES2017"; - TransformFlags[TransformFlags["ContainsES2016"] = 128] = "ContainsES2016"; - TransformFlags[TransformFlags["ContainsES2015"] = 256] = "ContainsES2015"; - TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; - TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 1024] = "ContainsDestructuringAssignment"; + TransformFlags[TransformFlags["ContainsES2021"] = 8] = "ContainsES2021"; + TransformFlags[TransformFlags["ContainsES2020"] = 16] = "ContainsES2020"; + TransformFlags[TransformFlags["ContainsES2019"] = 32] = "ContainsES2019"; + TransformFlags[TransformFlags["ContainsES2018"] = 64] = "ContainsES2018"; + TransformFlags[TransformFlags["ContainsES2017"] = 128] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 256] = "ContainsES2016"; + TransformFlags[TransformFlags["ContainsES2015"] = 512] = "ContainsES2015"; + TransformFlags[TransformFlags["ContainsGenerator"] = 1024] = "ContainsGenerator"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 2048] = "ContainsTypeScriptClassSyntax"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 4096] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsRestOrSpread"] = 8192] = "ContainsRestOrSpread"; - TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 16384] = "ContainsObjectRestOrSpread"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 32768] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 65536] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 131072] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 262144] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsAwait"] = 524288] = "ContainsAwait"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 1048576] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 2097152] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["ContainsClassFields"] = 4194304] = "ContainsClassFields"; - TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 8388608] = "ContainsPossibleTopLevelAwait"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 16384] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 32768] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 65536] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 131072] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 262144] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 524288] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsAwait"] = 1048576] = "ContainsAwait"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 2097152] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 4194304] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["ContainsClassFields"] = 8388608] = "ContainsClassFields"; + TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 16777216] = "ContainsPossibleTopLevelAwait"; // 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 @@ -5420,37 +5478,38 @@ var ts; TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript"; TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx"; TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext"; - TransformFlags[TransformFlags["AssertES2020"] = 8] = "AssertES2020"; - TransformFlags[TransformFlags["AssertES2019"] = 16] = "AssertES2019"; - TransformFlags[TransformFlags["AssertES2018"] = 32] = "AssertES2018"; - TransformFlags[TransformFlags["AssertES2017"] = 64] = "AssertES2017"; - TransformFlags[TransformFlags["AssertES2016"] = 128] = "AssertES2016"; - TransformFlags[TransformFlags["AssertES2015"] = 256] = "AssertES2015"; - TransformFlags[TransformFlags["AssertGenerator"] = 512] = "AssertGenerator"; - TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 1024] = "AssertDestructuringAssignment"; + TransformFlags[TransformFlags["AssertES2021"] = 8] = "AssertES2021"; + TransformFlags[TransformFlags["AssertES2020"] = 16] = "AssertES2020"; + TransformFlags[TransformFlags["AssertES2019"] = 32] = "AssertES2019"; + TransformFlags[TransformFlags["AssertES2018"] = 64] = "AssertES2018"; + TransformFlags[TransformFlags["AssertES2017"] = 128] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 256] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 512] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 1024] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 2048] = "AssertDestructuringAssignment"; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes"; TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes"; TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 547309568] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 547313664] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 547311616] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 538923008] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["PropertyExcludes"] = 536875008] = "PropertyExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 536905728] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 546379776] = "ModuleExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 557748224] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 557756416] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 557752320] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 540975104] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["PropertyExcludes"] = 536879104] = "PropertyExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 536940544] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 555888640] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536922112] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536879104] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537018368] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536973312] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536887296] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537165824] = "VariableDeclarationListExcludes"; TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 536887296] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 536879104] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 536903680] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 536887296] = "BindingPatternExcludes"; // Propagating flags // - Bitmasks for flags that should propagate from a child - TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 4096] = "PropertyNamePropagatingFlags"; + TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 8192] = "PropertyNamePropagatingFlags"; // Masks // - Additional bitmasks })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); @@ -6318,7 +6377,7 @@ var ts; * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. * Comparison is case-sensitive between the canonical paths. * - * @deprecated Use `containsPath` if possible. + * Use `containsPath` if file names are not already reduced and absolute. */ function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { var canonicalFileName = getCanonicalFileName(fileName); @@ -6438,6 +6497,11 @@ var ts; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time + /* @internal */ + function getModifiedTime(host, fileName) { + return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; + } + ts.getModifiedTime = getModifiedTime; function createPollingIntervalBasedLevels(levels) { var _a; return _a = {}, @@ -6494,6 +6558,51 @@ var ts; } } ts.setCustomPollingValues = setCustomPollingValues; + function pollWatchedFileQueue(host, queue, pollIndex, chunkSize, callbackOnWatchFileStat) { + var definedValueCopyToIndex = pollIndex; + // Max visit would be all elements of the queue + for (var canVisit = queue.length; chunkSize && canVisit; nextPollIndex(), canVisit--) { + var watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + // Only files polled count towards chunkSize + chunkSize--; + var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(host, watchedFile.fileName)); + if (watchedFile.isClosed) { + // Closed watcher as part of callback + queue[pollIndex] = undefined; + continue; + } + callbackOnWatchFileStat === null || callbackOnWatchFileStat === void 0 ? void 0 : callbackOnWatchFileStat(watchedFile, pollIndex, fileChanged); + // Defragment the queue while we are at it + if (queue[pollIndex]) { + // Copy this file to the non hole location + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + // Return next poll index + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + // There are holes from definedValueCopyToIndex to end of queue, change queue size + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } /* @internal */ function createDynamicPriorityPollingWatchFile(host) { var watchedFiles = []; @@ -6507,7 +6616,7 @@ var ts; fileName: fileName, callback: callback, unchangedPolls: 0, - mtime: getModifiedTime(fileName) + mtime: getModifiedTime(host, fileName) }; watchedFiles.push(file); addToPollingIntervalQueue(file, defaultPollingInterval); @@ -6550,25 +6659,9 @@ var ts; } } function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { - // Max visit would be all elements of the queue - var needsVisit = queue.length; - var definedValueCopyToIndex = pollIndex; - for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { - var watchedFile = queue[pollIndex]; - if (!watchedFile) { - continue; - } - else if (watchedFile.isClosed) { - queue[pollIndex] = undefined; - continue; - } - polled++; - var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); - if (watchedFile.isClosed) { - // Closed watcher as part of callback - queue[pollIndex] = undefined; - } - else if (fileChanged) { + return pollWatchedFileQueue(host, queue, pollIndex, chunkSize, onWatchFileStat); + function onWatchFileStat(watchedFile, pollIndex, fileChanged) { + if (fileChanged) { watchedFile.unchangedPolls = 0; // Changed files go to changedFilesInLastPoll queue if (queue !== changedFilesInLastPoll) { @@ -6590,27 +6683,6 @@ var ts; queue[pollIndex] = undefined; addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); } - if (queue[pollIndex]) { - // Copy this file to the non hole location - if (definedValueCopyToIndex < pollIndex) { - queue[definedValueCopyToIndex] = watchedFile; - queue[pollIndex] = undefined; - } - definedValueCopyToIndex++; - } - } - // Return next poll index - return pollIndex; - function nextPollIndex() { - pollIndex++; - if (pollIndex === queue.length) { - if (definedValueCopyToIndex < pollIndex) { - // There are holes from nextDefinedValueIndex to end of queue, change queue size - queue.length = definedValueCopyToIndex; - } - pollIndex = 0; - definedValueCopyToIndex = 0; - } } } function pollingIntervalQueue(pollingInterval) { @@ -6639,9 +6711,6 @@ var ts; function scheduleNextPoll(pollingInterval) { pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); } - function getModifiedTime(fileName) { - return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; - } } ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) { @@ -6692,6 +6761,37 @@ var ts; return watcher; } } + function createFixedChunkSizePollingWatchFile(host) { + var watchedFiles = []; + var pollIndex = 0; + var pollScheduled; + return watchFile; + function watchFile(fileName, callback) { + var file = { + fileName: fileName, + callback: callback, + mtime: getModifiedTime(host, fileName) + }; + watchedFiles.push(file); + scheduleNextPoll(); + return { + close: function () { + file.isClosed = true; + ts.unorderedRemoveItem(watchedFiles, file); + } + }; + } + function pollQueue() { + pollScheduled = undefined; + pollIndex = pollWatchedFileQueue(host, watchedFiles, pollIndex, pollingChunkSize[PollingInterval.Low]); + scheduleNextPoll(); + } + function scheduleNextPoll() { + if (!watchedFiles.length || pollScheduled) + return; + pollScheduled = host.setTimeout(pollQueue, PollingInterval.High); + } + } /* @internal */ function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) { var cache = new ts.Map(); @@ -7014,8 +7114,9 @@ var ts; } /*@internal*/ function createSystemWatchFunctions(_a) { - var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory; + var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind; var dynamicPollingWatchFile; + var fixedChunkSizePollingWatchFile; var nonPollingWatchFile; var hostRecursiveDirectoryWatcher; return { @@ -7032,6 +7133,8 @@ var ts; return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined); case ts.WatchFileKind.DynamicPriorityPolling: return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined); + case ts.WatchFileKind.FixedChunkSizePolling: + return ensureFixedChunkSizePollingWatchFile()(fileName, callback, /* pollingInterval */ undefined, /*options*/ undefined); case ts.WatchFileKind.UseFsEvents: return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options)); @@ -7045,8 +7148,10 @@ var ts; } } function ensureDynamicPollingWatchFile() { - return dynamicPollingWatchFile || - (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })); + return dynamicPollingWatchFile || (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })); + } + function ensureFixedChunkSizePollingWatchFile() { + return fixedChunkSizePollingWatchFile || (fixedChunkSizePollingWatchFile = createFixedChunkSizePollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })); } function updateOptionsForWatchFile(options, useNonPollingWatchers) { if (options && options.watchFile !== undefined) @@ -7072,7 +7177,7 @@ var ts; // Use notifications from FS to watch with falling back to fs.watchFile generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) : // Default to do not use fixed polling interval - { watchFile: ts.WatchFileKind.FixedPollingInterval }; + { watchFile: (defaultWatchFileKind === null || defaultWatchFileKind === void 0 ? void 0 : defaultWatchFileKind()) || ts.WatchFileKind.FixedPollingInterval }; } } function generateWatchFileOptions(watchFile, fallbackPolling, options) { @@ -7113,6 +7218,10 @@ var ts; case ts.WatchDirectoryKind.DynamicPriorityPolling: return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, /*options*/ undefined); + case ts.WatchDirectoryKind.FixedChunkSizePolling: + return ensureFixedChunkSizePollingWatchFile()(directoryName, function () { return callback(directoryName); }, + /* pollingInterval */ undefined, + /*options*/ undefined); case ts.WatchDirectoryKind.UseFsEvents: return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), recursive, PollingInterval.Medium, ts.getFallbackOptions(watchDirectoryOptions)); default: @@ -7191,13 +7300,13 @@ var ts; } var activeSession; var profilePath = "./profile.cpuprofile"; - var realpathSync = (_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync; var Buffer = require("buffer").Buffer; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + var realpathSync = useCaseSensitiveFileNames ? ((_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync) : _fs.realpathSync; var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); var getCurrentDirectory = ts.memoize(function () { return process.cwd(); }); var _c = createSystemWatchFunctions({ @@ -7218,6 +7327,7 @@ var ts; tscWatchFile: process.env.TSC_WATCHFILE, useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER, tscWatchDirectory: process.env.TSC_WATCHDIRECTORY, + defaultWatchFileKind: function () { var _a, _b; return (_b = (_a = sys).defaultWatchFileKind) === null || _b === void 0 ? void 0 : _b.call(_a); }, }), watchFile = _c.watchFile, watchDirectory = _c.watchDirectory; var nodeSystem = { args: process.argv.slice(2), @@ -7286,6 +7396,7 @@ var ts; }, enableCPUProfiler: enableCPUProfiler, disableCPUProfiler: disableCPUProfiler, + cpuProfilingEnabled: function () { return !!activeSession || ts.contains(process.execArgv, "--cpu-prof") || ts.contains(process.execArgv, "--prof"); }, realpath: realpath, debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -7535,7 +7646,7 @@ var ts; return event === "rename" && (!relativeName || relativeName === lastDirectoryPart || - relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) && + (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && !fileSystemEntryExists(fileOrDirectory, entryKind) ? invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : callback(event, relativeName); @@ -7845,7 +7956,7 @@ var ts; Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1103, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103", "'for await' loops are only allowed within async functions and at the top levels of modules."), A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), @@ -7894,7 +8005,7 @@ var ts; A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), - A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_1166", "A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type."), A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), @@ -7954,7 +8065,7 @@ var ts; A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), - An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231", "An export assignment must be at the top level of a file or module declaration."), An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), @@ -7980,6 +8091,7 @@ var ts; A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1258, ts.DiagnosticCategory.Error, "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258", "A default export must be at the top level of a file or module declaration."), Module_0_can_only_be_default_imported_using_the_1_flag: diag(1259, ts.DiagnosticCategory.Error, "Module_0_can_only_be_default_imported_using_the_1_flag_1259", "Module '{0}' can only be default-imported using the '{1}' flag"), Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), @@ -8066,7 +8178,7 @@ var ts; Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), Provides_a_root_package_name_when_using_outFile_with_declarations: diag(1390, ts.DiagnosticCategory.Message, "Provides_a_root_package_name_when_using_outFile_with_declarations_1390", "Provides a root package name when using outFile with declarations."), - The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The `bundledPackageName` option must be provided when using outFile and node module resolution with declaration emit."), + The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The 'bundledPackageName' option must be provided when using outFile and node module resolution with declaration emit."), An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), @@ -8106,6 +8218,9 @@ var ts; File_is_output_of_project_reference_source_0: diag(1428, ts.DiagnosticCategory.Message, "File_is_output_of_project_reference_source_0_1428", "File is output of project reference source '{0}'"), File_redirects_to_file_0: diag(1429, ts.DiagnosticCategory.Message, "File_redirects_to_file_0_1429", "File redirects to file '{0}'"), The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), + for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), + Decorators_may_not_be_applied_to_this_parameters: diag(1433, ts.DiagnosticCategory.Error, "Decorators_may_not_be_applied_to_this_parameters_1433", "Decorators may not be applied to 'this' parameters."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -8173,7 +8288,7 @@ var ts; The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), - The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_in_expression_must_not_be_a_primitive: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_not_be_a_primitive_2361", "The right-hand side of an 'in' expression must not be a primitive."), The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), @@ -8191,8 +8306,7 @@ var ts; A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers."), Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), - Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."), - get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."), + The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type: diag(2380, ts.DiagnosticCategory.Error, "The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type_2380", "The return type of a 'get' accessor must be assignable to its 'set' accessor type"), A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."), Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."), Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), @@ -8255,7 +8369,7 @@ var ts; Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), - Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_cl_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'. This is an instance of class '{2}'."), The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), @@ -8355,14 +8469,13 @@ var ts; The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the `lib` compiler option to '{2}' or later."), + Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{2}' or later."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), - Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), - Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), + A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter: diag(2556, ts.DiagnosticCategory.Error, "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556", "A spread argument must either have a tuple type or be passed to a rest parameter."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), @@ -8385,17 +8498,17 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to '{1}' or later."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{1}' or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later."), Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."), Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add `node` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add `jquery` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add 'jquery' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), @@ -8428,6 +8541,12 @@ var ts; Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target: diag(2625, ts.DiagnosticCategory.Error, "Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target_2625", "Variadic element at position {0} in source does not match element at position {1} in target."), Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target: diag(2626, ts.DiagnosticCategory.Error, "Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target_2626", "Type at position {0} in source is not compatible with type at position {1} in target."), Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target: diag(2627, ts.DiagnosticCategory.Error, "Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target_2627", "Type at positions {0} through {1} in source is not compatible with type at position {2} in target."), + Cannot_assign_to_0_because_it_is_an_enum: diag(2628, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_an_enum_2628", "Cannot assign to '{0}' because it is an enum."), + Cannot_assign_to_0_because_it_is_a_class: diag(2629, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_class_2629", "Cannot assign to '{0}' because it is a class."), + Cannot_assign_to_0_because_it_is_a_function: diag(2630, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_function_2630", "Cannot assign to '{0}' because it is a function."), + Cannot_assign_to_0_because_it_is_a_namespace: diag(2631, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_namespace_2631", "Cannot assign to '{0}' because it is a namespace."), + Cannot_assign_to_0_because_it_is_an_import: diag(2632, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_an_import_2632", "Cannot assign to '{0}' because it is an import."), + JSX_property_access_expressions_cannot_include_JSX_namespace_names: diag(2633, ts.DiagnosticCategory.Error, "JSX_property_access_expressions_cannot_include_JSX_namespace_names_2633", "JSX property access expressions cannot include JSX namespace names"), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -8474,7 +8593,7 @@ var ts; Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), @@ -8482,14 +8601,14 @@ var ts; _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a 'delete' operator must be a property reference."), The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a 'delete' operator cannot be a read-only property."), - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), - A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), - A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), @@ -8551,7 +8670,7 @@ var ts; The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."), Overload_0_of_1_2_gave_the_following_error: diag(2772, ts.DiagnosticCategory.Error, "Overload_0_of_1_2_gave_the_following_error_2772", "Overload {0} of {1}, '{2}', gave the following error."), Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"), - This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it__2774", "This condition will always return true since the function is always defined. Did you mean to call it instead?"), + This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774", "This condition will always return true since this function is always defined. Did you mean to call it instead?"), Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation: diag(2775, ts.DiagnosticCategory.Error, "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775", "Assertions require every name in the call target to be declared with an explicit type annotation."), Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name: diag(2776, ts.DiagnosticCategory.Error, "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776", "Assertions require the call target to be an identifier or qualified name."), The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access: diag(2777, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777", "The operand of an increment or decrement operator may not be an optional property access."), @@ -8575,6 +8694,21 @@ var ts; The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types: diag(2795, ts.DiagnosticCategory.Error, "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795", "The 'intrinsic' keyword can only be used to declare compiler provided intrinsic types."), It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked: diag(2796, ts.DiagnosticCategory.Error, "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796", "It is likely that you are missing a comma to separate these two template expressions. They form a tagged template expression which cannot be invoked."), A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract: diag(2797, ts.DiagnosticCategory.Error, "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797", "A mixin class that extends from a type variable containing an abstract construct signature must also be declared 'abstract'."), + The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), + Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), + Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), + This_condition_will_always_return_true_since_this_0_is_always_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_is_always_defined_2801", "This condition will always return true since this '{0}' is always defined."), + Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher: diag(2802, ts.DiagnosticCategory.Error, "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802", "Type '{0}' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher."), + Cannot_assign_to_private_method_0_Private_methods_are_not_writable: diag(2803, ts.DiagnosticCategory.Error, "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803", "Cannot assign to private method '{0}'. Private methods are not writable."), + Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name: diag(2804, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804", "Duplicate identifier '{0}'. Static and instance elements cannot share the same private name."), + Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag: diag(2805, ts.DiagnosticCategory.Error, "Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_no_2805", "Static fields with private names can't have initializers when the '--useDefineForClassFields' flag is not specified with a '--target' of 'esnext'. Consider adding the '--useDefineForClassFields' flag."), + Private_accessor_was_defined_without_a_getter: diag(2806, ts.DiagnosticCategory.Error, "Private_accessor_was_defined_without_a_getter_2806", "Private accessor was defined without a getter."), + This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0: diag(2807, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807", "This syntax requires an imported helper named '{1}' with {2} parameters, which is not compatible with the one in '{0}'. Consider upgrading your version of '{0}'."), + A_get_accessor_must_be_at_least_as_accessible_as_the_setter: diag(2808, ts.DiagnosticCategory.Error, "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808", "A get accessor must be at least as accessible as the setter"), + Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses: diag(2809, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809", "Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses."), + Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false: diag(2810, ts.DiagnosticCategory.Error, "Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnex_2810", "Property '{0}' may not be used in a static property's initializer in the same class when 'target' is 'esnext' and 'useDefineForClassFields' is 'false'."), + Initializer_for_property_0: diag(2811, ts.DiagnosticCategory.Error, "Initializer_for_property_0_2811", "Initializer for property '{0}'"), + Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom: diag(2812, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812", "Property '{0}' does not exist on type '{1}'. Try changing the 'lib' compiler option to include 'dom'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -8647,6 +8781,7 @@ var ts; Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2: diag(4084, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084", "Exported type alias '{0}' has or is using private name '{1}' from module {2}."), Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), @@ -8668,6 +8803,11 @@ var ts; Type_arguments_for_0_circularly_reference_themselves: diag(4109, ts.DiagnosticCategory.Error, "Type_arguments_for_0_circularly_reference_themselves_4109", "Type arguments for '{0}' circularly reference themselves."), Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."), Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0: diag(4111, ts.DiagnosticCategory.Error, "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111", "Property '{0}' comes from an index signature, so it must be accessed with ['{0}']."), + This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class: diag(4112, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112", "This member cannot have an 'override' modifier because its containing class '{0}' does not extend another class."), + This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0: diag(4113, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113", "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'."), + This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0: diag(4114, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114", "This member must have an 'override' modifier because it overrides a member in the base class '{0}'."), + This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115", "This parameter property must have an 'override' modifier because it overrides a member in base class '{0}'."), + This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0: diag(4116, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116", "This member must have an 'override' modifier because it overrides an abstract method that is declared in the base class '{0}'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -8702,7 +8842,7 @@ var ts; Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), - Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option `--tsBuildInfoFile` is specified."), + Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option '--tsBuildInfoFile' is specified."), _0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2: diag(5075, ts.DiagnosticCategory.Error, "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075", "'{0}' is assignable to the constraint of type '{1}', but '{1}' could be instantiated with a different subtype of constraint '{2}'."), _0_and_1_operations_cannot_be_mixed_without_parentheses: diag(5076, ts.DiagnosticCategory.Error, "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076", "'{0}' and '{1}' operations cannot be mixed without parentheses."), Unknown_build_option_0_Did_you_mean_1: diag(5077, ts.DiagnosticCategory.Error, "Unknown_build_option_0_Did_you_mean_1_5077", "Unknown build option '{0}'. Did you mean '{1}'?"), @@ -8715,10 +8855,14 @@ var ts; Tuple_members_must_all_have_names_or_all_not_have_names: diag(5084, ts.DiagnosticCategory.Error, "Tuple_members_must_all_have_names_or_all_not_have_names_5084", "Tuple members must all have names or all not have names."), A_tuple_member_cannot_be_both_optional_and_rest: diag(5085, ts.DiagnosticCategory.Error, "A_tuple_member_cannot_be_both_optional_and_rest_5085", "A tuple member cannot be both optional and rest."), A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type: diag(5086, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086", "A labeled tuple element is declared as optional with a question mark after the name and before the colon, rather than after the type."), - A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a `...` before the name, rather than before the type."), + A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a '...' before the name, rather than before the type."), The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), + Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."), + The_root_value_of_a_0_file_must_be_an_object: diag(5092, ts.DiagnosticCategory.Error, "The_root_value_of_a_0_file_must_be_an_object_5092", "The root value of a '{0}' file must be an object."), + Compiler_option_0_may_only_be_used_with_build: diag(5093, ts.DiagnosticCategory.Error, "Compiler_option_0_may_only_be_used_with_build_5093", "Compiler option '--{0}' may only be used with '--build'."), + Compiler_option_0_may_not_be_used_with_build: diag(5094, ts.DiagnosticCategory.Error, "Compiler_option_0_may_not_be_used_with_build_5094", "Compiler option '--{0}' may not be used with '--build'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -8734,7 +8878,7 @@ var ts; Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), @@ -8929,9 +9073,9 @@ var ts; Emit_class_fields_with_Define_instead_of_Set: diag(6222, ts.DiagnosticCategory.Message, "Emit_class_fields_with_Define_instead_of_Set_6222", "Emit class fields with Define instead of Set."), Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."), Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."), - Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."), - Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling'."), - Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority'."), + Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."), + Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling'."), + Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority_FixedChunkSize: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority', 'FixedChunkSize'."), Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively: diag(6228, ts.DiagnosticCategory.Message, "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6228", "Synchronously call callbacks and update the state of directory watchers on platforms that don't support recursive watching natively."), Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3: diag(6229, ts.DiagnosticCategory.Error, "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229", "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'."), Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."), @@ -8942,7 +9086,11 @@ var ts; Disable_loading_referenced_projects: diag(6235, ts.DiagnosticCategory.Message, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."), Arguments_for_the_rest_parameter_0_were_not_provided: diag(6236, ts.DiagnosticCategory.Error, "Arguments_for_the_rest_parameter_0_were_not_provided_6236", "Arguments for the rest parameter '{0}' were not provided."), Generates_an_event_trace_and_a_list_of_types: diag(6237, ts.DiagnosticCategory.Message, "Generates_an_event_trace_and_a_list_of_types_6237", "Generates an event trace and a list of types."), - Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the `jsx` and `jsxs` factory functions from. eg, react"), + Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the 'jsx' and 'jsxs' factory functions from. eg, react"), + File_0_exists_according_to_earlier_cached_lookups: diag(6239, ts.DiagnosticCategory.Message, "File_0_exists_according_to_earlier_cached_lookups_6239", "File '{0}' exists according to earlier cached lookups."), + File_0_does_not_exist_according_to_earlier_cached_lookups: diag(6240, ts.DiagnosticCategory.Message, "File_0_does_not_exist_according_to_earlier_cached_lookups_6240", "File '{0}' does not exist according to earlier cached lookups."), + Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1: diag(6241, ts.DiagnosticCategory.Message, "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241", "Resolution for type reference directive '{0}' was found in cache from location '{1}'."), + Resolving_type_reference_directive_0_containing_file_1: diag(6242, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_6242", "======== Resolving type reference directive '{0}', containing file '{1}'. ========"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -8987,16 +9135,19 @@ var ts; Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382", "Skipping build of project '{0}' because its dependency '{1}' was not built"), Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383", "Project '{0}' can't be built because its dependency '{1}' was not built"), Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, ts.DiagnosticCategory.Message, "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384", "Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it."), - _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), + The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + Project_0_is_being_forcibly_rebuilt: diag(6388, ts.DiagnosticCategory.Message, "Project_0_is_being_forcibly_rebuilt_6388", "Project '{0}' is being forcibly rebuilt"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option: diag(6504, ts.DiagnosticCategory.Error, "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504", "File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?"), Print_names_of_files_and_the_reason_they_are_part_of_the_compilation: diag(6505, ts.DiagnosticCategory.Message, "Print_names_of_files_and_the_reason_they_are_part_of_the_compilation_6505", "Print names of files and the reason they are part of the compilation."), - Require_undeclared_properties_from_index_signatures_to_use_element_accesses: diag(6803, ts.DiagnosticCategory.Error, "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803", "Require undeclared properties from index signatures to use element accesses."), Include_undefined_in_index_signature_results: diag(6800, ts.DiagnosticCategory.Message, "Include_undefined_in_index_signature_results_6800", "Include 'undefined' in index signature results"), + Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier: diag(6801, ts.DiagnosticCategory.Message, "Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier_6801", "Ensure overriding members in derived classes are marked with an 'override' modifier."), + Require_undeclared_properties_from_index_signatures_to_use_element_accesses: diag(6802, ts.DiagnosticCategory.Message, "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6802", "Require undeclared properties from index signatures to use element accesses."), 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."), @@ -9029,7 +9180,7 @@ var ts; Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), - If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'"), The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), @@ -9069,7 +9220,7 @@ var ts; JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), - Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one '@augments' or '@extends' tag."), Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), @@ -9314,6 +9465,10 @@ var ts; Add_all_missing_function_declarations: diag(95157, ts.DiagnosticCategory.Message, "Add_all_missing_function_declarations_95157", "Add all missing function declarations"), Method_not_implemented: diag(95158, ts.DiagnosticCategory.Message, "Method_not_implemented_95158", "Method not implemented."), Function_not_implemented: diag(95159, ts.DiagnosticCategory.Message, "Function_not_implemented_95159", "Function not implemented."), + Add_override_modifier: diag(95160, ts.DiagnosticCategory.Message, "Add_override_modifier_95160", "Add 'override' modifier"), + Remove_override_modifier: diag(95161, ts.DiagnosticCategory.Message, "Remove_override_modifier_95161", "Remove 'override' modifier"), + Add_all_missing_override_modifiers: diag(95162, ts.DiagnosticCategory.Message, "Add_all_missing_override_modifiers_95162", "Add all missing 'override' modifiers"), + Remove_all_unnecessary_override_modifiers: diag(95163, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_override_modifiers_95163", "Remove all unnecessary 'override' modifiers"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -9328,8 +9483,6 @@ var ts; The_shadowing_declaration_of_0_is_defined_here: diag(18017, ts.DiagnosticCategory.Error, "The_shadowing_declaration_of_0_is_defined_here_18017", "The shadowing declaration of '{0}' is defined here"), The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here: diag(18018, ts.DiagnosticCategory.Error, "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018", "The declaration of '{0}' that you probably intended to use is defined here"), _0_modifier_cannot_be_used_with_a_private_identifier: diag(18019, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_private_identifier_18019", "'{0}' modifier cannot be used with a private identifier."), - A_method_cannot_be_named_with_a_private_identifier: diag(18022, ts.DiagnosticCategory.Error, "A_method_cannot_be_named_with_a_private_identifier_18022", "A method cannot be named with a private identifier."), - An_accessor_cannot_be_named_with_a_private_identifier: diag(18023, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_named_with_a_private_identifier_18023", "An accessor cannot be named with a private identifier."), An_enum_member_cannot_be_named_with_a_private_identifier: diag(18024, ts.DiagnosticCategory.Error, "An_enum_member_cannot_be_named_with_a_private_identifier_18024", "An enum member cannot be named with a private identifier."), can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), Compiler_reserves_name_0_when_emitting_private_identifier_downlevel: diag(18027, ts.DiagnosticCategory.Error, "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027", "Compiler reserves name '{0}' when emitting private identifier downlevel."), @@ -9341,6 +9494,7 @@ var ts; Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead: diag(18033, ts.DiagnosticCategory.Error, "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033", "Only numeric enums can have computed members, but this expression has type '{0}'. If you do not need exhaustiveness checks, consider using an object literal instead."), Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compiler_option_is_specified_e_g_Fragment: diag(18034, ts.DiagnosticCategory.Message, "Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compi_18034", "Specify the JSX fragment factory function to use when targeting 'react' JSX emit with 'jsxFactory' compiler option is specified, e.g. 'Fragment'."), Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(18035, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name_18035", "Invalid value for 'jsxFragmentFactory'. '{0}' is not a valid identifier or qualified-name."), + Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator: diag(18036, ts.DiagnosticCategory.Error, "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036", "Class decorators can't be used with static private identifier. Consider removing the experimental decorator."), }; })(ts || (ts = {})); var ts; @@ -9408,6 +9562,7 @@ var ts; _a.private = 120 /* PrivateKeyword */, _a.protected = 121 /* ProtectedKeyword */, _a.public = 122 /* PublicKeyword */, + _a.override = 156 /* OverrideKeyword */, _a.readonly = 142 /* ReadonlyKeyword */, _a.require = 143 /* RequireKeyword */, _a.global = 154 /* GlobalKeyword */, @@ -9434,7 +9589,7 @@ var ts; _a.yield = 124 /* YieldKeyword */, _a.async = 129 /* AsyncKeyword */, _a.await = 130 /* AwaitKeyword */, - _a.of = 156 /* OfKeyword */, + _a.of = 157 /* OfKeyword */, _a); var textToKeyword = new ts.Map(ts.getEntries(textToKeywordObj)); var textToToken = new ts.Map(ts.getEntries(__assign(__assign({}, textToKeywordObj), { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 29 /* LessThanToken */, ">": 31 /* GreaterThanToken */, "<=": 32 /* LessThanEqualsToken */, ">=": 33 /* GreaterThanEqualsToken */, "==": 34 /* EqualsEqualsToken */, "!=": 35 /* ExclamationEqualsToken */, "===": 36 /* EqualsEqualsEqualsToken */, "!==": 37 /* ExclamationEqualsEqualsToken */, "=>": 38 /* EqualsGreaterThanToken */, "+": 39 /* PlusToken */, "-": 40 /* MinusToken */, "**": 42 /* AsteriskAsteriskToken */, "*": 41 /* AsteriskToken */, "/": 43 /* SlashToken */, "%": 44 /* PercentToken */, "++": 45 /* PlusPlusToken */, "--": 46 /* MinusMinusToken */, "<<": 47 /* LessThanLessThanToken */, ">": 48 /* GreaterThanGreaterThanToken */, ">>>": 49 /* GreaterThanGreaterThanGreaterThanToken */, "&": 50 /* AmpersandToken */, "|": 51 /* BarToken */, "^": 52 /* CaretToken */, "!": 53 /* ExclamationToken */, "~": 54 /* TildeToken */, "&&": 55 /* AmpersandAmpersandToken */, "||": 56 /* BarBarToken */, "?": 57 /* QuestionToken */, "??": 60 /* QuestionQuestionToken */, "?.": 28 /* QuestionDotToken */, ":": 58 /* ColonToken */, "=": 62 /* EqualsToken */, "+=": 63 /* PlusEqualsToken */, "-=": 64 /* MinusEqualsToken */, "*=": 65 /* AsteriskEqualsToken */, "**=": 66 /* AsteriskAsteriskEqualsToken */, "/=": 67 /* SlashEqualsToken */, "%=": 68 /* PercentEqualsToken */, "<<=": 69 /* LessThanLessThanEqualsToken */, ">>=": 70 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 72 /* AmpersandEqualsToken */, "|=": 73 /* BarEqualsToken */, "^=": 77 /* CaretEqualsToken */, "||=": 74 /* BarBarEqualsToken */, "&&=": 75 /* AmpersandAmpersandEqualsToken */, "??=": 76 /* QuestionQuestionEqualsToken */, "@": 59 /* AtToken */, "`": 61 /* BacktickToken */ }))); @@ -9750,11 +9905,11 @@ var ts; } ts.couldStartTrivia = couldStartTrivia; /* @internal */ - function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { - if (stopAtComments === void 0) { stopAtComments = false; } + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments, inJSDoc) { if (ts.positionIsSynthesized(pos)) { return pos; } + var canConsumeStar = false; // Keep in sync with couldStartTrivia while (true) { var ch = text.charCodeAt(pos); @@ -9769,6 +9924,7 @@ var ts; if (stopAfterLineBreak) { return pos; } + canConsumeStar = !!inJSDoc; continue; case 9 /* tab */: case 11 /* verticalTab */: @@ -9788,6 +9944,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { @@ -9799,6 +9956,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } break; @@ -9808,12 +9966,21 @@ var ts; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos); + canConsumeStar = false; continue; } break; case 35 /* hash */: if (pos === 0 && isShebangTrivia(text, pos)) { pos = scanShebangTrivia(text, pos); + canConsumeStar = false; + continue; + } + break; + case 42 /* asterisk */: + if (canConsumeStar) { + pos++; + canConsumeStar = false; continue; } break; @@ -10118,6 +10285,7 @@ var ts; reScanJsxToken: reScanJsxToken, reScanLessThanToken: reScanLessThanToken, reScanQuestionToken: reScanQuestionToken, + reScanInvalidIdentifier: reScanInvalidIdentifier, scanJsxToken: scanJsxToken, scanJsDocToken: scanJsDocToken, scan: scan, @@ -11120,15 +11288,9 @@ var ts; } return token = 79 /* PrivateIdentifier */; default: - if (isIdentifierStart(ch, languageVersion)) { - pos += charSize(ch); - while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) - pos += charSize(ch); - tokenValue = text.substring(tokenPos, pos); - if (ch === 92 /* backslash */) { - tokenValue += scanIdentifierParts(); - } - return token = getIdentifierToken(); + var identifierKind = scanIdentifier(ch, languageVersion); + if (identifierKind) { + return token = identifierKind; } else if (isWhiteSpaceSingleLine(ch)) { pos += charSize(ch); @@ -11145,6 +11307,31 @@ var ts; } } } + function reScanInvalidIdentifier() { + ts.Debug.assert(token === 0 /* Unknown */, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'."); + pos = tokenPos = startPos; + tokenFlags = 0; + var ch = codePointAt(text, pos); + var identifierKind = scanIdentifier(ch, 99 /* ESNext */); + if (identifierKind) { + return token = identifierKind; + } + pos += charSize(ch); + return token; // Still `SyntaKind.Unknown` + } + function scanIdentifier(startCharacter, languageVersion) { + var ch = startCharacter; + if (isIdentifierStart(ch, languageVersion)) { + pos += charSize(ch); + while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) + pos += charSize(ch); + tokenValue = text.substring(tokenPos, pos); + if (ch === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return getIdentifierToken(); + } + } function reScanGreaterToken() { if (token === 31 /* GreaterThanToken */) { if (text.charCodeAt(pos) === 62 /* greaterThan */) { @@ -11257,9 +11444,10 @@ var ts; pos = tokenPos; return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true); } - function reScanJsxToken() { + function reScanJsxToken(allowMultilineJsxText) { + if (allowMultilineJsxText === void 0) { allowMultilineJsxText = true; } pos = tokenPos = startPos; - return token = scanJsxToken(); + return token = scanJsxToken(allowMultilineJsxText); } function reScanLessThanToken() { if (token === 47 /* LessThanLessThanToken */) { @@ -11273,7 +11461,8 @@ var ts; pos = tokenPos + 1; return token = 57 /* QuestionToken */; } - function scanJsxToken() { + function scanJsxToken(allowMultilineJsxText) { + if (allowMultilineJsxText === void 0) { allowMultilineJsxText = true; } startPos = tokenPos = pos; if (pos >= end) { return token = 1 /* EndOfFileToken */; @@ -11293,15 +11482,9 @@ var ts; } // First non-whitespace character on this line. var firstNonWhitespace = 0; - var lastNonWhitespace = -1; // These initial values are special because the first line is: // firstNonWhitespace = 0 to indicate that we want leading whitespace, while (pos < end) { - // We want to keep track of the last non-whitespace (but including - // newlines character for hitting the end of the JSX Text region) - if (!isWhiteSpaceSingleLine(char)) { - lastNonWhitespace = pos; - } char = text.charCodeAt(pos); if (char === 123 /* openBrace */) { break; @@ -11319,8 +11502,6 @@ var ts; if (char === 125 /* closeBrace */) { error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1); } - if (lastNonWhitespace > 0) - lastNonWhitespace++; // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces. // i.e (- : whitespace) //
---- @@ -11330,13 +11511,17 @@ var ts; if (isLineBreak(char) && firstNonWhitespace === 0) { firstNonWhitespace = -1; } + else if (!allowMultilineJsxText && isLineBreak(char) && firstNonWhitespace > 0) { + // Stop JsxText on each line during formatting. This allows the formatter to + // indent each line correctly. + break; + } else if (!isWhiteSpaceLike(char)) { firstNonWhitespace = pos; } pos++; } - var endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace; - tokenValue = text.substring(startPos, endPosition); + tokenValue = text.substring(startPos, pos); return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */; } // Scans a JSX identifier; these differ from normal identifiers in that @@ -11359,6 +11544,7 @@ var ts; tokenValue += ":"; pos++; namespaceSeparator = true; + token = 78 /* Identifier */; // swap from keyword kind to identifier kind continue; } var oldPos = pos; @@ -11615,6 +11801,8 @@ var ts; switch (options.target) { case 99 /* ESNext */: return "lib.esnext.full.d.ts"; + case 8 /* ES2021 */: + return "lib.es2021.full.d.ts"; case 7 /* ES2020 */: return "lib.es2020.full.d.ts"; case 6 /* ES2019 */: @@ -11833,9 +12021,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 159 /* TypeParameter */) { + if (d && d.kind === 160 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (isFunctionLike(current) || isClassLike(current) || current.kind === 253 /* InterfaceDeclaration */) { + if (isFunctionLike(current) || isClassLike(current) || current.kind === 254 /* InterfaceDeclaration */) { return current; } } @@ -11843,7 +12031,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node, parent) { - return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 166 /* Constructor */; + return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) && parent.kind === 167 /* Constructor */; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -11873,14 +12061,14 @@ var ts; node = walkUpBindingElementsAndPatterns(node); } var flags = getFlags(node); - if (node.kind === 249 /* VariableDeclaration */) { + if (node.kind === 250 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 250 /* VariableDeclarationList */) { + if (node && node.kind === 251 /* VariableDeclarationList */) { flags |= getFlags(node); node = node.parent; } - if (node && node.kind === 232 /* VariableStatement */) { + if (node && node.kind === 233 /* VariableStatement */) { flags |= getFlags(node); } return flags; @@ -11898,19 +12086,22 @@ var ts; // nodes like variable declarations and binding elements can returned a view of their flags // that includes the modifiers from their container. i.e. flags like export/declare aren't // stored on the variable declaration directly, but on the containing variable statement - // (if it has one). Similarly, flags for let/const are store on the variable declaration + // (if it has one). Similarly, flags for let/const are stored on the variable declaration // list. By calling this function, all those flags are combined so that the client can treat // the node as if it actually had those flags. function getCombinedNodeFlags(node) { return getCombinedFlags(node, function (n) { return n.flags; }); } ts.getCombinedNodeFlags = getCombinedNodeFlags; + /* @internal */ + ts.supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; /** * Checks to see if the locale is in the appropriate format, * and if it is, attempts to set the appropriate language. */ function validateLocaleAndSetLanguage(locale, sys, errors) { - var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + var lowerCaseLocale = locale.toLowerCase(); + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale); if (!matchResult) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); @@ -11921,7 +12112,7 @@ var ts; var territory = matchResult[3]; // First try the entire locale, then fall back to just language if that's all we have. // Either ways do not fail, and fallback to the English diagnostic strings. - if (!trySetLanguageAndTerritory(language, territory, errors)) { + if (ts.contains(ts.supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) { trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); } // Set the UI locale for string collation @@ -12028,7 +12219,7 @@ var ts; } ts.idText = idText; function symbolName(symbol) { - if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) { + if (symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) { return idText(symbol.valueDeclaration.name); } return unescapeLeadingUnderscores(symbol.escapedName); @@ -12050,30 +12241,30 @@ var ts; } // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } break; - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: var expr = hostNode.expression; - if (expr.kind === 216 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) { + if (expr.kind === 217 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) { expr = expr.left; } switch (expr.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return expr.name; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; } } break; - case 207 /* ParenthesizedExpression */: { + case 208 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } - case 245 /* LabeledStatement */: { + case 246 /* LabeledStatement */: { if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } @@ -12110,16 +12301,16 @@ var ts; switch (declaration.kind) { case 78 /* Identifier */: return declaration; - case 333 /* JSDocPropertyTag */: - case 326 /* JSDocParameterTag */: { + case 337 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: { var name = declaration.name; - if (name.kind === 157 /* QualifiedName */) { + if (name.kind === 158 /* QualifiedName */) { return name.right; } break; } - case 203 /* CallExpression */: - case 216 /* BinaryExpression */: { + case 204 /* CallExpression */: + case 217 /* BinaryExpression */: { var expr_1 = declaration; switch (ts.getAssignmentDeclarationKind(expr_1)) { case 1 /* ExportsProperty */: @@ -12135,15 +12326,15 @@ var ts; return undefined; } } - case 331 /* JSDocTypedefTag */: + case 335 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); - case 325 /* JSDocEnumTag */: + case 329 /* JSDocEnumTag */: return nameForNamelessJSDocTypedef(declaration); - case 266 /* ExportAssignment */: { + case 267 /* ExportAssignment */: { var expression = declaration.expression; return ts.isIdentifier(expression) ? expression : undefined; } - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: var expr = declaration; if (ts.isBindableStaticElementAccessExpression(expr)) { return expr.argumentExpression; @@ -12156,7 +12347,7 @@ var ts; if (declaration === undefined) return undefined; return getNonAssignedNameOfDeclaration(declaration) || - (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + (ts.isFunctionExpression(declaration) || ts.isArrowFunction(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); } ts.getNameOfDeclaration = getNameOfDeclaration; /*@internal*/ @@ -12309,6 +12500,10 @@ var ts; return getFirstJSDocTag(node, ts.isJSDocReadonlyTag, /*noCache*/ true); } ts.getJSDocReadonlyTagNoCache = getJSDocReadonlyTagNoCache; + function getJSDocOverrideTagNoCache(node) { + return getFirstJSDocTag(node, ts.isJSDocOverrideTag, /*noCache*/ true); + } + ts.getJSDocOverrideTagNoCache = getJSDocOverrideTagNoCache; /** Gets the JSDoc deprecated tag for the node if present */ function getJSDocDeprecatedTag(node) { return getFirstJSDocTag(node, ts.isJSDocDeprecatedTag); @@ -12429,6 +12624,14 @@ var ts; return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + /** Gets the text of a jsdoc comment, flattening links to their text. */ + function getTextOfJSDocComment(comment) { + return typeof comment === "string" ? comment + : comment === null || comment === void 0 ? void 0 : comment.map(function (c) { + return c.kind === 313 /* JSDocText */ ? c.text : "{@link " + (c.name ? ts.entityNameToString(c.name) + " " : "") + c.text + "}"; + }).join(""); + } + ts.getTextOfJSDocComment = getTextOfJSDocComment; /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. @@ -12438,7 +12641,7 @@ var ts; return ts.emptyArray; } if (ts.isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 311 /* JSDocComment */); + ts.Debug.assert(node.parent.kind === 312 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } if (node.typeParameters) { @@ -12464,13 +12667,13 @@ var ts; } ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter; // #region - function isIdentifierOrPrivateIdentifier(node) { + function isMemberName(node) { return node.kind === 78 /* Identifier */ || node.kind === 79 /* PrivateIdentifier */; } - ts.isIdentifierOrPrivateIdentifier = isIdentifierOrPrivateIdentifier; + ts.isMemberName = isMemberName; /* @internal */ function isGetOrSetAccessorDeclaration(node) { - return node.kind === 168 /* SetAccessor */ || node.kind === 167 /* GetAccessor */; + return node.kind === 169 /* SetAccessor */ || node.kind === 168 /* GetAccessor */; } ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; function isPropertyAccessChain(node) { @@ -12488,10 +12691,10 @@ var ts; function isOptionalChain(node) { var kind = node.kind; return !!(node.flags & 32 /* OptionalChain */) && - (kind === 201 /* PropertyAccessExpression */ - || kind === 202 /* ElementAccessExpression */ - || kind === 203 /* CallExpression */ - || kind === 225 /* NonNullExpression */); + (kind === 202 /* PropertyAccessExpression */ + || kind === 203 /* ElementAccessExpression */ + || kind === 204 /* CallExpression */ + || kind === 226 /* NonNullExpression */); } ts.isOptionalChain = isOptionalChain; /* @internal */ @@ -12526,7 +12729,7 @@ var ts; } ts.isOutermostOptionalChain = isOutermostOptionalChain; function isNullishCoalesce(node) { - return node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */; + return node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */; } ts.isNullishCoalesce = isNullishCoalesce; function isConstTypeReference(node) { @@ -12543,17 +12746,17 @@ var ts; } ts.isNonNullChain = isNonNullChain; function isBreakOrContinueStatement(node) { - return node.kind === 241 /* BreakStatement */ || node.kind === 240 /* ContinueStatement */; + return node.kind === 242 /* BreakStatement */ || node.kind === 241 /* ContinueStatement */; } ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isNamedExportBindings(node) { - return node.kind === 269 /* NamespaceExport */ || node.kind === 268 /* NamedExports */; + return node.kind === 270 /* NamespaceExport */ || node.kind === 269 /* NamedExports */; } ts.isNamedExportBindings = isNamedExportBindings; function isUnparsedTextLike(node) { switch (node.kind) { - case 294 /* UnparsedText */: - case 295 /* UnparsedInternalText */: + case 295 /* UnparsedText */: + case 296 /* UnparsedInternalText */: return true; default: return false; @@ -12562,12 +12765,12 @@ var ts; ts.isUnparsedTextLike = isUnparsedTextLike; function isUnparsedNode(node) { return isUnparsedTextLike(node) || - node.kind === 292 /* UnparsedPrologue */ || - node.kind === 296 /* UnparsedSyntheticReference */; + node.kind === 293 /* UnparsedPrologue */ || + node.kind === 297 /* UnparsedSyntheticReference */; } ts.isUnparsedNode = isUnparsedNode; function isJSDocPropertyLikeTag(node) { - return node.kind === 333 /* JSDocPropertyTag */ || node.kind === 326 /* JSDocParameterTag */; + return node.kind === 337 /* JSDocPropertyTag */ || node.kind === 330 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; // #endregion @@ -12583,16 +12786,25 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 157 /* FirstNode */; + return kind >= 158 /* FirstNode */; } ts.isNodeKind = isNodeKind; + /** + * True if kind is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + function isTokenKind(kind) { + return kind >= 0 /* FirstToken */ && kind <= 157 /* LastToken */; + } + ts.isTokenKind = isTokenKind; /** * True if node is of some token syntax kind. * For example, this is true for an IfKeyword but not for an IfStatement. * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. */ function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 156 /* LastToken */; + return isTokenKind(n.kind); } ts.isToken = isToken; // Node Arrays @@ -12633,13 +12845,13 @@ var ts; ts.isImportOrExportSpecifier = isImportOrExportSpecifier; function isTypeOnlyImportOrExportDeclaration(node) { switch (node.kind) { - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return node.parent.parent.isTypeOnly; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return node.parent.isTypeOnly; - case 262 /* ImportClause */: - case 260 /* ImportEqualsDeclaration */: + case 263 /* ImportClause */: + case 261 /* ImportEqualsDeclaration */: return node.isTypeOnly; default: return false; @@ -12658,10 +12870,10 @@ var ts; ts.isGeneratedIdentifier = isGeneratedIdentifier; // Private Identifiers /*@internal*/ - function isPrivateIdentifierPropertyDeclaration(node) { - return ts.isPropertyDeclaration(node) && ts.isPrivateIdentifier(node.name); + function isPrivateIdentifierClassElementDeclaration(node) { + return (ts.isPropertyDeclaration(node) || isMethodOrAccessor(node)) && ts.isPrivateIdentifier(node.name); } - ts.isPrivateIdentifierPropertyDeclaration = isPrivateIdentifierPropertyDeclaration; + ts.isPrivateIdentifierClassElementDeclaration = isPrivateIdentifierClassElementDeclaration; /*@internal*/ function isPrivateIdentifierPropertyAccessExpression(node) { return ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name); @@ -12682,6 +12894,7 @@ var ts; case 121 /* ProtectedKeyword */: case 142 /* ReadonlyKeyword */: case 123 /* StaticKeyword */: + case 156 /* OverrideKeyword */: return true; } return false; @@ -12689,12 +12902,12 @@ var ts; ts.isModifierKind = isModifierKind; /* @internal */ function isParameterPropertyModifier(kind) { - return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + return !!(ts.modifierToFlag(kind) & 16476 /* ParameterPropertyModifier */); } ts.isParameterPropertyModifier = isParameterPropertyModifier; /* @internal */ function isClassMemberModifier(idToken) { - return isParameterPropertyModifier(idToken) || idToken === 123 /* StaticKeyword */; + return isParameterPropertyModifier(idToken) || idToken === 123 /* StaticKeyword */ || idToken === 156 /* OverrideKeyword */; } ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { @@ -12703,7 +12916,7 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 157 /* QualifiedName */ + return kind === 158 /* QualifiedName */ || kind === 78 /* Identifier */; } ts.isEntityName = isEntityName; @@ -12713,19 +12926,19 @@ var ts; || kind === 79 /* PrivateIdentifier */ || kind === 10 /* StringLiteral */ || kind === 8 /* NumericLiteral */ - || kind === 158 /* ComputedPropertyName */; + || kind === 159 /* ComputedPropertyName */; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; return kind === 78 /* Identifier */ - || kind === 196 /* ObjectBindingPattern */ - || kind === 197 /* ArrayBindingPattern */; + || kind === 197 /* ObjectBindingPattern */ + || kind === 198 /* ArrayBindingPattern */; } ts.isBindingName = isBindingName; // Functions function isFunctionLike(node) { - return node && isFunctionLikeKind(node.kind); + return !!node && isFunctionLikeKind(node.kind); } ts.isFunctionLike = isFunctionLike; /* @internal */ @@ -12735,13 +12948,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; default: return false; @@ -12750,14 +12963,14 @@ var ts; /* @internal */ function isFunctionLikeKind(kind) { switch (kind) { - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 313 /* JSDocSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 174 /* FunctionType */: - case 308 /* JSDocFunctionType */: - case 175 /* ConstructorType */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 315 /* JSDocSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 175 /* FunctionType */: + case 309 /* JSDocFunctionType */: + case 176 /* ConstructorType */: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -12772,29 +12985,29 @@ var ts; // Classes function isClassElement(node) { var kind = node.kind; - return kind === 166 /* Constructor */ - || kind === 163 /* PropertyDeclaration */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 171 /* IndexSignature */ - || kind === 229 /* SemicolonClassElement */; + return kind === 167 /* Constructor */ + || kind === 164 /* PropertyDeclaration */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 172 /* IndexSignature */ + || kind === 230 /* SemicolonClassElement */; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */); + return node && (node.kind === 253 /* ClassDeclaration */ || node.kind === 222 /* ClassExpression */); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 167 /* GetAccessor */ || node.kind === 168 /* SetAccessor */); + return node && (node.kind === 168 /* GetAccessor */ || node.kind === 169 /* SetAccessor */); } ts.isAccessor = isAccessor; /* @internal */ function isMethodOrAccessor(node) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return true; default: return false; @@ -12804,11 +13017,11 @@ var ts; // Type members function isTypeElement(node) { var kind = node.kind; - return kind === 170 /* ConstructSignature */ - || kind === 169 /* CallSignature */ - || kind === 162 /* PropertySignature */ - || kind === 164 /* MethodSignature */ - || kind === 171 /* IndexSignature */; + return kind === 171 /* ConstructSignature */ + || kind === 170 /* CallSignature */ + || kind === 163 /* PropertySignature */ + || kind === 165 /* MethodSignature */ + || kind === 172 /* IndexSignature */; } ts.isTypeElement = isTypeElement; function isClassOrTypeElement(node) { @@ -12817,12 +13030,12 @@ var ts; ts.isClassOrTypeElement = isClassOrTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 288 /* PropertyAssignment */ - || kind === 289 /* ShorthandPropertyAssignment */ - || kind === 290 /* SpreadAssignment */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 289 /* PropertyAssignment */ + || kind === 290 /* ShorthandPropertyAssignment */ + || kind === 291 /* SpreadAssignment */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; // Type @@ -12837,8 +13050,8 @@ var ts; ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return true; } return false; @@ -12849,8 +13062,8 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 197 /* ArrayBindingPattern */ - || kind === 196 /* ObjectBindingPattern */; + return kind === 198 /* ArrayBindingPattern */ + || kind === 197 /* ObjectBindingPattern */; } return false; } @@ -12858,15 +13071,15 @@ var ts; /* @internal */ function isAssignmentPattern(node) { var kind = node.kind; - return kind === 199 /* ArrayLiteralExpression */ - || kind === 200 /* ObjectLiteralExpression */; + return kind === 200 /* ArrayLiteralExpression */ + || kind === 201 /* ObjectLiteralExpression */; } ts.isAssignmentPattern = isAssignmentPattern; /* @internal */ function isArrayBindingElement(node) { var kind = node.kind; - return kind === 198 /* BindingElement */ - || kind === 222 /* OmittedExpression */; + return kind === 199 /* BindingElement */ + || kind === 223 /* OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; /** @@ -12875,9 +13088,9 @@ var ts; /* @internal */ function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: return true; } return false; @@ -12898,8 +13111,8 @@ var ts; /* @internal */ function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 196 /* ObjectBindingPattern */: - case 200 /* ObjectLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 201 /* ObjectLiteralExpression */: return true; } return false; @@ -12911,8 +13124,8 @@ var ts; /* @internal */ function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 197 /* ArrayBindingPattern */: - case 199 /* ArrayLiteralExpression */: + case 198 /* ArrayBindingPattern */: + case 200 /* ArrayLiteralExpression */: return true; } return false; @@ -12921,26 +13134,26 @@ var ts; /* @internal */ function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { var kind = node.kind; - return kind === 201 /* PropertyAccessExpression */ - || kind === 157 /* QualifiedName */ - || kind === 195 /* ImportType */; + return kind === 202 /* PropertyAccessExpression */ + || kind === 158 /* QualifiedName */ + || kind === 196 /* ImportType */; } ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; // Expression function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 201 /* PropertyAccessExpression */ - || kind === 157 /* QualifiedName */; + return kind === 202 /* PropertyAccessExpression */ + || kind === 158 /* QualifiedName */; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 205 /* TaggedTemplateExpression */: - case 161 /* Decorator */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 206 /* TaggedTemplateExpression */: + case 162 /* Decorator */: return true; default: return false; @@ -12948,12 +13161,12 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 203 /* CallExpression */ || node.kind === 204 /* NewExpression */; + return node.kind === 204 /* CallExpression */ || node.kind === 205 /* NewExpression */; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 218 /* TemplateExpression */ + return kind === 219 /* TemplateExpression */ || kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; @@ -12964,33 +13177,33 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: - case 204 /* NewExpression */: - case 203 /* CallExpression */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: - case 205 /* TaggedTemplateExpression */: - case 199 /* ArrayLiteralExpression */: - case 207 /* ParenthesizedExpression */: - case 200 /* ObjectLiteralExpression */: - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 205 /* NewExpression */: + case 204 /* CallExpression */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: + case 206 /* TaggedTemplateExpression */: + case 200 /* ArrayLiteralExpression */: + case 208 /* ParenthesizedExpression */: + case 201 /* ObjectLiteralExpression */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: case 78 /* Identifier */: case 13 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: case 9 /* BigIntLiteral */: case 10 /* StringLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: case 94 /* FalseKeyword */: case 103 /* NullKeyword */: case 107 /* ThisKeyword */: case 109 /* TrueKeyword */: case 105 /* SuperKeyword */: - case 225 /* NonNullExpression */: - case 226 /* MetaProperty */: + case 226 /* NonNullExpression */: + case 227 /* MetaProperty */: case 99 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression return true; default: @@ -13004,13 +13217,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: - case 210 /* DeleteExpression */: - case 211 /* TypeOfExpression */: - case 212 /* VoidExpression */: - case 213 /* AwaitExpression */: - case 206 /* TypeAssertionExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 211 /* DeleteExpression */: + case 212 /* TypeOfExpression */: + case 213 /* VoidExpression */: + case 214 /* AwaitExpression */: + case 207 /* TypeAssertionExpression */: return true; default: return isLeftHandSideExpressionKind(kind); @@ -13019,9 +13232,9 @@ var ts; /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return true; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */; default: @@ -13040,15 +13253,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 217 /* ConditionalExpression */: - case 219 /* YieldExpression */: - case 209 /* ArrowFunction */: - case 216 /* BinaryExpression */: - case 220 /* SpreadElement */: - case 224 /* AsExpression */: - case 222 /* OmittedExpression */: - case 337 /* CommaListExpression */: - case 336 /* PartiallyEmittedExpression */: + case 218 /* ConditionalExpression */: + case 220 /* YieldExpression */: + case 210 /* ArrowFunction */: + case 217 /* BinaryExpression */: + case 221 /* SpreadElement */: + case 225 /* AsExpression */: + case 223 /* OmittedExpression */: + case 341 /* CommaListExpression */: + case 340 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -13056,8 +13269,8 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 206 /* TypeAssertionExpression */ - || kind === 224 /* AsExpression */; + return kind === 207 /* TypeAssertionExpression */ + || kind === 225 /* AsExpression */; } ts.isAssertionExpression = isAssertionExpression; /* @internal */ @@ -13068,13 +13281,13 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return true; - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -13103,7 +13316,7 @@ var ts; ts.isExternalModuleIndicator = isExternalModuleIndicator; /* @internal */ function isForInOrOfStatement(node) { - return node.kind === 238 /* ForInStatement */ || node.kind === 239 /* ForOfStatement */; + return node.kind === 239 /* ForInStatement */ || node.kind === 240 /* ForOfStatement */; } ts.isForInOrOfStatement = isForInOrOfStatement; // Element @@ -13127,114 +13340,114 @@ var ts; /* @internal */ function isModuleBody(node) { var kind = node.kind; - return kind === 257 /* ModuleBlock */ - || kind === 256 /* ModuleDeclaration */ + return kind === 258 /* ModuleBlock */ + || kind === 257 /* ModuleDeclaration */ || kind === 78 /* Identifier */; } ts.isModuleBody = isModuleBody; /* @internal */ function isNamespaceBody(node) { var kind = node.kind; - return kind === 257 /* ModuleBlock */ - || kind === 256 /* ModuleDeclaration */; + return kind === 258 /* ModuleBlock */ + || kind === 257 /* ModuleDeclaration */; } ts.isNamespaceBody = isNamespaceBody; /* @internal */ function isJSDocNamespaceBody(node) { var kind = node.kind; return kind === 78 /* Identifier */ - || kind === 256 /* ModuleDeclaration */; + || kind === 257 /* ModuleDeclaration */; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; /* @internal */ function isNamedImportBindings(node) { var kind = node.kind; - return kind === 264 /* NamedImports */ - || kind === 263 /* NamespaceImport */; + return kind === 265 /* NamedImports */ + || kind === 264 /* NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; /* @internal */ function isModuleOrEnumDeclaration(node) { - return node.kind === 256 /* ModuleDeclaration */ || node.kind === 255 /* EnumDeclaration */; + return node.kind === 257 /* ModuleDeclaration */ || node.kind === 256 /* EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 209 /* ArrowFunction */ - || kind === 198 /* BindingElement */ - || kind === 252 /* ClassDeclaration */ - || kind === 221 /* ClassExpression */ - || kind === 166 /* Constructor */ - || kind === 255 /* EnumDeclaration */ - || kind === 291 /* EnumMember */ - || kind === 270 /* ExportSpecifier */ - || kind === 251 /* FunctionDeclaration */ - || kind === 208 /* FunctionExpression */ - || kind === 167 /* GetAccessor */ - || kind === 262 /* ImportClause */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 265 /* ImportSpecifier */ - || kind === 253 /* InterfaceDeclaration */ - || kind === 280 /* JsxAttribute */ - || kind === 165 /* MethodDeclaration */ - || kind === 164 /* MethodSignature */ - || kind === 256 /* ModuleDeclaration */ - || kind === 259 /* NamespaceExportDeclaration */ - || kind === 263 /* NamespaceImport */ - || kind === 269 /* NamespaceExport */ - || kind === 160 /* Parameter */ - || kind === 288 /* PropertyAssignment */ - || kind === 163 /* PropertyDeclaration */ - || kind === 162 /* PropertySignature */ - || kind === 168 /* SetAccessor */ - || kind === 289 /* ShorthandPropertyAssignment */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 159 /* TypeParameter */ - || kind === 249 /* VariableDeclaration */ - || kind === 331 /* JSDocTypedefTag */ - || kind === 324 /* JSDocCallbackTag */ - || kind === 333 /* JSDocPropertyTag */; + return kind === 210 /* ArrowFunction */ + || kind === 199 /* BindingElement */ + || kind === 253 /* ClassDeclaration */ + || kind === 222 /* ClassExpression */ + || kind === 167 /* Constructor */ + || kind === 256 /* EnumDeclaration */ + || kind === 292 /* EnumMember */ + || kind === 271 /* ExportSpecifier */ + || kind === 252 /* FunctionDeclaration */ + || kind === 209 /* FunctionExpression */ + || kind === 168 /* GetAccessor */ + || kind === 263 /* ImportClause */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 266 /* ImportSpecifier */ + || kind === 254 /* InterfaceDeclaration */ + || kind === 281 /* JsxAttribute */ + || kind === 166 /* MethodDeclaration */ + || kind === 165 /* MethodSignature */ + || kind === 257 /* ModuleDeclaration */ + || kind === 260 /* NamespaceExportDeclaration */ + || kind === 264 /* NamespaceImport */ + || kind === 270 /* NamespaceExport */ + || kind === 161 /* Parameter */ + || kind === 289 /* PropertyAssignment */ + || kind === 164 /* PropertyDeclaration */ + || kind === 163 /* PropertySignature */ + || kind === 169 /* SetAccessor */ + || kind === 290 /* ShorthandPropertyAssignment */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 160 /* TypeParameter */ + || kind === 250 /* VariableDeclaration */ + || kind === 335 /* JSDocTypedefTag */ + || kind === 328 /* JSDocCallbackTag */ + || kind === 337 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { - return kind === 251 /* FunctionDeclaration */ - || kind === 271 /* MissingDeclaration */ - || kind === 252 /* ClassDeclaration */ - || kind === 253 /* InterfaceDeclaration */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 255 /* EnumDeclaration */ - || kind === 256 /* ModuleDeclaration */ - || kind === 261 /* ImportDeclaration */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 267 /* ExportDeclaration */ - || kind === 266 /* ExportAssignment */ - || kind === 259 /* NamespaceExportDeclaration */; + return kind === 252 /* FunctionDeclaration */ + || kind === 272 /* MissingDeclaration */ + || kind === 253 /* ClassDeclaration */ + || kind === 254 /* InterfaceDeclaration */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 256 /* EnumDeclaration */ + || kind === 257 /* ModuleDeclaration */ + || kind === 262 /* ImportDeclaration */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 268 /* ExportDeclaration */ + || kind === 267 /* ExportAssignment */ + || kind === 260 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 241 /* BreakStatement */ - || kind === 240 /* ContinueStatement */ - || kind === 248 /* DebuggerStatement */ - || kind === 235 /* DoStatement */ - || kind === 233 /* ExpressionStatement */ - || kind === 231 /* EmptyStatement */ - || kind === 238 /* ForInStatement */ - || kind === 239 /* ForOfStatement */ - || kind === 237 /* ForStatement */ - || kind === 234 /* IfStatement */ - || kind === 245 /* LabeledStatement */ - || kind === 242 /* ReturnStatement */ - || kind === 244 /* SwitchStatement */ - || kind === 246 /* ThrowStatement */ - || kind === 247 /* TryStatement */ - || kind === 232 /* VariableStatement */ - || kind === 236 /* WhileStatement */ - || kind === 243 /* WithStatement */ - || kind === 335 /* NotEmittedStatement */ - || kind === 339 /* EndOfDeclarationMarker */ - || kind === 338 /* MergeDeclarationMarker */; + return kind === 242 /* BreakStatement */ + || kind === 241 /* ContinueStatement */ + || kind === 249 /* DebuggerStatement */ + || kind === 236 /* DoStatement */ + || kind === 234 /* ExpressionStatement */ + || kind === 232 /* EmptyStatement */ + || kind === 239 /* ForInStatement */ + || kind === 240 /* ForOfStatement */ + || kind === 238 /* ForStatement */ + || kind === 235 /* IfStatement */ + || kind === 246 /* LabeledStatement */ + || kind === 243 /* ReturnStatement */ + || kind === 245 /* SwitchStatement */ + || kind === 247 /* ThrowStatement */ + || kind === 248 /* TryStatement */ + || kind === 233 /* VariableStatement */ + || kind === 237 /* WhileStatement */ + || kind === 244 /* WithStatement */ + || kind === 339 /* NotEmittedStatement */ + || kind === 343 /* EndOfDeclarationMarker */ + || kind === 342 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { - if (node.kind === 159 /* TypeParameter */) { - return (node.parent && node.parent.kind !== 330 /* JSDocTemplateTag */) || ts.isInJSFile(node); + if (node.kind === 160 /* TypeParameter */) { + return (node.parent && node.parent.kind !== 334 /* JSDocTemplateTag */) || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -13261,10 +13474,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 230 /* Block */) + if (node.kind !== 231 /* Block */) return false; if (node.parent !== undefined) { - if (node.parent.kind === 247 /* TryStatement */ || node.parent.kind === 287 /* CatchClause */) { + if (node.parent.kind === 248 /* TryStatement */ || node.parent.kind === 288 /* CatchClause */) { return false; } } @@ -13278,15 +13491,15 @@ var ts; var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) - || kind === 230 /* Block */; + || kind === 231 /* Block */; } ts.isStatementOrBlock = isStatementOrBlock; // Module references /* @internal */ function isModuleReference(node) { var kind = node.kind; - return kind === 272 /* ExternalModuleReference */ - || kind === 157 /* QualifiedName */ + return kind === 273 /* ExternalModuleReference */ + || kind === 158 /* QualifiedName */ || kind === 78 /* Identifier */; } ts.isModuleReference = isModuleReference; @@ -13296,70 +13509,76 @@ var ts; var kind = node.kind; return kind === 107 /* ThisKeyword */ || kind === 78 /* Identifier */ - || kind === 201 /* PropertyAccessExpression */; + || kind === 202 /* PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; /* @internal */ function isJsxChild(node) { var kind = node.kind; - return kind === 273 /* JsxElement */ - || kind === 283 /* JsxExpression */ - || kind === 274 /* JsxSelfClosingElement */ + return kind === 274 /* JsxElement */ + || kind === 284 /* JsxExpression */ + || kind === 275 /* JsxSelfClosingElement */ || kind === 11 /* JsxText */ - || kind === 277 /* JsxFragment */; + || kind === 278 /* JsxFragment */; } ts.isJsxChild = isJsxChild; /* @internal */ function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 280 /* JsxAttribute */ - || kind === 282 /* JsxSpreadAttribute */; + return kind === 281 /* JsxAttribute */ + || kind === 283 /* JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; /* @internal */ function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 10 /* StringLiteral */ - || kind === 283 /* JsxExpression */; + || kind === 284 /* JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 275 /* JsxOpeningElement */ - || kind === 274 /* JsxSelfClosingElement */; + return kind === 276 /* JsxOpeningElement */ + || kind === 275 /* JsxSelfClosingElement */; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 284 /* CaseClause */ - || kind === 285 /* DefaultClause */; + return kind === 285 /* CaseClause */ + || kind === 286 /* DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; // JSDoc /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 301 /* FirstJSDocNode */ && node.kind <= 333 /* LastJSDocNode */; + return node.kind >= 302 /* FirstJSDocNode */ && node.kind <= 337 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 311 /* JSDocComment */ || node.kind === 310 /* JSDocNamepathType */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + return node.kind === 312 /* JSDocComment */ + || node.kind === 311 /* JSDocNamepathType */ + || node.kind === 313 /* JSDocText */ + || node.kind === 316 /* JSDocLink */ + || isJSDocTag(node) + || ts.isJSDocTypeLiteral(node) + || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 314 /* FirstJSDocTagNode */ && node.kind <= 333 /* LastJSDocTagNode */; + return node.kind >= 317 /* FirstJSDocTagNode */ && node.kind <= 337 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { - return node.kind === 168 /* SetAccessor */; + return node.kind === 169 /* SetAccessor */; } ts.isSetAccessor = isSetAccessor; function isGetAccessor(node) { - return node.kind === 167 /* GetAccessor */; + return node.kind === 168 /* GetAccessor */; } ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ @@ -13385,13 +13604,13 @@ var ts; /** True if has initializer node attached to it. */ function hasOnlyExpressionInitializer(node) { switch (node.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: - case 162 /* PropertySignature */: - case 163 /* PropertyDeclaration */: - case 288 /* PropertyAssignment */: - case 291 /* EnumMember */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: + case 163 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 289 /* PropertyAssignment */: + case 292 /* EnumMember */: return true; default: return false; @@ -13399,12 +13618,12 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - return node.kind === 280 /* JsxAttribute */ || node.kind === 282 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); + return node.kind === 281 /* JsxAttribute */ || node.kind === 283 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; /* @internal */ function isTypeReferenceType(node) { - return node.kind === 173 /* TypeReference */ || node.kind === 223 /* ExpressionWithTypeArguments */; + return node.kind === 174 /* TypeReference */ || node.kind === 224 /* ExpressionWithTypeArguments */; } ts.isTypeReferenceType = isTypeReferenceType; var MAX_SMI_X86 = 1073741823; @@ -13643,7 +13862,9 @@ var ts; } ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + return oldResolution.resolvedFileName === newResolution.resolvedFileName + && oldResolution.primary === newResolution.primary + && oldResolution.originalPath === newResolution.originalPath; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { @@ -13685,7 +13906,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 297 /* SourceFile */) { + while (node && node.kind !== 298 /* SourceFile */) { node = node.parent; } return node; @@ -13693,11 +13914,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 230 /* Block */: - case 258 /* CaseBlock */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 231 /* Block */: + case 259 /* CaseBlock */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: return true; } return false; @@ -13893,10 +14114,12 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 334 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 338 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, + /*stopAfterLineBreak*/ false, + /*stopAtComments*/ false, isInJSDoc(node)); } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { @@ -14015,9 +14238,11 @@ var ts; DataView: ["setBigInt64", "setBigUint64", "getBigInt64", "getBigUint64"], RelativeTimeFormat: ["format", "formatToParts", "resolvedOptions"] }, - esnext: { + es2021: { PromiseConstructor: ["any"], - String: ["replaceAll"], + String: ["replaceAll"] + }, + esnext: { NumberFormat: ["formatToParts"] } }; @@ -14110,7 +14335,7 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 249 /* VariableDeclaration */ && node.parent.kind === 287 /* CatchClause */; + return node.kind === 250 /* VariableDeclaration */ && node.parent.kind === 288 /* CatchClause */; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { @@ -14142,11 +14367,11 @@ var ts; ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. - return node && node.kind === 256 /* ModuleDeclaration */ && (!node.body); + return !!node && node.kind === 257 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 297 /* SourceFile */ || - node.kind === 256 /* ModuleDeclaration */ || + return node.kind === 298 /* SourceFile */ || + node.kind === 257 /* ModuleDeclaration */ || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -14163,16 +14388,17 @@ var ts; // - defined in the top level scope and source file is an external module // - defined inside ambient module declaration located in the top level scope and source file not an external module switch (node.parent.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: return ts.isExternalModule(node.parent); - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } ts.isModuleAugmentationExternal = isModuleAugmentationExternal; function getNonAugmentationDeclaration(symbol) { - return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); + var _a; + return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); } ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration; function isEffectiveExternalModule(node, compilerOptions) { @@ -14218,22 +14444,22 @@ var ts; ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile; function isBlockScope(node, parentNode) { switch (node.kind) { - case 297 /* SourceFile */: - case 258 /* CaseBlock */: - case 287 /* CatchClause */: - case 256 /* ModuleDeclaration */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 298 /* SourceFile */: + case 259 /* CaseBlock */: + case 288 /* CatchClause */: + case 257 /* ModuleDeclaration */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; - case 230 /* Block */: + case 231 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block return !ts.isFunctionLike(parentNode); @@ -14243,9 +14469,9 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: - case 313 /* JSDocSignature */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: + case 315 /* JSDocSignature */: return true; default: ts.assertType(node); @@ -14255,25 +14481,25 @@ var ts; ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 164 /* MethodSignature */: - case 171 /* IndexSignature */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 308 /* JSDocFunctionType */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 330 /* JSDocTemplateTag */: - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 165 /* MethodSignature */: + case 172 /* IndexSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 309 /* JSDocFunctionType */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 334 /* JSDocTemplateTag */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; default: ts.assertType(node); @@ -14283,8 +14509,8 @@ var ts; ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: return true; default: return false; @@ -14293,15 +14519,15 @@ var ts; ts.isAnyImportSyntax = isAnyImportSyntax; function isLateVisibilityPaintedStatement(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 232 /* VariableStatement */: - case 252 /* ClassDeclaration */: - case 251 /* FunctionDeclaration */: - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 233 /* VariableStatement */: + case 253 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: return true; default: return false; @@ -14334,7 +14560,7 @@ var ts; } ts.getNameFromIndexInfo = getNameFromIndexInfo; function isComputedNonLiteralName(name) { - return name.kind === 158 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); + return name.kind === 159 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); } ts.isComputedNonLiteralName = isComputedNonLiteralName; function getTextOfPropertyName(name) { @@ -14346,7 +14572,7 @@ var ts; case 8 /* NumericLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: if (isStringOrNumericLiteralLike(name.expression)) return ts.escapeLeadingUnderscores(name.expression.text); return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames"); @@ -14362,9 +14588,9 @@ var ts; case 79 /* PrivateIdentifier */: case 78 /* Identifier */: return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) { return entityNameToString(name.expression) + "." + entityNameToString(name.name); } @@ -14450,7 +14676,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 230 /* Block */) { + if (node.body && node.body.kind === 231 /* Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -14464,7 +14690,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -14473,28 +14699,28 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 249 /* VariableDeclaration */: - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 254 /* TypeAliasDeclaration */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 250 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 255 /* TypeAliasDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: errorNode = node.name; break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: var start = ts.skipTrivia(sourceFile.text, node.pos); var end = node.statements.length > 0 ? node.statements[0].pos : node.end; return ts.createTextSpanFromBounds(start, end); @@ -14546,11 +14772,11 @@ var ts; } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 203 /* CallExpression */ && n.expression.kind === 105 /* SuperKeyword */; + return n.kind === 204 /* CallExpression */ && n.expression.kind === 105 /* SuperKeyword */; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 203 /* CallExpression */ && n.expression.kind === 99 /* ImportKeyword */; + return n.kind === 204 /* CallExpression */ && n.expression.kind === 99 /* ImportKeyword */; } ts.isImportCall = isImportCall; function isImportMeta(n) { @@ -14564,7 +14790,7 @@ var ts; } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { - return node.kind === 233 /* ExpressionStatement */ + return node.kind === 234 /* ExpressionStatement */ && node.expression.kind === 10 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; @@ -14592,11 +14818,12 @@ var ts; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 160 /* Parameter */ || - node.kind === 159 /* TypeParameter */ || - node.kind === 208 /* FunctionExpression */ || - node.kind === 209 /* ArrowFunction */ || - node.kind === 207 /* ParenthesizedExpression */) ? + var commentRanges = (node.kind === 161 /* Parameter */ || + node.kind === 160 /* TypeParameter */ || + node.kind === 209 /* FunctionExpression */ || + node.kind === 210 /* ArrowFunction */ || + node.kind === 208 /* ParenthesizedExpression */ || + node.kind === 250 /* VariableDeclaration */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -14612,7 +14839,7 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (172 /* FirstTypeNode */ <= node.kind && node.kind <= 195 /* LastTypeNode */) { + if (173 /* FirstTypeNode */ <= node.kind && node.kind <= 196 /* LastTypeNode */) { return true; } switch (node.kind) { @@ -14628,32 +14855,32 @@ var ts; case 141 /* NeverKeyword */: return true; case 113 /* VoidKeyword */: - return node.parent.kind !== 212 /* VoidExpression */; - case 223 /* ExpressionWithTypeArguments */: + return node.parent.kind !== 213 /* VoidExpression */; + case 224 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 159 /* TypeParameter */: - return node.parent.kind === 190 /* MappedType */ || node.parent.kind === 185 /* InferType */; + case 160 /* TypeParameter */: + return node.parent.kind === 191 /* MappedType */ || node.parent.kind === 186 /* InferType */; // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container case 78 /* Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 157 /* QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 158 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 202 /* PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 78 /* Identifier */ || node.kind === 157 /* QualifiedName */ || node.kind === 201 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + ts.Debug.assert(node.kind === 78 /* Identifier */ || node.kind === 158 /* QualifiedName */ || node.kind === 202 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); // falls through - case 157 /* QualifiedName */: - case 201 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: case 107 /* ThisKeyword */: { var parent = node.parent; - if (parent.kind === 176 /* TypeQuery */) { + if (parent.kind === 177 /* TypeQuery */) { return false; } - if (parent.kind === 195 /* ImportType */) { + if (parent.kind === 196 /* ImportType */) { return !parent.isTypeOf; } // Do not recursively call isPartOfTypeNode on the parent. In the example: @@ -14662,40 +14889,40 @@ var ts; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. // Only C and A.B.C are type nodes. - if (172 /* FirstTypeNode */ <= parent.kind && parent.kind <= 195 /* LastTypeNode */) { + if (173 /* FirstTypeNode */ <= parent.kind && parent.kind <= 196 /* LastTypeNode */) { return true; } switch (parent.kind) { - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return node === parent.constraint; - case 330 /* JSDocTemplateTag */: + case 334 /* JSDocTemplateTag */: return node === parent.constraint; - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 160 /* Parameter */: - case 249 /* VariableDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 161 /* Parameter */: + case 250 /* VariableDeclaration */: return node === parent.type; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return node === parent.type; - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return node === parent.type; - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: return node === parent.type; - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: return ts.contains(parent.typeArguments, node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -14720,23 +14947,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitor(node); - case 258 /* CaseBlock */: - case 230 /* Block */: - case 234 /* IfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 243 /* WithStatement */: - case 244 /* SwitchStatement */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: - case 245 /* LabeledStatement */: - case 247 /* TryStatement */: - case 287 /* CatchClause */: + case 259 /* CaseBlock */: + case 231 /* Block */: + case 235 /* IfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 244 /* WithStatement */: + case 245 /* SwitchStatement */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 246 /* LabeledStatement */: + case 248 /* TryStatement */: + case 288 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -14746,23 +14973,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 255 /* EnumDeclaration */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: // These are not allowed inside a generator now, but eventually they may be allowed // as local types. Regardless, skip them to avoid the work. return; default: if (ts.isFunctionLike(node)) { - if (node.name && node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 159 /* ComputedPropertyName */) { // Note that we will not include methods/accessors of a class because they would require // first descending into the class. This is by design. traverse(node.name.expression); @@ -14785,10 +15012,10 @@ var ts; * @param node The type node. */ function getRestParameterElementType(node) { - if (node && node.kind === 178 /* ArrayType */) { + if (node && node.kind === 179 /* ArrayType */) { return node.elementType; } - else if (node && node.kind === 173 /* TypeReference */) { + else if (node && node.kind === 174 /* TypeReference */) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -14798,12 +15025,12 @@ var ts; ts.getRestParameterElementType = getRestParameterElementType; function getMembersOfDeclaration(node) { switch (node.kind) { - case 253 /* InterfaceDeclaration */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 177 /* TypeLiteral */: + case 254 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 178 /* TypeLiteral */: return node.members; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return node.properties; } } @@ -14811,14 +15038,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 198 /* BindingElement */: - case 291 /* EnumMember */: - case 160 /* Parameter */: - case 288 /* PropertyAssignment */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 289 /* ShorthandPropertyAssignment */: - case 249 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 292 /* EnumMember */: + case 161 /* Parameter */: + case 289 /* PropertyAssignment */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 290 /* ShorthandPropertyAssignment */: + case 250 /* VariableDeclaration */: return true; } } @@ -14830,8 +15057,8 @@ var ts; } ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { - return node.parent.kind === 250 /* VariableDeclarationList */ - && node.parent.parent.kind === 232 /* VariableStatement */; + return node.parent.kind === 251 /* VariableDeclarationList */ + && node.parent.parent.kind === 233 /* VariableStatement */; } ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; function isValidESSymbolDeclaration(node) { @@ -14842,13 +15069,13 @@ var ts; ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return true; } return false; @@ -14859,7 +15086,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 245 /* LabeledStatement */) { + if (node.statement.kind !== 246 /* LabeledStatement */) { return node.statement; } node = node.statement; @@ -14867,17 +15094,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 230 /* Block */ && ts.isFunctionLike(node.parent); + return node && node.kind === 231 /* Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 165 /* MethodDeclaration */ && node.parent.kind === 200 /* ObjectLiteralExpression */; + return node && node.kind === 166 /* MethodDeclaration */ && node.parent.kind === 201 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 165 /* MethodDeclaration */ && - (node.parent.kind === 200 /* ObjectLiteralExpression */ || - node.parent.kind === 221 /* ClassExpression */); + return node.kind === 166 /* MethodDeclaration */ && + (node.parent.kind === 201 /* ObjectLiteralExpression */ || + node.parent.kind === 222 /* ClassExpression */); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -14890,7 +15117,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return objectLiteral.properties.filter(function (property) { - if (property.kind === 288 /* PropertyAssignment */) { + if (property.kind === 289 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); return key === propName || (!!key2 && key2 === propName); } @@ -14939,14 +15166,14 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { - ts.Debug.assert(node.kind !== 297 /* SourceFile */); + ts.Debug.assert(node.kind !== 298 /* SourceFile */); while (true) { node = node.parent; if (!node) { return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. } switch (node.kind) { - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: // If the grandparent node is an object literal (as opposed to a class), // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container @@ -14961,9 +15188,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 161 /* Decorator */: + case 162 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 160 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 161 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -14974,26 +15201,26 @@ var ts; node = node.parent; } break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // falls through - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 256 /* ModuleDeclaration */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 255 /* EnumDeclaration */: - case 297 /* SourceFile */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 257 /* ModuleDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 256 /* EnumDeclaration */: + case 298 /* SourceFile */: return node; } } @@ -15012,9 +15239,9 @@ var ts; var container = getThisContainer(node, /*includeArrowFunctions*/ false); if (container) { switch (container.kind) { - case 166 /* Constructor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 167 /* Constructor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return container; } } @@ -15036,27 +15263,27 @@ var ts; return node; } switch (node.kind) { - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: node = node.parent; break; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: if (!stopOnFunctions) { continue; } // falls through - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return node; - case 161 /* Decorator */: + case 162 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 160 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 161 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -15072,14 +15299,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 208 /* FunctionExpression */ || func.kind === 209 /* ArrowFunction */) { + if (func.kind === 209 /* FunctionExpression */ || func.kind === 210 /* ArrowFunction */) { var prev = func; var parent = func.parent; - while (parent.kind === 207 /* ParenthesizedExpression */) { + while (parent.kind === 208 /* ParenthesizedExpression */) { prev = parent; parent = parent.parent; } - if (parent.kind === 203 /* CallExpression */ && parent.expression === prev) { + if (parent.kind === 204 /* CallExpression */ && parent.expression === prev) { return parent; } } @@ -15095,7 +15322,7 @@ var ts; */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 201 /* PropertyAccessExpression */ || kind === 202 /* ElementAccessExpression */) + return (kind === 202 /* PropertyAccessExpression */ || kind === 203 /* ElementAccessExpression */) && node.expression.kind === 105 /* SuperKeyword */; } ts.isSuperProperty = isSuperProperty; @@ -15104,7 +15331,7 @@ var ts; */ function isThisProperty(node) { var kind = node.kind; - return (kind === 201 /* PropertyAccessExpression */ || kind === 202 /* ElementAccessExpression */) + return (kind === 202 /* PropertyAccessExpression */ || kind === 203 /* ElementAccessExpression */) && node.expression.kind === 107 /* ThisKeyword */; } ts.isThisProperty = isThisProperty; @@ -15113,17 +15340,25 @@ var ts; return !!node && ts.isVariableDeclaration(node) && ((_a = node.initializer) === null || _a === void 0 ? void 0 : _a.kind) === 107 /* ThisKeyword */; } ts.isThisInitializedDeclaration = isThisInitializedDeclaration; + function isThisInitializedObjectBindingExpression(node) { + return !!node + && (ts.isShorthandPropertyAssignment(node) || ts.isPropertyAssignment(node)) + && ts.isBinaryExpression(node.parent.parent) + && node.parent.parent.operatorToken.kind === 62 /* EqualsToken */ + && node.parent.parent.right.kind === 107 /* ThisKeyword */; + } + ts.isThisInitializedObjectBindingExpression = isThisInitializedObjectBindingExpression; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return node.typeName; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) ? node.expression : undefined; // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s. case 78 /* Identifier */: - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return node; } return undefined; @@ -15131,10 +15366,10 @@ var ts; ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { switch (node.kind) { - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return node.tag; - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return node.tagName; default: return node.expression; @@ -15147,25 +15382,25 @@ var ts; return false; } switch (node.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: // classes are valid targets return true; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return parent.kind === 252 /* ClassDeclaration */; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: + return parent.kind === 253 /* ClassDeclaration */; + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && parent.kind === 252 /* ClassDeclaration */; - case 160 /* Parameter */: + && parent.kind === 253 /* ClassDeclaration */; + case 161 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; return parent.body !== undefined - && (parent.kind === 166 /* Constructor */ - || parent.kind === 165 /* MethodDeclaration */ - || parent.kind === 168 /* SetAccessor */) - && grandparent.kind === 252 /* ClassDeclaration */; + && (parent.kind === 167 /* Constructor */ + || parent.kind === 166 /* MethodDeclaration */ + || parent.kind === 169 /* SetAccessor */) + && grandparent.kind === 253 /* ClassDeclaration */; } return false; } @@ -15181,10 +15416,10 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 - case 165 /* MethodDeclaration */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 169 /* SetAccessor */: return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 default: return false; @@ -15193,9 +15428,9 @@ var ts; ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 275 /* JsxOpeningElement */ || - parent.kind === 274 /* JsxSelfClosingElement */ || - parent.kind === 276 /* JsxClosingElement */) { + if (parent.kind === 276 /* JsxOpeningElement */ || + parent.kind === 275 /* JsxSelfClosingElement */ || + parent.kind === 277 /* JsxClosingElement */) { return parent.tagName === node; } return false; @@ -15208,44 +15443,44 @@ var ts; case 109 /* TrueKeyword */: case 94 /* FalseKeyword */: case 13 /* RegularExpressionLiteral */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 205 /* TaggedTemplateExpression */: - case 224 /* AsExpression */: - case 206 /* TypeAssertionExpression */: - case 225 /* NonNullExpression */: - case 207 /* ParenthesizedExpression */: - case 208 /* FunctionExpression */: - case 221 /* ClassExpression */: - case 209 /* ArrowFunction */: - case 212 /* VoidExpression */: - case 210 /* DeleteExpression */: - case 211 /* TypeOfExpression */: - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: - case 216 /* BinaryExpression */: - case 217 /* ConditionalExpression */: - case 220 /* SpreadElement */: - case 218 /* TemplateExpression */: - case 222 /* OmittedExpression */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: - case 219 /* YieldExpression */: - case 213 /* AwaitExpression */: - case 226 /* MetaProperty */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 206 /* TaggedTemplateExpression */: + case 225 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 226 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 209 /* FunctionExpression */: + case 222 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 213 /* VoidExpression */: + case 211 /* DeleteExpression */: + case 212 /* TypeOfExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 217 /* BinaryExpression */: + case 218 /* ConditionalExpression */: + case 221 /* SpreadElement */: + case 219 /* TemplateExpression */: + case 223 /* OmittedExpression */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: + case 220 /* YieldExpression */: + case 214 /* AwaitExpression */: + case 227 /* MetaProperty */: return true; - case 157 /* QualifiedName */: - while (node.parent.kind === 157 /* QualifiedName */) { + case 158 /* QualifiedName */: + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 176 /* TypeQuery */ || isJSXTagName(node); + return node.parent.kind === 177 /* TypeQuery */ || isJSXTagName(node); case 78 /* Identifier */: - if (node.parent.kind === 176 /* TypeQuery */ || isJSXTagName(node)) { + if (node.parent.kind === 177 /* TypeQuery */ || isJSXTagName(node)) { return true; } // falls through @@ -15263,49 +15498,49 @@ var ts; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 291 /* EnumMember */: - case 288 /* PropertyAssignment */: - case 198 /* BindingElement */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 292 /* EnumMember */: + case 289 /* PropertyAssignment */: + case 199 /* BindingElement */: return parent.initializer === node; - case 233 /* ExpressionStatement */: - case 234 /* IfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 242 /* ReturnStatement */: - case 243 /* WithStatement */: - case 244 /* SwitchStatement */: - case 284 /* CaseClause */: - case 246 /* ThrowStatement */: + case 234 /* ExpressionStatement */: + case 235 /* IfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 243 /* ReturnStatement */: + case 244 /* WithStatement */: + case 245 /* SwitchStatement */: + case 285 /* CaseClause */: + case 247 /* ThrowStatement */: return parent.expression === node; - case 237 /* ForStatement */: + case 238 /* ForStatement */: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 250 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 251 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 250 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 251 /* VariableDeclarationList */) || forInStatement.expression === node; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return node === parent.expression; - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return node === parent.expression; - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return node === parent.expression; - case 161 /* Decorator */: - case 283 /* JsxExpression */: - case 282 /* JsxSpreadAttribute */: - case 290 /* SpreadAssignment */: + case 162 /* Decorator */: + case 284 /* JsxExpression */: + case 283 /* JsxSpreadAttribute */: + case 291 /* SpreadAssignment */: return true; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return parent.objectAssignmentInitializer === node; default: return isExpressionNode(parent); @@ -15313,14 +15548,18 @@ var ts; } ts.isInExpressionContext = isInExpressionContext; function isPartOfTypeQuery(node) { - while (node.kind === 157 /* QualifiedName */ || node.kind === 78 /* Identifier */) { + while (node.kind === 158 /* QualifiedName */ || node.kind === 78 /* Identifier */) { node = node.parent; } - return node.kind === 176 /* TypeQuery */; + return node.kind === 177 /* TypeQuery */; } ts.isPartOfTypeQuery = isPartOfTypeQuery; + function isNamespaceReexportDeclaration(node) { + return ts.isNamespaceExport(node) && !!node.parent.moduleSpecifier; + } + ts.isNamespaceReexportDeclaration = isNamespaceReexportDeclaration; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 272 /* ExternalModuleReference */; + return node.kind === 261 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 273 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -15329,12 +15568,11 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function getExternalModuleRequireArgument(node) { - return isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true) - && getLeftmostAccessExpression(node.initializer).arguments[0]; + return isRequireVariableDeclaration(node) && getLeftmostAccessExpression(node.initializer).arguments[0]; } ts.getExternalModuleRequireArgument = getExternalModuleRequireArgument; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 272 /* ExternalModuleReference */; + return node.kind === 261 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 273 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJS(file) { @@ -15370,7 +15608,7 @@ var ts; } ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, requireStringLiteralLikeArgument) { - if (callExpression.kind !== 203 /* CallExpression */) { + if (callExpression.kind !== 204 /* CallExpression */) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; @@ -15384,18 +15622,21 @@ var ts; return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; - function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) { - if (node.kind === 198 /* BindingElement */) { + /** + * Returns true if the node is a VariableDeclaration initialized to a require call (see `isRequireCall`). + * This function does not test if the node is in a JavaScript file or not. + */ + function isRequireVariableDeclaration(node) { + if (node.kind === 199 /* BindingElement */) { node = node.parent.parent; } - return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), requireStringLiteralLikeArgument); + return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), /*requireStringLiteralLikeArgument*/ true); } ts.isRequireVariableDeclaration = isRequireVariableDeclaration; - function isRequireVariableStatement(node, requireStringLiteralLikeArgument) { - if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; } + function isRequireVariableStatement(node) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 - && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); }); + && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl); }); } ts.isRequireVariableStatement = isRequireVariableStatement; function isSingleOrDoubleQuote(charCode) { @@ -15467,11 +15708,11 @@ var ts; function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); - return e.kind === 208 /* FunctionExpression */ || e.kind === 209 /* ArrowFunction */ ? initializer : undefined; + return e.kind === 209 /* FunctionExpression */ || e.kind === 210 /* ArrowFunction */ ? initializer : undefined; } - if (initializer.kind === 208 /* FunctionExpression */ || - initializer.kind === 221 /* ClassExpression */ || - initializer.kind === 209 /* ArrowFunction */) { + if (initializer.kind === 209 /* FunctionExpression */ || + initializer.kind === 222 /* ClassExpression */ || + initializer.kind === 210 /* ArrowFunction */) { return initializer; } if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { @@ -15592,8 +15833,7 @@ var ts; ts.isLiteralLikeAccess = isLiteralLikeAccess; /** x[0] OR x['a'] OR x[Symbol.y] */ function isLiteralLikeElementAccess(node) { - return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) || - isWellKnownSymbolSyntactically(node.argumentExpression)); + return ts.isElementAccessExpression(node) && isStringOrNumericLiteralLike(node.argumentExpression); } ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess; /** Any series of property and element accesses. */ @@ -15673,9 +15913,6 @@ var ts; return ts.escapeLeadingUnderscores(name.text); } } - if (ts.isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) { - return getPropertyNameForKnownSymbolName(ts.idText(node.argumentExpression.name)); - } return undefined; } ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName; @@ -15725,7 +15962,7 @@ var ts; ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { return isInJSFile(expr) && - expr.parent && expr.parent.kind === 233 /* ExpressionStatement */ && + expr.parent && expr.parent.kind === 234 /* ExpressionStatement */ && (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) && !!ts.getJSDocTypeTag(expr.parent); } @@ -15746,23 +15983,37 @@ var ts; return false; } var decl = symbol.valueDeclaration; - return decl.kind === 251 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + return decl.kind === 252 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); } ts.isFunctionSymbol = isFunctionSymbol; + function tryGetModuleSpecifierFromDeclaration(node) { + var _a, _b, _c; + switch (node.kind) { + case 250 /* VariableDeclaration */: + return node.initializer.arguments[0].text; + case 262 /* ImportDeclaration */: + return (_a = ts.tryCast(node.moduleSpecifier, ts.isStringLiteralLike)) === null || _a === void 0 ? void 0 : _a.text; + case 261 /* ImportEqualsDeclaration */: + return (_c = ts.tryCast((_b = ts.tryCast(node.moduleReference, ts.isExternalModuleReference)) === null || _b === void 0 ? void 0 : _b.expression, ts.isStringLiteralLike)) === null || _c === void 0 ? void 0 : _c.text; + default: + ts.Debug.assertNever(node); + } + } + ts.tryGetModuleSpecifierFromDeclaration = tryGetModuleSpecifierFromDeclaration; function importFromModuleSpecifier(node) { return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent); } ts.importFromModuleSpecifier = importFromModuleSpecifier; function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: return node.parent; - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: return node.parent.parent; - case 203 /* CallExpression */: + case 204 /* CallExpression */: return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined; - case 191 /* LiteralType */: + case 192 /* LiteralType */: ts.Debug.assert(ts.isStringLiteral(node)); return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: @@ -15772,15 +16023,17 @@ var ts; ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: return node.moduleSpecifier; - case 260 /* ImportEqualsDeclaration */: - return node.moduleReference.kind === 272 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; - case 195 /* ImportType */: + case 261 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 273 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 196 /* ImportType */: return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; - case 203 /* CallExpression */: + case 204 /* CallExpression */: return node.arguments[0]; + case 257 /* ModuleDeclaration */: + return node.name.kind === 10 /* StringLiteral */ ? node.name : undefined; default: return ts.Debug.assertNever(node); } @@ -15788,11 +16041,11 @@ var ts; ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return node; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport); default: return ts.Debug.assertNever(node); @@ -15800,7 +16053,7 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 261 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; + return node.kind === 262 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function forEachImportClauseDeclaration(node, action) { @@ -15821,13 +16074,13 @@ var ts; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 160 /* Parameter */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 289 /* ShorthandPropertyAssignment */: - case 288 /* PropertyAssignment */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 161 /* Parameter */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 290 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -15841,7 +16094,7 @@ var ts; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 331 /* JSDocTypedefTag */ || node.kind === 324 /* JSDocCallbackTag */ || node.kind === 325 /* JSDocEnumTag */; + return node.kind === 335 /* JSDocTypedefTag */ || node.kind === 328 /* JSDocCallbackTag */ || node.kind === 329 /* JSDocEnumTag */; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -15866,12 +16119,12 @@ var ts; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: var v = getSingleVariableOfVariableStatement(node); return v && v.initializer; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return node.initializer; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return node.initializer; } } @@ -15883,7 +16136,7 @@ var ts; function getNestedModuleDeclaration(node) { return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 256 /* ModuleDeclaration */ + node.body.kind === 257 /* ModuleDeclaration */ ? node.body : undefined; } @@ -15898,11 +16151,11 @@ var ts; if (ts.hasJSDocNodes(node)) { result = ts.append(result, ts.last(node.jsDoc)); } - if (node.kind === 160 /* Parameter */) { + if (node.kind === 161 /* Parameter */) { result = ts.addRange(result, (noCache ? ts.getJSDocParameterTagsNoCache : ts.getJSDocParameterTags)(node)); break; } - if (node.kind === 159 /* TypeParameter */) { + if (node.kind === 160 /* TypeParameter */) { result = ts.addRange(result, (noCache ? ts.getJSDocTypeParameterTagsNoCache : ts.getJSDocTypeParameterTags)(node)); break; } @@ -15913,10 +16166,11 @@ var ts; ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; function getNextJSDocCommentLocation(node) { var parent = node.parent; - if (parent.kind === 288 /* PropertyAssignment */ || - parent.kind === 266 /* ExportAssignment */ || - parent.kind === 163 /* PropertyDeclaration */ || - parent.kind === 233 /* ExpressionStatement */ && node.kind === 201 /* PropertyAccessExpression */ || + if (parent.kind === 289 /* PropertyAssignment */ || + parent.kind === 267 /* ExportAssignment */ || + parent.kind === 164 /* PropertyDeclaration */ || + parent.kind === 234 /* ExpressionStatement */ && node.kind === 202 /* PropertyAccessExpression */ || + parent.kind === 243 /* ReturnStatement */ || getNestedModuleDeclaration(parent) || ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) { return parent; @@ -16003,7 +16257,7 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 309 /* JSDocVariadicType */; + return node.dotDotDotToken !== undefined || !!type && type.kind === 310 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; function hasTypeArguments(node) { @@ -16020,31 +16274,34 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? binaryOperator === 62 /* EqualsToken */ || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? 1 /* Definite */ : 2 /* Compound */ : 0 /* None */; - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: var unaryOperator = parent.operator; return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; - case 207 /* ParenthesizedExpression */: - case 199 /* ArrayLiteralExpression */: - case 220 /* SpreadElement */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 200 /* ArrayLiteralExpression */: + case 221 /* SpreadElement */: + case 226 /* NonNullExpression */: node = parent; break; - case 289 /* ShorthandPropertyAssignment */: + case 291 /* SpreadAssignment */: + node = parent.parent; + break; + case 290 /* ShorthandPropertyAssignment */: if (parent.name !== node) { return 0 /* None */; } node = parent.parent; break; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: if (parent.name === node) { return 0 /* None */; } @@ -16071,22 +16328,22 @@ var ts; */ function isNodeWithPossibleHoistedDeclaration(node) { switch (node.kind) { - case 230 /* Block */: - case 232 /* VariableStatement */: - case 243 /* WithStatement */: - case 234 /* IfStatement */: - case 244 /* SwitchStatement */: - case 258 /* CaseBlock */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: - case 245 /* LabeledStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 247 /* TryStatement */: - case 287 /* CatchClause */: + case 231 /* Block */: + case 233 /* VariableStatement */: + case 244 /* WithStatement */: + case 235 /* IfStatement */: + case 245 /* SwitchStatement */: + case 259 /* CaseBlock */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 246 /* LabeledStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 248 /* TryStatement */: + case 288 /* CatchClause */: return true; } return false; @@ -16103,11 +16360,11 @@ var ts; return node; } function walkUpParenthesizedTypes(node) { - return walkUp(node, 186 /* ParenthesizedType */); + return walkUp(node, 187 /* ParenthesizedType */); } ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; function walkUpParenthesizedExpressions(node) { - return walkUp(node, 207 /* ParenthesizedExpression */); + return walkUp(node, 208 /* ParenthesizedExpression */); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; /** @@ -16117,7 +16374,7 @@ var ts; */ function walkUpParenthesizedTypesAndGetParentAndChild(node) { var child; - while (node && node.kind === 186 /* ParenthesizedType */) { + while (node && node.kind === 187 /* ParenthesizedType */) { child = node; node = node.parent; } @@ -16129,18 +16386,18 @@ var ts; } ts.skipParentheses = skipParentheses; function skipParenthesesUp(node) { - while (node.kind === 207 /* ParenthesizedExpression */) { + while (node.kind === 208 /* 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 !== 201 /* PropertyAccessExpression */ && node.kind !== 202 /* ElementAccessExpression */) { + if (node.kind !== 202 /* PropertyAccessExpression */ && node.kind !== 203 /* ElementAccessExpression */) { return false; } node = walkUpParenthesizedExpressions(node.parent); - return node && node.kind === 210 /* DeleteExpression */; + return node && node.kind === 211 /* DeleteExpression */; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -16193,7 +16450,7 @@ var ts; ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return isStringOrNumericLiteralLike(node) && - node.parent.kind === 158 /* ComputedPropertyName */ && + node.parent.kind === 159 /* ComputedPropertyName */ && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; @@ -16201,26 +16458,26 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 291 /* EnumMember */: - case 288 /* PropertyAssignment */: - case 201 /* PropertyAccessExpression */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 292 /* EnumMember */: + case 289 /* PropertyAssignment */: + case 202 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: // Name on right hand side of dot in a type query or type reference return parent.right === node; - case 198 /* BindingElement */: - case 265 /* ImportSpecifier */: + case 199 /* BindingElement */: + case 266 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 270 /* ExportSpecifier */: - case 280 /* JsxAttribute */: + case 271 /* ExportSpecifier */: + case 281 /* JsxAttribute */: // Any name in an export specifier or JSX Attribute return true; } @@ -16240,33 +16497,33 @@ var ts; // {} // {name: } function isAliasSymbolDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ || - node.kind === 259 /* NamespaceExportDeclaration */ || - node.kind === 262 /* ImportClause */ && !!node.name || - node.kind === 263 /* NamespaceImport */ || - node.kind === 269 /* NamespaceExport */ || - node.kind === 265 /* ImportSpecifier */ || - node.kind === 270 /* ExportSpecifier */ || - node.kind === 266 /* ExportAssignment */ && exportAssignmentIsAlias(node) || + return node.kind === 261 /* ImportEqualsDeclaration */ || + node.kind === 260 /* NamespaceExportDeclaration */ || + node.kind === 263 /* ImportClause */ && !!node.name || + node.kind === 264 /* NamespaceImport */ || + node.kind === 270 /* NamespaceExport */ || + node.kind === 266 /* ImportSpecifier */ || + node.kind === 271 /* ExportSpecifier */ || + node.kind === 267 /* ExportAssignment */ && exportAssignmentIsAlias(node) || ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) || ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableExpression(node.parent.right) || - node.kind === 289 /* ShorthandPropertyAssignment */ || - node.kind === 288 /* PropertyAssignment */ && isAliasableExpression(node.initializer); + node.kind === 290 /* ShorthandPropertyAssignment */ || + node.kind === 289 /* PropertyAssignment */ && isAliasableExpression(node.initializer); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getAliasDeclarationFromName(node) { switch (node.parent.kind) { - case 262 /* ImportClause */: - case 265 /* ImportSpecifier */: - case 263 /* NamespaceImport */: - case 270 /* ExportSpecifier */: - case 266 /* ExportAssignment */: - case 260 /* ImportEqualsDeclaration */: + case 263 /* ImportClause */: + case 266 /* ImportSpecifier */: + case 264 /* NamespaceImport */: + case 271 /* ExportSpecifier */: + case 267 /* ExportAssignment */: + case 261 /* ImportEqualsDeclaration */: return node.parent; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: do { node = node.parent; - } while (node.parent.kind === 157 /* QualifiedName */); + } while (node.parent.kind === 158 /* QualifiedName */); return getAliasDeclarationFromName(node); } } @@ -16285,7 +16542,7 @@ var ts; } ts.getExportAssignmentExpression = getExportAssignmentExpression; function getPropertyAssignmentAliasLikeExpression(node) { - return node.kind === 289 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 288 /* PropertyAssignment */ ? node.initializer : + return node.kind === 290 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 289 /* PropertyAssignment */ ? node.initializer : node.parent.right; } ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression; @@ -16351,11 +16608,11 @@ var ts; } ts.getAncestor = getAncestor; function isKeyword(token) { - return 80 /* FirstKeyword */ <= token && token <= 156 /* LastKeyword */; + return 80 /* FirstKeyword */ <= token && token <= 157 /* LastKeyword */; } ts.isKeyword = isKeyword; function isContextualKeyword(token) { - return 125 /* FirstContextualKeyword */ <= token && token <= 156 /* LastContextualKeyword */; + return 125 /* FirstContextualKeyword */ <= token && token <= 157 /* LastContextualKeyword */; } ts.isContextualKeyword = isContextualKeyword; function isNonContextualKeyword(token) { @@ -16399,14 +16656,14 @@ var ts; } var flags = 0 /* Normal */; switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: if (node.asteriskToken) { flags |= 1 /* Generator */; } // falls through - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: if (hasSyntacticModifier(node, 256 /* Async */)) { flags |= 2 /* Async */; } @@ -16420,10 +16677,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: return node.body !== undefined && node.asteriskToken === undefined && hasSyntacticModifier(node, 256 /* Async */); @@ -16446,9 +16703,6 @@ var ts; * 3. The computed name is *not* expressed as a NumericLiteral. * 4. The computed name is *not* expressed as a PlusToken or MinusToken * immediately followed by a NumericLiteral. - * 5. The computed name is *not* expressed as `Symbol.`, where `` - * is a property of the Symbol constructor that denotes a built-in - * Symbol. */ function hasDynamicName(declaration) { var name = ts.getNameOfDeclaration(declaration); @@ -16456,24 +16710,14 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - if (!(name.kind === 158 /* ComputedPropertyName */ || name.kind === 202 /* ElementAccessExpression */)) { + if (!(name.kind === 159 /* ComputedPropertyName */ || name.kind === 203 /* ElementAccessExpression */)) { return false; } var expr = ts.isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression; return !isStringOrNumericLiteralLike(expr) && - !isSignedNumericLiteral(expr) && - !isWellKnownSymbolSyntactically(expr); + !isSignedNumericLiteral(expr); } ts.isDynamicName = isDynamicName; - /** - * Checks if the expression is of the form: - * Symbol.name - * where Symbol is literally the word "Symbol", and name is any identifierName - */ - function isWellKnownSymbolSyntactically(node) { - return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); - } - ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { switch (name.kind) { case 78 /* Identifier */: @@ -16482,12 +16726,9 @@ var ts; case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: var nameExpression = name.expression; - if (isWellKnownSymbolSyntactically(nameExpression)) { - return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - else if (isStringOrNumericLiteralLike(nameExpression)) { + if (isStringOrNumericLiteralLike(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); } else if (isSignedNumericLiteral(nameExpression)) { @@ -16515,21 +16756,17 @@ var ts; } ts.isPropertyNameLiteral = isPropertyNameLiteral; function getTextOfIdentifierOrLiteral(node) { - return ts.isIdentifierOrPrivateIdentifier(node) ? ts.idText(node) : node.text; + return ts.isMemberName(node) ? ts.idText(node) : node.text; } ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { - return ts.isIdentifierOrPrivateIdentifier(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text); + return ts.isMemberName(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForUniqueESSymbol(symbol) { return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName; } ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol; - function getPropertyNameForKnownSymbolName(symbolName) { - return "__@" + symbolName; - } - ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) { return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description; } @@ -16551,11 +16788,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 160 /* Parameter */; + return root.kind === 161 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 198 /* BindingElement */) { + while (node.kind === 199 /* BindingElement */) { node = node.parent.parent; } return node; @@ -16563,15 +16800,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 166 /* Constructor */ - || kind === 208 /* FunctionExpression */ - || kind === 251 /* FunctionDeclaration */ - || kind === 209 /* ArrowFunction */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 256 /* ModuleDeclaration */ - || kind === 297 /* SourceFile */; + return kind === 167 /* Constructor */ + || kind === 209 /* FunctionExpression */ + || kind === 252 /* FunctionDeclaration */ + || kind === 210 /* ArrowFunction */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 257 /* ModuleDeclaration */ + || kind === 298 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -16590,23 +16827,23 @@ var ts; })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 204 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 205 /* NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 204 /* NewExpression */: + case 205 /* NewExpression */: return hasArguments ? 0 /* Left */ : 1 /* Right */; - case 214 /* PrefixUnaryExpression */: - case 211 /* TypeOfExpression */: - case 212 /* VoidExpression */: - case 210 /* DeleteExpression */: - case 213 /* AwaitExpression */: - case 217 /* ConditionalExpression */: - case 219 /* YieldExpression */: + case 215 /* PrefixUnaryExpression */: + case 212 /* TypeOfExpression */: + case 213 /* VoidExpression */: + case 211 /* DeleteExpression */: + case 214 /* AwaitExpression */: + case 218 /* ConditionalExpression */: + case 220 /* YieldExpression */: return 1 /* Right */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (operator) { case 42 /* AsteriskAsteriskToken */: case 62 /* EqualsToken */: @@ -16633,15 +16870,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 204 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 205 /* NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 216 /* BinaryExpression */) { + if (expression.kind === 217 /* BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 214 /* PrefixUnaryExpression */ || expression.kind === 215 /* PostfixUnaryExpression */) { + else if (expression.kind === 215 /* PrefixUnaryExpression */ || expression.kind === 216 /* PostfixUnaryExpression */) { return expression.operator; } else { @@ -16820,15 +17057,15 @@ var ts; })(OperatorPrecedence = ts.OperatorPrecedence || (ts.OperatorPrecedence = {})); function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return 0 /* Comma */; - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return 1 /* Spread */; - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return 2 /* Yield */; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return 4 /* Conditional */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (operatorKind) { case 27 /* CommaToken */: return 0 /* Comma */; @@ -16853,25 +17090,26 @@ var ts; return getBinaryOperatorPrecedence(operatorKind); } // TODO: Should prefix `++` and `--` be moved to the `Update` precedence? - case 206 /* TypeAssertionExpression */: - case 225 /* NonNullExpression */: - case 214 /* PrefixUnaryExpression */: - case 211 /* TypeOfExpression */: - case 212 /* VoidExpression */: - case 210 /* DeleteExpression */: - case 213 /* AwaitExpression */: + case 207 /* TypeAssertionExpression */: + case 226 /* NonNullExpression */: + case 215 /* PrefixUnaryExpression */: + case 212 /* TypeOfExpression */: + case 213 /* VoidExpression */: + case 211 /* DeleteExpression */: + case 214 /* AwaitExpression */: return 16 /* Unary */; - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return 17 /* Update */; - case 203 /* CallExpression */: + case 204 /* CallExpression */: return 18 /* LeftHandSide */; - case 204 /* NewExpression */: + case 205 /* NewExpression */: return hasArguments ? 19 /* Member */ : 18 /* LeftHandSide */; - case 205 /* TaggedTemplateExpression */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 206 /* TaggedTemplateExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 227 /* MetaProperty */: return 19 /* Member */; - case 224 /* AsExpression */: + case 225 /* AsExpression */: return 11 /* Relational */; case 107 /* ThisKeyword */: case 105 /* SuperKeyword */: @@ -16882,19 +17120,19 @@ var ts; case 8 /* NumericLiteral */: case 9 /* BigIntLiteral */: case 10 /* StringLiteral */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 221 /* ClassExpression */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 222 /* ClassExpression */: case 13 /* RegularExpressionLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: - case 218 /* TemplateExpression */: - case 207 /* ParenthesizedExpression */: - case 222 /* OmittedExpression */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: + case 219 /* TemplateExpression */: + case 208 /* ParenthesizedExpression */: + case 223 /* OmittedExpression */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: return 20 /* Primary */; default: return -1 /* Invalid */; @@ -16950,7 +17188,7 @@ var ts; function getSemanticJsxChildren(children) { return ts.filter(children, function (i) { switch (i.kind) { - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return !!i.expression; case 11 /* JsxText */: return !i.containsOnlyTriviaWhiteSpaces; @@ -17344,11 +17582,20 @@ var ts; return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getCanonicalAbsolutePath(host, path) { + return host.getCanonicalFileName(ts.getNormalizedAbsolutePath(path, host.getCurrentDirectory())); + } function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); if (!file || file.isDeclarationFile) { return undefined; } + // If the declaration already uses a non-relative name, and is outside the common source directory, continue to use it + var specifier = getExternalModuleName(declaration); + if (specifier && ts.isStringLiteralLike(specifier) && !ts.pathIsRelative(specifier.text) && + getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ts.ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1) { + return undefined; + } return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; @@ -17432,8 +17679,8 @@ var ts; return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !host.isSourceFileFromExternalLibrary(sourceFile) && - !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) && - (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName)); + (forceDtsEmit || (!(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) && + !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName))); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -17528,10 +17775,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 167 /* GetAccessor */) { + if (accessor.kind === 168 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 168 /* SetAccessor */) { + else if (accessor.kind === 169 /* SetAccessor */) { setAccessor = accessor; } else { @@ -17551,10 +17798,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 167 /* GetAccessor */ && !getAccessor) { + if (member.kind === 168 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 168 /* SetAccessor */ && !setAccessor) { + if (member.kind === 169 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -17603,7 +17850,7 @@ var ts; ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** template tags are only available when a typedef isn't already using them */ function isNonTypeAliasTemplate(tag) { - return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 311 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 312 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); } /** * Gets the effective type annotation of the value parameter of a set accessor. If the node @@ -17826,6 +18073,18 @@ var ts; return hasSyntacticModifier(node, 32 /* Static */); } ts.hasStaticModifier = hasStaticModifier; + function hasOverrideModifier(node) { + return hasEffectiveModifier(node, 16384 /* Override */); + } + ts.hasOverrideModifier = hasOverrideModifier; + function hasAbstractModifier(node) { + return hasSyntacticModifier(node, 128 /* Abstract */); + } + ts.hasAbstractModifier = hasAbstractModifier; + function hasAmbientModifier(node) { + return hasSyntacticModifier(node, 2 /* Ambient */); + } + ts.hasAmbientModifier = hasAmbientModifier; function hasEffectiveReadonlyModifier(node) { return hasEffectiveModifier(node, 64 /* Readonly */); } @@ -17839,7 +18098,7 @@ var ts; } ts.getSelectedSyntacticModifierFlags = getSelectedSyntacticModifierFlags; function getModifierFlagsWorker(node, includeJSDoc, alwaysIncludeJSDoc) { - if (node.kind >= 0 /* FirstToken */ && node.kind <= 156 /* LastToken */) { + if (node.kind >= 0 /* FirstToken */ && node.kind <= 157 /* LastToken */) { return 0 /* None */; } if (!(node.modifierFlagsCache & 536870912 /* HasComputedFlags */)) { @@ -17884,6 +18143,8 @@ var ts; flags |= 16 /* Protected */; if (ts.getJSDocReadonlyTagNoCache(node)) flags |= 64 /* Readonly */; + if (ts.getJSDocOverrideTagNoCache(node)) + flags |= 16384 /* Override */; } if (ts.getJSDocDeprecatedTagNoCache(node)) flags |= 8192 /* Deprecated */; @@ -17936,10 +18197,15 @@ var ts; case 87 /* DefaultKeyword */: return 512 /* Default */; case 129 /* AsyncKeyword */: return 256 /* Async */; case 142 /* ReadonlyKeyword */: return 64 /* Readonly */; + case 156 /* OverrideKeyword */: return 16384 /* Override */; } return 0 /* None */; } ts.modifierToFlag = modifierToFlag; + function createModifiers(modifierFlags) { + return modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; + } + ts.createModifiers = createModifiers; function isLogicalOperator(token) { return token === 56 /* BarBarToken */ || token === 55 /* AmpersandAmpersandToken */ @@ -17982,11 +18248,15 @@ var ts; && ts.isLeftHandSideExpression(node.left); } ts.isAssignmentExpression = isAssignmentExpression; + function isLeftHandSideOfAssignment(node) { + return isAssignmentExpression(node.parent) && node.parent.left === node; + } + ts.isLeftHandSideOfAssignment = isLeftHandSideOfAssignment; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { var kind = node.left.kind; - return kind === 200 /* ObjectLiteralExpression */ - || kind === 199 /* ArrayLiteralExpression */; + return kind === 201 /* ObjectLiteralExpression */ + || kind === 200 /* ArrayLiteralExpression */; } return false; } @@ -18003,12 +18273,12 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: do { node = node.left; } while (node.kind !== 78 /* Identifier */); return node; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: do { node = node.expression; } while (node.kind !== 78 /* Identifier */); @@ -18017,9 +18287,12 @@ var ts; } ts.getFirstIdentifier = getFirstIdentifier; function isDottedName(node) { - return node.kind === 78 /* Identifier */ || node.kind === 107 /* ThisKeyword */ || node.kind === 105 /* SuperKeyword */ || - node.kind === 201 /* PropertyAccessExpression */ && isDottedName(node.expression) || - node.kind === 207 /* ParenthesizedExpression */ && isDottedName(node.expression); + return node.kind === 78 /* Identifier */ + || node.kind === 107 /* ThisKeyword */ + || node.kind === 105 /* SuperKeyword */ + || node.kind === 227 /* MetaProperty */ + || node.kind === 202 /* PropertyAccessExpression */ && isDottedName(node.expression) + || node.kind === 208 /* ParenthesizedExpression */ && isDottedName(node.expression); } ts.isDottedName = isDottedName; function isPropertyAccessEntityNameExpression(node) { @@ -18033,6 +18306,12 @@ var ts; return baseStr + "." + entityNameToString(expr.name); } } + else if (ts.isElementAccessExpression(expr)) { + var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); + if (baseStr !== undefined && ts.isPropertyName(expr.argumentExpression)) { + return baseStr + "." + getPropertyNameForPropertyNameNode(expr.argumentExpression); + } + } else if (ts.isIdentifier(expr)) { return ts.unescapeLeadingUnderscores(expr.escapedText); } @@ -18044,22 +18323,22 @@ var ts; } ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 157 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 158 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 202 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 200 /* ObjectLiteralExpression */ && + return expression.kind === 201 /* ObjectLiteralExpression */ && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 199 /* ArrayLiteralExpression */ && + return expression.kind === 200 /* ArrayLiteralExpression */ && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - if (!isExportDefaultSymbol(symbol)) + if (!isExportDefaultSymbol(symbol) || !symbol.declarations) return undefined; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; @@ -18386,8 +18665,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 255 /* EnumDeclaration */: - case 256 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 257 /* ModuleDeclaration */: return parseNode === parseNode.parent.name; } } @@ -18414,9 +18693,11 @@ var ts; return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0; } ts.getCheckFlags = getCheckFlags; - function getDeclarationModifierFlagsFromSymbol(s) { + function getDeclarationModifierFlagsFromSymbol(s, isWrite) { + if (isWrite === void 0) { isWrite = false; } if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + var declaration = (isWrite && s.declarations && ts.find(s.declarations, function (d) { return d.kind === 169 /* SetAccessor */; })) || s.valueDeclaration; + var flags = ts.getCombinedModifierFlags(declaration); return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; } if (getCheckFlags(s) & 6 /* Synthetic */) { @@ -18464,35 +18745,35 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return accessKind(parent); - case 215 /* PostfixUnaryExpression */: - case 214 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: var operator = parent.operator; return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? operatorToken.kind === 62 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() : 0 /* Read */; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); - case 288 /* PropertyAssignment */: { + case 289 /* 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 289 /* ShorthandPropertyAssignment */: + case 290 /* 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 199 /* ArrayLiteralExpression */: + case 200 /* 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 && skipParenthesesUp(parent.parent).kind === 233 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 234 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; } } function reverseAccessKind(a) { @@ -18580,7 +18861,8 @@ var ts; } ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol; function getClassLikeDeclarationOfSymbol(symbol) { - return ts.find(symbol.declarations, ts.isClassLike); + var _a; + return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isClassLike); } ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; function getObjectFlags(type) { @@ -18623,7 +18905,6 @@ var ts; ts.getLastChild = getLastChild; function addToSeen(seen, key, value) { if (value === void 0) { value = true; } - key = String(key); if (seen.has(key)) { return false; } @@ -18636,7 +18917,7 @@ var ts; } ts.isObjectTypeDeclaration = isObjectTypeDeclaration; function isTypeNodeKind(kind) { - return (kind >= 172 /* FirstTypeNode */ && kind <= 195 /* LastTypeNode */) + return (kind >= 173 /* FirstTypeNode */ && kind <= 196 /* LastTypeNode */) || kind === 128 /* AnyKeyword */ || kind === 152 /* UnknownKeyword */ || kind === 144 /* NumberKeyword */ @@ -18648,25 +18929,25 @@ var ts; || kind === 113 /* VoidKeyword */ || kind === 150 /* UndefinedKeyword */ || kind === 141 /* NeverKeyword */ - || kind === 223 /* ExpressionWithTypeArguments */ - || kind === 303 /* JSDocAllType */ - || kind === 304 /* JSDocUnknownType */ - || kind === 305 /* JSDocNullableType */ - || kind === 306 /* JSDocNonNullableType */ - || kind === 307 /* JSDocOptionalType */ - || kind === 308 /* JSDocFunctionType */ - || kind === 309 /* JSDocVariadicType */; + || kind === 224 /* ExpressionWithTypeArguments */ + || kind === 304 /* JSDocAllType */ + || kind === 305 /* JSDocUnknownType */ + || kind === 306 /* JSDocNullableType */ + || kind === 307 /* JSDocNonNullableType */ + || kind === 308 /* JSDocOptionalType */ + || kind === 309 /* JSDocFunctionType */ + || kind === 310 /* JSDocVariadicType */; } ts.isTypeNodeKind = isTypeNodeKind; function isAccessExpression(node) { - return node.kind === 201 /* PropertyAccessExpression */ || node.kind === 202 /* ElementAccessExpression */; + return node.kind === 202 /* PropertyAccessExpression */ || node.kind === 203 /* ElementAccessExpression */; } ts.isAccessExpression = isAccessExpression; function getNameOfAccessExpression(node) { - if (node.kind === 201 /* PropertyAccessExpression */) { + if (node.kind === 202 /* PropertyAccessExpression */) { return node.name; } - ts.Debug.assert(node.kind === 202 /* ElementAccessExpression */); + ts.Debug.assert(node.kind === 203 /* ElementAccessExpression */); return node.argumentExpression; } ts.getNameOfAccessExpression = getNameOfAccessExpression; @@ -18681,7 +18962,7 @@ var ts; } ts.isBundleFileTextLike = isBundleFileTextLike; function isNamedImportsOrExports(node) { - return node.kind === 264 /* NamedImports */ || node.kind === 268 /* NamedExports */; + return node.kind === 265 /* NamedImports */ || node.kind === 269 /* NamedExports */; } ts.isNamedImportsOrExports = isNamedImportsOrExports; function getLeftmostAccessExpression(expr) { @@ -18694,28 +18975,28 @@ var ts; function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: node = node.operand; continue; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: node = node.left; continue; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: node = node.condition; continue; - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: node = node.tag; continue; - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (stopAtCallExpressions) { return node; } // falls through - case 224 /* AsExpression */: - case 202 /* ElementAccessExpression */: - case 201 /* PropertyAccessExpression */: - case 225 /* NonNullExpression */: - case 336 /* PartiallyEmittedExpression */: + case 225 /* AsExpression */: + case 203 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 226 /* NonNullExpression */: + case 340 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -18734,7 +19015,7 @@ var ts; } function Type(checker, flags) { this.flags = flags; - if (ts.Debug.isDebugging || ts.tracing.isTracing()) { + if (ts.Debug.isDebugging || ts.tracing) { this.checker = checker; } } @@ -19078,6 +19359,10 @@ var ts; return !!(compilerOptions.declaration || compilerOptions.composite); } ts.getEmitDeclarations = getEmitDeclarations; + function shouldPreserveConstEnums(compilerOptions) { + return !!(compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + } + ts.shouldPreserveConstEnums = shouldPreserveConstEnums; function isIncrementalCompilation(options) { return !!(options.incremental || options.composite); } @@ -19090,6 +19375,10 @@ var ts; return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs; } ts.getAllowJSCompilerOption = getAllowJSCompilerOption; + function getUseDefineForClassFields(compilerOptions) { + return compilerOptions.useDefineForClassFields === undefined ? compilerOptions.target === 99 /* ESNext */ : compilerOptions.useDefineForClassFields; + } + ts.getUseDefineForClassFields = getUseDefineForClassFields; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { return oldOptions !== newOptions && ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); @@ -19111,7 +19400,7 @@ var ts; ts.getJSXTransformEnabled = getJSXTransformEnabled; function getJSXImplicitImportBase(compilerOptions, file) { var jsxImportSourcePragmas = file === null || file === void 0 ? void 0 : file.pragmas.get("jsximportsource"); - var jsxImportSourcePragma = ts.isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[0] : jsxImportSourcePragmas; + var jsxImportSourcePragma = ts.isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[jsxImportSourcePragmas.length - 1] : jsxImportSourcePragmas; return compilerOptions.jsx === 4 /* ReactJSX */ || compilerOptions.jsx === 5 /* ReactJSXDev */ || compilerOptions.jsxImportSource || @@ -19140,37 +19429,65 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createSymlinkCache() { + function createSymlinkCache(cwd, getCanonicalFileName) { var symlinkedDirectories; + var symlinkedDirectoriesByRealpath; var symlinkedFiles; return { getSymlinkedFiles: function () { return symlinkedFiles; }, getSymlinkedDirectories: function () { return symlinkedDirectories; }, + getSymlinkedDirectoriesByRealpath: function () { return symlinkedDirectoriesByRealpath; }, setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); }, - setSymlinkedDirectory: function (path, directory) { return (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(path, directory); }, + setSymlinkedDirectory: function (symlink, real) { + // Large, interconnected dependency graphs in pnpm will have a huge number of symlinks + // where both the realpath and the symlink path are inside node_modules/.pnpm. Since + // this path is never a candidate for a module specifier, we can ignore it entirely. + var symlinkPath = ts.toPath(symlink, cwd, getCanonicalFileName); + if (!containsIgnoredPath(symlinkPath)) { + symlinkPath = ts.ensureTrailingDirectorySeparator(symlinkPath); + if (real !== false && !(symlinkedDirectories === null || symlinkedDirectories === void 0 ? void 0 : symlinkedDirectories.has(symlinkPath))) { + (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = ts.createMultiMap())).add(ts.ensureTrailingDirectorySeparator(real.realPath), symlink); + } + (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); + } + }, + setSymlinkedDirectoryFromSymlinkedFile: function (symlink, real) { + this.setSymlinkedFile(ts.toPath(symlink, cwd, getCanonicalFileName), real); + var _a = guessDirectorySymlink(real, symlink, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _a[0], commonOriginal = _a[1]; + if (commonResolved && commonOriginal) { + this.setSymlinkedDirectory(commonOriginal, { + real: commonResolved, + realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName), + }); + } + }, }; } ts.createSymlinkCache = createSymlinkCache; function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { - var cache = createSymlinkCache(); - var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { - return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) { - return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + var cache = createSymlinkCache(cwd, getCanonicalFileName); + var symlinks = ts.flatMap(files, function (sf) { + var pairs = sf.resolvedModules && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedModules.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) ? [res.resolvedFileName, res.originalPath] : undefined; + })); + return ts.concatenate(pairs, sf.resolvedTypeReferenceDirectiveNames && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedTypeReferenceDirectiveNames.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) && res.resolvedFileName ? [res.resolvedFileName, res.originalPath] : undefined; }))); - })); + }); for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + cache.setSymlinkedFile(ts.toPath(originalPath, cwd, getCanonicalFileName), resolvedPath); var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1]; if (commonResolved && commonOriginal) { - cache.setSymlinkedDirectory(ts.toPath(commonOriginal, cwd, getCanonicalFileName), { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); + cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); } } return cache; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(a, cwd)); + var bParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(b, cwd)); var isDirectory = false; while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && @@ -19554,6 +19871,14 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + function numberOfDirectorySeparators(str) { + var match = str.match(/\//g); + return match ? match.length : 0; + } + function compareNumberOfDirectorySeparators(path1, path2) { + return ts.compareValues(numberOfDirectorySeparators(path1), numberOfDirectorySeparators(path2)); + } + ts.compareNumberOfDirectorySeparators = compareNumberOfDirectorySeparators; /** * Extension boundaries by priority. Lower numbers indicate higher priorities, and are * aligned to the offset of the highest priority extension in the @@ -19850,21 +20175,21 @@ var ts; } ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite; function typeOnlyDeclarationIsExport(typeOnlyDeclaration) { - return typeOnlyDeclaration.kind === 270 /* ExportSpecifier */; + return typeOnlyDeclaration.kind === 271 /* ExportSpecifier */; } ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport; function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) { - while (node.kind === 78 /* Identifier */ || node.kind === 201 /* PropertyAccessExpression */) { + while (node.kind === 78 /* Identifier */ || node.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - if (node.kind !== 158 /* ComputedPropertyName */) { + if (node.kind !== 159 /* ComputedPropertyName */) { return false; } if (hasSyntacticModifier(node.parent, 128 /* Abstract */)) { return true; } var containerKind = node.parent.parent.kind; - return containerKind === 253 /* InterfaceDeclaration */ || containerKind === 177 /* TypeLiteral */; + return containerKind === 254 /* InterfaceDeclaration */ || containerKind === 178 /* TypeLiteral */; } /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */ function isIdentifierInNonEmittingHeritageClause(node) { @@ -19872,16 +20197,16 @@ var ts; return false; var heritageClause = ts.findAncestor(node.parent, function (parent) { switch (parent.kind) { - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: return true; - case 201 /* PropertyAccessExpression */: - case 223 /* ExpressionWithTypeArguments */: + case 202 /* PropertyAccessExpression */: + case 224 /* ExpressionWithTypeArguments */: return false; default: return "quit"; } }); - return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 116 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 253 /* InterfaceDeclaration */; + return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 116 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 254 /* InterfaceDeclaration */; } function isIdentifierTypeReference(node) { return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName); @@ -20034,6 +20359,76 @@ var ts; } } ts.expressionResultIsUnused = expressionResultIsUnused; + function containsIgnoredPath(path) { + return ts.some(ts.ignoredPaths, function (p) { return ts.stringContains(path, p); }); + } + ts.containsIgnoredPath = containsIgnoredPath; + function getContainingNodeArray(node) { + if (!node.parent) + return undefined; + switch (node.kind) { + case 160 /* TypeParameter */: + var parent_1 = node.parent; + return parent_1.kind === 186 /* InferType */ ? undefined : parent_1.typeParameters; + case 161 /* Parameter */: + return node.parent.parameters; + case 195 /* TemplateLiteralTypeSpan */: + return node.parent.templateSpans; + case 229 /* TemplateSpan */: + return node.parent.templateSpans; + case 162 /* Decorator */: + return node.parent.decorators; + case 287 /* HeritageClause */: + return node.parent.heritageClauses; + } + var parent = node.parent; + if (ts.isJSDocTag(node)) { + return ts.isJSDocTypeLiteral(node.parent) ? undefined : node.parent.tags; + } + switch (parent.kind) { + case 178 /* TypeLiteral */: + case 254 /* InterfaceDeclaration */: + return ts.isTypeElement(node) ? parent.members : undefined; + case 183 /* UnionType */: + case 184 /* IntersectionType */: + return parent.types; + case 180 /* TupleType */: + case 200 /* ArrayLiteralExpression */: + case 341 /* CommaListExpression */: + case 265 /* NamedImports */: + case 269 /* NamedExports */: + return parent.elements; + case 201 /* ObjectLiteralExpression */: + case 282 /* JsxAttributes */: + return parent.properties; + case 204 /* CallExpression */: + case 205 /* NewExpression */: + return ts.isTypeNode(node) ? parent.typeArguments : + parent.expression === node ? undefined : + parent.arguments; + case 274 /* JsxElement */: + case 278 /* JsxFragment */: + return ts.isJsxChild(node) ? parent.children : undefined; + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + return ts.isTypeNode(node) ? parent.typeArguments : undefined; + case 231 /* Block */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 258 /* ModuleBlock */: + return parent.statements; + case 259 /* CaseBlock */: + return parent.clauses; + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + return ts.isClassElement(node) ? parent.members : undefined; + case 256 /* EnumDeclaration */: + return ts.isEnumMember(node) ? parent.members : undefined; + case 298 /* SourceFile */: + return parent.statements; + } + } + ts.getContainingNodeArray = getContainingNodeArray; })(ts || (ts = {})); /* @internal */ var ts; @@ -20078,7 +20473,11 @@ var ts; var ts; (function (ts) { function createParenthesizerRules(factory) { + var binaryLeftOperandParenthesizerCache; + var binaryRightOperandParenthesizerCache; return { + getParenthesizeLeftSideOfBinaryForOperator: getParenthesizeLeftSideOfBinaryForOperator, + getParenthesizeRightSideOfBinaryForOperator: getParenthesizeRightSideOfBinaryForOperator, parenthesizeLeftSideOfBinary: parenthesizeLeftSideOfBinary, parenthesizeRightSideOfBinary: parenthesizeRightSideOfBinary, parenthesizeExpressionOfComputedPropertyName: parenthesizeExpressionOfComputedPropertyName, @@ -20099,6 +20498,24 @@ var ts; parenthesizeConstituentTypesOfUnionOrIntersectionType: parenthesizeConstituentTypesOfUnionOrIntersectionType, parenthesizeTypeArguments: parenthesizeTypeArguments, }; + function getParenthesizeLeftSideOfBinaryForOperator(operatorKind) { + binaryLeftOperandParenthesizerCache || (binaryLeftOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeLeftSideOfBinary(operatorKind, node); }; + binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } + function getParenthesizeRightSideOfBinaryForOperator(operatorKind) { + binaryRightOperandParenthesizerCache || (binaryRightOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeRightSideOfBinary(operatorKind, /*leftSide*/ undefined, node); }; + binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } /** * Determines whether the operand to a BinaryExpression needs to be parenthesized. * @@ -20125,10 +20542,10 @@ var ts; // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - var binaryOperatorPrecedence = ts.getOperatorPrecedence(216 /* BinaryExpression */, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(216 /* BinaryExpression */, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(217 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(217 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); - if (!isLeftSideOfBinary && operand.kind === 209 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */) { + if (!isLeftSideOfBinary && operand.kind === 210 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */) { // We need to parenthesize arrow functions on the right side to avoid it being // parsed as parenthesized expression: `a && (() => {})` return true; @@ -20140,7 +20557,7 @@ var ts; // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ - && operand.kind === 219 /* YieldExpression */) { + && operand.kind === 220 /* YieldExpression */) { return false; } return true; @@ -20228,7 +20645,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) { + if (node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -20254,7 +20671,7 @@ var ts; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. - if (skipped.kind === 207 /* ParenthesizedExpression */) { + if (skipped.kind === 208 /* ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -20271,7 +20688,7 @@ var ts; return ts.isCommaSequence(expression) ? factory.createParenthesizedExpression(expression) : expression; } function parenthesizeConditionOfConditionalExpression(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(217 /* ConditionalExpression */, 57 /* QuestionToken */); + var conditionalPrecedence = ts.getOperatorPrecedence(218 /* ConditionalExpression */, 57 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) { @@ -20304,8 +20721,8 @@ var ts; var needsParens = ts.isCommaSequence(check); if (!needsParens) { switch (ts.getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: needsParens = true; } } @@ -20318,9 +20735,9 @@ var ts; function parenthesizeExpressionOfNew(expression) { var leftmostExpr = ts.getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); switch (leftmostExpr.kind) { - case 203 /* CallExpression */: + case 204 /* CallExpression */: return factory.createParenthesizedExpression(expression); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return !leftmostExpr.arguments ? factory.createParenthesizedExpression(expression) : expression; // TODO(rbuckton): Verify this assertion holds @@ -20340,7 +20757,7 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 204 /* NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 205 /* NewExpression */ || emittedExpression.arguments)) { // TODO(rbuckton): Verify whether this assertion holds. return expression; } @@ -20362,7 +20779,7 @@ var ts; function parenthesizeExpressionForDisallowedComma(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(216 /* BinaryExpression */, 27 /* CommaToken */); + var commaPrecedence = ts.getOperatorPrecedence(217 /* BinaryExpression */, 27 /* CommaToken */); // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(factory.createParenthesizedExpression(expression), expression); } @@ -20371,44 +20788,44 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 208 /* FunctionExpression */ || kind === 209 /* ArrowFunction */) { + if (kind === 209 /* FunctionExpression */ || kind === 210 /* ArrowFunction */) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. var updated = factory.updateCallExpression(emittedExpression, ts.setTextRange(factory.createParenthesizedExpression(callee), callee), emittedExpression.typeArguments, emittedExpression.arguments); return factory.restoreOuterExpressions(expression, updated, 8 /* PartiallyEmittedExpressions */); } } var leftmostExpressionKind = ts.getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; - if (leftmostExpressionKind === 200 /* ObjectLiteralExpression */ || leftmostExpressionKind === 208 /* FunctionExpression */) { + if (leftmostExpressionKind === 201 /* ObjectLiteralExpression */ || leftmostExpressionKind === 209 /* FunctionExpression */) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return ts.setTextRange(factory.createParenthesizedExpression(expression), expression); } return expression; } function parenthesizeConciseBodyOfArrowFunction(body) { - if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 200 /* ObjectLiteralExpression */)) { + if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 201 /* ObjectLiteralExpression */)) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return ts.setTextRange(factory.createParenthesizedExpression(body), body); } return body; } function parenthesizeMemberOfConditionalType(member) { - return member.kind === 184 /* ConditionalType */ ? factory.createParenthesizedType(member) : member; + return member.kind === 185 /* ConditionalType */ ? factory.createParenthesizedType(member) : member; } function parenthesizeMemberOfElementType(member) { switch (member.kind) { - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return factory.createParenthesizedType(member); } return parenthesizeMemberOfConditionalType(member); } function parenthesizeElementTypeOfArrayType(member) { switch (member.kind) { - case 176 /* TypeQuery */: - case 188 /* TypeOperator */: - case 185 /* InferType */: + case 177 /* TypeQuery */: + case 189 /* TypeOperator */: + case 186 /* InferType */: return factory.createParenthesizedType(member); } return parenthesizeMemberOfElementType(member); @@ -20427,6 +20844,8 @@ var ts; } ts.createParenthesizerRules = createParenthesizerRules; ts.nullParenthesizerRules = { + getParenthesizeLeftSideOfBinaryForOperator: function (_) { return ts.identity; }, + getParenthesizeRightSideOfBinaryForOperator: function (_) { return ts.identity; }, parenthesizeLeftSideOfBinary: function (_binaryOperator, leftSide) { return leftSide; }, parenthesizeRightSideOfBinary: function (_binaryOperator, _leftSide, rightSide) { return rightSide; }, parenthesizeExpressionOfComputedPropertyName: ts.identity, @@ -20512,11 +20931,11 @@ var ts; } function convertToAssignmentPattern(node) { switch (node.kind) { - case 197 /* ArrayBindingPattern */: - case 199 /* ArrayLiteralExpression */: + case 198 /* ArrayBindingPattern */: + case 200 /* ArrayLiteralExpression */: return convertToArrayAssignmentPattern(node); - case 196 /* ObjectBindingPattern */: - case 200 /* ObjectLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 201 /* ObjectLiteralExpression */: return convertToObjectAssignmentPattern(node); } } @@ -20857,18 +21276,18 @@ var ts; createExternalModuleReference: createExternalModuleReference, updateExternalModuleReference: updateExternalModuleReference, // lazily load factory members for JSDoc types with similar structure - get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(303 /* JSDocAllType */); }, - get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(304 /* JSDocUnknownType */); }, - get createJSDocNonNullableType() { return getJSDocUnaryTypeCreateFunction(306 /* JSDocNonNullableType */); }, - get updateJSDocNonNullableType() { return getJSDocUnaryTypeUpdateFunction(306 /* JSDocNonNullableType */); }, - get createJSDocNullableType() { return getJSDocUnaryTypeCreateFunction(305 /* JSDocNullableType */); }, - get updateJSDocNullableType() { return getJSDocUnaryTypeUpdateFunction(305 /* JSDocNullableType */); }, - get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(307 /* JSDocOptionalType */); }, - get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(307 /* JSDocOptionalType */); }, - get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(309 /* JSDocVariadicType */); }, - get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(309 /* JSDocVariadicType */); }, - get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(310 /* JSDocNamepathType */); }, - get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(310 /* JSDocNamepathType */); }, + get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(304 /* JSDocAllType */); }, + get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(305 /* JSDocUnknownType */); }, + get createJSDocNonNullableType() { return getJSDocUnaryTypeCreateFunction(307 /* JSDocNonNullableType */); }, + get updateJSDocNonNullableType() { return getJSDocUnaryTypeUpdateFunction(307 /* JSDocNonNullableType */); }, + get createJSDocNullableType() { return getJSDocUnaryTypeCreateFunction(306 /* JSDocNullableType */); }, + get updateJSDocNullableType() { return getJSDocUnaryTypeUpdateFunction(306 /* JSDocNullableType */); }, + get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(308 /* JSDocOptionalType */); }, + get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(308 /* JSDocOptionalType */); }, + get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(310 /* JSDocVariadicType */); }, + get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(310 /* JSDocVariadicType */); }, + get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(311 /* JSDocNamepathType */); }, + get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(311 /* JSDocNamepathType */); }, createJSDocFunctionType: createJSDocFunctionType, updateJSDocFunctionType: updateJSDocFunctionType, createJSDocTypeLiteral: createJSDocTypeLiteral, @@ -20895,31 +21314,37 @@ var ts; updateJSDocSeeTag: updateJSDocSeeTag, createJSDocNameReference: createJSDocNameReference, updateJSDocNameReference: updateJSDocNameReference, + createJSDocLink: createJSDocLink, + updateJSDocLink: updateJSDocLink, // lazily load factory members for JSDoc tags with similar structure - get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(329 /* JSDocTypeTag */); }, - get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(329 /* JSDocTypeTag */); }, - get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(327 /* JSDocReturnTag */); }, - get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(327 /* JSDocReturnTag */); }, - get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(328 /* JSDocThisTag */); }, - get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(328 /* JSDocThisTag */); }, - get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(325 /* JSDocEnumTag */); }, - get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(325 /* JSDocEnumTag */); }, - get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(317 /* JSDocAuthorTag */); }, - get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(317 /* JSDocAuthorTag */); }, - get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(319 /* JSDocClassTag */); }, - get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(319 /* JSDocClassTag */); }, - get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(320 /* JSDocPublicTag */); }, - get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(320 /* JSDocPublicTag */); }, - get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(321 /* JSDocPrivateTag */); }, - get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(321 /* JSDocPrivateTag */); }, - get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(322 /* JSDocProtectedTag */); }, - get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(322 /* JSDocProtectedTag */); }, - get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(323 /* JSDocReadonlyTag */); }, - get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(323 /* JSDocReadonlyTag */); }, - get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(318 /* JSDocDeprecatedTag */); }, - get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(318 /* JSDocDeprecatedTag */); }, + get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(333 /* JSDocTypeTag */); }, + get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(333 /* JSDocTypeTag */); }, + get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(331 /* JSDocReturnTag */); }, + get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(331 /* JSDocReturnTag */); }, + get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(332 /* JSDocThisTag */); }, + get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(332 /* JSDocThisTag */); }, + get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(329 /* JSDocEnumTag */); }, + get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(329 /* JSDocEnumTag */); }, + get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(320 /* JSDocAuthorTag */); }, + get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(320 /* JSDocAuthorTag */); }, + get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(322 /* JSDocClassTag */); }, + get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(322 /* JSDocClassTag */); }, + get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(323 /* JSDocPublicTag */); }, + get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(323 /* JSDocPublicTag */); }, + get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(324 /* JSDocPrivateTag */); }, + get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(324 /* JSDocPrivateTag */); }, + get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(325 /* JSDocProtectedTag */); }, + get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(325 /* JSDocProtectedTag */); }, + get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(326 /* JSDocReadonlyTag */); }, + get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(326 /* JSDocReadonlyTag */); }, + get createJSDocOverrideTag() { return getJSDocSimpleTagCreateFunction(327 /* JSDocOverrideTag */); }, + get updateJSDocOverrideTag() { return getJSDocSimpleTagUpdateFunction(327 /* JSDocOverrideTag */); }, + get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(321 /* JSDocDeprecatedTag */); }, + get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(321 /* JSDocDeprecatedTag */); }, createJSDocUnknownTag: createJSDocUnknownTag, updateJSDocUnknownTag: updateJSDocUnknownTag, + createJSDocText: createJSDocText, + updateJSDocText: updateJSDocText, createJSDocComment: createJSDocComment, updateJSDocComment: updateJSDocComment, createJsxElement: createJsxElement, @@ -21103,11 +21528,11 @@ var ts; // don't propagate child flags. if (name) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 163 /* PropertyDeclaration */: - case 288 /* PropertyAssignment */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 289 /* PropertyAssignment */: if (ts.isIdentifier(name)) { node.transformFlags |= propagateIdentifierNameFlags(name); break; @@ -21148,7 +21573,7 @@ var ts; function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) { var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type); node.body = body; - node.transformFlags |= propagateChildFlags(node.body) & ~8388608 /* ContainsPossibleTopLevelAwait */; + node.transformFlags |= propagateChildFlags(node.body) & ~16777216 /* ContainsPossibleTopLevelAwait */; if (!body) node.transformFlags |= 1 /* ContainsTypeScript */; return node; @@ -21201,7 +21626,7 @@ var ts; var node = createBaseLiteral(8 /* NumericLiteral */, typeof value === "number" ? value + "" : value); node.numericLiteralFlags = numericLiteralFlags; if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -21220,7 +21645,7 @@ var ts; var node = createBaseStringLiteral(text, isSingleQuote); node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; if (hasExtendedUnicodeEscape) - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -21276,7 +21701,7 @@ var ts; node.typeArguments = createNodeArray(typeArguments); } if (node.originalKeywordKind === 130 /* AwaitKeyword */) { - node.transformFlags |= 8388608 /* ContainsPossibleTopLevelAwait */; + node.transformFlags |= 16777216 /* ContainsPossibleTopLevelAwait */; } return node; } @@ -21299,8 +21724,11 @@ var ts; } /** Create a unique temporary variable for use in a loop. */ // @api - function createLoopVariable() { - return createBaseGeneratedIdentifier("", 2 /* Loop */); + function createLoopVariable(reservedInNestedScopes) { + var flags = 2 /* Loop */; + if (reservedInNestedScopes) + flags |= 8 /* ReservedInNestedScopes */; + return createBaseGeneratedIdentifier("", flags); } /** Create a unique name based on the supplied text. */ // @api @@ -21325,7 +21753,7 @@ var ts; ts.Debug.fail("First character of private identifier must be #: " + text); var node = baseFactory.createBasePrivateIdentifierNode(79 /* PrivateIdentifier */); node.escapedText = ts.escapeLeadingUnderscores(text); - node.transformFlags |= 4194304 /* ContainsClassFields */; + node.transformFlags |= 8388608 /* ContainsClassFields */; return node; } // @@ -21335,7 +21763,7 @@ var ts; return baseFactory.createBaseTokenNode(kind); } function createToken(token) { - ts.Debug.assert(token >= 0 /* FirstToken */ && token <= 156 /* LastToken */, "Invalid token"); + ts.Debug.assert(token >= 0 /* FirstToken */ && token <= 157 /* LastToken */, "Invalid token"); ts.Debug.assert(token <= 14 /* FirstTemplateToken */ || token >= 17 /* LastTemplateToken */, "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals."); ts.Debug.assert(token <= 8 /* FirstLiteralToken */ || token >= 14 /* LastLiteralToken */, "Invalid token. Use 'createLiteralLikeNode' to create literals."); ts.Debug.assert(token !== 78 /* Identifier */, "Invalid token. Use 'createIdentifier' to create identifiers"); @@ -21345,8 +21773,8 @@ var ts; case 129 /* AsyncKeyword */: // 'async' modifier is ES2017 (async functions) or ES2018 (async generators) transformFlags = - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */; break; case 122 /* PublicKeyword */: case 120 /* PrivateKeyword */: @@ -21360,6 +21788,7 @@ var ts; case 155 /* BigIntKeyword */: case 141 /* NeverKeyword */: case 145 /* ObjectKeyword */: + case 156 /* OverrideKeyword */: case 147 /* StringKeyword */: case 131 /* BooleanKeyword */: case 148 /* SymbolKeyword */: @@ -21370,11 +21799,11 @@ var ts; break; case 123 /* StaticKeyword */: case 105 /* SuperKeyword */: - transformFlags = 256 /* ContainsES2015 */; + transformFlags = 512 /* ContainsES2015 */; break; case 107 /* ThisKeyword */: // 'this' indicates a lexical 'this' - transformFlags = 4096 /* ContainsLexicalThis */; + transformFlags = 8192 /* ContainsLexicalThis */; break; } if (transformFlags) { @@ -21442,6 +21871,9 @@ var ts; if (flags & 32 /* Static */) { result.push(createModifier(123 /* StaticKeyword */)); } + if (flags & 16384 /* Override */) { + result.push(createModifier(156 /* OverrideKeyword */)); + } if (flags & 64 /* Readonly */) { result.push(createModifier(142 /* ReadonlyKeyword */)); } @@ -21455,7 +21887,7 @@ var ts; // // @api function createQualifiedName(left, right) { - var node = createBaseNode(157 /* QualifiedName */); + var node = createBaseNode(158 /* QualifiedName */); node.left = left; node.right = asName(right); node.transformFlags |= @@ -21472,12 +21904,12 @@ var ts; } // @api function createComputedPropertyName(expression) { - var node = createBaseNode(158 /* ComputedPropertyName */); + var node = createBaseNode(159 /* ComputedPropertyName */); node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 256 /* ContainsES2015 */ | - 32768 /* ContainsComputedPropertyName */; + 512 /* ContainsES2015 */ | + 65536 /* ContainsComputedPropertyName */; return node; } // @api @@ -21491,7 +21923,7 @@ var ts; // // @api function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createBaseNamedDeclaration(159 /* TypeParameter */, + var node = createBaseNamedDeclaration(160 /* TypeParameter */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.constraint = constraint; @@ -21509,7 +21941,7 @@ var ts; } // @api function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(160 /* Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); + var node = createBaseVariableLikeDeclaration(161 /* Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.dotDotDotToken = dotDotDotToken; node.questionToken = questionToken; if (ts.isThisIdentifier(node.name)) { @@ -21521,10 +21953,10 @@ var ts; propagateChildFlags(node.questionToken); if (questionToken) node.transformFlags |= 1 /* ContainsTypeScript */; - if (ts.modifiersToFlags(node.modifiers) & 92 /* ParameterPropertyModifier */) - node.transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */; + if (ts.modifiersToFlags(node.modifiers) & 16476 /* ParameterPropertyModifier */) + node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; if (initializer || dotDotDotToken) - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; } return node; } @@ -21542,12 +21974,12 @@ var ts; } // @api function createDecorator(expression) { - var node = createBaseNode(161 /* Decorator */); + var node = createBaseNode(162 /* Decorator */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */ | - 2048 /* ContainsTypeScriptClassSyntax */; + 4096 /* ContainsTypeScriptClassSyntax */; return node; } // @api @@ -21561,7 +21993,7 @@ var ts; // // @api function createPropertySignature(modifiers, name, questionToken, type) { - var node = createBaseNamedDeclaration(162 /* PropertySignature */, + var node = createBaseNamedDeclaration(163 /* PropertySignature */, /*decorators*/ undefined, modifiers, name); node.type = type; node.questionToken = questionToken; @@ -21579,15 +22011,15 @@ var ts; } // @api function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(163 /* PropertyDeclaration */, decorators, modifiers, name, type, initializer); + var node = createBaseVariableLikeDeclaration(164 /* PropertyDeclaration */, decorators, modifiers, name, type, initializer); node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.transformFlags |= propagateChildFlags(node.questionToken) | propagateChildFlags(node.exclamationToken) | - 4194304 /* ContainsClassFields */; + 8388608 /* ContainsClassFields */; if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) { - node.transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */; + node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) { node.transformFlags |= 1 /* ContainsTypeScript */; @@ -21608,7 +22040,7 @@ var ts; } // @api function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(164 /* MethodSignature */, + var node = createBaseSignatureDeclaration(165 /* MethodSignature */, /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type); node.questionToken = questionToken; node.transformFlags = 1 /* ContainsTypeScript */; @@ -21627,26 +22059,26 @@ var ts; } // @api function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(165 /* MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(166 /* MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.questionToken = questionToken; node.transformFlags |= propagateChildFlags(node.asteriskToken) | propagateChildFlags(node.questionToken) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (questionToken) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (asteriskToken) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } else { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } } else if (asteriskToken) { - node.transformFlags |= 512 /* ContainsGenerator */; + node.transformFlags |= 1024 /* ContainsGenerator */; } return node; } @@ -21666,11 +22098,11 @@ var ts; } // @api function createConstructorDeclaration(decorators, modifiers, parameters, body) { - var node = createBaseFunctionLikeDeclaration(166 /* Constructor */, decorators, modifiers, + var node = createBaseFunctionLikeDeclaration(167 /* Constructor */, decorators, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -21684,7 +22116,7 @@ var ts; } // @api function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) { - return createBaseFunctionLikeDeclaration(167 /* GetAccessor */, decorators, modifiers, name, + return createBaseFunctionLikeDeclaration(168 /* GetAccessor */, decorators, modifiers, name, /*typeParameters*/ undefined, parameters, type, body); } // @api @@ -21700,7 +22132,7 @@ var ts; } // @api function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) { - return createBaseFunctionLikeDeclaration(168 /* SetAccessor */, decorators, modifiers, name, + return createBaseFunctionLikeDeclaration(169 /* SetAccessor */, decorators, modifiers, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); } @@ -21716,7 +22148,7 @@ var ts; } // @api function createCallSignature(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(169 /* CallSignature */, + var node = createBaseSignatureDeclaration(170 /* CallSignature */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); @@ -21733,7 +22165,7 @@ var ts; } // @api function createConstructSignature(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(170 /* ConstructSignature */, + var node = createBaseSignatureDeclaration(171 /* ConstructSignature */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); @@ -21750,7 +22182,7 @@ var ts; } // @api function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createBaseSignatureDeclaration(171 /* IndexSignature */, decorators, modifiers, + var node = createBaseSignatureDeclaration(172 /* IndexSignature */, decorators, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21767,7 +22199,7 @@ var ts; } // @api function createTemplateLiteralTypeSpan(type, literal) { - var node = createBaseNode(194 /* TemplateLiteralTypeSpan */); + var node = createBaseNode(195 /* TemplateLiteralTypeSpan */); node.type = type; node.literal = literal; node.transformFlags = 1 /* ContainsTypeScript */; @@ -21789,7 +22221,7 @@ var ts; } // @api function createTypePredicateNode(assertsModifier, parameterName, type) { - var node = createBaseNode(172 /* TypePredicate */); + var node = createBaseNode(173 /* TypePredicate */); node.assertsModifier = assertsModifier; node.parameterName = asName(parameterName); node.type = type; @@ -21806,7 +22238,7 @@ var ts; } // @api function createTypeReferenceNode(typeName, typeArguments) { - var node = createBaseNode(173 /* TypeReference */); + var node = createBaseNode(174 /* TypeReference */); node.typeName = asName(typeName); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(createNodeArray(typeArguments)); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21821,7 +22253,7 @@ var ts; } // @api function createFunctionTypeNode(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(174 /* FunctionType */, + var node = createBaseSignatureDeclaration(175 /* FunctionType */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); @@ -21847,7 +22279,7 @@ var ts; ts.Debug.fail("Incorrect number of arguments specified."); } function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(175 /* ConstructorType */, + var node = createBaseSignatureDeclaration(176 /* ConstructorType */, /*decorators*/ undefined, modifiers, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21881,7 +22313,7 @@ var ts; } // @api function createTypeQueryNode(exprName) { - var node = createBaseNode(176 /* TypeQuery */); + var node = createBaseNode(177 /* TypeQuery */); node.exprName = exprName; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21894,7 +22326,7 @@ var ts; } // @api function createTypeLiteralNode(members) { - var node = createBaseNode(177 /* TypeLiteral */); + var node = createBaseNode(178 /* TypeLiteral */); node.members = createNodeArray(members); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21907,7 +22339,7 @@ var ts; } // @api function createArrayTypeNode(elementType) { - var node = createBaseNode(178 /* ArrayType */); + var node = createBaseNode(179 /* ArrayType */); node.elementType = parenthesizerRules().parenthesizeElementTypeOfArrayType(elementType); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21920,7 +22352,7 @@ var ts; } // @api function createTupleTypeNode(elements) { - var node = createBaseNode(179 /* TupleType */); + var node = createBaseNode(180 /* TupleType */); node.elements = createNodeArray(elements); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21933,7 +22365,7 @@ var ts; } // @api function createNamedTupleMember(dotDotDotToken, name, questionToken, type) { - var node = createBaseNode(192 /* NamedTupleMember */); + var node = createBaseNode(193 /* NamedTupleMember */); node.dotDotDotToken = dotDotDotToken; node.name = name; node.questionToken = questionToken; @@ -21952,7 +22384,7 @@ var ts; } // @api function createOptionalTypeNode(type) { - var node = createBaseNode(180 /* OptionalType */); + var node = createBaseNode(181 /* OptionalType */); node.type = parenthesizerRules().parenthesizeElementTypeOfArrayType(type); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21965,7 +22397,7 @@ var ts; } // @api function createRestTypeNode(type) { - var node = createBaseNode(181 /* RestType */); + var node = createBaseNode(182 /* RestType */); node.type = type; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21989,7 +22421,7 @@ var ts; } // @api function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(182 /* UnionType */, types); + return createUnionOrIntersectionTypeNode(183 /* UnionType */, types); } // @api function updateUnionTypeNode(node, types) { @@ -21997,7 +22429,7 @@ var ts; } // @api function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(183 /* IntersectionType */, types); + return createUnionOrIntersectionTypeNode(184 /* IntersectionType */, types); } // @api function updateIntersectionTypeNode(node, types) { @@ -22005,7 +22437,7 @@ var ts; } // @api function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { - var node = createBaseNode(184 /* ConditionalType */); + var node = createBaseNode(185 /* ConditionalType */); node.checkType = parenthesizerRules().parenthesizeMemberOfConditionalType(checkType); node.extendsType = parenthesizerRules().parenthesizeMemberOfConditionalType(extendsType); node.trueType = trueType; @@ -22024,7 +22456,7 @@ var ts; } // @api function createInferTypeNode(typeParameter) { - var node = createBaseNode(185 /* InferType */); + var node = createBaseNode(186 /* InferType */); node.typeParameter = typeParameter; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -22037,7 +22469,7 @@ var ts; } // @api function createTemplateLiteralType(head, templateSpans) { - var node = createBaseNode(193 /* TemplateLiteralType */); + var node = createBaseNode(194 /* TemplateLiteralType */); node.head = head; node.templateSpans = createNodeArray(templateSpans); node.transformFlags = 1 /* ContainsTypeScript */; @@ -22053,7 +22485,7 @@ var ts; // @api function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { if (isTypeOf === void 0) { isTypeOf = false; } - var node = createBaseNode(195 /* ImportType */); + var node = createBaseNode(196 /* ImportType */); node.argument = argument; node.qualifier = qualifier; node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); @@ -22073,7 +22505,7 @@ var ts; } // @api function createParenthesizedType(type) { - var node = createBaseNode(186 /* ParenthesizedType */); + var node = createBaseNode(187 /* ParenthesizedType */); node.type = type; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -22086,13 +22518,13 @@ var ts; } // @api function createThisTypeNode() { - var node = createBaseNode(187 /* ThisType */); + var node = createBaseNode(188 /* ThisType */); node.transformFlags = 1 /* ContainsTypeScript */; return node; } // @api function createTypeOperatorNode(operator, type) { - var node = createBaseNode(188 /* TypeOperator */); + var node = createBaseNode(189 /* TypeOperator */); node.operator = operator; node.type = parenthesizerRules().parenthesizeMemberOfElementType(type); node.transformFlags = 1 /* ContainsTypeScript */; @@ -22106,7 +22538,7 @@ var ts; } // @api function createIndexedAccessTypeNode(objectType, indexType) { - var node = createBaseNode(189 /* IndexedAccessType */); + var node = createBaseNode(190 /* IndexedAccessType */); node.objectType = parenthesizerRules().parenthesizeMemberOfElementType(objectType); node.indexType = indexType; node.transformFlags = 1 /* ContainsTypeScript */; @@ -22121,7 +22553,7 @@ var ts; } // @api function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type) { - var node = createBaseNode(190 /* MappedType */); + var node = createBaseNode(191 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.nameType = nameType; @@ -22142,7 +22574,7 @@ var ts; } // @api function createLiteralTypeNode(literal) { - var node = createBaseNode(191 /* LiteralType */); + var node = createBaseNode(192 /* LiteralType */); node.literal = literal; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -22158,16 +22590,16 @@ var ts; // // @api function createObjectBindingPattern(elements) { - var node = createBaseNode(196 /* ObjectBindingPattern */); + var node = createBaseNode(197 /* ObjectBindingPattern */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | - 256 /* ContainsES2015 */ | - 131072 /* ContainsBindingPattern */; - if (node.transformFlags & 8192 /* ContainsRestOrSpread */) { + 512 /* ContainsES2015 */ | + 262144 /* ContainsBindingPattern */; + if (node.transformFlags & 16384 /* ContainsRestOrSpread */) { node.transformFlags |= - 32 /* ContainsES2018 */ | - 16384 /* ContainsObjectRestOrSpread */; + 64 /* ContainsES2018 */ | + 32768 /* ContainsObjectRestOrSpread */; } return node; } @@ -22179,12 +22611,12 @@ var ts; } // @api function createArrayBindingPattern(elements) { - var node = createBaseNode(197 /* ArrayBindingPattern */); + var node = createBaseNode(198 /* ArrayBindingPattern */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | - 256 /* ContainsES2015 */ | - 131072 /* ContainsBindingPattern */; + 512 /* ContainsES2015 */ | + 262144 /* ContainsBindingPattern */; return node; } // @api @@ -22195,21 +22627,21 @@ var ts; } // @api function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createBaseBindingLikeDeclaration(198 /* BindingElement */, + var node = createBaseBindingLikeDeclaration(199 /* BindingElement */, /*decorators*/ undefined, - /*modifiers*/ undefined, name, initializer); + /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; node.transformFlags |= propagateChildFlags(node.dotDotDotToken) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (node.propertyName) { node.transformFlags |= ts.isIdentifier(node.propertyName) ? propagateIdentifierNameFlags(node.propertyName) : propagateChildFlags(node.propertyName); } if (dotDotDotToken) - node.transformFlags |= 8192 /* ContainsRestOrSpread */; + node.transformFlags |= 16384 /* ContainsRestOrSpread */; return node; } // @api @@ -22231,7 +22663,7 @@ var ts; } // @api function createArrayLiteralExpression(elements, multiLine) { - var node = createBaseExpression(199 /* ArrayLiteralExpression */); + var node = createBaseExpression(200 /* ArrayLiteralExpression */); node.elements = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(elements)); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.elements); @@ -22245,7 +22677,7 @@ var ts; } // @api function createObjectLiteralExpression(properties, multiLine) { - var node = createBaseExpression(200 /* ObjectLiteralExpression */); + var node = createBaseExpression(201 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.properties); @@ -22259,7 +22691,7 @@ var ts; } // @api function createPropertyAccessExpression(expression, name) { - var node = createBaseExpression(201 /* PropertyAccessExpression */); + var node = createBaseExpression(202 /* PropertyAccessExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.name = asName(name); node.transformFlags = @@ -22271,8 +22703,8 @@ var ts; // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators node.transformFlags |= - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */; } return node; } @@ -22288,13 +22720,13 @@ var ts; } // @api function createPropertyAccessChain(expression, questionDotToken, name) { - var node = createBaseExpression(201 /* PropertyAccessExpression */); + var node = createBaseExpression(202 /* PropertyAccessExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.questionDotToken = questionDotToken; node.name = asName(name); node.transformFlags |= - 8 /* ContainsES2020 */ | + 16 /* ContainsES2020 */ | propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | (ts.isIdentifier(node.name) ? @@ -22315,7 +22747,7 @@ var ts; } // @api function createElementAccessExpression(expression, index) { - var node = createBaseExpression(202 /* ElementAccessExpression */); + var node = createBaseExpression(203 /* ElementAccessExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.argumentExpression = asExpression(index); node.transformFlags |= @@ -22325,8 +22757,8 @@ var ts; // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators node.transformFlags |= - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */; } return node; } @@ -22342,7 +22774,7 @@ var ts; } // @api function createElementAccessChain(expression, questionDotToken, index) { - var node = createBaseExpression(202 /* ElementAccessExpression */); + var node = createBaseExpression(203 /* ElementAccessExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.questionDotToken = questionDotToken; @@ -22351,7 +22783,7 @@ var ts; propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | propagateChildFlags(node.argumentExpression) | - 8 /* ContainsES2020 */; + 16 /* ContainsES2020 */; return node; } // @api @@ -22367,7 +22799,7 @@ var ts; } // @api function createCallExpression(expression, typeArguments, argumentsArray) { - var node = createBaseExpression(203 /* CallExpression */); + var node = createBaseExpression(204 /* CallExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); @@ -22379,10 +22811,10 @@ var ts; node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.isImportKeyword(node.expression)) { - node.transformFlags |= 2097152 /* ContainsDynamicImport */; + node.transformFlags |= 4194304 /* ContainsDynamicImport */; } else if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 4096 /* ContainsLexicalThis */; + node.transformFlags |= 8192 /* ContainsLexicalThis */; } return node; } @@ -22399,7 +22831,7 @@ var ts; } // @api function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) { - var node = createBaseExpression(203 /* CallExpression */); + var node = createBaseExpression(204 /* CallExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.questionDotToken = questionDotToken; @@ -22410,12 +22842,12 @@ var ts; propagateChildFlags(node.questionDotToken) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | - 8 /* ContainsES2020 */; + 16 /* ContainsES2020 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 4096 /* ContainsLexicalThis */; + node.transformFlags |= 8192 /* ContainsLexicalThis */; } return node; } @@ -22431,7 +22863,7 @@ var ts; } // @api function createNewExpression(expression, typeArguments, argumentsArray) { - var node = createBaseExpression(204 /* NewExpression */); + var node = createBaseExpression(205 /* NewExpression */); node.expression = parenthesizerRules().parenthesizeExpressionOfNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(argumentsArray) : undefined; @@ -22439,7 +22871,7 @@ var ts; propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | - 8 /* ContainsES2020 */; + 16 /* ContainsES2020 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } @@ -22455,7 +22887,7 @@ var ts; } // @api function createTaggedTemplateExpression(tag, typeArguments, template) { - var node = createBaseExpression(205 /* TaggedTemplateExpression */); + var node = createBaseExpression(206 /* TaggedTemplateExpression */); node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag); node.typeArguments = asNodeArray(typeArguments); node.template = template; @@ -22463,12 +22895,12 @@ var ts; propagateChildFlags(node.tag) | propagateChildrenFlags(node.typeArguments) | propagateChildFlags(node.template) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.hasInvalidEscape(node.template)) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } return node; } @@ -22482,7 +22914,7 @@ var ts; } // @api function createTypeAssertion(type, expression) { - var node = createBaseExpression(206 /* TypeAssertionExpression */); + var node = createBaseExpression(207 /* TypeAssertionExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.type = type; node.transformFlags |= @@ -22500,7 +22932,7 @@ var ts; } // @api function createParenthesizedExpression(expression) { - var node = createBaseExpression(207 /* ParenthesizedExpression */); + var node = createBaseExpression(208 /* ParenthesizedExpression */); node.expression = expression; node.transformFlags = propagateChildFlags(node.expression); return node; @@ -22513,7 +22945,7 @@ var ts; } // @api function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(208 /* FunctionExpression */, + var node = createBaseFunctionLikeDeclaration(209 /* FunctionExpression */, /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.asteriskToken); @@ -22522,14 +22954,14 @@ var ts; } if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (node.asteriskToken) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } else { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } } else if (node.asteriskToken) { - node.transformFlags |= 512 /* ContainsGenerator */; + node.transformFlags |= 1024 /* ContainsGenerator */; } return node; } @@ -22547,15 +22979,15 @@ var ts; } // @api function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createBaseFunctionLikeDeclaration(209 /* ArrowFunction */, + var node = createBaseFunctionLikeDeclaration(210 /* ArrowFunction */, /*decorators*/ undefined, modifiers, /*name*/ undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body)); node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* EqualsGreaterThanToken */); node.transformFlags |= propagateChildFlags(node.equalsGreaterThanToken) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } return node; } @@ -22572,7 +23004,7 @@ var ts; } // @api function createDeleteExpression(expression) { - var node = createBaseExpression(210 /* DeleteExpression */); + var node = createBaseExpression(211 /* DeleteExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -22585,7 +23017,7 @@ var ts; } // @api function createTypeOfExpression(expression) { - var node = createBaseExpression(211 /* TypeOfExpression */); + var node = createBaseExpression(212 /* TypeOfExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -22598,7 +23030,7 @@ var ts; } // @api function createVoidExpression(expression) { - var node = createBaseExpression(212 /* VoidExpression */); + var node = createBaseExpression(213 /* VoidExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -22611,13 +23043,13 @@ var ts; } // @api function createAwaitExpression(expression) { - var node = createBaseExpression(213 /* AwaitExpression */); + var node = createBaseExpression(214 /* AwaitExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */ | - 524288 /* ContainsAwait */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */ | + 1048576 /* ContainsAwait */; return node; } // @api @@ -22628,7 +23060,7 @@ var ts; } // @api function createPrefixUnaryExpression(operator, operand) { - var node = createBaseExpression(214 /* PrefixUnaryExpression */); + var node = createBaseExpression(215 /* PrefixUnaryExpression */); node.operator = operator; node.operand = parenthesizerRules().parenthesizeOperandOfPrefixUnary(operand); node.transformFlags |= propagateChildFlags(node.operand); @@ -22642,7 +23074,7 @@ var ts; } // @api function createPostfixUnaryExpression(operand, operator) { - var node = createBaseExpression(215 /* PostfixUnaryExpression */); + var node = createBaseExpression(216 /* PostfixUnaryExpression */); node.operator = operator; node.operand = parenthesizerRules().parenthesizeOperandOfPostfixUnary(operand); node.transformFlags = propagateChildFlags(node.operand); @@ -22656,7 +23088,7 @@ var ts; } // @api function createBinaryExpression(left, operator, right) { - var node = createBaseExpression(216 /* BinaryExpression */); + var node = createBaseExpression(217 /* BinaryExpression */); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = parenthesizerRules().parenthesizeLeftSideOfBinary(operatorKind, left); @@ -22667,45 +23099,45 @@ var ts; propagateChildFlags(node.operatorToken) | propagateChildFlags(node.right); if (operatorKind === 60 /* QuestionQuestionToken */) { - node.transformFlags |= 8 /* ContainsES2020 */; + node.transformFlags |= 16 /* ContainsES2020 */; } else if (operatorKind === 62 /* EqualsToken */) { if (ts.isObjectLiteralExpression(node.left)) { node.transformFlags |= - 256 /* ContainsES2015 */ | - 32 /* ContainsES2018 */ | - 1024 /* ContainsDestructuringAssignment */ | + 512 /* ContainsES2015 */ | + 64 /* ContainsES2018 */ | + 2048 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left); } else if (ts.isArrayLiteralExpression(node.left)) { node.transformFlags |= - 256 /* ContainsES2015 */ | - 1024 /* ContainsDestructuringAssignment */ | + 512 /* ContainsES2015 */ | + 2048 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left); } } else if (operatorKind === 42 /* AsteriskAsteriskToken */ || operatorKind === 66 /* AsteriskAsteriskEqualsToken */) { - node.transformFlags |= 128 /* ContainsES2016 */; + node.transformFlags |= 256 /* ContainsES2016 */; } else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) { - node.transformFlags |= 4 /* ContainsESNext */; + node.transformFlags |= 8 /* ContainsES2021 */; } return node; } function propagateAssignmentPatternFlags(node) { - if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) - return 16384 /* ContainsObjectRestOrSpread */; - if (node.transformFlags & 32 /* ContainsES2018 */) { + if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) + return 32768 /* ContainsObjectRestOrSpread */; + if (node.transformFlags & 64 /* ContainsES2018 */) { // check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c' // will not be correctly interpreted by the ES2018 transformer for (var _i = 0, _a = ts.getElementsOfBindingOrAssignmentPattern(node); _i < _a.length; _i++) { var element = _a[_i]; var target = ts.getTargetOfBindingOrAssignmentElement(element); if (target && ts.isAssignmentPattern(target)) { - if (target.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { - return 16384 /* ContainsObjectRestOrSpread */; + if (target.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { + return 32768 /* ContainsObjectRestOrSpread */; } - if (target.transformFlags & 32 /* ContainsES2018 */) { + if (target.transformFlags & 64 /* ContainsES2018 */) { var flags_1 = propagateAssignmentPatternFlags(target); if (flags_1) return flags_1; @@ -22725,7 +23157,7 @@ var ts; } // @api function createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse) { - var node = createBaseExpression(217 /* ConditionalExpression */); + var node = createBaseExpression(218 /* ConditionalExpression */); node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression(condition); node.questionToken = questionToken !== null && questionToken !== void 0 ? questionToken : createToken(57 /* QuestionToken */); node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue); @@ -22751,13 +23183,13 @@ var ts; } // @api function createTemplateExpression(head, templateSpans) { - var node = createBaseExpression(218 /* TemplateExpression */); + var node = createBaseExpression(219 /* TemplateExpression */); node.head = head; node.templateSpans = createNodeArray(templateSpans); node.transformFlags |= propagateChildFlags(node.head) | propagateChildrenFlags(node.templateSpans) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } // @api @@ -22796,9 +23228,9 @@ var ts; node.text = text; node.rawText = rawText; node.templateFlags = templateFlags & 2048 /* TemplateLiteralLikeFlags */; - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; if (node.templateFlags) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } return node; } @@ -22821,15 +23253,15 @@ var ts; // @api function createYieldExpression(asteriskToken, expression) { ts.Debug.assert(!asteriskToken || !!expression, "A `YieldExpression` with an asteriskToken must have an expression."); - var node = createBaseExpression(219 /* YieldExpression */); + var node = createBaseExpression(220 /* YieldExpression */); node.expression = expression && parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.asteriskToken) | - 256 /* ContainsES2015 */ | - 32 /* ContainsES2018 */ | - 262144 /* ContainsYield */; + 512 /* ContainsES2015 */ | + 64 /* ContainsES2018 */ | + 524288 /* ContainsYield */; return node; } // @api @@ -22841,12 +23273,12 @@ var ts; } // @api function createSpreadElement(expression) { - var node = createBaseExpression(220 /* SpreadElement */); + var node = createBaseExpression(221 /* SpreadElement */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 256 /* ContainsES2015 */ | - 8192 /* ContainsRestOrSpread */; + 512 /* ContainsES2015 */ | + 16384 /* ContainsRestOrSpread */; return node; } // @api @@ -22857,8 +23289,8 @@ var ts; } // @api function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(221 /* ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members); - node.transformFlags |= 256 /* ContainsES2015 */; + var node = createBaseClassLikeDeclaration(222 /* ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members); + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -22874,17 +23306,17 @@ var ts; } // @api function createOmittedExpression() { - return createBaseExpression(222 /* OmittedExpression */); + return createBaseExpression(223 /* OmittedExpression */); } // @api function createExpressionWithTypeArguments(expression, typeArguments) { - var node = createBaseNode(223 /* ExpressionWithTypeArguments */); + var node = createBaseNode(224 /* ExpressionWithTypeArguments */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } // @api @@ -22896,7 +23328,7 @@ var ts; } // @api function createAsExpression(expression, type) { - var node = createBaseExpression(224 /* AsExpression */); + var node = createBaseExpression(225 /* AsExpression */); node.expression = expression; node.type = type; node.transformFlags |= @@ -22914,7 +23346,7 @@ var ts; } // @api function createNonNullExpression(expression) { - var node = createBaseExpression(225 /* NonNullExpression */); + var node = createBaseExpression(226 /* NonNullExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.transformFlags |= propagateChildFlags(node.expression) | @@ -22932,7 +23364,7 @@ var ts; } // @api function createNonNullChain(expression) { - var node = createBaseExpression(225 /* NonNullExpression */); + var node = createBaseExpression(226 /* NonNullExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.transformFlags |= @@ -22949,13 +23381,13 @@ var ts; } // @api function createMetaProperty(keywordToken, name) { - var node = createBaseExpression(226 /* MetaProperty */); + var node = createBaseExpression(227 /* MetaProperty */); node.keywordToken = keywordToken; node.name = name; node.transformFlags |= propagateChildFlags(node.name); switch (keywordToken) { case 102 /* NewKeyword */: - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; break; case 99 /* ImportKeyword */: node.transformFlags |= 4 /* ContainsESNext */; @@ -22976,13 +23408,13 @@ var ts; // // @api function createTemplateSpan(expression, literal) { - var node = createBaseNode(228 /* TemplateSpan */); + var node = createBaseNode(229 /* TemplateSpan */); node.expression = expression; node.literal = literal; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.literal) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } // @api @@ -22994,8 +23426,8 @@ var ts; } // @api function createSemicolonClassElement() { - var node = createBaseNode(229 /* SemicolonClassElement */); - node.transformFlags |= 256 /* ContainsES2015 */; + var node = createBaseNode(230 /* SemicolonClassElement */); + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @@ -23003,7 +23435,7 @@ var ts; // // @api function createBlock(statements, multiLine) { - var node = createBaseNode(230 /* Block */); + var node = createBaseNode(231 /* Block */); node.statements = createNodeArray(statements); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.statements); @@ -23017,7 +23449,7 @@ var ts; } // @api function createVariableStatement(modifiers, declarationList) { - var node = createBaseDeclaration(232 /* VariableStatement */, /*decorators*/ undefined, modifiers); + var node = createBaseDeclaration(233 /* VariableStatement */, /*decorators*/ undefined, modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; node.transformFlags |= propagateChildFlags(node.declarationList); @@ -23035,11 +23467,11 @@ var ts; } // @api function createEmptyStatement() { - return createBaseNode(231 /* EmptyStatement */); + return createBaseNode(232 /* EmptyStatement */); } // @api function createExpressionStatement(expression) { - var node = createBaseNode(233 /* ExpressionStatement */); + var node = createBaseNode(234 /* ExpressionStatement */); node.expression = parenthesizerRules().parenthesizeExpressionOfExpressionStatement(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -23052,7 +23484,7 @@ var ts; } // @api function createIfStatement(expression, thenStatement, elseStatement) { - var node = createBaseNode(234 /* IfStatement */); + var node = createBaseNode(235 /* IfStatement */); node.expression = expression; node.thenStatement = asEmbeddedStatement(thenStatement); node.elseStatement = asEmbeddedStatement(elseStatement); @@ -23072,7 +23504,7 @@ var ts; } // @api function createDoStatement(statement, expression) { - var node = createBaseNode(235 /* DoStatement */); + var node = createBaseNode(236 /* DoStatement */); node.statement = asEmbeddedStatement(statement); node.expression = expression; node.transformFlags |= @@ -23089,7 +23521,7 @@ var ts; } // @api function createWhileStatement(expression, statement) { - var node = createBaseNode(236 /* WhileStatement */); + var node = createBaseNode(237 /* WhileStatement */); node.expression = expression; node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -23106,7 +23538,7 @@ var ts; } // @api function createForStatement(initializer, condition, incrementor, statement) { - var node = createBaseNode(237 /* ForStatement */); + var node = createBaseNode(238 /* ForStatement */); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -23129,7 +23561,7 @@ var ts; } // @api function createForInStatement(initializer, expression, statement) { - var node = createBaseNode(238 /* ForInStatement */); + var node = createBaseNode(239 /* ForInStatement */); node.initializer = initializer; node.expression = expression; node.statement = asEmbeddedStatement(statement); @@ -23149,7 +23581,7 @@ var ts; } // @api function createForOfStatement(awaitModifier, initializer, expression, statement) { - var node = createBaseNode(239 /* ForOfStatement */); + var node = createBaseNode(240 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); @@ -23159,9 +23591,9 @@ var ts; propagateChildFlags(node.initializer) | propagateChildFlags(node.expression) | propagateChildFlags(node.statement) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (awaitModifier) - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; return node; } // @api @@ -23175,11 +23607,11 @@ var ts; } // @api function createContinueStatement(label) { - var node = createBaseNode(240 /* ContinueStatement */); + var node = createBaseNode(241 /* ContinueStatement */); node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -23190,11 +23622,11 @@ var ts; } // @api function createBreakStatement(label) { - var node = createBaseNode(241 /* BreakStatement */); + var node = createBaseNode(242 /* BreakStatement */); node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -23205,13 +23637,13 @@ var ts; } // @api function createReturnStatement(expression) { - var node = createBaseNode(242 /* ReturnStatement */); + var node = createBaseNode(243 /* ReturnStatement */); node.expression = expression; // return in an ES2018 async generator must be awaited node.transformFlags |= propagateChildFlags(node.expression) | - 32 /* ContainsES2018 */ | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 64 /* ContainsES2018 */ | + 2097152 /* ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -23222,7 +23654,7 @@ var ts; } // @api function createWithStatement(expression, statement) { - var node = createBaseNode(243 /* WithStatement */); + var node = createBaseNode(244 /* WithStatement */); node.expression = expression; node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -23239,7 +23671,7 @@ var ts; } // @api function createSwitchStatement(expression, caseBlock) { - var node = createBaseNode(244 /* SwitchStatement */); + var node = createBaseNode(245 /* SwitchStatement */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.caseBlock = caseBlock; node.transformFlags |= @@ -23256,7 +23688,7 @@ var ts; } // @api function createLabeledStatement(label, statement) { - var node = createBaseNode(245 /* LabeledStatement */); + var node = createBaseNode(246 /* LabeledStatement */); node.label = asName(label); node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -23273,7 +23705,7 @@ var ts; } // @api function createThrowStatement(expression) { - var node = createBaseNode(246 /* ThrowStatement */); + var node = createBaseNode(247 /* ThrowStatement */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -23286,7 +23718,7 @@ var ts; } // @api function createTryStatement(tryBlock, catchClause, finallyBlock) { - var node = createBaseNode(247 /* TryStatement */); + var node = createBaseNode(248 /* TryStatement */); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -23306,11 +23738,11 @@ var ts; } // @api function createDebuggerStatement() { - return createBaseNode(248 /* DebuggerStatement */); + return createBaseNode(249 /* DebuggerStatement */); } // @api function createVariableDeclaration(name, exclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(249 /* VariableDeclaration */, + var node = createBaseVariableLikeDeclaration(250 /* VariableDeclaration */, /*decorators*/ undefined, /*modifiers*/ undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.exclamationToken = exclamationToken; @@ -23332,16 +23764,16 @@ var ts; // @api function createVariableDeclarationList(declarations, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createBaseNode(250 /* VariableDeclarationList */); + var node = createBaseNode(251 /* VariableDeclarationList */); node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); node.transformFlags |= propagateChildrenFlags(node.declarations) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; if (flags & 3 /* BlockScoped */) { node.transformFlags |= - 256 /* ContainsES2015 */ | - 65536 /* ContainsBlockScopedBinding */; + 512 /* ContainsES2015 */ | + 131072 /* ContainsBlockScopedBinding */; } return node; } @@ -23353,7 +23785,7 @@ var ts; } // @api function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(251 /* FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(252 /* FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; if (!node.body || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) { node.transformFlags = 1 /* ContainsTypeScript */; @@ -23361,17 +23793,17 @@ var ts; else { node.transformFlags |= propagateChildFlags(node.asteriskToken) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (node.asteriskToken) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } else { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } } else if (node.asteriskToken) { - node.transformFlags |= 512 /* ContainsGenerator */; + node.transformFlags |= 1024 /* ContainsGenerator */; } } return node; @@ -23391,13 +23823,13 @@ var ts; } // @api function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(252 /* ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members); + var node = createBaseClassLikeDeclaration(253 /* ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members); if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) { node.transformFlags = 1 /* ContainsTypeScript */; } else { - node.transformFlags |= 256 /* ContainsES2015 */; - if (node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */) { + node.transformFlags |= 512 /* ContainsES2015 */; + if (node.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */) { node.transformFlags |= 1 /* ContainsTypeScript */; } } @@ -23416,7 +23848,7 @@ var ts; } // @api function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(253 /* InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses); + var node = createBaseInterfaceOrClassLikeDeclaration(254 /* InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -23434,7 +23866,7 @@ var ts; } // @api function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createBaseGenericNamedDeclaration(254 /* TypeAliasDeclaration */, decorators, modifiers, name, typeParameters); + var node = createBaseGenericNamedDeclaration(255 /* TypeAliasDeclaration */, decorators, modifiers, name, typeParameters); node.type = type; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -23451,12 +23883,12 @@ var ts; } // @api function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createBaseNamedDeclaration(255 /* EnumDeclaration */, decorators, modifiers, name); + var node = createBaseNamedDeclaration(256 /* EnumDeclaration */, decorators, modifiers, name); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members) | 1 /* ContainsTypeScript */; - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` return node; } // @api @@ -23471,7 +23903,7 @@ var ts; // @api function createModuleDeclaration(decorators, modifiers, name, body, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createBaseDeclaration(256 /* ModuleDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(257 /* ModuleDeclaration */, decorators, modifiers); node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 1024 /* GlobalAugmentation */); node.name = name; node.body = body; @@ -23484,7 +23916,7 @@ var ts; propagateChildFlags(node.body) | 1 /* ContainsTypeScript */; } - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. return node; } // @api @@ -23498,7 +23930,7 @@ var ts; } // @api function createModuleBlock(statements) { - var node = createBaseNode(257 /* ModuleBlock */); + var node = createBaseNode(258 /* ModuleBlock */); node.statements = createNodeArray(statements); node.transformFlags |= propagateChildrenFlags(node.statements); return node; @@ -23511,7 +23943,7 @@ var ts; } // @api function createCaseBlock(clauses) { - var node = createBaseNode(258 /* CaseBlock */); + var node = createBaseNode(259 /* CaseBlock */); node.clauses = createNodeArray(clauses); node.transformFlags |= propagateChildrenFlags(node.clauses); return node; @@ -23524,7 +23956,7 @@ var ts; } // @api function createNamespaceExportDeclaration(name) { - var node = createBaseNamedDeclaration(259 /* NamespaceExportDeclaration */, + var node = createBaseNamedDeclaration(260 /* NamespaceExportDeclaration */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.transformFlags = 1 /* ContainsTypeScript */; @@ -23538,13 +23970,13 @@ var ts; } // @api function createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference) { - var node = createBaseNamedDeclaration(260 /* ImportEqualsDeclaration */, decorators, modifiers, name); + var node = createBaseNamedDeclaration(261 /* ImportEqualsDeclaration */, decorators, modifiers, name); node.isTypeOnly = isTypeOnly; node.moduleReference = moduleReference; node.transformFlags |= propagateChildFlags(node.moduleReference); if (!ts.isExternalModuleReference(node.moduleReference)) node.transformFlags |= 1 /* ContainsTypeScript */; - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context return node; } // @api @@ -23559,13 +23991,13 @@ var ts; } // @api function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createBaseDeclaration(261 /* ImportDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(262 /* ImportDeclaration */, decorators, modifiers); node.importClause = importClause; node.moduleSpecifier = moduleSpecifier; node.transformFlags |= propagateChildFlags(node.importClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23579,7 +24011,7 @@ var ts; } // @api function createImportClause(isTypeOnly, name, namedBindings) { - var node = createBaseNode(262 /* ImportClause */); + var node = createBaseNode(263 /* ImportClause */); node.isTypeOnly = isTypeOnly; node.name = name; node.namedBindings = namedBindings; @@ -23589,7 +24021,7 @@ var ts; if (isTypeOnly) { node.transformFlags |= 1 /* ContainsTypeScript */; } - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23602,10 +24034,10 @@ var ts; } // @api function createNamespaceImport(name) { - var node = createBaseNode(263 /* NamespaceImport */); + var node = createBaseNode(264 /* NamespaceImport */); node.name = name; node.transformFlags |= propagateChildFlags(node.name); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23616,12 +24048,12 @@ var ts; } // @api function createNamespaceExport(name) { - var node = createBaseNode(269 /* NamespaceExport */); + var node = createBaseNode(270 /* NamespaceExport */); node.name = name; node.transformFlags |= propagateChildFlags(node.name) | 4 /* ContainsESNext */; - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23632,10 +24064,10 @@ var ts; } // @api function createNamedImports(elements) { - var node = createBaseNode(264 /* NamedImports */); + var node = createBaseNode(265 /* NamedImports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23646,13 +24078,13 @@ var ts; } // @api function createImportSpecifier(propertyName, name) { - var node = createBaseNode(265 /* ImportSpecifier */); + var node = createBaseNode(266 /* ImportSpecifier */); node.propertyName = propertyName; node.name = name; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23664,13 +24096,13 @@ var ts; } // @api function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createBaseDeclaration(266 /* ExportAssignment */, decorators, modifiers); + var node = createBaseDeclaration(267 /* ExportAssignment */, decorators, modifiers); node.isExportEquals = isExportEquals; node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary(62 /* EqualsToken */, /*leftSide*/ undefined, expression) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23683,14 +24115,14 @@ var ts; } // @api function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier) { - var node = createBaseDeclaration(267 /* ExportDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(268 /* ExportDeclaration */, decorators, modifiers); node.isTypeOnly = isTypeOnly; node.exportClause = exportClause; node.moduleSpecifier = moduleSpecifier; node.transformFlags |= propagateChildFlags(node.exportClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23705,10 +24137,10 @@ var ts; } // @api function createNamedExports(elements) { - var node = createBaseNode(268 /* NamedExports */); + var node = createBaseNode(269 /* NamedExports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23719,13 +24151,13 @@ var ts; } // @api function createExportSpecifier(propertyName, name) { - var node = createBaseNode(270 /* ExportSpecifier */); + var node = createBaseNode(271 /* ExportSpecifier */); node.propertyName = asName(propertyName); node.name = asName(name); node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23737,7 +24169,7 @@ var ts; } // @api function createMissingDeclaration() { - var node = createBaseDeclaration(271 /* MissingDeclaration */, + var node = createBaseDeclaration(272 /* MissingDeclaration */, /*decorators*/ undefined, /*modifiers*/ undefined); return node; @@ -23747,10 +24179,10 @@ var ts; // // @api function createExternalModuleReference(expression) { - var node = createBaseNode(272 /* ExternalModuleReference */); + var node = createBaseNode(273 /* ExternalModuleReference */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23792,7 +24224,7 @@ var ts; } // @api function createJSDocFunctionType(parameters, type) { - var node = createBaseSignatureDeclaration(308 /* JSDocFunctionType */, + var node = createBaseSignatureDeclaration(309 /* JSDocFunctionType */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, @@ -23809,7 +24241,7 @@ var ts; // @api function createJSDocTypeLiteral(propertyTags, isArrayType) { if (isArrayType === void 0) { isArrayType = false; } - var node = createBaseNode(312 /* JSDocTypeLiteral */); + var node = createBaseNode(314 /* JSDocTypeLiteral */); node.jsDocPropertyTags = asNodeArray(propertyTags); node.isArrayType = isArrayType; return node; @@ -23823,7 +24255,7 @@ var ts; } // @api function createJSDocTypeExpression(type) { - var node = createBaseNode(301 /* JSDocTypeExpression */); + var node = createBaseNode(302 /* JSDocTypeExpression */); node.type = type; return node; } @@ -23835,7 +24267,7 @@ var ts; } // @api function createJSDocSignature(typeParameters, parameters, type) { - var node = createBaseNode(313 /* JSDocSignature */); + var node = createBaseNode(315 /* JSDocSignature */); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; @@ -23864,7 +24296,7 @@ var ts; } // @api function createJSDocTemplateTag(tagName, constraint, typeParameters, comment) { - var node = createBaseJSDocTag(330 /* JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment); + var node = createBaseJSDocTag(334 /* JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment); node.constraint = constraint; node.typeParameters = createNodeArray(typeParameters); return node; @@ -23881,7 +24313,7 @@ var ts; } // @api function createJSDocTypedefTag(tagName, typeExpression, fullName, comment) { - var node = createBaseJSDocTag(331 /* JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment); + var node = createBaseJSDocTag(335 /* JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment); node.typeExpression = typeExpression; node.fullName = fullName; node.name = ts.getJSDocTypeAliasName(fullName); @@ -23899,7 +24331,7 @@ var ts; } // @api function createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { - var node = createBaseJSDocTag(326 /* JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment); + var node = createBaseJSDocTag(330 /* JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -23920,7 +24352,7 @@ var ts; } // @api function createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { - var node = createBaseJSDocTag(333 /* JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment); + var node = createBaseJSDocTag(337 /* JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -23941,7 +24373,7 @@ var ts; } // @api function createJSDocCallbackTag(tagName, typeExpression, fullName, comment) { - var node = createBaseJSDocTag(324 /* JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment); + var node = createBaseJSDocTag(328 /* JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment); node.typeExpression = typeExpression; node.fullName = fullName; node.name = ts.getJSDocTypeAliasName(fullName); @@ -23959,7 +24391,7 @@ var ts; } // @api function createJSDocAugmentsTag(tagName, className, comment) { - var node = createBaseJSDocTag(315 /* JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment); + var node = createBaseJSDocTag(318 /* JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment); node.class = className; return node; } @@ -23974,13 +24406,13 @@ var ts; } // @api function createJSDocImplementsTag(tagName, className, comment) { - var node = createBaseJSDocTag(316 /* JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment); + var node = createBaseJSDocTag(319 /* JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment); node.class = className; return node; } // @api function createJSDocSeeTag(tagName, name, comment) { - var node = createBaseJSDocTag(332 /* JSDocSeeTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment); + var node = createBaseJSDocTag(336 /* JSDocSeeTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment); node.name = name; return node; } @@ -23994,7 +24426,7 @@ var ts; } // @api function createJSDocNameReference(name) { - var node = createBaseNode(302 /* JSDocNameReference */); + var node = createBaseNode(303 /* JSDocNameReference */); node.name = name; return node; } @@ -24005,6 +24437,19 @@ var ts; : node; } // @api + function createJSDocLink(name, text) { + var node = createBaseNode(316 /* JSDocLink */); + node.name = name; + node.text = text; + return node; + } + // @api + function updateJSDocLink(node, name, text) { + return node.name !== name + ? update(createJSDocLink(name, text), node) + : node; + } + // @api function updateJSDocImplementsTag(node, tagName, className, comment) { if (tagName === void 0) { tagName = getDefaultTagName(node); } return node.tagName !== tagName @@ -24065,7 +24510,7 @@ var ts; } // @api function createJSDocUnknownTag(tagName, comment) { - var node = createBaseJSDocTag(314 /* JSDocTag */, tagName, comment); + var node = createBaseJSDocTag(317 /* JSDocTag */, tagName, comment); return node; } // @api @@ -24076,8 +24521,20 @@ var ts; : node; } // @api + function createJSDocText(text) { + var node = createBaseNode(313 /* JSDocText */); + node.text = text; + return node; + } + // @api + function updateJSDocText(node, text) { + return node.text !== text + ? update(createJSDocText(text), node) + : node; + } + // @api function createJSDocComment(comment, tags) { - var node = createBaseNode(311 /* JSDocComment */); + var node = createBaseNode(312 /* JSDocComment */); node.comment = comment; node.tags = asNodeArray(tags); return node; @@ -24094,7 +24551,7 @@ var ts; // // @api function createJsxElement(openingElement, children, closingElement) { - var node = createBaseNode(273 /* JsxElement */); + var node = createBaseNode(274 /* JsxElement */); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -24115,7 +24572,7 @@ var ts; } // @api function createJsxSelfClosingElement(tagName, typeArguments, attributes) { - var node = createBaseNode(274 /* JsxSelfClosingElement */); + var node = createBaseNode(275 /* JsxSelfClosingElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -24139,7 +24596,7 @@ var ts; } // @api function createJsxOpeningElement(tagName, typeArguments, attributes) { - var node = createBaseNode(275 /* JsxOpeningElement */); + var node = createBaseNode(276 /* JsxOpeningElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -24163,7 +24620,7 @@ var ts; } // @api function createJsxClosingElement(tagName) { - var node = createBaseNode(276 /* JsxClosingElement */); + var node = createBaseNode(277 /* JsxClosingElement */); node.tagName = tagName; node.transformFlags |= propagateChildFlags(node.tagName) | @@ -24178,7 +24635,7 @@ var ts; } // @api function createJsxFragment(openingFragment, children, closingFragment) { - var node = createBaseNode(277 /* JsxFragment */); + var node = createBaseNode(278 /* JsxFragment */); node.openingFragment = openingFragment; node.children = createNodeArray(children); node.closingFragment = closingFragment; @@ -24214,19 +24671,19 @@ var ts; } // @api function createJsxOpeningFragment() { - var node = createBaseNode(278 /* JsxOpeningFragment */); + var node = createBaseNode(279 /* JsxOpeningFragment */); node.transformFlags |= 2 /* ContainsJsx */; return node; } // @api function createJsxJsxClosingFragment() { - var node = createBaseNode(279 /* JsxClosingFragment */); + var node = createBaseNode(280 /* JsxClosingFragment */); node.transformFlags |= 2 /* ContainsJsx */; return node; } // @api function createJsxAttribute(name, initializer) { - var node = createBaseNode(280 /* JsxAttribute */); + var node = createBaseNode(281 /* JsxAttribute */); node.name = name; node.initializer = initializer; node.transformFlags |= @@ -24244,7 +24701,7 @@ var ts; } // @api function createJsxAttributes(properties) { - var node = createBaseNode(281 /* JsxAttributes */); + var node = createBaseNode(282 /* JsxAttributes */); node.properties = createNodeArray(properties); node.transformFlags |= propagateChildrenFlags(node.properties) | @@ -24259,7 +24716,7 @@ var ts; } // @api function createJsxSpreadAttribute(expression) { - var node = createBaseNode(282 /* JsxSpreadAttribute */); + var node = createBaseNode(283 /* JsxSpreadAttribute */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression) | @@ -24274,7 +24731,7 @@ var ts; } // @api function createJsxExpression(dotDotDotToken, expression) { - var node = createBaseNode(283 /* JsxExpression */); + var node = createBaseNode(284 /* JsxExpression */); node.dotDotDotToken = dotDotDotToken; node.expression = expression; node.transformFlags |= @@ -24294,7 +24751,7 @@ var ts; // // @api function createCaseClause(expression, statements) { - var node = createBaseNode(284 /* CaseClause */); + var node = createBaseNode(285 /* CaseClause */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.statements = createNodeArray(statements); node.transformFlags |= @@ -24311,7 +24768,7 @@ var ts; } // @api function createDefaultClause(statements) { - var node = createBaseNode(285 /* DefaultClause */); + var node = createBaseNode(286 /* DefaultClause */); node.statements = createNodeArray(statements); node.transformFlags = propagateChildrenFlags(node.statements); return node; @@ -24324,13 +24781,13 @@ var ts; } // @api function createHeritageClause(token, types) { - var node = createBaseNode(286 /* HeritageClause */); + var node = createBaseNode(287 /* HeritageClause */); node.token = token; node.types = createNodeArray(types); node.transformFlags |= propagateChildrenFlags(node.types); switch (token) { case 93 /* ExtendsKeyword */: - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; break; case 116 /* ImplementsKeyword */: node.transformFlags |= 1 /* ContainsTypeScript */; @@ -24348,7 +24805,7 @@ var ts; } // @api function createCatchClause(variableDeclaration, block) { - var node = createBaseNode(287 /* CatchClause */); + var node = createBaseNode(288 /* CatchClause */); variableDeclaration = !ts.isString(variableDeclaration) ? variableDeclaration : createVariableDeclaration(variableDeclaration, /*exclamationToken*/ undefined, /*type*/ undefined, @@ -24359,7 +24816,7 @@ var ts; propagateChildFlags(node.variableDeclaration) | propagateChildFlags(node.block); if (!variableDeclaration) - node.transformFlags |= 16 /* ContainsES2019 */; + node.transformFlags |= 32 /* ContainsES2019 */; return node; } // @api @@ -24374,7 +24831,7 @@ var ts; // // @api function createPropertyAssignment(name, initializer) { - var node = createBaseNamedDeclaration(288 /* PropertyAssignment */, + var node = createBaseNamedDeclaration(289 /* PropertyAssignment */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); @@ -24404,13 +24861,13 @@ var ts; } // @api function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createBaseNamedDeclaration(289 /* ShorthandPropertyAssignment */, + var node = createBaseNamedDeclaration(290 /* ShorthandPropertyAssignment */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); node.transformFlags |= propagateChildFlags(node.objectAssignmentInitializer) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } function finishUpdateShorthandPropertyAssignment(updated, original) { @@ -24436,12 +24893,12 @@ var ts; } // @api function createSpreadAssignment(expression) { - var node = createBaseNode(290 /* SpreadAssignment */); + var node = createBaseNode(291 /* SpreadAssignment */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 32 /* ContainsES2018 */ | - 16384 /* ContainsObjectRestOrSpread */; + 64 /* ContainsES2018 */ | + 32768 /* ContainsObjectRestOrSpread */; return node; } // @api @@ -24455,7 +24912,7 @@ var ts; // // @api function createEnumMember(name, initializer) { - var node = createBaseNode(291 /* EnumMember */); + var node = createBaseNode(292 /* EnumMember */); node.name = asName(name); node.initializer = initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); node.transformFlags |= @@ -24476,7 +24933,7 @@ var ts; // // @api function createSourceFile(statements, endOfFileToken, flags) { - var node = baseFactory.createBaseSourceFileNode(297 /* SourceFile */); + var node = baseFactory.createBaseSourceFileNode(298 /* SourceFile */); node.statements = createNodeArray(statements); node.endOfFileToken = endOfFileToken; node.flags |= flags; @@ -24493,7 +24950,7 @@ var ts; return node; } function cloneSourceFileWithChanges(source, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) { - var node = baseFactory.createBaseSourceFileNode(297 /* SourceFile */); + var node = baseFactory.createBaseSourceFileNode(298 /* SourceFile */); for (var p in source) { if (p === "emitNode" || ts.hasProperty(node, p) || !ts.hasProperty(source, p)) continue; @@ -24531,7 +24988,7 @@ var ts; // @api function createBundle(sourceFiles, prepends) { if (prepends === void 0) { prepends = ts.emptyArray; } - var node = createBaseNode(298 /* Bundle */); + var node = createBaseNode(299 /* Bundle */); node.prepends = prepends; node.sourceFiles = sourceFiles; return node; @@ -24546,7 +25003,7 @@ var ts; } // @api function createUnparsedSource(prologues, syntheticReferences, texts) { - var node = createBaseNode(299 /* UnparsedSource */); + var node = createBaseNode(300 /* UnparsedSource */); node.prologues = prologues; node.syntheticReferences = syntheticReferences; node.texts = texts; @@ -24564,28 +25021,28 @@ var ts; } // @api function createUnparsedPrologue(data) { - return createBaseUnparsedNode(292 /* UnparsedPrologue */, data); + return createBaseUnparsedNode(293 /* UnparsedPrologue */, data); } // @api function createUnparsedPrepend(data, texts) { - var node = createBaseUnparsedNode(293 /* UnparsedPrepend */, data); + var node = createBaseUnparsedNode(294 /* UnparsedPrepend */, data); node.texts = texts; return node; } // @api function createUnparsedTextLike(data, internal) { - return createBaseUnparsedNode(internal ? 295 /* UnparsedInternalText */ : 294 /* UnparsedText */, data); + return createBaseUnparsedNode(internal ? 296 /* UnparsedInternalText */ : 295 /* UnparsedText */, data); } // @api function createUnparsedSyntheticReference(section) { - var node = createBaseNode(296 /* UnparsedSyntheticReference */); + var node = createBaseNode(297 /* UnparsedSyntheticReference */); node.data = section.data; node.section = section; return node; } // @api function createInputFiles() { - var node = createBaseNode(300 /* InputFiles */); + var node = createBaseNode(301 /* InputFiles */); node.javascriptText = ""; node.declarationText = ""; return node; @@ -24596,7 +25053,7 @@ var ts; // @api function createSyntheticExpression(type, isSpread, tupleNameSource) { if (isSpread === void 0) { isSpread = false; } - var node = createBaseNode(227 /* SyntheticExpression */); + var node = createBaseNode(228 /* SyntheticExpression */); node.type = type; node.isSpread = isSpread; node.tupleNameSource = tupleNameSource; @@ -24604,7 +25061,7 @@ var ts; } // @api function createSyntaxList(children) { - var node = createBaseNode(334 /* SyntaxList */); + var node = createBaseNode(338 /* SyntaxList */); node._children = children; return node; } @@ -24619,7 +25076,7 @@ var ts; */ // @api function createNotEmittedStatement(original) { - var node = createBaseNode(335 /* NotEmittedStatement */); + var node = createBaseNode(339 /* NotEmittedStatement */); node.original = original; ts.setTextRange(node, original); return node; @@ -24633,7 +25090,7 @@ var ts; */ // @api function createPartiallyEmittedExpression(expression, original) { - var node = createBaseNode(336 /* PartiallyEmittedExpression */); + var node = createBaseNode(340 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; node.transformFlags |= @@ -24661,7 +25118,7 @@ var ts; } // @api function createCommaListExpression(elements) { - var node = createBaseNode(337 /* CommaListExpression */); + var node = createBaseNode(341 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); node.transformFlags |= propagateChildrenFlags(node.elements); return node; @@ -24678,7 +25135,7 @@ var ts; */ // @api function createEndOfDeclarationMarker(original) { - var node = createBaseNode(339 /* EndOfDeclarationMarker */); + var node = createBaseNode(343 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -24689,14 +25146,14 @@ var ts; */ // @api function createMergeDeclarationMarker(original) { - var node = createBaseNode(338 /* MergeDeclarationMarker */); + var node = createBaseNode(342 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; } // @api function createSyntheticReferenceExpression(expression, thisArg) { - var node = createBaseNode(340 /* SyntheticReferenceExpression */); + var node = createBaseNode(344 /* SyntheticReferenceExpression */); node.expression = expression; node.thisArg = thisArg; node.transformFlags |= @@ -24718,7 +25175,7 @@ var ts; if (node === undefined) { return node; } - var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(297 /* SourceFile */) : + var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(298 /* SourceFile */) : ts.isIdentifier(node) ? baseFactory.createBaseIdentifierNode(78 /* Identifier */) : ts.isPrivateIdentifier(node) ? baseFactory.createBasePrivateIdentifierNode(79 /* PrivateIdentifier */) : !ts.isNodeKind(node.kind) ? baseFactory.createBaseTokenNode(node.kind) : @@ -24825,11 +25282,11 @@ var ts; } function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 207 /* ParenthesizedExpression */: return updateParenthesizedExpression(outerExpression, expression); - case 206 /* TypeAssertionExpression */: return updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 224 /* AsExpression */: return updateAsExpression(outerExpression, expression, outerExpression.type); - case 225 /* NonNullExpression */: return updateNonNullExpression(outerExpression, expression); - case 336 /* PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression); + case 208 /* ParenthesizedExpression */: return updateParenthesizedExpression(outerExpression, expression); + case 207 /* TypeAssertionExpression */: return updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 225 /* AsExpression */: return updateAsExpression(outerExpression, expression, outerExpression.type); + case 226 /* NonNullExpression */: return updateNonNullExpression(outerExpression, expression); + case 340 /* PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -24883,13 +25340,13 @@ var ts; case 9 /* BigIntLiteral */: case 10 /* StringLiteral */: return false; - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return target.properties.length > 0; default: return true; @@ -25292,23 +25749,24 @@ var ts; } function getDefaultTagNameForKind(kind) { switch (kind) { - case 329 /* JSDocTypeTag */: return "type"; - case 327 /* JSDocReturnTag */: return "returns"; - case 328 /* JSDocThisTag */: return "this"; - case 325 /* JSDocEnumTag */: return "enum"; - case 317 /* JSDocAuthorTag */: return "author"; - case 319 /* JSDocClassTag */: return "class"; - case 320 /* JSDocPublicTag */: return "public"; - case 321 /* JSDocPrivateTag */: return "private"; - case 322 /* JSDocProtectedTag */: return "protected"; - case 323 /* JSDocReadonlyTag */: return "readonly"; - case 330 /* JSDocTemplateTag */: return "template"; - case 331 /* JSDocTypedefTag */: return "typedef"; - case 326 /* JSDocParameterTag */: return "param"; - case 333 /* JSDocPropertyTag */: return "prop"; - case 324 /* JSDocCallbackTag */: return "callback"; - case 315 /* JSDocAugmentsTag */: return "augments"; - case 316 /* JSDocImplementsTag */: return "implements"; + case 333 /* JSDocTypeTag */: return "type"; + case 331 /* JSDocReturnTag */: return "returns"; + case 332 /* JSDocThisTag */: return "this"; + case 329 /* JSDocEnumTag */: return "enum"; + case 320 /* JSDocAuthorTag */: return "author"; + case 322 /* JSDocClassTag */: return "class"; + case 323 /* JSDocPublicTag */: return "public"; + case 324 /* JSDocPrivateTag */: return "private"; + case 325 /* JSDocProtectedTag */: return "protected"; + case 326 /* JSDocReadonlyTag */: return "readonly"; + case 327 /* JSDocOverrideTag */: return "override"; + case 334 /* JSDocTemplateTag */: return "template"; + case 335 /* JSDocTypedefTag */: return "typedef"; + case 330 /* JSDocParameterTag */: return "param"; + case 337 /* JSDocPropertyTag */: return "prop"; + case 328 /* JSDocCallbackTag */: return "callback"; + case 318 /* JSDocAugmentsTag */: return "augments"; + case 319 /* JSDocImplementsTag */: return "implements"; default: return ts.Debug.fail("Unsupported kind: " + ts.Debug.formatSyntaxKind(kind)); } @@ -25361,10 +25819,10 @@ var ts; } function propagateIdentifierNameFlags(node) { // An IdentifierName is allowed to be `await` - return propagateChildFlags(node) & ~8388608 /* ContainsPossibleTopLevelAwait */; + return propagateChildFlags(node) & ~16777216 /* ContainsPossibleTopLevelAwait */; } function propagatePropertyNameFlagsOfChild(node, transformFlags) { - return transformFlags | (node.transformFlags & 4096 /* PropertyNamePropagatingFlags */); + return transformFlags | (node.transformFlags & 8192 /* PropertyNamePropagatingFlags */); } function propagateChildFlags(child) { if (!child) @@ -25388,36 +25846,36 @@ var ts; */ /* @internal */ function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 172 /* FirstTypeNode */ && kind <= 195 /* LastTypeNode */) { + if (kind >= 173 /* FirstTypeNode */ && kind <= 196 /* LastTypeNode */) { return -2 /* TypeExcludes */; } switch (kind) { - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 199 /* ArrayLiteralExpression */: - return 536879104 /* ArrayLiteralOrCallOrNewExcludes */; - case 256 /* ModuleDeclaration */: - return 546379776 /* ModuleExcludes */; - case 160 /* Parameter */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 200 /* ArrayLiteralExpression */: + return 536887296 /* ArrayLiteralOrCallOrNewExcludes */; + case 257 /* ModuleDeclaration */: + return 555888640 /* ModuleExcludes */; + case 161 /* Parameter */: return 536870912 /* ParameterExcludes */; - case 209 /* ArrowFunction */: - return 547309568 /* ArrowFunctionExcludes */; - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - return 547313664 /* FunctionExcludes */; - case 250 /* VariableDeclarationList */: - return 537018368 /* VariableDeclarationListExcludes */; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - return 536905728 /* ClassExcludes */; - case 166 /* Constructor */: - return 547311616 /* ConstructorExcludes */; - case 163 /* PropertyDeclaration */: - return 536875008 /* PropertyExcludes */; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - return 538923008 /* MethodOrAccessorExcludes */; + case 210 /* ArrowFunction */: + return 557748224 /* ArrowFunctionExcludes */; + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + return 557756416 /* FunctionExcludes */; + case 251 /* VariableDeclarationList */: + return 537165824 /* VariableDeclarationListExcludes */; + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + return 536940544 /* ClassExcludes */; + case 167 /* Constructor */: + return 557752320 /* ConstructorExcludes */; + case 164 /* PropertyDeclaration */: + return 536879104 /* PropertyExcludes */; + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return 540975104 /* MethodOrAccessorExcludes */; case 128 /* AnyKeyword */: case 144 /* NumberKeyword */: case 155 /* BigIntKeyword */: @@ -25427,30 +25885,30 @@ var ts; case 131 /* BooleanKeyword */: case 148 /* SymbolKeyword */: case 113 /* VoidKeyword */: - case 159 /* TypeParameter */: - case 162 /* PropertySignature */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 160 /* TypeParameter */: + case 163 /* PropertySignature */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return -2 /* TypeExcludes */; - case 200 /* ObjectLiteralExpression */: - return 536922112 /* ObjectLiteralExcludes */; - case 287 /* CatchClause */: - return 536887296 /* CatchClauseExcludes */; - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: - return 536879104 /* BindingPatternExcludes */; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: - case 336 /* PartiallyEmittedExpression */: - case 207 /* ParenthesizedExpression */: + case 201 /* ObjectLiteralExpression */: + return 536973312 /* ObjectLiteralExcludes */; + case 288 /* CatchClause */: + return 536903680 /* CatchClauseExcludes */; + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + return 536887296 /* BindingPatternExcludes */; + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: + case 340 /* PartiallyEmittedExpression */: + case 208 /* ParenthesizedExpression */: case 105 /* SuperKeyword */: return 536870912 /* OuterExpressionExcludes */; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return 536870912 /* PropertyAccessExcludes */; default: return 536870912 /* NodeExcludes */; @@ -25749,7 +26207,7 @@ var ts; // To avoid holding onto transformation artifacts, we keep track of any // parse tree node we are annotating. This allows us to clean them up after // all transformations have completed. - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = (_a = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)))) !== null && _a !== void 0 ? _a : ts.Debug.fail("Could not determine parsed source file."); @@ -26236,13 +26694,27 @@ var ts; /*typeArguments*/ undefined, [moduleExpression, exportsExpression]); } // Class Fields Helpers - function createClassPrivateFieldGetHelper(receiver, privateField) { + function createClassPrivateFieldGetHelper(receiver, state, kind, f) { context.requestEmitHelper(ts.classPrivateFieldGetHelper); - return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ undefined, [receiver, privateField]); + var args; + if (!f) { + args = [receiver, state, factory.createStringLiteral(kind)]; + } + else { + args = [receiver, state, factory.createStringLiteral(kind), f]; + } + return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ undefined, args); } - function createClassPrivateFieldSetHelper(receiver, privateField, value) { + function createClassPrivateFieldSetHelper(receiver, state, value, kind, f) { context.requestEmitHelper(ts.classPrivateFieldSetHelper); - return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, [receiver, privateField, value]); + var args; + if (!f) { + args = [receiver, state, value, factory.createStringLiteral(kind)]; + } + else { + args = [receiver, state, value, factory.createStringLiteral(kind), f]; + } + return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, args); } } ts.createEmitHelperFactory = createEmitHelperFactory; @@ -26482,7 +26954,6 @@ var ts; scoped: false, text: "\n var __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n };" }; - // emit output for the __export helper function ts.exportStarHelper = { name: "typescript:export-star", importName: "__exportStar", @@ -26491,18 +26962,116 @@ var ts; priority: 2, text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n };" }; - // Class fields helpers + /** + * Parameters: + * @param receiver — The object from which the private member will be read. + * @param state — One of the following: + * - A WeakMap used to read a private instance field. + * - A WeakSet used as an instance brand for private instance methods and accessors. + * - A function value that should be the undecorated class constructor used to brand check private static fields, methods, and accessors. + * @param kind — (optional pre TS 4.3, required for TS 4.3+) One of the following values: + * - undefined — Indicates a private instance field (pre TS 4.3). + * - "f" — Indicates a private field (instance or static). + * - "m" — Indicates a private method (instance or static). + * - "a" — Indicates a private accessor (instance or static). + * @param f — (optional pre TS 4.3) Depends on the arguments for state and kind: + * - If kind is "m", this should be the function corresponding to the static or instance method. + * - If kind is "a", this should be the function corresponding to the getter method, or undefined if the getter was not defined. + * - If kind is "f" and state is a function, this should be an object holding the value of a static field, or undefined if the static field declaration has not yet been evaluated. + * Usage: + * This helper will only ever be used by the compiler in the following ways: + * + * Reading from a private instance field (pre TS 4.3): + * __classPrivateFieldGet(, ) + * + * Reading from a private instance field (TS 4.3+): + * __classPrivateFieldGet(, , "f") + * + * Reading from a private instance get accessor (when defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", ) + * + * Reading from a private instance get accessor (when not defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Reading from a private instance method (TS 4.3+): + * __classPrivateFieldGet(, , "m", ) + * + * Reading from a private static field (TS 4.3+): + * __classPrivateFieldGet(, , "f", <{ value: any }>) + * + * Reading from a private static get accessor (when defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", ) + * + * Reading from a private static get accessor (when not defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Reading from a private static method (TS 4.3+): + * __classPrivateFieldGet(, , "m", ) + */ ts.classPrivateFieldGetHelper = { name: "typescript:classPrivateFieldGet", importName: "__classPrivateFieldGet", scoped: false, - text: "\n var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, privateMap) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to get private field on non-instance\");\n }\n return privateMap.get(receiver);\n };" + text: "\n var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n };" }; + /** + * Parameters: + * @param receiver — The object on which the private member will be set. + * @param state — One of the following: + * - A WeakMap used to store a private instance field. + * - A WeakSet used as an instance brand for private instance methods and accessors. + * - A function value that should be the undecorated class constructor used to brand check private static fields, methods, and accessors. + * @param value — The value to set. + * @param kind — (optional pre TS 4.3, required for TS 4.3+) One of the following values: + * - undefined — Indicates a private instance field (pre TS 4.3). + * - "f" — Indicates a private field (instance or static). + * - "m" — Indicates a private method (instance or static). + * - "a" — Indicates a private accessor (instance or static). + * @param f — (optional pre TS 4.3) Depends on the arguments for state and kind: + * - If kind is "m", this should be the function corresponding to the static or instance method. + * - If kind is "a", this should be the function corresponding to the setter method, or undefined if the setter was not defined. + * - If kind is "f" and state is a function, this should be an object holding the value of a static field, or undefined if the static field declaration has not yet been evaluated. + * Usage: + * This helper will only ever be used by the compiler in the following ways: + * + * Writing to a private instance field (pre TS 4.3): + * __classPrivateFieldSet(, , ) + * + * Writing to a private instance field (TS 4.3+): + * __classPrivateFieldSet(, , , "f") + * + * Writing to a private instance set accessor (when defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", ) + * + * Writing to a private instance set accessor (when not defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Writing to a private instance method (TS 4.3+): + * __classPrivateFieldSet(, , , "m", ) + * NOTE: This always results in a runtime error. + * + * Writing to a private static field (TS 4.3+): + * __classPrivateFieldSet(, , , "f", <{ value: any }>) + * + * Writing to a private static set accessor (when defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", ) + * + * Writing to a private static set accessor (when not defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Writing to a private static method (TS 4.3+): + * __classPrivateFieldSet(, , , "m", ) + * NOTE: This always results in a runtime error. + */ ts.classPrivateFieldSetHelper = { name: "typescript:classPrivateFieldSet", importName: "__classPrivateFieldSet", scoped: false, - text: "\n var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, privateMap, value) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to set private field on non-instance\");\n }\n privateMap.set(receiver, value);\n return value;\n };" + text: "\n var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n };" }; var allUnscopedEmitHelpers; function getAllUnscopedEmitHelpers() { @@ -26591,25 +27160,93 @@ var ts; return node.kind === 17 /* TemplateTail */; } ts.isTemplateTail = isTemplateTail; + // Punctuation + function isDotDotDotToken(node) { + return node.kind === 25 /* DotDotDotToken */; + } + ts.isDotDotDotToken = isDotDotDotToken; + /*@internal*/ + function isCommaToken(node) { + return node.kind === 27 /* CommaToken */; + } + ts.isCommaToken = isCommaToken; + function isPlusToken(node) { + return node.kind === 39 /* PlusToken */; + } + ts.isPlusToken = isPlusToken; + function isMinusToken(node) { + return node.kind === 40 /* MinusToken */; + } + ts.isMinusToken = isMinusToken; + function isAsteriskToken(node) { + return node.kind === 41 /* AsteriskToken */; + } + ts.isAsteriskToken = isAsteriskToken; + /*@internal*/ + function isExclamationToken(node) { + return node.kind === 53 /* ExclamationToken */; + } + ts.isExclamationToken = isExclamationToken; + /*@internal*/ + function isQuestionToken(node) { + return node.kind === 57 /* QuestionToken */; + } + ts.isQuestionToken = isQuestionToken; + /*@internal*/ + function isColonToken(node) { + return node.kind === 58 /* ColonToken */; + } + ts.isColonToken = isColonToken; + /*@internal*/ + function isQuestionDotToken(node) { + return node.kind === 28 /* QuestionDotToken */; + } + ts.isQuestionDotToken = isQuestionDotToken; + /*@internal*/ + function isEqualsGreaterThanToken(node) { + return node.kind === 38 /* EqualsGreaterThanToken */; + } + ts.isEqualsGreaterThanToken = isEqualsGreaterThanToken; // Identifiers function isIdentifier(node) { return node.kind === 78 /* Identifier */; } ts.isIdentifier = isIdentifier; - // Names - function isQualifiedName(node) { - return node.kind === 157 /* QualifiedName */; - } - ts.isQualifiedName = isQualifiedName; - function isComputedPropertyName(node) { - return node.kind === 158 /* ComputedPropertyName */; - } - ts.isComputedPropertyName = isComputedPropertyName; function isPrivateIdentifier(node) { return node.kind === 79 /* PrivateIdentifier */; } ts.isPrivateIdentifier = isPrivateIdentifier; - // Tokens + // Reserved Words + /* @internal */ + function isExportModifier(node) { + return node.kind === 92 /* ExportKeyword */; + } + ts.isExportModifier = isExportModifier; + /* @internal */ + function isAsyncModifier(node) { + return node.kind === 129 /* AsyncKeyword */; + } + ts.isAsyncModifier = isAsyncModifier; + /* @internal */ + function isAssertsKeyword(node) { + return node.kind === 127 /* AssertsKeyword */; + } + ts.isAssertsKeyword = isAssertsKeyword; + /* @internal */ + function isAwaitKeyword(node) { + return node.kind === 130 /* AwaitKeyword */; + } + ts.isAwaitKeyword = isAwaitKeyword; + /* @internal */ + function isReadonlyKeyword(node) { + return node.kind === 142 /* ReadonlyKeyword */; + } + ts.isReadonlyKeyword = isReadonlyKeyword; + /* @internal */ + function isStaticModifier(node) { + return node.kind === 123 /* StaticKeyword */; + } + ts.isStaticModifier = isStaticModifier; /*@internal*/ function isSuperKeyword(node) { return node.kind === 105 /* SuperKeyword */; @@ -26620,597 +27257,591 @@ var ts; return node.kind === 99 /* ImportKeyword */; } ts.isImportKeyword = isImportKeyword; - /*@internal*/ - function isCommaToken(node) { - return node.kind === 27 /* CommaToken */; - } - ts.isCommaToken = isCommaToken; - /*@internal*/ - function isQuestionToken(node) { - return node.kind === 57 /* QuestionToken */; + // Names + function isQualifiedName(node) { + return node.kind === 158 /* QualifiedName */; } - ts.isQuestionToken = isQuestionToken; - /*@internal*/ - function isExclamationToken(node) { - return node.kind === 53 /* ExclamationToken */; + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 159 /* ComputedPropertyName */; } - ts.isExclamationToken = isExclamationToken; + ts.isComputedPropertyName = isComputedPropertyName; // Signature elements function isTypeParameterDeclaration(node) { - return node.kind === 159 /* TypeParameter */; + return node.kind === 160 /* TypeParameter */; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; // TODO(rbuckton): Rename to 'isParameterDeclaration' function isParameter(node) { - return node.kind === 160 /* Parameter */; + return node.kind === 161 /* Parameter */; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 161 /* Decorator */; + return node.kind === 162 /* Decorator */; } ts.isDecorator = isDecorator; // TypeMember function isPropertySignature(node) { - return node.kind === 162 /* PropertySignature */; + return node.kind === 163 /* PropertySignature */; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 163 /* PropertyDeclaration */; + return node.kind === 164 /* PropertyDeclaration */; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 164 /* MethodSignature */; + return node.kind === 165 /* MethodSignature */; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 165 /* MethodDeclaration */; + return node.kind === 166 /* MethodDeclaration */; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 166 /* Constructor */; + return node.kind === 167 /* Constructor */; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 167 /* GetAccessor */; + return node.kind === 168 /* GetAccessor */; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 168 /* SetAccessor */; + return node.kind === 169 /* SetAccessor */; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 169 /* CallSignature */; + return node.kind === 170 /* CallSignature */; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 170 /* ConstructSignature */; + return node.kind === 171 /* ConstructSignature */; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 171 /* IndexSignature */; + return node.kind === 172 /* IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; // Type function isTypePredicateNode(node) { - return node.kind === 172 /* TypePredicate */; + return node.kind === 173 /* TypePredicate */; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 173 /* TypeReference */; + return node.kind === 174 /* TypeReference */; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 174 /* FunctionType */; + return node.kind === 175 /* FunctionType */; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 175 /* ConstructorType */; + return node.kind === 176 /* ConstructorType */; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 176 /* TypeQuery */; + return node.kind === 177 /* TypeQuery */; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 177 /* TypeLiteral */; + return node.kind === 178 /* TypeLiteral */; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 178 /* ArrayType */; + return node.kind === 179 /* ArrayType */; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 179 /* TupleType */; + return node.kind === 180 /* TupleType */; } ts.isTupleTypeNode = isTupleTypeNode; function isNamedTupleMember(node) { - return node.kind === 192 /* NamedTupleMember */; + return node.kind === 193 /* NamedTupleMember */; } ts.isNamedTupleMember = isNamedTupleMember; function isOptionalTypeNode(node) { - return node.kind === 180 /* OptionalType */; + return node.kind === 181 /* OptionalType */; } ts.isOptionalTypeNode = isOptionalTypeNode; function isRestTypeNode(node) { - return node.kind === 181 /* RestType */; + return node.kind === 182 /* RestType */; } ts.isRestTypeNode = isRestTypeNode; function isUnionTypeNode(node) { - return node.kind === 182 /* UnionType */; + return node.kind === 183 /* UnionType */; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 183 /* IntersectionType */; + return node.kind === 184 /* IntersectionType */; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isConditionalTypeNode(node) { - return node.kind === 184 /* ConditionalType */; + return node.kind === 185 /* ConditionalType */; } ts.isConditionalTypeNode = isConditionalTypeNode; function isInferTypeNode(node) { - return node.kind === 185 /* InferType */; + return node.kind === 186 /* InferType */; } ts.isInferTypeNode = isInferTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 186 /* ParenthesizedType */; + return node.kind === 187 /* ParenthesizedType */; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 187 /* ThisType */; + return node.kind === 188 /* ThisType */; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 188 /* TypeOperator */; + return node.kind === 189 /* TypeOperator */; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 189 /* IndexedAccessType */; + return node.kind === 190 /* IndexedAccessType */; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 190 /* MappedType */; + return node.kind === 191 /* MappedType */; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 191 /* LiteralType */; + return node.kind === 192 /* LiteralType */; } ts.isLiteralTypeNode = isLiteralTypeNode; function isImportTypeNode(node) { - return node.kind === 195 /* ImportType */; + return node.kind === 196 /* ImportType */; } ts.isImportTypeNode = isImportTypeNode; function isTemplateLiteralTypeSpan(node) { - return node.kind === 194 /* TemplateLiteralTypeSpan */; + return node.kind === 195 /* TemplateLiteralTypeSpan */; } ts.isTemplateLiteralTypeSpan = isTemplateLiteralTypeSpan; function isTemplateLiteralTypeNode(node) { - return node.kind === 193 /* TemplateLiteralType */; + return node.kind === 194 /* TemplateLiteralType */; } ts.isTemplateLiteralTypeNode = isTemplateLiteralTypeNode; // Binding patterns function isObjectBindingPattern(node) { - return node.kind === 196 /* ObjectBindingPattern */; + return node.kind === 197 /* ObjectBindingPattern */; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 197 /* ArrayBindingPattern */; + return node.kind === 198 /* ArrayBindingPattern */; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 198 /* BindingElement */; + return node.kind === 199 /* BindingElement */; } ts.isBindingElement = isBindingElement; // Expression function isArrayLiteralExpression(node) { - return node.kind === 199 /* ArrayLiteralExpression */; + return node.kind === 200 /* ArrayLiteralExpression */; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 200 /* ObjectLiteralExpression */; + return node.kind === 201 /* ObjectLiteralExpression */; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 201 /* PropertyAccessExpression */; + return node.kind === 202 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 202 /* ElementAccessExpression */; + return node.kind === 203 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 203 /* CallExpression */; + return node.kind === 204 /* CallExpression */; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 204 /* NewExpression */; + return node.kind === 205 /* NewExpression */; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 205 /* TaggedTemplateExpression */; + return node.kind === 206 /* TaggedTemplateExpression */; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertionExpression(node) { - return node.kind === 206 /* TypeAssertionExpression */; + return node.kind === 207 /* TypeAssertionExpression */; } ts.isTypeAssertionExpression = isTypeAssertionExpression; function isParenthesizedExpression(node) { - return node.kind === 207 /* ParenthesizedExpression */; + return node.kind === 208 /* ParenthesizedExpression */; } ts.isParenthesizedExpression = isParenthesizedExpression; function isFunctionExpression(node) { - return node.kind === 208 /* FunctionExpression */; + return node.kind === 209 /* FunctionExpression */; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 209 /* ArrowFunction */; + return node.kind === 210 /* ArrowFunction */; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 210 /* DeleteExpression */; + return node.kind === 211 /* DeleteExpression */; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 211 /* TypeOfExpression */; + return node.kind === 212 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 212 /* VoidExpression */; + return node.kind === 213 /* VoidExpression */; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 213 /* AwaitExpression */; + return node.kind === 214 /* AwaitExpression */; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 214 /* PrefixUnaryExpression */; + return node.kind === 215 /* PrefixUnaryExpression */; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 215 /* PostfixUnaryExpression */; + return node.kind === 216 /* PostfixUnaryExpression */; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 216 /* BinaryExpression */; + return node.kind === 217 /* BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 217 /* ConditionalExpression */; + return node.kind === 218 /* ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 218 /* TemplateExpression */; + return node.kind === 219 /* TemplateExpression */; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 219 /* YieldExpression */; + return node.kind === 220 /* YieldExpression */; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 220 /* SpreadElement */; + return node.kind === 221 /* SpreadElement */; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 221 /* ClassExpression */; + return node.kind === 222 /* ClassExpression */; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 222 /* OmittedExpression */; + return node.kind === 223 /* OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 223 /* ExpressionWithTypeArguments */; + return node.kind === 224 /* ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 224 /* AsExpression */; + return node.kind === 225 /* AsExpression */; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 225 /* NonNullExpression */; + return node.kind === 226 /* NonNullExpression */; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 226 /* MetaProperty */; + return node.kind === 227 /* MetaProperty */; } ts.isMetaProperty = isMetaProperty; function isSyntheticExpression(node) { - return node.kind === 227 /* SyntheticExpression */; + return node.kind === 228 /* SyntheticExpression */; } ts.isSyntheticExpression = isSyntheticExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 336 /* PartiallyEmittedExpression */; + return node.kind === 340 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isCommaListExpression(node) { - return node.kind === 337 /* CommaListExpression */; + return node.kind === 341 /* CommaListExpression */; } ts.isCommaListExpression = isCommaListExpression; // Misc function isTemplateSpan(node) { - return node.kind === 228 /* TemplateSpan */; + return node.kind === 229 /* TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 229 /* SemicolonClassElement */; + return node.kind === 230 /* SemicolonClassElement */; } ts.isSemicolonClassElement = isSemicolonClassElement; // Elements function isBlock(node) { - return node.kind === 230 /* Block */; + return node.kind === 231 /* Block */; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 232 /* VariableStatement */; + return node.kind === 233 /* VariableStatement */; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 231 /* EmptyStatement */; + return node.kind === 232 /* EmptyStatement */; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 233 /* ExpressionStatement */; + return node.kind === 234 /* ExpressionStatement */; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 234 /* IfStatement */; + return node.kind === 235 /* IfStatement */; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 235 /* DoStatement */; + return node.kind === 236 /* DoStatement */; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 236 /* WhileStatement */; + return node.kind === 237 /* WhileStatement */; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 237 /* ForStatement */; + return node.kind === 238 /* ForStatement */; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 238 /* ForInStatement */; + return node.kind === 239 /* ForInStatement */; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 239 /* ForOfStatement */; + return node.kind === 240 /* ForOfStatement */; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 240 /* ContinueStatement */; + return node.kind === 241 /* ContinueStatement */; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 241 /* BreakStatement */; + return node.kind === 242 /* BreakStatement */; } ts.isBreakStatement = isBreakStatement; function isReturnStatement(node) { - return node.kind === 242 /* ReturnStatement */; + return node.kind === 243 /* ReturnStatement */; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 243 /* WithStatement */; + return node.kind === 244 /* WithStatement */; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 244 /* SwitchStatement */; + return node.kind === 245 /* SwitchStatement */; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 245 /* LabeledStatement */; + return node.kind === 246 /* LabeledStatement */; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 246 /* ThrowStatement */; + return node.kind === 247 /* ThrowStatement */; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 247 /* TryStatement */; + return node.kind === 248 /* TryStatement */; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 248 /* DebuggerStatement */; + return node.kind === 249 /* DebuggerStatement */; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 249 /* VariableDeclaration */; + return node.kind === 250 /* VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 250 /* VariableDeclarationList */; + return node.kind === 251 /* VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 251 /* FunctionDeclaration */; + return node.kind === 252 /* FunctionDeclaration */; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 252 /* ClassDeclaration */; + return node.kind === 253 /* ClassDeclaration */; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 253 /* InterfaceDeclaration */; + return node.kind === 254 /* InterfaceDeclaration */; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 254 /* TypeAliasDeclaration */; + return node.kind === 255 /* TypeAliasDeclaration */; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 255 /* EnumDeclaration */; + return node.kind === 256 /* EnumDeclaration */; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 256 /* ModuleDeclaration */; + return node.kind === 257 /* ModuleDeclaration */; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 257 /* ModuleBlock */; + return node.kind === 258 /* ModuleBlock */; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 258 /* CaseBlock */; + return node.kind === 259 /* CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 259 /* NamespaceExportDeclaration */; + return node.kind === 260 /* NamespaceExportDeclaration */; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */; + return node.kind === 261 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 261 /* ImportDeclaration */; + return node.kind === 262 /* ImportDeclaration */; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 262 /* ImportClause */; + return node.kind === 263 /* ImportClause */; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 263 /* NamespaceImport */; + return node.kind === 264 /* NamespaceImport */; } ts.isNamespaceImport = isNamespaceImport; function isNamespaceExport(node) { - return node.kind === 269 /* NamespaceExport */; + return node.kind === 270 /* NamespaceExport */; } ts.isNamespaceExport = isNamespaceExport; function isNamedImports(node) { - return node.kind === 264 /* NamedImports */; + return node.kind === 265 /* NamedImports */; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 265 /* ImportSpecifier */; + return node.kind === 266 /* ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 266 /* ExportAssignment */; + return node.kind === 267 /* ExportAssignment */; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 267 /* ExportDeclaration */; + return node.kind === 268 /* ExportDeclaration */; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 268 /* NamedExports */; + return node.kind === 269 /* NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 270 /* ExportSpecifier */; + return node.kind === 271 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 271 /* MissingDeclaration */; + return node.kind === 272 /* MissingDeclaration */; } ts.isMissingDeclaration = isMissingDeclaration; function isNotEmittedStatement(node) { - return node.kind === 335 /* NotEmittedStatement */; + return node.kind === 339 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ function isSyntheticReference(node) { - return node.kind === 340 /* SyntheticReferenceExpression */; + return node.kind === 344 /* SyntheticReferenceExpression */; } ts.isSyntheticReference = isSyntheticReference; /* @internal */ function isMergeDeclarationMarker(node) { - return node.kind === 338 /* MergeDeclarationMarker */; + return node.kind === 342 /* MergeDeclarationMarker */; } ts.isMergeDeclarationMarker = isMergeDeclarationMarker; /* @internal */ function isEndOfDeclarationMarker(node) { - return node.kind === 339 /* EndOfDeclarationMarker */; + return node.kind === 343 /* EndOfDeclarationMarker */; } ts.isEndOfDeclarationMarker = isEndOfDeclarationMarker; // Module References function isExternalModuleReference(node) { - return node.kind === 272 /* ExternalModuleReference */; + return node.kind === 273 /* ExternalModuleReference */; } ts.isExternalModuleReference = isExternalModuleReference; // JSX function isJsxElement(node) { - return node.kind === 273 /* JsxElement */; + return node.kind === 274 /* JsxElement */; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 274 /* JsxSelfClosingElement */; + return node.kind === 275 /* JsxSelfClosingElement */; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 275 /* JsxOpeningElement */; + return node.kind === 276 /* JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 276 /* JsxClosingElement */; + return node.kind === 277 /* JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxFragment(node) { - return node.kind === 277 /* JsxFragment */; + return node.kind === 278 /* JsxFragment */; } ts.isJsxFragment = isJsxFragment; function isJsxOpeningFragment(node) { - return node.kind === 278 /* JsxOpeningFragment */; + return node.kind === 279 /* JsxOpeningFragment */; } ts.isJsxOpeningFragment = isJsxOpeningFragment; function isJsxClosingFragment(node) { - return node.kind === 279 /* JsxClosingFragment */; + return node.kind === 280 /* JsxClosingFragment */; } ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 280 /* JsxAttribute */; + return node.kind === 281 /* JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 281 /* JsxAttributes */; + return node.kind === 282 /* JsxAttributes */; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 282 /* JsxSpreadAttribute */; + return node.kind === 283 /* JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 283 /* JsxExpression */; + return node.kind === 284 /* JsxExpression */; } ts.isJsxExpression = isJsxExpression; // Clauses function isCaseClause(node) { - return node.kind === 284 /* CaseClause */; + return node.kind === 285 /* CaseClause */; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 285 /* DefaultClause */; + return node.kind === 286 /* DefaultClause */; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 286 /* HeritageClause */; + return node.kind === 287 /* HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 287 /* CatchClause */; + return node.kind === 288 /* CatchClause */; } ts.isCatchClause = isCatchClause; // Property assignments function isPropertyAssignment(node) { - return node.kind === 288 /* PropertyAssignment */; + return node.kind === 289 /* PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 289 /* ShorthandPropertyAssignment */; + return node.kind === 290 /* ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 290 /* SpreadAssignment */; + return node.kind === 291 /* SpreadAssignment */; } ts.isSpreadAssignment = isSpreadAssignment; // Enum function isEnumMember(node) { - return node.kind === 291 /* EnumMember */; + return node.kind === 292 /* EnumMember */; } ts.isEnumMember = isEnumMember; // Unparsed // TODO(rbuckton): isUnparsedPrologue function isUnparsedPrepend(node) { - return node.kind === 293 /* UnparsedPrepend */; + return node.kind === 294 /* UnparsedPrepend */; } ts.isUnparsedPrepend = isUnparsedPrepend; // TODO(rbuckton): isUnparsedText @@ -27218,156 +27849,164 @@ var ts; // TODO(rbuckton): isUnparsedSyntheticReference // Top-level nodes function isSourceFile(node) { - return node.kind === 297 /* SourceFile */; + return node.kind === 298 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 298 /* Bundle */; + return node.kind === 299 /* Bundle */; } ts.isBundle = isBundle; function isUnparsedSource(node) { - return node.kind === 299 /* UnparsedSource */; + return node.kind === 300 /* UnparsedSource */; } ts.isUnparsedSource = isUnparsedSource; // TODO(rbuckton): isInputFiles // JSDoc Elements function isJSDocTypeExpression(node) { - return node.kind === 301 /* JSDocTypeExpression */; + return node.kind === 302 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocNameReference(node) { - return node.kind === 302 /* JSDocNameReference */; + return node.kind === 303 /* JSDocNameReference */; } ts.isJSDocNameReference = isJSDocNameReference; + function isJSDocLink(node) { + return node.kind === 316 /* JSDocLink */; + } + ts.isJSDocLink = isJSDocLink; function isJSDocAllType(node) { - return node.kind === 303 /* JSDocAllType */; + return node.kind === 304 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 304 /* JSDocUnknownType */; + return node.kind === 305 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 305 /* JSDocNullableType */; + return node.kind === 306 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 306 /* JSDocNonNullableType */; + return node.kind === 307 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 307 /* JSDocOptionalType */; + return node.kind === 308 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 308 /* JSDocFunctionType */; + return node.kind === 309 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 309 /* JSDocVariadicType */; + return node.kind === 310 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDocNamepathType(node) { - return node.kind === 310 /* JSDocNamepathType */; + return node.kind === 311 /* JSDocNamepathType */; } ts.isJSDocNamepathType = isJSDocNamepathType; function isJSDoc(node) { - return node.kind === 311 /* JSDocComment */; + return node.kind === 312 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocTypeLiteral(node) { - return node.kind === 312 /* JSDocTypeLiteral */; + return node.kind === 314 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; function isJSDocSignature(node) { - return node.kind === 313 /* JSDocSignature */; + return node.kind === 315 /* JSDocSignature */; } ts.isJSDocSignature = isJSDocSignature; // JSDoc Tags function isJSDocAugmentsTag(node) { - return node.kind === 315 /* JSDocAugmentsTag */; + return node.kind === 318 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocAuthorTag(node) { - return node.kind === 317 /* JSDocAuthorTag */; + return node.kind === 320 /* JSDocAuthorTag */; } ts.isJSDocAuthorTag = isJSDocAuthorTag; function isJSDocClassTag(node) { - return node.kind === 319 /* JSDocClassTag */; + return node.kind === 322 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocCallbackTag(node) { - return node.kind === 324 /* JSDocCallbackTag */; + return node.kind === 328 /* JSDocCallbackTag */; } ts.isJSDocCallbackTag = isJSDocCallbackTag; function isJSDocPublicTag(node) { - return node.kind === 320 /* JSDocPublicTag */; + return node.kind === 323 /* JSDocPublicTag */; } ts.isJSDocPublicTag = isJSDocPublicTag; function isJSDocPrivateTag(node) { - return node.kind === 321 /* JSDocPrivateTag */; + return node.kind === 324 /* JSDocPrivateTag */; } ts.isJSDocPrivateTag = isJSDocPrivateTag; function isJSDocProtectedTag(node) { - return node.kind === 322 /* JSDocProtectedTag */; + return node.kind === 325 /* JSDocProtectedTag */; } ts.isJSDocProtectedTag = isJSDocProtectedTag; function isJSDocReadonlyTag(node) { - return node.kind === 323 /* JSDocReadonlyTag */; + return node.kind === 326 /* JSDocReadonlyTag */; } ts.isJSDocReadonlyTag = isJSDocReadonlyTag; + function isJSDocOverrideTag(node) { + return node.kind === 327 /* JSDocOverrideTag */; + } + ts.isJSDocOverrideTag = isJSDocOverrideTag; function isJSDocDeprecatedTag(node) { - return node.kind === 318 /* JSDocDeprecatedTag */; + return node.kind === 321 /* JSDocDeprecatedTag */; } ts.isJSDocDeprecatedTag = isJSDocDeprecatedTag; function isJSDocSeeTag(node) { - return node.kind === 332 /* JSDocSeeTag */; + return node.kind === 336 /* JSDocSeeTag */; } ts.isJSDocSeeTag = isJSDocSeeTag; function isJSDocEnumTag(node) { - return node.kind === 325 /* JSDocEnumTag */; + return node.kind === 329 /* JSDocEnumTag */; } ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocParameterTag(node) { - return node.kind === 326 /* JSDocParameterTag */; + return node.kind === 330 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 327 /* JSDocReturnTag */; + return node.kind === 331 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocThisTag(node) { - return node.kind === 328 /* JSDocThisTag */; + return node.kind === 332 /* JSDocThisTag */; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocTypeTag(node) { - return node.kind === 329 /* JSDocTypeTag */; + return node.kind === 333 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 330 /* JSDocTemplateTag */; + return node.kind === 334 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 331 /* JSDocTypedefTag */; + return node.kind === 335 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocUnknownTag(node) { - return node.kind === 314 /* JSDocTag */; + return node.kind === 317 /* JSDocTag */; } ts.isJSDocUnknownTag = isJSDocUnknownTag; function isJSDocPropertyTag(node) { - return node.kind === 333 /* JSDocPropertyTag */; + return node.kind === 337 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocImplementsTag(node) { - return node.kind === 316 /* JSDocImplementsTag */; + return node.kind === 319 /* JSDocImplementsTag */; } ts.isJSDocImplementsTag = isJSDocImplementsTag; // Synthesized list /* @internal */ function isSyntaxList(n) { - return n.kind === 334 /* SyntaxList */; + return n.kind === 338 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; })(ts || (ts = {})); @@ -27384,7 +28023,7 @@ var ts; return ts.setTextRange(factory.createElementAccessExpression(target, memberName.expression), location); } else { - var expression = ts.setTextRange(ts.isIdentifierOrPrivateIdentifier(memberName) + var expression = ts.setTextRange(ts.isMemberName(memberName) ? factory.createPropertyAccessExpression(target, memberName) : factory.createElementAccessExpression(target, memberName), memberName); ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */; @@ -27566,14 +28205,14 @@ var ts; ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals."); } switch (property.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return createExpressionForAccessorDeclaration(factory, node.properties, property, receiver, !!node.multiLine); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return createExpressionForPropertyAssignment(factory, property, receiver); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(factory, property, receiver); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return createExpressionForMethodDeclaration(factory, property, receiver); } } @@ -27626,21 +28265,21 @@ var ts; } ts.startsWithUseStrict = startsWithUseStrict; function isCommaSequence(node) { - return node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || - node.kind === 337 /* CommaListExpression */; + return node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || + node.kind === 341 /* CommaListExpression */; } ts.isCommaSequence = isCommaSequence; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 15 /* All */; } switch (node.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return (kinds & 1 /* Parentheses */) !== 0; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return (kinds & 2 /* TypeAssertions */) !== 0; - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return (kinds & 4 /* NonNullAssertions */) !== 0; - case 336 /* PartiallyEmittedExpression */: + case 340 /* PartiallyEmittedExpression */: return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -27761,10 +28400,10 @@ var ts; var name = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name) ? name : factory.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 261 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 262 /* ImportDeclaration */ && node.importClause) { return factory.getGeneratedNameForNode(node); } - if (node.kind === 267 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 268 /* ExportDeclaration */ && node.moduleSpecifier) { return factory.getGeneratedNameForNode(node); } return undefined; @@ -27883,7 +28522,7 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // `b` in `({ a: b } = ...)` // `b` in `({ a: b = 1 } = ...)` // `{b}` in `({ a: {b} } = ...)` @@ -27895,11 +28534,11 @@ var ts; // `b[0]` in `({ a: b[0] } = ...)` // `b[0]` in `({ a: b[0] = 1 } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: // `a` in `({ a } = ...)` // `a` in `({ a = 1 } = ...)` return bindingElement.name; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } @@ -27931,12 +28570,12 @@ var ts; */ function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 160 /* Parameter */: - case 198 /* BindingElement */: + case 161 /* Parameter */: + case 199 /* BindingElement */: // `...` in `let [...a] = ...` return bindingElement.dotDotDotToken; - case 220 /* SpreadElement */: - case 290 /* SpreadAssignment */: + case 221 /* SpreadElement */: + case 291 /* SpreadAssignment */: // `...` in `[...a] = ...` return bindingElement; } @@ -27954,7 +28593,7 @@ var ts; ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 198 /* BindingElement */: + case 199 /* BindingElement */: // `a` in `let { a: b } = ...` // `[a]` in `let { [a]: b } = ...` // `"a"` in `let { "a": b } = ...` @@ -27969,7 +28608,7 @@ var ts; : propertyName; } break; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // `a` in `({ a: b } = ...)` // `[a]` in `({ [a]: b } = ...)` // `"a"` in `({ "a": b } = ...)` @@ -27984,7 +28623,7 @@ var ts; : propertyName; } break; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) { return ts.Debug.failBadSyntaxKind(bindingElement.name); @@ -28007,13 +28646,13 @@ var ts; */ function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: - case 199 /* ArrayLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + case 200 /* ArrayLiteralExpression */: // `a` in `{a}` // `a` in `[a]` return name.elements; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: // `a` in `{a}` return name.properties; } @@ -28034,46 +28673,294 @@ var ts; ts.getJSDocTypeAliasName = getJSDocTypeAliasName; function canHaveModifiers(node) { var kind = node.kind; - return kind === 160 /* Parameter */ - || kind === 162 /* PropertySignature */ - || kind === 163 /* PropertyDeclaration */ - || kind === 164 /* MethodSignature */ - || kind === 165 /* MethodDeclaration */ - || kind === 166 /* Constructor */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 171 /* IndexSignature */ - || kind === 208 /* FunctionExpression */ - || kind === 209 /* ArrowFunction */ - || kind === 221 /* ClassExpression */ - || kind === 232 /* VariableStatement */ - || kind === 251 /* FunctionDeclaration */ - || kind === 252 /* ClassDeclaration */ - || kind === 253 /* InterfaceDeclaration */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 255 /* EnumDeclaration */ - || kind === 256 /* ModuleDeclaration */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 261 /* ImportDeclaration */ - || kind === 266 /* ExportAssignment */ - || kind === 267 /* ExportDeclaration */; + return kind === 161 /* Parameter */ + || kind === 163 /* PropertySignature */ + || kind === 164 /* PropertyDeclaration */ + || kind === 165 /* MethodSignature */ + || kind === 166 /* MethodDeclaration */ + || kind === 167 /* Constructor */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 172 /* IndexSignature */ + || kind === 209 /* FunctionExpression */ + || kind === 210 /* ArrowFunction */ + || kind === 222 /* ClassExpression */ + || kind === 233 /* VariableStatement */ + || kind === 252 /* FunctionDeclaration */ + || kind === 253 /* ClassDeclaration */ + || kind === 254 /* InterfaceDeclaration */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 256 /* EnumDeclaration */ + || kind === 257 /* ModuleDeclaration */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 262 /* ImportDeclaration */ + || kind === 267 /* ExportAssignment */ + || kind === 268 /* ExportDeclaration */; } ts.canHaveModifiers = canHaveModifiers; - /* @internal */ - function isExportModifier(node) { - return node.kind === 92 /* ExportKeyword */; - } - ts.isExportModifier = isExportModifier; - /* @internal */ - function isAsyncModifier(node) { - return node.kind === 129 /* AsyncKeyword */; - } - ts.isAsyncModifier = isAsyncModifier; - /* @internal */ - function isStaticModifier(node) { - return node.kind === 123 /* StaticKeyword */; + ts.isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); + ts.isQuestionOrExclamationToken = ts.or(ts.isQuestionToken, ts.isExclamationToken); + ts.isIdentifierOrThisTypeNode = ts.or(ts.isIdentifier, ts.isThisTypeNode); + ts.isReadonlyKeywordOrPlusOrMinusToken = ts.or(ts.isReadonlyKeyword, ts.isPlusToken, ts.isMinusToken); + ts.isQuestionOrPlusOrMinusToken = ts.or(ts.isQuestionToken, ts.isPlusToken, ts.isMinusToken); + ts.isModuleName = ts.or(ts.isIdentifier, ts.isStringLiteral); + function isLiteralTypeLikeExpression(node) { + var kind = node.kind; + return kind === 103 /* NullKeyword */ + || kind === 109 /* TrueKeyword */ + || kind === 94 /* FalseKeyword */ + || ts.isLiteralExpression(node) + || ts.isPrefixUnaryExpression(node); + } + ts.isLiteralTypeLikeExpression = isLiteralTypeLikeExpression; + function isExponentiationOperator(kind) { + return kind === 42 /* AsteriskAsteriskToken */; + } + function isMultiplicativeOperator(kind) { + return kind === 41 /* AsteriskToken */ + || kind === 43 /* SlashToken */ + || kind === 44 /* PercentToken */; + } + function isMultiplicativeOperatorOrHigher(kind) { + return isExponentiationOperator(kind) + || isMultiplicativeOperator(kind); + } + function isAdditiveOperator(kind) { + return kind === 39 /* PlusToken */ + || kind === 40 /* MinusToken */; + } + function isAdditiveOperatorOrHigher(kind) { + return isAdditiveOperator(kind) + || isMultiplicativeOperatorOrHigher(kind); + } + function isShiftOperator(kind) { + return kind === 47 /* LessThanLessThanToken */ + || kind === 48 /* GreaterThanGreaterThanToken */ + || kind === 49 /* GreaterThanGreaterThanGreaterThanToken */; + } + function isShiftOperatorOrHigher(kind) { + return isShiftOperator(kind) + || isAdditiveOperatorOrHigher(kind); + } + function isRelationalOperator(kind) { + return kind === 29 /* LessThanToken */ + || kind === 32 /* LessThanEqualsToken */ + || kind === 31 /* GreaterThanToken */ + || kind === 33 /* GreaterThanEqualsToken */ + || kind === 101 /* InstanceOfKeyword */ + || kind === 100 /* InKeyword */; + } + function isRelationalOperatorOrHigher(kind) { + return isRelationalOperator(kind) + || isShiftOperatorOrHigher(kind); + } + function isEqualityOperator(kind) { + return kind === 34 /* EqualsEqualsToken */ + || kind === 36 /* EqualsEqualsEqualsToken */ + || kind === 35 /* ExclamationEqualsToken */ + || kind === 37 /* ExclamationEqualsEqualsToken */; + } + function isEqualityOperatorOrHigher(kind) { + return isEqualityOperator(kind) + || isRelationalOperatorOrHigher(kind); + } + function isBitwiseOperator(kind) { + return kind === 50 /* AmpersandToken */ + || kind === 51 /* BarToken */ + || kind === 52 /* CaretToken */; + } + function isBitwiseOperatorOrHigher(kind) { + return isBitwiseOperator(kind) + || isEqualityOperatorOrHigher(kind); + } + // NOTE: The version in utilities includes ExclamationToken, which is not a binary operator. + function isLogicalOperator(kind) { + return kind === 55 /* AmpersandAmpersandToken */ + || kind === 56 /* BarBarToken */; + } + function isLogicalOperatorOrHigher(kind) { + return isLogicalOperator(kind) + || isBitwiseOperatorOrHigher(kind); + } + function isAssignmentOperatorOrHigher(kind) { + return kind === 60 /* QuestionQuestionToken */ + || isLogicalOperatorOrHigher(kind) + || ts.isAssignmentOperator(kind); + } + function isBinaryOperator(kind) { + return isAssignmentOperatorOrHigher(kind) + || kind === 27 /* CommaToken */; + } + function isBinaryOperatorToken(node) { + return isBinaryOperator(node.kind); + } + ts.isBinaryOperatorToken = isBinaryOperatorToken; + var BinaryExpressionState; + (function (BinaryExpressionState) { + /** + * Handles walking into a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function enter(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, outerState) { + var prevUserState = stackIndex > 0 ? userStateStack[stackIndex - 1] : undefined; + ts.Debug.assertEqual(stateStack[stackIndex], enter); + userStateStack[stackIndex] = machine.onEnter(nodeStack[stackIndex], prevUserState, outerState); + stateStack[stackIndex] = nextState(machine, enter); + return stackIndex; + } + BinaryExpressionState.enter = enter; + /** + * Handles walking the `left` side of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function left(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], left); + ts.Debug.assertIsDefined(machine.onLeft); + stateStack[stackIndex] = nextState(machine, left); + var nextNode = machine.onLeft(nodeStack[stackIndex].left, userStateStack[stackIndex], nodeStack[stackIndex]); + if (nextNode) { + checkCircularity(stackIndex, nodeStack, nextNode); + return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode); + } + return stackIndex; + } + BinaryExpressionState.left = left; + /** + * Handles walking the `operatorToken` of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function operator(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], operator); + ts.Debug.assertIsDefined(machine.onOperator); + stateStack[stackIndex] = nextState(machine, operator); + machine.onOperator(nodeStack[stackIndex].operatorToken, userStateStack[stackIndex], nodeStack[stackIndex]); + return stackIndex; + } + BinaryExpressionState.operator = operator; + /** + * Handles walking the `right` side of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function right(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], right); + ts.Debug.assertIsDefined(machine.onRight); + stateStack[stackIndex] = nextState(machine, right); + var nextNode = machine.onRight(nodeStack[stackIndex].right, userStateStack[stackIndex], nodeStack[stackIndex]); + if (nextNode) { + checkCircularity(stackIndex, nodeStack, nextNode); + return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode); + } + return stackIndex; + } + BinaryExpressionState.right = right; + /** + * Handles walking out of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function exit(machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], exit); + stateStack[stackIndex] = nextState(machine, exit); + var result = machine.onExit(nodeStack[stackIndex], userStateStack[stackIndex]); + if (stackIndex > 0) { + stackIndex--; + if (machine.foldState) { + var side = stateStack[stackIndex] === exit ? "right" : "left"; + userStateStack[stackIndex] = machine.foldState(userStateStack[stackIndex], result, side); + } + } + else { + resultHolder.value = result; + } + return stackIndex; + } + BinaryExpressionState.exit = exit; + /** + * Handles a frame that is already done. + * @returns The `done` state. + */ + function done(_machine, stackIndex, stateStack, _nodeStack, _userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], done); + return stackIndex; + } + BinaryExpressionState.done = done; + function nextState(machine, currentState) { + switch (currentState) { + case enter: + if (machine.onLeft) + return left; + // falls through + case left: + if (machine.onOperator) + return operator; + // falls through + case operator: + if (machine.onRight) + return right; + // falls through + case right: return exit; + case exit: return done; + case done: return done; + default: ts.Debug.fail("Invalid state"); + } + } + BinaryExpressionState.nextState = nextState; + function pushStack(stackIndex, stateStack, nodeStack, userStateStack, node) { + stackIndex++; + stateStack[stackIndex] = enter; + nodeStack[stackIndex] = node; + userStateStack[stackIndex] = undefined; + return stackIndex; + } + function checkCircularity(stackIndex, nodeStack, node) { + if (ts.Debug.shouldAssert(2 /* Aggressive */)) { + while (stackIndex >= 0) { + ts.Debug.assert(nodeStack[stackIndex] !== node, "Circular traversal detected."); + stackIndex--; + } + } + } + })(BinaryExpressionState || (BinaryExpressionState = {})); + /** + * Holds state machine handler functions + */ + var BinaryExpressionStateMachine = /** @class */ (function () { + function BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState) { + this.onEnter = onEnter; + this.onLeft = onLeft; + this.onOperator = onOperator; + this.onRight = onRight; + this.onExit = onExit; + this.foldState = foldState; + } + return BinaryExpressionStateMachine; + }()); + function createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState) { + var machine = new BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState); + return trampoline; + function trampoline(node, outerState) { + var resultHolder = { value: undefined }; + var stateStack = [BinaryExpressionState.enter]; + var nodeStack = [node]; + var userStateStack = [undefined]; + var stackIndex = 0; + while (stateStack[stackIndex] !== BinaryExpressionState.done) { + stackIndex = stateStack[stackIndex](machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, outerState); + } + ts.Debug.assertEqual(stackIndex, 0); + return resultHolder.value; + } } - ts.isStaticModifier = isStaticModifier; + ts.createBinaryExpressionTrampoline = createBinaryExpressionTrampoline; })(ts || (ts = {})); var ts; (function (ts) { @@ -28155,19 +29042,19 @@ var ts; * that they appear in the source code. The language service depends on this property to locate nodes by position. */ function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 156 /* LastToken */) { + if (!node || node.kind <= 157 /* LastToken */) { return; } switch (node.kind) { - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -28175,9 +29062,9 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: return visitNode(cbNode, node.expression); - case 160 /* Parameter */: + case 161 /* Parameter */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || @@ -28185,7 +29072,7 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -28193,51 +29080,51 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.initializer); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -28249,374 +29136,390 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return visitNode(cbNode, node.assertsModifier) || visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return visitNodes(cbNode, cbNodes, node.members); - case 178 /* ArrayType */: + case 179 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 179 /* TupleType */: + case 180 /* TupleType */: return visitNodes(cbNode, cbNodes, node.elements); - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: return visitNodes(cbNode, cbNodes, node.types); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return visitNode(cbNode, node.checkType) || visitNode(cbNode, node.extendsType) || visitNode(cbNode, node.trueType) || visitNode(cbNode, node.falseType); - case 185 /* InferType */: + case 186 /* InferType */: return visitNode(cbNode, node.typeParameter); - case 195 /* ImportType */: + case 196 /* ImportType */: return visitNode(cbNode, node.argument) || visitNode(cbNode, node.qualifier) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 186 /* ParenthesizedType */: - case 188 /* TypeOperator */: + case 187 /* ParenthesizedType */: + case 189 /* TypeOperator */: return visitNode(cbNode, node.type); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 190 /* MappedType */: + case 191 /* MappedType */: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.nameType) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 191 /* LiteralType */: + case 192 /* LiteralType */: return visitNode(cbNode, node.literal); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: return visitNodes(cbNode, cbNodes, node.elements); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitNodes(cbNode, cbNodes, node.properties); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || visitNode(cbNode, node.name); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || visitNode(cbNode, node.argumentExpression); - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.template); - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 224 /* AsExpression */: + case 225 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return visitNode(cbNode, node.expression); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return visitNode(cbNode, node.name); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return visitNode(cbNode, node.expression); - case 230 /* Block */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 258 /* ModuleBlock */: return visitNodes(cbNode, cbNodes, node.statements); - case 297 /* SourceFile */: + case 298 /* SourceFile */: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return visitNodes(cbNode, cbNodes, node.declarations); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 240 /* ContinueStatement */: - case 241 /* BreakStatement */: + case 241 /* ContinueStatement */: + case 242 /* BreakStatement */: return visitNode(cbNode, node.label); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return visitNodes(cbNode, cbNodes, node.clauses); - case 284 /* CaseClause */: + case 285 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: return visitNodes(cbNode, cbNodes, node.statements); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 161 /* Decorator */: + case 162 /* Decorator */: return visitNode(cbNode, node.expression); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 291 /* EnumMember */: + case 292 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: return visitNode(cbNode, node.name); - case 264 /* NamedImports */: - case 268 /* NamedExports */: + case 265 /* NamedImports */: + case 269 /* NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 194 /* TemplateLiteralTypeSpan */: + case 195 /* TemplateLiteralTypeSpan */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.literal); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: return visitNodes(cbNode, cbNodes, node.types); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 271 /* MissingDeclaration */: + case 272 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return visitNode(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingFragment); - case 274 /* JsxSelfClosingElement */: - case 275 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 282 /* JsxSpreadAttribute */: + case 283 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 276 /* JsxClosingElement */: + case 277 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 180 /* OptionalType */: - case 181 /* RestType */: - case 301 /* JSDocTypeExpression */: - case 306 /* JSDocNonNullableType */: - case 305 /* JSDocNullableType */: - case 307 /* JSDocOptionalType */: - case 309 /* JSDocVariadicType */: + case 181 /* OptionalType */: + case 182 /* RestType */: + case 302 /* JSDocTypeExpression */: + case 307 /* JSDocNonNullableType */: + case 306 /* JSDocNullableType */: + case 308 /* JSDocOptionalType */: + case 310 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 311 /* JSDocComment */: - return visitNodes(cbNode, cbNodes, node.tags); - case 332 /* JSDocSeeTag */: + case 312 /* JSDocComment */: + return (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) + || visitNodes(cbNode, cbNodes, node.tags); + case 336 /* JSDocSeeTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.name); - case 302 /* JSDocNameReference */: + visitNode(cbNode, node.name) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 303 /* JSDocNameReference */: return visitNode(cbNode, node.name); - case 326 /* JSDocParameterTag */: - case 333 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: return visitNode(cbNode, node.tagName) || (node.isNameFirst ? visitNode(cbNode, node.name) || - visitNode(cbNode, node.typeExpression) + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) : visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.name)); - case 317 /* JSDocAuthorTag */: - return visitNode(cbNode, node.tagName); - case 316 /* JSDocImplementsTag */: + visitNode(cbNode, node.name)) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 320 /* JSDocAuthorTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.class); - case 315 /* JSDocAugmentsTag */: + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 319 /* JSDocImplementsTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.class); - case 330 /* JSDocTemplateTag */: + visitNode(cbNode, node.class) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 318 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 334 /* JSDocTemplateTag */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.constraint) || - visitNodes(cbNode, cbNodes, node.typeParameters); - case 331 /* JSDocTypedefTag */: + visitNodes(cbNode, cbNodes, node.typeParameters) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 335 /* JSDocTypedefTag */: return visitNode(cbNode, node.tagName) || (node.typeExpression && - node.typeExpression.kind === 301 /* JSDocTypeExpression */ + node.typeExpression.kind === 302 /* JSDocTypeExpression */ ? visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName) + visitNode(cbNode, node.fullName) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) : visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression)); - case 324 /* JSDocCallbackTag */: + visitNode(cbNode, node.typeExpression)) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 328 /* JSDocCallbackTag */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression); - case 327 /* JSDocReturnTag */: - case 329 /* JSDocTypeTag */: - case 328 /* JSDocThisTag */: - case 325 /* JSDocEnumTag */: + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 331 /* JSDocReturnTag */: + case 333 /* JSDocTypeTag */: + case 332 /* JSDocThisTag */: + case 329 /* JSDocEnumTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.typeExpression); - case 313 /* JSDocSignature */: + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 315 /* JSDocSignature */: return ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 312 /* JSDocTypeLiteral */: + case 316 /* JSDocLink */: + return visitNode(cbNode, node.name); + case 314 /* JSDocTypeLiteral */: return ts.forEach(node.jsDocPropertyTags, cbNode); - case 314 /* JSDocTag */: - case 319 /* JSDocClassTag */: - case 320 /* JSDocPublicTag */: - case 321 /* JSDocPrivateTag */: - case 322 /* JSDocProtectedTag */: - case 323 /* JSDocReadonlyTag */: - return visitNode(cbNode, node.tagName); - case 336 /* PartiallyEmittedExpression */: + case 317 /* JSDocTag */: + case 322 /* JSDocClassTag */: + case 323 /* JSDocPublicTag */: + case 324 /* JSDocPrivateTag */: + case 325 /* JSDocProtectedTag */: + case 326 /* JSDocReadonlyTag */: + case 321 /* JSDocDeprecatedTag */: + return visitNode(cbNode, node.tagName) + || (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 340 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -28636,62 +29539,58 @@ var ts; * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure. */ function forEachChildRecursively(rootNode, cbNode, cbNodes) { - var stack = [rootNode]; - while (stack.length) { - var parent = stack.pop(); - var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent)); - if (res) { - return res; - } - } - return; - function gatherPossibleChildren(node) { - var children = []; - forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal - return children; - function addWorkItem(n) { - children.unshift(n); - } - } - function visitAllPossibleChildren(parent, children) { - for (var _i = 0, children_5 = children; _i < children_5.length; _i++) { - var child = children_5[_i]; - if (ts.isArray(child)) { - if (cbNodes) { - var res = cbNodes(child, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - } - for (var i = child.length - 1; i >= 0; i--) { - var realChild = child[i]; - var res = cbNode(realChild, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - stack.push(realChild); - } - } - else { - stack.push(child); - var res = cbNode(child, parent); + var queue = gatherPossibleChildren(rootNode); + var parents = []; // tracks parent references for elements in queue + while (parents.length < queue.length) { + parents.push(rootNode); + } + while (queue.length !== 0) { + var current = queue.pop(); + var parent = parents.pop(); + if (ts.isArray(current)) { + if (cbNodes) { + var res = cbNodes(current, parent); if (res) { if (res === "skip") continue; return res; } } + for (var i = current.length - 1; i >= 0; --i) { + queue.push(current[i]); + parents.push(parent); + } + } + else { + var res = cbNode(current, parent); + if (res) { + if (res === "skip") + continue; + return res; + } + if (current.kind >= 158 /* FirstNode */) { + // add children in reverse order to the queue, so popping gives the first child + for (var _i = 0, _a = gatherPossibleChildren(current); _i < _a.length; _i++) { + var child = _a[_i]; + queue.push(child); + parents.push(current); + } + } } } } ts.forEachChildRecursively = forEachChildRecursively; + function gatherPossibleChildren(node) { + var children = []; + forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal + return children; + function addWorkItem(n) { + children.unshift(n); + } + } function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeParse"); var result; ts.perfLogger.logStartParseSourceFile(fileName); @@ -28704,7 +29603,7 @@ var ts; ts.perfLogger.logStopParseSourceFile(); ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } ts.createSourceFile = createSourceFile; @@ -28886,11 +29785,12 @@ var ts; // attached to the EOF token. var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + var _a; if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); if (scriptKind === 6 /* JSON */) { var result_3 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); - ts.convertToObjectWorker(result_3, result_3.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + ts.convertToObjectWorker(result_3, (_a = result_3.statements[0]) === null || _a === void 0 ? void 0 : _a.expression, result_3.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); result_3.referencedFiles = ts.emptyArray; result_3.typeReferenceDirectives = ts.emptyArray; result_3.libReferenceDirectives = ts.emptyArray; @@ -28930,35 +29830,54 @@ var ts; endOfFileToken = parseTokenNode(); } else { - var expression = void 0; - switch (token()) { - case 22 /* OpenBracketToken */: - expression = parseArrayLiteralExpression(); - break; - case 109 /* TrueKeyword */: - case 94 /* FalseKeyword */: - case 103 /* NullKeyword */: - expression = parseTokenNode(); - break; - case 40 /* MinusToken */: - if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) { - expression = parsePrefixUnaryExpression(); - } - else { - expression = parseObjectLiteralExpression(); - } - break; - case 8 /* NumericLiteral */: - case 10 /* StringLiteral */: - if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) { - expression = parseLiteralNode(); + // Loop and synthesize an ArrayLiteralExpression if there are more than + // one top-level expressions to ensure all input text is consumed. + var expressions = void 0; + while (token() !== 1 /* EndOfFileToken */) { + var expression_1 = void 0; + switch (token()) { + case 22 /* OpenBracketToken */: + expression_1 = parseArrayLiteralExpression(); + break; + case 109 /* TrueKeyword */: + case 94 /* FalseKeyword */: + case 103 /* NullKeyword */: + expression_1 = parseTokenNode(); + break; + case 40 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) { + expression_1 = parsePrefixUnaryExpression(); + } + else { + expression_1 = parseObjectLiteralExpression(); + } break; + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) { + expression_1 = parseLiteralNode(); + break; + } + // falls through + default: + expression_1 = parseObjectLiteralExpression(); + break; + } + // Error recovery: collect multiple top-level expressions + if (expressions && ts.isArray(expressions)) { + expressions.push(expression_1); + } + else if (expressions) { + expressions = [expressions, expression_1]; + } + else { + expressions = expression_1; + if (token() !== 1 /* EndOfFileToken */) { + parseErrorAtCurrentToken(ts.Diagnostics.Unexpected_token); } - // falls through - default: - expression = parseObjectLiteralExpression(); - break; + } } + var expression = ts.isArray(expressions) ? finishNode(factory.createArrayLiteralExpression(expressions), pos) : ts.Debug.checkDefined(expressions); var statement = factory.createExpressionStatement(expression); finishNode(statement, pos); statements = createNodeArray([statement], pos); @@ -29153,7 +30072,7 @@ var ts; return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements)); function containsPossibleTopLevelAwait(node) { return !(node.flags & 32768 /* AwaitContext */) - && !!(node.transformFlags & 8388608 /* ContainsPossibleTopLevelAwait */); + && !!(node.transformFlags & 16777216 /* ContainsPossibleTopLevelAwait */); } function findNextStatementWithAwait(statements, start) { for (var i = start; i < statements.length; i++) { @@ -29194,7 +30113,7 @@ var ts; ts.setTextRangePosWidth(sourceFile, 0, sourceText.length); setExternalModuleIndicator(sourceFile); // If we parsed this as an external module, it may contain top-level await - if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 8388608 /* ContainsPossibleTopLevelAwait */) { + if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 16777216 /* ContainsPossibleTopLevelAwait */) { sourceFile = reparseTopLevelAwait(sourceFile); } sourceFile.text = sourceText; @@ -29565,7 +30484,7 @@ var ts; ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, "", "", /*templateFlags*/ undefined) : kind === 8 /* NumericLiteral */ ? factory.createNumericLiteral("", /*numericLiteralFlags*/ undefined) : kind === 10 /* StringLiteral */ ? factory.createStringLiteral("", /*isSingleQuote*/ undefined) : - kind === 271 /* MissingDeclaration */ ? factory.createMissingDeclaration() : + kind === 272 /* MissingDeclaration */ ? factory.createMissingDeclaration() : factory.createToken(kind); return finishNode(result, pos); } @@ -29580,8 +30499,8 @@ var ts; // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for // each identifier in order to reduce memory consumption. function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) { - identifierCount++; if (isIdentifier) { + identifierCount++; var pos = getNodePos(); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker var originalKeywordKind = token(); @@ -29593,6 +30512,11 @@ var ts; parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); return createIdentifier(/*isIdentifier*/ true); } + if (token() === 0 /* Unknown */ && scanner.tryScan(function () { return scanner.reScanInvalidIdentifier() === 78 /* Identifier */; })) { + // Scanner has already recorded an 'Invalid character' error, so no need to add another from the parser. + return createIdentifier(/*isIdentifier*/ true); + } + identifierCount++; // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; var isReservedWord = scanner.isReservedWord(); @@ -29947,8 +30871,7 @@ var ts; var listPos = getNodePos(); while (!isListTerminator(kind)) { if (isListElement(kind, /*inErrorRecovery*/ false)) { - var element = parseListElement(kind, parseElement); - list.push(element); + list.push(parseListElement(kind, parseElement)); continue; } if (abortParsingListOrMoveToNextToken(kind)) { @@ -30098,14 +31021,14 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 166 /* Constructor */: - case 171 /* IndexSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 163 /* PropertyDeclaration */: - case 229 /* SemicolonClassElement */: + case 167 /* Constructor */: + case 172 /* IndexSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 230 /* SemicolonClassElement */: return true; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. @@ -30120,8 +31043,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: return true; } } @@ -30130,58 +31053,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 232 /* VariableStatement */: - case 230 /* Block */: - case 234 /* IfStatement */: - case 233 /* ExpressionStatement */: - case 246 /* ThrowStatement */: - case 242 /* ReturnStatement */: - case 244 /* SwitchStatement */: - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 237 /* ForStatement */: - case 236 /* WhileStatement */: - case 243 /* WithStatement */: - case 231 /* EmptyStatement */: - case 247 /* TryStatement */: - case 245 /* LabeledStatement */: - case 235 /* DoStatement */: - case 248 /* DebuggerStatement */: - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 252 /* FunctionDeclaration */: + case 233 /* VariableStatement */: + case 231 /* Block */: + case 235 /* IfStatement */: + case 234 /* ExpressionStatement */: + case 247 /* ThrowStatement */: + case 243 /* ReturnStatement */: + case 245 /* SwitchStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 238 /* ForStatement */: + case 237 /* WhileStatement */: + case 244 /* WithStatement */: + case 232 /* EmptyStatement */: + case 248 /* TryStatement */: + case 246 /* LabeledStatement */: + case 236 /* DoStatement */: + case 249 /* DebuggerStatement */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 291 /* EnumMember */; + return node.kind === 292 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 170 /* ConstructSignature */: - case 164 /* MethodSignature */: - case 171 /* IndexSignature */: - case 162 /* PropertySignature */: - case 169 /* CallSignature */: + case 171 /* ConstructSignature */: + case 165 /* MethodSignature */: + case 172 /* IndexSignature */: + case 163 /* PropertySignature */: + case 170 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 249 /* VariableDeclaration */) { + if (node.kind !== 250 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -30202,7 +31125,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 160 /* Parameter */) { + if (node.kind !== 161 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -30483,14 +31406,14 @@ var ts; // If true, we should abort parsing an error function. function typeHasArrowFunctionBlockingParseError(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return ts.nodeIsMissing(node.typeName); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: { + case 175 /* FunctionType */: + case 176 /* ConstructorType */: { var _a = node, parameters = _a.parameters, type = _a.type; return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); } - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return typeHasArrowFunctionBlockingParseError(node.type); default: return false; @@ -30671,19 +31594,21 @@ var ts; function parseParameterWorker(inOuterAwaitContext) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); + // FormalParameter [Yield,Await]: + // BindingElement[?Yield,?Await] + // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. + var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); if (token() === 107 /* ThisKeyword */) { - var node_1 = factory.createParameterDeclaration( - /*decorators*/ undefined, + var node_1 = factory.createParameterDeclaration(decorators, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), /*questionToken*/ undefined, parseTypeAnnotation(), /*initializer*/ undefined); + if (decorators) { + parseErrorAtRange(decorators[0], ts.Diagnostics.Decorators_may_not_be_applied_to_this_parameters); + } return withJSDoc(finishNode(node_1, pos), hasJSDoc); } - // FormalParameter [Yield,Await]: - // BindingElement[?Yield,?Await] - // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. - var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); var savedTopLevel = topLevel; topLevel = false; var modifiers = parseModifiers(); @@ -30770,14 +31695,14 @@ var ts; function parseSignatureMember(kind) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); - if (kind === 170 /* ConstructSignature */) { + if (kind === 171 /* ConstructSignature */) { parseExpected(102 /* NewKeyword */); } var typeParameters = parseTypeParameters(); var parameters = parseParameters(4 /* Type */); var type = parseReturnType(58 /* ColonToken */, /*isType*/ true); parseTypeMemberSemicolon(); - var node = kind === 169 /* CallSignature */ + var node = kind === 170 /* CallSignature */ ? factory.createCallSignature(typeParameters, parameters, type) : factory.createConstructSignature(typeParameters, parameters, type); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -30868,7 +31793,10 @@ var ts; } function isTypeMemberStart() { // Return true if we have the start of a signature member - if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) { + if (token() === 20 /* OpenParenToken */ || + token() === 29 /* LessThanToken */ || + token() === 134 /* GetKeyword */ || + token() === 146 /* SetKeyword */) { return true; } var idToken = false; @@ -30900,14 +31828,20 @@ var ts; } function parseTypeMember() { if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) { - return parseSignatureMember(169 /* CallSignature */); + return parseSignatureMember(170 /* CallSignature */); } if (token() === 102 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(170 /* ConstructSignature */); + return parseSignatureMember(171 /* ConstructSignature */); } var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiers(); + if (parseContextualModifier(134 /* GetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 168 /* GetAccessor */); + } + if (parseContextualModifier(146 /* SetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 169 /* SetAccessor */); + } if (isIndexSignature()) { return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers); } @@ -31940,7 +32874,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand, pos); } function isInOrOfKeyword(t) { - return t === 100 /* InKeyword */ || t === 156 /* OfKeyword */; + return t === 100 /* InKeyword */ || t === 157 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand, pos) { while (true) { @@ -32080,7 +33014,7 @@ var ts; if (token() === 42 /* AsteriskAsteriskToken */) { var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); var end = simpleUnaryExpression.end; - if (simpleUnaryExpression.kind === 206 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 207 /* TypeAssertionExpression */) { parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -32331,7 +33265,7 @@ var ts; var pos = getNodePos(); var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 275 /* JsxOpeningElement */) { + if (opening.kind === 276 /* JsxOpeningElement */) { var children = parseJsxChildren(opening); var closingElement = parseJsxClosingElement(inExpressionContext); if (!tagNamesAreEquivalent(opening.tagName, closingElement.tagName)) { @@ -32339,11 +33273,11 @@ var ts; } result = finishNode(factory.createJsxElement(opening, children, closingElement), pos); } - else if (opening.kind === 278 /* JsxOpeningFragment */) { + else if (opening.kind === 279 /* JsxOpeningFragment */) { result = finishNode(factory.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos); } else { - ts.Debug.assert(opening.kind === 274 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 275 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -32843,10 +33777,10 @@ var ts; var decorators = parseDecorators(); var modifiers = parseModifiers(); if (parseContextualModifier(134 /* GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167 /* GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* GetAccessor */); } if (parseContextualModifier(146 /* SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 169 /* SetAccessor */); } var asteriskToken = parseOptionalToken(41 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); @@ -32964,6 +33898,7 @@ var ts; // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); var openBracePosition = scanner.getTokenPos(); if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { var multiLine = scanner.hasPrecedingLineBreak(); @@ -32974,11 +33909,16 @@ var ts; ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); } } - return finishNode(factory.createBlock(statements, multiLine), pos); + var result = withJSDoc(finishNode(factory.createBlock(statements, multiLine), pos), hasJSDoc); + if (token() === 62 /* EqualsToken */) { + parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses); + nextToken(); + } + return result; } else { var statements = createMissingList(); - return finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos); + return withJSDoc(finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos), hasJSDoc); } } function parseFunctionBlock(flags, diagnosticMessage) { @@ -33005,21 +33945,24 @@ var ts; } function parseEmptyStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(26 /* SemicolonToken */); - return finishNode(factory.createEmptyStatement(), pos); + return withJSDoc(finishNode(factory.createEmptyStatement(), pos), hasJSDoc); } function parseIfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(98 /* IfKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var thenStatement = parseStatement(); var elseStatement = parseOptional(90 /* ElseKeyword */) ? parseStatement() : undefined; - return finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos); + return withJSDoc(finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc); } function parseDoStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(89 /* DoKeyword */); var statement = parseStatement(); parseExpected(114 /* WhileKeyword */); @@ -33031,19 +33974,21 @@ var ts; // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. parseOptional(26 /* SemicolonToken */); - return finishNode(factory.createDoStatement(statement, expression), pos); + return withJSDoc(finishNode(factory.createDoStatement(statement, expression), pos), hasJSDoc); } function parseWhileStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(114 /* WhileKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var statement = parseStatement(); - return finishNode(factory.createWhileStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWhileStatement(expression, statement), pos), hasJSDoc); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(96 /* ForKeyword */); var awaitToken = parseOptionalToken(130 /* AwaitKeyword */); parseExpected(20 /* OpenParenToken */); @@ -33057,7 +34002,7 @@ var ts; } } var node; - if (awaitToken ? parseExpected(156 /* OfKeyword */) : parseOptional(156 /* OfKeyword */)) { + if (awaitToken ? parseExpected(157 /* OfKeyword */) : parseOptional(157 /* OfKeyword */)) { var expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(21 /* CloseParenToken */); node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement()); @@ -33079,33 +34024,36 @@ var ts; parseExpected(21 /* CloseParenToken */); node = factory.createForStatement(initializer, condition, incrementor, parseStatement()); } - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseBreakOrContinueStatement(kind) { var pos = getNodePos(); - parseExpected(kind === 241 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */); + var hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(kind === 242 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */); var label = canParseSemicolon() ? undefined : parseIdentifier(); parseSemicolon(); - var node = kind === 241 /* BreakStatement */ + var node = kind === 242 /* BreakStatement */ ? factory.createBreakStatement(label) : factory.createContinueStatement(label); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseReturnStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(104 /* ReturnKeyword */); var expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression); parseSemicolon(); - return finishNode(factory.createReturnStatement(expression), pos); + return withJSDoc(finishNode(factory.createReturnStatement(expression), pos), hasJSDoc); } function parseWithStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(115 /* WithKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement); - return finishNode(factory.createWithStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWithStatement(expression, statement), pos), hasJSDoc); } function parseCaseClause() { var pos = getNodePos(); @@ -33134,17 +34082,19 @@ var ts; } function parseSwitchStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(106 /* SwitchKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var caseBlock = parseCaseBlock(); - return finishNode(factory.createSwitchStatement(expression, caseBlock), pos); + return withJSDoc(finishNode(factory.createSwitchStatement(expression, caseBlock), pos), hasJSDoc); } function parseThrowStatement() { // ThrowStatement[Yield] : // throw [no LineTerminator here]Expression[In, ?Yield]; var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(108 /* ThrowKeyword */); // Because of automatic semicolon insertion, we need to report error if this // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' @@ -33157,11 +34107,12 @@ var ts; expression = finishNode(factory.createIdentifier(""), getNodePos()); } parseSemicolon(); - return finishNode(factory.createThrowStatement(expression), pos); + return withJSDoc(finishNode(factory.createThrowStatement(expression), pos), hasJSDoc); } // TODO: Review for error recovery function parseTryStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(110 /* TryKeyword */); var tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); var catchClause = token() === 82 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -33172,7 +34123,7 @@ var ts; parseExpected(95 /* FinallyKeyword */); finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } - return finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos); + return withJSDoc(finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); } function parseCatchClause() { var pos = getNodePos(); @@ -33191,9 +34142,10 @@ var ts; } function parseDebuggerStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(86 /* DebuggerKeyword */); parseSemicolon(); - return finishNode(factory.createDebuggerStatement(), pos); + return withJSDoc(finishNode(factory.createDebuggerStatement(), pos), hasJSDoc); } function parseExpressionOrLabeledStatement() { // Avoiding having to do the lookahead for a labeled statement by just trying to parse @@ -33401,9 +34353,9 @@ var ts; case 96 /* ForKeyword */: return parseForOrForInOrForOfStatement(); case 85 /* ContinueKeyword */: - return parseBreakOrContinueStatement(240 /* ContinueStatement */); + return parseBreakOrContinueStatement(241 /* ContinueStatement */); case 80 /* BreakKeyword */: - return parseBreakOrContinueStatement(241 /* BreakStatement */); + return parseBreakOrContinueStatement(242 /* BreakStatement */); case 104 /* ReturnKeyword */: return parseReturnStatement(); case 115 /* WithKeyword */: @@ -33523,7 +34475,7 @@ var ts; if (decorators || modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - var missing = createMissingNode(271 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var missing = createMissingNode(272 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); ts.setTextRangePos(missing, pos); missing.decorators = decorators; missing.modifiers = modifiers; @@ -33605,6 +34557,7 @@ var ts; } function parseVariableDeclaration(allowExclamation) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); var name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations); var exclamationToken; if (allowExclamation && name.kind === 78 /* Identifier */ && @@ -33614,7 +34567,7 @@ var ts; var type = parseTypeAnnotation(); var initializer = isInOrOfKeyword(token()) ? undefined : parseInitializer(); var node = factory.createVariableDeclaration(name, exclamationToken, type, initializer); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseVariableDeclarationList(inForStatementInitializer) { var pos = getNodePos(); @@ -33642,7 +34595,7 @@ var ts; // this context. // The checker will then give an error that there is an empty declaration list. var declarations; - if (token() === 156 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 157 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { declarations = createMissingList(); } else { @@ -33746,12 +34699,12 @@ var ts; var parameters = parseParameters(0 /* None */); var type = parseReturnType(58 /* ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(0 /* None */); - var node = kind === 167 /* GetAccessor */ + var node = kind === 168 /* GetAccessor */ ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body); // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors node.typeParameters = typeParameters; - if (type && node.kind === 168 /* SetAccessor */) + if (type && node.kind === 169 /* SetAccessor */) node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -33894,10 +34847,10 @@ var ts; var decorators = parseDecorators(); var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); if (parseContextualModifier(134 /* GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167 /* GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* GetAccessor */); } if (parseContextualModifier(146 /* SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 169 /* SetAccessor */); } if (token() === 132 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) { var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers); @@ -33936,10 +34889,10 @@ var ts; return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, 221 /* ClassExpression */); + return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, 222 /* ClassExpression */); } function parseClassDeclaration(pos, hasJSDoc, decorators, modifiers) { - return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 252 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 253 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, kind) { var savedAwaitContext = inAwaitContext(); @@ -33961,7 +34914,7 @@ var ts; members = createMissingList(); } setAwaitContext(savedAwaitContext); - var node = kind === 252 /* ClassDeclaration */ + var node = kind === 253 /* ClassDeclaration */ ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -34200,7 +35153,7 @@ var ts; var namedBindings; if (!identifier || parseOptional(27 /* CommaToken */)) { - namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(264 /* NamedImports */); + namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(265 /* NamedImports */); } return finishNode(factory.createImportClause(isTypeOnly, identifier, namedBindings), pos); } @@ -34248,16 +35201,16 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - var node = kind === 264 /* NamedImports */ + var node = kind === 265 /* NamedImports */ ? factory.createNamedImports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseImportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */)) : factory.createNamedExports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */)); return finishNode(node, pos); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(270 /* ExportSpecifier */); + return parseImportOrExportSpecifier(271 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(265 /* ImportSpecifier */); + return parseImportOrExportSpecifier(266 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var pos = getNodePos(); @@ -34284,10 +35237,10 @@ var ts; else { name = identifierName; } - if (kind === 265 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 266 /* ImportSpecifier */ && checkIdentifierIsKeyword) { parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } - var node = kind === 265 /* ImportSpecifier */ + var node = kind === 266 /* ImportSpecifier */ ? factory.createImportSpecifier(propertyName, name) : factory.createExportSpecifier(propertyName, name); return finishNode(node, pos); @@ -34310,7 +35263,7 @@ var ts; moduleSpecifier = parseModuleSpecifier(); } else { - exportClause = parseNamedImportsOrExports(268 /* NamedExports */); + exportClause = parseNamedImportsOrExports(269 /* NamedExports */); // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. @@ -34499,7 +35452,10 @@ var ts; var tags; var tagsPos; var tagsEnd; + var linkEnd; + var commentsPos; var comments = []; + var parts = []; // + 3 for leading /**, - 5 in total for /** */ return scanner.scanRange(start + 3, length - 5, function () { // Initially we can parse out a tag. We also have seen a starting asterisk. @@ -34528,6 +35484,8 @@ var ts; case 59 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingWhitespace(comments); + if (!commentsPos) + commentsPos = getNodePos(); addTag(parseTag(indent)); // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning @@ -34570,6 +35528,22 @@ var ts; break; case 1 /* EndOfFileToken */: break loop; + case 18 /* OpenBraceToken */: + state = 2 /* SavingComments */; + var commentEnd = scanner.getStartPos(); + var linkStart = scanner.getTextPos() - 1; + var link = parseJSDocLink(linkStart); + if (link) { + if (!linkEnd) { + removeLeadingNewlines(comments); + } + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : start, commentEnd)); + parts.push(link); + comments = []; + linkEnd = scanner.getTextPos(); + break; + } + // fallthrough if it's not a {@link sequence default: // 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 @@ -34580,9 +35554,14 @@ var ts; } nextTokenJSDoc(); } - removeLeadingNewlines(comments); removeTrailingWhitespace(comments); - return createJSDocComment(); + if (parts.length && comments.length) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : start, commentsPos)); + } + if (parts.length && tags) + ts.Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); + var tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); + return finishNode(factory.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : comments.length ? comments.join("") : undefined, tagsArray), start, end); }); function removeLeadingNewlines(comments) { while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { @@ -34594,11 +35573,6 @@ var ts; comments.pop(); } } - function createJSDocComment() { - var comment = comments.length ? comments.join("") : undefined; - var tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); - return finishNode(factory.createJSDocComment(comment, tagsArray), start, end); - } function isNextNonwhitespaceTokenEndOfFile() { // We must use infinite lookahead, as there could be any number of newlines :( while (true) { @@ -34678,6 +35652,9 @@ var ts; case "readonly": tag = parseSimpleTag(start, factory.createJSDocReadonlyTag, tagName, margin, indentText); break; + case "override": + tag = parseSimpleTag(start, factory.createJSDocOverrideTag, tagName, margin, indentText); + break; case "deprecated": hasDeprecatedTag = true; tag = parseSimpleTag(start, factory.createJSDocDeprecatedTag, tagName, margin, indentText); @@ -34725,8 +35702,12 @@ var ts; return parseTagComments(margin, indentText.slice(margin)); } function parseTagComments(indent, initialMargin) { + var commentsPos = getNodePos(); var comments = []; + var parts = []; + var linkEnd; var state = 0 /* BeginningOfLine */; + var previousWhitespace = true; var margin; function pushComment(text) { if (!margin) { @@ -34752,7 +35733,9 @@ var ts; indent = 0; break; case 59 /* AtToken */: - if (state === 3 /* SavingBackticks */) { + if (state === 3 /* SavingBackticks */ + || state === 2 /* SavingComments */ && (!previousWhitespace || lookAhead(isNextJSDocTokenWhitespace))) { + // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace or not before whitespace comments.push(scanner.getTokenText()); break; } @@ -34776,13 +35759,18 @@ var ts; break; case 18 /* OpenBraceToken */: state = 2 /* SavingComments */; - if (lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) { - pushComment(scanner.getTokenText()); - nextTokenJSDoc(); + var commentEnd = scanner.getStartPos(); + var linkStart = scanner.getTextPos() - 1; + var link = parseJSDocLink(linkStart); + if (link) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : commentsPos, commentEnd)); + parts.push(link); + comments = []; + linkEnd = scanner.getTextPos(); + } + else { pushComment(scanner.getTokenText()); - nextTokenJSDoc(); } - pushComment(scanner.getTokenText()); break; case 61 /* BacktickToken */: if (state === 3 /* SavingBackticks */) { @@ -34809,15 +35797,51 @@ var ts; pushComment(scanner.getTokenText()); break; } + previousWhitespace = token() === 5 /* WhitespaceTrivia */; tok = nextTokenJSDoc(); } removeLeadingNewlines(comments); removeTrailingWhitespace(comments); - return comments.length === 0 ? undefined : comments.join(""); + if (parts.length) { + if (comments.length) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : commentsPos)); + } + return createNodeArray(parts, commentsPos, scanner.getTextPos()); + } + else if (comments.length) { + return comments.join(""); + } + } + function isNextJSDocTokenWhitespace() { + var next = nextTokenJSDoc(); + return next === 5 /* WhitespaceTrivia */ || next === 4 /* NewLineTrivia */; + } + function parseJSDocLink(start) { + if (!tryParse(parseJSDocLinkPrefix)) { + return undefined; + } + nextTokenJSDoc(); // start at token after link, then skip any whitespace + skipWhitespace(); + // parseEntityName logs an error for non-identifier, so create a MissingNode ourselves to avoid the error + var name = ts.tokenIsIdentifierOrKeyword(token()) + ? parseEntityName(/*allowReservedWords*/ true) + : undefined; + var text = []; + while (token() !== 19 /* CloseBraceToken */ && token() !== 4 /* NewLineTrivia */ && token() !== 1 /* EndOfFileToken */) { + text.push(scanner.getTokenText()); + nextTokenJSDoc(); + } + return finishNode(factory.createJSDocLink(name, text.join("")), start, scanner.getTextPos()); + } + function parseJSDocLinkPrefix() { + skipWhitespaceOrAsterisk(); + return token() === 18 /* OpenBraceToken */ + && nextTokenJSDoc() === 59 /* AtToken */ + && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) + && scanner.getTokenValue() === "link"; } function parseUnknownTag(start, tagName, indent, indentText) { - var end = getNodePos(); - return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function addTag(tag) { if (!tag) { @@ -34862,7 +35886,7 @@ var ts; switch (node.kind) { case 145 /* ObjectKeyword */: return true; - case 178 /* ArrayType */: + case 179 /* ArrayType */: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments; @@ -34873,11 +35897,11 @@ var ts; var isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; - skipWhitespace(); - if (isNameFirst) { + var indentText = skipWhitespaceOrAsterisk(); + if (isNameFirst && !lookAhead(parseJSDocLinkPrefix)) { typeExpression = tryParseTypeExpression(); } - var comment = parseTagComments(indent + scanner.getStartPos() - start); + var comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; @@ -34894,12 +35918,12 @@ var ts; var child = void 0; var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { - if (child.kind === 326 /* JSDocParameterTag */ || child.kind === 333 /* JSDocPropertyTag */) { + if (child.kind === 330 /* JSDocParameterTag */ || child.kind === 337 /* JSDocPropertyTag */) { children = ts.append(children, child); } } if (children) { - var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 178 /* ArrayType */), pos); + var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 179 /* ArrayType */), pos); return finishNode(factory.createJSDocTypeExpression(literal), pos); } } @@ -34909,27 +35933,34 @@ var ts; parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeExpression = tryParseTypeExpression(); - var end = getNodePos(); - return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function parseTypeTag(start, tagName, indent, indentText) { if (ts.some(tags, ts.isJSDocTypeTag)) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); - var end = getNodePos(); - var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined; - return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start, end); + var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; + return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start); } function parseSeeTag(start, tagName, indent, indentText) { - var nameExpression = parseJSDocNameReference(); - var end = getNodePos(); - var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined; - return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start, end); + var isLink = lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; }); + var nameExpression = isLink ? undefined : parseJSDocNameReference(); + var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; + return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start); } function parseAuthorTag(start, tagName, indent, indentText) { - var comments = parseAuthorNameAndEmail() + (parseTrailingTagComments(start, end, indent, indentText) || ""); - return finishNode(factory.createJSDocAuthorTag(tagName, comments || undefined), start); + var commentStart = getNodePos(); + var textOnly = parseAuthorNameAndEmail(); + var commentEnd = scanner.getStartPos(); + var comments = parseTrailingTagComments(start, commentEnd, indent, indentText); + if (!comments) { + commentEnd = scanner.getStartPos(); + } + var allParts = typeof comments !== "string" + ? createNodeArray(ts.concatenate([finishNode(textOnly, commentStart, commentEnd)], comments), commentStart) // cast away readonly + : textOnly.text + comments; + return finishNode(factory.createJSDocAuthorTag(tagName, allParts), start); } function parseAuthorNameAndEmail() { var comments = []; @@ -34950,17 +35981,15 @@ var ts; comments.push(scanner.getTokenText()); token = nextTokenJSDoc(); } - return comments.join(""); + return factory.createJSDocText(comments.join("")); } function parseImplementsTag(start, tagName, margin, indentText) { var className = parseExpressionWithTypeArgumentsForAugments(); - var end = getNodePos(); - return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseAugmentsTag(start, tagName, margin, indentText) { var className = parseExpressionWithTypeArgumentsForAugments(); - var end = getNodePos(); - return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseExpressionWithTypeArgumentsForAugments() { var usedBrace = parseOptional(18 /* OpenBraceToken */); @@ -34984,20 +36013,17 @@ var ts; return node; } function parseSimpleTag(start, createTag, tagName, margin, indentText) { - var end = getNodePos(); - return finishNode(createTag(tagName, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(createTag(tagName, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseThisTag(start, tagName, margin, indentText) { var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); - var end = getNodePos(); - return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseEnumTag(start, tagName, margin, indentText) { var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); - var end = getNodePos(); - return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseTypedefTag(start, tagName, indent, indentText) { var _a; @@ -35014,7 +36040,7 @@ var ts; var hasChildren = false; while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { hasChildren = true; - if (child.kind === 329 /* JSDocTypeTag */) { + if (child.kind === 333 /* JSDocTypeTag */) { if (childTypeTag) { parseErrorAtCurrentToken(ts.Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags); var lastError = ts.lastOrUndefined(parseDiagnostics); @@ -35032,7 +36058,7 @@ var ts; } } if (hasChildren) { - var isArrayType = typeExpression && typeExpression.type.kind === 178 /* ArrayType */; + var isArrayType = typeExpression && typeExpression.type.kind === 179 /* ArrayType */; var jsdocTypeLiteral = factory.createJSDocTypeLiteral(jsDocPropertyTags, isArrayType); typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : @@ -35085,17 +36111,16 @@ var ts; var returnTag = tryParse(function () { if (parseOptionalJsdoc(59 /* AtToken */)) { var tag = parseTag(indent); - if (tag && tag.kind === 327 /* JSDocReturnTag */) { + if (tag && tag.kind === 331 /* JSDocReturnTag */) { return tag; } } }); var typeExpression = finishNode(factory.createJSDocSignature(/*typeParameters*/ undefined, parameters, returnTag), start); - var end = getNodePos(); if (!comment) { - comment = parseTrailingTagComments(start, end, indent, indentText); + comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); } - return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start, end); + return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start); } function escapedTextsEqual(a, b) { while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { @@ -35120,7 +36145,7 @@ var ts; case 59 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target, indent); - if (child && (child.kind === 326 /* JSDocParameterTag */ || child.kind === 333 /* JSDocPropertyTag */) && + if (child && (child.kind === 330 /* JSDocParameterTag */ || child.kind === 337 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -35177,6 +36202,9 @@ var ts; function parseTemplateTagTypeParameter() { var typeParameterPos = getNodePos(); var name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); + if (ts.nodeIsMissing(name)) { + return undefined; + } return finishNode(factory.createTypeParameterDeclaration(name, /*constraint*/ undefined, /*defaultType*/ undefined), typeParameterPos); } function parseTemplateTagTypeParameters() { @@ -35184,7 +36212,10 @@ var ts; var typeParameters = []; do { skipWhitespace(); - typeParameters.push(parseTemplateTagTypeParameter()); + var node = parseTemplateTagTypeParameter(); + if (node !== undefined) { + typeParameters.push(node); + } skipWhitespaceOrAsterisk(); } while (parseOptionalJsdoc(27 /* CommaToken */)); return createNodeArray(typeParameters, pos); @@ -35203,8 +36234,7 @@ var ts; // TODO: Consider only parsing a single type parameter if there is a constraint. var constraint = token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; var typeParameters = parseTemplateTagTypeParameters(); - var end = getNodePos(); - return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function parseOptionalJsdoc(t) { if (token() === t) { @@ -36019,6 +37049,7 @@ var ts; ["es2018", "lib.es2018.d.ts"], ["es2019", "lib.es2019.d.ts"], ["es2020", "lib.es2020.d.ts"], + ["es2021", "lib.es2021.d.ts"], ["esnext", "lib.esnext.d.ts"], // Host only ["dom", "lib.dom.d.ts"], @@ -36058,14 +37089,17 @@ var ts; ["es2020.string", "lib.es2020.string.d.ts"], ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"], ["es2020.intl", "lib.es2020.intl.d.ts"], + ["es2021.promise", "lib.es2021.promise.d.ts"], + ["es2021.string", "lib.es2021.string.d.ts"], + ["es2021.weakref", "lib.es2021.weakref.d.ts"], ["esnext.array", "lib.es2019.array.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"], ["esnext.intl", "lib.esnext.intl.d.ts"], ["esnext.bigint", "lib.es2020.bigint.d.ts"], - ["esnext.string", "lib.esnext.string.d.ts"], - ["esnext.promise", "lib.esnext.promise.d.ts"], - ["esnext.weakref", "lib.esnext.weakref.d.ts"] + ["esnext.string", "lib.es2021.string.d.ts"], + ["esnext.promise", "lib.es2021.promise.d.ts"], + ["esnext.weakref", "lib.es2021.weakref.d.ts"] ]; /** * An array of supported "lib" reference file names used to determine the order for inclusion @@ -36089,11 +37123,12 @@ var ts; fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval, prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval, dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling, + fixedchunksizepolling: ts.WatchFileKind.FixedChunkSizePolling, usefsevents: ts.WatchFileKind.UseFsEvents, usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory, })), category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory, + description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling_UseFsEvents_UseFsEventsOnParentDirectory, }, { name: "watchDirectory", @@ -36101,9 +37136,10 @@ var ts; usefsevents: ts.WatchDirectoryKind.UseFsEvents, fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval, dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling, + fixedchunksizepolling: ts.WatchDirectoryKind.FixedChunkSizePolling, })), category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling, + description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling, }, { name: "fallbackPolling", @@ -36111,9 +37147,10 @@ var ts; fixedinterval: ts.PollingWatchKind.FixedInterval, priorityinterval: ts.PollingWatchKind.PriorityInterval, dynamicpriority: ts.PollingWatchKind.DynamicPriority, + fixedchunksize: ts.PollingWatchKind.FixedChunkSize, })), category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority, + description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority_FixedChunkSize, }, { name: "synchronousWatchDirectory", @@ -36272,6 +37309,7 @@ var ts; es2018: 5 /* ES2018 */, es2019: 6 /* ES2019 */, es2020: 7 /* ES2020 */, + es2021: 8 /* ES2021 */, esnext: 99 /* ESNext */, })), affectsSourceFile: true, @@ -36280,10 +37318,10 @@ var ts; paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT, }; - /* @internal */ - ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsWithoutBuild = [ + // CommandLine only options { name: "all", type: "boolean", @@ -36646,6 +37684,14 @@ var ts; category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Include_undefined_in_index_signature_results }, + { + name: "noImplicitOverride", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier + }, { name: "noPropertyAccessFromIndexSignature", type: "boolean", @@ -37061,7 +38107,9 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins }, - ]); + ]; + /* @internal */ + ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsWithoutBuild); /* @internal */ ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); /* @internal */ @@ -37076,8 +38124,7 @@ var ts; ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) { return ts.hasProperty(option, "transpileOptionValue"); }); - /* @internal */ - ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsOnlyBuild = [ { name: "verbose", shortName: "v", @@ -37105,7 +38152,9 @@ var ts; description: ts.Diagnostics.Delete_the_outputs_of_all_projects, type: "boolean" } - ]); + ]; + /* @internal */ + ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsOnlyBuild); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -37159,6 +38208,10 @@ var ts; return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations)); } ts.getOptionsNameMap = getOptionsNameMap; + var compilerOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_only_be_used_with_build, + getOptionsNameMap: getBuildOptionsNameMap + }; /* @internal */ ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, @@ -37220,6 +38273,10 @@ var ts; return option.name; } function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) { + var _a; + if ((_a = diagnostics.alternateMode) === null || _a === void 0 ? void 0 : _a.getOptionsNameMap().optionsNameMap.has(unknownOption.toLowerCase())) { + return createDiagnostics(diagnostics.alternateMode.diagnostic, unknownOption); + } var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName); return possibleOption ? createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : @@ -37374,6 +38431,7 @@ var ts; } /*@internal*/ ts.compilerOptionsDidYouMeanDiagnostics = { + alternateMode: compilerOptionsAlternateMode, getOptionsNameMap: getOptionsNameMap, optionDeclarations: ts.optionDeclarations, unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, @@ -37406,7 +38464,12 @@ var ts; function getBuildOptionsNameMap() { return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts)); } + var buildOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_not_be_used_with_build, + getOptionsNameMap: getOptionsNameMap + }; var buildOptionsDidYouMeanDiagnostics = { + alternateMode: buildOptionsAlternateMode, getOptionsNameMap: getBuildOptionsNameMap, optionDeclarations: ts.buildOpts, unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0, @@ -37482,7 +38545,7 @@ var ts; function parseConfigFileTextToJson(fileName, jsonText) { var jsonSourceFile = ts.parseJsonText(fileName, jsonText); return { - config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + config: convertConfigFileToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics, /*reportOptionsErrors*/ false, /*optionsIterator*/ undefined), error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined }; } @@ -37612,11 +38675,31 @@ var ts; } return _tsconfigRootOptions; } + function convertConfigFileToObject(sourceFile, errors, reportOptionsErrors, optionsIterator) { + var _a; + var rootExpression = (_a = sourceFile.statements[0]) === null || _a === void 0 ? void 0 : _a.expression; + var knownRootOptions = reportOptionsErrors ? getTsconfigRootOptionsMap() : undefined; + if (rootExpression && rootExpression.kind !== 201 /* ObjectLiteralExpression */) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, rootExpression, ts.Diagnostics.The_root_value_of_a_0_file_must_be_an_object, ts.getBaseFileName(sourceFile.fileName) === "jsconfig.json" ? "jsconfig.json" : "tsconfig.json")); + // Last-ditch error recovery. Somewhat useful because the JSON parser will recover from some parse errors by + // synthesizing a top-level array literal expression. There's a reasonable chance the first element of that + // array is a well-formed configuration object, made into an array element by stray characters. + if (ts.isArrayLiteralExpression(rootExpression)) { + var firstObject = ts.find(rootExpression.elements, ts.isObjectLiteralExpression); + if (firstObject) { + return convertToObjectWorker(sourceFile, firstObject, errors, /*returnValue*/ true, knownRootOptions, optionsIterator); + } + } + return {}; + } + return convertToObjectWorker(sourceFile, rootExpression, errors, /*returnValue*/ true, knownRootOptions, optionsIterator); + } /** * Convert the json syntax tree into the json value */ function convertToObject(sourceFile, errors) { - return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + var _a; + return convertToObjectWorker(sourceFile, (_a = sourceFile.statements[0]) === null || _a === void 0 ? void 0 : _a.expression, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); } ts.convertToObject = convertToObject; /** @@ -37625,18 +38708,18 @@ var ts; * Otherwise it just checks the errors and returns undefined */ /*@internal*/ - function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { - if (!sourceFile.statements.length) { + function convertToObjectWorker(sourceFile, rootExpression, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!rootExpression) { return returnValue ? {} : undefined; } - return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + return convertPropertyValueToJson(rootExpression, knownRootOptions); function isRootOptionMap(knownOptions) { return knownRootOptions && knownRootOptions.elementOptions === knownOptions; } function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) { var result = returnValue ? {} : undefined; var _loop_4 = function (element) { - if (element.kind !== 288 /* PropertyAssignment */) { + if (element.kind !== 289 /* PropertyAssignment */) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); return "continue"; } @@ -37730,13 +38813,13 @@ var ts; case 8 /* NumericLiteral */: reportInvalidOptionValue(option && option.type !== "number"); return validateValue(Number(valueExpression.text)); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { break; // not valid JSON syntax } reportInvalidOptionValue(option && option.type !== "number"); return validateValue(-Number(valueExpression.operand.text)); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; // Currently having element option declaration in the tsconfig with type "object" @@ -37753,7 +38836,7 @@ var ts; return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined)); } - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: reportInvalidOptionValue(option && option.type !== "list"); return validateValue(convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element)); } @@ -38301,14 +39384,14 @@ var ts; if (ownConfig.extendedConfigPath) { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, resolutionStack, errors, extendedConfigCache); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { var baseRaw_1 = extendedConfig.raw; var raw_1 = ownConfig.raw; + var relativeDifference_1; var setPropertyInRawIfNotUndefined = function (propertyName) { - var value = raw_1[propertyName] || baseRaw_1[propertyName]; - if (value) { - raw_1[propertyName] = value; + if (!raw_1[propertyName] && baseRaw_1[propertyName]) { + raw_1[propertyName] = ts.map(baseRaw_1[propertyName], function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1 || (relativeDifference_1 = ts.convertToRelativePath(ts.getDirectoryPath(ownConfig.extendedConfigPath), basePath, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames))), path); }); } }; setPropertyInRawIfNotUndefined("include"); @@ -38390,7 +39473,7 @@ var ts; } } }; - var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); + var json = convertConfigFileToObject(sourceFile, errors, /*reportOptionsErrors*/ true, optionsIterator); if (!typeAcquisition) { if (typingOptionstypeAcquisition) { typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? @@ -38428,7 +39511,7 @@ var ts; errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig)); return undefined; } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) { + function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache) { var _a; var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath); var value; @@ -38440,22 +39523,7 @@ var ts; else { extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (!extendedResult.parseDiagnostics.length) { - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); - if (isSuccessfulParsedTsconfig(extendedConfig)) { - // Update the paths to reflect base path - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); - var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; - var mapPropertiesInRawIfNotUndefined = function (propertyName) { - if (raw_2[propertyName]) { - raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); - } - }; - var raw_2 = extendedConfig.raw; - mapPropertiesInRawIfNotUndefined("include"); - mapPropertiesInRawIfNotUndefined("exclude"); - mapPropertiesInRawIfNotUndefined("files"); - } + extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, ts.getDirectoryPath(extendedConfigPath), ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); } if (extendedConfigCache) { extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig }); @@ -39152,13 +40220,24 @@ var ts; * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache) { var traceEnabled = isTraceEnabled(options, host); if (redirectedReference) { options = redirectedReference.commandLine.options; } - var failedLookupLocations = []; - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var containingDirectory = containingFile ? ts.getDirectoryPath(containingFile) : undefined; + var perFolderCache = containingDirectory ? cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference) : undefined; + var result = perFolderCache && perFolderCache.get(typeReferenceDirectiveName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile); + if (redirectedReference) + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + trace(host, ts.Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory); + traceResult(result); + } + return result; + } var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -39181,6 +40260,8 @@ var ts; trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); } } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -39191,17 +40272,31 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); - if (traceEnabled) { - if (packageId) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, ts.packageIdToString(packageId), primary); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); - } + resolvedTypeReferenceDirective = { + primary: primary, + resolvedFileName: resolvedFileName, + originalPath: fileName === resolvedFileName ? undefined : fileName, + packageId: packageId, + isExternalLibraryImport: pathContainsNodeModules(fileName), + }; + } + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, result); + if (traceEnabled) + traceResult(result); + return result; + function traceResult(result) { + var _a; + if (!((_a = result.resolvedTypeReferenceDirective) === null || _a === void 0 ? void 0 : _a.resolvedFileName)) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + else if (result.resolvedTypeReferenceDirective.packageId) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, ts.packageIdToString(result.resolvedTypeReferenceDirective.packageId), result.resolvedTypeReferenceDirective.primary); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, result.resolvedTypeReferenceDirective.primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } - return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { // Check primary library paths if (typeRoots && typeRoots.length) { @@ -39231,20 +40326,16 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = void 0; + var result_4; if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); - result = searchResult && searchResult.value; + result_4 = searchResult && searchResult.value; } else { var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; - result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); - } - var resolvedFile = resolvedTypeScriptOnly(result); - if (!resolvedFile && traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + result_4 = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); } - return resolvedFile; + return resolvedTypeScriptOnly(result_4); } else { if (traceEnabled) { @@ -39299,22 +40390,21 @@ var ts; return result; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; - function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) { - return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName); - } - ts.createModuleResolutionCache = createModuleResolutionCache; /*@internal*/ function createCacheWithRedirects(options) { var ownMap = new ts.Map(); var redirectsMap = new ts.Map(); return { - ownMap: ownMap, + getOwnMap: getOwnMap, redirectsMap: redirectsMap, getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, clear: clear, setOwnOptions: setOwnOptions, setOwnMap: setOwnMap }; + function getOwnMap() { + return ownMap; + } function setOwnOptions(newOptions) { options = newOptions; } @@ -39340,26 +40430,88 @@ var ts; } } ts.createCacheWithRedirects = createCacheWithRedirects; - /*@internal*/ - function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { - return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap }; + function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { + var cache; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear }; + function getPackageJsonInfo(packageJsonPath) { + return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); + } + function setPackageJsonInfo(packageJsonPath, info) { + (cache || (cache = new ts.Map())).set(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info); + } + function clear() { + cache = undefined; + } + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + function updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + if (!options.configFile) + return; + if (directoryToModuleNameMap.redirectsMap.size === 0) { + // The own map will be for projectCompilerOptions + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size === 0); + ts.Debug.assert(directoryToModuleNameMap.getOwnMap().size === 0); + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.getOwnMap().size === 0); + directoryToModuleNameMap.redirectsMap.set(options.configFile.path, directoryToModuleNameMap.getOwnMap()); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.redirectsMap.set(options.configFile.path, moduleNameToDirectoryMap.getOwnMap()); + } + else { + // Set correct own map + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size > 0); + var ref = { + sourceFile: options.configFile, + commandLine: { options: options } + }; + directoryToModuleNameMap.setOwnMap(directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnMap(moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); + } + directoryToModuleNameMap.setOwnOptions(options); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnOptions(options); + } + function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap) { + return { + getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, + clear: clear, + update: update, + }; + function clear() { + directoryToModuleNameMap.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap); + } function getOrCreateCacheForDirectory(directoryName, redirectedReference) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, function () { return new ts.Map(); }); } + } + function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + moduleNameToDirectoryMap || (moduleNameToDirectoryMap = createCacheWithRedirects(options)); + var packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName); + return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, + clear: clear, + update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; } }); + function clear() { + preDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + packageJsonInfoCache.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); + } function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); } - function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { - var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); - var result = cache.get(key); - if (!result) { - result = create(); - cache.set(key, result); - } - return result; - } function createPerModuleNameCache() { var directoryPathMap = new ts.Map(); return { get: get, set: set }; @@ -39426,7 +40578,17 @@ var ts; } } } - ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + ts.createModuleResolutionCache = createModuleResolutionCache; + function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { + var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); + return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + function clear() { + preDirectoryResolutionCache.clear(); + packageJsonInfoCache.clear(); + } + } + ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache) { var containingDirectory = ts.getDirectoryPath(containingFile); var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); @@ -39704,7 +40866,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, state.resultFromCache); function tryResolve(extensions) { @@ -39764,7 +40926,7 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { - var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined; return withPackageId(packageInfo, resolvedFromFile); } @@ -39797,8 +40959,9 @@ var ts; * For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo" * For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo" */ + /* @internal */ function parseNodeModuleFromPath(resolved) { - var path = ts.normalizePath(resolved.path); + var path = ts.normalizePath(resolved); var idx = path.lastIndexOf(ts.nodeModulesPathPart); if (idx === -1) { return undefined; @@ -39810,6 +40973,7 @@ var ts; } return path.slice(0, indexAfterPackageName); } + ts.parseNodeModuleFromPath = parseNodeModuleFromPath; function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; @@ -39893,21 +41057,43 @@ var ts; return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { + var _a, _b, _c; var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); + if (onlyRecordFailures) { + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + var existing = (_a = state.packageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfo(packageJsonPath); + if (existing !== undefined) { + if (typeof existing !== "boolean") { + if (traceEnabled) + trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + return existing; + } + else { + if (existing && traceEnabled) + trace(host, ts.Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + } + var directoryExists = ts.directoryProbablyExists(packageDirectory, host); if (directoryExists && host.fileExists(packageJsonPath)) { var packageJsonContent = ts.readJson(packageJsonPath, host); if (traceEnabled) { trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); - return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + return result; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + (_c = state.packageJsonInfoCache) === null || _c === void 0 ? void 0 : _c.setPackageJsonInfo(packageJsonPath, directoryExists); // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results state.failedLookupLocations.push(packageJsonPath); } @@ -40156,7 +41342,7 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath @@ -40197,13 +41383,13 @@ var ts; * This is the minumum code needed to expose that functionality; the rest is in the host. */ /* @internal */ - function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache, packageJsonInfoCache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache); } @@ -40249,26 +41435,26 @@ var ts; // A module is uninstantiated if it contains only switch (node.kind) { // 1. interface declarations, type alias declarations - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return 0 /* NonInstantiated */; // 2. const enum declarations - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: if (ts.isEnumConst(node)) { return 2 /* ConstEnumOnly */; } break; // 3. non-exported import declarations - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: if (!(ts.hasSyntacticModifier(node, 1 /* Export */))) { return 0 /* NonInstantiated */; } break; // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: var exportDeclaration = node; - if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 268 /* NamedExports */) { + if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 269 /* NamedExports */) { var state = 0 /* NonInstantiated */; for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; @@ -40284,7 +41470,7 @@ var ts; } break; // 5. other uninstantiated module declarations. - case 257 /* ModuleBlock */: { + case 258 /* ModuleBlock */: { var state_1 = 0 /* NonInstantiated */; ts.forEachChild(node, function (n) { var childState = getModuleInstanceStateCached(n, visited); @@ -40306,7 +41492,7 @@ var ts; }); return state_1; } - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return getModuleInstanceState(node, visited); case 78 /* Identifier */: // Only jsdoc typedef definition can exist in jsdoc namespace, and it should @@ -40378,14 +41564,14 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { - ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); ts.performance.measure("Bind", "beforeBind", "afterBind"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -40424,6 +41610,7 @@ var ts; var classifiableNames; var unreachableFlow = { flags: 1 /* Unreachable */ }; var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; + var bindBinaryExpressionFlow = createBindBinaryExpressionFlow(); /** * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) @@ -40506,7 +41693,7 @@ var ts; // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { - if (node.kind === 266 /* ExportAssignment */) { + if (node.kind === 267 /* ExportAssignment */) { return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; } var name = ts.getNameOfDeclaration(node); @@ -40515,7 +41702,7 @@ var ts; var moduleName = ts.getTextOfIdentifierOrLiteral(name); return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); } - if (name.kind === 158 /* ComputedPropertyName */) { + if (name.kind === 159 /* ComputedPropertyName */) { var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteralLike(nameExpression)) { @@ -40524,11 +41711,9 @@ var ts; if (ts.isSignedNumericLiteral(nameExpression)) { return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text; } - ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); - return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - if (ts.isWellKnownSymbolSyntactically(name)) { - return ts.getPropertyNameForKnownSymbolName(ts.idText(name.name)); + else { + ts.Debug.fail("Only computed properties with literal names have declaration names"); + } } if (ts.isPrivateIdentifier(name)) { // containingClass exists because private names only allowed inside classes @@ -40543,36 +41728,36 @@ var ts; return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return "__constructor" /* Constructor */; - case 174 /* FunctionType */: - case 169 /* CallSignature */: - case 313 /* JSDocSignature */: + case 175 /* FunctionType */: + case 170 /* CallSignature */: + case 315 /* JSDocSignature */: return "__call" /* Call */; - case 175 /* ConstructorType */: - case 170 /* ConstructSignature */: + case 176 /* ConstructorType */: + case 171 /* ConstructSignature */: return "__new" /* New */; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: return "__index" /* Index */; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return "__export" /* ExportStar */; - case 297 /* SourceFile */: + case 298 /* SourceFile */: // json file should behave as // module.exports = ... return "export=" /* ExportEquals */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); - case 160 /* Parameter */: + case 161 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 308 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + ts.Debug.assert(node.parent.kind === 309 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -40672,7 +41857,7 @@ var ts; // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if (symbol.declarations && symbol.declarations.length && - (node.kind === 266 /* ExportAssignment */ && !node.isExportEquals)) { + (node.kind === 267 /* ExportAssignment */ && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName_1 = false; multipleDefaultExports_1 = true; @@ -40711,7 +41896,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = !!(ts.getCombinedModifierFlags(node) & 1 /* Export */) || jsdocTreatAsExported(node); if (symbolFlags & 2097152 /* Alias */) { - if (node.kind === 270 /* ExportSpecifier */ || (node.kind === 260 /* ImportEqualsDeclaration */ && hasExportModifier)) { + if (node.kind === 271 /* ExportSpecifier */ || (node.kind === 261 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -40800,7 +41985,7 @@ var ts; // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. if (containerFlags & 1 /* IsContainer */) { - if (node.kind !== 209 /* ArrowFunction */) { + if (node.kind !== 210 /* ArrowFunction */) { thisParentContainer = container; } container = blockScopeContainer = node; @@ -40833,7 +42018,7 @@ var ts; } // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property initialization checks. - currentReturnTarget = isIIFE || node.kind === 166 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */)) ? createBranchLabel() : undefined; + currentReturnTarget = isIIFE || node.kind === 167 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 252 /* FunctionDeclaration */ || node.kind === 209 /* FunctionExpression */)) ? createBranchLabel() : undefined; currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; @@ -40848,13 +42033,14 @@ var ts; node.flags |= 512 /* HasExplicitReturn */; node.endFlowNode = currentFlow; } - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { node.flags |= emitFlags; + node.endFlowNode = currentFlow; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 166 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */))) { + if (node.kind === 167 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 252 /* FunctionDeclaration */ || node.kind === 209 /* FunctionExpression */))) { node.returnFlowNode = currentFlow; } } @@ -40881,8 +42067,8 @@ var ts; blockScopeContainer = savedBlockScopeContainer; } function bindEachFunctionsFirst(nodes) { - bindEach(nodes, function (n) { return n.kind === 251 /* FunctionDeclaration */ ? bind(n) : undefined; }); - bindEach(nodes, function (n) { return n.kind !== 251 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind === 252 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 252 /* FunctionDeclaration */ ? bind(n) : undefined; }); } function bindEach(nodes, bindFunction) { if (bindFunction === void 0) { bindFunction = bind; } @@ -40905,59 +42091,59 @@ var ts; inAssignmentPattern = saveInAssignmentPattern; return; } - if (node.kind >= 232 /* FirstStatement */ && node.kind <= 248 /* LastStatement */ && !options.allowUnreachableCode) { + if (node.kind >= 233 /* FirstStatement */ && node.kind <= 249 /* LastStatement */ && !options.allowUnreachableCode) { node.flowNode = currentFlow; } switch (node.kind) { - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: bindWhileStatement(node); break; - case 235 /* DoStatement */: + case 236 /* DoStatement */: bindDoStatement(node); break; - case 237 /* ForStatement */: + case 238 /* ForStatement */: bindForStatement(node); break; - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: bindForInOrForOfStatement(node); break; - case 234 /* IfStatement */: + case 235 /* IfStatement */: bindIfStatement(node); break; - case 242 /* ReturnStatement */: - case 246 /* ThrowStatement */: + case 243 /* ReturnStatement */: + case 247 /* ThrowStatement */: bindReturnOrThrow(node); break; - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 247 /* TryStatement */: + case 248 /* TryStatement */: bindTryStatement(node); break; - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: bindSwitchStatement(node); break; - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: bindCaseBlock(node); break; - case 284 /* CaseClause */: + case 285 /* CaseClause */: bindCaseClause(node); break; - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: bindExpressionStatement(node); break; - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: bindLabeledStatement(node); break; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: bindPostfixUnaryExpressionFlow(node); break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.isDestructuringAssignment(node)) { // Carry over whether we are in an assignment pattern to // binary expressions that could actually be an initializer @@ -40967,47 +42153,47 @@ var ts; } bindBinaryExpressionFlow(node); break; - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: bindDeleteExpressionFlow(node); break; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: bindConditionalExpressionFlow(node); break; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: bindVariableDeclarationFlow(node); break; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: bindAccessExpressionFlow(node); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: bindCallExpressionFlow(node); break; - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: bindNonNullExpressionFlow(node); break; - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: bindJSDocTypeAlias(node); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime - case 297 /* SourceFile */: { + case 298 /* SourceFile */: { bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); break; } - case 230 /* Block */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 258 /* ModuleBlock */: bindEachFunctionsFirst(node.statements); break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: bindBindingElementFlow(node); break; - case 200 /* ObjectLiteralExpression */: - case 199 /* ArrayLiteralExpression */: - case 288 /* PropertyAssignment */: - case 220 /* SpreadElement */: + case 201 /* ObjectLiteralExpression */: + case 200 /* ArrayLiteralExpression */: + case 289 /* PropertyAssignment */: + case 221 /* SpreadElement */: // Carry over whether we are in an assignment pattern of Object and Array literals // as well as their children that are valid assignment targets. inAssignmentPattern = saveInAssignmentPattern; @@ -41024,29 +42210,29 @@ var ts; case 78 /* Identifier */: case 79 /* PrivateIdentifier */: case 107 /* ThisKeyword */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return containsNarrowableReference(expr); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return hasNarrowableArgument(expr); - case 207 /* ParenthesizedExpression */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: return isNarrowingExpression(expr.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return isNarrowingBinaryExpression(expr); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return isNarrowingExpression(expr.expression); } return false; } function isNarrowableReference(expr) { - return expr.kind === 78 /* Identifier */ || expr.kind === 79 /* PrivateIdentifier */ || expr.kind === 107 /* ThisKeyword */ || expr.kind === 105 /* SuperKeyword */ || - (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isBinaryExpression(expr) && expr.operatorToken.kind === 27 /* CommaToken */ && isNarrowableReference(expr.right) || - ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || - ts.isAssignmentExpression(expr) && isNarrowableReference(expr.left); + return ts.isDottedName(expr) + || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) + || ts.isBinaryExpression(expr) && expr.operatorToken.kind === 27 /* CommaToken */ && isNarrowableReference(expr.right) + || ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) + || ts.isAssignmentExpression(expr) && isNarrowableReference(expr.left); } function containsNarrowableReference(expr) { return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression); @@ -41060,7 +42246,7 @@ var ts; } } } - if (expr.expression.kind === 201 /* PropertyAccessExpression */ && + if (expr.expression.kind === 202 /* PropertyAccessExpression */ && containsNarrowableReference(expr.expression.expression)) { return true; } @@ -41096,9 +42282,9 @@ var ts; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isNarrowableOperand(expr.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (expr.operatorToken.kind) { case 62 /* EqualsToken */: return isNarrowableOperand(expr.left); @@ -41174,26 +42360,26 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 234 /* IfStatement */: - case 236 /* WhileStatement */: - case 235 /* DoStatement */: + case 235 /* IfStatement */: + case 237 /* WhileStatement */: + case 236 /* DoStatement */: return parent.expression === node; - case 237 /* ForStatement */: - case 217 /* ConditionalExpression */: + case 238 /* ForStatement */: + case 218 /* ConditionalExpression */: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 207 /* ParenthesizedExpression */) { + if (node.kind === 208 /* ParenthesizedExpression */) { node = node.expression; } - else if (node.kind === 214 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) { + else if (node.kind === 215 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) { node = node.operand; } else { - return node.kind === 216 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ || + return node.kind === 217 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */); } @@ -41240,7 +42426,7 @@ var ts; } function setContinueTarget(node, target) { var label = activeLabelList; - while (label && node.parent.kind === 245 /* LabeledStatement */) { + while (label && node.parent.kind === 246 /* LabeledStatement */) { label.continueTarget = target; label = label.next; node = node.parent; @@ -41291,12 +42477,12 @@ var ts; bind(node.expression); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 239 /* ForOfStatement */) { + if (node.kind === 240 /* ForOfStatement */) { bind(node.awaitModifier); } addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 250 /* VariableDeclarationList */) { + if (node.initializer.kind !== 251 /* VariableDeclarationList */) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -41318,7 +42504,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 242 /* ReturnStatement */) { + if (node.kind === 243 /* ReturnStatement */) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -41335,7 +42521,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 241 /* BreakStatement */ ? breakTarget : continueTarget; + var flowLabel = node.kind === 242 /* BreakStatement */ ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -41440,7 +42626,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 285 /* DefaultClause */; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 286 /* DefaultClause */; }); // We mark a switch statement as possibly exhaustive if it has no default clause and if all // case clauses have unreachable end points (e.g. they all return). Note, we no longer need // this property in control flow analysis, it's there only for backwards compatibility. @@ -41488,9 +42674,9 @@ var ts; function maybeBindExpressionFlowIfCall(node) { // A top level or LHS of comma expression call expression with a dotted function name and at least one argument // is potentially an assertion and is therefore included in the control flow. - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { var call = node; - if (ts.isDottedName(call.expression) && call.expression.kind !== 105 /* SuperKeyword */) { + if (call.expression.kind !== 105 /* SuperKeyword */ && ts.isDottedName(call.expression)) { currentFlow = createFlowCall(currentFlow, call); } } @@ -41514,7 +42700,7 @@ var ts; currentFlow = finishFlowLabel(postStatementLabel); } function bindDestructuringTargetFlow(node) { - if (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) { + if (node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) { bindAssignmentTargetFlow(node.left); } else { @@ -41525,10 +42711,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node); } - else if (node.kind === 199 /* ArrayLiteralExpression */) { + else if (node.kind === 200 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 220 /* SpreadElement */) { + if (e.kind === 221 /* SpreadElement */) { bindAssignmentTargetFlow(e.expression); } else { @@ -41536,16 +42722,16 @@ var ts; } } } - else if (node.kind === 200 /* ObjectLiteralExpression */) { + else if (node.kind === 201 /* ObjectLiteralExpression */) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 288 /* PropertyAssignment */) { + if (p.kind === 289 /* PropertyAssignment */) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 289 /* ShorthandPropertyAssignment */) { + else if (p.kind === 290 /* ShorthandPropertyAssignment */) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 290 /* SpreadAssignment */) { + else if (p.kind === 291 /* SpreadAssignment */) { bindAssignmentTargetFlow(p.expression); } } @@ -41610,128 +42796,102 @@ var ts; } bindAssignmentTargetFlow(node.left); } - var BindBinaryExpressionFlowState; - (function (BindBinaryExpressionFlowState) { - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindThenBindChildren"] = 0] = "BindThenBindChildren"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["MaybeBindLeft"] = 1] = "MaybeBindLeft"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindToken"] = 2] = "BindToken"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindRight"] = 3] = "BindRight"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["FinishBind"] = 4] = "FinishBind"; - })(BindBinaryExpressionFlowState || (BindBinaryExpressionFlowState = {})); - function bindBinaryExpressionFlow(node) { - var workStacks = { - expr: [node], - state: [1 /* MaybeBindLeft */], - inStrictMode: [undefined], - parent: [undefined], - }; - var stackIndex = 0; - while (stackIndex >= 0) { - node = workStacks.expr[stackIndex]; - switch (workStacks.state[stackIndex]) { - case 0 /* BindThenBindChildren */: { - // This state is used only when recuring, to emulate the work that `bind` does before - // reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work. - ts.setParent(node, parent); - var saveInStrictMode = inStrictMode; - bindWorker(node); - var saveParent = parent; - parent = node; - advanceState(1 /* MaybeBindLeft */, saveInStrictMode, saveParent); - break; - } - case 1 /* MaybeBindLeft */: { - var operator = node.operatorToken.kind; - // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions - // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too - // For now, though, since the common cases are chained `+`, leaving it recursive is fine - if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */ || - ts.isLogicalOrCoalescingAssignmentOperator(operator)) { - if (isTopLevelLogicalExpression(node)) { - var postExpressionLabel = createBranchLabel(); - bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel); - currentFlow = finishFlowLabel(postExpressionLabel); - } - else { - bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget); - } - completeNode(); - } - else { - advanceState(2 /* BindToken */); - maybeBind(node.left); - } - break; + function createBindBinaryExpressionFlow() { + return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined); + function onEnter(node, state) { + if (state) { + state.stackIndex++; + // Emulate the work that `bind` does before reaching `bindChildren`. A normal call to + // `bindBinaryExpressionFlow` will already have done this work. + ts.setParent(node, parent); + var saveInStrictMode = inStrictMode; + bindWorker(node); + var saveParent = parent; + parent = node; + state.skip = false; + state.inStrictModeStack[state.stackIndex] = saveInStrictMode; + state.parentStack[state.stackIndex] = saveParent; + } + else { + state = { + stackIndex: 0, + skip: false, + inStrictModeStack: [undefined], + parentStack: [undefined] + }; + } + // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions + // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too + // For now, though, since the common cases are chained `+`, leaving it recursive is fine + var operator = node.operatorToken.kind; + if (operator === 55 /* AmpersandAmpersandToken */ || + operator === 56 /* BarBarToken */ || + operator === 60 /* QuestionQuestionToken */ || + ts.isLogicalOrCoalescingAssignmentOperator(operator)) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); } - case 2 /* BindToken */: { - if (node.operatorToken.kind === 27 /* CommaToken */) { - maybeBindExpressionFlowIfCall(node.left); - } - advanceState(3 /* BindRight */); - maybeBind(node.operatorToken); - break; + else { + bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget); } - case 3 /* BindRight */: { - advanceState(4 /* FinishBind */); - maybeBind(node.right); - break; + state.skip = true; + } + return state; + } + function onLeft(left, state, _node) { + if (!state.skip) { + return maybeBind(left); + } + } + function onOperator(operatorToken, state, node) { + if (!state.skip) { + if (operatorToken.kind === 27 /* CommaToken */) { + maybeBindExpressionFlowIfCall(node.left); } - case 4 /* FinishBind */: { - var operator = node.operatorToken.kind; - if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { - bindAssignmentTargetFlow(node.left); - if (operator === 62 /* EqualsToken */ && node.left.kind === 202 /* ElementAccessExpression */) { - var elementAccess = node.left; - if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); - } + bind(operatorToken); + } + } + function onRight(right, state, _node) { + if (!state.skip) { + return maybeBind(right); + } + } + function onExit(node, state) { + if (!state.skip) { + var operator = node.operatorToken.kind; + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 62 /* EqualsToken */ && node.left.kind === 203 /* ElementAccessExpression */) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); } } - completeNode(); - break; } - default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for bindBinaryExpressionFlow"); } - } - /** - * Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new - * head state; so `advanceState` must be called before any `maybeBind` during a state's execution. - */ - function advanceState(state, isInStrictMode, parent) { - workStacks.state[stackIndex] = state; - if (isInStrictMode !== undefined) { - workStacks.inStrictMode[stackIndex] = isInStrictMode; + var savedInStrictMode = state.inStrictModeStack[state.stackIndex]; + var savedParent = state.parentStack[state.stackIndex]; + if (savedInStrictMode !== undefined) { + inStrictMode = savedInStrictMode; } - if (parent !== undefined) { - workStacks.parent[stackIndex] = parent; + if (savedParent !== undefined) { + parent = savedParent; } + state.skip = false; + state.stackIndex--; } - function completeNode() { - if (workStacks.inStrictMode[stackIndex] !== undefined) { - inStrictMode = workStacks.inStrictMode[stackIndex]; - parent = workStacks.parent[stackIndex]; - } - stackIndex--; - } - /** - * If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it - */ function maybeBind(node) { if (node && ts.isBinaryExpression(node) && !ts.isDestructuringAssignment(node)) { - stackIndex++; - workStacks.expr[stackIndex] = node; - workStacks.state[stackIndex] = 0 /* BindThenBindChildren */; - workStacks.inStrictMode[stackIndex] = undefined; - workStacks.parent[stackIndex] = undefined; - } - else { - bind(node); + return node; } + bind(node); } } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 201 /* PropertyAccessExpression */) { + if (node.expression.kind === 202 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -41788,7 +42948,7 @@ var ts; } function bindJSDocTypeAlias(node) { ts.setParent(node.tagName, node); - if (node.kind !== 325 /* JSDocEnumTag */ && node.fullName) { + if (node.kind !== 329 /* JSDocEnumTag */ && node.fullName) { ts.setParent(node.fullName, node); ts.setParentRecursive(node.fullName, /*incremental*/ false); } @@ -41796,7 +42956,7 @@ var ts; function bindJSDocClassTag(node) { bindEachChild(node); var host = ts.getHostSignatureFromJSDoc(node); - if (host && host.kind !== 165 /* MethodDeclaration */) { + if (host && host.kind !== 166 /* MethodDeclaration */) { addDeclarationToSymbol(host.symbol, host, 32 /* Class */); } } @@ -41809,15 +42969,15 @@ var ts; } function bindOptionalChainRest(node) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: bind(node.questionDotToken); bind(node.name); break; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: bind(node.questionDotToken); bind(node.argumentExpression); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: bind(node.questionDotToken); bindEach(node.typeArguments); bindEach(node.arguments); @@ -41882,7 +43042,7 @@ var ts; // an immediately invoked function expression (IIFE). Initialize the flowNode property to // the current control flow (which includes evaluation of the IIFE arguments). var expr = ts.skipParentheses(node.expression); - if (expr.kind === 208 /* FunctionExpression */ || expr.kind === 209 /* ArrowFunction */) { + if (expr.kind === 209 /* FunctionExpression */ || expr.kind === 210 /* ArrowFunction */) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -41894,7 +43054,7 @@ var ts; } } } - if (node.expression.kind === 201 /* PropertyAccessExpression */) { + if (node.expression.kind === 202 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); @@ -41903,54 +43063,54 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 200 /* ObjectLiteralExpression */: - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 281 /* JsxAttributes */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 201 /* ObjectLiteralExpression */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 282 /* JsxAttributes */: return 1 /* IsContainer */; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return 1 /* IsContainer */ | 64 /* IsInterface */; - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 190 /* MappedType */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 191 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 297 /* SourceFile */: + case 298 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; } // falls through - case 166 /* Constructor */: - case 251 /* FunctionDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 169 /* CallSignature */: - case 313 /* JSDocSignature */: - case 308 /* JSDocFunctionType */: - case 174 /* FunctionType */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 175 /* ConstructorType */: + case 167 /* Constructor */: + case 252 /* FunctionDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 170 /* CallSignature */: + case 315 /* JSDocSignature */: + case 309 /* JSDocFunctionType */: + case 175 /* FunctionType */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 176 /* ConstructorType */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return 4 /* IsControlFlowContainer */; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 287 /* CatchClause */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 258 /* CaseBlock */: + case 288 /* CatchClause */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 259 /* CaseBlock */: return 2 /* IsBlockScopedContainer */; - case 230 /* Block */: + case 231 /* Block */: // do not treat blocks directly inside a function as a block-scoped-container. // Locals that reside in this block should go to the function locals. Otherwise 'x' // would not appear to be a redeclaration of a block scoped local in the following @@ -41983,45 +43143,45 @@ var ts; // members are declared (for example, a member of a class will go into a specific // symbol table depending on if it is static or not). We defer to specialized // handlers to take care of declaring these child members. - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 297 /* SourceFile */: + case 298 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 200 /* ObjectLiteralExpression */: - case 253 /* InterfaceDeclaration */: - case 281 /* JsxAttributes */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 201 /* ObjectLiteralExpression */: + case 254 /* InterfaceDeclaration */: + case 282 /* JsxAttributes */: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the // object / type / interface declaring them). An exception is type parameters, // which are in scope without qualification (similar to 'locals'). return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 313 /* JSDocSignature */: - case 171 /* IndexSignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 308 /* JSDocFunctionType */: - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 254 /* TypeAliasDeclaration */: - case 190 /* MappedType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 315 /* JSDocSignature */: + case 172 /* IndexSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 309 /* JSDocFunctionType */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 255 /* TypeAliasDeclaration */: + case 191 /* MappedType */: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -42122,7 +43282,7 @@ var ts; var seen = new ts.Map(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 290 /* SpreadAssignment */ || prop.name.kind !== 78 /* Identifier */) { + if (prop.kind === 291 /* SpreadAssignment */ || prop.name.kind !== 78 /* Identifier */) { continue; } var identifier = prop.name; @@ -42134,7 +43294,7 @@ var ts; // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 288 /* PropertyAssignment */ || prop.kind === 289 /* ShorthandPropertyAssignment */ || prop.kind === 165 /* MethodDeclaration */ + var currentKind = prop.kind === 289 /* PropertyAssignment */ || prop.kind === 290 /* ShorthandPropertyAssignment */ || prop.kind === 166 /* MethodDeclaration */ ? 1 /* Property */ : 2 /* Accessor */; var existingKind = seen.get(identifier.escapedText); @@ -42166,10 +43326,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (ts.isExternalOrCommonJsModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -42194,9 +43354,9 @@ var ts; var saveCurrentFlow = currentFlow; for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { var typeAlias = delayedTypeAliases_1[_i]; - var host = ts.getJSDocHost(typeAlias); - container = (host && ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); })) || file; - blockScopeContainer = (host && ts.getEnclosingBlockScopeContainer(host)) || file; + var host = typeAlias.parent.parent; + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); @@ -42368,8 +43528,8 @@ var ts; function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2 /* ES2015 */) { // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 297 /* SourceFile */ && - blockScopeContainer.kind !== 256 /* ModuleDeclaration */ && + if (blockScopeContainer.kind !== 298 /* SourceFile */ && + blockScopeContainer.kind !== 257 /* ModuleDeclaration */ && !ts.isFunctionLike(blockScopeContainer)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. @@ -42464,7 +43624,7 @@ var ts; // the current 'container' node when it changes. This helps us know which symbol table // a local should go into for example. Since terminal nodes are known not to have // children, as an optimization we don't process those. - if (node.kind > 156 /* LastToken */) { + if (node.kind > 157 /* LastToken */) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -42540,17 +43700,23 @@ var ts; } // falls through case 107 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 289 /* ShorthandPropertyAssignment */)) { + if (currentFlow && (ts.isExpression(node) || parent.kind === 290 /* ShorthandPropertyAssignment */)) { node.flowNode = currentFlow; } return checkContextualIdentifier(node); + case 158 /* QualifiedName */: + if (currentFlow && parent.kind === 177 /* TypeQuery */) { + node.flowNode = currentFlow; + } + break; + case 227 /* MetaProperty */: case 105 /* SuperKeyword */: node.flowNode = currentFlow; break; case 79 /* PrivateIdentifier */: return checkPrivateIdentifier(node); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: var expr = node; if (currentFlow && isNarrowableReference(expr)) { expr.flowNode = currentFlow; @@ -42565,7 +43731,7 @@ var ts; declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */); } break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: @@ -42601,78 +43767,78 @@ var ts; ts.Debug.fail("Unknown binary expression special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return checkStrictModeCatchClause(node); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return checkStrictModeDeleteExpression(node); case 8 /* NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return checkStrictModeWithStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return checkStrictModeLabeledStatement(node); - case 187 /* ThisType */: + case 188 /* ThisType */: seenThisKeyword = true; return; - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: break; // Binding the children will handle everything - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return bindTypeParameter(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return bindParameter(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return bindVariableDeclarationOrBindingElement(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return bindPropertyWorker(node); - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 291 /* EnumMember */: + case 292 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: // If this is an ObjectLiteralExpression method, then it sits in the same space // 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 */ : 103359 /* MethodExcludes */); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return bindFunctionDeclaration(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */); - case 174 /* FunctionType */: - case 308 /* JSDocFunctionType */: - case 313 /* JSDocSignature */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 309 /* JSDocFunctionType */: + case 315 /* JSDocSignature */: + case 176 /* ConstructorType */: return bindFunctionOrConstructorType(node); - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 190 /* MappedType */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 191 /* MappedType */: return bindAnonymousTypeWorker(node); - case 319 /* JSDocClassTag */: + case 322 /* JSDocClassTag */: return bindJSDocClassTag(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return bindFunctionExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: var assignmentKind = ts.getAssignmentDeclarationKind(node); switch (assignmentKind) { case 7 /* ObjectDefinePropertyValue */: @@ -42691,65 +43857,65 @@ var ts; } break; // Members of classes, interfaces, and modules - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: // All classes are automatically in strict mode in ES6. inStrictMode = true; return bindClassLikeDeclaration(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return bindEnumDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return bindModuleDeclaration(node); // Jsx-attributes - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return bindJsxAttributes(node); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); // Imports and exports - case 260 /* ImportEqualsDeclaration */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 261 /* ImportEqualsDeclaration */: + case 264 /* NamespaceImport */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return bindNamespaceExportDeclaration(node); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return bindImportClause(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return bindExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return bindExportAssignment(node); - case 297 /* SourceFile */: + case 298 /* SourceFile */: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 230 /* Block */: + case 231 /* Block */: if (!ts.isFunctionLike(node.parent)) { return; } // falls through - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 326 /* JSDocParameterTag */: - if (node.parent.kind === 313 /* JSDocSignature */) { + case 330 /* JSDocParameterTag */: + if (node.parent.kind === 315 /* JSDocSignature */) { return bindParameter(node); } - if (node.parent.kind !== 312 /* JSDocTypeLiteral */) { + if (node.parent.kind !== 314 /* JSDocTypeLiteral */) { break; } // falls through - case 333 /* JSDocPropertyTag */: + case 337 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 307 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 308 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } @@ -42777,8 +43943,8 @@ var ts; } function bindExportAssignment(node) { if (!container.symbol || !container.symbol.exports) { - // Export assignment in some sort of block construct - bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + // Incorrect export assignment in some sort of block construct + bindAnonymousDeclaration(node, 111551 /* Value */, getDeclarationName(node)); } else { var flags = ts.exportAssignmentIsAlias(node) @@ -42912,8 +44078,8 @@ var ts; } var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: var constructorSymbol = thisContainer.symbol; // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 62 /* EqualsToken */) { @@ -42935,11 +44101,11 @@ var ts; addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */); } break; - case 166 /* Constructor */: - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 167 /* Constructor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // this.foo assignment in a JavaScript class // Bind this property to the containing class var containingClass = thisContainer.parent; @@ -42951,7 +44117,7 @@ var ts; declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true); } break; - case 297 /* SourceFile */: + case 298 /* SourceFile */: // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script if (ts.hasDynamicName(node)) { break; @@ -42980,7 +44146,7 @@ var ts; if (node.expression.kind === 107 /* ThisKeyword */) { bindThisPropertyAssignment(node); } - else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 297 /* SourceFile */) { + else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 298 /* SourceFile */) { if (ts.isPrototypeAccess(node.expression)) { bindPrototypePropertyAssignment(node, node.parent); } @@ -43020,7 +44186,7 @@ var ts; } function bindObjectDefinePropertyAssignment(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); - var isToplevel = node.parent.parent.kind === 297 /* SourceFile */; + var isToplevel = node.parent.parent.kind === 298 /* SourceFile */; namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false); bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); } @@ -43129,8 +44295,8 @@ var ts; } function isTopLevelNamespaceAssignment(propertyAccess) { return ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 297 /* SourceFile */ - : propertyAccess.parent.parent.kind === 297 /* SourceFile */; + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 298 /* SourceFile */ + : propertyAccess.parent.parent.kind === 298 /* SourceFile */; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) { var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer); @@ -43209,7 +44375,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 252 /* ClassDeclaration */) { + if (node.kind === 253 /* ClassDeclaration */) { bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */); } else { @@ -43251,7 +44417,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { - if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true) && !ts.getJSDocTypeTag(node)) { + if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node) && !ts.getJSDocTypeTag(node)) { declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } else if (ts.isBlockOrCatchScoped(node)) { @@ -43275,7 +44441,7 @@ var ts; } } function bindParameter(node) { - if (node.kind === 326 /* JSDocParameterTag */ && container.kind !== 313 /* JSDocSignature */) { + if (node.kind === 330 /* JSDocParameterTag */ && container.kind !== 315 /* JSDocSignature */) { return; } if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) { @@ -43352,7 +44518,7 @@ var ts; declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */); } } - else if (node.parent.kind === 185 /* InferType */) { + else if (node.parent.kind === 186 /* InferType */) { var container_2 = getInferTypeContainer(node.parent); if (container_2) { if (!container_2.locals) { @@ -43371,7 +44537,7 @@ var ts; // reachability checks function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && ts.shouldPreserveConstEnums(options)); } function checkUnreachable(node) { if (!(currentFlow.flags & 1 /* Unreachable */)) { @@ -43380,11 +44546,11 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 231 /* EmptyStatement */) || + (ts.isStatementButNotDeclaration(node) && node.kind !== 232 /* EmptyStatement */) || // report error on class declarations - node.kind === 252 /* ClassDeclaration */ || + node.kind === 253 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 256 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); + (node.kind === 257 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -43428,12 +44594,12 @@ var ts; } function isPurelyTypeDeclaration(s) { switch (s.kind) { - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return true; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return getModuleInstanceState(s) !== 1 /* Instantiated */; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return ts.hasSyntacticModifier(s, 2048 /* Const */); default: return false; @@ -43633,7 +44799,7 @@ var ts; // (their type resolved directly to the member deeply referenced) // So to get the intervening symbols, we need to check if there's a type // query node on any of the symbol's declarations and get symbols there - if (d.type && d.type.kind === 176 /* TypeQuery */) { + if (d.type && d.type.kind === 177 /* TypeQuery */) { var query = d.type; var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); visitSymbol(entity); @@ -43860,6 +45026,7 @@ var ts; DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor"; DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment"; DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method"; + DeclarationMeaning[DeclarationMeaning["PrivateStatic"] = 16] = "PrivateStatic"; DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor"; DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod"; })(DeclarationMeaning || (DeclarationMeaning = {})); @@ -43951,12 +45118,12 @@ var ts; var instantiationCount = 0; var instantiationDepth = 0; var currentNode; - var typeCatalog = []; // NB: id is index + 1 var emptySymbols = ts.createSymbolTable(); var arrayVariances = [1 /* Covariant */]; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); @@ -43965,7 +45132,8 @@ var ts; var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16384 /* FreshLiteral */; + var checkBinaryExpression = createCheckBinaryExpression(); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); var globals = ts.createSymbolTable(); @@ -43988,7 +45156,6 @@ var ts; getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, - getTypeCatalog: function () { return typeCatalog; }, getTypeCount: function () { return typeCount; }, getInstantiationCount: function () { return totalInstantiationCount; }, getRelationCacheSizes: function () { return ({ @@ -44152,6 +45319,7 @@ var ts; return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, + getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: function (node, candidatesOutArray, argumentCount) { return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */); @@ -44195,6 +45363,7 @@ var ts; }, tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); }, + tryFindAmbientModule: function (moduleName) { return tryFindAmbientModule(moduleName, /*withAugmentations*/ true); }, tryFindAmbientModuleWithoutAugmentations: function (moduleName) { // we deliberately exclude augmentations // since we are only interested in declarations of the module itself @@ -44313,6 +45482,7 @@ var ts; var templateLiteralTypes = new ts.Map(); var stringMappingTypes = new ts.Map(); var substitutionTypes = new ts.Map(); + var subtypeReductionCache = new ts.Map(); var evolvingArrayTypes = []; var undefinedProperties = new ts.Map(); var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -44321,14 +45491,14 @@ var ts; var autoType = createIntrinsicType(1 /* Any */, "any"); var wildcardType = createIntrinsicType(1 /* Any */, "any"); var errorType = createIntrinsicType(1 /* Any */, "error"); - var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */); + var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 131072 /* ContainsWideningType */); var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */); var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined"); var nullType = createIntrinsicType(65536 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 131072 /* ContainsWideningType */); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); @@ -44354,7 +45524,7 @@ var ts; var voidType = createIntrinsicType(16384 /* Void */, "void"); var neverType = createIntrinsicType(131072 /* Never */, "never"); var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); - var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */); + var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 524288 /* NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); @@ -44366,7 +45536,7 @@ var ts; var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; + emptyJsxObjectType.objectFlags |= 2048 /* JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -44375,7 +45545,7 @@ var ts; var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */; + anyFunctionType.objectFlags |= 524288 /* NonInferrableType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -44455,6 +45625,7 @@ var ts; // This allows users to just specify library files they want to used through --lib // and they will not get an error from not having unrelated library files var deferredGlobalESSymbolConstructorSymbol; + var deferredGlobalESSymbolConstructorTypeSymbol; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; @@ -44506,7 +45677,7 @@ var ts; var flowNodePostSuper = []; var potentialThisCollisions = []; var potentialNewTargetCollisions = []; - var potentialWeakMapCollisions = []; + var potentialWeakMapSetCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); var suggestionDiagnostics = ts.createDiagnosticCollection(); @@ -44653,6 +45824,25 @@ var ts; } return diagnostic; } + function addDeprecatedSuggestionWorker(declarations, diagnostic) { + var deprecatedTag = Array.isArray(declarations) ? ts.forEach(declarations, ts.getJSDocDeprecatedTag) : ts.getJSDocDeprecatedTag(declarations); + if (deprecatedTag) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(deprecatedTag, ts.Diagnostics.The_declaration_was_marked_as_deprecated_here)); + } + // We call `addRelatedInfo()` before adding the diagnostic to prevent duplicates. + suggestionDiagnostics.add(diagnostic); + return diagnostic; + } + function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { + var diagnostic = ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, deprecatedEntity); + return addDeprecatedSuggestionWorker(declarations, diagnostic); + } + function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) { + var diagnostic = deprecatedEntity + ? ts.createDiagnosticForNode(location, ts.Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity) + : ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, signatureString); + return addDeprecatedSuggestionWorker(declaration, diagnostic); + } function createSymbol(flags, name, checkFlags) { symbolCount++; var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); @@ -44766,7 +45956,7 @@ var ts; // as we will already report a "Declaration name conflicts..." error, and this error // won't make much sense. if (target !== globalThisSymbol) { - error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(source.declarations && ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } } else { // error @@ -44800,9 +45990,11 @@ var ts; } return target; function addDuplicateLocations(locs, symbol) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - ts.pushIfUnique(locs, decl); + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, decl); + } } } } @@ -44848,9 +46040,9 @@ var ts; }); } function mergeModuleAugmentation(moduleName) { - var _a, _b; + var _a, _b, _c; var moduleAugmentation = moduleName.parent; - if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + if (((_a = moduleAugmentation.symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]) !== moduleAugmentation) { // this is a combined symbol for multiple augmentations within the same file. // its symbol already has accumulated information for all declarations // so we need to add it just once - do the work only for first declaration @@ -44887,11 +46079,11 @@ var ts; patternAmbientModuleAugmentations.set(moduleName.text, merged); } else { - if (((_a = mainModule_1.exports) === null || _a === void 0 ? void 0 : _a.get("__export" /* ExportStar */)) && ((_b = moduleAugmentation.symbol.exports) === null || _b === void 0 ? void 0 : _b.size)) { + if (((_b = mainModule_1.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */)) && ((_c = moduleAugmentation.symbol.exports) === null || _c === void 0 ? void 0 : _c.size)) { // We may need to merge the module augmentation's exports into the target symbols of the resolved exports var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */); - for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) { - var _d = _c[_i], key = _d[0], value = _d[1]; + for (var _i = 0, _d = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _d.length; _i++) { + var _e = _d[_i], key = _e[0], value = _e[1]; if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) { mergeSymbol(resolvedExports.get(key), value); } @@ -44932,7 +46124,7 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks()); } function isGlobalSourceFile(node) { - return node.kind === 297 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 298 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -44991,17 +46183,17 @@ var ts; } if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) { // declaration is before usage - if (declaration.kind === 198 /* BindingElement */) { + if (declaration.kind === 199 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) - var errorBindingElement = ts.getAncestor(usage, 198 /* BindingElement */); + var errorBindingElement = ts.getAncestor(usage, 199 /* BindingElement */); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 249 /* VariableDeclaration */), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 250 /* VariableDeclaration */), usage); } - else if (declaration.kind === 249 /* VariableDeclaration */) { + else if (declaration.kind === 250 /* VariableDeclaration */) { // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } @@ -45015,7 +46207,7 @@ var ts; } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property - return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + return !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); } @@ -45031,19 +46223,19 @@ var ts; // or if usage is in a type context: // 1. inside a type query (typeof in type position) // 2. inside a jsdoc comment - if (usage.parent.kind === 270 /* ExportSpecifier */ || (usage.parent.kind === 266 /* ExportAssignment */ && usage.parent.isExportEquals)) { + if (usage.parent.kind === 271 /* ExportSpecifier */ || (usage.parent.kind === 267 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; } // When resolving symbols for exports, the `usage` location passed in can be the export site directly - if (usage.kind === 266 /* ExportAssignment */ && usage.isExportEquals) { + if (usage.kind === 267 /* ExportAssignment */ && usage.isExportEquals) { return true; } if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + if (compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); @@ -45058,9 +46250,9 @@ var ts; } function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { switch (declaration.parent.parent.kind) { - case 232 /* VariableStatement */: - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: + case 233 /* VariableStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, declContainer)) { @@ -45081,16 +46273,16 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 163 /* PropertyDeclaration */ && + current.parent.kind === 164 /* PropertyDeclaration */ && current.parent.initializer === current; if (initializerOfProperty) { if (ts.hasSyntacticModifier(current.parent, 32 /* Static */)) { - if (declaration.kind === 165 /* MethodDeclaration */) { + if (declaration.kind === 166 /* MethodDeclaration */) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 163 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(declaration, 32 /* Static */); + var isDeclarationInstanceProperty = declaration.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(declaration, 32 /* Static */); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -45112,19 +46304,19 @@ var ts; return "quit"; } switch (node.kind) { - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return true; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // even when stopping at any property declaration, they need to come from the same class return stopAtAnyPropertyDeclaration && (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent) ? "quit" : true; - case 230 /* Block */: + case 231 /* Block */: switch (node.parent.kind) { - case 167 /* GetAccessor */: - case 165 /* MethodDeclaration */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 166 /* MethodDeclaration */: + case 169 /* SetAccessor */: return true; default: return false; @@ -45139,7 +46331,11 @@ var ts; function useOuterVariableScopeInParameter(result, location, lastLocation) { var target = ts.getEmitScriptTarget(compilerOptions); var functionLocation = location; - if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + if (ts.isParameter(lastLocation) + && functionLocation.body + && result.valueDeclaration + && result.valueDeclaration.pos >= functionLocation.body.pos + && result.valueDeclaration.end <= functionLocation.body.end) { // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body // - static field in a class expression // - optional chaining pre-es2020 @@ -45160,21 +46356,21 @@ var ts; } function requiresScopeChangeWorker(node) { switch (node.kind) { - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 166 /* Constructor */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 167 /* Constructor */: // do not descend into these return false; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 288 /* PropertyAssignment */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 289 /* PropertyAssignment */: return requiresScopeChangeWorker(node.name); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // static properties in classes introduce temporary variables if (ts.hasStaticModifier(node)) { - return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields; + return target < 99 /* ESNext */ || !useDefineForClassFields; } return requiresScopeChangeWorker(node.name); default: @@ -45203,6 +46399,7 @@ var ts; return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); } function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { + var _a; var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; @@ -45225,12 +46422,12 @@ 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 & 788968 /* Type */ && lastLocation.kind !== 311 /* JSDocComment */) { + if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 312 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || - lastLocation.kind === 160 /* Parameter */ || - lastLocation.kind === 159 /* TypeParameter */ + lastLocation.kind === 161 /* Parameter */ || + lastLocation.kind === 160 /* TypeParameter */ // local types not visible outside the function body : false; } @@ -45245,13 +46442,13 @@ var ts; // however it is detected separately when checking initializers of parameters // to make sure that they reference no variables declared after them. useResult = - lastLocation.kind === 160 /* Parameter */ || + lastLocation.kind === 161 /* Parameter */ || (lastLocation === location.type && !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); } } } - else if (location.kind === 184 /* ConditionalType */) { + else if (location.kind === 185 /* ConditionalType */) { // A type parameter declared using 'infer T' in a conditional type is visible only in // the true branch of the conditional type. useResult = lastLocation === location.trueType; @@ -45266,14 +46463,14 @@ var ts; } withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation); switch (location.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; // falls through - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports || emptySymbols; - if (location.kind === 297 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) { + if (location.kind === 298 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports.get("default" /* Default */)) { @@ -45297,13 +46494,13 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && - (ts.getDeclarationOfKind(moduleExport, 270 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 269 /* NamespaceExport */))) { + (ts.getDeclarationOfKind(moduleExport, 271 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 270 /* NamespaceExport */))) { break; } } // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs) if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) { - if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !((_a = result.declarations) === null || _a === void 0 ? void 0 : _a.some(ts.isJSDocTypeAlias))) { result = undefined; } else { @@ -45311,12 +46508,12 @@ var ts; } } break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // TypeScript 1.0 spec (April 2014): 8.4.1 // Initializer expressions for instance member variables are evaluated in the scope // of the class constructor body but are not permitted to reference parameters or @@ -45333,9 +46530,9 @@ var ts; } } break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: // 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! @@ -45354,7 +46551,7 @@ var ts; } break loop; } - if (location.kind === 221 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 222 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -45362,7 +46559,7 @@ var ts; } } break; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 93 /* ExtendsKeyword */) { var container = location.parent.parent; @@ -45382,9 +46579,9 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 253 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 254 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -45392,24 +46589,24 @@ var ts; } } break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: // when targeting ES6 or higher there is no 'arguments' in an arrow function // for lower compile targets the resolved symbol is used to emit an error if (compilerOptions.target >= 2 /* ES2015 */) { break; } // falls through - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -45422,7 +46619,7 @@ var ts; } } break; - case 161 /* Decorator */: + case 162 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -45431,7 +46628,7 @@ var ts; // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. // } // - if (location.parent && location.parent.kind === 160 /* Parameter */) { + if (location.parent && location.parent.kind === 161 /* Parameter */) { location = location.parent; } // @@ -45446,20 +46643,20 @@ var ts; // declare function y(x: T): any; // @param(1 as T) // <-- T should resolve to the type alias outside of class C // class C {} - if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 252 /* ClassDeclaration */)) { + if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 253 /* ClassDeclaration */)) { location = location.parent; } break; - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: // js type aliases do not resolve names from their host, so skip past it var root = ts.getJSDocRoot(location); if (root) { location = root.parent; } break; - case 160 /* Parameter */: + case 161 /* Parameter */: if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && ts.isBindingPattern(lastLocation))) { if (!associatedDeclarationForContainingInitializerOrBindingName) { @@ -45467,7 +46664,7 @@ var ts; } } break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && ts.isBindingPattern(lastLocation))) { if (ts.isParameterDeclaration(location) && !associatedDeclarationForContainingInitializerOrBindingName) { @@ -45475,7 +46672,7 @@ var ts; } } break; - case 185 /* InferType */: + case 186 /* InferType */: if (meaning & 262144 /* TypeParameter */) { var parameterName = location.typeParameter.name; if (parameterName && name === parameterName.escapedText) { @@ -45499,7 +46696,7 @@ var ts; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 297 /* SourceFile */); + ts.Debug.assert(lastLocation.kind === 298 /* SourceFile */); if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } @@ -45528,6 +46725,10 @@ var ts; var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + var isGlobalScopeAugmentationDeclaration = suggestion && suggestion.valueDeclaration && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); + if (isGlobalScopeAugmentationDeclaration) { + suggestion = undefined; + } if (suggestion) { var suggestionName = symbolToString(suggestion); var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); @@ -45554,7 +46755,7 @@ var ts; } // Perform extra checks only if error reporting was requested if (nameNotFoundMessage) { - if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields)) { // We have a match, but the reference occurred within a property initializer and the identifier also binds // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed // with ESNext+useDefineForClassFields because the scope semantics are different. @@ -45624,10 +46825,10 @@ var ts; } } function getIsDeferredContext(location, lastLocation) { - if (location.kind !== 209 /* ArrowFunction */ && location.kind !== 208 /* FunctionExpression */) { + if (location.kind !== 210 /* ArrowFunction */ && location.kind !== 209 /* FunctionExpression */) { // initializers in instance property declaration of class like entities are executed in constructor and thus deferred return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) || - (location.kind === 163 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(location, 32 /* Static */))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred + (location.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(location, 32 /* Static */))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred } if (lastLocation && lastLocation === location.name) { return false; @@ -45640,12 +46841,12 @@ var ts; } function isSelfReferenceLocation(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 256 /* ModuleDeclaration */: // For `namespace N { N; }` + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 257 /* ModuleDeclaration */: // For `namespace N { N; }` return true; default: return false; @@ -45655,12 +46856,14 @@ var ts; return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } function isTypeParameterSymbolDeclaredInContainer(symbol, container) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (decl.kind === 159 /* TypeParameter */) { - var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; - if (parent === container) { - return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.kind === 160 /* TypeParameter */) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + } } } } @@ -45713,9 +46916,9 @@ var ts; function getEntityNameForExtendingInterface(node) { switch (node.kind) { case 78 /* Identifier */: - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: if (ts.isEntityNameExpression(node.expression)) { return node.expression; } @@ -45759,7 +46962,7 @@ var ts; return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown"; } function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) { - if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 270 /* ExportSpecifier */) { + if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 271 /* ExportSpecifier */) { error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name); return true; } @@ -45828,13 +47031,14 @@ var ts; return false; } function checkResolvedBlockScopedVariable(result, errorLocation) { + var _a; ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) { // constructor functions aren't block scoped return; } // Block-scoped variables cannot be used before their definition - var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 255 /* EnumDeclaration */); }); + var declaration = (_a = result.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 256 /* EnumDeclaration */); }); if (declaration === undefined) return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration"); if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -45851,7 +47055,7 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); - if (compilerOptions.preserveConstEnums) { + if (ts.shouldPreserveConstEnums(compilerOptions)) { diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); } } @@ -45869,20 +47073,20 @@ var ts; } function getAnyImportSyntax(node) { switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return node; - case 262 /* ImportClause */: + case 263 /* ImportClause */: return node.parent; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return node.parent.parent; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: return node.parent.parent.parent; default: return undefined; } } function getDeclarationOfAliasSymbol(symbol) { - return ts.find(symbol.declarations, isAliasSymbolDeclaration); + return symbol.declarations && ts.findLast(symbol.declarations, isAliasSymbolDeclaration); } /** * An alias symbol is created by one of the following declarations: @@ -45897,25 +47101,26 @@ var ts; * module.exports = * {} * {name: } + * const { x } = require ... */ function isAliasSymbolDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ - || node.kind === 259 /* NamespaceExportDeclaration */ - || node.kind === 262 /* ImportClause */ && !!node.name - || node.kind === 263 /* NamespaceImport */ - || node.kind === 269 /* NamespaceExport */ - || node.kind === 265 /* ImportSpecifier */ - || node.kind === 270 /* ExportSpecifier */ - || node.kind === 266 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + return node.kind === 261 /* ImportEqualsDeclaration */ + || node.kind === 260 /* NamespaceExportDeclaration */ + || node.kind === 263 /* ImportClause */ && !!node.name + || node.kind === 264 /* NamespaceImport */ + || node.kind === 270 /* NamespaceExport */ + || node.kind === 266 /* ImportSpecifier */ + || node.kind === 271 /* ExportSpecifier */ + || node.kind === 267 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) || ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && ts.exportAssignmentIsAlias(node) || ts.isAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableOrJsExpression(node.parent.right) - || node.kind === 289 /* ShorthandPropertyAssignment */ - || node.kind === 288 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) - || ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true); + || node.kind === 290 /* ShorthandPropertyAssignment */ + || node.kind === 289 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) + || ts.isRequireVariableDeclaration(node); } function isAliasableOrJsExpression(e) { return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e); @@ -45928,7 +47133,7 @@ var ts; ? resolveSymbol(getPropertyOfType(resolveExternalModuleTypeByLiteral(name), commonJSPropertyAccess.name.escapedText)) : undefined; } - if (ts.isVariableDeclaration(node) || node.moduleReference.kind === 272 /* ExternalModuleReference */) { + if (ts.isVariableDeclaration(node) || node.moduleReference.kind === 273 /* ExternalModuleReference */) { var immediate = resolveExternalModuleName(node, ts.getExternalModuleRequireArgument(node) || ts.getExternalModuleImportEqualsDeclarationExpression(node)); var resolved_4 = resolveExternalModuleSymbol(immediate); markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false); @@ -45995,6 +47200,7 @@ var ts; return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias); } function getTargetOfImportClause(node, dontResolveAlias) { + var _a; var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { var exportDefaultSymbol = void 0; @@ -46004,7 +47210,7 @@ var ts; else { exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias); } - var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); if (!exportDefaultSymbol && !hasSyntheticDefault) { if (hasExportAssignmentSymbol(moduleSymbol)) { @@ -46012,7 +47218,9 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */); var exportAssignment = exportEqualsSymbol.valueDeclaration; var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName); - ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); + if (exportAssignment) { + ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); + } } else { reportNonDefaultExport(moduleSymbol, node); @@ -46029,7 +47237,7 @@ var ts; } } function reportNonDefaultExport(moduleSymbol, node) { - var _a, _b; + var _a, _b, _c; if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); } @@ -46037,7 +47245,7 @@ var ts; var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */); if (exportStar) { - var defaultExport = ts.find(exportStar.declarations, function (decl) { + var defaultExport = (_c = exportStar.declarations) === null || _c === void 0 ? void 0 : _c.find(function (decl) { var _a, _b; return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier && ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */))); @@ -46115,7 +47323,7 @@ var ts; } } function getExternalModuleMember(node, specifier, dontResolveAlias) { - var _a; + var _a, _b; if (dontResolveAlias === void 0) { dontResolveAlias = false; } var moduleSpecifier = ts.getExternalModuleRequireArgument(node) || node.moduleSpecifier; var moduleSymbol = resolveExternalModuleName(node, moduleSpecifier); // TODO: GH#18217 @@ -46124,7 +47332,7 @@ var ts; return undefined; } var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop); - var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, dontResolveAlias, suppressInteropError); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, /*dontResolveAlias*/ false, suppressInteropError); if (targetSymbol) { if (name.escapedText) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { @@ -46142,7 +47350,7 @@ var ts; symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); var symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias); if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) { - var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } @@ -46162,7 +47370,7 @@ var ts; } } else { - if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default" /* Default */)) { + if ((_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */)) { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); } else { @@ -46175,8 +47383,8 @@ var ts; } } function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) { - var _a; - var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText); + var _a, _b; + var localSymbol = (_b = (_a = moduleSymbol.valueDeclaration) === null || _a === void 0 ? void 0 : _a.locals) === null || _b === void 0 ? void 0 : _b.get(name.escapedText); var exports = moduleSymbol.exports; if (localSymbol) { var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */); @@ -46188,9 +47396,11 @@ var ts; var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined; var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); - ts.addRelatedInfo.apply(void 0, __spreadArray([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { - return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); - }))); + if (localSymbol.declarations) { + ts.addRelatedInfo.apply(void 0, __spreadArray([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { + return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); + }))); + } } } else { @@ -46277,31 +47487,31 @@ var ts; function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: - case 249 /* VariableDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 250 /* VariableDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return getTargetOfImportClause(node, dontRecursivelyResolve); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: return getTargetOfNamespaceExport(node, dontRecursivelyResolve); - case 265 /* ImportSpecifier */: - case 198 /* BindingElement */: + case 266 /* ImportSpecifier */: + case 199 /* BindingElement */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); - case 266 /* ExportAssignment */: - case 216 /* BinaryExpression */: + case 267 /* ExportAssignment */: + case 217 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return getTargetOfPropertyAssignment(node, dontRecursivelyResolve); - case 202 /* ElementAccessExpression */: - case 201 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: return getTargetOfAccessExpression(node, dontRecursivelyResolve); default: return ts.Debug.fail(); @@ -46453,13 +47663,13 @@ var ts; entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 78 /* Identifier */ || entityName.parent.kind === 157 /* QualifiedName */) { + if (entityName.kind === 78 /* Identifier */ || entityName.parent.kind === 158 /* QualifiedName */) { return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 260 /* ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 261 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } @@ -46483,9 +47693,9 @@ var ts; return getMergedSymbol(symbolFromJSPrototype); } } - else if (name.kind === 157 /* QualifiedName */ || name.kind === 201 /* PropertyAccessExpression */) { - var left = name.kind === 157 /* QualifiedName */ ? name.left : name.expression; - var right = name.kind === 157 /* QualifiedName */ ? name.right : name.name; + else if (name.kind === 158 /* QualifiedName */ || name.kind === 202 /* PropertyAccessExpression */) { + var left = name.kind === 158 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 158 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -46493,18 +47703,17 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJSFile(name)) { - if (namespace.valueDeclaration && - ts.isVariableDeclaration(namespace.valueDeclaration) && - namespace.valueDeclaration.initializer && - isCommonJsRequire(namespace.valueDeclaration.initializer)) { - var moduleName = namespace.valueDeclaration.initializer.arguments[0]; - var moduleSym = resolveExternalModuleName(moduleName, moduleName); - if (moduleSym) { - var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); - if (resolvedModuleSymbol) { - namespace = resolvedModuleSymbol; - } + if (namespace.valueDeclaration && + ts.isInJSFile(namespace.valueDeclaration) && + ts.isVariableDeclaration(namespace.valueDeclaration) && + namespace.valueDeclaration.initializer && + isCommonJsRequire(namespace.valueDeclaration.initializer)) { + var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + var moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; } } } @@ -46525,7 +47734,7 @@ var ts; throw ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); - if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 266 /* ExportAssignment */)) { + if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 267 /* ExportAssignment */)) { markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true); } return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); @@ -46762,7 +47971,7 @@ var ts; function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { - if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 297 /* SourceFile */)) { + if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 298 /* SourceFile */)) { var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop"; @@ -46813,7 +48022,10 @@ var ts; var exports = getExportsOfModuleAsArray(moduleSymbol); var exportEquals = resolveExternalModuleSymbol(moduleSymbol); if (exportEquals !== moduleSymbol) { - ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); + var type = getTypeOfSymbol(exportEquals); + if (shouldTreatPropertiesOfExternalModuleAsExports(type)) { + ts.addRange(exports, getPropertiesOfType(type)); + } } return exports; } @@ -46833,11 +48045,14 @@ var ts; return undefined; } var type = getTypeOfSymbol(exportEquals); - return type.flags & 131068 /* Primitive */ || - ts.getObjectFlags(type) & 1 /* Class */ || - isArrayOrTupleLikeType(type) - ? undefined - : getPropertyOfType(type, memberName); + return shouldTreatPropertiesOfExternalModuleAsExports(type) ? getPropertyOfType(type, memberName) : undefined; + } + function shouldTreatPropertiesOfExternalModuleAsExports(resolvedExternalModuleType) { + return !(resolvedExternalModuleType.flags & 131068 /* Primitive */ || + ts.getObjectFlags(resolvedExternalModuleType) & 1 /* Class */ || + // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path + isArrayType(resolvedExternalModuleType) || + isTupleType(resolvedExternalModuleType)); } function getExportsOfSymbol(symbol) { return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : @@ -46895,11 +48110,13 @@ var ts; if (exportStars) { var nestedSymbols = ts.createSymbolTable(); var lookupTable_1 = new ts.Map(); - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - var exportedSymbols = visit(resolvedModule); - extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + if (exportStars.declarations) { + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + } } lookupTable_1.forEach(function (_a, id) { var exportsWithDuplicate = _a.exportsWithDuplicate; @@ -46982,11 +48199,28 @@ var ts; var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); var objectLiteralContainer = getVariableDeclarationOfObjectLiteral(container, meaning); - if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { + if (enclosingDeclaration && + container.flags & getQualifiedLeftMeaning(meaning) && + getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { return ts.append(ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers), objectLiteralContainer); // This order expresses a preference for the real container if it is in scope } - var res = ts.append(ts.append(additionalContainers, container), objectLiteralContainer); - return ts.concatenate(res, reexportContainers); + // we potentially have a symbol which is a member of the instance side of something - look for a variable in scope with the container's type + // which may be acting like a namespace (eg, `Symbol` acts like a namespace when looking up `Symbol.toStringTag`) + var firstVariableMatch = !(container.flags & getQualifiedLeftMeaning(meaning)) + && container.flags & 788968 /* Type */ + && getDeclaredTypeOfSymbol(container).flags & 524288 /* Object */ + && meaning === 111551 /* Value */ + ? forEachSymbolTableInScope(enclosingDeclaration, function (t) { + return ts.forEachEntry(t, function (s) { + if (s.flags & getQualifiedLeftMeaning(meaning) && getTypeOfSymbol(s) === getDeclaredTypeOfSymbol(container)) { + return s; + } + }); + }) : undefined; + var res = firstVariableMatch ? __spreadArray(__spreadArray([firstVariableMatch], additionalContainers), [container]) : __spreadArray(__spreadArray([], additionalContainers), [container]); + res = ts.append(res, objectLiteralContainer); + res = ts.addRange(res, reexportContainers); + return res; } var candidates = ts.mapDefined(symbol.declarations, function (d) { if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) { @@ -47064,7 +48298,7 @@ var ts; var members = node.members; for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { var member = members_3[_i]; - if (member.kind === 166 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 167 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -47073,7 +48307,9 @@ var ts; var result = new Type(checker, flags); typeCount++; result.id = typeCount; - typeCatalog.push(result); + if (produceDiagnostics) { // Only record types from one checker + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.recordType(result); + } return result; } function createOriginType(flags) { @@ -47133,14 +48369,23 @@ var ts; }); return result || ts.emptyArray; } + function getNamedOrIndexSignatureMembers(members) { + var result = getNamedMembers(members); + var index = getIndexSymbolFromSymbolTable(members); + return index ? ts.concatenate(result, [index]) : result; + } function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - type.members = members; - type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members); - type.callSignatures = callSignatures; - type.constructSignatures = constructSignatures; - type.stringIndexInfo = stringIndexInfo; - type.numberIndexInfo = numberIndexInfo; - return type; + var resolved = type; + resolved.members = members; + resolved.properties = ts.emptyArray; + resolved.callSignatures = callSignatures; + resolved.constructSignatures = constructSignatures; + resolved.stringIndexInfo = stringIndexInfo; + resolved.numberIndexInfo = numberIndexInfo; + // This can loop back to getPropertyOfType() which would crash if `callSignatures` & `constructSignatures` are not initialized. + if (members !== emptySymbols) + resolved.properties = getNamedMembers(members); + return resolved; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); @@ -47163,28 +48408,28 @@ var ts; var _loop_8 = function (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { - if (result = callback(location.locals)) { + if (result = callback(location.locals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } } switch (location.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } // falls through - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var sym = getSymbolOfNode(location); // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred // to one another anyway) - if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) { + if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: // Type parameters are bound into `members` lists so they can merge across declarations // This is troublesome, since in all other respects, they behave like locals :cries: // TODO: the below is shared with similar code in `resolveName` - in fact, rephrasing all this symbol @@ -47210,7 +48455,7 @@ var ts; if (typeof state_2 === "object") return state_2.value; } - return callback(globals); + return callback(globals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true); } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace @@ -47230,11 +48475,11 @@ var ts; /** * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) */ - function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification, isLocalNameLookup) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - var result = trySymbolTable(symbols, ignoreQualification); + var result = trySymbolTable(symbols, ignoreQualification, isLocalNameLookup); visitedSymbolTables.pop(); return result; } @@ -47252,7 +48497,7 @@ var ts; !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning)); } - function trySymbolTable(symbols, ignoreQualification) { + function trySymbolTable(symbols, ignoreQualification, isLocalNameLookup) { // If symbol is directly available by its name in the symbol table if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { return [symbol]; @@ -47265,9 +48510,11 @@ var ts; && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // If we're looking up a local name to reference directly, omit namespace reexports, otherwise when we're trawling through an export list to make a dotted name, we can keep it + && (isLocalNameLookup ? !ts.some(symbolFromSymbolTable.declarations, ts.isNamespaceReexportDeclaration) : true) // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ // See similar comment in `resolveName` for details - && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 270 /* ExportSpecifier */))) { + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 271 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification); if (candidate) { @@ -47311,7 +48558,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 270 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 271 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -47326,10 +48573,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: continue; default: return false; @@ -47367,7 +48614,7 @@ var ts; return hasAccessibleDeclarations; } } - else if (allowModules) { + if (allowModules) { if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { if (shouldComputeAliasesToMakeVisible) { earlyModuleBail = true; @@ -47441,7 +48688,8 @@ var ts; return { accessibility: 2 /* CannotBeNamed */, errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), - errorModuleName: symbolToString(symbolExternalModule) + errorModuleName: symbolToString(symbolExternalModule), + errorNode: ts.isInJSFile(enclosingDeclaration) ? enclosingDeclaration : undefined, }; } } @@ -47458,10 +48706,10 @@ var ts; return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { - return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -47517,14 +48765,14 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 176 /* TypeQuery */ || + if (entityName.parent.kind === 177 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || - entityName.parent.kind === 158 /* ComputedPropertyName */) { + entityName.parent.kind === 159 /* ComputedPropertyName */) { // Typeof value meaning = 111551 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 157 /* QualifiedName */ || entityName.kind === 201 /* PropertyAccessExpression */ || - entityName.parent.kind === 260 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 158 /* QualifiedName */ || entityName.kind === 202 /* PropertyAccessExpression */ || + entityName.parent.kind === 261 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1920 /* Namespace */; @@ -47565,7 +48813,7 @@ var ts; function symbolToStringWorker(writer) { var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217 // add neverAsciiEscape for GH#39027 - var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 297 /* SourceFile */ ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true }); + var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 298 /* SourceFile */ ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); return writer; @@ -47577,10 +48825,10 @@ var ts; function signatureToStringWorker(writer) { var sigOutput; if (flags & 262144 /* WriteArrowStyleSignature */) { - sigOutput = kind === 1 /* Construct */ ? 175 /* ConstructorType */ : 174 /* FunctionType */; + sigOutput = kind === 1 /* Construct */ ? 176 /* ConstructorType */ : 175 /* FunctionType */; } else { - sigOutput = kind === 1 /* Construct */ ? 170 /* ConstructSignature */ : 169 /* CallSignature */; + sigOutput = kind === 1 /* Construct */ ? 171 /* ConstructSignature */ : 170 /* CallSignature */; } var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); @@ -47620,14 +48868,14 @@ var ts; return typeToString(type, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); } function symbolValueDeclarationIsContextSensitive(symbol) { - return symbol && symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration); + return symbol && !!symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration); } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0 /* None */; } return flags & 814775659 /* NodeBuilderFlagsMask */; } function isClassInstanceSide(type) { - return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(ts.getObjectFlags(type) & 1073741824 /* IsClassInstanceClone */)); + return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288 /* Object */) && !!(ts.getObjectFlags(type) & 16777216 /* IsClassInstanceClone */))); } function createNodeBuilder() { return { @@ -47961,7 +49209,9 @@ var ts; 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 === 221 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || + else if (symbol.flags & 32 /* Class */ + && !getBaseTypeVariableOfClass(symbol) + && !(symbol.valueDeclaration && symbol.valueDeclaration.kind === 222 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, isInstanceType); @@ -47992,7 +49242,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 297 /* SourceFile */ || declaration.parent.kind === 257 /* ModuleBlock */; + return declaration.parent.kind === 298 /* SourceFile */ || declaration.parent.kind === 258 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -48043,12 +49293,12 @@ var ts; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 174 /* FunctionType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 175 /* FunctionType */, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 175 /* ConstructorType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 176 /* ConstructorType */, context); return signatureNode; } } @@ -48228,17 +49478,17 @@ var ts; var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 169 /* CallSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 170 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; if (signature.flags & 4 /* Abstract */) continue; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 170 /* ConstructSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 171 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { var indexSignature = void 0; - if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + if (resolvedType.objectFlags & 1024 /* ReverseMapped */) { indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context, createElidedInformationPlaceholder(context)); } else { @@ -48282,15 +49532,29 @@ var ts; } return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } + function shouldUsePlaceholderForProperty(propertySymbol, context) { + var _a; + // Use placeholders for reverse mapped types we've either already descended into, or which + // are nested reverse mappings within a mapping over a non-anonymous type. The later is a restriction mostly just to + // reduce the blowup in printback size from doing, eg, a deep reverse mapping over `Window`. + // Since anonymous types usually come from expressions, this allows us to preserve the output + // for deep mappings which likely come from expressions, while truncating those parts which + // come from mappings over library functions. + return !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */) + && (ts.contains(context.reverseMappedStack, propertySymbol) + || (((_a = context.reverseMappedStack) === null || _a === void 0 ? void 0 : _a[0]) + && !(ts.getObjectFlags(ts.last(context.reverseMappedStack).propertyType) & 16 /* Anonymous */))); + } function addPropertyToElementList(propertySymbol, context, typeElements) { + var _a; var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */); - var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? + var propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */ && isLateBoundName(propertySymbol.escapedName)) { var decl = ts.first(propertySymbol.declarations); - if (hasLateBindableName(decl)) { + if (propertySymbol.declarations && hasLateBindableName(decl)) { if (ts.isBinaryExpression(decl)) { var name = ts.getNameOfDeclaration(decl); if (name && ts.isElementAccessExpression(name) && ts.isPropertyAccessEntityNameExpression(name.argumentExpression)) { @@ -48302,29 +49566,34 @@ var ts; } } } - context.enclosingDeclaration = saveEnclosingDeclaration; + context.enclosingDeclaration = propertySymbol.valueDeclaration || ((_a = propertySymbol.declarations) === null || _a === void 0 ? void 0 : _a[0]) || saveEnclosingDeclaration; var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context); + context.enclosingDeclaration = saveEnclosingDeclaration; context.approximateLength += (ts.symbolName(propertySymbol).length + 1); var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */); for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { var signature = signatures_1[_i]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 164 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken }); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 165 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken }); typeElements.push(preserveCommentsOn(methodDeclaration)); } } else { - var savedFlags = context.flags; - context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; var propertyTypeNode = void 0; - if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + if (shouldUsePlaceholderForProperty(propertySymbol, context)) { propertyTypeNode = createElidedInformationPlaceholder(context); } else { + if (propertyIsReverseMapped) { + context.reverseMappedStack || (context.reverseMappedStack = []); + context.reverseMappedStack.push(propertySymbol); + } propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); + if (propertyIsReverseMapped) { + context.reverseMappedStack.pop(); + } } - context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(142 /* ReadonlyKeyword */)] : undefined; if (modifiers) { context.approximateLength += 9; @@ -48333,9 +49602,10 @@ var ts; typeElements.push(preserveCommentsOn(propertySignature)); } function preserveCommentsOn(node) { - if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 333 /* JSDocPropertyTag */; })) { - var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 333 /* JSDocPropertyTag */; }); - var commentText = d.comment; + var _a; + if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 337 /* JSDocPropertyTag */; })) { + var d = (_a = propertySymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 337 /* JSDocPropertyTag */; }); + var commentText = ts.getTextOfJSDocComment(d.comment); if (commentText) { ts.setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]); } @@ -48364,25 +49634,25 @@ var ts; var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */); /** Map from type reference identifier text to [type, index in `result` where the type node is] */ var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; - var result_4 = []; + var result_5 = []; var i = 0; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var type = types_2[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result_4.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + result_5.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result_4.push(typeNode_1); + result_5.push(typeNode_1); } break; } context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result_4.push(typeNode); + result_5.push(typeNode); if (seenNames && ts.isIdentifierTypeReference(typeNode)) { - seenNames.add(typeNode.typeName.escapedText, [type, result_4.length - 1]); + seenNames.add(typeNode.typeName.escapedText, [type, result_5.length - 1]); } } } @@ -48404,13 +49674,13 @@ var ts; })) { for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { var _a = types_3[_i], type = _a[0], resultIndex = _a[1]; - result_4[resultIndex] = typeToTypeNodeHelper(type, context); + result_5[resultIndex] = typeToTypeNodeHelper(type, context); } } }); context.flags = saveContextFlags; } - return result_4; + return result_5; } } function typesAreSameReference(a, b) { @@ -48452,7 +49722,7 @@ var ts; } var expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0]; // If the expanded parameter list had a variadic in a non-trailing position, don't expand it - var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 166 /* Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); + var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 167 /* Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -48479,25 +49749,25 @@ var ts; } } var modifiers = options === null || options === void 0 ? void 0 : options.modifiers; - if ((kind === 175 /* ConstructorType */) && signature.flags & 4 /* Abstract */) { + if ((kind === 176 /* ConstructorType */) && signature.flags & 4 /* Abstract */) { var flags = ts.modifiersToFlags(modifiers); modifiers = ts.factory.createModifiersFromModifierFlags(flags | 128 /* Abstract */); } context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum - var node = kind === 169 /* CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : - kind === 170 /* ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : - kind === 164 /* MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : - kind === 165 /* MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === 166 /* Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) : - kind === 167 /* GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : - kind === 168 /* SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : - kind === 171 /* IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) : - kind === 308 /* JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : - kind === 174 /* FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 175 /* ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 251 /* FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === 208 /* FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : - kind === 209 /* ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) : + var node = kind === 170 /* CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : + kind === 171 /* ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : + kind === 165 /* MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : + kind === 166 /* MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 167 /* Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) : + kind === 168 /* GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : + kind === 169 /* SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : + kind === 172 /* IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) : + kind === 309 /* JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : + kind === 175 /* FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : + kind === 176 /* ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : + kind === 252 /* FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 209 /* FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : + kind === 210 /* ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) : ts.Debug.assertNever(kind); if (typeArguments) { node.typeArguments = ts.factory.createNodeArray(typeArguments); @@ -48519,9 +49789,9 @@ var ts; return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 160 /* Parameter */); + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 161 /* Parameter */); if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 326 /* JSDocParameterTag */); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 330 /* JSDocParameterTag */); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -48536,7 +49806,7 @@ var ts; var dotDotDotToken = isRest ? ts.factory.createToken(25 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 78 /* Identifier */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : - parameterDeclaration.name.kind === 157 /* QualifiedName */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 158 /* QualifiedName */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); @@ -48701,11 +49971,11 @@ var ts; } function getSpecifierForModuleSymbol(symbol, context) { var _a; - var file = ts.getDeclarationOfKind(symbol, 297 /* SourceFile */); + var file = ts.getDeclarationOfKind(symbol, 298 /* SourceFile */); if (!file) { var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); }); if (equivalentFileSymbol) { - file = ts.getDeclarationOfKind(equivalentFileSymbol, 297 /* SourceFile */); + file = ts.getDeclarationOfKind(equivalentFileSymbol, 298 /* SourceFile */); } } if (file && file.moduleName !== undefined) { @@ -48716,8 +49986,8 @@ var ts; if (context.tracker.trackReferencedAmbientModule) { var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); if (ts.length(ambientDecls)) { - for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { - var decl = ambientDecls_1[_i]; + for (var _i = 0, _b = ambientDecls; _i < _b.length; _i++) { + var decl = _b[_i]; context.tracker.trackReferencedAmbientModule(decl, symbol); } } @@ -48744,7 +50014,7 @@ var ts; // specifier preference var moduleResolverHost = context.tracker.moduleResolverHost; var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; - specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "project-relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); (_a = links.specifierCache) !== null && _a !== void 0 ? _a : (links.specifierCache = new ts.Map()); links.specifierCache.set(contextFile.path, specifier); } @@ -48888,7 +50158,7 @@ var ts; var chain = lookupSymbolChain(symbol, context, meaning); if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) { + && !(context.flags & 65536 /* AllowQualifiedNameInPlaceOfIdentifier */)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); @@ -48968,9 +50238,6 @@ var ts; if (fromNameType) { return fromNameType; } - if (ts.isKnownSymbol(symbol)) { - return ts.factory.createComputedPropertyName(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("Symbol"), symbol.escapedName.substr(3))); - } var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName); var stringNamed = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isStringNamed); return createPropertyNameNodeForIdentifierOrLiteral(rawName, stringNamed, singleQuote); @@ -49037,13 +50304,13 @@ var ts; function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { if (type !== errorType && enclosingDeclaration) { var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation) && !ts.isGetAccessorDeclaration(declWithExistingAnnotation)) { // try to reuse the existing annotation var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { - var result_5 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); - if (result_5) { - return result_5; + var result_6 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_6) { + return result_6; } } } @@ -49060,10 +50327,14 @@ var ts; function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { if (type !== errorType && context.enclosingDeclaration) { var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); - if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { - var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); - if (result) { - return result; + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation) { + var annotated = getTypeFromTypeNode(annotation); + var thisInstantiated = annotated.flags & 262144 /* TypeParameter */ && annotated.isThisType ? instantiateType(annotated, signature.mapper) : annotated; + if (thisInstantiated === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } } } } @@ -49107,7 +50378,7 @@ var ts; return transformed === existing ? ts.setTextRange(ts.factory.cloneNode(existing), existing) : transformed; function visitExistingNodeTreeSymbols(node) { // We don't _actually_ support jsdoc namepath types, emit `any` instead - if (ts.isJSDocAllType(node) || node.kind === 310 /* JSDocNamepathType */) { + if (ts.isJSDocAllType(node) || node.kind === 311 /* JSDocNamepathType */) { return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } if (ts.isJSDocUnknownType(node)) { @@ -49226,8 +50497,8 @@ var ts; } } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { - var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 165 /* MethodDeclaration */, /*useAcessors*/ true); - var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 164 /* MethodSignature */, /*useAcessors*/ false); + var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 166 /* MethodDeclaration */, /*useAcessors*/ true); + var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 165 /* MethodSignature */, /*useAcessors*/ false); // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of // declaration mapping // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration @@ -49239,7 +50510,7 @@ var ts; var deferredPrivatesStack = []; var oldcontext = context; context = __assign(__assign({}, oldcontext), { usedSymbolNames: new ts.Set(oldcontext.usedSymbolNames), remappedSymbolNames: new ts.Map(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { - var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false); + var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeAliases*/ false); if (accessibleResult.accessibility === 0 /* Accessible */) { // Lookup the root symbol of the chain of refs we'll use to access it and serialize it var chain = lookupSymbolChainWorker(sym, context, meaning); @@ -49448,6 +50719,7 @@ var ts; // If it's a class/interface/function: emit a class/interface/function with a `default` modifier // These forms can merge, eg (`export default 12; export default interface A {}`) function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) { + var _a, _b; var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName); var isDefault = symbol.escapedName === "default" /* Default */; if (isPrivate && !(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) { @@ -49506,9 +50778,9 @@ var ts; if (textRange && ts.isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) { textRange = textRange.parent.parent; } - var propertyAccessRequire = ts.find(symbol.declarations, ts.isPropertyAccessExpression); + var propertyAccessRequire = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isPropertyAccessExpression); if (propertyAccessRequire && ts.isBinaryExpression(propertyAccessRequire.parent) && ts.isIdentifier(propertyAccessRequire.parent.right) - && type.symbol && ts.isSourceFile(type.symbol.valueDeclaration)) { + && ((_b = type.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration) && ts.isSourceFile(type.symbol.valueDeclaration)) { var alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right; addResult(ts.factory.createExportDeclaration( /*decorators*/ undefined, @@ -49558,7 +50830,10 @@ var ts; serializeEnum(symbol, symbolName, modifierFlags); } if (symbol.flags & 32 /* Class */) { - if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { + if (symbol.flags & 4 /* Property */ + && symbol.valueDeclaration + && ts.isBinaryExpression(symbol.valueDeclaration.parent) + && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members, // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today. @@ -49584,12 +50859,14 @@ var ts; if (symbol.flags & 8388608 /* ExportStar */) { // synthesize export * from "moduleReference" // Straightforward - only one thing to do - make an export declaration - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - if (!resolvedModule) - continue; - addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */); + if (symbol.declarations) { + for (var _i = 0, _c = symbol.declarations; _i < _c.length; _i++) { + var node = _c[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + if (!resolvedModule) + continue; + addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */); + } } } if (needsPostExportDefault) { @@ -49627,15 +50904,16 @@ var ts; function addResult(node, additionalModifierFlags) { if (ts.canHaveModifiers(node)) { var newModifierFlags = 0 /* None */; + var enclosingDeclaration_1 = context.enclosingDeclaration && + (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 /* Export */ && - context.enclosingDeclaration && - (isExportingScope(context.enclosingDeclaration) || ts.isModuleDeclaration(context.enclosingDeclaration)) && + enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && canHaveExportModifier(node)) { // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private newModifierFlags |= 1 /* Export */; } if (addingDeclare && !(newModifierFlags & 1 /* Export */) && - (!context.enclosingDeclaration || !(context.enclosingDeclaration.flags & 8388608 /* Ambient */)) && + (!enclosingDeclaration_1 || !(enclosingDeclaration_1.flags & 8388608 /* Ambient */)) && (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) { // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope newModifierFlags |= 2 /* Ambient */; @@ -49650,19 +50928,23 @@ var ts; results.push(node); } function serializeTypeAlias(symbol, symbolName, modifierFlags) { + var _a; var aliasType = getDeclaredTypeOfTypeAlias(symbol); var typeParams = getSymbolLinks(symbol).typeParameters; var typeParamDecls = ts.map(typeParams, function (p) { return typeParameterToDeclaration(p, context); }); - var jsdocAliasDecl = ts.find(symbol.declarations, ts.isJSDocTypeAlias); - var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined; + var jsdocAliasDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isJSDocTypeAlias); + var commentText = ts.getTextOfJSDocComment(jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined); var oldFlags = context.flags; context.flags |= 8388608 /* InTypeAlias */; + var oldEnclosingDecl = context.enclosingDeclaration; + context.enclosingDeclaration = jsdocAliasDecl; var typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; + context.enclosingDeclaration = oldEnclosingDecl; } function serializeInterface(symbol, symbolName, modifierFlags) { var interfaceType = getDeclaredTypeOfClassOrInterface(symbol); @@ -49671,8 +50953,8 @@ var ts; var baseTypes = getBaseTypes(interfaceType); var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined; var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); }); - var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 169 /* CallSignature */); - var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 170 /* ConstructSignature */); + var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 170 /* CallSignature */); + var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 171 /* ConstructSignature */); var indexSignatures = serializeIndexSignatures(interfaceType, baseType); var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(93 /* ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551 /* Value */); }))]; addResult(ts.factory.createInterfaceDeclaration( @@ -49741,9 +51023,8 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; // Each overload becomes a separate function declaration, in order - var decl = signatureToSignatureDeclarationHelper(sig, 251 /* FunctionDeclaration */, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled }); - // for expressions assigned to `var`s, use the `var` as the text range - addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags); + var decl = signatureToSignatureDeclarationHelper(sig, 252 /* FunctionDeclaration */, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled }); + addResult(ts.setTextRange(decl, getSignatureTextRangeLocation(sig)), modifierFlags); } // Module symbol emit will take care of module-y members, provided it has exports if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) { @@ -49751,6 +51032,18 @@ var ts; serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true); } } + function getSignatureTextRangeLocation(signature) { + if (signature.declaration && signature.declaration.parent) { + if (ts.isBinaryExpression(signature.declaration.parent) && ts.getAssignmentDeclarationKind(signature.declaration.parent) === 5 /* Property */) { + return signature.declaration.parent; + } + // for expressions assigned to `var`s, use the `var` as the text range + if (ts.isVariableDeclaration(signature.declaration.parent) && signature.declaration.parent.parent) { + return signature.declaration.parent.parent; + } + } + return signature.declaration; + } function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) { if (ts.length(props)) { var localVsRemoteMap = ts.arrayToMultiMap(props, function (p) { @@ -49837,8 +51130,8 @@ var ts; return undefined; } function serializeAsClass(symbol, localName, modifierFlags) { - var _a; - var originalDecl = ts.find(symbol.declarations, ts.isClassLike); + var _a, _b; + var originalDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isClassLike); var oldEnclosing = context.enclosingDeclaration; context.enclosingDeclaration = originalDecl || oldEnclosing; var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -49849,7 +51142,7 @@ var ts; var implementsExpressions = originalImplements && sanitizeJSDocImplements(originalImplements) || ts.mapDefined(getImplementsTypes(classType), serializeImplementedType); var staticType = getTypeOfSymbol(symbol); - var isClass = !!((_a = staticType.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration) && ts.isClassLike(staticType.symbol.valueDeclaration); + var isClass = !!((_b = staticType.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration) && ts.isClassLike(staticType.symbol.valueDeclaration); var staticBaseType = isClass ? getBaseConstructorTypeOfClass(staticType) : anyType; @@ -49860,14 +51153,14 @@ var ts; // a union/intersection base type, but inherited properties // don't matter here. var valueDecl = s.valueDeclaration; - return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); + return !!valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); }); var hasPrivateIdentifier = ts.some(symbolProps, function (s) { // `valueDeclaration` could be undefined if inherited from // a union/intersection base type, but inherited properties // don't matter here. var valueDecl = s.valueDeclaration; - return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); + return !!valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); }); // Boil down all private properties into a single one. var privateProperties = hasPrivateIdentifier ? @@ -49890,7 +51183,7 @@ var ts; !ts.some(getSignaturesOfType(staticType, 1 /* Construct */)); var constructors = isNonConstructableClassLikeInJsFile ? [ts.factory.createConstructorDeclaration(/*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(8 /* Private */), [], /*body*/ undefined)] : - serializeSignatures(1 /* Construct */, staticType, staticBaseType, 166 /* Constructor */); + serializeSignatures(1 /* Construct */, staticType, staticBaseType, 167 /* Constructor */); var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); context.enclosingDeclaration = oldEnclosing; addResult(ts.setTextRange(ts.factory.createClassDeclaration( @@ -49917,8 +51210,8 @@ var ts; var targetName = getInternalSymbolName(target, verbatimTargetName); includePrivateSymbol(target); // the target may be within the same scope - attempt to serialize it first switch (node.kind) { - case 198 /* BindingElement */: - if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 249 /* VariableDeclaration */) { + case 199 /* BindingElement */: + if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 250 /* VariableDeclaration */) { // const { SomeClass } = require('./lib'); var specifier_1 = getSpecifierForModuleSymbol(target.parent || target, context); // './lib' var propertyName = node.propertyName; @@ -49930,13 +51223,13 @@ var ts; // We don't know how to serialize this (nested?) binding element ts.Debug.failBadSyntaxKind(((_c = node.parent) === null || _c === void 0 ? void 0 : _c.parent) || node, "Unhandled binding element grandparent kind in declaration serialization"); break; - case 289 /* ShorthandPropertyAssignment */: - if (((_e = (_d = node.parent) === null || _d === void 0 ? void 0 : _d.parent) === null || _e === void 0 ? void 0 : _e.kind) === 216 /* BinaryExpression */) { + case 290 /* ShorthandPropertyAssignment */: + if (((_e = (_d = node.parent) === null || _d === void 0 ? void 0 : _d.parent) === null || _e === void 0 ? void 0 : _e.kind) === 217 /* BinaryExpression */) { // module.exports = { SomeClass } serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), targetName); } break; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: // commonjs require: const x = require('y') if (ts.isPropertyAccessExpression(node.initializer)) { // const x = require('y').z @@ -49956,7 +51249,7 @@ var ts; break; } // else fall through and treat commonjs require just like import= - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // This _specifically_ only exists to handle json declarations - where we make aliases, but since // we emit no declarations for the json document, must not refer to it in the declarations if (target.escapedName === "export=" /* ExportEquals */ && ts.some(target.declarations, ts.isJsonSourceFile)) { @@ -49973,13 +51266,13 @@ var ts; ? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false) : ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)))), isLocalImport ? modifierFlags : 0 /* None */); break; - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: // export as namespace foo // TODO: Not part of a file's local or export symbol tables // Is bound into file.symbol.globalExports instead, which we don't currently traverse addResult(ts.factory.createNamespaceExportDeclaration(ts.idText(node.name)), 0 /* None */); break; - case 262 /* ImportClause */: + case 263 /* ImportClause */: addResult(ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, ts.factory.createIdentifier(localName), /*namedBindings*/ undefined), @@ -49988,18 +51281,18 @@ var ts; // In such cases, the `target` refers to the module itself already ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: addResult(ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */); break; - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: addResult(ts.factory.createExportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */); break; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: addResult(ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause( @@ -50008,7 +51301,7 @@ var ts; ts.factory.createImportSpecifier(localName !== verbatimTargetName ? ts.factory.createIdentifier(verbatimTargetName) : undefined, ts.factory.createIdentifier(localName)) ])), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: // does not use localName because the symbol name in this case refers to the name in the exports table, // which we must exactly preserve var specifier = node.parent.parent.moduleSpecifier; @@ -50016,12 +51309,12 @@ var ts; // another file serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.factory.createStringLiteral(specifier.text) : undefined); break; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: serializeMaybeAliasAssignment(symbol); break; - case 216 /* BinaryExpression */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 217 /* BinaryExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: // Could be best encoded as though an export specifier or as though an export assignment // If name is default or export=, do an export assignment // Otherwise do an export specifier @@ -50155,6 +51448,7 @@ var ts; } function makeSerializePropertySymbol(createProperty, methodKind, useAccessors) { return function serializePropertySymbol(p, isStatic, baseType) { + var _a, _b, _c, _d, _e; var modifierFlags = ts.getDeclarationModifierFlagsFromSymbol(p); var isPrivate = !!(modifierFlags & 8 /* Private */); if (isStatic && (p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */))) { @@ -50171,7 +51465,7 @@ var ts; } var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0); var name = getPropertyNameNodeForSymbol(p, context); - var firstPropertyLikeDecl = ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression)); + var firstPropertyLikeDecl = (_a = p.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression)); if (p.flags & 98304 /* Accessor */ && useAccessors) { var result = []; if (p.flags & 65536 /* SetAccessor */) { @@ -50181,13 +51475,13 @@ var ts; /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "arg", /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], - /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl)); + /*body*/ undefined), ((_b = p.declarations) === null || _b === void 0 ? void 0 : _b.find(ts.isSetAccessor)) || firstPropertyLikeDecl)); } if (p.flags & 32768 /* GetAccessor */) { var isPrivate_1 = modifierFlags & 8 /* Private */; result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration( /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), - /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl)); + /*body*/ undefined), ((_c = p.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isGetAccessor)) || firstPropertyLikeDecl)); } return result; } @@ -50198,7 +51492,7 @@ var ts; /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ - /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl); + /*initializer*/ undefined), ((_d = p.declarations) === null || _d === void 0 ? void 0 : _d.find(ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration))) || firstPropertyLikeDecl); } if (p.flags & (8192 /* Method */ | 16 /* Function */)) { var type = getTypeOfSymbol(p); @@ -50207,7 +51501,7 @@ var ts; return ts.setTextRange(createProperty( /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, /*type*/ undefined, - /*initializer*/ undefined), ts.find(p.declarations, ts.isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations[0]); + /*initializer*/ undefined), ((_e = p.declarations) === null || _e === void 0 ? void 0 : _e.find(ts.isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); } var results_1 = []; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { @@ -50218,7 +51512,8 @@ var ts; questionToken: p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, modifiers: flag ? ts.factory.createModifiersFromModifierFlags(flag) : undefined }); - results_1.push(ts.setTextRange(decl, sig.declaration)); + var location = sig.declaration && ts.isPrototypePropertyAssignment(sig.declaration.parent) ? sig.declaration.parent : sig.declaration; + results_1.push(ts.setTextRange(decl, location)); } return results_1; } @@ -50434,9 +51729,9 @@ var ts; return "public"; } function getTypeAliasForTypeLiteral(type) { - if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { + if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */ && type.symbol.declarations) { var node = ts.walkUpParenthesizedTypes(type.symbol.declarations[0].parent); - if (node.kind === 254 /* TypeAliasDeclaration */) { + if (node.kind === 255 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -50444,11 +51739,11 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 257 /* ModuleBlock */ && + node.parent.kind === 258 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } function isDefaultBindingContext(location) { - return location.kind === 297 /* SourceFile */ || ts.isAmbientModule(location); + return location.kind === 298 /* SourceFile */ || ts.isAmbientModule(location); } function getNameOfSymbolFromNameType(symbol, context) { var nameType = getSymbolLinks(symbol).nameType; @@ -50507,17 +51802,17 @@ var ts; if (!declaration) { declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway } - if (declaration.parent && declaration.parent.kind === 249 /* VariableDeclaration */) { + if (declaration.parent && declaration.parent.kind === 250 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } switch (declaration.kind) { - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { context.encounteredError = true; } - return declaration.kind === 221 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; + return declaration.kind === 222 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } var name = getNameOfSymbolFromNameType(symbol, context); @@ -50534,28 +51829,28 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: - case 325 /* JSDocEnumTag */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: + case 329 /* JSDocEnumTag */: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // falls through - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 251 /* FunctionDeclaration */: - case 255 /* EnumDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 252 /* FunctionDeclaration */: + case 256 /* EnumDeclaration */: + case 261 /* ImportEqualsDeclaration */: // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; @@ -50563,55 +51858,55 @@ var ts; var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 260 /* ImportEqualsDeclaration */ && parent.kind !== 297 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) { + !(node.kind !== 261 /* ImportEqualsDeclaration */ && parent.kind !== 298 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible return isDeclarationVisible(parent); - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasEffectiveModifier(node, 8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so: // falls through - case 166 /* Constructor */: - case 170 /* ConstructSignature */: - case 169 /* CallSignature */: - case 171 /* IndexSignature */: - case 160 /* Parameter */: - case 257 /* ModuleBlock */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 177 /* TypeLiteral */: - case 173 /* TypeReference */: - case 178 /* ArrayType */: - case 179 /* TupleType */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 186 /* ParenthesizedType */: - case 192 /* NamedTupleMember */: + case 167 /* Constructor */: + case 171 /* ConstructSignature */: + case 170 /* CallSignature */: + case 172 /* IndexSignature */: + case 161 /* Parameter */: + case 258 /* ModuleBlock */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 178 /* TypeLiteral */: + case 174 /* TypeReference */: + case 179 /* ArrayType */: + case 180 /* TupleType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 187 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: return isDeclarationVisible(node.parent); // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: + case 266 /* ImportSpecifier */: return false; // Type parameters are always visible - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: // Source file and namespace export are always visible // falls through - case 297 /* SourceFile */: - case 259 /* NamespaceExportDeclaration */: + case 298 /* SourceFile */: + case 260 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return false; default: return false; @@ -50620,10 +51915,10 @@ var ts; } function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 266 /* ExportAssignment */) { + if (node.parent && node.parent.kind === 267 /* ExportAssignment */) { exportSymbol = resolveName(node, node.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } - else if (node.parent.kind === 270 /* ExportSpecifier */) { + else if (node.parent.kind === 271 /* ExportSpecifier */) { exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; @@ -50728,12 +52023,12 @@ var ts; function getDeclarationContainer(node) { return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 249 /* VariableDeclaration */: - case 250 /* VariableDeclarationList */: - case 265 /* ImportSpecifier */: - case 264 /* NamedImports */: - case 263 /* NamespaceImport */: - case 262 /* ImportClause */: + case 250 /* VariableDeclaration */: + case 251 /* VariableDeclarationList */: + case 266 /* ImportSpecifier */: + case 265 /* NamedImports */: + case 264 /* NamespaceImport */: + case 263 /* ImportClause */: return false; default: return true; @@ -50796,9 +52091,16 @@ var ts; var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= 131072 /* ObjectRestType */; + result.objectFlags |= 8388608 /* ObjectRestType */; return result; } + function isGenericTypeWithUndefinedConstraint(type) { + return !!(type.flags & 465829888 /* Instantiable */) && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 32768 /* Undefined */); + } + function getNonUndefinedType(type) { + var typeOrConstraint = someType(type, isGenericTypeWithUndefinedConstraint) ? mapType(type, function (t) { return t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type; + return getTypeWithFacts(typeOrConstraint, 524288 /* NEUndefined */); + } // Determine the control flow type associated with a destructuring declaration or assignment. The following // forms of destructuring are possible: // let { x } = obj; // BindingElement @@ -50833,23 +52135,23 @@ var ts; function getParentElementAccess(node) { var ancestor = node.parent.parent; switch (ancestor.kind) { - case 198 /* BindingElement */: - case 288 /* PropertyAssignment */: + case 199 /* BindingElement */: + case 289 /* PropertyAssignment */: return getSyntheticElementAccess(ancestor); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return getSyntheticElementAccess(node.parent); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return ancestor.initializer; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return ancestor.right; } } function getDestructuringPropertyName(node) { var parent = node.parent; - if (node.kind === 198 /* BindingElement */ && parent.kind === 196 /* ObjectBindingPattern */) { + if (node.kind === 199 /* BindingElement */ && parent.kind === 197 /* ObjectBindingPattern */) { return getLiteralPropertyNameText(node.propertyName || node.name); } - if (node.kind === 288 /* PropertyAssignment */ || node.kind === 289 /* ShorthandPropertyAssignment */) { + if (node.kind === 289 /* PropertyAssignment */ || node.kind === 290 /* ShorthandPropertyAssignment */) { return getLiteralPropertyNameText(node.name); } return "" + parent.elements.indexOf(node); @@ -50875,7 +52177,7 @@ var ts; parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */); } var type; - if (pattern.kind === 196 /* ObjectBindingPattern */) { + if (pattern.kind === 197 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { parentType = getReducedType(parentType); if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { @@ -50895,7 +52197,7 @@ var ts; // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name = declaration.propertyName || declaration.name; var indexType = getLiteralTypeFromPropertyName(name); - var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */), declaration.name); + var declaredType = getIndexedAccessType(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */); type = getFlowTypeOfDestructuring(declaration, declaredType); } } @@ -50916,7 +52218,7 @@ var ts; else if (isArrayLikeType(parentType)) { var indexType = getLiteralType(index_2); var accessFlags = hasDefaultValue(declaration) ? 8 /* NoTupleBoundsCheck */ : 0; - var declaredType = getConstraintForLocation(getIndexedAccessTypeOrUndefined(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, declaration.name, accessFlags | 16 /* ExpressionPosition */) || errorType, declaration.name); + var declaredType = getIndexedAccessTypeOrUndefined(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, declaration.name, accessFlags | 16 /* ExpressionPosition */) || errorType; type = getFlowTypeOfDestructuring(declaration, declaredType); } else { @@ -50929,11 +52231,9 @@ var ts; if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ? - getTypeWithFacts(type, 524288 /* NEUndefined */) : - type; + return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ? getNonUndefinedType(type) : type; } - return widenTypeInferredFromInitializer(declaration, getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), checkDeclarationInitializer(declaration)], 2 /* Subtype */)); + return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration)], 2 /* Subtype */)); } function getTypeForDeclarationFromJSDocComment(declaration) { var jsdocType = ts.getJSDocType(declaration); @@ -50948,7 +52248,7 @@ var ts; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 199 /* ArrayLiteralExpression */ && expr.elements.length === 0; + return expr.kind === 200 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { if (optional === void 0) { optional = true; } @@ -50958,11 +52258,11 @@ var ts; function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 238 /* ForInStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForInStatement */) { var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 240 /* ForOfStatement */) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -50999,8 +52299,8 @@ var ts; if (ts.isParameter(declaration)) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 168 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { - var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 167 /* GetAccessor */); + if (func.kind === 169 /* SetAccessor */ && hasBindableName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 168 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -51071,7 +52371,7 @@ var ts; links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && ts.every(symbol.declarations, function (declaration) { return ts.isBinaryExpression(declaration) && isPossiblyAliasedThisProperty(declaration) && - (declaration.left.kind !== 202 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && + (declaration.left.kind !== 203 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ undefined, declaration, symbol, declaration); }); } @@ -51087,13 +52387,33 @@ var ts; !declaration.initializer && (noImplicitAny || ts.isInJSFile(declaration)); } function getDeclaringConstructor(symbol) { + if (!symbol.declarations) { + return; + } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var container = ts.getThisContainer(declaration, /*includeArrowFunctions*/ false); - if (container && (container.kind === 166 /* Constructor */ || isJSConstructor(container))) { + if (container && (container.kind === 167 /* Constructor */ || isJSConstructor(container))) { return container; } } + ; + } + /** Create a synthetic property access flow node after the last statement of the file */ + function getFlowTypeFromCommonJSExport(symbol) { + var file = ts.getSourceFileOfNode(symbol.declarations[0]); + var accessName = ts.unescapeLeadingUnderscores(symbol.escapedName); + var areAllModuleExports = symbol.declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && ts.isModuleExportsAccessExpression(d.expression); }); + var reference = areAllModuleExports + ? ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("module"), ts.factory.createIdentifier("exports")), accessName) + : ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("exports"), accessName); + if (areAllModuleExports) { + ts.setParent(reference.expression.expression, reference.expression); + } + ts.setParent(reference.expression, reference); + ts.setParent(reference, file); + reference.flowNode = file.endFlowNode; + return getFlowTypeOfReference(reference, autoType, undefinedType); } function getFlowTypeInConstructor(symbol, constructor) { var accessName = ts.startsWith(symbol.escapedName, "__#") @@ -51111,7 +52431,10 @@ var ts; return everyType(flowType, isNullableType) ? undefined : convertAutoToAny(flowType); } function getFlowTypeOfProperty(reference, prop) { - var initialType = prop && (!isAutoTypedProperty(prop) || ts.getEffectiveModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType; + var initialType = (prop === null || prop === void 0 ? void 0 : prop.valueDeclaration) + && (!isAutoTypedProperty(prop) || ts.getEffectiveModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) + && getTypeOfPropertyInBaseClass(prop) + || undefinedType; return getFlowTypeOfReference(reference, autoType, initialType); } function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) { @@ -51122,7 +52445,7 @@ var ts; if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + var containerObjectType = symbol.valueDeclaration && getJSContainerObjectType(symbol.valueDeclaration, symbol, container); return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var type; @@ -51134,40 +52457,42 @@ var ts; type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol)); } if (!type) { - var jsdocType = void 0; var types = void 0; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : - ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : - undefined; - if (!expression) { - continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere - } - var kind = ts.isAccessExpression(expression) - ? ts.getAssignmentDeclarationPropertyAccessKind(expression) - : ts.getAssignmentDeclarationKind(expression); - if (kind === 4 /* ThisProperty */ || ts.isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) { - if (isDeclarationInConstructor(expression)) { - definedInConstructor = true; + if (symbol.declarations) { + var jsdocType = void 0; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : + ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere } - else { - definedInMethod = true; + var kind = ts.isAccessExpression(expression) + ? ts.getAssignmentDeclarationPropertyAccessKind(expression) + : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */ || ts.isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + if (!ts.isCallExpression(expression)) { + jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } - if (!ts.isCallExpression(expression)) { - jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); - } - if (!jsdocType) { - (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); - } + type = jsdocType; } - type = jsdocType; if (!type) { if (!ts.length(types)) { return errorType; // No types from any declarations :( } - var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; + var constructorTypes = definedInConstructor && symbol.declarations ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { var propType = getTypeOfPropertyInBaseClass(symbol); @@ -51181,7 +52506,7 @@ var ts; } } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); - if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { + if (symbol.valueDeclaration && filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } @@ -51205,10 +52530,11 @@ var ts; mergeSymbolTable(exports, s.exports); } var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - type.objectFlags |= 16384 /* JSLiteral */; + type.objectFlags |= 8192 /* JSLiteral */; return type; } function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) { + var _a; var typeNode = ts.getEffectiveTypeAnnotationNode(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -51219,7 +52545,7 @@ var ts; errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type); } } - if (symbol.parent) { + if ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) { var typeNode_2 = ts.getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration); if (typeNode_2) { return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode_2), symbol.escapedName); @@ -51283,7 +52609,7 @@ var ts; // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because // it's unclear what that's supposed to mean, so it's probably a mistake. - if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { + if (s.valueDeclaration && exportedMember.valueDeclaration && ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName); var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration; ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName)); @@ -51305,9 +52631,9 @@ var ts; }); var result = createAnonymousType(initialSize !== members_4.size ? undefined : exportedType.symbol, // Only set the type's symbol if it looks to be the same as the original type members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo); - result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + result.objectFlags |= (ts.getObjectFlags(type) & 8192 /* JSLiteral */); // Propagate JSLiteral flag if (result.symbol && result.symbol.flags & 32 /* Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { - result.objectFlags |= 1073741824 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type + result.objectFlags |= 16777216 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type } return result; } @@ -51326,9 +52652,9 @@ var ts; var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. // Function expressions that are assigned to the prototype count as methods. - return thisContainer.kind === 166 /* Constructor */ || - thisContainer.kind === 251 /* FunctionDeclaration */ || - (thisContainer.kind === 208 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + return thisContainer.kind === 167 /* Constructor */ || + thisContainer.kind === 252 /* FunctionDeclaration */ || + (thisContainer.kind === 209 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); } function getConstructorDefinedThisAssignmentTypes(types, declarations) { ts.Debug.assert(types.length === declarations.length); @@ -51366,7 +52692,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -51390,7 +52716,7 @@ var ts; result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -51398,7 +52724,7 @@ var ts; function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - var restElement = lastElement && lastElement.kind === 198 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : undefined; + var restElement = lastElement && lastElement.kind === 199 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : undefined; if (elements.length === 0 || elements.length === 1 && restElement) { return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } @@ -51409,7 +52735,7 @@ var ts; if (includePatternInType) { result = cloneTypeReference(result); result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -51423,7 +52749,7 @@ var ts; function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { if (includePatternInType === void 0) { includePatternInType = false; } if (reportErrors === void 0) { reportErrors = false; } - return pattern.kind === 196 /* ObjectBindingPattern */ + return pattern.kind === 197 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -51439,8 +52765,17 @@ var ts; function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors); } + function isGlobalSymbolConstructor(node) { + var symbol = getSymbolOfNode(node); + var globalSymbol = getGlobalESSymbolConstructorTypeSymbol(/*reportErrors*/ false); + return globalSymbol && symbol && symbol === globalSymbol; + } function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) { if (type) { + // TODO: If back compat with pre-3.0/4.0 libs isn't required, remove the following SymbolConstructor special case transforming `symbol` into `unique symbol` + if (type.flags & 4096 /* ESSymbol */ && isGlobalSymbolConstructor(declaration.parent)) { + type = getESSymbolLikeTypeForNode(declaration); + } if (reportErrors) { reportErrorsFromWidening(declaration, type); } @@ -51462,7 +52797,7 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 160 /* Parameter */ ? root.parent : root; + var memberDeclaration = root.kind === 161 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function tryGetTypeFromEffectiveTypeNode(declaration) { @@ -51493,19 +52828,31 @@ var ts; if (symbol === requireSymbol) { return anyType; } - if (symbol.flags & 134217728 /* ModuleExports */) { + if (symbol.flags & 134217728 /* ModuleExports */ && symbol.valueDeclaration) { var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var result = createSymbol(fileSymbol.flags, "exports"); + result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : []; + result.parent = symbol; + result.target = fileSymbol; + if (fileSymbol.valueDeclaration) + result.valueDeclaration = fileSymbol.valueDeclaration; + if (fileSymbol.members) + result.members = new ts.Map(fileSymbol.members); + if (fileSymbol.exports) + result.exports = new ts.Map(fileSymbol.exports); var members = ts.createSymbolTable(); - members.set("exports", fileSymbol); + members.set("exports", result); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); } // Handle catch clause variables + ts.Debug.assertIsDefined(symbol.valueDeclaration); var declaration = symbol.valueDeclaration; if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { - var decl = declaration; - if (!decl.type) + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode === undefined) { return anyType; - var type_1 = getTypeOfNode(decl.type); + } + var type_1 = getTypeOfNode(typeNode); // an errorType will make `checkTryStatement` issue an error return isTypeAny(type_1) || type_1 === unknownType ? type_1 : errorType; } @@ -51525,7 +52872,7 @@ var ts; return reportCircularityError(symbol); } var type; - if (declaration.kind === 266 /* ExportAssignment */) { + if (declaration.kind === 267 /* ExportAssignment */) { type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } else if (ts.isBinaryExpression(declaration) || @@ -51580,7 +52927,7 @@ var ts; type = getTypeOfEnumMember(symbol); } else if (ts.isAccessor(declaration)) { - type = resolveTypeOfAccessors(symbol); + type = resolveTypeOfAccessors(symbol) || ts.Debug.fail("Non-write accessor resolution must always produce a type"); } else { return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol)); @@ -51596,7 +52943,7 @@ var ts; } function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { - if (accessor.kind === 167 /* GetAccessor */) { + if (accessor.kind === 168 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation; } @@ -51620,63 +52967,78 @@ var ts; } function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); - return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + return links.type || (links.type = getTypeOfAccessorsWorker(symbol) || ts.Debug.fail("Read type of accessor must always produce a type")); + } + function getTypeOfSetAccessor(symbol) { + var links = getSymbolLinks(symbol); + return links.writeType || (links.writeType = getTypeOfAccessorsWorker(symbol, /*writing*/ true)); } - function getTypeOfAccessorsWorker(symbol) { + function getTypeOfAccessorsWorker(symbol, writing) { + if (writing === void 0) { writing = false; } if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } - var type = resolveTypeOfAccessors(symbol); + var type = resolveTypeOfAccessors(symbol, writing); if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter = ts.getDeclarationOfKind(symbol, 167 /* GetAccessor */); + var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); error(getter, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } return type; } - function resolveTypeOfAccessors(symbol) { - var getter = ts.getDeclarationOfKind(symbol, 167 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 168 /* SetAccessor */); + function resolveTypeOfAccessors(symbol, writing) { + if (writing === void 0) { writing = false; } + var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); + // For write operations, prioritize type annotations on the setter + if (writing && setterType) { + return instantiateTypeIfNeeded(setterType, symbol); + } + // Else defer to the getter type if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { - return jsDocType; + return instantiateTypeIfNeeded(jsDocType, symbol); } } - // First try to see if the user specified a return type on the get-accessor. - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - return getterReturnType; + // Try to see if the user specified a return type on the get-accessor. + var getterType = getAnnotatedAccessorType(getter); + if (getterType) { + return instantiateTypeIfNeeded(getterType, symbol); } - else { - // If the user didn't specify a return type, try to use the set-accessor's parameter type. - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - return setterParameterType; + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + if (setterType) { + return setterType; + } + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + var returnTypeFromBody = getReturnTypeFromBody(getter); + return instantiateTypeIfNeeded(returnTypeFromBody, symbol); + } + // Otherwise, fall back to 'any'. + if (setter) { + if (!isPrivateWithinAmbient(setter)) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); } - else { - // If there are no specified types, try to infer it from the body of the get accessor if it exists. - if (getter && getter.body) { - return getReturnTypeFromBody(getter); - } - // Otherwise, fall back to 'any'. - else { - if (setter) { - if (!isPrivateWithinAmbient(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 exist a getter as we are current checking either setter or getter in this function"); - if (!isPrivateWithinAmbient(getter)) { - errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } - } - return anyType; - } + return anyType; + } + else if (getter) { + ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } + return anyType; + } + return undefined; + function instantiateTypeIfNeeded(type, symbol) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + var links = getSymbolLinks(symbol); + return instantiateType(type, links.mapper); + } + return type; } } function getBaseTypeVariableOfClass(symbol) { @@ -51706,9 +53068,9 @@ var ts; if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration && (declaration.kind === 216 /* BinaryExpression */ || + else if (declaration && (declaration.kind === 217 /* BinaryExpression */ || ts.isAccessExpression(declaration) && - declaration.parent.kind === 216 /* BinaryExpression */)) { + declaration.parent.kind === 217 /* BinaryExpression */)) { return getWidenedTypeForAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { @@ -51742,14 +53104,16 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); + var exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(getDeclarationOfAliasSymbol(symbol), /*dontResolveAlias*/ true); // It only makes sense to get the type of a value symbol. If the result of resolving // the alias is not a value, then it has no type. To get the type associated with a // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 111551 /* Value */ - ? getTypeOfSymbol(targetSymbol) - : errorType; + links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) + : isDuplicatedCommonJSExport(symbol.declarations) ? autoType + : targetSymbol.flags & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) + : errorType; } return links.type; } @@ -51775,7 +53139,7 @@ var ts; return errorType; } // Check if variable has initializer that circularly references the variable itself - if (noImplicitAny && (declaration.kind !== 160 /* Parameter */ || declaration.initializer)) { + if (noImplicitAny && (declaration.kind !== 161 /* Parameter */ || declaration.initializer)) { error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); } // Circularities could also result from parameters in function expressions that end up @@ -51792,6 +53156,15 @@ var ts; } return links.type; } + function getSetAccessorTypeOfSymbol(symbol) { + if (symbol.flags & 98304 /* Accessor */) { + var type = getTypeOfSetAccessor(symbol); + if (type) { + return type; + } + } + return getTypeOfSymbol(symbol); + } function getTypeOfSymbol(symbol) { var checkFlags = ts.getCheckFlags(symbol); if (checkFlags & 65536 /* DeferredType */) { @@ -51874,66 +53247,72 @@ var ts; return undefined; } switch (node.kind) { - case 232 /* VariableStatement */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 164 /* MethodSignature */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 308 /* JSDocFunctionType */: - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 254 /* TypeAliasDeclaration */: - case 330 /* JSDocTemplateTag */: - case 331 /* JSDocTypedefTag */: - case 325 /* JSDocEnumTag */: - case 324 /* JSDocCallbackTag */: - case 190 /* MappedType */: - case 184 /* ConditionalType */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 165 /* MethodSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 309 /* JSDocFunctionType */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 255 /* TypeAliasDeclaration */: + case 334 /* JSDocTemplateTag */: + case 335 /* JSDocTypedefTag */: + case 329 /* JSDocEnumTag */: + case 328 /* JSDocCallbackTag */: + case 191 /* MappedType */: + case 185 /* ConditionalType */: { var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 190 /* MappedType */) { + if (node.kind === 191 /* MappedType */) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } - else if (node.kind === 184 /* ConditionalType */) { + else if (node.kind === 185 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } - else if (node.kind === 232 /* VariableStatement */ && !ts.isInJSFile(node)) { - break; - } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && - (node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */ || node.kind === 253 /* InterfaceDeclaration */ || isJSConstructor(node)) && + (node.kind === 253 /* ClassDeclaration */ || node.kind === 222 /* ClassExpression */ || node.kind === 254 /* InterfaceDeclaration */ || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; - case 326 /* JSDocParameterTag */: + } + case 330 /* JSDocParameterTag */: var paramSymbol = ts.getParameterSymbolFromJSDoc(node); if (paramSymbol) { node = paramSymbol.valueDeclaration; } break; + case 312 /* JSDocComment */: { + var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + return node.tags + ? appendTypeParameters(outerTypeParameters, ts.flatMap(node.tags, function (t) { return ts.isJSDocTemplateTag(t) ? t.typeParameters : undefined; })) + : outerTypeParameters; + } } } } // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 253 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 254 /* InterfaceDeclaration */); ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, // interface, or type alias. function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + if (!symbol.declarations) { + return; + } var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 253 /* InterfaceDeclaration */ || - node.kind === 252 /* ClassDeclaration */ || - node.kind === 221 /* ClassExpression */ || + if (node.kind === 254 /* InterfaceDeclaration */ || + node.kind === 253 /* ClassDeclaration */ || + node.kind === 222 /* ClassExpression */ || isJSConstructor(node) || ts.isTypeAlias(node)) { var declaration = node; @@ -52027,7 +53406,9 @@ var ts; ctorReturn = getReturnTypeOfSignature(ctorSig[0]); } } - ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + if (baseConstructorType.symbol.declarations) { + ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } } return type.resolvedBaseConstructorType = errorType; } @@ -52037,20 +53418,22 @@ var ts; } function getImplementsTypes(type) { var resolvedImplementsTypes = ts.emptyArray; - for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration); - if (!implementsTypeNodes) - continue; - for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) { - var node = implementsTypeNodes_1[_b]; - var implementsType = getTypeFromTypeNode(node); - if (implementsType !== errorType) { - if (resolvedImplementsTypes === ts.emptyArray) { - resolvedImplementsTypes = [implementsType]; - } - else { - resolvedImplementsTypes.push(implementsType); + if (type.symbol.declarations) { + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration); + if (!implementsTypeNodes) + continue; + for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) { + var node = implementsTypeNodes_1[_b]; + var implementsType = getTypeFromTypeNode(node); + if (implementsType !== errorType) { + if (resolvedImplementsTypes === ts.emptyArray) { + resolvedImplementsTypes = [implementsType]; + } + else { + resolvedImplementsTypes.push(implementsType); + } } } } @@ -52077,10 +53460,10 @@ var ts; else { ts.Debug.fail("type must be class or interface"); } - if (!popTypeResolution()) { + if (!popTypeResolution() && type.symbol.declarations) { for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 252 /* ClassDeclaration */ || declaration.kind === 253 /* InterfaceDeclaration */) { + if (declaration.kind === 253 /* ClassDeclaration */ || declaration.kind === 254 /* InterfaceDeclaration */) { reportCircularBaseType(declaration, type); } } @@ -52173,29 +53556,31 @@ var ts; } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; - for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 253 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { - for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { - var node = _c[_b]; - var baseType = getReducedType(getTypeFromTypeNode(node)); - if (baseType !== errorType) { - if (isValidBaseType(baseType)) { - if (type !== baseType && !hasBaseType(baseType, type)) { - if (type.resolvedBaseTypes === ts.emptyArray) { - type.resolvedBaseTypes = [baseType]; + if (type.symbol.declarations) { + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 254 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { + var node = _c[_b]; + var baseType = getReducedType(getTypeFromTypeNode(node)); + if (baseType !== errorType) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } } else { - type.resolvedBaseTypes.push(baseType); + reportCircularBaseType(declaration, type); } } else { - reportCircularBaseType(declaration, type); + error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } - else { - error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); - } } } } @@ -52209,9 +53594,12 @@ var ts; * and if none of the base interfaces have a "this" type. */ function isThislessInterface(symbol) { + if (!symbol.declarations) { + return true; + } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 253 /* InterfaceDeclaration */) { + if (declaration.kind === 254 /* InterfaceDeclaration */) { if (declaration.flags & 128 /* ContainsThis */) { return false; } @@ -52236,7 +53624,7 @@ var ts; var originalLinks = links; if (!links.declaredType) { var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */; - var merged = mergeJSSymbols(symbol, getAssignedClassSymbol(symbol.valueDeclaration)); + var merged = mergeJSSymbols(symbol, symbol.valueDeclaration && getAssignedClassSymbol(symbol.valueDeclaration)); if (merged) { // note:we overwrite links because we just cloned the symbol symbol = links = merged; @@ -52266,6 +53654,7 @@ var ts; return links.declaredType; } function getDeclaredTypeOfTypeAlias(symbol) { + var _a; var links = getSymbolLinks(symbol); if (!links.declaredType) { // Note that we use the links object as the target here because the symbol object is used as the unique @@ -52273,7 +53662,7 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return errorType; } - var declaration = ts.Debug.checkDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found"); + var declaration = ts.Debug.checkDefined((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias), "Type alias symbol with no valid declaration found"); var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; @@ -52299,7 +53688,7 @@ var ts; if (ts.isStringLiteralLike(expr)) { return true; } - else if (expr.kind === 216 /* BinaryExpression */) { + else if (expr.kind === 217 /* BinaryExpression */) { return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); } return false; @@ -52314,12 +53703,12 @@ var ts; case 8 /* NumericLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: return true; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return expr.operator === 40 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; case 78 /* Identifier */: return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return isStringConcatExpression(expr); default: return false; @@ -52331,16 +53720,18 @@ var ts; return links.enumKind; } var hasNonLiteralMember = false; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 255 /* EnumDeclaration */) { - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - if (member.initializer && ts.isStringLiteralLike(member.initializer)) { - return links.enumKind = 1 /* Literal */; - } - if (!isLiteralEnumMember(member)) { - hasNonLiteralMember = true; + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 256 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + if (member.initializer && ts.isStringLiteralLike(member.initializer)) { + return links.enumKind = 1 /* Literal */; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; + } } } } @@ -52358,15 +53749,17 @@ var ts; if (getEnumKind(symbol) === 1 /* Literal */) { enumCount++; var memberTypeList = []; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 255 /* EnumDeclaration */) { - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var value = getEnumMemberValue(member); - var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member))); - getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 256 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var value = getEnumMemberValue(member); + var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member))); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + } } } } @@ -52443,11 +53836,11 @@ var ts; case 113 /* VoidKeyword */: case 150 /* UndefinedKeyword */: case 141 /* NeverKeyword */: - case 191 /* LiteralType */: + case 192 /* LiteralType */: return true; - case 178 /* ArrayType */: + case 179 /* ArrayType */: return isThislessType(node.elementType); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; @@ -52473,7 +53866,7 @@ var ts; function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - return (node.kind === 166 /* Constructor */ || (!!returnType && isThislessType(returnType))) && + return (node.kind === 167 /* Constructor */ || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } @@ -52489,14 +53882,14 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return isThislessVariableLikeDeclaration(declaration); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return isThislessFunctionLikeDeclaration(declaration); } } @@ -52522,7 +53915,7 @@ var ts; } } function isStaticPrivateIdentifierProperty(s) { - return !!s.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(s.valueDeclaration) && ts.hasSyntacticModifier(s.valueDeclaration, 32 /* Static */); + return !!s.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(s.valueDeclaration) && ts.hasSyntacticModifier(s.valueDeclaration, 32 /* Static */); } function resolveDeclaredMembers(type) { if (!type.declaredProperties) { @@ -52574,10 +53967,10 @@ var ts; return !!name && isLateBindableName(name); } /** - * Indicates whether a declaration has a dynamic name that cannot be late-bound. + * Indicates whether a declaration has an early-bound name or a dynamic name that can be late-bound. */ - function hasNonBindableDynamicName(node) { - return ts.hasDynamicName(node) && !hasLateBindableName(node); + function hasBindableName(node) { + return !ts.hasDynamicName(node) || hasLateBindableName(node); } /** * Indicates whether a declaration name is a dynamic name that cannot be late-bound. @@ -52847,7 +54240,8 @@ var ts; sig.resolvedMinArgumentCount = undefined; sig.target = undefined; sig.mapper = undefined; - sig.unionSignatures = undefined; + sig.compositeSignatures = undefined; + sig.compositeKind = undefined; return sig; } function cloneSignature(sig) { @@ -52855,12 +54249,14 @@ var ts; /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 39 /* PropagatingFlags */); result.target = sig.target; result.mapper = sig.mapper; - result.unionSignatures = sig.unionSignatures; + result.compositeSignatures = sig.compositeSignatures; + result.compositeKind = sig.compositeKind; return result; } function createUnionSignature(signature, unionSignatures) { var result = cloneSignature(signature); - result.unionSignatures = unionSignatures; + result.compositeSignatures = unionSignatures; + result.compositeKind = 1048576 /* Union */; result.target = undefined; result.mapper = undefined; return result; @@ -53019,7 +54415,7 @@ var ts; if (signatures !== masterList) { var signature_1 = signatures[0]; ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); - results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters && !compareTypeParametersIdentical(signature_1.typeParameters, s.typeParameters); }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); }); + results = !!signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters && !compareTypeParametersIdentical(signature_1.typeParameters, s.typeParameters); }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); }); if (!results) { return "break"; } @@ -53036,9 +54432,12 @@ var ts; return result || ts.emptyArray; } function compareTypeParametersIdentical(sourceParams, targetParams) { - if (sourceParams.length !== targetParams.length) { + if (ts.length(sourceParams) !== ts.length(targetParams)) { return false; } + if (!sourceParams || !targetParams) { + return true; + } var mapper = createTypeMapper(targetParams, sourceParams); for (var i = 0; i < sourceParams.length; i++) { var source = sourceParams[i]; @@ -53120,9 +54519,10 @@ var ts; var result = createSignature(declaration, typeParams, thisParam, params, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 39 /* PropagatingFlags */); - result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); + result.compositeKind = 1048576 /* Union */; + result.compositeSignatures = ts.concatenate(left.compositeKind !== 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); if (paramMapper) { - result.mapper = left.mapper && left.unionSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; + result.mapper = left.compositeKind !== 2097152 /* Intersection */ && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; } return result; } @@ -53255,6 +54655,7 @@ var ts; // Combinations of function, class, enum and module var members = emptySymbols; var stringIndexInfo = void 0; + var numberIndexInfo = void 0; if (symbol.exports) { members = getExportsOfSymbol(symbol); if (symbol === globalThisSymbol) { @@ -53267,20 +54668,31 @@ var ts; members = varsOnly_1; } } + var baseConstructorIndexInfo = void 0; setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) { - members = ts.createSymbolTable(getNamedMembers(members)); + members = ts.createSymbolTable(getNamedOrIndexSignatureMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } else if (baseConstructorType === anyType) { - stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + baseConstructorIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + } + } + var indexSymbol = getIndexSymbolFromSymbolTable(members); + if (indexSymbol) { + stringIndexInfo = getIndexInfoOfIndexSymbol(indexSymbol, 0 /* String */); + numberIndexInfo = getIndexInfoOfIndexSymbol(indexSymbol, 1 /* Number */); + } + else { + stringIndexInfo = baseConstructorIndexInfo; + if (symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ || + ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); }))) { + numberIndexInfo = enumNumberIndexInfo; } } - var numberIndexInfo = symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ || - ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); })) ? enumNumberIndexInfo : undefined; setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); // We resolve the members before computing the signatures because a signature may use // typeof with a qualified name expression that circularly references the type we are @@ -53305,6 +54717,18 @@ var ts; } } } + function replaceIndexedAccess(instantiable, type, replacement) { + // map type.indexType to 0 + // map type.objectType to `[TReplacement]` + // thus making the indexed access `[TReplacement][0]` or `TReplacement` + return instantiateType(instantiable, createTypeMapper([type.indexType, type.objectType], [getLiteralType(0), createTupleType([replacement])])); + } + function getIndexInfoOfIndexSymbol(indexSymbol, indexKind) { + var declaration = getIndexDeclarationOfIndexSymbol(indexSymbol, indexKind); + if (!declaration) + return undefined; + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasEffectiveModifier(declaration, 64 /* Readonly */), declaration); + } function resolveReverseMappedTypeMembers(type) { var indexInfo = getIndexInfoOfType(type.source, 0 /* String */); var modifiers = getMappedTypeModifiers(type.mappedType); @@ -53319,8 +54743,21 @@ var ts; inferredProp.declarations = prop.declarations; inferredProp.nameType = getSymbolLinks(prop).nameType; inferredProp.propertyType = getTypeOfSymbol(prop); - inferredProp.mappedType = type.mappedType; - inferredProp.constraintType = type.constraintType; + if (type.constraintType.type.flags & 8388608 /* IndexedAccess */ + && type.constraintType.type.objectType.flags & 262144 /* TypeParameter */ + && type.constraintType.type.indexType.flags & 262144 /* TypeParameter */) { + // A reverse mapping of `{[K in keyof T[K_1]]: T[K_1]}` is the same as that of `{[K in keyof T]: T}`, since all we care about is + // inferring to the "type parameter" (or indexed access) shared by the constraint and template. So, to reduce the number of + // type identities produced, we simplify such indexed access occurences + var newTypeParam = type.constraintType.type.objectType; + var newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type, newTypeParam); + inferredProp.mappedType = newMappedType; + inferredProp.constraintType = getIndexType(newTypeParam); + } + else { + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + } members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -53482,7 +54919,7 @@ var ts; } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 - return constraintDeclaration.kind === 188 /* TypeOperator */ && + return constraintDeclaration.kind === 189 /* TypeOperator */ && constraintDeclaration.operator === 138 /* KeyOfKeyword */; } function getModifiersTypeFromMappedType(type) { @@ -53534,7 +54971,7 @@ var ts; else if (type.objectFlags & 3 /* ClassOrInterface */) { resolveClassOrInterfaceMembers(type); } - else if (type.objectFlags & 2048 /* ReverseMapped */) { + else if (type.objectFlags & 1024 /* ReverseMapped */) { resolveReverseMappedTypeMembers(type); } else if (type.objectFlags & 16 /* Anonymous */) { @@ -53818,12 +55255,22 @@ var ts; if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; + var different = false; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type_3 = types_8[_i]; var baseType = getBaseConstraint(type_3); if (baseType) { + if (baseType !== type_3) { + different = true; + } baseTypes.push(baseType); } + else { + different = true; + } + } + if (!different) { + return t; } return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : @@ -53943,6 +55390,7 @@ var ts; return getReducedType(getApparentType(getReducedType(type))); } function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) { + var _a, _b; var singleProp; var propSet; var indexTypes; @@ -53951,8 +55399,9 @@ var ts; var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var current = _a[_i]; + var mergedInstantiations = false; + for (var _i = 0, _c = containingType.types; _i < _c.length; _i++) { + var current = _c[_i]; var type = getApparentType(current); if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); @@ -53968,13 +55417,25 @@ var ts; singleProp = prop; } else if (prop !== singleProp) { - if (!propSet) { - propSet = new ts.Map(); - propSet.set(getSymbolId(singleProp), singleProp); + var isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp); + // If the symbols are instances of one another with identical types - consider the symbols + // equivalent and just use the first one, which thus allows us to avoid eliding private + // members when intersecting a (this-)instantiations of a class with it's raw base or another instance + if (isInstantiation && compareProperties(singleProp, prop, function (a, b) { return a === b ? -1 /* True */ : 0 /* False */; }) === -1 /* True */) { + // If we merged instantiations of a generic type, we replicate the symbol parent resetting behavior we used + // to do when we recorded multiple distinct symbols so that we still get, eg, `Array.length` printed + // back and not `Array.length` when we're looking at a `.length` access on a `string[] | number[]` + mergedInstantiations = !!singleProp.parent && !!ts.length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent)); } - var id = getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + else { + if (!propSet) { + propSet = new ts.Map(); + propSet.set(getSymbolId(singleProp), singleProp); + } + var id = getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | @@ -53992,7 +55453,7 @@ var ts; checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0); indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } - else if (isObjectLiteralType(type)) { + else if (isObjectLiteralType(type) && !(ts.getObjectFlags(type) & 4194304 /* ContainsSpread */)) { checkFlags |= 32 /* WritePartial */; indexTypes = ts.append(indexTypes, undefinedType); } @@ -54008,7 +55469,19 @@ var ts; return undefined; } if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { - return singleProp; + if (mergedInstantiations) { + // No symbol from a union/intersection should have a `.parent` set (since unions/intersections don't act as symbol parents) + // Unless that parent is "reconstituted" from the "first value declaration" on the symbol (which is likely different than its instantiated parent!) + // They also have a `.containingType` set, which affects some services endpoints behavior, like `getRootSymbol` + var clone_1 = createSymbolWithType(singleProp, singleProp.type); + clone_1.parent = (_b = (_a = singleProp.valueDeclaration) === null || _a === void 0 ? void 0 : _a.symbol) === null || _b === void 0 ? void 0 : _b.parent; + clone_1.containingType = containingType; + clone_1.mapper = singleProp.mapper; + return clone_1; + } + else { + return singleProp; + } } var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; @@ -54017,8 +55490,8 @@ var ts; var propTypes = []; var firstValueDeclaration; var hasNonUniformValueDeclaration = false; - for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { - var prop = props_1[_b]; + for (var _d = 0, props_1 = props; _d < props_1.length; _d++) { + var prop = props_1[_d]; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } @@ -54095,15 +55568,15 @@ var ts; * no constituent property has type 'never', but the intersection of the constituent property types is 'never'. */ function getReducedType(type) { - if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) { + if (type.flags & 1048576 /* Union */ && type.objectFlags & 67108864 /* ContainsIntersections */) { return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); } else if (type.flags & 2097152 /* Intersection */) { - if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { - type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | - (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0); + if (!(type.objectFlags & 67108864 /* IsNeverIntersectionComputed */)) { + type.objectFlags |= 67108864 /* IsNeverIntersectionComputed */ | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 134217728 /* IsNeverIntersection */ : 0); } - return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; + return type.objectFlags & 134217728 /* IsNeverIntersection */ ? neverType : type; } return type; } @@ -54133,7 +55606,7 @@ var ts; return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */); } function elaborateNeverIntersection(errorInfo, type) { - if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) { + if (type.flags & 2097152 /* Intersection */ && ts.getObjectFlags(type) & 134217728 /* IsNeverIntersection */) { var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); if (neverProp) { return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(neverProp)); @@ -54220,7 +55693,8 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var prop = _a[_i]; if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { - propTypes.push(getTypeOfSymbol(prop)); + var propType = getTypeOfSymbol(prop); + propTypes.push(prop.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType); } } if (kind === 0 /* String */) { @@ -54254,10 +55728,10 @@ var ts; function isJSDocOptionalParameter(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 === 307 /* JSDocOptionalType */ + node.type && node.type.kind === 308 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 307 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 308 /* JSDocOptionalType */; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -54289,12 +55763,15 @@ var ts; } return false; } + function isOptionalPropertyDeclaration(node) { + return ts.isPropertyDeclaration(node) && node.questionToken; + } function isOptionalJSDocPropertyLikeTag(node) { if (!ts.isJSDocPropertyLikeTag(node)) { return false; } var isBracketed = node.isBracketed, typeExpression = node.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 307 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 308 /* JSDocOptionalType */; } function createTypePredicate(kind, parameterName, parameterIndex, type) { return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; @@ -54376,7 +55853,7 @@ var ts; else { parameters.push(paramSymbol); } - if (type && type.kind === 191 /* LiteralType */) { + if (type && type.kind === 192 /* LiteralType */) { flags |= 2 /* HasLiteralTypes */; } // Record a new minimum argument count if this is not an optional parameter @@ -54389,16 +55866,16 @@ var ts; } } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 167 /* GetAccessor */ || declaration.kind === 168 /* SetAccessor */) && - !hasNonBindableDynamicName(declaration) && + if ((declaration.kind === 168 /* GetAccessor */ || declaration.kind === 169 /* SetAccessor */) && + hasBindableName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; + var otherKind = declaration.kind === 168 /* GetAccessor */ ? 169 /* SetAccessor */ : 168 /* GetAccessor */; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 166 /* Constructor */ ? + var classType = declaration.kind === 167 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); @@ -54443,8 +55920,7 @@ var ts; if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node))) return undefined; var typeTag = ts.getJSDocTypeTag(node); - var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); - return signature && getErasedSignature(signature); + return (typeTag === null || typeTag === void 0 ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); } function getReturnTypeOfTypeTag(node) { var signature = getSignatureOfTypeTag(node); @@ -54467,14 +55943,14 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node.escapedText === argumentsSymbol.escapedName && getResolvedSymbol(node) === argumentsSymbol; - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - return node.name.kind === 158 /* ComputedPropertyName */ + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return node.name.kind === 159 /* ComputedPropertyName */ && traverse(node.name); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return traverse(node.expression); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); @@ -54482,7 +55958,7 @@ var ts; } } function getSignaturesOfSymbol(symbol) { - if (!symbol) + if (!symbol || !symbol.declarations) return ts.emptyArray; var result = []; for (var i = 0; i < symbol.declarations.length; i++) { @@ -54523,8 +55999,8 @@ var ts; var targetTypePredicate = getTypePredicateOfSignature(signature.target); signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; } - else if (signature.unionSignatures) { - signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + else if (signature.compositeSignatures) { + signature.resolvedTypePredicate = getUnionOrIntersectionTypePredicate(signature.compositeSignatures, signature.compositeKind) || noTypePredicate; } else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); @@ -54546,17 +56022,20 @@ var ts; function createTypePredicateFromTypePredicateNode(node, signature) { var parameterName = node.parameterName; var type = node.type && getTypeFromTypeNode(node.type); - return parameterName.kind === 187 /* ThisType */ ? + return parameterName.kind === 188 /* ThisType */ ? createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) : createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type); } + function getUnionOrIntersectionType(types, kind, unionReduction) { + return kind !== 2097152 /* Intersection */ ? getUnionType(types, unionReduction) : getIntersectionType(types); + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { return errorType; } var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : - signature.unionSignatures ? instantiateType(getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */), signature.mapper) : + signature.compositeSignatures ? instantiateType(getUnionOrIntersectionType(ts.map(signature.compositeSignatures, getReturnTypeOfSignature), signature.compositeKind, 2 /* Subtype */), signature.mapper) : getReturnTypeFromAnnotation(signature.declaration) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (signature.flags & 8 /* IsInnerCallChain */) { @@ -54589,7 +56068,7 @@ var ts; return signature.resolvedReturnType; } function getReturnTypeFromAnnotation(declaration) { - if (declaration.kind === 166 /* Constructor */) { + if (declaration.kind === 167 /* Constructor */) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); } if (ts.isJSDocConstructSignature(declaration)) { @@ -54599,12 +56078,12 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 167 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + if (declaration.kind === 168 /* GetAccessor */ && hasBindableName(declaration)) { var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 168 /* SetAccessor */); + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 169 /* SetAccessor */); var setterType = getAnnotatedAccessorType(setter); if (setterType) { return setterType; @@ -54681,9 +56160,20 @@ var ts; function getBaseSignature(signature) { var typeParameters = signature.typeParameters; if (typeParameters) { - var typeEraser_1 = createTypeEraser(typeParameters); - var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || unknownType; }); - return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); + if (signature.baseSignatureCache) { + return signature.baseSignatureCache; + } + var typeEraser = createTypeEraser(typeParameters); + var baseConstraintMapper_1 = createTypeMapper(typeParameters, ts.map(typeParameters, function (tp) { return getConstraintOfTypeParameter(tp) || unknownType; })); + var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(tp, baseConstraintMapper_1) || unknownType; }); + // Run N type params thru the immediate constraint mapper up to N times + // This way any noncircular interdependent type parameters are definitely resolved to their external dependencies + for (var i = 0; i < typeParameters.length - 1; i++) { + baseConstraints = instantiateTypes(baseConstraints, baseConstraintMapper_1); + } + // and then apply a type eraser to remove any remaining circularly dependent type parameters + baseConstraints = instantiateTypes(baseConstraints, typeEraser); + return signature.baseSignatureCache = instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); } return signature; } @@ -54694,7 +56184,7 @@ var ts; // will result in a different declaration kind. if (!signature.isolatedSignatureType) { var kind = signature.declaration ? signature.declaration.kind : 0 /* Unknown */; - var isConstructor = kind === 166 /* Constructor */ || kind === 170 /* ConstructSignature */ || kind === 175 /* ConstructorType */; + var isConstructor = kind === 167 /* Constructor */ || kind === 171 /* ConstructSignature */ || kind === 176 /* ConstructorType */; var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -54705,12 +56195,22 @@ var ts; return signature.isolatedSignatureType; } function getIndexSymbol(symbol) { - return symbol.members.get("__index" /* Index */); + return symbol.members ? getIndexSymbolFromSymbolTable(symbol.members) : undefined; + } + function getIndexSymbolFromSymbolTable(symbolTable) { + return symbolTable.get("__index" /* Index */); } function getIndexDeclarationOfSymbol(symbol, kind) { + var indexSymbol = symbol && getIndexSymbol(symbol); + return indexSymbol && getIndexDeclarationOfIndexSymbol(indexSymbol, kind); + } + function getIndexDeclarationOfSymbolTable(symbolTable, kind) { + var indexSymbol = symbolTable && getIndexSymbolFromSymbolTable(symbolTable); + return indexSymbol && getIndexDeclarationOfIndexSymbol(indexSymbol, kind); + } + function getIndexDeclarationOfIndexSymbol(indexSymbol, kind) { var syntaxKind = kind === 1 /* Number */ ? 144 /* NumberKeyword */ : 147 /* StringKeyword */; - var indexSymbol = getIndexSymbol(symbol); - if (indexSymbol) { + if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; var node = ts.cast(decl, ts.isIndexSignatureDeclaration); @@ -54738,17 +56238,18 @@ var ts; return ts.mapDefined(ts.filter(type.symbol && type.symbol.declarations, ts.isTypeParameterDeclaration), ts.getEffectiveConstraintOfTypeParameter)[0]; } function getInferredTypeParameterConstraint(typeParameter) { + var _a; var inferences; - if (typeParameter.symbol) { - for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.parent.kind === 185 /* InferType */) { + if ((_a = typeParameter.symbol) === null || _a === void 0 ? void 0 : _a.declarations) { + for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (declaration.parent.kind === 186 /* InferType */) { // When an 'infer T' declaration is immediately contained in a type reference node // (such as 'Foo'), T's constraint is inferred from the constraint of the // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are // present, we form an intersection of the inferred constraint types. - var _b = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _c = _b[0], childTypeParameter = _c === void 0 ? declaration.parent : _c, grandParent = _b[1]; - if (grandParent.kind === 173 /* TypeReference */) { + var _c = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _d = _c[0], childTypeParameter = _d === void 0 ? declaration.parent : _d, grandParent = _c[1]; + if (grandParent.kind === 174 /* TypeReference */) { var typeReference = grandParent; var typeParameters = getTypeParametersForTypeReference(typeReference); if (typeParameters) { @@ -54773,21 +56274,32 @@ var ts; } // When an 'infer T' declaration is immediately contained in a rest parameter declaration, a rest type // or a named rest tuple element, we infer an 'unknown[]' constraint. - else if (grandParent.kind === 160 /* Parameter */ && grandParent.dotDotDotToken || - grandParent.kind === 181 /* RestType */ || - grandParent.kind === 192 /* NamedTupleMember */ && grandParent.dotDotDotToken) { + else if (grandParent.kind === 161 /* Parameter */ && grandParent.dotDotDotToken || + grandParent.kind === 182 /* RestType */ || + grandParent.kind === 193 /* NamedTupleMember */ && grandParent.dotDotDotToken) { inferences = ts.append(inferences, createArrayType(unknownType)); } // When an 'infer T' declaration is immediately contained in a string template type, we infer a 'string' // constraint. - else if (grandParent.kind === 194 /* TemplateLiteralTypeSpan */) { + else if (grandParent.kind === 195 /* TemplateLiteralTypeSpan */) { inferences = ts.append(inferences, stringType); } // When an 'infer T' declaration is in the constraint position of a mapped type, we infer a 'keyof any' // constraint. - else if (grandParent.kind === 159 /* TypeParameter */ && grandParent.parent.kind === 190 /* MappedType */) { + else if (grandParent.kind === 160 /* TypeParameter */ && grandParent.parent.kind === 191 /* MappedType */) { inferences = ts.append(inferences, keyofConstraintType); } + // When an 'infer T' declaration is the template of a mapped type, and that mapped type is the extends + // clause of a conditional whose check type is also a mapped type, give it a constraint equal to the template + // of the check type's mapped type + else if (grandParent.kind === 191 /* MappedType */ && grandParent.type && + ts.skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 185 /* ConditionalType */ && + grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 191 /* MappedType */ && + grandParent.parent.checkType.type) { + var checkMappedType_1 = grandParent.parent.checkType; + var nodeType = getTypeFromTypeNode(checkMappedType_1.type); + inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); + } } } } @@ -54810,7 +56322,7 @@ var ts; if (type.flags & 1 /* Any */ && type !== errorType) { // Allow errorType to propegate to keep downstream errors suppressed // use keyofConstraintType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was), // use unknown otherwise - type = constraintDeclaration.parent.parent.kind === 190 /* MappedType */ ? keyofConstraintType : unknownType; + type = constraintDeclaration.parent.parent.kind === 191 /* MappedType */ ? keyofConstraintType : unknownType; } typeParameter.constraint = type; } @@ -54819,7 +56331,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - var tp = ts.getDeclarationOfKind(typeParameter.symbol, 159 /* TypeParameter */); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 160 /* TypeParameter */); var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; return host && getSymbolOfNode(host); } @@ -54846,6 +56358,9 @@ var ts; } return result; } + function getAliasId(aliasSymbol, aliasTypeArguments) { + return aliasSymbol ? "@" + getSymbolId(aliasSymbol) + (aliasTypeArguments ? ":" + getTypeListId(aliasTypeArguments) : "") : ""; + } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type // of an object literal or the anyFunctionType. This is because there are operations in the type checker @@ -54858,7 +56373,7 @@ var ts; result |= ts.getObjectFlags(type); } } - return result & 3670016 /* PropagatingFlags */; + return result & 917504 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -54880,15 +56395,18 @@ var ts; type.resolvedTypeArguments = source.resolvedTypeArguments; return type; } - function createDeferredTypeReference(target, node, mapper) { - var aliasSymbol = getAliasSymbolForTypeNode(node); - var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + function createDeferredTypeReference(target, node, mapper, aliasSymbol, aliasTypeArguments) { + if (!aliasSymbol) { + aliasSymbol = getAliasSymbolForTypeNode(node); + var localAliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + aliasTypeArguments = mapper ? instantiateTypes(localAliasTypeArguments, mapper) : localAliasTypeArguments; + } var type = createObjectType(4 /* Reference */, target.symbol); type.target = target; type.node = node; type.mapper = mapper; type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = mapper ? instantiateTypes(aliasTypeArguments, mapper) : aliasTypeArguments; + type.aliasTypeArguments = aliasTypeArguments; return type; } function getTypeArguments(type) { @@ -54899,8 +56417,8 @@ var ts; } var node = type.node; var typeArguments = !node ? ts.emptyArray : - node.kind === 173 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : - node.kind === 178 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : + node.kind === 174 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : + node.kind === 179 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); if (popTypeResolution()) { type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; @@ -54942,7 +56460,7 @@ var ts; return errorType; } } - if (node.kind === 173 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) { + if (node.kind === 174 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) { return createDeferredTypeReference(type, node, /*mapper*/ undefined); } // In a type reference, the outer type parameters of the referenced class or interface are automatically @@ -54953,17 +56471,17 @@ var ts; } return checkNoTypeArguments(node, symbol) ? type : errorType; } - function getTypeAliasInstantiation(symbol, typeArguments) { + function getTypeAliasInstantiation(symbol, typeArguments, aliasSymbol, aliasTypeArguments) { var type = getDeclaredTypeOfSymbol(symbol); if (type === intrinsicMarkerType && intrinsicTypeKinds.has(symbol.escapedName) && typeArguments && typeArguments.length === 1) { return getStringMappingType(symbol, typeArguments[0]); } var links = getSymbolLinks(symbol); var typeParameters = links.typeParameters; - var id = getTypeListId(typeArguments); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments)); } return instantiation; } @@ -54984,15 +56502,26 @@ var ts; ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return errorType; } - return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node)); + // We refrain from associating a local type alias with an instantiation of a top-level type alias + // because the local alias may end up being referenced in an inferred return type where it is not + // accessible--which in turn may lead to a large structural expansion of the type when generating + // a .d.ts file. See #43622 for an example. + var aliasSymbol = getAliasSymbolForTypeNode(node); + var newAliasSymbol = aliasSymbol && (isLocalTypeAlias(symbol) || !isLocalTypeAlias(aliasSymbol)) ? aliasSymbol : undefined; + return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), newAliasSymbol, getTypeArgumentsForAliasSymbol(newAliasSymbol)); } return checkNoTypeArguments(node, symbol) ? type : errorType; } + function isLocalTypeAlias(symbol) { + var _a; + var declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias); + return !!(declaration && ts.getContainingFunction(declaration)); + } function getTypeReferenceName(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return node.typeName; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. var expr = node.expression; @@ -55048,7 +56577,7 @@ var ts; var valueType = getTypeOfSymbol(symbol); var typeType = valueType; if (symbol.valueDeclaration) { - var isImportTypeWithQualifier = node.kind === 195 /* ImportType */ && node.qualifier; + var isImportTypeWithQualifier = node.kind === 196 /* ImportType */ && node.qualifier; // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL} if (valueType.symbol && valueType.symbol !== symbol && isImportTypeWithQualifier) { typeType = getTypeReferenceType(node, valueType.symbol); @@ -55074,7 +56603,7 @@ var ts; return result; } function isUnaryTupleTypeNode(node) { - return node.kind === 179 /* TupleType */ && node.elements.length === 1; + return node.kind === 180 /* TupleType */ && node.elements.length === 1; } function getImpliedConstraint(type, checkNode, extendsNode) { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elements[0], extendsNode.elements[0]) : @@ -55083,9 +56612,17 @@ var ts; } function getConditionalFlowTypeOfType(type, node) { var constraints; - while (node && !ts.isStatement(node) && node.kind !== 311 /* JSDocComment */) { + var covariant = true; + while (node && !ts.isStatement(node) && node.kind !== 312 /* JSDocComment */) { var parent = node.parent; - if (parent.kind === 184 /* ConditionalType */ && node === parent.trueType) { + // only consider variance flipped by parameter locations - `keyof` types would usually be considered variance inverting, but + // often get used in indexed accesses where they behave sortof invariantly, but our checking is lax + if (parent.kind === 161 /* Parameter */) { + covariant = !covariant; + } + // Always substitute on type parameters, regardless of variance, since even + // in contravariant positions, they may rely on substituted constraints to be valid + if ((covariant || type.flags & 8650752 /* TypeVariable */) && parent.kind === 185 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -55096,7 +56633,7 @@ var ts; return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type; } function isJSDocTypeReference(node) { - return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 173 /* TypeReference */ || node.kind === 195 /* ImportType */); + return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 174 /* TypeReference */ || node.kind === 196 /* ImportType */); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -55206,13 +56743,15 @@ var ts; function getTypeOfGlobalSymbol(symbol, arity) { function getTypeDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { - var declaration = declarations_3[_i]; - switch (declaration.kind) { - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - return declaration; + if (declarations) { + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; + switch (declaration.kind) { + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + return declaration; + } } } } @@ -55256,6 +56795,9 @@ var ts; function getGlobalESSymbolConstructorSymbol(reportErrors) { return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); } + function getGlobalESSymbolConstructorTypeSymbol(reportErrors) { + return deferredGlobalESSymbolConstructorTypeSymbol || (deferredGlobalESSymbolConstructorTypeSymbol = getGlobalTypeSymbol("SymbolConstructor", reportErrors)); + } function getGlobalESSymbolType(reportErrors) { return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType; } @@ -55332,11 +56874,11 @@ var ts; } function getTupleElementFlags(node) { switch (node.kind) { - case 180 /* OptionalType */: + case 181 /* OptionalType */: return 2 /* Optional */; - case 181 /* RestType */: + case 182 /* RestType */: return getRestTypeElementFlags(node); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return node.questionToken ? 2 /* Optional */ : node.dotDotDotToken ? getRestTypeElementFlags(node) : 1 /* Required */; @@ -55354,14 +56896,14 @@ var ts; return readonly ? globalReadonlyArrayType : globalArrayType; } var elementFlags = ts.map(node.elements, getTupleElementFlags); - var missingName = ts.some(node.elements, function (e) { return e.kind !== 192 /* NamedTupleMember */; }); + var missingName = ts.some(node.elements, function (e) { return e.kind !== 193 /* NamedTupleMember */; }); return getTupleTargetType(elementFlags, readonly, /*associatedNames*/ missingName ? undefined : node.elements); } // Return true if the given type reference node is directly aliased or if it needs to be deferred // because it is possibly contained in a circular chain of eagerly resolved types. function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) { - return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 178 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) : - node.kind === 179 /* TupleType */ ? ts.some(node.elements, mayResolveTypeAlias) : + return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 179 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) : + node.kind === 180 /* TupleType */ ? ts.some(node.elements, mayResolveTypeAlias) : hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias)); } // Return true when the given node is transitively contained in type constructs that eagerly @@ -55370,18 +56912,18 @@ var ts; function isResolvedByTypeAlias(node) { var parent = node.parent; switch (parent.kind) { - case 186 /* ParenthesizedType */: - case 192 /* NamedTupleMember */: - case 173 /* TypeReference */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 189 /* IndexedAccessType */: - case 184 /* ConditionalType */: - case 188 /* TypeOperator */: - case 178 /* ArrayType */: - case 179 /* TupleType */: + case 187 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: + case 174 /* TypeReference */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 190 /* IndexedAccessType */: + case 185 /* ConditionalType */: + case 189 /* TypeOperator */: + case 179 /* ArrayType */: + case 180 /* TupleType */: return isResolvedByTypeAlias(parent); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return true; } return false; @@ -55390,28 +56932,28 @@ var ts; // of a type alias. function mayResolveTypeAlias(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node.typeName, 788968 /* Type */).flags & 524288 /* TypeAlias */); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return true; - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return node.operator !== 151 /* UniqueKeyword */ && mayResolveTypeAlias(node.type); - case 186 /* ParenthesizedType */: - case 180 /* OptionalType */: - case 192 /* NamedTupleMember */: - case 307 /* JSDocOptionalType */: - case 305 /* JSDocNullableType */: - case 306 /* JSDocNonNullableType */: - case 301 /* JSDocTypeExpression */: + case 187 /* ParenthesizedType */: + case 181 /* OptionalType */: + case 193 /* NamedTupleMember */: + case 308 /* JSDocOptionalType */: + case 306 /* JSDocNullableType */: + case 307 /* JSDocNonNullableType */: + case 302 /* JSDocTypeExpression */: return mayResolveTypeAlias(node.type); - case 181 /* RestType */: - return node.type.kind !== 178 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType); - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 182 /* RestType */: + return node.type.kind !== 179 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType); + case 183 /* UnionType */: + case 184 /* IntersectionType */: return ts.some(node.types, mayResolveTypeAlias); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) || mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType); } @@ -55424,12 +56966,12 @@ var ts; if (target === emptyGenericType) { links.resolvedType = emptyObjectType; } - else if (!(node.kind === 179 /* TupleType */ && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8 /* Variadic */); })) && isDeferredTypeReferenceNode(node)) { - links.resolvedType = node.kind === 179 /* TupleType */ && node.elements.length === 0 ? target : + else if (!(node.kind === 180 /* TupleType */ && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8 /* Variadic */); })) && isDeferredTypeReferenceNode(node)) { + links.resolvedType = node.kind === 180 /* TupleType */ && node.elements.length === 0 ? target : createDeferredTypeReference(target, node, /*mapper*/ undefined); } else { - var elementTypes = node.kind === 178 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); + var elementTypes = node.kind === 179 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); links.resolvedType = createNormalizedTypeReference(target, elementTypes); } } @@ -55561,8 +57103,15 @@ var ts; addElement(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]); } else if (isTupleType(type)) { + var elements = getTypeArguments(type); + if (elements.length + expandedTypes.length >= 10000) { + error(currentNode, ts.isPartOfTypeNode(currentNode) + ? ts.Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent + : ts.Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent); + return { value: errorType }; + } // Spread variadic elements with tuple types into the resulting tuple. - ts.forEach(getTypeArguments(type), function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); + ts.forEach(elements, function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); } else { // Treat everything else as an array type and create a rest element. @@ -55575,7 +57124,9 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - _loop_13(i); + var state_4 = _loop_13(i); + if (typeof state_4 === "object") + return state_4.value; } // Turn optional elements preceding the last required element into required elements for (var i = 0; i < lastRequiredIndex; i++) { @@ -55664,7 +57215,7 @@ var ts; if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { - if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) + if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */)) includes |= 4194304 /* IncludesNonWideningType */; } else { @@ -55686,67 +57237,76 @@ var ts; } return includes; } - function isSetOfLiteralsFromSameEnum(types) { - var first = types[0]; - if (first.flags & 1024 /* EnumLiteral */) { - var firstEnum = getParentOfSymbol(first.symbol); - for (var i = 1; i < types.length; i++) { - var other = types[i]; - if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { - return false; - } - } - return true; + function removeSubtypes(types, hasObjectTypes) { + var id = getTypeListId(types); + var match = subtypeReductionCache.get(id); + if (match) { + return match; } - return false; - } - function removeSubtypes(types, primitivesOnly) { + // We assume that redundant primitive types have already been removed from the types array and that there + // are no any and unknown types in the array. Thus, the only possible supertypes for primitive types are empty + // object types, and if none of those are present we can exclude primitive types from the subtype check. + var hasEmptyObject = hasObjectTypes && ts.some(types, function (t) { return !!(t.flags & 524288 /* Object */) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t)); }); var len = types.length; - if (len === 0 || isSetOfLiteralsFromSameEnum(types)) { - return true; - } var i = len; var count = 0; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var target = types_11[_i]; - if (source !== target) { - if (count === 100000) { - // After 100000 subtype checks we estimate the remaining amount of work by assuming the - // same ratio of checks per element. If the estimated number of remaining type checks is - // greater than an upper limit we deem the union type too complex to represent. The - // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example - // caps union types at 5000 unique literal types and 1000 unique object types. - var estimatedCount = (count / (len - i)) * len; - if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); - error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); - return false; + if (hasEmptyObject || source.flags & 469499904 /* StructuredOrInstantiable */) { + // Find the first property with a unit type, if any. When constituents have a property by the same name + // but of a different unit type, we can quickly disqualify them from subtype checks. This helps subtype + // reduction of large discriminated union types. + var keyProperty = source.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */) ? + ts.find(getPropertiesOfType(source), function (p) { return isUnitType(getTypeOfSymbol(p)); }) : + undefined; + var keyPropertyType = keyProperty && getRegularTypeOfLiteralType(getTypeOfSymbol(keyProperty)); + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var target = types_11[_i]; + if (source !== target) { + if (count === 100000) { + // After 100000 subtype checks we estimate the remaining amount of work by assuming the + // same ratio of checks per element. If the estimated number of remaining type checks is + // greater than 1M we deem the union type too complex to represent. This for example + // caps union types at 1000 unique object types. + var estimatedCount = (count / (len - i)) * len; + if (estimatedCount > 1000000) { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); + error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); + return undefined; + } + } + count++; + if (keyProperty && target.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */)) { + var t = getTypeOfPropertyOfType(target, keyProperty.escapedName); + if (t && isUnitType(t) && getRegularTypeOfLiteralType(t) !== keyPropertyType) { + continue; + } + } + if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { + ts.orderedRemoveItemAt(types, i); + break; } - } - count++; - if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || - !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || - isTypeDerivedFrom(source, target))) { - ts.orderedRemoveItemAt(types, i); - break; } } } } - return true; + subtypeReductionCache.set(id, types); + return types; } - function removeRedundantLiteralTypes(types, includes) { + function removeRedundantLiteralTypes(types, includes, reduceVoidUndefined) { var i = types.length; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 134217856 /* StringLikeLiteral */ && includes & 4 /* String */ || - t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || - t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || - t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + var flags = t.flags; + var remove = flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + reduceVoidUndefined && flags & 32768 /* Undefined */ && includes & 16384 /* Void */ || isFreshLiteralType(t) && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); @@ -55778,7 +57338,7 @@ var ts; if (t.flags & 1048576 /* Union */) { var origin = t.origin; if (t.aliasSymbol || origin && !(origin.flags & 1048576 /* Union */)) { - namedUnions.push(t); + ts.pushIfUnique(namedUnions, t); } else if (origin && origin.flags & 1048576 /* Union */) { addNamedUnions(namedUnions, origin.types); @@ -55812,20 +57372,17 @@ var ts; if (includes & 3 /* AnyOrUnknown */) { return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; } - switch (unionReduction) { - case 1 /* Literal */: - if (includes & (134220672 /* FreshableLiteral */ | 8192 /* UniqueESSymbol */)) { - removeRedundantLiteralTypes(typeSet, includes); - } - if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { - removeStringLiteralsMatchedByTemplateLiterals(typeSet); - } - break; - case 2 /* Subtype */: - if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) { - return errorType; - } - break; + if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */) || includes & 16384 /* Void */ && includes & 32768 /* Undefined */) { + removeRedundantLiteralTypes(typeSet, includes, !!(unionReduction & 2 /* Subtype */)); + } + if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { + removeStringLiteralsMatchedByTemplateLiterals(typeSet); + } + if (unionReduction === 2 /* Subtype */) { + typeSet = removeSubtypes(typeSet, !!(includes & 524288 /* Object */)); + if (!typeSet) { + return errorType; + } } if (typeSet.length === 0) { return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType : @@ -55860,18 +57417,23 @@ var ts; origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes); } } - var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) | - (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0); + var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | + (includes & 2097152 /* Intersection */ ? 67108864 /* ContainsIntersections */ : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } - function getUnionTypePredicate(signatures) { + function getUnionOrIntersectionTypePredicate(signatures, kind) { var first; var types = []; for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { var sig = signatures_6[_i]; var pred = getTypePredicateOfSignature(sig); if (!pred || pred.kind === 2 /* AssertsThis */ || pred.kind === 3 /* AssertsIdentifier */) { - continue; + if (kind !== 2097152 /* Intersection */) { + continue; + } + else { + return; // intersections demand all members be type predicates for the result to have a predicate + } } if (first) { if (!typePredicateKindsMatch(first, pred)) { @@ -55885,11 +57447,11 @@ var ts; types.push(pred.type); } if (!first) { - // No union signatures had a type predicate. + // No signatures had a type predicate. return undefined; } - var unionType = getUnionType(types); - return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, unionType); + var compositeType = getUnionOrIntersectionType(types, kind); + return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, compositeType); } function typePredicateKindsMatch(a, b) { return a.kind === b.kind && a.parameterIndex === b.parameterIndex; @@ -55914,8 +57476,8 @@ var ts; var typeKey = !origin ? getTypeListId(types) : origin.flags & 1048576 /* Union */ ? "|" + getTypeListId(origin.types) : origin.flags & 2097152 /* Intersection */ ? "&" + getTypeListId(origin.types) : - "#" + origin.type.id; - var id = typeKey + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + "#" + origin.type.id + "|" + getTypeListId(types); // origin type id alone is insufficient, as `keyof x` may resolve to multiple WIP values while `x` is still resolving + var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { type = createUnionType(types, aliasSymbol, aliasTypeArguments, origin); @@ -56041,7 +57603,7 @@ var ts; // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); }); if (index < 0) { return false; } @@ -56050,7 +57612,7 @@ var ts; // the unionTypes array. while (i < types.length) { var t = types[i]; - if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) { + if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -56079,14 +57641,14 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */); + types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */); return true; } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { var result = createType(2097152 /* Intersection */); result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */); result.types = types; - result.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. + result.aliasSymbol = aliasSymbol; result.aliasTypeArguments = aliasTypeArguments; return result; } @@ -56147,7 +57709,7 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } - var id = getTypeListId(typeSet) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeSet) + getAliasId(aliasSymbol, aliasTypeArguments); var result = intersectionTypes.get(id); if (!result) { if (includes & 1048576 /* Union */) { @@ -56190,7 +57752,7 @@ var ts; function checkCrossProductUnion(types) { var size = getCrossProductUnionSize(types); if (size >= 100000) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); return false; } @@ -56240,11 +57802,17 @@ var ts; type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } + function instantiateTypeAsMappedNameType(nameType, type, t) { + return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); + } function getIndexTypeForMappedType(type, noIndexSignatures) { var constraint = filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); }); var nameType = type.declaration.nameType && getTypeFromTypeNode(type.declaration.nameType); + // If the constraint is exclusively string/number/never type(s), we need to pull the property names from the modified type and run them through the `nameType` mapper as well + // since they won't appear in the constraint, due to subtype reducing with the string/number index types + var properties = nameType && everyType(constraint, function (t) { return !!(t.flags & (4 /* String */ | 8 /* Number */ | 131072 /* Never */)); }) && getPropertiesOfType(getApparentType(getModifiersTypeFromMappedType(type))); return nameType ? - mapType(constraint, function (t) { return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); }) : + getUnionType([mapType(constraint, function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); }), mapType(getUnionType(ts.map(properties || ts.emptyArray, function (p) { return getLiteralTypeFromProperty(p, 8576 /* StringOrNumberLiteralOrUnique */); })), function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); })]) : constraint; } // Ordinarily we reduce a keyof M, where M is a mapped type { [P in K as N

]: X }, to simply N. This however presumes @@ -56274,13 +57842,13 @@ var ts; function getLiteralTypeFromProperty(prop, include) { if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { var type = getSymbolLinks(getLateBoundSymbol(prop)).nameType; - if (!type && !ts.isKnownSymbol(prop)) { + if (!type) { if (prop.escapedName === "default" /* Default */) { type = getLiteralType("default"); } else { var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); - type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + type = name && getLiteralTypeFromPropertyName(name) || (!ts.isKnownSymbol(prop) ? getLiteralType(ts.symbolName(prop)) : undefined); } } if (type && type.flags & include) { @@ -56380,7 +57948,6 @@ var ts; var type = templateLiteralTypes.get(id); if (!type) { templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes)); - type.regularType = type; } return type; function addSpans(texts, types) { @@ -56412,10 +57979,8 @@ var ts; return type.flags & 128 /* StringLiteral */ ? type.value : type.flags & 256 /* NumberLiteral */ ? "" + type.value : type.flags & 2048 /* BigIntLiteral */ ? ts.pseudoBigIntToString(type.value) : - type.flags & 512 /* BooleanLiteral */ ? type.intrinsicName : - type.flags & 65536 /* Null */ ? "null" : - type.flags & 32768 /* Undefined */ ? "undefined" : - undefined; + type.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) ? type.intrinsicName : + undefined; } function createTemplateLiteralType(texts, types) { var type = createType(134217728 /* TemplateLiteral */); @@ -56474,7 +58039,7 @@ var ts; if (noImplicitAny) { return false; // Flag is meaningless under `noImplicitAny` mode } - if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + if (ts.getObjectFlags(type) & 8192 /* JSLiteral */) { return true; } if (type.flags & 1048576 /* Union */) { @@ -56484,20 +58049,18 @@ var ts; return ts.some(type.types, isJSLiteralType); } if (type.flags & 465829888 /* Instantiable */) { - return isJSLiteralType(getResolvedBaseConstraint(type)); + var constraint = getResolvedBaseConstraint(type); + return constraint !== type && isJSLiteralType(constraint); } return false; } function getPropertyNameFromIndex(indexType, accessNode) { - var accessExpression = accessNode && accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode : undefined; return isTypeUsableAsPropertyName(indexType) ? getPropertyNameFromType(indexType) : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : - accessNode && ts.isPropertyName(accessNode) ? - // late bound names are handled in the first branch, so here we only need to handle normal names - ts.getPropertyNameForPropertyNameNode(accessNode) : - undefined; + accessNode && ts.isPropertyName(accessNode) ? + // late bound names are handled in the first branch, so here we only need to handle normal names + ts.getPropertyNameForPropertyNameNode(accessNode) : + undefined; } function isUncalledFunctionReference(node, symbol) { if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { @@ -56511,17 +58074,17 @@ var ts; } function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, suppressNoImplicitAnyError, accessNode, accessFlags, noUncheckedIndexedAccessCandidate, reportDeprecated) { var _a; - var accessExpression = accessNode && accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode : undefined; + var accessExpression = accessNode && accessNode.kind === 203 /* ElementAccessExpression */ ? accessNode : undefined; var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode); if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { - if (reportDeprecated && accessNode && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) { + if (reportDeprecated && accessNode && prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) { var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); - errorOrSuggestion(/* isError */ false, deprecatedNode, ts.Diagnostics._0_is_deprecated, propName); + addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName); } if (accessExpression) { - markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 107 /* ThisKeyword */); + markPropertyAsReferenced(prop, accessExpression, isSelfTypeAccess(accessExpression.expression, objectType.symbol)); if (isAssignmentToReadonlyEntity(accessExpression, prop, ts.getAssignmentTargetKind(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); return undefined; @@ -56671,13 +58234,13 @@ var ts; } } function getIndexNodeForAccessExpression(accessNode) { - return accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode.argumentExpression : - accessNode.kind === 189 /* IndexedAccessType */ ? accessNode.indexType : - accessNode.kind === 158 /* ComputedPropertyName */ ? accessNode.expression : + return accessNode.kind === 203 /* ElementAccessExpression */ ? accessNode.argumentExpression : + accessNode.kind === 190 /* IndexedAccessType */ ? accessNode.indexType : + accessNode.kind === 159 /* ComputedPropertyName */ ? accessNode.expression : accessNode; } function isPatternLiteralPlaceholderType(type) { - return templateConstraintType.types.indexOf(type) !== -1 || !!(type.flags & 1 /* Any */); + return !!(type.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 64 /* BigInt */)); } function isPatternLiteralType(type) { return !!(type.flags & 134217728 /* TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType); @@ -56690,6 +58253,13 @@ var ts; } return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) { + type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ | + (isGenericObjectType(type.substitute) || isGenericObjectType(type.baseType) ? 8388608 /* IsGenericObjectType */ : 0); + } + return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); + } return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type) || isGenericTupleType(type); } function isGenericIndexType(type) { @@ -56700,6 +58270,13 @@ var ts; } return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) { + type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ | + (isGenericIndexType(type.substitute) || isGenericIndexType(type.baseType) ? 33554432 /* IsGenericIndexType */ : 0); + } + return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); + } return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) && !isPatternLiteralType(type); } function isThisTypeParameter(type) { @@ -56775,6 +58352,12 @@ var ts; } return type[cache] = type; } + function isConditionalTypeAlwaysTrueDisregardingInferTypes(type) { + var extendsInferParamMapper = type.root.inferTypeParameters && createTypeMapper(type.root.inferTypeParameters, ts.map(type.root.inferTypeParameters, function () { return wildcardType; })); + var checkType = type.checkType; + var extendsType = type.extendsType; + return isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(instantiateType(extendsType, extendsInferParamMapper))); + } function getSimplifiedConditionalType(type, writing) { var checkType = type.checkType; var extendsType = type.extendsType; @@ -56845,14 +58428,14 @@ var ts; // for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved // eagerly using the constraint type of 'this' at the given location. - if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 189 /* IndexedAccessType */ ? + if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 190 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, objectType.target.fixedLength) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, objectType.target.fixedLength)))) { if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; } // Defer the operation by creating an indexed access type. - var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + getAliasId(aliasSymbol, aliasTypeArguments); var type = indexedAccessTypes.get(id); if (!type) { indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined)); @@ -56928,16 +58511,32 @@ var ts; } return type; } - function getConditionalType(root, mapper) { + function isTypicalNondistributiveConditional(root) { + return !root.isDistributive + && root.node.checkType.kind === 180 /* TupleType */ + && ts.length(root.node.checkType.elements) === 1 + && root.node.extendsType.kind === 180 /* TupleType */ + && ts.length(root.node.extendsType.elements) === 1; + } + /** + * We syntactually check for common nondistributive conditional shapes and unwrap them into + * the intended comparison - we do this so we can check if the unwrapped types are generic or + * not and appropriately defer condition calculation + */ + function unwrapNondistributiveConditionalTuple(root, type) { + return isTypicalNondistributiveConditional(root) && isTupleType(type) ? getTypeArguments(type)[0] : type; + } + function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { var result; var extraTypes; // We loop here for an immediately nested conditional type in the false position, effectively treating // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { - var checkType = instantiateType(root.checkType, mapper); + var isUnwrapped = isTypicalNondistributiveConditional(root); + var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); - var extendsType = instantiateType(root.extendsType, mapper); + var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } @@ -56948,21 +58547,24 @@ var ts; // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. - inferTypes(context.inferences, checkType, extendsType, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(context.inferences, checkType, extendsType, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); } - combinedMapper = mergeTypeMappers(mapper, context.mapper); + // It's possible for 'infer T' type paramteters to be given uninstantiated constraints when the + // those type parameters are used in type references (see getInferredTypeParameterConstraint). For + // that reason we need context.mapper to be first in the combined mapper. See #42636 for examples. + combinedMapper = mapper ? combineTypeMappers(context.mapper, mapper) : context.mapper; } // Instantiate the extends type including inferences for 'infer T' type parameters - var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + var inferredExtendsType = combinedMapper ? instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), combinedMapper) : extendsType; // We attempt to resolve the conditional type only when the check and extends types are non-generic if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) { // Return falseType for a definitely false extends check. We check an instantiations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instantiations will be and we can just return the false branch type. - if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { + if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && ((checkType.flags & 1 /* Any */ && !isUnwrapped) || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { // Return union of trueType and falseType for 'any' since it matches anything - if (checkType.flags & 1 /* Any */) { + if (checkType.flags & 1 /* Any */ && !isUnwrapped) { (extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper)); } // If falseType is an immediately nested conditional type that isn't distributive or has an @@ -56991,12 +58593,12 @@ var ts; // Return a deferred type for a check that is neither definitely true nor definitely false result = createType(16777216 /* Conditional */); result.root = root; - result.checkType = checkType; - result.extendsType = extendsType; + result.checkType = instantiateType(root.checkType, mapper); + result.extendsType = instantiateType(root.extendsType, mapper); result.mapper = mapper; result.combinedMapper = combinedMapper; - result.aliasSymbol = root.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 + result.aliasSymbol = aliasSymbol || root.aliasSymbol; + result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 break; } return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result; @@ -57202,7 +58804,7 @@ var ts; } } var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return spread; } } @@ -57308,14 +58910,15 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */ | 4194304 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ function isSpreadableProperty(prop) { - return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) && + var _a; + return !ts.some(prop.declarations, ts.isPrivateIdentifierClassElementDeclaration) && (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || - !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); })); + !((_a = prop.declarations) === null || _a === void 0 ? void 0 : _a.some(function (decl) { return ts.isClassLike(decl.parent); }))); } function getSpreadSymbol(prop, readonly) { var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); @@ -57340,11 +58943,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 134220672 /* FreshableLiteral */) { + if (type.flags & 2944 /* Literal */) { if (!type.freshType) { - var freshType = type.flags & 134217728 /* TemplateLiteral */ ? - createTemplateLiteralType(type.texts, type.types) : - createLiteralType(type.flags, type.value, type.symbol); + var freshType = createLiteralType(type.flags, type.value, type.symbol); freshType.regularType = type; freshType.freshType = freshType; type.freshType = freshType; @@ -57354,12 +58955,12 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 134220672 /* FreshableLiteral */ ? type.regularType : + return type.flags & 2944 /* Literal */ ? type.regularType : type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = mapType(type, getRegularTypeOfLiteralType))) : type; } function isFreshLiteralType(type) { - return !!(type.flags & 134220672 /* FreshableLiteral */) && type.freshType === type; + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -57405,7 +59006,7 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 253 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 254 /* InterfaceDeclaration */)) { if (!ts.hasSyntacticModifier(container, 32 /* Static */) && (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; @@ -57440,17 +59041,17 @@ var ts; } function getArrayElementTypeNode(node) { switch (node.kind) { - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return getArrayElementTypeNode(node.type); - case 179 /* TupleType */: + case 180 /* TupleType */: if (node.elements.length === 1) { node = node.elements[0]; - if (node.kind === 181 /* RestType */ || node.kind === 192 /* NamedTupleMember */ && node.dotDotDotToken) { + if (node.kind === 182 /* RestType */ || node.kind === 193 /* NamedTupleMember */ && node.dotDotDotToken) { return getArrayElementTypeNode(node.type); } } break; - case 178 /* ArrayType */: + case 179 /* ArrayType */: return node.elementType; } return undefined; @@ -57468,8 +59069,8 @@ var ts; function getTypeFromTypeNodeWorker(node) { switch (node.kind) { case 128 /* AnyKeyword */: - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: return anyType; case 152 /* UnknownKeyword */: return unknownType; @@ -57496,70 +59097,70 @@ var ts; return node.flags & 131072 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType; case 136 /* IntrinsicKeyword */: return intrinsicMarkerType; - case 187 /* ThisType */: + case 188 /* ThisType */: case 107 /* ThisKeyword */: // TODO(rbuckton): `ThisKeyword` is no longer a `TypeNode`, but we defensively allow it here because of incorrect casts in the Language Service and because of `isPartOfTypeNode`. return getTypeFromThisTypeNode(node); - case 191 /* LiteralType */: + case 192 /* LiteralType */: return getTypeFromLiteralTypeNode(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return getTypeFromTypeReference(node); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return node.assertsModifier ? voidType : booleanType; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 178 /* ArrayType */: - case 179 /* TupleType */: + case 179 /* ArrayType */: + case 180 /* TupleType */: return getTypeFromArrayOrTupleTypeNode(node); - case 180 /* OptionalType */: + case 181 /* OptionalType */: return getTypeFromOptionalTypeNode(node); - case 182 /* UnionType */: + case 183 /* UnionType */: return getTypeFromUnionTypeNode(node); - case 183 /* IntersectionType */: + case 184 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 305 /* JSDocNullableType */: + case 306 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 307 /* JSDocOptionalType */: + case 308 /* JSDocOptionalType */: return addOptionality(getTypeFromTypeNode(node.type)); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return getTypeFromNamedTupleTypeNode(node); - case 186 /* ParenthesizedType */: - case 306 /* JSDocNonNullableType */: - case 301 /* JSDocTypeExpression */: + case 187 /* ParenthesizedType */: + case 307 /* JSDocNonNullableType */: + case 302 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 181 /* RestType */: + case 182 /* RestType */: return getTypeFromRestTypeNode(node); - case 309 /* JSDocVariadicType */: + case 310 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 308 /* JSDocFunctionType */: - case 313 /* JSDocSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 309 /* JSDocFunctionType */: + case 315 /* JSDocSignature */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return getTypeFromIndexedAccessTypeNode(node); - case 190 /* MappedType */: + case 191 /* MappedType */: return getTypeFromMappedTypeNode(node); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return getTypeFromConditionalTypeNode(node); - case 185 /* InferType */: + case 186 /* InferType */: return getTypeFromInferTypeNode(node); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: return getTypeFromTemplateTypeNode(node); - case 195 /* ImportType */: + case 196 /* ImportType */: return getTypeFromImportTypeNode(node); // This function assumes that an identifier, qualified name, or property access expression is a type expression // Callers should first ensure this by calling `isPartOfTypeNode` // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s. case 78 /* Identifier */: - case 157 /* QualifiedName */: - case 201 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: var symbol = getSymbolAtLocation(node); return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: @@ -57712,7 +59313,7 @@ var ts; } return result; } - function getObjectTypeInstantiation(type, mapper) { + function getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { var declaration = type.objectFlags & 4 /* Reference */ ? type.node : type.symbol.declarations[0]; var links = getNodeLinks(declaration); var target = type.objectFlags & 4 /* Reference */ ? links.resolvedType : @@ -57729,8 +59330,9 @@ var ts; outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } typeParameters = outerTypeParameters || ts.emptyArray; - typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? - ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration); }) : + var allDeclarations_1 = type.objectFlags & 4 /* Reference */ ? [declaration] : type.symbol.declarations; + typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 8192 /* Method */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? + ts.filter(typeParameters, function (tp) { return ts.some(allDeclarations_1, function (d) { return isTypeParameterPossiblyReferenced(tp, d); }); }) : typeParameters; links.outerTypeParameters = typeParameters; } @@ -57740,17 +59342,19 @@ var ts; // instantiation cache key from the type IDs of the type arguments. var combinedMapper_1 = combineTypeMappers(type.mapper, mapper); var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); }); - var id = getTypeListId(typeArguments); + var newAliasSymbol = aliasSymbol || type.aliasSymbol; + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + var id = getTypeListId(typeArguments) + getAliasId(newAliasSymbol, newAliasTypeArguments); if (!target.instantiations) { target.instantiations = new ts.Map(); - target.instantiations.set(getTypeListId(typeParameters), target); + target.instantiations.set(getTypeListId(typeParameters) + getAliasId(target.aliasSymbol, target.aliasTypeArguments), target); } var result = target.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(typeParameters, typeArguments); - result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper) : - target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) : - instantiateAnonymousType(target, newMapper); + result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) : + target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) : + instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments); target.instantiations.set(id, result); } return result; @@ -57758,9 +59362,9 @@ var ts; return type; } function maybeTypeParameterReference(node) { - return !(node.kind === 157 /* QualifiedName */ || - node.parent.kind === 173 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName || - node.parent.kind === 195 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier); + return !(node.kind === 158 /* QualifiedName */ || + node.parent.kind === 174 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName || + node.parent.kind === 196 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier); } function isTypeParameterPossiblyReferenced(tp, node) { // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks @@ -57769,22 +59373,25 @@ var ts; if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container = tp.symbol.declarations[0].parent; for (var n = node; n !== container; n = n.parent) { - if (!n || n.kind === 230 /* Block */ || n.kind === 184 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) { + if (!n || n.kind === 231 /* Block */ || n.kind === 185 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) { return true; } } - return !!ts.forEachChild(node, containsReference); + return containsReference(node); } return true; function containsReference(node) { switch (node.kind) { - case 187 /* ThisType */: + case 188 /* ThisType */: return !!tp.isThisType; case 78 /* Identifier */: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return true; + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + return (!node.type && !!node.body) || !!ts.forEachChild(node, containsReference); } return !!ts.forEachChild(node, containsReference); } @@ -57799,7 +59406,7 @@ var ts; } return undefined; } - function instantiateMappedType(type, mapper) { + function instantiateMappedType(type, mapper, aliasSymbol, aliasTypeArguments) { // 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. @@ -57814,7 +59421,7 @@ var ts; if (typeVariable) { var mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapType(getReducedType(mappedTypeVariable), function (t) { + return mapTypeWithAlias(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) { if (!type.declaration.nameType) { if (isArrayType(t)) { @@ -57830,11 +59437,11 @@ var ts; return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper)); } return t; - }); + }, aliasSymbol, aliasTypeArguments); } } // If the constraint type of the instantiation is the wildcard type, return the wildcard type. - return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper); + return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments); } function getModifiedReadonlyState(state, modifiers) { return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state; @@ -57881,7 +59488,7 @@ var ts; strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; } - function instantiateAnonymousType(type, mapper) { + function instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; @@ -57894,29 +59501,29 @@ var ts; } result.target = type; result.mapper = mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + result.aliasSymbol = aliasSymbol || type.aliasSymbol; + result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); return result; } - function getConditionalTypeInstantiation(type, mapper) { + function getConditionalTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { var root = type.root; if (root.outerTypeParameters) { // We are instantiating a conditional type that has one or more type parameters in scope. Apply the // mapper to the type parameters to produce the effective list of type arguments, and compute the // instantiation cache key from the type IDs of the type arguments. var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); }); - var id = getTypeListId(typeArguments); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var result = root.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); - result = instantiateConditionalType(root, newMapper); + result = instantiateConditionalType(root, newMapper, aliasSymbol, aliasTypeArguments); root.instantiations.set(id, result); } return result; } return type; } - function instantiateConditionalType(root, mapper) { + function instantiateConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { // Check if we have a conditional type where the check type is a naked type parameter. If so, // the conditional type is distributive over union types and when T is instantiated to a union // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y). @@ -57924,31 +59531,34 @@ var ts; var checkType_1 = root.checkType; var instantiatedType = getMappedType(checkType_1, mapper); if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) { - return mapType(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); }); + return mapTypeWithAlias(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); }, aliasSymbol, aliasTypeArguments); } } - return getConditionalType(root, mapper); + return getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments); } function instantiateType(type, mapper) { - if (!(type && mapper && couldContainTypeVariables(type))) { + return type && mapper ? instantiateTypeWithAlias(type, mapper, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined) : type; + } + function instantiateTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) { + if (!couldContainTypeVariables(type)) { return type; } if (instantiationDepth === 50 || instantiationCount >= 5000000) { // 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. - ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); return errorType; } totalInstantiationCount++; instantiationCount++; instantiationDepth++; - var result = instantiateTypeWorker(type, mapper); + var result = instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments); instantiationDepth--; return result; } - function instantiateTypeWorker(type, mapper) { + function instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments) { var flags = type.flags; if (flags & 262144 /* TypeParameter */) { return getMappedType(type, mapper); @@ -57956,12 +59566,15 @@ var ts; if (flags & 524288 /* Object */) { var objectFlags = type.objectFlags; if (objectFlags & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */)) { - if (objectFlags & 4 /* Reference */ && !(type.node)) { + if (objectFlags & 4 /* Reference */ && !type.node) { var resolvedTypeArguments = type.resolvedTypeArguments; var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type; } - return getObjectTypeInstantiation(type, mapper); + if (objectFlags & 1024 /* ReverseMapped */) { + return instantiateReverseMappedType(type, mapper); + } + return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments); } return type; } @@ -57969,10 +59582,14 @@ var ts; var origin = type.flags & 1048576 /* Union */ ? type.origin : undefined; var types = origin && origin.flags & 3145728 /* UnionOrIntersection */ ? origin.types : type.types; var newTypes = instantiateTypes(types, mapper); - return newTypes === types ? type : - flags & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ? - getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : - getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + if (newTypes === types && aliasSymbol === type.aliasSymbol) { + return type; + } + var newAliasSymbol = aliasSymbol || type.aliasSymbol; + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + return flags & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ? + getIntersectionType(newTypes, newAliasSymbol, newAliasTypeArguments) : + getUnionType(newTypes, 1 /* Literal */, newAliasSymbol, newAliasTypeArguments); } if (flags & 4194304 /* Index */) { return getIndexType(instantiateType(type.type, mapper)); @@ -57984,10 +59601,12 @@ var ts; return getStringMappingType(type.symbol, instantiateType(type.type, mapper)); } if (flags & 8388608 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + var newAliasSymbol = aliasSymbol || type.aliasSymbol; + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, newAliasSymbol, newAliasTypeArguments); } if (flags & 16777216 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper), aliasSymbol, aliasTypeArguments); } if (flags & 33554432 /* Substitution */) { var maybeVariable = instantiateType(type.baseType, mapper); @@ -58004,6 +59623,21 @@ var ts; } return type; } + function instantiateReverseMappedType(type, mapper) { + var innerMappedType = instantiateType(type.mappedType, mapper); + if (!(ts.getObjectFlags(innerMappedType) & 32 /* Mapped */)) { + return type; + } + var innerIndexType = instantiateType(type.constraintType, mapper); + if (!(innerIndexType.flags & 4194304 /* Index */)) { + return type; + } + var instantiated = inferTypeForHomomorphicMappedType(instantiateType(type.source, mapper), innerMappedType, innerIndexType); + if (instantiated) { + return instantiated; + } + return type; // Nested invocation of `inferTypeForHomomorphicMappedType` or the `source` instantiated into something unmappable + } function getPermissiveInstantiation(type) { return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); @@ -58030,35 +59664,35 @@ var 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) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 251 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type return isContextSensitiveFunctionLikeDeclaration(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return ts.some(node.properties, isContextSensitive); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return ts.some(node.elements, isContextSensitive); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return (node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */) && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isContextSensitive(node.expression); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); - case 280 /* JsxAttribute */: { + case 281 /* JsxAttribute */: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. var initializer = node.initializer; return !!initializer && isContextSensitive(initializer); } - case 283 /* JsxExpression */: { + case 284 /* JsxExpression */: { // It is possible to that node.expression is undefined (e.g

) var expression = node.expression; return !!expression && isContextSensitive(expression); @@ -58077,7 +59711,7 @@ var ts; if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 209 /* ArrowFunction */) { + if (node.kind !== 210 /* ArrowFunction */) { // If the first parameter is not an explicit 'this' parameter, then the function has // an implicit 'this' parameter which is subject to contextual typing. var parameter = ts.firstOrUndefined(node.parameters); @@ -58090,7 +59724,7 @@ var ts; } function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 230 /* Block */ && isContextSensitive(node.body); + return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 231 /* Block */ && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -58193,23 +59827,23 @@ var ts; return true; } switch (node.kind) { - case 283 /* JsxExpression */: - case 207 /* ParenthesizedExpression */: + case 284 /* JsxExpression */: + case 208 /* ParenthesizedExpression */: return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (node.operatorToken.kind) { case 62 /* EqualsToken */: case 27 /* CommaToken */: return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); } break; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer); } return false; @@ -58409,7 +60043,7 @@ var ts; } function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) { switch (child.kind) { - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: // child is of the type of the expression return { errorNode: child, innerExpression: child.expression, nameType: nameType }; case 11 /* JsxText */: @@ -58418,9 +60052,9 @@ var ts; } // child is a string return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() }; - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: // child is of type JSX.Element return { errorNode: child, innerExpression: child, nameType: nameType }; default: @@ -58568,11 +60202,11 @@ var ts; } _b = prop.kind; switch (_b) { - case 168 /* SetAccessor */: return [3 /*break*/, 2]; - case 167 /* GetAccessor */: return [3 /*break*/, 2]; - case 165 /* MethodDeclaration */: return [3 /*break*/, 2]; - case 289 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; - case 288 /* PropertyAssignment */: return [3 /*break*/, 4]; + case 169 /* SetAccessor */: return [3 /*break*/, 2]; + case 168 /* GetAccessor */: return [3 /*break*/, 2]; + case 166 /* MethodDeclaration */: return [3 /*break*/, 2]; + case 290 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 289 /* PropertyAssignment */: return [3 /*break*/, 4]; } return [3 /*break*/, 6]; case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; @@ -58649,8 +60283,8 @@ var ts; return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; - var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 165 /* MethodDeclaration */ && - kind !== 164 /* MethodSignature */ && kind !== 166 /* Constructor */; + var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 166 /* MethodDeclaration */ && + kind !== 165 /* MethodSignature */ && kind !== 167 /* Constructor */; var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { @@ -58883,7 +60517,7 @@ var ts; // Type number or any numeric literal type is assignable to any numeric enum type or any // numeric enum literal type. This rule exists for backwards compatibility reasons because // bit-flag enum types sometimes look like literal enum types with numeric literal values. - if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) + if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || relation === assignableRelation && t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) return true; } return false; @@ -58920,7 +60554,7 @@ var ts; return false; } function isIgnoredJsxProperty(source, sourceProp) { - return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); + return ts.getObjectFlags(source) & 2048 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { while (true) { @@ -58930,6 +60564,7 @@ var ts; type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute : type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : type; + t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) break; type = t; @@ -58967,7 +60602,7 @@ var ts; reportIncompatibleStack(); } if (overflow) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); @@ -59103,6 +60738,14 @@ var ts; } break; } + case ts.Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target.code: { + secondaryRootErrors.unshift([ts.Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target, args[0], args[1]]); + break; + } + case ts.Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target.code: { + secondaryRootErrors.unshift([ts.Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target, args[0], args[1], args[2]]); + break; + } default: return ts.Debug.fail("Unhandled Diagnostic: " + msg.code); } @@ -59163,6 +60806,7 @@ var ts; reportError(ts.Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2, needsOriginalSource ? sourceType : generalizedSourceType, targetType, typeToString(constraint)); } else { + errorInfo = undefined; reportError(ts.Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, generalizedSourceType); } } @@ -59238,7 +60882,7 @@ var ts; if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { return -1 /* True */; } - reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */)); + reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 2048 /* JsxAttributes */)); return 0 /* False */; } // Normalize the source and target types: Turn fresh literal types into regular literal types, @@ -59273,16 +60917,16 @@ var ts; target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) { var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */); if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) { - if (source === nullStrippedTarget) - return -1 /* True */; - target = nullStrippedTarget; + target = getNormalizedType(nullStrippedTarget, /*writing*/ true); } + if (source === nullStrippedTarget) + return -1 /* True */; } if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); + var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384 /* FreshLiteral */); if (isPerformingExcessPropertyChecks) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -59367,7 +61011,7 @@ var ts; // We suppress recursive intersection property checks because they can generate lots of work when relating // recursive intersections that are structurally similar but not exactly identical. See #37854. if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) { + isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 524288 /* NonInferrableType */); }))) { inPropertyCheck = true; result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */); inPropertyCheck = false; @@ -59376,8 +61020,10 @@ var ts; return result; function reportErrorResults(source, target, result, isComparingJsxAttributes) { if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; + var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); + var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); + source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; + target = (originalTarget.aliasSymbol || targetHasBase) ? originalTarget : target; var maybeSuppress = overrideNextErrorInfo > 0; if (maybeSuppress) { overrideNextErrorInfo--; @@ -59418,13 +61064,13 @@ var ts; } } function traceUnionsOrIntersectionsTooLarge(source, target) { - if (!ts.tracing.isTracing()) { + if (!ts.tracing) { return; } if ((source.flags & 3145728 /* UnionOrIntersection */) && (target.flags & 3145728 /* UnionOrIntersection */)) { var sourceUnionOrIntersection = source; var targetUnionOrIntersection = target; - if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 262144 /* PrimitiveUnion */) { + if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 65536 /* PrimitiveUnion */) { // There's a fast path for comparing primitive unions return; } @@ -59449,11 +61095,11 @@ var ts; } traceUnionsOrIntersectionsTooLarge(source, target); if (flags & 3145728 /* UnionOrIntersection */) { - var result_6 = eachTypeRelatedToSomeType(source, target); - if (result_6) { - result_6 &= eachTypeRelatedToSomeType(target, source); + var result_7 = eachTypeRelatedToSomeType(source, target); + if (result_7) { + result_7 &= eachTypeRelatedToSomeType(target, source); } - return result_6; + return result_7; } return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */); } @@ -59467,10 +61113,11 @@ var ts; return getUnionType(ts.reduceLeft(types, appendPropType, /*initial*/ undefined) || ts.emptyArray); } function hasExcessProperties(source, target, reportErrors) { - if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + var _a; + if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 8192 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; @@ -59513,7 +61160,7 @@ var ts; } else { // use the property's value declaration if the property is assigned inside the literal itself - var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + var objectLiteralDeclaration_1 = ((_a = source.symbol) === null || _a === void 0 ? void 0 : _a.declarations) && ts.firstOrUndefined(source.symbol.declarations); var suggestion = void 0; if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) { var propDeclaration = prop.valueDeclaration; @@ -59542,11 +61189,11 @@ var ts; } } }; - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - var state_4 = _loop_16(prop); - if (typeof state_4 === "object") - return state_4.value; + for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { + var prop = _b[_i]; + var state_5 = _loop_16(prop); + if (typeof state_5 === "object") + return state_5.value; } return false; } @@ -59568,8 +61215,17 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) { - return -1 /* True */; + if (target.flags & 1048576 /* Union */) { + if (containsType(targetTypes, source)) { + return -1 /* True */; + } + var match = getMatchingUnionConstituentForType(target, source); + if (match) { + var related = isRelatedTo(source, match, /*reportErrors*/ false); + if (related) { + return related; + } + } } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { var type = targetTypes_1[_i]; @@ -59743,9 +61399,16 @@ var ts; targetStack = []; } else { + // generate a key where all type parameter id positions are replaced with unconstrained type parameter ids + // this isn't perfect - nested type references passed as type arguments will muck up the indexes and thus + // prevent finding matches- but it should hit up the common cases + var broadestEquivalentId = id.split(",").map(function (i) { return i.replace(/-\d+/g, function (_match, offset) { + var index = ts.length(id.slice(0, offset).match(/[-=]/g) || undefined); + return "=" + index; + }); }).join(","); for (var i = 0; i < maybeCount; i++) { // If source and target are already being compared, consider them related with assumptions - if (id === maybeKeys[i]) { + if (id === maybeKeys[i] || broadestEquivalentId === maybeKeys[i]) { return 3 /* Maybe */; } } @@ -59775,7 +61438,7 @@ var ts; }; } if (expandingFlags === 3 /* Both */) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { sourceId: source.id, sourceIdStack: sourceStack.map(function (t) { return t.id; }), targetId: target.id, @@ -59810,9 +61473,9 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { - ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) { @@ -59834,8 +61497,21 @@ var ts; if (target.flags & 2097152 /* Intersection */) { return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */); } - // Source is an intersection. Check to see if any constituents of the intersection are immediately related - // to the target. + // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the + // constraints of all non-primitive types in the source into a new intersection. We do this because the + // intersection may further constrain the constraints of the non-primitive types. For example, given a type + // parameter 'T extends 1 | 2', the intersection 'T & 1' should be reduced to '1' such that it doesn't + // appear to be comparable to '2'. + if (relation === comparableRelation && target.flags & 131068 /* Primitive */) { + var constraints = ts.sameMap(source.types, function (t) { return t.flags & 131068 /* Primitive */ ? t : getBaseConstraintOfType(t) || unknownType; }); + if (constraints !== source.types) { + source = getIntersectionType(constraints); + if (!(source.flags & 2097152 /* Intersection */)) { + return isRelatedTo(source, target, /*reportErrors*/ false); + } + } + } + // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually // useful and leads to some confusing error messages. Instead it is better to let the below checks @@ -59855,21 +61531,21 @@ var ts; if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_7 = 0 /* False */; + var result_8 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_7 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_8; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_7 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_8; } } } @@ -59949,6 +61625,20 @@ var ts; } } else if (target.flags & 8388608 /* IndexedAccess */) { + if (source.flags & 8388608 /* IndexedAccess */) { + // Relate components directly before falling back to constraint relationships + // A type S[K] is related to a type T[J] if S is related to T and K is related to J. + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + if (reportErrors) { + originalErrorInfo = errorInfo; + } + } // A type S is related to a type T[K] if S is related to C, where C is the base // constraint of T[K] for writing. if (relation === assignableRelation || relation === comparableRelation) { @@ -59959,11 +61649,24 @@ var ts; if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) { var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0); var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, target.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, accessFlags); - if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) { - return result; + if (constraint) { + if (reportErrors && originalErrorInfo) { + // create a new chain for the constraint error + resetErrorInfo(saveErrorInfo); + } + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + // prefer the shorter chain of the constraint comparison chain, and the direct comparison chain + if (reportErrors && originalErrorInfo && errorInfo) { + errorInfo = countMessageChainBreadth([originalErrorInfo]) <= countMessageChainBreadth([errorInfo]) ? originalErrorInfo : errorInfo; + } } } } + if (reportErrors) { + originalErrorInfo = undefined; + } } else if (isGenericMappedType(target) && !target.declaration.nameType) { // A source type T is related to a target type { [P in X]: T[P] } @@ -60007,27 +61710,48 @@ var ts; } } } - else if (target.flags & 134217728 /* TemplateLiteral */ && source.flags & 128 /* StringLiteral */) { - if (isPatternLiteralType(target)) { - // match all non-`string` segments - var result_8 = inferLiteralsFromTemplateLiteralType(source, target); - if (result_8 && ts.every(result_8, function (r, i) { return isStringLiteralTypeValueParsableAsType(r, target.types[i]); })) { - return -1 /* True */; - } + else if (target.flags & 16777216 /* Conditional */) { + var c = target; + // Check if the conditional is always true or always false but still deferred for distribution purposes + var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); + var skipFalse = !skipTrue && isConditionalTypeAlwaysTrueDisregardingInferTypes(c); + // Instantiate with a replacement mapper if the conditional is distributive, replacing the check type with a clone of itself, + // this way {x: string | number, y: string | number} -> (T extends T ? { x: T, y: T } : never) appropriately _fails_ when + // T = string | number (since that will end up distributing and producing `{x: string, y: string} | {x: number, y: number}`, + // to which `{x: string | number, y: string | number}` isn't assignable) + var distributionMapper = void 0; + var checkVar = getActualTypeVariable(c.root.checkType); + if (c.root.isDistributive && checkVar.flags & 262144 /* TypeParameter */) { + var newParam = cloneTypeParameter(checkVar); + distributionMapper = prependTypeMapping(checkVar, newParam, c.mapper); + newParam.mapper = distributionMapper; + } + // TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't) + var localResult = void 0; + if (skipTrue || (localResult = isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.trueType), distributionMapper) : getTrueTypeFromConditionalType(c), /*reportErrors*/ false))) { + if (!skipFalse) { + localResult = (localResult || 3 /* Maybe */) & isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.falseType), distributionMapper) : getFalseTypeFromConditionalType(c), /*reportErrors*/ false); + } + } + if (localResult) { + resetErrorInfo(saveErrorInfo); + return localResult; } } - if (source.flags & 8650752 /* TypeVariable */) { - if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { - // A type S[K] is related to a type T[J] if S is related to T and K is related to J. - if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { - result &= isRelatedTo(source.indexType, target.indexType, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } + else if (target.flags & 134217728 /* TemplateLiteral */) { + if (source.flags & 134217728 /* TemplateLiteral */) { + // Report unreliable variance for type variables referenced in template literal type placeholders. + // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. + instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } - else { + var result_9 = inferTypesFromTemplateLiteralType(source, target); + if (result_9 && ts.every(result_9, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { + return -1 /* True */; + } + } + if (source.flags & 8650752 /* TypeVariable */) { + // IndexedAccess comparisons are handled above in the `target.flags & TypeFlage.IndexedAccess` branch + if (!(source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */)) { var constraint = getConstraintOfType(source); if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. @@ -60042,7 +61766,7 @@ var ts; return result; } // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example - else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, intersectionState)) { + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors && !(target.flags & source.flags & 262144 /* TypeParameter */), /*headMessage*/ undefined, intersectionState)) { resetErrorInfo(saveErrorInfo); return result; } @@ -60055,17 +61779,10 @@ var ts; } } else if (source.flags & 134217728 /* TemplateLiteral */) { - if (target.flags & 134217728 /* TemplateLiteral */) { - if (source.texts.length === target.texts.length && - source.types.length === target.types.length && - ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) && - ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 /* Any */ | 4 /* String */)) || !!isRelatedTo(t, target.types[i], /*reportErrors*/ false); })) { - return -1 /* True */; - } - } - else { - var constraint = getBaseConstraintOfType(source); - if (result = isRelatedTo(constraint && constraint !== source ? constraint : stringType, target, reportErrors)) { + if (!(target.flags & 134217728 /* TemplateLiteral */)) { + var baseConstraint = getBaseConstraintOfType(source); + var constraint = baseConstraint && baseConstraint !== source ? baseConstraint : stringType; + if (result = isRelatedTo(constraint, target, reportErrors)) { resetErrorInfo(saveErrorInfo); return result; } @@ -60097,7 +61814,7 @@ var ts; if (sourceParams) { // If the source has infer type parameters, we instantiate them in the context of the target var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo); - inferTypes(ctx.inferences, target.extendsType, sourceExtends, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); sourceExtends = instantiateType(sourceExtends, ctx.mapper); mapper = ctx.mapper; } @@ -60155,7 +61872,7 @@ var ts; return 0 /* False */; } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && - !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { + !(ts.getObjectFlags(source) & 4096 /* MarkerType */ || ts.getObjectFlags(target) & 4096 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. @@ -60183,7 +61900,7 @@ var ts; } // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})` // and not `{} <- fresh({}) <- {[idx: string]: any}` - else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) { + else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 16384 /* FreshLiteral */ && !isEmptyObjectType(source)) { return 0 /* False */; } // Even if relationship doesn't hold for unions, intersections, or generic type references, @@ -60221,14 +61938,19 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_9) { - return result_9; + var result_10 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_10) { + return result_10; } } } } return 0 /* False */; + function countMessageChainBreadth(info) { + if (!info) + return 0; + return ts.reduceLeft(info, function (value, chain) { return value + 1 + countMessageChainBreadth(chain.next); }, 0); + } function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) { if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) { return result; @@ -60290,13 +62012,13 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_10; + var result_11; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + if (result_11 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { - return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_11 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } } @@ -60327,7 +62049,7 @@ var ts; numCombinations *= countTypes(getTypeOfSymbol(sourceProperty)); if (numCombinations > 25) { // We've reached the complexity limit. - ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); return 0 /* False */; } } @@ -60366,8 +62088,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_6 = _loop_18(i); - switch (state_6) { + var state_7 = _loop_18(i); + switch (state_7) { case "continue-outer": continue outer; } } @@ -60380,9 +62102,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_5 = _loop_17(combination); - if (typeof state_5 === "object") - return state_5.value; + var state_6 = _loop_17(combination); + if (typeof state_6 === "object") + return state_6.value; } // Compare the remaining non-discriminant properties of each match. var result = -1 /* True */; @@ -60436,7 +62158,7 @@ var ts; ts.Debug.assertIsDefined(links.deferralParent); ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */); - var result_11 = unionParent ? 0 /* False */ : -1 /* True */; + var result_12 = unionParent ? 0 /* False */ : -1 /* True */; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -60446,7 +62168,7 @@ var ts; // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_11 &= related; + result_12 &= related; } else { if (related) { @@ -60454,17 +62176,17 @@ var ts; } } } - if (unionParent && !result_11 && targetIsOptional) { - result_11 = isRelatedTo(source, undefinedType); + if (unionParent && !result_12 && targetIsOptional) { + result_12 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_11 && reportErrors) { + if (unionParent && !result_12 && reportErrors) { // The easiest way to get the right errors here is to un-defer (which may be costly) // If it turns out this is too costly too often, we can replicate the error handling logic within // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union // type on which to hand discriminable properties, which we are expressly trying to avoid here) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_11; + return result_12; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState); @@ -60795,7 +62517,7 @@ var ts; var targetSignature = ts.first(targetSignatures); result = signatureRelatedTo(sourceSignature, targetSignature, eraseGenerics, reportErrors, incompatibleReporter(sourceSignature, targetSignature)); if (!result && reportErrors && kind === 1 /* Construct */ && (sourceObjectFlags & targetObjectFlags) && - (((_a = targetSignature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 166 /* Constructor */ || ((_b = sourceSignature.declaration) === null || _b === void 0 ? void 0 : _b.kind) === 166 /* Constructor */)) { + (((_a = targetSignature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 167 /* Constructor */ || ((_b = sourceSignature.declaration) === null || _b === void 0 ? void 0 : _b.kind) === 167 /* Constructor */)) { var constructSignatureToString = function (signature) { return signatureToString(signature, /*enclosingDeclaration*/ undefined, 262144 /* WriteArrowStyleSignature */, kind); }; @@ -60903,10 +62625,17 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetType = getIndexTypeOfType(target, kind); - if (!targetType || targetType.flags & 1 /* Any */ && !sourceIsPrimitive) { - // Index signature of type any permits assignment from everything but primitives + if (!targetType) { return -1 /* True */; } + if (targetType.flags & 1 /* Any */ && !sourceIsPrimitive) { + // An index signature of type `any` permits assignment from everything but primitives, + // provided that there is also a `string` index signature of type `any`. + var stringIndexType = kind === 0 /* String */ ? targetType : getIndexTypeOfType(target, 0 /* String */); + if (stringIndexType && stringIndexType.flags & 1 /* Any */) { + return -1 /* True */; + } + } if (isGenericMappedType(source)) { // A generic mapped type { [P in K]: T } is related to a type with an index signature // { [x: string]: U }, and optionally with an index signature { [x: number]: V }, @@ -61061,7 +62790,7 @@ var ts; // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); - result.objectFlags |= 8192 /* MarkerType */; + result.objectFlags |= 4096 /* MarkerType */; return result; } function getAliasVariances(symbol) { @@ -61082,7 +62811,7 @@ var ts; if (typeParameters === void 0) { typeParameters = ts.emptyArray; } var variances = cache.variances; if (!variances) { - ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); // The emptyArray singleton is used to signal a recursive invocation. cache.variances = ts.emptyArray; variances = []; @@ -61121,7 +62850,7 @@ var ts; _loop_19(tp); } cache.variances = variances; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } return variances; } @@ -61149,7 +62878,7 @@ var ts; return !!(ts.getObjectFlags(type) & 4 /* Reference */) && !type.node; } function isTypeReferenceWithGenericArguments(type) { - return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return !!(t.flags & 262144 /* TypeParameter */) || isTypeReferenceWithGenericArguments(t); }); } /** * getTypeReferenceId(A) returns "111=0-12=1" @@ -61235,8 +62964,8 @@ var ts; } // Return true if the given class derives from each of the declaring classes of the protected // constituents of the given property. - function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) { + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p, writing) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons @@ -61254,23 +62983,26 @@ var ts; function isDeeplyNestedType(type, stack, depth) { if (depth >= 5) { var identity_1 = getRecursionIdentity(type); - if (identity_1) { - var count = 0; - for (var i = 0; i < depth; i++) { - if (getRecursionIdentity(stack[i]) === identity_1) { - count++; - if (count >= 5) { - return true; - } + var count = 0; + for (var i = 0; i < depth; i++) { + if (getRecursionIdentity(stack[i]) === identity_1) { + count++; + if (count >= 5) { + return true; } } } } return false; } - // Types with constituents that could circularly reference the type have a recursion identity. The recursion - // identity is some object that is common to instantiations of the type with the same origin. + // The recursion identity of a type is an object identity that is shared among multiple instantiations of the type. + // We track recursion identities in order to identify deeply nested and possibly infinite type instantiations with + // the same origin. For example, when type parameters are in scope in an object type such as { x: T }, all + // instantiations of that type have the same recursion identity. The default recursion identity is the object + // identity of the type, meaning that every type is unique. Generally, types with constituents that could circularly + // reference the type have a recursion identity that differs from the object identity. function getRecursionIdentity(type) { + // Object and array literals are known not to contain recursive references and don't need a recursion identity. if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) { if (ts.getObjectFlags(type) && 4 /* Reference */ && type.node) { // Deferred type references are tracked through their associated AST node. This gives us finer @@ -61288,6 +63020,9 @@ var ts; return type.target; } } + if (type.flags & 262144 /* TypeParameter */) { + return type.symbol; + } if (type.flags & 8388608 /* IndexedAccess */) { // Identity is the leftmost object type in a chain of indexed accesses, eg, in A[P][Q] it is A do { @@ -61299,7 +63034,7 @@ var ts; // The root object represents the origin of the conditional type return type.root; } - return undefined; + return type; } function isPropertyIdenticalTo(sourceProp, targetProp) { return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; @@ -61438,6 +63173,9 @@ var ts; // of those literal types. Otherwise, return the leftmost type for which no type to the // right is a supertype. function getSupertypeOrUnion(types) { + if (types.length === 1) { + return types[0]; + } return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); @@ -61472,9 +63210,32 @@ var ts; // or if it is not the undefined or null type and if it is assignable to ReadonlyArray return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } + function getSingleBaseForNonAugmentingSubtype(type) { + if (!(ts.getObjectFlags(type) & 4 /* Reference */) || !(ts.getObjectFlags(type.target) & 3 /* ClassOrInterface */)) { + return undefined; + } + if (ts.getObjectFlags(type) & 33554432 /* IdenticalBaseTypeCalculated */) { + return ts.getObjectFlags(type) & 67108864 /* IdenticalBaseTypeExists */ ? type.cachedEquivalentBaseType : undefined; + } + type.objectFlags |= 33554432 /* IdenticalBaseTypeCalculated */; + var target = type.target; + var bases = getBaseTypes(target); + if (bases.length !== 1) { + return undefined; + } + if (getMembersOfSymbol(type.symbol).size) { + return undefined; // If the interface has any members, they may subtype members in the base, so we should do a full structural comparison + } + var instantiatedBase = !ts.length(target.typeParameters) ? bases[0] : instantiateType(bases[0], createTypeMapper(target.typeParameters, getTypeArguments(type).slice(0, target.typeParameters.length))); + if (ts.length(getTypeArguments(type)) > ts.length(target.typeParameters)) { + instantiatedBase = getTypeWithThisArgument(instantiatedBase, ts.last(getTypeArguments(type))); + } + type.objectFlags |= 67108864 /* IdenticalBaseTypeExists */; + return type.cachedEquivalentBaseType = instantiatedBase; + } function isEmptyArrayLiteralType(type) { - var elementType = isArrayType(type) ? getTypeArguments(type)[0] : undefined; - return elementType === undefinedWideningType || elementType === implicitNeverType; + var elementType = getElementTypeOfArrayType(type); + return strictNullChecks ? elementType === implicitNeverType : elementType === undefinedWideningType; } function isTupleLikeType(type) { return isTupleType(type) || !!getPropertyOfType(type, "0"); @@ -61498,6 +63259,13 @@ var ts; function isUnitType(type) { return !!(type.flags & 109440 /* Unit */); } + function isUnitLikeType(type) { + return type.flags & 2097152 /* Intersection */ ? ts.some(type.types, isUnitType) : + !!(type.flags & 109440 /* Unit */); + } + function extractUnitType(type) { + return type.flags & 2097152 /* Intersection */ ? ts.find(type.types, isUnitType) || type : type; + } function isLiteralType(type) { return type.flags & 16 /* Boolean */ ? true : type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : @@ -61505,7 +63273,7 @@ var ts; } function getBaseTypeOfLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ ? stringType : + type.flags & 128 /* StringLiteral */ ? stringType : type.flags & 256 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : @@ -61514,7 +63282,7 @@ var ts; } function getWidenedLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : @@ -61648,14 +63416,17 @@ var ts; return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { + // First reduce away any constituents that are assignable to 'undefined' or 'null'. This not only eliminates + // 'undefined' and 'null', but also higher-order types such as a type parameter 'U extends undefined | null' + // that isn't eliminated by a NonNullable instantiation. + var reducedType = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); if (!deferredGlobalNonNullableTypeAlias) { deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; } - // Use NonNullable global type alias if available to improve quick info/declaration emit - if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { - return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); - } - return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior + // If the NonNullable type is available, return an instantiation. Otherwise just return the reduced type. + return deferredGlobalNonNullableTypeAlias !== unknownSymbol ? + getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [reducedType]) : + reducedType; } function getNonNullableType(type) { return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; @@ -61708,7 +63479,7 @@ var ts; function isObjectTypeWithInferableIndex(type) { return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 && - !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */); @@ -61741,7 +63512,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 16384 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -61752,7 +63523,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags; - regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */; + regularNew.objectFlags |= resolved.objectFlags & ~16384 /* FreshLiteral */; type.regularType = regularNew; return regularNew; } @@ -61782,7 +63553,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { var t = _a[_i]; - if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 4194304 /* ContainsSpread */)) { for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { var prop = _c[_b]; names.set(prop.escapedName, prop); @@ -61831,14 +63602,14 @@ var ts; var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); - result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening + result.objectFlags |= (ts.getObjectFlags(type) & (8192 /* JSLiteral */ | 524288 /* NonInferrableType */)); // Retain js literal flag through widening return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, /*context*/ undefined); } function getWidenedTypeWithContext(type, context) { - if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) { + if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) { if (context === undefined && type.widened) { return type.widened; } @@ -61883,7 +63654,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) { if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -61909,7 +63680,7 @@ var ts; for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -61928,12 +63699,12 @@ var ts; } var diagnostic; switch (declaration.kind) { - case 216 /* BinaryExpression */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 217 /* BinaryExpression */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 160 /* Parameter */: + case 161 /* Parameter */: var param = declaration; if (ts.isIdentifier(param.name) && (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && @@ -61948,23 +63719,23 @@ var ts; noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; if (!noImplicitAny) { // Don't issue a suggestion for binding elements since the codefix doesn't yet support them. return; } break; - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: if (noImplicitAny && !declaration.name) { if (wideningKind === 3 /* GeneratorYield */) { error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString); @@ -61978,7 +63749,7 @@ var ts; wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; - case 190 /* MappedType */: + case 191 /* MappedType */: if (noImplicitAny) { error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); } @@ -61989,7 +63760,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -62105,23 +63876,23 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) { - return !!(objectFlags & 134217728 /* CouldContainTypeVariables */); + if (objectFlags & 1048576 /* CouldContainTypeVariablesComputed */) { + return !!(objectFlags & 2097152 /* CouldContainTypeVariables */); } var result = !!(type.flags & 465829888 /* Instantiable */ || type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || - objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) || + objectFlags & (32 /* Mapped */ | 1024 /* ReverseMapped */ | 8388608 /* ObjectRestType */)) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables)); if (type.flags & 3899393 /* ObjectFlagsType */) { - type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0); + type.objectFlags |= 1048576 /* CouldContainTypeVariablesComputed */ | (result ? 2097152 /* CouldContainTypeVariables */ : 0); } return result; } function isNonGenericTopLevelType(type) { if (type.aliasSymbol && !type.aliasTypeArguments) { - var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 254 /* TypeAliasDeclaration */); - return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 297 /* SourceFile */ ? true : n.kind === 256 /* ModuleDeclaration */ ? false : "quit"; })); + var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 255 /* TypeAliasDeclaration */); + return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 298 /* SourceFile */ ? true : n.kind === 257 /* ModuleDeclaration */ ? false : "quit"; })); } return false; } @@ -62174,7 +63945,7 @@ var ts; // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive // arrow function, but is considered partially inferable because property 'a' has an inferable type. function isPartiallyInferableType(type) { - return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) || + return !(ts.getObjectFlags(type) & 524288 /* NonInferrableType */) || isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }) || isTupleType(type) && ts.some(getTypeArguments(type), isPartiallyInferableType); } @@ -62198,14 +63969,18 @@ var ts; } // For all other object types we infer a new object type where the reverse mapping has been // applied to the type of each property. - var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); + var reversed = createObjectType(1024 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + return links.type; } function inferReverseMappedType(sourceType, target, constraint) { var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); @@ -62297,51 +64072,113 @@ var ts; // * it does not contain a numeric seperator (the `BigInt` constructor does not accept a numeric seperator in its input) return success && result === 9 /* BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* ContainsSeparator */); } - function isStringLiteralTypeValueParsableAsType(s, target) { - if (target.flags & 1048576 /* Union */) { - return !!forEachType(target, function (t) { return isStringLiteralTypeValueParsableAsType(s, t); }); - } - switch (target) { - case stringType: return true; - case numberType: return s.value !== "" && isFinite(+(s.value)); - case bigintType: return s.value !== "" && isValidBigIntString(s.value); - // the next 4 should be handled in `getTemplateLiteralType`, as they are all exactly one value, but are here for completeness, just in case - // this function is ever used on types which don't come from template literal holes - case trueType: return s.value === "true"; - case falseType: return s.value === "false"; - case undefinedType: return s.value === "undefined"; - case nullType: return s.value === "null"; - default: return !!(target.flags & 1 /* Any */); - } - } - function inferLiteralsFromTemplateLiteralType(source, target) { - var value = source.value; - var texts = target.texts; - var lastIndex = texts.length - 1; - var startText = texts[0]; - var endText = texts[lastIndex]; - if (!(value.startsWith(startText) && value.slice(startText.length).endsWith(endText))) + function isValidTypeForTemplateLiteralPlaceholder(source, target) { + if (source === target || target.flags & (1 /* Any */ | 4 /* String */)) { + return true; + } + if (source.flags & 128 /* StringLiteral */) { + var value = source.value; + return !!(target.flags & 8 /* Number */ && value !== "" && isFinite(+value) || + target.flags & 64 /* BigInt */ && value !== "" && isValidBigIntString(value) || + target.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) && value === target.intrinsicName); + } + if (source.flags & 134217728 /* TemplateLiteral */) { + var texts = source.texts; + return texts.length === 2 && texts[0] === "" && texts[1] === "" && isTypeAssignableTo(source.types[0], target); + } + return isTypeAssignableTo(source, target); + } + function inferTypesFromTemplateLiteralType(source, target) { + return source.flags & 128 /* StringLiteral */ ? inferFromLiteralPartsToTemplateLiteral([source.value], ts.emptyArray, target) : + source.flags & 134217728 /* TemplateLiteral */ ? + ts.arraysEqual(source.texts, target.texts) ? ts.map(source.types, getStringLikeTypeForType) : + inferFromLiteralPartsToTemplateLiteral(source.texts, source.types, target) : + undefined; + } + function getStringLikeTypeForType(type) { + return type.flags & (1 /* Any */ | 402653316 /* StringLike */) ? type : getTemplateLiteralType(["", ""], [type]); + } + // This function infers from the text parts and type parts of a source literal to a target template literal. The number + // of text parts is always one more than the number of type parts, and a source string literal is treated as a source + // with one text part and zero type parts. The function returns an array of inferred string or template literal types + // corresponding to the placeholders in the target template literal, or undefined if the source doesn't match the target. + // + // We first check that the starting source text part matches the starting target text part, and that the ending source + // text part ends matches the ending target text part. We then iterate through the remaining target text parts, finding + // a match for each in the source and inferring string or template literal types created from the segments of the source + // that occur between the matches. During this iteration, seg holds the index of the current text part in the sourceTexts + // array and pos holds the current character position in the current text part. + // + // Consider inference from type `<<${string}>.<${number}-${number}>>` to type `<${string}.${string}>`, i.e. + // sourceTexts = ['<<', '>.<', '-', '>>'] + // sourceTypes = [string, number, number] + // target.texts = ['<', '.', '>'] + // We first match '<' in the target to the start of '<<' in the source and '>' in the target to the end of '>>' in + // the source. The first match for the '.' in target occurs at character 1 in the source text part at index 1, and thus + // the first inference is the template literal type `<${string}>`. The remainder of the source makes up the second + // inference, the template literal type `<${number}-${number}>`. + function inferFromLiteralPartsToTemplateLiteral(sourceTexts, sourceTypes, target) { + var lastSourceIndex = sourceTexts.length - 1; + var sourceStartText = sourceTexts[0]; + var sourceEndText = sourceTexts[lastSourceIndex]; + var targetTexts = target.texts; + var lastTargetIndex = targetTexts.length - 1; + var targetStartText = targetTexts[0]; + var targetEndText = targetTexts[lastTargetIndex]; + if (lastSourceIndex === 0 && sourceStartText.length < targetStartText.length + targetEndText.length || + !sourceStartText.startsWith(targetStartText) || !sourceEndText.endsWith(targetEndText)) return undefined; + var remainingEndText = sourceEndText.slice(0, sourceEndText.length - targetEndText.length); var matches = []; - var str = value.slice(startText.length, value.length - endText.length); - var pos = 0; - for (var i = 1; i < lastIndex; i++) { - var delim = texts[i]; - var delimPos = delim.length > 0 ? str.indexOf(delim, pos) : pos < str.length ? pos + 1 : -1; - if (delimPos < 0) + var seg = 0; + var pos = targetStartText.length; + for (var i = 1; i < lastTargetIndex; i++) { + var delim = targetTexts[i]; + if (delim.length > 0) { + var s = seg; + var p = pos; + while (true) { + p = getSourceText(s).indexOf(delim, p); + if (p >= 0) + break; + s++; + if (s === sourceTexts.length) + return undefined; + p = 0; + } + addMatch(s, p); + pos += delim.length; + } + else if (pos < getSourceText(seg).length) { + addMatch(seg, pos + 1); + } + else if (seg < lastSourceIndex) { + addMatch(seg + 1, 0); + } + else { return undefined; - matches.push(getLiteralType(str.slice(pos, delimPos))); - pos = delimPos + delim.length; + } } - matches.push(getLiteralType(str.slice(pos))); + addMatch(lastSourceIndex, getSourceText(lastSourceIndex).length); return matches; + function getSourceText(index) { + return index < lastSourceIndex ? sourceTexts[index] : remainingEndText; + } + function addMatch(s, p) { + var matchType = s === seg ? + getLiteralType(getSourceText(s).slice(pos, p)) : + getTemplateLiteralType(__spreadArray(__spreadArray([sourceTexts[seg].slice(pos)], sourceTexts.slice(seg + 1, s)), [getSourceText(s).slice(0, p)]), sourceTypes.slice(seg, s)); + matches.push(matchType); + seg = s; + pos = p; + } } function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) { if (priority === void 0) { priority = 0; } if (contravariant === void 0) { contravariant = false; } var bivariant = false; var propagationType; - var inferencePriority = 1024 /* MaxValue */; + var inferencePriority = 2048 /* MaxValue */; var allowComplexConstraintInference = true; var visited; var sourceStack; @@ -62428,8 +64265,8 @@ var ts; // not contain anyFunctionType when we come back to this argument for its second round // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard // when constructing types from type parameters that had no inference candidates). - if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || - (priority & 64 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || + (priority & 128 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); @@ -62456,7 +64293,7 @@ var ts; clearCachedInferences(inferences); } } - if (!(priority & 64 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 128 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; clearCachedInferences(inferences); } @@ -62496,7 +64333,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - inferWithPriority(empty, target.type, 128 /* LiteralKeyof */); + inferWithPriority(empty, target.type, 256 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -62508,6 +64345,13 @@ var ts; inferFromTypes(source.type, target.type); } } + else if (source.flags & 33554432 /* Substitution */) { + inferFromTypes(source.baseType, target); + var oldPriority = priority; + priority |= 4 /* SubstituteSource */; + inferFromTypes(source.substitute, target); // Make substitute inference at a lower priority + priority = oldPriority; + } else if (target.flags & 16777216 /* Conditional */) { invokeOnce(source, target, inferToConditionalType); } @@ -62527,7 +64371,7 @@ var ts; } else { source = getReducedType(source); - if (!(priority & 256 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { + if (!(priority & 512 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { var apparentSource = getApparentType(source); // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` @@ -62565,26 +64409,22 @@ var ts; } (visited || (visited = new ts.Map())).set(key, -1 /* Circularity */); var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; // We stop inferring and report a circularity if we encounter duplicate recursion identities on both // the source side and the target side. var saveExpandingFlags = expandingFlags; - var sourceIdentity = getRecursionIdentity(source) || source; - var targetIdentity = getRecursionIdentity(target) || target; - if (sourceIdentity && ts.contains(sourceStack, sourceIdentity)) + var sourceIdentity = getRecursionIdentity(source); + var targetIdentity = getRecursionIdentity(target); + if (ts.contains(sourceStack, sourceIdentity)) expandingFlags |= 1 /* Source */; - if (targetIdentity && ts.contains(targetStack, targetIdentity)) + if (ts.contains(targetStack, targetIdentity)) expandingFlags |= 2 /* Target */; if (expandingFlags !== 3 /* Both */) { - if (sourceIdentity) - (sourceStack || (sourceStack = [])).push(sourceIdentity); - if (targetIdentity) - (targetStack || (targetStack = [])).push(targetIdentity); + (sourceStack || (sourceStack = [])).push(sourceIdentity); + (targetStack || (targetStack = [])).push(targetIdentity); action(source, target); - if (targetIdentity) - targetStack.pop(); - if (sourceIdentity) - sourceStack.pop(); + targetStack.pop(); + sourceStack.pop(); } else { inferencePriority = -1 /* Circularity */; @@ -62624,7 +64464,7 @@ var ts; } } function inferFromContravariantTypes(source, target) { - if (strictFunctionTypes || priority & 512 /* AlwaysStrict */) { + if (strictFunctionTypes || priority & 1024 /* AlwaysStrict */) { contravariant = !contravariant; inferFromTypes(source, target); contravariant = !contravariant; @@ -62676,7 +64516,7 @@ var ts; else { for (var i = 0; i < sources.length; i++) { var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; inferFromTypes(sources[i], t); if (inferencePriority === priority) matched_1[i] = true; @@ -62755,9 +64595,9 @@ var ts; // We assign a lower priority to inferences made from types containing non-inferrable // types because we may only have a partial result (i.e. we may have failed to make // reverse inferences for some properties). - inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ? - 8 /* PartialHomomorphicMappedType */ : - 4 /* HomomorphicMappedType */); + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 524288 /* NonInferrableType */ ? + 16 /* PartialHomomorphicMappedType */ : + 8 /* HomomorphicMappedType */); } } return true; @@ -62765,7 +64605,7 @@ var ts; if (constraintType.flags & 262144 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type // parameter. First infer from 'keyof S' to K. - inferWithPriority(getIndexType(source), constraintType, 16 /* MappedTypeConstraint */); + inferWithPriority(getIndexType(source), constraintType, 32 /* MappedTypeConstraint */); // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X }, // where K extends keyof T, we make the same inferences as for a homomorphic mapped type // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a @@ -62794,16 +64634,14 @@ var ts; } else { var savePriority = priority; - priority |= contravariant ? 32 /* ContravariantConditional */ : 0; + priority |= contravariant ? 64 /* ContravariantConditional */ : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; inferToMultipleTypes(source, targetTypes, target.flags); priority = savePriority; } } function inferToTemplateLiteralType(source, target) { - var matches = source.flags & 128 /* StringLiteral */ ? inferLiteralsFromTemplateLiteralType(source, target) : - source.flags & 134217728 /* TemplateLiteral */ && ts.arraysEqual(source.texts, target.texts) ? source.types : - undefined; + var matches = inferTypesFromTemplateLiteralType(source, target); var types = target.types; for (var i = 0; i < types.length; i++) { inferFromTypes(matches ? matches[i] : neverType, types[i]); @@ -62919,7 +64757,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */); + var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* NonInferrableType */); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -62929,7 +64767,7 @@ var ts; 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 === 165 /* MethodDeclaration */ || kind === 164 /* MethodSignature */ || kind === 166 /* Constructor */; + bivariant = bivariant || kind === 166 /* MethodDeclaration */ || kind === 165 /* MethodSignature */ || kind === 167 /* Constructor */; applyToParameterTypes(source, target, inferFromContravariantTypes); bivariant = saveBivariant; } @@ -62956,7 +64794,7 @@ var ts; } } function isTypeOrBaseIdenticalTo(s, t) { - return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 134217856 /* StringLikeLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); + return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); } function isTypeCloselyMatchedBy(s, t) { return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol || @@ -62970,7 +64808,7 @@ var ts; return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); } function isObjectOrArrayLiteralType(type) { - return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */)); + return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 32768 /* ArrayLiteral */)); } function unionObjectAndArrayLiteralCandidates(candidates) { if (candidates.length > 1) { @@ -62983,7 +64821,7 @@ var ts; return candidates; } function getContravariantInference(inference) { - return inference.priority & 208 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + return inference.priority & 416 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } function getCovariantInference(inference, signature) { // Extract all object and array literal types and replace them with a single widened and normalized type. @@ -63000,7 +64838,7 @@ var ts; candidates; // If all inferences were made from a position that implies a combined result, infer a union type. // Otherwise, infer a common supertype. - var unwidenedType = inference.priority & 208 /* PriorityImpliesCombination */ ? + var unwidenedType = inference.priority & 416 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -63109,7 +64947,7 @@ var ts; case "BigUint64Array": return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later; default: - if (node.parent.kind === 289 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 290 /* ShorthandPropertyAssignment */) { return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer; } else { @@ -63130,26 +64968,24 @@ var ts; // TypeScript 1.0 spec (April 2014): 3.6.3 // A type query consists of the keyword typeof followed by an expression. // The expression is restricted to a single identifier or a sequence of identifiers separated by periods - return !!ts.findAncestor(node, function (n) { return n.kind === 176 /* TypeQuery */ ? true : n.kind === 78 /* Identifier */ || n.kind === 157 /* QualifiedName */ ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 177 /* TypeQuery */ ? true : n.kind === 78 /* Identifier */ || n.kind === 158 /* QualifiedName */ ? false : "quit"; }); } // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the // leftmost identifier followed by zero or more property names separated by dots. - // The result is undefined if the reference isn't a dotted name. We prefix nodes - // occurring in an apparent type position with '@' because the control flow type - // of such nodes may be based on the apparent type instead of the declared type. + // The result is undefined if the reference isn't a dotted name. function getFlowCacheKey(node, declaredType, initialType, flowContainer) { switch (node.kind) { case 78 /* Identifier */: var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; case 107 /* ThisKeyword */: return "0|" + (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType); - case 225 /* NonNullExpression */: - case 207 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: var propName = getAccessedPropertyName(node); if (propName !== undefined) { var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); @@ -63160,32 +64996,40 @@ var ts; } function isMatchingReference(source, target) { switch (target.kind) { - case 207 /* ParenthesizedExpression */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: return isMatchingReference(source, target.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return (ts.isAssignmentExpression(target) && isMatchingReference(source, target.left)) || (ts.isBinaryExpression(target) && target.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source, target.right)); } switch (source.kind) { + case 227 /* MetaProperty */: + return target.kind === 227 /* MetaProperty */ + && source.keywordToken === target.keywordToken + && source.name.escapedText === target.name.escapedText; case 78 /* Identifier */: case 79 /* PrivateIdentifier */: return target.kind === 78 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 249 /* VariableDeclaration */ || target.kind === 198 /* BindingElement */) && + (target.kind === 250 /* VariableDeclaration */ || target.kind === 199 /* BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); case 107 /* ThisKeyword */: return target.kind === 107 /* ThisKeyword */; case 105 /* SuperKeyword */: return target.kind === 105 /* SuperKeyword */; - case 225 /* NonNullExpression */: - case 207 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: return isMatchingReference(source.expression, target); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return ts.isAccessExpression(target) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 216 /* BinaryExpression */: + case 158 /* QualifiedName */: + return ts.isAccessExpression(target) && + source.right.escapedText === getAccessedPropertyName(target) && + isMatchingReference(source.left, target.expression); + case 217 /* BinaryExpression */: return (ts.isBinaryExpression(source) && source.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source.right, target)); } return false; @@ -63193,11 +65037,11 @@ var ts; // Given a source x, check if target matches x or is an && operation with an operand that matches x. function containsTruthyCheck(source, target) { return isMatchingReference(source, target) || - (target.kind === 216 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && + (target.kind === 217 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (containsTruthyCheck(source, target.left) || containsTruthyCheck(source, target.right))); } function getAccessedPropertyName(access) { - return access.kind === 201 /* PropertyAccessExpression */ ? access.name.escapedText : + return access.kind === 202 /* PropertyAccessExpression */ ? access.name.escapedText : ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : undefined; } @@ -63247,6 +65091,86 @@ var ts; } return result; } + // Given a set of constituent types and a property name, create and return a map keyed by the literal + // types of the property by that name in each constituent type. No map is returned if some key property + // has a non-literal type or if less than 10 or less than 50% of the constituents have a unique key. + // Entries with duplicate keys have unknownType as the value. + function mapTypesByKeyProperty(types, name) { + var map = new ts.Map(); + var count = 0; + var _loop_20 = function (type) { + if (type.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */)) { + var discriminant = getTypeOfPropertyOfType(type, name); + if (discriminant) { + if (!isLiteralType(discriminant)) { + return { value: undefined }; + } + var duplicate_1 = false; + forEachType(discriminant, function (t) { + var id = getTypeId(getRegularTypeOfLiteralType(t)); + var existing = map.get(id); + if (!existing) { + map.set(id, type); + } + else if (existing !== unknownType) { + map.set(id, unknownType); + duplicate_1 = true; + } + }); + if (!duplicate_1) + count++; + } + } + }; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; + var state_8 = _loop_20(type); + if (typeof state_8 === "object") + return state_8.value; + } + return count >= 10 && count * 2 >= types.length ? map : undefined; + } + // Return the name of a discriminant property for which it was possible and feasible to construct a map of + // constituent types keyed by the literal types of the property by that name in each constituent type. + function getKeyPropertyName(unionType) { + var types = unionType.types; + // We only construct maps for large unions with non-primitive constituents. + if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */) { + return undefined; + } + if (unionType.keyPropertyName === undefined) { + // The candidate key property name is the name of the first property with a unit type in one of the + // constituent types. + var keyPropertyName = ts.forEach(types, function (t) { + return t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ? + ts.forEach(getPropertiesOfType(t), function (p) { return isUnitType(getTypeOfSymbol(p)) ? p.escapedName : undefined; }) : + undefined; + }); + var mapByKeyProperty = keyPropertyName && mapTypesByKeyProperty(types, keyPropertyName); + unionType.keyPropertyName = mapByKeyProperty ? keyPropertyName : ""; + unionType.constituentMap = mapByKeyProperty; + } + return unionType.keyPropertyName.length ? unionType.keyPropertyName : undefined; + } + // Given a union type for which getKeyPropertyName returned a non-undefined result, return the constituent + // that corresponds to the given key type for that property name. + function getConstituentTypeForKeyType(unionType, keyType) { + var _a; + var result = (_a = unionType.constituentMap) === null || _a === void 0 ? void 0 : _a.get(getTypeId(getRegularTypeOfLiteralType(keyType))); + return result !== unknownType ? result : undefined; + } + function getMatchingUnionConstituentForType(unionType, type) { + var keyPropertyName = getKeyPropertyName(unionType); + var propType = keyPropertyName && getTypeOfPropertyOfType(type, keyPropertyName); + return propType && getConstituentTypeForKeyType(unionType, propType); + } + function getMatchingUnionConstituentForObjectLiteral(unionType, node) { + var keyPropertyName = getKeyPropertyName(unionType); + var propNode = keyPropertyName && ts.find(node.properties, function (p) { return p.symbol && p.kind === 289 /* PropertyAssignment */ && + p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer); }); + var propType = propNode && getTypeOfExpression(propNode.initializer); + return propType && getConstituentTypeForKeyType(unionType, propType); + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -63259,7 +65183,7 @@ var ts; } } } - if (expression.expression.kind === 201 /* PropertyAccessExpression */ && + if (expression.expression.kind === 202 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, expression.expression.expression)) { return true; } @@ -63306,14 +65230,6 @@ var ts; } return declaredType; } - function getTypeFactsOfTypes(types) { - var result = 0 /* None */; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; - result |= getTypeFacts(t); - } - return result; - } function isFunctionObjectType(type) { // We do a quick check for a "bind" property before performing the more expensive subtype // check. This gives us a quicker out in the common case where an object type is not a function. @@ -63321,7 +65237,8 @@ var ts; return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type) { + function getTypeFacts(type, ignoreObjects) { + if (ignoreObjects === void 0) { ignoreObjects = false; } var flags = type.flags; if (flags & 4 /* String */) { return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; @@ -63358,7 +65275,7 @@ var ts; (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } - if (flags & 524288 /* Object */) { + if (flags & 524288 /* Object */ && !ignoreObjects) { return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : isFunctionObjectType(type) ? @@ -63381,11 +65298,17 @@ var ts; return 0 /* None */; } if (flags & 465829888 /* Instantiable */) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType) : + return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : strictNullChecks ? 7929345 /* NonEmptyStringStrictFacts */ : 16776705 /* NonEmptyStringFacts */; } - if (flags & 3145728 /* UnionOrIntersection */) { - return getTypeFactsOfTypes(type.types); + if (flags & 1048576 /* Union */) { + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0 /* None */); + } + if (flags & 2097152 /* Intersection */) { + // When an intersection contains a primitive type we ignore object type constituents as they are + // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. + ignoreObjects || (ignoreObjects = maybeTypeOfKind(type, 131068 /* Primitive */)); + return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t, ignoreObjects); }, 16777215 /* All */); } return 16777215 /* All */; } @@ -63393,18 +65316,16 @@ var ts; return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { - if (defaultExpression) { - var defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]); - } - return type; + return defaultExpression ? + getUnionType([getNonUndefinedType(type), getTypeOfExpression(defaultExpression)]) : + type; } function getTypeOfDestructuredProperty(type, name) { var nameType = getLiteralTypeFromPropertyName(name); if (!isTypeUsableAsPropertyName(nameType)) return errorType; var text = getPropertyNameFromType(nameType); - return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || + return getTypeOfPropertyOfType(type, text) || isNumericLiteralName(text) && includeUndefinedInIndexSignature(getIndexTypeOfType(type, 1 /* Number */)) || includeUndefinedInIndexSignature(getIndexTypeOfType(type, 0 /* String */)) || errorType; @@ -63425,15 +65346,15 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) || errorType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 199 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 288 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 200 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 289 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 216 /* BinaryExpression */ && parent.parent.left === parent || - parent.parent.kind === 239 /* ForOfStatement */ && parent.parent.initializer === parent; + return parent.parent.kind === 217 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 240 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); @@ -63450,21 +65371,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return stringType; - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return checkRightHandSideOfForOf(parent) || errorType; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return undefinedType; - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return getAssignedTypeOfSpreadExpression(parent); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return errorType; @@ -63472,7 +65393,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 196 /* ObjectBindingPattern */ ? + var type = pattern.kind === 197 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : @@ -63490,30 +65411,30 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 238 /* ForInStatement */) { + if (node.parent.parent.kind === 239 /* ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 239 /* ForOfStatement */) { + if (node.parent.parent.kind === 240 /* ForOfStatement */) { return checkRightHandSideOfForOf(node.parent.parent) || errorType; } return errorType; } function getInitialType(node) { - return node.kind === 249 /* VariableDeclaration */ ? + return node.kind === 250 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function isEmptyArrayAssignment(node) { - return node.kind === 249 /* VariableDeclaration */ && node.initializer && + return node.kind === 250 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 198 /* BindingElement */ && node.parent.kind === 216 /* BinaryExpression */ && + node.kind !== 199 /* BindingElement */ && node.parent.kind === 217 /* BinaryExpression */ && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (node.operatorToken.kind) { case 62 /* EqualsToken */: case 74 /* BarBarEqualsToken */: @@ -63528,13 +65449,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 207 /* ParenthesizedExpression */ || - parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node || - parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? + return parent.kind === 208 /* ParenthesizedExpression */ || + parent.kind === 217 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node || + parent.kind === 217 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 284 /* CaseClause */) { + if (clause.kind === 285 /* CaseClause */) { return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); } return neverType; @@ -63554,7 +65475,7 @@ var ts; var witnesses = []; for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { var clause = _a[_i]; - if (clause.kind === 284 /* CaseClause */) { + if (clause.kind === 285 /* CaseClause */) { if (ts.isStringLiteralLike(clause.expression)) { witnesses.push(clause.expression.text); continue; @@ -63590,14 +65511,40 @@ var ts; function forEachType(type, f) { return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type); } + function someType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.some(type.types, f) : f(type); + } function everyType(type, f) { return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); } + function everyContainedType(type, f) { + return type.flags & 3145728 /* UnionOrIntersection */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 1048576 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); + if (filtered === types) { + return type; + } + var origin = type.origin; + var newOrigin = void 0; + if (origin && origin.flags & 1048576 /* Union */) { + // If the origin type is a (denormalized) union type, filter its non-union constituents. If that ends + // up removing a smaller number of types than in the normalized constituent set (meaning some of the + // filtered types are within nested unions in the origin), then we can't construct a new origin type. + // Otherwise, if we have exactly one type left in the origin set, return that as the filtered type. + // Otherwise, construct a new filtered origin type. + var originTypes = origin.types; + var originFiltered = ts.filter(originTypes, function (t) { return !!(t.flags & 1048576 /* Union */) || f(t); }); + if (originTypes.length - originFiltered.length === types.length - filtered.length) { + if (originFiltered.length === 1) { + return originFiltered[0]; + } + newOrigin = createOriginUnionOrIntersectionType(1048576 /* Union */, originFiltered); + } + } + return getUnionTypeFromSortedList(filtered, type.objectFlags, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, newOrigin); } return type.flags & 131072 /* Never */ || f(type) ? type : neverType; } @@ -63630,6 +65577,11 @@ var ts; } return changed ? mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : type; } + function mapTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) { + return type.flags & 1048576 /* Union */ && aliasSymbol ? + getUnionType(ts.map(type.types, mapper), 1 /* Literal */, aliasSymbol, aliasTypeArguments) : + mapType(type, mapper); + } function getConstituentCount(type) { return type.flags & 3145728 /* UnionOrIntersection */ ? type.types.length : 1; } @@ -63715,12 +65667,12 @@ var ts; var root = getReferenceRoot(node); var parent = root.parent; var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" || - parent.parent.kind === 203 /* CallExpression */ + parent.parent.kind === 204 /* CallExpression */ && ts.isIdentifier(parent.name) && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 202 /* ElementAccessExpression */ && + var isElementAssignment = parent.kind === 203 /* ElementAccessExpression */ && parent.expression === root && - parent.parent.kind === 216 /* BinaryExpression */ && + parent.parent.kind === 217 /* BinaryExpression */ && parent.parent.operatorToken.kind === 62 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && @@ -63728,8 +65680,8 @@ var ts; return isLengthPushOrUnshift || isElementAssignment; } function isDeclarationWithExplicitTypeAnnotation(declaration) { - return (declaration.kind === 249 /* VariableDeclaration */ || declaration.kind === 160 /* Parameter */ || - declaration.kind === 163 /* PropertyDeclaration */ || declaration.kind === 162 /* PropertySignature */) && + return (declaration.kind === 250 /* VariableDeclaration */ || declaration.kind === 161 /* Parameter */ || + declaration.kind === 164 /* PropertyDeclaration */ || declaration.kind === 163 /* PropertySignature */) && !!ts.getEffectiveTypeAnnotationNode(declaration); } function getExplicitTypeOfSymbol(symbol, diagnostic) { @@ -63748,7 +65700,7 @@ var ts; if (isDeclarationWithExplicitTypeAnnotation(declaration)) { return getTypeOfSymbol(symbol); } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 240 /* ForOfStatement */) { var statement = declaration.parent.parent; var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined); if (expressionType) { @@ -63776,11 +65728,25 @@ var ts; return getExplicitThisType(node); case 105 /* SuperKeyword */: return checkSuperExpression(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: { var type = getTypeOfDottedName(node.expression, diagnostic); - var prop = type && getPropertyOfType(type, node.name.escapedText); - return prop && getExplicitTypeOfSymbol(prop, diagnostic); - case 207 /* ParenthesizedExpression */: + if (type) { + var name = node.name; + var prop = void 0; + if (ts.isPrivateIdentifier(name)) { + if (!type.symbol) { + return undefined; + } + prop = getPropertyOfType(type, ts.getSymbolNameForPrivateIdentifier(type.symbol, name.escapedText)); + } + else { + prop = getPropertyOfType(type, name.escapedText); + } + return prop && getExplicitTypeOfSymbol(prop, diagnostic); + } + return undefined; + } + case 208 /* ParenthesizedExpression */: return getTypeOfDottedName(node.expression, diagnostic); } } @@ -63794,7 +65760,7 @@ var ts; // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call // target expression of an assertion. var funcType = void 0; - if (node.parent.kind === 233 /* ExpressionStatement */) { + if (node.parent.kind === 234 /* ExpressionStatement */) { funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined); } else if (node.expression.kind !== 105 /* SuperKeyword */) { @@ -63838,7 +65804,7 @@ var ts; } function isFalseExpression(expr) { var node = ts.skipParentheses(expr); - return node.kind === 94 /* FalseKeyword */ || node.kind === 216 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + return node.kind === 94 /* FalseKeyword */ || node.kind === 217 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); } function isReachableFlowNodeWorker(flow, noCacheCheck) { @@ -63973,7 +65939,7 @@ var ts; // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); - if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 225 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { + if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 226 /* NonNullExpression */ && !(resultType.flags & 131072 /* Never */) && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { return declaredType; } return resultType; @@ -63988,7 +65954,7 @@ var ts; 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. - ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); flowAnalysisDisabled = true; reportFlowControlError(reference); return errorType; @@ -64057,8 +66023,8 @@ var ts; // Check if we should continue with the control flow of the containing function. var container = flow.node; if (container && container !== flowContainer && - reference.kind !== 201 /* PropertyAccessExpression */ && - reference.kind !== 202 /* ElementAccessExpression */ && + reference.kind !== 202 /* PropertyAccessExpression */ && + reference.kind !== 203 /* ElementAccessExpression */ && reference.kind !== 107 /* ThisKeyword */) { flow = container.flowNode; continue; @@ -64083,7 +66049,7 @@ var ts; } function getInitialOrAssignedType(flow) { var node = flow.node; - return getConstraintForLocation(node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */ ? + return getNarrowableTypeForReference(node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */ ? getInitialType(node) : getAssignedType(node), reference); } @@ -64123,14 +66089,14 @@ var ts; // 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 === 208 /* FunctionExpression */ || init.kind === 209 /* ArrowFunction */)) { + if (init && (init.kind === 209 /* FunctionExpression */ || init.kind === 210 /* ArrowFunction */)) { return getTypeAtFlowNode(flow.antecedent); } } return declaredType; } // for (const _ in ref) acts as a nonnull on ref - if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 238 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 239 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); } // Assignment doesn't affect reference @@ -64141,7 +66107,7 @@ var ts; if (node.kind === 94 /* FalseKeyword */) { return unreachableNeverType; } - if (node.kind === 216 /* BinaryExpression */) { + if (node.kind === 217 /* BinaryExpression */) { if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); } @@ -64172,7 +66138,7 @@ var ts; function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 203 /* CallExpression */ ? + var expr = node.kind === 204 /* CallExpression */ ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { @@ -64180,7 +66146,7 @@ var ts; var type = getTypeFromFlowType(flowType); if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { var evolvedType_1 = type; - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); @@ -64228,7 +66194,7 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (expr.kind === 211 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + else if (expr.kind === 212 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else { @@ -64236,12 +66202,12 @@ var ts; if (optionalChainContainsReference(expr, reference)) { type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); }); } - else if (expr.kind === 211 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { + else if (expr.kind === 212 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); }); } } if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + type = narrowTypeBySwitchOnDiscriminantProperty(type, expr, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } } return createFlowType(type, isIncomplete(flowType)); @@ -64412,16 +66378,42 @@ var ts; if (propName === undefined) { return type; } - var propType = getTypeOfPropertyOfType(type, propName); + var removeNullable = strictNullChecks && ts.isOptionalChain(access) && maybeTypeOfKind(type, 98304 /* Nullable */); + var propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type, propName); if (!propType) { return type; } + propType = removeNullable ? getOptionalType(propType) : propType; var narrowedPropType = narrowType(propType); return filterType(type, function (t) { var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName); return !(discriminantType.flags & 131072 /* Never */) && isTypeComparableTo(discriminantType, narrowedPropType); }); } + function narrowTypeByDiscriminantProperty(type, access, operator, value, assumeTrue) { + if ((operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) && type.flags & 1048576 /* Union */) { + var keyPropertyName = getKeyPropertyName(type); + if (keyPropertyName && keyPropertyName === getAccessedPropertyName(access)) { + var candidate_2 = getConstituentTypeForKeyType(type, getTypeOfExpression(value)); + if (candidate_2) { + return operator === (assumeTrue ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */) ? candidate_2 : + isUnitType(getTypeOfPropertyOfType(candidate_2, keyPropertyName) || unknownType) ? filterType(type, function (t) { return t !== candidate_2; }) : + type; + } + } + } + return narrowTypeByDiscriminant(type, access, function (t) { return narrowTypeByEquality(t, operator, value, assumeTrue); }); + } + function narrowTypeBySwitchOnDiscriminantProperty(type, access, switchStatement, clauseStart, clauseEnd) { + if (clauseStart < clauseEnd && type.flags & 1048576 /* Union */ && getKeyPropertyName(type) === getAccessedPropertyName(access)) { + var clauseTypes = getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd); + var candidate = getUnionType(ts.map(clauseTypes, function (t) { return getConstituentTypeForKeyType(type, t) || unknownType; })); + if (candidate !== unknownType) { + return candidate; + } + } + return narrowTypeByDiscriminant(type, access, function (t) { return narrowTypeBySwitchOnDiscriminant(t, switchStatement, clauseStart, clauseEnd); }); + } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); @@ -64445,7 +66437,8 @@ var ts; return !assumeTrue; } function narrowByInKeyword(type, literal, assumeTrue) { - if (type.flags & (1048576 /* Union */ | 524288 /* Object */) + if (type.flags & 1048576 /* Union */ + || type.flags & 524288 /* Object */ && declaredType !== type || isThisTypeParameter(type) || type.flags & 2097152 /* Intersection */ && ts.every(type.types, function (t) { return t.symbol !== globalThisSymbol; })) { var propName_1 = ts.escapeLeadingUnderscores(literal.text); @@ -64464,40 +66457,40 @@ var ts; case 35 /* ExclamationEqualsToken */: case 36 /* EqualsEqualsEqualsToken */: case 37 /* ExclamationEqualsEqualsToken */: - var operator_1 = expr.operatorToken.kind; - var left_1 = getReferenceCandidate(expr.left); - var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 211 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { - return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + var operator = expr.operatorToken.kind; + var left = getReferenceCandidate(expr.left); + var right = getReferenceCandidate(expr.right); + if (left.kind === 212 /* TypeOfExpression */ && ts.isStringLiteralLike(right)) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); } - if (right_1.kind === 211 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { - return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + if (right.kind === 212 /* TypeOfExpression */ && ts.isStringLiteralLike(left)) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); } - if (isMatchingReference(reference, left_1)) { - return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + if (isMatchingReference(reference, left)) { + return narrowTypeByEquality(type, operator, right, assumeTrue); } - if (isMatchingReference(reference, right_1)) { - return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + if (isMatchingReference(reference, right)) { + return narrowTypeByEquality(type, operator, left, assumeTrue); } if (strictNullChecks) { - if (optionalChainContainsReference(left_1, reference)) { - type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue); + if (optionalChainContainsReference(left, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator, right, assumeTrue); } - else if (optionalChainContainsReference(right_1, reference)) { - type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); + else if (optionalChainContainsReference(right, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator, left, assumeTrue); } } - if (isMatchingReferenceDiscriminant(left_1, type)) { - return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + if (isMatchingReferenceDiscriminant(left, type)) { + return narrowTypeByDiscriminantProperty(type, left, operator, right, assumeTrue); } - if (isMatchingReferenceDiscriminant(right_1, type)) { - return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + if (isMatchingReferenceDiscriminant(right, type)) { + return narrowTypeByDiscriminantProperty(type, right, operator, left, assumeTrue); } - if (isMatchingConstructorReference(left_1)) { - return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue); + if (isMatchingConstructorReference(left)) { + return narrowTypeByConstructor(type, operator, right, assumeTrue); } - if (isMatchingConstructorReference(right_1)) { - return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue); + if (isMatchingConstructorReference(right)) { + return narrowTypeByConstructor(type, operator, left, assumeTrue); } break; case 101 /* InstanceOfKeyword */: @@ -64562,13 +66555,12 @@ var ts; } if (assumeTrue) { var filterFn = operator === 34 /* EqualsEqualsToken */ ? - (function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); }) : + function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); } : function (t) { return areTypesComparable(t, valueType); }; return replacePrimitivesWithLiterals(filterType(type, filterFn), valueType); } if (isUnitType(valueType)) { - var regularType_1 = getRegularTypeOfLiteralType(valueType); - return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; }); + return filterType(type, function (t) { return !(isUnitLikeType(t) && areTypesComparable(t, valueType)); }); } return type; } @@ -64590,7 +66582,7 @@ var ts; if (assumeTrue && type.flags & 2 /* Unknown */ && literal.text === "object") { // The pattern x && typeof x === 'object', where x is of type unknown, narrows x to type object. We don't // need to check for the reverse typeof x === 'object' && x since that already narrows correctly. - if (typeOfExpr.parent.parent.kind === 216 /* BinaryExpression */) { + if (typeOfExpr.parent.parent.kind === 217 /* BinaryExpression */) { var expr = typeOfExpr.parent.parent; if (expr.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && expr.right === typeOfExpr.parent && containsTruthyCheck(reference, expr.left)) { return nonPrimitiveType; @@ -64646,7 +66638,7 @@ var ts; if (!hasDefaultClause) { return caseType; } - var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + var defaultType = filterType(type, function (t) { return !(isUnitLikeType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(extractUnitType(t)))); }); return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } function getImpliedTypeFromTypeofGuard(type, text) { @@ -64828,7 +66820,16 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { - return filterType(type, function (t) { return !isRelated(t, candidate); }); + return filterType(type, function (t) { + if (!isRelated(t, candidate)) { + return true; + } + var constraint = getBaseConstraintOfType(t); + if (constraint && constraint !== t) { + return !isRelated(constraint, candidate); + } + return false; + }); } // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. @@ -64838,10 +66839,15 @@ var ts; return assignableType; } } - // If the candidate type is a subtype of the target type, narrow to the candidate type, - // if the target type is a subtype of the candidate type, narrow to the target type, - // otherwise, narrow to an intersection of the two types. - return isTypeSubtypeOf(candidate, type) ? candidate : isTypeSubtypeOf(type, candidate) ? type : getIntersectionType([type, candidate]); + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -64884,17 +66890,17 @@ var ts; case 78 /* Identifier */: case 107 /* ThisKeyword */: case 105 /* SuperKeyword */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return narrowTypeByCallExpression(type, expr, assumeTrue); - case 207 /* ParenthesizedExpression */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: return narrowType(type, expr.expression, assumeTrue); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: if (expr.operator === 53 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } @@ -64918,17 +66924,20 @@ var ts; // an dotted name expression, and if the location is not an assignment target, obtain the type // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. - if (location.kind === 78 /* Identifier */) { + if (location.kind === 78 /* Identifier */ || location.kind === 79 /* PrivateIdentifier */) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { + if (ts.isExpressionNode(location) && (!ts.isAssignmentTarget(location) || ts.isWriteAccess(location))) { var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } } } + if (ts.isDeclarationName(location) && ts.isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) { + return resolveTypeOfAccessors(location.parent.symbol, /*writing*/ true); + } // The location isn't a reference to the given symbol, meaning we're being asked // a hypothetical question of what type the symbol would have if there was a reference // to it at the given location. Since we have no control flow information for the @@ -64939,13 +66948,16 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 257 /* ModuleBlock */ || - node.kind === 297 /* SourceFile */ || - node.kind === 163 /* PropertyDeclaration */; + node.kind === 258 /* ModuleBlock */ || + node.kind === 298 /* SourceFile */ || + node.kind === 164 /* PropertyDeclaration */; }); } // Check if a parameter is assigned anywhere within its declaring function. function isParameterAssigned(symbol) { + if (!symbol.valueDeclaration) { + return false; + } var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); if (!(links.flags & 8388608 /* AssignmentsMarked */)) { @@ -64963,7 +66975,7 @@ var ts; if (node.kind === 78 /* Identifier */) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 160 /* Parameter */) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 161 /* Parameter */) { symbol.isAssigned = true; } } @@ -64979,7 +66991,7 @@ var ts; function removeOptionalityFromDeclaredType(declaredType, declaration) { if (pushTypeResolution(declaration.symbol, 2 /* DeclaredType */)) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 160 /* Parameter */ && + declaration.kind === 161 /* Parameter */ && declaration.initializer && getFalsyFlags(declaredType) & 32768 /* Undefined */ && !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */); @@ -64993,23 +67005,40 @@ var ts; } function isConstraintPosition(node) { var parent = node.parent; - return parent.kind === 201 /* PropertyAccessExpression */ || - parent.kind === 203 /* CallExpression */ && parent.expression === node || - parent.kind === 202 /* ElementAccessExpression */ && parent.expression === node || - parent.kind === 198 /* BindingElement */ && parent.name === node && !!parent.initializer; - } - function typeHasNullableConstraint(type) { - return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 98304 /* Nullable */); - } - function getConstraintForLocation(type, node) { - // When a node is the left hand expression of a property access, element access, or call expression, - // and the type of the node includes type variables with constraints that are nullable, we fetch the - // apparent type of the node *before* performing control flow analysis such that narrowings apply to - // the constraint type. - if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { - return mapType(getWidenedType(type), getBaseConstraintOrType); - } - return type; + // In an element access obj[x], we consider obj to be in a constraint position only when x is not + // of a generic type. This is because when both obj and x are of generic types T and K, we want + // the resulting type to be T[K]. + return parent.kind === 202 /* PropertyAccessExpression */ || + parent.kind === 204 /* CallExpression */ && parent.expression === node || + parent.kind === 203 /* ElementAccessExpression */ && parent.expression === node && + !isGenericIndexType(getTypeOfExpression(parent.argumentExpression)); + } + function isGenericTypeWithUnionConstraint(type) { + return !!(type.flags & 465829888 /* Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* Nullable */ | 1048576 /* Union */)); + } + function containsGenericType(type) { + return !!(type.flags & 465829888 /* Instantiable */ || type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, containsGenericType)); + } + function hasContextualTypeWithNoGenericTypes(node) { + // Computing the contextual type for a child of a JSX element involves resolving the type of the + // element's tag name, so we exclude that here to avoid circularities. + var contextualType = (ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && + !((ts.isJsxOpeningElement(node.parent) || ts.isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && + getContextualType(node); + return contextualType && !someType(contextualType, containsGenericType); + } + function getNarrowableTypeForReference(type, reference, checkMode) { + // When the type of a reference is or contains an instantiable type with a union type constraint, and + // when the reference is in a constraint position (where it is known we'll obtain the apparent type) or + // has a contextual type containing no top-level instantiables (meaning constraints will determine + // assignability), we substitute constraints for all instantiables in the type of the reference to give + // control flow analysis an opportunity to narrow it further. For example, for a reference of a type + // parameter type 'T extends string | undefined' with a contextual type 'string', we substitute + // 'string | undefined' to give control flow analysis the opportunity to narrow to type 'string'. + var substituteConstraints = !(checkMode && checkMode & 2 /* Inferential */) && + someType(type, isGenericTypeWithUnionConstraint) && + (isConstraintPosition(reference) || hasContextualTypeWithNoGenericTypes(reference)); + return substituteConstraints ? mapType(type, function (t) { return t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type; } function isExportOrExportExpression(location) { return !!ts.findAncestor(location, function (e) { return e.parent && ts.isExportAssignment(e.parent) && e.parent.expression === e && ts.isEntityNameExpression(e); }); @@ -65018,7 +67047,12 @@ var ts; if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { var target = resolveAlias(symbol); if (target.flags & 111551 /* Value */) { - if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(target)) { + // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled + // (because the const enum value will not be inlined), or if (2) the alias is an export + // of a const enum declaration that will be preserved. + if (compilerOptions.isolatedModules || + ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || + !isConstEnumOrConstEnumOnlyModule(target)) { markAliasSymbolAsReferenced(symbol); } else { @@ -65027,7 +67061,7 @@ var ts; } } } - function checkIdentifier(node) { + function checkIdentifier(node, checkMode) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { return errorType; @@ -65041,7 +67075,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2 /* ES2015 */) { - if (container.kind === 209 /* ArrowFunction */) { + if (container.kind === 210 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasSyntacticModifier(container, 256 /* Async */)) { @@ -65058,15 +67092,15 @@ var ts; } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var sourceSymbol = localOrExportSymbol.flags & 2097152 /* Alias */ ? resolveAlias(localOrExportSymbol) : localOrExportSymbol; - if (getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) { - errorOrSuggestion(/* isError */ false, node, ts.Diagnostics._0_is_deprecated, node.escapedText); + if (sourceSymbol.declarations && getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) { + addDeprecatedSuggestion(node, sourceSymbol.declarations, node.escapedText); } var declaration = localOrExportSymbol.valueDeclaration; - if (localOrExportSymbol.flags & 32 /* Class */) { + if (declaration && localOrExportSymbol.flags & 32 /* Class */) { // 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. - if (declaration.kind === 252 /* ClassDeclaration */ + if (declaration.kind === 253 /* ClassDeclaration */ && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -65078,14 +67112,14 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration.kind === 221 /* ClassExpression */) { + else if (declaration.kind === 222 /* ClassExpression */) { // When we emit a class expression with static members that contain a reference // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container.kind !== 297 /* SourceFile */) { + while (container.kind !== 298 /* SourceFile */) { if (container.parent === declaration) { - if (container.kind === 163 /* PropertyDeclaration */ && ts.hasSyntacticModifier(container, 32 /* Static */)) { + if (container.kind === 164 /* PropertyDeclaration */ && ts.hasSyntacticModifier(container, 32 /* Static */)) { getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } @@ -65096,12 +67130,18 @@ var ts; } } checkNestedBlockScopedBinding(node, symbol); - var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); + var type = getTypeOfSymbol(localOrExportSymbol); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + var assignmentError = localOrExportSymbol.flags & 384 /* Enum */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_an_enum + : localOrExportSymbol.flags & 32 /* Class */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_class + : localOrExportSymbol.flags & 1536 /* Module */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_namespace + : localOrExportSymbol.flags & 16 /* Function */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_function + : localOrExportSymbol.flags & 2097152 /* Alias */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_an_import + : ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable; + error(node, assignmentError, symbolToString(symbol)); return errorType; } if (isReadonlySymbol(localOrExportSymbol)) { @@ -65123,7 +67163,7 @@ var ts; } } else if (isAlias) { - declaration = ts.find(symbol.declarations, isSomeImportDeclaration); + declaration = getDeclarationOfAliasSymbol(symbol); } else { return type; @@ -65131,10 +67171,11 @@ var ts; if (!declaration) { return type; } + type = getNarrowableTypeForReference(type, node, checkMode); // The declaration container is the innermost function that encloses the declaration of the variable // or parameter. The flow container is the innermost function starting with which we analyze the control // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 160 /* Parameter */; + var isParameter = ts.getRootDeclaration(declaration).kind === 161 /* Parameter */; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; @@ -65143,8 +67184,8 @@ var ts; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === 208 /* FunctionExpression */ || - flowContainer.kind === 209 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 209 /* FunctionExpression */ || + flowContainer.kind === 210 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } @@ -65153,9 +67194,9 @@ var ts; // declaration container are the same). var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 || - isInTypeQuery(node) || node.parent.kind === 270 /* ExportSpecifier */) || - node.parent.kind === 225 /* NonNullExpression */ || - declaration.kind === 249 /* VariableDeclaration */ && declaration.exclamationToken || + isInTypeQuery(node) || node.parent.kind === 271 /* ExportSpecifier */) || + node.parent.kind === 226 /* NonNullExpression */ || + declaration.kind === 250 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 8388608 /* Ambient */; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : type === autoType || type === autoArrayType ? undefinedType : @@ -65180,17 +67221,21 @@ var ts; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } - function isInsideFunction(node, threshold) { - return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); + function isInsideFunctionOrInstancePropertyInitializer(node, threshold) { + return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n) || (n.parent && ts.isPropertyDeclaration(n.parent) && !ts.hasStaticModifier(n.parent) && n.parent.initializer === n); }); } 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 getEnclosingIterationStatement(node) { + return ts.findAncestor(node, function (n) { return (!n || ts.nodeStartsNewLexicalEnvironment(n)) ? "quit" : ts.isIterationStatement(n, /*lookInLabeledStatements*/ false); }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || + !symbol.valueDeclaration || ts.isSourceFile(symbol.valueDeclaration) || - symbol.valueDeclaration.parent.kind === 287 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 288 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -65198,22 +67243,14 @@ var ts; // 2. walk from the declaration up to the boundary of lexical environment and check // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - var usedInFunction = isInsideFunction(node.parent, container); - var current = container; - var containedInIterationStatement = false; - while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { - if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) { - containedInIterationStatement = true; - break; - } - current = current.parent; - } - if (containedInIterationStatement) { - if (usedInFunction) { + var isCaptured = isInsideFunctionOrInstancePropertyInitializer(node, container); + var enclosingIterationStatement = getEnclosingIterationStatement(container); + if (enclosingIterationStatement) { + if (isCaptured) { // mark iteration statement as containing block-scoped binding captured in some function var capturesBlockScopeBindingInLoopBody = true; if (ts.isForStatement(container)) { - var varDeclList = ts.getAncestor(symbol.valueDeclaration, 250 /* VariableDeclarationList */); + var varDeclList = ts.getAncestor(symbol.valueDeclaration, 251 /* VariableDeclarationList */); if (varDeclList && varDeclList.parent === container) { var part = getPartOfForStatementContainingNode(node.parent, container); if (part) { @@ -65228,13 +67265,13 @@ var ts; } } if (capturesBlockScopeBindingInLoopBody) { - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + getNodeLinks(enclosingIterationStatement).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 (ts.isForStatement(container)) { - var varDeclList = ts.getAncestor(symbol.valueDeclaration, 250 /* VariableDeclarationList */); + var varDeclList = ts.getAncestor(symbol.valueDeclaration, 251 /* VariableDeclarationList */); if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } @@ -65242,7 +67279,7 @@ var ts; // set 'declared inside loop' bit on the block-scoped binding getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } - if (usedInFunction) { + if (isCaptured) { getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } @@ -65253,7 +67290,7 @@ var ts; function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; - while (current.parent.kind === 207 /* ParenthesizedExpression */) { + while (current.parent.kind === 208 /* ParenthesizedExpression */) { current = current.parent; } // check if node is used as LHS in some assignment expression @@ -65261,7 +67298,7 @@ var ts; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 214 /* PrefixUnaryExpression */ || current.parent.kind === 215 /* PostfixUnaryExpression */)) { + else if ((current.parent.kind === 215 /* PrefixUnaryExpression */ || current.parent.kind === 216 /* PostfixUnaryExpression */)) { var expr = current.parent; isAssigned = expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */; } @@ -65274,7 +67311,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 163 /* PropertyDeclaration */ || container.kind === 166 /* Constructor */) { + if (container.kind === 164 /* PropertyDeclaration */ || container.kind === 167 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -65314,37 +67351,37 @@ var ts; // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var capturedByArrowFunction = false; - if (container.kind === 166 /* Constructor */) { + if (container.kind === 167 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 209 /* ArrowFunction */) { + if (container.kind === 210 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); capturedByArrowFunction = true; } switch (container.kind) { - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 166 /* Constructor */: + case 167 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -65432,7 +67469,7 @@ var ts; } function getClassNameFromPrototypeMethod(container) { // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 208 /* FunctionExpression */ && + if (container.kind === 209 /* FunctionExpression */ && ts.isBinaryExpression(container.parent) && ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { // Get the 'x' of 'x.prototype.y = container' @@ -65442,16 +67479,16 @@ var ts; .expression; // x } // x.prototype = { method() { } } - else if (container.kind === 165 /* MethodDeclaration */ && - container.parent.kind === 200 /* ObjectLiteralExpression */ && + else if (container.kind === 166 /* MethodDeclaration */ && + container.parent.kind === 201 /* 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 === 208 /* FunctionExpression */ && - container.parent.kind === 288 /* PropertyAssignment */ && - container.parent.parent.kind === 200 /* ObjectLiteralExpression */ && + else if (container.kind === 209 /* FunctionExpression */ && + container.parent.kind === 289 /* PropertyAssignment */ && + container.parent.parent.kind === 201 /* ObjectLiteralExpression */ && ts.isBinaryExpression(container.parent.parent.parent) && ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { return container.parent.parent.parent.left.expression; @@ -65459,7 +67496,7 @@ var ts; // Object.defineProperty(x, "method", { value: function() { } }); // Object.defineProperty(x, "method", { set: (x: () => void) => void }); // Object.defineProperty(x, "method", { get: () => function() { }) }); - else if (container.kind === 208 /* FunctionExpression */ && + else if (container.kind === 209 /* FunctionExpression */ && ts.isPropertyAssignment(container.parent) && ts.isIdentifier(container.parent.name) && (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && @@ -65484,7 +67521,7 @@ var ts; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 308 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 309 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -65498,16 +67535,16 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 160 /* Parameter */ && n.parent === constructorDecl; }); + return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 161 /* Parameter */ && n.parent === constructorDecl; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 203 /* CallExpression */ && node.parent.expression === node; + var isCallExpression = node.parent.kind === 204 /* CallExpression */ && node.parent.expression === node; var immediateContainer = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var container = immediateContainer; var needToCaptureLexicalThis = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - while (container && container.kind === 209 /* ArrowFunction */) { + while (container && container.kind === 210 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } @@ -65520,14 +67557,14 @@ var ts; // class B { // [super.foo()]() {} // } - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 158 /* ComputedPropertyName */; }); - if (current && current.kind === 158 /* ComputedPropertyName */) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 159 /* ComputedPropertyName */; }); + if (current && current.kind === 159 /* ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 200 /* ObjectLiteralExpression */)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 201 /* ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -65535,7 +67572,7 @@ var ts; } return errorType; } - if (!isCallExpression && immediateContainer.kind === 166 /* Constructor */) { + if (!isCallExpression && immediateContainer.kind === 167 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } if (ts.hasSyntacticModifier(container, 32 /* Static */) || isCallExpression) { @@ -65604,7 +67641,7 @@ var ts; // 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 === 165 /* MethodDeclaration */ && ts.hasSyntacticModifier(container, 256 /* Async */)) { + if (container.kind === 166 /* MethodDeclaration */ && ts.hasSyntacticModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } @@ -65618,7 +67655,7 @@ var ts; // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 200 /* ObjectLiteralExpression */) { + if (container.parent.kind === 201 /* ObjectLiteralExpression */) { if (languageVersion < 2 /* ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return errorType; @@ -65639,7 +67676,7 @@ var ts; if (!baseClassType) { return errorType; } - if (container.kind === 166 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 167 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return errorType; @@ -65654,7 +67691,7 @@ var ts; if (isCallExpression) { // TS 1.0 SPEC (April 2014): 4.8.1 // Super calls are only permitted in constructors of derived classes - return container.kind === 166 /* Constructor */; + return container.kind === 167 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -65662,21 +67699,21 @@ var ts; // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance // - In a static member function or static member accessor // topmost container must be something that is directly nested in the class declaration\object literal expression - if (ts.isClassLike(container.parent) || container.parent.kind === 200 /* ObjectLiteralExpression */) { + if (ts.isClassLike(container.parent) || container.parent.kind === 201 /* ObjectLiteralExpression */) { if (ts.hasSyntacticModifier(container, 32 /* Static */)) { - return container.kind === 165 /* MethodDeclaration */ || - container.kind === 164 /* MethodSignature */ || - container.kind === 167 /* GetAccessor */ || - container.kind === 168 /* SetAccessor */; + return container.kind === 166 /* MethodDeclaration */ || + container.kind === 165 /* MethodSignature */ || + container.kind === 168 /* GetAccessor */ || + container.kind === 169 /* SetAccessor */; } else { - return container.kind === 165 /* MethodDeclaration */ || - container.kind === 164 /* MethodSignature */ || - container.kind === 167 /* GetAccessor */ || - container.kind === 168 /* SetAccessor */ || - container.kind === 163 /* PropertyDeclaration */ || - container.kind === 162 /* PropertySignature */ || - container.kind === 166 /* Constructor */; + return container.kind === 166 /* MethodDeclaration */ || + container.kind === 165 /* MethodSignature */ || + container.kind === 168 /* GetAccessor */ || + container.kind === 169 /* SetAccessor */ || + container.kind === 164 /* PropertyDeclaration */ || + container.kind === 163 /* PropertySignature */ || + container.kind === 167 /* Constructor */; } } } @@ -65684,10 +67721,10 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 165 /* MethodDeclaration */ || - func.kind === 167 /* GetAccessor */ || - func.kind === 168 /* SetAccessor */) && func.parent.kind === 200 /* ObjectLiteralExpression */ ? func.parent : - func.kind === 208 /* FunctionExpression */ && func.parent.kind === 288 /* PropertyAssignment */ ? func.parent.parent : + return (func.kind === 166 /* MethodDeclaration */ || + func.kind === 168 /* GetAccessor */ || + func.kind === 169 /* SetAccessor */) && func.parent.kind === 201 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 209 /* FunctionExpression */ && func.parent.kind === 289 /* PropertyAssignment */ ? func.parent.parent : undefined; } function getThisTypeArgument(type) { @@ -65699,7 +67736,7 @@ var ts; }); } function getContextualThisParameterType(func) { - if (func.kind === 209 /* ArrowFunction */) { + if (func.kind === 210 /* ArrowFunction */) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -65726,7 +67763,7 @@ var ts; if (thisType) { return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral))); } - if (literal.parent.kind !== 288 /* PropertyAssignment */) { + if (literal.parent.kind !== 289 /* PropertyAssignment */) { break; } literal = literal.parent.parent; @@ -65740,7 +67777,7 @@ var ts; // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. var parent = ts.walkUpParenthesizedExpressions(func.parent); - if (parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) { + if (parent.kind === 217 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) { var target = parent.left; if (ts.isAccessExpression(target)) { var expression = target.expression; @@ -65793,11 +67830,11 @@ var ts; return getTypeFromTypeNode(typeNode); } switch (declaration.kind) { - case 160 /* Parameter */: + case 161 /* Parameter */: return getContextuallyTypedParameterType(declaration); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return getContextualTypeForBindingElement(declaration); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: if (ts.hasSyntacticModifier(declaration, 32 /* Static */)) { return getContextualTypeForStaticPropertyDeclaration(declaration); } @@ -65808,10 +67845,10 @@ var ts; var parent = declaration.parent.parent; var name = declaration.propertyName || declaration.name; var parentType = getContextualTypeForVariableLikeDeclaration(parent) || - parent.kind !== 198 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent); + parent.kind !== 199 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent); if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name)) return undefined; - if (parent.name.kind === 197 /* ArrayBindingPattern */) { + if (parent.name.kind === 198 /* ArrayBindingPattern */) { var index = ts.indexOfNode(declaration.parent.elements, declaration); if (index < 0) return undefined; @@ -65948,7 +67985,7 @@ var ts; return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 205 /* TaggedTemplateExpression */) { + if (template.parent.kind === 206 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -65982,16 +68019,16 @@ var ts; // In an assignment expression, the right operand is contextually typed by the type of the left operand. // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. function getContextualTypeForAssignmentDeclaration(binaryExpression) { + var _a, _b; var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return getTypeOfExpression(binaryExpression.left); + case 4 /* ThisProperty */: + return getContextualTypeForThisPropertyAssignment(binaryExpression); case 5 /* Property */: - case 1 /* ExportsProperty */: - case 6 /* Prototype */: - case 3 /* PrototypeProperty */: if (isPossiblyAliasedThisProperty(binaryExpression, kind)) { - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + return getContextualTypeForThisPropertyAssignment(binaryExpression); } // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. // See `bindStaticPropertyAssignment` in `binder.ts`. @@ -66012,11 +68049,11 @@ var ts; var id = lhs.expression; var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true); if (parentSymbol) { - var annotated = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); - if (annotated) { + var annotated_1 = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated_1) { var nameStr = ts.getElementOrPropertyAccessName(lhs); if (nameStr !== undefined) { - return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr); + return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated_1), nameStr); } } return undefined; @@ -66024,9 +68061,15 @@ var ts; } return ts.isInJSFile(decl) ? undefined : getTypeOfExpression(binaryExpression.left); } + case 1 /* ExportsProperty */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + var valueDeclaration = (_a = binaryExpression.left.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration; + // falls through case 2 /* ModuleExports */: - case 4 /* ThisProperty */: - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + valueDeclaration || (valueDeclaration = (_b = binaryExpression.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration); + var annotated = valueDeclaration && ts.getEffectiveTypeAnnotationNode(valueDeclaration); + return annotated ? getTypeFromTypeNode(annotated) : undefined; case 7 /* ObjectDefinePropertyValue */: case 8 /* ObjectDefinePropertyExports */: case 9 /* ObjectDefinePrototypeProperty */: @@ -66047,7 +68090,7 @@ var ts; var symbol = resolveName(declaration.left, name, 111551 /* Value */, undefined, undefined, /*isUse*/ true, /*excludeGlobals*/ true); return ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration); } - function getContextualTypeForThisPropertyAssignment(binaryExpression, kind) { + function getContextualTypeForThisPropertyAssignment(binaryExpression) { if (!binaryExpression.symbol) return getTypeOfExpression(binaryExpression.left); if (binaryExpression.symbol.valueDeclaration) { @@ -66059,8 +68102,6 @@ var ts; } } } - if (kind === 2 /* ModuleExports */) - return undefined; var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression); if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { return undefined; @@ -66115,9 +68156,13 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + if (propertyAssignmentType) { + return propertyAssignmentType; + } var type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { - if (!hasNonBindableDynamicName(element)) { + if (hasBindableName(element)) { // 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. @@ -66203,19 +68248,19 @@ var ts; case 78 /* Identifier */: case 150 /* UndefinedKeyword */: return true; - case 201 /* PropertyAccessExpression */: - case 207 /* ParenthesizedExpression */: + case 202 /* PropertyAccessExpression */: + case 208 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); - case 283 /* JsxExpression */: + case 284 /* 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 === 288 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 289 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 280 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. @@ -66226,15 +68271,9 @@ var ts; var instantiatedType = instantiateContextualType(contextualType, node, contextFlags); if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) { var apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true); - if (apparentType.flags & 1048576 /* Union */) { - if (ts.isObjectLiteralExpression(node)) { - return discriminateContextualTypeByObjectMembers(node, apparentType); - } - else if (ts.isJsxAttributes(node)) { - return discriminateContextualTypeByJSXAttributes(node, apparentType); - } - } - return apparentType; + return apparentType.flags & 1048576 /* Union */ && ts.isObjectLiteralExpression(node) ? discriminateContextualTypeByObjectMembers(node, apparentType) : + apparentType.flags & 1048576 /* Union */ && ts.isJsxAttributes(node) ? discriminateContextualTypeByJSXAttributes(node, apparentType) : + apparentType; } } // If the given contextual type contains instantiable types and if a mapper representing @@ -66301,58 +68340,60 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 198 /* BindingElement */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 199 /* BindingElement */: return getContextualTypeForInitializerExpression(node, contextFlags); - case 209 /* ArrowFunction */: - case 242 /* ReturnStatement */: + case 210 /* ArrowFunction */: + case 243 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return getContextualTypeForAwaitOperand(parent, contextFlags); - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (parent.expression.kind === 99 /* ImportKeyword */) { return stringType; } /* falls through */ - case 204 /* NewExpression */: + case 205 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return ts.isConstTypeReference(parent.type) ? tryFindWhenConstTypeReference(parent) : getTypeFromTypeNode(parent.type); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node, contextFlags); - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent, contextFlags); - case 290 /* SpreadAssignment */: - return getApparentTypeOfContextualType(parent.parent, contextFlags); - case 199 /* ArrayLiteralExpression */: { + case 291 /* SpreadAssignment */: + return getContextualType(parent.parent, contextFlags); + case 200 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node, contextFlags); - case 228 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 218 /* TemplateExpression */); + case 229 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 219 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 207 /* ParenthesizedExpression */: { + case 208 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags); } - case 283 /* JsxExpression */: + case 226 /* NonNullExpression */: + return getContextualType(parent, contextFlags); + case 284 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); - case 280 /* JsxAttribute */: - case 282 /* JsxSpreadAttribute */: + case 281 /* JsxAttribute */: + case 283 /* JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent); - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent, contextFlags); } return undefined; @@ -66388,14 +68429,14 @@ var ts; return propsType; } function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { - if (sig.unionSignatures) { + if (sig.compositeSignatures) { // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature, // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur // for a union signature). It's an unfortunate quirk of looking in the output of the signature for the type we want to use for the input. // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane. var results = []; - for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) { + for (var _i = 0, _a = sig.compositeSignatures; _i < _a.length; _i++) { var signature = _a[_i]; var instance = getReturnTypeOfSignature(signature); if (isTypeAny(instance)) { @@ -66407,7 +68448,7 @@ var ts; } results.push(propType); } - return getIntersectionType(results); + return getIntersectionType(results); // Same result for both union and intersection signatures } var instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); @@ -66432,16 +68473,19 @@ var ts; function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { var managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { - var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); // fetches interface type, or initializes symbol links type parmaeters var ctorType = getStaticTypeOfReferencedJsxConstructor(context); + if (managedSym.flags & 524288 /* TypeAlias */) { + var params = getSymbolLinks(managedSym).typeParameters; + if (ts.length(params) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], params, 2, ts.isInJSFile(context)); + return getTypeAliasInstantiation(managedSym, args); + } + } if (ts.length(declaredManagedType.typeParameters) >= 2) { var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } - else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); - return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); - } } return attributesType; } @@ -66486,16 +68530,93 @@ var ts; return apparentAttributesType; } } + function getIntersectedSignatures(signatures) { + return ts.getStrictOptionValue(compilerOptions, "noImplicitAny") + ? ts.reduceLeft(signatures, function (left, right) { + return left === right || !left ? left + : compareTypeParametersIdentical(left.typeParameters, right.typeParameters) ? combineSignaturesOfIntersectionMembers(left, right) + : undefined; + }) + : undefined; + } + function combineIntersectionThisParam(left, right, mapper) { + if (!left || !right) { + return left || right; + } + // A signature `this` type might be a read or a write position... It's very possible that it should be invariant + // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be + // pessimistic when contextual typing, for now, we'll union the `this` types. + var thisType = getUnionType([getTypeOfSymbol(left), instantiateType(getTypeOfSymbol(right), mapper)]); + return createSymbolWithType(left, thisType); + } + function combineIntersectionParameters(left, right, mapper) { + var leftCount = getParameterCount(left); + var rightCount = getParameterCount(right); + var longest = leftCount >= rightCount ? left : right; + var shorter = longest === left ? right : left; + var longestCount = longest === left ? leftCount : rightCount; + var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right)); + var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest); + var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0)); + for (var i = 0; i < longestCount; i++) { + var longestParamType = tryGetTypeAtPosition(longest, i); + if (longest === right) { + longestParamType = instantiateType(longestParamType, mapper); + } + var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType; + if (shorter === right) { + shorterParamType = instantiateType(shorterParamType, mapper); + } + var unionParamType = getUnionType([longestParamType, shorterParamType]); + var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1); + var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter); + var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i); + var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i); + var paramName = leftName === rightName ? leftName : + !leftName ? rightName : + !rightName ? leftName : + undefined; + var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg" + i); + paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType; + params[i] = paramSymbol; + } + if (needsExtraRestElement) { + var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args"); + restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount)); + if (shorter === right) { + restParamSymbol.type = instantiateType(restParamSymbol.type, mapper); + } + params[longestCount] = restParamSymbol; + } + return params; + } + function combineSignaturesOfIntersectionMembers(left, right) { + var typeParams = left.typeParameters || right.typeParameters; + var paramMapper; + if (left.typeParameters && right.typeParameters) { + paramMapper = createTypeMapper(right.typeParameters, left.typeParameters); + // We just use the type parameter defaults from the first signature + } + var declaration = left.declaration; + var params = combineIntersectionParameters(left, right, paramMapper); + var thisParam = combineIntersectionThisParam(left.thisParameter, right.thisParameter, paramMapper); + var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); + var result = createSignature(declaration, typeParams, thisParam, params, + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 39 /* PropagatingFlags */); + result.compositeKind = 2097152 /* Intersection */; + result.compositeSignatures = ts.concatenate(left.compositeKind === 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); + if (paramMapper) { + result.mapper = left.compositeKind === 2097152 /* Intersection */ && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; + } + return result; + } // If the given type is an object or union type with a single signature, and if that signature has at // least as many parameters as the given function, return the signature. Otherwise return undefined. function getContextualCallSignature(type, node) { var signatures = getSignaturesOfType(type, 0 /* Call */); - if (signatures.length === 1) { - var signature = signatures[0]; - if (!isAritySmaller(signature, node)) { - return signature; - } - } + var applicableByArity = ts.filter(signatures, function (s) { return !isAritySmaller(s, node); }); + return applicableByArity.length === 1 ? applicableByArity[0] : getIntersectedSignatures(applicableByArity); } /** If the contextual signature has fewer parameters than the function expression, do not use it */ function isAritySmaller(signature, target) { @@ -66512,7 +68633,7 @@ var ts; return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 208 /* FunctionExpression */ || node.kind === 209 /* ArrowFunction */; + return node.kind === 209 /* FunctionExpression */ || node.kind === 210 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -66526,7 +68647,7 @@ var ts; // all identical ignoring their return type, the result is same signature but with return type as // union type of return types from these signatures function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var typeTagSignature = getSignatureOfTypeTag(node); if (typeTagSignature) { return typeTagSignature; @@ -66574,8 +68695,8 @@ var ts; return node.isSpread ? getIndexedAccessType(node.type, numberType) : node.type; } function hasDefaultValue(node) { - return (node.kind === 198 /* BindingElement */ && !!node.initializer) || - (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */); + return (node.kind === 199 /* BindingElement */ && !!node.initializer) || + (node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */); } function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; @@ -66587,7 +68708,7 @@ var ts; var inConstContext = isConstContext(node); for (var i = 0; i < elementCount; i++) { var e = elements[i]; - if (e.kind === 220 /* SpreadElement */) { + if (e.kind === 221 /* SpreadElement */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */); } @@ -66630,7 +68751,7 @@ var ts; if (inDestructuringPattern) { return createTupleType(elementTypes, elementFlags); } - if (forceTuple || inConstContext || contextualType && forEachType(contextualType, isTupleLikeType)) { + if (forceTuple || inConstContext || contextualType && someType(contextualType, isTupleLikeType)) { return createArrayLiteralType(createTupleType(elementTypes, elementFlags, /*readonly*/ inConstContext)); } return createArrayLiteralType(createArrayType(elementTypes.length ? @@ -66644,13 +68765,13 @@ var ts; var literalType = type.literalType; if (!literalType) { literalType = type.literalType = cloneTypeReference(type); - literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + literalType.objectFlags |= 32768 /* ArrayLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; } return literalType; } function isNumericName(name) { switch (name.kind) { - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return isNumericComputedName(name); case 78 /* Identifier */: return isNumericLiteralName(name.escapedText); @@ -66697,6 +68818,20 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); + // The computed property name of a non-static class field within a loop must be stored in a block-scoped binding. + // (It needs to be bound at class evaluation time.) + if (ts.isPropertyDeclaration(node.parent) && !ts.hasStaticModifier(node.parent) && ts.isClassExpression(node.parent.parent)) { + var container = ts.getEnclosingBlockScopeContainer(node.parent.parent); + var enclosingIterationStatement = getEnclosingIterationStatement(container); + if (enclosingIterationStatement) { + // The computed field name will use a block scoped binding which can be unique for each iteration of the loop. + getNodeLinks(enclosingIterationStatement).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + // The generated variable which stores the computed field name must be block-scoped. + getNodeLinks(node).flags |= 524288 /* BlockScopedBindingInLoop */; + // The generated variable which stores the class must be block-scoped. + getNodeLinks(node.parent.parent).flags |= 524288 /* BlockScopedBindingInLoop */; + } + } // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). if (links.resolvedType.flags & 98304 /* Nullable */ || @@ -66704,9 +68839,6 @@ var ts; !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } - else { - checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true); - } } return links.resolvedType; } @@ -66746,7 +68878,7 @@ var ts; var spread = emptyObjectType; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 196 /* ObjectBindingPattern */ || contextualType.pattern.kind === 200 /* ObjectLiteralExpression */); + (contextualType.pattern.kind === 197 /* ObjectBindingPattern */ || contextualType.pattern.kind === 201 /* ObjectLiteralExpression */); var inConstContext = isConstContext(node); var checkFlags = inConstContext ? 8 /* Readonly */ : 0; var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); @@ -66761,7 +68893,7 @@ var ts; // which may never occur. for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; - if (elem.name && ts.isComputedPropertyName(elem.name) && !ts.isWellKnownSymbolSyntactically(elem.name)) { + if (elem.name && ts.isComputedPropertyName(elem.name)) { checkComputedPropertyName(elem.name); } } @@ -66769,16 +68901,16 @@ var ts; for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var memberDecl = _c[_b]; var member = getSymbolOfNode(memberDecl); - var computedNameType = memberDecl.name && memberDecl.name.kind === 158 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + var computedNameType = memberDecl.name && memberDecl.name.kind === 159 /* ComputedPropertyName */ ? checkComputedPropertyName(memberDecl.name) : undefined; - if (memberDecl.kind === 288 /* PropertyAssignment */ || - memberDecl.kind === 289 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 289 /* PropertyAssignment */ || + memberDecl.kind === 290 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { - var type = memberDecl.kind === 288 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + var type = memberDecl.kind === 289 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`. // we don't want to say "could not find 'a'". - memberDecl.kind === 289 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : + memberDecl.kind === 290 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); @@ -66790,7 +68922,7 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) : @@ -66801,8 +68933,8 @@ var ts; if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. - var isOptional = (memberDecl.kind === 288 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 289 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 289 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 290 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216 /* Optional */; } @@ -66828,7 +68960,7 @@ var ts; member = prop; allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop); } - else if (memberDecl.kind === 290 /* SpreadAssignment */) { + else if (memberDecl.kind === 291 /* SpreadAssignment */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } @@ -66840,15 +68972,20 @@ var ts; hasComputedNumberProperty = false; } var type = getReducedType(checkExpression(memberDecl.expression)); - if (!isValidSpreadType(type)) { - error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return errorType; + if (isValidSpreadType(type)) { + if (allPropertiesTable) { + checkSpreadPropOverrides(type, allPropertiesTable, memberDecl); + } + offset = propertiesArray.length; + if (spread === errorType) { + continue; + } + spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext); } - if (allPropertiesTable) { - checkSpreadPropOverrides(type, allPropertiesTable, memberDecl); + else { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + spread = errorType; } - spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext); - offset = propertiesArray.length; continue; } else { @@ -66857,7 +68994,7 @@ var ts; // an ordinary function declaration(section 6.1) with no parameters. // A set accessor declaration is processed in the same manner // as an ordinary function declaration with a single parameter and a Void return type. - ts.Debug.assert(memberDecl.kind === 167 /* GetAccessor */ || memberDecl.kind === 168 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 168 /* GetAccessor */ || memberDecl.kind === 169 /* SetAccessor */); checkNodeDeferred(memberDecl); } if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) { @@ -66882,7 +69019,7 @@ var ts; // type with those properties for which the binding pattern specifies a default value. // If the object literal is spread into another object literal, skip this step and let the top-level object // literal handle it instead. - if (contextualTypeHasPattern && node.parent.kind !== 290 /* SpreadAssignment */) { + if (contextualTypeHasPattern && node.parent.kind !== 291 /* SpreadAssignment */) { for (var _d = 0, _e = getPropertiesOfType(contextualType); _d < _e.length; _d++) { var prop = _e[_d]; if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) { @@ -66894,6 +69031,9 @@ var ts; } } } + if (spread === errorType) { + return errorType; + } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext); @@ -66910,9 +69050,9 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; if (isJSObjectLiteral) { - result.objectFlags |= 16384 /* JSLiteral */; + result.objectFlags |= 8192 /* JSLiteral */; } if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; @@ -67002,14 +69142,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var objectFlags = 4096 /* JsxAttributes */; + var objectFlags = 2048 /* JsxAttributes */; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -67025,7 +69165,7 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 282 /* JsxSpreadAttribute */); + ts.Debug.assert(attributeDecl.kind === 283 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false); attributesTable = ts.createSymbolTable(); @@ -67051,7 +69191,7 @@ var ts; } } // Handle children attribute - var parent = openingLikeElement.parent.kind === 273 /* JsxElement */ ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 274 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = checkJsxChildren(parent, checkMode); @@ -67067,7 +69207,7 @@ var ts; // 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 */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - childrenContextualType && forEachType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : + childrenContextualType && someType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : createArrayType(getUnionType(childrenTypes)); // Fake up a property declaration for the children childrenPropSymbol.valueDeclaration = ts.factory.createPropertySignature(/*modifiers*/ undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined); @@ -67093,7 +69233,7 @@ var ts; function createJsxAttributesType() { objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return result; } } @@ -67108,7 +69248,7 @@ var ts; childrenTypes.push(stringType); } } - else if (child.kind === 283 /* JsxExpression */ && !child.expression) { + else if (child.kind === 284 /* JsxExpression */ && !child.expression) { continue; // empty jsx expressions don't *really* count as present children } else { @@ -67259,7 +69399,7 @@ var ts; else if (propertiesOfJsxElementAttribPropInterface.length === 1) { return propertiesOfJsxElementAttribPropInterface[0].escapedName; } - else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + else if (propertiesOfJsxElementAttribPropInterface.length > 1 && jsxElementAttribPropInterfaceSym.declarations) { // More than one property on ElementAttributesProperty is an error error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer)); } @@ -67369,11 +69509,11 @@ var ts; if (!links.resolvedJsxElementAttributesType) { var symbol = getIntrinsicTagSymbol(node); if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { - return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol) || errorType; } else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { return links.resolvedJsxElementAttributesType = - getIndexTypeOfType(getDeclaredTypeOfSymbol(symbol), 0 /* String */); + getIndexTypeOfType(getJsxType(JsxNames.IntrinsicElements, node), 0 /* String */) || errorType; } else { return links.resolvedJsxElementAttributesType = errorType; @@ -67526,9 +69666,12 @@ var ts; * @param type The type of the object whose property is being accessed. (Not the type of the property.) * @param prop The symbol for the property being accessed. */ - function checkPropertyAccessibility(node, isSuper, type, prop) { - var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 157 /* QualifiedName */ ? node.right : node.kind === 195 /* ImportType */ ? node : node.name; + function checkPropertyAccessibility(node, isSuper, writing, type, prop, reportError) { + if (reportError === void 0) { reportError = true; } + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop, writing); + var errorNode = node.kind === 158 /* QualifiedName */ ? node.right : + node.kind === 196 /* ImportType */ ? node : + node.kind === 199 /* BindingElement */ && node.propertyName ? node.propertyName : node.name; if (isSuper) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or @@ -67539,7 +69682,9 @@ var ts; // a super property access is permitted and must specify a public static member function of the base class. if (languageVersion < 2 /* ES2015 */) { if (symbolHasNonMethodDeclaration(prop)) { - error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + if (reportError) { + error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + } return false; } } @@ -67548,24 +69693,22 @@ var ts; // This error could mask a private property access error. But, a member // cannot simultaneously be private and abstract, so this will trigger an // additional error elsewhere. - error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + if (reportError) { + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + } return false; } } // Referencing abstract properties within their own constructors is not allowed - if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { + if ((flags & 128 /* Abstract */) && symbolHasNonMethodDeclaration(prop) && + (ts.isThisProperty(node) || ts.isThisInitializedObjectBindingExpression(node) || ts.isObjectBindingPattern(node.parent) && ts.isThisInitializedDeclaration(node.parent.parent))) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); 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; - } - } - if (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name)) { - if (!ts.getContainingClass(node)) { - error(errorNode, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + if (reportError) { + 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; } - return true; } // Public properties are otherwise accessible. if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { @@ -67576,7 +69719,9 @@ var ts; if (flags & 8 /* Private */) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + if (reportError) { + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + } return false; } return true; @@ -67590,7 +69735,7 @@ var ts; // of the property as base classes var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + return isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing) ? enclosingClass : undefined; }); // A protected property is accessible if the property is within the declaring class or classes derived from it if (!enclosingClass) { @@ -67598,7 +69743,9 @@ var ts; // static member access is disallow var thisParameter = void 0; if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + if (reportError) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + } return false; } var thisType = getTypeFromTypeNode(thisParameter.type); @@ -67613,7 +69760,9 @@ var ts; type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined } if (!type || !hasBaseType(type, enclosingClass)) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + if (reportError) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2, symbolToString(prop), typeToString(enclosingClass), typeToString(type)); + } return false; } return true; @@ -67669,20 +69818,20 @@ var ts; } return nonNullType; } - function checkPropertyAccessExpression(node) { - return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) : - checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + function checkPropertyAccessExpression(node, checkMode) { + return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node, checkMode) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name, checkMode); } - function checkPropertyAccessChain(node) { + function checkPropertyAccessChain(node, checkMode) { var leftType = checkExpression(node.expression); var nonOptionalType = getOptionalExpressionType(leftType, node.expression); - return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name, checkMode), node, nonOptionalType !== leftType); } - function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); + function checkQualifiedName(node, checkMode) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right, checkMode); } function isMethodAccessForCall(node) { - while (node.parent.kind === 207 /* ParenthesizedExpression */) { + while (node.parent.kind === 208 /* ParenthesizedExpression */) { node = node.parent; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; @@ -67717,14 +69866,13 @@ var ts; } var diagName = diagnosticName(right); if (propertyOnType) { - var typeValueDecl = propertyOnType.valueDeclaration; - var typeClass_1 = ts.getContainingClass(typeValueDecl); - ts.Debug.assert(!!typeClass_1); + var typeValueDecl = ts.Debug.checkDefined(propertyOnType.valueDeclaration); + var typeClass_1 = ts.Debug.checkDefined(ts.getContainingClass(typeValueDecl)); // We found a private identifier property with the same description. // Either: // - There is a lexically scoped private identifier AND it shadows the one we found on the type. // - It is an attempt to access the private identifier outside of the class. - if (lexicallyScopedIdentifier) { + if (lexicallyScopedIdentifier === null || lexicallyScopedIdentifier === void 0 ? void 0 : lexicallyScopedIdentifier.valueDeclaration) { var lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration; var lexicalClass = ts.getContainingClass(lexicalValueDecl); ts.Debug.assert(!!lexicalClass); @@ -67743,17 +69891,42 @@ var ts; return (isConstructorDeclaredProperty(prop) || ts.isThisProperty(node) && isAutoTypedProperty(prop)) && ts.getThisContainer(node, /*includeArrowFunctions*/ true) === getDeclaringConstructor(prop); } - function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right, checkMode) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); - if (ts.isPrivateIdentifier(right)) { - checkExternalEmitHelpers(node, 524288 /* ClassPrivateFieldGet */); - } var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType; var prop; if (ts.isPrivateIdentifier(right)) { + if (languageVersion < 99 /* ESNext */) { + if (assignmentKind !== 0 /* None */) { + checkExternalEmitHelpers(node, 1048576 /* ClassPrivateFieldSet */); + } + if (assignmentKind !== 1 /* Definite */) { + checkExternalEmitHelpers(node, 524288 /* ClassPrivateFieldGet */); + } + } var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right); + if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && ts.isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) { + grammarErrorOnNode(right, ts.Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, ts.idText(right)); + } + if ((lexicallyScopedSymbol === null || lexicallyScopedSymbol === void 0 ? void 0 : lexicallyScopedSymbol.valueDeclaration) && (compilerOptions.target === 99 /* ESNext */ && !useDefineForClassFields)) { + var lexicalClass_1 = ts.getContainingClass(lexicallyScopedSymbol.valueDeclaration); + var parentStaticFieldInitializer = ts.findAncestor(node, function (n) { + if (n === lexicalClass_1) + return "quit"; + if (ts.isPropertyDeclaration(n.parent) && ts.hasStaticModifier(n.parent) && n.parent.initializer === n && n.parent.parent === lexicalClass_1) { + return true; + } + return false; + }); + if (parentStaticFieldInitializer) { + var parentStaticFieldInitializerSymbol = getSymbolOfNode(parentStaticFieldInitializer.parent); + ts.Debug.assert(parentStaticFieldInitializerSymbol, "Initializer without declaration symbol"); + var diagnostic = error(node, ts.Diagnostics.Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false, ts.symbolName(lexicallyScopedSymbol)); + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(parentStaticFieldInitializer.parent, ts.Diagnostics.Initializer_for_property_0, ts.symbolName(parentStaticFieldInitializerSymbol))); + } + } if (isAnyLike) { if (lexicallyScopedSymbol) { return apparentType; @@ -67768,6 +69941,12 @@ var ts; if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) { return errorType; } + else { + var isSetonlyAccessor = prop && prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (isSetonlyAccessor && assignmentKind !== 1 /* Definite */) { + error(node, ts.Diagnostics.Private_accessor_was_defined_without_a_getter); + } + } } else { if (isAnyLike) { @@ -67778,7 +69957,11 @@ var ts; } prop = getPropertyOfType(apparentType, right.escapedText); } - if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums. + // The exceptions are: + // 1. if 'isolatedModules' is enabled, because the const enum value will not be inlined, and + // 2. if 'preserveConstEnums' is enabled and the expression is itself an export, e.g. `export = Foo.Bar.Baz`. + if (ts.isIdentifier(left) && parentSymbol && (compilerOptions.isolatedModules || !(prop && isConstEnumOrConstEnumOnlyModule(prop)) || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) { markAliasReferenced(parentSymbol, node); } var propType; @@ -67811,44 +69994,48 @@ var ts; } } else { - if (getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) { - errorOrSuggestion(/* isError */ false, right, ts.Diagnostics._0_is_deprecated, right.escapedText); + if (prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) { + addDeprecatedSuggestion(right, prop.declarations, right.escapedText); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node, left.kind === 107 /* ThisKeyword */); + markPropertyAsReferenced(prop, node, isSelfTypeAccess(left, parentSymbol)); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left.kind === 105 /* SuperKeyword */, apparentType, prop); + var writing = ts.isWriteAccess(node); + checkPropertyAccessibility(node, left.kind === 105 /* SuperKeyword */, writing, apparentType, prop); if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) { error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } - propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : getConstraintForLocation(getTypeOfSymbol(prop), node); + propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : writing ? getSetAccessorTypeOfSymbol(prop) : getTypeOfSymbol(prop); } - return getFlowTypeOfAccessExpression(node, prop, propType, right); + return getFlowTypeOfAccessExpression(node, prop, propType, right, checkMode); } - function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { + function getFlowTypeOfAccessExpression(node, prop, propType, errorNode, checkMode) { // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. var assignmentKind = ts.getAssignmentTargetKind(node); - if (!ts.isAccessExpression(node) || - assignmentKind === 1 /* Definite */ || - prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { + if (assignmentKind === 1 /* Definite */ || + prop && + !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) + && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */) + && !isDuplicatedCommonJSExport(prop.declarations)) { return propType; } if (propType === autoType) { return getFlowTypeOfProperty(node, prop); } + propType = getNarrowableTypeForReference(propType, node, checkMode); // If strict null checks and strict property initialization checks are enabled, if we have // a this.xxx property access, if the property is an instance property without an initializer, // and if we are in a constructor of the same class as the property declaration, assume that // the property is uninitialized at the top of the control flow. var assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 107 /* ThisKeyword */) { + if (strictNullChecks && strictPropertyInitialization && ts.isAccessExpression(node) && node.expression.kind === 107 /* ThisKeyword */) { var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); - if (flowContainer.kind === 166 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) { + if (flowContainer.kind === 167 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) { assumeUninitialized = true; } } @@ -67875,13 +70062,14 @@ var ts; var diagnosticMessage; var declarationName = ts.idText(right); if (isInPropertyInitializer(node) + && !isOptionalPropertyDeclaration(valueDeclaration) && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) - && !isPropertyDeclaredInAncestorClass(prop)) { + && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } - else if (valueDeclaration.kind === 252 /* ClassDeclaration */ && - node.parent.kind !== 173 /* TypeReference */ && + else if (valueDeclaration.kind === 253 /* ClassDeclaration */ && + node.parent.kind !== 174 /* TypeReference */ && !(valueDeclaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); @@ -67893,22 +70081,22 @@ var ts; function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return true; - case 288 /* PropertyAssignment */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 290 /* SpreadAssignment */: - case 158 /* ComputedPropertyName */: - case 228 /* TemplateSpan */: - case 283 /* JsxExpression */: - case 280 /* JsxAttribute */: - case 281 /* JsxAttributes */: - case 282 /* JsxSpreadAttribute */: - case 275 /* JsxOpeningElement */: - case 223 /* ExpressionWithTypeArguments */: - case 286 /* HeritageClause */: + case 289 /* PropertyAssignment */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 291 /* SpreadAssignment */: + case 159 /* ComputedPropertyName */: + case 229 /* TemplateSpan */: + case 284 /* JsxExpression */: + case 281 /* JsxAttribute */: + case 282 /* JsxAttributes */: + case 283 /* JsxSpreadAttribute */: + case 276 /* JsxOpeningElement */: + case 224 /* ExpressionWithTypeArguments */: + case 287 /* HeritageClause */: return false; default: return ts.isExpressionNode(node) ? false : "quit"; @@ -67980,7 +70168,10 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, missingProperty, container); + var diagnostic = containerSeemsToBeEmptyDomElement(containingType) + ? ts.Diagnostics.Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom + : ts.Diagnostics.Property_0_does_not_exist_on_type_1; + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), diagnostic, missingProperty, container); } } } @@ -67991,9 +70182,14 @@ var ts; } diagnostics.add(resultDiagnostic); } + function containerSeemsToBeEmptyDomElement(containingType) { + return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && + everyContainedType(containingType, function (type) { return type.symbol && /^(EventTarget|Node|((HTML[a-zA-Z]*)?Element))$/.test(ts.unescapeLeadingUnderscores(type.symbol.escapedName)); }) && + isEmptyObjectType(containingType); + } function typeHasStaticProperty(propName, containingType) { var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); - return prop !== undefined && prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */); + return prop !== undefined && !!prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedLibForNonExistentName(name) { var missingName = diagnosticName(name); @@ -68024,7 +70220,15 @@ var ts; } } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 111551 /* Value */); + var props = getPropertiesOfType(containingType); + if (typeof name !== "string") { + var parent_2 = name.parent; + if (ts.isPropertyAccessExpression(parent_2)) { + props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_2, containingType, prop); }); + } + name = ts.idText(name); + } + return getSpellingSuggestionForName(name, props, 111551 /* Value */); } function getSuggestedSymbolForNonexistentJSXAttribute(name, containingType) { var strName = ts.isString(name) ? name : ts.idText(name); @@ -68119,20 +70323,20 @@ var ts; return undefined; } } - function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isSelfTypeAccess) { var valueDeclaration = prop && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration; if (!valueDeclaration) { return; } var hasPrivateModifier = ts.hasEffectiveModifier(valueDeclaration, 8 /* Private */); - var hasPrivateIdentifier = ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name); + var hasPrivateIdentifier = prop.valueDeclaration && ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name); if (!hasPrivateModifier && !hasPrivateIdentifier) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) { return; } - if (isThisAccess) { + if (isSelfTypeAccess) { // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); if (containingMethod && containingMethod.symbol === prop) { @@ -68141,18 +70345,22 @@ var ts; } (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */; } + function isSelfTypeAccess(name, parent) { + return name.kind === 107 /* ThisKeyword */ + || !!parent && ts.isEntityNameExpression(name) && parent === getResolvedSymbol(ts.getFirstIdentifier(name)); + } function isValidPropertyAccess(node, propertyName) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return isValidPropertyAccessWithType(node, node.expression.kind === 105 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); - case 195 /* ImportType */: + case 196 /* ImportType */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind === 201 /* PropertyAccessExpression */ && node.expression.kind === 105 /* SuperKeyword */, property.escapedName, type); + return isValidPropertyAccessWithType(node, node.kind === 202 /* PropertyAccessExpression */ && node.expression.kind === 105 /* SuperKeyword */, property.escapedName, type); // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context. } function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { @@ -68161,11 +70369,11 @@ var ts; } var prop = getPropertyOfType(type, propertyName); if (prop) { - if (ts.isPropertyAccessExpression(node) && prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)) { + if (prop.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration)) { var declClass_1 = ts.getContainingClass(prop.valueDeclaration); return !ts.isOptionalChain(node) && !!ts.findAncestor(node, function (parent) { return parent === declClass_1; }); } - return checkPropertyAccessibility(node, isSuper, type, prop); + return checkPropertyAccessibility(node, isSuper, /*writing*/ false, type, prop, /* reportError */ false); } // In js files properties of unions are allowed in completion return ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); @@ -68175,7 +70383,7 @@ var ts; */ function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 250 /* VariableDeclarationList */) { + if (initializer.kind === 251 /* VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); @@ -68204,7 +70412,7 @@ var ts; var child = expr; var node = expr.parent; while (node) { - if (node.kind === 238 /* ForInStatement */ && + if (node.kind === 239 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -68217,16 +70425,16 @@ var ts; } return false; } - function checkIndexedAccess(node) { - return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) : - checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + function checkIndexedAccess(node, checkMode) { + return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node, checkMode) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression), checkMode); } - function checkElementAccessChain(node) { + function checkElementAccessChain(node, checkMode) { var exprType = checkExpression(node.expression); var nonOptionalType = getOptionalExpressionType(exprType, node.expression); - return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression), checkMode), node, nonOptionalType !== exprType); } - function checkElementAccessExpression(node, exprType) { + function checkElementAccessExpression(node, exprType, checkMode) { var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; var indexExpression = node.argumentExpression; var indexType = checkExpression(indexExpression); @@ -68242,42 +70450,7 @@ var ts; 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) : 0 /* None */; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, /*noUncheckedIndexedAccessCandidate*/ undefined, node, accessFlags | 16 /* ExpressionPosition */) || errorType; - return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); - } - function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { - if (expressionType === errorType) { - // There is already an error, so no need to report one. - return false; - } - if (!ts.isWellKnownSymbolSyntactically(expression)) { - return false; - } - // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) { - if (reportError) { - error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); - } - return false; - } - // The name is Symbol., so make sure Symbol actually resolves to the - // global Symbol object - var leftHandSide = expression.expression; - var leftHandSideSymbol = getResolvedSymbol(leftHandSide); - if (!leftHandSideSymbol) { - return false; - } - var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true); - if (!globalESSymbol) { - // Already errored when we tried to look up the symbol - return false; - } - if (leftHandSideSymbol !== globalESSymbol) { - if (reportError) { - error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); - } - return false; - } - return true; + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, getNodeLinks(node).resolvedSymbol, indexedAccessType, indexExpression, checkMode), node); } function callLikeExpressionMayHaveTypeArguments(node) { return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node); @@ -68288,13 +70461,13 @@ var ts; // This gets us diagnostics for the type arguments and marks them as referenced. ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 205 /* TaggedTemplateExpression */) { + if (node.kind === 206 /* TaggedTemplateExpression */) { checkExpression(node.template); } else if (ts.isJsxOpeningLikeElement(node)) { checkExpression(node.attributes); } - else if (node.kind !== 161 /* Decorator */) { + else if (node.kind !== 162 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -68358,7 +70531,7 @@ var ts; } } function isSpreadArgument(arg) { - return !!arg && (arg.kind === 220 /* SpreadElement */ || arg.kind === 227 /* SyntheticExpression */ && arg.isSpread); + return !!arg && (arg.kind === 221 /* SpreadElement */ || arg.kind === 228 /* SyntheticExpression */ && arg.isSpread); } function getSpreadArgumentIndex(args) { return ts.findIndex(args, isSpreadArgument); @@ -68375,9 +70548,9 @@ var ts; var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments var effectiveParameterCount = getParameterCount(signature); var effectiveMinimumArguments = getMinArgumentCount(signature); - if (node.kind === 205 /* TaggedTemplateExpression */) { + if (node.kind === 206 /* TaggedTemplateExpression */) { argCount = args.length; - if (node.template.kind === 218 /* TemplateExpression */) { + if (node.template.kind === 219 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. @@ -68392,7 +70565,7 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 161 /* Decorator */) { + else if (node.kind === 162 /* Decorator */) { argCount = getDecoratorArgumentCount(node, signature); } else if (ts.isJsxOpeningLikeElement(node)) { @@ -68406,7 +70579,7 @@ var ts; } else if (!node.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(node.kind === 204 /* NewExpression */); + ts.Debug.assert(node.kind === 205 /* NewExpression */); return getMinArgumentCount(signature) === 0; } else { @@ -68481,7 +70654,7 @@ var ts; }); if (!inferenceContext) { applyToReturnTypes(contextualSignature, signature, function (source, target) { - inferTypes(context.inferences, source, target, 64 /* ReturnType */); + inferTypes(context.inferences, source, target, 128 /* ReturnType */); }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); @@ -68492,6 +70665,15 @@ var ts; inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } + function getThisArgumentType(thisArgumentNode) { + if (!thisArgumentNode) { + return voidType; + } + var thisArgumentType = checkExpression(thisArgumentNode); + return ts.isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) : + ts.isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) : + thisArgumentType; + } function inferTypeArguments(node, signature, args, checkMode, context) { if (ts.isJsxOpeningLikeElement(node)) { return inferJsxTypeArguments(node, signature, checkMode, context); @@ -68500,7 +70682,7 @@ var ts; // 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 // return type of 'wrap'. - if (node.kind !== 161 /* Decorator */) { + if (node.kind !== 162 /* Decorator */) { var contextualType = getContextualType(node, ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }) ? 8 /* SkipBindingPatterns */ : 0 /* None */); if (contextualType) { // We clone the inference context to avoid disturbing a resolution in progress for an @@ -68522,7 +70704,7 @@ var ts; instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 64 /* ReturnType */); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* ReturnType */); // Create a type mapper for instantiating generic contextual types using the inferences made // from the return type. We need a separate inference pass here because (a) instantiation of // the source type uses the outer context's return mapper (which excludes inferences made from @@ -68544,12 +70726,11 @@ var ts; var thisType = getThisTypeOfSignature(signature); if (thisType) { var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context.inferences, thisArgumentType, thisType); + inferTypes(context.inferences, getThisArgumentType(thisArgumentNode), thisType); } for (var i = 0; i < argCount; i++) { var arg = args[i]; - if (arg.kind !== 222 /* OmittedExpression */) { + if (arg.kind !== 223 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode); inferTypes(context.inferences, argType, paramType); @@ -68573,7 +70754,7 @@ var ts; 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 getMutableArrayOrTupleType(arg.kind === 227 /* SyntheticExpression */ ? arg.type : + return getMutableArrayOrTupleType(arg.kind === 228 /* SyntheticExpression */ ? arg.type : checkExpressionWithContextualType(arg.expression, restType, context, checkMode)); } } @@ -68583,13 +70764,13 @@ var ts; for (var i = index; i < argCount; i++) { var arg = args[i]; if (isSpreadArgument(arg)) { - var spreadType = arg.kind === 227 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression); + var spreadType = arg.kind === 228 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression); if (isArrayLikeType(spreadType)) { types.push(spreadType); flags.push(8 /* Variadic */); } else { - types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 220 /* SpreadElement */ ? arg.expression : arg)); + types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 221 /* SpreadElement */ ? arg.expression : arg)); flags.push(4 /* Rest */); } } @@ -68600,7 +70781,7 @@ var ts; types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); flags.push(1 /* Required */); } - if (arg.kind === 227 /* SyntheticExpression */ && arg.tupleNameSource) { + if (arg.kind === 228 /* SyntheticExpression */ && arg.tupleNameSource) { names.push(arg.tupleNameSource); } } @@ -68744,24 +70925,12 @@ var ts; return undefined; } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 204 /* NewExpression */) { + if (thisType && thisType !== voidType && node.kind !== 205 /* NewExpression */) { // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = void 0; - if (thisArgumentNode) { - thisArgumentType = checkExpression(thisArgumentNode); - if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { - thisArgumentType = getNonNullableType(thisArgumentType); - } - else if (ts.isOptionalChain(thisArgumentNode.parent)) { - thisArgumentType = removeOptionalTypeMarker(thisArgumentType); - } - } - else { - thisArgumentType = voidType; - } + var thisArgumentType = getThisArgumentType(thisArgumentNode); var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -68774,7 +70943,7 @@ var ts; var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { var arg = args[i]; - if (arg.kind !== 222 /* OmittedExpression */) { + if (arg.kind !== 223 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode); // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive), @@ -68819,7 +70988,7 @@ var ts; * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. */ function getThisArgumentOfCall(node) { - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { var callee = ts.skipOuterExpressions(node.expression); if (ts.isAccessExpression(callee)) { return callee.expression; @@ -68836,17 +71005,17 @@ var ts; * Returns the effective arguments for an expression that works like a function invocation. */ function getEffectiveCallArguments(node) { - if (node.kind === 205 /* TaggedTemplateExpression */) { + if (node.kind === 206 /* TaggedTemplateExpression */) { var template = node.template; var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; - if (template.kind === 218 /* TemplateExpression */) { + if (template.kind === 219 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_3.push(span.expression); }); } return args_3; } - if (node.kind === 161 /* Decorator */) { + if (node.kind === 162 /* Decorator */) { return getEffectiveDecoratorArguments(node); } if (ts.isJsxOpeningLikeElement(node)) { @@ -68857,10 +71026,10 @@ var ts; if (spreadIndex >= 0) { // Create synthetic arguments from spreads of tuple types. var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_20 = function (i) { + var _loop_21 = function (i) { var arg = args[i]; // We can call checkExpressionCached because spread expressions never have a contextual type. - var spreadType = arg.kind === 220 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); + var spreadType = arg.kind === 221 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); if (spreadType && isTupleType(spreadType)) { ts.forEach(getTypeArguments(spreadType), function (t, i) { var _a; @@ -68874,7 +71043,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_20(i); + _loop_21(i); } return effectiveArgs_1; } @@ -68887,30 +71056,30 @@ var ts; var parent = node.parent; var expr = node.expression; switch (parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* 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 160 /* Parameter */: + case 161 /* 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 === 166 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, parent.parent.kind === 167 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), createSyntheticExpression(expr, anyType), createSyntheticExpression(expr, numberType) ]; - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* 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 !== 163 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + var hasPropDesc = parent.kind !== 164 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; return [ createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), @@ -68924,17 +71093,17 @@ var ts; */ function getDecoratorArgumentCount(node, signature) { switch (node.parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return 1; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return 2; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* 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 160 /* Parameter */: + case 161 /* Parameter */: return 3; default: return ts.Debug.fail(); @@ -68980,77 +71149,66 @@ var ts; return constructorSymbol === globalPromiseSymbol; } function getArgumentArityError(node, signatures, args) { - var min = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - var belowArgCount = Number.NEGATIVE_INFINITY; - var aboveArgCount = Number.POSITIVE_INFINITY; - var argCount = args.length; + var _a; + var spreadIndex = getSpreadArgumentIndex(args); + if (spreadIndex > -1) { + return ts.createDiagnosticForNode(args[spreadIndex], ts.Diagnostics.A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter); + } + var min = Number.POSITIVE_INFINITY; // smallest parameter count + var max = Number.NEGATIVE_INFINITY; // largest parameter count + var maxBelow = Number.NEGATIVE_INFINITY; // largest parameter count that is smaller than the number of arguments + var minAbove = Number.POSITIVE_INFINITY; // smallest parameter count that is larger than the number of arguments var closestSignature; for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { var sig = signatures_8[_i]; - var minCount = getMinArgumentCount(sig); - var maxCount = getParameterCount(sig); - if (minCount < argCount && minCount > belowArgCount) - belowArgCount = minCount; - if (argCount < maxCount && maxCount < aboveArgCount) - aboveArgCount = maxCount; - if (minCount < min) { - min = minCount; + var minParameter = getMinArgumentCount(sig); + var maxParameter = getParameterCount(sig); + // smallest/largest parameter counts + if (minParameter < min) { + min = minParameter; closestSignature = sig; } - max = Math.max(max, maxCount); + max = Math.max(max, maxParameter); + // shortest parameter count *longer than the call*/longest parameter count *shorter than the call* + if (minParameter < args.length && minParameter > maxBelow) + maxBelow = minParameter; + if (args.length < maxParameter && maxParameter < minAbove) + minAbove = maxParameter; } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); - var paramRange = hasRestParameter ? min : - min < max ? min + "-" + max : - min; - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var spanArray; - var related; - var error = hasRestParameter || hasSpreadArgument ? - hasRestParameter && hasSpreadArgument ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - paramRange === 1 && argCount === 0 && isPromiseResolveArityError(node) ? - ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : - ts.Diagnostics.Expected_0_arguments_but_got_1; - if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { - var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; - if (paramDecl) { - related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : - ts.isRestParameter(paramDecl) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined); - } - } - if (min < argCount && argCount < max) { - return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); - } - if (!hasSpreadArgument && argCount < min) { - var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1; - } - if (hasRestParameter || hasSpreadArgument) { - spanArray = ts.factory.createNodeArray(args); - if (hasSpreadArgument && argCount) { - var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined; - spanArray = ts.factory.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1))); + var parameterRange = hasRestParameter ? min + : min < max ? min + "-" + max + : min; + var error = hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 + : parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node) ? ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise + : ts.Diagnostics.Expected_0_arguments_but_got_1; + if (min < args.length && args.length < max) { + // between min and max, but with no matching overload + return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove); + } + else if (args.length < min) { + // too short: put the error span on the call expression, not any of the args + var diagnostic = getDiagnosticForCallNode(node, error, parameterRange, args.length); + var parameter = (_a = closestSignature === null || closestSignature === void 0 ? void 0 : closestSignature.declaration) === null || _a === void 0 ? void 0 : _a.parameters[closestSignature.thisParameter ? args.length + 1 : args.length]; + if (parameter) { + var parameterError = ts.createDiagnosticForNode(parameter, ts.isBindingPattern(parameter.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided + : ts.isRestParameter(parameter) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided + : ts.Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : !ts.isBindingPattern(parameter.name) ? ts.idText(ts.getFirstIdentifier(parameter.name)) : undefined); + return ts.addRelatedInfo(diagnostic, parameterError); } + return diagnostic; } else { - spanArray = ts.factory.createNodeArray(args.slice(max)); - } - var pos = ts.first(spanArray).pos; - var end = ts.last(spanArray).end; - if (end === pos) { - end++; + // too long; error goes on the excess parameters + var errorSpan = ts.factory.createNodeArray(args.slice(max)); + var pos = ts.first(errorSpan).pos; + var end = ts.last(errorSpan).end; + if (end === pos) { + end++; + } + ts.setTextRangePosEnd(errorSpan, pos, end); + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), errorSpan, error, parameterRange, args.length); } - ts.setTextRangePosEnd(spanArray, pos, end); - var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var argCount = typeArguments.length; @@ -69081,8 +71239,8 @@ var ts; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) { - var isTaggedTemplate = node.kind === 205 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 161 /* Decorator */; + var isTaggedTemplate = node.kind === 206 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 162 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var reportErrors = !candidatesOutArray && produceDiagnostics; var typeArguments; @@ -69144,7 +71302,7 @@ var ts; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 203 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 204 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -69198,7 +71356,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_21 = function (c) { + var _loop_22 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2); if (diags_2) { @@ -69216,7 +71374,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_21(c); + _loop_22(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); @@ -69374,7 +71532,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_22 = function (i) { + var _loop_23 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -69382,7 +71540,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_22(i); + _loop_23(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* None */; @@ -69574,7 +71732,7 @@ var ts; function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have no common signatures. return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) || - !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & 1048576 /* Union */) && !(getReducedType(apparentFuncType).flags & 131072 /* Never */) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray, checkMode) { if (node.arguments && languageVersion < 1 /* ES5 */) { @@ -69689,7 +71847,7 @@ var ts; var declaration = signature.declaration; var modifiers = ts.getSelectedEffectiveModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */); // (1) Public constructors and (2) constructor functions are always accessible. - if (!modifiers || declaration.kind !== 166 /* Constructor */) { + if (!modifiers || declaration.kind !== 167 /* Constructor */) { return true; } var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol); @@ -69833,16 +71991,16 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 160 /* Parameter */: + case 161 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; default: return ts.Debug.fail(); @@ -69937,16 +72095,16 @@ var ts; } function resolveSignature(node, candidatesOutArray, checkMode) { switch (node.kind) { - case 203 /* CallExpression */: + case 204 /* CallExpression */: return resolveCallExpression(node, candidatesOutArray, checkMode); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return resolveNewExpression(node, candidatesOutArray, checkMode); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode); - case 161 /* Decorator */: + case 162 /* Decorator */: return resolveDecorator(node, candidatesOutArray, checkMode); - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode); } throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); @@ -70078,7 +72236,7 @@ var ts; return false; } var parent = node.parent; - while (parent && parent.kind === 201 /* PropertyAccessExpression */) { + while (parent && parent.kind === 202 /* PropertyAccessExpression */) { parent = parent.parent; } if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 62 /* EqualsToken */) { @@ -70105,12 +72263,12 @@ var ts; if (node.expression.kind === 105 /* SuperKeyword */) { return voidType; } - if (node.kind === 204 /* NewExpression */) { + if (node.kind === 205 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 166 /* Constructor */ && - declaration.kind !== 170 /* ConstructSignature */ && - declaration.kind !== 175 /* ConstructorType */ && + declaration.kind !== 167 /* Constructor */ && + declaration.kind !== 171 /* ConstructSignature */ && + declaration.kind !== 176 /* ConstructorType */ && !ts.isJSDocConstructSignature(declaration) && !isJSConstructor(declaration)) { // When resolved signature is a call signature (and not a construct signature) the result type is any @@ -70130,7 +72288,7 @@ var ts; if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } - if (node.kind === 203 /* CallExpression */ && node.parent.kind === 233 /* ExpressionStatement */ && + if (node.kind === 204 /* CallExpression */ && !node.questionDotToken && node.parent.kind === 234 /* ExpressionStatement */ && returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) { if (!ts.isDottedName(node.expression)) { error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name); @@ -70144,7 +72302,7 @@ var ts; var jsSymbol = getSymbolOfExpando(node, /*allowDeclaration*/ false); if ((_a = jsSymbol === null || jsSymbol === void 0 ? void 0 : jsSymbol.exports) === null || _a === void 0 ? void 0 : _a.size) { var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; + jsAssignmentType.objectFlags |= 8192 /* JSLiteral */; return getIntersectionType([returnType, jsAssignmentType]); } } @@ -70153,26 +72311,27 @@ var ts; function checkDeprecatedSignature(signature, node) { if (signature.declaration && signature.declaration.flags & 134217728 /* Deprecated */) { var suggestionNode = getDeprecatedSuggestionNode(node); - errorOrSuggestion(/*isError*/ false, suggestionNode, ts.Diagnostics._0_is_deprecated, signatureToString(signature)); + var name = ts.tryGetPropertyAccessOrIdentifierToString(ts.getInvokedExpression(node)); + addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature)); } } function getDeprecatedSuggestionNode(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 203 /* CallExpression */: - case 161 /* Decorator */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 162 /* Decorator */: + case 205 /* NewExpression */: return getDeprecatedSuggestionNode(node.expression); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return getDeprecatedSuggestionNode(node.tag); - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return getDeprecatedSuggestionNode(node.tagName); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return node.argumentExpression; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return node.name; - case 173 /* TypeReference */: + case 174 /* TypeReference */: var typeReference = node; return ts.isQualifiedName(typeReference.typeName) ? typeReference.typeName.right : typeReference; default: @@ -70223,10 +72382,11 @@ var ts; return createPromiseReturnType(node, anyType); } function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { + var _a; if (allowSyntheticDefaultImports && type && type !== errorType) { var synthType = type; if (!synthType.syntheticType) { - var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var file = (_a = originalSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); @@ -70264,9 +72424,9 @@ var ts; return false; } var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ - ? 251 /* FunctionDeclaration */ + ? 252 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ - ? 249 /* VariableDeclaration */ + ? 250 /* VariableDeclaration */ : 0 /* Unknown */; if (targetDeclarationKind !== 0 /* Unknown */) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); @@ -70296,19 +72456,19 @@ var ts; case 9 /* BigIntLiteral */: case 109 /* TrueKeyword */: case 94 /* FalseKeyword */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 218 /* TemplateExpression */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 219 /* TemplateExpression */: return true; - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isValidConstAssertionArgument(node.expression); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: var op = node.operator; var arg = node.operand; return op === 40 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) || op === 39 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: var expr = node.expression; if (ts.isIdentifier(expr)) { var symbol = getSymbolAtLocation(expr); @@ -70364,7 +72524,7 @@ var ts; error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return errorType; } - else if (container.kind === 166 /* Constructor */) { + else if (container.kind === 167 /* Constructor */) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -70411,7 +72571,7 @@ var ts; return restParameter.escapedName; } function isValidDeclarationForTupleLabel(d) { - return d.kind === 192 /* NamedTupleMember */ || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name)); + return d.kind === 193 /* NamedTupleMember */ || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name)); } function getNameableDeclarationAtPosition(signature, pos) { var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); @@ -70576,7 +72736,14 @@ var ts; } } function assignContextualParameterTypes(signature, context) { - signature.typeParameters = context.typeParameters; + if (context.typeParameters) { + if (!signature.typeParameters) { + signature.typeParameters = context.typeParameters; + } + else { + return; // This signature has already has a contextual inference performed and cached on it! + } + } if (context.thisParameter) { var parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { @@ -70687,7 +72854,7 @@ var ts; var yieldType; var nextType; var fallbackReturnType = voidType; - if (func.body.kind !== 230 /* Block */) { // Async or normal arrow function + if (func.body.kind !== 231 /* Block */) { // Async or normal arrow function returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */); if (isAsync) { // From within an async function you can return either a non-promise value or a promise. Any @@ -70872,7 +73039,7 @@ var ts; return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node)); } function computeExhaustiveSwitchStatement(node) { - if (node.expression.kind === 211 /* TypeOfExpression */) { + if (node.expression.kind === 212 /* TypeOfExpression */) { var operandType = getTypeOfExpression(node.expression.expression); var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); // notEqualFacts states that the type of the switched value is not equal to every type in the switch. @@ -70935,11 +73102,11 @@ var ts; } function mayReturnNever(func) { switch (func.kind) { - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; - case 165 /* MethodDeclaration */: - return func.parent.kind === 200 /* ObjectLiteralExpression */; + case 166 /* MethodDeclaration */: + return func.parent.kind === 201 /* ObjectLiteralExpression */; default: return false; } @@ -70965,21 +73132,21 @@ var ts; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (func.kind === 164 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 230 /* Block */ || !functionHasImplicitReturn(func)) { + if (func.kind === 165 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 231 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */; + var errorNode = ts.getEffectiveReturnTypeNode(func) || func; if (type && type.flags & 131072 /* Never */) { - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + error(errorNode, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (type && !hasExplicitReturn) { // minimal check: function has syntactic return type annotation and no explicit return statements in the body // this function does not conform to the specification. - // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + error(errorNode, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) { - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + error(errorNode, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); } else if (compilerOptions.noImplicitReturns) { if (!type) { @@ -70994,11 +73161,11 @@ var ts; return; } } - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + error(errorNode, ts.Diagnostics.Not_all_code_paths_return_a_value); } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) { @@ -71014,7 +73181,7 @@ var ts; var returnType = getReturnTypeFromBody(node, checkMode); var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); - returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */; + returnOnlyType.objectFlags |= 524288 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; } } @@ -71022,7 +73189,7 @@ var ts; } // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 208 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 209 /* FunctionExpression */) { checkGrammarForGenerator(node); } contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -71068,7 +73235,7 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnType = getReturnTypeFromAnnotation(node); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); @@ -71081,7 +73248,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 230 /* Block */) { + if (node.body.kind === 231 /* Block */) { checkSourceElement(node.body); } else { @@ -71171,7 +73338,7 @@ var ts; expr.expression.kind === 107 /* ThisKeyword */) { // Look for if this is the constructor for the class that `symbol` is a property of. var ctor = ts.getContainingFunction(expr); - if (!(ctor && (ctor.kind === 166 /* Constructor */ || isJSConstructor(ctor)))) { + if (!(ctor && (ctor.kind === 167 /* Constructor */ || isJSConstructor(ctor)))) { return true; } if (symbol.valueDeclaration) { @@ -71196,7 +73363,7 @@ var ts; var symbol_2 = getNodeLinks(node).resolvedSymbol; if (symbol_2.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol_2); - return !!declaration && declaration.kind === 263 /* NamespaceImport */; + return !!declaration && declaration.kind === 264 /* NamespaceImport */; } } } @@ -71277,7 +73444,7 @@ var ts; var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); var func = ts.getContainingFunction(node); - if (func && func.kind !== 166 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { + if (func && func.kind !== 167 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); ts.addRelatedInfo(diagnostic, relatedInfo); } @@ -71444,14 +73611,33 @@ var ts; rightType = checkNonNullType(rightType, right); // TypeScript 1.0 spec (April 2014): 4.15.5 // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, - // and the right operand to be of type Any, an object type, or a type parameter type. + // and the right operand to be + // + // 1. assignable to the non-primitive type, + // 2. an unconstrained type parameter, + // 3. a union or intersection including one or more type parameters, whose constituents are all assignable to the + // the non-primitive type, or are unconstrainted type parameters, or have constraints assignable to the + // non-primitive type, or + // 4. a type parameter whose constraint is + // i. an object type, + // ii. the non-primitive type, or + // iii. a union or intersection with at least one constituent assignable to an object or non-primitive type. + // + // The divergent behavior for type parameters and unions containing type parameters is a workaround for type + // parameters not being narrowable. If the right operand is a concrete type, we can error if there is any chance + // it is a primitive. But if the operand is a type parameter, it cannot be narrowed, so we don't issue an error + // unless *all* instantiations would result in an error. + // // The result is always of the Boolean primitive type. if (!(allTypesAssignableToKind(leftType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) || isTypeAssignableToKind(leftType, 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */ | 262144 /* TypeParameter */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { - error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + var rightTypeConstraint = getConstraintOfType(rightType); + if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */) || + rightTypeConstraint && (isTypeAssignableToKind(rightType, 3145728 /* UnionOrIntersection */) && !allTypesAssignableToKind(rightTypeConstraint, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */) || + !maybeTypeOfKind(rightTypeConstraint, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */))) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_not_be_a_primitive); } return booleanType; } @@ -71470,7 +73656,7 @@ var ts; if (rightIsThis === void 0) { rightIsThis = false; } var properties = node.properties; var property = properties[propertyIndex]; - if (property.kind === 288 /* PropertyAssignment */ || property.kind === 289 /* ShorthandPropertyAssignment */) { + if (property.kind === 289 /* PropertyAssignment */ || property.kind === 290 /* ShorthandPropertyAssignment */) { var name = property.name; var exprType = getLiteralTypeFromPropertyName(name); if (isTypeUsableAsPropertyName(exprType)) { @@ -71478,14 +73664,14 @@ var ts; var prop = getPropertyOfType(objectLiteralType, text); if (prop) { markPropertyAsReferenced(prop, property, rightIsThis); - checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + checkPropertyAccessibility(property, /*isSuper*/ false, /*writing*/ true, objectLiteralType, prop); } } var elementType = getIndexedAccessType(objectLiteralType, exprType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */); var type = getFlowTypeOfDestructuring(property, elementType); - return checkDestructuringAssignment(property.kind === 289 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); + return checkDestructuringAssignment(property.kind === 290 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } - else if (property.kind === 290 /* SpreadAssignment */) { + else if (property.kind === 291 /* SpreadAssignment */) { if (propertyIndex < properties.length - 1) { error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } @@ -71523,7 +73709,7 @@ var ts; var inBoundsType = compilerOptions.noUncheckedIndexedAccess ? undefined : possiblyOutOfBoundsType; for (var i = 0; i < elements.length; i++) { var type = possiblyOutOfBoundsType; - if (node.elements[i].kind === 220 /* SpreadElement */) { + if (node.elements[i].kind === 221 /* SpreadElement */) { type = inBoundsType = inBoundsType !== null && inBoundsType !== void 0 ? inBoundsType : (checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType); } checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, type, checkMode); @@ -71533,8 +73719,8 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 222 /* OmittedExpression */) { - if (element.kind !== 220 /* SpreadElement */) { + if (element.kind !== 223 /* OmittedExpression */) { + if (element.kind !== 221 /* SpreadElement */) { var indexType = getLiteralType(elementIndex); if (isArrayLikeType(sourceType)) { // We create a synthetic expression so that getIndexedAccessType doesn't get confused @@ -71552,7 +73738,7 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 216 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) { + if (restExpression.kind === 217 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -71568,7 +73754,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; - if (exprOrAssignment.kind === 289 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 290 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove @@ -71584,24 +73770,24 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 216 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) { + if (target.kind === 217 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 200 /* ObjectLiteralExpression */) { + if (target.kind === 201 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } - if (target.kind === 199 /* ArrayLiteralExpression */) { + if (target.kind === 200 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 290 /* SpreadAssignment */ ? + var error = target.parent.kind === 291 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; - var optionalError = target.parent.kind === 290 /* SpreadAssignment */ ? + var optionalError = target.parent.kind === 291 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access; if (checkReferenceExpression(target, error, optionalError)) { @@ -71626,8 +73812,8 @@ var ts; case 78 /* Identifier */: case 10 /* StringLiteral */: case 13 /* RegularExpressionLiteral */: - case 205 /* TaggedTemplateExpression */: - case 218 /* TemplateExpression */: + case 206 /* TaggedTemplateExpression */: + case 219 /* TemplateExpression */: case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: case 9 /* BigIntLiteral */: @@ -71635,27 +73821,27 @@ var ts; case 94 /* FalseKeyword */: case 103 /* NullKeyword */: case 150 /* UndefinedKeyword */: - case 208 /* FunctionExpression */: - case 221 /* ClassExpression */: - case 209 /* ArrowFunction */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 211 /* TypeOfExpression */: - case 225 /* NonNullExpression */: - case 274 /* JsxSelfClosingElement */: - case 273 /* JsxElement */: + case 209 /* FunctionExpression */: + case 222 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 212 /* TypeOfExpression */: + case 226 /* NonNullExpression */: + case 275 /* JsxSelfClosingElement */: + case 274 /* JsxElement */: return true; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: // Unary operators ~, !, +, and - have no side effects. // The rest do. switch (node.operator) { @@ -71667,9 +73853,9 @@ var ts; } return false; // Some forms listed here for clarity - case 212 /* VoidExpression */: // Explicit opt-out - case 206 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 224 /* AsExpression */: // Not SEF, but can produce useful type warnings + case 213 /* VoidExpression */: // Explicit opt-out + case 207 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 225 /* AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } @@ -71677,84 +73863,111 @@ var ts; function isTypeEqualityComparableTo(source, target) { return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } - var CheckBinaryExpressionState; - (function (CheckBinaryExpressionState) { - CheckBinaryExpressionState[CheckBinaryExpressionState["MaybeCheckLeft"] = 0] = "MaybeCheckLeft"; - CheckBinaryExpressionState[CheckBinaryExpressionState["CheckRight"] = 1] = "CheckRight"; - CheckBinaryExpressionState[CheckBinaryExpressionState["FinishCheck"] = 2] = "FinishCheck"; - })(CheckBinaryExpressionState || (CheckBinaryExpressionState = {})); - function checkBinaryExpression(node, checkMode) { - var workStacks = { - expr: [node], - state: [0 /* MaybeCheckLeft */], - leftType: [undefined] + function createCheckBinaryExpression() { + var trampoline = ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState); + return function (node, checkMode) { + var result = trampoline(node, checkMode); + ts.Debug.assertIsDefined(result); + return result; }; - var stackIndex = 0; - var lastResult; - while (stackIndex >= 0) { - node = workStacks.expr[stackIndex]; - switch (workStacks.state[stackIndex]) { - case 0 /* MaybeCheckLeft */: { - if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { - finishInvocation(checkExpression(node.right, checkMode)); - break; - } - checkGrammarNullishCoalesceWithLogicalExpression(node); - var operator = node.operatorToken.kind; - if (operator === 62 /* EqualsToken */ && (node.left.kind === 200 /* ObjectLiteralExpression */ || node.left.kind === 199 /* ArrayLiteralExpression */)) { - finishInvocation(checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 107 /* ThisKeyword */)); - break; - } - advanceState(1 /* CheckRight */); - maybeCheckExpression(node.left); - break; - } - case 1 /* CheckRight */: { - var leftType = lastResult; - workStacks.leftType[stackIndex] = leftType; - var operator = node.operatorToken.kind; - if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) { - if (operator === 55 /* AmpersandAmpersandToken */) { - var parent = ts.walkUpParenthesizedExpressions(node.parent); - checkTestingKnownTruthyCallableType(node.left, leftType, ts.isIfStatement(parent) ? parent.thenStatement : undefined); - } - checkTruthinessOfType(leftType, node.left); + function onEnter(node, state, checkMode) { + if (state) { + state.stackIndex++; + state.skip = false; + setLeftType(state, /*type*/ undefined); + setLastResult(state, /*type*/ undefined); + } + else { + state = { + checkMode: checkMode, + skip: false, + stackIndex: 0, + typeStack: [undefined, undefined], + }; + } + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { + state.skip = true; + setLastResult(state, checkExpression(node.right, checkMode)); + return state; + } + checkGrammarNullishCoalesceWithLogicalExpression(node); + var operator = node.operatorToken.kind; + if (operator === 62 /* EqualsToken */ && (node.left.kind === 201 /* ObjectLiteralExpression */ || node.left.kind === 200 /* ArrayLiteralExpression */)) { + state.skip = true; + setLastResult(state, checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 107 /* ThisKeyword */)); + return state; + } + return state; + } + function onLeft(left, state, _node) { + if (!state.skip) { + return maybeCheckExpression(state, left); + } + } + function onOperator(operatorToken, state, node) { + if (!state.skip) { + var leftType = getLastResult(state); + ts.Debug.assertIsDefined(leftType); + setLeftType(state, leftType); + setLastResult(state, /*type*/ undefined); + var operator = operatorToken.kind; + if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) { + if (operator === 55 /* AmpersandAmpersandToken */) { + var parent = ts.walkUpParenthesizedExpressions(node.parent); + checkTestingKnownTruthyCallableOrAwaitableType(node.left, leftType, ts.isIfStatement(parent) ? parent.thenStatement : undefined); } - advanceState(2 /* FinishCheck */); - maybeCheckExpression(node.right); - break; - } - case 2 /* FinishCheck */: { - var leftType = workStacks.leftType[stackIndex]; - var rightType = lastResult; - finishInvocation(checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node)); - break; + checkTruthinessOfType(leftType, node.left); } - default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for checkBinaryExpression"); } } - return lastResult; - function finishInvocation(result) { - lastResult = result; - stackIndex--; - } - /** - * Note that `advanceState` sets the _current_ head state, and that `maybeCheckExpression` potentially pushes on a new - * head state; so `advanceState` must be called before any `maybeCheckExpression` during a state's execution. - */ - function advanceState(nextState) { - workStacks.state[stackIndex] = nextState; + function onRight(right, state, _node) { + if (!state.skip) { + return maybeCheckExpression(state, right); + } } - function maybeCheckExpression(node) { - if (ts.isBinaryExpression(node)) { - stackIndex++; - workStacks.expr[stackIndex] = node; - workStacks.state[stackIndex] = 0 /* MaybeCheckLeft */; - workStacks.leftType[stackIndex] = undefined; + function onExit(node, state) { + var result; + if (state.skip) { + result = getLastResult(state); } else { - lastResult = checkExpression(node, checkMode); + var leftType = getLeftType(state); + ts.Debug.assertIsDefined(leftType); + var rightType = getLastResult(state); + ts.Debug.assertIsDefined(rightType); + result = checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node); + } + state.skip = false; + setLeftType(state, /*type*/ undefined); + setLastResult(state, /*type*/ undefined); + state.stackIndex--; + return result; + } + function foldState(state, result, _side) { + setLastResult(state, result); + return state; + } + function maybeCheckExpression(state, node) { + if (ts.isBinaryExpression(node)) { + return node; } + setLastResult(state, checkExpression(node, state.checkMode)); + } + function getLeftType(state) { + return state.typeStack[state.stackIndex]; + } + function setLeftType(state, type) { + state.typeStack[state.stackIndex] = type; + } + function getLastResult(state) { + return state.typeStack[state.stackIndex + 1]; + } + function setLastResult(state, type) { + // To reduce overhead, reuse the next stack entry to store the + // last result. This avoids the overhead of an additional property + // on `WorkArea` and reuses empty stack entries as we walk back up + // the stack. + state.typeStack[state.stackIndex + 1] = type; } } function checkGrammarNullishCoalesceWithLogicalExpression(node) { @@ -71772,7 +73985,7 @@ var ts; // expression-wide checks and does not use a work stack to fold nested binary expressions into the same callstack frame function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 62 /* EqualsToken */ && (left.kind === 200 /* ObjectLiteralExpression */ || left.kind === 199 /* ArrayLiteralExpression */)) { + if (operator === 62 /* EqualsToken */ && (left.kind === 201 /* ObjectLiteralExpression */ || left.kind === 200 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 107 /* ThisKeyword */); } var leftType; @@ -72007,7 +74220,7 @@ var ts; if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false); - if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { + if ((symbol === null || symbol === void 0 ? void 0 : symbol.declarations) && symbol.declarations.some(ts.isJSDocTypedefTag)) { addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop); addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol); } @@ -72202,7 +74415,7 @@ var ts; } function checkConditionalExpression(node, checkMode) { var type = checkTruthinessExpression(node.condition); - checkTestingKnownTruthyCallableType(node.condition, type, node.whenTrue); + checkTestingKnownTruthyCallableOrAwaitableType(node.condition, type, node.whenTrue); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); return getUnionType([type1, type2], 2 /* Subtype */); @@ -72219,10 +74432,14 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return getFreshTypeOfLiteralType(getTemplateLiteralType(texts, types)); + return isConstContext(node) || someType(getContextualType(node) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; + } + function isTemplateLiteralContextualType(type) { + return !!(type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */) || + type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 402653316 /* StringLike */)); } function getContextNode(node) { - if (node.kind === 281 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { + if (node.kind === 282 /* 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; @@ -72238,7 +74455,7 @@ var ts; // We strip literal freshness when an appropriate contextual type is present such that contextually typed // literals always preserve their literal types (otherwise they might widen during type inference). An alternative // here would be to not mark contextually typed literals as fresh in the first place. - var result = maybeTypeOfKind(type, 134220672 /* FreshableLiteral */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -72271,13 +74488,13 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 206 /* TypeAssertionExpression */ || node.kind === 224 /* AsExpression */; + return node.kind === 207 /* TypeAssertionExpression */ || node.kind === 225 /* AsExpression */; } function checkDeclarationInitializer(declaration, contextualType) { var initializer = ts.getEffectiveInitializer(declaration); var type = getQuickTypeOfExpression(initializer) || (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer)); - return ts.isParameter(declaration) && declaration.name.kind === 197 /* ArrayBindingPattern */ && + return ts.isParameter(declaration) && declaration.name.kind === 198 /* ArrayBindingPattern */ && isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ? padTupleType(type, declaration.name) : type; } @@ -72287,7 +74504,7 @@ var ts; var elementFlags = type.target.elementFlags.slice(); for (var i = getTypeReferenceArity(type); i < patternElements.length; i++) { var e = patternElements[i]; - if (i < patternElements.length - 1 || !(e.kind === 198 /* BindingElement */ && e.dotDotDotToken)) { + if (i < patternElements.length - 1 || !(e.kind === 199 /* BindingElement */ && e.dotDotDotToken)) { elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType); elementFlags.push(2 /* Optional */); if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) { @@ -72322,7 +74539,7 @@ var ts; // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || unknownType; - return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || @@ -72330,7 +74547,7 @@ var ts; } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return !!(contextualType.flags & (134217856 /* StringLikeLiteral */ | 4194304 /* Index */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || @@ -72354,7 +74571,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); @@ -72365,7 +74582,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -72583,7 +74800,7 @@ var ts; } } function checkExpression(node, checkMode, forceTuple) { - ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -72593,7 +74810,7 @@ var ts; checkConstEnumAccess(node, type); } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return type; } function checkConstEnumAccess(node, type) { @@ -72601,11 +74818,11 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 202 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 78 /* Identifier */ || node.kind === 157 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || - (node.parent.kind === 176 /* TypeQuery */ && node.parent.exprName === node)) || - (node.parent.kind === 270 /* ExportSpecifier */); // We allow reexporting const enums + var ok = (node.parent.kind === 202 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 203 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 78 /* Identifier */ || node.kind === 158 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 177 /* TypeQuery */ && node.parent.exprName === node)) || + (node.parent.kind === 271 /* ExportSpecifier */); // We allow reexporting const enums if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } @@ -72630,15 +74847,15 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { case 78 /* Identifier */: - return checkIdentifier(node); + return checkIdentifier(node, checkMode); case 107 /* ThisKeyword */: return checkThisExpression(node); case 105 /* SuperKeyword */: @@ -72658,78 +74875,78 @@ var ts; return trueType; case 94 /* FalseKeyword */: return falseType; - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return checkTemplateExpression(node); case 13 /* RegularExpressionLiteral */: return globalRegExpType; - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return checkArrayLiteral(node, checkMode, forceTuple); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); - case 201 /* PropertyAccessExpression */: - return checkPropertyAccessExpression(node); - case 157 /* QualifiedName */: - return checkQualifiedName(node); - case 202 /* ElementAccessExpression */: - return checkIndexedAccess(node); - case 203 /* CallExpression */: + case 202 /* PropertyAccessExpression */: + return checkPropertyAccessExpression(node, checkMode); + case 158 /* QualifiedName */: + return checkQualifiedName(node, checkMode); + case 203 /* ElementAccessExpression */: + return checkIndexedAccess(node, checkMode); + case 204 /* CallExpression */: if (node.expression.kind === 99 /* ImportKeyword */) { return checkImportCallExpression(node); } // falls through - case 204 /* NewExpression */: + case 205 /* NewExpression */: return checkCallExpression(node, checkMode); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return checkParenthesizedExpression(node, checkMode); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return checkClassExpression(node); - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return checkAssertion(node); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return checkNonNullAssertion(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return checkMetaProperty(node); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return checkDeleteExpression(node); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return checkVoidExpression(node); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return checkAwaitExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return checkBinaryExpression(node, checkMode); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return checkConditionalExpression(node, checkMode); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return checkSpreadExpression(node, checkMode); - case 222 /* OmittedExpression */: + case 223 /* OmittedExpression */: return undefinedWideningType; - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return checkYieldExpression(node); - case 227 /* SyntheticExpression */: + case 228 /* SyntheticExpression */: return checkSyntheticExpression(node); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return checkJsxExpression(node, checkMode); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return checkJsxElement(node, checkMode); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node, checkMode); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return checkJsxFragment(node); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return errorType; @@ -72765,11 +74982,11 @@ var ts; checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) { - if (!(func.kind === 166 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { + if (!(func.kind === 167 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } - if (func.kind === 166 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") { + if (func.kind === 167 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") { error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name); } } @@ -72780,13 +74997,13 @@ var ts; if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 166 /* Constructor */ || func.kind === 170 /* ConstructSignature */ || func.kind === 175 /* ConstructorType */) { + if (func.kind === 167 /* Constructor */ || func.kind === 171 /* ConstructSignature */ || func.kind === 176 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } - if (func.kind === 209 /* ArrowFunction */) { + if (func.kind === 210 /* ArrowFunction */) { error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); } - if (func.kind === 167 /* GetAccessor */ || func.kind === 168 /* SetAccessor */) { + if (func.kind === 168 /* GetAccessor */ || func.kind === 169 /* SetAccessor */) { error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters); } } @@ -72844,13 +75061,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 209 /* ArrowFunction */: - case 169 /* CallSignature */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 174 /* FunctionType */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 210 /* ArrowFunction */: + case 170 /* CallSignature */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 175 /* FunctionType */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: var parent = node.parent; if (node === parent.type) { return parent; @@ -72868,7 +75085,7 @@ var ts; error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 197 /* ArrayBindingPattern */ || name.kind === 196 /* ObjectBindingPattern */) { + else if (name.kind === 198 /* ArrayBindingPattern */ || name.kind === 197 /* ObjectBindingPattern */) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -72877,13 +75094,13 @@ var ts; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 171 /* IndexSignature */) { + if (node.kind === 172 /* IndexSignature */) { checkGrammarIndexSignature(node); } // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled - else if (node.kind === 174 /* FunctionType */ || node.kind === 251 /* FunctionDeclaration */ || node.kind === 175 /* ConstructorType */ || - node.kind === 169 /* CallSignature */ || node.kind === 166 /* Constructor */ || - node.kind === 170 /* ConstructSignature */) { + else if (node.kind === 175 /* FunctionType */ || node.kind === 252 /* FunctionDeclaration */ || node.kind === 176 /* ConstructorType */ || + node.kind === 170 /* CallSignature */ || node.kind === 167 /* Constructor */ || + node.kind === 171 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); @@ -72913,10 +75130,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 169 /* CallSignature */: + case 170 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -72946,7 +75163,7 @@ var ts; checkAsyncFunctionReturnType(node, returnTypeNode); } } - if (node.kind !== 171 /* IndexSignature */ && node.kind !== 308 /* JSDocFunctionType */) { + if (node.kind !== 172 /* IndexSignature */ && node.kind !== 309 /* JSDocFunctionType */) { registerForUnusedIdentifiersCheck(node); } } @@ -72958,7 +75175,7 @@ var ts; var privateIdentifiers = new ts.Map(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 166 /* Constructor */) { + if (member.kind === 167 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) { @@ -72970,25 +75187,27 @@ var ts; var isStatic = ts.hasSyntacticModifier(member, 32 /* Static */); var name = member.name; if (!name) { - return; + continue; } - var names = ts.isPrivateIdentifier(name) ? privateIdentifiers : + var isPrivate = ts.isPrivateIdentifier(name); + var privateStaticFlags = isPrivate && isStatic ? 16 /* PrivateStatic */ : 0; + var names = isPrivate ? privateIdentifiers : isStatic ? staticNames : instanceNames; var memberName = name && ts.getPropertyNameForPropertyNameNode(name); if (memberName) { switch (member.kind) { - case 167 /* GetAccessor */: - addName(names, name, memberName, 1 /* GetAccessor */); + case 168 /* GetAccessor */: + addName(names, name, memberName, 1 /* GetAccessor */ | privateStaticFlags); break; - case 168 /* SetAccessor */: - addName(names, name, memberName, 2 /* SetAccessor */); + case 169 /* SetAccessor */: + addName(names, name, memberName, 2 /* SetAccessor */ | privateStaticFlags); break; - case 163 /* PropertyDeclaration */: - addName(names, name, memberName, 3 /* GetOrSetAccessor */); + case 164 /* PropertyDeclaration */: + addName(names, name, memberName, 3 /* GetOrSetAccessor */ | privateStaticFlags); break; - case 165 /* MethodDeclaration */: - addName(names, name, memberName, 8 /* Method */); + case 166 /* MethodDeclaration */: + addName(names, name, memberName, 8 /* Method */ | privateStaticFlags); break; } } @@ -72997,16 +75216,25 @@ var ts; function addName(names, location, name, meaning) { var prev = names.get(name); if (prev) { - if (prev & 8 /* Method */) { - if (meaning !== 8 /* Method */) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); - } - } - else if (prev & meaning) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + // For private identifiers, do not allow mixing of static and instance members with the same name + if ((prev & 16 /* PrivateStatic */) !== (meaning & 16 /* PrivateStatic */)) { + error(location, ts.Diagnostics.Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name, ts.getTextOfNode(location)); } else { - names.set(name, prev | meaning); + var prevIsMethod = !!(prev & 8 /* Method */); + var isMethod = !!(meaning & 8 /* Method */); + if (prevIsMethod || isMethod) { + if (prevIsMethod !== isMethod) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + // If this is a method/method duplication is might be an overload, so this will be handled when overloads are considered + } + else if (prev & meaning & ~16 /* PrivateStatic */) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names.set(name, prev | meaning); + } } } else { @@ -73050,7 +75278,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 162 /* PropertySignature */) { + if (member.kind === 163 /* PropertySignature */) { var memberName = void 0; var name = member.name; switch (name.kind) { @@ -73075,11 +75303,11 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 253 /* InterfaceDeclaration */) { + if (node.kind === 254 /* InterfaceDeclaration */) { var nodeSymbol = getSymbolOfNode(node); // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration // to prevent this run check only for the first declaration of a given kind - if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + if (nodeSymbol.declarations && nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; } } @@ -73087,7 +75315,7 @@ var ts; // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); - if (indexSymbol) { + if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { var seenNumericIndexer = false; var seenStringIndexer = false; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -73121,11 +75349,9 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); - // Private class fields transformation relies on WeakMaps. - if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) { - for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) { - getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */; - } + setNodeLinksForPrivateIdentifierScope(node); + if (ts.isPrivateIdentifier(node.name) && ts.hasStaticModifier(node) && node.initializer && languageVersion === 99 /* ESNext */ && !compilerOptions.useDefineForClassFields) { + error(node.initializer, ts.Diagnostics.Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag); } } function checkPropertySignature(node) { @@ -73138,16 +75364,35 @@ var ts; // Grammar checking if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); - if (ts.isPrivateIdentifier(node.name)) { - error(node, ts.Diagnostics.A_method_cannot_be_named_with_a_private_identifier); - } // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (ts.hasSyntacticModifier(node, 128 /* Abstract */) && node.kind === 165 /* MethodDeclaration */ && node.body) { + if (ts.hasSyntacticModifier(node, 128 /* Abstract */) && node.kind === 166 /* MethodDeclaration */ && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } + // Private named methods are only allowed in class declarations + if (ts.isPrivateIdentifier(node.name) && !ts.getContainingClass(node)) { + error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + } + setNodeLinksForPrivateIdentifierScope(node); + } + function setNodeLinksForPrivateIdentifierScope(node) { + if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) { + for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) { + getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */; + } + // If this is a private element in a class expression inside the body of a loop, + // then we must use a block-scoped binding to store the additional variables required + // to transform private elements. + if (ts.isClassExpression(node.parent)) { + var enclosingIterationStatement = getEnclosingIterationStatement(node.parent); + if (enclosingIterationStatement) { + getNodeLinks(node.name).flags |= 524288 /* BlockScopedBindingInLoop */; + getNodeLinks(enclosingIterationStatement).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } + } + } } function checkConstructorDeclaration(node) { // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. @@ -73170,10 +75415,10 @@ var ts; return; } function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) { - if (ts.isPrivateIdentifierPropertyDeclaration(n)) { + if (ts.isPrivateIdentifierClassElementDeclaration(n)) { return true; } - return n.kind === 163 /* PropertyDeclaration */ && + return n.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(n, 32 /* Static */) && !!n.initializer; } @@ -73194,9 +75439,9 @@ var ts; // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) && + var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !useDefineForClassFields) && (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 92 /* ParameterPropertyModifier */); })); + ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */); })); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -73204,7 +75449,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) { var statement = statements_4[_i]; - if (statement.kind === 233 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 234 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -73229,7 +75474,7 @@ var ts; checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 167 /* GetAccessor */) { + if (node.kind === 168 /* GetAccessor */) { if (!(node.flags & 8388608 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 256 /* HasImplicitReturn */)) { if (!(node.flags & 512 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); @@ -73239,45 +75484,42 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } - if (ts.isPrivateIdentifier(node.name)) { - error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier); - } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. - var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; - var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); - if (otherAccessor) { - var nodeFlags = ts.getEffectiveModifierFlags(node); - var otherFlags = ts.getEffectiveModifierFlags(otherAccessor); - if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) { - error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + var symbol = getSymbolOfNode(node); + var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); + if (getter && setter && !(getNodeCheckFlags(getter) & 1 /* TypeChecked */)) { + getNodeLinks(getter).flags |= 1 /* TypeChecked */; + var getterFlags = ts.getEffectiveModifierFlags(getter); + var setterFlags = ts.getEffectiveModifierFlags(setter); + if ((getterFlags & 128 /* Abstract */) !== (setterFlags & 128 /* Abstract */)) { + error(getter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(setter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } + if (((getterFlags & 16 /* Protected */) && !(setterFlags & (16 /* Protected */ | 8 /* Private */))) || + ((getterFlags & 8 /* Private */) && !(setterFlags & 8 /* Private */))) { + error(getter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(setter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); } - if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) { - error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + var getterType = getAnnotatedAccessorType(getter); + var setterType = getAnnotatedAccessorType(setter); + if (getterType && setterType) { + checkTypeAssignableTo(getterType, setterType, getter, ts.Diagnostics.The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type); } - // TypeScript 1.0 spec (April 2014): 4.5 - // If both accessors include type annotations, the specified types must be identical. - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 167 /* GetAccessor */) { + if (node.kind === 168 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } checkSourceElement(node.body); - } - function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { - var firstType = getAnnotatedType(first); - var secondType = getAnnotatedType(second); - if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { - error(first, message); - } + setNodeLinksForPrivateIdentifierScope(node); } function checkMissingDeclaration(node) { checkDecorators(node); @@ -73314,7 +75556,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 173 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 174 /* 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); } ts.forEach(node.typeArguments, checkSourceElement); @@ -73329,7 +75571,7 @@ var ts; var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, getDeprecatedSuggestionNode(node), ts.Diagnostics._0_is_deprecated, symbol.escapedName); + addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 /* Enum */ && symbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); @@ -73367,7 +75609,7 @@ var ts; var hasNamedElement = ts.some(elementTypes, ts.isNamedTupleMember); for (var _i = 0, elementTypes_1 = elementTypes; _i < elementTypes_1.length; _i++) { var e = elementTypes_1[_i]; - if (e.kind !== 192 /* NamedTupleMember */ && hasNamedElement) { + if (e.kind !== 193 /* NamedTupleMember */ && hasNamedElement) { grammarErrorOnNode(e, ts.Diagnostics.Tuple_members_must_all_have_names_or_all_not_have_names); break; } @@ -73416,7 +75658,7 @@ var ts; var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { - if (accessNode.kind === 202 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + if (accessNode.kind === 203 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } @@ -73474,7 +75716,7 @@ var ts; ts.forEachChild(node, checkSourceElement); } function checkInferType(node) { - if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 184 /* ConditionalType */ && n.parent.extendsType === n; })) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 185 /* ConditionalType */ && n.parent.extendsType === n; })) { grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); @@ -73497,25 +75739,25 @@ var ts; if (node.dotDotDotToken && node.questionToken) { grammarErrorOnNode(node, ts.Diagnostics.A_tuple_member_cannot_be_both_optional_and_rest); } - if (node.type.kind === 180 /* OptionalType */) { + if (node.type.kind === 181 /* OptionalType */) { grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type); } - if (node.type.kind === 181 /* RestType */) { + if (node.type.kind === 182 /* RestType */) { grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type); } checkSourceElement(node.type); getTypeFromTypeNode(node); } function isPrivateWithinAmbient(node) { - return (ts.hasEffectiveModifier(node, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */); + return (ts.hasEffectiveModifier(node, 8 /* Private */) || ts.isPrivateIdentifierClassElementDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 253 /* InterfaceDeclaration */ && - n.parent.kind !== 252 /* ClassDeclaration */ && - n.parent.kind !== 221 /* ClassExpression */ && + if (n.parent.kind !== 254 /* InterfaceDeclaration */ && + n.parent.kind !== 253 /* ClassDeclaration */ && + n.parent.kind !== 222 /* ClassExpression */ && n.flags & 8388608 /* Ambient */) { if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { // It is nested in an ambient context, which means it is automatically exported @@ -73611,7 +75853,7 @@ var ts; // Both are literal property names that are the same. ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - var reportError = (node.kind === 165 /* MethodDeclaration */ || node.kind === 164 /* MethodSignature */) && + var reportError = (node.kind === 166 /* MethodDeclaration */ || node.kind === 165 /* MethodSignature */) && ts.hasSyntacticModifier(node, 32 /* Static */) !== ts.hasSyntacticModifier(subsequentNode, 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members @@ -73648,55 +75890,57 @@ var ts; var multipleConstructorImplementation = false; var hasNonAmbientClass = false; var functionDeclarations = []; - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var current = declarations_4[_i]; - var node = current; - var inAmbientContext = node.flags & 8388608 /* Ambient */; - var inAmbientContextOrInterface = node.parent && (node.parent.kind === 253 /* InterfaceDeclaration */ || node.parent.kind === 177 /* TypeLiteral */) || inAmbientContext; - if (inAmbientContextOrInterface) { - // check if declarations are consecutive only if they are non-ambient - // 1. ambient declarations can be interleaved - // i.e. this is legal - // declare function foo(); - // declare function bar(); - // declare function foo(); - // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one - previousDeclaration = undefined; - } - if ((node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */) && !inAmbientContext) { - hasNonAmbientClass = true; - } - if (node.kind === 251 /* FunctionDeclaration */ || node.kind === 165 /* MethodDeclaration */ || node.kind === 164 /* MethodSignature */ || node.kind === 166 /* Constructor */) { - functionDeclarations.push(node); - var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); - someNodeFlags |= currentNodeFlags; - allNodeFlags &= currentNodeFlags; - someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); - allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); - var bodyIsPresent = ts.nodeIsPresent(node.body); - if (bodyIsPresent && bodyDeclaration) { - if (isConstructor) { - multipleConstructorImplementation = true; + if (declarations) { + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; + var node = current; + var inAmbientContext = node.flags & 8388608 /* Ambient */; + var inAmbientContextOrInterface = node.parent && (node.parent.kind === 254 /* InterfaceDeclaration */ || node.parent.kind === 178 /* TypeLiteral */) || inAmbientContext; + if (inAmbientContextOrInterface) { + // check if declarations are consecutive only if they are non-ambient + // 1. ambient declarations can be interleaved + // i.e. this is legal + // declare function foo(); + // declare function bar(); + // declare function foo(); + // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one + previousDeclaration = undefined; + } + if ((node.kind === 253 /* ClassDeclaration */ || node.kind === 222 /* ClassExpression */) && !inAmbientContext) { + hasNonAmbientClass = true; + } + if (node.kind === 252 /* FunctionDeclaration */ || node.kind === 166 /* MethodDeclaration */ || node.kind === 165 /* MethodSignature */ || node.kind === 167 /* Constructor */) { + functionDeclarations.push(node); + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); + var bodyIsPresent = ts.nodeIsPresent(node.body); + if (bodyIsPresent && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } + } + else if ((previousDeclaration === null || previousDeclaration === void 0 ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (bodyIsPresent) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } } else { - duplicateFunctionDeclaration = true; + hasOverloads = true; } - } - else if ((previousDeclaration === null || previousDeclaration === void 0 ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) { - reportImplementationExpectedError(previousDeclaration); - } - if (bodyIsPresent) { - if (!bodyDeclaration) { - bodyDeclaration = node; + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; } } - else { - hasOverloads = true; - } - previousDeclaration = node; - if (!inAmbientContextOrInterface) { - lastSeenNonAmbientDeclaration = node; - } } } if (multipleConstructorImplementation) { @@ -73724,8 +75968,10 @@ var ts; reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { - checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); - checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (declarations) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + } if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); @@ -73799,43 +76045,46 @@ var ts; function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: // A jsdoc typedef and callback are, by definition, type aliases. // falls through - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return 2 /* ExportType */; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4 /* ExportNamespace */ | 1 /* ExportValue */ : 4 /* ExportNamespace */; - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: return 2 /* ExportType */ | 1 /* ExportValue */; - case 297 /* SourceFile */: + case 298 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: + case 217 /* BinaryExpression */: + var node_2 = d; + var expression = ts.isExportAssignment(node_2) ? node_2.expression : node_2.right; // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values - if (!ts.isEntityNameExpression(d.expression)) { + if (!ts.isEntityNameExpression(expression)) { return 1 /* ExportValue */; } - d = d.expression; + d = expression; // The below options all declare an Alias, which is allowed to merge with other values within the importing module. // falls through - case 260 /* ImportEqualsDeclaration */: - case 263 /* NamespaceImport */: - case 262 /* ImportClause */: - var result_12 = 0 /* None */; + case 261 /* ImportEqualsDeclaration */: + case 264 /* NamespaceImport */: + case 263 /* ImportClause */: + var result_13 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_12 |= getDeclarationSpaces(d); }); - return result_12; - case 249 /* VariableDeclaration */: - case 198 /* BindingElement */: - case 251 /* FunctionDeclaration */: - case 265 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + ts.forEach(target.declarations, function (d) { result_13 |= getDeclarationSpaces(d); }); + return result_13; + case 250 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 252 /* FunctionDeclaration */: + case 266 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 case 78 /* Identifier */: // https://github.com/microsoft/TypeScript/issues/36098 // Identifiers are used as declarations of assignment declarations whose parents may be // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});` @@ -74128,24 +76377,24 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 160 /* Parameter */: + case 161 /* Parameter */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -74192,15 +76441,15 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { - case 183 /* IntersectionType */: - case 182 /* UnionType */: + case 184 /* IntersectionType */: + case 183 /* UnionType */: return getEntityNameForDecoratorMetadataFromTypeList(node.types); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); - case 186 /* ParenthesizedType */: - case 192 /* NamedTupleMember */: + case 187 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: return getEntityNameForDecoratorMetadata(node.type); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return node.typeName; } } @@ -74209,13 +76458,13 @@ var ts; var commonEntityName; for (var _i = 0, types_23 = types; _i < types_23.length; _i++) { var typeNode = types_23[_i]; - while (typeNode.kind === 186 /* ParenthesizedType */ || typeNode.kind === 192 /* NamedTupleMember */) { + while (typeNode.kind === 187 /* ParenthesizedType */ || typeNode.kind === 193 /* NamedTupleMember */) { typeNode = typeNode.type; // Skip parens if need be } if (typeNode.kind === 141 /* NeverKeyword */) { continue; // Always elide `never` from the union/intersection if possible } - if (!strictNullChecks && (typeNode.kind === 191 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { + if (!strictNullChecks && (typeNode.kind === 192 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); @@ -74261,14 +76510,14 @@ var ts; } var firstDecorator = node.decorators[0]; checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); - if (node.kind === 160 /* Parameter */) { + if (node.kind === 161 /* Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* Param */); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -74277,23 +76526,23 @@ var ts; } } break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + var otherKind = node.kind === 168 /* GetAccessor */ ? 169 /* SetAccessor */ : 168 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 160 /* Parameter */: + case 161 /* Parameter */: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); var containingSignature = node.parent; for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { @@ -74356,7 +76605,7 @@ var ts; else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 157 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 158 /* QualifiedName */ ? node.name.right : node.name)); } } } @@ -74400,25 +76649,26 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return node.name; default: return undefined; } } function checkFunctionOrMethodDeclaration(node) { + var _a; checkDecorators(node); checkSignatureDeclaration(node); var functionFlags = ts.getFunctionFlags(node); // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name && node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 159 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // first we want to check the local symbol that contain this declaration // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode @@ -74427,7 +76677,7 @@ var ts; // Since the javascript won't do semantic analysis like typescript, // if the javascript file comes before the typescript file and both contain same name functions, // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. - var firstDeclaration = ts.find(localSymbol.declarations, + var firstDeclaration = (_a = localSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find( // Get first non javascript function declaration function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072 /* JavaScriptFile */); }); // Only type check the symbol once @@ -74439,7 +76689,7 @@ var ts; checkFunctionOrConstructorSymbol(symbol); } } - var body = node.kind === 164 /* MethodSignature */ ? undefined : node.body; + var body = node.kind === 165 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node)); if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { @@ -74481,42 +76731,42 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: checkUnusedClassMembers(node, addDiagnostic); checkUnusedTypeParameters(node, addDiagnostic); break; - case 297 /* SourceFile */: - case 256 /* ModuleDeclaration */: - case 230 /* Block */: - case 258 /* CaseBlock */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 298 /* SourceFile */: + case 257 /* ModuleDeclaration */: + case 231 /* Block */: + case 259 /* CaseBlock */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: checkUnusedLocalsAndParameters(node, addDiagnostic); break; - case 166 /* Constructor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 167 /* Constructor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: if (node.body) { // Don't report unused parameters in overloads checkUnusedLocalsAndParameters(node, addDiagnostic); } checkUnusedTypeParameters(node, addDiagnostic); break; - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: checkUnusedTypeParameters(node, addDiagnostic); break; - case 185 /* InferType */: + case 186 /* InferType */: checkUnusedInferTypeParameter(node, addDiagnostic); break; default: @@ -74536,11 +76786,11 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 165 /* MethodDeclaration */: - case 163 /* PropertyDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - if (member.kind === 168 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + case 166 /* MethodDeclaration */: + case 164 /* PropertyDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + if (member.kind === 169 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { // Already would have reported an error on the getter. break; } @@ -74551,7 +76801,7 @@ var ts; addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; - case 166 /* Constructor */: + case 167 /* Constructor */: for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasSyntacticModifier(parameter, 8 /* Private */)) { @@ -74559,8 +76809,8 @@ var ts; } } break; - case 171 /* IndexSignature */: - case 229 /* SemicolonClassElement */: + case 172 /* IndexSignature */: + case 230 /* SemicolonClassElement */: // Can't be private break; default: @@ -74577,7 +76827,8 @@ var ts; function checkUnusedTypeParameters(node, addDiagnostic) { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. - if (ts.last(getSymbolOfNode(node).declarations) !== node) + var declarations = getSymbolOfNode(node).declarations; + if (!declarations || ts.last(declarations) !== node) return; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); var seenParentsWithEveryUnused = new ts.Set(); @@ -74587,7 +76838,7 @@ var ts; continue; var name = ts.idText(typeParameter.name); var parent = typeParameter.parent; - if (parent.kind !== 185 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (parent.kind !== 186 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { if (ts.tryAddToSet(seenParentsWithEveryUnused, parent)) { var sourceFile = ts.getSourceFileOfNode(parent); var range = ts.isJSDocTemplateTag(parent) @@ -74623,11 +76874,15 @@ var ts; return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } function isValidUnusedLocalDeclaration(declaration) { - if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { - return !!ts.findAncestor(declaration.parent, function (ancestor) { - return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : - ts.isForOfStatement(ancestor) ? true : "quit"; - }); + if (ts.isBindingElement(declaration)) { + if (ts.isObjectBindingPattern(declaration.parent)) { + /** + * ignore starts with underscore names _ + * const { a: _a } = { a: 1 } + */ + return !!(declaration.propertyName && isIdentifierThatStartsWithUnderscore(declaration.name)); + } + return isIdentifierThatStartsWithUnderscore(declaration.name); } return ts.isAmbientModule(declaration) || (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); @@ -74643,39 +76898,41 @@ var ts; if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) { return; } - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (isValidUnusedLocalDeclaration(declaration)) { - continue; - } - if (isImportedDeclaration(declaration)) { - addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); - } - else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { - // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. - var lastElement = ts.last(declaration.parent.elements); - if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { - addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + if (local.declarations) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (isValidUnusedLocalDeclaration(declaration)) { + continue; } - } - else if (ts.isVariableDeclaration(declaration)) { - addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); - } - else { - var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); - var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); - if (parameter && name) { - if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { - if (ts.isBindingElement(declaration) && ts.isArrayBindingPattern(declaration.parent)) { - addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); - } - else { - addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); - } + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); } } + else if (ts.isVariableDeclaration(declaration)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } else { - errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); + if (parameter && name) { + if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { + if (ts.isBindingElement(declaration) && ts.isArrayBindingPattern(declaration.parent)) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + else { + addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); + } + } + } + else { + errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); + } } } } @@ -74685,7 +76942,7 @@ var ts; var importDecl = importClause.parent; var nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? - (importClause.namedBindings.kind === 263 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + (importClause.namedBindings.kind === 264 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 @@ -74703,7 +76960,7 @@ var ts; var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; if (bindingPattern.elements.length === bindingElements.length) { - if (bindingElements.length === 1 && bindingPattern.parent.kind === 249 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 250 /* VariableDeclarationList */) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 250 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 251 /* VariableDeclarationList */) { addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { @@ -74724,7 +76981,7 @@ var ts; if (declarationList.declarations.length === declarations.length) { addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) - : ts.createDiagnosticForNode(declarationList.parent.kind === 232 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + : ts.createDiagnosticForNode(declarationList.parent.kind === 233 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { @@ -74738,22 +76995,22 @@ var ts; switch (name.kind) { case 78 /* Identifier */: return ts.idText(name); - case 197 /* ArrayBindingPattern */: - case 196 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); default: return ts.Debug.assertNever(name); } } function isImportedDeclaration(node) { - return node.kind === 262 /* ImportClause */ || node.kind === 265 /* ImportSpecifier */ || node.kind === 263 /* NamespaceImport */; + return node.kind === 263 /* ImportClause */ || node.kind === 266 /* ImportSpecifier */ || node.kind === 264 /* NamespaceImport */; } function importClauseFromImported(decl) { - return decl.kind === 262 /* ImportClause */ ? decl : decl.kind === 263 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + return decl.kind === 263 /* ImportClause */ ? decl : decl.kind === 264 /* NamespaceImport */ ? decl.parent : decl.parent.parent; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 230 /* Block */) { + if (node.kind === 231 /* Block */) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -74783,12 +77040,12 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 163 /* PropertyDeclaration */ || - node.kind === 162 /* PropertySignature */ || - node.kind === 165 /* MethodDeclaration */ || - node.kind === 164 /* MethodSignature */ || - node.kind === 167 /* GetAccessor */ || - node.kind === 168 /* SetAccessor */) { + if (node.kind === 164 /* PropertyDeclaration */ || + node.kind === 163 /* PropertySignature */ || + node.kind === 166 /* MethodDeclaration */ || + node.kind === 165 /* MethodSignature */ || + node.kind === 168 /* GetAccessor */ || + node.kind === 169 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } @@ -74797,7 +77054,7 @@ var ts; return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 160 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 161 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -74834,10 +77091,11 @@ var ts; return false; }); } - function checkWeakMapCollision(node) { + function checkWeakMapSetCollision(node) { var enclosingBlockScope = ts.getEnclosingBlockScopeContainer(node); if (getNodeCheckFlags(enclosingBlockScope) & 67108864 /* ContainsClassWithPrivateIdentifiers */) { - errorSkippedOn("noEmit", node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, "WeakMap"); + ts.Debug.assert(ts.isNamedDeclaration(node) && ts.isIdentifier(node.name) && typeof node.name.escapedText === "string", "The target of a WeakMap/WeakSet collision check should be an identifier"); + errorSkippedOn("noEmit", node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, node.name.escapedText); } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { @@ -74854,7 +77112,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords errorSkippedOn("noEmit", name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -74869,7 +77127,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) { + if (parent.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. errorSkippedOn("noEmit", name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -74904,7 +77162,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 249 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 250 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -74916,17 +77174,17 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 250 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 232 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 251 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 233 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) var namesShareScope = container && - (container.kind === 230 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 257 /* ModuleBlock */ || - container.kind === 256 /* ModuleDeclaration */ || - container.kind === 297 /* SourceFile */); + (container.kind === 231 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 258 /* ModuleBlock */ || + container.kind === 257 /* ModuleDeclaration */ || + container.kind === 298 /* SourceFile */); // here we know that function scoped variable is shadowed by block scoped one // if they are defined in the same scope - binder has already reported redeclaration error // otherwise if variable has an initializer - show error that initialization will fail @@ -74957,18 +77215,18 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 198 /* BindingElement */) { - if (node.parent.kind === 196 /* ObjectBindingPattern */ && languageVersion < 99 /* ESNext */) { + if (ts.isBindingElement(node)) { + if (ts.isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < 5 /* ES2018 */) { checkExternalEmitHelpers(node, 4 /* Rest */); } // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 158 /* ComputedPropertyName */) { + if (node.propertyName && node.propertyName.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } // check private/protected variable access @@ -74981,15 +77239,15 @@ var ts; var nameText = getPropertyNameFromType(exprType); var property = getPropertyOfType(parentType, nameText); if (property) { - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 105 /* SuperKeyword */, parentType, property); + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isSelfTypeAccess*/ false); // A destructuring is never a write-only reference. + checkPropertyAccessibility(node, !!parent.initializer && parent.initializer.kind === 105 /* SuperKeyword */, /*writing*/ false, parentType, property); } } } } // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 197 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + if (node.name.kind === 198 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } ts.forEach(node.name.elements, checkSourceElement); @@ -75001,7 +77259,7 @@ var ts; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { - var needCheckInitializer = node.initializer && node.parent.parent.kind !== 238 /* ForInStatement */; + var needCheckInitializer = node.initializer && node.parent.parent.kind !== 239 /* ForInStatement */; var needCheckWidenedType = node.name.elements.length === 0; if (needCheckInitializer || needCheckWidenedType) { // Don't validate for-in initializer as it is already an error @@ -75029,7 +77287,7 @@ var ts; } // For a commonjs `const x = require`, validate the alias and exit var symbol = getSymbolOfNode(node); - if (symbol.flags & 2097152 /* Alias */ && ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true)) { + if (symbol.flags & 2097152 /* Alias */ && ts.isRequireVariableDeclaration(node)) { checkAliasSymbol(node); return; } @@ -75043,11 +77301,11 @@ var ts; ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && !!((_a = symbol.exports) === null || _a === void 0 ? void 0 : _a.size); - if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 238 /* ForInStatement */) { + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 239 /* ForInStatement */) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); } } - if (symbol.declarations.length > 1) { + if (symbol.declarations && symbol.declarations.length > 1) { if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) { error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } @@ -75065,26 +77323,27 @@ var ts; if (node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } - if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 163 /* PropertyDeclaration */ && node.kind !== 162 /* PropertySignature */) { + if (node.kind !== 164 /* PropertyDeclaration */ && node.kind !== 163 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) { + if (node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - if (languageVersion < 99 /* ESNext */ && needCollisionCheckForIdentifier(node, node.name, "WeakMap")) { - potentialWeakMapCollisions.push(node); + if (languageVersion < 99 /* ESNext */ + && (needCollisionCheckForIdentifier(node, node.name, "WeakMap") || needCollisionCheckForIdentifier(node, node.name, "WeakSet"))) { + potentialWeakMapSetCollisions.push(node); } } } function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) { var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); - var message = nextDeclaration.kind === 163 /* PropertyDeclaration */ || nextDeclaration.kind === 162 /* PropertySignature */ + var message = nextDeclaration.kind === 164 /* PropertyDeclaration */ || nextDeclaration.kind === 163 /* PropertySignature */ ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; var declName = ts.declarationNameToString(nextDeclarationName); @@ -75094,8 +77353,8 @@ var ts; } } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 160 /* Parameter */ && right.kind === 249 /* VariableDeclaration */) || - (left.kind === 249 /* VariableDeclaration */ && right.kind === 160 /* Parameter */)) { + if ((left.kind === 161 /* Parameter */ && right.kind === 250 /* VariableDeclaration */) || + (left.kind === 250 /* VariableDeclaration */ && right.kind === 161 /* Parameter */)) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -75111,10 +77370,10 @@ var ts; return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { - ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); checkGrammarVariableDeclaration(node); checkVariableLikeDeclaration(node); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkBindingElement(node) { checkGrammarBindingElement(node); @@ -75135,49 +77394,55 @@ var ts; // Grammar checking checkGrammarStatementInAmbientContext(node); var type = checkTruthinessExpression(node.expression); - checkTestingKnownTruthyCallableType(node.expression, type, node.thenStatement); + checkTestingKnownTruthyCallableOrAwaitableType(node.expression, type, node.thenStatement); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 231 /* EmptyStatement */) { + if (node.thenStatement.kind === 232 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); } - function checkTestingKnownTruthyCallableType(condExpr, type, body) { - if (!strictNullChecks) { + function checkTestingKnownTruthyCallableOrAwaitableType(condExpr, type, body) { + if (!strictNullChecks) + return; + if (getFalsyFlags(type)) return; - } var location = ts.isBinaryExpression(condExpr) ? condExpr.right : condExpr; var testedNode = ts.isIdentifier(location) ? location : ts.isPropertyAccessExpression(location) ? location.name : ts.isBinaryExpression(location) && ts.isIdentifier(location.right) ? location.right : undefined; - if (!testedNode) { - return; - } - var possiblyFalsy = getFalsyFlags(type); - if (possiblyFalsy) { + var isPropertyExpressionCast = ts.isPropertyAccessExpression(location) + && ts.isAssertionExpression(ts.skipParentheses(location.expression)); + if (!testedNode || isPropertyExpressionCast) { return; } // While it technically should be invalid for any known-truthy value - // to be tested, we de-scope to functions unrefenced in the block as a - // heuristic to identify the most common bugs. There are too many - // false positives for values sourced from type definitions without - // strictNullChecks otherwise. + // to be tested, we de-scope to functions and Promises unreferenced in + // the block as a heuristic to identify the most common bugs. There + // are too many false positives for values sourced from type + // definitions without strictNullChecks otherwise. var callSignatures = getSignaturesOfType(type, 0 /* Call */); - if (callSignatures.length === 0) { + var isPromise = !!getAwaitedTypeOfPromise(type); + if (callSignatures.length === 0 && !isPromise) { return; } var testedSymbol = getSymbolAtLocation(testedNode); if (!testedSymbol) { return; } - var isUsed = ts.isBinaryExpression(condExpr.parent) && isFunctionUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) - || body && isFunctionUsedInConditionBody(condExpr, body, testedNode, testedSymbol); + var isUsed = ts.isBinaryExpression(condExpr.parent) && isSymbolUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) + || body && isSymbolUsedInConditionBody(condExpr, body, testedNode, testedSymbol); if (!isUsed) { - error(location, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead); + if (isPromise) { + errorAndMaybeSuggestAwait(location, + /*maybeMissingAwait*/ true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, getTypeNameForErrorDisplay(type)); + } + else { + error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead); + } } } - function isFunctionUsedInConditionBody(expr, body, testedNode, testedSymbol) { + function isSymbolUsedInConditionBody(expr, body, testedNode, testedSymbol) { return !!ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); @@ -75214,7 +77479,7 @@ var ts; return ts.forEachChild(childNode, check); }); } - function isFunctionUsedInBinaryExpressionChain(node, testedSymbol) { + function isSymbolUsedInBinaryExpressionChain(node, testedSymbol) { while (ts.isBinaryExpression(node) && node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { var isUsed = ts.forEachChild(node.right, function visit(child) { if (ts.isIdentifier(child)) { @@ -75256,12 +77521,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 251 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer.kind === 251 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -75295,14 +77560,14 @@ var ts; // via checkRightHandSideOfForOf. // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. // Then check that the RHS is assignable to it. - if (node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer.kind === 251 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node); // There may be a destructuring assignment on the left side - if (varExpr.kind === 199 /* ArrayLiteralExpression */ || varExpr.kind === 200 /* ObjectLiteralExpression */) { + if (varExpr.kind === 200 /* ArrayLiteralExpression */ || varExpr.kind === 201 /* ObjectLiteralExpression */) { // iteratedType may be undefined. In this case, we still want to check the structure of // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like // to short circuit the type relation checking as much as possible, so we pass the unknownType. @@ -75334,7 +77599,7 @@ var ts; // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer.kind === 251 /* VariableDeclarationList */) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -75348,7 +77613,7 @@ var ts; // and Expr must be an expression of type Any, an object type, or a type parameter type. var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 199 /* ArrayLiteralExpression */ || varExpr.kind === 200 /* ObjectLiteralExpression */) { + if (varExpr.kind === 200 /* ArrayLiteralExpression */ || varExpr.kind === 201 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -75464,18 +77729,8 @@ var ts; // want to say that number is not an array type. But if the input was just // number and string input is allowed, we want to say that number is not an // array type or a string type. - var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined); - var _a = !(use & 4 /* AllowsStringInputFlag */) || hasStringConstituent - ? downlevelIteration - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] - : yieldType - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false] - : [ts.Diagnostics.Type_0_is_not_an_array_type, true] - : downlevelIteration - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] - : yieldType - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false] - : [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true], defaultDiagnostic = _a[0], maybeMissingAwait = _a[1]; + var allowsStrings = !!(use & 4 /* AllowsStringInputFlag */) && !hasStringConstituent; + var _a = getIterationDiagnosticDetails(allowsStrings, downlevelIteration), defaultDiagnostic = _a[0], maybeMissingAwait = _a[1]; errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType)); } return hasStringConstituent ? possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType : undefined; @@ -75489,6 +77744,40 @@ var ts; return getUnionType(possibleOutOfBounds ? [arrayElementType, stringType, undefinedType] : [arrayElementType, stringType], 2 /* Subtype */); } return (use & 128 /* PossiblyOutOfBounds */) ? includeUndefinedInIndexSignature(arrayElementType) : arrayElementType; + function getIterationDiagnosticDetails(allowsStrings, downlevelIteration) { + var _a; + if (downlevelIteration) { + return allowsStrings + ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] + : [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]; + } + var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined); + if (yieldType) { + return [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]; + } + if (isES2015OrLaterIterable((_a = inputType.symbol) === null || _a === void 0 ? void 0 : _a.escapedName)) { + return [ts.Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, true]; + } + return allowsStrings + ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true] + : [ts.Diagnostics.Type_0_is_not_an_array_type, true]; + } + } + function isES2015OrLaterIterable(n) { + switch (n) { + case "Float32Array": + case "Float64Array": + case "Int16Array": + case "Int32Array": + case "Int8Array": + case "NodeList": + case "Uint16Array": + case "Uint32Array": + case "Uint8Array": + case "Uint8ClampedArray": + return true; + } + return false; } /** * Gets the requested "iteration type" from an `Iterable`-like or `AsyncIterable`-like type. @@ -75732,6 +78021,11 @@ var ts; return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType)); } } + function getPropertyNameForKnownSymbolName(symbolName) { + var ctorType = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false); + var uniqueType = ctorType && getTypeOfPropertyOfType(getTypeOfSymbol(ctorType), ts.escapeLeadingUnderscores(symbolName)); + return uniqueType && isTypeUsableAsPropertyName(uniqueType) ? getPropertyNameFromType(uniqueType) : "__@" + symbolName; + } /** * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like * type from its members. @@ -75744,7 +78038,7 @@ var ts; */ function getIterationTypesOfIterableSlow(type, resolver, errorNode) { var _a; - var method = getPropertyOfType(type, ts.getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); + var method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); var methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : undefined; if (isTypeAny(methodType)) { return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); @@ -76043,12 +78337,12 @@ var ts; var functionFlags = ts.getFunctionFlags(func); if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - if (func.kind === 168 /* SetAccessor */) { + if (func.kind === 169 /* SetAccessor */) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 166 /* Constructor */) { + else if (func.kind === 167 /* Constructor */) { if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -76066,7 +78360,7 @@ var ts; } } } - else if (func.kind !== 166 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + else if (func.kind !== 167 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { // The function has a return type, but the return statement doesn't have an expression. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -76095,7 +78389,7 @@ var ts; var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 285 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 286 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -76104,7 +78398,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 284 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 285 /* CaseClause */) { // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable // to or from the type of the 'switch' expression. @@ -76136,7 +78430,7 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 245 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + if (current.kind === 246 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } @@ -76166,10 +78460,11 @@ var ts; // Grammar checking if (catchClause.variableDeclaration) { var declaration = catchClause.variableDeclaration; - if (declaration.type) { + var typeNode = ts.getEffectiveTypeAnnotationNode(ts.getRootDeclaration(declaration)); + if (typeNode) { var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ false); if (type && !(type.flags & 3 /* AnyOrUnknown */)) { - grammarErrorOnFirstToken(declaration.type, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified); + grammarErrorOnFirstToken(typeNode, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified); } } else if (declaration.initializer) { @@ -76180,7 +78475,7 @@ var ts; if (blockLocals_1) { ts.forEachKey(catchClause.locals, function (caughtName) { var blockLocal = blockLocals_1.get(caughtName); - if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { + if ((blockLocal === null || blockLocal === void 0 ? void 0 : blockLocal.valueDeclaration) && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); } }); @@ -76193,25 +78488,28 @@ var ts; checkBlock(node.finallyBlock); } } - function checkIndexConstraints(type) { - var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); - var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); + function checkIndexConstraints(type, isStatic) { + var _a, _b, _c, _d; + var declaredNumberIndexer = getIndexDeclarationOfSymbolTable(isStatic ? (_a = type.symbol) === null || _a === void 0 ? void 0 : _a.exports : (_b = type.symbol) === null || _b === void 0 ? void 0 : _b.members, 1 /* Number */); + var declaredStringIndexer = getIndexDeclarationOfSymbolTable(isStatic ? (_c = type.symbol) === null || _c === void 0 ? void 0 : _c.exports : (_d = type.symbol) === null || _d === void 0 ? void 0 : _d.members, 0 /* String */); var stringIndexType = getIndexTypeOfType(type, 0 /* String */); var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); if (stringIndexType || numberIndexType) { ts.forEach(getPropertiesOfObjectType(type), function (prop) { + if (isStatic && prop.flags & 4194304 /* Prototype */) + return; var propType = getTypeOfSymbol(prop); checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); var classDeclaration = type.symbol.valueDeclaration; - if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) { - for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { - var member = _a[_i]; + if (ts.getObjectFlags(type) & 1 /* Class */ && classDeclaration && ts.isClassLike(classDeclaration)) { + for (var _i = 0, _e = classDeclaration.members; _i < _e.length; _i++) { + var member = _e[_i]; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!ts.hasSyntacticModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) { + if (!ts.hasSyntacticModifier(member, 32 /* Static */) && !hasBindableName(member)) { var symbol = getSymbolOfNode(member); var propType = getTypeOfSymbol(symbol); checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); @@ -76226,7 +78524,7 @@ var ts; // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); - errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + errorNode = someBaseTypeHasBothIndexers || !type.symbol.declarations ? undefined : type.symbol.declarations[0]; } } if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217 @@ -76250,8 +78548,8 @@ var ts; // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; if (propDeclaration && name && - (propDeclaration.kind === 216 /* BinaryExpression */ || - name.kind === 158 /* ComputedPropertyName */ || + (propDeclaration.kind === 217 /* BinaryExpression */ || + name.kind === 159 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } @@ -76263,7 +78561,7 @@ var ts; // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); - errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + errorNode = someBaseClassHasBothPropertyAndIndexer || !containingType.symbol.declarations ? undefined : containingType.symbol.declarations[0]; } if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { var errorMessage = indexKind === 0 /* String */ @@ -76279,6 +78577,7 @@ var ts; switch (name.escapedText) { case "any": case "unknown": + case "never": case "number": case "bigint": case "boolean": @@ -76328,7 +78627,7 @@ var ts; function checkTypeParametersNotReferenced(root, typeParameters, index) { visit(root); function visit(node) { - if (node.kind === 173 /* TypeReference */) { + if (node.kind === 174 /* TypeReference */) { var type = getTypeFromTypeReference(node); if (type.flags & 262144 /* TypeParameter */) { for (var i = index; i < typeParameters.length; i++) { @@ -76343,14 +78642,14 @@ var ts; } /** Check that type parameter lists are identical across multiple declarations */ function checkTypeParameterListsIdentical(symbol) { - if (symbol.declarations.length === 1) { + if (symbol.declarations && symbol.declarations.length === 1) { return; } var links = getSymbolLinks(symbol); if (!links.typeParametersChecked) { links.typeParametersChecked = true; var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); - if (declarations.length <= 1) { + if (!declarations || declarations.length <= 1) { return; } var type = getDeclaredTypeOfSymbol(symbol); @@ -76414,6 +78713,9 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { + if (ts.some(node.decorators) && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { + grammarErrorOnNode(node.decorators[0], ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); + } if (!node.name && !ts.hasSyntacticModifier(node, 512 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } @@ -76442,7 +78744,8 @@ var ts; checkFunctionOrConstructorSymbol(symbol); checkClassForDuplicateDeclarations(node); // Only check for reserved static identifiers on non-ambient context. - if (!(node.flags & 8388608 /* Ambient */)) { + var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + if (!nodeInAmbientContext) { checkClassForStaticPropertyNameConflicts(node); } var baseTypeNode = ts.getEffectiveBaseTypeNode(node); @@ -76502,6 +78805,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } + checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { @@ -76531,14 +78835,76 @@ var ts; } if (produceDiagnostics) { checkIndexConstraints(type); + checkIndexConstraints(staticType, /*isStatic*/ true); checkTypeForDuplicateIndexSignatures(node); checkPropertyInitialization(node); } } + function checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType) { + var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); + var baseTypes = baseTypeNode && getBaseTypes(type); + var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; + var baseStaticType = getBaseConstructorTypeOfClass(type); + var _loop_24 = function (member) { + if (ts.hasAmbientModifier(member)) { + return "continue"; + } + if (ts.isConstructorDeclaration(member)) { + ts.forEach(member.parameters, function (param) { + if (ts.isParameterPropertyDeclaration(param, member)) { + checkClassMember(param, /*memberIsParameterProperty*/ true); + } + }); + } + checkClassMember(member); + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_24(member); + } + function checkClassMember(member, memberIsParameterProperty) { + var hasOverride = ts.hasOverrideModifier(member); + var hasStatic = ts.hasStaticModifier(member); + if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (!declaredProp) { + return; + } + var thisType = hasStatic ? staticType : typeWithThis; + var baseType = hasStatic ? baseStaticType : baseWithThis; + var prop = getPropertyOfType(thisType, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseType, declaredProp.escapedName); + var baseClassName = typeToString(baseWithThis); + if (prop && !baseProp && hasOverride) { + error(member, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); + } + else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.valueDeclaration) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { + var baseHasAbstract = ts.hasAbstractModifier(baseProp.valueDeclaration); + if (hasOverride) { + return; + } + if (!baseHasAbstract) { + var diag = memberIsParameterProperty ? + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : + ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; + error(member, diag, baseClassName); + } + else if (ts.hasAbstractModifier(member) && baseHasAbstract) { + error(member, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); + } + } + } + else if (hasOverride) { + var className = typeToString(type); + error(member, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, className); + } + } + } 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_23 = function (member) { + var _loop_25 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -76557,7 +78923,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_23(member); + _loop_25(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -76583,7 +78949,7 @@ var ts; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 252 /* ClassDeclaration */ || d.kind === 253 /* InterfaceDeclaration */; + return d.kind === 253 /* ClassDeclaration */ || d.kind === 254 /* InterfaceDeclaration */; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -76600,6 +78966,7 @@ var ts; // but not by other kinds of members. // Base class instance member variables and accessors can be overridden by // derived class instance member variables and accessors, but not by other kinds of members. + var _a, _b; // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfType(baseType); basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { @@ -76628,8 +78995,8 @@ var ts; // Searches other base types for a declaration that would satisfy the inherited abstract member. // (The class may have more than one base type via declaration merging with an interface with the // same name.) - for (var _a = 0, _b = getBaseTypes(type); _a < _b.length; _a++) { - var otherBaseType = _b[_a]; + for (var _c = 0, _d = getBaseTypes(type); _c < _d.length; _c++) { + var otherBaseType = _d[_c]; if (otherBaseType === baseType) continue; var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName); @@ -76638,7 +79005,7 @@ var ts; continue basePropertyCheck; } } - if (derivedClassDecl.kind === 221 /* ClassExpression */) { + if (derivedClassDecl.kind === 222 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -76659,7 +79026,7 @@ var ts; if (basePropertyFlags && derivedPropertyFlags) { // property/accessor is overridden with property/accessor if (baseDeclarationFlags & 128 /* Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer) - || base.valueDeclaration && base.valueDeclaration.parent.kind === 253 /* InterfaceDeclaration */ + || base.valueDeclaration && base.valueDeclaration.parent.kind === 254 /* InterfaceDeclaration */ || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) { // when the base property is abstract or from an interface, base/derived flags don't need to match // same when the derived property is from an assignment @@ -76673,13 +79040,13 @@ var ts; ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } - else if (compilerOptions.useDefineForClassFields) { - var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 163 /* PropertyDeclaration */ && !d.initializer; }); + else if (useDefineForClassFields) { + var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 164 /* PropertyDeclaration */ && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432 /* Transient */) && !(baseDeclarationFlags & 128 /* Abstract */) && !(derivedDeclarationFlags & 128 /* Abstract */) - && !derived.declarations.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); })) { + && !((_b = derived.declarations) === null || _b === void 0 ? void 0 : _b.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); }))) { var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol)); var propName = uninitialized.name; if (uninitialized.exclamationToken @@ -76790,7 +79157,7 @@ var ts; } } function isInstancePropertyWithoutInitializer(node) { - return node.kind === 163 /* PropertyDeclaration */ && + return node.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(node, 32 /* Static */ | 128 /* Abstract */) && !node.exclamationToken && !node.initializer; @@ -76814,7 +79181,7 @@ var ts; var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 253 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 254 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -76933,7 +79300,7 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: var value_2 = evaluate(expr.operand); if (typeof value_2 === "number") { switch (expr.operator) { @@ -76943,7 +79310,7 @@ var ts; } } break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { @@ -76972,7 +79339,7 @@ var ts; case 8 /* NumericLiteral */: checkGrammarNumericLiteral(expr); return +expr.text; - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return evaluate(expr.expression); case 78 /* Identifier */: var identifier = expr; @@ -76980,14 +79347,14 @@ var ts; return +(identifier.escapedText); } return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); - case 202 /* ElementAccessExpression */: - case 201 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384 /* Enum */) { var name = void 0; - if (ex.kind === 201 /* PropertyAccessExpression */) { + if (ex.kind === 202 /* PropertyAccessExpression */) { name = ex.name.escapedText; } else { @@ -77005,7 +79372,7 @@ var ts; if (memberSymbol) { var declaration = memberSymbol.valueDeclaration; if (declaration !== member) { - if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + if (declaration && isBlockScopedNameDeclaredBeforeUse(declaration, member)) { return getEnumMemberValue(declaration); } error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); @@ -77020,8 +79387,8 @@ var ts; } function isConstantMemberAccess(node) { return node.kind === 78 /* Identifier */ || - node.kind === 201 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || - node.kind === 202 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.kind === 202 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 203 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && ts.isStringLiteralLike(node.argumentExpression); } function checkEnumDeclaration(node) { @@ -77045,7 +79412,7 @@ var ts; var enumSymbol = getSymbolOfNode(node); var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); if (node === firstDeclaration) { - if (enumSymbol.declarations.length > 1) { + if (enumSymbol.declarations && enumSymbol.declarations.length > 1) { var enumIsConst_1 = ts.isEnumConst(node); // check that const is placed\omitted on all enum declarations ts.forEach(enumSymbol.declarations, function (decl) { @@ -77057,7 +79424,7 @@ var ts; var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 255 /* EnumDeclaration */) { + if (declaration.kind !== 256 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -77083,12 +79450,14 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; - if ((declaration.kind === 252 /* ClassDeclaration */ || - (declaration.kind === 251 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && - !(declaration.flags & 8388608 /* Ambient */)) { - return declaration; + if (declarations) { + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 253 /* ClassDeclaration */ || + (declaration.kind === 252 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 8388608 /* Ambient */)) { + return declaration; + } } } return undefined; @@ -77136,8 +79505,9 @@ var ts; // The following checks only apply on a non-ambient instantiated module declaration. if (symbol.flags & 512 /* ValueModule */ && !inAmbientContext + && symbol.declarations && symbol.declarations.length > 1 - && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions))) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -77149,7 +79519,7 @@ var ts; } // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. - var mergedClass = ts.getDeclarationOfKind(symbol, 252 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 253 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -77198,40 +79568,41 @@ var ts; } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { + var _a; switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // error each individual name in variable statement instead of marking the entire variable statement - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; + for (var _i = 0, _b = node.declarationList.declarations; _i < _b.length; _i++) { + var decl = _b[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 266 /* ExportAssignment */: - case 267 /* ExportDeclaration */: + case 267 /* ExportAssignment */: + case 268 /* ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 260 /* ImportEqualsDeclaration */: - case 261 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 198 /* BindingElement */: - case 249 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 250 /* VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { - for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { - var el = _c[_b]; + for (var _c = 0, _d = name.elements; _c < _d.length; _c++) { + var el = _d[_c]; // mark individual names in binding pattern checkModuleAugmentationElement(el, isGlobalAugmentation); } break; } // falls through - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 251 /* FunctionDeclaration */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 252 /* FunctionDeclaration */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } @@ -77244,7 +79615,7 @@ var ts; var reportError = !(symbol.flags & 33554432 /* Transient */); if (!reportError) { // symbol should not originate in augmentation - reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + reportError = !!((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.declarations) && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); } } break; @@ -77254,12 +79625,12 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: do { node = node.left; } while (node.kind !== 78 /* Identifier */); return node; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: do { if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) { return node.name; @@ -77279,9 +79650,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 257 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 297 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 267 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 258 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 298 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 268 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -77301,6 +79672,7 @@ var ts; return true; } function checkAliasSymbol(node) { + var _a; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { @@ -77315,21 +79687,21 @@ var ts; (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 270 /* ExportSpecifier */ ? + var message = node.kind === 271 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules - && node.kind === 270 /* ExportSpecifier */ + && node.kind === 271 /* ExportSpecifier */ && !node.parent.parent.isTypeOnly && !(target.flags & 111551 /* Value */) && !(node.flags & 8388608 /* Ambient */)) { error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type); } - if (ts.isImportSpecifier(node) && ts.every(target.declarations, function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, node.name, ts.Diagnostics._0_is_deprecated, symbol.escapedName); + if (ts.isImportSpecifier(node) && ((_a = target.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); }))) { + addDeprecatedSuggestion(node.name, target.declarations, symbol.escapedName); } } } @@ -77337,7 +79709,7 @@ var ts; checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkAliasSymbol(node); - if (node.kind === 265 /* ImportSpecifier */ && + if (node.kind === 266 /* ImportSpecifier */ && ts.idText(node.propertyName || node.name) === "default" && compilerOptions.esModuleInterop && moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) { @@ -77359,7 +79731,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 263 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 264 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015 && compilerOptions.esModuleInterop) { // import * as ns from "foo"; @@ -77387,7 +79759,7 @@ var ts; if (ts.hasSyntacticModifier(node, 1 /* Export */)) { markExportAsReferenced(node); } - if (node.moduleReference.kind !== 272 /* ExternalModuleReference */) { + if (node.moduleReference.kind !== 273 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { if (target.flags & 111551 /* Value */) { @@ -77430,10 +79802,10 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 257 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 257 /* ModuleBlock */ && + var inAmbientExternalModule = node.parent.kind === 258 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 258 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 8388608 /* Ambient */; - if (node.parent.kind !== 297 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + if (node.parent.kind !== 298 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -77466,14 +79838,14 @@ var ts; } function checkGrammarExportDeclaration(node) { var _a; - var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 268 /* NamedExports */; + var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 269 /* NamedExports */; if (isTypeOnlyExportStar) { grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type); } return !isTypeOnlyExportStar; } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 297 /* SourceFile */ || node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 256 /* ModuleDeclaration */; + var isInAppropriateContext = node.parent.kind === 298 /* SourceFile */ || node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 257 /* ModuleDeclaration */; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -77523,7 +79895,7 @@ var ts; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { @@ -77544,12 +79916,15 @@ var ts; } } function checkExportAssignment(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + var illegalContextMessage = node.isExportEquals + ? ts.Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration + : ts.Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration; + if (checkGrammarModuleElementContext(node, illegalContextMessage)) { // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 297 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 256 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 298 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 257 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -77609,7 +79984,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { + if (declaration && !isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -77633,10 +80008,12 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + if (!isDuplicatedCommonJSExport(declarations)) { + for (var _i = 0, _b = declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } } } } @@ -77645,6 +80022,11 @@ var ts; links.exportsChecked = true; } } + function isDuplicatedCommonJSExport(declarations) { + return declarations + && declarations.length > 1 + && declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && (ts.isExportsIdentifier(d.expression) || ts.isModuleExportsAccessExpression(d.expression)); }); + } function checkSourceElement(node) { if (node) { var saveCurrentNode = currentNode; @@ -77666,171 +80048,171 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 251 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } - if (kind >= 232 /* FirstStatement */ && kind <= 248 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) { + if (kind >= 233 /* FirstStatement */ && kind <= 249 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) { errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected); } switch (kind) { - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return checkTypeParameter(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return checkParameter(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return checkPropertyDeclaration(node); - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: return checkPropertySignature(node); - case 175 /* ConstructorType */: - case 174 /* FunctionType */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 176 /* ConstructorType */: + case 175 /* FunctionType */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return checkSignatureDeclaration(node); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: return checkMethodDeclaration(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return checkConstructorDeclaration(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return checkAccessorDeclaration(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return checkTypeReferenceNode(node); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return checkTypePredicate(node); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return checkTypeQuery(node); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return checkTypeLiteral(node); - case 178 /* ArrayType */: + case 179 /* ArrayType */: return checkArrayType(node); - case 179 /* TupleType */: + case 180 /* TupleType */: return checkTupleType(node); - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 186 /* ParenthesizedType */: - case 180 /* OptionalType */: - case 181 /* RestType */: + case 187 /* ParenthesizedType */: + case 181 /* OptionalType */: + case 182 /* RestType */: return checkSourceElement(node.type); - case 187 /* ThisType */: + case 188 /* ThisType */: return checkThisType(node); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return checkTypeOperator(node); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return checkConditionalType(node); - case 185 /* InferType */: + case 186 /* InferType */: return checkInferType(node); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: return checkTemplateLiteralType(node); - case 195 /* ImportType */: + case 196 /* ImportType */: return checkImportType(node); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return checkNamedTupleMember(node); - case 315 /* JSDocAugmentsTag */: + case 318 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 316 /* JSDocImplementsTag */: + case 319 /* JSDocImplementsTag */: return checkJSDocImplementsTag(node); - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return checkJSDocTypeAliasTag(node); - case 330 /* JSDocTemplateTag */: + case 334 /* JSDocTemplateTag */: return checkJSDocTemplateTag(node); - case 329 /* JSDocTypeTag */: + case 333 /* JSDocTypeTag */: return checkJSDocTypeTag(node); - case 326 /* JSDocParameterTag */: + case 330 /* JSDocParameterTag */: return checkJSDocParameterTag(node); - case 333 /* JSDocPropertyTag */: + case 337 /* JSDocPropertyTag */: return checkJSDocPropertyTag(node); - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: checkJSDocFunctionType(node); // falls through - case 306 /* JSDocNonNullableType */: - case 305 /* JSDocNullableType */: - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: - case 312 /* JSDocTypeLiteral */: + case 307 /* JSDocNonNullableType */: + case 306 /* JSDocNullableType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: + case 314 /* JSDocTypeLiteral */: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 309 /* JSDocVariadicType */: + case 310 /* JSDocVariadicType */: checkJSDocVariadicType(node); return; - case 301 /* JSDocTypeExpression */: + case 302 /* JSDocTypeExpression */: return checkSourceElement(node.type); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return checkIndexedAccessType(node); - case 190 /* MappedType */: + case 191 /* MappedType */: return checkMappedType(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 230 /* Block */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 258 /* ModuleBlock */: return checkBlock(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return checkVariableStatement(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return checkExpressionStatement(node); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return checkIfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return checkDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return checkWhileStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return checkForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return checkForInStatement(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return checkForOfStatement(node); - case 240 /* ContinueStatement */: - case 241 /* BreakStatement */: + case 241 /* ContinueStatement */: + case 242 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return checkReturnStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return checkWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return checkSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return checkLabeledStatement(node); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return checkThrowStatement(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return checkTryStatement(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return checkBindingElement(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return checkClassDeclaration(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return checkImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return checkExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return checkExportAssignment(node); - case 231 /* EmptyStatement */: - case 248 /* DebuggerStatement */: + case 232 /* EmptyStatement */: + case 249 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 271 /* MissingDeclaration */: + case 272 /* MissingDeclaration */: return checkMissingDeclaration(node); } } @@ -77875,7 +80257,8 @@ var ts; if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. var host_1 = ts.getHostSignatureFromJSDoc(paramTag); - if (host_1) { + var isCallbackTag = ts.isJSDocCallbackTag(paramTag.parent.parent); + if (host_1 || isCallbackTag) { /* Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. So in the following situation we will not create an array type: @@ -77883,7 +80266,9 @@ var ts; function f(a) {} Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. */ - var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var lastParamDeclaration = isCallbackTag + ? ts.lastOrUndefined(paramTag.parent.parent.typeExpression.parameters) + : ts.lastOrUndefined(host_1.parameters); var symbol = ts.getParameterSymbolFromJSDoc(paramTag); if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { @@ -77921,51 +80306,51 @@ var ts; } } function checkDeferredNode(node) { - ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; switch (node.kind) { - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 205 /* TaggedTemplateExpression */: - case 161 /* Decorator */: - case 275 /* JsxOpeningElement */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 206 /* TaggedTemplateExpression */: + case 162 /* Decorator */: + case 276 /* JsxOpeningElement */: // These node kinds are deferred checked when overload resolution fails // To save on work, we ensure the arguments are checked just once, in // a deferred way resolveUntypedCall(node); break; - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: checkAccessorDeclaration(node); break; - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: checkClassExpressionDeferred(node); break; - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: checkJsxSelfClosingElementDeferred(node); break; - case 273 /* JsxElement */: + case 274 /* JsxElement */: checkJsxElementDeferred(node); break; } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkSourceFile(node) { - ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeCheck"); checkSourceFileWorker(node); ts.performance.mark("afterCheck"); ts.performance.measure("Check", "beforeCheck", "afterCheck"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function unusedIsError(kind, isAmbient) { if (isAmbient) { @@ -77994,7 +80379,7 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - ts.clear(potentialWeakMapCollisions); + ts.clear(potentialWeakMapSetCollisions); ts.forEach(node.statements, checkSourceElement); checkSourceElement(node.endOfFileToken); checkDeferredNodes(node); @@ -78024,9 +80409,9 @@ var ts; ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); ts.clear(potentialNewTargetCollisions); } - if (potentialWeakMapCollisions.length) { - ts.forEach(potentialWeakMapCollisions, checkWeakMapCollision); - ts.clear(potentialWeakMapCollisions); + if (potentialWeakMapSetCollisions.length) { + ts.forEach(potentialWeakMapSetCollisions, checkWeakMapSetCollision); + ts.clear(potentialWeakMapSetCollisions); } links.flags |= 1 /* TypeChecked */; } @@ -78098,17 +80483,17 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 297 /* SourceFile */: - if (!ts.isExternalOrCommonJsModule(location)) + case 298 /* SourceFile */: + if (!ts.isExternalModule(location)) break; // falls through - case 256 /* ModuleDeclaration */: - copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); + case 257 /* ModuleDeclaration */: + copyLocallyVisibleExportSymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); @@ -78116,8 +80501,8 @@ var ts; // this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration. // falls through - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: // If we didn't come from static member of class or interface, // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. @@ -78126,7 +80511,7 @@ var ts; copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968 /* Type */); } break; - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -78166,6 +80551,16 @@ var ts; }); } } + function copyLocallyVisibleExportSymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + // Similar condition as in `resolveNameHelper` + if (!ts.getDeclarationOfKind(symbol, 271 /* ExportSpecifier */) && !ts.getDeclarationOfKind(symbol, 270 /* NamespaceExport */)) { + copySymbol(symbol, meaning); + } + }); + } + } } function isTypeDeclarationName(name) { return name.kind === 78 /* Identifier */ && @@ -78174,19 +80569,19 @@ var ts; } function isTypeDeclaration(node) { switch (node.kind) { - case 159 /* TypeParameter */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 160 /* TypeParameter */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return true; - case 262 /* ImportClause */: + case 263 /* ImportClause */: return node.isTypeOnly; - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return node.parent.parent.isTypeOnly; default: return false; @@ -78194,25 +80589,25 @@ var ts; } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(node) { - while (node.parent.kind === 157 /* QualifiedName */) { + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 173 /* TypeReference */; + return node.parent.kind === 174 /* TypeReference */; } function isHeritageClauseElementIdentifier(node) { - while (node.parent.kind === 201 /* PropertyAccessExpression */) { + while (node.parent.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 223 /* ExpressionWithTypeArguments */; + return node.parent.kind === 224 /* ExpressionWithTypeArguments */; } - function isJSDocEntryNameReference(node) { - while (node.parent.kind === 157 /* QualifiedName */) { + function getJSDocEntryNameReference(node) { + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } - while (node.parent.kind === 201 /* PropertyAccessExpression */) { + while (node.parent.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 302 /* JSDocNameReference */; + return ts.isJSDocNameReference(node.parent) ? node.parent : undefined; } function forEachEnclosingClass(node, callback) { var result; @@ -78240,13 +80635,13 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 157 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 158 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 260 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 261 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } - if (nodeOnRightSide.parent.kind === 266 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 267 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; @@ -78272,7 +80667,7 @@ var ts; node = parent; parent = parent.parent; } - if (parent && parent.kind === 195 /* ImportType */ && parent.qualifier === node) { + if (parent && parent.kind === 196 /* ImportType */ && parent.qualifier === node) { return parent; } return undefined; @@ -78282,7 +80677,7 @@ var ts; return getSymbolOfNode(name.parent); } if (ts.isInJSFile(name) && - name.parent.kind === 201 /* PropertyAccessExpression */ && + name.parent.kind === 202 /* PropertyAccessExpression */ && name.parent === name.parent.parent.left) { // Check if this is a special property assignment if (!ts.isPrivateIdentifier(name)) { @@ -78292,7 +80687,7 @@ var ts; } } } - if (name.parent.kind === 266 /* ExportAssignment */ && ts.isEntityNameExpression(name)) { + if (name.parent.kind === 267 /* ExportAssignment */ && ts.isEntityNameExpression(name)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(name, /*all meanings*/ 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); @@ -78302,7 +80697,7 @@ var ts; } else if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name) && isInRightSideOfImportOrExportAssignment(name)) { // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(name, 260 /* ImportEqualsDeclaration */); + var importEqualsDeclaration = ts.getAncestor(name, 261 /* ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true); } @@ -78320,7 +80715,7 @@ var ts; if (isHeritageClauseElementIdentifier(name)) { var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. - if (name.parent.kind === 223 /* ExpressionWithTypeArguments */) { + if (name.parent.kind === 224 /* ExpressionWithTypeArguments */) { meaning = 788968 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) { @@ -78336,10 +80731,10 @@ var ts; return entityNameSymbol; } } - if (name.parent.kind === 326 /* JSDocParameterTag */) { + if (name.parent.kind === 330 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(name.parent); } - if (name.parent.kind === 159 /* TypeParameter */ && name.parent.parent.kind === 330 /* JSDocTemplateTag */) { + if (name.parent.kind === 160 /* TypeParameter */ && name.parent.parent.kind === 334 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(name.parent); return typeParameter && typeParameter.symbol; @@ -78356,36 +80751,56 @@ var ts; } return resolveEntityName(name, 111551 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (name.kind === 201 /* PropertyAccessExpression */ || name.kind === 157 /* QualifiedName */) { + else if (name.kind === 202 /* PropertyAccessExpression */ || name.kind === 158 /* QualifiedName */) { var links = getNodeLinks(name); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (name.kind === 201 /* PropertyAccessExpression */) { - checkPropertyAccessExpression(name); + if (name.kind === 202 /* PropertyAccessExpression */) { + checkPropertyAccessExpression(name, 0 /* Normal */); } else { - checkQualifiedName(name); + checkQualifiedName(name, 0 /* Normal */); } return links.resolvedSymbol; } } else if (isTypeReferenceIdentifier(name)) { - var meaning = name.parent.kind === 173 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */; + var meaning = name.parent.kind === 174 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */; return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (isJSDocEntryNameReference(name)) { + var jsdocReference = getJSDocEntryNameReference(name); + if (jsdocReference || ts.isJSDocLink(name.parent)) { var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */; - return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); + var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ false, ts.getHostSignatureFromJSDoc(name)); + if (symbol) { + return symbol; + } + else if (ts.isQualifiedName(name) && ts.isIdentifier(name.left)) { + // resolve C.m as a static member first + var links = getNodeLinks(name); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + checkQualifiedName(name, 0 /* Normal */); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + // then resolve it as an instance member + var s = resolveEntityName(name.left, meaning, /*ignoreErrors*/ false); + if (s) { + var t = getDeclaredTypeOfSymbol(s); + return getPropertyOfType(t, name.right.escapedText); + } + } } - if (name.parent.kind === 172 /* TypePredicate */) { + if (name.parent.kind === 173 /* TypePredicate */) { return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */); } - // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node, ignoreErrors) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } var parent = node.parent; @@ -78408,8 +80823,8 @@ var ts; if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfNameOrPropertyAccessExpression(node); } - else if (parent.kind === 198 /* BindingElement */ && - grandParent.kind === 196 /* ObjectBindingPattern */ && + else if (parent.kind === 199 /* BindingElement */ && + grandParent.kind === 197 /* ObjectBindingPattern */ && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); @@ -78421,8 +80836,8 @@ var ts; switch (node.kind) { case 78 /* Identifier */: case 79 /* PrivateIdentifier */: - case 201 /* PropertyAccessExpression */: - case 157 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: return getSymbolOfNameOrPropertyAccessExpression(node); case 107 /* ThisKeyword */: var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); @@ -78436,14 +80851,14 @@ var ts; return checkExpression(node).symbol; } // falls through - case 187 /* ThisType */: + case 188 /* ThisType */: return getTypeFromThisTypeNode(node).symbol; case 105 /* SuperKeyword */: return checkExpression(node).symbol; case 132 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 166 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 167 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; @@ -78454,7 +80869,7 @@ var ts; // 3). Dynamic import call or require in javascript // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 261 /* ImportDeclaration */ || node.parent.kind === 267 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((node.parent.kind === 262 /* ImportDeclaration */ || node.parent.kind === 268 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || ((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, ignoreErrors); @@ -78476,7 +80891,7 @@ var ts; case 38 /* EqualsGreaterThanToken */: case 83 /* ClassKeyword */: return getSymbolOfNode(node.parent); - case 195 /* ImportType */: + case 196 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined; case 92 /* ExportKeyword */: return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined; @@ -78485,7 +80900,7 @@ var ts; } } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 289 /* ShorthandPropertyAssignment */) { + if (location && location.kind === 290 /* ShorthandPropertyAssignment */) { return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */); } return undefined; @@ -78564,27 +80979,27 @@ var ts; // [ a ] from // [a] = [ some array ...] function getTypeOfAssignmentPattern(expr) { - ts.Debug.assert(expr.kind === 200 /* ObjectLiteralExpression */ || expr.kind === 199 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.kind === 201 /* ObjectLiteralExpression */ || expr.kind === 200 /* ArrayLiteralExpression */); // If this is from "for of" // for ( { a } of elems) { // } - if (expr.parent.kind === 239 /* ForOfStatement */) { + if (expr.parent.kind === 240 /* ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 216 /* BinaryExpression */) { + if (expr.parent.kind === 217 /* BinaryExpression */) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 288 /* PropertyAssignment */) { - var node_2 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); - var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_2) || errorType; - var propertyIndex = ts.indexOfNode(node_2.properties, expr.parent); - return checkObjectLiteralDestructuringPropertyAssignment(node_2, typeOfParentObjectLiteral, propertyIndex); + if (expr.parent.kind === 289 /* PropertyAssignment */) { + var node_3 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); + var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_3) || errorType; + var propertyIndex = ts.indexOfNode(node_3.properties, expr.parent); + return checkObjectLiteralDestructuringPropertyAssignment(node_3, typeOfParentObjectLiteral, propertyIndex); } // Array literal assignment - array destructuring pattern var node = ts.cast(expr.parent, ts.isArrayLiteralExpression); @@ -78628,7 +81043,7 @@ var ts; case 8 /* NumericLiteral */: case 10 /* StringLiteral */: return getLiteralType(name.text); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(name); return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType; default: @@ -78725,6 +81140,7 @@ var ts; // When resolved as an expression identifier, if the given node references an exported entity, return the declaration // node of the exported entity's container. Otherwise, return undefined. function getReferencedExportContainer(nodeIn, prefixLocals) { + var _a; var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { // When resolving the export container for the name of a module or enum @@ -78745,7 +81161,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 297 /* SourceFile */) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && ((_a = parentSymbol_1.valueDeclaration) === null || _a === void 0 ? void 0 : _a.kind) === 298 /* SourceFile */) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -78775,11 +81191,12 @@ var ts; return undefined; } function isSymbolOfDestructuredElementOfCatchBinding(symbol) { - return ts.isBindingElement(symbol.valueDeclaration) - && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 287 /* CatchClause */; + return symbol.valueDeclaration + && ts.isBindingElement(symbol.valueDeclaration) + && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 288 /* CatchClause */; } function isSymbolOfDeclarationWithCollidingName(symbol) { - if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) { + if (symbol.flags & 418 /* BlockScoped */ && symbol.valueDeclaration && !ts.isSourceFile(symbol.valueDeclaration)) { var links = getSymbolLinks(symbol); if (links.isDeclarationWithCollidingName === undefined) { var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); @@ -78807,7 +81224,7 @@ var ts; // they will not collide with anything var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 230 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 231 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -78848,19 +81265,19 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: var symbol = getSymbolOfNode(node) || unknownSymbol; return isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: var exportClause = node.exportClause; return !!exportClause && (ts.isNamespaceExport(exportClause) || ts.some(exportClause.elements, isValueAliasDeclaration)); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return node.expression && node.expression.kind === 78 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; @@ -78869,7 +81286,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 297 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 298 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -78884,7 +81301,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 & 111551 /* Value */) && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; @@ -78892,13 +81309,14 @@ var ts; function isReferencedAliasDeclaration(node, checkChildren) { if (isAliasSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); - if (symbol && getSymbolLinks(symbol).referenced) { + var links = symbol && getSymbolLinks(symbol); + if (links === null || links === void 0 ? void 0 : links.referenced) { return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 if (target && ts.getEffectiveModifierFlags(node) & 1 /* Export */ && target.flags & 111551 /* Value */ && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -78935,13 +81353,13 @@ var ts; !isOptionalParameter(parameter) && !ts.isJSDocParameterTag(parameter) && !!parameter.initializer && - !ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + !ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && - ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameter(parameter) { return !!strictNullChecks && @@ -78976,15 +81394,15 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 291 /* EnumMember */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 292 /* EnumMember */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return true; } return false; } function getConstantValue(node) { - if (node.kind === 291 /* EnumMember */) { + if (node.kind === 292 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -79137,8 +81555,7 @@ var ts; } function isLiteralConstDeclaration(node) { if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 2944 /* Literal */) && isFreshLiteralType(type); + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } @@ -79257,12 +81674,12 @@ var ts; getJsxFragmentFactoryEntity: getJsxFragmentFactoryEntity, getAllAccessorDeclarations: function (accessor) { accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 - var otherKind = accessor.kind === 168 /* SetAccessor */ ? 167 /* GetAccessor */ : 168 /* SetAccessor */; + var otherKind = accessor.kind === 169 /* SetAccessor */ ? 168 /* GetAccessor */ : 169 /* SetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; - var setAccessor = accessor.kind === 168 /* SetAccessor */ ? accessor : otherAccessor; - var getAccessor = accessor.kind === 167 /* GetAccessor */ ? accessor : otherAccessor; + var setAccessor = accessor.kind === 169 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 168 /* GetAccessor */ ? accessor : otherAccessor; return { firstAccessor: firstAccessor, secondAccessor: secondAccessor, @@ -79278,7 +81695,7 @@ var ts; }, getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) { var n = ts.getParseTreeNode(node); - ts.Debug.assert(n && n.kind === 297 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile"); + ts.Debug.assert(n && n.kind === 298 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile"); var sym = getSymbolOfNode(node); if (!sym) { return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled); @@ -79301,11 +81718,13 @@ var ts; var s = _a[_i]; if (s.mergeId) { var merged = getMergedSymbol(s); - for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { - var d = _c[_b]; - var declFile = ts.getSourceFileOfNode(d); - if (declFile === importTarget) { - return true; + if (merged.declarations) { + for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declFile = ts.getSourceFileOfNode(d); + if (declFile === importTarget) { + return true; + } } } } @@ -79313,7 +81732,7 @@ var ts; return false; } function isInHeritageClause(node) { - return node.parent && node.parent.kind === 223 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 286 /* HeritageClause */; + return node.parent && node.parent.kind === 224 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 287 /* HeritageClause */; } // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -79325,7 +81744,7 @@ var ts; // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries var meaning = 788968 /* Type */ | 1920 /* Namespace */; - if ((node.kind === 78 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 201 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { + if ((node.kind === 78 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 202 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { meaning = 111551 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); @@ -79334,10 +81753,7 @@ var ts; // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForSymbol(symbol, meaning) { // program does not have any files with type reference directives - bail out - if (!fileToDirective) { - return undefined; - } - if (!isSymbolFromTypeDeclarationFile(symbol)) { + if (!fileToDirective || !isSymbolFromTypeDeclarationFile(symbol)) { return undefined; } // check what declarations in the symbol can contribute to the target meaning @@ -79376,7 +81792,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 297 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 298 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -79404,12 +81820,12 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = declaration.kind === 256 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 257 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 297 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 298 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -79429,7 +81845,7 @@ var ts; // It is an error for a non-external-module (i.e. script) to declare its own `globalThis`. // We can't use `builtinGlobals` for this due to synthetic expando-namespace generation in JS files. var fileGlobalThisSymbol = file.locals.get("globalThis"); - if (fileGlobalThisSymbol) { + if (fileGlobalThisSymbol === null || fileGlobalThisSymbol === void 0 ? void 0 : fileGlobalThisSymbol.declarations) { for (var _d = 0, _e = fileGlobalThisSymbol.declarations; _d < _e.length; _d++) { var declaration = _e[_d]; diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis")); @@ -79553,6 +81969,16 @@ var ts; if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name); } + else if (helper & 524288 /* ClassPrivateFieldGet */) { + if (!ts.some(getSignaturesOfSymbol(symbol), function (signature) { return getParameterCount(signature) > 3; })) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name, 4); + } + } + else if (helper & 1048576 /* ClassPrivateFieldSet */) { + if (!ts.some(getSignaturesOfSymbol(symbol), function (signature) { return getParameterCount(signature) > 4; })) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name, 5); + } + } } } } @@ -79602,14 +82028,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { - if (node.kind === 165 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + if (node.kind === 166 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 167 /* GetAccessor */ || node.kind === 168 /* SetAccessor */) { + else if (node.kind === 168 /* GetAccessor */ || node.kind === 169 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -79622,24 +82048,41 @@ var ts; if (quickResult !== undefined) { return quickResult; } - var lastStatic, lastDeclare, lastAsync, lastReadonly; + var lastStatic, lastDeclare, lastAsync, lastReadonly, lastOverride; var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; if (modifier.kind !== 142 /* ReadonlyKeyword */) { - if (node.kind === 162 /* PropertySignature */ || node.kind === 164 /* MethodSignature */) { + if (node.kind === 163 /* PropertySignature */ || node.kind === 165 /* MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 171 /* IndexSignature */) { + if (node.kind === 172 /* IndexSignature */ && (modifier.kind !== 123 /* StaticKeyword */ || !ts.isClassLike(node.parent))) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { case 84 /* ConstKeyword */: - if (node.kind !== 255 /* EnumDeclaration */) { + if (node.kind !== 256 /* EnumDeclaration */) { return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(84 /* ConstKeyword */)); } break; + case 156 /* OverrideKeyword */: + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "override"); + } + else if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "async"); + } + flags |= 16384 /* Override */; + lastOverride = modifier; + break; case 122 /* PublicKeyword */: case 121 /* ProtectedKeyword */: case 120 /* PrivateKeyword */: @@ -79647,6 +82090,9 @@ var ts; if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "override"); + } else if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } @@ -79656,7 +82102,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + else if (node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { @@ -79667,7 +82113,7 @@ var ts; return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); } } - else if (ts.isPrivateIdentifierPropertyDeclaration(node)) { + else if (ts.isPrivateIdentifierClassElementDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier); } flags |= ts.modifierToFlag(modifier.kind); @@ -79682,17 +82128,17 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + else if (node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - else if (ts.isPrivateIdentifierPropertyDeclaration(node)) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "static"); + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "override"); } flags |= 32 /* Static */; lastStatic = modifier; @@ -79701,8 +82147,8 @@ var ts; if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 163 /* PropertyDeclaration */ && node.kind !== 162 /* PropertySignature */ && node.kind !== 171 /* IndexSignature */ && node.kind !== 160 /* Parameter */) { - // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. + else if (node.kind !== 164 /* PropertyDeclaration */ && node.kind !== 163 /* PropertySignature */ && node.kind !== 172 /* IndexSignature */ && node.kind !== 161 /* Parameter */) { + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; @@ -79724,14 +82170,14 @@ var ts; else if (ts.isClassLike(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "export"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* Export */; break; case 87 /* DefaultKeyword */: - var container = node.parent.kind === 297 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 256 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 298 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 257 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512 /* Default */; @@ -79743,16 +82189,19 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override"); + } else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 257 /* ModuleBlock */) { + else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 258 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } - else if (ts.isPrivateIdentifierPropertyDeclaration(node)) { + else if (ts.isPrivateIdentifierClassElementDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare"); } flags |= 2 /* Ambient */; @@ -79762,15 +82211,15 @@ var ts; if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 252 /* ClassDeclaration */ && - node.kind !== 175 /* ConstructorType */) { - if (node.kind !== 165 /* MethodDeclaration */ && - node.kind !== 163 /* PropertyDeclaration */ && - node.kind !== 167 /* GetAccessor */ && - node.kind !== 168 /* SetAccessor */) { + if (node.kind !== 253 /* ClassDeclaration */ && + node.kind !== 176 /* ConstructorType */) { + if (node.kind !== 166 /* MethodDeclaration */ && + node.kind !== 164 /* PropertyDeclaration */ && + node.kind !== 168 /* GetAccessor */ && + node.kind !== 169 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 252 /* ClassDeclaration */ && ts.hasSyntacticModifier(node.parent, 128 /* Abstract */))) { + if (!(node.parent.kind === 253 /* ClassDeclaration */ && ts.hasSyntacticModifier(node.parent, 128 /* Abstract */))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -79782,6 +82231,9 @@ var ts; if (flags & 256 /* Async */ && lastAsync) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); } + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override"); + } } if (ts.isNamedDeclaration(node) && node.name.kind === 79 /* PrivateIdentifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract"); @@ -79795,7 +82247,7 @@ var ts; else if (flags & 2 /* Ambient */ || node.parent.flags & 8388608 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } if (flags & 128 /* Abstract */) { @@ -79806,13 +82258,16 @@ var ts; break; } } - if (node.kind === 166 /* Constructor */) { + if (node.kind === 167 /* Constructor */) { if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } if (flags & 128 /* Abstract */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 } + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(lastOverride, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); // TODO: GH#18217 + } else if (flags & 256 /* Async */) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } @@ -79821,13 +82276,13 @@ var ts; } return false; } - else if ((node.kind === 261 /* ImportDeclaration */ || node.kind === 260 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 262 /* ImportDeclaration */ || node.kind === 261 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 160 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 160 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { @@ -79848,38 +82303,38 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 166 /* Constructor */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 171 /* IndexSignature */: - case 256 /* ModuleDeclaration */: - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 160 /* Parameter */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 167 /* Constructor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 172 /* IndexSignature */: + case 257 /* ModuleDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 161 /* Parameter */: return false; default: - if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + if (node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { return false; } switch (node.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return nodeHasAnyModifiersExcept(node, 129 /* AsyncKeyword */); - case 252 /* ClassDeclaration */: - case 175 /* ConstructorType */: + case 253 /* ClassDeclaration */: + case 176 /* ConstructorType */: return nodeHasAnyModifiersExcept(node, 125 /* AbstractKeyword */); - case 253 /* InterfaceDeclaration */: - case 232 /* VariableStatement */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 233 /* VariableStatement */: + case 255 /* TypeAliasDeclaration */: return true; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return nodeHasAnyModifiersExcept(node, 84 /* ConstKeyword */); default: ts.Debug.fail(); @@ -79891,10 +82346,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -80055,7 +82510,7 @@ var ts; if (args) { for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { var arg = args_4[_i]; - if (arg.kind === 222 /* OmittedExpression */) { + if (arg.kind === 223 /* OmittedExpression */) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -80132,20 +82587,20 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 158 /* ComputedPropertyName */) { + if (node.kind !== 159 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 216 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { + if (computedPropertyName.expression.kind === 217 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 251 /* FunctionDeclaration */ || - node.kind === 208 /* FunctionExpression */ || - node.kind === 165 /* MethodDeclaration */); + ts.Debug.assert(node.kind === 252 /* FunctionDeclaration */ || + node.kind === 209 /* FunctionExpression */ || + node.kind === 166 /* MethodDeclaration */); if (node.flags & 8388608 /* Ambient */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -80164,7 +82619,7 @@ var ts; var seen = new ts.Map(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 290 /* SpreadAssignment */) { + if (prop.kind === 291 /* SpreadAssignment */) { if (inDestructuring) { // a rest property cannot be destructured any further var expression = ts.skipParentheses(prop.expression); @@ -80175,24 +82630,24 @@ var ts; continue; } var name = prop.name; - if (name.kind === 158 /* ComputedPropertyName */) { + if (name.kind === 159 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name); } - if (prop.kind === 289 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 290 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern); } if (name.kind === 79 /* PrivateIdentifier */) { - return grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); } // Modifiers are never allowed on properties except for 'async' on a method declaration if (prop.modifiers) { // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 var mod = _c[_b]; - if (mod.kind !== 129 /* AsyncKeyword */ || prop.kind !== 165 /* MethodDeclaration */) { + if (mod.kind !== 129 /* AsyncKeyword */ || prop.kind !== 166 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } @@ -80207,10 +82662,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 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); // falls through - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -80218,13 +82673,13 @@ var ts; } currentKind = 4 /* PropertyAssignment */; break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: currentKind = 8 /* Method */; break; - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: currentKind = 1 /* GetAccessor */; break; - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: currentKind = 2 /* SetAccessor */; break; default: @@ -80259,11 +82714,12 @@ var ts; } } function checkGrammarJsxElement(node) { + checkGrammarJsxName(node.tagName); checkGrammarTypeArguments(node, node.typeArguments); var seen = new ts.Map(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 282 /* JsxSpreadAttribute */) { + if (attr.kind === 283 /* JsxSpreadAttribute */) { continue; } var name = attr.name, initializer = attr.initializer; @@ -80273,11 +82729,32 @@ var ts; else { return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - if (initializer && initializer.kind === 283 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 284 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } } + function checkGrammarJsxName(node) { + if (ts.isPropertyAccessExpression(node)) { + var propName = node; + do { + var check_1 = checkGrammarJsxNestedIdentifier(propName.name); + if (check_1) { + return check_1; + } + propName = propName.expression; + } while (ts.isPropertyAccessExpression(propName)); + var check = checkGrammarJsxNestedIdentifier(propName); + if (check) { + return check; + } + } + function checkGrammarJsxNestedIdentifier(name) { + if (ts.isIdentifier(name) && ts.idText(name).indexOf(":") !== -1) { + return grammarErrorOnNode(name, ts.Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names); + } + } + } function checkGrammarJsxExpression(node) { if (node.expression && ts.isCommaSequence(node.expression)) { return grammarErrorOnNode(node.expression, ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array); @@ -80287,25 +82764,37 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 239 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { - if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) { - // use of 'for-await-of' in non-async function + if (forInOrOfStatement.kind === 240 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if (!(forInOrOfStatement.flags & 32768 /* AwaitContext */)) { var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement); - if (!hasParseDiagnostics(sourceFile)) { - var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); - var func = ts.getContainingFunction(forInOrOfStatement); - if (func && func.kind !== 166 /* Constructor */) { - ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); - var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); - ts.addRelatedInfo(diagnostic, relatedInfo); - } - diagnostics.add(diagnostic); - return true; + if (ts.isInTopLevelContext(forInOrOfStatement)) { + if (!hasParseDiagnostics(sourceFile)) { + if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module)); + } + if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher)); + } + } + } + else { + // use of 'for-await-of' in non-async function + if (!hasParseDiagnostics(sourceFile)) { + var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); + var func = ts.getContainingFunction(forInOrOfStatement); + if (func && func.kind !== 167 /* Constructor */) { + ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); + var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); + ts.addRelatedInfo(diagnostic, relatedInfo); + } + diagnostics.add(diagnostic); + return true; + } } return false; } } - if (forInOrOfStatement.initializer.kind === 250 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 251 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -80320,20 +82809,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 239 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 239 /* ForInStatement */ ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 239 /* ForInStatement */ ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -80343,26 +82832,34 @@ var ts; return false; } function checkGrammarAccessor(accessor) { - if (!(accessor.flags & 8388608 /* Ambient */)) { + if (!(accessor.flags & 8388608 /* Ambient */) && (accessor.parent.kind !== 178 /* TypeLiteral */) && (accessor.parent.kind !== 254 /* InterfaceDeclaration */)) { if (languageVersion < 1 /* ES5 */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } + if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(accessor.name)) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } if (accessor.body === undefined && !ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) { return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } - if (accessor.body && ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) { - return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + if (accessor.body) { + if (ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + if (accessor.parent.kind === 178 /* TypeLiteral */ || accessor.parent.kind === 254 /* InterfaceDeclaration */) { + return grammarErrorOnNode(accessor.body, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } } if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, accessor.kind === 167 /* GetAccessor */ ? + return grammarErrorOnNode(accessor.name, accessor.kind === 168 /* GetAccessor */ ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - if (accessor.kind === 168 /* SetAccessor */) { + if (accessor.kind === 169 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -80384,10 +82881,10 @@ var ts; * A set accessor has one parameter or a `this` parameter and one more parameter. */ function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 167 /* GetAccessor */ ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 168 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 167 /* GetAccessor */ ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 168 /* GetAccessor */ ? 1 : 2)) { return ts.getThisParameter(accessor); } } @@ -80405,7 +82902,7 @@ var ts; } } switch (parent.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: var decl = parent; if (decl.name.kind !== 78 /* Identifier */) { return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); @@ -80417,13 +82914,13 @@ var ts; return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); } break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: if (!ts.hasSyntacticModifier(parent, 32 /* Static */) || !ts.hasEffectiveModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: if (!ts.hasSyntacticModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } @@ -80433,7 +82930,7 @@ var ts; } } else if (node.operator === 142 /* ReadonlyKeyword */) { - if (node.type.kind !== 178 /* ArrayType */ && node.type.kind !== 179 /* TupleType */) { + if (node.type.kind !== 179 /* ArrayType */ && node.type.kind !== 180 /* TupleType */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(148 /* SymbolKeyword */)); } } @@ -80447,8 +82944,8 @@ var ts; if (checkGrammarFunctionLikeDeclaration(node)) { return true; } - if (node.kind === 165 /* MethodDeclaration */) { - if (node.parent.kind === 200 /* ObjectLiteralExpression */) { + if (node.kind === 166 /* MethodDeclaration */) { + if (node.parent.kind === 201 /* ObjectLiteralExpression */) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 129 /* AsyncKeyword */)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -80468,6 +82965,9 @@ var ts; } } if (ts.isClassLike(node.parent)) { + if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) { + return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } // Technically, computed properties in ambient contexts is disallowed // for property declarations and accessors too, not just methods. // However, property declarations disallow computed names in general, @@ -80476,14 +82976,14 @@ var ts; if (node.flags & 8388608 /* Ambient */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.kind === 165 /* MethodDeclaration */ && !node.body) { + else if (node.kind === 166 /* MethodDeclaration */ && !node.body) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 253 /* InterfaceDeclaration */) { + else if (node.parent.kind === 254 /* InterfaceDeclaration */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 177 /* TypeLiteral */) { + else if (node.parent.kind === 178 /* TypeLiteral */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } @@ -80494,11 +82994,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: if (node.label && current.label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 240 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 241 /* ContinueStatement */ && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -80506,8 +83006,8 @@ var ts; return false; } break; - case 244 /* SwitchStatement */: - if (node.kind === 241 /* BreakStatement */ && !node.label) { + case 245 /* SwitchStatement */: + if (node.kind === 242 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -80522,13 +83022,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 241 /* BreakStatement */ + var message = node.kind === 242 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 241 /* BreakStatement */ + var message = node.kind === 242 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -80552,12 +83052,12 @@ var ts; } function isStringOrNumberLiteralExpression(expr) { return ts.isStringOrNumericLiteralLike(expr) || - expr.kind === 214 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && + expr.kind === 215 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } function isBigIntLiteralExpression(expr) { return expr.kind === 9 /* BigIntLiteral */ || - expr.kind === 214 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && + expr.kind === 215 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && expr.operand.kind === 9 /* BigIntLiteral */; } function isSimpleLiteralEnumReference(expr) { @@ -80588,7 +83088,7 @@ var ts; } } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 238 /* ForInStatement */ && node.parent.parent.kind !== 239 /* ForOfStatement */) { + if (node.parent.parent.kind !== 239 /* ForInStatement */ && node.parent.parent.kind !== 240 /* ForOfStatement */) { if (node.flags & 8388608 /* Ambient */) { checkAmbientInitializer(node); } @@ -80601,7 +83101,7 @@ var ts; } } } - if (node.exclamationToken && (node.parent.parent.kind !== 232 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) { + if (node.exclamationToken && (node.parent.parent.kind !== 233 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) { var message = node.initializer ? ts.Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type @@ -80669,15 +83169,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 234 /* IfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 243 /* WithStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 235 /* IfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 244 /* WithStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: return false; - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -80762,14 +83262,14 @@ var ts; if (ts.isStringLiteral(node.name) && node.name.text === "constructor") { return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor); } - if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type)) { return true; } if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) { return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); } } - else if (node.parent.kind === 253 /* InterfaceDeclaration */) { + else if (node.parent.kind === 254 /* InterfaceDeclaration */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -80777,7 +83277,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 177 /* TypeLiteral */) { + else if (node.parent.kind === 178 /* TypeLiteral */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -80811,13 +83311,13 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 253 /* InterfaceDeclaration */ || - node.kind === 254 /* TypeAliasDeclaration */ || - node.kind === 261 /* ImportDeclaration */ || - node.kind === 260 /* ImportEqualsDeclaration */ || - node.kind === 267 /* ExportDeclaration */ || - node.kind === 266 /* ExportAssignment */ || - node.kind === 259 /* NamespaceExportDeclaration */ || + if (node.kind === 254 /* InterfaceDeclaration */ || + node.kind === 255 /* TypeAliasDeclaration */ || + node.kind === 262 /* ImportDeclaration */ || + node.kind === 261 /* ImportEqualsDeclaration */ || + node.kind === 268 /* ExportDeclaration */ || + node.kind === 267 /* ExportAssignment */ || + node.kind === 260 /* NamespaceExportDeclaration */ || ts.hasSyntacticModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } @@ -80826,7 +83326,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 232 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 233 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -80849,7 +83349,7 @@ var ts; // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if (node.parent.kind === 230 /* Block */ || node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + if (node.parent.kind === 231 /* Block */ || node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { var links_2 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_2.hasReportedStatementInAmbientContext) { @@ -80871,10 +83371,10 @@ var ts; if (languageVersion >= 1 /* ES5 */) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 191 /* LiteralType */)) { + else if (ts.isChildOfNodeWithKind(node, 192 /* LiteralType */)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 291 /* EnumMember */)) { + else if (ts.isChildOfNodeWithKind(node, 292 /* EnumMember */)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { @@ -80980,7 +83480,7 @@ var ts; } } function findBestTypeForObjectLiteral(source, unionTarget) { - if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) { + if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && someType(unionTarget, isArrayLikeType)) { return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } @@ -81032,6 +83532,10 @@ var ts; // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) { if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) { + var match = getMatchingUnionConstituentForType(target, source); + if (match) { + return match; + } var sourceProperties = getPropertiesOfType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); @@ -81049,33 +83553,19 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 251 /* FunctionDeclaration */ && declaration.kind !== 165 /* MethodDeclaration */) || + return (declaration.kind !== 252 /* FunctionDeclaration */ && declaration.kind !== 166 /* MethodDeclaration */) || !!declaration.body; } /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return ts.isIdentifier(name); default: return ts.isDeclarationName(name); } } - function isSomeImportDeclaration(decl) { - switch (decl.kind) { - case 262 /* ImportClause */: // For default import - case 260 /* ImportEqualsDeclaration */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: // For rename import `x as y` - return true; - case 78 /* Identifier */: - // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 265 /* ImportSpecifier */; - default: - return false; - } - } var JsxNames; (function (JsxNames) { JsxNames.JSX = "JSX"; @@ -81106,7 +83596,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); function visitNode(node, visitor, test, lift) { if (node === undefined || visitor === undefined) { return node; @@ -81295,6 +83784,24 @@ var ts; return updated; } ts.visitFunctionBody = visitFunctionBody; + /** + * Visits an iteration body, adding any block-scoped variables required by the transformation. + */ + function visitIterationBody(body, visitor, context) { + context.startBlockScope(); + var updated = visitNode(body, visitor, ts.isStatement, context.factory.liftToBlock); + var declarations = context.endBlockScope(); + if (ts.some(declarations)) { + if (ts.isBlock(updated)) { + declarations.push.apply(declarations, updated.statements); + return context.factory.updateBlock(updated, declarations); + } + declarations.push(updated); + return context.factory.createBlock(declarations); + } + return updated; + } + ts.visitIterationBody = visitIterationBody; function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor, nodeVisitor) { if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } if (nodeVisitor === void 0) { nodeVisitor = visitNode; } @@ -81303,299 +83810,433 @@ var ts; } var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 156 /* LastToken */) || kind === 187 /* ThisType */) { + if ((kind > 0 /* FirstToken */ && kind <= 157 /* LastToken */) || kind === 188 /* ThisType */) { return node; } var factory = context.factory; switch (kind) { // Names case 78 /* Identifier */: - return factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); - case 157 /* QualifiedName */: + ts.Debug.type(node); + return factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNodeOrTypeParameterDeclaration)); + case 158 /* QualifiedName */: + ts.Debug.type(node); return factory.updateQualifiedName(node, nodeVisitor(node.left, visitor, ts.isEntityName), nodeVisitor(node.right, visitor, ts.isIdentifier)); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: + ts.Debug.type(node); return factory.updateComputedPropertyName(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Signature elements - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: + ts.Debug.type(node); return factory.updateTypeParameterDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode)); - case 160 /* Parameter */: - return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 161 /* Decorator */: + case 161 /* Parameter */: + ts.Debug.type(node); + return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 162 /* Decorator */: + ts.Debug.type(node); return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Type elements - case 162 /* PropertySignature */: - return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 163 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + ts.Debug.type(node); + return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 164 /* PropertyDeclaration */: + ts.Debug.type(node); return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too - nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 164 /* MethodSignature */: - return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 165 /* MethodDeclaration */: - return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 166 /* Constructor */: + nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isQuestionOrExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 165 /* MethodSignature */: + ts.Debug.type(node); + return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 166 /* MethodDeclaration */: + ts.Debug.type(node); + return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 167 /* Constructor */: + ts.Debug.type(node); return factory.updateConstructorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: + ts.Debug.type(node); return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: + ts.Debug.type(node); return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 169 /* CallSignature */: + case 170 /* CallSignature */: + ts.Debug.type(node); return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: + ts.Debug.type(node); return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: + ts.Debug.type(node); return factory.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); // Types - case 172 /* TypePredicate */: - return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor), nodeVisitor(node.parameterName, visitor), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 173 /* TypeReference */: + case 173 /* TypePredicate */: + ts.Debug.type(node); + return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor, ts.isAssertsKeyword), nodeVisitor(node.parameterName, visitor, ts.isIdentifierOrThisTypeNode), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 174 /* TypeReference */: + ts.Debug.type(node); return factory.updateTypeReferenceNode(node, nodeVisitor(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 174 /* FunctionType */: + case 175 /* FunctionType */: + ts.Debug.type(node); return factory.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 175 /* ConstructorType */: + case 176 /* ConstructorType */: + ts.Debug.type(node); return factory.updateConstructorTypeNode(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: + ts.Debug.type(node); return factory.updateTypeQueryNode(node, nodeVisitor(node.exprName, visitor, ts.isEntityName)); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: + ts.Debug.type(node); return factory.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 178 /* ArrayType */: + case 179 /* ArrayType */: + ts.Debug.type(node); return factory.updateArrayTypeNode(node, nodeVisitor(node.elementType, visitor, ts.isTypeNode)); - case 179 /* TupleType */: + case 180 /* TupleType */: + ts.Debug.type(node); return factory.updateTupleTypeNode(node, nodesVisitor(node.elements, visitor, ts.isTypeNode)); - case 180 /* OptionalType */: + case 181 /* OptionalType */: + ts.Debug.type(node); return factory.updateOptionalTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 181 /* RestType */: + case 182 /* RestType */: + ts.Debug.type(node); return factory.updateRestTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 182 /* UnionType */: + case 183 /* UnionType */: + ts.Debug.type(node); return factory.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 183 /* IntersectionType */: + case 184 /* IntersectionType */: + ts.Debug.type(node); return factory.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: + ts.Debug.type(node); return factory.updateConditionalTypeNode(node, nodeVisitor(node.checkType, visitor, ts.isTypeNode), nodeVisitor(node.extendsType, visitor, ts.isTypeNode), nodeVisitor(node.trueType, visitor, ts.isTypeNode), nodeVisitor(node.falseType, visitor, ts.isTypeNode)); - case 185 /* InferType */: + case 186 /* InferType */: + ts.Debug.type(node); return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); - case 195 /* ImportType */: + case 196 /* ImportType */: + ts.Debug.type(node); return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); - case 192 /* NamedTupleMember */: - return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); - case 186 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: + ts.Debug.type(node); + return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isDotDotDotToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isQuestionToken), visitNode(node.type, visitor, ts.isTypeNode)); + case 187 /* ParenthesizedType */: + ts.Debug.type(node); return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: + ts.Debug.type(node); return factory.updateTypeOperatorNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: + ts.Debug.type(node); return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode)); - case 190 /* MappedType */: - return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 191 /* LiteralType */: + case 191 /* MappedType */: + ts.Debug.type(node); + return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 192 /* LiteralType */: + ts.Debug.type(node); return factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression)); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: + ts.Debug.type(node); return factory.updateTemplateLiteralType(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateLiteralTypeSpan)); - case 194 /* TemplateLiteralTypeSpan */: + case 195 /* TemplateLiteralTypeSpan */: + ts.Debug.type(node); return factory.updateTemplateLiteralTypeSpan(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Binding patterns - case 196 /* ObjectBindingPattern */: + case 197 /* ObjectBindingPattern */: + ts.Debug.type(node); return factory.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: + ts.Debug.type(node); return factory.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); - case 198 /* BindingElement */: - return factory.updateBindingElement(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.propertyName, visitor, ts.isPropertyName), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 199 /* BindingElement */: + ts.Debug.type(node); + return factory.updateBindingElement(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.propertyName, visitor, ts.isPropertyName), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.initializer, visitor, ts.isExpression)); // Expression - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: + ts.Debug.type(node); return factory.updateArrayLiteralExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression)); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + ts.Debug.type(node); return factory.updateObjectLiteralExpression(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (node.flags & 32 /* OptionalChain */) { - return factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier)); + ts.Debug.type(node); + return factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodeVisitor(node.name, visitor, ts.isMemberName)); } - return factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isIdentifierOrPrivateIdentifier)); - case 202 /* ElementAccessExpression */: + ts.Debug.type(node); + return factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isMemberName)); + case 203 /* ElementAccessExpression */: if (node.flags & 32 /* OptionalChain */) { - return factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); } + ts.Debug.type(node); return factory.updateElementAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (node.flags & 32 /* OptionalChain */) { - return factory.updateCallChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateCallChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); } + ts.Debug.type(node); return factory.updateCallExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 204 /* NewExpression */: + case 205 /* NewExpression */: + ts.Debug.type(node); return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 205 /* TaggedTemplateExpression */: - return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); - case 206 /* TypeAssertionExpression */: + case 206 /* TaggedTemplateExpression */: + ts.Debug.type(node); + return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); + case 207 /* TypeAssertionExpression */: + ts.Debug.type(node); return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: + ts.Debug.type(node); return factory.updateParenthesizedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 208 /* FunctionExpression */: - return factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 209 /* ArrowFunction */: - return factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, ts.isToken), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 210 /* DeleteExpression */: + case 209 /* FunctionExpression */: + ts.Debug.type(node); + return factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 210 /* ArrowFunction */: + ts.Debug.type(node); + return factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, ts.isEqualsGreaterThanToken), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 211 /* DeleteExpression */: + ts.Debug.type(node); return factory.updateDeleteExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: + ts.Debug.type(node); return factory.updateTypeOfExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: + ts.Debug.type(node); return factory.updateVoidExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: + ts.Debug.type(node); return factory.updateAwaitExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + ts.Debug.type(node); return factory.updatePrefixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression)); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + ts.Debug.type(node); return factory.updatePostfixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression)); - case 216 /* BinaryExpression */: - return factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isToken), nodeVisitor(node.right, visitor, ts.isExpression)); - case 217 /* ConditionalExpression */: - return factory.updateConditionalExpression(node, nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.whenTrue, visitor, ts.isExpression), nodeVisitor(node.colonToken, tokenVisitor, ts.isToken), nodeVisitor(node.whenFalse, visitor, ts.isExpression)); - case 218 /* TemplateExpression */: + case 217 /* BinaryExpression */: + ts.Debug.type(node); + return factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isBinaryOperatorToken), nodeVisitor(node.right, visitor, ts.isExpression)); + case 218 /* ConditionalExpression */: + ts.Debug.type(node); + return factory.updateConditionalExpression(node, nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.whenTrue, visitor, ts.isExpression), nodeVisitor(node.colonToken, tokenVisitor, ts.isColonToken), nodeVisitor(node.whenFalse, visitor, ts.isExpression)); + case 219 /* TemplateExpression */: + ts.Debug.type(node); return factory.updateTemplateExpression(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); - case 219 /* YieldExpression */: - return factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 220 /* SpreadElement */: + case 220 /* YieldExpression */: + ts.Debug.type(node); + return factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.expression, visitor, ts.isExpression)); + case 221 /* SpreadElement */: + ts.Debug.type(node); return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: + ts.Debug.type(node); return factory.updateClassExpression(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: + ts.Debug.type(node); return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 224 /* AsExpression */: + case 225 /* AsExpression */: + ts.Debug.type(node); return factory.updateAsExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: if (node.flags & 32 /* OptionalChain */) { + ts.Debug.type(node); return factory.updateNonNullChain(node, nodeVisitor(node.expression, visitor, ts.isExpression)); } + ts.Debug.type(node); return factory.updateNonNullExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: + ts.Debug.type(node); return factory.updateMetaProperty(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); // Misc - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: + ts.Debug.type(node); return factory.updateTemplateSpan(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element - case 230 /* Block */: + case 231 /* Block */: + ts.Debug.type(node); return factory.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: + ts.Debug.type(node); return factory.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: + ts.Debug.type(node); return factory.updateExpressionStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 234 /* IfStatement */: + case 235 /* IfStatement */: + ts.Debug.type(node); return factory.updateIfStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.thenStatement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.elseStatement, visitor, ts.isStatement, factory.liftToBlock)); - case 235 /* DoStatement */: - return factory.updateDoStatement(node, nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 236 /* WhileStatement */: - return factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 237 /* ForStatement */: - return factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.incrementor, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 238 /* ForInStatement */: - return factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 239 /* ForOfStatement */: - return factory.updateForOfStatement(node, nodeVisitor(node.awaitModifier, tokenVisitor, ts.isToken), nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 240 /* ContinueStatement */: + case 236 /* DoStatement */: + ts.Debug.type(node); + return factory.updateDoStatement(node, visitIterationBody(node.statement, visitor, context), nodeVisitor(node.expression, visitor, ts.isExpression)); + case 237 /* WhileStatement */: + ts.Debug.type(node); + return factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 238 /* ForStatement */: + ts.Debug.type(node); + return factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.incrementor, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 239 /* ForInStatement */: + ts.Debug.type(node); + return factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 240 /* ForOfStatement */: + ts.Debug.type(node); + return factory.updateForOfStatement(node, nodeVisitor(node.awaitModifier, tokenVisitor, ts.isAwaitKeyword), nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 241 /* ContinueStatement */: + ts.Debug.type(node); return factory.updateContinueStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier)); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: + ts.Debug.type(node); return factory.updateBreakStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier)); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: + ts.Debug.type(node); return factory.updateReturnStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 243 /* WithStatement */: + case 244 /* WithStatement */: + ts.Debug.type(node); return factory.updateWithStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: + ts.Debug.type(node); return factory.updateSwitchStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.caseBlock, visitor, ts.isCaseBlock)); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: + ts.Debug.type(node); return factory.updateLabeledStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: + ts.Debug.type(node); return factory.updateThrowStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 247 /* TryStatement */: + case 248 /* TryStatement */: + ts.Debug.type(node); return factory.updateTryStatement(node, nodeVisitor(node.tryBlock, visitor, ts.isBlock), nodeVisitor(node.catchClause, visitor, ts.isCatchClause), nodeVisitor(node.finallyBlock, visitor, ts.isBlock)); - case 249 /* VariableDeclaration */: - return factory.updateVariableDeclaration(node, nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 250 /* VariableDeclarationList */: + case 250 /* VariableDeclaration */: + ts.Debug.type(node); + return factory.updateVariableDeclaration(node, nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.exclamationToken, tokenVisitor, ts.isExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 251 /* VariableDeclarationList */: + ts.Debug.type(node); return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); - case 251 /* FunctionDeclaration */: - return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 252 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: + ts.Debug.type(node); + return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 253 /* ClassDeclaration */: + ts.Debug.type(node); return factory.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: + ts.Debug.type(node); return factory.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: + ts.Debug.type(node); return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: + ts.Debug.type(node); return factory.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); - case 256 /* ModuleDeclaration */: - return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.body, visitor, ts.isModuleBody)); - case 257 /* ModuleBlock */: + case 257 /* ModuleDeclaration */: + ts.Debug.type(node); + return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); + case 258 /* ModuleBlock */: + ts.Debug.type(node); return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: + ts.Debug.type(node); return factory.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: + ts.Debug.type(node); return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: + ts.Debug.type(node); return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: + ts.Debug.type(node); return factory.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression)); - case 262 /* ImportClause */: + case 263 /* ImportClause */: + ts.Debug.type(node); return factory.updateImportClause(node, node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.namedBindings, visitor, ts.isNamedImportBindings)); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: + ts.Debug.type(node); return factory.updateNamespaceImport(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: + ts.Debug.type(node); return factory.updateNamespaceExport(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 264 /* NamedImports */: + case 265 /* NamedImports */: + ts.Debug.type(node); return factory.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: + ts.Debug.type(node); return factory.updateImportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: + ts.Debug.type(node); return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: + ts.Debug.type(node); return factory.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression)); - case 268 /* NamedExports */: + case 269 /* NamedExports */: + ts.Debug.type(node); return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: + ts.Debug.type(node); return factory.updateExportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); // Module references - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: + ts.Debug.type(node); return factory.updateExternalModuleReference(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // JSX - case 273 /* JsxElement */: + case 274 /* JsxElement */: + ts.Debug.type(node); return factory.updateJsxElement(node, nodeVisitor(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingElement, visitor, ts.isJsxClosingElement)); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: + ts.Debug.type(node); return factory.updateJsxSelfClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes)); - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: + ts.Debug.type(node); return factory.updateJsxOpeningElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes)); - case 276 /* JsxClosingElement */: + case 277 /* JsxClosingElement */: + ts.Debug.type(node); return factory.updateJsxClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: + ts.Debug.type(node); return factory.updateJsxFragment(node, nodeVisitor(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingFragment, visitor, ts.isJsxClosingFragment)); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: + ts.Debug.type(node); return factory.updateJsxAttribute(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: + ts.Debug.type(node); return factory.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 282 /* JsxSpreadAttribute */: + case 283 /* JsxSpreadAttribute */: + ts.Debug.type(node); return factory.updateJsxSpreadAttribute(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: + ts.Debug.type(node); return factory.updateJsxExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Clauses - case 284 /* CaseClause */: + case 285 /* CaseClause */: + ts.Debug.type(node); return factory.updateCaseClause(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: + ts.Debug.type(node); return factory.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: + ts.Debug.type(node); return factory.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 287 /* CatchClause */: + case 288 /* CatchClause */: + ts.Debug.type(node); return factory.updateCatchClause(node, nodeVisitor(node.variableDeclaration, visitor, ts.isVariableDeclaration), nodeVisitor(node.block, visitor, ts.isBlock)); // Property assignments - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: + ts.Debug.type(node); return factory.updatePropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + ts.Debug.type(node); return factory.updateShorthandPropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: + ts.Debug.type(node); return factory.updateSpreadAssignment(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Enum - case 291 /* EnumMember */: + case 292 /* EnumMember */: + ts.Debug.type(node); return factory.updateEnumMember(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression)); // Top-level nodes - case 297 /* SourceFile */: + case 298 /* SourceFile */: + ts.Debug.type(node); return factory.updateSourceFile(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 336 /* PartiallyEmittedExpression */: + case 340 /* PartiallyEmittedExpression */: + ts.Debug.type(node); return factory.updatePartiallyEmittedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: + ts.Debug.type(node); return factory.updateCommaListExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -82270,7 +84911,7 @@ var ts; function chainBundle(context, transformSourceFile) { return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - return node.kind === 297 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + return node.kind === 298 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); } function transformBundle(node) { return context.factory.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); @@ -82321,7 +84962,7 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: // import "mod" // import x from "mod" // import * as x from "mod" @@ -82334,13 +84975,13 @@ var ts; hasImportDefault = true; } break; - case 260 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 272 /* ExternalModuleReference */) { + case 261 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 273 /* ExternalModuleReference */) { // import x = require("mod") externalImports.push(node); } break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" @@ -82371,13 +85012,13 @@ var ts; addExportedNamesForExportDeclaration(node); } break; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; } break; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: if (ts.hasSyntacticModifier(node, 1 /* Export */)) { for (var _b = 0, _c = node.declarationList.declarations; _b < _c.length; _b++) { var decl = _c[_b]; @@ -82385,7 +85026,7 @@ var ts; } } break; - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: if (ts.hasSyntacticModifier(node, 1 /* Export */)) { if (ts.hasSyntacticModifier(node, 512 /* Default */)) { // export default function() { } @@ -82405,7 +85046,7 @@ var ts; } } break; - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: if (ts.hasSyntacticModifier(node, 1 /* Export */)) { if (ts.hasSyntacticModifier(node, 512 /* Default */)) { // export default class { } @@ -82499,8 +85140,7 @@ var ts; * any such locations */ function isSimpleInlineableExpression(expression) { - return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression) || - ts.isWellKnownSymbolSyntactically(expression); + return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression); } ts.isSimpleInlineableExpression = isSimpleInlineableExpression; function isCompoundAssignment(kind) { @@ -82579,10 +85219,19 @@ var ts; * @param isStatic A value indicating whether the member should be a static or instance member. */ function isInitializedProperty(member) { - return member.kind === 163 /* PropertyDeclaration */ + return member.kind === 164 /* PropertyDeclaration */ && member.initializer !== undefined; } ts.isInitializedProperty = isInitializedProperty; + /** + * Gets a value indicating whether a class element is a private instance method or accessor. + * + * @param member The class element node. + */ + function isNonStaticMethodOrAccessorWithPrivateName(member) { + return !ts.hasStaticModifier(member) && ts.isMethodOrAccessor(member) && ts.isPrivateIdentifier(member.name); + } + ts.isNonStaticMethodOrAccessorWithPrivateName = isNonStaticMethodOrAccessorWithPrivateName; })(ts || (ts = {})); /*@internal*/ var ts; @@ -82856,8 +85505,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */)) + && !(element.transformFlags & (16384 /* ContainsRestOrSpread */ | 32768 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (16384 /* ContainsRestOrSpread */ | 32768 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor)); } @@ -82923,7 +85572,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 & 16384 /* ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { + if (element.transformFlags & 32768 /* ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { flattenContext.hasTransformedPriorElement = true; var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { @@ -83181,8 +85830,8 @@ var ts; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; // Enable substitution for property/element access to emit const enum values. - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(202 /* ElementAccessExpression */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(203 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; @@ -83208,14 +85857,14 @@ var ts; var applicableSubstitutions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - if (node.kind === 298 /* Bundle */) { + if (node.kind === 299 /* Bundle */) { return transformBundle(node); } return transformSourceFile(node); } function transformBundle(node) { return factory.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 300 /* InputFiles */) { + if (prepend.kind === 301 /* InputFiles */) { return ts.createUnparsedSourceFile(prepend, "js"); } return prepend; @@ -83266,16 +85915,16 @@ var ts; */ function onBeforeVisitNode(node) { switch (node.kind) { - case 297 /* SourceFile */: - case 258 /* CaseBlock */: - case 257 /* ModuleBlock */: - case 230 /* Block */: + case 298 /* SourceFile */: + case 259 /* CaseBlock */: + case 258 /* ModuleBlock */: + case 231 /* Block */: currentLexicalScope = node; currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; - case 252 /* ClassDeclaration */: - case 251 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: if (ts.hasSyntacticModifier(node, 2 /* Ambient */)) { break; } @@ -83287,7 +85936,7 @@ var ts; // These nodes should always have names unless they are default-exports; // however, class declaration parsing allows for undefined names, so syntactically invalid // programs may also have an undefined name. - ts.Debug.assert(node.kind === 252 /* ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* Default */)); + ts.Debug.assert(node.kind === 253 /* ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* Default */)); } if (ts.isClassDeclaration(node)) { // XXX: should probably also cover interfaces and type aliases that can have type variables? @@ -83330,10 +85979,10 @@ var ts; */ function sourceElementVisitorWorker(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 266 /* ExportAssignment */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 267 /* ExportAssignment */: + case 268 /* ExportDeclaration */: return visitElidableStatement(node); default: return visitorWorker(node); @@ -83354,13 +86003,13 @@ var ts; return node; } switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -83380,11 +86029,11 @@ var ts; * @param node The node to visit. */ function namespaceElementVisitorWorker(node) { - if (node.kind === 267 /* ExportDeclaration */ || - node.kind === 261 /* ImportDeclaration */ || - node.kind === 262 /* ImportClause */ || - (node.kind === 260 /* ImportEqualsDeclaration */ && - node.moduleReference.kind === 272 /* ExternalModuleReference */)) { + if (node.kind === 268 /* ExportDeclaration */ || + node.kind === 262 /* ImportDeclaration */ || + node.kind === 263 /* ImportClause */ || + (node.kind === 261 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 273 /* ExternalModuleReference */)) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -83408,26 +86057,26 @@ var ts; */ function classElementVisitorWorker(node) { switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return visitConstructor(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // Property declarations are not TypeScript syntax, but they must be visited // for the decorator transformation. return visitPropertyDeclaration(node); - case 171 /* IndexSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: + case 172 /* IndexSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: // Fallback to the default visit behavior. return visitorWorker(node); - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: return node; default: return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { - if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) { + if (ts.modifierToFlag(node.kind) & 18654 /* TypeScriptModifier */) { return undefined; } else if (currentNamespace && node.kind === 92 /* ExportKeyword */) { @@ -83460,13 +86109,13 @@ var ts; case 142 /* ReadonlyKeyword */: // TypeScript accessibility and readonly modifiers are elided // falls through - case 178 /* ArrayType */: - case 179 /* TupleType */: - case 180 /* OptionalType */: - case 181 /* RestType */: - case 177 /* TypeLiteral */: - case 172 /* TypePredicate */: - case 159 /* TypeParameter */: + case 179 /* ArrayType */: + case 180 /* TupleType */: + case 181 /* OptionalType */: + case 182 /* RestType */: + case 178 /* TypeLiteral */: + case 173 /* TypePredicate */: + case 160 /* TypeParameter */: case 128 /* AnyKeyword */: case 152 /* UnknownKeyword */: case 131 /* BooleanKeyword */: @@ -83475,43 +86124,43 @@ var ts; case 141 /* NeverKeyword */: case 113 /* VoidKeyword */: case 148 /* SymbolKeyword */: - case 175 /* ConstructorType */: - case 174 /* FunctionType */: - case 176 /* TypeQuery */: - case 173 /* TypeReference */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 184 /* ConditionalType */: - case 186 /* ParenthesizedType */: - case 187 /* ThisType */: - case 188 /* TypeOperator */: - case 189 /* IndexedAccessType */: - case 190 /* MappedType */: - case 191 /* LiteralType */: + case 176 /* ConstructorType */: + case 175 /* FunctionType */: + case 177 /* TypeQuery */: + case 174 /* TypeReference */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 185 /* ConditionalType */: + case 187 /* ParenthesizedType */: + case 188 /* ThisType */: + case 189 /* TypeOperator */: + case 190 /* IndexedAccessType */: + case 191 /* MappedType */: + case 192 /* LiteralType */: // TypeScript type nodes are elided. // falls through - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: // TypeScript index signatures are elided. // falls through - case 161 /* Decorator */: + case 162 /* Decorator */: // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. // falls through - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return undefined; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects return visitPropertyDeclaration(node); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 166 /* Constructor */: + case 167 /* Constructor */: return visitConstructor(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return factory.createNotEmittedStatement(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: // This may be a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -83521,7 +86170,7 @@ var ts; // - index signatures // - method overload signatures return visitClassDeclaration(node); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: // This may be a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -83531,35 +86180,35 @@ var ts; // - index signatures // - method overload signatures return visitClassExpression(node); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: // This may be a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause return visitHeritageClause(node); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); - case 160 /* Parameter */: + case 161 /* Parameter */: // This may be a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: @@ -83569,40 +86218,40 @@ var ts; // - type annotations // - this parameters return visitParameter(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: // ParenthesizedExpressions are TypeScript if their expression is a // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return visitNewExpression(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node); - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: return visitJsxJsxOpeningElement(node); default: // node contains some other TypeScript syntax @@ -83656,7 +86305,7 @@ var ts; return facts; } function hasTypeScriptClassSyntax(node) { - return !!(node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */); + return !!(node.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */); } function isClassLikeDeclarationWithTypeScriptSyntax(node) { return ts.some(node.decorators) @@ -84011,12 +86660,12 @@ var ts; */ function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return getAllDecoratorsOfAccessors(node, member); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return getAllDecoratorsOfMethod(member); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -84169,7 +86818,7 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); var descriptor = languageVersion > 0 /* ES3 */ - ? member.kind === 163 /* PropertyDeclaration */ + ? member.kind === 164 /* PropertyDeclaration */ // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it // should not invoke `Object.getOwnPropertyDescriptor`. ? factory.createVoidZero() @@ -84293,10 +86942,10 @@ var ts; */ function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 163 /* PropertyDeclaration */; + return kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 164 /* PropertyDeclaration */; } /** * Determines whether to emit the "design:returntype" metadata based on the node's kind. @@ -84306,7 +86955,7 @@ var ts; * @param node The node to test. */ function shouldAddReturnTypeMetadata(node) { - return node.kind === 165 /* MethodDeclaration */; + return node.kind === 166 /* MethodDeclaration */; } /** * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. @@ -84317,12 +86966,12 @@ var ts; */ function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return ts.getFirstConstructorWithBody(node) !== undefined; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return true; } return false; @@ -84339,15 +86988,15 @@ var ts; */ function serializeTypeOfNode(node) { switch (node.kind) { - case 163 /* PropertyDeclaration */: - case 160 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 161 /* Parameter */: return serializeTypeNode(node.type); - case 168 /* SetAccessor */: - case 167 /* GetAccessor */: + case 169 /* SetAccessor */: + case 168 /* GetAccessor */: return serializeTypeNode(getAccessorTypeNode(node)); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 165 /* MethodDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 166 /* MethodDeclaration */: return factory.createIdentifier("Function"); default: return factory.createVoidZero(); @@ -84384,7 +87033,7 @@ var ts; return factory.createArrayLiteralExpression(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 167 /* GetAccessor */) { + if (container && node.kind === 168 /* GetAccessor */) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -84433,27 +87082,27 @@ var ts; case 150 /* UndefinedKeyword */: case 141 /* NeverKeyword */: return factory.createVoidZero(); - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return serializeTypeNode(node.type); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return factory.createIdentifier("Function"); - case 178 /* ArrayType */: - case 179 /* TupleType */: + case 179 /* ArrayType */: + case 180 /* TupleType */: return factory.createIdentifier("Array"); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: case 131 /* BooleanKeyword */: return factory.createIdentifier("Boolean"); case 147 /* StringKeyword */: return factory.createIdentifier("String"); case 145 /* ObjectKeyword */: return factory.createIdentifier("Object"); - case 191 /* LiteralType */: + case 192 /* LiteralType */: switch (node.literal.kind) { case 10 /* StringLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: return factory.createIdentifier("String"); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: case 8 /* NumericLiteral */: return factory.createIdentifier("Number"); case 9 /* BigIntLiteral */: @@ -84474,37 +87123,37 @@ var ts; return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : factory.createIdentifier("Symbol"); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return serializeTypeReferenceNode(node); - case 183 /* IntersectionType */: - case 182 /* UnionType */: + case 184 /* IntersectionType */: + case 183 /* UnionType */: return serializeTypeList(node.types); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return serializeTypeList([node.trueType, node.falseType]); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: if (node.operator === 142 /* ReadonlyKeyword */) { return serializeTypeNode(node.type); } break; - case 176 /* TypeQuery */: - case 189 /* IndexedAccessType */: - case 190 /* MappedType */: - case 177 /* TypeLiteral */: + case 177 /* TypeQuery */: + case 190 /* IndexedAccessType */: + case 191 /* MappedType */: + case 178 /* TypeLiteral */: case 128 /* AnyKeyword */: case 152 /* UnknownKeyword */: - case 187 /* ThisType */: - case 195 /* ImportType */: + case 188 /* ThisType */: + case 196 /* ImportType */: break; // handle JSDoc types from an invalid parse - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: - case 308 /* JSDocFunctionType */: - case 309 /* JSDocVariadicType */: - case 310 /* JSDocNamepathType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: + case 309 /* JSDocFunctionType */: + case 310 /* JSDocVariadicType */: + case 311 /* JSDocNamepathType */: break; - case 305 /* JSDocNullableType */: - case 306 /* JSDocNonNullableType */: - case 307 /* JSDocOptionalType */: + case 306 /* JSDocNullableType */: + case 307 /* JSDocNonNullableType */: + case 308 /* JSDocOptionalType */: return serializeTypeNode(node.type); default: return ts.Debug.failBadSyntaxKind(node); @@ -84517,13 +87166,13 @@ var ts; var serializedUnion; for (var _i = 0, types_24 = types; _i < types_24.length; _i++) { var typeNode = types_24[_i]; - while (typeNode.kind === 186 /* ParenthesizedType */) { + while (typeNode.kind === 187 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } if (typeNode.kind === 141 /* NeverKeyword */) { continue; // Always elide `never` from the union/intersection if possible } - if (!strictNullChecks && (typeNode.kind === 191 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { + if (!strictNullChecks && (typeNode.kind === 192 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } var serializedIndividual = serializeTypeNode(typeNode); @@ -84633,7 +87282,7 @@ var ts; name.original = undefined; ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node. return name; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return serializeQualifiedNameAsExpression(node); } } @@ -85021,8 +87670,7 @@ var ts; */ function shouldEmitEnumDeclaration(node) { return !ts.isEnumConst(node) - || compilerOptions.preserveConstEnums - || compilerOptions.isolatedModules; + || ts.shouldPreserveConstEnums(compilerOptions); } /** * Visits an enum declaration. @@ -85156,7 +87804,7 @@ var ts; // If we can't find a parse tree node, assume the node is instantiated. return true; } - return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions)); } /** * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` @@ -85207,12 +87855,12 @@ var ts; // enums in any other scope are emitted as a `let` declaration. var statement = factory.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.createVariableDeclarationList([ factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ], currentLexicalScope.kind === 297 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ], currentLexicalScope.kind === 298 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { // Adjust the source map emit to match the old emitter. - if (node.kind === 255 /* EnumDeclaration */) { + if (node.kind === 256 /* EnumDeclaration */) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -85337,7 +87985,7 @@ var ts; var statementsLocation; var blockLocation; if (node.body) { - if (node.body.kind === 257 /* ModuleBlock */) { + if (node.body.kind === 258 /* ModuleBlock */) { saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = node.body.statements; blockLocation = node.body; @@ -85384,13 +88032,13 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (!node.body || node.body.kind !== 257 /* ModuleBlock */) { + if (!node.body || node.body.kind !== 258 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 256 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 257 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -85440,7 +88088,7 @@ var ts; * @param node The named import bindings node. */ function visitNamedImportBindings(node) { - if (node.kind === 263 /* NamespaceImport */) { + if (node.kind === 264 /* NamespaceImport */) { // Elide a namespace import if it is not referenced. return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } @@ -85693,16 +88341,16 @@ var ts; // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to // substitute the names of exported members of a namespace. context.enableSubstitution(78 /* Identifier */); - context.enableSubstitution(289 /* ShorthandPropertyAssignment */); + context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // We need to be notified when entering and exiting namespaces. - context.enableEmitNotification(256 /* ModuleDeclaration */); + context.enableEmitNotification(257 /* ModuleDeclaration */); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 256 /* ModuleDeclaration */; + return ts.getOriginalNode(node).kind === 257 /* ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 255 /* EnumDeclaration */; + return ts.getOriginalNode(node).kind === 256 /* EnumDeclaration */; } /** * Hook for node emit. @@ -85763,9 +88411,9 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return substituteExpressionIdentifier(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return substituteElementAccessExpression(node); } return node; @@ -85787,10 +88435,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_1 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_1, node); - ts.setCommentRange(clone_1, node); - return clone_1; + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -85803,9 +88451,9 @@ var ts; // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container && container.kind !== 297 /* SourceFile */) { - var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 256 /* ModuleDeclaration */) || - (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 255 /* EnumDeclaration */); + if (container && container.kind !== 298 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 257 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 256 /* EnumDeclaration */); if (substitute) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(container), node), /*location*/ node); @@ -85857,10 +88505,12 @@ var ts; */ ClassPropertySubstitutionFlags[ClassPropertySubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; })(ClassPropertySubstitutionFlags || (ClassPropertySubstitutionFlags = {})); - var PrivateIdentifierPlacement; - (function (PrivateIdentifierPlacement) { - PrivateIdentifierPlacement[PrivateIdentifierPlacement["InstanceField"] = 0] = "InstanceField"; - })(PrivateIdentifierPlacement || (PrivateIdentifierPlacement = {})); + var PrivateIdentifierKind; + (function (PrivateIdentifierKind) { + PrivateIdentifierKind["Field"] = "f"; + PrivateIdentifierKind["Method"] = "m"; + PrivateIdentifierKind["Accessor"] = "a"; + })(PrivateIdentifierKind = ts.PrivateIdentifierKind || (ts.PrivateIdentifierKind = {})); /** * Transforms ECMAScript Class Syntax. * TypeScript parameter property syntax is transformed in the TypeScript transformer. @@ -85869,11 +88519,12 @@ var ts; * When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty. */ function transformClassFields(context) { - var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment; + var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, addBlockScopedVariable = context.addBlockScopedVariable; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var shouldTransformPrivateFields = languageVersion < 99 /* ESNext */; + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); + var shouldTransformPrivateElements = languageVersion < 99 /* ESNext */; var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; var enabledSubstitutions; @@ -85894,7 +88545,7 @@ var ts; function transformSourceFile(node) { var options = context.getCompilerOptions(); if (node.isDeclarationFile - || options.useDefineForClassFields && options.target === 99 /* ESNext */) { + || useDefineForClassFields && options.target === 99 /* ESNext */) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -85902,41 +88553,41 @@ var ts; return visited; } function visitor(node) { - if (!(node.transformFlags & 4194304 /* ContainsClassFields */)) + if (!(node.transformFlags & 8388608 /* ContainsClassFields */)) return node; switch (node.kind) { - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: return visitClassLike(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return visitPropertyDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return visitPropertyAccessExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return visitPrefixUnaryExpression(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return visitPostfixUnaryExpression(node, /*valueIsDiscarded*/ false); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node); case 79 /* PrivateIdentifier */: return visitPrivateIdentifier(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitExpressionStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); } return ts.visitEachChild(node, visitor, context); } function visitorDestructuringTarget(node) { switch (node.kind) { - case 200 /* ObjectLiteralExpression */: - case 199 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitAssignmentPattern(node); default: return visitor(node); @@ -85947,7 +88598,7 @@ var ts; * Replace it with an empty identifier to indicate a problem with the code. */ function visitPrivateIdentifier(node) { - if (!shouldTransformPrivateFields) { + if (!shouldTransformPrivateElements) { return node; } return ts.setOriginalNode(factory.createIdentifier(""), node); @@ -85959,20 +88610,19 @@ var ts; */ function classElementVisitor(node) { switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: // Constructors for classes using class fields are transformed in // `visitClassDeclaration` or `visitClassExpression`. return undefined; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: - // Visit the name of the member (if it's a computed property name). - return ts.visitEachChild(node, classElementVisitor, context); - case 163 /* PropertyDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + return visitMethodOrAccessorDeclaration(node); + case 164 /* PropertyDeclaration */: return visitPropertyDeclaration(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: return node; default: return visitor(node); @@ -85997,44 +88647,96 @@ var ts; } return node; } + function visitMethodOrAccessorDeclaration(node) { + ts.Debug.assert(!ts.some(node.decorators)); + if (!shouldTransformPrivateElements || !ts.isPrivateIdentifier(node.name)) { + return ts.visitEachChild(node, classElementVisitor, context); + } + // leave invalid code untransformed + var info = accessPrivateIdentifier(node.name); + ts.Debug.assert(info, "Undeclared private name for property declaration."); + if (!info.isValid) { + return node; + } + var functionName = getHoistedFunctionName(node); + if (functionName) { + getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return !ts.isStaticModifier(m); }), node.asteriskToken, functionName, + /* typeParameters */ undefined, ts.visitParameterList(node.parameters, classElementVisitor, context), + /* type */ undefined, ts.visitFunctionBody(node.body, classElementVisitor, context)))); + } + // remove method declaration from class + return undefined; + } + function getHoistedFunctionName(node) { + ts.Debug.assert(ts.isPrivateIdentifier(node.name)); + var info = accessPrivateIdentifier(node.name); + ts.Debug.assert(info, "Undeclared private name for property declaration."); + if (info.kind === "m" /* Method */) { + return info.methodName; + } + if (info.kind === "a" /* Accessor */) { + if (ts.isGetAccessor(node)) { + return info.getterName; + } + if (ts.isSetAccessor(node)) { + return info.setterName; + } + } + } function visitPropertyDeclaration(node) { ts.Debug.assert(!ts.some(node.decorators)); - if (!shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) { - // Initializer is elided as the field is initialized in transformConstructor. - return factory.updatePropertyDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, - /*questionOrExclamationToken*/ undefined, - /*type*/ undefined, - /*initializer*/ undefined); + if (ts.isPrivateIdentifier(node.name)) { + if (!shouldTransformPrivateElements) { + // Initializer is elided as the field is initialized in transformConstructor. + return factory.updatePropertyDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined); + } + // leave invalid code untransformed + var info = accessPrivateIdentifier(node.name); + ts.Debug.assert(info, "Undeclared private name for property declaration."); + if (!info.isValid) { + return node; + } } // Create a temporary variable to store a computed property name (if necessary). // If it's not inlineable, then we emit an expression after the class which assigns // the property name to the temporary variable. - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { getPendingExpressions().push(expr); } return undefined; } function createPrivateIdentifierAccess(info, receiver) { - receiver = ts.visitNode(receiver, visitor, ts.isExpression); - switch (info.placement) { - case 0 /* InstanceField */: - return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(ts.nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver), info.weakMapName); - default: return ts.Debug.fail("Unexpected private identifier placement"); + return createPrivateIdentifierAccessHelper(info, ts.visitNode(receiver, visitor, ts.isExpression)); + } + function createPrivateIdentifierAccessHelper(info, receiver) { + ts.setCommentRange(receiver, ts.moveRangePos(receiver, -1)); + switch (info.kind) { + case "a" /* Accessor */: + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.getterName); + case "m" /* Method */: + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.methodName); + case "f" /* Field */: + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.variableName); + default: + ts.Debug.assertNever(info, "Unknown private element type"); } } function visitPropertyAccessExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifier(node.name)) { var privateIdentifierInfo = accessPrivateIdentifier(node.name); if (privateIdentifierInfo) { - return ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node); + return ts.setTextRange(ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node), node); } } return ts.visitEachChild(node, visitor, context); } function visitPrefixUnaryExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { var operator = node.operator === 45 /* PlusPlusToken */ ? 39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ? 40 /* MinusToken */ : undefined; @@ -86049,7 +88751,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitPostfixUnaryExpression(node, valueIsDiscarded) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { var operator = node.operator === 45 /* PlusPlusToken */ ? 39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ? 40 /* MinusToken */ : undefined; @@ -86070,7 +88772,7 @@ var ts; } function visitForStatement(node) { if (node.incrementor && ts.isPostfixUnaryExpression(node.incrementor)) { - return factory.updateForStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), visitPostfixUnaryExpression(node.incrementor, /*valueIsDiscarded*/ true), ts.visitNode(node.statement, visitor, ts.isStatement)); + return factory.updateForStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), visitPostfixUnaryExpression(node.incrementor, /*valueIsDiscarded*/ true), ts.visitIterationBody(node.statement, visitor, context)); } return ts.visitEachChild(node, visitor, context); } @@ -86090,16 +88792,21 @@ var ts; return { readExpression: readExpression, initializeExpression: initializeExpression }; } function visitCallExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { // Transform call expressions of private names to properly bind the `this` parameter. var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; + if (ts.isCallChain(node)) { + return factory.updateCallChain(node, factory.createPropertyAccessChain(ts.visitNode(target, visitor), node.questionDotToken, "call"), + /*questionDotToken*/ undefined, + /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); + } return factory.updateCallExpression(node, factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "call"), /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); } return ts.visitEachChild(node, visitor, context); } function visitTaggedTemplateExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) { // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access. var _a = factory.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; return factory.updateTaggedTemplateExpression(node, factory.createCallExpression(factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "bind"), @@ -86109,7 +88816,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitBinaryExpression(node) { - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { if (ts.isDestructuringAssignment(node)) { var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; @@ -86123,29 +88830,31 @@ var ts; if (ts.isAssignmentExpression(node) && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) { var info = accessPrivateIdentifier(node.left.name); if (info) { - return ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node); + return ts.setTextRange(ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node), node); } } } return ts.visitEachChild(node, visitor, context); } function createPrivateIdentifierAssignment(info, receiver, right, operator) { - switch (info.placement) { - case 0 /* InstanceField */: { - return createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator); - } - default: return ts.Debug.fail("Unexpected private identifier placement"); - } - } - function createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator) { receiver = ts.visitNode(receiver, visitor, ts.isExpression); right = ts.visitNode(right, visitor, ts.isExpression); if (ts.isCompoundAssignment(operator)) { var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression; - return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(initializeExpression || readExpression, info.weakMapName, factory.createBinaryExpression(context.getEmitHelperFactory().createClassPrivateFieldGetHelper(readExpression, info.weakMapName), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right)); - } - else { - return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.weakMapName, right); + receiver = initializeExpression || readExpression; + right = factory.createBinaryExpression(createPrivateIdentifierAccessHelper(info, readExpression), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right); + } + ts.setCommentRange(receiver, ts.moveRangePos(receiver, -1)); + switch (info.kind) { + case "a" /* Accessor */: + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, info.setterName); + case "m" /* Method */: + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, + /* f */ undefined); + case "f" /* Field */: + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, info.variableName); + default: + ts.Debug.assertNever(info, "Unknown private element type"); } } /** @@ -86154,25 +88863,43 @@ var ts; function visitClassLike(node) { var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { startPrivateIdentifierEnvironment(); + var name = ts.getNameOfDeclaration(node); + if (name && ts.isIdentifier(name)) { + getPrivateIdentifierEnvironment().className = ts.idText(name); + } + var privateInstanceMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); + if (ts.some(privateInstanceMethodsAndAccessors)) { + getPrivateIdentifierEnvironment().weakSetName = createHoistedVariableForClass("instances", privateInstanceMethodsAndAccessors[0].name); + } } var result = ts.isClassDeclaration(node) ? visitClassDeclaration(node) : visitClassExpression(node); - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { endPrivateIdentifierEnvironment(); } pendingExpressions = savedPendingExpressions; return result; } function doesClassElementNeedTransform(node) { - return ts.isPropertyDeclaration(node) || (shouldTransformPrivateFields && node.name && ts.isPrivateIdentifier(node.name)); + return ts.isPropertyDeclaration(node) || (shouldTransformPrivateElements && node.name && ts.isPrivateIdentifier(node.name)); + } + function getPrivateInstanceMethodsAndAccessors(node) { + return ts.filter(node.members, ts.isNonStaticMethodOrAccessorWithPrivateName); } function visitClassDeclaration(node) { if (!ts.forEach(node.members, doesClassElementNeedTransform)) { return ts.visitEachChild(node, visitor, context); } + var staticProperties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ true); + var pendingPrivateStateAssignment; + if (shouldTransformPrivateElements && ts.some(node.members, function (m) { return ts.hasStaticModifier(m) && !!m.name && ts.isPrivateIdentifier(m.name); })) { + var temp = factory.createTempVariable(hoistVariableDeclaration, /* reservedInNestedScopes */ true); + getPrivateIdentifierEnvironment().classConstructor = factory.cloneNode(temp); + pendingPrivateStateAssignment = factory.createAssignment(temp, factory.getInternalName(node)); + } var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */); var statements = [ @@ -86180,6 +88907,9 @@ var ts; /*decorators*/ undefined, node.modifiers, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)) ]; + if (pendingPrivateStateAssignment) { + getPendingExpressions().unshift(pendingPrivateStateAssignment); + } // Write any pending expressions from elided or moved computed property names if (ts.some(pendingExpressions)) { statements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))); @@ -86189,7 +88919,6 @@ var ts; // From ES6 specification: // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. - var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); if (ts.some(staticProperties)) { addPropertyStatements(statements, staticProperties, factory.getInternalName(node)); } @@ -86207,12 +88936,25 @@ var ts; // class declaration transformation. The VariableStatement visitor will insert // these statements after the class expression variable statement. var isDecoratedClassDeclaration = ts.isClassDeclaration(ts.getOriginalNode(node)); - var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); + var staticProperties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ true); var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */); + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; + var temp; + function createClassTempVar() { + var classCheckFlags = resolver.getNodeCheckFlags(node); + var isClassWithConstructorReference = classCheckFlags & 16777216 /* ClassWithConstructorReference */; + var requiresBlockScopedVar = classCheckFlags & 524288 /* BlockScopedBindingInLoop */; + return factory.createTempVariable(requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, !!isClassWithConstructorReference); + } + if (shouldTransformPrivateElements && ts.some(node.members, function (m) { return ts.hasStaticModifier(m) && !!m.name && ts.isPrivateIdentifier(m.name); })) { + temp = createClassTempVar(); + getPrivateIdentifierEnvironment().classConstructor = factory.cloneNode(temp); + } var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)); - if (ts.some(staticProperties) || ts.some(pendingExpressions)) { + var hasTransformableStatics = ts.some(staticProperties, function (p) { return !!p.initializer || (shouldTransformPrivateElements && ts.isPrivateIdentifier(p.name)); }); + if (hasTransformableStatics || ts.some(pendingExpressions)) { if (isDecoratedClassDeclaration) { ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration."); // Write any pending expressions from elided or moved computed property names @@ -86222,12 +88964,14 @@ var ts; if (pendingStatements && ts.some(staticProperties)) { addPropertyStatements(pendingStatements, staticProperties, factory.getInternalName(node)); } + if (temp) { + return factory.inlineExpressions([factory.createAssignment(temp, classExpression), temp]); + } return classExpression; } else { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; - var temp = factory.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + temp || (temp = createClassTempVar()); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); @@ -86249,14 +88993,17 @@ var ts; return classExpression; } function transformClassMembers(node, isDerivedClass) { - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { // Declare private names. for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (ts.isPrivateIdentifierPropertyDeclaration(member)) { - addPrivateIdentifierToEnvironment(member.name); + if (ts.isPrivateIdentifierClassElementDeclaration(member)) { + addPrivateIdentifierToEnvironment(member); } } + if (ts.some(getPrivateInstanceMethodsAndAccessors(node))) { + createBrandCheckWeakSetForPrivateMethods(); + } } var members = []; var constructor = transformConstructor(node, isDerivedClass); @@ -86266,21 +89013,27 @@ var ts; ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members); } - function isPropertyDeclarationThatRequiresConstructorStatement(member) { - if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* Abstract */)) { + function createBrandCheckWeakSetForPrivateMethods() { + var weakSetName = getPrivateIdentifierEnvironment().weakSetName; + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + getPendingExpressions().push(factory.createAssignment(weakSetName, factory.createNewExpression(factory.createIdentifier("WeakSet"), + /*typeArguments*/ undefined, []))); + } + function isClassElementThatRequiresConstructorStatement(member) { + if (ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* Abstract */)) { return false; } - if (context.getCompilerOptions().useDefineForClassFields) { + if (useDefineForClassFields) { // If we are using define semantics and targeting ESNext or higher, // then we don't need to transform any class properties. return languageVersion < 99 /* ESNext */; } - return ts.isInitializedProperty(member) || shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyDeclaration(member); + return ts.isInitializedProperty(member) || shouldTransformPrivateElements && ts.isPrivateIdentifierClassElementDeclaration(member); } function transformConstructor(node, isDerivedClass) { var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration); - var properties = node.members.filter(isPropertyDeclarationThatRequiresConstructorStatement); - if (!ts.some(properties)) { + var elements = node.members.filter(isClassElementThatRequiresConstructorStatement); + if (!ts.some(elements)) { return constructor; } var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context); @@ -86293,13 +89046,14 @@ var ts; /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { - var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false); if (!useDefineForClassFields) { properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); }); } + var privateMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); + var needsConstructorBody = ts.some(properties) || ts.some(privateMethodsAndAccessors); // Only generate synthetic constructor when there are property initializers to move. - if (!constructor && !ts.some(properties)) { + if (!constructor && !needsConstructorBody) { return ts.visitFunctionBody(/*node*/ undefined, visitor, context); } resumeLexicalEnvironment(); @@ -86338,7 +89092,10 @@ var ts; indexOfFirstStatement = afterParameterProperties; } } - addPropertyStatements(statements, properties, factory.createThis()); + var receiver = factory.createThis(); + // private methods can be called in property initializers, they should execute first. + addMethodStatements(statements, privateMethodsAndAccessors, receiver); + addPropertyStatements(statements, properties, receiver); // Add existing statements, skipping the initial super call. if (constructor) { ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); @@ -86400,27 +89157,30 @@ var ts; function transformProperty(property, receiver) { var _a; // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) - var emitAssignment = !context.getCompilerOptions().useDefineForClassFields; + var emitAssignment = !useDefineForClassFields; var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression) ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name)) : property.name; - if (shouldTransformPrivateFields && ts.isPrivateIdentifier(propertyName)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifier(propertyName)) { var privateIdentifierInfo = accessPrivateIdentifier(propertyName); if (privateIdentifierInfo) { - switch (privateIdentifierInfo.placement) { - case 0 /* InstanceField */: { - return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.weakMapName); + if (privateIdentifierInfo.kind === "f" /* Field */) { + if (!privateIdentifierInfo.isStatic) { + return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.brandCheckIdentifier); + } + else { + return createPrivateStaticFieldInitializer(privateIdentifierInfo.variableName, ts.visitNode(property.initializer, visitor, ts.isExpression)); } } + else { + return undefined; + } } else { ts.Debug.fail("Undeclared private name for property declaration."); } } - if (ts.isPrivateIdentifier(propertyName) && !property.initializer) { - return undefined; - } - if (ts.isPrivateIdentifier(propertyName) && !property.initializer) { + if ((ts.isPrivateIdentifier(propertyName) || ts.hasStaticModifier(property)) && !property.initializer) { return undefined; } var propertyOriginalNode = ts.getOriginalNode(property); @@ -86452,6 +89212,21 @@ var ts; classAliases = []; } } + /** + * Generates brand-check initializer for private methods. + * + * @param statements Statement list that should be used to append new statements. + * @param methods An array of method declarations. + * @param receiver The receiver on which each method should be assigned. + */ + function addMethodStatements(statements, methods, receiver) { + if (!shouldTransformPrivateElements || !ts.some(methods)) { + return; + } + var weakSetName = getPrivateIdentifierEnvironment().weakSetName; + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + statements.push(factory.createExpressionStatement(createPrivateInstanceMethodInitializer(receiver, weakSetName))); + } /** * Hooks node substitutions. * @@ -86487,10 +89262,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_2 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_2, node); - ts.setCommentRange(clone_2, node); - return clone_2; + var clone_3 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_3, node); + ts.setCommentRange(clone_3, node); + return clone_3; } } } @@ -86510,7 +89285,12 @@ var ts; var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left); if (!alreadyTransformed && !inlinable && shouldHoist) { var generatedName = factory.getGeneratedNameForNode(name); - hoistVariableDeclaration(generatedName); + if (resolver.getNodeCheckFlags(name) & 524288 /* BlockScopedBindingInLoop */) { + addBlockScopedVariable(generatedName); + } + else { + hoistVariableDeclaration(generatedName); + } return factory.createAssignment(generatedName, expression); } return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression; @@ -86524,22 +89304,164 @@ var ts; currentPrivateIdentifierEnvironment = privateIdentifierEnvironmentStack.pop(); } function getPrivateIdentifierEnvironment() { - return currentPrivateIdentifierEnvironment || (currentPrivateIdentifierEnvironment = new ts.Map()); + if (!currentPrivateIdentifierEnvironment) { + currentPrivateIdentifierEnvironment = { + className: "", + identifiers: new ts.Map() + }; + } + return currentPrivateIdentifierEnvironment; } function getPendingExpressions() { return pendingExpressions || (pendingExpressions = []); } - function addPrivateIdentifierToEnvironment(name) { - var text = ts.getTextOfPropertyName(name); - var weakMapName = factory.createUniqueName("_" + text.substring(1), 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */); - hoistVariableDeclaration(weakMapName); - getPrivateIdentifierEnvironment().set(name.escapedText, { placement: 0 /* InstanceField */, weakMapName: weakMapName }); - getPendingExpressions().push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), - /*typeArguments*/ undefined, []))); + function addPrivateIdentifierToEnvironment(node) { + var _a; + var text = ts.getTextOfPropertyName(node.name); + var env = getPrivateIdentifierEnvironment(); + var weakSetName = env.weakSetName, classConstructor = env.classConstructor; + var assignmentExpressions = []; + var privateName = node.name.escapedText; + var previousInfo = env.identifiers.get(privateName); + var isValid = !isReservedPrivateName(node.name) && previousInfo === undefined; + if (ts.hasStaticModifier(node)) { + ts.Debug.assert(classConstructor, "weakSetName should be set in private identifier environment"); + if (ts.isPropertyDeclaration(node)) { + var variableName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: "f" /* Field */, + variableName: variableName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + else if (ts.isMethodDeclaration(node)) { + var functionName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: "m" /* Method */, + methodName: functionName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + else if (ts.isGetAccessorDeclaration(node)) { + var getterName = createHoistedVariableForPrivateName(text + "_get", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic && !previousInfo.getterName) { + previousInfo.getterName = getterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: getterName, + setterName: undefined, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + } + else if (ts.isSetAccessorDeclaration(node)) { + var setterName = createHoistedVariableForPrivateName(text + "_set", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic && !previousInfo.setterName) { + previousInfo.setterName = setterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: undefined, + setterName: setterName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + } + else { + ts.Debug.assertNever(node, "Unknown class element type."); + } + } + else if (ts.isPropertyDeclaration(node)) { + var weakMapName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: "f" /* Field */, + brandCheckIdentifier: weakMapName, + isStatic: false, + variableName: undefined, + isValid: isValid, + }); + assignmentExpressions.push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), + /*typeArguments*/ undefined, []))); + } + else if (ts.isMethodDeclaration(node)) { + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + env.identifiers.set(privateName, { + kind: "m" /* Method */, + methodName: createHoistedVariableForPrivateName(text, node), + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + else if (ts.isAccessor(node)) { + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + if (ts.isGetAccessor(node)) { + var getterName = createHoistedVariableForPrivateName(text + "_get", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && !previousInfo.isStatic && !previousInfo.getterName) { + previousInfo.getterName = getterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: getterName, + setterName: undefined, + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + } + else { + var setterName = createHoistedVariableForPrivateName(text + "_set", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && !previousInfo.isStatic && !previousInfo.setterName) { + previousInfo.setterName = setterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: undefined, + setterName: setterName, + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + } + } + else { + ts.Debug.assertNever(node, "Unknown class element type."); + } + (_a = getPendingExpressions()).push.apply(_a, assignmentExpressions); + } + function createHoistedVariableForClass(name, node) { + var className = getPrivateIdentifierEnvironment().className; + var prefix = className ? "_" + className : ""; + var identifier = factory.createUniqueName(prefix + "_" + name, 16 /* Optimistic */); + if (resolver.getNodeCheckFlags(node) & 524288 /* BlockScopedBindingInLoop */) { + addBlockScopedVariable(identifier); + } + else { + hoistVariableDeclaration(identifier); + } + return identifier; + } + function createHoistedVariableForPrivateName(privateName, node) { + return createHoistedVariableForClass(privateName.substring(1), node.name); } function accessPrivateIdentifier(name) { if (currentPrivateIdentifierEnvironment) { - var info = currentPrivateIdentifierEnvironment.get(name.escapedText); + var info = currentPrivateIdentifierEnvironment.identifiers.get(name.escapedText); if (info) { return info; } @@ -86549,7 +89471,7 @@ var ts; if (!env) { continue; } - var info = env.get(name.escapedText); + var info = env.identifiers.get(name.escapedText); if (info) { return info; } @@ -86635,10 +89557,22 @@ var ts; } } ts.transformClassFields = transformClassFields; + function createPrivateStaticFieldInitializer(variableName, initializer) { + return ts.factory.createAssignment(variableName, ts.factory.createObjectLiteralExpression([ + ts.factory.createPropertyAssignment("value", initializer || ts.factory.createVoidZero()) + ])); + } function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) { return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakMapName, "set"), /*typeArguments*/ undefined, [receiver, initializer || ts.factory.createVoidZero()]); } + function createPrivateInstanceMethodInitializer(receiver, weakSetName) { + return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakSetName, "add"), + /*typeArguments*/ undefined, [receiver]); + } + function isReservedPrivateName(node) { + return node.escapedText === "#constructor"; + } })(ts || (ts = {})); /*@internal*/ var ts; @@ -86721,38 +89655,38 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 64 /* ContainsES2017 */) === 0) { + if ((node.transformFlags & 128 /* ContainsES2017 */) === 0) { return node; } switch (node.kind) { case 129 /* AsyncKeyword */: // ES2017 async modifier should be elided for targets < ES2017 return undefined; - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return visitAwaitExpression(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105 /* SuperKeyword */) { capturedSuperProperties.add(node.name.escapedText); } return ts.visitEachChild(node, visitor, context); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: if (capturedSuperProperties && node.expression.kind === 105 /* SuperKeyword */) { hasSuperElementAccess = true; } return ts.visitEachChild(node, visitor, context); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 166 /* Constructor */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 167 /* Constructor */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node); default: return ts.visitEachChild(node, visitor, context); @@ -86761,27 +89695,27 @@ var ts; function asyncBodyVisitor(node) { if (ts.isNodeWithPossibleHoistedDeclaration(node)) { switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatementInAsyncBody(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatementInAsyncBody(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatementInAsyncBody(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatementInAsyncBody(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClauseInAsyncBody(node); - case 230 /* Block */: - case 244 /* SwitchStatement */: - case 258 /* CaseBlock */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: - case 247 /* TryStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 234 /* IfStatement */: - case 243 /* WithStatement */: - case 245 /* LabeledStatement */: + case 231 /* Block */: + case 245 /* SwitchStatement */: + case 259 /* CaseBlock */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 248 /* TryStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 235 /* IfStatement */: + case 244 /* WithStatement */: + case 246 /* LabeledStatement */: return ts.visitEachChild(node, asyncBodyVisitor, context); default: return ts.Debug.assertNever(node, "Unhandled node."); @@ -86823,18 +89757,18 @@ var ts; function visitForInStatementInAsyncBody(node) { return factory.updateForInStatement(node, isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) - : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock)); + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context)); } function visitForOfStatementInAsyncBody(node) { return factory.updateForOfStatement(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) - : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock)); + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context)); } function visitForStatementInAsyncBody(node) { var initializer = node.initializer; // TODO: GH#18217 return factory.updateForStatement(node, isVariableDeclarationListWithCollidingName(initializer) ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false) - : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock)); + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context)); } /** * Visits an AwaitExpression node. @@ -86986,7 +89920,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 209 /* ArrowFunction */; + var isArrowFunction = node.kind === 210 /* ArrowFunction */; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current @@ -87077,17 +90011,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(203 /* CallExpression */); - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(202 /* ElementAccessExpression */); + context.enableSubstitution(204 /* CallExpression */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(203 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(252 /* ClassDeclaration */); - context.enableEmitNotification(165 /* MethodDeclaration */); - context.enableEmitNotification(167 /* GetAccessor */); - context.enableEmitNotification(168 /* SetAccessor */); - context.enableEmitNotification(166 /* Constructor */); + context.enableEmitNotification(253 /* ClassDeclaration */); + context.enableEmitNotification(166 /* MethodDeclaration */); + context.enableEmitNotification(168 /* GetAccessor */); + context.enableEmitNotification(169 /* SetAccessor */); + context.enableEmitNotification(167 /* Constructor */); // We need to be notified when entering the generated accessor arrow functions. - context.enableEmitNotification(232 /* VariableStatement */); + context.enableEmitNotification(233 /* VariableStatement */); } } /** @@ -87135,11 +90069,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return substituteCallExpression(node); } return node; @@ -87171,11 +90105,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 252 /* ClassDeclaration */ - || kind === 166 /* Constructor */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 253 /* ClassDeclaration */ + || kind === 167 /* Constructor */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { @@ -87354,74 +90288,74 @@ var ts; * expression of an `ExpressionStatement`). */ function visitorWorker(node, expressionResultIsUnused) { - if ((node.transformFlags & 32 /* ContainsES2018 */) === 0) { + if ((node.transformFlags & 64 /* ContainsES2018 */) === 0) { return node; } switch (node.kind) { - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return visitAwaitExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitYieldExpression(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitReturnStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node, expressionResultIsUnused); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitCommaListExpression(node, expressionResultIsUnused); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 238 /* ForInStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 239 /* ForInStatement */: return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return visitVoidExpression(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */); - case 160 /* Parameter */: + case 161 /* Parameter */: return visitParameter(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitExpressionStatement(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, expressionResultIsUnused); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105 /* SuperKeyword */) { capturedSuperProperties.add(node.name.escapedText); } return ts.visitEachChild(node, visitor, context); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: if (capturedSuperProperties && node.expression.kind === 105 /* SuperKeyword */) { hasSuperElementAccess = true; } return ts.visitEachChild(node, visitor, context); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); default: return ts.visitEachChild(node, visitor, context); @@ -87457,7 +90391,7 @@ var ts; function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 239 /* ForOfStatement */ && statement.awaitModifier) { + if (statement.kind === 240 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } return factory.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, factory.liftToBlock), node); @@ -87469,7 +90403,7 @@ var ts; var objects = []; for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { var e = elements_4[_i]; - if (e.kind === 290 /* SpreadAssignment */) { + if (e.kind === 291 /* SpreadAssignment */) { if (chunkObject) { objects.push(factory.createObjectLiteralExpression(chunkObject)); chunkObject = undefined; @@ -87478,7 +90412,7 @@ var ts; objects.push(ts.visitNode(target, visitor, ts.isExpression)); } else { - chunkObject = ts.append(chunkObject, e.kind === 288 /* PropertyAssignment */ + chunkObject = ts.append(chunkObject, e.kind === 289 /* PropertyAssignment */ ? factory.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } @@ -87489,7 +90423,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign(__assign({a}, o), {b}); @@ -87512,7 +90446,7 @@ var ts; // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we // end up with `{ a: 1, b: 2, c: 3 }` var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 200 /* ObjectLiteralExpression */) { + if (objects.length && objects[0].kind !== 201 /* ObjectLiteralExpression */) { objects.unshift(factory.createObjectLiteralExpression()); } var expression = objects[0]; @@ -87562,7 +90496,7 @@ var ts; * expression of an `ExpressionStatement`). */ function visitBinaryExpression(node, expressionResultIsUnused) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !expressionResultIsUnused); } if (node.operatorToken.kind === 27 /* CommaToken */) { @@ -87593,7 +90527,7 @@ var ts; function visitCatchClause(node) { if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name) && - node.variableDeclaration.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + node.variableDeclaration.name.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { var name = factory.getGeneratedNameForNode(node.variableDeclaration.name); var updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name); var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */); @@ -87634,14 +90568,14 @@ var ts; } function visitVariableDeclarationWorker(node, exportedVariableStatement) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */, /*rval*/ undefined, exportedVariableStatement); } return ts.visitEachChild(node, visitor, context); } function visitForStatement(node) { - return factory.updateForStatement(node, ts.visitNode(node.initializer, visitorWithUnusedExpressionResult, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitorWithUnusedExpressionResult, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement)); + return factory.updateForStatement(node, ts.visitNode(node.initializer, visitorWithUnusedExpressionResult, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitorWithUnusedExpressionResult, ts.isExpression), ts.visitIterationBody(node.statement, visitor, context)); } function visitVoidExpression(node) { return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context); @@ -87653,7 +90587,7 @@ var ts; */ function visitForOfStatement(node, outermostLabeledStatement) { var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); - if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (node.initializer.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } var result = node.awaitModifier ? @@ -87691,7 +90625,7 @@ var ts; var bodyLocation; var statementsLocation; var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; - var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + var statement = ts.visitIterationBody(node.statement, visitor, context); if (ts.isBlock(statement)) { ts.addRange(statements, statement.statements); bodyLocation = statement; @@ -87753,7 +90687,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return factory.updateParameterDeclaration(node, @@ -87905,7 +90839,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 & 16384 /* ContainsObjectRestOrSpread */) { + if (parameter.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { var temp = factory.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -87925,17 +90859,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(203 /* CallExpression */); - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(202 /* ElementAccessExpression */); + context.enableSubstitution(204 /* CallExpression */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(203 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(252 /* ClassDeclaration */); - context.enableEmitNotification(165 /* MethodDeclaration */); - context.enableEmitNotification(167 /* GetAccessor */); - context.enableEmitNotification(168 /* SetAccessor */); - context.enableEmitNotification(166 /* Constructor */); + context.enableEmitNotification(253 /* ClassDeclaration */); + context.enableEmitNotification(166 /* MethodDeclaration */); + context.enableEmitNotification(168 /* GetAccessor */); + context.enableEmitNotification(169 /* SetAccessor */); + context.enableEmitNotification(167 /* Constructor */); // We need to be notified when entering the generated accessor arrow functions. - context.enableEmitNotification(232 /* VariableStatement */); + context.enableEmitNotification(233 /* VariableStatement */); } } /** @@ -87983,11 +90917,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return substituteCallExpression(node); } return node; @@ -88019,11 +90953,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 252 /* ClassDeclaration */ - || kind === 166 /* Constructor */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 253 /* ClassDeclaration */ + || kind === 167 /* Constructor */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { @@ -88051,11 +90985,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 16 /* ContainsES2019 */) === 0) { + if ((node.transformFlags & 32 /* ContainsES2019 */) === 0) { return node; } switch (node.kind) { - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); @@ -88083,25 +91017,29 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 8 /* ContainsES2020 */) === 0) { + if ((node.transformFlags & 16 /* ContainsES2020 */) === 0) { return node; } switch (node.kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: - case 203 /* CallExpression */: - if (node.flags & 32 /* OptionalChain */) { + case 204 /* CallExpression */: { + var updated = visitNonOptionalCallExpression(node, /*captureThisArg*/ false); + ts.Debug.assertNotNode(updated, ts.isSyntheticReference); + return updated; + } + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + if (ts.isOptionalChain(node)) { var updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false); ts.Debug.assertNotNode(updated, ts.isSyntheticReference); return updated; } return ts.visitEachChild(node, visitor, context); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (node.operatorToken.kind === 60 /* QuestionQuestionToken */) { return transformNullishCoalescingExpression(node); } return ts.visitEachChild(node, visitor, context); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return visitDeleteExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -88143,7 +91081,7 @@ var ts; thisArg = expression; } } - expression = node.kind === 201 /* PropertyAccessExpression */ + expression = node.kind === 202 /* PropertyAccessExpression */ ? factory.updatePropertyAccessExpression(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)) : factory.updateElementAccessExpression(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); return thisArg ? factory.createSyntheticReferenceExpression(expression, thisArg) : expression; @@ -88153,14 +91091,23 @@ var ts; // If `node` is an optional chain, then it is the outermost chain of an optional expression. return visitOptionalExpression(node, captureThisArg, /*isDelete*/ false); } + if (ts.isParenthesizedExpression(node.expression) && ts.isOptionalChain(ts.skipParentheses(node.expression))) { + // capture thisArg for calls of parenthesized optional chains like `(foo?.bar)()` + var expression = visitNonOptionalParenthesizedExpression(node.expression, /*captureThisArg*/ true, /*isDelete*/ false); + var args = ts.visitNodes(node.arguments, visitor, ts.isExpression); + if (ts.isSyntheticReference(expression)) { + return ts.setTextRange(factory.createFunctionCallCall(expression.expression, expression.thisArg, args), node); + } + return factory.updateCallExpression(node, expression, /*typeArguments*/ undefined, args); + } return ts.visitEachChild(node, visitor, context); } function visitNonOptionalExpression(node, captureThisArg, isDelete) { switch (node.kind) { - case 207 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete); - case 203 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg); + case 208 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete); + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete); + case 204 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg); default: return ts.visitNode(node, visitor, ts.isExpression); } } @@ -88179,8 +91126,8 @@ var ts; for (var i = 0; i < chain.length; i++) { var segment = chain[i]; switch (segment.kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: if (i === chain.length - 1 && captureThisArg) { if (!ts.isSimpleCopiableExpression(rightExpression)) { thisArg = factory.createTempVariable(hoistVariableDeclaration); @@ -88190,11 +91137,11 @@ var ts; thisArg = rightExpression; } } - rightExpression = segment.kind === 201 /* PropertyAccessExpression */ + rightExpression = segment.kind === 202 /* PropertyAccessExpression */ ? factory.createPropertyAccessExpression(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)) : factory.createElementAccessExpression(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (i === 0 && leftThisArg) { rightExpression = factory.createFunctionCallCall(rightExpression, leftThisArg.kind === 105 /* SuperKeyword */ ? factory.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); } @@ -88237,7 +91184,7 @@ var ts; /*@internal*/ var ts; (function (ts) { - function transformESNext(context) { + function transformES2021(context) { var hoistVariableDeclaration = context.hoistVariableDeclaration, factory = context.factory; return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { @@ -88247,11 +91194,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 4 /* ContainsESNext */) === 0) { + if ((node.transformFlags & 8 /* ContainsES2021 */) === 0) { return node; } switch (node.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var binaryExpression = node; if (ts.isLogicalOrCoalescingAssignmentExpression(binaryExpression)) { return transformLogicalAssignment(binaryExpression); @@ -88287,6 +91234,29 @@ var ts; return factory.createBinaryExpression(left, nonAssignmentOperator, factory.createParenthesizedExpression(factory.createAssignment(assignmentTarget, right))); } } + ts.transformES2021 = transformES2021; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformESNext(context) { + return ts.chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if ((node.transformFlags & 4 /* ContainsESNext */) === 0) { + return node; + } + switch (node.kind) { + default: + return ts.visitEachChild(node, visitor, context); + } + } + } ts.transformESNext = transformESNext; })(ts || (ts = {})); /*@internal*/ @@ -88397,13 +91367,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 273 /* JsxElement */: + case 274 /* JsxElement */: return visitJsxElement(node, /*isChild*/ false); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ false); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -88413,13 +91383,13 @@ var ts; switch (node.kind) { case 11 /* JsxText */: return visitJsxText(node); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return visitJsxExpression(node); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return visitJsxElement(node, /*isChild*/ true); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ true); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ true); default: return ts.Debug.failBadSyntaxKind(node); @@ -88459,9 +91429,9 @@ var ts; function convertJsxChildrenToChildrenPropObject(children) { var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); if (ts.length(nonWhitespaceChildren) === 1) { - var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]); - return result_13 && factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", result_13) + var result_14 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result_14 && factory.createObjectLiteralExpression([ + factory.createPropertyAssignment("children", result_14) ]); } var result = ts.mapDefined(children, transformJsxChildToExpression); @@ -88537,21 +91507,29 @@ var ts; // When there are no attributes, React wants "null" } else { - // Map spans of JsxAttribute nodes into object literals and spans - // of JsxSpreadAttribute nodes into expressions. - var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread - ? ts.map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); - if (ts.isJsxSpreadAttribute(attrs[0])) { - // We must always emit at least one object literal before a spread - // argument.factory.createObjectLiteral - segments.unshift(factory.createObjectLiteralExpression()); + var target = compilerOptions.target; + if (target && target >= 5 /* ES2018 */) { + objectProperties = factory.createObjectLiteralExpression(ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { + return isSpread ? ts.map(attrs, transformJsxSpreadAttributeToSpreadAssignment) : ts.map(attrs, transformJsxAttributeToObjectLiteralElement); + }))); } - // Either emit one big object literal (no spread attribs), or - // a call to the __assign helper. - objectProperties = ts.singleOrUndefined(segments); - if (!objectProperties) { - objectProperties = emitHelpers().createAssignHelper(segments); + else { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. + var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument.factory.createObjectLiteral + segments.unshift(factory.createObjectLiteralExpression()); + } + // Either emit one big object literal (no spread attribs), or + // a call to the __assign helper. + objectProperties = ts.singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = emitHelpers().createAssignHelper(segments); + } } } var callee = currentFileState.importSpecifier === undefined @@ -88583,6 +91561,9 @@ var ts; } return element; } + function transformJsxSpreadAttributeToSpreadAssignment(node) { + return factory.createSpreadAssignment(ts.visitNode(node.expression, visitor, ts.isExpression)); + } function transformJsxSpreadAttributeToExpression(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } @@ -88602,7 +91583,7 @@ var ts; var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote); return ts.setTextRange(literal, node); } - else if (node.kind === 283 /* JsxExpression */) { + else if (node.kind === 284 /* JsxExpression */) { if (node.expression === undefined) { return factory.createTrue(); } @@ -88696,7 +91677,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 273 /* JsxElement */) { + if (node.kind === 274 /* JsxElement */) { return getTagName(node.openingElement); } else { @@ -88998,11 +91979,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 128 /* ContainsES2016 */) === 0) { + if ((node.transformFlags & 256 /* ContainsES2016 */) === 0) { return node; } switch (node.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -89215,11 +92196,11 @@ var ts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0 - && node.kind === 242 /* ReturnStatement */ + && node.kind === 243 /* ReturnStatement */ && !node.expression; } function isOrMayContainReturnCompletion(node) { - return node.transformFlags & 1048576 /* ContainsHoistedDeclarationOrCompletion */ + return node.transformFlags & 2097152 /* ContainsHoistedDeclarationOrCompletion */ && (ts.isReturnStatement(node) || ts.isIfStatement(node) || ts.isWithStatement(node) @@ -89234,7 +92215,7 @@ var ts; || ts.isBlock(node)); } function shouldVisitNode(node) { - return (node.transformFlags & 256 /* ContainsES2015 */) !== 0 + return (node.transformFlags & 512 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && isOrMayContainReturnCompletion(node)) || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) @@ -89256,65 +92237,65 @@ var ts; switch (node.kind) { case 123 /* StaticKeyword */: return undefined; // elide static keyword - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return visitClassDeclaration(node); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return visitClassExpression(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return visitParameter(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return visitArrowFunction(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return visitFunctionExpression(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitVariableDeclaration(node); case 78 /* Identifier */: return visitIdentifier(node); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return visitVariableDeclarationList(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitSwitchStatement(node); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return visitCaseBlock(node); - case 230 /* Block */: + case 231 /* Block */: return visitBlock(node, /*isFunctionBody*/ false); - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: return visitBreakOrContinueStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node, /*outermostLabeledStatement*/ undefined); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitExpressionStatement(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return visitShorthandPropertyAssignment(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return visitNewExpression(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, expressionResultIsUnused); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node, expressionResultIsUnused); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitCommaListExpression(node, expressionResultIsUnused); case 14 /* NoSubstitutionTemplateLiteral */: case 15 /* TemplateHead */: @@ -89325,30 +92306,30 @@ var ts; return visitStringLiteral(node); case 8 /* NumericLiteral */: return visitNumericLiteral(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return visitTemplateExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitYieldExpression(node); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return visitSpreadElement(node); case 105 /* SuperKeyword */: return visitSuperKeyword(/*isExpressionOfCall*/ false); case 107 /* ThisKeyword */: return visitThisKeyword(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return visitMetaProperty(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return visitAccessorDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitReturnStatement(node); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return visitVoidExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -89438,14 +92419,14 @@ var ts; // it is possible if either // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement - var jump = node.kind === 241 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var jump = node.kind === 242 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; var label = node.label; if (!label) { - if (node.kind === 241 /* BreakStatement */) { + if (node.kind === 242 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; } @@ -89456,7 +92437,7 @@ var ts; } } else { - if (node.kind === 241 /* BreakStatement */) { + if (node.kind === 242 /* BreakStatement */) { labelMarker = "break-" + label.escapedText; setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); } @@ -89768,7 +92749,7 @@ var ts; factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); if (isDerivedClass) { - if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 4096 /* ContainsLexicalThis */)) { + if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 8192 /* ContainsLexicalThis */)) { // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the // following representation: // @@ -89854,11 +92835,11 @@ var ts; */ function isSufficientlyCoveredByReturnStatements(statement) { // A return statement is considered covered. - if (statement.kind === 242 /* ReturnStatement */) { + if (statement.kind === 243 /* ReturnStatement */) { return true; } // An if-statement with two covered branches is covered. - else if (statement.kind === 234 /* IfStatement */) { + else if (statement.kind === 235 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && @@ -89866,7 +92847,7 @@ var ts; } } // A block is covered if it has a last statement which is covered. - else if (statement.kind === 230 /* Block */) { + else if (statement.kind === 231 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -90068,7 +93049,7 @@ var ts; * @param node A node. */ function insertCaptureThisForNodeIfNeeded(statements, node) { - if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 209 /* ArrowFunction */) { + if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 210 /* ArrowFunction */) { insertCaptureThisForNode(statements, node, factory.createThis()); return true; } @@ -90090,22 +93071,22 @@ var ts; if (hierarchyFacts & 16384 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return statements; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // Methods and accessors cannot be constructors, so 'new.target' will // always return 'undefined'. newTarget = factory.createVoidZero(); break; - case 166 /* Constructor */: + case 167 /* Constructor */: // Class constructors can only be called with `new`, so `this.constructor` // should be relatively safe to use. newTarget = factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), "constructor"); break; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: // Functions can be called or constructed, and may have a `this` due to // being a member or when calling an imported function via `other_1.f()`. newTarget = factory.createConditionalExpression(factory.createLogicalAnd(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), factory.createBinaryExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), 101 /* InstanceOfKeyword */, factory.getLocalName(node))), @@ -90140,20 +93121,20 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 166 /* Constructor */: + case 167 /* Constructor */: // Constructors are handled in visitClassExpression/visitClassDeclaration break; default: @@ -90182,7 +93163,7 @@ var ts; var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName); var e; - if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) { + if (!ts.isPrivateIdentifier(propertyName) && ts.getUseDefineForClassFields(context.getCompilerOptions())) { var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName; @@ -90274,7 +93255,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 4096 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { hierarchyFacts |= 32768 /* CapturedLexicalThis */; } var savedConvertedLoopState = convertedLoopState; @@ -90356,7 +93337,7 @@ var ts; : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */)) { + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 252 /* FunctionDeclaration */ || node.kind === 209 /* FunctionExpression */)) { name = factory.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */); @@ -90402,7 +93383,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 209 /* ArrowFunction */); + ts.Debug.assert(node.kind === 210 /* ArrowFunction */); // To align with the old emitter, we use a synthetic end position on the location // for the statement list we synthesize when we down-level an arrow function with // an expression function body. This prevents both comments and source maps from @@ -90563,7 +93544,7 @@ var ts; * @param node A VariableDeclarationList node. */ function visitVariableDeclarationList(node) { - if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 131072 /* ContainsBindingPattern */) { + if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 262144 /* ContainsBindingPattern */) { if (node.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } @@ -90576,7 +93557,7 @@ var ts; ts.setCommentRange(declarationList, node); // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. - if (node.transformFlags & 131072 /* ContainsBindingPattern */ + if (node.transformFlags & 262144 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -90588,8 +93569,8 @@ var ts; // 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]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var node = declarations_9[_i]; pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); end = Math.max(end, node.end); } @@ -90709,14 +93690,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return visitDoOrWhileStatement(node, outermostLabeledStatement); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node, outermostLabeledStatement); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node, outermostLabeledStatement); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -90900,9 +93881,9 @@ var ts; var numInitialProperties = -1, hasComputed = false; for (var i = 0; i < properties.length; i++) { var property = properties[i]; - if ((property.transformFlags & 262144 /* ContainsYield */ && + if ((property.transformFlags & 524288 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) - || (hasComputed = ts.Debug.checkDefined(property.name).kind === 158 /* ComputedPropertyName */)) { + || (hasComputed = ts.Debug.checkDefined(property.name).kind === 159 /* ComputedPropertyName */)) { numInitialProperties = i; break; } @@ -91005,24 +93986,24 @@ var ts; loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts); } else { - var clone_3 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); - loop = factory.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_4 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); + loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); } } else { - var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + loop = factory.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel); } statements.push(loop); return statements; } function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { switch (node.kind) { - case 237 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); - case 238 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); - case 239 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); - case 235 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); - case 236 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + case 238 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 239 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 240 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 236 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 237 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); } } @@ -91047,11 +94028,11 @@ var ts; function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: var initializer = node.initializer; - if (initializer && initializer.kind === 250 /* VariableDeclarationList */) { + if (initializer && initializer.kind === 251 /* VariableDeclarationList */) { loopInitializer = initializer; } break; @@ -91171,7 +94152,7 @@ var ts; */ function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = factory.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 262144 /* ContainsYield */) !== 0; + var containsYield = (node.initializer.transformFlags & 524288 /* ContainsYield */) !== 0; var emitFlags = 0 /* None */; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -91286,7 +94267,7 @@ var ts; var loopBody = factory.createBlock(statements, /*multiLine*/ true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 262144 /* ContainsYield */) !== 0; + var containsYield = (node.statement.transformFlags & 524288 /* ContainsYield */) !== 0; var emitFlags = 524288 /* ReuseTempVariableScope */; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -91459,20 +94440,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -91579,7 +94560,7 @@ var ts; var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (node.kind === 167 /* GetAccessor */) { + if (node.kind === 168 /* GetAccessor */) { updated = factory.updateGetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { @@ -91759,7 +94740,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 & 8192 /* ContainsRestOrSpread */ || + if (node.transformFlags & 16384 /* ContainsRestOrSpread */ || node.expression.kind === 105 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -91767,7 +94748,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 8192 /* ContainsRestOrSpread */) { + if (node.transformFlags & 16384 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -92085,13 +95066,13 @@ var ts; if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { enabledSubstitutions |= 1 /* CapturedThis */; context.enableSubstitution(107 /* ThisKeyword */); - context.enableEmitNotification(166 /* Constructor */); - context.enableEmitNotification(165 /* MethodDeclaration */); - context.enableEmitNotification(167 /* GetAccessor */); - context.enableEmitNotification(168 /* SetAccessor */); - context.enableEmitNotification(209 /* ArrowFunction */); - context.enableEmitNotification(208 /* FunctionExpression */); - context.enableEmitNotification(251 /* FunctionDeclaration */); + context.enableEmitNotification(167 /* Constructor */); + context.enableEmitNotification(166 /* MethodDeclaration */); + context.enableEmitNotification(168 /* GetAccessor */); + context.enableEmitNotification(169 /* SetAccessor */); + context.enableEmitNotification(210 /* ArrowFunction */); + context.enableEmitNotification(209 /* FunctionExpression */); + context.enableEmitNotification(252 /* FunctionDeclaration */); } } /** @@ -92132,10 +95113,10 @@ var ts; */ function isNameOfDeclarationWithCollidingName(node) { switch (node.parent.kind) { - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 249 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 250 /* VariableDeclaration */: return node.parent.name === node && resolver.isDeclarationWithCollidingName(node.parent); } @@ -92217,11 +95198,11 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 233 /* ExpressionStatement */) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 234 /* ExpressionStatement */) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 203 /* CallExpression */) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 204 /* CallExpression */) { return false; } var callTarget = statementExpression.expression; @@ -92229,7 +95210,7 @@ var ts; return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 220 /* SpreadElement */) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 221 /* SpreadElement */) { return false; } var expression = callArgument.expression; @@ -92255,15 +95236,15 @@ var ts; if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(275 /* JsxOpeningElement */); - context.enableEmitNotification(276 /* JsxClosingElement */); - context.enableEmitNotification(274 /* JsxSelfClosingElement */); + context.enableEmitNotification(276 /* JsxOpeningElement */); + context.enableEmitNotification(277 /* JsxClosingElement */); + context.enableEmitNotification(275 /* JsxSelfClosingElement */); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(288 /* PropertyAssignment */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(289 /* PropertyAssignment */); return ts.chainBundle(context, transformSourceFile); /** * Transforms an ES5 source file to ES3. @@ -92282,9 +95263,9 @@ var ts; */ function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 275 /* JsxOpeningElement */: - case 276 /* JsxClosingElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 277 /* JsxClosingElement */: + case 275 /* JsxSelfClosingElement */: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -92582,7 +95563,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 1024 /* ContainsGenerator */) === 0) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -92605,7 +95586,7 @@ var ts; else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) { return visitGenerator(node); } - else if (transformFlags & 512 /* ContainsGenerator */) { + else if (transformFlags & 1024 /* ContainsGenerator */) { return ts.visitEachChild(node, visitor, context); } else { @@ -92619,13 +95600,13 @@ var ts; */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 235 /* DoStatement */: + case 236 /* DoStatement */: return visitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return visitWhileStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -92638,30 +95619,30 @@ var ts; */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return visitFunctionExpression(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return visitAccessorDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: return visitBreakStatement(node); - case 240 /* ContinueStatement */: + case 241 /* ContinueStatement */: return visitContinueStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 262144 /* ContainsYield */) { + if (node.transformFlags & 524288 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 1048576 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (1024 /* ContainsGenerator */ | 2097152 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -92676,23 +95657,23 @@ var ts; */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitCommaListExpression(node); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return visitConditionalExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitYieldExpression(node); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return visitElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -92705,9 +95686,9 @@ var ts; */ function visitGenerator(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return visitFunctionExpression(node); default: return ts.Debug.failBadSyntaxKind(node); @@ -92866,7 +95847,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 262144 /* ContainsYield */) { + if (node.transformFlags & 524288 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -92915,7 +95896,7 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: // [source] // a.b = yield; // @@ -92927,7 +95908,7 @@ var ts; // _a.b = %sent%; target = factory.updatePropertyAccessExpression(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: // [source] // a[b] = yield; // @@ -93321,35 +96302,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 230 /* Block */: + case 231 /* Block */: return transformAndEmitBlock(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return transformAndEmitIfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return transformAndEmitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return transformAndEmitWhileStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return transformAndEmitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return transformAndEmitForInStatement(node); - case 240 /* ContinueStatement */: + case 241 /* ContinueStatement */: return transformAndEmitContinueStatement(node); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: return transformAndEmitBreakStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return transformAndEmitReturnStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return transformAndEmitWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return transformAndEmitThrowStatement(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -93569,7 +96550,7 @@ var ts; var variables = ts.getInitializedVariables(initializer); node = factory.updateForStatement(node, variables.length > 0 ? factory.inlineExpressions(ts.map(variables, transformInitializedVariable)) - : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitIterationBody(node.statement, visitor, context)); } else { node = ts.visitEachChild(node, visitor, context); @@ -93779,7 +96760,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 285 /* DefaultClause */ && defaultClauseIndex === -1) { + if (clause.kind === 286 /* DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -93792,7 +96773,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 284 /* CaseClause */) { + if (clause.kind === 285 /* CaseClause */) { if (containsYield(clause.expression) && pendingClauses.length > 0) { break; } @@ -93924,7 +96905,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 262144 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 524288 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -93957,10 +96938,10 @@ var ts; var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { // TODO(rbuckton): Does this need to be parented? - var clone_5 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); - ts.setSourceMapRange(clone_5, node); - ts.setCommentRange(clone_5, node); - return clone_5; + var clone_6 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -94953,11 +97934,11 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(216 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(214 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(215 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(289 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. - context.enableEmitNotification(297 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(217 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(215 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(216 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(298 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var currentSourceFile; // The current file. @@ -94973,7 +97954,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 2097152 /* ContainsDynamicImport */ || + node.transformFlags & 4194304 /* ContainsDynamicImport */ || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && ts.outFile(compilerOptions)))) { return node; } @@ -95285,23 +98266,23 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return visitClassDeclaration(node); - case 338 /* MergeDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 339 /* EndOfDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); @@ -95310,7 +98291,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 & 2097152 /* ContainsDynamicImport */) && !(node.transformFlags & 1024 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 4194304 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -95328,24 +98309,24 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; switch (elem.kind) { - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: if (destructuringNeedsFlattening(elem.initializer)) { return true; } break; - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: if (destructuringNeedsFlattening(elem.name)) { return true; } break; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: if (destructuringNeedsFlattening(elem.expression)) { return true; } break; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return false; default: ts.Debug.assertNever(elem, "Unhandled object member kind"); } @@ -95380,7 +98361,7 @@ var ts; var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); // Only use the external module name if it differs from the first argument. This allows us to preserve the quote style of the argument on output. var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument; - var containsLexicalThis = !!(node.transformFlags & 4096 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -95873,7 +98854,7 @@ var ts; // // To balance the declaration, add the exports of the elided variable // statement. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 232 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 233 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -95928,10 +98909,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true); @@ -96144,7 +99125,7 @@ var ts; * @param emit A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -96208,10 +99189,10 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return substituteExpressionIdentifier(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return substituteBinaryExpression(node); - case 215 /* PostfixUnaryExpression */: - case 214 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -96231,9 +99212,9 @@ var ts; } return node; } - if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) { + else if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 297 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 298 /* SourceFile */) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), /*location*/ node); } @@ -96308,8 +99289,8 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 215 /* PostfixUnaryExpression */ - ? ts.setTextRange(factory.createBinaryExpression(node.operand, factory.createToken(node.operator === 45 /* PlusPlusToken */ ? 63 /* PlusEqualsToken */ : 64 /* MinusEqualsToken */), factory.createNumericLiteral(1)), + var expression = node.kind === 216 /* PostfixUnaryExpression */ + ? ts.setTextRange(factory.createPrefixUnaryExpression(node.operator, node.operand), /*location*/ node) : node; for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { @@ -96318,6 +99299,12 @@ var ts; noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression); } + if (node.kind === 216 /* PostfixUnaryExpression */) { + noSubstitution[ts.getNodeId(expression)] = true; + expression = node.operator === 45 /* PlusPlusToken */ + ? factory.createSubtract(expression, factory.createNumericLiteral(1)) + : factory.createAdd(expression, factory.createNumericLiteral(1)); + } return expression; } } @@ -96360,12 +99347,12 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers for imported symbols. - context.enableSubstitution(289 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols - context.enableSubstitution(216 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(214 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(215 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(226 /* MetaProperty */); // Substitutes 'import.meta' - context.enableEmitNotification(297 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(217 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(215 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(216 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(227 /* MetaProperty */); // Substitutes 'import.meta' + context.enableEmitNotification(298 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var exportFunctionsMap = []; // The export function associated with a source file. @@ -96385,7 +99372,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 2097152 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 4194304 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -96554,7 +99541,7 @@ var ts; // - Temporary variables will appear at the top rather than at the bottom of the file ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 - var modifiers = node.transformFlags & 524288 /* ContainsAwait */ ? + var modifiers = node.transformFlags & 1048576 /* ContainsAwait */ ? factory.createModifiersFromModifierFlags(256 /* Async */) : undefined; var moduleObject = factory.createObjectLiteralExpression([ @@ -96589,7 +99576,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 267 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 268 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -96679,19 +99666,19 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(factory, entry, currentSourceFile); // TODO: GH#18217 switch (entry.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // falls through - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== undefined); // save import into the local statements.push(factory.createExpressionStatement(factory.createAssignment(importVariableName, parameterName))); break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { if (ts.isNamedExports(entry.exportClause)) { @@ -96750,13 +99737,13 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -96936,7 +99923,7 @@ var ts; function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 - && (enclosingBlockScopedContainer.kind === 297 /* SourceFile */ + && (enclosingBlockScopedContainer.kind === 298 /* SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); } /** @@ -97000,7 +99987,7 @@ var ts; // // To balance the declaration, we defer the exports of the elided variable // statement until we visit this declaration's `EndOfDeclarationMarker`. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 232 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 233 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasSyntacticModifier(node.original, 1 /* Export */); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -97062,10 +100049,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -97245,43 +100232,43 @@ var ts; */ function nestedElementVisitor(node) { switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return visitClassDeclaration(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return visitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return visitWhileStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return visitWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitSwitchStatement(node); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return visitCaseBlock(node); - case 284 /* CaseClause */: + case 285 /* CaseClause */: return visitCaseClause(node); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: return visitDefaultClause(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return visitTryStatement(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); - case 230 /* Block */: + case 231 /* Block */: return visitBlock(node); - case 338 /* MergeDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 339 /* EndOfDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -97295,7 +100282,7 @@ var ts; function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory.updateForStatement(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + node = factory.updateForStatement(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -97307,7 +100294,7 @@ var ts; function visitForInStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory.updateForInStatement(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); + node = factory.updateForInStatement(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -97319,7 +100306,7 @@ var ts; function visitForOfStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory.updateForOfStatement(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); + node = factory.updateForOfStatement(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -97360,7 +100347,7 @@ var ts; * @param node The node to visit. */ function visitDoStatement(node) { - return factory.updateDoStatement(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); + return factory.updateDoStatement(node, ts.visitIterationBody(node.statement, nestedElementVisitor, context), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); } /** * Visits the body of a WhileStatement to hoist declarations. @@ -97368,7 +100355,7 @@ var ts; * @param node The node to visit. */ function visitWhileStatement(node) { - return factory.updateWhileStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); + return factory.updateWhileStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); } /** * Visits the body of a LabeledStatement to hoist declarations. @@ -97469,7 +100456,7 @@ var ts; else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 1024 /* ContainsDestructuringAssignment */) || (node.transformFlags & 2097152 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 4194304 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -97507,7 +100494,7 @@ var ts; return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } /** - * Determines whether the target of a destructuring assigment refers to an exported symbol. + * Determines whether the target of a destructuring assignment refers to an exported symbol. * * @param node The destructuring target. */ @@ -97532,7 +100519,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 297 /* SourceFile */; + return container !== undefined && container.kind === 298 /* SourceFile */; } else { return false; @@ -97565,7 +100552,7 @@ var ts; * @param emitCallback A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -97615,7 +100602,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -97652,12 +100639,12 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return substituteExpressionIdentifier(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return substituteBinaryExpression(node); - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return substituteUnaryExpression(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return substituteMetaProperty(node); } return node; @@ -97751,14 +100738,14 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 215 /* PostfixUnaryExpression */ + var expression = node.kind === 216 /* PostfixUnaryExpression */ ? ts.setTextRange(factory.createPrefixUnaryExpression(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 215 /* PostfixUnaryExpression */) { + if (node.kind === 216 /* PostfixUnaryExpression */) { expression = node.operator === 45 /* PlusPlusToken */ ? factory.createSubtract(preventSubstitution(expression), factory.createNumericLiteral(1)) : factory.createAdd(preventSubstitution(expression), factory.createNumericLiteral(1)); @@ -97786,7 +100773,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); - if (exportContainer && exportContainer.kind === 297 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 298 /* SourceFile */) { exportedNames = ts.append(exportedNames, factory.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -97826,7 +100813,7 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(297 /* SourceFile */); + context.enableEmitNotification(298 /* SourceFile */); context.enableSubstitution(78 /* Identifier */); var helperNameSubstitutions; return ts.chainBundle(context, transformSourceFile); @@ -97858,12 +100845,12 @@ var ts; } function visitor(node) { switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // Elide `import=` as it is not legal with --module ES6 return undefined; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: var exportDecl = node; return visitExportDeclaration(exportDecl); } @@ -97968,7 +100955,8 @@ var ts; ts.isTypeAliasDeclaration(node) || ts.isConstructorDeclaration(node) || ts.isIndexSignatureDeclaration(node) || - ts.isPropertyAccessExpression(node); + ts.isPropertyAccessExpression(node) || + ts.isJSDocTypeAlias(node); } ts.canProduceDiagnostics = canProduceDiagnostics; function createGetSymbolAccessibilityDiagnosticForNodeName(node) { @@ -97997,7 +100985,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.kind === 253 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98026,7 +101014,7 @@ var ts; ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.kind === 253 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98066,14 +101054,14 @@ var ts; else if (ts.isImportEqualsDeclaration(node)) { return getImportEntityNameVisibilityError; } - else if (ts.isTypeAliasDeclaration(node)) { + else if (ts.isTypeAliasDeclaration(node) || ts.isJSDocTypeAlias(node)) { return getTypeAliasDeclarationVisibilityError; } else { return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) { + if (node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98082,8 +101070,8 @@ var ts; } // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. - else if (node.kind === 163 /* PropertyDeclaration */ || node.kind === 201 /* PropertyAccessExpression */ || node.kind === 162 /* PropertySignature */ || - (node.kind === 160 /* Parameter */ && ts.hasSyntacticModifier(node.parent, 8 /* Private */))) { + else if (node.kind === 164 /* PropertyDeclaration */ || node.kind === 202 /* PropertyAccessExpression */ || node.kind === 163 /* PropertySignature */ || + (node.kind === 161 /* Parameter */ && ts.hasSyntacticModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasSyntacticModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -98092,7 +101080,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 252 /* ClassDeclaration */ || node.kind === 160 /* Parameter */) { + else if (node.parent.kind === 253 /* ClassDeclaration */ || node.kind === 161 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98117,7 +101105,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (node.kind === 168 /* SetAccessor */) { + if (node.kind === 169 /* SetAccessor */) { // Getters can infer the return type from the returned expression, but setters cannot, so the // "_from_external_module_1_but_cannot_be_named" case cannot occur. if (ts.hasSyntacticModifier(node, 32 /* Static */)) { @@ -98156,26 +101144,26 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 169 /* CallSignature */: + case 170 /* CallSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasSyntacticModifier(node, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -98183,7 +101171,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.kind === 253 /* ClassDeclaration */) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -98197,7 +101185,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -98222,30 +101210,30 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 170 /* ConstructSignature */: - case 175 /* ConstructorType */: + case 171 /* ConstructSignature */: + case 176 /* ConstructorType */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 169 /* CallSignature */: + case 170 /* CallSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasSyntacticModifier(node.parent, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -98253,7 +101241,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 253 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98266,15 +101254,15 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 251 /* FunctionDeclaration */: - case 174 /* FunctionType */: + case 252 /* FunctionDeclaration */: + case 175 /* FunctionType */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; - case 168 /* SetAccessor */: - case 167 /* GetAccessor */: + case 169 /* SetAccessor */: + case 168 /* GetAccessor */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98288,39 +101276,39 @@ var ts; // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 190 /* MappedType */: + case 191 /* MappedType */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1; break; - case 175 /* ConstructorType */: - case 170 /* ConstructSignature */: + case 176 /* ConstructorType */: + case 171 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 169 /* CallSignature */: + case 170 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasSyntacticModifier(node.parent, 32 /* Static */)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 253 /* ClassDeclaration */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 174 /* FunctionType */: - case 251 /* FunctionDeclaration */: + case 175 /* FunctionType */: + case 252 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -98359,11 +101347,13 @@ var ts; typeName: node.name }; } - function getTypeAliasDeclarationVisibilityError() { + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name + diagnosticMessage: symbolAccessibilityResult.errorModuleName + ? ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2 + : ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: ts.isJSDocTypeAlias(node) ? ts.Debug.checkDefined(node.typeExpression) : node.type, + typeName: ts.isJSDocTypeAlias(node) ? ts.getNameOfDeclaration(node) : node.name, }; } } @@ -98384,7 +101374,7 @@ var ts; } function isInternalDeclaration(node, currentSourceFile) { var parseTreeNode = ts.getParseTreeNode(node); - if (parseTreeNode && parseTreeNode.kind === 160 /* Parameter */) { + if (parseTreeNode && parseTreeNode.kind === 161 /* Parameter */) { var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode); var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined; var text = currentSourceFile.text; @@ -98446,6 +101436,7 @@ var ts; reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; + var errorFallbackNode; var currentSourceFile; var refs; var libs; @@ -98515,8 +101506,8 @@ var ts; recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } function reportInaccessibleUniqueSymbolError() { @@ -98540,35 +101531,38 @@ var ts; } } function reportTruncationError() { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); } } function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { - var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); + var _a; + var primaryDeclaration = (_a = parentSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; }); - for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { - var augmentations = augmentingDeclarations_1[_i]; - context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + if (augmentingDeclarations) { + for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { + var augmentations = augmentingDeclarations_1[_i]; + context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + } } } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; - getSymbolAccessibilityDiagnostic = function (s) { return ({ + getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ diagnosticMessage: s.errorModuleName ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit, errorNode: s.errorNode || sourceFile - }); }; + })); }; var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled); getSymbolAccessibilityDiagnostic = oldDiag; return result; } function transformRoot(node) { - if (node.kind === 297 /* SourceFile */ && node.isDeclarationFile) { + if (node.kind === 298 /* SourceFile */ && node.isDeclarationFile) { return node; } - if (node.kind === 298 /* Bundle */) { + if (node.kind === 299 /* Bundle */) { isBundledEmit = true; refs = new ts.Map(); libs = new ts.Map(); @@ -98598,7 +101592,7 @@ var ts; var updated = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements); return factory.updateSourceFile(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); }), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 300 /* InputFiles */) { + if (prepend.kind === 301 /* InputFiles */) { var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal); hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib; collectReferences(sourceFile, refs); @@ -98690,7 +101684,7 @@ var ts; declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { - var specifier = ts.moduleSpecifiers.getModuleSpecifier(__assign(__assign({}, options), { baseUrl: options.baseUrl && ts.toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }), currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, + var specifier = ts.moduleSpecifiers.getModuleSpecifier(options, currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, /*preferences*/ undefined); if (!ts.pathIsRelative(specifier)) { // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration @@ -98739,7 +101733,7 @@ var ts; return name; } else { - if (name.kind === 197 /* ArrayBindingPattern */) { + if (name.kind === 198 /* ArrayBindingPattern */) { return factory.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); } else { @@ -98747,7 +101741,7 @@ var ts; } } function visitBindingElement(elem) { - if (elem.kind === 222 /* OmittedExpression */) { + if (elem.kind === 223 /* OmittedExpression */) { return elem; } return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); @@ -98785,7 +101779,7 @@ var ts; // Literal const declarations will have an initializer ensured rather than a type return; } - var shouldUseResolverType = node.kind === 160 /* Parameter */ && + var shouldUseResolverType = node.kind === 161 /* Parameter */ && (resolver.isRequiredInitializedParameter(node) || resolver.isOptionalUninitializedParameterProperty(node)); if (type && !shouldUseResolverType) { @@ -98794,7 +101788,7 @@ var ts; if (!ts.getParseTreeNode(node)) { return type ? ts.visitNode(type, visitDeclarationSubtree) : factory.createKeywordTypeNode(128 /* AnyKeyword */); } - if (node.kind === 168 /* SetAccessor */) { + if (node.kind === 169 /* SetAccessor */) { // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) return factory.createKeywordTypeNode(128 /* AnyKeyword */); @@ -98805,12 +101799,12 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); } - if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) { + if (node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */) { return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } - if (node.kind === 160 /* Parameter */ - || node.kind === 163 /* PropertyDeclaration */ - || node.kind === 162 /* PropertySignature */) { + if (node.kind === 161 /* Parameter */ + || node.kind === 164 /* PropertyDeclaration */ + || node.kind === 163 /* PropertySignature */) { if (!node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); @@ -98827,20 +101821,20 @@ var ts; function isDeclarationAndNotVisible(node) { node = ts.getParseTreeNode(node); switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 256 /* ModuleDeclaration */: - case 253 /* InterfaceDeclaration */: - case 252 /* ClassDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: + case 252 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 254 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: return !resolver.isDeclarationVisible(node); // The following should be doing their own visibility checks based on filtering their members - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return !getBindingNameVisible(node); - case 260 /* ImportEqualsDeclaration */: - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: + case 261 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: return false; } return false; @@ -98921,7 +101915,7 @@ var ts; function rewriteModuleSpecifier(parent, input) { if (!input) return undefined; // TODO: GH#18217 - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 256 /* ModuleDeclaration */ && parent.kind !== 195 /* ImportType */); + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 257 /* ModuleDeclaration */ && parent.kind !== 196 /* ImportType */); if (ts.isStringLiteralLike(input)) { if (isBundledEmit) { var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); @@ -98941,7 +101935,7 @@ var ts; function transformImportEqualsDeclaration(decl) { if (!resolver.isDeclarationVisible(decl)) return; - if (decl.moduleReference.kind === 272 /* ExternalModuleReference */) { + if (decl.moduleReference.kind === 273 /* ExternalModuleReference */) { // Rewrite external module names if necessary var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); return factory.updateImportEqualsDeclaration(decl, @@ -98968,7 +101962,7 @@ var ts; return visibleDefaultBinding && factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } - if (decl.importClause.namedBindings.kind === 263 /* NamespaceImport */) { + if (decl.importClause.namedBindings.kind === 264 /* NamespaceImport */) { // Namespace import (optionally with visible default) var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; @@ -99063,7 +102057,7 @@ var ts; // We'd see a TDZ violation at runtime var canProduceDiagnostic = ts.canProduceDiagnostics(input); var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; - var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 177 /* TypeLiteral */ || input.kind === 190 /* MappedType */) && input.parent.kind !== 254 /* TypeAliasDeclaration */); + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 178 /* TypeLiteral */ || input.kind === 191 /* MappedType */) && input.parent.kind !== 255 /* TypeAliasDeclaration */); // Emit methods which are private as properties with no type information if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { if (ts.hasEffectiveModifier(input, 8 /* Private */)) { @@ -99084,21 +102078,21 @@ var ts; } if (isProcessedComponent(input)) { switch (input.kind) { - case 223 /* ExpressionWithTypeArguments */: { + case 224 /* ExpressionWithTypeArguments */: { if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { checkEntityNameVisibility(input.expression, enclosingDeclaration); } var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(factory.updateExpressionWithTypeArguments(node, node.expression, node.typeArguments)); } - case 173 /* TypeReference */: { + case 174 /* TypeReference */: { checkEntityNameVisibility(input.typeName, enclosingDeclaration); var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(factory.updateTypeReferenceNode(node, node.typeName, node.typeArguments)); } - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: return cleanup(factory.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); - case 166 /* Constructor */: { + case 167 /* Constructor */: { // A constructor declaration may not have a type annotation var ctor = factory.createConstructorDeclaration( /*decorators*/ undefined, @@ -99106,7 +102100,7 @@ var ts; /*body*/ undefined); return cleanup(ctor); } - case 165 /* MethodDeclaration */: { + case 166 /* MethodDeclaration */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } @@ -99116,7 +102110,7 @@ var ts; /*body*/ undefined); return cleanup(sig); } - case 167 /* GetAccessor */: { + case 168 /* GetAccessor */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } @@ -99125,7 +102119,7 @@ var ts; /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), ensureType(input, accessorType), /*body*/ undefined)); } - case 168 /* SetAccessor */: { + case 169 /* SetAccessor */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } @@ -99133,31 +102127,31 @@ var ts; /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), /*body*/ undefined)); } - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updatePropertyDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type))); - case 164 /* MethodSignature */: { + case 165 /* MethodSignature */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updateMethodSignature(input, ensureModifiers(input), input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 169 /* CallSignature */: { + case 170 /* CallSignature */: { return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 171 /* IndexSignature */: { + case 172 /* IndexSignature */: { return cleanup(factory.updateIndexSignature(input, /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(128 /* AnyKeyword */))); } - case 249 /* VariableDeclaration */: { + case 250 /* VariableDeclaration */: { if (ts.isBindingPattern(input.name)) { return recreateBindingPattern(input.name); } @@ -99165,13 +102159,13 @@ var ts; suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types return cleanup(factory.updateVariableDeclaration(input, input.name, /*exclamationToken*/ undefined, ensureType(input, input.type), ensureNoInitializer(input))); } - case 159 /* TypeParameter */: { + case 160 /* TypeParameter */: { if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { return cleanup(factory.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); } return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); } - case 184 /* ConditionalType */: { + case 185 /* ConditionalType */: { // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); @@ -99183,13 +102177,13 @@ var ts; var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); return cleanup(factory.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); } - case 174 /* FunctionType */: { + case 175 /* FunctionType */: { return cleanup(factory.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 175 /* ConstructorType */: { + case 176 /* ConstructorType */: { return cleanup(factory.updateConstructorTypeNode(input, ensureModifiers(input), ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 195 /* ImportType */: { + case 196 /* ImportType */: { if (!ts.isLiteralImportTypeNode(input)) return cleanup(input); return cleanup(factory.updateImportTypeNode(input, factory.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); @@ -99221,7 +102215,7 @@ var ts; } } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 165 /* MethodDeclaration */ && ts.hasEffectiveModifier(node.parent, 8 /* Private */); + return node.parent.kind === 166 /* MethodDeclaration */ && ts.hasEffectiveModifier(node.parent, 8 /* Private */); } function visitDeclarationStatements(input) { if (!isPreservedDeclarationStatement(input)) { @@ -99231,7 +102225,7 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 267 /* ExportDeclaration */: { + case 268 /* ExportDeclaration */: { if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; } @@ -99241,7 +102235,7 @@ var ts; return factory.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); } - case 266 /* ExportAssignment */: { + case 267 /* ExportAssignment */: { // Always visible if the parent node isn't dropped for being not visible if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; @@ -99256,7 +102250,9 @@ var ts; diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: input }); }; + errorFallbackNode = input; var varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + errorFallbackNode = undefined; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */)); return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } @@ -99273,17 +102269,17 @@ var ts; // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too return statement; } - var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (11263 /* All */ ^ 1 /* Export */)); + var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (27647 /* All */ ^ 1 /* Export */)); return factory.updateModifiers(statement, modifiers); } function transformTopLevelDeclaration(input) { if (shouldStripInternal(input)) return; switch (input.kind) { - case 260 /* ImportEqualsDeclaration */: { + case 261 /* ImportEqualsDeclaration */: { return transformImportEqualsDeclaration(input); } - case 261 /* ImportDeclaration */: { + case 262 /* ImportDeclaration */: { return transformImportDeclaration(input); } } @@ -99304,14 +102300,14 @@ var ts; } var previousNeedsDeclare = needsDeclare; switch (input.kind) { - case 254 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + case 255 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all return cleanup(factory.updateTypeAliasDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); - case 253 /* InterfaceDeclaration */: { + case 254 /* InterfaceDeclaration */: { return cleanup(factory.updateInterfaceDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } - case 251 /* FunctionDeclaration */: { + case 252 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type var clean = cleanup(factory.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), @@ -99326,7 +102322,7 @@ var ts; fakespace_1.symbol = props[0].parent; var exportMappings_1 = []; var declarations = ts.mapDefined(props, function (p) { - if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + if (!p.valueDeclaration || !ts.isPropertyAccessExpression(p.valueDeclaration)) { return undefined; // TODO GH#33569: Handle element access expressions that created late bound names (rather than silently omitting them) } getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration); @@ -99378,10 +102374,10 @@ var ts; return clean; } } - case 256 /* ModuleDeclaration */: { + case 257 /* ModuleDeclaration */: { needsDeclare = false; var inner = input.body; - if (inner && inner.kind === 257 /* ModuleBlock */) { + if (inner && inner.kind === 258 /* ModuleBlock */) { var oldNeedsScopeFix = needsScopeFixMarker; var oldHasScopeFix = resultHasScopeMarker; resultHasScopeMarker = false; @@ -99424,7 +102420,9 @@ var ts; /*decorators*/ undefined, mods, input.name, body)); } } - case 252 /* ClassDeclaration */: { + case 253 /* ClassDeclaration */: { + errorNameNode = input.name; + errorFallbackNode = input; var modifiers = factory.createNodeArray(ensureModifiers(input)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -99432,7 +102430,7 @@ var ts; if (ctor) { var oldDiag_1 = getSymbolAccessibilityDiagnostic; parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { - if (!ts.hasSyntacticModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param)) + if (!ts.hasSyntacticModifier(param, 16476 /* ParameterPropertyModifier */) || shouldStripInternal(param)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 78 /* Identifier */) { @@ -99507,10 +102505,10 @@ var ts; /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); } } - case 232 /* VariableStatement */: { + case 233 /* VariableStatement */: { return cleanup(transformVariableStatement(input)); } - case 255 /* EnumDeclaration */: { + case 256 /* EnumDeclaration */: { return cleanup(factory.updateEnumDeclaration(input, /*decorators*/ undefined, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; @@ -99529,12 +102527,14 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 256 /* ModuleDeclaration */) { + if (input.kind === 257 /* ModuleDeclaration */) { needsDeclare = previousNeedsDeclare; } if (node === input) { return node; } + errorFallbackNode = undefined; + errorNameNode = undefined; return node && ts.setOriginalNode(preserveJsDoc(node, input), input); } } @@ -99550,7 +102550,7 @@ var ts; return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); } function recreateBindingElement(e) { - if (e.kind === 222 /* OmittedExpression */) { + if (e.kind === 223 /* OmittedExpression */) { return; } if (e.name) { @@ -99598,9 +102598,9 @@ var ts; return factory.createModifiersFromModifierFlags(newFlags); } function ensureModifierFlags(node) { - var mask = 11263 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files + var mask = 27647 /* All */ ^ (4 /* Public */ | 256 /* Async */ | 16384 /* Override */); // No async and override modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; - var parentIsFile = node.parent.kind === 297 /* SourceFile */; + var parentIsFile = node.parent.kind === 298 /* SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { mask ^= 2 /* Ambient */; additions = 0 /* None */; @@ -99629,7 +102629,7 @@ var ts; } ts.transformDeclarations = transformDeclarations; function isAlwaysType(node) { - if (node.kind === 253 /* InterfaceDeclaration */) { + if (node.kind === 254 /* InterfaceDeclaration */) { return true; } return false; @@ -99639,7 +102639,7 @@ var ts; return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); } function maskModifierFlags(node, modifierMask, modifierAdditions) { - if (modifierMask === void 0) { modifierMask = 11263 /* All */ ^ 4 /* Public */; } + if (modifierMask === void 0) { modifierMask = 27647 /* All */ ^ 4 /* Public */; } if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions; if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) { @@ -99654,7 +102654,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 167 /* GetAccessor */ + return accessor.kind === 168 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type @@ -99663,52 +102663,52 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return !ts.hasEffectiveModifier(node, 8 /* Private */); - case 160 /* Parameter */: - case 249 /* VariableDeclaration */: + case 161 /* Parameter */: + case 250 /* VariableDeclaration */: return true; } return false; } function isPreservedDeclarationStatement(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 256 /* ModuleDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 253 /* InterfaceDeclaration */: - case 252 /* ClassDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: - case 232 /* VariableStatement */: - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: + case 252 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 254 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 233 /* VariableStatement */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: return true; } return false; } function isProcessedComponent(node) { switch (node.kind) { - case 170 /* ConstructSignature */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 171 /* IndexSignature */: - case 249 /* VariableDeclaration */: - case 159 /* TypeParameter */: - case 223 /* ExpressionWithTypeArguments */: - case 173 /* TypeReference */: - case 184 /* ConditionalType */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 195 /* ImportType */: + case 171 /* ConstructSignature */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 172 /* IndexSignature */: + case 250 /* VariableDeclaration */: + case 160 /* TypeParameter */: + case 224 /* ExpressionWithTypeArguments */: + case 174 /* TypeReference */: + case 185 /* ConditionalType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 196 /* ImportType */: return true; } return false; @@ -99764,6 +102764,9 @@ var ts; if (languageVersion < 99 /* ESNext */) { transformers.push(ts.transformESNext); } + if (languageVersion < 8 /* ES2021 */) { + transformers.push(ts.transformES2021); + } if (languageVersion < 7 /* ES2020 */) { transformers.push(ts.transformES2020); } @@ -99840,7 +102843,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, factory, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(341 /* Count */); + var enabledSyntaxKindFeatures = new Array(345 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentStatements; @@ -99851,6 +102854,9 @@ var ts; var lexicalEnvironmentFlagsStack = []; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; + var blockScopedVariableDeclarationsStack = []; + var blockScopeStackOffset = 0; + var blockScopedVariableDeclarations; var emitHelpers; var onSubstituteNode = noEmitSubstitution; var onEmitNode = noEmitNotification; @@ -99873,6 +102879,9 @@ var ts; hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, addInitializationStatement: addInitializationStatement, + startBlockScope: startBlockScope, + endBlockScope: endBlockScope, + addBlockScopedVariable: addBlockScopedVariable, requestEmitHelper: requestEmitHelper, readEmitHelpers: readEmitHelpers, enableSubstitution: enableSubstitution, @@ -99916,9 +102925,9 @@ var ts; var transformed = []; for (var _a = 0, nodes_3 = nodes; _a < nodes_3.length; _a++) { var node = nodes_3[_a]; - ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 298 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); transformed.push((allowDtsFiles ? transformation : transformRoot)(node)); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // prevent modification of the lexical environment. state = 2 /* Completed */; @@ -100133,6 +103142,38 @@ var ts; function getLexicalEnvironmentFlags() { return lexicalEnvironmentFlags; } + /** + * Starts a block scope. Any existing block hoisted variables are pushed onto the stack and the related storage variables are reset. + */ + function startBlockScope() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot start a block scope during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot start a block scope after transformation has completed."); + blockScopedVariableDeclarationsStack[blockScopeStackOffset] = blockScopedVariableDeclarations; + blockScopeStackOffset++; + blockScopedVariableDeclarations = undefined; + } + /** + * Ends a block scope. The previous set of block hoisted variables are restored. Any hoisted declarations are returned. + */ + function endBlockScope() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot end a block scope during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot end a block scope after transformation has completed."); + var statements = ts.some(blockScopedVariableDeclarations) ? + [ + factory.createVariableStatement( + /*modifiers*/ undefined, factory.createVariableDeclarationList(blockScopedVariableDeclarations.map(function (identifier) { return factory.createVariableDeclaration(identifier); }), 1 /* Let */)) + ] : undefined; + blockScopeStackOffset--; + blockScopedVariableDeclarations = blockScopedVariableDeclarationsStack[blockScopeStackOffset]; + if (blockScopeStackOffset === 0) { + blockScopedVariableDeclarationsStack = []; + } + return statements; + } + function addBlockScopedVariable(name) { + ts.Debug.assert(blockScopeStackOffset > 0, "Cannot add a block scoped variable outside of an iteration body."); + (blockScopedVariableDeclarations || (blockScopedVariableDeclarations = [])).push(name); + } function requestEmitHelper(helper) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); @@ -100174,35 +103215,37 @@ var ts; } ts.transformNodes = transformNodes; ts.nullTransformationContext = { - get factory() { return ts.factory; }, - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: ts.returnUndefined, + factory: ts.factory, getCompilerOptions: function () { return ({}); }, - getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + getEmitHost: ts.notImplemented, getEmitHelperFactory: ts.notImplemented, + startLexicalEnvironment: ts.noop, + resumeLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop, + endLexicalEnvironment: ts.returnUndefined, setLexicalEnvironmentFlags: ts.noop, getLexicalEnvironmentFlags: function () { return 0; }, - hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + hoistFunctionDeclaration: ts.noop, addInitializationStatement: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, + startBlockScope: ts.noop, + endBlockScope: ts.returnUndefined, + addBlockScopedVariable: ts.noop, requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop, + readEmitHelpers: ts.notImplemented, + enableSubstitution: ts.noop, + enableEmitNotification: ts.noop, + isSubstitutionEnabled: ts.notImplemented, + isEmitNotificationEnabled: ts.notImplemented, + onSubstituteNode: noEmitSubstitution, + onEmitNode: noEmitNotification, addDiagnostic: ts.noop, }; })(ts || (ts = {})); var ts; (function (ts) { var brackets = createBracketsMap(); - var syntheticParent = { pos: -1, end: -1 }; /*@internal*/ function isBuildInfoFile(file) { return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */); @@ -100288,7 +103331,7 @@ var ts; /*@internal*/ function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); - if (sourceFile.kind === 298 /* Bundle */) { + if (sourceFile.kind === 299 /* Bundle */) { return getOutputPathsForBundle(options, forceDtsPaths); } else { @@ -100514,15 +103557,15 @@ var ts; sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); }) }; } - ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); emitBuildInfo(bundleBuildInfo, buildInfoPath); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { if (jsFilePath) { @@ -100649,13 +103692,13 @@ var ts; if (!declBlocked || forceDtsEmit) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, { - sourceMap: compilerOptions.declarationMap, + sourceMap: !forceDtsEmit && compilerOptions.declarationMap, sourceRoot: compilerOptions.sourceRoot, mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, // Explicitly do not passthru either `inline` option }); - if (forceDtsEmit && declarationTransform.transformed[0].kind === 297 /* SourceFile */) { + if (forceDtsEmit && declarationTransform.transformed[0].kind === 298 /* SourceFile */) { var sourceFile = declarationTransform.transformed[0]; exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; } @@ -100678,8 +103721,8 @@ var ts; ts.forEachChild(node, collectLinkedAliases); } function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) { - var bundle = sourceFileOrBundle.kind === 298 /* Bundle */ ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 297 /* SourceFile */ ? sourceFileOrBundle : undefined; + var bundle = sourceFileOrBundle.kind === 299 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 298 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; var sourceMapGenerator; if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { @@ -100720,7 +103763,7 @@ var ts; } function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { return (mapOptions.sourceMap || mapOptions.inlineSourceMap) - && (sourceFileOrBundle.kind !== 297 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); + && (sourceFileOrBundle.kind !== 298 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); } function getSourceRoot(mapOptions) { // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the @@ -100779,7 +103822,7 @@ var ts; ts.emitFiles = emitFiles; /*@internal*/ function getBuildInfoText(buildInfo) { - return JSON.stringify(buildInfo, undefined, 2); + return JSON.stringify(buildInfo); } ts.getBuildInfoText = getBuildInfoText; /*@internal*/ @@ -100960,7 +104003,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = ts.getNewLineCharacter(printerOptions); var moduleKind = ts.getEmitModuleKind(printerOptions); @@ -100999,9 +104042,11 @@ var ts; var detachedCommentsInfo; var hasWrittenComment = false; var commentsDisabled = !!printerOptions.removeComments; - var lastNode; var lastSubstitution; + var currentParenthesizerRule; var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; + var parenthesizer = ts.factory.parenthesizer; + var emitBinaryExpression = createEmitBinaryExpression(); reset(); return { // public API @@ -101029,9 +104074,9 @@ var ts; break; } switch (node.kind) { - case 297 /* SourceFile */: return printFile(node); - case 298 /* Bundle */: return printBundle(node); - case 299 /* UnparsedSource */: return printUnparsedSource(node); + case 298 /* SourceFile */: return printFile(node); + case 299 /* Bundle */: return printBundle(node); + case 300 /* UnparsedSource */: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -101065,7 +104110,7 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - emitList(syntheticParent, nodes, format); + emitList(/*parentNode*/ undefined, nodes, format); reset(); writer = previousWriter; } @@ -101200,7 +104245,7 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - pipelineEmit(hint, node); + pipelineEmit(hint, node, /*parenthesizerRule*/ undefined); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -101228,51 +104273,54 @@ var ts; currentSourceFile = undefined; currentLineMap = undefined; detachedCommentsInfo = undefined; - lastNode = undefined; - lastSubstitution = undefined; setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined); } function getCurrentLineMap() { return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); } - function emit(node) { + function emit(node, parenthesizerRule) { if (node === undefined) return; var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node); - var substitute = pipelineEmit(4 /* Unspecified */, node); + pipelineEmit(4 /* Unspecified */, node, parenthesizerRule); recordBundleFileInternalSectionEnd(prevSourceFileTextKind); - return substitute; } function emitIdentifierName(node) { if (node === undefined) return; - return pipelineEmit(2 /* IdentifierName */, node); + pipelineEmit(2 /* IdentifierName */, node, /*parenthesizerRule*/ undefined); } - function emitExpression(node) { + function emitExpression(node, parenthesizerRule) { if (node === undefined) return; - return pipelineEmit(1 /* Expression */, node); + pipelineEmit(1 /* Expression */, node, parenthesizerRule); } function emitJsxAttributeValue(node) { - return pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); + pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); } - function pipelineEmit(emitHint, node) { - var savedLastNode = lastNode; - var savedLastSubstitution = lastSubstitution; - var savedPreserveSourceNewlines = preserveSourceNewlines; - lastNode = node; - lastSubstitution = undefined; - if (preserveSourceNewlines && !!(ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) { + function beforeEmitNode(node) { + if (preserveSourceNewlines && (ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) { preserveSourceNewlines = false; } + } + function afterEmitNode(savedPreserveSourceNewlines) { + preserveSourceNewlines = savedPreserveSourceNewlines; + } + function pipelineEmit(emitHint, node, parenthesizerRule) { + currentParenthesizerRule = parenthesizerRule; var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node); pipelinePhase(emitHint, node); - ts.Debug.assert(lastNode === node); - var substitute = lastSubstitution; - lastNode = savedLastNode; - lastSubstitution = savedLastSubstitution; - preserveSourceNewlines = savedPreserveSourceNewlines; - return substitute || node; + currentParenthesizerRule = undefined; + } + function shouldEmitComments(node) { + return !commentsDisabled && !ts.isSourceFile(node); + } + function shouldEmitSourceMaps(node) { + return !sourceMapsDisabled && + !ts.isSourceFile(node) && + !ts.isInJsonFile(node) && + !ts.isUnparsedSource(node) && + !ts.isUnparsedPrepend(node); } function getPipelinePhase(phase, emitHint, node) { switch (phase) { @@ -101282,18 +104330,21 @@ var ts; } // falls through case 1 /* Substitution */: - if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) { + if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) { + if (currentParenthesizerRule) { + lastSubstitution = currentParenthesizerRule(lastSubstitution); + } return pipelineEmitWithSubstitution; } // falls through case 2 /* Comments */: - if (!commentsDisabled && node.kind !== 297 /* SourceFile */) { + if (shouldEmitComments(node)) { return pipelineEmitWithComments; } // falls through case 3 /* SourceMaps */: - if (!sourceMapsDisabled && node.kind !== 297 /* SourceFile */ && !ts.isInJsonFile(node)) { - return pipelineEmitWithSourceMap; + if (shouldEmitSourceMaps(node)) { + return pipelineEmitWithSourceMaps; } // falls through case 4 /* Emit */: @@ -101306,13 +104357,25 @@ var ts; return getPipelinePhase(currentPhase + 1, emitHint, node); } function pipelineEmitWithNotification(hint, node) { - ts.Debug.assert(lastNode === node); var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node); onEmitNode(hint, node, pipelinePhase); - ts.Debug.assert(lastNode === node); } function pipelineEmitWithHint(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (preserveSourceNewlines) { + var savedPreserveSourceNewlines = preserveSourceNewlines; + beforeEmitNode(node); + pipelineEmitWithHintWorker(hint, node); + afterEmitNode(savedPreserveSourceNewlines); + } + else { + pipelineEmitWithHintWorker(hint, node); + } + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); + // clear the parenthesizer rule as we ascend + currentParenthesizerRule = undefined; + } + function pipelineEmitWithHintWorker(hint, node) { if (hint === 0 /* SourceFile */) return emitSourceFile(ts.cast(node, ts.isSourceFile)); if (hint === 2 /* IdentifierName */) @@ -101326,24 +104389,12 @@ var ts; return emitEmptyStatement(/*isEmbeddedStatement*/ true); } if (hint === 4 /* Unspecified */) { - if (ts.isKeyword(node.kind)) - return writeTokenNode(node, writeKeyword); switch (node.kind) { // Pseudo-literals case 15 /* TemplateHead */: case 16 /* TemplateMiddle */: case 17 /* TemplateTail */: return emitLiteral(node, /*jsxAttributeEscape*/ false); - case 299 /* UnparsedSource */: - case 293 /* UnparsedPrepend */: - return emitUnparsedSourceOrPrepend(node); - case 292 /* UnparsedPrologue */: - return writeUnparsedNode(node); - case 294 /* UnparsedText */: - case 295 /* UnparsedInternalText */: - return emitUnparsedTextLike(node); - case 296 /* UnparsedSyntheticReference */: - return emitUnparsedSyntheticReference(node); // Identifiers case 78 /* Identifier */: return emitIdentifier(node); @@ -101352,282 +104403,323 @@ var ts; return emitPrivateIdentifier(node); // Parse tree nodes // Names - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return emitQualifiedName(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return emitComputedPropertyName(node); // Signature elements - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return emitTypeParameter(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return emitParameter(node); - case 161 /* Decorator */: + case 162 /* Decorator */: return emitDecorator(node); // Type members - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: return emitPropertySignature(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return emitPropertyDeclaration(node); - case 164 /* MethodSignature */: + case 165 /* MethodSignature */: return emitMethodSignature(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return emitMethodDeclaration(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return emitConstructor(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return emitAccessorDeclaration(node); - case 169 /* CallSignature */: + case 170 /* CallSignature */: return emitCallSignature(node); - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: return emitConstructSignature(node); - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: return emitIndexSignature(node); - case 194 /* TemplateLiteralTypeSpan */: - return emitTemplateTypeSpan(node); // Types - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return emitTypePredicate(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return emitTypeReference(node); - case 174 /* FunctionType */: + case 175 /* FunctionType */: return emitFunctionType(node); - case 308 /* JSDocFunctionType */: - return emitJSDocFunctionType(node); - case 175 /* ConstructorType */: + case 176 /* ConstructorType */: return emitConstructorType(node); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return emitTypeQuery(node); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return emitTypeLiteral(node); - case 178 /* ArrayType */: + case 179 /* ArrayType */: return emitArrayType(node); - case 179 /* TupleType */: + case 180 /* TupleType */: return emitTupleType(node); - case 180 /* OptionalType */: + case 181 /* OptionalType */: return emitOptionalType(node); - case 182 /* UnionType */: + // SyntaxKind.RestType is handled below + case 183 /* UnionType */: return emitUnionType(node); - case 183 /* IntersectionType */: + case 184 /* IntersectionType */: return emitIntersectionType(node); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return emitConditionalType(node); - case 185 /* InferType */: + case 186 /* InferType */: return emitInferType(node); - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return emitParenthesizedType(node); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(node); - case 187 /* ThisType */: + case 188 /* ThisType */: return emitThisType(); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return emitTypeOperator(node); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return emitIndexedAccessType(node); - case 190 /* MappedType */: + case 191 /* MappedType */: return emitMappedType(node); - case 191 /* LiteralType */: + case 192 /* LiteralType */: return emitLiteralType(node); - case 193 /* TemplateLiteralType */: + case 193 /* NamedTupleMember */: + return emitNamedTupleMember(node); + case 194 /* TemplateLiteralType */: return emitTemplateType(node); - case 195 /* ImportType */: + case 195 /* TemplateLiteralTypeSpan */: + return emitTemplateTypeSpan(node); + case 196 /* ImportType */: return emitImportTypeNode(node); - case 303 /* JSDocAllType */: - writePunctuation("*"); - return; - case 304 /* JSDocUnknownType */: - writePunctuation("?"); - return; - case 305 /* JSDocNullableType */: - return emitJSDocNullableType(node); - case 306 /* JSDocNonNullableType */: - return emitJSDocNonNullableType(node); - case 307 /* JSDocOptionalType */: - return emitJSDocOptionalType(node); - case 181 /* RestType */: - case 309 /* JSDocVariadicType */: - return emitRestOrJSDocVariadicType(node); - case 192 /* NamedTupleMember */: - return emitNamedTupleMember(node); // Binding patterns - case 196 /* ObjectBindingPattern */: + case 197 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return emitBindingElement(node); // Misc - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return emitTemplateSpan(node); - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: return emitSemicolonClassElement(); // Statements - case 230 /* Block */: + case 231 /* Block */: return emitBlock(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return emitVariableStatement(node); - case 231 /* EmptyStatement */: + case 232 /* EmptyStatement */: return emitEmptyStatement(/*isEmbeddedStatement*/ false); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return emitExpressionStatement(node); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return emitIfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return emitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return emitWhileStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return emitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return emitForInStatement(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return emitForOfStatement(node); - case 240 /* ContinueStatement */: + case 241 /* ContinueStatement */: return emitContinueStatement(node); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: return emitBreakStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return emitReturnStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return emitWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return emitSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return emitLabeledStatement(node); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return emitThrowStatement(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return emitTryStatement(node); - case 248 /* DebuggerStatement */: + case 249 /* DebuggerStatement */: return emitDebuggerStatement(node); // Declarations - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return emitVariableDeclarationList(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return emitFunctionDeclaration(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return emitClassDeclaration(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return emitTypeAliasDeclaration(node); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return emitModuleBlock(node); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return emitCaseBlock(node); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return emitNamespaceExportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return emitImportDeclaration(node); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return emitImportClause(node); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return emitNamespaceImport(node); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: return emitNamespaceExport(node); - case 264 /* NamedImports */: + case 265 /* NamedImports */: return emitNamedImports(node); - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: return emitImportSpecifier(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return emitExportAssignment(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return emitExportDeclaration(node); - case 268 /* NamedExports */: + case 269 /* NamedExports */: return emitNamedExports(node); - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: return emitExportSpecifier(node); - case 271 /* MissingDeclaration */: + case 272 /* MissingDeclaration */: return; // Module references - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: return emitExternalModuleReference(node); // JSX (non-expression) case 11 /* JsxText */: return emitJsxText(node); - case 275 /* JsxOpeningElement */: - case 278 /* JsxOpeningFragment */: + case 276 /* JsxOpeningElement */: + case 279 /* JsxOpeningFragment */: return emitJsxOpeningElementOrFragment(node); - case 276 /* JsxClosingElement */: - case 279 /* JsxClosingFragment */: + case 277 /* JsxClosingElement */: + case 280 /* JsxClosingFragment */: return emitJsxClosingElementOrFragment(node); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return emitJsxAttribute(node); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return emitJsxAttributes(node); - case 282 /* JsxSpreadAttribute */: + case 283 /* JsxSpreadAttribute */: return emitJsxSpreadAttribute(node); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return emitJsxExpression(node); // Clauses - case 284 /* CaseClause */: + case 285 /* CaseClause */: return emitCaseClause(node); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: return emitDefaultClause(node); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: return emitHeritageClause(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return emitCatchClause(node); // Property assignments - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: return emitSpreadAssignment(node); // Enum - case 291 /* EnumMember */: + case 292 /* EnumMember */: return emitEnumMember(node); + // Unparsed + case 293 /* UnparsedPrologue */: + return writeUnparsedNode(node); + case 300 /* UnparsedSource */: + case 294 /* UnparsedPrepend */: + return emitUnparsedSourceOrPrepend(node); + case 295 /* UnparsedText */: + case 296 /* UnparsedInternalText */: + return emitUnparsedTextLike(node); + case 297 /* UnparsedSyntheticReference */: + return emitUnparsedSyntheticReference(node); + // Top-level nodes + case 298 /* SourceFile */: + return emitSourceFile(node); + case 299 /* Bundle */: + return ts.Debug.fail("Bundles should be printed using printBundle"); + // SyntaxKind.UnparsedSource (handled above) + case 301 /* InputFiles */: + return ts.Debug.fail("InputFiles should not be printed"); // JSDoc nodes (only used in codefixes currently) - case 326 /* JSDocParameterTag */: - case 333 /* JSDocPropertyTag */: + case 302 /* JSDocTypeExpression */: + return emitJSDocTypeExpression(node); + case 303 /* JSDocNameReference */: + return emitJSDocNameReference(node); + case 304 /* JSDocAllType */: + return writePunctuation("*"); + case 305 /* JSDocUnknownType */: + return writePunctuation("?"); + case 306 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 307 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 308 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 309 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 182 /* RestType */: + case 310 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + case 311 /* JSDocNamepathType */: + return; + case 312 /* JSDocComment */: + return emitJSDoc(node); + case 314 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 315 /* JSDocSignature */: + return emitJSDocSignature(node); + case 317 /* JSDocTag */: + case 322 /* JSDocClassTag */: + return emitJSDocSimpleTag(node); + case 318 /* JSDocAugmentsTag */: + case 319 /* JSDocImplementsTag */: + return emitJSDocHeritageTag(node); + case 320 /* JSDocAuthorTag */: + case 321 /* JSDocDeprecatedTag */: + return; + // SyntaxKind.JSDocClassTag (see JSDocTag, above) + case 323 /* JSDocPublicTag */: + case 324 /* JSDocPrivateTag */: + case 325 /* JSDocProtectedTag */: + case 326 /* JSDocReadonlyTag */: + case 327 /* JSDocOverrideTag */: + return; + case 328 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + // SyntaxKind.JSDocEnumTag (see below) + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: return emitJSDocPropertyLikeTag(node); - case 327 /* JSDocReturnTag */: - case 329 /* JSDocTypeTag */: - case 328 /* JSDocThisTag */: - case 325 /* JSDocEnumTag */: + case 329 /* JSDocEnumTag */: + case 331 /* JSDocReturnTag */: + case 332 /* JSDocThisTag */: + case 333 /* JSDocTypeTag */: return emitJSDocSimpleTypedTag(node); - case 316 /* JSDocImplementsTag */: - case 315 /* JSDocAugmentsTag */: - return emitJSDocHeritageTag(node); - case 330 /* JSDocTemplateTag */: + case 334 /* JSDocTemplateTag */: return emitJSDocTemplateTag(node); - case 331 /* JSDocTypedefTag */: + case 335 /* JSDocTypedefTag */: return emitJSDocTypedefTag(node); - case 324 /* JSDocCallbackTag */: - return emitJSDocCallbackTag(node); - case 313 /* JSDocSignature */: - return emitJSDocSignature(node); - case 312 /* JSDocTypeLiteral */: - return emitJSDocTypeLiteral(node); - case 319 /* JSDocClassTag */: - case 314 /* JSDocTag */: - return emitJSDocSimpleTag(node); - case 332 /* JSDocSeeTag */: + case 336 /* JSDocSeeTag */: return emitJSDocSeeTag(node); - case 302 /* JSDocNameReference */: - return emitJSDocNameReference(node); - case 311 /* JSDocComment */: - return emitJSDoc(node); - // Transformation nodes (ignored) + // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) + // Transformation nodes + case 339 /* NotEmittedStatement */: + case 343 /* EndOfDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: + return; } if (ts.isExpression(node)) { hint = 1 /* Expression */; if (substituteNode !== ts.noEmitSubstitution) { - lastSubstitution = node = substituteNode(hint, node); + var substitute = substituteNode(hint, node) || node; + if (substitute !== node) { + node = substitute; + if (currentParenthesizerRule) { + node = currentParenthesizerRule(node); + } + } } } - else if (ts.isToken(node)) { - return writeTokenNode(node, writePunctuation); - } } if (hint === 1 /* Expression */) { switch (node.kind) { @@ -101642,84 +104734,92 @@ var ts; // Identifiers case 78 /* Identifier */: return emitIdentifier(node); - // Reserved words - case 94 /* FalseKeyword */: - case 103 /* NullKeyword */: - case 105 /* SuperKeyword */: - case 109 /* TrueKeyword */: - case 107 /* ThisKeyword */: - case 99 /* ImportKeyword */: - writeTokenNode(node, writeKeyword); - return; // Expressions - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return emitObjectLiteralExpression(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return emitPropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return emitElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return emitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return emitNewExpression(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: return emitTypeAssertionExpression(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return emitParenthesizedExpression(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return emitFunctionExpression(node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return emitArrowFunction(node); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return emitDeleteExpression(node); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return emitVoidExpression(node); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return emitAwaitExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return emitBinaryExpression(node); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return emitConditionalExpression(node); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return emitTemplateExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return emitYieldExpression(node); - case 220 /* SpreadElement */: - return emitSpreadExpression(node); - case 221 /* ClassExpression */: + case 221 /* SpreadElement */: + return emitSpreadElement(node); + case 222 /* ClassExpression */: return emitClassExpression(node); - case 222 /* OmittedExpression */: + case 223 /* OmittedExpression */: return; - case 224 /* AsExpression */: + case 225 /* AsExpression */: return emitAsExpression(node); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return emitNonNullExpression(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return emitMetaProperty(node); + case 228 /* SyntheticExpression */: + return ts.Debug.fail("SyntheticExpression should never be printed."); // JSX - case 273 /* JsxElement */: + case 274 /* JsxElement */: return emitJsxElement(node); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return emitJsxFragment(node); + // Synthesized list + case 338 /* SyntaxList */: + return ts.Debug.fail("SyntaxList should not be printed"); // Transformation nodes - case 336 /* PartiallyEmittedExpression */: + case 339 /* NotEmittedStatement */: + return; + case 340 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return emitCommaList(node); + case 342 /* MergeDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: + return; + case 344 /* SyntheticReferenceExpression */: + return ts.Debug.fail("SyntheticReferenceExpression should not be printed"); } } + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + if (ts.isTokenKind(node.kind)) + return writeTokenNode(node, writePunctuation); + ts.Debug.fail("Unhandled SyntaxKind: " + ts.Debug.formatSyntaxKind(node.kind) + "."); } function emitMappedTypeParameter(node) { emit(node.name); @@ -101729,10 +104829,11 @@ var ts; emit(node.constraint); } function pipelineEmitWithSubstitution(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node); - pipelinePhase(hint, lastSubstitution); - ts.Debug.assert(lastNode === node || lastSubstitution === node); + ts.Debug.assertIsDefined(lastSubstitution); + node = lastSubstitution; + lastSubstitution = undefined; + pipelinePhase(hint, node); } function getHelpersFromBundledSourceFiles(bundle) { var result; @@ -101758,7 +104859,7 @@ var ts; } function emitHelpers(node) { var helpersEmitted = false; - var bundle = node.kind === 298 /* Bundle */ ? node : undefined; + var bundle = node.kind === 299 /* Bundle */ ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -101858,7 +104959,7 @@ var ts; var pos = getTextPosWithWriteLine(); writeUnparsedNode(unparsed); if (bundleFileInfo) { - updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 294 /* UnparsedText */ ? + updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 295 /* UnparsedText */ ? "text" /* Text */ : "internal" /* Internal */); } @@ -101904,7 +105005,7 @@ var ts; } function emitComputedPropertyName(node) { writePunctuation("["); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName); writePunctuation("]"); } // @@ -101931,18 +105032,18 @@ var ts; emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); - if (node.parent && node.parent.kind === 308 /* JSDocFunctionType */ && !node.name) { + if (node.parent && node.parent.kind === 309 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { emitTypeAnnotation(node.type); } // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. - emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitDecorator(decorator) { writePunctuation("@"); - emitExpression(decorator.expression); + emitExpression(decorator.expression, parenthesizer.parenthesizeLeftSideOfAccess); } // // Type members @@ -101993,7 +105094,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeKeyword(node.kind === 167 /* GetAccessor */ ? "get" : "set"); + writeKeyword(node.kind === 168 /* GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); @@ -102107,7 +105208,7 @@ var ts; writePunctuation("}"); } function emitArrayType(node) { - emit(node.elementType); + emit(node.elementType, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("["); writePunctuation("]"); } @@ -102130,21 +105231,21 @@ var ts; emit(node.type); } function emitOptionalType(node) { - emit(node.type); + emit(node.type, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("?"); } function emitUnionType(node) { - emitList(node, node.types, 516 /* UnionTypeConstituents */); + emitList(node, node.types, 516 /* UnionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitIntersectionType(node) { - emitList(node, node.types, 520 /* IntersectionTypeConstituents */); + emitList(node, node.types, 520 /* IntersectionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitConditionalType(node) { - emit(node.checkType); + emit(node.checkType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writeKeyword("extends"); writeSpace(); - emit(node.extendsType); + emit(node.extendsType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writePunctuation("?"); writeSpace(); @@ -102170,10 +105271,10 @@ var ts; function emitTypeOperator(node) { writeTokenText(node.operator, writeKeyword); writeSpace(); - emit(node.type); + emit(node.type, parenthesizer.parenthesizeMemberOfElementType); } function emitIndexedAccessType(node) { - emit(node.objectType); + emit(node.objectType, parenthesizer.parenthesizeMemberOfElementType); writePunctuation("["); emit(node.indexType); writePunctuation("]"); @@ -102266,7 +105367,7 @@ var ts; writeSpace(); } emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // Expressions @@ -102274,7 +105375,7 @@ var ts; function emitArrayLiteralExpression(node) { var elements = node.elements; var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; - emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitObjectLiteralExpression(node) { ts.forEach(node.properties, generateMemberNames); @@ -102290,13 +105391,13 @@ var ts; } } function emitPropertyAccessExpression(node) { - var expression = ts.cast(emitExpression(node.expression), ts.isExpression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); var token = node.questionDotToken || ts.setTextRangePosEnd(ts.factory.createToken(24 /* DotToken */), node.expression.end, node.name.pos); var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token); var linesAfterDot = getLinesBetweenNodes(node, token, node.name); writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false); var shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ && - mayNeedDotDotForPropertyAccess(expression) && + mayNeedDotDotForPropertyAccess(node.expression) && !writer.hasTrailingComment() && !writer.hasTrailingWhitespace(); if (shouldEmitDotDot) { @@ -102332,27 +105433,27 @@ var ts; } } function emitElementAccessExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitNewExpression(node) { emitTokenWithComment(102 /* NewKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfNew); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitTaggedTemplateExpression(node) { - emitExpression(node.tag); + emitExpression(node.tag, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); writeSpace(); emitExpression(node.template); @@ -102361,12 +105462,12 @@ var ts; writePunctuation("<"); emit(node.type); writePunctuation(">"); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); - emitExpression(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); writeLineSeparatorsAfter(node.expression, node); decreaseIndentIf(indented); emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); @@ -102390,29 +105491,29 @@ var ts; function emitDeleteExpression(node) { emitTokenWithComment(88 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitTypeOfExpression(node) { emitTokenWithComment(111 /* TypeOfKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitVoidExpression(node) { emitTokenWithComment(113 /* VoidKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitAwaitExpression(node) { emitTokenWithComment(130 /* AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitPrefixUnaryExpression(node) { writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { writeSpace(); } - emitExpression(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPrefixUnary); } function shouldEmitWhitespaceBeforeOperand(node) { // In some cases, we need to emit a space between the operator and the operand. One obvious case @@ -102428,84 +105529,101 @@ var ts; // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. var operand = node.operand; - return operand.kind === 214 /* PrefixUnaryExpression */ + return operand.kind === 215 /* PrefixUnaryExpression */ && ((node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */)) || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */))); } function emitPostfixUnaryExpression(node) { - emitExpression(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary); writeTokenText(node.operator, writeOperator); } - var EmitBinaryExpressionState; - (function (EmitBinaryExpressionState) { - EmitBinaryExpressionState[EmitBinaryExpressionState["EmitLeft"] = 0] = "EmitLeft"; - EmitBinaryExpressionState[EmitBinaryExpressionState["EmitRight"] = 1] = "EmitRight"; - EmitBinaryExpressionState[EmitBinaryExpressionState["FinishEmit"] = 2] = "FinishEmit"; - })(EmitBinaryExpressionState || (EmitBinaryExpressionState = {})); - /** - * emitBinaryExpression includes an embedded work stack to attempt to handle as many nested binary expressions - * as possible without creating any additional stack frames. This can only be done when the emit pipeline does - * not require notification/substitution/comment/sourcemap decorations. - */ - function emitBinaryExpression(node) { - var nodeStack = [node]; - var stateStack = [0 /* EmitLeft */]; - var stackIndex = 0; - while (stackIndex >= 0) { - node = nodeStack[stackIndex]; - switch (stateStack[stackIndex]) { - case 0 /* EmitLeft */: { - maybePipelineEmitExpression(node.left); - break; - } - case 1 /* EmitRight */: { - var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */; - var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); - var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); - writeLinesAndIndent(linesBeforeOperator, isCommaOperator); - emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken, node.operatorToken.kind === 100 /* InKeyword */ ? writeKeyword : writeOperator); - emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts - writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); - maybePipelineEmitExpression(node.right); - break; - } - case 2 /* FinishEmit */: { - var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); - var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); - decreaseIndentIf(linesBeforeOperator, linesAfterOperator); - stackIndex--; - break; - } - default: return ts.Debug.fail("Invalid state " + stateStack[stackIndex] + " for emitBinaryExpressionWorker"); + function createEmitBinaryExpression() { + return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined); + function onEnter(node, state) { + if (state) { + state.stackIndex++; + state.preserveSourceNewlinesStack[state.stackIndex] = preserveSourceNewlines; + state.containerPosStack[state.stackIndex] = containerPos; + state.containerEndStack[state.stackIndex] = containerEnd; + state.declarationListContainerEndStack[state.stackIndex] = declarationListContainerEnd; + var emitComments_1 = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node); + var emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node); + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (emitComments_1) + emitCommentsBeforeNode(node); + if (emitSourceMaps) + emitSourceMapsBeforeNode(node); + beforeEmitNode(node); } - } - function maybePipelineEmitExpression(next) { - // Advance the state of this unit of work, - stateStack[stackIndex]++; - // Then actually do the work of emitting the node `next` returned by the prior state - // The following section should be identical to `pipelineEmit` save it assumes EmitHint.Expression and offloads - // binary expression handling, where possible, to the contained work queue - // #region trampolinePipelineEmit - var savedLastNode = lastNode; - var savedLastSubstitution = lastSubstitution; - lastNode = next; - lastSubstitution = undefined; + else { + state = { + stackIndex: 0, + preserveSourceNewlinesStack: [undefined], + containerPosStack: [-1], + containerEndStack: [-1], + declarationListContainerEndStack: [-1], + shouldEmitCommentsStack: [false], + shouldEmitSourceMapsStack: [false], + }; + } + return state; + } + function onLeft(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "left"); + } + function onOperator(operatorToken, _state, node) { + var isCommaOperator = operatorToken.kind !== 27 /* CommaToken */; + var linesBeforeOperator = getLinesBetweenNodes(node, node.left, operatorToken); + var linesAfterOperator = getLinesBetweenNodes(node, operatorToken, node.right); + writeLinesAndIndent(linesBeforeOperator, isCommaOperator); + emitLeadingCommentsOfPosition(operatorToken.pos); + writeTokenNode(operatorToken, operatorToken.kind === 100 /* InKeyword */ ? writeKeyword : writeOperator); + emitTrailingCommentsOfPosition(operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts + writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); + } + function onRight(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "right"); + } + function onExit(node, state) { + var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); + var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); + decreaseIndentIf(linesBeforeOperator, linesAfterOperator); + if (state.stackIndex > 0) { + var savedPreserveSourceNewlines = state.preserveSourceNewlinesStack[state.stackIndex]; + var savedContainerPos = state.containerPosStack[state.stackIndex]; + var savedContainerEnd = state.containerEndStack[state.stackIndex]; + var savedDeclarationListContainerEnd = state.declarationListContainerEndStack[state.stackIndex]; + var shouldEmitComments_1 = state.shouldEmitCommentsStack[state.stackIndex]; + var shouldEmitSourceMaps_1 = state.shouldEmitSourceMapsStack[state.stackIndex]; + afterEmitNode(savedPreserveSourceNewlines); + if (shouldEmitSourceMaps_1) + emitSourceMapsAfterNode(node); + if (shouldEmitComments_1) + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); + state.stackIndex--; + } + } + function maybeEmitExpression(next, parent, side) { + var parenthesizerRule = side === "left" ? + parenthesizer.getParenthesizeLeftSideOfBinaryForOperator(parent.operatorToken.kind) : + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(parent.operatorToken.kind); var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next); - if (pipelinePhase === pipelineEmitWithHint && ts.isBinaryExpression(next)) { - // If the target pipeline phase is emit directly, and the next node's also a binary expression, - // skip all the intermediate indirection and push the expression directly onto the work stack - stackIndex++; - stateStack[stackIndex] = 0 /* EmitLeft */; - nodeStack[stackIndex] = next; + if (pipelinePhase === pipelineEmitWithSubstitution) { + ts.Debug.assertIsDefined(lastSubstitution); + next = parenthesizerRule(ts.cast(lastSubstitution, ts.isExpression)); + pipelinePhase = getNextPipelinePhase(1 /* Substitution */, 1 /* Expression */, next); + lastSubstitution = undefined; } - else { - pipelinePhase(1 /* Expression */, next); + if (pipelinePhase === pipelineEmitWithComments || + pipelinePhase === pipelineEmitWithSourceMaps || + pipelinePhase === pipelineEmitWithHint) { + if (ts.isBinaryExpression(next)) { + return next; + } } - ts.Debug.assert(lastNode === next); - lastNode = savedLastNode; - lastSubstitution = savedLastSubstitution; - // #endregion trampolinePipelineEmit + currentParenthesizerRule = parenthesizerRule; + pipelinePhase(1 /* Expression */, next); } } function emitConditionalExpression(node) { @@ -102513,16 +105631,16 @@ var ts; var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue); var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken); var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse); - emitExpression(node.condition); + emitExpression(node.condition, parenthesizer.parenthesizeConditionOfConditionalExpression); writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); emit(node.questionToken); writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true); - emitExpression(node.whenTrue); + emitExpression(node.whenTrue, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion); writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true); emit(node.colonToken); writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true); - emitExpression(node.whenFalse); + emitExpression(node.whenFalse, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeColon, linesAfterColon); } function emitTemplateExpression(node) { @@ -102532,22 +105650,22 @@ var ts; function emitYieldExpression(node) { emitTokenWithComment(124 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); - emitExpressionWithLeadingSpace(node.expression); + emitExpressionWithLeadingSpace(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } - function emitSpreadExpression(node) { + function emitSpreadElement(node) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitClassExpression(node) { generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); } function emitAsExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); if (node.type) { writeSpace(); writeKeyword("as"); @@ -102556,7 +105674,7 @@ var ts; } } function emitNonNullExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); writeOperator("!"); } function emitMetaProperty(node) { @@ -102599,7 +105717,7 @@ var ts; } } function emitExpressionStatement(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfExpressionStatement); // Emit semicolon in non json files // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { @@ -102616,7 +105734,7 @@ var ts; if (node.elseStatement) { writeLineOrSpace(node, node.thenStatement, node.elseStatement); emitTokenWithComment(90 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); - if (node.elseStatement.kind === 234 /* IfStatement */) { + if (node.elseStatement.kind === 235 /* IfStatement */) { writeSpace(); emit(node.elseStatement); } @@ -102679,7 +105797,7 @@ var ts; emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(156 /* OfKeyword */, node.initializer.end, writeKeyword, node); + emitTokenWithComment(157 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); @@ -102687,7 +105805,7 @@ var ts; } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 250 /* VariableDeclarationList */) { + if (node.kind === 251 /* VariableDeclarationList */) { emit(node); } else { @@ -102724,7 +105842,7 @@ var ts; } pos = writeTokenText(token, writer, pos); if (isSimilarNode && contextNode.end !== pos) { - var isJsxExprContext = contextNode.kind === 283 /* JsxExpression */; + var isJsxExprContext = contextNode.kind === 284 /* JsxExpression */; emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ !isJsxExprContext, /*forceNoNewline*/ isJsxExprContext); } return pos; @@ -102788,7 +105906,7 @@ var ts; emit(node.name); emit(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); @@ -102807,9 +105925,6 @@ var ts; emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } - function emitBlockCallback(_hint, body) { - emitBlockFunctionBody(body); - } function emitSignatureAndBody(node, emitSignatureHead) { var body = node.body; if (body) { @@ -102822,12 +105937,7 @@ var ts; ts.forEach(node.parameters, generateNames); generateNames(node.body); emitSignatureHead(node); - if (onEmitNode) { - onEmitNode(4 /* Unspecified */, body, emitBlockCallback); - } - else { - emitBlockFunctionBody(body); - } + emitBlockFunctionBody(body); popNameGenerationScope(node); if (indentedFlag) { decreaseIndent(); @@ -102836,7 +105946,7 @@ var ts; else { emitSignatureHead(node); writeSpace(); - emitExpression(body); + emitExpression(body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); } } else { @@ -102880,6 +105990,7 @@ var ts; return true; } function emitBlockFunctionBody(body) { + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(body); writeSpace(); writePunctuation("{"); increaseIndent(); @@ -102894,6 +106005,7 @@ var ts; } decreaseIndent(); writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body); + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); @@ -102909,7 +106021,7 @@ var ts; increaseIndent(); } else { - emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset); + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, /*parenthesizerRule*/ undefined, statementOffset); } } function emitClassDeclaration(node) { @@ -102984,7 +106096,7 @@ var ts; var body = node.body; if (!body) return writeTrailingSemicolon(); - while (body.kind === 256 /* ModuleDeclaration */) { + while (body && ts.isModuleDeclaration(body)) { writePunctuation("."); emit(body.name); body = body.body; @@ -103074,7 +106186,9 @@ var ts; emitTokenWithComment(87 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, node.isExportEquals ? + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(62 /* EqualsToken */) : + parenthesizer.parenthesizeExpressionOfExportDefault); writeTrailingSemicolon(); } function emitExportDeclaration(node) { @@ -103246,7 +106360,7 @@ var ts; function emitCaseClause(node) { emitTokenWithComment(81 /* CaseKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { @@ -103307,7 +106421,7 @@ var ts; var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } - emitExpression(initializer); + emitExpression(initializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitShorthandPropertyAssignment(node) { emit(node.name); @@ -103315,13 +106429,13 @@ var ts; writeSpace(); writePunctuation("="); writeSpace(); - emitExpression(node.objectAssignmentInitializer); + emitExpression(node.objectAssignmentInitializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } } function emitSpreadAssignment(node) { if (node.expression) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } } // @@ -103329,7 +106443,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // JSDoc @@ -103337,18 +106451,21 @@ var ts; function emitJSDoc(node) { write("/**"); if (node.comment) { - var lines = node.comment.split(/\r\n?|\n/g); - for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { - var line = lines_2[_a]; - writeLine(); - writeSpace(); - writePunctuation("*"); - writeSpace(); - write(line); + var text = ts.getTextOfJSDocComment(node.comment); + if (text) { + var lines = text.split(/\r\n?|\n/g); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } } } if (node.tags) { - if (node.tags.length === 1 && node.tags[0].kind === 329 /* JSDocTypeTag */ && !node.comment) { + if (node.tags.length === 1 && node.tags[0].kind === 333 /* JSDocTypeTag */ && !node.comment) { writeSpace(); emit(node.tags[0]); } @@ -103393,7 +106510,7 @@ var ts; function emitJSDocTypedefTag(tag) { emitJSDocTagName(tag.tagName); if (tag.typeExpression) { - if (tag.typeExpression.kind === 301 /* JSDocTypeExpression */) { + if (tag.typeExpression.kind === 302 /* JSDocTypeExpression */) { emitJSDocTypeExpression(tag.typeExpression); } else { @@ -103412,7 +106529,7 @@ var ts; emit(tag.fullName); } emitJSDocComment(tag.comment); - if (tag.typeExpression && tag.typeExpression.kind === 312 /* JSDocTypeLiteral */) { + if (tag.typeExpression && tag.typeExpression.kind === 314 /* JSDocTypeLiteral */) { emitJSDocTypeLiteral(tag.typeExpression); } } @@ -103465,9 +106582,10 @@ var ts; emit(tagName); } function emitJSDocComment(comment) { - if (comment) { + var text = ts.getTextOfJSDocComment(comment); + if (text) { writeSpace(); - write(comment); + write(text); } } function emitJSDocTypeExpression(typeExpression) { @@ -103570,7 +106688,7 @@ var ts; emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitTripleSlashDirectivesIfNeeded(node); - emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); + emitList(node, statements, 1 /* MultiLine */, /*parenthesizerRule*/ undefined, index === -1 ? statements.length : index); popNameGenerationScope(node); } // Transformation nodes @@ -103578,7 +106696,7 @@ var ts; emitExpression(node.expression); } function emitCommaList(node) { - emitExpressionList(node, node.elements, 528 /* CommaListElements */); + emitExpressionList(node, node.elements, 528 /* CommaListElements */, /*parenthesizerRule*/ undefined); } /** * Emits any prologue directives at the start of a Statement list, returning the @@ -103724,12 +106842,12 @@ var ts; emit(node); } } - function emitInitializer(node, equalCommentStartPos, container) { + function emitInitializer(node, equalCommentStartPos, container, parenthesizerRule) { if (node) { writeSpace(); emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container); writeSpace(); - emitExpression(node); + emitExpression(node, parenthesizerRule); } } function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { @@ -103744,10 +106862,10 @@ var ts; emit(node); } } - function emitExpressionWithLeadingSpace(node) { + function emitExpressionWithLeadingSpace(node, parenthesizerRule) { if (node) { writeSpace(); - emitExpression(node); + emitExpression(node, parenthesizerRule); } } function emitWithTrailingSpace(node) { @@ -103777,7 +106895,7 @@ var ts; emitList(parentNode, decorators, 2146305 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 53776 /* TypeArguments */); + emitList(parentNode, typeArguments, 53776 /* TypeArguments */, parenthesizer.parenthesizeMemberOfElementType); } function emitTypeParameters(parentNode, typeParameters) { if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures @@ -103816,12 +106934,6 @@ var ts; function emitParametersForIndexSignature(parentNode, parameters) { emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */); } - function emitList(parentNode, children, format, start, count) { - emitNodeList(emit, parentNode, children, format, start, count); - } - function emitExpressionList(parentNode, children, format, start, count) { - emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 - } function writeDelimiter(format) { switch (format & 60 /* DelimitersMask */) { case 0 /* None */: @@ -103844,7 +106956,13 @@ var ts; break; } } - function emitNodeList(emit, parentNode, children, format, start, count) { + function emitList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count); + } + function emitExpressionList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emitExpression, parentNode, children, format, parenthesizerRule, start, count); + } + function emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; @@ -103863,8 +106981,7 @@ var ts; } if (format & 15360 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); - if (isEmpty && !isUndefined) { - // TODO: GH#18217 + if (isEmpty && children) { emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists } } @@ -103873,7 +106990,7 @@ var ts; } if (isEmpty) { // Write a line terminator if the parent node was multi-line - if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && ts.rangeIsOnSingleLine(parentNode, currentSourceFile))) { + if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && (!parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile)))) { writeLine(); } else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) { @@ -103881,6 +106998,7 @@ var ts; } } else { + ts.Debug.type(children); // Write the opening line terminator or leading whitespace. var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; @@ -103915,7 +107033,7 @@ var ts; // a // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline // , - if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { + if (format & 60 /* DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { emitLeadingCommentsOfPosition(previousSibling.end); } writeDelimiter(format); @@ -103948,7 +107066,12 @@ var ts; shouldEmitInterveningComments = mayEmitInterveningComments; } nextListElementPos = child.pos; - emit(child); + if (emit.length === 1) { + emit(child); + } + else { + emit(child, parenthesizerRule); + } if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); shouldDecreaseIndentAfterEmit = false; @@ -103973,7 +107096,7 @@ var ts; // 2 // /* end of element 2 */ // ]; - if (previousSibling && parentNode.end !== previousSibling.end && (format & 60 /* DelimitersMask */) && !skipTrailingComments) { + if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60 /* DelimitersMask */) && !skipTrailingComments) { emitLeadingCommentsOfPosition(hasTrailingComma && (children === null || children === void 0 ? void 0 : children.end) ? children.end : previousSibling.end); } // Decrease the indent, if requested. @@ -103994,8 +107117,7 @@ var ts; onAfterEmitNodeArray(children); } if (format & 15360 /* BracketsMask */) { - if (isEmpty && !isUndefined) { - // TODO: GH#18217 + if (isEmpty && children) { emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists } writePunctuation(getClosingBracket(format)); @@ -104126,7 +107248,7 @@ var ts; } var firstChild_1 = children[0]; if (firstChild_1 === undefined) { - return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; + return !parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } if (firstChild_1.pos === nextListElementPos) { // If this child starts at the beginning of a list item in a parent list, its leading @@ -104150,7 +107272,8 @@ var ts; // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } - if (!ts.positionIsSynthesized(parentNode.pos) && + if (parentNode && + !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || ts.getOriginalNode(firstChild_1.parent) === ts.getOriginalNode(parentNode))) { if (preserveSourceNewlines) { @@ -104173,10 +107296,10 @@ var ts; // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } - else if (!ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode) && previousNode.parent === nextNode.parent) { - if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); }); - } + else if (preserveSourceNewlines && siblingNodePositionsAreComparable(previousNode, nextNode)) { + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); }); + } + else if (!preserveSourceNewlines && !ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode)) { return ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1; } else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) { @@ -104195,9 +107318,9 @@ var ts; } var lastChild = ts.lastOrUndefined(children); if (lastChild === undefined) { - return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; + return !parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } - if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { + if (parentNode && !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { if (preserveSourceNewlines) { var end_1 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end; return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_1, parentNode.end, currentSourceFile, includeComments); }); @@ -104283,7 +107406,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 207 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + while (node.kind === 208 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -104353,84 +107476,84 @@ var ts; if (!node) return; switch (node.kind) { - case 230 /* Block */: + case 231 /* Block */: ts.forEach(node.statements, generateNames); break; - case 245 /* LabeledStatement */: - case 243 /* WithStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 246 /* LabeledStatement */: + case 244 /* WithStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: generateNames(node.statement); break; - case 234 /* IfStatement */: + case 235 /* IfStatement */: generateNames(node.thenStatement); generateNames(node.elseStatement); break; - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: - case 238 /* ForInStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: + case 239 /* ForInStatement */: generateNames(node.initializer); generateNames(node.statement); break; - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: generateNames(node.caseBlock); break; - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: ts.forEach(node.clauses, generateNames); break; - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: ts.forEach(node.statements, generateNames); break; - case 247 /* TryStatement */: + case 248 /* TryStatement */: generateNames(node.tryBlock); generateNames(node.catchClause); generateNames(node.finallyBlock); break; - case 287 /* CatchClause */: + case 288 /* CatchClause */: generateNames(node.variableDeclaration); generateNames(node.block); break; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: generateNames(node.declarationList); break; - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: ts.forEach(node.declarations, generateNames); break; - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: generateNameIfNeeded(node.name); break; - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: generateNameIfNeeded(node.name); if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { ts.forEach(node.parameters, generateNames); generateNames(node.body); } break; - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: ts.forEach(node.elements, generateNames); break; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: generateNames(node.importClause); break; - case 262 /* ImportClause */: + case 263 /* ImportClause */: generateNameIfNeeded(node.name); generateNames(node.namedBindings); break; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: generateNameIfNeeded(node.name); break; - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: generateNameIfNeeded(node.name); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: ts.forEach(node.elements, generateNames); break; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: generateNameIfNeeded(node.propertyName || node.name); break; } @@ -104439,12 +107562,12 @@ var ts; if (!node) return; switch (node.kind) { - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: generateNameIfNeeded(node.name); break; } @@ -104626,23 +107749,23 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 266 /* ExportAssignment */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 267 /* ExportAssignment */: return generateNameForExportDefault(); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return generateNameForClassExpression(); - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return generateNameForMethodOrAccessor(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return makeTempVariableName(0 /* Auto */, /*reserveInNestedScopes*/ true); default: return makeTempVariableName(0 /* Auto */); @@ -104685,25 +107808,45 @@ var ts; } // Comments function pipelineEmitWithComments(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node); + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + emitCommentsBeforeNode(node); + pipelinePhase(hint, node); + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitCommentsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit leading comments + emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + } + } + function emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit trailing comments + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = false; + } + emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitLeadingCommentsOfNode(node, emitFlags, pos, end) { enterComment(); hasWrittenComment = false; - var emitFlags = ts.getEmitFlags(node); - var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; - var isEmittedNode = node.kind !== 335 /* NotEmittedStatement */; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */; var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; // Save current container state on the stack. - var savedContainerPos = containerPos; - var savedContainerEnd = containerEnd; - var savedDeclarationListContainerEnd = declarationListContainerEnd; if ((pos > 0 || end > 0) && pos !== end) { // Emit leading comments if the position is not synthesized and the node // has not opted out from emitting leading comments. if (!skipLeadingComments) { - emitLeadingComments(pos, isEmittedNode); + emitLeadingComments(pos, /*isEmittedNode*/ node.kind !== 339 /* NotEmittedStatement */); } if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments. @@ -104714,23 +107857,17 @@ var ts; containerEnd = end; // To avoid invalid comment emit in a down-level binding pattern, we // keep track of the last declaration list container's end - if (node.kind === 250 /* VariableDeclarationList */) { + if (node.kind === 251 /* VariableDeclarationList */) { declarationListContainerEnd = end; } } } ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); exitComment(); - var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node); - if (emitFlags & 2048 /* NoNestedComments */) { - commentsDisabled = true; - pipelinePhase(hint, node); - commentsDisabled = false; - } - else { - pipelinePhase(hint, node); - } + } + function emitTrailingCommentsOfNode(node, emitFlags, pos, end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { enterComment(); + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); if ((pos > 0 || end > 0) && pos !== end) { // Restore previous container state. @@ -104739,12 +107876,11 @@ var ts; declarationListContainerEnd = savedDeclarationListContainerEnd; // Emit trailing comments if the position is not synthesized and the node // has not opted out from emitting leading comments and is an emitted node. - if (!skipTrailingComments && isEmittedNode) { + if (!skipTrailingComments && node.kind !== 339 /* NotEmittedStatement */) { emitTrailingComments(end); } } exitComment(); - ts.Debug.assert(lastNode === node || lastSubstitution === node); } function emitLeadingSynthesizedComment(comment) { if (comment.hasLeadingNewline || comment.kind === 2 /* SingleLineCommentTrivia */) { @@ -104804,6 +107940,23 @@ var ts; } exitComment(); } + function siblingNodePositionsAreComparable(previousNode, nextNode) { + if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) { + return false; + } + if (nextNode.pos < previousNode.end) { + return false; + } + previousNode = ts.getOriginalNode(previousNode); + nextNode = ts.getOriginalNode(nextNode); + var parent = previousNode.parent; + if (!parent || parent !== nextNode.parent) { + return false; + } + var parentNodeArray = ts.getContainingNodeArray(previousNode); + var prevNodeIndex = parentNodeArray === null || parentNodeArray === void 0 ? void 0 : parentNodeArray.indexOf(previousNode); + return prevNodeIndex !== undefined && prevNodeIndex > -1 && parentNodeArray.indexOf(nextNode) === prevNodeIndex + 1; + } function emitLeadingComments(pos, isEmittedNode) { hasWrittenComment = false; if (isEmittedNode) { @@ -104976,42 +108129,49 @@ var ts; } return node.parsedSourceMap || undefined; } - function pipelineEmitWithSourceMap(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); + function pipelineEmitWithSourceMaps(hint, node) { var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node); - if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) { - pipelinePhase(hint, node); - } - else if (ts.isUnparsedNode(node)) { + emitSourceMapsBeforeNode(node); + pipelinePhase(hint, node); + emitSourceMapsAfterNode(node); + } + function emitSourceMapsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit leading sourcemap + if (ts.isUnparsedNode(node)) { + ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); var parsed = getParsedSourceMap(node.parent); if (parsed && sourceMapGenerator) { sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); } - pipelinePhase(hint, node); } else { - var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; - var emitFlags = ts.getEmitFlags(node); - if (node.kind !== 335 /* NotEmittedStatement */ + var source = sourceMapRange.source || sourceMapSource; + if (node.kind !== 339 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 - && pos >= 0) { - emitSourcePos(source, skipSourceTrivia(source, pos)); + && sourceMapRange.pos >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); } if (emitFlags & 64 /* NoNestedSourceMaps */) { sourceMapsDisabled = true; - pipelinePhase(hint, node); - sourceMapsDisabled = false; } - else { - pipelinePhase(hint, node); + } + } + function emitSourceMapsAfterNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit trailing sourcemap + if (!ts.isUnparsedNode(node)) { + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = false; } - if (node.kind !== 335 /* NotEmittedStatement */ + if (node.kind !== 339 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 - && end >= 0) { - emitSourcePos(source, end); + && sourceMapRange.end >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); } } - ts.Debug.assert(lastNode === node || lastSubstitution === node); } /** * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source @@ -105163,12 +108323,22 @@ var ts; return ts.getBaseFileName(ts.normalizePath(fileName)); } function createCachedFileSystemEntries(rootDir, rootDirPath) { - var resultFromHost = { - files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories(rootDir) || [] - }; - cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); - return resultFromHost; + var _a; + if (!host.realpath || ts.ensureTrailingDirectorySeparator(toPath(host.realpath(rootDir))) === rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); + return resultFromHost; + } + // If the directory is symlink do not cache the result + if ((_a = host.directoryExists) === null || _a === void 0 ? void 0 : _a.call(host, rootDir)) { + cachedReadDirectoryResult.set(rootDirPath, false); + return false; + } + // Non existing directory + return undefined; } /** * If the readDirectory result was already cached, it returns that @@ -105243,17 +108413,32 @@ var ts; } function readDirectory(rootDir, extensions, excludes, includes, depth) { var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { + var rootResult = tryReadDirectory(rootDir, rootDirPath); + var rootSymLinkResult; + if (rootResult !== undefined) { return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir) { var path = toPath(dir); if (path === rootDirPath) { - return result; - } - return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + return rootResult || getFileSystemEntriesFromHost(dir, path); + } + var result = tryReadDirectory(dir, path); + return result !== undefined ? + result || getFileSystemEntriesFromHost(dir, path) : + ts.emptyFileSystemEntries; + } + function getFileSystemEntriesFromHost(dir, path) { + if (rootSymLinkResult && path === rootDirPath) + return rootSymLinkResult; + var result = { + files: ts.map(host.readDirectory(dir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || ts.emptyArray, + directories: host.getDirectories(dir) || ts.emptyArray + }; + if (path === rootDirPath) + rootSymLinkResult = result; + return result; } } function realpath(s) { @@ -105261,7 +108446,7 @@ var ts; } function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { + if (existingResult !== undefined) { // Just clear the cache for now // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated clearCache(); @@ -105321,9 +108506,9 @@ var ts; /** * Updates the map of shared extended config file watches with a new set of extended config files from a base config file of the project */ - function updateSharedExtendedConfigFileWatcher(projectPath, parsed, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath) { + function updateSharedExtendedConfigFileWatcher(projectPath, options, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath) { var _a; - var extendedConfigs = ts.arrayToMap(((_a = parsed === null || parsed === void 0 ? void 0 : parsed.options.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath); + var extendedConfigs = ts.arrayToMap(((_a = options === null || options === void 0 ? void 0 : options.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath); // remove project from all unrelated watchers extendedConfigFilesMap.forEach(function (watcher, extendedConfigFilePath) { if (!extendedConfigs.has(extendedConfigFilePath)) { @@ -105341,12 +108526,12 @@ var ts; // start watching previously unseen extended config extendedConfigFilesMap.set(extendedConfigFilePath, { projects: new ts.Set([projectPath]), - fileWatcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath), + watcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath), close: function () { var existing = extendedConfigFilesMap.get(extendedConfigFilePath); if (!existing || existing.projects.size !== 0) return; - existing.fileWatcher.close(); + existing.watcher.close(); extendedConfigFilesMap.delete(extendedConfigFilePath); }, }); @@ -105354,6 +108539,31 @@ var ts; }); } ts.updateSharedExtendedConfigFileWatcher = updateSharedExtendedConfigFileWatcher; + /** + * Remove the project from the extended config file watchers and close not needed watches + */ + function clearSharedExtendedConfigFileWatcher(projectPath, extendedConfigFilesMap) { + extendedConfigFilesMap.forEach(function (watcher) { + if (watcher.projects.delete(projectPath)) + watcher.close(); + }); + } + ts.clearSharedExtendedConfigFileWatcher = clearSharedExtendedConfigFileWatcher; + /** + * Clean the extendsConfigCache when extended config file has changed + */ + function cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath) { + if (!extendedConfigCache.delete(extendedConfigFilePath)) + return; + extendedConfigCache.forEach(function (_a, key) { + var _b; + var extendedResult = _a.extendedResult; + if ((_b = extendedResult.extendedSourceFiles) === null || _b === void 0 ? void 0 : _b.some(function (extendedFile) { return toPath(extendedFile) === extendedConfigFilePath; })) { + cleanExtendedConfigCache(extendedConfigCache, key, toPath); + } + }); + } + ts.cleanExtendedConfigCache = cleanExtendedConfigCache; /** * Updates the existing missing file watches with the new set of missing files after new program is created */ @@ -105405,7 +108615,7 @@ var ts; ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; /* @internal */ function isIgnoredFileFromWildCardWatching(_a) { - var watchedDirPath = _a.watchedDirPath, fileOrDirectory = _a.fileOrDirectory, fileOrDirectoryPath = _a.fileOrDirectoryPath, configFileName = _a.configFileName, options = _a.options, program = _a.program, extraFileExtensions = _a.extraFileExtensions, currentDirectory = _a.currentDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, writeLog = _a.writeLog; + var watchedDirPath = _a.watchedDirPath, fileOrDirectory = _a.fileOrDirectory, fileOrDirectoryPath = _a.fileOrDirectoryPath, configFileName = _a.configFileName, options = _a.options, program = _a.program, extraFileExtensions = _a.extraFileExtensions, currentDirectory = _a.currentDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, writeLog = _a.writeLog, toPath = _a.toPath; var newPath = ts.removeIgnoredPath(fileOrDirectoryPath); if (!newPath) { writeLog("Project: " + configFileName + " Detected ignored path: " + fileOrDirectory); @@ -105441,7 +108651,8 @@ var ts; } // just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(fileOrDirectoryPath); - var realProgram = isBuilderProgram(program) ? program.getProgramOrUndefined() : program; + var realProgram = ts.isArray(program) ? undefined : isBuilderProgram(program) ? program.getProgramOrUndefined() : program; + var builderProgram = !realProgram && !ts.isArray(program) ? program : undefined; if (hasSourceFile((filePathWithoutExtension + ".ts" /* Ts */)) || hasSourceFile((filePathWithoutExtension + ".tsx" /* Tsx */))) { writeLog("Project: " + configFileName + " Detected output file: " + fileOrDirectory); @@ -105451,7 +108662,9 @@ var ts; function hasSourceFile(file) { return realProgram ? !!realProgram.getSourceFileByPath(file) : - program.getState().fileInfos.has(file); + builderProgram ? + builderProgram.getState().fileInfos.has(file) : + !!ts.find(program, function (rootFile) { return toPath(rootFile) === file; }); } } ts.isIgnoredFileFromWildCardWatching = isIgnoredFileFromWildCardWatching; @@ -105925,7 +109138,7 @@ var ts; var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; var lineContent = file.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); // trim from end - lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + lineContent = lineContent.replace(/\t/g, " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); @@ -106130,38 +109343,31 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, 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 === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames())) { + if (!program || (hasChangedAutomaticTypeDirectiveNames === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames())) return false; - } // If root file names don't match - if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) { + if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) return false; - } var seenResolvedRefs; // If project references don't match - if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + 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)) { + if (program.getSourceFiles().some(sourceFileNotUptoDate)) return false; - } // If any of the missing file paths are now created - if (program.getMissingFilePaths().some(fileExists)) { + if (program.getMissingFilePaths().some(fileExists)) return false; - } var currentOptions = program.getCompilerOptions(); // If the compilation settings do no match, then the program is not up-to-date - if (!ts.compareDataObjects(currentOptions, newOptions)) { + if (!ts.compareDataObjects(currentOptions, newOptions)) return false; - } // If everything matches but the text of config file is changed, // error locations can change for program options, so update the program - if (currentOptions.configFile && newOptions.configFile) { + if (currentOptions.configFile && newOptions.configFile) return currentOptions.configFile.text === newOptions.configFile.text; - } return true; function sourceFileNotUptoDate(sourceFile) { return !sourceFileVersionUptoDate(sourceFile) || @@ -106171,21 +109377,25 @@ var ts; return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName); } function projectReferenceUptoDate(oldRef, newRef, index) { - if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { - return false; - } - return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + return ts.projectReferenceIsEqualTo(oldRef, newRef) && + resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); } function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { if (oldResolvedRef) { - if (ts.contains(seenResolvedRefs, oldResolvedRef)) { - // Assume true + // Assume true + if (ts.contains(seenResolvedRefs, oldResolvedRef)) return true; - } - // If sourceFile for the oldResolvedRef existed, check the version for uptodate - if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + var refPath_1 = resolveProjectReferencePath(oldRef); + var newParsedCommandLine = getParsedCommandLine(refPath_1); + // Check if config file exists + if (!newParsedCommandLine) + return false; + // If change in source file + if (oldResolvedRef.commandLine.options.configFile !== newParsedCommandLine.options.configFile) + return false; + // check file names + if (!ts.arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newParsedCommandLine.fileNames)) return false; - } // Add to seen before checking the referenced paths of this config file (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); // If child project references are upto date, this project reference is uptodate @@ -106195,7 +109405,8 @@ var ts; } // In old program, not able to resolve project reference path, // so if config file doesnt exist, it is uptodate. - return !fileExists(resolveProjectReferencePath(oldRef)); + var refPath = resolveProjectReferencePath(oldRef); + return !getParsedCommandLine(refPath); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -106259,7 +109470,7 @@ var ts; var modulesWithElidedImports = new ts.Map(); // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. var sourceFilesFoundSearchingNodeModules = new ts.Map(); - ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeProgram"); var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHostLike(host); @@ -106274,6 +109485,7 @@ var ts; var hasEmitBlockingDiagnostics = new ts.Map(); var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; + var typeReferenceDirectiveResolutionCache; var actualResolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { @@ -106288,7 +109500,7 @@ var ts; }); }; } else { - moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options); + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName, options); var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } @@ -106297,7 +109509,8 @@ var ts; actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); }; } else { - var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; // TODO: GH#18217 actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } // Map from a stringified PackageId to the source file with that id. @@ -106335,15 +109548,15 @@ var ts; getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect, forEachResolvedProjectReference: forEachResolvedProjectReference }), onProgramCreateComplete = _d.onProgramCreateComplete, fileExists = _d.fileExists, directoryExists = _d.directoryExists; - ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`. var structureIsReused; - ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); structureIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (structureIsReused !== 2 /* Completely */) { processingDefaultLibFiles = []; processingOtherFiles = []; @@ -106381,13 +109594,13 @@ var ts; }); } } - ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); ts.forEach(rootNames, function (name, index) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.RootFile, index: index }); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { - ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile); @@ -106395,7 +109608,7 @@ var ts; for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i], { kind: ts.FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: (_b = resolutions[i]) === null || _b === void 0 ? void 0 : _b.packageId }); } - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // Do not process the default library if: // - The '--noLib' flag is used. @@ -106436,12 +109649,25 @@ var ts; host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); } } - oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference) { - if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { - host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + if (!host.getParsedCommandLine) { + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference) { + if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + } + }); + } + } + // Release commandlines that new program does not use + if (oldProgram && host.onReleaseParsedCommandLine) { + forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, parent, index) { + var oldReference = (parent === null || parent === void 0 ? void 0 : parent.commandLine.projectReferences[index]) || oldProgram.getProjectReferences()[index]; + var oldRefPath = resolveProjectReferencePath(oldReference); + if (!(projectReferenceRedirects === null || projectReferenceRedirects === void 0 ? void 0 : projectReferenceRedirects.has(toPath(oldRefPath)))) { + host.onReleaseParsedCommandLine(oldRefPath, oldResolvedRef, oldProgram.getCompilerOptions()); } }); } + typeReferenceDirectiveResolutionCache = undefined; // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; var program = { @@ -106470,7 +109696,6 @@ var ts; getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, - getTypeCatalog: function () { return getDiagnosticsProducingTypeChecker().getTypeCatalog(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getInstantiationCount: function () { return getDiagnosticsProducingTypeChecker().getInstantiationCount(); }, getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); }, @@ -106518,19 +109743,19 @@ var ts; verifyCompilerOptions(); ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return program; function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) { if (!moduleNames.length) return ts.emptyArray; var containingFileName = ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); var redirectedReference = getRedirectReferenceForResolution(containingFile); - ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveModule"); var result = actualResolveModuleNamesWorker(moduleNames, containingFileName, reusedNames, redirectedReference); ts.performance.mark("afterResolveModule"); ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile) { @@ -106538,12 +109763,12 @@ var ts; return []; var containingFileName = !ts.isString(containingFile) ? ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile; var redirectedReference = !ts.isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined; - ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveTypeReference"); var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference); ts.performance.mark("afterResolveTypeReference"); ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function getRedirectReferenceForResolution(file) { @@ -106636,13 +109861,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_14 = []; + var result_15 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_14.push(resolvedModule); + result_15.push(resolvedModule); } - return result_14; + return result_15; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -106753,7 +109978,9 @@ var ts; var newResolvedRef = parseProjectReferenceConfigFile(newRef); if (oldResolvedRef) { // Resolved project reference has gone missing or changed - return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + return !newResolvedRef || + newResolvedRef.sourceFile !== oldResolvedRef.sourceFile || + !ts.arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newResolvedRef.commandLine.fileNames); } else { // A previously-unresolved reference may be resolved now @@ -107015,7 +110242,7 @@ var ts; } function emitBuildInfo(writeFileCallback) { ts.Debug.assert(!ts.outFile(options)); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeEmit"); var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), /*targetSourceFile*/ undefined, @@ -107024,7 +110251,7 @@ var ts; /*onlyBuildInfo*/ true); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return emitResult; } function getResolvedProjectReferences() { @@ -107070,9 +110297,9 @@ var ts; return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) { - ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); var result = runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function isEmitBlocked(emitFileName) { @@ -107276,22 +110503,22 @@ var ts; // Return directly from the case if the given node doesnt want to visit each child // Otherwise break to visit each child switch (parent.kind) { - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?")); return "skip"; } // falls through - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: - case 249 /* VariableDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: + case 250 /* VariableDeclaration */: // type annotation if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files)); @@ -107299,58 +110526,58 @@ var ts; } } switch (node.kind) { - case 262 /* ImportClause */: + case 263 /* ImportClause */: if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type")); return "skip"; } break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type")); return "skip"; } break; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files)); return "skip"; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: var heritageClause = node; if (heritageClause.token === 116 /* ImplementsKeyword */) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: var interfaceKeyword = ts.tokenToString(117 /* InterfaceKeyword */); ts.Debug.assertIsDefined(interfaceKeyword); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword)); return "skip"; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var moduleKeyword = node.flags & 16 /* Namespace */ ? ts.tokenToString(140 /* NamespaceKeyword */) : ts.tokenToString(139 /* ModuleKeyword */); ts.Debug.assertIsDefined(moduleKeyword); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword)); return "skip"; - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files)); return "skip"; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(91 /* EnumKeyword */)); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword)); return "skip"; - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files)); return "skip"; - case 224 /* AsExpression */: + case 225 /* AsExpression */: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files)); return "skip"; - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } } @@ -107359,29 +110586,29 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning)); } switch (parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: // Check type parameters if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files)); return "skip"; } // falls through - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // Check modifiers if (nodes === parent.modifiers) { - checkModifiers(parent.modifiers, parent.kind === 232 /* VariableStatement */); + checkModifiers(parent.modifiers, parent.kind === 233 /* VariableStatement */); return "skip"; } break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // Check modifiers of property declaration if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { @@ -107393,19 +110620,19 @@ var ts; return "skip"; } break; - case 160 /* Parameter */: + case 161 /* Parameter */: // Check modifiers of parameter declaration if (nodes === parent.modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 223 /* ExpressionWithTypeArguments */: - case 274 /* JsxSelfClosingElement */: - case 275 /* JsxOpeningElement */: - case 205 /* TaggedTemplateExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 224 /* ExpressionWithTypeArguments */: + case 275 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 206 /* TaggedTemplateExpression */: // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files)); @@ -107430,6 +110657,7 @@ var ts; case 142 /* ReadonlyKeyword */: case 133 /* DeclareKeyword */: case 125 /* AbstractKeyword */: + case 156 /* OverrideKeyword */: diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind))); break; // These are all legal modifiers. @@ -107733,13 +110961,13 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { - ts.tracing.push("program" /* Program */, "findSourceFile", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "findSourceFile", { fileName: fileName, isDefaultLib: isDefaultLib || undefined, fileIncludeKind: ts.FileIncludeKind[reason.kind], }); var result = findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { @@ -107998,9 +111226,9 @@ var ts; } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { - ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { // If we already found this library as a primary reference - nothing to do @@ -108071,12 +111299,14 @@ var ts; return host.getCanonicalFileName(fileName); } function processImportedModules(file) { + var _a; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var resolutions = resolveModuleNamesReusingOldState(moduleNames, file); ts.Debug.assert(resolutions.length === moduleNames.length); + var optionsForFile = (useSourceOfProjectReferenceRedirect ? (_a = getRedirectReferenceForResolution(file)) === null || _a === void 0 ? void 0 : _a.commandLine.options : undefined) || options; for (var index = 0; index < moduleNames.length; index++) { var resolution = resolutions[index]; ts.setResolvedModule(file, moduleNames[index], resolution); @@ -108099,11 +111329,11 @@ var ts; // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') // This may still end up being an untyped module -- the file won't be included but imports will be allowed. var shouldAddFile = resolvedFileName - && !getResolutionDiagnostic(options, resolution) - && !options.noResolve + && !getResolutionDiagnostic(optionsForFile, resolution) + && !optionsForFile.noResolve && index < file.imports.length && !elideImport - && !(isJsFile && !ts.getAllowJSCompilerOption(options)) + && !(isJsFile && !ts.getAllowJSCompilerOption(optionsForFile)) && (ts.isInJSFile(file.imports[index]) || !(file.imports[index].flags & 4194304 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); @@ -108306,6 +111536,9 @@ var ts; if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } + if (options.preserveConstEnums === false) { + createDiagnosticForOptionName(ts.Diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled, "preserveConstEnums", "isolatedModules"); + } var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); @@ -108336,9 +111569,10 @@ var ts; 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 + // there has to be common source directory if user specified --outdir || --rootDir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted if (options.outDir || // there is --outDir specified + options.rootDir || // there is --rootDir specified options.sourceRoot || // there is --sourceRoot specified options.mapRoot) { // there is --mapRoot specified // Precalculate and cache the common source directory @@ -108835,7 +112069,7 @@ var ts; } function handleDirectoryCouldBeSymlink(directory) { var _a; - if (!host.getResolvedProjectReferences()) + if (!host.getResolvedProjectReferences() || ts.containsIgnoredPath(directory)) return; // Because we already watch node_modules, handle symlinks in there if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart)) @@ -108852,7 +112086,7 @@ var ts; symlinkCache.setSymlinkedDirectory(directoryPath, false); return; } - symlinkCache.setSymlinkedDirectory(directoryPath, { + symlinkCache.setSymlinkedDirectory(directory, { real: ts.ensureTrailingDirectorySeparator(real), realPath: realPath }); @@ -109128,12 +112362,15 @@ var ts; // From ambient modules for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { var ambientModule = _g[_f]; - if (ambientModule.declarations.length > 1) { + if (ambientModule.declarations && ambientModule.declarations.length > 1) { addReferenceFromAmbientModule(ambientModule); } } return referencedFiles; function addReferenceFromAmbientModule(symbol) { + if (!symbol.declarations) { + return; + } // Add any file other than our own as reference for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; @@ -109158,7 +112395,7 @@ var ts; /** * Creates the state of file references and signature for the new program from oldState if it is safe */ - function create(newProgram, getCanonicalFileName, oldState) { + function create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { var fileInfos = new ts.Map(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? new ts.Map() : undefined; var exportedModulesMap = referencedMap ? new ts.Map() : undefined; @@ -109184,13 +112421,14 @@ var ts; } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) }); + fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined }); } return { fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState }; } BuilderState.create = create; @@ -109212,6 +112450,7 @@ var ts; referencedMap: state.referencedMap && new ts.Map(state.referencedMap), exportedModulesMap: state.exportedModulesMap && new ts.Map(state.exportedModulesMap), hasCalledUpdateShapeSignature: new ts.Set(state.hasCalledUpdateShapeSignature), + useFileVersionAsSignature: state.useFileVersionAsSignature, }; } BuilderState.clone = clone; @@ -109267,23 +112506,12 @@ var ts; return ts.Debug.fail(); var prevSignature = info.signature; var latestSignature; - if (sourceFile.isDeclarationFile) { - latestSignature = sourceFile.version; - if (exportedModulesMapCache && latestSignature !== prevSignature) { - // All the references in this file are exported - var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined; - exportedModulesMapCache.set(sourceFile.resolvedPath, references || false); - } - } - else { + if (!sourceFile.isDeclarationFile && !state.useFileVersionAsSignature) { var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken, /*customTransformers*/ undefined, /*forceDtsEmit*/ true); - var firstDts_1 = emitOutput_1.outputFiles && - programOfThisState.getCompilerOptions().declarationMap ? - emitOutput_1.outputFiles.length > 1 ? emitOutput_1.outputFiles[1] : undefined : - emitOutput_1.outputFiles.length > 0 ? emitOutput_1.outputFiles[0] : undefined; + var firstDts_1 = ts.firstOrUndefined(emitOutput_1.outputFiles); if (firstDts_1) { ts.Debug.assert(ts.fileExtensionIs(firstDts_1.name, ".d.ts" /* Dts */), "File extension for signature expected to be dts", function () { return "Found: " + ts.getAnyExtensionFromPath(firstDts_1.name) + " for " + firstDts_1.name + ":: All output files: " + JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; })); }); latestSignature = (computeHash || ts.generateDjb2Hash)(firstDts_1.text); @@ -109291,12 +112519,18 @@ var ts; updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache); } } - else { - latestSignature = prevSignature; // TODO: GH#18217 + } + // Default is to use file version as signature + if (latestSignature === undefined) { + latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + // All the references in this file are exported + var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined; + exportedModulesMapCache.set(sourceFile.resolvedPath, references || false); } } cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature); - return !prevSignature || latestSignature !== prevSignature; + return latestSignature !== prevSignature; } BuilderState.updateShapeSignature = updateShapeSignature; /** @@ -109416,7 +112650,7 @@ var ts; */ function isFileAffectingGlobalScope(sourceFile) { return containsGlobalScopeAugmentation(sourceFile) || - !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + !ts.isExternalOrCommonJsModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); } /** * Gets all files of the program excluding the default library file @@ -109504,8 +112738,8 @@ var ts; /** * Create the state so that we can iterate on changedFiles/affected files */ - function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { - var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); state.compilerOptions = compilerOptions; @@ -109743,6 +112977,7 @@ var ts; * This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change */ function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash) { + var _a; removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath); // If affected files is everything except default library, then nothing more to do if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) { @@ -109756,8 +112991,15 @@ var ts; removeSemanticDiagnosticsOf(state, f.resolvedPath); }); } + // When a change affects the global scope, all files are considered to be affected without updating their signature + // That means when affected file is handled, its signature can be out of date + // To avoid this, ensure that we update the signature for any affected file in this scenario. + ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap); return; } + else { + ts.Debug.assert(state.hasCalledUpdateShapeSignature.has(affectedFile.resolvedPath) || ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.has(affectedFile.resolvedPath)), "Signature not updated for affected file: " + affectedFile.fileName); + } if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) { forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); }); } @@ -109969,83 +113211,116 @@ var ts; return undefined; var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory(); var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); - var fileInfos = {}; - state.fileInfos.forEach(function (value, key) { + var fileNames = []; + var fileNameToFileId = new ts.Map(); + var fileIdsList; + var fileNamesToFileIdListId; + var fileInfos = ts.arrayFrom(state.fileInfos.entries(), function (_a) { + var key = _a[0], value = _a[1]; + // Ensure fileId + var fileId = toFileId(key); + ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope }; + var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + return value.version === actualSignature ? + value.affectsGlobalScope ? + { version: value.version, signature: undefined, affectsGlobalScope: true } : + value.version : + actualSignature !== undefined ? + signature === undefined ? + value : + { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope } : + { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope }; }); - var result = { - fileInfos: fileInfos, - options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath) - }; + var referencedMap; if (state.referencedMap) { - var referencedMap = {}; - for (var _i = 0, _a = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { - var key = _a[_i]; - referencedMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.referencedMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); - } - result.referencedMap = referencedMap; + referencedMap = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive).map(function (key) { return [ + toFileId(key), + toFileIdListId(state.referencedMap.get(key)) + ]; }); } + var exportedModulesMap; if (state.exportedModulesMap) { - var exportedModulesMap = {}; - for (var _b = 0, _c = ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) { - var key = _c[_b]; + exportedModulesMap = ts.mapDefined(ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive), function (key) { var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key); // Not in temporary cache, use existing value if (newValue === undefined) - exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.exportedModulesMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); + return [toFileId(key), toFileIdListId(state.exportedModulesMap.get(key))]; // Value in cache and has updated value map, use that else if (newValue) - exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); - } - result.exportedModulesMap = exportedModulesMap; + return [toFileId(key), toFileIdListId(newValue)]; + }); } + var semanticDiagnosticsPerFile; if (state.semanticDiagnosticsPerFile) { - var semanticDiagnosticsPerFile = []; - for (var _d = 0, _e = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) { - var key = _e[_d]; + for (var _i = 0, _a = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var key = _a[_i]; var value = state.semanticDiagnosticsPerFile.get(key); - semanticDiagnosticsPerFile.push(value.length ? + (semanticDiagnosticsPerFile || (semanticDiagnosticsPerFile = [])).push(value.length ? [ - relativeToBuildInfo(key), + toFileId(key), state.hasReusableDiagnostic ? value : convertToReusableDiagnostics(value, relativeToBuildInfo) ] : - relativeToBuildInfo(key)); + toFileId(key)); } - result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile; } + var affectedFilesPendingEmit; if (state.affectedFilesPendingEmit) { - var affectedFilesPendingEmit = []; var seenFiles = new ts.Set(); - for (var _f = 0, _g = state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(ts.compareStringsCaseSensitive); _f < _g.length; _f++) { - var path = _g[_f]; + for (var _b = 0, _c = state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) { + var path = _c[_b]; if (ts.tryAddToSet(seenFiles, path)) { - affectedFilesPendingEmit.push([relativeToBuildInfo(path), state.affectedFilesPendingEmitKind.get(path)]); + (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push([toFileId(path), state.affectedFilesPendingEmitKind.get(path)]); } } - result.affectedFilesPendingEmit = affectedFilesPendingEmit; } - return result; + return { + fileNames: fileNames, + fileInfos: fileInfos, + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + fileIdsList: fileIdsList, + referencedMap: referencedMap, + exportedModulesMap: exportedModulesMap, + semanticDiagnosticsPerFile: semanticDiagnosticsPerFile, + affectedFilesPendingEmit: affectedFilesPendingEmit, + }; function relativeToBuildInfoEnsuringAbsolutePath(path) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory)); } function relativeToBuildInfo(path) { return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName)); } + function toFileId(path) { + var fileId = fileNameToFileId.get(path); + if (fileId === undefined) { + fileNames.push(relativeToBuildInfo(path)); + fileNameToFileId.set(path, fileId = fileNames.length); + } + return fileId; + } + function toFileIdListId(set) { + var fileIds = ts.arrayFrom(set.keys(), toFileId).sort(ts.compareValues); + var key = fileIds.join(); + var fileIdListId = fileNamesToFileIdListId === null || fileNamesToFileIdListId === void 0 ? void 0 : fileNamesToFileIdListId.get(key); + if (fileIdListId === undefined) { + (fileIdsList || (fileIdsList = [])).push(fileIds); + (fileNamesToFileIdListId || (fileNamesToFileIdListId = new ts.Map())).set(key, fileIdListId = fileIdsList.length); + } + return fileIdListId; + } } - function convertToReusableCompilerOptions(options, relativeToBuildInfo) { - var result = {}; + function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { + var result; var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo); + for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var name = _a[_i]; + var optionInfo = optionsNameMap.get(name.toLowerCase()); + if ((optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || name === "skipLibCheck" || name === "skipDefaultLibCheck") { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); } } - if (result.configFilePath) { - result.configFilePath = relativeToBuildInfo(result.configFilePath); - } return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { @@ -110137,7 +113412,7 @@ var ts; * Computing hash to for signature verification */ var computeHash = ts.maybeBind(host, host.createHash); - var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState, host.disableUseFileVersionAsSignature); var backupState; newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); }; // To ensure that we arent storing any references to old program or new program without state @@ -110361,37 +113636,31 @@ var ts; state.affectedFilesPendingEmitIndex = 0; } } - function getMapOfReferencedSet(mapLike, toPath) { - if (!mapLike) - return undefined; - var map = new ts.Map(); - // Copies keys/values from template. Note that for..in will not throw if - // template is undefined, and instead will just exit the loop. - for (var key in mapLike) { - if (ts.hasProperty(mapLike, key)) { - map.set(toPath(key), new ts.Set(mapLike[key].map(toPath))); - } - } - return map; + function toBuilderStateFileInfo(fileInfo) { + return ts.isString(fileInfo) ? + { version: fileInfo, signature: fileInfo, affectsGlobalScope: undefined } : + ts.isString(fileInfo.signature) ? + fileInfo : + { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope }; } + ts.toBuilderStateFileInfo = toBuilderStateFileInfo; function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { + var _a; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var filePaths = program.fileNames.map(toPath); + var filePathsSetList = (_a = program.fileIdsList) === null || _a === void 0 ? void 0 : _a.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); var fileInfos = new ts.Map(); - for (var key in program.fileInfos) { - if (ts.hasProperty(program.fileInfos, key)) { - fileInfos.set(toPath(key), program.fileInfos[key]); - } - } + program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); var state = { fileInfos: fileInfos, - compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), - referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), - exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), - semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + referencedMap: toMapOfReferencedSet(program.referencedMap), + exportedModulesMap: toMapOfReferencedSet(program.exportedModulesMap), + semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), hasReusableDiagnostic: true, - affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }), - affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }, function (value) { return value[1]; }), + affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), + affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, }; return { @@ -110424,6 +113693,15 @@ var ts; function toAbsolutePath(path) { return ts.getNormalizedAbsolutePath(path, buildInfoDirectory); } + function toFilePath(fileId) { + return filePaths[fileId - 1]; + } + function toFilePathsSet(fileIdsListId) { + return filePathsSetList[fileIdsListId - 1]; + } + function toMapOfReferencedSet(referenceMap) { + return referenceMap && ts.arrayToMap(referenceMap, function (value) { return toFilePath(value[0]); }, function (value) { return toFilePathsSet(value[1]); }); + } } ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { @@ -110536,9 +113814,9 @@ var ts; var resolutionsWithFailedLookups = []; var resolvedFileToResolution = ts.createMultiMap(); var hasChangedAutomaticTypeDirectiveNames = false; - var failedLookupChecks = []; - var startsWithPathChecks = []; - var isInDirectoryChecks = []; + var failedLookupChecks; + var startsWithPathChecks; + var isInDirectoryChecks; var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. @@ -110547,9 +113825,12 @@ var ts; var resolvedModuleNames = new ts.Map(); var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); - var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var moduleResolutionCache = ts.createModuleResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, perDirectoryResolvedModuleNames, nonRelativeModuleNameCache); var resolvedTypeReferenceDirectives = new ts.Map(); var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); + var typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, moduleResolutionCache.getPackageJsonInfoCache(), perDirectoryResolvedTypeReferenceDirectives); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -110581,6 +113862,7 @@ var ts; invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, createHasInvalidatedResolution: createHasInvalidatedResolution, + isFileWithInvalidatedNonRelativeUnresolvedImports: isFileWithInvalidatedNonRelativeUnresolvedImports, updateTypeRootsWatch: updateTypeRootsWatch, closeTypeRootsWatch: closeTypeRootsWatch, clear: clear @@ -110606,9 +113888,9 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) clearPerDirectoryResolutions(); @@ -110644,9 +113926,8 @@ var ts; isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { - perDirectoryResolvedModuleNames.clear(); - nonRelativeModuleNameCache.clear(); - perDirectoryResolvedTypeReferenceDirectives.clear(); + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } @@ -110673,7 +113954,7 @@ var ts; if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results - var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; if (resolvedModule) { // Modify existing resolution so its saved in the directory cache as well primaryResult.resolvedModule = resolvedModule; @@ -110684,6 +113965,9 @@ var ts; // Default return the result from the first pass return primaryResult; } + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + return ts.resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache); + } function resolveNamesWithLocalCache(_a) { var _b; var names = _a.names, containingFile = _a.containingFile, redirectedReference = _a.redirectedReference, cache = _a.cache, perDirectoryCacheWithRedirects = _a.perDirectoryCacheWithRedirects, loader = _a.loader, getResolutionWithResolvedFileName = _a.getResolutionWithResolvedFileName, shouldRetryResolution = _a.shouldRetryResolution, reusedNames = _a.reusedNames, logChanges = _a.logChanges; @@ -110771,7 +114055,7 @@ var ts; redirectedReference: redirectedReference, cache: resolvedTypeReferenceDirectives, perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives, - loader: ts.resolveTypeReferenceDirective, + loader: resolveTypeReferenceDirective, getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective, shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, }); @@ -111046,7 +114330,7 @@ var ts; if (isCreatingWatchedDirectory) { // Watching directory is created // Invalidate any resolution has failed lookup in this directory - isInDirectoryChecks.push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); } else { // If something to do with folder/file starting with "." in node_modules folder, skip it @@ -111064,8 +114348,8 @@ var ts; if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory - failedLookupChecks.push(fileOrDirectoryPath); - startsWithPathChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { @@ -111076,27 +114360,33 @@ var ts; return false; } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created - failedLookupChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + // If the invalidated file is from a node_modules package, invalidate everything else + // in the package since we might not get notifications for other files in the package. + // This hardens our logic against unreliable file watchers. + var packagePath = ts.parseNodeModuleFromPath(fileOrDirectoryPath); + if (packagePath) + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks.length && !startsWithPathChecks.length && !isInDirectoryChecks.length) { + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { return false; } var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { return resolution.failedLookupLocations.some(function (location) { var locationPath = resolutionHost.toPath(location); return ts.contains(failedLookupChecks, locationPath) || - startsWithPathChecks.some(function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath); }) || - isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); }); + ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || + (isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); })); }); } function closeTypeRootsWatch() { @@ -111247,6 +114537,9 @@ var ts; return [ambient]; var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); + if (!moduleSourceFile) { + return []; + } var modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host); var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); var existingSpecifier = ts.forEach(modulePaths, function (modulePath) { return ts.forEach(host.getFileIncludeReasons().get(ts.toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)), function (reason) { @@ -111317,7 +114610,7 @@ var ts; if (!baseUrl && !paths || relativePreference === 0 /* Relative */) { return relativePath; } - var baseDirectory = ts.getPathsBasePath(compilerOptions, host) || baseUrl; + var baseDirectory = ts.getNormalizedAbsolutePath(ts.getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory()); var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName); if (!relativeToBaseUrl) { return relativePath; @@ -111332,7 +114625,9 @@ var ts; return nonRelative; } if (relativePreference === 3 /* ExternalNonRelative */) { - var projectDirectory = host.getCurrentDirectory(); + var projectDirectory = compilerOptions.configFilePath ? + ts.toPath(ts.getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) : + info.getCanonicalFileName(host.getCurrentDirectory()); var modulePath = ts.toPath(moduleFileName, projectDirectory, getCanonicalFileName); var sourceIsInternal = ts.startsWith(sourceDirectory, projectDirectory); var targetIsInternal = ts.startsWith(modulePath, projectDirectory); @@ -111384,12 +114679,8 @@ var ts; return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined; }) || false; } - function numberOfDirectorySeparators(str) { - var match = str.match(/\//g); - return match ? match.length : 0; - } function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) { - return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareValues(numberOfDirectorySeparators(a.path), numberOfDirectorySeparators(b.path)); + return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareNumberOfDirectorySeparators(a.path, b.path); } function getNearestAncestorDirectoryWithPackageJson(host, fileName) { if (host.getNearestAncestorDirectoryWithPackageJson) { @@ -111403,40 +114694,49 @@ var ts; var getCanonicalFileName = ts.hostGetCanonicalFileName(host); var cwd = host.getCurrentDirectory(); var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined; - var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray; + var importedPath = ts.toPath(importedFileName, cwd, getCanonicalFileName); + var redirects = host.redirectTargetsMap.get(importedPath) || ts.emptyArray; var importedFileNames = __spreadArray(__spreadArray(__spreadArray([], (referenceRedirect ? [referenceRedirect] : ts.emptyArray)), [importedFileName]), redirects); var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + var shouldFilterIgnoredPaths = !ts.every(targets, ts.containsIgnoredPath); if (!preferSymlinks) { - var result_15 = ts.forEach(targets, function (p) { return cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + // Symlinks inside ignored paths are already filtered out of the symlink cache, + // so we only need to remove them from the realpath filenames. + var result_16 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_16) + return result_16; } var links = host.getSymlinkCache ? host.getSymlinkCache() : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd); - var symlinkedDirectories = links.getSymlinkedDirectories(); - var useCaseSensitiveFileNames = !host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames(); - var result = symlinkedDirectories && ts.forEachEntry(symlinkedDirectories, function (resolved, path) { - if (resolved === false) - return undefined; - if (ts.startsWithDirectory(importingFileName, resolved.realPath, getCanonicalFileName)) { - return undefined; // Don't want to a package to globally import from itself + var symlinkedDirectories = links.getSymlinkedDirectoriesByRealpath(); + var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); + var result = symlinkedDirectories && ts.forEachAncestorDirectory(ts.getDirectoryPath(fullImportedFileName), function (realPathDirectory) { + var symlinkDirectories = symlinkedDirectories.get(ts.ensureTrailingDirectorySeparator(ts.toPath(realPathDirectory, cwd, getCanonicalFileName))); + if (!symlinkDirectories) + return undefined; // Continue to ancestor directory + // Don't want to a package to globally import from itself (importNameCodeFix_symlink_own_package.ts) + if (ts.startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) { + return false; // Stop search, each ancestor directory will also hit this condition } return ts.forEach(targets, function (target) { - if (!ts.containsPath(resolved.real, target, !useCaseSensitiveFileNames)) { + if (!ts.startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) { return; } - var relative = ts.getRelativePathFromDirectory(resolved.real, target, getCanonicalFileName); - var option = ts.resolvePath(path, relative); - if (!host.fileExists || host.fileExists(option)) { - var result_16 = cb(option, target === referenceRedirect); - if (result_16) - return result_16; + var relative = ts.getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName); + for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { + var symlinkDirectory = symlinkDirectories_1[_i]; + var option = ts.resolvePath(symlinkDirectory, relative); + var result_17 = cb(option, target === referenceRedirect); + shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths + if (result_17) + return result_17; } }); }); - return result || - (preferSymlinks ? ts.forEach(targets, function (p) { return cb(p, p === referenceRedirect); }) : undefined); + return result || (preferSymlinks + ? ts.forEach(targets, function (p) { return shouldFilterIgnoredPaths && ts.containsIgnoredPath(p) ? undefined : cb(p, p === referenceRedirect); }) + : undefined); } moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule; /** @@ -111444,8 +114744,14 @@ var ts; * Symlinks will be returned first so they are preferred over the real path. */ function getAllModulePaths(importingFileName, importedFileName, host) { - var cwd = host.getCurrentDirectory(); + var _a; + var cache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + if (cache) { + var cached = cache.get(importingFileName, ts.toPath(importedFileName, host.getCurrentDirectory(), getCanonicalFileName)); + if (typeof cached === "object") + return cached; + } var allFileNames = new ts.Map(); var importedFileFromNodeModules = false; forEachFileNameOfModule(importingFileName, importedFileName, host, @@ -111457,7 +114763,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_24 = function (directory) { + var _loop_26 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -111480,10 +114786,10 @@ var ts; out_directory_1 = directory; }; var out_directory_1; - for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_7 = _loop_24(directory); + for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { + var state_9 = _loop_26(directory); directory = out_directory_1; - if (state_7 === "break") + if (state_9 === "break") break; } if (allFileNames.size) { @@ -111492,10 +114798,14 @@ var ts; remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators); sortedPaths.push.apply(sortedPaths, remainingPaths); } + if (cache) { + cache.set(importingFileName, ts.toPath(importedFileName, host.getCurrentDirectory(), getCanonicalFileName), sortedPaths); + } return sortedPaths; } function tryGetModuleNameFromAmbientModule(moduleSymbol, checker) { - var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); + var _a; + var decl = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { return decl.name.text; } @@ -111551,7 +114861,7 @@ var ts; ts.startsWith(relativeToBaseUrl, prefix) && ts.endsWith(relativeToBaseUrl, suffix) || !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); return key.replace("*", matchedStar); } } @@ -111855,10 +115165,10 @@ var ts; } ts.createWatchStatusReporter = createWatchStatusReporter; /** Parses config file using System interface */ - function parseConfigFileWithSystem(configFileName, optionsToExtend, watchOptionsToExtend, system, reportDiagnostic) { + function parseConfigFileWithSystem(configFileName, optionsToExtend, extendedConfigCache, watchOptionsToExtend, system, reportDiagnostic) { var host = system; host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; - var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, /*extendedConfigCache*/ undefined, watchOptionsToExtend); + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend); host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; } @@ -112126,7 +115436,10 @@ var ts; MissingFile: "Missing file", WildcardDirectory: "Wild card directory", FailedLookupLocations: "Failed Lookup Locations", - TypeRoots: "Type roots" + TypeRoots: "Type roots", + ConfigFileOfReferencedProject: "Config file of referened project", + ExtendedConfigOfReferencedProject: "Extended config file of referenced project", + WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project", }; function createWatchFactory(host, options) { var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; @@ -112173,6 +115486,7 @@ var ts; getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }), createHash: ts.maybeBind(host, host.createHash), readDirectory: ts.maybeBind(host, host.readDirectory), + disableUseFileVersionAsSignature: host.disableUseFileVersionAsSignature, }; function writeFile(fileName, text, writeByteOrderMark, onError) { try { @@ -112230,7 +115544,8 @@ var ts; createDirectory: function (path) { return system.createDirectory(path); }, writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, createHash: ts.maybeBind(system, system.createHash), - createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram + createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, + disableUseFileVersionAsSignature: system.disableUseFileVersionAsSignature, }; } ts.createProgramHost = createProgramHost; @@ -112318,6 +115633,7 @@ var ts; if (system === void 0) { system = ts.sys; } var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system); host.createHash = ts.maybeBind(system, system.createHash); + host.disableUseFileVersionAsSignature = system.disableUseFileVersionAsSignature; ts.setGetSourceFileAsHashVersioned(host, system); ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); }); return host; @@ -112361,11 +115677,13 @@ var ts; function createWatchProgram(host) { var builderProgram; var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc - var extendedConfigFilesMap; // Map of file watchers for the extended config files var missingFilesMap; // Map of file watchers for the missing files var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file var timerToUpdateProgram; // timer callback to recompile the program var timerToInvalidateFailedLookupResolutions; // timer callback to invalidate resolutions for changes in failed lookup locations + var parsedConfigs; // Parsed commandline and watching cached for referenced projects + var sharedExtendedConfigFileWatchers; // Map of file watchers for extended files, shared between different referenced projects + var extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info var missingFilePathsRequestedForRelease; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations @@ -112415,6 +115733,7 @@ var ts; compilerHost.getNewLine = function () { return newLine; }; compilerHost.fileExists = fileExists; compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile; + compilerHost.onReleaseParsedCommandLine = onReleaseParsedCommandLine; // Members for ResolutionCacheHost compilerHost.toPath = toPath; compilerHost.getCompilationSettings = function () { return compilerOptions; }; @@ -112428,6 +115747,7 @@ var ts; compilerHost.fileIsOpen = ts.returnFalse; compilerHost.getCurrentProgram = getCurrentProgram; compilerHost.writeLog = writeLog; + compilerHost.getParsedCommandLine = getParsedCommandLine; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : @@ -112458,7 +115778,8 @@ var ts; // Update the wild card directory watch watchConfigFileWildCardDirectories(); // Update extended config file watch - watchExtendedConfigFiles(); + if (configFileName) + updateExtendedConfigFilesWatches(toPath(configFileName), compilerOptions, watchOptions, ts.WatchType.ExtendedConfigFile); return configFileName ? { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } : { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close }; @@ -112475,9 +115796,11 @@ var ts; configFileWatcher.close(); configFileWatcher = undefined; } - if (extendedConfigFilesMap) { - ts.clearMap(extendedConfigFilesMap, ts.closeFileWatcher); - extendedConfigFilesMap = undefined; + extendedConfigCache === null || extendedConfigCache === void 0 ? void 0 : extendedConfigCache.clear(); + extendedConfigCache = undefined; + if (sharedExtendedConfigFileWatchers) { + ts.clearMap(sharedExtendedConfigFileWatchers, ts.closeFileWatcherOf); + sharedExtendedConfigFileWatchers = undefined; } if (watchedWildcardDirectories) { ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); @@ -112487,6 +115810,17 @@ var ts; ts.clearMap(missingFilesMap, ts.closeFileWatcher); missingFilesMap = undefined; } + if (parsedConfigs) { + ts.clearMap(parsedConfigs, function (config) { + var _a; + (_a = config.watcher) === null || _a === void 0 ? void 0 : _a.close(); + config.watcher = undefined; + if (config.watchedDirectories) + ts.clearMap(config.watchedDirectories, ts.closeFileWatcherOf); + config.watchedDirectories = undefined; + }); + parsedConfigs = undefined; + } } function getCurrentBuilderProgram() { return builderProgram; @@ -112506,7 +115840,7 @@ 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, projectReferences)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; @@ -112525,6 +115859,8 @@ var ts; writeLog("CreatingProgramWith::"); writeLog(" roots: " + JSON.stringify(rootFileNames)); writeLog(" options: " + JSON.stringify(compilerOptions)); + if (projectReferences) + writeLog(" projectReferences: " + JSON.stringify(projectReferences)); var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; @@ -112747,10 +116083,10 @@ var ts; // Update the wild card directory watch watchConfigFileWildCardDirectories(); // Update extended config file watch - watchExtendedConfigFiles(); + updateExtendedConfigFilesWatches(toPath(configFileName), compilerOptions, watchOptions, ts.WatchType.ExtendedConfigFile); } function parseConfigFile() { - setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217 + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, extendedConfigCache || (extendedConfigCache = new ts.Map()), watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217 } function setConfigFileParsingResult(configFileParseResult) { rootFileNames = configFileParseResult.fileNames; @@ -112762,6 +116098,56 @@ var ts; canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInputFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } + function getParsedCommandLine(configFileName) { + var configPath = toPath(configFileName); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath); + if (config) { + if (!config.reloadLevel) + return config.parsedCommandLine; + // With host implementing getParsedCommandLine we cant just update file names + if (config.parsedCommandLine && config.reloadLevel === ts.ConfigFileProgramReloadLevel.Partial && !host.getParsedCommandLine) { + writeLog("Reloading new file names and options"); + var fileNames = ts.getFileNamesFromConfigSpecs(config.parsedCommandLine.options.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost); + config.parsedCommandLine = __assign(__assign({}, config.parsedCommandLine), { fileNames: fileNames }); + config.reloadLevel = undefined; + return config.parsedCommandLine; + } + } + writeLog("Loading config file: " + configFileName); + var parsedCommandLine = host.getParsedCommandLine ? + host.getParsedCommandLine(configFileName) : + getParsedCommandLineFromConfigFileHost(configFileName); + if (config) { + config.parsedCommandLine = parsedCommandLine; + config.reloadLevel = undefined; + } + else { + (parsedConfigs || (parsedConfigs = new ts.Map())).set(configPath, config = { parsedCommandLine: parsedCommandLine }); + } + watchReferencedProject(configFileName, configPath, config); + return parsedCommandLine; + } + function getParsedCommandLineFromConfigFileHost(configFileName) { + // Ignore the file absent errors + var onUnRecoverableConfigFileDiagnostic = parseConfigFileHost.onUnRecoverableConfigFileDiagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + var parsedCommandLine = ts.getParsedCommandLineOfConfigFile(configFileName, + /*optionsToExtend*/ undefined, parseConfigFileHost, extendedConfigCache || (extendedConfigCache = new ts.Map()), watchOptionsToExtend); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = onUnRecoverableConfigFileDiagnostic; + return parsedCommandLine; + } + function onReleaseParsedCommandLine(fileName) { + var _a; + var path = toPath(fileName); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(path); + if (!config) + return; + parsedConfigs.delete(path); + if (config.watchedDirectories) + ts.clearMap(config.watchedDirectories, ts.closeFileWatcherOf); + (_a = config.watcher) === null || _a === void 0 ? void 0 : _a.close(); + ts.clearSharedExtendedConfigFileWatcher(path, sharedExtendedConfigFileWatchers); + } function watchFilePath(path, file, callback, pollingInterval, options, watchType) { return watchFile(file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options, watchType); } @@ -112771,7 +116157,6 @@ var ts; if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) { resolutionCache.invalidateResolutionOfFile(path); } - resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); nextSourceFileVersion(path); // Update the program scheduleProgramUpdate(); @@ -112782,7 +116167,10 @@ var ts; } } function watchMissingFilePath(missingFilePath) { - return watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); + // If watching missing referenced config file, we are already watching it so no need for separate watcher + return (parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.has(missingFilePath)) ? + ts.noopFileWatcher : + watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); @@ -112819,10 +116207,11 @@ var ts; configFileName: configFileName, extraFileExtensions: extraFileExtensions, options: compilerOptions, - program: getCurrentBuilderProgram(), + program: getCurrentBuilderProgram() || rootFileNames, currentDirectory: currentDirectory, useCaseSensitiveFileNames: useCaseSensitiveFileNames, - writeLog: writeLog + writeLog: writeLog, + toPath: toPath, })) return; // Reload is pending, do the reload @@ -112833,18 +116222,87 @@ var ts; } }, flags, watchOptions, ts.WatchType.WildcardDirectory); } - function watchExtendedConfigFiles() { - var _a; - // Update the extended config files watcher - ts.mutateMap(extendedConfigFilesMap || (extendedConfigFilesMap = new ts.Map()), ts.arrayToMap(((_a = compilerOptions.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath), { - // Watch the extended config files - createNewValue: watchExtendedConfigFile, - // Config files that are no longer extended should no longer be watched. - onDeleteValue: ts.closeFileWatcher - }); + function updateExtendedConfigFilesWatches(forProjectPath, options, watchOptions, watchType) { + ts.updateSharedExtendedConfigFileWatcher(forProjectPath, options, sharedExtendedConfigFileWatchers || (sharedExtendedConfigFileWatchers = new ts.Map()), function (extendedConfigFileName, extendedConfigFilePath) { return watchFile(extendedConfigFileName, function (_fileName, eventKind) { + var _a; + updateCachedSystemWithFile(extendedConfigFileName, extendedConfigFilePath, eventKind); + // Update extended config cache + if (extendedConfigCache) + ts.cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath); + // Update projects + var projects = (_a = sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects; + // If there are no referenced projects this extended config file watcher depend on ignore + if (!(projects === null || projects === void 0 ? void 0 : projects.size)) + return; + projects.forEach(function (projectPath) { + if (toPath(configFileName) === projectPath) { + // If this is the config file of the project, reload completely + reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + } + else { + // Reload config for the referenced projects and remove the resolutions from referenced projects since the config file changed + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(projectPath); + if (config) + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(projectPath); + } + scheduleProgramUpdate(); + }); + }, ts.PollingInterval.High, watchOptions, watchType); }, toPath); } - function watchExtendedConfigFile(extendedConfigFile) { - return watchFile(extendedConfigFile, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ExtendedConfigFile); + function watchReferencedProject(configFileName, configPath, commandLine) { + var _a, _b, _c, _d, _e; + // Watch file + commandLine.watcher || (commandLine.watcher = watchFile(configFileName, function (_fileName, eventKind) { + updateCachedSystemWithFile(configFileName, configPath, eventKind); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath); + if (config) + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(configPath); + scheduleProgramUpdate(); + }, ts.PollingInterval.High, ((_a = commandLine.parsedCommandLine) === null || _a === void 0 ? void 0 : _a.watchOptions) || watchOptions, ts.WatchType.ConfigFileOfReferencedProject)); + // Watch Wild card + if ((_b = commandLine.parsedCommandLine) === null || _b === void 0 ? void 0 : _b.wildcardDirectories) { + ts.updateWatchingWildcardDirectories(commandLine.watchedDirectories || (commandLine.watchedDirectories = new ts.Map()), new ts.Map(ts.getEntries((_c = commandLine.parsedCommandLine) === null || _c === void 0 ? void 0 : _c.wildcardDirectories)), function (directory, flags) { + var _a; + return watchDirectory(directory, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + // Since the file existence changed, update the sourceFiles cache + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + nextSourceFileVersion(fileOrDirectoryPath); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath); + if (!(config === null || config === void 0 ? void 0 : config.parsedCommandLine)) + return; + if (ts.isIgnoredFileFromWildCardWatching({ + watchedDirPath: toPath(directory), + fileOrDirectory: fileOrDirectory, + fileOrDirectoryPath: fileOrDirectoryPath, + configFileName: configFileName, + options: config.parsedCommandLine.options, + program: config.parsedCommandLine.fileNames, + currentDirectory: currentDirectory, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + writeLog: writeLog, + toPath: toPath, + })) + return; + // Reload is pending, do the reload + if (config.reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) { + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + // Schedule Update the program + scheduleProgramUpdate(); + } + }, flags, ((_a = commandLine.parsedCommandLine) === null || _a === void 0 ? void 0 : _a.watchOptions) || watchOptions, ts.WatchType.WildcardDirectoryOfReferencedProject); + }); + } + else if (commandLine.watchedDirectories) { + ts.clearMap(commandLine.watchedDirectories, ts.closeFileWatcherOf); + commandLine.watchedDirectories = undefined; + } + // Watch extended config files + updateExtendedConfigFilesWatches(configPath, (_d = commandLine.parsedCommandLine) === null || _d === void 0 ? void 0 : _d.options, ((_e = commandLine.parsedCommandLine) === null || _e === void 0 ? void 0 : _e.watchOptions) || watchOptions, ts.WatchType.ExtendedConfigOfReferencedProject); } } ts.createWatchProgram = createWatchProgram; @@ -113004,12 +116462,19 @@ var ts; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined; + var typeReferenceDirectiveResolutionCache = !compilerHost.resolveTypeReferenceDirectives ? ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()) : undefined; if (!compilerHost.resolveModuleNames) { var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; }; compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3); }; } + if (!compilerHost.resolveTypeReferenceDirectives) { + var loader_4 = function (moduleName, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(moduleName, containingFile, state.projectCompilerOptions, compilerHost, redirectedReference, state.typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return ts.loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_4); + }; + } var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -113034,6 +116499,7 @@ var ts; projectErrorsReported: new ts.Map(), compilerHost: compilerHost, moduleResolutionCache: moduleResolutionCache, + typeReferenceDirectiveResolutionCache: typeReferenceDirectiveResolutionCache, // Mutable state buildOrder: undefined, readFileWithCache: function (f) { return host.readFile(f); }, @@ -113072,6 +116538,10 @@ var ts; function isParsedCommandLine(entry) { return !!entry.options; } + function getCachedParsedConfigFile(state, configFilePath) { + var value = state.configFileCache.get(configFilePath); + return value && isParsedCommandLine(value) ? value : undefined; + } function parseConfigFile(state, configFileName, configFilePath) { var configFileCache = state.configFileCache; var value = configFileCache.get(configFilePath); @@ -113217,7 +116687,7 @@ var ts; function disableCache(state) { if (!state.cache) return; - var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache; + var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache, typeReferenceDirectiveResolutionCache = state.typeReferenceDirectiveResolutionCache; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; host.directoryExists = cache.originalDirectoryExists; @@ -113226,10 +116696,8 @@ var ts; compilerHost.getSourceFile = cache.originalGetSourceFile; state.readFileWithCache = cache.originalReadFileWithCache; extendedConfigCache.clear(); - if (moduleResolutionCache) { - moduleResolutionCache.directoryToModuleNameMap.clear(); - moduleResolutionCache.moduleNameToDirectoryMap.clear(); - } + moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache === null || typeReferenceDirectiveResolutionCache === void 0 ? void 0 : typeReferenceDirectiveResolutionCache.clear(); state.cache = undefined; } function clearProjectStatus(state, resolved) { @@ -113396,6 +116864,7 @@ var ts; return withProgramOrUndefined(action) || ts.emptyArray; } function createProgram() { + var _a, _b; ts.Debug.assert(program === undefined); if (state.options.dry) { reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project); @@ -113415,7 +116884,8 @@ var ts; var host = state.host, compilerHost = state.compilerHost; state.projectCompilerOptions = config.options; // Update module resolution cache if needed - updateModuleResolutionCache(state, project, config); + (_a = state.moduleResolutionCache) === null || _a === void 0 ? void 0 : _a.update(config.options); + (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options); // Create program program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences); if (state.watch) { @@ -113590,7 +117060,7 @@ var ts; emitBundle(writeFile, customTransformers); break; case BuildStep.BuildInvalidatedProjectOfBundle: - ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken); + ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken, writeFile, customTransformers); step = BuildStep.Done; break; case BuildStep.QueueReferencingProjects: @@ -113732,34 +117202,9 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } - function updateModuleResolutionCache(state, proj, config) { - if (!state.moduleResolutionCache) - return; - // Update module resolution cache if needed - var moduleResolutionCache = state.moduleResolutionCache; - var projPath = toPath(state, proj); - if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) { - // The own map will be for projectCompilerOptions - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0); - moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap); - moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap); - } - else { - // Set correct own map - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0); - var ref = { - sourceFile: config.options.configFile, - commandLine: config - }; - moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); - } - moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options); - } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { // Check tsconfig time - var tsconfigTime = state.host.getModifiedTime(configFile) || ts.missingFileModifiedTime; + var tsconfigTime = ts.getModifiedTime(state.host, configFile); if (oldestOutputFileTime < tsconfigTime) { return { type: ts.UpToDateStatusType.OutOfDateWithSelf, @@ -113769,6 +117214,7 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { + var force = !!state.options.force; var newestInputFileName = undefined; var newestInputFileTime = minimumDate; var host = state.host; @@ -113781,10 +117227,13 @@ var ts; reason: inputFile + " does not exist" }; } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; + if (!force) { + var inputTime = ts.getModifiedTime(host, inputFile); + host.getModifiedTime(inputFile); + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } } // Container if no files are specified in the project @@ -113803,36 +117252,38 @@ var ts; var missingOutputFileName; var newestDeclarationFileContentChangedTime = minimumDate; var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { - var output = outputs_1[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = 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 outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + if (!force) { + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = ts.getModifiedTime(host, output); + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var outputModifiedTime = ts.getModifiedTime(host, output); + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } } } var pseudoUpToDate = false; @@ -113868,7 +117319,8 @@ var ts; }; } // Check oldest output file name only if there is no missing output file name - if (!missingOutputFileName) { + // (a check we will have skipped if this is a forced build) + if (!force && !missingOutputFileName) { // If the upstream project's newest file is older than our oldest output, we // can't be out of date because of it if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { @@ -113914,7 +117366,7 @@ var ts; if (extendedConfigStatus) return extendedConfigStatus; } - if (!state.buildInfoChecked.has(resolvedPath)) { + if (!force && !state.buildInfoChecked.has(resolvedPath)) { state.buildInfoChecked.set(resolvedPath, true); var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); if (buildInfoPath) { @@ -113974,7 +117426,7 @@ var ts; reportStatus(state, verboseMessage, proj.options.configFilePath); } if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, ts.getModifiedTime(host, file)); } host.setModifiedTime(file, now); } @@ -114056,7 +117508,7 @@ var ts; } } } - function build(state, project, cancellationToken, onlyReferences) { + function build(state, project, cancellationToken, writeFile, getCustomTransformers, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); if (!buildOrder) return ts.ExitStatus.InvalidProject_OutputsSkipped; @@ -114068,7 +117520,7 @@ var ts; if (!invalidatedProject) break; reportQueue = false; - invalidatedProject.done(cancellationToken); + invalidatedProject.done(cancellationToken, writeFile, getCustomTransformers === null || getCustomTransformers === void 0 ? void 0 : getCustomTransformers(invalidatedProject.project)); if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; } @@ -114103,8 +117555,14 @@ var ts; continue; } var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames()); + if (!outputs.length) + continue; + var inputFileNames = new ts.Set(parsed.fileNames.map(function (f) { return toPath(state, f); })); for (var _a = 0, outputs_3 = outputs; _a < outputs_3.length; _a++) { var output = outputs_3[_a]; + // If output name is same as input file name, do not delete and ignore the error + if (inputFileNames.has(toPath(state, output))) + continue; if (host.fileExists(output)) { if (filesToDelete) { filesToDelete.push(output); @@ -114180,7 +117638,7 @@ var ts; }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); } function watchExtendedConfigFiles(state, resolvedPath, parsed) { - ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { + ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { var _a; return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (projectConfigFilePath) { return invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ts.ConfigFileProgramReloadLevel.Full); @@ -114191,6 +117649,7 @@ var ts; if (!state.watch) return; ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), new ts.Map(ts.getEntries(parsed.wildcardDirectories)), function (dir, flags) { return state.watchDirectory(dir, function (fileOrDirectory) { + var _a; if (ts.isIgnoredFileFromWildCardWatching({ watchedDirPath: toPath(state, dir), fileOrDirectory: fileOrDirectory, @@ -114198,9 +117657,10 @@ var ts; configFileName: resolved, currentDirectory: state.currentDirectory, options: parsed.options, - program: state.builderPrograms.get(resolvedPath), + program: state.builderPrograms.get(resolvedPath) || ((_a = getCachedParsedConfigFile(state, resolvedPath)) === null || _a === void 0 ? void 0 : _a.fileNames), useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames, - writeLog: function (s) { return state.writeLog(s); } + writeLog: function (s) { return state.writeLog(s); }, + toPath: function (fileName) { return toPath(state, fileName); } })) return; invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Partial); @@ -114235,19 +117695,16 @@ var ts; } function stopWatching(state) { ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher); - ts.clearMap(state.allWatchedExtendedConfigFiles, function (watcher) { - watcher.projects.clear(); - watcher.close(); - }); + ts.clearMap(state.allWatchedExtendedConfigFiles, ts.closeFileWatcherOf); ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); }); ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); }); } function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) { var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions); return { - build: function (project, cancellationToken) { return build(state, project, cancellationToken); }, + build: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers); }, clean: function (project) { return clean(state, project); }, - buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); }, + buildReferences: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers, /*onlyReferences*/ true); }, cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); }, getNextInvalidatedProject: function (cancellationToken) { setupInitialBuild(state, cancellationToken); @@ -114337,6 +117794,9 @@ var ts; } } function reportUpToDateStatus(state, configFileName, status) { + if (state.options.force && (status.type === ts.UpToDateStatusType.UpToDate || status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes)) { + return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); + } switch (status.type) { case ts.UpToDateStatusType.OutOfDateWithSelf: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); @@ -114886,6 +118346,9 @@ var ts; SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["link"] = 22] = "link"; + SymbolDisplayPartKind[SymbolDisplayPartKind["linkName"] = 23] = "linkName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["linkText"] = 24] = "linkText"; })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); var OutliningSpanKind; (function (OutliningSpanKind) { @@ -114996,6 +118459,12 @@ var ts; ScriptElementKind["jsxAttribute"] = "JSX attribute"; /** String literal */ ScriptElementKind["string"] = "string"; + /** Jsdoc @link: in `{@link C link text}`, the before and after text "{@link " and "}" */ + ScriptElementKind["link"] = "link"; + /** Jsdoc @link: in `{@link C link text}`, the entity name "C" */ + ScriptElementKind["linkName"] = "link name"; + /** Jsdoc @link: in `{@link C link text}`, the link text "link text" */ + ScriptElementKind["linkText"] = "link text"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; (function (ScriptElementKindModifier) { @@ -115088,37 +118557,37 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; - case 160 /* Parameter */: - case 198 /* BindingElement */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 287 /* CatchClause */: - case 280 /* JsxAttribute */: + case 161 /* Parameter */: + case 199 /* BindingElement */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 288 /* CatchClause */: + case 281 /* JsxAttribute */: return 1 /* Value */; - case 159 /* TypeParameter */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 177 /* TypeLiteral */: + case 160 /* TypeParameter */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 178 /* TypeLiteral */: return 2 /* Type */; - case 331 /* JSDocTypedefTag */: + case 335 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; - case 291 /* EnumMember */: - case 252 /* ClassDeclaration */: + case 292 /* EnumMember */: + case 253 /* ClassDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; } @@ -115128,16 +118597,16 @@ var ts; else { return 4 /* Namespace */; } - case 255 /* EnumDeclaration */: - case 264 /* NamedImports */: - case 265 /* ImportSpecifier */: - case 260 /* ImportEqualsDeclaration */: - case 261 /* ImportDeclaration */: - case 266 /* ExportAssignment */: - case 267 /* ExportDeclaration */: + case 256 /* EnumDeclaration */: + case 265 /* NamedImports */: + case 266 /* ImportSpecifier */: + case 261 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 267 /* ExportAssignment */: + case 268 /* ExportDeclaration */: return 7 /* All */; // An external module can be a Value - case 297 /* SourceFile */: + case 298 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 7 /* All */; @@ -115145,13 +118614,13 @@ var ts; ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { node = getAdjustedReferenceLocation(node); - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 266 /* ExportAssignment */ - || node.parent.kind === 272 /* ExternalModuleReference */ - || node.parent.kind === 265 /* ImportSpecifier */ - || node.parent.kind === 262 /* ImportClause */ + else if (node.parent.kind === 267 /* ExportAssignment */ + || node.parent.kind === 273 /* ExternalModuleReference */ + || node.parent.kind === 266 /* ImportSpecifier */ + || node.parent.kind === 263 /* ImportClause */ || ts.isImportEqualsDeclaration(node.parent) && node === node.parent.name) { return 7 /* All */; } @@ -115161,7 +118630,7 @@ var ts; else if (ts.isDeclarationName(node)) { return getMeaningFromDeclaration(node.parent); } - else if (ts.isEntityName(node) && ts.isJSDocNameReference(node.parent)) { + else if (ts.isEntityName(node) && (ts.isJSDocNameReference(node.parent) || ts.isJSDocLink(node.parent))) { return 7 /* All */; } else if (isTypeReference(node)) { @@ -115187,11 +118656,11 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - var name = node.kind === 157 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; - return name && name.parent.kind === 260 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; + var name = node.kind === 158 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; + return name && name.parent.kind === 261 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; } function isInRightSideOfInternalImportEqualsDeclaration(node) { - while (node.parent.kind === 157 /* QualifiedName */) { + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -115203,27 +118672,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 157 /* QualifiedName */) { - while (root.parent && root.parent.kind === 157 /* QualifiedName */) { + if (root.parent.kind === 158 /* QualifiedName */) { + while (root.parent && root.parent.kind === 158 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 173 /* TypeReference */ && !isLastClause; + return root.parent.kind === 174 /* TypeReference */ && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 201 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 201 /* PropertyAccessExpression */) { + if (root.parent.kind === 202 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 202 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 223 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 286 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 224 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 287 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 252 /* ClassDeclaration */ && root.parent.parent.token === 116 /* ImplementsKeyword */) || - (decl.kind === 253 /* InterfaceDeclaration */ && root.parent.parent.token === 93 /* ExtendsKeyword */); + return (decl.kind === 253 /* ClassDeclaration */ && root.parent.parent.token === 116 /* ImplementsKeyword */) || + (decl.kind === 254 /* InterfaceDeclaration */ && root.parent.parent.token === 93 /* ExtendsKeyword */); } return false; } @@ -115234,15 +118703,15 @@ var ts; switch (node.kind) { case 107 /* ThisKeyword */: return !ts.isExpressionNode(node); - case 187 /* ThisType */: + case 188 /* ThisType */: return true; } switch (node.parent.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return true; - case 195 /* ImportType */: + case 196 /* ImportType */: return !node.parent.isTypeOf; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } return false; @@ -115309,7 +118778,7 @@ var ts; ts.climbPastPropertyOrElementAccess = climbPastPropertyOrElementAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 245 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { + if (referenceNode.kind === 246 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -115370,22 +118839,22 @@ var ts; ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { switch (node.parent.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 288 /* PropertyAssignment */: - case 291 /* EnumMember */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 256 /* ModuleDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 289 /* PropertyAssignment */: + case 292 /* EnumMember */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 257 /* ModuleDeclaration */: return ts.getNameOfDeclaration(node.parent) === node; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return node.parent.argumentExpression === node; - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return true; - case 191 /* LiteralType */: - return node.parent.parent.kind === 189 /* IndexedAccessType */; + case 192 /* LiteralType */: + return node.parent.parent.kind === 190 /* IndexedAccessType */; default: return false; } @@ -115409,17 +118878,17 @@ var ts; return undefined; } switch (node.kind) { - case 297 /* SourceFile */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 256 /* ModuleDeclaration */: + case 298 /* SourceFile */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 257 /* ModuleDeclaration */: return node; } } @@ -115427,54 +118896,54 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return "module" /* moduleElement */; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return "class" /* classElement */; - case 253 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; - case 254 /* TypeAliasDeclaration */: - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: + case 254 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 255 /* TypeAliasDeclaration */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: return "type" /* typeElement */; - case 255 /* EnumDeclaration */: return "enum" /* enumElement */; - case 249 /* VariableDeclaration */: + case 256 /* EnumDeclaration */: return "enum" /* enumElement */; + case 250 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 209 /* ArrowFunction */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return "function" /* functionElement */; - case 167 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; - case 168 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 168 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 169 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: return "method" /* memberFunctionElement */; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: var initializer = node.initializer; return ts.isFunctionLike(initializer) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 289 /* ShorthandPropertyAssignment */: - case 290 /* SpreadAssignment */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 290 /* ShorthandPropertyAssignment */: + case 291 /* SpreadAssignment */: return "property" /* memberVariableElement */; - case 171 /* IndexSignature */: return "index" /* indexSignatureElement */; - case 170 /* ConstructSignature */: return "construct" /* constructSignatureElement */; - case 169 /* CallSignature */: return "call" /* callSignatureElement */; - case 166 /* Constructor */: return "constructor" /* constructorImplementationElement */; - case 159 /* TypeParameter */: return "type parameter" /* typeParameterElement */; - case 291 /* EnumMember */: return "enum member" /* enumMemberElement */; - case 160 /* Parameter */: return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; - case 260 /* ImportEqualsDeclaration */: - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: - case 263 /* NamespaceImport */: - case 269 /* NamespaceExport */: + case 172 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 171 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 170 /* CallSignature */: return "call" /* callSignatureElement */; + case 167 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 160 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 292 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 161 /* Parameter */: return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 261 /* ImportEqualsDeclaration */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: + case 264 /* NamespaceImport */: + case 270 /* NamespaceExport */: return "alias" /* alias */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { @@ -115503,7 +118972,7 @@ var ts; } case 78 /* Identifier */: return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: var scriptKind = getNodeKind(node.expression); // If the expression didn't come back with something (like it does for an identifiers) return scriptKind === "" /* unknown */ ? "const" /* constElement */ : scriptKind; @@ -115526,7 +118995,7 @@ var ts; return true; case 78 /* Identifier */: // 'this' as a parameter - return ts.identifierIsThisKeyword(node) && node.parent.kind === 160 /* Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 161 /* Parameter */; default: return false; } @@ -115591,42 +119060,42 @@ var ts; return false; } switch (n.kind) { - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 200 /* ObjectLiteralExpression */: - case 196 /* ObjectBindingPattern */: - case 177 /* TypeLiteral */: - case 230 /* Block */: - case 257 /* ModuleBlock */: - case 258 /* CaseBlock */: - case 264 /* NamedImports */: - case 268 /* NamedExports */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 201 /* ObjectLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 178 /* TypeLiteral */: + case 231 /* Block */: + case 258 /* ModuleBlock */: + case 259 /* CaseBlock */: + case 265 /* NamedImports */: + case 269 /* NamedExports */: return nodeEndsWith(n, 19 /* CloseBraceToken */, sourceFile); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 204 /* NewExpression */: + case 205 /* NewExpression */: if (!n.arguments) { return true; } // falls through - case 203 /* CallExpression */: - case 207 /* ParenthesizedExpression */: - case 186 /* ParenthesizedType */: + case 204 /* CallExpression */: + case 208 /* ParenthesizedExpression */: + case 187 /* ParenthesizedType */: return nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 170 /* ConstructSignature */: - case 169 /* CallSignature */: - case 209 /* ArrowFunction */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 171 /* ConstructSignature */: + case 170 /* CallSignature */: + case 210 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -115636,65 +119105,65 @@ var ts; // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. return hasChildOfKind(n, 21 /* CloseParenToken */, sourceFile); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return !!n.body && isCompletedNode(n.body, sourceFile); - case 234 /* IfStatement */: + case 235 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 26 /* SemicolonToken */, sourceFile); - case 199 /* ArrayLiteralExpression */: - case 197 /* ArrayBindingPattern */: - case 202 /* ElementAccessExpression */: - case 158 /* ComputedPropertyName */: - case 179 /* TupleType */: + case 200 /* ArrayLiteralExpression */: + case 198 /* ArrayBindingPattern */: + case 203 /* ElementAccessExpression */: + case 159 /* ComputedPropertyName */: + case 180 /* TupleType */: return nodeEndsWith(n, 23 /* CloseBracketToken */, sourceFile); - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 23 /* CloseBracketToken */, sourceFile); - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed return false; - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 236 /* WhileStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 237 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 235 /* DoStatement */: + case 236 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; return hasChildOfKind(n, 114 /* WhileKeyword */, sourceFile) ? nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile) : isCompletedNode(n.statement, sourceFile); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 211 /* TypeOfExpression */: - case 210 /* DeleteExpression */: - case 212 /* VoidExpression */: - case 219 /* YieldExpression */: - case 220 /* SpreadElement */: + case 212 /* TypeOfExpression */: + case 211 /* DeleteExpression */: + case 213 /* VoidExpression */: + case 220 /* YieldExpression */: + case 221 /* SpreadElement */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 267 /* ExportDeclaration */: - case 261 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: return ts.nodeIsPresent(n.moduleSpecifier); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -115820,11 +119289,11 @@ var ts; function getAdjustedLocationForDeclaration(node, forRename) { if (!forRename) { switch (node.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return getAdjustedLocationForClass(node); - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return getAdjustedLocationForFunction(node); } } @@ -116084,7 +119553,7 @@ var ts; // for (... /**/in [|name|]) // for (... /**/of [|name|]) if (node.kind === 100 /* InKeyword */ && ts.isForInStatement(parent) || - node.kind === 156 /* OfKeyword */ && ts.isForOfStatement(parent)) { + node.kind === 157 /* OfKeyword */ && ts.isForOfStatement(parent)) { return ts.skipOuterExpressions(parent.expression); } } @@ -116153,6 +119622,21 @@ var ts; return current; } } + /** + * Returns the first token where position is in [start, end), + * excluding `JsxText` tokens containing only whitespace. + */ + function findFirstNonJsxWhitespaceToken(sourceFile, position) { + var tokenAtPosition = getTokenAtPosition(sourceFile, position); + while (isWhiteSpaceOnlyJsxText(tokenAtPosition)) { + var nextToken = findNextToken(tokenAtPosition, tokenAtPosition.parent, sourceFile); + if (!nextToken) + return; + tokenAtPosition = nextToken; + } + return tokenAtPosition; + } + ts.findFirstNonJsxWhitespaceToken = findFirstNonJsxWhitespaceToken; /** * The token on the left of the position is the token that strictly includes the position * or sits to the left of the cursor if it is on a boundary. For example @@ -116239,7 +119723,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 297 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 298 /* 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. @@ -116312,17 +119796,17 @@ var ts; return true; } //
{ |
or
- if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 283 /* JsxExpression */) { + if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 284 /* JsxExpression */) { return true; } //
{ // | // } < /div> - if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 283 /* JsxExpression */) { + if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 284 /* JsxExpression */) { return true; } //
|
- if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 276 /* JsxClosingElement */) { + if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 277 /* JsxClosingElement */) { return true; } return false; @@ -116353,7 +119837,7 @@ var ts; function isInsideJsxElement(sourceFile, position) { function isInsideJsxElementTraversal(node) { while (node) { - if (node.kind >= 274 /* JsxSelfClosingElement */ && node.kind <= 283 /* JsxExpression */ + if (node.kind >= 275 /* JsxSelfClosingElement */ && node.kind <= 284 /* JsxExpression */ || node.kind === 11 /* JsxText */ || node.kind === 29 /* LessThanToken */ || node.kind === 31 /* GreaterThanToken */ @@ -116363,7 +119847,7 @@ var ts; || node.kind === 43 /* SlashToken */) { node = node.parent; } - else if (node.kind === 273 /* JsxElement */) { + else if (node.kind === 274 /* JsxElement */) { if (position > node.getStart(sourceFile)) return true; node = node.parent; @@ -116571,16 +120055,16 @@ var ts; result.push("deprecated" /* deprecatedModifier */); if (node.flags & 8388608 /* Ambient */) result.push("declare" /* ambientModifier */); - if (node.kind === 266 /* ExportAssignment */) + if (node.kind === 267 /* ExportAssignment */) result.push("export" /* exportedModifier */); return result.length > 0 ? result.join(",") : "" /* none */; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 173 /* TypeReference */ || node.kind === 203 /* CallExpression */) { + if (node.kind === 174 /* TypeReference */ || node.kind === 204 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 252 /* ClassDeclaration */ || node.kind === 253 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 253 /* ClassDeclaration */ || node.kind === 254 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; @@ -116625,18 +120109,18 @@ var ts; } ts.cloneCompilerOptions = cloneCompilerOptions; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 199 /* ArrayLiteralExpression */ || - node.kind === 200 /* ObjectLiteralExpression */) { + if (node.kind === 200 /* ArrayLiteralExpression */ || + node.kind === 201 /* ObjectLiteralExpression */) { // [a,b,c] from: // [a, b, c] = someExpression; - if (node.parent.kind === 216 /* BinaryExpression */ && + if (node.parent.kind === 217 /* BinaryExpression */ && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */) { return true; } // [a, b, c] from: // for([a, b, c] of expression) - if (node.parent.kind === 239 /* ForOfStatement */ && + if (node.parent.kind === 240 /* ForOfStatement */ && node.parent.initializer === node) { return true; } @@ -116644,7 +120128,7 @@ var ts; // [x, [a, b, c] ] = someExpression // or // {x, a: {a, b, c} } = someExpression - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 288 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 289 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { return true; } } @@ -116764,7 +120248,7 @@ var ts; } ts.skipConstraint = skipConstraint; function getNameFromPropertyName(name) { - return name.kind === 158 /* ComputedPropertyName */ + return name.kind === 159 /* ComputedPropertyName */ // treat computed property names where expression is string/numeric literal as just string/numeric literal ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined : ts.isPrivateIdentifier(name) ? ts.idText(name) : ts.getTextOfIdentifierOrLiteral(name); @@ -116783,7 +120267,7 @@ var ts; } ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules; function createModuleSpecifierResolutionHost(program, host) { - // Mix in `getProbableSymlinks` from Program when host doesn't have it + // Mix in `getSymlinkCache` from Program when host doesn't have it // in order for non-Project hosts to have a symlinks cache. return { fileExists: function (fileName) { return program.fileExists(fileName); }, @@ -116791,6 +120275,7 @@ var ts; readFile: ts.maybeBind(host, host.readFile), useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), getSymlinkCache: ts.maybeBind(host, host.getSymlinkCache) || program.getSymlinkCache, + getModuleSpecifierCache: ts.maybeBind(host, host.getModuleSpecifierCache), getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation), getSourceFiles: function () { return program.getSourceFiles(); }, redirectTargetsMap: program.redirectTargetsMap, @@ -116865,6 +120350,13 @@ var ts; }); } ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isModuleSpecifierLike(node) { + return ts.isStringLiteralLike(node) && (ts.isExternalModuleReference(node.parent) || + ts.isImportDeclaration(node.parent) || + ts.isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ false) && node.parent.arguments[0] === node || + ts.isImportCall(node.parent) && node.parent.arguments[0] === node); + } + ts.isModuleSpecifierLike = isModuleSpecifierLike; function isObjectBindingElementWithoutPropertyName(bindingElement) { return ts.isBindingElement(bindingElement) && ts.isObjectBindingPattern(bindingElement.parent) && @@ -116898,7 +120390,7 @@ var ts; ts.findModifier = findModifier; function insertImports(changes, sourceFile, imports, blankLineBetween) { var decl = ts.isArray(imports) ? imports[0] : imports; - var importKindPredicate = decl.kind === 232 /* VariableStatement */ ? ts.isRequireVariableStatement : ts.isAnyImportSyntax; + var importKindPredicate = decl.kind === 233 /* VariableStatement */ ? ts.isRequireVariableStatement : ts.isAnyImportSyntax; var existingImportStatements = ts.filter(sourceFile.statements, importKindPredicate); var sortedNewImports = ts.isArray(imports) ? ts.stableSort(imports, ts.OrganizeImports.compareImportsOrRequireStatements) : [imports]; if (!existingImportStatements.length) { @@ -116976,7 +120468,7 @@ var ts; // Display-part writer helpers // #region function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 160 /* Parameter */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 161 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -117139,6 +120631,14 @@ var ts; return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); } ts.operatorPart = operatorPart; + function parameterNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.parameterName); + } + ts.parameterNamePart = parameterNamePart; + function propertyNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.propertyName); + } + ts.propertyNamePart = propertyNamePart; function textOrKeywordPart(text) { var kind = ts.stringToToken(text); return kind === undefined @@ -117150,6 +120650,58 @@ var ts; return displayPart(text, ts.SymbolDisplayPartKind.text); } ts.textPart = textPart; + function typeAliasNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.aliasName); + } + ts.typeAliasNamePart = typeAliasNamePart; + function typeParameterNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.typeParameterName); + } + ts.typeParameterNamePart = typeParameterNamePart; + function linkTextPart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.linkText); + } + ts.linkTextPart = linkTextPart; + function linkNamePart(name, target) { + return { + text: ts.getTextOfNode(name), + kind: ts.SymbolDisplayPartKind[ts.SymbolDisplayPartKind.linkName], + target: { + fileName: ts.getSourceFileOfNode(target).fileName, + textSpan: createTextSpanFromNode(target), + }, + }; + } + ts.linkNamePart = linkNamePart; + function linkPart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.link); + } + ts.linkPart = linkPart; + function buildLinkParts(link, checker) { + var _a; + var parts = [linkPart("{@link ")]; + if (!link.name) { + if (link.text) { + parts.push(linkTextPart(link.text)); + } + } + else { + var symbol = checker === null || checker === void 0 ? void 0 : checker.getSymbolAtLocation(link.name); + var decl = (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) || ((_a = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]); + if (decl) { + parts.push(linkNamePart(link.name, decl)); + if (link.text) { + parts.push(linkTextPart(link.text)); + } + } + else { + parts.push(linkTextPart(ts.getTextOfNode(link.name) + link.text)); + } + } + parts.push(linkPart("}")); + return parts; + } + ts.buildLinkParts = buildLinkParts; var carriageReturnLineFeed = "\r\n"; /** * The default is CRLF. @@ -117435,21 +120987,23 @@ var ts; } /* @internal */ function needsParentheses(expression) { - return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ + || ts.isObjectLiteralExpression(expression) + || ts.isAsExpression(expression) && ts.isObjectLiteralExpression(expression.expression); } ts.needsParentheses = needsParentheses; function getContextualTypeFromParent(node, checker) { var parent = node.parent; switch (parent.kind) { - case 204 /* NewExpression */: + case 205 /* NewExpression */: return checker.getContextualType(parent); - case 216 /* BinaryExpression */: { + case 217 /* BinaryExpression */: { var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; return isEqualityOperatorKind(operatorToken.kind) ? checker.getTypeAtLocation(node === right ? left : right) : checker.getContextualType(node); } - case 284 /* CaseClause */: + case 285 /* CaseClause */: return parent.expression === node ? getSwitchedType(parent, checker) : undefined; default: return checker.getContextualType(node); @@ -117460,7 +121014,7 @@ var ts; // Editors can pass in undefined or empty string - we want to infer the preference in those cases. var quotePreference = getQuotePreference(sourceFile, preferences); var quoted = JSON.stringify(text); - return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'" : quoted; + return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace(/'/g, "\\'").replace(/\\"/g, '"') + "'" : quoted; } ts.quote = quote; function isEqualityOperatorKind(kind) { @@ -117479,8 +121033,8 @@ var ts; switch (node.kind) { case 10 /* StringLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: - case 218 /* TemplateExpression */: - case 205 /* TaggedTemplateExpression */: + case 219 /* TemplateExpression */: + case 206 /* TaggedTemplateExpression */: return true; default: return false; @@ -117513,41 +121067,41 @@ var ts; } ts.getTypeNodeIfAccessible = getTypeNodeIfAccessible; function syntaxRequiresTrailingCommaOrSemicolonOrASI(kind) { - return kind === 169 /* CallSignature */ - || kind === 170 /* ConstructSignature */ - || kind === 171 /* IndexSignature */ - || kind === 162 /* PropertySignature */ - || kind === 164 /* MethodSignature */; + return kind === 170 /* CallSignature */ + || kind === 171 /* ConstructSignature */ + || kind === 172 /* IndexSignature */ + || kind === 163 /* PropertySignature */ + || kind === 165 /* MethodSignature */; } ts.syntaxRequiresTrailingCommaOrSemicolonOrASI = syntaxRequiresTrailingCommaOrSemicolonOrASI; function syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(kind) { - return kind === 251 /* FunctionDeclaration */ - || kind === 166 /* Constructor */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 252 /* FunctionDeclaration */ + || kind === 167 /* Constructor */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } ts.syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI = syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI; function syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(kind) { - return kind === 256 /* ModuleDeclaration */; + return kind === 257 /* ModuleDeclaration */; } ts.syntaxRequiresTrailingModuleBlockOrSemicolonOrASI = syntaxRequiresTrailingModuleBlockOrSemicolonOrASI; function syntaxRequiresTrailingSemicolonOrASI(kind) { - return kind === 232 /* VariableStatement */ - || kind === 233 /* ExpressionStatement */ - || kind === 235 /* DoStatement */ - || kind === 240 /* ContinueStatement */ - || kind === 241 /* BreakStatement */ - || kind === 242 /* ReturnStatement */ - || kind === 246 /* ThrowStatement */ - || kind === 248 /* DebuggerStatement */ - || kind === 163 /* PropertyDeclaration */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 261 /* ImportDeclaration */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 267 /* ExportDeclaration */ - || kind === 259 /* NamespaceExportDeclaration */ - || kind === 266 /* ExportAssignment */; + return kind === 233 /* VariableStatement */ + || kind === 234 /* ExpressionStatement */ + || kind === 236 /* DoStatement */ + || kind === 241 /* ContinueStatement */ + || kind === 242 /* BreakStatement */ + || kind === 243 /* ReturnStatement */ + || kind === 247 /* ThrowStatement */ + || kind === 249 /* DebuggerStatement */ + || kind === 164 /* PropertyDeclaration */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 262 /* ImportDeclaration */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 268 /* ExportDeclaration */ + || kind === 260 /* NamespaceExportDeclaration */ + || kind === 267 /* ExportAssignment */; } ts.syntaxRequiresTrailingSemicolonOrASI = syntaxRequiresTrailingSemicolonOrASI; ts.syntaxMayBeASICandidate = ts.or(syntaxRequiresTrailingCommaOrSemicolonOrASI, syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI, syntaxRequiresTrailingModuleBlockOrSemicolonOrASI, syntaxRequiresTrailingSemicolonOrASI); @@ -117577,7 +121131,7 @@ var ts; return false; } // See comment in parser’s `parseDoStatement` - if (node.kind === 235 /* DoStatement */) { + if (node.kind === 236 /* DoStatement */) { return true; } var topNode = ts.findAncestor(node, function (ancestor) { return !ancestor.parent; }); @@ -117751,6 +121305,94 @@ var ts; } } ts.createPackageJsonInfo = createPackageJsonInfo; + function createPackageJsonImportFilter(fromFile, host) { + var packageJsons = ((host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName)) || getPackageJsonsVisibleToFile(fromFile.fileName, host)).filter(function (p) { return p.parseable; }); + var usesNodeCoreModules; + return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier }; + function moduleSpecifierIsCoveredByPackageJson(specifier) { + var packageName = getNodeModuleRootSpecifier(specifier); + for (var _i = 0, packageJsons_1 = packageJsons; _i < packageJsons_1.length; _i++) { + var packageJson = packageJsons_1[_i]; + if (packageJson.has(packageName) || packageJson.has(ts.getTypesPackageName(packageName))) { + return true; + } + } + return false; + } + function allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost) { + if (!packageJsons.length || !moduleSymbol.valueDeclaration) { + return true; + } + var declaringSourceFile = moduleSymbol.valueDeclaration.getSourceFile(); + var declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName, moduleSpecifierResolutionHost); + if (typeof declaringNodeModuleName === "undefined") { + return true; + } + var declaredModuleSpecifier = ts.stripQuotes(moduleSymbol.getName()); + if (isAllowedCoreNodeModulesImport(declaredModuleSpecifier)) { + return true; + } + return moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName) + || moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier); + } + function allowsImportingSourceFile(sourceFile, moduleSpecifierResolutionHost) { + if (!packageJsons.length) { + return true; + } + var moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName, moduleSpecifierResolutionHost); + if (!moduleSpecifier) { + return true; + } + return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); + } + function allowsImportingSpecifier(moduleSpecifier) { + if (!packageJsons.length || isAllowedCoreNodeModulesImport(moduleSpecifier)) { + return true; + } + if (ts.pathIsRelative(moduleSpecifier) || ts.isRootedDiskPath(moduleSpecifier)) { + return true; + } + return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); + } + function isAllowedCoreNodeModulesImport(moduleSpecifier) { + // If we’re in JavaScript, it can be difficult to tell whether the user wants to import + // from Node core modules or not. We can start by seeing if the user is actually using + // any node core modules, as opposed to simply having @types/node accidentally as a + // dependency of a dependency. + if (ts.isSourceFileJS(fromFile) && ts.JsTyping.nodeCoreModules.has(moduleSpecifier)) { + if (usesNodeCoreModules === undefined) { + usesNodeCoreModules = consumesNodeCoreModules(fromFile); + } + if (usesNodeCoreModules) { + return true; + } + } + return false; + } + function getNodeModulesPackageNameFromFileName(importedFileName, moduleSpecifierResolutionHost) { + if (!ts.stringContains(importedFileName, "node_modules")) { + return undefined; + } + var specifier = ts.moduleSpecifiers.getNodeModulesPackageName(host.getCompilationSettings(), fromFile.path, importedFileName, moduleSpecifierResolutionHost); + if (!specifier) { + return undefined; + } + // Paths here are not node_modules, so we don’t care about them; + // returning anything will trigger a lookup in package.json. + if (!ts.pathIsRelative(specifier) && !ts.isRootedDiskPath(specifier)) { + return getNodeModuleRootSpecifier(specifier); + } + } + function getNodeModuleRootSpecifier(fullSpecifier) { + var components = ts.getPathComponents(ts.getPackageNameFromTypesPackageName(fullSpecifier)).slice(1); + // Scoped packages + if (ts.startsWith(components[0], "@")) { + return components[0] + "/" + components[1]; + } + return components[0]; + } + } + ts.createPackageJsonImportFilter = createPackageJsonImportFilter; function tryParseJson(text) { try { return JSON.parse(text); @@ -117827,9 +121469,9 @@ var ts; } ts.firstOrOnly = firstOrOnly; function getNameForExportedSymbol(symbol, scriptTarget) { - if (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */) { + if (!(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */)) { // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. - return ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) + return ts.firstDefined(symbol.declarations, function (d) { var _a; return ts.isExportAssignment(d) ? (_a = ts.tryCast(ts.skipOuterExpressions(d.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget); } return symbol.name; @@ -117893,6 +121535,184 @@ var ts; return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation); } ts.isNonGlobalDeclaration = isNonGlobalDeclaration; + var ImportKind; + (function (ImportKind) { + ImportKind[ImportKind["Named"] = 0] = "Named"; + ImportKind[ImportKind["Default"] = 1] = "Default"; + ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; + ImportKind[ImportKind["CommonJS"] = 3] = "CommonJS"; + })(ImportKind = ts.ImportKind || (ts.ImportKind = {})); + var ExportKind; + (function (ExportKind) { + ExportKind[ExportKind["Named"] = 0] = "Named"; + ExportKind[ExportKind["Default"] = 1] = "Default"; + ExportKind[ExportKind["ExportEquals"] = 2] = "ExportEquals"; + ExportKind[ExportKind["UMD"] = 3] = "UMD"; + })(ExportKind = ts.ExportKind || (ts.ExportKind = {})); + function createExportMapCache() { + var cache; + var projectVersion; + var usableByFileName; + var wrapped = { + isEmpty: function () { + return !cache; + }, + clear: function () { + cache = undefined; + projectVersion = undefined; + }, + set: function (suggestions, version) { + cache = suggestions; + if (version) { + projectVersion = version; + } + }, + get: function (file, checker, version) { + if (usableByFileName && file !== usableByFileName) { + return undefined; + } + if (version && projectVersion === version) { + return cache; + } + cache === null || cache === void 0 ? void 0 : cache.forEach(function (infos) { + var _a, _b, _c; + for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { + var info = infos_1[_i]; + // If the symbol/moduleSymbol was a merged symbol, it will have a new identity + // in the checker, even though the symbols to merge are the same (guaranteed by + // cache invalidation in synchronizeHostData). + if ((_a = info.symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) { + info.symbol = checker.getMergedSymbol(info.exportKind === 1 /* Default */ + ? (_b = info.symbol.declarations[0].localSymbol) !== null && _b !== void 0 ? _b : info.symbol.declarations[0].symbol + : info.symbol.declarations[0].symbol); + } + if ((_c = info.moduleSymbol.declarations) === null || _c === void 0 ? void 0 : _c.length) { + info.moduleSymbol = checker.getMergedSymbol(info.moduleSymbol.declarations[0].symbol); + } + } + }); + return cache; + }, + onFileChanged: function (oldSourceFile, newSourceFile, typeAcquisitionEnabled) { + if (fileIsGlobalOnly(oldSourceFile) && fileIsGlobalOnly(newSourceFile)) { + // File is purely global; doesn't affect export map + return false; + } + if (usableByFileName && usableByFileName !== newSourceFile.path || + // If ATA is enabled, auto-imports uses existing imports to guess whether you want auto-imports from node. + // Adding or removing imports from node could change the outcome of that guess, so could change the suggestions list. + typeAcquisitionEnabled && consumesNodeCoreModules(oldSourceFile) !== consumesNodeCoreModules(newSourceFile) || + // Module agumentation and ambient module changes can add or remove exports available to be auto-imported. + // Changes elsewhere in the file can change the *type* of an export in a module augmentation, + // but type info is gathered in getCompletionEntryDetails, which doesn’t use the cache. + !ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations) || + !ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile)) { + this.clear(); + return true; + } + usableByFileName = newSourceFile.path; + return false; + }, + }; + if (ts.Debug.isDebugging) { + Object.defineProperty(wrapped, "__cache", { get: function () { return cache; } }); + } + return wrapped; + function fileIsGlobalOnly(file) { + return !file.commonJsModuleIndicator && !file.externalModuleIndicator && !file.moduleAugmentations && !file.ambientModuleNames; + } + function ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile) { + if (!ts.arrayIsEqualTo(oldSourceFile.ambientModuleNames, newSourceFile.ambientModuleNames)) { + return false; + } + var oldFileStatementIndex = -1; + var newFileStatementIndex = -1; + var _loop_1 = function (ambientModuleName) { + var isMatchingModuleDeclaration = function (node) { return ts.isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName; }; + oldFileStatementIndex = ts.findIndex(oldSourceFile.statements, isMatchingModuleDeclaration, oldFileStatementIndex + 1); + newFileStatementIndex = ts.findIndex(newSourceFile.statements, isMatchingModuleDeclaration, newFileStatementIndex + 1); + if (oldSourceFile.statements[oldFileStatementIndex] !== newSourceFile.statements[newFileStatementIndex]) { + return { value: false }; + } + }; + for (var _i = 0, _a = newSourceFile.ambientModuleNames; _i < _a.length; _i++) { + var ambientModuleName = _a[_i]; + var state_1 = _loop_1(ambientModuleName); + if (typeof state_1 === "object") + return state_1.value; + } + return true; + } + } + ts.createExportMapCache = createExportMapCache; + function createModuleSpecifierCache() { + var cache; + var importingFileName; + var wrapped = { + get: function (fromFileName, toFileName) { + if (!cache || fromFileName !== importingFileName) + return undefined; + return cache.get(toFileName); + }, + set: function (fromFileName, toFileName, moduleSpecifiers) { + if (cache && fromFileName !== importingFileName) { + cache.clear(); + } + importingFileName = fromFileName; + (cache || (cache = new ts.Map())).set(toFileName, moduleSpecifiers); + }, + clear: function () { + cache = undefined; + importingFileName = undefined; + }, + count: function () { + return cache ? cache.size : 0; + } + }; + if (ts.Debug.isDebugging) { + Object.defineProperty(wrapped, "__cache", { get: function () { return cache; } }); + } + return wrapped; + } + ts.createModuleSpecifierCache = createModuleSpecifierCache; + function isImportableFile(program, from, to, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) { + var _a; + if (from === to) + return false; + var cachedResult = moduleSpecifierCache === null || moduleSpecifierCache === void 0 ? void 0 : moduleSpecifierCache.get(from.path, to.path); + if (cachedResult !== undefined) { + return !!cachedResult; + } + var getCanonicalFileName = ts.hostGetCanonicalFileName(moduleSpecifierResolutionHost); + var globalTypingsCache = (_a = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation) === null || _a === void 0 ? void 0 : _a.call(moduleSpecifierResolutionHost); + var hasImportablePath = !!ts.moduleSpecifiers.forEachFileNameOfModule(from.fileName, to.fileName, moduleSpecifierResolutionHost, + /*preferSymlinks*/ false, function (toPath) { + var toFile = program.getSourceFile(toPath); + // Determine to import using toPath only if toPath is what we were looking at + // or there doesnt exist the file in the program by the symlink + return (toFile === to || !toFile) && + isImportablePath(from.fileName, toPath, getCanonicalFileName, globalTypingsCache); + }); + if (packageJsonFilter) { + var isImportable = hasImportablePath && packageJsonFilter.allowsImportingSourceFile(to, moduleSpecifierResolutionHost); + moduleSpecifierCache === null || moduleSpecifierCache === void 0 ? void 0 : moduleSpecifierCache.set(from.path, to.path, isImportable); + return isImportable; + } + return hasImportablePath; + } + ts.isImportableFile = isImportableFile; + /** + * Don't include something from a `node_modules` that isn't actually reachable by a global import. + * A relative import to node_modules is usually a bad idea. + */ + function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) { + // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. + var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); + var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules)); + return toNodeModulesParent === undefined + || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) + || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); + } // #endregion })(ts || (ts = {})); var ts; @@ -118334,13 +122154,13 @@ var ts; // That means we're calling back into the host around every 1.2k of the file we process. // Lib.d.ts has similar numbers. switch (kind) { - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 251 /* FunctionDeclaration */: - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: cancellationToken.throwIfCancellationRequested(); } } @@ -118547,10 +122367,11 @@ var ts; pushClassification(start, width, 1 /* comment */); } function classifyJSDocComment(docComment) { + var _a, _b, _c, _d, _e, _f, _g; var pos = docComment.pos; if (docComment.tags) { - for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { - var tag = _a[_i]; + for (var _i = 0, _h = docComment.tags; _i < _h.length; _i++) { + var tag = _h[_i]; // As we walk through each tag, classify the portion of text from the end of // the last tag (or the start of the entire doc comment) as 'comment'. if (tag.pos !== pos) { @@ -118559,22 +122380,56 @@ var ts; pushClassification(tag.pos, 1, 10 /* punctuation */); // "@" pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; + var commentStart = tag.tagName.end; switch (tag.kind) { - case 326 /* JSDocParameterTag */: - processJSDocParameterTag(tag); + case 330 /* JSDocParameterTag */: + var param = tag; + processJSDocParameterTag(param); + commentStart = param.isNameFirst && ((_a = param.typeExpression) === null || _a === void 0 ? void 0 : _a.end) || param.name.end; break; - case 330 /* JSDocTemplateTag */: + case 337 /* JSDocPropertyTag */: + var prop = tag; + commentStart = prop.isNameFirst && ((_b = prop.typeExpression) === null || _b === void 0 ? void 0 : _b.end) || prop.name.end; + break; + case 334 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); pos = tag.end; + commentStart = tag.typeParameters.end; + break; + case 335 /* JSDocTypedefTag */: + var type = tag; + commentStart = ((_c = type.typeExpression) === null || _c === void 0 ? void 0 : _c.kind) === 302 /* JSDocTypeExpression */ && ((_d = type.fullName) === null || _d === void 0 ? void 0 : _d.end) || ((_e = type.typeExpression) === null || _e === void 0 ? void 0 : _e.end) || commentStart; break; - case 329 /* JSDocTypeTag */: + case 328 /* JSDocCallbackTag */: + commentStart = tag.typeExpression.end; + break; + case 333 /* JSDocTypeTag */: processElement(tag.typeExpression); pos = tag.end; + commentStart = tag.typeExpression.end; + break; + case 332 /* JSDocThisTag */: + case 329 /* JSDocEnumTag */: + commentStart = tag.typeExpression.end; break; - case 327 /* JSDocReturnTag */: + case 331 /* JSDocReturnTag */: processElement(tag.typeExpression); pos = tag.end; + commentStart = ((_f = tag.typeExpression) === null || _f === void 0 ? void 0 : _f.end) || commentStart; break; + case 336 /* JSDocSeeTag */: + commentStart = ((_g = tag.name) === null || _g === void 0 ? void 0 : _g.end) || commentStart; + break; + case 318 /* JSDocAugmentsTag */: + case 319 /* JSDocImplementsTag */: + commentStart = tag.class.end; + break; + } + if (typeof tag.comment === "object") { + pushCommentRange(tag.comment.pos, tag.comment.end - tag.comment.pos); + } + else if (typeof tag.comment === "string") { + pushCommentRange(commentStart, tag.end - commentStart); } } } @@ -118722,22 +122577,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } break; - case 276 /* JsxClosingElement */: + case 277 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } break; - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } break; - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: if (token.parent.name === token) { return 22 /* jsxAttribute */; } @@ -118766,17 +122621,17 @@ var ts; var parent = token.parent; if (tokenKind === 62 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (parent.kind === 249 /* VariableDeclaration */ || - parent.kind === 163 /* PropertyDeclaration */ || - parent.kind === 160 /* Parameter */ || - parent.kind === 280 /* JsxAttribute */) { + if (parent.kind === 250 /* VariableDeclaration */ || + parent.kind === 164 /* PropertyDeclaration */ || + parent.kind === 161 /* Parameter */ || + parent.kind === 281 /* JsxAttribute */) { return 5 /* operator */; } } - if (parent.kind === 216 /* BinaryExpression */ || - parent.kind === 214 /* PrefixUnaryExpression */ || - parent.kind === 215 /* PostfixUnaryExpression */ || - parent.kind === 217 /* ConditionalExpression */) { + if (parent.kind === 217 /* BinaryExpression */ || + parent.kind === 215 /* PrefixUnaryExpression */ || + parent.kind === 216 /* PostfixUnaryExpression */ || + parent.kind === 218 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -118789,7 +122644,7 @@ var ts; return 25 /* bigintLiteral */; } else if (tokenKind === 10 /* StringLiteral */) { - return token && token.parent.kind === 280 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + return token && token.parent.kind === 281 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 13 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -118805,32 +122660,32 @@ var ts; else if (tokenKind === 78 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 160 /* Parameter */: + case 161 /* Parameter */: if (token.parent.name === token) { return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } @@ -118932,13 +122787,13 @@ var ts; var inJSXElement = false; function visit(node) { switch (node.kind) { - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 251 /* FunctionDeclaration */: - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: cancellationToken.throwIfCancellationRequested(); } if (!node || !ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth()) || node.getFullWidth() === 0) { @@ -119084,25 +122939,25 @@ var ts; return (ts.isQualifiedName(node.parent) && node.parent.right === node) || (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node); } var tokenFromDeclarationMapping = new ts.Map([ - [249 /* VariableDeclaration */, 7 /* variable */], - [160 /* Parameter */, 6 /* parameter */], - [163 /* PropertyDeclaration */, 9 /* property */], - [256 /* ModuleDeclaration */, 3 /* namespace */], - [255 /* EnumDeclaration */, 1 /* enum */], - [291 /* EnumMember */, 8 /* enumMember */], - [252 /* ClassDeclaration */, 0 /* class */], - [165 /* MethodDeclaration */, 11 /* member */], - [251 /* FunctionDeclaration */, 10 /* function */], - [208 /* FunctionExpression */, 10 /* function */], - [164 /* MethodSignature */, 11 /* member */], - [167 /* GetAccessor */, 9 /* property */], - [168 /* SetAccessor */, 9 /* property */], - [162 /* PropertySignature */, 9 /* property */], - [253 /* InterfaceDeclaration */, 2 /* interface */], - [254 /* TypeAliasDeclaration */, 5 /* type */], - [159 /* TypeParameter */, 4 /* typeParameter */], - [288 /* PropertyAssignment */, 9 /* property */], - [289 /* ShorthandPropertyAssignment */, 9 /* property */] + [250 /* VariableDeclaration */, 7 /* variable */], + [161 /* Parameter */, 6 /* parameter */], + [164 /* PropertyDeclaration */, 9 /* property */], + [257 /* ModuleDeclaration */, 3 /* namespace */], + [256 /* EnumDeclaration */, 1 /* enum */], + [292 /* EnumMember */, 8 /* enumMember */], + [253 /* ClassDeclaration */, 0 /* class */], + [166 /* MethodDeclaration */, 11 /* member */], + [252 /* FunctionDeclaration */, 10 /* function */], + [209 /* FunctionExpression */, 10 /* function */], + [165 /* MethodSignature */, 11 /* member */], + [168 /* GetAccessor */, 9 /* property */], + [169 /* SetAccessor */, 9 /* property */], + [163 /* PropertySignature */, 9 /* property */], + [254 /* InterfaceDeclaration */, 2 /* interface */], + [255 /* TypeAliasDeclaration */, 5 /* type */], + [160 /* TypeParameter */, 4 /* typeParameter */], + [289 /* PropertyAssignment */, 9 /* property */], + [290 /* ShorthandPropertyAssignment */, 9 /* property */] ]); })(v2020 = classifier.v2020 || (classifier.v2020 = {})); })(classifier = ts.classifier || (ts.classifier = {})); @@ -119122,12 +122977,12 @@ var ts; if (ts.isInString(sourceFile, position, contextToken)) { if (!contextToken || !ts.isStringLiteralLike(contextToken)) return undefined; - var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); - return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, preferences); + var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); + return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, options, preferences); } } StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; - function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, preferences) { + function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, options, preferences) { if (completion === undefined) { return undefined; } @@ -119137,7 +122992,7 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences, options); // Target will not be used, so arbitrary return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, optionalReplacementSpan: optionalReplacementSpan, entries: entries }; } case 2 /* Types */: { @@ -119154,10 +123009,10 @@ var ts; return ts.Debug.assertNever(completion); } } - function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken) { + function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken, preferences) { if (!contextToken || !ts.isStringLiteralLike(contextToken)) return undefined; - var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); + var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken); } StringCompletions.getStringLiteralCompletionDetails = getStringLiteralCompletionDetails; @@ -119206,13 +123061,13 @@ var ts; StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties"; StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); - function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host, preferences) { var parent = walkUpParentheses(node.parent); switch (parent.kind) { - case 191 /* LiteralType */: { + case 192 /* LiteralType */: { var grandParent = walkUpParentheses(parent.parent); switch (grandParent.kind) { - case 173 /* TypeReference */: { + case 174 /* TypeReference */: { var typeReference_1 = grandParent; var typeArgument = ts.findAncestor(parent, function (n) { return n.parent === typeReference_1; }); if (typeArgument) { @@ -119220,7 +123075,7 @@ var ts; } return undefined; } - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { // foo: string; @@ -119232,9 +123087,9 @@ var ts; return undefined; } return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(objectType)); - case 195 /* ImportType */: - return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 182 /* UnionType */: { + case 196 /* ImportType */: + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; + case 183 /* UnionType */: { if (!ts.isTypeReferenceNode(grandParent.parent)) { return undefined; } @@ -119246,7 +123101,7 @@ var ts; return undefined; } } - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { @@ -119263,7 +123118,7 @@ var ts; return stringLiteralCompletionsForObjectLiteral(typeChecker, parent.parent); } return fromContextualType(); - case 202 /* ElementAccessExpression */: { + case 203 /* ElementAccessExpression */: { var _b = parent, expression = _b.expression, argumentExpression = _b.argumentExpression; if (node === ts.skipParentheses(argumentExpression)) { // Get all names of properties on the expression @@ -119276,8 +123131,8 @@ var ts; } return undefined; } - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: 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 @@ -119286,16 +123141,16 @@ var ts; return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); } // falls through (is `require("")` or `import("")`) - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: - case 272 /* ExternalModuleReference */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 273 /* ExternalModuleReference */: // Get all known external module names or complete a path to a module // i.e. import * as ns from "/*completion position*/"; // var y = import("/*completion position*/"); // import x = require("/*completion position*/"); // var y = require("/*completion position*/"); // export * from "/*completion position*/"; - return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; default: return fromContextualType(); } @@ -119307,9 +123162,9 @@ var ts; } function walkUpParentheses(node) { switch (node.kind) { - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return ts.walkUpParenthesizedTypes(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return ts.walkUpParenthesizedExpressions(node); default: return node; @@ -119337,7 +123192,7 @@ var ts; function stringLiteralCompletionsFromProperties(type) { return type && { kind: 1 /* Properties */, - symbols: ts.filter(type.getApparentProperties(), function (prop) { return !(prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)); }), + symbols: ts.filter(type.getApparentProperties(), function (prop) { return !(prop.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration)); }), hasIndexSignature: ts.hasIndexSignature(type) }; } @@ -119375,23 +123230,23 @@ var ts; return Math.max(name.indexOf(ts.directorySeparator), name.indexOf(ts.altDirectorySeparator)) !== -1 ? { name: name, kind: kind, extension: extension, span: wholeSpan } : { name: name, kind: kind, extension: extension, span: span }; }); } - function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { - return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); + function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) { + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences)); } - function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) { + function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = sourceFile.path; var scriptDirectory = ts.getDirectoryPath(scriptPath); return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue)) - ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) + ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, preferences) : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); } function getExtensionOptions(compilerOptions, includeExtensions) { if (includeExtensions === void 0) { includeExtensions = false; } return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions: includeExtensions }; } - function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) { - var extensionOptions = getExtensionOptions(compilerOptions); + function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, preferences) { + var extensionOptions = getExtensionOptions(compilerOptions, preferences.importModuleSpecifierEnding === "js"); if (compilerOptions.rootDirs) { return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); } @@ -119508,7 +123363,7 @@ var ts; continue; var patterns = paths[path]; if (patterns) { - var _loop_1 = function (name, kind, extension) { + var _loop_2 = function (name, kind, extension) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(function (entry) { return entry.name === name; })) { result.push(nameAndKind(name, kind, extension)); @@ -119516,7 +123371,7 @@ var ts; }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; - _loop_1(name, kind, extension); + _loop_2(name, kind, extension); } } } @@ -119551,7 +123406,7 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_2 = function (moduleName) { + var _loop_3 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); @@ -119559,7 +123414,7 @@ var ts; }; for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { var moduleName = _c[_b]; - _loop_2(moduleName); + _loop_3(moduleName); } } if (!foundGlobal) { @@ -119806,6 +123661,7 @@ var ts; SymbolOriginInfoKind[SymbolOriginInfoKind["Export"] = 4] = "Export"; SymbolOriginInfoKind[SymbolOriginInfoKind["Promise"] = 8] = "Promise"; SymbolOriginInfoKind[SymbolOriginInfoKind["Nullable"] = 16] = "Nullable"; + SymbolOriginInfoKind[SymbolOriginInfoKind["ResolvedExport"] = 32] = "ResolvedExport"; SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberNoExport"] = 2] = "SymbolMemberNoExport"; SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberExport"] = 6] = "SymbolMemberExport"; })(SymbolOriginInfoKind || (SymbolOriginInfoKind = {})); @@ -119818,8 +123674,14 @@ var ts; function originIsExport(origin) { return !!(origin && origin.kind & 4 /* Export */); } + function originIsResolvedExport(origin) { + return !!(origin && origin.kind === 32 /* ResolvedExport */); + } + function originIncludesSymbolName(origin) { + return originIsExport(origin) || originIsResolvedExport(origin); + } function originIsPackageJsonImport(origin) { - return originIsExport(origin) && !!origin.isFromPackageJson; + return (originIsExport(origin) || originIsResolvedExport(origin)) && !!origin.isFromPackageJson; } function originIsPromise(origin) { return !!(origin.kind & 8 /* Promise */); @@ -119845,52 +123707,6 @@ var ts; GlobalsSearch[GlobalsSearch["Success"] = 1] = "Success"; GlobalsSearch[GlobalsSearch["Fail"] = 2] = "Fail"; })(GlobalsSearch || (GlobalsSearch = {})); - function createImportSuggestionsForFileCache() { - var cache; - var projectVersion; - var fileName; - return { - isEmpty: function () { - return !cache; - }, - clear: function () { - cache = undefined; - fileName = undefined; - projectVersion = undefined; - }, - set: function (file, suggestions, version) { - cache = suggestions; - fileName = file; - if (version) { - projectVersion = version; - } - }, - get: function (file, checker, version) { - if (file !== fileName) { - return undefined; - } - if (version) { - return projectVersion === version ? cache : undefined; - } - ts.forEach(cache, function (suggestion) { - var _a, _b, _c; - // If the symbol/moduleSymbol was a merged symbol, it will have a new identity - // in the checker, even though the symbols to merge are the same (guaranteed by - // cache invalidation in synchronizeHostData). - if ((_a = suggestion.symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) { - suggestion.symbol = checker.getMergedSymbol(suggestion.origin.isDefaultExport - ? (_b = suggestion.symbol.declarations[0].localSymbol) !== null && _b !== void 0 ? _b : suggestion.symbol.declarations[0].symbol - : suggestion.symbol.declarations[0].symbol); - } - if ((_c = suggestion.origin.moduleSymbol.declarations) === null || _c === void 0 ? void 0 : _c.length) { - suggestion.origin.moduleSymbol = checker.getMergedSymbol(suggestion.origin.moduleSymbol.declarations[0].symbol); - } - }); - return cache; - }, - }; - } - Completions.createImportSuggestionsForFileCache = createImportSuggestionsForFileCache; function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); @@ -119898,6 +123714,13 @@ var ts; if (triggerCharacter && !ts.isInString(sourceFile, position, contextToken) && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) { return undefined; } + if (triggerCharacter === " ") { + // `isValidTrigger` ensures we are at `import |` + if (preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) { + return { isGlobalCompletion: true, isMemberCompletion: false, isNewIdentifierLocation: true, isIncomplete: true, entries: [] }; + } + return undefined; + } var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, contextToken, typeChecker, compilerOptions, host, log, preferences); if (stringCompletions) { return stringCompletions; @@ -119921,6 +123744,8 @@ var ts; return jsdocCompletionInfo(ts.JsDoc.getJSDocTagCompletions()); case 3 /* JsDocParameterName */: return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag)); + case 4 /* Keywords */: + return specificKeywordCompletionInfo(completionData.keywords); default: return ts.Debug.assertNever(completionData); } @@ -119929,33 +123754,36 @@ var ts; function jsdocCompletionInfo(entries) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } + function specificKeywordCompletionInfo(keywords) { + return { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: false, + entries: keywords.map(function (k) { return ({ + name: ts.tokenToString(k), + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, + sortText: SortText.GlobalsOrKeywords, + }); }), + }; + } function getOptionalReplacementSpan(location) { // StringLiteralLike locations are handled separately in stringCompletions.ts return (location === null || location === void 0 ? void 0 : location.kind) === 78 /* Identifier */ ? ts.createTextSpanFromNode(location) : undefined; } function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { - var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextMap = completionData.symbolToSortTextMap; - if (location && location.parent && ts.isJsxClosingElement(location.parent)) { - // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, - // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. - // For example: - // var x =
" with type any - // And at `
` (with a closing `>`), the completion list will contain "div". - var tagName = location.parent.parent.openingElement.tagName; - var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 31 /* GreaterThanToken */, sourceFile); - var entry = { - name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), - kind: "class" /* classElement */, - kindModifiers: undefined, - sortText: SortText.LocationPriority, - }; - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, optionalReplacementSpan: getOptionalReplacementSpan(location), entries: [entry] }; + var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation, isJsxIdentifierExpected = completionData.isJsxIdentifierExpected, importCompletionNode = completionData.importCompletionNode, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextMap = completionData.symbolToSortTextMap; + // Verify if the file is JSX language variant + if (ts.getLanguageVariant(sourceFile.scriptKind) === 1 /* JSX */) { + var completionInfo = getJsxClosingTagCompletion(location, sourceFile); + if (completionInfo) { + return completionInfo; + } } var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, - /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); + /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { @@ -119963,7 +123791,7 @@ var ts; return undefined; } getCompletionEntriesFromSymbols(symbols, entries, - /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); + /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); } if (keywordFilters !== 0 /* None */) { var entryNames = new ts.Set(entries.map(function (e) { return e.name; })); @@ -119999,6 +123827,49 @@ var ts; return false; } } + function getJsxClosingTagCompletion(location, sourceFile) { + // We wanna walk up the tree till we find a JSX closing element + var jsxClosingElement = ts.findAncestor(location, function (node) { + switch (node.kind) { + case 277 /* JsxClosingElement */: + return true; + case 43 /* SlashToken */: + case 31 /* GreaterThanToken */: + case 78 /* Identifier */: + case 202 /* PropertyAccessExpression */: + return false; + default: + return "quit"; + } + }); + if (jsxClosingElement) { + // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, + // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. + // For example: + // var x =
" with type any + // And at `
` (with a closing `>`), the completion list will contain "div". + // And at property access expressions ` ` the completion will + // return full closing tag with an optional replacement span + // For example: + // var x = + // var y = + // the completion list at "1" and "2" will contain "MainComponent.Child" with a replacement span of closing tag name + var hasClosingAngleBracket = !!ts.findChildOfKind(jsxClosingElement, 31 /* GreaterThanToken */, sourceFile); + var tagName = jsxClosingElement.parent.openingElement.tagName; + var closingTag = tagName.getText(sourceFile); + var fullClosingTag = closingTag + (hasClosingAngleBracket ? "" : ">"); + var replacementSpan = ts.createTextSpanFromNode(jsxClosingElement.tagName); + var entry = { + name: fullClosingTag, + kind: "class" /* classElement */, + kindModifiers: undefined, + sortText: SortText.LocationPriority, + }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, optionalReplacementSpan: replacementSpan, entries: [entry] }; + } + return; + } function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location @@ -120025,9 +123896,13 @@ var ts; function createCompletionEntryForLiteral(sourceFile, preferences, literal) { return { name: completionNameForLiteral(sourceFile, preferences, literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority }; } - function createCompletionEntry(symbol, sortText, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { + function createCompletionEntry(symbol, sortText, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, options, preferences) { + var _a; var insertText; var replacementSpan = ts.getReplacementSpanForContextToken(contextToken); + var data; + var isSnippet; + var sourceDisplay; var insertQuestionDot = origin && originIsNullableMember(origin); var useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; if (origin && originIsThisType(origin)) { @@ -120071,9 +123946,24 @@ var ts; insertText = needsConvertPropertyAccess ? "" + awaitText + insertText : "" + awaitText + (insertQuestionDot ? "?." : ".") + insertText; replacementSpan = ts.createTextSpanFromBounds(propertyAccessToConvert.getStart(sourceFile), propertyAccessToConvert.end); } + if (originIsResolvedExport(origin)) { + ts.Debug.assertIsDefined(importCompletionNode); + (_a = getInsertTextAndReplacementSpanForImportCompletion(name, importCompletionNode, origin, useSemicolons, options, preferences), insertText = _a.insertText, replacementSpan = _a.replacementSpan); + sourceDisplay = [ts.textPart(origin.moduleSpecifier)]; + isSnippet = preferences.includeCompletionsWithSnippetText ? true : undefined; + } if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { return undefined; } + if (originIsExport(origin) || originIsResolvedExport(origin)) { + data = { + exportName: origin.exportName, + fileName: origin.fileName, + ambientModuleName: origin.fileName ? undefined : ts.stripQuotes(origin.moduleSymbol.name), + isPackageJsonImport: origin.isFromPackageJson ? true : undefined, + moduleSpecifier: originIsResolvedExport(origin) ? origin.moduleSpecifier : undefined, + }; + } // TODO(drosen): Right now we just permit *all* semantic meanings when calling // 'getSymbolKind' which is permissible given that it is backwards compatible; but // really we should consider passing the meaning for the node so that we don't report @@ -120091,9 +123981,30 @@ var ts; isRecommended: isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker) || undefined, insertText: insertText, replacementSpan: replacementSpan, + sourceDisplay: sourceDisplay, + isSnippet: isSnippet, isPackageJsonImport: originIsPackageJsonImport(origin) || undefined, + isImportStatementCompletion: originIsResolvedExport(origin) || undefined, + data: data, }; } + function getInsertTextAndReplacementSpanForImportCompletion(name, importCompletionNode, origin, useSemicolons, options, preferences) { + var sourceFile = importCompletionNode.getSourceFile(); + var replacementSpan = ts.createTextSpanFromNode(importCompletionNode, sourceFile); + var quotedModuleSpecifier = ts.quote(sourceFile, preferences, origin.moduleSpecifier); + var exportKind = origin.isDefaultExport ? 1 /* Default */ : + origin.exportName === "export=" /* ExportEquals */ ? 2 /* ExportEquals */ : + 0 /* Named */; + var tabStop = preferences.includeCompletionsWithSnippetText ? "$1" : ""; + var importKind = ts.codefix.getImportKind(sourceFile, exportKind, options); + var suffix = useSemicolons ? ";" : ""; + switch (importKind) { + case 3 /* CommonJS */: return { replacementSpan: replacementSpan, insertText: "import " + name + tabStop + " = require(" + quotedModuleSpecifier + ")" + suffix }; + case 1 /* Default */: return { replacementSpan: replacementSpan, insertText: "import " + name + tabStop + " from " + quotedModuleSpecifier + suffix }; + case 2 /* Namespace */: return { replacementSpan: replacementSpan, insertText: "import * as " + name + tabStop + " from " + quotedModuleSpecifier + suffix }; + case 0 /* Named */: return { replacementSpan: replacementSpan, insertText: "import { " + name + tabStop + " } from " + quotedModuleSpecifier + suffix }; + } + } function quotePropertyName(sourceFile, preferences, name) { if (/^\d+$/.test(name)) { return name; @@ -120108,29 +124019,31 @@ var ts; if (originIsExport(origin)) { return ts.stripQuotes(origin.moduleSymbol.name); } + if (originIsResolvedExport(origin)) { + return origin.moduleSpecifier; + } if ((origin === null || origin === void 0 ? void 0 : origin.kind) === 1 /* ThisType */) { return CompletionSource.ThisProperty; } } - function getCompletionEntriesFromSymbols(symbols, entries, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) { + function getCompletionEntriesFromSymbols(symbols, entries, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) { var start = ts.timestamp(); + var variableDeclaration = getVariableDeclaration(location); + var useSemicolons = ts.probablyUsesSemicolons(sourceFile); // Tracks unique names. // Value is set to false for global variables or completions from external module exports, because we can have multiple of those; // true otherwise. Based on the order we add things we will always see locals first, then globals, then module exports. // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. var uniques = new ts.Map(); - for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { - var symbol = symbols_1[_i]; - var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; + for (var i = 0; i < symbols.length; i++) { + var symbol = symbols[i]; + var origin = symbolToOriginInfoMap === null || symbolToOriginInfoMap === void 0 ? void 0 : symbolToOriginInfoMap[i]; var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, !!jsxIdentifierExpected); - if (!info) { + if (!info || uniques.get(info.name) || kind === 1 /* Global */ && symbolToSortTextMap && !shouldIncludeSymbol(symbol, symbolToSortTextMap)) { continue; } var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; - if (uniques.get(name)) { - continue; - } - var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); + var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, compilerOptions, preferences); if (!entry) { continue; } @@ -120147,6 +124060,46 @@ var ts; has: function (name) { return uniques.has(name); }, add: function (name) { return uniques.set(name, true); }, }; + function shouldIncludeSymbol(symbol, symbolToSortTextMap) { + if (!ts.isSourceFile(location)) { + // export = /**/ here we want to get all meanings, so any symbol is ok + if (ts.isExportAssignment(location.parent)) { + return true; + } + // Filter out variables from their own initializers + // `const a = /* no 'a' here */` + if (variableDeclaration && symbol.valueDeclaration === variableDeclaration) { + return false; + } + // External modules can have global export declarations that will be + // available as global keywords in all scopes. But if the external module + // already has an explicit export and user only wants to user explicit + // module imports then the global keywords will be filtered out so auto + // import suggestions will win in the completion + var symbolOrigin = ts.skipAlias(symbol, typeChecker); + // We only want to filter out the global keywords + // Auto Imports are not available for scripts so this conditional is always false + if (!!sourceFile.externalModuleIndicator + && !compilerOptions.allowUmdGlobalAccess + && symbolToSortTextMap[ts.getSymbolId(symbol)] === SortText.GlobalsOrKeywords + && (symbolToSortTextMap[ts.getSymbolId(symbolOrigin)] === SortText.AutoImportSuggestions + || symbolToSortTextMap[ts.getSymbolId(symbolOrigin)] === SortText.LocationPriority)) { + return false; + } + // Continue with origin symbol + symbol = symbolOrigin; + // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) + if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { + return !!(symbol.flags & 1920 /* Namespace */); + } + if (isTypeOnlyLocation) { + // It's a type, but you can reach it by namespace.type as well + return symbolCanBeReferencedAtTypeLocation(symbol, typeChecker); + } + } + // expressions are value space (which includes the value namespaces) + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 111551 /* Value */); + } } Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; function getLabelCompletionAtPosition(node) { @@ -120180,6 +124133,20 @@ var ts; return entries; } function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences) { + if (entryId.data) { + var autoImport = getAutoImportSymbolFromCompletionEntryData(entryId.name, entryId.data, program, host); + if (autoImport) { + return { + type: "symbol", + symbol: autoImport.symbol, + location: ts.getTouchingPropertyName(sourceFile, position), + previousToken: ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined), + isJsxInitializer: false, + isTypeOnlyLocation: false, + origin: autoImport.origin, + }; + } + } var compilerOptions = program.getCompilerOptions(); var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId, host); if (!completionData) { @@ -120196,11 +124163,11 @@ var ts; // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - return ts.firstDefined(symbols, function (symbol) { - var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + return ts.firstDefined(symbols, function (symbol, index) { + var origin = symbolToOriginInfoMap[index]; var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind, completionData.isJsxIdentifierExpected); return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source - ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation } + ? { type: "symbol", symbol: symbol, location: location, origin: origin, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation } : undefined; }) || { type: "none" }; } @@ -120210,7 +124177,7 @@ var ts; var name = entryId.name; var contextToken = ts.findPrecedingToken(position, sourceFile); if (ts.isInString(sourceFile, position, contextToken)) { - return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken); + return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken, preferences); } // Compute all the completion symbols again. var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences); @@ -120224,13 +124191,15 @@ var ts; return ts.JsDoc.getJSDocTagCompletionDetails(name); case 3 /* JsDocParameterName */: return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); + case 4 /* Keywords */: + return request.keywords.indexOf(ts.stringToToken(name)) > -1 ? createSimpleDetails(name, "keyword" /* keyword */, ts.SymbolDisplayPartKind.keyword) : undefined; default: return ts.Debug.assertNever(request); } } case "symbol": { - var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, origin = symbolCompletion.origin, previousToken = symbolCompletion.previousToken; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(origin, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, entryId.data), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } case "literal": { @@ -120256,15 +124225,17 @@ var ts; } Completions.createCompletionDetailsForSymbol = createCompletionDetailsForSymbol; function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { - return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; + return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source, sourceDisplay: source }; } Completions.createCompletionDetails = createCompletionDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) { - var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { + function getCompletionEntryCodeActionsAndSourceDisplay(origin, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data) { + if (data === null || data === void 0 ? void 0 : data.moduleSpecifier) { + return { codeActions: undefined, sourceDisplay: [ts.textPart(data.moduleSpecifier)] }; + } + if (!origin || !originIsExport(origin)) { return { codeActions: undefined, sourceDisplay: undefined }; } - var moduleSymbol = symbolOriginInfo.moduleSymbol; + var moduleSymbol = origin.moduleSymbol; var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, compilerOptions.target), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; @@ -120280,6 +124251,7 @@ var ts; CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName"; CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag"; CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName"; + CompletionDataKind[CompletionDataKind["Keywords"] = 4] = "Keywords"; })(CompletionDataKind || (CompletionDataKind = {})); var CompletionKind; (function (CompletionKind) { @@ -120307,11 +124279,11 @@ var ts; return ts.getContextualTypeFromParent(previousToken, checker); case 62 /* EqualsToken */: switch (parent.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return checker.getContextualType(parent.initializer); // TODO: GH#18217 - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return checker.getTypeAtLocation(parent.left); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return checker.getContextualTypeForJsxAttribute(parent); default: return undefined; @@ -120321,7 +124293,7 @@ var ts; case 81 /* CaseKeyword */: return ts.getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); case 18 /* OpenBraceToken */: - return ts.isJsxExpression(parent) && parent.parent.kind !== 273 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; + return ts.isJsxExpression(parent) && parent.parent.kind !== 274 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; default: var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile); return argInfo ? @@ -120340,7 +124312,8 @@ var ts; return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); } function isModuleSymbol(symbol) { - return symbol.declarations.some(function (d) { return d.kind === 297 /* SourceFile */; }); + var _a; + return !!((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d.kind === 298 /* SourceFile */; })); } function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId, host) { var typeChecker = program.getTypeChecker(); @@ -120391,11 +124364,11 @@ var ts; if (tag.tagName.pos <= position && position <= tag.tagName.end) { return { kind: 1 /* JsDocTagName */ }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 301 /* JSDocTypeExpression */) { + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 302 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 333 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 337 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -120420,7 +124393,7 @@ var ts; var contextToken = previousToken; // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. - if (contextToken && position <= contextToken.end && (ts.isIdentifierOrPrivateIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { + if (contextToken && position <= contextToken.end && (ts.isMemberName(contextToken) || ts.isKeyword(contextToken.kind))) { var start_1 = ts.timestamp(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1)); @@ -120436,10 +124409,22 @@ var ts; var isStartingCloseTag = false; var isJsxInitializer = false; var isJsxIdentifierExpected = false; + var importCompletionNode; var location = ts.getTouchingPropertyName(sourceFile, position); if (contextToken) { + var importCompletionCandidate = getImportCompletionNode(contextToken); + if (importCompletionCandidate === 153 /* FromKeyword */) { + return { kind: 4 /* Keywords */, keywords: [153 /* FromKeyword */] }; + } + // Import statement completions use `insertText`, and also require the `data` property of `CompletionEntryIdentifier` + // added in TypeScript 4.3 to be sent back from the client during `getCompletionEntryDetails`. Since this feature + // is not backward compatible with older clients, the language service defaults to disabling it, allowing newer clients + // to opt in with the `includeCompletionsForImportStatements` user preference. + if (importCompletionCandidate && preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) { + importCompletionNode = importCompletionCandidate; + } // Bail out if this is a known invalid completion location - if (isCompletionListBlocker(contextToken)) { + if (!importCompletionNode && isCompletionListBlocker(contextToken)) { log("Returning an empty list because completion was requested in an invalid position."); return undefined; } @@ -120448,7 +124433,7 @@ var ts; isRightOfDot = contextToken.kind === 24 /* DotToken */; isRightOfQuestionDot = contextToken.kind === 28 /* QuestionDotToken */; switch (parent.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: propertyAccessToConvert = parent; node = propertyAccessToConvert.expression; if ((ts.isCallExpression(node) || ts.isFunctionLike(node)) && @@ -120461,14 +124446,14 @@ var ts; return undefined; } break; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: node = parent.left; break; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: node = parent.name; break; - case 195 /* ImportType */: - case 226 /* MetaProperty */: + case 196 /* ImportType */: + case 227 /* MetaProperty */: node = parent; break; default: @@ -120477,11 +124462,11 @@ var ts; return undefined; } } - else if (sourceFile.languageVariant === 1 /* JSX */) { + else if (!importCompletionNode && sourceFile.languageVariant === 1 /* JSX */) { // // If the tagname is a property access expression, we will then walk up to the top most of property access expression. // Then, try to get a JSX container and its associated attributes type. - if (parent && parent.kind === 201 /* PropertyAccessExpression */) { + if (parent && parent.kind === 202 /* PropertyAccessExpression */) { contextToken = parent; parent = parent.parent; } @@ -120489,45 +124474,45 @@ var ts; if (currentToken.parent === location) { switch (currentToken.kind) { case 31 /* GreaterThanToken */: - if (currentToken.parent.kind === 273 /* JsxElement */ || currentToken.parent.kind === 275 /* JsxOpeningElement */) { + if (currentToken.parent.kind === 274 /* JsxElement */ || currentToken.parent.kind === 276 /* JsxOpeningElement */) { location = currentToken; } break; case 43 /* SlashToken */: - if (currentToken.parent.kind === 274 /* JsxSelfClosingElement */) { + if (currentToken.parent.kind === 275 /* JsxSelfClosingElement */) { location = currentToken; } break; } } switch (parent.kind) { - case 276 /* JsxClosingElement */: + case 277 /* JsxClosingElement */: if (contextToken.kind === 43 /* SlashToken */) { isStartingCloseTag = true; location = contextToken; } break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (!binaryExpressionMayBeOpenTag(parent)) { break; } // falls through - case 274 /* JsxSelfClosingElement */: - case 273 /* JsxElement */: - case 275 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + case 274 /* JsxElement */: + case 276 /* JsxOpeningElement */: isJsxIdentifierExpected = true; if (contextToken.kind === 29 /* LessThanToken */) { isRightOfOpenTag = true; location = contextToken; } break; - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: // For `
`, `parent` will be `{true}` and `previousToken` will be `}` if (previousToken.kind === 19 /* CloseBraceToken */ && currentToken.kind === 31 /* GreaterThanToken */) { isJsxIdentifierExpected = true; } break; - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: // For `
`, `parent` will be JsxAttribute and `previousToken` will be its initializer if (parent.initializer === previousToken && previousToken.end < position) { @@ -120561,8 +124546,11 @@ var ts; var symbols = []; var symbolToOriginInfoMap = []; var symbolToSortTextMap = []; - var importSuggestionsCache = host.getImportSuggestionsCache && host.getImportSuggestionsCache(); + var seenPropertySymbols = new ts.Map(); var isTypeOnly = isTypeOnlyCompletion(); + var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { + return ts.createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); + }); if (isRightOfDot || isRightOfQuestionDot) { getTypeScriptMemberSymbols(); } @@ -120571,7 +124559,7 @@ var ts; ts.Debug.assertEachIsDefined(tagSymbols, "getJsxIntrinsicTagNames() should all be defined"); tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); - completionKind = 3 /* MemberLike */; + completionKind = 1 /* Global */; keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { @@ -120580,7 +124568,7 @@ var ts; if (tagSymbol) { symbols = [tagSymbol]; } - completionKind = 3 /* MemberLike */; + completionKind = 1 /* Global */; keywordFilters = 0 /* None */; } else { @@ -120613,14 +124601,15 @@ var ts; symbolToSortTextMap: symbolToSortTextMap, isTypeOnlyLocation: isTypeOnly, isJsxIdentifierExpected: isJsxIdentifierExpected, + importCompletionNode: importCompletionNode, }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 326 /* JSDocParameterTag */: - case 333 /* JSDocPropertyTag */: - case 327 /* JSDocReturnTag */: - case 329 /* JSDocTypeTag */: - case 331 /* JSDocTypedefTag */: + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: + case 331 /* JSDocReturnTag */: + case 333 /* JSDocTypeTag */: + case 335 /* JSDocTypedefTag */: return true; default: return false; @@ -120648,10 +124637,10 @@ var ts; var exportedSymbols = typeChecker.getExportsOfModule(symbol); ts.Debug.assertEachIsDefined(exportedSymbols, "getExportsOfModule() should all be defined"); var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess(isImportType ? node : (node.parent), symbol.name); }; - var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; + var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol, typeChecker); }; var isValidAccess = isNamespaceName // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion. - ? function (symbol) { return !!(symbol.flags & 1920 /* Namespace */) && !symbol.declarations.every(function (d) { return d.parent === node.parent; }); } + ? function (symbol) { var _a; return !!(symbol.flags & 1920 /* Namespace */) && !((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return d.parent === node.parent; })); } : isRhsOfImportDeclaration ? // Any kind is allowed when dotting off namespace in internal import equals declaration function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : @@ -120665,7 +124654,7 @@ var ts; // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). if (!isTypeLocation && symbol.declarations && - symbol.declarations.some(function (d) { return d.kind !== 297 /* SourceFile */ && d.kind !== 256 /* ModuleDeclaration */ && d.kind !== 255 /* EnumDeclaration */; })) { + symbol.declarations.some(function (d) { return d.kind !== 298 /* SourceFile */ && d.kind !== 257 /* ModuleDeclaration */ && d.kind !== 256 /* EnumDeclaration */; })) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { @@ -120712,7 +124701,7 @@ var ts; if (isRightOfQuestionDot && ts.some(type.getCallSignatures())) { isNewIdentifierLocation = true; } - var propertyAccess = node.kind === 195 /* ImportType */ ? node : node.parent; + var propertyAccess = node.kind === 196 /* ImportType */ ? node : node.parent; if (isUncheckedFile) { // In javascript files, for union types, we don't just get the members that // the individual types have in common, we also include all the members that @@ -120751,13 +124740,24 @@ var ts; var nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName); // If this is nested like for `namespace N { export const sym = Symbol(); }`, we'll add the completion for `N`. var firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker); - if (firstAccessibleSymbol && !symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)]) { + if (firstAccessibleSymbol && ts.addToSeen(seenPropertySymbols, ts.getSymbolId(firstAccessibleSymbol))) { + var index = symbols.length; symbols.push(firstAccessibleSymbol); var moduleSymbol = firstAccessibleSymbol.parent; - symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] = - !moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol) - ? { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) } - : { kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), moduleSymbol: moduleSymbol, isDefaultExport: false }; + if (!moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol)) { + symbolToOriginInfoMap[index] = { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) }; + } + else { + var origin = { + kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), + moduleSymbol: moduleSymbol, + isDefaultExport: false, + symbolName: firstAccessibleSymbol.name, + exportName: firstAccessibleSymbol.name, + fileName: ts.isExternalModuleNameRelative(ts.stripQuotes(moduleSymbol.name)) ? ts.cast(moduleSymbol.valueDeclaration, ts.isSourceFile).fileName : undefined, + }; + symbolToOriginInfoMap[index] = origin; + } } else if (preferences.includeCompletionsWithInsertText) { addSymbolOriginInfo(symbol); @@ -120777,11 +124777,11 @@ var ts; } function addSymbolOriginInfo(symbol) { if (preferences.includeCompletionsWithInsertText) { - if (insertAwait && !symbolToOriginInfoMap[ts.getSymbolId(symbol)]) { - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: getNullableSymbolOriginInfoKind(8 /* Promise */) }; + if (insertAwait && ts.addToSeen(seenPropertySymbols, ts.getSymbolId(symbol))) { + symbolToOriginInfoMap[symbols.length] = { kind: getNullableSymbolOriginInfoKind(8 /* Promise */) }; } else if (insertQuestionDot) { - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 16 /* Nullable */ }; + symbolToOriginInfoMap[symbols.length] = { kind: 16 /* Nullable */ }; } } } @@ -120794,7 +124794,9 @@ var ts; return ts.isIdentifier(e) ? e : ts.isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : undefined; } function tryGetGlobalSymbols() { - var result = tryGetObjectLikeCompletionSymbols() + var result = tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() + || tryGetObjectLikeCompletionSymbols() + || tryGetImportCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() || tryGetLocalNamedExportCompletionSymbols() || tryGetConstructorCompletion() @@ -120827,11 +124829,17 @@ var ts; isNewIdentifierLocation = false; return 1 /* Success */; } + function tryGetImportCompletionSymbols() { + if (!importCompletionNode) + return 0 /* Continue */; + collectAutoImports(/*resolveModuleSpecifiers*/ true); + return 1 /* Success */; + } function getGlobalCompletions() { keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; - isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); + isNewIdentifierLocation = isNewIdentifierDefinitionLocation(); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); } @@ -120868,50 +124876,36 @@ var ts; var symbolMeanings = (isTypeOnly ? 0 /* None */ : 111551 /* Value */) | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); ts.Debug.assertEachIsDefined(symbols, "getSymbolsInScope() should all be defined"); - for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { - var symbol = symbols_2[_i]; + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; if (!typeChecker.isArgumentsSymbol(symbol) && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === sourceFile; })) { symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.GlobalsOrKeywords; } } // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` - if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 297 /* SourceFile */) { + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 298 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { for (var _a = 0, _b = getPropertiesForCompletion(thisType, typeChecker); _a < _b.length; _a++) { var symbol = _b[_a]; - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 1 /* ThisType */ }; + symbolToOriginInfoMap[symbols.length] = { kind: 1 /* ThisType */ }; symbols.push(symbol); symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.SuggestedClassMembers; } } } - if (shouldOfferImportCompletions()) { - var lowerCaseTokenText_1 = previousToken && ts.isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; - var autoImportSuggestions = getSymbolsFromOtherSourceFileExports(program.getCompilerOptions().target, host); - if (!detailsEntryId && importSuggestionsCache) { - importSuggestionsCache.set(sourceFile.fileName, autoImportSuggestions, host.getProjectVersion && host.getProjectVersion()); - } - autoImportSuggestions.forEach(function (_a) { - var symbol = _a.symbol, symbolName = _a.symbolName, skipFilter = _a.skipFilter, origin = _a.origin; - if (detailsEntryId) { - if (detailsEntryId.source && ts.stripQuotes(origin.moduleSymbol.name) !== detailsEntryId.source) { - return; - } - } - else if (!skipFilter && !stringContainsCharactersInOrder(symbolName.toLowerCase(), lowerCaseTokenText_1)) { - return; - } - var symbolId = ts.getSymbolId(symbol); - symbols.push(symbol); - symbolToOriginInfoMap[symbolId] = origin; - symbolToSortTextMap[symbolId] = SortText.AutoImportSuggestions; - }); + collectAutoImports(/*resolveModuleSpecifier*/ false); + if (isTypeOnly) { + keywordFilters = contextToken && ts.isAssertionExpression(contextToken.parent) + ? 6 /* TypeAssertionKeywords */ + : 7 /* TypeKeywords */; } - filterGlobalCompletion(symbols); } function shouldOfferImportCompletions() { + // If already typing an import statement, provide completions for it. + if (importCompletionNode) + return true; // If current completion is for non-contextual Object literal shortahands, ignore auto-import symbols if (isNonContextualObjectLiteral) return false; @@ -120929,42 +124923,15 @@ var ts; } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { - case 297 /* SourceFile */: - case 218 /* TemplateExpression */: - case 283 /* JsxExpression */: - case 230 /* Block */: + case 298 /* SourceFile */: + case 219 /* TemplateExpression */: + case 284 /* JsxExpression */: + case 231 /* Block */: return true; default: return ts.isStatement(scopeNode); } } - function filterGlobalCompletion(symbols) { - var isTypeOnly = isTypeOnlyCompletion(); - if (isTypeOnly) { - keywordFilters = contextToken && ts.isAssertionExpression(contextToken.parent) - ? 6 /* TypeAssertionKeywords */ - : 7 /* TypeKeywords */; - } - ts.filterMutate(symbols, function (symbol) { - if (!ts.isSourceFile(location)) { - // export = /**/ here we want to get all meanings, so any symbol is ok - if (ts.isExportAssignment(location.parent)) { - return true; - } - symbol = ts.skipAlias(symbol, typeChecker); - // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) - if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { - return !!(symbol.flags & 1920 /* Namespace */); - } - if (isTypeOnly) { - // It's a type, but you can reach it by namespace.type as well - return symbolCanBeReferencedAtTypeLocation(symbol); - } - } - // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 111551 /* Value */); - }); - } function isTypeOnlyCompletion() { return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && @@ -120974,191 +124941,105 @@ var ts; } function isContextTokenValueLocation(contextToken) { return contextToken && - contextToken.kind === 111 /* TypeOfKeyword */ && - (contextToken.parent.kind === 176 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); + ((contextToken.kind === 111 /* TypeOfKeyword */ && + (contextToken.parent.kind === 177 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent))) || + (contextToken.kind === 127 /* AssertsKeyword */ && contextToken.parent.kind === 173 /* TypePredicate */)); } function isContextTokenTypeLocation(contextToken) { if (contextToken) { var parentKind = contextToken.parent.kind; switch (contextToken.kind) { case 58 /* ColonToken */: - return parentKind === 163 /* PropertyDeclaration */ || - parentKind === 162 /* PropertySignature */ || - parentKind === 160 /* Parameter */ || - parentKind === 249 /* VariableDeclaration */ || + return parentKind === 164 /* PropertyDeclaration */ || + parentKind === 163 /* PropertySignature */ || + parentKind === 161 /* Parameter */ || + parentKind === 250 /* VariableDeclaration */ || ts.isFunctionLikeKind(parentKind); case 62 /* EqualsToken */: - return parentKind === 254 /* TypeAliasDeclaration */; + return parentKind === 255 /* TypeAliasDeclaration */; case 126 /* AsKeyword */: - return parentKind === 224 /* AsExpression */; + return parentKind === 225 /* AsExpression */; case 29 /* LessThanToken */: - return parentKind === 173 /* TypeReference */ || - parentKind === 206 /* TypeAssertionExpression */; + return parentKind === 174 /* TypeReference */ || + parentKind === 207 /* TypeAssertionExpression */; case 93 /* ExtendsKeyword */: - return parentKind === 159 /* TypeParameter */; + return parentKind === 160 /* TypeParameter */; } } return false; } - /** True if symbol is a type or a module containing at least one type. */ - function symbolCanBeReferencedAtTypeLocation(symbol, seenModules) { - if (seenModules === void 0) { seenModules = new ts.Map(); } - var sym = ts.skipAlias(symbol.exportSymbol || symbol, typeChecker); - return !!(sym.flags & 788968 /* Type */) || - !!(sym.flags & 1536 /* Module */) && - ts.addToSeen(seenModules, ts.getSymbolId(sym)) && - typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); - } - /** - * Gathers symbols that can be imported from other files, de-duplicating along the way. Symbols can be "duplicates" - * if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but - * it’s just an alias to the first, and both have the same name, so we generally want to filter those aliases out, - * if and only if the the first can be imported (it may be excluded due to package.json filtering in - * `codefix.forEachExternalModuleToImportFrom`). - * - * Example. Imagine a chain of node_modules re-exporting one original symbol: - * - * ```js - * node_modules/x/index.js node_modules/y/index.js node_modules/z/index.js - * +-----------------------+ +--------------------------+ +--------------------------+ - * | | | | | | - * | export const foo = 0; | <--- | export { foo } from 'x'; | <--- | export { foo } from 'y'; | - * | | | | | | - * +-----------------------+ +--------------------------+ +--------------------------+ - * ``` - * - * Also imagine three buckets, which we’ll reference soon: - * - * ```md - * | | | | | | - * | **Bucket A** | | **Bucket B** | | **Bucket C** | - * | Symbols to | | Aliases to symbols | | Symbols to return | - * | definitely | | in Buckets A or C | | if nothing better | - * | return | | (don’t return these) | | comes along | - * |__________________| |______________________| |___________________| - * ``` - * - * We _probably_ want to show `foo` from 'x', but not from 'y' or 'z'. However, if 'x' is not in a package.json, it - * will not appear in a `forEachExternalModuleToImportFrom` iteration. Furthermore, the order of iterations is not - * guaranteed, as it is host-dependent. Therefore, when presented with the symbol `foo` from module 'y' alone, we - * may not be sure whether or not it should go in the list. So, we’ll take the following steps: - * - * 1. Resolve alias `foo` from 'y' to the export declaration in 'x', get the symbol there, and see if that symbol is - * already in Bucket A (symbols we already know will be returned). If it is, put `foo` from 'y' in Bucket B - * (symbols that are aliases to symbols in Bucket A). If it’s not, put it in Bucket C. - * 2. Next, imagine we see `foo` from module 'z'. Again, we resolve the alias to the nearest export, which is in 'y'. - * At this point, if that nearest export from 'y' is in _any_ of the three buckets, we know the symbol in 'z' - * should never be returned in the final list, so put it in Bucket B. - * 3. Next, imagine we see `foo` from module 'x', the original. Syntactically, it doesn’t look like a re-export, so - * we can just check Bucket C to see if we put any aliases to the original in there. If they exist, throw them out. - * Put this symbol in Bucket A. - * 4. After we’ve iterated through every symbol of every module, any symbol left in Bucket C means that step 3 didn’t - * occur for that symbol---that is, the original symbol is not in Bucket A, so we should include the alias. Move - * everything from Bucket C to Bucket A. - */ - function getSymbolsFromOtherSourceFileExports(target, host) { - var cached = importSuggestionsCache && importSuggestionsCache.get(sourceFile.fileName, typeChecker, detailsEntryId && host.getProjectVersion ? host.getProjectVersion() : undefined); - if (cached) { - log("getSymbolsFromOtherSourceFileExports: Using cached list"); - return cached; - } - var startTime = ts.timestamp(); - log("getSymbolsFromOtherSourceFileExports: Recomputing list" + (detailsEntryId ? " for details entry" : "")); - var seenResolvedModules = new ts.Map(); - var seenExports = new ts.Map(); - /** Bucket B */ - var aliasesToAlreadyIncludedSymbols = new ts.Map(); - /** Bucket C */ - var aliasesToReturnIfOriginalsAreMissing = new ts.Map(); - /** Bucket A */ - var results = []; - /** Ids present in `results` for faster lookup */ - var resultSymbolIds = new ts.Map(); - ts.codefix.forEachExternalModuleToImportFrom(program, host, sourceFile, !detailsEntryId, /*useAutoImportProvider*/ true, function (moduleSymbol, _, program, isFromPackageJson) { - // Perf -- ignore other modules if this is a request for details - if (detailsEntryId && detailsEntryId.source && ts.stripQuotes(moduleSymbol.name) !== detailsEntryId.source) { - return; - } - var typeChecker = program.getTypeChecker(); - var resolvedModuleSymbol = typeChecker.resolveExternalModuleSymbol(moduleSymbol); - // resolvedModuleSymbol may be a namespace. A namespace may be `export =` by multiple module declarations, but only keep the first one. - if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { + /** Mutates `symbols`, `symbolToOriginInfoMap`, and `symbolToSortTextMap` */ + function collectAutoImports(resolveModuleSpecifiers) { + var _a, _b, _c, _d, _e; + if (!shouldOfferImportCompletions()) + return; + ts.Debug.assert(!(detailsEntryId === null || detailsEntryId === void 0 ? void 0 : detailsEntryId.data)); + var start = ts.timestamp(); + var moduleSpecifierCache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); + (_b = host.log) === null || _b === void 0 ? void 0 : _b.call(host, "collectAutoImports: starting, " + (resolveModuleSpecifiers ? "" : "not ") + "resolving module specifiers"); + if (moduleSpecifierCache) { + (_c = host.log) === null || _c === void 0 ? void 0 : _c.call(host, "collectAutoImports: module specifier cache size: " + moduleSpecifierCache.count()); + } + var lowerCaseTokenText = previousToken && ts.isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; + var exportInfo = ts.codefix.getSymbolToExportInfoMap(sourceFile, host, program); + var packageJsonAutoImportProvider = (_d = host.getPackageJsonAutoImportProvider) === null || _d === void 0 ? void 0 : _d.call(host); + var packageJsonFilter = detailsEntryId ? undefined : ts.createPackageJsonImportFilter(sourceFile, host); + exportInfo.forEach(function (info, key) { + var symbolName = key.substring(0, key.indexOf("|")); + if (!detailsEntryId && ts.isStringANonContextualKeyword(symbolName)) return; + var isCompletionDetailsMatch = detailsEntryId && ts.some(info, function (i) { return detailsEntryId.source === ts.stripQuotes(i.moduleSymbol.name); }); + if (isCompletionDetailsMatch || isNameMatch(symbolName)) { + // If we don't need to resolve module specifiers, we can use any re-export that is importable at all + // (We need to ensure that at least one is importable to show a completion.) + var _a = resolveModuleSpecifiers + ? ts.codefix.getModuleSpecifierForBestExportInfo(info, sourceFile, program, host, preferences) + : { moduleSpecifier: undefined, exportInfo: ts.find(info, isImportableExportInfo) }, moduleSpecifier = _a.moduleSpecifier, exportInfo_1 = _a.exportInfo; + if (!exportInfo_1) + return; + var moduleFile = ts.tryCast(exportInfo_1.moduleSymbol.valueDeclaration, ts.isSourceFile); + var isDefaultExport = exportInfo_1.exportKind === 1 /* Default */; + var symbol = isDefaultExport && ts.getLocalSymbolForExportDefault(exportInfo_1.symbol) || exportInfo_1.symbol; + pushAutoImportSymbol(symbol, { + kind: resolveModuleSpecifiers ? 32 /* ResolvedExport */ : 4 /* Export */, + moduleSpecifier: moduleSpecifier, + symbolName: symbolName, + exportName: exportInfo_1.exportKind === 2 /* ExportEquals */ ? "export=" /* ExportEquals */ : exportInfo_1.symbol.name, + fileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, + isDefaultExport: isDefaultExport, + moduleSymbol: exportInfo_1.moduleSymbol, + isFromPackageJson: exportInfo_1.isFromPackageJson, + }); } - // Don't add another completion for `export =` of a symbol that's already global. - // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. - if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, ts.isNonGlobalDeclaration)) { - pushSymbol(resolvedModuleSymbol, moduleSymbol, isFromPackageJson, /*skipFilter*/ true); - } - for (var _i = 0, _a = typeChecker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { - var symbol = _a[_i]; - var symbolId = ts.getSymbolId(symbol).toString(); - // `getExportsAndPropertiesOfModule` can include duplicates - if (!ts.addToSeen(seenExports, symbolId)) { - continue; - } - // If this is `export { _break as break };` (a keyword) -- skip this and prefer the keyword completion. - if (ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.propertyName && ts.isIdentifierANonContextualKeyword(d.name); })) { - continue; - } - // If `symbol.parent !== moduleSymbol`, this is an `export * from "foo"` re-export. Those don't create new symbols. - var isExportStarFromReExport = typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol; - // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). - if (isExportStarFromReExport || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !d.propertyName && !!d.parent.parent.moduleSpecifier; })) { - // Walk the export chain back one module (step 1 or 2 in diagrammed example). - // Or, in the case of `export * from "foo"`, `symbol` already points to the original export, so just use that. - var nearestExportSymbol = isExportStarFromReExport ? symbol : getNearestExportSymbol(symbol); - if (!nearestExportSymbol) - continue; - var nearestExportSymbolId = ts.getSymbolId(nearestExportSymbol).toString(); - var symbolHasBeenSeen = resultSymbolIds.has(nearestExportSymbolId) || aliasesToAlreadyIncludedSymbols.has(nearestExportSymbolId); - if (!symbolHasBeenSeen) { - aliasesToReturnIfOriginalsAreMissing.set(nearestExportSymbolId, { alias: symbol, moduleSymbol: moduleSymbol, isFromPackageJson: isFromPackageJson }); - aliasesToAlreadyIncludedSymbols.set(symbolId, true); - } - else { - // Perf - we know this symbol is an alias to one that’s already covered in `symbols`, so store it here - // in case another symbol re-exports this one; that way we can short-circuit as soon as we see this symbol id. - ts.addToSeen(aliasesToAlreadyIncludedSymbols, symbolId); - } - } - else { - // This is not a re-export, so see if we have any aliases pending and remove them (step 3 in diagrammed example) - aliasesToReturnIfOriginalsAreMissing.delete(symbolId); - pushSymbol(symbol, moduleSymbol, isFromPackageJson, /*skipFilter*/ false); - } - } - }); - // By this point, any potential duplicates that were actually duplicates have been - // removed, so the rest need to be added. (Step 4 in diagrammed example) - aliasesToReturnIfOriginalsAreMissing.forEach(function (_a) { - var alias = _a.alias, moduleSymbol = _a.moduleSymbol, isFromPackageJson = _a.isFromPackageJson; - return pushSymbol(alias, moduleSymbol, isFromPackageJson, /*skipFilter*/ false); }); - log("getSymbolsFromOtherSourceFileExports: " + (ts.timestamp() - startTime)); - return results; - function pushSymbol(symbol, moduleSymbol, isFromPackageJson, skipFilter) { - var isDefaultExport = symbol.escapedName === "default" /* Default */; - if (isDefaultExport) { - symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; + (_e = host.log) === null || _e === void 0 ? void 0 : _e.call(host, "collectAutoImports: done in " + (ts.timestamp() - start) + " ms"); + function isNameMatch(symbolName) { + var lowerCaseSymbolName = symbolName.toLowerCase(); + if (resolveModuleSpecifiers && lowerCaseTokenText) { + // Use a more restrictive filter if resolving module specifiers since resolving module specifiers is expensive. + return lowerCaseTokenText[0] === lowerCaseSymbolName[0] && stringContainsCharactersInOrder(lowerCaseSymbolName, lowerCaseTokenText); } - if (typeChecker.isUndefinedSymbol(symbol)) { - return; + return stringContainsCharactersInOrder(lowerCaseSymbolName, lowerCaseTokenText); + } + function isImportableExportInfo(info) { + var moduleFile = ts.tryCast(info.moduleSymbol.valueDeclaration, ts.isSourceFile); + if (!moduleFile) { + return packageJsonFilter + ? packageJsonFilter.allowsImportingAmbientModule(info.moduleSymbol, getModuleSpecifierResolutionHost(info.isFromPackageJson)) + : true; } - ts.addToSeen(resultSymbolIds, ts.getSymbolId(symbol)); - var origin = { kind: 4 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport, isFromPackageJson: isFromPackageJson }; - results.push({ - symbol: symbol, - symbolName: ts.getNameForExportedSymbol(symbol, target), - origin: origin, - skipFilter: skipFilter, - }); + return ts.isImportableFile(info.isFromPackageJson ? packageJsonAutoImportProvider : program, sourceFile, moduleFile, packageJsonFilter, getModuleSpecifierResolutionHost(info.isFromPackageJson), moduleSpecifierCache); } } - function getNearestExportSymbol(fromSymbol) { - return findAlias(typeChecker, fromSymbol, function (alias) { - return ts.some(alias.declarations, function (d) { return ts.isExportSpecifier(d) || !!d.localSymbol; }); - }); + function pushAutoImportSymbol(symbol, origin) { + var symbolId = ts.getSymbolId(symbol); + if (symbolToSortTextMap[symbolId] === SortText.GlobalsOrKeywords) { + // If an auto-importable symbol is available as a global, don't add the auto import + return; + } + symbolToOriginInfoMap[symbols.length] = origin; + symbolToSortTextMap[symbolId] = importCompletionNode ? SortText.LocationPriority : SortText.AutoImportSuggestions; + symbols.push(symbol); } /** * True if you could remove some characters in `a` to get `b`. @@ -121170,7 +125051,8 @@ var ts; return true; } var characterIndex = 0; - for (var strIndex = 0; strIndex < str.length; strIndex++) { + var len = str.length; + for (var strIndex = 0; strIndex < len; strIndex++) { if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) { characterIndex++; if (characterIndex === characters.length) { @@ -121206,7 +125088,7 @@ var ts; return true; } if (contextToken.kind === 31 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 275 /* JsxOpeningElement */) { + if (contextToken.parent.kind === 276 /* JsxOpeningElement */) { // Two possibilities: // 1.
/**/ // - contextToken: GreaterThanToken (before cursor) @@ -121216,54 +125098,56 @@ var ts; // - contextToken: GreaterThanToken (before cursor) // - location: GreaterThanToken (after cursor) // - same parent (JSXOpeningElement) - return location.parent.kind !== 275 /* JsxOpeningElement */; + return location.parent.kind !== 276 /* JsxOpeningElement */; } - if (contextToken.parent.kind === 276 /* JsxClosingElement */ || contextToken.parent.kind === 274 /* JsxSelfClosingElement */) { - return !!contextToken.parent.parent && contextToken.parent.parent.kind === 273 /* JsxElement */; + if (contextToken.parent.kind === 277 /* JsxClosingElement */ || contextToken.parent.kind === 275 /* JsxSelfClosingElement */) { + return !!contextToken.parent.parent && contextToken.parent.parent.kind === 274 /* JsxElement */; } } return false; } - function isNewIdentifierDefinitionLocation(previousToken) { - if (previousToken) { - var containingNodeKind = previousToken.parent.kind; + function isNewIdentifierDefinitionLocation() { + if (contextToken) { + var containingNodeKind = contextToken.parent.kind; // Previous token may have been a keyword that was converted to an identifier. - switch (keywordForNode(previousToken)) { + switch (keywordForNode(contextToken)) { case 27 /* CommaToken */: - return containingNodeKind === 203 /* CallExpression */ // func( a, | - || containingNodeKind === 166 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 204 /* NewExpression */ // new C(a, | - || containingNodeKind === 199 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 216 /* BinaryExpression */ // const x = (a, | - || containingNodeKind === 174 /* FunctionType */; // var x: (s: string, list| + return containingNodeKind === 204 /* CallExpression */ // func( a, | + || containingNodeKind === 167 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 205 /* NewExpression */ // new C(a, | + || containingNodeKind === 200 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 217 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 175 /* FunctionType */ // var x: (s: string, list| + || containingNodeKind === 201 /* ObjectLiteralExpression */; // const obj = { x, | case 20 /* OpenParenToken */: - return containingNodeKind === 203 /* CallExpression */ // func( | - || containingNodeKind === 166 /* Constructor */ // constructor( | - || containingNodeKind === 204 /* NewExpression */ // new C(a| - || containingNodeKind === 207 /* ParenthesizedExpression */ // const x = (a| - || containingNodeKind === 186 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + return containingNodeKind === 204 /* CallExpression */ // func( | + || containingNodeKind === 167 /* Constructor */ // constructor( | + || containingNodeKind === 205 /* NewExpression */ // new C(a| + || containingNodeKind === 208 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 187 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ case 22 /* OpenBracketToken */: - return containingNodeKind === 199 /* ArrayLiteralExpression */ // [ | - || containingNodeKind === 171 /* IndexSignature */ // [ | : string ] - || containingNodeKind === 158 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + return containingNodeKind === 200 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 172 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 159 /* ComputedPropertyName */; // [ | /* this can become an index signature */ case 139 /* ModuleKeyword */: // module | case 140 /* NamespaceKeyword */: // namespace | return true; case 24 /* DotToken */: - return containingNodeKind === 256 /* ModuleDeclaration */; // module A.| + return containingNodeKind === 257 /* ModuleDeclaration */; // module A.| case 18 /* OpenBraceToken */: - return containingNodeKind === 252 /* ClassDeclaration */; // class A{ | + return containingNodeKind === 253 /* ClassDeclaration */ // class A { | + || containingNodeKind === 201 /* ObjectLiteralExpression */; // const obj = { | case 62 /* EqualsToken */: - return containingNodeKind === 249 /* VariableDeclaration */ // const x = a| - || containingNodeKind === 216 /* BinaryExpression */; // x = a| + return containingNodeKind === 250 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 217 /* BinaryExpression */; // x = a| case 15 /* TemplateHead */: - return containingNodeKind === 218 /* TemplateExpression */; // `aa ${| + return containingNodeKind === 219 /* TemplateExpression */; // `aa ${| case 16 /* TemplateMiddle */: - return containingNodeKind === 228 /* TemplateSpan */; // `aa ${10} dd ${| + return containingNodeKind === 229 /* TemplateSpan */; // `aa ${10} dd ${| case 122 /* PublicKeyword */: case 120 /* PrivateKeyword */: case 121 /* ProtectedKeyword */: - return containingNodeKind === 163 /* PropertyDeclaration */; // class A{ public | + return containingNodeKind === 164 /* PropertyDeclaration */; // class A{ public | } } return false; @@ -121276,6 +125160,25 @@ var ts; return (ts.isRegularExpressionLiteral(contextToken) || ts.isStringTextContainingNode(contextToken)) && (ts.rangeContainsPositionExclusive(ts.createTextRangeFromSpan(ts.createTextSpanFromNode(contextToken)), position) || position === contextToken.end && (!!contextToken.isUnterminated || ts.isRegularExpressionLiteral(contextToken))); } + function tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() { + var typeLiteralNode = tryGetTypeLiteralNode(contextToken); + if (!typeLiteralNode) + return 0 /* Continue */; + var intersectionTypeNode = ts.isIntersectionTypeNode(typeLiteralNode.parent) ? typeLiteralNode.parent : undefined; + var containerTypeNode = intersectionTypeNode || typeLiteralNode; + var containerExpectedType = getConstraintOfTypeArgumentProperty(containerTypeNode, typeChecker); + if (!containerExpectedType) + return 0 /* Continue */; + var containerActualType = typeChecker.getTypeFromTypeNode(containerTypeNode); + var members = getPropertiesForCompletion(containerExpectedType, typeChecker); + var existingMembers = getPropertiesForCompletion(containerActualType, typeChecker); + var existingMemberEscapedNames = new ts.Set(); + existingMembers.forEach(function (s) { return existingMemberEscapedNames.add(s.escapedName); }); + symbols = ts.filter(members, function (s) { return !existingMemberEscapedNames.has(s.escapedName); }); + completionKind = 0 /* ObjectPropertyDeclaration */; + isNewIdentifierLocation = true; + return 1 /* Success */; + } /** * Aggregates relevant symbols for completion in object literals and object binding patterns. * Relevant symbols are stored in the captured 'symbols' variable. @@ -121290,7 +125193,7 @@ var ts; completionKind = 0 /* ObjectPropertyDeclaration */; var typeMembers; var existingMembers; - if (objectLikeContainer.kind === 200 /* ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 201 /* ObjectLiteralExpression */) { var instantiatedType = tryGetObjectLiteralContextualType(objectLikeContainer, typeChecker); // Check completions for Object property value shorthand if (instantiatedType === undefined) { @@ -121315,7 +125218,7 @@ var ts; } } else { - ts.Debug.assert(objectLikeContainer.kind === 196 /* ObjectBindingPattern */); + ts.Debug.assert(objectLikeContainer.kind === 197 /* ObjectBindingPattern */); // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -121326,12 +125229,12 @@ var ts; // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function - var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 239 /* ForOfStatement */; - if (!canGetType && rootDeclaration.kind === 160 /* Parameter */) { + var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 240 /* ForOfStatement */; + if (!canGetType && rootDeclaration.kind === 161 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - else if (rootDeclaration.parent.kind === 165 /* MethodDeclaration */ || rootDeclaration.parent.kind === 168 /* SetAccessor */) { + else if (rootDeclaration.parent.kind === 166 /* MethodDeclaration */ || rootDeclaration.parent.kind === 169 /* SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } @@ -121378,9 +125281,9 @@ var ts; if (!namedImportsOrExports) return 0 /* Continue */; // try to show exported member for imported/re-exported module - var moduleSpecifier = (namedImportsOrExports.kind === 264 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + var moduleSpecifier = (namedImportsOrExports.kind === 265 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; if (!moduleSpecifier) - return namedImportsOrExports.kind === 264 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */; + return namedImportsOrExports.kind === 265 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 if (!moduleSpecifierSymbol) return 2 /* Fail */; @@ -121448,12 +125351,16 @@ var ts; case "static": classElementModifierFlags = classElementModifierFlags | 32 /* Static */; break; + case "override": + classElementModifierFlags = classElementModifierFlags | 16384 /* Override */; + break; } } // No member list for private methods if (!(classElementModifierFlags & 8 /* Private */)) { // List of property symbols of base type that are not private and already implemented - var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) { + var baseTypeNodes = ts.isClassLike(decl) && classElementModifierFlags & 16384 /* Override */ ? ts.singleElementArray(ts.getEffectiveBaseTypeNode(decl)) : ts.getAllSuperTypeNodes(decl); + var baseSymbols = ts.flatMap(baseTypeNodes, function (baseTypeNode) { var type = typeChecker.getTypeAtLocation(baseTypeNode); return classElementModifierFlags & 32 /* Static */ ? (type === null || type === void 0 ? void 0 : type.symbol) && typeChecker.getPropertiesOfType(typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl)) : @@ -121533,11 +125440,11 @@ var ts; case 30 /* LessThanSlashToken */: case 43 /* SlashToken */: case 78 /* Identifier */: - case 201 /* PropertyAccessExpression */: - case 281 /* JsxAttributes */: - case 280 /* JsxAttribute */: - case 282 /* JsxSpreadAttribute */: - if (parent && (parent.kind === 274 /* JsxSelfClosingElement */ || parent.kind === 275 /* JsxOpeningElement */)) { + case 202 /* PropertyAccessExpression */: + case 282 /* JsxAttributes */: + case 281 /* JsxAttribute */: + case 283 /* JsxSpreadAttribute */: + if (parent && (parent.kind === 275 /* JsxSelfClosingElement */ || parent.kind === 276 /* JsxOpeningElement */)) { if (contextToken.kind === 31 /* GreaterThanToken */) { var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined); if (!parent.typeArguments || (precedingToken && precedingToken.kind === 43 /* SlashToken */)) @@ -121545,7 +125452,7 @@ var ts; } return parent; } - else if (parent.kind === 280 /* JsxAttribute */) { + else if (parent.kind === 281 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -121557,7 +125464,7 @@ var ts; // its parent is a JsxExpression, whose parent is a JsxAttribute, // whose parent is a JsxOpeningLikeElement case 10 /* StringLiteral */: - if (parent && ((parent.kind === 280 /* JsxAttribute */) || (parent.kind === 282 /* JsxSpreadAttribute */))) { + if (parent && ((parent.kind === 281 /* JsxAttribute */) || (parent.kind === 283 /* JsxSpreadAttribute */))) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -121567,8 +125474,8 @@ var ts; break; case 19 /* CloseBraceToken */: if (parent && - parent.kind === 283 /* JsxExpression */ && - parent.parent && parent.parent.kind === 280 /* JsxAttribute */) { + parent.kind === 284 /* JsxExpression */ && + parent.parent && parent.parent.kind === 281 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -121576,7 +125483,7 @@ var ts; // each JsxAttribute can have initializer as JsxExpression return parent.parent.parent.parent; } - if (parent && parent.kind === 282 /* JsxSpreadAttribute */) { + if (parent && parent.kind === 283 /* JsxSpreadAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -121596,49 +125503,49 @@ var ts; var containingNodeKind = parent.kind; switch (contextToken.kind) { case 27 /* CommaToken */: - return containingNodeKind === 249 /* VariableDeclaration */ || + return containingNodeKind === 250 /* VariableDeclaration */ || isVariableDeclarationListButNotTypeArgument(contextToken) || - containingNodeKind === 232 /* VariableStatement */ || - containingNodeKind === 255 /* EnumDeclaration */ || // enum a { foo, | + containingNodeKind === 233 /* VariableStatement */ || + containingNodeKind === 256 /* EnumDeclaration */ || // enum a { foo, | isFunctionLikeButNotConstructor(containingNodeKind) || - containingNodeKind === 253 /* InterfaceDeclaration */ || // interface A= contextToken.pos); case 24 /* DotToken */: - return containingNodeKind === 197 /* ArrayBindingPattern */; // var [.| + return containingNodeKind === 198 /* ArrayBindingPattern */; // var [.| case 58 /* ColonToken */: - return containingNodeKind === 198 /* BindingElement */; // var {x :html| + return containingNodeKind === 199 /* BindingElement */; // var {x :html| case 22 /* OpenBracketToken */: - return containingNodeKind === 197 /* ArrayBindingPattern */; // var [x| + return containingNodeKind === 198 /* ArrayBindingPattern */; // var [x| case 20 /* OpenParenToken */: - return containingNodeKind === 287 /* CatchClause */ || + return containingNodeKind === 288 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); case 18 /* OpenBraceToken */: - return containingNodeKind === 255 /* EnumDeclaration */; // enum a { | + return containingNodeKind === 256 /* EnumDeclaration */; // enum a { | case 29 /* LessThanToken */: - return containingNodeKind === 252 /* ClassDeclaration */ || // class A< | - containingNodeKind === 221 /* ClassExpression */ || // var C = class D< | - containingNodeKind === 253 /* InterfaceDeclaration */ || // interface A< | - containingNodeKind === 254 /* TypeAliasDeclaration */ || // type List< | + return containingNodeKind === 253 /* ClassDeclaration */ || // class A< | + containingNodeKind === 222 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 254 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 255 /* TypeAliasDeclaration */ || // type List< | ts.isFunctionLikeKind(containingNodeKind); case 123 /* StaticKeyword */: - return containingNodeKind === 163 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); + return containingNodeKind === 164 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); case 25 /* DotDotDotToken */: - return containingNodeKind === 160 /* Parameter */ || - (!!parent.parent && parent.parent.kind === 197 /* ArrayBindingPattern */); // var [...z| + return containingNodeKind === 161 /* Parameter */ || + (!!parent.parent && parent.parent.kind === 198 /* ArrayBindingPattern */); // var [...z| case 122 /* PublicKeyword */: case 120 /* PrivateKeyword */: case 121 /* ProtectedKeyword */: - return containingNodeKind === 160 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); + return containingNodeKind === 161 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); case 126 /* AsKeyword */: - return containingNodeKind === 265 /* ImportSpecifier */ || - containingNodeKind === 270 /* ExportSpecifier */ || - containingNodeKind === 263 /* NamespaceImport */; + return containingNodeKind === 266 /* ImportSpecifier */ || + containingNodeKind === 271 /* ExportSpecifier */ || + containingNodeKind === 264 /* NamespaceImport */; case 134 /* GetKeyword */: case 146 /* SetKeyword */: return !isFromObjectTypeDeclaration(contextToken); @@ -121656,7 +125563,7 @@ var ts; case 41 /* AsteriskToken */: return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } - // If the previous token is keyword correspoding to class member completion keyword + // If the previous token is keyword corresponding to class member completion keyword // there will be completion available here if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { return false; @@ -121691,6 +125598,31 @@ var ts; case 129 /* AsyncKeyword */: return ts.isPropertyDeclaration(contextToken.parent); } + // If we are inside a class declaration, and `constructor` is totally not present, + // but we request a completion manually at a whitespace... + var ancestorClassLike = ts.findAncestor(contextToken.parent, ts.isClassLike); + if (ancestorClassLike && contextToken === previousToken && isPreviousPropertyDeclarationTerminated(contextToken, position)) { + return false; // Don't block completions. + } + var ancestorPropertyDeclaraion = ts.getAncestor(contextToken.parent, 164 /* PropertyDeclaration */); + // If we are inside a class declaration and typing `constructor` after property declaration... + if (ancestorPropertyDeclaraion + && contextToken !== previousToken + && ts.isClassLike(previousToken.parent.parent) + // And the cursor is at the token... + && position <= previousToken.end) { + // If we are sure that the previous property declaration is terminated according to newline or semicolon... + if (isPreviousPropertyDeclarationTerminated(contextToken, previousToken.end)) { + return false; // Don't block completions. + } + else if (contextToken.kind !== 62 /* EqualsToken */ + // Should not block: `class C { blah = c/**/ }` + // But should block: `class C { blah = somewhat c/**/ }` and `class C { blah: SomeType c/**/ }` + && (ts.isInitializedProperty(ancestorPropertyDeclaraion) + || ts.hasType(ancestorPropertyDeclaraion))) { + return true; + } + } return ts.isDeclarationName(contextToken) && !ts.isShorthandPropertyAssignment(contextToken.parent) && !ts.isJsxAttribute(contextToken.parent) @@ -121698,8 +125630,13 @@ var ts; // If `contextToken !== previousToken`, this is `class C ex/**/`. && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } + function isPreviousPropertyDeclarationTerminated(contextToken, position) { + return contextToken.kind !== 62 /* EqualsToken */ && + (contextToken.kind === 26 /* SemicolonToken */ + || !ts.positionsAreOnSameLine(contextToken.end, position, sourceFile)); + } function isFunctionLikeButNotConstructor(kind) { - return ts.isFunctionLikeKind(kind) && kind !== 166 /* Constructor */; + return ts.isFunctionLikeKind(kind) && kind !== 167 /* Constructor */; } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8 /* NumericLiteral */) { @@ -121709,7 +125646,7 @@ var ts; return false; } function isVariableDeclarationListButNotTypeArgument(node) { - return node.parent.kind === 250 /* VariableDeclarationList */ + return node.parent.kind === 251 /* VariableDeclarationList */ && !ts.isPossiblyTypeArgumentPosition(node, sourceFile, typeChecker); } /** @@ -121727,13 +125664,13 @@ var ts; for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 288 /* PropertyAssignment */ && - m.kind !== 289 /* ShorthandPropertyAssignment */ && - m.kind !== 198 /* BindingElement */ && - m.kind !== 165 /* MethodDeclaration */ && - m.kind !== 167 /* GetAccessor */ && - m.kind !== 168 /* SetAccessor */ && - m.kind !== 290 /* SpreadAssignment */) { + if (m.kind !== 289 /* PropertyAssignment */ && + m.kind !== 290 /* ShorthandPropertyAssignment */ && + m.kind !== 199 /* BindingElement */ && + m.kind !== 166 /* MethodDeclaration */ && + m.kind !== 168 /* GetAccessor */ && + m.kind !== 169 /* SetAccessor */ && + m.kind !== 291 /* SpreadAssignment */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -121806,10 +125743,10 @@ var ts; for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 163 /* PropertyDeclaration */ && - m.kind !== 165 /* MethodDeclaration */ && - m.kind !== 167 /* GetAccessor */ && - m.kind !== 168 /* SetAccessor */) { + if (m.kind !== 164 /* PropertyDeclaration */ && + m.kind !== 166 /* MethodDeclaration */ && + m.kind !== 168 /* GetAccessor */ && + m.kind !== 169 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -121833,7 +125770,7 @@ var ts; return !existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */) && - !(propertySymbol.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(propertySymbol.valueDeclaration)); + !(propertySymbol.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(propertySymbol.valueDeclaration)); }); } /** @@ -121851,7 +125788,7 @@ var ts; if (isCurrentlyEditingNode(attr)) { continue; } - if (attr.kind === 280 /* JsxAttribute */) { + if (attr.kind === 281 /* JsxAttribute */) { seenNames.add(attr.name.escapedText); } else if (ts.isJsxSpreadAttribute(attr)) { @@ -121866,8 +125803,35 @@ var ts; return node.getStart(sourceFile) <= position && position <= node.getEnd(); } } + function getAutoImportSymbolFromCompletionEntryData(name, data, program, host) { + var containingProgram = data.isPackageJsonImport ? host.getPackageJsonAutoImportProvider() : program; + var checker = containingProgram.getTypeChecker(); + var moduleSymbol = data.ambientModuleName ? checker.tryFindAmbientModule(data.ambientModuleName) : + data.fileName ? checker.getMergedSymbol(ts.Debug.checkDefined(containingProgram.getSourceFile(data.fileName)).symbol) : + undefined; + if (!moduleSymbol) + return undefined; + var symbol = data.exportName === "export=" /* ExportEquals */ + ? checker.resolveExternalModuleSymbol(moduleSymbol) + : checker.tryGetMemberInModuleExportsAndProperties(data.exportName, moduleSymbol); + if (!symbol) + return undefined; + var isDefaultExport = data.exportName === "default" /* Default */; + symbol = isDefaultExport && ts.getLocalSymbolForExportDefault(symbol) || symbol; + return { + symbol: symbol, + origin: { + kind: data.moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */, + moduleSymbol: moduleSymbol, + symbolName: name, + isDefaultExport: isDefaultExport, + exportName: data.exportName, + fileName: data.fileName, + } + }; + } function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, jsxIdentifierExpected) { - var name = originIsExport(origin) ? ts.getNameForExportedSymbol(symbol, target) : symbol.name; + var name = originIncludesSymbolName(origin) ? origin.symbolName : symbol.name; if (name === undefined // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) @@ -121877,7 +125841,7 @@ var ts; return undefined; } var validNameResult = { name: name, needsConvertPropertyAccess: false }; - if (ts.isIdentifierText(name, target, jsxIdentifierExpected ? 1 /* JSX */ : 0 /* Standard */) || symbol.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) { + if (ts.isIdentifierText(name, target, jsxIdentifierExpected ? 1 /* JSX */ : 0 /* Standard */) || symbol.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) { return validNameResult; } switch (kind) { @@ -121901,7 +125865,7 @@ var ts; var _keywordCompletions = []; var allKeywordsCompletions = ts.memoize(function () { var res = []; - for (var i = 80 /* FirstKeyword */; i <= 156 /* LastKeyword */; i++) { + for (var i = 80 /* FirstKeyword */; i <= 157 /* LastKeyword */; i++) { res.push({ name: ts.tokenToString(i), kind: "keyword" /* keyword */, @@ -121968,6 +125932,7 @@ var ts; case 141 /* NeverKeyword */: case 144 /* NumberKeyword */: case 145 /* ObjectKeyword */: + case 156 /* OverrideKeyword */: case 120 /* PrivateKeyword */: case 121 /* ProtectedKeyword */: case 122 /* PublicKeyword */: @@ -121993,6 +125958,7 @@ var ts; case 146 /* SetKeyword */: case 129 /* AsyncKeyword */: case 133 /* DeclareKeyword */: + case 156 /* OverrideKeyword */: return true; default: return ts.isClassMemberModifier(kind); @@ -122053,7 +126019,7 @@ var ts; function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position) { // class c { method() { } | method2() { } } switch (location.kind) { - case 334 /* SyntaxList */: + case 338 /* SyntaxList */: return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); case 1 /* EndOfFileToken */: var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); @@ -122074,6 +126040,12 @@ var ts; } if (!contextToken) return undefined; + // class C { blah; constructor/**/ } and so on + if (location.kind === 132 /* ConstructorKeyword */ + // class C { blah \n constructor/**/ } + || (ts.isIdentifier(contextToken) && ts.isPropertyDeclaration(contextToken.parent) && ts.isClassLike(location))) { + return ts.findAncestor(contextToken, ts.isClassLike); + } switch (contextToken.kind) { case 62 /* EqualsToken */: // class c { public prop = | /* global completions */ } return undefined; @@ -122099,6 +126071,44 @@ var ts; ? contextToken.parent.parent : undefined; } } + function tryGetTypeLiteralNode(node) { + if (!node) + return undefined; + var parent = node.parent; + switch (node.kind) { + case 18 /* OpenBraceToken */: + if (ts.isTypeLiteralNode(parent)) { + return parent; + } + break; + case 26 /* SemicolonToken */: + case 27 /* CommaToken */: + case 78 /* Identifier */: + if (parent.kind === 163 /* PropertySignature */ && ts.isTypeLiteralNode(parent.parent)) { + return parent.parent; + } + break; + } + return undefined; + } + function getConstraintOfTypeArgumentProperty(node, checker) { + if (!node) + return undefined; + if (ts.isTypeNode(node) && ts.isTypeReferenceType(node.parent)) { + return checker.getTypeArgumentConstraint(node); + } + var t = getConstraintOfTypeArgumentProperty(node.parent, checker); + if (!t) + return undefined; + switch (node.kind) { + case 163 /* PropertySignature */: + return checker.getTypeOfPropertyOfContextualType(t, node.symbol.escapedName); + case 184 /* IntersectionType */: + case 178 /* TypeLiteral */: + case 183 /* UnionType */: + return t; + } + } // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes function isFromObjectTypeDeclaration(node) { return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent); @@ -122122,6 +126132,8 @@ var ts; return !!contextToken && (ts.isStringLiteralLike(contextToken) ? !!ts.tryGetImportFromModuleSpecifier(contextToken) : contextToken.kind === 43 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); + case " ": + return !!contextToken && ts.isImportKeyword(contextToken) && contextToken.parent.kind === 298 /* SourceFile */; default: return ts.Debug.assertNever(triggerCharacter); } @@ -122130,14 +126142,6 @@ var ts; var left = _a.left; return ts.nodeIsMissing(left); } - function findAlias(typeChecker, symbol, predicate) { - var currentAlias = symbol; - while (currentAlias.flags & 2097152 /* Alias */ && (currentAlias = typeChecker.getImmediateAliasedSymbol(currentAlias))) { - if (predicate(currentAlias)) { - return currentAlias; - } - } - } /** Determines if a type is exactly the same type resolved by the global 'self', 'global', or 'globalThis'. */ function isProbablyGlobalType(type, sourceFile, checker) { // The type of `self` and `window` is the same in lib.dom.d.ts, but `window` does not exist in @@ -122164,11 +126168,67 @@ var ts; if (type) { return type; } - if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) { + if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ && node === node.parent.left) { + // Object literal is assignment pattern: ({ | } = x) return typeChecker.getTypeAtLocation(node.parent); } return undefined; } + function getImportCompletionNode(contextToken) { + var candidate = getCandidate(); + return candidate === 153 /* FromKeyword */ || candidate && ts.rangeIsOnSingleLine(candidate, candidate.getSourceFile()) ? candidate : undefined; + function getCandidate() { + var parent = contextToken.parent; + if (ts.isImportEqualsDeclaration(parent)) { + return isModuleSpecifierMissingOrEmpty(parent.moduleReference) ? parent : undefined; + } + if (ts.isNamedImports(parent) || ts.isNamespaceImport(parent)) { + if (isModuleSpecifierMissingOrEmpty(parent.parent.parent.moduleSpecifier) && (ts.isNamespaceImport(parent) || parent.elements.length < 2) && !parent.parent.name) { + // At `import { ... } |` or `import * as Foo |`, the only possible completion is `from` + return contextToken.kind === 19 /* CloseBraceToken */ || contextToken.kind === 78 /* Identifier */ + ? 153 /* FromKeyword */ + : parent.parent.parent; + } + return undefined; + } + if (ts.isImportKeyword(contextToken) && ts.isSourceFile(parent)) { + // A lone import keyword with nothing following it does not parse as a statement at all + return contextToken; + } + if (ts.isImportKeyword(contextToken) && ts.isImportDeclaration(parent)) { + // `import s| from` + return isModuleSpecifierMissingOrEmpty(parent.moduleSpecifier) ? parent : undefined; + } + return undefined; + } + } + function isModuleSpecifierMissingOrEmpty(specifier) { + var _a; + if (ts.nodeIsMissing(specifier)) + return true; + return !((_a = ts.tryCast(ts.isExternalModuleReference(specifier) ? specifier.expression : specifier, ts.isStringLiteralLike)) === null || _a === void 0 ? void 0 : _a.text); + } + function getVariableDeclaration(property) { + var variableDeclaration = ts.findAncestor(property, function (node) { + return ts.isFunctionBlock(node) || isArrowFunctionBody(node) || ts.isBindingPattern(node) + ? "quit" + : ts.isVariableDeclaration(node); + }); + return variableDeclaration; + } + function isArrowFunctionBody(node) { + return node.parent && ts.isArrowFunction(node.parent) && node.parent.body === node; + } + ; + /** True if symbol is a type or a module containing at least one type. */ + function symbolCanBeReferencedAtTypeLocation(symbol, checker, seenModules) { + if (seenModules === void 0) { seenModules = new ts.Map(); } + var sym = ts.skipAlias(symbol.exportSymbol || symbol, checker); + return !!(sym.flags & 788968 /* Type */) || + !!(sym.flags & 1536 /* Module */) && + ts.addToSeen(seenModules, ts.getSymbolId(sym)) && + checker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, checker, seenModules); }); + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); var ts; @@ -122203,10 +126263,12 @@ var ts; if (!referenceEntries) return undefined; var map = ts.arrayToMultiMap(referenceEntries.map(ts.FindAllReferences.toHighlightSpan), function (e) { return e.fileName; }, function (e) { return e.span; }); - return ts.arrayFrom(map.entries(), function (_a) { + return ts.mapDefined(ts.arrayFrom(map.entries()), function (_a) { var fileName = _a[0], highlightSpans = _a[1]; if (!sourceFilesSet.has(fileName)) { - ts.Debug.assert(program.redirectTargetsMap.has(fileName)); + if (!program.redirectTargetsMap.has(fileName)) { + return undefined; + } var redirectTarget_1 = program.getSourceFile(fileName); var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); fileName = redirect.fileName; @@ -122301,7 +126363,7 @@ var ts; var child = throwStatement; while (child.parent) { var parent = child.parent; - if (ts.isFunctionBlock(parent) || parent.kind === 297 /* SourceFile */) { + if (ts.isFunctionBlock(parent) || parent.kind === 298 /* SourceFile */) { return parent; } // A throw-statement is only owned by a try-statement if the try-statement has @@ -122333,16 +126395,16 @@ var ts; function getBreakOrContinueOwner(statement) { return ts.findAncestor(statement, function (node) { switch (node.kind) { - case 244 /* SwitchStatement */: - if (statement.kind === 240 /* ContinueStatement */) { + case 245 /* SwitchStatement */: + if (statement.kind === 241 /* ContinueStatement */) { return false; } // falls through - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 236 /* WhileStatement */: - case 235 /* DoStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 237 /* WhileStatement */: + case 236 /* DoStatement */: return !statement.label || isLabeledBy(node, statement.label.escapedText); default: // Don't cross function boundaries. @@ -122358,11 +126420,11 @@ var ts; // Types of node whose children might have modifiers. var container = declaration.parent; switch (container.kind) { - case 257 /* ModuleBlock */: - case 297 /* SourceFile */: - case 230 /* Block */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 258 /* ModuleBlock */: + case 298 /* SourceFile */: + case 231 /* Block */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) { return __spreadArray(__spreadArray([], declaration.members), [declaration]); @@ -122370,14 +126432,14 @@ var ts; else { return container.statements; } - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 251 /* FunctionDeclaration */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: return __spreadArray(__spreadArray([], container.parameters), (ts.isClassLike(container.parent) ? container.parent.members : [])); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 177 /* TypeLiteral */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 178 /* TypeLiteral */: var nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. @@ -122392,7 +126454,7 @@ var ts; } return nodes; // Syntactically invalid positions that the parser might produce anyway - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return undefined; default: ts.Debug.assertNever(container, "Invalid container kind."); @@ -122413,7 +126475,7 @@ var ts; var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 96 /* ForKeyword */, 114 /* WhileKeyword */, 89 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 235 /* DoStatement */) { + if (loopNode.kind === 236 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 114 /* WhileKeyword */)) { @@ -122433,13 +126495,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -122612,6 +126674,9 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + function isDocumentRegistryEntry(entry) { + return !!entry.sourceFile; + } function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); } @@ -122628,10 +126693,16 @@ var ts; var entries = buckets.get(name); var sourceFiles = []; entries.forEach(function (entry, name) { - sourceFiles.push({ - name: name, - refCount: entry.languageServiceRefCount - }); + if (isDocumentRegistryEntry(entry)) { + sourceFiles.push({ + name: name, + scriptKind: entry.sourceFile.scriptKind, + refCount: entry.languageServiceRefCount + }); + } + else { + entry.forEach(function (value, scriptKind) { return sourceFiles.push({ name: name, scriptKind: scriptKind, refCount: value.languageServiceRefCount }); }); + } }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); return { @@ -122657,10 +126728,17 @@ var ts; function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); } + function getDocumentRegistryEntry(bucketEntry, scriptKind) { + var entry = isDocumentRegistryEntry(bucketEntry) ? bucketEntry : bucketEntry.get(ts.Debug.checkDefined(scriptKind, "If there are more than one scriptKind's for same document the scriptKind should be provided")); + ts.Debug.assert(scriptKind === undefined || !entry || entry.sourceFile.scriptKind === scriptKind, "Script kind should match provided ScriptKind:" + scriptKind + " and sourceFile.scriptKind: " + (entry === null || entry === void 0 ? void 0 : entry.sourceFile.scriptKind) + ", !entry: " + !entry); + return entry; + } function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { - var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); - var entry = bucket.get(path); + scriptKind = ts.ensureScriptKind(fileName, scriptKind); var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; + var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); + var bucketEntry = bucket.get(path); + var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -122669,7 +126747,7 @@ var ts; sourceFile: sourceFile, languageServiceRefCount: 0 }; - bucket.set(path, entry); + setBucketEntry(); } } if (!entry) { @@ -122682,7 +126760,7 @@ var ts; sourceFile: sourceFile, languageServiceRefCount: 1, }; - bucket.set(path, entry); + setBucketEntry(); } else { // We have an entry for this file. However, it may be for a different version of @@ -122705,25 +126783,49 @@ var ts; } ts.Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; + function setBucketEntry() { + if (!bucketEntry) { + bucket.set(path, entry); + } + else if (isDocumentRegistryEntry(bucketEntry)) { + var scriptKindMap = new ts.Map(); + scriptKindMap.set(bucketEntry.sourceFile.scriptKind, bucketEntry); + scriptKindMap.set(scriptKind, entry); + bucket.set(path, scriptKindMap); + } + else { + bucketEntry.set(scriptKind, entry); + } + } } - function releaseDocument(fileName, compilationSettings) { + function releaseDocument(fileName, compilationSettings, scriptKind) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(compilationSettings); - return releaseDocumentWithKey(path, key); + return releaseDocumentWithKey(path, key, scriptKind); } - function releaseDocumentWithKey(path, key) { + function releaseDocumentWithKey(path, key, scriptKind) { var bucket = ts.Debug.checkDefined(buckets.get(key)); - var entry = bucket.get(path); + var bucketEntry = bucket.get(path); + var entry = getDocumentRegistryEntry(bucketEntry, scriptKind); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - bucket.delete(path); + if (isDocumentRegistryEntry(bucketEntry)) { + bucket.delete(path); + } + else { + bucketEntry.delete(scriptKind); + if (bucketEntry.size === 1) { + bucket.set(path, ts.firstDefinedIterator(bucketEntry.values(), ts.identity)); + } + } } } - function getLanguageServiceRefCounts(path) { + function getLanguageServiceRefCounts(path, scriptKind) { return ts.arrayFrom(buckets.entries(), function (_a) { var key = _a[0], bucket = _a[1]; - var entry = bucket.get(path); + var bucketEntry = bucket.get(path); + var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); return [key, entry && entry.languageServiceRefCount]; }); } @@ -122786,10 +126888,12 @@ var ts; return sourceFiles; } // Module augmentations may use this module's exports without importing it. - for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (ts.isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) { - addIndirectUser(decl); + if (exportingModuleSymbol.declarations) { + for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) { + addIndirectUser(decl); + } } } // This may return duplicates (if there are multiple module declarations in a single source file, all importing the same thing as a namespace), but `State.markSearchedSymbol` will handle that. @@ -122806,14 +126910,14 @@ var ts; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); switch (direct.kind) { - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (ts.isImportCall(direct)) { handleImportCall(direct); break; } if (!isAvailableThroughGlobal) { var parent = direct.parent; - if (exportKind === 2 /* ExportEquals */ && parent.kind === 249 /* VariableDeclaration */) { + if (exportKind === 2 /* ExportEquals */ && parent.kind === 250 /* VariableDeclaration */) { var name = parent.name; if (name.kind === 78 /* Identifier */) { directImports.push(name); @@ -122824,25 +126928,25 @@ var ts; break; case 78 /* Identifier */: // for 'const x = require("y"); break; // TODO: GH#23879 - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: handleNamespaceImport(direct, direct.name, ts.hasSyntacticModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false); break; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: directImports.push(direct); var namedBindings = direct.importClause && direct.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 263 /* NamespaceImport */) { + if (namedBindings && namedBindings.kind === 264 /* NamespaceImport */) { handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true); } else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) { addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports } break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: if (!direct.exportClause) { // This is `export * from "foo"`, so imports of this module may import the export too. handleDirectImports(getContainingModuleSymbol(direct, checker)); } - else if (direct.exportClause.kind === 269 /* NamespaceExport */) { + else if (direct.exportClause.kind === 270 /* NamespaceExport */) { // `export * as foo from "foo"` add to indirect uses addIndirectUser(getSourceFileLikeForImportDeclaration(direct), /** addTransitiveDependencies */ true); } @@ -122851,7 +126955,7 @@ var ts; directImports.push(direct); } break; - case 195 /* ImportType */: + case 196 /* ImportType */: // Only check for typeof import('xyz') if (direct.isTypeOf && !direct.qualifier && isExported(direct)) { addIndirectUser(direct.getSourceFile(), /** addTransitiveDependencies */ true); @@ -122884,7 +126988,7 @@ var ts; } else if (!isAvailableThroughGlobal) { var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); - ts.Debug.assert(sourceFileLike.kind === 297 /* SourceFile */ || sourceFileLike.kind === 256 /* ModuleDeclaration */); + ts.Debug.assert(sourceFileLike.kind === 298 /* SourceFile */ || sourceFileLike.kind === 257 /* ModuleDeclaration */); if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { addIndirectUser(sourceFileLike, /** addTransitiveDependencies */ true); } @@ -122940,7 +127044,7 @@ var ts; } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { - if (decl.kind === 260 /* ImportEqualsDeclaration */) { + if (decl.kind === 261 /* ImportEqualsDeclaration */) { if (isExternalModuleImportEquals(decl)) { handleNamespaceImportLike(decl.name); } @@ -122950,7 +127054,7 @@ var ts; handleNamespaceImportLike(decl); return; } - if (decl.kind === 195 /* ImportType */) { + if (decl.kind === 196 /* ImportType */) { if (decl.qualifier) { var firstIdentifier = ts.getFirstIdentifier(decl.qualifier); if (firstIdentifier.escapedText === ts.symbolName(exportSymbol)) { @@ -122966,7 +127070,7 @@ var ts; if (decl.moduleSpecifier.kind !== 10 /* StringLiteral */) { return; } - if (decl.kind === 267 /* ExportDeclaration */) { + if (decl.kind === 268 /* ExportDeclaration */) { if (decl.exportClause && ts.isNamedExports(decl.exportClause)) { searchForNamedImport(decl.exportClause); } @@ -122975,10 +127079,10 @@ var ts; var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: handleNamespaceImportLike(namedBindings.name); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: // 'default' might be accessed as a named import `{ default as foo }`. if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) { searchForNamedImport(namedBindings); @@ -123028,7 +127132,7 @@ var ts; } } else { - var localSymbol = element.kind === 270 /* ExportSpecifier */ && element.propertyName + var localSymbol = element.kind === 271 /* ExportSpecifier */ && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. : checker.getSymbolAtLocation(name); addSearch(name, localSymbol); @@ -123057,7 +127161,7 @@ var ts; for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { var referencingFile = sourceFiles_1[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; - if (searchSourceFile.kind === 297 /* SourceFile */) { + if ((searchSourceFile === null || searchSourceFile === void 0 ? void 0 : searchSourceFile.kind) === 298 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { var ref = _b[_a]; if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { @@ -123105,7 +127209,7 @@ var ts; } /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return ts.forEach(sourceFileLike.kind === 297 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return ts.forEach(sourceFileLike.kind === 298 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); }); } @@ -123120,15 +127224,15 @@ var ts; else { forEachPossibleImportOrExportStatement(sourceFile, function (statement) { switch (statement.kind) { - case 267 /* ExportDeclaration */: - case 261 /* ImportDeclaration */: { + case 268 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: { var decl = statement; if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) { action(decl, decl.moduleSpecifier); } break; } - case 260 /* ImportEqualsDeclaration */: { + case 261 /* ImportEqualsDeclaration */: { var decl = statement; if (isExternalModuleImportEquals(decl)) { action(decl, decl.moduleReference.expression); @@ -123149,14 +127253,15 @@ var ts; function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { return comingFromExport ? getExport() : getExport() || getImport(); function getExport() { + var _a; var parent = node.parent; - var grandParent = parent.parent; + var grandparent = parent.parent; if (symbol.exportSymbol) { - if (parent.kind === 201 /* PropertyAccessExpression */) { + if (parent.kind === 202 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. - return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) - ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false) + return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === parent; })) && ts.isBinaryExpression(grandparent) + ? getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ false) : undefined; } else { @@ -123186,15 +127291,15 @@ var ts; return getExportAssignmentExport(parent); } // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. - else if (ts.isExportAssignment(grandParent)) { - return getExportAssignmentExport(grandParent); + else if (ts.isExportAssignment(grandparent)) { + return getExportAssignmentExport(grandparent); } // Similar for `module.exports =` and `exports.A =`. else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } - else if (ts.isBinaryExpression(grandParent)) { - return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true); + else if (ts.isBinaryExpression(grandparent)) { + return getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ true); } else if (ts.isJSDocTypedefTag(parent)) { return exportInfo(symbol, 0 /* Named */); @@ -123202,9 +127307,10 @@ var ts; } function getExportAssignmentExport(ex) { // Get the symbol for the `export =` node; its parent is the module it's the export of. - var exportingModuleSymbol = ts.Debug.checkDefined(ex.symbol.parent, "Expected export symbol to have a parent"); + if (!ex.symbol.parent) + return undefined; var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */; - return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; + return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: ex.symbol.parent, exportKind: exportKind } }; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; @@ -123258,7 +127364,7 @@ var ts; if (importedSymbol.flags & 2097152 /* Alias */) { return ts.Debug.checkDefined(checker.getImmediateAliasedSymbol(importedSymbol)); } - var decl = importedSymbol.valueDeclaration; + var decl = ts.Debug.checkDefined(importedSymbol.valueDeclaration); if (ts.isExportAssignment(decl)) { // `export = class {}` return ts.Debug.checkDefined(decl.expression.symbol); } @@ -123285,17 +127391,17 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return parent.name === node && isExternalModuleImportEquals(parent); - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. return !parent.propertyName; - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: ts.Debug.assert(parent.name === node); return true; - case 198 /* BindingElement */: - return ts.isInJSFile(node) && ts.isRequireVariableDeclaration(parent, /*requireStringLiteralLikeArgument*/ true); + case 199 /* BindingElement */: + return ts.isInJSFile(node) && ts.isRequireVariableDeclaration(parent); default: return false; } @@ -123319,7 +127425,8 @@ var ts; return checker.getExportSpecifierLocalTargetSymbol(declaration); } else if (ts.isPropertyAccessExpression(declaration) && ts.isModuleExportsAccessExpression(declaration.expression) && !ts.isPrivateIdentifier(declaration.name)) { - return checker.getExportSpecifierLocalTargetSymbol(declaration.name); + // Export of form 'module.exports.propName = expr'; + return checker.getSymbolAtLocation(declaration); } else if (ts.isShorthandPropertyAssignment(declaration) && ts.isBinaryExpression(declaration.parent.parent) @@ -123334,21 +127441,21 @@ var ts; return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); } function getSourceFileLikeForImportDeclaration(node) { - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { return node.getSourceFile(); } var parent = node.parent; - if (parent.kind === 297 /* SourceFile */) { + if (parent.kind === 298 /* SourceFile */) { return parent; } - ts.Debug.assert(parent.kind === 257 /* ModuleBlock */); + ts.Debug.assert(parent.kind === 258 /* ModuleBlock */); return ts.cast(parent.parent, isAmbientModuleDeclaration); } function isAmbientModuleDeclaration(node) { - return node.kind === 256 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */; + return node.kind === 257 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */; } function isExternalModuleImportEquals(eq) { - return eq.moduleReference.kind === 272 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */; + return eq.moduleReference.kind === 273 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -123451,7 +127558,7 @@ var ts; if (!node) return undefined; switch (node.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return !ts.isVariableDeclarationList(node.parent) || node.parent.declarations.length !== 1 ? node : ts.isVariableStatement(node.parent.parent) ? @@ -123459,28 +127566,28 @@ var ts; ts.isForInOrOfStatement(node.parent.parent) ? getContextNode(node.parent.parent) : node.parent; - case 198 /* BindingElement */: + case 199 /* BindingElement */: return getContextNode(node.parent.parent); - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: return node.parent.parent.parent; - case 270 /* ExportSpecifier */: - case 263 /* NamespaceImport */: + case 271 /* ExportSpecifier */: + case 264 /* NamespaceImport */: return node.parent.parent; - case 262 /* ImportClause */: - case 269 /* NamespaceExport */: + case 263 /* ImportClause */: + case 270 /* NamespaceExport */: return node.parent; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return ts.isExpressionStatement(node.parent) ? node.parent : node; - case 239 /* ForOfStatement */: - case 238 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 239 /* ForInStatement */: return { start: node.initializer, end: node.expression }; - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent) ? getContextNode(ts.findAncestor(node.parent, function (node) { return ts.isBinaryExpression(node) || ts.isForInOrOfStatement(node); @@ -123537,9 +127644,9 @@ var ts; var node = ts.getTouchingPropertyName(sourceFile, position); var referenceEntries; var entries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); - if (node.parent.kind === 201 /* PropertyAccessExpression */ - || node.parent.kind === 198 /* BindingElement */ - || node.parent.kind === 202 /* ElementAccessExpression */ + if (node.parent.kind === 202 /* PropertyAccessExpression */ + || node.parent.kind === 199 /* BindingElement */ + || node.parent.kind === 203 /* ElementAccessExpression */ || node.kind === 105 /* SuperKeyword */) { referenceEntries = entries && __spreadArray([], entries); } @@ -123563,13 +127670,13 @@ var ts; } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { return undefined; } var checker = program.getTypeChecker(); // 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 === 289 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 290 /* ShorthandPropertyAssignment */) { var result_1 = []; Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_1.push(nodeEntry(node)); }); return result_1; @@ -123744,13 +127851,13 @@ var ts; if (symbol) { return getDefinitionKindAndDisplayParts(symbol, checker, node); } - else if (node.kind === 200 /* ObjectLiteralExpression */) { + else if (node.kind === 201 /* ObjectLiteralExpression */) { return { kind: "interface" /* interfaceElement */, displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(21 /* CloseParenToken */)] }; } - else if (node.kind === 221 /* ClassExpression */) { + else if (node.kind === 222 /* ClassExpression */) { return { kind: "local class" /* localClassElement */, displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(21 /* CloseParenToken */)] @@ -123811,47 +127918,47 @@ var ts; if (!!(decl.flags & 8388608 /* Ambient */)) return true; switch (decl.kind) { - case 216 /* BinaryExpression */: - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 217 /* BinaryExpression */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: case 87 /* DefaultKeyword */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: - case 270 /* ExportSpecifier */: - case 262 /* ImportClause */: // default import - case 260 /* ImportEqualsDeclaration */: - case 265 /* ImportSpecifier */: - case 253 /* InterfaceDeclaration */: - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: - case 280 /* JsxAttribute */: - case 256 /* ModuleDeclaration */: - case 259 /* NamespaceExportDeclaration */: - case 263 /* NamespaceImport */: - case 269 /* NamespaceExport */: - case 160 /* Parameter */: - case 289 /* ShorthandPropertyAssignment */: - case 254 /* TypeAliasDeclaration */: - case 159 /* TypeParameter */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: + case 271 /* ExportSpecifier */: + case 263 /* ImportClause */: // default import + case 261 /* ImportEqualsDeclaration */: + case 266 /* ImportSpecifier */: + case 254 /* InterfaceDeclaration */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: + case 281 /* JsxAttribute */: + case 257 /* ModuleDeclaration */: + case 260 /* NamespaceExportDeclaration */: + case 264 /* NamespaceImport */: + case 270 /* NamespaceExport */: + case 161 /* Parameter */: + case 290 /* ShorthandPropertyAssignment */: + case 255 /* TypeAliasDeclaration */: + case 160 /* TypeParameter */: return true; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return !!decl.body; - case 249 /* VariableDeclaration */: - case 163 /* PropertyDeclaration */: + case 250 /* VariableDeclaration */: + case 164 /* PropertyDeclaration */: return !!decl.initializer || ts.isCatchClause(decl.parent); - case 164 /* MethodSignature */: - case 162 /* PropertySignature */: - case 333 /* JSDocPropertyTag */: - case 326 /* JSDocParameterTag */: + case 165 /* MethodSignature */: + case 163 /* PropertySignature */: + case 337 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: return false; default: return ts.Debug.failBadSyntaxKind(decl); @@ -123873,7 +127980,7 @@ var ts; } if (ts.isSourceFile(node)) { var resolvedRef = ts.GoToDefinition.getReferenceAtPosition(node, position, program); - if (!resolvedRef) { + if (!(resolvedRef === null || resolvedRef === void 0 ? void 0 : resolvedRef.file)) { return undefined; } var moduleSymbol = program.getTypeChecker().getMergedSymbol(resolvedRef.file.symbol); @@ -123902,7 +128009,7 @@ var ts; if (!symbol) { // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. if (!options.implementations && ts.isStringLiteralLike(node)) { - if (ts.isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ true) || ts.isExternalModuleReference(node.parent) || ts.isImportDeclaration(node.parent) || ts.isImportCall(node.parent)) { + if (ts.isModuleSpecifierLike(node)) { var fileIncludeReasons = program.getFileIncludeReasons(); var referencedFileName = (_b = (_a = node.getSourceFile().resolvedModules) === null || _a === void 0 ? void 0 : _a.get(node.text)) === null || _b === void 0 ? void 0 : _b.resolvedFileName; var referencedFile = referencedFileName ? program.getSourceFile(referencedFileName) : undefined; @@ -124003,7 +128110,7 @@ var ts; result = references; continue; } - var _loop_3 = function (entry) { + var _loop_4 = function (entry) { if (!entry.definition || entry.definition.type !== 0 /* Symbol */) { result.push(entry); return "continue"; @@ -124035,7 +128142,7 @@ var ts; }; for (var _b = 0, references_2 = references; _b < references_2.length; _b++) { var entry = references_2[_b]; - _loop_3(entry); + _loop_4(entry); } } return result; @@ -124072,10 +128179,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; switch (decl.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) break; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { references.push(nodeEntry(decl.name)); } @@ -124087,7 +128194,7 @@ var ts; } } var exported = symbol.exports.get("export=" /* ExportEquals */); - if (exported) { + if (exported === null || exported === void 0 ? void 0 : exported.declarations) { for (var _b = 0, _c = exported.declarations; _b < _c.length; _b++) { var decl = _c[_b]; var sourceFile = decl.getSourceFile(); @@ -124150,14 +128257,14 @@ var ts; var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); - var exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); + var exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) || !symbol.declarations ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); if (exportSpecifier) { // When renaming at an export specifier, rename the export and not the thing being exported. getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); } - else if (node && node.kind === 87 /* DefaultKeyword */) { + else if (node && node.kind === 87 /* DefaultKeyword */ && symbol.escapedName === "default" /* Default */ && symbol.parent) { addReference(node, symbol, state); - searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.checkDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state); } else { var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === 2 /* Rename */, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); @@ -124183,7 +128290,7 @@ var ts; } function getSpecialSearchKind(node) { switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: case 132 /* ConstructorKeyword */: return 1 /* Constructor */; case 78 /* Identifier */: @@ -124314,8 +128421,8 @@ var ts; var sourceId = ts.getNodeId(sourceFile); var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = new ts.Set()); var anyNewSymbols = false; - for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { - var sym = symbols_3[_i]; + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var sym = symbols_2[_i]; anyNewSymbols = ts.tryAddToSet(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols; } return anyNewSymbols; @@ -124372,7 +128479,9 @@ var ts; for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { var node = _d[_c]; // Import specifiers should be handled by importSearches - if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) { + var symbol = checker.getSymbolAtLocation(node); + var hasExportAssignmentDeclaration = ts.some(symbol === null || symbol === void 0 ? void 0 : symbol.declarations, function (d) { return ts.tryCast(d, ts.isExportAssignment) ? true : false; }); + if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && (symbol === exportSymbol || hasExportAssignmentDeclaration)) { cb(node); } } @@ -124424,7 +128533,7 @@ var ts; // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 208 /* FunctionExpression */ || valueDeclaration.kind === 221 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 209 /* FunctionExpression */ || valueDeclaration.kind === 222 /* ClassExpression */)) { return valueDeclaration; } if (!declarations) { @@ -124432,9 +128541,9 @@ var ts; } // If this is private property or method, the scope is the containing class if (flags & (4 /* Property */ | 8192 /* Method */)) { - var privateDeclaration = ts.find(declarations, function (d) { return ts.hasEffectiveModifier(d, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(d); }); + var privateDeclaration = ts.find(declarations, function (d) { return ts.hasEffectiveModifier(d, 8 /* Private */) || ts.isPrivateIdentifierClassElementDeclaration(d); }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 252 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 253 /* ClassDeclaration */); } // Else this is a public property and could be accessed from anywhere. return undefined; @@ -124463,7 +128572,7 @@ var ts; // Different declarations have different containers, bail out return undefined; } - if (!container || container.kind === 297 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + if (!container || container.kind === 298 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -124679,6 +128788,10 @@ var ts; default: ts.Debug.assertNever(state.specialSearchKind); } + // Use the parent symbol if the location is commonjs require syntax on javascript files only. + referenceSymbol = ts.isInJSFile(referenceLocation) && referenceLocation.parent.kind === 199 /* BindingElement */ && ts.isRequireVariableDeclaration(referenceLocation.parent) + ? referenceLocation.parent.symbol + : referenceSymbol; getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { @@ -124841,14 +128954,14 @@ var ts; for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; var ctrKeyword = ts.findChildOfKind(decl, 132 /* ConstructorKeyword */, sourceFile); - ts.Debug.assert(decl.kind === 166 /* Constructor */ && !!ctrKeyword); + ts.Debug.assert(decl.kind === 167 /* Constructor */ && !!ctrKeyword); addNode(ctrKeyword); } } if (classSymbol.exports) { classSymbol.exports.forEach(function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 165 /* MethodDeclaration */) { + if (decl && decl.kind === 166 /* MethodDeclaration */) { var body = decl.body; if (body) { forEachDescendantOfKind(body, 107 /* ThisKeyword */, function (thisKeyword) { @@ -124872,7 +128985,7 @@ var ts; } for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 166 /* Constructor */); + ts.Debug.assert(decl.kind === 167 /* Constructor */); var body = decl.body; if (body) { forEachDescendantOfKind(body, 105 /* SuperKeyword */, function (node) { @@ -124902,7 +129015,7 @@ var ts; if (refNode.kind !== 78 /* Identifier */) { return; } - if (refNode.parent.kind === 289 /* ShorthandPropertyAssignment */) { + if (refNode.parent.kind === 290 /* ShorthandPropertyAssignment */) { // Go ahead and dereference the shorthand assignment by going to its definition getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); } @@ -124922,7 +129035,7 @@ var ts; } else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) { var body = typeHavingNode.body; - if (body.kind === 230 /* Block */) { + if (body.kind === 231 /* Block */) { ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression) addIfImplementation(returnStatement.expression); @@ -124950,13 +129063,13 @@ var ts; */ function isImplementationExpression(node) { switch (node.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isImplementationExpression(node.expression); - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: - case 200 /* ObjectLiteralExpression */: - case 221 /* ClassExpression */: - case 199 /* ArrayLiteralExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 201 /* ObjectLiteralExpression */: + case 222 /* ClassExpression */: + case 200 /* ArrayLiteralExpression */: return true; default: return false; @@ -125009,13 +129122,13 @@ var ts; // Whether 'super' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -125036,41 +129149,43 @@ var ts; return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function isParameterName(node) { - return node.kind === 78 /* Identifier */ && node.parent.kind === 160 /* Parameter */ && node.parent.name === node; + return node.kind === 78 /* Identifier */ && node.parent.kind === 161 /* Parameter */ && node.parent.name === node; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { + staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning object literals break; } // falls through - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) { return undefined; } // falls through - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: break; // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. default: return undefined; } - var references = ts.flatMap(searchSpaceNode.kind === 297 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { + var references = ts.flatMap(searchSpaceNode.kind === 298 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) { if (!ts.isThis(node)) { @@ -125078,19 +129193,20 @@ var ts; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: return searchSpaceNode.symbol === container.symbol; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: - // Make sure the container belongs to the same class + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 201 /* ObjectLiteralExpression */: + // Make sure the container belongs to the same class/object literals // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getSyntacticModifierFlags(container) & 32 /* Static */) === staticFlag; - case 297 /* SourceFile */: - return container.kind === 297 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node); + case 298 /* SourceFile */: + return container.kind === 298 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node); } }); }).map(function (n) { return nodeEntry(n); }); @@ -125200,7 +129316,7 @@ 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]); } - var exportSpecifier = ts.getDeclarationOfKind(symbol, 270 /* ExportSpecifier */); + var exportSpecifier = ts.getDeclarationOfKind(symbol, 271 /* ExportSpecifier */); if (!isForRenamePopulateSearchSymbolSet || exportSpecifier && !exportSpecifier.propertyName) { var localSymbol = exportSpecifier && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); if (localSymbol) { @@ -125245,7 +129361,7 @@ var ts; }); } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - var bindingElement = ts.getDeclarationOfKind(symbol, 198 /* BindingElement */); + var bindingElement = ts.getDeclarationOfKind(symbol, 199 /* BindingElement */); if (bindingElement && ts.isObjectBindingElementWithoutPropertyName(bindingElement)) { return ts.getPropertySymbolFromBindingElement(checker, bindingElement); } @@ -125498,16 +129614,16 @@ var ts; return; } switch (node.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: - if (node.parent.kind === 200 /* ObjectLiteralExpression */) { + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + if (node.parent.kind === 201 /* ObjectLiteralExpression */) { return (_a = ts.getAssignedName(node.parent)) === null || _a === void 0 ? void 0 : _a.getText(); } return (_b = ts.getNameOfDeclaration(node.parent)) === null || _b === void 0 ? void 0 : _b.getText(); - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: if (ts.isModuleBlock(node.parent) && ts.isIdentifier(node.parent.parent.name)) { return node.parent.parent.name.getText(); } @@ -125713,55 +129829,55 @@ var ts; } switch (node.kind) { case 78 /* Identifier */: - case 260 /* ImportEqualsDeclaration */: - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: // do not descend into nodes that cannot contain callable nodes return; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: // do not descend into the type side of an assertion collect(node.expression); return; - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: // do not descend into the type of a variable or parameter declaration collect(node.name); collect(node.initializer); return; - case 203 /* CallExpression */: + case 204 /* CallExpression */: // do not descend into the type arguments of a call expression recordCallSite(node); collect(node.expression); ts.forEach(node.arguments, collect); return; - case 204 /* NewExpression */: + case 205 /* NewExpression */: // do not descend into the type arguments of a new expression recordCallSite(node); collect(node.expression); ts.forEach(node.arguments, collect); return; - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: // do not descend into the type arguments of a tagged template expression recordCallSite(node); collect(node.tag); collect(node.template); return; - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: // do not descend into the type arguments of a JsxOpeningLikeElement recordCallSite(node); collect(node.tagName); collect(node.attributes); return; - case 161 /* Decorator */: + case 162 /* Decorator */: recordCallSite(node); collect(node.expression); return; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: recordCallSite(node); ts.forEachChild(node, collect); break; @@ -125811,22 +129927,22 @@ var ts; var callSites = []; var collect = createCallSiteCollector(program, callSites); switch (node.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: collectCallSitesOfSourceFile(node, collect); break; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: collectCallSitesOfModuleDeclaration(node, collect); break; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: collectCallSitesOfFunctionLikeDeclaration(program.getTypeChecker(), node, collect); break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: collectCallSitesOfClassLikeDeclaration(node, collect); break; default: @@ -125959,7 +130075,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_4 = function (sourceFile) { + var _loop_5 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.fileName); var newImportFromPath = newFromOld !== null && newFromOld !== void 0 ? newFromOld : sourceFile.fileName; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -125976,7 +130092,7 @@ var ts; }, function (importLiteral) { var importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); // No need to update if it's an ambient module^M - if (importedModuleSymbol && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) + if ((importedModuleSymbol === null || importedModuleSymbol === void 0 ? void 0 : importedModuleSymbol.declarations) && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) return undefined; var toImport = oldFromNew !== undefined // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. @@ -125991,7 +130107,7 @@ var ts; }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_4(sourceFile); + _loop_5(sourceFile); } } function combineNormal(pathA, pathB) { @@ -126082,8 +130198,10 @@ var ts; (function (GoToDefinition) { function getDefinitionAtPosition(program, sourceFile, position) { var resolvedRef = getReferenceAtPosition(sourceFile, position, program); - if (resolvedRef) { - return [getDefinitionInfoForFileReference(resolvedRef.reference.fileName, resolvedRef.file.fileName)]; + var fileReferenceDefinition = resolvedRef && [getDefinitionInfoForFileReference(resolvedRef.reference.fileName, resolvedRef.fileName, resolvedRef.unverified)] || ts.emptyArray; + if (resolvedRef === null || resolvedRef === void 0 ? void 0 : resolvedRef.file) { + // If `file` is missing, do a symbol-based lookup as well + return fileReferenceDefinition; } var node = ts.getTouchingPropertyName(sourceFile, position); if (node === sourceFile) { @@ -126100,7 +130218,7 @@ var ts; // Could not find a symbol e.g. node is string or number keyword, // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol if (!symbol) { - return getDefinitionInfoForIndexSignatures(node, typeChecker); + return ts.concatenate(fileReferenceDefinition, getDefinitionInfoForIndexSignatures(node, typeChecker)); } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. @@ -126122,9 +130240,10 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 289 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 290 /* ShorthandPropertyAssignment */) { var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); - return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : []; + var definitions = (shorthandSymbol_1 === null || shorthandSymbol_1 === void 0 ? void 0 : shorthandSymbol_1.declarations) ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : ts.emptyArray; + return ts.concatenate(definitions, getDefinitionFromObjectLiteralElement(typeChecker, node) || ts.emptyArray); } // If the node is the name of a BindingElement within an ObjectBindingPattern instead of just returning the // declaration the symbol (which is itself), we should try to get to the original type of the ObjectBindingPattern @@ -126146,25 +130265,7 @@ var ts; return prop && getDefinitionFromSymbol(typeChecker, prop, node); }); } - // If the current location we want to find its definition is in an object literal, try to get the contextual type for the - // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. - // For example - // interface Props{ - // /*first*/prop1: number - // prop2: boolean - // } - // function Foo(arg: Props) {} - // Foo( { pr/*1*/op1: 10, prop2: true }) - var element = ts.getContainingObjectLiteralElement(node); - if (element) { - var contextualType = element && typeChecker.getContextualType(element.parent); - if (contextualType) { - return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) { - return getDefinitionFromSymbol(typeChecker, propertySymbol, node); - }); - } - } - return getDefinitionFromSymbol(typeChecker, symbol, node); + return ts.concatenate(fileReferenceDefinition, getDefinitionFromObjectLiteralElement(typeChecker, node) || getDefinitionFromSymbol(typeChecker, symbol, node)); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; /** @@ -126178,22 +130279,60 @@ var ts; || ts.isAssignmentExpression(calledDeclaration.parent) || (!ts.isCallLikeExpression(calledDeclaration.parent) && s === calledDeclaration.parent.symbol); } + // If the current location we want to find its definition is in an object literal, try to get the contextual type for the + // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. + // For example + // interface Props{ + // /*first*/prop1: number + // prop2: boolean + // } + // function Foo(arg: Props) {} + // Foo( { pr/*1*/op1: 10, prop2: true }) + function getDefinitionFromObjectLiteralElement(typeChecker, node) { + var element = ts.getContainingObjectLiteralElement(node); + if (element) { + var contextualType = element && typeChecker.getContextualType(element.parent); + if (contextualType) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); + } + } + } function getReferenceAtPosition(sourceFile, position, program) { + var _a, _b; var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); if (referencePath) { var file = program.getSourceFileFromReference(sourceFile, referencePath); - return file && { reference: referencePath, file: file }; + return file && { reference: referencePath, fileName: file.fileName, file: file, unverified: false }; } var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); var file = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217 - return file && { reference: typeReferenceDirective, file: file }; + return file && { reference: typeReferenceDirective, fileName: file.fileName, file: file, unverified: false }; } var libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position); if (libReferenceDirective) { var file = program.getLibFileFromReference(libReferenceDirective); - return file && { reference: libReferenceDirective, file: file }; + return file && { reference: libReferenceDirective, fileName: file.fileName, file: file, unverified: false }; + } + if ((_a = sourceFile.resolvedModules) === null || _a === void 0 ? void 0 : _a.size) { + var node = ts.getTokenAtPosition(sourceFile, position); + if (ts.isModuleSpecifierLike(node) && ts.isExternalModuleNameRelative(node.text) && sourceFile.resolvedModules.has(node.text)) { + var verifiedFileName = (_b = sourceFile.resolvedModules.get(node.text)) === null || _b === void 0 ? void 0 : _b.resolvedFileName; + var fileName = verifiedFileName || ts.resolvePath(ts.getDirectoryPath(sourceFile.fileName), node.text); + return { + file: program.getSourceFile(fileName), + fileName: fileName, + reference: { + pos: node.getStart(), + end: node.getEnd(), + fileName: node.text + }, + unverified: !verifiedFileName, + }; + } } return undefined; } @@ -126264,7 +130403,7 @@ var ts; // get the aliased symbol instead. This allows for goto def on an import e.g. // import {A, B} from "mod"; // to jump to the implementation directly. - if (symbol && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { + if ((symbol === null || symbol === void 0 ? void 0 : symbol.declarations) && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { var aliased = checker.getAliasedSymbol(symbol); if (aliased.declarations) { return aliased; @@ -126285,14 +130424,14 @@ var ts; return true; } switch (declaration.kind) { - case 262 /* ImportClause */: - case 260 /* ImportEqualsDeclaration */: + case 263 /* ImportClause */: + case 261 /* ImportEqualsDeclaration */: return true; - case 265 /* ImportSpecifier */: - return declaration.parent.kind === 264 /* NamedImports */; - case 198 /* BindingElement */: - case 249 /* VariableDeclaration */: - return ts.isInJSFile(declaration) && ts.isRequireVariableDeclaration(declaration, /*requireStringLiteralLikeArgument*/ true); + case 266 /* ImportSpecifier */: + return declaration.parent.kind === 265 /* NamedImports */; + case 199 /* BindingElement */: + case 250 /* VariableDeclaration */: + return ts.isInJSFile(declaration) && ts.isRequireVariableDeclaration(declaration); default: return false; } @@ -126344,7 +130483,38 @@ var ts; var sourceFile = name.getSourceFile(); var textSpan = ts.createTextSpanFromNode(name, sourceFile); return __assign(__assign({ fileName: sourceFile.fileName, textSpan: textSpan, kind: symbolKind, name: symbolName, containerKind: undefined, // TODO: GH#18217 - containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !checker.isDeclarationVisible(declaration) }); + containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !isDefinitionVisible(checker, declaration) }); + } + function isDefinitionVisible(checker, declaration) { + if (checker.isDeclarationVisible(declaration)) + return true; + if (!declaration.parent) + return false; + // Variable initializers are visible if variable is visible + if (ts.hasInitializer(declaration.parent) && declaration.parent.initializer === declaration) + return isDefinitionVisible(checker, declaration.parent); + // Handle some exceptions here like arrow function, members of class and object literal expression which are technically not visible but we want the definition to be determined by its parent + switch (declaration.kind) { + case 164 /* PropertyDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + // Private/protected properties/methods are not visible + if (ts.hasEffectiveModifier(declaration, 8 /* Private */)) + return false; + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 167 /* Constructor */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 201 /* ObjectLiteralExpression */: + case 222 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + return isDefinitionVisible(checker, declaration.parent); + default: + return false; + } } function createDefinitionFromSignatureDeclaration(typeChecker, decl) { return createDefinitionInfo(decl, typeChecker, decl.symbol, decl); @@ -126353,14 +130523,15 @@ var ts; return ts.find(refs, function (ref) { return ts.textRangeContainsPositionInclusive(ref, pos); }); } GoToDefinition.findReferenceInPosition = findReferenceInPosition; - function getDefinitionInfoForFileReference(name, targetFileName) { + function getDefinitionInfoForFileReference(name, targetFileName, unverified) { return { fileName: targetFileName, textSpan: ts.createTextSpanFromBounds(0, 0), kind: "script" /* scriptElement */, name: name, containerName: undefined, - containerKind: undefined, // TODO: GH#18217 + containerKind: undefined, + unverified: unverified, }; } /** Returns a CallLikeExpression where `node` is the target being invoked. */ @@ -126377,9 +130548,9 @@ var ts; } function isConstructorLike(node) { switch (node.kind) { - case 166 /* Constructor */: - case 175 /* ConstructorType */: - case 170 /* ConstructSignature */: + case 167 /* Constructor */: + case 176 /* ConstructorType */: + case 171 /* ConstructSignature */: return true; default: return false; @@ -126436,6 +130607,7 @@ var ts; "kind", "lends", "license", + "link", "listens", "member", "memberof", @@ -126473,78 +130645,115 @@ var ts; ]; var jsDocTagNameCompletionEntries; var jsDocTagCompletionEntries; - function getJsDocCommentsFromDeclarations(declarations) { + function getJsDocCommentsFromDeclarations(declarations, checker) { // Only collect doc comments from duplicate declarations once: // In case of a union property there might be same declaration multiple times // which only varies in type parameter // Eg. const a: Array | Array; a.length // The property length will have two declarations of property length coming // from Array - Array and Array - var documentationComment = []; + var parts = []; ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { var comment = _a[_i].comment; if (comment === undefined) continue; - ts.pushIfUnique(documentationComment, comment); + var newparts = getDisplayPartsFromComment(comment, checker); + if (!ts.contains(parts, newparts, isIdenticalListOfDisplayParts)) { + parts.push(newparts); + } } }); - return ts.intersperse(ts.map(documentationComment, ts.textPart), ts.lineBreakPart()); + return ts.flatten(ts.intersperse(parts, [ts.lineBreakPart()])); } JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function isIdenticalListOfDisplayParts(parts1, parts2) { + return ts.arraysEqual(parts1, parts2, function (p1, p2) { return p1.kind === p2.kind && p1.text === p2.text; }); + } function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 326 /* JSDocParameterTag */: - case 333 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: return [declaration]; - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); } } - function getJsDocTagsFromDeclarations(declarations) { + function getJsDocTagsFromDeclarations(declarations, checker) { // Only collect doc comments from duplicate declarations once. var tags = []; ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { var tag = _a[_i]; - tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); + tags.push({ name: tag.tagName.text, text: getCommentDisplayParts(tag, checker) }); } }); return tags; } JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations; - function getCommentText(tag) { - var comment = tag.comment; - switch (tag.kind) { - case 316 /* JSDocImplementsTag */: + function getDisplayPartsFromComment(comment, checker) { + if (typeof comment === "string") { + return [ts.textPart(comment)]; + } + return ts.flatMap(comment, function (node) { return node.kind === 313 /* JSDocText */ ? [ts.textPart(node.text)] : ts.buildLinkParts(node, checker); }); + } + function getCommentDisplayParts(tag, checker) { + var comment = tag.comment, kind = tag.kind; + var namePart = getTagNameDisplayPart(kind); + switch (kind) { + case 319 /* JSDocImplementsTag */: return withNode(tag.class); - case 315 /* JSDocAugmentsTag */: + case 318 /* JSDocAugmentsTag */: return withNode(tag.class); - case 330 /* JSDocTemplateTag */: - return withList(tag.typeParameters); - case 329 /* JSDocTypeTag */: + case 334 /* JSDocTemplateTag */: + return addComment(tag.typeParameters.map(function (tp) { return tp.getText(); }).join(", ")); + case 333 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 333 /* JSDocPropertyTag */: - case 326 /* JSDocParameterTag */: - case 332 /* JSDocSeeTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 337 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: + case 336 /* JSDocSeeTag */: var name = tag.name; - return name ? withNode(name) : comment; + return name ? withNode(name) + : comment === undefined ? undefined + : getDisplayPartsFromComment(comment, checker); default: - return comment; + return comment === undefined ? undefined : getDisplayPartsFromComment(comment, checker); } function withNode(node) { return addComment(node.getText()); } - function withList(list) { - return addComment(list.map(function (x) { return x.getText(); }).join(", ")); - } function addComment(s) { - return comment === undefined ? s : s + " " + comment; + if (comment) { + if (s.match(/^https?$/)) { + return __spreadArray([ts.textPart(s)], getDisplayPartsFromComment(comment, checker)); + } + else { + return __spreadArray([namePart(s), ts.spacePart()], getDisplayPartsFromComment(comment, checker)); + } + } + else { + return [ts.textPart(s)]; + } + } + } + function getTagNameDisplayPart(kind) { + switch (kind) { + case 330 /* JSDocParameterTag */: + return ts.parameterNamePart; + case 337 /* JSDocPropertyTag */: + return ts.propertyNamePart; + case 334 /* JSDocTemplateTag */: + return ts.typeParameterNamePart; + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + return ts.typeAliasNamePart; + default: + return ts.textPart; } } function getJSDocTagNameCompletions() { @@ -126638,7 +130847,7 @@ var ts; * @param position The (character-indexed) position in the file where the check should * be performed. */ - function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { + function getDocCommentTemplateAtPosition(newLine, sourceFile, position, options) { var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc); if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) { @@ -126650,7 +130859,7 @@ var ts; if (!existingDocComment && tokenStart < position) { return undefined; } - var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); + var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos, options); if (!commentOwnerInfo) { return undefined; } @@ -126700,76 +130909,77 @@ var ts; function returnsDocComment(indentationStr, newLine) { return indentationStr + " * @returns" + newLine; } - function getCommentOwnerInfo(tokenAtPos) { - return ts.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker); + function getCommentOwnerInfo(tokenAtPos, options) { + return ts.forEachAncestor(tokenAtPos, function (n) { return getCommentOwnerInfoWorker(n, options); }); } - function getCommentOwnerInfoWorker(commentOwner) { + function getCommentOwnerInfoWorker(commentOwner, options) { switch (commentOwner.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 164 /* MethodSignature */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 165 /* MethodSignature */: + case 210 /* ArrowFunction */: var host = commentOwner; - return { commentOwner: commentOwner, parameters: host.parameters, hasReturn: hasReturn(host) }; - case 288 /* PropertyAssignment */: - return getCommentOwnerInfoWorker(commentOwner.initializer); - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 162 /* PropertySignature */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: - case 254 /* TypeAliasDeclaration */: + return { commentOwner: commentOwner, parameters: host.parameters, hasReturn: hasReturn(host, options) }; + case 289 /* PropertyAssignment */: + return getCommentOwnerInfoWorker(commentOwner.initializer, options); + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 163 /* PropertySignature */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: + case 255 /* TypeAliasDeclaration */: return { commentOwner: commentOwner }; - case 232 /* VariableStatement */: { + case 233 /* VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; var host_1 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; return host_1 - ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1) } + ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1, options) } : { commentOwner: commentOwner }; } - case 297 /* SourceFile */: + case 298 /* SourceFile */: return "quit"; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: // If in walking up the tree, we hit a a nested namespace declaration, // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - return commentOwner.parent.kind === 256 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; - case 233 /* ExpressionStatement */: - return getCommentOwnerInfoWorker(commentOwner.expression); - case 216 /* BinaryExpression */: { + return commentOwner.parent.kind === 257 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 234 /* ExpressionStatement */: + return getCommentOwnerInfoWorker(commentOwner.expression, options); + case 217 /* BinaryExpression */: { var be = commentOwner; if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } return ts.isFunctionLike(be.right) - ? { commentOwner: commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right) } + ? { commentOwner: commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right, options) } : { commentOwner: commentOwner }; } - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: var init = commentOwner.initializer; if (init && (ts.isFunctionExpression(init) || ts.isArrowFunction(init))) { - return { commentOwner: commentOwner, parameters: init.parameters, hasReturn: hasReturn(init) }; + return { commentOwner: commentOwner, parameters: init.parameters, hasReturn: hasReturn(init, options) }; } } } - function hasReturn(node) { - return ts.isArrowFunction(node) && ts.isExpression(node.body) - || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; }); + function hasReturn(node, options) { + return !!(options === null || options === void 0 ? void 0 : options.generateReturnInDocTemplate) && + (ts.isArrowFunction(node) && ts.isExpression(node.body) + || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; })); } function getRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 207 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 208 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return rightHandSide; - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return ts.find(rightHandSide.members, ts.isConstructorDeclaration); } } @@ -126785,7 +130995,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_5 = function (sourceFile) { + var _loop_6 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -126797,7 +131007,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var sourceFile = sourceFiles_4[_i]; - _loop_5(sourceFile); + _loop_6(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -126828,9 +131038,9 @@ var ts; } function shouldKeepItem(declaration, checker) { switch (declaration.kind) { - case 262 /* ImportClause */: - case 265 /* ImportSpecifier */: - case 260 /* ImportEqualsDeclaration */: + case 263 /* ImportClause */: + case 266 /* ImportSpecifier */: + case 261 /* ImportEqualsDeclaration */: var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217 var imported = checker.getAliasedSymbol(importer); return importer.escapedName !== imported.escapedName; @@ -126840,7 +131050,7 @@ var ts; } function tryAddSingleDeclarationName(declaration, containers) { var name = ts.getNameOfDeclaration(declaration); - return !!name && (pushLiteral(name, containers) || name.kind === 158 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); + return !!name && (pushLiteral(name, containers) || name.kind === 159 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); } // Only added the names of computed properties if they're simple dotted expressions, like: // @@ -126857,7 +131067,7 @@ var ts; // First, if we started with a computed property name, then add all but the last // portion into the container array. var name = ts.getNameOfDeclaration(declaration); - if (name && name.kind === 158 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { + if (name && name.kind === 159 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { return ts.emptyArray; } // Don't include the last portion. @@ -127057,6 +131267,28 @@ var ts; addChildrenRecursively(child); endNode(); } + function addNodeWithRecursiveInitializer(node) { + if (node.initializer && isFunctionOrClassExpression(node.initializer)) { + startNode(node); + ts.forEachChild(node.initializer, addChildrenRecursively); + endNode(); + } + else { + addNodeWithRecursiveChild(node, node.initializer); + } + } + /** + * Historically, we've elided dynamic names from the nav tree (including late bound names), + * but included certain "well known" symbol names. While we no longer distinguish those well-known + * symbols from other unique symbols, we do the below to retain those members in the nav tree. + */ + function hasNavigationBarName(node) { + return !ts.hasDynamicName(node) || + (node.kind !== 217 /* BinaryExpression */ && + ts.isPropertyAccessExpression(node.name.expression) && + ts.isIdentifier(node.name.expression.expression) && + ts.idText(node.name.expression.expression) === "Symbol"); + } /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ function addChildrenRecursively(node) { var _a; @@ -127065,7 +131297,7 @@ var ts; return; } switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. var ctr = node; addNodeWithRecursiveChild(ctr, ctr.body); @@ -127077,21 +131309,25 @@ var ts; } } break; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 164 /* MethodSignature */: - if (!ts.hasDynamicName(node)) { + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 165 /* MethodSignature */: + if (hasNavigationBarName(node)) { addNodeWithRecursiveChild(node, node.body); } break; - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - if (!ts.hasDynamicName(node)) { + case 164 /* PropertyDeclaration */: + if (hasNavigationBarName(node)) { + addNodeWithRecursiveInitializer(node); + } + break; + case 163 /* PropertySignature */: + if (hasNavigationBarName(node)) { addLeafNode(node); } break; - case 262 /* ImportClause */: + case 263 /* ImportClause */: var importClause = node; // Handle default import case e.g.: // import d from "mod"; @@ -127103,7 +131339,7 @@ var ts; // import {a, b as B} from "mod"; var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 263 /* NamespaceImport */) { + if (namedBindings.kind === 264 /* NamespaceImport */) { addLeafNode(namedBindings); } else { @@ -127114,32 +131350,27 @@ var ts; } } break; - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: addNodeWithRecursiveChild(node, node.name); break; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: var expression = node.expression; // Use the expression as the name of the SpreadAssignment, otherwise show as . ts.isIdentifier(expression) ? addLeafNode(node, expression) : addLeafNode(node); break; - case 198 /* BindingElement */: - case 288 /* PropertyAssignment */: - case 249 /* VariableDeclaration */: - var _e = node, name = _e.name, initializer = _e.initializer; - if (ts.isBindingPattern(name)) { - addChildrenRecursively(name); - } - else if (initializer && isFunctionOrClassExpression(initializer)) { - // Add a node for the VariableDeclaration, but not for the initializer. - startNode(node); - ts.forEachChild(initializer, addChildrenRecursively); - endNode(); + case 199 /* BindingElement */: + case 289 /* PropertyAssignment */: + case 250 /* VariableDeclaration */: { + var child = node; + if (ts.isBindingPattern(child.name)) { + addChildrenRecursively(child.name); } else { - addNodeWithRecursiveChild(node, initializer); + addNodeWithRecursiveInitializer(child); } break; - case 251 /* FunctionDeclaration */: + } + case 252 /* FunctionDeclaration */: var nameNode = node.name; // If we see a function declaration track as a possible ES5 class if (nameNode && ts.isIdentifier(nameNode)) { @@ -127147,34 +131378,34 @@ var ts; } addNodeWithRecursiveChild(node, node.body); break; - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: addNodeWithRecursiveChild(node, node.body); break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: startNode(node); - for (var _f = 0, _g = node.members; _f < _g.length; _f++) { - var member = _g[_f]; + for (var _e = 0, _f = node.members; _e < _f.length; _e++) { + var member = _f[_e]; if (!isComputedProperty(member)) { addLeafNode(member); } } endNode(); break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: startNode(node); - for (var _h = 0, _j = node.members; _h < _j.length; _h++) { - var member = _j[_h]; + for (var _g = 0, _h = node.members; _g < _h.length; _g++) { + var member = _h[_g]; addChildrenRecursively(member); } endNode(); break; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 266 /* ExportAssignment */: { + case 267 /* ExportAssignment */: { var expression_1 = node.expression; var child = ts.isObjectLiteralExpression(expression_1) || ts.isCallExpression(expression_1) ? expression_1 : ts.isArrowFunction(expression_1) || ts.isFunctionExpression(expression_1) ? expression_1.body : undefined; @@ -127188,16 +131419,16 @@ var ts; } break; } - case 270 /* ExportSpecifier */: - case 260 /* ImportEqualsDeclaration */: - case 171 /* IndexSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 254 /* TypeAliasDeclaration */: + case 271 /* ExportSpecifier */: + case 261 /* ImportEqualsDeclaration */: + case 172 /* IndexSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 255 /* TypeAliasDeclaration */: addLeafNode(node); break; - case 203 /* CallExpression */: - case 216 /* BinaryExpression */: { + case 204 /* CallExpression */: + case 217 /* BinaryExpression */: { var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: @@ -127249,7 +131480,7 @@ var ts; defineCall.arguments[0] : defineCall.arguments[0].expression; var memberName = defineCall.arguments[1]; - var _k = startNestedNodes(node, className), depth = _k[0], classNameIdentifier = _k[1]; + var _j = startNestedNodes(node, className), depth = _j[0], classNameIdentifier = _j[1]; startNode(node, classNameIdentifier); startNode(node, ts.setTextRange(ts.factory.createIdentifier(memberName.text), memberName)); addChildrenRecursively(node.arguments[2]); @@ -127439,13 +131670,14 @@ var ts; return false; } switch (a.kind) { - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return ts.hasSyntacticModifier(a, 32 /* Static */) === ts.hasSyntacticModifier(b, 32 /* Static */); - case 256 /* ModuleDeclaration */: - return areSameModule(a, b); + case 257 /* ModuleDeclaration */: + return areSameModule(a, b) + && getFullyQualifiedModuleName(a) === getFullyQualifiedModuleName(b); default: return true; } @@ -127462,8 +131694,7 @@ var ts; // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { - // TODO: GH#18217 - return a.body.kind === b.body.kind && (a.body.kind !== 256 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); + return a.body.kind === b.body.kind && (a.body.kind !== 257 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); } /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { @@ -127493,7 +131724,7 @@ var ts; * So `new()` can still come before an `aardvark` method. */ function tryGetName(node) { - if (node.kind === 256 /* ModuleDeclaration */) { + if (node.kind === 257 /* ModuleDeclaration */) { return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); @@ -127502,16 +131733,16 @@ var ts; return propertyName && ts.unescapeLeadingUnderscores(propertyName); } switch (node.kind) { - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 221 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 222 /* ClassExpression */: return getFunctionOrClassName(node); default: return undefined; } } function getItemName(node, name) { - if (node.kind === 256 /* ModuleDeclaration */) { + if (node.kind === 257 /* ModuleDeclaration */) { return cleanText(getModuleName(node)); } if (name) { @@ -127523,18 +131754,18 @@ var ts; } } switch (node.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: var sourceFile = node; return ts.isExternalModule(sourceFile) ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" : ""; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return ts.isExportAssignment(node) && node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; - case 209 /* ArrowFunction */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: if (ts.getSyntacticModifierFlags(node) & 512 /* Default */) { return "default"; } @@ -127542,13 +131773,13 @@ var ts; // (eg: "app\n.onactivated"), so we should remove the whitespace for readability in the // navigation bar. return getFunctionOrClassName(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return "constructor"; - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: return "new()"; - case 169 /* CallSignature */: + case 170 /* CallSignature */: return "()"; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: return "[]"; default: return ""; @@ -127581,19 +131812,19 @@ var ts; } // Some nodes are otherwise important enough to always include in the primary navigation menu. switch (navigationBarNodeKind(item)) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 255 /* EnumDeclaration */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 297 /* SourceFile */: - case 254 /* TypeAliasDeclaration */: - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 256 /* EnumDeclaration */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 298 /* SourceFile */: + case 255 /* TypeAliasDeclaration */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: return true; - case 209 /* ArrowFunction */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; @@ -127603,10 +131834,10 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 257 /* ModuleBlock */: - case 297 /* SourceFile */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: + case 258 /* ModuleBlock */: + case 298 /* SourceFile */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: return true; default: return false; @@ -127663,9 +131894,12 @@ var ts; if (ts.isAmbientModule(moduleDeclaration)) { return ts.getTextOfNode(moduleDeclaration.name); } + return getFullyQualifiedModuleName(moduleDeclaration); + } + function getFullyQualifiedModuleName(moduleDeclaration) { // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = [ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)]; - while (moduleDeclaration.body && moduleDeclaration.body.kind === 256 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 257 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } @@ -127679,13 +131913,13 @@ var ts; return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { - return !member.name || member.name.kind === 158 /* ComputedPropertyName */; + return !member.name || member.name.kind === 159 /* ComputedPropertyName */; } function getNodeSpan(node) { - return node.kind === 297 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); + return node.kind === 298 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); } function getModifiers(node) { - if (node.parent && node.parent.kind === 249 /* VariableDeclaration */) { + if (node.parent && node.parent.kind === 250 /* VariableDeclaration */) { node = node.parent; } return ts.getNodeModifiers(node); @@ -127743,9 +131977,9 @@ var ts; } function isFunctionOrClassExpression(node) { switch (node.kind) { - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: - case 221 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 222 /* ClassExpression */: return true; default: return false; @@ -127774,9 +132008,9 @@ var ts; * 2) Coalescing imports from the same module * 3) Sorting imports */ - function organizeImports(sourceFile, formatContext, host, program, preferences) { + function organizeImports(sourceFile, formatContext, host, program, preferences, skipDestructiveCodeActions) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext, preferences: preferences }); - var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; + var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program, skipDestructiveCodeActions)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; // All of the old ImportDeclarations in the file, in syntactic order. var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports); @@ -127811,26 +132045,35 @@ var ts; ? coalesce(importGroup) : importGroup; }); - // Delete or replace the first import. + // Delete all nodes if there are no imports. if (newImportDecls.length === 0) { - changeTracker.delete(sourceFile, oldImportDecls[0]); + // Consider the first node to have trailingTrivia as we want to exclude the + // "header" comment. + changeTracker.deleteNodes(sourceFile, oldImportDecls, { + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, + }, /*hasTrailingComment*/ true); } else { // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. - changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { + var replaceOptions = { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), - }); - } - // Delete any subsequent imports. - for (var i = 1; i < oldImportDecls.length; i++) { - changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + }; + changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, replaceOptions); + var hasTrailingComment = changeTracker.nodeHasTrailingComment(sourceFile, oldImportDecls[0], replaceOptions); + changeTracker.deleteNodes(sourceFile, oldImportDecls.slice(1), { + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, + }, hasTrailingComment); } } } OrganizeImports.organizeImports = organizeImports; - function removeUnusedImports(oldImports, sourceFile, program) { + function removeUnusedImports(oldImports, sourceFile, program, skipDestructiveCodeActions) { + // As a precaution, consider unused import detection to be destructive (GH #43051) + if (skipDestructiveCodeActions) { + return oldImports; + } var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); var jsxFragmentFactory = typeChecker.getJsxFragmentFactory(sourceFile); @@ -128101,11 +132344,11 @@ var ts; function getModuleSpecifierExpression(declaration) { var _a; switch (declaration.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return (_a = ts.tryCast(declaration.moduleReference, ts.isExternalModuleReference)) === null || _a === void 0 ? void 0 : _a.expression; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return declaration.moduleSpecifier; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return declaration.declarationList.declarations[0].initializer.arguments[0]; } } @@ -128144,19 +132387,19 @@ var ts; function getImportKindOrder(s1) { var _a; switch (s1.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: if (!s1.importClause) return 0; if (s1.importClause.isTypeOnly) return 1; - if (((_a = s1.importClause.namedBindings) === null || _a === void 0 ? void 0 : _a.kind) === 263 /* NamespaceImport */) + if (((_a = s1.importClause.namedBindings) === null || _a === void 0 ? void 0 : _a.kind) === 264 /* NamespaceImport */) return 2; if (s1.importClause.name) return 3; return 4; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return 5; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return 6; } } @@ -128312,7 +132555,7 @@ var ts; } function getOutliningSpanForNode(n, sourceFile) { switch (n.kind) { - case 230 /* Block */: + case 231 /* Block */: if (ts.isFunctionLike(n.parent)) { return functionSpan(n.parent, n, sourceFile); } @@ -128320,16 +132563,16 @@ var ts; // If the latter, we want to collapse the block, but consider its hint span // to be the entire span of the parent. switch (n.parent.kind) { - case 235 /* DoStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 237 /* ForStatement */: - case 234 /* IfStatement */: - case 236 /* WhileStatement */: - case 243 /* WithStatement */: - case 287 /* CatchClause */: + case 236 /* DoStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 238 /* ForStatement */: + case 235 /* IfStatement */: + case 237 /* WhileStatement */: + case 244 /* WithStatement */: + case 288 /* CatchClause */: return spanForNode(n.parent); - case 247 /* TryStatement */: + case 248 /* TryStatement */: // Could be the try-block, or the finally-block. var tryStatement = n.parent; if (tryStatement.tryBlock === n) { @@ -128346,40 +132589,40 @@ var ts; // the span of the block, independent of any parent span. return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */); } - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return spanForNode(n.parent); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 258 /* CaseBlock */: - case 177 /* TypeLiteral */: - case 196 /* ObjectBindingPattern */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 259 /* CaseBlock */: + case 178 /* TypeLiteral */: + case 197 /* ObjectBindingPattern */: return spanForNode(n); - case 179 /* TupleType */: + case 180 /* TupleType */: return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !ts.isTupleTypeNode(n.parent), 22 /* OpenBracketToken */); - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: return spanForNodeArray(n.statements); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return spanForObjectOrArrayLiteral(n); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return spanForObjectOrArrayLiteral(n, 22 /* OpenBracketToken */); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return spanForJSXElement(n); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return spanForJSXFragment(n); - case 274 /* JsxSelfClosingElement */: - case 275 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: return spanForJSXAttributes(n.attributes); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: case 14 /* NoSubstitutionTemplateLiteral */: return spanForTemplateLiteral(n); - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !ts.isBindingElement(n.parent), 22 /* OpenBracketToken */); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return spanForArrowFunction(n); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return spanForCallExpression(n); } function spanForCallExpression(node) { @@ -128446,7 +132689,7 @@ var ts; function functionSpan(node, body, sourceFile) { var openToken = tryGetFunctionOpenToken(node, body, sourceFile); var closeToken = ts.findChildOfKind(body, 19 /* CloseBraceToken */, sourceFile); - return openToken && closeToken && spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ node.kind !== 209 /* ArrowFunction */); + return openToken && closeToken && spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ node.kind !== 210 /* ArrowFunction */); } function spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse, useFullStart) { if (autoCollapse === void 0) { autoCollapse = false; } @@ -128749,15 +132992,15 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_6 = function (start) { + var _loop_7 = 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_1 = _loop_6(start); - if (typeof state_1 === "object") - return state_1.value; + var state_2 = _loop_7(start); + if (typeof state_2 === "object") + return state_2.value; } return -1; } @@ -129309,7 +133552,7 @@ var ts; function getRenameInfo(program, sourceFile, position, options) { var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position)); if (nodeIsEligibleForRename(node)) { - var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }, options); + var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, options); if (renameInfo) { return renameInfo; } @@ -129317,7 +133560,7 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); } Rename.getRenameInfo = getRenameInfo; - function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile, options) { + function getRenameInfoForNode(node, typeChecker, sourceFile, program, options) { var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) { if (ts.isStringLiteralLike(node)) { @@ -129337,7 +133580,7 @@ var ts; if (!declarations || declarations.length === 0) return; // Disallow rename for elements that are defined in the standard TypeScript library. - if (declarations.some(isDefinedInLibraryFile)) { + if (declarations.some(function (declaration) { return isDefinedInLibraryFile(program, declaration); })) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } // Cannot rename `default` as in `import { default as foo } from "./someModule"; @@ -129348,18 +133591,22 @@ var ts; return options && options.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 158 /* ComputedPropertyName */) + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 159 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) : undefined; var displayName = specifierName || typeChecker.symbolToString(symbol); var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(typeChecker, symbol), node, sourceFile); } + function isDefinedInLibraryFile(program, declaration) { + var sourceFile = declaration.getSourceFile(); + return program.isSourceFileDefaultLibrary(sourceFile) && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */); + } function getRenameInfoForModule(node, sourceFile, moduleSymbol) { if (!ts.isExternalModuleNameRelative(node.text)) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); } - var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var moduleSourceFile = moduleSymbol.declarations && ts.find(moduleSymbol.declarations, ts.isSourceFile); if (!moduleSourceFile) return undefined; var withoutIndex = ts.endsWith(node.text, "/index") || ts.endsWith(node.text, "/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); @@ -129440,6 +133687,10 @@ var ts; if (ts.getTokenPosOfNode(node, sourceFile, /*includeJsDoc*/ true) > pos) { break outer; } + var comment = ts.singleOrUndefined(ts.getTrailingCommentRanges(sourceFile.text, node.end)); + if (comment && comment.kind === 2 /* SingleLineCommentTrivia */) { + pushSelectionCommentRange(comment.pos, comment.end); + } if (positionShouldSnapToNode(sourceFile, pos, node)) { // 1. Blocks are effectively redundant with SyntaxLists. // 2. TemplateSpans, along with the SyntaxLists containing them, are a somewhat unintuitive grouping @@ -129502,6 +133753,14 @@ var ts; } } } + function pushSelectionCommentRange(start, end) { + pushSelectionRange(start, end); + var pos = start; + while (sourceFile.text.charCodeAt(pos) === 47 /* slash */) { + pos++; + } + pushSelectionRange(pos, end); + } } SmartSelectionRange.getSmartSelectionRange = getSmartSelectionRange; /** @@ -129565,7 +133824,7 @@ var ts; var groupedWithBrackets = groupChildren(groupedWithPlusMinusTokens, function (_a) { var kind = _a.kind; return kind === 22 /* OpenBracketToken */ || - kind === 159 /* TypeParameter */ || + kind === 160 /* TypeParameter */ || kind === 23 /* CloseBracketToken */; }); return [ @@ -129679,22 +133938,22 @@ var ts; return kind === 18 /* OpenBraceToken */ || kind === 22 /* OpenBracketToken */ || kind === 20 /* OpenParenToken */ - || kind === 275 /* JsxOpeningElement */; + || kind === 276 /* JsxOpeningElement */; } function isListCloser(token) { var kind = token && token.kind; return kind === 19 /* CloseBraceToken */ || kind === 23 /* CloseBracketToken */ || kind === 21 /* CloseParenToken */ - || kind === 276 /* JsxClosingElement */; + || kind === 277 /* JsxClosingElement */; } function getEndPos(sourceFile, node) { switch (node.kind) { - case 326 /* JSDocParameterTag */: - case 324 /* JSDocCallbackTag */: - case 333 /* JSDocPropertyTag */: - case 331 /* JSDocTypedefTag */: - case 328 /* JSDocThisTag */: + case 330 /* JSDocParameterTag */: + case 328 /* JSDocCallbackTag */: + case 337 /* JSDocPropertyTag */: + case 335 /* JSDocTypedefTag */: + case 332 /* JSDocThisTag */: return sourceFile.getLineEndOfPosition(node.getStart()); default: return node.getEnd(); @@ -129904,10 +134163,10 @@ var ts; } return undefined; } - else if (ts.isTemplateHead(node) && parent.parent.kind === 205 /* TaggedTemplateExpression */) { + else if (ts.isTemplateHead(node) && parent.parent.kind === 206 /* TaggedTemplateExpression */) { var templateExpression = parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 218 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 219 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } @@ -129976,17 +134235,17 @@ var ts; return undefined; var parent = startingToken.parent; switch (parent.kind) { - case 207 /* ParenthesizedExpression */: - case 165 /* MethodDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 208 /* ParenthesizedExpression */: + case 166 /* MethodDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: var info = getArgumentOrParameterListInfo(startingToken, sourceFile); if (!info) return undefined; var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; var contextualType = ts.isMethodDeclaration(parent) ? checker.getContextualTypeForObjectLiteralElement(parent) : checker.getContextualType(parent); return contextualType && { contextualType: contextualType, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; - case 216 /* BinaryExpression */: { + case 217 /* BinaryExpression */: { var highestBinary = getHighestBinary(parent); var contextualType_1 = checker.getContextualType(highestBinary); var argumentIndex_1 = startingToken.kind === 20 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1; @@ -130110,7 +134369,7 @@ var ts; // | | // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. - if (template.kind === 218 /* TemplateExpression */) { + if (template.kind === 219 /* TemplateExpression */) { var lastSpan = ts.last(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -130119,7 +134378,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { - var _loop_7 = function (n) { + var _loop_8 = 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.formatSyntaxKind(n.kind) + ", parent: " + ts.Debug.formatSyntaxKind(n.parent.kind); }); @@ -130129,9 +134388,9 @@ var ts; } }; for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) { - var state_2 = _loop_7(n); - if (typeof state_2 === "object") - return state_2.value; + var state_3 = _loop_8(n); + if (typeof state_3 === "object") + return state_3.value; } return undefined; } @@ -130181,7 +134440,19 @@ var ts; itemsSeen += item.length; } 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: ts.flatMapToMutable(items, ts.identity), applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var help = { items: ts.flatMapToMutable(items, ts.identity), applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var selected = help.items[selectedItemIndex]; + if (selected.isVariadic) { + var firstRest = ts.findIndex(selected.parameters, function (p) { return !!p.isRest; }); + if (-1 < firstRest && firstRest < selected.parameters.length - 1) { + // We don't have any code to get this correct; instead, don't highlight a current parameter AT ALL + help.argumentIndex = selected.parameters.length; + } + else { + help.argumentIndex = Math.min(help.argumentIndex, selected.parameters.length - 1); + } + } + return help; } function createTypeHelpItems(symbol, _a, sourceFile, checker) { var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; @@ -130196,7 +134467,7 @@ var ts; 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 tags = symbol.getJsDocTags(checker); var prefixDisplayParts = __spreadArray(__spreadArray([], typeSymbolDisplay), [ts.punctuationPart(29 /* LessThanToken */)]); return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(31 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; } @@ -130263,14 +134534,15 @@ var ts; printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); var isOptional = checker.isOptionalParameter(parameter.valueDeclaration); - return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional }; + var isRest = !!(parameter.checkFlags & 32768 /* RestParameter */); + return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional, isRest: isRest }; } function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { var displayParts = ts.mapToDisplayParts(function (writer) { var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false, isRest: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -130480,7 +134752,7 @@ var ts; diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); } } - if (ts.isFunctionLikeDeclaration(node)) { + if (canBeConvertedToAsync(node)) { addConvertToAsyncFunctionDiagnostics(node, checker, diags); } node.forEachChild(check); @@ -130491,11 +134763,11 @@ var ts; function containsTopLevelCommonjs(sourceFile) { return sourceFile.statements.some(function (statement) { switch (statement.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); }); - case 233 /* ExpressionStatement */: { + case 234 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); @@ -130512,12 +134784,12 @@ var ts; } function importNameForConvertToDefaultImport(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; - return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 263 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 264 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : undefined; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return node.name; default: return undefined; @@ -130533,35 +134805,35 @@ var ts; return !ts.isAsyncFunction(node) && node.body && ts.isBlock(node.body) && - hasReturnStatementWithPromiseHandler(node.body) && + hasReturnStatementWithPromiseHandler(node.body, checker) && returnsPromise(node, checker); } function returnsPromise(node, checker) { - var functionType = checker.getTypeAtLocation(node); - var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); - var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; + var signature = checker.getSignatureFromDeclaration(node); + var returnType = signature ? checker.getReturnTypeOfSignature(signature) : undefined; return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); } + ts.returnsPromise = returnsPromise; function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } - function hasReturnStatementWithPromiseHandler(body) { - return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); + function hasReturnStatementWithPromiseHandler(body, checker) { + return !!ts.forEachReturnStatement(body, function (statement) { return isReturnStatementWithFixablePromiseHandler(statement, checker); }); } - function isReturnStatementWithFixablePromiseHandler(node) { - return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); + function isReturnStatementWithFixablePromiseHandler(node, checker) { + return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression, checker); } ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler; // Should be kept up to date with transformExpression in convertToAsyncFunction.ts - function isFixablePromiseHandler(node) { + function isFixablePromiseHandler(node, checker) { // ensure outermost call exists and is a promise handler - if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + if (!isPromiseHandler(node) || !node.arguments.every(function (arg) { return isFixablePromiseArgument(arg, checker); })) { 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)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(function (arg) { return isFixablePromiseArgument(arg, checker); })) { return false; } currentNode = currentNode.expression; @@ -130584,16 +134856,24 @@ var ts; }); } // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts - function isFixablePromiseArgument(arg) { + function isFixablePromiseArgument(arg, checker) { switch (arg.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true); // falls through case 103 /* NullKeyword */: - case 78 /* Identifier */: // identifier includes undefined return true; + case 78 /* Identifier */: + case 202 /* PropertyAccessExpression */: { + var symbol = checker.getSymbolAtLocation(arg); + if (!symbol) { + return false; + } + return checker.isUndefinedSymbol(symbol) || + ts.some(ts.skipAlias(symbol, checker).declarations, function (d) { return ts.isFunctionLike(d) || ts.hasInitializer(d) && !!d.initializer && ts.isFunctionLike(d.initializer); }); + } default: return false; } @@ -130603,18 +134883,30 @@ var ts; } function canBeConvertedToClass(node, checker) { var _a, _b, _c, _d; - if (node.kind === 208 /* FunctionExpression */) { + if (node.kind === 209 /* FunctionExpression */) { if (ts.isVariableDeclaration(node.parent) && ((_a = node.symbol.members) === null || _a === void 0 ? void 0 : _a.size)) { return true; } var symbol = checker.getSymbolOfExpando(node, /*allowDeclaration*/ false); return !!(symbol && (((_b = symbol.exports) === null || _b === void 0 ? void 0 : _b.size) || ((_c = symbol.members) === null || _c === void 0 ? void 0 : _c.size))); } - if (node.kind === 251 /* FunctionDeclaration */) { + if (node.kind === 252 /* FunctionDeclaration */) { return !!((_d = node.symbol.members) === null || _d === void 0 ? void 0 : _d.size); } return false; } + function canBeConvertedToAsync(node) { + switch (node.kind) { + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + return true; + default: + return false; + } + } + ts.canBeConvertedToAsync = canBeConvertedToAsync; })(ts || (ts = {})); /* @internal */ var ts; @@ -130630,7 +134922,7 @@ var ts; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32 /* Class */) { - return ts.getDeclarationOfKind(symbol, 221 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 222 /* ClassExpression */) ? "local class" /* localClassElement */ : "class" /* classElement */; } if (flags & 384 /* Enum */) @@ -130714,11 +135006,11 @@ var ts; // If we requested completions after `x.` at the top-level, we may be at a source file location. switch (location.parent && location.parent.kind) { // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. - case 275 /* JsxOpeningElement */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: return location.kind === 78 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return "JSX attribute" /* jsxAttribute */; default: return "property" /* memberVariableElement */; @@ -130764,6 +135056,7 @@ var ts; SymbolDisplay.getSymbolModifiers = getSymbolModifiers; // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) { + var _a; if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } var displayParts = []; var documentation = []; @@ -130787,8 +135080,8 @@ var ts; symbolKind = "property" /* memberVariableElement */; } var signature = void 0; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (location.parent && location.parent.kind === 201 /* PropertyAccessExpression */) { + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (location.parent && location.parent.kind === 202 /* PropertyAccessExpression */) { var right = location.parent.name; // Either the location is on the right of a property access, or on the left and the right is missing if (right === location || (right && right.getFullWidth() === 0)) { @@ -130808,9 +135101,9 @@ var ts; } if (callExpressionLike) { signature = typeChecker.getResolvedSignature(callExpressionLike); // TODO: GH#18217 - var useConstructSignatures = callExpressionLike.kind === 204 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 105 /* SuperKeyword */); + var useConstructSignatures = callExpressionLike.kind === 205 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 105 /* SuperKeyword */); var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); - if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { + if (signature && !ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { // Get the first signature if there is one -- allSignatures may contain // either the original signature or its target, so check for either signature = allSignatures.length ? allSignatures[0] : undefined; @@ -130872,7 +135165,7 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration - (location.kind === 132 /* ConstructorKeyword */ && location.parent.kind === 166 /* Constructor */)) { // At constructor keyword of constructor declaration + (location.kind === 132 /* ConstructorKeyword */ && location.parent.kind === 167 /* Constructor */)) { // At constructor keyword of constructor declaration // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; // Use function declaration to write the signatures only if the symbol corresponding to this declaration @@ -130880,24 +135173,26 @@ var ts; return declaration === (location.kind === 132 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { - var allSignatures = functionDeclaration_1.kind === 166 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration_1.kind === 167 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217 } else { signature = allSignatures[0]; } - if (functionDeclaration_1.kind === 166 /* Constructor */) { + if (functionDeclaration_1.kind === 167 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 169 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 170 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } - addSignatureDisplayParts(signature, allSignatures); + if (signature) { + addSignatureDisplayParts(signature, allSignatures); + } hasAddedSymbolInfo = true; hasMultipleSignatures = allSignatures.length > 1; } @@ -130905,7 +135200,7 @@ var ts; } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { addAliasPrefixIfNecessary(); - if (ts.getDeclarationOfKind(symbol, 221 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 222 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) // (local class) class @@ -130949,7 +135244,7 @@ var ts; } if (symbolFlags & 1536 /* Module */ && !isThisExpression) { prefixNextMeaning(); - var declaration = ts.getDeclarationOfKind(symbol, 256 /* ModuleDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 257 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 78 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 140 /* NamespaceKeyword */ : 139 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); @@ -130970,7 +135265,7 @@ var ts; } else { // Method/function type parameter - var decl = ts.getDeclarationOfKind(symbol, 159 /* TypeParameter */); + var decl = ts.getDeclarationOfKind(symbol, 160 /* TypeParameter */); if (decl === undefined) return ts.Debug.fail(); var declaration = decl.parent; @@ -130978,16 +135273,16 @@ var ts; if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217 - if (declaration.kind === 170 /* ConstructSignature */) { + if (declaration.kind === 171 /* ConstructSignature */) { displayParts.push(ts.keywordPart(102 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 169 /* CallSignature */ && declaration.name) { + else if (declaration.kind !== 170 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } - else if (declaration.kind === 254 /* TypeAliasDeclaration */) { + else if (declaration.kind === 255 /* TypeAliasDeclaration */) { // Type alias type parameter // For example // type list = T[]; // Both T will go through same code path @@ -131003,8 +135298,8 @@ var ts; if (symbolFlags & 8 /* EnumMember */) { symbolKind = "enum member" /* enumMemberElement */; addPrefixForAnyFunctionOrVar(symbol, "enum member"); - var declaration = symbol.declarations[0]; - if (declaration.kind === 291 /* EnumMember */) { + var declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]; + if ((declaration === null || declaration === void 0 ? void 0 : declaration.kind) === 292 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -131034,31 +135329,33 @@ var ts; } else { documentationFromAlias = resolvedSymbol.getContextualDocumentationComment(resolvedNode, typeChecker); - tagsFromAlias = resolvedSymbol.getJsDocTags(); + tagsFromAlias = resolvedSymbol.getJsDocTags(typeChecker); } } } - switch (symbol.declarations[0].kind) { - case 259 /* NamespaceExportDeclaration */: - displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(140 /* NamespaceKeyword */)); - break; - case 266 /* ExportAssignment */: - displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 62 /* EqualsToken */ : 87 /* DefaultKeyword */)); - break; - case 270 /* ExportSpecifier */: - displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); - break; - default: - displayParts.push(ts.keywordPart(99 /* ImportKeyword */)); + if (symbol.declarations) { + switch (symbol.declarations[0].kind) { + case 260 /* NamespaceExportDeclaration */: + displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(140 /* NamespaceKeyword */)); + break; + case 267 /* ExportAssignment */: + displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 62 /* EqualsToken */ : 87 /* DefaultKeyword */)); + break; + case 271 /* ExportSpecifier */: + displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); + break; + default: + displayParts.push(ts.keywordPart(99 /* ImportKeyword */)); + } } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 260 /* ImportEqualsDeclaration */) { + if (declaration.kind === 261 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); @@ -131145,10 +135442,10 @@ var ts; // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 297 /* SourceFile */; })) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 216 /* BinaryExpression */) { + if (symbol.parent && symbol.declarations && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 298 /* SourceFile */; })) { + for (var _i = 0, _b = symbol.declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (!declaration.parent || declaration.parent.kind !== 217 /* BinaryExpression */) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); @@ -131156,7 +135453,7 @@ var ts; continue; } documentation = rhsSymbol.getDocumentationComment(typeChecker); - tags = rhsSymbol.getJsDocTags(); + tags = rhsSymbol.getJsDocTags(typeChecker); if (documentation.length > 0) { break; } @@ -131164,7 +135461,7 @@ var ts; } } if (tags.length === 0 && !hasMultipleSignatures) { - tags = symbol.getJsDocTags(); + tags = symbol.getJsDocTags(typeChecker); } if (documentation.length === 0 && documentationFromAlias) { documentation = documentationFromAlias; @@ -131266,16 +135563,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 208 /* FunctionExpression */) { + if (declaration.kind === 209 /* FunctionExpression */) { return true; } - if (declaration.kind !== 249 /* VariableDeclaration */ && declaration.kind !== 251 /* FunctionDeclaration */) { + if (declaration.kind !== 250 /* VariableDeclaration */ && declaration.kind !== 252 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { // Reached source file or module block - if (parent.kind === 297 /* SourceFile */ || parent.kind === 257 /* ModuleBlock */) { + if (parent.kind === 298 /* SourceFile */ || parent.kind === 258 /* ModuleBlock */) { return false; } } @@ -131381,7 +135678,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_8 = function (opt) { + var _loop_9 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -131400,7 +135697,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_8(opt); + _loop_9(opt); } return options; } @@ -131576,10 +135873,10 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 280 /* JsxAttribute */: - case 275 /* JsxOpeningElement */: - case 276 /* JsxClosingElement */: - case 274 /* JsxSelfClosingElement */: + case 281 /* JsxAttribute */: + case 276 /* JsxOpeningElement */: + case 277 /* JsxClosingElement */: + case 275 /* JsxSelfClosingElement */: // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. return ts.isKeyword(node.kind) || node.kind === 78 /* Identifier */; } @@ -131587,14 +135884,7 @@ var ts; return false; } function shouldRescanJsxText(node) { - var isJSXText = ts.isJsxText(node); - if (isJSXText) { - var containingElement = ts.findAncestor(node.parent, function (p) { return ts.isJsxElement(p); }); - if (!containingElement) - return false; // should never happen - return !ts.isParenthesizedExpression(containingElement.parent); - } - return false; + return ts.isJsxText(node); } function shouldRescanSlashToken(container) { return container.kind === 13 /* RegularExpressionLiteral */; @@ -131691,7 +135981,7 @@ var ts; return scanner.scanJsxIdentifier(); case 5 /* RescanJsxText */: lastScanAction = 5 /* RescanJsxText */; - return scanner.reScanJsxToken(); + return scanner.reScanJsxToken(/* allowMultilineJsxText */ false); case 6 /* RescanJsxAttributeValue */: lastScanAction = 6 /* RescanJsxAttributeValue */; return scanner.reScanJsxAttributeValue(); @@ -131780,7 +136070,7 @@ var ts; (function (formatting) { function getAllRules() { var allTokens = []; - for (var token = 0 /* FirstToken */; token <= 156 /* LastToken */; token++) { + for (var token = 0 /* FirstToken */; token <= 157 /* LastToken */; token++) { if (token !== 1 /* EndOfFileToken */) { allTokens.push(token); } @@ -131795,9 +136085,9 @@ var ts; var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(__spreadArray(__spreadArray([], allTokens), [3 /* MultiLineCommentTrivia */])); var anyTokenIncludingEOF = tokenRangeFrom(__spreadArray(__spreadArray([], allTokens), [1 /* EndOfFileToken */])); - var keywords = tokenRangeFromRange(80 /* FirstKeyword */, 156 /* LastKeyword */); + var keywords = tokenRangeFromRange(80 /* FirstKeyword */, 157 /* LastKeyword */); var binaryOperators = tokenRangeFromRange(29 /* FirstBinaryOperator */, 77 /* LastBinaryOperator */); - var binaryKeywordOperators = [100 /* InKeyword */, 101 /* InstanceOfKeyword */, 156 /* OfKeyword */, 126 /* AsKeyword */, 137 /* IsKeyword */]; + var binaryKeywordOperators = [100 /* InKeyword */, 101 /* InstanceOfKeyword */, 157 /* OfKeyword */, 126 /* AsKeyword */, 137 /* IsKeyword */]; var unaryPrefixOperators = [45 /* PlusPlusToken */, 46 /* MinusMinusToken */, 54 /* TildeToken */, 53 /* ExclamationToken */]; var unaryPrefixExpressions = [ 8 /* NumericLiteral */, 9 /* BigIntLiteral */, 78 /* Identifier */, 20 /* OpenParenToken */, @@ -132108,51 +136398,51 @@ var ts; return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; } function isForContext(context) { - return context.contextNode.kind === 237 /* ForStatement */; + return context.contextNode.kind === 238 /* ForStatement */; } function isNotForContext(context) { return !isForContext(context); } function isBinaryOpContext(context) { switch (context.contextNode.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return context.contextNode.operatorToken.kind !== 27 /* CommaToken */; - case 217 /* ConditionalExpression */: - case 184 /* ConditionalType */: - case 224 /* AsExpression */: - case 270 /* ExportSpecifier */: - case 265 /* ImportSpecifier */: - case 172 /* TypePredicate */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 218 /* ConditionalExpression */: + case 185 /* ConditionalType */: + case 225 /* AsExpression */: + case 271 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 173 /* TypePredicate */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 198 /* BindingElement */: + case 199 /* BindingElement */: // equals in type X = ... // falls through - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: // equal in import a = module('a'); // falls through - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // equal in let a = 0 // falls through - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: // equal in p = 0 // falls through - case 160 /* Parameter */: - case 291 /* EnumMember */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 161 /* Parameter */: + case 292 /* EnumMember */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return context.currentTokenSpan.kind === 62 /* EqualsToken */ || context.nextTokenSpan.kind === 62 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: // "in" keyword in [P in keyof T]: T[P] // falls through - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return context.currentTokenSpan.kind === 100 /* InKeyword */ || context.nextTokenSpan.kind === 100 /* InKeyword */ || context.currentTokenSpan.kind === 62 /* EqualsToken */ || context.nextTokenSpan.kind === 62 /* EqualsToken */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 239 /* ForOfStatement */: - return context.currentTokenSpan.kind === 156 /* OfKeyword */ || context.nextTokenSpan.kind === 156 /* OfKeyword */; + case 240 /* ForOfStatement */: + return context.currentTokenSpan.kind === 157 /* OfKeyword */ || context.nextTokenSpan.kind === 157 /* OfKeyword */; } return false; } @@ -132164,22 +136454,22 @@ var ts; } function isTypeAnnotationContext(context) { var contextKind = context.contextNode.kind; - return contextKind === 163 /* PropertyDeclaration */ || - contextKind === 162 /* PropertySignature */ || - contextKind === 160 /* Parameter */ || - contextKind === 249 /* VariableDeclaration */ || + return contextKind === 164 /* PropertyDeclaration */ || + contextKind === 163 /* PropertySignature */ || + contextKind === 161 /* Parameter */ || + contextKind === 250 /* VariableDeclaration */ || ts.isFunctionLikeKind(contextKind); } function isConditionalOperatorContext(context) { - return context.contextNode.kind === 217 /* ConditionalExpression */ || - context.contextNode.kind === 184 /* ConditionalType */; + return context.contextNode.kind === 218 /* ConditionalExpression */ || + context.contextNode.kind === 185 /* ConditionalType */; } function isSameLineTokenOrBeforeBlockContext(context) { return context.TokensAreOnSameLine() || isBeforeBlockContext(context); } function isBraceWrappedContext(context) { - return context.contextNode.kind === 196 /* ObjectBindingPattern */ || - context.contextNode.kind === 190 /* MappedType */ || + return context.contextNode.kind === 197 /* ObjectBindingPattern */ || + context.contextNode.kind === 191 /* MappedType */ || isSingleLineBlockContext(context); } // This check is done before an open brace in a control construct, a function, or a typescript block declaration @@ -132205,34 +136495,34 @@ var ts; return true; } switch (node.kind) { - case 230 /* Block */: - case 258 /* CaseBlock */: - case 200 /* ObjectLiteralExpression */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 259 /* CaseBlock */: + case 201 /* ObjectLiteralExpression */: + case 258 /* ModuleBlock */: return true; } return false; } function isFunctionDeclContext(context) { switch (context.contextNode.kind) { - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: // case SyntaxKind.MemberFunctionDeclaration: // falls through - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // case SyntaxKind.MethodSignature: // falls through - case 169 /* CallSignature */: - case 208 /* FunctionExpression */: - case 166 /* Constructor */: - case 209 /* ArrowFunction */: + case 170 /* CallSignature */: + case 209 /* FunctionExpression */: + case 167 /* Constructor */: + case 210 /* ArrowFunction */: // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: // falls through - case 253 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one + case 254 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one return true; } return false; @@ -132241,40 +136531,40 @@ var ts; return !isFunctionDeclContext(context); } function isFunctionDeclarationOrFunctionExpressionContext(context) { - return context.contextNode.kind === 251 /* FunctionDeclaration */ || context.contextNode.kind === 208 /* FunctionExpression */; + return context.contextNode.kind === 252 /* FunctionDeclaration */ || context.contextNode.kind === 209 /* FunctionExpression */; } function isTypeScriptDeclWithBlockContext(context) { return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); } function nodeIsTypeScriptDeclWithBlockContext(node) { switch (node.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 177 /* TypeLiteral */: - case 256 /* ModuleDeclaration */: - case 267 /* ExportDeclaration */: - case 268 /* NamedExports */: - case 261 /* ImportDeclaration */: - case 264 /* NamedImports */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 178 /* TypeLiteral */: + case 257 /* ModuleDeclaration */: + case 268 /* ExportDeclaration */: + case 269 /* NamedExports */: + case 262 /* ImportDeclaration */: + case 265 /* NamedImports */: return true; } return false; } function isAfterCodeBlockContext(context) { switch (context.currentTokenParent.kind) { - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 287 /* CatchClause */: - case 257 /* ModuleBlock */: - case 244 /* SwitchStatement */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 288 /* CatchClause */: + case 258 /* ModuleBlock */: + case 245 /* SwitchStatement */: return true; - case 230 /* Block */: { + case 231 /* Block */: { var blockParent = context.currentTokenParent.parent; // In a codefix scenario, we can't rely on parents being set. So just always return true. - if (!blockParent || blockParent.kind !== 209 /* ArrowFunction */ && blockParent.kind !== 208 /* FunctionExpression */) { + if (!blockParent || blockParent.kind !== 210 /* ArrowFunction */ && blockParent.kind !== 209 /* FunctionExpression */) { return true; } } @@ -132283,32 +136573,32 @@ var ts; } function isControlDeclContext(context) { switch (context.contextNode.kind) { - case 234 /* IfStatement */: - case 244 /* SwitchStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 236 /* WhileStatement */: - case 247 /* TryStatement */: - case 235 /* DoStatement */: - case 243 /* WithStatement */: + case 235 /* IfStatement */: + case 245 /* SwitchStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 237 /* WhileStatement */: + case 248 /* TryStatement */: + case 236 /* DoStatement */: + case 244 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: // falls through - case 287 /* CatchClause */: + case 288 /* CatchClause */: return true; default: return false; } } function isObjectContext(context) { - return context.contextNode.kind === 200 /* ObjectLiteralExpression */; + return context.contextNode.kind === 201 /* ObjectLiteralExpression */; } function isFunctionCallContext(context) { - return context.contextNode.kind === 203 /* CallExpression */; + return context.contextNode.kind === 204 /* CallExpression */; } function isNewContext(context) { - return context.contextNode.kind === 204 /* NewExpression */; + return context.contextNode.kind === 205 /* NewExpression */; } function isFunctionCallOrNewContext(context) { return isFunctionCallContext(context) || isNewContext(context); @@ -132323,10 +136613,10 @@ var ts; return context.nextTokenSpan.kind !== 21 /* CloseParenToken */; } function isArrowFunctionContext(context) { - return context.contextNode.kind === 209 /* ArrowFunction */; + return context.contextNode.kind === 210 /* ArrowFunction */; } function isImportTypeContext(context) { - return context.contextNode.kind === 195 /* ImportType */; + return context.contextNode.kind === 196 /* ImportType */; } function isNonJsxSameLineTokenContext(context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 11 /* JsxText */; @@ -132335,19 +136625,19 @@ var ts; return context.contextNode.kind !== 11 /* JsxText */; } function isNonJsxElementOrFragmentContext(context) { - return context.contextNode.kind !== 273 /* JsxElement */ && context.contextNode.kind !== 277 /* JsxFragment */; + return context.contextNode.kind !== 274 /* JsxElement */ && context.contextNode.kind !== 278 /* JsxFragment */; } function isJsxExpressionContext(context) { - return context.contextNode.kind === 283 /* JsxExpression */ || context.contextNode.kind === 282 /* JsxSpreadAttribute */; + return context.contextNode.kind === 284 /* JsxExpression */ || context.contextNode.kind === 283 /* JsxSpreadAttribute */; } function isNextTokenParentJsxAttribute(context) { - return context.nextTokenParent.kind === 280 /* JsxAttribute */; + return context.nextTokenParent.kind === 281 /* JsxAttribute */; } function isJsxAttributeContext(context) { - return context.contextNode.kind === 280 /* JsxAttribute */; + return context.contextNode.kind === 281 /* JsxAttribute */; } function isJsxSelfClosingElementContext(context) { - return context.contextNode.kind === 274 /* JsxSelfClosingElement */; + return context.contextNode.kind === 275 /* JsxSelfClosingElement */; } function isNotBeforeBlockInFunctionDeclarationContext(context) { return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); @@ -132362,45 +136652,45 @@ var ts; while (ts.isExpressionNode(node)) { node = node.parent; } - return node.kind === 161 /* Decorator */; + return node.kind === 162 /* Decorator */; } function isStartOfVariableDeclarationList(context) { - return context.currentTokenParent.kind === 250 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 251 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; } function isNotFormatOnEnter(context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */; } function isModuleDeclContext(context) { - return context.contextNode.kind === 256 /* ModuleDeclaration */; + return context.contextNode.kind === 257 /* ModuleDeclaration */; } function isObjectTypeContext(context) { - return context.contextNode.kind === 177 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === 178 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; } function isConstructorSignatureContext(context) { - return context.contextNode.kind === 170 /* ConstructSignature */; + return context.contextNode.kind === 171 /* ConstructSignature */; } function isTypeArgumentOrParameterOrAssertion(token, parent) { if (token.kind !== 29 /* LessThanToken */ && token.kind !== 31 /* GreaterThanToken */) { return false; } switch (parent.kind) { - case 173 /* TypeReference */: - case 206 /* TypeAssertionExpression */: - case 254 /* TypeAliasDeclaration */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 223 /* ExpressionWithTypeArguments */: + case 174 /* TypeReference */: + case 207 /* TypeAssertionExpression */: + case 255 /* TypeAliasDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 224 /* ExpressionWithTypeArguments */: return true; default: return false; @@ -132411,28 +136701,28 @@ var ts; isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); } function isTypeAssertionContext(context) { - return context.contextNode.kind === 206 /* TypeAssertionExpression */; + return context.contextNode.kind === 207 /* TypeAssertionExpression */; } function isVoidOpContext(context) { - return context.currentTokenSpan.kind === 113 /* VoidKeyword */ && context.currentTokenParent.kind === 212 /* VoidExpression */; + return context.currentTokenSpan.kind === 113 /* VoidKeyword */ && context.currentTokenParent.kind === 213 /* VoidExpression */; } function isYieldOrYieldStarWithOperand(context) { - return context.contextNode.kind === 219 /* YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 220 /* YieldExpression */ && context.contextNode.expression !== undefined; } function isNonNullAssertionContext(context) { - return context.contextNode.kind === 225 /* NonNullExpression */; + return context.contextNode.kind === 226 /* NonNullExpression */; } function isNotStatementConditionContext(context) { return !isStatementConditionContext(context); } function isStatementConditionContext(context) { switch (context.contextNode.kind) { - case 234 /* IfStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 235 /* IfStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return true; default: return false; @@ -132457,12 +136747,12 @@ var ts; return nextTokenKind === 19 /* CloseBraceToken */ || nextTokenKind === 1 /* EndOfFileToken */; } - if (nextTokenKind === 229 /* SemicolonClassElement */ || + if (nextTokenKind === 230 /* SemicolonClassElement */ || nextTokenKind === 26 /* SemicolonToken */) { return false; } - if (context.contextNode.kind === 253 /* InterfaceDeclaration */ || - context.contextNode.kind === 254 /* TypeAliasDeclaration */) { + if (context.contextNode.kind === 254 /* InterfaceDeclaration */ || + context.contextNode.kind === 255 /* TypeAliasDeclaration */) { // Can’t remove semicolon after `foo`; it would parse as a method declaration: // // interface I { @@ -132476,9 +136766,9 @@ var ts; if (ts.isPropertyDeclaration(context.currentTokenParent)) { return !context.currentTokenParent.initializer; } - return context.currentTokenParent.kind !== 237 /* ForStatement */ - && context.currentTokenParent.kind !== 231 /* EmptyStatement */ - && context.currentTokenParent.kind !== 229 /* SemicolonClassElement */ + return context.currentTokenParent.kind !== 238 /* ForStatement */ + && context.currentTokenParent.kind !== 232 /* EmptyStatement */ + && context.currentTokenParent.kind !== 230 /* SemicolonClassElement */ && nextTokenKind !== 22 /* OpenBracketToken */ && nextTokenKind !== 20 /* OpenParenToken */ && nextTokenKind !== 39 /* PlusToken */ @@ -132486,7 +136776,7 @@ var ts; && nextTokenKind !== 43 /* SlashToken */ && nextTokenKind !== 13 /* RegularExpressionLiteral */ && nextTokenKind !== 27 /* CommaToken */ - && nextTokenKind !== 218 /* TemplateExpression */ + && nextTokenKind !== 219 /* TemplateExpression */ && nextTokenKind !== 15 /* TemplateHead */ && nextTokenKind !== 14 /* NoSubstitutionTemplateLiteral */ && nextTokenKind !== 24 /* DotToken */; @@ -132577,12 +136867,12 @@ var ts; return map; } function getRuleBucketIndex(row, column) { - ts.Debug.assert(row <= 156 /* LastKeyword */ && column <= 156 /* LastKeyword */, "Must compute formatting context from tokens"); + ts.Debug.assert(row <= 157 /* LastKeyword */ && column <= 157 /* LastKeyword */, "Must compute formatting context from tokens"); return (row * mapRowLength) + column; } var maskBitSize = 5; var mask = 31; // MaskBitSize bits - var mapRowLength = 156 /* LastToken */ + 1; + var mapRowLength = 157 /* LastToken */ + 1; var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["StopRulesSpecific"] = 0] = "StopRulesSpecific"; @@ -132770,17 +137060,17 @@ var ts; // i.e. parent is class declaration with the list of members and node is one of members. function isListElement(parent, node) { switch (parent.kind) { - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var body = parent.body; - return !!body && body.kind === 257 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); - case 297 /* SourceFile */: - case 230 /* Block */: - case 257 /* ModuleBlock */: + return !!body && body.kind === 258 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 298 /* SourceFile */: + case 231 /* Block */: + case 258 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -132934,14 +137224,17 @@ var ts; processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); } if (!formattingScanner.isOnToken()) { + var indentation = formatting.SmartIndenter.nodeWillIndentChild(options, enclosingNode, /*child*/ undefined, sourceFile, /*indentByDefault*/ false) + ? initialIndentation + options.indentSize + : initialIndentation; var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); - if (options.trimTrailingWhitespace !== false) { - trimTrailingWhitespacesForRemainingRange(); - } + indentTriviaItems(leadingTrivia, indentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); } } + if (options.trimTrailingWhitespace !== false) { + trimTrailingWhitespacesForRemainingRange(); + } return edits; // local functions /** Tries to compute the indentation for a list element. @@ -132988,10 +137281,9 @@ var ts; // - we need to get the indentation on last line and the delta of parent return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; } - else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; - } - else if (formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) { + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile) || + formatting.SmartIndenter.childIsUnindentedBranchOfConditionalExpression(parent, node, startLine, sourceFile) || + formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) { return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; } else { @@ -133007,19 +137299,19 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 252 /* ClassDeclaration */: return 83 /* ClassKeyword */; - case 253 /* InterfaceDeclaration */: return 117 /* InterfaceKeyword */; - case 251 /* FunctionDeclaration */: return 97 /* FunctionKeyword */; - case 255 /* EnumDeclaration */: return 255 /* EnumDeclaration */; - case 167 /* GetAccessor */: return 134 /* GetKeyword */; - case 168 /* SetAccessor */: return 146 /* SetKeyword */; - case 165 /* MethodDeclaration */: + case 253 /* ClassDeclaration */: return 83 /* ClassKeyword */; + case 254 /* InterfaceDeclaration */: return 117 /* InterfaceKeyword */; + case 252 /* FunctionDeclaration */: return 97 /* FunctionKeyword */; + case 256 /* EnumDeclaration */: return 256 /* EnumDeclaration */; + case 168 /* GetAccessor */: return 134 /* GetKeyword */; + case 169 /* SetAccessor */: return 146 /* SetKeyword */; + case 166 /* MethodDeclaration */: if (node.asteriskToken) { return 41 /* AsteriskToken */; } // falls through - case 163 /* PropertyDeclaration */: - case 160 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 161 /* Parameter */: var name = ts.getNameOfDeclaration(node); if (name) { return name.kind; @@ -133076,15 +137368,16 @@ var ts; case 43 /* SlashToken */: case 31 /* GreaterThanToken */: switch (container.kind) { - case 275 /* JsxOpeningElement */: - case 276 /* JsxClosingElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 277 /* JsxClosingElement */: + case 275 /* JsxSelfClosingElement */: + case 224 /* ExpressionWithTypeArguments */: return false; } break; case 22 /* OpenBracketToken */: case 23 /* CloseBracketToken */: - if (container.kind !== 190 /* MappedType */) { + if (container.kind !== 191 /* MappedType */) { return false; } break; @@ -133129,11 +137422,6 @@ var ts; if (tokenInfo.token.end > node.end) { break; } - if (node.kind === 11 /* JsxText */) { - // Intentation rules for jsx text are handled by `indentMultilineCommentOrJsxText` inside `processChildNode`; just fastforward past it here - formattingScanner.advance(); - continue; - } consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node); } if (!node.parent && formattingScanner.isOnEOF()) { @@ -133192,27 +137480,11 @@ var ts; return inheritedIndentation; } } - var effectiveParentStartLine = child.kind === 161 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 162 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); - if (child.kind === 11 /* JsxText */) { - var range = { pos: child.getStart(), end: child.getEnd() }; - if (range.pos !== range.end) { // don't indent zero-width jsx text - var siblings = parent.getChildren(sourceFile); - var currentIndex = ts.findIndex(siblings, function (arg) { return arg.pos === child.pos; }); - var previousNode = siblings[currentIndex - 1]; - if (previousNode) { - // The jsx text needs no indentation whatsoever if it ends on the same line the previous sibling ends on - if (sourceFile.getLineAndCharacterOfPosition(range.end).line !== sourceFile.getLineAndCharacterOfPosition(previousNode.end).line) { - // The first line is (already) "indented" if the text starts on the same line as the previous sibling element ends on - var firstLineIsIndented = sourceFile.getLineAndCharacterOfPosition(range.pos).line === sourceFile.getLineAndCharacterOfPosition(previousNode.end).line; - indentMultilineCommentOrJsxText(range, childIndentation.indentation, firstLineIsIndented, /*indentFinalLine*/ false, /*jsxStyle*/ true); - } - } - } - } childContextNode = node; - if (isFirstListItem && parent.kind === 199 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + if (isFirstListItem && parent.kind === 200 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -133336,7 +137608,7 @@ var ts; switch (triviaItem.kind) { case 3 /* MultiLineCommentTrivia */: if (triviaInRange) { - indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); + indentMultilineComment(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); } indentNextTokenOrTrivia = false; break; @@ -133453,7 +137725,7 @@ var ts; function indentationIsDifferent(indentationString, startLinePosition) { return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length); } - function indentMultilineCommentOrJsxText(commentRange, indentation, firstLineIsIndented, indentFinalLine, jsxTextStyleIndent) { + function indentMultilineComment(commentRange, indentation, firstLineIsIndented, indentFinalLine) { if (indentFinalLine === void 0) { indentFinalLine = true; } // split comment in lines var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; @@ -133491,13 +137763,6 @@ var ts; var nonWhitespaceCharacterAndColumn = i === 0 ? nonWhitespaceColumnInFirstPart : formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options); - if (jsxTextStyleIndent) { - // skip adding indentation to blank lines - if (ts.isLineBreak(sourceFile.text.charCodeAt(ts.getStartPositionOfLine(startLine, sourceFile)))) - continue; - // reset delta on every line - delta = indentation - nonWhitespaceCharacterAndColumn.column; - } var newIndentation = nonWhitespaceCharacterAndColumn.column + delta; if (newIndentation > 0) { var indentationString = getIndentationString(newIndentation, options); @@ -133652,12 +137917,12 @@ var ts; formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { - case 166 /* Constructor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 209 /* ArrowFunction */: + case 167 /* Constructor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 210 /* ArrowFunction */: if (node.typeParameters === list) { return 29 /* LessThanToken */; } @@ -133665,8 +137930,8 @@ var ts; return 20 /* OpenParenToken */; } break; - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: if (node.typeArguments === list) { return 29 /* LessThanToken */; } @@ -133674,12 +137939,12 @@ var ts; return 20 /* OpenParenToken */; } break; - case 173 /* TypeReference */: + case 174 /* TypeReference */: if (node.typeArguments === list) { return 29 /* LessThanToken */; } break; - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return 18 /* OpenBraceToken */; } return 0 /* Unknown */; @@ -133797,7 +138062,7 @@ var ts; if (options.indentStyle === ts.IndentStyle.Block) { return getBlockIndent(sourceFile, position, options); } - if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 216 /* BinaryExpression */) { + if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 217 /* BinaryExpression */) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { @@ -133880,6 +138145,7 @@ var ts; } SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) { + var _a; var parent = current.parent; // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if // * parent and child nodes start on the same line, or @@ -133895,7 +138161,25 @@ var ts; childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { // check if current node is a list item - if yes, take indentation from it - var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine); + var firstListChild = (_a = getContainingList(current, sourceFile)) === null || _a === void 0 ? void 0 : _a[0]; + // A list indents its children if the children begin on a later line than the list itself: + // + // f1( L0 - List start + // { L1 - First child start: indented, along with all other children + // prop: 0 + // }, + // { + // prop: 1 + // } + // ) + // + // f2({ L0 - List start and first child start: children are not indented. + // prop: 0 Object properties are indented only one level, because the list + // }, { itself contributes nothing. + // prop: 1 L3 - The indentation of the second object literal is best understood by + // }) looking at the relationship between the list and *first* list item. + var listIndentsChild = !!firstListChild && getStartLineAndCharacterForNode(firstListChild, sourceFile).line > containingListOrParentStart.line; + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, listIndentsChild); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } @@ -133951,7 +138235,7 @@ var ts; // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && - (parent.kind === 297 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 298 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -133999,7 +138283,7 @@ var ts; } SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 234 /* IfStatement */ && parent.elseStatement === child) { + if (parent.kind === 235 /* IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 90 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -134008,6 +138292,49 @@ var ts; return false; } SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement; + // A multiline conditional typically increases the indentation of its whenTrue and whenFalse children: + // + // condition + // ? whenTrue + // : whenFalse; + // + // However, that indentation does not apply if the subexpressions themselves span multiple lines, + // applying their own indentation: + // + // (() => { + // return complexCalculationForCondition(); + // })() ? { + // whenTrue: 'multiline object literal' + // } : ( + // whenFalse('multiline parenthesized expression') + // ); + // + // In these cases, we must discard the indentation increase that would otherwise be applied to the + // whenTrue and whenFalse children to avoid double-indenting their contents. To identify this scenario, + // we check for the whenTrue branch beginning on the line that the condition ends, and the whenFalse + // branch beginning on the line that the whenTrue branch ends. + function childIsUnindentedBranchOfConditionalExpression(parent, child, childStartLine, sourceFile) { + if (ts.isConditionalExpression(parent) && (child === parent.whenTrue || child === parent.whenFalse)) { + var conditionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, parent.condition.end).line; + if (child === parent.whenTrue) { + return childStartLine === conditionEndLine; + } + else { + // On the whenFalse side, we have to look at the whenTrue side, because if that one was + // indented, whenFalse must also be indented: + // + // const y = true + // ? 1 : ( L1: whenTrue indented because it's on a new line + // 0 L2: indented two stops, one because whenTrue was indented + // ); and one because of the parentheses spanning multiple lines + var trueStartLine = getStartLineAndCharacterForNode(parent.whenTrue, sourceFile).line; + var trueEndLine = ts.getLineAndCharacterOfPosition(sourceFile, parent.whenTrue.end).line; + return conditionEndLine === trueStartLine && trueEndLine === childStartLine; + } + } + return false; + } + SmartIndenter.childIsUnindentedBranchOfConditionalExpression = childIsUnindentedBranchOfConditionalExpression; function argumentStartsOnSameLineAsPreviousArgument(parent, child, childStartLine, sourceFile) { if (ts.isCallOrNewExpression(parent)) { if (!parent.arguments) @@ -134037,40 +138364,40 @@ var ts; } function getListByRange(start, end, node, sourceFile) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return getList(node.typeArguments); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return getList(node.properties); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return getList(node.elements); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return getList(node.members); - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 166 /* Constructor */: - case 175 /* ConstructorType */: - case 170 /* ConstructSignature */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 167 /* Constructor */: + case 176 /* ConstructorType */: + case 171 /* ConstructSignature */: return getList(node.typeParameters) || getList(node.parameters); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 330 /* JSDocTemplateTag */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 334 /* JSDocTemplateTag */: return getList(node.typeParameters); - case 204 /* NewExpression */: - case 203 /* CallExpression */: + case 205 /* NewExpression */: + case 204 /* CallExpression */: return getList(node.typeArguments) || getList(node.arguments); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return getList(node.declarations); - case 264 /* NamedImports */: - case 268 /* NamedExports */: + case 265 /* NamedImports */: + case 269 /* NamedExports */: return getList(node.elements); - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: return getList(node.elements); } function getList(list) { @@ -134093,7 +138420,7 @@ var ts; return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options); } function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) { - if (node.parent && node.parent.kind === 250 /* VariableDeclarationList */) { + if (node.parent && node.parent.kind === 251 /* VariableDeclarationList */) { // VariableDeclarationList has no wrapping tokens return -1 /* Unknown */; } @@ -134166,94 +138493,94 @@ var ts; function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { var childKind = child ? child.kind : 0 /* Unknown */; switch (parent.kind) { - case 233 /* ExpressionStatement */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 199 /* ArrayLiteralExpression */: - case 230 /* Block */: - case 257 /* ModuleBlock */: - case 200 /* ObjectLiteralExpression */: - case 177 /* TypeLiteral */: - case 190 /* MappedType */: - case 179 /* TupleType */: - case 258 /* CaseBlock */: - case 285 /* DefaultClause */: - case 284 /* CaseClause */: - case 207 /* ParenthesizedExpression */: - case 201 /* PropertyAccessExpression */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 232 /* VariableStatement */: - case 266 /* ExportAssignment */: - case 242 /* ReturnStatement */: - case 217 /* ConditionalExpression */: - case 197 /* ArrayBindingPattern */: - case 196 /* ObjectBindingPattern */: - case 275 /* JsxOpeningElement */: - case 278 /* JsxOpeningFragment */: - case 274 /* JsxSelfClosingElement */: - case 283 /* JsxExpression */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 160 /* Parameter */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 186 /* ParenthesizedType */: - case 205 /* TaggedTemplateExpression */: - case 213 /* AwaitExpression */: - case 268 /* NamedExports */: - case 264 /* NamedImports */: - case 270 /* ExportSpecifier */: - case 265 /* ImportSpecifier */: - case 163 /* PropertyDeclaration */: + case 234 /* ExpressionStatement */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 200 /* ArrayLiteralExpression */: + case 231 /* Block */: + case 258 /* ModuleBlock */: + case 201 /* ObjectLiteralExpression */: + case 178 /* TypeLiteral */: + case 191 /* MappedType */: + case 180 /* TupleType */: + case 259 /* CaseBlock */: + case 286 /* DefaultClause */: + case 285 /* CaseClause */: + case 208 /* ParenthesizedExpression */: + case 202 /* PropertyAccessExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 233 /* VariableStatement */: + case 267 /* ExportAssignment */: + case 243 /* ReturnStatement */: + case 218 /* ConditionalExpression */: + case 198 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 276 /* JsxOpeningElement */: + case 279 /* JsxOpeningFragment */: + case 275 /* JsxSelfClosingElement */: + case 284 /* JsxExpression */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 161 /* Parameter */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 187 /* ParenthesizedType */: + case 206 /* TaggedTemplateExpression */: + case 214 /* AwaitExpression */: + case 269 /* NamedExports */: + case 265 /* NamedImports */: + case 271 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 164 /* PropertyDeclaration */: return true; - case 249 /* VariableDeclaration */: - case 288 /* PropertyAssignment */: - case 216 /* BinaryExpression */: - if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 200 /* ObjectLiteralExpression */) { // TODO: GH#18217 + case 250 /* VariableDeclaration */: + case 289 /* PropertyAssignment */: + case 217 /* BinaryExpression */: + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 201 /* ObjectLiteralExpression */) { // TODO: GH#18217 return rangeIsOnOneLine(sourceFile, child); } - if (parent.kind !== 216 /* BinaryExpression */) { + if (parent.kind !== 217 /* BinaryExpression */) { return true; } break; - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 237 /* ForStatement */: - case 234 /* IfStatement */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - return childKind !== 230 /* Block */; - case 209 /* ArrowFunction */: - if (sourceFile && childKind === 207 /* ParenthesizedExpression */) { + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 238 /* ForStatement */: + case 235 /* IfStatement */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return childKind !== 231 /* Block */; + case 210 /* ArrowFunction */: + if (sourceFile && childKind === 208 /* ParenthesizedExpression */) { return rangeIsOnOneLine(sourceFile, child); } - return childKind !== 230 /* Block */; - case 267 /* ExportDeclaration */: - return childKind !== 268 /* NamedExports */; - case 261 /* ImportDeclaration */: - return childKind !== 262 /* ImportClause */ || - (!!child.namedBindings && child.namedBindings.kind !== 264 /* NamedImports */); - case 273 /* JsxElement */: - return childKind !== 276 /* JsxClosingElement */; - case 277 /* JsxFragment */: - return childKind !== 279 /* JsxClosingFragment */; - case 183 /* IntersectionType */: - case 182 /* UnionType */: - if (childKind === 177 /* TypeLiteral */ || childKind === 179 /* TupleType */) { + return childKind !== 231 /* Block */; + case 268 /* ExportDeclaration */: + return childKind !== 269 /* NamedExports */; + case 262 /* ImportDeclaration */: + return childKind !== 263 /* ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 265 /* NamedImports */); + case 274 /* JsxElement */: + return childKind !== 277 /* JsxClosingElement */; + case 278 /* JsxFragment */: + return childKind !== 280 /* JsxClosingFragment */; + case 184 /* IntersectionType */: + case 183 /* UnionType */: + if (childKind === 178 /* TypeLiteral */ || childKind === 180 /* TupleType */) { return false; } - // falls through + break; } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -134261,11 +138588,11 @@ var ts; SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; function isControlFlowEndingStatement(kind, parent) { switch (kind) { - case 242 /* ReturnStatement */: - case 246 /* ThrowStatement */: - case 240 /* ContinueStatement */: - case 241 /* BreakStatement */: - return parent.kind !== 230 /* Block */; + case 243 /* ReturnStatement */: + case 247 /* ThrowStatement */: + case 241 /* ContinueStatement */: + case 242 /* BreakStatement */: + return parent.kind !== 231 /* Block */; default: return false; } @@ -134373,7 +138700,9 @@ var ts; function getAdjustedRange(sourceFile, startNode, endNode, options) { return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) }; } - function getAdjustedStartPosition(sourceFile, node, options) { + function getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment) { + var _a, _b; + if (hasTrailingComment === void 0) { hasTrailingComment = false; } var leadingTriviaOption = options.leadingTriviaOption; if (leadingTriviaOption === LeadingTriviaOption.Exclude) { return node.getStart(sourceFile); @@ -134404,6 +138733,15 @@ var ts; // when b is deleted - we delete it return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start; } + // if node has a trailing comments, use comment end position as the text has already been included. + if (hasTrailingComment) { + // Check first for leading comments as if the node is the first import, we want to exclude the trivia; + // otherwise we get the trailing comments. + var comment = ((_a = ts.getLeadingCommentRanges(sourceFile.text, fullStart)) === null || _a === void 0 ? void 0 : _a[0]) || ((_b = ts.getTrailingCommentRanges(sourceFile.text, fullStart)) === null || _b === void 0 ? void 0 : _b[0]); + if (comment) { + return ts.skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + } + } // get start position of the line following the line that contains fullstart position // (but only if the fullstart isn't the very beginning of the file) var nextLineStart = fullStart > 0 ? 1 : 0; @@ -134412,6 +138750,35 @@ var ts; adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } + /** Return the end position of a multiline comment of it is on another line; otherwise returns `undefined`; */ + function getEndPositionOfMultilineTrailingComment(sourceFile, node, options) { + var end = node.end; + var trailingTriviaOption = options.trailingTriviaOption; + if (trailingTriviaOption === TrailingTriviaOption.Include) { + // If the trailing comment is a multiline comment that extends to the next lines, + // return the end of the comment and track it for the next nodes to adjust. + var comments = ts.getTrailingCommentRanges(sourceFile.text, end); + if (comments) { + var nodeEndLine = ts.getLineOfLocalPosition(sourceFile, node.end); + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + // Single line can break the loop as trivia will only be this line. + // Comments on subsequest lines are also ignored. + if (comment.kind === 2 /* SingleLineCommentTrivia */ || ts.getLineOfLocalPosition(sourceFile, comment.pos) > nodeEndLine) { + break; + } + // Get the end line of the comment and compare against the end line of the node. + // If the comment end line position and the multiline comment extends to multiple lines, + // then is safe to return the end position. + var commentEndLine = ts.getLineOfLocalPosition(sourceFile, comment.end); + if (commentEndLine > nodeEndLine) { + return ts.skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + } + } + } + } + return undefined; + } function getAdjustedEndPosition(sourceFile, node, options) { var _a; var end = node.end; @@ -134427,6 +138794,10 @@ var ts; } return end; } + var multilineEndPosition = getEndPositionOfMultilineTrailingComment(sourceFile, node, options); + if (multilineEndPosition) { + return multilineEndPosition; + } var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))) ? newEnd @@ -134436,14 +138807,7 @@ var ts; * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ function isSeparator(node, candidate) { - return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 200 /* ObjectLiteralExpression */)); - } - function spaces(count) { - var s = ""; - for (var i = 0; i < count; i++) { - s += " "; - } - return s; + return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 201 /* ObjectLiteralExpression */)); } function isThisTypeAnnotatable(containingFunction) { return ts.isFunctionExpression(containingFunction) || ts.isFunctionDeclaration(containingFunction); @@ -134489,6 +138853,17 @@ var ts; if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options)); }; + ChangeTracker.prototype.deleteNodes = function (sourceFile, nodes, options, hasTrailingComment) { + if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } + // When deleting multiple nodes we need to track if the end position is including multiline trailing comments. + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var pos = getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment); + var end = getAdjustedEndPosition(sourceFile, node, options); + this.deleteRange(sourceFile, { pos: pos, end: end }); + hasTrailingComment = !!getEndPositionOfMultilineTrailingComment(sourceFile, node, options); + } + }; ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); }; @@ -134531,6 +138906,10 @@ var ts; if (options === void 0) { options = useNonAdjustedPositions; } this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; + ChangeTracker.prototype.nodeHasTrailingComment = function (sourceFile, oldNode, configurableEnd) { + if (configurableEnd === void 0) { configurableEnd = useNonAdjustedPositions; } + return !!getEndPositionOfMultilineTrailingComment(sourceFile, oldNode, configurableEnd); + }; ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { var next = ts.findNextToken(node, node.parent, sourceFile); return next && next.kind === 27 /* CommaToken */ ? next : undefined; @@ -134635,7 +139014,7 @@ var ts; } } else { - endNode = (_a = (node.kind === 249 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken)) !== null && _a !== void 0 ? _a : node.name; + endNode = (_a = (node.kind === 250 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken)) !== null && _a !== void 0 ? _a : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); return true; @@ -134677,6 +139056,15 @@ var ts; this.insertNodeBefore(sourceFile, firstStatement, newStatement); } }; + ChangeTracker.prototype.insertNodeAtConstructorStartAfterSuperCall = function (sourceFile, ctr, newStatement) { + var superCallStatement = ts.find(ctr.body.statements, function (stmt) { return ts.isExpressionStatement(stmt) && ts.isSuperCall(stmt.expression); }); + if (!superCallStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, __spreadArray(__spreadArray([], ctr.body.statements), [newStatement])); + } + else { + this.insertNodeAfter(sourceFile, superCallStatement, newStatement); + } + }; ChangeTracker.prototype.insertNodeAtConstructorEnd = function (sourceFile, ctr, newStatement) { var lastStatement = ts.lastOrUndefined(ctr.body.statements); if (!lastStatement || !ctr.body.multiLine) { @@ -134792,18 +139180,18 @@ var ts; }; ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { switch (node.kind) { - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: case 10 /* StringLiteral */: case 78 /* Identifier */: return { prefix: ", " }; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return { suffix: "," + this.newLineCharacter }; case 92 /* ExportKeyword */: return { prefix: " " }; - case 160 /* Parameter */: + case 161 /* Parameter */: return {}; default: ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it @@ -134812,7 +139200,7 @@ var ts; }; ChangeTracker.prototype.insertName = function (sourceFile, node, name) { ts.Debug.assert(!node.name); - if (node.kind === 209 /* ArrowFunction */) { + if (node.kind === 210 /* ArrowFunction */) { var arrow = ts.findChildOfKind(node, 38 /* EqualsGreaterThanToken */, sourceFile); var lparen = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile); if (lparen) { @@ -134826,14 +139214,14 @@ var ts; // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)` this.replaceRange(sourceFile, arrow, ts.factory.createToken(21 /* CloseParenToken */)); } - if (node.body.kind !== 230 /* Block */) { + if (node.body.kind !== 231 /* Block */) { // `() => 0` => `function f() { return 0; }` this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.factory.createToken(18 /* OpenBraceToken */), ts.factory.createToken(104 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); this.insertNodesAt(sourceFile, node.body.end, [ts.factory.createToken(26 /* SemicolonToken */), ts.factory.createToken(19 /* CloseBraceToken */)], { joiner: " " }); } } else { - var pos = ts.findChildOfKind(node, node.kind === 208 /* FunctionExpression */ ? 97 /* FunctionKeyword */ : 83 /* ClassKeyword */, sourceFile).end; + var pos = ts.findChildOfKind(node, node.kind === 209 /* FunctionExpression */ ? 97 /* FunctionKeyword */ : 83 /* ClassKeyword */, sourceFile).end; this.insertNodeAt(sourceFile, pos, ts.factory.createIdentifier(name), { prefix: " " }); } }; @@ -134865,47 +139253,22 @@ var ts; // a, b, c // create change for adding 'e' after 'a' as // - find start of next element after a (it is b) - // - use this start as start and end position in final change - // - build text of change by formatting the text of node + separator + whitespace trivia of b + // - use next element start as start and end position in final change + // - build text of change by formatting the text of node + whitespace trivia of b // in multiline case it will work as // a, // b, // c, // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#') - // a,* - // ***insertedtext# + // a, + // insertedtext# // ###b, // c, - // find line and character of the next element - var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart())); - // find line and character of the token that precedes next element (usually it is separator) - var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end); - var prefix = void 0; - var startPos = void 0; - if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) { - // next element is located on the same line with separator: - // a,$$$$b - // ^ ^ - // | |-next element - // |-separator - // where $$$ is some leading trivia - // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces - // a, x,$$$$b - // ^ ^ ^ - // | | |-next element - // | |-new inserted node padded with spaces - // |-separator - startPos = nextToken.end; - prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character); - } - else { - // next element is located on different line that separator - // let insert position be the beginning of the line that contains next element - startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); - } + var nextNode = containingList[index + 1]; + var startPos = skipWhitespacesAndLineBreaks(sourceFile.text, nextNode.getFullStart()); // write separator and leading trivia of the next element as suffix - var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, startPos); + this.insertNodesAt(sourceFile, startPos, [newNode], { suffix: suffix }); } } else { @@ -134977,7 +139340,7 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.Set(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_9 = function (sourceFile, node) { + var _loop_10 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(sourceFile, node)); @@ -134990,7 +139353,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_9(sourceFile, node); + _loop_10(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -135049,14 +139412,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_10 = function (i) { + var _loop_11 = 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_10(i); + _loop_11(i); } var textChanges = ts.mapDefined(normalized, function (c) { var span = ts.createTextSpanFromRange(c.range); @@ -135170,11 +139533,12 @@ var ts; function createWriter(newLine) { var lastNonTriviaPosition = 0; var writer = ts.createTextWriter(newLine); - var onEmitNode = function (hint, node, printCallback) { + var onBeforeEmitNode = function (node) { if (node) { setPos(node, lastNonTriviaPosition); } - printCallback(hint, node); + }; + var onAfterEmitNode = function (node) { if (node) { setEnd(node, lastNonTriviaPosition); } @@ -135293,7 +139657,8 @@ var ts; lastNonTriviaPosition = 0; } return { - onEmitNode: onEmitNode, + onBeforeEmitNode: onBeforeEmitNode, + onAfterEmitNode: onAfterEmitNode, onBeforeEmitNodeArray: onBeforeEmitNodeArray, onAfterEmitNodeArray: onAfterEmitNodeArray, onBeforeEmitToken: onBeforeEmitToken, @@ -135408,14 +139773,14 @@ var ts; } textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment; function needSemicolonBetween(a, b) { - return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 158 /* ComputedPropertyName */ + return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 159 /* ComputedPropertyName */ || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[` } var deleteDeclaration; (function (deleteDeclaration_1) { function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) { switch (node.kind) { - case 160 /* Parameter */: { + case 161 /* Parameter */: { var oldFunction = node.parent; if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1 && @@ -135430,15 +139795,17 @@ var ts; } break; } - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isAnyImportSyntax); // For first import, leave header comment in place, otherwise only delete JSDoc comments - deleteNode(changes, sourceFile, node, { leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); + deleteNode(changes, sourceFile, node, { + leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine, + }); break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: var pattern = node.parent; - var preserveComma = pattern.kind === 197 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); + var preserveComma = pattern.kind === 198 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); if (preserveComma) { deleteNode(changes, sourceFile, node); } @@ -135446,13 +139813,13 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); break; - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); break; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: var namedImports = node.parent; if (namedImports.elements.length === 1) { deleteImportBinding(changes, sourceFile, namedImports); @@ -135461,7 +139828,7 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: deleteImportBinding(changes, sourceFile, node); break; case 26 /* SemicolonToken */: @@ -135470,12 +139837,16 @@ var ts; case 97 /* FunctionKeyword */: deleteNode(changes, sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.Exclude }); break; - case 252 /* ClassDeclaration */: - case 251 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: deleteNode(changes, sourceFile, node, { leadingTriviaOption: ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; default: - if (ts.isImportClause(node.parent) && node.parent.name === node) { + if (!node.parent) { + // a misbehaving client can reach here with the SourceFile node + deleteNode(changes, sourceFile, node); + } + else if (ts.isImportClause(node.parent) && node.parent.name === node) { deleteDefaultImport(changes, sourceFile, node.parent); } else if (ts.isCallExpression(node.parent) && ts.contains(node.parent.arguments, node)) { @@ -135518,13 +139889,13 @@ var ts; // Delete the entire import declaration // |import * as ns from './file'| // |import { a } from './file'| - var importDecl = ts.getAncestor(node, 261 /* ImportDeclaration */); + var importDecl = ts.getAncestor(node, 262 /* ImportDeclaration */); deleteNode(changes, sourceFile, importDecl); } } function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) { var parent = node.parent; - if (parent.kind === 287 /* CatchClause */) { + if (parent.kind === 288 /* CatchClause */) { // TODO: There's currently no unused diagnostic for this, could be a suggestion changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 20 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 21 /* CloseParenToken */, sourceFile)); return; @@ -135535,14 +139906,14 @@ var ts; } var gp = parent.parent; switch (gp.kind) { - case 239 /* ForOfStatement */: - case 238 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 239 /* ForInStatement */: changes.replaceNode(sourceFile, node, ts.factory.createObjectLiteralExpression()); break; - case 237 /* ForStatement */: + case 238 /* ForStatement */: deleteNode(changes, sourceFile, parent); break; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: deleteNode(changes, sourceFile, gp, { leadingTriviaOption: ts.hasJSDocNodes(gp) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; default: @@ -135598,6 +139969,10 @@ var ts; return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); } codefix.createCodeFixAction = createCodeFixAction; + function createCodeFixActionMaybeFixAll(fixName, changes, description, fixId, fixAllDescription, command) { + return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, fixAllDescription && diagnosticToString(fixAllDescription), command); + } + codefix.createCodeFixActionMaybeFixAll = createCodeFixActionMaybeFixAll; function createCodeFixActionWorker(fixName, description, changes, fixId, fixAllDescription, command) { return { fixName: fixName, description: description, changes: changes, fixId: fixId, fixAllDescription: fixAllDescription, commands: command ? [command] : undefined }; } @@ -135736,7 +140111,10 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code], + errorCodes: [ + ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + ], getCodeActions: function (context) { var sourceFile = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { @@ -135849,6 +140227,7 @@ var ts; ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1.code, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap.code, + ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined.code, ts.Diagnostics.Type_0_is_not_an_array_type.code, ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code, ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators.code, @@ -135947,14 +140326,14 @@ var ts; } var isCompleteFix = identifiers.isCompleteFix; var initializers; - var _loop_11 = function (identifier) { + var _loop_12 = function (identifier) { var symbol = checker.getSymbolAtLocation(identifier); if (!symbol) { return "continue"; } var declaration = ts.tryCast(symbol.valueDeclaration, ts.isVariableDeclaration); var variableName = declaration && ts.tryCast(declaration.name, ts.isIdentifier); - var variableStatement = ts.getAncestor(declaration, 232 /* VariableStatement */); + var variableStatement = ts.getAncestor(declaration, 233 /* VariableStatement */); if (!declaration || !variableStatement || declaration.type || !declaration.initializer || @@ -135980,7 +140359,7 @@ var ts; }; for (var _i = 0, _a = identifiers.identifiers; _i < _a.length; _i++) { var identifier = _a[_i]; - _loop_11(identifier); + _loop_12(identifier); } return initializers && { initializers: initializers, @@ -136032,10 +140411,10 @@ var ts; function isInsideAwaitableBody(node) { return node.kind & 32768 /* AwaitContext */ || !!ts.findAncestor(node, function (ancestor) { return ancestor.parent && ts.isArrowFunction(ancestor.parent) && ancestor.parent.body === ancestor || - ts.isBlock(ancestor) && (ancestor.parent.kind === 251 /* FunctionDeclaration */ || - ancestor.parent.kind === 208 /* FunctionExpression */ || - ancestor.parent.kind === 209 /* ArrowFunction */ || - ancestor.parent.kind === 165 /* MethodDeclaration */); + ts.isBlock(ancestor) && (ancestor.parent.kind === 252 /* FunctionDeclaration */ || + ancestor.parent.kind === 209 /* FunctionExpression */ || + ancestor.parent.kind === 210 /* ArrowFunction */ || + ancestor.parent.kind === 166 /* MethodDeclaration */); }); } function makeChange(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) { @@ -136154,10 +140533,10 @@ var ts; function isPossiblyPartOfDestructuring(node) { switch (node.kind) { case 78 /* Identifier */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return true; default: return false; @@ -136172,7 +140551,7 @@ var ts; function isPossiblyPartOfCommaSeperatedInitializer(node) { switch (node.kind) { case 78 /* Identifier */: - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: case 27 /* CommaToken */: return true; default: @@ -136221,7 +140600,7 @@ var ts; return; } var declaration = token.parent; - if (declaration.kind === 163 /* PropertyDeclaration */ && + if (declaration.kind === 164 /* PropertyDeclaration */ && (!fixedNodes || ts.tryAddToSet(fixedNodes, declaration))) { changeTracker.insertModifierBefore(sourceFile, 133 /* DeclareKeyword */, declaration); } @@ -136358,26 +140737,26 @@ var ts; } function isDeclarationWithType(node) { return ts.isFunctionLikeDeclaration(node) || - node.kind === 249 /* VariableDeclaration */ || - node.kind === 162 /* PropertySignature */ || - node.kind === 163 /* PropertyDeclaration */; + node.kind === 250 /* VariableDeclaration */ || + node.kind === 163 /* PropertySignature */ || + node.kind === 164 /* PropertyDeclaration */; } function transformJSDocType(node) { switch (node.kind) { - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: return ts.factory.createTypeReferenceNode("any", ts.emptyArray); - case 307 /* JSDocOptionalType */: + case 308 /* JSDocOptionalType */: return transformJSDocOptionalType(node); - case 306 /* JSDocNonNullableType */: + case 307 /* JSDocNonNullableType */: return transformJSDocType(node.type); - case 305 /* JSDocNullableType */: + case 306 /* JSDocNullableType */: return transformJSDocNullableType(node); - case 309 /* JSDocVariadicType */: + case 310 /* JSDocVariadicType */: return transformJSDocVariadicType(node); - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: return transformJSDocFunctionType(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return transformJSDocTypeReference(node); default: var visited = ts.visitEachChild(node, transformJSDocType, ts.nullTransformationContext); @@ -136402,7 +140781,7 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 309 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 + var isRest = node.type.kind === 310 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 var name = node.name || (isRest ? "rest" : "arg" + index); var dotdotdot = isRest ? ts.factory.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken; return ts.factory.createParameterDeclaration(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); @@ -136473,7 +140852,7 @@ var ts; }); function doChange(changes, sourceFile, position, checker, preferences, compilerOptions) { var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position)); - if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + if (!ctorSymbol || !ctorSymbol.valueDeclaration || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { // Bad input return undefined; } @@ -136500,7 +140879,7 @@ var ts; // all instance members are stored in the "member" array of symbol if (symbol.members) { symbol.members.forEach(function (member, key) { - if (key === "constructor") { + if (key === "constructor" && member.valueDeclaration) { // fn.prototype.constructor = fn changes.delete(sourceFile, member.valueDeclaration.parent); return; @@ -136514,7 +140893,7 @@ var ts; // all static members are stored in the "exports" array of symbol if (symbol.exports) { symbol.exports.forEach(function (member) { - if (member.name === "prototype") { + if (member.name === "prototype" && member.declarations) { var firstDeclaration = member.declarations[0]; // only one "x.prototype = { ... }" will pass if (member.declarations.length === 1 && @@ -136576,7 +140955,7 @@ var ts; return members; } // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end - var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 233 /* ExpressionStatement */ + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 234 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); if (!assignmentExpr) { @@ -136637,7 +141016,7 @@ var ts; var arrowFunctionBody = arrowFunction.body; var bodyBlock; // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 230 /* Block */) { + if (arrowFunctionBody.kind === 231 /* Block */) { bodyBlock = arrowFunctionBody; } // case 2: () => [1,2,3] @@ -136739,7 +141118,7 @@ var ts; functionToConvert = tokenAtPosition.parent.initializer; } else { - functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.canBeConvertedToAsync); } if (!functionToConvert) { return; @@ -136748,7 +141127,10 @@ var ts; var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap); - var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray; + if (!ts.returnsPromise(functionToConvertRenamed, checker)) { + return; + } + var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : ts.emptyArray; var transformer = { checker: checker, synthNamesMap: synthNamesMap, setOfExpressionsToReturn: setOfExpressionsToReturn, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; @@ -136758,7 +141140,7 @@ var ts; functionToConvert.getStart(sourceFile); var options = functionToConvert.modifiers ? { prefix: " " } : { suffix: " " }; changes.insertModifierAt(sourceFile, pos, 129 /* AsyncKeyword */, options); - var _loop_12 = function (returnStatement) { + var _loop_13 = function (returnStatement) { ts.forEachChild(returnStatement, function visit(node) { if (ts.isCallExpression(node)) { var newNodes = transformExpression(node, transformer); @@ -136771,13 +141153,13 @@ var ts; }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var returnStatement = returnStatements_1[_i]; - _loop_12(returnStatement); + _loop_13(returnStatement); } } - function getReturnStatementsWithPromiseHandlers(body) { + function getReturnStatementsWithPromiseHandlers(body, checker) { var res = []; ts.forEachReturnStatement(body, function (ret) { - if (ts.isReturnStatementWithFixablePromiseHandler(ret)) + if (ts.isReturnStatementWithFixablePromiseHandler(ret, checker)) res.push(ret); }); return res; @@ -136848,7 +141230,10 @@ var ts; // so we push an entry for 'response'. if (lastCallSignature && !ts.isParameter(node.parent) && !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.factory.createUniqueName("result", 16 /* Optimistic */); + var ident = (firstParameter === null || firstParameter === void 0 ? void 0 : firstParameter.valueDeclaration) + && ts.isParameter(firstParameter.valueDeclaration) + && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) + || ts.factory.createUniqueName("result", 16 /* Optimistic */); var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); collidingSymbolMap.add(ident.text, symbol); @@ -137026,6 +141411,7 @@ var ts; case 103 /* NullKeyword */: // do not produce a transformed statement for a null argument break; + case 202 /* PropertyAccessExpression */: case 78 /* Identifier */: // identifier includes undefined if (!argName) { // undefined was argument passed to promise handler @@ -137047,8 +141433,8 @@ var ts; prevArgName.types.push(returnType); } return varDeclOrAssignment; - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: { + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: { var funcBody = func.body; var returnType_1 = (_c = getLastCallSignature(transformer.checker.getTypeAtLocation(func), transformer.checker)) === null || _c === void 0 ? void 0 : _c.getReturnType(); // Arrow functions with block bodies { } will enter this control flow @@ -137059,7 +141445,7 @@ var ts; var statement = _f[_i]; if (ts.isReturnStatement(statement)) { seenReturnStatement = true; - if (ts.isReturnStatementWithFixablePromiseHandler(statement)) { + if (ts.isReturnStatementWithFixablePromiseHandler(statement, transformer.checker)) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } else { @@ -137076,7 +141462,7 @@ var ts; : removeReturns(refactoredStmts, prevArgName, transformer, seenReturnStatement); } else { - var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.factory.createReturnStatement(funcBody)] : ts.emptyArray; + var innerRetStmts = ts.isFixablePromiseHandler(funcBody, transformer.checker) ? [ts.factory.createReturnStatement(funcBody)] : ts.emptyArray; var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { return innerCbBody; @@ -137169,6 +141555,9 @@ var ts; else if (ts.isIdentifier(funcNode)) { name = getMapEntryOrDefault(funcNode); } + else if (ts.isPropertyAccessExpression(funcNode) && ts.isIdentifier(funcNode.name)) { + name = getMapEntryOrDefault(funcNode.name); + } // return undefined argName when arg is null or undefined // eslint-disable-next-line no-in-operator if (!name || "identifier" in name && name.identifier.text === "undefined") { @@ -137264,10 +141653,10 @@ var ts; } var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { changes.replaceNode(importingFile, importNode, ts.factory.createPropertyAccessExpression(ts.getSynthesizedDeepClone(importNode), "default")); } @@ -137334,20 +141723,20 @@ var ts; } function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, useSitesToUnqualify, quotePreference) { switch (statement.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); return false; - case 233 /* ExpressionStatement */: { + case 234 /* ExpressionStatement */: { var expression = statement.expression; switch (expression.kind) { - case 203 /* CallExpression */: { + case 204 /* CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); } return false; } - case 216 /* BinaryExpression */: { + case 217 /* BinaryExpression */: { var operatorToken = expression.operatorToken; return operatorToken.kind === 62 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports, useSitesToUnqualify); } @@ -137396,8 +141785,8 @@ var ts; /** Converts `const name = require("moduleSpecifier").propertyName` */ function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { switch (name.kind) { - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: { + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` var tmp = makeUniqueName(propertyName, identifiers); return convertedImports([ @@ -137448,16 +141837,16 @@ var ts; function tryChangeModuleExportsObject(object, useSitesToUnqualify) { var statements = ts.mapAllOrFail(object.properties, function (prop) { switch (prop.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. // falls through - case 289 /* ShorthandPropertyAssignment */: - case 290 /* SpreadAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 291 /* SpreadAssignment */: return undefined; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer, useSitesToUnqualify); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.factory.createToken(92 /* ExportKeyword */)], prop, useSitesToUnqualify); default: ts.Debug.assertNever(prop, "Convert to ES6 got invalid prop kind " + prop.kind); @@ -137521,7 +141910,7 @@ var ts; function convertExportsDotXEquals_replaceNode(name, exported, useSitesToUnqualify) { var modifiers = [ts.factory.createToken(92 /* ExportKeyword */)]; switch (exported.kind) { - case 208 /* FunctionExpression */: { + case 209 /* FunctionExpression */: { var expressionName = exported.name; if (expressionName && expressionName.text !== name) { // `exports.f = function g() {}` -> `export const f = function g() {}` @@ -137529,10 +141918,10 @@ var ts; } } // falls through - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: // `exports.f = function() {}` --> `export function f() {}` return functionExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: // `exports.C = class {}` --> `export class C {}` return classExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify); default: @@ -137552,7 +141941,7 @@ var ts; : ts.getSynthesizedDeepCloneWithReplacements(nodeOrNodes, /*includeTrivia*/ true, replaceNode); function replaceNode(original) { // We are replacing `mod.SomeExport` wih `SomeExport`, so we only need to look at PropertyAccessExpressions - if (original.kind === 201 /* PropertyAccessExpression */) { + if (original.kind === 202 /* PropertyAccessExpression */) { var replacement = useSitesToUnqualify.get(original); // Remove entry from `useSitesToUnqualify` so the refactor knows it's taken care of by the parent statement we're replacing useSitesToUnqualify.delete(original); @@ -137567,7 +141956,7 @@ var ts; */ function convertSingleImport(name, moduleSpecifier, checker, identifiers, target, quotePreference) { switch (name.kind) { - case 196 /* ObjectBindingPattern */: { + case 197 /* ObjectBindingPattern */: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) ? undefined @@ -137580,7 +141969,7 @@ var ts; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration - case 197 /* ArrayBindingPattern */: { + case 198 /* ArrayBindingPattern */: { /* import x from "x"; const [a, b, c] = x; @@ -137599,7 +141988,9 @@ var ts; } /** * Convert `import x = require("x").` - * Also converts uses like `x.y()` to `y()` and uses a named import. + * Also: + * - Convert `x.default()` to `x()` to handle ES6 default export + * - Converts uses like `x.y()` to `y()` and uses a named import. */ function convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference) { var nameSymbol = checker.getSymbolAtLocation(name); @@ -137616,14 +142007,21 @@ var ts; } var parent = use.parent; if (ts.isPropertyAccessExpression(parent)) { - var expression = parent.expression, propertyName = parent.name.text; - ts.Debug.assert(expression === use, "Didn't expect expression === use"); // Else shouldn't have been in `collectIdentifiers` - var idName = namedBindingsNames.get(propertyName); - if (idName === undefined) { - idName = makeUniqueName(propertyName, identifiers); - namedBindingsNames.set(propertyName, idName); + var propertyName = parent.name.text; + if (propertyName === "default") { + needDefaultImport = true; + var importDefaultName = use.getText(); + (useSitesToUnqualify !== null && useSitesToUnqualify !== void 0 ? useSitesToUnqualify : (useSitesToUnqualify = new ts.Map())).set(parent, ts.factory.createIdentifier(importDefaultName)); + } + else { + ts.Debug.assert(parent.expression === use, "Didn't expect expression === use"); // Else shouldn't have been in `collectIdentifiers` + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + (useSitesToUnqualify !== null && useSitesToUnqualify !== void 0 ? useSitesToUnqualify : (useSitesToUnqualify = new ts.Map())).set(parent, ts.factory.createIdentifier(idName)); } - (useSitesToUnqualify !== null && useSitesToUnqualify !== void 0 ? useSitesToUnqualify : (useSitesToUnqualify = new ts.Map())).set(parent, ts.factory.createIdentifier(idName)); } else { needDefaultImport = true; @@ -137664,11 +142062,11 @@ var ts; function isFreeIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return parent.name !== node; - case 198 /* BindingElement */: + case 199 /* BindingElement */: return parent.propertyName !== node; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: return parent.propertyName !== node; default: return true; @@ -138145,87 +142543,138 @@ var ts; ImportFixKind[ImportFixKind["AddToExisting"] = 2] = "AddToExisting"; ImportFixKind[ImportFixKind["AddNew"] = 3] = "AddNew"; })(ImportFixKind || (ImportFixKind = {})); - var ImportKind; - (function (ImportKind) { - ImportKind[ImportKind["Named"] = 0] = "Named"; - ImportKind[ImportKind["Default"] = 1] = "Default"; - ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; - ImportKind[ImportKind["CommonJS"] = 3] = "CommonJS"; - })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { var compilerOptions = program.getCompilerOptions(); var exportInfos = ts.pathIsBareSpecifier(ts.stripQuotes(moduleSymbol.name)) - ? [getSymbolExportInfoForSymbol(exportedSymbol, moduleSymbol, sourceFile, program, host)] + ? [getSymbolExportInfoForSymbol(exportedSymbol, moduleSymbol, program, host)] : getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, host, program, /*useAutoImportProvider*/ true); var useRequire = shouldUseRequire(sourceFile, program); var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && !ts.isSourceFileJS(sourceFile) && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences)).moduleSpecifier; var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences); - return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; + return { moduleSpecifier: fix.moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences) { ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol"); - // We sort the best codefixes first, so taking `first` is best. - return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences)); + return getBestFix(getImportFixes(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences), sourceFile, host); } function codeFixActionToCodeAction(_a) { var description = _a.description, changes = _a.changes, commands = _a.commands; return { description: description, changes: changes, commands: commands }; } - function getSymbolExportInfoForSymbol(symbol, moduleSymbol, importingFile, program, host) { + function getSymbolExportInfoForSymbol(symbol, moduleSymbol, program, host) { var _a, _b; var compilerOptions = program.getCompilerOptions(); - var mainProgramInfo = getInfoWithChecker(program.getTypeChecker()); + var mainProgramInfo = getInfoWithChecker(program.getTypeChecker(), /*isFromPackageJson*/ false); if (mainProgramInfo) { return mainProgramInfo; } var autoImportProvider = (_b = (_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getTypeChecker(); - return ts.Debug.checkDefined(autoImportProvider && getInfoWithChecker(autoImportProvider), "Could not find symbol in specified module for code actions"); - function getInfoWithChecker(checker) { - var defaultInfo = getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions); + return ts.Debug.checkDefined(autoImportProvider && getInfoWithChecker(autoImportProvider, /*isFromPackageJson*/ true), "Could not find symbol in specified module for code actions"); + function getInfoWithChecker(checker, isFromPackageJson) { + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); if (defaultInfo && ts.skipAlias(defaultInfo.symbol, checker) === symbol) { - return { moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker) }; + return { symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, exportKind: defaultInfo.exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker), isFromPackageJson: isFromPackageJson }; } var named = checker.tryGetMemberInModuleExportsAndProperties(symbol.name, moduleSymbol); if (named && ts.skipAlias(named, checker) === symbol) { - return { moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker) }; + return { symbol: named, moduleSymbol: moduleSymbol, exportKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker), isFromPackageJson: isFromPackageJson }; } } } function getAllReExportingModules(importingFile, exportedSymbol, exportingModuleSymbol, symbolName, host, program, useAutoImportProvider) { var result = []; var compilerOptions = program.getCompilerOptions(); - forEachExternalModuleToImportFrom(program, host, importingFile, /*filterByPackageJson*/ false, useAutoImportProvider, function (moduleSymbol, moduleFile, program) { + var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { + return ts.createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); + }); + forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, function (moduleSymbol, moduleFile, program, isFromPackageJson) { var checker = program.getTypeChecker(); // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(importingFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } - var defaultInfo = getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions); - if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { - result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + result.push({ symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, exportKind: defaultInfo.exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker), isFromPackageJson: isFromPackageJson }); } for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { - result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + result.push({ symbol: exported, moduleSymbol: moduleSymbol, exportKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker), isFromPackageJson: isFromPackageJson }); } } }); return result; + function isImportable(program, moduleFile, isFromPackageJson) { + var _a; + return !moduleFile || ts.isImportableFile(program, importingFile, moduleFile, /*packageJsonFilter*/ undefined, getModuleSpecifierResolutionHost(isFromPackageJson), (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host)); + } } + function getModuleSpecifierForBestExportInfo(exportInfo, importingFile, program, host, preferences) { + return getBestFix(getNewImportFixes(program, importingFile, /*position*/ undefined, /*preferTypeOnlyImport*/ false, /*useRequire*/ false, exportInfo, host, preferences), importingFile, host); + } + codefix.getModuleSpecifierForBestExportInfo = getModuleSpecifierForBestExportInfo; + function getSymbolToExportInfoMap(importingFile, host, program) { + var _a, _b, _c, _d, _e, _f, _g, _h; + var start = ts.timestamp(); + // Pulling the AutoImportProvider project will trigger its updateGraph if pending, + // which will invalidate the export map cache if things change, so pull it before + // checking the cache. + (_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host); + var cache = (_b = host.getExportMapCache) === null || _b === void 0 ? void 0 : _b.call(host); + if (cache) { + var cached = cache.get(importingFile.path, program.getTypeChecker(), (_c = host.getProjectVersion) === null || _c === void 0 ? void 0 : _c.call(host)); + if (cached) { + (_d = host.log) === null || _d === void 0 ? void 0 : _d.call(host, "getSymbolToExportInfoMap: cache hit"); + return cached; + } + else { + (_e = host.log) === null || _e === void 0 ? void 0 : _e.call(host, "getSymbolToExportInfoMap: cache miss or empty; calculating new results"); + } + } + var result = ts.createMultiMap(); + var compilerOptions = program.getCompilerOptions(); + var target = ts.getEmitScriptTarget(compilerOptions); + forEachExternalModuleToImportFrom(program, host, /*useAutoImportProvider*/ true, function (moduleSymbol, _moduleFile, program, isFromPackageJson) { + var checker = program.getTypeChecker(); + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo) { + var name = ts.getNameForExportedSymbol(ts.getLocalSymbolForExportDefault(defaultInfo.symbol) || defaultInfo.symbol, target); + result.add(key(name, defaultInfo.symbol, moduleSymbol, checker), { symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, exportKind: defaultInfo.exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker), isFromPackageJson: isFromPackageJson }); + } + var seenExports = new ts.Map(); + for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { + var exported = _a[_i]; + if (exported !== (defaultInfo === null || defaultInfo === void 0 ? void 0 : defaultInfo.symbol) && ts.addToSeen(seenExports, exported)) { + result.add(key(ts.getNameForExportedSymbol(exported, target), exported, moduleSymbol, checker), { symbol: exported, moduleSymbol: moduleSymbol, exportKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker), isFromPackageJson: isFromPackageJson }); + } + } + }); + if (cache) { + (_f = host.log) === null || _f === void 0 ? void 0 : _f.call(host, "getSymbolToExportInfoMap: caching results"); + cache.set(result, (_g = host.getProjectVersion) === null || _g === void 0 ? void 0 : _g.call(host)); + } + (_h = host.log) === null || _h === void 0 ? void 0 : _h.call(host, "getSymbolToExportInfoMap: done in " + (ts.timestamp() - start) + " ms"); + return result; + function key(name, alias, moduleSymbol, checker) { + var moduleName = ts.stripQuotes(moduleSymbol.name); + var moduleKey = ts.isExternalModuleNameRelative(moduleName) ? "/" : moduleName; + return name + "|" + ts.getSymbolId(ts.skipAlias(alias, checker)) + "|" + moduleKey; + } + } + codefix.getSymbolToExportInfoMap = getSymbolToExportInfoMap; function isTypeOnlySymbol(s, checker) { return !(ts.skipAlias(s, checker).flags & 111551 /* Value */); } function isTypeOnlyPosition(sourceFile, position) { return ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); } - function getFixForImport(exportInfos, symbolName, + function getImportFixes(exportInfos, symbolName, /** undefined only for missing JSX namespace */ position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); - var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); + var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile, program.getCompilerOptions()); }); var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); var addToExisting = tryAddToExistingImport(existingImports, position !== undefined && isTypeOnlyPosition(sourceFile, position)); // Don't bother providing an action to add a new import if we can add to an existing one. @@ -138248,10 +142697,11 @@ var ts; return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration; var namespacePrefix = getNamespaceLikeImportText(declaration); - if (namespacePrefix) { + var moduleSpecifier = ts.tryGetModuleSpecifierFromDeclaration(declaration); + if (namespacePrefix && moduleSpecifier) { var moduleSymbol = getTargetModuleFromNamespaceLikeImport(declaration, checker); if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { - return { kind: 0 /* UseNamespace */, namespacePrefix: namespacePrefix, position: position }; + return { kind: 0 /* UseNamespace */, namespacePrefix: namespacePrefix, position: position, moduleSpecifier: moduleSpecifier }; } } }); @@ -138259,11 +142709,11 @@ var ts; function getTargetModuleFromNamespaceLikeImport(declaration, checker) { var _a; switch (declaration.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return checker.resolveExternalModuleName(declaration.initializer.arguments[0]); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return checker.getAliasedSymbol(declaration.symbol); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: var namespaceImport = ts.tryCast((_a = declaration.importClause) === null || _a === void 0 ? void 0 : _a.namedBindings, ts.isNamespaceImport); return namespaceImport && checker.getAliasedSymbol(namespaceImport.symbol); default: @@ -138273,11 +142723,11 @@ var ts; function getNamespaceLikeImportText(declaration) { var _a, _b, _c; switch (declaration.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return (_a = ts.tryCast(declaration.name, ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return declaration.name.text; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return (_c = ts.tryCast((_b = declaration.importClause) === null || _b === void 0 ? void 0 : _b.namedBindings, ts.isNamespaceImport)) === null || _c === void 0 ? void 0 : _c.name.text; default: return ts.Debug.assertNever(declaration); @@ -138286,31 +142736,38 @@ var ts; function tryAddToExistingImport(existingImports, canUseTypeOnlyImport) { return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind === 260 /* ImportEqualsDeclaration */) + if (declaration.kind === 261 /* ImportEqualsDeclaration */) return undefined; - if (declaration.kind === 249 /* VariableDeclaration */) { - return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 196 /* ObjectBindingPattern */ + if (declaration.kind === 250 /* VariableDeclaration */) { + return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 197 /* ObjectBindingPattern */ ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: declaration.name, importKind: importKind, moduleSpecifier: declaration.initializer.arguments[0].text, canUseTypeOnlyImport: false } : undefined; } var importClause = declaration.importClause; - if (!importClause) + if (!importClause || !ts.isStringLiteralLike(declaration.moduleSpecifier)) return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; - return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 264 /* NamedImports */) - ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.getText(), canUseTypeOnlyImport: canUseTypeOnlyImport } + // A type-only import may not have both a default and named imports, so the only way a name can + // be added to an existing type-only import is adding a named import to existing named bindings. + if (importClause.isTypeOnly && !(importKind === 0 /* Named */ && namedBindings)) + return undefined; + return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 265 /* NamedImports */) + ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.text, canUseTypeOnlyImport: canUseTypeOnlyImport } : undefined; }); } - function getExistingImportDeclarations(_a, checker, sourceFile) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + function getExistingImportDeclarations(_a, checker, importingFile, compilerOptions) { + var moduleSymbol = _a.moduleSymbol, exportKind = _a.exportKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + if (exportedSymbolIsTypeOnly && ts.isSourceFileJS(importingFile)) + return ts.emptyArray; + var importKind = getImportKind(importingFile, exportKind, compilerOptions); + return ts.mapDefined(importingFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); - if (ts.isRequireVariableDeclaration(i.parent, /*requireStringLiteralLikeArgument*/ true)) { + if (ts.isRequireVariableDeclaration(i.parent)) { return checker.resolveExternalModuleName(moduleSpecifier) === moduleSymbol ? { declaration: i.parent, importKind: importKind } : undefined; } - if (i.kind === 261 /* ImportDeclaration */ || i.kind === 260 /* ImportEqualsDeclaration */) { + if (i.kind === 262 /* ImportDeclaration */ || i.kind === 261 /* ImportEqualsDeclaration */) { return checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; } }); @@ -138343,45 +142800,29 @@ var ts; // 5. Literally nothing to go on return true; } - function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) { + function getNewImportFixes(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) { var isJs = ts.isSourceFileJS(sourceFile); var compilerOptions = program.getCompilerOptions(); - var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; - var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getTypeChecker(), compilerOptions, sourceFile, ts.createModuleSpecifierResolutionHost(program, host), preferences) + var moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); + return ts.flatMap(moduleSymbols, function (exportInfo) { + return ts.moduleSpecifiers.getModuleSpecifiers(exportInfo.moduleSymbol, program.getTypeChecker(), compilerOptions, sourceFile, moduleSpecifierResolutionHost, preferences) .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.checkDefined(position, "position should be defined") } - : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, useRequire: useRequire, typeOnly: preferTypeOnlyImport }; + return exportInfo.exportedSymbolIsTypeOnly && isJs && position !== undefined + ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: position, exportInfo: exportInfo } + : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: getImportKind(sourceFile, exportInfo.exportKind, compilerOptions), useRequire: useRequire, typeOnly: preferTypeOnlyImport, exportInfo: exportInfo }; }); }); - // Sort by presence in package.json, then shortest paths first - return ts.sort(choicesForEachExportingModule, function (a, b) { - var allowsImportingA = allowsImportingSpecifier(a.moduleSpecifier); - var allowsImportingB = allowsImportingSpecifier(b.moduleSpecifier); - if (allowsImportingA && !allowsImportingB) { - return -1; - } - if (allowsImportingB && !allowsImportingA) { - return 1; - } - return a.moduleSpecifier.length - b.moduleSpecifier.length; - }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport, useRequire); }); - return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences); + return existingDeclaration ? [existingDeclaration] : getNewImportFixes(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences); } function newImportInfoFromExistingSpecifier(_a, preferTypeOnlyImport, useRequire) { var declaration = _a.declaration, importKind = _a.importKind; - var moduleSpecifier = declaration.kind === 261 /* ImportDeclaration */ ? declaration.moduleSpecifier : - declaration.kind === 249 /* VariableDeclaration */ ? declaration.initializer.arguments[0] : - declaration.moduleReference.kind === 272 /* ExternalModuleReference */ ? declaration.moduleReference.expression : - undefined; - return moduleSpecifier && ts.isStringLiteral(moduleSpecifier) - ? { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier.text, importKind: importKind, typeOnly: preferTypeOnlyImport, useRequire: useRequire } + var moduleSpecifier = ts.tryGetModuleSpecifierFromDeclaration(declaration); + return moduleSpecifier + ? { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, typeOnly: preferTypeOnlyImport, useRequire: useRequire } : undefined; } function getFixesInfo(context, errorCode, pos, useAutoImportProvider) { @@ -138389,7 +142830,28 @@ var ts; var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ? getFixesInfoForUMDImport(context, symbolToken) : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider) : undefined; - return info && __assign(__assign({}, info), { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) }); + return info && __assign(__assign({}, info), { fixes: sortFixes(info.fixes, context.sourceFile, context.host) }); + } + function sortFixes(fixes, sourceFile, host) { + var allowsImportingSpecifier = ts.createPackageJsonImportFilter(sourceFile, host).allowsImportingSpecifier; + return ts.sort(fixes, function (a, b) { return ts.compareValues(a.kind, b.kind) || compareModuleSpecifiers(a, b, allowsImportingSpecifier); }); + } + function getBestFix(fixes, sourceFile, host) { + // These will always be placed first if available, and are better than other kinds + if (fixes[0].kind === 0 /* UseNamespace */ || fixes[0].kind === 2 /* AddToExisting */) { + return fixes[0]; + } + var allowsImportingSpecifier = ts.createPackageJsonImportFilter(sourceFile, host).allowsImportingSpecifier; + return fixes.reduce(function (best, fix) { + return compareModuleSpecifiers(fix, best, allowsImportingSpecifier) === -1 /* LessThan */ ? fix : best; + }); + } + function compareModuleSpecifiers(a, b, allowsImportingSpecifier) { + if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) { + return ts.compareBooleans(allowsImportingSpecifier(a.moduleSpecifier), allowsImportingSpecifier(b.moduleSpecifier)) + || ts.compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); + } + return 0 /* EqualTo */; } function getFixesInfoForUMDImport(_a, token) { var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences; @@ -138399,9 +142861,9 @@ var ts; return undefined; var symbol = checker.getAliasedSymbol(umdSymbol); var symbolName = umdSymbol.name; - var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(sourceFile, program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; + var exportInfos = [{ symbol: umdSymbol, moduleSymbol: symbol, exportKind: 3 /* UMD */, exportedSymbolIsTypeOnly: false, isFromPackageJson: false }]; var useRequire = shouldUseRequire(sourceFile, program); - var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, useRequire, program, sourceFile, host, preferences); + var fixes = getImportFixes(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, useRequire, program, sourceFile, host, preferences); return { fixes: fixes, symbolName: symbolName }; } function getUmdSymbol(token, checker) { @@ -138415,6 +142877,16 @@ var ts; ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 111551 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } + function getImportKind(importingFile, exportKind, compilerOptions) { + switch (exportKind) { + case 0 /* Named */: return 0 /* Named */; + case 1 /* Default */: return 1 /* Default */; + case 2 /* ExportEquals */: return getExportEqualsImportKind(importingFile, compilerOptions); + case 3 /* UMD */: return getUmdImportKind(importingFile, compilerOptions); + default: return ts.Debug.assertNever(exportKind); + } + } + codefix.getImportKind = getImportKind; function getUmdImportKind(importingFile, compilerOptions) { // Import a synthetic `default` if enabled. if (ts.getAllowSyntheticDefaultImports(compilerOptions)) { @@ -138444,22 +142916,22 @@ var ts; function getFixesInfoForNonUMDImport(_a, symbolToken, useAutoImportProvider) { var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences; var checker = program.getTypeChecker(); - var symbolName = getSymbolName(sourceFile, checker, symbolToken); + var compilerOptions = program.getCompilerOptions(); + var symbolName = getSymbolName(sourceFile, checker, symbolToken, compilerOptions); // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default" /* Default */, "'default' isn't a legal identifier and couldn't occur here"); - var compilerOptions = program.getCompilerOptions(); var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(symbolToken); var useRequire = shouldUseRequire(sourceFile, program); var exportInfos = getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host); var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfos.entries(), function (_a) { var _ = _a[0], exportInfos = _a[1]; - return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences); + return getImportFixes(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences); })); return { fixes: fixes, symbolName: symbolName }; } - function getSymbolName(sourceFile, checker, symbolToken) { + function getSymbolName(sourceFile, checker, symbolToken, compilerOptions) { var parent = symbolToken.parent; - if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken) { + if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken && compilerOptions.jsx !== 4 /* ReactJSX */ && compilerOptions.jsx !== 5 /* ReactJSXDev */) { var jsxNamespace = checker.getJsxNamespace(sourceFile); if (ts.isIntrinsicJsxName(symbolToken.text) || !checker.resolveName(jsxNamespace, parent, 111551 /* Value */, /*excludeGlobals*/ true)) { return jsxNamespace; @@ -138468,43 +142940,55 @@ var ts; return symbolToken.text; } // Returns a map from an exported symbol's ID to a list of every way it's (re-)exported. - function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, program, useAutoImportProvider, host) { + function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, fromFile, program, useAutoImportProvider, host) { + var _a; // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); - function addSymbol(moduleSymbol, exportedSymbol, importKind, checker) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); + var packageJsonFilter = ts.createPackageJsonImportFilter(fromFile, host); + var moduleSpecifierCache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); + var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { + return ts.createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); + }); + function addSymbol(moduleSymbol, toFile, exportedSymbol, exportKind, program, isFromPackageJson) { + var moduleSpecifierResolutionHost = getModuleSpecifierResolutionHost(isFromPackageJson); + if (toFile && ts.isImportableFile(program, fromFile, toFile, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) || + !toFile && packageJsonFilter.allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost)) { + var checker = program.getTypeChecker(); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { symbol: exportedSymbol, moduleSymbol: moduleSymbol, exportKind: exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker), isFromPackageJson: isFromPackageJson }); + } } - forEachExternalModuleToImportFrom(program, host, sourceFile, /*filterByPackageJson*/ true, useAutoImportProvider, function (moduleSymbol, _, program) { + forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, function (moduleSymbol, sourceFile, program, isFromPackageJson) { var checker = program.getTypeChecker(); cancellationToken.throwIfCancellationRequested(); var compilerOptions = program.getCompilerOptions(); - var defaultInfo = getDefaultLikeExportInfo(sourceFile, moduleSymbol, checker, compilerOptions); + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind, checker); + addSymbol(moduleSymbol, sourceFile, defaultInfo.symbol, defaultInfo.exportKind, program, isFromPackageJson); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */, checker); + addSymbol(moduleSymbol, sourceFile, exportSymbolWithIdenticalName, 0 /* Named */, program, isFromPackageJson); } }); return originalSymbolToExportInfos; } - function getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions) { - var exported = getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions); + 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); + var symbol = exported.symbol, exportKind = exported.exportKind; + var info = getDefaultExportInfoWorker(symbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, exportKind: exportKind }, info); } - function getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions) { + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) + return { symbol: exportEquals, exportKind: 2 /* ExportEquals */ }; 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: getExportEqualsImportKind(importingFile, compilerOptions) }; + return { symbol: defaultExport, exportKind: 1 /* Default */ }; } function getExportEqualsImportKind(importingFile, compilerOptions) { var allowSyntheticDefaults = ts.getAllowSyntheticDefaultImports(compilerOptions); @@ -138523,7 +143007,8 @@ var ts; // on how to handle it. for (var _i = 0, _a = importingFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - if (ts.isImportEqualsDeclaration(statement)) { + // `import foo` parses as an ImportEqualsDeclaration even though it could be an ImportDeclaration + if (ts.isImportEqualsDeclaration(statement) && !ts.nodeIsMissing(statement.moduleReference)) { return 3 /* CommonJS */; } } @@ -138531,7 +143016,7 @@ var ts; // allowSyntheticDefaultImports/esModuleInterop is enabled. return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */; } - function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { + function getDefaultExportInfoWorker(defaultExport, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -138545,21 +143030,20 @@ var ts; // but we can still offer completions for it. // - `aliased.parent` will be undefined if the module is exporting `globalThis.something`, // or another expression that resolves to a global. - return getDefaultExportInfoWorker(aliased, aliased.parent, checker, compilerOptions); + return getDefaultExportInfoWorker(aliased, checker, compilerOptions); } } if (defaultExport.escapedName !== "default" /* Default */ && defaultExport.escapedName !== "export=" /* ExportEquals */) { return { symbolForMeaning: defaultExport, name: defaultExport.getName() }; } - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; + return { symbolForMeaning: defaultExport, name: ts.getNameForExportedSymbol(defaultExport, compilerOptions.target) }; } function getNameForExportDefault(symbol) { return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { + var _a; if (ts.isExportAssignment(declaration)) { - if (ts.isIdentifier(declaration.expression)) { - return declaration.expression.text; - } + return (_a = ts.tryCast(ts.skipOuterExpressions(declaration.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text; } else if (ts.isExportSpecifier(declaration)) { ts.Debug.assert(declaration.name.text === "default" /* Default */, "Expected the specifier to be a default export"); @@ -138602,7 +143086,7 @@ var ts; } } function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, canUseTypeOnlyImport) { - if (clause.kind === 196 /* ObjectBindingPattern */) { + if (clause.kind === 197 /* ObjectBindingPattern */) { if (defaultImport) { addElementToBindingPattern(clause, defaultImport, "default"); } @@ -138729,48 +143213,23 @@ var ts; var declarations = _a.declarations; return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); } - function forEachExternalModuleToImportFrom(program, host, from, filterByPackageJson, useAutoImportProvider, cb) { + function forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, cb) { var _a, _b; - forEachExternalModuleToImportFromInProgram(program, host, from, filterByPackageJson, function (module, file) { return cb(module, file, program, /*isFromPackageJson*/ false); }); + forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), function (module, file) { return cb(module, file, program, /*isFromPackageJson*/ false); }); var autoImportProvider = useAutoImportProvider && ((_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host)); if (autoImportProvider) { var start = ts.timestamp(); - forEachExternalModuleToImportFromInProgram(autoImportProvider, host, from, filterByPackageJson, function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); + forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); (_b = host.log) === null || _b === void 0 ? void 0 : _b.call(host, "forEachExternalModuleToImportFrom autoImportProvider: " + (ts.timestamp() - start)); } } codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; - function forEachExternalModuleToImportFromInProgram(program, host, from, filterByPackageJson, cb) { - var _a; - var filteredCount = 0; - var moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); - var packageJson = filterByPackageJson && createAutoImportFilter(from, program, host, moduleSpecifierResolutionHost); - forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), function (module, sourceFile) { - if (sourceFile === undefined) { - if (!packageJson || packageJson.allowsImportingAmbientModule(module)) { - cb(module, sourceFile); - } - else if (packageJson) { - filteredCount++; - } - } - else if (sourceFile && - sourceFile !== from && - isImportableFile(program, from, sourceFile, moduleSpecifierResolutionHost)) { - if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile)) { - cb(module, sourceFile); - } - else if (packageJson) { - filteredCount++; - } - } - }); - (_a = host.log) === null || _a === void 0 ? void 0 : _a.call(host, "forEachExternalModuleToImportFrom: filtered out " + filteredCount + " modules by package.json contents"); - } function forEachExternalModule(checker, allSourceFiles, cb) { for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { var ambient = _a[_i]; - cb(ambient, /*sourceFile*/ undefined); + if (!ts.stringContains(ambient.name, "*")) { + cb(ambient, /*sourceFile*/ undefined); + } } for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { var sourceFile = allSourceFiles_1[_b]; @@ -138779,31 +143238,6 @@ var ts; } } } - function isImportableFile(program, from, to, moduleSpecifierResolutionHost) { - var _a; - var getCanonicalFileName = ts.hostGetCanonicalFileName(moduleSpecifierResolutionHost); - var globalTypingsCache = (_a = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation) === null || _a === void 0 ? void 0 : _a.call(moduleSpecifierResolutionHost); - return !!ts.moduleSpecifiers.forEachFileNameOfModule(from.fileName, to.fileName, moduleSpecifierResolutionHost, - /*preferSymlinks*/ false, function (toPath) { - var toFile = program.getSourceFile(toPath); - // Determine to import using toPath only if toPath is what we were looking at - // or there doesnt exist the file in the program by the symlink - return (toFile === to || !toFile) && - isImportablePath(from.fileName, toPath, getCanonicalFileName, globalTypingsCache); - }); - } - /** - * Don't include something from a `node_modules` that isn't actually reachable by a global import. - * A relative import to node_modules is usually a bad idea. - */ - function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) { - // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. - var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); - var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules)); - return toNodeModulesParent === undefined - || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) - || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); - } function moduleSymbolToValidIdentifier(moduleSymbol, target) { return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); } @@ -138835,99 +143269,122 @@ var ts; return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; } codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; - function createAutoImportFilter(fromFile, program, host, moduleSpecifierResolutionHost) { - if (moduleSpecifierResolutionHost === void 0) { moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); } - var packageJsons = ((host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName)) || ts.getPackageJsonsVisibleToFile(fromFile.fileName, host)).filter(function (p) { return p.parseable; }); - var usesNodeCoreModules; - return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier, moduleSpecifierResolutionHost: moduleSpecifierResolutionHost }; - function moduleSpecifierIsCoveredByPackageJson(specifier) { - var packageName = getNodeModuleRootSpecifier(specifier); - for (var _i = 0, packageJsons_1 = packageJsons; _i < packageJsons_1.length; _i++) { - var packageJson = packageJsons_1[_i]; - if (packageJson.has(packageName) || packageJson.has(ts.getTypesPackageName(packageName))) { - return true; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var _a; + var fixName = "fixOverrideModifier"; + var fixAddOverrideId = "fixAddOverrideModifier"; + var fixRemoveOverrideId = "fixRemoveOverrideModifier"; + var errorCodes = [ + ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code, + ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code, + ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code, + ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code, + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code + ]; + var errorCodeFixIdMap = (_a = {}, + _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code] = [ + ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Add_all_missing_override_modifiers, + ], + _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code] = [ + ts.Diagnostics.Remove_override_modifier, fixRemoveOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers + ], + _a[ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code] = [ + ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Add_all_missing_override_modifiers, + ], + _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code] = [ + ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers + ], + _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code] = [ + ts.Diagnostics.Remove_override_modifier, fixRemoveOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers + ], + _a); + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var errorCode = context.errorCode, span = context.span, sourceFile = context.sourceFile; + var info = errorCodeFixIdMap[errorCode]; + if (!info) + return ts.emptyArray; + var descriptions = info[0], fixId = info[1], fixAllDescriptions = info[2]; + if (ts.isSourceFileJS(sourceFile)) + return ts.emptyArray; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { return dispatchChanges(changes, context, errorCode, span.start); }); + return [ + codefix.createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId, fixAllDescriptions) + ]; + }, + fixIds: [fixName, fixAddOverrideId, fixRemoveOverrideId], + getAllCodeActions: function (context) { + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var code = diag.code, start = diag.start, file = diag.file; + var info = errorCodeFixIdMap[code]; + if (!info || info[1] !== context.fixId || ts.isSourceFileJS(file)) { + return; } - } - return false; - } - function allowsImportingAmbientModule(moduleSymbol) { - if (!packageJsons.length) { - return true; - } - var declaringSourceFile = moduleSymbol.valueDeclaration.getSourceFile(); - var declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName); - if (typeof declaringNodeModuleName === "undefined") { - return true; - } - var declaredModuleSpecifier = ts.stripQuotes(moduleSymbol.getName()); - if (isAllowedCoreNodeModulesImport(declaredModuleSpecifier)) { - return true; - } - return moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName) - || moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier); - } - function allowsImportingSourceFile(sourceFile) { - if (!packageJsons.length) { - return true; - } - var moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName); - if (!moduleSpecifier) { - return true; - } - return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); + dispatchChanges(changes, context, code, start); + }); } - /** - * Use for a specific module specifier that has already been resolved. - * Use `allowsImportingAmbientModule` or `allowsImportingSourceFile` to resolve - * the best module specifier for a given module _and_ determine if it’s importable. - */ - function allowsImportingSpecifier(moduleSpecifier) { - if (!packageJsons.length || isAllowedCoreNodeModulesImport(moduleSpecifier)) { - return true; - } - if (ts.pathIsRelative(moduleSpecifier) || ts.isRootedDiskPath(moduleSpecifier)) { + }); + function dispatchChanges(changeTracker, context, errorCode, pos) { + switch (errorCode) { + case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code: + case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code: + case ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code: + return doAddOverrideModifierChange(changeTracker, context.sourceFile, pos); + case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code: + case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code: + return doRemoveOverrideModifierChange(changeTracker, context.sourceFile, pos); + default: + ts.Debug.fail("Unexpected error code: " + errorCode); + } + } + function doAddOverrideModifierChange(changeTracker, sourceFile, pos) { + var classElement = findContainerClassElementLike(sourceFile, pos); + var modifiers = classElement.modifiers || ts.emptyArray; + var staticModifier = ts.find(modifiers, ts.isStaticModifier); + var accessibilityModifier = ts.find(modifiers, function (m) { return ts.isAccessibilityModifier(m.kind); }); + var modifierPos = staticModifier ? staticModifier.end : + accessibilityModifier ? accessibilityModifier.end : + classElement.decorators ? ts.skipTrivia(sourceFile.text, classElement.decorators.end) : classElement.getStart(sourceFile); + var options = accessibilityModifier || staticModifier ? { prefix: " " } : { suffix: " " }; + changeTracker.insertModifierAt(sourceFile, modifierPos, 156 /* OverrideKeyword */, options); + } + function doRemoveOverrideModifierChange(changeTracker, sourceFile, pos) { + var classElement = findContainerClassElementLike(sourceFile, pos); + var overrideModifier = classElement.modifiers && ts.find(classElement.modifiers, function (modifier) { return modifier.kind === 156 /* OverrideKeyword */; }); + ts.Debug.assertIsDefined(overrideModifier); + changeTracker.deleteModifier(sourceFile, overrideModifier); + } + function isClassElementLikeHasJSDoc(node) { + switch (node.kind) { + case 167 /* Constructor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return true; - } - return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); - } - function isAllowedCoreNodeModulesImport(moduleSpecifier) { - // If we’re in JavaScript, it can be difficult to tell whether the user wants to import - // from Node core modules or not. We can start by seeing if the user is actually using - // any node core modules, as opposed to simply having @types/node accidentally as a - // dependency of a dependency. - if (ts.isSourceFileJS(fromFile) && ts.JsTyping.nodeCoreModules.has(moduleSpecifier)) { - if (usesNodeCoreModules === undefined) { - usesNodeCoreModules = ts.consumesNodeCoreModules(fromFile); - } - if (usesNodeCoreModules) { - return true; - } - } - return false; - } - function getNodeModulesPackageNameFromFileName(importedFileName) { - if (!ts.stringContains(importedFileName, "node_modules")) { - return undefined; - } - var specifier = ts.moduleSpecifiers.getNodeModulesPackageName(host.getCompilationSettings(), fromFile.path, importedFileName, moduleSpecifierResolutionHost); - if (!specifier) { - return undefined; - } - // Paths here are not node_modules, so we don’t care about them; - // returning anything will trigger a lookup in package.json. - if (!ts.pathIsRelative(specifier) && !ts.isRootedDiskPath(specifier)) { - return getNodeModuleRootSpecifier(specifier); - } - } - function getNodeModuleRootSpecifier(fullSpecifier) { - var components = ts.getPathComponents(ts.getPackageNameFromTypesPackageName(fullSpecifier)).slice(1); - // Scoped packages - if (ts.startsWith(components[0], "@")) { - return components[0] + "/" + components[1]; - } - return components[0]; + case 161 /* Parameter */: + return ts.isParameterPropertyDeclaration(node, node.parent); + default: + return false; } } + function findContainerClassElementLike(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var classElement = ts.findAncestor(token, function (node) { + if (ts.isClassLike(node)) + return "quit"; + return isClassElementLikeHasJSDoc(node); + }); + ts.Debug.assert(classElement && isClassElementLikeHasJSDoc(classElement)); + return classElement; + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -139043,7 +143500,7 @@ var ts; }); function getNamedTupleMember(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - return ts.findAncestor(token, function (t) { return t.kind === 192 /* NamedTupleMember */; }); + return ts.findAncestor(token, function (t) { return t.kind === 193 /* NamedTupleMember */; }); } function doChange(changes, sourceFile, namedTupleMember) { if (!namedTupleMember) { @@ -139052,11 +143509,11 @@ var ts; var unwrappedType = namedTupleMember.type; var sawOptional = false; var sawRest = false; - while (unwrappedType.kind === 180 /* OptionalType */ || unwrappedType.kind === 181 /* RestType */ || unwrappedType.kind === 186 /* ParenthesizedType */) { - if (unwrappedType.kind === 180 /* OptionalType */) { + while (unwrappedType.kind === 181 /* OptionalType */ || unwrappedType.kind === 182 /* RestType */ || unwrappedType.kind === 187 /* ParenthesizedType */) { + if (unwrappedType.kind === 181 /* OptionalType */) { sawOptional = true; } - else if (unwrappedType.kind === 181 /* RestType */) { + else if (unwrappedType.kind === 182 /* RestType */) { sawRest = true; } unwrappedType = unwrappedType.type; @@ -139120,7 +143577,7 @@ var ts; var checker = context.program.getTypeChecker(); var suggestedSymbol; if (ts.isPropertyAccessExpression(parent) && parent.name === node) { - ts.Debug.assert(ts.isIdentifierOrPrivateIdentifier(node), "Expected an identifier for spelling (property access)"); + ts.Debug.assert(ts.isMemberName(node), "Expected an identifier for spelling (property access)"); var containingType = checker.getTypeAtLocation(parent.expression); if (parent.flags & 32 /* OptionalChain */) { containingType = checker.getNonNullableType(containingType); @@ -139159,7 +143616,7 @@ var ts; var suggestion = ts.symbolName(suggestedSymbol); if (!ts.isIdentifierText(suggestion, target) && ts.isPropertyAccessExpression(node.parent)) { var valDecl = suggestedSymbol.valueDeclaration; - if (ts.isNamedDeclaration(valDecl) && ts.isPrivateIdentifier(valDecl.name)) { + if (valDecl && ts.isNamedDeclaration(valDecl) && ts.isPrivateIdentifier(valDecl.name)) { changes.replaceNode(sourceFile, node, ts.factory.createIdentifier(suggestion)); } else { @@ -139356,19 +143813,19 @@ var ts; } function getVariableLikeInitializer(declaration) { switch (declaration.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: - case 163 /* PropertyDeclaration */: - case 288 /* PropertyAssignment */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: + case 164 /* PropertyDeclaration */: + case 289 /* PropertyAssignment */: return declaration.initializer; - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return declaration.initializer && (ts.isJsxExpression(declaration.initializer) ? declaration.initializer.expression : undefined); - case 289 /* ShorthandPropertyAssignment */: - case 162 /* PropertySignature */: - case 291 /* EnumMember */: - case 333 /* JSDocPropertyTag */: - case 326 /* JSDocParameterTag */: + case 290 /* ShorthandPropertyAssignment */: + case 163 /* PropertySignature */: + case 292 /* EnumMember */: + case 337 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: return undefined; } } @@ -139469,7 +143926,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = codefix.getAllSupers(classDeclaration, checker); - var _loop_13 = function (info) { + var _loop_14 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -139494,9 +143951,9 @@ var ts; } } }; - for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { - var info = infos_1[_i]; - _loop_13(info); + for (var _i = 0, infos_2 = infos; _i < infos_2.length; _i++) { + var info = infos_2[_i]; + _loop_14(info); } }); })); @@ -139586,7 +144043,7 @@ var ts; function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, token, makeStatic) { var tokenName = token.text; if (makeStatic) { - if (classDeclaration.kind === 221 /* ClassExpression */) { + if (classDeclaration.kind === 222 /* ClassExpression */) { return; } var className = classDeclaration.name.getText(); @@ -139638,15 +144095,15 @@ var ts; } function getTypeNode(checker, classDeclaration, token) { var typeNode; - if (token.parent.parent.kind === 216 /* BinaryExpression */) { + if (token.parent.parent.kind === 217 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration, /*flags*/ undefined); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration, 1 /* NoTruncation */); } else { var contextualType = checker.getContextualType(token.parent); - typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined) : undefined; + typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, 1 /* NoTruncation */) : undefined; } return typeNode || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } @@ -139710,7 +144167,7 @@ var ts; } function addMethodDeclaration(context, changes, callExpression, name, modifierFlags, parentDeclaration, sourceFile) { var importAdder = codefix.createImportAdder(sourceFile, context.program, context.preferences, context.host); - var methodDeclaration = codefix.createSignatureDeclarationFromCallExpression(165 /* MethodDeclaration */, context, importAdder, callExpression, name, modifierFlags, parentDeclaration); + var methodDeclaration = codefix.createSignatureDeclarationFromCallExpression(166 /* MethodDeclaration */, context, importAdder, callExpression, name, modifierFlags, parentDeclaration); var containingMethodDeclaration = ts.findAncestor(callExpression, function (n) { return ts.isMethodDeclaration(n) || ts.isConstructorDeclaration(n); }); if (containingMethodDeclaration && containingMethodDeclaration.parent === parentDeclaration) { changes.insertNodeAfter(sourceFile, containingMethodDeclaration, methodDeclaration); @@ -139739,7 +144196,7 @@ var ts; } function addFunctionDeclaration(changes, context, info) { var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); - var functionDeclaration = codefix.createSignatureDeclarationFromCallExpression(251 /* FunctionDeclaration */, context, importAdder, info.call, info.token, info.modifierFlags, info.parentDeclaration); + var functionDeclaration = codefix.createSignatureDeclarationFromCallExpression(252 /* FunctionDeclaration */, context, importAdder, info.call, ts.idText(info.token), info.modifierFlags, info.parentDeclaration); changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -139826,7 +144283,10 @@ var ts; return { type: "install package", file: fileName, packageName: packageName }; } function tryGetImportedPackageName(sourceFile, pos) { - var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; + var moduleSpecifierText = ts.tryCast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral); + if (!moduleSpecifierText) + return undefined; + var moduleName = moduleSpecifierText.text; var packageName = ts.parsePackageName(moduleName).packageName; return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; } @@ -140056,7 +144516,10 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code], + errorCodes: [ + ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code, + ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code, + ], getCodeActions: function (context) { var compilerOptions = context.program.getCompilerOptions(); var configFile = compilerOptions.configFile; @@ -140427,7 +144890,7 @@ var ts; } function isImport(token) { return token.kind === 99 /* ImportKeyword */ - || token.kind === 78 /* Identifier */ && (token.parent.kind === 265 /* ImportSpecifier */ || token.parent.kind === 262 /* ImportClause */); + || token.kind === 78 /* Identifier */ && (token.parent.kind === 266 /* ImportSpecifier */ || token.parent.kind === 263 /* ImportClause */); } /** Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. */ function tryGetFullImport(token) { @@ -140437,7 +144900,7 @@ var ts; return ts.isVariableDeclarationList(token.parent) && ts.first(token.parent.getChildren(sourceFile)) === token; } function deleteEntireVariableStatement(changes, sourceFile, node) { - changes.delete(sourceFile, node.parent.kind === 232 /* VariableStatement */ ? node.parent : node); + changes.delete(sourceFile, node.parent.kind === 233 /* VariableStatement */ ? node.parent : node); } function deleteDestructuringElements(changes, sourceFile, node) { ts.forEach(node.elements, function (n) { return changes.delete(sourceFile, n); }); @@ -140462,14 +144925,14 @@ var ts; } function canPrefix(token) { switch (token.parent.kind) { - case 160 /* Parameter */: - case 159 /* TypeParameter */: + case 161 /* Parameter */: + case 160 /* TypeParameter */: return true; - case 249 /* VariableDeclaration */: { + case 250 /* VariableDeclaration */: { var varDecl = token.parent; switch (varDecl.parent.parent.kind) { - case 239 /* ForOfStatement */: - case 238 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 239 /* ForInStatement */: return true; } } @@ -140493,8 +144956,10 @@ var ts; if (ts.isParameter(parent)) { tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, program, cancellationToken, isFixAll); } - else if (!isFixAll || !(ts.isIdentifier(token) && ts.FindAllReferences.Core.isSymbolReferencedInFile(token, checker, sourceFile))) { - changes.delete(sourceFile, ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent); + else if (!(isFixAll && ts.isIdentifier(token) && ts.FindAllReferences.Core.isSymbolReferencedInFile(token, checker, sourceFile))) { + var node = ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent; + ts.Debug.assert(node !== sourceFile, "should not delete whole source file"); + changes.delete(sourceFile, node); } } function tryDeleteParameter(changes, sourceFile, parameter, checker, sourceFiles, program, cancellationToken, isFixAll) { @@ -140517,8 +144982,8 @@ var ts; function mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll) { var parent = parameter.parent; switch (parent.kind) { - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: var index = parent.parameters.indexOf(parameter); var referent = ts.isMethodDeclaration(parent) ? parent.name : parent; var entries = ts.FindAllReferences.Core.getReferencedSymbolsForNode(parent.pos, referent, program, sourceFiles, cancellationToken); @@ -140548,17 +145013,17 @@ var ts; } } return true; - case 251 /* FunctionDeclaration */: { + case 252 /* FunctionDeclaration */: { if (parent.name && isCallbackLike(checker, sourceFile, parent.name)) { return isLastParameter(parent, parameter, isFixAll); } return true; } - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused. return isLastParameter(parent, parameter, isFixAll); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: // Setter must have a parameter return false; default: @@ -140616,7 +145081,7 @@ var ts; var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { switch (container.kind) { - case 234 /* IfStatement */: + case 235 /* IfStatement */: if (container.elseStatement) { if (ts.isBlock(statement.parent)) { break; @@ -140627,8 +145092,8 @@ var ts; return; } // falls through - case 236 /* WhileStatement */: - case 237 /* ForStatement */: + case 237 /* WhileStatement */: + case 238 /* ForStatement */: changes.delete(sourceFile, container); return; } @@ -140701,7 +145166,7 @@ var ts; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; - if (typeNode.kind === 305 /* JSDocNullableType */) { + if (typeNode.kind === 306 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); @@ -140721,7 +145186,7 @@ var ts; if (!info) return; var typeNode = info.typeNode, type = info.type; - var fixedType = typeNode.kind === 305 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; + var fixedType = typeNode.kind === 306 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; doChange(changes, sourceFile, typeNode, fixedType, checker); }); } @@ -140738,22 +145203,22 @@ var ts; // NOTE: Some locations are not handled yet: // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments switch (node.kind) { - case 224 /* AsExpression */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 251 /* FunctionDeclaration */: - case 167 /* GetAccessor */: - case 171 /* IndexSignature */: - case 190 /* MappedType */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 168 /* SetAccessor */: - case 254 /* TypeAliasDeclaration */: - case 206 /* TypeAssertionExpression */: - case 249 /* VariableDeclaration */: + case 225 /* AsExpression */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 252 /* FunctionDeclaration */: + case 168 /* GetAccessor */: + case 172 /* IndexSignature */: + case 191 /* MappedType */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 169 /* SetAccessor */: + case 255 /* TypeAliasDeclaration */: + case 207 /* TypeAssertionExpression */: + case 250 /* VariableDeclaration */: return true; default: return false; @@ -140768,7 +145233,7 @@ var ts; (function (codefix) { var fixId = "fixMissingCallParentheses"; var errorCodes = [ - ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead.code, + ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -140814,7 +145279,7 @@ var ts; var fixId = "fixAwaitInSyncFunction"; var errorCodes = [ ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, - ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -140855,14 +145320,14 @@ var ts; } var insertBefore; switch (containingFunction.kind) { - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: insertBefore = containingFunction.name; break; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: insertBefore = ts.findChildOfKind(containingFunction, 97 /* FunctionKeyword */, sourceFile); break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); break; default: @@ -141061,7 +145526,7 @@ var ts; var typeNode = ts.getTypeNodeIfAccessible(type, parent, program, host); if (typeNode) { // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags - var typeTag = ts.factory.createJSDocTypeTag(/*tagName*/ undefined, ts.factory.createJSDocTypeExpression(typeNode), /*comment*/ ""); + var typeTag = ts.factory.createJSDocTypeTag(/*tagName*/ undefined, ts.factory.createJSDocTypeExpression(typeNode), /*comment*/ undefined); addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]); } importAdder.writeFixes(changes); @@ -141195,13 +145660,13 @@ var ts; function annotate(changes, importAdder, sourceFile, declaration, type, program, host) { var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { - if (ts.isInJSFile(sourceFile) && declaration.kind !== 162 /* PropertySignature */) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 163 /* PropertySignature */) { var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration; if (!parent) { return; } var typeExpression = ts.factory.createJSDocTypeExpression(typeNode); - var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.factory.createJSDocReturnTag(/*tagName*/ undefined, typeExpression, "") : ts.factory.createJSDocTypeTag(/*tagName*/ undefined, typeExpression, ""); + var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.factory.createJSDocReturnTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined) : ts.factory.createJSDocTypeTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined); addJSDocTags(changes, sourceFile, parent, [typeTag]); } else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, ts.getEmitScriptTarget(program.getCompilerOptions()))) { @@ -141256,13 +145721,13 @@ var ts; else { var paramTags = ts.map(inferences, function (_a) { var name = _a.name, typeNode = _a.typeNode, isOptional = _a.isOptional; - return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!isOptional, ts.factory.createJSDocTypeExpression(typeNode), /* isNameFirst */ false, ""); + return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!isOptional, ts.factory.createJSDocTypeExpression(typeNode), /* isNameFirst */ false, /*comment*/ undefined); }); addJSDocTags(changes, sourceFile, signature, paramTags); } } function addJSDocTags(changes, sourceFile, parent, newTags) { - var comments = ts.mapDefined(parent.jsDoc, function (j) { return j.comment; }); + var comments = ts.flatMap(parent.jsDoc, function (j) { return typeof j.comment === "string" ? ts.factory.createJSDocText(j.comment) : j.comment; }); var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }); var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) { var merged = tryMergeJsdocTags(tag, newTag); @@ -141270,15 +145735,15 @@ var ts; oldTags[i] = merged; return !!merged; }); }); - var tag = ts.factory.createJSDocComment(comments.join("\n"), ts.factory.createNodeArray(__spreadArray(__spreadArray([], (oldTags || ts.emptyArray)), unmergedNewTags))); - var jsDocNode = parent.kind === 209 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent; + var tag = ts.factory.createJSDocComment(ts.factory.createNodeArray(ts.intersperse(comments, ts.factory.createJSDocText("\n"))), ts.factory.createNodeArray(__spreadArray(__spreadArray([], (oldTags || ts.emptyArray)), unmergedNewTags))); + var jsDocNode = parent.kind === 210 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent; jsDocNode.jsDoc = parent.jsDoc; jsDocNode.jsDocCache = parent.jsDocCache; changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag); } codefix.addJSDocTags = addJSDocTags; function getJsDocNodeForArrowFunction(signature) { - if (signature.parent.kind === 163 /* PropertyDeclaration */) { + if (signature.parent.kind === 164 /* PropertyDeclaration */) { return signature.parent; } return signature.parent.parent; @@ -141288,14 +145753,14 @@ var ts; return undefined; } switch (oldTag.kind) { - case 326 /* JSDocParameterTag */: { + case 330 /* JSDocParameterTag */: { var oldParam = oldTag; var newParam = newTag; return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText ? ts.factory.createJSDocParameterTag(/*tagName*/ undefined, newParam.name, /*isBracketed*/ false, newParam.typeExpression, newParam.isNameFirst, oldParam.comment) : undefined; } - case 327 /* JSDocReturnTag */: + case 331 /* JSDocReturnTag */: return ts.factory.createJSDocReturnTag(/*tagName*/ undefined, newTag.typeExpression, oldTag.comment); } } @@ -141320,19 +145785,19 @@ var ts; function getFunctionReferences(containingFunction, sourceFile, program, cancellationToken) { var searchToken; switch (containingFunction.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: searchToken = ts.findChildOfKind(containingFunction, 132 /* ConstructorKeyword */, sourceFile); break; - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: var parent = containingFunction.parent; searchToken = (ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent)) && ts.isIdentifier(parent.name) ? parent.name : containingFunction.name; break; - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: searchToken = containingFunction.name; break; } @@ -141474,24 +145939,24 @@ var ts; node = node.parent; } switch (node.parent.kind) { - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: inferTypeFromExpressionStatement(node, usage); break; - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: usage.isNumber = true; break; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: inferTypeFromPrefixUnaryExpression(node.parent, usage); break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: inferTypeFromBinaryExpression(node, node.parent, usage); break; - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: inferTypeFromSwitchStatementLabel(node.parent, usage); break; - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: if (node.parent.expression === node) { inferTypeFromCallExpression(node.parent, usage); } @@ -141499,20 +145964,20 @@ var ts; inferTypeFromContextualType(node, usage); } break; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: inferTypeFromPropertyAccessExpression(node.parent, usage); break; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: inferTypeFromPropertyElementExpression(node.parent, node, usage); break; - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: inferTypeFromPropertyAssignment(node.parent, usage); break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: inferTypeFromPropertyDeclaration(node.parent, usage); break; - case 249 /* VariableDeclaration */: { + case 250 /* VariableDeclaration */: { var _a = node.parent, name = _a.name, initializer = _a.initializer; if (node === name) { if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. @@ -141634,7 +146099,7 @@ var ts; case 56 /* BarBarToken */: case 60 /* QuestionQuestionToken */: if (node === parent.left && - (node.parent.parent.kind === 249 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + (node.parent.parent.kind === 250 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { // var x = x || {}; // TODO: use getFalsyflagsOfType addCandidateType(usage, checker.getTypeAtLocation(parent.right)); @@ -141662,7 +146127,7 @@ var ts; } } calculateUsageOfNode(parent, call.return_); - if (parent.kind === 203 /* CallExpression */) { + if (parent.kind === 204 /* CallExpression */) { (usage.calls || (usage.calls = [])).push(call); } else { @@ -141765,7 +146230,7 @@ var ts; var anon = anons_1[_i]; for (var _a = 0, _b = checker.getPropertiesOfType(anon); _a < _b.length; _a++) { var p = _b[_a]; - props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration)); + props.add(p.name, p.valueDeclaration ? checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration) : checker.getAnyType()); } calls.push.apply(calls, checker.getSignaturesOfType(anon, 0 /* Call */)); constructs.push.apply(constructs, checker.getSignaturesOfType(anon, 1 /* Construct */)); @@ -141906,12 +146371,13 @@ var ts; if (!usageParam) { break; } - var genericParamType = checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration); + var genericParamType = genericParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration) : checker.getAnyType(); var elementType = isRest && checker.getElementTypeOfArrayType(genericParamType); if (elementType) { genericParamType = elementType; } - var targetType = usageParam.type || checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration); + var targetType = usageParam.type + || (usageParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration) : checker.getAnyType()); types.push.apply(types, inferTypeParameters(genericParamType, targetType, typeParameter)); } var genericReturn = checker.getReturnTypeOfSignature(genericSig); @@ -141925,7 +146391,7 @@ var ts; function getSignatureFromCalls(calls) { var parameters = []; var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; })); - var _loop_14 = function (i) { + var _loop_15 = function (i) { var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); })); if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) { @@ -141934,7 +146400,7 @@ var ts; parameters.push(symbol); }; for (var i = 0; i < length; i++) { - _loop_14(i); + _loop_15(i); } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); // TODO: GH#18217 @@ -142105,8 +146571,8 @@ var ts; var ambient = !!(enclosingDeclaration.flags & 8388608 /* Ambient */); var quotePreference = ts.getQuotePreference(sourceFile, preferences); switch (declaration.kind) { - case 162 /* PropertySignature */: - case 163 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 164 /* PropertyDeclaration */: var flags = quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : undefined; var typeNode = checker.typeToTypeNode(type, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); if (importAdder) { @@ -142120,8 +146586,8 @@ var ts; /*decorators*/ undefined, modifiers, name, optional ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: { + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: { var typeNode_1 = checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); var allAccessors = ts.getAllAccessorDeclarations(declarations, declaration); var orderedAccessors = allAccessors.secondAccessor @@ -142150,8 +146616,8 @@ var ts; } break; } - case 164 /* MethodSignature */: - case 165 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 166 /* MethodDeclaration */: // The signature for the implementation appears as an entry in `signatures` iff // there is only one signature. // If there are overloads and an implementation signature, it appears as an @@ -142181,7 +146647,7 @@ var ts; } else { ts.Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count"); - addClassElement(createMethodImplementingSignatures(signatures, name, optional, modifiers, quotePreference)); + addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference)); } } break; @@ -142197,7 +146663,7 @@ var ts; var checker = program.getTypeChecker(); var scriptTarget = ts.getEmitScriptTarget(program.getCompilerOptions()); var flags = 1 /* NoTruncation */ | 1073741824 /* NoUndefinedOptionalParameterType */ | 256 /* SuppressAnyReturnType */ | (quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0); - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 165 /* MethodDeclaration */, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 166 /* MethodDeclaration */, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); if (!signatureDeclaration) { return undefined; } @@ -142281,7 +146747,7 @@ var ts; var type = isJs || contextualType === undefined ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker); - if (kind === 165 /* MethodDeclaration */) { + if (kind === 166 /* MethodDeclaration */) { return ts.factory.createMethodDeclaration( /*decorators*/ undefined, modifiers, asteriskToken, name, /*questionToken*/ undefined, typeParameters, parameters, type, ts.isInterfaceDeclaration(contextNode) ? undefined : createStubbedMethodBody(quotePreference)); @@ -142317,7 +146783,7 @@ var ts; } return parameters; } - function createMethodImplementingSignatures(signatures, name, optional, modifiers, quotePreference) { + function createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference) { /** This is *a* signature with the maximal number of arguments, * such that if there is a "maximal" signature without rest arguments, * this is one of them. @@ -142348,8 +146814,13 @@ var ts; parameters.push(restParameter); } return createStubbedMethod(modifiers, name, optional, - /*typeParameters*/ undefined, parameters, - /*returnType*/ undefined, quotePreference); + /*typeParameters*/ undefined, parameters, getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), quotePreference); + } + function getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration) { + if (ts.length(signatures)) { + var type = checker.getUnionType(ts.map(signatures, checker.getReturnTypeOfSignature)); + return checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); + } } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference) { return ts.factory.createMethodDeclaration( @@ -142476,13 +146947,13 @@ var ts; if (ts.isClassLike(container)) { var modifierFlags = ts.getEffectiveModifierFlags(declaration); if (ts.isSourceFileJS(file)) { - var modifiers = createModifiers(modifierFlags); + var modifiers = ts.createModifiers(modifierFlags); accessorModifiers = modifiers; fieldModifiers = modifiers; } else { - accessorModifiers = createModifiers(prepareModifierFlagsForAccessor(modifierFlags)); - fieldModifiers = createModifiers(prepareModifierFlagsForField(modifierFlags)); + accessorModifiers = ts.createModifiers(prepareModifierFlagsForAccessor(modifierFlags)); + fieldModifiers = ts.createModifiers(prepareModifierFlagsForField(modifierFlags)); } } updateFieldDeclaration(changeTracker, file, declaration, type, fieldName, fieldModifiers); @@ -142517,9 +146988,6 @@ var ts; var leftHead = isStatic ? container.name : ts.factory.createThis(); // TODO: GH#18217 return ts.isIdentifier(fieldName) ? ts.factory.createPropertyAccessExpression(leftHead, fieldName) : ts.factory.createElementAccessExpression(leftHead, ts.factory.createStringLiteralFromNode(fieldName)); } - function createModifiers(modifierFlags) { - return modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; - } function prepareModifierFlagsForAccessor(modifierFlags) { modifierFlags &= ~64 /* Readonly */; // avoid Readonly modifier because it will convert to get accessor modifierFlags &= ~8 /* Private */; @@ -142564,7 +147032,7 @@ var ts; isStatic: ts.hasStaticModifier(declaration), isReadonly: ts.hasEffectiveReadonlyModifier(declaration), type: getDeclarationType(declaration, program), - container: declaration.kind === 160 /* Parameter */ ? declaration.parent.parent : declaration.parent, + container: declaration.kind === 161 /* Parameter */ ? declaration.parent.parent : declaration.parent, originalName: declaration.name.text, declaration: declaration, fieldName: fieldName, @@ -142654,7 +147122,7 @@ var ts; if (!superSymbol) break; var symbol = superSymbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(superSymbol) : superSymbol; - var superDecl = ts.find(symbol.declarations, ts.isClassLike); + var superDecl = symbol.declarations && ts.find(symbol.declarations, ts.isClassLike); if (!superDecl) break; res.push(superDecl); @@ -142700,7 +147168,7 @@ var ts; }); function getActionsForUsageOfInvalidImport(context) { var sourceFile = context.sourceFile; - var targetKind = ts.Diagnostics.This_expression_is_not_callable.code === context.errorCode ? 203 /* CallExpression */ : 204 /* NewExpression */; + var targetKind = ts.Diagnostics.This_expression_is_not_callable.code === context.errorCode ? 204 /* CallExpression */ : 205 /* NewExpression */; var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind; }); if (!node) { return []; @@ -143034,7 +147502,7 @@ var ts; function getImportTypeNode(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); ts.Debug.assert(token.kind === 99 /* ImportKeyword */, "This token should be an ImportKeyword"); - ts.Debug.assert(token.parent.kind === 195 /* ImportType */, "Token parent should be an ImportType"); + ts.Debug.assert(token.parent.kind === 196 /* ImportType */, "Token parent should be an ImportType"); return token.parent; } function doChange(changes, sourceFile, importType) { @@ -143301,7 +147769,7 @@ var ts; var token = ts.getTokenAtPosition(sourceFile, pos); var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(token); - if (symbol) { + if (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) { return symbol.valueDeclaration.parent.parent; } } @@ -143496,23 +147964,23 @@ var ts; return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_find_export_statement) }; } var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol; - var flags = ts.getSyntacticModifierFlags(exportNode); + var flags = ts.getSyntacticModifierFlags(exportNode) || ((ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) ? 513 /* ExportDefault */ : 0 /* None */); var wasDefault = !!(flags & 512 /* Default */); // If source file already has a default export, don't offer refactor. if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.This_file_already_has_a_default_export) }; } switch (exportNode.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 256 /* ModuleDeclaration */: { + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 257 /* ModuleDeclaration */: { var node = exportNode; return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; } - case 232 /* VariableStatement */: { + case 233 /* VariableStatement */: { var vs = exportNode; // Must be `export const x = something;`. if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { @@ -143524,6 +147992,11 @@ var ts; ts.Debug.assert(!wasDefault, "Can't have a default flag here"); return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; } + case 267 /* ExportAssignment */: { + var node = exportNode; + var exp = node.expression; + return node.isExportEquals ? undefined : { exportNode: node, exportName: exp, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol }; + } default: return undefined; } @@ -143535,17 +148008,24 @@ var ts; function changeExport(exportingSourceFile, _a, changes, checker) { var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; if (wasDefault) { - changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 87 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + if (ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) { + var exp = exportNode.expression; + var spec = makeExportSpecifier(exp.text, exp.text); + changes.replaceNode(exportingSourceFile, exportNode, ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([spec]))); + } + else { + changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 87 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + } } else { var exportKeyword = ts.Debug.checkDefined(ts.findModifier(exportNode, 92 /* ExportKeyword */), "Should find an export keyword in modifier list"); switch (exportNode.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.factory.createToken(87 /* DefaultKeyword */)); break; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // If 'x' isn't used in this file and doesn't have type definition, `export const x = 0;` --> `export default 0;` var decl = ts.first(exportNode.declarationList.declarations); if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile) && !decl.type) { @@ -143554,15 +148034,15 @@ var ts; break; } // falls through - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 256 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 257 /* ModuleDeclaration */: // `export type T = number;` -> `type T = number; export default T;` changes.deleteModifier(exportingSourceFile, exportKeyword); changes.insertNodeAfter(exportingSourceFile, exportNode, ts.factory.createExportDefault(ts.factory.createIdentifier(exportName.text))); break; default: - ts.Debug.assertNever(exportNode, "Unexpected exportNode kind " + exportNode.kind); + ts.Debug.fail("Unexpected exportNode kind " + exportNode.kind); } } } @@ -143583,18 +148063,18 @@ var ts; function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { var parent = ref.parent; switch (parent.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: // `a.default` --> `a.foo` changes.replaceNode(importingSourceFile, ref, ts.factory.createIdentifier(exportName)); break; - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: { + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: { var spec = parent; // `default as foo` --> `foo`, `default as bar` --> `foo as bar` changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); break; } - case 262 /* ImportClause */: { + case 263 /* ImportClause */: { var clause = parent; ts.Debug.assert(clause.name === ref, "Import clause name should match provided ref"); var spec = makeImportSpecifier(exportName, ref.text); @@ -143603,7 +148083,7 @@ var ts; // `import foo from "./a";` --> `import { foo } from "./a";` changes.replaceNode(importingSourceFile, ref, ts.factory.createNamedImports([spec])); } - else if (namedBindings.kind === 263 /* NamespaceImport */) { + else if (namedBindings.kind === 264 /* NamespaceImport */) { // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";` changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; @@ -143624,11 +148104,11 @@ var ts; function changeNamedToDefaultImport(importingSourceFile, ref, changes) { var parent = ref.parent; switch (parent.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: // `a.foo` --> `a.default` changes.replaceNode(importingSourceFile, ref, ts.factory.createIdentifier("default")); break; - case 265 /* ImportSpecifier */: { + case 266 /* ImportSpecifier */: { // `import { foo } from "./a";` --> `import foo from "./a";` // `import { foo as bar } from "./a";` --> `import bar from "./a";` var defaultImport = ts.factory.createIdentifier(parent.name.text); @@ -143641,7 +148121,7 @@ var ts; } break; } - case 270 /* ExportSpecifier */: { + case 271 /* ExportSpecifier */: { // `export { foo } from "./a";` --> `export { default as foo } from "./a";` // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` // `export { foo as default } from "./a";` --> `export { default } from "./a";` @@ -143687,14 +148167,16 @@ var ts; if (!info) return ts.emptyArray; if (!refactor.isRefactorErrorInfo(info)) { - var namespaceImport = info.kind === 263 /* NamespaceImport */; + var namespaceImport = info.kind === 264 /* NamespaceImport */; var action = namespaceImport ? namespaceToNamedAction : namedToNamespaceAction; return [{ name: refactorName, description: action.description, actions: [action] }]; } if (context.preferences.provideRefactorNotApplicableReason) { return [ - { name: refactorName, description: namespaceToNamedAction.description, actions: [__assign(__assign({}, namespaceToNamedAction), { notApplicableReason: info.error })] }, - { name: refactorName, description: namedToNamespaceAction.description, actions: [__assign(__assign({}, namedToNamespaceAction), { notApplicableReason: info.error })] } + { name: refactorName, description: namespaceToNamedAction.description, + actions: [__assign(__assign({}, namespaceToNamedAction), { notApplicableReason: info.error })] }, + { name: refactorName, description: namedToNamespaceAction.description, + actions: [__assign(__assign({}, namedToNamespaceAction), { notApplicableReason: info.error })] } ]; } return ts.emptyArray; @@ -143729,7 +148211,7 @@ var ts; } function doChange(sourceFile, program, changes, toConvert) { var checker = program.getTypeChecker(); - if (toConvert.kind === 263 /* NamespaceImport */) { + if (toConvert.kind === 264 /* NamespaceImport */) { doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); } else { @@ -143794,7 +148276,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_15 = function (element) { + var _loop_16 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(namespaceImportName), propertyName); @@ -143813,7 +148295,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_15(element); + _loop_16(element); } changes.replaceNode(sourceFile, toConvert, ts.factory.createNamespaceImport(ts.factory.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -144130,27 +148612,27 @@ var ts; var lastDeclaration = signatureDecls[signatureDecls.length - 1]; var updated = lastDeclaration; switch (lastDeclaration.kind) { - case 164 /* MethodSignature */: { + case 165 /* MethodSignature */: { updated = ts.factory.updateMethodSignature(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); break; } - case 165 /* MethodDeclaration */: { + case 166 /* MethodDeclaration */: { updated = ts.factory.updateMethodDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } - case 169 /* CallSignature */: { + case 170 /* CallSignature */: { updated = ts.factory.updateCallSignature(lastDeclaration, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); break; } - case 166 /* Constructor */: { + case 167 /* Constructor */: { updated = ts.factory.updateConstructorDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.body); break; } - case 170 /* ConstructSignature */: { + case 171 /* ConstructSignature */: { updated = ts.factory.updateConstructSignature(lastDeclaration, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); break; } - case 251 /* FunctionDeclaration */: { + case 252 /* FunctionDeclaration */: { updated = ts.factory.updateFunctionDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } @@ -144202,12 +148684,12 @@ var ts; } function isConvertableSignatureDeclaration(d) { switch (d.kind) { - case 164 /* MethodSignature */: - case 165 /* MethodDeclaration */: - case 169 /* CallSignature */: - case 166 /* Constructor */: - case 170 /* ConstructSignature */: - case 251 /* FunctionDeclaration */: + case 165 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 170 /* CallSignature */: + case 167 /* Constructor */: + case 171 /* ConstructSignature */: + case 252 /* FunctionDeclaration */: return true; } return false; @@ -144347,7 +148829,6 @@ var ts; }; } } - // Skip these since we don't have a way to report errors yet if (refactor.refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { if (constantExtraction.errors.length === 0) { // Don't issue refactorings with duplicated names. @@ -144479,24 +148960,28 @@ var ts; /** * getRangeToExtract takes a span inside a text file and returns either an expression or an array * of statements representing the minimum set of nodes needed to extract the entire span. This - * process may fail, in which case a set of errors is returned instead (these are currently - * not shown to the user, but can be used by us diagnostically) + * process may fail, in which case a set of errors is returned instead. These errors are shown to + * users if they have the provideRefactorNotApplicableReason option set. */ // exported only for tests - function getRangeToExtract(sourceFile, span, considerEmptySpans) { - if (considerEmptySpans === void 0) { considerEmptySpans = true; } + function getRangeToExtract(sourceFile, span, invoked) { + if (invoked === void 0) { invoked = true; } var length = span.length; - if (length === 0 && !considerEmptySpans) { + if (length === 0 && !invoked) { return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] }; } - var cursorRequest = length === 0 && considerEmptySpans; + var cursorRequest = length === 0 && invoked; + var startToken = ts.findFirstNonJsxWhitespaceToken(sourceFile, span.start); + var endToken = ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)); + /* If the refactoring command is invoked through a keyboard action it's safe to assume that the user is actively looking for + refactoring actions at the span location. As they may not know the exact range that will trigger a refactoring, we expand the + searched span to cover a real node range making it more likely that something useful will show up. */ + var adjustedSpan = startToken && endToken && invoked ? getAdjustedSpanFromNodes(startToken, endToken, sourceFile) : span; // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span. // This may fail (e.g. you select two statements in the root of a source file) - var startToken = ts.getTokenAtPosition(sourceFile, span.start); - var start = cursorRequest ? getExtractableParent(startToken) : ts.getParentNodeInSpan(startToken, sourceFile, span); + var start = cursorRequest ? getExtractableParent(startToken) : ts.getParentNodeInSpan(startToken, sourceFile, adjustedSpan); // Do the same for the ending position - var endToken = ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)); - var end = cursorRequest ? start : ts.getParentNodeInSpan(endToken, sourceFile, span); + var end = cursorRequest ? start : ts.getParentNodeInSpan(endToken, sourceFile, adjustedSpan); var declarations = []; // We'll modify these flags as we walk the tree to collect data // about what things need to be done as part of the extraction. @@ -144505,6 +148990,9 @@ var ts; // cannot find either start or end node return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } + if (ts.isJSDoc(start)) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractJSDoc)] }; + } if (start.parent !== end.parent) { // start and end nodes belong to different subtrees return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; @@ -144539,9 +149027,6 @@ var ts; } return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; } - if (ts.isJSDoc(start)) { - return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractJSDoc)] }; - } if (ts.isReturnStatement(start) && !start.expression) { // Makes no sense to extract an expression-less return statement. return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; @@ -144594,20 +149079,20 @@ var ts; function checkForStaticContext(nodeToCheck, containingClass) { var current = nodeToCheck; while (current !== containingClass) { - if (current.kind === 163 /* PropertyDeclaration */) { + if (current.kind === 164 /* PropertyDeclaration */) { if (ts.hasSyntacticModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 160 /* Parameter */) { + else if (current.kind === 161 /* Parameter */) { var ctorOrMethod = ts.getContainingFunction(current); - if (ctorOrMethod.kind === 166 /* Constructor */) { + if (ctorOrMethod.kind === 167 /* Constructor */) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 165 /* MethodDeclaration */) { + else if (current.kind === 166 /* MethodDeclaration */) { if (ts.hasSyntacticModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } @@ -144650,7 +149135,7 @@ var ts; return true; } if (ts.isDeclaration(node)) { - var declaringNode = (node.kind === 249 /* VariableDeclaration */) ? node.parent.parent : node; + var declaringNode = (node.kind === 250 /* VariableDeclaration */) ? node.parent.parent : node; if (ts.hasSyntacticModifier(declaringNode, 1 /* Export */)) { // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! @@ -144662,16 +149147,16 @@ var ts; } // Some things can't be extracted in certain situations switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); return true; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; case 105 /* SuperKeyword */: // For a super *constructor call*, we have to be extracting the entire class, // but a super *method call* simply implies a 'this' reference - if (node.parent.kind === 203 /* CallExpression */) { + if (node.parent.kind === 204 /* CallExpression */) { // Super constructor call var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { @@ -144683,7 +149168,7 @@ var ts; rangeFacts |= RangeFacts.UsesThis; } break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: // check if arrow function uses this ts.forEachChild(node, function check(n) { if (ts.isThis(n)) { @@ -144697,39 +149182,39 @@ var ts; } }); // falls through - case 252 /* ClassDeclaration */: - case 251 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { // You cannot extract global declarations (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); } // falls through - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // do not dive into functions or classes return false; } var savedPermittedJumps = permittedJumps; switch (node.kind) { - case 234 /* IfStatement */: + case 235 /* IfStatement */: permittedJumps = 0 /* None */; break; - case 247 /* TryStatement */: + case 248 /* TryStatement */: // forbid all jumps inside try blocks permittedJumps = 0 /* None */; break; - case 230 /* Block */: - if (node.parent && node.parent.kind === 247 /* TryStatement */ && node.parent.finallyBlock === node) { + case 231 /* Block */: + if (node.parent && node.parent.kind === 248 /* TryStatement */ && node.parent.finallyBlock === node) { // allow unconditional returns from finally blocks permittedJumps = 4 /* Return */; } break; - case 285 /* DefaultClause */: - case 284 /* CaseClause */: + case 286 /* DefaultClause */: + case 285 /* CaseClause */: // allow unlabeled break inside case clauses permittedJumps |= 1 /* Break */; break; @@ -144741,19 +149226,19 @@ var ts; break; } switch (node.kind) { - case 187 /* ThisType */: + case 188 /* ThisType */: case 107 /* ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; break; - case 245 /* LabeledStatement */: { + case 246 /* LabeledStatement */: { var label = node.label; (seenLabels || (seenLabels = [])).push(label.escapedText); ts.forEachChild(node, visit); seenLabels.pop(); break; } - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: { + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: { var label = node.label; if (label) { if (!ts.contains(seenLabels, label.escapedText)) { @@ -144762,20 +149247,20 @@ var ts; } } else { - if (!(permittedJumps & (node.kind === 241 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + if (!(permittedJumps & (node.kind === 242 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { // attempt to break or continue in a forbidden context (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); } } break; } - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: rangeFacts |= RangeFacts.IsGenerator; break; - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: if (permittedJumps & 4 /* Return */) { rangeFacts |= RangeFacts.HasReturn; } @@ -144792,6 +149277,18 @@ var ts; } } extractSymbol.getRangeToExtract = getRangeToExtract; + /** + * Includes the final semicolon so that the span covers statements in cases where it would otherwise + * only cover the declaration list. + */ + function getAdjustedSpanFromNodes(startNode, endNode, sourceFile) { + var start = startNode.getStart(sourceFile); + var end = endNode.getEnd(); + if (sourceFile.text.charCodeAt(end) === 59 /* semicolon */) { + end++; + } + return { start: start, length: end - start }; + } function getStatementOrExpressionRange(node) { if (ts.isStatement(node)) { return [node]; @@ -144829,7 +149326,7 @@ var ts; while (true) { current = current.parent; // A function parameter's initializer is actually in the outer scope, not the function declaration - if (current.kind === 160 /* Parameter */) { + if (current.kind === 161 /* Parameter */) { // Skip all the way to the outer scope of the function that declared this parameter current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; } @@ -144840,7 +149337,7 @@ var ts; // * Module/namespace or source file if (isScope(current)) { scopes.push(current); - if (current.kind === 297 /* SourceFile */) { + if (current.kind === 298 /* SourceFile */) { return scopes; } } @@ -144930,32 +149427,32 @@ var ts; } function getDescriptionForFunctionLikeDeclaration(scope) { switch (scope.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return "constructor"; - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: return scope.name ? "function '" + scope.name.text + "'" : ts.ANONYMOUS; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return "arrow function"; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return "method '" + scope.name.getText() + "'"; - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: return "'get " + scope.name.getText() + "'"; - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: return "'set " + scope.name.getText() + "'"; default: throw ts.Debug.assertNever(scope, "Unexpected scope kind " + scope.kind); } } function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 252 /* ClassDeclaration */ + return scope.kind === 253 /* ClassDeclaration */ ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration" : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; } function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 257 /* ModuleBlock */ + return scope.kind === 258 /* ModuleBlock */ ? "namespace '" + scope.parent.name.getText() + "'" : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; } @@ -145244,7 +149741,7 @@ var ts; var localReference = ts.factory.createIdentifier(localNameText); changeTracker.replaceNode(context.file, node, localReference); } - else if (node.parent.kind === 233 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + else if (node.parent.kind === 234 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { // If the parent is an expression statement and the target scope is the immediately enclosing one, // replace the statement with the declaration. var newVariableStatement = ts.factory.createVariableStatement( @@ -145263,7 +149760,7 @@ var ts; changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); } // Consume - if (node.parent.kind === 233 /* ExpressionStatement */) { + if (node.parent.kind === 234 /* ExpressionStatement */) { // If the parent is an expression statement, delete it. changeTracker.delete(context.file, node.parent); } @@ -145590,7 +150087,7 @@ var ts; var scope = scopes_1[_i]; usagesPerScope.push({ usages: new ts.Map(), typeParameterUsages: new ts.Map(), substitutions: new ts.Map() }); substitutionsPerScope.push(new ts.Map()); - functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 251 /* FunctionDeclaration */ + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 252 /* FunctionDeclaration */ ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] : []); var constantErrors = []; @@ -145653,7 +150150,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_16 = function (i) { + var _loop_17 = 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 @@ -145693,7 +150190,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_16(i); + _loop_17(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -145909,30 +150406,30 @@ var ts; function isExtractableExpression(node) { var parent = node.parent; switch (parent.kind) { - case 291 /* EnumMember */: + case 292 /* EnumMember */: return false; } switch (node.kind) { case 10 /* StringLiteral */: - return parent.kind !== 261 /* ImportDeclaration */ && - parent.kind !== 265 /* ImportSpecifier */; - case 220 /* SpreadElement */: - case 196 /* ObjectBindingPattern */: - case 198 /* BindingElement */: + return parent.kind !== 262 /* ImportDeclaration */ && + parent.kind !== 266 /* ImportSpecifier */; + case 221 /* SpreadElement */: + case 197 /* ObjectBindingPattern */: + case 199 /* BindingElement */: return false; case 78 /* Identifier */: - return parent.kind !== 198 /* BindingElement */ && - parent.kind !== 265 /* ImportSpecifier */ && - parent.kind !== 270 /* ExportSpecifier */; + return parent.kind !== 199 /* BindingElement */ && + parent.kind !== 266 /* ImportSpecifier */ && + parent.kind !== 271 /* ExportSpecifier */; } return true; } function isBlockLike(node) { switch (node.kind) { - case 230 /* Block */: - case 297 /* SourceFile */: - case 257 /* ModuleBlock */: - case 284 /* CaseClause */: + case 231 /* Block */: + case 298 /* SourceFile */: + case 258 /* ModuleBlock */: + case 285 /* CaseClause */: return true; default: return false; @@ -146074,7 +150571,7 @@ var ts; if (ts.isTypeReferenceNode(node)) { if (ts.isIdentifier(node.typeName)) { var symbol = checker.resolveName(node.typeName.text, node.typeName, 262144 /* TypeParameter */, /* excludeGlobals */ true); - if (symbol) { + if (symbol === null || symbol === void 0 ? void 0 : symbol.declarations) { var declaration = ts.cast(ts.first(symbol.declarations), ts.isTypeParameterDeclaration); if (rangeContainsSkipTrivia(statement, declaration, file) && !rangeContainsSkipTrivia(selection, declaration, file)) { ts.pushIfUnique(result, declaration); @@ -146097,7 +150594,7 @@ var ts; else if (ts.isTypeQueryNode(node)) { if (ts.isIdentifier(node.exprName)) { var symbol = checker.resolveName(node.exprName.text, node.exprName, 111551 /* Value */, /* excludeGlobals */ false); - if (symbol && rangeContainsSkipTrivia(statement, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) { + if ((symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) && rangeContainsSkipTrivia(statement, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) { return true; } } @@ -146317,11 +150814,11 @@ var ts; } function isPureImport(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return true; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return !ts.hasSyntacticModifier(node, 1 /* Export */); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); default: return false; @@ -146382,10 +150879,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_17 = function (sourceFile) { + var _loop_18 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_18 = function (statement) { + var _loop_19 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -146407,22 +150904,22 @@ var ts; }; for (var _b = 0, _c = sourceFile.statements; _b < _c.length; _b++) { var statement = _c[_b]; - _loop_18(statement); + _loop_19(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_17(sourceFile); + _loop_18(sourceFile); } } function getNamespaceLikeImport(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 263 /* NamespaceImport */ ? + case 262 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 264 /* NamespaceImport */ ? node.importClause.namedBindings.name : undefined; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return node.name; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return ts.tryCast(node.name, ts.isIdentifier); default: return ts.Debug.assertNever(node, "Unexpected node kind " + node.kind); @@ -146453,20 +150950,20 @@ var ts; var newNamespaceId = ts.factory.createIdentifier(newNamespaceName); var newModuleString = ts.factory.createStringLiteral(newModuleSpecifier); switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamespaceImport(newNamespaceId)), newModuleString); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return ts.factory.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, newNamespaceId, ts.factory.createExternalModuleReference(newModuleString)); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return ts.factory.createVariableDeclaration(newNamespaceId, /*exclamationToken*/ undefined, /*type*/ undefined, createRequireCall(newModuleString)); default: return ts.Debug.assertNever(node, "Unexpected node kind " + node.kind); } } function moduleSpecifierFromImport(i) { - return (i.kind === 261 /* ImportDeclaration */ ? i.moduleSpecifier - : i.kind === 260 /* ImportEqualsDeclaration */ ? i.moduleReference.expression + return (i.kind === 262 /* ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 261 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]); } function forEachImportInStatement(statement, cb) { @@ -146536,15 +151033,15 @@ var ts; } function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { switch (importDecl.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); break; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: if (isUnused(importDecl.name)) { changes.delete(sourceFile, importDecl); } break; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); break; default: @@ -146557,7 +151054,7 @@ var ts; var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; var defaultUnused = !name || isUnused(name); var namedBindingsUnused = !namedBindings || - (namedBindings.kind === 263 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); + (namedBindings.kind === 264 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); if (defaultUnused && namedBindingsUnused) { changes.delete(sourceFile, importDecl); } @@ -146569,7 +151066,7 @@ var ts; if (namedBindingsUnused) { changes.replaceNode(sourceFile, importDecl.importClause, ts.factory.updateImportClause(importDecl.importClause, importDecl.importClause.isTypeOnly, name, /*namedBindings*/ undefined)); } - else if (namedBindings.kind === 264 /* NamedImports */) { + else if (namedBindings.kind === 265 /* NamedImports */) { for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { var element = _b[_i]; if (isUnused(element.name)) @@ -146587,9 +151084,9 @@ var ts; changes.delete(sourceFile, name); } break; - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: break; - case 196 /* ObjectBindingPattern */: + case 197 /* ObjectBindingPattern */: if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); } @@ -146617,6 +151114,9 @@ var ts; var oldFileNamedImports = []; var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`. newFileImportsFromOldFile.forEach(function (symbol) { + if (!symbol.declarations) { + return; + } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; if (!isTopLevelDeclaration(decl)) @@ -146716,14 +151216,14 @@ var ts; // Below should all be utilities function isInImport(decl) { switch (decl.kind) { - case 260 /* ImportEqualsDeclaration */: - case 265 /* ImportSpecifier */: - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: + case 261 /* ImportEqualsDeclaration */: + case 266 /* ImportSpecifier */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: return true; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return isVariableDeclarationInImport(decl); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); default: return false; @@ -146735,7 +151235,7 @@ var ts; } function filterImport(i, moduleSpecifier, keep) { switch (i.kind) { - case 261 /* ImportDeclaration */: { + case 262 /* ImportDeclaration */: { var clause = i.importClause; if (!clause) return undefined; @@ -146745,9 +151245,9 @@ var ts; ? ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImport, namedBindings), moduleSpecifier) : undefined; } - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return keep(i.name) ? i : undefined; - case 249 /* VariableDeclaration */: { + case 250 /* VariableDeclaration */: { var name = filterBindingName(i.name, keep); return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; } @@ -146756,7 +151256,7 @@ var ts; } } function filterNamedBindings(namedBindings, keep) { - if (namedBindings.kind === 263 /* NamespaceImport */) { + if (namedBindings.kind === 264 /* NamespaceImport */) { return keep(namedBindings.name) ? namedBindings : undefined; } else { @@ -146768,9 +151268,9 @@ var ts; switch (name.kind) { case 78 /* Identifier */: return keep(name) ? name : undefined; - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: return name; - case 196 /* ObjectBindingPattern */: { + case 197 /* ObjectBindingPattern */: { // We can't handle nested destructurings or property names well here, so just copy them all. var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); return newElements.length ? ts.factory.createObjectBindingPattern(newElements) : undefined; @@ -146827,13 +151327,13 @@ var ts; } function isNonVariableTopLevelDeclaration(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 261 /* ImportEqualsDeclaration */: return true; default: return false; @@ -146841,17 +151341,17 @@ var ts; } function forEachTopLevelDeclaration(statement, cb) { switch (statement.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 261 /* ImportEqualsDeclaration */: return cb(statement); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return ts.firstDefined(statement.declarationList.declarations, function (decl) { return forEachTopLevelDeclarationInBindingName(decl.name, cb); }); - case 233 /* ExpressionStatement */: { + case 234 /* ExpressionStatement */: { var expression = statement.expression; return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) @@ -146863,8 +151363,8 @@ var ts; switch (name.kind) { case 78 /* Identifier */: return cb(ts.cast(name.parent, function (x) { return ts.isVariableDeclaration(x) || ts.isBindingElement(x); })); - case 197 /* ArrayBindingPattern */: - case 196 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: return ts.firstDefined(name.elements, function (em) { return ts.isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb); }); default: return ts.Debug.assertNever(name, "Unexpected name kind " + name.kind); @@ -146875,9 +151375,9 @@ var ts; } function getTopLevelDeclarationStatement(d) { switch (d.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return d.parent.parent; - case 198 /* BindingElement */: + case 199 /* BindingElement */: return getTopLevelDeclarationStatement(ts.cast(d.parent.parent, function (p) { return ts.isVariableDeclaration(p) || ts.isBindingElement(p); })); default: return d; @@ -146910,23 +151410,23 @@ var ts; function addEs6Export(d) { var modifiers = ts.concatenate([ts.factory.createModifier(92 /* ExportKeyword */)], d.modifiers); switch (d.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return ts.factory.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return ts.factory.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return ts.factory.updateVariableStatement(d, modifiers, d.declarationList); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return ts.factory.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return ts.factory.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return ts.factory.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return ts.factory.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return ts.factory.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.isTypeOnly, d.name, d.moduleReference); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(d, "Unexpected declaration kind " + d.kind); @@ -146937,18 +151437,18 @@ var ts; } function getNamesToExportInCommonJS(decl) { switch (decl.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: return [decl.name.text]; // TODO: GH#18217 - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 261 /* ImportEqualsDeclaration */: return ts.emptyArray; - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return ts.Debug.fail("Can't export an ExpressionStatement"); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(decl, "Unexpected decl kind " + decl.kind); @@ -147117,13 +151617,13 @@ var ts; return { edits: [] }; // TODO: GH#30113 } function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) { - var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); - changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ", - // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter - indentation: 0, - leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include - }); + var signature = groupedReferences.signature; + var newFunctionDeclarationParams = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); + if (signature) { + var newSignatureParams = ts.map(createNewParameters(signature, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); + replaceParameters(signature, newSignatureParams); + } + replaceParameters(functionDeclaration, newFunctionDeclarationParams); var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); }); for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) { var call = functionCalls_1[_i]; @@ -147132,6 +151632,15 @@ var ts; changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include }); } } + function replaceParameters(declarationOrSignature, parameterDeclarations) { + changes.replaceNodeRangeWithNodes(sourceFile, ts.first(declarationOrSignature.parameters), ts.last(declarationOrSignature.parameters), parameterDeclarations, { + joiner: ", ", + // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter + indentation: 0, + leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include + }); + } } function getGroupedReferences(functionDeclaration, program, cancellationToken) { var functionNames = getFunctionNames(functionDeclaration); @@ -147150,12 +151659,38 @@ var ts; var functionSymbols = ts.map(functionNames, getSymbolTargetAtLocation); var classSymbols = ts.map(classNames, getSymbolTargetAtLocation); var isConstructor = ts.isConstructorDeclaration(functionDeclaration); + var contextualSymbols = ts.map(functionNames, function (name) { return getSymbolForContextualType(name, checker); }); for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) { var entry = referenceEntries_1[_i]; - if (entry.kind !== 1 /* Node */) { + if (entry.kind === 0 /* Span */) { groupedReferences.valid = false; continue; } + /* Declarations in object literals may be implementations of method signatures which have a different symbol from the declaration + For example: + interface IFoo { m(a: number): void } + const foo: IFoo = { m(a: number): void {} } + In these cases we get the symbol for the signature from the contextual type. + */ + if (ts.contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) { + if (isValidMethodSignature(entry.node.parent)) { + groupedReferences.signature = entry.node.parent; + continue; + } + var call = entryToFunctionCall(entry); + if (call) { + groupedReferences.functionCalls.push(call); + continue; + } + } + var contextualSymbol = getSymbolForContextualType(entry.node, checker); + if (contextualSymbol && ts.contains(contextualSymbols, contextualSymbol)) { + var decl = entryToDeclaration(entry); + if (decl) { + groupedReferences.declarations.push(decl); + continue; + } + } /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function. Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test: class A { foo(a: number, b: number) { return a + b; } } @@ -147218,6 +151753,19 @@ var ts; return symbol && ts.getSymbolTarget(symbol, checker); } } + /** + * Gets the symbol for the contextual type of the node if it is not a union or intersection. + */ + function getSymbolForContextualType(node, checker) { + var element = ts.getContainingObjectLiteralElement(node); + if (element) { + var contextualType = checker.getContextualTypeForObjectLiteralElement(element); + var symbol = contextualType === null || contextualType === void 0 ? void 0 : contextualType.getSymbol(); + if (symbol && !(ts.getCheckFlags(symbol) & 6 /* Synthetic */)) { + return symbol; + } + } + } function entryToImportOrExport(entry) { var node = entry.node; if (ts.isImportSpecifier(node.parent) @@ -147243,15 +151791,15 @@ var ts; var parent = functionReference.parent; switch (parent.kind) { // foo(...) or super(...) or new Foo(...) - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: var callOrNewExpression = ts.tryCast(parent, ts.isCallOrNewExpression); if (callOrNewExpression && callOrNewExpression.expression === functionReference) { return callOrNewExpression; } break; // x.foo(...) - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression); if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { var callOrNewExpression_1 = ts.tryCast(propertyAccessExpression.parent, ts.isCallOrNewExpression); @@ -147261,7 +151809,7 @@ var ts; } break; // x["foo"](...) - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression); if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { var callOrNewExpression_2 = ts.tryCast(elementAccessExpression.parent, ts.isCallOrNewExpression); @@ -147280,14 +151828,14 @@ var ts; var parent = reference.parent; switch (parent.kind) { // `C.foo` - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression); if (propertyAccessExpression && propertyAccessExpression.expression === reference) { return propertyAccessExpression; } break; // `C["foo"]` - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression); if (elementAccessExpression && elementAccessExpression.expression === reference) { return elementAccessExpression; @@ -147325,15 +151873,24 @@ var ts; } return false; } + function isValidMethodSignature(node) { + return ts.isMethodSignature(node) && (ts.isInterfaceDeclaration(node.parent) || ts.isTypeLiteralNode(node.parent)); + } function isValidFunctionDeclaration(functionDeclaration, checker) { + var _a; if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false; switch (functionDeclaration.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: + if (ts.isObjectLiteralExpression(functionDeclaration.parent)) { + var contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker); + // don't offer the refactor when there are multiple signatures since we won't know which ones the user wants to change + return ((_a = contextualSymbol === null || contextualSymbol === void 0 ? void 0 : contextualSymbol.declarations) === null || _a === void 0 ? void 0 : _a.length) === 1 && isSingleImplementation(functionDeclaration, checker); + } return isSingleImplementation(functionDeclaration, checker); - case 166 /* Constructor */: + case 167 /* Constructor */: if (ts.isClassDeclaration(functionDeclaration.parent)) { return hasNameOrDefault(functionDeclaration.parent) && isSingleImplementation(functionDeclaration, checker); } @@ -147341,8 +151898,8 @@ var ts; return isValidVariableDeclaration(functionDeclaration.parent.parent) && isSingleImplementation(functionDeclaration, checker); } - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return isValidVariableDeclaration(functionDeclaration.parent); } return false; @@ -147492,7 +152049,7 @@ var ts; } function getClassNames(constructorDeclaration) { switch (constructorDeclaration.parent.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: var classDeclaration = constructorDeclaration.parent; if (classDeclaration.name) return [classDeclaration.name]; @@ -147500,7 +152057,7 @@ var ts; // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault` var defaultModifier = ts.Debug.checkDefined(ts.findModifier(classDeclaration, 87 /* DefaultKeyword */), "Nameless class declaration should be a default export"); return [defaultModifier]; - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: var classExpression = constructorDeclaration.parent; var variableDeclaration = constructorDeclaration.parent.parent; var className = classExpression.name; @@ -147511,25 +152068,25 @@ var ts; } function getFunctionNames(functionDeclaration) { switch (functionDeclaration.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: if (functionDeclaration.name) return [functionDeclaration.name]; // If the function declaration doesn't have a name, it should have a default modifier. // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault` var defaultModifier = ts.Debug.checkDefined(ts.findModifier(functionDeclaration, 87 /* DefaultKeyword */), "Nameless function declaration should be a default export"); return [defaultModifier]; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return [functionDeclaration.name]; - case 166 /* Constructor */: + case 167 /* Constructor */: var ctrKeyword = ts.Debug.checkDefined(ts.findChildOfKind(functionDeclaration, 132 /* ConstructorKeyword */, functionDeclaration.getSourceFile()), "Constructor declaration should have constructor keyword"); - if (functionDeclaration.parent.kind === 221 /* ClassExpression */) { + if (functionDeclaration.parent.kind === 222 /* ClassExpression */) { var variableDeclaration = functionDeclaration.parent.parent; return [variableDeclaration.name, ctrKeyword]; } return [ctrKeyword]; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return [functionDeclaration.parent.name]; - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: if (functionDeclaration.name) return [functionDeclaration.name, functionDeclaration.parent.name]; return [functionDeclaration.parent.name]; @@ -147620,11 +152177,11 @@ var ts; function getParentBinaryExpression(expr) { var container = ts.findAncestor(expr.parent, function (n) { switch (n.kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return false; - case 218 /* TemplateExpression */: - case 216 /* BinaryExpression */: + case 219 /* TemplateExpression */: + case 217 /* BinaryExpression */: return !(ts.isBinaryExpression(n.parent) && isNotEqualsOperator(n.parent)); default: return "quit"; @@ -147701,7 +152258,7 @@ var ts; var templateSpans = []; var templateHead = ts.factory.createTemplateHead(headText); copyCommentFromStringLiterals(headIndexes, templateHead); - var _loop_19 = function (i) { + var _loop_20 = function (i) { var currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); copyOperatorComments(i, currentNode); var _c = concatConsecutiveString(i + 1, nodes), newIndex = _c[0], subsequentText = _c[1], stringIndexes = _c[2]; @@ -147725,7 +152282,7 @@ var ts; }; var out_i_1; for (var i = begin; i < nodes.length; i++) { - _loop_19(i); + _loop_20(i); i = out_i_1; } return ts.factory.createTemplateExpression(templateHead, templateSpans); @@ -147925,7 +152482,9 @@ var ts; var body = convertToBlock(func.body); var variableDeclaration = variableInfo.variableDeclaration, variableDeclarationList = variableInfo.variableDeclarationList, statement = variableInfo.statement, name = variableInfo.name; ts.suppressLeadingTrivia(statement); - var newNode = ts.factory.createFunctionDeclaration(func.decorators, statement.modifiers, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); + var modifiersFlags = (ts.getCombinedModifierFlags(variableDeclaration) & 1 /* Export */) | ts.getEffectiveModifierFlags(func); + var modifiers = ts.factory.createModifiersFromModifierFlags(modifiersFlags); + var newNode = ts.factory.createFunctionDeclaration(func.decorators, ts.length(modifiers) ? modifiers : undefined, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); if (variableDeclarationList.declarations.length === 1) { return ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, statement, newNode); }); } @@ -147983,9 +152542,7 @@ var ts; function getEditsForAction(context) { var info = getInfo(context); if (info && !refactor.isRefactorErrorInfo(info)) { - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { - return t.tryInsertTypeAnnotation(context.file, info.declaration, info.returnTypeNode); - }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, t, info.declaration, info.returnTypeNode); }); return { renameFilename: undefined, renameLocation: undefined, edits: edits }; } return undefined; @@ -148010,11 +152567,26 @@ var ts; } return ts.emptyArray; } + function doChange(sourceFile, changes, declaration, typeNode) { + var closeParen = ts.findChildOfKind(declaration, 21 /* CloseParenToken */, sourceFile); + var needParens = ts.isArrowFunction(declaration) && closeParen === undefined; + var endNode = needParens ? ts.first(declaration.parameters) : closeParen; + if (endNode) { + if (needParens) { + changes.insertNodeBefore(sourceFile, endNode, ts.factory.createToken(20 /* OpenParenToken */)); + changes.insertNodeAfter(sourceFile, endNode, ts.factory.createToken(21 /* CloseParenToken */)); + } + changes.insertNodeAt(sourceFile, endNode.end, typeNode, { prefix: ": " }); + } + } function getInfo(context) { if (ts.isInJSFile(context.file) || !refactor.refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind)) return; var token = ts.getTokenAtPosition(context.file, context.startPosition); - var declaration = ts.findAncestor(token, isConvertibleDeclaration); + var declaration = ts.findAncestor(token, function (n) { + return ts.isBlock(n) || n.parent && ts.isArrowFunction(n.parent) && (n.kind === 38 /* EqualsGreaterThanToken */ || n.parent.body === n) ? "quit" : + isConvertibleDeclaration(n); + }); if (!declaration || !declaration.body || declaration.type) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Return_type_must_be_inferred_from_a_function) }; } @@ -148023,7 +152595,6 @@ var ts; if (!returnType) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_determine_function_return_type) }; } - ; var returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, 1 /* NoTruncation */); if (returnTypeNode) { return { declaration: declaration, returnTypeNode: returnTypeNode }; @@ -148031,10 +152602,10 @@ var ts; } function isConvertibleDeclaration(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: return true; default: return false; @@ -148136,8 +152707,8 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 301 /* FirstJSDocNode */ || kid.kind > 333 /* LastJSDocNode */; }); - return child.kind < 157 /* FirstNode */ ? + var child = ts.find(children, function (kid) { return kid.kind < 302 /* FirstJSDocNode */ || kid.kind > 337 /* LastJSDocNode */; }); + return child.kind < 158 /* FirstNode */ ? child : child.getFirstToken(sourceFile); }; @@ -148148,7 +152719,7 @@ var ts; if (!child) { return undefined; } - return child.kind < 157 /* FirstNode */ ? child : child.getLastToken(sourceFile); + return child.kind < 158 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { return ts.forEachChild(this, cbNode, cbNodeArray); @@ -148206,11 +152777,11 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(334 /* SyntaxList */, nodes.pos, nodes.end, parent); + var list = createNode(338 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { - var node = nodes_1[_i]; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; addSyntheticNodes(list._children, pos, node.pos, parent); list._children.push(node); pos = node.end; @@ -148317,13 +152888,13 @@ var ts; }; SymbolObject.prototype.getContextualDocumentationComment = function (context, checker) { switch (context === null || context === void 0 ? void 0 : context.kind) { - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: if (!this.contextualGetAccessorDocumentationComment) { this.contextualGetAccessorDocumentationComment = ts.emptyArray; this.contextualGetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isGetAccessor), checker); } return this.contextualGetAccessorDocumentationComment; - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: if (!this.contextualSetAccessorDocumentationComment) { this.contextualSetAccessorDocumentationComment = ts.emptyArray; this.contextualSetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isSetAccessor), checker); @@ -148333,9 +152904,9 @@ var ts; return this.getDocumentationComment(checker); } }; - SymbolObject.prototype.getJsDocTags = function () { + SymbolObject.prototype.getJsDocTags = function (checker) { if (this.tags === undefined) { - this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations); + this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations, checker); } return this.tags; }; @@ -148496,7 +153067,7 @@ var ts; }; SignatureObject.prototype.getJsDocTags = function () { if (this.jsDocTags === undefined) { - this.jsDocTags = this.declaration ? getJsDocTags([this.declaration], this.checker) : []; + this.jsDocTags = this.declaration ? getJsDocTagsOfSignature(this.declaration, this.checker) : []; } return this.jsDocTags; }; @@ -148510,29 +153081,34 @@ var ts; function hasJSDocInheritDocTag(node) { return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); } - function getJsDocTags(declarations, checker) { - var tags = ts.JsDoc.getJsDocTagsFromDeclarations(declarations); - if (tags.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - ts.forEachUnique(declarations, function (declaration) { - var inheritedTags = findBaseOfDeclaration(checker, declaration, function (symbol) { return symbol.getJsDocTags(); }); - if (inheritedTags) { - tags = __spreadArray(__spreadArray([], inheritedTags), tags); - } - }); + function getJsDocTagsOfSignature(declaration, checker) { + var tags = ts.JsDoc.getJsDocTagsFromDeclarations([declaration], checker); + if (tags.length === 0 || hasJSDocInheritDocTag(declaration)) { + var inheritedTags = findBaseOfDeclaration(checker, declaration, function (symbol) { var _a; return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) === 1 ? symbol.getJsDocTags() : undefined; }); + if (inheritedTags) { + tags = __spreadArray(__spreadArray([], inheritedTags), tags); + } } return tags; } function getDocumentationComment(declarations, checker) { if (!declarations) return ts.emptyArray; - var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); + var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations, checker); if (checker && (doc.length === 0 || declarations.some(hasJSDocInheritDocTag))) { - ts.forEachUnique(declarations, function (declaration) { - var inheritedDocs = findBaseOfDeclaration(checker, declaration, function (symbol) { return symbol.getDocumentationComment(checker); }); + var seenSymbols_1 = new ts.Set(); + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; + var inheritedDocs = findBaseOfDeclaration(checker, declaration, function (symbol) { + if (!seenSymbols_1.has(symbol)) { + seenSymbols_1.add(symbol); + return symbol.getDocumentationComment(checker); + } + }); // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); - }); + } } return doc; } @@ -148546,7 +153122,7 @@ var ts; __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { var _this = _super.call(this, kind, pos, end) || this; - _this.kind = 297 /* SourceFile */; + _this.kind = 298 /* SourceFile */; return _this; } SourceFileObject.prototype.update = function (newText, textChangeRange) { @@ -148605,10 +153181,10 @@ var ts; } function visit(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -148628,31 +153204,31 @@ var ts; } ts.forEachChild(node, visit); break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: - case 256 /* ModuleDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 270 /* ExportSpecifier */: - case 265 /* ImportSpecifier */: - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 177 /* TypeLiteral */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 257 /* ModuleDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 271 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 178 /* TypeLiteral */: addDeclaration(node); ts.forEachChild(node, visit); break; - case 160 /* Parameter */: + case 161 /* Parameter */: // Only consider parameter properties - if (!ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) { + if (!ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { break; } // falls through - case 249 /* VariableDeclaration */: - case 198 /* BindingElement */: { + case 250 /* VariableDeclaration */: + case 199 /* BindingElement */: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -148663,12 +153239,12 @@ var ts; } } // falls through - case 291 /* EnumMember */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 292 /* EnumMember */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: addDeclaration(node); break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; var exportDeclaration = node; @@ -148681,7 +153257,7 @@ var ts; } } break; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -148693,7 +153269,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 263 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 264 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -148702,7 +153278,7 @@ var ts; } } break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } @@ -148796,15 +153372,7 @@ var ts; var fileName = rootFileNames_1[_i]; this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName)); } - // store the compilation settings - this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); } - HostCache.prototype.compilationSettings = function () { - return this._compilationSettings; - }; - HostCache.prototype.getProjectReferences = function () { - return this.host.getProjectReferences && this.host.getProjectReferences(); - }; HostCache.prototype.createEntry = function (fileName, path) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); @@ -148954,7 +153522,7 @@ var ts; }; CancellationTokenObject.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { - ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "CancellationTokenObject" }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "CancellationTokenObject" }); throw new ts.OperationCanceledException(); } }; @@ -148984,7 +153552,7 @@ var ts; }; ThrottledCancellationToken.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { - ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "ThrottledCancellationToken" }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "ThrottledCancellationToken" }); throw new ts.OperationCanceledException(); } }; @@ -149084,7 +153652,7 @@ var ts; return sourceFile; } function synchronizeHostData() { - var _a, _b; + var _a, _b, _c; ts.Debug.assert(languageServiceMode !== ts.LanguageServiceMode.Syntactic); // perform fast check if host supports it if (host.getProjectVersion) { @@ -149105,11 +153673,22 @@ var ts; // Get a fresh cache of the host information var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); + var newSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; var hasChangedAutomaticTypeDirectiveNames = ts.maybeBind(host, host.hasChangedAutomaticTypeDirectiveNames); - var projectReferences = hostCache.getProjectReferences(); + var projectReferences = (_b = host.getProjectReferences) === null || _b === void 0 ? void 0 : _b.call(host); + var parsedCommandLines; + var parseConfigHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: readFile, + readDirectory: readDirectory, + trace: ts.maybeBind(host, host.trace), + getCurrentDirectory: function () { return currentDirectory; }, + onUnRecoverableConfigFileDiagnostic: ts.noop, + }; // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (_path, fileName) { return host.getScriptVersion(fileName); }, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { + if (ts.isProgramUptoDate(program, rootFileNames, newSettings, function (_path, fileName) { return host.getScriptVersion(fileName); }, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -149117,7 +153696,6 @@ var ts; // instance. If we cancel midway through, we may end up in an inconsistent state where // the program points to old source files that have been invalidated because of // incremental parsing. - var newSettings = hostCache.compilationSettings(); // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -149139,19 +153717,18 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, - readDirectory: function (path, extensions, exclude, include, depth) { - ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); - return host.readDirectory(path, extensions, exclude, include, depth); - }, + readDirectory: readDirectory, onReleaseOldSourceFile: onReleaseOldSourceFile, + onReleaseParsedCommandLine: onReleaseParsedCommandLine, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: hasChangedAutomaticTypeDirectiveNames, - trace: ts.maybeBind(host, host.trace), + trace: parseConfigHost.trace, resolveModuleNames: ts.maybeBind(host, host.resolveModuleNames), resolveTypeReferenceDirectives: ts.maybeBind(host, host.resolveTypeReferenceDirectives), useSourceOfProjectReferenceRedirect: ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect), + getParsedCommandLine: getParsedCommandLine, }; - (_b = host.setCompilerHost) === null || _b === void 0 ? void 0 : _b.call(host, compilerHost); + (_c = host.setCompilerHost) === null || _c === void 0 ? void 0 : _c.call(host, compilerHost); var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); var options = { rootNames: rootFileNames, @@ -149164,6 +153741,7 @@ var ts; // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. // It needs to be cleared to allow all collected snapshots to be released hostCache = undefined; + parsedCommandLines = undefined; // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during // the course of whatever called `synchronizeHostData` @@ -149172,6 +153750,36 @@ var ts; // pointers set property. program.getTypeChecker(); return; + function getParsedCommandLine(fileName) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var existing = parsedCommandLines === null || parsedCommandLines === void 0 ? void 0 : parsedCommandLines.get(path); + if (existing !== undefined) + return existing || undefined; + var result = host.getParsedCommandLine ? + host.getParsedCommandLine(fileName) : + getParsedCommandLineOfConfigFileUsingSourceFile(fileName); + (parsedCommandLines || (parsedCommandLines = new ts.Map())).set(path, result || false); + return result; + } + function getParsedCommandLineOfConfigFileUsingSourceFile(configFileName) { + var result = getOrCreateSourceFile(configFileName, 100 /* JSON */); + if (!result) + return undefined; + result.path = ts.toPath(configFileName, currentDirectory, getCanonicalFileName); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; + return ts.parseJsonSourceFileConfigFileContent(result, parseConfigHost, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), + /*optionsToExtend*/ undefined, ts.getNormalizedAbsolutePath(configFileName, currentDirectory)); + } + function onReleaseParsedCommandLine(configFileName, oldResolvedRef, oldOptions) { + var _a; + if (host.getParsedCommandLine) { + (_a = host.onReleaseParsedCommandLine) === null || _a === void 0 ? void 0 : _a.call(host, configFileName, oldResolvedRef, oldOptions); + } + else if (oldResolvedRef) { + onReleaseOldSourceFile(oldResolvedRef.sourceFile, oldOptions); + } + } function fileExists(fileName) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = hostCache && hostCache.getEntryByPath(path); @@ -149188,11 +153796,15 @@ var ts; } return host.readFile && host.readFile(fileName); } + function readDirectory(path, extensions, exclude, include, depth) { + ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + } // Release any files we have acquired in the old program but are // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind); } function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); @@ -149237,8 +153849,13 @@ var ts; // We do not support the scenario where a host can modify a registered // file's script kind, i.e. in one project some file is treated as ".ts" // and in another as ".js" - ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind."); - return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + if (hostFileInformation.scriptKind === oldSourceFile.scriptKind) { + return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + } + else { + // Release old source file and fall through to aquire new file with new script kind + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind); + } } // We didn't already have the file. Fall through and acquire it from the registry. } @@ -149267,7 +153884,7 @@ var ts; // Use paths to ensure we are using correct key and paths as document registry could be created with different current directory than host var key_1 = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()); ts.forEach(program.getSourceFiles(), function (f) { - return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1); + return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1, f.scriptKind); }); program = undefined; // TODO: GH#18217 } @@ -149310,10 +153927,10 @@ var ts; synchronizeHostData(); return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter); } - function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { + function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences, data) { if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions, host)), // TODO: GH#18217 + return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source, data: data }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions, host)), // TODO: GH#18217 preferences, cancellationToken); } function getCompletionEntrySymbol(fileName, position, name, source, preferences) { @@ -149340,7 +153957,7 @@ var ts; textSpan: ts.createTextSpanFromNode(nodeForQuickInfo, sourceFile), displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_2, ts.getContainerNode(nodeForQuickInfo)); }), documentation: type_2.symbol ? type_2.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_2.symbol ? type_2.symbol.getJsDocTags() : undefined + tags: type_2.symbol ? type_2.symbol.getJsDocTags(typeChecker) : undefined }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { @@ -149359,19 +153976,23 @@ var ts; if (ts.isNewExpression(node.parent) && node.pos === node.parent.pos) { return node.parent.expression; } + if (ts.isNamedTupleMember(node.parent) && node.pos === node.parent.pos) { + return node.parent; + } return node; } function shouldGetType(sourceFile, node, position) { switch (node.kind) { case 78 /* Identifier */: - return !ts.isLabelName(node) && !ts.isTagName(node); - case 201 /* PropertyAccessExpression */: - case 157 /* QualifiedName */: + return !ts.isLabelName(node) && !ts.isTagName(node) && !ts.isConstTypeReference(node.parent); + case 202 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: // Don't return quickInfo if inside the comment in `a/**/.b` return !ts.isInComment(sourceFile, position); case 107 /* ThisKeyword */: - case 187 /* ThisType */: + case 188 /* ThisType */: case 105 /* SuperKeyword */: + case 193 /* NamedTupleMember */: return true; default: return false; @@ -149476,15 +154097,15 @@ var ts; return undefined; } switch (node.kind) { - case 201 /* PropertyAccessExpression */: - case 157 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: case 10 /* StringLiteral */: case 94 /* FalseKeyword */: case 109 /* TrueKeyword */: case 103 /* NullKeyword */: case 105 /* SuperKeyword */: case 107 /* ThisKeyword */: - case 187 /* ThisType */: + case 188 /* ThisType */: case 78 /* Identifier */: break; // Cant create the text span @@ -149501,7 +154122,7 @@ var ts; // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module - if (nodeForStartPos.parent.parent.kind === 256 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 257 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -149529,15 +154150,7 @@ var ts; function getNavigationTree(fileName) { return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); } - function isTsOrTsxFile(fileName) { - var kind = ts.getScriptKind(fileName, host); - return kind === 3 /* TS */ || kind === 4 /* TSX */; - } function getSemanticClassifications(fileName, span, format) { - if (!isTsOrTsxFile(fileName)) { - // do not run semantic classification on non-ts-or-tsx files - return []; - } synchronizeHostData(); var responseFormat = format || "original" /* Original */; if (responseFormat === "2020" /* TwentyTwenty */) { @@ -149548,10 +154161,6 @@ var ts; } } function getEncodedSemanticClassifications(fileName, span, format) { - if (!isTsOrTsxFile(fileName)) { - // do not run semantic classification on non-ts-or-tsx files - return { spans: [], endOfLineState: 0 /* None */ }; - } synchronizeHostData(); var responseFormat = format || "original" /* Original */; if (responseFormat === "original" /* Original */) { @@ -149642,13 +154251,13 @@ var ts; var formatContext = ts.formatting.getFormatContext(formatOptions, host); return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } - function organizeImports(scope, formatOptions, preferences) { + function organizeImports(args, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); - ts.Debug.assert(scope.type === "file"); - var sourceFile = getValidSourceFile(scope.fileName); + ts.Debug.assert(args.type === "file"); + var sourceFile = getValidSourceFile(args.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions, host); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, args.skipDestructiveCodeActions); } function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } @@ -149665,8 +154274,8 @@ var ts; ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); } - function getDocCommentTemplateAtPosition(fileName, position) { - return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); + function getDocCommentTemplateAtPosition(fileName, position, options) { + return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position, options); } function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too @@ -150081,6 +154690,16 @@ var ts; var file = getValidSourceFile(fileName); return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName); } + function toLineColumnOffset(fileName, position) { + // Go to Definition supports returning a zero-length span at position 0 for + // non-existent files. We need to special-case the conversion of position 0 + // to avoid a crash trying to get the text for that file, since this function + // otherwise assumes that 'fileName' is the name of a file that exists. + if (position === 0) { + return { line: 0, character: 0 }; + } + return sourceMapper.toLineColumnOffset(fileName, position); + } function prepareCallHierarchy(fileName, position) { synchronizeHostData(); var declarations = ts.CallHierarchy.resolveCallHierarchyDeclaration(program, ts.getTouchingPropertyName(getValidSourceFile(fileName), position)); @@ -150153,7 +154772,7 @@ var ts; getAutoImportProvider: getAutoImportProvider, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, - toLineColumnOffset: sourceMapper.toLineColumnOffset, + toLineColumnOffset: toLineColumnOffset, getSourceMapper: function () { return sourceMapper; }, clearSourceMapperCache: function () { return sourceMapper.clearCache(); }, prepareCallHierarchy: prepareCallHierarchy, @@ -150224,7 +154843,7 @@ var ts; */ function literalIsName(node) { return ts.isDeclarationName(node) || - node.parent.kind === 272 /* ExternalModuleReference */ || + node.parent.kind === 273 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } @@ -150242,13 +154861,13 @@ var ts; case 10 /* StringLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: - if (node.parent.kind === 158 /* ComputedPropertyName */) { + if (node.parent.kind === 159 /* ComputedPropertyName */) { return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through case 78 /* Identifier */: return ts.isObjectLiteralElement(node.parent) && - (node.parent.parent.kind === 200 /* ObjectLiteralExpression */ || node.parent.parent.kind === 281 /* JsxAttributes */) && + (node.parent.parent.kind === 201 /* ObjectLiteralExpression */ || node.parent.parent.kind === 282 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } return undefined; @@ -150290,7 +154909,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 202 /* ElementAccessExpression */ && + node.parent.kind === 203 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /** @@ -150370,114 +154989,114 @@ var ts; if (node) { var parent = node.parent; switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 249 /* VariableDeclaration */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 250 /* VariableDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return spanInVariableDeclaration(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return spanInParameterDeclaration(node); - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 166 /* Constructor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 167 /* Constructor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 230 /* Block */: + case 231 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // falls through - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return spanInBlock(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return spanInBlock(node.block); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: // Span on while(...) return textSpanEndingAtNextToken(node, node.expression); - case 235 /* DoStatement */: + case 236 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 248 /* DebuggerStatement */: + case 249 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 234 /* IfStatement */: + case 235 /* IfStatement */: // set on if(..) span return textSpanEndingAtNextToken(node, node.expression); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return spanInForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: // span of for (a in ...) return textSpanEndingAtNextToken(node, node.expression); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: // span in initializer return spanInInitializerOfForLike(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: // span on switch(...) return textSpanEndingAtNextToken(node, node.expression); - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 247 /* TryStatement */: + case 248 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } // falls through - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: - case 198 /* BindingElement */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: + case 199 /* BindingElement */: // span on complete node return textSpan(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: // span in statement return spanInNode(node.statement); - case 161 /* Decorator */: + case 162 /* Decorator */: return spanInNodeArray(parent.decorators); - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return undefined; // Tokens: case 26 /* SemicolonToken */: @@ -150507,7 +155126,7 @@ var ts; case 82 /* CatchKeyword */: case 95 /* FinallyKeyword */: return spanInNextNode(node); - case 156 /* OfKeyword */: + case 157 /* OfKeyword */: return spanInOfKeyword(node); default: // Destructuring pattern in destructuring assignment @@ -150520,13 +155139,13 @@ var ts; // `a` or `...c` or `d: x` from // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern if ((node.kind === 78 /* Identifier */ || - node.kind === 220 /* SpreadElement */ || - node.kind === 288 /* PropertyAssignment */ || - node.kind === 289 /* ShorthandPropertyAssignment */) && + node.kind === 221 /* SpreadElement */ || + node.kind === 289 /* PropertyAssignment */ || + node.kind === 290 /* ShorthandPropertyAssignment */) && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { return textSpan(node); } - if (node.kind === 216 /* BinaryExpression */) { + if (node.kind === 217 /* BinaryExpression */) { var _a = node, left = _a.left, operatorToken = _a.operatorToken; // Set breakpoint in destructuring pattern if its destructuring assignment // [a, b, c] or {a, b, c} of @@ -150548,22 +155167,22 @@ var ts; } if (ts.isExpressionNode(node)) { switch (parent.kind) { - case 235 /* DoStatement */: + case 236 /* DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); - case 161 /* Decorator */: + case 162 /* Decorator */: // Set breakpoint on the decorator emit return spanInNode(node.parent); - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: return textSpan(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (node.parent.operatorToken.kind === 27 /* CommaToken */) { // If this is a comma expression, the breakpoint is possible in this expression return textSpan(node); } break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: if (node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); @@ -150572,21 +155191,21 @@ var ts; } } switch (node.parent.kind) { - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // If this is name of property assignment, set breakpoint in the initializer if (node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } break; - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: // Breakpoint in type assertion goes to its operand if (node.parent.type === node) { return spanInNextNode(node.parent.type); } break; - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: { + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: { // initializer of variable/parameter declaration go to previous node var _b = node.parent, initializer = _b.initializer, type = _b.type; if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { @@ -150594,7 +155213,7 @@ var ts; } break; } - case 216 /* BinaryExpression */: { + case 217 /* BinaryExpression */: { var left = node.parent.left; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { // If initializer of destructuring assignment move to previous token @@ -150624,7 +155243,7 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 238 /* ForInStatement */) { + if (variableDeclaration.parent.parent.kind === 239 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } var parent = variableDeclaration.parent; @@ -150636,7 +155255,7 @@ var ts; // or its declaration from 'for of' if (variableDeclaration.initializer || ts.hasSyntacticModifier(variableDeclaration, 1 /* Export */) || - parent.parent.kind === 239 /* ForOfStatement */) { + parent.parent.kind === 240 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } if (ts.isVariableDeclarationList(variableDeclaration.parent) && @@ -150677,7 +155296,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasSyntacticModifier(functionDeclaration, 1 /* Export */) || - (functionDeclaration.parent.kind === 252 /* ClassDeclaration */ && functionDeclaration.kind !== 166 /* Constructor */); + (functionDeclaration.parent.kind === 253 /* ClassDeclaration */ && functionDeclaration.kind !== 167 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -150700,26 +155319,26 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // Set on parent if on same line otherwise on first statement // falls through - case 236 /* WhileStatement */: - case 234 /* IfStatement */: - case 238 /* ForInStatement */: + case 237 /* WhileStatement */: + case 235 /* IfStatement */: + case 239 /* ForInStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); // Set span on previous token if it starts on same line otherwise on the first statement of the block - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement return spanInNode(block.statements[0]); } function spanInInitializerOfForLike(forLikeStatement) { - if (forLikeStatement.initializer.kind === 250 /* VariableDeclarationList */) { + if (forLikeStatement.initializer.kind === 251 /* VariableDeclarationList */) { // Declaration list - set breakpoint in first declaration var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -150744,21 +155363,21 @@ var ts; } function spanInBindingPattern(bindingPattern) { // Set breakpoint in first binding element - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 222 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 223 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } // Empty binding pattern of binding element, set breakpoint on binding element - if (bindingPattern.parent.kind === 198 /* BindingElement */) { + if (bindingPattern.parent.kind === 199 /* BindingElement */) { return textSpan(bindingPattern.parent); } // Variable declaration is used as the span return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 197 /* ArrayBindingPattern */ && node.kind !== 196 /* ObjectBindingPattern */); - var elements = node.kind === 199 /* ArrayLiteralExpression */ ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 222 /* OmittedExpression */ ? element : undefined; }); + ts.Debug.assert(node.kind !== 198 /* ArrayBindingPattern */ && node.kind !== 197 /* ObjectBindingPattern */); + var elements = node.kind === 200 /* ArrayLiteralExpression */ ? node.elements : node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 223 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -150766,18 +155385,18 @@ var ts; // just nested element in another destructuring assignment // set breakpoint on assignment when parent is destructuring assignment // Otherwise set breakpoint for this element - return textSpan(node.parent.kind === 216 /* BinaryExpression */ ? node.parent : node); + return textSpan(node.parent.kind === 217 /* BinaryExpression */ ? node.parent : node); } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -150785,25 +155404,25 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: // If this is not an instantiated module block, no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } // falls through - case 255 /* EnumDeclaration */: - case 252 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 253 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 230 /* Block */: + case 231 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // falls through - case 287 /* CatchClause */: + case 288 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -150811,7 +155430,7 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 196 /* ObjectBindingPattern */: + case 197 /* ObjectBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -150827,7 +155446,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -150842,12 +155461,12 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 235 /* DoStatement */ || // Go to while keyword and do action instead - node.parent.kind === 203 /* CallExpression */ || - node.parent.kind === 204 /* NewExpression */) { + if (node.parent.kind === 236 /* DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 204 /* CallExpression */ || + node.parent.kind === 205 /* NewExpression */) { return spanInPreviousNode(node); } - if (node.parent.kind === 207 /* ParenthesizedExpression */) { + if (node.parent.kind === 208 /* ParenthesizedExpression */) { return spanInNextNode(node); } // Default to parent node @@ -150856,21 +155475,21 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 166 /* Constructor */: - case 236 /* WhileStatement */: - case 235 /* DoStatement */: - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 207 /* ParenthesizedExpression */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 167 /* Constructor */: + case 237 /* WhileStatement */: + case 236 /* DoStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 208 /* ParenthesizedExpression */: return spanInPreviousNode(node); // Default to parent node default: @@ -150880,20 +155499,20 @@ var ts; function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration if (ts.isFunctionLike(node.parent) || - node.parent.kind === 288 /* PropertyAssignment */ || - node.parent.kind === 160 /* Parameter */) { + node.parent.kind === 289 /* PropertyAssignment */ || + node.parent.kind === 161 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 206 /* TypeAssertionExpression */) { + if (node.parent.kind === 207 /* TypeAssertionExpression */) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 235 /* DoStatement */) { + if (node.parent.kind === 236 /* DoStatement */) { // Set span on while expression return textSpanEndingAtNextToken(node, node.parent.expression); } @@ -150901,7 +155520,7 @@ var ts; return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 239 /* ForOfStatement */) { + if (node.parent.kind === 240 /* ForOfStatement */) { // Set using next token return spanInNextNode(node); } @@ -151442,11 +156061,11 @@ var ts; return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); }); }; /** Get a string based representation of a completion list entry details */ - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences, data) { var _this = this; return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions); - return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences, data); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { @@ -151470,9 +156089,9 @@ var ts; return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); }); }; - LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { + LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); }); + return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position, options); }); }; /// NAVIGATE TO /** Return a list of symbols that are interesting to navigate to */ @@ -152612,7 +157231,7 @@ var ts; }, factoryDeprecation); /** @deprecated Use `factory.createJSDocParameterTag` or the factory supplied by your transformation context instead. */ ts.createJSDocParamTag = ts.Debug.deprecate(function createJSDocParamTag(name, isBracketed, typeExpression, comment) { - return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, isBracketed, typeExpression, /*isNameFirst*/ false, comment); + return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, isBracketed, typeExpression, /*isNameFirst*/ false, comment ? ts.factory.createNodeArray([ts.factory.createJSDocText(comment)]) : undefined); }, factoryDeprecation); /** @deprecated Use `factory.createComma` or the factory supplied by your transformation context instead. */ ts.createComma = ts.Debug.deprecate(function createComma(left, right) { @@ -152662,7 +157281,7 @@ var ts; ts.createNode = ts.Debug.deprecate(function createNode(kind, pos, end) { if (pos === void 0) { pos = 0; } if (end === void 0) { end = 0; } - return ts.setTextRangePosEnd(kind === 297 /* SourceFile */ ? ts.parseBaseNodeFactory.createBaseSourceFileNode(kind) : + return ts.setTextRangePosEnd(kind === 298 /* SourceFile */ ? ts.parseBaseNodeFactory.createBaseSourceFileNode(kind) : kind === 78 /* Identifier */ ? ts.parseBaseNodeFactory.createBaseIdentifierNode(kind) : kind === 79 /* PrivateIdentifier */ ? ts.parseBaseNodeFactory.createBasePrivateIdentifierNode(kind) : !ts.isNodeKind(kind) ? ts.parseBaseNodeFactory.createBaseTokenNode(kind) : @@ -152691,13 +157310,30 @@ var ts; // #region Renamed node Tests /** @deprecated Use `isTypeAssertionExpression` instead. */ ts.isTypeAssertion = ts.Debug.deprecate(function isTypeAssertion(node) { - return node.kind === 206 /* TypeAssertionExpression */; + return node.kind === 207 /* TypeAssertionExpression */; }, { since: "4.0", warnAfter: "4.1", message: "Use `isTypeAssertionExpression` instead." }); // #endregion + // DEPRECATION: Renamed node tests + // DEPRECATION PLAN: + // - soft: 4.2 + // - warn: 4.3 + // - error: TBD + // #region Renamed node Tests + /** + * @deprecated Use `isMemberName` instead. + */ + ts.isIdentifierOrPrivateIdentifier = ts.Debug.deprecate(function isIdentifierOrPrivateIdentifier(node) { + return ts.isMemberName(node); + }, { + since: "4.2", + warnAfter: "4.3", + message: "Use `isMemberName` instead." + }); + // #endregion Renamed node Tests })(ts || (ts = {})); diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 1050818279ea0..2d44d601a4731 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 = "4.2"; + const versionMajorMinor = "4.3"; /** The version of the TypeScript compiler release */ const version: string; /** @@ -260,192 +260,196 @@ declare namespace ts { FromKeyword = 153, GlobalKeyword = 154, BigIntKeyword = 155, - OfKeyword = 156, - QualifiedName = 157, - ComputedPropertyName = 158, - TypeParameter = 159, - Parameter = 160, - Decorator = 161, - PropertySignature = 162, - PropertyDeclaration = 163, - MethodSignature = 164, - MethodDeclaration = 165, - Constructor = 166, - GetAccessor = 167, - SetAccessor = 168, - CallSignature = 169, - ConstructSignature = 170, - IndexSignature = 171, - TypePredicate = 172, - TypeReference = 173, - FunctionType = 174, - ConstructorType = 175, - TypeQuery = 176, - TypeLiteral = 177, - ArrayType = 178, - TupleType = 179, - OptionalType = 180, - RestType = 181, - UnionType = 182, - IntersectionType = 183, - ConditionalType = 184, - InferType = 185, - ParenthesizedType = 186, - ThisType = 187, - TypeOperator = 188, - IndexedAccessType = 189, - MappedType = 190, - LiteralType = 191, - NamedTupleMember = 192, - TemplateLiteralType = 193, - TemplateLiteralTypeSpan = 194, - ImportType = 195, - ObjectBindingPattern = 196, - ArrayBindingPattern = 197, - BindingElement = 198, - ArrayLiteralExpression = 199, - ObjectLiteralExpression = 200, - PropertyAccessExpression = 201, - ElementAccessExpression = 202, - CallExpression = 203, - NewExpression = 204, - TaggedTemplateExpression = 205, - TypeAssertionExpression = 206, - ParenthesizedExpression = 207, - FunctionExpression = 208, - ArrowFunction = 209, - DeleteExpression = 210, - TypeOfExpression = 211, - VoidExpression = 212, - AwaitExpression = 213, - PrefixUnaryExpression = 214, - PostfixUnaryExpression = 215, - BinaryExpression = 216, - ConditionalExpression = 217, - TemplateExpression = 218, - YieldExpression = 219, - SpreadElement = 220, - ClassExpression = 221, - OmittedExpression = 222, - ExpressionWithTypeArguments = 223, - AsExpression = 224, - NonNullExpression = 225, - MetaProperty = 226, - SyntheticExpression = 227, - TemplateSpan = 228, - SemicolonClassElement = 229, - Block = 230, - EmptyStatement = 231, - VariableStatement = 232, - ExpressionStatement = 233, - IfStatement = 234, - DoStatement = 235, - WhileStatement = 236, - ForStatement = 237, - ForInStatement = 238, - ForOfStatement = 239, - ContinueStatement = 240, - BreakStatement = 241, - ReturnStatement = 242, - WithStatement = 243, - SwitchStatement = 244, - LabeledStatement = 245, - ThrowStatement = 246, - TryStatement = 247, - DebuggerStatement = 248, - VariableDeclaration = 249, - VariableDeclarationList = 250, - FunctionDeclaration = 251, - ClassDeclaration = 252, - InterfaceDeclaration = 253, - TypeAliasDeclaration = 254, - EnumDeclaration = 255, - ModuleDeclaration = 256, - ModuleBlock = 257, - CaseBlock = 258, - NamespaceExportDeclaration = 259, - ImportEqualsDeclaration = 260, - ImportDeclaration = 261, - ImportClause = 262, - NamespaceImport = 263, - NamedImports = 264, - ImportSpecifier = 265, - ExportAssignment = 266, - ExportDeclaration = 267, - NamedExports = 268, - NamespaceExport = 269, - ExportSpecifier = 270, - MissingDeclaration = 271, - ExternalModuleReference = 272, - JsxElement = 273, - JsxSelfClosingElement = 274, - JsxOpeningElement = 275, - JsxClosingElement = 276, - JsxFragment = 277, - JsxOpeningFragment = 278, - JsxClosingFragment = 279, - JsxAttribute = 280, - JsxAttributes = 281, - JsxSpreadAttribute = 282, - JsxExpression = 283, - CaseClause = 284, - DefaultClause = 285, - HeritageClause = 286, - CatchClause = 287, - PropertyAssignment = 288, - ShorthandPropertyAssignment = 289, - SpreadAssignment = 290, - EnumMember = 291, - UnparsedPrologue = 292, - UnparsedPrepend = 293, - UnparsedText = 294, - UnparsedInternalText = 295, - UnparsedSyntheticReference = 296, - SourceFile = 297, - Bundle = 298, - UnparsedSource = 299, - InputFiles = 300, - JSDocTypeExpression = 301, - JSDocNameReference = 302, - JSDocAllType = 303, - JSDocUnknownType = 304, - JSDocNullableType = 305, - JSDocNonNullableType = 306, - JSDocOptionalType = 307, - JSDocFunctionType = 308, - JSDocVariadicType = 309, - JSDocNamepathType = 310, - JSDocComment = 311, - JSDocTypeLiteral = 312, - JSDocSignature = 313, - JSDocTag = 314, - JSDocAugmentsTag = 315, - JSDocImplementsTag = 316, - JSDocAuthorTag = 317, - JSDocDeprecatedTag = 318, - JSDocClassTag = 319, - JSDocPublicTag = 320, - JSDocPrivateTag = 321, - JSDocProtectedTag = 322, - JSDocReadonlyTag = 323, - JSDocCallbackTag = 324, - JSDocEnumTag = 325, - JSDocParameterTag = 326, - JSDocReturnTag = 327, - JSDocThisTag = 328, - JSDocTypeTag = 329, - JSDocTemplateTag = 330, - JSDocTypedefTag = 331, - JSDocSeeTag = 332, - JSDocPropertyTag = 333, - SyntaxList = 334, - NotEmittedStatement = 335, - PartiallyEmittedExpression = 336, - CommaListExpression = 337, - MergeDeclarationMarker = 338, - EndOfDeclarationMarker = 339, - SyntheticReferenceExpression = 340, - Count = 341, + OverrideKeyword = 156, + OfKeyword = 157, + QualifiedName = 158, + ComputedPropertyName = 159, + TypeParameter = 160, + Parameter = 161, + Decorator = 162, + PropertySignature = 163, + PropertyDeclaration = 164, + MethodSignature = 165, + MethodDeclaration = 166, + Constructor = 167, + GetAccessor = 168, + SetAccessor = 169, + CallSignature = 170, + ConstructSignature = 171, + IndexSignature = 172, + TypePredicate = 173, + TypeReference = 174, + FunctionType = 175, + ConstructorType = 176, + TypeQuery = 177, + TypeLiteral = 178, + ArrayType = 179, + TupleType = 180, + OptionalType = 181, + RestType = 182, + UnionType = 183, + IntersectionType = 184, + ConditionalType = 185, + InferType = 186, + ParenthesizedType = 187, + ThisType = 188, + TypeOperator = 189, + IndexedAccessType = 190, + MappedType = 191, + LiteralType = 192, + NamedTupleMember = 193, + TemplateLiteralType = 194, + TemplateLiteralTypeSpan = 195, + ImportType = 196, + ObjectBindingPattern = 197, + ArrayBindingPattern = 198, + BindingElement = 199, + ArrayLiteralExpression = 200, + ObjectLiteralExpression = 201, + PropertyAccessExpression = 202, + ElementAccessExpression = 203, + CallExpression = 204, + NewExpression = 205, + TaggedTemplateExpression = 206, + TypeAssertionExpression = 207, + ParenthesizedExpression = 208, + FunctionExpression = 209, + ArrowFunction = 210, + DeleteExpression = 211, + TypeOfExpression = 212, + VoidExpression = 213, + AwaitExpression = 214, + PrefixUnaryExpression = 215, + PostfixUnaryExpression = 216, + BinaryExpression = 217, + ConditionalExpression = 218, + TemplateExpression = 219, + YieldExpression = 220, + SpreadElement = 221, + ClassExpression = 222, + OmittedExpression = 223, + ExpressionWithTypeArguments = 224, + AsExpression = 225, + NonNullExpression = 226, + MetaProperty = 227, + SyntheticExpression = 228, + TemplateSpan = 229, + SemicolonClassElement = 230, + Block = 231, + EmptyStatement = 232, + VariableStatement = 233, + ExpressionStatement = 234, + IfStatement = 235, + DoStatement = 236, + WhileStatement = 237, + ForStatement = 238, + ForInStatement = 239, + ForOfStatement = 240, + ContinueStatement = 241, + BreakStatement = 242, + ReturnStatement = 243, + WithStatement = 244, + SwitchStatement = 245, + LabeledStatement = 246, + ThrowStatement = 247, + TryStatement = 248, + DebuggerStatement = 249, + VariableDeclaration = 250, + VariableDeclarationList = 251, + FunctionDeclaration = 252, + ClassDeclaration = 253, + InterfaceDeclaration = 254, + TypeAliasDeclaration = 255, + EnumDeclaration = 256, + ModuleDeclaration = 257, + ModuleBlock = 258, + CaseBlock = 259, + NamespaceExportDeclaration = 260, + ImportEqualsDeclaration = 261, + ImportDeclaration = 262, + ImportClause = 263, + NamespaceImport = 264, + NamedImports = 265, + ImportSpecifier = 266, + ExportAssignment = 267, + ExportDeclaration = 268, + NamedExports = 269, + NamespaceExport = 270, + ExportSpecifier = 271, + MissingDeclaration = 272, + ExternalModuleReference = 273, + JsxElement = 274, + JsxSelfClosingElement = 275, + JsxOpeningElement = 276, + JsxClosingElement = 277, + JsxFragment = 278, + JsxOpeningFragment = 279, + JsxClosingFragment = 280, + JsxAttribute = 281, + JsxAttributes = 282, + JsxSpreadAttribute = 283, + JsxExpression = 284, + CaseClause = 285, + DefaultClause = 286, + HeritageClause = 287, + CatchClause = 288, + PropertyAssignment = 289, + ShorthandPropertyAssignment = 290, + SpreadAssignment = 291, + EnumMember = 292, + UnparsedPrologue = 293, + UnparsedPrepend = 294, + UnparsedText = 295, + UnparsedInternalText = 296, + UnparsedSyntheticReference = 297, + SourceFile = 298, + Bundle = 299, + UnparsedSource = 300, + InputFiles = 301, + JSDocTypeExpression = 302, + JSDocNameReference = 303, + JSDocAllType = 304, + JSDocUnknownType = 305, + JSDocNullableType = 306, + JSDocNonNullableType = 307, + JSDocOptionalType = 308, + JSDocFunctionType = 309, + JSDocVariadicType = 310, + JSDocNamepathType = 311, + JSDocComment = 312, + JSDocText = 313, + JSDocTypeLiteral = 314, + JSDocSignature = 315, + JSDocLink = 316, + JSDocTag = 317, + JSDocAugmentsTag = 318, + JSDocImplementsTag = 319, + JSDocAuthorTag = 320, + JSDocDeprecatedTag = 321, + JSDocClassTag = 322, + JSDocPublicTag = 323, + JSDocPrivateTag = 324, + JSDocProtectedTag = 325, + JSDocReadonlyTag = 326, + JSDocOverrideTag = 327, + JSDocCallbackTag = 328, + JSDocEnumTag = 329, + JSDocParameterTag = 330, + JSDocReturnTag = 331, + JSDocThisTag = 332, + JSDocTypeTag = 333, + JSDocTemplateTag = 334, + JSDocTypedefTag = 335, + JSDocSeeTag = 336, + JSDocPropertyTag = 337, + SyntaxList = 338, + NotEmittedStatement = 339, + PartiallyEmittedExpression = 340, + CommaListExpression = 341, + MergeDeclarationMarker = 342, + EndOfDeclarationMarker = 343, + SyntheticReferenceExpression = 344, + Count = 345, FirstAssignment = 62, LastAssignment = 77, FirstCompoundAssignment = 63, @@ -453,15 +457,15 @@ declare namespace ts { FirstReservedWord = 80, LastReservedWord = 115, FirstKeyword = 80, - LastKeyword = 156, + LastKeyword = 157, FirstFutureReservedWord = 116, LastFutureReservedWord = 124, - FirstTypeNode = 172, - LastTypeNode = 195, + FirstTypeNode = 173, + LastTypeNode = 196, FirstPunctuation = 18, LastPunctuation = 77, FirstToken = 0, - LastToken = 156, + LastToken = 157, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, @@ -470,20 +474,20 @@ declare namespace ts { LastTemplateToken = 17, FirstBinaryOperator = 29, LastBinaryOperator = 77, - FirstStatement = 232, - LastStatement = 248, - FirstNode = 157, - FirstJSDocNode = 301, - LastJSDocNode = 333, - FirstJSDocTagNode = 314, - LastJSDocTagNode = 333, + FirstStatement = 233, + LastStatement = 249, + FirstNode = 158, + FirstJSDocNode = 302, + LastJSDocNode = 337, + FirstJSDocTagNode = 317, + LastJSDocTagNode = 337, } export type TriviaSyntaxKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; export type LiteralSyntaxKind = SyntaxKind.NumericLiteral | SyntaxKind.BigIntLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral; export type PseudoLiteralSyntaxKind = SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle | SyntaxKind.TemplateTail; export type PunctuationSyntaxKind = SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.CloseParenToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.DotToken | SyntaxKind.DotDotDotToken | SyntaxKind.SemicolonToken | SyntaxKind.CommaToken | SyntaxKind.QuestionDotToken | SyntaxKind.LessThanToken | SyntaxKind.LessThanSlashToken | SyntaxKind.GreaterThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.EqualsEqualsToken | SyntaxKind.ExclamationEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.EqualsGreaterThanToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.AsteriskToken | SyntaxKind.AsteriskAsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken | SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken | SyntaxKind.ExclamationToken | SyntaxKind.TildeToken | SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken | SyntaxKind.QuestionQuestionToken | SyntaxKind.QuestionToken | SyntaxKind.ColonToken | SyntaxKind.AtToken | SyntaxKind.BacktickToken | SyntaxKind.EqualsToken | SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken; - export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | 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.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | 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; - export type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.StaticKeyword; + export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | 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.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | 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; + export type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword; export type KeywordTypeSyntaxKind = SyntaxKind.AnyKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VoidKeyword; export type TokenSyntaxKind = SyntaxKind.Unknown | SyntaxKind.EndOfFileToken | TriviaSyntaxKind | LiteralSyntaxKind | PseudoLiteralSyntaxKind | PunctuationSyntaxKind | SyntaxKind.Identifier | KeywordSyntaxKind; export type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; @@ -533,13 +537,14 @@ declare namespace ts { Const = 2048, HasComputedJSDocModifiers = 4096, Deprecated = 8192, + Override = 16384, HasComputedFlags = 536870912, AccessibilityModifier = 28, - ParameterPropertyModifier = 92, + ParameterPropertyModifier = 16476, NonPublicAccessibilityModifier = 24, - TypeScriptModifier = 2270, + TypeScriptModifier = 18654, ExportDefault = 513, - All = 11263 + All = 27647 } export enum JsxFlags { None = 0, @@ -558,7 +563,7 @@ declare namespace ts { } export interface JSDocContainer { } - export type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | NamespaceExportDeclaration | ExportAssignment | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | NamedTupleMember | EndOfFileToken; + export type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | EmptyStatement | DebuggerStatement | Block | VariableStatement | ExpressionStatement | IfStatement | DoStatement | WhileStatement | ForStatement | ForInStatement | ForOfStatement | BreakStatement | ContinueStatement | ReturnStatement | WithStatement | SwitchStatement | LabeledStatement | ThrowStatement | TryStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | VariableDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | NamespaceExportDeclaration | ExportAssignment | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | NamedTupleMember | EndOfFileToken; export type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; export type HasTypeArguments = CallExpression | NewExpression | TaggedTemplateExpression | JsxOpeningElement | JsxSelfClosingElement; export type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; @@ -603,10 +608,11 @@ declare namespace ts { export type ProtectedKeyword = ModifierToken; export type PublicKeyword = ModifierToken; export type ReadonlyKeyword = ModifierToken; + export type OverrideKeyword = ModifierToken; export type StaticKeyword = ModifierToken; /** @deprecated Use `ReadonlyKeyword` instead. */ export type ReadonlyToken = ReadonlyKeyword; - export type Modifier = AbstractKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | ReadonlyKeyword | StaticKeyword; + export type Modifier = AbstractKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | OverrideKeyword | ReadonlyKeyword | StaticKeyword; export type AccessibilityModifier = PublicKeyword | PrivateKeyword | ProtectedKeyword; export type ParameterPropertyModifier = AccessibilityModifier | ReadonlyKeyword; export type ClassMemberModifier = AccessibilityModifier | ReadonlyKeyword | StaticKeyword; @@ -638,6 +644,7 @@ declare namespace ts { } export type EntityName = Identifier | QualifiedName; export type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | PrivateIdentifier; + export type MemberName = Identifier | PrivateIdentifier; export type DeclarationName = Identifier | PrivateIdentifier | StringLiteralLike | NumericLiteral | ComputedPropertyName | ElementAccessExpression | BindingPattern | EntityNameExpression; export interface Declaration extends Node { _declarationBrand: any; @@ -686,7 +693,7 @@ declare namespace ts { readonly kind: SyntaxKind.ConstructSignature; } export type BindingName = Identifier | BindingPattern; - export interface VariableDeclaration extends NamedDeclaration { + export interface VariableDeclaration extends NamedDeclaration, JSDocContainer { readonly kind: SyntaxKind.VariableDeclaration; readonly parent: VariableDeclarationList | CatchClause; readonly name: BindingName; @@ -820,15 +827,15 @@ declare namespace ts { readonly kind: SyntaxKind.SemicolonClassElement; readonly parent: ClassLikeDeclaration; } - export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.GetAccessor; - readonly parent: ClassLikeDeclaration | ObjectLiteralExpression; + readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; readonly name: PropertyName; readonly body?: FunctionBody; } - export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.SetAccessor; - readonly parent: ClassLikeDeclaration | ObjectLiteralExpression; + readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; readonly name: PropertyName; readonly body?: FunctionBody; } @@ -1216,11 +1223,11 @@ declare namespace ts { readonly kind: SyntaxKind.PropertyAccessExpression; readonly expression: LeftHandSideExpression; readonly questionDotToken?: QuestionDotToken; - readonly name: Identifier | PrivateIdentifier; + readonly name: MemberName; } export interface PropertyAccessChain extends PropertyAccessExpression { _optionalChainBrand: any; - readonly name: Identifier | PrivateIdentifier; + readonly name: MemberName; } export interface SuperPropertyAccessExpression extends PropertyAccessExpression { readonly expression: SuperExpression; @@ -1373,7 +1380,7 @@ declare namespace ts { readonly containsOnlyTriviaWhiteSpaces: boolean; } export type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; - export interface Statement extends Node { + export interface Statement extends Node, JSDocContainer { _statementBrand: any; } export interface NotEmittedStatement extends Statement { @@ -1401,11 +1408,11 @@ declare namespace ts { readonly kind: SyntaxKind.Block; readonly statements: NodeArray; } - export interface VariableStatement extends Statement, JSDocContainer { + export interface VariableStatement extends Statement { readonly kind: SyntaxKind.VariableStatement; readonly declarationList: VariableDeclarationList; } - export interface ExpressionStatement extends Statement, JSDocContainer { + export interface ExpressionStatement extends Statement { readonly kind: SyntaxKind.ExpressionStatement; readonly expression: Expression; } @@ -1486,7 +1493,7 @@ declare namespace ts { readonly statements: NodeArray; } export type CaseOrDefaultClause = CaseClause | DefaultClause; - export interface LabeledStatement extends Statement, JSDocContainer { + export interface LabeledStatement extends Statement { readonly kind: SyntaxKind.LabeledStatement; readonly label: Identifier; readonly statement: Statement; @@ -1606,7 +1613,7 @@ declare namespace ts { readonly parent: ImportEqualsDeclaration; readonly expression: Expression; } - export interface ImportDeclaration extends Statement, JSDocContainer { + export interface ImportDeclaration extends Statement { readonly kind: SyntaxKind.ImportDeclaration; readonly parent: SourceFile | ModuleBlock; readonly importClause?: ImportClause; @@ -1742,12 +1749,21 @@ declare namespace ts { readonly kind: SyntaxKind.JSDocComment; readonly parent: HasJSDoc; readonly tags?: NodeArray; - readonly comment?: string; + readonly comment?: string | NodeArray; } export interface JSDocTag extends Node { readonly parent: JSDoc | JSDocTypeLiteral; readonly tagName: Identifier; - readonly comment?: string; + readonly comment?: string | NodeArray; + } + export interface JSDocLink extends Node { + readonly kind: SyntaxKind.JSDocLink; + readonly name?: EntityName; + text: string; + } + export interface JSDocText extends Node { + readonly kind: SyntaxKind.JSDocText; + text: string; } export interface JSDocUnknownTag extends JSDocTag { readonly kind: SyntaxKind.JSDocTag; @@ -1789,6 +1805,9 @@ declare namespace ts { export interface JSDocReadonlyTag extends JSDocTag { readonly kind: SyntaxKind.JSDocReadonlyTag; } + export interface JSDocOverrideTag extends JSDocTag { + readonly kind: SyntaxKind.JSDocOverrideTag; + } export interface JSDocEnumTag extends JSDocTag, Declaration { readonly kind: SyntaxKind.JSDocEnumTag; readonly parent: JSDoc; @@ -2080,7 +2099,6 @@ declare namespace ts { * Gets a type checker that can be used to semantically analyze source files in the program. */ getTypeChecker(): TypeChecker; - getTypeCatalog(): readonly Type[]; getNodeCount(): number; getIdentifierCount(): number; getSymbolCount(): number; @@ -2186,7 +2204,7 @@ declare namespace ts { * The function returns the value (local variable) symbol of an identifier in the short-hand property assignment. * This is necessary as an identifier in short-hand property assignment can contains two meaning: property name and property value. */ - getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getShorthandAssignmentValueSymbol(location: Node | undefined): Symbol | undefined; getExportSpecifierLocalTargetSymbol(location: ExportSpecifier | Identifier): Symbol | undefined; /** * If a symbol is a local symbol with an associated exported symbol, returns the exported symbol. @@ -2261,6 +2279,8 @@ declare namespace ts { NoTypeReduction = 536870912, NoUndefinedOptionalParameterType = 1073741824, AllowThisInObjectLiteral = 32768, + AllowQualifiedNameInPlaceOfIdentifier = 65536, + /** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */ AllowQualifedNameInPlaceOfIdentifier = 65536, AllowAnonymousIdentifier = 131072, AllowEmptyUnionOrIntersection = 262144, @@ -2271,8 +2291,7 @@ declare namespace ts { IgnoreErrors = 70221824, InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, - InInitialEntityName = 16777216, - InReverseMappedType = 33554432 + InInitialEntityName = 16777216 } export enum TypeFormatFlags { None = 0, @@ -2405,8 +2424,8 @@ declare namespace ts { export interface Symbol { flags: SymbolFlags; escapedName: __String; - declarations: Declaration[]; - valueDeclaration: Declaration; + declarations?: Declaration[]; + valueDeclaration?: Declaration; members?: SymbolTable; exports?: SymbolTable; globalExports?: SymbolTable; @@ -2540,15 +2559,15 @@ declare namespace ts { ObjectLiteral = 128, EvolvingArray = 256, ObjectLiteralPatternWithComputedProperties = 512, - ContainsSpread = 1024, - ReverseMapped = 2048, - JsxAttributes = 4096, - MarkerType = 8192, - JSLiteral = 16384, - FreshLiteral = 32768, - ArrayLiteral = 65536, - ObjectRestType = 131072, + ReverseMapped = 1024, + JsxAttributes = 2048, + MarkerType = 4096, + JSLiteral = 8192, + FreshLiteral = 16384, + ArrayLiteral = 32768, ClassOrInterface = 3, + ContainsSpread = 4194304, + ObjectRestType = 8388608, } export interface ObjectType extends Type { objectFlags: ObjectFlags; @@ -2656,14 +2675,13 @@ declare namespace ts { export interface TemplateLiteralType extends InstantiableType { texts: readonly string[]; types: readonly Type[]; - freshType: TemplateLiteralType; - regularType: TemplateLiteralType; } export interface StringMappingType extends InstantiableType { symbol: Symbol; type: Type; } export interface SubstitutionType extends InstantiableType { + objectFlags: ObjectFlags; baseType: Type; substitute: Type; } @@ -2688,16 +2706,17 @@ declare namespace ts { export enum InferencePriority { NakedTypeVariable = 1, SpeculativeTuple = 2, - HomomorphicMappedType = 4, - PartialHomomorphicMappedType = 8, - MappedTypeConstraint = 16, - ContravariantConditional = 32, - ReturnType = 64, - LiteralKeyof = 128, - NoConstraints = 256, - AlwaysStrict = 512, - MaxValue = 1024, - PriorityImpliesCombination = 208, + SubstituteSource = 4, + HomomorphicMappedType = 8, + PartialHomomorphicMappedType = 16, + MappedTypeConstraint = 32, + ContravariantConditional = 64, + ReturnType = 128, + LiteralKeyof = 256, + NoConstraints = 512, + AlwaysStrict = 1024, + MaxValue = 2048, + PriorityImpliesCombination = 416, Circularity = -1 } /** @deprecated Use FileExtensionInfo instead. */ @@ -2774,18 +2793,21 @@ declare namespace ts { FixedPollingInterval = 0, PriorityPollingInterval = 1, DynamicPriorityPolling = 2, - UseFsEvents = 3, - UseFsEventsOnParentDirectory = 4 + FixedChunkSizePolling = 3, + UseFsEvents = 4, + UseFsEventsOnParentDirectory = 5 } export enum WatchDirectoryKind { UseFsEvents = 0, FixedPollingInterval = 1, - DynamicPriorityPolling = 2 + DynamicPriorityPolling = 2, + FixedChunkSizePolling = 3 } export enum PollingWatchKind { FixedInterval = 0, PriorityInterval = 1, - DynamicPriority = 2 + DynamicPriority = 2, + FixedChunkSize = 3 } export type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; export interface CompilerOptions { @@ -2847,6 +2869,7 @@ declare namespace ts { outFile?: string; paths?: MapLike; preserveConstEnums?: boolean; + noImplicitOverride?: boolean; preserveSymlinks?: boolean; project?: string; reactNamespace?: string; @@ -2957,6 +2980,7 @@ declare namespace ts { ES2018 = 5, ES2019 = 6, ES2020 = 7, + ES2021 = 8, ESNext = 99, JSON = 100, Latest = 99 @@ -3130,17 +3154,21 @@ declare namespace ts { Iterator = 8388608, NoAsciiEscaping = 16777216, } - export interface EmitHelper { + export interface EmitHelperBase { readonly name: string; readonly scoped: boolean; readonly text: string | ((node: EmitHelperUniqueNameCallback) => string); readonly priority?: number; readonly dependencies?: EmitHelper[]; } - export interface UnscopedEmitHelper extends EmitHelper { + export interface ScopedEmitHelper extends EmitHelperBase { + readonly scoped: true; + } + export interface UnscopedEmitHelper extends EmitHelperBase { readonly scoped: false; readonly text: string; } + export type EmitHelper = ScopedEmitHelper | UnscopedEmitHelper; export type EmitHelperUniqueNameCallback = (name: string) => string; export enum EmitHint { SourceFile = 0, @@ -3168,14 +3196,27 @@ declare namespace ts { createStringLiteralFromNode(sourceNode: PropertyNameLiteral, isSingleQuote?: boolean): StringLiteral; createRegularExpressionLiteral(text: string): RegularExpressionLiteral; createIdentifier(text: string): Identifier; - /** Create a unique temporary variable. */ - createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; - /** Create a unique temporary variable for use in a loop. */ - createLoopVariable(): Identifier; + /** + * Create a unique temporary variable. + * @param recordTempVariable An optional callback used to record the temporary variable name. This + * should usually be a reference to `hoistVariableDeclaration` from a `TransformationContext`, but + * can be `undefined` if you plan to record the temporary variable manually. + * @param reservedInNestedScopes When `true`, reserves the temporary variable name in all nested scopes + * during emit so that the variable can be referenced in a nested function body. This is an alternative to + * setting `EmitFlags.ReuseTempVariableScope` on the nested function itself. + */ + createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, reservedInNestedScopes?: boolean): Identifier; + /** + * Create a unique temporary variable for use in a loop. + * @param reservedInNestedScopes When `true`, reserves the temporary variable name in all nested scopes + * during emit so that the variable can be referenced in a nested function body. This is an alternative to + * setting `EmitFlags.ReuseTempVariableScope` on the nested function itself. + */ + createLoopVariable(reservedInNestedScopes?: boolean): Identifier; /** Create a unique name based on the supplied text. */ createUniqueName(text: string, flags?: GeneratedIdentifierFlags): Identifier; /** Create a unique name generated for a node. */ - getGeneratedNameForNode(node: Node | undefined): Identifier; + getGeneratedNameForNode(node: Node | undefined, flags?: GeneratedIdentifierFlags): Identifier; createPrivateIdentifier(text: string): PrivateIdentifier; createToken(token: SyntaxKind.SuperKeyword): SuperExpression; createToken(token: SyntaxKind.ThisKeyword): ThisExpression; @@ -3286,10 +3327,10 @@ declare namespace ts { updateArrayLiteralExpression(node: ArrayLiteralExpression, elements: readonly Expression[]): ArrayLiteralExpression; createObjectLiteralExpression(properties?: readonly ObjectLiteralElementLike[], multiLine?: boolean): ObjectLiteralExpression; updateObjectLiteralExpression(node: ObjectLiteralExpression, properties: readonly ObjectLiteralElementLike[]): ObjectLiteralExpression; - createPropertyAccessExpression(expression: Expression, name: string | Identifier | PrivateIdentifier): PropertyAccessExpression; - updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: Identifier | PrivateIdentifier): PropertyAccessExpression; - createPropertyAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | Identifier | PrivateIdentifier): PropertyAccessChain; - updatePropertyAccessChain(node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: Identifier | PrivateIdentifier): PropertyAccessChain; + createPropertyAccessExpression(expression: Expression, name: string | MemberName): PropertyAccessExpression; + updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: MemberName): PropertyAccessExpression; + createPropertyAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | MemberName): PropertyAccessChain; + updatePropertyAccessChain(node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: MemberName): PropertyAccessChain; createElementAccessExpression(expression: Expression, index: number | Expression): ElementAccessExpression; updateElementAccessExpression(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; createElementAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, index: number | Expression): ElementAccessChain; @@ -3457,52 +3498,58 @@ declare namespace ts { updateJSDocTypeExpression(node: JSDocTypeExpression, type: TypeNode): JSDocTypeExpression; createJSDocNameReference(name: EntityName): JSDocNameReference; updateJSDocNameReference(node: JSDocNameReference, name: EntityName): JSDocNameReference; + createJSDocLink(name: EntityName | undefined, text: string): JSDocLink; + updateJSDocLink(node: JSDocLink, name: EntityName | undefined, text: string): JSDocLink; createJSDocTypeLiteral(jsDocPropertyTags?: readonly JSDocPropertyLikeTag[], isArrayType?: boolean): JSDocTypeLiteral; updateJSDocTypeLiteral(node: JSDocTypeLiteral, jsDocPropertyTags: readonly JSDocPropertyLikeTag[] | undefined, isArrayType: boolean | undefined): JSDocTypeLiteral; createJSDocSignature(typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag): JSDocSignature; updateJSDocSignature(node: JSDocSignature, typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type: JSDocReturnTag | undefined): JSDocSignature; - createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string): JSDocTemplateTag; - updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | undefined): JSDocTemplateTag; - createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string): JSDocTypedefTag; - updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | undefined): JSDocTypedefTag; - createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string): JSDocParameterTag; - updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | undefined): JSDocParameterTag; - createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string): JSDocPropertyTag; - updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | undefined): JSDocPropertyTag; - createJSDocTypeTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string): JSDocTypeTag; - updateJSDocTypeTag(node: JSDocTypeTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | undefined): JSDocTypeTag; - createJSDocSeeTag(tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string): JSDocSeeTag; - updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string): JSDocSeeTag; - createJSDocReturnTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string): JSDocReturnTag; - updateJSDocReturnTag(node: JSDocReturnTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | undefined): JSDocReturnTag; - createJSDocThisTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string): JSDocThisTag; - updateJSDocThisTag(node: JSDocThisTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | undefined): JSDocThisTag; - createJSDocEnumTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string): JSDocEnumTag; - updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | undefined): JSDocEnumTag; - createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string): JSDocCallbackTag; - updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | undefined): JSDocCallbackTag; - createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string): JSDocAugmentsTag; - updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment: string | undefined): JSDocAugmentsTag; - createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string): JSDocImplementsTag; - updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment: string | undefined): JSDocImplementsTag; - createJSDocAuthorTag(tagName: Identifier | undefined, comment?: string): JSDocAuthorTag; - updateJSDocAuthorTag(node: JSDocAuthorTag, tagName: Identifier | undefined, comment: string | undefined): JSDocAuthorTag; - createJSDocClassTag(tagName: Identifier | undefined, comment?: string): JSDocClassTag; - updateJSDocClassTag(node: JSDocClassTag, tagName: Identifier | undefined, comment: string | undefined): JSDocClassTag; - createJSDocPublicTag(tagName: Identifier | undefined, comment?: string): JSDocPublicTag; - updateJSDocPublicTag(node: JSDocPublicTag, tagName: Identifier | undefined, comment: string | undefined): JSDocPublicTag; - createJSDocPrivateTag(tagName: Identifier | undefined, comment?: string): JSDocPrivateTag; - updateJSDocPrivateTag(node: JSDocPrivateTag, tagName: Identifier | undefined, comment: string | undefined): JSDocPrivateTag; - createJSDocProtectedTag(tagName: Identifier | undefined, comment?: string): JSDocProtectedTag; - updateJSDocProtectedTag(node: JSDocProtectedTag, tagName: Identifier | undefined, comment: string | undefined): JSDocProtectedTag; - createJSDocReadonlyTag(tagName: Identifier | undefined, comment?: string): JSDocReadonlyTag; - updateJSDocReadonlyTag(node: JSDocReadonlyTag, tagName: Identifier | undefined, comment: string | undefined): JSDocReadonlyTag; - createJSDocUnknownTag(tagName: Identifier, comment?: string): JSDocUnknownTag; - updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | undefined): JSDocUnknownTag; - createJSDocDeprecatedTag(tagName: Identifier, comment?: string): JSDocDeprecatedTag; - updateJSDocDeprecatedTag(node: JSDocDeprecatedTag, tagName: Identifier, comment?: string): JSDocDeprecatedTag; - createJSDocComment(comment?: string | undefined, tags?: readonly JSDocTag[] | undefined): JSDoc; - updateJSDocComment(node: JSDoc, comment: string | undefined, tags: readonly JSDocTag[] | undefined): JSDoc; + createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray): JSDocTemplateTag; + updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | NodeArray | undefined): JSDocTemplateTag; + createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocTypedefTag; + updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocTypedefTag; + createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocParameterTag; + updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocParameterTag; + createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocPropertyTag; + updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocPropertyTag; + createJSDocTypeTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocTypeTag; + updateJSDocTypeTag(node: JSDocTypeTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined): JSDocTypeTag; + createJSDocSeeTag(tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag; + updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag; + createJSDocReturnTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray): JSDocReturnTag; + updateJSDocReturnTag(node: JSDocReturnTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined): JSDocReturnTag; + createJSDocThisTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocThisTag; + updateJSDocThisTag(node: JSDocThisTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined): JSDocThisTag; + createJSDocEnumTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocEnumTag; + updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined): JSDocEnumTag; + createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocCallbackTag; + updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocCallbackTag; + createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string | NodeArray): JSDocAugmentsTag; + updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment: string | NodeArray | undefined): JSDocAugmentsTag; + createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string | NodeArray): JSDocImplementsTag; + updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment: string | NodeArray | undefined): JSDocImplementsTag; + createJSDocAuthorTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocAuthorTag; + updateJSDocAuthorTag(node: JSDocAuthorTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocAuthorTag; + createJSDocClassTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocClassTag; + updateJSDocClassTag(node: JSDocClassTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocClassTag; + createJSDocPublicTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocPublicTag; + updateJSDocPublicTag(node: JSDocPublicTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocPublicTag; + createJSDocPrivateTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocPrivateTag; + updateJSDocPrivateTag(node: JSDocPrivateTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocPrivateTag; + createJSDocProtectedTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocProtectedTag; + updateJSDocProtectedTag(node: JSDocProtectedTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocProtectedTag; + createJSDocReadonlyTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocReadonlyTag; + updateJSDocReadonlyTag(node: JSDocReadonlyTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocReadonlyTag; + createJSDocUnknownTag(tagName: Identifier, comment?: string | NodeArray): JSDocUnknownTag; + updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | NodeArray | undefined): JSDocUnknownTag; + createJSDocDeprecatedTag(tagName: Identifier, comment?: string | NodeArray): JSDocDeprecatedTag; + updateJSDocDeprecatedTag(node: JSDocDeprecatedTag, tagName: Identifier, comment?: string | NodeArray): JSDocDeprecatedTag; + createJSDocOverrideTag(tagName: Identifier, comment?: string | NodeArray): JSDocOverrideTag; + updateJSDocOverrideTag(node: JSDocOverrideTag, tagName: Identifier, comment?: string | NodeArray): JSDocOverrideTag; + createJSDocText(text: string): JSDocText; + updateJSDocText(node: JSDocText, text: string): JSDocText; + createJSDocComment(comment?: string | NodeArray | undefined, tags?: readonly JSDocTag[] | undefined): JSDoc; + updateJSDocComment(node: JSDoc, comment: string | NodeArray | undefined, tags: readonly JSDocTag[] | undefined): JSDoc; createJsxElement(openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement; updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement; createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxSelfClosingElement; @@ -3750,12 +3797,12 @@ declare namespace ts { * }); * ``` */ - onEmitNode?(hint: EmitHint, node: Node | undefined, emitCallback: (hint: EmitHint, node: Node | undefined) => void): void; + onEmitNode?(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; /** * A hook used to check if an emit notification is required for a node. * @param node The node to emit. */ - isEmitNotificationEnabled?(node: Node | undefined): boolean; + isEmitNotificationEnabled?(node: Node): boolean; /** * A hook used by the Printer to perform just-in-time substitution of a node. This is * primarily used by node transformations that need to substitute one node for another, @@ -3869,6 +3916,8 @@ declare namespace ts { readonly disableSuggestions?: boolean; readonly quotePreference?: "auto" | "double" | "single"; readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsForImportStatements?: boolean; + readonly includeCompletionsWithSnippetText?: boolean; readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; @@ -3967,9 +4016,10 @@ declare namespace ts { scanJsxIdentifier(): SyntaxKind; scanJsxAttributeValue(): SyntaxKind; reScanJsxAttributeValue(): SyntaxKind; - reScanJsxToken(): JsxTokenSyntaxKind; + reScanJsxToken(allowMultilineJsxText?: boolean): JsxTokenSyntaxKind; reScanLessThanToken(): SyntaxKind; reScanQuestionToken(): SyntaxKind; + reScanInvalidIdentifier(): SyntaxKind; scanJsxToken(): JsxTokenSyntaxKind; scanJsDocToken(): JSDocSyntaxKind; scan(): SyntaxKind; @@ -4101,7 +4151,7 @@ declare namespace ts { function idText(identifierOrPrivateName: Identifier | PrivateIdentifier): string; function symbolName(symbol: Symbol): string; function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | PrivateIdentifier | undefined; - function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined; + function getNameOfDeclaration(declaration: Declaration | Expression | undefined): DeclarationName | undefined; /** * Gets the JSDoc parameter tags for the node if present. * @@ -4147,6 +4197,7 @@ declare namespace ts { function getJSDocProtectedTag(node: Node): JSDocProtectedTag | undefined; /** Gets the JSDoc protected tag for the node if present */ function getJSDocReadonlyTag(node: Node): JSDocReadonlyTag | undefined; + function getJSDocOverrideTagNoCache(node: Node): JSDocOverrideTag | undefined; /** Gets the JSDoc deprecated tag for the node if present */ function getJSDocDeprecatedTag(node: Node): JSDocDeprecatedTag | undefined; /** Gets the JSDoc enum tag for the node if present */ @@ -4184,13 +4235,15 @@ declare namespace ts { function getAllJSDocTags(node: Node, predicate: (tag: JSDocTag) => tag is T): readonly T[]; /** Gets all JSDoc tags of a specified kind */ function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): readonly JSDocTag[]; + /** Gets the text of a jsdoc comment, flattening links to their text. */ + function getTextOfJSDocComment(comment?: string | NodeArray): string | undefined; /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. */ function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): readonly TypeParameterDeclaration[]; function getEffectiveConstraintOfTypeParameter(node: TypeParameterDeclaration): TypeNode | undefined; - function isIdentifierOrPrivateIdentifier(node: Node): node is Identifier | PrivateIdentifier; + function isMemberName(node: Node): node is MemberName; function isPropertyAccessChain(node: Node): node is PropertyAccessChain; function isElementAccessChain(node: Node): node is ElementAccessChain; function isCallChain(node: Node): node is CallChain; @@ -4205,6 +4258,12 @@ declare namespace ts { function isUnparsedTextLike(node: Node): node is UnparsedTextLike; function isUnparsedNode(node: Node): node is UnparsedNode; function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag; + /** + * True if kind is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + function isTokenKind(kind: SyntaxKind): boolean; /** * True if node is of some token syntax kind. * For example, this is true for an IfKeyword but not for an IfStatement. @@ -4221,7 +4280,7 @@ declare namespace ts { function isEntityName(node: Node): node is EntityName; function isPropertyName(node: Node): node is PropertyName; function isBindingName(node: Node): node is BindingName; - function isFunctionLike(node: Node): node is SignatureDeclaration; + function isFunctionLike(node: Node | undefined): node is SignatureDeclaration; function isClassElement(node: Node): node is ClassElement; function isClassLike(node: Node): node is ClassLikeDeclaration; function isAccessor(node: Node): node is AccessorDeclaration; @@ -4347,10 +4406,14 @@ declare namespace ts { function isTemplateHead(node: Node): node is TemplateHead; function isTemplateMiddle(node: Node): node is TemplateMiddle; function isTemplateTail(node: Node): node is TemplateTail; + function isDotDotDotToken(node: Node): node is DotDotDotToken; + function isPlusToken(node: Node): node is PlusToken; + function isMinusToken(node: Node): node is MinusToken; + function isAsteriskToken(node: Node): node is AsteriskToken; function isIdentifier(node: Node): node is Identifier; + function isPrivateIdentifier(node: Node): node is PrivateIdentifier; function isQualifiedName(node: Node): node is QualifiedName; function isComputedPropertyName(node: Node): node is ComputedPropertyName; - function isPrivateIdentifier(node: Node): node is PrivateIdentifier; function isTypeParameterDeclaration(node: Node): node is TypeParameterDeclaration; function isParameter(node: Node): node is ParameterDeclaration; function isDecorator(node: Node): node is Decorator; @@ -4493,6 +4556,7 @@ declare namespace ts { function isUnparsedSource(node: Node): node is UnparsedSource; function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression; function isJSDocNameReference(node: Node): node is JSDocNameReference; + function isJSDocLink(node: Node): node is JSDocLink; function isJSDocAllType(node: Node): node is JSDocAllType; function isJSDocUnknownType(node: Node): node is JSDocUnknownType; function isJSDocNullableType(node: Node): node is JSDocNullableType; @@ -4512,6 +4576,7 @@ declare namespace ts { function isJSDocPrivateTag(node: Node): node is JSDocPrivateTag; function isJSDocProtectedTag(node: Node): node is JSDocProtectedTag; function isJSDocReadonlyTag(node: Node): node is JSDocReadonlyTag; + function isJSDocOverrideTag(node: Node): node is JSDocOverrideTag; function isJSDocDeprecatedTag(node: Node): node is JSDocDeprecatedTag; function isJSDocSeeTag(node: Node): node is JSDocSeeTag; function isJSDocEnumTag(node: Node): node is JSDocEnumTag; @@ -4576,7 +4641,7 @@ declare namespace ts { /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ - export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): ParsedCommandLine | undefined; + export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions | undefined, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): ParsedCommandLine | undefined; /** * Read tsconfig.json file * @param fileName The path to the config file @@ -4644,13 +4709,13 @@ declare namespace ts { export {}; } declare namespace ts { - function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; + export function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, cache?: TypeReferenceDirectiveResolutionCache): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -4659,30 +4724,46 @@ declare namespace ts { * More type directives might appear in the program later as a result of loading actual source files; * this list is only the set of defaults that are implicitly included. */ - function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + export function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + export interface TypeReferenceDirectiveResolutionCache extends PerDirectoryResolutionCache, PackageJsonInfoCache { + } /** - * Cached module resolutions per containing directory. + * Cached resolutions per containing directory. * This assumes that any module id will have the same resolution for sibling files located in the same folder. */ - interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { - getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + export interface PerDirectoryResolutionCache { + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + clear(): void; + /** + * Updates with the current compilerOptions the cache will operate with. + * This updates the redirects map as well if needed so module resolutions are cached if they can across the projects + */ + update(options: CompilerOptions): void; + } + export interface ModuleResolutionCache extends PerDirectoryResolutionCache, NonRelativeModuleNameResolutionCache, PackageJsonInfoCache { + getPackageJsonInfoCache(): PackageJsonInfoCache; } /** * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. */ - interface NonRelativeModuleNameResolutionCache { + export interface NonRelativeModuleNameResolutionCache extends PackageJsonInfoCache { getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; } - interface PerModuleNameCache { + export interface PackageJsonInfoCache { + clear(): void; + } + export interface PerModuleNameCache { get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; } - function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions): ModuleResolutionCache; - function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions): ModuleResolutionCache; + export function createTypeReferenceDirectiveResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions, packageJsonInfoCache?: PackageJsonInfoCache): TypeReferenceDirectiveResolutionCache; + export function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; + export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export {}; } declare namespace ts { /** @@ -4749,6 +4830,10 @@ declare namespace ts { * environment and merging hoisted declarations upon completion. */ function visitFunctionBody(node: ConciseBody, visitor: Visitor, context: TransformationContext): ConciseBody; + /** + * Visits an iteration body, adding any block-scoped variables required by the transformation. + */ + function visitIterationBody(body: Statement, visitor: Visitor, context: TransformationContext): Statement; /** * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place. * @@ -5037,6 +5122,8 @@ declare namespace ts { interface WatchCompilerHost extends ProgramHost, WatchHost { /** Instead of using output d.ts file from project reference, use its source file */ useSourceOfProjectReferenceRedirect?(): boolean; + /** If provided, use this method to get parsed command lines for referenced projects */ + getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; } @@ -5132,9 +5219,9 @@ declare namespace ts { interface SolutionBuilderWithWatchHost extends SolutionBuilderHostBase, WatchHost { } interface SolutionBuilder { - build(project?: string, cancellationToken?: CancellationToken): ExitStatus; + build(project?: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; clean(project?: string): ExitStatus; - buildReferences(project: string, cancellationToken?: CancellationToken): ExitStatus; + buildReferences(project: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; cleanReferences(project?: string): ExitStatus; getNextInvalidatedProject(cancellationToken?: CancellationToken): InvalidatedProject | undefined; } @@ -5292,7 +5379,7 @@ declare namespace ts { getName(): string; getDeclarations(): Declaration[] | undefined; getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; - getJsDocTags(): JSDocTagInfo[]; + getJsDocTags(checker?: TypeChecker): JSDocTagInfo[]; } interface Type { getFlags(): TypeFlags; @@ -5423,6 +5510,7 @@ declare namespace ts { isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; writeFile?(fileName: string, content: string): void; + getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; } type WithMetadata = T & { metadata?: unknown; @@ -5512,12 +5600,13 @@ declare namespace ts { * * @param fileName The path to the file * @param position A zero based index of the character where you want the entries - * @param entryName The name from an existing completion which came from `getCompletionsAtPosition` + * @param entryName The `name` from an existing completion which came from `getCompletionsAtPosition` * @param formatOptions How should code samples in the completions be formatted, can be undefined for backwards compatibility - * @param source Source code for the current file, can be undefined for backwards compatibility + * @param source `source` property from the completion entry * @param preferences User settings, can be undefined for backwards compatibility + * @param data `data` property from the completion entry */ - getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; + getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined, data: CompletionEntryData | undefined): CompletionEntryDetails | undefined; getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; /** * Gets semantic information about the identifier at a particular position in a @@ -5556,7 +5645,7 @@ declare namespace ts { getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; - getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion | undefined; + getDocCommentTemplateAtPosition(fileName: string, position: number, options?: DocCommentTemplateOptions): TextInsertion | undefined; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; /** * This will return a defined result if the position is after the `>` of the opening tag, or somewhere in the text, of a JSXElement with no closing tag. @@ -5578,7 +5667,7 @@ declare namespace ts { applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise; getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined, triggerReason?: RefactorTriggerReason, kind?: string): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; - organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; + organizeImports(args: OrganizeImportsArgs, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; getProgram(): Program | undefined; @@ -5595,8 +5684,10 @@ declare namespace ts { type: "file"; fileName: string; } - type OrganizeImportsScope = CombinedCodeFixScope; - type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#"; + interface OrganizeImportsArgs extends CombinedCodeFixScope { + skipDestructiveCodeActions?: boolean; + } + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; interface GetCompletionsAtPositionOptions extends UserPreferences { /** * If the editor is asking for completions because a certain character was typed @@ -5948,6 +6039,7 @@ declare namespace ts { name: string; containerKind: ScriptElementKind; containerName: string; + unverified?: boolean; } interface DefinitionInfoAndBoundSpan { definitions?: readonly DefinitionInfo[]; @@ -5982,15 +6074,21 @@ declare namespace ts { typeParameterName = 18, enumMemberName = 19, functionName = 20, - regularExpressionLiteral = 21 + regularExpressionLiteral = 21, + link = 22, + linkName = 23, + linkText = 24 } interface SymbolDisplayPart { text: string; kind: string; } + interface JSDocLinkDisplayPart extends SymbolDisplayPart { + target: DocumentSpan; + } interface JSDocTagInfo { name: string; - text?: string; + text?: SymbolDisplayPart[]; } interface QuickInfo { kind: ScriptElementKind; @@ -6021,11 +6119,15 @@ declare namespace ts { interface RenameInfoOptions { readonly allowRenameOfImportPath?: boolean; } + interface DocCommentTemplateOptions { + readonly generateReturnInDocTemplate?: boolean; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; displayParts: SymbolDisplayPart[]; isOptional: boolean; + isRest?: boolean; } interface SelectionRange { textSpan: TextSpan; @@ -6071,14 +6173,36 @@ declare namespace ts { * true when the current location also allows for a new identifier */ isNewIdentifierLocation: boolean; + /** + * Indicates to client to continue requesting completions on subsequent keystrokes. + */ + isIncomplete?: true; entries: CompletionEntry[]; } + interface CompletionEntryData { + /** The file name declaring the export's module symbol, if it was an external module */ + fileName?: string; + /** The module name (with quotes stripped) of the export's module symbol, if it was an ambient module */ + ambientModuleName?: string; + /** True if the export was found in the package.json AutoImportProvider */ + isPackageJsonImport?: true; + /** + * The name of the property or export in the module's symbol table. Differs from the completion name + * in the case of InternalSymbolName.ExportEquals and InternalSymbolName.Default. + */ + exportName: string; + /** + * Set for auto imports with eagerly resolved module specifiers. + */ + moduleSpecifier?: string; + } interface CompletionEntry { name: string; kind: ScriptElementKind; kindModifiers?: string; sortText: string; insertText?: string; + isSnippet?: true; /** * An optional span that indicates the text to be replaced by this completion item. * If present, this span should be used instead of the default one. @@ -6087,9 +6211,20 @@ declare namespace ts { replacementSpan?: TextSpan; hasAction?: true; source?: string; + sourceDisplay?: SymbolDisplayPart[]; isRecommended?: true; isFromUncheckedFile?: true; isPackageJsonImport?: true; + isImportStatementCompletion?: true; + /** + * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, + * that allows TS Server to look up the symbol represented by the completion item, disambiguating + * items with the same name. Currently only defined for auto-import completions, but the type is + * `unknown` in the protocol, so it can be changed as needed to support other kinds of completions. + * The presence of this property should generally not be used to assume that this completion entry + * is an auto-import. + */ + data?: CompletionEntryData; } interface CompletionEntryDetails { name: string; @@ -6099,7 +6234,9 @@ declare namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; codeActions?: CodeAction[]; + /** @deprecated Use `sourceDisplay` instead. */ source?: SymbolDisplayPart[]; + sourceDisplay?: SymbolDisplayPart[]; } interface OutliningSpan { /** The span of the document to actually collapse. */ @@ -6253,7 +6390,13 @@ declare namespace ts { */ jsxAttribute = "JSX attribute", /** String literal */ - string = "string" + string = "string", + /** Jsdoc @link: in `{@link C link text}`, the before and after text "{@link " and "}" */ + link = "link", + /** Jsdoc @link: in `{@link C link text}`, the entity name "C" */ + linkName = "link name", + /** Jsdoc @link: in `{@link C link text}`, the link text "link text" */ + linkText = "link text" } enum ScriptElementKindModifier { none = "", @@ -6394,8 +6537,23 @@ declare namespace ts { * @param fileName The name of the file to be released * @param compilationSettings The compilation settings used to acquire the file */ + /**@deprecated pass scriptKind for correctness */ releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + /** + * Informs the DocumentRegistry that a file is not needed any longer. + * + * Note: It is not allowed to call release on a SourceFile that was not acquired from + * this registry originally. + * + * @param fileName The name of the file to be released + * @param compilationSettings The compilation settings used to acquire the file + * @param scriptKind The script kind of the file to be released + */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind: ScriptKind): void; + /** + * @deprecated pass scriptKind for correctness */ releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind: ScriptKind): void; reportStats(): string; } type DocumentRegistryBucketKey = string & { @@ -6466,7 +6624,7 @@ declare namespace ts { /** @deprecated Use `factory.createRegularExpressionLiteral` or the factory supplied by your transformation context instead. */ const createRegularExpressionLiteral: (text: string) => RegularExpressionLiteral; /** @deprecated Use `factory.createLoopVariable` or the factory supplied by your transformation context instead. */ - const createLoopVariable: () => Identifier; + const createLoopVariable: (reservedInNestedScopes?: boolean | undefined) => Identifier; /** @deprecated Use `factory.createUniqueName` or the factory supplied by your transformation context instead. */ const createUniqueName: (text: string, flags?: GeneratedIdentifierFlags | undefined) => Identifier; /** @deprecated Use `factory.createPrivateIdentifier` or the factory supplied by your transformation context instead. */ @@ -6638,13 +6796,13 @@ declare namespace ts { /** @deprecated Use `factory.updateObjectLiteralExpression` or the factory supplied by your transformation context instead. */ const updateObjectLiteral: (node: ObjectLiteralExpression, properties: readonly ObjectLiteralElementLike[]) => ObjectLiteralExpression; /** @deprecated Use `factory.createPropertyAccessExpression` or the factory supplied by your transformation context instead. */ - const createPropertyAccess: (expression: Expression, name: string | Identifier | PrivateIdentifier) => PropertyAccessExpression; + const createPropertyAccess: (expression: Expression, name: string | MemberName) => PropertyAccessExpression; /** @deprecated Use `factory.updatePropertyAccessExpression` or the factory supplied by your transformation context instead. */ - const updatePropertyAccess: (node: PropertyAccessExpression, expression: Expression, name: Identifier | PrivateIdentifier) => PropertyAccessExpression; + const updatePropertyAccess: (node: PropertyAccessExpression, expression: Expression, name: MemberName) => PropertyAccessExpression; /** @deprecated Use `factory.createPropertyAccessChain` or the factory supplied by your transformation context instead. */ - const createPropertyAccessChain: (expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | Identifier | PrivateIdentifier) => PropertyAccessChain; + const createPropertyAccessChain: (expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | MemberName) => PropertyAccessChain; /** @deprecated Use `factory.updatePropertyAccessChain` or the factory supplied by your transformation context instead. */ - const updatePropertyAccessChain: (node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: Identifier | PrivateIdentifier) => PropertyAccessChain; + const updatePropertyAccessChain: (node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: MemberName) => PropertyAccessChain; /** @deprecated Use `factory.createElementAccessExpression` or the factory supplied by your transformation context instead. */ const createElementAccess: (expression: Expression, index: number | Expression) => ElementAccessExpression; /** @deprecated Use `factory.updateElementAccessExpression` or the factory supplied by your transformation context instead. */ @@ -6914,51 +7072,51 @@ declare namespace ts { /** @deprecated Use `factory.createJSDocTypeExpression` or the factory supplied by your transformation context instead. */ const createJSDocTypeExpression: (type: TypeNode) => JSDocTypeExpression; /** @deprecated Use `factory.createJSDocTypeTag` or the factory supplied by your transformation context instead. */ - const createJSDocTypeTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | undefined) => JSDocTypeTag; + const createJSDocTypeTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray | undefined) => JSDocTypeTag; /** @deprecated Use `factory.createJSDocReturnTag` or the factory supplied by your transformation context instead. */ - const createJSDocReturnTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | undefined, comment?: string | undefined) => JSDocReturnTag; + const createJSDocReturnTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | undefined, comment?: string | NodeArray | undefined) => JSDocReturnTag; /** @deprecated Use `factory.createJSDocThisTag` or the factory supplied by your transformation context instead. */ - const createJSDocThisTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | undefined) => JSDocThisTag; + const createJSDocThisTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray | undefined) => JSDocThisTag; /** @deprecated Use `factory.createJSDocComment` or the factory supplied by your transformation context instead. */ - const createJSDocComment: (comment?: string | undefined, tags?: readonly JSDocTag[] | undefined) => JSDoc; + const createJSDocComment: (comment?: string | NodeArray | undefined, tags?: readonly JSDocTag[] | undefined) => JSDoc; /** @deprecated Use `factory.createJSDocParameterTag` or the factory supplied by your transformation context instead. */ - const createJSDocParameterTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | undefined) => JSDocParameterTag; + const createJSDocParameterTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | NodeArray | undefined) => JSDocParameterTag; /** @deprecated Use `factory.createJSDocClassTag` or the factory supplied by your transformation context instead. */ - const createJSDocClassTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocClassTag; + const createJSDocClassTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocClassTag; /** @deprecated Use `factory.createJSDocAugmentsTag` or the factory supplied by your transformation context instead. */ const createJSDocAugmentsTag: (tagName: Identifier | undefined, className: ExpressionWithTypeArguments & { readonly expression: Identifier | PropertyAccessEntityNameExpression; - }, comment?: string | undefined) => JSDocAugmentsTag; + }, comment?: string | NodeArray | undefined) => JSDocAugmentsTag; /** @deprecated Use `factory.createJSDocEnumTag` or the factory supplied by your transformation context instead. */ - const createJSDocEnumTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | undefined) => JSDocEnumTag; + const createJSDocEnumTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray | undefined) => JSDocEnumTag; /** @deprecated Use `factory.createJSDocTemplateTag` or the factory supplied by your transformation context instead. */ - const createJSDocTemplateTag: (tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | undefined) => JSDocTemplateTag; + const createJSDocTemplateTag: (tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray | undefined) => JSDocTemplateTag; /** @deprecated Use `factory.createJSDocTypedefTag` or the factory supplied by your transformation context instead. */ - const createJSDocTypedefTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeLiteral | JSDocTypeExpression | undefined, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | undefined) => JSDocTypedefTag; + const createJSDocTypedefTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeLiteral | JSDocTypeExpression | undefined, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | NodeArray | undefined) => JSDocTypedefTag; /** @deprecated Use `factory.createJSDocCallbackTag` or the factory supplied by your transformation context instead. */ - const createJSDocCallbackTag: (tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | undefined) => JSDocCallbackTag; + const createJSDocCallbackTag: (tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | NodeArray | undefined) => JSDocCallbackTag; /** @deprecated Use `factory.createJSDocSignature` or the factory supplied by your transformation context instead. */ const createJSDocSignature: (typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag | undefined) => JSDocSignature; /** @deprecated Use `factory.createJSDocPropertyTag` or the factory supplied by your transformation context instead. */ - const createJSDocPropertyTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | undefined) => JSDocPropertyTag; + const createJSDocPropertyTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | NodeArray | undefined) => JSDocPropertyTag; /** @deprecated Use `factory.createJSDocTypeLiteral` or the factory supplied by your transformation context instead. */ const createJSDocTypeLiteral: (jsDocPropertyTags?: readonly JSDocPropertyLikeTag[] | undefined, isArrayType?: boolean | undefined) => JSDocTypeLiteral; /** @deprecated Use `factory.createJSDocImplementsTag` or the factory supplied by your transformation context instead. */ const createJSDocImplementsTag: (tagName: Identifier | undefined, className: ExpressionWithTypeArguments & { readonly expression: Identifier | PropertyAccessEntityNameExpression; - }, comment?: string | undefined) => JSDocImplementsTag; + }, comment?: string | NodeArray | undefined) => JSDocImplementsTag; /** @deprecated Use `factory.createJSDocAuthorTag` or the factory supplied by your transformation context instead. */ - const createJSDocAuthorTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocAuthorTag; + const createJSDocAuthorTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocAuthorTag; /** @deprecated Use `factory.createJSDocPublicTag` or the factory supplied by your transformation context instead. */ - const createJSDocPublicTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocPublicTag; + const createJSDocPublicTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocPublicTag; /** @deprecated Use `factory.createJSDocPrivateTag` or the factory supplied by your transformation context instead. */ - const createJSDocPrivateTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocPrivateTag; + const createJSDocPrivateTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocPrivateTag; /** @deprecated Use `factory.createJSDocProtectedTag` or the factory supplied by your transformation context instead. */ - const createJSDocProtectedTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocProtectedTag; + const createJSDocProtectedTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocProtectedTag; /** @deprecated Use `factory.createJSDocReadonlyTag` or the factory supplied by your transformation context instead. */ - const createJSDocReadonlyTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocReadonlyTag; + const createJSDocReadonlyTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocReadonlyTag; /** @deprecated Use `factory.createJSDocUnknownTag` or the factory supplied by your transformation context instead. */ - const createJSDocTag: (tagName: Identifier, comment?: string | undefined) => JSDocUnknownTag; + const createJSDocTag: (tagName: Identifier, comment?: string | NodeArray | undefined) => JSDocUnknownTag; /** @deprecated Use `factory.createJsxElement` or the factory supplied by your transformation context instead. */ const createJsxElement: (openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement) => JsxElement; /** @deprecated Use `factory.updateJsxElement` or the factory supplied by your transformation context instead. */ @@ -7214,4 +7372,8 @@ declare namespace ts { */ interface Map extends ESMap { } + /** + * @deprecated Use `isMemberName` instead. + */ + const isIdentifierOrPrivateIdentifier: (node: Node) => node is MemberName; } diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index bf9fd8adc3ce6..59f7d01b56ae8 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -286,11 +286,11 @@ var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "4.2"; + ts.versionMajorMinor = "4.3"; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = ts.versionMajorMinor + ".0-dev"; + ts.version = "4.3.2"; /* @internal */ var Comparison; (function (Comparison) { @@ -2594,6 +2594,8 @@ var ts; } } Debug.assertMissingNode = assertMissingNode; + function type(_value) { } + Debug.type = type; function getFunctionName(func) { if (typeof func !== "function") { return ""; @@ -2855,11 +2857,11 @@ var ts; this.objectFlags & 8 /* Tuple */ ? "TupleType" : this.objectFlags & 16 /* Anonymous */ ? "AnonymousType" : this.objectFlags & 32 /* Mapped */ ? "MappedType" : - this.objectFlags & 2048 /* ReverseMapped */ ? "ReverseMappedType" : + this.objectFlags & 1024 /* ReverseMapped */ ? "ReverseMappedType" : this.objectFlags & 256 /* EvolvingArray */ ? "EvolvingArrayType" : "ObjectType" : "Type"; - var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~2367 /* ObjectTypeKindMask */ : 0; + var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~1343 /* ObjectTypeKindMask */ : 0; return "" + typeHeader + (this.symbol ? " '" + ts.symbolName(this.symbol) + "'" : "") + (remainingObjectFlags ? " (" + formatObjectFlags(remainingObjectFlags) + ")" : ""); } }, @@ -3405,16 +3407,22 @@ var ts; typeof PerformanceObserver === "function" && hasRequiredAPI(performance, PerformanceObserver)) { return { + // For now we always write native performance events when running in the browser. We may + // make this conditional in the future if we find that native web performance hooks + // in the browser also slow down compilation. + shouldWriteNativeEvents: true, performance: performance, PerformanceObserver: PerformanceObserver }; } } function tryGetNodePerformanceHooks() { - if (typeof module === "object" && typeof require === "function") { + if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof module === "object" && typeof require === "function") { try { - var _a = require("perf_hooks"), performance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; - if (hasRequiredAPI(performance_1, PerformanceObserver_1)) { + var performance_1; + var _a = require("perf_hooks"), nodePerformance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; + if (hasRequiredAPI(nodePerformance_1, PerformanceObserver_1)) { + performance_1 = nodePerformance_1; // There is a bug in Node's performance.measure prior to 12.16.3/13.13.0 that does not // match the Web Performance API specification. Node's implementation did not allow // optional `start` and `end` arguments for `performance.measure`. @@ -3422,27 +3430,26 @@ var ts; var version_1 = new ts.Version(process.versions.node); var range = new ts.VersionRange("<12.16.3 || 13 <13.13"); if (range.test(version_1)) { - return { - performance: { - get timeOrigin() { return performance_1.timeOrigin; }, - now: function () { return performance_1.now(); }, - mark: function (name) { return performance_1.mark(name); }, - measure: function (name, start, end) { - if (start === void 0) { start = "nodeStart"; } - if (end === undefined) { - end = "__performance.measure-fix__"; - performance_1.mark(end); - } - performance_1.measure(name, start, end); - if (end === "__performance.measure-fix__") { - performance_1.clearMarks("__performance.measure-fix__"); - } + performance_1 = { + get timeOrigin() { return nodePerformance_1.timeOrigin; }, + now: function () { return nodePerformance_1.now(); }, + mark: function (name) { return nodePerformance_1.mark(name); }, + measure: function (name, start, end) { + if (start === void 0) { start = "nodeStart"; } + if (end === undefined) { + end = "__performance.measure-fix__"; + nodePerformance_1.mark(end); } - }, - PerformanceObserver: PerformanceObserver_1 + nodePerformance_1.measure(name, start, end); + if (end === "__performance.measure-fix__") { + nodePerformance_1.clearMarks("__performance.measure-fix__"); + } + } }; } return { + // By default, only write native events when generating a cpu profile or using the v8 profiler. + shouldWriteNativeEvents: false, performance: performance_1, PerformanceObserver: PerformanceObserver_1 }; @@ -3473,7 +3480,6 @@ var ts; var performance; (function (performance) { var perfHooks; - var perfObserver; // when set, indicates the implementation of `Performance` to use for user timing. // when unset, indicates user timing is unavailable or disabled. var performanceImpl; @@ -3504,6 +3510,9 @@ var ts; } performance.createTimer = createTimer; performance.nullTimer = { enter: ts.noop, exit: ts.noop }; + var enabled = false; + var timeorigin = ts.timestamp(); + var marks = new ts.Map(); var counts = new ts.Map(); var durations = new ts.Map(); /** @@ -3512,7 +3521,13 @@ var ts; * @param markName The name of the mark. */ function mark(markName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + var _a; + if (enabled) { + var count = (_a = counts.get(markName)) !== null && _a !== void 0 ? _a : 0; + counts.set(markName, count + 1); + marks.set(markName, ts.timestamp()); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + } } performance.mark = mark; /** @@ -3525,7 +3540,14 @@ var ts; * used. */ function measure(measureName, startMarkName, endMarkName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + var _a, _b; + if (enabled) { + var end = (_a = (endMarkName !== undefined ? marks.get(endMarkName) : undefined)) !== null && _a !== void 0 ? _a : ts.timestamp(); + var start = (_b = (startMarkName !== undefined ? marks.get(startMarkName) : undefined)) !== null && _b !== void 0 ? _b : timeorigin; + var previousDuration = durations.get(measureName) || 0; + durations.set(measureName, previousDuration + (end - start)); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + } } performance.measure = measure; /** @@ -3559,40 +3581,41 @@ var ts; * Indicates whether the performance API is enabled. */ function isEnabled() { - return !!performanceImpl; + return enabled; } performance.isEnabled = isEnabled; /** Enables (and resets) performance measurements for the compiler. */ - function enable() { - if (!performanceImpl) { + function enable(system) { + var _a; + if (system === void 0) { system = ts.sys; } + if (!enabled) { + enabled = true; perfHooks || (perfHooks = ts.tryGetNativePerformanceHooks()); - if (!perfHooks) - return false; - perfObserver || (perfObserver = new perfHooks.PerformanceObserver(updateStatisticsFromList)); - perfObserver.observe({ entryTypes: ["mark", "measure"] }); - performanceImpl = perfHooks.performance; + if (perfHooks) { + timeorigin = perfHooks.performance.timeOrigin; + // NodeJS's Web Performance API is currently slower than expected, but we'd still like + // to be able to leverage native trace events when node is run with either `--cpu-prof` + // or `--prof`, if we're running with our own `--generateCpuProfile` flag, or when + // running in debug mode (since its possible to generate a cpu profile while debugging). + if (perfHooks.shouldWriteNativeEvents || ((_a = system === null || system === void 0 ? void 0 : system.cpuProfilingEnabled) === null || _a === void 0 ? void 0 : _a.call(system)) || (system === null || system === void 0 ? void 0 : system.debugMode)) { + performanceImpl = perfHooks.performance; + } + } } return true; } performance.enable = enable; /** Disables performance measurements for the compiler. */ function disable() { - perfObserver === null || perfObserver === void 0 ? void 0 : perfObserver.disconnect(); - performanceImpl = undefined; - counts.clear(); - durations.clear(); - } - performance.disable = disable; - function updateStatisticsFromList(list) { - for (var _i = 0, _a = list.getEntriesByType("mark"); _i < _a.length; _i++) { - var mark_1 = _a[_i]; - counts.set(mark_1.name, (counts.get(mark_1.name) || 0) + 1); - } - for (var _b = 0, _c = list.getEntriesByType("measure"); _b < _c.length; _b++) { - var measure_1 = _c[_b]; - durations.set(measure_1.name, (durations.get(measure_1.name) || 0) + measure_1.duration); + if (enabled) { + marks.clear(); + counts.clear(); + durations.clear(); + performanceImpl = undefined; + enabled = false; } } + performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); /* @internal */ @@ -3636,40 +3659,35 @@ var ts; /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; })(ts || (ts = {})); +/* Tracing events for the compiler. */ /*@internal*/ -/** Tracing events for the compiler. */ var ts; (function (ts) { - var tracing; - (function (tracing) { - var Mode; - (function (Mode) { - Mode[Mode["Project"] = 0] = "Project"; - Mode[Mode["Build"] = 1] = "Build"; - Mode[Mode["Server"] = 2] = "Server"; - })(Mode = tracing.Mode || (tracing.Mode = {})); + // enable the above using startTracing() + // `tracingEnabled` should never be used directly, only through the above + var tracingEnabled; + (function (tracingEnabled) { var fs; var traceCount = 0; - var traceFd; + var traceFd = 0; var mode; + var typeCatalog = []; // NB: id is index + 1 var legendPath; var legend = []; ; - /** Starts tracing for the given project (unless the `fs` module is unavailable). */ + /** Starts tracing for the given project. */ function startTracing(tracingMode, traceDir, configFilePath) { - ts.Debug.assert(!traceFd, "Tracing already started"); + ts.Debug.assert(!ts.tracing, "Tracing already started"); if (fs === undefined) { try { fs = require("fs"); } - catch (_a) { - fs = false; + catch (e) { + throw new Error("tracing requires having fs\n(original error: " + (e.message || e) + ")"); } } - if (!fs) { - return; - } mode = tracingMode; + typeCatalog.length = 0; if (legendPath === undefined) { legendPath = ts.combinePaths(traceDir, "legend.json"); } @@ -3677,9 +3695,9 @@ var ts; if (!fs.existsSync(traceDir)) { fs.mkdirSync(traceDir, { recursive: true }); } - var countPart = mode === 1 /* Build */ ? "." + process.pid + "-" + ++traceCount : - mode === 2 /* Server */ ? "." + process.pid : - ""; + var countPart = mode === "build" ? "." + process.pid + "-" + ++traceCount + : mode === "server" ? "." + process.pid + : ""; var tracePath = ts.combinePaths(traceDir, "trace" + countPart + ".json"); var typesPath = ts.combinePaths(traceDir, "types" + countPart + ".json"); legend.push({ @@ -3688,25 +3706,22 @@ var ts; typesPath: typesPath, }); traceFd = fs.openSync(tracePath, "w"); + ts.tracing = tracingEnabled; // only when traceFd is properly set // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import) var meta = { cat: "__metadata", ph: "M", ts: 1000 * ts.timestamp(), pid: 1, tid: 1 }; fs.writeSync(traceFd, "[\n" + [__assign({ name: "process_name", args: { name: "tsc" } }, meta), __assign({ name: "thread_name", args: { name: "Main" } }, meta), __assign(__assign({ name: "TracingStartedInBrowser" }, meta), { cat: "disabled-by-default-devtools.timeline" })] .map(function (v) { return JSON.stringify(v); }).join(",\n")); } - tracing.startTracing = startTracing; - /** Stops tracing for the in-progress project and dumps the type catalog (unless the `fs` module is unavailable). */ - function stopTracing(typeCatalog) { - if (!traceFd) { - ts.Debug.assert(!fs, "Tracing is not in progress"); - return; - } - ts.Debug.assert(fs); - ts.Debug.assert(!!typeCatalog === (mode !== 2 /* Server */)); // Have a type catalog iff not in server mode + tracingEnabled.startTracing = startTracing; + /** Stops tracing for the in-progress project and dumps the type catalog. */ + function stopTracing() { + ts.Debug.assert(ts.tracing, "Tracing is not in progress"); + ts.Debug.assert(!!typeCatalog.length === (mode !== "server")); // Have a type catalog iff not in server mode fs.writeSync(traceFd, "\n]\n"); fs.closeSync(traceFd); - traceFd = undefined; - if (typeCatalog) { + ts.tracing = undefined; + if (typeCatalog.length) { dumpTypes(typeCatalog); } else { @@ -3715,11 +3730,13 @@ var ts; legend[legend.length - 1].typesPath = undefined; } } - tracing.stopTracing = stopTracing; - function isTracing() { - return !!traceFd; + tracingEnabled.stopTracing = stopTracing; + function recordType(type) { + if (mode !== "server") { + typeCatalog.push(type); + } } - tracing.isTracing = isTracing; + tracingEnabled.recordType = recordType; var Phase; (function (Phase) { Phase["Parse"] = "parse"; @@ -3729,13 +3746,11 @@ var ts; Phase["CheckTypes"] = "checkTypes"; Phase["Emit"] = "emit"; Phase["Session"] = "session"; - })(Phase = tracing.Phase || (tracing.Phase = {})); + })(Phase = tracingEnabled.Phase || (tracingEnabled.Phase = {})); function instant(phase, name, args) { - if (!traceFd) - return; writeEvent("I", phase, name, args, "\"s\":\"g\""); } - tracing.instant = instant; + tracingEnabled.instant = instant; var eventStack = []; /** * @param separateBeginAndEnd - used for special cases where we need the trace point even if the event @@ -3745,47 +3760,42 @@ var ts; */ function push(phase, name, args, separateBeginAndEnd) { if (separateBeginAndEnd === void 0) { separateBeginAndEnd = false; } - if (!traceFd) - return; if (separateBeginAndEnd) { writeEvent("B", phase, name, args); } eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } - tracing.push = push; + tracingEnabled.push = push; function pop() { - if (!traceFd) - return; ts.Debug.assert(eventStack.length > 0); writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); eventStack.length--; } - tracing.pop = pop; + tracingEnabled.pop = pop; function popAll() { - if (!traceFd) - return; var endTime = 1000 * ts.timestamp(); for (var i = eventStack.length - 1; i >= 0; i--) { writeStackEvent(i, endTime); } eventStack.length = 0; } - tracing.popAll = popAll; + tracingEnabled.popAll = popAll; + // sample every 10ms + var sampleInterval = 1000 * 10; function writeStackEvent(index, endTime) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); } - else { + // test if [time,endTime) straddles a sampling point + else if (sampleInterval - (time % sampleInterval) <= endTime - time) { writeEvent("X", phase, name, args, "\"dur\":" + (endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { if (time === void 0) { time = 1000 * ts.timestamp(); } - ts.Debug.assert(traceFd); - ts.Debug.assert(fs); // In server mode, there's no easy way to dump type information, so we drop events that would require it. - if (mode === 2 /* Server */ && phase === "checkTypes" /* CheckTypes */) + if (mode === "server" && phase === "checkTypes" /* CheckTypes */) return; ts.performance.mark("beginTracing"); fs.writeSync(traceFd, ",\n{\"pid\":1,\"tid\":1,\"ph\":\"" + eventType + "\",\"cat\":\"" + phase + "\",\"ts\":" + time + ",\"name\":\"" + name + "\""); @@ -3797,15 +3807,24 @@ var ts; ts.performance.mark("endTracing"); ts.performance.measure("Tracing", "beginTracing", "endTracing"); } - function indexFromOne(lc) { - return { - line: lc.line + 1, - character: lc.character + 1, - }; + function getLocation(node) { + var file = ts.getSourceFileOfNode(node); + return !file + ? undefined + : { + path: file.path, + start: indexFromOne(ts.getLineAndCharacterOfPosition(file, node.pos)), + end: indexFromOne(ts.getLineAndCharacterOfPosition(file, node.end)), + }; + function indexFromOne(lc) { + return { + line: lc.line + 1, + character: lc.character + 1, + }; + } } function dumpTypes(types) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; - ts.Debug.assert(fs); + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x; ts.performance.mark("beginDumpTypes"); var typesPath = legend[legend.length - 1].typesPath; var typesFd = fs.openSync(typesPath, "w"); @@ -3817,15 +3836,13 @@ var ts; var type = types[i]; var objectFlags = type.objectFlags; var symbol = (_a = type.aliasSymbol) !== null && _a !== void 0 ? _a : type.symbol; - var firstDeclaration = (_b = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _b === void 0 ? void 0 : _b[0]; - var firstFile = firstDeclaration && ts.getSourceFileOfNode(firstDeclaration); // It's slow to compute the display text, so skip it unless it's really valuable (or cheap) var display = void 0; if ((objectFlags & 16 /* Anonymous */) | (type.flags & 2944 /* Literal */)) { try { - display = (_c = type.checker) === null || _c === void 0 ? void 0 : _c.typeToString(type); + display = (_b = type.checker) === null || _b === void 0 ? void 0 : _b.typeToString(type); } - catch (_s) { + catch (_y) { display = undefined; } } @@ -3833,26 +3850,52 @@ var ts; if (type.flags & 8388608 /* IndexedAccess */) { var indexedAccessType = type; indexedAccessProperties = { - indexedAccessObjectType: (_d = indexedAccessType.objectType) === null || _d === void 0 ? void 0 : _d.id, - indexedAccessIndexType: (_e = indexedAccessType.indexType) === null || _e === void 0 ? void 0 : _e.id, + indexedAccessObjectType: (_c = indexedAccessType.objectType) === null || _c === void 0 ? void 0 : _c.id, + indexedAccessIndexType: (_d = indexedAccessType.indexType) === null || _d === void 0 ? void 0 : _d.id, }; } var referenceProperties = {}; if (objectFlags & 4 /* Reference */) { var referenceType = type; referenceProperties = { - instantiatedType: (_f = referenceType.target) === null || _f === void 0 ? void 0 : _f.id, - typeArguments: (_g = referenceType.resolvedTypeArguments) === null || _g === void 0 ? void 0 : _g.map(function (t) { return t.id; }), + instantiatedType: (_e = referenceType.target) === null || _e === void 0 ? void 0 : _e.id, + typeArguments: (_f = referenceType.resolvedTypeArguments) === null || _f === void 0 ? void 0 : _f.map(function (t) { return t.id; }), + referenceLocation: getLocation(referenceType.node), }; } var conditionalProperties = {}; if (type.flags & 16777216 /* Conditional */) { var conditionalType = type; conditionalProperties = { - conditionalCheckType: (_h = conditionalType.checkType) === null || _h === void 0 ? void 0 : _h.id, - conditionalExtendsType: (_j = conditionalType.extendsType) === null || _j === void 0 ? void 0 : _j.id, - conditionalTrueType: (_l = (_k = conditionalType.resolvedTrueType) === null || _k === void 0 ? void 0 : _k.id) !== null && _l !== void 0 ? _l : -1, - conditionalFalseType: (_o = (_m = conditionalType.resolvedFalseType) === null || _m === void 0 ? void 0 : _m.id) !== null && _o !== void 0 ? _o : -1, + conditionalCheckType: (_g = conditionalType.checkType) === null || _g === void 0 ? void 0 : _g.id, + conditionalExtendsType: (_h = conditionalType.extendsType) === null || _h === void 0 ? void 0 : _h.id, + conditionalTrueType: (_k = (_j = conditionalType.resolvedTrueType) === null || _j === void 0 ? void 0 : _j.id) !== null && _k !== void 0 ? _k : -1, + conditionalFalseType: (_m = (_l = conditionalType.resolvedFalseType) === null || _l === void 0 ? void 0 : _l.id) !== null && _m !== void 0 ? _m : -1, + }; + } + var substitutionProperties = {}; + if (type.flags & 33554432 /* Substitution */) { + var substitutionType = type; + substitutionProperties = { + substitutionBaseType: (_o = substitutionType.baseType) === null || _o === void 0 ? void 0 : _o.id, + substituteType: (_p = substitutionType.substitute) === null || _p === void 0 ? void 0 : _p.id, + }; + } + var reverseMappedProperties = {}; + if (objectFlags & 1024 /* ReverseMapped */) { + var reverseMappedType = type; + reverseMappedProperties = { + reverseMappedSourceType: (_q = reverseMappedType.source) === null || _q === void 0 ? void 0 : _q.id, + reverseMappedMappedType: (_r = reverseMappedType.mappedType) === null || _r === void 0 ? void 0 : _r.id, + reverseMappedConstraintType: (_s = reverseMappedType.constraintType) === null || _s === void 0 ? void 0 : _s.id, + }; + } + var evolvingArrayProperties = {}; + if (objectFlags & 256 /* EvolvingArray */) { + var evolvingArrayType = type; + evolvingArrayProperties = { + evolvingArrayElementType: evolvingArrayType.elementType.id, + evolvingArrayFinalType: (_t = evolvingArrayType.finalArrayType) === null || _t === void 0 ? void 0 : _t.id, }; } // We can't print out an arbitrary object, so just assign each one a unique number. @@ -3866,11 +3909,7 @@ var ts; recursionIdentityMap.set(recursionIdentity, recursionToken); } } - var descriptor = __assign(__assign(__assign(__assign({ id: type.id, intrinsicName: type.intrinsicName, symbolName: (symbol === null || symbol === void 0 ? void 0 : symbol.escapedName) && ts.unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, unionTypes: (type.flags & 1048576 /* Union */) ? (_p = type.types) === null || _p === void 0 ? void 0 : _p.map(function (t) { return t.id; }) : undefined, intersectionTypes: (type.flags & 2097152 /* Intersection */) ? type.types.map(function (t) { return t.id; }) : undefined, aliasTypeArguments: (_q = type.aliasTypeArguments) === null || _q === void 0 ? void 0 : _q.map(function (t) { return t.id; }), keyofType: (type.flags & 4194304 /* Index */) ? (_r = type.type) === null || _r === void 0 ? void 0 : _r.id : undefined }, indexedAccessProperties), referenceProperties), conditionalProperties), { firstDeclaration: firstDeclaration && { - path: firstFile.path, - start: indexFromOne(ts.getLineAndCharacterOfPosition(firstFile, firstDeclaration.pos)), - end: indexFromOne(ts.getLineAndCharacterOfPosition(ts.getSourceFileOfNode(firstDeclaration), firstDeclaration.end)), - }, flags: ts.Debug.formatTypeFlags(type.flags).split("|"), display: display }); + var descriptor = __assign(__assign(__assign(__assign(__assign(__assign(__assign({ id: type.id, intrinsicName: type.intrinsicName, symbolName: (symbol === null || symbol === void 0 ? void 0 : symbol.escapedName) && ts.unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, isTuple: objectFlags & 8 /* Tuple */ ? true : undefined, unionTypes: (type.flags & 1048576 /* Union */) ? (_u = type.types) === null || _u === void 0 ? void 0 : _u.map(function (t) { return t.id; }) : undefined, intersectionTypes: (type.flags & 2097152 /* Intersection */) ? type.types.map(function (t) { return t.id; }) : undefined, aliasTypeArguments: (_v = type.aliasTypeArguments) === null || _v === void 0 ? void 0 : _v.map(function (t) { return t.id; }), keyofType: (type.flags & 4194304 /* Index */) ? (_w = type.type) === null || _w === void 0 ? void 0 : _w.id : undefined }, indexedAccessProperties), referenceProperties), conditionalProperties), substitutionProperties), reverseMappedProperties), evolvingArrayProperties), { destructuringPattern: getLocation(type.pattern), firstDeclaration: getLocation((_x = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _x === void 0 ? void 0 : _x[0]), flags: ts.Debug.formatTypeFlags(type.flags).split("|"), display: display }); fs.writeSync(typesFd, JSON.stringify(descriptor)); if (i < numTypes - 1) { fs.writeSync(typesFd, ",\n"); @@ -3885,11 +3924,13 @@ var ts; if (!legendPath) { return; } - ts.Debug.assert(fs); fs.writeFileSync(legendPath, JSON.stringify(legend)); } - tracing.dumpLegend = dumpLegend; - })(tracing = ts.tracing || (ts.tracing = {})); + tracingEnabled.dumpLegend = dumpLegend; + })(tracingEnabled || (tracingEnabled = {})); + // define after tracingEnabled is initialized + ts.startTracing = tracingEnabled.startTracing; + ts.dumpTracingLegend = tracingEnabled.dumpLegend; })(ts || (ts = {})); var ts; (function (ts) { @@ -4065,215 +4106,216 @@ var ts; SyntaxKind[SyntaxKind["FromKeyword"] = 153] = "FromKeyword"; SyntaxKind[SyntaxKind["GlobalKeyword"] = 154] = "GlobalKeyword"; SyntaxKind[SyntaxKind["BigIntKeyword"] = 155] = "BigIntKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 156] = "OfKeyword"; + SyntaxKind[SyntaxKind["OverrideKeyword"] = 156] = "OverrideKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 157] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 157] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 158] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 158] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 159] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 159] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 160] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 161] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 160] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 161] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 162] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 162] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 163] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 164] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 165] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 166] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 167] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 168] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 169] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 170] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 171] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 163] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 164] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 165] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 166] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 167] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 168] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 169] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 170] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 171] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 172] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 172] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 173] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 174] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 175] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 176] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 177] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 178] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 179] = "TupleType"; - SyntaxKind[SyntaxKind["OptionalType"] = 180] = "OptionalType"; - SyntaxKind[SyntaxKind["RestType"] = 181] = "RestType"; - SyntaxKind[SyntaxKind["UnionType"] = 182] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 183] = "IntersectionType"; - SyntaxKind[SyntaxKind["ConditionalType"] = 184] = "ConditionalType"; - SyntaxKind[SyntaxKind["InferType"] = 185] = "InferType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 186] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 187] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 188] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 189] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 190] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 191] = "LiteralType"; - SyntaxKind[SyntaxKind["NamedTupleMember"] = 192] = "NamedTupleMember"; - SyntaxKind[SyntaxKind["TemplateLiteralType"] = 193] = "TemplateLiteralType"; - SyntaxKind[SyntaxKind["TemplateLiteralTypeSpan"] = 194] = "TemplateLiteralTypeSpan"; - SyntaxKind[SyntaxKind["ImportType"] = 195] = "ImportType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 173] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 174] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 175] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 176] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 177] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 178] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 179] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 180] = "TupleType"; + SyntaxKind[SyntaxKind["OptionalType"] = 181] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 182] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 183] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 184] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 185] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 186] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 187] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 188] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 189] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 190] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 191] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 192] = "LiteralType"; + SyntaxKind[SyntaxKind["NamedTupleMember"] = 193] = "NamedTupleMember"; + SyntaxKind[SyntaxKind["TemplateLiteralType"] = 194] = "TemplateLiteralType"; + SyntaxKind[SyntaxKind["TemplateLiteralTypeSpan"] = 195] = "TemplateLiteralTypeSpan"; + SyntaxKind[SyntaxKind["ImportType"] = 196] = "ImportType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 196] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 197] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 198] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 197] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 198] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 199] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 199] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 200] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 201] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 202] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 203] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 204] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 205] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 206] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 207] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 208] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 209] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 210] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 211] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 212] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 213] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 214] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 215] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 216] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 217] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 218] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 219] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 220] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 221] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 222] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 223] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 224] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 225] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 226] = "MetaProperty"; - SyntaxKind[SyntaxKind["SyntheticExpression"] = 227] = "SyntheticExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 200] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 201] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 202] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 203] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 204] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 205] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 206] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 207] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 208] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 209] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 210] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 211] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 212] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 213] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 214] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 215] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 216] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 217] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 218] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 219] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 220] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 221] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 222] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 223] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 224] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 225] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 226] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 227] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 228] = "SyntheticExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 228] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 229] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 229] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 230] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 230] = "Block"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 231] = "EmptyStatement"; - SyntaxKind[SyntaxKind["VariableStatement"] = 232] = "VariableStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 233] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 234] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 235] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 236] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 237] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 238] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 239] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 240] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 241] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 242] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 243] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 244] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 245] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 246] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 247] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 248] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 249] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 250] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 251] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 252] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 253] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 254] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 255] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 256] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 257] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 258] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 259] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 260] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 261] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 262] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 263] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 264] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 265] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 266] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 267] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 268] = "NamedExports"; - SyntaxKind[SyntaxKind["NamespaceExport"] = 269] = "NamespaceExport"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 270] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 271] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 231] = "Block"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 232] = "EmptyStatement"; + SyntaxKind[SyntaxKind["VariableStatement"] = 233] = "VariableStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 234] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 235] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 236] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 237] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 238] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 239] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 240] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 241] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 242] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 243] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 244] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 245] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 246] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 247] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 248] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 249] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 250] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 251] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 252] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 253] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 254] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 255] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 256] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 257] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 258] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 259] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 260] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 261] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 262] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 263] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 264] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 265] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 266] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 267] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 268] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 269] = "NamedExports"; + SyntaxKind[SyntaxKind["NamespaceExport"] = 270] = "NamespaceExport"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 271] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 272] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 272] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 273] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 273] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 274] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 275] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 276] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxFragment"] = 277] = "JsxFragment"; - SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 278] = "JsxOpeningFragment"; - SyntaxKind[SyntaxKind["JsxClosingFragment"] = 279] = "JsxClosingFragment"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 280] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 281] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 282] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 283] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 274] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 275] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 276] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 277] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 278] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 279] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 280] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 281] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 282] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 283] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 284] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 284] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 285] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 286] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 287] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 285] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 286] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 287] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 288] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 288] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 289] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 290] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 289] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 290] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 291] = "SpreadAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 291] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 292] = "EnumMember"; // Unparsed - SyntaxKind[SyntaxKind["UnparsedPrologue"] = 292] = "UnparsedPrologue"; - SyntaxKind[SyntaxKind["UnparsedPrepend"] = 293] = "UnparsedPrepend"; - SyntaxKind[SyntaxKind["UnparsedText"] = 294] = "UnparsedText"; - SyntaxKind[SyntaxKind["UnparsedInternalText"] = 295] = "UnparsedInternalText"; - SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 296] = "UnparsedSyntheticReference"; + SyntaxKind[SyntaxKind["UnparsedPrologue"] = 293] = "UnparsedPrologue"; + SyntaxKind[SyntaxKind["UnparsedPrepend"] = 294] = "UnparsedPrepend"; + SyntaxKind[SyntaxKind["UnparsedText"] = 295] = "UnparsedText"; + SyntaxKind[SyntaxKind["UnparsedInternalText"] = 296] = "UnparsedInternalText"; + SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 297] = "UnparsedSyntheticReference"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 297] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 298] = "Bundle"; - SyntaxKind[SyntaxKind["UnparsedSource"] = 299] = "UnparsedSource"; - SyntaxKind[SyntaxKind["InputFiles"] = 300] = "InputFiles"; + SyntaxKind[SyntaxKind["SourceFile"] = 298] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 299] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 300] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 301] = "InputFiles"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 301] = "JSDocTypeExpression"; - SyntaxKind[SyntaxKind["JSDocNameReference"] = 302] = "JSDocNameReference"; - // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 303] = "JSDocAllType"; - // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 304] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 305] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 306] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 307] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 308] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 309] = "JSDocVariadicType"; - // https://jsdoc.app/about-namepaths.html - SyntaxKind[SyntaxKind["JSDocNamepathType"] = 310] = "JSDocNamepathType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 311] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 312] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocSignature"] = 313] = "JSDocSignature"; - SyntaxKind[SyntaxKind["JSDocTag"] = 314] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 315] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 316] = "JSDocImplementsTag"; - SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 317] = "JSDocAuthorTag"; - SyntaxKind[SyntaxKind["JSDocDeprecatedTag"] = 318] = "JSDocDeprecatedTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 319] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocPublicTag"] = 320] = "JSDocPublicTag"; - SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 321] = "JSDocPrivateTag"; - SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 322] = "JSDocProtectedTag"; - SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 323] = "JSDocReadonlyTag"; - SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 324] = "JSDocCallbackTag"; - SyntaxKind[SyntaxKind["JSDocEnumTag"] = 325] = "JSDocEnumTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 326] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 327] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocThisTag"] = 328] = "JSDocThisTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 329] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 330] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 331] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocSeeTag"] = 332] = "JSDocSeeTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 333] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 302] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocNameReference"] = 303] = "JSDocNameReference"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 304] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 305] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 306] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 307] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 308] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 309] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 310] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocNamepathType"] = 311] = "JSDocNamepathType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 312] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocText"] = 313] = "JSDocText"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 314] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 315] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocLink"] = 316] = "JSDocLink"; + SyntaxKind[SyntaxKind["JSDocTag"] = 317] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 318] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 319] = "JSDocImplementsTag"; + SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 320] = "JSDocAuthorTag"; + SyntaxKind[SyntaxKind["JSDocDeprecatedTag"] = 321] = "JSDocDeprecatedTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 322] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocPublicTag"] = 323] = "JSDocPublicTag"; + SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 324] = "JSDocPrivateTag"; + SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 325] = "JSDocProtectedTag"; + SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 326] = "JSDocReadonlyTag"; + SyntaxKind[SyntaxKind["JSDocOverrideTag"] = 327] = "JSDocOverrideTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 328] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 329] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 330] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 331] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 332] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 333] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 334] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 335] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocSeeTag"] = 336] = "JSDocSeeTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 337] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 334] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 338] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 335] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 336] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 337] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 338] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 339] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 340] = "SyntheticReferenceExpression"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 339] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 340] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 341] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 342] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 343] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 344] = "SyntheticReferenceExpression"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 341] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 345] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 62] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 77] = "LastAssignment"; @@ -4282,15 +4324,15 @@ var ts; SyntaxKind[SyntaxKind["FirstReservedWord"] = 80] = "FirstReservedWord"; SyntaxKind[SyntaxKind["LastReservedWord"] = 115] = "LastReservedWord"; SyntaxKind[SyntaxKind["FirstKeyword"] = 80] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 156] = "LastKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 157] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 116] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 124] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 172] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 195] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 173] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 196] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 77] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 156] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 157] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; @@ -4299,15 +4341,15 @@ var ts; SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken"; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 29] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 77] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstStatement"] = 232] = "FirstStatement"; - SyntaxKind[SyntaxKind["LastStatement"] = 248] = "LastStatement"; - SyntaxKind[SyntaxKind["FirstNode"] = 157] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 301] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 333] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 314] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 333] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstStatement"] = 233] = "FirstStatement"; + SyntaxKind[SyntaxKind["LastStatement"] = 249] = "LastStatement"; + SyntaxKind[SyntaxKind["FirstNode"] = 158] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 302] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 337] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 317] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 337] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 125] = "FirstContextualKeyword"; - /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 156] = "LastContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 157] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -4377,14 +4419,15 @@ var ts; ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; ModifierFlags[ModifierFlags["HasComputedJSDocModifiers"] = 4096] = "HasComputedJSDocModifiers"; ModifierFlags[ModifierFlags["Deprecated"] = 8192] = "Deprecated"; + ModifierFlags[ModifierFlags["Override"] = 16384] = "Override"; ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. - ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 16476] = "ParameterPropertyModifier"; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; - ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; + ModifierFlags[ModifierFlags["TypeScriptModifier"] = 18654] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; - ModifierFlags[ModifierFlags["All"] = 11263] = "All"; + ModifierFlags[ModifierFlags["All"] = 27647] = "All"; })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); var JsxFlags; (function (JsxFlags) { @@ -4565,6 +4608,8 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["NoUndefinedOptionalParameterType"] = 1073741824] = "NoUndefinedOptionalParameterType"; // Error handling NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifiedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifiedNameInPlaceOfIdentifier"; + /** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */ NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier"; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection"; @@ -4579,7 +4624,6 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; - NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -4884,10 +4928,6 @@ var ts; TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["StringLikeLiteral"] = 134217856] = "StringLikeLiteral"; - /* @internal */ - TypeFlags[TypeFlags["FreshableLiteral"] = 134220672] = "FreshableLiteral"; - /* @internal */ TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; /* @internal */ TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; @@ -4936,6 +4976,9 @@ var ts; /* @internal */ TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags + // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check + // for a certain TypeFlags value to determine their meaning. var ObjectFlags; (function (ObjectFlags) { ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; @@ -4948,50 +4991,59 @@ var ts; ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; - ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; - ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; - ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; - ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; - ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; - ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral"; - ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 1024] = "ReverseMapped"; + ObjectFlags[ObjectFlags["JsxAttributes"] = 2048] = "JsxAttributes"; + ObjectFlags[ObjectFlags["MarkerType"] = 4096] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 8192] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 16384] = "FreshLiteral"; + ObjectFlags[ObjectFlags["ArrayLiteral"] = 32768] = "ArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion"; + ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType"; + ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral"; + ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 262144] = "ContainsObjectOrArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType"; + ObjectFlags[ObjectFlags["NonInferrableType"] = 524288] = "NonInferrableType"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; + ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 1048576] = "CouldContainTypeVariablesComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; + ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 2097152] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; + ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags"; + // Object flags that uniquely identify the kind of ObjectType /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed"; + ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 1343] = "ObjectTypeKindMask"; + // Flags that require TypeFlags.Object + ObjectFlags[ObjectFlags["ContainsSpread"] = 4194304] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ObjectRestType"] = 8388608] = "ObjectRestType"; /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 16777216] = "IsClassInstanceClone"; + // Flags that require TypeFlags.Object and ObjectFlags.Reference /* @internal */ - ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeCalculated"] = 33554432] = "IdenticalBaseTypeCalculated"; /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeExists"] = 67108864] = "IdenticalBaseTypeExists"; + // Flags that require TypeFlags.UnionOrIntersection or TypeFlags.Substitution /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection"; + ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 1073741824] = "IsClassInstanceClone"; - ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; /* @internal */ - ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; + ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags"; - // Object flags that uniquely identify the kind of ObjectType + ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + // Flags that require TypeFlags.Union + /* @internal */ + ObjectFlags[ObjectFlags["ContainsIntersections"] = 67108864] = "ContainsIntersections"; + // Flags that require TypeFlags.Intersection /* @internal */ - ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 2367] = "ObjectTypeKindMask"; + ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 67108864] = "IsNeverIntersectionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersection"] = 134217728] = "IsNeverIntersection"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ var VarianceFlags; @@ -5065,16 +5117,17 @@ var ts; (function (InferencePriority) { InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; InferencePriority[InferencePriority["SpeculativeTuple"] = 2] = "SpeculativeTuple"; - InferencePriority[InferencePriority["HomomorphicMappedType"] = 4] = "HomomorphicMappedType"; - InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 8] = "PartialHomomorphicMappedType"; - InferencePriority[InferencePriority["MappedTypeConstraint"] = 16] = "MappedTypeConstraint"; - InferencePriority[InferencePriority["ContravariantConditional"] = 32] = "ContravariantConditional"; - InferencePriority[InferencePriority["ReturnType"] = 64] = "ReturnType"; - InferencePriority[InferencePriority["LiteralKeyof"] = 128] = "LiteralKeyof"; - InferencePriority[InferencePriority["NoConstraints"] = 256] = "NoConstraints"; - InferencePriority[InferencePriority["AlwaysStrict"] = 512] = "AlwaysStrict"; - InferencePriority[InferencePriority["MaxValue"] = 1024] = "MaxValue"; - InferencePriority[InferencePriority["PriorityImpliesCombination"] = 208] = "PriorityImpliesCombination"; + InferencePriority[InferencePriority["SubstituteSource"] = 4] = "SubstituteSource"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 8] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 16] = "PartialHomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 32] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ContravariantConditional"] = 64] = "ContravariantConditional"; + InferencePriority[InferencePriority["ReturnType"] = 128] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 256] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 512] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 1024] = "AlwaysStrict"; + InferencePriority[InferencePriority["MaxValue"] = 2048] = "MaxValue"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 416] = "PriorityImpliesCombination"; InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); /* @internal */ @@ -5152,20 +5205,23 @@ var ts; WatchFileKind[WatchFileKind["FixedPollingInterval"] = 0] = "FixedPollingInterval"; WatchFileKind[WatchFileKind["PriorityPollingInterval"] = 1] = "PriorityPollingInterval"; WatchFileKind[WatchFileKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; - WatchFileKind[WatchFileKind["UseFsEvents"] = 3] = "UseFsEvents"; - WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 4] = "UseFsEventsOnParentDirectory"; + WatchFileKind[WatchFileKind["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; + WatchFileKind[WatchFileKind["UseFsEvents"] = 4] = "UseFsEvents"; + WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 5] = "UseFsEventsOnParentDirectory"; })(WatchFileKind = ts.WatchFileKind || (ts.WatchFileKind = {})); var WatchDirectoryKind; (function (WatchDirectoryKind) { WatchDirectoryKind[WatchDirectoryKind["UseFsEvents"] = 0] = "UseFsEvents"; WatchDirectoryKind[WatchDirectoryKind["FixedPollingInterval"] = 1] = "FixedPollingInterval"; WatchDirectoryKind[WatchDirectoryKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; + WatchDirectoryKind[WatchDirectoryKind["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; })(WatchDirectoryKind = ts.WatchDirectoryKind || (ts.WatchDirectoryKind = {})); var PollingWatchKind; (function (PollingWatchKind) { PollingWatchKind[PollingWatchKind["FixedInterval"] = 0] = "FixedInterval"; PollingWatchKind[PollingWatchKind["PriorityInterval"] = 1] = "PriorityInterval"; PollingWatchKind[PollingWatchKind["DynamicPriority"] = 2] = "DynamicPriority"; + PollingWatchKind[PollingWatchKind["FixedChunkSize"] = 3] = "FixedChunkSize"; })(PollingWatchKind = ts.PollingWatchKind || (ts.PollingWatchKind = {})); var ModuleKind; (function (ModuleKind) { @@ -5226,6 +5282,7 @@ var ts; ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019"; ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020"; + ScriptTarget[ScriptTarget["ES2021"] = 8] = "ES2021"; ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext"; ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest"; @@ -5388,29 +5445,30 @@ var ts; TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript"; TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx"; TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext"; - TransformFlags[TransformFlags["ContainsES2020"] = 8] = "ContainsES2020"; - TransformFlags[TransformFlags["ContainsES2019"] = 16] = "ContainsES2019"; - TransformFlags[TransformFlags["ContainsES2018"] = 32] = "ContainsES2018"; - TransformFlags[TransformFlags["ContainsES2017"] = 64] = "ContainsES2017"; - TransformFlags[TransformFlags["ContainsES2016"] = 128] = "ContainsES2016"; - TransformFlags[TransformFlags["ContainsES2015"] = 256] = "ContainsES2015"; - TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; - TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 1024] = "ContainsDestructuringAssignment"; + TransformFlags[TransformFlags["ContainsES2021"] = 8] = "ContainsES2021"; + TransformFlags[TransformFlags["ContainsES2020"] = 16] = "ContainsES2020"; + TransformFlags[TransformFlags["ContainsES2019"] = 32] = "ContainsES2019"; + TransformFlags[TransformFlags["ContainsES2018"] = 64] = "ContainsES2018"; + TransformFlags[TransformFlags["ContainsES2017"] = 128] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 256] = "ContainsES2016"; + TransformFlags[TransformFlags["ContainsES2015"] = 512] = "ContainsES2015"; + TransformFlags[TransformFlags["ContainsGenerator"] = 1024] = "ContainsGenerator"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 2048] = "ContainsTypeScriptClassSyntax"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 4096] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsRestOrSpread"] = 8192] = "ContainsRestOrSpread"; - TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 16384] = "ContainsObjectRestOrSpread"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 32768] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 65536] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 131072] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 262144] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsAwait"] = 524288] = "ContainsAwait"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 1048576] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 2097152] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["ContainsClassFields"] = 4194304] = "ContainsClassFields"; - TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 8388608] = "ContainsPossibleTopLevelAwait"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 16384] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 32768] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 65536] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 131072] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 262144] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 524288] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsAwait"] = 1048576] = "ContainsAwait"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 2097152] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 4194304] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["ContainsClassFields"] = 8388608] = "ContainsClassFields"; + TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 16777216] = "ContainsPossibleTopLevelAwait"; // 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 @@ -5420,37 +5478,38 @@ var ts; TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript"; TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx"; TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext"; - TransformFlags[TransformFlags["AssertES2020"] = 8] = "AssertES2020"; - TransformFlags[TransformFlags["AssertES2019"] = 16] = "AssertES2019"; - TransformFlags[TransformFlags["AssertES2018"] = 32] = "AssertES2018"; - TransformFlags[TransformFlags["AssertES2017"] = 64] = "AssertES2017"; - TransformFlags[TransformFlags["AssertES2016"] = 128] = "AssertES2016"; - TransformFlags[TransformFlags["AssertES2015"] = 256] = "AssertES2015"; - TransformFlags[TransformFlags["AssertGenerator"] = 512] = "AssertGenerator"; - TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 1024] = "AssertDestructuringAssignment"; + TransformFlags[TransformFlags["AssertES2021"] = 8] = "AssertES2021"; + TransformFlags[TransformFlags["AssertES2020"] = 16] = "AssertES2020"; + TransformFlags[TransformFlags["AssertES2019"] = 32] = "AssertES2019"; + TransformFlags[TransformFlags["AssertES2018"] = 64] = "AssertES2018"; + TransformFlags[TransformFlags["AssertES2017"] = 128] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 256] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 512] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 1024] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 2048] = "AssertDestructuringAssignment"; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes"; TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes"; TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 547309568] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 547313664] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 547311616] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 538923008] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["PropertyExcludes"] = 536875008] = "PropertyExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 536905728] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 546379776] = "ModuleExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 557748224] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 557756416] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 557752320] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 540975104] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["PropertyExcludes"] = 536879104] = "PropertyExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 536940544] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 555888640] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536922112] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536879104] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537018368] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536973312] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536887296] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537165824] = "VariableDeclarationListExcludes"; TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 536887296] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 536879104] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 536903680] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 536887296] = "BindingPatternExcludes"; // Propagating flags // - Bitmasks for flags that should propagate from a child - TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 4096] = "PropertyNamePropagatingFlags"; + TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 8192] = "PropertyNamePropagatingFlags"; // Masks // - Additional bitmasks })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); @@ -6318,7 +6377,7 @@ var ts; * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. * Comparison is case-sensitive between the canonical paths. * - * @deprecated Use `containsPath` if possible. + * Use `containsPath` if file names are not already reduced and absolute. */ function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { var canonicalFileName = getCanonicalFileName(fileName); @@ -6438,6 +6497,11 @@ var ts; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time + /* @internal */ + function getModifiedTime(host, fileName) { + return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; + } + ts.getModifiedTime = getModifiedTime; function createPollingIntervalBasedLevels(levels) { var _a; return _a = {}, @@ -6494,6 +6558,51 @@ var ts; } } ts.setCustomPollingValues = setCustomPollingValues; + function pollWatchedFileQueue(host, queue, pollIndex, chunkSize, callbackOnWatchFileStat) { + var definedValueCopyToIndex = pollIndex; + // Max visit would be all elements of the queue + for (var canVisit = queue.length; chunkSize && canVisit; nextPollIndex(), canVisit--) { + var watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + // Only files polled count towards chunkSize + chunkSize--; + var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(host, watchedFile.fileName)); + if (watchedFile.isClosed) { + // Closed watcher as part of callback + queue[pollIndex] = undefined; + continue; + } + callbackOnWatchFileStat === null || callbackOnWatchFileStat === void 0 ? void 0 : callbackOnWatchFileStat(watchedFile, pollIndex, fileChanged); + // Defragment the queue while we are at it + if (queue[pollIndex]) { + // Copy this file to the non hole location + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + // Return next poll index + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + // There are holes from definedValueCopyToIndex to end of queue, change queue size + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } /* @internal */ function createDynamicPriorityPollingWatchFile(host) { var watchedFiles = []; @@ -6507,7 +6616,7 @@ var ts; fileName: fileName, callback: callback, unchangedPolls: 0, - mtime: getModifiedTime(fileName) + mtime: getModifiedTime(host, fileName) }; watchedFiles.push(file); addToPollingIntervalQueue(file, defaultPollingInterval); @@ -6550,25 +6659,9 @@ var ts; } } function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { - // Max visit would be all elements of the queue - var needsVisit = queue.length; - var definedValueCopyToIndex = pollIndex; - for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { - var watchedFile = queue[pollIndex]; - if (!watchedFile) { - continue; - } - else if (watchedFile.isClosed) { - queue[pollIndex] = undefined; - continue; - } - polled++; - var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); - if (watchedFile.isClosed) { - // Closed watcher as part of callback - queue[pollIndex] = undefined; - } - else if (fileChanged) { + return pollWatchedFileQueue(host, queue, pollIndex, chunkSize, onWatchFileStat); + function onWatchFileStat(watchedFile, pollIndex, fileChanged) { + if (fileChanged) { watchedFile.unchangedPolls = 0; // Changed files go to changedFilesInLastPoll queue if (queue !== changedFilesInLastPoll) { @@ -6590,27 +6683,6 @@ var ts; queue[pollIndex] = undefined; addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); } - if (queue[pollIndex]) { - // Copy this file to the non hole location - if (definedValueCopyToIndex < pollIndex) { - queue[definedValueCopyToIndex] = watchedFile; - queue[pollIndex] = undefined; - } - definedValueCopyToIndex++; - } - } - // Return next poll index - return pollIndex; - function nextPollIndex() { - pollIndex++; - if (pollIndex === queue.length) { - if (definedValueCopyToIndex < pollIndex) { - // There are holes from nextDefinedValueIndex to end of queue, change queue size - queue.length = definedValueCopyToIndex; - } - pollIndex = 0; - definedValueCopyToIndex = 0; - } } } function pollingIntervalQueue(pollingInterval) { @@ -6639,9 +6711,6 @@ var ts; function scheduleNextPoll(pollingInterval) { pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); } - function getModifiedTime(fileName) { - return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; - } } ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) { @@ -6692,6 +6761,37 @@ var ts; return watcher; } } + function createFixedChunkSizePollingWatchFile(host) { + var watchedFiles = []; + var pollIndex = 0; + var pollScheduled; + return watchFile; + function watchFile(fileName, callback) { + var file = { + fileName: fileName, + callback: callback, + mtime: getModifiedTime(host, fileName) + }; + watchedFiles.push(file); + scheduleNextPoll(); + return { + close: function () { + file.isClosed = true; + ts.unorderedRemoveItem(watchedFiles, file); + } + }; + } + function pollQueue() { + pollScheduled = undefined; + pollIndex = pollWatchedFileQueue(host, watchedFiles, pollIndex, pollingChunkSize[PollingInterval.Low]); + scheduleNextPoll(); + } + function scheduleNextPoll() { + if (!watchedFiles.length || pollScheduled) + return; + pollScheduled = host.setTimeout(pollQueue, PollingInterval.High); + } + } /* @internal */ function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) { var cache = new ts.Map(); @@ -7014,8 +7114,9 @@ var ts; } /*@internal*/ function createSystemWatchFunctions(_a) { - var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory; + var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind; var dynamicPollingWatchFile; + var fixedChunkSizePollingWatchFile; var nonPollingWatchFile; var hostRecursiveDirectoryWatcher; return { @@ -7032,6 +7133,8 @@ var ts; return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined); case ts.WatchFileKind.DynamicPriorityPolling: return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined); + case ts.WatchFileKind.FixedChunkSizePolling: + return ensureFixedChunkSizePollingWatchFile()(fileName, callback, /* pollingInterval */ undefined, /*options*/ undefined); case ts.WatchFileKind.UseFsEvents: return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options)); @@ -7045,8 +7148,10 @@ var ts; } } function ensureDynamicPollingWatchFile() { - return dynamicPollingWatchFile || - (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })); + return dynamicPollingWatchFile || (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })); + } + function ensureFixedChunkSizePollingWatchFile() { + return fixedChunkSizePollingWatchFile || (fixedChunkSizePollingWatchFile = createFixedChunkSizePollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })); } function updateOptionsForWatchFile(options, useNonPollingWatchers) { if (options && options.watchFile !== undefined) @@ -7072,7 +7177,7 @@ var ts; // Use notifications from FS to watch with falling back to fs.watchFile generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) : // Default to do not use fixed polling interval - { watchFile: ts.WatchFileKind.FixedPollingInterval }; + { watchFile: (defaultWatchFileKind === null || defaultWatchFileKind === void 0 ? void 0 : defaultWatchFileKind()) || ts.WatchFileKind.FixedPollingInterval }; } } function generateWatchFileOptions(watchFile, fallbackPolling, options) { @@ -7113,6 +7218,10 @@ var ts; case ts.WatchDirectoryKind.DynamicPriorityPolling: return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, /*options*/ undefined); + case ts.WatchDirectoryKind.FixedChunkSizePolling: + return ensureFixedChunkSizePollingWatchFile()(directoryName, function () { return callback(directoryName); }, + /* pollingInterval */ undefined, + /*options*/ undefined); case ts.WatchDirectoryKind.UseFsEvents: return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), recursive, PollingInterval.Medium, ts.getFallbackOptions(watchDirectoryOptions)); default: @@ -7191,13 +7300,13 @@ var ts; } var activeSession; var profilePath = "./profile.cpuprofile"; - var realpathSync = (_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync; var Buffer = require("buffer").Buffer; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + var realpathSync = useCaseSensitiveFileNames ? ((_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync) : _fs.realpathSync; var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); var getCurrentDirectory = ts.memoize(function () { return process.cwd(); }); var _c = createSystemWatchFunctions({ @@ -7218,6 +7327,7 @@ var ts; tscWatchFile: process.env.TSC_WATCHFILE, useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER, tscWatchDirectory: process.env.TSC_WATCHDIRECTORY, + defaultWatchFileKind: function () { var _a, _b; return (_b = (_a = sys).defaultWatchFileKind) === null || _b === void 0 ? void 0 : _b.call(_a); }, }), watchFile = _c.watchFile, watchDirectory = _c.watchDirectory; var nodeSystem = { args: process.argv.slice(2), @@ -7286,6 +7396,7 @@ var ts; }, enableCPUProfiler: enableCPUProfiler, disableCPUProfiler: disableCPUProfiler, + cpuProfilingEnabled: function () { return !!activeSession || ts.contains(process.execArgv, "--cpu-prof") || ts.contains(process.execArgv, "--prof"); }, realpath: realpath, debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -7535,7 +7646,7 @@ var ts; return event === "rename" && (!relativeName || relativeName === lastDirectoryPart || - relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) && + (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && !fileSystemEntryExists(fileOrDirectory, entryKind) ? invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : callback(event, relativeName); @@ -7845,7 +7956,7 @@ var ts; Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1103, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103", "'for await' loops are only allowed within async functions and at the top levels of modules."), A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), @@ -7894,7 +8005,7 @@ var ts; A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), - A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_1166", "A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type."), A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), @@ -7954,7 +8065,7 @@ var ts; A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), - An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231", "An export assignment must be at the top level of a file or module declaration."), An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), @@ -7980,6 +8091,7 @@ var ts; A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1258, ts.DiagnosticCategory.Error, "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258", "A default export must be at the top level of a file or module declaration."), Module_0_can_only_be_default_imported_using_the_1_flag: diag(1259, ts.DiagnosticCategory.Error, "Module_0_can_only_be_default_imported_using_the_1_flag_1259", "Module '{0}' can only be default-imported using the '{1}' flag"), Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), @@ -8066,7 +8178,7 @@ var ts; Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), Provides_a_root_package_name_when_using_outFile_with_declarations: diag(1390, ts.DiagnosticCategory.Message, "Provides_a_root_package_name_when_using_outFile_with_declarations_1390", "Provides a root package name when using outFile with declarations."), - The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The `bundledPackageName` option must be provided when using outFile and node module resolution with declaration emit."), + The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The 'bundledPackageName' option must be provided when using outFile and node module resolution with declaration emit."), An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), @@ -8106,6 +8218,9 @@ var ts; File_is_output_of_project_reference_source_0: diag(1428, ts.DiagnosticCategory.Message, "File_is_output_of_project_reference_source_0_1428", "File is output of project reference source '{0}'"), File_redirects_to_file_0: diag(1429, ts.DiagnosticCategory.Message, "File_redirects_to_file_0_1429", "File redirects to file '{0}'"), The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), + for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), + Decorators_may_not_be_applied_to_this_parameters: diag(1433, ts.DiagnosticCategory.Error, "Decorators_may_not_be_applied_to_this_parameters_1433", "Decorators may not be applied to 'this' parameters."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -8173,7 +8288,7 @@ var ts; The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), - The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_in_expression_must_not_be_a_primitive: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_not_be_a_primitive_2361", "The right-hand side of an 'in' expression must not be a primitive."), The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), @@ -8191,8 +8306,7 @@ var ts; A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers."), Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), - Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."), - get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."), + The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type: diag(2380, ts.DiagnosticCategory.Error, "The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type_2380", "The return type of a 'get' accessor must be assignable to its 'set' accessor type"), A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."), Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."), Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), @@ -8255,7 +8369,7 @@ var ts; Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), - Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_cl_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'. This is an instance of class '{2}'."), The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), @@ -8355,14 +8469,13 @@ var ts; The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the `lib` compiler option to '{2}' or later."), + Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{2}' or later."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), - Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), - Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), + A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter: diag(2556, ts.DiagnosticCategory.Error, "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556", "A spread argument must either have a tuple type or be passed to a rest parameter."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), @@ -8385,17 +8498,17 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to '{1}' or later."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{1}' or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later."), Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."), Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add `node` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add `jquery` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add 'jquery' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), @@ -8428,6 +8541,12 @@ var ts; Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target: diag(2625, ts.DiagnosticCategory.Error, "Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target_2625", "Variadic element at position {0} in source does not match element at position {1} in target."), Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target: diag(2626, ts.DiagnosticCategory.Error, "Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target_2626", "Type at position {0} in source is not compatible with type at position {1} in target."), Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target: diag(2627, ts.DiagnosticCategory.Error, "Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target_2627", "Type at positions {0} through {1} in source is not compatible with type at position {2} in target."), + Cannot_assign_to_0_because_it_is_an_enum: diag(2628, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_an_enum_2628", "Cannot assign to '{0}' because it is an enum."), + Cannot_assign_to_0_because_it_is_a_class: diag(2629, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_class_2629", "Cannot assign to '{0}' because it is a class."), + Cannot_assign_to_0_because_it_is_a_function: diag(2630, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_function_2630", "Cannot assign to '{0}' because it is a function."), + Cannot_assign_to_0_because_it_is_a_namespace: diag(2631, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_namespace_2631", "Cannot assign to '{0}' because it is a namespace."), + Cannot_assign_to_0_because_it_is_an_import: diag(2632, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_an_import_2632", "Cannot assign to '{0}' because it is an import."), + JSX_property_access_expressions_cannot_include_JSX_namespace_names: diag(2633, ts.DiagnosticCategory.Error, "JSX_property_access_expressions_cannot_include_JSX_namespace_names_2633", "JSX property access expressions cannot include JSX namespace names"), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -8474,7 +8593,7 @@ var ts; Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), @@ -8482,14 +8601,14 @@ var ts; _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a 'delete' operator must be a property reference."), The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a 'delete' operator cannot be a read-only property."), - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), - A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), - A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), @@ -8551,7 +8670,7 @@ var ts; The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."), Overload_0_of_1_2_gave_the_following_error: diag(2772, ts.DiagnosticCategory.Error, "Overload_0_of_1_2_gave_the_following_error_2772", "Overload {0} of {1}, '{2}', gave the following error."), Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"), - This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it__2774", "This condition will always return true since the function is always defined. Did you mean to call it instead?"), + This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774", "This condition will always return true since this function is always defined. Did you mean to call it instead?"), Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation: diag(2775, ts.DiagnosticCategory.Error, "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775", "Assertions require every name in the call target to be declared with an explicit type annotation."), Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name: diag(2776, ts.DiagnosticCategory.Error, "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776", "Assertions require the call target to be an identifier or qualified name."), The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access: diag(2777, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777", "The operand of an increment or decrement operator may not be an optional property access."), @@ -8575,6 +8694,21 @@ var ts; The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types: diag(2795, ts.DiagnosticCategory.Error, "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795", "The 'intrinsic' keyword can only be used to declare compiler provided intrinsic types."), It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked: diag(2796, ts.DiagnosticCategory.Error, "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796", "It is likely that you are missing a comma to separate these two template expressions. They form a tagged template expression which cannot be invoked."), A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract: diag(2797, ts.DiagnosticCategory.Error, "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797", "A mixin class that extends from a type variable containing an abstract construct signature must also be declared 'abstract'."), + The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), + Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), + Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), + This_condition_will_always_return_true_since_this_0_is_always_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_is_always_defined_2801", "This condition will always return true since this '{0}' is always defined."), + Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher: diag(2802, ts.DiagnosticCategory.Error, "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802", "Type '{0}' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher."), + Cannot_assign_to_private_method_0_Private_methods_are_not_writable: diag(2803, ts.DiagnosticCategory.Error, "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803", "Cannot assign to private method '{0}'. Private methods are not writable."), + Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name: diag(2804, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804", "Duplicate identifier '{0}'. Static and instance elements cannot share the same private name."), + Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag: diag(2805, ts.DiagnosticCategory.Error, "Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_no_2805", "Static fields with private names can't have initializers when the '--useDefineForClassFields' flag is not specified with a '--target' of 'esnext'. Consider adding the '--useDefineForClassFields' flag."), + Private_accessor_was_defined_without_a_getter: diag(2806, ts.DiagnosticCategory.Error, "Private_accessor_was_defined_without_a_getter_2806", "Private accessor was defined without a getter."), + This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0: diag(2807, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807", "This syntax requires an imported helper named '{1}' with {2} parameters, which is not compatible with the one in '{0}'. Consider upgrading your version of '{0}'."), + A_get_accessor_must_be_at_least_as_accessible_as_the_setter: diag(2808, ts.DiagnosticCategory.Error, "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808", "A get accessor must be at least as accessible as the setter"), + Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses: diag(2809, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809", "Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses."), + Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false: diag(2810, ts.DiagnosticCategory.Error, "Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnex_2810", "Property '{0}' may not be used in a static property's initializer in the same class when 'target' is 'esnext' and 'useDefineForClassFields' is 'false'."), + Initializer_for_property_0: diag(2811, ts.DiagnosticCategory.Error, "Initializer_for_property_0_2811", "Initializer for property '{0}'"), + Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom: diag(2812, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812", "Property '{0}' does not exist on type '{1}'. Try changing the 'lib' compiler option to include 'dom'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -8647,6 +8781,7 @@ var ts; Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2: diag(4084, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084", "Exported type alias '{0}' has or is using private name '{1}' from module {2}."), Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), @@ -8668,6 +8803,11 @@ var ts; Type_arguments_for_0_circularly_reference_themselves: diag(4109, ts.DiagnosticCategory.Error, "Type_arguments_for_0_circularly_reference_themselves_4109", "Type arguments for '{0}' circularly reference themselves."), Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."), Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0: diag(4111, ts.DiagnosticCategory.Error, "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111", "Property '{0}' comes from an index signature, so it must be accessed with ['{0}']."), + This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class: diag(4112, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112", "This member cannot have an 'override' modifier because its containing class '{0}' does not extend another class."), + This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0: diag(4113, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113", "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'."), + This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0: diag(4114, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114", "This member must have an 'override' modifier because it overrides a member in the base class '{0}'."), + This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115", "This parameter property must have an 'override' modifier because it overrides a member in base class '{0}'."), + This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0: diag(4116, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116", "This member must have an 'override' modifier because it overrides an abstract method that is declared in the base class '{0}'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -8702,7 +8842,7 @@ var ts; Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), - Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option `--tsBuildInfoFile` is specified."), + Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option '--tsBuildInfoFile' is specified."), _0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2: diag(5075, ts.DiagnosticCategory.Error, "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075", "'{0}' is assignable to the constraint of type '{1}', but '{1}' could be instantiated with a different subtype of constraint '{2}'."), _0_and_1_operations_cannot_be_mixed_without_parentheses: diag(5076, ts.DiagnosticCategory.Error, "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076", "'{0}' and '{1}' operations cannot be mixed without parentheses."), Unknown_build_option_0_Did_you_mean_1: diag(5077, ts.DiagnosticCategory.Error, "Unknown_build_option_0_Did_you_mean_1_5077", "Unknown build option '{0}'. Did you mean '{1}'?"), @@ -8715,10 +8855,14 @@ var ts; Tuple_members_must_all_have_names_or_all_not_have_names: diag(5084, ts.DiagnosticCategory.Error, "Tuple_members_must_all_have_names_or_all_not_have_names_5084", "Tuple members must all have names or all not have names."), A_tuple_member_cannot_be_both_optional_and_rest: diag(5085, ts.DiagnosticCategory.Error, "A_tuple_member_cannot_be_both_optional_and_rest_5085", "A tuple member cannot be both optional and rest."), A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type: diag(5086, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086", "A labeled tuple element is declared as optional with a question mark after the name and before the colon, rather than after the type."), - A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a `...` before the name, rather than before the type."), + A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a '...' before the name, rather than before the type."), The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), + Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."), + The_root_value_of_a_0_file_must_be_an_object: diag(5092, ts.DiagnosticCategory.Error, "The_root_value_of_a_0_file_must_be_an_object_5092", "The root value of a '{0}' file must be an object."), + Compiler_option_0_may_only_be_used_with_build: diag(5093, ts.DiagnosticCategory.Error, "Compiler_option_0_may_only_be_used_with_build_5093", "Compiler option '--{0}' may only be used with '--build'."), + Compiler_option_0_may_not_be_used_with_build: diag(5094, ts.DiagnosticCategory.Error, "Compiler_option_0_may_not_be_used_with_build_5094", "Compiler option '--{0}' may not be used with '--build'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -8734,7 +8878,7 @@ var ts; Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), @@ -8929,9 +9073,9 @@ var ts; Emit_class_fields_with_Define_instead_of_Set: diag(6222, ts.DiagnosticCategory.Message, "Emit_class_fields_with_Define_instead_of_Set_6222", "Emit class fields with Define instead of Set."), Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."), Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."), - Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."), - Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling'."), - Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority'."), + Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."), + Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling'."), + Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority_FixedChunkSize: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority', 'FixedChunkSize'."), Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively: diag(6228, ts.DiagnosticCategory.Message, "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6228", "Synchronously call callbacks and update the state of directory watchers on platforms that don't support recursive watching natively."), Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3: diag(6229, ts.DiagnosticCategory.Error, "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229", "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'."), Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."), @@ -8942,7 +9086,11 @@ var ts; Disable_loading_referenced_projects: diag(6235, ts.DiagnosticCategory.Message, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."), Arguments_for_the_rest_parameter_0_were_not_provided: diag(6236, ts.DiagnosticCategory.Error, "Arguments_for_the_rest_parameter_0_were_not_provided_6236", "Arguments for the rest parameter '{0}' were not provided."), Generates_an_event_trace_and_a_list_of_types: diag(6237, ts.DiagnosticCategory.Message, "Generates_an_event_trace_and_a_list_of_types_6237", "Generates an event trace and a list of types."), - Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the `jsx` and `jsxs` factory functions from. eg, react"), + Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the 'jsx' and 'jsxs' factory functions from. eg, react"), + File_0_exists_according_to_earlier_cached_lookups: diag(6239, ts.DiagnosticCategory.Message, "File_0_exists_according_to_earlier_cached_lookups_6239", "File '{0}' exists according to earlier cached lookups."), + File_0_does_not_exist_according_to_earlier_cached_lookups: diag(6240, ts.DiagnosticCategory.Message, "File_0_does_not_exist_according_to_earlier_cached_lookups_6240", "File '{0}' does not exist according to earlier cached lookups."), + Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1: diag(6241, ts.DiagnosticCategory.Message, "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241", "Resolution for type reference directive '{0}' was found in cache from location '{1}'."), + Resolving_type_reference_directive_0_containing_file_1: diag(6242, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_6242", "======== Resolving type reference directive '{0}', containing file '{1}'. ========"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -8987,16 +9135,19 @@ var ts; Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382", "Skipping build of project '{0}' because its dependency '{1}' was not built"), Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383", "Project '{0}' can't be built because its dependency '{1}' was not built"), Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, ts.DiagnosticCategory.Message, "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384", "Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it."), - _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), + The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + Project_0_is_being_forcibly_rebuilt: diag(6388, ts.DiagnosticCategory.Message, "Project_0_is_being_forcibly_rebuilt_6388", "Project '{0}' is being forcibly rebuilt"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option: diag(6504, ts.DiagnosticCategory.Error, "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504", "File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?"), Print_names_of_files_and_the_reason_they_are_part_of_the_compilation: diag(6505, ts.DiagnosticCategory.Message, "Print_names_of_files_and_the_reason_they_are_part_of_the_compilation_6505", "Print names of files and the reason they are part of the compilation."), - Require_undeclared_properties_from_index_signatures_to_use_element_accesses: diag(6803, ts.DiagnosticCategory.Error, "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803", "Require undeclared properties from index signatures to use element accesses."), Include_undefined_in_index_signature_results: diag(6800, ts.DiagnosticCategory.Message, "Include_undefined_in_index_signature_results_6800", "Include 'undefined' in index signature results"), + Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier: diag(6801, ts.DiagnosticCategory.Message, "Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier_6801", "Ensure overriding members in derived classes are marked with an 'override' modifier."), + Require_undeclared_properties_from_index_signatures_to_use_element_accesses: diag(6802, ts.DiagnosticCategory.Message, "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6802", "Require undeclared properties from index signatures to use element accesses."), 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."), @@ -9029,7 +9180,7 @@ var ts; Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), - If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'"), The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), @@ -9069,7 +9220,7 @@ var ts; JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), - Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one '@augments' or '@extends' tag."), Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), @@ -9314,6 +9465,10 @@ var ts; Add_all_missing_function_declarations: diag(95157, ts.DiagnosticCategory.Message, "Add_all_missing_function_declarations_95157", "Add all missing function declarations"), Method_not_implemented: diag(95158, ts.DiagnosticCategory.Message, "Method_not_implemented_95158", "Method not implemented."), Function_not_implemented: diag(95159, ts.DiagnosticCategory.Message, "Function_not_implemented_95159", "Function not implemented."), + Add_override_modifier: diag(95160, ts.DiagnosticCategory.Message, "Add_override_modifier_95160", "Add 'override' modifier"), + Remove_override_modifier: diag(95161, ts.DiagnosticCategory.Message, "Remove_override_modifier_95161", "Remove 'override' modifier"), + Add_all_missing_override_modifiers: diag(95162, ts.DiagnosticCategory.Message, "Add_all_missing_override_modifiers_95162", "Add all missing 'override' modifiers"), + Remove_all_unnecessary_override_modifiers: diag(95163, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_override_modifiers_95163", "Remove all unnecessary 'override' modifiers"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -9328,8 +9483,6 @@ var ts; The_shadowing_declaration_of_0_is_defined_here: diag(18017, ts.DiagnosticCategory.Error, "The_shadowing_declaration_of_0_is_defined_here_18017", "The shadowing declaration of '{0}' is defined here"), The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here: diag(18018, ts.DiagnosticCategory.Error, "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018", "The declaration of '{0}' that you probably intended to use is defined here"), _0_modifier_cannot_be_used_with_a_private_identifier: diag(18019, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_private_identifier_18019", "'{0}' modifier cannot be used with a private identifier."), - A_method_cannot_be_named_with_a_private_identifier: diag(18022, ts.DiagnosticCategory.Error, "A_method_cannot_be_named_with_a_private_identifier_18022", "A method cannot be named with a private identifier."), - An_accessor_cannot_be_named_with_a_private_identifier: diag(18023, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_named_with_a_private_identifier_18023", "An accessor cannot be named with a private identifier."), An_enum_member_cannot_be_named_with_a_private_identifier: diag(18024, ts.DiagnosticCategory.Error, "An_enum_member_cannot_be_named_with_a_private_identifier_18024", "An enum member cannot be named with a private identifier."), can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), Compiler_reserves_name_0_when_emitting_private_identifier_downlevel: diag(18027, ts.DiagnosticCategory.Error, "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027", "Compiler reserves name '{0}' when emitting private identifier downlevel."), @@ -9341,6 +9494,7 @@ var ts; Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead: diag(18033, ts.DiagnosticCategory.Error, "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033", "Only numeric enums can have computed members, but this expression has type '{0}'. If you do not need exhaustiveness checks, consider using an object literal instead."), Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compiler_option_is_specified_e_g_Fragment: diag(18034, ts.DiagnosticCategory.Message, "Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compi_18034", "Specify the JSX fragment factory function to use when targeting 'react' JSX emit with 'jsxFactory' compiler option is specified, e.g. 'Fragment'."), Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(18035, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name_18035", "Invalid value for 'jsxFragmentFactory'. '{0}' is not a valid identifier or qualified-name."), + Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator: diag(18036, ts.DiagnosticCategory.Error, "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036", "Class decorators can't be used with static private identifier. Consider removing the experimental decorator."), }; })(ts || (ts = {})); var ts; @@ -9408,6 +9562,7 @@ var ts; _a.private = 120 /* PrivateKeyword */, _a.protected = 121 /* ProtectedKeyword */, _a.public = 122 /* PublicKeyword */, + _a.override = 156 /* OverrideKeyword */, _a.readonly = 142 /* ReadonlyKeyword */, _a.require = 143 /* RequireKeyword */, _a.global = 154 /* GlobalKeyword */, @@ -9434,7 +9589,7 @@ var ts; _a.yield = 124 /* YieldKeyword */, _a.async = 129 /* AsyncKeyword */, _a.await = 130 /* AwaitKeyword */, - _a.of = 156 /* OfKeyword */, + _a.of = 157 /* OfKeyword */, _a); var textToKeyword = new ts.Map(ts.getEntries(textToKeywordObj)); var textToToken = new ts.Map(ts.getEntries(__assign(__assign({}, textToKeywordObj), { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 29 /* LessThanToken */, ">": 31 /* GreaterThanToken */, "<=": 32 /* LessThanEqualsToken */, ">=": 33 /* GreaterThanEqualsToken */, "==": 34 /* EqualsEqualsToken */, "!=": 35 /* ExclamationEqualsToken */, "===": 36 /* EqualsEqualsEqualsToken */, "!==": 37 /* ExclamationEqualsEqualsToken */, "=>": 38 /* EqualsGreaterThanToken */, "+": 39 /* PlusToken */, "-": 40 /* MinusToken */, "**": 42 /* AsteriskAsteriskToken */, "*": 41 /* AsteriskToken */, "/": 43 /* SlashToken */, "%": 44 /* PercentToken */, "++": 45 /* PlusPlusToken */, "--": 46 /* MinusMinusToken */, "<<": 47 /* LessThanLessThanToken */, ">": 48 /* GreaterThanGreaterThanToken */, ">>>": 49 /* GreaterThanGreaterThanGreaterThanToken */, "&": 50 /* AmpersandToken */, "|": 51 /* BarToken */, "^": 52 /* CaretToken */, "!": 53 /* ExclamationToken */, "~": 54 /* TildeToken */, "&&": 55 /* AmpersandAmpersandToken */, "||": 56 /* BarBarToken */, "?": 57 /* QuestionToken */, "??": 60 /* QuestionQuestionToken */, "?.": 28 /* QuestionDotToken */, ":": 58 /* ColonToken */, "=": 62 /* EqualsToken */, "+=": 63 /* PlusEqualsToken */, "-=": 64 /* MinusEqualsToken */, "*=": 65 /* AsteriskEqualsToken */, "**=": 66 /* AsteriskAsteriskEqualsToken */, "/=": 67 /* SlashEqualsToken */, "%=": 68 /* PercentEqualsToken */, "<<=": 69 /* LessThanLessThanEqualsToken */, ">>=": 70 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 72 /* AmpersandEqualsToken */, "|=": 73 /* BarEqualsToken */, "^=": 77 /* CaretEqualsToken */, "||=": 74 /* BarBarEqualsToken */, "&&=": 75 /* AmpersandAmpersandEqualsToken */, "??=": 76 /* QuestionQuestionEqualsToken */, "@": 59 /* AtToken */, "`": 61 /* BacktickToken */ }))); @@ -9750,11 +9905,11 @@ var ts; } ts.couldStartTrivia = couldStartTrivia; /* @internal */ - function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { - if (stopAtComments === void 0) { stopAtComments = false; } + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments, inJSDoc) { if (ts.positionIsSynthesized(pos)) { return pos; } + var canConsumeStar = false; // Keep in sync with couldStartTrivia while (true) { var ch = text.charCodeAt(pos); @@ -9769,6 +9924,7 @@ var ts; if (stopAfterLineBreak) { return pos; } + canConsumeStar = !!inJSDoc; continue; case 9 /* tab */: case 11 /* verticalTab */: @@ -9788,6 +9944,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { @@ -9799,6 +9956,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } break; @@ -9808,12 +9966,21 @@ var ts; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos); + canConsumeStar = false; continue; } break; case 35 /* hash */: if (pos === 0 && isShebangTrivia(text, pos)) { pos = scanShebangTrivia(text, pos); + canConsumeStar = false; + continue; + } + break; + case 42 /* asterisk */: + if (canConsumeStar) { + pos++; + canConsumeStar = false; continue; } break; @@ -10118,6 +10285,7 @@ var ts; reScanJsxToken: reScanJsxToken, reScanLessThanToken: reScanLessThanToken, reScanQuestionToken: reScanQuestionToken, + reScanInvalidIdentifier: reScanInvalidIdentifier, scanJsxToken: scanJsxToken, scanJsDocToken: scanJsDocToken, scan: scan, @@ -11120,15 +11288,9 @@ var ts; } return token = 79 /* PrivateIdentifier */; default: - if (isIdentifierStart(ch, languageVersion)) { - pos += charSize(ch); - while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) - pos += charSize(ch); - tokenValue = text.substring(tokenPos, pos); - if (ch === 92 /* backslash */) { - tokenValue += scanIdentifierParts(); - } - return token = getIdentifierToken(); + var identifierKind = scanIdentifier(ch, languageVersion); + if (identifierKind) { + return token = identifierKind; } else if (isWhiteSpaceSingleLine(ch)) { pos += charSize(ch); @@ -11145,6 +11307,31 @@ var ts; } } } + function reScanInvalidIdentifier() { + ts.Debug.assert(token === 0 /* Unknown */, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'."); + pos = tokenPos = startPos; + tokenFlags = 0; + var ch = codePointAt(text, pos); + var identifierKind = scanIdentifier(ch, 99 /* ESNext */); + if (identifierKind) { + return token = identifierKind; + } + pos += charSize(ch); + return token; // Still `SyntaKind.Unknown` + } + function scanIdentifier(startCharacter, languageVersion) { + var ch = startCharacter; + if (isIdentifierStart(ch, languageVersion)) { + pos += charSize(ch); + while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) + pos += charSize(ch); + tokenValue = text.substring(tokenPos, pos); + if (ch === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return getIdentifierToken(); + } + } function reScanGreaterToken() { if (token === 31 /* GreaterThanToken */) { if (text.charCodeAt(pos) === 62 /* greaterThan */) { @@ -11257,9 +11444,10 @@ var ts; pos = tokenPos; return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true); } - function reScanJsxToken() { + function reScanJsxToken(allowMultilineJsxText) { + if (allowMultilineJsxText === void 0) { allowMultilineJsxText = true; } pos = tokenPos = startPos; - return token = scanJsxToken(); + return token = scanJsxToken(allowMultilineJsxText); } function reScanLessThanToken() { if (token === 47 /* LessThanLessThanToken */) { @@ -11273,7 +11461,8 @@ var ts; pos = tokenPos + 1; return token = 57 /* QuestionToken */; } - function scanJsxToken() { + function scanJsxToken(allowMultilineJsxText) { + if (allowMultilineJsxText === void 0) { allowMultilineJsxText = true; } startPos = tokenPos = pos; if (pos >= end) { return token = 1 /* EndOfFileToken */; @@ -11293,15 +11482,9 @@ var ts; } // First non-whitespace character on this line. var firstNonWhitespace = 0; - var lastNonWhitespace = -1; // These initial values are special because the first line is: // firstNonWhitespace = 0 to indicate that we want leading whitespace, while (pos < end) { - // We want to keep track of the last non-whitespace (but including - // newlines character for hitting the end of the JSX Text region) - if (!isWhiteSpaceSingleLine(char)) { - lastNonWhitespace = pos; - } char = text.charCodeAt(pos); if (char === 123 /* openBrace */) { break; @@ -11319,8 +11502,6 @@ var ts; if (char === 125 /* closeBrace */) { error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1); } - if (lastNonWhitespace > 0) - lastNonWhitespace++; // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces. // i.e (- : whitespace) //
---- @@ -11330,13 +11511,17 @@ var ts; if (isLineBreak(char) && firstNonWhitespace === 0) { firstNonWhitespace = -1; } + else if (!allowMultilineJsxText && isLineBreak(char) && firstNonWhitespace > 0) { + // Stop JsxText on each line during formatting. This allows the formatter to + // indent each line correctly. + break; + } else if (!isWhiteSpaceLike(char)) { firstNonWhitespace = pos; } pos++; } - var endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace; - tokenValue = text.substring(startPos, endPosition); + tokenValue = text.substring(startPos, pos); return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */; } // Scans a JSX identifier; these differ from normal identifiers in that @@ -11359,6 +11544,7 @@ var ts; tokenValue += ":"; pos++; namespaceSeparator = true; + token = 78 /* Identifier */; // swap from keyword kind to identifier kind continue; } var oldPos = pos; @@ -11615,6 +11801,8 @@ var ts; switch (options.target) { case 99 /* ESNext */: return "lib.esnext.full.d.ts"; + case 8 /* ES2021 */: + return "lib.es2021.full.d.ts"; case 7 /* ES2020 */: return "lib.es2020.full.d.ts"; case 6 /* ES2019 */: @@ -11833,9 +12021,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 159 /* TypeParameter */) { + if (d && d.kind === 160 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (isFunctionLike(current) || isClassLike(current) || current.kind === 253 /* InterfaceDeclaration */) { + if (isFunctionLike(current) || isClassLike(current) || current.kind === 254 /* InterfaceDeclaration */) { return current; } } @@ -11843,7 +12031,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node, parent) { - return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 166 /* Constructor */; + return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) && parent.kind === 167 /* Constructor */; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -11873,14 +12061,14 @@ var ts; node = walkUpBindingElementsAndPatterns(node); } var flags = getFlags(node); - if (node.kind === 249 /* VariableDeclaration */) { + if (node.kind === 250 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 250 /* VariableDeclarationList */) { + if (node && node.kind === 251 /* VariableDeclarationList */) { flags |= getFlags(node); node = node.parent; } - if (node && node.kind === 232 /* VariableStatement */) { + if (node && node.kind === 233 /* VariableStatement */) { flags |= getFlags(node); } return flags; @@ -11898,19 +12086,22 @@ var ts; // nodes like variable declarations and binding elements can returned a view of their flags // that includes the modifiers from their container. i.e. flags like export/declare aren't // stored on the variable declaration directly, but on the containing variable statement - // (if it has one). Similarly, flags for let/const are store on the variable declaration + // (if it has one). Similarly, flags for let/const are stored on the variable declaration // list. By calling this function, all those flags are combined so that the client can treat // the node as if it actually had those flags. function getCombinedNodeFlags(node) { return getCombinedFlags(node, function (n) { return n.flags; }); } ts.getCombinedNodeFlags = getCombinedNodeFlags; + /* @internal */ + ts.supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; /** * Checks to see if the locale is in the appropriate format, * and if it is, attempts to set the appropriate language. */ function validateLocaleAndSetLanguage(locale, sys, errors) { - var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + var lowerCaseLocale = locale.toLowerCase(); + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale); if (!matchResult) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); @@ -11921,7 +12112,7 @@ var ts; var territory = matchResult[3]; // First try the entire locale, then fall back to just language if that's all we have. // Either ways do not fail, and fallback to the English diagnostic strings. - if (!trySetLanguageAndTerritory(language, territory, errors)) { + if (ts.contains(ts.supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) { trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); } // Set the UI locale for string collation @@ -12028,7 +12219,7 @@ var ts; } ts.idText = idText; function symbolName(symbol) { - if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) { + if (symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) { return idText(symbol.valueDeclaration.name); } return unescapeLeadingUnderscores(symbol.escapedName); @@ -12050,30 +12241,30 @@ var ts; } // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } break; - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: var expr = hostNode.expression; - if (expr.kind === 216 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) { + if (expr.kind === 217 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) { expr = expr.left; } switch (expr.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return expr.name; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; } } break; - case 207 /* ParenthesizedExpression */: { + case 208 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } - case 245 /* LabeledStatement */: { + case 246 /* LabeledStatement */: { if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } @@ -12110,16 +12301,16 @@ var ts; switch (declaration.kind) { case 78 /* Identifier */: return declaration; - case 333 /* JSDocPropertyTag */: - case 326 /* JSDocParameterTag */: { + case 337 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: { var name = declaration.name; - if (name.kind === 157 /* QualifiedName */) { + if (name.kind === 158 /* QualifiedName */) { return name.right; } break; } - case 203 /* CallExpression */: - case 216 /* BinaryExpression */: { + case 204 /* CallExpression */: + case 217 /* BinaryExpression */: { var expr_1 = declaration; switch (ts.getAssignmentDeclarationKind(expr_1)) { case 1 /* ExportsProperty */: @@ -12135,15 +12326,15 @@ var ts; return undefined; } } - case 331 /* JSDocTypedefTag */: + case 335 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); - case 325 /* JSDocEnumTag */: + case 329 /* JSDocEnumTag */: return nameForNamelessJSDocTypedef(declaration); - case 266 /* ExportAssignment */: { + case 267 /* ExportAssignment */: { var expression = declaration.expression; return ts.isIdentifier(expression) ? expression : undefined; } - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: var expr = declaration; if (ts.isBindableStaticElementAccessExpression(expr)) { return expr.argumentExpression; @@ -12156,7 +12347,7 @@ var ts; if (declaration === undefined) return undefined; return getNonAssignedNameOfDeclaration(declaration) || - (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + (ts.isFunctionExpression(declaration) || ts.isArrowFunction(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); } ts.getNameOfDeclaration = getNameOfDeclaration; /*@internal*/ @@ -12309,6 +12500,10 @@ var ts; return getFirstJSDocTag(node, ts.isJSDocReadonlyTag, /*noCache*/ true); } ts.getJSDocReadonlyTagNoCache = getJSDocReadonlyTagNoCache; + function getJSDocOverrideTagNoCache(node) { + return getFirstJSDocTag(node, ts.isJSDocOverrideTag, /*noCache*/ true); + } + ts.getJSDocOverrideTagNoCache = getJSDocOverrideTagNoCache; /** Gets the JSDoc deprecated tag for the node if present */ function getJSDocDeprecatedTag(node) { return getFirstJSDocTag(node, ts.isJSDocDeprecatedTag); @@ -12429,6 +12624,14 @@ var ts; return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + /** Gets the text of a jsdoc comment, flattening links to their text. */ + function getTextOfJSDocComment(comment) { + return typeof comment === "string" ? comment + : comment === null || comment === void 0 ? void 0 : comment.map(function (c) { + return c.kind === 313 /* JSDocText */ ? c.text : "{@link " + (c.name ? ts.entityNameToString(c.name) + " " : "") + c.text + "}"; + }).join(""); + } + ts.getTextOfJSDocComment = getTextOfJSDocComment; /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. @@ -12438,7 +12641,7 @@ var ts; return ts.emptyArray; } if (ts.isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 311 /* JSDocComment */); + ts.Debug.assert(node.parent.kind === 312 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } if (node.typeParameters) { @@ -12464,13 +12667,13 @@ var ts; } ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter; // #region - function isIdentifierOrPrivateIdentifier(node) { + function isMemberName(node) { return node.kind === 78 /* Identifier */ || node.kind === 79 /* PrivateIdentifier */; } - ts.isIdentifierOrPrivateIdentifier = isIdentifierOrPrivateIdentifier; + ts.isMemberName = isMemberName; /* @internal */ function isGetOrSetAccessorDeclaration(node) { - return node.kind === 168 /* SetAccessor */ || node.kind === 167 /* GetAccessor */; + return node.kind === 169 /* SetAccessor */ || node.kind === 168 /* GetAccessor */; } ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; function isPropertyAccessChain(node) { @@ -12488,10 +12691,10 @@ var ts; function isOptionalChain(node) { var kind = node.kind; return !!(node.flags & 32 /* OptionalChain */) && - (kind === 201 /* PropertyAccessExpression */ - || kind === 202 /* ElementAccessExpression */ - || kind === 203 /* CallExpression */ - || kind === 225 /* NonNullExpression */); + (kind === 202 /* PropertyAccessExpression */ + || kind === 203 /* ElementAccessExpression */ + || kind === 204 /* CallExpression */ + || kind === 226 /* NonNullExpression */); } ts.isOptionalChain = isOptionalChain; /* @internal */ @@ -12526,7 +12729,7 @@ var ts; } ts.isOutermostOptionalChain = isOutermostOptionalChain; function isNullishCoalesce(node) { - return node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */; + return node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */; } ts.isNullishCoalesce = isNullishCoalesce; function isConstTypeReference(node) { @@ -12543,17 +12746,17 @@ var ts; } ts.isNonNullChain = isNonNullChain; function isBreakOrContinueStatement(node) { - return node.kind === 241 /* BreakStatement */ || node.kind === 240 /* ContinueStatement */; + return node.kind === 242 /* BreakStatement */ || node.kind === 241 /* ContinueStatement */; } ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isNamedExportBindings(node) { - return node.kind === 269 /* NamespaceExport */ || node.kind === 268 /* NamedExports */; + return node.kind === 270 /* NamespaceExport */ || node.kind === 269 /* NamedExports */; } ts.isNamedExportBindings = isNamedExportBindings; function isUnparsedTextLike(node) { switch (node.kind) { - case 294 /* UnparsedText */: - case 295 /* UnparsedInternalText */: + case 295 /* UnparsedText */: + case 296 /* UnparsedInternalText */: return true; default: return false; @@ -12562,12 +12765,12 @@ var ts; ts.isUnparsedTextLike = isUnparsedTextLike; function isUnparsedNode(node) { return isUnparsedTextLike(node) || - node.kind === 292 /* UnparsedPrologue */ || - node.kind === 296 /* UnparsedSyntheticReference */; + node.kind === 293 /* UnparsedPrologue */ || + node.kind === 297 /* UnparsedSyntheticReference */; } ts.isUnparsedNode = isUnparsedNode; function isJSDocPropertyLikeTag(node) { - return node.kind === 333 /* JSDocPropertyTag */ || node.kind === 326 /* JSDocParameterTag */; + return node.kind === 337 /* JSDocPropertyTag */ || node.kind === 330 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; // #endregion @@ -12583,16 +12786,25 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 157 /* FirstNode */; + return kind >= 158 /* FirstNode */; } ts.isNodeKind = isNodeKind; + /** + * True if kind is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + function isTokenKind(kind) { + return kind >= 0 /* FirstToken */ && kind <= 157 /* LastToken */; + } + ts.isTokenKind = isTokenKind; /** * True if node is of some token syntax kind. * For example, this is true for an IfKeyword but not for an IfStatement. * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. */ function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 156 /* LastToken */; + return isTokenKind(n.kind); } ts.isToken = isToken; // Node Arrays @@ -12633,13 +12845,13 @@ var ts; ts.isImportOrExportSpecifier = isImportOrExportSpecifier; function isTypeOnlyImportOrExportDeclaration(node) { switch (node.kind) { - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return node.parent.parent.isTypeOnly; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return node.parent.isTypeOnly; - case 262 /* ImportClause */: - case 260 /* ImportEqualsDeclaration */: + case 263 /* ImportClause */: + case 261 /* ImportEqualsDeclaration */: return node.isTypeOnly; default: return false; @@ -12658,10 +12870,10 @@ var ts; ts.isGeneratedIdentifier = isGeneratedIdentifier; // Private Identifiers /*@internal*/ - function isPrivateIdentifierPropertyDeclaration(node) { - return ts.isPropertyDeclaration(node) && ts.isPrivateIdentifier(node.name); + function isPrivateIdentifierClassElementDeclaration(node) { + return (ts.isPropertyDeclaration(node) || isMethodOrAccessor(node)) && ts.isPrivateIdentifier(node.name); } - ts.isPrivateIdentifierPropertyDeclaration = isPrivateIdentifierPropertyDeclaration; + ts.isPrivateIdentifierClassElementDeclaration = isPrivateIdentifierClassElementDeclaration; /*@internal*/ function isPrivateIdentifierPropertyAccessExpression(node) { return ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name); @@ -12682,6 +12894,7 @@ var ts; case 121 /* ProtectedKeyword */: case 142 /* ReadonlyKeyword */: case 123 /* StaticKeyword */: + case 156 /* OverrideKeyword */: return true; } return false; @@ -12689,12 +12902,12 @@ var ts; ts.isModifierKind = isModifierKind; /* @internal */ function isParameterPropertyModifier(kind) { - return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + return !!(ts.modifierToFlag(kind) & 16476 /* ParameterPropertyModifier */); } ts.isParameterPropertyModifier = isParameterPropertyModifier; /* @internal */ function isClassMemberModifier(idToken) { - return isParameterPropertyModifier(idToken) || idToken === 123 /* StaticKeyword */; + return isParameterPropertyModifier(idToken) || idToken === 123 /* StaticKeyword */ || idToken === 156 /* OverrideKeyword */; } ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { @@ -12703,7 +12916,7 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 157 /* QualifiedName */ + return kind === 158 /* QualifiedName */ || kind === 78 /* Identifier */; } ts.isEntityName = isEntityName; @@ -12713,19 +12926,19 @@ var ts; || kind === 79 /* PrivateIdentifier */ || kind === 10 /* StringLiteral */ || kind === 8 /* NumericLiteral */ - || kind === 158 /* ComputedPropertyName */; + || kind === 159 /* ComputedPropertyName */; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; return kind === 78 /* Identifier */ - || kind === 196 /* ObjectBindingPattern */ - || kind === 197 /* ArrayBindingPattern */; + || kind === 197 /* ObjectBindingPattern */ + || kind === 198 /* ArrayBindingPattern */; } ts.isBindingName = isBindingName; // Functions function isFunctionLike(node) { - return node && isFunctionLikeKind(node.kind); + return !!node && isFunctionLikeKind(node.kind); } ts.isFunctionLike = isFunctionLike; /* @internal */ @@ -12735,13 +12948,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; default: return false; @@ -12750,14 +12963,14 @@ var ts; /* @internal */ function isFunctionLikeKind(kind) { switch (kind) { - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 313 /* JSDocSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 174 /* FunctionType */: - case 308 /* JSDocFunctionType */: - case 175 /* ConstructorType */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 315 /* JSDocSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 175 /* FunctionType */: + case 309 /* JSDocFunctionType */: + case 176 /* ConstructorType */: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -12772,29 +12985,29 @@ var ts; // Classes function isClassElement(node) { var kind = node.kind; - return kind === 166 /* Constructor */ - || kind === 163 /* PropertyDeclaration */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 171 /* IndexSignature */ - || kind === 229 /* SemicolonClassElement */; + return kind === 167 /* Constructor */ + || kind === 164 /* PropertyDeclaration */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 172 /* IndexSignature */ + || kind === 230 /* SemicolonClassElement */; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */); + return node && (node.kind === 253 /* ClassDeclaration */ || node.kind === 222 /* ClassExpression */); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 167 /* GetAccessor */ || node.kind === 168 /* SetAccessor */); + return node && (node.kind === 168 /* GetAccessor */ || node.kind === 169 /* SetAccessor */); } ts.isAccessor = isAccessor; /* @internal */ function isMethodOrAccessor(node) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return true; default: return false; @@ -12804,11 +13017,11 @@ var ts; // Type members function isTypeElement(node) { var kind = node.kind; - return kind === 170 /* ConstructSignature */ - || kind === 169 /* CallSignature */ - || kind === 162 /* PropertySignature */ - || kind === 164 /* MethodSignature */ - || kind === 171 /* IndexSignature */; + return kind === 171 /* ConstructSignature */ + || kind === 170 /* CallSignature */ + || kind === 163 /* PropertySignature */ + || kind === 165 /* MethodSignature */ + || kind === 172 /* IndexSignature */; } ts.isTypeElement = isTypeElement; function isClassOrTypeElement(node) { @@ -12817,12 +13030,12 @@ var ts; ts.isClassOrTypeElement = isClassOrTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 288 /* PropertyAssignment */ - || kind === 289 /* ShorthandPropertyAssignment */ - || kind === 290 /* SpreadAssignment */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 289 /* PropertyAssignment */ + || kind === 290 /* ShorthandPropertyAssignment */ + || kind === 291 /* SpreadAssignment */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; // Type @@ -12837,8 +13050,8 @@ var ts; ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return true; } return false; @@ -12849,8 +13062,8 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 197 /* ArrayBindingPattern */ - || kind === 196 /* ObjectBindingPattern */; + return kind === 198 /* ArrayBindingPattern */ + || kind === 197 /* ObjectBindingPattern */; } return false; } @@ -12858,15 +13071,15 @@ var ts; /* @internal */ function isAssignmentPattern(node) { var kind = node.kind; - return kind === 199 /* ArrayLiteralExpression */ - || kind === 200 /* ObjectLiteralExpression */; + return kind === 200 /* ArrayLiteralExpression */ + || kind === 201 /* ObjectLiteralExpression */; } ts.isAssignmentPattern = isAssignmentPattern; /* @internal */ function isArrayBindingElement(node) { var kind = node.kind; - return kind === 198 /* BindingElement */ - || kind === 222 /* OmittedExpression */; + return kind === 199 /* BindingElement */ + || kind === 223 /* OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; /** @@ -12875,9 +13088,9 @@ var ts; /* @internal */ function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: return true; } return false; @@ -12898,8 +13111,8 @@ var ts; /* @internal */ function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 196 /* ObjectBindingPattern */: - case 200 /* ObjectLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 201 /* ObjectLiteralExpression */: return true; } return false; @@ -12911,8 +13124,8 @@ var ts; /* @internal */ function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 197 /* ArrayBindingPattern */: - case 199 /* ArrayLiteralExpression */: + case 198 /* ArrayBindingPattern */: + case 200 /* ArrayLiteralExpression */: return true; } return false; @@ -12921,26 +13134,26 @@ var ts; /* @internal */ function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { var kind = node.kind; - return kind === 201 /* PropertyAccessExpression */ - || kind === 157 /* QualifiedName */ - || kind === 195 /* ImportType */; + return kind === 202 /* PropertyAccessExpression */ + || kind === 158 /* QualifiedName */ + || kind === 196 /* ImportType */; } ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; // Expression function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 201 /* PropertyAccessExpression */ - || kind === 157 /* QualifiedName */; + return kind === 202 /* PropertyAccessExpression */ + || kind === 158 /* QualifiedName */; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 205 /* TaggedTemplateExpression */: - case 161 /* Decorator */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 206 /* TaggedTemplateExpression */: + case 162 /* Decorator */: return true; default: return false; @@ -12948,12 +13161,12 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 203 /* CallExpression */ || node.kind === 204 /* NewExpression */; + return node.kind === 204 /* CallExpression */ || node.kind === 205 /* NewExpression */; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 218 /* TemplateExpression */ + return kind === 219 /* TemplateExpression */ || kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; @@ -12964,33 +13177,33 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: - case 204 /* NewExpression */: - case 203 /* CallExpression */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: - case 205 /* TaggedTemplateExpression */: - case 199 /* ArrayLiteralExpression */: - case 207 /* ParenthesizedExpression */: - case 200 /* ObjectLiteralExpression */: - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 205 /* NewExpression */: + case 204 /* CallExpression */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: + case 206 /* TaggedTemplateExpression */: + case 200 /* ArrayLiteralExpression */: + case 208 /* ParenthesizedExpression */: + case 201 /* ObjectLiteralExpression */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: case 78 /* Identifier */: case 13 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: case 9 /* BigIntLiteral */: case 10 /* StringLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: case 94 /* FalseKeyword */: case 103 /* NullKeyword */: case 107 /* ThisKeyword */: case 109 /* TrueKeyword */: case 105 /* SuperKeyword */: - case 225 /* NonNullExpression */: - case 226 /* MetaProperty */: + case 226 /* NonNullExpression */: + case 227 /* MetaProperty */: case 99 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression return true; default: @@ -13004,13 +13217,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: - case 210 /* DeleteExpression */: - case 211 /* TypeOfExpression */: - case 212 /* VoidExpression */: - case 213 /* AwaitExpression */: - case 206 /* TypeAssertionExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 211 /* DeleteExpression */: + case 212 /* TypeOfExpression */: + case 213 /* VoidExpression */: + case 214 /* AwaitExpression */: + case 207 /* TypeAssertionExpression */: return true; default: return isLeftHandSideExpressionKind(kind); @@ -13019,9 +13232,9 @@ var ts; /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return true; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */; default: @@ -13040,15 +13253,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 217 /* ConditionalExpression */: - case 219 /* YieldExpression */: - case 209 /* ArrowFunction */: - case 216 /* BinaryExpression */: - case 220 /* SpreadElement */: - case 224 /* AsExpression */: - case 222 /* OmittedExpression */: - case 337 /* CommaListExpression */: - case 336 /* PartiallyEmittedExpression */: + case 218 /* ConditionalExpression */: + case 220 /* YieldExpression */: + case 210 /* ArrowFunction */: + case 217 /* BinaryExpression */: + case 221 /* SpreadElement */: + case 225 /* AsExpression */: + case 223 /* OmittedExpression */: + case 341 /* CommaListExpression */: + case 340 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -13056,8 +13269,8 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 206 /* TypeAssertionExpression */ - || kind === 224 /* AsExpression */; + return kind === 207 /* TypeAssertionExpression */ + || kind === 225 /* AsExpression */; } ts.isAssertionExpression = isAssertionExpression; /* @internal */ @@ -13068,13 +13281,13 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return true; - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -13103,7 +13316,7 @@ var ts; ts.isExternalModuleIndicator = isExternalModuleIndicator; /* @internal */ function isForInOrOfStatement(node) { - return node.kind === 238 /* ForInStatement */ || node.kind === 239 /* ForOfStatement */; + return node.kind === 239 /* ForInStatement */ || node.kind === 240 /* ForOfStatement */; } ts.isForInOrOfStatement = isForInOrOfStatement; // Element @@ -13127,114 +13340,114 @@ var ts; /* @internal */ function isModuleBody(node) { var kind = node.kind; - return kind === 257 /* ModuleBlock */ - || kind === 256 /* ModuleDeclaration */ + return kind === 258 /* ModuleBlock */ + || kind === 257 /* ModuleDeclaration */ || kind === 78 /* Identifier */; } ts.isModuleBody = isModuleBody; /* @internal */ function isNamespaceBody(node) { var kind = node.kind; - return kind === 257 /* ModuleBlock */ - || kind === 256 /* ModuleDeclaration */; + return kind === 258 /* ModuleBlock */ + || kind === 257 /* ModuleDeclaration */; } ts.isNamespaceBody = isNamespaceBody; /* @internal */ function isJSDocNamespaceBody(node) { var kind = node.kind; return kind === 78 /* Identifier */ - || kind === 256 /* ModuleDeclaration */; + || kind === 257 /* ModuleDeclaration */; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; /* @internal */ function isNamedImportBindings(node) { var kind = node.kind; - return kind === 264 /* NamedImports */ - || kind === 263 /* NamespaceImport */; + return kind === 265 /* NamedImports */ + || kind === 264 /* NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; /* @internal */ function isModuleOrEnumDeclaration(node) { - return node.kind === 256 /* ModuleDeclaration */ || node.kind === 255 /* EnumDeclaration */; + return node.kind === 257 /* ModuleDeclaration */ || node.kind === 256 /* EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 209 /* ArrowFunction */ - || kind === 198 /* BindingElement */ - || kind === 252 /* ClassDeclaration */ - || kind === 221 /* ClassExpression */ - || kind === 166 /* Constructor */ - || kind === 255 /* EnumDeclaration */ - || kind === 291 /* EnumMember */ - || kind === 270 /* ExportSpecifier */ - || kind === 251 /* FunctionDeclaration */ - || kind === 208 /* FunctionExpression */ - || kind === 167 /* GetAccessor */ - || kind === 262 /* ImportClause */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 265 /* ImportSpecifier */ - || kind === 253 /* InterfaceDeclaration */ - || kind === 280 /* JsxAttribute */ - || kind === 165 /* MethodDeclaration */ - || kind === 164 /* MethodSignature */ - || kind === 256 /* ModuleDeclaration */ - || kind === 259 /* NamespaceExportDeclaration */ - || kind === 263 /* NamespaceImport */ - || kind === 269 /* NamespaceExport */ - || kind === 160 /* Parameter */ - || kind === 288 /* PropertyAssignment */ - || kind === 163 /* PropertyDeclaration */ - || kind === 162 /* PropertySignature */ - || kind === 168 /* SetAccessor */ - || kind === 289 /* ShorthandPropertyAssignment */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 159 /* TypeParameter */ - || kind === 249 /* VariableDeclaration */ - || kind === 331 /* JSDocTypedefTag */ - || kind === 324 /* JSDocCallbackTag */ - || kind === 333 /* JSDocPropertyTag */; + return kind === 210 /* ArrowFunction */ + || kind === 199 /* BindingElement */ + || kind === 253 /* ClassDeclaration */ + || kind === 222 /* ClassExpression */ + || kind === 167 /* Constructor */ + || kind === 256 /* EnumDeclaration */ + || kind === 292 /* EnumMember */ + || kind === 271 /* ExportSpecifier */ + || kind === 252 /* FunctionDeclaration */ + || kind === 209 /* FunctionExpression */ + || kind === 168 /* GetAccessor */ + || kind === 263 /* ImportClause */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 266 /* ImportSpecifier */ + || kind === 254 /* InterfaceDeclaration */ + || kind === 281 /* JsxAttribute */ + || kind === 166 /* MethodDeclaration */ + || kind === 165 /* MethodSignature */ + || kind === 257 /* ModuleDeclaration */ + || kind === 260 /* NamespaceExportDeclaration */ + || kind === 264 /* NamespaceImport */ + || kind === 270 /* NamespaceExport */ + || kind === 161 /* Parameter */ + || kind === 289 /* PropertyAssignment */ + || kind === 164 /* PropertyDeclaration */ + || kind === 163 /* PropertySignature */ + || kind === 169 /* SetAccessor */ + || kind === 290 /* ShorthandPropertyAssignment */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 160 /* TypeParameter */ + || kind === 250 /* VariableDeclaration */ + || kind === 335 /* JSDocTypedefTag */ + || kind === 328 /* JSDocCallbackTag */ + || kind === 337 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { - return kind === 251 /* FunctionDeclaration */ - || kind === 271 /* MissingDeclaration */ - || kind === 252 /* ClassDeclaration */ - || kind === 253 /* InterfaceDeclaration */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 255 /* EnumDeclaration */ - || kind === 256 /* ModuleDeclaration */ - || kind === 261 /* ImportDeclaration */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 267 /* ExportDeclaration */ - || kind === 266 /* ExportAssignment */ - || kind === 259 /* NamespaceExportDeclaration */; + return kind === 252 /* FunctionDeclaration */ + || kind === 272 /* MissingDeclaration */ + || kind === 253 /* ClassDeclaration */ + || kind === 254 /* InterfaceDeclaration */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 256 /* EnumDeclaration */ + || kind === 257 /* ModuleDeclaration */ + || kind === 262 /* ImportDeclaration */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 268 /* ExportDeclaration */ + || kind === 267 /* ExportAssignment */ + || kind === 260 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 241 /* BreakStatement */ - || kind === 240 /* ContinueStatement */ - || kind === 248 /* DebuggerStatement */ - || kind === 235 /* DoStatement */ - || kind === 233 /* ExpressionStatement */ - || kind === 231 /* EmptyStatement */ - || kind === 238 /* ForInStatement */ - || kind === 239 /* ForOfStatement */ - || kind === 237 /* ForStatement */ - || kind === 234 /* IfStatement */ - || kind === 245 /* LabeledStatement */ - || kind === 242 /* ReturnStatement */ - || kind === 244 /* SwitchStatement */ - || kind === 246 /* ThrowStatement */ - || kind === 247 /* TryStatement */ - || kind === 232 /* VariableStatement */ - || kind === 236 /* WhileStatement */ - || kind === 243 /* WithStatement */ - || kind === 335 /* NotEmittedStatement */ - || kind === 339 /* EndOfDeclarationMarker */ - || kind === 338 /* MergeDeclarationMarker */; + return kind === 242 /* BreakStatement */ + || kind === 241 /* ContinueStatement */ + || kind === 249 /* DebuggerStatement */ + || kind === 236 /* DoStatement */ + || kind === 234 /* ExpressionStatement */ + || kind === 232 /* EmptyStatement */ + || kind === 239 /* ForInStatement */ + || kind === 240 /* ForOfStatement */ + || kind === 238 /* ForStatement */ + || kind === 235 /* IfStatement */ + || kind === 246 /* LabeledStatement */ + || kind === 243 /* ReturnStatement */ + || kind === 245 /* SwitchStatement */ + || kind === 247 /* ThrowStatement */ + || kind === 248 /* TryStatement */ + || kind === 233 /* VariableStatement */ + || kind === 237 /* WhileStatement */ + || kind === 244 /* WithStatement */ + || kind === 339 /* NotEmittedStatement */ + || kind === 343 /* EndOfDeclarationMarker */ + || kind === 342 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { - if (node.kind === 159 /* TypeParameter */) { - return (node.parent && node.parent.kind !== 330 /* JSDocTemplateTag */) || ts.isInJSFile(node); + if (node.kind === 160 /* TypeParameter */) { + return (node.parent && node.parent.kind !== 334 /* JSDocTemplateTag */) || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -13261,10 +13474,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 230 /* Block */) + if (node.kind !== 231 /* Block */) return false; if (node.parent !== undefined) { - if (node.parent.kind === 247 /* TryStatement */ || node.parent.kind === 287 /* CatchClause */) { + if (node.parent.kind === 248 /* TryStatement */ || node.parent.kind === 288 /* CatchClause */) { return false; } } @@ -13278,15 +13491,15 @@ var ts; var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) - || kind === 230 /* Block */; + || kind === 231 /* Block */; } ts.isStatementOrBlock = isStatementOrBlock; // Module references /* @internal */ function isModuleReference(node) { var kind = node.kind; - return kind === 272 /* ExternalModuleReference */ - || kind === 157 /* QualifiedName */ + return kind === 273 /* ExternalModuleReference */ + || kind === 158 /* QualifiedName */ || kind === 78 /* Identifier */; } ts.isModuleReference = isModuleReference; @@ -13296,70 +13509,76 @@ var ts; var kind = node.kind; return kind === 107 /* ThisKeyword */ || kind === 78 /* Identifier */ - || kind === 201 /* PropertyAccessExpression */; + || kind === 202 /* PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; /* @internal */ function isJsxChild(node) { var kind = node.kind; - return kind === 273 /* JsxElement */ - || kind === 283 /* JsxExpression */ - || kind === 274 /* JsxSelfClosingElement */ + return kind === 274 /* JsxElement */ + || kind === 284 /* JsxExpression */ + || kind === 275 /* JsxSelfClosingElement */ || kind === 11 /* JsxText */ - || kind === 277 /* JsxFragment */; + || kind === 278 /* JsxFragment */; } ts.isJsxChild = isJsxChild; /* @internal */ function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 280 /* JsxAttribute */ - || kind === 282 /* JsxSpreadAttribute */; + return kind === 281 /* JsxAttribute */ + || kind === 283 /* JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; /* @internal */ function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 10 /* StringLiteral */ - || kind === 283 /* JsxExpression */; + || kind === 284 /* JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 275 /* JsxOpeningElement */ - || kind === 274 /* JsxSelfClosingElement */; + return kind === 276 /* JsxOpeningElement */ + || kind === 275 /* JsxSelfClosingElement */; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 284 /* CaseClause */ - || kind === 285 /* DefaultClause */; + return kind === 285 /* CaseClause */ + || kind === 286 /* DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; // JSDoc /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 301 /* FirstJSDocNode */ && node.kind <= 333 /* LastJSDocNode */; + return node.kind >= 302 /* FirstJSDocNode */ && node.kind <= 337 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 311 /* JSDocComment */ || node.kind === 310 /* JSDocNamepathType */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + return node.kind === 312 /* JSDocComment */ + || node.kind === 311 /* JSDocNamepathType */ + || node.kind === 313 /* JSDocText */ + || node.kind === 316 /* JSDocLink */ + || isJSDocTag(node) + || ts.isJSDocTypeLiteral(node) + || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 314 /* FirstJSDocTagNode */ && node.kind <= 333 /* LastJSDocTagNode */; + return node.kind >= 317 /* FirstJSDocTagNode */ && node.kind <= 337 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { - return node.kind === 168 /* SetAccessor */; + return node.kind === 169 /* SetAccessor */; } ts.isSetAccessor = isSetAccessor; function isGetAccessor(node) { - return node.kind === 167 /* GetAccessor */; + return node.kind === 168 /* GetAccessor */; } ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ @@ -13385,13 +13604,13 @@ var ts; /** True if has initializer node attached to it. */ function hasOnlyExpressionInitializer(node) { switch (node.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: - case 162 /* PropertySignature */: - case 163 /* PropertyDeclaration */: - case 288 /* PropertyAssignment */: - case 291 /* EnumMember */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: + case 163 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 289 /* PropertyAssignment */: + case 292 /* EnumMember */: return true; default: return false; @@ -13399,12 +13618,12 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - return node.kind === 280 /* JsxAttribute */ || node.kind === 282 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); + return node.kind === 281 /* JsxAttribute */ || node.kind === 283 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; /* @internal */ function isTypeReferenceType(node) { - return node.kind === 173 /* TypeReference */ || node.kind === 223 /* ExpressionWithTypeArguments */; + return node.kind === 174 /* TypeReference */ || node.kind === 224 /* ExpressionWithTypeArguments */; } ts.isTypeReferenceType = isTypeReferenceType; var MAX_SMI_X86 = 1073741823; @@ -13643,7 +13862,9 @@ var ts; } ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + return oldResolution.resolvedFileName === newResolution.resolvedFileName + && oldResolution.primary === newResolution.primary + && oldResolution.originalPath === newResolution.originalPath; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { @@ -13685,7 +13906,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 297 /* SourceFile */) { + while (node && node.kind !== 298 /* SourceFile */) { node = node.parent; } return node; @@ -13693,11 +13914,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 230 /* Block */: - case 258 /* CaseBlock */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 231 /* Block */: + case 259 /* CaseBlock */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: return true; } return false; @@ -13893,10 +14114,12 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 334 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 338 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, + /*stopAfterLineBreak*/ false, + /*stopAtComments*/ false, isInJSDoc(node)); } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { @@ -14015,9 +14238,11 @@ var ts; DataView: ["setBigInt64", "setBigUint64", "getBigInt64", "getBigUint64"], RelativeTimeFormat: ["format", "formatToParts", "resolvedOptions"] }, - esnext: { + es2021: { PromiseConstructor: ["any"], - String: ["replaceAll"], + String: ["replaceAll"] + }, + esnext: { NumberFormat: ["formatToParts"] } }; @@ -14110,7 +14335,7 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 249 /* VariableDeclaration */ && node.parent.kind === 287 /* CatchClause */; + return node.kind === 250 /* VariableDeclaration */ && node.parent.kind === 288 /* CatchClause */; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { @@ -14142,11 +14367,11 @@ var ts; ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. - return node && node.kind === 256 /* ModuleDeclaration */ && (!node.body); + return !!node && node.kind === 257 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 297 /* SourceFile */ || - node.kind === 256 /* ModuleDeclaration */ || + return node.kind === 298 /* SourceFile */ || + node.kind === 257 /* ModuleDeclaration */ || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -14163,16 +14388,17 @@ var ts; // - defined in the top level scope and source file is an external module // - defined inside ambient module declaration located in the top level scope and source file not an external module switch (node.parent.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: return ts.isExternalModule(node.parent); - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } ts.isModuleAugmentationExternal = isModuleAugmentationExternal; function getNonAugmentationDeclaration(symbol) { - return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); + var _a; + return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); } ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration; function isEffectiveExternalModule(node, compilerOptions) { @@ -14218,22 +14444,22 @@ var ts; ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile; function isBlockScope(node, parentNode) { switch (node.kind) { - case 297 /* SourceFile */: - case 258 /* CaseBlock */: - case 287 /* CatchClause */: - case 256 /* ModuleDeclaration */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 298 /* SourceFile */: + case 259 /* CaseBlock */: + case 288 /* CatchClause */: + case 257 /* ModuleDeclaration */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; - case 230 /* Block */: + case 231 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block return !ts.isFunctionLike(parentNode); @@ -14243,9 +14469,9 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: - case 313 /* JSDocSignature */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: + case 315 /* JSDocSignature */: return true; default: ts.assertType(node); @@ -14255,25 +14481,25 @@ var ts; ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 164 /* MethodSignature */: - case 171 /* IndexSignature */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 308 /* JSDocFunctionType */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 330 /* JSDocTemplateTag */: - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 165 /* MethodSignature */: + case 172 /* IndexSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 309 /* JSDocFunctionType */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 334 /* JSDocTemplateTag */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; default: ts.assertType(node); @@ -14283,8 +14509,8 @@ var ts; ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: return true; default: return false; @@ -14293,15 +14519,15 @@ var ts; ts.isAnyImportSyntax = isAnyImportSyntax; function isLateVisibilityPaintedStatement(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 232 /* VariableStatement */: - case 252 /* ClassDeclaration */: - case 251 /* FunctionDeclaration */: - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 233 /* VariableStatement */: + case 253 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: return true; default: return false; @@ -14334,7 +14560,7 @@ var ts; } ts.getNameFromIndexInfo = getNameFromIndexInfo; function isComputedNonLiteralName(name) { - return name.kind === 158 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); + return name.kind === 159 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); } ts.isComputedNonLiteralName = isComputedNonLiteralName; function getTextOfPropertyName(name) { @@ -14346,7 +14572,7 @@ var ts; case 8 /* NumericLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: if (isStringOrNumericLiteralLike(name.expression)) return ts.escapeLeadingUnderscores(name.expression.text); return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames"); @@ -14362,9 +14588,9 @@ var ts; case 79 /* PrivateIdentifier */: case 78 /* Identifier */: return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) { return entityNameToString(name.expression) + "." + entityNameToString(name.name); } @@ -14450,7 +14676,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 230 /* Block */) { + if (node.body && node.body.kind === 231 /* Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -14464,7 +14690,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -14473,28 +14699,28 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 249 /* VariableDeclaration */: - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 254 /* TypeAliasDeclaration */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 250 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 255 /* TypeAliasDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: errorNode = node.name; break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: var start = ts.skipTrivia(sourceFile.text, node.pos); var end = node.statements.length > 0 ? node.statements[0].pos : node.end; return ts.createTextSpanFromBounds(start, end); @@ -14546,11 +14772,11 @@ var ts; } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 203 /* CallExpression */ && n.expression.kind === 105 /* SuperKeyword */; + return n.kind === 204 /* CallExpression */ && n.expression.kind === 105 /* SuperKeyword */; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 203 /* CallExpression */ && n.expression.kind === 99 /* ImportKeyword */; + return n.kind === 204 /* CallExpression */ && n.expression.kind === 99 /* ImportKeyword */; } ts.isImportCall = isImportCall; function isImportMeta(n) { @@ -14564,7 +14790,7 @@ var ts; } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { - return node.kind === 233 /* ExpressionStatement */ + return node.kind === 234 /* ExpressionStatement */ && node.expression.kind === 10 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; @@ -14592,11 +14818,12 @@ var ts; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 160 /* Parameter */ || - node.kind === 159 /* TypeParameter */ || - node.kind === 208 /* FunctionExpression */ || - node.kind === 209 /* ArrowFunction */ || - node.kind === 207 /* ParenthesizedExpression */) ? + var commentRanges = (node.kind === 161 /* Parameter */ || + node.kind === 160 /* TypeParameter */ || + node.kind === 209 /* FunctionExpression */ || + node.kind === 210 /* ArrowFunction */ || + node.kind === 208 /* ParenthesizedExpression */ || + node.kind === 250 /* VariableDeclaration */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -14612,7 +14839,7 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (172 /* FirstTypeNode */ <= node.kind && node.kind <= 195 /* LastTypeNode */) { + if (173 /* FirstTypeNode */ <= node.kind && node.kind <= 196 /* LastTypeNode */) { return true; } switch (node.kind) { @@ -14628,32 +14855,32 @@ var ts; case 141 /* NeverKeyword */: return true; case 113 /* VoidKeyword */: - return node.parent.kind !== 212 /* VoidExpression */; - case 223 /* ExpressionWithTypeArguments */: + return node.parent.kind !== 213 /* VoidExpression */; + case 224 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 159 /* TypeParameter */: - return node.parent.kind === 190 /* MappedType */ || node.parent.kind === 185 /* InferType */; + case 160 /* TypeParameter */: + return node.parent.kind === 191 /* MappedType */ || node.parent.kind === 186 /* InferType */; // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container case 78 /* Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 157 /* QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 158 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 202 /* PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 78 /* Identifier */ || node.kind === 157 /* QualifiedName */ || node.kind === 201 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + ts.Debug.assert(node.kind === 78 /* Identifier */ || node.kind === 158 /* QualifiedName */ || node.kind === 202 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); // falls through - case 157 /* QualifiedName */: - case 201 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: case 107 /* ThisKeyword */: { var parent = node.parent; - if (parent.kind === 176 /* TypeQuery */) { + if (parent.kind === 177 /* TypeQuery */) { return false; } - if (parent.kind === 195 /* ImportType */) { + if (parent.kind === 196 /* ImportType */) { return !parent.isTypeOf; } // Do not recursively call isPartOfTypeNode on the parent. In the example: @@ -14662,40 +14889,40 @@ var ts; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. // Only C and A.B.C are type nodes. - if (172 /* FirstTypeNode */ <= parent.kind && parent.kind <= 195 /* LastTypeNode */) { + if (173 /* FirstTypeNode */ <= parent.kind && parent.kind <= 196 /* LastTypeNode */) { return true; } switch (parent.kind) { - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return node === parent.constraint; - case 330 /* JSDocTemplateTag */: + case 334 /* JSDocTemplateTag */: return node === parent.constraint; - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 160 /* Parameter */: - case 249 /* VariableDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 161 /* Parameter */: + case 250 /* VariableDeclaration */: return node === parent.type; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return node === parent.type; - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return node === parent.type; - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: return node === parent.type; - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: return ts.contains(parent.typeArguments, node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -14720,23 +14947,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitor(node); - case 258 /* CaseBlock */: - case 230 /* Block */: - case 234 /* IfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 243 /* WithStatement */: - case 244 /* SwitchStatement */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: - case 245 /* LabeledStatement */: - case 247 /* TryStatement */: - case 287 /* CatchClause */: + case 259 /* CaseBlock */: + case 231 /* Block */: + case 235 /* IfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 244 /* WithStatement */: + case 245 /* SwitchStatement */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 246 /* LabeledStatement */: + case 248 /* TryStatement */: + case 288 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -14746,23 +14973,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 255 /* EnumDeclaration */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: // These are not allowed inside a generator now, but eventually they may be allowed // as local types. Regardless, skip them to avoid the work. return; default: if (ts.isFunctionLike(node)) { - if (node.name && node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 159 /* ComputedPropertyName */) { // Note that we will not include methods/accessors of a class because they would require // first descending into the class. This is by design. traverse(node.name.expression); @@ -14785,10 +15012,10 @@ var ts; * @param node The type node. */ function getRestParameterElementType(node) { - if (node && node.kind === 178 /* ArrayType */) { + if (node && node.kind === 179 /* ArrayType */) { return node.elementType; } - else if (node && node.kind === 173 /* TypeReference */) { + else if (node && node.kind === 174 /* TypeReference */) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -14798,12 +15025,12 @@ var ts; ts.getRestParameterElementType = getRestParameterElementType; function getMembersOfDeclaration(node) { switch (node.kind) { - case 253 /* InterfaceDeclaration */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 177 /* TypeLiteral */: + case 254 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 178 /* TypeLiteral */: return node.members; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return node.properties; } } @@ -14811,14 +15038,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 198 /* BindingElement */: - case 291 /* EnumMember */: - case 160 /* Parameter */: - case 288 /* PropertyAssignment */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 289 /* ShorthandPropertyAssignment */: - case 249 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 292 /* EnumMember */: + case 161 /* Parameter */: + case 289 /* PropertyAssignment */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 290 /* ShorthandPropertyAssignment */: + case 250 /* VariableDeclaration */: return true; } } @@ -14830,8 +15057,8 @@ var ts; } ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { - return node.parent.kind === 250 /* VariableDeclarationList */ - && node.parent.parent.kind === 232 /* VariableStatement */; + return node.parent.kind === 251 /* VariableDeclarationList */ + && node.parent.parent.kind === 233 /* VariableStatement */; } ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; function isValidESSymbolDeclaration(node) { @@ -14842,13 +15069,13 @@ var ts; ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return true; } return false; @@ -14859,7 +15086,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 245 /* LabeledStatement */) { + if (node.statement.kind !== 246 /* LabeledStatement */) { return node.statement; } node = node.statement; @@ -14867,17 +15094,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 230 /* Block */ && ts.isFunctionLike(node.parent); + return node && node.kind === 231 /* Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 165 /* MethodDeclaration */ && node.parent.kind === 200 /* ObjectLiteralExpression */; + return node && node.kind === 166 /* MethodDeclaration */ && node.parent.kind === 201 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 165 /* MethodDeclaration */ && - (node.parent.kind === 200 /* ObjectLiteralExpression */ || - node.parent.kind === 221 /* ClassExpression */); + return node.kind === 166 /* MethodDeclaration */ && + (node.parent.kind === 201 /* ObjectLiteralExpression */ || + node.parent.kind === 222 /* ClassExpression */); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -14890,7 +15117,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return objectLiteral.properties.filter(function (property) { - if (property.kind === 288 /* PropertyAssignment */) { + if (property.kind === 289 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); return key === propName || (!!key2 && key2 === propName); } @@ -14939,14 +15166,14 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { - ts.Debug.assert(node.kind !== 297 /* SourceFile */); + ts.Debug.assert(node.kind !== 298 /* SourceFile */); while (true) { node = node.parent; if (!node) { return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. } switch (node.kind) { - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: // If the grandparent node is an object literal (as opposed to a class), // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container @@ -14961,9 +15188,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 161 /* Decorator */: + case 162 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 160 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 161 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -14974,26 +15201,26 @@ var ts; node = node.parent; } break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // falls through - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 256 /* ModuleDeclaration */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 255 /* EnumDeclaration */: - case 297 /* SourceFile */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 257 /* ModuleDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 256 /* EnumDeclaration */: + case 298 /* SourceFile */: return node; } } @@ -15012,9 +15239,9 @@ var ts; var container = getThisContainer(node, /*includeArrowFunctions*/ false); if (container) { switch (container.kind) { - case 166 /* Constructor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 167 /* Constructor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return container; } } @@ -15036,27 +15263,27 @@ var ts; return node; } switch (node.kind) { - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: node = node.parent; break; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: if (!stopOnFunctions) { continue; } // falls through - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return node; - case 161 /* Decorator */: + case 162 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 160 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 161 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -15072,14 +15299,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 208 /* FunctionExpression */ || func.kind === 209 /* ArrowFunction */) { + if (func.kind === 209 /* FunctionExpression */ || func.kind === 210 /* ArrowFunction */) { var prev = func; var parent = func.parent; - while (parent.kind === 207 /* ParenthesizedExpression */) { + while (parent.kind === 208 /* ParenthesizedExpression */) { prev = parent; parent = parent.parent; } - if (parent.kind === 203 /* CallExpression */ && parent.expression === prev) { + if (parent.kind === 204 /* CallExpression */ && parent.expression === prev) { return parent; } } @@ -15095,7 +15322,7 @@ var ts; */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 201 /* PropertyAccessExpression */ || kind === 202 /* ElementAccessExpression */) + return (kind === 202 /* PropertyAccessExpression */ || kind === 203 /* ElementAccessExpression */) && node.expression.kind === 105 /* SuperKeyword */; } ts.isSuperProperty = isSuperProperty; @@ -15104,7 +15331,7 @@ var ts; */ function isThisProperty(node) { var kind = node.kind; - return (kind === 201 /* PropertyAccessExpression */ || kind === 202 /* ElementAccessExpression */) + return (kind === 202 /* PropertyAccessExpression */ || kind === 203 /* ElementAccessExpression */) && node.expression.kind === 107 /* ThisKeyword */; } ts.isThisProperty = isThisProperty; @@ -15113,17 +15340,25 @@ var ts; return !!node && ts.isVariableDeclaration(node) && ((_a = node.initializer) === null || _a === void 0 ? void 0 : _a.kind) === 107 /* ThisKeyword */; } ts.isThisInitializedDeclaration = isThisInitializedDeclaration; + function isThisInitializedObjectBindingExpression(node) { + return !!node + && (ts.isShorthandPropertyAssignment(node) || ts.isPropertyAssignment(node)) + && ts.isBinaryExpression(node.parent.parent) + && node.parent.parent.operatorToken.kind === 62 /* EqualsToken */ + && node.parent.parent.right.kind === 107 /* ThisKeyword */; + } + ts.isThisInitializedObjectBindingExpression = isThisInitializedObjectBindingExpression; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return node.typeName; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) ? node.expression : undefined; // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s. case 78 /* Identifier */: - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return node; } return undefined; @@ -15131,10 +15366,10 @@ var ts; ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { switch (node.kind) { - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return node.tag; - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return node.tagName; default: return node.expression; @@ -15147,25 +15382,25 @@ var ts; return false; } switch (node.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: // classes are valid targets return true; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return parent.kind === 252 /* ClassDeclaration */; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: + return parent.kind === 253 /* ClassDeclaration */; + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && parent.kind === 252 /* ClassDeclaration */; - case 160 /* Parameter */: + && parent.kind === 253 /* ClassDeclaration */; + case 161 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; return parent.body !== undefined - && (parent.kind === 166 /* Constructor */ - || parent.kind === 165 /* MethodDeclaration */ - || parent.kind === 168 /* SetAccessor */) - && grandparent.kind === 252 /* ClassDeclaration */; + && (parent.kind === 167 /* Constructor */ + || parent.kind === 166 /* MethodDeclaration */ + || parent.kind === 169 /* SetAccessor */) + && grandparent.kind === 253 /* ClassDeclaration */; } return false; } @@ -15181,10 +15416,10 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 - case 165 /* MethodDeclaration */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 169 /* SetAccessor */: return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 default: return false; @@ -15193,9 +15428,9 @@ var ts; ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 275 /* JsxOpeningElement */ || - parent.kind === 274 /* JsxSelfClosingElement */ || - parent.kind === 276 /* JsxClosingElement */) { + if (parent.kind === 276 /* JsxOpeningElement */ || + parent.kind === 275 /* JsxSelfClosingElement */ || + parent.kind === 277 /* JsxClosingElement */) { return parent.tagName === node; } return false; @@ -15208,44 +15443,44 @@ var ts; case 109 /* TrueKeyword */: case 94 /* FalseKeyword */: case 13 /* RegularExpressionLiteral */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 205 /* TaggedTemplateExpression */: - case 224 /* AsExpression */: - case 206 /* TypeAssertionExpression */: - case 225 /* NonNullExpression */: - case 207 /* ParenthesizedExpression */: - case 208 /* FunctionExpression */: - case 221 /* ClassExpression */: - case 209 /* ArrowFunction */: - case 212 /* VoidExpression */: - case 210 /* DeleteExpression */: - case 211 /* TypeOfExpression */: - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: - case 216 /* BinaryExpression */: - case 217 /* ConditionalExpression */: - case 220 /* SpreadElement */: - case 218 /* TemplateExpression */: - case 222 /* OmittedExpression */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: - case 219 /* YieldExpression */: - case 213 /* AwaitExpression */: - case 226 /* MetaProperty */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 206 /* TaggedTemplateExpression */: + case 225 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 226 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 209 /* FunctionExpression */: + case 222 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 213 /* VoidExpression */: + case 211 /* DeleteExpression */: + case 212 /* TypeOfExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 217 /* BinaryExpression */: + case 218 /* ConditionalExpression */: + case 221 /* SpreadElement */: + case 219 /* TemplateExpression */: + case 223 /* OmittedExpression */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: + case 220 /* YieldExpression */: + case 214 /* AwaitExpression */: + case 227 /* MetaProperty */: return true; - case 157 /* QualifiedName */: - while (node.parent.kind === 157 /* QualifiedName */) { + case 158 /* QualifiedName */: + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 176 /* TypeQuery */ || isJSXTagName(node); + return node.parent.kind === 177 /* TypeQuery */ || isJSXTagName(node); case 78 /* Identifier */: - if (node.parent.kind === 176 /* TypeQuery */ || isJSXTagName(node)) { + if (node.parent.kind === 177 /* TypeQuery */ || isJSXTagName(node)) { return true; } // falls through @@ -15263,49 +15498,49 @@ var ts; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 291 /* EnumMember */: - case 288 /* PropertyAssignment */: - case 198 /* BindingElement */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 292 /* EnumMember */: + case 289 /* PropertyAssignment */: + case 199 /* BindingElement */: return parent.initializer === node; - case 233 /* ExpressionStatement */: - case 234 /* IfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 242 /* ReturnStatement */: - case 243 /* WithStatement */: - case 244 /* SwitchStatement */: - case 284 /* CaseClause */: - case 246 /* ThrowStatement */: + case 234 /* ExpressionStatement */: + case 235 /* IfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 243 /* ReturnStatement */: + case 244 /* WithStatement */: + case 245 /* SwitchStatement */: + case 285 /* CaseClause */: + case 247 /* ThrowStatement */: return parent.expression === node; - case 237 /* ForStatement */: + case 238 /* ForStatement */: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 250 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 251 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 250 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 251 /* VariableDeclarationList */) || forInStatement.expression === node; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return node === parent.expression; - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return node === parent.expression; - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return node === parent.expression; - case 161 /* Decorator */: - case 283 /* JsxExpression */: - case 282 /* JsxSpreadAttribute */: - case 290 /* SpreadAssignment */: + case 162 /* Decorator */: + case 284 /* JsxExpression */: + case 283 /* JsxSpreadAttribute */: + case 291 /* SpreadAssignment */: return true; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return parent.objectAssignmentInitializer === node; default: return isExpressionNode(parent); @@ -15313,14 +15548,18 @@ var ts; } ts.isInExpressionContext = isInExpressionContext; function isPartOfTypeQuery(node) { - while (node.kind === 157 /* QualifiedName */ || node.kind === 78 /* Identifier */) { + while (node.kind === 158 /* QualifiedName */ || node.kind === 78 /* Identifier */) { node = node.parent; } - return node.kind === 176 /* TypeQuery */; + return node.kind === 177 /* TypeQuery */; } ts.isPartOfTypeQuery = isPartOfTypeQuery; + function isNamespaceReexportDeclaration(node) { + return ts.isNamespaceExport(node) && !!node.parent.moduleSpecifier; + } + ts.isNamespaceReexportDeclaration = isNamespaceReexportDeclaration; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 272 /* ExternalModuleReference */; + return node.kind === 261 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 273 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -15329,12 +15568,11 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function getExternalModuleRequireArgument(node) { - return isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true) - && getLeftmostAccessExpression(node.initializer).arguments[0]; + return isRequireVariableDeclaration(node) && getLeftmostAccessExpression(node.initializer).arguments[0]; } ts.getExternalModuleRequireArgument = getExternalModuleRequireArgument; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 272 /* ExternalModuleReference */; + return node.kind === 261 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 273 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJS(file) { @@ -15370,7 +15608,7 @@ var ts; } ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, requireStringLiteralLikeArgument) { - if (callExpression.kind !== 203 /* CallExpression */) { + if (callExpression.kind !== 204 /* CallExpression */) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; @@ -15384,18 +15622,21 @@ var ts; return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; - function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) { - if (node.kind === 198 /* BindingElement */) { + /** + * Returns true if the node is a VariableDeclaration initialized to a require call (see `isRequireCall`). + * This function does not test if the node is in a JavaScript file or not. + */ + function isRequireVariableDeclaration(node) { + if (node.kind === 199 /* BindingElement */) { node = node.parent.parent; } - return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), requireStringLiteralLikeArgument); + return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), /*requireStringLiteralLikeArgument*/ true); } ts.isRequireVariableDeclaration = isRequireVariableDeclaration; - function isRequireVariableStatement(node, requireStringLiteralLikeArgument) { - if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; } + function isRequireVariableStatement(node) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 - && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); }); + && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl); }); } ts.isRequireVariableStatement = isRequireVariableStatement; function isSingleOrDoubleQuote(charCode) { @@ -15467,11 +15708,11 @@ var ts; function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); - return e.kind === 208 /* FunctionExpression */ || e.kind === 209 /* ArrowFunction */ ? initializer : undefined; + return e.kind === 209 /* FunctionExpression */ || e.kind === 210 /* ArrowFunction */ ? initializer : undefined; } - if (initializer.kind === 208 /* FunctionExpression */ || - initializer.kind === 221 /* ClassExpression */ || - initializer.kind === 209 /* ArrowFunction */) { + if (initializer.kind === 209 /* FunctionExpression */ || + initializer.kind === 222 /* ClassExpression */ || + initializer.kind === 210 /* ArrowFunction */) { return initializer; } if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { @@ -15592,8 +15833,7 @@ var ts; ts.isLiteralLikeAccess = isLiteralLikeAccess; /** x[0] OR x['a'] OR x[Symbol.y] */ function isLiteralLikeElementAccess(node) { - return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) || - isWellKnownSymbolSyntactically(node.argumentExpression)); + return ts.isElementAccessExpression(node) && isStringOrNumericLiteralLike(node.argumentExpression); } ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess; /** Any series of property and element accesses. */ @@ -15673,9 +15913,6 @@ var ts; return ts.escapeLeadingUnderscores(name.text); } } - if (ts.isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) { - return getPropertyNameForKnownSymbolName(ts.idText(node.argumentExpression.name)); - } return undefined; } ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName; @@ -15725,7 +15962,7 @@ var ts; ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { return isInJSFile(expr) && - expr.parent && expr.parent.kind === 233 /* ExpressionStatement */ && + expr.parent && expr.parent.kind === 234 /* ExpressionStatement */ && (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) && !!ts.getJSDocTypeTag(expr.parent); } @@ -15746,23 +15983,37 @@ var ts; return false; } var decl = symbol.valueDeclaration; - return decl.kind === 251 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + return decl.kind === 252 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); } ts.isFunctionSymbol = isFunctionSymbol; + function tryGetModuleSpecifierFromDeclaration(node) { + var _a, _b, _c; + switch (node.kind) { + case 250 /* VariableDeclaration */: + return node.initializer.arguments[0].text; + case 262 /* ImportDeclaration */: + return (_a = ts.tryCast(node.moduleSpecifier, ts.isStringLiteralLike)) === null || _a === void 0 ? void 0 : _a.text; + case 261 /* ImportEqualsDeclaration */: + return (_c = ts.tryCast((_b = ts.tryCast(node.moduleReference, ts.isExternalModuleReference)) === null || _b === void 0 ? void 0 : _b.expression, ts.isStringLiteralLike)) === null || _c === void 0 ? void 0 : _c.text; + default: + ts.Debug.assertNever(node); + } + } + ts.tryGetModuleSpecifierFromDeclaration = tryGetModuleSpecifierFromDeclaration; function importFromModuleSpecifier(node) { return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent); } ts.importFromModuleSpecifier = importFromModuleSpecifier; function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: return node.parent; - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: return node.parent.parent; - case 203 /* CallExpression */: + case 204 /* CallExpression */: return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined; - case 191 /* LiteralType */: + case 192 /* LiteralType */: ts.Debug.assert(ts.isStringLiteral(node)); return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: @@ -15772,15 +16023,17 @@ var ts; ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: return node.moduleSpecifier; - case 260 /* ImportEqualsDeclaration */: - return node.moduleReference.kind === 272 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; - case 195 /* ImportType */: + case 261 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 273 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 196 /* ImportType */: return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; - case 203 /* CallExpression */: + case 204 /* CallExpression */: return node.arguments[0]; + case 257 /* ModuleDeclaration */: + return node.name.kind === 10 /* StringLiteral */ ? node.name : undefined; default: return ts.Debug.assertNever(node); } @@ -15788,11 +16041,11 @@ var ts; ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return node; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport); default: return ts.Debug.assertNever(node); @@ -15800,7 +16053,7 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 261 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; + return node.kind === 262 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function forEachImportClauseDeclaration(node, action) { @@ -15821,13 +16074,13 @@ var ts; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 160 /* Parameter */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 289 /* ShorthandPropertyAssignment */: - case 288 /* PropertyAssignment */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 161 /* Parameter */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 290 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -15841,7 +16094,7 @@ var ts; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 331 /* JSDocTypedefTag */ || node.kind === 324 /* JSDocCallbackTag */ || node.kind === 325 /* JSDocEnumTag */; + return node.kind === 335 /* JSDocTypedefTag */ || node.kind === 328 /* JSDocCallbackTag */ || node.kind === 329 /* JSDocEnumTag */; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -15866,12 +16119,12 @@ var ts; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: var v = getSingleVariableOfVariableStatement(node); return v && v.initializer; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return node.initializer; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return node.initializer; } } @@ -15883,7 +16136,7 @@ var ts; function getNestedModuleDeclaration(node) { return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 256 /* ModuleDeclaration */ + node.body.kind === 257 /* ModuleDeclaration */ ? node.body : undefined; } @@ -15898,11 +16151,11 @@ var ts; if (ts.hasJSDocNodes(node)) { result = ts.append(result, ts.last(node.jsDoc)); } - if (node.kind === 160 /* Parameter */) { + if (node.kind === 161 /* Parameter */) { result = ts.addRange(result, (noCache ? ts.getJSDocParameterTagsNoCache : ts.getJSDocParameterTags)(node)); break; } - if (node.kind === 159 /* TypeParameter */) { + if (node.kind === 160 /* TypeParameter */) { result = ts.addRange(result, (noCache ? ts.getJSDocTypeParameterTagsNoCache : ts.getJSDocTypeParameterTags)(node)); break; } @@ -15913,10 +16166,11 @@ var ts; ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; function getNextJSDocCommentLocation(node) { var parent = node.parent; - if (parent.kind === 288 /* PropertyAssignment */ || - parent.kind === 266 /* ExportAssignment */ || - parent.kind === 163 /* PropertyDeclaration */ || - parent.kind === 233 /* ExpressionStatement */ && node.kind === 201 /* PropertyAccessExpression */ || + if (parent.kind === 289 /* PropertyAssignment */ || + parent.kind === 267 /* ExportAssignment */ || + parent.kind === 164 /* PropertyDeclaration */ || + parent.kind === 234 /* ExpressionStatement */ && node.kind === 202 /* PropertyAccessExpression */ || + parent.kind === 243 /* ReturnStatement */ || getNestedModuleDeclaration(parent) || ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) { return parent; @@ -16003,7 +16257,7 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 309 /* JSDocVariadicType */; + return node.dotDotDotToken !== undefined || !!type && type.kind === 310 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; function hasTypeArguments(node) { @@ -16020,31 +16274,34 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? binaryOperator === 62 /* EqualsToken */ || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? 1 /* Definite */ : 2 /* Compound */ : 0 /* None */; - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: var unaryOperator = parent.operator; return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; - case 207 /* ParenthesizedExpression */: - case 199 /* ArrayLiteralExpression */: - case 220 /* SpreadElement */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 200 /* ArrayLiteralExpression */: + case 221 /* SpreadElement */: + case 226 /* NonNullExpression */: node = parent; break; - case 289 /* ShorthandPropertyAssignment */: + case 291 /* SpreadAssignment */: + node = parent.parent; + break; + case 290 /* ShorthandPropertyAssignment */: if (parent.name !== node) { return 0 /* None */; } node = parent.parent; break; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: if (parent.name === node) { return 0 /* None */; } @@ -16071,22 +16328,22 @@ var ts; */ function isNodeWithPossibleHoistedDeclaration(node) { switch (node.kind) { - case 230 /* Block */: - case 232 /* VariableStatement */: - case 243 /* WithStatement */: - case 234 /* IfStatement */: - case 244 /* SwitchStatement */: - case 258 /* CaseBlock */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: - case 245 /* LabeledStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 247 /* TryStatement */: - case 287 /* CatchClause */: + case 231 /* Block */: + case 233 /* VariableStatement */: + case 244 /* WithStatement */: + case 235 /* IfStatement */: + case 245 /* SwitchStatement */: + case 259 /* CaseBlock */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 246 /* LabeledStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 248 /* TryStatement */: + case 288 /* CatchClause */: return true; } return false; @@ -16103,11 +16360,11 @@ var ts; return node; } function walkUpParenthesizedTypes(node) { - return walkUp(node, 186 /* ParenthesizedType */); + return walkUp(node, 187 /* ParenthesizedType */); } ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; function walkUpParenthesizedExpressions(node) { - return walkUp(node, 207 /* ParenthesizedExpression */); + return walkUp(node, 208 /* ParenthesizedExpression */); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; /** @@ -16117,7 +16374,7 @@ var ts; */ function walkUpParenthesizedTypesAndGetParentAndChild(node) { var child; - while (node && node.kind === 186 /* ParenthesizedType */) { + while (node && node.kind === 187 /* ParenthesizedType */) { child = node; node = node.parent; } @@ -16129,18 +16386,18 @@ var ts; } ts.skipParentheses = skipParentheses; function skipParenthesesUp(node) { - while (node.kind === 207 /* ParenthesizedExpression */) { + while (node.kind === 208 /* 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 !== 201 /* PropertyAccessExpression */ && node.kind !== 202 /* ElementAccessExpression */) { + if (node.kind !== 202 /* PropertyAccessExpression */ && node.kind !== 203 /* ElementAccessExpression */) { return false; } node = walkUpParenthesizedExpressions(node.parent); - return node && node.kind === 210 /* DeleteExpression */; + return node && node.kind === 211 /* DeleteExpression */; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -16193,7 +16450,7 @@ var ts; ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return isStringOrNumericLiteralLike(node) && - node.parent.kind === 158 /* ComputedPropertyName */ && + node.parent.kind === 159 /* ComputedPropertyName */ && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; @@ -16201,26 +16458,26 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 291 /* EnumMember */: - case 288 /* PropertyAssignment */: - case 201 /* PropertyAccessExpression */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 292 /* EnumMember */: + case 289 /* PropertyAssignment */: + case 202 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: // Name on right hand side of dot in a type query or type reference return parent.right === node; - case 198 /* BindingElement */: - case 265 /* ImportSpecifier */: + case 199 /* BindingElement */: + case 266 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 270 /* ExportSpecifier */: - case 280 /* JsxAttribute */: + case 271 /* ExportSpecifier */: + case 281 /* JsxAttribute */: // Any name in an export specifier or JSX Attribute return true; } @@ -16240,33 +16497,33 @@ var ts; // {} // {name: } function isAliasSymbolDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ || - node.kind === 259 /* NamespaceExportDeclaration */ || - node.kind === 262 /* ImportClause */ && !!node.name || - node.kind === 263 /* NamespaceImport */ || - node.kind === 269 /* NamespaceExport */ || - node.kind === 265 /* ImportSpecifier */ || - node.kind === 270 /* ExportSpecifier */ || - node.kind === 266 /* ExportAssignment */ && exportAssignmentIsAlias(node) || + return node.kind === 261 /* ImportEqualsDeclaration */ || + node.kind === 260 /* NamespaceExportDeclaration */ || + node.kind === 263 /* ImportClause */ && !!node.name || + node.kind === 264 /* NamespaceImport */ || + node.kind === 270 /* NamespaceExport */ || + node.kind === 266 /* ImportSpecifier */ || + node.kind === 271 /* ExportSpecifier */ || + node.kind === 267 /* ExportAssignment */ && exportAssignmentIsAlias(node) || ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) || ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableExpression(node.parent.right) || - node.kind === 289 /* ShorthandPropertyAssignment */ || - node.kind === 288 /* PropertyAssignment */ && isAliasableExpression(node.initializer); + node.kind === 290 /* ShorthandPropertyAssignment */ || + node.kind === 289 /* PropertyAssignment */ && isAliasableExpression(node.initializer); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getAliasDeclarationFromName(node) { switch (node.parent.kind) { - case 262 /* ImportClause */: - case 265 /* ImportSpecifier */: - case 263 /* NamespaceImport */: - case 270 /* ExportSpecifier */: - case 266 /* ExportAssignment */: - case 260 /* ImportEqualsDeclaration */: + case 263 /* ImportClause */: + case 266 /* ImportSpecifier */: + case 264 /* NamespaceImport */: + case 271 /* ExportSpecifier */: + case 267 /* ExportAssignment */: + case 261 /* ImportEqualsDeclaration */: return node.parent; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: do { node = node.parent; - } while (node.parent.kind === 157 /* QualifiedName */); + } while (node.parent.kind === 158 /* QualifiedName */); return getAliasDeclarationFromName(node); } } @@ -16285,7 +16542,7 @@ var ts; } ts.getExportAssignmentExpression = getExportAssignmentExpression; function getPropertyAssignmentAliasLikeExpression(node) { - return node.kind === 289 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 288 /* PropertyAssignment */ ? node.initializer : + return node.kind === 290 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 289 /* PropertyAssignment */ ? node.initializer : node.parent.right; } ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression; @@ -16351,11 +16608,11 @@ var ts; } ts.getAncestor = getAncestor; function isKeyword(token) { - return 80 /* FirstKeyword */ <= token && token <= 156 /* LastKeyword */; + return 80 /* FirstKeyword */ <= token && token <= 157 /* LastKeyword */; } ts.isKeyword = isKeyword; function isContextualKeyword(token) { - return 125 /* FirstContextualKeyword */ <= token && token <= 156 /* LastContextualKeyword */; + return 125 /* FirstContextualKeyword */ <= token && token <= 157 /* LastContextualKeyword */; } ts.isContextualKeyword = isContextualKeyword; function isNonContextualKeyword(token) { @@ -16399,14 +16656,14 @@ var ts; } var flags = 0 /* Normal */; switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: if (node.asteriskToken) { flags |= 1 /* Generator */; } // falls through - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: if (hasSyntacticModifier(node, 256 /* Async */)) { flags |= 2 /* Async */; } @@ -16420,10 +16677,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: return node.body !== undefined && node.asteriskToken === undefined && hasSyntacticModifier(node, 256 /* Async */); @@ -16446,9 +16703,6 @@ var ts; * 3. The computed name is *not* expressed as a NumericLiteral. * 4. The computed name is *not* expressed as a PlusToken or MinusToken * immediately followed by a NumericLiteral. - * 5. The computed name is *not* expressed as `Symbol.`, where `` - * is a property of the Symbol constructor that denotes a built-in - * Symbol. */ function hasDynamicName(declaration) { var name = ts.getNameOfDeclaration(declaration); @@ -16456,24 +16710,14 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - if (!(name.kind === 158 /* ComputedPropertyName */ || name.kind === 202 /* ElementAccessExpression */)) { + if (!(name.kind === 159 /* ComputedPropertyName */ || name.kind === 203 /* ElementAccessExpression */)) { return false; } var expr = ts.isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression; return !isStringOrNumericLiteralLike(expr) && - !isSignedNumericLiteral(expr) && - !isWellKnownSymbolSyntactically(expr); + !isSignedNumericLiteral(expr); } ts.isDynamicName = isDynamicName; - /** - * Checks if the expression is of the form: - * Symbol.name - * where Symbol is literally the word "Symbol", and name is any identifierName - */ - function isWellKnownSymbolSyntactically(node) { - return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); - } - ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { switch (name.kind) { case 78 /* Identifier */: @@ -16482,12 +16726,9 @@ var ts; case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: var nameExpression = name.expression; - if (isWellKnownSymbolSyntactically(nameExpression)) { - return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - else if (isStringOrNumericLiteralLike(nameExpression)) { + if (isStringOrNumericLiteralLike(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); } else if (isSignedNumericLiteral(nameExpression)) { @@ -16515,21 +16756,17 @@ var ts; } ts.isPropertyNameLiteral = isPropertyNameLiteral; function getTextOfIdentifierOrLiteral(node) { - return ts.isIdentifierOrPrivateIdentifier(node) ? ts.idText(node) : node.text; + return ts.isMemberName(node) ? ts.idText(node) : node.text; } ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { - return ts.isIdentifierOrPrivateIdentifier(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text); + return ts.isMemberName(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForUniqueESSymbol(symbol) { return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName; } ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol; - function getPropertyNameForKnownSymbolName(symbolName) { - return "__@" + symbolName; - } - ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) { return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description; } @@ -16551,11 +16788,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 160 /* Parameter */; + return root.kind === 161 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 198 /* BindingElement */) { + while (node.kind === 199 /* BindingElement */) { node = node.parent.parent; } return node; @@ -16563,15 +16800,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 166 /* Constructor */ - || kind === 208 /* FunctionExpression */ - || kind === 251 /* FunctionDeclaration */ - || kind === 209 /* ArrowFunction */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 256 /* ModuleDeclaration */ - || kind === 297 /* SourceFile */; + return kind === 167 /* Constructor */ + || kind === 209 /* FunctionExpression */ + || kind === 252 /* FunctionDeclaration */ + || kind === 210 /* ArrowFunction */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 257 /* ModuleDeclaration */ + || kind === 298 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -16590,23 +16827,23 @@ var ts; })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 204 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 205 /* NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 204 /* NewExpression */: + case 205 /* NewExpression */: return hasArguments ? 0 /* Left */ : 1 /* Right */; - case 214 /* PrefixUnaryExpression */: - case 211 /* TypeOfExpression */: - case 212 /* VoidExpression */: - case 210 /* DeleteExpression */: - case 213 /* AwaitExpression */: - case 217 /* ConditionalExpression */: - case 219 /* YieldExpression */: + case 215 /* PrefixUnaryExpression */: + case 212 /* TypeOfExpression */: + case 213 /* VoidExpression */: + case 211 /* DeleteExpression */: + case 214 /* AwaitExpression */: + case 218 /* ConditionalExpression */: + case 220 /* YieldExpression */: return 1 /* Right */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (operator) { case 42 /* AsteriskAsteriskToken */: case 62 /* EqualsToken */: @@ -16633,15 +16870,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 204 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 205 /* NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 216 /* BinaryExpression */) { + if (expression.kind === 217 /* BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 214 /* PrefixUnaryExpression */ || expression.kind === 215 /* PostfixUnaryExpression */) { + else if (expression.kind === 215 /* PrefixUnaryExpression */ || expression.kind === 216 /* PostfixUnaryExpression */) { return expression.operator; } else { @@ -16820,15 +17057,15 @@ var ts; })(OperatorPrecedence = ts.OperatorPrecedence || (ts.OperatorPrecedence = {})); function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return 0 /* Comma */; - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return 1 /* Spread */; - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return 2 /* Yield */; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return 4 /* Conditional */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (operatorKind) { case 27 /* CommaToken */: return 0 /* Comma */; @@ -16853,25 +17090,26 @@ var ts; return getBinaryOperatorPrecedence(operatorKind); } // TODO: Should prefix `++` and `--` be moved to the `Update` precedence? - case 206 /* TypeAssertionExpression */: - case 225 /* NonNullExpression */: - case 214 /* PrefixUnaryExpression */: - case 211 /* TypeOfExpression */: - case 212 /* VoidExpression */: - case 210 /* DeleteExpression */: - case 213 /* AwaitExpression */: + case 207 /* TypeAssertionExpression */: + case 226 /* NonNullExpression */: + case 215 /* PrefixUnaryExpression */: + case 212 /* TypeOfExpression */: + case 213 /* VoidExpression */: + case 211 /* DeleteExpression */: + case 214 /* AwaitExpression */: return 16 /* Unary */; - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return 17 /* Update */; - case 203 /* CallExpression */: + case 204 /* CallExpression */: return 18 /* LeftHandSide */; - case 204 /* NewExpression */: + case 205 /* NewExpression */: return hasArguments ? 19 /* Member */ : 18 /* LeftHandSide */; - case 205 /* TaggedTemplateExpression */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 206 /* TaggedTemplateExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 227 /* MetaProperty */: return 19 /* Member */; - case 224 /* AsExpression */: + case 225 /* AsExpression */: return 11 /* Relational */; case 107 /* ThisKeyword */: case 105 /* SuperKeyword */: @@ -16882,19 +17120,19 @@ var ts; case 8 /* NumericLiteral */: case 9 /* BigIntLiteral */: case 10 /* StringLiteral */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 221 /* ClassExpression */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 222 /* ClassExpression */: case 13 /* RegularExpressionLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: - case 218 /* TemplateExpression */: - case 207 /* ParenthesizedExpression */: - case 222 /* OmittedExpression */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: + case 219 /* TemplateExpression */: + case 208 /* ParenthesizedExpression */: + case 223 /* OmittedExpression */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: return 20 /* Primary */; default: return -1 /* Invalid */; @@ -16950,7 +17188,7 @@ var ts; function getSemanticJsxChildren(children) { return ts.filter(children, function (i) { switch (i.kind) { - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return !!i.expression; case 11 /* JsxText */: return !i.containsOnlyTriviaWhiteSpaces; @@ -17344,11 +17582,20 @@ var ts; return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getCanonicalAbsolutePath(host, path) { + return host.getCanonicalFileName(ts.getNormalizedAbsolutePath(path, host.getCurrentDirectory())); + } function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); if (!file || file.isDeclarationFile) { return undefined; } + // If the declaration already uses a non-relative name, and is outside the common source directory, continue to use it + var specifier = getExternalModuleName(declaration); + if (specifier && ts.isStringLiteralLike(specifier) && !ts.pathIsRelative(specifier.text) && + getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ts.ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1) { + return undefined; + } return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; @@ -17432,8 +17679,8 @@ var ts; return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !host.isSourceFileFromExternalLibrary(sourceFile) && - !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) && - (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName)); + (forceDtsEmit || (!(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) && + !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName))); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -17528,10 +17775,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 167 /* GetAccessor */) { + if (accessor.kind === 168 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 168 /* SetAccessor */) { + else if (accessor.kind === 169 /* SetAccessor */) { setAccessor = accessor; } else { @@ -17551,10 +17798,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 167 /* GetAccessor */ && !getAccessor) { + if (member.kind === 168 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 168 /* SetAccessor */ && !setAccessor) { + if (member.kind === 169 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -17603,7 +17850,7 @@ var ts; ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** template tags are only available when a typedef isn't already using them */ function isNonTypeAliasTemplate(tag) { - return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 311 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 312 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); } /** * Gets the effective type annotation of the value parameter of a set accessor. If the node @@ -17826,6 +18073,18 @@ var ts; return hasSyntacticModifier(node, 32 /* Static */); } ts.hasStaticModifier = hasStaticModifier; + function hasOverrideModifier(node) { + return hasEffectiveModifier(node, 16384 /* Override */); + } + ts.hasOverrideModifier = hasOverrideModifier; + function hasAbstractModifier(node) { + return hasSyntacticModifier(node, 128 /* Abstract */); + } + ts.hasAbstractModifier = hasAbstractModifier; + function hasAmbientModifier(node) { + return hasSyntacticModifier(node, 2 /* Ambient */); + } + ts.hasAmbientModifier = hasAmbientModifier; function hasEffectiveReadonlyModifier(node) { return hasEffectiveModifier(node, 64 /* Readonly */); } @@ -17839,7 +18098,7 @@ var ts; } ts.getSelectedSyntacticModifierFlags = getSelectedSyntacticModifierFlags; function getModifierFlagsWorker(node, includeJSDoc, alwaysIncludeJSDoc) { - if (node.kind >= 0 /* FirstToken */ && node.kind <= 156 /* LastToken */) { + if (node.kind >= 0 /* FirstToken */ && node.kind <= 157 /* LastToken */) { return 0 /* None */; } if (!(node.modifierFlagsCache & 536870912 /* HasComputedFlags */)) { @@ -17884,6 +18143,8 @@ var ts; flags |= 16 /* Protected */; if (ts.getJSDocReadonlyTagNoCache(node)) flags |= 64 /* Readonly */; + if (ts.getJSDocOverrideTagNoCache(node)) + flags |= 16384 /* Override */; } if (ts.getJSDocDeprecatedTagNoCache(node)) flags |= 8192 /* Deprecated */; @@ -17936,10 +18197,15 @@ var ts; case 87 /* DefaultKeyword */: return 512 /* Default */; case 129 /* AsyncKeyword */: return 256 /* Async */; case 142 /* ReadonlyKeyword */: return 64 /* Readonly */; + case 156 /* OverrideKeyword */: return 16384 /* Override */; } return 0 /* None */; } ts.modifierToFlag = modifierToFlag; + function createModifiers(modifierFlags) { + return modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; + } + ts.createModifiers = createModifiers; function isLogicalOperator(token) { return token === 56 /* BarBarToken */ || token === 55 /* AmpersandAmpersandToken */ @@ -17982,11 +18248,15 @@ var ts; && ts.isLeftHandSideExpression(node.left); } ts.isAssignmentExpression = isAssignmentExpression; + function isLeftHandSideOfAssignment(node) { + return isAssignmentExpression(node.parent) && node.parent.left === node; + } + ts.isLeftHandSideOfAssignment = isLeftHandSideOfAssignment; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { var kind = node.left.kind; - return kind === 200 /* ObjectLiteralExpression */ - || kind === 199 /* ArrayLiteralExpression */; + return kind === 201 /* ObjectLiteralExpression */ + || kind === 200 /* ArrayLiteralExpression */; } return false; } @@ -18003,12 +18273,12 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: do { node = node.left; } while (node.kind !== 78 /* Identifier */); return node; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: do { node = node.expression; } while (node.kind !== 78 /* Identifier */); @@ -18017,9 +18287,12 @@ var ts; } ts.getFirstIdentifier = getFirstIdentifier; function isDottedName(node) { - return node.kind === 78 /* Identifier */ || node.kind === 107 /* ThisKeyword */ || node.kind === 105 /* SuperKeyword */ || - node.kind === 201 /* PropertyAccessExpression */ && isDottedName(node.expression) || - node.kind === 207 /* ParenthesizedExpression */ && isDottedName(node.expression); + return node.kind === 78 /* Identifier */ + || node.kind === 107 /* ThisKeyword */ + || node.kind === 105 /* SuperKeyword */ + || node.kind === 227 /* MetaProperty */ + || node.kind === 202 /* PropertyAccessExpression */ && isDottedName(node.expression) + || node.kind === 208 /* ParenthesizedExpression */ && isDottedName(node.expression); } ts.isDottedName = isDottedName; function isPropertyAccessEntityNameExpression(node) { @@ -18033,6 +18306,12 @@ var ts; return baseStr + "." + entityNameToString(expr.name); } } + else if (ts.isElementAccessExpression(expr)) { + var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); + if (baseStr !== undefined && ts.isPropertyName(expr.argumentExpression)) { + return baseStr + "." + getPropertyNameForPropertyNameNode(expr.argumentExpression); + } + } else if (ts.isIdentifier(expr)) { return ts.unescapeLeadingUnderscores(expr.escapedText); } @@ -18044,22 +18323,22 @@ var ts; } ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 157 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 158 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 202 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 200 /* ObjectLiteralExpression */ && + return expression.kind === 201 /* ObjectLiteralExpression */ && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 199 /* ArrayLiteralExpression */ && + return expression.kind === 200 /* ArrayLiteralExpression */ && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - if (!isExportDefaultSymbol(symbol)) + if (!isExportDefaultSymbol(symbol) || !symbol.declarations) return undefined; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; @@ -18386,8 +18665,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 255 /* EnumDeclaration */: - case 256 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 257 /* ModuleDeclaration */: return parseNode === parseNode.parent.name; } } @@ -18414,9 +18693,11 @@ var ts; return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0; } ts.getCheckFlags = getCheckFlags; - function getDeclarationModifierFlagsFromSymbol(s) { + function getDeclarationModifierFlagsFromSymbol(s, isWrite) { + if (isWrite === void 0) { isWrite = false; } if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + var declaration = (isWrite && s.declarations && ts.find(s.declarations, function (d) { return d.kind === 169 /* SetAccessor */; })) || s.valueDeclaration; + var flags = ts.getCombinedModifierFlags(declaration); return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; } if (getCheckFlags(s) & 6 /* Synthetic */) { @@ -18464,35 +18745,35 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return accessKind(parent); - case 215 /* PostfixUnaryExpression */: - case 214 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: var operator = parent.operator; return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? operatorToken.kind === 62 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() : 0 /* Read */; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); - case 288 /* PropertyAssignment */: { + case 289 /* 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 289 /* ShorthandPropertyAssignment */: + case 290 /* 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 199 /* ArrayLiteralExpression */: + case 200 /* 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 && skipParenthesesUp(parent.parent).kind === 233 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 234 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; } } function reverseAccessKind(a) { @@ -18580,7 +18861,8 @@ var ts; } ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol; function getClassLikeDeclarationOfSymbol(symbol) { - return ts.find(symbol.declarations, ts.isClassLike); + var _a; + return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isClassLike); } ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; function getObjectFlags(type) { @@ -18623,7 +18905,6 @@ var ts; ts.getLastChild = getLastChild; function addToSeen(seen, key, value) { if (value === void 0) { value = true; } - key = String(key); if (seen.has(key)) { return false; } @@ -18636,7 +18917,7 @@ var ts; } ts.isObjectTypeDeclaration = isObjectTypeDeclaration; function isTypeNodeKind(kind) { - return (kind >= 172 /* FirstTypeNode */ && kind <= 195 /* LastTypeNode */) + return (kind >= 173 /* FirstTypeNode */ && kind <= 196 /* LastTypeNode */) || kind === 128 /* AnyKeyword */ || kind === 152 /* UnknownKeyword */ || kind === 144 /* NumberKeyword */ @@ -18648,25 +18929,25 @@ var ts; || kind === 113 /* VoidKeyword */ || kind === 150 /* UndefinedKeyword */ || kind === 141 /* NeverKeyword */ - || kind === 223 /* ExpressionWithTypeArguments */ - || kind === 303 /* JSDocAllType */ - || kind === 304 /* JSDocUnknownType */ - || kind === 305 /* JSDocNullableType */ - || kind === 306 /* JSDocNonNullableType */ - || kind === 307 /* JSDocOptionalType */ - || kind === 308 /* JSDocFunctionType */ - || kind === 309 /* JSDocVariadicType */; + || kind === 224 /* ExpressionWithTypeArguments */ + || kind === 304 /* JSDocAllType */ + || kind === 305 /* JSDocUnknownType */ + || kind === 306 /* JSDocNullableType */ + || kind === 307 /* JSDocNonNullableType */ + || kind === 308 /* JSDocOptionalType */ + || kind === 309 /* JSDocFunctionType */ + || kind === 310 /* JSDocVariadicType */; } ts.isTypeNodeKind = isTypeNodeKind; function isAccessExpression(node) { - return node.kind === 201 /* PropertyAccessExpression */ || node.kind === 202 /* ElementAccessExpression */; + return node.kind === 202 /* PropertyAccessExpression */ || node.kind === 203 /* ElementAccessExpression */; } ts.isAccessExpression = isAccessExpression; function getNameOfAccessExpression(node) { - if (node.kind === 201 /* PropertyAccessExpression */) { + if (node.kind === 202 /* PropertyAccessExpression */) { return node.name; } - ts.Debug.assert(node.kind === 202 /* ElementAccessExpression */); + ts.Debug.assert(node.kind === 203 /* ElementAccessExpression */); return node.argumentExpression; } ts.getNameOfAccessExpression = getNameOfAccessExpression; @@ -18681,7 +18962,7 @@ var ts; } ts.isBundleFileTextLike = isBundleFileTextLike; function isNamedImportsOrExports(node) { - return node.kind === 264 /* NamedImports */ || node.kind === 268 /* NamedExports */; + return node.kind === 265 /* NamedImports */ || node.kind === 269 /* NamedExports */; } ts.isNamedImportsOrExports = isNamedImportsOrExports; function getLeftmostAccessExpression(expr) { @@ -18694,28 +18975,28 @@ var ts; function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: node = node.operand; continue; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: node = node.left; continue; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: node = node.condition; continue; - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: node = node.tag; continue; - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (stopAtCallExpressions) { return node; } // falls through - case 224 /* AsExpression */: - case 202 /* ElementAccessExpression */: - case 201 /* PropertyAccessExpression */: - case 225 /* NonNullExpression */: - case 336 /* PartiallyEmittedExpression */: + case 225 /* AsExpression */: + case 203 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 226 /* NonNullExpression */: + case 340 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -18734,7 +19015,7 @@ var ts; } function Type(checker, flags) { this.flags = flags; - if (ts.Debug.isDebugging || ts.tracing.isTracing()) { + if (ts.Debug.isDebugging || ts.tracing) { this.checker = checker; } } @@ -19078,6 +19359,10 @@ var ts; return !!(compilerOptions.declaration || compilerOptions.composite); } ts.getEmitDeclarations = getEmitDeclarations; + function shouldPreserveConstEnums(compilerOptions) { + return !!(compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + } + ts.shouldPreserveConstEnums = shouldPreserveConstEnums; function isIncrementalCompilation(options) { return !!(options.incremental || options.composite); } @@ -19090,6 +19375,10 @@ var ts; return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs; } ts.getAllowJSCompilerOption = getAllowJSCompilerOption; + function getUseDefineForClassFields(compilerOptions) { + return compilerOptions.useDefineForClassFields === undefined ? compilerOptions.target === 99 /* ESNext */ : compilerOptions.useDefineForClassFields; + } + ts.getUseDefineForClassFields = getUseDefineForClassFields; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { return oldOptions !== newOptions && ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); @@ -19111,7 +19400,7 @@ var ts; ts.getJSXTransformEnabled = getJSXTransformEnabled; function getJSXImplicitImportBase(compilerOptions, file) { var jsxImportSourcePragmas = file === null || file === void 0 ? void 0 : file.pragmas.get("jsximportsource"); - var jsxImportSourcePragma = ts.isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[0] : jsxImportSourcePragmas; + var jsxImportSourcePragma = ts.isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[jsxImportSourcePragmas.length - 1] : jsxImportSourcePragmas; return compilerOptions.jsx === 4 /* ReactJSX */ || compilerOptions.jsx === 5 /* ReactJSXDev */ || compilerOptions.jsxImportSource || @@ -19140,37 +19429,65 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createSymlinkCache() { + function createSymlinkCache(cwd, getCanonicalFileName) { var symlinkedDirectories; + var symlinkedDirectoriesByRealpath; var symlinkedFiles; return { getSymlinkedFiles: function () { return symlinkedFiles; }, getSymlinkedDirectories: function () { return symlinkedDirectories; }, + getSymlinkedDirectoriesByRealpath: function () { return symlinkedDirectoriesByRealpath; }, setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); }, - setSymlinkedDirectory: function (path, directory) { return (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(path, directory); }, + setSymlinkedDirectory: function (symlink, real) { + // Large, interconnected dependency graphs in pnpm will have a huge number of symlinks + // where both the realpath and the symlink path are inside node_modules/.pnpm. Since + // this path is never a candidate for a module specifier, we can ignore it entirely. + var symlinkPath = ts.toPath(symlink, cwd, getCanonicalFileName); + if (!containsIgnoredPath(symlinkPath)) { + symlinkPath = ts.ensureTrailingDirectorySeparator(symlinkPath); + if (real !== false && !(symlinkedDirectories === null || symlinkedDirectories === void 0 ? void 0 : symlinkedDirectories.has(symlinkPath))) { + (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = ts.createMultiMap())).add(ts.ensureTrailingDirectorySeparator(real.realPath), symlink); + } + (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); + } + }, + setSymlinkedDirectoryFromSymlinkedFile: function (symlink, real) { + this.setSymlinkedFile(ts.toPath(symlink, cwd, getCanonicalFileName), real); + var _a = guessDirectorySymlink(real, symlink, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _a[0], commonOriginal = _a[1]; + if (commonResolved && commonOriginal) { + this.setSymlinkedDirectory(commonOriginal, { + real: commonResolved, + realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName), + }); + } + }, }; } ts.createSymlinkCache = createSymlinkCache; function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { - var cache = createSymlinkCache(); - var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { - return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) { - return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + var cache = createSymlinkCache(cwd, getCanonicalFileName); + var symlinks = ts.flatMap(files, function (sf) { + var pairs = sf.resolvedModules && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedModules.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) ? [res.resolvedFileName, res.originalPath] : undefined; + })); + return ts.concatenate(pairs, sf.resolvedTypeReferenceDirectiveNames && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedTypeReferenceDirectiveNames.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) && res.resolvedFileName ? [res.resolvedFileName, res.originalPath] : undefined; }))); - })); + }); for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + cache.setSymlinkedFile(ts.toPath(originalPath, cwd, getCanonicalFileName), resolvedPath); var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1]; if (commonResolved && commonOriginal) { - cache.setSymlinkedDirectory(ts.toPath(commonOriginal, cwd, getCanonicalFileName), { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); + cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); } } return cache; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(a, cwd)); + var bParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(b, cwd)); var isDirectory = false; while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && @@ -19554,6 +19871,14 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + function numberOfDirectorySeparators(str) { + var match = str.match(/\//g); + return match ? match.length : 0; + } + function compareNumberOfDirectorySeparators(path1, path2) { + return ts.compareValues(numberOfDirectorySeparators(path1), numberOfDirectorySeparators(path2)); + } + ts.compareNumberOfDirectorySeparators = compareNumberOfDirectorySeparators; /** * Extension boundaries by priority. Lower numbers indicate higher priorities, and are * aligned to the offset of the highest priority extension in the @@ -19850,21 +20175,21 @@ var ts; } ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite; function typeOnlyDeclarationIsExport(typeOnlyDeclaration) { - return typeOnlyDeclaration.kind === 270 /* ExportSpecifier */; + return typeOnlyDeclaration.kind === 271 /* ExportSpecifier */; } ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport; function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) { - while (node.kind === 78 /* Identifier */ || node.kind === 201 /* PropertyAccessExpression */) { + while (node.kind === 78 /* Identifier */ || node.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - if (node.kind !== 158 /* ComputedPropertyName */) { + if (node.kind !== 159 /* ComputedPropertyName */) { return false; } if (hasSyntacticModifier(node.parent, 128 /* Abstract */)) { return true; } var containerKind = node.parent.parent.kind; - return containerKind === 253 /* InterfaceDeclaration */ || containerKind === 177 /* TypeLiteral */; + return containerKind === 254 /* InterfaceDeclaration */ || containerKind === 178 /* TypeLiteral */; } /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */ function isIdentifierInNonEmittingHeritageClause(node) { @@ -19872,16 +20197,16 @@ var ts; return false; var heritageClause = ts.findAncestor(node.parent, function (parent) { switch (parent.kind) { - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: return true; - case 201 /* PropertyAccessExpression */: - case 223 /* ExpressionWithTypeArguments */: + case 202 /* PropertyAccessExpression */: + case 224 /* ExpressionWithTypeArguments */: return false; default: return "quit"; } }); - return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 116 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 253 /* InterfaceDeclaration */; + return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 116 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 254 /* InterfaceDeclaration */; } function isIdentifierTypeReference(node) { return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName); @@ -20034,6 +20359,76 @@ var ts; } } ts.expressionResultIsUnused = expressionResultIsUnused; + function containsIgnoredPath(path) { + return ts.some(ts.ignoredPaths, function (p) { return ts.stringContains(path, p); }); + } + ts.containsIgnoredPath = containsIgnoredPath; + function getContainingNodeArray(node) { + if (!node.parent) + return undefined; + switch (node.kind) { + case 160 /* TypeParameter */: + var parent_1 = node.parent; + return parent_1.kind === 186 /* InferType */ ? undefined : parent_1.typeParameters; + case 161 /* Parameter */: + return node.parent.parameters; + case 195 /* TemplateLiteralTypeSpan */: + return node.parent.templateSpans; + case 229 /* TemplateSpan */: + return node.parent.templateSpans; + case 162 /* Decorator */: + return node.parent.decorators; + case 287 /* HeritageClause */: + return node.parent.heritageClauses; + } + var parent = node.parent; + if (ts.isJSDocTag(node)) { + return ts.isJSDocTypeLiteral(node.parent) ? undefined : node.parent.tags; + } + switch (parent.kind) { + case 178 /* TypeLiteral */: + case 254 /* InterfaceDeclaration */: + return ts.isTypeElement(node) ? parent.members : undefined; + case 183 /* UnionType */: + case 184 /* IntersectionType */: + return parent.types; + case 180 /* TupleType */: + case 200 /* ArrayLiteralExpression */: + case 341 /* CommaListExpression */: + case 265 /* NamedImports */: + case 269 /* NamedExports */: + return parent.elements; + case 201 /* ObjectLiteralExpression */: + case 282 /* JsxAttributes */: + return parent.properties; + case 204 /* CallExpression */: + case 205 /* NewExpression */: + return ts.isTypeNode(node) ? parent.typeArguments : + parent.expression === node ? undefined : + parent.arguments; + case 274 /* JsxElement */: + case 278 /* JsxFragment */: + return ts.isJsxChild(node) ? parent.children : undefined; + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + return ts.isTypeNode(node) ? parent.typeArguments : undefined; + case 231 /* Block */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 258 /* ModuleBlock */: + return parent.statements; + case 259 /* CaseBlock */: + return parent.clauses; + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + return ts.isClassElement(node) ? parent.members : undefined; + case 256 /* EnumDeclaration */: + return ts.isEnumMember(node) ? parent.members : undefined; + case 298 /* SourceFile */: + return parent.statements; + } + } + ts.getContainingNodeArray = getContainingNodeArray; })(ts || (ts = {})); /* @internal */ var ts; @@ -20078,7 +20473,11 @@ var ts; var ts; (function (ts) { function createParenthesizerRules(factory) { + var binaryLeftOperandParenthesizerCache; + var binaryRightOperandParenthesizerCache; return { + getParenthesizeLeftSideOfBinaryForOperator: getParenthesizeLeftSideOfBinaryForOperator, + getParenthesizeRightSideOfBinaryForOperator: getParenthesizeRightSideOfBinaryForOperator, parenthesizeLeftSideOfBinary: parenthesizeLeftSideOfBinary, parenthesizeRightSideOfBinary: parenthesizeRightSideOfBinary, parenthesizeExpressionOfComputedPropertyName: parenthesizeExpressionOfComputedPropertyName, @@ -20099,6 +20498,24 @@ var ts; parenthesizeConstituentTypesOfUnionOrIntersectionType: parenthesizeConstituentTypesOfUnionOrIntersectionType, parenthesizeTypeArguments: parenthesizeTypeArguments, }; + function getParenthesizeLeftSideOfBinaryForOperator(operatorKind) { + binaryLeftOperandParenthesizerCache || (binaryLeftOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeLeftSideOfBinary(operatorKind, node); }; + binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } + function getParenthesizeRightSideOfBinaryForOperator(operatorKind) { + binaryRightOperandParenthesizerCache || (binaryRightOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeRightSideOfBinary(operatorKind, /*leftSide*/ undefined, node); }; + binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } /** * Determines whether the operand to a BinaryExpression needs to be parenthesized. * @@ -20125,10 +20542,10 @@ var ts; // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - var binaryOperatorPrecedence = ts.getOperatorPrecedence(216 /* BinaryExpression */, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(216 /* BinaryExpression */, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(217 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(217 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); - if (!isLeftSideOfBinary && operand.kind === 209 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */) { + if (!isLeftSideOfBinary && operand.kind === 210 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */) { // We need to parenthesize arrow functions on the right side to avoid it being // parsed as parenthesized expression: `a && (() => {})` return true; @@ -20140,7 +20557,7 @@ var ts; // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ - && operand.kind === 219 /* YieldExpression */) { + && operand.kind === 220 /* YieldExpression */) { return false; } return true; @@ -20228,7 +20645,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) { + if (node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -20254,7 +20671,7 @@ var ts; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. - if (skipped.kind === 207 /* ParenthesizedExpression */) { + if (skipped.kind === 208 /* ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -20271,7 +20688,7 @@ var ts; return ts.isCommaSequence(expression) ? factory.createParenthesizedExpression(expression) : expression; } function parenthesizeConditionOfConditionalExpression(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(217 /* ConditionalExpression */, 57 /* QuestionToken */); + var conditionalPrecedence = ts.getOperatorPrecedence(218 /* ConditionalExpression */, 57 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) { @@ -20304,8 +20721,8 @@ var ts; var needsParens = ts.isCommaSequence(check); if (!needsParens) { switch (ts.getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: needsParens = true; } } @@ -20318,9 +20735,9 @@ var ts; function parenthesizeExpressionOfNew(expression) { var leftmostExpr = ts.getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); switch (leftmostExpr.kind) { - case 203 /* CallExpression */: + case 204 /* CallExpression */: return factory.createParenthesizedExpression(expression); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return !leftmostExpr.arguments ? factory.createParenthesizedExpression(expression) : expression; // TODO(rbuckton): Verify this assertion holds @@ -20340,7 +20757,7 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 204 /* NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 205 /* NewExpression */ || emittedExpression.arguments)) { // TODO(rbuckton): Verify whether this assertion holds. return expression; } @@ -20362,7 +20779,7 @@ var ts; function parenthesizeExpressionForDisallowedComma(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(216 /* BinaryExpression */, 27 /* CommaToken */); + var commaPrecedence = ts.getOperatorPrecedence(217 /* BinaryExpression */, 27 /* CommaToken */); // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(factory.createParenthesizedExpression(expression), expression); } @@ -20371,44 +20788,44 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 208 /* FunctionExpression */ || kind === 209 /* ArrowFunction */) { + if (kind === 209 /* FunctionExpression */ || kind === 210 /* ArrowFunction */) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. var updated = factory.updateCallExpression(emittedExpression, ts.setTextRange(factory.createParenthesizedExpression(callee), callee), emittedExpression.typeArguments, emittedExpression.arguments); return factory.restoreOuterExpressions(expression, updated, 8 /* PartiallyEmittedExpressions */); } } var leftmostExpressionKind = ts.getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; - if (leftmostExpressionKind === 200 /* ObjectLiteralExpression */ || leftmostExpressionKind === 208 /* FunctionExpression */) { + if (leftmostExpressionKind === 201 /* ObjectLiteralExpression */ || leftmostExpressionKind === 209 /* FunctionExpression */) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return ts.setTextRange(factory.createParenthesizedExpression(expression), expression); } return expression; } function parenthesizeConciseBodyOfArrowFunction(body) { - if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 200 /* ObjectLiteralExpression */)) { + if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 201 /* ObjectLiteralExpression */)) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return ts.setTextRange(factory.createParenthesizedExpression(body), body); } return body; } function parenthesizeMemberOfConditionalType(member) { - return member.kind === 184 /* ConditionalType */ ? factory.createParenthesizedType(member) : member; + return member.kind === 185 /* ConditionalType */ ? factory.createParenthesizedType(member) : member; } function parenthesizeMemberOfElementType(member) { switch (member.kind) { - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return factory.createParenthesizedType(member); } return parenthesizeMemberOfConditionalType(member); } function parenthesizeElementTypeOfArrayType(member) { switch (member.kind) { - case 176 /* TypeQuery */: - case 188 /* TypeOperator */: - case 185 /* InferType */: + case 177 /* TypeQuery */: + case 189 /* TypeOperator */: + case 186 /* InferType */: return factory.createParenthesizedType(member); } return parenthesizeMemberOfElementType(member); @@ -20427,6 +20844,8 @@ var ts; } ts.createParenthesizerRules = createParenthesizerRules; ts.nullParenthesizerRules = { + getParenthesizeLeftSideOfBinaryForOperator: function (_) { return ts.identity; }, + getParenthesizeRightSideOfBinaryForOperator: function (_) { return ts.identity; }, parenthesizeLeftSideOfBinary: function (_binaryOperator, leftSide) { return leftSide; }, parenthesizeRightSideOfBinary: function (_binaryOperator, _leftSide, rightSide) { return rightSide; }, parenthesizeExpressionOfComputedPropertyName: ts.identity, @@ -20512,11 +20931,11 @@ var ts; } function convertToAssignmentPattern(node) { switch (node.kind) { - case 197 /* ArrayBindingPattern */: - case 199 /* ArrayLiteralExpression */: + case 198 /* ArrayBindingPattern */: + case 200 /* ArrayLiteralExpression */: return convertToArrayAssignmentPattern(node); - case 196 /* ObjectBindingPattern */: - case 200 /* ObjectLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 201 /* ObjectLiteralExpression */: return convertToObjectAssignmentPattern(node); } } @@ -20857,18 +21276,18 @@ var ts; createExternalModuleReference: createExternalModuleReference, updateExternalModuleReference: updateExternalModuleReference, // lazily load factory members for JSDoc types with similar structure - get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(303 /* JSDocAllType */); }, - get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(304 /* JSDocUnknownType */); }, - get createJSDocNonNullableType() { return getJSDocUnaryTypeCreateFunction(306 /* JSDocNonNullableType */); }, - get updateJSDocNonNullableType() { return getJSDocUnaryTypeUpdateFunction(306 /* JSDocNonNullableType */); }, - get createJSDocNullableType() { return getJSDocUnaryTypeCreateFunction(305 /* JSDocNullableType */); }, - get updateJSDocNullableType() { return getJSDocUnaryTypeUpdateFunction(305 /* JSDocNullableType */); }, - get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(307 /* JSDocOptionalType */); }, - get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(307 /* JSDocOptionalType */); }, - get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(309 /* JSDocVariadicType */); }, - get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(309 /* JSDocVariadicType */); }, - get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(310 /* JSDocNamepathType */); }, - get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(310 /* JSDocNamepathType */); }, + get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(304 /* JSDocAllType */); }, + get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(305 /* JSDocUnknownType */); }, + get createJSDocNonNullableType() { return getJSDocUnaryTypeCreateFunction(307 /* JSDocNonNullableType */); }, + get updateJSDocNonNullableType() { return getJSDocUnaryTypeUpdateFunction(307 /* JSDocNonNullableType */); }, + get createJSDocNullableType() { return getJSDocUnaryTypeCreateFunction(306 /* JSDocNullableType */); }, + get updateJSDocNullableType() { return getJSDocUnaryTypeUpdateFunction(306 /* JSDocNullableType */); }, + get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(308 /* JSDocOptionalType */); }, + get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(308 /* JSDocOptionalType */); }, + get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(310 /* JSDocVariadicType */); }, + get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(310 /* JSDocVariadicType */); }, + get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(311 /* JSDocNamepathType */); }, + get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(311 /* JSDocNamepathType */); }, createJSDocFunctionType: createJSDocFunctionType, updateJSDocFunctionType: updateJSDocFunctionType, createJSDocTypeLiteral: createJSDocTypeLiteral, @@ -20895,31 +21314,37 @@ var ts; updateJSDocSeeTag: updateJSDocSeeTag, createJSDocNameReference: createJSDocNameReference, updateJSDocNameReference: updateJSDocNameReference, + createJSDocLink: createJSDocLink, + updateJSDocLink: updateJSDocLink, // lazily load factory members for JSDoc tags with similar structure - get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(329 /* JSDocTypeTag */); }, - get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(329 /* JSDocTypeTag */); }, - get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(327 /* JSDocReturnTag */); }, - get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(327 /* JSDocReturnTag */); }, - get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(328 /* JSDocThisTag */); }, - get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(328 /* JSDocThisTag */); }, - get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(325 /* JSDocEnumTag */); }, - get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(325 /* JSDocEnumTag */); }, - get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(317 /* JSDocAuthorTag */); }, - get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(317 /* JSDocAuthorTag */); }, - get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(319 /* JSDocClassTag */); }, - get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(319 /* JSDocClassTag */); }, - get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(320 /* JSDocPublicTag */); }, - get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(320 /* JSDocPublicTag */); }, - get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(321 /* JSDocPrivateTag */); }, - get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(321 /* JSDocPrivateTag */); }, - get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(322 /* JSDocProtectedTag */); }, - get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(322 /* JSDocProtectedTag */); }, - get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(323 /* JSDocReadonlyTag */); }, - get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(323 /* JSDocReadonlyTag */); }, - get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(318 /* JSDocDeprecatedTag */); }, - get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(318 /* JSDocDeprecatedTag */); }, + get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(333 /* JSDocTypeTag */); }, + get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(333 /* JSDocTypeTag */); }, + get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(331 /* JSDocReturnTag */); }, + get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(331 /* JSDocReturnTag */); }, + get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(332 /* JSDocThisTag */); }, + get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(332 /* JSDocThisTag */); }, + get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(329 /* JSDocEnumTag */); }, + get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(329 /* JSDocEnumTag */); }, + get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(320 /* JSDocAuthorTag */); }, + get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(320 /* JSDocAuthorTag */); }, + get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(322 /* JSDocClassTag */); }, + get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(322 /* JSDocClassTag */); }, + get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(323 /* JSDocPublicTag */); }, + get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(323 /* JSDocPublicTag */); }, + get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(324 /* JSDocPrivateTag */); }, + get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(324 /* JSDocPrivateTag */); }, + get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(325 /* JSDocProtectedTag */); }, + get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(325 /* JSDocProtectedTag */); }, + get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(326 /* JSDocReadonlyTag */); }, + get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(326 /* JSDocReadonlyTag */); }, + get createJSDocOverrideTag() { return getJSDocSimpleTagCreateFunction(327 /* JSDocOverrideTag */); }, + get updateJSDocOverrideTag() { return getJSDocSimpleTagUpdateFunction(327 /* JSDocOverrideTag */); }, + get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(321 /* JSDocDeprecatedTag */); }, + get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(321 /* JSDocDeprecatedTag */); }, createJSDocUnknownTag: createJSDocUnknownTag, updateJSDocUnknownTag: updateJSDocUnknownTag, + createJSDocText: createJSDocText, + updateJSDocText: updateJSDocText, createJSDocComment: createJSDocComment, updateJSDocComment: updateJSDocComment, createJsxElement: createJsxElement, @@ -21103,11 +21528,11 @@ var ts; // don't propagate child flags. if (name) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 163 /* PropertyDeclaration */: - case 288 /* PropertyAssignment */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 289 /* PropertyAssignment */: if (ts.isIdentifier(name)) { node.transformFlags |= propagateIdentifierNameFlags(name); break; @@ -21148,7 +21573,7 @@ var ts; function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) { var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type); node.body = body; - node.transformFlags |= propagateChildFlags(node.body) & ~8388608 /* ContainsPossibleTopLevelAwait */; + node.transformFlags |= propagateChildFlags(node.body) & ~16777216 /* ContainsPossibleTopLevelAwait */; if (!body) node.transformFlags |= 1 /* ContainsTypeScript */; return node; @@ -21201,7 +21626,7 @@ var ts; var node = createBaseLiteral(8 /* NumericLiteral */, typeof value === "number" ? value + "" : value); node.numericLiteralFlags = numericLiteralFlags; if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -21220,7 +21645,7 @@ var ts; var node = createBaseStringLiteral(text, isSingleQuote); node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; if (hasExtendedUnicodeEscape) - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -21276,7 +21701,7 @@ var ts; node.typeArguments = createNodeArray(typeArguments); } if (node.originalKeywordKind === 130 /* AwaitKeyword */) { - node.transformFlags |= 8388608 /* ContainsPossibleTopLevelAwait */; + node.transformFlags |= 16777216 /* ContainsPossibleTopLevelAwait */; } return node; } @@ -21299,8 +21724,11 @@ var ts; } /** Create a unique temporary variable for use in a loop. */ // @api - function createLoopVariable() { - return createBaseGeneratedIdentifier("", 2 /* Loop */); + function createLoopVariable(reservedInNestedScopes) { + var flags = 2 /* Loop */; + if (reservedInNestedScopes) + flags |= 8 /* ReservedInNestedScopes */; + return createBaseGeneratedIdentifier("", flags); } /** Create a unique name based on the supplied text. */ // @api @@ -21325,7 +21753,7 @@ var ts; ts.Debug.fail("First character of private identifier must be #: " + text); var node = baseFactory.createBasePrivateIdentifierNode(79 /* PrivateIdentifier */); node.escapedText = ts.escapeLeadingUnderscores(text); - node.transformFlags |= 4194304 /* ContainsClassFields */; + node.transformFlags |= 8388608 /* ContainsClassFields */; return node; } // @@ -21335,7 +21763,7 @@ var ts; return baseFactory.createBaseTokenNode(kind); } function createToken(token) { - ts.Debug.assert(token >= 0 /* FirstToken */ && token <= 156 /* LastToken */, "Invalid token"); + ts.Debug.assert(token >= 0 /* FirstToken */ && token <= 157 /* LastToken */, "Invalid token"); ts.Debug.assert(token <= 14 /* FirstTemplateToken */ || token >= 17 /* LastTemplateToken */, "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals."); ts.Debug.assert(token <= 8 /* FirstLiteralToken */ || token >= 14 /* LastLiteralToken */, "Invalid token. Use 'createLiteralLikeNode' to create literals."); ts.Debug.assert(token !== 78 /* Identifier */, "Invalid token. Use 'createIdentifier' to create identifiers"); @@ -21345,8 +21773,8 @@ var ts; case 129 /* AsyncKeyword */: // 'async' modifier is ES2017 (async functions) or ES2018 (async generators) transformFlags = - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */; break; case 122 /* PublicKeyword */: case 120 /* PrivateKeyword */: @@ -21360,6 +21788,7 @@ var ts; case 155 /* BigIntKeyword */: case 141 /* NeverKeyword */: case 145 /* ObjectKeyword */: + case 156 /* OverrideKeyword */: case 147 /* StringKeyword */: case 131 /* BooleanKeyword */: case 148 /* SymbolKeyword */: @@ -21370,11 +21799,11 @@ var ts; break; case 123 /* StaticKeyword */: case 105 /* SuperKeyword */: - transformFlags = 256 /* ContainsES2015 */; + transformFlags = 512 /* ContainsES2015 */; break; case 107 /* ThisKeyword */: // 'this' indicates a lexical 'this' - transformFlags = 4096 /* ContainsLexicalThis */; + transformFlags = 8192 /* ContainsLexicalThis */; break; } if (transformFlags) { @@ -21442,6 +21871,9 @@ var ts; if (flags & 32 /* Static */) { result.push(createModifier(123 /* StaticKeyword */)); } + if (flags & 16384 /* Override */) { + result.push(createModifier(156 /* OverrideKeyword */)); + } if (flags & 64 /* Readonly */) { result.push(createModifier(142 /* ReadonlyKeyword */)); } @@ -21455,7 +21887,7 @@ var ts; // // @api function createQualifiedName(left, right) { - var node = createBaseNode(157 /* QualifiedName */); + var node = createBaseNode(158 /* QualifiedName */); node.left = left; node.right = asName(right); node.transformFlags |= @@ -21472,12 +21904,12 @@ var ts; } // @api function createComputedPropertyName(expression) { - var node = createBaseNode(158 /* ComputedPropertyName */); + var node = createBaseNode(159 /* ComputedPropertyName */); node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 256 /* ContainsES2015 */ | - 32768 /* ContainsComputedPropertyName */; + 512 /* ContainsES2015 */ | + 65536 /* ContainsComputedPropertyName */; return node; } // @api @@ -21491,7 +21923,7 @@ var ts; // // @api function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createBaseNamedDeclaration(159 /* TypeParameter */, + var node = createBaseNamedDeclaration(160 /* TypeParameter */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.constraint = constraint; @@ -21509,7 +21941,7 @@ var ts; } // @api function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(160 /* Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); + var node = createBaseVariableLikeDeclaration(161 /* Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.dotDotDotToken = dotDotDotToken; node.questionToken = questionToken; if (ts.isThisIdentifier(node.name)) { @@ -21521,10 +21953,10 @@ var ts; propagateChildFlags(node.questionToken); if (questionToken) node.transformFlags |= 1 /* ContainsTypeScript */; - if (ts.modifiersToFlags(node.modifiers) & 92 /* ParameterPropertyModifier */) - node.transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */; + if (ts.modifiersToFlags(node.modifiers) & 16476 /* ParameterPropertyModifier */) + node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; if (initializer || dotDotDotToken) - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; } return node; } @@ -21542,12 +21974,12 @@ var ts; } // @api function createDecorator(expression) { - var node = createBaseNode(161 /* Decorator */); + var node = createBaseNode(162 /* Decorator */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */ | - 2048 /* ContainsTypeScriptClassSyntax */; + 4096 /* ContainsTypeScriptClassSyntax */; return node; } // @api @@ -21561,7 +21993,7 @@ var ts; // // @api function createPropertySignature(modifiers, name, questionToken, type) { - var node = createBaseNamedDeclaration(162 /* PropertySignature */, + var node = createBaseNamedDeclaration(163 /* PropertySignature */, /*decorators*/ undefined, modifiers, name); node.type = type; node.questionToken = questionToken; @@ -21579,15 +22011,15 @@ var ts; } // @api function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(163 /* PropertyDeclaration */, decorators, modifiers, name, type, initializer); + var node = createBaseVariableLikeDeclaration(164 /* PropertyDeclaration */, decorators, modifiers, name, type, initializer); node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.transformFlags |= propagateChildFlags(node.questionToken) | propagateChildFlags(node.exclamationToken) | - 4194304 /* ContainsClassFields */; + 8388608 /* ContainsClassFields */; if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) { - node.transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */; + node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) { node.transformFlags |= 1 /* ContainsTypeScript */; @@ -21608,7 +22040,7 @@ var ts; } // @api function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(164 /* MethodSignature */, + var node = createBaseSignatureDeclaration(165 /* MethodSignature */, /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type); node.questionToken = questionToken; node.transformFlags = 1 /* ContainsTypeScript */; @@ -21627,26 +22059,26 @@ var ts; } // @api function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(165 /* MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(166 /* MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.questionToken = questionToken; node.transformFlags |= propagateChildFlags(node.asteriskToken) | propagateChildFlags(node.questionToken) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (questionToken) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (asteriskToken) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } else { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } } else if (asteriskToken) { - node.transformFlags |= 512 /* ContainsGenerator */; + node.transformFlags |= 1024 /* ContainsGenerator */; } return node; } @@ -21666,11 +22098,11 @@ var ts; } // @api function createConstructorDeclaration(decorators, modifiers, parameters, body) { - var node = createBaseFunctionLikeDeclaration(166 /* Constructor */, decorators, modifiers, + var node = createBaseFunctionLikeDeclaration(167 /* Constructor */, decorators, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -21684,7 +22116,7 @@ var ts; } // @api function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) { - return createBaseFunctionLikeDeclaration(167 /* GetAccessor */, decorators, modifiers, name, + return createBaseFunctionLikeDeclaration(168 /* GetAccessor */, decorators, modifiers, name, /*typeParameters*/ undefined, parameters, type, body); } // @api @@ -21700,7 +22132,7 @@ var ts; } // @api function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) { - return createBaseFunctionLikeDeclaration(168 /* SetAccessor */, decorators, modifiers, name, + return createBaseFunctionLikeDeclaration(169 /* SetAccessor */, decorators, modifiers, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); } @@ -21716,7 +22148,7 @@ var ts; } // @api function createCallSignature(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(169 /* CallSignature */, + var node = createBaseSignatureDeclaration(170 /* CallSignature */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); @@ -21733,7 +22165,7 @@ var ts; } // @api function createConstructSignature(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(170 /* ConstructSignature */, + var node = createBaseSignatureDeclaration(171 /* ConstructSignature */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); @@ -21750,7 +22182,7 @@ var ts; } // @api function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createBaseSignatureDeclaration(171 /* IndexSignature */, decorators, modifiers, + var node = createBaseSignatureDeclaration(172 /* IndexSignature */, decorators, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21767,7 +22199,7 @@ var ts; } // @api function createTemplateLiteralTypeSpan(type, literal) { - var node = createBaseNode(194 /* TemplateLiteralTypeSpan */); + var node = createBaseNode(195 /* TemplateLiteralTypeSpan */); node.type = type; node.literal = literal; node.transformFlags = 1 /* ContainsTypeScript */; @@ -21789,7 +22221,7 @@ var ts; } // @api function createTypePredicateNode(assertsModifier, parameterName, type) { - var node = createBaseNode(172 /* TypePredicate */); + var node = createBaseNode(173 /* TypePredicate */); node.assertsModifier = assertsModifier; node.parameterName = asName(parameterName); node.type = type; @@ -21806,7 +22238,7 @@ var ts; } // @api function createTypeReferenceNode(typeName, typeArguments) { - var node = createBaseNode(173 /* TypeReference */); + var node = createBaseNode(174 /* TypeReference */); node.typeName = asName(typeName); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(createNodeArray(typeArguments)); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21821,7 +22253,7 @@ var ts; } // @api function createFunctionTypeNode(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(174 /* FunctionType */, + var node = createBaseSignatureDeclaration(175 /* FunctionType */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); @@ -21847,7 +22279,7 @@ var ts; ts.Debug.fail("Incorrect number of arguments specified."); } function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(175 /* ConstructorType */, + var node = createBaseSignatureDeclaration(176 /* ConstructorType */, /*decorators*/ undefined, modifiers, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21881,7 +22313,7 @@ var ts; } // @api function createTypeQueryNode(exprName) { - var node = createBaseNode(176 /* TypeQuery */); + var node = createBaseNode(177 /* TypeQuery */); node.exprName = exprName; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21894,7 +22326,7 @@ var ts; } // @api function createTypeLiteralNode(members) { - var node = createBaseNode(177 /* TypeLiteral */); + var node = createBaseNode(178 /* TypeLiteral */); node.members = createNodeArray(members); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21907,7 +22339,7 @@ var ts; } // @api function createArrayTypeNode(elementType) { - var node = createBaseNode(178 /* ArrayType */); + var node = createBaseNode(179 /* ArrayType */); node.elementType = parenthesizerRules().parenthesizeElementTypeOfArrayType(elementType); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21920,7 +22352,7 @@ var ts; } // @api function createTupleTypeNode(elements) { - var node = createBaseNode(179 /* TupleType */); + var node = createBaseNode(180 /* TupleType */); node.elements = createNodeArray(elements); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21933,7 +22365,7 @@ var ts; } // @api function createNamedTupleMember(dotDotDotToken, name, questionToken, type) { - var node = createBaseNode(192 /* NamedTupleMember */); + var node = createBaseNode(193 /* NamedTupleMember */); node.dotDotDotToken = dotDotDotToken; node.name = name; node.questionToken = questionToken; @@ -21952,7 +22384,7 @@ var ts; } // @api function createOptionalTypeNode(type) { - var node = createBaseNode(180 /* OptionalType */); + var node = createBaseNode(181 /* OptionalType */); node.type = parenthesizerRules().parenthesizeElementTypeOfArrayType(type); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21965,7 +22397,7 @@ var ts; } // @api function createRestTypeNode(type) { - var node = createBaseNode(181 /* RestType */); + var node = createBaseNode(182 /* RestType */); node.type = type; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21989,7 +22421,7 @@ var ts; } // @api function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(182 /* UnionType */, types); + return createUnionOrIntersectionTypeNode(183 /* UnionType */, types); } // @api function updateUnionTypeNode(node, types) { @@ -21997,7 +22429,7 @@ var ts; } // @api function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(183 /* IntersectionType */, types); + return createUnionOrIntersectionTypeNode(184 /* IntersectionType */, types); } // @api function updateIntersectionTypeNode(node, types) { @@ -22005,7 +22437,7 @@ var ts; } // @api function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { - var node = createBaseNode(184 /* ConditionalType */); + var node = createBaseNode(185 /* ConditionalType */); node.checkType = parenthesizerRules().parenthesizeMemberOfConditionalType(checkType); node.extendsType = parenthesizerRules().parenthesizeMemberOfConditionalType(extendsType); node.trueType = trueType; @@ -22024,7 +22456,7 @@ var ts; } // @api function createInferTypeNode(typeParameter) { - var node = createBaseNode(185 /* InferType */); + var node = createBaseNode(186 /* InferType */); node.typeParameter = typeParameter; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -22037,7 +22469,7 @@ var ts; } // @api function createTemplateLiteralType(head, templateSpans) { - var node = createBaseNode(193 /* TemplateLiteralType */); + var node = createBaseNode(194 /* TemplateLiteralType */); node.head = head; node.templateSpans = createNodeArray(templateSpans); node.transformFlags = 1 /* ContainsTypeScript */; @@ -22053,7 +22485,7 @@ var ts; // @api function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { if (isTypeOf === void 0) { isTypeOf = false; } - var node = createBaseNode(195 /* ImportType */); + var node = createBaseNode(196 /* ImportType */); node.argument = argument; node.qualifier = qualifier; node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); @@ -22073,7 +22505,7 @@ var ts; } // @api function createParenthesizedType(type) { - var node = createBaseNode(186 /* ParenthesizedType */); + var node = createBaseNode(187 /* ParenthesizedType */); node.type = type; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -22086,13 +22518,13 @@ var ts; } // @api function createThisTypeNode() { - var node = createBaseNode(187 /* ThisType */); + var node = createBaseNode(188 /* ThisType */); node.transformFlags = 1 /* ContainsTypeScript */; return node; } // @api function createTypeOperatorNode(operator, type) { - var node = createBaseNode(188 /* TypeOperator */); + var node = createBaseNode(189 /* TypeOperator */); node.operator = operator; node.type = parenthesizerRules().parenthesizeMemberOfElementType(type); node.transformFlags = 1 /* ContainsTypeScript */; @@ -22106,7 +22538,7 @@ var ts; } // @api function createIndexedAccessTypeNode(objectType, indexType) { - var node = createBaseNode(189 /* IndexedAccessType */); + var node = createBaseNode(190 /* IndexedAccessType */); node.objectType = parenthesizerRules().parenthesizeMemberOfElementType(objectType); node.indexType = indexType; node.transformFlags = 1 /* ContainsTypeScript */; @@ -22121,7 +22553,7 @@ var ts; } // @api function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type) { - var node = createBaseNode(190 /* MappedType */); + var node = createBaseNode(191 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.nameType = nameType; @@ -22142,7 +22574,7 @@ var ts; } // @api function createLiteralTypeNode(literal) { - var node = createBaseNode(191 /* LiteralType */); + var node = createBaseNode(192 /* LiteralType */); node.literal = literal; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -22158,16 +22590,16 @@ var ts; // // @api function createObjectBindingPattern(elements) { - var node = createBaseNode(196 /* ObjectBindingPattern */); + var node = createBaseNode(197 /* ObjectBindingPattern */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | - 256 /* ContainsES2015 */ | - 131072 /* ContainsBindingPattern */; - if (node.transformFlags & 8192 /* ContainsRestOrSpread */) { + 512 /* ContainsES2015 */ | + 262144 /* ContainsBindingPattern */; + if (node.transformFlags & 16384 /* ContainsRestOrSpread */) { node.transformFlags |= - 32 /* ContainsES2018 */ | - 16384 /* ContainsObjectRestOrSpread */; + 64 /* ContainsES2018 */ | + 32768 /* ContainsObjectRestOrSpread */; } return node; } @@ -22179,12 +22611,12 @@ var ts; } // @api function createArrayBindingPattern(elements) { - var node = createBaseNode(197 /* ArrayBindingPattern */); + var node = createBaseNode(198 /* ArrayBindingPattern */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | - 256 /* ContainsES2015 */ | - 131072 /* ContainsBindingPattern */; + 512 /* ContainsES2015 */ | + 262144 /* ContainsBindingPattern */; return node; } // @api @@ -22195,21 +22627,21 @@ var ts; } // @api function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createBaseBindingLikeDeclaration(198 /* BindingElement */, + var node = createBaseBindingLikeDeclaration(199 /* BindingElement */, /*decorators*/ undefined, - /*modifiers*/ undefined, name, initializer); + /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; node.transformFlags |= propagateChildFlags(node.dotDotDotToken) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (node.propertyName) { node.transformFlags |= ts.isIdentifier(node.propertyName) ? propagateIdentifierNameFlags(node.propertyName) : propagateChildFlags(node.propertyName); } if (dotDotDotToken) - node.transformFlags |= 8192 /* ContainsRestOrSpread */; + node.transformFlags |= 16384 /* ContainsRestOrSpread */; return node; } // @api @@ -22231,7 +22663,7 @@ var ts; } // @api function createArrayLiteralExpression(elements, multiLine) { - var node = createBaseExpression(199 /* ArrayLiteralExpression */); + var node = createBaseExpression(200 /* ArrayLiteralExpression */); node.elements = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(elements)); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.elements); @@ -22245,7 +22677,7 @@ var ts; } // @api function createObjectLiteralExpression(properties, multiLine) { - var node = createBaseExpression(200 /* ObjectLiteralExpression */); + var node = createBaseExpression(201 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.properties); @@ -22259,7 +22691,7 @@ var ts; } // @api function createPropertyAccessExpression(expression, name) { - var node = createBaseExpression(201 /* PropertyAccessExpression */); + var node = createBaseExpression(202 /* PropertyAccessExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.name = asName(name); node.transformFlags = @@ -22271,8 +22703,8 @@ var ts; // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators node.transformFlags |= - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */; } return node; } @@ -22288,13 +22720,13 @@ var ts; } // @api function createPropertyAccessChain(expression, questionDotToken, name) { - var node = createBaseExpression(201 /* PropertyAccessExpression */); + var node = createBaseExpression(202 /* PropertyAccessExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.questionDotToken = questionDotToken; node.name = asName(name); node.transformFlags |= - 8 /* ContainsES2020 */ | + 16 /* ContainsES2020 */ | propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | (ts.isIdentifier(node.name) ? @@ -22315,7 +22747,7 @@ var ts; } // @api function createElementAccessExpression(expression, index) { - var node = createBaseExpression(202 /* ElementAccessExpression */); + var node = createBaseExpression(203 /* ElementAccessExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.argumentExpression = asExpression(index); node.transformFlags |= @@ -22325,8 +22757,8 @@ var ts; // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators node.transformFlags |= - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */; } return node; } @@ -22342,7 +22774,7 @@ var ts; } // @api function createElementAccessChain(expression, questionDotToken, index) { - var node = createBaseExpression(202 /* ElementAccessExpression */); + var node = createBaseExpression(203 /* ElementAccessExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.questionDotToken = questionDotToken; @@ -22351,7 +22783,7 @@ var ts; propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | propagateChildFlags(node.argumentExpression) | - 8 /* ContainsES2020 */; + 16 /* ContainsES2020 */; return node; } // @api @@ -22367,7 +22799,7 @@ var ts; } // @api function createCallExpression(expression, typeArguments, argumentsArray) { - var node = createBaseExpression(203 /* CallExpression */); + var node = createBaseExpression(204 /* CallExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); @@ -22379,10 +22811,10 @@ var ts; node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.isImportKeyword(node.expression)) { - node.transformFlags |= 2097152 /* ContainsDynamicImport */; + node.transformFlags |= 4194304 /* ContainsDynamicImport */; } else if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 4096 /* ContainsLexicalThis */; + node.transformFlags |= 8192 /* ContainsLexicalThis */; } return node; } @@ -22399,7 +22831,7 @@ var ts; } // @api function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) { - var node = createBaseExpression(203 /* CallExpression */); + var node = createBaseExpression(204 /* CallExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.questionDotToken = questionDotToken; @@ -22410,12 +22842,12 @@ var ts; propagateChildFlags(node.questionDotToken) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | - 8 /* ContainsES2020 */; + 16 /* ContainsES2020 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 4096 /* ContainsLexicalThis */; + node.transformFlags |= 8192 /* ContainsLexicalThis */; } return node; } @@ -22431,7 +22863,7 @@ var ts; } // @api function createNewExpression(expression, typeArguments, argumentsArray) { - var node = createBaseExpression(204 /* NewExpression */); + var node = createBaseExpression(205 /* NewExpression */); node.expression = parenthesizerRules().parenthesizeExpressionOfNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(argumentsArray) : undefined; @@ -22439,7 +22871,7 @@ var ts; propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | - 8 /* ContainsES2020 */; + 16 /* ContainsES2020 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } @@ -22455,7 +22887,7 @@ var ts; } // @api function createTaggedTemplateExpression(tag, typeArguments, template) { - var node = createBaseExpression(205 /* TaggedTemplateExpression */); + var node = createBaseExpression(206 /* TaggedTemplateExpression */); node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag); node.typeArguments = asNodeArray(typeArguments); node.template = template; @@ -22463,12 +22895,12 @@ var ts; propagateChildFlags(node.tag) | propagateChildrenFlags(node.typeArguments) | propagateChildFlags(node.template) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.hasInvalidEscape(node.template)) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } return node; } @@ -22482,7 +22914,7 @@ var ts; } // @api function createTypeAssertion(type, expression) { - var node = createBaseExpression(206 /* TypeAssertionExpression */); + var node = createBaseExpression(207 /* TypeAssertionExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.type = type; node.transformFlags |= @@ -22500,7 +22932,7 @@ var ts; } // @api function createParenthesizedExpression(expression) { - var node = createBaseExpression(207 /* ParenthesizedExpression */); + var node = createBaseExpression(208 /* ParenthesizedExpression */); node.expression = expression; node.transformFlags = propagateChildFlags(node.expression); return node; @@ -22513,7 +22945,7 @@ var ts; } // @api function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(208 /* FunctionExpression */, + var node = createBaseFunctionLikeDeclaration(209 /* FunctionExpression */, /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.asteriskToken); @@ -22522,14 +22954,14 @@ var ts; } if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (node.asteriskToken) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } else { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } } else if (node.asteriskToken) { - node.transformFlags |= 512 /* ContainsGenerator */; + node.transformFlags |= 1024 /* ContainsGenerator */; } return node; } @@ -22547,15 +22979,15 @@ var ts; } // @api function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createBaseFunctionLikeDeclaration(209 /* ArrowFunction */, + var node = createBaseFunctionLikeDeclaration(210 /* ArrowFunction */, /*decorators*/ undefined, modifiers, /*name*/ undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body)); node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* EqualsGreaterThanToken */); node.transformFlags |= propagateChildFlags(node.equalsGreaterThanToken) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } return node; } @@ -22572,7 +23004,7 @@ var ts; } // @api function createDeleteExpression(expression) { - var node = createBaseExpression(210 /* DeleteExpression */); + var node = createBaseExpression(211 /* DeleteExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -22585,7 +23017,7 @@ var ts; } // @api function createTypeOfExpression(expression) { - var node = createBaseExpression(211 /* TypeOfExpression */); + var node = createBaseExpression(212 /* TypeOfExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -22598,7 +23030,7 @@ var ts; } // @api function createVoidExpression(expression) { - var node = createBaseExpression(212 /* VoidExpression */); + var node = createBaseExpression(213 /* VoidExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -22611,13 +23043,13 @@ var ts; } // @api function createAwaitExpression(expression) { - var node = createBaseExpression(213 /* AwaitExpression */); + var node = createBaseExpression(214 /* AwaitExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */ | - 524288 /* ContainsAwait */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */ | + 1048576 /* ContainsAwait */; return node; } // @api @@ -22628,7 +23060,7 @@ var ts; } // @api function createPrefixUnaryExpression(operator, operand) { - var node = createBaseExpression(214 /* PrefixUnaryExpression */); + var node = createBaseExpression(215 /* PrefixUnaryExpression */); node.operator = operator; node.operand = parenthesizerRules().parenthesizeOperandOfPrefixUnary(operand); node.transformFlags |= propagateChildFlags(node.operand); @@ -22642,7 +23074,7 @@ var ts; } // @api function createPostfixUnaryExpression(operand, operator) { - var node = createBaseExpression(215 /* PostfixUnaryExpression */); + var node = createBaseExpression(216 /* PostfixUnaryExpression */); node.operator = operator; node.operand = parenthesizerRules().parenthesizeOperandOfPostfixUnary(operand); node.transformFlags = propagateChildFlags(node.operand); @@ -22656,7 +23088,7 @@ var ts; } // @api function createBinaryExpression(left, operator, right) { - var node = createBaseExpression(216 /* BinaryExpression */); + var node = createBaseExpression(217 /* BinaryExpression */); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = parenthesizerRules().parenthesizeLeftSideOfBinary(operatorKind, left); @@ -22667,45 +23099,45 @@ var ts; propagateChildFlags(node.operatorToken) | propagateChildFlags(node.right); if (operatorKind === 60 /* QuestionQuestionToken */) { - node.transformFlags |= 8 /* ContainsES2020 */; + node.transformFlags |= 16 /* ContainsES2020 */; } else if (operatorKind === 62 /* EqualsToken */) { if (ts.isObjectLiteralExpression(node.left)) { node.transformFlags |= - 256 /* ContainsES2015 */ | - 32 /* ContainsES2018 */ | - 1024 /* ContainsDestructuringAssignment */ | + 512 /* ContainsES2015 */ | + 64 /* ContainsES2018 */ | + 2048 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left); } else if (ts.isArrayLiteralExpression(node.left)) { node.transformFlags |= - 256 /* ContainsES2015 */ | - 1024 /* ContainsDestructuringAssignment */ | + 512 /* ContainsES2015 */ | + 2048 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left); } } else if (operatorKind === 42 /* AsteriskAsteriskToken */ || operatorKind === 66 /* AsteriskAsteriskEqualsToken */) { - node.transformFlags |= 128 /* ContainsES2016 */; + node.transformFlags |= 256 /* ContainsES2016 */; } else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) { - node.transformFlags |= 4 /* ContainsESNext */; + node.transformFlags |= 8 /* ContainsES2021 */; } return node; } function propagateAssignmentPatternFlags(node) { - if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) - return 16384 /* ContainsObjectRestOrSpread */; - if (node.transformFlags & 32 /* ContainsES2018 */) { + if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) + return 32768 /* ContainsObjectRestOrSpread */; + if (node.transformFlags & 64 /* ContainsES2018 */) { // check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c' // will not be correctly interpreted by the ES2018 transformer for (var _i = 0, _a = ts.getElementsOfBindingOrAssignmentPattern(node); _i < _a.length; _i++) { var element = _a[_i]; var target = ts.getTargetOfBindingOrAssignmentElement(element); if (target && ts.isAssignmentPattern(target)) { - if (target.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { - return 16384 /* ContainsObjectRestOrSpread */; + if (target.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { + return 32768 /* ContainsObjectRestOrSpread */; } - if (target.transformFlags & 32 /* ContainsES2018 */) { + if (target.transformFlags & 64 /* ContainsES2018 */) { var flags_1 = propagateAssignmentPatternFlags(target); if (flags_1) return flags_1; @@ -22725,7 +23157,7 @@ var ts; } // @api function createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse) { - var node = createBaseExpression(217 /* ConditionalExpression */); + var node = createBaseExpression(218 /* ConditionalExpression */); node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression(condition); node.questionToken = questionToken !== null && questionToken !== void 0 ? questionToken : createToken(57 /* QuestionToken */); node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue); @@ -22751,13 +23183,13 @@ var ts; } // @api function createTemplateExpression(head, templateSpans) { - var node = createBaseExpression(218 /* TemplateExpression */); + var node = createBaseExpression(219 /* TemplateExpression */); node.head = head; node.templateSpans = createNodeArray(templateSpans); node.transformFlags |= propagateChildFlags(node.head) | propagateChildrenFlags(node.templateSpans) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } // @api @@ -22796,9 +23228,9 @@ var ts; node.text = text; node.rawText = rawText; node.templateFlags = templateFlags & 2048 /* TemplateLiteralLikeFlags */; - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; if (node.templateFlags) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } return node; } @@ -22821,15 +23253,15 @@ var ts; // @api function createYieldExpression(asteriskToken, expression) { ts.Debug.assert(!asteriskToken || !!expression, "A `YieldExpression` with an asteriskToken must have an expression."); - var node = createBaseExpression(219 /* YieldExpression */); + var node = createBaseExpression(220 /* YieldExpression */); node.expression = expression && parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.asteriskToken) | - 256 /* ContainsES2015 */ | - 32 /* ContainsES2018 */ | - 262144 /* ContainsYield */; + 512 /* ContainsES2015 */ | + 64 /* ContainsES2018 */ | + 524288 /* ContainsYield */; return node; } // @api @@ -22841,12 +23273,12 @@ var ts; } // @api function createSpreadElement(expression) { - var node = createBaseExpression(220 /* SpreadElement */); + var node = createBaseExpression(221 /* SpreadElement */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 256 /* ContainsES2015 */ | - 8192 /* ContainsRestOrSpread */; + 512 /* ContainsES2015 */ | + 16384 /* ContainsRestOrSpread */; return node; } // @api @@ -22857,8 +23289,8 @@ var ts; } // @api function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(221 /* ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members); - node.transformFlags |= 256 /* ContainsES2015 */; + var node = createBaseClassLikeDeclaration(222 /* ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members); + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -22874,17 +23306,17 @@ var ts; } // @api function createOmittedExpression() { - return createBaseExpression(222 /* OmittedExpression */); + return createBaseExpression(223 /* OmittedExpression */); } // @api function createExpressionWithTypeArguments(expression, typeArguments) { - var node = createBaseNode(223 /* ExpressionWithTypeArguments */); + var node = createBaseNode(224 /* ExpressionWithTypeArguments */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } // @api @@ -22896,7 +23328,7 @@ var ts; } // @api function createAsExpression(expression, type) { - var node = createBaseExpression(224 /* AsExpression */); + var node = createBaseExpression(225 /* AsExpression */); node.expression = expression; node.type = type; node.transformFlags |= @@ -22914,7 +23346,7 @@ var ts; } // @api function createNonNullExpression(expression) { - var node = createBaseExpression(225 /* NonNullExpression */); + var node = createBaseExpression(226 /* NonNullExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.transformFlags |= propagateChildFlags(node.expression) | @@ -22932,7 +23364,7 @@ var ts; } // @api function createNonNullChain(expression) { - var node = createBaseExpression(225 /* NonNullExpression */); + var node = createBaseExpression(226 /* NonNullExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.transformFlags |= @@ -22949,13 +23381,13 @@ var ts; } // @api function createMetaProperty(keywordToken, name) { - var node = createBaseExpression(226 /* MetaProperty */); + var node = createBaseExpression(227 /* MetaProperty */); node.keywordToken = keywordToken; node.name = name; node.transformFlags |= propagateChildFlags(node.name); switch (keywordToken) { case 102 /* NewKeyword */: - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; break; case 99 /* ImportKeyword */: node.transformFlags |= 4 /* ContainsESNext */; @@ -22976,13 +23408,13 @@ var ts; // // @api function createTemplateSpan(expression, literal) { - var node = createBaseNode(228 /* TemplateSpan */); + var node = createBaseNode(229 /* TemplateSpan */); node.expression = expression; node.literal = literal; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.literal) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } // @api @@ -22994,8 +23426,8 @@ var ts; } // @api function createSemicolonClassElement() { - var node = createBaseNode(229 /* SemicolonClassElement */); - node.transformFlags |= 256 /* ContainsES2015 */; + var node = createBaseNode(230 /* SemicolonClassElement */); + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @@ -23003,7 +23435,7 @@ var ts; // // @api function createBlock(statements, multiLine) { - var node = createBaseNode(230 /* Block */); + var node = createBaseNode(231 /* Block */); node.statements = createNodeArray(statements); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.statements); @@ -23017,7 +23449,7 @@ var ts; } // @api function createVariableStatement(modifiers, declarationList) { - var node = createBaseDeclaration(232 /* VariableStatement */, /*decorators*/ undefined, modifiers); + var node = createBaseDeclaration(233 /* VariableStatement */, /*decorators*/ undefined, modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; node.transformFlags |= propagateChildFlags(node.declarationList); @@ -23035,11 +23467,11 @@ var ts; } // @api function createEmptyStatement() { - return createBaseNode(231 /* EmptyStatement */); + return createBaseNode(232 /* EmptyStatement */); } // @api function createExpressionStatement(expression) { - var node = createBaseNode(233 /* ExpressionStatement */); + var node = createBaseNode(234 /* ExpressionStatement */); node.expression = parenthesizerRules().parenthesizeExpressionOfExpressionStatement(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -23052,7 +23484,7 @@ var ts; } // @api function createIfStatement(expression, thenStatement, elseStatement) { - var node = createBaseNode(234 /* IfStatement */); + var node = createBaseNode(235 /* IfStatement */); node.expression = expression; node.thenStatement = asEmbeddedStatement(thenStatement); node.elseStatement = asEmbeddedStatement(elseStatement); @@ -23072,7 +23504,7 @@ var ts; } // @api function createDoStatement(statement, expression) { - var node = createBaseNode(235 /* DoStatement */); + var node = createBaseNode(236 /* DoStatement */); node.statement = asEmbeddedStatement(statement); node.expression = expression; node.transformFlags |= @@ -23089,7 +23521,7 @@ var ts; } // @api function createWhileStatement(expression, statement) { - var node = createBaseNode(236 /* WhileStatement */); + var node = createBaseNode(237 /* WhileStatement */); node.expression = expression; node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -23106,7 +23538,7 @@ var ts; } // @api function createForStatement(initializer, condition, incrementor, statement) { - var node = createBaseNode(237 /* ForStatement */); + var node = createBaseNode(238 /* ForStatement */); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -23129,7 +23561,7 @@ var ts; } // @api function createForInStatement(initializer, expression, statement) { - var node = createBaseNode(238 /* ForInStatement */); + var node = createBaseNode(239 /* ForInStatement */); node.initializer = initializer; node.expression = expression; node.statement = asEmbeddedStatement(statement); @@ -23149,7 +23581,7 @@ var ts; } // @api function createForOfStatement(awaitModifier, initializer, expression, statement) { - var node = createBaseNode(239 /* ForOfStatement */); + var node = createBaseNode(240 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); @@ -23159,9 +23591,9 @@ var ts; propagateChildFlags(node.initializer) | propagateChildFlags(node.expression) | propagateChildFlags(node.statement) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (awaitModifier) - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; return node; } // @api @@ -23175,11 +23607,11 @@ var ts; } // @api function createContinueStatement(label) { - var node = createBaseNode(240 /* ContinueStatement */); + var node = createBaseNode(241 /* ContinueStatement */); node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -23190,11 +23622,11 @@ var ts; } // @api function createBreakStatement(label) { - var node = createBaseNode(241 /* BreakStatement */); + var node = createBaseNode(242 /* BreakStatement */); node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -23205,13 +23637,13 @@ var ts; } // @api function createReturnStatement(expression) { - var node = createBaseNode(242 /* ReturnStatement */); + var node = createBaseNode(243 /* ReturnStatement */); node.expression = expression; // return in an ES2018 async generator must be awaited node.transformFlags |= propagateChildFlags(node.expression) | - 32 /* ContainsES2018 */ | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 64 /* ContainsES2018 */ | + 2097152 /* ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -23222,7 +23654,7 @@ var ts; } // @api function createWithStatement(expression, statement) { - var node = createBaseNode(243 /* WithStatement */); + var node = createBaseNode(244 /* WithStatement */); node.expression = expression; node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -23239,7 +23671,7 @@ var ts; } // @api function createSwitchStatement(expression, caseBlock) { - var node = createBaseNode(244 /* SwitchStatement */); + var node = createBaseNode(245 /* SwitchStatement */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.caseBlock = caseBlock; node.transformFlags |= @@ -23256,7 +23688,7 @@ var ts; } // @api function createLabeledStatement(label, statement) { - var node = createBaseNode(245 /* LabeledStatement */); + var node = createBaseNode(246 /* LabeledStatement */); node.label = asName(label); node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -23273,7 +23705,7 @@ var ts; } // @api function createThrowStatement(expression) { - var node = createBaseNode(246 /* ThrowStatement */); + var node = createBaseNode(247 /* ThrowStatement */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -23286,7 +23718,7 @@ var ts; } // @api function createTryStatement(tryBlock, catchClause, finallyBlock) { - var node = createBaseNode(247 /* TryStatement */); + var node = createBaseNode(248 /* TryStatement */); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -23306,11 +23738,11 @@ var ts; } // @api function createDebuggerStatement() { - return createBaseNode(248 /* DebuggerStatement */); + return createBaseNode(249 /* DebuggerStatement */); } // @api function createVariableDeclaration(name, exclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(249 /* VariableDeclaration */, + var node = createBaseVariableLikeDeclaration(250 /* VariableDeclaration */, /*decorators*/ undefined, /*modifiers*/ undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.exclamationToken = exclamationToken; @@ -23332,16 +23764,16 @@ var ts; // @api function createVariableDeclarationList(declarations, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createBaseNode(250 /* VariableDeclarationList */); + var node = createBaseNode(251 /* VariableDeclarationList */); node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); node.transformFlags |= propagateChildrenFlags(node.declarations) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; if (flags & 3 /* BlockScoped */) { node.transformFlags |= - 256 /* ContainsES2015 */ | - 65536 /* ContainsBlockScopedBinding */; + 512 /* ContainsES2015 */ | + 131072 /* ContainsBlockScopedBinding */; } return node; } @@ -23353,7 +23785,7 @@ var ts; } // @api function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(251 /* FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(252 /* FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; if (!node.body || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) { node.transformFlags = 1 /* ContainsTypeScript */; @@ -23361,17 +23793,17 @@ var ts; else { node.transformFlags |= propagateChildFlags(node.asteriskToken) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (node.asteriskToken) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } else { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } } else if (node.asteriskToken) { - node.transformFlags |= 512 /* ContainsGenerator */; + node.transformFlags |= 1024 /* ContainsGenerator */; } } return node; @@ -23391,13 +23823,13 @@ var ts; } // @api function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(252 /* ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members); + var node = createBaseClassLikeDeclaration(253 /* ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members); if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) { node.transformFlags = 1 /* ContainsTypeScript */; } else { - node.transformFlags |= 256 /* ContainsES2015 */; - if (node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */) { + node.transformFlags |= 512 /* ContainsES2015 */; + if (node.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */) { node.transformFlags |= 1 /* ContainsTypeScript */; } } @@ -23416,7 +23848,7 @@ var ts; } // @api function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(253 /* InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses); + var node = createBaseInterfaceOrClassLikeDeclaration(254 /* InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -23434,7 +23866,7 @@ var ts; } // @api function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createBaseGenericNamedDeclaration(254 /* TypeAliasDeclaration */, decorators, modifiers, name, typeParameters); + var node = createBaseGenericNamedDeclaration(255 /* TypeAliasDeclaration */, decorators, modifiers, name, typeParameters); node.type = type; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -23451,12 +23883,12 @@ var ts; } // @api function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createBaseNamedDeclaration(255 /* EnumDeclaration */, decorators, modifiers, name); + var node = createBaseNamedDeclaration(256 /* EnumDeclaration */, decorators, modifiers, name); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members) | 1 /* ContainsTypeScript */; - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` return node; } // @api @@ -23471,7 +23903,7 @@ var ts; // @api function createModuleDeclaration(decorators, modifiers, name, body, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createBaseDeclaration(256 /* ModuleDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(257 /* ModuleDeclaration */, decorators, modifiers); node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 1024 /* GlobalAugmentation */); node.name = name; node.body = body; @@ -23484,7 +23916,7 @@ var ts; propagateChildFlags(node.body) | 1 /* ContainsTypeScript */; } - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. return node; } // @api @@ -23498,7 +23930,7 @@ var ts; } // @api function createModuleBlock(statements) { - var node = createBaseNode(257 /* ModuleBlock */); + var node = createBaseNode(258 /* ModuleBlock */); node.statements = createNodeArray(statements); node.transformFlags |= propagateChildrenFlags(node.statements); return node; @@ -23511,7 +23943,7 @@ var ts; } // @api function createCaseBlock(clauses) { - var node = createBaseNode(258 /* CaseBlock */); + var node = createBaseNode(259 /* CaseBlock */); node.clauses = createNodeArray(clauses); node.transformFlags |= propagateChildrenFlags(node.clauses); return node; @@ -23524,7 +23956,7 @@ var ts; } // @api function createNamespaceExportDeclaration(name) { - var node = createBaseNamedDeclaration(259 /* NamespaceExportDeclaration */, + var node = createBaseNamedDeclaration(260 /* NamespaceExportDeclaration */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.transformFlags = 1 /* ContainsTypeScript */; @@ -23538,13 +23970,13 @@ var ts; } // @api function createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference) { - var node = createBaseNamedDeclaration(260 /* ImportEqualsDeclaration */, decorators, modifiers, name); + var node = createBaseNamedDeclaration(261 /* ImportEqualsDeclaration */, decorators, modifiers, name); node.isTypeOnly = isTypeOnly; node.moduleReference = moduleReference; node.transformFlags |= propagateChildFlags(node.moduleReference); if (!ts.isExternalModuleReference(node.moduleReference)) node.transformFlags |= 1 /* ContainsTypeScript */; - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context return node; } // @api @@ -23559,13 +23991,13 @@ var ts; } // @api function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createBaseDeclaration(261 /* ImportDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(262 /* ImportDeclaration */, decorators, modifiers); node.importClause = importClause; node.moduleSpecifier = moduleSpecifier; node.transformFlags |= propagateChildFlags(node.importClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23579,7 +24011,7 @@ var ts; } // @api function createImportClause(isTypeOnly, name, namedBindings) { - var node = createBaseNode(262 /* ImportClause */); + var node = createBaseNode(263 /* ImportClause */); node.isTypeOnly = isTypeOnly; node.name = name; node.namedBindings = namedBindings; @@ -23589,7 +24021,7 @@ var ts; if (isTypeOnly) { node.transformFlags |= 1 /* ContainsTypeScript */; } - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23602,10 +24034,10 @@ var ts; } // @api function createNamespaceImport(name) { - var node = createBaseNode(263 /* NamespaceImport */); + var node = createBaseNode(264 /* NamespaceImport */); node.name = name; node.transformFlags |= propagateChildFlags(node.name); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23616,12 +24048,12 @@ var ts; } // @api function createNamespaceExport(name) { - var node = createBaseNode(269 /* NamespaceExport */); + var node = createBaseNode(270 /* NamespaceExport */); node.name = name; node.transformFlags |= propagateChildFlags(node.name) | 4 /* ContainsESNext */; - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23632,10 +24064,10 @@ var ts; } // @api function createNamedImports(elements) { - var node = createBaseNode(264 /* NamedImports */); + var node = createBaseNode(265 /* NamedImports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23646,13 +24078,13 @@ var ts; } // @api function createImportSpecifier(propertyName, name) { - var node = createBaseNode(265 /* ImportSpecifier */); + var node = createBaseNode(266 /* ImportSpecifier */); node.propertyName = propertyName; node.name = name; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23664,13 +24096,13 @@ var ts; } // @api function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createBaseDeclaration(266 /* ExportAssignment */, decorators, modifiers); + var node = createBaseDeclaration(267 /* ExportAssignment */, decorators, modifiers); node.isExportEquals = isExportEquals; node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary(62 /* EqualsToken */, /*leftSide*/ undefined, expression) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23683,14 +24115,14 @@ var ts; } // @api function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier) { - var node = createBaseDeclaration(267 /* ExportDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(268 /* ExportDeclaration */, decorators, modifiers); node.isTypeOnly = isTypeOnly; node.exportClause = exportClause; node.moduleSpecifier = moduleSpecifier; node.transformFlags |= propagateChildFlags(node.exportClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23705,10 +24137,10 @@ var ts; } // @api function createNamedExports(elements) { - var node = createBaseNode(268 /* NamedExports */); + var node = createBaseNode(269 /* NamedExports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23719,13 +24151,13 @@ var ts; } // @api function createExportSpecifier(propertyName, name) { - var node = createBaseNode(270 /* ExportSpecifier */); + var node = createBaseNode(271 /* ExportSpecifier */); node.propertyName = asName(propertyName); node.name = asName(name); node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23737,7 +24169,7 @@ var ts; } // @api function createMissingDeclaration() { - var node = createBaseDeclaration(271 /* MissingDeclaration */, + var node = createBaseDeclaration(272 /* MissingDeclaration */, /*decorators*/ undefined, /*modifiers*/ undefined); return node; @@ -23747,10 +24179,10 @@ var ts; // // @api function createExternalModuleReference(expression) { - var node = createBaseNode(272 /* ExternalModuleReference */); + var node = createBaseNode(273 /* ExternalModuleReference */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23792,7 +24224,7 @@ var ts; } // @api function createJSDocFunctionType(parameters, type) { - var node = createBaseSignatureDeclaration(308 /* JSDocFunctionType */, + var node = createBaseSignatureDeclaration(309 /* JSDocFunctionType */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, @@ -23809,7 +24241,7 @@ var ts; // @api function createJSDocTypeLiteral(propertyTags, isArrayType) { if (isArrayType === void 0) { isArrayType = false; } - var node = createBaseNode(312 /* JSDocTypeLiteral */); + var node = createBaseNode(314 /* JSDocTypeLiteral */); node.jsDocPropertyTags = asNodeArray(propertyTags); node.isArrayType = isArrayType; return node; @@ -23823,7 +24255,7 @@ var ts; } // @api function createJSDocTypeExpression(type) { - var node = createBaseNode(301 /* JSDocTypeExpression */); + var node = createBaseNode(302 /* JSDocTypeExpression */); node.type = type; return node; } @@ -23835,7 +24267,7 @@ var ts; } // @api function createJSDocSignature(typeParameters, parameters, type) { - var node = createBaseNode(313 /* JSDocSignature */); + var node = createBaseNode(315 /* JSDocSignature */); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; @@ -23864,7 +24296,7 @@ var ts; } // @api function createJSDocTemplateTag(tagName, constraint, typeParameters, comment) { - var node = createBaseJSDocTag(330 /* JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment); + var node = createBaseJSDocTag(334 /* JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment); node.constraint = constraint; node.typeParameters = createNodeArray(typeParameters); return node; @@ -23881,7 +24313,7 @@ var ts; } // @api function createJSDocTypedefTag(tagName, typeExpression, fullName, comment) { - var node = createBaseJSDocTag(331 /* JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment); + var node = createBaseJSDocTag(335 /* JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment); node.typeExpression = typeExpression; node.fullName = fullName; node.name = ts.getJSDocTypeAliasName(fullName); @@ -23899,7 +24331,7 @@ var ts; } // @api function createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { - var node = createBaseJSDocTag(326 /* JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment); + var node = createBaseJSDocTag(330 /* JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -23920,7 +24352,7 @@ var ts; } // @api function createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { - var node = createBaseJSDocTag(333 /* JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment); + var node = createBaseJSDocTag(337 /* JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -23941,7 +24373,7 @@ var ts; } // @api function createJSDocCallbackTag(tagName, typeExpression, fullName, comment) { - var node = createBaseJSDocTag(324 /* JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment); + var node = createBaseJSDocTag(328 /* JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment); node.typeExpression = typeExpression; node.fullName = fullName; node.name = ts.getJSDocTypeAliasName(fullName); @@ -23959,7 +24391,7 @@ var ts; } // @api function createJSDocAugmentsTag(tagName, className, comment) { - var node = createBaseJSDocTag(315 /* JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment); + var node = createBaseJSDocTag(318 /* JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment); node.class = className; return node; } @@ -23974,13 +24406,13 @@ var ts; } // @api function createJSDocImplementsTag(tagName, className, comment) { - var node = createBaseJSDocTag(316 /* JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment); + var node = createBaseJSDocTag(319 /* JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment); node.class = className; return node; } // @api function createJSDocSeeTag(tagName, name, comment) { - var node = createBaseJSDocTag(332 /* JSDocSeeTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment); + var node = createBaseJSDocTag(336 /* JSDocSeeTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment); node.name = name; return node; } @@ -23994,7 +24426,7 @@ var ts; } // @api function createJSDocNameReference(name) { - var node = createBaseNode(302 /* JSDocNameReference */); + var node = createBaseNode(303 /* JSDocNameReference */); node.name = name; return node; } @@ -24005,6 +24437,19 @@ var ts; : node; } // @api + function createJSDocLink(name, text) { + var node = createBaseNode(316 /* JSDocLink */); + node.name = name; + node.text = text; + return node; + } + // @api + function updateJSDocLink(node, name, text) { + return node.name !== name + ? update(createJSDocLink(name, text), node) + : node; + } + // @api function updateJSDocImplementsTag(node, tagName, className, comment) { if (tagName === void 0) { tagName = getDefaultTagName(node); } return node.tagName !== tagName @@ -24065,7 +24510,7 @@ var ts; } // @api function createJSDocUnknownTag(tagName, comment) { - var node = createBaseJSDocTag(314 /* JSDocTag */, tagName, comment); + var node = createBaseJSDocTag(317 /* JSDocTag */, tagName, comment); return node; } // @api @@ -24076,8 +24521,20 @@ var ts; : node; } // @api + function createJSDocText(text) { + var node = createBaseNode(313 /* JSDocText */); + node.text = text; + return node; + } + // @api + function updateJSDocText(node, text) { + return node.text !== text + ? update(createJSDocText(text), node) + : node; + } + // @api function createJSDocComment(comment, tags) { - var node = createBaseNode(311 /* JSDocComment */); + var node = createBaseNode(312 /* JSDocComment */); node.comment = comment; node.tags = asNodeArray(tags); return node; @@ -24094,7 +24551,7 @@ var ts; // // @api function createJsxElement(openingElement, children, closingElement) { - var node = createBaseNode(273 /* JsxElement */); + var node = createBaseNode(274 /* JsxElement */); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -24115,7 +24572,7 @@ var ts; } // @api function createJsxSelfClosingElement(tagName, typeArguments, attributes) { - var node = createBaseNode(274 /* JsxSelfClosingElement */); + var node = createBaseNode(275 /* JsxSelfClosingElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -24139,7 +24596,7 @@ var ts; } // @api function createJsxOpeningElement(tagName, typeArguments, attributes) { - var node = createBaseNode(275 /* JsxOpeningElement */); + var node = createBaseNode(276 /* JsxOpeningElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -24163,7 +24620,7 @@ var ts; } // @api function createJsxClosingElement(tagName) { - var node = createBaseNode(276 /* JsxClosingElement */); + var node = createBaseNode(277 /* JsxClosingElement */); node.tagName = tagName; node.transformFlags |= propagateChildFlags(node.tagName) | @@ -24178,7 +24635,7 @@ var ts; } // @api function createJsxFragment(openingFragment, children, closingFragment) { - var node = createBaseNode(277 /* JsxFragment */); + var node = createBaseNode(278 /* JsxFragment */); node.openingFragment = openingFragment; node.children = createNodeArray(children); node.closingFragment = closingFragment; @@ -24214,19 +24671,19 @@ var ts; } // @api function createJsxOpeningFragment() { - var node = createBaseNode(278 /* JsxOpeningFragment */); + var node = createBaseNode(279 /* JsxOpeningFragment */); node.transformFlags |= 2 /* ContainsJsx */; return node; } // @api function createJsxJsxClosingFragment() { - var node = createBaseNode(279 /* JsxClosingFragment */); + var node = createBaseNode(280 /* JsxClosingFragment */); node.transformFlags |= 2 /* ContainsJsx */; return node; } // @api function createJsxAttribute(name, initializer) { - var node = createBaseNode(280 /* JsxAttribute */); + var node = createBaseNode(281 /* JsxAttribute */); node.name = name; node.initializer = initializer; node.transformFlags |= @@ -24244,7 +24701,7 @@ var ts; } // @api function createJsxAttributes(properties) { - var node = createBaseNode(281 /* JsxAttributes */); + var node = createBaseNode(282 /* JsxAttributes */); node.properties = createNodeArray(properties); node.transformFlags |= propagateChildrenFlags(node.properties) | @@ -24259,7 +24716,7 @@ var ts; } // @api function createJsxSpreadAttribute(expression) { - var node = createBaseNode(282 /* JsxSpreadAttribute */); + var node = createBaseNode(283 /* JsxSpreadAttribute */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression) | @@ -24274,7 +24731,7 @@ var ts; } // @api function createJsxExpression(dotDotDotToken, expression) { - var node = createBaseNode(283 /* JsxExpression */); + var node = createBaseNode(284 /* JsxExpression */); node.dotDotDotToken = dotDotDotToken; node.expression = expression; node.transformFlags |= @@ -24294,7 +24751,7 @@ var ts; // // @api function createCaseClause(expression, statements) { - var node = createBaseNode(284 /* CaseClause */); + var node = createBaseNode(285 /* CaseClause */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.statements = createNodeArray(statements); node.transformFlags |= @@ -24311,7 +24768,7 @@ var ts; } // @api function createDefaultClause(statements) { - var node = createBaseNode(285 /* DefaultClause */); + var node = createBaseNode(286 /* DefaultClause */); node.statements = createNodeArray(statements); node.transformFlags = propagateChildrenFlags(node.statements); return node; @@ -24324,13 +24781,13 @@ var ts; } // @api function createHeritageClause(token, types) { - var node = createBaseNode(286 /* HeritageClause */); + var node = createBaseNode(287 /* HeritageClause */); node.token = token; node.types = createNodeArray(types); node.transformFlags |= propagateChildrenFlags(node.types); switch (token) { case 93 /* ExtendsKeyword */: - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; break; case 116 /* ImplementsKeyword */: node.transformFlags |= 1 /* ContainsTypeScript */; @@ -24348,7 +24805,7 @@ var ts; } // @api function createCatchClause(variableDeclaration, block) { - var node = createBaseNode(287 /* CatchClause */); + var node = createBaseNode(288 /* CatchClause */); variableDeclaration = !ts.isString(variableDeclaration) ? variableDeclaration : createVariableDeclaration(variableDeclaration, /*exclamationToken*/ undefined, /*type*/ undefined, @@ -24359,7 +24816,7 @@ var ts; propagateChildFlags(node.variableDeclaration) | propagateChildFlags(node.block); if (!variableDeclaration) - node.transformFlags |= 16 /* ContainsES2019 */; + node.transformFlags |= 32 /* ContainsES2019 */; return node; } // @api @@ -24374,7 +24831,7 @@ var ts; // // @api function createPropertyAssignment(name, initializer) { - var node = createBaseNamedDeclaration(288 /* PropertyAssignment */, + var node = createBaseNamedDeclaration(289 /* PropertyAssignment */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); @@ -24404,13 +24861,13 @@ var ts; } // @api function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createBaseNamedDeclaration(289 /* ShorthandPropertyAssignment */, + var node = createBaseNamedDeclaration(290 /* ShorthandPropertyAssignment */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); node.transformFlags |= propagateChildFlags(node.objectAssignmentInitializer) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } function finishUpdateShorthandPropertyAssignment(updated, original) { @@ -24436,12 +24893,12 @@ var ts; } // @api function createSpreadAssignment(expression) { - var node = createBaseNode(290 /* SpreadAssignment */); + var node = createBaseNode(291 /* SpreadAssignment */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 32 /* ContainsES2018 */ | - 16384 /* ContainsObjectRestOrSpread */; + 64 /* ContainsES2018 */ | + 32768 /* ContainsObjectRestOrSpread */; return node; } // @api @@ -24455,7 +24912,7 @@ var ts; // // @api function createEnumMember(name, initializer) { - var node = createBaseNode(291 /* EnumMember */); + var node = createBaseNode(292 /* EnumMember */); node.name = asName(name); node.initializer = initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); node.transformFlags |= @@ -24476,7 +24933,7 @@ var ts; // // @api function createSourceFile(statements, endOfFileToken, flags) { - var node = baseFactory.createBaseSourceFileNode(297 /* SourceFile */); + var node = baseFactory.createBaseSourceFileNode(298 /* SourceFile */); node.statements = createNodeArray(statements); node.endOfFileToken = endOfFileToken; node.flags |= flags; @@ -24493,7 +24950,7 @@ var ts; return node; } function cloneSourceFileWithChanges(source, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) { - var node = baseFactory.createBaseSourceFileNode(297 /* SourceFile */); + var node = baseFactory.createBaseSourceFileNode(298 /* SourceFile */); for (var p in source) { if (p === "emitNode" || ts.hasProperty(node, p) || !ts.hasProperty(source, p)) continue; @@ -24531,7 +24988,7 @@ var ts; // @api function createBundle(sourceFiles, prepends) { if (prepends === void 0) { prepends = ts.emptyArray; } - var node = createBaseNode(298 /* Bundle */); + var node = createBaseNode(299 /* Bundle */); node.prepends = prepends; node.sourceFiles = sourceFiles; return node; @@ -24546,7 +25003,7 @@ var ts; } // @api function createUnparsedSource(prologues, syntheticReferences, texts) { - var node = createBaseNode(299 /* UnparsedSource */); + var node = createBaseNode(300 /* UnparsedSource */); node.prologues = prologues; node.syntheticReferences = syntheticReferences; node.texts = texts; @@ -24564,28 +25021,28 @@ var ts; } // @api function createUnparsedPrologue(data) { - return createBaseUnparsedNode(292 /* UnparsedPrologue */, data); + return createBaseUnparsedNode(293 /* UnparsedPrologue */, data); } // @api function createUnparsedPrepend(data, texts) { - var node = createBaseUnparsedNode(293 /* UnparsedPrepend */, data); + var node = createBaseUnparsedNode(294 /* UnparsedPrepend */, data); node.texts = texts; return node; } // @api function createUnparsedTextLike(data, internal) { - return createBaseUnparsedNode(internal ? 295 /* UnparsedInternalText */ : 294 /* UnparsedText */, data); + return createBaseUnparsedNode(internal ? 296 /* UnparsedInternalText */ : 295 /* UnparsedText */, data); } // @api function createUnparsedSyntheticReference(section) { - var node = createBaseNode(296 /* UnparsedSyntheticReference */); + var node = createBaseNode(297 /* UnparsedSyntheticReference */); node.data = section.data; node.section = section; return node; } // @api function createInputFiles() { - var node = createBaseNode(300 /* InputFiles */); + var node = createBaseNode(301 /* InputFiles */); node.javascriptText = ""; node.declarationText = ""; return node; @@ -24596,7 +25053,7 @@ var ts; // @api function createSyntheticExpression(type, isSpread, tupleNameSource) { if (isSpread === void 0) { isSpread = false; } - var node = createBaseNode(227 /* SyntheticExpression */); + var node = createBaseNode(228 /* SyntheticExpression */); node.type = type; node.isSpread = isSpread; node.tupleNameSource = tupleNameSource; @@ -24604,7 +25061,7 @@ var ts; } // @api function createSyntaxList(children) { - var node = createBaseNode(334 /* SyntaxList */); + var node = createBaseNode(338 /* SyntaxList */); node._children = children; return node; } @@ -24619,7 +25076,7 @@ var ts; */ // @api function createNotEmittedStatement(original) { - var node = createBaseNode(335 /* NotEmittedStatement */); + var node = createBaseNode(339 /* NotEmittedStatement */); node.original = original; ts.setTextRange(node, original); return node; @@ -24633,7 +25090,7 @@ var ts; */ // @api function createPartiallyEmittedExpression(expression, original) { - var node = createBaseNode(336 /* PartiallyEmittedExpression */); + var node = createBaseNode(340 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; node.transformFlags |= @@ -24661,7 +25118,7 @@ var ts; } // @api function createCommaListExpression(elements) { - var node = createBaseNode(337 /* CommaListExpression */); + var node = createBaseNode(341 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); node.transformFlags |= propagateChildrenFlags(node.elements); return node; @@ -24678,7 +25135,7 @@ var ts; */ // @api function createEndOfDeclarationMarker(original) { - var node = createBaseNode(339 /* EndOfDeclarationMarker */); + var node = createBaseNode(343 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -24689,14 +25146,14 @@ var ts; */ // @api function createMergeDeclarationMarker(original) { - var node = createBaseNode(338 /* MergeDeclarationMarker */); + var node = createBaseNode(342 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; } // @api function createSyntheticReferenceExpression(expression, thisArg) { - var node = createBaseNode(340 /* SyntheticReferenceExpression */); + var node = createBaseNode(344 /* SyntheticReferenceExpression */); node.expression = expression; node.thisArg = thisArg; node.transformFlags |= @@ -24718,7 +25175,7 @@ var ts; if (node === undefined) { return node; } - var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(297 /* SourceFile */) : + var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(298 /* SourceFile */) : ts.isIdentifier(node) ? baseFactory.createBaseIdentifierNode(78 /* Identifier */) : ts.isPrivateIdentifier(node) ? baseFactory.createBasePrivateIdentifierNode(79 /* PrivateIdentifier */) : !ts.isNodeKind(node.kind) ? baseFactory.createBaseTokenNode(node.kind) : @@ -24825,11 +25282,11 @@ var ts; } function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 207 /* ParenthesizedExpression */: return updateParenthesizedExpression(outerExpression, expression); - case 206 /* TypeAssertionExpression */: return updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 224 /* AsExpression */: return updateAsExpression(outerExpression, expression, outerExpression.type); - case 225 /* NonNullExpression */: return updateNonNullExpression(outerExpression, expression); - case 336 /* PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression); + case 208 /* ParenthesizedExpression */: return updateParenthesizedExpression(outerExpression, expression); + case 207 /* TypeAssertionExpression */: return updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 225 /* AsExpression */: return updateAsExpression(outerExpression, expression, outerExpression.type); + case 226 /* NonNullExpression */: return updateNonNullExpression(outerExpression, expression); + case 340 /* PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -24883,13 +25340,13 @@ var ts; case 9 /* BigIntLiteral */: case 10 /* StringLiteral */: return false; - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return target.properties.length > 0; default: return true; @@ -25292,23 +25749,24 @@ var ts; } function getDefaultTagNameForKind(kind) { switch (kind) { - case 329 /* JSDocTypeTag */: return "type"; - case 327 /* JSDocReturnTag */: return "returns"; - case 328 /* JSDocThisTag */: return "this"; - case 325 /* JSDocEnumTag */: return "enum"; - case 317 /* JSDocAuthorTag */: return "author"; - case 319 /* JSDocClassTag */: return "class"; - case 320 /* JSDocPublicTag */: return "public"; - case 321 /* JSDocPrivateTag */: return "private"; - case 322 /* JSDocProtectedTag */: return "protected"; - case 323 /* JSDocReadonlyTag */: return "readonly"; - case 330 /* JSDocTemplateTag */: return "template"; - case 331 /* JSDocTypedefTag */: return "typedef"; - case 326 /* JSDocParameterTag */: return "param"; - case 333 /* JSDocPropertyTag */: return "prop"; - case 324 /* JSDocCallbackTag */: return "callback"; - case 315 /* JSDocAugmentsTag */: return "augments"; - case 316 /* JSDocImplementsTag */: return "implements"; + case 333 /* JSDocTypeTag */: return "type"; + case 331 /* JSDocReturnTag */: return "returns"; + case 332 /* JSDocThisTag */: return "this"; + case 329 /* JSDocEnumTag */: return "enum"; + case 320 /* JSDocAuthorTag */: return "author"; + case 322 /* JSDocClassTag */: return "class"; + case 323 /* JSDocPublicTag */: return "public"; + case 324 /* JSDocPrivateTag */: return "private"; + case 325 /* JSDocProtectedTag */: return "protected"; + case 326 /* JSDocReadonlyTag */: return "readonly"; + case 327 /* JSDocOverrideTag */: return "override"; + case 334 /* JSDocTemplateTag */: return "template"; + case 335 /* JSDocTypedefTag */: return "typedef"; + case 330 /* JSDocParameterTag */: return "param"; + case 337 /* JSDocPropertyTag */: return "prop"; + case 328 /* JSDocCallbackTag */: return "callback"; + case 318 /* JSDocAugmentsTag */: return "augments"; + case 319 /* JSDocImplementsTag */: return "implements"; default: return ts.Debug.fail("Unsupported kind: " + ts.Debug.formatSyntaxKind(kind)); } @@ -25361,10 +25819,10 @@ var ts; } function propagateIdentifierNameFlags(node) { // An IdentifierName is allowed to be `await` - return propagateChildFlags(node) & ~8388608 /* ContainsPossibleTopLevelAwait */; + return propagateChildFlags(node) & ~16777216 /* ContainsPossibleTopLevelAwait */; } function propagatePropertyNameFlagsOfChild(node, transformFlags) { - return transformFlags | (node.transformFlags & 4096 /* PropertyNamePropagatingFlags */); + return transformFlags | (node.transformFlags & 8192 /* PropertyNamePropagatingFlags */); } function propagateChildFlags(child) { if (!child) @@ -25388,36 +25846,36 @@ var ts; */ /* @internal */ function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 172 /* FirstTypeNode */ && kind <= 195 /* LastTypeNode */) { + if (kind >= 173 /* FirstTypeNode */ && kind <= 196 /* LastTypeNode */) { return -2 /* TypeExcludes */; } switch (kind) { - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 199 /* ArrayLiteralExpression */: - return 536879104 /* ArrayLiteralOrCallOrNewExcludes */; - case 256 /* ModuleDeclaration */: - return 546379776 /* ModuleExcludes */; - case 160 /* Parameter */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 200 /* ArrayLiteralExpression */: + return 536887296 /* ArrayLiteralOrCallOrNewExcludes */; + case 257 /* ModuleDeclaration */: + return 555888640 /* ModuleExcludes */; + case 161 /* Parameter */: return 536870912 /* ParameterExcludes */; - case 209 /* ArrowFunction */: - return 547309568 /* ArrowFunctionExcludes */; - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - return 547313664 /* FunctionExcludes */; - case 250 /* VariableDeclarationList */: - return 537018368 /* VariableDeclarationListExcludes */; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - return 536905728 /* ClassExcludes */; - case 166 /* Constructor */: - return 547311616 /* ConstructorExcludes */; - case 163 /* PropertyDeclaration */: - return 536875008 /* PropertyExcludes */; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - return 538923008 /* MethodOrAccessorExcludes */; + case 210 /* ArrowFunction */: + return 557748224 /* ArrowFunctionExcludes */; + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + return 557756416 /* FunctionExcludes */; + case 251 /* VariableDeclarationList */: + return 537165824 /* VariableDeclarationListExcludes */; + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + return 536940544 /* ClassExcludes */; + case 167 /* Constructor */: + return 557752320 /* ConstructorExcludes */; + case 164 /* PropertyDeclaration */: + return 536879104 /* PropertyExcludes */; + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return 540975104 /* MethodOrAccessorExcludes */; case 128 /* AnyKeyword */: case 144 /* NumberKeyword */: case 155 /* BigIntKeyword */: @@ -25427,30 +25885,30 @@ var ts; case 131 /* BooleanKeyword */: case 148 /* SymbolKeyword */: case 113 /* VoidKeyword */: - case 159 /* TypeParameter */: - case 162 /* PropertySignature */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 160 /* TypeParameter */: + case 163 /* PropertySignature */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return -2 /* TypeExcludes */; - case 200 /* ObjectLiteralExpression */: - return 536922112 /* ObjectLiteralExcludes */; - case 287 /* CatchClause */: - return 536887296 /* CatchClauseExcludes */; - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: - return 536879104 /* BindingPatternExcludes */; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: - case 336 /* PartiallyEmittedExpression */: - case 207 /* ParenthesizedExpression */: + case 201 /* ObjectLiteralExpression */: + return 536973312 /* ObjectLiteralExcludes */; + case 288 /* CatchClause */: + return 536903680 /* CatchClauseExcludes */; + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + return 536887296 /* BindingPatternExcludes */; + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: + case 340 /* PartiallyEmittedExpression */: + case 208 /* ParenthesizedExpression */: case 105 /* SuperKeyword */: return 536870912 /* OuterExpressionExcludes */; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return 536870912 /* PropertyAccessExcludes */; default: return 536870912 /* NodeExcludes */; @@ -25749,7 +26207,7 @@ var ts; // To avoid holding onto transformation artifacts, we keep track of any // parse tree node we are annotating. This allows us to clean them up after // all transformations have completed. - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = (_a = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)))) !== null && _a !== void 0 ? _a : ts.Debug.fail("Could not determine parsed source file."); @@ -26236,13 +26694,27 @@ var ts; /*typeArguments*/ undefined, [moduleExpression, exportsExpression]); } // Class Fields Helpers - function createClassPrivateFieldGetHelper(receiver, privateField) { + function createClassPrivateFieldGetHelper(receiver, state, kind, f) { context.requestEmitHelper(ts.classPrivateFieldGetHelper); - return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ undefined, [receiver, privateField]); + var args; + if (!f) { + args = [receiver, state, factory.createStringLiteral(kind)]; + } + else { + args = [receiver, state, factory.createStringLiteral(kind), f]; + } + return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ undefined, args); } - function createClassPrivateFieldSetHelper(receiver, privateField, value) { + function createClassPrivateFieldSetHelper(receiver, state, value, kind, f) { context.requestEmitHelper(ts.classPrivateFieldSetHelper); - return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, [receiver, privateField, value]); + var args; + if (!f) { + args = [receiver, state, value, factory.createStringLiteral(kind)]; + } + else { + args = [receiver, state, value, factory.createStringLiteral(kind), f]; + } + return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, args); } } ts.createEmitHelperFactory = createEmitHelperFactory; @@ -26482,7 +26954,6 @@ var ts; scoped: false, text: "\n var __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n };" }; - // emit output for the __export helper function ts.exportStarHelper = { name: "typescript:export-star", importName: "__exportStar", @@ -26491,18 +26962,116 @@ var ts; priority: 2, text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n };" }; - // Class fields helpers + /** + * Parameters: + * @param receiver — The object from which the private member will be read. + * @param state — One of the following: + * - A WeakMap used to read a private instance field. + * - A WeakSet used as an instance brand for private instance methods and accessors. + * - A function value that should be the undecorated class constructor used to brand check private static fields, methods, and accessors. + * @param kind — (optional pre TS 4.3, required for TS 4.3+) One of the following values: + * - undefined — Indicates a private instance field (pre TS 4.3). + * - "f" — Indicates a private field (instance or static). + * - "m" — Indicates a private method (instance or static). + * - "a" — Indicates a private accessor (instance or static). + * @param f — (optional pre TS 4.3) Depends on the arguments for state and kind: + * - If kind is "m", this should be the function corresponding to the static or instance method. + * - If kind is "a", this should be the function corresponding to the getter method, or undefined if the getter was not defined. + * - If kind is "f" and state is a function, this should be an object holding the value of a static field, or undefined if the static field declaration has not yet been evaluated. + * Usage: + * This helper will only ever be used by the compiler in the following ways: + * + * Reading from a private instance field (pre TS 4.3): + * __classPrivateFieldGet(, ) + * + * Reading from a private instance field (TS 4.3+): + * __classPrivateFieldGet(, , "f") + * + * Reading from a private instance get accessor (when defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", ) + * + * Reading from a private instance get accessor (when not defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Reading from a private instance method (TS 4.3+): + * __classPrivateFieldGet(, , "m", ) + * + * Reading from a private static field (TS 4.3+): + * __classPrivateFieldGet(, , "f", <{ value: any }>) + * + * Reading from a private static get accessor (when defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", ) + * + * Reading from a private static get accessor (when not defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Reading from a private static method (TS 4.3+): + * __classPrivateFieldGet(, , "m", ) + */ ts.classPrivateFieldGetHelper = { name: "typescript:classPrivateFieldGet", importName: "__classPrivateFieldGet", scoped: false, - text: "\n var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, privateMap) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to get private field on non-instance\");\n }\n return privateMap.get(receiver);\n };" + text: "\n var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n };" }; + /** + * Parameters: + * @param receiver — The object on which the private member will be set. + * @param state — One of the following: + * - A WeakMap used to store a private instance field. + * - A WeakSet used as an instance brand for private instance methods and accessors. + * - A function value that should be the undecorated class constructor used to brand check private static fields, methods, and accessors. + * @param value — The value to set. + * @param kind — (optional pre TS 4.3, required for TS 4.3+) One of the following values: + * - undefined — Indicates a private instance field (pre TS 4.3). + * - "f" — Indicates a private field (instance or static). + * - "m" — Indicates a private method (instance or static). + * - "a" — Indicates a private accessor (instance or static). + * @param f — (optional pre TS 4.3) Depends on the arguments for state and kind: + * - If kind is "m", this should be the function corresponding to the static or instance method. + * - If kind is "a", this should be the function corresponding to the setter method, or undefined if the setter was not defined. + * - If kind is "f" and state is a function, this should be an object holding the value of a static field, or undefined if the static field declaration has not yet been evaluated. + * Usage: + * This helper will only ever be used by the compiler in the following ways: + * + * Writing to a private instance field (pre TS 4.3): + * __classPrivateFieldSet(, , ) + * + * Writing to a private instance field (TS 4.3+): + * __classPrivateFieldSet(, , , "f") + * + * Writing to a private instance set accessor (when defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", ) + * + * Writing to a private instance set accessor (when not defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Writing to a private instance method (TS 4.3+): + * __classPrivateFieldSet(, , , "m", ) + * NOTE: This always results in a runtime error. + * + * Writing to a private static field (TS 4.3+): + * __classPrivateFieldSet(, , , "f", <{ value: any }>) + * + * Writing to a private static set accessor (when defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", ) + * + * Writing to a private static set accessor (when not defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Writing to a private static method (TS 4.3+): + * __classPrivateFieldSet(, , , "m", ) + * NOTE: This always results in a runtime error. + */ ts.classPrivateFieldSetHelper = { name: "typescript:classPrivateFieldSet", importName: "__classPrivateFieldSet", scoped: false, - text: "\n var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, privateMap, value) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to set private field on non-instance\");\n }\n privateMap.set(receiver, value);\n return value;\n };" + text: "\n var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n };" }; var allUnscopedEmitHelpers; function getAllUnscopedEmitHelpers() { @@ -26591,25 +27160,93 @@ var ts; return node.kind === 17 /* TemplateTail */; } ts.isTemplateTail = isTemplateTail; + // Punctuation + function isDotDotDotToken(node) { + return node.kind === 25 /* DotDotDotToken */; + } + ts.isDotDotDotToken = isDotDotDotToken; + /*@internal*/ + function isCommaToken(node) { + return node.kind === 27 /* CommaToken */; + } + ts.isCommaToken = isCommaToken; + function isPlusToken(node) { + return node.kind === 39 /* PlusToken */; + } + ts.isPlusToken = isPlusToken; + function isMinusToken(node) { + return node.kind === 40 /* MinusToken */; + } + ts.isMinusToken = isMinusToken; + function isAsteriskToken(node) { + return node.kind === 41 /* AsteriskToken */; + } + ts.isAsteriskToken = isAsteriskToken; + /*@internal*/ + function isExclamationToken(node) { + return node.kind === 53 /* ExclamationToken */; + } + ts.isExclamationToken = isExclamationToken; + /*@internal*/ + function isQuestionToken(node) { + return node.kind === 57 /* QuestionToken */; + } + ts.isQuestionToken = isQuestionToken; + /*@internal*/ + function isColonToken(node) { + return node.kind === 58 /* ColonToken */; + } + ts.isColonToken = isColonToken; + /*@internal*/ + function isQuestionDotToken(node) { + return node.kind === 28 /* QuestionDotToken */; + } + ts.isQuestionDotToken = isQuestionDotToken; + /*@internal*/ + function isEqualsGreaterThanToken(node) { + return node.kind === 38 /* EqualsGreaterThanToken */; + } + ts.isEqualsGreaterThanToken = isEqualsGreaterThanToken; // Identifiers function isIdentifier(node) { return node.kind === 78 /* Identifier */; } ts.isIdentifier = isIdentifier; - // Names - function isQualifiedName(node) { - return node.kind === 157 /* QualifiedName */; - } - ts.isQualifiedName = isQualifiedName; - function isComputedPropertyName(node) { - return node.kind === 158 /* ComputedPropertyName */; - } - ts.isComputedPropertyName = isComputedPropertyName; function isPrivateIdentifier(node) { return node.kind === 79 /* PrivateIdentifier */; } ts.isPrivateIdentifier = isPrivateIdentifier; - // Tokens + // Reserved Words + /* @internal */ + function isExportModifier(node) { + return node.kind === 92 /* ExportKeyword */; + } + ts.isExportModifier = isExportModifier; + /* @internal */ + function isAsyncModifier(node) { + return node.kind === 129 /* AsyncKeyword */; + } + ts.isAsyncModifier = isAsyncModifier; + /* @internal */ + function isAssertsKeyword(node) { + return node.kind === 127 /* AssertsKeyword */; + } + ts.isAssertsKeyword = isAssertsKeyword; + /* @internal */ + function isAwaitKeyword(node) { + return node.kind === 130 /* AwaitKeyword */; + } + ts.isAwaitKeyword = isAwaitKeyword; + /* @internal */ + function isReadonlyKeyword(node) { + return node.kind === 142 /* ReadonlyKeyword */; + } + ts.isReadonlyKeyword = isReadonlyKeyword; + /* @internal */ + function isStaticModifier(node) { + return node.kind === 123 /* StaticKeyword */; + } + ts.isStaticModifier = isStaticModifier; /*@internal*/ function isSuperKeyword(node) { return node.kind === 105 /* SuperKeyword */; @@ -26620,597 +27257,591 @@ var ts; return node.kind === 99 /* ImportKeyword */; } ts.isImportKeyword = isImportKeyword; - /*@internal*/ - function isCommaToken(node) { - return node.kind === 27 /* CommaToken */; - } - ts.isCommaToken = isCommaToken; - /*@internal*/ - function isQuestionToken(node) { - return node.kind === 57 /* QuestionToken */; + // Names + function isQualifiedName(node) { + return node.kind === 158 /* QualifiedName */; } - ts.isQuestionToken = isQuestionToken; - /*@internal*/ - function isExclamationToken(node) { - return node.kind === 53 /* ExclamationToken */; + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 159 /* ComputedPropertyName */; } - ts.isExclamationToken = isExclamationToken; + ts.isComputedPropertyName = isComputedPropertyName; // Signature elements function isTypeParameterDeclaration(node) { - return node.kind === 159 /* TypeParameter */; + return node.kind === 160 /* TypeParameter */; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; // TODO(rbuckton): Rename to 'isParameterDeclaration' function isParameter(node) { - return node.kind === 160 /* Parameter */; + return node.kind === 161 /* Parameter */; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 161 /* Decorator */; + return node.kind === 162 /* Decorator */; } ts.isDecorator = isDecorator; // TypeMember function isPropertySignature(node) { - return node.kind === 162 /* PropertySignature */; + return node.kind === 163 /* PropertySignature */; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 163 /* PropertyDeclaration */; + return node.kind === 164 /* PropertyDeclaration */; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 164 /* MethodSignature */; + return node.kind === 165 /* MethodSignature */; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 165 /* MethodDeclaration */; + return node.kind === 166 /* MethodDeclaration */; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 166 /* Constructor */; + return node.kind === 167 /* Constructor */; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 167 /* GetAccessor */; + return node.kind === 168 /* GetAccessor */; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 168 /* SetAccessor */; + return node.kind === 169 /* SetAccessor */; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 169 /* CallSignature */; + return node.kind === 170 /* CallSignature */; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 170 /* ConstructSignature */; + return node.kind === 171 /* ConstructSignature */; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 171 /* IndexSignature */; + return node.kind === 172 /* IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; // Type function isTypePredicateNode(node) { - return node.kind === 172 /* TypePredicate */; + return node.kind === 173 /* TypePredicate */; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 173 /* TypeReference */; + return node.kind === 174 /* TypeReference */; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 174 /* FunctionType */; + return node.kind === 175 /* FunctionType */; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 175 /* ConstructorType */; + return node.kind === 176 /* ConstructorType */; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 176 /* TypeQuery */; + return node.kind === 177 /* TypeQuery */; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 177 /* TypeLiteral */; + return node.kind === 178 /* TypeLiteral */; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 178 /* ArrayType */; + return node.kind === 179 /* ArrayType */; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 179 /* TupleType */; + return node.kind === 180 /* TupleType */; } ts.isTupleTypeNode = isTupleTypeNode; function isNamedTupleMember(node) { - return node.kind === 192 /* NamedTupleMember */; + return node.kind === 193 /* NamedTupleMember */; } ts.isNamedTupleMember = isNamedTupleMember; function isOptionalTypeNode(node) { - return node.kind === 180 /* OptionalType */; + return node.kind === 181 /* OptionalType */; } ts.isOptionalTypeNode = isOptionalTypeNode; function isRestTypeNode(node) { - return node.kind === 181 /* RestType */; + return node.kind === 182 /* RestType */; } ts.isRestTypeNode = isRestTypeNode; function isUnionTypeNode(node) { - return node.kind === 182 /* UnionType */; + return node.kind === 183 /* UnionType */; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 183 /* IntersectionType */; + return node.kind === 184 /* IntersectionType */; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isConditionalTypeNode(node) { - return node.kind === 184 /* ConditionalType */; + return node.kind === 185 /* ConditionalType */; } ts.isConditionalTypeNode = isConditionalTypeNode; function isInferTypeNode(node) { - return node.kind === 185 /* InferType */; + return node.kind === 186 /* InferType */; } ts.isInferTypeNode = isInferTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 186 /* ParenthesizedType */; + return node.kind === 187 /* ParenthesizedType */; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 187 /* ThisType */; + return node.kind === 188 /* ThisType */; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 188 /* TypeOperator */; + return node.kind === 189 /* TypeOperator */; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 189 /* IndexedAccessType */; + return node.kind === 190 /* IndexedAccessType */; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 190 /* MappedType */; + return node.kind === 191 /* MappedType */; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 191 /* LiteralType */; + return node.kind === 192 /* LiteralType */; } ts.isLiteralTypeNode = isLiteralTypeNode; function isImportTypeNode(node) { - return node.kind === 195 /* ImportType */; + return node.kind === 196 /* ImportType */; } ts.isImportTypeNode = isImportTypeNode; function isTemplateLiteralTypeSpan(node) { - return node.kind === 194 /* TemplateLiteralTypeSpan */; + return node.kind === 195 /* TemplateLiteralTypeSpan */; } ts.isTemplateLiteralTypeSpan = isTemplateLiteralTypeSpan; function isTemplateLiteralTypeNode(node) { - return node.kind === 193 /* TemplateLiteralType */; + return node.kind === 194 /* TemplateLiteralType */; } ts.isTemplateLiteralTypeNode = isTemplateLiteralTypeNode; // Binding patterns function isObjectBindingPattern(node) { - return node.kind === 196 /* ObjectBindingPattern */; + return node.kind === 197 /* ObjectBindingPattern */; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 197 /* ArrayBindingPattern */; + return node.kind === 198 /* ArrayBindingPattern */; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 198 /* BindingElement */; + return node.kind === 199 /* BindingElement */; } ts.isBindingElement = isBindingElement; // Expression function isArrayLiteralExpression(node) { - return node.kind === 199 /* ArrayLiteralExpression */; + return node.kind === 200 /* ArrayLiteralExpression */; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 200 /* ObjectLiteralExpression */; + return node.kind === 201 /* ObjectLiteralExpression */; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 201 /* PropertyAccessExpression */; + return node.kind === 202 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 202 /* ElementAccessExpression */; + return node.kind === 203 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 203 /* CallExpression */; + return node.kind === 204 /* CallExpression */; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 204 /* NewExpression */; + return node.kind === 205 /* NewExpression */; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 205 /* TaggedTemplateExpression */; + return node.kind === 206 /* TaggedTemplateExpression */; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertionExpression(node) { - return node.kind === 206 /* TypeAssertionExpression */; + return node.kind === 207 /* TypeAssertionExpression */; } ts.isTypeAssertionExpression = isTypeAssertionExpression; function isParenthesizedExpression(node) { - return node.kind === 207 /* ParenthesizedExpression */; + return node.kind === 208 /* ParenthesizedExpression */; } ts.isParenthesizedExpression = isParenthesizedExpression; function isFunctionExpression(node) { - return node.kind === 208 /* FunctionExpression */; + return node.kind === 209 /* FunctionExpression */; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 209 /* ArrowFunction */; + return node.kind === 210 /* ArrowFunction */; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 210 /* DeleteExpression */; + return node.kind === 211 /* DeleteExpression */; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 211 /* TypeOfExpression */; + return node.kind === 212 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 212 /* VoidExpression */; + return node.kind === 213 /* VoidExpression */; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 213 /* AwaitExpression */; + return node.kind === 214 /* AwaitExpression */; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 214 /* PrefixUnaryExpression */; + return node.kind === 215 /* PrefixUnaryExpression */; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 215 /* PostfixUnaryExpression */; + return node.kind === 216 /* PostfixUnaryExpression */; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 216 /* BinaryExpression */; + return node.kind === 217 /* BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 217 /* ConditionalExpression */; + return node.kind === 218 /* ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 218 /* TemplateExpression */; + return node.kind === 219 /* TemplateExpression */; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 219 /* YieldExpression */; + return node.kind === 220 /* YieldExpression */; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 220 /* SpreadElement */; + return node.kind === 221 /* SpreadElement */; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 221 /* ClassExpression */; + return node.kind === 222 /* ClassExpression */; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 222 /* OmittedExpression */; + return node.kind === 223 /* OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 223 /* ExpressionWithTypeArguments */; + return node.kind === 224 /* ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 224 /* AsExpression */; + return node.kind === 225 /* AsExpression */; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 225 /* NonNullExpression */; + return node.kind === 226 /* NonNullExpression */; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 226 /* MetaProperty */; + return node.kind === 227 /* MetaProperty */; } ts.isMetaProperty = isMetaProperty; function isSyntheticExpression(node) { - return node.kind === 227 /* SyntheticExpression */; + return node.kind === 228 /* SyntheticExpression */; } ts.isSyntheticExpression = isSyntheticExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 336 /* PartiallyEmittedExpression */; + return node.kind === 340 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isCommaListExpression(node) { - return node.kind === 337 /* CommaListExpression */; + return node.kind === 341 /* CommaListExpression */; } ts.isCommaListExpression = isCommaListExpression; // Misc function isTemplateSpan(node) { - return node.kind === 228 /* TemplateSpan */; + return node.kind === 229 /* TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 229 /* SemicolonClassElement */; + return node.kind === 230 /* SemicolonClassElement */; } ts.isSemicolonClassElement = isSemicolonClassElement; // Elements function isBlock(node) { - return node.kind === 230 /* Block */; + return node.kind === 231 /* Block */; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 232 /* VariableStatement */; + return node.kind === 233 /* VariableStatement */; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 231 /* EmptyStatement */; + return node.kind === 232 /* EmptyStatement */; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 233 /* ExpressionStatement */; + return node.kind === 234 /* ExpressionStatement */; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 234 /* IfStatement */; + return node.kind === 235 /* IfStatement */; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 235 /* DoStatement */; + return node.kind === 236 /* DoStatement */; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 236 /* WhileStatement */; + return node.kind === 237 /* WhileStatement */; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 237 /* ForStatement */; + return node.kind === 238 /* ForStatement */; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 238 /* ForInStatement */; + return node.kind === 239 /* ForInStatement */; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 239 /* ForOfStatement */; + return node.kind === 240 /* ForOfStatement */; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 240 /* ContinueStatement */; + return node.kind === 241 /* ContinueStatement */; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 241 /* BreakStatement */; + return node.kind === 242 /* BreakStatement */; } ts.isBreakStatement = isBreakStatement; function isReturnStatement(node) { - return node.kind === 242 /* ReturnStatement */; + return node.kind === 243 /* ReturnStatement */; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 243 /* WithStatement */; + return node.kind === 244 /* WithStatement */; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 244 /* SwitchStatement */; + return node.kind === 245 /* SwitchStatement */; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 245 /* LabeledStatement */; + return node.kind === 246 /* LabeledStatement */; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 246 /* ThrowStatement */; + return node.kind === 247 /* ThrowStatement */; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 247 /* TryStatement */; + return node.kind === 248 /* TryStatement */; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 248 /* DebuggerStatement */; + return node.kind === 249 /* DebuggerStatement */; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 249 /* VariableDeclaration */; + return node.kind === 250 /* VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 250 /* VariableDeclarationList */; + return node.kind === 251 /* VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 251 /* FunctionDeclaration */; + return node.kind === 252 /* FunctionDeclaration */; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 252 /* ClassDeclaration */; + return node.kind === 253 /* ClassDeclaration */; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 253 /* InterfaceDeclaration */; + return node.kind === 254 /* InterfaceDeclaration */; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 254 /* TypeAliasDeclaration */; + return node.kind === 255 /* TypeAliasDeclaration */; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 255 /* EnumDeclaration */; + return node.kind === 256 /* EnumDeclaration */; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 256 /* ModuleDeclaration */; + return node.kind === 257 /* ModuleDeclaration */; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 257 /* ModuleBlock */; + return node.kind === 258 /* ModuleBlock */; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 258 /* CaseBlock */; + return node.kind === 259 /* CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 259 /* NamespaceExportDeclaration */; + return node.kind === 260 /* NamespaceExportDeclaration */; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */; + return node.kind === 261 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 261 /* ImportDeclaration */; + return node.kind === 262 /* ImportDeclaration */; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 262 /* ImportClause */; + return node.kind === 263 /* ImportClause */; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 263 /* NamespaceImport */; + return node.kind === 264 /* NamespaceImport */; } ts.isNamespaceImport = isNamespaceImport; function isNamespaceExport(node) { - return node.kind === 269 /* NamespaceExport */; + return node.kind === 270 /* NamespaceExport */; } ts.isNamespaceExport = isNamespaceExport; function isNamedImports(node) { - return node.kind === 264 /* NamedImports */; + return node.kind === 265 /* NamedImports */; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 265 /* ImportSpecifier */; + return node.kind === 266 /* ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 266 /* ExportAssignment */; + return node.kind === 267 /* ExportAssignment */; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 267 /* ExportDeclaration */; + return node.kind === 268 /* ExportDeclaration */; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 268 /* NamedExports */; + return node.kind === 269 /* NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 270 /* ExportSpecifier */; + return node.kind === 271 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 271 /* MissingDeclaration */; + return node.kind === 272 /* MissingDeclaration */; } ts.isMissingDeclaration = isMissingDeclaration; function isNotEmittedStatement(node) { - return node.kind === 335 /* NotEmittedStatement */; + return node.kind === 339 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ function isSyntheticReference(node) { - return node.kind === 340 /* SyntheticReferenceExpression */; + return node.kind === 344 /* SyntheticReferenceExpression */; } ts.isSyntheticReference = isSyntheticReference; /* @internal */ function isMergeDeclarationMarker(node) { - return node.kind === 338 /* MergeDeclarationMarker */; + return node.kind === 342 /* MergeDeclarationMarker */; } ts.isMergeDeclarationMarker = isMergeDeclarationMarker; /* @internal */ function isEndOfDeclarationMarker(node) { - return node.kind === 339 /* EndOfDeclarationMarker */; + return node.kind === 343 /* EndOfDeclarationMarker */; } ts.isEndOfDeclarationMarker = isEndOfDeclarationMarker; // Module References function isExternalModuleReference(node) { - return node.kind === 272 /* ExternalModuleReference */; + return node.kind === 273 /* ExternalModuleReference */; } ts.isExternalModuleReference = isExternalModuleReference; // JSX function isJsxElement(node) { - return node.kind === 273 /* JsxElement */; + return node.kind === 274 /* JsxElement */; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 274 /* JsxSelfClosingElement */; + return node.kind === 275 /* JsxSelfClosingElement */; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 275 /* JsxOpeningElement */; + return node.kind === 276 /* JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 276 /* JsxClosingElement */; + return node.kind === 277 /* JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxFragment(node) { - return node.kind === 277 /* JsxFragment */; + return node.kind === 278 /* JsxFragment */; } ts.isJsxFragment = isJsxFragment; function isJsxOpeningFragment(node) { - return node.kind === 278 /* JsxOpeningFragment */; + return node.kind === 279 /* JsxOpeningFragment */; } ts.isJsxOpeningFragment = isJsxOpeningFragment; function isJsxClosingFragment(node) { - return node.kind === 279 /* JsxClosingFragment */; + return node.kind === 280 /* JsxClosingFragment */; } ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 280 /* JsxAttribute */; + return node.kind === 281 /* JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 281 /* JsxAttributes */; + return node.kind === 282 /* JsxAttributes */; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 282 /* JsxSpreadAttribute */; + return node.kind === 283 /* JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 283 /* JsxExpression */; + return node.kind === 284 /* JsxExpression */; } ts.isJsxExpression = isJsxExpression; // Clauses function isCaseClause(node) { - return node.kind === 284 /* CaseClause */; + return node.kind === 285 /* CaseClause */; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 285 /* DefaultClause */; + return node.kind === 286 /* DefaultClause */; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 286 /* HeritageClause */; + return node.kind === 287 /* HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 287 /* CatchClause */; + return node.kind === 288 /* CatchClause */; } ts.isCatchClause = isCatchClause; // Property assignments function isPropertyAssignment(node) { - return node.kind === 288 /* PropertyAssignment */; + return node.kind === 289 /* PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 289 /* ShorthandPropertyAssignment */; + return node.kind === 290 /* ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 290 /* SpreadAssignment */; + return node.kind === 291 /* SpreadAssignment */; } ts.isSpreadAssignment = isSpreadAssignment; // Enum function isEnumMember(node) { - return node.kind === 291 /* EnumMember */; + return node.kind === 292 /* EnumMember */; } ts.isEnumMember = isEnumMember; // Unparsed // TODO(rbuckton): isUnparsedPrologue function isUnparsedPrepend(node) { - return node.kind === 293 /* UnparsedPrepend */; + return node.kind === 294 /* UnparsedPrepend */; } ts.isUnparsedPrepend = isUnparsedPrepend; // TODO(rbuckton): isUnparsedText @@ -27218,156 +27849,164 @@ var ts; // TODO(rbuckton): isUnparsedSyntheticReference // Top-level nodes function isSourceFile(node) { - return node.kind === 297 /* SourceFile */; + return node.kind === 298 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 298 /* Bundle */; + return node.kind === 299 /* Bundle */; } ts.isBundle = isBundle; function isUnparsedSource(node) { - return node.kind === 299 /* UnparsedSource */; + return node.kind === 300 /* UnparsedSource */; } ts.isUnparsedSource = isUnparsedSource; // TODO(rbuckton): isInputFiles // JSDoc Elements function isJSDocTypeExpression(node) { - return node.kind === 301 /* JSDocTypeExpression */; + return node.kind === 302 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocNameReference(node) { - return node.kind === 302 /* JSDocNameReference */; + return node.kind === 303 /* JSDocNameReference */; } ts.isJSDocNameReference = isJSDocNameReference; + function isJSDocLink(node) { + return node.kind === 316 /* JSDocLink */; + } + ts.isJSDocLink = isJSDocLink; function isJSDocAllType(node) { - return node.kind === 303 /* JSDocAllType */; + return node.kind === 304 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 304 /* JSDocUnknownType */; + return node.kind === 305 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 305 /* JSDocNullableType */; + return node.kind === 306 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 306 /* JSDocNonNullableType */; + return node.kind === 307 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 307 /* JSDocOptionalType */; + return node.kind === 308 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 308 /* JSDocFunctionType */; + return node.kind === 309 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 309 /* JSDocVariadicType */; + return node.kind === 310 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDocNamepathType(node) { - return node.kind === 310 /* JSDocNamepathType */; + return node.kind === 311 /* JSDocNamepathType */; } ts.isJSDocNamepathType = isJSDocNamepathType; function isJSDoc(node) { - return node.kind === 311 /* JSDocComment */; + return node.kind === 312 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocTypeLiteral(node) { - return node.kind === 312 /* JSDocTypeLiteral */; + return node.kind === 314 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; function isJSDocSignature(node) { - return node.kind === 313 /* JSDocSignature */; + return node.kind === 315 /* JSDocSignature */; } ts.isJSDocSignature = isJSDocSignature; // JSDoc Tags function isJSDocAugmentsTag(node) { - return node.kind === 315 /* JSDocAugmentsTag */; + return node.kind === 318 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocAuthorTag(node) { - return node.kind === 317 /* JSDocAuthorTag */; + return node.kind === 320 /* JSDocAuthorTag */; } ts.isJSDocAuthorTag = isJSDocAuthorTag; function isJSDocClassTag(node) { - return node.kind === 319 /* JSDocClassTag */; + return node.kind === 322 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocCallbackTag(node) { - return node.kind === 324 /* JSDocCallbackTag */; + return node.kind === 328 /* JSDocCallbackTag */; } ts.isJSDocCallbackTag = isJSDocCallbackTag; function isJSDocPublicTag(node) { - return node.kind === 320 /* JSDocPublicTag */; + return node.kind === 323 /* JSDocPublicTag */; } ts.isJSDocPublicTag = isJSDocPublicTag; function isJSDocPrivateTag(node) { - return node.kind === 321 /* JSDocPrivateTag */; + return node.kind === 324 /* JSDocPrivateTag */; } ts.isJSDocPrivateTag = isJSDocPrivateTag; function isJSDocProtectedTag(node) { - return node.kind === 322 /* JSDocProtectedTag */; + return node.kind === 325 /* JSDocProtectedTag */; } ts.isJSDocProtectedTag = isJSDocProtectedTag; function isJSDocReadonlyTag(node) { - return node.kind === 323 /* JSDocReadonlyTag */; + return node.kind === 326 /* JSDocReadonlyTag */; } ts.isJSDocReadonlyTag = isJSDocReadonlyTag; + function isJSDocOverrideTag(node) { + return node.kind === 327 /* JSDocOverrideTag */; + } + ts.isJSDocOverrideTag = isJSDocOverrideTag; function isJSDocDeprecatedTag(node) { - return node.kind === 318 /* JSDocDeprecatedTag */; + return node.kind === 321 /* JSDocDeprecatedTag */; } ts.isJSDocDeprecatedTag = isJSDocDeprecatedTag; function isJSDocSeeTag(node) { - return node.kind === 332 /* JSDocSeeTag */; + return node.kind === 336 /* JSDocSeeTag */; } ts.isJSDocSeeTag = isJSDocSeeTag; function isJSDocEnumTag(node) { - return node.kind === 325 /* JSDocEnumTag */; + return node.kind === 329 /* JSDocEnumTag */; } ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocParameterTag(node) { - return node.kind === 326 /* JSDocParameterTag */; + return node.kind === 330 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 327 /* JSDocReturnTag */; + return node.kind === 331 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocThisTag(node) { - return node.kind === 328 /* JSDocThisTag */; + return node.kind === 332 /* JSDocThisTag */; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocTypeTag(node) { - return node.kind === 329 /* JSDocTypeTag */; + return node.kind === 333 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 330 /* JSDocTemplateTag */; + return node.kind === 334 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 331 /* JSDocTypedefTag */; + return node.kind === 335 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocUnknownTag(node) { - return node.kind === 314 /* JSDocTag */; + return node.kind === 317 /* JSDocTag */; } ts.isJSDocUnknownTag = isJSDocUnknownTag; function isJSDocPropertyTag(node) { - return node.kind === 333 /* JSDocPropertyTag */; + return node.kind === 337 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocImplementsTag(node) { - return node.kind === 316 /* JSDocImplementsTag */; + return node.kind === 319 /* JSDocImplementsTag */; } ts.isJSDocImplementsTag = isJSDocImplementsTag; // Synthesized list /* @internal */ function isSyntaxList(n) { - return n.kind === 334 /* SyntaxList */; + return n.kind === 338 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; })(ts || (ts = {})); @@ -27384,7 +28023,7 @@ var ts; return ts.setTextRange(factory.createElementAccessExpression(target, memberName.expression), location); } else { - var expression = ts.setTextRange(ts.isIdentifierOrPrivateIdentifier(memberName) + var expression = ts.setTextRange(ts.isMemberName(memberName) ? factory.createPropertyAccessExpression(target, memberName) : factory.createElementAccessExpression(target, memberName), memberName); ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */; @@ -27566,14 +28205,14 @@ var ts; ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals."); } switch (property.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return createExpressionForAccessorDeclaration(factory, node.properties, property, receiver, !!node.multiLine); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return createExpressionForPropertyAssignment(factory, property, receiver); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(factory, property, receiver); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return createExpressionForMethodDeclaration(factory, property, receiver); } } @@ -27626,21 +28265,21 @@ var ts; } ts.startsWithUseStrict = startsWithUseStrict; function isCommaSequence(node) { - return node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || - node.kind === 337 /* CommaListExpression */; + return node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || + node.kind === 341 /* CommaListExpression */; } ts.isCommaSequence = isCommaSequence; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 15 /* All */; } switch (node.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return (kinds & 1 /* Parentheses */) !== 0; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return (kinds & 2 /* TypeAssertions */) !== 0; - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return (kinds & 4 /* NonNullAssertions */) !== 0; - case 336 /* PartiallyEmittedExpression */: + case 340 /* PartiallyEmittedExpression */: return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -27761,10 +28400,10 @@ var ts; var name = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name) ? name : factory.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 261 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 262 /* ImportDeclaration */ && node.importClause) { return factory.getGeneratedNameForNode(node); } - if (node.kind === 267 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 268 /* ExportDeclaration */ && node.moduleSpecifier) { return factory.getGeneratedNameForNode(node); } return undefined; @@ -27883,7 +28522,7 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // `b` in `({ a: b } = ...)` // `b` in `({ a: b = 1 } = ...)` // `{b}` in `({ a: {b} } = ...)` @@ -27895,11 +28534,11 @@ var ts; // `b[0]` in `({ a: b[0] } = ...)` // `b[0]` in `({ a: b[0] = 1 } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: // `a` in `({ a } = ...)` // `a` in `({ a = 1 } = ...)` return bindingElement.name; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } @@ -27931,12 +28570,12 @@ var ts; */ function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 160 /* Parameter */: - case 198 /* BindingElement */: + case 161 /* Parameter */: + case 199 /* BindingElement */: // `...` in `let [...a] = ...` return bindingElement.dotDotDotToken; - case 220 /* SpreadElement */: - case 290 /* SpreadAssignment */: + case 221 /* SpreadElement */: + case 291 /* SpreadAssignment */: // `...` in `[...a] = ...` return bindingElement; } @@ -27954,7 +28593,7 @@ var ts; ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 198 /* BindingElement */: + case 199 /* BindingElement */: // `a` in `let { a: b } = ...` // `[a]` in `let { [a]: b } = ...` // `"a"` in `let { "a": b } = ...` @@ -27969,7 +28608,7 @@ var ts; : propertyName; } break; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // `a` in `({ a: b } = ...)` // `[a]` in `({ [a]: b } = ...)` // `"a"` in `({ "a": b } = ...)` @@ -27984,7 +28623,7 @@ var ts; : propertyName; } break; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) { return ts.Debug.failBadSyntaxKind(bindingElement.name); @@ -28007,13 +28646,13 @@ var ts; */ function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: - case 199 /* ArrayLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + case 200 /* ArrayLiteralExpression */: // `a` in `{a}` // `a` in `[a]` return name.elements; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: // `a` in `{a}` return name.properties; } @@ -28034,46 +28673,294 @@ var ts; ts.getJSDocTypeAliasName = getJSDocTypeAliasName; function canHaveModifiers(node) { var kind = node.kind; - return kind === 160 /* Parameter */ - || kind === 162 /* PropertySignature */ - || kind === 163 /* PropertyDeclaration */ - || kind === 164 /* MethodSignature */ - || kind === 165 /* MethodDeclaration */ - || kind === 166 /* Constructor */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 171 /* IndexSignature */ - || kind === 208 /* FunctionExpression */ - || kind === 209 /* ArrowFunction */ - || kind === 221 /* ClassExpression */ - || kind === 232 /* VariableStatement */ - || kind === 251 /* FunctionDeclaration */ - || kind === 252 /* ClassDeclaration */ - || kind === 253 /* InterfaceDeclaration */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 255 /* EnumDeclaration */ - || kind === 256 /* ModuleDeclaration */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 261 /* ImportDeclaration */ - || kind === 266 /* ExportAssignment */ - || kind === 267 /* ExportDeclaration */; + return kind === 161 /* Parameter */ + || kind === 163 /* PropertySignature */ + || kind === 164 /* PropertyDeclaration */ + || kind === 165 /* MethodSignature */ + || kind === 166 /* MethodDeclaration */ + || kind === 167 /* Constructor */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 172 /* IndexSignature */ + || kind === 209 /* FunctionExpression */ + || kind === 210 /* ArrowFunction */ + || kind === 222 /* ClassExpression */ + || kind === 233 /* VariableStatement */ + || kind === 252 /* FunctionDeclaration */ + || kind === 253 /* ClassDeclaration */ + || kind === 254 /* InterfaceDeclaration */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 256 /* EnumDeclaration */ + || kind === 257 /* ModuleDeclaration */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 262 /* ImportDeclaration */ + || kind === 267 /* ExportAssignment */ + || kind === 268 /* ExportDeclaration */; } ts.canHaveModifiers = canHaveModifiers; - /* @internal */ - function isExportModifier(node) { - return node.kind === 92 /* ExportKeyword */; - } - ts.isExportModifier = isExportModifier; - /* @internal */ - function isAsyncModifier(node) { - return node.kind === 129 /* AsyncKeyword */; - } - ts.isAsyncModifier = isAsyncModifier; - /* @internal */ - function isStaticModifier(node) { - return node.kind === 123 /* StaticKeyword */; + ts.isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); + ts.isQuestionOrExclamationToken = ts.or(ts.isQuestionToken, ts.isExclamationToken); + ts.isIdentifierOrThisTypeNode = ts.or(ts.isIdentifier, ts.isThisTypeNode); + ts.isReadonlyKeywordOrPlusOrMinusToken = ts.or(ts.isReadonlyKeyword, ts.isPlusToken, ts.isMinusToken); + ts.isQuestionOrPlusOrMinusToken = ts.or(ts.isQuestionToken, ts.isPlusToken, ts.isMinusToken); + ts.isModuleName = ts.or(ts.isIdentifier, ts.isStringLiteral); + function isLiteralTypeLikeExpression(node) { + var kind = node.kind; + return kind === 103 /* NullKeyword */ + || kind === 109 /* TrueKeyword */ + || kind === 94 /* FalseKeyword */ + || ts.isLiteralExpression(node) + || ts.isPrefixUnaryExpression(node); + } + ts.isLiteralTypeLikeExpression = isLiteralTypeLikeExpression; + function isExponentiationOperator(kind) { + return kind === 42 /* AsteriskAsteriskToken */; + } + function isMultiplicativeOperator(kind) { + return kind === 41 /* AsteriskToken */ + || kind === 43 /* SlashToken */ + || kind === 44 /* PercentToken */; + } + function isMultiplicativeOperatorOrHigher(kind) { + return isExponentiationOperator(kind) + || isMultiplicativeOperator(kind); + } + function isAdditiveOperator(kind) { + return kind === 39 /* PlusToken */ + || kind === 40 /* MinusToken */; + } + function isAdditiveOperatorOrHigher(kind) { + return isAdditiveOperator(kind) + || isMultiplicativeOperatorOrHigher(kind); + } + function isShiftOperator(kind) { + return kind === 47 /* LessThanLessThanToken */ + || kind === 48 /* GreaterThanGreaterThanToken */ + || kind === 49 /* GreaterThanGreaterThanGreaterThanToken */; + } + function isShiftOperatorOrHigher(kind) { + return isShiftOperator(kind) + || isAdditiveOperatorOrHigher(kind); + } + function isRelationalOperator(kind) { + return kind === 29 /* LessThanToken */ + || kind === 32 /* LessThanEqualsToken */ + || kind === 31 /* GreaterThanToken */ + || kind === 33 /* GreaterThanEqualsToken */ + || kind === 101 /* InstanceOfKeyword */ + || kind === 100 /* InKeyword */; + } + function isRelationalOperatorOrHigher(kind) { + return isRelationalOperator(kind) + || isShiftOperatorOrHigher(kind); + } + function isEqualityOperator(kind) { + return kind === 34 /* EqualsEqualsToken */ + || kind === 36 /* EqualsEqualsEqualsToken */ + || kind === 35 /* ExclamationEqualsToken */ + || kind === 37 /* ExclamationEqualsEqualsToken */; + } + function isEqualityOperatorOrHigher(kind) { + return isEqualityOperator(kind) + || isRelationalOperatorOrHigher(kind); + } + function isBitwiseOperator(kind) { + return kind === 50 /* AmpersandToken */ + || kind === 51 /* BarToken */ + || kind === 52 /* CaretToken */; + } + function isBitwiseOperatorOrHigher(kind) { + return isBitwiseOperator(kind) + || isEqualityOperatorOrHigher(kind); + } + // NOTE: The version in utilities includes ExclamationToken, which is not a binary operator. + function isLogicalOperator(kind) { + return kind === 55 /* AmpersandAmpersandToken */ + || kind === 56 /* BarBarToken */; + } + function isLogicalOperatorOrHigher(kind) { + return isLogicalOperator(kind) + || isBitwiseOperatorOrHigher(kind); + } + function isAssignmentOperatorOrHigher(kind) { + return kind === 60 /* QuestionQuestionToken */ + || isLogicalOperatorOrHigher(kind) + || ts.isAssignmentOperator(kind); + } + function isBinaryOperator(kind) { + return isAssignmentOperatorOrHigher(kind) + || kind === 27 /* CommaToken */; + } + function isBinaryOperatorToken(node) { + return isBinaryOperator(node.kind); + } + ts.isBinaryOperatorToken = isBinaryOperatorToken; + var BinaryExpressionState; + (function (BinaryExpressionState) { + /** + * Handles walking into a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function enter(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, outerState) { + var prevUserState = stackIndex > 0 ? userStateStack[stackIndex - 1] : undefined; + ts.Debug.assertEqual(stateStack[stackIndex], enter); + userStateStack[stackIndex] = machine.onEnter(nodeStack[stackIndex], prevUserState, outerState); + stateStack[stackIndex] = nextState(machine, enter); + return stackIndex; + } + BinaryExpressionState.enter = enter; + /** + * Handles walking the `left` side of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function left(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], left); + ts.Debug.assertIsDefined(machine.onLeft); + stateStack[stackIndex] = nextState(machine, left); + var nextNode = machine.onLeft(nodeStack[stackIndex].left, userStateStack[stackIndex], nodeStack[stackIndex]); + if (nextNode) { + checkCircularity(stackIndex, nodeStack, nextNode); + return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode); + } + return stackIndex; + } + BinaryExpressionState.left = left; + /** + * Handles walking the `operatorToken` of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function operator(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], operator); + ts.Debug.assertIsDefined(machine.onOperator); + stateStack[stackIndex] = nextState(machine, operator); + machine.onOperator(nodeStack[stackIndex].operatorToken, userStateStack[stackIndex], nodeStack[stackIndex]); + return stackIndex; + } + BinaryExpressionState.operator = operator; + /** + * Handles walking the `right` side of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function right(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], right); + ts.Debug.assertIsDefined(machine.onRight); + stateStack[stackIndex] = nextState(machine, right); + var nextNode = machine.onRight(nodeStack[stackIndex].right, userStateStack[stackIndex], nodeStack[stackIndex]); + if (nextNode) { + checkCircularity(stackIndex, nodeStack, nextNode); + return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode); + } + return stackIndex; + } + BinaryExpressionState.right = right; + /** + * Handles walking out of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function exit(machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], exit); + stateStack[stackIndex] = nextState(machine, exit); + var result = machine.onExit(nodeStack[stackIndex], userStateStack[stackIndex]); + if (stackIndex > 0) { + stackIndex--; + if (machine.foldState) { + var side = stateStack[stackIndex] === exit ? "right" : "left"; + userStateStack[stackIndex] = machine.foldState(userStateStack[stackIndex], result, side); + } + } + else { + resultHolder.value = result; + } + return stackIndex; + } + BinaryExpressionState.exit = exit; + /** + * Handles a frame that is already done. + * @returns The `done` state. + */ + function done(_machine, stackIndex, stateStack, _nodeStack, _userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], done); + return stackIndex; + } + BinaryExpressionState.done = done; + function nextState(machine, currentState) { + switch (currentState) { + case enter: + if (machine.onLeft) + return left; + // falls through + case left: + if (machine.onOperator) + return operator; + // falls through + case operator: + if (machine.onRight) + return right; + // falls through + case right: return exit; + case exit: return done; + case done: return done; + default: ts.Debug.fail("Invalid state"); + } + } + BinaryExpressionState.nextState = nextState; + function pushStack(stackIndex, stateStack, nodeStack, userStateStack, node) { + stackIndex++; + stateStack[stackIndex] = enter; + nodeStack[stackIndex] = node; + userStateStack[stackIndex] = undefined; + return stackIndex; + } + function checkCircularity(stackIndex, nodeStack, node) { + if (ts.Debug.shouldAssert(2 /* Aggressive */)) { + while (stackIndex >= 0) { + ts.Debug.assert(nodeStack[stackIndex] !== node, "Circular traversal detected."); + stackIndex--; + } + } + } + })(BinaryExpressionState || (BinaryExpressionState = {})); + /** + * Holds state machine handler functions + */ + var BinaryExpressionStateMachine = /** @class */ (function () { + function BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState) { + this.onEnter = onEnter; + this.onLeft = onLeft; + this.onOperator = onOperator; + this.onRight = onRight; + this.onExit = onExit; + this.foldState = foldState; + } + return BinaryExpressionStateMachine; + }()); + function createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState) { + var machine = new BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState); + return trampoline; + function trampoline(node, outerState) { + var resultHolder = { value: undefined }; + var stateStack = [BinaryExpressionState.enter]; + var nodeStack = [node]; + var userStateStack = [undefined]; + var stackIndex = 0; + while (stateStack[stackIndex] !== BinaryExpressionState.done) { + stackIndex = stateStack[stackIndex](machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, outerState); + } + ts.Debug.assertEqual(stackIndex, 0); + return resultHolder.value; + } } - ts.isStaticModifier = isStaticModifier; + ts.createBinaryExpressionTrampoline = createBinaryExpressionTrampoline; })(ts || (ts = {})); var ts; (function (ts) { @@ -28155,19 +29042,19 @@ var ts; * that they appear in the source code. The language service depends on this property to locate nodes by position. */ function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 156 /* LastToken */) { + if (!node || node.kind <= 157 /* LastToken */) { return; } switch (node.kind) { - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -28175,9 +29062,9 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: return visitNode(cbNode, node.expression); - case 160 /* Parameter */: + case 161 /* Parameter */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || @@ -28185,7 +29072,7 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -28193,51 +29080,51 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.initializer); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -28249,374 +29136,390 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return visitNode(cbNode, node.assertsModifier) || visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return visitNodes(cbNode, cbNodes, node.members); - case 178 /* ArrayType */: + case 179 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 179 /* TupleType */: + case 180 /* TupleType */: return visitNodes(cbNode, cbNodes, node.elements); - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: return visitNodes(cbNode, cbNodes, node.types); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return visitNode(cbNode, node.checkType) || visitNode(cbNode, node.extendsType) || visitNode(cbNode, node.trueType) || visitNode(cbNode, node.falseType); - case 185 /* InferType */: + case 186 /* InferType */: return visitNode(cbNode, node.typeParameter); - case 195 /* ImportType */: + case 196 /* ImportType */: return visitNode(cbNode, node.argument) || visitNode(cbNode, node.qualifier) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 186 /* ParenthesizedType */: - case 188 /* TypeOperator */: + case 187 /* ParenthesizedType */: + case 189 /* TypeOperator */: return visitNode(cbNode, node.type); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 190 /* MappedType */: + case 191 /* MappedType */: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.nameType) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 191 /* LiteralType */: + case 192 /* LiteralType */: return visitNode(cbNode, node.literal); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: return visitNodes(cbNode, cbNodes, node.elements); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitNodes(cbNode, cbNodes, node.properties); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || visitNode(cbNode, node.name); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || visitNode(cbNode, node.argumentExpression); - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.template); - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 224 /* AsExpression */: + case 225 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return visitNode(cbNode, node.expression); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return visitNode(cbNode, node.name); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return visitNode(cbNode, node.expression); - case 230 /* Block */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 258 /* ModuleBlock */: return visitNodes(cbNode, cbNodes, node.statements); - case 297 /* SourceFile */: + case 298 /* SourceFile */: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return visitNodes(cbNode, cbNodes, node.declarations); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 240 /* ContinueStatement */: - case 241 /* BreakStatement */: + case 241 /* ContinueStatement */: + case 242 /* BreakStatement */: return visitNode(cbNode, node.label); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return visitNodes(cbNode, cbNodes, node.clauses); - case 284 /* CaseClause */: + case 285 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: return visitNodes(cbNode, cbNodes, node.statements); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 161 /* Decorator */: + case 162 /* Decorator */: return visitNode(cbNode, node.expression); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 291 /* EnumMember */: + case 292 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: return visitNode(cbNode, node.name); - case 264 /* NamedImports */: - case 268 /* NamedExports */: + case 265 /* NamedImports */: + case 269 /* NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 194 /* TemplateLiteralTypeSpan */: + case 195 /* TemplateLiteralTypeSpan */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.literal); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: return visitNodes(cbNode, cbNodes, node.types); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 271 /* MissingDeclaration */: + case 272 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return visitNode(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingFragment); - case 274 /* JsxSelfClosingElement */: - case 275 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 282 /* JsxSpreadAttribute */: + case 283 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 276 /* JsxClosingElement */: + case 277 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 180 /* OptionalType */: - case 181 /* RestType */: - case 301 /* JSDocTypeExpression */: - case 306 /* JSDocNonNullableType */: - case 305 /* JSDocNullableType */: - case 307 /* JSDocOptionalType */: - case 309 /* JSDocVariadicType */: + case 181 /* OptionalType */: + case 182 /* RestType */: + case 302 /* JSDocTypeExpression */: + case 307 /* JSDocNonNullableType */: + case 306 /* JSDocNullableType */: + case 308 /* JSDocOptionalType */: + case 310 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 311 /* JSDocComment */: - return visitNodes(cbNode, cbNodes, node.tags); - case 332 /* JSDocSeeTag */: + case 312 /* JSDocComment */: + return (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) + || visitNodes(cbNode, cbNodes, node.tags); + case 336 /* JSDocSeeTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.name); - case 302 /* JSDocNameReference */: + visitNode(cbNode, node.name) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 303 /* JSDocNameReference */: return visitNode(cbNode, node.name); - case 326 /* JSDocParameterTag */: - case 333 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: return visitNode(cbNode, node.tagName) || (node.isNameFirst ? visitNode(cbNode, node.name) || - visitNode(cbNode, node.typeExpression) + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) : visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.name)); - case 317 /* JSDocAuthorTag */: - return visitNode(cbNode, node.tagName); - case 316 /* JSDocImplementsTag */: + visitNode(cbNode, node.name)) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 320 /* JSDocAuthorTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.class); - case 315 /* JSDocAugmentsTag */: + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 319 /* JSDocImplementsTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.class); - case 330 /* JSDocTemplateTag */: + visitNode(cbNode, node.class) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 318 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 334 /* JSDocTemplateTag */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.constraint) || - visitNodes(cbNode, cbNodes, node.typeParameters); - case 331 /* JSDocTypedefTag */: + visitNodes(cbNode, cbNodes, node.typeParameters) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 335 /* JSDocTypedefTag */: return visitNode(cbNode, node.tagName) || (node.typeExpression && - node.typeExpression.kind === 301 /* JSDocTypeExpression */ + node.typeExpression.kind === 302 /* JSDocTypeExpression */ ? visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName) + visitNode(cbNode, node.fullName) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) : visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression)); - case 324 /* JSDocCallbackTag */: + visitNode(cbNode, node.typeExpression)) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 328 /* JSDocCallbackTag */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression); - case 327 /* JSDocReturnTag */: - case 329 /* JSDocTypeTag */: - case 328 /* JSDocThisTag */: - case 325 /* JSDocEnumTag */: + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 331 /* JSDocReturnTag */: + case 333 /* JSDocTypeTag */: + case 332 /* JSDocThisTag */: + case 329 /* JSDocEnumTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.typeExpression); - case 313 /* JSDocSignature */: + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 315 /* JSDocSignature */: return ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 312 /* JSDocTypeLiteral */: + case 316 /* JSDocLink */: + return visitNode(cbNode, node.name); + case 314 /* JSDocTypeLiteral */: return ts.forEach(node.jsDocPropertyTags, cbNode); - case 314 /* JSDocTag */: - case 319 /* JSDocClassTag */: - case 320 /* JSDocPublicTag */: - case 321 /* JSDocPrivateTag */: - case 322 /* JSDocProtectedTag */: - case 323 /* JSDocReadonlyTag */: - return visitNode(cbNode, node.tagName); - case 336 /* PartiallyEmittedExpression */: + case 317 /* JSDocTag */: + case 322 /* JSDocClassTag */: + case 323 /* JSDocPublicTag */: + case 324 /* JSDocPrivateTag */: + case 325 /* JSDocProtectedTag */: + case 326 /* JSDocReadonlyTag */: + case 321 /* JSDocDeprecatedTag */: + return visitNode(cbNode, node.tagName) + || (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 340 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -28636,62 +29539,58 @@ var ts; * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure. */ function forEachChildRecursively(rootNode, cbNode, cbNodes) { - var stack = [rootNode]; - while (stack.length) { - var parent = stack.pop(); - var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent)); - if (res) { - return res; - } - } - return; - function gatherPossibleChildren(node) { - var children = []; - forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal - return children; - function addWorkItem(n) { - children.unshift(n); - } - } - function visitAllPossibleChildren(parent, children) { - for (var _i = 0, children_5 = children; _i < children_5.length; _i++) { - var child = children_5[_i]; - if (ts.isArray(child)) { - if (cbNodes) { - var res = cbNodes(child, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - } - for (var i = child.length - 1; i >= 0; i--) { - var realChild = child[i]; - var res = cbNode(realChild, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - stack.push(realChild); - } - } - else { - stack.push(child); - var res = cbNode(child, parent); + var queue = gatherPossibleChildren(rootNode); + var parents = []; // tracks parent references for elements in queue + while (parents.length < queue.length) { + parents.push(rootNode); + } + while (queue.length !== 0) { + var current = queue.pop(); + var parent = parents.pop(); + if (ts.isArray(current)) { + if (cbNodes) { + var res = cbNodes(current, parent); if (res) { if (res === "skip") continue; return res; } } + for (var i = current.length - 1; i >= 0; --i) { + queue.push(current[i]); + parents.push(parent); + } + } + else { + var res = cbNode(current, parent); + if (res) { + if (res === "skip") + continue; + return res; + } + if (current.kind >= 158 /* FirstNode */) { + // add children in reverse order to the queue, so popping gives the first child + for (var _i = 0, _a = gatherPossibleChildren(current); _i < _a.length; _i++) { + var child = _a[_i]; + queue.push(child); + parents.push(current); + } + } } } } ts.forEachChildRecursively = forEachChildRecursively; + function gatherPossibleChildren(node) { + var children = []; + forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal + return children; + function addWorkItem(n) { + children.unshift(n); + } + } function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeParse"); var result; ts.perfLogger.logStartParseSourceFile(fileName); @@ -28704,7 +29603,7 @@ var ts; ts.perfLogger.logStopParseSourceFile(); ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } ts.createSourceFile = createSourceFile; @@ -28886,11 +29785,12 @@ var ts; // attached to the EOF token. var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + var _a; if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); if (scriptKind === 6 /* JSON */) { var result_3 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); - ts.convertToObjectWorker(result_3, result_3.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + ts.convertToObjectWorker(result_3, (_a = result_3.statements[0]) === null || _a === void 0 ? void 0 : _a.expression, result_3.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); result_3.referencedFiles = ts.emptyArray; result_3.typeReferenceDirectives = ts.emptyArray; result_3.libReferenceDirectives = ts.emptyArray; @@ -28930,35 +29830,54 @@ var ts; endOfFileToken = parseTokenNode(); } else { - var expression = void 0; - switch (token()) { - case 22 /* OpenBracketToken */: - expression = parseArrayLiteralExpression(); - break; - case 109 /* TrueKeyword */: - case 94 /* FalseKeyword */: - case 103 /* NullKeyword */: - expression = parseTokenNode(); - break; - case 40 /* MinusToken */: - if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) { - expression = parsePrefixUnaryExpression(); - } - else { - expression = parseObjectLiteralExpression(); - } - break; - case 8 /* NumericLiteral */: - case 10 /* StringLiteral */: - if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) { - expression = parseLiteralNode(); + // Loop and synthesize an ArrayLiteralExpression if there are more than + // one top-level expressions to ensure all input text is consumed. + var expressions = void 0; + while (token() !== 1 /* EndOfFileToken */) { + var expression_1 = void 0; + switch (token()) { + case 22 /* OpenBracketToken */: + expression_1 = parseArrayLiteralExpression(); + break; + case 109 /* TrueKeyword */: + case 94 /* FalseKeyword */: + case 103 /* NullKeyword */: + expression_1 = parseTokenNode(); + break; + case 40 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) { + expression_1 = parsePrefixUnaryExpression(); + } + else { + expression_1 = parseObjectLiteralExpression(); + } break; + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) { + expression_1 = parseLiteralNode(); + break; + } + // falls through + default: + expression_1 = parseObjectLiteralExpression(); + break; + } + // Error recovery: collect multiple top-level expressions + if (expressions && ts.isArray(expressions)) { + expressions.push(expression_1); + } + else if (expressions) { + expressions = [expressions, expression_1]; + } + else { + expressions = expression_1; + if (token() !== 1 /* EndOfFileToken */) { + parseErrorAtCurrentToken(ts.Diagnostics.Unexpected_token); } - // falls through - default: - expression = parseObjectLiteralExpression(); - break; + } } + var expression = ts.isArray(expressions) ? finishNode(factory.createArrayLiteralExpression(expressions), pos) : ts.Debug.checkDefined(expressions); var statement = factory.createExpressionStatement(expression); finishNode(statement, pos); statements = createNodeArray([statement], pos); @@ -29153,7 +30072,7 @@ var ts; return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements)); function containsPossibleTopLevelAwait(node) { return !(node.flags & 32768 /* AwaitContext */) - && !!(node.transformFlags & 8388608 /* ContainsPossibleTopLevelAwait */); + && !!(node.transformFlags & 16777216 /* ContainsPossibleTopLevelAwait */); } function findNextStatementWithAwait(statements, start) { for (var i = start; i < statements.length; i++) { @@ -29194,7 +30113,7 @@ var ts; ts.setTextRangePosWidth(sourceFile, 0, sourceText.length); setExternalModuleIndicator(sourceFile); // If we parsed this as an external module, it may contain top-level await - if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 8388608 /* ContainsPossibleTopLevelAwait */) { + if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 16777216 /* ContainsPossibleTopLevelAwait */) { sourceFile = reparseTopLevelAwait(sourceFile); } sourceFile.text = sourceText; @@ -29565,7 +30484,7 @@ var ts; ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, "", "", /*templateFlags*/ undefined) : kind === 8 /* NumericLiteral */ ? factory.createNumericLiteral("", /*numericLiteralFlags*/ undefined) : kind === 10 /* StringLiteral */ ? factory.createStringLiteral("", /*isSingleQuote*/ undefined) : - kind === 271 /* MissingDeclaration */ ? factory.createMissingDeclaration() : + kind === 272 /* MissingDeclaration */ ? factory.createMissingDeclaration() : factory.createToken(kind); return finishNode(result, pos); } @@ -29580,8 +30499,8 @@ var ts; // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for // each identifier in order to reduce memory consumption. function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) { - identifierCount++; if (isIdentifier) { + identifierCount++; var pos = getNodePos(); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker var originalKeywordKind = token(); @@ -29593,6 +30512,11 @@ var ts; parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); return createIdentifier(/*isIdentifier*/ true); } + if (token() === 0 /* Unknown */ && scanner.tryScan(function () { return scanner.reScanInvalidIdentifier() === 78 /* Identifier */; })) { + // Scanner has already recorded an 'Invalid character' error, so no need to add another from the parser. + return createIdentifier(/*isIdentifier*/ true); + } + identifierCount++; // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; var isReservedWord = scanner.isReservedWord(); @@ -29947,8 +30871,7 @@ var ts; var listPos = getNodePos(); while (!isListTerminator(kind)) { if (isListElement(kind, /*inErrorRecovery*/ false)) { - var element = parseListElement(kind, parseElement); - list.push(element); + list.push(parseListElement(kind, parseElement)); continue; } if (abortParsingListOrMoveToNextToken(kind)) { @@ -30098,14 +31021,14 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 166 /* Constructor */: - case 171 /* IndexSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 163 /* PropertyDeclaration */: - case 229 /* SemicolonClassElement */: + case 167 /* Constructor */: + case 172 /* IndexSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 230 /* SemicolonClassElement */: return true; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. @@ -30120,8 +31043,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: return true; } } @@ -30130,58 +31053,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 232 /* VariableStatement */: - case 230 /* Block */: - case 234 /* IfStatement */: - case 233 /* ExpressionStatement */: - case 246 /* ThrowStatement */: - case 242 /* ReturnStatement */: - case 244 /* SwitchStatement */: - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 237 /* ForStatement */: - case 236 /* WhileStatement */: - case 243 /* WithStatement */: - case 231 /* EmptyStatement */: - case 247 /* TryStatement */: - case 245 /* LabeledStatement */: - case 235 /* DoStatement */: - case 248 /* DebuggerStatement */: - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 252 /* FunctionDeclaration */: + case 233 /* VariableStatement */: + case 231 /* Block */: + case 235 /* IfStatement */: + case 234 /* ExpressionStatement */: + case 247 /* ThrowStatement */: + case 243 /* ReturnStatement */: + case 245 /* SwitchStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 238 /* ForStatement */: + case 237 /* WhileStatement */: + case 244 /* WithStatement */: + case 232 /* EmptyStatement */: + case 248 /* TryStatement */: + case 246 /* LabeledStatement */: + case 236 /* DoStatement */: + case 249 /* DebuggerStatement */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 291 /* EnumMember */; + return node.kind === 292 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 170 /* ConstructSignature */: - case 164 /* MethodSignature */: - case 171 /* IndexSignature */: - case 162 /* PropertySignature */: - case 169 /* CallSignature */: + case 171 /* ConstructSignature */: + case 165 /* MethodSignature */: + case 172 /* IndexSignature */: + case 163 /* PropertySignature */: + case 170 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 249 /* VariableDeclaration */) { + if (node.kind !== 250 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -30202,7 +31125,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 160 /* Parameter */) { + if (node.kind !== 161 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -30483,14 +31406,14 @@ var ts; // If true, we should abort parsing an error function. function typeHasArrowFunctionBlockingParseError(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return ts.nodeIsMissing(node.typeName); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: { + case 175 /* FunctionType */: + case 176 /* ConstructorType */: { var _a = node, parameters = _a.parameters, type = _a.type; return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); } - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return typeHasArrowFunctionBlockingParseError(node.type); default: return false; @@ -30671,19 +31594,21 @@ var ts; function parseParameterWorker(inOuterAwaitContext) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); + // FormalParameter [Yield,Await]: + // BindingElement[?Yield,?Await] + // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. + var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); if (token() === 107 /* ThisKeyword */) { - var node_1 = factory.createParameterDeclaration( - /*decorators*/ undefined, + var node_1 = factory.createParameterDeclaration(decorators, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), /*questionToken*/ undefined, parseTypeAnnotation(), /*initializer*/ undefined); + if (decorators) { + parseErrorAtRange(decorators[0], ts.Diagnostics.Decorators_may_not_be_applied_to_this_parameters); + } return withJSDoc(finishNode(node_1, pos), hasJSDoc); } - // FormalParameter [Yield,Await]: - // BindingElement[?Yield,?Await] - // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. - var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); var savedTopLevel = topLevel; topLevel = false; var modifiers = parseModifiers(); @@ -30770,14 +31695,14 @@ var ts; function parseSignatureMember(kind) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); - if (kind === 170 /* ConstructSignature */) { + if (kind === 171 /* ConstructSignature */) { parseExpected(102 /* NewKeyword */); } var typeParameters = parseTypeParameters(); var parameters = parseParameters(4 /* Type */); var type = parseReturnType(58 /* ColonToken */, /*isType*/ true); parseTypeMemberSemicolon(); - var node = kind === 169 /* CallSignature */ + var node = kind === 170 /* CallSignature */ ? factory.createCallSignature(typeParameters, parameters, type) : factory.createConstructSignature(typeParameters, parameters, type); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -30868,7 +31793,10 @@ var ts; } function isTypeMemberStart() { // Return true if we have the start of a signature member - if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) { + if (token() === 20 /* OpenParenToken */ || + token() === 29 /* LessThanToken */ || + token() === 134 /* GetKeyword */ || + token() === 146 /* SetKeyword */) { return true; } var idToken = false; @@ -30900,14 +31828,20 @@ var ts; } function parseTypeMember() { if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) { - return parseSignatureMember(169 /* CallSignature */); + return parseSignatureMember(170 /* CallSignature */); } if (token() === 102 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(170 /* ConstructSignature */); + return parseSignatureMember(171 /* ConstructSignature */); } var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiers(); + if (parseContextualModifier(134 /* GetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 168 /* GetAccessor */); + } + if (parseContextualModifier(146 /* SetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 169 /* SetAccessor */); + } if (isIndexSignature()) { return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers); } @@ -31940,7 +32874,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand, pos); } function isInOrOfKeyword(t) { - return t === 100 /* InKeyword */ || t === 156 /* OfKeyword */; + return t === 100 /* InKeyword */ || t === 157 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand, pos) { while (true) { @@ -32080,7 +33014,7 @@ var ts; if (token() === 42 /* AsteriskAsteriskToken */) { var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); var end = simpleUnaryExpression.end; - if (simpleUnaryExpression.kind === 206 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 207 /* TypeAssertionExpression */) { parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -32331,7 +33265,7 @@ var ts; var pos = getNodePos(); var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 275 /* JsxOpeningElement */) { + if (opening.kind === 276 /* JsxOpeningElement */) { var children = parseJsxChildren(opening); var closingElement = parseJsxClosingElement(inExpressionContext); if (!tagNamesAreEquivalent(opening.tagName, closingElement.tagName)) { @@ -32339,11 +33273,11 @@ var ts; } result = finishNode(factory.createJsxElement(opening, children, closingElement), pos); } - else if (opening.kind === 278 /* JsxOpeningFragment */) { + else if (opening.kind === 279 /* JsxOpeningFragment */) { result = finishNode(factory.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos); } else { - ts.Debug.assert(opening.kind === 274 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 275 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -32843,10 +33777,10 @@ var ts; var decorators = parseDecorators(); var modifiers = parseModifiers(); if (parseContextualModifier(134 /* GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167 /* GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* GetAccessor */); } if (parseContextualModifier(146 /* SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 169 /* SetAccessor */); } var asteriskToken = parseOptionalToken(41 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); @@ -32964,6 +33898,7 @@ var ts; // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); var openBracePosition = scanner.getTokenPos(); if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { var multiLine = scanner.hasPrecedingLineBreak(); @@ -32974,11 +33909,16 @@ var ts; ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); } } - return finishNode(factory.createBlock(statements, multiLine), pos); + var result = withJSDoc(finishNode(factory.createBlock(statements, multiLine), pos), hasJSDoc); + if (token() === 62 /* EqualsToken */) { + parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses); + nextToken(); + } + return result; } else { var statements = createMissingList(); - return finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos); + return withJSDoc(finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos), hasJSDoc); } } function parseFunctionBlock(flags, diagnosticMessage) { @@ -33005,21 +33945,24 @@ var ts; } function parseEmptyStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(26 /* SemicolonToken */); - return finishNode(factory.createEmptyStatement(), pos); + return withJSDoc(finishNode(factory.createEmptyStatement(), pos), hasJSDoc); } function parseIfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(98 /* IfKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var thenStatement = parseStatement(); var elseStatement = parseOptional(90 /* ElseKeyword */) ? parseStatement() : undefined; - return finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos); + return withJSDoc(finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc); } function parseDoStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(89 /* DoKeyword */); var statement = parseStatement(); parseExpected(114 /* WhileKeyword */); @@ -33031,19 +33974,21 @@ var ts; // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. parseOptional(26 /* SemicolonToken */); - return finishNode(factory.createDoStatement(statement, expression), pos); + return withJSDoc(finishNode(factory.createDoStatement(statement, expression), pos), hasJSDoc); } function parseWhileStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(114 /* WhileKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var statement = parseStatement(); - return finishNode(factory.createWhileStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWhileStatement(expression, statement), pos), hasJSDoc); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(96 /* ForKeyword */); var awaitToken = parseOptionalToken(130 /* AwaitKeyword */); parseExpected(20 /* OpenParenToken */); @@ -33057,7 +34002,7 @@ var ts; } } var node; - if (awaitToken ? parseExpected(156 /* OfKeyword */) : parseOptional(156 /* OfKeyword */)) { + if (awaitToken ? parseExpected(157 /* OfKeyword */) : parseOptional(157 /* OfKeyword */)) { var expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(21 /* CloseParenToken */); node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement()); @@ -33079,33 +34024,36 @@ var ts; parseExpected(21 /* CloseParenToken */); node = factory.createForStatement(initializer, condition, incrementor, parseStatement()); } - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseBreakOrContinueStatement(kind) { var pos = getNodePos(); - parseExpected(kind === 241 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */); + var hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(kind === 242 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */); var label = canParseSemicolon() ? undefined : parseIdentifier(); parseSemicolon(); - var node = kind === 241 /* BreakStatement */ + var node = kind === 242 /* BreakStatement */ ? factory.createBreakStatement(label) : factory.createContinueStatement(label); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseReturnStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(104 /* ReturnKeyword */); var expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression); parseSemicolon(); - return finishNode(factory.createReturnStatement(expression), pos); + return withJSDoc(finishNode(factory.createReturnStatement(expression), pos), hasJSDoc); } function parseWithStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(115 /* WithKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement); - return finishNode(factory.createWithStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWithStatement(expression, statement), pos), hasJSDoc); } function parseCaseClause() { var pos = getNodePos(); @@ -33134,17 +34082,19 @@ var ts; } function parseSwitchStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(106 /* SwitchKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var caseBlock = parseCaseBlock(); - return finishNode(factory.createSwitchStatement(expression, caseBlock), pos); + return withJSDoc(finishNode(factory.createSwitchStatement(expression, caseBlock), pos), hasJSDoc); } function parseThrowStatement() { // ThrowStatement[Yield] : // throw [no LineTerminator here]Expression[In, ?Yield]; var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(108 /* ThrowKeyword */); // Because of automatic semicolon insertion, we need to report error if this // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' @@ -33157,11 +34107,12 @@ var ts; expression = finishNode(factory.createIdentifier(""), getNodePos()); } parseSemicolon(); - return finishNode(factory.createThrowStatement(expression), pos); + return withJSDoc(finishNode(factory.createThrowStatement(expression), pos), hasJSDoc); } // TODO: Review for error recovery function parseTryStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(110 /* TryKeyword */); var tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); var catchClause = token() === 82 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -33172,7 +34123,7 @@ var ts; parseExpected(95 /* FinallyKeyword */); finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } - return finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos); + return withJSDoc(finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); } function parseCatchClause() { var pos = getNodePos(); @@ -33191,9 +34142,10 @@ var ts; } function parseDebuggerStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(86 /* DebuggerKeyword */); parseSemicolon(); - return finishNode(factory.createDebuggerStatement(), pos); + return withJSDoc(finishNode(factory.createDebuggerStatement(), pos), hasJSDoc); } function parseExpressionOrLabeledStatement() { // Avoiding having to do the lookahead for a labeled statement by just trying to parse @@ -33401,9 +34353,9 @@ var ts; case 96 /* ForKeyword */: return parseForOrForInOrForOfStatement(); case 85 /* ContinueKeyword */: - return parseBreakOrContinueStatement(240 /* ContinueStatement */); + return parseBreakOrContinueStatement(241 /* ContinueStatement */); case 80 /* BreakKeyword */: - return parseBreakOrContinueStatement(241 /* BreakStatement */); + return parseBreakOrContinueStatement(242 /* BreakStatement */); case 104 /* ReturnKeyword */: return parseReturnStatement(); case 115 /* WithKeyword */: @@ -33523,7 +34475,7 @@ var ts; if (decorators || modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - var missing = createMissingNode(271 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var missing = createMissingNode(272 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); ts.setTextRangePos(missing, pos); missing.decorators = decorators; missing.modifiers = modifiers; @@ -33605,6 +34557,7 @@ var ts; } function parseVariableDeclaration(allowExclamation) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); var name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations); var exclamationToken; if (allowExclamation && name.kind === 78 /* Identifier */ && @@ -33614,7 +34567,7 @@ var ts; var type = parseTypeAnnotation(); var initializer = isInOrOfKeyword(token()) ? undefined : parseInitializer(); var node = factory.createVariableDeclaration(name, exclamationToken, type, initializer); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseVariableDeclarationList(inForStatementInitializer) { var pos = getNodePos(); @@ -33642,7 +34595,7 @@ var ts; // this context. // The checker will then give an error that there is an empty declaration list. var declarations; - if (token() === 156 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 157 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { declarations = createMissingList(); } else { @@ -33746,12 +34699,12 @@ var ts; var parameters = parseParameters(0 /* None */); var type = parseReturnType(58 /* ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(0 /* None */); - var node = kind === 167 /* GetAccessor */ + var node = kind === 168 /* GetAccessor */ ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body); // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors node.typeParameters = typeParameters; - if (type && node.kind === 168 /* SetAccessor */) + if (type && node.kind === 169 /* SetAccessor */) node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -33894,10 +34847,10 @@ var ts; var decorators = parseDecorators(); var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); if (parseContextualModifier(134 /* GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167 /* GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* GetAccessor */); } if (parseContextualModifier(146 /* SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 169 /* SetAccessor */); } if (token() === 132 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) { var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers); @@ -33936,10 +34889,10 @@ var ts; return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, 221 /* ClassExpression */); + return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, 222 /* ClassExpression */); } function parseClassDeclaration(pos, hasJSDoc, decorators, modifiers) { - return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 252 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 253 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, kind) { var savedAwaitContext = inAwaitContext(); @@ -33961,7 +34914,7 @@ var ts; members = createMissingList(); } setAwaitContext(savedAwaitContext); - var node = kind === 252 /* ClassDeclaration */ + var node = kind === 253 /* ClassDeclaration */ ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -34200,7 +35153,7 @@ var ts; var namedBindings; if (!identifier || parseOptional(27 /* CommaToken */)) { - namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(264 /* NamedImports */); + namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(265 /* NamedImports */); } return finishNode(factory.createImportClause(isTypeOnly, identifier, namedBindings), pos); } @@ -34248,16 +35201,16 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - var node = kind === 264 /* NamedImports */ + var node = kind === 265 /* NamedImports */ ? factory.createNamedImports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseImportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */)) : factory.createNamedExports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */)); return finishNode(node, pos); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(270 /* ExportSpecifier */); + return parseImportOrExportSpecifier(271 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(265 /* ImportSpecifier */); + return parseImportOrExportSpecifier(266 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var pos = getNodePos(); @@ -34284,10 +35237,10 @@ var ts; else { name = identifierName; } - if (kind === 265 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 266 /* ImportSpecifier */ && checkIdentifierIsKeyword) { parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } - var node = kind === 265 /* ImportSpecifier */ + var node = kind === 266 /* ImportSpecifier */ ? factory.createImportSpecifier(propertyName, name) : factory.createExportSpecifier(propertyName, name); return finishNode(node, pos); @@ -34310,7 +35263,7 @@ var ts; moduleSpecifier = parseModuleSpecifier(); } else { - exportClause = parseNamedImportsOrExports(268 /* NamedExports */); + exportClause = parseNamedImportsOrExports(269 /* NamedExports */); // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. @@ -34499,7 +35452,10 @@ var ts; var tags; var tagsPos; var tagsEnd; + var linkEnd; + var commentsPos; var comments = []; + var parts = []; // + 3 for leading /**, - 5 in total for /** */ return scanner.scanRange(start + 3, length - 5, function () { // Initially we can parse out a tag. We also have seen a starting asterisk. @@ -34528,6 +35484,8 @@ var ts; case 59 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingWhitespace(comments); + if (!commentsPos) + commentsPos = getNodePos(); addTag(parseTag(indent)); // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning @@ -34570,6 +35528,22 @@ var ts; break; case 1 /* EndOfFileToken */: break loop; + case 18 /* OpenBraceToken */: + state = 2 /* SavingComments */; + var commentEnd = scanner.getStartPos(); + var linkStart = scanner.getTextPos() - 1; + var link = parseJSDocLink(linkStart); + if (link) { + if (!linkEnd) { + removeLeadingNewlines(comments); + } + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : start, commentEnd)); + parts.push(link); + comments = []; + linkEnd = scanner.getTextPos(); + break; + } + // fallthrough if it's not a {@link sequence default: // 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 @@ -34580,9 +35554,14 @@ var ts; } nextTokenJSDoc(); } - removeLeadingNewlines(comments); removeTrailingWhitespace(comments); - return createJSDocComment(); + if (parts.length && comments.length) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : start, commentsPos)); + } + if (parts.length && tags) + ts.Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); + var tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); + return finishNode(factory.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : comments.length ? comments.join("") : undefined, tagsArray), start, end); }); function removeLeadingNewlines(comments) { while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { @@ -34594,11 +35573,6 @@ var ts; comments.pop(); } } - function createJSDocComment() { - var comment = comments.length ? comments.join("") : undefined; - var tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); - return finishNode(factory.createJSDocComment(comment, tagsArray), start, end); - } function isNextNonwhitespaceTokenEndOfFile() { // We must use infinite lookahead, as there could be any number of newlines :( while (true) { @@ -34678,6 +35652,9 @@ var ts; case "readonly": tag = parseSimpleTag(start, factory.createJSDocReadonlyTag, tagName, margin, indentText); break; + case "override": + tag = parseSimpleTag(start, factory.createJSDocOverrideTag, tagName, margin, indentText); + break; case "deprecated": hasDeprecatedTag = true; tag = parseSimpleTag(start, factory.createJSDocDeprecatedTag, tagName, margin, indentText); @@ -34725,8 +35702,12 @@ var ts; return parseTagComments(margin, indentText.slice(margin)); } function parseTagComments(indent, initialMargin) { + var commentsPos = getNodePos(); var comments = []; + var parts = []; + var linkEnd; var state = 0 /* BeginningOfLine */; + var previousWhitespace = true; var margin; function pushComment(text) { if (!margin) { @@ -34752,7 +35733,9 @@ var ts; indent = 0; break; case 59 /* AtToken */: - if (state === 3 /* SavingBackticks */) { + if (state === 3 /* SavingBackticks */ + || state === 2 /* SavingComments */ && (!previousWhitespace || lookAhead(isNextJSDocTokenWhitespace))) { + // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace or not before whitespace comments.push(scanner.getTokenText()); break; } @@ -34776,13 +35759,18 @@ var ts; break; case 18 /* OpenBraceToken */: state = 2 /* SavingComments */; - if (lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) { - pushComment(scanner.getTokenText()); - nextTokenJSDoc(); + var commentEnd = scanner.getStartPos(); + var linkStart = scanner.getTextPos() - 1; + var link = parseJSDocLink(linkStart); + if (link) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : commentsPos, commentEnd)); + parts.push(link); + comments = []; + linkEnd = scanner.getTextPos(); + } + else { pushComment(scanner.getTokenText()); - nextTokenJSDoc(); } - pushComment(scanner.getTokenText()); break; case 61 /* BacktickToken */: if (state === 3 /* SavingBackticks */) { @@ -34809,15 +35797,51 @@ var ts; pushComment(scanner.getTokenText()); break; } + previousWhitespace = token() === 5 /* WhitespaceTrivia */; tok = nextTokenJSDoc(); } removeLeadingNewlines(comments); removeTrailingWhitespace(comments); - return comments.length === 0 ? undefined : comments.join(""); + if (parts.length) { + if (comments.length) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : commentsPos)); + } + return createNodeArray(parts, commentsPos, scanner.getTextPos()); + } + else if (comments.length) { + return comments.join(""); + } + } + function isNextJSDocTokenWhitespace() { + var next = nextTokenJSDoc(); + return next === 5 /* WhitespaceTrivia */ || next === 4 /* NewLineTrivia */; + } + function parseJSDocLink(start) { + if (!tryParse(parseJSDocLinkPrefix)) { + return undefined; + } + nextTokenJSDoc(); // start at token after link, then skip any whitespace + skipWhitespace(); + // parseEntityName logs an error for non-identifier, so create a MissingNode ourselves to avoid the error + var name = ts.tokenIsIdentifierOrKeyword(token()) + ? parseEntityName(/*allowReservedWords*/ true) + : undefined; + var text = []; + while (token() !== 19 /* CloseBraceToken */ && token() !== 4 /* NewLineTrivia */ && token() !== 1 /* EndOfFileToken */) { + text.push(scanner.getTokenText()); + nextTokenJSDoc(); + } + return finishNode(factory.createJSDocLink(name, text.join("")), start, scanner.getTextPos()); + } + function parseJSDocLinkPrefix() { + skipWhitespaceOrAsterisk(); + return token() === 18 /* OpenBraceToken */ + && nextTokenJSDoc() === 59 /* AtToken */ + && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) + && scanner.getTokenValue() === "link"; } function parseUnknownTag(start, tagName, indent, indentText) { - var end = getNodePos(); - return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function addTag(tag) { if (!tag) { @@ -34862,7 +35886,7 @@ var ts; switch (node.kind) { case 145 /* ObjectKeyword */: return true; - case 178 /* ArrayType */: + case 179 /* ArrayType */: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments; @@ -34873,11 +35897,11 @@ var ts; var isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; - skipWhitespace(); - if (isNameFirst) { + var indentText = skipWhitespaceOrAsterisk(); + if (isNameFirst && !lookAhead(parseJSDocLinkPrefix)) { typeExpression = tryParseTypeExpression(); } - var comment = parseTagComments(indent + scanner.getStartPos() - start); + var comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; @@ -34894,12 +35918,12 @@ var ts; var child = void 0; var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { - if (child.kind === 326 /* JSDocParameterTag */ || child.kind === 333 /* JSDocPropertyTag */) { + if (child.kind === 330 /* JSDocParameterTag */ || child.kind === 337 /* JSDocPropertyTag */) { children = ts.append(children, child); } } if (children) { - var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 178 /* ArrayType */), pos); + var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 179 /* ArrayType */), pos); return finishNode(factory.createJSDocTypeExpression(literal), pos); } } @@ -34909,27 +35933,34 @@ var ts; parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeExpression = tryParseTypeExpression(); - var end = getNodePos(); - return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function parseTypeTag(start, tagName, indent, indentText) { if (ts.some(tags, ts.isJSDocTypeTag)) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); - var end = getNodePos(); - var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined; - return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start, end); + var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; + return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start); } function parseSeeTag(start, tagName, indent, indentText) { - var nameExpression = parseJSDocNameReference(); - var end = getNodePos(); - var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined; - return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start, end); + var isLink = lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; }); + var nameExpression = isLink ? undefined : parseJSDocNameReference(); + var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; + return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start); } function parseAuthorTag(start, tagName, indent, indentText) { - var comments = parseAuthorNameAndEmail() + (parseTrailingTagComments(start, end, indent, indentText) || ""); - return finishNode(factory.createJSDocAuthorTag(tagName, comments || undefined), start); + var commentStart = getNodePos(); + var textOnly = parseAuthorNameAndEmail(); + var commentEnd = scanner.getStartPos(); + var comments = parseTrailingTagComments(start, commentEnd, indent, indentText); + if (!comments) { + commentEnd = scanner.getStartPos(); + } + var allParts = typeof comments !== "string" + ? createNodeArray(ts.concatenate([finishNode(textOnly, commentStart, commentEnd)], comments), commentStart) // cast away readonly + : textOnly.text + comments; + return finishNode(factory.createJSDocAuthorTag(tagName, allParts), start); } function parseAuthorNameAndEmail() { var comments = []; @@ -34950,17 +35981,15 @@ var ts; comments.push(scanner.getTokenText()); token = nextTokenJSDoc(); } - return comments.join(""); + return factory.createJSDocText(comments.join("")); } function parseImplementsTag(start, tagName, margin, indentText) { var className = parseExpressionWithTypeArgumentsForAugments(); - var end = getNodePos(); - return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseAugmentsTag(start, tagName, margin, indentText) { var className = parseExpressionWithTypeArgumentsForAugments(); - var end = getNodePos(); - return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseExpressionWithTypeArgumentsForAugments() { var usedBrace = parseOptional(18 /* OpenBraceToken */); @@ -34984,20 +36013,17 @@ var ts; return node; } function parseSimpleTag(start, createTag, tagName, margin, indentText) { - var end = getNodePos(); - return finishNode(createTag(tagName, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(createTag(tagName, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseThisTag(start, tagName, margin, indentText) { var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); - var end = getNodePos(); - return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseEnumTag(start, tagName, margin, indentText) { var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); - var end = getNodePos(); - return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseTypedefTag(start, tagName, indent, indentText) { var _a; @@ -35014,7 +36040,7 @@ var ts; var hasChildren = false; while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { hasChildren = true; - if (child.kind === 329 /* JSDocTypeTag */) { + if (child.kind === 333 /* JSDocTypeTag */) { if (childTypeTag) { parseErrorAtCurrentToken(ts.Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags); var lastError = ts.lastOrUndefined(parseDiagnostics); @@ -35032,7 +36058,7 @@ var ts; } } if (hasChildren) { - var isArrayType = typeExpression && typeExpression.type.kind === 178 /* ArrayType */; + var isArrayType = typeExpression && typeExpression.type.kind === 179 /* ArrayType */; var jsdocTypeLiteral = factory.createJSDocTypeLiteral(jsDocPropertyTags, isArrayType); typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : @@ -35085,17 +36111,16 @@ var ts; var returnTag = tryParse(function () { if (parseOptionalJsdoc(59 /* AtToken */)) { var tag = parseTag(indent); - if (tag && tag.kind === 327 /* JSDocReturnTag */) { + if (tag && tag.kind === 331 /* JSDocReturnTag */) { return tag; } } }); var typeExpression = finishNode(factory.createJSDocSignature(/*typeParameters*/ undefined, parameters, returnTag), start); - var end = getNodePos(); if (!comment) { - comment = parseTrailingTagComments(start, end, indent, indentText); + comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); } - return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start, end); + return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start); } function escapedTextsEqual(a, b) { while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { @@ -35120,7 +36145,7 @@ var ts; case 59 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target, indent); - if (child && (child.kind === 326 /* JSDocParameterTag */ || child.kind === 333 /* JSDocPropertyTag */) && + if (child && (child.kind === 330 /* JSDocParameterTag */ || child.kind === 337 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -35177,6 +36202,9 @@ var ts; function parseTemplateTagTypeParameter() { var typeParameterPos = getNodePos(); var name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); + if (ts.nodeIsMissing(name)) { + return undefined; + } return finishNode(factory.createTypeParameterDeclaration(name, /*constraint*/ undefined, /*defaultType*/ undefined), typeParameterPos); } function parseTemplateTagTypeParameters() { @@ -35184,7 +36212,10 @@ var ts; var typeParameters = []; do { skipWhitespace(); - typeParameters.push(parseTemplateTagTypeParameter()); + var node = parseTemplateTagTypeParameter(); + if (node !== undefined) { + typeParameters.push(node); + } skipWhitespaceOrAsterisk(); } while (parseOptionalJsdoc(27 /* CommaToken */)); return createNodeArray(typeParameters, pos); @@ -35203,8 +36234,7 @@ var ts; // TODO: Consider only parsing a single type parameter if there is a constraint. var constraint = token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; var typeParameters = parseTemplateTagTypeParameters(); - var end = getNodePos(); - return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function parseOptionalJsdoc(t) { if (token() === t) { @@ -36019,6 +37049,7 @@ var ts; ["es2018", "lib.es2018.d.ts"], ["es2019", "lib.es2019.d.ts"], ["es2020", "lib.es2020.d.ts"], + ["es2021", "lib.es2021.d.ts"], ["esnext", "lib.esnext.d.ts"], // Host only ["dom", "lib.dom.d.ts"], @@ -36058,14 +37089,17 @@ var ts; ["es2020.string", "lib.es2020.string.d.ts"], ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"], ["es2020.intl", "lib.es2020.intl.d.ts"], + ["es2021.promise", "lib.es2021.promise.d.ts"], + ["es2021.string", "lib.es2021.string.d.ts"], + ["es2021.weakref", "lib.es2021.weakref.d.ts"], ["esnext.array", "lib.es2019.array.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"], ["esnext.intl", "lib.esnext.intl.d.ts"], ["esnext.bigint", "lib.es2020.bigint.d.ts"], - ["esnext.string", "lib.esnext.string.d.ts"], - ["esnext.promise", "lib.esnext.promise.d.ts"], - ["esnext.weakref", "lib.esnext.weakref.d.ts"] + ["esnext.string", "lib.es2021.string.d.ts"], + ["esnext.promise", "lib.es2021.promise.d.ts"], + ["esnext.weakref", "lib.es2021.weakref.d.ts"] ]; /** * An array of supported "lib" reference file names used to determine the order for inclusion @@ -36089,11 +37123,12 @@ var ts; fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval, prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval, dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling, + fixedchunksizepolling: ts.WatchFileKind.FixedChunkSizePolling, usefsevents: ts.WatchFileKind.UseFsEvents, usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory, })), category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory, + description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling_UseFsEvents_UseFsEventsOnParentDirectory, }, { name: "watchDirectory", @@ -36101,9 +37136,10 @@ var ts; usefsevents: ts.WatchDirectoryKind.UseFsEvents, fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval, dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling, + fixedchunksizepolling: ts.WatchDirectoryKind.FixedChunkSizePolling, })), category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling, + description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling, }, { name: "fallbackPolling", @@ -36111,9 +37147,10 @@ var ts; fixedinterval: ts.PollingWatchKind.FixedInterval, priorityinterval: ts.PollingWatchKind.PriorityInterval, dynamicpriority: ts.PollingWatchKind.DynamicPriority, + fixedchunksize: ts.PollingWatchKind.FixedChunkSize, })), category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority, + description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority_FixedChunkSize, }, { name: "synchronousWatchDirectory", @@ -36272,6 +37309,7 @@ var ts; es2018: 5 /* ES2018 */, es2019: 6 /* ES2019 */, es2020: 7 /* ES2020 */, + es2021: 8 /* ES2021 */, esnext: 99 /* ESNext */, })), affectsSourceFile: true, @@ -36280,10 +37318,10 @@ var ts; paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT, }; - /* @internal */ - ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsWithoutBuild = [ + // CommandLine only options { name: "all", type: "boolean", @@ -36646,6 +37684,14 @@ var ts; category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Include_undefined_in_index_signature_results }, + { + name: "noImplicitOverride", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier + }, { name: "noPropertyAccessFromIndexSignature", type: "boolean", @@ -37061,7 +38107,9 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins }, - ]); + ]; + /* @internal */ + ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsWithoutBuild); /* @internal */ ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); /* @internal */ @@ -37076,8 +38124,7 @@ var ts; ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) { return ts.hasProperty(option, "transpileOptionValue"); }); - /* @internal */ - ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsOnlyBuild = [ { name: "verbose", shortName: "v", @@ -37105,7 +38152,9 @@ var ts; description: ts.Diagnostics.Delete_the_outputs_of_all_projects, type: "boolean" } - ]); + ]; + /* @internal */ + ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsOnlyBuild); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -37159,6 +38208,10 @@ var ts; return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations)); } ts.getOptionsNameMap = getOptionsNameMap; + var compilerOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_only_be_used_with_build, + getOptionsNameMap: getBuildOptionsNameMap + }; /* @internal */ ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, @@ -37220,6 +38273,10 @@ var ts; return option.name; } function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) { + var _a; + if ((_a = diagnostics.alternateMode) === null || _a === void 0 ? void 0 : _a.getOptionsNameMap().optionsNameMap.has(unknownOption.toLowerCase())) { + return createDiagnostics(diagnostics.alternateMode.diagnostic, unknownOption); + } var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName); return possibleOption ? createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : @@ -37374,6 +38431,7 @@ var ts; } /*@internal*/ ts.compilerOptionsDidYouMeanDiagnostics = { + alternateMode: compilerOptionsAlternateMode, getOptionsNameMap: getOptionsNameMap, optionDeclarations: ts.optionDeclarations, unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, @@ -37406,7 +38464,12 @@ var ts; function getBuildOptionsNameMap() { return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts)); } + var buildOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_not_be_used_with_build, + getOptionsNameMap: getOptionsNameMap + }; var buildOptionsDidYouMeanDiagnostics = { + alternateMode: buildOptionsAlternateMode, getOptionsNameMap: getBuildOptionsNameMap, optionDeclarations: ts.buildOpts, unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0, @@ -37482,7 +38545,7 @@ var ts; function parseConfigFileTextToJson(fileName, jsonText) { var jsonSourceFile = ts.parseJsonText(fileName, jsonText); return { - config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + config: convertConfigFileToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics, /*reportOptionsErrors*/ false, /*optionsIterator*/ undefined), error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined }; } @@ -37612,11 +38675,31 @@ var ts; } return _tsconfigRootOptions; } + function convertConfigFileToObject(sourceFile, errors, reportOptionsErrors, optionsIterator) { + var _a; + var rootExpression = (_a = sourceFile.statements[0]) === null || _a === void 0 ? void 0 : _a.expression; + var knownRootOptions = reportOptionsErrors ? getTsconfigRootOptionsMap() : undefined; + if (rootExpression && rootExpression.kind !== 201 /* ObjectLiteralExpression */) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, rootExpression, ts.Diagnostics.The_root_value_of_a_0_file_must_be_an_object, ts.getBaseFileName(sourceFile.fileName) === "jsconfig.json" ? "jsconfig.json" : "tsconfig.json")); + // Last-ditch error recovery. Somewhat useful because the JSON parser will recover from some parse errors by + // synthesizing a top-level array literal expression. There's a reasonable chance the first element of that + // array is a well-formed configuration object, made into an array element by stray characters. + if (ts.isArrayLiteralExpression(rootExpression)) { + var firstObject = ts.find(rootExpression.elements, ts.isObjectLiteralExpression); + if (firstObject) { + return convertToObjectWorker(sourceFile, firstObject, errors, /*returnValue*/ true, knownRootOptions, optionsIterator); + } + } + return {}; + } + return convertToObjectWorker(sourceFile, rootExpression, errors, /*returnValue*/ true, knownRootOptions, optionsIterator); + } /** * Convert the json syntax tree into the json value */ function convertToObject(sourceFile, errors) { - return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + var _a; + return convertToObjectWorker(sourceFile, (_a = sourceFile.statements[0]) === null || _a === void 0 ? void 0 : _a.expression, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); } ts.convertToObject = convertToObject; /** @@ -37625,18 +38708,18 @@ var ts; * Otherwise it just checks the errors and returns undefined */ /*@internal*/ - function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { - if (!sourceFile.statements.length) { + function convertToObjectWorker(sourceFile, rootExpression, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!rootExpression) { return returnValue ? {} : undefined; } - return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + return convertPropertyValueToJson(rootExpression, knownRootOptions); function isRootOptionMap(knownOptions) { return knownRootOptions && knownRootOptions.elementOptions === knownOptions; } function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) { var result = returnValue ? {} : undefined; var _loop_4 = function (element) { - if (element.kind !== 288 /* PropertyAssignment */) { + if (element.kind !== 289 /* PropertyAssignment */) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); return "continue"; } @@ -37730,13 +38813,13 @@ var ts; case 8 /* NumericLiteral */: reportInvalidOptionValue(option && option.type !== "number"); return validateValue(Number(valueExpression.text)); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { break; // not valid JSON syntax } reportInvalidOptionValue(option && option.type !== "number"); return validateValue(-Number(valueExpression.operand.text)); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; // Currently having element option declaration in the tsconfig with type "object" @@ -37753,7 +38836,7 @@ var ts; return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined)); } - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: reportInvalidOptionValue(option && option.type !== "list"); return validateValue(convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element)); } @@ -38301,14 +39384,14 @@ var ts; if (ownConfig.extendedConfigPath) { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, resolutionStack, errors, extendedConfigCache); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { var baseRaw_1 = extendedConfig.raw; var raw_1 = ownConfig.raw; + var relativeDifference_1; var setPropertyInRawIfNotUndefined = function (propertyName) { - var value = raw_1[propertyName] || baseRaw_1[propertyName]; - if (value) { - raw_1[propertyName] = value; + if (!raw_1[propertyName] && baseRaw_1[propertyName]) { + raw_1[propertyName] = ts.map(baseRaw_1[propertyName], function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1 || (relativeDifference_1 = ts.convertToRelativePath(ts.getDirectoryPath(ownConfig.extendedConfigPath), basePath, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames))), path); }); } }; setPropertyInRawIfNotUndefined("include"); @@ -38390,7 +39473,7 @@ var ts; } } }; - var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); + var json = convertConfigFileToObject(sourceFile, errors, /*reportOptionsErrors*/ true, optionsIterator); if (!typeAcquisition) { if (typingOptionstypeAcquisition) { typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? @@ -38428,7 +39511,7 @@ var ts; errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig)); return undefined; } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) { + function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache) { var _a; var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath); var value; @@ -38440,22 +39523,7 @@ var ts; else { extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (!extendedResult.parseDiagnostics.length) { - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); - if (isSuccessfulParsedTsconfig(extendedConfig)) { - // Update the paths to reflect base path - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); - var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; - var mapPropertiesInRawIfNotUndefined = function (propertyName) { - if (raw_2[propertyName]) { - raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); - } - }; - var raw_2 = extendedConfig.raw; - mapPropertiesInRawIfNotUndefined("include"); - mapPropertiesInRawIfNotUndefined("exclude"); - mapPropertiesInRawIfNotUndefined("files"); - } + extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, ts.getDirectoryPath(extendedConfigPath), ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); } if (extendedConfigCache) { extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig }); @@ -39152,13 +40220,24 @@ var ts; * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache) { var traceEnabled = isTraceEnabled(options, host); if (redirectedReference) { options = redirectedReference.commandLine.options; } - var failedLookupLocations = []; - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var containingDirectory = containingFile ? ts.getDirectoryPath(containingFile) : undefined; + var perFolderCache = containingDirectory ? cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference) : undefined; + var result = perFolderCache && perFolderCache.get(typeReferenceDirectiveName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile); + if (redirectedReference) + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + trace(host, ts.Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory); + traceResult(result); + } + return result; + } var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -39181,6 +40260,8 @@ var ts; trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); } } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -39191,17 +40272,31 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); - if (traceEnabled) { - if (packageId) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, ts.packageIdToString(packageId), primary); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); - } + resolvedTypeReferenceDirective = { + primary: primary, + resolvedFileName: resolvedFileName, + originalPath: fileName === resolvedFileName ? undefined : fileName, + packageId: packageId, + isExternalLibraryImport: pathContainsNodeModules(fileName), + }; + } + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, result); + if (traceEnabled) + traceResult(result); + return result; + function traceResult(result) { + var _a; + if (!((_a = result.resolvedTypeReferenceDirective) === null || _a === void 0 ? void 0 : _a.resolvedFileName)) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + else if (result.resolvedTypeReferenceDirective.packageId) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, ts.packageIdToString(result.resolvedTypeReferenceDirective.packageId), result.resolvedTypeReferenceDirective.primary); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, result.resolvedTypeReferenceDirective.primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } - return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { // Check primary library paths if (typeRoots && typeRoots.length) { @@ -39231,20 +40326,16 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = void 0; + var result_4; if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); - result = searchResult && searchResult.value; + result_4 = searchResult && searchResult.value; } else { var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; - result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); - } - var resolvedFile = resolvedTypeScriptOnly(result); - if (!resolvedFile && traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + result_4 = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); } - return resolvedFile; + return resolvedTypeScriptOnly(result_4); } else { if (traceEnabled) { @@ -39299,22 +40390,21 @@ var ts; return result; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; - function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) { - return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName); - } - ts.createModuleResolutionCache = createModuleResolutionCache; /*@internal*/ function createCacheWithRedirects(options) { var ownMap = new ts.Map(); var redirectsMap = new ts.Map(); return { - ownMap: ownMap, + getOwnMap: getOwnMap, redirectsMap: redirectsMap, getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, clear: clear, setOwnOptions: setOwnOptions, setOwnMap: setOwnMap }; + function getOwnMap() { + return ownMap; + } function setOwnOptions(newOptions) { options = newOptions; } @@ -39340,26 +40430,88 @@ var ts; } } ts.createCacheWithRedirects = createCacheWithRedirects; - /*@internal*/ - function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { - return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap }; + function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { + var cache; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear }; + function getPackageJsonInfo(packageJsonPath) { + return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); + } + function setPackageJsonInfo(packageJsonPath, info) { + (cache || (cache = new ts.Map())).set(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info); + } + function clear() { + cache = undefined; + } + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + function updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + if (!options.configFile) + return; + if (directoryToModuleNameMap.redirectsMap.size === 0) { + // The own map will be for projectCompilerOptions + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size === 0); + ts.Debug.assert(directoryToModuleNameMap.getOwnMap().size === 0); + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.getOwnMap().size === 0); + directoryToModuleNameMap.redirectsMap.set(options.configFile.path, directoryToModuleNameMap.getOwnMap()); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.redirectsMap.set(options.configFile.path, moduleNameToDirectoryMap.getOwnMap()); + } + else { + // Set correct own map + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size > 0); + var ref = { + sourceFile: options.configFile, + commandLine: { options: options } + }; + directoryToModuleNameMap.setOwnMap(directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnMap(moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); + } + directoryToModuleNameMap.setOwnOptions(options); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnOptions(options); + } + function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap) { + return { + getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, + clear: clear, + update: update, + }; + function clear() { + directoryToModuleNameMap.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap); + } function getOrCreateCacheForDirectory(directoryName, redirectedReference) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, function () { return new ts.Map(); }); } + } + function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + moduleNameToDirectoryMap || (moduleNameToDirectoryMap = createCacheWithRedirects(options)); + var packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName); + return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, + clear: clear, + update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; } }); + function clear() { + preDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + packageJsonInfoCache.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); + } function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); } - function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { - var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); - var result = cache.get(key); - if (!result) { - result = create(); - cache.set(key, result); - } - return result; - } function createPerModuleNameCache() { var directoryPathMap = new ts.Map(); return { get: get, set: set }; @@ -39426,7 +40578,17 @@ var ts; } } } - ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + ts.createModuleResolutionCache = createModuleResolutionCache; + function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { + var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); + return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + function clear() { + preDirectoryResolutionCache.clear(); + packageJsonInfoCache.clear(); + } + } + ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache) { var containingDirectory = ts.getDirectoryPath(containingFile); var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); @@ -39704,7 +40866,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, state.resultFromCache); function tryResolve(extensions) { @@ -39764,7 +40926,7 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { - var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined; return withPackageId(packageInfo, resolvedFromFile); } @@ -39797,8 +40959,9 @@ var ts; * For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo" * For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo" */ + /* @internal */ function parseNodeModuleFromPath(resolved) { - var path = ts.normalizePath(resolved.path); + var path = ts.normalizePath(resolved); var idx = path.lastIndexOf(ts.nodeModulesPathPart); if (idx === -1) { return undefined; @@ -39810,6 +40973,7 @@ var ts; } return path.slice(0, indexAfterPackageName); } + ts.parseNodeModuleFromPath = parseNodeModuleFromPath; function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; @@ -39893,21 +41057,43 @@ var ts; return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { + var _a, _b, _c; var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); + if (onlyRecordFailures) { + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + var existing = (_a = state.packageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfo(packageJsonPath); + if (existing !== undefined) { + if (typeof existing !== "boolean") { + if (traceEnabled) + trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + return existing; + } + else { + if (existing && traceEnabled) + trace(host, ts.Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + } + var directoryExists = ts.directoryProbablyExists(packageDirectory, host); if (directoryExists && host.fileExists(packageJsonPath)) { var packageJsonContent = ts.readJson(packageJsonPath, host); if (traceEnabled) { trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); - return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + return result; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + (_c = state.packageJsonInfoCache) === null || _c === void 0 ? void 0 : _c.setPackageJsonInfo(packageJsonPath, directoryExists); // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results state.failedLookupLocations.push(packageJsonPath); } @@ -40156,7 +41342,7 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath @@ -40197,13 +41383,13 @@ var ts; * This is the minumum code needed to expose that functionality; the rest is in the host. */ /* @internal */ - function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache, packageJsonInfoCache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache); } @@ -40249,26 +41435,26 @@ var ts; // A module is uninstantiated if it contains only switch (node.kind) { // 1. interface declarations, type alias declarations - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return 0 /* NonInstantiated */; // 2. const enum declarations - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: if (ts.isEnumConst(node)) { return 2 /* ConstEnumOnly */; } break; // 3. non-exported import declarations - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: if (!(ts.hasSyntacticModifier(node, 1 /* Export */))) { return 0 /* NonInstantiated */; } break; // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: var exportDeclaration = node; - if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 268 /* NamedExports */) { + if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 269 /* NamedExports */) { var state = 0 /* NonInstantiated */; for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; @@ -40284,7 +41470,7 @@ var ts; } break; // 5. other uninstantiated module declarations. - case 257 /* ModuleBlock */: { + case 258 /* ModuleBlock */: { var state_1 = 0 /* NonInstantiated */; ts.forEachChild(node, function (n) { var childState = getModuleInstanceStateCached(n, visited); @@ -40306,7 +41492,7 @@ var ts; }); return state_1; } - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return getModuleInstanceState(node, visited); case 78 /* Identifier */: // Only jsdoc typedef definition can exist in jsdoc namespace, and it should @@ -40378,14 +41564,14 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { - ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); ts.performance.measure("Bind", "beforeBind", "afterBind"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -40424,6 +41610,7 @@ var ts; var classifiableNames; var unreachableFlow = { flags: 1 /* Unreachable */ }; var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; + var bindBinaryExpressionFlow = createBindBinaryExpressionFlow(); /** * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) @@ -40506,7 +41693,7 @@ var ts; // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { - if (node.kind === 266 /* ExportAssignment */) { + if (node.kind === 267 /* ExportAssignment */) { return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; } var name = ts.getNameOfDeclaration(node); @@ -40515,7 +41702,7 @@ var ts; var moduleName = ts.getTextOfIdentifierOrLiteral(name); return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); } - if (name.kind === 158 /* ComputedPropertyName */) { + if (name.kind === 159 /* ComputedPropertyName */) { var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteralLike(nameExpression)) { @@ -40524,11 +41711,9 @@ var ts; if (ts.isSignedNumericLiteral(nameExpression)) { return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text; } - ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); - return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - if (ts.isWellKnownSymbolSyntactically(name)) { - return ts.getPropertyNameForKnownSymbolName(ts.idText(name.name)); + else { + ts.Debug.fail("Only computed properties with literal names have declaration names"); + } } if (ts.isPrivateIdentifier(name)) { // containingClass exists because private names only allowed inside classes @@ -40543,36 +41728,36 @@ var ts; return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return "__constructor" /* Constructor */; - case 174 /* FunctionType */: - case 169 /* CallSignature */: - case 313 /* JSDocSignature */: + case 175 /* FunctionType */: + case 170 /* CallSignature */: + case 315 /* JSDocSignature */: return "__call" /* Call */; - case 175 /* ConstructorType */: - case 170 /* ConstructSignature */: + case 176 /* ConstructorType */: + case 171 /* ConstructSignature */: return "__new" /* New */; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: return "__index" /* Index */; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return "__export" /* ExportStar */; - case 297 /* SourceFile */: + case 298 /* SourceFile */: // json file should behave as // module.exports = ... return "export=" /* ExportEquals */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); - case 160 /* Parameter */: + case 161 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 308 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + ts.Debug.assert(node.parent.kind === 309 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -40672,7 +41857,7 @@ var ts; // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if (symbol.declarations && symbol.declarations.length && - (node.kind === 266 /* ExportAssignment */ && !node.isExportEquals)) { + (node.kind === 267 /* ExportAssignment */ && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName_1 = false; multipleDefaultExports_1 = true; @@ -40711,7 +41896,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = !!(ts.getCombinedModifierFlags(node) & 1 /* Export */) || jsdocTreatAsExported(node); if (symbolFlags & 2097152 /* Alias */) { - if (node.kind === 270 /* ExportSpecifier */ || (node.kind === 260 /* ImportEqualsDeclaration */ && hasExportModifier)) { + if (node.kind === 271 /* ExportSpecifier */ || (node.kind === 261 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -40800,7 +41985,7 @@ var ts; // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. if (containerFlags & 1 /* IsContainer */) { - if (node.kind !== 209 /* ArrowFunction */) { + if (node.kind !== 210 /* ArrowFunction */) { thisParentContainer = container; } container = blockScopeContainer = node; @@ -40833,7 +42018,7 @@ var ts; } // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property initialization checks. - currentReturnTarget = isIIFE || node.kind === 166 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */)) ? createBranchLabel() : undefined; + currentReturnTarget = isIIFE || node.kind === 167 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 252 /* FunctionDeclaration */ || node.kind === 209 /* FunctionExpression */)) ? createBranchLabel() : undefined; currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; @@ -40848,13 +42033,14 @@ var ts; node.flags |= 512 /* HasExplicitReturn */; node.endFlowNode = currentFlow; } - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { node.flags |= emitFlags; + node.endFlowNode = currentFlow; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 166 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */))) { + if (node.kind === 167 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 252 /* FunctionDeclaration */ || node.kind === 209 /* FunctionExpression */))) { node.returnFlowNode = currentFlow; } } @@ -40881,8 +42067,8 @@ var ts; blockScopeContainer = savedBlockScopeContainer; } function bindEachFunctionsFirst(nodes) { - bindEach(nodes, function (n) { return n.kind === 251 /* FunctionDeclaration */ ? bind(n) : undefined; }); - bindEach(nodes, function (n) { return n.kind !== 251 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind === 252 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 252 /* FunctionDeclaration */ ? bind(n) : undefined; }); } function bindEach(nodes, bindFunction) { if (bindFunction === void 0) { bindFunction = bind; } @@ -40905,59 +42091,59 @@ var ts; inAssignmentPattern = saveInAssignmentPattern; return; } - if (node.kind >= 232 /* FirstStatement */ && node.kind <= 248 /* LastStatement */ && !options.allowUnreachableCode) { + if (node.kind >= 233 /* FirstStatement */ && node.kind <= 249 /* LastStatement */ && !options.allowUnreachableCode) { node.flowNode = currentFlow; } switch (node.kind) { - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: bindWhileStatement(node); break; - case 235 /* DoStatement */: + case 236 /* DoStatement */: bindDoStatement(node); break; - case 237 /* ForStatement */: + case 238 /* ForStatement */: bindForStatement(node); break; - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: bindForInOrForOfStatement(node); break; - case 234 /* IfStatement */: + case 235 /* IfStatement */: bindIfStatement(node); break; - case 242 /* ReturnStatement */: - case 246 /* ThrowStatement */: + case 243 /* ReturnStatement */: + case 247 /* ThrowStatement */: bindReturnOrThrow(node); break; - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 247 /* TryStatement */: + case 248 /* TryStatement */: bindTryStatement(node); break; - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: bindSwitchStatement(node); break; - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: bindCaseBlock(node); break; - case 284 /* CaseClause */: + case 285 /* CaseClause */: bindCaseClause(node); break; - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: bindExpressionStatement(node); break; - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: bindLabeledStatement(node); break; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: bindPostfixUnaryExpressionFlow(node); break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.isDestructuringAssignment(node)) { // Carry over whether we are in an assignment pattern to // binary expressions that could actually be an initializer @@ -40967,47 +42153,47 @@ var ts; } bindBinaryExpressionFlow(node); break; - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: bindDeleteExpressionFlow(node); break; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: bindConditionalExpressionFlow(node); break; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: bindVariableDeclarationFlow(node); break; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: bindAccessExpressionFlow(node); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: bindCallExpressionFlow(node); break; - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: bindNonNullExpressionFlow(node); break; - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: bindJSDocTypeAlias(node); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime - case 297 /* SourceFile */: { + case 298 /* SourceFile */: { bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); break; } - case 230 /* Block */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 258 /* ModuleBlock */: bindEachFunctionsFirst(node.statements); break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: bindBindingElementFlow(node); break; - case 200 /* ObjectLiteralExpression */: - case 199 /* ArrayLiteralExpression */: - case 288 /* PropertyAssignment */: - case 220 /* SpreadElement */: + case 201 /* ObjectLiteralExpression */: + case 200 /* ArrayLiteralExpression */: + case 289 /* PropertyAssignment */: + case 221 /* SpreadElement */: // Carry over whether we are in an assignment pattern of Object and Array literals // as well as their children that are valid assignment targets. inAssignmentPattern = saveInAssignmentPattern; @@ -41024,29 +42210,29 @@ var ts; case 78 /* Identifier */: case 79 /* PrivateIdentifier */: case 107 /* ThisKeyword */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return containsNarrowableReference(expr); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return hasNarrowableArgument(expr); - case 207 /* ParenthesizedExpression */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: return isNarrowingExpression(expr.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return isNarrowingBinaryExpression(expr); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return isNarrowingExpression(expr.expression); } return false; } function isNarrowableReference(expr) { - return expr.kind === 78 /* Identifier */ || expr.kind === 79 /* PrivateIdentifier */ || expr.kind === 107 /* ThisKeyword */ || expr.kind === 105 /* SuperKeyword */ || - (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isBinaryExpression(expr) && expr.operatorToken.kind === 27 /* CommaToken */ && isNarrowableReference(expr.right) || - ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || - ts.isAssignmentExpression(expr) && isNarrowableReference(expr.left); + return ts.isDottedName(expr) + || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) + || ts.isBinaryExpression(expr) && expr.operatorToken.kind === 27 /* CommaToken */ && isNarrowableReference(expr.right) + || ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) + || ts.isAssignmentExpression(expr) && isNarrowableReference(expr.left); } function containsNarrowableReference(expr) { return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression); @@ -41060,7 +42246,7 @@ var ts; } } } - if (expr.expression.kind === 201 /* PropertyAccessExpression */ && + if (expr.expression.kind === 202 /* PropertyAccessExpression */ && containsNarrowableReference(expr.expression.expression)) { return true; } @@ -41096,9 +42282,9 @@ var ts; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isNarrowableOperand(expr.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (expr.operatorToken.kind) { case 62 /* EqualsToken */: return isNarrowableOperand(expr.left); @@ -41174,26 +42360,26 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 234 /* IfStatement */: - case 236 /* WhileStatement */: - case 235 /* DoStatement */: + case 235 /* IfStatement */: + case 237 /* WhileStatement */: + case 236 /* DoStatement */: return parent.expression === node; - case 237 /* ForStatement */: - case 217 /* ConditionalExpression */: + case 238 /* ForStatement */: + case 218 /* ConditionalExpression */: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 207 /* ParenthesizedExpression */) { + if (node.kind === 208 /* ParenthesizedExpression */) { node = node.expression; } - else if (node.kind === 214 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) { + else if (node.kind === 215 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) { node = node.operand; } else { - return node.kind === 216 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ || + return node.kind === 217 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */); } @@ -41240,7 +42426,7 @@ var ts; } function setContinueTarget(node, target) { var label = activeLabelList; - while (label && node.parent.kind === 245 /* LabeledStatement */) { + while (label && node.parent.kind === 246 /* LabeledStatement */) { label.continueTarget = target; label = label.next; node = node.parent; @@ -41291,12 +42477,12 @@ var ts; bind(node.expression); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 239 /* ForOfStatement */) { + if (node.kind === 240 /* ForOfStatement */) { bind(node.awaitModifier); } addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 250 /* VariableDeclarationList */) { + if (node.initializer.kind !== 251 /* VariableDeclarationList */) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -41318,7 +42504,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 242 /* ReturnStatement */) { + if (node.kind === 243 /* ReturnStatement */) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -41335,7 +42521,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 241 /* BreakStatement */ ? breakTarget : continueTarget; + var flowLabel = node.kind === 242 /* BreakStatement */ ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -41440,7 +42626,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 285 /* DefaultClause */; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 286 /* DefaultClause */; }); // We mark a switch statement as possibly exhaustive if it has no default clause and if all // case clauses have unreachable end points (e.g. they all return). Note, we no longer need // this property in control flow analysis, it's there only for backwards compatibility. @@ -41488,9 +42674,9 @@ var ts; function maybeBindExpressionFlowIfCall(node) { // A top level or LHS of comma expression call expression with a dotted function name and at least one argument // is potentially an assertion and is therefore included in the control flow. - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { var call = node; - if (ts.isDottedName(call.expression) && call.expression.kind !== 105 /* SuperKeyword */) { + if (call.expression.kind !== 105 /* SuperKeyword */ && ts.isDottedName(call.expression)) { currentFlow = createFlowCall(currentFlow, call); } } @@ -41514,7 +42700,7 @@ var ts; currentFlow = finishFlowLabel(postStatementLabel); } function bindDestructuringTargetFlow(node) { - if (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) { + if (node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) { bindAssignmentTargetFlow(node.left); } else { @@ -41525,10 +42711,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node); } - else if (node.kind === 199 /* ArrayLiteralExpression */) { + else if (node.kind === 200 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 220 /* SpreadElement */) { + if (e.kind === 221 /* SpreadElement */) { bindAssignmentTargetFlow(e.expression); } else { @@ -41536,16 +42722,16 @@ var ts; } } } - else if (node.kind === 200 /* ObjectLiteralExpression */) { + else if (node.kind === 201 /* ObjectLiteralExpression */) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 288 /* PropertyAssignment */) { + if (p.kind === 289 /* PropertyAssignment */) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 289 /* ShorthandPropertyAssignment */) { + else if (p.kind === 290 /* ShorthandPropertyAssignment */) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 290 /* SpreadAssignment */) { + else if (p.kind === 291 /* SpreadAssignment */) { bindAssignmentTargetFlow(p.expression); } } @@ -41610,128 +42796,102 @@ var ts; } bindAssignmentTargetFlow(node.left); } - var BindBinaryExpressionFlowState; - (function (BindBinaryExpressionFlowState) { - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindThenBindChildren"] = 0] = "BindThenBindChildren"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["MaybeBindLeft"] = 1] = "MaybeBindLeft"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindToken"] = 2] = "BindToken"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindRight"] = 3] = "BindRight"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["FinishBind"] = 4] = "FinishBind"; - })(BindBinaryExpressionFlowState || (BindBinaryExpressionFlowState = {})); - function bindBinaryExpressionFlow(node) { - var workStacks = { - expr: [node], - state: [1 /* MaybeBindLeft */], - inStrictMode: [undefined], - parent: [undefined], - }; - var stackIndex = 0; - while (stackIndex >= 0) { - node = workStacks.expr[stackIndex]; - switch (workStacks.state[stackIndex]) { - case 0 /* BindThenBindChildren */: { - // This state is used only when recuring, to emulate the work that `bind` does before - // reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work. - ts.setParent(node, parent); - var saveInStrictMode = inStrictMode; - bindWorker(node); - var saveParent = parent; - parent = node; - advanceState(1 /* MaybeBindLeft */, saveInStrictMode, saveParent); - break; - } - case 1 /* MaybeBindLeft */: { - var operator = node.operatorToken.kind; - // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions - // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too - // For now, though, since the common cases are chained `+`, leaving it recursive is fine - if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */ || - ts.isLogicalOrCoalescingAssignmentOperator(operator)) { - if (isTopLevelLogicalExpression(node)) { - var postExpressionLabel = createBranchLabel(); - bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel); - currentFlow = finishFlowLabel(postExpressionLabel); - } - else { - bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget); - } - completeNode(); - } - else { - advanceState(2 /* BindToken */); - maybeBind(node.left); - } - break; + function createBindBinaryExpressionFlow() { + return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined); + function onEnter(node, state) { + if (state) { + state.stackIndex++; + // Emulate the work that `bind` does before reaching `bindChildren`. A normal call to + // `bindBinaryExpressionFlow` will already have done this work. + ts.setParent(node, parent); + var saveInStrictMode = inStrictMode; + bindWorker(node); + var saveParent = parent; + parent = node; + state.skip = false; + state.inStrictModeStack[state.stackIndex] = saveInStrictMode; + state.parentStack[state.stackIndex] = saveParent; + } + else { + state = { + stackIndex: 0, + skip: false, + inStrictModeStack: [undefined], + parentStack: [undefined] + }; + } + // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions + // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too + // For now, though, since the common cases are chained `+`, leaving it recursive is fine + var operator = node.operatorToken.kind; + if (operator === 55 /* AmpersandAmpersandToken */ || + operator === 56 /* BarBarToken */ || + operator === 60 /* QuestionQuestionToken */ || + ts.isLogicalOrCoalescingAssignmentOperator(operator)) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); } - case 2 /* BindToken */: { - if (node.operatorToken.kind === 27 /* CommaToken */) { - maybeBindExpressionFlowIfCall(node.left); - } - advanceState(3 /* BindRight */); - maybeBind(node.operatorToken); - break; + else { + bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget); } - case 3 /* BindRight */: { - advanceState(4 /* FinishBind */); - maybeBind(node.right); - break; + state.skip = true; + } + return state; + } + function onLeft(left, state, _node) { + if (!state.skip) { + return maybeBind(left); + } + } + function onOperator(operatorToken, state, node) { + if (!state.skip) { + if (operatorToken.kind === 27 /* CommaToken */) { + maybeBindExpressionFlowIfCall(node.left); } - case 4 /* FinishBind */: { - var operator = node.operatorToken.kind; - if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { - bindAssignmentTargetFlow(node.left); - if (operator === 62 /* EqualsToken */ && node.left.kind === 202 /* ElementAccessExpression */) { - var elementAccess = node.left; - if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); - } + bind(operatorToken); + } + } + function onRight(right, state, _node) { + if (!state.skip) { + return maybeBind(right); + } + } + function onExit(node, state) { + if (!state.skip) { + var operator = node.operatorToken.kind; + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 62 /* EqualsToken */ && node.left.kind === 203 /* ElementAccessExpression */) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); } } - completeNode(); - break; } - default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for bindBinaryExpressionFlow"); } - } - /** - * Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new - * head state; so `advanceState` must be called before any `maybeBind` during a state's execution. - */ - function advanceState(state, isInStrictMode, parent) { - workStacks.state[stackIndex] = state; - if (isInStrictMode !== undefined) { - workStacks.inStrictMode[stackIndex] = isInStrictMode; + var savedInStrictMode = state.inStrictModeStack[state.stackIndex]; + var savedParent = state.parentStack[state.stackIndex]; + if (savedInStrictMode !== undefined) { + inStrictMode = savedInStrictMode; } - if (parent !== undefined) { - workStacks.parent[stackIndex] = parent; + if (savedParent !== undefined) { + parent = savedParent; } + state.skip = false; + state.stackIndex--; } - function completeNode() { - if (workStacks.inStrictMode[stackIndex] !== undefined) { - inStrictMode = workStacks.inStrictMode[stackIndex]; - parent = workStacks.parent[stackIndex]; - } - stackIndex--; - } - /** - * If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it - */ function maybeBind(node) { if (node && ts.isBinaryExpression(node) && !ts.isDestructuringAssignment(node)) { - stackIndex++; - workStacks.expr[stackIndex] = node; - workStacks.state[stackIndex] = 0 /* BindThenBindChildren */; - workStacks.inStrictMode[stackIndex] = undefined; - workStacks.parent[stackIndex] = undefined; - } - else { - bind(node); + return node; } + bind(node); } } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 201 /* PropertyAccessExpression */) { + if (node.expression.kind === 202 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -41788,7 +42948,7 @@ var ts; } function bindJSDocTypeAlias(node) { ts.setParent(node.tagName, node); - if (node.kind !== 325 /* JSDocEnumTag */ && node.fullName) { + if (node.kind !== 329 /* JSDocEnumTag */ && node.fullName) { ts.setParent(node.fullName, node); ts.setParentRecursive(node.fullName, /*incremental*/ false); } @@ -41796,7 +42956,7 @@ var ts; function bindJSDocClassTag(node) { bindEachChild(node); var host = ts.getHostSignatureFromJSDoc(node); - if (host && host.kind !== 165 /* MethodDeclaration */) { + if (host && host.kind !== 166 /* MethodDeclaration */) { addDeclarationToSymbol(host.symbol, host, 32 /* Class */); } } @@ -41809,15 +42969,15 @@ var ts; } function bindOptionalChainRest(node) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: bind(node.questionDotToken); bind(node.name); break; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: bind(node.questionDotToken); bind(node.argumentExpression); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: bind(node.questionDotToken); bindEach(node.typeArguments); bindEach(node.arguments); @@ -41882,7 +43042,7 @@ var ts; // an immediately invoked function expression (IIFE). Initialize the flowNode property to // the current control flow (which includes evaluation of the IIFE arguments). var expr = ts.skipParentheses(node.expression); - if (expr.kind === 208 /* FunctionExpression */ || expr.kind === 209 /* ArrowFunction */) { + if (expr.kind === 209 /* FunctionExpression */ || expr.kind === 210 /* ArrowFunction */) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -41894,7 +43054,7 @@ var ts; } } } - if (node.expression.kind === 201 /* PropertyAccessExpression */) { + if (node.expression.kind === 202 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); @@ -41903,54 +43063,54 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 200 /* ObjectLiteralExpression */: - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 281 /* JsxAttributes */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 201 /* ObjectLiteralExpression */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 282 /* JsxAttributes */: return 1 /* IsContainer */; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return 1 /* IsContainer */ | 64 /* IsInterface */; - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 190 /* MappedType */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 191 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 297 /* SourceFile */: + case 298 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; } // falls through - case 166 /* Constructor */: - case 251 /* FunctionDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 169 /* CallSignature */: - case 313 /* JSDocSignature */: - case 308 /* JSDocFunctionType */: - case 174 /* FunctionType */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 175 /* ConstructorType */: + case 167 /* Constructor */: + case 252 /* FunctionDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 170 /* CallSignature */: + case 315 /* JSDocSignature */: + case 309 /* JSDocFunctionType */: + case 175 /* FunctionType */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 176 /* ConstructorType */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return 4 /* IsControlFlowContainer */; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 287 /* CatchClause */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 258 /* CaseBlock */: + case 288 /* CatchClause */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 259 /* CaseBlock */: return 2 /* IsBlockScopedContainer */; - case 230 /* Block */: + case 231 /* Block */: // do not treat blocks directly inside a function as a block-scoped-container. // Locals that reside in this block should go to the function locals. Otherwise 'x' // would not appear to be a redeclaration of a block scoped local in the following @@ -41983,45 +43143,45 @@ var ts; // members are declared (for example, a member of a class will go into a specific // symbol table depending on if it is static or not). We defer to specialized // handlers to take care of declaring these child members. - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 297 /* SourceFile */: + case 298 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 200 /* ObjectLiteralExpression */: - case 253 /* InterfaceDeclaration */: - case 281 /* JsxAttributes */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 201 /* ObjectLiteralExpression */: + case 254 /* InterfaceDeclaration */: + case 282 /* JsxAttributes */: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the // object / type / interface declaring them). An exception is type parameters, // which are in scope without qualification (similar to 'locals'). return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 313 /* JSDocSignature */: - case 171 /* IndexSignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 308 /* JSDocFunctionType */: - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 254 /* TypeAliasDeclaration */: - case 190 /* MappedType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 315 /* JSDocSignature */: + case 172 /* IndexSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 309 /* JSDocFunctionType */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 255 /* TypeAliasDeclaration */: + case 191 /* MappedType */: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -42122,7 +43282,7 @@ var ts; var seen = new ts.Map(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 290 /* SpreadAssignment */ || prop.name.kind !== 78 /* Identifier */) { + if (prop.kind === 291 /* SpreadAssignment */ || prop.name.kind !== 78 /* Identifier */) { continue; } var identifier = prop.name; @@ -42134,7 +43294,7 @@ var ts; // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 288 /* PropertyAssignment */ || prop.kind === 289 /* ShorthandPropertyAssignment */ || prop.kind === 165 /* MethodDeclaration */ + var currentKind = prop.kind === 289 /* PropertyAssignment */ || prop.kind === 290 /* ShorthandPropertyAssignment */ || prop.kind === 166 /* MethodDeclaration */ ? 1 /* Property */ : 2 /* Accessor */; var existingKind = seen.get(identifier.escapedText); @@ -42166,10 +43326,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (ts.isExternalOrCommonJsModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -42194,9 +43354,9 @@ var ts; var saveCurrentFlow = currentFlow; for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { var typeAlias = delayedTypeAliases_1[_i]; - var host = ts.getJSDocHost(typeAlias); - container = (host && ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); })) || file; - blockScopeContainer = (host && ts.getEnclosingBlockScopeContainer(host)) || file; + var host = typeAlias.parent.parent; + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); @@ -42368,8 +43528,8 @@ var ts; function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2 /* ES2015 */) { // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 297 /* SourceFile */ && - blockScopeContainer.kind !== 256 /* ModuleDeclaration */ && + if (blockScopeContainer.kind !== 298 /* SourceFile */ && + blockScopeContainer.kind !== 257 /* ModuleDeclaration */ && !ts.isFunctionLike(blockScopeContainer)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. @@ -42464,7 +43624,7 @@ var ts; // the current 'container' node when it changes. This helps us know which symbol table // a local should go into for example. Since terminal nodes are known not to have // children, as an optimization we don't process those. - if (node.kind > 156 /* LastToken */) { + if (node.kind > 157 /* LastToken */) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -42540,17 +43700,23 @@ var ts; } // falls through case 107 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 289 /* ShorthandPropertyAssignment */)) { + if (currentFlow && (ts.isExpression(node) || parent.kind === 290 /* ShorthandPropertyAssignment */)) { node.flowNode = currentFlow; } return checkContextualIdentifier(node); + case 158 /* QualifiedName */: + if (currentFlow && parent.kind === 177 /* TypeQuery */) { + node.flowNode = currentFlow; + } + break; + case 227 /* MetaProperty */: case 105 /* SuperKeyword */: node.flowNode = currentFlow; break; case 79 /* PrivateIdentifier */: return checkPrivateIdentifier(node); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: var expr = node; if (currentFlow && isNarrowableReference(expr)) { expr.flowNode = currentFlow; @@ -42565,7 +43731,7 @@ var ts; declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */); } break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: @@ -42601,78 +43767,78 @@ var ts; ts.Debug.fail("Unknown binary expression special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return checkStrictModeCatchClause(node); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return checkStrictModeDeleteExpression(node); case 8 /* NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return checkStrictModeWithStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return checkStrictModeLabeledStatement(node); - case 187 /* ThisType */: + case 188 /* ThisType */: seenThisKeyword = true; return; - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: break; // Binding the children will handle everything - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return bindTypeParameter(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return bindParameter(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return bindVariableDeclarationOrBindingElement(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return bindPropertyWorker(node); - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 291 /* EnumMember */: + case 292 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: // If this is an ObjectLiteralExpression method, then it sits in the same space // 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 */ : 103359 /* MethodExcludes */); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return bindFunctionDeclaration(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */); - case 174 /* FunctionType */: - case 308 /* JSDocFunctionType */: - case 313 /* JSDocSignature */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 309 /* JSDocFunctionType */: + case 315 /* JSDocSignature */: + case 176 /* ConstructorType */: return bindFunctionOrConstructorType(node); - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 190 /* MappedType */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 191 /* MappedType */: return bindAnonymousTypeWorker(node); - case 319 /* JSDocClassTag */: + case 322 /* JSDocClassTag */: return bindJSDocClassTag(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return bindFunctionExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: var assignmentKind = ts.getAssignmentDeclarationKind(node); switch (assignmentKind) { case 7 /* ObjectDefinePropertyValue */: @@ -42691,65 +43857,65 @@ var ts; } break; // Members of classes, interfaces, and modules - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: // All classes are automatically in strict mode in ES6. inStrictMode = true; return bindClassLikeDeclaration(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return bindEnumDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return bindModuleDeclaration(node); // Jsx-attributes - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return bindJsxAttributes(node); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); // Imports and exports - case 260 /* ImportEqualsDeclaration */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 261 /* ImportEqualsDeclaration */: + case 264 /* NamespaceImport */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return bindNamespaceExportDeclaration(node); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return bindImportClause(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return bindExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return bindExportAssignment(node); - case 297 /* SourceFile */: + case 298 /* SourceFile */: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 230 /* Block */: + case 231 /* Block */: if (!ts.isFunctionLike(node.parent)) { return; } // falls through - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 326 /* JSDocParameterTag */: - if (node.parent.kind === 313 /* JSDocSignature */) { + case 330 /* JSDocParameterTag */: + if (node.parent.kind === 315 /* JSDocSignature */) { return bindParameter(node); } - if (node.parent.kind !== 312 /* JSDocTypeLiteral */) { + if (node.parent.kind !== 314 /* JSDocTypeLiteral */) { break; } // falls through - case 333 /* JSDocPropertyTag */: + case 337 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 307 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 308 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } @@ -42777,8 +43943,8 @@ var ts; } function bindExportAssignment(node) { if (!container.symbol || !container.symbol.exports) { - // Export assignment in some sort of block construct - bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + // Incorrect export assignment in some sort of block construct + bindAnonymousDeclaration(node, 111551 /* Value */, getDeclarationName(node)); } else { var flags = ts.exportAssignmentIsAlias(node) @@ -42912,8 +44078,8 @@ var ts; } var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: var constructorSymbol = thisContainer.symbol; // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 62 /* EqualsToken */) { @@ -42935,11 +44101,11 @@ var ts; addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */); } break; - case 166 /* Constructor */: - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 167 /* Constructor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // this.foo assignment in a JavaScript class // Bind this property to the containing class var containingClass = thisContainer.parent; @@ -42951,7 +44117,7 @@ var ts; declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true); } break; - case 297 /* SourceFile */: + case 298 /* SourceFile */: // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script if (ts.hasDynamicName(node)) { break; @@ -42980,7 +44146,7 @@ var ts; if (node.expression.kind === 107 /* ThisKeyword */) { bindThisPropertyAssignment(node); } - else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 297 /* SourceFile */) { + else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 298 /* SourceFile */) { if (ts.isPrototypeAccess(node.expression)) { bindPrototypePropertyAssignment(node, node.parent); } @@ -43020,7 +44186,7 @@ var ts; } function bindObjectDefinePropertyAssignment(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); - var isToplevel = node.parent.parent.kind === 297 /* SourceFile */; + var isToplevel = node.parent.parent.kind === 298 /* SourceFile */; namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false); bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); } @@ -43129,8 +44295,8 @@ var ts; } function isTopLevelNamespaceAssignment(propertyAccess) { return ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 297 /* SourceFile */ - : propertyAccess.parent.parent.kind === 297 /* SourceFile */; + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 298 /* SourceFile */ + : propertyAccess.parent.parent.kind === 298 /* SourceFile */; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) { var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer); @@ -43209,7 +44375,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 252 /* ClassDeclaration */) { + if (node.kind === 253 /* ClassDeclaration */) { bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */); } else { @@ -43251,7 +44417,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { - if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true) && !ts.getJSDocTypeTag(node)) { + if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node) && !ts.getJSDocTypeTag(node)) { declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } else if (ts.isBlockOrCatchScoped(node)) { @@ -43275,7 +44441,7 @@ var ts; } } function bindParameter(node) { - if (node.kind === 326 /* JSDocParameterTag */ && container.kind !== 313 /* JSDocSignature */) { + if (node.kind === 330 /* JSDocParameterTag */ && container.kind !== 315 /* JSDocSignature */) { return; } if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) { @@ -43352,7 +44518,7 @@ var ts; declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */); } } - else if (node.parent.kind === 185 /* InferType */) { + else if (node.parent.kind === 186 /* InferType */) { var container_2 = getInferTypeContainer(node.parent); if (container_2) { if (!container_2.locals) { @@ -43371,7 +44537,7 @@ var ts; // reachability checks function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && ts.shouldPreserveConstEnums(options)); } function checkUnreachable(node) { if (!(currentFlow.flags & 1 /* Unreachable */)) { @@ -43380,11 +44546,11 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 231 /* EmptyStatement */) || + (ts.isStatementButNotDeclaration(node) && node.kind !== 232 /* EmptyStatement */) || // report error on class declarations - node.kind === 252 /* ClassDeclaration */ || + node.kind === 253 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 256 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); + (node.kind === 257 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -43428,12 +44594,12 @@ var ts; } function isPurelyTypeDeclaration(s) { switch (s.kind) { - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return true; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return getModuleInstanceState(s) !== 1 /* Instantiated */; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return ts.hasSyntacticModifier(s, 2048 /* Const */); default: return false; @@ -43633,7 +44799,7 @@ var ts; // (their type resolved directly to the member deeply referenced) // So to get the intervening symbols, we need to check if there's a type // query node on any of the symbol's declarations and get symbols there - if (d.type && d.type.kind === 176 /* TypeQuery */) { + if (d.type && d.type.kind === 177 /* TypeQuery */) { var query = d.type; var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); visitSymbol(entity); @@ -43860,6 +45026,7 @@ var ts; DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor"; DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment"; DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method"; + DeclarationMeaning[DeclarationMeaning["PrivateStatic"] = 16] = "PrivateStatic"; DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor"; DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod"; })(DeclarationMeaning || (DeclarationMeaning = {})); @@ -43951,12 +45118,12 @@ var ts; var instantiationCount = 0; var instantiationDepth = 0; var currentNode; - var typeCatalog = []; // NB: id is index + 1 var emptySymbols = ts.createSymbolTable(); var arrayVariances = [1 /* Covariant */]; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); @@ -43965,7 +45132,8 @@ var ts; var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16384 /* FreshLiteral */; + var checkBinaryExpression = createCheckBinaryExpression(); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); var globals = ts.createSymbolTable(); @@ -43988,7 +45156,6 @@ var ts; getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, - getTypeCatalog: function () { return typeCatalog; }, getTypeCount: function () { return typeCount; }, getInstantiationCount: function () { return totalInstantiationCount; }, getRelationCacheSizes: function () { return ({ @@ -44152,6 +45319,7 @@ var ts; return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, + getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: function (node, candidatesOutArray, argumentCount) { return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */); @@ -44195,6 +45363,7 @@ var ts; }, tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); }, + tryFindAmbientModule: function (moduleName) { return tryFindAmbientModule(moduleName, /*withAugmentations*/ true); }, tryFindAmbientModuleWithoutAugmentations: function (moduleName) { // we deliberately exclude augmentations // since we are only interested in declarations of the module itself @@ -44313,6 +45482,7 @@ var ts; var templateLiteralTypes = new ts.Map(); var stringMappingTypes = new ts.Map(); var substitutionTypes = new ts.Map(); + var subtypeReductionCache = new ts.Map(); var evolvingArrayTypes = []; var undefinedProperties = new ts.Map(); var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -44321,14 +45491,14 @@ var ts; var autoType = createIntrinsicType(1 /* Any */, "any"); var wildcardType = createIntrinsicType(1 /* Any */, "any"); var errorType = createIntrinsicType(1 /* Any */, "error"); - var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */); + var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 131072 /* ContainsWideningType */); var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */); var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined"); var nullType = createIntrinsicType(65536 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 131072 /* ContainsWideningType */); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); @@ -44354,7 +45524,7 @@ var ts; var voidType = createIntrinsicType(16384 /* Void */, "void"); var neverType = createIntrinsicType(131072 /* Never */, "never"); var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); - var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */); + var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 524288 /* NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); @@ -44366,7 +45536,7 @@ var ts; var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; + emptyJsxObjectType.objectFlags |= 2048 /* JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -44375,7 +45545,7 @@ var ts; var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */; + anyFunctionType.objectFlags |= 524288 /* NonInferrableType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -44455,6 +45625,7 @@ var ts; // This allows users to just specify library files they want to used through --lib // and they will not get an error from not having unrelated library files var deferredGlobalESSymbolConstructorSymbol; + var deferredGlobalESSymbolConstructorTypeSymbol; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; @@ -44506,7 +45677,7 @@ var ts; var flowNodePostSuper = []; var potentialThisCollisions = []; var potentialNewTargetCollisions = []; - var potentialWeakMapCollisions = []; + var potentialWeakMapSetCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); var suggestionDiagnostics = ts.createDiagnosticCollection(); @@ -44653,6 +45824,25 @@ var ts; } return diagnostic; } + function addDeprecatedSuggestionWorker(declarations, diagnostic) { + var deprecatedTag = Array.isArray(declarations) ? ts.forEach(declarations, ts.getJSDocDeprecatedTag) : ts.getJSDocDeprecatedTag(declarations); + if (deprecatedTag) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(deprecatedTag, ts.Diagnostics.The_declaration_was_marked_as_deprecated_here)); + } + // We call `addRelatedInfo()` before adding the diagnostic to prevent duplicates. + suggestionDiagnostics.add(diagnostic); + return diagnostic; + } + function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { + var diagnostic = ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, deprecatedEntity); + return addDeprecatedSuggestionWorker(declarations, diagnostic); + } + function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) { + var diagnostic = deprecatedEntity + ? ts.createDiagnosticForNode(location, ts.Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity) + : ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, signatureString); + return addDeprecatedSuggestionWorker(declaration, diagnostic); + } function createSymbol(flags, name, checkFlags) { symbolCount++; var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); @@ -44766,7 +45956,7 @@ var ts; // as we will already report a "Declaration name conflicts..." error, and this error // won't make much sense. if (target !== globalThisSymbol) { - error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(source.declarations && ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } } else { // error @@ -44800,9 +45990,11 @@ var ts; } return target; function addDuplicateLocations(locs, symbol) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - ts.pushIfUnique(locs, decl); + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, decl); + } } } } @@ -44848,9 +46040,9 @@ var ts; }); } function mergeModuleAugmentation(moduleName) { - var _a, _b; + var _a, _b, _c; var moduleAugmentation = moduleName.parent; - if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + if (((_a = moduleAugmentation.symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]) !== moduleAugmentation) { // this is a combined symbol for multiple augmentations within the same file. // its symbol already has accumulated information for all declarations // so we need to add it just once - do the work only for first declaration @@ -44887,11 +46079,11 @@ var ts; patternAmbientModuleAugmentations.set(moduleName.text, merged); } else { - if (((_a = mainModule_1.exports) === null || _a === void 0 ? void 0 : _a.get("__export" /* ExportStar */)) && ((_b = moduleAugmentation.symbol.exports) === null || _b === void 0 ? void 0 : _b.size)) { + if (((_b = mainModule_1.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */)) && ((_c = moduleAugmentation.symbol.exports) === null || _c === void 0 ? void 0 : _c.size)) { // We may need to merge the module augmentation's exports into the target symbols of the resolved exports var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */); - for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) { - var _d = _c[_i], key = _d[0], value = _d[1]; + for (var _i = 0, _d = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _d.length; _i++) { + var _e = _d[_i], key = _e[0], value = _e[1]; if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) { mergeSymbol(resolvedExports.get(key), value); } @@ -44932,7 +46124,7 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks()); } function isGlobalSourceFile(node) { - return node.kind === 297 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 298 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -44991,17 +46183,17 @@ var ts; } if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) { // declaration is before usage - if (declaration.kind === 198 /* BindingElement */) { + if (declaration.kind === 199 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) - var errorBindingElement = ts.getAncestor(usage, 198 /* BindingElement */); + var errorBindingElement = ts.getAncestor(usage, 199 /* BindingElement */); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 249 /* VariableDeclaration */), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 250 /* VariableDeclaration */), usage); } - else if (declaration.kind === 249 /* VariableDeclaration */) { + else if (declaration.kind === 250 /* VariableDeclaration */) { // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } @@ -45015,7 +46207,7 @@ var ts; } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property - return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + return !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); } @@ -45031,19 +46223,19 @@ var ts; // or if usage is in a type context: // 1. inside a type query (typeof in type position) // 2. inside a jsdoc comment - if (usage.parent.kind === 270 /* ExportSpecifier */ || (usage.parent.kind === 266 /* ExportAssignment */ && usage.parent.isExportEquals)) { + if (usage.parent.kind === 271 /* ExportSpecifier */ || (usage.parent.kind === 267 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; } // When resolving symbols for exports, the `usage` location passed in can be the export site directly - if (usage.kind === 266 /* ExportAssignment */ && usage.isExportEquals) { + if (usage.kind === 267 /* ExportAssignment */ && usage.isExportEquals) { return true; } if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + if (compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); @@ -45058,9 +46250,9 @@ var ts; } function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { switch (declaration.parent.parent.kind) { - case 232 /* VariableStatement */: - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: + case 233 /* VariableStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, declContainer)) { @@ -45081,16 +46273,16 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 163 /* PropertyDeclaration */ && + current.parent.kind === 164 /* PropertyDeclaration */ && current.parent.initializer === current; if (initializerOfProperty) { if (ts.hasSyntacticModifier(current.parent, 32 /* Static */)) { - if (declaration.kind === 165 /* MethodDeclaration */) { + if (declaration.kind === 166 /* MethodDeclaration */) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 163 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(declaration, 32 /* Static */); + var isDeclarationInstanceProperty = declaration.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(declaration, 32 /* Static */); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -45112,19 +46304,19 @@ var ts; return "quit"; } switch (node.kind) { - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return true; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // even when stopping at any property declaration, they need to come from the same class return stopAtAnyPropertyDeclaration && (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent) ? "quit" : true; - case 230 /* Block */: + case 231 /* Block */: switch (node.parent.kind) { - case 167 /* GetAccessor */: - case 165 /* MethodDeclaration */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 166 /* MethodDeclaration */: + case 169 /* SetAccessor */: return true; default: return false; @@ -45139,7 +46331,11 @@ var ts; function useOuterVariableScopeInParameter(result, location, lastLocation) { var target = ts.getEmitScriptTarget(compilerOptions); var functionLocation = location; - if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + if (ts.isParameter(lastLocation) + && functionLocation.body + && result.valueDeclaration + && result.valueDeclaration.pos >= functionLocation.body.pos + && result.valueDeclaration.end <= functionLocation.body.end) { // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body // - static field in a class expression // - optional chaining pre-es2020 @@ -45160,21 +46356,21 @@ var ts; } function requiresScopeChangeWorker(node) { switch (node.kind) { - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 166 /* Constructor */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 167 /* Constructor */: // do not descend into these return false; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 288 /* PropertyAssignment */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 289 /* PropertyAssignment */: return requiresScopeChangeWorker(node.name); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // static properties in classes introduce temporary variables if (ts.hasStaticModifier(node)) { - return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields; + return target < 99 /* ESNext */ || !useDefineForClassFields; } return requiresScopeChangeWorker(node.name); default: @@ -45203,6 +46399,7 @@ var ts; return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); } function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { + var _a; var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; @@ -45225,12 +46422,12 @@ 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 & 788968 /* Type */ && lastLocation.kind !== 311 /* JSDocComment */) { + if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 312 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || - lastLocation.kind === 160 /* Parameter */ || - lastLocation.kind === 159 /* TypeParameter */ + lastLocation.kind === 161 /* Parameter */ || + lastLocation.kind === 160 /* TypeParameter */ // local types not visible outside the function body : false; } @@ -45245,13 +46442,13 @@ var ts; // however it is detected separately when checking initializers of parameters // to make sure that they reference no variables declared after them. useResult = - lastLocation.kind === 160 /* Parameter */ || + lastLocation.kind === 161 /* Parameter */ || (lastLocation === location.type && !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); } } } - else if (location.kind === 184 /* ConditionalType */) { + else if (location.kind === 185 /* ConditionalType */) { // A type parameter declared using 'infer T' in a conditional type is visible only in // the true branch of the conditional type. useResult = lastLocation === location.trueType; @@ -45266,14 +46463,14 @@ var ts; } withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation); switch (location.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; // falls through - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports || emptySymbols; - if (location.kind === 297 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) { + if (location.kind === 298 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports.get("default" /* Default */)) { @@ -45297,13 +46494,13 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && - (ts.getDeclarationOfKind(moduleExport, 270 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 269 /* NamespaceExport */))) { + (ts.getDeclarationOfKind(moduleExport, 271 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 270 /* NamespaceExport */))) { break; } } // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs) if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) { - if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !((_a = result.declarations) === null || _a === void 0 ? void 0 : _a.some(ts.isJSDocTypeAlias))) { result = undefined; } else { @@ -45311,12 +46508,12 @@ var ts; } } break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // TypeScript 1.0 spec (April 2014): 8.4.1 // Initializer expressions for instance member variables are evaluated in the scope // of the class constructor body but are not permitted to reference parameters or @@ -45333,9 +46530,9 @@ var ts; } } break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: // 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! @@ -45354,7 +46551,7 @@ var ts; } break loop; } - if (location.kind === 221 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 222 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -45362,7 +46559,7 @@ var ts; } } break; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 93 /* ExtendsKeyword */) { var container = location.parent.parent; @@ -45382,9 +46579,9 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 253 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 254 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -45392,24 +46589,24 @@ var ts; } } break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: // when targeting ES6 or higher there is no 'arguments' in an arrow function // for lower compile targets the resolved symbol is used to emit an error if (compilerOptions.target >= 2 /* ES2015 */) { break; } // falls through - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -45422,7 +46619,7 @@ var ts; } } break; - case 161 /* Decorator */: + case 162 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -45431,7 +46628,7 @@ var ts; // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. // } // - if (location.parent && location.parent.kind === 160 /* Parameter */) { + if (location.parent && location.parent.kind === 161 /* Parameter */) { location = location.parent; } // @@ -45446,20 +46643,20 @@ var ts; // declare function y(x: T): any; // @param(1 as T) // <-- T should resolve to the type alias outside of class C // class C {} - if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 252 /* ClassDeclaration */)) { + if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 253 /* ClassDeclaration */)) { location = location.parent; } break; - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: // js type aliases do not resolve names from their host, so skip past it var root = ts.getJSDocRoot(location); if (root) { location = root.parent; } break; - case 160 /* Parameter */: + case 161 /* Parameter */: if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && ts.isBindingPattern(lastLocation))) { if (!associatedDeclarationForContainingInitializerOrBindingName) { @@ -45467,7 +46664,7 @@ var ts; } } break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && ts.isBindingPattern(lastLocation))) { if (ts.isParameterDeclaration(location) && !associatedDeclarationForContainingInitializerOrBindingName) { @@ -45475,7 +46672,7 @@ var ts; } } break; - case 185 /* InferType */: + case 186 /* InferType */: if (meaning & 262144 /* TypeParameter */) { var parameterName = location.typeParameter.name; if (parameterName && name === parameterName.escapedText) { @@ -45499,7 +46696,7 @@ var ts; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 297 /* SourceFile */); + ts.Debug.assert(lastLocation.kind === 298 /* SourceFile */); if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } @@ -45528,6 +46725,10 @@ var ts; var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + var isGlobalScopeAugmentationDeclaration = suggestion && suggestion.valueDeclaration && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); + if (isGlobalScopeAugmentationDeclaration) { + suggestion = undefined; + } if (suggestion) { var suggestionName = symbolToString(suggestion); var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); @@ -45554,7 +46755,7 @@ var ts; } // Perform extra checks only if error reporting was requested if (nameNotFoundMessage) { - if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields)) { // We have a match, but the reference occurred within a property initializer and the identifier also binds // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed // with ESNext+useDefineForClassFields because the scope semantics are different. @@ -45624,10 +46825,10 @@ var ts; } } function getIsDeferredContext(location, lastLocation) { - if (location.kind !== 209 /* ArrowFunction */ && location.kind !== 208 /* FunctionExpression */) { + if (location.kind !== 210 /* ArrowFunction */ && location.kind !== 209 /* FunctionExpression */) { // initializers in instance property declaration of class like entities are executed in constructor and thus deferred return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) || - (location.kind === 163 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(location, 32 /* Static */))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred + (location.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(location, 32 /* Static */))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred } if (lastLocation && lastLocation === location.name) { return false; @@ -45640,12 +46841,12 @@ var ts; } function isSelfReferenceLocation(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 256 /* ModuleDeclaration */: // For `namespace N { N; }` + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 257 /* ModuleDeclaration */: // For `namespace N { N; }` return true; default: return false; @@ -45655,12 +46856,14 @@ var ts; return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } function isTypeParameterSymbolDeclaredInContainer(symbol, container) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (decl.kind === 159 /* TypeParameter */) { - var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; - if (parent === container) { - return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.kind === 160 /* TypeParameter */) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + } } } } @@ -45713,9 +46916,9 @@ var ts; function getEntityNameForExtendingInterface(node) { switch (node.kind) { case 78 /* Identifier */: - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: if (ts.isEntityNameExpression(node.expression)) { return node.expression; } @@ -45759,7 +46962,7 @@ var ts; return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown"; } function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) { - if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 270 /* ExportSpecifier */) { + if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 271 /* ExportSpecifier */) { error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name); return true; } @@ -45828,13 +47031,14 @@ var ts; return false; } function checkResolvedBlockScopedVariable(result, errorLocation) { + var _a; ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) { // constructor functions aren't block scoped return; } // Block-scoped variables cannot be used before their definition - var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 255 /* EnumDeclaration */); }); + var declaration = (_a = result.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 256 /* EnumDeclaration */); }); if (declaration === undefined) return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration"); if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -45851,7 +47055,7 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); - if (compilerOptions.preserveConstEnums) { + if (ts.shouldPreserveConstEnums(compilerOptions)) { diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); } } @@ -45869,20 +47073,20 @@ var ts; } function getAnyImportSyntax(node) { switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return node; - case 262 /* ImportClause */: + case 263 /* ImportClause */: return node.parent; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return node.parent.parent; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: return node.parent.parent.parent; default: return undefined; } } function getDeclarationOfAliasSymbol(symbol) { - return ts.find(symbol.declarations, isAliasSymbolDeclaration); + return symbol.declarations && ts.findLast(symbol.declarations, isAliasSymbolDeclaration); } /** * An alias symbol is created by one of the following declarations: @@ -45897,25 +47101,26 @@ var ts; * module.exports = * {} * {name: } + * const { x } = require ... */ function isAliasSymbolDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ - || node.kind === 259 /* NamespaceExportDeclaration */ - || node.kind === 262 /* ImportClause */ && !!node.name - || node.kind === 263 /* NamespaceImport */ - || node.kind === 269 /* NamespaceExport */ - || node.kind === 265 /* ImportSpecifier */ - || node.kind === 270 /* ExportSpecifier */ - || node.kind === 266 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + return node.kind === 261 /* ImportEqualsDeclaration */ + || node.kind === 260 /* NamespaceExportDeclaration */ + || node.kind === 263 /* ImportClause */ && !!node.name + || node.kind === 264 /* NamespaceImport */ + || node.kind === 270 /* NamespaceExport */ + || node.kind === 266 /* ImportSpecifier */ + || node.kind === 271 /* ExportSpecifier */ + || node.kind === 267 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) || ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && ts.exportAssignmentIsAlias(node) || ts.isAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableOrJsExpression(node.parent.right) - || node.kind === 289 /* ShorthandPropertyAssignment */ - || node.kind === 288 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) - || ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true); + || node.kind === 290 /* ShorthandPropertyAssignment */ + || node.kind === 289 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) + || ts.isRequireVariableDeclaration(node); } function isAliasableOrJsExpression(e) { return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e); @@ -45928,7 +47133,7 @@ var ts; ? resolveSymbol(getPropertyOfType(resolveExternalModuleTypeByLiteral(name), commonJSPropertyAccess.name.escapedText)) : undefined; } - if (ts.isVariableDeclaration(node) || node.moduleReference.kind === 272 /* ExternalModuleReference */) { + if (ts.isVariableDeclaration(node) || node.moduleReference.kind === 273 /* ExternalModuleReference */) { var immediate = resolveExternalModuleName(node, ts.getExternalModuleRequireArgument(node) || ts.getExternalModuleImportEqualsDeclarationExpression(node)); var resolved_4 = resolveExternalModuleSymbol(immediate); markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false); @@ -45995,6 +47200,7 @@ var ts; return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias); } function getTargetOfImportClause(node, dontResolveAlias) { + var _a; var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { var exportDefaultSymbol = void 0; @@ -46004,7 +47210,7 @@ var ts; else { exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias); } - var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); if (!exportDefaultSymbol && !hasSyntheticDefault) { if (hasExportAssignmentSymbol(moduleSymbol)) { @@ -46012,7 +47218,9 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */); var exportAssignment = exportEqualsSymbol.valueDeclaration; var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName); - ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); + if (exportAssignment) { + ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); + } } else { reportNonDefaultExport(moduleSymbol, node); @@ -46029,7 +47237,7 @@ var ts; } } function reportNonDefaultExport(moduleSymbol, node) { - var _a, _b; + var _a, _b, _c; if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); } @@ -46037,7 +47245,7 @@ var ts; var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */); if (exportStar) { - var defaultExport = ts.find(exportStar.declarations, function (decl) { + var defaultExport = (_c = exportStar.declarations) === null || _c === void 0 ? void 0 : _c.find(function (decl) { var _a, _b; return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier && ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */))); @@ -46115,7 +47323,7 @@ var ts; } } function getExternalModuleMember(node, specifier, dontResolveAlias) { - var _a; + var _a, _b; if (dontResolveAlias === void 0) { dontResolveAlias = false; } var moduleSpecifier = ts.getExternalModuleRequireArgument(node) || node.moduleSpecifier; var moduleSymbol = resolveExternalModuleName(node, moduleSpecifier); // TODO: GH#18217 @@ -46124,7 +47332,7 @@ var ts; return undefined; } var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop); - var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, dontResolveAlias, suppressInteropError); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, /*dontResolveAlias*/ false, suppressInteropError); if (targetSymbol) { if (name.escapedText) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { @@ -46142,7 +47350,7 @@ var ts; symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); var symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias); if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) { - var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } @@ -46162,7 +47370,7 @@ var ts; } } else { - if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default" /* Default */)) { + if ((_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */)) { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); } else { @@ -46175,8 +47383,8 @@ var ts; } } function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) { - var _a; - var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText); + var _a, _b; + var localSymbol = (_b = (_a = moduleSymbol.valueDeclaration) === null || _a === void 0 ? void 0 : _a.locals) === null || _b === void 0 ? void 0 : _b.get(name.escapedText); var exports = moduleSymbol.exports; if (localSymbol) { var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */); @@ -46188,9 +47396,11 @@ var ts; var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined; var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); - ts.addRelatedInfo.apply(void 0, __spreadArray([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { - return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); - }))); + if (localSymbol.declarations) { + ts.addRelatedInfo.apply(void 0, __spreadArray([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { + return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); + }))); + } } } else { @@ -46277,31 +47487,31 @@ var ts; function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: - case 249 /* VariableDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 250 /* VariableDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return getTargetOfImportClause(node, dontRecursivelyResolve); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: return getTargetOfNamespaceExport(node, dontRecursivelyResolve); - case 265 /* ImportSpecifier */: - case 198 /* BindingElement */: + case 266 /* ImportSpecifier */: + case 199 /* BindingElement */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); - case 266 /* ExportAssignment */: - case 216 /* BinaryExpression */: + case 267 /* ExportAssignment */: + case 217 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return getTargetOfPropertyAssignment(node, dontRecursivelyResolve); - case 202 /* ElementAccessExpression */: - case 201 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: return getTargetOfAccessExpression(node, dontRecursivelyResolve); default: return ts.Debug.fail(); @@ -46453,13 +47663,13 @@ var ts; entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 78 /* Identifier */ || entityName.parent.kind === 157 /* QualifiedName */) { + if (entityName.kind === 78 /* Identifier */ || entityName.parent.kind === 158 /* QualifiedName */) { return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 260 /* ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 261 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } @@ -46483,9 +47693,9 @@ var ts; return getMergedSymbol(symbolFromJSPrototype); } } - else if (name.kind === 157 /* QualifiedName */ || name.kind === 201 /* PropertyAccessExpression */) { - var left = name.kind === 157 /* QualifiedName */ ? name.left : name.expression; - var right = name.kind === 157 /* QualifiedName */ ? name.right : name.name; + else if (name.kind === 158 /* QualifiedName */ || name.kind === 202 /* PropertyAccessExpression */) { + var left = name.kind === 158 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 158 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -46493,18 +47703,17 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJSFile(name)) { - if (namespace.valueDeclaration && - ts.isVariableDeclaration(namespace.valueDeclaration) && - namespace.valueDeclaration.initializer && - isCommonJsRequire(namespace.valueDeclaration.initializer)) { - var moduleName = namespace.valueDeclaration.initializer.arguments[0]; - var moduleSym = resolveExternalModuleName(moduleName, moduleName); - if (moduleSym) { - var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); - if (resolvedModuleSymbol) { - namespace = resolvedModuleSymbol; - } + if (namespace.valueDeclaration && + ts.isInJSFile(namespace.valueDeclaration) && + ts.isVariableDeclaration(namespace.valueDeclaration) && + namespace.valueDeclaration.initializer && + isCommonJsRequire(namespace.valueDeclaration.initializer)) { + var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + var moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; } } } @@ -46525,7 +47734,7 @@ var ts; throw ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); - if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 266 /* ExportAssignment */)) { + if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 267 /* ExportAssignment */)) { markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true); } return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); @@ -46762,7 +47971,7 @@ var ts; function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { - if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 297 /* SourceFile */)) { + if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 298 /* SourceFile */)) { var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop"; @@ -46813,7 +48022,10 @@ var ts; var exports = getExportsOfModuleAsArray(moduleSymbol); var exportEquals = resolveExternalModuleSymbol(moduleSymbol); if (exportEquals !== moduleSymbol) { - ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); + var type = getTypeOfSymbol(exportEquals); + if (shouldTreatPropertiesOfExternalModuleAsExports(type)) { + ts.addRange(exports, getPropertiesOfType(type)); + } } return exports; } @@ -46833,11 +48045,14 @@ var ts; return undefined; } var type = getTypeOfSymbol(exportEquals); - return type.flags & 131068 /* Primitive */ || - ts.getObjectFlags(type) & 1 /* Class */ || - isArrayOrTupleLikeType(type) - ? undefined - : getPropertyOfType(type, memberName); + return shouldTreatPropertiesOfExternalModuleAsExports(type) ? getPropertyOfType(type, memberName) : undefined; + } + function shouldTreatPropertiesOfExternalModuleAsExports(resolvedExternalModuleType) { + return !(resolvedExternalModuleType.flags & 131068 /* Primitive */ || + ts.getObjectFlags(resolvedExternalModuleType) & 1 /* Class */ || + // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path + isArrayType(resolvedExternalModuleType) || + isTupleType(resolvedExternalModuleType)); } function getExportsOfSymbol(symbol) { return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : @@ -46895,11 +48110,13 @@ var ts; if (exportStars) { var nestedSymbols = ts.createSymbolTable(); var lookupTable_1 = new ts.Map(); - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - var exportedSymbols = visit(resolvedModule); - extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + if (exportStars.declarations) { + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + } } lookupTable_1.forEach(function (_a, id) { var exportsWithDuplicate = _a.exportsWithDuplicate; @@ -46982,11 +48199,28 @@ var ts; var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); var objectLiteralContainer = getVariableDeclarationOfObjectLiteral(container, meaning); - if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { + if (enclosingDeclaration && + container.flags & getQualifiedLeftMeaning(meaning) && + getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { return ts.append(ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers), objectLiteralContainer); // This order expresses a preference for the real container if it is in scope } - var res = ts.append(ts.append(additionalContainers, container), objectLiteralContainer); - return ts.concatenate(res, reexportContainers); + // we potentially have a symbol which is a member of the instance side of something - look for a variable in scope with the container's type + // which may be acting like a namespace (eg, `Symbol` acts like a namespace when looking up `Symbol.toStringTag`) + var firstVariableMatch = !(container.flags & getQualifiedLeftMeaning(meaning)) + && container.flags & 788968 /* Type */ + && getDeclaredTypeOfSymbol(container).flags & 524288 /* Object */ + && meaning === 111551 /* Value */ + ? forEachSymbolTableInScope(enclosingDeclaration, function (t) { + return ts.forEachEntry(t, function (s) { + if (s.flags & getQualifiedLeftMeaning(meaning) && getTypeOfSymbol(s) === getDeclaredTypeOfSymbol(container)) { + return s; + } + }); + }) : undefined; + var res = firstVariableMatch ? __spreadArray(__spreadArray([firstVariableMatch], additionalContainers), [container]) : __spreadArray(__spreadArray([], additionalContainers), [container]); + res = ts.append(res, objectLiteralContainer); + res = ts.addRange(res, reexportContainers); + return res; } var candidates = ts.mapDefined(symbol.declarations, function (d) { if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) { @@ -47064,7 +48298,7 @@ var ts; var members = node.members; for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { var member = members_3[_i]; - if (member.kind === 166 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 167 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -47073,7 +48307,9 @@ var ts; var result = new Type(checker, flags); typeCount++; result.id = typeCount; - typeCatalog.push(result); + if (produceDiagnostics) { // Only record types from one checker + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.recordType(result); + } return result; } function createOriginType(flags) { @@ -47133,14 +48369,23 @@ var ts; }); return result || ts.emptyArray; } + function getNamedOrIndexSignatureMembers(members) { + var result = getNamedMembers(members); + var index = getIndexSymbolFromSymbolTable(members); + return index ? ts.concatenate(result, [index]) : result; + } function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - type.members = members; - type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members); - type.callSignatures = callSignatures; - type.constructSignatures = constructSignatures; - type.stringIndexInfo = stringIndexInfo; - type.numberIndexInfo = numberIndexInfo; - return type; + var resolved = type; + resolved.members = members; + resolved.properties = ts.emptyArray; + resolved.callSignatures = callSignatures; + resolved.constructSignatures = constructSignatures; + resolved.stringIndexInfo = stringIndexInfo; + resolved.numberIndexInfo = numberIndexInfo; + // This can loop back to getPropertyOfType() which would crash if `callSignatures` & `constructSignatures` are not initialized. + if (members !== emptySymbols) + resolved.properties = getNamedMembers(members); + return resolved; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); @@ -47163,28 +48408,28 @@ var ts; var _loop_8 = function (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { - if (result = callback(location.locals)) { + if (result = callback(location.locals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } } switch (location.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } // falls through - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var sym = getSymbolOfNode(location); // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred // to one another anyway) - if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) { + if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: // Type parameters are bound into `members` lists so they can merge across declarations // This is troublesome, since in all other respects, they behave like locals :cries: // TODO: the below is shared with similar code in `resolveName` - in fact, rephrasing all this symbol @@ -47210,7 +48455,7 @@ var ts; if (typeof state_2 === "object") return state_2.value; } - return callback(globals); + return callback(globals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true); } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace @@ -47230,11 +48475,11 @@ var ts; /** * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) */ - function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification, isLocalNameLookup) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - var result = trySymbolTable(symbols, ignoreQualification); + var result = trySymbolTable(symbols, ignoreQualification, isLocalNameLookup); visitedSymbolTables.pop(); return result; } @@ -47252,7 +48497,7 @@ var ts; !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning)); } - function trySymbolTable(symbols, ignoreQualification) { + function trySymbolTable(symbols, ignoreQualification, isLocalNameLookup) { // If symbol is directly available by its name in the symbol table if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { return [symbol]; @@ -47265,9 +48510,11 @@ var ts; && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // If we're looking up a local name to reference directly, omit namespace reexports, otherwise when we're trawling through an export list to make a dotted name, we can keep it + && (isLocalNameLookup ? !ts.some(symbolFromSymbolTable.declarations, ts.isNamespaceReexportDeclaration) : true) // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ // See similar comment in `resolveName` for details - && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 270 /* ExportSpecifier */))) { + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 271 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification); if (candidate) { @@ -47311,7 +48558,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 270 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 271 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -47326,10 +48573,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: continue; default: return false; @@ -47367,7 +48614,7 @@ var ts; return hasAccessibleDeclarations; } } - else if (allowModules) { + if (allowModules) { if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { if (shouldComputeAliasesToMakeVisible) { earlyModuleBail = true; @@ -47441,7 +48688,8 @@ var ts; return { accessibility: 2 /* CannotBeNamed */, errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), - errorModuleName: symbolToString(symbolExternalModule) + errorModuleName: symbolToString(symbolExternalModule), + errorNode: ts.isInJSFile(enclosingDeclaration) ? enclosingDeclaration : undefined, }; } } @@ -47458,10 +48706,10 @@ var ts; return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { - return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -47517,14 +48765,14 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 176 /* TypeQuery */ || + if (entityName.parent.kind === 177 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || - entityName.parent.kind === 158 /* ComputedPropertyName */) { + entityName.parent.kind === 159 /* ComputedPropertyName */) { // Typeof value meaning = 111551 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 157 /* QualifiedName */ || entityName.kind === 201 /* PropertyAccessExpression */ || - entityName.parent.kind === 260 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 158 /* QualifiedName */ || entityName.kind === 202 /* PropertyAccessExpression */ || + entityName.parent.kind === 261 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1920 /* Namespace */; @@ -47565,7 +48813,7 @@ var ts; function symbolToStringWorker(writer) { var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217 // add neverAsciiEscape for GH#39027 - var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 297 /* SourceFile */ ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true }); + var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 298 /* SourceFile */ ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); return writer; @@ -47577,10 +48825,10 @@ var ts; function signatureToStringWorker(writer) { var sigOutput; if (flags & 262144 /* WriteArrowStyleSignature */) { - sigOutput = kind === 1 /* Construct */ ? 175 /* ConstructorType */ : 174 /* FunctionType */; + sigOutput = kind === 1 /* Construct */ ? 176 /* ConstructorType */ : 175 /* FunctionType */; } else { - sigOutput = kind === 1 /* Construct */ ? 170 /* ConstructSignature */ : 169 /* CallSignature */; + sigOutput = kind === 1 /* Construct */ ? 171 /* ConstructSignature */ : 170 /* CallSignature */; } var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); @@ -47620,14 +48868,14 @@ var ts; return typeToString(type, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); } function symbolValueDeclarationIsContextSensitive(symbol) { - return symbol && symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration); + return symbol && !!symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration); } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0 /* None */; } return flags & 814775659 /* NodeBuilderFlagsMask */; } function isClassInstanceSide(type) { - return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(ts.getObjectFlags(type) & 1073741824 /* IsClassInstanceClone */)); + return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288 /* Object */) && !!(ts.getObjectFlags(type) & 16777216 /* IsClassInstanceClone */))); } function createNodeBuilder() { return { @@ -47961,7 +49209,9 @@ var ts; 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 === 221 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || + else if (symbol.flags & 32 /* Class */ + && !getBaseTypeVariableOfClass(symbol) + && !(symbol.valueDeclaration && symbol.valueDeclaration.kind === 222 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, isInstanceType); @@ -47992,7 +49242,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 297 /* SourceFile */ || declaration.parent.kind === 257 /* ModuleBlock */; + return declaration.parent.kind === 298 /* SourceFile */ || declaration.parent.kind === 258 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -48043,12 +49293,12 @@ var ts; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 174 /* FunctionType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 175 /* FunctionType */, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 175 /* ConstructorType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 176 /* ConstructorType */, context); return signatureNode; } } @@ -48228,17 +49478,17 @@ var ts; var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 169 /* CallSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 170 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; if (signature.flags & 4 /* Abstract */) continue; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 170 /* ConstructSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 171 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { var indexSignature = void 0; - if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + if (resolvedType.objectFlags & 1024 /* ReverseMapped */) { indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context, createElidedInformationPlaceholder(context)); } else { @@ -48282,15 +49532,29 @@ var ts; } return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } + function shouldUsePlaceholderForProperty(propertySymbol, context) { + var _a; + // Use placeholders for reverse mapped types we've either already descended into, or which + // are nested reverse mappings within a mapping over a non-anonymous type. The later is a restriction mostly just to + // reduce the blowup in printback size from doing, eg, a deep reverse mapping over `Window`. + // Since anonymous types usually come from expressions, this allows us to preserve the output + // for deep mappings which likely come from expressions, while truncating those parts which + // come from mappings over library functions. + return !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */) + && (ts.contains(context.reverseMappedStack, propertySymbol) + || (((_a = context.reverseMappedStack) === null || _a === void 0 ? void 0 : _a[0]) + && !(ts.getObjectFlags(ts.last(context.reverseMappedStack).propertyType) & 16 /* Anonymous */))); + } function addPropertyToElementList(propertySymbol, context, typeElements) { + var _a; var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */); - var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? + var propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */ && isLateBoundName(propertySymbol.escapedName)) { var decl = ts.first(propertySymbol.declarations); - if (hasLateBindableName(decl)) { + if (propertySymbol.declarations && hasLateBindableName(decl)) { if (ts.isBinaryExpression(decl)) { var name = ts.getNameOfDeclaration(decl); if (name && ts.isElementAccessExpression(name) && ts.isPropertyAccessEntityNameExpression(name.argumentExpression)) { @@ -48302,29 +49566,34 @@ var ts; } } } - context.enclosingDeclaration = saveEnclosingDeclaration; + context.enclosingDeclaration = propertySymbol.valueDeclaration || ((_a = propertySymbol.declarations) === null || _a === void 0 ? void 0 : _a[0]) || saveEnclosingDeclaration; var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context); + context.enclosingDeclaration = saveEnclosingDeclaration; context.approximateLength += (ts.symbolName(propertySymbol).length + 1); var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */); for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { var signature = signatures_1[_i]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 164 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken }); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 165 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken }); typeElements.push(preserveCommentsOn(methodDeclaration)); } } else { - var savedFlags = context.flags; - context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; var propertyTypeNode = void 0; - if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + if (shouldUsePlaceholderForProperty(propertySymbol, context)) { propertyTypeNode = createElidedInformationPlaceholder(context); } else { + if (propertyIsReverseMapped) { + context.reverseMappedStack || (context.reverseMappedStack = []); + context.reverseMappedStack.push(propertySymbol); + } propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); + if (propertyIsReverseMapped) { + context.reverseMappedStack.pop(); + } } - context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(142 /* ReadonlyKeyword */)] : undefined; if (modifiers) { context.approximateLength += 9; @@ -48333,9 +49602,10 @@ var ts; typeElements.push(preserveCommentsOn(propertySignature)); } function preserveCommentsOn(node) { - if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 333 /* JSDocPropertyTag */; })) { - var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 333 /* JSDocPropertyTag */; }); - var commentText = d.comment; + var _a; + if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 337 /* JSDocPropertyTag */; })) { + var d = (_a = propertySymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 337 /* JSDocPropertyTag */; }); + var commentText = ts.getTextOfJSDocComment(d.comment); if (commentText) { ts.setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]); } @@ -48364,25 +49634,25 @@ var ts; var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */); /** Map from type reference identifier text to [type, index in `result` where the type node is] */ var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; - var result_4 = []; + var result_5 = []; var i = 0; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var type = types_2[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result_4.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + result_5.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result_4.push(typeNode_1); + result_5.push(typeNode_1); } break; } context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result_4.push(typeNode); + result_5.push(typeNode); if (seenNames && ts.isIdentifierTypeReference(typeNode)) { - seenNames.add(typeNode.typeName.escapedText, [type, result_4.length - 1]); + seenNames.add(typeNode.typeName.escapedText, [type, result_5.length - 1]); } } } @@ -48404,13 +49674,13 @@ var ts; })) { for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { var _a = types_3[_i], type = _a[0], resultIndex = _a[1]; - result_4[resultIndex] = typeToTypeNodeHelper(type, context); + result_5[resultIndex] = typeToTypeNodeHelper(type, context); } } }); context.flags = saveContextFlags; } - return result_4; + return result_5; } } function typesAreSameReference(a, b) { @@ -48452,7 +49722,7 @@ var ts; } var expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0]; // If the expanded parameter list had a variadic in a non-trailing position, don't expand it - var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 166 /* Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); + var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 167 /* Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -48479,25 +49749,25 @@ var ts; } } var modifiers = options === null || options === void 0 ? void 0 : options.modifiers; - if ((kind === 175 /* ConstructorType */) && signature.flags & 4 /* Abstract */) { + if ((kind === 176 /* ConstructorType */) && signature.flags & 4 /* Abstract */) { var flags = ts.modifiersToFlags(modifiers); modifiers = ts.factory.createModifiersFromModifierFlags(flags | 128 /* Abstract */); } context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum - var node = kind === 169 /* CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : - kind === 170 /* ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : - kind === 164 /* MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : - kind === 165 /* MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === 166 /* Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) : - kind === 167 /* GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : - kind === 168 /* SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : - kind === 171 /* IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) : - kind === 308 /* JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : - kind === 174 /* FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 175 /* ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 251 /* FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === 208 /* FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : - kind === 209 /* ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) : + var node = kind === 170 /* CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : + kind === 171 /* ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : + kind === 165 /* MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : + kind === 166 /* MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 167 /* Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) : + kind === 168 /* GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : + kind === 169 /* SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : + kind === 172 /* IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) : + kind === 309 /* JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : + kind === 175 /* FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : + kind === 176 /* ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : + kind === 252 /* FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 209 /* FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : + kind === 210 /* ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) : ts.Debug.assertNever(kind); if (typeArguments) { node.typeArguments = ts.factory.createNodeArray(typeArguments); @@ -48519,9 +49789,9 @@ var ts; return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 160 /* Parameter */); + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 161 /* Parameter */); if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 326 /* JSDocParameterTag */); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 330 /* JSDocParameterTag */); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -48536,7 +49806,7 @@ var ts; var dotDotDotToken = isRest ? ts.factory.createToken(25 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 78 /* Identifier */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : - parameterDeclaration.name.kind === 157 /* QualifiedName */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 158 /* QualifiedName */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); @@ -48701,11 +49971,11 @@ var ts; } function getSpecifierForModuleSymbol(symbol, context) { var _a; - var file = ts.getDeclarationOfKind(symbol, 297 /* SourceFile */); + var file = ts.getDeclarationOfKind(symbol, 298 /* SourceFile */); if (!file) { var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); }); if (equivalentFileSymbol) { - file = ts.getDeclarationOfKind(equivalentFileSymbol, 297 /* SourceFile */); + file = ts.getDeclarationOfKind(equivalentFileSymbol, 298 /* SourceFile */); } } if (file && file.moduleName !== undefined) { @@ -48716,8 +49986,8 @@ var ts; if (context.tracker.trackReferencedAmbientModule) { var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); if (ts.length(ambientDecls)) { - for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { - var decl = ambientDecls_1[_i]; + for (var _i = 0, _b = ambientDecls; _i < _b.length; _i++) { + var decl = _b[_i]; context.tracker.trackReferencedAmbientModule(decl, symbol); } } @@ -48744,7 +50014,7 @@ var ts; // specifier preference var moduleResolverHost = context.tracker.moduleResolverHost; var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; - specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "project-relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); (_a = links.specifierCache) !== null && _a !== void 0 ? _a : (links.specifierCache = new ts.Map()); links.specifierCache.set(contextFile.path, specifier); } @@ -48888,7 +50158,7 @@ var ts; var chain = lookupSymbolChain(symbol, context, meaning); if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) { + && !(context.flags & 65536 /* AllowQualifiedNameInPlaceOfIdentifier */)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); @@ -48968,9 +50238,6 @@ var ts; if (fromNameType) { return fromNameType; } - if (ts.isKnownSymbol(symbol)) { - return ts.factory.createComputedPropertyName(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("Symbol"), symbol.escapedName.substr(3))); - } var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName); var stringNamed = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isStringNamed); return createPropertyNameNodeForIdentifierOrLiteral(rawName, stringNamed, singleQuote); @@ -49037,13 +50304,13 @@ var ts; function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { if (type !== errorType && enclosingDeclaration) { var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation) && !ts.isGetAccessorDeclaration(declWithExistingAnnotation)) { // try to reuse the existing annotation var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { - var result_5 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); - if (result_5) { - return result_5; + var result_6 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_6) { + return result_6; } } } @@ -49060,10 +50327,14 @@ var ts; function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { if (type !== errorType && context.enclosingDeclaration) { var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); - if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { - var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); - if (result) { - return result; + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation) { + var annotated = getTypeFromTypeNode(annotation); + var thisInstantiated = annotated.flags & 262144 /* TypeParameter */ && annotated.isThisType ? instantiateType(annotated, signature.mapper) : annotated; + if (thisInstantiated === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } } } } @@ -49107,7 +50378,7 @@ var ts; return transformed === existing ? ts.setTextRange(ts.factory.cloneNode(existing), existing) : transformed; function visitExistingNodeTreeSymbols(node) { // We don't _actually_ support jsdoc namepath types, emit `any` instead - if (ts.isJSDocAllType(node) || node.kind === 310 /* JSDocNamepathType */) { + if (ts.isJSDocAllType(node) || node.kind === 311 /* JSDocNamepathType */) { return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } if (ts.isJSDocUnknownType(node)) { @@ -49226,8 +50497,8 @@ var ts; } } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { - var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 165 /* MethodDeclaration */, /*useAcessors*/ true); - var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 164 /* MethodSignature */, /*useAcessors*/ false); + var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 166 /* MethodDeclaration */, /*useAcessors*/ true); + var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 165 /* MethodSignature */, /*useAcessors*/ false); // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of // declaration mapping // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration @@ -49239,7 +50510,7 @@ var ts; var deferredPrivatesStack = []; var oldcontext = context; context = __assign(__assign({}, oldcontext), { usedSymbolNames: new ts.Set(oldcontext.usedSymbolNames), remappedSymbolNames: new ts.Map(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { - var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false); + var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeAliases*/ false); if (accessibleResult.accessibility === 0 /* Accessible */) { // Lookup the root symbol of the chain of refs we'll use to access it and serialize it var chain = lookupSymbolChainWorker(sym, context, meaning); @@ -49448,6 +50719,7 @@ var ts; // If it's a class/interface/function: emit a class/interface/function with a `default` modifier // These forms can merge, eg (`export default 12; export default interface A {}`) function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) { + var _a, _b; var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName); var isDefault = symbol.escapedName === "default" /* Default */; if (isPrivate && !(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) { @@ -49506,9 +50778,9 @@ var ts; if (textRange && ts.isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) { textRange = textRange.parent.parent; } - var propertyAccessRequire = ts.find(symbol.declarations, ts.isPropertyAccessExpression); + var propertyAccessRequire = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isPropertyAccessExpression); if (propertyAccessRequire && ts.isBinaryExpression(propertyAccessRequire.parent) && ts.isIdentifier(propertyAccessRequire.parent.right) - && type.symbol && ts.isSourceFile(type.symbol.valueDeclaration)) { + && ((_b = type.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration) && ts.isSourceFile(type.symbol.valueDeclaration)) { var alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right; addResult(ts.factory.createExportDeclaration( /*decorators*/ undefined, @@ -49558,7 +50830,10 @@ var ts; serializeEnum(symbol, symbolName, modifierFlags); } if (symbol.flags & 32 /* Class */) { - if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { + if (symbol.flags & 4 /* Property */ + && symbol.valueDeclaration + && ts.isBinaryExpression(symbol.valueDeclaration.parent) + && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members, // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today. @@ -49584,12 +50859,14 @@ var ts; if (symbol.flags & 8388608 /* ExportStar */) { // synthesize export * from "moduleReference" // Straightforward - only one thing to do - make an export declaration - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - if (!resolvedModule) - continue; - addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */); + if (symbol.declarations) { + for (var _i = 0, _c = symbol.declarations; _i < _c.length; _i++) { + var node = _c[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + if (!resolvedModule) + continue; + addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */); + } } } if (needsPostExportDefault) { @@ -49627,15 +50904,16 @@ var ts; function addResult(node, additionalModifierFlags) { if (ts.canHaveModifiers(node)) { var newModifierFlags = 0 /* None */; + var enclosingDeclaration_1 = context.enclosingDeclaration && + (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 /* Export */ && - context.enclosingDeclaration && - (isExportingScope(context.enclosingDeclaration) || ts.isModuleDeclaration(context.enclosingDeclaration)) && + enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && canHaveExportModifier(node)) { // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private newModifierFlags |= 1 /* Export */; } if (addingDeclare && !(newModifierFlags & 1 /* Export */) && - (!context.enclosingDeclaration || !(context.enclosingDeclaration.flags & 8388608 /* Ambient */)) && + (!enclosingDeclaration_1 || !(enclosingDeclaration_1.flags & 8388608 /* Ambient */)) && (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) { // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope newModifierFlags |= 2 /* Ambient */; @@ -49650,19 +50928,23 @@ var ts; results.push(node); } function serializeTypeAlias(symbol, symbolName, modifierFlags) { + var _a; var aliasType = getDeclaredTypeOfTypeAlias(symbol); var typeParams = getSymbolLinks(symbol).typeParameters; var typeParamDecls = ts.map(typeParams, function (p) { return typeParameterToDeclaration(p, context); }); - var jsdocAliasDecl = ts.find(symbol.declarations, ts.isJSDocTypeAlias); - var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined; + var jsdocAliasDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isJSDocTypeAlias); + var commentText = ts.getTextOfJSDocComment(jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined); var oldFlags = context.flags; context.flags |= 8388608 /* InTypeAlias */; + var oldEnclosingDecl = context.enclosingDeclaration; + context.enclosingDeclaration = jsdocAliasDecl; var typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; + context.enclosingDeclaration = oldEnclosingDecl; } function serializeInterface(symbol, symbolName, modifierFlags) { var interfaceType = getDeclaredTypeOfClassOrInterface(symbol); @@ -49671,8 +50953,8 @@ var ts; var baseTypes = getBaseTypes(interfaceType); var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined; var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); }); - var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 169 /* CallSignature */); - var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 170 /* ConstructSignature */); + var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 170 /* CallSignature */); + var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 171 /* ConstructSignature */); var indexSignatures = serializeIndexSignatures(interfaceType, baseType); var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(93 /* ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551 /* Value */); }))]; addResult(ts.factory.createInterfaceDeclaration( @@ -49741,9 +51023,8 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; // Each overload becomes a separate function declaration, in order - var decl = signatureToSignatureDeclarationHelper(sig, 251 /* FunctionDeclaration */, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled }); - // for expressions assigned to `var`s, use the `var` as the text range - addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags); + var decl = signatureToSignatureDeclarationHelper(sig, 252 /* FunctionDeclaration */, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled }); + addResult(ts.setTextRange(decl, getSignatureTextRangeLocation(sig)), modifierFlags); } // Module symbol emit will take care of module-y members, provided it has exports if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) { @@ -49751,6 +51032,18 @@ var ts; serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true); } } + function getSignatureTextRangeLocation(signature) { + if (signature.declaration && signature.declaration.parent) { + if (ts.isBinaryExpression(signature.declaration.parent) && ts.getAssignmentDeclarationKind(signature.declaration.parent) === 5 /* Property */) { + return signature.declaration.parent; + } + // for expressions assigned to `var`s, use the `var` as the text range + if (ts.isVariableDeclaration(signature.declaration.parent) && signature.declaration.parent.parent) { + return signature.declaration.parent.parent; + } + } + return signature.declaration; + } function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) { if (ts.length(props)) { var localVsRemoteMap = ts.arrayToMultiMap(props, function (p) { @@ -49837,8 +51130,8 @@ var ts; return undefined; } function serializeAsClass(symbol, localName, modifierFlags) { - var _a; - var originalDecl = ts.find(symbol.declarations, ts.isClassLike); + var _a, _b; + var originalDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isClassLike); var oldEnclosing = context.enclosingDeclaration; context.enclosingDeclaration = originalDecl || oldEnclosing; var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -49849,7 +51142,7 @@ var ts; var implementsExpressions = originalImplements && sanitizeJSDocImplements(originalImplements) || ts.mapDefined(getImplementsTypes(classType), serializeImplementedType); var staticType = getTypeOfSymbol(symbol); - var isClass = !!((_a = staticType.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration) && ts.isClassLike(staticType.symbol.valueDeclaration); + var isClass = !!((_b = staticType.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration) && ts.isClassLike(staticType.symbol.valueDeclaration); var staticBaseType = isClass ? getBaseConstructorTypeOfClass(staticType) : anyType; @@ -49860,14 +51153,14 @@ var ts; // a union/intersection base type, but inherited properties // don't matter here. var valueDecl = s.valueDeclaration; - return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); + return !!valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); }); var hasPrivateIdentifier = ts.some(symbolProps, function (s) { // `valueDeclaration` could be undefined if inherited from // a union/intersection base type, but inherited properties // don't matter here. var valueDecl = s.valueDeclaration; - return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); + return !!valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); }); // Boil down all private properties into a single one. var privateProperties = hasPrivateIdentifier ? @@ -49890,7 +51183,7 @@ var ts; !ts.some(getSignaturesOfType(staticType, 1 /* Construct */)); var constructors = isNonConstructableClassLikeInJsFile ? [ts.factory.createConstructorDeclaration(/*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(8 /* Private */), [], /*body*/ undefined)] : - serializeSignatures(1 /* Construct */, staticType, staticBaseType, 166 /* Constructor */); + serializeSignatures(1 /* Construct */, staticType, staticBaseType, 167 /* Constructor */); var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); context.enclosingDeclaration = oldEnclosing; addResult(ts.setTextRange(ts.factory.createClassDeclaration( @@ -49917,8 +51210,8 @@ var ts; var targetName = getInternalSymbolName(target, verbatimTargetName); includePrivateSymbol(target); // the target may be within the same scope - attempt to serialize it first switch (node.kind) { - case 198 /* BindingElement */: - if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 249 /* VariableDeclaration */) { + case 199 /* BindingElement */: + if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 250 /* VariableDeclaration */) { // const { SomeClass } = require('./lib'); var specifier_1 = getSpecifierForModuleSymbol(target.parent || target, context); // './lib' var propertyName = node.propertyName; @@ -49930,13 +51223,13 @@ var ts; // We don't know how to serialize this (nested?) binding element ts.Debug.failBadSyntaxKind(((_c = node.parent) === null || _c === void 0 ? void 0 : _c.parent) || node, "Unhandled binding element grandparent kind in declaration serialization"); break; - case 289 /* ShorthandPropertyAssignment */: - if (((_e = (_d = node.parent) === null || _d === void 0 ? void 0 : _d.parent) === null || _e === void 0 ? void 0 : _e.kind) === 216 /* BinaryExpression */) { + case 290 /* ShorthandPropertyAssignment */: + if (((_e = (_d = node.parent) === null || _d === void 0 ? void 0 : _d.parent) === null || _e === void 0 ? void 0 : _e.kind) === 217 /* BinaryExpression */) { // module.exports = { SomeClass } serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), targetName); } break; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: // commonjs require: const x = require('y') if (ts.isPropertyAccessExpression(node.initializer)) { // const x = require('y').z @@ -49956,7 +51249,7 @@ var ts; break; } // else fall through and treat commonjs require just like import= - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // This _specifically_ only exists to handle json declarations - where we make aliases, but since // we emit no declarations for the json document, must not refer to it in the declarations if (target.escapedName === "export=" /* ExportEquals */ && ts.some(target.declarations, ts.isJsonSourceFile)) { @@ -49973,13 +51266,13 @@ var ts; ? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false) : ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)))), isLocalImport ? modifierFlags : 0 /* None */); break; - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: // export as namespace foo // TODO: Not part of a file's local or export symbol tables // Is bound into file.symbol.globalExports instead, which we don't currently traverse addResult(ts.factory.createNamespaceExportDeclaration(ts.idText(node.name)), 0 /* None */); break; - case 262 /* ImportClause */: + case 263 /* ImportClause */: addResult(ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, ts.factory.createIdentifier(localName), /*namedBindings*/ undefined), @@ -49988,18 +51281,18 @@ var ts; // In such cases, the `target` refers to the module itself already ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: addResult(ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */); break; - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: addResult(ts.factory.createExportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */); break; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: addResult(ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause( @@ -50008,7 +51301,7 @@ var ts; ts.factory.createImportSpecifier(localName !== verbatimTargetName ? ts.factory.createIdentifier(verbatimTargetName) : undefined, ts.factory.createIdentifier(localName)) ])), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: // does not use localName because the symbol name in this case refers to the name in the exports table, // which we must exactly preserve var specifier = node.parent.parent.moduleSpecifier; @@ -50016,12 +51309,12 @@ var ts; // another file serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.factory.createStringLiteral(specifier.text) : undefined); break; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: serializeMaybeAliasAssignment(symbol); break; - case 216 /* BinaryExpression */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 217 /* BinaryExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: // Could be best encoded as though an export specifier or as though an export assignment // If name is default or export=, do an export assignment // Otherwise do an export specifier @@ -50155,6 +51448,7 @@ var ts; } function makeSerializePropertySymbol(createProperty, methodKind, useAccessors) { return function serializePropertySymbol(p, isStatic, baseType) { + var _a, _b, _c, _d, _e; var modifierFlags = ts.getDeclarationModifierFlagsFromSymbol(p); var isPrivate = !!(modifierFlags & 8 /* Private */); if (isStatic && (p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */))) { @@ -50171,7 +51465,7 @@ var ts; } var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0); var name = getPropertyNameNodeForSymbol(p, context); - var firstPropertyLikeDecl = ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression)); + var firstPropertyLikeDecl = (_a = p.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression)); if (p.flags & 98304 /* Accessor */ && useAccessors) { var result = []; if (p.flags & 65536 /* SetAccessor */) { @@ -50181,13 +51475,13 @@ var ts; /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "arg", /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], - /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl)); + /*body*/ undefined), ((_b = p.declarations) === null || _b === void 0 ? void 0 : _b.find(ts.isSetAccessor)) || firstPropertyLikeDecl)); } if (p.flags & 32768 /* GetAccessor */) { var isPrivate_1 = modifierFlags & 8 /* Private */; result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration( /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), - /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl)); + /*body*/ undefined), ((_c = p.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isGetAccessor)) || firstPropertyLikeDecl)); } return result; } @@ -50198,7 +51492,7 @@ var ts; /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ - /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl); + /*initializer*/ undefined), ((_d = p.declarations) === null || _d === void 0 ? void 0 : _d.find(ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration))) || firstPropertyLikeDecl); } if (p.flags & (8192 /* Method */ | 16 /* Function */)) { var type = getTypeOfSymbol(p); @@ -50207,7 +51501,7 @@ var ts; return ts.setTextRange(createProperty( /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, /*type*/ undefined, - /*initializer*/ undefined), ts.find(p.declarations, ts.isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations[0]); + /*initializer*/ undefined), ((_e = p.declarations) === null || _e === void 0 ? void 0 : _e.find(ts.isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); } var results_1 = []; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { @@ -50218,7 +51512,8 @@ var ts; questionToken: p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, modifiers: flag ? ts.factory.createModifiersFromModifierFlags(flag) : undefined }); - results_1.push(ts.setTextRange(decl, sig.declaration)); + var location = sig.declaration && ts.isPrototypePropertyAssignment(sig.declaration.parent) ? sig.declaration.parent : sig.declaration; + results_1.push(ts.setTextRange(decl, location)); } return results_1; } @@ -50434,9 +51729,9 @@ var ts; return "public"; } function getTypeAliasForTypeLiteral(type) { - if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { + if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */ && type.symbol.declarations) { var node = ts.walkUpParenthesizedTypes(type.symbol.declarations[0].parent); - if (node.kind === 254 /* TypeAliasDeclaration */) { + if (node.kind === 255 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -50444,11 +51739,11 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 257 /* ModuleBlock */ && + node.parent.kind === 258 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } function isDefaultBindingContext(location) { - return location.kind === 297 /* SourceFile */ || ts.isAmbientModule(location); + return location.kind === 298 /* SourceFile */ || ts.isAmbientModule(location); } function getNameOfSymbolFromNameType(symbol, context) { var nameType = getSymbolLinks(symbol).nameType; @@ -50507,17 +51802,17 @@ var ts; if (!declaration) { declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway } - if (declaration.parent && declaration.parent.kind === 249 /* VariableDeclaration */) { + if (declaration.parent && declaration.parent.kind === 250 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } switch (declaration.kind) { - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { context.encounteredError = true; } - return declaration.kind === 221 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; + return declaration.kind === 222 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } var name = getNameOfSymbolFromNameType(symbol, context); @@ -50534,28 +51829,28 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: - case 325 /* JSDocEnumTag */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: + case 329 /* JSDocEnumTag */: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // falls through - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 251 /* FunctionDeclaration */: - case 255 /* EnumDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 252 /* FunctionDeclaration */: + case 256 /* EnumDeclaration */: + case 261 /* ImportEqualsDeclaration */: // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; @@ -50563,55 +51858,55 @@ var ts; var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 260 /* ImportEqualsDeclaration */ && parent.kind !== 297 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) { + !(node.kind !== 261 /* ImportEqualsDeclaration */ && parent.kind !== 298 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible return isDeclarationVisible(parent); - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasEffectiveModifier(node, 8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so: // falls through - case 166 /* Constructor */: - case 170 /* ConstructSignature */: - case 169 /* CallSignature */: - case 171 /* IndexSignature */: - case 160 /* Parameter */: - case 257 /* ModuleBlock */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 177 /* TypeLiteral */: - case 173 /* TypeReference */: - case 178 /* ArrayType */: - case 179 /* TupleType */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 186 /* ParenthesizedType */: - case 192 /* NamedTupleMember */: + case 167 /* Constructor */: + case 171 /* ConstructSignature */: + case 170 /* CallSignature */: + case 172 /* IndexSignature */: + case 161 /* Parameter */: + case 258 /* ModuleBlock */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 178 /* TypeLiteral */: + case 174 /* TypeReference */: + case 179 /* ArrayType */: + case 180 /* TupleType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 187 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: return isDeclarationVisible(node.parent); // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: + case 266 /* ImportSpecifier */: return false; // Type parameters are always visible - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: // Source file and namespace export are always visible // falls through - case 297 /* SourceFile */: - case 259 /* NamespaceExportDeclaration */: + case 298 /* SourceFile */: + case 260 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return false; default: return false; @@ -50620,10 +51915,10 @@ var ts; } function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 266 /* ExportAssignment */) { + if (node.parent && node.parent.kind === 267 /* ExportAssignment */) { exportSymbol = resolveName(node, node.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } - else if (node.parent.kind === 270 /* ExportSpecifier */) { + else if (node.parent.kind === 271 /* ExportSpecifier */) { exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; @@ -50728,12 +52023,12 @@ var ts; function getDeclarationContainer(node) { return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 249 /* VariableDeclaration */: - case 250 /* VariableDeclarationList */: - case 265 /* ImportSpecifier */: - case 264 /* NamedImports */: - case 263 /* NamespaceImport */: - case 262 /* ImportClause */: + case 250 /* VariableDeclaration */: + case 251 /* VariableDeclarationList */: + case 266 /* ImportSpecifier */: + case 265 /* NamedImports */: + case 264 /* NamespaceImport */: + case 263 /* ImportClause */: return false; default: return true; @@ -50796,9 +52091,16 @@ var ts; var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= 131072 /* ObjectRestType */; + result.objectFlags |= 8388608 /* ObjectRestType */; return result; } + function isGenericTypeWithUndefinedConstraint(type) { + return !!(type.flags & 465829888 /* Instantiable */) && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 32768 /* Undefined */); + } + function getNonUndefinedType(type) { + var typeOrConstraint = someType(type, isGenericTypeWithUndefinedConstraint) ? mapType(type, function (t) { return t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type; + return getTypeWithFacts(typeOrConstraint, 524288 /* NEUndefined */); + } // Determine the control flow type associated with a destructuring declaration or assignment. The following // forms of destructuring are possible: // let { x } = obj; // BindingElement @@ -50833,23 +52135,23 @@ var ts; function getParentElementAccess(node) { var ancestor = node.parent.parent; switch (ancestor.kind) { - case 198 /* BindingElement */: - case 288 /* PropertyAssignment */: + case 199 /* BindingElement */: + case 289 /* PropertyAssignment */: return getSyntheticElementAccess(ancestor); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return getSyntheticElementAccess(node.parent); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return ancestor.initializer; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return ancestor.right; } } function getDestructuringPropertyName(node) { var parent = node.parent; - if (node.kind === 198 /* BindingElement */ && parent.kind === 196 /* ObjectBindingPattern */) { + if (node.kind === 199 /* BindingElement */ && parent.kind === 197 /* ObjectBindingPattern */) { return getLiteralPropertyNameText(node.propertyName || node.name); } - if (node.kind === 288 /* PropertyAssignment */ || node.kind === 289 /* ShorthandPropertyAssignment */) { + if (node.kind === 289 /* PropertyAssignment */ || node.kind === 290 /* ShorthandPropertyAssignment */) { return getLiteralPropertyNameText(node.name); } return "" + parent.elements.indexOf(node); @@ -50875,7 +52177,7 @@ var ts; parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */); } var type; - if (pattern.kind === 196 /* ObjectBindingPattern */) { + if (pattern.kind === 197 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { parentType = getReducedType(parentType); if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { @@ -50895,7 +52197,7 @@ var ts; // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name = declaration.propertyName || declaration.name; var indexType = getLiteralTypeFromPropertyName(name); - var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */), declaration.name); + var declaredType = getIndexedAccessType(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */); type = getFlowTypeOfDestructuring(declaration, declaredType); } } @@ -50916,7 +52218,7 @@ var ts; else if (isArrayLikeType(parentType)) { var indexType = getLiteralType(index_2); var accessFlags = hasDefaultValue(declaration) ? 8 /* NoTupleBoundsCheck */ : 0; - var declaredType = getConstraintForLocation(getIndexedAccessTypeOrUndefined(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, declaration.name, accessFlags | 16 /* ExpressionPosition */) || errorType, declaration.name); + var declaredType = getIndexedAccessTypeOrUndefined(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, declaration.name, accessFlags | 16 /* ExpressionPosition */) || errorType; type = getFlowTypeOfDestructuring(declaration, declaredType); } else { @@ -50929,11 +52231,9 @@ var ts; if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ? - getTypeWithFacts(type, 524288 /* NEUndefined */) : - type; + return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ? getNonUndefinedType(type) : type; } - return widenTypeInferredFromInitializer(declaration, getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), checkDeclarationInitializer(declaration)], 2 /* Subtype */)); + return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration)], 2 /* Subtype */)); } function getTypeForDeclarationFromJSDocComment(declaration) { var jsdocType = ts.getJSDocType(declaration); @@ -50948,7 +52248,7 @@ var ts; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 199 /* ArrayLiteralExpression */ && expr.elements.length === 0; + return expr.kind === 200 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { if (optional === void 0) { optional = true; } @@ -50958,11 +52258,11 @@ var ts; function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 238 /* ForInStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForInStatement */) { var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 240 /* ForOfStatement */) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -50999,8 +52299,8 @@ var ts; if (ts.isParameter(declaration)) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 168 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { - var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 167 /* GetAccessor */); + if (func.kind === 169 /* SetAccessor */ && hasBindableName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 168 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -51071,7 +52371,7 @@ var ts; links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && ts.every(symbol.declarations, function (declaration) { return ts.isBinaryExpression(declaration) && isPossiblyAliasedThisProperty(declaration) && - (declaration.left.kind !== 202 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && + (declaration.left.kind !== 203 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ undefined, declaration, symbol, declaration); }); } @@ -51087,13 +52387,33 @@ var ts; !declaration.initializer && (noImplicitAny || ts.isInJSFile(declaration)); } function getDeclaringConstructor(symbol) { + if (!symbol.declarations) { + return; + } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var container = ts.getThisContainer(declaration, /*includeArrowFunctions*/ false); - if (container && (container.kind === 166 /* Constructor */ || isJSConstructor(container))) { + if (container && (container.kind === 167 /* Constructor */ || isJSConstructor(container))) { return container; } } + ; + } + /** Create a synthetic property access flow node after the last statement of the file */ + function getFlowTypeFromCommonJSExport(symbol) { + var file = ts.getSourceFileOfNode(symbol.declarations[0]); + var accessName = ts.unescapeLeadingUnderscores(symbol.escapedName); + var areAllModuleExports = symbol.declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && ts.isModuleExportsAccessExpression(d.expression); }); + var reference = areAllModuleExports + ? ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("module"), ts.factory.createIdentifier("exports")), accessName) + : ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("exports"), accessName); + if (areAllModuleExports) { + ts.setParent(reference.expression.expression, reference.expression); + } + ts.setParent(reference.expression, reference); + ts.setParent(reference, file); + reference.flowNode = file.endFlowNode; + return getFlowTypeOfReference(reference, autoType, undefinedType); } function getFlowTypeInConstructor(symbol, constructor) { var accessName = ts.startsWith(symbol.escapedName, "__#") @@ -51111,7 +52431,10 @@ var ts; return everyType(flowType, isNullableType) ? undefined : convertAutoToAny(flowType); } function getFlowTypeOfProperty(reference, prop) { - var initialType = prop && (!isAutoTypedProperty(prop) || ts.getEffectiveModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType; + var initialType = (prop === null || prop === void 0 ? void 0 : prop.valueDeclaration) + && (!isAutoTypedProperty(prop) || ts.getEffectiveModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) + && getTypeOfPropertyInBaseClass(prop) + || undefinedType; return getFlowTypeOfReference(reference, autoType, initialType); } function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) { @@ -51122,7 +52445,7 @@ var ts; if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + var containerObjectType = symbol.valueDeclaration && getJSContainerObjectType(symbol.valueDeclaration, symbol, container); return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var type; @@ -51134,40 +52457,42 @@ var ts; type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol)); } if (!type) { - var jsdocType = void 0; var types = void 0; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : - ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : - undefined; - if (!expression) { - continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere - } - var kind = ts.isAccessExpression(expression) - ? ts.getAssignmentDeclarationPropertyAccessKind(expression) - : ts.getAssignmentDeclarationKind(expression); - if (kind === 4 /* ThisProperty */ || ts.isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) { - if (isDeclarationInConstructor(expression)) { - definedInConstructor = true; + if (symbol.declarations) { + var jsdocType = void 0; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : + ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere } - else { - definedInMethod = true; + var kind = ts.isAccessExpression(expression) + ? ts.getAssignmentDeclarationPropertyAccessKind(expression) + : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */ || ts.isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + if (!ts.isCallExpression(expression)) { + jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } - if (!ts.isCallExpression(expression)) { - jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); - } - if (!jsdocType) { - (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); - } + type = jsdocType; } - type = jsdocType; if (!type) { if (!ts.length(types)) { return errorType; // No types from any declarations :( } - var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; + var constructorTypes = definedInConstructor && symbol.declarations ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { var propType = getTypeOfPropertyInBaseClass(symbol); @@ -51181,7 +52506,7 @@ var ts; } } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); - if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { + if (symbol.valueDeclaration && filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } @@ -51205,10 +52530,11 @@ var ts; mergeSymbolTable(exports, s.exports); } var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - type.objectFlags |= 16384 /* JSLiteral */; + type.objectFlags |= 8192 /* JSLiteral */; return type; } function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) { + var _a; var typeNode = ts.getEffectiveTypeAnnotationNode(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -51219,7 +52545,7 @@ var ts; errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type); } } - if (symbol.parent) { + if ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) { var typeNode_2 = ts.getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration); if (typeNode_2) { return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode_2), symbol.escapedName); @@ -51283,7 +52609,7 @@ var ts; // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because // it's unclear what that's supposed to mean, so it's probably a mistake. - if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { + if (s.valueDeclaration && exportedMember.valueDeclaration && ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName); var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration; ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName)); @@ -51305,9 +52631,9 @@ var ts; }); var result = createAnonymousType(initialSize !== members_4.size ? undefined : exportedType.symbol, // Only set the type's symbol if it looks to be the same as the original type members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo); - result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + result.objectFlags |= (ts.getObjectFlags(type) & 8192 /* JSLiteral */); // Propagate JSLiteral flag if (result.symbol && result.symbol.flags & 32 /* Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { - result.objectFlags |= 1073741824 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type + result.objectFlags |= 16777216 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type } return result; } @@ -51326,9 +52652,9 @@ var ts; var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. // Function expressions that are assigned to the prototype count as methods. - return thisContainer.kind === 166 /* Constructor */ || - thisContainer.kind === 251 /* FunctionDeclaration */ || - (thisContainer.kind === 208 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + return thisContainer.kind === 167 /* Constructor */ || + thisContainer.kind === 252 /* FunctionDeclaration */ || + (thisContainer.kind === 209 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); } function getConstructorDefinedThisAssignmentTypes(types, declarations) { ts.Debug.assert(types.length === declarations.length); @@ -51366,7 +52692,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -51390,7 +52716,7 @@ var ts; result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -51398,7 +52724,7 @@ var ts; function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - var restElement = lastElement && lastElement.kind === 198 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : undefined; + var restElement = lastElement && lastElement.kind === 199 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : undefined; if (elements.length === 0 || elements.length === 1 && restElement) { return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } @@ -51409,7 +52735,7 @@ var ts; if (includePatternInType) { result = cloneTypeReference(result); result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -51423,7 +52749,7 @@ var ts; function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { if (includePatternInType === void 0) { includePatternInType = false; } if (reportErrors === void 0) { reportErrors = false; } - return pattern.kind === 196 /* ObjectBindingPattern */ + return pattern.kind === 197 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -51439,8 +52765,17 @@ var ts; function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors); } + function isGlobalSymbolConstructor(node) { + var symbol = getSymbolOfNode(node); + var globalSymbol = getGlobalESSymbolConstructorTypeSymbol(/*reportErrors*/ false); + return globalSymbol && symbol && symbol === globalSymbol; + } function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) { if (type) { + // TODO: If back compat with pre-3.0/4.0 libs isn't required, remove the following SymbolConstructor special case transforming `symbol` into `unique symbol` + if (type.flags & 4096 /* ESSymbol */ && isGlobalSymbolConstructor(declaration.parent)) { + type = getESSymbolLikeTypeForNode(declaration); + } if (reportErrors) { reportErrorsFromWidening(declaration, type); } @@ -51462,7 +52797,7 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 160 /* Parameter */ ? root.parent : root; + var memberDeclaration = root.kind === 161 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function tryGetTypeFromEffectiveTypeNode(declaration) { @@ -51493,19 +52828,31 @@ var ts; if (symbol === requireSymbol) { return anyType; } - if (symbol.flags & 134217728 /* ModuleExports */) { + if (symbol.flags & 134217728 /* ModuleExports */ && symbol.valueDeclaration) { var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var result = createSymbol(fileSymbol.flags, "exports"); + result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : []; + result.parent = symbol; + result.target = fileSymbol; + if (fileSymbol.valueDeclaration) + result.valueDeclaration = fileSymbol.valueDeclaration; + if (fileSymbol.members) + result.members = new ts.Map(fileSymbol.members); + if (fileSymbol.exports) + result.exports = new ts.Map(fileSymbol.exports); var members = ts.createSymbolTable(); - members.set("exports", fileSymbol); + members.set("exports", result); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); } // Handle catch clause variables + ts.Debug.assertIsDefined(symbol.valueDeclaration); var declaration = symbol.valueDeclaration; if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { - var decl = declaration; - if (!decl.type) + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode === undefined) { return anyType; - var type_1 = getTypeOfNode(decl.type); + } + var type_1 = getTypeOfNode(typeNode); // an errorType will make `checkTryStatement` issue an error return isTypeAny(type_1) || type_1 === unknownType ? type_1 : errorType; } @@ -51525,7 +52872,7 @@ var ts; return reportCircularityError(symbol); } var type; - if (declaration.kind === 266 /* ExportAssignment */) { + if (declaration.kind === 267 /* ExportAssignment */) { type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } else if (ts.isBinaryExpression(declaration) || @@ -51580,7 +52927,7 @@ var ts; type = getTypeOfEnumMember(symbol); } else if (ts.isAccessor(declaration)) { - type = resolveTypeOfAccessors(symbol); + type = resolveTypeOfAccessors(symbol) || ts.Debug.fail("Non-write accessor resolution must always produce a type"); } else { return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol)); @@ -51596,7 +52943,7 @@ var ts; } function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { - if (accessor.kind === 167 /* GetAccessor */) { + if (accessor.kind === 168 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation; } @@ -51620,63 +52967,78 @@ var ts; } function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); - return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + return links.type || (links.type = getTypeOfAccessorsWorker(symbol) || ts.Debug.fail("Read type of accessor must always produce a type")); + } + function getTypeOfSetAccessor(symbol) { + var links = getSymbolLinks(symbol); + return links.writeType || (links.writeType = getTypeOfAccessorsWorker(symbol, /*writing*/ true)); } - function getTypeOfAccessorsWorker(symbol) { + function getTypeOfAccessorsWorker(symbol, writing) { + if (writing === void 0) { writing = false; } if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } - var type = resolveTypeOfAccessors(symbol); + var type = resolveTypeOfAccessors(symbol, writing); if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter = ts.getDeclarationOfKind(symbol, 167 /* GetAccessor */); + var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); error(getter, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } return type; } - function resolveTypeOfAccessors(symbol) { - var getter = ts.getDeclarationOfKind(symbol, 167 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 168 /* SetAccessor */); + function resolveTypeOfAccessors(symbol, writing) { + if (writing === void 0) { writing = false; } + var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); + // For write operations, prioritize type annotations on the setter + if (writing && setterType) { + return instantiateTypeIfNeeded(setterType, symbol); + } + // Else defer to the getter type if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { - return jsDocType; + return instantiateTypeIfNeeded(jsDocType, symbol); } } - // First try to see if the user specified a return type on the get-accessor. - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - return getterReturnType; + // Try to see if the user specified a return type on the get-accessor. + var getterType = getAnnotatedAccessorType(getter); + if (getterType) { + return instantiateTypeIfNeeded(getterType, symbol); } - else { - // If the user didn't specify a return type, try to use the set-accessor's parameter type. - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - return setterParameterType; + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + if (setterType) { + return setterType; + } + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + var returnTypeFromBody = getReturnTypeFromBody(getter); + return instantiateTypeIfNeeded(returnTypeFromBody, symbol); + } + // Otherwise, fall back to 'any'. + if (setter) { + if (!isPrivateWithinAmbient(setter)) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); } - else { - // If there are no specified types, try to infer it from the body of the get accessor if it exists. - if (getter && getter.body) { - return getReturnTypeFromBody(getter); - } - // Otherwise, fall back to 'any'. - else { - if (setter) { - if (!isPrivateWithinAmbient(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 exist a getter as we are current checking either setter or getter in this function"); - if (!isPrivateWithinAmbient(getter)) { - errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } - } - return anyType; - } + return anyType; + } + else if (getter) { + ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } + return anyType; + } + return undefined; + function instantiateTypeIfNeeded(type, symbol) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + var links = getSymbolLinks(symbol); + return instantiateType(type, links.mapper); + } + return type; } } function getBaseTypeVariableOfClass(symbol) { @@ -51706,9 +53068,9 @@ var ts; if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration && (declaration.kind === 216 /* BinaryExpression */ || + else if (declaration && (declaration.kind === 217 /* BinaryExpression */ || ts.isAccessExpression(declaration) && - declaration.parent.kind === 216 /* BinaryExpression */)) { + declaration.parent.kind === 217 /* BinaryExpression */)) { return getWidenedTypeForAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { @@ -51742,14 +53104,16 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); + var exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(getDeclarationOfAliasSymbol(symbol), /*dontResolveAlias*/ true); // It only makes sense to get the type of a value symbol. If the result of resolving // the alias is not a value, then it has no type. To get the type associated with a // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 111551 /* Value */ - ? getTypeOfSymbol(targetSymbol) - : errorType; + links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) + : isDuplicatedCommonJSExport(symbol.declarations) ? autoType + : targetSymbol.flags & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) + : errorType; } return links.type; } @@ -51775,7 +53139,7 @@ var ts; return errorType; } // Check if variable has initializer that circularly references the variable itself - if (noImplicitAny && (declaration.kind !== 160 /* Parameter */ || declaration.initializer)) { + if (noImplicitAny && (declaration.kind !== 161 /* Parameter */ || declaration.initializer)) { error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); } // Circularities could also result from parameters in function expressions that end up @@ -51792,6 +53156,15 @@ var ts; } return links.type; } + function getSetAccessorTypeOfSymbol(symbol) { + if (symbol.flags & 98304 /* Accessor */) { + var type = getTypeOfSetAccessor(symbol); + if (type) { + return type; + } + } + return getTypeOfSymbol(symbol); + } function getTypeOfSymbol(symbol) { var checkFlags = ts.getCheckFlags(symbol); if (checkFlags & 65536 /* DeferredType */) { @@ -51874,66 +53247,72 @@ var ts; return undefined; } switch (node.kind) { - case 232 /* VariableStatement */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 164 /* MethodSignature */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 308 /* JSDocFunctionType */: - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 254 /* TypeAliasDeclaration */: - case 330 /* JSDocTemplateTag */: - case 331 /* JSDocTypedefTag */: - case 325 /* JSDocEnumTag */: - case 324 /* JSDocCallbackTag */: - case 190 /* MappedType */: - case 184 /* ConditionalType */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 165 /* MethodSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 309 /* JSDocFunctionType */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 255 /* TypeAliasDeclaration */: + case 334 /* JSDocTemplateTag */: + case 335 /* JSDocTypedefTag */: + case 329 /* JSDocEnumTag */: + case 328 /* JSDocCallbackTag */: + case 191 /* MappedType */: + case 185 /* ConditionalType */: { var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 190 /* MappedType */) { + if (node.kind === 191 /* MappedType */) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } - else if (node.kind === 184 /* ConditionalType */) { + else if (node.kind === 185 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } - else if (node.kind === 232 /* VariableStatement */ && !ts.isInJSFile(node)) { - break; - } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && - (node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */ || node.kind === 253 /* InterfaceDeclaration */ || isJSConstructor(node)) && + (node.kind === 253 /* ClassDeclaration */ || node.kind === 222 /* ClassExpression */ || node.kind === 254 /* InterfaceDeclaration */ || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; - case 326 /* JSDocParameterTag */: + } + case 330 /* JSDocParameterTag */: var paramSymbol = ts.getParameterSymbolFromJSDoc(node); if (paramSymbol) { node = paramSymbol.valueDeclaration; } break; + case 312 /* JSDocComment */: { + var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + return node.tags + ? appendTypeParameters(outerTypeParameters, ts.flatMap(node.tags, function (t) { return ts.isJSDocTemplateTag(t) ? t.typeParameters : undefined; })) + : outerTypeParameters; + } } } } // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 253 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 254 /* InterfaceDeclaration */); ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, // interface, or type alias. function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + if (!symbol.declarations) { + return; + } var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 253 /* InterfaceDeclaration */ || - node.kind === 252 /* ClassDeclaration */ || - node.kind === 221 /* ClassExpression */ || + if (node.kind === 254 /* InterfaceDeclaration */ || + node.kind === 253 /* ClassDeclaration */ || + node.kind === 222 /* ClassExpression */ || isJSConstructor(node) || ts.isTypeAlias(node)) { var declaration = node; @@ -52027,7 +53406,9 @@ var ts; ctorReturn = getReturnTypeOfSignature(ctorSig[0]); } } - ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + if (baseConstructorType.symbol.declarations) { + ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } } return type.resolvedBaseConstructorType = errorType; } @@ -52037,20 +53418,22 @@ var ts; } function getImplementsTypes(type) { var resolvedImplementsTypes = ts.emptyArray; - for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration); - if (!implementsTypeNodes) - continue; - for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) { - var node = implementsTypeNodes_1[_b]; - var implementsType = getTypeFromTypeNode(node); - if (implementsType !== errorType) { - if (resolvedImplementsTypes === ts.emptyArray) { - resolvedImplementsTypes = [implementsType]; - } - else { - resolvedImplementsTypes.push(implementsType); + if (type.symbol.declarations) { + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration); + if (!implementsTypeNodes) + continue; + for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) { + var node = implementsTypeNodes_1[_b]; + var implementsType = getTypeFromTypeNode(node); + if (implementsType !== errorType) { + if (resolvedImplementsTypes === ts.emptyArray) { + resolvedImplementsTypes = [implementsType]; + } + else { + resolvedImplementsTypes.push(implementsType); + } } } } @@ -52077,10 +53460,10 @@ var ts; else { ts.Debug.fail("type must be class or interface"); } - if (!popTypeResolution()) { + if (!popTypeResolution() && type.symbol.declarations) { for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 252 /* ClassDeclaration */ || declaration.kind === 253 /* InterfaceDeclaration */) { + if (declaration.kind === 253 /* ClassDeclaration */ || declaration.kind === 254 /* InterfaceDeclaration */) { reportCircularBaseType(declaration, type); } } @@ -52173,29 +53556,31 @@ var ts; } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; - for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 253 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { - for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { - var node = _c[_b]; - var baseType = getReducedType(getTypeFromTypeNode(node)); - if (baseType !== errorType) { - if (isValidBaseType(baseType)) { - if (type !== baseType && !hasBaseType(baseType, type)) { - if (type.resolvedBaseTypes === ts.emptyArray) { - type.resolvedBaseTypes = [baseType]; + if (type.symbol.declarations) { + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 254 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { + var node = _c[_b]; + var baseType = getReducedType(getTypeFromTypeNode(node)); + if (baseType !== errorType) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } } else { - type.resolvedBaseTypes.push(baseType); + reportCircularBaseType(declaration, type); } } else { - reportCircularBaseType(declaration, type); + error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } - else { - error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); - } } } } @@ -52209,9 +53594,12 @@ var ts; * and if none of the base interfaces have a "this" type. */ function isThislessInterface(symbol) { + if (!symbol.declarations) { + return true; + } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 253 /* InterfaceDeclaration */) { + if (declaration.kind === 254 /* InterfaceDeclaration */) { if (declaration.flags & 128 /* ContainsThis */) { return false; } @@ -52236,7 +53624,7 @@ var ts; var originalLinks = links; if (!links.declaredType) { var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */; - var merged = mergeJSSymbols(symbol, getAssignedClassSymbol(symbol.valueDeclaration)); + var merged = mergeJSSymbols(symbol, symbol.valueDeclaration && getAssignedClassSymbol(symbol.valueDeclaration)); if (merged) { // note:we overwrite links because we just cloned the symbol symbol = links = merged; @@ -52266,6 +53654,7 @@ var ts; return links.declaredType; } function getDeclaredTypeOfTypeAlias(symbol) { + var _a; var links = getSymbolLinks(symbol); if (!links.declaredType) { // Note that we use the links object as the target here because the symbol object is used as the unique @@ -52273,7 +53662,7 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return errorType; } - var declaration = ts.Debug.checkDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found"); + var declaration = ts.Debug.checkDefined((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias), "Type alias symbol with no valid declaration found"); var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; @@ -52299,7 +53688,7 @@ var ts; if (ts.isStringLiteralLike(expr)) { return true; } - else if (expr.kind === 216 /* BinaryExpression */) { + else if (expr.kind === 217 /* BinaryExpression */) { return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); } return false; @@ -52314,12 +53703,12 @@ var ts; case 8 /* NumericLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: return true; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return expr.operator === 40 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; case 78 /* Identifier */: return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return isStringConcatExpression(expr); default: return false; @@ -52331,16 +53720,18 @@ var ts; return links.enumKind; } var hasNonLiteralMember = false; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 255 /* EnumDeclaration */) { - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - if (member.initializer && ts.isStringLiteralLike(member.initializer)) { - return links.enumKind = 1 /* Literal */; - } - if (!isLiteralEnumMember(member)) { - hasNonLiteralMember = true; + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 256 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + if (member.initializer && ts.isStringLiteralLike(member.initializer)) { + return links.enumKind = 1 /* Literal */; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; + } } } } @@ -52358,15 +53749,17 @@ var ts; if (getEnumKind(symbol) === 1 /* Literal */) { enumCount++; var memberTypeList = []; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 255 /* EnumDeclaration */) { - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var value = getEnumMemberValue(member); - var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member))); - getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 256 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var value = getEnumMemberValue(member); + var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member))); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + } } } } @@ -52443,11 +53836,11 @@ var ts; case 113 /* VoidKeyword */: case 150 /* UndefinedKeyword */: case 141 /* NeverKeyword */: - case 191 /* LiteralType */: + case 192 /* LiteralType */: return true; - case 178 /* ArrayType */: + case 179 /* ArrayType */: return isThislessType(node.elementType); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; @@ -52473,7 +53866,7 @@ var ts; function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - return (node.kind === 166 /* Constructor */ || (!!returnType && isThislessType(returnType))) && + return (node.kind === 167 /* Constructor */ || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } @@ -52489,14 +53882,14 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return isThislessVariableLikeDeclaration(declaration); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return isThislessFunctionLikeDeclaration(declaration); } } @@ -52522,7 +53915,7 @@ var ts; } } function isStaticPrivateIdentifierProperty(s) { - return !!s.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(s.valueDeclaration) && ts.hasSyntacticModifier(s.valueDeclaration, 32 /* Static */); + return !!s.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(s.valueDeclaration) && ts.hasSyntacticModifier(s.valueDeclaration, 32 /* Static */); } function resolveDeclaredMembers(type) { if (!type.declaredProperties) { @@ -52574,10 +53967,10 @@ var ts; return !!name && isLateBindableName(name); } /** - * Indicates whether a declaration has a dynamic name that cannot be late-bound. + * Indicates whether a declaration has an early-bound name or a dynamic name that can be late-bound. */ - function hasNonBindableDynamicName(node) { - return ts.hasDynamicName(node) && !hasLateBindableName(node); + function hasBindableName(node) { + return !ts.hasDynamicName(node) || hasLateBindableName(node); } /** * Indicates whether a declaration name is a dynamic name that cannot be late-bound. @@ -52847,7 +54240,8 @@ var ts; sig.resolvedMinArgumentCount = undefined; sig.target = undefined; sig.mapper = undefined; - sig.unionSignatures = undefined; + sig.compositeSignatures = undefined; + sig.compositeKind = undefined; return sig; } function cloneSignature(sig) { @@ -52855,12 +54249,14 @@ var ts; /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 39 /* PropagatingFlags */); result.target = sig.target; result.mapper = sig.mapper; - result.unionSignatures = sig.unionSignatures; + result.compositeSignatures = sig.compositeSignatures; + result.compositeKind = sig.compositeKind; return result; } function createUnionSignature(signature, unionSignatures) { var result = cloneSignature(signature); - result.unionSignatures = unionSignatures; + result.compositeSignatures = unionSignatures; + result.compositeKind = 1048576 /* Union */; result.target = undefined; result.mapper = undefined; return result; @@ -53019,7 +54415,7 @@ var ts; if (signatures !== masterList) { var signature_1 = signatures[0]; ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); - results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters && !compareTypeParametersIdentical(signature_1.typeParameters, s.typeParameters); }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); }); + results = !!signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters && !compareTypeParametersIdentical(signature_1.typeParameters, s.typeParameters); }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); }); if (!results) { return "break"; } @@ -53036,9 +54432,12 @@ var ts; return result || ts.emptyArray; } function compareTypeParametersIdentical(sourceParams, targetParams) { - if (sourceParams.length !== targetParams.length) { + if (ts.length(sourceParams) !== ts.length(targetParams)) { return false; } + if (!sourceParams || !targetParams) { + return true; + } var mapper = createTypeMapper(targetParams, sourceParams); for (var i = 0; i < sourceParams.length; i++) { var source = sourceParams[i]; @@ -53120,9 +54519,10 @@ var ts; var result = createSignature(declaration, typeParams, thisParam, params, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 39 /* PropagatingFlags */); - result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); + result.compositeKind = 1048576 /* Union */; + result.compositeSignatures = ts.concatenate(left.compositeKind !== 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); if (paramMapper) { - result.mapper = left.mapper && left.unionSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; + result.mapper = left.compositeKind !== 2097152 /* Intersection */ && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; } return result; } @@ -53255,6 +54655,7 @@ var ts; // Combinations of function, class, enum and module var members = emptySymbols; var stringIndexInfo = void 0; + var numberIndexInfo = void 0; if (symbol.exports) { members = getExportsOfSymbol(symbol); if (symbol === globalThisSymbol) { @@ -53267,20 +54668,31 @@ var ts; members = varsOnly_1; } } + var baseConstructorIndexInfo = void 0; setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) { - members = ts.createSymbolTable(getNamedMembers(members)); + members = ts.createSymbolTable(getNamedOrIndexSignatureMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } else if (baseConstructorType === anyType) { - stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + baseConstructorIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + } + } + var indexSymbol = getIndexSymbolFromSymbolTable(members); + if (indexSymbol) { + stringIndexInfo = getIndexInfoOfIndexSymbol(indexSymbol, 0 /* String */); + numberIndexInfo = getIndexInfoOfIndexSymbol(indexSymbol, 1 /* Number */); + } + else { + stringIndexInfo = baseConstructorIndexInfo; + if (symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ || + ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); }))) { + numberIndexInfo = enumNumberIndexInfo; } } - var numberIndexInfo = symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ || - ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); })) ? enumNumberIndexInfo : undefined; setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); // We resolve the members before computing the signatures because a signature may use // typeof with a qualified name expression that circularly references the type we are @@ -53305,6 +54717,18 @@ var ts; } } } + function replaceIndexedAccess(instantiable, type, replacement) { + // map type.indexType to 0 + // map type.objectType to `[TReplacement]` + // thus making the indexed access `[TReplacement][0]` or `TReplacement` + return instantiateType(instantiable, createTypeMapper([type.indexType, type.objectType], [getLiteralType(0), createTupleType([replacement])])); + } + function getIndexInfoOfIndexSymbol(indexSymbol, indexKind) { + var declaration = getIndexDeclarationOfIndexSymbol(indexSymbol, indexKind); + if (!declaration) + return undefined; + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasEffectiveModifier(declaration, 64 /* Readonly */), declaration); + } function resolveReverseMappedTypeMembers(type) { var indexInfo = getIndexInfoOfType(type.source, 0 /* String */); var modifiers = getMappedTypeModifiers(type.mappedType); @@ -53319,8 +54743,21 @@ var ts; inferredProp.declarations = prop.declarations; inferredProp.nameType = getSymbolLinks(prop).nameType; inferredProp.propertyType = getTypeOfSymbol(prop); - inferredProp.mappedType = type.mappedType; - inferredProp.constraintType = type.constraintType; + if (type.constraintType.type.flags & 8388608 /* IndexedAccess */ + && type.constraintType.type.objectType.flags & 262144 /* TypeParameter */ + && type.constraintType.type.indexType.flags & 262144 /* TypeParameter */) { + // A reverse mapping of `{[K in keyof T[K_1]]: T[K_1]}` is the same as that of `{[K in keyof T]: T}`, since all we care about is + // inferring to the "type parameter" (or indexed access) shared by the constraint and template. So, to reduce the number of + // type identities produced, we simplify such indexed access occurences + var newTypeParam = type.constraintType.type.objectType; + var newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type, newTypeParam); + inferredProp.mappedType = newMappedType; + inferredProp.constraintType = getIndexType(newTypeParam); + } + else { + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + } members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -53482,7 +54919,7 @@ var ts; } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 - return constraintDeclaration.kind === 188 /* TypeOperator */ && + return constraintDeclaration.kind === 189 /* TypeOperator */ && constraintDeclaration.operator === 138 /* KeyOfKeyword */; } function getModifiersTypeFromMappedType(type) { @@ -53534,7 +54971,7 @@ var ts; else if (type.objectFlags & 3 /* ClassOrInterface */) { resolveClassOrInterfaceMembers(type); } - else if (type.objectFlags & 2048 /* ReverseMapped */) { + else if (type.objectFlags & 1024 /* ReverseMapped */) { resolveReverseMappedTypeMembers(type); } else if (type.objectFlags & 16 /* Anonymous */) { @@ -53818,12 +55255,22 @@ var ts; if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; + var different = false; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type_3 = types_8[_i]; var baseType = getBaseConstraint(type_3); if (baseType) { + if (baseType !== type_3) { + different = true; + } baseTypes.push(baseType); } + else { + different = true; + } + } + if (!different) { + return t; } return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : @@ -53943,6 +55390,7 @@ var ts; return getReducedType(getApparentType(getReducedType(type))); } function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) { + var _a, _b; var singleProp; var propSet; var indexTypes; @@ -53951,8 +55399,9 @@ var ts; var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var current = _a[_i]; + var mergedInstantiations = false; + for (var _i = 0, _c = containingType.types; _i < _c.length; _i++) { + var current = _c[_i]; var type = getApparentType(current); if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); @@ -53968,13 +55417,25 @@ var ts; singleProp = prop; } else if (prop !== singleProp) { - if (!propSet) { - propSet = new ts.Map(); - propSet.set(getSymbolId(singleProp), singleProp); + var isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp); + // If the symbols are instances of one another with identical types - consider the symbols + // equivalent and just use the first one, which thus allows us to avoid eliding private + // members when intersecting a (this-)instantiations of a class with it's raw base or another instance + if (isInstantiation && compareProperties(singleProp, prop, function (a, b) { return a === b ? -1 /* True */ : 0 /* False */; }) === -1 /* True */) { + // If we merged instantiations of a generic type, we replicate the symbol parent resetting behavior we used + // to do when we recorded multiple distinct symbols so that we still get, eg, `Array.length` printed + // back and not `Array.length` when we're looking at a `.length` access on a `string[] | number[]` + mergedInstantiations = !!singleProp.parent && !!ts.length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent)); } - var id = getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + else { + if (!propSet) { + propSet = new ts.Map(); + propSet.set(getSymbolId(singleProp), singleProp); + } + var id = getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | @@ -53992,7 +55453,7 @@ var ts; checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0); indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } - else if (isObjectLiteralType(type)) { + else if (isObjectLiteralType(type) && !(ts.getObjectFlags(type) & 4194304 /* ContainsSpread */)) { checkFlags |= 32 /* WritePartial */; indexTypes = ts.append(indexTypes, undefinedType); } @@ -54008,7 +55469,19 @@ var ts; return undefined; } if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { - return singleProp; + if (mergedInstantiations) { + // No symbol from a union/intersection should have a `.parent` set (since unions/intersections don't act as symbol parents) + // Unless that parent is "reconstituted" from the "first value declaration" on the symbol (which is likely different than its instantiated parent!) + // They also have a `.containingType` set, which affects some services endpoints behavior, like `getRootSymbol` + var clone_1 = createSymbolWithType(singleProp, singleProp.type); + clone_1.parent = (_b = (_a = singleProp.valueDeclaration) === null || _a === void 0 ? void 0 : _a.symbol) === null || _b === void 0 ? void 0 : _b.parent; + clone_1.containingType = containingType; + clone_1.mapper = singleProp.mapper; + return clone_1; + } + else { + return singleProp; + } } var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; @@ -54017,8 +55490,8 @@ var ts; var propTypes = []; var firstValueDeclaration; var hasNonUniformValueDeclaration = false; - for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { - var prop = props_1[_b]; + for (var _d = 0, props_1 = props; _d < props_1.length; _d++) { + var prop = props_1[_d]; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } @@ -54095,15 +55568,15 @@ var ts; * no constituent property has type 'never', but the intersection of the constituent property types is 'never'. */ function getReducedType(type) { - if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) { + if (type.flags & 1048576 /* Union */ && type.objectFlags & 67108864 /* ContainsIntersections */) { return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); } else if (type.flags & 2097152 /* Intersection */) { - if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { - type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | - (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0); + if (!(type.objectFlags & 67108864 /* IsNeverIntersectionComputed */)) { + type.objectFlags |= 67108864 /* IsNeverIntersectionComputed */ | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 134217728 /* IsNeverIntersection */ : 0); } - return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; + return type.objectFlags & 134217728 /* IsNeverIntersection */ ? neverType : type; } return type; } @@ -54133,7 +55606,7 @@ var ts; return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */); } function elaborateNeverIntersection(errorInfo, type) { - if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) { + if (type.flags & 2097152 /* Intersection */ && ts.getObjectFlags(type) & 134217728 /* IsNeverIntersection */) { var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); if (neverProp) { return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(neverProp)); @@ -54220,7 +55693,8 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var prop = _a[_i]; if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { - propTypes.push(getTypeOfSymbol(prop)); + var propType = getTypeOfSymbol(prop); + propTypes.push(prop.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType); } } if (kind === 0 /* String */) { @@ -54254,10 +55728,10 @@ var ts; function isJSDocOptionalParameter(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 === 307 /* JSDocOptionalType */ + node.type && node.type.kind === 308 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 307 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 308 /* JSDocOptionalType */; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -54289,12 +55763,15 @@ var ts; } return false; } + function isOptionalPropertyDeclaration(node) { + return ts.isPropertyDeclaration(node) && node.questionToken; + } function isOptionalJSDocPropertyLikeTag(node) { if (!ts.isJSDocPropertyLikeTag(node)) { return false; } var isBracketed = node.isBracketed, typeExpression = node.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 307 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 308 /* JSDocOptionalType */; } function createTypePredicate(kind, parameterName, parameterIndex, type) { return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; @@ -54376,7 +55853,7 @@ var ts; else { parameters.push(paramSymbol); } - if (type && type.kind === 191 /* LiteralType */) { + if (type && type.kind === 192 /* LiteralType */) { flags |= 2 /* HasLiteralTypes */; } // Record a new minimum argument count if this is not an optional parameter @@ -54389,16 +55866,16 @@ var ts; } } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 167 /* GetAccessor */ || declaration.kind === 168 /* SetAccessor */) && - !hasNonBindableDynamicName(declaration) && + if ((declaration.kind === 168 /* GetAccessor */ || declaration.kind === 169 /* SetAccessor */) && + hasBindableName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; + var otherKind = declaration.kind === 168 /* GetAccessor */ ? 169 /* SetAccessor */ : 168 /* GetAccessor */; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 166 /* Constructor */ ? + var classType = declaration.kind === 167 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); @@ -54443,8 +55920,7 @@ var ts; if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node))) return undefined; var typeTag = ts.getJSDocTypeTag(node); - var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); - return signature && getErasedSignature(signature); + return (typeTag === null || typeTag === void 0 ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); } function getReturnTypeOfTypeTag(node) { var signature = getSignatureOfTypeTag(node); @@ -54467,14 +55943,14 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node.escapedText === argumentsSymbol.escapedName && getResolvedSymbol(node) === argumentsSymbol; - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - return node.name.kind === 158 /* ComputedPropertyName */ + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return node.name.kind === 159 /* ComputedPropertyName */ && traverse(node.name); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return traverse(node.expression); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); @@ -54482,7 +55958,7 @@ var ts; } } function getSignaturesOfSymbol(symbol) { - if (!symbol) + if (!symbol || !symbol.declarations) return ts.emptyArray; var result = []; for (var i = 0; i < symbol.declarations.length; i++) { @@ -54523,8 +55999,8 @@ var ts; var targetTypePredicate = getTypePredicateOfSignature(signature.target); signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; } - else if (signature.unionSignatures) { - signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + else if (signature.compositeSignatures) { + signature.resolvedTypePredicate = getUnionOrIntersectionTypePredicate(signature.compositeSignatures, signature.compositeKind) || noTypePredicate; } else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); @@ -54546,17 +56022,20 @@ var ts; function createTypePredicateFromTypePredicateNode(node, signature) { var parameterName = node.parameterName; var type = node.type && getTypeFromTypeNode(node.type); - return parameterName.kind === 187 /* ThisType */ ? + return parameterName.kind === 188 /* ThisType */ ? createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) : createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type); } + function getUnionOrIntersectionType(types, kind, unionReduction) { + return kind !== 2097152 /* Intersection */ ? getUnionType(types, unionReduction) : getIntersectionType(types); + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { return errorType; } var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : - signature.unionSignatures ? instantiateType(getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */), signature.mapper) : + signature.compositeSignatures ? instantiateType(getUnionOrIntersectionType(ts.map(signature.compositeSignatures, getReturnTypeOfSignature), signature.compositeKind, 2 /* Subtype */), signature.mapper) : getReturnTypeFromAnnotation(signature.declaration) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (signature.flags & 8 /* IsInnerCallChain */) { @@ -54589,7 +56068,7 @@ var ts; return signature.resolvedReturnType; } function getReturnTypeFromAnnotation(declaration) { - if (declaration.kind === 166 /* Constructor */) { + if (declaration.kind === 167 /* Constructor */) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); } if (ts.isJSDocConstructSignature(declaration)) { @@ -54599,12 +56078,12 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 167 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + if (declaration.kind === 168 /* GetAccessor */ && hasBindableName(declaration)) { var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 168 /* SetAccessor */); + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 169 /* SetAccessor */); var setterType = getAnnotatedAccessorType(setter); if (setterType) { return setterType; @@ -54681,9 +56160,20 @@ var ts; function getBaseSignature(signature) { var typeParameters = signature.typeParameters; if (typeParameters) { - var typeEraser_1 = createTypeEraser(typeParameters); - var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || unknownType; }); - return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); + if (signature.baseSignatureCache) { + return signature.baseSignatureCache; + } + var typeEraser = createTypeEraser(typeParameters); + var baseConstraintMapper_1 = createTypeMapper(typeParameters, ts.map(typeParameters, function (tp) { return getConstraintOfTypeParameter(tp) || unknownType; })); + var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(tp, baseConstraintMapper_1) || unknownType; }); + // Run N type params thru the immediate constraint mapper up to N times + // This way any noncircular interdependent type parameters are definitely resolved to their external dependencies + for (var i = 0; i < typeParameters.length - 1; i++) { + baseConstraints = instantiateTypes(baseConstraints, baseConstraintMapper_1); + } + // and then apply a type eraser to remove any remaining circularly dependent type parameters + baseConstraints = instantiateTypes(baseConstraints, typeEraser); + return signature.baseSignatureCache = instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); } return signature; } @@ -54694,7 +56184,7 @@ var ts; // will result in a different declaration kind. if (!signature.isolatedSignatureType) { var kind = signature.declaration ? signature.declaration.kind : 0 /* Unknown */; - var isConstructor = kind === 166 /* Constructor */ || kind === 170 /* ConstructSignature */ || kind === 175 /* ConstructorType */; + var isConstructor = kind === 167 /* Constructor */ || kind === 171 /* ConstructSignature */ || kind === 176 /* ConstructorType */; var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -54705,12 +56195,22 @@ var ts; return signature.isolatedSignatureType; } function getIndexSymbol(symbol) { - return symbol.members.get("__index" /* Index */); + return symbol.members ? getIndexSymbolFromSymbolTable(symbol.members) : undefined; + } + function getIndexSymbolFromSymbolTable(symbolTable) { + return symbolTable.get("__index" /* Index */); } function getIndexDeclarationOfSymbol(symbol, kind) { + var indexSymbol = symbol && getIndexSymbol(symbol); + return indexSymbol && getIndexDeclarationOfIndexSymbol(indexSymbol, kind); + } + function getIndexDeclarationOfSymbolTable(symbolTable, kind) { + var indexSymbol = symbolTable && getIndexSymbolFromSymbolTable(symbolTable); + return indexSymbol && getIndexDeclarationOfIndexSymbol(indexSymbol, kind); + } + function getIndexDeclarationOfIndexSymbol(indexSymbol, kind) { var syntaxKind = kind === 1 /* Number */ ? 144 /* NumberKeyword */ : 147 /* StringKeyword */; - var indexSymbol = getIndexSymbol(symbol); - if (indexSymbol) { + if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; var node = ts.cast(decl, ts.isIndexSignatureDeclaration); @@ -54738,17 +56238,18 @@ var ts; return ts.mapDefined(ts.filter(type.symbol && type.symbol.declarations, ts.isTypeParameterDeclaration), ts.getEffectiveConstraintOfTypeParameter)[0]; } function getInferredTypeParameterConstraint(typeParameter) { + var _a; var inferences; - if (typeParameter.symbol) { - for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.parent.kind === 185 /* InferType */) { + if ((_a = typeParameter.symbol) === null || _a === void 0 ? void 0 : _a.declarations) { + for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (declaration.parent.kind === 186 /* InferType */) { // When an 'infer T' declaration is immediately contained in a type reference node // (such as 'Foo'), T's constraint is inferred from the constraint of the // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are // present, we form an intersection of the inferred constraint types. - var _b = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _c = _b[0], childTypeParameter = _c === void 0 ? declaration.parent : _c, grandParent = _b[1]; - if (grandParent.kind === 173 /* TypeReference */) { + var _c = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _d = _c[0], childTypeParameter = _d === void 0 ? declaration.parent : _d, grandParent = _c[1]; + if (grandParent.kind === 174 /* TypeReference */) { var typeReference = grandParent; var typeParameters = getTypeParametersForTypeReference(typeReference); if (typeParameters) { @@ -54773,21 +56274,32 @@ var ts; } // When an 'infer T' declaration is immediately contained in a rest parameter declaration, a rest type // or a named rest tuple element, we infer an 'unknown[]' constraint. - else if (grandParent.kind === 160 /* Parameter */ && grandParent.dotDotDotToken || - grandParent.kind === 181 /* RestType */ || - grandParent.kind === 192 /* NamedTupleMember */ && grandParent.dotDotDotToken) { + else if (grandParent.kind === 161 /* Parameter */ && grandParent.dotDotDotToken || + grandParent.kind === 182 /* RestType */ || + grandParent.kind === 193 /* NamedTupleMember */ && grandParent.dotDotDotToken) { inferences = ts.append(inferences, createArrayType(unknownType)); } // When an 'infer T' declaration is immediately contained in a string template type, we infer a 'string' // constraint. - else if (grandParent.kind === 194 /* TemplateLiteralTypeSpan */) { + else if (grandParent.kind === 195 /* TemplateLiteralTypeSpan */) { inferences = ts.append(inferences, stringType); } // When an 'infer T' declaration is in the constraint position of a mapped type, we infer a 'keyof any' // constraint. - else if (grandParent.kind === 159 /* TypeParameter */ && grandParent.parent.kind === 190 /* MappedType */) { + else if (grandParent.kind === 160 /* TypeParameter */ && grandParent.parent.kind === 191 /* MappedType */) { inferences = ts.append(inferences, keyofConstraintType); } + // When an 'infer T' declaration is the template of a mapped type, and that mapped type is the extends + // clause of a conditional whose check type is also a mapped type, give it a constraint equal to the template + // of the check type's mapped type + else if (grandParent.kind === 191 /* MappedType */ && grandParent.type && + ts.skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 185 /* ConditionalType */ && + grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 191 /* MappedType */ && + grandParent.parent.checkType.type) { + var checkMappedType_1 = grandParent.parent.checkType; + var nodeType = getTypeFromTypeNode(checkMappedType_1.type); + inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); + } } } } @@ -54810,7 +56322,7 @@ var ts; if (type.flags & 1 /* Any */ && type !== errorType) { // Allow errorType to propegate to keep downstream errors suppressed // use keyofConstraintType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was), // use unknown otherwise - type = constraintDeclaration.parent.parent.kind === 190 /* MappedType */ ? keyofConstraintType : unknownType; + type = constraintDeclaration.parent.parent.kind === 191 /* MappedType */ ? keyofConstraintType : unknownType; } typeParameter.constraint = type; } @@ -54819,7 +56331,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - var tp = ts.getDeclarationOfKind(typeParameter.symbol, 159 /* TypeParameter */); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 160 /* TypeParameter */); var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; return host && getSymbolOfNode(host); } @@ -54846,6 +56358,9 @@ var ts; } return result; } + function getAliasId(aliasSymbol, aliasTypeArguments) { + return aliasSymbol ? "@" + getSymbolId(aliasSymbol) + (aliasTypeArguments ? ":" + getTypeListId(aliasTypeArguments) : "") : ""; + } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type // of an object literal or the anyFunctionType. This is because there are operations in the type checker @@ -54858,7 +56373,7 @@ var ts; result |= ts.getObjectFlags(type); } } - return result & 3670016 /* PropagatingFlags */; + return result & 917504 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -54880,15 +56395,18 @@ var ts; type.resolvedTypeArguments = source.resolvedTypeArguments; return type; } - function createDeferredTypeReference(target, node, mapper) { - var aliasSymbol = getAliasSymbolForTypeNode(node); - var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + function createDeferredTypeReference(target, node, mapper, aliasSymbol, aliasTypeArguments) { + if (!aliasSymbol) { + aliasSymbol = getAliasSymbolForTypeNode(node); + var localAliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + aliasTypeArguments = mapper ? instantiateTypes(localAliasTypeArguments, mapper) : localAliasTypeArguments; + } var type = createObjectType(4 /* Reference */, target.symbol); type.target = target; type.node = node; type.mapper = mapper; type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = mapper ? instantiateTypes(aliasTypeArguments, mapper) : aliasTypeArguments; + type.aliasTypeArguments = aliasTypeArguments; return type; } function getTypeArguments(type) { @@ -54899,8 +56417,8 @@ var ts; } var node = type.node; var typeArguments = !node ? ts.emptyArray : - node.kind === 173 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : - node.kind === 178 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : + node.kind === 174 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : + node.kind === 179 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); if (popTypeResolution()) { type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; @@ -54942,7 +56460,7 @@ var ts; return errorType; } } - if (node.kind === 173 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) { + if (node.kind === 174 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) { return createDeferredTypeReference(type, node, /*mapper*/ undefined); } // In a type reference, the outer type parameters of the referenced class or interface are automatically @@ -54953,17 +56471,17 @@ var ts; } return checkNoTypeArguments(node, symbol) ? type : errorType; } - function getTypeAliasInstantiation(symbol, typeArguments) { + function getTypeAliasInstantiation(symbol, typeArguments, aliasSymbol, aliasTypeArguments) { var type = getDeclaredTypeOfSymbol(symbol); if (type === intrinsicMarkerType && intrinsicTypeKinds.has(symbol.escapedName) && typeArguments && typeArguments.length === 1) { return getStringMappingType(symbol, typeArguments[0]); } var links = getSymbolLinks(symbol); var typeParameters = links.typeParameters; - var id = getTypeListId(typeArguments); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments)); } return instantiation; } @@ -54984,15 +56502,26 @@ var ts; ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return errorType; } - return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node)); + // We refrain from associating a local type alias with an instantiation of a top-level type alias + // because the local alias may end up being referenced in an inferred return type where it is not + // accessible--which in turn may lead to a large structural expansion of the type when generating + // a .d.ts file. See #43622 for an example. + var aliasSymbol = getAliasSymbolForTypeNode(node); + var newAliasSymbol = aliasSymbol && (isLocalTypeAlias(symbol) || !isLocalTypeAlias(aliasSymbol)) ? aliasSymbol : undefined; + return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), newAliasSymbol, getTypeArgumentsForAliasSymbol(newAliasSymbol)); } return checkNoTypeArguments(node, symbol) ? type : errorType; } + function isLocalTypeAlias(symbol) { + var _a; + var declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias); + return !!(declaration && ts.getContainingFunction(declaration)); + } function getTypeReferenceName(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return node.typeName; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. var expr = node.expression; @@ -55048,7 +56577,7 @@ var ts; var valueType = getTypeOfSymbol(symbol); var typeType = valueType; if (symbol.valueDeclaration) { - var isImportTypeWithQualifier = node.kind === 195 /* ImportType */ && node.qualifier; + var isImportTypeWithQualifier = node.kind === 196 /* ImportType */ && node.qualifier; // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL} if (valueType.symbol && valueType.symbol !== symbol && isImportTypeWithQualifier) { typeType = getTypeReferenceType(node, valueType.symbol); @@ -55074,7 +56603,7 @@ var ts; return result; } function isUnaryTupleTypeNode(node) { - return node.kind === 179 /* TupleType */ && node.elements.length === 1; + return node.kind === 180 /* TupleType */ && node.elements.length === 1; } function getImpliedConstraint(type, checkNode, extendsNode) { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elements[0], extendsNode.elements[0]) : @@ -55083,9 +56612,17 @@ var ts; } function getConditionalFlowTypeOfType(type, node) { var constraints; - while (node && !ts.isStatement(node) && node.kind !== 311 /* JSDocComment */) { + var covariant = true; + while (node && !ts.isStatement(node) && node.kind !== 312 /* JSDocComment */) { var parent = node.parent; - if (parent.kind === 184 /* ConditionalType */ && node === parent.trueType) { + // only consider variance flipped by parameter locations - `keyof` types would usually be considered variance inverting, but + // often get used in indexed accesses where they behave sortof invariantly, but our checking is lax + if (parent.kind === 161 /* Parameter */) { + covariant = !covariant; + } + // Always substitute on type parameters, regardless of variance, since even + // in contravariant positions, they may rely on substituted constraints to be valid + if ((covariant || type.flags & 8650752 /* TypeVariable */) && parent.kind === 185 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -55096,7 +56633,7 @@ var ts; return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type; } function isJSDocTypeReference(node) { - return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 173 /* TypeReference */ || node.kind === 195 /* ImportType */); + return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 174 /* TypeReference */ || node.kind === 196 /* ImportType */); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -55206,13 +56743,15 @@ var ts; function getTypeOfGlobalSymbol(symbol, arity) { function getTypeDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { - var declaration = declarations_3[_i]; - switch (declaration.kind) { - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - return declaration; + if (declarations) { + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; + switch (declaration.kind) { + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + return declaration; + } } } } @@ -55256,6 +56795,9 @@ var ts; function getGlobalESSymbolConstructorSymbol(reportErrors) { return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); } + function getGlobalESSymbolConstructorTypeSymbol(reportErrors) { + return deferredGlobalESSymbolConstructorTypeSymbol || (deferredGlobalESSymbolConstructorTypeSymbol = getGlobalTypeSymbol("SymbolConstructor", reportErrors)); + } function getGlobalESSymbolType(reportErrors) { return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType; } @@ -55332,11 +56874,11 @@ var ts; } function getTupleElementFlags(node) { switch (node.kind) { - case 180 /* OptionalType */: + case 181 /* OptionalType */: return 2 /* Optional */; - case 181 /* RestType */: + case 182 /* RestType */: return getRestTypeElementFlags(node); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return node.questionToken ? 2 /* Optional */ : node.dotDotDotToken ? getRestTypeElementFlags(node) : 1 /* Required */; @@ -55354,14 +56896,14 @@ var ts; return readonly ? globalReadonlyArrayType : globalArrayType; } var elementFlags = ts.map(node.elements, getTupleElementFlags); - var missingName = ts.some(node.elements, function (e) { return e.kind !== 192 /* NamedTupleMember */; }); + var missingName = ts.some(node.elements, function (e) { return e.kind !== 193 /* NamedTupleMember */; }); return getTupleTargetType(elementFlags, readonly, /*associatedNames*/ missingName ? undefined : node.elements); } // Return true if the given type reference node is directly aliased or if it needs to be deferred // because it is possibly contained in a circular chain of eagerly resolved types. function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) { - return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 178 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) : - node.kind === 179 /* TupleType */ ? ts.some(node.elements, mayResolveTypeAlias) : + return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 179 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) : + node.kind === 180 /* TupleType */ ? ts.some(node.elements, mayResolveTypeAlias) : hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias)); } // Return true when the given node is transitively contained in type constructs that eagerly @@ -55370,18 +56912,18 @@ var ts; function isResolvedByTypeAlias(node) { var parent = node.parent; switch (parent.kind) { - case 186 /* ParenthesizedType */: - case 192 /* NamedTupleMember */: - case 173 /* TypeReference */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 189 /* IndexedAccessType */: - case 184 /* ConditionalType */: - case 188 /* TypeOperator */: - case 178 /* ArrayType */: - case 179 /* TupleType */: + case 187 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: + case 174 /* TypeReference */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 190 /* IndexedAccessType */: + case 185 /* ConditionalType */: + case 189 /* TypeOperator */: + case 179 /* ArrayType */: + case 180 /* TupleType */: return isResolvedByTypeAlias(parent); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return true; } return false; @@ -55390,28 +56932,28 @@ var ts; // of a type alias. function mayResolveTypeAlias(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node.typeName, 788968 /* Type */).flags & 524288 /* TypeAlias */); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return true; - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return node.operator !== 151 /* UniqueKeyword */ && mayResolveTypeAlias(node.type); - case 186 /* ParenthesizedType */: - case 180 /* OptionalType */: - case 192 /* NamedTupleMember */: - case 307 /* JSDocOptionalType */: - case 305 /* JSDocNullableType */: - case 306 /* JSDocNonNullableType */: - case 301 /* JSDocTypeExpression */: + case 187 /* ParenthesizedType */: + case 181 /* OptionalType */: + case 193 /* NamedTupleMember */: + case 308 /* JSDocOptionalType */: + case 306 /* JSDocNullableType */: + case 307 /* JSDocNonNullableType */: + case 302 /* JSDocTypeExpression */: return mayResolveTypeAlias(node.type); - case 181 /* RestType */: - return node.type.kind !== 178 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType); - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 182 /* RestType */: + return node.type.kind !== 179 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType); + case 183 /* UnionType */: + case 184 /* IntersectionType */: return ts.some(node.types, mayResolveTypeAlias); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) || mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType); } @@ -55424,12 +56966,12 @@ var ts; if (target === emptyGenericType) { links.resolvedType = emptyObjectType; } - else if (!(node.kind === 179 /* TupleType */ && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8 /* Variadic */); })) && isDeferredTypeReferenceNode(node)) { - links.resolvedType = node.kind === 179 /* TupleType */ && node.elements.length === 0 ? target : + else if (!(node.kind === 180 /* TupleType */ && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8 /* Variadic */); })) && isDeferredTypeReferenceNode(node)) { + links.resolvedType = node.kind === 180 /* TupleType */ && node.elements.length === 0 ? target : createDeferredTypeReference(target, node, /*mapper*/ undefined); } else { - var elementTypes = node.kind === 178 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); + var elementTypes = node.kind === 179 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); links.resolvedType = createNormalizedTypeReference(target, elementTypes); } } @@ -55561,8 +57103,15 @@ var ts; addElement(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]); } else if (isTupleType(type)) { + var elements = getTypeArguments(type); + if (elements.length + expandedTypes.length >= 10000) { + error(currentNode, ts.isPartOfTypeNode(currentNode) + ? ts.Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent + : ts.Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent); + return { value: errorType }; + } // Spread variadic elements with tuple types into the resulting tuple. - ts.forEach(getTypeArguments(type), function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); + ts.forEach(elements, function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); } else { // Treat everything else as an array type and create a rest element. @@ -55575,7 +57124,9 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - _loop_13(i); + var state_4 = _loop_13(i); + if (typeof state_4 === "object") + return state_4.value; } // Turn optional elements preceding the last required element into required elements for (var i = 0; i < lastRequiredIndex; i++) { @@ -55664,7 +57215,7 @@ var ts; if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { - if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) + if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */)) includes |= 4194304 /* IncludesNonWideningType */; } else { @@ -55686,67 +57237,76 @@ var ts; } return includes; } - function isSetOfLiteralsFromSameEnum(types) { - var first = types[0]; - if (first.flags & 1024 /* EnumLiteral */) { - var firstEnum = getParentOfSymbol(first.symbol); - for (var i = 1; i < types.length; i++) { - var other = types[i]; - if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { - return false; - } - } - return true; + function removeSubtypes(types, hasObjectTypes) { + var id = getTypeListId(types); + var match = subtypeReductionCache.get(id); + if (match) { + return match; } - return false; - } - function removeSubtypes(types, primitivesOnly) { + // We assume that redundant primitive types have already been removed from the types array and that there + // are no any and unknown types in the array. Thus, the only possible supertypes for primitive types are empty + // object types, and if none of those are present we can exclude primitive types from the subtype check. + var hasEmptyObject = hasObjectTypes && ts.some(types, function (t) { return !!(t.flags & 524288 /* Object */) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t)); }); var len = types.length; - if (len === 0 || isSetOfLiteralsFromSameEnum(types)) { - return true; - } var i = len; var count = 0; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var target = types_11[_i]; - if (source !== target) { - if (count === 100000) { - // After 100000 subtype checks we estimate the remaining amount of work by assuming the - // same ratio of checks per element. If the estimated number of remaining type checks is - // greater than an upper limit we deem the union type too complex to represent. The - // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example - // caps union types at 5000 unique literal types and 1000 unique object types. - var estimatedCount = (count / (len - i)) * len; - if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); - error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); - return false; + if (hasEmptyObject || source.flags & 469499904 /* StructuredOrInstantiable */) { + // Find the first property with a unit type, if any. When constituents have a property by the same name + // but of a different unit type, we can quickly disqualify them from subtype checks. This helps subtype + // reduction of large discriminated union types. + var keyProperty = source.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */) ? + ts.find(getPropertiesOfType(source), function (p) { return isUnitType(getTypeOfSymbol(p)); }) : + undefined; + var keyPropertyType = keyProperty && getRegularTypeOfLiteralType(getTypeOfSymbol(keyProperty)); + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var target = types_11[_i]; + if (source !== target) { + if (count === 100000) { + // After 100000 subtype checks we estimate the remaining amount of work by assuming the + // same ratio of checks per element. If the estimated number of remaining type checks is + // greater than 1M we deem the union type too complex to represent. This for example + // caps union types at 1000 unique object types. + var estimatedCount = (count / (len - i)) * len; + if (estimatedCount > 1000000) { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); + error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); + return undefined; + } + } + count++; + if (keyProperty && target.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */)) { + var t = getTypeOfPropertyOfType(target, keyProperty.escapedName); + if (t && isUnitType(t) && getRegularTypeOfLiteralType(t) !== keyPropertyType) { + continue; + } + } + if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { + ts.orderedRemoveItemAt(types, i); + break; } - } - count++; - if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || - !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || - isTypeDerivedFrom(source, target))) { - ts.orderedRemoveItemAt(types, i); - break; } } } } - return true; + subtypeReductionCache.set(id, types); + return types; } - function removeRedundantLiteralTypes(types, includes) { + function removeRedundantLiteralTypes(types, includes, reduceVoidUndefined) { var i = types.length; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 134217856 /* StringLikeLiteral */ && includes & 4 /* String */ || - t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || - t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || - t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + var flags = t.flags; + var remove = flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + reduceVoidUndefined && flags & 32768 /* Undefined */ && includes & 16384 /* Void */ || isFreshLiteralType(t) && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); @@ -55778,7 +57338,7 @@ var ts; if (t.flags & 1048576 /* Union */) { var origin = t.origin; if (t.aliasSymbol || origin && !(origin.flags & 1048576 /* Union */)) { - namedUnions.push(t); + ts.pushIfUnique(namedUnions, t); } else if (origin && origin.flags & 1048576 /* Union */) { addNamedUnions(namedUnions, origin.types); @@ -55812,20 +57372,17 @@ var ts; if (includes & 3 /* AnyOrUnknown */) { return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; } - switch (unionReduction) { - case 1 /* Literal */: - if (includes & (134220672 /* FreshableLiteral */ | 8192 /* UniqueESSymbol */)) { - removeRedundantLiteralTypes(typeSet, includes); - } - if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { - removeStringLiteralsMatchedByTemplateLiterals(typeSet); - } - break; - case 2 /* Subtype */: - if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) { - return errorType; - } - break; + if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */) || includes & 16384 /* Void */ && includes & 32768 /* Undefined */) { + removeRedundantLiteralTypes(typeSet, includes, !!(unionReduction & 2 /* Subtype */)); + } + if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { + removeStringLiteralsMatchedByTemplateLiterals(typeSet); + } + if (unionReduction === 2 /* Subtype */) { + typeSet = removeSubtypes(typeSet, !!(includes & 524288 /* Object */)); + if (!typeSet) { + return errorType; + } } if (typeSet.length === 0) { return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType : @@ -55860,18 +57417,23 @@ var ts; origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes); } } - var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) | - (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0); + var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | + (includes & 2097152 /* Intersection */ ? 67108864 /* ContainsIntersections */ : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } - function getUnionTypePredicate(signatures) { + function getUnionOrIntersectionTypePredicate(signatures, kind) { var first; var types = []; for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { var sig = signatures_6[_i]; var pred = getTypePredicateOfSignature(sig); if (!pred || pred.kind === 2 /* AssertsThis */ || pred.kind === 3 /* AssertsIdentifier */) { - continue; + if (kind !== 2097152 /* Intersection */) { + continue; + } + else { + return; // intersections demand all members be type predicates for the result to have a predicate + } } if (first) { if (!typePredicateKindsMatch(first, pred)) { @@ -55885,11 +57447,11 @@ var ts; types.push(pred.type); } if (!first) { - // No union signatures had a type predicate. + // No signatures had a type predicate. return undefined; } - var unionType = getUnionType(types); - return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, unionType); + var compositeType = getUnionOrIntersectionType(types, kind); + return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, compositeType); } function typePredicateKindsMatch(a, b) { return a.kind === b.kind && a.parameterIndex === b.parameterIndex; @@ -55914,8 +57476,8 @@ var ts; var typeKey = !origin ? getTypeListId(types) : origin.flags & 1048576 /* Union */ ? "|" + getTypeListId(origin.types) : origin.flags & 2097152 /* Intersection */ ? "&" + getTypeListId(origin.types) : - "#" + origin.type.id; - var id = typeKey + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + "#" + origin.type.id + "|" + getTypeListId(types); // origin type id alone is insufficient, as `keyof x` may resolve to multiple WIP values while `x` is still resolving + var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { type = createUnionType(types, aliasSymbol, aliasTypeArguments, origin); @@ -56041,7 +57603,7 @@ var ts; // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); }); if (index < 0) { return false; } @@ -56050,7 +57612,7 @@ var ts; // the unionTypes array. while (i < types.length) { var t = types[i]; - if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) { + if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -56079,14 +57641,14 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */); + types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */); return true; } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { var result = createType(2097152 /* Intersection */); result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */); result.types = types; - result.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. + result.aliasSymbol = aliasSymbol; result.aliasTypeArguments = aliasTypeArguments; return result; } @@ -56147,7 +57709,7 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } - var id = getTypeListId(typeSet) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeSet) + getAliasId(aliasSymbol, aliasTypeArguments); var result = intersectionTypes.get(id); if (!result) { if (includes & 1048576 /* Union */) { @@ -56190,7 +57752,7 @@ var ts; function checkCrossProductUnion(types) { var size = getCrossProductUnionSize(types); if (size >= 100000) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); return false; } @@ -56240,11 +57802,17 @@ var ts; type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } + function instantiateTypeAsMappedNameType(nameType, type, t) { + return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); + } function getIndexTypeForMappedType(type, noIndexSignatures) { var constraint = filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); }); var nameType = type.declaration.nameType && getTypeFromTypeNode(type.declaration.nameType); + // If the constraint is exclusively string/number/never type(s), we need to pull the property names from the modified type and run them through the `nameType` mapper as well + // since they won't appear in the constraint, due to subtype reducing with the string/number index types + var properties = nameType && everyType(constraint, function (t) { return !!(t.flags & (4 /* String */ | 8 /* Number */ | 131072 /* Never */)); }) && getPropertiesOfType(getApparentType(getModifiersTypeFromMappedType(type))); return nameType ? - mapType(constraint, function (t) { return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); }) : + getUnionType([mapType(constraint, function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); }), mapType(getUnionType(ts.map(properties || ts.emptyArray, function (p) { return getLiteralTypeFromProperty(p, 8576 /* StringOrNumberLiteralOrUnique */); })), function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); })]) : constraint; } // Ordinarily we reduce a keyof M, where M is a mapped type { [P in K as N

]: X }, to simply N. This however presumes @@ -56274,13 +57842,13 @@ var ts; function getLiteralTypeFromProperty(prop, include) { if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { var type = getSymbolLinks(getLateBoundSymbol(prop)).nameType; - if (!type && !ts.isKnownSymbol(prop)) { + if (!type) { if (prop.escapedName === "default" /* Default */) { type = getLiteralType("default"); } else { var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); - type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + type = name && getLiteralTypeFromPropertyName(name) || (!ts.isKnownSymbol(prop) ? getLiteralType(ts.symbolName(prop)) : undefined); } } if (type && type.flags & include) { @@ -56380,7 +57948,6 @@ var ts; var type = templateLiteralTypes.get(id); if (!type) { templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes)); - type.regularType = type; } return type; function addSpans(texts, types) { @@ -56412,10 +57979,8 @@ var ts; return type.flags & 128 /* StringLiteral */ ? type.value : type.flags & 256 /* NumberLiteral */ ? "" + type.value : type.flags & 2048 /* BigIntLiteral */ ? ts.pseudoBigIntToString(type.value) : - type.flags & 512 /* BooleanLiteral */ ? type.intrinsicName : - type.flags & 65536 /* Null */ ? "null" : - type.flags & 32768 /* Undefined */ ? "undefined" : - undefined; + type.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) ? type.intrinsicName : + undefined; } function createTemplateLiteralType(texts, types) { var type = createType(134217728 /* TemplateLiteral */); @@ -56474,7 +58039,7 @@ var ts; if (noImplicitAny) { return false; // Flag is meaningless under `noImplicitAny` mode } - if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + if (ts.getObjectFlags(type) & 8192 /* JSLiteral */) { return true; } if (type.flags & 1048576 /* Union */) { @@ -56484,20 +58049,18 @@ var ts; return ts.some(type.types, isJSLiteralType); } if (type.flags & 465829888 /* Instantiable */) { - return isJSLiteralType(getResolvedBaseConstraint(type)); + var constraint = getResolvedBaseConstraint(type); + return constraint !== type && isJSLiteralType(constraint); } return false; } function getPropertyNameFromIndex(indexType, accessNode) { - var accessExpression = accessNode && accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode : undefined; return isTypeUsableAsPropertyName(indexType) ? getPropertyNameFromType(indexType) : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : - accessNode && ts.isPropertyName(accessNode) ? - // late bound names are handled in the first branch, so here we only need to handle normal names - ts.getPropertyNameForPropertyNameNode(accessNode) : - undefined; + accessNode && ts.isPropertyName(accessNode) ? + // late bound names are handled in the first branch, so here we only need to handle normal names + ts.getPropertyNameForPropertyNameNode(accessNode) : + undefined; } function isUncalledFunctionReference(node, symbol) { if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { @@ -56511,17 +58074,17 @@ var ts; } function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, suppressNoImplicitAnyError, accessNode, accessFlags, noUncheckedIndexedAccessCandidate, reportDeprecated) { var _a; - var accessExpression = accessNode && accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode : undefined; + var accessExpression = accessNode && accessNode.kind === 203 /* ElementAccessExpression */ ? accessNode : undefined; var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode); if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { - if (reportDeprecated && accessNode && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) { + if (reportDeprecated && accessNode && prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) { var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); - errorOrSuggestion(/* isError */ false, deprecatedNode, ts.Diagnostics._0_is_deprecated, propName); + addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName); } if (accessExpression) { - markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 107 /* ThisKeyword */); + markPropertyAsReferenced(prop, accessExpression, isSelfTypeAccess(accessExpression.expression, objectType.symbol)); if (isAssignmentToReadonlyEntity(accessExpression, prop, ts.getAssignmentTargetKind(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); return undefined; @@ -56671,13 +58234,13 @@ var ts; } } function getIndexNodeForAccessExpression(accessNode) { - return accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode.argumentExpression : - accessNode.kind === 189 /* IndexedAccessType */ ? accessNode.indexType : - accessNode.kind === 158 /* ComputedPropertyName */ ? accessNode.expression : + return accessNode.kind === 203 /* ElementAccessExpression */ ? accessNode.argumentExpression : + accessNode.kind === 190 /* IndexedAccessType */ ? accessNode.indexType : + accessNode.kind === 159 /* ComputedPropertyName */ ? accessNode.expression : accessNode; } function isPatternLiteralPlaceholderType(type) { - return templateConstraintType.types.indexOf(type) !== -1 || !!(type.flags & 1 /* Any */); + return !!(type.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 64 /* BigInt */)); } function isPatternLiteralType(type) { return !!(type.flags & 134217728 /* TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType); @@ -56690,6 +58253,13 @@ var ts; } return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) { + type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ | + (isGenericObjectType(type.substitute) || isGenericObjectType(type.baseType) ? 8388608 /* IsGenericObjectType */ : 0); + } + return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); + } return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type) || isGenericTupleType(type); } function isGenericIndexType(type) { @@ -56700,6 +58270,13 @@ var ts; } return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) { + type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ | + (isGenericIndexType(type.substitute) || isGenericIndexType(type.baseType) ? 33554432 /* IsGenericIndexType */ : 0); + } + return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); + } return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) && !isPatternLiteralType(type); } function isThisTypeParameter(type) { @@ -56775,6 +58352,12 @@ var ts; } return type[cache] = type; } + function isConditionalTypeAlwaysTrueDisregardingInferTypes(type) { + var extendsInferParamMapper = type.root.inferTypeParameters && createTypeMapper(type.root.inferTypeParameters, ts.map(type.root.inferTypeParameters, function () { return wildcardType; })); + var checkType = type.checkType; + var extendsType = type.extendsType; + return isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(instantiateType(extendsType, extendsInferParamMapper))); + } function getSimplifiedConditionalType(type, writing) { var checkType = type.checkType; var extendsType = type.extendsType; @@ -56845,14 +58428,14 @@ var ts; // for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved // eagerly using the constraint type of 'this' at the given location. - if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 189 /* IndexedAccessType */ ? + if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 190 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, objectType.target.fixedLength) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, objectType.target.fixedLength)))) { if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; } // Defer the operation by creating an indexed access type. - var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + getAliasId(aliasSymbol, aliasTypeArguments); var type = indexedAccessTypes.get(id); if (!type) { indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined)); @@ -56928,16 +58511,32 @@ var ts; } return type; } - function getConditionalType(root, mapper) { + function isTypicalNondistributiveConditional(root) { + return !root.isDistributive + && root.node.checkType.kind === 180 /* TupleType */ + && ts.length(root.node.checkType.elements) === 1 + && root.node.extendsType.kind === 180 /* TupleType */ + && ts.length(root.node.extendsType.elements) === 1; + } + /** + * We syntactually check for common nondistributive conditional shapes and unwrap them into + * the intended comparison - we do this so we can check if the unwrapped types are generic or + * not and appropriately defer condition calculation + */ + function unwrapNondistributiveConditionalTuple(root, type) { + return isTypicalNondistributiveConditional(root) && isTupleType(type) ? getTypeArguments(type)[0] : type; + } + function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { var result; var extraTypes; // We loop here for an immediately nested conditional type in the false position, effectively treating // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { - var checkType = instantiateType(root.checkType, mapper); + var isUnwrapped = isTypicalNondistributiveConditional(root); + var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); - var extendsType = instantiateType(root.extendsType, mapper); + var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } @@ -56948,21 +58547,24 @@ var ts; // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. - inferTypes(context.inferences, checkType, extendsType, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(context.inferences, checkType, extendsType, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); } - combinedMapper = mergeTypeMappers(mapper, context.mapper); + // It's possible for 'infer T' type paramteters to be given uninstantiated constraints when the + // those type parameters are used in type references (see getInferredTypeParameterConstraint). For + // that reason we need context.mapper to be first in the combined mapper. See #42636 for examples. + combinedMapper = mapper ? combineTypeMappers(context.mapper, mapper) : context.mapper; } // Instantiate the extends type including inferences for 'infer T' type parameters - var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + var inferredExtendsType = combinedMapper ? instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), combinedMapper) : extendsType; // We attempt to resolve the conditional type only when the check and extends types are non-generic if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) { // Return falseType for a definitely false extends check. We check an instantiations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instantiations will be and we can just return the false branch type. - if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { + if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && ((checkType.flags & 1 /* Any */ && !isUnwrapped) || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { // Return union of trueType and falseType for 'any' since it matches anything - if (checkType.flags & 1 /* Any */) { + if (checkType.flags & 1 /* Any */ && !isUnwrapped) { (extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper)); } // If falseType is an immediately nested conditional type that isn't distributive or has an @@ -56991,12 +58593,12 @@ var ts; // Return a deferred type for a check that is neither definitely true nor definitely false result = createType(16777216 /* Conditional */); result.root = root; - result.checkType = checkType; - result.extendsType = extendsType; + result.checkType = instantiateType(root.checkType, mapper); + result.extendsType = instantiateType(root.extendsType, mapper); result.mapper = mapper; result.combinedMapper = combinedMapper; - result.aliasSymbol = root.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 + result.aliasSymbol = aliasSymbol || root.aliasSymbol; + result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 break; } return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result; @@ -57202,7 +58804,7 @@ var ts; } } var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return spread; } } @@ -57308,14 +58910,15 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */ | 4194304 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ function isSpreadableProperty(prop) { - return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) && + var _a; + return !ts.some(prop.declarations, ts.isPrivateIdentifierClassElementDeclaration) && (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || - !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); })); + !((_a = prop.declarations) === null || _a === void 0 ? void 0 : _a.some(function (decl) { return ts.isClassLike(decl.parent); }))); } function getSpreadSymbol(prop, readonly) { var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); @@ -57340,11 +58943,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 134220672 /* FreshableLiteral */) { + if (type.flags & 2944 /* Literal */) { if (!type.freshType) { - var freshType = type.flags & 134217728 /* TemplateLiteral */ ? - createTemplateLiteralType(type.texts, type.types) : - createLiteralType(type.flags, type.value, type.symbol); + var freshType = createLiteralType(type.flags, type.value, type.symbol); freshType.regularType = type; freshType.freshType = freshType; type.freshType = freshType; @@ -57354,12 +58955,12 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 134220672 /* FreshableLiteral */ ? type.regularType : + return type.flags & 2944 /* Literal */ ? type.regularType : type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = mapType(type, getRegularTypeOfLiteralType))) : type; } function isFreshLiteralType(type) { - return !!(type.flags & 134220672 /* FreshableLiteral */) && type.freshType === type; + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -57405,7 +59006,7 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 253 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 254 /* InterfaceDeclaration */)) { if (!ts.hasSyntacticModifier(container, 32 /* Static */) && (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; @@ -57440,17 +59041,17 @@ var ts; } function getArrayElementTypeNode(node) { switch (node.kind) { - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return getArrayElementTypeNode(node.type); - case 179 /* TupleType */: + case 180 /* TupleType */: if (node.elements.length === 1) { node = node.elements[0]; - if (node.kind === 181 /* RestType */ || node.kind === 192 /* NamedTupleMember */ && node.dotDotDotToken) { + if (node.kind === 182 /* RestType */ || node.kind === 193 /* NamedTupleMember */ && node.dotDotDotToken) { return getArrayElementTypeNode(node.type); } } break; - case 178 /* ArrayType */: + case 179 /* ArrayType */: return node.elementType; } return undefined; @@ -57468,8 +59069,8 @@ var ts; function getTypeFromTypeNodeWorker(node) { switch (node.kind) { case 128 /* AnyKeyword */: - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: return anyType; case 152 /* UnknownKeyword */: return unknownType; @@ -57496,70 +59097,70 @@ var ts; return node.flags & 131072 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType; case 136 /* IntrinsicKeyword */: return intrinsicMarkerType; - case 187 /* ThisType */: + case 188 /* ThisType */: case 107 /* ThisKeyword */: // TODO(rbuckton): `ThisKeyword` is no longer a `TypeNode`, but we defensively allow it here because of incorrect casts in the Language Service and because of `isPartOfTypeNode`. return getTypeFromThisTypeNode(node); - case 191 /* LiteralType */: + case 192 /* LiteralType */: return getTypeFromLiteralTypeNode(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return getTypeFromTypeReference(node); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return node.assertsModifier ? voidType : booleanType; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 178 /* ArrayType */: - case 179 /* TupleType */: + case 179 /* ArrayType */: + case 180 /* TupleType */: return getTypeFromArrayOrTupleTypeNode(node); - case 180 /* OptionalType */: + case 181 /* OptionalType */: return getTypeFromOptionalTypeNode(node); - case 182 /* UnionType */: + case 183 /* UnionType */: return getTypeFromUnionTypeNode(node); - case 183 /* IntersectionType */: + case 184 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 305 /* JSDocNullableType */: + case 306 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 307 /* JSDocOptionalType */: + case 308 /* JSDocOptionalType */: return addOptionality(getTypeFromTypeNode(node.type)); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return getTypeFromNamedTupleTypeNode(node); - case 186 /* ParenthesizedType */: - case 306 /* JSDocNonNullableType */: - case 301 /* JSDocTypeExpression */: + case 187 /* ParenthesizedType */: + case 307 /* JSDocNonNullableType */: + case 302 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 181 /* RestType */: + case 182 /* RestType */: return getTypeFromRestTypeNode(node); - case 309 /* JSDocVariadicType */: + case 310 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 308 /* JSDocFunctionType */: - case 313 /* JSDocSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 309 /* JSDocFunctionType */: + case 315 /* JSDocSignature */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return getTypeFromIndexedAccessTypeNode(node); - case 190 /* MappedType */: + case 191 /* MappedType */: return getTypeFromMappedTypeNode(node); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return getTypeFromConditionalTypeNode(node); - case 185 /* InferType */: + case 186 /* InferType */: return getTypeFromInferTypeNode(node); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: return getTypeFromTemplateTypeNode(node); - case 195 /* ImportType */: + case 196 /* ImportType */: return getTypeFromImportTypeNode(node); // This function assumes that an identifier, qualified name, or property access expression is a type expression // Callers should first ensure this by calling `isPartOfTypeNode` // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s. case 78 /* Identifier */: - case 157 /* QualifiedName */: - case 201 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: var symbol = getSymbolAtLocation(node); return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: @@ -57712,7 +59313,7 @@ var ts; } return result; } - function getObjectTypeInstantiation(type, mapper) { + function getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { var declaration = type.objectFlags & 4 /* Reference */ ? type.node : type.symbol.declarations[0]; var links = getNodeLinks(declaration); var target = type.objectFlags & 4 /* Reference */ ? links.resolvedType : @@ -57729,8 +59330,9 @@ var ts; outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } typeParameters = outerTypeParameters || ts.emptyArray; - typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? - ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration); }) : + var allDeclarations_1 = type.objectFlags & 4 /* Reference */ ? [declaration] : type.symbol.declarations; + typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 8192 /* Method */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? + ts.filter(typeParameters, function (tp) { return ts.some(allDeclarations_1, function (d) { return isTypeParameterPossiblyReferenced(tp, d); }); }) : typeParameters; links.outerTypeParameters = typeParameters; } @@ -57740,17 +59342,19 @@ var ts; // instantiation cache key from the type IDs of the type arguments. var combinedMapper_1 = combineTypeMappers(type.mapper, mapper); var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); }); - var id = getTypeListId(typeArguments); + var newAliasSymbol = aliasSymbol || type.aliasSymbol; + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + var id = getTypeListId(typeArguments) + getAliasId(newAliasSymbol, newAliasTypeArguments); if (!target.instantiations) { target.instantiations = new ts.Map(); - target.instantiations.set(getTypeListId(typeParameters), target); + target.instantiations.set(getTypeListId(typeParameters) + getAliasId(target.aliasSymbol, target.aliasTypeArguments), target); } var result = target.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(typeParameters, typeArguments); - result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper) : - target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) : - instantiateAnonymousType(target, newMapper); + result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) : + target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) : + instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments); target.instantiations.set(id, result); } return result; @@ -57758,9 +59362,9 @@ var ts; return type; } function maybeTypeParameterReference(node) { - return !(node.kind === 157 /* QualifiedName */ || - node.parent.kind === 173 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName || - node.parent.kind === 195 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier); + return !(node.kind === 158 /* QualifiedName */ || + node.parent.kind === 174 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName || + node.parent.kind === 196 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier); } function isTypeParameterPossiblyReferenced(tp, node) { // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks @@ -57769,22 +59373,25 @@ var ts; if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container = tp.symbol.declarations[0].parent; for (var n = node; n !== container; n = n.parent) { - if (!n || n.kind === 230 /* Block */ || n.kind === 184 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) { + if (!n || n.kind === 231 /* Block */ || n.kind === 185 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) { return true; } } - return !!ts.forEachChild(node, containsReference); + return containsReference(node); } return true; function containsReference(node) { switch (node.kind) { - case 187 /* ThisType */: + case 188 /* ThisType */: return !!tp.isThisType; case 78 /* Identifier */: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return true; + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + return (!node.type && !!node.body) || !!ts.forEachChild(node, containsReference); } return !!ts.forEachChild(node, containsReference); } @@ -57799,7 +59406,7 @@ var ts; } return undefined; } - function instantiateMappedType(type, mapper) { + function instantiateMappedType(type, mapper, aliasSymbol, aliasTypeArguments) { // 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. @@ -57814,7 +59421,7 @@ var ts; if (typeVariable) { var mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapType(getReducedType(mappedTypeVariable), function (t) { + return mapTypeWithAlias(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) { if (!type.declaration.nameType) { if (isArrayType(t)) { @@ -57830,11 +59437,11 @@ var ts; return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper)); } return t; - }); + }, aliasSymbol, aliasTypeArguments); } } // If the constraint type of the instantiation is the wildcard type, return the wildcard type. - return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper); + return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments); } function getModifiedReadonlyState(state, modifiers) { return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state; @@ -57881,7 +59488,7 @@ var ts; strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; } - function instantiateAnonymousType(type, mapper) { + function instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; @@ -57894,29 +59501,29 @@ var ts; } result.target = type; result.mapper = mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + result.aliasSymbol = aliasSymbol || type.aliasSymbol; + result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); return result; } - function getConditionalTypeInstantiation(type, mapper) { + function getConditionalTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { var root = type.root; if (root.outerTypeParameters) { // We are instantiating a conditional type that has one or more type parameters in scope. Apply the // mapper to the type parameters to produce the effective list of type arguments, and compute the // instantiation cache key from the type IDs of the type arguments. var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); }); - var id = getTypeListId(typeArguments); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var result = root.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); - result = instantiateConditionalType(root, newMapper); + result = instantiateConditionalType(root, newMapper, aliasSymbol, aliasTypeArguments); root.instantiations.set(id, result); } return result; } return type; } - function instantiateConditionalType(root, mapper) { + function instantiateConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { // Check if we have a conditional type where the check type is a naked type parameter. If so, // the conditional type is distributive over union types and when T is instantiated to a union // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y). @@ -57924,31 +59531,34 @@ var ts; var checkType_1 = root.checkType; var instantiatedType = getMappedType(checkType_1, mapper); if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) { - return mapType(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); }); + return mapTypeWithAlias(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); }, aliasSymbol, aliasTypeArguments); } } - return getConditionalType(root, mapper); + return getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments); } function instantiateType(type, mapper) { - if (!(type && mapper && couldContainTypeVariables(type))) { + return type && mapper ? instantiateTypeWithAlias(type, mapper, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined) : type; + } + function instantiateTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) { + if (!couldContainTypeVariables(type)) { return type; } if (instantiationDepth === 50 || instantiationCount >= 5000000) { // 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. - ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); return errorType; } totalInstantiationCount++; instantiationCount++; instantiationDepth++; - var result = instantiateTypeWorker(type, mapper); + var result = instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments); instantiationDepth--; return result; } - function instantiateTypeWorker(type, mapper) { + function instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments) { var flags = type.flags; if (flags & 262144 /* TypeParameter */) { return getMappedType(type, mapper); @@ -57956,12 +59566,15 @@ var ts; if (flags & 524288 /* Object */) { var objectFlags = type.objectFlags; if (objectFlags & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */)) { - if (objectFlags & 4 /* Reference */ && !(type.node)) { + if (objectFlags & 4 /* Reference */ && !type.node) { var resolvedTypeArguments = type.resolvedTypeArguments; var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type; } - return getObjectTypeInstantiation(type, mapper); + if (objectFlags & 1024 /* ReverseMapped */) { + return instantiateReverseMappedType(type, mapper); + } + return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments); } return type; } @@ -57969,10 +59582,14 @@ var ts; var origin = type.flags & 1048576 /* Union */ ? type.origin : undefined; var types = origin && origin.flags & 3145728 /* UnionOrIntersection */ ? origin.types : type.types; var newTypes = instantiateTypes(types, mapper); - return newTypes === types ? type : - flags & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ? - getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : - getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + if (newTypes === types && aliasSymbol === type.aliasSymbol) { + return type; + } + var newAliasSymbol = aliasSymbol || type.aliasSymbol; + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + return flags & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ? + getIntersectionType(newTypes, newAliasSymbol, newAliasTypeArguments) : + getUnionType(newTypes, 1 /* Literal */, newAliasSymbol, newAliasTypeArguments); } if (flags & 4194304 /* Index */) { return getIndexType(instantiateType(type.type, mapper)); @@ -57984,10 +59601,12 @@ var ts; return getStringMappingType(type.symbol, instantiateType(type.type, mapper)); } if (flags & 8388608 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + var newAliasSymbol = aliasSymbol || type.aliasSymbol; + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, newAliasSymbol, newAliasTypeArguments); } if (flags & 16777216 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper), aliasSymbol, aliasTypeArguments); } if (flags & 33554432 /* Substitution */) { var maybeVariable = instantiateType(type.baseType, mapper); @@ -58004,6 +59623,21 @@ var ts; } return type; } + function instantiateReverseMappedType(type, mapper) { + var innerMappedType = instantiateType(type.mappedType, mapper); + if (!(ts.getObjectFlags(innerMappedType) & 32 /* Mapped */)) { + return type; + } + var innerIndexType = instantiateType(type.constraintType, mapper); + if (!(innerIndexType.flags & 4194304 /* Index */)) { + return type; + } + var instantiated = inferTypeForHomomorphicMappedType(instantiateType(type.source, mapper), innerMappedType, innerIndexType); + if (instantiated) { + return instantiated; + } + return type; // Nested invocation of `inferTypeForHomomorphicMappedType` or the `source` instantiated into something unmappable + } function getPermissiveInstantiation(type) { return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); @@ -58030,35 +59664,35 @@ var 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) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 251 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type return isContextSensitiveFunctionLikeDeclaration(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return ts.some(node.properties, isContextSensitive); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return ts.some(node.elements, isContextSensitive); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return (node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */) && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isContextSensitive(node.expression); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); - case 280 /* JsxAttribute */: { + case 281 /* JsxAttribute */: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. var initializer = node.initializer; return !!initializer && isContextSensitive(initializer); } - case 283 /* JsxExpression */: { + case 284 /* JsxExpression */: { // It is possible to that node.expression is undefined (e.g

) var expression = node.expression; return !!expression && isContextSensitive(expression); @@ -58077,7 +59711,7 @@ var ts; if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 209 /* ArrowFunction */) { + if (node.kind !== 210 /* ArrowFunction */) { // If the first parameter is not an explicit 'this' parameter, then the function has // an implicit 'this' parameter which is subject to contextual typing. var parameter = ts.firstOrUndefined(node.parameters); @@ -58090,7 +59724,7 @@ var ts; } function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 230 /* Block */ && isContextSensitive(node.body); + return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 231 /* Block */ && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -58193,23 +59827,23 @@ var ts; return true; } switch (node.kind) { - case 283 /* JsxExpression */: - case 207 /* ParenthesizedExpression */: + case 284 /* JsxExpression */: + case 208 /* ParenthesizedExpression */: return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (node.operatorToken.kind) { case 62 /* EqualsToken */: case 27 /* CommaToken */: return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); } break; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer); } return false; @@ -58409,7 +60043,7 @@ var ts; } function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) { switch (child.kind) { - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: // child is of the type of the expression return { errorNode: child, innerExpression: child.expression, nameType: nameType }; case 11 /* JsxText */: @@ -58418,9 +60052,9 @@ var ts; } // child is a string return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() }; - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: // child is of type JSX.Element return { errorNode: child, innerExpression: child, nameType: nameType }; default: @@ -58568,11 +60202,11 @@ var ts; } _b = prop.kind; switch (_b) { - case 168 /* SetAccessor */: return [3 /*break*/, 2]; - case 167 /* GetAccessor */: return [3 /*break*/, 2]; - case 165 /* MethodDeclaration */: return [3 /*break*/, 2]; - case 289 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; - case 288 /* PropertyAssignment */: return [3 /*break*/, 4]; + case 169 /* SetAccessor */: return [3 /*break*/, 2]; + case 168 /* GetAccessor */: return [3 /*break*/, 2]; + case 166 /* MethodDeclaration */: return [3 /*break*/, 2]; + case 290 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 289 /* PropertyAssignment */: return [3 /*break*/, 4]; } return [3 /*break*/, 6]; case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; @@ -58649,8 +60283,8 @@ var ts; return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; - var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 165 /* MethodDeclaration */ && - kind !== 164 /* MethodSignature */ && kind !== 166 /* Constructor */; + var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 166 /* MethodDeclaration */ && + kind !== 165 /* MethodSignature */ && kind !== 167 /* Constructor */; var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { @@ -58883,7 +60517,7 @@ var ts; // Type number or any numeric literal type is assignable to any numeric enum type or any // numeric enum literal type. This rule exists for backwards compatibility reasons because // bit-flag enum types sometimes look like literal enum types with numeric literal values. - if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) + if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || relation === assignableRelation && t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) return true; } return false; @@ -58920,7 +60554,7 @@ var ts; return false; } function isIgnoredJsxProperty(source, sourceProp) { - return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); + return ts.getObjectFlags(source) & 2048 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { while (true) { @@ -58930,6 +60564,7 @@ var ts; type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute : type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : type; + t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) break; type = t; @@ -58967,7 +60602,7 @@ var ts; reportIncompatibleStack(); } if (overflow) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); @@ -59103,6 +60738,14 @@ var ts; } break; } + case ts.Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target.code: { + secondaryRootErrors.unshift([ts.Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target, args[0], args[1]]); + break; + } + case ts.Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target.code: { + secondaryRootErrors.unshift([ts.Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target, args[0], args[1], args[2]]); + break; + } default: return ts.Debug.fail("Unhandled Diagnostic: " + msg.code); } @@ -59163,6 +60806,7 @@ var ts; reportError(ts.Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2, needsOriginalSource ? sourceType : generalizedSourceType, targetType, typeToString(constraint)); } else { + errorInfo = undefined; reportError(ts.Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, generalizedSourceType); } } @@ -59238,7 +60882,7 @@ var ts; if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { return -1 /* True */; } - reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */)); + reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 2048 /* JsxAttributes */)); return 0 /* False */; } // Normalize the source and target types: Turn fresh literal types into regular literal types, @@ -59273,16 +60917,16 @@ var ts; target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) { var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */); if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) { - if (source === nullStrippedTarget) - return -1 /* True */; - target = nullStrippedTarget; + target = getNormalizedType(nullStrippedTarget, /*writing*/ true); } + if (source === nullStrippedTarget) + return -1 /* True */; } if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); + var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384 /* FreshLiteral */); if (isPerformingExcessPropertyChecks) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -59367,7 +61011,7 @@ var ts; // We suppress recursive intersection property checks because they can generate lots of work when relating // recursive intersections that are structurally similar but not exactly identical. See #37854. if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) { + isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 524288 /* NonInferrableType */); }))) { inPropertyCheck = true; result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */); inPropertyCheck = false; @@ -59376,8 +61020,10 @@ var ts; return result; function reportErrorResults(source, target, result, isComparingJsxAttributes) { if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; + var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); + var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); + source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; + target = (originalTarget.aliasSymbol || targetHasBase) ? originalTarget : target; var maybeSuppress = overrideNextErrorInfo > 0; if (maybeSuppress) { overrideNextErrorInfo--; @@ -59418,13 +61064,13 @@ var ts; } } function traceUnionsOrIntersectionsTooLarge(source, target) { - if (!ts.tracing.isTracing()) { + if (!ts.tracing) { return; } if ((source.flags & 3145728 /* UnionOrIntersection */) && (target.flags & 3145728 /* UnionOrIntersection */)) { var sourceUnionOrIntersection = source; var targetUnionOrIntersection = target; - if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 262144 /* PrimitiveUnion */) { + if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 65536 /* PrimitiveUnion */) { // There's a fast path for comparing primitive unions return; } @@ -59449,11 +61095,11 @@ var ts; } traceUnionsOrIntersectionsTooLarge(source, target); if (flags & 3145728 /* UnionOrIntersection */) { - var result_6 = eachTypeRelatedToSomeType(source, target); - if (result_6) { - result_6 &= eachTypeRelatedToSomeType(target, source); + var result_7 = eachTypeRelatedToSomeType(source, target); + if (result_7) { + result_7 &= eachTypeRelatedToSomeType(target, source); } - return result_6; + return result_7; } return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */); } @@ -59467,10 +61113,11 @@ var ts; return getUnionType(ts.reduceLeft(types, appendPropType, /*initial*/ undefined) || ts.emptyArray); } function hasExcessProperties(source, target, reportErrors) { - if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + var _a; + if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 8192 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; @@ -59513,7 +61160,7 @@ var ts; } else { // use the property's value declaration if the property is assigned inside the literal itself - var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + var objectLiteralDeclaration_1 = ((_a = source.symbol) === null || _a === void 0 ? void 0 : _a.declarations) && ts.firstOrUndefined(source.symbol.declarations); var suggestion = void 0; if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) { var propDeclaration = prop.valueDeclaration; @@ -59542,11 +61189,11 @@ var ts; } } }; - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - var state_4 = _loop_16(prop); - if (typeof state_4 === "object") - return state_4.value; + for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { + var prop = _b[_i]; + var state_5 = _loop_16(prop); + if (typeof state_5 === "object") + return state_5.value; } return false; } @@ -59568,8 +61215,17 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) { - return -1 /* True */; + if (target.flags & 1048576 /* Union */) { + if (containsType(targetTypes, source)) { + return -1 /* True */; + } + var match = getMatchingUnionConstituentForType(target, source); + if (match) { + var related = isRelatedTo(source, match, /*reportErrors*/ false); + if (related) { + return related; + } + } } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { var type = targetTypes_1[_i]; @@ -59743,9 +61399,16 @@ var ts; targetStack = []; } else { + // generate a key where all type parameter id positions are replaced with unconstrained type parameter ids + // this isn't perfect - nested type references passed as type arguments will muck up the indexes and thus + // prevent finding matches- but it should hit up the common cases + var broadestEquivalentId = id.split(",").map(function (i) { return i.replace(/-\d+/g, function (_match, offset) { + var index = ts.length(id.slice(0, offset).match(/[-=]/g) || undefined); + return "=" + index; + }); }).join(","); for (var i = 0; i < maybeCount; i++) { // If source and target are already being compared, consider them related with assumptions - if (id === maybeKeys[i]) { + if (id === maybeKeys[i] || broadestEquivalentId === maybeKeys[i]) { return 3 /* Maybe */; } } @@ -59775,7 +61438,7 @@ var ts; }; } if (expandingFlags === 3 /* Both */) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { sourceId: source.id, sourceIdStack: sourceStack.map(function (t) { return t.id; }), targetId: target.id, @@ -59810,9 +61473,9 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { - ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) { @@ -59834,8 +61497,21 @@ var ts; if (target.flags & 2097152 /* Intersection */) { return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */); } - // Source is an intersection. Check to see if any constituents of the intersection are immediately related - // to the target. + // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the + // constraints of all non-primitive types in the source into a new intersection. We do this because the + // intersection may further constrain the constraints of the non-primitive types. For example, given a type + // parameter 'T extends 1 | 2', the intersection 'T & 1' should be reduced to '1' such that it doesn't + // appear to be comparable to '2'. + if (relation === comparableRelation && target.flags & 131068 /* Primitive */) { + var constraints = ts.sameMap(source.types, function (t) { return t.flags & 131068 /* Primitive */ ? t : getBaseConstraintOfType(t) || unknownType; }); + if (constraints !== source.types) { + source = getIntersectionType(constraints); + if (!(source.flags & 2097152 /* Intersection */)) { + return isRelatedTo(source, target, /*reportErrors*/ false); + } + } + } + // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually // useful and leads to some confusing error messages. Instead it is better to let the below checks @@ -59855,21 +61531,21 @@ var ts; if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_7 = 0 /* False */; + var result_8 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_7 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_8; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_7 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_8; } } } @@ -59949,6 +61625,20 @@ var ts; } } else if (target.flags & 8388608 /* IndexedAccess */) { + if (source.flags & 8388608 /* IndexedAccess */) { + // Relate components directly before falling back to constraint relationships + // A type S[K] is related to a type T[J] if S is related to T and K is related to J. + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + if (reportErrors) { + originalErrorInfo = errorInfo; + } + } // A type S is related to a type T[K] if S is related to C, where C is the base // constraint of T[K] for writing. if (relation === assignableRelation || relation === comparableRelation) { @@ -59959,11 +61649,24 @@ var ts; if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) { var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0); var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, target.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, accessFlags); - if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) { - return result; + if (constraint) { + if (reportErrors && originalErrorInfo) { + // create a new chain for the constraint error + resetErrorInfo(saveErrorInfo); + } + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + // prefer the shorter chain of the constraint comparison chain, and the direct comparison chain + if (reportErrors && originalErrorInfo && errorInfo) { + errorInfo = countMessageChainBreadth([originalErrorInfo]) <= countMessageChainBreadth([errorInfo]) ? originalErrorInfo : errorInfo; + } } } } + if (reportErrors) { + originalErrorInfo = undefined; + } } else if (isGenericMappedType(target) && !target.declaration.nameType) { // A source type T is related to a target type { [P in X]: T[P] } @@ -60007,27 +61710,48 @@ var ts; } } } - else if (target.flags & 134217728 /* TemplateLiteral */ && source.flags & 128 /* StringLiteral */) { - if (isPatternLiteralType(target)) { - // match all non-`string` segments - var result_8 = inferLiteralsFromTemplateLiteralType(source, target); - if (result_8 && ts.every(result_8, function (r, i) { return isStringLiteralTypeValueParsableAsType(r, target.types[i]); })) { - return -1 /* True */; - } + else if (target.flags & 16777216 /* Conditional */) { + var c = target; + // Check if the conditional is always true or always false but still deferred for distribution purposes + var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); + var skipFalse = !skipTrue && isConditionalTypeAlwaysTrueDisregardingInferTypes(c); + // Instantiate with a replacement mapper if the conditional is distributive, replacing the check type with a clone of itself, + // this way {x: string | number, y: string | number} -> (T extends T ? { x: T, y: T } : never) appropriately _fails_ when + // T = string | number (since that will end up distributing and producing `{x: string, y: string} | {x: number, y: number}`, + // to which `{x: string | number, y: string | number}` isn't assignable) + var distributionMapper = void 0; + var checkVar = getActualTypeVariable(c.root.checkType); + if (c.root.isDistributive && checkVar.flags & 262144 /* TypeParameter */) { + var newParam = cloneTypeParameter(checkVar); + distributionMapper = prependTypeMapping(checkVar, newParam, c.mapper); + newParam.mapper = distributionMapper; + } + // TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't) + var localResult = void 0; + if (skipTrue || (localResult = isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.trueType), distributionMapper) : getTrueTypeFromConditionalType(c), /*reportErrors*/ false))) { + if (!skipFalse) { + localResult = (localResult || 3 /* Maybe */) & isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.falseType), distributionMapper) : getFalseTypeFromConditionalType(c), /*reportErrors*/ false); + } + } + if (localResult) { + resetErrorInfo(saveErrorInfo); + return localResult; } } - if (source.flags & 8650752 /* TypeVariable */) { - if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { - // A type S[K] is related to a type T[J] if S is related to T and K is related to J. - if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { - result &= isRelatedTo(source.indexType, target.indexType, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } + else if (target.flags & 134217728 /* TemplateLiteral */) { + if (source.flags & 134217728 /* TemplateLiteral */) { + // Report unreliable variance for type variables referenced in template literal type placeholders. + // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. + instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } - else { + var result_9 = inferTypesFromTemplateLiteralType(source, target); + if (result_9 && ts.every(result_9, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { + return -1 /* True */; + } + } + if (source.flags & 8650752 /* TypeVariable */) { + // IndexedAccess comparisons are handled above in the `target.flags & TypeFlage.IndexedAccess` branch + if (!(source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */)) { var constraint = getConstraintOfType(source); if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. @@ -60042,7 +61766,7 @@ var ts; return result; } // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example - else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, intersectionState)) { + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors && !(target.flags & source.flags & 262144 /* TypeParameter */), /*headMessage*/ undefined, intersectionState)) { resetErrorInfo(saveErrorInfo); return result; } @@ -60055,17 +61779,10 @@ var ts; } } else if (source.flags & 134217728 /* TemplateLiteral */) { - if (target.flags & 134217728 /* TemplateLiteral */) { - if (source.texts.length === target.texts.length && - source.types.length === target.types.length && - ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) && - ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 /* Any */ | 4 /* String */)) || !!isRelatedTo(t, target.types[i], /*reportErrors*/ false); })) { - return -1 /* True */; - } - } - else { - var constraint = getBaseConstraintOfType(source); - if (result = isRelatedTo(constraint && constraint !== source ? constraint : stringType, target, reportErrors)) { + if (!(target.flags & 134217728 /* TemplateLiteral */)) { + var baseConstraint = getBaseConstraintOfType(source); + var constraint = baseConstraint && baseConstraint !== source ? baseConstraint : stringType; + if (result = isRelatedTo(constraint, target, reportErrors)) { resetErrorInfo(saveErrorInfo); return result; } @@ -60097,7 +61814,7 @@ var ts; if (sourceParams) { // If the source has infer type parameters, we instantiate them in the context of the target var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo); - inferTypes(ctx.inferences, target.extendsType, sourceExtends, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); sourceExtends = instantiateType(sourceExtends, ctx.mapper); mapper = ctx.mapper; } @@ -60155,7 +61872,7 @@ var ts; return 0 /* False */; } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && - !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { + !(ts.getObjectFlags(source) & 4096 /* MarkerType */ || ts.getObjectFlags(target) & 4096 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. @@ -60183,7 +61900,7 @@ var ts; } // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})` // and not `{} <- fresh({}) <- {[idx: string]: any}` - else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) { + else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 16384 /* FreshLiteral */ && !isEmptyObjectType(source)) { return 0 /* False */; } // Even if relationship doesn't hold for unions, intersections, or generic type references, @@ -60221,14 +61938,19 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_9) { - return result_9; + var result_10 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_10) { + return result_10; } } } } return 0 /* False */; + function countMessageChainBreadth(info) { + if (!info) + return 0; + return ts.reduceLeft(info, function (value, chain) { return value + 1 + countMessageChainBreadth(chain.next); }, 0); + } function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) { if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) { return result; @@ -60290,13 +62012,13 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_10; + var result_11; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + if (result_11 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { - return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_11 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } } @@ -60327,7 +62049,7 @@ var ts; numCombinations *= countTypes(getTypeOfSymbol(sourceProperty)); if (numCombinations > 25) { // We've reached the complexity limit. - ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); return 0 /* False */; } } @@ -60366,8 +62088,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_6 = _loop_18(i); - switch (state_6) { + var state_7 = _loop_18(i); + switch (state_7) { case "continue-outer": continue outer; } } @@ -60380,9 +62102,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_5 = _loop_17(combination); - if (typeof state_5 === "object") - return state_5.value; + var state_6 = _loop_17(combination); + if (typeof state_6 === "object") + return state_6.value; } // Compare the remaining non-discriminant properties of each match. var result = -1 /* True */; @@ -60436,7 +62158,7 @@ var ts; ts.Debug.assertIsDefined(links.deferralParent); ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */); - var result_11 = unionParent ? 0 /* False */ : -1 /* True */; + var result_12 = unionParent ? 0 /* False */ : -1 /* True */; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -60446,7 +62168,7 @@ var ts; // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_11 &= related; + result_12 &= related; } else { if (related) { @@ -60454,17 +62176,17 @@ var ts; } } } - if (unionParent && !result_11 && targetIsOptional) { - result_11 = isRelatedTo(source, undefinedType); + if (unionParent && !result_12 && targetIsOptional) { + result_12 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_11 && reportErrors) { + if (unionParent && !result_12 && reportErrors) { // The easiest way to get the right errors here is to un-defer (which may be costly) // If it turns out this is too costly too often, we can replicate the error handling logic within // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union // type on which to hand discriminable properties, which we are expressly trying to avoid here) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_11; + return result_12; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState); @@ -60795,7 +62517,7 @@ var ts; var targetSignature = ts.first(targetSignatures); result = signatureRelatedTo(sourceSignature, targetSignature, eraseGenerics, reportErrors, incompatibleReporter(sourceSignature, targetSignature)); if (!result && reportErrors && kind === 1 /* Construct */ && (sourceObjectFlags & targetObjectFlags) && - (((_a = targetSignature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 166 /* Constructor */ || ((_b = sourceSignature.declaration) === null || _b === void 0 ? void 0 : _b.kind) === 166 /* Constructor */)) { + (((_a = targetSignature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 167 /* Constructor */ || ((_b = sourceSignature.declaration) === null || _b === void 0 ? void 0 : _b.kind) === 167 /* Constructor */)) { var constructSignatureToString = function (signature) { return signatureToString(signature, /*enclosingDeclaration*/ undefined, 262144 /* WriteArrowStyleSignature */, kind); }; @@ -60903,10 +62625,17 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetType = getIndexTypeOfType(target, kind); - if (!targetType || targetType.flags & 1 /* Any */ && !sourceIsPrimitive) { - // Index signature of type any permits assignment from everything but primitives + if (!targetType) { return -1 /* True */; } + if (targetType.flags & 1 /* Any */ && !sourceIsPrimitive) { + // An index signature of type `any` permits assignment from everything but primitives, + // provided that there is also a `string` index signature of type `any`. + var stringIndexType = kind === 0 /* String */ ? targetType : getIndexTypeOfType(target, 0 /* String */); + if (stringIndexType && stringIndexType.flags & 1 /* Any */) { + return -1 /* True */; + } + } if (isGenericMappedType(source)) { // A generic mapped type { [P in K]: T } is related to a type with an index signature // { [x: string]: U }, and optionally with an index signature { [x: number]: V }, @@ -61061,7 +62790,7 @@ var ts; // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); - result.objectFlags |= 8192 /* MarkerType */; + result.objectFlags |= 4096 /* MarkerType */; return result; } function getAliasVariances(symbol) { @@ -61082,7 +62811,7 @@ var ts; if (typeParameters === void 0) { typeParameters = ts.emptyArray; } var variances = cache.variances; if (!variances) { - ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); // The emptyArray singleton is used to signal a recursive invocation. cache.variances = ts.emptyArray; variances = []; @@ -61121,7 +62850,7 @@ var ts; _loop_19(tp); } cache.variances = variances; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } return variances; } @@ -61149,7 +62878,7 @@ var ts; return !!(ts.getObjectFlags(type) & 4 /* Reference */) && !type.node; } function isTypeReferenceWithGenericArguments(type) { - return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return !!(t.flags & 262144 /* TypeParameter */) || isTypeReferenceWithGenericArguments(t); }); } /** * getTypeReferenceId(A) returns "111=0-12=1" @@ -61235,8 +62964,8 @@ var ts; } // Return true if the given class derives from each of the declaring classes of the protected // constituents of the given property. - function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) { + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p, writing) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons @@ -61254,23 +62983,26 @@ var ts; function isDeeplyNestedType(type, stack, depth) { if (depth >= 5) { var identity_1 = getRecursionIdentity(type); - if (identity_1) { - var count = 0; - for (var i = 0; i < depth; i++) { - if (getRecursionIdentity(stack[i]) === identity_1) { - count++; - if (count >= 5) { - return true; - } + var count = 0; + for (var i = 0; i < depth; i++) { + if (getRecursionIdentity(stack[i]) === identity_1) { + count++; + if (count >= 5) { + return true; } } } } return false; } - // Types with constituents that could circularly reference the type have a recursion identity. The recursion - // identity is some object that is common to instantiations of the type with the same origin. + // The recursion identity of a type is an object identity that is shared among multiple instantiations of the type. + // We track recursion identities in order to identify deeply nested and possibly infinite type instantiations with + // the same origin. For example, when type parameters are in scope in an object type such as { x: T }, all + // instantiations of that type have the same recursion identity. The default recursion identity is the object + // identity of the type, meaning that every type is unique. Generally, types with constituents that could circularly + // reference the type have a recursion identity that differs from the object identity. function getRecursionIdentity(type) { + // Object and array literals are known not to contain recursive references and don't need a recursion identity. if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) { if (ts.getObjectFlags(type) && 4 /* Reference */ && type.node) { // Deferred type references are tracked through their associated AST node. This gives us finer @@ -61288,6 +63020,9 @@ var ts; return type.target; } } + if (type.flags & 262144 /* TypeParameter */) { + return type.symbol; + } if (type.flags & 8388608 /* IndexedAccess */) { // Identity is the leftmost object type in a chain of indexed accesses, eg, in A[P][Q] it is A do { @@ -61299,7 +63034,7 @@ var ts; // The root object represents the origin of the conditional type return type.root; } - return undefined; + return type; } function isPropertyIdenticalTo(sourceProp, targetProp) { return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; @@ -61438,6 +63173,9 @@ var ts; // of those literal types. Otherwise, return the leftmost type for which no type to the // right is a supertype. function getSupertypeOrUnion(types) { + if (types.length === 1) { + return types[0]; + } return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); @@ -61472,9 +63210,32 @@ var ts; // or if it is not the undefined or null type and if it is assignable to ReadonlyArray return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } + function getSingleBaseForNonAugmentingSubtype(type) { + if (!(ts.getObjectFlags(type) & 4 /* Reference */) || !(ts.getObjectFlags(type.target) & 3 /* ClassOrInterface */)) { + return undefined; + } + if (ts.getObjectFlags(type) & 33554432 /* IdenticalBaseTypeCalculated */) { + return ts.getObjectFlags(type) & 67108864 /* IdenticalBaseTypeExists */ ? type.cachedEquivalentBaseType : undefined; + } + type.objectFlags |= 33554432 /* IdenticalBaseTypeCalculated */; + var target = type.target; + var bases = getBaseTypes(target); + if (bases.length !== 1) { + return undefined; + } + if (getMembersOfSymbol(type.symbol).size) { + return undefined; // If the interface has any members, they may subtype members in the base, so we should do a full structural comparison + } + var instantiatedBase = !ts.length(target.typeParameters) ? bases[0] : instantiateType(bases[0], createTypeMapper(target.typeParameters, getTypeArguments(type).slice(0, target.typeParameters.length))); + if (ts.length(getTypeArguments(type)) > ts.length(target.typeParameters)) { + instantiatedBase = getTypeWithThisArgument(instantiatedBase, ts.last(getTypeArguments(type))); + } + type.objectFlags |= 67108864 /* IdenticalBaseTypeExists */; + return type.cachedEquivalentBaseType = instantiatedBase; + } function isEmptyArrayLiteralType(type) { - var elementType = isArrayType(type) ? getTypeArguments(type)[0] : undefined; - return elementType === undefinedWideningType || elementType === implicitNeverType; + var elementType = getElementTypeOfArrayType(type); + return strictNullChecks ? elementType === implicitNeverType : elementType === undefinedWideningType; } function isTupleLikeType(type) { return isTupleType(type) || !!getPropertyOfType(type, "0"); @@ -61498,6 +63259,13 @@ var ts; function isUnitType(type) { return !!(type.flags & 109440 /* Unit */); } + function isUnitLikeType(type) { + return type.flags & 2097152 /* Intersection */ ? ts.some(type.types, isUnitType) : + !!(type.flags & 109440 /* Unit */); + } + function extractUnitType(type) { + return type.flags & 2097152 /* Intersection */ ? ts.find(type.types, isUnitType) || type : type; + } function isLiteralType(type) { return type.flags & 16 /* Boolean */ ? true : type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : @@ -61505,7 +63273,7 @@ var ts; } function getBaseTypeOfLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ ? stringType : + type.flags & 128 /* StringLiteral */ ? stringType : type.flags & 256 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : @@ -61514,7 +63282,7 @@ var ts; } function getWidenedLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : @@ -61648,14 +63416,17 @@ var ts; return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { + // First reduce away any constituents that are assignable to 'undefined' or 'null'. This not only eliminates + // 'undefined' and 'null', but also higher-order types such as a type parameter 'U extends undefined | null' + // that isn't eliminated by a NonNullable instantiation. + var reducedType = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); if (!deferredGlobalNonNullableTypeAlias) { deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; } - // Use NonNullable global type alias if available to improve quick info/declaration emit - if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { - return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); - } - return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior + // If the NonNullable type is available, return an instantiation. Otherwise just return the reduced type. + return deferredGlobalNonNullableTypeAlias !== unknownSymbol ? + getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [reducedType]) : + reducedType; } function getNonNullableType(type) { return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; @@ -61708,7 +63479,7 @@ var ts; function isObjectTypeWithInferableIndex(type) { return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 && - !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */); @@ -61741,7 +63512,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 16384 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -61752,7 +63523,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags; - regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */; + regularNew.objectFlags |= resolved.objectFlags & ~16384 /* FreshLiteral */; type.regularType = regularNew; return regularNew; } @@ -61782,7 +63553,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { var t = _a[_i]; - if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 4194304 /* ContainsSpread */)) { for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { var prop = _c[_b]; names.set(prop.escapedName, prop); @@ -61831,14 +63602,14 @@ var ts; var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); - result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening + result.objectFlags |= (ts.getObjectFlags(type) & (8192 /* JSLiteral */ | 524288 /* NonInferrableType */)); // Retain js literal flag through widening return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, /*context*/ undefined); } function getWidenedTypeWithContext(type, context) { - if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) { + if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) { if (context === undefined && type.widened) { return type.widened; } @@ -61883,7 +63654,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) { if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -61909,7 +63680,7 @@ var ts; for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -61928,12 +63699,12 @@ var ts; } var diagnostic; switch (declaration.kind) { - case 216 /* BinaryExpression */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 217 /* BinaryExpression */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 160 /* Parameter */: + case 161 /* Parameter */: var param = declaration; if (ts.isIdentifier(param.name) && (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && @@ -61948,23 +63719,23 @@ var ts; noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; if (!noImplicitAny) { // Don't issue a suggestion for binding elements since the codefix doesn't yet support them. return; } break; - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: if (noImplicitAny && !declaration.name) { if (wideningKind === 3 /* GeneratorYield */) { error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString); @@ -61978,7 +63749,7 @@ var ts; wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; - case 190 /* MappedType */: + case 191 /* MappedType */: if (noImplicitAny) { error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); } @@ -61989,7 +63760,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -62105,23 +63876,23 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) { - return !!(objectFlags & 134217728 /* CouldContainTypeVariables */); + if (objectFlags & 1048576 /* CouldContainTypeVariablesComputed */) { + return !!(objectFlags & 2097152 /* CouldContainTypeVariables */); } var result = !!(type.flags & 465829888 /* Instantiable */ || type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || - objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) || + objectFlags & (32 /* Mapped */ | 1024 /* ReverseMapped */ | 8388608 /* ObjectRestType */)) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables)); if (type.flags & 3899393 /* ObjectFlagsType */) { - type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0); + type.objectFlags |= 1048576 /* CouldContainTypeVariablesComputed */ | (result ? 2097152 /* CouldContainTypeVariables */ : 0); } return result; } function isNonGenericTopLevelType(type) { if (type.aliasSymbol && !type.aliasTypeArguments) { - var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 254 /* TypeAliasDeclaration */); - return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 297 /* SourceFile */ ? true : n.kind === 256 /* ModuleDeclaration */ ? false : "quit"; })); + var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 255 /* TypeAliasDeclaration */); + return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 298 /* SourceFile */ ? true : n.kind === 257 /* ModuleDeclaration */ ? false : "quit"; })); } return false; } @@ -62174,7 +63945,7 @@ var ts; // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive // arrow function, but is considered partially inferable because property 'a' has an inferable type. function isPartiallyInferableType(type) { - return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) || + return !(ts.getObjectFlags(type) & 524288 /* NonInferrableType */) || isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }) || isTupleType(type) && ts.some(getTypeArguments(type), isPartiallyInferableType); } @@ -62198,14 +63969,18 @@ var ts; } // For all other object types we infer a new object type where the reverse mapping has been // applied to the type of each property. - var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); + var reversed = createObjectType(1024 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + return links.type; } function inferReverseMappedType(sourceType, target, constraint) { var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); @@ -62297,51 +64072,113 @@ var ts; // * it does not contain a numeric seperator (the `BigInt` constructor does not accept a numeric seperator in its input) return success && result === 9 /* BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* ContainsSeparator */); } - function isStringLiteralTypeValueParsableAsType(s, target) { - if (target.flags & 1048576 /* Union */) { - return !!forEachType(target, function (t) { return isStringLiteralTypeValueParsableAsType(s, t); }); - } - switch (target) { - case stringType: return true; - case numberType: return s.value !== "" && isFinite(+(s.value)); - case bigintType: return s.value !== "" && isValidBigIntString(s.value); - // the next 4 should be handled in `getTemplateLiteralType`, as they are all exactly one value, but are here for completeness, just in case - // this function is ever used on types which don't come from template literal holes - case trueType: return s.value === "true"; - case falseType: return s.value === "false"; - case undefinedType: return s.value === "undefined"; - case nullType: return s.value === "null"; - default: return !!(target.flags & 1 /* Any */); - } - } - function inferLiteralsFromTemplateLiteralType(source, target) { - var value = source.value; - var texts = target.texts; - var lastIndex = texts.length - 1; - var startText = texts[0]; - var endText = texts[lastIndex]; - if (!(value.startsWith(startText) && value.slice(startText.length).endsWith(endText))) + function isValidTypeForTemplateLiteralPlaceholder(source, target) { + if (source === target || target.flags & (1 /* Any */ | 4 /* String */)) { + return true; + } + if (source.flags & 128 /* StringLiteral */) { + var value = source.value; + return !!(target.flags & 8 /* Number */ && value !== "" && isFinite(+value) || + target.flags & 64 /* BigInt */ && value !== "" && isValidBigIntString(value) || + target.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) && value === target.intrinsicName); + } + if (source.flags & 134217728 /* TemplateLiteral */) { + var texts = source.texts; + return texts.length === 2 && texts[0] === "" && texts[1] === "" && isTypeAssignableTo(source.types[0], target); + } + return isTypeAssignableTo(source, target); + } + function inferTypesFromTemplateLiteralType(source, target) { + return source.flags & 128 /* StringLiteral */ ? inferFromLiteralPartsToTemplateLiteral([source.value], ts.emptyArray, target) : + source.flags & 134217728 /* TemplateLiteral */ ? + ts.arraysEqual(source.texts, target.texts) ? ts.map(source.types, getStringLikeTypeForType) : + inferFromLiteralPartsToTemplateLiteral(source.texts, source.types, target) : + undefined; + } + function getStringLikeTypeForType(type) { + return type.flags & (1 /* Any */ | 402653316 /* StringLike */) ? type : getTemplateLiteralType(["", ""], [type]); + } + // This function infers from the text parts and type parts of a source literal to a target template literal. The number + // of text parts is always one more than the number of type parts, and a source string literal is treated as a source + // with one text part and zero type parts. The function returns an array of inferred string or template literal types + // corresponding to the placeholders in the target template literal, or undefined if the source doesn't match the target. + // + // We first check that the starting source text part matches the starting target text part, and that the ending source + // text part ends matches the ending target text part. We then iterate through the remaining target text parts, finding + // a match for each in the source and inferring string or template literal types created from the segments of the source + // that occur between the matches. During this iteration, seg holds the index of the current text part in the sourceTexts + // array and pos holds the current character position in the current text part. + // + // Consider inference from type `<<${string}>.<${number}-${number}>>` to type `<${string}.${string}>`, i.e. + // sourceTexts = ['<<', '>.<', '-', '>>'] + // sourceTypes = [string, number, number] + // target.texts = ['<', '.', '>'] + // We first match '<' in the target to the start of '<<' in the source and '>' in the target to the end of '>>' in + // the source. The first match for the '.' in target occurs at character 1 in the source text part at index 1, and thus + // the first inference is the template literal type `<${string}>`. The remainder of the source makes up the second + // inference, the template literal type `<${number}-${number}>`. + function inferFromLiteralPartsToTemplateLiteral(sourceTexts, sourceTypes, target) { + var lastSourceIndex = sourceTexts.length - 1; + var sourceStartText = sourceTexts[0]; + var sourceEndText = sourceTexts[lastSourceIndex]; + var targetTexts = target.texts; + var lastTargetIndex = targetTexts.length - 1; + var targetStartText = targetTexts[0]; + var targetEndText = targetTexts[lastTargetIndex]; + if (lastSourceIndex === 0 && sourceStartText.length < targetStartText.length + targetEndText.length || + !sourceStartText.startsWith(targetStartText) || !sourceEndText.endsWith(targetEndText)) return undefined; + var remainingEndText = sourceEndText.slice(0, sourceEndText.length - targetEndText.length); var matches = []; - var str = value.slice(startText.length, value.length - endText.length); - var pos = 0; - for (var i = 1; i < lastIndex; i++) { - var delim = texts[i]; - var delimPos = delim.length > 0 ? str.indexOf(delim, pos) : pos < str.length ? pos + 1 : -1; - if (delimPos < 0) + var seg = 0; + var pos = targetStartText.length; + for (var i = 1; i < lastTargetIndex; i++) { + var delim = targetTexts[i]; + if (delim.length > 0) { + var s = seg; + var p = pos; + while (true) { + p = getSourceText(s).indexOf(delim, p); + if (p >= 0) + break; + s++; + if (s === sourceTexts.length) + return undefined; + p = 0; + } + addMatch(s, p); + pos += delim.length; + } + else if (pos < getSourceText(seg).length) { + addMatch(seg, pos + 1); + } + else if (seg < lastSourceIndex) { + addMatch(seg + 1, 0); + } + else { return undefined; - matches.push(getLiteralType(str.slice(pos, delimPos))); - pos = delimPos + delim.length; + } } - matches.push(getLiteralType(str.slice(pos))); + addMatch(lastSourceIndex, getSourceText(lastSourceIndex).length); return matches; + function getSourceText(index) { + return index < lastSourceIndex ? sourceTexts[index] : remainingEndText; + } + function addMatch(s, p) { + var matchType = s === seg ? + getLiteralType(getSourceText(s).slice(pos, p)) : + getTemplateLiteralType(__spreadArray(__spreadArray([sourceTexts[seg].slice(pos)], sourceTexts.slice(seg + 1, s)), [getSourceText(s).slice(0, p)]), sourceTypes.slice(seg, s)); + matches.push(matchType); + seg = s; + pos = p; + } } function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) { if (priority === void 0) { priority = 0; } if (contravariant === void 0) { contravariant = false; } var bivariant = false; var propagationType; - var inferencePriority = 1024 /* MaxValue */; + var inferencePriority = 2048 /* MaxValue */; var allowComplexConstraintInference = true; var visited; var sourceStack; @@ -62428,8 +64265,8 @@ var ts; // not contain anyFunctionType when we come back to this argument for its second round // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard // when constructing types from type parameters that had no inference candidates). - if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || - (priority & 64 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || + (priority & 128 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); @@ -62456,7 +64293,7 @@ var ts; clearCachedInferences(inferences); } } - if (!(priority & 64 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 128 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; clearCachedInferences(inferences); } @@ -62496,7 +64333,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - inferWithPriority(empty, target.type, 128 /* LiteralKeyof */); + inferWithPriority(empty, target.type, 256 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -62508,6 +64345,13 @@ var ts; inferFromTypes(source.type, target.type); } } + else if (source.flags & 33554432 /* Substitution */) { + inferFromTypes(source.baseType, target); + var oldPriority = priority; + priority |= 4 /* SubstituteSource */; + inferFromTypes(source.substitute, target); // Make substitute inference at a lower priority + priority = oldPriority; + } else if (target.flags & 16777216 /* Conditional */) { invokeOnce(source, target, inferToConditionalType); } @@ -62527,7 +64371,7 @@ var ts; } else { source = getReducedType(source); - if (!(priority & 256 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { + if (!(priority & 512 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { var apparentSource = getApparentType(source); // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` @@ -62565,26 +64409,22 @@ var ts; } (visited || (visited = new ts.Map())).set(key, -1 /* Circularity */); var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; // We stop inferring and report a circularity if we encounter duplicate recursion identities on both // the source side and the target side. var saveExpandingFlags = expandingFlags; - var sourceIdentity = getRecursionIdentity(source) || source; - var targetIdentity = getRecursionIdentity(target) || target; - if (sourceIdentity && ts.contains(sourceStack, sourceIdentity)) + var sourceIdentity = getRecursionIdentity(source); + var targetIdentity = getRecursionIdentity(target); + if (ts.contains(sourceStack, sourceIdentity)) expandingFlags |= 1 /* Source */; - if (targetIdentity && ts.contains(targetStack, targetIdentity)) + if (ts.contains(targetStack, targetIdentity)) expandingFlags |= 2 /* Target */; if (expandingFlags !== 3 /* Both */) { - if (sourceIdentity) - (sourceStack || (sourceStack = [])).push(sourceIdentity); - if (targetIdentity) - (targetStack || (targetStack = [])).push(targetIdentity); + (sourceStack || (sourceStack = [])).push(sourceIdentity); + (targetStack || (targetStack = [])).push(targetIdentity); action(source, target); - if (targetIdentity) - targetStack.pop(); - if (sourceIdentity) - sourceStack.pop(); + targetStack.pop(); + sourceStack.pop(); } else { inferencePriority = -1 /* Circularity */; @@ -62624,7 +64464,7 @@ var ts; } } function inferFromContravariantTypes(source, target) { - if (strictFunctionTypes || priority & 512 /* AlwaysStrict */) { + if (strictFunctionTypes || priority & 1024 /* AlwaysStrict */) { contravariant = !contravariant; inferFromTypes(source, target); contravariant = !contravariant; @@ -62676,7 +64516,7 @@ var ts; else { for (var i = 0; i < sources.length; i++) { var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; inferFromTypes(sources[i], t); if (inferencePriority === priority) matched_1[i] = true; @@ -62755,9 +64595,9 @@ var ts; // We assign a lower priority to inferences made from types containing non-inferrable // types because we may only have a partial result (i.e. we may have failed to make // reverse inferences for some properties). - inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ? - 8 /* PartialHomomorphicMappedType */ : - 4 /* HomomorphicMappedType */); + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 524288 /* NonInferrableType */ ? + 16 /* PartialHomomorphicMappedType */ : + 8 /* HomomorphicMappedType */); } } return true; @@ -62765,7 +64605,7 @@ var ts; if (constraintType.flags & 262144 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type // parameter. First infer from 'keyof S' to K. - inferWithPriority(getIndexType(source), constraintType, 16 /* MappedTypeConstraint */); + inferWithPriority(getIndexType(source), constraintType, 32 /* MappedTypeConstraint */); // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X }, // where K extends keyof T, we make the same inferences as for a homomorphic mapped type // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a @@ -62794,16 +64634,14 @@ var ts; } else { var savePriority = priority; - priority |= contravariant ? 32 /* ContravariantConditional */ : 0; + priority |= contravariant ? 64 /* ContravariantConditional */ : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; inferToMultipleTypes(source, targetTypes, target.flags); priority = savePriority; } } function inferToTemplateLiteralType(source, target) { - var matches = source.flags & 128 /* StringLiteral */ ? inferLiteralsFromTemplateLiteralType(source, target) : - source.flags & 134217728 /* TemplateLiteral */ && ts.arraysEqual(source.texts, target.texts) ? source.types : - undefined; + var matches = inferTypesFromTemplateLiteralType(source, target); var types = target.types; for (var i = 0; i < types.length; i++) { inferFromTypes(matches ? matches[i] : neverType, types[i]); @@ -62919,7 +64757,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */); + var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* NonInferrableType */); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -62929,7 +64767,7 @@ var ts; 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 === 165 /* MethodDeclaration */ || kind === 164 /* MethodSignature */ || kind === 166 /* Constructor */; + bivariant = bivariant || kind === 166 /* MethodDeclaration */ || kind === 165 /* MethodSignature */ || kind === 167 /* Constructor */; applyToParameterTypes(source, target, inferFromContravariantTypes); bivariant = saveBivariant; } @@ -62956,7 +64794,7 @@ var ts; } } function isTypeOrBaseIdenticalTo(s, t) { - return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 134217856 /* StringLikeLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); + return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); } function isTypeCloselyMatchedBy(s, t) { return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol || @@ -62970,7 +64808,7 @@ var ts; return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); } function isObjectOrArrayLiteralType(type) { - return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */)); + return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 32768 /* ArrayLiteral */)); } function unionObjectAndArrayLiteralCandidates(candidates) { if (candidates.length > 1) { @@ -62983,7 +64821,7 @@ var ts; return candidates; } function getContravariantInference(inference) { - return inference.priority & 208 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + return inference.priority & 416 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } function getCovariantInference(inference, signature) { // Extract all object and array literal types and replace them with a single widened and normalized type. @@ -63000,7 +64838,7 @@ var ts; candidates; // If all inferences were made from a position that implies a combined result, infer a union type. // Otherwise, infer a common supertype. - var unwidenedType = inference.priority & 208 /* PriorityImpliesCombination */ ? + var unwidenedType = inference.priority & 416 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -63109,7 +64947,7 @@ var ts; case "BigUint64Array": return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later; default: - if (node.parent.kind === 289 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 290 /* ShorthandPropertyAssignment */) { return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer; } else { @@ -63130,26 +64968,24 @@ var ts; // TypeScript 1.0 spec (April 2014): 3.6.3 // A type query consists of the keyword typeof followed by an expression. // The expression is restricted to a single identifier or a sequence of identifiers separated by periods - return !!ts.findAncestor(node, function (n) { return n.kind === 176 /* TypeQuery */ ? true : n.kind === 78 /* Identifier */ || n.kind === 157 /* QualifiedName */ ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 177 /* TypeQuery */ ? true : n.kind === 78 /* Identifier */ || n.kind === 158 /* QualifiedName */ ? false : "quit"; }); } // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the // leftmost identifier followed by zero or more property names separated by dots. - // The result is undefined if the reference isn't a dotted name. We prefix nodes - // occurring in an apparent type position with '@' because the control flow type - // of such nodes may be based on the apparent type instead of the declared type. + // The result is undefined if the reference isn't a dotted name. function getFlowCacheKey(node, declaredType, initialType, flowContainer) { switch (node.kind) { case 78 /* Identifier */: var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; case 107 /* ThisKeyword */: return "0|" + (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType); - case 225 /* NonNullExpression */: - case 207 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: var propName = getAccessedPropertyName(node); if (propName !== undefined) { var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); @@ -63160,32 +64996,40 @@ var ts; } function isMatchingReference(source, target) { switch (target.kind) { - case 207 /* ParenthesizedExpression */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: return isMatchingReference(source, target.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return (ts.isAssignmentExpression(target) && isMatchingReference(source, target.left)) || (ts.isBinaryExpression(target) && target.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source, target.right)); } switch (source.kind) { + case 227 /* MetaProperty */: + return target.kind === 227 /* MetaProperty */ + && source.keywordToken === target.keywordToken + && source.name.escapedText === target.name.escapedText; case 78 /* Identifier */: case 79 /* PrivateIdentifier */: return target.kind === 78 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 249 /* VariableDeclaration */ || target.kind === 198 /* BindingElement */) && + (target.kind === 250 /* VariableDeclaration */ || target.kind === 199 /* BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); case 107 /* ThisKeyword */: return target.kind === 107 /* ThisKeyword */; case 105 /* SuperKeyword */: return target.kind === 105 /* SuperKeyword */; - case 225 /* NonNullExpression */: - case 207 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: return isMatchingReference(source.expression, target); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return ts.isAccessExpression(target) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 216 /* BinaryExpression */: + case 158 /* QualifiedName */: + return ts.isAccessExpression(target) && + source.right.escapedText === getAccessedPropertyName(target) && + isMatchingReference(source.left, target.expression); + case 217 /* BinaryExpression */: return (ts.isBinaryExpression(source) && source.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source.right, target)); } return false; @@ -63193,11 +65037,11 @@ var ts; // Given a source x, check if target matches x or is an && operation with an operand that matches x. function containsTruthyCheck(source, target) { return isMatchingReference(source, target) || - (target.kind === 216 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && + (target.kind === 217 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (containsTruthyCheck(source, target.left) || containsTruthyCheck(source, target.right))); } function getAccessedPropertyName(access) { - return access.kind === 201 /* PropertyAccessExpression */ ? access.name.escapedText : + return access.kind === 202 /* PropertyAccessExpression */ ? access.name.escapedText : ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : undefined; } @@ -63247,6 +65091,86 @@ var ts; } return result; } + // Given a set of constituent types and a property name, create and return a map keyed by the literal + // types of the property by that name in each constituent type. No map is returned if some key property + // has a non-literal type or if less than 10 or less than 50% of the constituents have a unique key. + // Entries with duplicate keys have unknownType as the value. + function mapTypesByKeyProperty(types, name) { + var map = new ts.Map(); + var count = 0; + var _loop_20 = function (type) { + if (type.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */)) { + var discriminant = getTypeOfPropertyOfType(type, name); + if (discriminant) { + if (!isLiteralType(discriminant)) { + return { value: undefined }; + } + var duplicate_1 = false; + forEachType(discriminant, function (t) { + var id = getTypeId(getRegularTypeOfLiteralType(t)); + var existing = map.get(id); + if (!existing) { + map.set(id, type); + } + else if (existing !== unknownType) { + map.set(id, unknownType); + duplicate_1 = true; + } + }); + if (!duplicate_1) + count++; + } + } + }; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; + var state_8 = _loop_20(type); + if (typeof state_8 === "object") + return state_8.value; + } + return count >= 10 && count * 2 >= types.length ? map : undefined; + } + // Return the name of a discriminant property for which it was possible and feasible to construct a map of + // constituent types keyed by the literal types of the property by that name in each constituent type. + function getKeyPropertyName(unionType) { + var types = unionType.types; + // We only construct maps for large unions with non-primitive constituents. + if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */) { + return undefined; + } + if (unionType.keyPropertyName === undefined) { + // The candidate key property name is the name of the first property with a unit type in one of the + // constituent types. + var keyPropertyName = ts.forEach(types, function (t) { + return t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ? + ts.forEach(getPropertiesOfType(t), function (p) { return isUnitType(getTypeOfSymbol(p)) ? p.escapedName : undefined; }) : + undefined; + }); + var mapByKeyProperty = keyPropertyName && mapTypesByKeyProperty(types, keyPropertyName); + unionType.keyPropertyName = mapByKeyProperty ? keyPropertyName : ""; + unionType.constituentMap = mapByKeyProperty; + } + return unionType.keyPropertyName.length ? unionType.keyPropertyName : undefined; + } + // Given a union type for which getKeyPropertyName returned a non-undefined result, return the constituent + // that corresponds to the given key type for that property name. + function getConstituentTypeForKeyType(unionType, keyType) { + var _a; + var result = (_a = unionType.constituentMap) === null || _a === void 0 ? void 0 : _a.get(getTypeId(getRegularTypeOfLiteralType(keyType))); + return result !== unknownType ? result : undefined; + } + function getMatchingUnionConstituentForType(unionType, type) { + var keyPropertyName = getKeyPropertyName(unionType); + var propType = keyPropertyName && getTypeOfPropertyOfType(type, keyPropertyName); + return propType && getConstituentTypeForKeyType(unionType, propType); + } + function getMatchingUnionConstituentForObjectLiteral(unionType, node) { + var keyPropertyName = getKeyPropertyName(unionType); + var propNode = keyPropertyName && ts.find(node.properties, function (p) { return p.symbol && p.kind === 289 /* PropertyAssignment */ && + p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer); }); + var propType = propNode && getTypeOfExpression(propNode.initializer); + return propType && getConstituentTypeForKeyType(unionType, propType); + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -63259,7 +65183,7 @@ var ts; } } } - if (expression.expression.kind === 201 /* PropertyAccessExpression */ && + if (expression.expression.kind === 202 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, expression.expression.expression)) { return true; } @@ -63306,14 +65230,6 @@ var ts; } return declaredType; } - function getTypeFactsOfTypes(types) { - var result = 0 /* None */; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; - result |= getTypeFacts(t); - } - return result; - } function isFunctionObjectType(type) { // We do a quick check for a "bind" property before performing the more expensive subtype // check. This gives us a quicker out in the common case where an object type is not a function. @@ -63321,7 +65237,8 @@ var ts; return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type) { + function getTypeFacts(type, ignoreObjects) { + if (ignoreObjects === void 0) { ignoreObjects = false; } var flags = type.flags; if (flags & 4 /* String */) { return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; @@ -63358,7 +65275,7 @@ var ts; (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } - if (flags & 524288 /* Object */) { + if (flags & 524288 /* Object */ && !ignoreObjects) { return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : isFunctionObjectType(type) ? @@ -63381,11 +65298,17 @@ var ts; return 0 /* None */; } if (flags & 465829888 /* Instantiable */) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType) : + return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : strictNullChecks ? 7929345 /* NonEmptyStringStrictFacts */ : 16776705 /* NonEmptyStringFacts */; } - if (flags & 3145728 /* UnionOrIntersection */) { - return getTypeFactsOfTypes(type.types); + if (flags & 1048576 /* Union */) { + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0 /* None */); + } + if (flags & 2097152 /* Intersection */) { + // When an intersection contains a primitive type we ignore object type constituents as they are + // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. + ignoreObjects || (ignoreObjects = maybeTypeOfKind(type, 131068 /* Primitive */)); + return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t, ignoreObjects); }, 16777215 /* All */); } return 16777215 /* All */; } @@ -63393,18 +65316,16 @@ var ts; return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { - if (defaultExpression) { - var defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]); - } - return type; + return defaultExpression ? + getUnionType([getNonUndefinedType(type), getTypeOfExpression(defaultExpression)]) : + type; } function getTypeOfDestructuredProperty(type, name) { var nameType = getLiteralTypeFromPropertyName(name); if (!isTypeUsableAsPropertyName(nameType)) return errorType; var text = getPropertyNameFromType(nameType); - return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || + return getTypeOfPropertyOfType(type, text) || isNumericLiteralName(text) && includeUndefinedInIndexSignature(getIndexTypeOfType(type, 1 /* Number */)) || includeUndefinedInIndexSignature(getIndexTypeOfType(type, 0 /* String */)) || errorType; @@ -63425,15 +65346,15 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) || errorType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 199 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 288 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 200 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 289 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 216 /* BinaryExpression */ && parent.parent.left === parent || - parent.parent.kind === 239 /* ForOfStatement */ && parent.parent.initializer === parent; + return parent.parent.kind === 217 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 240 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); @@ -63450,21 +65371,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return stringType; - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return checkRightHandSideOfForOf(parent) || errorType; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return undefinedType; - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return getAssignedTypeOfSpreadExpression(parent); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return errorType; @@ -63472,7 +65393,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 196 /* ObjectBindingPattern */ ? + var type = pattern.kind === 197 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : @@ -63490,30 +65411,30 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 238 /* ForInStatement */) { + if (node.parent.parent.kind === 239 /* ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 239 /* ForOfStatement */) { + if (node.parent.parent.kind === 240 /* ForOfStatement */) { return checkRightHandSideOfForOf(node.parent.parent) || errorType; } return errorType; } function getInitialType(node) { - return node.kind === 249 /* VariableDeclaration */ ? + return node.kind === 250 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function isEmptyArrayAssignment(node) { - return node.kind === 249 /* VariableDeclaration */ && node.initializer && + return node.kind === 250 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 198 /* BindingElement */ && node.parent.kind === 216 /* BinaryExpression */ && + node.kind !== 199 /* BindingElement */ && node.parent.kind === 217 /* BinaryExpression */ && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (node.operatorToken.kind) { case 62 /* EqualsToken */: case 74 /* BarBarEqualsToken */: @@ -63528,13 +65449,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 207 /* ParenthesizedExpression */ || - parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node || - parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? + return parent.kind === 208 /* ParenthesizedExpression */ || + parent.kind === 217 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node || + parent.kind === 217 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 284 /* CaseClause */) { + if (clause.kind === 285 /* CaseClause */) { return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); } return neverType; @@ -63554,7 +65475,7 @@ var ts; var witnesses = []; for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { var clause = _a[_i]; - if (clause.kind === 284 /* CaseClause */) { + if (clause.kind === 285 /* CaseClause */) { if (ts.isStringLiteralLike(clause.expression)) { witnesses.push(clause.expression.text); continue; @@ -63590,14 +65511,40 @@ var ts; function forEachType(type, f) { return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type); } + function someType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.some(type.types, f) : f(type); + } function everyType(type, f) { return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); } + function everyContainedType(type, f) { + return type.flags & 3145728 /* UnionOrIntersection */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 1048576 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); + if (filtered === types) { + return type; + } + var origin = type.origin; + var newOrigin = void 0; + if (origin && origin.flags & 1048576 /* Union */) { + // If the origin type is a (denormalized) union type, filter its non-union constituents. If that ends + // up removing a smaller number of types than in the normalized constituent set (meaning some of the + // filtered types are within nested unions in the origin), then we can't construct a new origin type. + // Otherwise, if we have exactly one type left in the origin set, return that as the filtered type. + // Otherwise, construct a new filtered origin type. + var originTypes = origin.types; + var originFiltered = ts.filter(originTypes, function (t) { return !!(t.flags & 1048576 /* Union */) || f(t); }); + if (originTypes.length - originFiltered.length === types.length - filtered.length) { + if (originFiltered.length === 1) { + return originFiltered[0]; + } + newOrigin = createOriginUnionOrIntersectionType(1048576 /* Union */, originFiltered); + } + } + return getUnionTypeFromSortedList(filtered, type.objectFlags, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, newOrigin); } return type.flags & 131072 /* Never */ || f(type) ? type : neverType; } @@ -63630,6 +65577,11 @@ var ts; } return changed ? mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : type; } + function mapTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) { + return type.flags & 1048576 /* Union */ && aliasSymbol ? + getUnionType(ts.map(type.types, mapper), 1 /* Literal */, aliasSymbol, aliasTypeArguments) : + mapType(type, mapper); + } function getConstituentCount(type) { return type.flags & 3145728 /* UnionOrIntersection */ ? type.types.length : 1; } @@ -63715,12 +65667,12 @@ var ts; var root = getReferenceRoot(node); var parent = root.parent; var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" || - parent.parent.kind === 203 /* CallExpression */ + parent.parent.kind === 204 /* CallExpression */ && ts.isIdentifier(parent.name) && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 202 /* ElementAccessExpression */ && + var isElementAssignment = parent.kind === 203 /* ElementAccessExpression */ && parent.expression === root && - parent.parent.kind === 216 /* BinaryExpression */ && + parent.parent.kind === 217 /* BinaryExpression */ && parent.parent.operatorToken.kind === 62 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && @@ -63728,8 +65680,8 @@ var ts; return isLengthPushOrUnshift || isElementAssignment; } function isDeclarationWithExplicitTypeAnnotation(declaration) { - return (declaration.kind === 249 /* VariableDeclaration */ || declaration.kind === 160 /* Parameter */ || - declaration.kind === 163 /* PropertyDeclaration */ || declaration.kind === 162 /* PropertySignature */) && + return (declaration.kind === 250 /* VariableDeclaration */ || declaration.kind === 161 /* Parameter */ || + declaration.kind === 164 /* PropertyDeclaration */ || declaration.kind === 163 /* PropertySignature */) && !!ts.getEffectiveTypeAnnotationNode(declaration); } function getExplicitTypeOfSymbol(symbol, diagnostic) { @@ -63748,7 +65700,7 @@ var ts; if (isDeclarationWithExplicitTypeAnnotation(declaration)) { return getTypeOfSymbol(symbol); } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 240 /* ForOfStatement */) { var statement = declaration.parent.parent; var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined); if (expressionType) { @@ -63776,11 +65728,25 @@ var ts; return getExplicitThisType(node); case 105 /* SuperKeyword */: return checkSuperExpression(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: { var type = getTypeOfDottedName(node.expression, diagnostic); - var prop = type && getPropertyOfType(type, node.name.escapedText); - return prop && getExplicitTypeOfSymbol(prop, diagnostic); - case 207 /* ParenthesizedExpression */: + if (type) { + var name = node.name; + var prop = void 0; + if (ts.isPrivateIdentifier(name)) { + if (!type.symbol) { + return undefined; + } + prop = getPropertyOfType(type, ts.getSymbolNameForPrivateIdentifier(type.symbol, name.escapedText)); + } + else { + prop = getPropertyOfType(type, name.escapedText); + } + return prop && getExplicitTypeOfSymbol(prop, diagnostic); + } + return undefined; + } + case 208 /* ParenthesizedExpression */: return getTypeOfDottedName(node.expression, diagnostic); } } @@ -63794,7 +65760,7 @@ var ts; // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call // target expression of an assertion. var funcType = void 0; - if (node.parent.kind === 233 /* ExpressionStatement */) { + if (node.parent.kind === 234 /* ExpressionStatement */) { funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined); } else if (node.expression.kind !== 105 /* SuperKeyword */) { @@ -63838,7 +65804,7 @@ var ts; } function isFalseExpression(expr) { var node = ts.skipParentheses(expr); - return node.kind === 94 /* FalseKeyword */ || node.kind === 216 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + return node.kind === 94 /* FalseKeyword */ || node.kind === 217 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); } function isReachableFlowNodeWorker(flow, noCacheCheck) { @@ -63973,7 +65939,7 @@ var ts; // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); - if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 225 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { + if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 226 /* NonNullExpression */ && !(resultType.flags & 131072 /* Never */) && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { return declaredType; } return resultType; @@ -63988,7 +65954,7 @@ var ts; 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. - ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); flowAnalysisDisabled = true; reportFlowControlError(reference); return errorType; @@ -64057,8 +66023,8 @@ var ts; // Check if we should continue with the control flow of the containing function. var container = flow.node; if (container && container !== flowContainer && - reference.kind !== 201 /* PropertyAccessExpression */ && - reference.kind !== 202 /* ElementAccessExpression */ && + reference.kind !== 202 /* PropertyAccessExpression */ && + reference.kind !== 203 /* ElementAccessExpression */ && reference.kind !== 107 /* ThisKeyword */) { flow = container.flowNode; continue; @@ -64083,7 +66049,7 @@ var ts; } function getInitialOrAssignedType(flow) { var node = flow.node; - return getConstraintForLocation(node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */ ? + return getNarrowableTypeForReference(node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */ ? getInitialType(node) : getAssignedType(node), reference); } @@ -64123,14 +66089,14 @@ var ts; // 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 === 208 /* FunctionExpression */ || init.kind === 209 /* ArrowFunction */)) { + if (init && (init.kind === 209 /* FunctionExpression */ || init.kind === 210 /* ArrowFunction */)) { return getTypeAtFlowNode(flow.antecedent); } } return declaredType; } // for (const _ in ref) acts as a nonnull on ref - if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 238 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 239 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); } // Assignment doesn't affect reference @@ -64141,7 +66107,7 @@ var ts; if (node.kind === 94 /* FalseKeyword */) { return unreachableNeverType; } - if (node.kind === 216 /* BinaryExpression */) { + if (node.kind === 217 /* BinaryExpression */) { if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); } @@ -64172,7 +66138,7 @@ var ts; function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 203 /* CallExpression */ ? + var expr = node.kind === 204 /* CallExpression */ ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { @@ -64180,7 +66146,7 @@ var ts; var type = getTypeFromFlowType(flowType); if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { var evolvedType_1 = type; - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); @@ -64228,7 +66194,7 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (expr.kind === 211 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + else if (expr.kind === 212 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else { @@ -64236,12 +66202,12 @@ var ts; if (optionalChainContainsReference(expr, reference)) { type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); }); } - else if (expr.kind === 211 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { + else if (expr.kind === 212 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); }); } } if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + type = narrowTypeBySwitchOnDiscriminantProperty(type, expr, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } } return createFlowType(type, isIncomplete(flowType)); @@ -64412,16 +66378,42 @@ var ts; if (propName === undefined) { return type; } - var propType = getTypeOfPropertyOfType(type, propName); + var removeNullable = strictNullChecks && ts.isOptionalChain(access) && maybeTypeOfKind(type, 98304 /* Nullable */); + var propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type, propName); if (!propType) { return type; } + propType = removeNullable ? getOptionalType(propType) : propType; var narrowedPropType = narrowType(propType); return filterType(type, function (t) { var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName); return !(discriminantType.flags & 131072 /* Never */) && isTypeComparableTo(discriminantType, narrowedPropType); }); } + function narrowTypeByDiscriminantProperty(type, access, operator, value, assumeTrue) { + if ((operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) && type.flags & 1048576 /* Union */) { + var keyPropertyName = getKeyPropertyName(type); + if (keyPropertyName && keyPropertyName === getAccessedPropertyName(access)) { + var candidate_2 = getConstituentTypeForKeyType(type, getTypeOfExpression(value)); + if (candidate_2) { + return operator === (assumeTrue ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */) ? candidate_2 : + isUnitType(getTypeOfPropertyOfType(candidate_2, keyPropertyName) || unknownType) ? filterType(type, function (t) { return t !== candidate_2; }) : + type; + } + } + } + return narrowTypeByDiscriminant(type, access, function (t) { return narrowTypeByEquality(t, operator, value, assumeTrue); }); + } + function narrowTypeBySwitchOnDiscriminantProperty(type, access, switchStatement, clauseStart, clauseEnd) { + if (clauseStart < clauseEnd && type.flags & 1048576 /* Union */ && getKeyPropertyName(type) === getAccessedPropertyName(access)) { + var clauseTypes = getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd); + var candidate = getUnionType(ts.map(clauseTypes, function (t) { return getConstituentTypeForKeyType(type, t) || unknownType; })); + if (candidate !== unknownType) { + return candidate; + } + } + return narrowTypeByDiscriminant(type, access, function (t) { return narrowTypeBySwitchOnDiscriminant(t, switchStatement, clauseStart, clauseEnd); }); + } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); @@ -64445,7 +66437,8 @@ var ts; return !assumeTrue; } function narrowByInKeyword(type, literal, assumeTrue) { - if (type.flags & (1048576 /* Union */ | 524288 /* Object */) + if (type.flags & 1048576 /* Union */ + || type.flags & 524288 /* Object */ && declaredType !== type || isThisTypeParameter(type) || type.flags & 2097152 /* Intersection */ && ts.every(type.types, function (t) { return t.symbol !== globalThisSymbol; })) { var propName_1 = ts.escapeLeadingUnderscores(literal.text); @@ -64464,40 +66457,40 @@ var ts; case 35 /* ExclamationEqualsToken */: case 36 /* EqualsEqualsEqualsToken */: case 37 /* ExclamationEqualsEqualsToken */: - var operator_1 = expr.operatorToken.kind; - var left_1 = getReferenceCandidate(expr.left); - var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 211 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { - return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + var operator = expr.operatorToken.kind; + var left = getReferenceCandidate(expr.left); + var right = getReferenceCandidate(expr.right); + if (left.kind === 212 /* TypeOfExpression */ && ts.isStringLiteralLike(right)) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); } - if (right_1.kind === 211 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { - return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + if (right.kind === 212 /* TypeOfExpression */ && ts.isStringLiteralLike(left)) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); } - if (isMatchingReference(reference, left_1)) { - return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + if (isMatchingReference(reference, left)) { + return narrowTypeByEquality(type, operator, right, assumeTrue); } - if (isMatchingReference(reference, right_1)) { - return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + if (isMatchingReference(reference, right)) { + return narrowTypeByEquality(type, operator, left, assumeTrue); } if (strictNullChecks) { - if (optionalChainContainsReference(left_1, reference)) { - type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue); + if (optionalChainContainsReference(left, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator, right, assumeTrue); } - else if (optionalChainContainsReference(right_1, reference)) { - type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); + else if (optionalChainContainsReference(right, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator, left, assumeTrue); } } - if (isMatchingReferenceDiscriminant(left_1, type)) { - return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + if (isMatchingReferenceDiscriminant(left, type)) { + return narrowTypeByDiscriminantProperty(type, left, operator, right, assumeTrue); } - if (isMatchingReferenceDiscriminant(right_1, type)) { - return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + if (isMatchingReferenceDiscriminant(right, type)) { + return narrowTypeByDiscriminantProperty(type, right, operator, left, assumeTrue); } - if (isMatchingConstructorReference(left_1)) { - return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue); + if (isMatchingConstructorReference(left)) { + return narrowTypeByConstructor(type, operator, right, assumeTrue); } - if (isMatchingConstructorReference(right_1)) { - return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue); + if (isMatchingConstructorReference(right)) { + return narrowTypeByConstructor(type, operator, left, assumeTrue); } break; case 101 /* InstanceOfKeyword */: @@ -64562,13 +66555,12 @@ var ts; } if (assumeTrue) { var filterFn = operator === 34 /* EqualsEqualsToken */ ? - (function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); }) : + function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); } : function (t) { return areTypesComparable(t, valueType); }; return replacePrimitivesWithLiterals(filterType(type, filterFn), valueType); } if (isUnitType(valueType)) { - var regularType_1 = getRegularTypeOfLiteralType(valueType); - return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; }); + return filterType(type, function (t) { return !(isUnitLikeType(t) && areTypesComparable(t, valueType)); }); } return type; } @@ -64590,7 +66582,7 @@ var ts; if (assumeTrue && type.flags & 2 /* Unknown */ && literal.text === "object") { // The pattern x && typeof x === 'object', where x is of type unknown, narrows x to type object. We don't // need to check for the reverse typeof x === 'object' && x since that already narrows correctly. - if (typeOfExpr.parent.parent.kind === 216 /* BinaryExpression */) { + if (typeOfExpr.parent.parent.kind === 217 /* BinaryExpression */) { var expr = typeOfExpr.parent.parent; if (expr.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && expr.right === typeOfExpr.parent && containsTruthyCheck(reference, expr.left)) { return nonPrimitiveType; @@ -64646,7 +66638,7 @@ var ts; if (!hasDefaultClause) { return caseType; } - var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + var defaultType = filterType(type, function (t) { return !(isUnitLikeType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(extractUnitType(t)))); }); return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } function getImpliedTypeFromTypeofGuard(type, text) { @@ -64828,7 +66820,16 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { - return filterType(type, function (t) { return !isRelated(t, candidate); }); + return filterType(type, function (t) { + if (!isRelated(t, candidate)) { + return true; + } + var constraint = getBaseConstraintOfType(t); + if (constraint && constraint !== t) { + return !isRelated(constraint, candidate); + } + return false; + }); } // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. @@ -64838,10 +66839,15 @@ var ts; return assignableType; } } - // If the candidate type is a subtype of the target type, narrow to the candidate type, - // if the target type is a subtype of the candidate type, narrow to the target type, - // otherwise, narrow to an intersection of the two types. - return isTypeSubtypeOf(candidate, type) ? candidate : isTypeSubtypeOf(type, candidate) ? type : getIntersectionType([type, candidate]); + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -64884,17 +66890,17 @@ var ts; case 78 /* Identifier */: case 107 /* ThisKeyword */: case 105 /* SuperKeyword */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return narrowTypeByCallExpression(type, expr, assumeTrue); - case 207 /* ParenthesizedExpression */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: return narrowType(type, expr.expression, assumeTrue); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: if (expr.operator === 53 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } @@ -64918,17 +66924,20 @@ var ts; // an dotted name expression, and if the location is not an assignment target, obtain the type // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. - if (location.kind === 78 /* Identifier */) { + if (location.kind === 78 /* Identifier */ || location.kind === 79 /* PrivateIdentifier */) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { + if (ts.isExpressionNode(location) && (!ts.isAssignmentTarget(location) || ts.isWriteAccess(location))) { var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } } } + if (ts.isDeclarationName(location) && ts.isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) { + return resolveTypeOfAccessors(location.parent.symbol, /*writing*/ true); + } // The location isn't a reference to the given symbol, meaning we're being asked // a hypothetical question of what type the symbol would have if there was a reference // to it at the given location. Since we have no control flow information for the @@ -64939,13 +66948,16 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 257 /* ModuleBlock */ || - node.kind === 297 /* SourceFile */ || - node.kind === 163 /* PropertyDeclaration */; + node.kind === 258 /* ModuleBlock */ || + node.kind === 298 /* SourceFile */ || + node.kind === 164 /* PropertyDeclaration */; }); } // Check if a parameter is assigned anywhere within its declaring function. function isParameterAssigned(symbol) { + if (!symbol.valueDeclaration) { + return false; + } var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); if (!(links.flags & 8388608 /* AssignmentsMarked */)) { @@ -64963,7 +66975,7 @@ var ts; if (node.kind === 78 /* Identifier */) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 160 /* Parameter */) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 161 /* Parameter */) { symbol.isAssigned = true; } } @@ -64979,7 +66991,7 @@ var ts; function removeOptionalityFromDeclaredType(declaredType, declaration) { if (pushTypeResolution(declaration.symbol, 2 /* DeclaredType */)) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 160 /* Parameter */ && + declaration.kind === 161 /* Parameter */ && declaration.initializer && getFalsyFlags(declaredType) & 32768 /* Undefined */ && !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */); @@ -64993,23 +67005,40 @@ var ts; } function isConstraintPosition(node) { var parent = node.parent; - return parent.kind === 201 /* PropertyAccessExpression */ || - parent.kind === 203 /* CallExpression */ && parent.expression === node || - parent.kind === 202 /* ElementAccessExpression */ && parent.expression === node || - parent.kind === 198 /* BindingElement */ && parent.name === node && !!parent.initializer; - } - function typeHasNullableConstraint(type) { - return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 98304 /* Nullable */); - } - function getConstraintForLocation(type, node) { - // When a node is the left hand expression of a property access, element access, or call expression, - // and the type of the node includes type variables with constraints that are nullable, we fetch the - // apparent type of the node *before* performing control flow analysis such that narrowings apply to - // the constraint type. - if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { - return mapType(getWidenedType(type), getBaseConstraintOrType); - } - return type; + // In an element access obj[x], we consider obj to be in a constraint position only when x is not + // of a generic type. This is because when both obj and x are of generic types T and K, we want + // the resulting type to be T[K]. + return parent.kind === 202 /* PropertyAccessExpression */ || + parent.kind === 204 /* CallExpression */ && parent.expression === node || + parent.kind === 203 /* ElementAccessExpression */ && parent.expression === node && + !isGenericIndexType(getTypeOfExpression(parent.argumentExpression)); + } + function isGenericTypeWithUnionConstraint(type) { + return !!(type.flags & 465829888 /* Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* Nullable */ | 1048576 /* Union */)); + } + function containsGenericType(type) { + return !!(type.flags & 465829888 /* Instantiable */ || type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, containsGenericType)); + } + function hasContextualTypeWithNoGenericTypes(node) { + // Computing the contextual type for a child of a JSX element involves resolving the type of the + // element's tag name, so we exclude that here to avoid circularities. + var contextualType = (ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && + !((ts.isJsxOpeningElement(node.parent) || ts.isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && + getContextualType(node); + return contextualType && !someType(contextualType, containsGenericType); + } + function getNarrowableTypeForReference(type, reference, checkMode) { + // When the type of a reference is or contains an instantiable type with a union type constraint, and + // when the reference is in a constraint position (where it is known we'll obtain the apparent type) or + // has a contextual type containing no top-level instantiables (meaning constraints will determine + // assignability), we substitute constraints for all instantiables in the type of the reference to give + // control flow analysis an opportunity to narrow it further. For example, for a reference of a type + // parameter type 'T extends string | undefined' with a contextual type 'string', we substitute + // 'string | undefined' to give control flow analysis the opportunity to narrow to type 'string'. + var substituteConstraints = !(checkMode && checkMode & 2 /* Inferential */) && + someType(type, isGenericTypeWithUnionConstraint) && + (isConstraintPosition(reference) || hasContextualTypeWithNoGenericTypes(reference)); + return substituteConstraints ? mapType(type, function (t) { return t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type; } function isExportOrExportExpression(location) { return !!ts.findAncestor(location, function (e) { return e.parent && ts.isExportAssignment(e.parent) && e.parent.expression === e && ts.isEntityNameExpression(e); }); @@ -65018,7 +67047,12 @@ var ts; if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { var target = resolveAlias(symbol); if (target.flags & 111551 /* Value */) { - if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(target)) { + // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled + // (because the const enum value will not be inlined), or if (2) the alias is an export + // of a const enum declaration that will be preserved. + if (compilerOptions.isolatedModules || + ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || + !isConstEnumOrConstEnumOnlyModule(target)) { markAliasSymbolAsReferenced(symbol); } else { @@ -65027,7 +67061,7 @@ var ts; } } } - function checkIdentifier(node) { + function checkIdentifier(node, checkMode) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { return errorType; @@ -65041,7 +67075,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2 /* ES2015 */) { - if (container.kind === 209 /* ArrowFunction */) { + if (container.kind === 210 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasSyntacticModifier(container, 256 /* Async */)) { @@ -65058,15 +67092,15 @@ var ts; } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var sourceSymbol = localOrExportSymbol.flags & 2097152 /* Alias */ ? resolveAlias(localOrExportSymbol) : localOrExportSymbol; - if (getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) { - errorOrSuggestion(/* isError */ false, node, ts.Diagnostics._0_is_deprecated, node.escapedText); + if (sourceSymbol.declarations && getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) { + addDeprecatedSuggestion(node, sourceSymbol.declarations, node.escapedText); } var declaration = localOrExportSymbol.valueDeclaration; - if (localOrExportSymbol.flags & 32 /* Class */) { + if (declaration && localOrExportSymbol.flags & 32 /* Class */) { // 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. - if (declaration.kind === 252 /* ClassDeclaration */ + if (declaration.kind === 253 /* ClassDeclaration */ && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -65078,14 +67112,14 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration.kind === 221 /* ClassExpression */) { + else if (declaration.kind === 222 /* ClassExpression */) { // When we emit a class expression with static members that contain a reference // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container.kind !== 297 /* SourceFile */) { + while (container.kind !== 298 /* SourceFile */) { if (container.parent === declaration) { - if (container.kind === 163 /* PropertyDeclaration */ && ts.hasSyntacticModifier(container, 32 /* Static */)) { + if (container.kind === 164 /* PropertyDeclaration */ && ts.hasSyntacticModifier(container, 32 /* Static */)) { getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } @@ -65096,12 +67130,18 @@ var ts; } } checkNestedBlockScopedBinding(node, symbol); - var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); + var type = getTypeOfSymbol(localOrExportSymbol); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + var assignmentError = localOrExportSymbol.flags & 384 /* Enum */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_an_enum + : localOrExportSymbol.flags & 32 /* Class */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_class + : localOrExportSymbol.flags & 1536 /* Module */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_namespace + : localOrExportSymbol.flags & 16 /* Function */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_function + : localOrExportSymbol.flags & 2097152 /* Alias */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_an_import + : ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable; + error(node, assignmentError, symbolToString(symbol)); return errorType; } if (isReadonlySymbol(localOrExportSymbol)) { @@ -65123,7 +67163,7 @@ var ts; } } else if (isAlias) { - declaration = ts.find(symbol.declarations, isSomeImportDeclaration); + declaration = getDeclarationOfAliasSymbol(symbol); } else { return type; @@ -65131,10 +67171,11 @@ var ts; if (!declaration) { return type; } + type = getNarrowableTypeForReference(type, node, checkMode); // The declaration container is the innermost function that encloses the declaration of the variable // or parameter. The flow container is the innermost function starting with which we analyze the control // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 160 /* Parameter */; + var isParameter = ts.getRootDeclaration(declaration).kind === 161 /* Parameter */; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; @@ -65143,8 +67184,8 @@ var ts; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === 208 /* FunctionExpression */ || - flowContainer.kind === 209 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 209 /* FunctionExpression */ || + flowContainer.kind === 210 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } @@ -65153,9 +67194,9 @@ var ts; // declaration container are the same). var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 || - isInTypeQuery(node) || node.parent.kind === 270 /* ExportSpecifier */) || - node.parent.kind === 225 /* NonNullExpression */ || - declaration.kind === 249 /* VariableDeclaration */ && declaration.exclamationToken || + isInTypeQuery(node) || node.parent.kind === 271 /* ExportSpecifier */) || + node.parent.kind === 226 /* NonNullExpression */ || + declaration.kind === 250 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 8388608 /* Ambient */; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : type === autoType || type === autoArrayType ? undefinedType : @@ -65180,17 +67221,21 @@ var ts; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } - function isInsideFunction(node, threshold) { - return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); + function isInsideFunctionOrInstancePropertyInitializer(node, threshold) { + return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n) || (n.parent && ts.isPropertyDeclaration(n.parent) && !ts.hasStaticModifier(n.parent) && n.parent.initializer === n); }); } 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 getEnclosingIterationStatement(node) { + return ts.findAncestor(node, function (n) { return (!n || ts.nodeStartsNewLexicalEnvironment(n)) ? "quit" : ts.isIterationStatement(n, /*lookInLabeledStatements*/ false); }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || + !symbol.valueDeclaration || ts.isSourceFile(symbol.valueDeclaration) || - symbol.valueDeclaration.parent.kind === 287 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 288 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -65198,22 +67243,14 @@ var ts; // 2. walk from the declaration up to the boundary of lexical environment and check // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - var usedInFunction = isInsideFunction(node.parent, container); - var current = container; - var containedInIterationStatement = false; - while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { - if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) { - containedInIterationStatement = true; - break; - } - current = current.parent; - } - if (containedInIterationStatement) { - if (usedInFunction) { + var isCaptured = isInsideFunctionOrInstancePropertyInitializer(node, container); + var enclosingIterationStatement = getEnclosingIterationStatement(container); + if (enclosingIterationStatement) { + if (isCaptured) { // mark iteration statement as containing block-scoped binding captured in some function var capturesBlockScopeBindingInLoopBody = true; if (ts.isForStatement(container)) { - var varDeclList = ts.getAncestor(symbol.valueDeclaration, 250 /* VariableDeclarationList */); + var varDeclList = ts.getAncestor(symbol.valueDeclaration, 251 /* VariableDeclarationList */); if (varDeclList && varDeclList.parent === container) { var part = getPartOfForStatementContainingNode(node.parent, container); if (part) { @@ -65228,13 +67265,13 @@ var ts; } } if (capturesBlockScopeBindingInLoopBody) { - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + getNodeLinks(enclosingIterationStatement).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 (ts.isForStatement(container)) { - var varDeclList = ts.getAncestor(symbol.valueDeclaration, 250 /* VariableDeclarationList */); + var varDeclList = ts.getAncestor(symbol.valueDeclaration, 251 /* VariableDeclarationList */); if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } @@ -65242,7 +67279,7 @@ var ts; // set 'declared inside loop' bit on the block-scoped binding getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } - if (usedInFunction) { + if (isCaptured) { getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } @@ -65253,7 +67290,7 @@ var ts; function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; - while (current.parent.kind === 207 /* ParenthesizedExpression */) { + while (current.parent.kind === 208 /* ParenthesizedExpression */) { current = current.parent; } // check if node is used as LHS in some assignment expression @@ -65261,7 +67298,7 @@ var ts; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 214 /* PrefixUnaryExpression */ || current.parent.kind === 215 /* PostfixUnaryExpression */)) { + else if ((current.parent.kind === 215 /* PrefixUnaryExpression */ || current.parent.kind === 216 /* PostfixUnaryExpression */)) { var expr = current.parent; isAssigned = expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */; } @@ -65274,7 +67311,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 163 /* PropertyDeclaration */ || container.kind === 166 /* Constructor */) { + if (container.kind === 164 /* PropertyDeclaration */ || container.kind === 167 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -65314,37 +67351,37 @@ var ts; // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var capturedByArrowFunction = false; - if (container.kind === 166 /* Constructor */) { + if (container.kind === 167 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 209 /* ArrowFunction */) { + if (container.kind === 210 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); capturedByArrowFunction = true; } switch (container.kind) { - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 166 /* Constructor */: + case 167 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -65432,7 +67469,7 @@ var ts; } function getClassNameFromPrototypeMethod(container) { // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 208 /* FunctionExpression */ && + if (container.kind === 209 /* FunctionExpression */ && ts.isBinaryExpression(container.parent) && ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { // Get the 'x' of 'x.prototype.y = container' @@ -65442,16 +67479,16 @@ var ts; .expression; // x } // x.prototype = { method() { } } - else if (container.kind === 165 /* MethodDeclaration */ && - container.parent.kind === 200 /* ObjectLiteralExpression */ && + else if (container.kind === 166 /* MethodDeclaration */ && + container.parent.kind === 201 /* 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 === 208 /* FunctionExpression */ && - container.parent.kind === 288 /* PropertyAssignment */ && - container.parent.parent.kind === 200 /* ObjectLiteralExpression */ && + else if (container.kind === 209 /* FunctionExpression */ && + container.parent.kind === 289 /* PropertyAssignment */ && + container.parent.parent.kind === 201 /* ObjectLiteralExpression */ && ts.isBinaryExpression(container.parent.parent.parent) && ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { return container.parent.parent.parent.left.expression; @@ -65459,7 +67496,7 @@ var ts; // Object.defineProperty(x, "method", { value: function() { } }); // Object.defineProperty(x, "method", { set: (x: () => void) => void }); // Object.defineProperty(x, "method", { get: () => function() { }) }); - else if (container.kind === 208 /* FunctionExpression */ && + else if (container.kind === 209 /* FunctionExpression */ && ts.isPropertyAssignment(container.parent) && ts.isIdentifier(container.parent.name) && (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && @@ -65484,7 +67521,7 @@ var ts; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 308 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 309 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -65498,16 +67535,16 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 160 /* Parameter */ && n.parent === constructorDecl; }); + return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 161 /* Parameter */ && n.parent === constructorDecl; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 203 /* CallExpression */ && node.parent.expression === node; + var isCallExpression = node.parent.kind === 204 /* CallExpression */ && node.parent.expression === node; var immediateContainer = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var container = immediateContainer; var needToCaptureLexicalThis = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - while (container && container.kind === 209 /* ArrowFunction */) { + while (container && container.kind === 210 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } @@ -65520,14 +67557,14 @@ var ts; // class B { // [super.foo()]() {} // } - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 158 /* ComputedPropertyName */; }); - if (current && current.kind === 158 /* ComputedPropertyName */) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 159 /* ComputedPropertyName */; }); + if (current && current.kind === 159 /* ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 200 /* ObjectLiteralExpression */)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 201 /* ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -65535,7 +67572,7 @@ var ts; } return errorType; } - if (!isCallExpression && immediateContainer.kind === 166 /* Constructor */) { + if (!isCallExpression && immediateContainer.kind === 167 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } if (ts.hasSyntacticModifier(container, 32 /* Static */) || isCallExpression) { @@ -65604,7 +67641,7 @@ var ts; // 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 === 165 /* MethodDeclaration */ && ts.hasSyntacticModifier(container, 256 /* Async */)) { + if (container.kind === 166 /* MethodDeclaration */ && ts.hasSyntacticModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } @@ -65618,7 +67655,7 @@ var ts; // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 200 /* ObjectLiteralExpression */) { + if (container.parent.kind === 201 /* ObjectLiteralExpression */) { if (languageVersion < 2 /* ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return errorType; @@ -65639,7 +67676,7 @@ var ts; if (!baseClassType) { return errorType; } - if (container.kind === 166 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 167 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return errorType; @@ -65654,7 +67691,7 @@ var ts; if (isCallExpression) { // TS 1.0 SPEC (April 2014): 4.8.1 // Super calls are only permitted in constructors of derived classes - return container.kind === 166 /* Constructor */; + return container.kind === 167 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -65662,21 +67699,21 @@ var ts; // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance // - In a static member function or static member accessor // topmost container must be something that is directly nested in the class declaration\object literal expression - if (ts.isClassLike(container.parent) || container.parent.kind === 200 /* ObjectLiteralExpression */) { + if (ts.isClassLike(container.parent) || container.parent.kind === 201 /* ObjectLiteralExpression */) { if (ts.hasSyntacticModifier(container, 32 /* Static */)) { - return container.kind === 165 /* MethodDeclaration */ || - container.kind === 164 /* MethodSignature */ || - container.kind === 167 /* GetAccessor */ || - container.kind === 168 /* SetAccessor */; + return container.kind === 166 /* MethodDeclaration */ || + container.kind === 165 /* MethodSignature */ || + container.kind === 168 /* GetAccessor */ || + container.kind === 169 /* SetAccessor */; } else { - return container.kind === 165 /* MethodDeclaration */ || - container.kind === 164 /* MethodSignature */ || - container.kind === 167 /* GetAccessor */ || - container.kind === 168 /* SetAccessor */ || - container.kind === 163 /* PropertyDeclaration */ || - container.kind === 162 /* PropertySignature */ || - container.kind === 166 /* Constructor */; + return container.kind === 166 /* MethodDeclaration */ || + container.kind === 165 /* MethodSignature */ || + container.kind === 168 /* GetAccessor */ || + container.kind === 169 /* SetAccessor */ || + container.kind === 164 /* PropertyDeclaration */ || + container.kind === 163 /* PropertySignature */ || + container.kind === 167 /* Constructor */; } } } @@ -65684,10 +67721,10 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 165 /* MethodDeclaration */ || - func.kind === 167 /* GetAccessor */ || - func.kind === 168 /* SetAccessor */) && func.parent.kind === 200 /* ObjectLiteralExpression */ ? func.parent : - func.kind === 208 /* FunctionExpression */ && func.parent.kind === 288 /* PropertyAssignment */ ? func.parent.parent : + return (func.kind === 166 /* MethodDeclaration */ || + func.kind === 168 /* GetAccessor */ || + func.kind === 169 /* SetAccessor */) && func.parent.kind === 201 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 209 /* FunctionExpression */ && func.parent.kind === 289 /* PropertyAssignment */ ? func.parent.parent : undefined; } function getThisTypeArgument(type) { @@ -65699,7 +67736,7 @@ var ts; }); } function getContextualThisParameterType(func) { - if (func.kind === 209 /* ArrowFunction */) { + if (func.kind === 210 /* ArrowFunction */) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -65726,7 +67763,7 @@ var ts; if (thisType) { return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral))); } - if (literal.parent.kind !== 288 /* PropertyAssignment */) { + if (literal.parent.kind !== 289 /* PropertyAssignment */) { break; } literal = literal.parent.parent; @@ -65740,7 +67777,7 @@ var ts; // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. var parent = ts.walkUpParenthesizedExpressions(func.parent); - if (parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) { + if (parent.kind === 217 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) { var target = parent.left; if (ts.isAccessExpression(target)) { var expression = target.expression; @@ -65793,11 +67830,11 @@ var ts; return getTypeFromTypeNode(typeNode); } switch (declaration.kind) { - case 160 /* Parameter */: + case 161 /* Parameter */: return getContextuallyTypedParameterType(declaration); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return getContextualTypeForBindingElement(declaration); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: if (ts.hasSyntacticModifier(declaration, 32 /* Static */)) { return getContextualTypeForStaticPropertyDeclaration(declaration); } @@ -65808,10 +67845,10 @@ var ts; var parent = declaration.parent.parent; var name = declaration.propertyName || declaration.name; var parentType = getContextualTypeForVariableLikeDeclaration(parent) || - parent.kind !== 198 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent); + parent.kind !== 199 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent); if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name)) return undefined; - if (parent.name.kind === 197 /* ArrayBindingPattern */) { + if (parent.name.kind === 198 /* ArrayBindingPattern */) { var index = ts.indexOfNode(declaration.parent.elements, declaration); if (index < 0) return undefined; @@ -65948,7 +67985,7 @@ var ts; return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 205 /* TaggedTemplateExpression */) { + if (template.parent.kind === 206 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -65982,16 +68019,16 @@ var ts; // In an assignment expression, the right operand is contextually typed by the type of the left operand. // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. function getContextualTypeForAssignmentDeclaration(binaryExpression) { + var _a, _b; var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return getTypeOfExpression(binaryExpression.left); + case 4 /* ThisProperty */: + return getContextualTypeForThisPropertyAssignment(binaryExpression); case 5 /* Property */: - case 1 /* ExportsProperty */: - case 6 /* Prototype */: - case 3 /* PrototypeProperty */: if (isPossiblyAliasedThisProperty(binaryExpression, kind)) { - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + return getContextualTypeForThisPropertyAssignment(binaryExpression); } // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. // See `bindStaticPropertyAssignment` in `binder.ts`. @@ -66012,11 +68049,11 @@ var ts; var id = lhs.expression; var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true); if (parentSymbol) { - var annotated = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); - if (annotated) { + var annotated_1 = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated_1) { var nameStr = ts.getElementOrPropertyAccessName(lhs); if (nameStr !== undefined) { - return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr); + return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated_1), nameStr); } } return undefined; @@ -66024,9 +68061,15 @@ var ts; } return ts.isInJSFile(decl) ? undefined : getTypeOfExpression(binaryExpression.left); } + case 1 /* ExportsProperty */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + var valueDeclaration = (_a = binaryExpression.left.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration; + // falls through case 2 /* ModuleExports */: - case 4 /* ThisProperty */: - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + valueDeclaration || (valueDeclaration = (_b = binaryExpression.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration); + var annotated = valueDeclaration && ts.getEffectiveTypeAnnotationNode(valueDeclaration); + return annotated ? getTypeFromTypeNode(annotated) : undefined; case 7 /* ObjectDefinePropertyValue */: case 8 /* ObjectDefinePropertyExports */: case 9 /* ObjectDefinePrototypeProperty */: @@ -66047,7 +68090,7 @@ var ts; var symbol = resolveName(declaration.left, name, 111551 /* Value */, undefined, undefined, /*isUse*/ true, /*excludeGlobals*/ true); return ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration); } - function getContextualTypeForThisPropertyAssignment(binaryExpression, kind) { + function getContextualTypeForThisPropertyAssignment(binaryExpression) { if (!binaryExpression.symbol) return getTypeOfExpression(binaryExpression.left); if (binaryExpression.symbol.valueDeclaration) { @@ -66059,8 +68102,6 @@ var ts; } } } - if (kind === 2 /* ModuleExports */) - return undefined; var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression); if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { return undefined; @@ -66115,9 +68156,13 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + if (propertyAssignmentType) { + return propertyAssignmentType; + } var type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { - if (!hasNonBindableDynamicName(element)) { + if (hasBindableName(element)) { // 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. @@ -66203,19 +68248,19 @@ var ts; case 78 /* Identifier */: case 150 /* UndefinedKeyword */: return true; - case 201 /* PropertyAccessExpression */: - case 207 /* ParenthesizedExpression */: + case 202 /* PropertyAccessExpression */: + case 208 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); - case 283 /* JsxExpression */: + case 284 /* 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 === 288 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 289 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 280 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. @@ -66226,15 +68271,9 @@ var ts; var instantiatedType = instantiateContextualType(contextualType, node, contextFlags); if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) { var apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true); - if (apparentType.flags & 1048576 /* Union */) { - if (ts.isObjectLiteralExpression(node)) { - return discriminateContextualTypeByObjectMembers(node, apparentType); - } - else if (ts.isJsxAttributes(node)) { - return discriminateContextualTypeByJSXAttributes(node, apparentType); - } - } - return apparentType; + return apparentType.flags & 1048576 /* Union */ && ts.isObjectLiteralExpression(node) ? discriminateContextualTypeByObjectMembers(node, apparentType) : + apparentType.flags & 1048576 /* Union */ && ts.isJsxAttributes(node) ? discriminateContextualTypeByJSXAttributes(node, apparentType) : + apparentType; } } // If the given contextual type contains instantiable types and if a mapper representing @@ -66301,58 +68340,60 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 198 /* BindingElement */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 199 /* BindingElement */: return getContextualTypeForInitializerExpression(node, contextFlags); - case 209 /* ArrowFunction */: - case 242 /* ReturnStatement */: + case 210 /* ArrowFunction */: + case 243 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return getContextualTypeForAwaitOperand(parent, contextFlags); - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (parent.expression.kind === 99 /* ImportKeyword */) { return stringType; } /* falls through */ - case 204 /* NewExpression */: + case 205 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return ts.isConstTypeReference(parent.type) ? tryFindWhenConstTypeReference(parent) : getTypeFromTypeNode(parent.type); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node, contextFlags); - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent, contextFlags); - case 290 /* SpreadAssignment */: - return getApparentTypeOfContextualType(parent.parent, contextFlags); - case 199 /* ArrayLiteralExpression */: { + case 291 /* SpreadAssignment */: + return getContextualType(parent.parent, contextFlags); + case 200 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node, contextFlags); - case 228 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 218 /* TemplateExpression */); + case 229 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 219 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 207 /* ParenthesizedExpression */: { + case 208 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags); } - case 283 /* JsxExpression */: + case 226 /* NonNullExpression */: + return getContextualType(parent, contextFlags); + case 284 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); - case 280 /* JsxAttribute */: - case 282 /* JsxSpreadAttribute */: + case 281 /* JsxAttribute */: + case 283 /* JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent); - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent, contextFlags); } return undefined; @@ -66388,14 +68429,14 @@ var ts; return propsType; } function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { - if (sig.unionSignatures) { + if (sig.compositeSignatures) { // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature, // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur // for a union signature). It's an unfortunate quirk of looking in the output of the signature for the type we want to use for the input. // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane. var results = []; - for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) { + for (var _i = 0, _a = sig.compositeSignatures; _i < _a.length; _i++) { var signature = _a[_i]; var instance = getReturnTypeOfSignature(signature); if (isTypeAny(instance)) { @@ -66407,7 +68448,7 @@ var ts; } results.push(propType); } - return getIntersectionType(results); + return getIntersectionType(results); // Same result for both union and intersection signatures } var instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); @@ -66432,16 +68473,19 @@ var ts; function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { var managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { - var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); // fetches interface type, or initializes symbol links type parmaeters var ctorType = getStaticTypeOfReferencedJsxConstructor(context); + if (managedSym.flags & 524288 /* TypeAlias */) { + var params = getSymbolLinks(managedSym).typeParameters; + if (ts.length(params) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], params, 2, ts.isInJSFile(context)); + return getTypeAliasInstantiation(managedSym, args); + } + } if (ts.length(declaredManagedType.typeParameters) >= 2) { var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } - else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); - return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); - } } return attributesType; } @@ -66486,16 +68530,93 @@ var ts; return apparentAttributesType; } } + function getIntersectedSignatures(signatures) { + return ts.getStrictOptionValue(compilerOptions, "noImplicitAny") + ? ts.reduceLeft(signatures, function (left, right) { + return left === right || !left ? left + : compareTypeParametersIdentical(left.typeParameters, right.typeParameters) ? combineSignaturesOfIntersectionMembers(left, right) + : undefined; + }) + : undefined; + } + function combineIntersectionThisParam(left, right, mapper) { + if (!left || !right) { + return left || right; + } + // A signature `this` type might be a read or a write position... It's very possible that it should be invariant + // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be + // pessimistic when contextual typing, for now, we'll union the `this` types. + var thisType = getUnionType([getTypeOfSymbol(left), instantiateType(getTypeOfSymbol(right), mapper)]); + return createSymbolWithType(left, thisType); + } + function combineIntersectionParameters(left, right, mapper) { + var leftCount = getParameterCount(left); + var rightCount = getParameterCount(right); + var longest = leftCount >= rightCount ? left : right; + var shorter = longest === left ? right : left; + var longestCount = longest === left ? leftCount : rightCount; + var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right)); + var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest); + var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0)); + for (var i = 0; i < longestCount; i++) { + var longestParamType = tryGetTypeAtPosition(longest, i); + if (longest === right) { + longestParamType = instantiateType(longestParamType, mapper); + } + var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType; + if (shorter === right) { + shorterParamType = instantiateType(shorterParamType, mapper); + } + var unionParamType = getUnionType([longestParamType, shorterParamType]); + var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1); + var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter); + var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i); + var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i); + var paramName = leftName === rightName ? leftName : + !leftName ? rightName : + !rightName ? leftName : + undefined; + var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg" + i); + paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType; + params[i] = paramSymbol; + } + if (needsExtraRestElement) { + var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args"); + restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount)); + if (shorter === right) { + restParamSymbol.type = instantiateType(restParamSymbol.type, mapper); + } + params[longestCount] = restParamSymbol; + } + return params; + } + function combineSignaturesOfIntersectionMembers(left, right) { + var typeParams = left.typeParameters || right.typeParameters; + var paramMapper; + if (left.typeParameters && right.typeParameters) { + paramMapper = createTypeMapper(right.typeParameters, left.typeParameters); + // We just use the type parameter defaults from the first signature + } + var declaration = left.declaration; + var params = combineIntersectionParameters(left, right, paramMapper); + var thisParam = combineIntersectionThisParam(left.thisParameter, right.thisParameter, paramMapper); + var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); + var result = createSignature(declaration, typeParams, thisParam, params, + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 39 /* PropagatingFlags */); + result.compositeKind = 2097152 /* Intersection */; + result.compositeSignatures = ts.concatenate(left.compositeKind === 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); + if (paramMapper) { + result.mapper = left.compositeKind === 2097152 /* Intersection */ && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; + } + return result; + } // If the given type is an object or union type with a single signature, and if that signature has at // least as many parameters as the given function, return the signature. Otherwise return undefined. function getContextualCallSignature(type, node) { var signatures = getSignaturesOfType(type, 0 /* Call */); - if (signatures.length === 1) { - var signature = signatures[0]; - if (!isAritySmaller(signature, node)) { - return signature; - } - } + var applicableByArity = ts.filter(signatures, function (s) { return !isAritySmaller(s, node); }); + return applicableByArity.length === 1 ? applicableByArity[0] : getIntersectedSignatures(applicableByArity); } /** If the contextual signature has fewer parameters than the function expression, do not use it */ function isAritySmaller(signature, target) { @@ -66512,7 +68633,7 @@ var ts; return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 208 /* FunctionExpression */ || node.kind === 209 /* ArrowFunction */; + return node.kind === 209 /* FunctionExpression */ || node.kind === 210 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -66526,7 +68647,7 @@ var ts; // all identical ignoring their return type, the result is same signature but with return type as // union type of return types from these signatures function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var typeTagSignature = getSignatureOfTypeTag(node); if (typeTagSignature) { return typeTagSignature; @@ -66574,8 +68695,8 @@ var ts; return node.isSpread ? getIndexedAccessType(node.type, numberType) : node.type; } function hasDefaultValue(node) { - return (node.kind === 198 /* BindingElement */ && !!node.initializer) || - (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */); + return (node.kind === 199 /* BindingElement */ && !!node.initializer) || + (node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */); } function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; @@ -66587,7 +68708,7 @@ var ts; var inConstContext = isConstContext(node); for (var i = 0; i < elementCount; i++) { var e = elements[i]; - if (e.kind === 220 /* SpreadElement */) { + if (e.kind === 221 /* SpreadElement */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */); } @@ -66630,7 +68751,7 @@ var ts; if (inDestructuringPattern) { return createTupleType(elementTypes, elementFlags); } - if (forceTuple || inConstContext || contextualType && forEachType(contextualType, isTupleLikeType)) { + if (forceTuple || inConstContext || contextualType && someType(contextualType, isTupleLikeType)) { return createArrayLiteralType(createTupleType(elementTypes, elementFlags, /*readonly*/ inConstContext)); } return createArrayLiteralType(createArrayType(elementTypes.length ? @@ -66644,13 +68765,13 @@ var ts; var literalType = type.literalType; if (!literalType) { literalType = type.literalType = cloneTypeReference(type); - literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + literalType.objectFlags |= 32768 /* ArrayLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; } return literalType; } function isNumericName(name) { switch (name.kind) { - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return isNumericComputedName(name); case 78 /* Identifier */: return isNumericLiteralName(name.escapedText); @@ -66697,6 +68818,20 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); + // The computed property name of a non-static class field within a loop must be stored in a block-scoped binding. + // (It needs to be bound at class evaluation time.) + if (ts.isPropertyDeclaration(node.parent) && !ts.hasStaticModifier(node.parent) && ts.isClassExpression(node.parent.parent)) { + var container = ts.getEnclosingBlockScopeContainer(node.parent.parent); + var enclosingIterationStatement = getEnclosingIterationStatement(container); + if (enclosingIterationStatement) { + // The computed field name will use a block scoped binding which can be unique for each iteration of the loop. + getNodeLinks(enclosingIterationStatement).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + // The generated variable which stores the computed field name must be block-scoped. + getNodeLinks(node).flags |= 524288 /* BlockScopedBindingInLoop */; + // The generated variable which stores the class must be block-scoped. + getNodeLinks(node.parent.parent).flags |= 524288 /* BlockScopedBindingInLoop */; + } + } // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). if (links.resolvedType.flags & 98304 /* Nullable */ || @@ -66704,9 +68839,6 @@ var ts; !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } - else { - checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true); - } } return links.resolvedType; } @@ -66746,7 +68878,7 @@ var ts; var spread = emptyObjectType; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 196 /* ObjectBindingPattern */ || contextualType.pattern.kind === 200 /* ObjectLiteralExpression */); + (contextualType.pattern.kind === 197 /* ObjectBindingPattern */ || contextualType.pattern.kind === 201 /* ObjectLiteralExpression */); var inConstContext = isConstContext(node); var checkFlags = inConstContext ? 8 /* Readonly */ : 0; var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); @@ -66761,7 +68893,7 @@ var ts; // which may never occur. for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; - if (elem.name && ts.isComputedPropertyName(elem.name) && !ts.isWellKnownSymbolSyntactically(elem.name)) { + if (elem.name && ts.isComputedPropertyName(elem.name)) { checkComputedPropertyName(elem.name); } } @@ -66769,16 +68901,16 @@ var ts; for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var memberDecl = _c[_b]; var member = getSymbolOfNode(memberDecl); - var computedNameType = memberDecl.name && memberDecl.name.kind === 158 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + var computedNameType = memberDecl.name && memberDecl.name.kind === 159 /* ComputedPropertyName */ ? checkComputedPropertyName(memberDecl.name) : undefined; - if (memberDecl.kind === 288 /* PropertyAssignment */ || - memberDecl.kind === 289 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 289 /* PropertyAssignment */ || + memberDecl.kind === 290 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { - var type = memberDecl.kind === 288 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + var type = memberDecl.kind === 289 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`. // we don't want to say "could not find 'a'". - memberDecl.kind === 289 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : + memberDecl.kind === 290 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); @@ -66790,7 +68922,7 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) : @@ -66801,8 +68933,8 @@ var ts; if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. - var isOptional = (memberDecl.kind === 288 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 289 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 289 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 290 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216 /* Optional */; } @@ -66828,7 +68960,7 @@ var ts; member = prop; allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop); } - else if (memberDecl.kind === 290 /* SpreadAssignment */) { + else if (memberDecl.kind === 291 /* SpreadAssignment */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } @@ -66840,15 +68972,20 @@ var ts; hasComputedNumberProperty = false; } var type = getReducedType(checkExpression(memberDecl.expression)); - if (!isValidSpreadType(type)) { - error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return errorType; + if (isValidSpreadType(type)) { + if (allPropertiesTable) { + checkSpreadPropOverrides(type, allPropertiesTable, memberDecl); + } + offset = propertiesArray.length; + if (spread === errorType) { + continue; + } + spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext); } - if (allPropertiesTable) { - checkSpreadPropOverrides(type, allPropertiesTable, memberDecl); + else { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + spread = errorType; } - spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext); - offset = propertiesArray.length; continue; } else { @@ -66857,7 +68994,7 @@ var ts; // an ordinary function declaration(section 6.1) with no parameters. // A set accessor declaration is processed in the same manner // as an ordinary function declaration with a single parameter and a Void return type. - ts.Debug.assert(memberDecl.kind === 167 /* GetAccessor */ || memberDecl.kind === 168 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 168 /* GetAccessor */ || memberDecl.kind === 169 /* SetAccessor */); checkNodeDeferred(memberDecl); } if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) { @@ -66882,7 +69019,7 @@ var ts; // type with those properties for which the binding pattern specifies a default value. // If the object literal is spread into another object literal, skip this step and let the top-level object // literal handle it instead. - if (contextualTypeHasPattern && node.parent.kind !== 290 /* SpreadAssignment */) { + if (contextualTypeHasPattern && node.parent.kind !== 291 /* SpreadAssignment */) { for (var _d = 0, _e = getPropertiesOfType(contextualType); _d < _e.length; _d++) { var prop = _e[_d]; if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) { @@ -66894,6 +69031,9 @@ var ts; } } } + if (spread === errorType) { + return errorType; + } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext); @@ -66910,9 +69050,9 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; if (isJSObjectLiteral) { - result.objectFlags |= 16384 /* JSLiteral */; + result.objectFlags |= 8192 /* JSLiteral */; } if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; @@ -67002,14 +69142,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var objectFlags = 4096 /* JsxAttributes */; + var objectFlags = 2048 /* JsxAttributes */; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -67025,7 +69165,7 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 282 /* JsxSpreadAttribute */); + ts.Debug.assert(attributeDecl.kind === 283 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false); attributesTable = ts.createSymbolTable(); @@ -67051,7 +69191,7 @@ var ts; } } // Handle children attribute - var parent = openingLikeElement.parent.kind === 273 /* JsxElement */ ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 274 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = checkJsxChildren(parent, checkMode); @@ -67067,7 +69207,7 @@ var ts; // 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 */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - childrenContextualType && forEachType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : + childrenContextualType && someType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : createArrayType(getUnionType(childrenTypes)); // Fake up a property declaration for the children childrenPropSymbol.valueDeclaration = ts.factory.createPropertySignature(/*modifiers*/ undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined); @@ -67093,7 +69233,7 @@ var ts; function createJsxAttributesType() { objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return result; } } @@ -67108,7 +69248,7 @@ var ts; childrenTypes.push(stringType); } } - else if (child.kind === 283 /* JsxExpression */ && !child.expression) { + else if (child.kind === 284 /* JsxExpression */ && !child.expression) { continue; // empty jsx expressions don't *really* count as present children } else { @@ -67259,7 +69399,7 @@ var ts; else if (propertiesOfJsxElementAttribPropInterface.length === 1) { return propertiesOfJsxElementAttribPropInterface[0].escapedName; } - else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + else if (propertiesOfJsxElementAttribPropInterface.length > 1 && jsxElementAttribPropInterfaceSym.declarations) { // More than one property on ElementAttributesProperty is an error error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer)); } @@ -67369,11 +69509,11 @@ var ts; if (!links.resolvedJsxElementAttributesType) { var symbol = getIntrinsicTagSymbol(node); if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { - return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol) || errorType; } else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { return links.resolvedJsxElementAttributesType = - getIndexTypeOfType(getDeclaredTypeOfSymbol(symbol), 0 /* String */); + getIndexTypeOfType(getJsxType(JsxNames.IntrinsicElements, node), 0 /* String */) || errorType; } else { return links.resolvedJsxElementAttributesType = errorType; @@ -67526,9 +69666,12 @@ var ts; * @param type The type of the object whose property is being accessed. (Not the type of the property.) * @param prop The symbol for the property being accessed. */ - function checkPropertyAccessibility(node, isSuper, type, prop) { - var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 157 /* QualifiedName */ ? node.right : node.kind === 195 /* ImportType */ ? node : node.name; + function checkPropertyAccessibility(node, isSuper, writing, type, prop, reportError) { + if (reportError === void 0) { reportError = true; } + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop, writing); + var errorNode = node.kind === 158 /* QualifiedName */ ? node.right : + node.kind === 196 /* ImportType */ ? node : + node.kind === 199 /* BindingElement */ && node.propertyName ? node.propertyName : node.name; if (isSuper) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or @@ -67539,7 +69682,9 @@ var ts; // a super property access is permitted and must specify a public static member function of the base class. if (languageVersion < 2 /* ES2015 */) { if (symbolHasNonMethodDeclaration(prop)) { - error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + if (reportError) { + error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + } return false; } } @@ -67548,24 +69693,22 @@ var ts; // This error could mask a private property access error. But, a member // cannot simultaneously be private and abstract, so this will trigger an // additional error elsewhere. - error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + if (reportError) { + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + } return false; } } // Referencing abstract properties within their own constructors is not allowed - if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { + if ((flags & 128 /* Abstract */) && symbolHasNonMethodDeclaration(prop) && + (ts.isThisProperty(node) || ts.isThisInitializedObjectBindingExpression(node) || ts.isObjectBindingPattern(node.parent) && ts.isThisInitializedDeclaration(node.parent.parent))) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); 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; - } - } - if (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name)) { - if (!ts.getContainingClass(node)) { - error(errorNode, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + if (reportError) { + 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; } - return true; } // Public properties are otherwise accessible. if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { @@ -67576,7 +69719,9 @@ var ts; if (flags & 8 /* Private */) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + if (reportError) { + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + } return false; } return true; @@ -67590,7 +69735,7 @@ var ts; // of the property as base classes var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + return isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing) ? enclosingClass : undefined; }); // A protected property is accessible if the property is within the declaring class or classes derived from it if (!enclosingClass) { @@ -67598,7 +69743,9 @@ var ts; // static member access is disallow var thisParameter = void 0; if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + if (reportError) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + } return false; } var thisType = getTypeFromTypeNode(thisParameter.type); @@ -67613,7 +69760,9 @@ var ts; type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined } if (!type || !hasBaseType(type, enclosingClass)) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + if (reportError) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2, symbolToString(prop), typeToString(enclosingClass), typeToString(type)); + } return false; } return true; @@ -67669,20 +69818,20 @@ var ts; } return nonNullType; } - function checkPropertyAccessExpression(node) { - return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) : - checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + function checkPropertyAccessExpression(node, checkMode) { + return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node, checkMode) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name, checkMode); } - function checkPropertyAccessChain(node) { + function checkPropertyAccessChain(node, checkMode) { var leftType = checkExpression(node.expression); var nonOptionalType = getOptionalExpressionType(leftType, node.expression); - return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name, checkMode), node, nonOptionalType !== leftType); } - function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); + function checkQualifiedName(node, checkMode) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right, checkMode); } function isMethodAccessForCall(node) { - while (node.parent.kind === 207 /* ParenthesizedExpression */) { + while (node.parent.kind === 208 /* ParenthesizedExpression */) { node = node.parent; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; @@ -67717,14 +69866,13 @@ var ts; } var diagName = diagnosticName(right); if (propertyOnType) { - var typeValueDecl = propertyOnType.valueDeclaration; - var typeClass_1 = ts.getContainingClass(typeValueDecl); - ts.Debug.assert(!!typeClass_1); + var typeValueDecl = ts.Debug.checkDefined(propertyOnType.valueDeclaration); + var typeClass_1 = ts.Debug.checkDefined(ts.getContainingClass(typeValueDecl)); // We found a private identifier property with the same description. // Either: // - There is a lexically scoped private identifier AND it shadows the one we found on the type. // - It is an attempt to access the private identifier outside of the class. - if (lexicallyScopedIdentifier) { + if (lexicallyScopedIdentifier === null || lexicallyScopedIdentifier === void 0 ? void 0 : lexicallyScopedIdentifier.valueDeclaration) { var lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration; var lexicalClass = ts.getContainingClass(lexicalValueDecl); ts.Debug.assert(!!lexicalClass); @@ -67743,17 +69891,42 @@ var ts; return (isConstructorDeclaredProperty(prop) || ts.isThisProperty(node) && isAutoTypedProperty(prop)) && ts.getThisContainer(node, /*includeArrowFunctions*/ true) === getDeclaringConstructor(prop); } - function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right, checkMode) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); - if (ts.isPrivateIdentifier(right)) { - checkExternalEmitHelpers(node, 524288 /* ClassPrivateFieldGet */); - } var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType; var prop; if (ts.isPrivateIdentifier(right)) { + if (languageVersion < 99 /* ESNext */) { + if (assignmentKind !== 0 /* None */) { + checkExternalEmitHelpers(node, 1048576 /* ClassPrivateFieldSet */); + } + if (assignmentKind !== 1 /* Definite */) { + checkExternalEmitHelpers(node, 524288 /* ClassPrivateFieldGet */); + } + } var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right); + if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && ts.isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) { + grammarErrorOnNode(right, ts.Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, ts.idText(right)); + } + if ((lexicallyScopedSymbol === null || lexicallyScopedSymbol === void 0 ? void 0 : lexicallyScopedSymbol.valueDeclaration) && (compilerOptions.target === 99 /* ESNext */ && !useDefineForClassFields)) { + var lexicalClass_1 = ts.getContainingClass(lexicallyScopedSymbol.valueDeclaration); + var parentStaticFieldInitializer = ts.findAncestor(node, function (n) { + if (n === lexicalClass_1) + return "quit"; + if (ts.isPropertyDeclaration(n.parent) && ts.hasStaticModifier(n.parent) && n.parent.initializer === n && n.parent.parent === lexicalClass_1) { + return true; + } + return false; + }); + if (parentStaticFieldInitializer) { + var parentStaticFieldInitializerSymbol = getSymbolOfNode(parentStaticFieldInitializer.parent); + ts.Debug.assert(parentStaticFieldInitializerSymbol, "Initializer without declaration symbol"); + var diagnostic = error(node, ts.Diagnostics.Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false, ts.symbolName(lexicallyScopedSymbol)); + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(parentStaticFieldInitializer.parent, ts.Diagnostics.Initializer_for_property_0, ts.symbolName(parentStaticFieldInitializerSymbol))); + } + } if (isAnyLike) { if (lexicallyScopedSymbol) { return apparentType; @@ -67768,6 +69941,12 @@ var ts; if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) { return errorType; } + else { + var isSetonlyAccessor = prop && prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (isSetonlyAccessor && assignmentKind !== 1 /* Definite */) { + error(node, ts.Diagnostics.Private_accessor_was_defined_without_a_getter); + } + } } else { if (isAnyLike) { @@ -67778,7 +69957,11 @@ var ts; } prop = getPropertyOfType(apparentType, right.escapedText); } - if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums. + // The exceptions are: + // 1. if 'isolatedModules' is enabled, because the const enum value will not be inlined, and + // 2. if 'preserveConstEnums' is enabled and the expression is itself an export, e.g. `export = Foo.Bar.Baz`. + if (ts.isIdentifier(left) && parentSymbol && (compilerOptions.isolatedModules || !(prop && isConstEnumOrConstEnumOnlyModule(prop)) || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) { markAliasReferenced(parentSymbol, node); } var propType; @@ -67811,44 +69994,48 @@ var ts; } } else { - if (getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) { - errorOrSuggestion(/* isError */ false, right, ts.Diagnostics._0_is_deprecated, right.escapedText); + if (prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) { + addDeprecatedSuggestion(right, prop.declarations, right.escapedText); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node, left.kind === 107 /* ThisKeyword */); + markPropertyAsReferenced(prop, node, isSelfTypeAccess(left, parentSymbol)); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left.kind === 105 /* SuperKeyword */, apparentType, prop); + var writing = ts.isWriteAccess(node); + checkPropertyAccessibility(node, left.kind === 105 /* SuperKeyword */, writing, apparentType, prop); if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) { error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } - propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : getConstraintForLocation(getTypeOfSymbol(prop), node); + propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : writing ? getSetAccessorTypeOfSymbol(prop) : getTypeOfSymbol(prop); } - return getFlowTypeOfAccessExpression(node, prop, propType, right); + return getFlowTypeOfAccessExpression(node, prop, propType, right, checkMode); } - function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { + function getFlowTypeOfAccessExpression(node, prop, propType, errorNode, checkMode) { // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. var assignmentKind = ts.getAssignmentTargetKind(node); - if (!ts.isAccessExpression(node) || - assignmentKind === 1 /* Definite */ || - prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { + if (assignmentKind === 1 /* Definite */ || + prop && + !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) + && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */) + && !isDuplicatedCommonJSExport(prop.declarations)) { return propType; } if (propType === autoType) { return getFlowTypeOfProperty(node, prop); } + propType = getNarrowableTypeForReference(propType, node, checkMode); // If strict null checks and strict property initialization checks are enabled, if we have // a this.xxx property access, if the property is an instance property without an initializer, // and if we are in a constructor of the same class as the property declaration, assume that // the property is uninitialized at the top of the control flow. var assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 107 /* ThisKeyword */) { + if (strictNullChecks && strictPropertyInitialization && ts.isAccessExpression(node) && node.expression.kind === 107 /* ThisKeyword */) { var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); - if (flowContainer.kind === 166 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) { + if (flowContainer.kind === 167 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) { assumeUninitialized = true; } } @@ -67875,13 +70062,14 @@ var ts; var diagnosticMessage; var declarationName = ts.idText(right); if (isInPropertyInitializer(node) + && !isOptionalPropertyDeclaration(valueDeclaration) && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) - && !isPropertyDeclaredInAncestorClass(prop)) { + && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } - else if (valueDeclaration.kind === 252 /* ClassDeclaration */ && - node.parent.kind !== 173 /* TypeReference */ && + else if (valueDeclaration.kind === 253 /* ClassDeclaration */ && + node.parent.kind !== 174 /* TypeReference */ && !(valueDeclaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); @@ -67893,22 +70081,22 @@ var ts; function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return true; - case 288 /* PropertyAssignment */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 290 /* SpreadAssignment */: - case 158 /* ComputedPropertyName */: - case 228 /* TemplateSpan */: - case 283 /* JsxExpression */: - case 280 /* JsxAttribute */: - case 281 /* JsxAttributes */: - case 282 /* JsxSpreadAttribute */: - case 275 /* JsxOpeningElement */: - case 223 /* ExpressionWithTypeArguments */: - case 286 /* HeritageClause */: + case 289 /* PropertyAssignment */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 291 /* SpreadAssignment */: + case 159 /* ComputedPropertyName */: + case 229 /* TemplateSpan */: + case 284 /* JsxExpression */: + case 281 /* JsxAttribute */: + case 282 /* JsxAttributes */: + case 283 /* JsxSpreadAttribute */: + case 276 /* JsxOpeningElement */: + case 224 /* ExpressionWithTypeArguments */: + case 287 /* HeritageClause */: return false; default: return ts.isExpressionNode(node) ? false : "quit"; @@ -67980,7 +70168,10 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, missingProperty, container); + var diagnostic = containerSeemsToBeEmptyDomElement(containingType) + ? ts.Diagnostics.Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom + : ts.Diagnostics.Property_0_does_not_exist_on_type_1; + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), diagnostic, missingProperty, container); } } } @@ -67991,9 +70182,14 @@ var ts; } diagnostics.add(resultDiagnostic); } + function containerSeemsToBeEmptyDomElement(containingType) { + return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && + everyContainedType(containingType, function (type) { return type.symbol && /^(EventTarget|Node|((HTML[a-zA-Z]*)?Element))$/.test(ts.unescapeLeadingUnderscores(type.symbol.escapedName)); }) && + isEmptyObjectType(containingType); + } function typeHasStaticProperty(propName, containingType) { var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); - return prop !== undefined && prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */); + return prop !== undefined && !!prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedLibForNonExistentName(name) { var missingName = diagnosticName(name); @@ -68024,7 +70220,15 @@ var ts; } } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 111551 /* Value */); + var props = getPropertiesOfType(containingType); + if (typeof name !== "string") { + var parent_2 = name.parent; + if (ts.isPropertyAccessExpression(parent_2)) { + props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_2, containingType, prop); }); + } + name = ts.idText(name); + } + return getSpellingSuggestionForName(name, props, 111551 /* Value */); } function getSuggestedSymbolForNonexistentJSXAttribute(name, containingType) { var strName = ts.isString(name) ? name : ts.idText(name); @@ -68119,20 +70323,20 @@ var ts; return undefined; } } - function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isSelfTypeAccess) { var valueDeclaration = prop && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration; if (!valueDeclaration) { return; } var hasPrivateModifier = ts.hasEffectiveModifier(valueDeclaration, 8 /* Private */); - var hasPrivateIdentifier = ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name); + var hasPrivateIdentifier = prop.valueDeclaration && ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name); if (!hasPrivateModifier && !hasPrivateIdentifier) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) { return; } - if (isThisAccess) { + if (isSelfTypeAccess) { // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); if (containingMethod && containingMethod.symbol === prop) { @@ -68141,18 +70345,22 @@ var ts; } (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */; } + function isSelfTypeAccess(name, parent) { + return name.kind === 107 /* ThisKeyword */ + || !!parent && ts.isEntityNameExpression(name) && parent === getResolvedSymbol(ts.getFirstIdentifier(name)); + } function isValidPropertyAccess(node, propertyName) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return isValidPropertyAccessWithType(node, node.expression.kind === 105 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); - case 195 /* ImportType */: + case 196 /* ImportType */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind === 201 /* PropertyAccessExpression */ && node.expression.kind === 105 /* SuperKeyword */, property.escapedName, type); + return isValidPropertyAccessWithType(node, node.kind === 202 /* PropertyAccessExpression */ && node.expression.kind === 105 /* SuperKeyword */, property.escapedName, type); // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context. } function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { @@ -68161,11 +70369,11 @@ var ts; } var prop = getPropertyOfType(type, propertyName); if (prop) { - if (ts.isPropertyAccessExpression(node) && prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)) { + if (prop.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration)) { var declClass_1 = ts.getContainingClass(prop.valueDeclaration); return !ts.isOptionalChain(node) && !!ts.findAncestor(node, function (parent) { return parent === declClass_1; }); } - return checkPropertyAccessibility(node, isSuper, type, prop); + return checkPropertyAccessibility(node, isSuper, /*writing*/ false, type, prop, /* reportError */ false); } // In js files properties of unions are allowed in completion return ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); @@ -68175,7 +70383,7 @@ var ts; */ function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 250 /* VariableDeclarationList */) { + if (initializer.kind === 251 /* VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); @@ -68204,7 +70412,7 @@ var ts; var child = expr; var node = expr.parent; while (node) { - if (node.kind === 238 /* ForInStatement */ && + if (node.kind === 239 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -68217,16 +70425,16 @@ var ts; } return false; } - function checkIndexedAccess(node) { - return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) : - checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + function checkIndexedAccess(node, checkMode) { + return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node, checkMode) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression), checkMode); } - function checkElementAccessChain(node) { + function checkElementAccessChain(node, checkMode) { var exprType = checkExpression(node.expression); var nonOptionalType = getOptionalExpressionType(exprType, node.expression); - return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression), checkMode), node, nonOptionalType !== exprType); } - function checkElementAccessExpression(node, exprType) { + function checkElementAccessExpression(node, exprType, checkMode) { var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; var indexExpression = node.argumentExpression; var indexType = checkExpression(indexExpression); @@ -68242,42 +70450,7 @@ var ts; 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) : 0 /* None */; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, /*noUncheckedIndexedAccessCandidate*/ undefined, node, accessFlags | 16 /* ExpressionPosition */) || errorType; - return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); - } - function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { - if (expressionType === errorType) { - // There is already an error, so no need to report one. - return false; - } - if (!ts.isWellKnownSymbolSyntactically(expression)) { - return false; - } - // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) { - if (reportError) { - error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); - } - return false; - } - // The name is Symbol., so make sure Symbol actually resolves to the - // global Symbol object - var leftHandSide = expression.expression; - var leftHandSideSymbol = getResolvedSymbol(leftHandSide); - if (!leftHandSideSymbol) { - return false; - } - var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true); - if (!globalESSymbol) { - // Already errored when we tried to look up the symbol - return false; - } - if (leftHandSideSymbol !== globalESSymbol) { - if (reportError) { - error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); - } - return false; - } - return true; + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, getNodeLinks(node).resolvedSymbol, indexedAccessType, indexExpression, checkMode), node); } function callLikeExpressionMayHaveTypeArguments(node) { return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node); @@ -68288,13 +70461,13 @@ var ts; // This gets us diagnostics for the type arguments and marks them as referenced. ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 205 /* TaggedTemplateExpression */) { + if (node.kind === 206 /* TaggedTemplateExpression */) { checkExpression(node.template); } else if (ts.isJsxOpeningLikeElement(node)) { checkExpression(node.attributes); } - else if (node.kind !== 161 /* Decorator */) { + else if (node.kind !== 162 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -68358,7 +70531,7 @@ var ts; } } function isSpreadArgument(arg) { - return !!arg && (arg.kind === 220 /* SpreadElement */ || arg.kind === 227 /* SyntheticExpression */ && arg.isSpread); + return !!arg && (arg.kind === 221 /* SpreadElement */ || arg.kind === 228 /* SyntheticExpression */ && arg.isSpread); } function getSpreadArgumentIndex(args) { return ts.findIndex(args, isSpreadArgument); @@ -68375,9 +70548,9 @@ var ts; var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments var effectiveParameterCount = getParameterCount(signature); var effectiveMinimumArguments = getMinArgumentCount(signature); - if (node.kind === 205 /* TaggedTemplateExpression */) { + if (node.kind === 206 /* TaggedTemplateExpression */) { argCount = args.length; - if (node.template.kind === 218 /* TemplateExpression */) { + if (node.template.kind === 219 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. @@ -68392,7 +70565,7 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 161 /* Decorator */) { + else if (node.kind === 162 /* Decorator */) { argCount = getDecoratorArgumentCount(node, signature); } else if (ts.isJsxOpeningLikeElement(node)) { @@ -68406,7 +70579,7 @@ var ts; } else if (!node.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(node.kind === 204 /* NewExpression */); + ts.Debug.assert(node.kind === 205 /* NewExpression */); return getMinArgumentCount(signature) === 0; } else { @@ -68481,7 +70654,7 @@ var ts; }); if (!inferenceContext) { applyToReturnTypes(contextualSignature, signature, function (source, target) { - inferTypes(context.inferences, source, target, 64 /* ReturnType */); + inferTypes(context.inferences, source, target, 128 /* ReturnType */); }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); @@ -68492,6 +70665,15 @@ var ts; inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } + function getThisArgumentType(thisArgumentNode) { + if (!thisArgumentNode) { + return voidType; + } + var thisArgumentType = checkExpression(thisArgumentNode); + return ts.isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) : + ts.isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) : + thisArgumentType; + } function inferTypeArguments(node, signature, args, checkMode, context) { if (ts.isJsxOpeningLikeElement(node)) { return inferJsxTypeArguments(node, signature, checkMode, context); @@ -68500,7 +70682,7 @@ var ts; // 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 // return type of 'wrap'. - if (node.kind !== 161 /* Decorator */) { + if (node.kind !== 162 /* Decorator */) { var contextualType = getContextualType(node, ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }) ? 8 /* SkipBindingPatterns */ : 0 /* None */); if (contextualType) { // We clone the inference context to avoid disturbing a resolution in progress for an @@ -68522,7 +70704,7 @@ var ts; instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 64 /* ReturnType */); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* ReturnType */); // Create a type mapper for instantiating generic contextual types using the inferences made // from the return type. We need a separate inference pass here because (a) instantiation of // the source type uses the outer context's return mapper (which excludes inferences made from @@ -68544,12 +70726,11 @@ var ts; var thisType = getThisTypeOfSignature(signature); if (thisType) { var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context.inferences, thisArgumentType, thisType); + inferTypes(context.inferences, getThisArgumentType(thisArgumentNode), thisType); } for (var i = 0; i < argCount; i++) { var arg = args[i]; - if (arg.kind !== 222 /* OmittedExpression */) { + if (arg.kind !== 223 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode); inferTypes(context.inferences, argType, paramType); @@ -68573,7 +70754,7 @@ var ts; 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 getMutableArrayOrTupleType(arg.kind === 227 /* SyntheticExpression */ ? arg.type : + return getMutableArrayOrTupleType(arg.kind === 228 /* SyntheticExpression */ ? arg.type : checkExpressionWithContextualType(arg.expression, restType, context, checkMode)); } } @@ -68583,13 +70764,13 @@ var ts; for (var i = index; i < argCount; i++) { var arg = args[i]; if (isSpreadArgument(arg)) { - var spreadType = arg.kind === 227 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression); + var spreadType = arg.kind === 228 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression); if (isArrayLikeType(spreadType)) { types.push(spreadType); flags.push(8 /* Variadic */); } else { - types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 220 /* SpreadElement */ ? arg.expression : arg)); + types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 221 /* SpreadElement */ ? arg.expression : arg)); flags.push(4 /* Rest */); } } @@ -68600,7 +70781,7 @@ var ts; types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); flags.push(1 /* Required */); } - if (arg.kind === 227 /* SyntheticExpression */ && arg.tupleNameSource) { + if (arg.kind === 228 /* SyntheticExpression */ && arg.tupleNameSource) { names.push(arg.tupleNameSource); } } @@ -68744,24 +70925,12 @@ var ts; return undefined; } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 204 /* NewExpression */) { + if (thisType && thisType !== voidType && node.kind !== 205 /* NewExpression */) { // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = void 0; - if (thisArgumentNode) { - thisArgumentType = checkExpression(thisArgumentNode); - if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { - thisArgumentType = getNonNullableType(thisArgumentType); - } - else if (ts.isOptionalChain(thisArgumentNode.parent)) { - thisArgumentType = removeOptionalTypeMarker(thisArgumentType); - } - } - else { - thisArgumentType = voidType; - } + var thisArgumentType = getThisArgumentType(thisArgumentNode); var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -68774,7 +70943,7 @@ var ts; var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { var arg = args[i]; - if (arg.kind !== 222 /* OmittedExpression */) { + if (arg.kind !== 223 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode); // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive), @@ -68819,7 +70988,7 @@ var ts; * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. */ function getThisArgumentOfCall(node) { - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { var callee = ts.skipOuterExpressions(node.expression); if (ts.isAccessExpression(callee)) { return callee.expression; @@ -68836,17 +71005,17 @@ var ts; * Returns the effective arguments for an expression that works like a function invocation. */ function getEffectiveCallArguments(node) { - if (node.kind === 205 /* TaggedTemplateExpression */) { + if (node.kind === 206 /* TaggedTemplateExpression */) { var template = node.template; var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; - if (template.kind === 218 /* TemplateExpression */) { + if (template.kind === 219 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_3.push(span.expression); }); } return args_3; } - if (node.kind === 161 /* Decorator */) { + if (node.kind === 162 /* Decorator */) { return getEffectiveDecoratorArguments(node); } if (ts.isJsxOpeningLikeElement(node)) { @@ -68857,10 +71026,10 @@ var ts; if (spreadIndex >= 0) { // Create synthetic arguments from spreads of tuple types. var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_20 = function (i) { + var _loop_21 = function (i) { var arg = args[i]; // We can call checkExpressionCached because spread expressions never have a contextual type. - var spreadType = arg.kind === 220 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); + var spreadType = arg.kind === 221 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); if (spreadType && isTupleType(spreadType)) { ts.forEach(getTypeArguments(spreadType), function (t, i) { var _a; @@ -68874,7 +71043,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_20(i); + _loop_21(i); } return effectiveArgs_1; } @@ -68887,30 +71056,30 @@ var ts; var parent = node.parent; var expr = node.expression; switch (parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* 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 160 /* Parameter */: + case 161 /* 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 === 166 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, parent.parent.kind === 167 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), createSyntheticExpression(expr, anyType), createSyntheticExpression(expr, numberType) ]; - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* 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 !== 163 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + var hasPropDesc = parent.kind !== 164 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; return [ createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), @@ -68924,17 +71093,17 @@ var ts; */ function getDecoratorArgumentCount(node, signature) { switch (node.parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return 1; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return 2; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* 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 160 /* Parameter */: + case 161 /* Parameter */: return 3; default: return ts.Debug.fail(); @@ -68980,77 +71149,66 @@ var ts; return constructorSymbol === globalPromiseSymbol; } function getArgumentArityError(node, signatures, args) { - var min = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - var belowArgCount = Number.NEGATIVE_INFINITY; - var aboveArgCount = Number.POSITIVE_INFINITY; - var argCount = args.length; + var _a; + var spreadIndex = getSpreadArgumentIndex(args); + if (spreadIndex > -1) { + return ts.createDiagnosticForNode(args[spreadIndex], ts.Diagnostics.A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter); + } + var min = Number.POSITIVE_INFINITY; // smallest parameter count + var max = Number.NEGATIVE_INFINITY; // largest parameter count + var maxBelow = Number.NEGATIVE_INFINITY; // largest parameter count that is smaller than the number of arguments + var minAbove = Number.POSITIVE_INFINITY; // smallest parameter count that is larger than the number of arguments var closestSignature; for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { var sig = signatures_8[_i]; - var minCount = getMinArgumentCount(sig); - var maxCount = getParameterCount(sig); - if (minCount < argCount && minCount > belowArgCount) - belowArgCount = minCount; - if (argCount < maxCount && maxCount < aboveArgCount) - aboveArgCount = maxCount; - if (minCount < min) { - min = minCount; + var minParameter = getMinArgumentCount(sig); + var maxParameter = getParameterCount(sig); + // smallest/largest parameter counts + if (minParameter < min) { + min = minParameter; closestSignature = sig; } - max = Math.max(max, maxCount); + max = Math.max(max, maxParameter); + // shortest parameter count *longer than the call*/longest parameter count *shorter than the call* + if (minParameter < args.length && minParameter > maxBelow) + maxBelow = minParameter; + if (args.length < maxParameter && maxParameter < minAbove) + minAbove = maxParameter; } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); - var paramRange = hasRestParameter ? min : - min < max ? min + "-" + max : - min; - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var spanArray; - var related; - var error = hasRestParameter || hasSpreadArgument ? - hasRestParameter && hasSpreadArgument ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - paramRange === 1 && argCount === 0 && isPromiseResolveArityError(node) ? - ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : - ts.Diagnostics.Expected_0_arguments_but_got_1; - if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { - var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; - if (paramDecl) { - related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : - ts.isRestParameter(paramDecl) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined); - } - } - if (min < argCount && argCount < max) { - return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); - } - if (!hasSpreadArgument && argCount < min) { - var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1; - } - if (hasRestParameter || hasSpreadArgument) { - spanArray = ts.factory.createNodeArray(args); - if (hasSpreadArgument && argCount) { - var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined; - spanArray = ts.factory.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1))); + var parameterRange = hasRestParameter ? min + : min < max ? min + "-" + max + : min; + var error = hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 + : parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node) ? ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise + : ts.Diagnostics.Expected_0_arguments_but_got_1; + if (min < args.length && args.length < max) { + // between min and max, but with no matching overload + return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove); + } + else if (args.length < min) { + // too short: put the error span on the call expression, not any of the args + var diagnostic = getDiagnosticForCallNode(node, error, parameterRange, args.length); + var parameter = (_a = closestSignature === null || closestSignature === void 0 ? void 0 : closestSignature.declaration) === null || _a === void 0 ? void 0 : _a.parameters[closestSignature.thisParameter ? args.length + 1 : args.length]; + if (parameter) { + var parameterError = ts.createDiagnosticForNode(parameter, ts.isBindingPattern(parameter.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided + : ts.isRestParameter(parameter) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided + : ts.Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : !ts.isBindingPattern(parameter.name) ? ts.idText(ts.getFirstIdentifier(parameter.name)) : undefined); + return ts.addRelatedInfo(diagnostic, parameterError); } + return diagnostic; } else { - spanArray = ts.factory.createNodeArray(args.slice(max)); - } - var pos = ts.first(spanArray).pos; - var end = ts.last(spanArray).end; - if (end === pos) { - end++; + // too long; error goes on the excess parameters + var errorSpan = ts.factory.createNodeArray(args.slice(max)); + var pos = ts.first(errorSpan).pos; + var end = ts.last(errorSpan).end; + if (end === pos) { + end++; + } + ts.setTextRangePosEnd(errorSpan, pos, end); + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), errorSpan, error, parameterRange, args.length); } - ts.setTextRangePosEnd(spanArray, pos, end); - var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var argCount = typeArguments.length; @@ -69081,8 +71239,8 @@ var ts; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) { - var isTaggedTemplate = node.kind === 205 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 161 /* Decorator */; + var isTaggedTemplate = node.kind === 206 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 162 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var reportErrors = !candidatesOutArray && produceDiagnostics; var typeArguments; @@ -69144,7 +71302,7 @@ var ts; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 203 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 204 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -69198,7 +71356,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_21 = function (c) { + var _loop_22 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2); if (diags_2) { @@ -69216,7 +71374,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_21(c); + _loop_22(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); @@ -69374,7 +71532,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_22 = function (i) { + var _loop_23 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -69382,7 +71540,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_22(i); + _loop_23(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* None */; @@ -69574,7 +71732,7 @@ var ts; function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have no common signatures. return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) || - !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & 1048576 /* Union */) && !(getReducedType(apparentFuncType).flags & 131072 /* Never */) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray, checkMode) { if (node.arguments && languageVersion < 1 /* ES5 */) { @@ -69689,7 +71847,7 @@ var ts; var declaration = signature.declaration; var modifiers = ts.getSelectedEffectiveModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */); // (1) Public constructors and (2) constructor functions are always accessible. - if (!modifiers || declaration.kind !== 166 /* Constructor */) { + if (!modifiers || declaration.kind !== 167 /* Constructor */) { return true; } var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol); @@ -69833,16 +71991,16 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 160 /* Parameter */: + case 161 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; default: return ts.Debug.fail(); @@ -69937,16 +72095,16 @@ var ts; } function resolveSignature(node, candidatesOutArray, checkMode) { switch (node.kind) { - case 203 /* CallExpression */: + case 204 /* CallExpression */: return resolveCallExpression(node, candidatesOutArray, checkMode); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return resolveNewExpression(node, candidatesOutArray, checkMode); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode); - case 161 /* Decorator */: + case 162 /* Decorator */: return resolveDecorator(node, candidatesOutArray, checkMode); - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode); } throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); @@ -70078,7 +72236,7 @@ var ts; return false; } var parent = node.parent; - while (parent && parent.kind === 201 /* PropertyAccessExpression */) { + while (parent && parent.kind === 202 /* PropertyAccessExpression */) { parent = parent.parent; } if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 62 /* EqualsToken */) { @@ -70105,12 +72263,12 @@ var ts; if (node.expression.kind === 105 /* SuperKeyword */) { return voidType; } - if (node.kind === 204 /* NewExpression */) { + if (node.kind === 205 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 166 /* Constructor */ && - declaration.kind !== 170 /* ConstructSignature */ && - declaration.kind !== 175 /* ConstructorType */ && + declaration.kind !== 167 /* Constructor */ && + declaration.kind !== 171 /* ConstructSignature */ && + declaration.kind !== 176 /* ConstructorType */ && !ts.isJSDocConstructSignature(declaration) && !isJSConstructor(declaration)) { // When resolved signature is a call signature (and not a construct signature) the result type is any @@ -70130,7 +72288,7 @@ var ts; if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } - if (node.kind === 203 /* CallExpression */ && node.parent.kind === 233 /* ExpressionStatement */ && + if (node.kind === 204 /* CallExpression */ && !node.questionDotToken && node.parent.kind === 234 /* ExpressionStatement */ && returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) { if (!ts.isDottedName(node.expression)) { error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name); @@ -70144,7 +72302,7 @@ var ts; var jsSymbol = getSymbolOfExpando(node, /*allowDeclaration*/ false); if ((_a = jsSymbol === null || jsSymbol === void 0 ? void 0 : jsSymbol.exports) === null || _a === void 0 ? void 0 : _a.size) { var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; + jsAssignmentType.objectFlags |= 8192 /* JSLiteral */; return getIntersectionType([returnType, jsAssignmentType]); } } @@ -70153,26 +72311,27 @@ var ts; function checkDeprecatedSignature(signature, node) { if (signature.declaration && signature.declaration.flags & 134217728 /* Deprecated */) { var suggestionNode = getDeprecatedSuggestionNode(node); - errorOrSuggestion(/*isError*/ false, suggestionNode, ts.Diagnostics._0_is_deprecated, signatureToString(signature)); + var name = ts.tryGetPropertyAccessOrIdentifierToString(ts.getInvokedExpression(node)); + addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature)); } } function getDeprecatedSuggestionNode(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 203 /* CallExpression */: - case 161 /* Decorator */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 162 /* Decorator */: + case 205 /* NewExpression */: return getDeprecatedSuggestionNode(node.expression); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return getDeprecatedSuggestionNode(node.tag); - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return getDeprecatedSuggestionNode(node.tagName); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return node.argumentExpression; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return node.name; - case 173 /* TypeReference */: + case 174 /* TypeReference */: var typeReference = node; return ts.isQualifiedName(typeReference.typeName) ? typeReference.typeName.right : typeReference; default: @@ -70223,10 +72382,11 @@ var ts; return createPromiseReturnType(node, anyType); } function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { + var _a; if (allowSyntheticDefaultImports && type && type !== errorType) { var synthType = type; if (!synthType.syntheticType) { - var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var file = (_a = originalSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); @@ -70264,9 +72424,9 @@ var ts; return false; } var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ - ? 251 /* FunctionDeclaration */ + ? 252 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ - ? 249 /* VariableDeclaration */ + ? 250 /* VariableDeclaration */ : 0 /* Unknown */; if (targetDeclarationKind !== 0 /* Unknown */) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); @@ -70296,19 +72456,19 @@ var ts; case 9 /* BigIntLiteral */: case 109 /* TrueKeyword */: case 94 /* FalseKeyword */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 218 /* TemplateExpression */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 219 /* TemplateExpression */: return true; - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isValidConstAssertionArgument(node.expression); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: var op = node.operator; var arg = node.operand; return op === 40 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) || op === 39 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: var expr = node.expression; if (ts.isIdentifier(expr)) { var symbol = getSymbolAtLocation(expr); @@ -70364,7 +72524,7 @@ var ts; error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return errorType; } - else if (container.kind === 166 /* Constructor */) { + else if (container.kind === 167 /* Constructor */) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -70411,7 +72571,7 @@ var ts; return restParameter.escapedName; } function isValidDeclarationForTupleLabel(d) { - return d.kind === 192 /* NamedTupleMember */ || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name)); + return d.kind === 193 /* NamedTupleMember */ || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name)); } function getNameableDeclarationAtPosition(signature, pos) { var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); @@ -70576,7 +72736,14 @@ var ts; } } function assignContextualParameterTypes(signature, context) { - signature.typeParameters = context.typeParameters; + if (context.typeParameters) { + if (!signature.typeParameters) { + signature.typeParameters = context.typeParameters; + } + else { + return; // This signature has already has a contextual inference performed and cached on it! + } + } if (context.thisParameter) { var parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { @@ -70687,7 +72854,7 @@ var ts; var yieldType; var nextType; var fallbackReturnType = voidType; - if (func.body.kind !== 230 /* Block */) { // Async or normal arrow function + if (func.body.kind !== 231 /* Block */) { // Async or normal arrow function returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */); if (isAsync) { // From within an async function you can return either a non-promise value or a promise. Any @@ -70872,7 +73039,7 @@ var ts; return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node)); } function computeExhaustiveSwitchStatement(node) { - if (node.expression.kind === 211 /* TypeOfExpression */) { + if (node.expression.kind === 212 /* TypeOfExpression */) { var operandType = getTypeOfExpression(node.expression.expression); var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); // notEqualFacts states that the type of the switched value is not equal to every type in the switch. @@ -70935,11 +73102,11 @@ var ts; } function mayReturnNever(func) { switch (func.kind) { - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; - case 165 /* MethodDeclaration */: - return func.parent.kind === 200 /* ObjectLiteralExpression */; + case 166 /* MethodDeclaration */: + return func.parent.kind === 201 /* ObjectLiteralExpression */; default: return false; } @@ -70965,21 +73132,21 @@ var ts; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (func.kind === 164 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 230 /* Block */ || !functionHasImplicitReturn(func)) { + if (func.kind === 165 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 231 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */; + var errorNode = ts.getEffectiveReturnTypeNode(func) || func; if (type && type.flags & 131072 /* Never */) { - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + error(errorNode, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (type && !hasExplicitReturn) { // minimal check: function has syntactic return type annotation and no explicit return statements in the body // this function does not conform to the specification. - // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + error(errorNode, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) { - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + error(errorNode, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); } else if (compilerOptions.noImplicitReturns) { if (!type) { @@ -70994,11 +73161,11 @@ var ts; return; } } - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + error(errorNode, ts.Diagnostics.Not_all_code_paths_return_a_value); } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) { @@ -71014,7 +73181,7 @@ var ts; var returnType = getReturnTypeFromBody(node, checkMode); var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); - returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */; + returnOnlyType.objectFlags |= 524288 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; } } @@ -71022,7 +73189,7 @@ var ts; } // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 208 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 209 /* FunctionExpression */) { checkGrammarForGenerator(node); } contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -71068,7 +73235,7 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnType = getReturnTypeFromAnnotation(node); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); @@ -71081,7 +73248,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 230 /* Block */) { + if (node.body.kind === 231 /* Block */) { checkSourceElement(node.body); } else { @@ -71171,7 +73338,7 @@ var ts; expr.expression.kind === 107 /* ThisKeyword */) { // Look for if this is the constructor for the class that `symbol` is a property of. var ctor = ts.getContainingFunction(expr); - if (!(ctor && (ctor.kind === 166 /* Constructor */ || isJSConstructor(ctor)))) { + if (!(ctor && (ctor.kind === 167 /* Constructor */ || isJSConstructor(ctor)))) { return true; } if (symbol.valueDeclaration) { @@ -71196,7 +73363,7 @@ var ts; var symbol_2 = getNodeLinks(node).resolvedSymbol; if (symbol_2.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol_2); - return !!declaration && declaration.kind === 263 /* NamespaceImport */; + return !!declaration && declaration.kind === 264 /* NamespaceImport */; } } } @@ -71277,7 +73444,7 @@ var ts; var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); var func = ts.getContainingFunction(node); - if (func && func.kind !== 166 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { + if (func && func.kind !== 167 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); ts.addRelatedInfo(diagnostic, relatedInfo); } @@ -71444,14 +73611,33 @@ var ts; rightType = checkNonNullType(rightType, right); // TypeScript 1.0 spec (April 2014): 4.15.5 // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, - // and the right operand to be of type Any, an object type, or a type parameter type. + // and the right operand to be + // + // 1. assignable to the non-primitive type, + // 2. an unconstrained type parameter, + // 3. a union or intersection including one or more type parameters, whose constituents are all assignable to the + // the non-primitive type, or are unconstrainted type parameters, or have constraints assignable to the + // non-primitive type, or + // 4. a type parameter whose constraint is + // i. an object type, + // ii. the non-primitive type, or + // iii. a union or intersection with at least one constituent assignable to an object or non-primitive type. + // + // The divergent behavior for type parameters and unions containing type parameters is a workaround for type + // parameters not being narrowable. If the right operand is a concrete type, we can error if there is any chance + // it is a primitive. But if the operand is a type parameter, it cannot be narrowed, so we don't issue an error + // unless *all* instantiations would result in an error. + // // The result is always of the Boolean primitive type. if (!(allTypesAssignableToKind(leftType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) || isTypeAssignableToKind(leftType, 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */ | 262144 /* TypeParameter */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { - error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + var rightTypeConstraint = getConstraintOfType(rightType); + if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */) || + rightTypeConstraint && (isTypeAssignableToKind(rightType, 3145728 /* UnionOrIntersection */) && !allTypesAssignableToKind(rightTypeConstraint, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */) || + !maybeTypeOfKind(rightTypeConstraint, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */))) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_not_be_a_primitive); } return booleanType; } @@ -71470,7 +73656,7 @@ var ts; if (rightIsThis === void 0) { rightIsThis = false; } var properties = node.properties; var property = properties[propertyIndex]; - if (property.kind === 288 /* PropertyAssignment */ || property.kind === 289 /* ShorthandPropertyAssignment */) { + if (property.kind === 289 /* PropertyAssignment */ || property.kind === 290 /* ShorthandPropertyAssignment */) { var name = property.name; var exprType = getLiteralTypeFromPropertyName(name); if (isTypeUsableAsPropertyName(exprType)) { @@ -71478,14 +73664,14 @@ var ts; var prop = getPropertyOfType(objectLiteralType, text); if (prop) { markPropertyAsReferenced(prop, property, rightIsThis); - checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + checkPropertyAccessibility(property, /*isSuper*/ false, /*writing*/ true, objectLiteralType, prop); } } var elementType = getIndexedAccessType(objectLiteralType, exprType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */); var type = getFlowTypeOfDestructuring(property, elementType); - return checkDestructuringAssignment(property.kind === 289 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); + return checkDestructuringAssignment(property.kind === 290 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } - else if (property.kind === 290 /* SpreadAssignment */) { + else if (property.kind === 291 /* SpreadAssignment */) { if (propertyIndex < properties.length - 1) { error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } @@ -71523,7 +73709,7 @@ var ts; var inBoundsType = compilerOptions.noUncheckedIndexedAccess ? undefined : possiblyOutOfBoundsType; for (var i = 0; i < elements.length; i++) { var type = possiblyOutOfBoundsType; - if (node.elements[i].kind === 220 /* SpreadElement */) { + if (node.elements[i].kind === 221 /* SpreadElement */) { type = inBoundsType = inBoundsType !== null && inBoundsType !== void 0 ? inBoundsType : (checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType); } checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, type, checkMode); @@ -71533,8 +73719,8 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 222 /* OmittedExpression */) { - if (element.kind !== 220 /* SpreadElement */) { + if (element.kind !== 223 /* OmittedExpression */) { + if (element.kind !== 221 /* SpreadElement */) { var indexType = getLiteralType(elementIndex); if (isArrayLikeType(sourceType)) { // We create a synthetic expression so that getIndexedAccessType doesn't get confused @@ -71552,7 +73738,7 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 216 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) { + if (restExpression.kind === 217 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -71568,7 +73754,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; - if (exprOrAssignment.kind === 289 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 290 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove @@ -71584,24 +73770,24 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 216 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) { + if (target.kind === 217 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 200 /* ObjectLiteralExpression */) { + if (target.kind === 201 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } - if (target.kind === 199 /* ArrayLiteralExpression */) { + if (target.kind === 200 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 290 /* SpreadAssignment */ ? + var error = target.parent.kind === 291 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; - var optionalError = target.parent.kind === 290 /* SpreadAssignment */ ? + var optionalError = target.parent.kind === 291 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access; if (checkReferenceExpression(target, error, optionalError)) { @@ -71626,8 +73812,8 @@ var ts; case 78 /* Identifier */: case 10 /* StringLiteral */: case 13 /* RegularExpressionLiteral */: - case 205 /* TaggedTemplateExpression */: - case 218 /* TemplateExpression */: + case 206 /* TaggedTemplateExpression */: + case 219 /* TemplateExpression */: case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: case 9 /* BigIntLiteral */: @@ -71635,27 +73821,27 @@ var ts; case 94 /* FalseKeyword */: case 103 /* NullKeyword */: case 150 /* UndefinedKeyword */: - case 208 /* FunctionExpression */: - case 221 /* ClassExpression */: - case 209 /* ArrowFunction */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 211 /* TypeOfExpression */: - case 225 /* NonNullExpression */: - case 274 /* JsxSelfClosingElement */: - case 273 /* JsxElement */: + case 209 /* FunctionExpression */: + case 222 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 212 /* TypeOfExpression */: + case 226 /* NonNullExpression */: + case 275 /* JsxSelfClosingElement */: + case 274 /* JsxElement */: return true; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: // Unary operators ~, !, +, and - have no side effects. // The rest do. switch (node.operator) { @@ -71667,9 +73853,9 @@ var ts; } return false; // Some forms listed here for clarity - case 212 /* VoidExpression */: // Explicit opt-out - case 206 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 224 /* AsExpression */: // Not SEF, but can produce useful type warnings + case 213 /* VoidExpression */: // Explicit opt-out + case 207 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 225 /* AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } @@ -71677,84 +73863,111 @@ var ts; function isTypeEqualityComparableTo(source, target) { return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } - var CheckBinaryExpressionState; - (function (CheckBinaryExpressionState) { - CheckBinaryExpressionState[CheckBinaryExpressionState["MaybeCheckLeft"] = 0] = "MaybeCheckLeft"; - CheckBinaryExpressionState[CheckBinaryExpressionState["CheckRight"] = 1] = "CheckRight"; - CheckBinaryExpressionState[CheckBinaryExpressionState["FinishCheck"] = 2] = "FinishCheck"; - })(CheckBinaryExpressionState || (CheckBinaryExpressionState = {})); - function checkBinaryExpression(node, checkMode) { - var workStacks = { - expr: [node], - state: [0 /* MaybeCheckLeft */], - leftType: [undefined] + function createCheckBinaryExpression() { + var trampoline = ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState); + return function (node, checkMode) { + var result = trampoline(node, checkMode); + ts.Debug.assertIsDefined(result); + return result; }; - var stackIndex = 0; - var lastResult; - while (stackIndex >= 0) { - node = workStacks.expr[stackIndex]; - switch (workStacks.state[stackIndex]) { - case 0 /* MaybeCheckLeft */: { - if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { - finishInvocation(checkExpression(node.right, checkMode)); - break; - } - checkGrammarNullishCoalesceWithLogicalExpression(node); - var operator = node.operatorToken.kind; - if (operator === 62 /* EqualsToken */ && (node.left.kind === 200 /* ObjectLiteralExpression */ || node.left.kind === 199 /* ArrayLiteralExpression */)) { - finishInvocation(checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 107 /* ThisKeyword */)); - break; - } - advanceState(1 /* CheckRight */); - maybeCheckExpression(node.left); - break; - } - case 1 /* CheckRight */: { - var leftType = lastResult; - workStacks.leftType[stackIndex] = leftType; - var operator = node.operatorToken.kind; - if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) { - if (operator === 55 /* AmpersandAmpersandToken */) { - var parent = ts.walkUpParenthesizedExpressions(node.parent); - checkTestingKnownTruthyCallableType(node.left, leftType, ts.isIfStatement(parent) ? parent.thenStatement : undefined); - } - checkTruthinessOfType(leftType, node.left); + function onEnter(node, state, checkMode) { + if (state) { + state.stackIndex++; + state.skip = false; + setLeftType(state, /*type*/ undefined); + setLastResult(state, /*type*/ undefined); + } + else { + state = { + checkMode: checkMode, + skip: false, + stackIndex: 0, + typeStack: [undefined, undefined], + }; + } + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { + state.skip = true; + setLastResult(state, checkExpression(node.right, checkMode)); + return state; + } + checkGrammarNullishCoalesceWithLogicalExpression(node); + var operator = node.operatorToken.kind; + if (operator === 62 /* EqualsToken */ && (node.left.kind === 201 /* ObjectLiteralExpression */ || node.left.kind === 200 /* ArrayLiteralExpression */)) { + state.skip = true; + setLastResult(state, checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 107 /* ThisKeyword */)); + return state; + } + return state; + } + function onLeft(left, state, _node) { + if (!state.skip) { + return maybeCheckExpression(state, left); + } + } + function onOperator(operatorToken, state, node) { + if (!state.skip) { + var leftType = getLastResult(state); + ts.Debug.assertIsDefined(leftType); + setLeftType(state, leftType); + setLastResult(state, /*type*/ undefined); + var operator = operatorToken.kind; + if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) { + if (operator === 55 /* AmpersandAmpersandToken */) { + var parent = ts.walkUpParenthesizedExpressions(node.parent); + checkTestingKnownTruthyCallableOrAwaitableType(node.left, leftType, ts.isIfStatement(parent) ? parent.thenStatement : undefined); } - advanceState(2 /* FinishCheck */); - maybeCheckExpression(node.right); - break; - } - case 2 /* FinishCheck */: { - var leftType = workStacks.leftType[stackIndex]; - var rightType = lastResult; - finishInvocation(checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node)); - break; + checkTruthinessOfType(leftType, node.left); } - default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for checkBinaryExpression"); } } - return lastResult; - function finishInvocation(result) { - lastResult = result; - stackIndex--; - } - /** - * Note that `advanceState` sets the _current_ head state, and that `maybeCheckExpression` potentially pushes on a new - * head state; so `advanceState` must be called before any `maybeCheckExpression` during a state's execution. - */ - function advanceState(nextState) { - workStacks.state[stackIndex] = nextState; + function onRight(right, state, _node) { + if (!state.skip) { + return maybeCheckExpression(state, right); + } } - function maybeCheckExpression(node) { - if (ts.isBinaryExpression(node)) { - stackIndex++; - workStacks.expr[stackIndex] = node; - workStacks.state[stackIndex] = 0 /* MaybeCheckLeft */; - workStacks.leftType[stackIndex] = undefined; + function onExit(node, state) { + var result; + if (state.skip) { + result = getLastResult(state); } else { - lastResult = checkExpression(node, checkMode); + var leftType = getLeftType(state); + ts.Debug.assertIsDefined(leftType); + var rightType = getLastResult(state); + ts.Debug.assertIsDefined(rightType); + result = checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node); + } + state.skip = false; + setLeftType(state, /*type*/ undefined); + setLastResult(state, /*type*/ undefined); + state.stackIndex--; + return result; + } + function foldState(state, result, _side) { + setLastResult(state, result); + return state; + } + function maybeCheckExpression(state, node) { + if (ts.isBinaryExpression(node)) { + return node; } + setLastResult(state, checkExpression(node, state.checkMode)); + } + function getLeftType(state) { + return state.typeStack[state.stackIndex]; + } + function setLeftType(state, type) { + state.typeStack[state.stackIndex] = type; + } + function getLastResult(state) { + return state.typeStack[state.stackIndex + 1]; + } + function setLastResult(state, type) { + // To reduce overhead, reuse the next stack entry to store the + // last result. This avoids the overhead of an additional property + // on `WorkArea` and reuses empty stack entries as we walk back up + // the stack. + state.typeStack[state.stackIndex + 1] = type; } } function checkGrammarNullishCoalesceWithLogicalExpression(node) { @@ -71772,7 +73985,7 @@ var ts; // expression-wide checks and does not use a work stack to fold nested binary expressions into the same callstack frame function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 62 /* EqualsToken */ && (left.kind === 200 /* ObjectLiteralExpression */ || left.kind === 199 /* ArrayLiteralExpression */)) { + if (operator === 62 /* EqualsToken */ && (left.kind === 201 /* ObjectLiteralExpression */ || left.kind === 200 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 107 /* ThisKeyword */); } var leftType; @@ -72007,7 +74220,7 @@ var ts; if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false); - if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { + if ((symbol === null || symbol === void 0 ? void 0 : symbol.declarations) && symbol.declarations.some(ts.isJSDocTypedefTag)) { addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop); addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol); } @@ -72202,7 +74415,7 @@ var ts; } function checkConditionalExpression(node, checkMode) { var type = checkTruthinessExpression(node.condition); - checkTestingKnownTruthyCallableType(node.condition, type, node.whenTrue); + checkTestingKnownTruthyCallableOrAwaitableType(node.condition, type, node.whenTrue); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); return getUnionType([type1, type2], 2 /* Subtype */); @@ -72219,10 +74432,14 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return getFreshTypeOfLiteralType(getTemplateLiteralType(texts, types)); + return isConstContext(node) || someType(getContextualType(node) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; + } + function isTemplateLiteralContextualType(type) { + return !!(type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */) || + type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 402653316 /* StringLike */)); } function getContextNode(node) { - if (node.kind === 281 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { + if (node.kind === 282 /* 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; @@ -72238,7 +74455,7 @@ var ts; // We strip literal freshness when an appropriate contextual type is present such that contextually typed // literals always preserve their literal types (otherwise they might widen during type inference). An alternative // here would be to not mark contextually typed literals as fresh in the first place. - var result = maybeTypeOfKind(type, 134220672 /* FreshableLiteral */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -72271,13 +74488,13 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 206 /* TypeAssertionExpression */ || node.kind === 224 /* AsExpression */; + return node.kind === 207 /* TypeAssertionExpression */ || node.kind === 225 /* AsExpression */; } function checkDeclarationInitializer(declaration, contextualType) { var initializer = ts.getEffectiveInitializer(declaration); var type = getQuickTypeOfExpression(initializer) || (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer)); - return ts.isParameter(declaration) && declaration.name.kind === 197 /* ArrayBindingPattern */ && + return ts.isParameter(declaration) && declaration.name.kind === 198 /* ArrayBindingPattern */ && isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ? padTupleType(type, declaration.name) : type; } @@ -72287,7 +74504,7 @@ var ts; var elementFlags = type.target.elementFlags.slice(); for (var i = getTypeReferenceArity(type); i < patternElements.length; i++) { var e = patternElements[i]; - if (i < patternElements.length - 1 || !(e.kind === 198 /* BindingElement */ && e.dotDotDotToken)) { + if (i < patternElements.length - 1 || !(e.kind === 199 /* BindingElement */ && e.dotDotDotToken)) { elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType); elementFlags.push(2 /* Optional */); if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) { @@ -72322,7 +74539,7 @@ var ts; // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || unknownType; - return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || @@ -72330,7 +74547,7 @@ var ts; } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return !!(contextualType.flags & (134217856 /* StringLikeLiteral */ | 4194304 /* Index */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || @@ -72354,7 +74571,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); @@ -72365,7 +74582,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -72583,7 +74800,7 @@ var ts; } } function checkExpression(node, checkMode, forceTuple) { - ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -72593,7 +74810,7 @@ var ts; checkConstEnumAccess(node, type); } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return type; } function checkConstEnumAccess(node, type) { @@ -72601,11 +74818,11 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 202 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 78 /* Identifier */ || node.kind === 157 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || - (node.parent.kind === 176 /* TypeQuery */ && node.parent.exprName === node)) || - (node.parent.kind === 270 /* ExportSpecifier */); // We allow reexporting const enums + var ok = (node.parent.kind === 202 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 203 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 78 /* Identifier */ || node.kind === 158 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 177 /* TypeQuery */ && node.parent.exprName === node)) || + (node.parent.kind === 271 /* ExportSpecifier */); // We allow reexporting const enums if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } @@ -72630,15 +74847,15 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { case 78 /* Identifier */: - return checkIdentifier(node); + return checkIdentifier(node, checkMode); case 107 /* ThisKeyword */: return checkThisExpression(node); case 105 /* SuperKeyword */: @@ -72658,78 +74875,78 @@ var ts; return trueType; case 94 /* FalseKeyword */: return falseType; - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return checkTemplateExpression(node); case 13 /* RegularExpressionLiteral */: return globalRegExpType; - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return checkArrayLiteral(node, checkMode, forceTuple); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); - case 201 /* PropertyAccessExpression */: - return checkPropertyAccessExpression(node); - case 157 /* QualifiedName */: - return checkQualifiedName(node); - case 202 /* ElementAccessExpression */: - return checkIndexedAccess(node); - case 203 /* CallExpression */: + case 202 /* PropertyAccessExpression */: + return checkPropertyAccessExpression(node, checkMode); + case 158 /* QualifiedName */: + return checkQualifiedName(node, checkMode); + case 203 /* ElementAccessExpression */: + return checkIndexedAccess(node, checkMode); + case 204 /* CallExpression */: if (node.expression.kind === 99 /* ImportKeyword */) { return checkImportCallExpression(node); } // falls through - case 204 /* NewExpression */: + case 205 /* NewExpression */: return checkCallExpression(node, checkMode); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return checkParenthesizedExpression(node, checkMode); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return checkClassExpression(node); - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return checkAssertion(node); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return checkNonNullAssertion(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return checkMetaProperty(node); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return checkDeleteExpression(node); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return checkVoidExpression(node); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return checkAwaitExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return checkBinaryExpression(node, checkMode); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return checkConditionalExpression(node, checkMode); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return checkSpreadExpression(node, checkMode); - case 222 /* OmittedExpression */: + case 223 /* OmittedExpression */: return undefinedWideningType; - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return checkYieldExpression(node); - case 227 /* SyntheticExpression */: + case 228 /* SyntheticExpression */: return checkSyntheticExpression(node); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return checkJsxExpression(node, checkMode); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return checkJsxElement(node, checkMode); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node, checkMode); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return checkJsxFragment(node); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return errorType; @@ -72765,11 +74982,11 @@ var ts; checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) { - if (!(func.kind === 166 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { + if (!(func.kind === 167 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } - if (func.kind === 166 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") { + if (func.kind === 167 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") { error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name); } } @@ -72780,13 +74997,13 @@ var ts; if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 166 /* Constructor */ || func.kind === 170 /* ConstructSignature */ || func.kind === 175 /* ConstructorType */) { + if (func.kind === 167 /* Constructor */ || func.kind === 171 /* ConstructSignature */ || func.kind === 176 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } - if (func.kind === 209 /* ArrowFunction */) { + if (func.kind === 210 /* ArrowFunction */) { error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); } - if (func.kind === 167 /* GetAccessor */ || func.kind === 168 /* SetAccessor */) { + if (func.kind === 168 /* GetAccessor */ || func.kind === 169 /* SetAccessor */) { error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters); } } @@ -72844,13 +75061,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 209 /* ArrowFunction */: - case 169 /* CallSignature */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 174 /* FunctionType */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 210 /* ArrowFunction */: + case 170 /* CallSignature */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 175 /* FunctionType */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: var parent = node.parent; if (node === parent.type) { return parent; @@ -72868,7 +75085,7 @@ var ts; error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 197 /* ArrayBindingPattern */ || name.kind === 196 /* ObjectBindingPattern */) { + else if (name.kind === 198 /* ArrayBindingPattern */ || name.kind === 197 /* ObjectBindingPattern */) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -72877,13 +75094,13 @@ var ts; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 171 /* IndexSignature */) { + if (node.kind === 172 /* IndexSignature */) { checkGrammarIndexSignature(node); } // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled - else if (node.kind === 174 /* FunctionType */ || node.kind === 251 /* FunctionDeclaration */ || node.kind === 175 /* ConstructorType */ || - node.kind === 169 /* CallSignature */ || node.kind === 166 /* Constructor */ || - node.kind === 170 /* ConstructSignature */) { + else if (node.kind === 175 /* FunctionType */ || node.kind === 252 /* FunctionDeclaration */ || node.kind === 176 /* ConstructorType */ || + node.kind === 170 /* CallSignature */ || node.kind === 167 /* Constructor */ || + node.kind === 171 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); @@ -72913,10 +75130,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 169 /* CallSignature */: + case 170 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -72946,7 +75163,7 @@ var ts; checkAsyncFunctionReturnType(node, returnTypeNode); } } - if (node.kind !== 171 /* IndexSignature */ && node.kind !== 308 /* JSDocFunctionType */) { + if (node.kind !== 172 /* IndexSignature */ && node.kind !== 309 /* JSDocFunctionType */) { registerForUnusedIdentifiersCheck(node); } } @@ -72958,7 +75175,7 @@ var ts; var privateIdentifiers = new ts.Map(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 166 /* Constructor */) { + if (member.kind === 167 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) { @@ -72970,25 +75187,27 @@ var ts; var isStatic = ts.hasSyntacticModifier(member, 32 /* Static */); var name = member.name; if (!name) { - return; + continue; } - var names = ts.isPrivateIdentifier(name) ? privateIdentifiers : + var isPrivate = ts.isPrivateIdentifier(name); + var privateStaticFlags = isPrivate && isStatic ? 16 /* PrivateStatic */ : 0; + var names = isPrivate ? privateIdentifiers : isStatic ? staticNames : instanceNames; var memberName = name && ts.getPropertyNameForPropertyNameNode(name); if (memberName) { switch (member.kind) { - case 167 /* GetAccessor */: - addName(names, name, memberName, 1 /* GetAccessor */); + case 168 /* GetAccessor */: + addName(names, name, memberName, 1 /* GetAccessor */ | privateStaticFlags); break; - case 168 /* SetAccessor */: - addName(names, name, memberName, 2 /* SetAccessor */); + case 169 /* SetAccessor */: + addName(names, name, memberName, 2 /* SetAccessor */ | privateStaticFlags); break; - case 163 /* PropertyDeclaration */: - addName(names, name, memberName, 3 /* GetOrSetAccessor */); + case 164 /* PropertyDeclaration */: + addName(names, name, memberName, 3 /* GetOrSetAccessor */ | privateStaticFlags); break; - case 165 /* MethodDeclaration */: - addName(names, name, memberName, 8 /* Method */); + case 166 /* MethodDeclaration */: + addName(names, name, memberName, 8 /* Method */ | privateStaticFlags); break; } } @@ -72997,16 +75216,25 @@ var ts; function addName(names, location, name, meaning) { var prev = names.get(name); if (prev) { - if (prev & 8 /* Method */) { - if (meaning !== 8 /* Method */) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); - } - } - else if (prev & meaning) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + // For private identifiers, do not allow mixing of static and instance members with the same name + if ((prev & 16 /* PrivateStatic */) !== (meaning & 16 /* PrivateStatic */)) { + error(location, ts.Diagnostics.Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name, ts.getTextOfNode(location)); } else { - names.set(name, prev | meaning); + var prevIsMethod = !!(prev & 8 /* Method */); + var isMethod = !!(meaning & 8 /* Method */); + if (prevIsMethod || isMethod) { + if (prevIsMethod !== isMethod) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + // If this is a method/method duplication is might be an overload, so this will be handled when overloads are considered + } + else if (prev & meaning & ~16 /* PrivateStatic */) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names.set(name, prev | meaning); + } } } else { @@ -73050,7 +75278,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 162 /* PropertySignature */) { + if (member.kind === 163 /* PropertySignature */) { var memberName = void 0; var name = member.name; switch (name.kind) { @@ -73075,11 +75303,11 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 253 /* InterfaceDeclaration */) { + if (node.kind === 254 /* InterfaceDeclaration */) { var nodeSymbol = getSymbolOfNode(node); // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration // to prevent this run check only for the first declaration of a given kind - if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + if (nodeSymbol.declarations && nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; } } @@ -73087,7 +75315,7 @@ var ts; // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); - if (indexSymbol) { + if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { var seenNumericIndexer = false; var seenStringIndexer = false; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -73121,11 +75349,9 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); - // Private class fields transformation relies on WeakMaps. - if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) { - for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) { - getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */; - } + setNodeLinksForPrivateIdentifierScope(node); + if (ts.isPrivateIdentifier(node.name) && ts.hasStaticModifier(node) && node.initializer && languageVersion === 99 /* ESNext */ && !compilerOptions.useDefineForClassFields) { + error(node.initializer, ts.Diagnostics.Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag); } } function checkPropertySignature(node) { @@ -73138,16 +75364,35 @@ var ts; // Grammar checking if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); - if (ts.isPrivateIdentifier(node.name)) { - error(node, ts.Diagnostics.A_method_cannot_be_named_with_a_private_identifier); - } // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (ts.hasSyntacticModifier(node, 128 /* Abstract */) && node.kind === 165 /* MethodDeclaration */ && node.body) { + if (ts.hasSyntacticModifier(node, 128 /* Abstract */) && node.kind === 166 /* MethodDeclaration */ && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } + // Private named methods are only allowed in class declarations + if (ts.isPrivateIdentifier(node.name) && !ts.getContainingClass(node)) { + error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + } + setNodeLinksForPrivateIdentifierScope(node); + } + function setNodeLinksForPrivateIdentifierScope(node) { + if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) { + for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) { + getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */; + } + // If this is a private element in a class expression inside the body of a loop, + // then we must use a block-scoped binding to store the additional variables required + // to transform private elements. + if (ts.isClassExpression(node.parent)) { + var enclosingIterationStatement = getEnclosingIterationStatement(node.parent); + if (enclosingIterationStatement) { + getNodeLinks(node.name).flags |= 524288 /* BlockScopedBindingInLoop */; + getNodeLinks(enclosingIterationStatement).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } + } + } } function checkConstructorDeclaration(node) { // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. @@ -73170,10 +75415,10 @@ var ts; return; } function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) { - if (ts.isPrivateIdentifierPropertyDeclaration(n)) { + if (ts.isPrivateIdentifierClassElementDeclaration(n)) { return true; } - return n.kind === 163 /* PropertyDeclaration */ && + return n.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(n, 32 /* Static */) && !!n.initializer; } @@ -73194,9 +75439,9 @@ var ts; // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) && + var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !useDefineForClassFields) && (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 92 /* ParameterPropertyModifier */); })); + ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */); })); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -73204,7 +75449,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) { var statement = statements_4[_i]; - if (statement.kind === 233 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 234 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -73229,7 +75474,7 @@ var ts; checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 167 /* GetAccessor */) { + if (node.kind === 168 /* GetAccessor */) { if (!(node.flags & 8388608 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 256 /* HasImplicitReturn */)) { if (!(node.flags & 512 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); @@ -73239,45 +75484,42 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } - if (ts.isPrivateIdentifier(node.name)) { - error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier); - } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. - var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; - var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); - if (otherAccessor) { - var nodeFlags = ts.getEffectiveModifierFlags(node); - var otherFlags = ts.getEffectiveModifierFlags(otherAccessor); - if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) { - error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + var symbol = getSymbolOfNode(node); + var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); + if (getter && setter && !(getNodeCheckFlags(getter) & 1 /* TypeChecked */)) { + getNodeLinks(getter).flags |= 1 /* TypeChecked */; + var getterFlags = ts.getEffectiveModifierFlags(getter); + var setterFlags = ts.getEffectiveModifierFlags(setter); + if ((getterFlags & 128 /* Abstract */) !== (setterFlags & 128 /* Abstract */)) { + error(getter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(setter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } + if (((getterFlags & 16 /* Protected */) && !(setterFlags & (16 /* Protected */ | 8 /* Private */))) || + ((getterFlags & 8 /* Private */) && !(setterFlags & 8 /* Private */))) { + error(getter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(setter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); } - if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) { - error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + var getterType = getAnnotatedAccessorType(getter); + var setterType = getAnnotatedAccessorType(setter); + if (getterType && setterType) { + checkTypeAssignableTo(getterType, setterType, getter, ts.Diagnostics.The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type); } - // TypeScript 1.0 spec (April 2014): 4.5 - // If both accessors include type annotations, the specified types must be identical. - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 167 /* GetAccessor */) { + if (node.kind === 168 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } checkSourceElement(node.body); - } - function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { - var firstType = getAnnotatedType(first); - var secondType = getAnnotatedType(second); - if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { - error(first, message); - } + setNodeLinksForPrivateIdentifierScope(node); } function checkMissingDeclaration(node) { checkDecorators(node); @@ -73314,7 +75556,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 173 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 174 /* 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); } ts.forEach(node.typeArguments, checkSourceElement); @@ -73329,7 +75571,7 @@ var ts; var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, getDeprecatedSuggestionNode(node), ts.Diagnostics._0_is_deprecated, symbol.escapedName); + addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 /* Enum */ && symbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); @@ -73367,7 +75609,7 @@ var ts; var hasNamedElement = ts.some(elementTypes, ts.isNamedTupleMember); for (var _i = 0, elementTypes_1 = elementTypes; _i < elementTypes_1.length; _i++) { var e = elementTypes_1[_i]; - if (e.kind !== 192 /* NamedTupleMember */ && hasNamedElement) { + if (e.kind !== 193 /* NamedTupleMember */ && hasNamedElement) { grammarErrorOnNode(e, ts.Diagnostics.Tuple_members_must_all_have_names_or_all_not_have_names); break; } @@ -73416,7 +75658,7 @@ var ts; var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { - if (accessNode.kind === 202 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + if (accessNode.kind === 203 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } @@ -73474,7 +75716,7 @@ var ts; ts.forEachChild(node, checkSourceElement); } function checkInferType(node) { - if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 184 /* ConditionalType */ && n.parent.extendsType === n; })) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 185 /* ConditionalType */ && n.parent.extendsType === n; })) { grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); @@ -73497,25 +75739,25 @@ var ts; if (node.dotDotDotToken && node.questionToken) { grammarErrorOnNode(node, ts.Diagnostics.A_tuple_member_cannot_be_both_optional_and_rest); } - if (node.type.kind === 180 /* OptionalType */) { + if (node.type.kind === 181 /* OptionalType */) { grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type); } - if (node.type.kind === 181 /* RestType */) { + if (node.type.kind === 182 /* RestType */) { grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type); } checkSourceElement(node.type); getTypeFromTypeNode(node); } function isPrivateWithinAmbient(node) { - return (ts.hasEffectiveModifier(node, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */); + return (ts.hasEffectiveModifier(node, 8 /* Private */) || ts.isPrivateIdentifierClassElementDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 253 /* InterfaceDeclaration */ && - n.parent.kind !== 252 /* ClassDeclaration */ && - n.parent.kind !== 221 /* ClassExpression */ && + if (n.parent.kind !== 254 /* InterfaceDeclaration */ && + n.parent.kind !== 253 /* ClassDeclaration */ && + n.parent.kind !== 222 /* ClassExpression */ && n.flags & 8388608 /* Ambient */) { if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { // It is nested in an ambient context, which means it is automatically exported @@ -73611,7 +75853,7 @@ var ts; // Both are literal property names that are the same. ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - var reportError = (node.kind === 165 /* MethodDeclaration */ || node.kind === 164 /* MethodSignature */) && + var reportError = (node.kind === 166 /* MethodDeclaration */ || node.kind === 165 /* MethodSignature */) && ts.hasSyntacticModifier(node, 32 /* Static */) !== ts.hasSyntacticModifier(subsequentNode, 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members @@ -73648,55 +75890,57 @@ var ts; var multipleConstructorImplementation = false; var hasNonAmbientClass = false; var functionDeclarations = []; - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var current = declarations_4[_i]; - var node = current; - var inAmbientContext = node.flags & 8388608 /* Ambient */; - var inAmbientContextOrInterface = node.parent && (node.parent.kind === 253 /* InterfaceDeclaration */ || node.parent.kind === 177 /* TypeLiteral */) || inAmbientContext; - if (inAmbientContextOrInterface) { - // check if declarations are consecutive only if they are non-ambient - // 1. ambient declarations can be interleaved - // i.e. this is legal - // declare function foo(); - // declare function bar(); - // declare function foo(); - // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one - previousDeclaration = undefined; - } - if ((node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */) && !inAmbientContext) { - hasNonAmbientClass = true; - } - if (node.kind === 251 /* FunctionDeclaration */ || node.kind === 165 /* MethodDeclaration */ || node.kind === 164 /* MethodSignature */ || node.kind === 166 /* Constructor */) { - functionDeclarations.push(node); - var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); - someNodeFlags |= currentNodeFlags; - allNodeFlags &= currentNodeFlags; - someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); - allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); - var bodyIsPresent = ts.nodeIsPresent(node.body); - if (bodyIsPresent && bodyDeclaration) { - if (isConstructor) { - multipleConstructorImplementation = true; + if (declarations) { + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; + var node = current; + var inAmbientContext = node.flags & 8388608 /* Ambient */; + var inAmbientContextOrInterface = node.parent && (node.parent.kind === 254 /* InterfaceDeclaration */ || node.parent.kind === 178 /* TypeLiteral */) || inAmbientContext; + if (inAmbientContextOrInterface) { + // check if declarations are consecutive only if they are non-ambient + // 1. ambient declarations can be interleaved + // i.e. this is legal + // declare function foo(); + // declare function bar(); + // declare function foo(); + // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one + previousDeclaration = undefined; + } + if ((node.kind === 253 /* ClassDeclaration */ || node.kind === 222 /* ClassExpression */) && !inAmbientContext) { + hasNonAmbientClass = true; + } + if (node.kind === 252 /* FunctionDeclaration */ || node.kind === 166 /* MethodDeclaration */ || node.kind === 165 /* MethodSignature */ || node.kind === 167 /* Constructor */) { + functionDeclarations.push(node); + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); + var bodyIsPresent = ts.nodeIsPresent(node.body); + if (bodyIsPresent && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } + } + else if ((previousDeclaration === null || previousDeclaration === void 0 ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (bodyIsPresent) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } } else { - duplicateFunctionDeclaration = true; + hasOverloads = true; } - } - else if ((previousDeclaration === null || previousDeclaration === void 0 ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) { - reportImplementationExpectedError(previousDeclaration); - } - if (bodyIsPresent) { - if (!bodyDeclaration) { - bodyDeclaration = node; + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; } } - else { - hasOverloads = true; - } - previousDeclaration = node; - if (!inAmbientContextOrInterface) { - lastSeenNonAmbientDeclaration = node; - } } } if (multipleConstructorImplementation) { @@ -73724,8 +75968,10 @@ var ts; reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { - checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); - checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (declarations) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + } if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); @@ -73799,43 +76045,46 @@ var ts; function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: // A jsdoc typedef and callback are, by definition, type aliases. // falls through - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return 2 /* ExportType */; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4 /* ExportNamespace */ | 1 /* ExportValue */ : 4 /* ExportNamespace */; - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: return 2 /* ExportType */ | 1 /* ExportValue */; - case 297 /* SourceFile */: + case 298 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: + case 217 /* BinaryExpression */: + var node_2 = d; + var expression = ts.isExportAssignment(node_2) ? node_2.expression : node_2.right; // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values - if (!ts.isEntityNameExpression(d.expression)) { + if (!ts.isEntityNameExpression(expression)) { return 1 /* ExportValue */; } - d = d.expression; + d = expression; // The below options all declare an Alias, which is allowed to merge with other values within the importing module. // falls through - case 260 /* ImportEqualsDeclaration */: - case 263 /* NamespaceImport */: - case 262 /* ImportClause */: - var result_12 = 0 /* None */; + case 261 /* ImportEqualsDeclaration */: + case 264 /* NamespaceImport */: + case 263 /* ImportClause */: + var result_13 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_12 |= getDeclarationSpaces(d); }); - return result_12; - case 249 /* VariableDeclaration */: - case 198 /* BindingElement */: - case 251 /* FunctionDeclaration */: - case 265 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + ts.forEach(target.declarations, function (d) { result_13 |= getDeclarationSpaces(d); }); + return result_13; + case 250 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 252 /* FunctionDeclaration */: + case 266 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 case 78 /* Identifier */: // https://github.com/microsoft/TypeScript/issues/36098 // Identifiers are used as declarations of assignment declarations whose parents may be // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});` @@ -74128,24 +76377,24 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 160 /* Parameter */: + case 161 /* Parameter */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -74192,15 +76441,15 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { - case 183 /* IntersectionType */: - case 182 /* UnionType */: + case 184 /* IntersectionType */: + case 183 /* UnionType */: return getEntityNameForDecoratorMetadataFromTypeList(node.types); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); - case 186 /* ParenthesizedType */: - case 192 /* NamedTupleMember */: + case 187 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: return getEntityNameForDecoratorMetadata(node.type); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return node.typeName; } } @@ -74209,13 +76458,13 @@ var ts; var commonEntityName; for (var _i = 0, types_23 = types; _i < types_23.length; _i++) { var typeNode = types_23[_i]; - while (typeNode.kind === 186 /* ParenthesizedType */ || typeNode.kind === 192 /* NamedTupleMember */) { + while (typeNode.kind === 187 /* ParenthesizedType */ || typeNode.kind === 193 /* NamedTupleMember */) { typeNode = typeNode.type; // Skip parens if need be } if (typeNode.kind === 141 /* NeverKeyword */) { continue; // Always elide `never` from the union/intersection if possible } - if (!strictNullChecks && (typeNode.kind === 191 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { + if (!strictNullChecks && (typeNode.kind === 192 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); @@ -74261,14 +76510,14 @@ var ts; } var firstDecorator = node.decorators[0]; checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); - if (node.kind === 160 /* Parameter */) { + if (node.kind === 161 /* Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* Param */); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -74277,23 +76526,23 @@ var ts; } } break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + var otherKind = node.kind === 168 /* GetAccessor */ ? 169 /* SetAccessor */ : 168 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 160 /* Parameter */: + case 161 /* Parameter */: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); var containingSignature = node.parent; for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { @@ -74356,7 +76605,7 @@ var ts; else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 157 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 158 /* QualifiedName */ ? node.name.right : node.name)); } } } @@ -74400,25 +76649,26 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return node.name; default: return undefined; } } function checkFunctionOrMethodDeclaration(node) { + var _a; checkDecorators(node); checkSignatureDeclaration(node); var functionFlags = ts.getFunctionFlags(node); // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name && node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 159 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // first we want to check the local symbol that contain this declaration // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode @@ -74427,7 +76677,7 @@ var ts; // Since the javascript won't do semantic analysis like typescript, // if the javascript file comes before the typescript file and both contain same name functions, // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. - var firstDeclaration = ts.find(localSymbol.declarations, + var firstDeclaration = (_a = localSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find( // Get first non javascript function declaration function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072 /* JavaScriptFile */); }); // Only type check the symbol once @@ -74439,7 +76689,7 @@ var ts; checkFunctionOrConstructorSymbol(symbol); } } - var body = node.kind === 164 /* MethodSignature */ ? undefined : node.body; + var body = node.kind === 165 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node)); if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { @@ -74481,42 +76731,42 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: checkUnusedClassMembers(node, addDiagnostic); checkUnusedTypeParameters(node, addDiagnostic); break; - case 297 /* SourceFile */: - case 256 /* ModuleDeclaration */: - case 230 /* Block */: - case 258 /* CaseBlock */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 298 /* SourceFile */: + case 257 /* ModuleDeclaration */: + case 231 /* Block */: + case 259 /* CaseBlock */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: checkUnusedLocalsAndParameters(node, addDiagnostic); break; - case 166 /* Constructor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 167 /* Constructor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: if (node.body) { // Don't report unused parameters in overloads checkUnusedLocalsAndParameters(node, addDiagnostic); } checkUnusedTypeParameters(node, addDiagnostic); break; - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: checkUnusedTypeParameters(node, addDiagnostic); break; - case 185 /* InferType */: + case 186 /* InferType */: checkUnusedInferTypeParameter(node, addDiagnostic); break; default: @@ -74536,11 +76786,11 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 165 /* MethodDeclaration */: - case 163 /* PropertyDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - if (member.kind === 168 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + case 166 /* MethodDeclaration */: + case 164 /* PropertyDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + if (member.kind === 169 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { // Already would have reported an error on the getter. break; } @@ -74551,7 +76801,7 @@ var ts; addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; - case 166 /* Constructor */: + case 167 /* Constructor */: for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasSyntacticModifier(parameter, 8 /* Private */)) { @@ -74559,8 +76809,8 @@ var ts; } } break; - case 171 /* IndexSignature */: - case 229 /* SemicolonClassElement */: + case 172 /* IndexSignature */: + case 230 /* SemicolonClassElement */: // Can't be private break; default: @@ -74577,7 +76827,8 @@ var ts; function checkUnusedTypeParameters(node, addDiagnostic) { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. - if (ts.last(getSymbolOfNode(node).declarations) !== node) + var declarations = getSymbolOfNode(node).declarations; + if (!declarations || ts.last(declarations) !== node) return; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); var seenParentsWithEveryUnused = new ts.Set(); @@ -74587,7 +76838,7 @@ var ts; continue; var name = ts.idText(typeParameter.name); var parent = typeParameter.parent; - if (parent.kind !== 185 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (parent.kind !== 186 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { if (ts.tryAddToSet(seenParentsWithEveryUnused, parent)) { var sourceFile = ts.getSourceFileOfNode(parent); var range = ts.isJSDocTemplateTag(parent) @@ -74623,11 +76874,15 @@ var ts; return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } function isValidUnusedLocalDeclaration(declaration) { - if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { - return !!ts.findAncestor(declaration.parent, function (ancestor) { - return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : - ts.isForOfStatement(ancestor) ? true : "quit"; - }); + if (ts.isBindingElement(declaration)) { + if (ts.isObjectBindingPattern(declaration.parent)) { + /** + * ignore starts with underscore names _ + * const { a: _a } = { a: 1 } + */ + return !!(declaration.propertyName && isIdentifierThatStartsWithUnderscore(declaration.name)); + } + return isIdentifierThatStartsWithUnderscore(declaration.name); } return ts.isAmbientModule(declaration) || (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); @@ -74643,39 +76898,41 @@ var ts; if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) { return; } - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (isValidUnusedLocalDeclaration(declaration)) { - continue; - } - if (isImportedDeclaration(declaration)) { - addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); - } - else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { - // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. - var lastElement = ts.last(declaration.parent.elements); - if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { - addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + if (local.declarations) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (isValidUnusedLocalDeclaration(declaration)) { + continue; } - } - else if (ts.isVariableDeclaration(declaration)) { - addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); - } - else { - var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); - var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); - if (parameter && name) { - if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { - if (ts.isBindingElement(declaration) && ts.isArrayBindingPattern(declaration.parent)) { - addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); - } - else { - addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); - } + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); } } + else if (ts.isVariableDeclaration(declaration)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } else { - errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); + if (parameter && name) { + if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { + if (ts.isBindingElement(declaration) && ts.isArrayBindingPattern(declaration.parent)) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + else { + addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); + } + } + } + else { + errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); + } } } } @@ -74685,7 +76942,7 @@ var ts; var importDecl = importClause.parent; var nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? - (importClause.namedBindings.kind === 263 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + (importClause.namedBindings.kind === 264 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 @@ -74703,7 +76960,7 @@ var ts; var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; if (bindingPattern.elements.length === bindingElements.length) { - if (bindingElements.length === 1 && bindingPattern.parent.kind === 249 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 250 /* VariableDeclarationList */) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 250 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 251 /* VariableDeclarationList */) { addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { @@ -74724,7 +76981,7 @@ var ts; if (declarationList.declarations.length === declarations.length) { addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) - : ts.createDiagnosticForNode(declarationList.parent.kind === 232 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + : ts.createDiagnosticForNode(declarationList.parent.kind === 233 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { @@ -74738,22 +76995,22 @@ var ts; switch (name.kind) { case 78 /* Identifier */: return ts.idText(name); - case 197 /* ArrayBindingPattern */: - case 196 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); default: return ts.Debug.assertNever(name); } } function isImportedDeclaration(node) { - return node.kind === 262 /* ImportClause */ || node.kind === 265 /* ImportSpecifier */ || node.kind === 263 /* NamespaceImport */; + return node.kind === 263 /* ImportClause */ || node.kind === 266 /* ImportSpecifier */ || node.kind === 264 /* NamespaceImport */; } function importClauseFromImported(decl) { - return decl.kind === 262 /* ImportClause */ ? decl : decl.kind === 263 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + return decl.kind === 263 /* ImportClause */ ? decl : decl.kind === 264 /* NamespaceImport */ ? decl.parent : decl.parent.parent; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 230 /* Block */) { + if (node.kind === 231 /* Block */) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -74783,12 +77040,12 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 163 /* PropertyDeclaration */ || - node.kind === 162 /* PropertySignature */ || - node.kind === 165 /* MethodDeclaration */ || - node.kind === 164 /* MethodSignature */ || - node.kind === 167 /* GetAccessor */ || - node.kind === 168 /* SetAccessor */) { + if (node.kind === 164 /* PropertyDeclaration */ || + node.kind === 163 /* PropertySignature */ || + node.kind === 166 /* MethodDeclaration */ || + node.kind === 165 /* MethodSignature */ || + node.kind === 168 /* GetAccessor */ || + node.kind === 169 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } @@ -74797,7 +77054,7 @@ var ts; return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 160 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 161 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -74834,10 +77091,11 @@ var ts; return false; }); } - function checkWeakMapCollision(node) { + function checkWeakMapSetCollision(node) { var enclosingBlockScope = ts.getEnclosingBlockScopeContainer(node); if (getNodeCheckFlags(enclosingBlockScope) & 67108864 /* ContainsClassWithPrivateIdentifiers */) { - errorSkippedOn("noEmit", node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, "WeakMap"); + ts.Debug.assert(ts.isNamedDeclaration(node) && ts.isIdentifier(node.name) && typeof node.name.escapedText === "string", "The target of a WeakMap/WeakSet collision check should be an identifier"); + errorSkippedOn("noEmit", node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, node.name.escapedText); } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { @@ -74854,7 +77112,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords errorSkippedOn("noEmit", name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -74869,7 +77127,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) { + if (parent.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. errorSkippedOn("noEmit", name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -74904,7 +77162,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 249 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 250 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -74916,17 +77174,17 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 250 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 232 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 251 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 233 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) var namesShareScope = container && - (container.kind === 230 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 257 /* ModuleBlock */ || - container.kind === 256 /* ModuleDeclaration */ || - container.kind === 297 /* SourceFile */); + (container.kind === 231 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 258 /* ModuleBlock */ || + container.kind === 257 /* ModuleDeclaration */ || + container.kind === 298 /* SourceFile */); // here we know that function scoped variable is shadowed by block scoped one // if they are defined in the same scope - binder has already reported redeclaration error // otherwise if variable has an initializer - show error that initialization will fail @@ -74957,18 +77215,18 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 198 /* BindingElement */) { - if (node.parent.kind === 196 /* ObjectBindingPattern */ && languageVersion < 99 /* ESNext */) { + if (ts.isBindingElement(node)) { + if (ts.isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < 5 /* ES2018 */) { checkExternalEmitHelpers(node, 4 /* Rest */); } // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 158 /* ComputedPropertyName */) { + if (node.propertyName && node.propertyName.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } // check private/protected variable access @@ -74981,15 +77239,15 @@ var ts; var nameText = getPropertyNameFromType(exprType); var property = getPropertyOfType(parentType, nameText); if (property) { - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 105 /* SuperKeyword */, parentType, property); + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isSelfTypeAccess*/ false); // A destructuring is never a write-only reference. + checkPropertyAccessibility(node, !!parent.initializer && parent.initializer.kind === 105 /* SuperKeyword */, /*writing*/ false, parentType, property); } } } } // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 197 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + if (node.name.kind === 198 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } ts.forEach(node.name.elements, checkSourceElement); @@ -75001,7 +77259,7 @@ var ts; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { - var needCheckInitializer = node.initializer && node.parent.parent.kind !== 238 /* ForInStatement */; + var needCheckInitializer = node.initializer && node.parent.parent.kind !== 239 /* ForInStatement */; var needCheckWidenedType = node.name.elements.length === 0; if (needCheckInitializer || needCheckWidenedType) { // Don't validate for-in initializer as it is already an error @@ -75029,7 +77287,7 @@ var ts; } // For a commonjs `const x = require`, validate the alias and exit var symbol = getSymbolOfNode(node); - if (symbol.flags & 2097152 /* Alias */ && ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true)) { + if (symbol.flags & 2097152 /* Alias */ && ts.isRequireVariableDeclaration(node)) { checkAliasSymbol(node); return; } @@ -75043,11 +77301,11 @@ var ts; ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && !!((_a = symbol.exports) === null || _a === void 0 ? void 0 : _a.size); - if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 238 /* ForInStatement */) { + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 239 /* ForInStatement */) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); } } - if (symbol.declarations.length > 1) { + if (symbol.declarations && symbol.declarations.length > 1) { if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) { error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } @@ -75065,26 +77323,27 @@ var ts; if (node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } - if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 163 /* PropertyDeclaration */ && node.kind !== 162 /* PropertySignature */) { + if (node.kind !== 164 /* PropertyDeclaration */ && node.kind !== 163 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) { + if (node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - if (languageVersion < 99 /* ESNext */ && needCollisionCheckForIdentifier(node, node.name, "WeakMap")) { - potentialWeakMapCollisions.push(node); + if (languageVersion < 99 /* ESNext */ + && (needCollisionCheckForIdentifier(node, node.name, "WeakMap") || needCollisionCheckForIdentifier(node, node.name, "WeakSet"))) { + potentialWeakMapSetCollisions.push(node); } } } function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) { var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); - var message = nextDeclaration.kind === 163 /* PropertyDeclaration */ || nextDeclaration.kind === 162 /* PropertySignature */ + var message = nextDeclaration.kind === 164 /* PropertyDeclaration */ || nextDeclaration.kind === 163 /* PropertySignature */ ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; var declName = ts.declarationNameToString(nextDeclarationName); @@ -75094,8 +77353,8 @@ var ts; } } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 160 /* Parameter */ && right.kind === 249 /* VariableDeclaration */) || - (left.kind === 249 /* VariableDeclaration */ && right.kind === 160 /* Parameter */)) { + if ((left.kind === 161 /* Parameter */ && right.kind === 250 /* VariableDeclaration */) || + (left.kind === 250 /* VariableDeclaration */ && right.kind === 161 /* Parameter */)) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -75111,10 +77370,10 @@ var ts; return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { - ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); checkGrammarVariableDeclaration(node); checkVariableLikeDeclaration(node); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkBindingElement(node) { checkGrammarBindingElement(node); @@ -75135,49 +77394,55 @@ var ts; // Grammar checking checkGrammarStatementInAmbientContext(node); var type = checkTruthinessExpression(node.expression); - checkTestingKnownTruthyCallableType(node.expression, type, node.thenStatement); + checkTestingKnownTruthyCallableOrAwaitableType(node.expression, type, node.thenStatement); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 231 /* EmptyStatement */) { + if (node.thenStatement.kind === 232 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); } - function checkTestingKnownTruthyCallableType(condExpr, type, body) { - if (!strictNullChecks) { + function checkTestingKnownTruthyCallableOrAwaitableType(condExpr, type, body) { + if (!strictNullChecks) + return; + if (getFalsyFlags(type)) return; - } var location = ts.isBinaryExpression(condExpr) ? condExpr.right : condExpr; var testedNode = ts.isIdentifier(location) ? location : ts.isPropertyAccessExpression(location) ? location.name : ts.isBinaryExpression(location) && ts.isIdentifier(location.right) ? location.right : undefined; - if (!testedNode) { - return; - } - var possiblyFalsy = getFalsyFlags(type); - if (possiblyFalsy) { + var isPropertyExpressionCast = ts.isPropertyAccessExpression(location) + && ts.isAssertionExpression(ts.skipParentheses(location.expression)); + if (!testedNode || isPropertyExpressionCast) { return; } // While it technically should be invalid for any known-truthy value - // to be tested, we de-scope to functions unrefenced in the block as a - // heuristic to identify the most common bugs. There are too many - // false positives for values sourced from type definitions without - // strictNullChecks otherwise. + // to be tested, we de-scope to functions and Promises unreferenced in + // the block as a heuristic to identify the most common bugs. There + // are too many false positives for values sourced from type + // definitions without strictNullChecks otherwise. var callSignatures = getSignaturesOfType(type, 0 /* Call */); - if (callSignatures.length === 0) { + var isPromise = !!getAwaitedTypeOfPromise(type); + if (callSignatures.length === 0 && !isPromise) { return; } var testedSymbol = getSymbolAtLocation(testedNode); if (!testedSymbol) { return; } - var isUsed = ts.isBinaryExpression(condExpr.parent) && isFunctionUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) - || body && isFunctionUsedInConditionBody(condExpr, body, testedNode, testedSymbol); + var isUsed = ts.isBinaryExpression(condExpr.parent) && isSymbolUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) + || body && isSymbolUsedInConditionBody(condExpr, body, testedNode, testedSymbol); if (!isUsed) { - error(location, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead); + if (isPromise) { + errorAndMaybeSuggestAwait(location, + /*maybeMissingAwait*/ true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, getTypeNameForErrorDisplay(type)); + } + else { + error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead); + } } } - function isFunctionUsedInConditionBody(expr, body, testedNode, testedSymbol) { + function isSymbolUsedInConditionBody(expr, body, testedNode, testedSymbol) { return !!ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); @@ -75214,7 +77479,7 @@ var ts; return ts.forEachChild(childNode, check); }); } - function isFunctionUsedInBinaryExpressionChain(node, testedSymbol) { + function isSymbolUsedInBinaryExpressionChain(node, testedSymbol) { while (ts.isBinaryExpression(node) && node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { var isUsed = ts.forEachChild(node.right, function visit(child) { if (ts.isIdentifier(child)) { @@ -75256,12 +77521,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 251 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer.kind === 251 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -75295,14 +77560,14 @@ var ts; // via checkRightHandSideOfForOf. // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. // Then check that the RHS is assignable to it. - if (node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer.kind === 251 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node); // There may be a destructuring assignment on the left side - if (varExpr.kind === 199 /* ArrayLiteralExpression */ || varExpr.kind === 200 /* ObjectLiteralExpression */) { + if (varExpr.kind === 200 /* ArrayLiteralExpression */ || varExpr.kind === 201 /* ObjectLiteralExpression */) { // iteratedType may be undefined. In this case, we still want to check the structure of // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like // to short circuit the type relation checking as much as possible, so we pass the unknownType. @@ -75334,7 +77599,7 @@ var ts; // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer.kind === 251 /* VariableDeclarationList */) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -75348,7 +77613,7 @@ var ts; // and Expr must be an expression of type Any, an object type, or a type parameter type. var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 199 /* ArrayLiteralExpression */ || varExpr.kind === 200 /* ObjectLiteralExpression */) { + if (varExpr.kind === 200 /* ArrayLiteralExpression */ || varExpr.kind === 201 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -75464,18 +77729,8 @@ var ts; // want to say that number is not an array type. But if the input was just // number and string input is allowed, we want to say that number is not an // array type or a string type. - var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined); - var _a = !(use & 4 /* AllowsStringInputFlag */) || hasStringConstituent - ? downlevelIteration - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] - : yieldType - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false] - : [ts.Diagnostics.Type_0_is_not_an_array_type, true] - : downlevelIteration - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] - : yieldType - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false] - : [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true], defaultDiagnostic = _a[0], maybeMissingAwait = _a[1]; + var allowsStrings = !!(use & 4 /* AllowsStringInputFlag */) && !hasStringConstituent; + var _a = getIterationDiagnosticDetails(allowsStrings, downlevelIteration), defaultDiagnostic = _a[0], maybeMissingAwait = _a[1]; errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType)); } return hasStringConstituent ? possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType : undefined; @@ -75489,6 +77744,40 @@ var ts; return getUnionType(possibleOutOfBounds ? [arrayElementType, stringType, undefinedType] : [arrayElementType, stringType], 2 /* Subtype */); } return (use & 128 /* PossiblyOutOfBounds */) ? includeUndefinedInIndexSignature(arrayElementType) : arrayElementType; + function getIterationDiagnosticDetails(allowsStrings, downlevelIteration) { + var _a; + if (downlevelIteration) { + return allowsStrings + ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] + : [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]; + } + var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined); + if (yieldType) { + return [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]; + } + if (isES2015OrLaterIterable((_a = inputType.symbol) === null || _a === void 0 ? void 0 : _a.escapedName)) { + return [ts.Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, true]; + } + return allowsStrings + ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true] + : [ts.Diagnostics.Type_0_is_not_an_array_type, true]; + } + } + function isES2015OrLaterIterable(n) { + switch (n) { + case "Float32Array": + case "Float64Array": + case "Int16Array": + case "Int32Array": + case "Int8Array": + case "NodeList": + case "Uint16Array": + case "Uint32Array": + case "Uint8Array": + case "Uint8ClampedArray": + return true; + } + return false; } /** * Gets the requested "iteration type" from an `Iterable`-like or `AsyncIterable`-like type. @@ -75732,6 +78021,11 @@ var ts; return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType)); } } + function getPropertyNameForKnownSymbolName(symbolName) { + var ctorType = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false); + var uniqueType = ctorType && getTypeOfPropertyOfType(getTypeOfSymbol(ctorType), ts.escapeLeadingUnderscores(symbolName)); + return uniqueType && isTypeUsableAsPropertyName(uniqueType) ? getPropertyNameFromType(uniqueType) : "__@" + symbolName; + } /** * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like * type from its members. @@ -75744,7 +78038,7 @@ var ts; */ function getIterationTypesOfIterableSlow(type, resolver, errorNode) { var _a; - var method = getPropertyOfType(type, ts.getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); + var method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); var methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : undefined; if (isTypeAny(methodType)) { return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); @@ -76043,12 +78337,12 @@ var ts; var functionFlags = ts.getFunctionFlags(func); if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - if (func.kind === 168 /* SetAccessor */) { + if (func.kind === 169 /* SetAccessor */) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 166 /* Constructor */) { + else if (func.kind === 167 /* Constructor */) { if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -76066,7 +78360,7 @@ var ts; } } } - else if (func.kind !== 166 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + else if (func.kind !== 167 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { // The function has a return type, but the return statement doesn't have an expression. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -76095,7 +78389,7 @@ var ts; var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 285 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 286 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -76104,7 +78398,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 284 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 285 /* CaseClause */) { // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable // to or from the type of the 'switch' expression. @@ -76136,7 +78430,7 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 245 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + if (current.kind === 246 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } @@ -76166,10 +78460,11 @@ var ts; // Grammar checking if (catchClause.variableDeclaration) { var declaration = catchClause.variableDeclaration; - if (declaration.type) { + var typeNode = ts.getEffectiveTypeAnnotationNode(ts.getRootDeclaration(declaration)); + if (typeNode) { var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ false); if (type && !(type.flags & 3 /* AnyOrUnknown */)) { - grammarErrorOnFirstToken(declaration.type, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified); + grammarErrorOnFirstToken(typeNode, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified); } } else if (declaration.initializer) { @@ -76180,7 +78475,7 @@ var ts; if (blockLocals_1) { ts.forEachKey(catchClause.locals, function (caughtName) { var blockLocal = blockLocals_1.get(caughtName); - if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { + if ((blockLocal === null || blockLocal === void 0 ? void 0 : blockLocal.valueDeclaration) && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); } }); @@ -76193,25 +78488,28 @@ var ts; checkBlock(node.finallyBlock); } } - function checkIndexConstraints(type) { - var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); - var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); + function checkIndexConstraints(type, isStatic) { + var _a, _b, _c, _d; + var declaredNumberIndexer = getIndexDeclarationOfSymbolTable(isStatic ? (_a = type.symbol) === null || _a === void 0 ? void 0 : _a.exports : (_b = type.symbol) === null || _b === void 0 ? void 0 : _b.members, 1 /* Number */); + var declaredStringIndexer = getIndexDeclarationOfSymbolTable(isStatic ? (_c = type.symbol) === null || _c === void 0 ? void 0 : _c.exports : (_d = type.symbol) === null || _d === void 0 ? void 0 : _d.members, 0 /* String */); var stringIndexType = getIndexTypeOfType(type, 0 /* String */); var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); if (stringIndexType || numberIndexType) { ts.forEach(getPropertiesOfObjectType(type), function (prop) { + if (isStatic && prop.flags & 4194304 /* Prototype */) + return; var propType = getTypeOfSymbol(prop); checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); var classDeclaration = type.symbol.valueDeclaration; - if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) { - for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { - var member = _a[_i]; + if (ts.getObjectFlags(type) & 1 /* Class */ && classDeclaration && ts.isClassLike(classDeclaration)) { + for (var _i = 0, _e = classDeclaration.members; _i < _e.length; _i++) { + var member = _e[_i]; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!ts.hasSyntacticModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) { + if (!ts.hasSyntacticModifier(member, 32 /* Static */) && !hasBindableName(member)) { var symbol = getSymbolOfNode(member); var propType = getTypeOfSymbol(symbol); checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); @@ -76226,7 +78524,7 @@ var ts; // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); - errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + errorNode = someBaseTypeHasBothIndexers || !type.symbol.declarations ? undefined : type.symbol.declarations[0]; } } if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217 @@ -76250,8 +78548,8 @@ var ts; // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; if (propDeclaration && name && - (propDeclaration.kind === 216 /* BinaryExpression */ || - name.kind === 158 /* ComputedPropertyName */ || + (propDeclaration.kind === 217 /* BinaryExpression */ || + name.kind === 159 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } @@ -76263,7 +78561,7 @@ var ts; // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); - errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + errorNode = someBaseClassHasBothPropertyAndIndexer || !containingType.symbol.declarations ? undefined : containingType.symbol.declarations[0]; } if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { var errorMessage = indexKind === 0 /* String */ @@ -76279,6 +78577,7 @@ var ts; switch (name.escapedText) { case "any": case "unknown": + case "never": case "number": case "bigint": case "boolean": @@ -76328,7 +78627,7 @@ var ts; function checkTypeParametersNotReferenced(root, typeParameters, index) { visit(root); function visit(node) { - if (node.kind === 173 /* TypeReference */) { + if (node.kind === 174 /* TypeReference */) { var type = getTypeFromTypeReference(node); if (type.flags & 262144 /* TypeParameter */) { for (var i = index; i < typeParameters.length; i++) { @@ -76343,14 +78642,14 @@ var ts; } /** Check that type parameter lists are identical across multiple declarations */ function checkTypeParameterListsIdentical(symbol) { - if (symbol.declarations.length === 1) { + if (symbol.declarations && symbol.declarations.length === 1) { return; } var links = getSymbolLinks(symbol); if (!links.typeParametersChecked) { links.typeParametersChecked = true; var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); - if (declarations.length <= 1) { + if (!declarations || declarations.length <= 1) { return; } var type = getDeclaredTypeOfSymbol(symbol); @@ -76414,6 +78713,9 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { + if (ts.some(node.decorators) && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { + grammarErrorOnNode(node.decorators[0], ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); + } if (!node.name && !ts.hasSyntacticModifier(node, 512 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } @@ -76442,7 +78744,8 @@ var ts; checkFunctionOrConstructorSymbol(symbol); checkClassForDuplicateDeclarations(node); // Only check for reserved static identifiers on non-ambient context. - if (!(node.flags & 8388608 /* Ambient */)) { + var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + if (!nodeInAmbientContext) { checkClassForStaticPropertyNameConflicts(node); } var baseTypeNode = ts.getEffectiveBaseTypeNode(node); @@ -76502,6 +78805,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } + checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { @@ -76531,14 +78835,76 @@ var ts; } if (produceDiagnostics) { checkIndexConstraints(type); + checkIndexConstraints(staticType, /*isStatic*/ true); checkTypeForDuplicateIndexSignatures(node); checkPropertyInitialization(node); } } + function checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType) { + var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); + var baseTypes = baseTypeNode && getBaseTypes(type); + var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; + var baseStaticType = getBaseConstructorTypeOfClass(type); + var _loop_24 = function (member) { + if (ts.hasAmbientModifier(member)) { + return "continue"; + } + if (ts.isConstructorDeclaration(member)) { + ts.forEach(member.parameters, function (param) { + if (ts.isParameterPropertyDeclaration(param, member)) { + checkClassMember(param, /*memberIsParameterProperty*/ true); + } + }); + } + checkClassMember(member); + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_24(member); + } + function checkClassMember(member, memberIsParameterProperty) { + var hasOverride = ts.hasOverrideModifier(member); + var hasStatic = ts.hasStaticModifier(member); + if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (!declaredProp) { + return; + } + var thisType = hasStatic ? staticType : typeWithThis; + var baseType = hasStatic ? baseStaticType : baseWithThis; + var prop = getPropertyOfType(thisType, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseType, declaredProp.escapedName); + var baseClassName = typeToString(baseWithThis); + if (prop && !baseProp && hasOverride) { + error(member, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); + } + else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.valueDeclaration) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { + var baseHasAbstract = ts.hasAbstractModifier(baseProp.valueDeclaration); + if (hasOverride) { + return; + } + if (!baseHasAbstract) { + var diag = memberIsParameterProperty ? + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : + ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; + error(member, diag, baseClassName); + } + else if (ts.hasAbstractModifier(member) && baseHasAbstract) { + error(member, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); + } + } + } + else if (hasOverride) { + var className = typeToString(type); + error(member, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, className); + } + } + } 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_23 = function (member) { + var _loop_25 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -76557,7 +78923,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_23(member); + _loop_25(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -76583,7 +78949,7 @@ var ts; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 252 /* ClassDeclaration */ || d.kind === 253 /* InterfaceDeclaration */; + return d.kind === 253 /* ClassDeclaration */ || d.kind === 254 /* InterfaceDeclaration */; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -76600,6 +78966,7 @@ var ts; // but not by other kinds of members. // Base class instance member variables and accessors can be overridden by // derived class instance member variables and accessors, but not by other kinds of members. + var _a, _b; // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfType(baseType); basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { @@ -76628,8 +78995,8 @@ var ts; // Searches other base types for a declaration that would satisfy the inherited abstract member. // (The class may have more than one base type via declaration merging with an interface with the // same name.) - for (var _a = 0, _b = getBaseTypes(type); _a < _b.length; _a++) { - var otherBaseType = _b[_a]; + for (var _c = 0, _d = getBaseTypes(type); _c < _d.length; _c++) { + var otherBaseType = _d[_c]; if (otherBaseType === baseType) continue; var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName); @@ -76638,7 +79005,7 @@ var ts; continue basePropertyCheck; } } - if (derivedClassDecl.kind === 221 /* ClassExpression */) { + if (derivedClassDecl.kind === 222 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -76659,7 +79026,7 @@ var ts; if (basePropertyFlags && derivedPropertyFlags) { // property/accessor is overridden with property/accessor if (baseDeclarationFlags & 128 /* Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer) - || base.valueDeclaration && base.valueDeclaration.parent.kind === 253 /* InterfaceDeclaration */ + || base.valueDeclaration && base.valueDeclaration.parent.kind === 254 /* InterfaceDeclaration */ || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) { // when the base property is abstract or from an interface, base/derived flags don't need to match // same when the derived property is from an assignment @@ -76673,13 +79040,13 @@ var ts; ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } - else if (compilerOptions.useDefineForClassFields) { - var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 163 /* PropertyDeclaration */ && !d.initializer; }); + else if (useDefineForClassFields) { + var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 164 /* PropertyDeclaration */ && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432 /* Transient */) && !(baseDeclarationFlags & 128 /* Abstract */) && !(derivedDeclarationFlags & 128 /* Abstract */) - && !derived.declarations.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); })) { + && !((_b = derived.declarations) === null || _b === void 0 ? void 0 : _b.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); }))) { var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol)); var propName = uninitialized.name; if (uninitialized.exclamationToken @@ -76790,7 +79157,7 @@ var ts; } } function isInstancePropertyWithoutInitializer(node) { - return node.kind === 163 /* PropertyDeclaration */ && + return node.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(node, 32 /* Static */ | 128 /* Abstract */) && !node.exclamationToken && !node.initializer; @@ -76814,7 +79181,7 @@ var ts; var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 253 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 254 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -76933,7 +79300,7 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: var value_2 = evaluate(expr.operand); if (typeof value_2 === "number") { switch (expr.operator) { @@ -76943,7 +79310,7 @@ var ts; } } break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { @@ -76972,7 +79339,7 @@ var ts; case 8 /* NumericLiteral */: checkGrammarNumericLiteral(expr); return +expr.text; - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return evaluate(expr.expression); case 78 /* Identifier */: var identifier = expr; @@ -76980,14 +79347,14 @@ var ts; return +(identifier.escapedText); } return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); - case 202 /* ElementAccessExpression */: - case 201 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384 /* Enum */) { var name = void 0; - if (ex.kind === 201 /* PropertyAccessExpression */) { + if (ex.kind === 202 /* PropertyAccessExpression */) { name = ex.name.escapedText; } else { @@ -77005,7 +79372,7 @@ var ts; if (memberSymbol) { var declaration = memberSymbol.valueDeclaration; if (declaration !== member) { - if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + if (declaration && isBlockScopedNameDeclaredBeforeUse(declaration, member)) { return getEnumMemberValue(declaration); } error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); @@ -77020,8 +79387,8 @@ var ts; } function isConstantMemberAccess(node) { return node.kind === 78 /* Identifier */ || - node.kind === 201 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || - node.kind === 202 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.kind === 202 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 203 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && ts.isStringLiteralLike(node.argumentExpression); } function checkEnumDeclaration(node) { @@ -77045,7 +79412,7 @@ var ts; var enumSymbol = getSymbolOfNode(node); var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); if (node === firstDeclaration) { - if (enumSymbol.declarations.length > 1) { + if (enumSymbol.declarations && enumSymbol.declarations.length > 1) { var enumIsConst_1 = ts.isEnumConst(node); // check that const is placed\omitted on all enum declarations ts.forEach(enumSymbol.declarations, function (decl) { @@ -77057,7 +79424,7 @@ var ts; var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 255 /* EnumDeclaration */) { + if (declaration.kind !== 256 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -77083,12 +79450,14 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; - if ((declaration.kind === 252 /* ClassDeclaration */ || - (declaration.kind === 251 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && - !(declaration.flags & 8388608 /* Ambient */)) { - return declaration; + if (declarations) { + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 253 /* ClassDeclaration */ || + (declaration.kind === 252 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 8388608 /* Ambient */)) { + return declaration; + } } } return undefined; @@ -77136,8 +79505,9 @@ var ts; // The following checks only apply on a non-ambient instantiated module declaration. if (symbol.flags & 512 /* ValueModule */ && !inAmbientContext + && symbol.declarations && symbol.declarations.length > 1 - && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions))) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -77149,7 +79519,7 @@ var ts; } // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. - var mergedClass = ts.getDeclarationOfKind(symbol, 252 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 253 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -77198,40 +79568,41 @@ var ts; } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { + var _a; switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // error each individual name in variable statement instead of marking the entire variable statement - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; + for (var _i = 0, _b = node.declarationList.declarations; _i < _b.length; _i++) { + var decl = _b[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 266 /* ExportAssignment */: - case 267 /* ExportDeclaration */: + case 267 /* ExportAssignment */: + case 268 /* ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 260 /* ImportEqualsDeclaration */: - case 261 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 198 /* BindingElement */: - case 249 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 250 /* VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { - for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { - var el = _c[_b]; + for (var _c = 0, _d = name.elements; _c < _d.length; _c++) { + var el = _d[_c]; // mark individual names in binding pattern checkModuleAugmentationElement(el, isGlobalAugmentation); } break; } // falls through - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 251 /* FunctionDeclaration */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 252 /* FunctionDeclaration */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } @@ -77244,7 +79615,7 @@ var ts; var reportError = !(symbol.flags & 33554432 /* Transient */); if (!reportError) { // symbol should not originate in augmentation - reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + reportError = !!((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.declarations) && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); } } break; @@ -77254,12 +79625,12 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: do { node = node.left; } while (node.kind !== 78 /* Identifier */); return node; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: do { if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) { return node.name; @@ -77279,9 +79650,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 257 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 297 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 267 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 258 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 298 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 268 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -77301,6 +79672,7 @@ var ts; return true; } function checkAliasSymbol(node) { + var _a; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { @@ -77315,21 +79687,21 @@ var ts; (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 270 /* ExportSpecifier */ ? + var message = node.kind === 271 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules - && node.kind === 270 /* ExportSpecifier */ + && node.kind === 271 /* ExportSpecifier */ && !node.parent.parent.isTypeOnly && !(target.flags & 111551 /* Value */) && !(node.flags & 8388608 /* Ambient */)) { error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type); } - if (ts.isImportSpecifier(node) && ts.every(target.declarations, function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, node.name, ts.Diagnostics._0_is_deprecated, symbol.escapedName); + if (ts.isImportSpecifier(node) && ((_a = target.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); }))) { + addDeprecatedSuggestion(node.name, target.declarations, symbol.escapedName); } } } @@ -77337,7 +79709,7 @@ var ts; checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkAliasSymbol(node); - if (node.kind === 265 /* ImportSpecifier */ && + if (node.kind === 266 /* ImportSpecifier */ && ts.idText(node.propertyName || node.name) === "default" && compilerOptions.esModuleInterop && moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) { @@ -77359,7 +79731,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 263 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 264 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015 && compilerOptions.esModuleInterop) { // import * as ns from "foo"; @@ -77387,7 +79759,7 @@ var ts; if (ts.hasSyntacticModifier(node, 1 /* Export */)) { markExportAsReferenced(node); } - if (node.moduleReference.kind !== 272 /* ExternalModuleReference */) { + if (node.moduleReference.kind !== 273 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { if (target.flags & 111551 /* Value */) { @@ -77430,10 +79802,10 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 257 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 257 /* ModuleBlock */ && + var inAmbientExternalModule = node.parent.kind === 258 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 258 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 8388608 /* Ambient */; - if (node.parent.kind !== 297 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + if (node.parent.kind !== 298 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -77466,14 +79838,14 @@ var ts; } function checkGrammarExportDeclaration(node) { var _a; - var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 268 /* NamedExports */; + var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 269 /* NamedExports */; if (isTypeOnlyExportStar) { grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type); } return !isTypeOnlyExportStar; } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 297 /* SourceFile */ || node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 256 /* ModuleDeclaration */; + var isInAppropriateContext = node.parent.kind === 298 /* SourceFile */ || node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 257 /* ModuleDeclaration */; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -77523,7 +79895,7 @@ var ts; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { @@ -77544,12 +79916,15 @@ var ts; } } function checkExportAssignment(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + var illegalContextMessage = node.isExportEquals + ? ts.Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration + : ts.Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration; + if (checkGrammarModuleElementContext(node, illegalContextMessage)) { // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 297 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 256 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 298 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 257 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -77609,7 +79984,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { + if (declaration && !isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -77633,10 +80008,12 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + if (!isDuplicatedCommonJSExport(declarations)) { + for (var _i = 0, _b = declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } } } } @@ -77645,6 +80022,11 @@ var ts; links.exportsChecked = true; } } + function isDuplicatedCommonJSExport(declarations) { + return declarations + && declarations.length > 1 + && declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && (ts.isExportsIdentifier(d.expression) || ts.isModuleExportsAccessExpression(d.expression)); }); + } function checkSourceElement(node) { if (node) { var saveCurrentNode = currentNode; @@ -77666,171 +80048,171 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 251 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } - if (kind >= 232 /* FirstStatement */ && kind <= 248 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) { + if (kind >= 233 /* FirstStatement */ && kind <= 249 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) { errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected); } switch (kind) { - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return checkTypeParameter(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return checkParameter(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return checkPropertyDeclaration(node); - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: return checkPropertySignature(node); - case 175 /* ConstructorType */: - case 174 /* FunctionType */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 176 /* ConstructorType */: + case 175 /* FunctionType */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return checkSignatureDeclaration(node); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: return checkMethodDeclaration(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return checkConstructorDeclaration(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return checkAccessorDeclaration(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return checkTypeReferenceNode(node); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return checkTypePredicate(node); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return checkTypeQuery(node); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return checkTypeLiteral(node); - case 178 /* ArrayType */: + case 179 /* ArrayType */: return checkArrayType(node); - case 179 /* TupleType */: + case 180 /* TupleType */: return checkTupleType(node); - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 186 /* ParenthesizedType */: - case 180 /* OptionalType */: - case 181 /* RestType */: + case 187 /* ParenthesizedType */: + case 181 /* OptionalType */: + case 182 /* RestType */: return checkSourceElement(node.type); - case 187 /* ThisType */: + case 188 /* ThisType */: return checkThisType(node); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return checkTypeOperator(node); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return checkConditionalType(node); - case 185 /* InferType */: + case 186 /* InferType */: return checkInferType(node); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: return checkTemplateLiteralType(node); - case 195 /* ImportType */: + case 196 /* ImportType */: return checkImportType(node); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return checkNamedTupleMember(node); - case 315 /* JSDocAugmentsTag */: + case 318 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 316 /* JSDocImplementsTag */: + case 319 /* JSDocImplementsTag */: return checkJSDocImplementsTag(node); - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return checkJSDocTypeAliasTag(node); - case 330 /* JSDocTemplateTag */: + case 334 /* JSDocTemplateTag */: return checkJSDocTemplateTag(node); - case 329 /* JSDocTypeTag */: + case 333 /* JSDocTypeTag */: return checkJSDocTypeTag(node); - case 326 /* JSDocParameterTag */: + case 330 /* JSDocParameterTag */: return checkJSDocParameterTag(node); - case 333 /* JSDocPropertyTag */: + case 337 /* JSDocPropertyTag */: return checkJSDocPropertyTag(node); - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: checkJSDocFunctionType(node); // falls through - case 306 /* JSDocNonNullableType */: - case 305 /* JSDocNullableType */: - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: - case 312 /* JSDocTypeLiteral */: + case 307 /* JSDocNonNullableType */: + case 306 /* JSDocNullableType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: + case 314 /* JSDocTypeLiteral */: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 309 /* JSDocVariadicType */: + case 310 /* JSDocVariadicType */: checkJSDocVariadicType(node); return; - case 301 /* JSDocTypeExpression */: + case 302 /* JSDocTypeExpression */: return checkSourceElement(node.type); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return checkIndexedAccessType(node); - case 190 /* MappedType */: + case 191 /* MappedType */: return checkMappedType(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 230 /* Block */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 258 /* ModuleBlock */: return checkBlock(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return checkVariableStatement(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return checkExpressionStatement(node); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return checkIfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return checkDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return checkWhileStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return checkForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return checkForInStatement(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return checkForOfStatement(node); - case 240 /* ContinueStatement */: - case 241 /* BreakStatement */: + case 241 /* ContinueStatement */: + case 242 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return checkReturnStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return checkWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return checkSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return checkLabeledStatement(node); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return checkThrowStatement(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return checkTryStatement(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return checkBindingElement(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return checkClassDeclaration(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return checkImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return checkExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return checkExportAssignment(node); - case 231 /* EmptyStatement */: - case 248 /* DebuggerStatement */: + case 232 /* EmptyStatement */: + case 249 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 271 /* MissingDeclaration */: + case 272 /* MissingDeclaration */: return checkMissingDeclaration(node); } } @@ -77875,7 +80257,8 @@ var ts; if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. var host_1 = ts.getHostSignatureFromJSDoc(paramTag); - if (host_1) { + var isCallbackTag = ts.isJSDocCallbackTag(paramTag.parent.parent); + if (host_1 || isCallbackTag) { /* Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. So in the following situation we will not create an array type: @@ -77883,7 +80266,9 @@ var ts; function f(a) {} Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. */ - var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var lastParamDeclaration = isCallbackTag + ? ts.lastOrUndefined(paramTag.parent.parent.typeExpression.parameters) + : ts.lastOrUndefined(host_1.parameters); var symbol = ts.getParameterSymbolFromJSDoc(paramTag); if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { @@ -77921,51 +80306,51 @@ var ts; } } function checkDeferredNode(node) { - ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; switch (node.kind) { - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 205 /* TaggedTemplateExpression */: - case 161 /* Decorator */: - case 275 /* JsxOpeningElement */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 206 /* TaggedTemplateExpression */: + case 162 /* Decorator */: + case 276 /* JsxOpeningElement */: // These node kinds are deferred checked when overload resolution fails // To save on work, we ensure the arguments are checked just once, in // a deferred way resolveUntypedCall(node); break; - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: checkAccessorDeclaration(node); break; - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: checkClassExpressionDeferred(node); break; - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: checkJsxSelfClosingElementDeferred(node); break; - case 273 /* JsxElement */: + case 274 /* JsxElement */: checkJsxElementDeferred(node); break; } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkSourceFile(node) { - ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeCheck"); checkSourceFileWorker(node); ts.performance.mark("afterCheck"); ts.performance.measure("Check", "beforeCheck", "afterCheck"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function unusedIsError(kind, isAmbient) { if (isAmbient) { @@ -77994,7 +80379,7 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - ts.clear(potentialWeakMapCollisions); + ts.clear(potentialWeakMapSetCollisions); ts.forEach(node.statements, checkSourceElement); checkSourceElement(node.endOfFileToken); checkDeferredNodes(node); @@ -78024,9 +80409,9 @@ var ts; ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); ts.clear(potentialNewTargetCollisions); } - if (potentialWeakMapCollisions.length) { - ts.forEach(potentialWeakMapCollisions, checkWeakMapCollision); - ts.clear(potentialWeakMapCollisions); + if (potentialWeakMapSetCollisions.length) { + ts.forEach(potentialWeakMapSetCollisions, checkWeakMapSetCollision); + ts.clear(potentialWeakMapSetCollisions); } links.flags |= 1 /* TypeChecked */; } @@ -78098,17 +80483,17 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 297 /* SourceFile */: - if (!ts.isExternalOrCommonJsModule(location)) + case 298 /* SourceFile */: + if (!ts.isExternalModule(location)) break; // falls through - case 256 /* ModuleDeclaration */: - copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); + case 257 /* ModuleDeclaration */: + copyLocallyVisibleExportSymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); @@ -78116,8 +80501,8 @@ var ts; // this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration. // falls through - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: // If we didn't come from static member of class or interface, // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. @@ -78126,7 +80511,7 @@ var ts; copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968 /* Type */); } break; - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -78166,6 +80551,16 @@ var ts; }); } } + function copyLocallyVisibleExportSymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + // Similar condition as in `resolveNameHelper` + if (!ts.getDeclarationOfKind(symbol, 271 /* ExportSpecifier */) && !ts.getDeclarationOfKind(symbol, 270 /* NamespaceExport */)) { + copySymbol(symbol, meaning); + } + }); + } + } } function isTypeDeclarationName(name) { return name.kind === 78 /* Identifier */ && @@ -78174,19 +80569,19 @@ var ts; } function isTypeDeclaration(node) { switch (node.kind) { - case 159 /* TypeParameter */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 160 /* TypeParameter */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return true; - case 262 /* ImportClause */: + case 263 /* ImportClause */: return node.isTypeOnly; - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return node.parent.parent.isTypeOnly; default: return false; @@ -78194,25 +80589,25 @@ var ts; } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(node) { - while (node.parent.kind === 157 /* QualifiedName */) { + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 173 /* TypeReference */; + return node.parent.kind === 174 /* TypeReference */; } function isHeritageClauseElementIdentifier(node) { - while (node.parent.kind === 201 /* PropertyAccessExpression */) { + while (node.parent.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 223 /* ExpressionWithTypeArguments */; + return node.parent.kind === 224 /* ExpressionWithTypeArguments */; } - function isJSDocEntryNameReference(node) { - while (node.parent.kind === 157 /* QualifiedName */) { + function getJSDocEntryNameReference(node) { + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } - while (node.parent.kind === 201 /* PropertyAccessExpression */) { + while (node.parent.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 302 /* JSDocNameReference */; + return ts.isJSDocNameReference(node.parent) ? node.parent : undefined; } function forEachEnclosingClass(node, callback) { var result; @@ -78240,13 +80635,13 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 157 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 158 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 260 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 261 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } - if (nodeOnRightSide.parent.kind === 266 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 267 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; @@ -78272,7 +80667,7 @@ var ts; node = parent; parent = parent.parent; } - if (parent && parent.kind === 195 /* ImportType */ && parent.qualifier === node) { + if (parent && parent.kind === 196 /* ImportType */ && parent.qualifier === node) { return parent; } return undefined; @@ -78282,7 +80677,7 @@ var ts; return getSymbolOfNode(name.parent); } if (ts.isInJSFile(name) && - name.parent.kind === 201 /* PropertyAccessExpression */ && + name.parent.kind === 202 /* PropertyAccessExpression */ && name.parent === name.parent.parent.left) { // Check if this is a special property assignment if (!ts.isPrivateIdentifier(name)) { @@ -78292,7 +80687,7 @@ var ts; } } } - if (name.parent.kind === 266 /* ExportAssignment */ && ts.isEntityNameExpression(name)) { + if (name.parent.kind === 267 /* ExportAssignment */ && ts.isEntityNameExpression(name)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(name, /*all meanings*/ 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); @@ -78302,7 +80697,7 @@ var ts; } else if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name) && isInRightSideOfImportOrExportAssignment(name)) { // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(name, 260 /* ImportEqualsDeclaration */); + var importEqualsDeclaration = ts.getAncestor(name, 261 /* ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true); } @@ -78320,7 +80715,7 @@ var ts; if (isHeritageClauseElementIdentifier(name)) { var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. - if (name.parent.kind === 223 /* ExpressionWithTypeArguments */) { + if (name.parent.kind === 224 /* ExpressionWithTypeArguments */) { meaning = 788968 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) { @@ -78336,10 +80731,10 @@ var ts; return entityNameSymbol; } } - if (name.parent.kind === 326 /* JSDocParameterTag */) { + if (name.parent.kind === 330 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(name.parent); } - if (name.parent.kind === 159 /* TypeParameter */ && name.parent.parent.kind === 330 /* JSDocTemplateTag */) { + if (name.parent.kind === 160 /* TypeParameter */ && name.parent.parent.kind === 334 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(name.parent); return typeParameter && typeParameter.symbol; @@ -78356,36 +80751,56 @@ var ts; } return resolveEntityName(name, 111551 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (name.kind === 201 /* PropertyAccessExpression */ || name.kind === 157 /* QualifiedName */) { + else if (name.kind === 202 /* PropertyAccessExpression */ || name.kind === 158 /* QualifiedName */) { var links = getNodeLinks(name); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (name.kind === 201 /* PropertyAccessExpression */) { - checkPropertyAccessExpression(name); + if (name.kind === 202 /* PropertyAccessExpression */) { + checkPropertyAccessExpression(name, 0 /* Normal */); } else { - checkQualifiedName(name); + checkQualifiedName(name, 0 /* Normal */); } return links.resolvedSymbol; } } else if (isTypeReferenceIdentifier(name)) { - var meaning = name.parent.kind === 173 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */; + var meaning = name.parent.kind === 174 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */; return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (isJSDocEntryNameReference(name)) { + var jsdocReference = getJSDocEntryNameReference(name); + if (jsdocReference || ts.isJSDocLink(name.parent)) { var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */; - return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); + var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ false, ts.getHostSignatureFromJSDoc(name)); + if (symbol) { + return symbol; + } + else if (ts.isQualifiedName(name) && ts.isIdentifier(name.left)) { + // resolve C.m as a static member first + var links = getNodeLinks(name); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + checkQualifiedName(name, 0 /* Normal */); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + // then resolve it as an instance member + var s = resolveEntityName(name.left, meaning, /*ignoreErrors*/ false); + if (s) { + var t = getDeclaredTypeOfSymbol(s); + return getPropertyOfType(t, name.right.escapedText); + } + } } - if (name.parent.kind === 172 /* TypePredicate */) { + if (name.parent.kind === 173 /* TypePredicate */) { return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */); } - // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node, ignoreErrors) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } var parent = node.parent; @@ -78408,8 +80823,8 @@ var ts; if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfNameOrPropertyAccessExpression(node); } - else if (parent.kind === 198 /* BindingElement */ && - grandParent.kind === 196 /* ObjectBindingPattern */ && + else if (parent.kind === 199 /* BindingElement */ && + grandParent.kind === 197 /* ObjectBindingPattern */ && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); @@ -78421,8 +80836,8 @@ var ts; switch (node.kind) { case 78 /* Identifier */: case 79 /* PrivateIdentifier */: - case 201 /* PropertyAccessExpression */: - case 157 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: return getSymbolOfNameOrPropertyAccessExpression(node); case 107 /* ThisKeyword */: var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); @@ -78436,14 +80851,14 @@ var ts; return checkExpression(node).symbol; } // falls through - case 187 /* ThisType */: + case 188 /* ThisType */: return getTypeFromThisTypeNode(node).symbol; case 105 /* SuperKeyword */: return checkExpression(node).symbol; case 132 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 166 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 167 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; @@ -78454,7 +80869,7 @@ var ts; // 3). Dynamic import call or require in javascript // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 261 /* ImportDeclaration */ || node.parent.kind === 267 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((node.parent.kind === 262 /* ImportDeclaration */ || node.parent.kind === 268 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || ((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, ignoreErrors); @@ -78476,7 +80891,7 @@ var ts; case 38 /* EqualsGreaterThanToken */: case 83 /* ClassKeyword */: return getSymbolOfNode(node.parent); - case 195 /* ImportType */: + case 196 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined; case 92 /* ExportKeyword */: return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined; @@ -78485,7 +80900,7 @@ var ts; } } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 289 /* ShorthandPropertyAssignment */) { + if (location && location.kind === 290 /* ShorthandPropertyAssignment */) { return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */); } return undefined; @@ -78564,27 +80979,27 @@ var ts; // [ a ] from // [a] = [ some array ...] function getTypeOfAssignmentPattern(expr) { - ts.Debug.assert(expr.kind === 200 /* ObjectLiteralExpression */ || expr.kind === 199 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.kind === 201 /* ObjectLiteralExpression */ || expr.kind === 200 /* ArrayLiteralExpression */); // If this is from "for of" // for ( { a } of elems) { // } - if (expr.parent.kind === 239 /* ForOfStatement */) { + if (expr.parent.kind === 240 /* ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 216 /* BinaryExpression */) { + if (expr.parent.kind === 217 /* BinaryExpression */) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 288 /* PropertyAssignment */) { - var node_2 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); - var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_2) || errorType; - var propertyIndex = ts.indexOfNode(node_2.properties, expr.parent); - return checkObjectLiteralDestructuringPropertyAssignment(node_2, typeOfParentObjectLiteral, propertyIndex); + if (expr.parent.kind === 289 /* PropertyAssignment */) { + var node_3 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); + var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_3) || errorType; + var propertyIndex = ts.indexOfNode(node_3.properties, expr.parent); + return checkObjectLiteralDestructuringPropertyAssignment(node_3, typeOfParentObjectLiteral, propertyIndex); } // Array literal assignment - array destructuring pattern var node = ts.cast(expr.parent, ts.isArrayLiteralExpression); @@ -78628,7 +81043,7 @@ var ts; case 8 /* NumericLiteral */: case 10 /* StringLiteral */: return getLiteralType(name.text); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(name); return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType; default: @@ -78725,6 +81140,7 @@ var ts; // When resolved as an expression identifier, if the given node references an exported entity, return the declaration // node of the exported entity's container. Otherwise, return undefined. function getReferencedExportContainer(nodeIn, prefixLocals) { + var _a; var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { // When resolving the export container for the name of a module or enum @@ -78745,7 +81161,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 297 /* SourceFile */) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && ((_a = parentSymbol_1.valueDeclaration) === null || _a === void 0 ? void 0 : _a.kind) === 298 /* SourceFile */) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -78775,11 +81191,12 @@ var ts; return undefined; } function isSymbolOfDestructuredElementOfCatchBinding(symbol) { - return ts.isBindingElement(symbol.valueDeclaration) - && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 287 /* CatchClause */; + return symbol.valueDeclaration + && ts.isBindingElement(symbol.valueDeclaration) + && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 288 /* CatchClause */; } function isSymbolOfDeclarationWithCollidingName(symbol) { - if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) { + if (symbol.flags & 418 /* BlockScoped */ && symbol.valueDeclaration && !ts.isSourceFile(symbol.valueDeclaration)) { var links = getSymbolLinks(symbol); if (links.isDeclarationWithCollidingName === undefined) { var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); @@ -78807,7 +81224,7 @@ var ts; // they will not collide with anything var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 230 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 231 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -78848,19 +81265,19 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: var symbol = getSymbolOfNode(node) || unknownSymbol; return isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: var exportClause = node.exportClause; return !!exportClause && (ts.isNamespaceExport(exportClause) || ts.some(exportClause.elements, isValueAliasDeclaration)); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return node.expression && node.expression.kind === 78 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; @@ -78869,7 +81286,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 297 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 298 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -78884,7 +81301,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 & 111551 /* Value */) && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; @@ -78892,13 +81309,14 @@ var ts; function isReferencedAliasDeclaration(node, checkChildren) { if (isAliasSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); - if (symbol && getSymbolLinks(symbol).referenced) { + var links = symbol && getSymbolLinks(symbol); + if (links === null || links === void 0 ? void 0 : links.referenced) { return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 if (target && ts.getEffectiveModifierFlags(node) & 1 /* Export */ && target.flags & 111551 /* Value */ && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -78935,13 +81353,13 @@ var ts; !isOptionalParameter(parameter) && !ts.isJSDocParameterTag(parameter) && !!parameter.initializer && - !ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + !ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && - ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameter(parameter) { return !!strictNullChecks && @@ -78976,15 +81394,15 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 291 /* EnumMember */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 292 /* EnumMember */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return true; } return false; } function getConstantValue(node) { - if (node.kind === 291 /* EnumMember */) { + if (node.kind === 292 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -79137,8 +81555,7 @@ var ts; } function isLiteralConstDeclaration(node) { if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 2944 /* Literal */) && isFreshLiteralType(type); + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } @@ -79257,12 +81674,12 @@ var ts; getJsxFragmentFactoryEntity: getJsxFragmentFactoryEntity, getAllAccessorDeclarations: function (accessor) { accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 - var otherKind = accessor.kind === 168 /* SetAccessor */ ? 167 /* GetAccessor */ : 168 /* SetAccessor */; + var otherKind = accessor.kind === 169 /* SetAccessor */ ? 168 /* GetAccessor */ : 169 /* SetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; - var setAccessor = accessor.kind === 168 /* SetAccessor */ ? accessor : otherAccessor; - var getAccessor = accessor.kind === 167 /* GetAccessor */ ? accessor : otherAccessor; + var setAccessor = accessor.kind === 169 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 168 /* GetAccessor */ ? accessor : otherAccessor; return { firstAccessor: firstAccessor, secondAccessor: secondAccessor, @@ -79278,7 +81695,7 @@ var ts; }, getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) { var n = ts.getParseTreeNode(node); - ts.Debug.assert(n && n.kind === 297 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile"); + ts.Debug.assert(n && n.kind === 298 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile"); var sym = getSymbolOfNode(node); if (!sym) { return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled); @@ -79301,11 +81718,13 @@ var ts; var s = _a[_i]; if (s.mergeId) { var merged = getMergedSymbol(s); - for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { - var d = _c[_b]; - var declFile = ts.getSourceFileOfNode(d); - if (declFile === importTarget) { - return true; + if (merged.declarations) { + for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declFile = ts.getSourceFileOfNode(d); + if (declFile === importTarget) { + return true; + } } } } @@ -79313,7 +81732,7 @@ var ts; return false; } function isInHeritageClause(node) { - return node.parent && node.parent.kind === 223 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 286 /* HeritageClause */; + return node.parent && node.parent.kind === 224 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 287 /* HeritageClause */; } // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -79325,7 +81744,7 @@ var ts; // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries var meaning = 788968 /* Type */ | 1920 /* Namespace */; - if ((node.kind === 78 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 201 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { + if ((node.kind === 78 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 202 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { meaning = 111551 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); @@ -79334,10 +81753,7 @@ var ts; // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForSymbol(symbol, meaning) { // program does not have any files with type reference directives - bail out - if (!fileToDirective) { - return undefined; - } - if (!isSymbolFromTypeDeclarationFile(symbol)) { + if (!fileToDirective || !isSymbolFromTypeDeclarationFile(symbol)) { return undefined; } // check what declarations in the symbol can contribute to the target meaning @@ -79376,7 +81792,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 297 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 298 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -79404,12 +81820,12 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = declaration.kind === 256 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 257 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 297 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 298 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -79429,7 +81845,7 @@ var ts; // It is an error for a non-external-module (i.e. script) to declare its own `globalThis`. // We can't use `builtinGlobals` for this due to synthetic expando-namespace generation in JS files. var fileGlobalThisSymbol = file.locals.get("globalThis"); - if (fileGlobalThisSymbol) { + if (fileGlobalThisSymbol === null || fileGlobalThisSymbol === void 0 ? void 0 : fileGlobalThisSymbol.declarations) { for (var _d = 0, _e = fileGlobalThisSymbol.declarations; _d < _e.length; _d++) { var declaration = _e[_d]; diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis")); @@ -79553,6 +81969,16 @@ var ts; if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name); } + else if (helper & 524288 /* ClassPrivateFieldGet */) { + if (!ts.some(getSignaturesOfSymbol(symbol), function (signature) { return getParameterCount(signature) > 3; })) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name, 4); + } + } + else if (helper & 1048576 /* ClassPrivateFieldSet */) { + if (!ts.some(getSignaturesOfSymbol(symbol), function (signature) { return getParameterCount(signature) > 4; })) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name, 5); + } + } } } } @@ -79602,14 +82028,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { - if (node.kind === 165 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + if (node.kind === 166 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 167 /* GetAccessor */ || node.kind === 168 /* SetAccessor */) { + else if (node.kind === 168 /* GetAccessor */ || node.kind === 169 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -79622,24 +82048,41 @@ var ts; if (quickResult !== undefined) { return quickResult; } - var lastStatic, lastDeclare, lastAsync, lastReadonly; + var lastStatic, lastDeclare, lastAsync, lastReadonly, lastOverride; var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; if (modifier.kind !== 142 /* ReadonlyKeyword */) { - if (node.kind === 162 /* PropertySignature */ || node.kind === 164 /* MethodSignature */) { + if (node.kind === 163 /* PropertySignature */ || node.kind === 165 /* MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 171 /* IndexSignature */) { + if (node.kind === 172 /* IndexSignature */ && (modifier.kind !== 123 /* StaticKeyword */ || !ts.isClassLike(node.parent))) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { case 84 /* ConstKeyword */: - if (node.kind !== 255 /* EnumDeclaration */) { + if (node.kind !== 256 /* EnumDeclaration */) { return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(84 /* ConstKeyword */)); } break; + case 156 /* OverrideKeyword */: + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "override"); + } + else if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "async"); + } + flags |= 16384 /* Override */; + lastOverride = modifier; + break; case 122 /* PublicKeyword */: case 121 /* ProtectedKeyword */: case 120 /* PrivateKeyword */: @@ -79647,6 +82090,9 @@ var ts; if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "override"); + } else if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } @@ -79656,7 +82102,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + else if (node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { @@ -79667,7 +82113,7 @@ var ts; return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); } } - else if (ts.isPrivateIdentifierPropertyDeclaration(node)) { + else if (ts.isPrivateIdentifierClassElementDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier); } flags |= ts.modifierToFlag(modifier.kind); @@ -79682,17 +82128,17 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + else if (node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - else if (ts.isPrivateIdentifierPropertyDeclaration(node)) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "static"); + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "override"); } flags |= 32 /* Static */; lastStatic = modifier; @@ -79701,8 +82147,8 @@ var ts; if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 163 /* PropertyDeclaration */ && node.kind !== 162 /* PropertySignature */ && node.kind !== 171 /* IndexSignature */ && node.kind !== 160 /* Parameter */) { - // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. + else if (node.kind !== 164 /* PropertyDeclaration */ && node.kind !== 163 /* PropertySignature */ && node.kind !== 172 /* IndexSignature */ && node.kind !== 161 /* Parameter */) { + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; @@ -79724,14 +82170,14 @@ var ts; else if (ts.isClassLike(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "export"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* Export */; break; case 87 /* DefaultKeyword */: - var container = node.parent.kind === 297 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 256 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 298 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 257 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512 /* Default */; @@ -79743,16 +82189,19 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override"); + } else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 257 /* ModuleBlock */) { + else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 258 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } - else if (ts.isPrivateIdentifierPropertyDeclaration(node)) { + else if (ts.isPrivateIdentifierClassElementDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare"); } flags |= 2 /* Ambient */; @@ -79762,15 +82211,15 @@ var ts; if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 252 /* ClassDeclaration */ && - node.kind !== 175 /* ConstructorType */) { - if (node.kind !== 165 /* MethodDeclaration */ && - node.kind !== 163 /* PropertyDeclaration */ && - node.kind !== 167 /* GetAccessor */ && - node.kind !== 168 /* SetAccessor */) { + if (node.kind !== 253 /* ClassDeclaration */ && + node.kind !== 176 /* ConstructorType */) { + if (node.kind !== 166 /* MethodDeclaration */ && + node.kind !== 164 /* PropertyDeclaration */ && + node.kind !== 168 /* GetAccessor */ && + node.kind !== 169 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 252 /* ClassDeclaration */ && ts.hasSyntacticModifier(node.parent, 128 /* Abstract */))) { + if (!(node.parent.kind === 253 /* ClassDeclaration */ && ts.hasSyntacticModifier(node.parent, 128 /* Abstract */))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -79782,6 +82231,9 @@ var ts; if (flags & 256 /* Async */ && lastAsync) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); } + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override"); + } } if (ts.isNamedDeclaration(node) && node.name.kind === 79 /* PrivateIdentifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract"); @@ -79795,7 +82247,7 @@ var ts; else if (flags & 2 /* Ambient */ || node.parent.flags & 8388608 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } if (flags & 128 /* Abstract */) { @@ -79806,13 +82258,16 @@ var ts; break; } } - if (node.kind === 166 /* Constructor */) { + if (node.kind === 167 /* Constructor */) { if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } if (flags & 128 /* Abstract */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 } + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(lastOverride, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); // TODO: GH#18217 + } else if (flags & 256 /* Async */) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } @@ -79821,13 +82276,13 @@ var ts; } return false; } - else if ((node.kind === 261 /* ImportDeclaration */ || node.kind === 260 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 262 /* ImportDeclaration */ || node.kind === 261 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 160 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 160 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { @@ -79848,38 +82303,38 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 166 /* Constructor */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 171 /* IndexSignature */: - case 256 /* ModuleDeclaration */: - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 160 /* Parameter */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 167 /* Constructor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 172 /* IndexSignature */: + case 257 /* ModuleDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 161 /* Parameter */: return false; default: - if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + if (node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { return false; } switch (node.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return nodeHasAnyModifiersExcept(node, 129 /* AsyncKeyword */); - case 252 /* ClassDeclaration */: - case 175 /* ConstructorType */: + case 253 /* ClassDeclaration */: + case 176 /* ConstructorType */: return nodeHasAnyModifiersExcept(node, 125 /* AbstractKeyword */); - case 253 /* InterfaceDeclaration */: - case 232 /* VariableStatement */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 233 /* VariableStatement */: + case 255 /* TypeAliasDeclaration */: return true; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return nodeHasAnyModifiersExcept(node, 84 /* ConstKeyword */); default: ts.Debug.fail(); @@ -79891,10 +82346,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -80055,7 +82510,7 @@ var ts; if (args) { for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { var arg = args_4[_i]; - if (arg.kind === 222 /* OmittedExpression */) { + if (arg.kind === 223 /* OmittedExpression */) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -80132,20 +82587,20 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 158 /* ComputedPropertyName */) { + if (node.kind !== 159 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 216 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { + if (computedPropertyName.expression.kind === 217 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 251 /* FunctionDeclaration */ || - node.kind === 208 /* FunctionExpression */ || - node.kind === 165 /* MethodDeclaration */); + ts.Debug.assert(node.kind === 252 /* FunctionDeclaration */ || + node.kind === 209 /* FunctionExpression */ || + node.kind === 166 /* MethodDeclaration */); if (node.flags & 8388608 /* Ambient */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -80164,7 +82619,7 @@ var ts; var seen = new ts.Map(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 290 /* SpreadAssignment */) { + if (prop.kind === 291 /* SpreadAssignment */) { if (inDestructuring) { // a rest property cannot be destructured any further var expression = ts.skipParentheses(prop.expression); @@ -80175,24 +82630,24 @@ var ts; continue; } var name = prop.name; - if (name.kind === 158 /* ComputedPropertyName */) { + if (name.kind === 159 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name); } - if (prop.kind === 289 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 290 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern); } if (name.kind === 79 /* PrivateIdentifier */) { - return grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); } // Modifiers are never allowed on properties except for 'async' on a method declaration if (prop.modifiers) { // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 var mod = _c[_b]; - if (mod.kind !== 129 /* AsyncKeyword */ || prop.kind !== 165 /* MethodDeclaration */) { + if (mod.kind !== 129 /* AsyncKeyword */ || prop.kind !== 166 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } @@ -80207,10 +82662,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 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); // falls through - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -80218,13 +82673,13 @@ var ts; } currentKind = 4 /* PropertyAssignment */; break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: currentKind = 8 /* Method */; break; - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: currentKind = 1 /* GetAccessor */; break; - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: currentKind = 2 /* SetAccessor */; break; default: @@ -80259,11 +82714,12 @@ var ts; } } function checkGrammarJsxElement(node) { + checkGrammarJsxName(node.tagName); checkGrammarTypeArguments(node, node.typeArguments); var seen = new ts.Map(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 282 /* JsxSpreadAttribute */) { + if (attr.kind === 283 /* JsxSpreadAttribute */) { continue; } var name = attr.name, initializer = attr.initializer; @@ -80273,11 +82729,32 @@ var ts; else { return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - if (initializer && initializer.kind === 283 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 284 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } } + function checkGrammarJsxName(node) { + if (ts.isPropertyAccessExpression(node)) { + var propName = node; + do { + var check_1 = checkGrammarJsxNestedIdentifier(propName.name); + if (check_1) { + return check_1; + } + propName = propName.expression; + } while (ts.isPropertyAccessExpression(propName)); + var check = checkGrammarJsxNestedIdentifier(propName); + if (check) { + return check; + } + } + function checkGrammarJsxNestedIdentifier(name) { + if (ts.isIdentifier(name) && ts.idText(name).indexOf(":") !== -1) { + return grammarErrorOnNode(name, ts.Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names); + } + } + } function checkGrammarJsxExpression(node) { if (node.expression && ts.isCommaSequence(node.expression)) { return grammarErrorOnNode(node.expression, ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array); @@ -80287,25 +82764,37 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 239 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { - if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) { - // use of 'for-await-of' in non-async function + if (forInOrOfStatement.kind === 240 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if (!(forInOrOfStatement.flags & 32768 /* AwaitContext */)) { var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement); - if (!hasParseDiagnostics(sourceFile)) { - var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); - var func = ts.getContainingFunction(forInOrOfStatement); - if (func && func.kind !== 166 /* Constructor */) { - ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); - var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); - ts.addRelatedInfo(diagnostic, relatedInfo); - } - diagnostics.add(diagnostic); - return true; + if (ts.isInTopLevelContext(forInOrOfStatement)) { + if (!hasParseDiagnostics(sourceFile)) { + if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module)); + } + if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher)); + } + } + } + else { + // use of 'for-await-of' in non-async function + if (!hasParseDiagnostics(sourceFile)) { + var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); + var func = ts.getContainingFunction(forInOrOfStatement); + if (func && func.kind !== 167 /* Constructor */) { + ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); + var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); + ts.addRelatedInfo(diagnostic, relatedInfo); + } + diagnostics.add(diagnostic); + return true; + } } return false; } } - if (forInOrOfStatement.initializer.kind === 250 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 251 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -80320,20 +82809,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 239 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 239 /* ForInStatement */ ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 239 /* ForInStatement */ ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -80343,26 +82832,34 @@ var ts; return false; } function checkGrammarAccessor(accessor) { - if (!(accessor.flags & 8388608 /* Ambient */)) { + if (!(accessor.flags & 8388608 /* Ambient */) && (accessor.parent.kind !== 178 /* TypeLiteral */) && (accessor.parent.kind !== 254 /* InterfaceDeclaration */)) { if (languageVersion < 1 /* ES5 */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } + if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(accessor.name)) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } if (accessor.body === undefined && !ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) { return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } - if (accessor.body && ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) { - return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + if (accessor.body) { + if (ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + if (accessor.parent.kind === 178 /* TypeLiteral */ || accessor.parent.kind === 254 /* InterfaceDeclaration */) { + return grammarErrorOnNode(accessor.body, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } } if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, accessor.kind === 167 /* GetAccessor */ ? + return grammarErrorOnNode(accessor.name, accessor.kind === 168 /* GetAccessor */ ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - if (accessor.kind === 168 /* SetAccessor */) { + if (accessor.kind === 169 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -80384,10 +82881,10 @@ var ts; * A set accessor has one parameter or a `this` parameter and one more parameter. */ function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 167 /* GetAccessor */ ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 168 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 167 /* GetAccessor */ ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 168 /* GetAccessor */ ? 1 : 2)) { return ts.getThisParameter(accessor); } } @@ -80405,7 +82902,7 @@ var ts; } } switch (parent.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: var decl = parent; if (decl.name.kind !== 78 /* Identifier */) { return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); @@ -80417,13 +82914,13 @@ var ts; return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); } break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: if (!ts.hasSyntacticModifier(parent, 32 /* Static */) || !ts.hasEffectiveModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: if (!ts.hasSyntacticModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } @@ -80433,7 +82930,7 @@ var ts; } } else if (node.operator === 142 /* ReadonlyKeyword */) { - if (node.type.kind !== 178 /* ArrayType */ && node.type.kind !== 179 /* TupleType */) { + if (node.type.kind !== 179 /* ArrayType */ && node.type.kind !== 180 /* TupleType */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(148 /* SymbolKeyword */)); } } @@ -80447,8 +82944,8 @@ var ts; if (checkGrammarFunctionLikeDeclaration(node)) { return true; } - if (node.kind === 165 /* MethodDeclaration */) { - if (node.parent.kind === 200 /* ObjectLiteralExpression */) { + if (node.kind === 166 /* MethodDeclaration */) { + if (node.parent.kind === 201 /* ObjectLiteralExpression */) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 129 /* AsyncKeyword */)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -80468,6 +82965,9 @@ var ts; } } if (ts.isClassLike(node.parent)) { + if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) { + return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } // Technically, computed properties in ambient contexts is disallowed // for property declarations and accessors too, not just methods. // However, property declarations disallow computed names in general, @@ -80476,14 +82976,14 @@ var ts; if (node.flags & 8388608 /* Ambient */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.kind === 165 /* MethodDeclaration */ && !node.body) { + else if (node.kind === 166 /* MethodDeclaration */ && !node.body) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 253 /* InterfaceDeclaration */) { + else if (node.parent.kind === 254 /* InterfaceDeclaration */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 177 /* TypeLiteral */) { + else if (node.parent.kind === 178 /* TypeLiteral */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } @@ -80494,11 +82994,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: if (node.label && current.label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 240 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 241 /* ContinueStatement */ && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -80506,8 +83006,8 @@ var ts; return false; } break; - case 244 /* SwitchStatement */: - if (node.kind === 241 /* BreakStatement */ && !node.label) { + case 245 /* SwitchStatement */: + if (node.kind === 242 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -80522,13 +83022,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 241 /* BreakStatement */ + var message = node.kind === 242 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 241 /* BreakStatement */ + var message = node.kind === 242 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -80552,12 +83052,12 @@ var ts; } function isStringOrNumberLiteralExpression(expr) { return ts.isStringOrNumericLiteralLike(expr) || - expr.kind === 214 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && + expr.kind === 215 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } function isBigIntLiteralExpression(expr) { return expr.kind === 9 /* BigIntLiteral */ || - expr.kind === 214 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && + expr.kind === 215 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && expr.operand.kind === 9 /* BigIntLiteral */; } function isSimpleLiteralEnumReference(expr) { @@ -80588,7 +83088,7 @@ var ts; } } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 238 /* ForInStatement */ && node.parent.parent.kind !== 239 /* ForOfStatement */) { + if (node.parent.parent.kind !== 239 /* ForInStatement */ && node.parent.parent.kind !== 240 /* ForOfStatement */) { if (node.flags & 8388608 /* Ambient */) { checkAmbientInitializer(node); } @@ -80601,7 +83101,7 @@ var ts; } } } - if (node.exclamationToken && (node.parent.parent.kind !== 232 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) { + if (node.exclamationToken && (node.parent.parent.kind !== 233 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) { var message = node.initializer ? ts.Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type @@ -80669,15 +83169,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 234 /* IfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 243 /* WithStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 235 /* IfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 244 /* WithStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: return false; - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -80762,14 +83262,14 @@ var ts; if (ts.isStringLiteral(node.name) && node.name.text === "constructor") { return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor); } - if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type)) { return true; } if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) { return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); } } - else if (node.parent.kind === 253 /* InterfaceDeclaration */) { + else if (node.parent.kind === 254 /* InterfaceDeclaration */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -80777,7 +83277,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 177 /* TypeLiteral */) { + else if (node.parent.kind === 178 /* TypeLiteral */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -80811,13 +83311,13 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 253 /* InterfaceDeclaration */ || - node.kind === 254 /* TypeAliasDeclaration */ || - node.kind === 261 /* ImportDeclaration */ || - node.kind === 260 /* ImportEqualsDeclaration */ || - node.kind === 267 /* ExportDeclaration */ || - node.kind === 266 /* ExportAssignment */ || - node.kind === 259 /* NamespaceExportDeclaration */ || + if (node.kind === 254 /* InterfaceDeclaration */ || + node.kind === 255 /* TypeAliasDeclaration */ || + node.kind === 262 /* ImportDeclaration */ || + node.kind === 261 /* ImportEqualsDeclaration */ || + node.kind === 268 /* ExportDeclaration */ || + node.kind === 267 /* ExportAssignment */ || + node.kind === 260 /* NamespaceExportDeclaration */ || ts.hasSyntacticModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } @@ -80826,7 +83326,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 232 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 233 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -80849,7 +83349,7 @@ var ts; // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if (node.parent.kind === 230 /* Block */ || node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + if (node.parent.kind === 231 /* Block */ || node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { var links_2 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_2.hasReportedStatementInAmbientContext) { @@ -80871,10 +83371,10 @@ var ts; if (languageVersion >= 1 /* ES5 */) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 191 /* LiteralType */)) { + else if (ts.isChildOfNodeWithKind(node, 192 /* LiteralType */)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 291 /* EnumMember */)) { + else if (ts.isChildOfNodeWithKind(node, 292 /* EnumMember */)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { @@ -80980,7 +83480,7 @@ var ts; } } function findBestTypeForObjectLiteral(source, unionTarget) { - if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) { + if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && someType(unionTarget, isArrayLikeType)) { return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } @@ -81032,6 +83532,10 @@ var ts; // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) { if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) { + var match = getMatchingUnionConstituentForType(target, source); + if (match) { + return match; + } var sourceProperties = getPropertiesOfType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); @@ -81049,33 +83553,19 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 251 /* FunctionDeclaration */ && declaration.kind !== 165 /* MethodDeclaration */) || + return (declaration.kind !== 252 /* FunctionDeclaration */ && declaration.kind !== 166 /* MethodDeclaration */) || !!declaration.body; } /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return ts.isIdentifier(name); default: return ts.isDeclarationName(name); } } - function isSomeImportDeclaration(decl) { - switch (decl.kind) { - case 262 /* ImportClause */: // For default import - case 260 /* ImportEqualsDeclaration */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: // For rename import `x as y` - return true; - case 78 /* Identifier */: - // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 265 /* ImportSpecifier */; - default: - return false; - } - } var JsxNames; (function (JsxNames) { JsxNames.JSX = "JSX"; @@ -81106,7 +83596,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); function visitNode(node, visitor, test, lift) { if (node === undefined || visitor === undefined) { return node; @@ -81295,6 +83784,24 @@ var ts; return updated; } ts.visitFunctionBody = visitFunctionBody; + /** + * Visits an iteration body, adding any block-scoped variables required by the transformation. + */ + function visitIterationBody(body, visitor, context) { + context.startBlockScope(); + var updated = visitNode(body, visitor, ts.isStatement, context.factory.liftToBlock); + var declarations = context.endBlockScope(); + if (ts.some(declarations)) { + if (ts.isBlock(updated)) { + declarations.push.apply(declarations, updated.statements); + return context.factory.updateBlock(updated, declarations); + } + declarations.push(updated); + return context.factory.createBlock(declarations); + } + return updated; + } + ts.visitIterationBody = visitIterationBody; function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor, nodeVisitor) { if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } if (nodeVisitor === void 0) { nodeVisitor = visitNode; } @@ -81303,299 +83810,433 @@ var ts; } var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 156 /* LastToken */) || kind === 187 /* ThisType */) { + if ((kind > 0 /* FirstToken */ && kind <= 157 /* LastToken */) || kind === 188 /* ThisType */) { return node; } var factory = context.factory; switch (kind) { // Names case 78 /* Identifier */: - return factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); - case 157 /* QualifiedName */: + ts.Debug.type(node); + return factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNodeOrTypeParameterDeclaration)); + case 158 /* QualifiedName */: + ts.Debug.type(node); return factory.updateQualifiedName(node, nodeVisitor(node.left, visitor, ts.isEntityName), nodeVisitor(node.right, visitor, ts.isIdentifier)); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: + ts.Debug.type(node); return factory.updateComputedPropertyName(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Signature elements - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: + ts.Debug.type(node); return factory.updateTypeParameterDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode)); - case 160 /* Parameter */: - return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 161 /* Decorator */: + case 161 /* Parameter */: + ts.Debug.type(node); + return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 162 /* Decorator */: + ts.Debug.type(node); return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Type elements - case 162 /* PropertySignature */: - return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 163 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + ts.Debug.type(node); + return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 164 /* PropertyDeclaration */: + ts.Debug.type(node); return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too - nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 164 /* MethodSignature */: - return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 165 /* MethodDeclaration */: - return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 166 /* Constructor */: + nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isQuestionOrExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 165 /* MethodSignature */: + ts.Debug.type(node); + return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 166 /* MethodDeclaration */: + ts.Debug.type(node); + return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 167 /* Constructor */: + ts.Debug.type(node); return factory.updateConstructorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: + ts.Debug.type(node); return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: + ts.Debug.type(node); return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 169 /* CallSignature */: + case 170 /* CallSignature */: + ts.Debug.type(node); return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: + ts.Debug.type(node); return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: + ts.Debug.type(node); return factory.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); // Types - case 172 /* TypePredicate */: - return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor), nodeVisitor(node.parameterName, visitor), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 173 /* TypeReference */: + case 173 /* TypePredicate */: + ts.Debug.type(node); + return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor, ts.isAssertsKeyword), nodeVisitor(node.parameterName, visitor, ts.isIdentifierOrThisTypeNode), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 174 /* TypeReference */: + ts.Debug.type(node); return factory.updateTypeReferenceNode(node, nodeVisitor(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 174 /* FunctionType */: + case 175 /* FunctionType */: + ts.Debug.type(node); return factory.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 175 /* ConstructorType */: + case 176 /* ConstructorType */: + ts.Debug.type(node); return factory.updateConstructorTypeNode(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: + ts.Debug.type(node); return factory.updateTypeQueryNode(node, nodeVisitor(node.exprName, visitor, ts.isEntityName)); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: + ts.Debug.type(node); return factory.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 178 /* ArrayType */: + case 179 /* ArrayType */: + ts.Debug.type(node); return factory.updateArrayTypeNode(node, nodeVisitor(node.elementType, visitor, ts.isTypeNode)); - case 179 /* TupleType */: + case 180 /* TupleType */: + ts.Debug.type(node); return factory.updateTupleTypeNode(node, nodesVisitor(node.elements, visitor, ts.isTypeNode)); - case 180 /* OptionalType */: + case 181 /* OptionalType */: + ts.Debug.type(node); return factory.updateOptionalTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 181 /* RestType */: + case 182 /* RestType */: + ts.Debug.type(node); return factory.updateRestTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 182 /* UnionType */: + case 183 /* UnionType */: + ts.Debug.type(node); return factory.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 183 /* IntersectionType */: + case 184 /* IntersectionType */: + ts.Debug.type(node); return factory.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: + ts.Debug.type(node); return factory.updateConditionalTypeNode(node, nodeVisitor(node.checkType, visitor, ts.isTypeNode), nodeVisitor(node.extendsType, visitor, ts.isTypeNode), nodeVisitor(node.trueType, visitor, ts.isTypeNode), nodeVisitor(node.falseType, visitor, ts.isTypeNode)); - case 185 /* InferType */: + case 186 /* InferType */: + ts.Debug.type(node); return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); - case 195 /* ImportType */: + case 196 /* ImportType */: + ts.Debug.type(node); return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); - case 192 /* NamedTupleMember */: - return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); - case 186 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: + ts.Debug.type(node); + return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isDotDotDotToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isQuestionToken), visitNode(node.type, visitor, ts.isTypeNode)); + case 187 /* ParenthesizedType */: + ts.Debug.type(node); return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: + ts.Debug.type(node); return factory.updateTypeOperatorNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: + ts.Debug.type(node); return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode)); - case 190 /* MappedType */: - return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 191 /* LiteralType */: + case 191 /* MappedType */: + ts.Debug.type(node); + return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 192 /* LiteralType */: + ts.Debug.type(node); return factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression)); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: + ts.Debug.type(node); return factory.updateTemplateLiteralType(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateLiteralTypeSpan)); - case 194 /* TemplateLiteralTypeSpan */: + case 195 /* TemplateLiteralTypeSpan */: + ts.Debug.type(node); return factory.updateTemplateLiteralTypeSpan(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Binding patterns - case 196 /* ObjectBindingPattern */: + case 197 /* ObjectBindingPattern */: + ts.Debug.type(node); return factory.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: + ts.Debug.type(node); return factory.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); - case 198 /* BindingElement */: - return factory.updateBindingElement(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.propertyName, visitor, ts.isPropertyName), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 199 /* BindingElement */: + ts.Debug.type(node); + return factory.updateBindingElement(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.propertyName, visitor, ts.isPropertyName), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.initializer, visitor, ts.isExpression)); // Expression - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: + ts.Debug.type(node); return factory.updateArrayLiteralExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression)); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + ts.Debug.type(node); return factory.updateObjectLiteralExpression(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (node.flags & 32 /* OptionalChain */) { - return factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier)); + ts.Debug.type(node); + return factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodeVisitor(node.name, visitor, ts.isMemberName)); } - return factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isIdentifierOrPrivateIdentifier)); - case 202 /* ElementAccessExpression */: + ts.Debug.type(node); + return factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isMemberName)); + case 203 /* ElementAccessExpression */: if (node.flags & 32 /* OptionalChain */) { - return factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); } + ts.Debug.type(node); return factory.updateElementAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (node.flags & 32 /* OptionalChain */) { - return factory.updateCallChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateCallChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); } + ts.Debug.type(node); return factory.updateCallExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 204 /* NewExpression */: + case 205 /* NewExpression */: + ts.Debug.type(node); return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 205 /* TaggedTemplateExpression */: - return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); - case 206 /* TypeAssertionExpression */: + case 206 /* TaggedTemplateExpression */: + ts.Debug.type(node); + return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); + case 207 /* TypeAssertionExpression */: + ts.Debug.type(node); return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: + ts.Debug.type(node); return factory.updateParenthesizedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 208 /* FunctionExpression */: - return factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 209 /* ArrowFunction */: - return factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, ts.isToken), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 210 /* DeleteExpression */: + case 209 /* FunctionExpression */: + ts.Debug.type(node); + return factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 210 /* ArrowFunction */: + ts.Debug.type(node); + return factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, ts.isEqualsGreaterThanToken), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 211 /* DeleteExpression */: + ts.Debug.type(node); return factory.updateDeleteExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: + ts.Debug.type(node); return factory.updateTypeOfExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: + ts.Debug.type(node); return factory.updateVoidExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: + ts.Debug.type(node); return factory.updateAwaitExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + ts.Debug.type(node); return factory.updatePrefixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression)); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + ts.Debug.type(node); return factory.updatePostfixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression)); - case 216 /* BinaryExpression */: - return factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isToken), nodeVisitor(node.right, visitor, ts.isExpression)); - case 217 /* ConditionalExpression */: - return factory.updateConditionalExpression(node, nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.whenTrue, visitor, ts.isExpression), nodeVisitor(node.colonToken, tokenVisitor, ts.isToken), nodeVisitor(node.whenFalse, visitor, ts.isExpression)); - case 218 /* TemplateExpression */: + case 217 /* BinaryExpression */: + ts.Debug.type(node); + return factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isBinaryOperatorToken), nodeVisitor(node.right, visitor, ts.isExpression)); + case 218 /* ConditionalExpression */: + ts.Debug.type(node); + return factory.updateConditionalExpression(node, nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.whenTrue, visitor, ts.isExpression), nodeVisitor(node.colonToken, tokenVisitor, ts.isColonToken), nodeVisitor(node.whenFalse, visitor, ts.isExpression)); + case 219 /* TemplateExpression */: + ts.Debug.type(node); return factory.updateTemplateExpression(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); - case 219 /* YieldExpression */: - return factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 220 /* SpreadElement */: + case 220 /* YieldExpression */: + ts.Debug.type(node); + return factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.expression, visitor, ts.isExpression)); + case 221 /* SpreadElement */: + ts.Debug.type(node); return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: + ts.Debug.type(node); return factory.updateClassExpression(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: + ts.Debug.type(node); return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 224 /* AsExpression */: + case 225 /* AsExpression */: + ts.Debug.type(node); return factory.updateAsExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: if (node.flags & 32 /* OptionalChain */) { + ts.Debug.type(node); return factory.updateNonNullChain(node, nodeVisitor(node.expression, visitor, ts.isExpression)); } + ts.Debug.type(node); return factory.updateNonNullExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: + ts.Debug.type(node); return factory.updateMetaProperty(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); // Misc - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: + ts.Debug.type(node); return factory.updateTemplateSpan(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element - case 230 /* Block */: + case 231 /* Block */: + ts.Debug.type(node); return factory.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: + ts.Debug.type(node); return factory.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: + ts.Debug.type(node); return factory.updateExpressionStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 234 /* IfStatement */: + case 235 /* IfStatement */: + ts.Debug.type(node); return factory.updateIfStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.thenStatement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.elseStatement, visitor, ts.isStatement, factory.liftToBlock)); - case 235 /* DoStatement */: - return factory.updateDoStatement(node, nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 236 /* WhileStatement */: - return factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 237 /* ForStatement */: - return factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.incrementor, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 238 /* ForInStatement */: - return factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 239 /* ForOfStatement */: - return factory.updateForOfStatement(node, nodeVisitor(node.awaitModifier, tokenVisitor, ts.isToken), nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 240 /* ContinueStatement */: + case 236 /* DoStatement */: + ts.Debug.type(node); + return factory.updateDoStatement(node, visitIterationBody(node.statement, visitor, context), nodeVisitor(node.expression, visitor, ts.isExpression)); + case 237 /* WhileStatement */: + ts.Debug.type(node); + return factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 238 /* ForStatement */: + ts.Debug.type(node); + return factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.incrementor, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 239 /* ForInStatement */: + ts.Debug.type(node); + return factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 240 /* ForOfStatement */: + ts.Debug.type(node); + return factory.updateForOfStatement(node, nodeVisitor(node.awaitModifier, tokenVisitor, ts.isAwaitKeyword), nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 241 /* ContinueStatement */: + ts.Debug.type(node); return factory.updateContinueStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier)); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: + ts.Debug.type(node); return factory.updateBreakStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier)); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: + ts.Debug.type(node); return factory.updateReturnStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 243 /* WithStatement */: + case 244 /* WithStatement */: + ts.Debug.type(node); return factory.updateWithStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: + ts.Debug.type(node); return factory.updateSwitchStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.caseBlock, visitor, ts.isCaseBlock)); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: + ts.Debug.type(node); return factory.updateLabeledStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: + ts.Debug.type(node); return factory.updateThrowStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 247 /* TryStatement */: + case 248 /* TryStatement */: + ts.Debug.type(node); return factory.updateTryStatement(node, nodeVisitor(node.tryBlock, visitor, ts.isBlock), nodeVisitor(node.catchClause, visitor, ts.isCatchClause), nodeVisitor(node.finallyBlock, visitor, ts.isBlock)); - case 249 /* VariableDeclaration */: - return factory.updateVariableDeclaration(node, nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 250 /* VariableDeclarationList */: + case 250 /* VariableDeclaration */: + ts.Debug.type(node); + return factory.updateVariableDeclaration(node, nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.exclamationToken, tokenVisitor, ts.isExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 251 /* VariableDeclarationList */: + ts.Debug.type(node); return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); - case 251 /* FunctionDeclaration */: - return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 252 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: + ts.Debug.type(node); + return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 253 /* ClassDeclaration */: + ts.Debug.type(node); return factory.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: + ts.Debug.type(node); return factory.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: + ts.Debug.type(node); return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: + ts.Debug.type(node); return factory.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); - case 256 /* ModuleDeclaration */: - return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.body, visitor, ts.isModuleBody)); - case 257 /* ModuleBlock */: + case 257 /* ModuleDeclaration */: + ts.Debug.type(node); + return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); + case 258 /* ModuleBlock */: + ts.Debug.type(node); return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: + ts.Debug.type(node); return factory.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: + ts.Debug.type(node); return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: + ts.Debug.type(node); return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: + ts.Debug.type(node); return factory.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression)); - case 262 /* ImportClause */: + case 263 /* ImportClause */: + ts.Debug.type(node); return factory.updateImportClause(node, node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.namedBindings, visitor, ts.isNamedImportBindings)); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: + ts.Debug.type(node); return factory.updateNamespaceImport(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: + ts.Debug.type(node); return factory.updateNamespaceExport(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 264 /* NamedImports */: + case 265 /* NamedImports */: + ts.Debug.type(node); return factory.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: + ts.Debug.type(node); return factory.updateImportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: + ts.Debug.type(node); return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: + ts.Debug.type(node); return factory.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression)); - case 268 /* NamedExports */: + case 269 /* NamedExports */: + ts.Debug.type(node); return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: + ts.Debug.type(node); return factory.updateExportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); // Module references - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: + ts.Debug.type(node); return factory.updateExternalModuleReference(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // JSX - case 273 /* JsxElement */: + case 274 /* JsxElement */: + ts.Debug.type(node); return factory.updateJsxElement(node, nodeVisitor(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingElement, visitor, ts.isJsxClosingElement)); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: + ts.Debug.type(node); return factory.updateJsxSelfClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes)); - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: + ts.Debug.type(node); return factory.updateJsxOpeningElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes)); - case 276 /* JsxClosingElement */: + case 277 /* JsxClosingElement */: + ts.Debug.type(node); return factory.updateJsxClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: + ts.Debug.type(node); return factory.updateJsxFragment(node, nodeVisitor(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingFragment, visitor, ts.isJsxClosingFragment)); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: + ts.Debug.type(node); return factory.updateJsxAttribute(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: + ts.Debug.type(node); return factory.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 282 /* JsxSpreadAttribute */: + case 283 /* JsxSpreadAttribute */: + ts.Debug.type(node); return factory.updateJsxSpreadAttribute(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: + ts.Debug.type(node); return factory.updateJsxExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Clauses - case 284 /* CaseClause */: + case 285 /* CaseClause */: + ts.Debug.type(node); return factory.updateCaseClause(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: + ts.Debug.type(node); return factory.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: + ts.Debug.type(node); return factory.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 287 /* CatchClause */: + case 288 /* CatchClause */: + ts.Debug.type(node); return factory.updateCatchClause(node, nodeVisitor(node.variableDeclaration, visitor, ts.isVariableDeclaration), nodeVisitor(node.block, visitor, ts.isBlock)); // Property assignments - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: + ts.Debug.type(node); return factory.updatePropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + ts.Debug.type(node); return factory.updateShorthandPropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: + ts.Debug.type(node); return factory.updateSpreadAssignment(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Enum - case 291 /* EnumMember */: + case 292 /* EnumMember */: + ts.Debug.type(node); return factory.updateEnumMember(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression)); // Top-level nodes - case 297 /* SourceFile */: + case 298 /* SourceFile */: + ts.Debug.type(node); return factory.updateSourceFile(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 336 /* PartiallyEmittedExpression */: + case 340 /* PartiallyEmittedExpression */: + ts.Debug.type(node); return factory.updatePartiallyEmittedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: + ts.Debug.type(node); return factory.updateCommaListExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -82270,7 +84911,7 @@ var ts; function chainBundle(context, transformSourceFile) { return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - return node.kind === 297 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + return node.kind === 298 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); } function transformBundle(node) { return context.factory.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); @@ -82321,7 +84962,7 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: // import "mod" // import x from "mod" // import * as x from "mod" @@ -82334,13 +84975,13 @@ var ts; hasImportDefault = true; } break; - case 260 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 272 /* ExternalModuleReference */) { + case 261 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 273 /* ExternalModuleReference */) { // import x = require("mod") externalImports.push(node); } break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" @@ -82371,13 +85012,13 @@ var ts; addExportedNamesForExportDeclaration(node); } break; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; } break; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: if (ts.hasSyntacticModifier(node, 1 /* Export */)) { for (var _b = 0, _c = node.declarationList.declarations; _b < _c.length; _b++) { var decl = _c[_b]; @@ -82385,7 +85026,7 @@ var ts; } } break; - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: if (ts.hasSyntacticModifier(node, 1 /* Export */)) { if (ts.hasSyntacticModifier(node, 512 /* Default */)) { // export default function() { } @@ -82405,7 +85046,7 @@ var ts; } } break; - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: if (ts.hasSyntacticModifier(node, 1 /* Export */)) { if (ts.hasSyntacticModifier(node, 512 /* Default */)) { // export default class { } @@ -82499,8 +85140,7 @@ var ts; * any such locations */ function isSimpleInlineableExpression(expression) { - return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression) || - ts.isWellKnownSymbolSyntactically(expression); + return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression); } ts.isSimpleInlineableExpression = isSimpleInlineableExpression; function isCompoundAssignment(kind) { @@ -82579,10 +85219,19 @@ var ts; * @param isStatic A value indicating whether the member should be a static or instance member. */ function isInitializedProperty(member) { - return member.kind === 163 /* PropertyDeclaration */ + return member.kind === 164 /* PropertyDeclaration */ && member.initializer !== undefined; } ts.isInitializedProperty = isInitializedProperty; + /** + * Gets a value indicating whether a class element is a private instance method or accessor. + * + * @param member The class element node. + */ + function isNonStaticMethodOrAccessorWithPrivateName(member) { + return !ts.hasStaticModifier(member) && ts.isMethodOrAccessor(member) && ts.isPrivateIdentifier(member.name); + } + ts.isNonStaticMethodOrAccessorWithPrivateName = isNonStaticMethodOrAccessorWithPrivateName; })(ts || (ts = {})); /*@internal*/ var ts; @@ -82856,8 +85505,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */)) + && !(element.transformFlags & (16384 /* ContainsRestOrSpread */ | 32768 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (16384 /* ContainsRestOrSpread */ | 32768 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor)); } @@ -82923,7 +85572,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 & 16384 /* ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { + if (element.transformFlags & 32768 /* ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { flattenContext.hasTransformedPriorElement = true; var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { @@ -83181,8 +85830,8 @@ var ts; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; // Enable substitution for property/element access to emit const enum values. - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(202 /* ElementAccessExpression */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(203 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; @@ -83208,14 +85857,14 @@ var ts; var applicableSubstitutions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - if (node.kind === 298 /* Bundle */) { + if (node.kind === 299 /* Bundle */) { return transformBundle(node); } return transformSourceFile(node); } function transformBundle(node) { return factory.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 300 /* InputFiles */) { + if (prepend.kind === 301 /* InputFiles */) { return ts.createUnparsedSourceFile(prepend, "js"); } return prepend; @@ -83266,16 +85915,16 @@ var ts; */ function onBeforeVisitNode(node) { switch (node.kind) { - case 297 /* SourceFile */: - case 258 /* CaseBlock */: - case 257 /* ModuleBlock */: - case 230 /* Block */: + case 298 /* SourceFile */: + case 259 /* CaseBlock */: + case 258 /* ModuleBlock */: + case 231 /* Block */: currentLexicalScope = node; currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; - case 252 /* ClassDeclaration */: - case 251 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: if (ts.hasSyntacticModifier(node, 2 /* Ambient */)) { break; } @@ -83287,7 +85936,7 @@ var ts; // These nodes should always have names unless they are default-exports; // however, class declaration parsing allows for undefined names, so syntactically invalid // programs may also have an undefined name. - ts.Debug.assert(node.kind === 252 /* ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* Default */)); + ts.Debug.assert(node.kind === 253 /* ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* Default */)); } if (ts.isClassDeclaration(node)) { // XXX: should probably also cover interfaces and type aliases that can have type variables? @@ -83330,10 +85979,10 @@ var ts; */ function sourceElementVisitorWorker(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 266 /* ExportAssignment */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 267 /* ExportAssignment */: + case 268 /* ExportDeclaration */: return visitElidableStatement(node); default: return visitorWorker(node); @@ -83354,13 +86003,13 @@ var ts; return node; } switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -83380,11 +86029,11 @@ var ts; * @param node The node to visit. */ function namespaceElementVisitorWorker(node) { - if (node.kind === 267 /* ExportDeclaration */ || - node.kind === 261 /* ImportDeclaration */ || - node.kind === 262 /* ImportClause */ || - (node.kind === 260 /* ImportEqualsDeclaration */ && - node.moduleReference.kind === 272 /* ExternalModuleReference */)) { + if (node.kind === 268 /* ExportDeclaration */ || + node.kind === 262 /* ImportDeclaration */ || + node.kind === 263 /* ImportClause */ || + (node.kind === 261 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 273 /* ExternalModuleReference */)) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -83408,26 +86057,26 @@ var ts; */ function classElementVisitorWorker(node) { switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return visitConstructor(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // Property declarations are not TypeScript syntax, but they must be visited // for the decorator transformation. return visitPropertyDeclaration(node); - case 171 /* IndexSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: + case 172 /* IndexSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: // Fallback to the default visit behavior. return visitorWorker(node); - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: return node; default: return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { - if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) { + if (ts.modifierToFlag(node.kind) & 18654 /* TypeScriptModifier */) { return undefined; } else if (currentNamespace && node.kind === 92 /* ExportKeyword */) { @@ -83460,13 +86109,13 @@ var ts; case 142 /* ReadonlyKeyword */: // TypeScript accessibility and readonly modifiers are elided // falls through - case 178 /* ArrayType */: - case 179 /* TupleType */: - case 180 /* OptionalType */: - case 181 /* RestType */: - case 177 /* TypeLiteral */: - case 172 /* TypePredicate */: - case 159 /* TypeParameter */: + case 179 /* ArrayType */: + case 180 /* TupleType */: + case 181 /* OptionalType */: + case 182 /* RestType */: + case 178 /* TypeLiteral */: + case 173 /* TypePredicate */: + case 160 /* TypeParameter */: case 128 /* AnyKeyword */: case 152 /* UnknownKeyword */: case 131 /* BooleanKeyword */: @@ -83475,43 +86124,43 @@ var ts; case 141 /* NeverKeyword */: case 113 /* VoidKeyword */: case 148 /* SymbolKeyword */: - case 175 /* ConstructorType */: - case 174 /* FunctionType */: - case 176 /* TypeQuery */: - case 173 /* TypeReference */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 184 /* ConditionalType */: - case 186 /* ParenthesizedType */: - case 187 /* ThisType */: - case 188 /* TypeOperator */: - case 189 /* IndexedAccessType */: - case 190 /* MappedType */: - case 191 /* LiteralType */: + case 176 /* ConstructorType */: + case 175 /* FunctionType */: + case 177 /* TypeQuery */: + case 174 /* TypeReference */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 185 /* ConditionalType */: + case 187 /* ParenthesizedType */: + case 188 /* ThisType */: + case 189 /* TypeOperator */: + case 190 /* IndexedAccessType */: + case 191 /* MappedType */: + case 192 /* LiteralType */: // TypeScript type nodes are elided. // falls through - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: // TypeScript index signatures are elided. // falls through - case 161 /* Decorator */: + case 162 /* Decorator */: // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. // falls through - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return undefined; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects return visitPropertyDeclaration(node); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 166 /* Constructor */: + case 167 /* Constructor */: return visitConstructor(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return factory.createNotEmittedStatement(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: // This may be a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -83521,7 +86170,7 @@ var ts; // - index signatures // - method overload signatures return visitClassDeclaration(node); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: // This may be a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -83531,35 +86180,35 @@ var ts; // - index signatures // - method overload signatures return visitClassExpression(node); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: // This may be a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause return visitHeritageClause(node); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); - case 160 /* Parameter */: + case 161 /* Parameter */: // This may be a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: @@ -83569,40 +86218,40 @@ var ts; // - type annotations // - this parameters return visitParameter(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: // ParenthesizedExpressions are TypeScript if their expression is a // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return visitNewExpression(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node); - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: return visitJsxJsxOpeningElement(node); default: // node contains some other TypeScript syntax @@ -83656,7 +86305,7 @@ var ts; return facts; } function hasTypeScriptClassSyntax(node) { - return !!(node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */); + return !!(node.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */); } function isClassLikeDeclarationWithTypeScriptSyntax(node) { return ts.some(node.decorators) @@ -84011,12 +86660,12 @@ var ts; */ function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return getAllDecoratorsOfAccessors(node, member); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return getAllDecoratorsOfMethod(member); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -84169,7 +86818,7 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); var descriptor = languageVersion > 0 /* ES3 */ - ? member.kind === 163 /* PropertyDeclaration */ + ? member.kind === 164 /* PropertyDeclaration */ // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it // should not invoke `Object.getOwnPropertyDescriptor`. ? factory.createVoidZero() @@ -84293,10 +86942,10 @@ var ts; */ function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 163 /* PropertyDeclaration */; + return kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 164 /* PropertyDeclaration */; } /** * Determines whether to emit the "design:returntype" metadata based on the node's kind. @@ -84306,7 +86955,7 @@ var ts; * @param node The node to test. */ function shouldAddReturnTypeMetadata(node) { - return node.kind === 165 /* MethodDeclaration */; + return node.kind === 166 /* MethodDeclaration */; } /** * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. @@ -84317,12 +86966,12 @@ var ts; */ function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return ts.getFirstConstructorWithBody(node) !== undefined; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return true; } return false; @@ -84339,15 +86988,15 @@ var ts; */ function serializeTypeOfNode(node) { switch (node.kind) { - case 163 /* PropertyDeclaration */: - case 160 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 161 /* Parameter */: return serializeTypeNode(node.type); - case 168 /* SetAccessor */: - case 167 /* GetAccessor */: + case 169 /* SetAccessor */: + case 168 /* GetAccessor */: return serializeTypeNode(getAccessorTypeNode(node)); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 165 /* MethodDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 166 /* MethodDeclaration */: return factory.createIdentifier("Function"); default: return factory.createVoidZero(); @@ -84384,7 +87033,7 @@ var ts; return factory.createArrayLiteralExpression(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 167 /* GetAccessor */) { + if (container && node.kind === 168 /* GetAccessor */) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -84433,27 +87082,27 @@ var ts; case 150 /* UndefinedKeyword */: case 141 /* NeverKeyword */: return factory.createVoidZero(); - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return serializeTypeNode(node.type); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return factory.createIdentifier("Function"); - case 178 /* ArrayType */: - case 179 /* TupleType */: + case 179 /* ArrayType */: + case 180 /* TupleType */: return factory.createIdentifier("Array"); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: case 131 /* BooleanKeyword */: return factory.createIdentifier("Boolean"); case 147 /* StringKeyword */: return factory.createIdentifier("String"); case 145 /* ObjectKeyword */: return factory.createIdentifier("Object"); - case 191 /* LiteralType */: + case 192 /* LiteralType */: switch (node.literal.kind) { case 10 /* StringLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: return factory.createIdentifier("String"); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: case 8 /* NumericLiteral */: return factory.createIdentifier("Number"); case 9 /* BigIntLiteral */: @@ -84474,37 +87123,37 @@ var ts; return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : factory.createIdentifier("Symbol"); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return serializeTypeReferenceNode(node); - case 183 /* IntersectionType */: - case 182 /* UnionType */: + case 184 /* IntersectionType */: + case 183 /* UnionType */: return serializeTypeList(node.types); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return serializeTypeList([node.trueType, node.falseType]); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: if (node.operator === 142 /* ReadonlyKeyword */) { return serializeTypeNode(node.type); } break; - case 176 /* TypeQuery */: - case 189 /* IndexedAccessType */: - case 190 /* MappedType */: - case 177 /* TypeLiteral */: + case 177 /* TypeQuery */: + case 190 /* IndexedAccessType */: + case 191 /* MappedType */: + case 178 /* TypeLiteral */: case 128 /* AnyKeyword */: case 152 /* UnknownKeyword */: - case 187 /* ThisType */: - case 195 /* ImportType */: + case 188 /* ThisType */: + case 196 /* ImportType */: break; // handle JSDoc types from an invalid parse - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: - case 308 /* JSDocFunctionType */: - case 309 /* JSDocVariadicType */: - case 310 /* JSDocNamepathType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: + case 309 /* JSDocFunctionType */: + case 310 /* JSDocVariadicType */: + case 311 /* JSDocNamepathType */: break; - case 305 /* JSDocNullableType */: - case 306 /* JSDocNonNullableType */: - case 307 /* JSDocOptionalType */: + case 306 /* JSDocNullableType */: + case 307 /* JSDocNonNullableType */: + case 308 /* JSDocOptionalType */: return serializeTypeNode(node.type); default: return ts.Debug.failBadSyntaxKind(node); @@ -84517,13 +87166,13 @@ var ts; var serializedUnion; for (var _i = 0, types_24 = types; _i < types_24.length; _i++) { var typeNode = types_24[_i]; - while (typeNode.kind === 186 /* ParenthesizedType */) { + while (typeNode.kind === 187 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } if (typeNode.kind === 141 /* NeverKeyword */) { continue; // Always elide `never` from the union/intersection if possible } - if (!strictNullChecks && (typeNode.kind === 191 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { + if (!strictNullChecks && (typeNode.kind === 192 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } var serializedIndividual = serializeTypeNode(typeNode); @@ -84633,7 +87282,7 @@ var ts; name.original = undefined; ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node. return name; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return serializeQualifiedNameAsExpression(node); } } @@ -85021,8 +87670,7 @@ var ts; */ function shouldEmitEnumDeclaration(node) { return !ts.isEnumConst(node) - || compilerOptions.preserveConstEnums - || compilerOptions.isolatedModules; + || ts.shouldPreserveConstEnums(compilerOptions); } /** * Visits an enum declaration. @@ -85156,7 +87804,7 @@ var ts; // If we can't find a parse tree node, assume the node is instantiated. return true; } - return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions)); } /** * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` @@ -85207,12 +87855,12 @@ var ts; // enums in any other scope are emitted as a `let` declaration. var statement = factory.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.createVariableDeclarationList([ factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ], currentLexicalScope.kind === 297 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ], currentLexicalScope.kind === 298 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { // Adjust the source map emit to match the old emitter. - if (node.kind === 255 /* EnumDeclaration */) { + if (node.kind === 256 /* EnumDeclaration */) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -85337,7 +87985,7 @@ var ts; var statementsLocation; var blockLocation; if (node.body) { - if (node.body.kind === 257 /* ModuleBlock */) { + if (node.body.kind === 258 /* ModuleBlock */) { saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = node.body.statements; blockLocation = node.body; @@ -85384,13 +88032,13 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (!node.body || node.body.kind !== 257 /* ModuleBlock */) { + if (!node.body || node.body.kind !== 258 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 256 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 257 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -85440,7 +88088,7 @@ var ts; * @param node The named import bindings node. */ function visitNamedImportBindings(node) { - if (node.kind === 263 /* NamespaceImport */) { + if (node.kind === 264 /* NamespaceImport */) { // Elide a namespace import if it is not referenced. return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } @@ -85693,16 +88341,16 @@ var ts; // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to // substitute the names of exported members of a namespace. context.enableSubstitution(78 /* Identifier */); - context.enableSubstitution(289 /* ShorthandPropertyAssignment */); + context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // We need to be notified when entering and exiting namespaces. - context.enableEmitNotification(256 /* ModuleDeclaration */); + context.enableEmitNotification(257 /* ModuleDeclaration */); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 256 /* ModuleDeclaration */; + return ts.getOriginalNode(node).kind === 257 /* ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 255 /* EnumDeclaration */; + return ts.getOriginalNode(node).kind === 256 /* EnumDeclaration */; } /** * Hook for node emit. @@ -85763,9 +88411,9 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return substituteExpressionIdentifier(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return substituteElementAccessExpression(node); } return node; @@ -85787,10 +88435,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_1 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_1, node); - ts.setCommentRange(clone_1, node); - return clone_1; + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -85803,9 +88451,9 @@ var ts; // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container && container.kind !== 297 /* SourceFile */) { - var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 256 /* ModuleDeclaration */) || - (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 255 /* EnumDeclaration */); + if (container && container.kind !== 298 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 257 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 256 /* EnumDeclaration */); if (substitute) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(container), node), /*location*/ node); @@ -85857,10 +88505,12 @@ var ts; */ ClassPropertySubstitutionFlags[ClassPropertySubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; })(ClassPropertySubstitutionFlags || (ClassPropertySubstitutionFlags = {})); - var PrivateIdentifierPlacement; - (function (PrivateIdentifierPlacement) { - PrivateIdentifierPlacement[PrivateIdentifierPlacement["InstanceField"] = 0] = "InstanceField"; - })(PrivateIdentifierPlacement || (PrivateIdentifierPlacement = {})); + var PrivateIdentifierKind; + (function (PrivateIdentifierKind) { + PrivateIdentifierKind["Field"] = "f"; + PrivateIdentifierKind["Method"] = "m"; + PrivateIdentifierKind["Accessor"] = "a"; + })(PrivateIdentifierKind = ts.PrivateIdentifierKind || (ts.PrivateIdentifierKind = {})); /** * Transforms ECMAScript Class Syntax. * TypeScript parameter property syntax is transformed in the TypeScript transformer. @@ -85869,11 +88519,12 @@ var ts; * When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty. */ function transformClassFields(context) { - var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment; + var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, addBlockScopedVariable = context.addBlockScopedVariable; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var shouldTransformPrivateFields = languageVersion < 99 /* ESNext */; + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); + var shouldTransformPrivateElements = languageVersion < 99 /* ESNext */; var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; var enabledSubstitutions; @@ -85894,7 +88545,7 @@ var ts; function transformSourceFile(node) { var options = context.getCompilerOptions(); if (node.isDeclarationFile - || options.useDefineForClassFields && options.target === 99 /* ESNext */) { + || useDefineForClassFields && options.target === 99 /* ESNext */) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -85902,41 +88553,41 @@ var ts; return visited; } function visitor(node) { - if (!(node.transformFlags & 4194304 /* ContainsClassFields */)) + if (!(node.transformFlags & 8388608 /* ContainsClassFields */)) return node; switch (node.kind) { - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: return visitClassLike(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return visitPropertyDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return visitPropertyAccessExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return visitPrefixUnaryExpression(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return visitPostfixUnaryExpression(node, /*valueIsDiscarded*/ false); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node); case 79 /* PrivateIdentifier */: return visitPrivateIdentifier(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitExpressionStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); } return ts.visitEachChild(node, visitor, context); } function visitorDestructuringTarget(node) { switch (node.kind) { - case 200 /* ObjectLiteralExpression */: - case 199 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitAssignmentPattern(node); default: return visitor(node); @@ -85947,7 +88598,7 @@ var ts; * Replace it with an empty identifier to indicate a problem with the code. */ function visitPrivateIdentifier(node) { - if (!shouldTransformPrivateFields) { + if (!shouldTransformPrivateElements) { return node; } return ts.setOriginalNode(factory.createIdentifier(""), node); @@ -85959,20 +88610,19 @@ var ts; */ function classElementVisitor(node) { switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: // Constructors for classes using class fields are transformed in // `visitClassDeclaration` or `visitClassExpression`. return undefined; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: - // Visit the name of the member (if it's a computed property name). - return ts.visitEachChild(node, classElementVisitor, context); - case 163 /* PropertyDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + return visitMethodOrAccessorDeclaration(node); + case 164 /* PropertyDeclaration */: return visitPropertyDeclaration(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: return node; default: return visitor(node); @@ -85997,44 +88647,96 @@ var ts; } return node; } + function visitMethodOrAccessorDeclaration(node) { + ts.Debug.assert(!ts.some(node.decorators)); + if (!shouldTransformPrivateElements || !ts.isPrivateIdentifier(node.name)) { + return ts.visitEachChild(node, classElementVisitor, context); + } + // leave invalid code untransformed + var info = accessPrivateIdentifier(node.name); + ts.Debug.assert(info, "Undeclared private name for property declaration."); + if (!info.isValid) { + return node; + } + var functionName = getHoistedFunctionName(node); + if (functionName) { + getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return !ts.isStaticModifier(m); }), node.asteriskToken, functionName, + /* typeParameters */ undefined, ts.visitParameterList(node.parameters, classElementVisitor, context), + /* type */ undefined, ts.visitFunctionBody(node.body, classElementVisitor, context)))); + } + // remove method declaration from class + return undefined; + } + function getHoistedFunctionName(node) { + ts.Debug.assert(ts.isPrivateIdentifier(node.name)); + var info = accessPrivateIdentifier(node.name); + ts.Debug.assert(info, "Undeclared private name for property declaration."); + if (info.kind === "m" /* Method */) { + return info.methodName; + } + if (info.kind === "a" /* Accessor */) { + if (ts.isGetAccessor(node)) { + return info.getterName; + } + if (ts.isSetAccessor(node)) { + return info.setterName; + } + } + } function visitPropertyDeclaration(node) { ts.Debug.assert(!ts.some(node.decorators)); - if (!shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) { - // Initializer is elided as the field is initialized in transformConstructor. - return factory.updatePropertyDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, - /*questionOrExclamationToken*/ undefined, - /*type*/ undefined, - /*initializer*/ undefined); + if (ts.isPrivateIdentifier(node.name)) { + if (!shouldTransformPrivateElements) { + // Initializer is elided as the field is initialized in transformConstructor. + return factory.updatePropertyDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined); + } + // leave invalid code untransformed + var info = accessPrivateIdentifier(node.name); + ts.Debug.assert(info, "Undeclared private name for property declaration."); + if (!info.isValid) { + return node; + } } // Create a temporary variable to store a computed property name (if necessary). // If it's not inlineable, then we emit an expression after the class which assigns // the property name to the temporary variable. - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { getPendingExpressions().push(expr); } return undefined; } function createPrivateIdentifierAccess(info, receiver) { - receiver = ts.visitNode(receiver, visitor, ts.isExpression); - switch (info.placement) { - case 0 /* InstanceField */: - return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(ts.nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver), info.weakMapName); - default: return ts.Debug.fail("Unexpected private identifier placement"); + return createPrivateIdentifierAccessHelper(info, ts.visitNode(receiver, visitor, ts.isExpression)); + } + function createPrivateIdentifierAccessHelper(info, receiver) { + ts.setCommentRange(receiver, ts.moveRangePos(receiver, -1)); + switch (info.kind) { + case "a" /* Accessor */: + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.getterName); + case "m" /* Method */: + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.methodName); + case "f" /* Field */: + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.variableName); + default: + ts.Debug.assertNever(info, "Unknown private element type"); } } function visitPropertyAccessExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifier(node.name)) { var privateIdentifierInfo = accessPrivateIdentifier(node.name); if (privateIdentifierInfo) { - return ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node); + return ts.setTextRange(ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node), node); } } return ts.visitEachChild(node, visitor, context); } function visitPrefixUnaryExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { var operator = node.operator === 45 /* PlusPlusToken */ ? 39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ? 40 /* MinusToken */ : undefined; @@ -86049,7 +88751,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitPostfixUnaryExpression(node, valueIsDiscarded) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { var operator = node.operator === 45 /* PlusPlusToken */ ? 39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ? 40 /* MinusToken */ : undefined; @@ -86070,7 +88772,7 @@ var ts; } function visitForStatement(node) { if (node.incrementor && ts.isPostfixUnaryExpression(node.incrementor)) { - return factory.updateForStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), visitPostfixUnaryExpression(node.incrementor, /*valueIsDiscarded*/ true), ts.visitNode(node.statement, visitor, ts.isStatement)); + return factory.updateForStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), visitPostfixUnaryExpression(node.incrementor, /*valueIsDiscarded*/ true), ts.visitIterationBody(node.statement, visitor, context)); } return ts.visitEachChild(node, visitor, context); } @@ -86090,16 +88792,21 @@ var ts; return { readExpression: readExpression, initializeExpression: initializeExpression }; } function visitCallExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { // Transform call expressions of private names to properly bind the `this` parameter. var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; + if (ts.isCallChain(node)) { + return factory.updateCallChain(node, factory.createPropertyAccessChain(ts.visitNode(target, visitor), node.questionDotToken, "call"), + /*questionDotToken*/ undefined, + /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); + } return factory.updateCallExpression(node, factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "call"), /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); } return ts.visitEachChild(node, visitor, context); } function visitTaggedTemplateExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) { // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access. var _a = factory.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; return factory.updateTaggedTemplateExpression(node, factory.createCallExpression(factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "bind"), @@ -86109,7 +88816,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitBinaryExpression(node) { - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { if (ts.isDestructuringAssignment(node)) { var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; @@ -86123,29 +88830,31 @@ var ts; if (ts.isAssignmentExpression(node) && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) { var info = accessPrivateIdentifier(node.left.name); if (info) { - return ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node); + return ts.setTextRange(ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node), node); } } } return ts.visitEachChild(node, visitor, context); } function createPrivateIdentifierAssignment(info, receiver, right, operator) { - switch (info.placement) { - case 0 /* InstanceField */: { - return createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator); - } - default: return ts.Debug.fail("Unexpected private identifier placement"); - } - } - function createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator) { receiver = ts.visitNode(receiver, visitor, ts.isExpression); right = ts.visitNode(right, visitor, ts.isExpression); if (ts.isCompoundAssignment(operator)) { var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression; - return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(initializeExpression || readExpression, info.weakMapName, factory.createBinaryExpression(context.getEmitHelperFactory().createClassPrivateFieldGetHelper(readExpression, info.weakMapName), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right)); - } - else { - return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.weakMapName, right); + receiver = initializeExpression || readExpression; + right = factory.createBinaryExpression(createPrivateIdentifierAccessHelper(info, readExpression), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right); + } + ts.setCommentRange(receiver, ts.moveRangePos(receiver, -1)); + switch (info.kind) { + case "a" /* Accessor */: + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, info.setterName); + case "m" /* Method */: + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, + /* f */ undefined); + case "f" /* Field */: + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, info.variableName); + default: + ts.Debug.assertNever(info, "Unknown private element type"); } } /** @@ -86154,25 +88863,43 @@ var ts; function visitClassLike(node) { var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { startPrivateIdentifierEnvironment(); + var name = ts.getNameOfDeclaration(node); + if (name && ts.isIdentifier(name)) { + getPrivateIdentifierEnvironment().className = ts.idText(name); + } + var privateInstanceMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); + if (ts.some(privateInstanceMethodsAndAccessors)) { + getPrivateIdentifierEnvironment().weakSetName = createHoistedVariableForClass("instances", privateInstanceMethodsAndAccessors[0].name); + } } var result = ts.isClassDeclaration(node) ? visitClassDeclaration(node) : visitClassExpression(node); - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { endPrivateIdentifierEnvironment(); } pendingExpressions = savedPendingExpressions; return result; } function doesClassElementNeedTransform(node) { - return ts.isPropertyDeclaration(node) || (shouldTransformPrivateFields && node.name && ts.isPrivateIdentifier(node.name)); + return ts.isPropertyDeclaration(node) || (shouldTransformPrivateElements && node.name && ts.isPrivateIdentifier(node.name)); + } + function getPrivateInstanceMethodsAndAccessors(node) { + return ts.filter(node.members, ts.isNonStaticMethodOrAccessorWithPrivateName); } function visitClassDeclaration(node) { if (!ts.forEach(node.members, doesClassElementNeedTransform)) { return ts.visitEachChild(node, visitor, context); } + var staticProperties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ true); + var pendingPrivateStateAssignment; + if (shouldTransformPrivateElements && ts.some(node.members, function (m) { return ts.hasStaticModifier(m) && !!m.name && ts.isPrivateIdentifier(m.name); })) { + var temp = factory.createTempVariable(hoistVariableDeclaration, /* reservedInNestedScopes */ true); + getPrivateIdentifierEnvironment().classConstructor = factory.cloneNode(temp); + pendingPrivateStateAssignment = factory.createAssignment(temp, factory.getInternalName(node)); + } var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */); var statements = [ @@ -86180,6 +88907,9 @@ var ts; /*decorators*/ undefined, node.modifiers, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)) ]; + if (pendingPrivateStateAssignment) { + getPendingExpressions().unshift(pendingPrivateStateAssignment); + } // Write any pending expressions from elided or moved computed property names if (ts.some(pendingExpressions)) { statements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))); @@ -86189,7 +88919,6 @@ var ts; // From ES6 specification: // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. - var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); if (ts.some(staticProperties)) { addPropertyStatements(statements, staticProperties, factory.getInternalName(node)); } @@ -86207,12 +88936,25 @@ var ts; // class declaration transformation. The VariableStatement visitor will insert // these statements after the class expression variable statement. var isDecoratedClassDeclaration = ts.isClassDeclaration(ts.getOriginalNode(node)); - var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); + var staticProperties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ true); var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */); + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; + var temp; + function createClassTempVar() { + var classCheckFlags = resolver.getNodeCheckFlags(node); + var isClassWithConstructorReference = classCheckFlags & 16777216 /* ClassWithConstructorReference */; + var requiresBlockScopedVar = classCheckFlags & 524288 /* BlockScopedBindingInLoop */; + return factory.createTempVariable(requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, !!isClassWithConstructorReference); + } + if (shouldTransformPrivateElements && ts.some(node.members, function (m) { return ts.hasStaticModifier(m) && !!m.name && ts.isPrivateIdentifier(m.name); })) { + temp = createClassTempVar(); + getPrivateIdentifierEnvironment().classConstructor = factory.cloneNode(temp); + } var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)); - if (ts.some(staticProperties) || ts.some(pendingExpressions)) { + var hasTransformableStatics = ts.some(staticProperties, function (p) { return !!p.initializer || (shouldTransformPrivateElements && ts.isPrivateIdentifier(p.name)); }); + if (hasTransformableStatics || ts.some(pendingExpressions)) { if (isDecoratedClassDeclaration) { ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration."); // Write any pending expressions from elided or moved computed property names @@ -86222,12 +88964,14 @@ var ts; if (pendingStatements && ts.some(staticProperties)) { addPropertyStatements(pendingStatements, staticProperties, factory.getInternalName(node)); } + if (temp) { + return factory.inlineExpressions([factory.createAssignment(temp, classExpression), temp]); + } return classExpression; } else { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; - var temp = factory.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + temp || (temp = createClassTempVar()); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); @@ -86249,14 +88993,17 @@ var ts; return classExpression; } function transformClassMembers(node, isDerivedClass) { - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { // Declare private names. for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (ts.isPrivateIdentifierPropertyDeclaration(member)) { - addPrivateIdentifierToEnvironment(member.name); + if (ts.isPrivateIdentifierClassElementDeclaration(member)) { + addPrivateIdentifierToEnvironment(member); } } + if (ts.some(getPrivateInstanceMethodsAndAccessors(node))) { + createBrandCheckWeakSetForPrivateMethods(); + } } var members = []; var constructor = transformConstructor(node, isDerivedClass); @@ -86266,21 +89013,27 @@ var ts; ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members); } - function isPropertyDeclarationThatRequiresConstructorStatement(member) { - if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* Abstract */)) { + function createBrandCheckWeakSetForPrivateMethods() { + var weakSetName = getPrivateIdentifierEnvironment().weakSetName; + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + getPendingExpressions().push(factory.createAssignment(weakSetName, factory.createNewExpression(factory.createIdentifier("WeakSet"), + /*typeArguments*/ undefined, []))); + } + function isClassElementThatRequiresConstructorStatement(member) { + if (ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* Abstract */)) { return false; } - if (context.getCompilerOptions().useDefineForClassFields) { + if (useDefineForClassFields) { // If we are using define semantics and targeting ESNext or higher, // then we don't need to transform any class properties. return languageVersion < 99 /* ESNext */; } - return ts.isInitializedProperty(member) || shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyDeclaration(member); + return ts.isInitializedProperty(member) || shouldTransformPrivateElements && ts.isPrivateIdentifierClassElementDeclaration(member); } function transformConstructor(node, isDerivedClass) { var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration); - var properties = node.members.filter(isPropertyDeclarationThatRequiresConstructorStatement); - if (!ts.some(properties)) { + var elements = node.members.filter(isClassElementThatRequiresConstructorStatement); + if (!ts.some(elements)) { return constructor; } var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context); @@ -86293,13 +89046,14 @@ var ts; /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { - var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false); if (!useDefineForClassFields) { properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); }); } + var privateMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); + var needsConstructorBody = ts.some(properties) || ts.some(privateMethodsAndAccessors); // Only generate synthetic constructor when there are property initializers to move. - if (!constructor && !ts.some(properties)) { + if (!constructor && !needsConstructorBody) { return ts.visitFunctionBody(/*node*/ undefined, visitor, context); } resumeLexicalEnvironment(); @@ -86338,7 +89092,10 @@ var ts; indexOfFirstStatement = afterParameterProperties; } } - addPropertyStatements(statements, properties, factory.createThis()); + var receiver = factory.createThis(); + // private methods can be called in property initializers, they should execute first. + addMethodStatements(statements, privateMethodsAndAccessors, receiver); + addPropertyStatements(statements, properties, receiver); // Add existing statements, skipping the initial super call. if (constructor) { ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); @@ -86400,27 +89157,30 @@ var ts; function transformProperty(property, receiver) { var _a; // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) - var emitAssignment = !context.getCompilerOptions().useDefineForClassFields; + var emitAssignment = !useDefineForClassFields; var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression) ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name)) : property.name; - if (shouldTransformPrivateFields && ts.isPrivateIdentifier(propertyName)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifier(propertyName)) { var privateIdentifierInfo = accessPrivateIdentifier(propertyName); if (privateIdentifierInfo) { - switch (privateIdentifierInfo.placement) { - case 0 /* InstanceField */: { - return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.weakMapName); + if (privateIdentifierInfo.kind === "f" /* Field */) { + if (!privateIdentifierInfo.isStatic) { + return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.brandCheckIdentifier); + } + else { + return createPrivateStaticFieldInitializer(privateIdentifierInfo.variableName, ts.visitNode(property.initializer, visitor, ts.isExpression)); } } + else { + return undefined; + } } else { ts.Debug.fail("Undeclared private name for property declaration."); } } - if (ts.isPrivateIdentifier(propertyName) && !property.initializer) { - return undefined; - } - if (ts.isPrivateIdentifier(propertyName) && !property.initializer) { + if ((ts.isPrivateIdentifier(propertyName) || ts.hasStaticModifier(property)) && !property.initializer) { return undefined; } var propertyOriginalNode = ts.getOriginalNode(property); @@ -86452,6 +89212,21 @@ var ts; classAliases = []; } } + /** + * Generates brand-check initializer for private methods. + * + * @param statements Statement list that should be used to append new statements. + * @param methods An array of method declarations. + * @param receiver The receiver on which each method should be assigned. + */ + function addMethodStatements(statements, methods, receiver) { + if (!shouldTransformPrivateElements || !ts.some(methods)) { + return; + } + var weakSetName = getPrivateIdentifierEnvironment().weakSetName; + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + statements.push(factory.createExpressionStatement(createPrivateInstanceMethodInitializer(receiver, weakSetName))); + } /** * Hooks node substitutions. * @@ -86487,10 +89262,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_2 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_2, node); - ts.setCommentRange(clone_2, node); - return clone_2; + var clone_3 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_3, node); + ts.setCommentRange(clone_3, node); + return clone_3; } } } @@ -86510,7 +89285,12 @@ var ts; var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left); if (!alreadyTransformed && !inlinable && shouldHoist) { var generatedName = factory.getGeneratedNameForNode(name); - hoistVariableDeclaration(generatedName); + if (resolver.getNodeCheckFlags(name) & 524288 /* BlockScopedBindingInLoop */) { + addBlockScopedVariable(generatedName); + } + else { + hoistVariableDeclaration(generatedName); + } return factory.createAssignment(generatedName, expression); } return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression; @@ -86524,22 +89304,164 @@ var ts; currentPrivateIdentifierEnvironment = privateIdentifierEnvironmentStack.pop(); } function getPrivateIdentifierEnvironment() { - return currentPrivateIdentifierEnvironment || (currentPrivateIdentifierEnvironment = new ts.Map()); + if (!currentPrivateIdentifierEnvironment) { + currentPrivateIdentifierEnvironment = { + className: "", + identifiers: new ts.Map() + }; + } + return currentPrivateIdentifierEnvironment; } function getPendingExpressions() { return pendingExpressions || (pendingExpressions = []); } - function addPrivateIdentifierToEnvironment(name) { - var text = ts.getTextOfPropertyName(name); - var weakMapName = factory.createUniqueName("_" + text.substring(1), 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */); - hoistVariableDeclaration(weakMapName); - getPrivateIdentifierEnvironment().set(name.escapedText, { placement: 0 /* InstanceField */, weakMapName: weakMapName }); - getPendingExpressions().push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), - /*typeArguments*/ undefined, []))); + function addPrivateIdentifierToEnvironment(node) { + var _a; + var text = ts.getTextOfPropertyName(node.name); + var env = getPrivateIdentifierEnvironment(); + var weakSetName = env.weakSetName, classConstructor = env.classConstructor; + var assignmentExpressions = []; + var privateName = node.name.escapedText; + var previousInfo = env.identifiers.get(privateName); + var isValid = !isReservedPrivateName(node.name) && previousInfo === undefined; + if (ts.hasStaticModifier(node)) { + ts.Debug.assert(classConstructor, "weakSetName should be set in private identifier environment"); + if (ts.isPropertyDeclaration(node)) { + var variableName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: "f" /* Field */, + variableName: variableName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + else if (ts.isMethodDeclaration(node)) { + var functionName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: "m" /* Method */, + methodName: functionName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + else if (ts.isGetAccessorDeclaration(node)) { + var getterName = createHoistedVariableForPrivateName(text + "_get", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic && !previousInfo.getterName) { + previousInfo.getterName = getterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: getterName, + setterName: undefined, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + } + else if (ts.isSetAccessorDeclaration(node)) { + var setterName = createHoistedVariableForPrivateName(text + "_set", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic && !previousInfo.setterName) { + previousInfo.setterName = setterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: undefined, + setterName: setterName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + } + else { + ts.Debug.assertNever(node, "Unknown class element type."); + } + } + else if (ts.isPropertyDeclaration(node)) { + var weakMapName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: "f" /* Field */, + brandCheckIdentifier: weakMapName, + isStatic: false, + variableName: undefined, + isValid: isValid, + }); + assignmentExpressions.push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), + /*typeArguments*/ undefined, []))); + } + else if (ts.isMethodDeclaration(node)) { + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + env.identifiers.set(privateName, { + kind: "m" /* Method */, + methodName: createHoistedVariableForPrivateName(text, node), + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + else if (ts.isAccessor(node)) { + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + if (ts.isGetAccessor(node)) { + var getterName = createHoistedVariableForPrivateName(text + "_get", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && !previousInfo.isStatic && !previousInfo.getterName) { + previousInfo.getterName = getterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: getterName, + setterName: undefined, + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + } + else { + var setterName = createHoistedVariableForPrivateName(text + "_set", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && !previousInfo.isStatic && !previousInfo.setterName) { + previousInfo.setterName = setterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: undefined, + setterName: setterName, + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + } + } + else { + ts.Debug.assertNever(node, "Unknown class element type."); + } + (_a = getPendingExpressions()).push.apply(_a, assignmentExpressions); + } + function createHoistedVariableForClass(name, node) { + var className = getPrivateIdentifierEnvironment().className; + var prefix = className ? "_" + className : ""; + var identifier = factory.createUniqueName(prefix + "_" + name, 16 /* Optimistic */); + if (resolver.getNodeCheckFlags(node) & 524288 /* BlockScopedBindingInLoop */) { + addBlockScopedVariable(identifier); + } + else { + hoistVariableDeclaration(identifier); + } + return identifier; + } + function createHoistedVariableForPrivateName(privateName, node) { + return createHoistedVariableForClass(privateName.substring(1), node.name); } function accessPrivateIdentifier(name) { if (currentPrivateIdentifierEnvironment) { - var info = currentPrivateIdentifierEnvironment.get(name.escapedText); + var info = currentPrivateIdentifierEnvironment.identifiers.get(name.escapedText); if (info) { return info; } @@ -86549,7 +89471,7 @@ var ts; if (!env) { continue; } - var info = env.get(name.escapedText); + var info = env.identifiers.get(name.escapedText); if (info) { return info; } @@ -86635,10 +89557,22 @@ var ts; } } ts.transformClassFields = transformClassFields; + function createPrivateStaticFieldInitializer(variableName, initializer) { + return ts.factory.createAssignment(variableName, ts.factory.createObjectLiteralExpression([ + ts.factory.createPropertyAssignment("value", initializer || ts.factory.createVoidZero()) + ])); + } function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) { return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakMapName, "set"), /*typeArguments*/ undefined, [receiver, initializer || ts.factory.createVoidZero()]); } + function createPrivateInstanceMethodInitializer(receiver, weakSetName) { + return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakSetName, "add"), + /*typeArguments*/ undefined, [receiver]); + } + function isReservedPrivateName(node) { + return node.escapedText === "#constructor"; + } })(ts || (ts = {})); /*@internal*/ var ts; @@ -86721,38 +89655,38 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 64 /* ContainsES2017 */) === 0) { + if ((node.transformFlags & 128 /* ContainsES2017 */) === 0) { return node; } switch (node.kind) { case 129 /* AsyncKeyword */: // ES2017 async modifier should be elided for targets < ES2017 return undefined; - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return visitAwaitExpression(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105 /* SuperKeyword */) { capturedSuperProperties.add(node.name.escapedText); } return ts.visitEachChild(node, visitor, context); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: if (capturedSuperProperties && node.expression.kind === 105 /* SuperKeyword */) { hasSuperElementAccess = true; } return ts.visitEachChild(node, visitor, context); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 166 /* Constructor */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 167 /* Constructor */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node); default: return ts.visitEachChild(node, visitor, context); @@ -86761,27 +89695,27 @@ var ts; function asyncBodyVisitor(node) { if (ts.isNodeWithPossibleHoistedDeclaration(node)) { switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatementInAsyncBody(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatementInAsyncBody(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatementInAsyncBody(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatementInAsyncBody(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClauseInAsyncBody(node); - case 230 /* Block */: - case 244 /* SwitchStatement */: - case 258 /* CaseBlock */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: - case 247 /* TryStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 234 /* IfStatement */: - case 243 /* WithStatement */: - case 245 /* LabeledStatement */: + case 231 /* Block */: + case 245 /* SwitchStatement */: + case 259 /* CaseBlock */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 248 /* TryStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 235 /* IfStatement */: + case 244 /* WithStatement */: + case 246 /* LabeledStatement */: return ts.visitEachChild(node, asyncBodyVisitor, context); default: return ts.Debug.assertNever(node, "Unhandled node."); @@ -86823,18 +89757,18 @@ var ts; function visitForInStatementInAsyncBody(node) { return factory.updateForInStatement(node, isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) - : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock)); + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context)); } function visitForOfStatementInAsyncBody(node) { return factory.updateForOfStatement(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) - : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock)); + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context)); } function visitForStatementInAsyncBody(node) { var initializer = node.initializer; // TODO: GH#18217 return factory.updateForStatement(node, isVariableDeclarationListWithCollidingName(initializer) ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false) - : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock)); + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context)); } /** * Visits an AwaitExpression node. @@ -86986,7 +89920,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 209 /* ArrowFunction */; + var isArrowFunction = node.kind === 210 /* ArrowFunction */; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current @@ -87077,17 +90011,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(203 /* CallExpression */); - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(202 /* ElementAccessExpression */); + context.enableSubstitution(204 /* CallExpression */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(203 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(252 /* ClassDeclaration */); - context.enableEmitNotification(165 /* MethodDeclaration */); - context.enableEmitNotification(167 /* GetAccessor */); - context.enableEmitNotification(168 /* SetAccessor */); - context.enableEmitNotification(166 /* Constructor */); + context.enableEmitNotification(253 /* ClassDeclaration */); + context.enableEmitNotification(166 /* MethodDeclaration */); + context.enableEmitNotification(168 /* GetAccessor */); + context.enableEmitNotification(169 /* SetAccessor */); + context.enableEmitNotification(167 /* Constructor */); // We need to be notified when entering the generated accessor arrow functions. - context.enableEmitNotification(232 /* VariableStatement */); + context.enableEmitNotification(233 /* VariableStatement */); } } /** @@ -87135,11 +90069,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return substituteCallExpression(node); } return node; @@ -87171,11 +90105,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 252 /* ClassDeclaration */ - || kind === 166 /* Constructor */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 253 /* ClassDeclaration */ + || kind === 167 /* Constructor */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { @@ -87354,74 +90288,74 @@ var ts; * expression of an `ExpressionStatement`). */ function visitorWorker(node, expressionResultIsUnused) { - if ((node.transformFlags & 32 /* ContainsES2018 */) === 0) { + if ((node.transformFlags & 64 /* ContainsES2018 */) === 0) { return node; } switch (node.kind) { - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return visitAwaitExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitYieldExpression(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitReturnStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node, expressionResultIsUnused); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitCommaListExpression(node, expressionResultIsUnused); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 238 /* ForInStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 239 /* ForInStatement */: return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return visitVoidExpression(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */); - case 160 /* Parameter */: + case 161 /* Parameter */: return visitParameter(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitExpressionStatement(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, expressionResultIsUnused); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105 /* SuperKeyword */) { capturedSuperProperties.add(node.name.escapedText); } return ts.visitEachChild(node, visitor, context); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: if (capturedSuperProperties && node.expression.kind === 105 /* SuperKeyword */) { hasSuperElementAccess = true; } return ts.visitEachChild(node, visitor, context); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); default: return ts.visitEachChild(node, visitor, context); @@ -87457,7 +90391,7 @@ var ts; function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 239 /* ForOfStatement */ && statement.awaitModifier) { + if (statement.kind === 240 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } return factory.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, factory.liftToBlock), node); @@ -87469,7 +90403,7 @@ var ts; var objects = []; for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { var e = elements_4[_i]; - if (e.kind === 290 /* SpreadAssignment */) { + if (e.kind === 291 /* SpreadAssignment */) { if (chunkObject) { objects.push(factory.createObjectLiteralExpression(chunkObject)); chunkObject = undefined; @@ -87478,7 +90412,7 @@ var ts; objects.push(ts.visitNode(target, visitor, ts.isExpression)); } else { - chunkObject = ts.append(chunkObject, e.kind === 288 /* PropertyAssignment */ + chunkObject = ts.append(chunkObject, e.kind === 289 /* PropertyAssignment */ ? factory.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } @@ -87489,7 +90423,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign(__assign({a}, o), {b}); @@ -87512,7 +90446,7 @@ var ts; // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we // end up with `{ a: 1, b: 2, c: 3 }` var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 200 /* ObjectLiteralExpression */) { + if (objects.length && objects[0].kind !== 201 /* ObjectLiteralExpression */) { objects.unshift(factory.createObjectLiteralExpression()); } var expression = objects[0]; @@ -87562,7 +90496,7 @@ var ts; * expression of an `ExpressionStatement`). */ function visitBinaryExpression(node, expressionResultIsUnused) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !expressionResultIsUnused); } if (node.operatorToken.kind === 27 /* CommaToken */) { @@ -87593,7 +90527,7 @@ var ts; function visitCatchClause(node) { if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name) && - node.variableDeclaration.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + node.variableDeclaration.name.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { var name = factory.getGeneratedNameForNode(node.variableDeclaration.name); var updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name); var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */); @@ -87634,14 +90568,14 @@ var ts; } function visitVariableDeclarationWorker(node, exportedVariableStatement) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */, /*rval*/ undefined, exportedVariableStatement); } return ts.visitEachChild(node, visitor, context); } function visitForStatement(node) { - return factory.updateForStatement(node, ts.visitNode(node.initializer, visitorWithUnusedExpressionResult, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitorWithUnusedExpressionResult, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement)); + return factory.updateForStatement(node, ts.visitNode(node.initializer, visitorWithUnusedExpressionResult, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitorWithUnusedExpressionResult, ts.isExpression), ts.visitIterationBody(node.statement, visitor, context)); } function visitVoidExpression(node) { return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context); @@ -87653,7 +90587,7 @@ var ts; */ function visitForOfStatement(node, outermostLabeledStatement) { var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); - if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (node.initializer.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } var result = node.awaitModifier ? @@ -87691,7 +90625,7 @@ var ts; var bodyLocation; var statementsLocation; var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; - var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + var statement = ts.visitIterationBody(node.statement, visitor, context); if (ts.isBlock(statement)) { ts.addRange(statements, statement.statements); bodyLocation = statement; @@ -87753,7 +90687,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return factory.updateParameterDeclaration(node, @@ -87905,7 +90839,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 & 16384 /* ContainsObjectRestOrSpread */) { + if (parameter.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { var temp = factory.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -87925,17 +90859,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(203 /* CallExpression */); - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(202 /* ElementAccessExpression */); + context.enableSubstitution(204 /* CallExpression */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(203 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(252 /* ClassDeclaration */); - context.enableEmitNotification(165 /* MethodDeclaration */); - context.enableEmitNotification(167 /* GetAccessor */); - context.enableEmitNotification(168 /* SetAccessor */); - context.enableEmitNotification(166 /* Constructor */); + context.enableEmitNotification(253 /* ClassDeclaration */); + context.enableEmitNotification(166 /* MethodDeclaration */); + context.enableEmitNotification(168 /* GetAccessor */); + context.enableEmitNotification(169 /* SetAccessor */); + context.enableEmitNotification(167 /* Constructor */); // We need to be notified when entering the generated accessor arrow functions. - context.enableEmitNotification(232 /* VariableStatement */); + context.enableEmitNotification(233 /* VariableStatement */); } } /** @@ -87983,11 +90917,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return substituteCallExpression(node); } return node; @@ -88019,11 +90953,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 252 /* ClassDeclaration */ - || kind === 166 /* Constructor */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 253 /* ClassDeclaration */ + || kind === 167 /* Constructor */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { @@ -88051,11 +90985,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 16 /* ContainsES2019 */) === 0) { + if ((node.transformFlags & 32 /* ContainsES2019 */) === 0) { return node; } switch (node.kind) { - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); @@ -88083,25 +91017,29 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 8 /* ContainsES2020 */) === 0) { + if ((node.transformFlags & 16 /* ContainsES2020 */) === 0) { return node; } switch (node.kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: - case 203 /* CallExpression */: - if (node.flags & 32 /* OptionalChain */) { + case 204 /* CallExpression */: { + var updated = visitNonOptionalCallExpression(node, /*captureThisArg*/ false); + ts.Debug.assertNotNode(updated, ts.isSyntheticReference); + return updated; + } + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + if (ts.isOptionalChain(node)) { var updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false); ts.Debug.assertNotNode(updated, ts.isSyntheticReference); return updated; } return ts.visitEachChild(node, visitor, context); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (node.operatorToken.kind === 60 /* QuestionQuestionToken */) { return transformNullishCoalescingExpression(node); } return ts.visitEachChild(node, visitor, context); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return visitDeleteExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -88143,7 +91081,7 @@ var ts; thisArg = expression; } } - expression = node.kind === 201 /* PropertyAccessExpression */ + expression = node.kind === 202 /* PropertyAccessExpression */ ? factory.updatePropertyAccessExpression(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)) : factory.updateElementAccessExpression(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); return thisArg ? factory.createSyntheticReferenceExpression(expression, thisArg) : expression; @@ -88153,14 +91091,23 @@ var ts; // If `node` is an optional chain, then it is the outermost chain of an optional expression. return visitOptionalExpression(node, captureThisArg, /*isDelete*/ false); } + if (ts.isParenthesizedExpression(node.expression) && ts.isOptionalChain(ts.skipParentheses(node.expression))) { + // capture thisArg for calls of parenthesized optional chains like `(foo?.bar)()` + var expression = visitNonOptionalParenthesizedExpression(node.expression, /*captureThisArg*/ true, /*isDelete*/ false); + var args = ts.visitNodes(node.arguments, visitor, ts.isExpression); + if (ts.isSyntheticReference(expression)) { + return ts.setTextRange(factory.createFunctionCallCall(expression.expression, expression.thisArg, args), node); + } + return factory.updateCallExpression(node, expression, /*typeArguments*/ undefined, args); + } return ts.visitEachChild(node, visitor, context); } function visitNonOptionalExpression(node, captureThisArg, isDelete) { switch (node.kind) { - case 207 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete); - case 203 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg); + case 208 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete); + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete); + case 204 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg); default: return ts.visitNode(node, visitor, ts.isExpression); } } @@ -88179,8 +91126,8 @@ var ts; for (var i = 0; i < chain.length; i++) { var segment = chain[i]; switch (segment.kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: if (i === chain.length - 1 && captureThisArg) { if (!ts.isSimpleCopiableExpression(rightExpression)) { thisArg = factory.createTempVariable(hoistVariableDeclaration); @@ -88190,11 +91137,11 @@ var ts; thisArg = rightExpression; } } - rightExpression = segment.kind === 201 /* PropertyAccessExpression */ + rightExpression = segment.kind === 202 /* PropertyAccessExpression */ ? factory.createPropertyAccessExpression(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)) : factory.createElementAccessExpression(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (i === 0 && leftThisArg) { rightExpression = factory.createFunctionCallCall(rightExpression, leftThisArg.kind === 105 /* SuperKeyword */ ? factory.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); } @@ -88237,7 +91184,7 @@ var ts; /*@internal*/ var ts; (function (ts) { - function transformESNext(context) { + function transformES2021(context) { var hoistVariableDeclaration = context.hoistVariableDeclaration, factory = context.factory; return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { @@ -88247,11 +91194,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 4 /* ContainsESNext */) === 0) { + if ((node.transformFlags & 8 /* ContainsES2021 */) === 0) { return node; } switch (node.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var binaryExpression = node; if (ts.isLogicalOrCoalescingAssignmentExpression(binaryExpression)) { return transformLogicalAssignment(binaryExpression); @@ -88287,6 +91234,29 @@ var ts; return factory.createBinaryExpression(left, nonAssignmentOperator, factory.createParenthesizedExpression(factory.createAssignment(assignmentTarget, right))); } } + ts.transformES2021 = transformES2021; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformESNext(context) { + return ts.chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if ((node.transformFlags & 4 /* ContainsESNext */) === 0) { + return node; + } + switch (node.kind) { + default: + return ts.visitEachChild(node, visitor, context); + } + } + } ts.transformESNext = transformESNext; })(ts || (ts = {})); /*@internal*/ @@ -88397,13 +91367,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 273 /* JsxElement */: + case 274 /* JsxElement */: return visitJsxElement(node, /*isChild*/ false); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ false); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -88413,13 +91383,13 @@ var ts; switch (node.kind) { case 11 /* JsxText */: return visitJsxText(node); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return visitJsxExpression(node); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return visitJsxElement(node, /*isChild*/ true); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ true); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ true); default: return ts.Debug.failBadSyntaxKind(node); @@ -88459,9 +91429,9 @@ var ts; function convertJsxChildrenToChildrenPropObject(children) { var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); if (ts.length(nonWhitespaceChildren) === 1) { - var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]); - return result_13 && factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", result_13) + var result_14 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result_14 && factory.createObjectLiteralExpression([ + factory.createPropertyAssignment("children", result_14) ]); } var result = ts.mapDefined(children, transformJsxChildToExpression); @@ -88537,21 +91507,29 @@ var ts; // When there are no attributes, React wants "null" } else { - // Map spans of JsxAttribute nodes into object literals and spans - // of JsxSpreadAttribute nodes into expressions. - var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread - ? ts.map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); - if (ts.isJsxSpreadAttribute(attrs[0])) { - // We must always emit at least one object literal before a spread - // argument.factory.createObjectLiteral - segments.unshift(factory.createObjectLiteralExpression()); + var target = compilerOptions.target; + if (target && target >= 5 /* ES2018 */) { + objectProperties = factory.createObjectLiteralExpression(ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { + return isSpread ? ts.map(attrs, transformJsxSpreadAttributeToSpreadAssignment) : ts.map(attrs, transformJsxAttributeToObjectLiteralElement); + }))); } - // Either emit one big object literal (no spread attribs), or - // a call to the __assign helper. - objectProperties = ts.singleOrUndefined(segments); - if (!objectProperties) { - objectProperties = emitHelpers().createAssignHelper(segments); + else { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. + var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument.factory.createObjectLiteral + segments.unshift(factory.createObjectLiteralExpression()); + } + // Either emit one big object literal (no spread attribs), or + // a call to the __assign helper. + objectProperties = ts.singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = emitHelpers().createAssignHelper(segments); + } } } var callee = currentFileState.importSpecifier === undefined @@ -88583,6 +91561,9 @@ var ts; } return element; } + function transformJsxSpreadAttributeToSpreadAssignment(node) { + return factory.createSpreadAssignment(ts.visitNode(node.expression, visitor, ts.isExpression)); + } function transformJsxSpreadAttributeToExpression(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } @@ -88602,7 +91583,7 @@ var ts; var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote); return ts.setTextRange(literal, node); } - else if (node.kind === 283 /* JsxExpression */) { + else if (node.kind === 284 /* JsxExpression */) { if (node.expression === undefined) { return factory.createTrue(); } @@ -88696,7 +91677,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 273 /* JsxElement */) { + if (node.kind === 274 /* JsxElement */) { return getTagName(node.openingElement); } else { @@ -88998,11 +91979,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 128 /* ContainsES2016 */) === 0) { + if ((node.transformFlags & 256 /* ContainsES2016 */) === 0) { return node; } switch (node.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -89215,11 +92196,11 @@ var ts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0 - && node.kind === 242 /* ReturnStatement */ + && node.kind === 243 /* ReturnStatement */ && !node.expression; } function isOrMayContainReturnCompletion(node) { - return node.transformFlags & 1048576 /* ContainsHoistedDeclarationOrCompletion */ + return node.transformFlags & 2097152 /* ContainsHoistedDeclarationOrCompletion */ && (ts.isReturnStatement(node) || ts.isIfStatement(node) || ts.isWithStatement(node) @@ -89234,7 +92215,7 @@ var ts; || ts.isBlock(node)); } function shouldVisitNode(node) { - return (node.transformFlags & 256 /* ContainsES2015 */) !== 0 + return (node.transformFlags & 512 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && isOrMayContainReturnCompletion(node)) || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) @@ -89256,65 +92237,65 @@ var ts; switch (node.kind) { case 123 /* StaticKeyword */: return undefined; // elide static keyword - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return visitClassDeclaration(node); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return visitClassExpression(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return visitParameter(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return visitArrowFunction(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return visitFunctionExpression(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitVariableDeclaration(node); case 78 /* Identifier */: return visitIdentifier(node); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return visitVariableDeclarationList(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitSwitchStatement(node); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return visitCaseBlock(node); - case 230 /* Block */: + case 231 /* Block */: return visitBlock(node, /*isFunctionBody*/ false); - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: return visitBreakOrContinueStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node, /*outermostLabeledStatement*/ undefined); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitExpressionStatement(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return visitShorthandPropertyAssignment(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return visitNewExpression(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, expressionResultIsUnused); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node, expressionResultIsUnused); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitCommaListExpression(node, expressionResultIsUnused); case 14 /* NoSubstitutionTemplateLiteral */: case 15 /* TemplateHead */: @@ -89325,30 +92306,30 @@ var ts; return visitStringLiteral(node); case 8 /* NumericLiteral */: return visitNumericLiteral(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return visitTemplateExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitYieldExpression(node); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return visitSpreadElement(node); case 105 /* SuperKeyword */: return visitSuperKeyword(/*isExpressionOfCall*/ false); case 107 /* ThisKeyword */: return visitThisKeyword(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return visitMetaProperty(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return visitAccessorDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitReturnStatement(node); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return visitVoidExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -89438,14 +92419,14 @@ var ts; // it is possible if either // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement - var jump = node.kind === 241 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var jump = node.kind === 242 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; var label = node.label; if (!label) { - if (node.kind === 241 /* BreakStatement */) { + if (node.kind === 242 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; } @@ -89456,7 +92437,7 @@ var ts; } } else { - if (node.kind === 241 /* BreakStatement */) { + if (node.kind === 242 /* BreakStatement */) { labelMarker = "break-" + label.escapedText; setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); } @@ -89768,7 +92749,7 @@ var ts; factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); if (isDerivedClass) { - if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 4096 /* ContainsLexicalThis */)) { + if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 8192 /* ContainsLexicalThis */)) { // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the // following representation: // @@ -89854,11 +92835,11 @@ var ts; */ function isSufficientlyCoveredByReturnStatements(statement) { // A return statement is considered covered. - if (statement.kind === 242 /* ReturnStatement */) { + if (statement.kind === 243 /* ReturnStatement */) { return true; } // An if-statement with two covered branches is covered. - else if (statement.kind === 234 /* IfStatement */) { + else if (statement.kind === 235 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && @@ -89866,7 +92847,7 @@ var ts; } } // A block is covered if it has a last statement which is covered. - else if (statement.kind === 230 /* Block */) { + else if (statement.kind === 231 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -90068,7 +93049,7 @@ var ts; * @param node A node. */ function insertCaptureThisForNodeIfNeeded(statements, node) { - if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 209 /* ArrowFunction */) { + if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 210 /* ArrowFunction */) { insertCaptureThisForNode(statements, node, factory.createThis()); return true; } @@ -90090,22 +93071,22 @@ var ts; if (hierarchyFacts & 16384 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return statements; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // Methods and accessors cannot be constructors, so 'new.target' will // always return 'undefined'. newTarget = factory.createVoidZero(); break; - case 166 /* Constructor */: + case 167 /* Constructor */: // Class constructors can only be called with `new`, so `this.constructor` // should be relatively safe to use. newTarget = factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), "constructor"); break; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: // Functions can be called or constructed, and may have a `this` due to // being a member or when calling an imported function via `other_1.f()`. newTarget = factory.createConditionalExpression(factory.createLogicalAnd(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), factory.createBinaryExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), 101 /* InstanceOfKeyword */, factory.getLocalName(node))), @@ -90140,20 +93121,20 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 166 /* Constructor */: + case 167 /* Constructor */: // Constructors are handled in visitClassExpression/visitClassDeclaration break; default: @@ -90182,7 +93163,7 @@ var ts; var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName); var e; - if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) { + if (!ts.isPrivateIdentifier(propertyName) && ts.getUseDefineForClassFields(context.getCompilerOptions())) { var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName; @@ -90274,7 +93255,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 4096 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { hierarchyFacts |= 32768 /* CapturedLexicalThis */; } var savedConvertedLoopState = convertedLoopState; @@ -90356,7 +93337,7 @@ var ts; : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */)) { + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 252 /* FunctionDeclaration */ || node.kind === 209 /* FunctionExpression */)) { name = factory.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */); @@ -90402,7 +93383,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 209 /* ArrowFunction */); + ts.Debug.assert(node.kind === 210 /* ArrowFunction */); // To align with the old emitter, we use a synthetic end position on the location // for the statement list we synthesize when we down-level an arrow function with // an expression function body. This prevents both comments and source maps from @@ -90563,7 +93544,7 @@ var ts; * @param node A VariableDeclarationList node. */ function visitVariableDeclarationList(node) { - if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 131072 /* ContainsBindingPattern */) { + if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 262144 /* ContainsBindingPattern */) { if (node.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } @@ -90576,7 +93557,7 @@ var ts; ts.setCommentRange(declarationList, node); // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. - if (node.transformFlags & 131072 /* ContainsBindingPattern */ + if (node.transformFlags & 262144 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -90588,8 +93569,8 @@ var ts; // 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]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var node = declarations_9[_i]; pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); end = Math.max(end, node.end); } @@ -90709,14 +93690,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return visitDoOrWhileStatement(node, outermostLabeledStatement); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node, outermostLabeledStatement); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node, outermostLabeledStatement); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -90900,9 +93881,9 @@ var ts; var numInitialProperties = -1, hasComputed = false; for (var i = 0; i < properties.length; i++) { var property = properties[i]; - if ((property.transformFlags & 262144 /* ContainsYield */ && + if ((property.transformFlags & 524288 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) - || (hasComputed = ts.Debug.checkDefined(property.name).kind === 158 /* ComputedPropertyName */)) { + || (hasComputed = ts.Debug.checkDefined(property.name).kind === 159 /* ComputedPropertyName */)) { numInitialProperties = i; break; } @@ -91005,24 +93986,24 @@ var ts; loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts); } else { - var clone_3 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); - loop = factory.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_4 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); + loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); } } else { - var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + loop = factory.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel); } statements.push(loop); return statements; } function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { switch (node.kind) { - case 237 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); - case 238 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); - case 239 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); - case 235 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); - case 236 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + case 238 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 239 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 240 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 236 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 237 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); } } @@ -91047,11 +94028,11 @@ var ts; function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: var initializer = node.initializer; - if (initializer && initializer.kind === 250 /* VariableDeclarationList */) { + if (initializer && initializer.kind === 251 /* VariableDeclarationList */) { loopInitializer = initializer; } break; @@ -91171,7 +94152,7 @@ var ts; */ function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = factory.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 262144 /* ContainsYield */) !== 0; + var containsYield = (node.initializer.transformFlags & 524288 /* ContainsYield */) !== 0; var emitFlags = 0 /* None */; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -91286,7 +94267,7 @@ var ts; var loopBody = factory.createBlock(statements, /*multiLine*/ true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 262144 /* ContainsYield */) !== 0; + var containsYield = (node.statement.transformFlags & 524288 /* ContainsYield */) !== 0; var emitFlags = 524288 /* ReuseTempVariableScope */; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -91459,20 +94440,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -91579,7 +94560,7 @@ var ts; var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (node.kind === 167 /* GetAccessor */) { + if (node.kind === 168 /* GetAccessor */) { updated = factory.updateGetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { @@ -91759,7 +94740,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 & 8192 /* ContainsRestOrSpread */ || + if (node.transformFlags & 16384 /* ContainsRestOrSpread */ || node.expression.kind === 105 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -91767,7 +94748,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 8192 /* ContainsRestOrSpread */) { + if (node.transformFlags & 16384 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -92085,13 +95066,13 @@ var ts; if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { enabledSubstitutions |= 1 /* CapturedThis */; context.enableSubstitution(107 /* ThisKeyword */); - context.enableEmitNotification(166 /* Constructor */); - context.enableEmitNotification(165 /* MethodDeclaration */); - context.enableEmitNotification(167 /* GetAccessor */); - context.enableEmitNotification(168 /* SetAccessor */); - context.enableEmitNotification(209 /* ArrowFunction */); - context.enableEmitNotification(208 /* FunctionExpression */); - context.enableEmitNotification(251 /* FunctionDeclaration */); + context.enableEmitNotification(167 /* Constructor */); + context.enableEmitNotification(166 /* MethodDeclaration */); + context.enableEmitNotification(168 /* GetAccessor */); + context.enableEmitNotification(169 /* SetAccessor */); + context.enableEmitNotification(210 /* ArrowFunction */); + context.enableEmitNotification(209 /* FunctionExpression */); + context.enableEmitNotification(252 /* FunctionDeclaration */); } } /** @@ -92132,10 +95113,10 @@ var ts; */ function isNameOfDeclarationWithCollidingName(node) { switch (node.parent.kind) { - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 249 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 250 /* VariableDeclaration */: return node.parent.name === node && resolver.isDeclarationWithCollidingName(node.parent); } @@ -92217,11 +95198,11 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 233 /* ExpressionStatement */) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 234 /* ExpressionStatement */) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 203 /* CallExpression */) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 204 /* CallExpression */) { return false; } var callTarget = statementExpression.expression; @@ -92229,7 +95210,7 @@ var ts; return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 220 /* SpreadElement */) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 221 /* SpreadElement */) { return false; } var expression = callArgument.expression; @@ -92255,15 +95236,15 @@ var ts; if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(275 /* JsxOpeningElement */); - context.enableEmitNotification(276 /* JsxClosingElement */); - context.enableEmitNotification(274 /* JsxSelfClosingElement */); + context.enableEmitNotification(276 /* JsxOpeningElement */); + context.enableEmitNotification(277 /* JsxClosingElement */); + context.enableEmitNotification(275 /* JsxSelfClosingElement */); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(288 /* PropertyAssignment */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(289 /* PropertyAssignment */); return ts.chainBundle(context, transformSourceFile); /** * Transforms an ES5 source file to ES3. @@ -92282,9 +95263,9 @@ var ts; */ function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 275 /* JsxOpeningElement */: - case 276 /* JsxClosingElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 277 /* JsxClosingElement */: + case 275 /* JsxSelfClosingElement */: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -92582,7 +95563,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 1024 /* ContainsGenerator */) === 0) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -92605,7 +95586,7 @@ var ts; else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) { return visitGenerator(node); } - else if (transformFlags & 512 /* ContainsGenerator */) { + else if (transformFlags & 1024 /* ContainsGenerator */) { return ts.visitEachChild(node, visitor, context); } else { @@ -92619,13 +95600,13 @@ var ts; */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 235 /* DoStatement */: + case 236 /* DoStatement */: return visitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return visitWhileStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -92638,30 +95619,30 @@ var ts; */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return visitFunctionExpression(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return visitAccessorDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: return visitBreakStatement(node); - case 240 /* ContinueStatement */: + case 241 /* ContinueStatement */: return visitContinueStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 262144 /* ContainsYield */) { + if (node.transformFlags & 524288 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 1048576 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (1024 /* ContainsGenerator */ | 2097152 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -92676,23 +95657,23 @@ var ts; */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitCommaListExpression(node); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return visitConditionalExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitYieldExpression(node); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return visitElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -92705,9 +95686,9 @@ var ts; */ function visitGenerator(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return visitFunctionExpression(node); default: return ts.Debug.failBadSyntaxKind(node); @@ -92866,7 +95847,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 262144 /* ContainsYield */) { + if (node.transformFlags & 524288 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -92915,7 +95896,7 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: // [source] // a.b = yield; // @@ -92927,7 +95908,7 @@ var ts; // _a.b = %sent%; target = factory.updatePropertyAccessExpression(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: // [source] // a[b] = yield; // @@ -93321,35 +96302,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 230 /* Block */: + case 231 /* Block */: return transformAndEmitBlock(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return transformAndEmitIfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return transformAndEmitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return transformAndEmitWhileStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return transformAndEmitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return transformAndEmitForInStatement(node); - case 240 /* ContinueStatement */: + case 241 /* ContinueStatement */: return transformAndEmitContinueStatement(node); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: return transformAndEmitBreakStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return transformAndEmitReturnStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return transformAndEmitWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return transformAndEmitThrowStatement(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -93569,7 +96550,7 @@ var ts; var variables = ts.getInitializedVariables(initializer); node = factory.updateForStatement(node, variables.length > 0 ? factory.inlineExpressions(ts.map(variables, transformInitializedVariable)) - : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitIterationBody(node.statement, visitor, context)); } else { node = ts.visitEachChild(node, visitor, context); @@ -93779,7 +96760,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 285 /* DefaultClause */ && defaultClauseIndex === -1) { + if (clause.kind === 286 /* DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -93792,7 +96773,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 284 /* CaseClause */) { + if (clause.kind === 285 /* CaseClause */) { if (containsYield(clause.expression) && pendingClauses.length > 0) { break; } @@ -93924,7 +96905,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 262144 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 524288 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -93957,10 +96938,10 @@ var ts; var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { // TODO(rbuckton): Does this need to be parented? - var clone_5 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); - ts.setSourceMapRange(clone_5, node); - ts.setCommentRange(clone_5, node); - return clone_5; + var clone_6 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -94953,11 +97934,11 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(216 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(214 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(215 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(289 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. - context.enableEmitNotification(297 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(217 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(215 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(216 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(298 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var currentSourceFile; // The current file. @@ -94973,7 +97954,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 2097152 /* ContainsDynamicImport */ || + node.transformFlags & 4194304 /* ContainsDynamicImport */ || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && ts.outFile(compilerOptions)))) { return node; } @@ -95285,23 +98266,23 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return visitClassDeclaration(node); - case 338 /* MergeDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 339 /* EndOfDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); @@ -95310,7 +98291,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 & 2097152 /* ContainsDynamicImport */) && !(node.transformFlags & 1024 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 4194304 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -95328,24 +98309,24 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; switch (elem.kind) { - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: if (destructuringNeedsFlattening(elem.initializer)) { return true; } break; - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: if (destructuringNeedsFlattening(elem.name)) { return true; } break; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: if (destructuringNeedsFlattening(elem.expression)) { return true; } break; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return false; default: ts.Debug.assertNever(elem, "Unhandled object member kind"); } @@ -95380,7 +98361,7 @@ var ts; var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); // Only use the external module name if it differs from the first argument. This allows us to preserve the quote style of the argument on output. var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument; - var containsLexicalThis = !!(node.transformFlags & 4096 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -95873,7 +98854,7 @@ var ts; // // To balance the declaration, add the exports of the elided variable // statement. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 232 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 233 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -95928,10 +98909,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true); @@ -96144,7 +99125,7 @@ var ts; * @param emit A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -96208,10 +99189,10 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return substituteExpressionIdentifier(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return substituteBinaryExpression(node); - case 215 /* PostfixUnaryExpression */: - case 214 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -96231,9 +99212,9 @@ var ts; } return node; } - if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) { + else if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 297 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 298 /* SourceFile */) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), /*location*/ node); } @@ -96308,8 +99289,8 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 215 /* PostfixUnaryExpression */ - ? ts.setTextRange(factory.createBinaryExpression(node.operand, factory.createToken(node.operator === 45 /* PlusPlusToken */ ? 63 /* PlusEqualsToken */ : 64 /* MinusEqualsToken */), factory.createNumericLiteral(1)), + var expression = node.kind === 216 /* PostfixUnaryExpression */ + ? ts.setTextRange(factory.createPrefixUnaryExpression(node.operator, node.operand), /*location*/ node) : node; for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { @@ -96318,6 +99299,12 @@ var ts; noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression); } + if (node.kind === 216 /* PostfixUnaryExpression */) { + noSubstitution[ts.getNodeId(expression)] = true; + expression = node.operator === 45 /* PlusPlusToken */ + ? factory.createSubtract(expression, factory.createNumericLiteral(1)) + : factory.createAdd(expression, factory.createNumericLiteral(1)); + } return expression; } } @@ -96360,12 +99347,12 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers for imported symbols. - context.enableSubstitution(289 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols - context.enableSubstitution(216 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(214 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(215 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(226 /* MetaProperty */); // Substitutes 'import.meta' - context.enableEmitNotification(297 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(217 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(215 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(216 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(227 /* MetaProperty */); // Substitutes 'import.meta' + context.enableEmitNotification(298 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var exportFunctionsMap = []; // The export function associated with a source file. @@ -96385,7 +99372,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 2097152 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 4194304 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -96554,7 +99541,7 @@ var ts; // - Temporary variables will appear at the top rather than at the bottom of the file ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 - var modifiers = node.transformFlags & 524288 /* ContainsAwait */ ? + var modifiers = node.transformFlags & 1048576 /* ContainsAwait */ ? factory.createModifiersFromModifierFlags(256 /* Async */) : undefined; var moduleObject = factory.createObjectLiteralExpression([ @@ -96589,7 +99576,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 267 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 268 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -96679,19 +99666,19 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(factory, entry, currentSourceFile); // TODO: GH#18217 switch (entry.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // falls through - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== undefined); // save import into the local statements.push(factory.createExpressionStatement(factory.createAssignment(importVariableName, parameterName))); break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { if (ts.isNamedExports(entry.exportClause)) { @@ -96750,13 +99737,13 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -96936,7 +99923,7 @@ var ts; function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 - && (enclosingBlockScopedContainer.kind === 297 /* SourceFile */ + && (enclosingBlockScopedContainer.kind === 298 /* SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); } /** @@ -97000,7 +99987,7 @@ var ts; // // To balance the declaration, we defer the exports of the elided variable // statement until we visit this declaration's `EndOfDeclarationMarker`. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 232 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 233 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasSyntacticModifier(node.original, 1 /* Export */); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -97062,10 +100049,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -97245,43 +100232,43 @@ var ts; */ function nestedElementVisitor(node) { switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return visitClassDeclaration(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return visitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return visitWhileStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return visitWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitSwitchStatement(node); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return visitCaseBlock(node); - case 284 /* CaseClause */: + case 285 /* CaseClause */: return visitCaseClause(node); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: return visitDefaultClause(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return visitTryStatement(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); - case 230 /* Block */: + case 231 /* Block */: return visitBlock(node); - case 338 /* MergeDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 339 /* EndOfDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -97295,7 +100282,7 @@ var ts; function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory.updateForStatement(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + node = factory.updateForStatement(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -97307,7 +100294,7 @@ var ts; function visitForInStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory.updateForInStatement(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); + node = factory.updateForInStatement(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -97319,7 +100306,7 @@ var ts; function visitForOfStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory.updateForOfStatement(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); + node = factory.updateForOfStatement(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -97360,7 +100347,7 @@ var ts; * @param node The node to visit. */ function visitDoStatement(node) { - return factory.updateDoStatement(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); + return factory.updateDoStatement(node, ts.visitIterationBody(node.statement, nestedElementVisitor, context), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); } /** * Visits the body of a WhileStatement to hoist declarations. @@ -97368,7 +100355,7 @@ var ts; * @param node The node to visit. */ function visitWhileStatement(node) { - return factory.updateWhileStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); + return factory.updateWhileStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); } /** * Visits the body of a LabeledStatement to hoist declarations. @@ -97469,7 +100456,7 @@ var ts; else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 1024 /* ContainsDestructuringAssignment */) || (node.transformFlags & 2097152 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 4194304 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -97507,7 +100494,7 @@ var ts; return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } /** - * Determines whether the target of a destructuring assigment refers to an exported symbol. + * Determines whether the target of a destructuring assignment refers to an exported symbol. * * @param node The destructuring target. */ @@ -97532,7 +100519,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 297 /* SourceFile */; + return container !== undefined && container.kind === 298 /* SourceFile */; } else { return false; @@ -97565,7 +100552,7 @@ var ts; * @param emitCallback A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -97615,7 +100602,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -97652,12 +100639,12 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return substituteExpressionIdentifier(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return substituteBinaryExpression(node); - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return substituteUnaryExpression(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return substituteMetaProperty(node); } return node; @@ -97751,14 +100738,14 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 215 /* PostfixUnaryExpression */ + var expression = node.kind === 216 /* PostfixUnaryExpression */ ? ts.setTextRange(factory.createPrefixUnaryExpression(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 215 /* PostfixUnaryExpression */) { + if (node.kind === 216 /* PostfixUnaryExpression */) { expression = node.operator === 45 /* PlusPlusToken */ ? factory.createSubtract(preventSubstitution(expression), factory.createNumericLiteral(1)) : factory.createAdd(preventSubstitution(expression), factory.createNumericLiteral(1)); @@ -97786,7 +100773,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); - if (exportContainer && exportContainer.kind === 297 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 298 /* SourceFile */) { exportedNames = ts.append(exportedNames, factory.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -97826,7 +100813,7 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(297 /* SourceFile */); + context.enableEmitNotification(298 /* SourceFile */); context.enableSubstitution(78 /* Identifier */); var helperNameSubstitutions; return ts.chainBundle(context, transformSourceFile); @@ -97858,12 +100845,12 @@ var ts; } function visitor(node) { switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // Elide `import=` as it is not legal with --module ES6 return undefined; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: var exportDecl = node; return visitExportDeclaration(exportDecl); } @@ -97968,7 +100955,8 @@ var ts; ts.isTypeAliasDeclaration(node) || ts.isConstructorDeclaration(node) || ts.isIndexSignatureDeclaration(node) || - ts.isPropertyAccessExpression(node); + ts.isPropertyAccessExpression(node) || + ts.isJSDocTypeAlias(node); } ts.canProduceDiagnostics = canProduceDiagnostics; function createGetSymbolAccessibilityDiagnosticForNodeName(node) { @@ -97997,7 +100985,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.kind === 253 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98026,7 +101014,7 @@ var ts; ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.kind === 253 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98066,14 +101054,14 @@ var ts; else if (ts.isImportEqualsDeclaration(node)) { return getImportEntityNameVisibilityError; } - else if (ts.isTypeAliasDeclaration(node)) { + else if (ts.isTypeAliasDeclaration(node) || ts.isJSDocTypeAlias(node)) { return getTypeAliasDeclarationVisibilityError; } else { return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) { + if (node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98082,8 +101070,8 @@ var ts; } // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. - else if (node.kind === 163 /* PropertyDeclaration */ || node.kind === 201 /* PropertyAccessExpression */ || node.kind === 162 /* PropertySignature */ || - (node.kind === 160 /* Parameter */ && ts.hasSyntacticModifier(node.parent, 8 /* Private */))) { + else if (node.kind === 164 /* PropertyDeclaration */ || node.kind === 202 /* PropertyAccessExpression */ || node.kind === 163 /* PropertySignature */ || + (node.kind === 161 /* Parameter */ && ts.hasSyntacticModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasSyntacticModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -98092,7 +101080,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 252 /* ClassDeclaration */ || node.kind === 160 /* Parameter */) { + else if (node.parent.kind === 253 /* ClassDeclaration */ || node.kind === 161 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98117,7 +101105,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (node.kind === 168 /* SetAccessor */) { + if (node.kind === 169 /* SetAccessor */) { // Getters can infer the return type from the returned expression, but setters cannot, so the // "_from_external_module_1_but_cannot_be_named" case cannot occur. if (ts.hasSyntacticModifier(node, 32 /* Static */)) { @@ -98156,26 +101144,26 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 169 /* CallSignature */: + case 170 /* CallSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasSyntacticModifier(node, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -98183,7 +101171,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.kind === 253 /* ClassDeclaration */) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -98197,7 +101185,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -98222,30 +101210,30 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 170 /* ConstructSignature */: - case 175 /* ConstructorType */: + case 171 /* ConstructSignature */: + case 176 /* ConstructorType */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 169 /* CallSignature */: + case 170 /* CallSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasSyntacticModifier(node.parent, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -98253,7 +101241,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 253 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98266,15 +101254,15 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 251 /* FunctionDeclaration */: - case 174 /* FunctionType */: + case 252 /* FunctionDeclaration */: + case 175 /* FunctionType */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; - case 168 /* SetAccessor */: - case 167 /* GetAccessor */: + case 169 /* SetAccessor */: + case 168 /* GetAccessor */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98288,39 +101276,39 @@ var ts; // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 190 /* MappedType */: + case 191 /* MappedType */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1; break; - case 175 /* ConstructorType */: - case 170 /* ConstructSignature */: + case 176 /* ConstructorType */: + case 171 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 169 /* CallSignature */: + case 170 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasSyntacticModifier(node.parent, 32 /* Static */)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 253 /* ClassDeclaration */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 174 /* FunctionType */: - case 251 /* FunctionDeclaration */: + case 175 /* FunctionType */: + case 252 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -98359,11 +101347,13 @@ var ts; typeName: node.name }; } - function getTypeAliasDeclarationVisibilityError() { + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name + diagnosticMessage: symbolAccessibilityResult.errorModuleName + ? ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2 + : ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: ts.isJSDocTypeAlias(node) ? ts.Debug.checkDefined(node.typeExpression) : node.type, + typeName: ts.isJSDocTypeAlias(node) ? ts.getNameOfDeclaration(node) : node.name, }; } } @@ -98384,7 +101374,7 @@ var ts; } function isInternalDeclaration(node, currentSourceFile) { var parseTreeNode = ts.getParseTreeNode(node); - if (parseTreeNode && parseTreeNode.kind === 160 /* Parameter */) { + if (parseTreeNode && parseTreeNode.kind === 161 /* Parameter */) { var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode); var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined; var text = currentSourceFile.text; @@ -98446,6 +101436,7 @@ var ts; reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; + var errorFallbackNode; var currentSourceFile; var refs; var libs; @@ -98515,8 +101506,8 @@ var ts; recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } function reportInaccessibleUniqueSymbolError() { @@ -98540,35 +101531,38 @@ var ts; } } function reportTruncationError() { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); } } function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { - var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); + var _a; + var primaryDeclaration = (_a = parentSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; }); - for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { - var augmentations = augmentingDeclarations_1[_i]; - context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + if (augmentingDeclarations) { + for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { + var augmentations = augmentingDeclarations_1[_i]; + context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + } } } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; - getSymbolAccessibilityDiagnostic = function (s) { return ({ + getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ diagnosticMessage: s.errorModuleName ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit, errorNode: s.errorNode || sourceFile - }); }; + })); }; var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled); getSymbolAccessibilityDiagnostic = oldDiag; return result; } function transformRoot(node) { - if (node.kind === 297 /* SourceFile */ && node.isDeclarationFile) { + if (node.kind === 298 /* SourceFile */ && node.isDeclarationFile) { return node; } - if (node.kind === 298 /* Bundle */) { + if (node.kind === 299 /* Bundle */) { isBundledEmit = true; refs = new ts.Map(); libs = new ts.Map(); @@ -98598,7 +101592,7 @@ var ts; var updated = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements); return factory.updateSourceFile(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); }), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 300 /* InputFiles */) { + if (prepend.kind === 301 /* InputFiles */) { var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal); hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib; collectReferences(sourceFile, refs); @@ -98690,7 +101684,7 @@ var ts; declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { - var specifier = ts.moduleSpecifiers.getModuleSpecifier(__assign(__assign({}, options), { baseUrl: options.baseUrl && ts.toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }), currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, + var specifier = ts.moduleSpecifiers.getModuleSpecifier(options, currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, /*preferences*/ undefined); if (!ts.pathIsRelative(specifier)) { // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration @@ -98739,7 +101733,7 @@ var ts; return name; } else { - if (name.kind === 197 /* ArrayBindingPattern */) { + if (name.kind === 198 /* ArrayBindingPattern */) { return factory.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); } else { @@ -98747,7 +101741,7 @@ var ts; } } function visitBindingElement(elem) { - if (elem.kind === 222 /* OmittedExpression */) { + if (elem.kind === 223 /* OmittedExpression */) { return elem; } return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); @@ -98785,7 +101779,7 @@ var ts; // Literal const declarations will have an initializer ensured rather than a type return; } - var shouldUseResolverType = node.kind === 160 /* Parameter */ && + var shouldUseResolverType = node.kind === 161 /* Parameter */ && (resolver.isRequiredInitializedParameter(node) || resolver.isOptionalUninitializedParameterProperty(node)); if (type && !shouldUseResolverType) { @@ -98794,7 +101788,7 @@ var ts; if (!ts.getParseTreeNode(node)) { return type ? ts.visitNode(type, visitDeclarationSubtree) : factory.createKeywordTypeNode(128 /* AnyKeyword */); } - if (node.kind === 168 /* SetAccessor */) { + if (node.kind === 169 /* SetAccessor */) { // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) return factory.createKeywordTypeNode(128 /* AnyKeyword */); @@ -98805,12 +101799,12 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); } - if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) { + if (node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */) { return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } - if (node.kind === 160 /* Parameter */ - || node.kind === 163 /* PropertyDeclaration */ - || node.kind === 162 /* PropertySignature */) { + if (node.kind === 161 /* Parameter */ + || node.kind === 164 /* PropertyDeclaration */ + || node.kind === 163 /* PropertySignature */) { if (!node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); @@ -98827,20 +101821,20 @@ var ts; function isDeclarationAndNotVisible(node) { node = ts.getParseTreeNode(node); switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 256 /* ModuleDeclaration */: - case 253 /* InterfaceDeclaration */: - case 252 /* ClassDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: + case 252 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 254 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: return !resolver.isDeclarationVisible(node); // The following should be doing their own visibility checks based on filtering their members - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return !getBindingNameVisible(node); - case 260 /* ImportEqualsDeclaration */: - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: + case 261 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: return false; } return false; @@ -98921,7 +101915,7 @@ var ts; function rewriteModuleSpecifier(parent, input) { if (!input) return undefined; // TODO: GH#18217 - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 256 /* ModuleDeclaration */ && parent.kind !== 195 /* ImportType */); + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 257 /* ModuleDeclaration */ && parent.kind !== 196 /* ImportType */); if (ts.isStringLiteralLike(input)) { if (isBundledEmit) { var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); @@ -98941,7 +101935,7 @@ var ts; function transformImportEqualsDeclaration(decl) { if (!resolver.isDeclarationVisible(decl)) return; - if (decl.moduleReference.kind === 272 /* ExternalModuleReference */) { + if (decl.moduleReference.kind === 273 /* ExternalModuleReference */) { // Rewrite external module names if necessary var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); return factory.updateImportEqualsDeclaration(decl, @@ -98968,7 +101962,7 @@ var ts; return visibleDefaultBinding && factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } - if (decl.importClause.namedBindings.kind === 263 /* NamespaceImport */) { + if (decl.importClause.namedBindings.kind === 264 /* NamespaceImport */) { // Namespace import (optionally with visible default) var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; @@ -99063,7 +102057,7 @@ var ts; // We'd see a TDZ violation at runtime var canProduceDiagnostic = ts.canProduceDiagnostics(input); var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; - var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 177 /* TypeLiteral */ || input.kind === 190 /* MappedType */) && input.parent.kind !== 254 /* TypeAliasDeclaration */); + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 178 /* TypeLiteral */ || input.kind === 191 /* MappedType */) && input.parent.kind !== 255 /* TypeAliasDeclaration */); // Emit methods which are private as properties with no type information if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { if (ts.hasEffectiveModifier(input, 8 /* Private */)) { @@ -99084,21 +102078,21 @@ var ts; } if (isProcessedComponent(input)) { switch (input.kind) { - case 223 /* ExpressionWithTypeArguments */: { + case 224 /* ExpressionWithTypeArguments */: { if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { checkEntityNameVisibility(input.expression, enclosingDeclaration); } var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(factory.updateExpressionWithTypeArguments(node, node.expression, node.typeArguments)); } - case 173 /* TypeReference */: { + case 174 /* TypeReference */: { checkEntityNameVisibility(input.typeName, enclosingDeclaration); var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(factory.updateTypeReferenceNode(node, node.typeName, node.typeArguments)); } - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: return cleanup(factory.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); - case 166 /* Constructor */: { + case 167 /* Constructor */: { // A constructor declaration may not have a type annotation var ctor = factory.createConstructorDeclaration( /*decorators*/ undefined, @@ -99106,7 +102100,7 @@ var ts; /*body*/ undefined); return cleanup(ctor); } - case 165 /* MethodDeclaration */: { + case 166 /* MethodDeclaration */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } @@ -99116,7 +102110,7 @@ var ts; /*body*/ undefined); return cleanup(sig); } - case 167 /* GetAccessor */: { + case 168 /* GetAccessor */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } @@ -99125,7 +102119,7 @@ var ts; /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), ensureType(input, accessorType), /*body*/ undefined)); } - case 168 /* SetAccessor */: { + case 169 /* SetAccessor */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } @@ -99133,31 +102127,31 @@ var ts; /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), /*body*/ undefined)); } - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updatePropertyDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type))); - case 164 /* MethodSignature */: { + case 165 /* MethodSignature */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updateMethodSignature(input, ensureModifiers(input), input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 169 /* CallSignature */: { + case 170 /* CallSignature */: { return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 171 /* IndexSignature */: { + case 172 /* IndexSignature */: { return cleanup(factory.updateIndexSignature(input, /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(128 /* AnyKeyword */))); } - case 249 /* VariableDeclaration */: { + case 250 /* VariableDeclaration */: { if (ts.isBindingPattern(input.name)) { return recreateBindingPattern(input.name); } @@ -99165,13 +102159,13 @@ var ts; suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types return cleanup(factory.updateVariableDeclaration(input, input.name, /*exclamationToken*/ undefined, ensureType(input, input.type), ensureNoInitializer(input))); } - case 159 /* TypeParameter */: { + case 160 /* TypeParameter */: { if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { return cleanup(factory.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); } return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); } - case 184 /* ConditionalType */: { + case 185 /* ConditionalType */: { // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); @@ -99183,13 +102177,13 @@ var ts; var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); return cleanup(factory.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); } - case 174 /* FunctionType */: { + case 175 /* FunctionType */: { return cleanup(factory.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 175 /* ConstructorType */: { + case 176 /* ConstructorType */: { return cleanup(factory.updateConstructorTypeNode(input, ensureModifiers(input), ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 195 /* ImportType */: { + case 196 /* ImportType */: { if (!ts.isLiteralImportTypeNode(input)) return cleanup(input); return cleanup(factory.updateImportTypeNode(input, factory.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); @@ -99221,7 +102215,7 @@ var ts; } } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 165 /* MethodDeclaration */ && ts.hasEffectiveModifier(node.parent, 8 /* Private */); + return node.parent.kind === 166 /* MethodDeclaration */ && ts.hasEffectiveModifier(node.parent, 8 /* Private */); } function visitDeclarationStatements(input) { if (!isPreservedDeclarationStatement(input)) { @@ -99231,7 +102225,7 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 267 /* ExportDeclaration */: { + case 268 /* ExportDeclaration */: { if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; } @@ -99241,7 +102235,7 @@ var ts; return factory.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); } - case 266 /* ExportAssignment */: { + case 267 /* ExportAssignment */: { // Always visible if the parent node isn't dropped for being not visible if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; @@ -99256,7 +102250,9 @@ var ts; diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: input }); }; + errorFallbackNode = input; var varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + errorFallbackNode = undefined; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */)); return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } @@ -99273,17 +102269,17 @@ var ts; // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too return statement; } - var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (11263 /* All */ ^ 1 /* Export */)); + var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (27647 /* All */ ^ 1 /* Export */)); return factory.updateModifiers(statement, modifiers); } function transformTopLevelDeclaration(input) { if (shouldStripInternal(input)) return; switch (input.kind) { - case 260 /* ImportEqualsDeclaration */: { + case 261 /* ImportEqualsDeclaration */: { return transformImportEqualsDeclaration(input); } - case 261 /* ImportDeclaration */: { + case 262 /* ImportDeclaration */: { return transformImportDeclaration(input); } } @@ -99304,14 +102300,14 @@ var ts; } var previousNeedsDeclare = needsDeclare; switch (input.kind) { - case 254 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + case 255 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all return cleanup(factory.updateTypeAliasDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); - case 253 /* InterfaceDeclaration */: { + case 254 /* InterfaceDeclaration */: { return cleanup(factory.updateInterfaceDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } - case 251 /* FunctionDeclaration */: { + case 252 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type var clean = cleanup(factory.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), @@ -99326,7 +102322,7 @@ var ts; fakespace_1.symbol = props[0].parent; var exportMappings_1 = []; var declarations = ts.mapDefined(props, function (p) { - if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + if (!p.valueDeclaration || !ts.isPropertyAccessExpression(p.valueDeclaration)) { return undefined; // TODO GH#33569: Handle element access expressions that created late bound names (rather than silently omitting them) } getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration); @@ -99378,10 +102374,10 @@ var ts; return clean; } } - case 256 /* ModuleDeclaration */: { + case 257 /* ModuleDeclaration */: { needsDeclare = false; var inner = input.body; - if (inner && inner.kind === 257 /* ModuleBlock */) { + if (inner && inner.kind === 258 /* ModuleBlock */) { var oldNeedsScopeFix = needsScopeFixMarker; var oldHasScopeFix = resultHasScopeMarker; resultHasScopeMarker = false; @@ -99424,7 +102420,9 @@ var ts; /*decorators*/ undefined, mods, input.name, body)); } } - case 252 /* ClassDeclaration */: { + case 253 /* ClassDeclaration */: { + errorNameNode = input.name; + errorFallbackNode = input; var modifiers = factory.createNodeArray(ensureModifiers(input)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -99432,7 +102430,7 @@ var ts; if (ctor) { var oldDiag_1 = getSymbolAccessibilityDiagnostic; parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { - if (!ts.hasSyntacticModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param)) + if (!ts.hasSyntacticModifier(param, 16476 /* ParameterPropertyModifier */) || shouldStripInternal(param)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 78 /* Identifier */) { @@ -99507,10 +102505,10 @@ var ts; /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); } } - case 232 /* VariableStatement */: { + case 233 /* VariableStatement */: { return cleanup(transformVariableStatement(input)); } - case 255 /* EnumDeclaration */: { + case 256 /* EnumDeclaration */: { return cleanup(factory.updateEnumDeclaration(input, /*decorators*/ undefined, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; @@ -99529,12 +102527,14 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 256 /* ModuleDeclaration */) { + if (input.kind === 257 /* ModuleDeclaration */) { needsDeclare = previousNeedsDeclare; } if (node === input) { return node; } + errorFallbackNode = undefined; + errorNameNode = undefined; return node && ts.setOriginalNode(preserveJsDoc(node, input), input); } } @@ -99550,7 +102550,7 @@ var ts; return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); } function recreateBindingElement(e) { - if (e.kind === 222 /* OmittedExpression */) { + if (e.kind === 223 /* OmittedExpression */) { return; } if (e.name) { @@ -99598,9 +102598,9 @@ var ts; return factory.createModifiersFromModifierFlags(newFlags); } function ensureModifierFlags(node) { - var mask = 11263 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files + var mask = 27647 /* All */ ^ (4 /* Public */ | 256 /* Async */ | 16384 /* Override */); // No async and override modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; - var parentIsFile = node.parent.kind === 297 /* SourceFile */; + var parentIsFile = node.parent.kind === 298 /* SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { mask ^= 2 /* Ambient */; additions = 0 /* None */; @@ -99629,7 +102629,7 @@ var ts; } ts.transformDeclarations = transformDeclarations; function isAlwaysType(node) { - if (node.kind === 253 /* InterfaceDeclaration */) { + if (node.kind === 254 /* InterfaceDeclaration */) { return true; } return false; @@ -99639,7 +102639,7 @@ var ts; return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); } function maskModifierFlags(node, modifierMask, modifierAdditions) { - if (modifierMask === void 0) { modifierMask = 11263 /* All */ ^ 4 /* Public */; } + if (modifierMask === void 0) { modifierMask = 27647 /* All */ ^ 4 /* Public */; } if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions; if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) { @@ -99654,7 +102654,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 167 /* GetAccessor */ + return accessor.kind === 168 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type @@ -99663,52 +102663,52 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return !ts.hasEffectiveModifier(node, 8 /* Private */); - case 160 /* Parameter */: - case 249 /* VariableDeclaration */: + case 161 /* Parameter */: + case 250 /* VariableDeclaration */: return true; } return false; } function isPreservedDeclarationStatement(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 256 /* ModuleDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 253 /* InterfaceDeclaration */: - case 252 /* ClassDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: - case 232 /* VariableStatement */: - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: + case 252 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 254 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 233 /* VariableStatement */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: return true; } return false; } function isProcessedComponent(node) { switch (node.kind) { - case 170 /* ConstructSignature */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 171 /* IndexSignature */: - case 249 /* VariableDeclaration */: - case 159 /* TypeParameter */: - case 223 /* ExpressionWithTypeArguments */: - case 173 /* TypeReference */: - case 184 /* ConditionalType */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 195 /* ImportType */: + case 171 /* ConstructSignature */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 172 /* IndexSignature */: + case 250 /* VariableDeclaration */: + case 160 /* TypeParameter */: + case 224 /* ExpressionWithTypeArguments */: + case 174 /* TypeReference */: + case 185 /* ConditionalType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 196 /* ImportType */: return true; } return false; @@ -99764,6 +102764,9 @@ var ts; if (languageVersion < 99 /* ESNext */) { transformers.push(ts.transformESNext); } + if (languageVersion < 8 /* ES2021 */) { + transformers.push(ts.transformES2021); + } if (languageVersion < 7 /* ES2020 */) { transformers.push(ts.transformES2020); } @@ -99840,7 +102843,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, factory, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(341 /* Count */); + var enabledSyntaxKindFeatures = new Array(345 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentStatements; @@ -99851,6 +102854,9 @@ var ts; var lexicalEnvironmentFlagsStack = []; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; + var blockScopedVariableDeclarationsStack = []; + var blockScopeStackOffset = 0; + var blockScopedVariableDeclarations; var emitHelpers; var onSubstituteNode = noEmitSubstitution; var onEmitNode = noEmitNotification; @@ -99873,6 +102879,9 @@ var ts; hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, addInitializationStatement: addInitializationStatement, + startBlockScope: startBlockScope, + endBlockScope: endBlockScope, + addBlockScopedVariable: addBlockScopedVariable, requestEmitHelper: requestEmitHelper, readEmitHelpers: readEmitHelpers, enableSubstitution: enableSubstitution, @@ -99916,9 +102925,9 @@ var ts; var transformed = []; for (var _a = 0, nodes_3 = nodes; _a < nodes_3.length; _a++) { var node = nodes_3[_a]; - ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 298 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); transformed.push((allowDtsFiles ? transformation : transformRoot)(node)); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // prevent modification of the lexical environment. state = 2 /* Completed */; @@ -100133,6 +103142,38 @@ var ts; function getLexicalEnvironmentFlags() { return lexicalEnvironmentFlags; } + /** + * Starts a block scope. Any existing block hoisted variables are pushed onto the stack and the related storage variables are reset. + */ + function startBlockScope() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot start a block scope during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot start a block scope after transformation has completed."); + blockScopedVariableDeclarationsStack[blockScopeStackOffset] = blockScopedVariableDeclarations; + blockScopeStackOffset++; + blockScopedVariableDeclarations = undefined; + } + /** + * Ends a block scope. The previous set of block hoisted variables are restored. Any hoisted declarations are returned. + */ + function endBlockScope() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot end a block scope during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot end a block scope after transformation has completed."); + var statements = ts.some(blockScopedVariableDeclarations) ? + [ + factory.createVariableStatement( + /*modifiers*/ undefined, factory.createVariableDeclarationList(blockScopedVariableDeclarations.map(function (identifier) { return factory.createVariableDeclaration(identifier); }), 1 /* Let */)) + ] : undefined; + blockScopeStackOffset--; + blockScopedVariableDeclarations = blockScopedVariableDeclarationsStack[blockScopeStackOffset]; + if (blockScopeStackOffset === 0) { + blockScopedVariableDeclarationsStack = []; + } + return statements; + } + function addBlockScopedVariable(name) { + ts.Debug.assert(blockScopeStackOffset > 0, "Cannot add a block scoped variable outside of an iteration body."); + (blockScopedVariableDeclarations || (blockScopedVariableDeclarations = [])).push(name); + } function requestEmitHelper(helper) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); @@ -100174,35 +103215,37 @@ var ts; } ts.transformNodes = transformNodes; ts.nullTransformationContext = { - get factory() { return ts.factory; }, - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: ts.returnUndefined, + factory: ts.factory, getCompilerOptions: function () { return ({}); }, - getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + getEmitHost: ts.notImplemented, getEmitHelperFactory: ts.notImplemented, + startLexicalEnvironment: ts.noop, + resumeLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop, + endLexicalEnvironment: ts.returnUndefined, setLexicalEnvironmentFlags: ts.noop, getLexicalEnvironmentFlags: function () { return 0; }, - hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + hoistFunctionDeclaration: ts.noop, addInitializationStatement: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, + startBlockScope: ts.noop, + endBlockScope: ts.returnUndefined, + addBlockScopedVariable: ts.noop, requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop, + readEmitHelpers: ts.notImplemented, + enableSubstitution: ts.noop, + enableEmitNotification: ts.noop, + isSubstitutionEnabled: ts.notImplemented, + isEmitNotificationEnabled: ts.notImplemented, + onSubstituteNode: noEmitSubstitution, + onEmitNode: noEmitNotification, addDiagnostic: ts.noop, }; })(ts || (ts = {})); var ts; (function (ts) { var brackets = createBracketsMap(); - var syntheticParent = { pos: -1, end: -1 }; /*@internal*/ function isBuildInfoFile(file) { return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */); @@ -100288,7 +103331,7 @@ var ts; /*@internal*/ function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); - if (sourceFile.kind === 298 /* Bundle */) { + if (sourceFile.kind === 299 /* Bundle */) { return getOutputPathsForBundle(options, forceDtsPaths); } else { @@ -100514,15 +103557,15 @@ var ts; sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); }) }; } - ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); emitBuildInfo(bundleBuildInfo, buildInfoPath); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { if (jsFilePath) { @@ -100649,13 +103692,13 @@ var ts; if (!declBlocked || forceDtsEmit) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, { - sourceMap: compilerOptions.declarationMap, + sourceMap: !forceDtsEmit && compilerOptions.declarationMap, sourceRoot: compilerOptions.sourceRoot, mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, // Explicitly do not passthru either `inline` option }); - if (forceDtsEmit && declarationTransform.transformed[0].kind === 297 /* SourceFile */) { + if (forceDtsEmit && declarationTransform.transformed[0].kind === 298 /* SourceFile */) { var sourceFile = declarationTransform.transformed[0]; exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; } @@ -100678,8 +103721,8 @@ var ts; ts.forEachChild(node, collectLinkedAliases); } function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) { - var bundle = sourceFileOrBundle.kind === 298 /* Bundle */ ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 297 /* SourceFile */ ? sourceFileOrBundle : undefined; + var bundle = sourceFileOrBundle.kind === 299 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 298 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; var sourceMapGenerator; if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { @@ -100720,7 +103763,7 @@ var ts; } function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { return (mapOptions.sourceMap || mapOptions.inlineSourceMap) - && (sourceFileOrBundle.kind !== 297 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); + && (sourceFileOrBundle.kind !== 298 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); } function getSourceRoot(mapOptions) { // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the @@ -100779,7 +103822,7 @@ var ts; ts.emitFiles = emitFiles; /*@internal*/ function getBuildInfoText(buildInfo) { - return JSON.stringify(buildInfo, undefined, 2); + return JSON.stringify(buildInfo); } ts.getBuildInfoText = getBuildInfoText; /*@internal*/ @@ -100960,7 +104003,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = ts.getNewLineCharacter(printerOptions); var moduleKind = ts.getEmitModuleKind(printerOptions); @@ -100999,9 +104042,11 @@ var ts; var detachedCommentsInfo; var hasWrittenComment = false; var commentsDisabled = !!printerOptions.removeComments; - var lastNode; var lastSubstitution; + var currentParenthesizerRule; var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; + var parenthesizer = ts.factory.parenthesizer; + var emitBinaryExpression = createEmitBinaryExpression(); reset(); return { // public API @@ -101029,9 +104074,9 @@ var ts; break; } switch (node.kind) { - case 297 /* SourceFile */: return printFile(node); - case 298 /* Bundle */: return printBundle(node); - case 299 /* UnparsedSource */: return printUnparsedSource(node); + case 298 /* SourceFile */: return printFile(node); + case 299 /* Bundle */: return printBundle(node); + case 300 /* UnparsedSource */: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -101065,7 +104110,7 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - emitList(syntheticParent, nodes, format); + emitList(/*parentNode*/ undefined, nodes, format); reset(); writer = previousWriter; } @@ -101200,7 +104245,7 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - pipelineEmit(hint, node); + pipelineEmit(hint, node, /*parenthesizerRule*/ undefined); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -101228,51 +104273,54 @@ var ts; currentSourceFile = undefined; currentLineMap = undefined; detachedCommentsInfo = undefined; - lastNode = undefined; - lastSubstitution = undefined; setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined); } function getCurrentLineMap() { return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); } - function emit(node) { + function emit(node, parenthesizerRule) { if (node === undefined) return; var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node); - var substitute = pipelineEmit(4 /* Unspecified */, node); + pipelineEmit(4 /* Unspecified */, node, parenthesizerRule); recordBundleFileInternalSectionEnd(prevSourceFileTextKind); - return substitute; } function emitIdentifierName(node) { if (node === undefined) return; - return pipelineEmit(2 /* IdentifierName */, node); + pipelineEmit(2 /* IdentifierName */, node, /*parenthesizerRule*/ undefined); } - function emitExpression(node) { + function emitExpression(node, parenthesizerRule) { if (node === undefined) return; - return pipelineEmit(1 /* Expression */, node); + pipelineEmit(1 /* Expression */, node, parenthesizerRule); } function emitJsxAttributeValue(node) { - return pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); + pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); } - function pipelineEmit(emitHint, node) { - var savedLastNode = lastNode; - var savedLastSubstitution = lastSubstitution; - var savedPreserveSourceNewlines = preserveSourceNewlines; - lastNode = node; - lastSubstitution = undefined; - if (preserveSourceNewlines && !!(ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) { + function beforeEmitNode(node) { + if (preserveSourceNewlines && (ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) { preserveSourceNewlines = false; } + } + function afterEmitNode(savedPreserveSourceNewlines) { + preserveSourceNewlines = savedPreserveSourceNewlines; + } + function pipelineEmit(emitHint, node, parenthesizerRule) { + currentParenthesizerRule = parenthesizerRule; var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node); pipelinePhase(emitHint, node); - ts.Debug.assert(lastNode === node); - var substitute = lastSubstitution; - lastNode = savedLastNode; - lastSubstitution = savedLastSubstitution; - preserveSourceNewlines = savedPreserveSourceNewlines; - return substitute || node; + currentParenthesizerRule = undefined; + } + function shouldEmitComments(node) { + return !commentsDisabled && !ts.isSourceFile(node); + } + function shouldEmitSourceMaps(node) { + return !sourceMapsDisabled && + !ts.isSourceFile(node) && + !ts.isInJsonFile(node) && + !ts.isUnparsedSource(node) && + !ts.isUnparsedPrepend(node); } function getPipelinePhase(phase, emitHint, node) { switch (phase) { @@ -101282,18 +104330,21 @@ var ts; } // falls through case 1 /* Substitution */: - if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) { + if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) { + if (currentParenthesizerRule) { + lastSubstitution = currentParenthesizerRule(lastSubstitution); + } return pipelineEmitWithSubstitution; } // falls through case 2 /* Comments */: - if (!commentsDisabled && node.kind !== 297 /* SourceFile */) { + if (shouldEmitComments(node)) { return pipelineEmitWithComments; } // falls through case 3 /* SourceMaps */: - if (!sourceMapsDisabled && node.kind !== 297 /* SourceFile */ && !ts.isInJsonFile(node)) { - return pipelineEmitWithSourceMap; + if (shouldEmitSourceMaps(node)) { + return pipelineEmitWithSourceMaps; } // falls through case 4 /* Emit */: @@ -101306,13 +104357,25 @@ var ts; return getPipelinePhase(currentPhase + 1, emitHint, node); } function pipelineEmitWithNotification(hint, node) { - ts.Debug.assert(lastNode === node); var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node); onEmitNode(hint, node, pipelinePhase); - ts.Debug.assert(lastNode === node); } function pipelineEmitWithHint(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (preserveSourceNewlines) { + var savedPreserveSourceNewlines = preserveSourceNewlines; + beforeEmitNode(node); + pipelineEmitWithHintWorker(hint, node); + afterEmitNode(savedPreserveSourceNewlines); + } + else { + pipelineEmitWithHintWorker(hint, node); + } + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); + // clear the parenthesizer rule as we ascend + currentParenthesizerRule = undefined; + } + function pipelineEmitWithHintWorker(hint, node) { if (hint === 0 /* SourceFile */) return emitSourceFile(ts.cast(node, ts.isSourceFile)); if (hint === 2 /* IdentifierName */) @@ -101326,24 +104389,12 @@ var ts; return emitEmptyStatement(/*isEmbeddedStatement*/ true); } if (hint === 4 /* Unspecified */) { - if (ts.isKeyword(node.kind)) - return writeTokenNode(node, writeKeyword); switch (node.kind) { // Pseudo-literals case 15 /* TemplateHead */: case 16 /* TemplateMiddle */: case 17 /* TemplateTail */: return emitLiteral(node, /*jsxAttributeEscape*/ false); - case 299 /* UnparsedSource */: - case 293 /* UnparsedPrepend */: - return emitUnparsedSourceOrPrepend(node); - case 292 /* UnparsedPrologue */: - return writeUnparsedNode(node); - case 294 /* UnparsedText */: - case 295 /* UnparsedInternalText */: - return emitUnparsedTextLike(node); - case 296 /* UnparsedSyntheticReference */: - return emitUnparsedSyntheticReference(node); // Identifiers case 78 /* Identifier */: return emitIdentifier(node); @@ -101352,282 +104403,323 @@ var ts; return emitPrivateIdentifier(node); // Parse tree nodes // Names - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return emitQualifiedName(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return emitComputedPropertyName(node); // Signature elements - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return emitTypeParameter(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return emitParameter(node); - case 161 /* Decorator */: + case 162 /* Decorator */: return emitDecorator(node); // Type members - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: return emitPropertySignature(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return emitPropertyDeclaration(node); - case 164 /* MethodSignature */: + case 165 /* MethodSignature */: return emitMethodSignature(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return emitMethodDeclaration(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return emitConstructor(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return emitAccessorDeclaration(node); - case 169 /* CallSignature */: + case 170 /* CallSignature */: return emitCallSignature(node); - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: return emitConstructSignature(node); - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: return emitIndexSignature(node); - case 194 /* TemplateLiteralTypeSpan */: - return emitTemplateTypeSpan(node); // Types - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return emitTypePredicate(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return emitTypeReference(node); - case 174 /* FunctionType */: + case 175 /* FunctionType */: return emitFunctionType(node); - case 308 /* JSDocFunctionType */: - return emitJSDocFunctionType(node); - case 175 /* ConstructorType */: + case 176 /* ConstructorType */: return emitConstructorType(node); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return emitTypeQuery(node); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return emitTypeLiteral(node); - case 178 /* ArrayType */: + case 179 /* ArrayType */: return emitArrayType(node); - case 179 /* TupleType */: + case 180 /* TupleType */: return emitTupleType(node); - case 180 /* OptionalType */: + case 181 /* OptionalType */: return emitOptionalType(node); - case 182 /* UnionType */: + // SyntaxKind.RestType is handled below + case 183 /* UnionType */: return emitUnionType(node); - case 183 /* IntersectionType */: + case 184 /* IntersectionType */: return emitIntersectionType(node); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return emitConditionalType(node); - case 185 /* InferType */: + case 186 /* InferType */: return emitInferType(node); - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return emitParenthesizedType(node); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(node); - case 187 /* ThisType */: + case 188 /* ThisType */: return emitThisType(); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return emitTypeOperator(node); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return emitIndexedAccessType(node); - case 190 /* MappedType */: + case 191 /* MappedType */: return emitMappedType(node); - case 191 /* LiteralType */: + case 192 /* LiteralType */: return emitLiteralType(node); - case 193 /* TemplateLiteralType */: + case 193 /* NamedTupleMember */: + return emitNamedTupleMember(node); + case 194 /* TemplateLiteralType */: return emitTemplateType(node); - case 195 /* ImportType */: + case 195 /* TemplateLiteralTypeSpan */: + return emitTemplateTypeSpan(node); + case 196 /* ImportType */: return emitImportTypeNode(node); - case 303 /* JSDocAllType */: - writePunctuation("*"); - return; - case 304 /* JSDocUnknownType */: - writePunctuation("?"); - return; - case 305 /* JSDocNullableType */: - return emitJSDocNullableType(node); - case 306 /* JSDocNonNullableType */: - return emitJSDocNonNullableType(node); - case 307 /* JSDocOptionalType */: - return emitJSDocOptionalType(node); - case 181 /* RestType */: - case 309 /* JSDocVariadicType */: - return emitRestOrJSDocVariadicType(node); - case 192 /* NamedTupleMember */: - return emitNamedTupleMember(node); // Binding patterns - case 196 /* ObjectBindingPattern */: + case 197 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return emitBindingElement(node); // Misc - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return emitTemplateSpan(node); - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: return emitSemicolonClassElement(); // Statements - case 230 /* Block */: + case 231 /* Block */: return emitBlock(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return emitVariableStatement(node); - case 231 /* EmptyStatement */: + case 232 /* EmptyStatement */: return emitEmptyStatement(/*isEmbeddedStatement*/ false); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return emitExpressionStatement(node); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return emitIfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return emitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return emitWhileStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return emitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return emitForInStatement(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return emitForOfStatement(node); - case 240 /* ContinueStatement */: + case 241 /* ContinueStatement */: return emitContinueStatement(node); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: return emitBreakStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return emitReturnStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return emitWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return emitSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return emitLabeledStatement(node); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return emitThrowStatement(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return emitTryStatement(node); - case 248 /* DebuggerStatement */: + case 249 /* DebuggerStatement */: return emitDebuggerStatement(node); // Declarations - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return emitVariableDeclarationList(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return emitFunctionDeclaration(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return emitClassDeclaration(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return emitTypeAliasDeclaration(node); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return emitModuleBlock(node); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return emitCaseBlock(node); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return emitNamespaceExportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return emitImportDeclaration(node); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return emitImportClause(node); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return emitNamespaceImport(node); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: return emitNamespaceExport(node); - case 264 /* NamedImports */: + case 265 /* NamedImports */: return emitNamedImports(node); - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: return emitImportSpecifier(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return emitExportAssignment(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return emitExportDeclaration(node); - case 268 /* NamedExports */: + case 269 /* NamedExports */: return emitNamedExports(node); - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: return emitExportSpecifier(node); - case 271 /* MissingDeclaration */: + case 272 /* MissingDeclaration */: return; // Module references - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: return emitExternalModuleReference(node); // JSX (non-expression) case 11 /* JsxText */: return emitJsxText(node); - case 275 /* JsxOpeningElement */: - case 278 /* JsxOpeningFragment */: + case 276 /* JsxOpeningElement */: + case 279 /* JsxOpeningFragment */: return emitJsxOpeningElementOrFragment(node); - case 276 /* JsxClosingElement */: - case 279 /* JsxClosingFragment */: + case 277 /* JsxClosingElement */: + case 280 /* JsxClosingFragment */: return emitJsxClosingElementOrFragment(node); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return emitJsxAttribute(node); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return emitJsxAttributes(node); - case 282 /* JsxSpreadAttribute */: + case 283 /* JsxSpreadAttribute */: return emitJsxSpreadAttribute(node); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return emitJsxExpression(node); // Clauses - case 284 /* CaseClause */: + case 285 /* CaseClause */: return emitCaseClause(node); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: return emitDefaultClause(node); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: return emitHeritageClause(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return emitCatchClause(node); // Property assignments - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: return emitSpreadAssignment(node); // Enum - case 291 /* EnumMember */: + case 292 /* EnumMember */: return emitEnumMember(node); + // Unparsed + case 293 /* UnparsedPrologue */: + return writeUnparsedNode(node); + case 300 /* UnparsedSource */: + case 294 /* UnparsedPrepend */: + return emitUnparsedSourceOrPrepend(node); + case 295 /* UnparsedText */: + case 296 /* UnparsedInternalText */: + return emitUnparsedTextLike(node); + case 297 /* UnparsedSyntheticReference */: + return emitUnparsedSyntheticReference(node); + // Top-level nodes + case 298 /* SourceFile */: + return emitSourceFile(node); + case 299 /* Bundle */: + return ts.Debug.fail("Bundles should be printed using printBundle"); + // SyntaxKind.UnparsedSource (handled above) + case 301 /* InputFiles */: + return ts.Debug.fail("InputFiles should not be printed"); // JSDoc nodes (only used in codefixes currently) - case 326 /* JSDocParameterTag */: - case 333 /* JSDocPropertyTag */: + case 302 /* JSDocTypeExpression */: + return emitJSDocTypeExpression(node); + case 303 /* JSDocNameReference */: + return emitJSDocNameReference(node); + case 304 /* JSDocAllType */: + return writePunctuation("*"); + case 305 /* JSDocUnknownType */: + return writePunctuation("?"); + case 306 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 307 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 308 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 309 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 182 /* RestType */: + case 310 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + case 311 /* JSDocNamepathType */: + return; + case 312 /* JSDocComment */: + return emitJSDoc(node); + case 314 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 315 /* JSDocSignature */: + return emitJSDocSignature(node); + case 317 /* JSDocTag */: + case 322 /* JSDocClassTag */: + return emitJSDocSimpleTag(node); + case 318 /* JSDocAugmentsTag */: + case 319 /* JSDocImplementsTag */: + return emitJSDocHeritageTag(node); + case 320 /* JSDocAuthorTag */: + case 321 /* JSDocDeprecatedTag */: + return; + // SyntaxKind.JSDocClassTag (see JSDocTag, above) + case 323 /* JSDocPublicTag */: + case 324 /* JSDocPrivateTag */: + case 325 /* JSDocProtectedTag */: + case 326 /* JSDocReadonlyTag */: + case 327 /* JSDocOverrideTag */: + return; + case 328 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + // SyntaxKind.JSDocEnumTag (see below) + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: return emitJSDocPropertyLikeTag(node); - case 327 /* JSDocReturnTag */: - case 329 /* JSDocTypeTag */: - case 328 /* JSDocThisTag */: - case 325 /* JSDocEnumTag */: + case 329 /* JSDocEnumTag */: + case 331 /* JSDocReturnTag */: + case 332 /* JSDocThisTag */: + case 333 /* JSDocTypeTag */: return emitJSDocSimpleTypedTag(node); - case 316 /* JSDocImplementsTag */: - case 315 /* JSDocAugmentsTag */: - return emitJSDocHeritageTag(node); - case 330 /* JSDocTemplateTag */: + case 334 /* JSDocTemplateTag */: return emitJSDocTemplateTag(node); - case 331 /* JSDocTypedefTag */: + case 335 /* JSDocTypedefTag */: return emitJSDocTypedefTag(node); - case 324 /* JSDocCallbackTag */: - return emitJSDocCallbackTag(node); - case 313 /* JSDocSignature */: - return emitJSDocSignature(node); - case 312 /* JSDocTypeLiteral */: - return emitJSDocTypeLiteral(node); - case 319 /* JSDocClassTag */: - case 314 /* JSDocTag */: - return emitJSDocSimpleTag(node); - case 332 /* JSDocSeeTag */: + case 336 /* JSDocSeeTag */: return emitJSDocSeeTag(node); - case 302 /* JSDocNameReference */: - return emitJSDocNameReference(node); - case 311 /* JSDocComment */: - return emitJSDoc(node); - // Transformation nodes (ignored) + // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) + // Transformation nodes + case 339 /* NotEmittedStatement */: + case 343 /* EndOfDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: + return; } if (ts.isExpression(node)) { hint = 1 /* Expression */; if (substituteNode !== ts.noEmitSubstitution) { - lastSubstitution = node = substituteNode(hint, node); + var substitute = substituteNode(hint, node) || node; + if (substitute !== node) { + node = substitute; + if (currentParenthesizerRule) { + node = currentParenthesizerRule(node); + } + } } } - else if (ts.isToken(node)) { - return writeTokenNode(node, writePunctuation); - } } if (hint === 1 /* Expression */) { switch (node.kind) { @@ -101642,84 +104734,92 @@ var ts; // Identifiers case 78 /* Identifier */: return emitIdentifier(node); - // Reserved words - case 94 /* FalseKeyword */: - case 103 /* NullKeyword */: - case 105 /* SuperKeyword */: - case 109 /* TrueKeyword */: - case 107 /* ThisKeyword */: - case 99 /* ImportKeyword */: - writeTokenNode(node, writeKeyword); - return; // Expressions - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return emitObjectLiteralExpression(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return emitPropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return emitElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return emitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return emitNewExpression(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: return emitTypeAssertionExpression(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return emitParenthesizedExpression(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return emitFunctionExpression(node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return emitArrowFunction(node); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return emitDeleteExpression(node); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return emitVoidExpression(node); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return emitAwaitExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return emitBinaryExpression(node); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return emitConditionalExpression(node); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return emitTemplateExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return emitYieldExpression(node); - case 220 /* SpreadElement */: - return emitSpreadExpression(node); - case 221 /* ClassExpression */: + case 221 /* SpreadElement */: + return emitSpreadElement(node); + case 222 /* ClassExpression */: return emitClassExpression(node); - case 222 /* OmittedExpression */: + case 223 /* OmittedExpression */: return; - case 224 /* AsExpression */: + case 225 /* AsExpression */: return emitAsExpression(node); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return emitNonNullExpression(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return emitMetaProperty(node); + case 228 /* SyntheticExpression */: + return ts.Debug.fail("SyntheticExpression should never be printed."); // JSX - case 273 /* JsxElement */: + case 274 /* JsxElement */: return emitJsxElement(node); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return emitJsxFragment(node); + // Synthesized list + case 338 /* SyntaxList */: + return ts.Debug.fail("SyntaxList should not be printed"); // Transformation nodes - case 336 /* PartiallyEmittedExpression */: + case 339 /* NotEmittedStatement */: + return; + case 340 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return emitCommaList(node); + case 342 /* MergeDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: + return; + case 344 /* SyntheticReferenceExpression */: + return ts.Debug.fail("SyntheticReferenceExpression should not be printed"); } } + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + if (ts.isTokenKind(node.kind)) + return writeTokenNode(node, writePunctuation); + ts.Debug.fail("Unhandled SyntaxKind: " + ts.Debug.formatSyntaxKind(node.kind) + "."); } function emitMappedTypeParameter(node) { emit(node.name); @@ -101729,10 +104829,11 @@ var ts; emit(node.constraint); } function pipelineEmitWithSubstitution(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node); - pipelinePhase(hint, lastSubstitution); - ts.Debug.assert(lastNode === node || lastSubstitution === node); + ts.Debug.assertIsDefined(lastSubstitution); + node = lastSubstitution; + lastSubstitution = undefined; + pipelinePhase(hint, node); } function getHelpersFromBundledSourceFiles(bundle) { var result; @@ -101758,7 +104859,7 @@ var ts; } function emitHelpers(node) { var helpersEmitted = false; - var bundle = node.kind === 298 /* Bundle */ ? node : undefined; + var bundle = node.kind === 299 /* Bundle */ ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -101858,7 +104959,7 @@ var ts; var pos = getTextPosWithWriteLine(); writeUnparsedNode(unparsed); if (bundleFileInfo) { - updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 294 /* UnparsedText */ ? + updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 295 /* UnparsedText */ ? "text" /* Text */ : "internal" /* Internal */); } @@ -101904,7 +105005,7 @@ var ts; } function emitComputedPropertyName(node) { writePunctuation("["); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName); writePunctuation("]"); } // @@ -101931,18 +105032,18 @@ var ts; emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); - if (node.parent && node.parent.kind === 308 /* JSDocFunctionType */ && !node.name) { + if (node.parent && node.parent.kind === 309 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { emitTypeAnnotation(node.type); } // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. - emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitDecorator(decorator) { writePunctuation("@"); - emitExpression(decorator.expression); + emitExpression(decorator.expression, parenthesizer.parenthesizeLeftSideOfAccess); } // // Type members @@ -101993,7 +105094,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeKeyword(node.kind === 167 /* GetAccessor */ ? "get" : "set"); + writeKeyword(node.kind === 168 /* GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); @@ -102107,7 +105208,7 @@ var ts; writePunctuation("}"); } function emitArrayType(node) { - emit(node.elementType); + emit(node.elementType, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("["); writePunctuation("]"); } @@ -102130,21 +105231,21 @@ var ts; emit(node.type); } function emitOptionalType(node) { - emit(node.type); + emit(node.type, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("?"); } function emitUnionType(node) { - emitList(node, node.types, 516 /* UnionTypeConstituents */); + emitList(node, node.types, 516 /* UnionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitIntersectionType(node) { - emitList(node, node.types, 520 /* IntersectionTypeConstituents */); + emitList(node, node.types, 520 /* IntersectionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitConditionalType(node) { - emit(node.checkType); + emit(node.checkType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writeKeyword("extends"); writeSpace(); - emit(node.extendsType); + emit(node.extendsType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writePunctuation("?"); writeSpace(); @@ -102170,10 +105271,10 @@ var ts; function emitTypeOperator(node) { writeTokenText(node.operator, writeKeyword); writeSpace(); - emit(node.type); + emit(node.type, parenthesizer.parenthesizeMemberOfElementType); } function emitIndexedAccessType(node) { - emit(node.objectType); + emit(node.objectType, parenthesizer.parenthesizeMemberOfElementType); writePunctuation("["); emit(node.indexType); writePunctuation("]"); @@ -102266,7 +105367,7 @@ var ts; writeSpace(); } emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // Expressions @@ -102274,7 +105375,7 @@ var ts; function emitArrayLiteralExpression(node) { var elements = node.elements; var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; - emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitObjectLiteralExpression(node) { ts.forEach(node.properties, generateMemberNames); @@ -102290,13 +105391,13 @@ var ts; } } function emitPropertyAccessExpression(node) { - var expression = ts.cast(emitExpression(node.expression), ts.isExpression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); var token = node.questionDotToken || ts.setTextRangePosEnd(ts.factory.createToken(24 /* DotToken */), node.expression.end, node.name.pos); var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token); var linesAfterDot = getLinesBetweenNodes(node, token, node.name); writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false); var shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ && - mayNeedDotDotForPropertyAccess(expression) && + mayNeedDotDotForPropertyAccess(node.expression) && !writer.hasTrailingComment() && !writer.hasTrailingWhitespace(); if (shouldEmitDotDot) { @@ -102332,27 +105433,27 @@ var ts; } } function emitElementAccessExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitNewExpression(node) { emitTokenWithComment(102 /* NewKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfNew); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitTaggedTemplateExpression(node) { - emitExpression(node.tag); + emitExpression(node.tag, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); writeSpace(); emitExpression(node.template); @@ -102361,12 +105462,12 @@ var ts; writePunctuation("<"); emit(node.type); writePunctuation(">"); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); - emitExpression(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); writeLineSeparatorsAfter(node.expression, node); decreaseIndentIf(indented); emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); @@ -102390,29 +105491,29 @@ var ts; function emitDeleteExpression(node) { emitTokenWithComment(88 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitTypeOfExpression(node) { emitTokenWithComment(111 /* TypeOfKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitVoidExpression(node) { emitTokenWithComment(113 /* VoidKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitAwaitExpression(node) { emitTokenWithComment(130 /* AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitPrefixUnaryExpression(node) { writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { writeSpace(); } - emitExpression(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPrefixUnary); } function shouldEmitWhitespaceBeforeOperand(node) { // In some cases, we need to emit a space between the operator and the operand. One obvious case @@ -102428,84 +105529,101 @@ var ts; // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. var operand = node.operand; - return operand.kind === 214 /* PrefixUnaryExpression */ + return operand.kind === 215 /* PrefixUnaryExpression */ && ((node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */)) || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */))); } function emitPostfixUnaryExpression(node) { - emitExpression(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary); writeTokenText(node.operator, writeOperator); } - var EmitBinaryExpressionState; - (function (EmitBinaryExpressionState) { - EmitBinaryExpressionState[EmitBinaryExpressionState["EmitLeft"] = 0] = "EmitLeft"; - EmitBinaryExpressionState[EmitBinaryExpressionState["EmitRight"] = 1] = "EmitRight"; - EmitBinaryExpressionState[EmitBinaryExpressionState["FinishEmit"] = 2] = "FinishEmit"; - })(EmitBinaryExpressionState || (EmitBinaryExpressionState = {})); - /** - * emitBinaryExpression includes an embedded work stack to attempt to handle as many nested binary expressions - * as possible without creating any additional stack frames. This can only be done when the emit pipeline does - * not require notification/substitution/comment/sourcemap decorations. - */ - function emitBinaryExpression(node) { - var nodeStack = [node]; - var stateStack = [0 /* EmitLeft */]; - var stackIndex = 0; - while (stackIndex >= 0) { - node = nodeStack[stackIndex]; - switch (stateStack[stackIndex]) { - case 0 /* EmitLeft */: { - maybePipelineEmitExpression(node.left); - break; - } - case 1 /* EmitRight */: { - var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */; - var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); - var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); - writeLinesAndIndent(linesBeforeOperator, isCommaOperator); - emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken, node.operatorToken.kind === 100 /* InKeyword */ ? writeKeyword : writeOperator); - emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts - writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); - maybePipelineEmitExpression(node.right); - break; - } - case 2 /* FinishEmit */: { - var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); - var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); - decreaseIndentIf(linesBeforeOperator, linesAfterOperator); - stackIndex--; - break; - } - default: return ts.Debug.fail("Invalid state " + stateStack[stackIndex] + " for emitBinaryExpressionWorker"); + function createEmitBinaryExpression() { + return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined); + function onEnter(node, state) { + if (state) { + state.stackIndex++; + state.preserveSourceNewlinesStack[state.stackIndex] = preserveSourceNewlines; + state.containerPosStack[state.stackIndex] = containerPos; + state.containerEndStack[state.stackIndex] = containerEnd; + state.declarationListContainerEndStack[state.stackIndex] = declarationListContainerEnd; + var emitComments_1 = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node); + var emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node); + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (emitComments_1) + emitCommentsBeforeNode(node); + if (emitSourceMaps) + emitSourceMapsBeforeNode(node); + beforeEmitNode(node); } - } - function maybePipelineEmitExpression(next) { - // Advance the state of this unit of work, - stateStack[stackIndex]++; - // Then actually do the work of emitting the node `next` returned by the prior state - // The following section should be identical to `pipelineEmit` save it assumes EmitHint.Expression and offloads - // binary expression handling, where possible, to the contained work queue - // #region trampolinePipelineEmit - var savedLastNode = lastNode; - var savedLastSubstitution = lastSubstitution; - lastNode = next; - lastSubstitution = undefined; + else { + state = { + stackIndex: 0, + preserveSourceNewlinesStack: [undefined], + containerPosStack: [-1], + containerEndStack: [-1], + declarationListContainerEndStack: [-1], + shouldEmitCommentsStack: [false], + shouldEmitSourceMapsStack: [false], + }; + } + return state; + } + function onLeft(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "left"); + } + function onOperator(operatorToken, _state, node) { + var isCommaOperator = operatorToken.kind !== 27 /* CommaToken */; + var linesBeforeOperator = getLinesBetweenNodes(node, node.left, operatorToken); + var linesAfterOperator = getLinesBetweenNodes(node, operatorToken, node.right); + writeLinesAndIndent(linesBeforeOperator, isCommaOperator); + emitLeadingCommentsOfPosition(operatorToken.pos); + writeTokenNode(operatorToken, operatorToken.kind === 100 /* InKeyword */ ? writeKeyword : writeOperator); + emitTrailingCommentsOfPosition(operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts + writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); + } + function onRight(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "right"); + } + function onExit(node, state) { + var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); + var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); + decreaseIndentIf(linesBeforeOperator, linesAfterOperator); + if (state.stackIndex > 0) { + var savedPreserveSourceNewlines = state.preserveSourceNewlinesStack[state.stackIndex]; + var savedContainerPos = state.containerPosStack[state.stackIndex]; + var savedContainerEnd = state.containerEndStack[state.stackIndex]; + var savedDeclarationListContainerEnd = state.declarationListContainerEndStack[state.stackIndex]; + var shouldEmitComments_1 = state.shouldEmitCommentsStack[state.stackIndex]; + var shouldEmitSourceMaps_1 = state.shouldEmitSourceMapsStack[state.stackIndex]; + afterEmitNode(savedPreserveSourceNewlines); + if (shouldEmitSourceMaps_1) + emitSourceMapsAfterNode(node); + if (shouldEmitComments_1) + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); + state.stackIndex--; + } + } + function maybeEmitExpression(next, parent, side) { + var parenthesizerRule = side === "left" ? + parenthesizer.getParenthesizeLeftSideOfBinaryForOperator(parent.operatorToken.kind) : + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(parent.operatorToken.kind); var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next); - if (pipelinePhase === pipelineEmitWithHint && ts.isBinaryExpression(next)) { - // If the target pipeline phase is emit directly, and the next node's also a binary expression, - // skip all the intermediate indirection and push the expression directly onto the work stack - stackIndex++; - stateStack[stackIndex] = 0 /* EmitLeft */; - nodeStack[stackIndex] = next; + if (pipelinePhase === pipelineEmitWithSubstitution) { + ts.Debug.assertIsDefined(lastSubstitution); + next = parenthesizerRule(ts.cast(lastSubstitution, ts.isExpression)); + pipelinePhase = getNextPipelinePhase(1 /* Substitution */, 1 /* Expression */, next); + lastSubstitution = undefined; } - else { - pipelinePhase(1 /* Expression */, next); + if (pipelinePhase === pipelineEmitWithComments || + pipelinePhase === pipelineEmitWithSourceMaps || + pipelinePhase === pipelineEmitWithHint) { + if (ts.isBinaryExpression(next)) { + return next; + } } - ts.Debug.assert(lastNode === next); - lastNode = savedLastNode; - lastSubstitution = savedLastSubstitution; - // #endregion trampolinePipelineEmit + currentParenthesizerRule = parenthesizerRule; + pipelinePhase(1 /* Expression */, next); } } function emitConditionalExpression(node) { @@ -102513,16 +105631,16 @@ var ts; var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue); var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken); var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse); - emitExpression(node.condition); + emitExpression(node.condition, parenthesizer.parenthesizeConditionOfConditionalExpression); writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); emit(node.questionToken); writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true); - emitExpression(node.whenTrue); + emitExpression(node.whenTrue, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion); writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true); emit(node.colonToken); writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true); - emitExpression(node.whenFalse); + emitExpression(node.whenFalse, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeColon, linesAfterColon); } function emitTemplateExpression(node) { @@ -102532,22 +105650,22 @@ var ts; function emitYieldExpression(node) { emitTokenWithComment(124 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); - emitExpressionWithLeadingSpace(node.expression); + emitExpressionWithLeadingSpace(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } - function emitSpreadExpression(node) { + function emitSpreadElement(node) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitClassExpression(node) { generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); } function emitAsExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); if (node.type) { writeSpace(); writeKeyword("as"); @@ -102556,7 +105674,7 @@ var ts; } } function emitNonNullExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); writeOperator("!"); } function emitMetaProperty(node) { @@ -102599,7 +105717,7 @@ var ts; } } function emitExpressionStatement(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfExpressionStatement); // Emit semicolon in non json files // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { @@ -102616,7 +105734,7 @@ var ts; if (node.elseStatement) { writeLineOrSpace(node, node.thenStatement, node.elseStatement); emitTokenWithComment(90 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); - if (node.elseStatement.kind === 234 /* IfStatement */) { + if (node.elseStatement.kind === 235 /* IfStatement */) { writeSpace(); emit(node.elseStatement); } @@ -102679,7 +105797,7 @@ var ts; emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(156 /* OfKeyword */, node.initializer.end, writeKeyword, node); + emitTokenWithComment(157 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); @@ -102687,7 +105805,7 @@ var ts; } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 250 /* VariableDeclarationList */) { + if (node.kind === 251 /* VariableDeclarationList */) { emit(node); } else { @@ -102724,7 +105842,7 @@ var ts; } pos = writeTokenText(token, writer, pos); if (isSimilarNode && contextNode.end !== pos) { - var isJsxExprContext = contextNode.kind === 283 /* JsxExpression */; + var isJsxExprContext = contextNode.kind === 284 /* JsxExpression */; emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ !isJsxExprContext, /*forceNoNewline*/ isJsxExprContext); } return pos; @@ -102788,7 +105906,7 @@ var ts; emit(node.name); emit(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); @@ -102807,9 +105925,6 @@ var ts; emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } - function emitBlockCallback(_hint, body) { - emitBlockFunctionBody(body); - } function emitSignatureAndBody(node, emitSignatureHead) { var body = node.body; if (body) { @@ -102822,12 +105937,7 @@ var ts; ts.forEach(node.parameters, generateNames); generateNames(node.body); emitSignatureHead(node); - if (onEmitNode) { - onEmitNode(4 /* Unspecified */, body, emitBlockCallback); - } - else { - emitBlockFunctionBody(body); - } + emitBlockFunctionBody(body); popNameGenerationScope(node); if (indentedFlag) { decreaseIndent(); @@ -102836,7 +105946,7 @@ var ts; else { emitSignatureHead(node); writeSpace(); - emitExpression(body); + emitExpression(body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); } } else { @@ -102880,6 +105990,7 @@ var ts; return true; } function emitBlockFunctionBody(body) { + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(body); writeSpace(); writePunctuation("{"); increaseIndent(); @@ -102894,6 +106005,7 @@ var ts; } decreaseIndent(); writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body); + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); @@ -102909,7 +106021,7 @@ var ts; increaseIndent(); } else { - emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset); + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, /*parenthesizerRule*/ undefined, statementOffset); } } function emitClassDeclaration(node) { @@ -102984,7 +106096,7 @@ var ts; var body = node.body; if (!body) return writeTrailingSemicolon(); - while (body.kind === 256 /* ModuleDeclaration */) { + while (body && ts.isModuleDeclaration(body)) { writePunctuation("."); emit(body.name); body = body.body; @@ -103074,7 +106186,9 @@ var ts; emitTokenWithComment(87 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, node.isExportEquals ? + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(62 /* EqualsToken */) : + parenthesizer.parenthesizeExpressionOfExportDefault); writeTrailingSemicolon(); } function emitExportDeclaration(node) { @@ -103246,7 +106360,7 @@ var ts; function emitCaseClause(node) { emitTokenWithComment(81 /* CaseKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { @@ -103307,7 +106421,7 @@ var ts; var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } - emitExpression(initializer); + emitExpression(initializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitShorthandPropertyAssignment(node) { emit(node.name); @@ -103315,13 +106429,13 @@ var ts; writeSpace(); writePunctuation("="); writeSpace(); - emitExpression(node.objectAssignmentInitializer); + emitExpression(node.objectAssignmentInitializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } } function emitSpreadAssignment(node) { if (node.expression) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } } // @@ -103329,7 +106443,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // JSDoc @@ -103337,18 +106451,21 @@ var ts; function emitJSDoc(node) { write("/**"); if (node.comment) { - var lines = node.comment.split(/\r\n?|\n/g); - for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { - var line = lines_2[_a]; - writeLine(); - writeSpace(); - writePunctuation("*"); - writeSpace(); - write(line); + var text = ts.getTextOfJSDocComment(node.comment); + if (text) { + var lines = text.split(/\r\n?|\n/g); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } } } if (node.tags) { - if (node.tags.length === 1 && node.tags[0].kind === 329 /* JSDocTypeTag */ && !node.comment) { + if (node.tags.length === 1 && node.tags[0].kind === 333 /* JSDocTypeTag */ && !node.comment) { writeSpace(); emit(node.tags[0]); } @@ -103393,7 +106510,7 @@ var ts; function emitJSDocTypedefTag(tag) { emitJSDocTagName(tag.tagName); if (tag.typeExpression) { - if (tag.typeExpression.kind === 301 /* JSDocTypeExpression */) { + if (tag.typeExpression.kind === 302 /* JSDocTypeExpression */) { emitJSDocTypeExpression(tag.typeExpression); } else { @@ -103412,7 +106529,7 @@ var ts; emit(tag.fullName); } emitJSDocComment(tag.comment); - if (tag.typeExpression && tag.typeExpression.kind === 312 /* JSDocTypeLiteral */) { + if (tag.typeExpression && tag.typeExpression.kind === 314 /* JSDocTypeLiteral */) { emitJSDocTypeLiteral(tag.typeExpression); } } @@ -103465,9 +106582,10 @@ var ts; emit(tagName); } function emitJSDocComment(comment) { - if (comment) { + var text = ts.getTextOfJSDocComment(comment); + if (text) { writeSpace(); - write(comment); + write(text); } } function emitJSDocTypeExpression(typeExpression) { @@ -103570,7 +106688,7 @@ var ts; emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitTripleSlashDirectivesIfNeeded(node); - emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); + emitList(node, statements, 1 /* MultiLine */, /*parenthesizerRule*/ undefined, index === -1 ? statements.length : index); popNameGenerationScope(node); } // Transformation nodes @@ -103578,7 +106696,7 @@ var ts; emitExpression(node.expression); } function emitCommaList(node) { - emitExpressionList(node, node.elements, 528 /* CommaListElements */); + emitExpressionList(node, node.elements, 528 /* CommaListElements */, /*parenthesizerRule*/ undefined); } /** * Emits any prologue directives at the start of a Statement list, returning the @@ -103724,12 +106842,12 @@ var ts; emit(node); } } - function emitInitializer(node, equalCommentStartPos, container) { + function emitInitializer(node, equalCommentStartPos, container, parenthesizerRule) { if (node) { writeSpace(); emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container); writeSpace(); - emitExpression(node); + emitExpression(node, parenthesizerRule); } } function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { @@ -103744,10 +106862,10 @@ var ts; emit(node); } } - function emitExpressionWithLeadingSpace(node) { + function emitExpressionWithLeadingSpace(node, parenthesizerRule) { if (node) { writeSpace(); - emitExpression(node); + emitExpression(node, parenthesizerRule); } } function emitWithTrailingSpace(node) { @@ -103777,7 +106895,7 @@ var ts; emitList(parentNode, decorators, 2146305 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 53776 /* TypeArguments */); + emitList(parentNode, typeArguments, 53776 /* TypeArguments */, parenthesizer.parenthesizeMemberOfElementType); } function emitTypeParameters(parentNode, typeParameters) { if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures @@ -103816,12 +106934,6 @@ var ts; function emitParametersForIndexSignature(parentNode, parameters) { emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */); } - function emitList(parentNode, children, format, start, count) { - emitNodeList(emit, parentNode, children, format, start, count); - } - function emitExpressionList(parentNode, children, format, start, count) { - emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 - } function writeDelimiter(format) { switch (format & 60 /* DelimitersMask */) { case 0 /* None */: @@ -103844,7 +106956,13 @@ var ts; break; } } - function emitNodeList(emit, parentNode, children, format, start, count) { + function emitList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count); + } + function emitExpressionList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emitExpression, parentNode, children, format, parenthesizerRule, start, count); + } + function emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; @@ -103863,8 +106981,7 @@ var ts; } if (format & 15360 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); - if (isEmpty && !isUndefined) { - // TODO: GH#18217 + if (isEmpty && children) { emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists } } @@ -103873,7 +106990,7 @@ var ts; } if (isEmpty) { // Write a line terminator if the parent node was multi-line - if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && ts.rangeIsOnSingleLine(parentNode, currentSourceFile))) { + if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && (!parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile)))) { writeLine(); } else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) { @@ -103881,6 +106998,7 @@ var ts; } } else { + ts.Debug.type(children); // Write the opening line terminator or leading whitespace. var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; @@ -103915,7 +107033,7 @@ var ts; // a // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline // , - if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { + if (format & 60 /* DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { emitLeadingCommentsOfPosition(previousSibling.end); } writeDelimiter(format); @@ -103948,7 +107066,12 @@ var ts; shouldEmitInterveningComments = mayEmitInterveningComments; } nextListElementPos = child.pos; - emit(child); + if (emit.length === 1) { + emit(child); + } + else { + emit(child, parenthesizerRule); + } if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); shouldDecreaseIndentAfterEmit = false; @@ -103973,7 +107096,7 @@ var ts; // 2 // /* end of element 2 */ // ]; - if (previousSibling && parentNode.end !== previousSibling.end && (format & 60 /* DelimitersMask */) && !skipTrailingComments) { + if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60 /* DelimitersMask */) && !skipTrailingComments) { emitLeadingCommentsOfPosition(hasTrailingComma && (children === null || children === void 0 ? void 0 : children.end) ? children.end : previousSibling.end); } // Decrease the indent, if requested. @@ -103994,8 +107117,7 @@ var ts; onAfterEmitNodeArray(children); } if (format & 15360 /* BracketsMask */) { - if (isEmpty && !isUndefined) { - // TODO: GH#18217 + if (isEmpty && children) { emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists } writePunctuation(getClosingBracket(format)); @@ -104126,7 +107248,7 @@ var ts; } var firstChild_1 = children[0]; if (firstChild_1 === undefined) { - return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; + return !parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } if (firstChild_1.pos === nextListElementPos) { // If this child starts at the beginning of a list item in a parent list, its leading @@ -104150,7 +107272,8 @@ var ts; // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } - if (!ts.positionIsSynthesized(parentNode.pos) && + if (parentNode && + !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || ts.getOriginalNode(firstChild_1.parent) === ts.getOriginalNode(parentNode))) { if (preserveSourceNewlines) { @@ -104173,10 +107296,10 @@ var ts; // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } - else if (!ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode) && previousNode.parent === nextNode.parent) { - if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); }); - } + else if (preserveSourceNewlines && siblingNodePositionsAreComparable(previousNode, nextNode)) { + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); }); + } + else if (!preserveSourceNewlines && !ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode)) { return ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1; } else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) { @@ -104195,9 +107318,9 @@ var ts; } var lastChild = ts.lastOrUndefined(children); if (lastChild === undefined) { - return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; + return !parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } - if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { + if (parentNode && !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { if (preserveSourceNewlines) { var end_1 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end; return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_1, parentNode.end, currentSourceFile, includeComments); }); @@ -104283,7 +107406,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 207 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + while (node.kind === 208 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -104353,84 +107476,84 @@ var ts; if (!node) return; switch (node.kind) { - case 230 /* Block */: + case 231 /* Block */: ts.forEach(node.statements, generateNames); break; - case 245 /* LabeledStatement */: - case 243 /* WithStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 246 /* LabeledStatement */: + case 244 /* WithStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: generateNames(node.statement); break; - case 234 /* IfStatement */: + case 235 /* IfStatement */: generateNames(node.thenStatement); generateNames(node.elseStatement); break; - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: - case 238 /* ForInStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: + case 239 /* ForInStatement */: generateNames(node.initializer); generateNames(node.statement); break; - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: generateNames(node.caseBlock); break; - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: ts.forEach(node.clauses, generateNames); break; - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: ts.forEach(node.statements, generateNames); break; - case 247 /* TryStatement */: + case 248 /* TryStatement */: generateNames(node.tryBlock); generateNames(node.catchClause); generateNames(node.finallyBlock); break; - case 287 /* CatchClause */: + case 288 /* CatchClause */: generateNames(node.variableDeclaration); generateNames(node.block); break; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: generateNames(node.declarationList); break; - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: ts.forEach(node.declarations, generateNames); break; - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: generateNameIfNeeded(node.name); break; - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: generateNameIfNeeded(node.name); if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { ts.forEach(node.parameters, generateNames); generateNames(node.body); } break; - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: ts.forEach(node.elements, generateNames); break; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: generateNames(node.importClause); break; - case 262 /* ImportClause */: + case 263 /* ImportClause */: generateNameIfNeeded(node.name); generateNames(node.namedBindings); break; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: generateNameIfNeeded(node.name); break; - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: generateNameIfNeeded(node.name); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: ts.forEach(node.elements, generateNames); break; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: generateNameIfNeeded(node.propertyName || node.name); break; } @@ -104439,12 +107562,12 @@ var ts; if (!node) return; switch (node.kind) { - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: generateNameIfNeeded(node.name); break; } @@ -104626,23 +107749,23 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 266 /* ExportAssignment */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 267 /* ExportAssignment */: return generateNameForExportDefault(); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return generateNameForClassExpression(); - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return generateNameForMethodOrAccessor(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return makeTempVariableName(0 /* Auto */, /*reserveInNestedScopes*/ true); default: return makeTempVariableName(0 /* Auto */); @@ -104685,25 +107808,45 @@ var ts; } // Comments function pipelineEmitWithComments(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node); + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + emitCommentsBeforeNode(node); + pipelinePhase(hint, node); + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitCommentsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit leading comments + emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + } + } + function emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit trailing comments + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = false; + } + emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitLeadingCommentsOfNode(node, emitFlags, pos, end) { enterComment(); hasWrittenComment = false; - var emitFlags = ts.getEmitFlags(node); - var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; - var isEmittedNode = node.kind !== 335 /* NotEmittedStatement */; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */; var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; // Save current container state on the stack. - var savedContainerPos = containerPos; - var savedContainerEnd = containerEnd; - var savedDeclarationListContainerEnd = declarationListContainerEnd; if ((pos > 0 || end > 0) && pos !== end) { // Emit leading comments if the position is not synthesized and the node // has not opted out from emitting leading comments. if (!skipLeadingComments) { - emitLeadingComments(pos, isEmittedNode); + emitLeadingComments(pos, /*isEmittedNode*/ node.kind !== 339 /* NotEmittedStatement */); } if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments. @@ -104714,23 +107857,17 @@ var ts; containerEnd = end; // To avoid invalid comment emit in a down-level binding pattern, we // keep track of the last declaration list container's end - if (node.kind === 250 /* VariableDeclarationList */) { + if (node.kind === 251 /* VariableDeclarationList */) { declarationListContainerEnd = end; } } } ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); exitComment(); - var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node); - if (emitFlags & 2048 /* NoNestedComments */) { - commentsDisabled = true; - pipelinePhase(hint, node); - commentsDisabled = false; - } - else { - pipelinePhase(hint, node); - } + } + function emitTrailingCommentsOfNode(node, emitFlags, pos, end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { enterComment(); + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); if ((pos > 0 || end > 0) && pos !== end) { // Restore previous container state. @@ -104739,12 +107876,11 @@ var ts; declarationListContainerEnd = savedDeclarationListContainerEnd; // Emit trailing comments if the position is not synthesized and the node // has not opted out from emitting leading comments and is an emitted node. - if (!skipTrailingComments && isEmittedNode) { + if (!skipTrailingComments && node.kind !== 339 /* NotEmittedStatement */) { emitTrailingComments(end); } } exitComment(); - ts.Debug.assert(lastNode === node || lastSubstitution === node); } function emitLeadingSynthesizedComment(comment) { if (comment.hasLeadingNewline || comment.kind === 2 /* SingleLineCommentTrivia */) { @@ -104804,6 +107940,23 @@ var ts; } exitComment(); } + function siblingNodePositionsAreComparable(previousNode, nextNode) { + if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) { + return false; + } + if (nextNode.pos < previousNode.end) { + return false; + } + previousNode = ts.getOriginalNode(previousNode); + nextNode = ts.getOriginalNode(nextNode); + var parent = previousNode.parent; + if (!parent || parent !== nextNode.parent) { + return false; + } + var parentNodeArray = ts.getContainingNodeArray(previousNode); + var prevNodeIndex = parentNodeArray === null || parentNodeArray === void 0 ? void 0 : parentNodeArray.indexOf(previousNode); + return prevNodeIndex !== undefined && prevNodeIndex > -1 && parentNodeArray.indexOf(nextNode) === prevNodeIndex + 1; + } function emitLeadingComments(pos, isEmittedNode) { hasWrittenComment = false; if (isEmittedNode) { @@ -104976,42 +108129,49 @@ var ts; } return node.parsedSourceMap || undefined; } - function pipelineEmitWithSourceMap(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); + function pipelineEmitWithSourceMaps(hint, node) { var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node); - if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) { - pipelinePhase(hint, node); - } - else if (ts.isUnparsedNode(node)) { + emitSourceMapsBeforeNode(node); + pipelinePhase(hint, node); + emitSourceMapsAfterNode(node); + } + function emitSourceMapsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit leading sourcemap + if (ts.isUnparsedNode(node)) { + ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); var parsed = getParsedSourceMap(node.parent); if (parsed && sourceMapGenerator) { sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); } - pipelinePhase(hint, node); } else { - var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; - var emitFlags = ts.getEmitFlags(node); - if (node.kind !== 335 /* NotEmittedStatement */ + var source = sourceMapRange.source || sourceMapSource; + if (node.kind !== 339 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 - && pos >= 0) { - emitSourcePos(source, skipSourceTrivia(source, pos)); + && sourceMapRange.pos >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); } if (emitFlags & 64 /* NoNestedSourceMaps */) { sourceMapsDisabled = true; - pipelinePhase(hint, node); - sourceMapsDisabled = false; } - else { - pipelinePhase(hint, node); + } + } + function emitSourceMapsAfterNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit trailing sourcemap + if (!ts.isUnparsedNode(node)) { + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = false; } - if (node.kind !== 335 /* NotEmittedStatement */ + if (node.kind !== 339 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 - && end >= 0) { - emitSourcePos(source, end); + && sourceMapRange.end >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); } } - ts.Debug.assert(lastNode === node || lastSubstitution === node); } /** * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source @@ -105163,12 +108323,22 @@ var ts; return ts.getBaseFileName(ts.normalizePath(fileName)); } function createCachedFileSystemEntries(rootDir, rootDirPath) { - var resultFromHost = { - files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories(rootDir) || [] - }; - cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); - return resultFromHost; + var _a; + if (!host.realpath || ts.ensureTrailingDirectorySeparator(toPath(host.realpath(rootDir))) === rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); + return resultFromHost; + } + // If the directory is symlink do not cache the result + if ((_a = host.directoryExists) === null || _a === void 0 ? void 0 : _a.call(host, rootDir)) { + cachedReadDirectoryResult.set(rootDirPath, false); + return false; + } + // Non existing directory + return undefined; } /** * If the readDirectory result was already cached, it returns that @@ -105243,17 +108413,32 @@ var ts; } function readDirectory(rootDir, extensions, excludes, includes, depth) { var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { + var rootResult = tryReadDirectory(rootDir, rootDirPath); + var rootSymLinkResult; + if (rootResult !== undefined) { return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir) { var path = toPath(dir); if (path === rootDirPath) { - return result; - } - return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + return rootResult || getFileSystemEntriesFromHost(dir, path); + } + var result = tryReadDirectory(dir, path); + return result !== undefined ? + result || getFileSystemEntriesFromHost(dir, path) : + ts.emptyFileSystemEntries; + } + function getFileSystemEntriesFromHost(dir, path) { + if (rootSymLinkResult && path === rootDirPath) + return rootSymLinkResult; + var result = { + files: ts.map(host.readDirectory(dir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || ts.emptyArray, + directories: host.getDirectories(dir) || ts.emptyArray + }; + if (path === rootDirPath) + rootSymLinkResult = result; + return result; } } function realpath(s) { @@ -105261,7 +108446,7 @@ var ts; } function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { + if (existingResult !== undefined) { // Just clear the cache for now // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated clearCache(); @@ -105321,9 +108506,9 @@ var ts; /** * Updates the map of shared extended config file watches with a new set of extended config files from a base config file of the project */ - function updateSharedExtendedConfigFileWatcher(projectPath, parsed, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath) { + function updateSharedExtendedConfigFileWatcher(projectPath, options, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath) { var _a; - var extendedConfigs = ts.arrayToMap(((_a = parsed === null || parsed === void 0 ? void 0 : parsed.options.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath); + var extendedConfigs = ts.arrayToMap(((_a = options === null || options === void 0 ? void 0 : options.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath); // remove project from all unrelated watchers extendedConfigFilesMap.forEach(function (watcher, extendedConfigFilePath) { if (!extendedConfigs.has(extendedConfigFilePath)) { @@ -105341,12 +108526,12 @@ var ts; // start watching previously unseen extended config extendedConfigFilesMap.set(extendedConfigFilePath, { projects: new ts.Set([projectPath]), - fileWatcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath), + watcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath), close: function () { var existing = extendedConfigFilesMap.get(extendedConfigFilePath); if (!existing || existing.projects.size !== 0) return; - existing.fileWatcher.close(); + existing.watcher.close(); extendedConfigFilesMap.delete(extendedConfigFilePath); }, }); @@ -105354,6 +108539,31 @@ var ts; }); } ts.updateSharedExtendedConfigFileWatcher = updateSharedExtendedConfigFileWatcher; + /** + * Remove the project from the extended config file watchers and close not needed watches + */ + function clearSharedExtendedConfigFileWatcher(projectPath, extendedConfigFilesMap) { + extendedConfigFilesMap.forEach(function (watcher) { + if (watcher.projects.delete(projectPath)) + watcher.close(); + }); + } + ts.clearSharedExtendedConfigFileWatcher = clearSharedExtendedConfigFileWatcher; + /** + * Clean the extendsConfigCache when extended config file has changed + */ + function cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath) { + if (!extendedConfigCache.delete(extendedConfigFilePath)) + return; + extendedConfigCache.forEach(function (_a, key) { + var _b; + var extendedResult = _a.extendedResult; + if ((_b = extendedResult.extendedSourceFiles) === null || _b === void 0 ? void 0 : _b.some(function (extendedFile) { return toPath(extendedFile) === extendedConfigFilePath; })) { + cleanExtendedConfigCache(extendedConfigCache, key, toPath); + } + }); + } + ts.cleanExtendedConfigCache = cleanExtendedConfigCache; /** * Updates the existing missing file watches with the new set of missing files after new program is created */ @@ -105405,7 +108615,7 @@ var ts; ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; /* @internal */ function isIgnoredFileFromWildCardWatching(_a) { - var watchedDirPath = _a.watchedDirPath, fileOrDirectory = _a.fileOrDirectory, fileOrDirectoryPath = _a.fileOrDirectoryPath, configFileName = _a.configFileName, options = _a.options, program = _a.program, extraFileExtensions = _a.extraFileExtensions, currentDirectory = _a.currentDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, writeLog = _a.writeLog; + var watchedDirPath = _a.watchedDirPath, fileOrDirectory = _a.fileOrDirectory, fileOrDirectoryPath = _a.fileOrDirectoryPath, configFileName = _a.configFileName, options = _a.options, program = _a.program, extraFileExtensions = _a.extraFileExtensions, currentDirectory = _a.currentDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, writeLog = _a.writeLog, toPath = _a.toPath; var newPath = ts.removeIgnoredPath(fileOrDirectoryPath); if (!newPath) { writeLog("Project: " + configFileName + " Detected ignored path: " + fileOrDirectory); @@ -105441,7 +108651,8 @@ var ts; } // just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(fileOrDirectoryPath); - var realProgram = isBuilderProgram(program) ? program.getProgramOrUndefined() : program; + var realProgram = ts.isArray(program) ? undefined : isBuilderProgram(program) ? program.getProgramOrUndefined() : program; + var builderProgram = !realProgram && !ts.isArray(program) ? program : undefined; if (hasSourceFile((filePathWithoutExtension + ".ts" /* Ts */)) || hasSourceFile((filePathWithoutExtension + ".tsx" /* Tsx */))) { writeLog("Project: " + configFileName + " Detected output file: " + fileOrDirectory); @@ -105451,7 +108662,9 @@ var ts; function hasSourceFile(file) { return realProgram ? !!realProgram.getSourceFileByPath(file) : - program.getState().fileInfos.has(file); + builderProgram ? + builderProgram.getState().fileInfos.has(file) : + !!ts.find(program, function (rootFile) { return toPath(rootFile) === file; }); } } ts.isIgnoredFileFromWildCardWatching = isIgnoredFileFromWildCardWatching; @@ -105925,7 +109138,7 @@ var ts; var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; var lineContent = file.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); // trim from end - lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + lineContent = lineContent.replace(/\t/g, " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); @@ -106130,38 +109343,31 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, 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 === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames())) { + if (!program || (hasChangedAutomaticTypeDirectiveNames === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames())) return false; - } // If root file names don't match - if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) { + if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) return false; - } var seenResolvedRefs; // If project references don't match - if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + 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)) { + if (program.getSourceFiles().some(sourceFileNotUptoDate)) return false; - } // If any of the missing file paths are now created - if (program.getMissingFilePaths().some(fileExists)) { + if (program.getMissingFilePaths().some(fileExists)) return false; - } var currentOptions = program.getCompilerOptions(); // If the compilation settings do no match, then the program is not up-to-date - if (!ts.compareDataObjects(currentOptions, newOptions)) { + if (!ts.compareDataObjects(currentOptions, newOptions)) return false; - } // If everything matches but the text of config file is changed, // error locations can change for program options, so update the program - if (currentOptions.configFile && newOptions.configFile) { + if (currentOptions.configFile && newOptions.configFile) return currentOptions.configFile.text === newOptions.configFile.text; - } return true; function sourceFileNotUptoDate(sourceFile) { return !sourceFileVersionUptoDate(sourceFile) || @@ -106171,21 +109377,25 @@ var ts; return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName); } function projectReferenceUptoDate(oldRef, newRef, index) { - if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { - return false; - } - return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + return ts.projectReferenceIsEqualTo(oldRef, newRef) && + resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); } function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { if (oldResolvedRef) { - if (ts.contains(seenResolvedRefs, oldResolvedRef)) { - // Assume true + // Assume true + if (ts.contains(seenResolvedRefs, oldResolvedRef)) return true; - } - // If sourceFile for the oldResolvedRef existed, check the version for uptodate - if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + var refPath_1 = resolveProjectReferencePath(oldRef); + var newParsedCommandLine = getParsedCommandLine(refPath_1); + // Check if config file exists + if (!newParsedCommandLine) + return false; + // If change in source file + if (oldResolvedRef.commandLine.options.configFile !== newParsedCommandLine.options.configFile) + return false; + // check file names + if (!ts.arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newParsedCommandLine.fileNames)) return false; - } // Add to seen before checking the referenced paths of this config file (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); // If child project references are upto date, this project reference is uptodate @@ -106195,7 +109405,8 @@ var ts; } // In old program, not able to resolve project reference path, // so if config file doesnt exist, it is uptodate. - return !fileExists(resolveProjectReferencePath(oldRef)); + var refPath = resolveProjectReferencePath(oldRef); + return !getParsedCommandLine(refPath); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -106259,7 +109470,7 @@ var ts; var modulesWithElidedImports = new ts.Map(); // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. var sourceFilesFoundSearchingNodeModules = new ts.Map(); - ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeProgram"); var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHostLike(host); @@ -106274,6 +109485,7 @@ var ts; var hasEmitBlockingDiagnostics = new ts.Map(); var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; + var typeReferenceDirectiveResolutionCache; var actualResolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { @@ -106288,7 +109500,7 @@ var ts; }); }; } else { - moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options); + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName, options); var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } @@ -106297,7 +109509,8 @@ var ts; actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); }; } else { - var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; // TODO: GH#18217 actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } // Map from a stringified PackageId to the source file with that id. @@ -106335,15 +109548,15 @@ var ts; getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect, forEachResolvedProjectReference: forEachResolvedProjectReference }), onProgramCreateComplete = _d.onProgramCreateComplete, fileExists = _d.fileExists, directoryExists = _d.directoryExists; - ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`. var structureIsReused; - ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); structureIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (structureIsReused !== 2 /* Completely */) { processingDefaultLibFiles = []; processingOtherFiles = []; @@ -106381,13 +109594,13 @@ var ts; }); } } - ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); ts.forEach(rootNames, function (name, index) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.RootFile, index: index }); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { - ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile); @@ -106395,7 +109608,7 @@ var ts; for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i], { kind: ts.FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: (_b = resolutions[i]) === null || _b === void 0 ? void 0 : _b.packageId }); } - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // Do not process the default library if: // - The '--noLib' flag is used. @@ -106436,12 +109649,25 @@ var ts; host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); } } - oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference) { - if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { - host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + if (!host.getParsedCommandLine) { + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference) { + if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + } + }); + } + } + // Release commandlines that new program does not use + if (oldProgram && host.onReleaseParsedCommandLine) { + forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, parent, index) { + var oldReference = (parent === null || parent === void 0 ? void 0 : parent.commandLine.projectReferences[index]) || oldProgram.getProjectReferences()[index]; + var oldRefPath = resolveProjectReferencePath(oldReference); + if (!(projectReferenceRedirects === null || projectReferenceRedirects === void 0 ? void 0 : projectReferenceRedirects.has(toPath(oldRefPath)))) { + host.onReleaseParsedCommandLine(oldRefPath, oldResolvedRef, oldProgram.getCompilerOptions()); } }); } + typeReferenceDirectiveResolutionCache = undefined; // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; var program = { @@ -106470,7 +109696,6 @@ var ts; getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, - getTypeCatalog: function () { return getDiagnosticsProducingTypeChecker().getTypeCatalog(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getInstantiationCount: function () { return getDiagnosticsProducingTypeChecker().getInstantiationCount(); }, getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); }, @@ -106518,19 +109743,19 @@ var ts; verifyCompilerOptions(); ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return program; function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) { if (!moduleNames.length) return ts.emptyArray; var containingFileName = ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); var redirectedReference = getRedirectReferenceForResolution(containingFile); - ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveModule"); var result = actualResolveModuleNamesWorker(moduleNames, containingFileName, reusedNames, redirectedReference); ts.performance.mark("afterResolveModule"); ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile) { @@ -106538,12 +109763,12 @@ var ts; return []; var containingFileName = !ts.isString(containingFile) ? ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile; var redirectedReference = !ts.isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined; - ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveTypeReference"); var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference); ts.performance.mark("afterResolveTypeReference"); ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function getRedirectReferenceForResolution(file) { @@ -106636,13 +109861,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_14 = []; + var result_15 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_14.push(resolvedModule); + result_15.push(resolvedModule); } - return result_14; + return result_15; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -106753,7 +109978,9 @@ var ts; var newResolvedRef = parseProjectReferenceConfigFile(newRef); if (oldResolvedRef) { // Resolved project reference has gone missing or changed - return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + return !newResolvedRef || + newResolvedRef.sourceFile !== oldResolvedRef.sourceFile || + !ts.arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newResolvedRef.commandLine.fileNames); } else { // A previously-unresolved reference may be resolved now @@ -107015,7 +110242,7 @@ var ts; } function emitBuildInfo(writeFileCallback) { ts.Debug.assert(!ts.outFile(options)); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeEmit"); var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), /*targetSourceFile*/ undefined, @@ -107024,7 +110251,7 @@ var ts; /*onlyBuildInfo*/ true); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return emitResult; } function getResolvedProjectReferences() { @@ -107070,9 +110297,9 @@ var ts; return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) { - ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); var result = runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function isEmitBlocked(emitFileName) { @@ -107276,22 +110503,22 @@ var ts; // Return directly from the case if the given node doesnt want to visit each child // Otherwise break to visit each child switch (parent.kind) { - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?")); return "skip"; } // falls through - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: - case 249 /* VariableDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: + case 250 /* VariableDeclaration */: // type annotation if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files)); @@ -107299,58 +110526,58 @@ var ts; } } switch (node.kind) { - case 262 /* ImportClause */: + case 263 /* ImportClause */: if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type")); return "skip"; } break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type")); return "skip"; } break; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files)); return "skip"; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: var heritageClause = node; if (heritageClause.token === 116 /* ImplementsKeyword */) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: var interfaceKeyword = ts.tokenToString(117 /* InterfaceKeyword */); ts.Debug.assertIsDefined(interfaceKeyword); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword)); return "skip"; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var moduleKeyword = node.flags & 16 /* Namespace */ ? ts.tokenToString(140 /* NamespaceKeyword */) : ts.tokenToString(139 /* ModuleKeyword */); ts.Debug.assertIsDefined(moduleKeyword); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword)); return "skip"; - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files)); return "skip"; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(91 /* EnumKeyword */)); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword)); return "skip"; - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files)); return "skip"; - case 224 /* AsExpression */: + case 225 /* AsExpression */: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files)); return "skip"; - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } } @@ -107359,29 +110586,29 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning)); } switch (parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: // Check type parameters if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files)); return "skip"; } // falls through - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // Check modifiers if (nodes === parent.modifiers) { - checkModifiers(parent.modifiers, parent.kind === 232 /* VariableStatement */); + checkModifiers(parent.modifiers, parent.kind === 233 /* VariableStatement */); return "skip"; } break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // Check modifiers of property declaration if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { @@ -107393,19 +110620,19 @@ var ts; return "skip"; } break; - case 160 /* Parameter */: + case 161 /* Parameter */: // Check modifiers of parameter declaration if (nodes === parent.modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 223 /* ExpressionWithTypeArguments */: - case 274 /* JsxSelfClosingElement */: - case 275 /* JsxOpeningElement */: - case 205 /* TaggedTemplateExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 224 /* ExpressionWithTypeArguments */: + case 275 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 206 /* TaggedTemplateExpression */: // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files)); @@ -107430,6 +110657,7 @@ var ts; case 142 /* ReadonlyKeyword */: case 133 /* DeclareKeyword */: case 125 /* AbstractKeyword */: + case 156 /* OverrideKeyword */: diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind))); break; // These are all legal modifiers. @@ -107733,13 +110961,13 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { - ts.tracing.push("program" /* Program */, "findSourceFile", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "findSourceFile", { fileName: fileName, isDefaultLib: isDefaultLib || undefined, fileIncludeKind: ts.FileIncludeKind[reason.kind], }); var result = findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { @@ -107998,9 +111226,9 @@ var ts; } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { - ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { // If we already found this library as a primary reference - nothing to do @@ -108071,12 +111299,14 @@ var ts; return host.getCanonicalFileName(fileName); } function processImportedModules(file) { + var _a; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var resolutions = resolveModuleNamesReusingOldState(moduleNames, file); ts.Debug.assert(resolutions.length === moduleNames.length); + var optionsForFile = (useSourceOfProjectReferenceRedirect ? (_a = getRedirectReferenceForResolution(file)) === null || _a === void 0 ? void 0 : _a.commandLine.options : undefined) || options; for (var index = 0; index < moduleNames.length; index++) { var resolution = resolutions[index]; ts.setResolvedModule(file, moduleNames[index], resolution); @@ -108099,11 +111329,11 @@ var ts; // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') // This may still end up being an untyped module -- the file won't be included but imports will be allowed. var shouldAddFile = resolvedFileName - && !getResolutionDiagnostic(options, resolution) - && !options.noResolve + && !getResolutionDiagnostic(optionsForFile, resolution) + && !optionsForFile.noResolve && index < file.imports.length && !elideImport - && !(isJsFile && !ts.getAllowJSCompilerOption(options)) + && !(isJsFile && !ts.getAllowJSCompilerOption(optionsForFile)) && (ts.isInJSFile(file.imports[index]) || !(file.imports[index].flags & 4194304 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); @@ -108306,6 +111536,9 @@ var ts; if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } + if (options.preserveConstEnums === false) { + createDiagnosticForOptionName(ts.Diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled, "preserveConstEnums", "isolatedModules"); + } var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); @@ -108336,9 +111569,10 @@ var ts; 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 + // there has to be common source directory if user specified --outdir || --rootDir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted if (options.outDir || // there is --outDir specified + options.rootDir || // there is --rootDir specified options.sourceRoot || // there is --sourceRoot specified options.mapRoot) { // there is --mapRoot specified // Precalculate and cache the common source directory @@ -108835,7 +112069,7 @@ var ts; } function handleDirectoryCouldBeSymlink(directory) { var _a; - if (!host.getResolvedProjectReferences()) + if (!host.getResolvedProjectReferences() || ts.containsIgnoredPath(directory)) return; // Because we already watch node_modules, handle symlinks in there if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart)) @@ -108852,7 +112086,7 @@ var ts; symlinkCache.setSymlinkedDirectory(directoryPath, false); return; } - symlinkCache.setSymlinkedDirectory(directoryPath, { + symlinkCache.setSymlinkedDirectory(directory, { real: ts.ensureTrailingDirectorySeparator(real), realPath: realPath }); @@ -109128,12 +112362,15 @@ var ts; // From ambient modules for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { var ambientModule = _g[_f]; - if (ambientModule.declarations.length > 1) { + if (ambientModule.declarations && ambientModule.declarations.length > 1) { addReferenceFromAmbientModule(ambientModule); } } return referencedFiles; function addReferenceFromAmbientModule(symbol) { + if (!symbol.declarations) { + return; + } // Add any file other than our own as reference for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; @@ -109158,7 +112395,7 @@ var ts; /** * Creates the state of file references and signature for the new program from oldState if it is safe */ - function create(newProgram, getCanonicalFileName, oldState) { + function create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { var fileInfos = new ts.Map(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? new ts.Map() : undefined; var exportedModulesMap = referencedMap ? new ts.Map() : undefined; @@ -109184,13 +112421,14 @@ var ts; } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) }); + fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined }); } return { fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState }; } BuilderState.create = create; @@ -109212,6 +112450,7 @@ var ts; referencedMap: state.referencedMap && new ts.Map(state.referencedMap), exportedModulesMap: state.exportedModulesMap && new ts.Map(state.exportedModulesMap), hasCalledUpdateShapeSignature: new ts.Set(state.hasCalledUpdateShapeSignature), + useFileVersionAsSignature: state.useFileVersionAsSignature, }; } BuilderState.clone = clone; @@ -109267,23 +112506,12 @@ var ts; return ts.Debug.fail(); var prevSignature = info.signature; var latestSignature; - if (sourceFile.isDeclarationFile) { - latestSignature = sourceFile.version; - if (exportedModulesMapCache && latestSignature !== prevSignature) { - // All the references in this file are exported - var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined; - exportedModulesMapCache.set(sourceFile.resolvedPath, references || false); - } - } - else { + if (!sourceFile.isDeclarationFile && !state.useFileVersionAsSignature) { var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken, /*customTransformers*/ undefined, /*forceDtsEmit*/ true); - var firstDts_1 = emitOutput_1.outputFiles && - programOfThisState.getCompilerOptions().declarationMap ? - emitOutput_1.outputFiles.length > 1 ? emitOutput_1.outputFiles[1] : undefined : - emitOutput_1.outputFiles.length > 0 ? emitOutput_1.outputFiles[0] : undefined; + var firstDts_1 = ts.firstOrUndefined(emitOutput_1.outputFiles); if (firstDts_1) { ts.Debug.assert(ts.fileExtensionIs(firstDts_1.name, ".d.ts" /* Dts */), "File extension for signature expected to be dts", function () { return "Found: " + ts.getAnyExtensionFromPath(firstDts_1.name) + " for " + firstDts_1.name + ":: All output files: " + JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; })); }); latestSignature = (computeHash || ts.generateDjb2Hash)(firstDts_1.text); @@ -109291,12 +112519,18 @@ var ts; updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache); } } - else { - latestSignature = prevSignature; // TODO: GH#18217 + } + // Default is to use file version as signature + if (latestSignature === undefined) { + latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + // All the references in this file are exported + var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined; + exportedModulesMapCache.set(sourceFile.resolvedPath, references || false); } } cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature); - return !prevSignature || latestSignature !== prevSignature; + return latestSignature !== prevSignature; } BuilderState.updateShapeSignature = updateShapeSignature; /** @@ -109416,7 +112650,7 @@ var ts; */ function isFileAffectingGlobalScope(sourceFile) { return containsGlobalScopeAugmentation(sourceFile) || - !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + !ts.isExternalOrCommonJsModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); } /** * Gets all files of the program excluding the default library file @@ -109504,8 +112738,8 @@ var ts; /** * Create the state so that we can iterate on changedFiles/affected files */ - function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { - var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); state.compilerOptions = compilerOptions; @@ -109743,6 +112977,7 @@ var ts; * This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change */ function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash) { + var _a; removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath); // If affected files is everything except default library, then nothing more to do if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) { @@ -109756,8 +112991,15 @@ var ts; removeSemanticDiagnosticsOf(state, f.resolvedPath); }); } + // When a change affects the global scope, all files are considered to be affected without updating their signature + // That means when affected file is handled, its signature can be out of date + // To avoid this, ensure that we update the signature for any affected file in this scenario. + ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap); return; } + else { + ts.Debug.assert(state.hasCalledUpdateShapeSignature.has(affectedFile.resolvedPath) || ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.has(affectedFile.resolvedPath)), "Signature not updated for affected file: " + affectedFile.fileName); + } if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) { forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); }); } @@ -109969,83 +113211,116 @@ var ts; return undefined; var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory(); var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); - var fileInfos = {}; - state.fileInfos.forEach(function (value, key) { + var fileNames = []; + var fileNameToFileId = new ts.Map(); + var fileIdsList; + var fileNamesToFileIdListId; + var fileInfos = ts.arrayFrom(state.fileInfos.entries(), function (_a) { + var key = _a[0], value = _a[1]; + // Ensure fileId + var fileId = toFileId(key); + ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope }; + var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + return value.version === actualSignature ? + value.affectsGlobalScope ? + { version: value.version, signature: undefined, affectsGlobalScope: true } : + value.version : + actualSignature !== undefined ? + signature === undefined ? + value : + { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope } : + { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope }; }); - var result = { - fileInfos: fileInfos, - options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath) - }; + var referencedMap; if (state.referencedMap) { - var referencedMap = {}; - for (var _i = 0, _a = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { - var key = _a[_i]; - referencedMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.referencedMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); - } - result.referencedMap = referencedMap; + referencedMap = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive).map(function (key) { return [ + toFileId(key), + toFileIdListId(state.referencedMap.get(key)) + ]; }); } + var exportedModulesMap; if (state.exportedModulesMap) { - var exportedModulesMap = {}; - for (var _b = 0, _c = ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) { - var key = _c[_b]; + exportedModulesMap = ts.mapDefined(ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive), function (key) { var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key); // Not in temporary cache, use existing value if (newValue === undefined) - exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.exportedModulesMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); + return [toFileId(key), toFileIdListId(state.exportedModulesMap.get(key))]; // Value in cache and has updated value map, use that else if (newValue) - exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); - } - result.exportedModulesMap = exportedModulesMap; + return [toFileId(key), toFileIdListId(newValue)]; + }); } + var semanticDiagnosticsPerFile; if (state.semanticDiagnosticsPerFile) { - var semanticDiagnosticsPerFile = []; - for (var _d = 0, _e = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) { - var key = _e[_d]; + for (var _i = 0, _a = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var key = _a[_i]; var value = state.semanticDiagnosticsPerFile.get(key); - semanticDiagnosticsPerFile.push(value.length ? + (semanticDiagnosticsPerFile || (semanticDiagnosticsPerFile = [])).push(value.length ? [ - relativeToBuildInfo(key), + toFileId(key), state.hasReusableDiagnostic ? value : convertToReusableDiagnostics(value, relativeToBuildInfo) ] : - relativeToBuildInfo(key)); + toFileId(key)); } - result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile; } + var affectedFilesPendingEmit; if (state.affectedFilesPendingEmit) { - var affectedFilesPendingEmit = []; var seenFiles = new ts.Set(); - for (var _f = 0, _g = state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(ts.compareStringsCaseSensitive); _f < _g.length; _f++) { - var path = _g[_f]; + for (var _b = 0, _c = state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) { + var path = _c[_b]; if (ts.tryAddToSet(seenFiles, path)) { - affectedFilesPendingEmit.push([relativeToBuildInfo(path), state.affectedFilesPendingEmitKind.get(path)]); + (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push([toFileId(path), state.affectedFilesPendingEmitKind.get(path)]); } } - result.affectedFilesPendingEmit = affectedFilesPendingEmit; } - return result; + return { + fileNames: fileNames, + fileInfos: fileInfos, + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + fileIdsList: fileIdsList, + referencedMap: referencedMap, + exportedModulesMap: exportedModulesMap, + semanticDiagnosticsPerFile: semanticDiagnosticsPerFile, + affectedFilesPendingEmit: affectedFilesPendingEmit, + }; function relativeToBuildInfoEnsuringAbsolutePath(path) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory)); } function relativeToBuildInfo(path) { return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName)); } + function toFileId(path) { + var fileId = fileNameToFileId.get(path); + if (fileId === undefined) { + fileNames.push(relativeToBuildInfo(path)); + fileNameToFileId.set(path, fileId = fileNames.length); + } + return fileId; + } + function toFileIdListId(set) { + var fileIds = ts.arrayFrom(set.keys(), toFileId).sort(ts.compareValues); + var key = fileIds.join(); + var fileIdListId = fileNamesToFileIdListId === null || fileNamesToFileIdListId === void 0 ? void 0 : fileNamesToFileIdListId.get(key); + if (fileIdListId === undefined) { + (fileIdsList || (fileIdsList = [])).push(fileIds); + (fileNamesToFileIdListId || (fileNamesToFileIdListId = new ts.Map())).set(key, fileIdListId = fileIdsList.length); + } + return fileIdListId; + } } - function convertToReusableCompilerOptions(options, relativeToBuildInfo) { - var result = {}; + function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { + var result; var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo); + for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var name = _a[_i]; + var optionInfo = optionsNameMap.get(name.toLowerCase()); + if ((optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || name === "skipLibCheck" || name === "skipDefaultLibCheck") { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); } } - if (result.configFilePath) { - result.configFilePath = relativeToBuildInfo(result.configFilePath); - } return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { @@ -110137,7 +113412,7 @@ var ts; * Computing hash to for signature verification */ var computeHash = ts.maybeBind(host, host.createHash); - var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState, host.disableUseFileVersionAsSignature); var backupState; newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); }; // To ensure that we arent storing any references to old program or new program without state @@ -110361,37 +113636,31 @@ var ts; state.affectedFilesPendingEmitIndex = 0; } } - function getMapOfReferencedSet(mapLike, toPath) { - if (!mapLike) - return undefined; - var map = new ts.Map(); - // Copies keys/values from template. Note that for..in will not throw if - // template is undefined, and instead will just exit the loop. - for (var key in mapLike) { - if (ts.hasProperty(mapLike, key)) { - map.set(toPath(key), new ts.Set(mapLike[key].map(toPath))); - } - } - return map; + function toBuilderStateFileInfo(fileInfo) { + return ts.isString(fileInfo) ? + { version: fileInfo, signature: fileInfo, affectsGlobalScope: undefined } : + ts.isString(fileInfo.signature) ? + fileInfo : + { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope }; } + ts.toBuilderStateFileInfo = toBuilderStateFileInfo; function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { + var _a; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var filePaths = program.fileNames.map(toPath); + var filePathsSetList = (_a = program.fileIdsList) === null || _a === void 0 ? void 0 : _a.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); var fileInfos = new ts.Map(); - for (var key in program.fileInfos) { - if (ts.hasProperty(program.fileInfos, key)) { - fileInfos.set(toPath(key), program.fileInfos[key]); - } - } + program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); var state = { fileInfos: fileInfos, - compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), - referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), - exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), - semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + referencedMap: toMapOfReferencedSet(program.referencedMap), + exportedModulesMap: toMapOfReferencedSet(program.exportedModulesMap), + semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), hasReusableDiagnostic: true, - affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }), - affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }, function (value) { return value[1]; }), + affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), + affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, }; return { @@ -110424,6 +113693,15 @@ var ts; function toAbsolutePath(path) { return ts.getNormalizedAbsolutePath(path, buildInfoDirectory); } + function toFilePath(fileId) { + return filePaths[fileId - 1]; + } + function toFilePathsSet(fileIdsListId) { + return filePathsSetList[fileIdsListId - 1]; + } + function toMapOfReferencedSet(referenceMap) { + return referenceMap && ts.arrayToMap(referenceMap, function (value) { return toFilePath(value[0]); }, function (value) { return toFilePathsSet(value[1]); }); + } } ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { @@ -110536,9 +113814,9 @@ var ts; var resolutionsWithFailedLookups = []; var resolvedFileToResolution = ts.createMultiMap(); var hasChangedAutomaticTypeDirectiveNames = false; - var failedLookupChecks = []; - var startsWithPathChecks = []; - var isInDirectoryChecks = []; + var failedLookupChecks; + var startsWithPathChecks; + var isInDirectoryChecks; var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. @@ -110547,9 +113825,12 @@ var ts; var resolvedModuleNames = new ts.Map(); var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); - var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var moduleResolutionCache = ts.createModuleResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, perDirectoryResolvedModuleNames, nonRelativeModuleNameCache); var resolvedTypeReferenceDirectives = new ts.Map(); var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); + var typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, moduleResolutionCache.getPackageJsonInfoCache(), perDirectoryResolvedTypeReferenceDirectives); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -110581,6 +113862,7 @@ var ts; invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, createHasInvalidatedResolution: createHasInvalidatedResolution, + isFileWithInvalidatedNonRelativeUnresolvedImports: isFileWithInvalidatedNonRelativeUnresolvedImports, updateTypeRootsWatch: updateTypeRootsWatch, closeTypeRootsWatch: closeTypeRootsWatch, clear: clear @@ -110606,9 +113888,9 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) clearPerDirectoryResolutions(); @@ -110644,9 +113926,8 @@ var ts; isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { - perDirectoryResolvedModuleNames.clear(); - nonRelativeModuleNameCache.clear(); - perDirectoryResolvedTypeReferenceDirectives.clear(); + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } @@ -110673,7 +113954,7 @@ var ts; if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results - var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; if (resolvedModule) { // Modify existing resolution so its saved in the directory cache as well primaryResult.resolvedModule = resolvedModule; @@ -110684,6 +113965,9 @@ var ts; // Default return the result from the first pass return primaryResult; } + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + return ts.resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache); + } function resolveNamesWithLocalCache(_a) { var _b; var names = _a.names, containingFile = _a.containingFile, redirectedReference = _a.redirectedReference, cache = _a.cache, perDirectoryCacheWithRedirects = _a.perDirectoryCacheWithRedirects, loader = _a.loader, getResolutionWithResolvedFileName = _a.getResolutionWithResolvedFileName, shouldRetryResolution = _a.shouldRetryResolution, reusedNames = _a.reusedNames, logChanges = _a.logChanges; @@ -110771,7 +114055,7 @@ var ts; redirectedReference: redirectedReference, cache: resolvedTypeReferenceDirectives, perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives, - loader: ts.resolveTypeReferenceDirective, + loader: resolveTypeReferenceDirective, getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective, shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, }); @@ -111046,7 +114330,7 @@ var ts; if (isCreatingWatchedDirectory) { // Watching directory is created // Invalidate any resolution has failed lookup in this directory - isInDirectoryChecks.push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); } else { // If something to do with folder/file starting with "." in node_modules folder, skip it @@ -111064,8 +114348,8 @@ var ts; if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory - failedLookupChecks.push(fileOrDirectoryPath); - startsWithPathChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { @@ -111076,27 +114360,33 @@ var ts; return false; } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created - failedLookupChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + // If the invalidated file is from a node_modules package, invalidate everything else + // in the package since we might not get notifications for other files in the package. + // This hardens our logic against unreliable file watchers. + var packagePath = ts.parseNodeModuleFromPath(fileOrDirectoryPath); + if (packagePath) + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks.length && !startsWithPathChecks.length && !isInDirectoryChecks.length) { + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { return false; } var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { return resolution.failedLookupLocations.some(function (location) { var locationPath = resolutionHost.toPath(location); return ts.contains(failedLookupChecks, locationPath) || - startsWithPathChecks.some(function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath); }) || - isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); }); + ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || + (isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); })); }); } function closeTypeRootsWatch() { @@ -111247,6 +114537,9 @@ var ts; return [ambient]; var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); + if (!moduleSourceFile) { + return []; + } var modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host); var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); var existingSpecifier = ts.forEach(modulePaths, function (modulePath) { return ts.forEach(host.getFileIncludeReasons().get(ts.toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)), function (reason) { @@ -111317,7 +114610,7 @@ var ts; if (!baseUrl && !paths || relativePreference === 0 /* Relative */) { return relativePath; } - var baseDirectory = ts.getPathsBasePath(compilerOptions, host) || baseUrl; + var baseDirectory = ts.getNormalizedAbsolutePath(ts.getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory()); var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName); if (!relativeToBaseUrl) { return relativePath; @@ -111332,7 +114625,9 @@ var ts; return nonRelative; } if (relativePreference === 3 /* ExternalNonRelative */) { - var projectDirectory = host.getCurrentDirectory(); + var projectDirectory = compilerOptions.configFilePath ? + ts.toPath(ts.getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) : + info.getCanonicalFileName(host.getCurrentDirectory()); var modulePath = ts.toPath(moduleFileName, projectDirectory, getCanonicalFileName); var sourceIsInternal = ts.startsWith(sourceDirectory, projectDirectory); var targetIsInternal = ts.startsWith(modulePath, projectDirectory); @@ -111384,12 +114679,8 @@ var ts; return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined; }) || false; } - function numberOfDirectorySeparators(str) { - var match = str.match(/\//g); - return match ? match.length : 0; - } function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) { - return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareValues(numberOfDirectorySeparators(a.path), numberOfDirectorySeparators(b.path)); + return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareNumberOfDirectorySeparators(a.path, b.path); } function getNearestAncestorDirectoryWithPackageJson(host, fileName) { if (host.getNearestAncestorDirectoryWithPackageJson) { @@ -111403,40 +114694,49 @@ var ts; var getCanonicalFileName = ts.hostGetCanonicalFileName(host); var cwd = host.getCurrentDirectory(); var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined; - var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray; + var importedPath = ts.toPath(importedFileName, cwd, getCanonicalFileName); + var redirects = host.redirectTargetsMap.get(importedPath) || ts.emptyArray; var importedFileNames = __spreadArray(__spreadArray(__spreadArray([], (referenceRedirect ? [referenceRedirect] : ts.emptyArray)), [importedFileName]), redirects); var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + var shouldFilterIgnoredPaths = !ts.every(targets, ts.containsIgnoredPath); if (!preferSymlinks) { - var result_15 = ts.forEach(targets, function (p) { return cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + // Symlinks inside ignored paths are already filtered out of the symlink cache, + // so we only need to remove them from the realpath filenames. + var result_16 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_16) + return result_16; } var links = host.getSymlinkCache ? host.getSymlinkCache() : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd); - var symlinkedDirectories = links.getSymlinkedDirectories(); - var useCaseSensitiveFileNames = !host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames(); - var result = symlinkedDirectories && ts.forEachEntry(symlinkedDirectories, function (resolved, path) { - if (resolved === false) - return undefined; - if (ts.startsWithDirectory(importingFileName, resolved.realPath, getCanonicalFileName)) { - return undefined; // Don't want to a package to globally import from itself + var symlinkedDirectories = links.getSymlinkedDirectoriesByRealpath(); + var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); + var result = symlinkedDirectories && ts.forEachAncestorDirectory(ts.getDirectoryPath(fullImportedFileName), function (realPathDirectory) { + var symlinkDirectories = symlinkedDirectories.get(ts.ensureTrailingDirectorySeparator(ts.toPath(realPathDirectory, cwd, getCanonicalFileName))); + if (!symlinkDirectories) + return undefined; // Continue to ancestor directory + // Don't want to a package to globally import from itself (importNameCodeFix_symlink_own_package.ts) + if (ts.startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) { + return false; // Stop search, each ancestor directory will also hit this condition } return ts.forEach(targets, function (target) { - if (!ts.containsPath(resolved.real, target, !useCaseSensitiveFileNames)) { + if (!ts.startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) { return; } - var relative = ts.getRelativePathFromDirectory(resolved.real, target, getCanonicalFileName); - var option = ts.resolvePath(path, relative); - if (!host.fileExists || host.fileExists(option)) { - var result_16 = cb(option, target === referenceRedirect); - if (result_16) - return result_16; + var relative = ts.getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName); + for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { + var symlinkDirectory = symlinkDirectories_1[_i]; + var option = ts.resolvePath(symlinkDirectory, relative); + var result_17 = cb(option, target === referenceRedirect); + shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths + if (result_17) + return result_17; } }); }); - return result || - (preferSymlinks ? ts.forEach(targets, function (p) { return cb(p, p === referenceRedirect); }) : undefined); + return result || (preferSymlinks + ? ts.forEach(targets, function (p) { return shouldFilterIgnoredPaths && ts.containsIgnoredPath(p) ? undefined : cb(p, p === referenceRedirect); }) + : undefined); } moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule; /** @@ -111444,8 +114744,14 @@ var ts; * Symlinks will be returned first so they are preferred over the real path. */ function getAllModulePaths(importingFileName, importedFileName, host) { - var cwd = host.getCurrentDirectory(); + var _a; + var cache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + if (cache) { + var cached = cache.get(importingFileName, ts.toPath(importedFileName, host.getCurrentDirectory(), getCanonicalFileName)); + if (typeof cached === "object") + return cached; + } var allFileNames = new ts.Map(); var importedFileFromNodeModules = false; forEachFileNameOfModule(importingFileName, importedFileName, host, @@ -111457,7 +114763,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_24 = function (directory) { + var _loop_26 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -111480,10 +114786,10 @@ var ts; out_directory_1 = directory; }; var out_directory_1; - for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_7 = _loop_24(directory); + for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { + var state_9 = _loop_26(directory); directory = out_directory_1; - if (state_7 === "break") + if (state_9 === "break") break; } if (allFileNames.size) { @@ -111492,10 +114798,14 @@ var ts; remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators); sortedPaths.push.apply(sortedPaths, remainingPaths); } + if (cache) { + cache.set(importingFileName, ts.toPath(importedFileName, host.getCurrentDirectory(), getCanonicalFileName), sortedPaths); + } return sortedPaths; } function tryGetModuleNameFromAmbientModule(moduleSymbol, checker) { - var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); + var _a; + var decl = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { return decl.name.text; } @@ -111551,7 +114861,7 @@ var ts; ts.startsWith(relativeToBaseUrl, prefix) && ts.endsWith(relativeToBaseUrl, suffix) || !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); return key.replace("*", matchedStar); } } @@ -111855,10 +115165,10 @@ var ts; } ts.createWatchStatusReporter = createWatchStatusReporter; /** Parses config file using System interface */ - function parseConfigFileWithSystem(configFileName, optionsToExtend, watchOptionsToExtend, system, reportDiagnostic) { + function parseConfigFileWithSystem(configFileName, optionsToExtend, extendedConfigCache, watchOptionsToExtend, system, reportDiagnostic) { var host = system; host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; - var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, /*extendedConfigCache*/ undefined, watchOptionsToExtend); + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend); host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; } @@ -112126,7 +115436,10 @@ var ts; MissingFile: "Missing file", WildcardDirectory: "Wild card directory", FailedLookupLocations: "Failed Lookup Locations", - TypeRoots: "Type roots" + TypeRoots: "Type roots", + ConfigFileOfReferencedProject: "Config file of referened project", + ExtendedConfigOfReferencedProject: "Extended config file of referenced project", + WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project", }; function createWatchFactory(host, options) { var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; @@ -112173,6 +115486,7 @@ var ts; getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }), createHash: ts.maybeBind(host, host.createHash), readDirectory: ts.maybeBind(host, host.readDirectory), + disableUseFileVersionAsSignature: host.disableUseFileVersionAsSignature, }; function writeFile(fileName, text, writeByteOrderMark, onError) { try { @@ -112230,7 +115544,8 @@ var ts; createDirectory: function (path) { return system.createDirectory(path); }, writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, createHash: ts.maybeBind(system, system.createHash), - createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram + createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, + disableUseFileVersionAsSignature: system.disableUseFileVersionAsSignature, }; } ts.createProgramHost = createProgramHost; @@ -112318,6 +115633,7 @@ var ts; if (system === void 0) { system = ts.sys; } var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system); host.createHash = ts.maybeBind(system, system.createHash); + host.disableUseFileVersionAsSignature = system.disableUseFileVersionAsSignature; ts.setGetSourceFileAsHashVersioned(host, system); ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); }); return host; @@ -112361,11 +115677,13 @@ var ts; function createWatchProgram(host) { var builderProgram; var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc - var extendedConfigFilesMap; // Map of file watchers for the extended config files var missingFilesMap; // Map of file watchers for the missing files var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file var timerToUpdateProgram; // timer callback to recompile the program var timerToInvalidateFailedLookupResolutions; // timer callback to invalidate resolutions for changes in failed lookup locations + var parsedConfigs; // Parsed commandline and watching cached for referenced projects + var sharedExtendedConfigFileWatchers; // Map of file watchers for extended files, shared between different referenced projects + var extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info var missingFilePathsRequestedForRelease; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations @@ -112415,6 +115733,7 @@ var ts; compilerHost.getNewLine = function () { return newLine; }; compilerHost.fileExists = fileExists; compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile; + compilerHost.onReleaseParsedCommandLine = onReleaseParsedCommandLine; // Members for ResolutionCacheHost compilerHost.toPath = toPath; compilerHost.getCompilationSettings = function () { return compilerOptions; }; @@ -112428,6 +115747,7 @@ var ts; compilerHost.fileIsOpen = ts.returnFalse; compilerHost.getCurrentProgram = getCurrentProgram; compilerHost.writeLog = writeLog; + compilerHost.getParsedCommandLine = getParsedCommandLine; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : @@ -112458,7 +115778,8 @@ var ts; // Update the wild card directory watch watchConfigFileWildCardDirectories(); // Update extended config file watch - watchExtendedConfigFiles(); + if (configFileName) + updateExtendedConfigFilesWatches(toPath(configFileName), compilerOptions, watchOptions, ts.WatchType.ExtendedConfigFile); return configFileName ? { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } : { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close }; @@ -112475,9 +115796,11 @@ var ts; configFileWatcher.close(); configFileWatcher = undefined; } - if (extendedConfigFilesMap) { - ts.clearMap(extendedConfigFilesMap, ts.closeFileWatcher); - extendedConfigFilesMap = undefined; + extendedConfigCache === null || extendedConfigCache === void 0 ? void 0 : extendedConfigCache.clear(); + extendedConfigCache = undefined; + if (sharedExtendedConfigFileWatchers) { + ts.clearMap(sharedExtendedConfigFileWatchers, ts.closeFileWatcherOf); + sharedExtendedConfigFileWatchers = undefined; } if (watchedWildcardDirectories) { ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); @@ -112487,6 +115810,17 @@ var ts; ts.clearMap(missingFilesMap, ts.closeFileWatcher); missingFilesMap = undefined; } + if (parsedConfigs) { + ts.clearMap(parsedConfigs, function (config) { + var _a; + (_a = config.watcher) === null || _a === void 0 ? void 0 : _a.close(); + config.watcher = undefined; + if (config.watchedDirectories) + ts.clearMap(config.watchedDirectories, ts.closeFileWatcherOf); + config.watchedDirectories = undefined; + }); + parsedConfigs = undefined; + } } function getCurrentBuilderProgram() { return builderProgram; @@ -112506,7 +115840,7 @@ 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, projectReferences)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; @@ -112525,6 +115859,8 @@ var ts; writeLog("CreatingProgramWith::"); writeLog(" roots: " + JSON.stringify(rootFileNames)); writeLog(" options: " + JSON.stringify(compilerOptions)); + if (projectReferences) + writeLog(" projectReferences: " + JSON.stringify(projectReferences)); var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; @@ -112747,10 +116083,10 @@ var ts; // Update the wild card directory watch watchConfigFileWildCardDirectories(); // Update extended config file watch - watchExtendedConfigFiles(); + updateExtendedConfigFilesWatches(toPath(configFileName), compilerOptions, watchOptions, ts.WatchType.ExtendedConfigFile); } function parseConfigFile() { - setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217 + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, extendedConfigCache || (extendedConfigCache = new ts.Map()), watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217 } function setConfigFileParsingResult(configFileParseResult) { rootFileNames = configFileParseResult.fileNames; @@ -112762,6 +116098,56 @@ var ts; canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInputFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } + function getParsedCommandLine(configFileName) { + var configPath = toPath(configFileName); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath); + if (config) { + if (!config.reloadLevel) + return config.parsedCommandLine; + // With host implementing getParsedCommandLine we cant just update file names + if (config.parsedCommandLine && config.reloadLevel === ts.ConfigFileProgramReloadLevel.Partial && !host.getParsedCommandLine) { + writeLog("Reloading new file names and options"); + var fileNames = ts.getFileNamesFromConfigSpecs(config.parsedCommandLine.options.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost); + config.parsedCommandLine = __assign(__assign({}, config.parsedCommandLine), { fileNames: fileNames }); + config.reloadLevel = undefined; + return config.parsedCommandLine; + } + } + writeLog("Loading config file: " + configFileName); + var parsedCommandLine = host.getParsedCommandLine ? + host.getParsedCommandLine(configFileName) : + getParsedCommandLineFromConfigFileHost(configFileName); + if (config) { + config.parsedCommandLine = parsedCommandLine; + config.reloadLevel = undefined; + } + else { + (parsedConfigs || (parsedConfigs = new ts.Map())).set(configPath, config = { parsedCommandLine: parsedCommandLine }); + } + watchReferencedProject(configFileName, configPath, config); + return parsedCommandLine; + } + function getParsedCommandLineFromConfigFileHost(configFileName) { + // Ignore the file absent errors + var onUnRecoverableConfigFileDiagnostic = parseConfigFileHost.onUnRecoverableConfigFileDiagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + var parsedCommandLine = ts.getParsedCommandLineOfConfigFile(configFileName, + /*optionsToExtend*/ undefined, parseConfigFileHost, extendedConfigCache || (extendedConfigCache = new ts.Map()), watchOptionsToExtend); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = onUnRecoverableConfigFileDiagnostic; + return parsedCommandLine; + } + function onReleaseParsedCommandLine(fileName) { + var _a; + var path = toPath(fileName); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(path); + if (!config) + return; + parsedConfigs.delete(path); + if (config.watchedDirectories) + ts.clearMap(config.watchedDirectories, ts.closeFileWatcherOf); + (_a = config.watcher) === null || _a === void 0 ? void 0 : _a.close(); + ts.clearSharedExtendedConfigFileWatcher(path, sharedExtendedConfigFileWatchers); + } function watchFilePath(path, file, callback, pollingInterval, options, watchType) { return watchFile(file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options, watchType); } @@ -112771,7 +116157,6 @@ var ts; if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) { resolutionCache.invalidateResolutionOfFile(path); } - resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); nextSourceFileVersion(path); // Update the program scheduleProgramUpdate(); @@ -112782,7 +116167,10 @@ var ts; } } function watchMissingFilePath(missingFilePath) { - return watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); + // If watching missing referenced config file, we are already watching it so no need for separate watcher + return (parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.has(missingFilePath)) ? + ts.noopFileWatcher : + watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); @@ -112819,10 +116207,11 @@ var ts; configFileName: configFileName, extraFileExtensions: extraFileExtensions, options: compilerOptions, - program: getCurrentBuilderProgram(), + program: getCurrentBuilderProgram() || rootFileNames, currentDirectory: currentDirectory, useCaseSensitiveFileNames: useCaseSensitiveFileNames, - writeLog: writeLog + writeLog: writeLog, + toPath: toPath, })) return; // Reload is pending, do the reload @@ -112833,18 +116222,87 @@ var ts; } }, flags, watchOptions, ts.WatchType.WildcardDirectory); } - function watchExtendedConfigFiles() { - var _a; - // Update the extended config files watcher - ts.mutateMap(extendedConfigFilesMap || (extendedConfigFilesMap = new ts.Map()), ts.arrayToMap(((_a = compilerOptions.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath), { - // Watch the extended config files - createNewValue: watchExtendedConfigFile, - // Config files that are no longer extended should no longer be watched. - onDeleteValue: ts.closeFileWatcher - }); + function updateExtendedConfigFilesWatches(forProjectPath, options, watchOptions, watchType) { + ts.updateSharedExtendedConfigFileWatcher(forProjectPath, options, sharedExtendedConfigFileWatchers || (sharedExtendedConfigFileWatchers = new ts.Map()), function (extendedConfigFileName, extendedConfigFilePath) { return watchFile(extendedConfigFileName, function (_fileName, eventKind) { + var _a; + updateCachedSystemWithFile(extendedConfigFileName, extendedConfigFilePath, eventKind); + // Update extended config cache + if (extendedConfigCache) + ts.cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath); + // Update projects + var projects = (_a = sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects; + // If there are no referenced projects this extended config file watcher depend on ignore + if (!(projects === null || projects === void 0 ? void 0 : projects.size)) + return; + projects.forEach(function (projectPath) { + if (toPath(configFileName) === projectPath) { + // If this is the config file of the project, reload completely + reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + } + else { + // Reload config for the referenced projects and remove the resolutions from referenced projects since the config file changed + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(projectPath); + if (config) + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(projectPath); + } + scheduleProgramUpdate(); + }); + }, ts.PollingInterval.High, watchOptions, watchType); }, toPath); } - function watchExtendedConfigFile(extendedConfigFile) { - return watchFile(extendedConfigFile, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ExtendedConfigFile); + function watchReferencedProject(configFileName, configPath, commandLine) { + var _a, _b, _c, _d, _e; + // Watch file + commandLine.watcher || (commandLine.watcher = watchFile(configFileName, function (_fileName, eventKind) { + updateCachedSystemWithFile(configFileName, configPath, eventKind); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath); + if (config) + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(configPath); + scheduleProgramUpdate(); + }, ts.PollingInterval.High, ((_a = commandLine.parsedCommandLine) === null || _a === void 0 ? void 0 : _a.watchOptions) || watchOptions, ts.WatchType.ConfigFileOfReferencedProject)); + // Watch Wild card + if ((_b = commandLine.parsedCommandLine) === null || _b === void 0 ? void 0 : _b.wildcardDirectories) { + ts.updateWatchingWildcardDirectories(commandLine.watchedDirectories || (commandLine.watchedDirectories = new ts.Map()), new ts.Map(ts.getEntries((_c = commandLine.parsedCommandLine) === null || _c === void 0 ? void 0 : _c.wildcardDirectories)), function (directory, flags) { + var _a; + return watchDirectory(directory, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + // Since the file existence changed, update the sourceFiles cache + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + nextSourceFileVersion(fileOrDirectoryPath); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath); + if (!(config === null || config === void 0 ? void 0 : config.parsedCommandLine)) + return; + if (ts.isIgnoredFileFromWildCardWatching({ + watchedDirPath: toPath(directory), + fileOrDirectory: fileOrDirectory, + fileOrDirectoryPath: fileOrDirectoryPath, + configFileName: configFileName, + options: config.parsedCommandLine.options, + program: config.parsedCommandLine.fileNames, + currentDirectory: currentDirectory, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + writeLog: writeLog, + toPath: toPath, + })) + return; + // Reload is pending, do the reload + if (config.reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) { + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + // Schedule Update the program + scheduleProgramUpdate(); + } + }, flags, ((_a = commandLine.parsedCommandLine) === null || _a === void 0 ? void 0 : _a.watchOptions) || watchOptions, ts.WatchType.WildcardDirectoryOfReferencedProject); + }); + } + else if (commandLine.watchedDirectories) { + ts.clearMap(commandLine.watchedDirectories, ts.closeFileWatcherOf); + commandLine.watchedDirectories = undefined; + } + // Watch extended config files + updateExtendedConfigFilesWatches(configPath, (_d = commandLine.parsedCommandLine) === null || _d === void 0 ? void 0 : _d.options, ((_e = commandLine.parsedCommandLine) === null || _e === void 0 ? void 0 : _e.watchOptions) || watchOptions, ts.WatchType.ExtendedConfigOfReferencedProject); } } ts.createWatchProgram = createWatchProgram; @@ -113004,12 +116462,19 @@ var ts; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined; + var typeReferenceDirectiveResolutionCache = !compilerHost.resolveTypeReferenceDirectives ? ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()) : undefined; if (!compilerHost.resolveModuleNames) { var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; }; compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3); }; } + if (!compilerHost.resolveTypeReferenceDirectives) { + var loader_4 = function (moduleName, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(moduleName, containingFile, state.projectCompilerOptions, compilerHost, redirectedReference, state.typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return ts.loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_4); + }; + } var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -113034,6 +116499,7 @@ var ts; projectErrorsReported: new ts.Map(), compilerHost: compilerHost, moduleResolutionCache: moduleResolutionCache, + typeReferenceDirectiveResolutionCache: typeReferenceDirectiveResolutionCache, // Mutable state buildOrder: undefined, readFileWithCache: function (f) { return host.readFile(f); }, @@ -113072,6 +116538,10 @@ var ts; function isParsedCommandLine(entry) { return !!entry.options; } + function getCachedParsedConfigFile(state, configFilePath) { + var value = state.configFileCache.get(configFilePath); + return value && isParsedCommandLine(value) ? value : undefined; + } function parseConfigFile(state, configFileName, configFilePath) { var configFileCache = state.configFileCache; var value = configFileCache.get(configFilePath); @@ -113217,7 +116687,7 @@ var ts; function disableCache(state) { if (!state.cache) return; - var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache; + var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache, typeReferenceDirectiveResolutionCache = state.typeReferenceDirectiveResolutionCache; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; host.directoryExists = cache.originalDirectoryExists; @@ -113226,10 +116696,8 @@ var ts; compilerHost.getSourceFile = cache.originalGetSourceFile; state.readFileWithCache = cache.originalReadFileWithCache; extendedConfigCache.clear(); - if (moduleResolutionCache) { - moduleResolutionCache.directoryToModuleNameMap.clear(); - moduleResolutionCache.moduleNameToDirectoryMap.clear(); - } + moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache === null || typeReferenceDirectiveResolutionCache === void 0 ? void 0 : typeReferenceDirectiveResolutionCache.clear(); state.cache = undefined; } function clearProjectStatus(state, resolved) { @@ -113396,6 +116864,7 @@ var ts; return withProgramOrUndefined(action) || ts.emptyArray; } function createProgram() { + var _a, _b; ts.Debug.assert(program === undefined); if (state.options.dry) { reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project); @@ -113415,7 +116884,8 @@ var ts; var host = state.host, compilerHost = state.compilerHost; state.projectCompilerOptions = config.options; // Update module resolution cache if needed - updateModuleResolutionCache(state, project, config); + (_a = state.moduleResolutionCache) === null || _a === void 0 ? void 0 : _a.update(config.options); + (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options); // Create program program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences); if (state.watch) { @@ -113590,7 +117060,7 @@ var ts; emitBundle(writeFile, customTransformers); break; case BuildStep.BuildInvalidatedProjectOfBundle: - ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken); + ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken, writeFile, customTransformers); step = BuildStep.Done; break; case BuildStep.QueueReferencingProjects: @@ -113732,34 +117202,9 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } - function updateModuleResolutionCache(state, proj, config) { - if (!state.moduleResolutionCache) - return; - // Update module resolution cache if needed - var moduleResolutionCache = state.moduleResolutionCache; - var projPath = toPath(state, proj); - if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) { - // The own map will be for projectCompilerOptions - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0); - moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap); - moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap); - } - else { - // Set correct own map - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0); - var ref = { - sourceFile: config.options.configFile, - commandLine: config - }; - moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); - } - moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options); - } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { // Check tsconfig time - var tsconfigTime = state.host.getModifiedTime(configFile) || ts.missingFileModifiedTime; + var tsconfigTime = ts.getModifiedTime(state.host, configFile); if (oldestOutputFileTime < tsconfigTime) { return { type: ts.UpToDateStatusType.OutOfDateWithSelf, @@ -113769,6 +117214,7 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { + var force = !!state.options.force; var newestInputFileName = undefined; var newestInputFileTime = minimumDate; var host = state.host; @@ -113781,10 +117227,13 @@ var ts; reason: inputFile + " does not exist" }; } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; + if (!force) { + var inputTime = ts.getModifiedTime(host, inputFile); + host.getModifiedTime(inputFile); + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } } // Container if no files are specified in the project @@ -113803,36 +117252,38 @@ var ts; var missingOutputFileName; var newestDeclarationFileContentChangedTime = minimumDate; var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { - var output = outputs_1[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = 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 outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + if (!force) { + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = ts.getModifiedTime(host, output); + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var outputModifiedTime = ts.getModifiedTime(host, output); + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } } } var pseudoUpToDate = false; @@ -113868,7 +117319,8 @@ var ts; }; } // Check oldest output file name only if there is no missing output file name - if (!missingOutputFileName) { + // (a check we will have skipped if this is a forced build) + if (!force && !missingOutputFileName) { // If the upstream project's newest file is older than our oldest output, we // can't be out of date because of it if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { @@ -113914,7 +117366,7 @@ var ts; if (extendedConfigStatus) return extendedConfigStatus; } - if (!state.buildInfoChecked.has(resolvedPath)) { + if (!force && !state.buildInfoChecked.has(resolvedPath)) { state.buildInfoChecked.set(resolvedPath, true); var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); if (buildInfoPath) { @@ -113974,7 +117426,7 @@ var ts; reportStatus(state, verboseMessage, proj.options.configFilePath); } if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, ts.getModifiedTime(host, file)); } host.setModifiedTime(file, now); } @@ -114056,7 +117508,7 @@ var ts; } } } - function build(state, project, cancellationToken, onlyReferences) { + function build(state, project, cancellationToken, writeFile, getCustomTransformers, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); if (!buildOrder) return ts.ExitStatus.InvalidProject_OutputsSkipped; @@ -114068,7 +117520,7 @@ var ts; if (!invalidatedProject) break; reportQueue = false; - invalidatedProject.done(cancellationToken); + invalidatedProject.done(cancellationToken, writeFile, getCustomTransformers === null || getCustomTransformers === void 0 ? void 0 : getCustomTransformers(invalidatedProject.project)); if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; } @@ -114103,8 +117555,14 @@ var ts; continue; } var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames()); + if (!outputs.length) + continue; + var inputFileNames = new ts.Set(parsed.fileNames.map(function (f) { return toPath(state, f); })); for (var _a = 0, outputs_3 = outputs; _a < outputs_3.length; _a++) { var output = outputs_3[_a]; + // If output name is same as input file name, do not delete and ignore the error + if (inputFileNames.has(toPath(state, output))) + continue; if (host.fileExists(output)) { if (filesToDelete) { filesToDelete.push(output); @@ -114180,7 +117638,7 @@ var ts; }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); } function watchExtendedConfigFiles(state, resolvedPath, parsed) { - ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { + ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { var _a; return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (projectConfigFilePath) { return invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ts.ConfigFileProgramReloadLevel.Full); @@ -114191,6 +117649,7 @@ var ts; if (!state.watch) return; ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), new ts.Map(ts.getEntries(parsed.wildcardDirectories)), function (dir, flags) { return state.watchDirectory(dir, function (fileOrDirectory) { + var _a; if (ts.isIgnoredFileFromWildCardWatching({ watchedDirPath: toPath(state, dir), fileOrDirectory: fileOrDirectory, @@ -114198,9 +117657,10 @@ var ts; configFileName: resolved, currentDirectory: state.currentDirectory, options: parsed.options, - program: state.builderPrograms.get(resolvedPath), + program: state.builderPrograms.get(resolvedPath) || ((_a = getCachedParsedConfigFile(state, resolvedPath)) === null || _a === void 0 ? void 0 : _a.fileNames), useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames, - writeLog: function (s) { return state.writeLog(s); } + writeLog: function (s) { return state.writeLog(s); }, + toPath: function (fileName) { return toPath(state, fileName); } })) return; invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Partial); @@ -114235,19 +117695,16 @@ var ts; } function stopWatching(state) { ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher); - ts.clearMap(state.allWatchedExtendedConfigFiles, function (watcher) { - watcher.projects.clear(); - watcher.close(); - }); + ts.clearMap(state.allWatchedExtendedConfigFiles, ts.closeFileWatcherOf); ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); }); ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); }); } function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) { var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions); return { - build: function (project, cancellationToken) { return build(state, project, cancellationToken); }, + build: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers); }, clean: function (project) { return clean(state, project); }, - buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); }, + buildReferences: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers, /*onlyReferences*/ true); }, cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); }, getNextInvalidatedProject: function (cancellationToken) { setupInitialBuild(state, cancellationToken); @@ -114337,6 +117794,9 @@ var ts; } } function reportUpToDateStatus(state, configFileName, status) { + if (state.options.force && (status.type === ts.UpToDateStatusType.UpToDate || status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes)) { + return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); + } switch (status.type) { case ts.UpToDateStatusType.OutOfDateWithSelf: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); @@ -114886,6 +118346,9 @@ var ts; SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["link"] = 22] = "link"; + SymbolDisplayPartKind[SymbolDisplayPartKind["linkName"] = 23] = "linkName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["linkText"] = 24] = "linkText"; })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); var OutliningSpanKind; (function (OutliningSpanKind) { @@ -114996,6 +118459,12 @@ var ts; ScriptElementKind["jsxAttribute"] = "JSX attribute"; /** String literal */ ScriptElementKind["string"] = "string"; + /** Jsdoc @link: in `{@link C link text}`, the before and after text "{@link " and "}" */ + ScriptElementKind["link"] = "link"; + /** Jsdoc @link: in `{@link C link text}`, the entity name "C" */ + ScriptElementKind["linkName"] = "link name"; + /** Jsdoc @link: in `{@link C link text}`, the link text "link text" */ + ScriptElementKind["linkText"] = "link text"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; (function (ScriptElementKindModifier) { @@ -115088,37 +118557,37 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; - case 160 /* Parameter */: - case 198 /* BindingElement */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 287 /* CatchClause */: - case 280 /* JsxAttribute */: + case 161 /* Parameter */: + case 199 /* BindingElement */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 288 /* CatchClause */: + case 281 /* JsxAttribute */: return 1 /* Value */; - case 159 /* TypeParameter */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 177 /* TypeLiteral */: + case 160 /* TypeParameter */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 178 /* TypeLiteral */: return 2 /* Type */; - case 331 /* JSDocTypedefTag */: + case 335 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; - case 291 /* EnumMember */: - case 252 /* ClassDeclaration */: + case 292 /* EnumMember */: + case 253 /* ClassDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; } @@ -115128,16 +118597,16 @@ var ts; else { return 4 /* Namespace */; } - case 255 /* EnumDeclaration */: - case 264 /* NamedImports */: - case 265 /* ImportSpecifier */: - case 260 /* ImportEqualsDeclaration */: - case 261 /* ImportDeclaration */: - case 266 /* ExportAssignment */: - case 267 /* ExportDeclaration */: + case 256 /* EnumDeclaration */: + case 265 /* NamedImports */: + case 266 /* ImportSpecifier */: + case 261 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 267 /* ExportAssignment */: + case 268 /* ExportDeclaration */: return 7 /* All */; // An external module can be a Value - case 297 /* SourceFile */: + case 298 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 7 /* All */; @@ -115145,13 +118614,13 @@ var ts; ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { node = getAdjustedReferenceLocation(node); - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 266 /* ExportAssignment */ - || node.parent.kind === 272 /* ExternalModuleReference */ - || node.parent.kind === 265 /* ImportSpecifier */ - || node.parent.kind === 262 /* ImportClause */ + else if (node.parent.kind === 267 /* ExportAssignment */ + || node.parent.kind === 273 /* ExternalModuleReference */ + || node.parent.kind === 266 /* ImportSpecifier */ + || node.parent.kind === 263 /* ImportClause */ || ts.isImportEqualsDeclaration(node.parent) && node === node.parent.name) { return 7 /* All */; } @@ -115161,7 +118630,7 @@ var ts; else if (ts.isDeclarationName(node)) { return getMeaningFromDeclaration(node.parent); } - else if (ts.isEntityName(node) && ts.isJSDocNameReference(node.parent)) { + else if (ts.isEntityName(node) && (ts.isJSDocNameReference(node.parent) || ts.isJSDocLink(node.parent))) { return 7 /* All */; } else if (isTypeReference(node)) { @@ -115187,11 +118656,11 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - var name = node.kind === 157 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; - return name && name.parent.kind === 260 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; + var name = node.kind === 158 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; + return name && name.parent.kind === 261 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; } function isInRightSideOfInternalImportEqualsDeclaration(node) { - while (node.parent.kind === 157 /* QualifiedName */) { + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -115203,27 +118672,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 157 /* QualifiedName */) { - while (root.parent && root.parent.kind === 157 /* QualifiedName */) { + if (root.parent.kind === 158 /* QualifiedName */) { + while (root.parent && root.parent.kind === 158 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 173 /* TypeReference */ && !isLastClause; + return root.parent.kind === 174 /* TypeReference */ && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 201 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 201 /* PropertyAccessExpression */) { + if (root.parent.kind === 202 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 202 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 223 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 286 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 224 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 287 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 252 /* ClassDeclaration */ && root.parent.parent.token === 116 /* ImplementsKeyword */) || - (decl.kind === 253 /* InterfaceDeclaration */ && root.parent.parent.token === 93 /* ExtendsKeyword */); + return (decl.kind === 253 /* ClassDeclaration */ && root.parent.parent.token === 116 /* ImplementsKeyword */) || + (decl.kind === 254 /* InterfaceDeclaration */ && root.parent.parent.token === 93 /* ExtendsKeyword */); } return false; } @@ -115234,15 +118703,15 @@ var ts; switch (node.kind) { case 107 /* ThisKeyword */: return !ts.isExpressionNode(node); - case 187 /* ThisType */: + case 188 /* ThisType */: return true; } switch (node.parent.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return true; - case 195 /* ImportType */: + case 196 /* ImportType */: return !node.parent.isTypeOf; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } return false; @@ -115309,7 +118778,7 @@ var ts; ts.climbPastPropertyOrElementAccess = climbPastPropertyOrElementAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 245 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { + if (referenceNode.kind === 246 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -115370,22 +118839,22 @@ var ts; ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { switch (node.parent.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 288 /* PropertyAssignment */: - case 291 /* EnumMember */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 256 /* ModuleDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 289 /* PropertyAssignment */: + case 292 /* EnumMember */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 257 /* ModuleDeclaration */: return ts.getNameOfDeclaration(node.parent) === node; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return node.parent.argumentExpression === node; - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return true; - case 191 /* LiteralType */: - return node.parent.parent.kind === 189 /* IndexedAccessType */; + case 192 /* LiteralType */: + return node.parent.parent.kind === 190 /* IndexedAccessType */; default: return false; } @@ -115409,17 +118878,17 @@ var ts; return undefined; } switch (node.kind) { - case 297 /* SourceFile */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 256 /* ModuleDeclaration */: + case 298 /* SourceFile */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 257 /* ModuleDeclaration */: return node; } } @@ -115427,54 +118896,54 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return "module" /* moduleElement */; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return "class" /* classElement */; - case 253 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; - case 254 /* TypeAliasDeclaration */: - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: + case 254 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 255 /* TypeAliasDeclaration */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: return "type" /* typeElement */; - case 255 /* EnumDeclaration */: return "enum" /* enumElement */; - case 249 /* VariableDeclaration */: + case 256 /* EnumDeclaration */: return "enum" /* enumElement */; + case 250 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 209 /* ArrowFunction */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return "function" /* functionElement */; - case 167 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; - case 168 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 168 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 169 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: return "method" /* memberFunctionElement */; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: var initializer = node.initializer; return ts.isFunctionLike(initializer) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 289 /* ShorthandPropertyAssignment */: - case 290 /* SpreadAssignment */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 290 /* ShorthandPropertyAssignment */: + case 291 /* SpreadAssignment */: return "property" /* memberVariableElement */; - case 171 /* IndexSignature */: return "index" /* indexSignatureElement */; - case 170 /* ConstructSignature */: return "construct" /* constructSignatureElement */; - case 169 /* CallSignature */: return "call" /* callSignatureElement */; - case 166 /* Constructor */: return "constructor" /* constructorImplementationElement */; - case 159 /* TypeParameter */: return "type parameter" /* typeParameterElement */; - case 291 /* EnumMember */: return "enum member" /* enumMemberElement */; - case 160 /* Parameter */: return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; - case 260 /* ImportEqualsDeclaration */: - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: - case 263 /* NamespaceImport */: - case 269 /* NamespaceExport */: + case 172 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 171 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 170 /* CallSignature */: return "call" /* callSignatureElement */; + case 167 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 160 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 292 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 161 /* Parameter */: return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 261 /* ImportEqualsDeclaration */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: + case 264 /* NamespaceImport */: + case 270 /* NamespaceExport */: return "alias" /* alias */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { @@ -115503,7 +118972,7 @@ var ts; } case 78 /* Identifier */: return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: var scriptKind = getNodeKind(node.expression); // If the expression didn't come back with something (like it does for an identifiers) return scriptKind === "" /* unknown */ ? "const" /* constElement */ : scriptKind; @@ -115526,7 +118995,7 @@ var ts; return true; case 78 /* Identifier */: // 'this' as a parameter - return ts.identifierIsThisKeyword(node) && node.parent.kind === 160 /* Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 161 /* Parameter */; default: return false; } @@ -115591,42 +119060,42 @@ var ts; return false; } switch (n.kind) { - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 200 /* ObjectLiteralExpression */: - case 196 /* ObjectBindingPattern */: - case 177 /* TypeLiteral */: - case 230 /* Block */: - case 257 /* ModuleBlock */: - case 258 /* CaseBlock */: - case 264 /* NamedImports */: - case 268 /* NamedExports */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 201 /* ObjectLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 178 /* TypeLiteral */: + case 231 /* Block */: + case 258 /* ModuleBlock */: + case 259 /* CaseBlock */: + case 265 /* NamedImports */: + case 269 /* NamedExports */: return nodeEndsWith(n, 19 /* CloseBraceToken */, sourceFile); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 204 /* NewExpression */: + case 205 /* NewExpression */: if (!n.arguments) { return true; } // falls through - case 203 /* CallExpression */: - case 207 /* ParenthesizedExpression */: - case 186 /* ParenthesizedType */: + case 204 /* CallExpression */: + case 208 /* ParenthesizedExpression */: + case 187 /* ParenthesizedType */: return nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 170 /* ConstructSignature */: - case 169 /* CallSignature */: - case 209 /* ArrowFunction */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 171 /* ConstructSignature */: + case 170 /* CallSignature */: + case 210 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -115636,65 +119105,65 @@ var ts; // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. return hasChildOfKind(n, 21 /* CloseParenToken */, sourceFile); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return !!n.body && isCompletedNode(n.body, sourceFile); - case 234 /* IfStatement */: + case 235 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 26 /* SemicolonToken */, sourceFile); - case 199 /* ArrayLiteralExpression */: - case 197 /* ArrayBindingPattern */: - case 202 /* ElementAccessExpression */: - case 158 /* ComputedPropertyName */: - case 179 /* TupleType */: + case 200 /* ArrayLiteralExpression */: + case 198 /* ArrayBindingPattern */: + case 203 /* ElementAccessExpression */: + case 159 /* ComputedPropertyName */: + case 180 /* TupleType */: return nodeEndsWith(n, 23 /* CloseBracketToken */, sourceFile); - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 23 /* CloseBracketToken */, sourceFile); - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed return false; - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 236 /* WhileStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 237 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 235 /* DoStatement */: + case 236 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; return hasChildOfKind(n, 114 /* WhileKeyword */, sourceFile) ? nodeEndsWith(n, 21 /* CloseParenToken */, sourceFile) : isCompletedNode(n.statement, sourceFile); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 211 /* TypeOfExpression */: - case 210 /* DeleteExpression */: - case 212 /* VoidExpression */: - case 219 /* YieldExpression */: - case 220 /* SpreadElement */: + case 212 /* TypeOfExpression */: + case 211 /* DeleteExpression */: + case 213 /* VoidExpression */: + case 220 /* YieldExpression */: + case 221 /* SpreadElement */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 267 /* ExportDeclaration */: - case 261 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: return ts.nodeIsPresent(n.moduleSpecifier); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -115820,11 +119289,11 @@ var ts; function getAdjustedLocationForDeclaration(node, forRename) { if (!forRename) { switch (node.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return getAdjustedLocationForClass(node); - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return getAdjustedLocationForFunction(node); } } @@ -116084,7 +119553,7 @@ var ts; // for (... /**/in [|name|]) // for (... /**/of [|name|]) if (node.kind === 100 /* InKeyword */ && ts.isForInStatement(parent) || - node.kind === 156 /* OfKeyword */ && ts.isForOfStatement(parent)) { + node.kind === 157 /* OfKeyword */ && ts.isForOfStatement(parent)) { return ts.skipOuterExpressions(parent.expression); } } @@ -116153,6 +119622,21 @@ var ts; return current; } } + /** + * Returns the first token where position is in [start, end), + * excluding `JsxText` tokens containing only whitespace. + */ + function findFirstNonJsxWhitespaceToken(sourceFile, position) { + var tokenAtPosition = getTokenAtPosition(sourceFile, position); + while (isWhiteSpaceOnlyJsxText(tokenAtPosition)) { + var nextToken = findNextToken(tokenAtPosition, tokenAtPosition.parent, sourceFile); + if (!nextToken) + return; + tokenAtPosition = nextToken; + } + return tokenAtPosition; + } + ts.findFirstNonJsxWhitespaceToken = findFirstNonJsxWhitespaceToken; /** * The token on the left of the position is the token that strictly includes the position * or sits to the left of the cursor if it is on a boundary. For example @@ -116239,7 +119723,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 297 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 298 /* 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. @@ -116312,17 +119796,17 @@ var ts; return true; } //
{ |
or
- if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 283 /* JsxExpression */) { + if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 284 /* JsxExpression */) { return true; } //
{ // | // } < /div> - if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 283 /* JsxExpression */) { + if (token && token.kind === 19 /* CloseBraceToken */ && token.parent.kind === 284 /* JsxExpression */) { return true; } //
|
- if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 276 /* JsxClosingElement */) { + if (token.kind === 29 /* LessThanToken */ && token.parent.kind === 277 /* JsxClosingElement */) { return true; } return false; @@ -116353,7 +119837,7 @@ var ts; function isInsideJsxElement(sourceFile, position) { function isInsideJsxElementTraversal(node) { while (node) { - if (node.kind >= 274 /* JsxSelfClosingElement */ && node.kind <= 283 /* JsxExpression */ + if (node.kind >= 275 /* JsxSelfClosingElement */ && node.kind <= 284 /* JsxExpression */ || node.kind === 11 /* JsxText */ || node.kind === 29 /* LessThanToken */ || node.kind === 31 /* GreaterThanToken */ @@ -116363,7 +119847,7 @@ var ts; || node.kind === 43 /* SlashToken */) { node = node.parent; } - else if (node.kind === 273 /* JsxElement */) { + else if (node.kind === 274 /* JsxElement */) { if (position > node.getStart(sourceFile)) return true; node = node.parent; @@ -116571,16 +120055,16 @@ var ts; result.push("deprecated" /* deprecatedModifier */); if (node.flags & 8388608 /* Ambient */) result.push("declare" /* ambientModifier */); - if (node.kind === 266 /* ExportAssignment */) + if (node.kind === 267 /* ExportAssignment */) result.push("export" /* exportedModifier */); return result.length > 0 ? result.join(",") : "" /* none */; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 173 /* TypeReference */ || node.kind === 203 /* CallExpression */) { + if (node.kind === 174 /* TypeReference */ || node.kind === 204 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 252 /* ClassDeclaration */ || node.kind === 253 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 253 /* ClassDeclaration */ || node.kind === 254 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; @@ -116625,18 +120109,18 @@ var ts; } ts.cloneCompilerOptions = cloneCompilerOptions; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 199 /* ArrayLiteralExpression */ || - node.kind === 200 /* ObjectLiteralExpression */) { + if (node.kind === 200 /* ArrayLiteralExpression */ || + node.kind === 201 /* ObjectLiteralExpression */) { // [a,b,c] from: // [a, b, c] = someExpression; - if (node.parent.kind === 216 /* BinaryExpression */ && + if (node.parent.kind === 217 /* BinaryExpression */ && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */) { return true; } // [a, b, c] from: // for([a, b, c] of expression) - if (node.parent.kind === 239 /* ForOfStatement */ && + if (node.parent.kind === 240 /* ForOfStatement */ && node.parent.initializer === node) { return true; } @@ -116644,7 +120128,7 @@ var ts; // [x, [a, b, c] ] = someExpression // or // {x, a: {a, b, c} } = someExpression - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 288 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 289 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { return true; } } @@ -116764,7 +120248,7 @@ var ts; } ts.skipConstraint = skipConstraint; function getNameFromPropertyName(name) { - return name.kind === 158 /* ComputedPropertyName */ + return name.kind === 159 /* ComputedPropertyName */ // treat computed property names where expression is string/numeric literal as just string/numeric literal ? ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined : ts.isPrivateIdentifier(name) ? ts.idText(name) : ts.getTextOfIdentifierOrLiteral(name); @@ -116783,7 +120267,7 @@ var ts; } ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules; function createModuleSpecifierResolutionHost(program, host) { - // Mix in `getProbableSymlinks` from Program when host doesn't have it + // Mix in `getSymlinkCache` from Program when host doesn't have it // in order for non-Project hosts to have a symlinks cache. return { fileExists: function (fileName) { return program.fileExists(fileName); }, @@ -116791,6 +120275,7 @@ var ts; readFile: ts.maybeBind(host, host.readFile), useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), getSymlinkCache: ts.maybeBind(host, host.getSymlinkCache) || program.getSymlinkCache, + getModuleSpecifierCache: ts.maybeBind(host, host.getModuleSpecifierCache), getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation), getSourceFiles: function () { return program.getSourceFiles(); }, redirectTargetsMap: program.redirectTargetsMap, @@ -116865,6 +120350,13 @@ var ts; }); } ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isModuleSpecifierLike(node) { + return ts.isStringLiteralLike(node) && (ts.isExternalModuleReference(node.parent) || + ts.isImportDeclaration(node.parent) || + ts.isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ false) && node.parent.arguments[0] === node || + ts.isImportCall(node.parent) && node.parent.arguments[0] === node); + } + ts.isModuleSpecifierLike = isModuleSpecifierLike; function isObjectBindingElementWithoutPropertyName(bindingElement) { return ts.isBindingElement(bindingElement) && ts.isObjectBindingPattern(bindingElement.parent) && @@ -116898,7 +120390,7 @@ var ts; ts.findModifier = findModifier; function insertImports(changes, sourceFile, imports, blankLineBetween) { var decl = ts.isArray(imports) ? imports[0] : imports; - var importKindPredicate = decl.kind === 232 /* VariableStatement */ ? ts.isRequireVariableStatement : ts.isAnyImportSyntax; + var importKindPredicate = decl.kind === 233 /* VariableStatement */ ? ts.isRequireVariableStatement : ts.isAnyImportSyntax; var existingImportStatements = ts.filter(sourceFile.statements, importKindPredicate); var sortedNewImports = ts.isArray(imports) ? ts.stableSort(imports, ts.OrganizeImports.compareImportsOrRequireStatements) : [imports]; if (!existingImportStatements.length) { @@ -116976,7 +120468,7 @@ var ts; // Display-part writer helpers // #region function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 160 /* Parameter */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 161 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -117139,6 +120631,14 @@ var ts; return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); } ts.operatorPart = operatorPart; + function parameterNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.parameterName); + } + ts.parameterNamePart = parameterNamePart; + function propertyNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.propertyName); + } + ts.propertyNamePart = propertyNamePart; function textOrKeywordPart(text) { var kind = ts.stringToToken(text); return kind === undefined @@ -117150,6 +120650,58 @@ var ts; return displayPart(text, ts.SymbolDisplayPartKind.text); } ts.textPart = textPart; + function typeAliasNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.aliasName); + } + ts.typeAliasNamePart = typeAliasNamePart; + function typeParameterNamePart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.typeParameterName); + } + ts.typeParameterNamePart = typeParameterNamePart; + function linkTextPart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.linkText); + } + ts.linkTextPart = linkTextPart; + function linkNamePart(name, target) { + return { + text: ts.getTextOfNode(name), + kind: ts.SymbolDisplayPartKind[ts.SymbolDisplayPartKind.linkName], + target: { + fileName: ts.getSourceFileOfNode(target).fileName, + textSpan: createTextSpanFromNode(target), + }, + }; + } + ts.linkNamePart = linkNamePart; + function linkPart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.link); + } + ts.linkPart = linkPart; + function buildLinkParts(link, checker) { + var _a; + var parts = [linkPart("{@link ")]; + if (!link.name) { + if (link.text) { + parts.push(linkTextPart(link.text)); + } + } + else { + var symbol = checker === null || checker === void 0 ? void 0 : checker.getSymbolAtLocation(link.name); + var decl = (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) || ((_a = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]); + if (decl) { + parts.push(linkNamePart(link.name, decl)); + if (link.text) { + parts.push(linkTextPart(link.text)); + } + } + else { + parts.push(linkTextPart(ts.getTextOfNode(link.name) + link.text)); + } + } + parts.push(linkPart("}")); + return parts; + } + ts.buildLinkParts = buildLinkParts; var carriageReturnLineFeed = "\r\n"; /** * The default is CRLF. @@ -117435,21 +120987,23 @@ var ts; } /* @internal */ function needsParentheses(expression) { - return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ + || ts.isObjectLiteralExpression(expression) + || ts.isAsExpression(expression) && ts.isObjectLiteralExpression(expression.expression); } ts.needsParentheses = needsParentheses; function getContextualTypeFromParent(node, checker) { var parent = node.parent; switch (parent.kind) { - case 204 /* NewExpression */: + case 205 /* NewExpression */: return checker.getContextualType(parent); - case 216 /* BinaryExpression */: { + case 217 /* BinaryExpression */: { var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; return isEqualityOperatorKind(operatorToken.kind) ? checker.getTypeAtLocation(node === right ? left : right) : checker.getContextualType(node); } - case 284 /* CaseClause */: + case 285 /* CaseClause */: return parent.expression === node ? getSwitchedType(parent, checker) : undefined; default: return checker.getContextualType(node); @@ -117460,7 +121014,7 @@ var ts; // Editors can pass in undefined or empty string - we want to infer the preference in those cases. var quotePreference = getQuotePreference(sourceFile, preferences); var quoted = JSON.stringify(text); - return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'" : quoted; + return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace(/'/g, "\\'").replace(/\\"/g, '"') + "'" : quoted; } ts.quote = quote; function isEqualityOperatorKind(kind) { @@ -117479,8 +121033,8 @@ var ts; switch (node.kind) { case 10 /* StringLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: - case 218 /* TemplateExpression */: - case 205 /* TaggedTemplateExpression */: + case 219 /* TemplateExpression */: + case 206 /* TaggedTemplateExpression */: return true; default: return false; @@ -117513,41 +121067,41 @@ var ts; } ts.getTypeNodeIfAccessible = getTypeNodeIfAccessible; function syntaxRequiresTrailingCommaOrSemicolonOrASI(kind) { - return kind === 169 /* CallSignature */ - || kind === 170 /* ConstructSignature */ - || kind === 171 /* IndexSignature */ - || kind === 162 /* PropertySignature */ - || kind === 164 /* MethodSignature */; + return kind === 170 /* CallSignature */ + || kind === 171 /* ConstructSignature */ + || kind === 172 /* IndexSignature */ + || kind === 163 /* PropertySignature */ + || kind === 165 /* MethodSignature */; } ts.syntaxRequiresTrailingCommaOrSemicolonOrASI = syntaxRequiresTrailingCommaOrSemicolonOrASI; function syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(kind) { - return kind === 251 /* FunctionDeclaration */ - || kind === 166 /* Constructor */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 252 /* FunctionDeclaration */ + || kind === 167 /* Constructor */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } ts.syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI = syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI; function syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(kind) { - return kind === 256 /* ModuleDeclaration */; + return kind === 257 /* ModuleDeclaration */; } ts.syntaxRequiresTrailingModuleBlockOrSemicolonOrASI = syntaxRequiresTrailingModuleBlockOrSemicolonOrASI; function syntaxRequiresTrailingSemicolonOrASI(kind) { - return kind === 232 /* VariableStatement */ - || kind === 233 /* ExpressionStatement */ - || kind === 235 /* DoStatement */ - || kind === 240 /* ContinueStatement */ - || kind === 241 /* BreakStatement */ - || kind === 242 /* ReturnStatement */ - || kind === 246 /* ThrowStatement */ - || kind === 248 /* DebuggerStatement */ - || kind === 163 /* PropertyDeclaration */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 261 /* ImportDeclaration */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 267 /* ExportDeclaration */ - || kind === 259 /* NamespaceExportDeclaration */ - || kind === 266 /* ExportAssignment */; + return kind === 233 /* VariableStatement */ + || kind === 234 /* ExpressionStatement */ + || kind === 236 /* DoStatement */ + || kind === 241 /* ContinueStatement */ + || kind === 242 /* BreakStatement */ + || kind === 243 /* ReturnStatement */ + || kind === 247 /* ThrowStatement */ + || kind === 249 /* DebuggerStatement */ + || kind === 164 /* PropertyDeclaration */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 262 /* ImportDeclaration */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 268 /* ExportDeclaration */ + || kind === 260 /* NamespaceExportDeclaration */ + || kind === 267 /* ExportAssignment */; } ts.syntaxRequiresTrailingSemicolonOrASI = syntaxRequiresTrailingSemicolonOrASI; ts.syntaxMayBeASICandidate = ts.or(syntaxRequiresTrailingCommaOrSemicolonOrASI, syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI, syntaxRequiresTrailingModuleBlockOrSemicolonOrASI, syntaxRequiresTrailingSemicolonOrASI); @@ -117577,7 +121131,7 @@ var ts; return false; } // See comment in parser’s `parseDoStatement` - if (node.kind === 235 /* DoStatement */) { + if (node.kind === 236 /* DoStatement */) { return true; } var topNode = ts.findAncestor(node, function (ancestor) { return !ancestor.parent; }); @@ -117751,6 +121305,94 @@ var ts; } } ts.createPackageJsonInfo = createPackageJsonInfo; + function createPackageJsonImportFilter(fromFile, host) { + var packageJsons = ((host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName)) || getPackageJsonsVisibleToFile(fromFile.fileName, host)).filter(function (p) { return p.parseable; }); + var usesNodeCoreModules; + return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier }; + function moduleSpecifierIsCoveredByPackageJson(specifier) { + var packageName = getNodeModuleRootSpecifier(specifier); + for (var _i = 0, packageJsons_1 = packageJsons; _i < packageJsons_1.length; _i++) { + var packageJson = packageJsons_1[_i]; + if (packageJson.has(packageName) || packageJson.has(ts.getTypesPackageName(packageName))) { + return true; + } + } + return false; + } + function allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost) { + if (!packageJsons.length || !moduleSymbol.valueDeclaration) { + return true; + } + var declaringSourceFile = moduleSymbol.valueDeclaration.getSourceFile(); + var declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName, moduleSpecifierResolutionHost); + if (typeof declaringNodeModuleName === "undefined") { + return true; + } + var declaredModuleSpecifier = ts.stripQuotes(moduleSymbol.getName()); + if (isAllowedCoreNodeModulesImport(declaredModuleSpecifier)) { + return true; + } + return moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName) + || moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier); + } + function allowsImportingSourceFile(sourceFile, moduleSpecifierResolutionHost) { + if (!packageJsons.length) { + return true; + } + var moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName, moduleSpecifierResolutionHost); + if (!moduleSpecifier) { + return true; + } + return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); + } + function allowsImportingSpecifier(moduleSpecifier) { + if (!packageJsons.length || isAllowedCoreNodeModulesImport(moduleSpecifier)) { + return true; + } + if (ts.pathIsRelative(moduleSpecifier) || ts.isRootedDiskPath(moduleSpecifier)) { + return true; + } + return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); + } + function isAllowedCoreNodeModulesImport(moduleSpecifier) { + // If we’re in JavaScript, it can be difficult to tell whether the user wants to import + // from Node core modules or not. We can start by seeing if the user is actually using + // any node core modules, as opposed to simply having @types/node accidentally as a + // dependency of a dependency. + if (ts.isSourceFileJS(fromFile) && ts.JsTyping.nodeCoreModules.has(moduleSpecifier)) { + if (usesNodeCoreModules === undefined) { + usesNodeCoreModules = consumesNodeCoreModules(fromFile); + } + if (usesNodeCoreModules) { + return true; + } + } + return false; + } + function getNodeModulesPackageNameFromFileName(importedFileName, moduleSpecifierResolutionHost) { + if (!ts.stringContains(importedFileName, "node_modules")) { + return undefined; + } + var specifier = ts.moduleSpecifiers.getNodeModulesPackageName(host.getCompilationSettings(), fromFile.path, importedFileName, moduleSpecifierResolutionHost); + if (!specifier) { + return undefined; + } + // Paths here are not node_modules, so we don’t care about them; + // returning anything will trigger a lookup in package.json. + if (!ts.pathIsRelative(specifier) && !ts.isRootedDiskPath(specifier)) { + return getNodeModuleRootSpecifier(specifier); + } + } + function getNodeModuleRootSpecifier(fullSpecifier) { + var components = ts.getPathComponents(ts.getPackageNameFromTypesPackageName(fullSpecifier)).slice(1); + // Scoped packages + if (ts.startsWith(components[0], "@")) { + return components[0] + "/" + components[1]; + } + return components[0]; + } + } + ts.createPackageJsonImportFilter = createPackageJsonImportFilter; function tryParseJson(text) { try { return JSON.parse(text); @@ -117827,9 +121469,9 @@ var ts; } ts.firstOrOnly = firstOrOnly; function getNameForExportedSymbol(symbol, scriptTarget) { - if (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */) { + if (!(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */)) { // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. - return ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) + return ts.firstDefined(symbol.declarations, function (d) { var _a; return ts.isExportAssignment(d) ? (_a = ts.tryCast(ts.skipOuterExpressions(d.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget); } return symbol.name; @@ -117893,6 +121535,184 @@ var ts; return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation); } ts.isNonGlobalDeclaration = isNonGlobalDeclaration; + var ImportKind; + (function (ImportKind) { + ImportKind[ImportKind["Named"] = 0] = "Named"; + ImportKind[ImportKind["Default"] = 1] = "Default"; + ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; + ImportKind[ImportKind["CommonJS"] = 3] = "CommonJS"; + })(ImportKind = ts.ImportKind || (ts.ImportKind = {})); + var ExportKind; + (function (ExportKind) { + ExportKind[ExportKind["Named"] = 0] = "Named"; + ExportKind[ExportKind["Default"] = 1] = "Default"; + ExportKind[ExportKind["ExportEquals"] = 2] = "ExportEquals"; + ExportKind[ExportKind["UMD"] = 3] = "UMD"; + })(ExportKind = ts.ExportKind || (ts.ExportKind = {})); + function createExportMapCache() { + var cache; + var projectVersion; + var usableByFileName; + var wrapped = { + isEmpty: function () { + return !cache; + }, + clear: function () { + cache = undefined; + projectVersion = undefined; + }, + set: function (suggestions, version) { + cache = suggestions; + if (version) { + projectVersion = version; + } + }, + get: function (file, checker, version) { + if (usableByFileName && file !== usableByFileName) { + return undefined; + } + if (version && projectVersion === version) { + return cache; + } + cache === null || cache === void 0 ? void 0 : cache.forEach(function (infos) { + var _a, _b, _c; + for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { + var info = infos_1[_i]; + // If the symbol/moduleSymbol was a merged symbol, it will have a new identity + // in the checker, even though the symbols to merge are the same (guaranteed by + // cache invalidation in synchronizeHostData). + if ((_a = info.symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) { + info.symbol = checker.getMergedSymbol(info.exportKind === 1 /* Default */ + ? (_b = info.symbol.declarations[0].localSymbol) !== null && _b !== void 0 ? _b : info.symbol.declarations[0].symbol + : info.symbol.declarations[0].symbol); + } + if ((_c = info.moduleSymbol.declarations) === null || _c === void 0 ? void 0 : _c.length) { + info.moduleSymbol = checker.getMergedSymbol(info.moduleSymbol.declarations[0].symbol); + } + } + }); + return cache; + }, + onFileChanged: function (oldSourceFile, newSourceFile, typeAcquisitionEnabled) { + if (fileIsGlobalOnly(oldSourceFile) && fileIsGlobalOnly(newSourceFile)) { + // File is purely global; doesn't affect export map + return false; + } + if (usableByFileName && usableByFileName !== newSourceFile.path || + // If ATA is enabled, auto-imports uses existing imports to guess whether you want auto-imports from node. + // Adding or removing imports from node could change the outcome of that guess, so could change the suggestions list. + typeAcquisitionEnabled && consumesNodeCoreModules(oldSourceFile) !== consumesNodeCoreModules(newSourceFile) || + // Module agumentation and ambient module changes can add or remove exports available to be auto-imported. + // Changes elsewhere in the file can change the *type* of an export in a module augmentation, + // but type info is gathered in getCompletionEntryDetails, which doesn’t use the cache. + !ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations) || + !ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile)) { + this.clear(); + return true; + } + usableByFileName = newSourceFile.path; + return false; + }, + }; + if (ts.Debug.isDebugging) { + Object.defineProperty(wrapped, "__cache", { get: function () { return cache; } }); + } + return wrapped; + function fileIsGlobalOnly(file) { + return !file.commonJsModuleIndicator && !file.externalModuleIndicator && !file.moduleAugmentations && !file.ambientModuleNames; + } + function ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile) { + if (!ts.arrayIsEqualTo(oldSourceFile.ambientModuleNames, newSourceFile.ambientModuleNames)) { + return false; + } + var oldFileStatementIndex = -1; + var newFileStatementIndex = -1; + var _loop_1 = function (ambientModuleName) { + var isMatchingModuleDeclaration = function (node) { return ts.isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName; }; + oldFileStatementIndex = ts.findIndex(oldSourceFile.statements, isMatchingModuleDeclaration, oldFileStatementIndex + 1); + newFileStatementIndex = ts.findIndex(newSourceFile.statements, isMatchingModuleDeclaration, newFileStatementIndex + 1); + if (oldSourceFile.statements[oldFileStatementIndex] !== newSourceFile.statements[newFileStatementIndex]) { + return { value: false }; + } + }; + for (var _i = 0, _a = newSourceFile.ambientModuleNames; _i < _a.length; _i++) { + var ambientModuleName = _a[_i]; + var state_1 = _loop_1(ambientModuleName); + if (typeof state_1 === "object") + return state_1.value; + } + return true; + } + } + ts.createExportMapCache = createExportMapCache; + function createModuleSpecifierCache() { + var cache; + var importingFileName; + var wrapped = { + get: function (fromFileName, toFileName) { + if (!cache || fromFileName !== importingFileName) + return undefined; + return cache.get(toFileName); + }, + set: function (fromFileName, toFileName, moduleSpecifiers) { + if (cache && fromFileName !== importingFileName) { + cache.clear(); + } + importingFileName = fromFileName; + (cache || (cache = new ts.Map())).set(toFileName, moduleSpecifiers); + }, + clear: function () { + cache = undefined; + importingFileName = undefined; + }, + count: function () { + return cache ? cache.size : 0; + } + }; + if (ts.Debug.isDebugging) { + Object.defineProperty(wrapped, "__cache", { get: function () { return cache; } }); + } + return wrapped; + } + ts.createModuleSpecifierCache = createModuleSpecifierCache; + function isImportableFile(program, from, to, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) { + var _a; + if (from === to) + return false; + var cachedResult = moduleSpecifierCache === null || moduleSpecifierCache === void 0 ? void 0 : moduleSpecifierCache.get(from.path, to.path); + if (cachedResult !== undefined) { + return !!cachedResult; + } + var getCanonicalFileName = ts.hostGetCanonicalFileName(moduleSpecifierResolutionHost); + var globalTypingsCache = (_a = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation) === null || _a === void 0 ? void 0 : _a.call(moduleSpecifierResolutionHost); + var hasImportablePath = !!ts.moduleSpecifiers.forEachFileNameOfModule(from.fileName, to.fileName, moduleSpecifierResolutionHost, + /*preferSymlinks*/ false, function (toPath) { + var toFile = program.getSourceFile(toPath); + // Determine to import using toPath only if toPath is what we were looking at + // or there doesnt exist the file in the program by the symlink + return (toFile === to || !toFile) && + isImportablePath(from.fileName, toPath, getCanonicalFileName, globalTypingsCache); + }); + if (packageJsonFilter) { + var isImportable = hasImportablePath && packageJsonFilter.allowsImportingSourceFile(to, moduleSpecifierResolutionHost); + moduleSpecifierCache === null || moduleSpecifierCache === void 0 ? void 0 : moduleSpecifierCache.set(from.path, to.path, isImportable); + return isImportable; + } + return hasImportablePath; + } + ts.isImportableFile = isImportableFile; + /** + * Don't include something from a `node_modules` that isn't actually reachable by a global import. + * A relative import to node_modules is usually a bad idea. + */ + function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) { + // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. + var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); + var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules)); + return toNodeModulesParent === undefined + || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) + || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); + } // #endregion })(ts || (ts = {})); var ts; @@ -118334,13 +122154,13 @@ var ts; // That means we're calling back into the host around every 1.2k of the file we process. // Lib.d.ts has similar numbers. switch (kind) { - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 251 /* FunctionDeclaration */: - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: cancellationToken.throwIfCancellationRequested(); } } @@ -118547,10 +122367,11 @@ var ts; pushClassification(start, width, 1 /* comment */); } function classifyJSDocComment(docComment) { + var _a, _b, _c, _d, _e, _f, _g; var pos = docComment.pos; if (docComment.tags) { - for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { - var tag = _a[_i]; + for (var _i = 0, _h = docComment.tags; _i < _h.length; _i++) { + var tag = _h[_i]; // As we walk through each tag, classify the portion of text from the end of // the last tag (or the start of the entire doc comment) as 'comment'. if (tag.pos !== pos) { @@ -118559,22 +122380,56 @@ var ts; pushClassification(tag.pos, 1, 10 /* punctuation */); // "@" pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; + var commentStart = tag.tagName.end; switch (tag.kind) { - case 326 /* JSDocParameterTag */: - processJSDocParameterTag(tag); + case 330 /* JSDocParameterTag */: + var param = tag; + processJSDocParameterTag(param); + commentStart = param.isNameFirst && ((_a = param.typeExpression) === null || _a === void 0 ? void 0 : _a.end) || param.name.end; break; - case 330 /* JSDocTemplateTag */: + case 337 /* JSDocPropertyTag */: + var prop = tag; + commentStart = prop.isNameFirst && ((_b = prop.typeExpression) === null || _b === void 0 ? void 0 : _b.end) || prop.name.end; + break; + case 334 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); pos = tag.end; + commentStart = tag.typeParameters.end; + break; + case 335 /* JSDocTypedefTag */: + var type = tag; + commentStart = ((_c = type.typeExpression) === null || _c === void 0 ? void 0 : _c.kind) === 302 /* JSDocTypeExpression */ && ((_d = type.fullName) === null || _d === void 0 ? void 0 : _d.end) || ((_e = type.typeExpression) === null || _e === void 0 ? void 0 : _e.end) || commentStart; break; - case 329 /* JSDocTypeTag */: + case 328 /* JSDocCallbackTag */: + commentStart = tag.typeExpression.end; + break; + case 333 /* JSDocTypeTag */: processElement(tag.typeExpression); pos = tag.end; + commentStart = tag.typeExpression.end; + break; + case 332 /* JSDocThisTag */: + case 329 /* JSDocEnumTag */: + commentStart = tag.typeExpression.end; break; - case 327 /* JSDocReturnTag */: + case 331 /* JSDocReturnTag */: processElement(tag.typeExpression); pos = tag.end; + commentStart = ((_f = tag.typeExpression) === null || _f === void 0 ? void 0 : _f.end) || commentStart; break; + case 336 /* JSDocSeeTag */: + commentStart = ((_g = tag.name) === null || _g === void 0 ? void 0 : _g.end) || commentStart; + break; + case 318 /* JSDocAugmentsTag */: + case 319 /* JSDocImplementsTag */: + commentStart = tag.class.end; + break; + } + if (typeof tag.comment === "object") { + pushCommentRange(tag.comment.pos, tag.comment.end - tag.comment.pos); + } + else if (typeof tag.comment === "string") { + pushCommentRange(commentStart, tag.end - commentStart); } } } @@ -118722,22 +122577,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } break; - case 276 /* JsxClosingElement */: + case 277 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } break; - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } break; - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: if (token.parent.name === token) { return 22 /* jsxAttribute */; } @@ -118766,17 +122621,17 @@ var ts; var parent = token.parent; if (tokenKind === 62 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (parent.kind === 249 /* VariableDeclaration */ || - parent.kind === 163 /* PropertyDeclaration */ || - parent.kind === 160 /* Parameter */ || - parent.kind === 280 /* JsxAttribute */) { + if (parent.kind === 250 /* VariableDeclaration */ || + parent.kind === 164 /* PropertyDeclaration */ || + parent.kind === 161 /* Parameter */ || + parent.kind === 281 /* JsxAttribute */) { return 5 /* operator */; } } - if (parent.kind === 216 /* BinaryExpression */ || - parent.kind === 214 /* PrefixUnaryExpression */ || - parent.kind === 215 /* PostfixUnaryExpression */ || - parent.kind === 217 /* ConditionalExpression */) { + if (parent.kind === 217 /* BinaryExpression */ || + parent.kind === 215 /* PrefixUnaryExpression */ || + parent.kind === 216 /* PostfixUnaryExpression */ || + parent.kind === 218 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -118789,7 +122644,7 @@ var ts; return 25 /* bigintLiteral */; } else if (tokenKind === 10 /* StringLiteral */) { - return token && token.parent.kind === 280 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + return token && token.parent.kind === 281 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 13 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -118805,32 +122660,32 @@ var ts; else if (tokenKind === 78 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 160 /* Parameter */: + case 161 /* Parameter */: if (token.parent.name === token) { return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } @@ -118932,13 +122787,13 @@ var ts; var inJSXElement = false; function visit(node) { switch (node.kind) { - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 251 /* FunctionDeclaration */: - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: cancellationToken.throwIfCancellationRequested(); } if (!node || !ts.textSpanIntersectsWith(span, node.pos, node.getFullWidth()) || node.getFullWidth() === 0) { @@ -119084,25 +122939,25 @@ var ts; return (ts.isQualifiedName(node.parent) && node.parent.right === node) || (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node); } var tokenFromDeclarationMapping = new ts.Map([ - [249 /* VariableDeclaration */, 7 /* variable */], - [160 /* Parameter */, 6 /* parameter */], - [163 /* PropertyDeclaration */, 9 /* property */], - [256 /* ModuleDeclaration */, 3 /* namespace */], - [255 /* EnumDeclaration */, 1 /* enum */], - [291 /* EnumMember */, 8 /* enumMember */], - [252 /* ClassDeclaration */, 0 /* class */], - [165 /* MethodDeclaration */, 11 /* member */], - [251 /* FunctionDeclaration */, 10 /* function */], - [208 /* FunctionExpression */, 10 /* function */], - [164 /* MethodSignature */, 11 /* member */], - [167 /* GetAccessor */, 9 /* property */], - [168 /* SetAccessor */, 9 /* property */], - [162 /* PropertySignature */, 9 /* property */], - [253 /* InterfaceDeclaration */, 2 /* interface */], - [254 /* TypeAliasDeclaration */, 5 /* type */], - [159 /* TypeParameter */, 4 /* typeParameter */], - [288 /* PropertyAssignment */, 9 /* property */], - [289 /* ShorthandPropertyAssignment */, 9 /* property */] + [250 /* VariableDeclaration */, 7 /* variable */], + [161 /* Parameter */, 6 /* parameter */], + [164 /* PropertyDeclaration */, 9 /* property */], + [257 /* ModuleDeclaration */, 3 /* namespace */], + [256 /* EnumDeclaration */, 1 /* enum */], + [292 /* EnumMember */, 8 /* enumMember */], + [253 /* ClassDeclaration */, 0 /* class */], + [166 /* MethodDeclaration */, 11 /* member */], + [252 /* FunctionDeclaration */, 10 /* function */], + [209 /* FunctionExpression */, 10 /* function */], + [165 /* MethodSignature */, 11 /* member */], + [168 /* GetAccessor */, 9 /* property */], + [169 /* SetAccessor */, 9 /* property */], + [163 /* PropertySignature */, 9 /* property */], + [254 /* InterfaceDeclaration */, 2 /* interface */], + [255 /* TypeAliasDeclaration */, 5 /* type */], + [160 /* TypeParameter */, 4 /* typeParameter */], + [289 /* PropertyAssignment */, 9 /* property */], + [290 /* ShorthandPropertyAssignment */, 9 /* property */] ]); })(v2020 = classifier.v2020 || (classifier.v2020 = {})); })(classifier = ts.classifier || (ts.classifier = {})); @@ -119122,12 +122977,12 @@ var ts; if (ts.isInString(sourceFile, position, contextToken)) { if (!contextToken || !ts.isStringLiteralLike(contextToken)) return undefined; - var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); - return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, preferences); + var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); + return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, options, preferences); } } StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; - function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, preferences) { + function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, options, preferences) { if (completion === undefined) { return undefined; } @@ -119137,7 +122992,7 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences, options); // Target will not be used, so arbitrary return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, optionalReplacementSpan: optionalReplacementSpan, entries: entries }; } case 2 /* Types */: { @@ -119154,10 +123009,10 @@ var ts; return ts.Debug.assertNever(completion); } } - function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken) { + function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, options, host, cancellationToken, preferences) { if (!contextToken || !ts.isStringLiteralLike(contextToken)) return undefined; - var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); + var completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken); } StringCompletions.getStringLiteralCompletionDetails = getStringLiteralCompletionDetails; @@ -119206,13 +123061,13 @@ var ts; StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties"; StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); - function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host, preferences) { var parent = walkUpParentheses(node.parent); switch (parent.kind) { - case 191 /* LiteralType */: { + case 192 /* LiteralType */: { var grandParent = walkUpParentheses(parent.parent); switch (grandParent.kind) { - case 173 /* TypeReference */: { + case 174 /* TypeReference */: { var typeReference_1 = grandParent; var typeArgument = ts.findAncestor(parent, function (n) { return n.parent === typeReference_1; }); if (typeArgument) { @@ -119220,7 +123075,7 @@ var ts; } return undefined; } - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { // foo: string; @@ -119232,9 +123087,9 @@ var ts; return undefined; } return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(objectType)); - case 195 /* ImportType */: - return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 182 /* UnionType */: { + case 196 /* ImportType */: + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; + case 183 /* UnionType */: { if (!ts.isTypeReferenceNode(grandParent.parent)) { return undefined; } @@ -119246,7 +123101,7 @@ var ts; return undefined; } } - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { @@ -119263,7 +123118,7 @@ var ts; return stringLiteralCompletionsForObjectLiteral(typeChecker, parent.parent); } return fromContextualType(); - case 202 /* ElementAccessExpression */: { + case 203 /* ElementAccessExpression */: { var _b = parent, expression = _b.expression, argumentExpression = _b.argumentExpression; if (node === ts.skipParentheses(argumentExpression)) { // Get all names of properties on the expression @@ -119276,8 +123131,8 @@ var ts; } return undefined; } - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: 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 @@ -119286,16 +123141,16 @@ var ts; return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); } // falls through (is `require("")` or `import("")`) - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: - case 272 /* ExternalModuleReference */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 273 /* ExternalModuleReference */: // Get all known external module names or complete a path to a module // i.e. import * as ns from "/*completion position*/"; // var y = import("/*completion position*/"); // import x = require("/*completion position*/"); // var y = require("/*completion position*/"); // export * from "/*completion position*/"; - return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + return { kind: 0 /* Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; default: return fromContextualType(); } @@ -119307,9 +123162,9 @@ var ts; } function walkUpParentheses(node) { switch (node.kind) { - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return ts.walkUpParenthesizedTypes(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return ts.walkUpParenthesizedExpressions(node); default: return node; @@ -119337,7 +123192,7 @@ var ts; function stringLiteralCompletionsFromProperties(type) { return type && { kind: 1 /* Properties */, - symbols: ts.filter(type.getApparentProperties(), function (prop) { return !(prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)); }), + symbols: ts.filter(type.getApparentProperties(), function (prop) { return !(prop.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration)); }), hasIndexSignature: ts.hasIndexSignature(type) }; } @@ -119375,23 +123230,23 @@ var ts; return Math.max(name.indexOf(ts.directorySeparator), name.indexOf(ts.altDirectorySeparator)) !== -1 ? { name: name, kind: kind, extension: extension, span: wholeSpan } : { name: name, kind: kind, extension: extension, span: span }; }); } - function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { - return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); + function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) { + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences)); } - function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) { + function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = sourceFile.path; var scriptDirectory = ts.getDirectoryPath(scriptPath); return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (ts.isRootedDiskPath(literalValue) || ts.isUrl(literalValue)) - ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) + ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, preferences) : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); } function getExtensionOptions(compilerOptions, includeExtensions) { if (includeExtensions === void 0) { includeExtensions = false; } return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions: includeExtensions }; } - function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) { - var extensionOptions = getExtensionOptions(compilerOptions); + function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, preferences) { + var extensionOptions = getExtensionOptions(compilerOptions, preferences.importModuleSpecifierEnding === "js"); if (compilerOptions.rootDirs) { return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); } @@ -119508,7 +123363,7 @@ var ts; continue; var patterns = paths[path]; if (patterns) { - var _loop_1 = function (name, kind, extension) { + var _loop_2 = function (name, kind, extension) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(function (entry) { return entry.name === name; })) { result.push(nameAndKind(name, kind, extension)); @@ -119516,7 +123371,7 @@ var ts; }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; - _loop_1(name, kind, extension); + _loop_2(name, kind, extension); } } } @@ -119551,7 +123406,7 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_2 = function (moduleName) { + var _loop_3 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); @@ -119559,7 +123414,7 @@ var ts; }; for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { var moduleName = _c[_b]; - _loop_2(moduleName); + _loop_3(moduleName); } } if (!foundGlobal) { @@ -119806,6 +123661,7 @@ var ts; SymbolOriginInfoKind[SymbolOriginInfoKind["Export"] = 4] = "Export"; SymbolOriginInfoKind[SymbolOriginInfoKind["Promise"] = 8] = "Promise"; SymbolOriginInfoKind[SymbolOriginInfoKind["Nullable"] = 16] = "Nullable"; + SymbolOriginInfoKind[SymbolOriginInfoKind["ResolvedExport"] = 32] = "ResolvedExport"; SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberNoExport"] = 2] = "SymbolMemberNoExport"; SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberExport"] = 6] = "SymbolMemberExport"; })(SymbolOriginInfoKind || (SymbolOriginInfoKind = {})); @@ -119818,8 +123674,14 @@ var ts; function originIsExport(origin) { return !!(origin && origin.kind & 4 /* Export */); } + function originIsResolvedExport(origin) { + return !!(origin && origin.kind === 32 /* ResolvedExport */); + } + function originIncludesSymbolName(origin) { + return originIsExport(origin) || originIsResolvedExport(origin); + } function originIsPackageJsonImport(origin) { - return originIsExport(origin) && !!origin.isFromPackageJson; + return (originIsExport(origin) || originIsResolvedExport(origin)) && !!origin.isFromPackageJson; } function originIsPromise(origin) { return !!(origin.kind & 8 /* Promise */); @@ -119845,52 +123707,6 @@ var ts; GlobalsSearch[GlobalsSearch["Success"] = 1] = "Success"; GlobalsSearch[GlobalsSearch["Fail"] = 2] = "Fail"; })(GlobalsSearch || (GlobalsSearch = {})); - function createImportSuggestionsForFileCache() { - var cache; - var projectVersion; - var fileName; - return { - isEmpty: function () { - return !cache; - }, - clear: function () { - cache = undefined; - fileName = undefined; - projectVersion = undefined; - }, - set: function (file, suggestions, version) { - cache = suggestions; - fileName = file; - if (version) { - projectVersion = version; - } - }, - get: function (file, checker, version) { - if (file !== fileName) { - return undefined; - } - if (version) { - return projectVersion === version ? cache : undefined; - } - ts.forEach(cache, function (suggestion) { - var _a, _b, _c; - // If the symbol/moduleSymbol was a merged symbol, it will have a new identity - // in the checker, even though the symbols to merge are the same (guaranteed by - // cache invalidation in synchronizeHostData). - if ((_a = suggestion.symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) { - suggestion.symbol = checker.getMergedSymbol(suggestion.origin.isDefaultExport - ? (_b = suggestion.symbol.declarations[0].localSymbol) !== null && _b !== void 0 ? _b : suggestion.symbol.declarations[0].symbol - : suggestion.symbol.declarations[0].symbol); - } - if ((_c = suggestion.origin.moduleSymbol.declarations) === null || _c === void 0 ? void 0 : _c.length) { - suggestion.origin.moduleSymbol = checker.getMergedSymbol(suggestion.origin.moduleSymbol.declarations[0].symbol); - } - }); - return cache; - }, - }; - } - Completions.createImportSuggestionsForFileCache = createImportSuggestionsForFileCache; function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); @@ -119898,6 +123714,13 @@ var ts; if (triggerCharacter && !ts.isInString(sourceFile, position, contextToken) && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) { return undefined; } + if (triggerCharacter === " ") { + // `isValidTrigger` ensures we are at `import |` + if (preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) { + return { isGlobalCompletion: true, isMemberCompletion: false, isNewIdentifierLocation: true, isIncomplete: true, entries: [] }; + } + return undefined; + } var stringCompletions = Completions.StringCompletions.getStringLiteralCompletions(sourceFile, position, contextToken, typeChecker, compilerOptions, host, log, preferences); if (stringCompletions) { return stringCompletions; @@ -119921,6 +123744,8 @@ var ts; return jsdocCompletionInfo(ts.JsDoc.getJSDocTagCompletions()); case 3 /* JsDocParameterName */: return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag)); + case 4 /* Keywords */: + return specificKeywordCompletionInfo(completionData.keywords); default: return ts.Debug.assertNever(completionData); } @@ -119929,33 +123754,36 @@ var ts; function jsdocCompletionInfo(entries) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } + function specificKeywordCompletionInfo(keywords) { + return { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: false, + entries: keywords.map(function (k) { return ({ + name: ts.tokenToString(k), + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, + sortText: SortText.GlobalsOrKeywords, + }); }), + }; + } function getOptionalReplacementSpan(location) { // StringLiteralLike locations are handled separately in stringCompletions.ts return (location === null || location === void 0 ? void 0 : location.kind) === 78 /* Identifier */ ? ts.createTextSpanFromNode(location) : undefined; } function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { - var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextMap = completionData.symbolToSortTextMap; - if (location && location.parent && ts.isJsxClosingElement(location.parent)) { - // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, - // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. - // For example: - // var x =
" with type any - // And at `
` (with a closing `>`), the completion list will contain "div". - var tagName = location.parent.parent.openingElement.tagName; - var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 31 /* GreaterThanToken */, sourceFile); - var entry = { - name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), - kind: "class" /* classElement */, - kindModifiers: undefined, - sortText: SortText.LocationPriority, - }; - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, optionalReplacementSpan: getOptionalReplacementSpan(location), entries: [entry] }; + var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation, isJsxIdentifierExpected = completionData.isJsxIdentifierExpected, importCompletionNode = completionData.importCompletionNode, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextMap = completionData.symbolToSortTextMap; + // Verify if the file is JSX language variant + if (ts.getLanguageVariant(sourceFile.scriptKind) === 1 /* JSX */) { + var completionInfo = getJsxClosingTagCompletion(location, sourceFile); + if (completionInfo) { + return completionInfo; + } } var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, - /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); + /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { @@ -119963,7 +123791,7 @@ var ts; return undefined; } getCompletionEntriesFromSymbols(symbols, entries, - /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); + /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); } if (keywordFilters !== 0 /* None */) { var entryNames = new ts.Set(entries.map(function (e) { return e.name; })); @@ -119999,6 +123827,49 @@ var ts; return false; } } + function getJsxClosingTagCompletion(location, sourceFile) { + // We wanna walk up the tree till we find a JSX closing element + var jsxClosingElement = ts.findAncestor(location, function (node) { + switch (node.kind) { + case 277 /* JsxClosingElement */: + return true; + case 43 /* SlashToken */: + case 31 /* GreaterThanToken */: + case 78 /* Identifier */: + case 202 /* PropertyAccessExpression */: + return false; + default: + return "quit"; + } + }); + if (jsxClosingElement) { + // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, + // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. + // For example: + // var x =
" with type any + // And at `
` (with a closing `>`), the completion list will contain "div". + // And at property access expressions ` ` the completion will + // return full closing tag with an optional replacement span + // For example: + // var x = + // var y = + // the completion list at "1" and "2" will contain "MainComponent.Child" with a replacement span of closing tag name + var hasClosingAngleBracket = !!ts.findChildOfKind(jsxClosingElement, 31 /* GreaterThanToken */, sourceFile); + var tagName = jsxClosingElement.parent.openingElement.tagName; + var closingTag = tagName.getText(sourceFile); + var fullClosingTag = closingTag + (hasClosingAngleBracket ? "" : ">"); + var replacementSpan = ts.createTextSpanFromNode(jsxClosingElement.tagName); + var entry = { + name: fullClosingTag, + kind: "class" /* classElement */, + kindModifiers: undefined, + sortText: SortText.LocationPriority, + }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, optionalReplacementSpan: replacementSpan, entries: [entry] }; + } + return; + } function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location @@ -120025,9 +123896,13 @@ var ts; function createCompletionEntryForLiteral(sourceFile, preferences, literal) { return { name: completionNameForLiteral(sourceFile, preferences, literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority }; } - function createCompletionEntry(symbol, sortText, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { + function createCompletionEntry(symbol, sortText, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, options, preferences) { + var _a; var insertText; var replacementSpan = ts.getReplacementSpanForContextToken(contextToken); + var data; + var isSnippet; + var sourceDisplay; var insertQuestionDot = origin && originIsNullableMember(origin); var useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; if (origin && originIsThisType(origin)) { @@ -120071,9 +123946,24 @@ var ts; insertText = needsConvertPropertyAccess ? "" + awaitText + insertText : "" + awaitText + (insertQuestionDot ? "?." : ".") + insertText; replacementSpan = ts.createTextSpanFromBounds(propertyAccessToConvert.getStart(sourceFile), propertyAccessToConvert.end); } + if (originIsResolvedExport(origin)) { + ts.Debug.assertIsDefined(importCompletionNode); + (_a = getInsertTextAndReplacementSpanForImportCompletion(name, importCompletionNode, origin, useSemicolons, options, preferences), insertText = _a.insertText, replacementSpan = _a.replacementSpan); + sourceDisplay = [ts.textPart(origin.moduleSpecifier)]; + isSnippet = preferences.includeCompletionsWithSnippetText ? true : undefined; + } if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { return undefined; } + if (originIsExport(origin) || originIsResolvedExport(origin)) { + data = { + exportName: origin.exportName, + fileName: origin.fileName, + ambientModuleName: origin.fileName ? undefined : ts.stripQuotes(origin.moduleSymbol.name), + isPackageJsonImport: origin.isFromPackageJson ? true : undefined, + moduleSpecifier: originIsResolvedExport(origin) ? origin.moduleSpecifier : undefined, + }; + } // TODO(drosen): Right now we just permit *all* semantic meanings when calling // 'getSymbolKind' which is permissible given that it is backwards compatible; but // really we should consider passing the meaning for the node so that we don't report @@ -120091,9 +123981,30 @@ var ts; isRecommended: isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker) || undefined, insertText: insertText, replacementSpan: replacementSpan, + sourceDisplay: sourceDisplay, + isSnippet: isSnippet, isPackageJsonImport: originIsPackageJsonImport(origin) || undefined, + isImportStatementCompletion: originIsResolvedExport(origin) || undefined, + data: data, }; } + function getInsertTextAndReplacementSpanForImportCompletion(name, importCompletionNode, origin, useSemicolons, options, preferences) { + var sourceFile = importCompletionNode.getSourceFile(); + var replacementSpan = ts.createTextSpanFromNode(importCompletionNode, sourceFile); + var quotedModuleSpecifier = ts.quote(sourceFile, preferences, origin.moduleSpecifier); + var exportKind = origin.isDefaultExport ? 1 /* Default */ : + origin.exportName === "export=" /* ExportEquals */ ? 2 /* ExportEquals */ : + 0 /* Named */; + var tabStop = preferences.includeCompletionsWithSnippetText ? "$1" : ""; + var importKind = ts.codefix.getImportKind(sourceFile, exportKind, options); + var suffix = useSemicolons ? ";" : ""; + switch (importKind) { + case 3 /* CommonJS */: return { replacementSpan: replacementSpan, insertText: "import " + name + tabStop + " = require(" + quotedModuleSpecifier + ")" + suffix }; + case 1 /* Default */: return { replacementSpan: replacementSpan, insertText: "import " + name + tabStop + " from " + quotedModuleSpecifier + suffix }; + case 2 /* Namespace */: return { replacementSpan: replacementSpan, insertText: "import * as " + name + tabStop + " from " + quotedModuleSpecifier + suffix }; + case 0 /* Named */: return { replacementSpan: replacementSpan, insertText: "import { " + name + tabStop + " } from " + quotedModuleSpecifier + suffix }; + } + } function quotePropertyName(sourceFile, preferences, name) { if (/^\d+$/.test(name)) { return name; @@ -120108,29 +124019,31 @@ var ts; if (originIsExport(origin)) { return ts.stripQuotes(origin.moduleSymbol.name); } + if (originIsResolvedExport(origin)) { + return origin.moduleSpecifier; + } if ((origin === null || origin === void 0 ? void 0 : origin.kind) === 1 /* ThisType */) { return CompletionSource.ThisProperty; } } - function getCompletionEntriesFromSymbols(symbols, entries, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) { + function getCompletionEntriesFromSymbols(symbols, entries, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) { var start = ts.timestamp(); + var variableDeclaration = getVariableDeclaration(location); + var useSemicolons = ts.probablyUsesSemicolons(sourceFile); // Tracks unique names. // Value is set to false for global variables or completions from external module exports, because we can have multiple of those; // true otherwise. Based on the order we add things we will always see locals first, then globals, then module exports. // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. var uniques = new ts.Map(); - for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { - var symbol = symbols_1[_i]; - var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; + for (var i = 0; i < symbols.length; i++) { + var symbol = symbols[i]; + var origin = symbolToOriginInfoMap === null || symbolToOriginInfoMap === void 0 ? void 0 : symbolToOriginInfoMap[i]; var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, !!jsxIdentifierExpected); - if (!info) { + if (!info || uniques.get(info.name) || kind === 1 /* Global */ && symbolToSortTextMap && !shouldIncludeSymbol(symbol, symbolToSortTextMap)) { continue; } var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; - if (uniques.get(name)) { - continue; - } - var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); + var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, compilerOptions, preferences); if (!entry) { continue; } @@ -120147,6 +124060,46 @@ var ts; has: function (name) { return uniques.has(name); }, add: function (name) { return uniques.set(name, true); }, }; + function shouldIncludeSymbol(symbol, symbolToSortTextMap) { + if (!ts.isSourceFile(location)) { + // export = /**/ here we want to get all meanings, so any symbol is ok + if (ts.isExportAssignment(location.parent)) { + return true; + } + // Filter out variables from their own initializers + // `const a = /* no 'a' here */` + if (variableDeclaration && symbol.valueDeclaration === variableDeclaration) { + return false; + } + // External modules can have global export declarations that will be + // available as global keywords in all scopes. But if the external module + // already has an explicit export and user only wants to user explicit + // module imports then the global keywords will be filtered out so auto + // import suggestions will win in the completion + var symbolOrigin = ts.skipAlias(symbol, typeChecker); + // We only want to filter out the global keywords + // Auto Imports are not available for scripts so this conditional is always false + if (!!sourceFile.externalModuleIndicator + && !compilerOptions.allowUmdGlobalAccess + && symbolToSortTextMap[ts.getSymbolId(symbol)] === SortText.GlobalsOrKeywords + && (symbolToSortTextMap[ts.getSymbolId(symbolOrigin)] === SortText.AutoImportSuggestions + || symbolToSortTextMap[ts.getSymbolId(symbolOrigin)] === SortText.LocationPriority)) { + return false; + } + // Continue with origin symbol + symbol = symbolOrigin; + // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) + if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { + return !!(symbol.flags & 1920 /* Namespace */); + } + if (isTypeOnlyLocation) { + // It's a type, but you can reach it by namespace.type as well + return symbolCanBeReferencedAtTypeLocation(symbol, typeChecker); + } + } + // expressions are value space (which includes the value namespaces) + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 111551 /* Value */); + } } Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; function getLabelCompletionAtPosition(node) { @@ -120180,6 +124133,20 @@ var ts; return entries; } function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences) { + if (entryId.data) { + var autoImport = getAutoImportSymbolFromCompletionEntryData(entryId.name, entryId.data, program, host); + if (autoImport) { + return { + type: "symbol", + symbol: autoImport.symbol, + location: ts.getTouchingPropertyName(sourceFile, position), + previousToken: ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined), + isJsxInitializer: false, + isTypeOnlyLocation: false, + origin: autoImport.origin, + }; + } + } var compilerOptions = program.getCompilerOptions(); var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId, host); if (!completionData) { @@ -120196,11 +124163,11 @@ var ts; // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - return ts.firstDefined(symbols, function (symbol) { - var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + return ts.firstDefined(symbols, function (symbol, index) { + var origin = symbolToOriginInfoMap[index]; var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind, completionData.isJsxIdentifierExpected); return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source - ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation } + ? { type: "symbol", symbol: symbol, location: location, origin: origin, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation } : undefined; }) || { type: "none" }; } @@ -120210,7 +124177,7 @@ var ts; var name = entryId.name; var contextToken = ts.findPrecedingToken(position, sourceFile); if (ts.isInString(sourceFile, position, contextToken)) { - return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken); + return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken, preferences); } // Compute all the completion symbols again. var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences); @@ -120224,13 +124191,15 @@ var ts; return ts.JsDoc.getJSDocTagCompletionDetails(name); case 3 /* JsDocParameterName */: return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); + case 4 /* Keywords */: + return request.keywords.indexOf(ts.stringToToken(name)) > -1 ? createSimpleDetails(name, "keyword" /* keyword */, ts.SymbolDisplayPartKind.keyword) : undefined; default: return ts.Debug.assertNever(request); } } case "symbol": { - var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + var symbol = symbolCompletion.symbol, location = symbolCompletion.location, origin = symbolCompletion.origin, previousToken = symbolCompletion.previousToken; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(origin, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, entryId.data), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } case "literal": { @@ -120256,15 +124225,17 @@ var ts; } Completions.createCompletionDetailsForSymbol = createCompletionDetailsForSymbol; function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { - return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; + return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source, sourceDisplay: source }; } Completions.createCompletionDetails = createCompletionDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences) { - var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { + function getCompletionEntryCodeActionsAndSourceDisplay(origin, symbol, program, checker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data) { + if (data === null || data === void 0 ? void 0 : data.moduleSpecifier) { + return { codeActions: undefined, sourceDisplay: [ts.textPart(data.moduleSpecifier)] }; + } + if (!origin || !originIsExport(origin)) { return { codeActions: undefined, sourceDisplay: undefined }; } - var moduleSymbol = symbolOriginInfo.moduleSymbol; + var moduleSymbol = origin.moduleSymbol; var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, compilerOptions.target), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; @@ -120280,6 +124251,7 @@ var ts; CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName"; CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag"; CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName"; + CompletionDataKind[CompletionDataKind["Keywords"] = 4] = "Keywords"; })(CompletionDataKind || (CompletionDataKind = {})); var CompletionKind; (function (CompletionKind) { @@ -120307,11 +124279,11 @@ var ts; return ts.getContextualTypeFromParent(previousToken, checker); case 62 /* EqualsToken */: switch (parent.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return checker.getContextualType(parent.initializer); // TODO: GH#18217 - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return checker.getTypeAtLocation(parent.left); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return checker.getContextualTypeForJsxAttribute(parent); default: return undefined; @@ -120321,7 +124293,7 @@ var ts; case 81 /* CaseKeyword */: return ts.getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); case 18 /* OpenBraceToken */: - return ts.isJsxExpression(parent) && parent.parent.kind !== 273 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; + return ts.isJsxExpression(parent) && parent.parent.kind !== 274 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; default: var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile); return argInfo ? @@ -120340,7 +124312,8 @@ var ts; return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); } function isModuleSymbol(symbol) { - return symbol.declarations.some(function (d) { return d.kind === 297 /* SourceFile */; }); + var _a; + return !!((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d.kind === 298 /* SourceFile */; })); } function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId, host) { var typeChecker = program.getTypeChecker(); @@ -120391,11 +124364,11 @@ var ts; if (tag.tagName.pos <= position && position <= tag.tagName.end) { return { kind: 1 /* JsDocTagName */ }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 301 /* JSDocTypeExpression */) { + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 302 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 333 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 337 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -120420,7 +124393,7 @@ var ts; var contextToken = previousToken; // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. - if (contextToken && position <= contextToken.end && (ts.isIdentifierOrPrivateIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { + if (contextToken && position <= contextToken.end && (ts.isMemberName(contextToken) || ts.isKeyword(contextToken.kind))) { var start_1 = ts.timestamp(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1)); @@ -120436,10 +124409,22 @@ var ts; var isStartingCloseTag = false; var isJsxInitializer = false; var isJsxIdentifierExpected = false; + var importCompletionNode; var location = ts.getTouchingPropertyName(sourceFile, position); if (contextToken) { + var importCompletionCandidate = getImportCompletionNode(contextToken); + if (importCompletionCandidate === 153 /* FromKeyword */) { + return { kind: 4 /* Keywords */, keywords: [153 /* FromKeyword */] }; + } + // Import statement completions use `insertText`, and also require the `data` property of `CompletionEntryIdentifier` + // added in TypeScript 4.3 to be sent back from the client during `getCompletionEntryDetails`. Since this feature + // is not backward compatible with older clients, the language service defaults to disabling it, allowing newer clients + // to opt in with the `includeCompletionsForImportStatements` user preference. + if (importCompletionCandidate && preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) { + importCompletionNode = importCompletionCandidate; + } // Bail out if this is a known invalid completion location - if (isCompletionListBlocker(contextToken)) { + if (!importCompletionNode && isCompletionListBlocker(contextToken)) { log("Returning an empty list because completion was requested in an invalid position."); return undefined; } @@ -120448,7 +124433,7 @@ var ts; isRightOfDot = contextToken.kind === 24 /* DotToken */; isRightOfQuestionDot = contextToken.kind === 28 /* QuestionDotToken */; switch (parent.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: propertyAccessToConvert = parent; node = propertyAccessToConvert.expression; if ((ts.isCallExpression(node) || ts.isFunctionLike(node)) && @@ -120461,14 +124446,14 @@ var ts; return undefined; } break; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: node = parent.left; break; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: node = parent.name; break; - case 195 /* ImportType */: - case 226 /* MetaProperty */: + case 196 /* ImportType */: + case 227 /* MetaProperty */: node = parent; break; default: @@ -120477,11 +124462,11 @@ var ts; return undefined; } } - else if (sourceFile.languageVariant === 1 /* JSX */) { + else if (!importCompletionNode && sourceFile.languageVariant === 1 /* JSX */) { // // If the tagname is a property access expression, we will then walk up to the top most of property access expression. // Then, try to get a JSX container and its associated attributes type. - if (parent && parent.kind === 201 /* PropertyAccessExpression */) { + if (parent && parent.kind === 202 /* PropertyAccessExpression */) { contextToken = parent; parent = parent.parent; } @@ -120489,45 +124474,45 @@ var ts; if (currentToken.parent === location) { switch (currentToken.kind) { case 31 /* GreaterThanToken */: - if (currentToken.parent.kind === 273 /* JsxElement */ || currentToken.parent.kind === 275 /* JsxOpeningElement */) { + if (currentToken.parent.kind === 274 /* JsxElement */ || currentToken.parent.kind === 276 /* JsxOpeningElement */) { location = currentToken; } break; case 43 /* SlashToken */: - if (currentToken.parent.kind === 274 /* JsxSelfClosingElement */) { + if (currentToken.parent.kind === 275 /* JsxSelfClosingElement */) { location = currentToken; } break; } } switch (parent.kind) { - case 276 /* JsxClosingElement */: + case 277 /* JsxClosingElement */: if (contextToken.kind === 43 /* SlashToken */) { isStartingCloseTag = true; location = contextToken; } break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (!binaryExpressionMayBeOpenTag(parent)) { break; } // falls through - case 274 /* JsxSelfClosingElement */: - case 273 /* JsxElement */: - case 275 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + case 274 /* JsxElement */: + case 276 /* JsxOpeningElement */: isJsxIdentifierExpected = true; if (contextToken.kind === 29 /* LessThanToken */) { isRightOfOpenTag = true; location = contextToken; } break; - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: // For `
`, `parent` will be `{true}` and `previousToken` will be `}` if (previousToken.kind === 19 /* CloseBraceToken */ && currentToken.kind === 31 /* GreaterThanToken */) { isJsxIdentifierExpected = true; } break; - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: // For `
`, `parent` will be JsxAttribute and `previousToken` will be its initializer if (parent.initializer === previousToken && previousToken.end < position) { @@ -120561,8 +124546,11 @@ var ts; var symbols = []; var symbolToOriginInfoMap = []; var symbolToSortTextMap = []; - var importSuggestionsCache = host.getImportSuggestionsCache && host.getImportSuggestionsCache(); + var seenPropertySymbols = new ts.Map(); var isTypeOnly = isTypeOnlyCompletion(); + var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { + return ts.createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); + }); if (isRightOfDot || isRightOfQuestionDot) { getTypeScriptMemberSymbols(); } @@ -120571,7 +124559,7 @@ var ts; ts.Debug.assertEachIsDefined(tagSymbols, "getJsxIntrinsicTagNames() should all be defined"); tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); - completionKind = 3 /* MemberLike */; + completionKind = 1 /* Global */; keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { @@ -120580,7 +124568,7 @@ var ts; if (tagSymbol) { symbols = [tagSymbol]; } - completionKind = 3 /* MemberLike */; + completionKind = 1 /* Global */; keywordFilters = 0 /* None */; } else { @@ -120613,14 +124601,15 @@ var ts; symbolToSortTextMap: symbolToSortTextMap, isTypeOnlyLocation: isTypeOnly, isJsxIdentifierExpected: isJsxIdentifierExpected, + importCompletionNode: importCompletionNode, }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 326 /* JSDocParameterTag */: - case 333 /* JSDocPropertyTag */: - case 327 /* JSDocReturnTag */: - case 329 /* JSDocTypeTag */: - case 331 /* JSDocTypedefTag */: + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: + case 331 /* JSDocReturnTag */: + case 333 /* JSDocTypeTag */: + case 335 /* JSDocTypedefTag */: return true; default: return false; @@ -120648,10 +124637,10 @@ var ts; var exportedSymbols = typeChecker.getExportsOfModule(symbol); ts.Debug.assertEachIsDefined(exportedSymbols, "getExportsOfModule() should all be defined"); var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess(isImportType ? node : (node.parent), symbol.name); }; - var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; + var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol, typeChecker); }; var isValidAccess = isNamespaceName // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion. - ? function (symbol) { return !!(symbol.flags & 1920 /* Namespace */) && !symbol.declarations.every(function (d) { return d.parent === node.parent; }); } + ? function (symbol) { var _a; return !!(symbol.flags & 1920 /* Namespace */) && !((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return d.parent === node.parent; })); } : isRhsOfImportDeclaration ? // Any kind is allowed when dotting off namespace in internal import equals declaration function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : @@ -120665,7 +124654,7 @@ var ts; // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). if (!isTypeLocation && symbol.declarations && - symbol.declarations.some(function (d) { return d.kind !== 297 /* SourceFile */ && d.kind !== 256 /* ModuleDeclaration */ && d.kind !== 255 /* EnumDeclaration */; })) { + symbol.declarations.some(function (d) { return d.kind !== 298 /* SourceFile */ && d.kind !== 257 /* ModuleDeclaration */ && d.kind !== 256 /* EnumDeclaration */; })) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { @@ -120712,7 +124701,7 @@ var ts; if (isRightOfQuestionDot && ts.some(type.getCallSignatures())) { isNewIdentifierLocation = true; } - var propertyAccess = node.kind === 195 /* ImportType */ ? node : node.parent; + var propertyAccess = node.kind === 196 /* ImportType */ ? node : node.parent; if (isUncheckedFile) { // In javascript files, for union types, we don't just get the members that // the individual types have in common, we also include all the members that @@ -120751,13 +124740,24 @@ var ts; var nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName); // If this is nested like for `namespace N { export const sym = Symbol(); }`, we'll add the completion for `N`. var firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker); - if (firstAccessibleSymbol && !symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)]) { + if (firstAccessibleSymbol && ts.addToSeen(seenPropertySymbols, ts.getSymbolId(firstAccessibleSymbol))) { + var index = symbols.length; symbols.push(firstAccessibleSymbol); var moduleSymbol = firstAccessibleSymbol.parent; - symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] = - !moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol) - ? { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) } - : { kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), moduleSymbol: moduleSymbol, isDefaultExport: false }; + if (!moduleSymbol || !ts.isExternalModuleSymbol(moduleSymbol)) { + symbolToOriginInfoMap[index] = { kind: getNullableSymbolOriginInfoKind(2 /* SymbolMemberNoExport */) }; + } + else { + var origin = { + kind: getNullableSymbolOriginInfoKind(6 /* SymbolMemberExport */), + moduleSymbol: moduleSymbol, + isDefaultExport: false, + symbolName: firstAccessibleSymbol.name, + exportName: firstAccessibleSymbol.name, + fileName: ts.isExternalModuleNameRelative(ts.stripQuotes(moduleSymbol.name)) ? ts.cast(moduleSymbol.valueDeclaration, ts.isSourceFile).fileName : undefined, + }; + symbolToOriginInfoMap[index] = origin; + } } else if (preferences.includeCompletionsWithInsertText) { addSymbolOriginInfo(symbol); @@ -120777,11 +124777,11 @@ var ts; } function addSymbolOriginInfo(symbol) { if (preferences.includeCompletionsWithInsertText) { - if (insertAwait && !symbolToOriginInfoMap[ts.getSymbolId(symbol)]) { - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: getNullableSymbolOriginInfoKind(8 /* Promise */) }; + if (insertAwait && ts.addToSeen(seenPropertySymbols, ts.getSymbolId(symbol))) { + symbolToOriginInfoMap[symbols.length] = { kind: getNullableSymbolOriginInfoKind(8 /* Promise */) }; } else if (insertQuestionDot) { - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 16 /* Nullable */ }; + symbolToOriginInfoMap[symbols.length] = { kind: 16 /* Nullable */ }; } } } @@ -120794,7 +124794,9 @@ var ts; return ts.isIdentifier(e) ? e : ts.isPropertyAccessExpression(e) ? getLeftMostName(e.expression) : undefined; } function tryGetGlobalSymbols() { - var result = tryGetObjectLikeCompletionSymbols() + var result = tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() + || tryGetObjectLikeCompletionSymbols() + || tryGetImportCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() || tryGetLocalNamedExportCompletionSymbols() || tryGetConstructorCompletion() @@ -120827,11 +124829,17 @@ var ts; isNewIdentifierLocation = false; return 1 /* Success */; } + function tryGetImportCompletionSymbols() { + if (!importCompletionNode) + return 0 /* Continue */; + collectAutoImports(/*resolveModuleSpecifiers*/ true); + return 1 /* Success */; + } function getGlobalCompletions() { keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; - isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); + isNewIdentifierLocation = isNewIdentifierDefinitionLocation(); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); } @@ -120868,50 +124876,36 @@ var ts; var symbolMeanings = (isTypeOnly ? 0 /* None */ : 111551 /* Value */) | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); ts.Debug.assertEachIsDefined(symbols, "getSymbolsInScope() should all be defined"); - for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { - var symbol = symbols_2[_i]; + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; if (!typeChecker.isArgumentsSymbol(symbol) && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === sourceFile; })) { symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.GlobalsOrKeywords; } } // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` - if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 297 /* SourceFile */) { + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 298 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { for (var _a = 0, _b = getPropertiesForCompletion(thisType, typeChecker); _a < _b.length; _a++) { var symbol = _b[_a]; - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 1 /* ThisType */ }; + symbolToOriginInfoMap[symbols.length] = { kind: 1 /* ThisType */ }; symbols.push(symbol); symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.SuggestedClassMembers; } } } - if (shouldOfferImportCompletions()) { - var lowerCaseTokenText_1 = previousToken && ts.isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; - var autoImportSuggestions = getSymbolsFromOtherSourceFileExports(program.getCompilerOptions().target, host); - if (!detailsEntryId && importSuggestionsCache) { - importSuggestionsCache.set(sourceFile.fileName, autoImportSuggestions, host.getProjectVersion && host.getProjectVersion()); - } - autoImportSuggestions.forEach(function (_a) { - var symbol = _a.symbol, symbolName = _a.symbolName, skipFilter = _a.skipFilter, origin = _a.origin; - if (detailsEntryId) { - if (detailsEntryId.source && ts.stripQuotes(origin.moduleSymbol.name) !== detailsEntryId.source) { - return; - } - } - else if (!skipFilter && !stringContainsCharactersInOrder(symbolName.toLowerCase(), lowerCaseTokenText_1)) { - return; - } - var symbolId = ts.getSymbolId(symbol); - symbols.push(symbol); - symbolToOriginInfoMap[symbolId] = origin; - symbolToSortTextMap[symbolId] = SortText.AutoImportSuggestions; - }); + collectAutoImports(/*resolveModuleSpecifier*/ false); + if (isTypeOnly) { + keywordFilters = contextToken && ts.isAssertionExpression(contextToken.parent) + ? 6 /* TypeAssertionKeywords */ + : 7 /* TypeKeywords */; } - filterGlobalCompletion(symbols); } function shouldOfferImportCompletions() { + // If already typing an import statement, provide completions for it. + if (importCompletionNode) + return true; // If current completion is for non-contextual Object literal shortahands, ignore auto-import symbols if (isNonContextualObjectLiteral) return false; @@ -120929,42 +124923,15 @@ var ts; } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { - case 297 /* SourceFile */: - case 218 /* TemplateExpression */: - case 283 /* JsxExpression */: - case 230 /* Block */: + case 298 /* SourceFile */: + case 219 /* TemplateExpression */: + case 284 /* JsxExpression */: + case 231 /* Block */: return true; default: return ts.isStatement(scopeNode); } } - function filterGlobalCompletion(symbols) { - var isTypeOnly = isTypeOnlyCompletion(); - if (isTypeOnly) { - keywordFilters = contextToken && ts.isAssertionExpression(contextToken.parent) - ? 6 /* TypeAssertionKeywords */ - : 7 /* TypeKeywords */; - } - ts.filterMutate(symbols, function (symbol) { - if (!ts.isSourceFile(location)) { - // export = /**/ here we want to get all meanings, so any symbol is ok - if (ts.isExportAssignment(location.parent)) { - return true; - } - symbol = ts.skipAlias(symbol, typeChecker); - // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) - if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { - return !!(symbol.flags & 1920 /* Namespace */); - } - if (isTypeOnly) { - // It's a type, but you can reach it by namespace.type as well - return symbolCanBeReferencedAtTypeLocation(symbol); - } - } - // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 111551 /* Value */); - }); - } function isTypeOnlyCompletion() { return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && @@ -120974,191 +124941,105 @@ var ts; } function isContextTokenValueLocation(contextToken) { return contextToken && - contextToken.kind === 111 /* TypeOfKeyword */ && - (contextToken.parent.kind === 176 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent)); + ((contextToken.kind === 111 /* TypeOfKeyword */ && + (contextToken.parent.kind === 177 /* TypeQuery */ || ts.isTypeOfExpression(contextToken.parent))) || + (contextToken.kind === 127 /* AssertsKeyword */ && contextToken.parent.kind === 173 /* TypePredicate */)); } function isContextTokenTypeLocation(contextToken) { if (contextToken) { var parentKind = contextToken.parent.kind; switch (contextToken.kind) { case 58 /* ColonToken */: - return parentKind === 163 /* PropertyDeclaration */ || - parentKind === 162 /* PropertySignature */ || - parentKind === 160 /* Parameter */ || - parentKind === 249 /* VariableDeclaration */ || + return parentKind === 164 /* PropertyDeclaration */ || + parentKind === 163 /* PropertySignature */ || + parentKind === 161 /* Parameter */ || + parentKind === 250 /* VariableDeclaration */ || ts.isFunctionLikeKind(parentKind); case 62 /* EqualsToken */: - return parentKind === 254 /* TypeAliasDeclaration */; + return parentKind === 255 /* TypeAliasDeclaration */; case 126 /* AsKeyword */: - return parentKind === 224 /* AsExpression */; + return parentKind === 225 /* AsExpression */; case 29 /* LessThanToken */: - return parentKind === 173 /* TypeReference */ || - parentKind === 206 /* TypeAssertionExpression */; + return parentKind === 174 /* TypeReference */ || + parentKind === 207 /* TypeAssertionExpression */; case 93 /* ExtendsKeyword */: - return parentKind === 159 /* TypeParameter */; + return parentKind === 160 /* TypeParameter */; } } return false; } - /** True if symbol is a type or a module containing at least one type. */ - function symbolCanBeReferencedAtTypeLocation(symbol, seenModules) { - if (seenModules === void 0) { seenModules = new ts.Map(); } - var sym = ts.skipAlias(symbol.exportSymbol || symbol, typeChecker); - return !!(sym.flags & 788968 /* Type */) || - !!(sym.flags & 1536 /* Module */) && - ts.addToSeen(seenModules, ts.getSymbolId(sym)) && - typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); - } - /** - * Gathers symbols that can be imported from other files, de-duplicating along the way. Symbols can be "duplicates" - * if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but - * it’s just an alias to the first, and both have the same name, so we generally want to filter those aliases out, - * if and only if the the first can be imported (it may be excluded due to package.json filtering in - * `codefix.forEachExternalModuleToImportFrom`). - * - * Example. Imagine a chain of node_modules re-exporting one original symbol: - * - * ```js - * node_modules/x/index.js node_modules/y/index.js node_modules/z/index.js - * +-----------------------+ +--------------------------+ +--------------------------+ - * | | | | | | - * | export const foo = 0; | <--- | export { foo } from 'x'; | <--- | export { foo } from 'y'; | - * | | | | | | - * +-----------------------+ +--------------------------+ +--------------------------+ - * ``` - * - * Also imagine three buckets, which we’ll reference soon: - * - * ```md - * | | | | | | - * | **Bucket A** | | **Bucket B** | | **Bucket C** | - * | Symbols to | | Aliases to symbols | | Symbols to return | - * | definitely | | in Buckets A or C | | if nothing better | - * | return | | (don’t return these) | | comes along | - * |__________________| |______________________| |___________________| - * ``` - * - * We _probably_ want to show `foo` from 'x', but not from 'y' or 'z'. However, if 'x' is not in a package.json, it - * will not appear in a `forEachExternalModuleToImportFrom` iteration. Furthermore, the order of iterations is not - * guaranteed, as it is host-dependent. Therefore, when presented with the symbol `foo` from module 'y' alone, we - * may not be sure whether or not it should go in the list. So, we’ll take the following steps: - * - * 1. Resolve alias `foo` from 'y' to the export declaration in 'x', get the symbol there, and see if that symbol is - * already in Bucket A (symbols we already know will be returned). If it is, put `foo` from 'y' in Bucket B - * (symbols that are aliases to symbols in Bucket A). If it’s not, put it in Bucket C. - * 2. Next, imagine we see `foo` from module 'z'. Again, we resolve the alias to the nearest export, which is in 'y'. - * At this point, if that nearest export from 'y' is in _any_ of the three buckets, we know the symbol in 'z' - * should never be returned in the final list, so put it in Bucket B. - * 3. Next, imagine we see `foo` from module 'x', the original. Syntactically, it doesn’t look like a re-export, so - * we can just check Bucket C to see if we put any aliases to the original in there. If they exist, throw them out. - * Put this symbol in Bucket A. - * 4. After we’ve iterated through every symbol of every module, any symbol left in Bucket C means that step 3 didn’t - * occur for that symbol---that is, the original symbol is not in Bucket A, so we should include the alias. Move - * everything from Bucket C to Bucket A. - */ - function getSymbolsFromOtherSourceFileExports(target, host) { - var cached = importSuggestionsCache && importSuggestionsCache.get(sourceFile.fileName, typeChecker, detailsEntryId && host.getProjectVersion ? host.getProjectVersion() : undefined); - if (cached) { - log("getSymbolsFromOtherSourceFileExports: Using cached list"); - return cached; - } - var startTime = ts.timestamp(); - log("getSymbolsFromOtherSourceFileExports: Recomputing list" + (detailsEntryId ? " for details entry" : "")); - var seenResolvedModules = new ts.Map(); - var seenExports = new ts.Map(); - /** Bucket B */ - var aliasesToAlreadyIncludedSymbols = new ts.Map(); - /** Bucket C */ - var aliasesToReturnIfOriginalsAreMissing = new ts.Map(); - /** Bucket A */ - var results = []; - /** Ids present in `results` for faster lookup */ - var resultSymbolIds = new ts.Map(); - ts.codefix.forEachExternalModuleToImportFrom(program, host, sourceFile, !detailsEntryId, /*useAutoImportProvider*/ true, function (moduleSymbol, _, program, isFromPackageJson) { - // Perf -- ignore other modules if this is a request for details - if (detailsEntryId && detailsEntryId.source && ts.stripQuotes(moduleSymbol.name) !== detailsEntryId.source) { - return; - } - var typeChecker = program.getTypeChecker(); - var resolvedModuleSymbol = typeChecker.resolveExternalModuleSymbol(moduleSymbol); - // resolvedModuleSymbol may be a namespace. A namespace may be `export =` by multiple module declarations, but only keep the first one. - if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { + /** Mutates `symbols`, `symbolToOriginInfoMap`, and `symbolToSortTextMap` */ + function collectAutoImports(resolveModuleSpecifiers) { + var _a, _b, _c, _d, _e; + if (!shouldOfferImportCompletions()) + return; + ts.Debug.assert(!(detailsEntryId === null || detailsEntryId === void 0 ? void 0 : detailsEntryId.data)); + var start = ts.timestamp(); + var moduleSpecifierCache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); + (_b = host.log) === null || _b === void 0 ? void 0 : _b.call(host, "collectAutoImports: starting, " + (resolveModuleSpecifiers ? "" : "not ") + "resolving module specifiers"); + if (moduleSpecifierCache) { + (_c = host.log) === null || _c === void 0 ? void 0 : _c.call(host, "collectAutoImports: module specifier cache size: " + moduleSpecifierCache.count()); + } + var lowerCaseTokenText = previousToken && ts.isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; + var exportInfo = ts.codefix.getSymbolToExportInfoMap(sourceFile, host, program); + var packageJsonAutoImportProvider = (_d = host.getPackageJsonAutoImportProvider) === null || _d === void 0 ? void 0 : _d.call(host); + var packageJsonFilter = detailsEntryId ? undefined : ts.createPackageJsonImportFilter(sourceFile, host); + exportInfo.forEach(function (info, key) { + var symbolName = key.substring(0, key.indexOf("|")); + if (!detailsEntryId && ts.isStringANonContextualKeyword(symbolName)) return; + var isCompletionDetailsMatch = detailsEntryId && ts.some(info, function (i) { return detailsEntryId.source === ts.stripQuotes(i.moduleSymbol.name); }); + if (isCompletionDetailsMatch || isNameMatch(symbolName)) { + // If we don't need to resolve module specifiers, we can use any re-export that is importable at all + // (We need to ensure that at least one is importable to show a completion.) + var _a = resolveModuleSpecifiers + ? ts.codefix.getModuleSpecifierForBestExportInfo(info, sourceFile, program, host, preferences) + : { moduleSpecifier: undefined, exportInfo: ts.find(info, isImportableExportInfo) }, moduleSpecifier = _a.moduleSpecifier, exportInfo_1 = _a.exportInfo; + if (!exportInfo_1) + return; + var moduleFile = ts.tryCast(exportInfo_1.moduleSymbol.valueDeclaration, ts.isSourceFile); + var isDefaultExport = exportInfo_1.exportKind === 1 /* Default */; + var symbol = isDefaultExport && ts.getLocalSymbolForExportDefault(exportInfo_1.symbol) || exportInfo_1.symbol; + pushAutoImportSymbol(symbol, { + kind: resolveModuleSpecifiers ? 32 /* ResolvedExport */ : 4 /* Export */, + moduleSpecifier: moduleSpecifier, + symbolName: symbolName, + exportName: exportInfo_1.exportKind === 2 /* ExportEquals */ ? "export=" /* ExportEquals */ : exportInfo_1.symbol.name, + fileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, + isDefaultExport: isDefaultExport, + moduleSymbol: exportInfo_1.moduleSymbol, + isFromPackageJson: exportInfo_1.isFromPackageJson, + }); } - // Don't add another completion for `export =` of a symbol that's already global. - // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. - if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, ts.isNonGlobalDeclaration)) { - pushSymbol(resolvedModuleSymbol, moduleSymbol, isFromPackageJson, /*skipFilter*/ true); - } - for (var _i = 0, _a = typeChecker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { - var symbol = _a[_i]; - var symbolId = ts.getSymbolId(symbol).toString(); - // `getExportsAndPropertiesOfModule` can include duplicates - if (!ts.addToSeen(seenExports, symbolId)) { - continue; - } - // If this is `export { _break as break };` (a keyword) -- skip this and prefer the keyword completion. - if (ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.propertyName && ts.isIdentifierANonContextualKeyword(d.name); })) { - continue; - } - // If `symbol.parent !== moduleSymbol`, this is an `export * from "foo"` re-export. Those don't create new symbols. - var isExportStarFromReExport = typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol; - // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). - if (isExportStarFromReExport || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !d.propertyName && !!d.parent.parent.moduleSpecifier; })) { - // Walk the export chain back one module (step 1 or 2 in diagrammed example). - // Or, in the case of `export * from "foo"`, `symbol` already points to the original export, so just use that. - var nearestExportSymbol = isExportStarFromReExport ? symbol : getNearestExportSymbol(symbol); - if (!nearestExportSymbol) - continue; - var nearestExportSymbolId = ts.getSymbolId(nearestExportSymbol).toString(); - var symbolHasBeenSeen = resultSymbolIds.has(nearestExportSymbolId) || aliasesToAlreadyIncludedSymbols.has(nearestExportSymbolId); - if (!symbolHasBeenSeen) { - aliasesToReturnIfOriginalsAreMissing.set(nearestExportSymbolId, { alias: symbol, moduleSymbol: moduleSymbol, isFromPackageJson: isFromPackageJson }); - aliasesToAlreadyIncludedSymbols.set(symbolId, true); - } - else { - // Perf - we know this symbol is an alias to one that’s already covered in `symbols`, so store it here - // in case another symbol re-exports this one; that way we can short-circuit as soon as we see this symbol id. - ts.addToSeen(aliasesToAlreadyIncludedSymbols, symbolId); - } - } - else { - // This is not a re-export, so see if we have any aliases pending and remove them (step 3 in diagrammed example) - aliasesToReturnIfOriginalsAreMissing.delete(symbolId); - pushSymbol(symbol, moduleSymbol, isFromPackageJson, /*skipFilter*/ false); - } - } - }); - // By this point, any potential duplicates that were actually duplicates have been - // removed, so the rest need to be added. (Step 4 in diagrammed example) - aliasesToReturnIfOriginalsAreMissing.forEach(function (_a) { - var alias = _a.alias, moduleSymbol = _a.moduleSymbol, isFromPackageJson = _a.isFromPackageJson; - return pushSymbol(alias, moduleSymbol, isFromPackageJson, /*skipFilter*/ false); }); - log("getSymbolsFromOtherSourceFileExports: " + (ts.timestamp() - startTime)); - return results; - function pushSymbol(symbol, moduleSymbol, isFromPackageJson, skipFilter) { - var isDefaultExport = symbol.escapedName === "default" /* Default */; - if (isDefaultExport) { - symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; + (_e = host.log) === null || _e === void 0 ? void 0 : _e.call(host, "collectAutoImports: done in " + (ts.timestamp() - start) + " ms"); + function isNameMatch(symbolName) { + var lowerCaseSymbolName = symbolName.toLowerCase(); + if (resolveModuleSpecifiers && lowerCaseTokenText) { + // Use a more restrictive filter if resolving module specifiers since resolving module specifiers is expensive. + return lowerCaseTokenText[0] === lowerCaseSymbolName[0] && stringContainsCharactersInOrder(lowerCaseSymbolName, lowerCaseTokenText); } - if (typeChecker.isUndefinedSymbol(symbol)) { - return; + return stringContainsCharactersInOrder(lowerCaseSymbolName, lowerCaseTokenText); + } + function isImportableExportInfo(info) { + var moduleFile = ts.tryCast(info.moduleSymbol.valueDeclaration, ts.isSourceFile); + if (!moduleFile) { + return packageJsonFilter + ? packageJsonFilter.allowsImportingAmbientModule(info.moduleSymbol, getModuleSpecifierResolutionHost(info.isFromPackageJson)) + : true; } - ts.addToSeen(resultSymbolIds, ts.getSymbolId(symbol)); - var origin = { kind: 4 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport, isFromPackageJson: isFromPackageJson }; - results.push({ - symbol: symbol, - symbolName: ts.getNameForExportedSymbol(symbol, target), - origin: origin, - skipFilter: skipFilter, - }); + return ts.isImportableFile(info.isFromPackageJson ? packageJsonAutoImportProvider : program, sourceFile, moduleFile, packageJsonFilter, getModuleSpecifierResolutionHost(info.isFromPackageJson), moduleSpecifierCache); } } - function getNearestExportSymbol(fromSymbol) { - return findAlias(typeChecker, fromSymbol, function (alias) { - return ts.some(alias.declarations, function (d) { return ts.isExportSpecifier(d) || !!d.localSymbol; }); - }); + function pushAutoImportSymbol(symbol, origin) { + var symbolId = ts.getSymbolId(symbol); + if (symbolToSortTextMap[symbolId] === SortText.GlobalsOrKeywords) { + // If an auto-importable symbol is available as a global, don't add the auto import + return; + } + symbolToOriginInfoMap[symbols.length] = origin; + symbolToSortTextMap[symbolId] = importCompletionNode ? SortText.LocationPriority : SortText.AutoImportSuggestions; + symbols.push(symbol); } /** * True if you could remove some characters in `a` to get `b`. @@ -121170,7 +125051,8 @@ var ts; return true; } var characterIndex = 0; - for (var strIndex = 0; strIndex < str.length; strIndex++) { + var len = str.length; + for (var strIndex = 0; strIndex < len; strIndex++) { if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) { characterIndex++; if (characterIndex === characters.length) { @@ -121206,7 +125088,7 @@ var ts; return true; } if (contextToken.kind === 31 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 275 /* JsxOpeningElement */) { + if (contextToken.parent.kind === 276 /* JsxOpeningElement */) { // Two possibilities: // 1.
/**/ // - contextToken: GreaterThanToken (before cursor) @@ -121216,54 +125098,56 @@ var ts; // - contextToken: GreaterThanToken (before cursor) // - location: GreaterThanToken (after cursor) // - same parent (JSXOpeningElement) - return location.parent.kind !== 275 /* JsxOpeningElement */; + return location.parent.kind !== 276 /* JsxOpeningElement */; } - if (contextToken.parent.kind === 276 /* JsxClosingElement */ || contextToken.parent.kind === 274 /* JsxSelfClosingElement */) { - return !!contextToken.parent.parent && contextToken.parent.parent.kind === 273 /* JsxElement */; + if (contextToken.parent.kind === 277 /* JsxClosingElement */ || contextToken.parent.kind === 275 /* JsxSelfClosingElement */) { + return !!contextToken.parent.parent && contextToken.parent.parent.kind === 274 /* JsxElement */; } } return false; } - function isNewIdentifierDefinitionLocation(previousToken) { - if (previousToken) { - var containingNodeKind = previousToken.parent.kind; + function isNewIdentifierDefinitionLocation() { + if (contextToken) { + var containingNodeKind = contextToken.parent.kind; // Previous token may have been a keyword that was converted to an identifier. - switch (keywordForNode(previousToken)) { + switch (keywordForNode(contextToken)) { case 27 /* CommaToken */: - return containingNodeKind === 203 /* CallExpression */ // func( a, | - || containingNodeKind === 166 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ - || containingNodeKind === 204 /* NewExpression */ // new C(a, | - || containingNodeKind === 199 /* ArrayLiteralExpression */ // [a, | - || containingNodeKind === 216 /* BinaryExpression */ // const x = (a, | - || containingNodeKind === 174 /* FunctionType */; // var x: (s: string, list| + return containingNodeKind === 204 /* CallExpression */ // func( a, | + || containingNodeKind === 167 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 205 /* NewExpression */ // new C(a, | + || containingNodeKind === 200 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 217 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 175 /* FunctionType */ // var x: (s: string, list| + || containingNodeKind === 201 /* ObjectLiteralExpression */; // const obj = { x, | case 20 /* OpenParenToken */: - return containingNodeKind === 203 /* CallExpression */ // func( | - || containingNodeKind === 166 /* Constructor */ // constructor( | - || containingNodeKind === 204 /* NewExpression */ // new C(a| - || containingNodeKind === 207 /* ParenthesizedExpression */ // const x = (a| - || containingNodeKind === 186 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + return containingNodeKind === 204 /* CallExpression */ // func( | + || containingNodeKind === 167 /* Constructor */ // constructor( | + || containingNodeKind === 205 /* NewExpression */ // new C(a| + || containingNodeKind === 208 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 187 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ case 22 /* OpenBracketToken */: - return containingNodeKind === 199 /* ArrayLiteralExpression */ // [ | - || containingNodeKind === 171 /* IndexSignature */ // [ | : string ] - || containingNodeKind === 158 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + return containingNodeKind === 200 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 172 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 159 /* ComputedPropertyName */; // [ | /* this can become an index signature */ case 139 /* ModuleKeyword */: // module | case 140 /* NamespaceKeyword */: // namespace | return true; case 24 /* DotToken */: - return containingNodeKind === 256 /* ModuleDeclaration */; // module A.| + return containingNodeKind === 257 /* ModuleDeclaration */; // module A.| case 18 /* OpenBraceToken */: - return containingNodeKind === 252 /* ClassDeclaration */; // class A{ | + return containingNodeKind === 253 /* ClassDeclaration */ // class A { | + || containingNodeKind === 201 /* ObjectLiteralExpression */; // const obj = { | case 62 /* EqualsToken */: - return containingNodeKind === 249 /* VariableDeclaration */ // const x = a| - || containingNodeKind === 216 /* BinaryExpression */; // x = a| + return containingNodeKind === 250 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 217 /* BinaryExpression */; // x = a| case 15 /* TemplateHead */: - return containingNodeKind === 218 /* TemplateExpression */; // `aa ${| + return containingNodeKind === 219 /* TemplateExpression */; // `aa ${| case 16 /* TemplateMiddle */: - return containingNodeKind === 228 /* TemplateSpan */; // `aa ${10} dd ${| + return containingNodeKind === 229 /* TemplateSpan */; // `aa ${10} dd ${| case 122 /* PublicKeyword */: case 120 /* PrivateKeyword */: case 121 /* ProtectedKeyword */: - return containingNodeKind === 163 /* PropertyDeclaration */; // class A{ public | + return containingNodeKind === 164 /* PropertyDeclaration */; // class A{ public | } } return false; @@ -121276,6 +125160,25 @@ var ts; return (ts.isRegularExpressionLiteral(contextToken) || ts.isStringTextContainingNode(contextToken)) && (ts.rangeContainsPositionExclusive(ts.createTextRangeFromSpan(ts.createTextSpanFromNode(contextToken)), position) || position === contextToken.end && (!!contextToken.isUnterminated || ts.isRegularExpressionLiteral(contextToken))); } + function tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() { + var typeLiteralNode = tryGetTypeLiteralNode(contextToken); + if (!typeLiteralNode) + return 0 /* Continue */; + var intersectionTypeNode = ts.isIntersectionTypeNode(typeLiteralNode.parent) ? typeLiteralNode.parent : undefined; + var containerTypeNode = intersectionTypeNode || typeLiteralNode; + var containerExpectedType = getConstraintOfTypeArgumentProperty(containerTypeNode, typeChecker); + if (!containerExpectedType) + return 0 /* Continue */; + var containerActualType = typeChecker.getTypeFromTypeNode(containerTypeNode); + var members = getPropertiesForCompletion(containerExpectedType, typeChecker); + var existingMembers = getPropertiesForCompletion(containerActualType, typeChecker); + var existingMemberEscapedNames = new ts.Set(); + existingMembers.forEach(function (s) { return existingMemberEscapedNames.add(s.escapedName); }); + symbols = ts.filter(members, function (s) { return !existingMemberEscapedNames.has(s.escapedName); }); + completionKind = 0 /* ObjectPropertyDeclaration */; + isNewIdentifierLocation = true; + return 1 /* Success */; + } /** * Aggregates relevant symbols for completion in object literals and object binding patterns. * Relevant symbols are stored in the captured 'symbols' variable. @@ -121290,7 +125193,7 @@ var ts; completionKind = 0 /* ObjectPropertyDeclaration */; var typeMembers; var existingMembers; - if (objectLikeContainer.kind === 200 /* ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 201 /* ObjectLiteralExpression */) { var instantiatedType = tryGetObjectLiteralContextualType(objectLikeContainer, typeChecker); // Check completions for Object property value shorthand if (instantiatedType === undefined) { @@ -121315,7 +125218,7 @@ var ts; } } else { - ts.Debug.assert(objectLikeContainer.kind === 196 /* ObjectBindingPattern */); + ts.Debug.assert(objectLikeContainer.kind === 197 /* ObjectBindingPattern */); // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -121326,12 +125229,12 @@ var ts; // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function - var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 239 /* ForOfStatement */; - if (!canGetType && rootDeclaration.kind === 160 /* Parameter */) { + var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 240 /* ForOfStatement */; + if (!canGetType && rootDeclaration.kind === 161 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - else if (rootDeclaration.parent.kind === 165 /* MethodDeclaration */ || rootDeclaration.parent.kind === 168 /* SetAccessor */) { + else if (rootDeclaration.parent.kind === 166 /* MethodDeclaration */ || rootDeclaration.parent.kind === 169 /* SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } @@ -121378,9 +125281,9 @@ var ts; if (!namedImportsOrExports) return 0 /* Continue */; // try to show exported member for imported/re-exported module - var moduleSpecifier = (namedImportsOrExports.kind === 264 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + var moduleSpecifier = (namedImportsOrExports.kind === 265 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; if (!moduleSpecifier) - return namedImportsOrExports.kind === 264 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */; + return namedImportsOrExports.kind === 265 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 if (!moduleSpecifierSymbol) return 2 /* Fail */; @@ -121448,12 +125351,16 @@ var ts; case "static": classElementModifierFlags = classElementModifierFlags | 32 /* Static */; break; + case "override": + classElementModifierFlags = classElementModifierFlags | 16384 /* Override */; + break; } } // No member list for private methods if (!(classElementModifierFlags & 8 /* Private */)) { // List of property symbols of base type that are not private and already implemented - var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) { + var baseTypeNodes = ts.isClassLike(decl) && classElementModifierFlags & 16384 /* Override */ ? ts.singleElementArray(ts.getEffectiveBaseTypeNode(decl)) : ts.getAllSuperTypeNodes(decl); + var baseSymbols = ts.flatMap(baseTypeNodes, function (baseTypeNode) { var type = typeChecker.getTypeAtLocation(baseTypeNode); return classElementModifierFlags & 32 /* Static */ ? (type === null || type === void 0 ? void 0 : type.symbol) && typeChecker.getPropertiesOfType(typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl)) : @@ -121533,11 +125440,11 @@ var ts; case 30 /* LessThanSlashToken */: case 43 /* SlashToken */: case 78 /* Identifier */: - case 201 /* PropertyAccessExpression */: - case 281 /* JsxAttributes */: - case 280 /* JsxAttribute */: - case 282 /* JsxSpreadAttribute */: - if (parent && (parent.kind === 274 /* JsxSelfClosingElement */ || parent.kind === 275 /* JsxOpeningElement */)) { + case 202 /* PropertyAccessExpression */: + case 282 /* JsxAttributes */: + case 281 /* JsxAttribute */: + case 283 /* JsxSpreadAttribute */: + if (parent && (parent.kind === 275 /* JsxSelfClosingElement */ || parent.kind === 276 /* JsxOpeningElement */)) { if (contextToken.kind === 31 /* GreaterThanToken */) { var precedingToken = ts.findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined); if (!parent.typeArguments || (precedingToken && precedingToken.kind === 43 /* SlashToken */)) @@ -121545,7 +125452,7 @@ var ts; } return parent; } - else if (parent.kind === 280 /* JsxAttribute */) { + else if (parent.kind === 281 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -121557,7 +125464,7 @@ var ts; // its parent is a JsxExpression, whose parent is a JsxAttribute, // whose parent is a JsxOpeningLikeElement case 10 /* StringLiteral */: - if (parent && ((parent.kind === 280 /* JsxAttribute */) || (parent.kind === 282 /* JsxSpreadAttribute */))) { + if (parent && ((parent.kind === 281 /* JsxAttribute */) || (parent.kind === 283 /* JsxSpreadAttribute */))) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -121567,8 +125474,8 @@ var ts; break; case 19 /* CloseBraceToken */: if (parent && - parent.kind === 283 /* JsxExpression */ && - parent.parent && parent.parent.kind === 280 /* JsxAttribute */) { + parent.kind === 284 /* JsxExpression */ && + parent.parent && parent.parent.kind === 281 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -121576,7 +125483,7 @@ var ts; // each JsxAttribute can have initializer as JsxExpression return parent.parent.parent.parent; } - if (parent && parent.kind === 282 /* JsxSpreadAttribute */) { + if (parent && parent.kind === 283 /* JsxSpreadAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -121596,49 +125503,49 @@ var ts; var containingNodeKind = parent.kind; switch (contextToken.kind) { case 27 /* CommaToken */: - return containingNodeKind === 249 /* VariableDeclaration */ || + return containingNodeKind === 250 /* VariableDeclaration */ || isVariableDeclarationListButNotTypeArgument(contextToken) || - containingNodeKind === 232 /* VariableStatement */ || - containingNodeKind === 255 /* EnumDeclaration */ || // enum a { foo, | + containingNodeKind === 233 /* VariableStatement */ || + containingNodeKind === 256 /* EnumDeclaration */ || // enum a { foo, | isFunctionLikeButNotConstructor(containingNodeKind) || - containingNodeKind === 253 /* InterfaceDeclaration */ || // interface A= contextToken.pos); case 24 /* DotToken */: - return containingNodeKind === 197 /* ArrayBindingPattern */; // var [.| + return containingNodeKind === 198 /* ArrayBindingPattern */; // var [.| case 58 /* ColonToken */: - return containingNodeKind === 198 /* BindingElement */; // var {x :html| + return containingNodeKind === 199 /* BindingElement */; // var {x :html| case 22 /* OpenBracketToken */: - return containingNodeKind === 197 /* ArrayBindingPattern */; // var [x| + return containingNodeKind === 198 /* ArrayBindingPattern */; // var [x| case 20 /* OpenParenToken */: - return containingNodeKind === 287 /* CatchClause */ || + return containingNodeKind === 288 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); case 18 /* OpenBraceToken */: - return containingNodeKind === 255 /* EnumDeclaration */; // enum a { | + return containingNodeKind === 256 /* EnumDeclaration */; // enum a { | case 29 /* LessThanToken */: - return containingNodeKind === 252 /* ClassDeclaration */ || // class A< | - containingNodeKind === 221 /* ClassExpression */ || // var C = class D< | - containingNodeKind === 253 /* InterfaceDeclaration */ || // interface A< | - containingNodeKind === 254 /* TypeAliasDeclaration */ || // type List< | + return containingNodeKind === 253 /* ClassDeclaration */ || // class A< | + containingNodeKind === 222 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 254 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 255 /* TypeAliasDeclaration */ || // type List< | ts.isFunctionLikeKind(containingNodeKind); case 123 /* StaticKeyword */: - return containingNodeKind === 163 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); + return containingNodeKind === 164 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); case 25 /* DotDotDotToken */: - return containingNodeKind === 160 /* Parameter */ || - (!!parent.parent && parent.parent.kind === 197 /* ArrayBindingPattern */); // var [...z| + return containingNodeKind === 161 /* Parameter */ || + (!!parent.parent && parent.parent.kind === 198 /* ArrayBindingPattern */); // var [...z| case 122 /* PublicKeyword */: case 120 /* PrivateKeyword */: case 121 /* ProtectedKeyword */: - return containingNodeKind === 160 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); + return containingNodeKind === 161 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); case 126 /* AsKeyword */: - return containingNodeKind === 265 /* ImportSpecifier */ || - containingNodeKind === 270 /* ExportSpecifier */ || - containingNodeKind === 263 /* NamespaceImport */; + return containingNodeKind === 266 /* ImportSpecifier */ || + containingNodeKind === 271 /* ExportSpecifier */ || + containingNodeKind === 264 /* NamespaceImport */; case 134 /* GetKeyword */: case 146 /* SetKeyword */: return !isFromObjectTypeDeclaration(contextToken); @@ -121656,7 +125563,7 @@ var ts; case 41 /* AsteriskToken */: return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } - // If the previous token is keyword correspoding to class member completion keyword + // If the previous token is keyword corresponding to class member completion keyword // there will be completion available here if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { return false; @@ -121691,6 +125598,31 @@ var ts; case 129 /* AsyncKeyword */: return ts.isPropertyDeclaration(contextToken.parent); } + // If we are inside a class declaration, and `constructor` is totally not present, + // but we request a completion manually at a whitespace... + var ancestorClassLike = ts.findAncestor(contextToken.parent, ts.isClassLike); + if (ancestorClassLike && contextToken === previousToken && isPreviousPropertyDeclarationTerminated(contextToken, position)) { + return false; // Don't block completions. + } + var ancestorPropertyDeclaraion = ts.getAncestor(contextToken.parent, 164 /* PropertyDeclaration */); + // If we are inside a class declaration and typing `constructor` after property declaration... + if (ancestorPropertyDeclaraion + && contextToken !== previousToken + && ts.isClassLike(previousToken.parent.parent) + // And the cursor is at the token... + && position <= previousToken.end) { + // If we are sure that the previous property declaration is terminated according to newline or semicolon... + if (isPreviousPropertyDeclarationTerminated(contextToken, previousToken.end)) { + return false; // Don't block completions. + } + else if (contextToken.kind !== 62 /* EqualsToken */ + // Should not block: `class C { blah = c/**/ }` + // But should block: `class C { blah = somewhat c/**/ }` and `class C { blah: SomeType c/**/ }` + && (ts.isInitializedProperty(ancestorPropertyDeclaraion) + || ts.hasType(ancestorPropertyDeclaraion))) { + return true; + } + } return ts.isDeclarationName(contextToken) && !ts.isShorthandPropertyAssignment(contextToken.parent) && !ts.isJsxAttribute(contextToken.parent) @@ -121698,8 +125630,13 @@ var ts; // If `contextToken !== previousToken`, this is `class C ex/**/`. && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } + function isPreviousPropertyDeclarationTerminated(contextToken, position) { + return contextToken.kind !== 62 /* EqualsToken */ && + (contextToken.kind === 26 /* SemicolonToken */ + || !ts.positionsAreOnSameLine(contextToken.end, position, sourceFile)); + } function isFunctionLikeButNotConstructor(kind) { - return ts.isFunctionLikeKind(kind) && kind !== 166 /* Constructor */; + return ts.isFunctionLikeKind(kind) && kind !== 167 /* Constructor */; } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8 /* NumericLiteral */) { @@ -121709,7 +125646,7 @@ var ts; return false; } function isVariableDeclarationListButNotTypeArgument(node) { - return node.parent.kind === 250 /* VariableDeclarationList */ + return node.parent.kind === 251 /* VariableDeclarationList */ && !ts.isPossiblyTypeArgumentPosition(node, sourceFile, typeChecker); } /** @@ -121727,13 +125664,13 @@ var ts; for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 288 /* PropertyAssignment */ && - m.kind !== 289 /* ShorthandPropertyAssignment */ && - m.kind !== 198 /* BindingElement */ && - m.kind !== 165 /* MethodDeclaration */ && - m.kind !== 167 /* GetAccessor */ && - m.kind !== 168 /* SetAccessor */ && - m.kind !== 290 /* SpreadAssignment */) { + if (m.kind !== 289 /* PropertyAssignment */ && + m.kind !== 290 /* ShorthandPropertyAssignment */ && + m.kind !== 199 /* BindingElement */ && + m.kind !== 166 /* MethodDeclaration */ && + m.kind !== 168 /* GetAccessor */ && + m.kind !== 169 /* SetAccessor */ && + m.kind !== 291 /* SpreadAssignment */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -121806,10 +125743,10 @@ var ts; for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 163 /* PropertyDeclaration */ && - m.kind !== 165 /* MethodDeclaration */ && - m.kind !== 167 /* GetAccessor */ && - m.kind !== 168 /* SetAccessor */) { + if (m.kind !== 164 /* PropertyDeclaration */ && + m.kind !== 166 /* MethodDeclaration */ && + m.kind !== 168 /* GetAccessor */ && + m.kind !== 169 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -121833,7 +125770,7 @@ var ts; return !existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */) && - !(propertySymbol.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(propertySymbol.valueDeclaration)); + !(propertySymbol.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(propertySymbol.valueDeclaration)); }); } /** @@ -121851,7 +125788,7 @@ var ts; if (isCurrentlyEditingNode(attr)) { continue; } - if (attr.kind === 280 /* JsxAttribute */) { + if (attr.kind === 281 /* JsxAttribute */) { seenNames.add(attr.name.escapedText); } else if (ts.isJsxSpreadAttribute(attr)) { @@ -121866,8 +125803,35 @@ var ts; return node.getStart(sourceFile) <= position && position <= node.getEnd(); } } + function getAutoImportSymbolFromCompletionEntryData(name, data, program, host) { + var containingProgram = data.isPackageJsonImport ? host.getPackageJsonAutoImportProvider() : program; + var checker = containingProgram.getTypeChecker(); + var moduleSymbol = data.ambientModuleName ? checker.tryFindAmbientModule(data.ambientModuleName) : + data.fileName ? checker.getMergedSymbol(ts.Debug.checkDefined(containingProgram.getSourceFile(data.fileName)).symbol) : + undefined; + if (!moduleSymbol) + return undefined; + var symbol = data.exportName === "export=" /* ExportEquals */ + ? checker.resolveExternalModuleSymbol(moduleSymbol) + : checker.tryGetMemberInModuleExportsAndProperties(data.exportName, moduleSymbol); + if (!symbol) + return undefined; + var isDefaultExport = data.exportName === "default" /* Default */; + symbol = isDefaultExport && ts.getLocalSymbolForExportDefault(symbol) || symbol; + return { + symbol: symbol, + origin: { + kind: data.moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */, + moduleSymbol: moduleSymbol, + symbolName: name, + isDefaultExport: isDefaultExport, + exportName: data.exportName, + fileName: data.fileName, + } + }; + } function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, jsxIdentifierExpected) { - var name = originIsExport(origin) ? ts.getNameForExportedSymbol(symbol, target) : symbol.name; + var name = originIncludesSymbolName(origin) ? origin.symbolName : symbol.name; if (name === undefined // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) @@ -121877,7 +125841,7 @@ var ts; return undefined; } var validNameResult = { name: name, needsConvertPropertyAccess: false }; - if (ts.isIdentifierText(name, target, jsxIdentifierExpected ? 1 /* JSX */ : 0 /* Standard */) || symbol.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) { + if (ts.isIdentifierText(name, target, jsxIdentifierExpected ? 1 /* JSX */ : 0 /* Standard */) || symbol.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) { return validNameResult; } switch (kind) { @@ -121901,7 +125865,7 @@ var ts; var _keywordCompletions = []; var allKeywordsCompletions = ts.memoize(function () { var res = []; - for (var i = 80 /* FirstKeyword */; i <= 156 /* LastKeyword */; i++) { + for (var i = 80 /* FirstKeyword */; i <= 157 /* LastKeyword */; i++) { res.push({ name: ts.tokenToString(i), kind: "keyword" /* keyword */, @@ -121968,6 +125932,7 @@ var ts; case 141 /* NeverKeyword */: case 144 /* NumberKeyword */: case 145 /* ObjectKeyword */: + case 156 /* OverrideKeyword */: case 120 /* PrivateKeyword */: case 121 /* ProtectedKeyword */: case 122 /* PublicKeyword */: @@ -121993,6 +125958,7 @@ var ts; case 146 /* SetKeyword */: case 129 /* AsyncKeyword */: case 133 /* DeclareKeyword */: + case 156 /* OverrideKeyword */: return true; default: return ts.isClassMemberModifier(kind); @@ -122053,7 +126019,7 @@ var ts; function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position) { // class c { method() { } | method2() { } } switch (location.kind) { - case 334 /* SyntaxList */: + case 338 /* SyntaxList */: return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); case 1 /* EndOfFileToken */: var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); @@ -122074,6 +126040,12 @@ var ts; } if (!contextToken) return undefined; + // class C { blah; constructor/**/ } and so on + if (location.kind === 132 /* ConstructorKeyword */ + // class C { blah \n constructor/**/ } + || (ts.isIdentifier(contextToken) && ts.isPropertyDeclaration(contextToken.parent) && ts.isClassLike(location))) { + return ts.findAncestor(contextToken, ts.isClassLike); + } switch (contextToken.kind) { case 62 /* EqualsToken */: // class c { public prop = | /* global completions */ } return undefined; @@ -122099,6 +126071,44 @@ var ts; ? contextToken.parent.parent : undefined; } } + function tryGetTypeLiteralNode(node) { + if (!node) + return undefined; + var parent = node.parent; + switch (node.kind) { + case 18 /* OpenBraceToken */: + if (ts.isTypeLiteralNode(parent)) { + return parent; + } + break; + case 26 /* SemicolonToken */: + case 27 /* CommaToken */: + case 78 /* Identifier */: + if (parent.kind === 163 /* PropertySignature */ && ts.isTypeLiteralNode(parent.parent)) { + return parent.parent; + } + break; + } + return undefined; + } + function getConstraintOfTypeArgumentProperty(node, checker) { + if (!node) + return undefined; + if (ts.isTypeNode(node) && ts.isTypeReferenceType(node.parent)) { + return checker.getTypeArgumentConstraint(node); + } + var t = getConstraintOfTypeArgumentProperty(node.parent, checker); + if (!t) + return undefined; + switch (node.kind) { + case 163 /* PropertySignature */: + return checker.getTypeOfPropertyOfContextualType(t, node.symbol.escapedName); + case 184 /* IntersectionType */: + case 178 /* TypeLiteral */: + case 183 /* UnionType */: + return t; + } + } // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes function isFromObjectTypeDeclaration(node) { return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent); @@ -122122,6 +126132,8 @@ var ts; return !!contextToken && (ts.isStringLiteralLike(contextToken) ? !!ts.tryGetImportFromModuleSpecifier(contextToken) : contextToken.kind === 43 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); + case " ": + return !!contextToken && ts.isImportKeyword(contextToken) && contextToken.parent.kind === 298 /* SourceFile */; default: return ts.Debug.assertNever(triggerCharacter); } @@ -122130,14 +126142,6 @@ var ts; var left = _a.left; return ts.nodeIsMissing(left); } - function findAlias(typeChecker, symbol, predicate) { - var currentAlias = symbol; - while (currentAlias.flags & 2097152 /* Alias */ && (currentAlias = typeChecker.getImmediateAliasedSymbol(currentAlias))) { - if (predicate(currentAlias)) { - return currentAlias; - } - } - } /** Determines if a type is exactly the same type resolved by the global 'self', 'global', or 'globalThis'. */ function isProbablyGlobalType(type, sourceFile, checker) { // The type of `self` and `window` is the same in lib.dom.d.ts, but `window` does not exist in @@ -122164,11 +126168,67 @@ var ts; if (type) { return type; } - if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) { + if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ && node === node.parent.left) { + // Object literal is assignment pattern: ({ | } = x) return typeChecker.getTypeAtLocation(node.parent); } return undefined; } + function getImportCompletionNode(contextToken) { + var candidate = getCandidate(); + return candidate === 153 /* FromKeyword */ || candidate && ts.rangeIsOnSingleLine(candidate, candidate.getSourceFile()) ? candidate : undefined; + function getCandidate() { + var parent = contextToken.parent; + if (ts.isImportEqualsDeclaration(parent)) { + return isModuleSpecifierMissingOrEmpty(parent.moduleReference) ? parent : undefined; + } + if (ts.isNamedImports(parent) || ts.isNamespaceImport(parent)) { + if (isModuleSpecifierMissingOrEmpty(parent.parent.parent.moduleSpecifier) && (ts.isNamespaceImport(parent) || parent.elements.length < 2) && !parent.parent.name) { + // At `import { ... } |` or `import * as Foo |`, the only possible completion is `from` + return contextToken.kind === 19 /* CloseBraceToken */ || contextToken.kind === 78 /* Identifier */ + ? 153 /* FromKeyword */ + : parent.parent.parent; + } + return undefined; + } + if (ts.isImportKeyword(contextToken) && ts.isSourceFile(parent)) { + // A lone import keyword with nothing following it does not parse as a statement at all + return contextToken; + } + if (ts.isImportKeyword(contextToken) && ts.isImportDeclaration(parent)) { + // `import s| from` + return isModuleSpecifierMissingOrEmpty(parent.moduleSpecifier) ? parent : undefined; + } + return undefined; + } + } + function isModuleSpecifierMissingOrEmpty(specifier) { + var _a; + if (ts.nodeIsMissing(specifier)) + return true; + return !((_a = ts.tryCast(ts.isExternalModuleReference(specifier) ? specifier.expression : specifier, ts.isStringLiteralLike)) === null || _a === void 0 ? void 0 : _a.text); + } + function getVariableDeclaration(property) { + var variableDeclaration = ts.findAncestor(property, function (node) { + return ts.isFunctionBlock(node) || isArrowFunctionBody(node) || ts.isBindingPattern(node) + ? "quit" + : ts.isVariableDeclaration(node); + }); + return variableDeclaration; + } + function isArrowFunctionBody(node) { + return node.parent && ts.isArrowFunction(node.parent) && node.parent.body === node; + } + ; + /** True if symbol is a type or a module containing at least one type. */ + function symbolCanBeReferencedAtTypeLocation(symbol, checker, seenModules) { + if (seenModules === void 0) { seenModules = new ts.Map(); } + var sym = ts.skipAlias(symbol.exportSymbol || symbol, checker); + return !!(sym.flags & 788968 /* Type */) || + !!(sym.flags & 1536 /* Module */) && + ts.addToSeen(seenModules, ts.getSymbolId(sym)) && + checker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, checker, seenModules); }); + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); var ts; @@ -122203,10 +126263,12 @@ var ts; if (!referenceEntries) return undefined; var map = ts.arrayToMultiMap(referenceEntries.map(ts.FindAllReferences.toHighlightSpan), function (e) { return e.fileName; }, function (e) { return e.span; }); - return ts.arrayFrom(map.entries(), function (_a) { + return ts.mapDefined(ts.arrayFrom(map.entries()), function (_a) { var fileName = _a[0], highlightSpans = _a[1]; if (!sourceFilesSet.has(fileName)) { - ts.Debug.assert(program.redirectTargetsMap.has(fileName)); + if (!program.redirectTargetsMap.has(fileName)) { + return undefined; + } var redirectTarget_1 = program.getSourceFile(fileName); var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); fileName = redirect.fileName; @@ -122301,7 +126363,7 @@ var ts; var child = throwStatement; while (child.parent) { var parent = child.parent; - if (ts.isFunctionBlock(parent) || parent.kind === 297 /* SourceFile */) { + if (ts.isFunctionBlock(parent) || parent.kind === 298 /* SourceFile */) { return parent; } // A throw-statement is only owned by a try-statement if the try-statement has @@ -122333,16 +126395,16 @@ var ts; function getBreakOrContinueOwner(statement) { return ts.findAncestor(statement, function (node) { switch (node.kind) { - case 244 /* SwitchStatement */: - if (statement.kind === 240 /* ContinueStatement */) { + case 245 /* SwitchStatement */: + if (statement.kind === 241 /* ContinueStatement */) { return false; } // falls through - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 236 /* WhileStatement */: - case 235 /* DoStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 237 /* WhileStatement */: + case 236 /* DoStatement */: return !statement.label || isLabeledBy(node, statement.label.escapedText); default: // Don't cross function boundaries. @@ -122358,11 +126420,11 @@ var ts; // Types of node whose children might have modifiers. var container = declaration.parent; switch (container.kind) { - case 257 /* ModuleBlock */: - case 297 /* SourceFile */: - case 230 /* Block */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 258 /* ModuleBlock */: + case 298 /* SourceFile */: + case 231 /* Block */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) { return __spreadArray(__spreadArray([], declaration.members), [declaration]); @@ -122370,14 +126432,14 @@ var ts; else { return container.statements; } - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 251 /* FunctionDeclaration */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: return __spreadArray(__spreadArray([], container.parameters), (ts.isClassLike(container.parent) ? container.parent.members : [])); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 177 /* TypeLiteral */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 178 /* TypeLiteral */: var nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. @@ -122392,7 +126454,7 @@ var ts; } return nodes; // Syntactically invalid positions that the parser might produce anyway - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return undefined; default: ts.Debug.assertNever(container, "Invalid container kind."); @@ -122413,7 +126475,7 @@ var ts; var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 96 /* ForKeyword */, 114 /* WhileKeyword */, 89 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 235 /* DoStatement */) { + if (loopNode.kind === 236 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 114 /* WhileKeyword */)) { @@ -122433,13 +126495,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -122612,6 +126674,9 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + function isDocumentRegistryEntry(entry) { + return !!entry.sourceFile; + } function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); } @@ -122628,10 +126693,16 @@ var ts; var entries = buckets.get(name); var sourceFiles = []; entries.forEach(function (entry, name) { - sourceFiles.push({ - name: name, - refCount: entry.languageServiceRefCount - }); + if (isDocumentRegistryEntry(entry)) { + sourceFiles.push({ + name: name, + scriptKind: entry.sourceFile.scriptKind, + refCount: entry.languageServiceRefCount + }); + } + else { + entry.forEach(function (value, scriptKind) { return sourceFiles.push({ name: name, scriptKind: scriptKind, refCount: value.languageServiceRefCount }); }); + } }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); return { @@ -122657,10 +126728,17 @@ var ts; function updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind) { return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); } + function getDocumentRegistryEntry(bucketEntry, scriptKind) { + var entry = isDocumentRegistryEntry(bucketEntry) ? bucketEntry : bucketEntry.get(ts.Debug.checkDefined(scriptKind, "If there are more than one scriptKind's for same document the scriptKind should be provided")); + ts.Debug.assert(scriptKind === undefined || !entry || entry.sourceFile.scriptKind === scriptKind, "Script kind should match provided ScriptKind:" + scriptKind + " and sourceFile.scriptKind: " + (entry === null || entry === void 0 ? void 0 : entry.sourceFile.scriptKind) + ", !entry: " + !entry); + return entry; + } function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { - var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); - var entry = bucket.get(path); + scriptKind = ts.ensureScriptKind(fileName, scriptKind); var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; + var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); + var bucketEntry = bucket.get(path); + var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -122669,7 +126747,7 @@ var ts; sourceFile: sourceFile, languageServiceRefCount: 0 }; - bucket.set(path, entry); + setBucketEntry(); } } if (!entry) { @@ -122682,7 +126760,7 @@ var ts; sourceFile: sourceFile, languageServiceRefCount: 1, }; - bucket.set(path, entry); + setBucketEntry(); } else { // We have an entry for this file. However, it may be for a different version of @@ -122705,25 +126783,49 @@ var ts; } ts.Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; + function setBucketEntry() { + if (!bucketEntry) { + bucket.set(path, entry); + } + else if (isDocumentRegistryEntry(bucketEntry)) { + var scriptKindMap = new ts.Map(); + scriptKindMap.set(bucketEntry.sourceFile.scriptKind, bucketEntry); + scriptKindMap.set(scriptKind, entry); + bucket.set(path, scriptKindMap); + } + else { + bucketEntry.set(scriptKind, entry); + } + } } - function releaseDocument(fileName, compilationSettings) { + function releaseDocument(fileName, compilationSettings, scriptKind) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var key = getKeyForCompilationSettings(compilationSettings); - return releaseDocumentWithKey(path, key); + return releaseDocumentWithKey(path, key, scriptKind); } - function releaseDocumentWithKey(path, key) { + function releaseDocumentWithKey(path, key, scriptKind) { var bucket = ts.Debug.checkDefined(buckets.get(key)); - var entry = bucket.get(path); + var bucketEntry = bucket.get(path); + var entry = getDocumentRegistryEntry(bucketEntry, scriptKind); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - bucket.delete(path); + if (isDocumentRegistryEntry(bucketEntry)) { + bucket.delete(path); + } + else { + bucketEntry.delete(scriptKind); + if (bucketEntry.size === 1) { + bucket.set(path, ts.firstDefinedIterator(bucketEntry.values(), ts.identity)); + } + } } } - function getLanguageServiceRefCounts(path) { + function getLanguageServiceRefCounts(path, scriptKind) { return ts.arrayFrom(buckets.entries(), function (_a) { var key = _a[0], bucket = _a[1]; - var entry = bucket.get(path); + var bucketEntry = bucket.get(path); + var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); return [key, entry && entry.languageServiceRefCount]; }); } @@ -122786,10 +126888,12 @@ var ts; return sourceFiles; } // Module augmentations may use this module's exports without importing it. - for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (ts.isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) { - addIndirectUser(decl); + if (exportingModuleSymbol.declarations) { + for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) { + addIndirectUser(decl); + } } } // This may return duplicates (if there are multiple module declarations in a single source file, all importing the same thing as a namespace), but `State.markSearchedSymbol` will handle that. @@ -122806,14 +126910,14 @@ var ts; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); switch (direct.kind) { - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (ts.isImportCall(direct)) { handleImportCall(direct); break; } if (!isAvailableThroughGlobal) { var parent = direct.parent; - if (exportKind === 2 /* ExportEquals */ && parent.kind === 249 /* VariableDeclaration */) { + if (exportKind === 2 /* ExportEquals */ && parent.kind === 250 /* VariableDeclaration */) { var name = parent.name; if (name.kind === 78 /* Identifier */) { directImports.push(name); @@ -122824,25 +126928,25 @@ var ts; break; case 78 /* Identifier */: // for 'const x = require("y"); break; // TODO: GH#23879 - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: handleNamespaceImport(direct, direct.name, ts.hasSyntacticModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false); break; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: directImports.push(direct); var namedBindings = direct.importClause && direct.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 263 /* NamespaceImport */) { + if (namedBindings && namedBindings.kind === 264 /* NamespaceImport */) { handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true); } else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) { addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports } break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: if (!direct.exportClause) { // This is `export * from "foo"`, so imports of this module may import the export too. handleDirectImports(getContainingModuleSymbol(direct, checker)); } - else if (direct.exportClause.kind === 269 /* NamespaceExport */) { + else if (direct.exportClause.kind === 270 /* NamespaceExport */) { // `export * as foo from "foo"` add to indirect uses addIndirectUser(getSourceFileLikeForImportDeclaration(direct), /** addTransitiveDependencies */ true); } @@ -122851,7 +126955,7 @@ var ts; directImports.push(direct); } break; - case 195 /* ImportType */: + case 196 /* ImportType */: // Only check for typeof import('xyz') if (direct.isTypeOf && !direct.qualifier && isExported(direct)) { addIndirectUser(direct.getSourceFile(), /** addTransitiveDependencies */ true); @@ -122884,7 +126988,7 @@ var ts; } else if (!isAvailableThroughGlobal) { var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); - ts.Debug.assert(sourceFileLike.kind === 297 /* SourceFile */ || sourceFileLike.kind === 256 /* ModuleDeclaration */); + ts.Debug.assert(sourceFileLike.kind === 298 /* SourceFile */ || sourceFileLike.kind === 257 /* ModuleDeclaration */); if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { addIndirectUser(sourceFileLike, /** addTransitiveDependencies */ true); } @@ -122940,7 +127044,7 @@ var ts; } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { - if (decl.kind === 260 /* ImportEqualsDeclaration */) { + if (decl.kind === 261 /* ImportEqualsDeclaration */) { if (isExternalModuleImportEquals(decl)) { handleNamespaceImportLike(decl.name); } @@ -122950,7 +127054,7 @@ var ts; handleNamespaceImportLike(decl); return; } - if (decl.kind === 195 /* ImportType */) { + if (decl.kind === 196 /* ImportType */) { if (decl.qualifier) { var firstIdentifier = ts.getFirstIdentifier(decl.qualifier); if (firstIdentifier.escapedText === ts.symbolName(exportSymbol)) { @@ -122966,7 +127070,7 @@ var ts; if (decl.moduleSpecifier.kind !== 10 /* StringLiteral */) { return; } - if (decl.kind === 267 /* ExportDeclaration */) { + if (decl.kind === 268 /* ExportDeclaration */) { if (decl.exportClause && ts.isNamedExports(decl.exportClause)) { searchForNamedImport(decl.exportClause); } @@ -122975,10 +127079,10 @@ var ts; var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: handleNamespaceImportLike(namedBindings.name); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: // 'default' might be accessed as a named import `{ default as foo }`. if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) { searchForNamedImport(namedBindings); @@ -123028,7 +127132,7 @@ var ts; } } else { - var localSymbol = element.kind === 270 /* ExportSpecifier */ && element.propertyName + var localSymbol = element.kind === 271 /* ExportSpecifier */ && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. : checker.getSymbolAtLocation(name); addSearch(name, localSymbol); @@ -123057,7 +127161,7 @@ var ts; for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { var referencingFile = sourceFiles_1[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; - if (searchSourceFile.kind === 297 /* SourceFile */) { + if ((searchSourceFile === null || searchSourceFile === void 0 ? void 0 : searchSourceFile.kind) === 298 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { var ref = _b[_a]; if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { @@ -123105,7 +127209,7 @@ var ts; } /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return ts.forEach(sourceFileLike.kind === 297 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return ts.forEach(sourceFileLike.kind === 298 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); }); } @@ -123120,15 +127224,15 @@ var ts; else { forEachPossibleImportOrExportStatement(sourceFile, function (statement) { switch (statement.kind) { - case 267 /* ExportDeclaration */: - case 261 /* ImportDeclaration */: { + case 268 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: { var decl = statement; if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) { action(decl, decl.moduleSpecifier); } break; } - case 260 /* ImportEqualsDeclaration */: { + case 261 /* ImportEqualsDeclaration */: { var decl = statement; if (isExternalModuleImportEquals(decl)) { action(decl, decl.moduleReference.expression); @@ -123149,14 +127253,15 @@ var ts; function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { return comingFromExport ? getExport() : getExport() || getImport(); function getExport() { + var _a; var parent = node.parent; - var grandParent = parent.parent; + var grandparent = parent.parent; if (symbol.exportSymbol) { - if (parent.kind === 201 /* PropertyAccessExpression */) { + if (parent.kind === 202 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. - return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) - ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false) + return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d === parent; })) && ts.isBinaryExpression(grandparent) + ? getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ false) : undefined; } else { @@ -123186,15 +127291,15 @@ var ts; return getExportAssignmentExport(parent); } // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. - else if (ts.isExportAssignment(grandParent)) { - return getExportAssignmentExport(grandParent); + else if (ts.isExportAssignment(grandparent)) { + return getExportAssignmentExport(grandparent); } // Similar for `module.exports =` and `exports.A =`. else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } - else if (ts.isBinaryExpression(grandParent)) { - return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true); + else if (ts.isBinaryExpression(grandparent)) { + return getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ true); } else if (ts.isJSDocTypedefTag(parent)) { return exportInfo(symbol, 0 /* Named */); @@ -123202,9 +127307,10 @@ var ts; } function getExportAssignmentExport(ex) { // Get the symbol for the `export =` node; its parent is the module it's the export of. - var exportingModuleSymbol = ts.Debug.checkDefined(ex.symbol.parent, "Expected export symbol to have a parent"); + if (!ex.symbol.parent) + return undefined; var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */; - return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; + return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: ex.symbol.parent, exportKind: exportKind } }; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; @@ -123258,7 +127364,7 @@ var ts; if (importedSymbol.flags & 2097152 /* Alias */) { return ts.Debug.checkDefined(checker.getImmediateAliasedSymbol(importedSymbol)); } - var decl = importedSymbol.valueDeclaration; + var decl = ts.Debug.checkDefined(importedSymbol.valueDeclaration); if (ts.isExportAssignment(decl)) { // `export = class {}` return ts.Debug.checkDefined(decl.expression.symbol); } @@ -123285,17 +127391,17 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return parent.name === node && isExternalModuleImportEquals(parent); - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. return !parent.propertyName; - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: ts.Debug.assert(parent.name === node); return true; - case 198 /* BindingElement */: - return ts.isInJSFile(node) && ts.isRequireVariableDeclaration(parent, /*requireStringLiteralLikeArgument*/ true); + case 199 /* BindingElement */: + return ts.isInJSFile(node) && ts.isRequireVariableDeclaration(parent); default: return false; } @@ -123319,7 +127425,8 @@ var ts; return checker.getExportSpecifierLocalTargetSymbol(declaration); } else if (ts.isPropertyAccessExpression(declaration) && ts.isModuleExportsAccessExpression(declaration.expression) && !ts.isPrivateIdentifier(declaration.name)) { - return checker.getExportSpecifierLocalTargetSymbol(declaration.name); + // Export of form 'module.exports.propName = expr'; + return checker.getSymbolAtLocation(declaration); } else if (ts.isShorthandPropertyAssignment(declaration) && ts.isBinaryExpression(declaration.parent.parent) @@ -123334,21 +127441,21 @@ var ts; return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); } function getSourceFileLikeForImportDeclaration(node) { - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { return node.getSourceFile(); } var parent = node.parent; - if (parent.kind === 297 /* SourceFile */) { + if (parent.kind === 298 /* SourceFile */) { return parent; } - ts.Debug.assert(parent.kind === 257 /* ModuleBlock */); + ts.Debug.assert(parent.kind === 258 /* ModuleBlock */); return ts.cast(parent.parent, isAmbientModuleDeclaration); } function isAmbientModuleDeclaration(node) { - return node.kind === 256 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */; + return node.kind === 257 /* ModuleDeclaration */ && node.name.kind === 10 /* StringLiteral */; } function isExternalModuleImportEquals(eq) { - return eq.moduleReference.kind === 272 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */; + return eq.moduleReference.kind === 273 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 10 /* StringLiteral */; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -123451,7 +127558,7 @@ var ts; if (!node) return undefined; switch (node.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return !ts.isVariableDeclarationList(node.parent) || node.parent.declarations.length !== 1 ? node : ts.isVariableStatement(node.parent.parent) ? @@ -123459,28 +127566,28 @@ var ts; ts.isForInOrOfStatement(node.parent.parent) ? getContextNode(node.parent.parent) : node.parent; - case 198 /* BindingElement */: + case 199 /* BindingElement */: return getContextNode(node.parent.parent); - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: return node.parent.parent.parent; - case 270 /* ExportSpecifier */: - case 263 /* NamespaceImport */: + case 271 /* ExportSpecifier */: + case 264 /* NamespaceImport */: return node.parent.parent; - case 262 /* ImportClause */: - case 269 /* NamespaceExport */: + case 263 /* ImportClause */: + case 270 /* NamespaceExport */: return node.parent; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return ts.isExpressionStatement(node.parent) ? node.parent : node; - case 239 /* ForOfStatement */: - case 238 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 239 /* ForInStatement */: return { start: node.initializer, end: node.expression }; - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent) ? getContextNode(ts.findAncestor(node.parent, function (node) { return ts.isBinaryExpression(node) || ts.isForInOrOfStatement(node); @@ -123537,9 +127644,9 @@ var ts; var node = ts.getTouchingPropertyName(sourceFile, position); var referenceEntries; var entries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); - if (node.parent.kind === 201 /* PropertyAccessExpression */ - || node.parent.kind === 198 /* BindingElement */ - || node.parent.kind === 202 /* ElementAccessExpression */ + if (node.parent.kind === 202 /* PropertyAccessExpression */ + || node.parent.kind === 199 /* BindingElement */ + || node.parent.kind === 203 /* ElementAccessExpression */ || node.kind === 105 /* SuperKeyword */) { referenceEntries = entries && __spreadArray([], entries); } @@ -123563,13 +127670,13 @@ var ts; } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { return undefined; } var checker = program.getTypeChecker(); // 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 === 289 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 290 /* ShorthandPropertyAssignment */) { var result_1 = []; Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_1.push(nodeEntry(node)); }); return result_1; @@ -123744,13 +127851,13 @@ var ts; if (symbol) { return getDefinitionKindAndDisplayParts(symbol, checker, node); } - else if (node.kind === 200 /* ObjectLiteralExpression */) { + else if (node.kind === 201 /* ObjectLiteralExpression */) { return { kind: "interface" /* interfaceElement */, displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(21 /* CloseParenToken */)] }; } - else if (node.kind === 221 /* ClassExpression */) { + else if (node.kind === 222 /* ClassExpression */) { return { kind: "local class" /* localClassElement */, displayParts: [ts.punctuationPart(20 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(21 /* CloseParenToken */)] @@ -123811,47 +127918,47 @@ var ts; if (!!(decl.flags & 8388608 /* Ambient */)) return true; switch (decl.kind) { - case 216 /* BinaryExpression */: - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 217 /* BinaryExpression */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: case 87 /* DefaultKeyword */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: - case 270 /* ExportSpecifier */: - case 262 /* ImportClause */: // default import - case 260 /* ImportEqualsDeclaration */: - case 265 /* ImportSpecifier */: - case 253 /* InterfaceDeclaration */: - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: - case 280 /* JsxAttribute */: - case 256 /* ModuleDeclaration */: - case 259 /* NamespaceExportDeclaration */: - case 263 /* NamespaceImport */: - case 269 /* NamespaceExport */: - case 160 /* Parameter */: - case 289 /* ShorthandPropertyAssignment */: - case 254 /* TypeAliasDeclaration */: - case 159 /* TypeParameter */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: + case 271 /* ExportSpecifier */: + case 263 /* ImportClause */: // default import + case 261 /* ImportEqualsDeclaration */: + case 266 /* ImportSpecifier */: + case 254 /* InterfaceDeclaration */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: + case 281 /* JsxAttribute */: + case 257 /* ModuleDeclaration */: + case 260 /* NamespaceExportDeclaration */: + case 264 /* NamespaceImport */: + case 270 /* NamespaceExport */: + case 161 /* Parameter */: + case 290 /* ShorthandPropertyAssignment */: + case 255 /* TypeAliasDeclaration */: + case 160 /* TypeParameter */: return true; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return !!decl.body; - case 249 /* VariableDeclaration */: - case 163 /* PropertyDeclaration */: + case 250 /* VariableDeclaration */: + case 164 /* PropertyDeclaration */: return !!decl.initializer || ts.isCatchClause(decl.parent); - case 164 /* MethodSignature */: - case 162 /* PropertySignature */: - case 333 /* JSDocPropertyTag */: - case 326 /* JSDocParameterTag */: + case 165 /* MethodSignature */: + case 163 /* PropertySignature */: + case 337 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: return false; default: return ts.Debug.failBadSyntaxKind(decl); @@ -123873,7 +127980,7 @@ var ts; } if (ts.isSourceFile(node)) { var resolvedRef = ts.GoToDefinition.getReferenceAtPosition(node, position, program); - if (!resolvedRef) { + if (!(resolvedRef === null || resolvedRef === void 0 ? void 0 : resolvedRef.file)) { return undefined; } var moduleSymbol = program.getTypeChecker().getMergedSymbol(resolvedRef.file.symbol); @@ -123902,7 +128009,7 @@ var ts; if (!symbol) { // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. if (!options.implementations && ts.isStringLiteralLike(node)) { - if (ts.isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ true) || ts.isExternalModuleReference(node.parent) || ts.isImportDeclaration(node.parent) || ts.isImportCall(node.parent)) { + if (ts.isModuleSpecifierLike(node)) { var fileIncludeReasons = program.getFileIncludeReasons(); var referencedFileName = (_b = (_a = node.getSourceFile().resolvedModules) === null || _a === void 0 ? void 0 : _a.get(node.text)) === null || _b === void 0 ? void 0 : _b.resolvedFileName; var referencedFile = referencedFileName ? program.getSourceFile(referencedFileName) : undefined; @@ -124003,7 +128110,7 @@ var ts; result = references; continue; } - var _loop_3 = function (entry) { + var _loop_4 = function (entry) { if (!entry.definition || entry.definition.type !== 0 /* Symbol */) { result.push(entry); return "continue"; @@ -124035,7 +128142,7 @@ var ts; }; for (var _b = 0, references_2 = references; _b < references_2.length; _b++) { var entry = references_2[_b]; - _loop_3(entry); + _loop_4(entry); } } return result; @@ -124072,10 +128179,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; switch (decl.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) break; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { references.push(nodeEntry(decl.name)); } @@ -124087,7 +128194,7 @@ var ts; } } var exported = symbol.exports.get("export=" /* ExportEquals */); - if (exported) { + if (exported === null || exported === void 0 ? void 0 : exported.declarations) { for (var _b = 0, _c = exported.declarations; _b < _c.length; _b++) { var decl = _c[_b]; var sourceFile = decl.getSourceFile(); @@ -124150,14 +128257,14 @@ var ts; var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); - var exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); + var exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) || !symbol.declarations ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); if (exportSpecifier) { // When renaming at an export specifier, rename the export and not the thing being exported. getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); } - else if (node && node.kind === 87 /* DefaultKeyword */) { + else if (node && node.kind === 87 /* DefaultKeyword */ && symbol.escapedName === "default" /* Default */ && symbol.parent) { addReference(node, symbol, state); - searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.checkDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: 1 /* Default */ }, state); } else { var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === 2 /* Rename */, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); @@ -124183,7 +128290,7 @@ var ts; } function getSpecialSearchKind(node) { switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: case 132 /* ConstructorKeyword */: return 1 /* Constructor */; case 78 /* Identifier */: @@ -124314,8 +128421,8 @@ var ts; var sourceId = ts.getNodeId(sourceFile); var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = new ts.Set()); var anyNewSymbols = false; - for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { - var sym = symbols_3[_i]; + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var sym = symbols_2[_i]; anyNewSymbols = ts.tryAddToSet(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols; } return anyNewSymbols; @@ -124372,7 +128479,9 @@ var ts; for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { var node = _d[_c]; // Import specifiers should be handled by importSearches - if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) { + var symbol = checker.getSymbolAtLocation(node); + var hasExportAssignmentDeclaration = ts.some(symbol === null || symbol === void 0 ? void 0 : symbol.declarations, function (d) { return ts.tryCast(d, ts.isExportAssignment) ? true : false; }); + if (ts.isIdentifier(node) && !ts.isImportOrExportSpecifier(node.parent) && (symbol === exportSymbol || hasExportAssignmentDeclaration)) { cb(node); } } @@ -124424,7 +128533,7 @@ var ts; // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 208 /* FunctionExpression */ || valueDeclaration.kind === 221 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 209 /* FunctionExpression */ || valueDeclaration.kind === 222 /* ClassExpression */)) { return valueDeclaration; } if (!declarations) { @@ -124432,9 +128541,9 @@ var ts; } // If this is private property or method, the scope is the containing class if (flags & (4 /* Property */ | 8192 /* Method */)) { - var privateDeclaration = ts.find(declarations, function (d) { return ts.hasEffectiveModifier(d, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(d); }); + var privateDeclaration = ts.find(declarations, function (d) { return ts.hasEffectiveModifier(d, 8 /* Private */) || ts.isPrivateIdentifierClassElementDeclaration(d); }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 252 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 253 /* ClassDeclaration */); } // Else this is a public property and could be accessed from anywhere. return undefined; @@ -124463,7 +128572,7 @@ var ts; // Different declarations have different containers, bail out return undefined; } - if (!container || container.kind === 297 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + if (!container || container.kind === 298 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -124679,6 +128788,10 @@ var ts; default: ts.Debug.assertNever(state.specialSearchKind); } + // Use the parent symbol if the location is commonjs require syntax on javascript files only. + referenceSymbol = ts.isInJSFile(referenceLocation) && referenceLocation.parent.kind === 199 /* BindingElement */ && ts.isRequireVariableDeclaration(referenceLocation.parent) + ? referenceLocation.parent.symbol + : referenceSymbol; getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { @@ -124841,14 +128954,14 @@ var ts; for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; var ctrKeyword = ts.findChildOfKind(decl, 132 /* ConstructorKeyword */, sourceFile); - ts.Debug.assert(decl.kind === 166 /* Constructor */ && !!ctrKeyword); + ts.Debug.assert(decl.kind === 167 /* Constructor */ && !!ctrKeyword); addNode(ctrKeyword); } } if (classSymbol.exports) { classSymbol.exports.forEach(function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 165 /* MethodDeclaration */) { + if (decl && decl.kind === 166 /* MethodDeclaration */) { var body = decl.body; if (body) { forEachDescendantOfKind(body, 107 /* ThisKeyword */, function (thisKeyword) { @@ -124872,7 +128985,7 @@ var ts; } for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 166 /* Constructor */); + ts.Debug.assert(decl.kind === 167 /* Constructor */); var body = decl.body; if (body) { forEachDescendantOfKind(body, 105 /* SuperKeyword */, function (node) { @@ -124902,7 +129015,7 @@ var ts; if (refNode.kind !== 78 /* Identifier */) { return; } - if (refNode.parent.kind === 289 /* ShorthandPropertyAssignment */) { + if (refNode.parent.kind === 290 /* ShorthandPropertyAssignment */) { // Go ahead and dereference the shorthand assignment by going to its definition getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); } @@ -124922,7 +129035,7 @@ var ts; } else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) { var body = typeHavingNode.body; - if (body.kind === 230 /* Block */) { + if (body.kind === 231 /* Block */) { ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression) addIfImplementation(returnStatement.expression); @@ -124950,13 +129063,13 @@ var ts; */ function isImplementationExpression(node) { switch (node.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isImplementationExpression(node.expression); - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: - case 200 /* ObjectLiteralExpression */: - case 221 /* ClassExpression */: - case 199 /* ArrayLiteralExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 201 /* ObjectLiteralExpression */: + case 222 /* ClassExpression */: + case 200 /* ArrayLiteralExpression */: return true; default: return false; @@ -125009,13 +129122,13 @@ var ts; // Whether 'super' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -125036,41 +129149,43 @@ var ts; return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function isParameterName(node) { - return node.kind === 78 /* Identifier */ && node.parent.kind === 160 /* Parameter */ && node.parent.name === node; + return node.kind === 78 /* Identifier */ && node.parent.kind === 161 /* Parameter */ && node.parent.name === node; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { + staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning object literals break; } // falls through - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: staticFlag &= ts.getSyntacticModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) { return undefined; } // falls through - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: break; // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. default: return undefined; } - var references = ts.flatMap(searchSpaceNode.kind === 297 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { + var references = ts.flatMap(searchSpaceNode.kind === 298 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) { if (!ts.isThis(node)) { @@ -125078,19 +129193,20 @@ var ts; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: return searchSpaceNode.symbol === container.symbol; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: - // Make sure the container belongs to the same class + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 201 /* ObjectLiteralExpression */: + // Make sure the container belongs to the same class/object literals // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getSyntacticModifierFlags(container) & 32 /* Static */) === staticFlag; - case 297 /* SourceFile */: - return container.kind === 297 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node); + case 298 /* SourceFile */: + return container.kind === 298 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node); } }); }).map(function (n) { return nodeEntry(n); }); @@ -125200,7 +129316,7 @@ 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]); } - var exportSpecifier = ts.getDeclarationOfKind(symbol, 270 /* ExportSpecifier */); + var exportSpecifier = ts.getDeclarationOfKind(symbol, 271 /* ExportSpecifier */); if (!isForRenamePopulateSearchSymbolSet || exportSpecifier && !exportSpecifier.propertyName) { var localSymbol = exportSpecifier && checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); if (localSymbol) { @@ -125245,7 +129361,7 @@ var ts; }); } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - var bindingElement = ts.getDeclarationOfKind(symbol, 198 /* BindingElement */); + var bindingElement = ts.getDeclarationOfKind(symbol, 199 /* BindingElement */); if (bindingElement && ts.isObjectBindingElementWithoutPropertyName(bindingElement)) { return ts.getPropertySymbolFromBindingElement(checker, bindingElement); } @@ -125498,16 +129614,16 @@ var ts; return; } switch (node.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: - if (node.parent.kind === 200 /* ObjectLiteralExpression */) { + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + if (node.parent.kind === 201 /* ObjectLiteralExpression */) { return (_a = ts.getAssignedName(node.parent)) === null || _a === void 0 ? void 0 : _a.getText(); } return (_b = ts.getNameOfDeclaration(node.parent)) === null || _b === void 0 ? void 0 : _b.getText(); - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: if (ts.isModuleBlock(node.parent) && ts.isIdentifier(node.parent.parent.name)) { return node.parent.parent.name.getText(); } @@ -125713,55 +129829,55 @@ var ts; } switch (node.kind) { case 78 /* Identifier */: - case 260 /* ImportEqualsDeclaration */: - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: // do not descend into nodes that cannot contain callable nodes return; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: // do not descend into the type side of an assertion collect(node.expression); return; - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: // do not descend into the type of a variable or parameter declaration collect(node.name); collect(node.initializer); return; - case 203 /* CallExpression */: + case 204 /* CallExpression */: // do not descend into the type arguments of a call expression recordCallSite(node); collect(node.expression); ts.forEach(node.arguments, collect); return; - case 204 /* NewExpression */: + case 205 /* NewExpression */: // do not descend into the type arguments of a new expression recordCallSite(node); collect(node.expression); ts.forEach(node.arguments, collect); return; - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: // do not descend into the type arguments of a tagged template expression recordCallSite(node); collect(node.tag); collect(node.template); return; - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: // do not descend into the type arguments of a JsxOpeningLikeElement recordCallSite(node); collect(node.tagName); collect(node.attributes); return; - case 161 /* Decorator */: + case 162 /* Decorator */: recordCallSite(node); collect(node.expression); return; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: recordCallSite(node); ts.forEachChild(node, collect); break; @@ -125811,22 +129927,22 @@ var ts; var callSites = []; var collect = createCallSiteCollector(program, callSites); switch (node.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: collectCallSitesOfSourceFile(node, collect); break; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: collectCallSitesOfModuleDeclaration(node, collect); break; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: collectCallSitesOfFunctionLikeDeclaration(program.getTypeChecker(), node, collect); break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: collectCallSitesOfClassLikeDeclaration(node, collect); break; default: @@ -125959,7 +130075,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_4 = function (sourceFile) { + var _loop_5 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.fileName); var newImportFromPath = newFromOld !== null && newFromOld !== void 0 ? newFromOld : sourceFile.fileName; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -125976,7 +130092,7 @@ var ts; }, function (importLiteral) { var importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); // No need to update if it's an ambient module^M - if (importedModuleSymbol && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) + if ((importedModuleSymbol === null || importedModuleSymbol === void 0 ? void 0 : importedModuleSymbol.declarations) && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) return undefined; var toImport = oldFromNew !== undefined // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. @@ -125991,7 +130107,7 @@ var ts; }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_4(sourceFile); + _loop_5(sourceFile); } } function combineNormal(pathA, pathB) { @@ -126082,8 +130198,10 @@ var ts; (function (GoToDefinition) { function getDefinitionAtPosition(program, sourceFile, position) { var resolvedRef = getReferenceAtPosition(sourceFile, position, program); - if (resolvedRef) { - return [getDefinitionInfoForFileReference(resolvedRef.reference.fileName, resolvedRef.file.fileName)]; + var fileReferenceDefinition = resolvedRef && [getDefinitionInfoForFileReference(resolvedRef.reference.fileName, resolvedRef.fileName, resolvedRef.unverified)] || ts.emptyArray; + if (resolvedRef === null || resolvedRef === void 0 ? void 0 : resolvedRef.file) { + // If `file` is missing, do a symbol-based lookup as well + return fileReferenceDefinition; } var node = ts.getTouchingPropertyName(sourceFile, position); if (node === sourceFile) { @@ -126100,7 +130218,7 @@ var ts; // Could not find a symbol e.g. node is string or number keyword, // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol if (!symbol) { - return getDefinitionInfoForIndexSignatures(node, typeChecker); + return ts.concatenate(fileReferenceDefinition, getDefinitionInfoForIndexSignatures(node, typeChecker)); } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. @@ -126122,9 +130240,10 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 289 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 290 /* ShorthandPropertyAssignment */) { var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); - return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : []; + var definitions = (shorthandSymbol_1 === null || shorthandSymbol_1 === void 0 ? void 0 : shorthandSymbol_1.declarations) ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : ts.emptyArray; + return ts.concatenate(definitions, getDefinitionFromObjectLiteralElement(typeChecker, node) || ts.emptyArray); } // If the node is the name of a BindingElement within an ObjectBindingPattern instead of just returning the // declaration the symbol (which is itself), we should try to get to the original type of the ObjectBindingPattern @@ -126146,25 +130265,7 @@ var ts; return prop && getDefinitionFromSymbol(typeChecker, prop, node); }); } - // If the current location we want to find its definition is in an object literal, try to get the contextual type for the - // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. - // For example - // interface Props{ - // /*first*/prop1: number - // prop2: boolean - // } - // function Foo(arg: Props) {} - // Foo( { pr/*1*/op1: 10, prop2: true }) - var element = ts.getContainingObjectLiteralElement(node); - if (element) { - var contextualType = element && typeChecker.getContextualType(element.parent); - if (contextualType) { - return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) { - return getDefinitionFromSymbol(typeChecker, propertySymbol, node); - }); - } - } - return getDefinitionFromSymbol(typeChecker, symbol, node); + return ts.concatenate(fileReferenceDefinition, getDefinitionFromObjectLiteralElement(typeChecker, node) || getDefinitionFromSymbol(typeChecker, symbol, node)); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; /** @@ -126178,22 +130279,60 @@ var ts; || ts.isAssignmentExpression(calledDeclaration.parent) || (!ts.isCallLikeExpression(calledDeclaration.parent) && s === calledDeclaration.parent.symbol); } + // If the current location we want to find its definition is in an object literal, try to get the contextual type for the + // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. + // For example + // interface Props{ + // /*first*/prop1: number + // prop2: boolean + // } + // function Foo(arg: Props) {} + // Foo( { pr/*1*/op1: 10, prop2: true }) + function getDefinitionFromObjectLiteralElement(typeChecker, node) { + var element = ts.getContainingObjectLiteralElement(node); + if (element) { + var contextualType = element && typeChecker.getContextualType(element.parent); + if (contextualType) { + return ts.flatMap(ts.getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), function (propertySymbol) { + return getDefinitionFromSymbol(typeChecker, propertySymbol, node); + }); + } + } + } function getReferenceAtPosition(sourceFile, position, program) { + var _a, _b; var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); if (referencePath) { var file = program.getSourceFileFromReference(sourceFile, referencePath); - return file && { reference: referencePath, file: file }; + return file && { reference: referencePath, fileName: file.fileName, file: file, unverified: false }; } var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); var file = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217 - return file && { reference: typeReferenceDirective, file: file }; + return file && { reference: typeReferenceDirective, fileName: file.fileName, file: file, unverified: false }; } var libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position); if (libReferenceDirective) { var file = program.getLibFileFromReference(libReferenceDirective); - return file && { reference: libReferenceDirective, file: file }; + return file && { reference: libReferenceDirective, fileName: file.fileName, file: file, unverified: false }; + } + if ((_a = sourceFile.resolvedModules) === null || _a === void 0 ? void 0 : _a.size) { + var node = ts.getTokenAtPosition(sourceFile, position); + if (ts.isModuleSpecifierLike(node) && ts.isExternalModuleNameRelative(node.text) && sourceFile.resolvedModules.has(node.text)) { + var verifiedFileName = (_b = sourceFile.resolvedModules.get(node.text)) === null || _b === void 0 ? void 0 : _b.resolvedFileName; + var fileName = verifiedFileName || ts.resolvePath(ts.getDirectoryPath(sourceFile.fileName), node.text); + return { + file: program.getSourceFile(fileName), + fileName: fileName, + reference: { + pos: node.getStart(), + end: node.getEnd(), + fileName: node.text + }, + unverified: !verifiedFileName, + }; + } } return undefined; } @@ -126264,7 +130403,7 @@ var ts; // get the aliased symbol instead. This allows for goto def on an import e.g. // import {A, B} from "mod"; // to jump to the implementation directly. - if (symbol && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { + if ((symbol === null || symbol === void 0 ? void 0 : symbol.declarations) && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { var aliased = checker.getAliasedSymbol(symbol); if (aliased.declarations) { return aliased; @@ -126285,14 +130424,14 @@ var ts; return true; } switch (declaration.kind) { - case 262 /* ImportClause */: - case 260 /* ImportEqualsDeclaration */: + case 263 /* ImportClause */: + case 261 /* ImportEqualsDeclaration */: return true; - case 265 /* ImportSpecifier */: - return declaration.parent.kind === 264 /* NamedImports */; - case 198 /* BindingElement */: - case 249 /* VariableDeclaration */: - return ts.isInJSFile(declaration) && ts.isRequireVariableDeclaration(declaration, /*requireStringLiteralLikeArgument*/ true); + case 266 /* ImportSpecifier */: + return declaration.parent.kind === 265 /* NamedImports */; + case 199 /* BindingElement */: + case 250 /* VariableDeclaration */: + return ts.isInJSFile(declaration) && ts.isRequireVariableDeclaration(declaration); default: return false; } @@ -126344,7 +130483,38 @@ var ts; var sourceFile = name.getSourceFile(); var textSpan = ts.createTextSpanFromNode(name, sourceFile); return __assign(__assign({ fileName: sourceFile.fileName, textSpan: textSpan, kind: symbolKind, name: symbolName, containerKind: undefined, // TODO: GH#18217 - containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !checker.isDeclarationVisible(declaration) }); + containerName: containerName }, ts.FindAllReferences.toContextSpan(textSpan, sourceFile, ts.FindAllReferences.getContextNode(declaration))), { isLocal: !isDefinitionVisible(checker, declaration) }); + } + function isDefinitionVisible(checker, declaration) { + if (checker.isDeclarationVisible(declaration)) + return true; + if (!declaration.parent) + return false; + // Variable initializers are visible if variable is visible + if (ts.hasInitializer(declaration.parent) && declaration.parent.initializer === declaration) + return isDefinitionVisible(checker, declaration.parent); + // Handle some exceptions here like arrow function, members of class and object literal expression which are technically not visible but we want the definition to be determined by its parent + switch (declaration.kind) { + case 164 /* PropertyDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + // Private/protected properties/methods are not visible + if (ts.hasEffectiveModifier(declaration, 8 /* Private */)) + return false; + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 167 /* Constructor */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 201 /* ObjectLiteralExpression */: + case 222 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + return isDefinitionVisible(checker, declaration.parent); + default: + return false; + } } function createDefinitionFromSignatureDeclaration(typeChecker, decl) { return createDefinitionInfo(decl, typeChecker, decl.symbol, decl); @@ -126353,14 +130523,15 @@ var ts; return ts.find(refs, function (ref) { return ts.textRangeContainsPositionInclusive(ref, pos); }); } GoToDefinition.findReferenceInPosition = findReferenceInPosition; - function getDefinitionInfoForFileReference(name, targetFileName) { + function getDefinitionInfoForFileReference(name, targetFileName, unverified) { return { fileName: targetFileName, textSpan: ts.createTextSpanFromBounds(0, 0), kind: "script" /* scriptElement */, name: name, containerName: undefined, - containerKind: undefined, // TODO: GH#18217 + containerKind: undefined, + unverified: unverified, }; } /** Returns a CallLikeExpression where `node` is the target being invoked. */ @@ -126377,9 +130548,9 @@ var ts; } function isConstructorLike(node) { switch (node.kind) { - case 166 /* Constructor */: - case 175 /* ConstructorType */: - case 170 /* ConstructSignature */: + case 167 /* Constructor */: + case 176 /* ConstructorType */: + case 171 /* ConstructSignature */: return true; default: return false; @@ -126436,6 +130607,7 @@ var ts; "kind", "lends", "license", + "link", "listens", "member", "memberof", @@ -126473,78 +130645,115 @@ var ts; ]; var jsDocTagNameCompletionEntries; var jsDocTagCompletionEntries; - function getJsDocCommentsFromDeclarations(declarations) { + function getJsDocCommentsFromDeclarations(declarations, checker) { // Only collect doc comments from duplicate declarations once: // In case of a union property there might be same declaration multiple times // which only varies in type parameter // Eg. const a: Array | Array; a.length // The property length will have two declarations of property length coming // from Array - Array and Array - var documentationComment = []; + var parts = []; ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { var comment = _a[_i].comment; if (comment === undefined) continue; - ts.pushIfUnique(documentationComment, comment); + var newparts = getDisplayPartsFromComment(comment, checker); + if (!ts.contains(parts, newparts, isIdenticalListOfDisplayParts)) { + parts.push(newparts); + } } }); - return ts.intersperse(ts.map(documentationComment, ts.textPart), ts.lineBreakPart()); + return ts.flatten(ts.intersperse(parts, [ts.lineBreakPart()])); } JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function isIdenticalListOfDisplayParts(parts1, parts2) { + return ts.arraysEqual(parts1, parts2, function (p1, p2) { return p1.kind === p2.kind && p1.text === p2.text; }); + } function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 326 /* JSDocParameterTag */: - case 333 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: return [declaration]; - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); } } - function getJsDocTagsFromDeclarations(declarations) { + function getJsDocTagsFromDeclarations(declarations, checker) { // Only collect doc comments from duplicate declarations once. var tags = []; ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { var tag = _a[_i]; - tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); + tags.push({ name: tag.tagName.text, text: getCommentDisplayParts(tag, checker) }); } }); return tags; } JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations; - function getCommentText(tag) { - var comment = tag.comment; - switch (tag.kind) { - case 316 /* JSDocImplementsTag */: + function getDisplayPartsFromComment(comment, checker) { + if (typeof comment === "string") { + return [ts.textPart(comment)]; + } + return ts.flatMap(comment, function (node) { return node.kind === 313 /* JSDocText */ ? [ts.textPart(node.text)] : ts.buildLinkParts(node, checker); }); + } + function getCommentDisplayParts(tag, checker) { + var comment = tag.comment, kind = tag.kind; + var namePart = getTagNameDisplayPart(kind); + switch (kind) { + case 319 /* JSDocImplementsTag */: return withNode(tag.class); - case 315 /* JSDocAugmentsTag */: + case 318 /* JSDocAugmentsTag */: return withNode(tag.class); - case 330 /* JSDocTemplateTag */: - return withList(tag.typeParameters); - case 329 /* JSDocTypeTag */: + case 334 /* JSDocTemplateTag */: + return addComment(tag.typeParameters.map(function (tp) { return tp.getText(); }).join(", ")); + case 333 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 333 /* JSDocPropertyTag */: - case 326 /* JSDocParameterTag */: - case 332 /* JSDocSeeTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 337 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: + case 336 /* JSDocSeeTag */: var name = tag.name; - return name ? withNode(name) : comment; + return name ? withNode(name) + : comment === undefined ? undefined + : getDisplayPartsFromComment(comment, checker); default: - return comment; + return comment === undefined ? undefined : getDisplayPartsFromComment(comment, checker); } function withNode(node) { return addComment(node.getText()); } - function withList(list) { - return addComment(list.map(function (x) { return x.getText(); }).join(", ")); - } function addComment(s) { - return comment === undefined ? s : s + " " + comment; + if (comment) { + if (s.match(/^https?$/)) { + return __spreadArray([ts.textPart(s)], getDisplayPartsFromComment(comment, checker)); + } + else { + return __spreadArray([namePart(s), ts.spacePart()], getDisplayPartsFromComment(comment, checker)); + } + } + else { + return [ts.textPart(s)]; + } + } + } + function getTagNameDisplayPart(kind) { + switch (kind) { + case 330 /* JSDocParameterTag */: + return ts.parameterNamePart; + case 337 /* JSDocPropertyTag */: + return ts.propertyNamePart; + case 334 /* JSDocTemplateTag */: + return ts.typeParameterNamePart; + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + return ts.typeAliasNamePart; + default: + return ts.textPart; } } function getJSDocTagNameCompletions() { @@ -126638,7 +130847,7 @@ var ts; * @param position The (character-indexed) position in the file where the check should * be performed. */ - function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { + function getDocCommentTemplateAtPosition(newLine, sourceFile, position, options) { var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); var existingDocComment = ts.findAncestor(tokenAtPos, ts.isJSDoc); if (existingDocComment && (existingDocComment.comment !== undefined || ts.length(existingDocComment.tags))) { @@ -126650,7 +130859,7 @@ var ts; if (!existingDocComment && tokenStart < position) { return undefined; } - var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); + var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos, options); if (!commentOwnerInfo) { return undefined; } @@ -126700,76 +130909,77 @@ var ts; function returnsDocComment(indentationStr, newLine) { return indentationStr + " * @returns" + newLine; } - function getCommentOwnerInfo(tokenAtPos) { - return ts.forEachAncestor(tokenAtPos, getCommentOwnerInfoWorker); + function getCommentOwnerInfo(tokenAtPos, options) { + return ts.forEachAncestor(tokenAtPos, function (n) { return getCommentOwnerInfoWorker(n, options); }); } - function getCommentOwnerInfoWorker(commentOwner) { + function getCommentOwnerInfoWorker(commentOwner, options) { switch (commentOwner.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 164 /* MethodSignature */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 165 /* MethodSignature */: + case 210 /* ArrowFunction */: var host = commentOwner; - return { commentOwner: commentOwner, parameters: host.parameters, hasReturn: hasReturn(host) }; - case 288 /* PropertyAssignment */: - return getCommentOwnerInfoWorker(commentOwner.initializer); - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 162 /* PropertySignature */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: - case 254 /* TypeAliasDeclaration */: + return { commentOwner: commentOwner, parameters: host.parameters, hasReturn: hasReturn(host, options) }; + case 289 /* PropertyAssignment */: + return getCommentOwnerInfoWorker(commentOwner.initializer, options); + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 163 /* PropertySignature */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: + case 255 /* TypeAliasDeclaration */: return { commentOwner: commentOwner }; - case 232 /* VariableStatement */: { + case 233 /* VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; var host_1 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; return host_1 - ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1) } + ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1, options) } : { commentOwner: commentOwner }; } - case 297 /* SourceFile */: + case 298 /* SourceFile */: return "quit"; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: // If in walking up the tree, we hit a a nested namespace declaration, // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - return commentOwner.parent.kind === 256 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; - case 233 /* ExpressionStatement */: - return getCommentOwnerInfoWorker(commentOwner.expression); - case 216 /* BinaryExpression */: { + return commentOwner.parent.kind === 257 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 234 /* ExpressionStatement */: + return getCommentOwnerInfoWorker(commentOwner.expression, options); + case 217 /* BinaryExpression */: { var be = commentOwner; if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } return ts.isFunctionLike(be.right) - ? { commentOwner: commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right) } + ? { commentOwner: commentOwner, parameters: be.right.parameters, hasReturn: hasReturn(be.right, options) } : { commentOwner: commentOwner }; } - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: var init = commentOwner.initializer; if (init && (ts.isFunctionExpression(init) || ts.isArrowFunction(init))) { - return { commentOwner: commentOwner, parameters: init.parameters, hasReturn: hasReturn(init) }; + return { commentOwner: commentOwner, parameters: init.parameters, hasReturn: hasReturn(init, options) }; } } } - function hasReturn(node) { - return ts.isArrowFunction(node) && ts.isExpression(node.body) - || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; }); + function hasReturn(node, options) { + return !!(options === null || options === void 0 ? void 0 : options.generateReturnInDocTemplate) && + (ts.isArrowFunction(node) && ts.isExpression(node.body) + || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; })); } function getRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 207 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 208 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return rightHandSide; - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return ts.find(rightHandSide.members, ts.isConstructorDeclaration); } } @@ -126785,7 +130995,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_5 = function (sourceFile) { + var _loop_6 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -126797,7 +131007,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { var sourceFile = sourceFiles_4[_i]; - _loop_5(sourceFile); + _loop_6(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -126828,9 +131038,9 @@ var ts; } function shouldKeepItem(declaration, checker) { switch (declaration.kind) { - case 262 /* ImportClause */: - case 265 /* ImportSpecifier */: - case 260 /* ImportEqualsDeclaration */: + case 263 /* ImportClause */: + case 266 /* ImportSpecifier */: + case 261 /* ImportEqualsDeclaration */: var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217 var imported = checker.getAliasedSymbol(importer); return importer.escapedName !== imported.escapedName; @@ -126840,7 +131050,7 @@ var ts; } function tryAddSingleDeclarationName(declaration, containers) { var name = ts.getNameOfDeclaration(declaration); - return !!name && (pushLiteral(name, containers) || name.kind === 158 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); + return !!name && (pushLiteral(name, containers) || name.kind === 159 /* ComputedPropertyName */ && tryAddComputedPropertyName(name.expression, containers)); } // Only added the names of computed properties if they're simple dotted expressions, like: // @@ -126857,7 +131067,7 @@ var ts; // First, if we started with a computed property name, then add all but the last // portion into the container array. var name = ts.getNameOfDeclaration(declaration); - if (name && name.kind === 158 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { + if (name && name.kind === 159 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers)) { return ts.emptyArray; } // Don't include the last portion. @@ -127057,6 +131267,28 @@ var ts; addChildrenRecursively(child); endNode(); } + function addNodeWithRecursiveInitializer(node) { + if (node.initializer && isFunctionOrClassExpression(node.initializer)) { + startNode(node); + ts.forEachChild(node.initializer, addChildrenRecursively); + endNode(); + } + else { + addNodeWithRecursiveChild(node, node.initializer); + } + } + /** + * Historically, we've elided dynamic names from the nav tree (including late bound names), + * but included certain "well known" symbol names. While we no longer distinguish those well-known + * symbols from other unique symbols, we do the below to retain those members in the nav tree. + */ + function hasNavigationBarName(node) { + return !ts.hasDynamicName(node) || + (node.kind !== 217 /* BinaryExpression */ && + ts.isPropertyAccessExpression(node.name.expression) && + ts.isIdentifier(node.name.expression.expression) && + ts.idText(node.name.expression.expression) === "Symbol"); + } /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ function addChildrenRecursively(node) { var _a; @@ -127065,7 +131297,7 @@ var ts; return; } switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. var ctr = node; addNodeWithRecursiveChild(ctr, ctr.body); @@ -127077,21 +131309,25 @@ var ts; } } break; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 164 /* MethodSignature */: - if (!ts.hasDynamicName(node)) { + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 165 /* MethodSignature */: + if (hasNavigationBarName(node)) { addNodeWithRecursiveChild(node, node.body); } break; - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - if (!ts.hasDynamicName(node)) { + case 164 /* PropertyDeclaration */: + if (hasNavigationBarName(node)) { + addNodeWithRecursiveInitializer(node); + } + break; + case 163 /* PropertySignature */: + if (hasNavigationBarName(node)) { addLeafNode(node); } break; - case 262 /* ImportClause */: + case 263 /* ImportClause */: var importClause = node; // Handle default import case e.g.: // import d from "mod"; @@ -127103,7 +131339,7 @@ var ts; // import {a, b as B} from "mod"; var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 263 /* NamespaceImport */) { + if (namedBindings.kind === 264 /* NamespaceImport */) { addLeafNode(namedBindings); } else { @@ -127114,32 +131350,27 @@ var ts; } } break; - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: addNodeWithRecursiveChild(node, node.name); break; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: var expression = node.expression; // Use the expression as the name of the SpreadAssignment, otherwise show as . ts.isIdentifier(expression) ? addLeafNode(node, expression) : addLeafNode(node); break; - case 198 /* BindingElement */: - case 288 /* PropertyAssignment */: - case 249 /* VariableDeclaration */: - var _e = node, name = _e.name, initializer = _e.initializer; - if (ts.isBindingPattern(name)) { - addChildrenRecursively(name); - } - else if (initializer && isFunctionOrClassExpression(initializer)) { - // Add a node for the VariableDeclaration, but not for the initializer. - startNode(node); - ts.forEachChild(initializer, addChildrenRecursively); - endNode(); + case 199 /* BindingElement */: + case 289 /* PropertyAssignment */: + case 250 /* VariableDeclaration */: { + var child = node; + if (ts.isBindingPattern(child.name)) { + addChildrenRecursively(child.name); } else { - addNodeWithRecursiveChild(node, initializer); + addNodeWithRecursiveInitializer(child); } break; - case 251 /* FunctionDeclaration */: + } + case 252 /* FunctionDeclaration */: var nameNode = node.name; // If we see a function declaration track as a possible ES5 class if (nameNode && ts.isIdentifier(nameNode)) { @@ -127147,34 +131378,34 @@ var ts; } addNodeWithRecursiveChild(node, node.body); break; - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: addNodeWithRecursiveChild(node, node.body); break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: startNode(node); - for (var _f = 0, _g = node.members; _f < _g.length; _f++) { - var member = _g[_f]; + for (var _e = 0, _f = node.members; _e < _f.length; _e++) { + var member = _f[_e]; if (!isComputedProperty(member)) { addLeafNode(member); } } endNode(); break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: startNode(node); - for (var _h = 0, _j = node.members; _h < _j.length; _h++) { - var member = _j[_h]; + for (var _g = 0, _h = node.members; _g < _h.length; _g++) { + var member = _h[_g]; addChildrenRecursively(member); } endNode(); break; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 266 /* ExportAssignment */: { + case 267 /* ExportAssignment */: { var expression_1 = node.expression; var child = ts.isObjectLiteralExpression(expression_1) || ts.isCallExpression(expression_1) ? expression_1 : ts.isArrowFunction(expression_1) || ts.isFunctionExpression(expression_1) ? expression_1.body : undefined; @@ -127188,16 +131419,16 @@ var ts; } break; } - case 270 /* ExportSpecifier */: - case 260 /* ImportEqualsDeclaration */: - case 171 /* IndexSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 254 /* TypeAliasDeclaration */: + case 271 /* ExportSpecifier */: + case 261 /* ImportEqualsDeclaration */: + case 172 /* IndexSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 255 /* TypeAliasDeclaration */: addLeafNode(node); break; - case 203 /* CallExpression */: - case 216 /* BinaryExpression */: { + case 204 /* CallExpression */: + case 217 /* BinaryExpression */: { var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: @@ -127249,7 +131480,7 @@ var ts; defineCall.arguments[0] : defineCall.arguments[0].expression; var memberName = defineCall.arguments[1]; - var _k = startNestedNodes(node, className), depth = _k[0], classNameIdentifier = _k[1]; + var _j = startNestedNodes(node, className), depth = _j[0], classNameIdentifier = _j[1]; startNode(node, classNameIdentifier); startNode(node, ts.setTextRange(ts.factory.createIdentifier(memberName.text), memberName)); addChildrenRecursively(node.arguments[2]); @@ -127439,13 +131670,14 @@ var ts; return false; } switch (a.kind) { - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return ts.hasSyntacticModifier(a, 32 /* Static */) === ts.hasSyntacticModifier(b, 32 /* Static */); - case 256 /* ModuleDeclaration */: - return areSameModule(a, b); + case 257 /* ModuleDeclaration */: + return areSameModule(a, b) + && getFullyQualifiedModuleName(a) === getFullyQualifiedModuleName(b); default: return true; } @@ -127462,8 +131694,7 @@ var ts; // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { - // TODO: GH#18217 - return a.body.kind === b.body.kind && (a.body.kind !== 256 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); + return a.body.kind === b.body.kind && (a.body.kind !== 257 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); } /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { @@ -127493,7 +131724,7 @@ var ts; * So `new()` can still come before an `aardvark` method. */ function tryGetName(node) { - if (node.kind === 256 /* ModuleDeclaration */) { + if (node.kind === 257 /* ModuleDeclaration */) { return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); @@ -127502,16 +131733,16 @@ var ts; return propertyName && ts.unescapeLeadingUnderscores(propertyName); } switch (node.kind) { - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 221 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 222 /* ClassExpression */: return getFunctionOrClassName(node); default: return undefined; } } function getItemName(node, name) { - if (node.kind === 256 /* ModuleDeclaration */) { + if (node.kind === 257 /* ModuleDeclaration */) { return cleanText(getModuleName(node)); } if (name) { @@ -127523,18 +131754,18 @@ var ts; } } switch (node.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: var sourceFile = node; return ts.isExternalModule(sourceFile) ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" : ""; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return ts.isExportAssignment(node) && node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; - case 209 /* ArrowFunction */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: if (ts.getSyntacticModifierFlags(node) & 512 /* Default */) { return "default"; } @@ -127542,13 +131773,13 @@ var ts; // (eg: "app\n.onactivated"), so we should remove the whitespace for readability in the // navigation bar. return getFunctionOrClassName(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return "constructor"; - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: return "new()"; - case 169 /* CallSignature */: + case 170 /* CallSignature */: return "()"; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: return "[]"; default: return ""; @@ -127581,19 +131812,19 @@ var ts; } // Some nodes are otherwise important enough to always include in the primary navigation menu. switch (navigationBarNodeKind(item)) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 255 /* EnumDeclaration */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 297 /* SourceFile */: - case 254 /* TypeAliasDeclaration */: - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 256 /* EnumDeclaration */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 298 /* SourceFile */: + case 255 /* TypeAliasDeclaration */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: return true; - case 209 /* ArrowFunction */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; @@ -127603,10 +131834,10 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 257 /* ModuleBlock */: - case 297 /* SourceFile */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: + case 258 /* ModuleBlock */: + case 298 /* SourceFile */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: return true; default: return false; @@ -127663,9 +131894,12 @@ var ts; if (ts.isAmbientModule(moduleDeclaration)) { return ts.getTextOfNode(moduleDeclaration.name); } + return getFullyQualifiedModuleName(moduleDeclaration); + } + function getFullyQualifiedModuleName(moduleDeclaration) { // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = [ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)]; - while (moduleDeclaration.body && moduleDeclaration.body.kind === 256 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 257 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } @@ -127679,13 +131913,13 @@ var ts; return decl.body && ts.isModuleDeclaration(decl.body) ? getInteriorModule(decl.body) : decl; } function isComputedProperty(member) { - return !member.name || member.name.kind === 158 /* ComputedPropertyName */; + return !member.name || member.name.kind === 159 /* ComputedPropertyName */; } function getNodeSpan(node) { - return node.kind === 297 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); + return node.kind === 298 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); } function getModifiers(node) { - if (node.parent && node.parent.kind === 249 /* VariableDeclaration */) { + if (node.parent && node.parent.kind === 250 /* VariableDeclaration */) { node = node.parent; } return ts.getNodeModifiers(node); @@ -127743,9 +131977,9 @@ var ts; } function isFunctionOrClassExpression(node) { switch (node.kind) { - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: - case 221 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 222 /* ClassExpression */: return true; default: return false; @@ -127774,9 +132008,9 @@ var ts; * 2) Coalescing imports from the same module * 3) Sorting imports */ - function organizeImports(sourceFile, formatContext, host, program, preferences) { + function organizeImports(sourceFile, formatContext, host, program, preferences, skipDestructiveCodeActions) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext, preferences: preferences }); - var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; + var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program, skipDestructiveCodeActions)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; // All of the old ImportDeclarations in the file, in syntactic order. var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports); @@ -127811,26 +132045,35 @@ var ts; ? coalesce(importGroup) : importGroup; }); - // Delete or replace the first import. + // Delete all nodes if there are no imports. if (newImportDecls.length === 0) { - changeTracker.delete(sourceFile, oldImportDecls[0]); + // Consider the first node to have trailingTrivia as we want to exclude the + // "header" comment. + changeTracker.deleteNodes(sourceFile, oldImportDecls, { + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, + }, /*hasTrailingComment*/ true); } else { // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. - changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { + var replaceOptions = { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), - }); - } - // Delete any subsequent imports. - for (var i = 1; i < oldImportDecls.length; i++) { - changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + }; + changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, replaceOptions); + var hasTrailingComment = changeTracker.nodeHasTrailingComment(sourceFile, oldImportDecls[0], replaceOptions); + changeTracker.deleteNodes(sourceFile, oldImportDecls.slice(1), { + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, + }, hasTrailingComment); } } } OrganizeImports.organizeImports = organizeImports; - function removeUnusedImports(oldImports, sourceFile, program) { + function removeUnusedImports(oldImports, sourceFile, program, skipDestructiveCodeActions) { + // As a precaution, consider unused import detection to be destructive (GH #43051) + if (skipDestructiveCodeActions) { + return oldImports; + } var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); var jsxFragmentFactory = typeChecker.getJsxFragmentFactory(sourceFile); @@ -128101,11 +132344,11 @@ var ts; function getModuleSpecifierExpression(declaration) { var _a; switch (declaration.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return (_a = ts.tryCast(declaration.moduleReference, ts.isExternalModuleReference)) === null || _a === void 0 ? void 0 : _a.expression; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return declaration.moduleSpecifier; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return declaration.declarationList.declarations[0].initializer.arguments[0]; } } @@ -128144,19 +132387,19 @@ var ts; function getImportKindOrder(s1) { var _a; switch (s1.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: if (!s1.importClause) return 0; if (s1.importClause.isTypeOnly) return 1; - if (((_a = s1.importClause.namedBindings) === null || _a === void 0 ? void 0 : _a.kind) === 263 /* NamespaceImport */) + if (((_a = s1.importClause.namedBindings) === null || _a === void 0 ? void 0 : _a.kind) === 264 /* NamespaceImport */) return 2; if (s1.importClause.name) return 3; return 4; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return 5; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return 6; } } @@ -128312,7 +132555,7 @@ var ts; } function getOutliningSpanForNode(n, sourceFile) { switch (n.kind) { - case 230 /* Block */: + case 231 /* Block */: if (ts.isFunctionLike(n.parent)) { return functionSpan(n.parent, n, sourceFile); } @@ -128320,16 +132563,16 @@ var ts; // If the latter, we want to collapse the block, but consider its hint span // to be the entire span of the parent. switch (n.parent.kind) { - case 235 /* DoStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 237 /* ForStatement */: - case 234 /* IfStatement */: - case 236 /* WhileStatement */: - case 243 /* WithStatement */: - case 287 /* CatchClause */: + case 236 /* DoStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 238 /* ForStatement */: + case 235 /* IfStatement */: + case 237 /* WhileStatement */: + case 244 /* WithStatement */: + case 288 /* CatchClause */: return spanForNode(n.parent); - case 247 /* TryStatement */: + case 248 /* TryStatement */: // Could be the try-block, or the finally-block. var tryStatement = n.parent; if (tryStatement.tryBlock === n) { @@ -128346,40 +132589,40 @@ var ts; // the span of the block, independent of any parent span. return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */); } - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return spanForNode(n.parent); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 258 /* CaseBlock */: - case 177 /* TypeLiteral */: - case 196 /* ObjectBindingPattern */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 259 /* CaseBlock */: + case 178 /* TypeLiteral */: + case 197 /* ObjectBindingPattern */: return spanForNode(n); - case 179 /* TupleType */: + case 180 /* TupleType */: return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !ts.isTupleTypeNode(n.parent), 22 /* OpenBracketToken */); - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: return spanForNodeArray(n.statements); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return spanForObjectOrArrayLiteral(n); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return spanForObjectOrArrayLiteral(n, 22 /* OpenBracketToken */); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return spanForJSXElement(n); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return spanForJSXFragment(n); - case 274 /* JsxSelfClosingElement */: - case 275 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: return spanForJSXAttributes(n.attributes); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: case 14 /* NoSubstitutionTemplateLiteral */: return spanForTemplateLiteral(n); - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !ts.isBindingElement(n.parent), 22 /* OpenBracketToken */); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return spanForArrowFunction(n); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return spanForCallExpression(n); } function spanForCallExpression(node) { @@ -128446,7 +132689,7 @@ var ts; function functionSpan(node, body, sourceFile) { var openToken = tryGetFunctionOpenToken(node, body, sourceFile); var closeToken = ts.findChildOfKind(body, 19 /* CloseBraceToken */, sourceFile); - return openToken && closeToken && spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ node.kind !== 209 /* ArrowFunction */); + return openToken && closeToken && spanBetweenTokens(openToken, closeToken, node, sourceFile, /*autoCollapse*/ node.kind !== 210 /* ArrowFunction */); } function spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse, useFullStart) { if (autoCollapse === void 0) { autoCollapse = false; } @@ -128749,15 +132992,15 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_6 = function (start) { + var _loop_7 = 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_1 = _loop_6(start); - if (typeof state_1 === "object") - return state_1.value; + var state_2 = _loop_7(start); + if (typeof state_2 === "object") + return state_2.value; } return -1; } @@ -129309,7 +133552,7 @@ var ts; function getRenameInfo(program, sourceFile, position, options) { var node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position)); if (nodeIsEligibleForRename(node)) { - var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }, options); + var renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, options); if (renameInfo) { return renameInfo; } @@ -129317,7 +133560,7 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); } Rename.getRenameInfo = getRenameInfo; - function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile, options) { + function getRenameInfoForNode(node, typeChecker, sourceFile, program, options) { var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) { if (ts.isStringLiteralLike(node)) { @@ -129337,7 +133580,7 @@ var ts; if (!declarations || declarations.length === 0) return; // Disallow rename for elements that are defined in the standard TypeScript library. - if (declarations.some(isDefinedInLibraryFile)) { + if (declarations.some(function (declaration) { return isDefinedInLibraryFile(program, declaration); })) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } // Cannot rename `default` as in `import { default as foo } from "./someModule"; @@ -129348,18 +133591,22 @@ var ts; return options && options.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 158 /* ComputedPropertyName */) + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 159 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) : undefined; var displayName = specifierName || typeChecker.symbolToString(symbol); var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(typeChecker, symbol), node, sourceFile); } + function isDefinedInLibraryFile(program, declaration) { + var sourceFile = declaration.getSourceFile(); + return program.isSourceFileDefaultLibrary(sourceFile) && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */); + } function getRenameInfoForModule(node, sourceFile, moduleSymbol) { if (!ts.isExternalModuleNameRelative(node.text)) { return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); } - var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var moduleSourceFile = moduleSymbol.declarations && ts.find(moduleSymbol.declarations, ts.isSourceFile); if (!moduleSourceFile) return undefined; var withoutIndex = ts.endsWith(node.text, "/index") || ts.endsWith(node.text, "/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); @@ -129440,6 +133687,10 @@ var ts; if (ts.getTokenPosOfNode(node, sourceFile, /*includeJsDoc*/ true) > pos) { break outer; } + var comment = ts.singleOrUndefined(ts.getTrailingCommentRanges(sourceFile.text, node.end)); + if (comment && comment.kind === 2 /* SingleLineCommentTrivia */) { + pushSelectionCommentRange(comment.pos, comment.end); + } if (positionShouldSnapToNode(sourceFile, pos, node)) { // 1. Blocks are effectively redundant with SyntaxLists. // 2. TemplateSpans, along with the SyntaxLists containing them, are a somewhat unintuitive grouping @@ -129502,6 +133753,14 @@ var ts; } } } + function pushSelectionCommentRange(start, end) { + pushSelectionRange(start, end); + var pos = start; + while (sourceFile.text.charCodeAt(pos) === 47 /* slash */) { + pos++; + } + pushSelectionRange(pos, end); + } } SmartSelectionRange.getSmartSelectionRange = getSmartSelectionRange; /** @@ -129565,7 +133824,7 @@ var ts; var groupedWithBrackets = groupChildren(groupedWithPlusMinusTokens, function (_a) { var kind = _a.kind; return kind === 22 /* OpenBracketToken */ || - kind === 159 /* TypeParameter */ || + kind === 160 /* TypeParameter */ || kind === 23 /* CloseBracketToken */; }); return [ @@ -129679,22 +133938,22 @@ var ts; return kind === 18 /* OpenBraceToken */ || kind === 22 /* OpenBracketToken */ || kind === 20 /* OpenParenToken */ - || kind === 275 /* JsxOpeningElement */; + || kind === 276 /* JsxOpeningElement */; } function isListCloser(token) { var kind = token && token.kind; return kind === 19 /* CloseBraceToken */ || kind === 23 /* CloseBracketToken */ || kind === 21 /* CloseParenToken */ - || kind === 276 /* JsxClosingElement */; + || kind === 277 /* JsxClosingElement */; } function getEndPos(sourceFile, node) { switch (node.kind) { - case 326 /* JSDocParameterTag */: - case 324 /* JSDocCallbackTag */: - case 333 /* JSDocPropertyTag */: - case 331 /* JSDocTypedefTag */: - case 328 /* JSDocThisTag */: + case 330 /* JSDocParameterTag */: + case 328 /* JSDocCallbackTag */: + case 337 /* JSDocPropertyTag */: + case 335 /* JSDocTypedefTag */: + case 332 /* JSDocThisTag */: return sourceFile.getLineEndOfPosition(node.getStart()); default: return node.getEnd(); @@ -129904,10 +134163,10 @@ var ts; } return undefined; } - else if (ts.isTemplateHead(node) && parent.parent.kind === 205 /* TaggedTemplateExpression */) { + else if (ts.isTemplateHead(node) && parent.parent.kind === 206 /* TaggedTemplateExpression */) { var templateExpression = parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 218 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 219 /* TemplateExpression */); var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } @@ -129976,17 +134235,17 @@ var ts; return undefined; var parent = startingToken.parent; switch (parent.kind) { - case 207 /* ParenthesizedExpression */: - case 165 /* MethodDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 208 /* ParenthesizedExpression */: + case 166 /* MethodDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: var info = getArgumentOrParameterListInfo(startingToken, sourceFile); if (!info) return undefined; var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; var contextualType = ts.isMethodDeclaration(parent) ? checker.getContextualTypeForObjectLiteralElement(parent) : checker.getContextualType(parent); return contextualType && { contextualType: contextualType, argumentIndex: argumentIndex, argumentCount: argumentCount, argumentsSpan: argumentsSpan }; - case 216 /* BinaryExpression */: { + case 217 /* BinaryExpression */: { var highestBinary = getHighestBinary(parent); var contextualType_1 = checker.getContextualType(highestBinary); var argumentIndex_1 = startingToken.kind === 20 /* OpenParenToken */ ? 0 : countBinaryExpressionParameters(parent) - 1; @@ -130110,7 +134369,7 @@ var ts; // | | // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. - if (template.kind === 218 /* TemplateExpression */) { + if (template.kind === 219 /* TemplateExpression */) { var lastSpan = ts.last(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -130119,7 +134378,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { - var _loop_7 = function (n) { + var _loop_8 = 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.formatSyntaxKind(n.kind) + ", parent: " + ts.Debug.formatSyntaxKind(n.parent.kind); }); @@ -130129,9 +134388,9 @@ var ts; } }; for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) { - var state_2 = _loop_7(n); - if (typeof state_2 === "object") - return state_2.value; + var state_3 = _loop_8(n); + if (typeof state_3 === "object") + return state_3.value; } return undefined; } @@ -130181,7 +134440,19 @@ var ts; itemsSeen += item.length; } 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: ts.flatMapToMutable(items, ts.identity), applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var help = { items: ts.flatMapToMutable(items, ts.identity), applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; + var selected = help.items[selectedItemIndex]; + if (selected.isVariadic) { + var firstRest = ts.findIndex(selected.parameters, function (p) { return !!p.isRest; }); + if (-1 < firstRest && firstRest < selected.parameters.length - 1) { + // We don't have any code to get this correct; instead, don't highlight a current parameter AT ALL + help.argumentIndex = selected.parameters.length; + } + else { + help.argumentIndex = Math.min(help.argumentIndex, selected.parameters.length - 1); + } + } + return help; } function createTypeHelpItems(symbol, _a, sourceFile, checker) { var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; @@ -130196,7 +134467,7 @@ var ts; 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 tags = symbol.getJsDocTags(checker); var prefixDisplayParts = __spreadArray(__spreadArray([], typeSymbolDisplay), [ts.punctuationPart(29 /* LessThanToken */)]); return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(31 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; } @@ -130263,14 +134534,15 @@ var ts; printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); var isOptional = checker.isOptionalParameter(parameter.valueDeclaration); - return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional }; + var isRest = !!(parameter.checkFlags & 32768 /* RestParameter */); + return { name: parameter.name, documentation: parameter.getDocumentationComment(checker), displayParts: displayParts, isOptional: isOptional, isRest: isRest }; } function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { var displayParts = ts.mapToDisplayParts(function (writer) { var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false, isRest: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -130480,7 +134752,7 @@ var ts; diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); } } - if (ts.isFunctionLikeDeclaration(node)) { + if (canBeConvertedToAsync(node)) { addConvertToAsyncFunctionDiagnostics(node, checker, diags); } node.forEachChild(check); @@ -130491,11 +134763,11 @@ var ts; function containsTopLevelCommonjs(sourceFile) { return sourceFile.statements.some(function (statement) { switch (statement.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); }); - case 233 /* ExpressionStatement */: { + case 234 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); @@ -130512,12 +134784,12 @@ var ts; } function importNameForConvertToDefaultImport(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; - return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 263 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 264 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) ? importClause.namedBindings.name : undefined; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return node.name; default: return undefined; @@ -130533,35 +134805,35 @@ var ts; return !ts.isAsyncFunction(node) && node.body && ts.isBlock(node.body) && - hasReturnStatementWithPromiseHandler(node.body) && + hasReturnStatementWithPromiseHandler(node.body, checker) && returnsPromise(node, checker); } function returnsPromise(node, checker) { - var functionType = checker.getTypeAtLocation(node); - var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); - var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; + var signature = checker.getSignatureFromDeclaration(node); + var returnType = signature ? checker.getReturnTypeOfSignature(signature) : undefined; return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); } + ts.returnsPromise = returnsPromise; function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } - function hasReturnStatementWithPromiseHandler(body) { - return !!ts.forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); + function hasReturnStatementWithPromiseHandler(body, checker) { + return !!ts.forEachReturnStatement(body, function (statement) { return isReturnStatementWithFixablePromiseHandler(statement, checker); }); } - function isReturnStatementWithFixablePromiseHandler(node) { - return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); + function isReturnStatementWithFixablePromiseHandler(node, checker) { + return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression, checker); } ts.isReturnStatementWithFixablePromiseHandler = isReturnStatementWithFixablePromiseHandler; // Should be kept up to date with transformExpression in convertToAsyncFunction.ts - function isFixablePromiseHandler(node) { + function isFixablePromiseHandler(node, checker) { // ensure outermost call exists and is a promise handler - if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + if (!isPromiseHandler(node) || !node.arguments.every(function (arg) { return isFixablePromiseArgument(arg, checker); })) { 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)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(function (arg) { return isFixablePromiseArgument(arg, checker); })) { return false; } currentNode = currentNode.expression; @@ -130584,16 +134856,24 @@ var ts; }); } // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts - function isFixablePromiseArgument(arg) { + function isFixablePromiseArgument(arg, checker) { switch (arg.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true); // falls through case 103 /* NullKeyword */: - case 78 /* Identifier */: // identifier includes undefined return true; + case 78 /* Identifier */: + case 202 /* PropertyAccessExpression */: { + var symbol = checker.getSymbolAtLocation(arg); + if (!symbol) { + return false; + } + return checker.isUndefinedSymbol(symbol) || + ts.some(ts.skipAlias(symbol, checker).declarations, function (d) { return ts.isFunctionLike(d) || ts.hasInitializer(d) && !!d.initializer && ts.isFunctionLike(d.initializer); }); + } default: return false; } @@ -130603,18 +134883,30 @@ var ts; } function canBeConvertedToClass(node, checker) { var _a, _b, _c, _d; - if (node.kind === 208 /* FunctionExpression */) { + if (node.kind === 209 /* FunctionExpression */) { if (ts.isVariableDeclaration(node.parent) && ((_a = node.symbol.members) === null || _a === void 0 ? void 0 : _a.size)) { return true; } var symbol = checker.getSymbolOfExpando(node, /*allowDeclaration*/ false); return !!(symbol && (((_b = symbol.exports) === null || _b === void 0 ? void 0 : _b.size) || ((_c = symbol.members) === null || _c === void 0 ? void 0 : _c.size))); } - if (node.kind === 251 /* FunctionDeclaration */) { + if (node.kind === 252 /* FunctionDeclaration */) { return !!((_d = node.symbol.members) === null || _d === void 0 ? void 0 : _d.size); } return false; } + function canBeConvertedToAsync(node) { + switch (node.kind) { + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + return true; + default: + return false; + } + } + ts.canBeConvertedToAsync = canBeConvertedToAsync; })(ts || (ts = {})); /* @internal */ var ts; @@ -130630,7 +134922,7 @@ var ts; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32 /* Class */) { - return ts.getDeclarationOfKind(symbol, 221 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 222 /* ClassExpression */) ? "local class" /* localClassElement */ : "class" /* classElement */; } if (flags & 384 /* Enum */) @@ -130714,11 +135006,11 @@ var ts; // If we requested completions after `x.` at the top-level, we may be at a source file location. switch (location.parent && location.parent.kind) { // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. - case 275 /* JsxOpeningElement */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: return location.kind === 78 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return "JSX attribute" /* jsxAttribute */; default: return "property" /* memberVariableElement */; @@ -130764,6 +135056,7 @@ var ts; SymbolDisplay.getSymbolModifiers = getSymbolModifiers; // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) { + var _a; if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } var displayParts = []; var documentation = []; @@ -130787,8 +135080,8 @@ var ts; symbolKind = "property" /* memberVariableElement */; } var signature = void 0; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (location.parent && location.parent.kind === 201 /* PropertyAccessExpression */) { + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (location.parent && location.parent.kind === 202 /* PropertyAccessExpression */) { var right = location.parent.name; // Either the location is on the right of a property access, or on the left and the right is missing if (right === location || (right && right.getFullWidth() === 0)) { @@ -130808,9 +135101,9 @@ var ts; } if (callExpressionLike) { signature = typeChecker.getResolvedSignature(callExpressionLike); // TODO: GH#18217 - var useConstructSignatures = callExpressionLike.kind === 204 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 105 /* SuperKeyword */); + var useConstructSignatures = callExpressionLike.kind === 205 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 105 /* SuperKeyword */); var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); - if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { + if (signature && !ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { // Get the first signature if there is one -- allSignatures may contain // either the original signature or its target, so check for either signature = allSignatures.length ? allSignatures[0] : undefined; @@ -130872,7 +135165,7 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration - (location.kind === 132 /* ConstructorKeyword */ && location.parent.kind === 166 /* Constructor */)) { // At constructor keyword of constructor declaration + (location.kind === 132 /* ConstructorKeyword */ && location.parent.kind === 167 /* Constructor */)) { // At constructor keyword of constructor declaration // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; // Use function declaration to write the signatures only if the symbol corresponding to this declaration @@ -130880,24 +135173,26 @@ var ts; return declaration === (location.kind === 132 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { - var allSignatures = functionDeclaration_1.kind === 166 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration_1.kind === 167 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217 } else { signature = allSignatures[0]; } - if (functionDeclaration_1.kind === 166 /* Constructor */) { + if (functionDeclaration_1.kind === 167 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 169 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 170 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } - addSignatureDisplayParts(signature, allSignatures); + if (signature) { + addSignatureDisplayParts(signature, allSignatures); + } hasAddedSymbolInfo = true; hasMultipleSignatures = allSignatures.length > 1; } @@ -130905,7 +135200,7 @@ var ts; } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { addAliasPrefixIfNecessary(); - if (ts.getDeclarationOfKind(symbol, 221 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 222 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) // (local class) class @@ -130949,7 +135244,7 @@ var ts; } if (symbolFlags & 1536 /* Module */ && !isThisExpression) { prefixNextMeaning(); - var declaration = ts.getDeclarationOfKind(symbol, 256 /* ModuleDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 257 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 78 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 140 /* NamespaceKeyword */ : 139 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); @@ -130970,7 +135265,7 @@ var ts; } else { // Method/function type parameter - var decl = ts.getDeclarationOfKind(symbol, 159 /* TypeParameter */); + var decl = ts.getDeclarationOfKind(symbol, 160 /* TypeParameter */); if (decl === undefined) return ts.Debug.fail(); var declaration = decl.parent; @@ -130978,16 +135273,16 @@ var ts; if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217 - if (declaration.kind === 170 /* ConstructSignature */) { + if (declaration.kind === 171 /* ConstructSignature */) { displayParts.push(ts.keywordPart(102 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 169 /* CallSignature */ && declaration.name) { + else if (declaration.kind !== 170 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } - else if (declaration.kind === 254 /* TypeAliasDeclaration */) { + else if (declaration.kind === 255 /* TypeAliasDeclaration */) { // Type alias type parameter // For example // type list = T[]; // Both T will go through same code path @@ -131003,8 +135298,8 @@ var ts; if (symbolFlags & 8 /* EnumMember */) { symbolKind = "enum member" /* enumMemberElement */; addPrefixForAnyFunctionOrVar(symbol, "enum member"); - var declaration = symbol.declarations[0]; - if (declaration.kind === 291 /* EnumMember */) { + var declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]; + if ((declaration === null || declaration === void 0 ? void 0 : declaration.kind) === 292 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -131034,31 +135329,33 @@ var ts; } else { documentationFromAlias = resolvedSymbol.getContextualDocumentationComment(resolvedNode, typeChecker); - tagsFromAlias = resolvedSymbol.getJsDocTags(); + tagsFromAlias = resolvedSymbol.getJsDocTags(typeChecker); } } } - switch (symbol.declarations[0].kind) { - case 259 /* NamespaceExportDeclaration */: - displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(140 /* NamespaceKeyword */)); - break; - case 266 /* ExportAssignment */: - displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); - displayParts.push(ts.spacePart()); - displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 62 /* EqualsToken */ : 87 /* DefaultKeyword */)); - break; - case 270 /* ExportSpecifier */: - displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); - break; - default: - displayParts.push(ts.keywordPart(99 /* ImportKeyword */)); + if (symbol.declarations) { + switch (symbol.declarations[0].kind) { + case 260 /* NamespaceExportDeclaration */: + displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(140 /* NamespaceKeyword */)); + break; + case 267 /* ExportAssignment */: + displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 62 /* EqualsToken */ : 87 /* DefaultKeyword */)); + break; + case 271 /* ExportSpecifier */: + displayParts.push(ts.keywordPart(92 /* ExportKeyword */)); + break; + default: + displayParts.push(ts.keywordPart(99 /* ImportKeyword */)); + } } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 260 /* ImportEqualsDeclaration */) { + if (declaration.kind === 261 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); @@ -131145,10 +135442,10 @@ var ts; // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 297 /* SourceFile */; })) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 216 /* BinaryExpression */) { + if (symbol.parent && symbol.declarations && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 298 /* SourceFile */; })) { + for (var _i = 0, _b = symbol.declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (!declaration.parent || declaration.parent.kind !== 217 /* BinaryExpression */) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); @@ -131156,7 +135453,7 @@ var ts; continue; } documentation = rhsSymbol.getDocumentationComment(typeChecker); - tags = rhsSymbol.getJsDocTags(); + tags = rhsSymbol.getJsDocTags(typeChecker); if (documentation.length > 0) { break; } @@ -131164,7 +135461,7 @@ var ts; } } if (tags.length === 0 && !hasMultipleSignatures) { - tags = symbol.getJsDocTags(); + tags = symbol.getJsDocTags(typeChecker); } if (documentation.length === 0 && documentationFromAlias) { documentation = documentationFromAlias; @@ -131266,16 +135563,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 208 /* FunctionExpression */) { + if (declaration.kind === 209 /* FunctionExpression */) { return true; } - if (declaration.kind !== 249 /* VariableDeclaration */ && declaration.kind !== 251 /* FunctionDeclaration */) { + if (declaration.kind !== 250 /* VariableDeclaration */ && declaration.kind !== 252 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { // Reached source file or module block - if (parent.kind === 297 /* SourceFile */ || parent.kind === 257 /* ModuleBlock */) { + if (parent.kind === 298 /* SourceFile */ || parent.kind === 258 /* ModuleBlock */) { return false; } } @@ -131381,7 +135678,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_8 = function (opt) { + var _loop_9 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -131400,7 +135697,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_8(opt); + _loop_9(opt); } return options; } @@ -131576,10 +135873,10 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 280 /* JsxAttribute */: - case 275 /* JsxOpeningElement */: - case 276 /* JsxClosingElement */: - case 274 /* JsxSelfClosingElement */: + case 281 /* JsxAttribute */: + case 276 /* JsxOpeningElement */: + case 277 /* JsxClosingElement */: + case 275 /* JsxSelfClosingElement */: // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. return ts.isKeyword(node.kind) || node.kind === 78 /* Identifier */; } @@ -131587,14 +135884,7 @@ var ts; return false; } function shouldRescanJsxText(node) { - var isJSXText = ts.isJsxText(node); - if (isJSXText) { - var containingElement = ts.findAncestor(node.parent, function (p) { return ts.isJsxElement(p); }); - if (!containingElement) - return false; // should never happen - return !ts.isParenthesizedExpression(containingElement.parent); - } - return false; + return ts.isJsxText(node); } function shouldRescanSlashToken(container) { return container.kind === 13 /* RegularExpressionLiteral */; @@ -131691,7 +135981,7 @@ var ts; return scanner.scanJsxIdentifier(); case 5 /* RescanJsxText */: lastScanAction = 5 /* RescanJsxText */; - return scanner.reScanJsxToken(); + return scanner.reScanJsxToken(/* allowMultilineJsxText */ false); case 6 /* RescanJsxAttributeValue */: lastScanAction = 6 /* RescanJsxAttributeValue */; return scanner.reScanJsxAttributeValue(); @@ -131780,7 +136070,7 @@ var ts; (function (formatting) { function getAllRules() { var allTokens = []; - for (var token = 0 /* FirstToken */; token <= 156 /* LastToken */; token++) { + for (var token = 0 /* FirstToken */; token <= 157 /* LastToken */; token++) { if (token !== 1 /* EndOfFileToken */) { allTokens.push(token); } @@ -131795,9 +136085,9 @@ var ts; var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(__spreadArray(__spreadArray([], allTokens), [3 /* MultiLineCommentTrivia */])); var anyTokenIncludingEOF = tokenRangeFrom(__spreadArray(__spreadArray([], allTokens), [1 /* EndOfFileToken */])); - var keywords = tokenRangeFromRange(80 /* FirstKeyword */, 156 /* LastKeyword */); + var keywords = tokenRangeFromRange(80 /* FirstKeyword */, 157 /* LastKeyword */); var binaryOperators = tokenRangeFromRange(29 /* FirstBinaryOperator */, 77 /* LastBinaryOperator */); - var binaryKeywordOperators = [100 /* InKeyword */, 101 /* InstanceOfKeyword */, 156 /* OfKeyword */, 126 /* AsKeyword */, 137 /* IsKeyword */]; + var binaryKeywordOperators = [100 /* InKeyword */, 101 /* InstanceOfKeyword */, 157 /* OfKeyword */, 126 /* AsKeyword */, 137 /* IsKeyword */]; var unaryPrefixOperators = [45 /* PlusPlusToken */, 46 /* MinusMinusToken */, 54 /* TildeToken */, 53 /* ExclamationToken */]; var unaryPrefixExpressions = [ 8 /* NumericLiteral */, 9 /* BigIntLiteral */, 78 /* Identifier */, 20 /* OpenParenToken */, @@ -132108,51 +136398,51 @@ var ts; return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; } function isForContext(context) { - return context.contextNode.kind === 237 /* ForStatement */; + return context.contextNode.kind === 238 /* ForStatement */; } function isNotForContext(context) { return !isForContext(context); } function isBinaryOpContext(context) { switch (context.contextNode.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return context.contextNode.operatorToken.kind !== 27 /* CommaToken */; - case 217 /* ConditionalExpression */: - case 184 /* ConditionalType */: - case 224 /* AsExpression */: - case 270 /* ExportSpecifier */: - case 265 /* ImportSpecifier */: - case 172 /* TypePredicate */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 218 /* ConditionalExpression */: + case 185 /* ConditionalType */: + case 225 /* AsExpression */: + case 271 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 173 /* TypePredicate */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 198 /* BindingElement */: + case 199 /* BindingElement */: // equals in type X = ... // falls through - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: // equal in import a = module('a'); // falls through - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // equal in let a = 0 // falls through - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: // equal in p = 0 // falls through - case 160 /* Parameter */: - case 291 /* EnumMember */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 161 /* Parameter */: + case 292 /* EnumMember */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return context.currentTokenSpan.kind === 62 /* EqualsToken */ || context.nextTokenSpan.kind === 62 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: // "in" keyword in [P in keyof T]: T[P] // falls through - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return context.currentTokenSpan.kind === 100 /* InKeyword */ || context.nextTokenSpan.kind === 100 /* InKeyword */ || context.currentTokenSpan.kind === 62 /* EqualsToken */ || context.nextTokenSpan.kind === 62 /* EqualsToken */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 239 /* ForOfStatement */: - return context.currentTokenSpan.kind === 156 /* OfKeyword */ || context.nextTokenSpan.kind === 156 /* OfKeyword */; + case 240 /* ForOfStatement */: + return context.currentTokenSpan.kind === 157 /* OfKeyword */ || context.nextTokenSpan.kind === 157 /* OfKeyword */; } return false; } @@ -132164,22 +136454,22 @@ var ts; } function isTypeAnnotationContext(context) { var contextKind = context.contextNode.kind; - return contextKind === 163 /* PropertyDeclaration */ || - contextKind === 162 /* PropertySignature */ || - contextKind === 160 /* Parameter */ || - contextKind === 249 /* VariableDeclaration */ || + return contextKind === 164 /* PropertyDeclaration */ || + contextKind === 163 /* PropertySignature */ || + contextKind === 161 /* Parameter */ || + contextKind === 250 /* VariableDeclaration */ || ts.isFunctionLikeKind(contextKind); } function isConditionalOperatorContext(context) { - return context.contextNode.kind === 217 /* ConditionalExpression */ || - context.contextNode.kind === 184 /* ConditionalType */; + return context.contextNode.kind === 218 /* ConditionalExpression */ || + context.contextNode.kind === 185 /* ConditionalType */; } function isSameLineTokenOrBeforeBlockContext(context) { return context.TokensAreOnSameLine() || isBeforeBlockContext(context); } function isBraceWrappedContext(context) { - return context.contextNode.kind === 196 /* ObjectBindingPattern */ || - context.contextNode.kind === 190 /* MappedType */ || + return context.contextNode.kind === 197 /* ObjectBindingPattern */ || + context.contextNode.kind === 191 /* MappedType */ || isSingleLineBlockContext(context); } // This check is done before an open brace in a control construct, a function, or a typescript block declaration @@ -132205,34 +136495,34 @@ var ts; return true; } switch (node.kind) { - case 230 /* Block */: - case 258 /* CaseBlock */: - case 200 /* ObjectLiteralExpression */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 259 /* CaseBlock */: + case 201 /* ObjectLiteralExpression */: + case 258 /* ModuleBlock */: return true; } return false; } function isFunctionDeclContext(context) { switch (context.contextNode.kind) { - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: // case SyntaxKind.MemberFunctionDeclaration: // falls through - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // case SyntaxKind.MethodSignature: // falls through - case 169 /* CallSignature */: - case 208 /* FunctionExpression */: - case 166 /* Constructor */: - case 209 /* ArrowFunction */: + case 170 /* CallSignature */: + case 209 /* FunctionExpression */: + case 167 /* Constructor */: + case 210 /* ArrowFunction */: // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: // falls through - case 253 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one + case 254 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one return true; } return false; @@ -132241,40 +136531,40 @@ var ts; return !isFunctionDeclContext(context); } function isFunctionDeclarationOrFunctionExpressionContext(context) { - return context.contextNode.kind === 251 /* FunctionDeclaration */ || context.contextNode.kind === 208 /* FunctionExpression */; + return context.contextNode.kind === 252 /* FunctionDeclaration */ || context.contextNode.kind === 209 /* FunctionExpression */; } function isTypeScriptDeclWithBlockContext(context) { return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); } function nodeIsTypeScriptDeclWithBlockContext(node) { switch (node.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 177 /* TypeLiteral */: - case 256 /* ModuleDeclaration */: - case 267 /* ExportDeclaration */: - case 268 /* NamedExports */: - case 261 /* ImportDeclaration */: - case 264 /* NamedImports */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 178 /* TypeLiteral */: + case 257 /* ModuleDeclaration */: + case 268 /* ExportDeclaration */: + case 269 /* NamedExports */: + case 262 /* ImportDeclaration */: + case 265 /* NamedImports */: return true; } return false; } function isAfterCodeBlockContext(context) { switch (context.currentTokenParent.kind) { - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 287 /* CatchClause */: - case 257 /* ModuleBlock */: - case 244 /* SwitchStatement */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 288 /* CatchClause */: + case 258 /* ModuleBlock */: + case 245 /* SwitchStatement */: return true; - case 230 /* Block */: { + case 231 /* Block */: { var blockParent = context.currentTokenParent.parent; // In a codefix scenario, we can't rely on parents being set. So just always return true. - if (!blockParent || blockParent.kind !== 209 /* ArrowFunction */ && blockParent.kind !== 208 /* FunctionExpression */) { + if (!blockParent || blockParent.kind !== 210 /* ArrowFunction */ && blockParent.kind !== 209 /* FunctionExpression */) { return true; } } @@ -132283,32 +136573,32 @@ var ts; } function isControlDeclContext(context) { switch (context.contextNode.kind) { - case 234 /* IfStatement */: - case 244 /* SwitchStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 236 /* WhileStatement */: - case 247 /* TryStatement */: - case 235 /* DoStatement */: - case 243 /* WithStatement */: + case 235 /* IfStatement */: + case 245 /* SwitchStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 237 /* WhileStatement */: + case 248 /* TryStatement */: + case 236 /* DoStatement */: + case 244 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: // falls through - case 287 /* CatchClause */: + case 288 /* CatchClause */: return true; default: return false; } } function isObjectContext(context) { - return context.contextNode.kind === 200 /* ObjectLiteralExpression */; + return context.contextNode.kind === 201 /* ObjectLiteralExpression */; } function isFunctionCallContext(context) { - return context.contextNode.kind === 203 /* CallExpression */; + return context.contextNode.kind === 204 /* CallExpression */; } function isNewContext(context) { - return context.contextNode.kind === 204 /* NewExpression */; + return context.contextNode.kind === 205 /* NewExpression */; } function isFunctionCallOrNewContext(context) { return isFunctionCallContext(context) || isNewContext(context); @@ -132323,10 +136613,10 @@ var ts; return context.nextTokenSpan.kind !== 21 /* CloseParenToken */; } function isArrowFunctionContext(context) { - return context.contextNode.kind === 209 /* ArrowFunction */; + return context.contextNode.kind === 210 /* ArrowFunction */; } function isImportTypeContext(context) { - return context.contextNode.kind === 195 /* ImportType */; + return context.contextNode.kind === 196 /* ImportType */; } function isNonJsxSameLineTokenContext(context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 11 /* JsxText */; @@ -132335,19 +136625,19 @@ var ts; return context.contextNode.kind !== 11 /* JsxText */; } function isNonJsxElementOrFragmentContext(context) { - return context.contextNode.kind !== 273 /* JsxElement */ && context.contextNode.kind !== 277 /* JsxFragment */; + return context.contextNode.kind !== 274 /* JsxElement */ && context.contextNode.kind !== 278 /* JsxFragment */; } function isJsxExpressionContext(context) { - return context.contextNode.kind === 283 /* JsxExpression */ || context.contextNode.kind === 282 /* JsxSpreadAttribute */; + return context.contextNode.kind === 284 /* JsxExpression */ || context.contextNode.kind === 283 /* JsxSpreadAttribute */; } function isNextTokenParentJsxAttribute(context) { - return context.nextTokenParent.kind === 280 /* JsxAttribute */; + return context.nextTokenParent.kind === 281 /* JsxAttribute */; } function isJsxAttributeContext(context) { - return context.contextNode.kind === 280 /* JsxAttribute */; + return context.contextNode.kind === 281 /* JsxAttribute */; } function isJsxSelfClosingElementContext(context) { - return context.contextNode.kind === 274 /* JsxSelfClosingElement */; + return context.contextNode.kind === 275 /* JsxSelfClosingElement */; } function isNotBeforeBlockInFunctionDeclarationContext(context) { return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); @@ -132362,45 +136652,45 @@ var ts; while (ts.isExpressionNode(node)) { node = node.parent; } - return node.kind === 161 /* Decorator */; + return node.kind === 162 /* Decorator */; } function isStartOfVariableDeclarationList(context) { - return context.currentTokenParent.kind === 250 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 251 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; } function isNotFormatOnEnter(context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */; } function isModuleDeclContext(context) { - return context.contextNode.kind === 256 /* ModuleDeclaration */; + return context.contextNode.kind === 257 /* ModuleDeclaration */; } function isObjectTypeContext(context) { - return context.contextNode.kind === 177 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === 178 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; } function isConstructorSignatureContext(context) { - return context.contextNode.kind === 170 /* ConstructSignature */; + return context.contextNode.kind === 171 /* ConstructSignature */; } function isTypeArgumentOrParameterOrAssertion(token, parent) { if (token.kind !== 29 /* LessThanToken */ && token.kind !== 31 /* GreaterThanToken */) { return false; } switch (parent.kind) { - case 173 /* TypeReference */: - case 206 /* TypeAssertionExpression */: - case 254 /* TypeAliasDeclaration */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 223 /* ExpressionWithTypeArguments */: + case 174 /* TypeReference */: + case 207 /* TypeAssertionExpression */: + case 255 /* TypeAliasDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 224 /* ExpressionWithTypeArguments */: return true; default: return false; @@ -132411,28 +136701,28 @@ var ts; isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); } function isTypeAssertionContext(context) { - return context.contextNode.kind === 206 /* TypeAssertionExpression */; + return context.contextNode.kind === 207 /* TypeAssertionExpression */; } function isVoidOpContext(context) { - return context.currentTokenSpan.kind === 113 /* VoidKeyword */ && context.currentTokenParent.kind === 212 /* VoidExpression */; + return context.currentTokenSpan.kind === 113 /* VoidKeyword */ && context.currentTokenParent.kind === 213 /* VoidExpression */; } function isYieldOrYieldStarWithOperand(context) { - return context.contextNode.kind === 219 /* YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 220 /* YieldExpression */ && context.contextNode.expression !== undefined; } function isNonNullAssertionContext(context) { - return context.contextNode.kind === 225 /* NonNullExpression */; + return context.contextNode.kind === 226 /* NonNullExpression */; } function isNotStatementConditionContext(context) { return !isStatementConditionContext(context); } function isStatementConditionContext(context) { switch (context.contextNode.kind) { - case 234 /* IfStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 235 /* IfStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return true; default: return false; @@ -132457,12 +136747,12 @@ var ts; return nextTokenKind === 19 /* CloseBraceToken */ || nextTokenKind === 1 /* EndOfFileToken */; } - if (nextTokenKind === 229 /* SemicolonClassElement */ || + if (nextTokenKind === 230 /* SemicolonClassElement */ || nextTokenKind === 26 /* SemicolonToken */) { return false; } - if (context.contextNode.kind === 253 /* InterfaceDeclaration */ || - context.contextNode.kind === 254 /* TypeAliasDeclaration */) { + if (context.contextNode.kind === 254 /* InterfaceDeclaration */ || + context.contextNode.kind === 255 /* TypeAliasDeclaration */) { // Can’t remove semicolon after `foo`; it would parse as a method declaration: // // interface I { @@ -132476,9 +136766,9 @@ var ts; if (ts.isPropertyDeclaration(context.currentTokenParent)) { return !context.currentTokenParent.initializer; } - return context.currentTokenParent.kind !== 237 /* ForStatement */ - && context.currentTokenParent.kind !== 231 /* EmptyStatement */ - && context.currentTokenParent.kind !== 229 /* SemicolonClassElement */ + return context.currentTokenParent.kind !== 238 /* ForStatement */ + && context.currentTokenParent.kind !== 232 /* EmptyStatement */ + && context.currentTokenParent.kind !== 230 /* SemicolonClassElement */ && nextTokenKind !== 22 /* OpenBracketToken */ && nextTokenKind !== 20 /* OpenParenToken */ && nextTokenKind !== 39 /* PlusToken */ @@ -132486,7 +136776,7 @@ var ts; && nextTokenKind !== 43 /* SlashToken */ && nextTokenKind !== 13 /* RegularExpressionLiteral */ && nextTokenKind !== 27 /* CommaToken */ - && nextTokenKind !== 218 /* TemplateExpression */ + && nextTokenKind !== 219 /* TemplateExpression */ && nextTokenKind !== 15 /* TemplateHead */ && nextTokenKind !== 14 /* NoSubstitutionTemplateLiteral */ && nextTokenKind !== 24 /* DotToken */; @@ -132577,12 +136867,12 @@ var ts; return map; } function getRuleBucketIndex(row, column) { - ts.Debug.assert(row <= 156 /* LastKeyword */ && column <= 156 /* LastKeyword */, "Must compute formatting context from tokens"); + ts.Debug.assert(row <= 157 /* LastKeyword */ && column <= 157 /* LastKeyword */, "Must compute formatting context from tokens"); return (row * mapRowLength) + column; } var maskBitSize = 5; var mask = 31; // MaskBitSize bits - var mapRowLength = 156 /* LastToken */ + 1; + var mapRowLength = 157 /* LastToken */ + 1; var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["StopRulesSpecific"] = 0] = "StopRulesSpecific"; @@ -132770,17 +137060,17 @@ var ts; // i.e. parent is class declaration with the list of members and node is one of members. function isListElement(parent, node) { switch (parent.kind) { - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var body = parent.body; - return !!body && body.kind === 257 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); - case 297 /* SourceFile */: - case 230 /* Block */: - case 257 /* ModuleBlock */: + return !!body && body.kind === 258 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 298 /* SourceFile */: + case 231 /* Block */: + case 258 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -132934,14 +137224,17 @@ var ts; processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); } if (!formattingScanner.isOnToken()) { + var indentation = formatting.SmartIndenter.nodeWillIndentChild(options, enclosingNode, /*child*/ undefined, sourceFile, /*indentByDefault*/ false) + ? initialIndentation + options.indentSize + : initialIndentation; var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); - if (options.trimTrailingWhitespace !== false) { - trimTrailingWhitespacesForRemainingRange(); - } + indentTriviaItems(leadingTrivia, indentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); } } + if (options.trimTrailingWhitespace !== false) { + trimTrailingWhitespacesForRemainingRange(); + } return edits; // local functions /** Tries to compute the indentation for a list element. @@ -132988,10 +137281,9 @@ var ts; // - we need to get the indentation on last line and the delta of parent return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; } - else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; - } - else if (formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) { + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile) || + formatting.SmartIndenter.childIsUnindentedBranchOfConditionalExpression(parent, node, startLine, sourceFile) || + formatting.SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)) { return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; } else { @@ -133007,19 +137299,19 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 252 /* ClassDeclaration */: return 83 /* ClassKeyword */; - case 253 /* InterfaceDeclaration */: return 117 /* InterfaceKeyword */; - case 251 /* FunctionDeclaration */: return 97 /* FunctionKeyword */; - case 255 /* EnumDeclaration */: return 255 /* EnumDeclaration */; - case 167 /* GetAccessor */: return 134 /* GetKeyword */; - case 168 /* SetAccessor */: return 146 /* SetKeyword */; - case 165 /* MethodDeclaration */: + case 253 /* ClassDeclaration */: return 83 /* ClassKeyword */; + case 254 /* InterfaceDeclaration */: return 117 /* InterfaceKeyword */; + case 252 /* FunctionDeclaration */: return 97 /* FunctionKeyword */; + case 256 /* EnumDeclaration */: return 256 /* EnumDeclaration */; + case 168 /* GetAccessor */: return 134 /* GetKeyword */; + case 169 /* SetAccessor */: return 146 /* SetKeyword */; + case 166 /* MethodDeclaration */: if (node.asteriskToken) { return 41 /* AsteriskToken */; } // falls through - case 163 /* PropertyDeclaration */: - case 160 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 161 /* Parameter */: var name = ts.getNameOfDeclaration(node); if (name) { return name.kind; @@ -133076,15 +137368,16 @@ var ts; case 43 /* SlashToken */: case 31 /* GreaterThanToken */: switch (container.kind) { - case 275 /* JsxOpeningElement */: - case 276 /* JsxClosingElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 277 /* JsxClosingElement */: + case 275 /* JsxSelfClosingElement */: + case 224 /* ExpressionWithTypeArguments */: return false; } break; case 22 /* OpenBracketToken */: case 23 /* CloseBracketToken */: - if (container.kind !== 190 /* MappedType */) { + if (container.kind !== 191 /* MappedType */) { return false; } break; @@ -133129,11 +137422,6 @@ var ts; if (tokenInfo.token.end > node.end) { break; } - if (node.kind === 11 /* JsxText */) { - // Intentation rules for jsx text are handled by `indentMultilineCommentOrJsxText` inside `processChildNode`; just fastforward past it here - formattingScanner.advance(); - continue; - } consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node); } if (!node.parent && formattingScanner.isOnEOF()) { @@ -133192,27 +137480,11 @@ var ts; return inheritedIndentation; } } - var effectiveParentStartLine = child.kind === 161 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 162 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); - if (child.kind === 11 /* JsxText */) { - var range = { pos: child.getStart(), end: child.getEnd() }; - if (range.pos !== range.end) { // don't indent zero-width jsx text - var siblings = parent.getChildren(sourceFile); - var currentIndex = ts.findIndex(siblings, function (arg) { return arg.pos === child.pos; }); - var previousNode = siblings[currentIndex - 1]; - if (previousNode) { - // The jsx text needs no indentation whatsoever if it ends on the same line the previous sibling ends on - if (sourceFile.getLineAndCharacterOfPosition(range.end).line !== sourceFile.getLineAndCharacterOfPosition(previousNode.end).line) { - // The first line is (already) "indented" if the text starts on the same line as the previous sibling element ends on - var firstLineIsIndented = sourceFile.getLineAndCharacterOfPosition(range.pos).line === sourceFile.getLineAndCharacterOfPosition(previousNode.end).line; - indentMultilineCommentOrJsxText(range, childIndentation.indentation, firstLineIsIndented, /*indentFinalLine*/ false, /*jsxStyle*/ true); - } - } - } - } childContextNode = node; - if (isFirstListItem && parent.kind === 199 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + if (isFirstListItem && parent.kind === 200 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -133336,7 +137608,7 @@ var ts; switch (triviaItem.kind) { case 3 /* MultiLineCommentTrivia */: if (triviaInRange) { - indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); + indentMultilineComment(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); } indentNextTokenOrTrivia = false; break; @@ -133453,7 +137725,7 @@ var ts; function indentationIsDifferent(indentationString, startLinePosition) { return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length); } - function indentMultilineCommentOrJsxText(commentRange, indentation, firstLineIsIndented, indentFinalLine, jsxTextStyleIndent) { + function indentMultilineComment(commentRange, indentation, firstLineIsIndented, indentFinalLine) { if (indentFinalLine === void 0) { indentFinalLine = true; } // split comment in lines var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; @@ -133491,13 +137763,6 @@ var ts; var nonWhitespaceCharacterAndColumn = i === 0 ? nonWhitespaceColumnInFirstPart : formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options); - if (jsxTextStyleIndent) { - // skip adding indentation to blank lines - if (ts.isLineBreak(sourceFile.text.charCodeAt(ts.getStartPositionOfLine(startLine, sourceFile)))) - continue; - // reset delta on every line - delta = indentation - nonWhitespaceCharacterAndColumn.column; - } var newIndentation = nonWhitespaceCharacterAndColumn.column + delta; if (newIndentation > 0) { var indentationString = getIndentationString(newIndentation, options); @@ -133652,12 +137917,12 @@ var ts; formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { - case 166 /* Constructor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 209 /* ArrowFunction */: + case 167 /* Constructor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 210 /* ArrowFunction */: if (node.typeParameters === list) { return 29 /* LessThanToken */; } @@ -133665,8 +137930,8 @@ var ts; return 20 /* OpenParenToken */; } break; - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: if (node.typeArguments === list) { return 29 /* LessThanToken */; } @@ -133674,12 +137939,12 @@ var ts; return 20 /* OpenParenToken */; } break; - case 173 /* TypeReference */: + case 174 /* TypeReference */: if (node.typeArguments === list) { return 29 /* LessThanToken */; } break; - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return 18 /* OpenBraceToken */; } return 0 /* Unknown */; @@ -133797,7 +138062,7 @@ var ts; if (options.indentStyle === ts.IndentStyle.Block) { return getBlockIndent(sourceFile, position, options); } - if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 216 /* BinaryExpression */) { + if (precedingToken.kind === 27 /* CommaToken */ && precedingToken.parent.kind !== 217 /* BinaryExpression */) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { @@ -133880,6 +138145,7 @@ var ts; } SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, isNextChild, options) { + var _a; var parent = current.parent; // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if // * parent and child nodes start on the same line, or @@ -133895,7 +138161,25 @@ var ts; childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { // check if current node is a list item - if yes, take indentation from it - var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, !parentAndChildShareLine); + var firstListChild = (_a = getContainingList(current, sourceFile)) === null || _a === void 0 ? void 0 : _a[0]; + // A list indents its children if the children begin on a later line than the list itself: + // + // f1( L0 - List start + // { L1 - First child start: indented, along with all other children + // prop: 0 + // }, + // { + // prop: 1 + // } + // ) + // + // f2({ L0 - List start and first child start: children are not indented. + // prop: 0 Object properties are indented only one level, because the list + // }, { itself contributes nothing. + // prop: 1 L3 - The indentation of the second object literal is best understood by + // }) looking at the relationship between the list and *first* list item. + var listIndentsChild = !!firstListChild && getStartLineAndCharacterForNode(firstListChild, sourceFile).line > containingListOrParentStart.line; + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options, listIndentsChild); if (actualIndentation !== -1 /* Unknown */) { return actualIndentation + indentationDelta; } @@ -133951,7 +138235,7 @@ var ts; // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && - (parent.kind === 297 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 298 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -133999,7 +138283,7 @@ var ts; } SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 234 /* IfStatement */ && parent.elseStatement === child) { + if (parent.kind === 235 /* IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 90 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -134008,6 +138292,49 @@ var ts; return false; } SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement; + // A multiline conditional typically increases the indentation of its whenTrue and whenFalse children: + // + // condition + // ? whenTrue + // : whenFalse; + // + // However, that indentation does not apply if the subexpressions themselves span multiple lines, + // applying their own indentation: + // + // (() => { + // return complexCalculationForCondition(); + // })() ? { + // whenTrue: 'multiline object literal' + // } : ( + // whenFalse('multiline parenthesized expression') + // ); + // + // In these cases, we must discard the indentation increase that would otherwise be applied to the + // whenTrue and whenFalse children to avoid double-indenting their contents. To identify this scenario, + // we check for the whenTrue branch beginning on the line that the condition ends, and the whenFalse + // branch beginning on the line that the whenTrue branch ends. + function childIsUnindentedBranchOfConditionalExpression(parent, child, childStartLine, sourceFile) { + if (ts.isConditionalExpression(parent) && (child === parent.whenTrue || child === parent.whenFalse)) { + var conditionEndLine = ts.getLineAndCharacterOfPosition(sourceFile, parent.condition.end).line; + if (child === parent.whenTrue) { + return childStartLine === conditionEndLine; + } + else { + // On the whenFalse side, we have to look at the whenTrue side, because if that one was + // indented, whenFalse must also be indented: + // + // const y = true + // ? 1 : ( L1: whenTrue indented because it's on a new line + // 0 L2: indented two stops, one because whenTrue was indented + // ); and one because of the parentheses spanning multiple lines + var trueStartLine = getStartLineAndCharacterForNode(parent.whenTrue, sourceFile).line; + var trueEndLine = ts.getLineAndCharacterOfPosition(sourceFile, parent.whenTrue.end).line; + return conditionEndLine === trueStartLine && trueEndLine === childStartLine; + } + } + return false; + } + SmartIndenter.childIsUnindentedBranchOfConditionalExpression = childIsUnindentedBranchOfConditionalExpression; function argumentStartsOnSameLineAsPreviousArgument(parent, child, childStartLine, sourceFile) { if (ts.isCallOrNewExpression(parent)) { if (!parent.arguments) @@ -134037,40 +138364,40 @@ var ts; } function getListByRange(start, end, node, sourceFile) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return getList(node.typeArguments); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return getList(node.properties); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return getList(node.elements); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return getList(node.members); - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 166 /* Constructor */: - case 175 /* ConstructorType */: - case 170 /* ConstructSignature */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 167 /* Constructor */: + case 176 /* ConstructorType */: + case 171 /* ConstructSignature */: return getList(node.typeParameters) || getList(node.parameters); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 330 /* JSDocTemplateTag */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 334 /* JSDocTemplateTag */: return getList(node.typeParameters); - case 204 /* NewExpression */: - case 203 /* CallExpression */: + case 205 /* NewExpression */: + case 204 /* CallExpression */: return getList(node.typeArguments) || getList(node.arguments); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return getList(node.declarations); - case 264 /* NamedImports */: - case 268 /* NamedExports */: + case 265 /* NamedImports */: + case 269 /* NamedExports */: return getList(node.elements); - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: return getList(node.elements); } function getList(list) { @@ -134093,7 +138420,7 @@ var ts; return findColumnForFirstNonWhitespaceCharacterInLine(sourceFile.getLineAndCharacterOfPosition(list.pos), sourceFile, options); } function getActualIndentationForListItem(node, sourceFile, options, listIndentsChild) { - if (node.parent && node.parent.kind === 250 /* VariableDeclarationList */) { + if (node.parent && node.parent.kind === 251 /* VariableDeclarationList */) { // VariableDeclarationList has no wrapping tokens return -1 /* Unknown */; } @@ -134166,94 +138493,94 @@ var ts; function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { var childKind = child ? child.kind : 0 /* Unknown */; switch (parent.kind) { - case 233 /* ExpressionStatement */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 199 /* ArrayLiteralExpression */: - case 230 /* Block */: - case 257 /* ModuleBlock */: - case 200 /* ObjectLiteralExpression */: - case 177 /* TypeLiteral */: - case 190 /* MappedType */: - case 179 /* TupleType */: - case 258 /* CaseBlock */: - case 285 /* DefaultClause */: - case 284 /* CaseClause */: - case 207 /* ParenthesizedExpression */: - case 201 /* PropertyAccessExpression */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 232 /* VariableStatement */: - case 266 /* ExportAssignment */: - case 242 /* ReturnStatement */: - case 217 /* ConditionalExpression */: - case 197 /* ArrayBindingPattern */: - case 196 /* ObjectBindingPattern */: - case 275 /* JsxOpeningElement */: - case 278 /* JsxOpeningFragment */: - case 274 /* JsxSelfClosingElement */: - case 283 /* JsxExpression */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 160 /* Parameter */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 186 /* ParenthesizedType */: - case 205 /* TaggedTemplateExpression */: - case 213 /* AwaitExpression */: - case 268 /* NamedExports */: - case 264 /* NamedImports */: - case 270 /* ExportSpecifier */: - case 265 /* ImportSpecifier */: - case 163 /* PropertyDeclaration */: + case 234 /* ExpressionStatement */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 200 /* ArrayLiteralExpression */: + case 231 /* Block */: + case 258 /* ModuleBlock */: + case 201 /* ObjectLiteralExpression */: + case 178 /* TypeLiteral */: + case 191 /* MappedType */: + case 180 /* TupleType */: + case 259 /* CaseBlock */: + case 286 /* DefaultClause */: + case 285 /* CaseClause */: + case 208 /* ParenthesizedExpression */: + case 202 /* PropertyAccessExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 233 /* VariableStatement */: + case 267 /* ExportAssignment */: + case 243 /* ReturnStatement */: + case 218 /* ConditionalExpression */: + case 198 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 276 /* JsxOpeningElement */: + case 279 /* JsxOpeningFragment */: + case 275 /* JsxSelfClosingElement */: + case 284 /* JsxExpression */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 161 /* Parameter */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 187 /* ParenthesizedType */: + case 206 /* TaggedTemplateExpression */: + case 214 /* AwaitExpression */: + case 269 /* NamedExports */: + case 265 /* NamedImports */: + case 271 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 164 /* PropertyDeclaration */: return true; - case 249 /* VariableDeclaration */: - case 288 /* PropertyAssignment */: - case 216 /* BinaryExpression */: - if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 200 /* ObjectLiteralExpression */) { // TODO: GH#18217 + case 250 /* VariableDeclaration */: + case 289 /* PropertyAssignment */: + case 217 /* BinaryExpression */: + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 201 /* ObjectLiteralExpression */) { // TODO: GH#18217 return rangeIsOnOneLine(sourceFile, child); } - if (parent.kind !== 216 /* BinaryExpression */) { + if (parent.kind !== 217 /* BinaryExpression */) { return true; } break; - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 237 /* ForStatement */: - case 234 /* IfStatement */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - return childKind !== 230 /* Block */; - case 209 /* ArrowFunction */: - if (sourceFile && childKind === 207 /* ParenthesizedExpression */) { + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 238 /* ForStatement */: + case 235 /* IfStatement */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return childKind !== 231 /* Block */; + case 210 /* ArrowFunction */: + if (sourceFile && childKind === 208 /* ParenthesizedExpression */) { return rangeIsOnOneLine(sourceFile, child); } - return childKind !== 230 /* Block */; - case 267 /* ExportDeclaration */: - return childKind !== 268 /* NamedExports */; - case 261 /* ImportDeclaration */: - return childKind !== 262 /* ImportClause */ || - (!!child.namedBindings && child.namedBindings.kind !== 264 /* NamedImports */); - case 273 /* JsxElement */: - return childKind !== 276 /* JsxClosingElement */; - case 277 /* JsxFragment */: - return childKind !== 279 /* JsxClosingFragment */; - case 183 /* IntersectionType */: - case 182 /* UnionType */: - if (childKind === 177 /* TypeLiteral */ || childKind === 179 /* TupleType */) { + return childKind !== 231 /* Block */; + case 268 /* ExportDeclaration */: + return childKind !== 269 /* NamedExports */; + case 262 /* ImportDeclaration */: + return childKind !== 263 /* ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 265 /* NamedImports */); + case 274 /* JsxElement */: + return childKind !== 277 /* JsxClosingElement */; + case 278 /* JsxFragment */: + return childKind !== 280 /* JsxClosingFragment */; + case 184 /* IntersectionType */: + case 183 /* UnionType */: + if (childKind === 178 /* TypeLiteral */ || childKind === 180 /* TupleType */) { return false; } - // falls through + break; } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -134261,11 +138588,11 @@ var ts; SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; function isControlFlowEndingStatement(kind, parent) { switch (kind) { - case 242 /* ReturnStatement */: - case 246 /* ThrowStatement */: - case 240 /* ContinueStatement */: - case 241 /* BreakStatement */: - return parent.kind !== 230 /* Block */; + case 243 /* ReturnStatement */: + case 247 /* ThrowStatement */: + case 241 /* ContinueStatement */: + case 242 /* BreakStatement */: + return parent.kind !== 231 /* Block */; default: return false; } @@ -134373,7 +138700,9 @@ var ts; function getAdjustedRange(sourceFile, startNode, endNode, options) { return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) }; } - function getAdjustedStartPosition(sourceFile, node, options) { + function getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment) { + var _a, _b; + if (hasTrailingComment === void 0) { hasTrailingComment = false; } var leadingTriviaOption = options.leadingTriviaOption; if (leadingTriviaOption === LeadingTriviaOption.Exclude) { return node.getStart(sourceFile); @@ -134404,6 +138733,15 @@ var ts; // when b is deleted - we delete it return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start; } + // if node has a trailing comments, use comment end position as the text has already been included. + if (hasTrailingComment) { + // Check first for leading comments as if the node is the first import, we want to exclude the trivia; + // otherwise we get the trailing comments. + var comment = ((_a = ts.getLeadingCommentRanges(sourceFile.text, fullStart)) === null || _a === void 0 ? void 0 : _a[0]) || ((_b = ts.getTrailingCommentRanges(sourceFile.text, fullStart)) === null || _b === void 0 ? void 0 : _b[0]); + if (comment) { + return ts.skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + } + } // get start position of the line following the line that contains fullstart position // (but only if the fullstart isn't the very beginning of the file) var nextLineStart = fullStart > 0 ? 1 : 0; @@ -134412,6 +138750,35 @@ var ts; adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } + /** Return the end position of a multiline comment of it is on another line; otherwise returns `undefined`; */ + function getEndPositionOfMultilineTrailingComment(sourceFile, node, options) { + var end = node.end; + var trailingTriviaOption = options.trailingTriviaOption; + if (trailingTriviaOption === TrailingTriviaOption.Include) { + // If the trailing comment is a multiline comment that extends to the next lines, + // return the end of the comment and track it for the next nodes to adjust. + var comments = ts.getTrailingCommentRanges(sourceFile.text, end); + if (comments) { + var nodeEndLine = ts.getLineOfLocalPosition(sourceFile, node.end); + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + // Single line can break the loop as trivia will only be this line. + // Comments on subsequest lines are also ignored. + if (comment.kind === 2 /* SingleLineCommentTrivia */ || ts.getLineOfLocalPosition(sourceFile, comment.pos) > nodeEndLine) { + break; + } + // Get the end line of the comment and compare against the end line of the node. + // If the comment end line position and the multiline comment extends to multiple lines, + // then is safe to return the end position. + var commentEndLine = ts.getLineOfLocalPosition(sourceFile, comment.end); + if (commentEndLine > nodeEndLine) { + return ts.skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + } + } + } + } + return undefined; + } function getAdjustedEndPosition(sourceFile, node, options) { var _a; var end = node.end; @@ -134427,6 +138794,10 @@ var ts; } return end; } + var multilineEndPosition = getEndPositionOfMultilineTrailingComment(sourceFile, node, options); + if (multilineEndPosition) { + return multilineEndPosition; + } var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))) ? newEnd @@ -134436,14 +138807,7 @@ var ts; * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ function isSeparator(node, candidate) { - return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 200 /* ObjectLiteralExpression */)); - } - function spaces(count) { - var s = ""; - for (var i = 0; i < count; i++) { - s += " "; - } - return s; + return !!candidate && !!node.parent && (candidate.kind === 27 /* CommaToken */ || (candidate.kind === 26 /* SemicolonToken */ && node.parent.kind === 201 /* ObjectLiteralExpression */)); } function isThisTypeAnnotatable(containingFunction) { return ts.isFunctionExpression(containingFunction) || ts.isFunctionDeclaration(containingFunction); @@ -134489,6 +138853,17 @@ var ts; if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options)); }; + ChangeTracker.prototype.deleteNodes = function (sourceFile, nodes, options, hasTrailingComment) { + if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } + // When deleting multiple nodes we need to track if the end position is including multiline trailing comments. + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var pos = getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment); + var end = getAdjustedEndPosition(sourceFile, node, options); + this.deleteRange(sourceFile, { pos: pos, end: end }); + hasTrailingComment = !!getEndPositionOfMultilineTrailingComment(sourceFile, node, options); + } + }; ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); }; @@ -134531,6 +138906,10 @@ var ts; if (options === void 0) { options = useNonAdjustedPositions; } this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; + ChangeTracker.prototype.nodeHasTrailingComment = function (sourceFile, oldNode, configurableEnd) { + if (configurableEnd === void 0) { configurableEnd = useNonAdjustedPositions; } + return !!getEndPositionOfMultilineTrailingComment(sourceFile, oldNode, configurableEnd); + }; ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { var next = ts.findNextToken(node, node.parent, sourceFile); return next && next.kind === 27 /* CommaToken */ ? next : undefined; @@ -134635,7 +139014,7 @@ var ts; } } else { - endNode = (_a = (node.kind === 249 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken)) !== null && _a !== void 0 ? _a : node.name; + endNode = (_a = (node.kind === 250 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken)) !== null && _a !== void 0 ? _a : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); return true; @@ -134677,6 +139056,15 @@ var ts; this.insertNodeBefore(sourceFile, firstStatement, newStatement); } }; + ChangeTracker.prototype.insertNodeAtConstructorStartAfterSuperCall = function (sourceFile, ctr, newStatement) { + var superCallStatement = ts.find(ctr.body.statements, function (stmt) { return ts.isExpressionStatement(stmt) && ts.isSuperCall(stmt.expression); }); + if (!superCallStatement || !ctr.body.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, __spreadArray(__spreadArray([], ctr.body.statements), [newStatement])); + } + else { + this.insertNodeAfter(sourceFile, superCallStatement, newStatement); + } + }; ChangeTracker.prototype.insertNodeAtConstructorEnd = function (sourceFile, ctr, newStatement) { var lastStatement = ts.lastOrUndefined(ctr.body.statements); if (!lastStatement || !ctr.body.multiLine) { @@ -134792,18 +139180,18 @@ var ts; }; ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { switch (node.kind) { - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: case 10 /* StringLiteral */: case 78 /* Identifier */: return { prefix: ", " }; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return { suffix: "," + this.newLineCharacter }; case 92 /* ExportKeyword */: return { prefix: " " }; - case 160 /* Parameter */: + case 161 /* Parameter */: return {}; default: ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it @@ -134812,7 +139200,7 @@ var ts; }; ChangeTracker.prototype.insertName = function (sourceFile, node, name) { ts.Debug.assert(!node.name); - if (node.kind === 209 /* ArrowFunction */) { + if (node.kind === 210 /* ArrowFunction */) { var arrow = ts.findChildOfKind(node, 38 /* EqualsGreaterThanToken */, sourceFile); var lparen = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile); if (lparen) { @@ -134826,14 +139214,14 @@ var ts; // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)` this.replaceRange(sourceFile, arrow, ts.factory.createToken(21 /* CloseParenToken */)); } - if (node.body.kind !== 230 /* Block */) { + if (node.body.kind !== 231 /* Block */) { // `() => 0` => `function f() { return 0; }` this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.factory.createToken(18 /* OpenBraceToken */), ts.factory.createToken(104 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); this.insertNodesAt(sourceFile, node.body.end, [ts.factory.createToken(26 /* SemicolonToken */), ts.factory.createToken(19 /* CloseBraceToken */)], { joiner: " " }); } } else { - var pos = ts.findChildOfKind(node, node.kind === 208 /* FunctionExpression */ ? 97 /* FunctionKeyword */ : 83 /* ClassKeyword */, sourceFile).end; + var pos = ts.findChildOfKind(node, node.kind === 209 /* FunctionExpression */ ? 97 /* FunctionKeyword */ : 83 /* ClassKeyword */, sourceFile).end; this.insertNodeAt(sourceFile, pos, ts.factory.createIdentifier(name), { prefix: " " }); } }; @@ -134865,47 +139253,22 @@ var ts; // a, b, c // create change for adding 'e' after 'a' as // - find start of next element after a (it is b) - // - use this start as start and end position in final change - // - build text of change by formatting the text of node + separator + whitespace trivia of b + // - use next element start as start and end position in final change + // - build text of change by formatting the text of node + whitespace trivia of b // in multiline case it will work as // a, // b, // c, // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#') - // a,* - // ***insertedtext# + // a, + // insertedtext# // ###b, // c, - // find line and character of the next element - var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart())); - // find line and character of the token that precedes next element (usually it is separator) - var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end); - var prefix = void 0; - var startPos = void 0; - if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) { - // next element is located on the same line with separator: - // a,$$$$b - // ^ ^ - // | |-next element - // |-separator - // where $$$ is some leading trivia - // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces - // a, x,$$$$b - // ^ ^ ^ - // | | |-next element - // | |-new inserted node padded with spaces - // |-separator - startPos = nextToken.end; - prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character); - } - else { - // next element is located on different line that separator - // let insert position be the beginning of the line that contains next element - startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); - } + var nextNode = containingList[index + 1]; + var startPos = skipWhitespacesAndLineBreaks(sourceFile.text, nextNode.getFullStart()); // write separator and leading trivia of the next element as suffix - var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, startPos); + this.insertNodesAt(sourceFile, startPos, [newNode], { suffix: suffix }); } } else { @@ -134977,7 +139340,7 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.Set(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_9 = function (sourceFile, node) { + var _loop_10 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(sourceFile, node)); @@ -134990,7 +139353,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_9(sourceFile, node); + _loop_10(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -135049,14 +139412,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_10 = function (i) { + var _loop_11 = 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_10(i); + _loop_11(i); } var textChanges = ts.mapDefined(normalized, function (c) { var span = ts.createTextSpanFromRange(c.range); @@ -135170,11 +139533,12 @@ var ts; function createWriter(newLine) { var lastNonTriviaPosition = 0; var writer = ts.createTextWriter(newLine); - var onEmitNode = function (hint, node, printCallback) { + var onBeforeEmitNode = function (node) { if (node) { setPos(node, lastNonTriviaPosition); } - printCallback(hint, node); + }; + var onAfterEmitNode = function (node) { if (node) { setEnd(node, lastNonTriviaPosition); } @@ -135293,7 +139657,8 @@ var ts; lastNonTriviaPosition = 0; } return { - onEmitNode: onEmitNode, + onBeforeEmitNode: onBeforeEmitNode, + onAfterEmitNode: onAfterEmitNode, onBeforeEmitNodeArray: onBeforeEmitNodeArray, onAfterEmitNodeArray: onAfterEmitNodeArray, onBeforeEmitToken: onBeforeEmitToken, @@ -135408,14 +139773,14 @@ var ts; } textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment; function needSemicolonBetween(a, b) { - return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 158 /* ComputedPropertyName */ + return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 159 /* ComputedPropertyName */ || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[` } var deleteDeclaration; (function (deleteDeclaration_1) { function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) { switch (node.kind) { - case 160 /* Parameter */: { + case 161 /* Parameter */: { var oldFunction = node.parent; if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1 && @@ -135430,15 +139795,17 @@ var ts; } break; } - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isAnyImportSyntax); // For first import, leave header comment in place, otherwise only delete JSDoc comments - deleteNode(changes, sourceFile, node, { leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); + deleteNode(changes, sourceFile, node, { + leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine, + }); break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: var pattern = node.parent; - var preserveComma = pattern.kind === 197 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); + var preserveComma = pattern.kind === 198 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); if (preserveComma) { deleteNode(changes, sourceFile, node); } @@ -135446,13 +139813,13 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); break; - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); break; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: var namedImports = node.parent; if (namedImports.elements.length === 1) { deleteImportBinding(changes, sourceFile, namedImports); @@ -135461,7 +139828,7 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: deleteImportBinding(changes, sourceFile, node); break; case 26 /* SemicolonToken */: @@ -135470,12 +139837,16 @@ var ts; case 97 /* FunctionKeyword */: deleteNode(changes, sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.Exclude }); break; - case 252 /* ClassDeclaration */: - case 251 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: deleteNode(changes, sourceFile, node, { leadingTriviaOption: ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; default: - if (ts.isImportClause(node.parent) && node.parent.name === node) { + if (!node.parent) { + // a misbehaving client can reach here with the SourceFile node + deleteNode(changes, sourceFile, node); + } + else if (ts.isImportClause(node.parent) && node.parent.name === node) { deleteDefaultImport(changes, sourceFile, node.parent); } else if (ts.isCallExpression(node.parent) && ts.contains(node.parent.arguments, node)) { @@ -135518,13 +139889,13 @@ var ts; // Delete the entire import declaration // |import * as ns from './file'| // |import { a } from './file'| - var importDecl = ts.getAncestor(node, 261 /* ImportDeclaration */); + var importDecl = ts.getAncestor(node, 262 /* ImportDeclaration */); deleteNode(changes, sourceFile, importDecl); } } function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) { var parent = node.parent; - if (parent.kind === 287 /* CatchClause */) { + if (parent.kind === 288 /* CatchClause */) { // TODO: There's currently no unused diagnostic for this, could be a suggestion changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 20 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 21 /* CloseParenToken */, sourceFile)); return; @@ -135535,14 +139906,14 @@ var ts; } var gp = parent.parent; switch (gp.kind) { - case 239 /* ForOfStatement */: - case 238 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 239 /* ForInStatement */: changes.replaceNode(sourceFile, node, ts.factory.createObjectLiteralExpression()); break; - case 237 /* ForStatement */: + case 238 /* ForStatement */: deleteNode(changes, sourceFile, parent); break; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: deleteNode(changes, sourceFile, gp, { leadingTriviaOption: ts.hasJSDocNodes(gp) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; default: @@ -135598,6 +139969,10 @@ var ts; return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); } codefix.createCodeFixAction = createCodeFixAction; + function createCodeFixActionMaybeFixAll(fixName, changes, description, fixId, fixAllDescription, command) { + return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, fixAllDescription && diagnosticToString(fixAllDescription), command); + } + codefix.createCodeFixActionMaybeFixAll = createCodeFixActionMaybeFixAll; function createCodeFixActionWorker(fixName, description, changes, fixId, fixAllDescription, command) { return { fixName: fixName, description: description, changes: changes, fixId: fixId, fixAllDescription: fixAllDescription, commands: command ? [command] : undefined }; } @@ -135736,7 +140111,10 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code], + errorCodes: [ + ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + ], getCodeActions: function (context) { var sourceFile = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { @@ -135849,6 +140227,7 @@ var ts; ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1.code, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap.code, + ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined.code, ts.Diagnostics.Type_0_is_not_an_array_type.code, ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code, ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators.code, @@ -135947,14 +140326,14 @@ var ts; } var isCompleteFix = identifiers.isCompleteFix; var initializers; - var _loop_11 = function (identifier) { + var _loop_12 = function (identifier) { var symbol = checker.getSymbolAtLocation(identifier); if (!symbol) { return "continue"; } var declaration = ts.tryCast(symbol.valueDeclaration, ts.isVariableDeclaration); var variableName = declaration && ts.tryCast(declaration.name, ts.isIdentifier); - var variableStatement = ts.getAncestor(declaration, 232 /* VariableStatement */); + var variableStatement = ts.getAncestor(declaration, 233 /* VariableStatement */); if (!declaration || !variableStatement || declaration.type || !declaration.initializer || @@ -135980,7 +140359,7 @@ var ts; }; for (var _i = 0, _a = identifiers.identifiers; _i < _a.length; _i++) { var identifier = _a[_i]; - _loop_11(identifier); + _loop_12(identifier); } return initializers && { initializers: initializers, @@ -136032,10 +140411,10 @@ var ts; function isInsideAwaitableBody(node) { return node.kind & 32768 /* AwaitContext */ || !!ts.findAncestor(node, function (ancestor) { return ancestor.parent && ts.isArrowFunction(ancestor.parent) && ancestor.parent.body === ancestor || - ts.isBlock(ancestor) && (ancestor.parent.kind === 251 /* FunctionDeclaration */ || - ancestor.parent.kind === 208 /* FunctionExpression */ || - ancestor.parent.kind === 209 /* ArrowFunction */ || - ancestor.parent.kind === 165 /* MethodDeclaration */); + ts.isBlock(ancestor) && (ancestor.parent.kind === 252 /* FunctionDeclaration */ || + ancestor.parent.kind === 209 /* FunctionExpression */ || + ancestor.parent.kind === 210 /* ArrowFunction */ || + ancestor.parent.kind === 166 /* MethodDeclaration */); }); } function makeChange(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) { @@ -136154,10 +140533,10 @@ var ts; function isPossiblyPartOfDestructuring(node) { switch (node.kind) { case 78 /* Identifier */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return true; default: return false; @@ -136172,7 +140551,7 @@ var ts; function isPossiblyPartOfCommaSeperatedInitializer(node) { switch (node.kind) { case 78 /* Identifier */: - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: case 27 /* CommaToken */: return true; default: @@ -136221,7 +140600,7 @@ var ts; return; } var declaration = token.parent; - if (declaration.kind === 163 /* PropertyDeclaration */ && + if (declaration.kind === 164 /* PropertyDeclaration */ && (!fixedNodes || ts.tryAddToSet(fixedNodes, declaration))) { changeTracker.insertModifierBefore(sourceFile, 133 /* DeclareKeyword */, declaration); } @@ -136358,26 +140737,26 @@ var ts; } function isDeclarationWithType(node) { return ts.isFunctionLikeDeclaration(node) || - node.kind === 249 /* VariableDeclaration */ || - node.kind === 162 /* PropertySignature */ || - node.kind === 163 /* PropertyDeclaration */; + node.kind === 250 /* VariableDeclaration */ || + node.kind === 163 /* PropertySignature */ || + node.kind === 164 /* PropertyDeclaration */; } function transformJSDocType(node) { switch (node.kind) { - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: return ts.factory.createTypeReferenceNode("any", ts.emptyArray); - case 307 /* JSDocOptionalType */: + case 308 /* JSDocOptionalType */: return transformJSDocOptionalType(node); - case 306 /* JSDocNonNullableType */: + case 307 /* JSDocNonNullableType */: return transformJSDocType(node.type); - case 305 /* JSDocNullableType */: + case 306 /* JSDocNullableType */: return transformJSDocNullableType(node); - case 309 /* JSDocVariadicType */: + case 310 /* JSDocVariadicType */: return transformJSDocVariadicType(node); - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: return transformJSDocFunctionType(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return transformJSDocTypeReference(node); default: var visited = ts.visitEachChild(node, transformJSDocType, ts.nullTransformationContext); @@ -136402,7 +140781,7 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 309 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 + var isRest = node.type.kind === 310 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 var name = node.name || (isRest ? "rest" : "arg" + index); var dotdotdot = isRest ? ts.factory.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken; return ts.factory.createParameterDeclaration(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); @@ -136473,7 +140852,7 @@ var ts; }); function doChange(changes, sourceFile, position, checker, preferences, compilerOptions) { var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position)); - if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { + if (!ctorSymbol || !ctorSymbol.valueDeclaration || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { // Bad input return undefined; } @@ -136500,7 +140879,7 @@ var ts; // all instance members are stored in the "member" array of symbol if (symbol.members) { symbol.members.forEach(function (member, key) { - if (key === "constructor") { + if (key === "constructor" && member.valueDeclaration) { // fn.prototype.constructor = fn changes.delete(sourceFile, member.valueDeclaration.parent); return; @@ -136514,7 +140893,7 @@ var ts; // all static members are stored in the "exports" array of symbol if (symbol.exports) { symbol.exports.forEach(function (member) { - if (member.name === "prototype") { + if (member.name === "prototype" && member.declarations) { var firstDeclaration = member.declarations[0]; // only one "x.prototype = { ... }" will pass if (member.declarations.length === 1 && @@ -136576,7 +140955,7 @@ var ts; return members; } // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end - var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 233 /* ExpressionStatement */ + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 234 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); if (!assignmentExpr) { @@ -136637,7 +141016,7 @@ var ts; var arrowFunctionBody = arrowFunction.body; var bodyBlock; // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 230 /* Block */) { + if (arrowFunctionBody.kind === 231 /* Block */) { bodyBlock = arrowFunctionBody; } // case 2: () => [1,2,3] @@ -136739,7 +141118,7 @@ var ts; functionToConvert = tokenAtPosition.parent.initializer; } else { - functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.canBeConvertedToAsync); } if (!functionToConvert) { return; @@ -136748,7 +141127,10 @@ var ts; var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap); - var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray; + if (!ts.returnsPromise(functionToConvertRenamed, checker)) { + return; + } + var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : ts.emptyArray; var transformer = { checker: checker, synthNamesMap: synthNamesMap, setOfExpressionsToReturn: setOfExpressionsToReturn, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; @@ -136758,7 +141140,7 @@ var ts; functionToConvert.getStart(sourceFile); var options = functionToConvert.modifiers ? { prefix: " " } : { suffix: " " }; changes.insertModifierAt(sourceFile, pos, 129 /* AsyncKeyword */, options); - var _loop_12 = function (returnStatement) { + var _loop_13 = function (returnStatement) { ts.forEachChild(returnStatement, function visit(node) { if (ts.isCallExpression(node)) { var newNodes = transformExpression(node, transformer); @@ -136771,13 +141153,13 @@ var ts; }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var returnStatement = returnStatements_1[_i]; - _loop_12(returnStatement); + _loop_13(returnStatement); } } - function getReturnStatementsWithPromiseHandlers(body) { + function getReturnStatementsWithPromiseHandlers(body, checker) { var res = []; ts.forEachReturnStatement(body, function (ret) { - if (ts.isReturnStatementWithFixablePromiseHandler(ret)) + if (ts.isReturnStatementWithFixablePromiseHandler(ret, checker)) res.push(ret); }); return res; @@ -136848,7 +141230,10 @@ var ts; // so we push an entry for 'response'. if (lastCallSignature && !ts.isParameter(node.parent) && !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.factory.createUniqueName("result", 16 /* Optimistic */); + var ident = (firstParameter === null || firstParameter === void 0 ? void 0 : firstParameter.valueDeclaration) + && ts.isParameter(firstParameter.valueDeclaration) + && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) + || ts.factory.createUniqueName("result", 16 /* Optimistic */); var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); collidingSymbolMap.add(ident.text, symbol); @@ -137026,6 +141411,7 @@ var ts; case 103 /* NullKeyword */: // do not produce a transformed statement for a null argument break; + case 202 /* PropertyAccessExpression */: case 78 /* Identifier */: // identifier includes undefined if (!argName) { // undefined was argument passed to promise handler @@ -137047,8 +141433,8 @@ var ts; prevArgName.types.push(returnType); } return varDeclOrAssignment; - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: { + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: { var funcBody = func.body; var returnType_1 = (_c = getLastCallSignature(transformer.checker.getTypeAtLocation(func), transformer.checker)) === null || _c === void 0 ? void 0 : _c.getReturnType(); // Arrow functions with block bodies { } will enter this control flow @@ -137059,7 +141445,7 @@ var ts; var statement = _f[_i]; if (ts.isReturnStatement(statement)) { seenReturnStatement = true; - if (ts.isReturnStatementWithFixablePromiseHandler(statement)) { + if (ts.isReturnStatementWithFixablePromiseHandler(statement, transformer.checker)) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } else { @@ -137076,7 +141462,7 @@ var ts; : removeReturns(refactoredStmts, prevArgName, transformer, seenReturnStatement); } else { - var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.factory.createReturnStatement(funcBody)] : ts.emptyArray; + var innerRetStmts = ts.isFixablePromiseHandler(funcBody, transformer.checker) ? [ts.factory.createReturnStatement(funcBody)] : ts.emptyArray; var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { return innerCbBody; @@ -137169,6 +141555,9 @@ var ts; else if (ts.isIdentifier(funcNode)) { name = getMapEntryOrDefault(funcNode); } + else if (ts.isPropertyAccessExpression(funcNode) && ts.isIdentifier(funcNode.name)) { + name = getMapEntryOrDefault(funcNode.name); + } // return undefined argName when arg is null or undefined // eslint-disable-next-line no-in-operator if (!name || "identifier" in name && name.identifier.text === "undefined") { @@ -137264,10 +141653,10 @@ var ts; } var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { changes.replaceNode(importingFile, importNode, ts.factory.createPropertyAccessExpression(ts.getSynthesizedDeepClone(importNode), "default")); } @@ -137334,20 +141723,20 @@ var ts; } function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, useSitesToUnqualify, quotePreference) { switch (statement.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); return false; - case 233 /* ExpressionStatement */: { + case 234 /* ExpressionStatement */: { var expression = statement.expression; switch (expression.kind) { - case 203 /* CallExpression */: { + case 204 /* CallExpression */: { if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); } return false; } - case 216 /* BinaryExpression */: { + case 217 /* BinaryExpression */: { var operatorToken = expression.operatorToken; return operatorToken.kind === 62 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports, useSitesToUnqualify); } @@ -137396,8 +141785,8 @@ var ts; /** Converts `const name = require("moduleSpecifier").propertyName` */ function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { switch (name.kind) { - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: { + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` var tmp = makeUniqueName(propertyName, identifiers); return convertedImports([ @@ -137448,16 +141837,16 @@ var ts; function tryChangeModuleExportsObject(object, useSitesToUnqualify) { var statements = ts.mapAllOrFail(object.properties, function (prop) { switch (prop.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. // falls through - case 289 /* ShorthandPropertyAssignment */: - case 290 /* SpreadAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 291 /* SpreadAssignment */: return undefined; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer, useSitesToUnqualify); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.factory.createToken(92 /* ExportKeyword */)], prop, useSitesToUnqualify); default: ts.Debug.assertNever(prop, "Convert to ES6 got invalid prop kind " + prop.kind); @@ -137521,7 +141910,7 @@ var ts; function convertExportsDotXEquals_replaceNode(name, exported, useSitesToUnqualify) { var modifiers = [ts.factory.createToken(92 /* ExportKeyword */)]; switch (exported.kind) { - case 208 /* FunctionExpression */: { + case 209 /* FunctionExpression */: { var expressionName = exported.name; if (expressionName && expressionName.text !== name) { // `exports.f = function g() {}` -> `export const f = function g() {}` @@ -137529,10 +141918,10 @@ var ts; } } // falls through - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: // `exports.f = function() {}` --> `export function f() {}` return functionExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: // `exports.C = class {}` --> `export class C {}` return classExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify); default: @@ -137552,7 +141941,7 @@ var ts; : ts.getSynthesizedDeepCloneWithReplacements(nodeOrNodes, /*includeTrivia*/ true, replaceNode); function replaceNode(original) { // We are replacing `mod.SomeExport` wih `SomeExport`, so we only need to look at PropertyAccessExpressions - if (original.kind === 201 /* PropertyAccessExpression */) { + if (original.kind === 202 /* PropertyAccessExpression */) { var replacement = useSitesToUnqualify.get(original); // Remove entry from `useSitesToUnqualify` so the refactor knows it's taken care of by the parent statement we're replacing useSitesToUnqualify.delete(original); @@ -137567,7 +141956,7 @@ var ts; */ function convertSingleImport(name, moduleSpecifier, checker, identifiers, target, quotePreference) { switch (name.kind) { - case 196 /* ObjectBindingPattern */: { + case 197 /* ObjectBindingPattern */: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) ? undefined @@ -137580,7 +141969,7 @@ var ts; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration - case 197 /* ArrayBindingPattern */: { + case 198 /* ArrayBindingPattern */: { /* import x from "x"; const [a, b, c] = x; @@ -137599,7 +141988,9 @@ var ts; } /** * Convert `import x = require("x").` - * Also converts uses like `x.y()` to `y()` and uses a named import. + * Also: + * - Convert `x.default()` to `x()` to handle ES6 default export + * - Converts uses like `x.y()` to `y()` and uses a named import. */ function convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference) { var nameSymbol = checker.getSymbolAtLocation(name); @@ -137616,14 +142007,21 @@ var ts; } var parent = use.parent; if (ts.isPropertyAccessExpression(parent)) { - var expression = parent.expression, propertyName = parent.name.text; - ts.Debug.assert(expression === use, "Didn't expect expression === use"); // Else shouldn't have been in `collectIdentifiers` - var idName = namedBindingsNames.get(propertyName); - if (idName === undefined) { - idName = makeUniqueName(propertyName, identifiers); - namedBindingsNames.set(propertyName, idName); + var propertyName = parent.name.text; + if (propertyName === "default") { + needDefaultImport = true; + var importDefaultName = use.getText(); + (useSitesToUnqualify !== null && useSitesToUnqualify !== void 0 ? useSitesToUnqualify : (useSitesToUnqualify = new ts.Map())).set(parent, ts.factory.createIdentifier(importDefaultName)); + } + else { + ts.Debug.assert(parent.expression === use, "Didn't expect expression === use"); // Else shouldn't have been in `collectIdentifiers` + var idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } + (useSitesToUnqualify !== null && useSitesToUnqualify !== void 0 ? useSitesToUnqualify : (useSitesToUnqualify = new ts.Map())).set(parent, ts.factory.createIdentifier(idName)); } - (useSitesToUnqualify !== null && useSitesToUnqualify !== void 0 ? useSitesToUnqualify : (useSitesToUnqualify = new ts.Map())).set(parent, ts.factory.createIdentifier(idName)); } else { needDefaultImport = true; @@ -137664,11 +142062,11 @@ var ts; function isFreeIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return parent.name !== node; - case 198 /* BindingElement */: + case 199 /* BindingElement */: return parent.propertyName !== node; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: return parent.propertyName !== node; default: return true; @@ -138145,87 +142543,138 @@ var ts; ImportFixKind[ImportFixKind["AddToExisting"] = 2] = "AddToExisting"; ImportFixKind[ImportFixKind["AddNew"] = 3] = "AddNew"; })(ImportFixKind || (ImportFixKind = {})); - var ImportKind; - (function (ImportKind) { - ImportKind[ImportKind["Named"] = 0] = "Named"; - ImportKind[ImportKind["Default"] = 1] = "Default"; - ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; - ImportKind[ImportKind["CommonJS"] = 3] = "CommonJS"; - })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { var compilerOptions = program.getCompilerOptions(); var exportInfos = ts.pathIsBareSpecifier(ts.stripQuotes(moduleSymbol.name)) - ? [getSymbolExportInfoForSymbol(exportedSymbol, moduleSymbol, sourceFile, program, host)] + ? [getSymbolExportInfoForSymbol(exportedSymbol, moduleSymbol, program, host)] : getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, host, program, /*useAutoImportProvider*/ true); var useRequire = shouldUseRequire(sourceFile, program); var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && !ts.isSourceFileJS(sourceFile) && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences)).moduleSpecifier; var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences); - return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; + return { moduleSpecifier: fix.moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences) { ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol"); - // We sort the best codefixes first, so taking `first` is best. - return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences)); + return getBestFix(getImportFixes(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences), sourceFile, host); } function codeFixActionToCodeAction(_a) { var description = _a.description, changes = _a.changes, commands = _a.commands; return { description: description, changes: changes, commands: commands }; } - function getSymbolExportInfoForSymbol(symbol, moduleSymbol, importingFile, program, host) { + function getSymbolExportInfoForSymbol(symbol, moduleSymbol, program, host) { var _a, _b; var compilerOptions = program.getCompilerOptions(); - var mainProgramInfo = getInfoWithChecker(program.getTypeChecker()); + var mainProgramInfo = getInfoWithChecker(program.getTypeChecker(), /*isFromPackageJson*/ false); if (mainProgramInfo) { return mainProgramInfo; } var autoImportProvider = (_b = (_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getTypeChecker(); - return ts.Debug.checkDefined(autoImportProvider && getInfoWithChecker(autoImportProvider), "Could not find symbol in specified module for code actions"); - function getInfoWithChecker(checker) { - var defaultInfo = getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions); + return ts.Debug.checkDefined(autoImportProvider && getInfoWithChecker(autoImportProvider, /*isFromPackageJson*/ true), "Could not find symbol in specified module for code actions"); + function getInfoWithChecker(checker, isFromPackageJson) { + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); if (defaultInfo && ts.skipAlias(defaultInfo.symbol, checker) === symbol) { - return { moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker) }; + return { symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, exportKind: defaultInfo.exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker), isFromPackageJson: isFromPackageJson }; } var named = checker.tryGetMemberInModuleExportsAndProperties(symbol.name, moduleSymbol); if (named && ts.skipAlias(named, checker) === symbol) { - return { moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker) }; + return { symbol: named, moduleSymbol: moduleSymbol, exportKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker), isFromPackageJson: isFromPackageJson }; } } } function getAllReExportingModules(importingFile, exportedSymbol, exportingModuleSymbol, symbolName, host, program, useAutoImportProvider) { var result = []; var compilerOptions = program.getCompilerOptions(); - forEachExternalModuleToImportFrom(program, host, importingFile, /*filterByPackageJson*/ false, useAutoImportProvider, function (moduleSymbol, moduleFile, program) { + var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { + return ts.createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); + }); + forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, function (moduleSymbol, moduleFile, program, isFromPackageJson) { var checker = program.getTypeChecker(); // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(importingFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } - var defaultInfo = getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions); - if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { - result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + result.push({ symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, exportKind: defaultInfo.exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker), isFromPackageJson: isFromPackageJson }); } for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { - result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + result.push({ symbol: exported, moduleSymbol: moduleSymbol, exportKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker), isFromPackageJson: isFromPackageJson }); } } }); return result; + function isImportable(program, moduleFile, isFromPackageJson) { + var _a; + return !moduleFile || ts.isImportableFile(program, importingFile, moduleFile, /*packageJsonFilter*/ undefined, getModuleSpecifierResolutionHost(isFromPackageJson), (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host)); + } } + function getModuleSpecifierForBestExportInfo(exportInfo, importingFile, program, host, preferences) { + return getBestFix(getNewImportFixes(program, importingFile, /*position*/ undefined, /*preferTypeOnlyImport*/ false, /*useRequire*/ false, exportInfo, host, preferences), importingFile, host); + } + codefix.getModuleSpecifierForBestExportInfo = getModuleSpecifierForBestExportInfo; + function getSymbolToExportInfoMap(importingFile, host, program) { + var _a, _b, _c, _d, _e, _f, _g, _h; + var start = ts.timestamp(); + // Pulling the AutoImportProvider project will trigger its updateGraph if pending, + // which will invalidate the export map cache if things change, so pull it before + // checking the cache. + (_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host); + var cache = (_b = host.getExportMapCache) === null || _b === void 0 ? void 0 : _b.call(host); + if (cache) { + var cached = cache.get(importingFile.path, program.getTypeChecker(), (_c = host.getProjectVersion) === null || _c === void 0 ? void 0 : _c.call(host)); + if (cached) { + (_d = host.log) === null || _d === void 0 ? void 0 : _d.call(host, "getSymbolToExportInfoMap: cache hit"); + return cached; + } + else { + (_e = host.log) === null || _e === void 0 ? void 0 : _e.call(host, "getSymbolToExportInfoMap: cache miss or empty; calculating new results"); + } + } + var result = ts.createMultiMap(); + var compilerOptions = program.getCompilerOptions(); + var target = ts.getEmitScriptTarget(compilerOptions); + forEachExternalModuleToImportFrom(program, host, /*useAutoImportProvider*/ true, function (moduleSymbol, _moduleFile, program, isFromPackageJson) { + var checker = program.getTypeChecker(); + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo) { + var name = ts.getNameForExportedSymbol(ts.getLocalSymbolForExportDefault(defaultInfo.symbol) || defaultInfo.symbol, target); + result.add(key(name, defaultInfo.symbol, moduleSymbol, checker), { symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, exportKind: defaultInfo.exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker), isFromPackageJson: isFromPackageJson }); + } + var seenExports = new ts.Map(); + for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { + var exported = _a[_i]; + if (exported !== (defaultInfo === null || defaultInfo === void 0 ? void 0 : defaultInfo.symbol) && ts.addToSeen(seenExports, exported)) { + result.add(key(ts.getNameForExportedSymbol(exported, target), exported, moduleSymbol, checker), { symbol: exported, moduleSymbol: moduleSymbol, exportKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker), isFromPackageJson: isFromPackageJson }); + } + } + }); + if (cache) { + (_f = host.log) === null || _f === void 0 ? void 0 : _f.call(host, "getSymbolToExportInfoMap: caching results"); + cache.set(result, (_g = host.getProjectVersion) === null || _g === void 0 ? void 0 : _g.call(host)); + } + (_h = host.log) === null || _h === void 0 ? void 0 : _h.call(host, "getSymbolToExportInfoMap: done in " + (ts.timestamp() - start) + " ms"); + return result; + function key(name, alias, moduleSymbol, checker) { + var moduleName = ts.stripQuotes(moduleSymbol.name); + var moduleKey = ts.isExternalModuleNameRelative(moduleName) ? "/" : moduleName; + return name + "|" + ts.getSymbolId(ts.skipAlias(alias, checker)) + "|" + moduleKey; + } + } + codefix.getSymbolToExportInfoMap = getSymbolToExportInfoMap; function isTypeOnlySymbol(s, checker) { return !(ts.skipAlias(s, checker).flags & 111551 /* Value */); } function isTypeOnlyPosition(sourceFile, position) { return ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); } - function getFixForImport(exportInfos, symbolName, + function getImportFixes(exportInfos, symbolName, /** undefined only for missing JSX namespace */ position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); - var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); + var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile, program.getCompilerOptions()); }); var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); var addToExisting = tryAddToExistingImport(existingImports, position !== undefined && isTypeOnlyPosition(sourceFile, position)); // Don't bother providing an action to add a new import if we can add to an existing one. @@ -138248,10 +142697,11 @@ var ts; return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration; var namespacePrefix = getNamespaceLikeImportText(declaration); - if (namespacePrefix) { + var moduleSpecifier = ts.tryGetModuleSpecifierFromDeclaration(declaration); + if (namespacePrefix && moduleSpecifier) { var moduleSymbol = getTargetModuleFromNamespaceLikeImport(declaration, checker); if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { - return { kind: 0 /* UseNamespace */, namespacePrefix: namespacePrefix, position: position }; + return { kind: 0 /* UseNamespace */, namespacePrefix: namespacePrefix, position: position, moduleSpecifier: moduleSpecifier }; } } }); @@ -138259,11 +142709,11 @@ var ts; function getTargetModuleFromNamespaceLikeImport(declaration, checker) { var _a; switch (declaration.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return checker.resolveExternalModuleName(declaration.initializer.arguments[0]); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return checker.getAliasedSymbol(declaration.symbol); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: var namespaceImport = ts.tryCast((_a = declaration.importClause) === null || _a === void 0 ? void 0 : _a.namedBindings, ts.isNamespaceImport); return namespaceImport && checker.getAliasedSymbol(namespaceImport.symbol); default: @@ -138273,11 +142723,11 @@ var ts; function getNamespaceLikeImportText(declaration) { var _a, _b, _c; switch (declaration.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return (_a = ts.tryCast(declaration.name, ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return declaration.name.text; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return (_c = ts.tryCast((_b = declaration.importClause) === null || _b === void 0 ? void 0 : _b.namedBindings, ts.isNamespaceImport)) === null || _c === void 0 ? void 0 : _c.name.text; default: return ts.Debug.assertNever(declaration); @@ -138286,31 +142736,38 @@ var ts; function tryAddToExistingImport(existingImports, canUseTypeOnlyImport) { return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind === 260 /* ImportEqualsDeclaration */) + if (declaration.kind === 261 /* ImportEqualsDeclaration */) return undefined; - if (declaration.kind === 249 /* VariableDeclaration */) { - return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 196 /* ObjectBindingPattern */ + if (declaration.kind === 250 /* VariableDeclaration */) { + return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 197 /* ObjectBindingPattern */ ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: declaration.name, importKind: importKind, moduleSpecifier: declaration.initializer.arguments[0].text, canUseTypeOnlyImport: false } : undefined; } var importClause = declaration.importClause; - if (!importClause) + if (!importClause || !ts.isStringLiteralLike(declaration.moduleSpecifier)) return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; - return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 264 /* NamedImports */) - ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.getText(), canUseTypeOnlyImport: canUseTypeOnlyImport } + // A type-only import may not have both a default and named imports, so the only way a name can + // be added to an existing type-only import is adding a named import to existing named bindings. + if (importClause.isTypeOnly && !(importKind === 0 /* Named */ && namedBindings)) + return undefined; + return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 265 /* NamedImports */) + ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.text, canUseTypeOnlyImport: canUseTypeOnlyImport } : undefined; }); } - function getExistingImportDeclarations(_a, checker, sourceFile) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; + function getExistingImportDeclarations(_a, checker, importingFile, compilerOptions) { + var moduleSymbol = _a.moduleSymbol, exportKind = _a.exportKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + if (exportedSymbolIsTypeOnly && ts.isSourceFileJS(importingFile)) + return ts.emptyArray; + var importKind = getImportKind(importingFile, exportKind, compilerOptions); + return ts.mapDefined(importingFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); - if (ts.isRequireVariableDeclaration(i.parent, /*requireStringLiteralLikeArgument*/ true)) { + if (ts.isRequireVariableDeclaration(i.parent)) { return checker.resolveExternalModuleName(moduleSpecifier) === moduleSymbol ? { declaration: i.parent, importKind: importKind } : undefined; } - if (i.kind === 261 /* ImportDeclaration */ || i.kind === 260 /* ImportEqualsDeclaration */) { + if (i.kind === 262 /* ImportDeclaration */ || i.kind === 261 /* ImportEqualsDeclaration */) { return checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; } }); @@ -138343,45 +142800,29 @@ var ts; // 5. Literally nothing to go on return true; } - function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) { + function getNewImportFixes(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) { var isJs = ts.isSourceFileJS(sourceFile); var compilerOptions = program.getCompilerOptions(); - var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; - var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getTypeChecker(), compilerOptions, sourceFile, ts.createModuleSpecifierResolutionHost(program, host), preferences) + var moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); + return ts.flatMap(moduleSymbols, function (exportInfo) { + return ts.moduleSpecifiers.getModuleSpecifiers(exportInfo.moduleSymbol, program.getTypeChecker(), compilerOptions, sourceFile, moduleSpecifierResolutionHost, preferences) .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.checkDefined(position, "position should be defined") } - : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, useRequire: useRequire, typeOnly: preferTypeOnlyImport }; + return exportInfo.exportedSymbolIsTypeOnly && isJs && position !== undefined + ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: position, exportInfo: exportInfo } + : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: getImportKind(sourceFile, exportInfo.exportKind, compilerOptions), useRequire: useRequire, typeOnly: preferTypeOnlyImport, exportInfo: exportInfo }; }); }); - // Sort by presence in package.json, then shortest paths first - return ts.sort(choicesForEachExportingModule, function (a, b) { - var allowsImportingA = allowsImportingSpecifier(a.moduleSpecifier); - var allowsImportingB = allowsImportingSpecifier(b.moduleSpecifier); - if (allowsImportingA && !allowsImportingB) { - return -1; - } - if (allowsImportingB && !allowsImportingA) { - return 1; - } - return a.moduleSpecifier.length - b.moduleSpecifier.length; - }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport, useRequire); }); - return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences); + return existingDeclaration ? [existingDeclaration] : getNewImportFixes(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences); } function newImportInfoFromExistingSpecifier(_a, preferTypeOnlyImport, useRequire) { var declaration = _a.declaration, importKind = _a.importKind; - var moduleSpecifier = declaration.kind === 261 /* ImportDeclaration */ ? declaration.moduleSpecifier : - declaration.kind === 249 /* VariableDeclaration */ ? declaration.initializer.arguments[0] : - declaration.moduleReference.kind === 272 /* ExternalModuleReference */ ? declaration.moduleReference.expression : - undefined; - return moduleSpecifier && ts.isStringLiteral(moduleSpecifier) - ? { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier.text, importKind: importKind, typeOnly: preferTypeOnlyImport, useRequire: useRequire } + var moduleSpecifier = ts.tryGetModuleSpecifierFromDeclaration(declaration); + return moduleSpecifier + ? { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, typeOnly: preferTypeOnlyImport, useRequire: useRequire } : undefined; } function getFixesInfo(context, errorCode, pos, useAutoImportProvider) { @@ -138389,7 +142830,28 @@ var ts; var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ? getFixesInfoForUMDImport(context, symbolToken) : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider) : undefined; - return info && __assign(__assign({}, info), { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) }); + return info && __assign(__assign({}, info), { fixes: sortFixes(info.fixes, context.sourceFile, context.host) }); + } + function sortFixes(fixes, sourceFile, host) { + var allowsImportingSpecifier = ts.createPackageJsonImportFilter(sourceFile, host).allowsImportingSpecifier; + return ts.sort(fixes, function (a, b) { return ts.compareValues(a.kind, b.kind) || compareModuleSpecifiers(a, b, allowsImportingSpecifier); }); + } + function getBestFix(fixes, sourceFile, host) { + // These will always be placed first if available, and are better than other kinds + if (fixes[0].kind === 0 /* UseNamespace */ || fixes[0].kind === 2 /* AddToExisting */) { + return fixes[0]; + } + var allowsImportingSpecifier = ts.createPackageJsonImportFilter(sourceFile, host).allowsImportingSpecifier; + return fixes.reduce(function (best, fix) { + return compareModuleSpecifiers(fix, best, allowsImportingSpecifier) === -1 /* LessThan */ ? fix : best; + }); + } + function compareModuleSpecifiers(a, b, allowsImportingSpecifier) { + if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) { + return ts.compareBooleans(allowsImportingSpecifier(a.moduleSpecifier), allowsImportingSpecifier(b.moduleSpecifier)) + || ts.compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); + } + return 0 /* EqualTo */; } function getFixesInfoForUMDImport(_a, token) { var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences; @@ -138399,9 +142861,9 @@ var ts; return undefined; var symbol = checker.getAliasedSymbol(umdSymbol); var symbolName = umdSymbol.name; - var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(sourceFile, program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; + var exportInfos = [{ symbol: umdSymbol, moduleSymbol: symbol, exportKind: 3 /* UMD */, exportedSymbolIsTypeOnly: false, isFromPackageJson: false }]; var useRequire = shouldUseRequire(sourceFile, program); - var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, useRequire, program, sourceFile, host, preferences); + var fixes = getImportFixes(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, useRequire, program, sourceFile, host, preferences); return { fixes: fixes, symbolName: symbolName }; } function getUmdSymbol(token, checker) { @@ -138415,6 +142877,16 @@ var ts; ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 111551 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } + function getImportKind(importingFile, exportKind, compilerOptions) { + switch (exportKind) { + case 0 /* Named */: return 0 /* Named */; + case 1 /* Default */: return 1 /* Default */; + case 2 /* ExportEquals */: return getExportEqualsImportKind(importingFile, compilerOptions); + case 3 /* UMD */: return getUmdImportKind(importingFile, compilerOptions); + default: return ts.Debug.assertNever(exportKind); + } + } + codefix.getImportKind = getImportKind; function getUmdImportKind(importingFile, compilerOptions) { // Import a synthetic `default` if enabled. if (ts.getAllowSyntheticDefaultImports(compilerOptions)) { @@ -138444,22 +142916,22 @@ var ts; function getFixesInfoForNonUMDImport(_a, symbolToken, useAutoImportProvider) { var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences; var checker = program.getTypeChecker(); - var symbolName = getSymbolName(sourceFile, checker, symbolToken); + var compilerOptions = program.getCompilerOptions(); + var symbolName = getSymbolName(sourceFile, checker, symbolToken, compilerOptions); // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default" /* Default */, "'default' isn't a legal identifier and couldn't occur here"); - var compilerOptions = program.getCompilerOptions(); var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(symbolToken); var useRequire = shouldUseRequire(sourceFile, program); var exportInfos = getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host); var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfos.entries(), function (_a) { var _ = _a[0], exportInfos = _a[1]; - return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences); + return getImportFixes(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences); })); return { fixes: fixes, symbolName: symbolName }; } - function getSymbolName(sourceFile, checker, symbolToken) { + function getSymbolName(sourceFile, checker, symbolToken, compilerOptions) { var parent = symbolToken.parent; - if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken) { + if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken && compilerOptions.jsx !== 4 /* ReactJSX */ && compilerOptions.jsx !== 5 /* ReactJSXDev */) { var jsxNamespace = checker.getJsxNamespace(sourceFile); if (ts.isIntrinsicJsxName(symbolToken.text) || !checker.resolveName(jsxNamespace, parent, 111551 /* Value */, /*excludeGlobals*/ true)) { return jsxNamespace; @@ -138468,43 +142940,55 @@ var ts; return symbolToken.text; } // Returns a map from an exported symbol's ID to a list of every way it's (re-)exported. - function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, program, useAutoImportProvider, host) { + function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, fromFile, program, useAutoImportProvider, host) { + var _a; // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); - function addSymbol(moduleSymbol, exportedSymbol, importKind, checker) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); + var packageJsonFilter = ts.createPackageJsonImportFilter(fromFile, host); + var moduleSpecifierCache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); + var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { + return ts.createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); + }); + function addSymbol(moduleSymbol, toFile, exportedSymbol, exportKind, program, isFromPackageJson) { + var moduleSpecifierResolutionHost = getModuleSpecifierResolutionHost(isFromPackageJson); + if (toFile && ts.isImportableFile(program, fromFile, toFile, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) || + !toFile && packageJsonFilter.allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost)) { + var checker = program.getTypeChecker(); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { symbol: exportedSymbol, moduleSymbol: moduleSymbol, exportKind: exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker), isFromPackageJson: isFromPackageJson }); + } } - forEachExternalModuleToImportFrom(program, host, sourceFile, /*filterByPackageJson*/ true, useAutoImportProvider, function (moduleSymbol, _, program) { + forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, function (moduleSymbol, sourceFile, program, isFromPackageJson) { var checker = program.getTypeChecker(); cancellationToken.throwIfCancellationRequested(); var compilerOptions = program.getCompilerOptions(); - var defaultInfo = getDefaultLikeExportInfo(sourceFile, moduleSymbol, checker, compilerOptions); + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind, checker); + addSymbol(moduleSymbol, sourceFile, defaultInfo.symbol, defaultInfo.exportKind, program, isFromPackageJson); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */, checker); + addSymbol(moduleSymbol, sourceFile, exportSymbolWithIdenticalName, 0 /* Named */, program, isFromPackageJson); } }); return originalSymbolToExportInfos; } - function getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions) { - var exported = getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions); + 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); + var symbol = exported.symbol, exportKind = exported.exportKind; + var info = getDefaultExportInfoWorker(symbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, exportKind: exportKind }, info); } - function getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions) { + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) + return { symbol: exportEquals, exportKind: 2 /* ExportEquals */ }; 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: getExportEqualsImportKind(importingFile, compilerOptions) }; + return { symbol: defaultExport, exportKind: 1 /* Default */ }; } function getExportEqualsImportKind(importingFile, compilerOptions) { var allowSyntheticDefaults = ts.getAllowSyntheticDefaultImports(compilerOptions); @@ -138523,7 +143007,8 @@ var ts; // on how to handle it. for (var _i = 0, _a = importingFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - if (ts.isImportEqualsDeclaration(statement)) { + // `import foo` parses as an ImportEqualsDeclaration even though it could be an ImportDeclaration + if (ts.isImportEqualsDeclaration(statement) && !ts.nodeIsMissing(statement.moduleReference)) { return 3 /* CommonJS */; } } @@ -138531,7 +143016,7 @@ var ts; // allowSyntheticDefaultImports/esModuleInterop is enabled. return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */; } - function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { + function getDefaultExportInfoWorker(defaultExport, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -138545,21 +143030,20 @@ var ts; // but we can still offer completions for it. // - `aliased.parent` will be undefined if the module is exporting `globalThis.something`, // or another expression that resolves to a global. - return getDefaultExportInfoWorker(aliased, aliased.parent, checker, compilerOptions); + return getDefaultExportInfoWorker(aliased, checker, compilerOptions); } } if (defaultExport.escapedName !== "default" /* Default */ && defaultExport.escapedName !== "export=" /* ExportEquals */) { return { symbolForMeaning: defaultExport, name: defaultExport.getName() }; } - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; + return { symbolForMeaning: defaultExport, name: ts.getNameForExportedSymbol(defaultExport, compilerOptions.target) }; } function getNameForExportDefault(symbol) { return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { + var _a; if (ts.isExportAssignment(declaration)) { - if (ts.isIdentifier(declaration.expression)) { - return declaration.expression.text; - } + return (_a = ts.tryCast(ts.skipOuterExpressions(declaration.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text; } else if (ts.isExportSpecifier(declaration)) { ts.Debug.assert(declaration.name.text === "default" /* Default */, "Expected the specifier to be a default export"); @@ -138602,7 +143086,7 @@ var ts; } } function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, canUseTypeOnlyImport) { - if (clause.kind === 196 /* ObjectBindingPattern */) { + if (clause.kind === 197 /* ObjectBindingPattern */) { if (defaultImport) { addElementToBindingPattern(clause, defaultImport, "default"); } @@ -138729,48 +143213,23 @@ var ts; var declarations = _a.declarations; return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); } - function forEachExternalModuleToImportFrom(program, host, from, filterByPackageJson, useAutoImportProvider, cb) { + function forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, cb) { var _a, _b; - forEachExternalModuleToImportFromInProgram(program, host, from, filterByPackageJson, function (module, file) { return cb(module, file, program, /*isFromPackageJson*/ false); }); + forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), function (module, file) { return cb(module, file, program, /*isFromPackageJson*/ false); }); var autoImportProvider = useAutoImportProvider && ((_a = host.getPackageJsonAutoImportProvider) === null || _a === void 0 ? void 0 : _a.call(host)); if (autoImportProvider) { var start = ts.timestamp(); - forEachExternalModuleToImportFromInProgram(autoImportProvider, host, from, filterByPackageJson, function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); + forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); (_b = host.log) === null || _b === void 0 ? void 0 : _b.call(host, "forEachExternalModuleToImportFrom autoImportProvider: " + (ts.timestamp() - start)); } } codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; - function forEachExternalModuleToImportFromInProgram(program, host, from, filterByPackageJson, cb) { - var _a; - var filteredCount = 0; - var moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); - var packageJson = filterByPackageJson && createAutoImportFilter(from, program, host, moduleSpecifierResolutionHost); - forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), function (module, sourceFile) { - if (sourceFile === undefined) { - if (!packageJson || packageJson.allowsImportingAmbientModule(module)) { - cb(module, sourceFile); - } - else if (packageJson) { - filteredCount++; - } - } - else if (sourceFile && - sourceFile !== from && - isImportableFile(program, from, sourceFile, moduleSpecifierResolutionHost)) { - if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile)) { - cb(module, sourceFile); - } - else if (packageJson) { - filteredCount++; - } - } - }); - (_a = host.log) === null || _a === void 0 ? void 0 : _a.call(host, "forEachExternalModuleToImportFrom: filtered out " + filteredCount + " modules by package.json contents"); - } function forEachExternalModule(checker, allSourceFiles, cb) { for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { var ambient = _a[_i]; - cb(ambient, /*sourceFile*/ undefined); + if (!ts.stringContains(ambient.name, "*")) { + cb(ambient, /*sourceFile*/ undefined); + } } for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { var sourceFile = allSourceFiles_1[_b]; @@ -138779,31 +143238,6 @@ var ts; } } } - function isImportableFile(program, from, to, moduleSpecifierResolutionHost) { - var _a; - var getCanonicalFileName = ts.hostGetCanonicalFileName(moduleSpecifierResolutionHost); - var globalTypingsCache = (_a = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation) === null || _a === void 0 ? void 0 : _a.call(moduleSpecifierResolutionHost); - return !!ts.moduleSpecifiers.forEachFileNameOfModule(from.fileName, to.fileName, moduleSpecifierResolutionHost, - /*preferSymlinks*/ false, function (toPath) { - var toFile = program.getSourceFile(toPath); - // Determine to import using toPath only if toPath is what we were looking at - // or there doesnt exist the file in the program by the symlink - return (toFile === to || !toFile) && - isImportablePath(from.fileName, toPath, getCanonicalFileName, globalTypingsCache); - }); - } - /** - * Don't include something from a `node_modules` that isn't actually reachable by a global import. - * A relative import to node_modules is usually a bad idea. - */ - function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) { - // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. - var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); - var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules)); - return toNodeModulesParent === undefined - || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) - || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); - } function moduleSymbolToValidIdentifier(moduleSymbol, target) { return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); } @@ -138835,99 +143269,122 @@ var ts; return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; } codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; - function createAutoImportFilter(fromFile, program, host, moduleSpecifierResolutionHost) { - if (moduleSpecifierResolutionHost === void 0) { moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); } - var packageJsons = ((host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName)) || ts.getPackageJsonsVisibleToFile(fromFile.fileName, host)).filter(function (p) { return p.parseable; }); - var usesNodeCoreModules; - return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier, moduleSpecifierResolutionHost: moduleSpecifierResolutionHost }; - function moduleSpecifierIsCoveredByPackageJson(specifier) { - var packageName = getNodeModuleRootSpecifier(specifier); - for (var _i = 0, packageJsons_1 = packageJsons; _i < packageJsons_1.length; _i++) { - var packageJson = packageJsons_1[_i]; - if (packageJson.has(packageName) || packageJson.has(ts.getTypesPackageName(packageName))) { - return true; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var _a; + var fixName = "fixOverrideModifier"; + var fixAddOverrideId = "fixAddOverrideModifier"; + var fixRemoveOverrideId = "fixRemoveOverrideModifier"; + var errorCodes = [ + ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code, + ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code, + ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code, + ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code, + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code + ]; + var errorCodeFixIdMap = (_a = {}, + _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code] = [ + ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Add_all_missing_override_modifiers, + ], + _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code] = [ + ts.Diagnostics.Remove_override_modifier, fixRemoveOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers + ], + _a[ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code] = [ + ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Add_all_missing_override_modifiers, + ], + _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code] = [ + ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers + ], + _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code] = [ + ts.Diagnostics.Remove_override_modifier, fixRemoveOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers + ], + _a); + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var errorCode = context.errorCode, span = context.span, sourceFile = context.sourceFile; + var info = errorCodeFixIdMap[errorCode]; + if (!info) + return ts.emptyArray; + var descriptions = info[0], fixId = info[1], fixAllDescriptions = info[2]; + if (ts.isSourceFileJS(sourceFile)) + return ts.emptyArray; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { return dispatchChanges(changes, context, errorCode, span.start); }); + return [ + codefix.createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId, fixAllDescriptions) + ]; + }, + fixIds: [fixName, fixAddOverrideId, fixRemoveOverrideId], + getAllCodeActions: function (context) { + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var code = diag.code, start = diag.start, file = diag.file; + var info = errorCodeFixIdMap[code]; + if (!info || info[1] !== context.fixId || ts.isSourceFileJS(file)) { + return; } - } - return false; - } - function allowsImportingAmbientModule(moduleSymbol) { - if (!packageJsons.length) { - return true; - } - var declaringSourceFile = moduleSymbol.valueDeclaration.getSourceFile(); - var declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName); - if (typeof declaringNodeModuleName === "undefined") { - return true; - } - var declaredModuleSpecifier = ts.stripQuotes(moduleSymbol.getName()); - if (isAllowedCoreNodeModulesImport(declaredModuleSpecifier)) { - return true; - } - return moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName) - || moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier); - } - function allowsImportingSourceFile(sourceFile) { - if (!packageJsons.length) { - return true; - } - var moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName); - if (!moduleSpecifier) { - return true; - } - return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); + dispatchChanges(changes, context, code, start); + }); } - /** - * Use for a specific module specifier that has already been resolved. - * Use `allowsImportingAmbientModule` or `allowsImportingSourceFile` to resolve - * the best module specifier for a given module _and_ determine if it’s importable. - */ - function allowsImportingSpecifier(moduleSpecifier) { - if (!packageJsons.length || isAllowedCoreNodeModulesImport(moduleSpecifier)) { - return true; - } - if (ts.pathIsRelative(moduleSpecifier) || ts.isRootedDiskPath(moduleSpecifier)) { + }); + function dispatchChanges(changeTracker, context, errorCode, pos) { + switch (errorCode) { + case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code: + case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code: + case ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code: + return doAddOverrideModifierChange(changeTracker, context.sourceFile, pos); + case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code: + case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code: + return doRemoveOverrideModifierChange(changeTracker, context.sourceFile, pos); + default: + ts.Debug.fail("Unexpected error code: " + errorCode); + } + } + function doAddOverrideModifierChange(changeTracker, sourceFile, pos) { + var classElement = findContainerClassElementLike(sourceFile, pos); + var modifiers = classElement.modifiers || ts.emptyArray; + var staticModifier = ts.find(modifiers, ts.isStaticModifier); + var accessibilityModifier = ts.find(modifiers, function (m) { return ts.isAccessibilityModifier(m.kind); }); + var modifierPos = staticModifier ? staticModifier.end : + accessibilityModifier ? accessibilityModifier.end : + classElement.decorators ? ts.skipTrivia(sourceFile.text, classElement.decorators.end) : classElement.getStart(sourceFile); + var options = accessibilityModifier || staticModifier ? { prefix: " " } : { suffix: " " }; + changeTracker.insertModifierAt(sourceFile, modifierPos, 156 /* OverrideKeyword */, options); + } + function doRemoveOverrideModifierChange(changeTracker, sourceFile, pos) { + var classElement = findContainerClassElementLike(sourceFile, pos); + var overrideModifier = classElement.modifiers && ts.find(classElement.modifiers, function (modifier) { return modifier.kind === 156 /* OverrideKeyword */; }); + ts.Debug.assertIsDefined(overrideModifier); + changeTracker.deleteModifier(sourceFile, overrideModifier); + } + function isClassElementLikeHasJSDoc(node) { + switch (node.kind) { + case 167 /* Constructor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return true; - } - return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); - } - function isAllowedCoreNodeModulesImport(moduleSpecifier) { - // If we’re in JavaScript, it can be difficult to tell whether the user wants to import - // from Node core modules or not. We can start by seeing if the user is actually using - // any node core modules, as opposed to simply having @types/node accidentally as a - // dependency of a dependency. - if (ts.isSourceFileJS(fromFile) && ts.JsTyping.nodeCoreModules.has(moduleSpecifier)) { - if (usesNodeCoreModules === undefined) { - usesNodeCoreModules = ts.consumesNodeCoreModules(fromFile); - } - if (usesNodeCoreModules) { - return true; - } - } - return false; - } - function getNodeModulesPackageNameFromFileName(importedFileName) { - if (!ts.stringContains(importedFileName, "node_modules")) { - return undefined; - } - var specifier = ts.moduleSpecifiers.getNodeModulesPackageName(host.getCompilationSettings(), fromFile.path, importedFileName, moduleSpecifierResolutionHost); - if (!specifier) { - return undefined; - } - // Paths here are not node_modules, so we don’t care about them; - // returning anything will trigger a lookup in package.json. - if (!ts.pathIsRelative(specifier) && !ts.isRootedDiskPath(specifier)) { - return getNodeModuleRootSpecifier(specifier); - } - } - function getNodeModuleRootSpecifier(fullSpecifier) { - var components = ts.getPathComponents(ts.getPackageNameFromTypesPackageName(fullSpecifier)).slice(1); - // Scoped packages - if (ts.startsWith(components[0], "@")) { - return components[0] + "/" + components[1]; - } - return components[0]; + case 161 /* Parameter */: + return ts.isParameterPropertyDeclaration(node, node.parent); + default: + return false; } } + function findContainerClassElementLike(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var classElement = ts.findAncestor(token, function (node) { + if (ts.isClassLike(node)) + return "quit"; + return isClassElementLikeHasJSDoc(node); + }); + ts.Debug.assert(classElement && isClassElementLikeHasJSDoc(classElement)); + return classElement; + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -139043,7 +143500,7 @@ var ts; }); function getNamedTupleMember(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - return ts.findAncestor(token, function (t) { return t.kind === 192 /* NamedTupleMember */; }); + return ts.findAncestor(token, function (t) { return t.kind === 193 /* NamedTupleMember */; }); } function doChange(changes, sourceFile, namedTupleMember) { if (!namedTupleMember) { @@ -139052,11 +143509,11 @@ var ts; var unwrappedType = namedTupleMember.type; var sawOptional = false; var sawRest = false; - while (unwrappedType.kind === 180 /* OptionalType */ || unwrappedType.kind === 181 /* RestType */ || unwrappedType.kind === 186 /* ParenthesizedType */) { - if (unwrappedType.kind === 180 /* OptionalType */) { + while (unwrappedType.kind === 181 /* OptionalType */ || unwrappedType.kind === 182 /* RestType */ || unwrappedType.kind === 187 /* ParenthesizedType */) { + if (unwrappedType.kind === 181 /* OptionalType */) { sawOptional = true; } - else if (unwrappedType.kind === 181 /* RestType */) { + else if (unwrappedType.kind === 182 /* RestType */) { sawRest = true; } unwrappedType = unwrappedType.type; @@ -139120,7 +143577,7 @@ var ts; var checker = context.program.getTypeChecker(); var suggestedSymbol; if (ts.isPropertyAccessExpression(parent) && parent.name === node) { - ts.Debug.assert(ts.isIdentifierOrPrivateIdentifier(node), "Expected an identifier for spelling (property access)"); + ts.Debug.assert(ts.isMemberName(node), "Expected an identifier for spelling (property access)"); var containingType = checker.getTypeAtLocation(parent.expression); if (parent.flags & 32 /* OptionalChain */) { containingType = checker.getNonNullableType(containingType); @@ -139159,7 +143616,7 @@ var ts; var suggestion = ts.symbolName(suggestedSymbol); if (!ts.isIdentifierText(suggestion, target) && ts.isPropertyAccessExpression(node.parent)) { var valDecl = suggestedSymbol.valueDeclaration; - if (ts.isNamedDeclaration(valDecl) && ts.isPrivateIdentifier(valDecl.name)) { + if (valDecl && ts.isNamedDeclaration(valDecl) && ts.isPrivateIdentifier(valDecl.name)) { changes.replaceNode(sourceFile, node, ts.factory.createIdentifier(suggestion)); } else { @@ -139356,19 +143813,19 @@ var ts; } function getVariableLikeInitializer(declaration) { switch (declaration.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: - case 163 /* PropertyDeclaration */: - case 288 /* PropertyAssignment */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: + case 164 /* PropertyDeclaration */: + case 289 /* PropertyAssignment */: return declaration.initializer; - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return declaration.initializer && (ts.isJsxExpression(declaration.initializer) ? declaration.initializer.expression : undefined); - case 289 /* ShorthandPropertyAssignment */: - case 162 /* PropertySignature */: - case 291 /* EnumMember */: - case 333 /* JSDocPropertyTag */: - case 326 /* JSDocParameterTag */: + case 290 /* ShorthandPropertyAssignment */: + case 163 /* PropertySignature */: + case 292 /* EnumMember */: + case 337 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: return undefined; } } @@ -139469,7 +143926,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = codefix.getAllSupers(classDeclaration, checker); - var _loop_13 = function (info) { + var _loop_14 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -139494,9 +143951,9 @@ var ts; } } }; - for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { - var info = infos_1[_i]; - _loop_13(info); + for (var _i = 0, infos_2 = infos; _i < infos_2.length; _i++) { + var info = infos_2[_i]; + _loop_14(info); } }); })); @@ -139586,7 +144043,7 @@ var ts; function addMissingMemberInJs(changeTracker, declSourceFile, classDeclaration, token, makeStatic) { var tokenName = token.text; if (makeStatic) { - if (classDeclaration.kind === 221 /* ClassExpression */) { + if (classDeclaration.kind === 222 /* ClassExpression */) { return; } var className = classDeclaration.name.getText(); @@ -139638,15 +144095,15 @@ var ts; } function getTypeNode(checker, classDeclaration, token) { var typeNode; - if (token.parent.parent.kind === 216 /* BinaryExpression */) { + if (token.parent.parent.kind === 217 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration, /*flags*/ undefined); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration, 1 /* NoTruncation */); } else { var contextualType = checker.getContextualType(token.parent); - typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined) : undefined; + typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, 1 /* NoTruncation */) : undefined; } return typeNode || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } @@ -139710,7 +144167,7 @@ var ts; } function addMethodDeclaration(context, changes, callExpression, name, modifierFlags, parentDeclaration, sourceFile) { var importAdder = codefix.createImportAdder(sourceFile, context.program, context.preferences, context.host); - var methodDeclaration = codefix.createSignatureDeclarationFromCallExpression(165 /* MethodDeclaration */, context, importAdder, callExpression, name, modifierFlags, parentDeclaration); + var methodDeclaration = codefix.createSignatureDeclarationFromCallExpression(166 /* MethodDeclaration */, context, importAdder, callExpression, name, modifierFlags, parentDeclaration); var containingMethodDeclaration = ts.findAncestor(callExpression, function (n) { return ts.isMethodDeclaration(n) || ts.isConstructorDeclaration(n); }); if (containingMethodDeclaration && containingMethodDeclaration.parent === parentDeclaration) { changes.insertNodeAfter(sourceFile, containingMethodDeclaration, methodDeclaration); @@ -139739,7 +144196,7 @@ var ts; } function addFunctionDeclaration(changes, context, info) { var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); - var functionDeclaration = codefix.createSignatureDeclarationFromCallExpression(251 /* FunctionDeclaration */, context, importAdder, info.call, info.token, info.modifierFlags, info.parentDeclaration); + var functionDeclaration = codefix.createSignatureDeclarationFromCallExpression(252 /* FunctionDeclaration */, context, importAdder, info.call, ts.idText(info.token), info.modifierFlags, info.parentDeclaration); changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -139826,7 +144283,10 @@ var ts; return { type: "install package", file: fileName, packageName: packageName }; } function tryGetImportedPackageName(sourceFile, pos) { - var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; + var moduleSpecifierText = ts.tryCast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral); + if (!moduleSpecifierText) + return undefined; + var moduleName = moduleSpecifierText.text; var packageName = ts.parsePackageName(moduleName).packageName; return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; } @@ -140056,7 +144516,10 @@ var ts; var codefix; (function (codefix) { codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code], + errorCodes: [ + ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code, + ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code, + ], getCodeActions: function (context) { var compilerOptions = context.program.getCompilerOptions(); var configFile = compilerOptions.configFile; @@ -140427,7 +144890,7 @@ var ts; } function isImport(token) { return token.kind === 99 /* ImportKeyword */ - || token.kind === 78 /* Identifier */ && (token.parent.kind === 265 /* ImportSpecifier */ || token.parent.kind === 262 /* ImportClause */); + || token.kind === 78 /* Identifier */ && (token.parent.kind === 266 /* ImportSpecifier */ || token.parent.kind === 263 /* ImportClause */); } /** Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. */ function tryGetFullImport(token) { @@ -140437,7 +144900,7 @@ var ts; return ts.isVariableDeclarationList(token.parent) && ts.first(token.parent.getChildren(sourceFile)) === token; } function deleteEntireVariableStatement(changes, sourceFile, node) { - changes.delete(sourceFile, node.parent.kind === 232 /* VariableStatement */ ? node.parent : node); + changes.delete(sourceFile, node.parent.kind === 233 /* VariableStatement */ ? node.parent : node); } function deleteDestructuringElements(changes, sourceFile, node) { ts.forEach(node.elements, function (n) { return changes.delete(sourceFile, n); }); @@ -140462,14 +144925,14 @@ var ts; } function canPrefix(token) { switch (token.parent.kind) { - case 160 /* Parameter */: - case 159 /* TypeParameter */: + case 161 /* Parameter */: + case 160 /* TypeParameter */: return true; - case 249 /* VariableDeclaration */: { + case 250 /* VariableDeclaration */: { var varDecl = token.parent; switch (varDecl.parent.parent.kind) { - case 239 /* ForOfStatement */: - case 238 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 239 /* ForInStatement */: return true; } } @@ -140493,8 +144956,10 @@ var ts; if (ts.isParameter(parent)) { tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, program, cancellationToken, isFixAll); } - else if (!isFixAll || !(ts.isIdentifier(token) && ts.FindAllReferences.Core.isSymbolReferencedInFile(token, checker, sourceFile))) { - changes.delete(sourceFile, ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent); + else if (!(isFixAll && ts.isIdentifier(token) && ts.FindAllReferences.Core.isSymbolReferencedInFile(token, checker, sourceFile))) { + var node = ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent; + ts.Debug.assert(node !== sourceFile, "should not delete whole source file"); + changes.delete(sourceFile, node); } } function tryDeleteParameter(changes, sourceFile, parameter, checker, sourceFiles, program, cancellationToken, isFixAll) { @@ -140517,8 +144982,8 @@ var ts; function mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll) { var parent = parameter.parent; switch (parent.kind) { - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: var index = parent.parameters.indexOf(parameter); var referent = ts.isMethodDeclaration(parent) ? parent.name : parent; var entries = ts.FindAllReferences.Core.getReferencedSymbolsForNode(parent.pos, referent, program, sourceFiles, cancellationToken); @@ -140548,17 +145013,17 @@ var ts; } } return true; - case 251 /* FunctionDeclaration */: { + case 252 /* FunctionDeclaration */: { if (parent.name && isCallbackLike(checker, sourceFile, parent.name)) { return isLastParameter(parent, parameter, isFixAll); } return true; } - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused. return isLastParameter(parent, parameter, isFixAll); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: // Setter must have a parameter return false; default: @@ -140616,7 +145081,7 @@ var ts; var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { switch (container.kind) { - case 234 /* IfStatement */: + case 235 /* IfStatement */: if (container.elseStatement) { if (ts.isBlock(statement.parent)) { break; @@ -140627,8 +145092,8 @@ var ts; return; } // falls through - case 236 /* WhileStatement */: - case 237 /* ForStatement */: + case 237 /* WhileStatement */: + case 238 /* ForStatement */: changes.delete(sourceFile, container); return; } @@ -140701,7 +145166,7 @@ var ts; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; - if (typeNode.kind === 305 /* JSDocNullableType */) { + if (typeNode.kind === 306 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); @@ -140721,7 +145186,7 @@ var ts; if (!info) return; var typeNode = info.typeNode, type = info.type; - var fixedType = typeNode.kind === 305 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; + var fixedType = typeNode.kind === 306 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; doChange(changes, sourceFile, typeNode, fixedType, checker); }); } @@ -140738,22 +145203,22 @@ var ts; // NOTE: Some locations are not handled yet: // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments switch (node.kind) { - case 224 /* AsExpression */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 251 /* FunctionDeclaration */: - case 167 /* GetAccessor */: - case 171 /* IndexSignature */: - case 190 /* MappedType */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 168 /* SetAccessor */: - case 254 /* TypeAliasDeclaration */: - case 206 /* TypeAssertionExpression */: - case 249 /* VariableDeclaration */: + case 225 /* AsExpression */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 252 /* FunctionDeclaration */: + case 168 /* GetAccessor */: + case 172 /* IndexSignature */: + case 191 /* MappedType */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 169 /* SetAccessor */: + case 255 /* TypeAliasDeclaration */: + case 207 /* TypeAssertionExpression */: + case 250 /* VariableDeclaration */: return true; default: return false; @@ -140768,7 +145233,7 @@ var ts; (function (codefix) { var fixId = "fixMissingCallParentheses"; var errorCodes = [ - ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead.code, + ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -140814,7 +145279,7 @@ var ts; var fixId = "fixAwaitInSyncFunction"; var errorCodes = [ ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, - ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, + ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -140855,14 +145320,14 @@ var ts; } var insertBefore; switch (containingFunction.kind) { - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: insertBefore = containingFunction.name; break; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: insertBefore = ts.findChildOfKind(containingFunction, 97 /* FunctionKeyword */, sourceFile); break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: insertBefore = ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); break; default: @@ -141061,7 +145526,7 @@ var ts; var typeNode = ts.getTypeNodeIfAccessible(type, parent, program, host); if (typeNode) { // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags - var typeTag = ts.factory.createJSDocTypeTag(/*tagName*/ undefined, ts.factory.createJSDocTypeExpression(typeNode), /*comment*/ ""); + var typeTag = ts.factory.createJSDocTypeTag(/*tagName*/ undefined, ts.factory.createJSDocTypeExpression(typeNode), /*comment*/ undefined); addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]); } importAdder.writeFixes(changes); @@ -141195,13 +145660,13 @@ var ts; function annotate(changes, importAdder, sourceFile, declaration, type, program, host) { var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { - if (ts.isInJSFile(sourceFile) && declaration.kind !== 162 /* PropertySignature */) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 163 /* PropertySignature */) { var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration; if (!parent) { return; } var typeExpression = ts.factory.createJSDocTypeExpression(typeNode); - var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.factory.createJSDocReturnTag(/*tagName*/ undefined, typeExpression, "") : ts.factory.createJSDocTypeTag(/*tagName*/ undefined, typeExpression, ""); + var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.factory.createJSDocReturnTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined) : ts.factory.createJSDocTypeTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined); addJSDocTags(changes, sourceFile, parent, [typeTag]); } else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, ts.getEmitScriptTarget(program.getCompilerOptions()))) { @@ -141256,13 +145721,13 @@ var ts; else { var paramTags = ts.map(inferences, function (_a) { var name = _a.name, typeNode = _a.typeNode, isOptional = _a.isOptional; - return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!isOptional, ts.factory.createJSDocTypeExpression(typeNode), /* isNameFirst */ false, ""); + return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!isOptional, ts.factory.createJSDocTypeExpression(typeNode), /* isNameFirst */ false, /*comment*/ undefined); }); addJSDocTags(changes, sourceFile, signature, paramTags); } } function addJSDocTags(changes, sourceFile, parent, newTags) { - var comments = ts.mapDefined(parent.jsDoc, function (j) { return j.comment; }); + var comments = ts.flatMap(parent.jsDoc, function (j) { return typeof j.comment === "string" ? ts.factory.createJSDocText(j.comment) : j.comment; }); var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }); var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) { var merged = tryMergeJsdocTags(tag, newTag); @@ -141270,15 +145735,15 @@ var ts; oldTags[i] = merged; return !!merged; }); }); - var tag = ts.factory.createJSDocComment(comments.join("\n"), ts.factory.createNodeArray(__spreadArray(__spreadArray([], (oldTags || ts.emptyArray)), unmergedNewTags))); - var jsDocNode = parent.kind === 209 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent; + var tag = ts.factory.createJSDocComment(ts.factory.createNodeArray(ts.intersperse(comments, ts.factory.createJSDocText("\n"))), ts.factory.createNodeArray(__spreadArray(__spreadArray([], (oldTags || ts.emptyArray)), unmergedNewTags))); + var jsDocNode = parent.kind === 210 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent; jsDocNode.jsDoc = parent.jsDoc; jsDocNode.jsDocCache = parent.jsDocCache; changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag); } codefix.addJSDocTags = addJSDocTags; function getJsDocNodeForArrowFunction(signature) { - if (signature.parent.kind === 163 /* PropertyDeclaration */) { + if (signature.parent.kind === 164 /* PropertyDeclaration */) { return signature.parent; } return signature.parent.parent; @@ -141288,14 +145753,14 @@ var ts; return undefined; } switch (oldTag.kind) { - case 326 /* JSDocParameterTag */: { + case 330 /* JSDocParameterTag */: { var oldParam = oldTag; var newParam = newTag; return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText ? ts.factory.createJSDocParameterTag(/*tagName*/ undefined, newParam.name, /*isBracketed*/ false, newParam.typeExpression, newParam.isNameFirst, oldParam.comment) : undefined; } - case 327 /* JSDocReturnTag */: + case 331 /* JSDocReturnTag */: return ts.factory.createJSDocReturnTag(/*tagName*/ undefined, newTag.typeExpression, oldTag.comment); } } @@ -141320,19 +145785,19 @@ var ts; function getFunctionReferences(containingFunction, sourceFile, program, cancellationToken) { var searchToken; switch (containingFunction.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: searchToken = ts.findChildOfKind(containingFunction, 132 /* ConstructorKeyword */, sourceFile); break; - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: var parent = containingFunction.parent; searchToken = (ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent)) && ts.isIdentifier(parent.name) ? parent.name : containingFunction.name; break; - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: searchToken = containingFunction.name; break; } @@ -141474,24 +145939,24 @@ var ts; node = node.parent; } switch (node.parent.kind) { - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: inferTypeFromExpressionStatement(node, usage); break; - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: usage.isNumber = true; break; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: inferTypeFromPrefixUnaryExpression(node.parent, usage); break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: inferTypeFromBinaryExpression(node, node.parent, usage); break; - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: inferTypeFromSwitchStatementLabel(node.parent, usage); break; - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: if (node.parent.expression === node) { inferTypeFromCallExpression(node.parent, usage); } @@ -141499,20 +145964,20 @@ var ts; inferTypeFromContextualType(node, usage); } break; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: inferTypeFromPropertyAccessExpression(node.parent, usage); break; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: inferTypeFromPropertyElementExpression(node.parent, node, usage); break; - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: inferTypeFromPropertyAssignment(node.parent, usage); break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: inferTypeFromPropertyDeclaration(node.parent, usage); break; - case 249 /* VariableDeclaration */: { + case 250 /* VariableDeclaration */: { var _a = node.parent, name = _a.name, initializer = _a.initializer; if (node === name) { if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. @@ -141634,7 +146099,7 @@ var ts; case 56 /* BarBarToken */: case 60 /* QuestionQuestionToken */: if (node === parent.left && - (node.parent.parent.kind === 249 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + (node.parent.parent.kind === 250 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { // var x = x || {}; // TODO: use getFalsyflagsOfType addCandidateType(usage, checker.getTypeAtLocation(parent.right)); @@ -141662,7 +146127,7 @@ var ts; } } calculateUsageOfNode(parent, call.return_); - if (parent.kind === 203 /* CallExpression */) { + if (parent.kind === 204 /* CallExpression */) { (usage.calls || (usage.calls = [])).push(call); } else { @@ -141765,7 +146230,7 @@ var ts; var anon = anons_1[_i]; for (var _a = 0, _b = checker.getPropertiesOfType(anon); _a < _b.length; _a++) { var p = _b[_a]; - props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration)); + props.add(p.name, p.valueDeclaration ? checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration) : checker.getAnyType()); } calls.push.apply(calls, checker.getSignaturesOfType(anon, 0 /* Call */)); constructs.push.apply(constructs, checker.getSignaturesOfType(anon, 1 /* Construct */)); @@ -141906,12 +146371,13 @@ var ts; if (!usageParam) { break; } - var genericParamType = checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration); + var genericParamType = genericParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration) : checker.getAnyType(); var elementType = isRest && checker.getElementTypeOfArrayType(genericParamType); if (elementType) { genericParamType = elementType; } - var targetType = usageParam.type || checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration); + var targetType = usageParam.type + || (usageParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration) : checker.getAnyType()); types.push.apply(types, inferTypeParameters(genericParamType, targetType, typeParameter)); } var genericReturn = checker.getReturnTypeOfSignature(genericSig); @@ -141925,7 +146391,7 @@ var ts; function getSignatureFromCalls(calls) { var parameters = []; var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; })); - var _loop_14 = function (i) { + var _loop_15 = function (i) { var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); })); if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) { @@ -141934,7 +146400,7 @@ var ts; parameters.push(symbol); }; for (var i = 0; i < length; i++) { - _loop_14(i); + _loop_15(i); } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); // TODO: GH#18217 @@ -142105,8 +146571,8 @@ var ts; var ambient = !!(enclosingDeclaration.flags & 8388608 /* Ambient */); var quotePreference = ts.getQuotePreference(sourceFile, preferences); switch (declaration.kind) { - case 162 /* PropertySignature */: - case 163 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 164 /* PropertyDeclaration */: var flags = quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : undefined; var typeNode = checker.typeToTypeNode(type, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); if (importAdder) { @@ -142120,8 +146586,8 @@ var ts; /*decorators*/ undefined, modifiers, name, optional ? ts.factory.createToken(57 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: { + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: { var typeNode_1 = checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); var allAccessors = ts.getAllAccessorDeclarations(declarations, declaration); var orderedAccessors = allAccessors.secondAccessor @@ -142150,8 +146616,8 @@ var ts; } break; } - case 164 /* MethodSignature */: - case 165 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 166 /* MethodDeclaration */: // The signature for the implementation appears as an entry in `signatures` iff // there is only one signature. // If there are overloads and an implementation signature, it appears as an @@ -142181,7 +146647,7 @@ var ts; } else { ts.Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count"); - addClassElement(createMethodImplementingSignatures(signatures, name, optional, modifiers, quotePreference)); + addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference)); } } break; @@ -142197,7 +146663,7 @@ var ts; var checker = program.getTypeChecker(); var scriptTarget = ts.getEmitScriptTarget(program.getCompilerOptions()); var flags = 1 /* NoTruncation */ | 1073741824 /* NoUndefinedOptionalParameterType */ | 256 /* SuppressAnyReturnType */ | (quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0); - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 165 /* MethodDeclaration */, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 166 /* MethodDeclaration */, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); if (!signatureDeclaration) { return undefined; } @@ -142281,7 +146747,7 @@ var ts; var type = isJs || contextualType === undefined ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker); - if (kind === 165 /* MethodDeclaration */) { + if (kind === 166 /* MethodDeclaration */) { return ts.factory.createMethodDeclaration( /*decorators*/ undefined, modifiers, asteriskToken, name, /*questionToken*/ undefined, typeParameters, parameters, type, ts.isInterfaceDeclaration(contextNode) ? undefined : createStubbedMethodBody(quotePreference)); @@ -142317,7 +146783,7 @@ var ts; } return parameters; } - function createMethodImplementingSignatures(signatures, name, optional, modifiers, quotePreference) { + function createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference) { /** This is *a* signature with the maximal number of arguments, * such that if there is a "maximal" signature without rest arguments, * this is one of them. @@ -142348,8 +146814,13 @@ var ts; parameters.push(restParameter); } return createStubbedMethod(modifiers, name, optional, - /*typeParameters*/ undefined, parameters, - /*returnType*/ undefined, quotePreference); + /*typeParameters*/ undefined, parameters, getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), quotePreference); + } + function getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration) { + if (ts.length(signatures)) { + var type = checker.getUnionType(ts.map(signatures, checker.getReturnTypeOfSignature)); + return checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); + } } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference) { return ts.factory.createMethodDeclaration( @@ -142476,13 +146947,13 @@ var ts; if (ts.isClassLike(container)) { var modifierFlags = ts.getEffectiveModifierFlags(declaration); if (ts.isSourceFileJS(file)) { - var modifiers = createModifiers(modifierFlags); + var modifiers = ts.createModifiers(modifierFlags); accessorModifiers = modifiers; fieldModifiers = modifiers; } else { - accessorModifiers = createModifiers(prepareModifierFlagsForAccessor(modifierFlags)); - fieldModifiers = createModifiers(prepareModifierFlagsForField(modifierFlags)); + accessorModifiers = ts.createModifiers(prepareModifierFlagsForAccessor(modifierFlags)); + fieldModifiers = ts.createModifiers(prepareModifierFlagsForField(modifierFlags)); } } updateFieldDeclaration(changeTracker, file, declaration, type, fieldName, fieldModifiers); @@ -142517,9 +146988,6 @@ var ts; var leftHead = isStatic ? container.name : ts.factory.createThis(); // TODO: GH#18217 return ts.isIdentifier(fieldName) ? ts.factory.createPropertyAccessExpression(leftHead, fieldName) : ts.factory.createElementAccessExpression(leftHead, ts.factory.createStringLiteralFromNode(fieldName)); } - function createModifiers(modifierFlags) { - return modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; - } function prepareModifierFlagsForAccessor(modifierFlags) { modifierFlags &= ~64 /* Readonly */; // avoid Readonly modifier because it will convert to get accessor modifierFlags &= ~8 /* Private */; @@ -142564,7 +147032,7 @@ var ts; isStatic: ts.hasStaticModifier(declaration), isReadonly: ts.hasEffectiveReadonlyModifier(declaration), type: getDeclarationType(declaration, program), - container: declaration.kind === 160 /* Parameter */ ? declaration.parent.parent : declaration.parent, + container: declaration.kind === 161 /* Parameter */ ? declaration.parent.parent : declaration.parent, originalName: declaration.name.text, declaration: declaration, fieldName: fieldName, @@ -142654,7 +147122,7 @@ var ts; if (!superSymbol) break; var symbol = superSymbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(superSymbol) : superSymbol; - var superDecl = ts.find(symbol.declarations, ts.isClassLike); + var superDecl = symbol.declarations && ts.find(symbol.declarations, ts.isClassLike); if (!superDecl) break; res.push(superDecl); @@ -142700,7 +147168,7 @@ var ts; }); function getActionsForUsageOfInvalidImport(context) { var sourceFile = context.sourceFile; - var targetKind = ts.Diagnostics.This_expression_is_not_callable.code === context.errorCode ? 203 /* CallExpression */ : 204 /* NewExpression */; + var targetKind = ts.Diagnostics.This_expression_is_not_callable.code === context.errorCode ? 204 /* CallExpression */ : 205 /* NewExpression */; var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind; }); if (!node) { return []; @@ -143034,7 +147502,7 @@ var ts; function getImportTypeNode(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); ts.Debug.assert(token.kind === 99 /* ImportKeyword */, "This token should be an ImportKeyword"); - ts.Debug.assert(token.parent.kind === 195 /* ImportType */, "Token parent should be an ImportType"); + ts.Debug.assert(token.parent.kind === 196 /* ImportType */, "Token parent should be an ImportType"); return token.parent; } function doChange(changes, sourceFile, importType) { @@ -143301,7 +147769,7 @@ var ts; var token = ts.getTokenAtPosition(sourceFile, pos); var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(token); - if (symbol) { + if (symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) { return symbol.valueDeclaration.parent.parent; } } @@ -143496,23 +147964,23 @@ var ts; return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_find_export_statement) }; } var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol; - var flags = ts.getSyntacticModifierFlags(exportNode); + var flags = ts.getSyntacticModifierFlags(exportNode) || ((ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) ? 513 /* ExportDefault */ : 0 /* None */); var wasDefault = !!(flags & 512 /* Default */); // If source file already has a default export, don't offer refactor. if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.This_file_already_has_a_default_export) }; } switch (exportNode.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 256 /* ModuleDeclaration */: { + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 257 /* ModuleDeclaration */: { var node = exportNode; return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; } - case 232 /* VariableStatement */: { + case 233 /* VariableStatement */: { var vs = exportNode; // Must be `export const x = something;`. if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { @@ -143524,6 +147992,11 @@ var ts; ts.Debug.assert(!wasDefault, "Can't have a default flag here"); return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; } + case 267 /* ExportAssignment */: { + var node = exportNode; + var exp = node.expression; + return node.isExportEquals ? undefined : { exportNode: node, exportName: exp, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol }; + } default: return undefined; } @@ -143535,17 +148008,24 @@ var ts; function changeExport(exportingSourceFile, _a, changes, checker) { var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; if (wasDefault) { - changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 87 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + if (ts.isExportAssignment(exportNode) && !exportNode.isExportEquals) { + var exp = exportNode.expression; + var spec = makeExportSpecifier(exp.text, exp.text); + changes.replaceNode(exportingSourceFile, exportNode, ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports([spec]))); + } + else { + changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 87 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + } } else { var exportKeyword = ts.Debug.checkDefined(ts.findModifier(exportNode, 92 /* ExportKeyword */), "Should find an export keyword in modifier list"); switch (exportNode.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.factory.createToken(87 /* DefaultKeyword */)); break; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // If 'x' isn't used in this file and doesn't have type definition, `export const x = 0;` --> `export default 0;` var decl = ts.first(exportNode.declarationList.declarations); if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile) && !decl.type) { @@ -143554,15 +148034,15 @@ var ts; break; } // falls through - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 256 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 257 /* ModuleDeclaration */: // `export type T = number;` -> `type T = number; export default T;` changes.deleteModifier(exportingSourceFile, exportKeyword); changes.insertNodeAfter(exportingSourceFile, exportNode, ts.factory.createExportDefault(ts.factory.createIdentifier(exportName.text))); break; default: - ts.Debug.assertNever(exportNode, "Unexpected exportNode kind " + exportNode.kind); + ts.Debug.fail("Unexpected exportNode kind " + exportNode.kind); } } } @@ -143583,18 +148063,18 @@ var ts; function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { var parent = ref.parent; switch (parent.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: // `a.default` --> `a.foo` changes.replaceNode(importingSourceFile, ref, ts.factory.createIdentifier(exportName)); break; - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: { + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: { var spec = parent; // `default as foo` --> `foo`, `default as bar` --> `foo as bar` changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); break; } - case 262 /* ImportClause */: { + case 263 /* ImportClause */: { var clause = parent; ts.Debug.assert(clause.name === ref, "Import clause name should match provided ref"); var spec = makeImportSpecifier(exportName, ref.text); @@ -143603,7 +148083,7 @@ var ts; // `import foo from "./a";` --> `import { foo } from "./a";` changes.replaceNode(importingSourceFile, ref, ts.factory.createNamedImports([spec])); } - else if (namedBindings.kind === 263 /* NamespaceImport */) { + else if (namedBindings.kind === 264 /* NamespaceImport */) { // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";` changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; @@ -143624,11 +148104,11 @@ var ts; function changeNamedToDefaultImport(importingSourceFile, ref, changes) { var parent = ref.parent; switch (parent.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: // `a.foo` --> `a.default` changes.replaceNode(importingSourceFile, ref, ts.factory.createIdentifier("default")); break; - case 265 /* ImportSpecifier */: { + case 266 /* ImportSpecifier */: { // `import { foo } from "./a";` --> `import foo from "./a";` // `import { foo as bar } from "./a";` --> `import bar from "./a";` var defaultImport = ts.factory.createIdentifier(parent.name.text); @@ -143641,7 +148121,7 @@ var ts; } break; } - case 270 /* ExportSpecifier */: { + case 271 /* ExportSpecifier */: { // `export { foo } from "./a";` --> `export { default as foo } from "./a";` // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` // `export { foo as default } from "./a";` --> `export { default } from "./a";` @@ -143687,14 +148167,16 @@ var ts; if (!info) return ts.emptyArray; if (!refactor.isRefactorErrorInfo(info)) { - var namespaceImport = info.kind === 263 /* NamespaceImport */; + var namespaceImport = info.kind === 264 /* NamespaceImport */; var action = namespaceImport ? namespaceToNamedAction : namedToNamespaceAction; return [{ name: refactorName, description: action.description, actions: [action] }]; } if (context.preferences.provideRefactorNotApplicableReason) { return [ - { name: refactorName, description: namespaceToNamedAction.description, actions: [__assign(__assign({}, namespaceToNamedAction), { notApplicableReason: info.error })] }, - { name: refactorName, description: namedToNamespaceAction.description, actions: [__assign(__assign({}, namedToNamespaceAction), { notApplicableReason: info.error })] } + { name: refactorName, description: namespaceToNamedAction.description, + actions: [__assign(__assign({}, namespaceToNamedAction), { notApplicableReason: info.error })] }, + { name: refactorName, description: namedToNamespaceAction.description, + actions: [__assign(__assign({}, namedToNamespaceAction), { notApplicableReason: info.error })] } ]; } return ts.emptyArray; @@ -143729,7 +148211,7 @@ var ts; } function doChange(sourceFile, program, changes, toConvert) { var checker = program.getTypeChecker(); - if (toConvert.kind === 263 /* NamespaceImport */) { + if (toConvert.kind === 264 /* NamespaceImport */) { doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); } else { @@ -143794,7 +148276,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_15 = function (element) { + var _loop_16 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(namespaceImportName), propertyName); @@ -143813,7 +148295,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_15(element); + _loop_16(element); } changes.replaceNode(sourceFile, toConvert, ts.factory.createNamespaceImport(ts.factory.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -144130,27 +148612,27 @@ var ts; var lastDeclaration = signatureDecls[signatureDecls.length - 1]; var updated = lastDeclaration; switch (lastDeclaration.kind) { - case 164 /* MethodSignature */: { + case 165 /* MethodSignature */: { updated = ts.factory.updateMethodSignature(lastDeclaration, lastDeclaration.modifiers, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); break; } - case 165 /* MethodDeclaration */: { + case 166 /* MethodDeclaration */: { updated = ts.factory.updateMethodDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.questionToken, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } - case 169 /* CallSignature */: { + case 170 /* CallSignature */: { updated = ts.factory.updateCallSignature(lastDeclaration, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); break; } - case 166 /* Constructor */: { + case 167 /* Constructor */: { updated = ts.factory.updateConstructorDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.body); break; } - case 170 /* ConstructSignature */: { + case 171 /* ConstructSignature */: { updated = ts.factory.updateConstructSignature(lastDeclaration, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type); break; } - case 251 /* FunctionDeclaration */: { + case 252 /* FunctionDeclaration */: { updated = ts.factory.updateFunctionDeclaration(lastDeclaration, lastDeclaration.decorators, lastDeclaration.modifiers, lastDeclaration.asteriskToken, lastDeclaration.name, lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, lastDeclaration.body); break; } @@ -144202,12 +148684,12 @@ var ts; } function isConvertableSignatureDeclaration(d) { switch (d.kind) { - case 164 /* MethodSignature */: - case 165 /* MethodDeclaration */: - case 169 /* CallSignature */: - case 166 /* Constructor */: - case 170 /* ConstructSignature */: - case 251 /* FunctionDeclaration */: + case 165 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 170 /* CallSignature */: + case 167 /* Constructor */: + case 171 /* ConstructSignature */: + case 252 /* FunctionDeclaration */: return true; } return false; @@ -144347,7 +148829,6 @@ var ts; }; } } - // Skip these since we don't have a way to report errors yet if (refactor.refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { if (constantExtraction.errors.length === 0) { // Don't issue refactorings with duplicated names. @@ -144479,24 +148960,28 @@ var ts; /** * getRangeToExtract takes a span inside a text file and returns either an expression or an array * of statements representing the minimum set of nodes needed to extract the entire span. This - * process may fail, in which case a set of errors is returned instead (these are currently - * not shown to the user, but can be used by us diagnostically) + * process may fail, in which case a set of errors is returned instead. These errors are shown to + * users if they have the provideRefactorNotApplicableReason option set. */ // exported only for tests - function getRangeToExtract(sourceFile, span, considerEmptySpans) { - if (considerEmptySpans === void 0) { considerEmptySpans = true; } + function getRangeToExtract(sourceFile, span, invoked) { + if (invoked === void 0) { invoked = true; } var length = span.length; - if (length === 0 && !considerEmptySpans) { + if (length === 0 && !invoked) { return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] }; } - var cursorRequest = length === 0 && considerEmptySpans; + var cursorRequest = length === 0 && invoked; + var startToken = ts.findFirstNonJsxWhitespaceToken(sourceFile, span.start); + var endToken = ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)); + /* If the refactoring command is invoked through a keyboard action it's safe to assume that the user is actively looking for + refactoring actions at the span location. As they may not know the exact range that will trigger a refactoring, we expand the + searched span to cover a real node range making it more likely that something useful will show up. */ + var adjustedSpan = startToken && endToken && invoked ? getAdjustedSpanFromNodes(startToken, endToken, sourceFile) : span; // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span. // This may fail (e.g. you select two statements in the root of a source file) - var startToken = ts.getTokenAtPosition(sourceFile, span.start); - var start = cursorRequest ? getExtractableParent(startToken) : ts.getParentNodeInSpan(startToken, sourceFile, span); + var start = cursorRequest ? getExtractableParent(startToken) : ts.getParentNodeInSpan(startToken, sourceFile, adjustedSpan); // Do the same for the ending position - var endToken = ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)); - var end = cursorRequest ? start : ts.getParentNodeInSpan(endToken, sourceFile, span); + var end = cursorRequest ? start : ts.getParentNodeInSpan(endToken, sourceFile, adjustedSpan); var declarations = []; // We'll modify these flags as we walk the tree to collect data // about what things need to be done as part of the extraction. @@ -144505,6 +148990,9 @@ var ts; // cannot find either start or end node return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } + if (ts.isJSDoc(start)) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractJSDoc)] }; + } if (start.parent !== end.parent) { // start and end nodes belong to different subtrees return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; @@ -144539,9 +149027,6 @@ var ts; } return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations } }; } - if (ts.isJSDoc(start)) { - return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractJSDoc)] }; - } if (ts.isReturnStatement(start) && !start.expression) { // Makes no sense to extract an expression-less return statement. return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; @@ -144594,20 +149079,20 @@ var ts; function checkForStaticContext(nodeToCheck, containingClass) { var current = nodeToCheck; while (current !== containingClass) { - if (current.kind === 163 /* PropertyDeclaration */) { + if (current.kind === 164 /* PropertyDeclaration */) { if (ts.hasSyntacticModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 160 /* Parameter */) { + else if (current.kind === 161 /* Parameter */) { var ctorOrMethod = ts.getContainingFunction(current); - if (ctorOrMethod.kind === 166 /* Constructor */) { + if (ctorOrMethod.kind === 167 /* Constructor */) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 165 /* MethodDeclaration */) { + else if (current.kind === 166 /* MethodDeclaration */) { if (ts.hasSyntacticModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } @@ -144650,7 +149135,7 @@ var ts; return true; } if (ts.isDeclaration(node)) { - var declaringNode = (node.kind === 249 /* VariableDeclaration */) ? node.parent.parent : node; + var declaringNode = (node.kind === 250 /* VariableDeclaration */) ? node.parent.parent : node; if (ts.hasSyntacticModifier(declaringNode, 1 /* Export */)) { // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! @@ -144662,16 +149147,16 @@ var ts; } // Some things can't be extracted in certain situations switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); return true; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; case 105 /* SuperKeyword */: // For a super *constructor call*, we have to be extracting the entire class, // but a super *method call* simply implies a 'this' reference - if (node.parent.kind === 203 /* CallExpression */) { + if (node.parent.kind === 204 /* CallExpression */) { // Super constructor call var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { @@ -144683,7 +149168,7 @@ var ts; rangeFacts |= RangeFacts.UsesThis; } break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: // check if arrow function uses this ts.forEachChild(node, function check(n) { if (ts.isThis(n)) { @@ -144697,39 +149182,39 @@ var ts; } }); // falls through - case 252 /* ClassDeclaration */: - case 251 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { // You cannot extract global declarations (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); } // falls through - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // do not dive into functions or classes return false; } var savedPermittedJumps = permittedJumps; switch (node.kind) { - case 234 /* IfStatement */: + case 235 /* IfStatement */: permittedJumps = 0 /* None */; break; - case 247 /* TryStatement */: + case 248 /* TryStatement */: // forbid all jumps inside try blocks permittedJumps = 0 /* None */; break; - case 230 /* Block */: - if (node.parent && node.parent.kind === 247 /* TryStatement */ && node.parent.finallyBlock === node) { + case 231 /* Block */: + if (node.parent && node.parent.kind === 248 /* TryStatement */ && node.parent.finallyBlock === node) { // allow unconditional returns from finally blocks permittedJumps = 4 /* Return */; } break; - case 285 /* DefaultClause */: - case 284 /* CaseClause */: + case 286 /* DefaultClause */: + case 285 /* CaseClause */: // allow unlabeled break inside case clauses permittedJumps |= 1 /* Break */; break; @@ -144741,19 +149226,19 @@ var ts; break; } switch (node.kind) { - case 187 /* ThisType */: + case 188 /* ThisType */: case 107 /* ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; break; - case 245 /* LabeledStatement */: { + case 246 /* LabeledStatement */: { var label = node.label; (seenLabels || (seenLabels = [])).push(label.escapedText); ts.forEachChild(node, visit); seenLabels.pop(); break; } - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: { + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: { var label = node.label; if (label) { if (!ts.contains(seenLabels, label.escapedText)) { @@ -144762,20 +149247,20 @@ var ts; } } else { - if (!(permittedJumps & (node.kind === 241 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + if (!(permittedJumps & (node.kind === 242 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { // attempt to break or continue in a forbidden context (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); } } break; } - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: rangeFacts |= RangeFacts.IsGenerator; break; - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: if (permittedJumps & 4 /* Return */) { rangeFacts |= RangeFacts.HasReturn; } @@ -144792,6 +149277,18 @@ var ts; } } extractSymbol.getRangeToExtract = getRangeToExtract; + /** + * Includes the final semicolon so that the span covers statements in cases where it would otherwise + * only cover the declaration list. + */ + function getAdjustedSpanFromNodes(startNode, endNode, sourceFile) { + var start = startNode.getStart(sourceFile); + var end = endNode.getEnd(); + if (sourceFile.text.charCodeAt(end) === 59 /* semicolon */) { + end++; + } + return { start: start, length: end - start }; + } function getStatementOrExpressionRange(node) { if (ts.isStatement(node)) { return [node]; @@ -144829,7 +149326,7 @@ var ts; while (true) { current = current.parent; // A function parameter's initializer is actually in the outer scope, not the function declaration - if (current.kind === 160 /* Parameter */) { + if (current.kind === 161 /* Parameter */) { // Skip all the way to the outer scope of the function that declared this parameter current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; } @@ -144840,7 +149337,7 @@ var ts; // * Module/namespace or source file if (isScope(current)) { scopes.push(current); - if (current.kind === 297 /* SourceFile */) { + if (current.kind === 298 /* SourceFile */) { return scopes; } } @@ -144930,32 +149427,32 @@ var ts; } function getDescriptionForFunctionLikeDeclaration(scope) { switch (scope.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return "constructor"; - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: return scope.name ? "function '" + scope.name.text + "'" : ts.ANONYMOUS; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return "arrow function"; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return "method '" + scope.name.getText() + "'"; - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: return "'get " + scope.name.getText() + "'"; - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: return "'set " + scope.name.getText() + "'"; default: throw ts.Debug.assertNever(scope, "Unexpected scope kind " + scope.kind); } } function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 252 /* ClassDeclaration */ + return scope.kind === 253 /* ClassDeclaration */ ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration" : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; } function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 257 /* ModuleBlock */ + return scope.kind === 258 /* ModuleBlock */ ? "namespace '" + scope.parent.name.getText() + "'" : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; } @@ -145244,7 +149741,7 @@ var ts; var localReference = ts.factory.createIdentifier(localNameText); changeTracker.replaceNode(context.file, node, localReference); } - else if (node.parent.kind === 233 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + else if (node.parent.kind === 234 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { // If the parent is an expression statement and the target scope is the immediately enclosing one, // replace the statement with the declaration. var newVariableStatement = ts.factory.createVariableStatement( @@ -145263,7 +149760,7 @@ var ts; changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); } // Consume - if (node.parent.kind === 233 /* ExpressionStatement */) { + if (node.parent.kind === 234 /* ExpressionStatement */) { // If the parent is an expression statement, delete it. changeTracker.delete(context.file, node.parent); } @@ -145590,7 +150087,7 @@ var ts; var scope = scopes_1[_i]; usagesPerScope.push({ usages: new ts.Map(), typeParameterUsages: new ts.Map(), substitutions: new ts.Map() }); substitutionsPerScope.push(new ts.Map()); - functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 251 /* FunctionDeclaration */ + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 252 /* FunctionDeclaration */ ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] : []); var constantErrors = []; @@ -145653,7 +150150,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_16 = function (i) { + var _loop_17 = 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 @@ -145693,7 +150190,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_16(i); + _loop_17(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -145909,30 +150406,30 @@ var ts; function isExtractableExpression(node) { var parent = node.parent; switch (parent.kind) { - case 291 /* EnumMember */: + case 292 /* EnumMember */: return false; } switch (node.kind) { case 10 /* StringLiteral */: - return parent.kind !== 261 /* ImportDeclaration */ && - parent.kind !== 265 /* ImportSpecifier */; - case 220 /* SpreadElement */: - case 196 /* ObjectBindingPattern */: - case 198 /* BindingElement */: + return parent.kind !== 262 /* ImportDeclaration */ && + parent.kind !== 266 /* ImportSpecifier */; + case 221 /* SpreadElement */: + case 197 /* ObjectBindingPattern */: + case 199 /* BindingElement */: return false; case 78 /* Identifier */: - return parent.kind !== 198 /* BindingElement */ && - parent.kind !== 265 /* ImportSpecifier */ && - parent.kind !== 270 /* ExportSpecifier */; + return parent.kind !== 199 /* BindingElement */ && + parent.kind !== 266 /* ImportSpecifier */ && + parent.kind !== 271 /* ExportSpecifier */; } return true; } function isBlockLike(node) { switch (node.kind) { - case 230 /* Block */: - case 297 /* SourceFile */: - case 257 /* ModuleBlock */: - case 284 /* CaseClause */: + case 231 /* Block */: + case 298 /* SourceFile */: + case 258 /* ModuleBlock */: + case 285 /* CaseClause */: return true; default: return false; @@ -146074,7 +150571,7 @@ var ts; if (ts.isTypeReferenceNode(node)) { if (ts.isIdentifier(node.typeName)) { var symbol = checker.resolveName(node.typeName.text, node.typeName, 262144 /* TypeParameter */, /* excludeGlobals */ true); - if (symbol) { + if (symbol === null || symbol === void 0 ? void 0 : symbol.declarations) { var declaration = ts.cast(ts.first(symbol.declarations), ts.isTypeParameterDeclaration); if (rangeContainsSkipTrivia(statement, declaration, file) && !rangeContainsSkipTrivia(selection, declaration, file)) { ts.pushIfUnique(result, declaration); @@ -146097,7 +150594,7 @@ var ts; else if (ts.isTypeQueryNode(node)) { if (ts.isIdentifier(node.exprName)) { var symbol = checker.resolveName(node.exprName.text, node.exprName, 111551 /* Value */, /* excludeGlobals */ false); - if (symbol && rangeContainsSkipTrivia(statement, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) { + if ((symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration) && rangeContainsSkipTrivia(statement, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) { return true; } } @@ -146317,11 +150814,11 @@ var ts; } function isPureImport(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return true; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return !ts.hasSyntacticModifier(node, 1 /* Export */); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); default: return false; @@ -146382,10 +150879,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_17 = function (sourceFile) { + var _loop_18 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_18 = function (statement) { + var _loop_19 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -146407,22 +150904,22 @@ var ts; }; for (var _b = 0, _c = sourceFile.statements; _b < _c.length; _b++) { var statement = _c[_b]; - _loop_18(statement); + _loop_19(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_17(sourceFile); + _loop_18(sourceFile); } } function getNamespaceLikeImport(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 263 /* NamespaceImport */ ? + case 262 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 264 /* NamespaceImport */ ? node.importClause.namedBindings.name : undefined; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return node.name; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return ts.tryCast(node.name, ts.isIdentifier); default: return ts.Debug.assertNever(node, "Unexpected node kind " + node.kind); @@ -146453,20 +150950,20 @@ var ts; var newNamespaceId = ts.factory.createIdentifier(newNamespaceName); var newModuleString = ts.factory.createStringLiteral(newModuleSpecifier); switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamespaceImport(newNamespaceId)), newModuleString); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return ts.factory.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, newNamespaceId, ts.factory.createExternalModuleReference(newModuleString)); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return ts.factory.createVariableDeclaration(newNamespaceId, /*exclamationToken*/ undefined, /*type*/ undefined, createRequireCall(newModuleString)); default: return ts.Debug.assertNever(node, "Unexpected node kind " + node.kind); } } function moduleSpecifierFromImport(i) { - return (i.kind === 261 /* ImportDeclaration */ ? i.moduleSpecifier - : i.kind === 260 /* ImportEqualsDeclaration */ ? i.moduleReference.expression + return (i.kind === 262 /* ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 261 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]); } function forEachImportInStatement(statement, cb) { @@ -146536,15 +151033,15 @@ var ts; } function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { switch (importDecl.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); break; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: if (isUnused(importDecl.name)) { changes.delete(sourceFile, importDecl); } break; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); break; default: @@ -146557,7 +151054,7 @@ var ts; var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; var defaultUnused = !name || isUnused(name); var namedBindingsUnused = !namedBindings || - (namedBindings.kind === 263 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); + (namedBindings.kind === 264 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every(function (e) { return isUnused(e.name); })); if (defaultUnused && namedBindingsUnused) { changes.delete(sourceFile, importDecl); } @@ -146569,7 +151066,7 @@ var ts; if (namedBindingsUnused) { changes.replaceNode(sourceFile, importDecl.importClause, ts.factory.updateImportClause(importDecl.importClause, importDecl.importClause.isTypeOnly, name, /*namedBindings*/ undefined)); } - else if (namedBindings.kind === 264 /* NamedImports */) { + else if (namedBindings.kind === 265 /* NamedImports */) { for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { var element = _b[_i]; if (isUnused(element.name)) @@ -146587,9 +151084,9 @@ var ts; changes.delete(sourceFile, name); } break; - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: break; - case 196 /* ObjectBindingPattern */: + case 197 /* ObjectBindingPattern */: if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); } @@ -146617,6 +151114,9 @@ var ts; var oldFileNamedImports = []; var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`. newFileImportsFromOldFile.forEach(function (symbol) { + if (!symbol.declarations) { + return; + } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; if (!isTopLevelDeclaration(decl)) @@ -146716,14 +151216,14 @@ var ts; // Below should all be utilities function isInImport(decl) { switch (decl.kind) { - case 260 /* ImportEqualsDeclaration */: - case 265 /* ImportSpecifier */: - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: + case 261 /* ImportEqualsDeclaration */: + case 266 /* ImportSpecifier */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: return true; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return isVariableDeclarationInImport(decl); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); default: return false; @@ -146735,7 +151235,7 @@ var ts; } function filterImport(i, moduleSpecifier, keep) { switch (i.kind) { - case 261 /* ImportDeclaration */: { + case 262 /* ImportDeclaration */: { var clause = i.importClause; if (!clause) return undefined; @@ -146745,9 +151245,9 @@ var ts; ? ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImport, namedBindings), moduleSpecifier) : undefined; } - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return keep(i.name) ? i : undefined; - case 249 /* VariableDeclaration */: { + case 250 /* VariableDeclaration */: { var name = filterBindingName(i.name, keep); return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; } @@ -146756,7 +151256,7 @@ var ts; } } function filterNamedBindings(namedBindings, keep) { - if (namedBindings.kind === 263 /* NamespaceImport */) { + if (namedBindings.kind === 264 /* NamespaceImport */) { return keep(namedBindings.name) ? namedBindings : undefined; } else { @@ -146768,9 +151268,9 @@ var ts; switch (name.kind) { case 78 /* Identifier */: return keep(name) ? name : undefined; - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: return name; - case 196 /* ObjectBindingPattern */: { + case 197 /* ObjectBindingPattern */: { // We can't handle nested destructurings or property names well here, so just copy them all. var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); return newElements.length ? ts.factory.createObjectBindingPattern(newElements) : undefined; @@ -146827,13 +151327,13 @@ var ts; } function isNonVariableTopLevelDeclaration(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 261 /* ImportEqualsDeclaration */: return true; default: return false; @@ -146841,17 +151341,17 @@ var ts; } function forEachTopLevelDeclaration(statement, cb) { switch (statement.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 261 /* ImportEqualsDeclaration */: return cb(statement); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return ts.firstDefined(statement.declarationList.declarations, function (decl) { return forEachTopLevelDeclarationInBindingName(decl.name, cb); }); - case 233 /* ExpressionStatement */: { + case 234 /* ExpressionStatement */: { var expression = statement.expression; return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) @@ -146863,8 +151363,8 @@ var ts; switch (name.kind) { case 78 /* Identifier */: return cb(ts.cast(name.parent, function (x) { return ts.isVariableDeclaration(x) || ts.isBindingElement(x); })); - case 197 /* ArrayBindingPattern */: - case 196 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: return ts.firstDefined(name.elements, function (em) { return ts.isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb); }); default: return ts.Debug.assertNever(name, "Unexpected name kind " + name.kind); @@ -146875,9 +151375,9 @@ var ts; } function getTopLevelDeclarationStatement(d) { switch (d.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return d.parent.parent; - case 198 /* BindingElement */: + case 199 /* BindingElement */: return getTopLevelDeclarationStatement(ts.cast(d.parent.parent, function (p) { return ts.isVariableDeclaration(p) || ts.isBindingElement(p); })); default: return d; @@ -146910,23 +151410,23 @@ var ts; function addEs6Export(d) { var modifiers = ts.concatenate([ts.factory.createModifier(92 /* ExportKeyword */)], d.modifiers); switch (d.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return ts.factory.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return ts.factory.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return ts.factory.updateVariableStatement(d, modifiers, d.declarationList); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return ts.factory.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return ts.factory.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return ts.factory.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return ts.factory.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return ts.factory.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.isTypeOnly, d.name, d.moduleReference); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(d, "Unexpected declaration kind " + d.kind); @@ -146937,18 +151437,18 @@ var ts; } function getNamesToExportInCommonJS(decl) { switch (decl.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: return [decl.name.text]; // TODO: GH#18217 - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 261 /* ImportEqualsDeclaration */: return ts.emptyArray; - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return ts.Debug.fail("Can't export an ExpressionStatement"); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: return ts.Debug.assertNever(decl, "Unexpected decl kind " + decl.kind); @@ -147117,13 +151617,13 @@ var ts; return { edits: [] }; // TODO: GH#30113 } function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) { - var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); - changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ", - // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter - indentation: 0, - leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include - }); + var signature = groupedReferences.signature; + var newFunctionDeclarationParams = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); + if (signature) { + var newSignatureParams = ts.map(createNewParameters(signature, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); + replaceParameters(signature, newSignatureParams); + } + replaceParameters(functionDeclaration, newFunctionDeclarationParams); var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); }); for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) { var call = functionCalls_1[_i]; @@ -147132,6 +151632,15 @@ var ts; changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include }); } } + function replaceParameters(declarationOrSignature, parameterDeclarations) { + changes.replaceNodeRangeWithNodes(sourceFile, ts.first(declarationOrSignature.parameters), ts.last(declarationOrSignature.parameters), parameterDeclarations, { + joiner: ", ", + // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter + indentation: 0, + leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include + }); + } } function getGroupedReferences(functionDeclaration, program, cancellationToken) { var functionNames = getFunctionNames(functionDeclaration); @@ -147150,12 +151659,38 @@ var ts; var functionSymbols = ts.map(functionNames, getSymbolTargetAtLocation); var classSymbols = ts.map(classNames, getSymbolTargetAtLocation); var isConstructor = ts.isConstructorDeclaration(functionDeclaration); + var contextualSymbols = ts.map(functionNames, function (name) { return getSymbolForContextualType(name, checker); }); for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) { var entry = referenceEntries_1[_i]; - if (entry.kind !== 1 /* Node */) { + if (entry.kind === 0 /* Span */) { groupedReferences.valid = false; continue; } + /* Declarations in object literals may be implementations of method signatures which have a different symbol from the declaration + For example: + interface IFoo { m(a: number): void } + const foo: IFoo = { m(a: number): void {} } + In these cases we get the symbol for the signature from the contextual type. + */ + if (ts.contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) { + if (isValidMethodSignature(entry.node.parent)) { + groupedReferences.signature = entry.node.parent; + continue; + } + var call = entryToFunctionCall(entry); + if (call) { + groupedReferences.functionCalls.push(call); + continue; + } + } + var contextualSymbol = getSymbolForContextualType(entry.node, checker); + if (contextualSymbol && ts.contains(contextualSymbols, contextualSymbol)) { + var decl = entryToDeclaration(entry); + if (decl) { + groupedReferences.declarations.push(decl); + continue; + } + } /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function. Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test: class A { foo(a: number, b: number) { return a + b; } } @@ -147218,6 +151753,19 @@ var ts; return symbol && ts.getSymbolTarget(symbol, checker); } } + /** + * Gets the symbol for the contextual type of the node if it is not a union or intersection. + */ + function getSymbolForContextualType(node, checker) { + var element = ts.getContainingObjectLiteralElement(node); + if (element) { + var contextualType = checker.getContextualTypeForObjectLiteralElement(element); + var symbol = contextualType === null || contextualType === void 0 ? void 0 : contextualType.getSymbol(); + if (symbol && !(ts.getCheckFlags(symbol) & 6 /* Synthetic */)) { + return symbol; + } + } + } function entryToImportOrExport(entry) { var node = entry.node; if (ts.isImportSpecifier(node.parent) @@ -147243,15 +151791,15 @@ var ts; var parent = functionReference.parent; switch (parent.kind) { // foo(...) or super(...) or new Foo(...) - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: var callOrNewExpression = ts.tryCast(parent, ts.isCallOrNewExpression); if (callOrNewExpression && callOrNewExpression.expression === functionReference) { return callOrNewExpression; } break; // x.foo(...) - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression); if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { var callOrNewExpression_1 = ts.tryCast(propertyAccessExpression.parent, ts.isCallOrNewExpression); @@ -147261,7 +151809,7 @@ var ts; } break; // x["foo"](...) - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression); if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { var callOrNewExpression_2 = ts.tryCast(elementAccessExpression.parent, ts.isCallOrNewExpression); @@ -147280,14 +151828,14 @@ var ts; var parent = reference.parent; switch (parent.kind) { // `C.foo` - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression); if (propertyAccessExpression && propertyAccessExpression.expression === reference) { return propertyAccessExpression; } break; // `C["foo"]` - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression); if (elementAccessExpression && elementAccessExpression.expression === reference) { return elementAccessExpression; @@ -147325,15 +151873,24 @@ var ts; } return false; } + function isValidMethodSignature(node) { + return ts.isMethodSignature(node) && (ts.isInterfaceDeclaration(node.parent) || ts.isTypeLiteralNode(node.parent)); + } function isValidFunctionDeclaration(functionDeclaration, checker) { + var _a; if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false; switch (functionDeclaration.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: + if (ts.isObjectLiteralExpression(functionDeclaration.parent)) { + var contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker); + // don't offer the refactor when there are multiple signatures since we won't know which ones the user wants to change + return ((_a = contextualSymbol === null || contextualSymbol === void 0 ? void 0 : contextualSymbol.declarations) === null || _a === void 0 ? void 0 : _a.length) === 1 && isSingleImplementation(functionDeclaration, checker); + } return isSingleImplementation(functionDeclaration, checker); - case 166 /* Constructor */: + case 167 /* Constructor */: if (ts.isClassDeclaration(functionDeclaration.parent)) { return hasNameOrDefault(functionDeclaration.parent) && isSingleImplementation(functionDeclaration, checker); } @@ -147341,8 +151898,8 @@ var ts; return isValidVariableDeclaration(functionDeclaration.parent.parent) && isSingleImplementation(functionDeclaration, checker); } - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return isValidVariableDeclaration(functionDeclaration.parent); } return false; @@ -147492,7 +152049,7 @@ var ts; } function getClassNames(constructorDeclaration) { switch (constructorDeclaration.parent.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: var classDeclaration = constructorDeclaration.parent; if (classDeclaration.name) return [classDeclaration.name]; @@ -147500,7 +152057,7 @@ var ts; // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault` var defaultModifier = ts.Debug.checkDefined(ts.findModifier(classDeclaration, 87 /* DefaultKeyword */), "Nameless class declaration should be a default export"); return [defaultModifier]; - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: var classExpression = constructorDeclaration.parent; var variableDeclaration = constructorDeclaration.parent.parent; var className = classExpression.name; @@ -147511,25 +152068,25 @@ var ts; } function getFunctionNames(functionDeclaration) { switch (functionDeclaration.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: if (functionDeclaration.name) return [functionDeclaration.name]; // If the function declaration doesn't have a name, it should have a default modifier. // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault` var defaultModifier = ts.Debug.checkDefined(ts.findModifier(functionDeclaration, 87 /* DefaultKeyword */), "Nameless function declaration should be a default export"); return [defaultModifier]; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return [functionDeclaration.name]; - case 166 /* Constructor */: + case 167 /* Constructor */: var ctrKeyword = ts.Debug.checkDefined(ts.findChildOfKind(functionDeclaration, 132 /* ConstructorKeyword */, functionDeclaration.getSourceFile()), "Constructor declaration should have constructor keyword"); - if (functionDeclaration.parent.kind === 221 /* ClassExpression */) { + if (functionDeclaration.parent.kind === 222 /* ClassExpression */) { var variableDeclaration = functionDeclaration.parent.parent; return [variableDeclaration.name, ctrKeyword]; } return [ctrKeyword]; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return [functionDeclaration.parent.name]; - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: if (functionDeclaration.name) return [functionDeclaration.name, functionDeclaration.parent.name]; return [functionDeclaration.parent.name]; @@ -147620,11 +152177,11 @@ var ts; function getParentBinaryExpression(expr) { var container = ts.findAncestor(expr.parent, function (n) { switch (n.kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return false; - case 218 /* TemplateExpression */: - case 216 /* BinaryExpression */: + case 219 /* TemplateExpression */: + case 217 /* BinaryExpression */: return !(ts.isBinaryExpression(n.parent) && isNotEqualsOperator(n.parent)); default: return "quit"; @@ -147701,7 +152258,7 @@ var ts; var templateSpans = []; var templateHead = ts.factory.createTemplateHead(headText); copyCommentFromStringLiterals(headIndexes, templateHead); - var _loop_19 = function (i) { + var _loop_20 = function (i) { var currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); copyOperatorComments(i, currentNode); var _c = concatConsecutiveString(i + 1, nodes), newIndex = _c[0], subsequentText = _c[1], stringIndexes = _c[2]; @@ -147725,7 +152282,7 @@ var ts; }; var out_i_1; for (var i = begin; i < nodes.length; i++) { - _loop_19(i); + _loop_20(i); i = out_i_1; } return ts.factory.createTemplateExpression(templateHead, templateSpans); @@ -147925,7 +152482,9 @@ var ts; var body = convertToBlock(func.body); var variableDeclaration = variableInfo.variableDeclaration, variableDeclarationList = variableInfo.variableDeclarationList, statement = variableInfo.statement, name = variableInfo.name; ts.suppressLeadingTrivia(statement); - var newNode = ts.factory.createFunctionDeclaration(func.decorators, statement.modifiers, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); + var modifiersFlags = (ts.getCombinedModifierFlags(variableDeclaration) & 1 /* Export */) | ts.getEffectiveModifierFlags(func); + var modifiers = ts.factory.createModifiersFromModifierFlags(modifiersFlags); + var newNode = ts.factory.createFunctionDeclaration(func.decorators, ts.length(modifiers) ? modifiers : undefined, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); if (variableDeclarationList.declarations.length === 1) { return ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, statement, newNode); }); } @@ -147983,9 +152542,7 @@ var ts; function getEditsForAction(context) { var info = getInfo(context); if (info && !refactor.isRefactorErrorInfo(info)) { - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { - return t.tryInsertTypeAnnotation(context.file, info.declaration, info.returnTypeNode); - }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, t, info.declaration, info.returnTypeNode); }); return { renameFilename: undefined, renameLocation: undefined, edits: edits }; } return undefined; @@ -148010,11 +152567,26 @@ var ts; } return ts.emptyArray; } + function doChange(sourceFile, changes, declaration, typeNode) { + var closeParen = ts.findChildOfKind(declaration, 21 /* CloseParenToken */, sourceFile); + var needParens = ts.isArrowFunction(declaration) && closeParen === undefined; + var endNode = needParens ? ts.first(declaration.parameters) : closeParen; + if (endNode) { + if (needParens) { + changes.insertNodeBefore(sourceFile, endNode, ts.factory.createToken(20 /* OpenParenToken */)); + changes.insertNodeAfter(sourceFile, endNode, ts.factory.createToken(21 /* CloseParenToken */)); + } + changes.insertNodeAt(sourceFile, endNode.end, typeNode, { prefix: ": " }); + } + } function getInfo(context) { if (ts.isInJSFile(context.file) || !refactor.refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind)) return; var token = ts.getTokenAtPosition(context.file, context.startPosition); - var declaration = ts.findAncestor(token, isConvertibleDeclaration); + var declaration = ts.findAncestor(token, function (n) { + return ts.isBlock(n) || n.parent && ts.isArrowFunction(n.parent) && (n.kind === 38 /* EqualsGreaterThanToken */ || n.parent.body === n) ? "quit" : + isConvertibleDeclaration(n); + }); if (!declaration || !declaration.body || declaration.type) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Return_type_must_be_inferred_from_a_function) }; } @@ -148023,7 +152595,6 @@ var ts; if (!returnType) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_determine_function_return_type) }; } - ; var returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, 1 /* NoTruncation */); if (returnTypeNode) { return { declaration: declaration, returnTypeNode: returnTypeNode }; @@ -148031,10 +152602,10 @@ var ts; } function isConvertibleDeclaration(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: return true; default: return false; @@ -148136,8 +152707,8 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 301 /* FirstJSDocNode */ || kid.kind > 333 /* LastJSDocNode */; }); - return child.kind < 157 /* FirstNode */ ? + var child = ts.find(children, function (kid) { return kid.kind < 302 /* FirstJSDocNode */ || kid.kind > 337 /* LastJSDocNode */; }); + return child.kind < 158 /* FirstNode */ ? child : child.getFirstToken(sourceFile); }; @@ -148148,7 +152719,7 @@ var ts; if (!child) { return undefined; } - return child.kind < 157 /* FirstNode */ ? child : child.getLastToken(sourceFile); + return child.kind < 158 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { return ts.forEachChild(this, cbNode, cbNodeArray); @@ -148206,11 +152777,11 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(334 /* SyntaxList */, nodes.pos, nodes.end, parent); + var list = createNode(338 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { - var node = nodes_1[_i]; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; addSyntheticNodes(list._children, pos, node.pos, parent); list._children.push(node); pos = node.end; @@ -148317,13 +152888,13 @@ var ts; }; SymbolObject.prototype.getContextualDocumentationComment = function (context, checker) { switch (context === null || context === void 0 ? void 0 : context.kind) { - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: if (!this.contextualGetAccessorDocumentationComment) { this.contextualGetAccessorDocumentationComment = ts.emptyArray; this.contextualGetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isGetAccessor), checker); } return this.contextualGetAccessorDocumentationComment; - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: if (!this.contextualSetAccessorDocumentationComment) { this.contextualSetAccessorDocumentationComment = ts.emptyArray; this.contextualSetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isSetAccessor), checker); @@ -148333,9 +152904,9 @@ var ts; return this.getDocumentationComment(checker); } }; - SymbolObject.prototype.getJsDocTags = function () { + SymbolObject.prototype.getJsDocTags = function (checker) { if (this.tags === undefined) { - this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations); + this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations, checker); } return this.tags; }; @@ -148496,7 +153067,7 @@ var ts; }; SignatureObject.prototype.getJsDocTags = function () { if (this.jsDocTags === undefined) { - this.jsDocTags = this.declaration ? getJsDocTags([this.declaration], this.checker) : []; + this.jsDocTags = this.declaration ? getJsDocTagsOfSignature(this.declaration, this.checker) : []; } return this.jsDocTags; }; @@ -148510,29 +153081,34 @@ var ts; function hasJSDocInheritDocTag(node) { return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); } - function getJsDocTags(declarations, checker) { - var tags = ts.JsDoc.getJsDocTagsFromDeclarations(declarations); - if (tags.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - ts.forEachUnique(declarations, function (declaration) { - var inheritedTags = findBaseOfDeclaration(checker, declaration, function (symbol) { return symbol.getJsDocTags(); }); - if (inheritedTags) { - tags = __spreadArray(__spreadArray([], inheritedTags), tags); - } - }); + function getJsDocTagsOfSignature(declaration, checker) { + var tags = ts.JsDoc.getJsDocTagsFromDeclarations([declaration], checker); + if (tags.length === 0 || hasJSDocInheritDocTag(declaration)) { + var inheritedTags = findBaseOfDeclaration(checker, declaration, function (symbol) { var _a; return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) === 1 ? symbol.getJsDocTags() : undefined; }); + if (inheritedTags) { + tags = __spreadArray(__spreadArray([], inheritedTags), tags); + } } return tags; } function getDocumentationComment(declarations, checker) { if (!declarations) return ts.emptyArray; - var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); + var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations, checker); if (checker && (doc.length === 0 || declarations.some(hasJSDocInheritDocTag))) { - ts.forEachUnique(declarations, function (declaration) { - var inheritedDocs = findBaseOfDeclaration(checker, declaration, function (symbol) { return symbol.getDocumentationComment(checker); }); + var seenSymbols_1 = new ts.Set(); + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; + var inheritedDocs = findBaseOfDeclaration(checker, declaration, function (symbol) { + if (!seenSymbols_1.has(symbol)) { + seenSymbols_1.add(symbol); + return symbol.getDocumentationComment(checker); + } + }); // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); - }); + } } return doc; } @@ -148546,7 +153122,7 @@ var ts; __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { var _this = _super.call(this, kind, pos, end) || this; - _this.kind = 297 /* SourceFile */; + _this.kind = 298 /* SourceFile */; return _this; } SourceFileObject.prototype.update = function (newText, textChangeRange) { @@ -148605,10 +153181,10 @@ var ts; } function visit(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -148628,31 +153204,31 @@ var ts; } ts.forEachChild(node, visit); break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: - case 256 /* ModuleDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 270 /* ExportSpecifier */: - case 265 /* ImportSpecifier */: - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 177 /* TypeLiteral */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 257 /* ModuleDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 271 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 178 /* TypeLiteral */: addDeclaration(node); ts.forEachChild(node, visit); break; - case 160 /* Parameter */: + case 161 /* Parameter */: // Only consider parameter properties - if (!ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) { + if (!ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { break; } // falls through - case 249 /* VariableDeclaration */: - case 198 /* BindingElement */: { + case 250 /* VariableDeclaration */: + case 199 /* BindingElement */: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -148663,12 +153239,12 @@ var ts; } } // falls through - case 291 /* EnumMember */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 292 /* EnumMember */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: addDeclaration(node); break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; var exportDeclaration = node; @@ -148681,7 +153257,7 @@ var ts; } } break; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -148693,7 +153269,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 263 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 264 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -148702,7 +153278,7 @@ var ts; } } break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } @@ -148796,15 +153372,7 @@ var ts; var fileName = rootFileNames_1[_i]; this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName)); } - // store the compilation settings - this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); } - HostCache.prototype.compilationSettings = function () { - return this._compilationSettings; - }; - HostCache.prototype.getProjectReferences = function () { - return this.host.getProjectReferences && this.host.getProjectReferences(); - }; HostCache.prototype.createEntry = function (fileName, path) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); @@ -148954,7 +153522,7 @@ var ts; }; CancellationTokenObject.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { - ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "CancellationTokenObject" }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "CancellationTokenObject" }); throw new ts.OperationCanceledException(); } }; @@ -148984,7 +153552,7 @@ var ts; }; ThrottledCancellationToken.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { - ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "ThrottledCancellationToken" }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("session" /* Session */, "cancellationThrown", { kind: "ThrottledCancellationToken" }); throw new ts.OperationCanceledException(); } }; @@ -149084,7 +153652,7 @@ var ts; return sourceFile; } function synchronizeHostData() { - var _a, _b; + var _a, _b, _c; ts.Debug.assert(languageServiceMode !== ts.LanguageServiceMode.Syntactic); // perform fast check if host supports it if (host.getProjectVersion) { @@ -149105,11 +153673,22 @@ var ts; // Get a fresh cache of the host information var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); + var newSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; var hasChangedAutomaticTypeDirectiveNames = ts.maybeBind(host, host.hasChangedAutomaticTypeDirectiveNames); - var projectReferences = hostCache.getProjectReferences(); + var projectReferences = (_b = host.getProjectReferences) === null || _b === void 0 ? void 0 : _b.call(host); + var parsedCommandLines; + var parseConfigHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: readFile, + readDirectory: readDirectory, + trace: ts.maybeBind(host, host.trace), + getCurrentDirectory: function () { return currentDirectory; }, + onUnRecoverableConfigFileDiagnostic: ts.noop, + }; // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (_path, fileName) { return host.getScriptVersion(fileName); }, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { + if (ts.isProgramUptoDate(program, rootFileNames, newSettings, function (_path, fileName) { return host.getScriptVersion(fileName); }, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -149117,7 +153696,6 @@ var ts; // instance. If we cancel midway through, we may end up in an inconsistent state where // the program points to old source files that have been invalidated because of // incremental parsing. - var newSettings = hostCache.compilationSettings(); // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -149139,19 +153717,18 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, - readDirectory: function (path, extensions, exclude, include, depth) { - ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); - return host.readDirectory(path, extensions, exclude, include, depth); - }, + readDirectory: readDirectory, onReleaseOldSourceFile: onReleaseOldSourceFile, + onReleaseParsedCommandLine: onReleaseParsedCommandLine, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: hasChangedAutomaticTypeDirectiveNames, - trace: ts.maybeBind(host, host.trace), + trace: parseConfigHost.trace, resolveModuleNames: ts.maybeBind(host, host.resolveModuleNames), resolveTypeReferenceDirectives: ts.maybeBind(host, host.resolveTypeReferenceDirectives), useSourceOfProjectReferenceRedirect: ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect), + getParsedCommandLine: getParsedCommandLine, }; - (_b = host.setCompilerHost) === null || _b === void 0 ? void 0 : _b.call(host, compilerHost); + (_c = host.setCompilerHost) === null || _c === void 0 ? void 0 : _c.call(host, compilerHost); var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); var options = { rootNames: rootFileNames, @@ -149164,6 +153741,7 @@ var ts; // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. // It needs to be cleared to allow all collected snapshots to be released hostCache = undefined; + parsedCommandLines = undefined; // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during // the course of whatever called `synchronizeHostData` @@ -149172,6 +153750,36 @@ var ts; // pointers set property. program.getTypeChecker(); return; + function getParsedCommandLine(fileName) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var existing = parsedCommandLines === null || parsedCommandLines === void 0 ? void 0 : parsedCommandLines.get(path); + if (existing !== undefined) + return existing || undefined; + var result = host.getParsedCommandLine ? + host.getParsedCommandLine(fileName) : + getParsedCommandLineOfConfigFileUsingSourceFile(fileName); + (parsedCommandLines || (parsedCommandLines = new ts.Map())).set(path, result || false); + return result; + } + function getParsedCommandLineOfConfigFileUsingSourceFile(configFileName) { + var result = getOrCreateSourceFile(configFileName, 100 /* JSON */); + if (!result) + return undefined; + result.path = ts.toPath(configFileName, currentDirectory, getCanonicalFileName); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; + return ts.parseJsonSourceFileConfigFileContent(result, parseConfigHost, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), + /*optionsToExtend*/ undefined, ts.getNormalizedAbsolutePath(configFileName, currentDirectory)); + } + function onReleaseParsedCommandLine(configFileName, oldResolvedRef, oldOptions) { + var _a; + if (host.getParsedCommandLine) { + (_a = host.onReleaseParsedCommandLine) === null || _a === void 0 ? void 0 : _a.call(host, configFileName, oldResolvedRef, oldOptions); + } + else if (oldResolvedRef) { + onReleaseOldSourceFile(oldResolvedRef.sourceFile, oldOptions); + } + } function fileExists(fileName) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = hostCache && hostCache.getEntryByPath(path); @@ -149188,11 +153796,15 @@ var ts; } return host.readFile && host.readFile(fileName); } + function readDirectory(path, extensions, exclude, include, depth) { + ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + } // Release any files we have acquired in the old program but are // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { var oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind); } function getOrCreateSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); @@ -149237,8 +153849,13 @@ var ts; // We do not support the scenario where a host can modify a registered // file's script kind, i.e. in one project some file is treated as ".ts" // and in another as ".js" - ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind."); - return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + if (hostFileInformation.scriptKind === oldSourceFile.scriptKind) { + return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + } + else { + // Release old source file and fall through to aquire new file with new script kind + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind); + } } // We didn't already have the file. Fall through and acquire it from the registry. } @@ -149267,7 +153884,7 @@ var ts; // Use paths to ensure we are using correct key and paths as document registry could be created with different current directory than host var key_1 = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()); ts.forEach(program.getSourceFiles(), function (f) { - return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1); + return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1, f.scriptKind); }); program = undefined; // TODO: GH#18217 } @@ -149310,10 +153927,10 @@ var ts; synchronizeHostData(); return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter); } - function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { + function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences, data) { if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions, host)), // TODO: GH#18217 + return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source, data: data }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions, host)), // TODO: GH#18217 preferences, cancellationToken); } function getCompletionEntrySymbol(fileName, position, name, source, preferences) { @@ -149340,7 +153957,7 @@ var ts; textSpan: ts.createTextSpanFromNode(nodeForQuickInfo, sourceFile), displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_2, ts.getContainerNode(nodeForQuickInfo)); }), documentation: type_2.symbol ? type_2.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_2.symbol ? type_2.symbol.getJsDocTags() : undefined + tags: type_2.symbol ? type_2.symbol.getJsDocTags(typeChecker) : undefined }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { @@ -149359,19 +153976,23 @@ var ts; if (ts.isNewExpression(node.parent) && node.pos === node.parent.pos) { return node.parent.expression; } + if (ts.isNamedTupleMember(node.parent) && node.pos === node.parent.pos) { + return node.parent; + } return node; } function shouldGetType(sourceFile, node, position) { switch (node.kind) { case 78 /* Identifier */: - return !ts.isLabelName(node) && !ts.isTagName(node); - case 201 /* PropertyAccessExpression */: - case 157 /* QualifiedName */: + return !ts.isLabelName(node) && !ts.isTagName(node) && !ts.isConstTypeReference(node.parent); + case 202 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: // Don't return quickInfo if inside the comment in `a/**/.b` return !ts.isInComment(sourceFile, position); case 107 /* ThisKeyword */: - case 187 /* ThisType */: + case 188 /* ThisType */: case 105 /* SuperKeyword */: + case 193 /* NamedTupleMember */: return true; default: return false; @@ -149476,15 +154097,15 @@ var ts; return undefined; } switch (node.kind) { - case 201 /* PropertyAccessExpression */: - case 157 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: case 10 /* StringLiteral */: case 94 /* FalseKeyword */: case 109 /* TrueKeyword */: case 103 /* NullKeyword */: case 105 /* SuperKeyword */: case 107 /* ThisKeyword */: - case 187 /* ThisType */: + case 188 /* ThisType */: case 78 /* Identifier */: break; // Cant create the text span @@ -149501,7 +154122,7 @@ var ts; // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module - if (nodeForStartPos.parent.parent.kind === 256 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 257 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -149529,15 +154150,7 @@ var ts; function getNavigationTree(fileName) { return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); } - function isTsOrTsxFile(fileName) { - var kind = ts.getScriptKind(fileName, host); - return kind === 3 /* TS */ || kind === 4 /* TSX */; - } function getSemanticClassifications(fileName, span, format) { - if (!isTsOrTsxFile(fileName)) { - // do not run semantic classification on non-ts-or-tsx files - return []; - } synchronizeHostData(); var responseFormat = format || "original" /* Original */; if (responseFormat === "2020" /* TwentyTwenty */) { @@ -149548,10 +154161,6 @@ var ts; } } function getEncodedSemanticClassifications(fileName, span, format) { - if (!isTsOrTsxFile(fileName)) { - // do not run semantic classification on non-ts-or-tsx files - return { spans: [], endOfLineState: 0 /* None */ }; - } synchronizeHostData(); var responseFormat = format || "original" /* Original */; if (responseFormat === "original" /* Original */) { @@ -149642,13 +154251,13 @@ var ts; var formatContext = ts.formatting.getFormatContext(formatOptions, host); return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } - function organizeImports(scope, formatOptions, preferences) { + function organizeImports(args, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); - ts.Debug.assert(scope.type === "file"); - var sourceFile = getValidSourceFile(scope.fileName); + ts.Debug.assert(args.type === "file"); + var sourceFile = getValidSourceFile(args.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions, host); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, args.skipDestructiveCodeActions); } function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } @@ -149665,8 +154274,8 @@ var ts; ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); } - function getDocCommentTemplateAtPosition(fileName, position) { - return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); + function getDocCommentTemplateAtPosition(fileName, position, options) { + return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position, options); } function isValidBraceCompletionAtPosition(fileName, position, openingBrace) { // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too @@ -150081,6 +154690,16 @@ var ts; var file = getValidSourceFile(fileName); return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName); } + function toLineColumnOffset(fileName, position) { + // Go to Definition supports returning a zero-length span at position 0 for + // non-existent files. We need to special-case the conversion of position 0 + // to avoid a crash trying to get the text for that file, since this function + // otherwise assumes that 'fileName' is the name of a file that exists. + if (position === 0) { + return { line: 0, character: 0 }; + } + return sourceMapper.toLineColumnOffset(fileName, position); + } function prepareCallHierarchy(fileName, position) { synchronizeHostData(); var declarations = ts.CallHierarchy.resolveCallHierarchyDeclaration(program, ts.getTouchingPropertyName(getValidSourceFile(fileName), position)); @@ -150153,7 +154772,7 @@ var ts; getAutoImportProvider: getAutoImportProvider, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, - toLineColumnOffset: sourceMapper.toLineColumnOffset, + toLineColumnOffset: toLineColumnOffset, getSourceMapper: function () { return sourceMapper; }, clearSourceMapperCache: function () { return sourceMapper.clearCache(); }, prepareCallHierarchy: prepareCallHierarchy, @@ -150224,7 +154843,7 @@ var ts; */ function literalIsName(node) { return ts.isDeclarationName(node) || - node.parent.kind === 272 /* ExternalModuleReference */ || + node.parent.kind === 273 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } @@ -150242,13 +154861,13 @@ var ts; case 10 /* StringLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: - if (node.parent.kind === 158 /* ComputedPropertyName */) { + if (node.parent.kind === 159 /* ComputedPropertyName */) { return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through case 78 /* Identifier */: return ts.isObjectLiteralElement(node.parent) && - (node.parent.parent.kind === 200 /* ObjectLiteralExpression */ || node.parent.parent.kind === 281 /* JsxAttributes */) && + (node.parent.parent.kind === 201 /* ObjectLiteralExpression */ || node.parent.parent.kind === 282 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } return undefined; @@ -150290,7 +154909,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 202 /* ElementAccessExpression */ && + node.parent.kind === 203 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /** @@ -150370,114 +154989,114 @@ var ts; if (node) { var parent = node.parent; switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 249 /* VariableDeclaration */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 250 /* VariableDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return spanInVariableDeclaration(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return spanInParameterDeclaration(node); - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 166 /* Constructor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 167 /* Constructor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 230 /* Block */: + case 231 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // falls through - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return spanInBlock(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return spanInBlock(node.block); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: // Span on while(...) return textSpanEndingAtNextToken(node, node.expression); - case 235 /* DoStatement */: + case 236 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 248 /* DebuggerStatement */: + case 249 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 234 /* IfStatement */: + case 235 /* IfStatement */: // set on if(..) span return textSpanEndingAtNextToken(node, node.expression); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return spanInForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: // span of for (a in ...) return textSpanEndingAtNextToken(node, node.expression); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: // span in initializer return spanInInitializerOfForLike(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: // span on switch(...) return textSpanEndingAtNextToken(node, node.expression); - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 247 /* TryStatement */: + case 248 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } // falls through - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: - case 198 /* BindingElement */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: + case 199 /* BindingElement */: // span on complete node return textSpan(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: // span in statement return spanInNode(node.statement); - case 161 /* Decorator */: + case 162 /* Decorator */: return spanInNodeArray(parent.decorators); - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return undefined; // Tokens: case 26 /* SemicolonToken */: @@ -150507,7 +155126,7 @@ var ts; case 82 /* CatchKeyword */: case 95 /* FinallyKeyword */: return spanInNextNode(node); - case 156 /* OfKeyword */: + case 157 /* OfKeyword */: return spanInOfKeyword(node); default: // Destructuring pattern in destructuring assignment @@ -150520,13 +155139,13 @@ var ts; // `a` or `...c` or `d: x` from // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern if ((node.kind === 78 /* Identifier */ || - node.kind === 220 /* SpreadElement */ || - node.kind === 288 /* PropertyAssignment */ || - node.kind === 289 /* ShorthandPropertyAssignment */) && + node.kind === 221 /* SpreadElement */ || + node.kind === 289 /* PropertyAssignment */ || + node.kind === 290 /* ShorthandPropertyAssignment */) && ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { return textSpan(node); } - if (node.kind === 216 /* BinaryExpression */) { + if (node.kind === 217 /* BinaryExpression */) { var _a = node, left = _a.left, operatorToken = _a.operatorToken; // Set breakpoint in destructuring pattern if its destructuring assignment // [a, b, c] or {a, b, c} of @@ -150548,22 +155167,22 @@ var ts; } if (ts.isExpressionNode(node)) { switch (parent.kind) { - case 235 /* DoStatement */: + case 236 /* DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); - case 161 /* Decorator */: + case 162 /* Decorator */: // Set breakpoint on the decorator emit return spanInNode(node.parent); - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: return textSpan(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (node.parent.operatorToken.kind === 27 /* CommaToken */) { // If this is a comma expression, the breakpoint is possible in this expression return textSpan(node); } break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: if (node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); @@ -150572,21 +155191,21 @@ var ts; } } switch (node.parent.kind) { - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // If this is name of property assignment, set breakpoint in the initializer if (node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } break; - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: // Breakpoint in type assertion goes to its operand if (node.parent.type === node) { return spanInNextNode(node.parent.type); } break; - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: { + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: { // initializer of variable/parameter declaration go to previous node var _b = node.parent, initializer = _b.initializer, type = _b.type; if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { @@ -150594,7 +155213,7 @@ var ts; } break; } - case 216 /* BinaryExpression */: { + case 217 /* BinaryExpression */: { var left = node.parent.left; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { // If initializer of destructuring assignment move to previous token @@ -150624,7 +155243,7 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 238 /* ForInStatement */) { + if (variableDeclaration.parent.parent.kind === 239 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } var parent = variableDeclaration.parent; @@ -150636,7 +155255,7 @@ var ts; // or its declaration from 'for of' if (variableDeclaration.initializer || ts.hasSyntacticModifier(variableDeclaration, 1 /* Export */) || - parent.parent.kind === 239 /* ForOfStatement */) { + parent.parent.kind === 240 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } if (ts.isVariableDeclarationList(variableDeclaration.parent) && @@ -150677,7 +155296,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasSyntacticModifier(functionDeclaration, 1 /* Export */) || - (functionDeclaration.parent.kind === 252 /* ClassDeclaration */ && functionDeclaration.kind !== 166 /* Constructor */); + (functionDeclaration.parent.kind === 253 /* ClassDeclaration */ && functionDeclaration.kind !== 167 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -150700,26 +155319,26 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // Set on parent if on same line otherwise on first statement // falls through - case 236 /* WhileStatement */: - case 234 /* IfStatement */: - case 238 /* ForInStatement */: + case 237 /* WhileStatement */: + case 235 /* IfStatement */: + case 239 /* ForInStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); // Set span on previous token if it starts on same line otherwise on the first statement of the block - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement return spanInNode(block.statements[0]); } function spanInInitializerOfForLike(forLikeStatement) { - if (forLikeStatement.initializer.kind === 250 /* VariableDeclarationList */) { + if (forLikeStatement.initializer.kind === 251 /* VariableDeclarationList */) { // Declaration list - set breakpoint in first declaration var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -150744,21 +155363,21 @@ var ts; } function spanInBindingPattern(bindingPattern) { // Set breakpoint in first binding element - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 222 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 223 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } // Empty binding pattern of binding element, set breakpoint on binding element - if (bindingPattern.parent.kind === 198 /* BindingElement */) { + if (bindingPattern.parent.kind === 199 /* BindingElement */) { return textSpan(bindingPattern.parent); } // Variable declaration is used as the span return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 197 /* ArrayBindingPattern */ && node.kind !== 196 /* ObjectBindingPattern */); - var elements = node.kind === 199 /* ArrayLiteralExpression */ ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 222 /* OmittedExpression */ ? element : undefined; }); + ts.Debug.assert(node.kind !== 198 /* ArrayBindingPattern */ && node.kind !== 197 /* ObjectBindingPattern */); + var elements = node.kind === 200 /* ArrayLiteralExpression */ ? node.elements : node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 223 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -150766,18 +155385,18 @@ var ts; // just nested element in another destructuring assignment // set breakpoint on assignment when parent is destructuring assignment // Otherwise set breakpoint for this element - return textSpan(node.parent.kind === 216 /* BinaryExpression */ ? node.parent : node); + return textSpan(node.parent.kind === 217 /* BinaryExpression */ ? node.parent : node); } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -150785,25 +155404,25 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: // If this is not an instantiated module block, no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } // falls through - case 255 /* EnumDeclaration */: - case 252 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 253 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 230 /* Block */: + case 231 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // falls through - case 287 /* CatchClause */: + case 288 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -150811,7 +155430,7 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 196 /* ObjectBindingPattern */: + case 197 /* ObjectBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -150827,7 +155446,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -150842,12 +155461,12 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 235 /* DoStatement */ || // Go to while keyword and do action instead - node.parent.kind === 203 /* CallExpression */ || - node.parent.kind === 204 /* NewExpression */) { + if (node.parent.kind === 236 /* DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 204 /* CallExpression */ || + node.parent.kind === 205 /* NewExpression */) { return spanInPreviousNode(node); } - if (node.parent.kind === 207 /* ParenthesizedExpression */) { + if (node.parent.kind === 208 /* ParenthesizedExpression */) { return spanInNextNode(node); } // Default to parent node @@ -150856,21 +155475,21 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 166 /* Constructor */: - case 236 /* WhileStatement */: - case 235 /* DoStatement */: - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 207 /* ParenthesizedExpression */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 167 /* Constructor */: + case 237 /* WhileStatement */: + case 236 /* DoStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 208 /* ParenthesizedExpression */: return spanInPreviousNode(node); // Default to parent node default: @@ -150880,20 +155499,20 @@ var ts; function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration if (ts.isFunctionLike(node.parent) || - node.parent.kind === 288 /* PropertyAssignment */ || - node.parent.kind === 160 /* Parameter */) { + node.parent.kind === 289 /* PropertyAssignment */ || + node.parent.kind === 161 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 206 /* TypeAssertionExpression */) { + if (node.parent.kind === 207 /* TypeAssertionExpression */) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 235 /* DoStatement */) { + if (node.parent.kind === 236 /* DoStatement */) { // Set span on while expression return textSpanEndingAtNextToken(node, node.parent.expression); } @@ -150901,7 +155520,7 @@ var ts; return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 239 /* ForOfStatement */) { + if (node.parent.kind === 240 /* ForOfStatement */) { // Set using next token return spanInNextNode(node); } @@ -151442,11 +156061,11 @@ var ts; return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); }); }; /** Get a string based representation of a completion list entry details */ - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences, data) { var _this = this; return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions); - return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences, data); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { @@ -151470,9 +156089,9 @@ var ts; return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); }); }; - LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { + LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); }); + return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position, options); }); }; /// NAVIGATE TO /** Return a list of symbols that are interesting to navigate to */ @@ -152612,7 +157231,7 @@ var ts; }, factoryDeprecation); /** @deprecated Use `factory.createJSDocParameterTag` or the factory supplied by your transformation context instead. */ ts.createJSDocParamTag = ts.Debug.deprecate(function createJSDocParamTag(name, isBracketed, typeExpression, comment) { - return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, isBracketed, typeExpression, /*isNameFirst*/ false, comment); + return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, isBracketed, typeExpression, /*isNameFirst*/ false, comment ? ts.factory.createNodeArray([ts.factory.createJSDocText(comment)]) : undefined); }, factoryDeprecation); /** @deprecated Use `factory.createComma` or the factory supplied by your transformation context instead. */ ts.createComma = ts.Debug.deprecate(function createComma(left, right) { @@ -152662,7 +157281,7 @@ var ts; ts.createNode = ts.Debug.deprecate(function createNode(kind, pos, end) { if (pos === void 0) { pos = 0; } if (end === void 0) { end = 0; } - return ts.setTextRangePosEnd(kind === 297 /* SourceFile */ ? ts.parseBaseNodeFactory.createBaseSourceFileNode(kind) : + return ts.setTextRangePosEnd(kind === 298 /* SourceFile */ ? ts.parseBaseNodeFactory.createBaseSourceFileNode(kind) : kind === 78 /* Identifier */ ? ts.parseBaseNodeFactory.createBaseIdentifierNode(kind) : kind === 79 /* PrivateIdentifier */ ? ts.parseBaseNodeFactory.createBasePrivateIdentifierNode(kind) : !ts.isNodeKind(kind) ? ts.parseBaseNodeFactory.createBaseTokenNode(kind) : @@ -152691,13 +157310,30 @@ var ts; // #region Renamed node Tests /** @deprecated Use `isTypeAssertionExpression` instead. */ ts.isTypeAssertion = ts.Debug.deprecate(function isTypeAssertion(node) { - return node.kind === 206 /* TypeAssertionExpression */; + return node.kind === 207 /* TypeAssertionExpression */; }, { since: "4.0", warnAfter: "4.1", message: "Use `isTypeAssertionExpression` instead." }); // #endregion + // DEPRECATION: Renamed node tests + // DEPRECATION PLAN: + // - soft: 4.2 + // - warn: 4.3 + // - error: TBD + // #region Renamed node Tests + /** + * @deprecated Use `isMemberName` instead. + */ + ts.isIdentifierOrPrivateIdentifier = ts.Debug.deprecate(function isIdentifierOrPrivateIdentifier(node) { + return ts.isMemberName(node); + }, { + since: "4.2", + warnAfter: "4.3", + message: "Use `isMemberName` instead." + }); + // #endregion Renamed node Tests })(ts || (ts = {})); //# sourceMappingURL=typescriptServices.js.map diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 4f9a74223a677..6810860b9c4b6 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -81,11 +81,11 @@ var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "4.2"; + ts.versionMajorMinor = "4.3"; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = ts.versionMajorMinor + ".0-dev"; + ts.version = "4.3.2"; /* @internal */ var Comparison; (function (Comparison) { @@ -2389,6 +2389,8 @@ var ts; } } Debug.assertMissingNode = assertMissingNode; + function type(_value) { } + Debug.type = type; function getFunctionName(func) { if (typeof func !== "function") { return ""; @@ -2650,11 +2652,11 @@ var ts; this.objectFlags & 8 /* Tuple */ ? "TupleType" : this.objectFlags & 16 /* Anonymous */ ? "AnonymousType" : this.objectFlags & 32 /* Mapped */ ? "MappedType" : - this.objectFlags & 2048 /* ReverseMapped */ ? "ReverseMappedType" : + this.objectFlags & 1024 /* ReverseMapped */ ? "ReverseMappedType" : this.objectFlags & 256 /* EvolvingArray */ ? "EvolvingArrayType" : "ObjectType" : "Type"; - var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~2367 /* ObjectTypeKindMask */ : 0; + var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~1343 /* ObjectTypeKindMask */ : 0; return "" + typeHeader + (this.symbol ? " '" + ts.symbolName(this.symbol) + "'" : "") + (remainingObjectFlags ? " (" + formatObjectFlags(remainingObjectFlags) + ")" : ""); } }, @@ -3200,16 +3202,22 @@ var ts; typeof PerformanceObserver === "function" && hasRequiredAPI(performance, PerformanceObserver)) { return { + // For now we always write native performance events when running in the browser. We may + // make this conditional in the future if we find that native web performance hooks + // in the browser also slow down compilation. + shouldWriteNativeEvents: true, performance: performance, PerformanceObserver: PerformanceObserver }; } } function tryGetNodePerformanceHooks() { - if (typeof module === "object" && typeof require === "function") { + if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof module === "object" && typeof require === "function") { try { - var _a = require("perf_hooks"), performance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; - if (hasRequiredAPI(performance_1, PerformanceObserver_1)) { + var performance_1; + var _a = require("perf_hooks"), nodePerformance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver; + if (hasRequiredAPI(nodePerformance_1, PerformanceObserver_1)) { + performance_1 = nodePerformance_1; // There is a bug in Node's performance.measure prior to 12.16.3/13.13.0 that does not // match the Web Performance API specification. Node's implementation did not allow // optional `start` and `end` arguments for `performance.measure`. @@ -3217,27 +3225,26 @@ var ts; var version_1 = new ts.Version(process.versions.node); var range = new ts.VersionRange("<12.16.3 || 13 <13.13"); if (range.test(version_1)) { - return { - performance: { - get timeOrigin() { return performance_1.timeOrigin; }, - now: function () { return performance_1.now(); }, - mark: function (name) { return performance_1.mark(name); }, - measure: function (name, start, end) { - if (start === void 0) { start = "nodeStart"; } - if (end === undefined) { - end = "__performance.measure-fix__"; - performance_1.mark(end); - } - performance_1.measure(name, start, end); - if (end === "__performance.measure-fix__") { - performance_1.clearMarks("__performance.measure-fix__"); - } + performance_1 = { + get timeOrigin() { return nodePerformance_1.timeOrigin; }, + now: function () { return nodePerformance_1.now(); }, + mark: function (name) { return nodePerformance_1.mark(name); }, + measure: function (name, start, end) { + if (start === void 0) { start = "nodeStart"; } + if (end === undefined) { + end = "__performance.measure-fix__"; + nodePerformance_1.mark(end); } - }, - PerformanceObserver: PerformanceObserver_1 + nodePerformance_1.measure(name, start, end); + if (end === "__performance.measure-fix__") { + nodePerformance_1.clearMarks("__performance.measure-fix__"); + } + } }; } return { + // By default, only write native events when generating a cpu profile or using the v8 profiler. + shouldWriteNativeEvents: false, performance: performance_1, PerformanceObserver: PerformanceObserver_1 }; @@ -3268,7 +3275,6 @@ var ts; var performance; (function (performance) { var perfHooks; - var perfObserver; // when set, indicates the implementation of `Performance` to use for user timing. // when unset, indicates user timing is unavailable or disabled. var performanceImpl; @@ -3299,6 +3305,9 @@ var ts; } performance.createTimer = createTimer; performance.nullTimer = { enter: ts.noop, exit: ts.noop }; + var enabled = false; + var timeorigin = ts.timestamp(); + var marks = new ts.Map(); var counts = new ts.Map(); var durations = new ts.Map(); /** @@ -3307,7 +3316,13 @@ var ts; * @param markName The name of the mark. */ function mark(markName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + var _a; + if (enabled) { + var count = (_a = counts.get(markName)) !== null && _a !== void 0 ? _a : 0; + counts.set(markName, count + 1); + marks.set(markName, ts.timestamp()); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName); + } } performance.mark = mark; /** @@ -3320,7 +3335,14 @@ var ts; * used. */ function measure(measureName, startMarkName, endMarkName) { - performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + var _a, _b; + if (enabled) { + var end = (_a = (endMarkName !== undefined ? marks.get(endMarkName) : undefined)) !== null && _a !== void 0 ? _a : ts.timestamp(); + var start = (_b = (startMarkName !== undefined ? marks.get(startMarkName) : undefined)) !== null && _b !== void 0 ? _b : timeorigin; + var previousDuration = durations.get(measureName) || 0; + durations.set(measureName, previousDuration + (end - start)); + performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName); + } } performance.measure = measure; /** @@ -3354,40 +3376,41 @@ var ts; * Indicates whether the performance API is enabled. */ function isEnabled() { - return !!performanceImpl; + return enabled; } performance.isEnabled = isEnabled; /** Enables (and resets) performance measurements for the compiler. */ - function enable() { - if (!performanceImpl) { + function enable(system) { + var _a; + if (system === void 0) { system = ts.sys; } + if (!enabled) { + enabled = true; perfHooks || (perfHooks = ts.tryGetNativePerformanceHooks()); - if (!perfHooks) - return false; - perfObserver || (perfObserver = new perfHooks.PerformanceObserver(updateStatisticsFromList)); - perfObserver.observe({ entryTypes: ["mark", "measure"] }); - performanceImpl = perfHooks.performance; + if (perfHooks) { + timeorigin = perfHooks.performance.timeOrigin; + // NodeJS's Web Performance API is currently slower than expected, but we'd still like + // to be able to leverage native trace events when node is run with either `--cpu-prof` + // or `--prof`, if we're running with our own `--generateCpuProfile` flag, or when + // running in debug mode (since its possible to generate a cpu profile while debugging). + if (perfHooks.shouldWriteNativeEvents || ((_a = system === null || system === void 0 ? void 0 : system.cpuProfilingEnabled) === null || _a === void 0 ? void 0 : _a.call(system)) || (system === null || system === void 0 ? void 0 : system.debugMode)) { + performanceImpl = perfHooks.performance; + } + } } return true; } performance.enable = enable; /** Disables performance measurements for the compiler. */ function disable() { - perfObserver === null || perfObserver === void 0 ? void 0 : perfObserver.disconnect(); - performanceImpl = undefined; - counts.clear(); - durations.clear(); - } - performance.disable = disable; - function updateStatisticsFromList(list) { - for (var _i = 0, _a = list.getEntriesByType("mark"); _i < _a.length; _i++) { - var mark_1 = _a[_i]; - counts.set(mark_1.name, (counts.get(mark_1.name) || 0) + 1); - } - for (var _b = 0, _c = list.getEntriesByType("measure"); _b < _c.length; _b++) { - var measure_1 = _c[_b]; - durations.set(measure_1.name, (durations.get(measure_1.name) || 0) + measure_1.duration); + if (enabled) { + marks.clear(); + counts.clear(); + durations.clear(); + performanceImpl = undefined; + enabled = false; } } + performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); /* @internal */ @@ -3431,40 +3454,35 @@ var ts; /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; })(ts || (ts = {})); +/* Tracing events for the compiler. */ /*@internal*/ -/** Tracing events for the compiler. */ var ts; (function (ts) { - var tracing; - (function (tracing) { - var Mode; - (function (Mode) { - Mode[Mode["Project"] = 0] = "Project"; - Mode[Mode["Build"] = 1] = "Build"; - Mode[Mode["Server"] = 2] = "Server"; - })(Mode = tracing.Mode || (tracing.Mode = {})); + // enable the above using startTracing() + // `tracingEnabled` should never be used directly, only through the above + var tracingEnabled; + (function (tracingEnabled) { var fs; var traceCount = 0; - var traceFd; + var traceFd = 0; var mode; + var typeCatalog = []; // NB: id is index + 1 var legendPath; var legend = []; ; - /** Starts tracing for the given project (unless the `fs` module is unavailable). */ + /** Starts tracing for the given project. */ function startTracing(tracingMode, traceDir, configFilePath) { - ts.Debug.assert(!traceFd, "Tracing already started"); + ts.Debug.assert(!ts.tracing, "Tracing already started"); if (fs === undefined) { try { fs = require("fs"); } - catch (_a) { - fs = false; + catch (e) { + throw new Error("tracing requires having fs\n(original error: " + (e.message || e) + ")"); } } - if (!fs) { - return; - } mode = tracingMode; + typeCatalog.length = 0; if (legendPath === undefined) { legendPath = ts.combinePaths(traceDir, "legend.json"); } @@ -3472,9 +3490,9 @@ var ts; if (!fs.existsSync(traceDir)) { fs.mkdirSync(traceDir, { recursive: true }); } - var countPart = mode === 1 /* Build */ ? "." + process.pid + "-" + ++traceCount : - mode === 2 /* Server */ ? "." + process.pid : - ""; + var countPart = mode === "build" ? "." + process.pid + "-" + ++traceCount + : mode === "server" ? "." + process.pid + : ""; var tracePath = ts.combinePaths(traceDir, "trace" + countPart + ".json"); var typesPath = ts.combinePaths(traceDir, "types" + countPart + ".json"); legend.push({ @@ -3483,25 +3501,22 @@ var ts; typesPath: typesPath, }); traceFd = fs.openSync(tracePath, "w"); + ts.tracing = tracingEnabled; // only when traceFd is properly set // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import) var meta = { cat: "__metadata", ph: "M", ts: 1000 * ts.timestamp(), pid: 1, tid: 1 }; fs.writeSync(traceFd, "[\n" + [__assign({ name: "process_name", args: { name: "tsc" } }, meta), __assign({ name: "thread_name", args: { name: "Main" } }, meta), __assign(__assign({ name: "TracingStartedInBrowser" }, meta), { cat: "disabled-by-default-devtools.timeline" })] .map(function (v) { return JSON.stringify(v); }).join(",\n")); } - tracing.startTracing = startTracing; - /** Stops tracing for the in-progress project and dumps the type catalog (unless the `fs` module is unavailable). */ - function stopTracing(typeCatalog) { - if (!traceFd) { - ts.Debug.assert(!fs, "Tracing is not in progress"); - return; - } - ts.Debug.assert(fs); - ts.Debug.assert(!!typeCatalog === (mode !== 2 /* Server */)); // Have a type catalog iff not in server mode + tracingEnabled.startTracing = startTracing; + /** Stops tracing for the in-progress project and dumps the type catalog. */ + function stopTracing() { + ts.Debug.assert(ts.tracing, "Tracing is not in progress"); + ts.Debug.assert(!!typeCatalog.length === (mode !== "server")); // Have a type catalog iff not in server mode fs.writeSync(traceFd, "\n]\n"); fs.closeSync(traceFd); - traceFd = undefined; - if (typeCatalog) { + ts.tracing = undefined; + if (typeCatalog.length) { dumpTypes(typeCatalog); } else { @@ -3510,11 +3525,13 @@ var ts; legend[legend.length - 1].typesPath = undefined; } } - tracing.stopTracing = stopTracing; - function isTracing() { - return !!traceFd; + tracingEnabled.stopTracing = stopTracing; + function recordType(type) { + if (mode !== "server") { + typeCatalog.push(type); + } } - tracing.isTracing = isTracing; + tracingEnabled.recordType = recordType; var Phase; (function (Phase) { Phase["Parse"] = "parse"; @@ -3524,13 +3541,11 @@ var ts; Phase["CheckTypes"] = "checkTypes"; Phase["Emit"] = "emit"; Phase["Session"] = "session"; - })(Phase = tracing.Phase || (tracing.Phase = {})); + })(Phase = tracingEnabled.Phase || (tracingEnabled.Phase = {})); function instant(phase, name, args) { - if (!traceFd) - return; writeEvent("I", phase, name, args, "\"s\":\"g\""); } - tracing.instant = instant; + tracingEnabled.instant = instant; var eventStack = []; /** * @param separateBeginAndEnd - used for special cases where we need the trace point even if the event @@ -3540,47 +3555,42 @@ var ts; */ function push(phase, name, args, separateBeginAndEnd) { if (separateBeginAndEnd === void 0) { separateBeginAndEnd = false; } - if (!traceFd) - return; if (separateBeginAndEnd) { writeEvent("B", phase, name, args); } eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd }); } - tracing.push = push; + tracingEnabled.push = push; function pop() { - if (!traceFd) - return; ts.Debug.assert(eventStack.length > 0); writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp()); eventStack.length--; } - tracing.pop = pop; + tracingEnabled.pop = pop; function popAll() { - if (!traceFd) - return; var endTime = 1000 * ts.timestamp(); for (var i = eventStack.length - 1; i >= 0; i--) { writeStackEvent(i, endTime); } eventStack.length = 0; } - tracing.popAll = popAll; + tracingEnabled.popAll = popAll; + // sample every 10ms + var sampleInterval = 1000 * 10; function writeStackEvent(index, endTime) { var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd; if (separateBeginAndEnd) { writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); } - else { + // test if [time,endTime) straddles a sampling point + else if (sampleInterval - (time % sampleInterval) <= endTime - time) { writeEvent("X", phase, name, args, "\"dur\":" + (endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { if (time === void 0) { time = 1000 * ts.timestamp(); } - ts.Debug.assert(traceFd); - ts.Debug.assert(fs); // In server mode, there's no easy way to dump type information, so we drop events that would require it. - if (mode === 2 /* Server */ && phase === "checkTypes" /* CheckTypes */) + if (mode === "server" && phase === "checkTypes" /* CheckTypes */) return; ts.performance.mark("beginTracing"); fs.writeSync(traceFd, ",\n{\"pid\":1,\"tid\":1,\"ph\":\"" + eventType + "\",\"cat\":\"" + phase + "\",\"ts\":" + time + ",\"name\":\"" + name + "\""); @@ -3592,15 +3602,24 @@ var ts; ts.performance.mark("endTracing"); ts.performance.measure("Tracing", "beginTracing", "endTracing"); } - function indexFromOne(lc) { - return { - line: lc.line + 1, - character: lc.character + 1, - }; + function getLocation(node) { + var file = ts.getSourceFileOfNode(node); + return !file + ? undefined + : { + path: file.path, + start: indexFromOne(ts.getLineAndCharacterOfPosition(file, node.pos)), + end: indexFromOne(ts.getLineAndCharacterOfPosition(file, node.end)), + }; + function indexFromOne(lc) { + return { + line: lc.line + 1, + character: lc.character + 1, + }; + } } function dumpTypes(types) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; - ts.Debug.assert(fs); + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x; ts.performance.mark("beginDumpTypes"); var typesPath = legend[legend.length - 1].typesPath; var typesFd = fs.openSync(typesPath, "w"); @@ -3612,15 +3631,13 @@ var ts; var type = types[i]; var objectFlags = type.objectFlags; var symbol = (_a = type.aliasSymbol) !== null && _a !== void 0 ? _a : type.symbol; - var firstDeclaration = (_b = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _b === void 0 ? void 0 : _b[0]; - var firstFile = firstDeclaration && ts.getSourceFileOfNode(firstDeclaration); // It's slow to compute the display text, so skip it unless it's really valuable (or cheap) var display = void 0; if ((objectFlags & 16 /* Anonymous */) | (type.flags & 2944 /* Literal */)) { try { - display = (_c = type.checker) === null || _c === void 0 ? void 0 : _c.typeToString(type); + display = (_b = type.checker) === null || _b === void 0 ? void 0 : _b.typeToString(type); } - catch (_s) { + catch (_y) { display = undefined; } } @@ -3628,26 +3645,52 @@ var ts; if (type.flags & 8388608 /* IndexedAccess */) { var indexedAccessType = type; indexedAccessProperties = { - indexedAccessObjectType: (_d = indexedAccessType.objectType) === null || _d === void 0 ? void 0 : _d.id, - indexedAccessIndexType: (_e = indexedAccessType.indexType) === null || _e === void 0 ? void 0 : _e.id, + indexedAccessObjectType: (_c = indexedAccessType.objectType) === null || _c === void 0 ? void 0 : _c.id, + indexedAccessIndexType: (_d = indexedAccessType.indexType) === null || _d === void 0 ? void 0 : _d.id, }; } var referenceProperties = {}; if (objectFlags & 4 /* Reference */) { var referenceType = type; referenceProperties = { - instantiatedType: (_f = referenceType.target) === null || _f === void 0 ? void 0 : _f.id, - typeArguments: (_g = referenceType.resolvedTypeArguments) === null || _g === void 0 ? void 0 : _g.map(function (t) { return t.id; }), + instantiatedType: (_e = referenceType.target) === null || _e === void 0 ? void 0 : _e.id, + typeArguments: (_f = referenceType.resolvedTypeArguments) === null || _f === void 0 ? void 0 : _f.map(function (t) { return t.id; }), + referenceLocation: getLocation(referenceType.node), }; } var conditionalProperties = {}; if (type.flags & 16777216 /* Conditional */) { var conditionalType = type; conditionalProperties = { - conditionalCheckType: (_h = conditionalType.checkType) === null || _h === void 0 ? void 0 : _h.id, - conditionalExtendsType: (_j = conditionalType.extendsType) === null || _j === void 0 ? void 0 : _j.id, - conditionalTrueType: (_l = (_k = conditionalType.resolvedTrueType) === null || _k === void 0 ? void 0 : _k.id) !== null && _l !== void 0 ? _l : -1, - conditionalFalseType: (_o = (_m = conditionalType.resolvedFalseType) === null || _m === void 0 ? void 0 : _m.id) !== null && _o !== void 0 ? _o : -1, + conditionalCheckType: (_g = conditionalType.checkType) === null || _g === void 0 ? void 0 : _g.id, + conditionalExtendsType: (_h = conditionalType.extendsType) === null || _h === void 0 ? void 0 : _h.id, + conditionalTrueType: (_k = (_j = conditionalType.resolvedTrueType) === null || _j === void 0 ? void 0 : _j.id) !== null && _k !== void 0 ? _k : -1, + conditionalFalseType: (_m = (_l = conditionalType.resolvedFalseType) === null || _l === void 0 ? void 0 : _l.id) !== null && _m !== void 0 ? _m : -1, + }; + } + var substitutionProperties = {}; + if (type.flags & 33554432 /* Substitution */) { + var substitutionType = type; + substitutionProperties = { + substitutionBaseType: (_o = substitutionType.baseType) === null || _o === void 0 ? void 0 : _o.id, + substituteType: (_p = substitutionType.substitute) === null || _p === void 0 ? void 0 : _p.id, + }; + } + var reverseMappedProperties = {}; + if (objectFlags & 1024 /* ReverseMapped */) { + var reverseMappedType = type; + reverseMappedProperties = { + reverseMappedSourceType: (_q = reverseMappedType.source) === null || _q === void 0 ? void 0 : _q.id, + reverseMappedMappedType: (_r = reverseMappedType.mappedType) === null || _r === void 0 ? void 0 : _r.id, + reverseMappedConstraintType: (_s = reverseMappedType.constraintType) === null || _s === void 0 ? void 0 : _s.id, + }; + } + var evolvingArrayProperties = {}; + if (objectFlags & 256 /* EvolvingArray */) { + var evolvingArrayType = type; + evolvingArrayProperties = { + evolvingArrayElementType: evolvingArrayType.elementType.id, + evolvingArrayFinalType: (_t = evolvingArrayType.finalArrayType) === null || _t === void 0 ? void 0 : _t.id, }; } // We can't print out an arbitrary object, so just assign each one a unique number. @@ -3661,11 +3704,7 @@ var ts; recursionIdentityMap.set(recursionIdentity, recursionToken); } } - var descriptor = __assign(__assign(__assign(__assign({ id: type.id, intrinsicName: type.intrinsicName, symbolName: (symbol === null || symbol === void 0 ? void 0 : symbol.escapedName) && ts.unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, unionTypes: (type.flags & 1048576 /* Union */) ? (_p = type.types) === null || _p === void 0 ? void 0 : _p.map(function (t) { return t.id; }) : undefined, intersectionTypes: (type.flags & 2097152 /* Intersection */) ? type.types.map(function (t) { return t.id; }) : undefined, aliasTypeArguments: (_q = type.aliasTypeArguments) === null || _q === void 0 ? void 0 : _q.map(function (t) { return t.id; }), keyofType: (type.flags & 4194304 /* Index */) ? (_r = type.type) === null || _r === void 0 ? void 0 : _r.id : undefined }, indexedAccessProperties), referenceProperties), conditionalProperties), { firstDeclaration: firstDeclaration && { - path: firstFile.path, - start: indexFromOne(ts.getLineAndCharacterOfPosition(firstFile, firstDeclaration.pos)), - end: indexFromOne(ts.getLineAndCharacterOfPosition(ts.getSourceFileOfNode(firstDeclaration), firstDeclaration.end)), - }, flags: ts.Debug.formatTypeFlags(type.flags).split("|"), display: display }); + var descriptor = __assign(__assign(__assign(__assign(__assign(__assign(__assign({ id: type.id, intrinsicName: type.intrinsicName, symbolName: (symbol === null || symbol === void 0 ? void 0 : symbol.escapedName) && ts.unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, isTuple: objectFlags & 8 /* Tuple */ ? true : undefined, unionTypes: (type.flags & 1048576 /* Union */) ? (_u = type.types) === null || _u === void 0 ? void 0 : _u.map(function (t) { return t.id; }) : undefined, intersectionTypes: (type.flags & 2097152 /* Intersection */) ? type.types.map(function (t) { return t.id; }) : undefined, aliasTypeArguments: (_v = type.aliasTypeArguments) === null || _v === void 0 ? void 0 : _v.map(function (t) { return t.id; }), keyofType: (type.flags & 4194304 /* Index */) ? (_w = type.type) === null || _w === void 0 ? void 0 : _w.id : undefined }, indexedAccessProperties), referenceProperties), conditionalProperties), substitutionProperties), reverseMappedProperties), evolvingArrayProperties), { destructuringPattern: getLocation(type.pattern), firstDeclaration: getLocation((_x = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _x === void 0 ? void 0 : _x[0]), flags: ts.Debug.formatTypeFlags(type.flags).split("|"), display: display }); fs.writeSync(typesFd, JSON.stringify(descriptor)); if (i < numTypes - 1) { fs.writeSync(typesFd, ",\n"); @@ -3680,11 +3719,13 @@ var ts; if (!legendPath) { return; } - ts.Debug.assert(fs); fs.writeFileSync(legendPath, JSON.stringify(legend)); } - tracing.dumpLegend = dumpLegend; - })(tracing = ts.tracing || (ts.tracing = {})); + tracingEnabled.dumpLegend = dumpLegend; + })(tracingEnabled || (tracingEnabled = {})); + // define after tracingEnabled is initialized + ts.startTracing = tracingEnabled.startTracing; + ts.dumpTracingLegend = tracingEnabled.dumpLegend; })(ts || (ts = {})); var ts; (function (ts) { @@ -3860,215 +3901,216 @@ var ts; SyntaxKind[SyntaxKind["FromKeyword"] = 153] = "FromKeyword"; SyntaxKind[SyntaxKind["GlobalKeyword"] = 154] = "GlobalKeyword"; SyntaxKind[SyntaxKind["BigIntKeyword"] = 155] = "BigIntKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 156] = "OfKeyword"; + SyntaxKind[SyntaxKind["OverrideKeyword"] = 156] = "OverrideKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 157] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 157] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 158] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 158] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 159] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 159] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 160] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 161] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 160] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 161] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 162] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 162] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 163] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 164] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 165] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 166] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 167] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 168] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 169] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 170] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 171] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 163] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 164] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 165] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 166] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 167] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 168] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 169] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 170] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 171] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 172] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 172] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 173] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 174] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 175] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 176] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 177] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 178] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 179] = "TupleType"; - SyntaxKind[SyntaxKind["OptionalType"] = 180] = "OptionalType"; - SyntaxKind[SyntaxKind["RestType"] = 181] = "RestType"; - SyntaxKind[SyntaxKind["UnionType"] = 182] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 183] = "IntersectionType"; - SyntaxKind[SyntaxKind["ConditionalType"] = 184] = "ConditionalType"; - SyntaxKind[SyntaxKind["InferType"] = 185] = "InferType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 186] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 187] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 188] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 189] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 190] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 191] = "LiteralType"; - SyntaxKind[SyntaxKind["NamedTupleMember"] = 192] = "NamedTupleMember"; - SyntaxKind[SyntaxKind["TemplateLiteralType"] = 193] = "TemplateLiteralType"; - SyntaxKind[SyntaxKind["TemplateLiteralTypeSpan"] = 194] = "TemplateLiteralTypeSpan"; - SyntaxKind[SyntaxKind["ImportType"] = 195] = "ImportType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 173] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 174] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 175] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 176] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 177] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 178] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 179] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 180] = "TupleType"; + SyntaxKind[SyntaxKind["OptionalType"] = 181] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 182] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 183] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 184] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 185] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 186] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 187] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 188] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 189] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 190] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 191] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 192] = "LiteralType"; + SyntaxKind[SyntaxKind["NamedTupleMember"] = 193] = "NamedTupleMember"; + SyntaxKind[SyntaxKind["TemplateLiteralType"] = 194] = "TemplateLiteralType"; + SyntaxKind[SyntaxKind["TemplateLiteralTypeSpan"] = 195] = "TemplateLiteralTypeSpan"; + SyntaxKind[SyntaxKind["ImportType"] = 196] = "ImportType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 196] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 197] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 198] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 197] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 198] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 199] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 199] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 200] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 201] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 202] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 203] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 204] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 205] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 206] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 207] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 208] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 209] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 210] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 211] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 212] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 213] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 214] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 215] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 216] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 217] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 218] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 219] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 220] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 221] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 222] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 223] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 224] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 225] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 226] = "MetaProperty"; - SyntaxKind[SyntaxKind["SyntheticExpression"] = 227] = "SyntheticExpression"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 200] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 201] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 202] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 203] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 204] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 205] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 206] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 207] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 208] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 209] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 210] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 211] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 212] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 213] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 214] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 215] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 216] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 217] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 218] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 219] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 220] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 221] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 222] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 223] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 224] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 225] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 226] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 227] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 228] = "SyntheticExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 228] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 229] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 229] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 230] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 230] = "Block"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 231] = "EmptyStatement"; - SyntaxKind[SyntaxKind["VariableStatement"] = 232] = "VariableStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 233] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 234] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 235] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 236] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 237] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 238] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 239] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 240] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 241] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 242] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 243] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 244] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 245] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 246] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 247] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 248] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 249] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 250] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 251] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 252] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 253] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 254] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 255] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 256] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 257] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 258] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 259] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 260] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 261] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 262] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 263] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 264] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 265] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 266] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 267] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 268] = "NamedExports"; - SyntaxKind[SyntaxKind["NamespaceExport"] = 269] = "NamespaceExport"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 270] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 271] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 231] = "Block"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 232] = "EmptyStatement"; + SyntaxKind[SyntaxKind["VariableStatement"] = 233] = "VariableStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 234] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 235] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 236] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 237] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 238] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 239] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 240] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 241] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 242] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 243] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 244] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 245] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 246] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 247] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 248] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 249] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 250] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 251] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 252] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 253] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 254] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 255] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 256] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 257] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 258] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 259] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 260] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 261] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 262] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 263] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 264] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 265] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 266] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 267] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 268] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 269] = "NamedExports"; + SyntaxKind[SyntaxKind["NamespaceExport"] = 270] = "NamespaceExport"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 271] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 272] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 272] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 273] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 273] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 274] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 275] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 276] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxFragment"] = 277] = "JsxFragment"; - SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 278] = "JsxOpeningFragment"; - SyntaxKind[SyntaxKind["JsxClosingFragment"] = 279] = "JsxClosingFragment"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 280] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 281] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 282] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 283] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 274] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 275] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 276] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 277] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 278] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 279] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 280] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 281] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 282] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 283] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 284] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 284] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 285] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 286] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 287] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 285] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 286] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 287] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 288] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 288] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 289] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 290] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 289] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 290] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 291] = "SpreadAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 291] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 292] = "EnumMember"; // Unparsed - SyntaxKind[SyntaxKind["UnparsedPrologue"] = 292] = "UnparsedPrologue"; - SyntaxKind[SyntaxKind["UnparsedPrepend"] = 293] = "UnparsedPrepend"; - SyntaxKind[SyntaxKind["UnparsedText"] = 294] = "UnparsedText"; - SyntaxKind[SyntaxKind["UnparsedInternalText"] = 295] = "UnparsedInternalText"; - SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 296] = "UnparsedSyntheticReference"; + SyntaxKind[SyntaxKind["UnparsedPrologue"] = 293] = "UnparsedPrologue"; + SyntaxKind[SyntaxKind["UnparsedPrepend"] = 294] = "UnparsedPrepend"; + SyntaxKind[SyntaxKind["UnparsedText"] = 295] = "UnparsedText"; + SyntaxKind[SyntaxKind["UnparsedInternalText"] = 296] = "UnparsedInternalText"; + SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 297] = "UnparsedSyntheticReference"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 297] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 298] = "Bundle"; - SyntaxKind[SyntaxKind["UnparsedSource"] = 299] = "UnparsedSource"; - SyntaxKind[SyntaxKind["InputFiles"] = 300] = "InputFiles"; + SyntaxKind[SyntaxKind["SourceFile"] = 298] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 299] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 300] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 301] = "InputFiles"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 301] = "JSDocTypeExpression"; - SyntaxKind[SyntaxKind["JSDocNameReference"] = 302] = "JSDocNameReference"; - // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 303] = "JSDocAllType"; - // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 304] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 305] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 306] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 307] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 308] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 309] = "JSDocVariadicType"; - // https://jsdoc.app/about-namepaths.html - SyntaxKind[SyntaxKind["JSDocNamepathType"] = 310] = "JSDocNamepathType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 311] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 312] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocSignature"] = 313] = "JSDocSignature"; - SyntaxKind[SyntaxKind["JSDocTag"] = 314] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 315] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 316] = "JSDocImplementsTag"; - SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 317] = "JSDocAuthorTag"; - SyntaxKind[SyntaxKind["JSDocDeprecatedTag"] = 318] = "JSDocDeprecatedTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 319] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocPublicTag"] = 320] = "JSDocPublicTag"; - SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 321] = "JSDocPrivateTag"; - SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 322] = "JSDocProtectedTag"; - SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 323] = "JSDocReadonlyTag"; - SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 324] = "JSDocCallbackTag"; - SyntaxKind[SyntaxKind["JSDocEnumTag"] = 325] = "JSDocEnumTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 326] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 327] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocThisTag"] = 328] = "JSDocThisTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 329] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 330] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 331] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocSeeTag"] = 332] = "JSDocSeeTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 333] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 302] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocNameReference"] = 303] = "JSDocNameReference"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 304] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 305] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 306] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 307] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 308] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 309] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 310] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocNamepathType"] = 311] = "JSDocNamepathType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 312] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocText"] = 313] = "JSDocText"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 314] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 315] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocLink"] = 316] = "JSDocLink"; + SyntaxKind[SyntaxKind["JSDocTag"] = 317] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 318] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 319] = "JSDocImplementsTag"; + SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 320] = "JSDocAuthorTag"; + SyntaxKind[SyntaxKind["JSDocDeprecatedTag"] = 321] = "JSDocDeprecatedTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 322] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocPublicTag"] = 323] = "JSDocPublicTag"; + SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 324] = "JSDocPrivateTag"; + SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 325] = "JSDocProtectedTag"; + SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 326] = "JSDocReadonlyTag"; + SyntaxKind[SyntaxKind["JSDocOverrideTag"] = 327] = "JSDocOverrideTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 328] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 329] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 330] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 331] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 332] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 333] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 334] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 335] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocSeeTag"] = 336] = "JSDocSeeTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 337] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 334] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 338] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 335] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 336] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 337] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 338] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 339] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 340] = "SyntheticReferenceExpression"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 339] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 340] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 341] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 342] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 343] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 344] = "SyntheticReferenceExpression"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 341] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 345] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 62] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 77] = "LastAssignment"; @@ -4077,15 +4119,15 @@ var ts; SyntaxKind[SyntaxKind["FirstReservedWord"] = 80] = "FirstReservedWord"; SyntaxKind[SyntaxKind["LastReservedWord"] = 115] = "LastReservedWord"; SyntaxKind[SyntaxKind["FirstKeyword"] = 80] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 156] = "LastKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 157] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 116] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 124] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 172] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 195] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 173] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 196] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 77] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 156] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 157] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; @@ -4094,15 +4136,15 @@ var ts; SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken"; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 29] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 77] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstStatement"] = 232] = "FirstStatement"; - SyntaxKind[SyntaxKind["LastStatement"] = 248] = "LastStatement"; - SyntaxKind[SyntaxKind["FirstNode"] = 157] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 301] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 333] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 314] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 333] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstStatement"] = 233] = "FirstStatement"; + SyntaxKind[SyntaxKind["LastStatement"] = 249] = "LastStatement"; + SyntaxKind[SyntaxKind["FirstNode"] = 158] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 302] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 337] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 317] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 337] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 125] = "FirstContextualKeyword"; - /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 156] = "LastContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 157] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -4172,14 +4214,15 @@ var ts; ModifierFlags[ModifierFlags["Const"] = 2048] = "Const"; ModifierFlags[ModifierFlags["HasComputedJSDocModifiers"] = 4096] = "HasComputedJSDocModifiers"; ModifierFlags[ModifierFlags["Deprecated"] = 8192] = "Deprecated"; + ModifierFlags[ModifierFlags["Override"] = 16384] = "Override"; ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier"; // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. - ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier"; + ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 16476] = "ParameterPropertyModifier"; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; - ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; + ModifierFlags[ModifierFlags["TypeScriptModifier"] = 18654] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; - ModifierFlags[ModifierFlags["All"] = 11263] = "All"; + ModifierFlags[ModifierFlags["All"] = 27647] = "All"; })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); var JsxFlags; (function (JsxFlags) { @@ -4360,6 +4403,8 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["NoUndefinedOptionalParameterType"] = 1073741824] = "NoUndefinedOptionalParameterType"; // Error handling NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; + NodeBuilderFlags[NodeBuilderFlags["AllowQualifiedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifiedNameInPlaceOfIdentifier"; + /** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */ NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier"; NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection"; @@ -4374,7 +4419,6 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; - NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -4679,10 +4723,6 @@ var ts; TypeFlags[TypeFlags["Unit"] = 109440] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["StringLikeLiteral"] = 134217856] = "StringLikeLiteral"; - /* @internal */ - TypeFlags[TypeFlags["FreshableLiteral"] = 134220672] = "FreshableLiteral"; - /* @internal */ TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique"; /* @internal */ TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy"; @@ -4731,6 +4771,9 @@ var ts; /* @internal */ TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); + // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags + // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check + // for a certain TypeFlags value to determine their meaning. var ObjectFlags; (function (ObjectFlags) { ObjectFlags[ObjectFlags["Class"] = 1] = "Class"; @@ -4743,50 +4786,59 @@ var ts; ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral"; ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray"; ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties"; - ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread"; - ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes"; - ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; - ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; - ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; - ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral"; - ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType"; + ObjectFlags[ObjectFlags["ReverseMapped"] = 1024] = "ReverseMapped"; + ObjectFlags[ObjectFlags["JsxAttributes"] = 2048] = "JsxAttributes"; + ObjectFlags[ObjectFlags["MarkerType"] = 4096] = "MarkerType"; + ObjectFlags[ObjectFlags["JSLiteral"] = 8192] = "JSLiteral"; + ObjectFlags[ObjectFlags["FreshLiteral"] = 16384] = "FreshLiteral"; + ObjectFlags[ObjectFlags["ArrayLiteral"] = 32768] = "ArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion"; + ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType"; + ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType"; /* @internal */ - ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral"; + ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 262144] = "ContainsObjectOrArrayLiteral"; /* @internal */ - ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType"; + ObjectFlags[ObjectFlags["NonInferrableType"] = 524288] = "NonInferrableType"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; + ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 1048576] = "CouldContainTypeVariablesComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; + ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 2097152] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; + ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening"; /* @internal */ - ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags"; + // Object flags that uniquely identify the kind of ObjectType /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed"; + ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 1343] = "ObjectTypeKindMask"; + // Flags that require TypeFlags.Object + ObjectFlags[ObjectFlags["ContainsSpread"] = 4194304] = "ContainsSpread"; + ObjectFlags[ObjectFlags["ObjectRestType"] = 8388608] = "ObjectRestType"; /* @internal */ - ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables"; + ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 16777216] = "IsClassInstanceClone"; + // Flags that require TypeFlags.Object and ObjectFlags.Reference /* @internal */ - ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeCalculated"] = 33554432] = "IdenticalBaseTypeCalculated"; /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed"; + ObjectFlags[ObjectFlags["IdenticalBaseTypeExists"] = 67108864] = "IdenticalBaseTypeExists"; + // Flags that require TypeFlags.UnionOrIntersection or TypeFlags.Substitution /* @internal */ - ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection"; + ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 1073741824] = "IsClassInstanceClone"; - ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; /* @internal */ - ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; + ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; /* @internal */ - ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags"; - // Object flags that uniquely identify the kind of ObjectType + ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + // Flags that require TypeFlags.Union /* @internal */ - ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 2367] = "ObjectTypeKindMask"; + ObjectFlags[ObjectFlags["ContainsIntersections"] = 67108864] = "ContainsIntersections"; + // Flags that require TypeFlags.Intersection + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 67108864] = "IsNeverIntersectionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersection"] = 134217728] = "IsNeverIntersection"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ var VarianceFlags; @@ -4860,16 +4912,17 @@ var ts; (function (InferencePriority) { InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; InferencePriority[InferencePriority["SpeculativeTuple"] = 2] = "SpeculativeTuple"; - InferencePriority[InferencePriority["HomomorphicMappedType"] = 4] = "HomomorphicMappedType"; - InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 8] = "PartialHomomorphicMappedType"; - InferencePriority[InferencePriority["MappedTypeConstraint"] = 16] = "MappedTypeConstraint"; - InferencePriority[InferencePriority["ContravariantConditional"] = 32] = "ContravariantConditional"; - InferencePriority[InferencePriority["ReturnType"] = 64] = "ReturnType"; - InferencePriority[InferencePriority["LiteralKeyof"] = 128] = "LiteralKeyof"; - InferencePriority[InferencePriority["NoConstraints"] = 256] = "NoConstraints"; - InferencePriority[InferencePriority["AlwaysStrict"] = 512] = "AlwaysStrict"; - InferencePriority[InferencePriority["MaxValue"] = 1024] = "MaxValue"; - InferencePriority[InferencePriority["PriorityImpliesCombination"] = 208] = "PriorityImpliesCombination"; + InferencePriority[InferencePriority["SubstituteSource"] = 4] = "SubstituteSource"; + InferencePriority[InferencePriority["HomomorphicMappedType"] = 8] = "HomomorphicMappedType"; + InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 16] = "PartialHomomorphicMappedType"; + InferencePriority[InferencePriority["MappedTypeConstraint"] = 32] = "MappedTypeConstraint"; + InferencePriority[InferencePriority["ContravariantConditional"] = 64] = "ContravariantConditional"; + InferencePriority[InferencePriority["ReturnType"] = 128] = "ReturnType"; + InferencePriority[InferencePriority["LiteralKeyof"] = 256] = "LiteralKeyof"; + InferencePriority[InferencePriority["NoConstraints"] = 512] = "NoConstraints"; + InferencePriority[InferencePriority["AlwaysStrict"] = 1024] = "AlwaysStrict"; + InferencePriority[InferencePriority["MaxValue"] = 2048] = "MaxValue"; + InferencePriority[InferencePriority["PriorityImpliesCombination"] = 416] = "PriorityImpliesCombination"; InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); /* @internal */ @@ -4947,20 +5000,23 @@ var ts; WatchFileKind[WatchFileKind["FixedPollingInterval"] = 0] = "FixedPollingInterval"; WatchFileKind[WatchFileKind["PriorityPollingInterval"] = 1] = "PriorityPollingInterval"; WatchFileKind[WatchFileKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; - WatchFileKind[WatchFileKind["UseFsEvents"] = 3] = "UseFsEvents"; - WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 4] = "UseFsEventsOnParentDirectory"; + WatchFileKind[WatchFileKind["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; + WatchFileKind[WatchFileKind["UseFsEvents"] = 4] = "UseFsEvents"; + WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 5] = "UseFsEventsOnParentDirectory"; })(WatchFileKind = ts.WatchFileKind || (ts.WatchFileKind = {})); var WatchDirectoryKind; (function (WatchDirectoryKind) { WatchDirectoryKind[WatchDirectoryKind["UseFsEvents"] = 0] = "UseFsEvents"; WatchDirectoryKind[WatchDirectoryKind["FixedPollingInterval"] = 1] = "FixedPollingInterval"; WatchDirectoryKind[WatchDirectoryKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; + WatchDirectoryKind[WatchDirectoryKind["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; })(WatchDirectoryKind = ts.WatchDirectoryKind || (ts.WatchDirectoryKind = {})); var PollingWatchKind; (function (PollingWatchKind) { PollingWatchKind[PollingWatchKind["FixedInterval"] = 0] = "FixedInterval"; PollingWatchKind[PollingWatchKind["PriorityInterval"] = 1] = "PriorityInterval"; PollingWatchKind[PollingWatchKind["DynamicPriority"] = 2] = "DynamicPriority"; + PollingWatchKind[PollingWatchKind["FixedChunkSize"] = 3] = "FixedChunkSize"; })(PollingWatchKind = ts.PollingWatchKind || (ts.PollingWatchKind = {})); var ModuleKind; (function (ModuleKind) { @@ -5021,6 +5077,7 @@ var ts; ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019"; ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020"; + ScriptTarget[ScriptTarget["ES2021"] = 8] = "ES2021"; ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext"; ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest"; @@ -5183,29 +5240,30 @@ var ts; TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript"; TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx"; TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext"; - TransformFlags[TransformFlags["ContainsES2020"] = 8] = "ContainsES2020"; - TransformFlags[TransformFlags["ContainsES2019"] = 16] = "ContainsES2019"; - TransformFlags[TransformFlags["ContainsES2018"] = 32] = "ContainsES2018"; - TransformFlags[TransformFlags["ContainsES2017"] = 64] = "ContainsES2017"; - TransformFlags[TransformFlags["ContainsES2016"] = 128] = "ContainsES2016"; - TransformFlags[TransformFlags["ContainsES2015"] = 256] = "ContainsES2015"; - TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; - TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 1024] = "ContainsDestructuringAssignment"; + TransformFlags[TransformFlags["ContainsES2021"] = 8] = "ContainsES2021"; + TransformFlags[TransformFlags["ContainsES2020"] = 16] = "ContainsES2020"; + TransformFlags[TransformFlags["ContainsES2019"] = 32] = "ContainsES2019"; + TransformFlags[TransformFlags["ContainsES2018"] = 64] = "ContainsES2018"; + TransformFlags[TransformFlags["ContainsES2017"] = 128] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 256] = "ContainsES2016"; + TransformFlags[TransformFlags["ContainsES2015"] = 512] = "ContainsES2015"; + TransformFlags[TransformFlags["ContainsGenerator"] = 1024] = "ContainsGenerator"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 2048] = "ContainsTypeScriptClassSyntax"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 4096] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsRestOrSpread"] = 8192] = "ContainsRestOrSpread"; - TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 16384] = "ContainsObjectRestOrSpread"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 32768] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 65536] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 131072] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 262144] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsAwait"] = 524288] = "ContainsAwait"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 1048576] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 2097152] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["ContainsClassFields"] = 4194304] = "ContainsClassFields"; - TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 8388608] = "ContainsPossibleTopLevelAwait"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 16384] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 32768] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 65536] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 131072] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 262144] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 524288] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsAwait"] = 1048576] = "ContainsAwait"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 2097152] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 4194304] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["ContainsClassFields"] = 8388608] = "ContainsClassFields"; + TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 16777216] = "ContainsPossibleTopLevelAwait"; // 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 @@ -5215,37 +5273,38 @@ var ts; TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript"; TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx"; TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext"; - TransformFlags[TransformFlags["AssertES2020"] = 8] = "AssertES2020"; - TransformFlags[TransformFlags["AssertES2019"] = 16] = "AssertES2019"; - TransformFlags[TransformFlags["AssertES2018"] = 32] = "AssertES2018"; - TransformFlags[TransformFlags["AssertES2017"] = 64] = "AssertES2017"; - TransformFlags[TransformFlags["AssertES2016"] = 128] = "AssertES2016"; - TransformFlags[TransformFlags["AssertES2015"] = 256] = "AssertES2015"; - TransformFlags[TransformFlags["AssertGenerator"] = 512] = "AssertGenerator"; - TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 1024] = "AssertDestructuringAssignment"; + TransformFlags[TransformFlags["AssertES2021"] = 8] = "AssertES2021"; + TransformFlags[TransformFlags["AssertES2020"] = 16] = "AssertES2020"; + TransformFlags[TransformFlags["AssertES2019"] = 32] = "AssertES2019"; + TransformFlags[TransformFlags["AssertES2018"] = 64] = "AssertES2018"; + TransformFlags[TransformFlags["AssertES2017"] = 128] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 256] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 512] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 1024] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 2048] = "AssertDestructuringAssignment"; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes"; TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes"; TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 547309568] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 547313664] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 547311616] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 538923008] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["PropertyExcludes"] = 536875008] = "PropertyExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 536905728] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 546379776] = "ModuleExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 557748224] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 557756416] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 557752320] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 540975104] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["PropertyExcludes"] = 536879104] = "PropertyExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 536940544] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 555888640] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536922112] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536879104] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537018368] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536973312] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536887296] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537165824] = "VariableDeclarationListExcludes"; TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 536887296] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 536879104] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 536903680] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 536887296] = "BindingPatternExcludes"; // Propagating flags // - Bitmasks for flags that should propagate from a child - TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 4096] = "PropertyNamePropagatingFlags"; + TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 8192] = "PropertyNamePropagatingFlags"; // Masks // - Additional bitmasks })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); @@ -6113,7 +6172,7 @@ var ts; * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. * Comparison is case-sensitive between the canonical paths. * - * @deprecated Use `containsPath` if possible. + * Use `containsPath` if file names are not already reduced and absolute. */ function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { var canonicalFileName = getCanonicalFileName(fileName); @@ -6233,6 +6292,11 @@ var ts; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time + /* @internal */ + function getModifiedTime(host, fileName) { + return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; + } + ts.getModifiedTime = getModifiedTime; function createPollingIntervalBasedLevels(levels) { var _a; return _a = {}, @@ -6289,6 +6353,51 @@ var ts; } } ts.setCustomPollingValues = setCustomPollingValues; + function pollWatchedFileQueue(host, queue, pollIndex, chunkSize, callbackOnWatchFileStat) { + var definedValueCopyToIndex = pollIndex; + // Max visit would be all elements of the queue + for (var canVisit = queue.length; chunkSize && canVisit; nextPollIndex(), canVisit--) { + var watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + // Only files polled count towards chunkSize + chunkSize--; + var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(host, watchedFile.fileName)); + if (watchedFile.isClosed) { + // Closed watcher as part of callback + queue[pollIndex] = undefined; + continue; + } + callbackOnWatchFileStat === null || callbackOnWatchFileStat === void 0 ? void 0 : callbackOnWatchFileStat(watchedFile, pollIndex, fileChanged); + // Defragment the queue while we are at it + if (queue[pollIndex]) { + // Copy this file to the non hole location + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + // Return next poll index + return pollIndex; + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + // There are holes from definedValueCopyToIndex to end of queue, change queue size + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } /* @internal */ function createDynamicPriorityPollingWatchFile(host) { var watchedFiles = []; @@ -6302,7 +6411,7 @@ var ts; fileName: fileName, callback: callback, unchangedPolls: 0, - mtime: getModifiedTime(fileName) + mtime: getModifiedTime(host, fileName) }; watchedFiles.push(file); addToPollingIntervalQueue(file, defaultPollingInterval); @@ -6345,25 +6454,9 @@ var ts; } } function pollQueue(queue, pollingInterval, pollIndex, chunkSize) { - // Max visit would be all elements of the queue - var needsVisit = queue.length; - var definedValueCopyToIndex = pollIndex; - for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { - var watchedFile = queue[pollIndex]; - if (!watchedFile) { - continue; - } - else if (watchedFile.isClosed) { - queue[pollIndex] = undefined; - continue; - } - polled++; - var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); - if (watchedFile.isClosed) { - // Closed watcher as part of callback - queue[pollIndex] = undefined; - } - else if (fileChanged) { + return pollWatchedFileQueue(host, queue, pollIndex, chunkSize, onWatchFileStat); + function onWatchFileStat(watchedFile, pollIndex, fileChanged) { + if (fileChanged) { watchedFile.unchangedPolls = 0; // Changed files go to changedFilesInLastPoll queue if (queue !== changedFilesInLastPoll) { @@ -6385,27 +6478,6 @@ var ts; queue[pollIndex] = undefined; addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); } - if (queue[pollIndex]) { - // Copy this file to the non hole location - if (definedValueCopyToIndex < pollIndex) { - queue[definedValueCopyToIndex] = watchedFile; - queue[pollIndex] = undefined; - } - definedValueCopyToIndex++; - } - } - // Return next poll index - return pollIndex; - function nextPollIndex() { - pollIndex++; - if (pollIndex === queue.length) { - if (definedValueCopyToIndex < pollIndex) { - // There are holes from nextDefinedValueIndex to end of queue, change queue size - queue.length = definedValueCopyToIndex; - } - pollIndex = 0; - definedValueCopyToIndex = 0; - } } } function pollingIntervalQueue(pollingInterval) { @@ -6434,9 +6506,6 @@ var ts; function scheduleNextPoll(pollingInterval) { pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); } - function getModifiedTime(fileName) { - return host.getModifiedTime(fileName) || ts.missingFileModifiedTime; - } } ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile; function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) { @@ -6487,6 +6556,37 @@ var ts; return watcher; } } + function createFixedChunkSizePollingWatchFile(host) { + var watchedFiles = []; + var pollIndex = 0; + var pollScheduled; + return watchFile; + function watchFile(fileName, callback) { + var file = { + fileName: fileName, + callback: callback, + mtime: getModifiedTime(host, fileName) + }; + watchedFiles.push(file); + scheduleNextPoll(); + return { + close: function () { + file.isClosed = true; + ts.unorderedRemoveItem(watchedFiles, file); + } + }; + } + function pollQueue() { + pollScheduled = undefined; + pollIndex = pollWatchedFileQueue(host, watchedFiles, pollIndex, pollingChunkSize[PollingInterval.Low]); + scheduleNextPoll(); + } + function scheduleNextPoll() { + if (!watchedFiles.length || pollScheduled) + return; + pollScheduled = host.setTimeout(pollQueue, PollingInterval.High); + } + } /* @internal */ function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) { var cache = new ts.Map(); @@ -6809,8 +6909,9 @@ var ts; } /*@internal*/ function createSystemWatchFunctions(_a) { - var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory; + var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind; var dynamicPollingWatchFile; + var fixedChunkSizePollingWatchFile; var nonPollingWatchFile; var hostRecursiveDirectoryWatcher; return { @@ -6827,6 +6928,8 @@ var ts; return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined); case ts.WatchFileKind.DynamicPriorityPolling: return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined); + case ts.WatchFileKind.FixedChunkSizePolling: + return ensureFixedChunkSizePollingWatchFile()(fileName, callback, /* pollingInterval */ undefined, /*options*/ undefined); case ts.WatchFileKind.UseFsEvents: return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options)); @@ -6840,8 +6943,10 @@ var ts; } } function ensureDynamicPollingWatchFile() { - return dynamicPollingWatchFile || - (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })); + return dynamicPollingWatchFile || (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })); + } + function ensureFixedChunkSizePollingWatchFile() { + return fixedChunkSizePollingWatchFile || (fixedChunkSizePollingWatchFile = createFixedChunkSizePollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout })); } function updateOptionsForWatchFile(options, useNonPollingWatchers) { if (options && options.watchFile !== undefined) @@ -6867,7 +6972,7 @@ var ts; // Use notifications from FS to watch with falling back to fs.watchFile generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) : // Default to do not use fixed polling interval - { watchFile: ts.WatchFileKind.FixedPollingInterval }; + { watchFile: (defaultWatchFileKind === null || defaultWatchFileKind === void 0 ? void 0 : defaultWatchFileKind()) || ts.WatchFileKind.FixedPollingInterval }; } } function generateWatchFileOptions(watchFile, fallbackPolling, options) { @@ -6908,6 +7013,10 @@ var ts; case ts.WatchDirectoryKind.DynamicPriorityPolling: return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, /*options*/ undefined); + case ts.WatchDirectoryKind.FixedChunkSizePolling: + return ensureFixedChunkSizePollingWatchFile()(directoryName, function () { return callback(directoryName); }, + /* pollingInterval */ undefined, + /*options*/ undefined); case ts.WatchDirectoryKind.UseFsEvents: return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), recursive, PollingInterval.Medium, ts.getFallbackOptions(watchDirectoryOptions)); default: @@ -6986,13 +7095,13 @@ var ts; } var activeSession; var profilePath = "./profile.cpuprofile"; - var realpathSync = (_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync; var Buffer = require("buffer").Buffer; var nodeVersion = getNodeMajorVersion(); var isNode4OrLater = nodeVersion >= 4; var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin"; var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + var realpathSync = useCaseSensitiveFileNames ? ((_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync) : _fs.realpathSync; var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); var getCurrentDirectory = ts.memoize(function () { return process.cwd(); }); var _c = createSystemWatchFunctions({ @@ -7013,6 +7122,7 @@ var ts; tscWatchFile: process.env.TSC_WATCHFILE, useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER, tscWatchDirectory: process.env.TSC_WATCHDIRECTORY, + defaultWatchFileKind: function () { var _a, _b; return (_b = (_a = sys).defaultWatchFileKind) === null || _b === void 0 ? void 0 : _b.call(_a); }, }), watchFile = _c.watchFile, watchDirectory = _c.watchDirectory; var nodeSystem = { args: process.argv.slice(2), @@ -7081,6 +7191,7 @@ var ts; }, enableCPUProfiler: enableCPUProfiler, disableCPUProfiler: disableCPUProfiler, + cpuProfilingEnabled: function () { return !!activeSession || ts.contains(process.execArgv, "--cpu-prof") || ts.contains(process.execArgv, "--prof"); }, realpath: realpath, debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -7330,7 +7441,7 @@ var ts; return event === "rename" && (!relativeName || relativeName === lastDirectoryPart || - relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) && + (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) && !fileSystemEntryExists(fileOrDirectory, entryKind) ? invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) : callback(event, relativeName); @@ -7640,7 +7751,7 @@ var ts; Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1103, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1103", "'for await' loops are only allowed within async functions and at the top levels of modules."), A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), @@ -7689,7 +7800,7 @@ var ts; A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165", "A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."), - A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."), + A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_1166", "A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type."), A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168", "A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."), A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169", "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."), A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170", "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."), @@ -7749,7 +7860,7 @@ var ts; A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), - An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231", "An export assignment must be at the top level of a file or module declaration."), An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), @@ -7775,6 +7886,7 @@ var ts; A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), + A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1258, ts.DiagnosticCategory.Error, "A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration_1258", "A default export must be at the top level of a file or module declaration."), Module_0_can_only_be_default_imported_using_the_1_flag: diag(1259, ts.DiagnosticCategory.Error, "Module_0_can_only_be_default_imported_using_the_1_flag_1259", "Module '{0}' can only be default-imported using the '{1}' flag"), Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), @@ -7861,7 +7973,7 @@ var ts; Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."), _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."), Provides_a_root_package_name_when_using_outFile_with_declarations: diag(1390, ts.DiagnosticCategory.Message, "Provides_a_root_package_name_when_using_outFile_with_declarations_1390", "Provides a root package name when using outFile with declarations."), - The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The `bundledPackageName` option must be provided when using outFile and node module resolution with declaration emit."), + The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The 'bundledPackageName' option must be provided when using outFile and node module resolution with declaration emit."), An_import_alias_cannot_use_import_type: diag(1392, ts.DiagnosticCategory.Error, "An_import_alias_cannot_use_import_type_1392", "An import alias cannot use 'import type'"), Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"), Imported_via_0_from_file_1_with_packageId_2: diag(1394, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_with_packageId_2_1394", "Imported via {0} from file '{1}' with packageId '{2}'"), @@ -7901,6 +8013,9 @@ var ts; File_is_output_of_project_reference_source_0: diag(1428, ts.DiagnosticCategory.Message, "File_is_output_of_project_reference_source_0_1428", "File is output of project reference source '{0}'"), File_redirects_to_file_0: diag(1429, ts.DiagnosticCategory.Message, "File_redirects_to_file_0_1429", "File redirects to file '{0}'"), The_file_is_in_the_program_because_Colon: diag(1430, ts.DiagnosticCategory.Message, "The_file_is_in_the_program_because_Colon_1430", "The file is in the program because:"), + for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1431, ts.DiagnosticCategory.Error, "for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_1431", "'for await' loops are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1432, ts.DiagnosticCategory.Error, "Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), + Decorators_may_not_be_applied_to_this_parameters: diag(1433, ts.DiagnosticCategory.Error, "Decorators_may_not_be_applied_to_this_parameters_1433", "Decorators may not be applied to 'this' parameters."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -7968,7 +8083,7 @@ var ts; The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), - The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_in_expression_must_not_be_a_primitive: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_not_be_a_primitive_2361", "The right-hand side of an 'in' expression must not be a primitive."), The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."), The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), @@ -7986,8 +8101,7 @@ var ts; A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers."), Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), - Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."), - get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."), + The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type: diag(2380, ts.DiagnosticCategory.Error, "The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type_2380", "The return type of a 'get' accessor must be assignable to its 'set' accessor type"), A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."), Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."), Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), @@ -8050,7 +8164,7 @@ var ts; Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), - Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_cl_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'. This is an instance of class '{2}'."), The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), @@ -8150,14 +8264,13 @@ var ts; The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the `lib` compiler option to '{2}' or later."), + Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{2}' or later."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), - Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."), - Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."), + A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter: diag(2556, ts.DiagnosticCategory.Error, "A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter_2556", "A spread argument must either have a tuple type or be passed to a rest parameter."), Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), @@ -8180,17 +8293,17 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to '{1}' or later."), - Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{1}' or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the 'lib' compiler option to es2015 or later."), Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."), Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add `node` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add `jquery` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add 'jquery' to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), @@ -8223,6 +8336,12 @@ var ts; Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target: diag(2625, ts.DiagnosticCategory.Error, "Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target_2625", "Variadic element at position {0} in source does not match element at position {1} in target."), Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target: diag(2626, ts.DiagnosticCategory.Error, "Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target_2626", "Type at position {0} in source is not compatible with type at position {1} in target."), Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target: diag(2627, ts.DiagnosticCategory.Error, "Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target_2627", "Type at positions {0} through {1} in source is not compatible with type at position {2} in target."), + Cannot_assign_to_0_because_it_is_an_enum: diag(2628, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_an_enum_2628", "Cannot assign to '{0}' because it is an enum."), + Cannot_assign_to_0_because_it_is_a_class: diag(2629, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_class_2629", "Cannot assign to '{0}' because it is a class."), + Cannot_assign_to_0_because_it_is_a_function: diag(2630, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_function_2630", "Cannot assign to '{0}' because it is a function."), + Cannot_assign_to_0_because_it_is_a_namespace: diag(2631, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_namespace_2631", "Cannot assign to '{0}' because it is a namespace."), + Cannot_assign_to_0_because_it_is_an_import: diag(2632, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_an_import_2632", "Cannot assign to '{0}' because it is an import."), + JSX_property_access_expressions_cannot_include_JSX_namespace_names: diag(2633, ts.DiagnosticCategory.Error, "JSX_property_access_expressions_cannot_include_JSX_namespace_names_2633", "JSX property access expressions cannot include JSX namespace names"), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -8269,7 +8388,7 @@ var ts; Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), @@ -8277,14 +8396,14 @@ var ts; _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a 'delete' operator must be a property reference."), The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a 'delete' operator cannot be a read-only property."), - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), - A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), - A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor: diag(2715, ts.DiagnosticCategory.Error, "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715", "Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."), @@ -8346,7 +8465,7 @@ var ts; The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."), Overload_0_of_1_2_gave_the_following_error: diag(2772, ts.DiagnosticCategory.Error, "Overload_0_of_1_2_gave_the_following_error_2772", "Overload {0} of {1}, '{2}', gave the following error."), Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"), - This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it__2774", "This condition will always return true since the function is always defined. Did you mean to call it instead?"), + This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774", "This condition will always return true since this function is always defined. Did you mean to call it instead?"), Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation: diag(2775, ts.DiagnosticCategory.Error, "Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation_2775", "Assertions require every name in the call target to be declared with an explicit type annotation."), Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name: diag(2776, ts.DiagnosticCategory.Error, "Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name_2776", "Assertions require the call target to be an identifier or qualified name."), The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access: diag(2777, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777", "The operand of an increment or decrement operator may not be an optional property access."), @@ -8370,6 +8489,21 @@ var ts; The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types: diag(2795, ts.DiagnosticCategory.Error, "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795", "The 'intrinsic' keyword can only be used to declare compiler provided intrinsic types."), It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked: diag(2796, ts.DiagnosticCategory.Error, "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796", "It is likely that you are missing a comma to separate these two template expressions. They form a tagged template expression which cannot be invoked."), A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract: diag(2797, ts.DiagnosticCategory.Error, "A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_2797", "A mixin class that extends from a type variable containing an abstract construct signature must also be declared 'abstract'."), + The_declaration_was_marked_as_deprecated_here: diag(2798, ts.DiagnosticCategory.Error, "The_declaration_was_marked_as_deprecated_here_2798", "The declaration was marked as deprecated here."), + Type_produces_a_tuple_type_that_is_too_large_to_represent: diag(2799, ts.DiagnosticCategory.Error, "Type_produces_a_tuple_type_that_is_too_large_to_represent_2799", "Type produces a tuple type that is too large to represent."), + Expression_produces_a_tuple_type_that_is_too_large_to_represent: diag(2800, ts.DiagnosticCategory.Error, "Expression_produces_a_tuple_type_that_is_too_large_to_represent_2800", "Expression produces a tuple type that is too large to represent."), + This_condition_will_always_return_true_since_this_0_is_always_defined: diag(2801, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_this_0_is_always_defined_2801", "This condition will always return true since this '{0}' is always defined."), + Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher: diag(2802, ts.DiagnosticCategory.Error, "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802", "Type '{0}' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher."), + Cannot_assign_to_private_method_0_Private_methods_are_not_writable: diag(2803, ts.DiagnosticCategory.Error, "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803", "Cannot assign to private method '{0}'. Private methods are not writable."), + Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name: diag(2804, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804", "Duplicate identifier '{0}'. Static and instance elements cannot share the same private name."), + Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag: diag(2805, ts.DiagnosticCategory.Error, "Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_no_2805", "Static fields with private names can't have initializers when the '--useDefineForClassFields' flag is not specified with a '--target' of 'esnext'. Consider adding the '--useDefineForClassFields' flag."), + Private_accessor_was_defined_without_a_getter: diag(2806, ts.DiagnosticCategory.Error, "Private_accessor_was_defined_without_a_getter_2806", "Private accessor was defined without a getter."), + This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0: diag(2807, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807", "This syntax requires an imported helper named '{1}' with {2} parameters, which is not compatible with the one in '{0}'. Consider upgrading your version of '{0}'."), + A_get_accessor_must_be_at_least_as_accessible_as_the_setter: diag(2808, ts.DiagnosticCategory.Error, "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808", "A get accessor must be at least as accessible as the setter"), + Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses: diag(2809, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809", "Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses."), + Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false: diag(2810, ts.DiagnosticCategory.Error, "Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnex_2810", "Property '{0}' may not be used in a static property's initializer in the same class when 'target' is 'esnext' and 'useDefineForClassFields' is 'false'."), + Initializer_for_property_0: diag(2811, ts.DiagnosticCategory.Error, "Initializer_for_property_0_2811", "Initializer for property '{0}'"), + Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom: diag(2812, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812", "Property '{0}' does not exist on type '{1}'. Try changing the 'lib' compiler option to include 'dom'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -8442,6 +8576,7 @@ var ts; Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2: diag(4084, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084", "Exported type alias '{0}' has or is using private name '{1}' from module {2}."), Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Error, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), @@ -8463,6 +8598,11 @@ var ts; Type_arguments_for_0_circularly_reference_themselves: diag(4109, ts.DiagnosticCategory.Error, "Type_arguments_for_0_circularly_reference_themselves_4109", "Type arguments for '{0}' circularly reference themselves."), Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."), Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0: diag(4111, ts.DiagnosticCategory.Error, "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111", "Property '{0}' comes from an index signature, so it must be accessed with ['{0}']."), + This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class: diag(4112, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another__4112", "This member cannot have an 'override' modifier because its containing class '{0}' does not extend another class."), + This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0: diag(4113, ts.DiagnosticCategory.Error, "This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_4113", "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'."), + This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0: diag(4114, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0_4114", "This member must have an 'override' modifier because it overrides a member in the base class '{0}'."), + This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0: diag(4115, ts.DiagnosticCategory.Error, "This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0_4115", "This parameter property must have an 'override' modifier because it overrides a member in base class '{0}'."), + This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0: diag(4116, ts.DiagnosticCategory.Error, "This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared__4116", "This member must have an 'override' modifier because it overrides an abstract method that is declared in the base class '{0}'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -8497,7 +8637,7 @@ var ts; Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), - Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option `--tsBuildInfoFile` is specified."), + Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified: diag(5074, ts.DiagnosticCategory.Error, "Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBui_5074", "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option '--tsBuildInfoFile' is specified."), _0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2: diag(5075, ts.DiagnosticCategory.Error, "_0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_5075", "'{0}' is assignable to the constraint of type '{1}', but '{1}' could be instantiated with a different subtype of constraint '{2}'."), _0_and_1_operations_cannot_be_mixed_without_parentheses: diag(5076, ts.DiagnosticCategory.Error, "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076", "'{0}' and '{1}' operations cannot be mixed without parentheses."), Unknown_build_option_0_Did_you_mean_1: diag(5077, ts.DiagnosticCategory.Error, "Unknown_build_option_0_Did_you_mean_1_5077", "Unknown build option '{0}'. Did you mean '{1}'?"), @@ -8510,10 +8650,14 @@ var ts; Tuple_members_must_all_have_names_or_all_not_have_names: diag(5084, ts.DiagnosticCategory.Error, "Tuple_members_must_all_have_names_or_all_not_have_names_5084", "Tuple members must all have names or all not have names."), A_tuple_member_cannot_be_both_optional_and_rest: diag(5085, ts.DiagnosticCategory.Error, "A_tuple_member_cannot_be_both_optional_and_rest_5085", "A tuple member cannot be both optional and rest."), A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type: diag(5086, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086", "A labeled tuple element is declared as optional with a question mark after the name and before the colon, rather than after the type."), - A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a `...` before the name, rather than before the type."), + A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a '...' before the name, rather than before the type."), The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary: diag(5088, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088", "The inferred type of '{0}' references a type with a cyclic structure which cannot be trivially serialized. A type annotation is necessary."), Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."), Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"), + Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled: diag(5091, ts.DiagnosticCategory.Error, "Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled_5091", "Option 'preserveConstEnums' cannot be disabled when 'isolatedModules' is enabled."), + The_root_value_of_a_0_file_must_be_an_object: diag(5092, ts.DiagnosticCategory.Error, "The_root_value_of_a_0_file_must_be_an_object_5092", "The root value of a '{0}' file must be an object."), + Compiler_option_0_may_only_be_used_with_build: diag(5093, ts.DiagnosticCategory.Error, "Compiler_option_0_may_only_be_used_with_build_5093", "Compiler option '--{0}' may only be used with '--build'."), + Compiler_option_0_may_not_be_used_with_build: diag(5094, ts.DiagnosticCategory.Error, "Compiler_option_0_may_not_be_used_with_build_5094", "Compiler option '--{0}' may not be used with '--build'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -8529,7 +8673,7 @@ var ts; Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), @@ -8724,9 +8868,9 @@ var ts; Emit_class_fields_with_Define_instead_of_Set: diag(6222, ts.DiagnosticCategory.Message, "Emit_class_fields_with_Define_instead_of_Set_6222", "Emit class fields with Define instead of Set."), Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."), Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."), - Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."), - Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling'."), - Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority'."), + Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."), + Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling'."), + Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority_FixedChunkSize: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority', 'FixedChunkSize'."), Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively: diag(6228, ts.DiagnosticCategory.Message, "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6228", "Synchronously call callbacks and update the state of directory watchers on platforms that don't support recursive watching natively."), Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3: diag(6229, ts.DiagnosticCategory.Error, "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229", "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'."), Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."), @@ -8737,7 +8881,11 @@ var ts; Disable_loading_referenced_projects: diag(6235, ts.DiagnosticCategory.Message, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."), Arguments_for_the_rest_parameter_0_were_not_provided: diag(6236, ts.DiagnosticCategory.Error, "Arguments_for_the_rest_parameter_0_were_not_provided_6236", "Arguments for the rest parameter '{0}' were not provided."), Generates_an_event_trace_and_a_list_of_types: diag(6237, ts.DiagnosticCategory.Message, "Generates_an_event_trace_and_a_list_of_types_6237", "Generates an event trace and a list of types."), - Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the `jsx` and `jsxs` factory functions from. eg, react"), + Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the 'jsx' and 'jsxs' factory functions from. eg, react"), + File_0_exists_according_to_earlier_cached_lookups: diag(6239, ts.DiagnosticCategory.Message, "File_0_exists_according_to_earlier_cached_lookups_6239", "File '{0}' exists according to earlier cached lookups."), + File_0_does_not_exist_according_to_earlier_cached_lookups: diag(6240, ts.DiagnosticCategory.Message, "File_0_does_not_exist_according_to_earlier_cached_lookups_6240", "File '{0}' does not exist according to earlier cached lookups."), + Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1: diag(6241, ts.DiagnosticCategory.Message, "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241", "Resolution for type reference directive '{0}' was found in cache from location '{1}'."), + Resolving_type_reference_directive_0_containing_file_1: diag(6242, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_6242", "======== Resolving type reference directive '{0}', containing file '{1}'. ========"), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -8782,16 +8930,19 @@ var ts; Skipping_build_of_project_0_because_its_dependency_1_was_not_built: diag(6382, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382", "Skipping build of project '{0}' because its dependency '{1}' was not built"), Project_0_can_t_be_built_because_its_dependency_1_was_not_built: diag(6383, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383", "Project '{0}' can't be built because its dependency '{1}' was not built"), Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it: diag(6384, ts.DiagnosticCategory.Message, "Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_di_6384", "Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it."), - _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."), + The_signature_0_of_1_is_deprecated: diag(6387, ts.DiagnosticCategory.Suggestion, "The_signature_0_of_1_is_deprecated_6387", "The signature '{0}' of '{1}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true), + Project_0_is_being_forcibly_rebuilt: diag(6388, ts.DiagnosticCategory.Message, "Project_0_is_being_forcibly_rebuilt_6388", "Project '{0}' is being forcibly rebuilt"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option: diag(6504, ts.DiagnosticCategory.Error, "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504", "File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?"), Print_names_of_files_and_the_reason_they_are_part_of_the_compilation: diag(6505, ts.DiagnosticCategory.Message, "Print_names_of_files_and_the_reason_they_are_part_of_the_compilation_6505", "Print names of files and the reason they are part of the compilation."), - Require_undeclared_properties_from_index_signatures_to_use_element_accesses: diag(6803, ts.DiagnosticCategory.Error, "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803", "Require undeclared properties from index signatures to use element accesses."), Include_undefined_in_index_signature_results: diag(6800, ts.DiagnosticCategory.Message, "Include_undefined_in_index_signature_results_6800", "Include 'undefined' in index signature results"), + Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier: diag(6801, ts.DiagnosticCategory.Message, "Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier_6801", "Ensure overriding members in derived classes are marked with an 'override' modifier."), + Require_undeclared_properties_from_index_signatures_to_use_element_accesses: diag(6802, ts.DiagnosticCategory.Message, "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6802", "Require undeclared properties from index signatures to use element accesses."), 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."), @@ -8824,7 +8975,7 @@ var ts; Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), - If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'"), The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), @@ -8864,7 +9015,7 @@ var ts; JSDoc_0_is_not_attached_to_a_class: diag(8022, ts.DiagnosticCategory.Error, "JSDoc_0_is_not_attached_to_a_class_8022", "JSDoc '@{0}' is not attached to a class."), JSDoc_0_1_does_not_match_the_extends_2_clause: diag(8023, ts.DiagnosticCategory.Error, "JSDoc_0_1_does_not_match_the_extends_2_clause_8023", "JSDoc '@{0} {1}' does not match the 'extends {2}' clause."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name: diag(8024, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name."), - Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one `@augments` or `@extends` tag."), + Class_declarations_cannot_have_more_than_one_augments_or_extends_tag: diag(8025, ts.DiagnosticCategory.Error, "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025", "Class declarations cannot have more than one '@augments' or '@extends' tag."), Expected_0_type_arguments_provide_these_with_an_extends_tag: diag(8026, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_provide_these_with_an_extends_tag_8026", "Expected {0} type arguments; provide these with an '@extends' tag."), Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), @@ -9109,6 +9260,10 @@ var ts; Add_all_missing_function_declarations: diag(95157, ts.DiagnosticCategory.Message, "Add_all_missing_function_declarations_95157", "Add all missing function declarations"), Method_not_implemented: diag(95158, ts.DiagnosticCategory.Message, "Method_not_implemented_95158", "Method not implemented."), Function_not_implemented: diag(95159, ts.DiagnosticCategory.Message, "Function_not_implemented_95159", "Function not implemented."), + Add_override_modifier: diag(95160, ts.DiagnosticCategory.Message, "Add_override_modifier_95160", "Add 'override' modifier"), + Remove_override_modifier: diag(95161, ts.DiagnosticCategory.Message, "Remove_override_modifier_95161", "Remove 'override' modifier"), + Add_all_missing_override_modifiers: diag(95162, ts.DiagnosticCategory.Message, "Add_all_missing_override_modifiers_95162", "Add all missing 'override' modifiers"), + Remove_all_unnecessary_override_modifiers: diag(95163, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_override_modifiers_95163", "Remove all unnecessary 'override' modifiers"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -9123,8 +9278,6 @@ var ts; The_shadowing_declaration_of_0_is_defined_here: diag(18017, ts.DiagnosticCategory.Error, "The_shadowing_declaration_of_0_is_defined_here_18017", "The shadowing declaration of '{0}' is defined here"), The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here: diag(18018, ts.DiagnosticCategory.Error, "The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here_18018", "The declaration of '{0}' that you probably intended to use is defined here"), _0_modifier_cannot_be_used_with_a_private_identifier: diag(18019, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_private_identifier_18019", "'{0}' modifier cannot be used with a private identifier."), - A_method_cannot_be_named_with_a_private_identifier: diag(18022, ts.DiagnosticCategory.Error, "A_method_cannot_be_named_with_a_private_identifier_18022", "A method cannot be named with a private identifier."), - An_accessor_cannot_be_named_with_a_private_identifier: diag(18023, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_named_with_a_private_identifier_18023", "An accessor cannot be named with a private identifier."), An_enum_member_cannot_be_named_with_a_private_identifier: diag(18024, ts.DiagnosticCategory.Error, "An_enum_member_cannot_be_named_with_a_private_identifier_18024", "An enum member cannot be named with a private identifier."), can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), Compiler_reserves_name_0_when_emitting_private_identifier_downlevel: diag(18027, ts.DiagnosticCategory.Error, "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027", "Compiler reserves name '{0}' when emitting private identifier downlevel."), @@ -9136,6 +9289,7 @@ var ts; Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead: diag(18033, ts.DiagnosticCategory.Error, "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033", "Only numeric enums can have computed members, but this expression has type '{0}'. If you do not need exhaustiveness checks, consider using an object literal instead."), Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compiler_option_is_specified_e_g_Fragment: diag(18034, ts.DiagnosticCategory.Message, "Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compi_18034", "Specify the JSX fragment factory function to use when targeting 'react' JSX emit with 'jsxFactory' compiler option is specified, e.g. 'Fragment'."), Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(18035, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name_18035", "Invalid value for 'jsxFragmentFactory'. '{0}' is not a valid identifier or qualified-name."), + Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator: diag(18036, ts.DiagnosticCategory.Error, "Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_dec_18036", "Class decorators can't be used with static private identifier. Consider removing the experimental decorator."), }; })(ts || (ts = {})); var ts; @@ -9203,6 +9357,7 @@ var ts; _a.private = 120 /* PrivateKeyword */, _a.protected = 121 /* ProtectedKeyword */, _a.public = 122 /* PublicKeyword */, + _a.override = 156 /* OverrideKeyword */, _a.readonly = 142 /* ReadonlyKeyword */, _a.require = 143 /* RequireKeyword */, _a.global = 154 /* GlobalKeyword */, @@ -9229,7 +9384,7 @@ var ts; _a.yield = 124 /* YieldKeyword */, _a.async = 129 /* AsyncKeyword */, _a.await = 130 /* AwaitKeyword */, - _a.of = 156 /* OfKeyword */, + _a.of = 157 /* OfKeyword */, _a); var textToKeyword = new ts.Map(ts.getEntries(textToKeywordObj)); var textToToken = new ts.Map(ts.getEntries(__assign(__assign({}, textToKeywordObj), { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 29 /* LessThanToken */, ">": 31 /* GreaterThanToken */, "<=": 32 /* LessThanEqualsToken */, ">=": 33 /* GreaterThanEqualsToken */, "==": 34 /* EqualsEqualsToken */, "!=": 35 /* ExclamationEqualsToken */, "===": 36 /* EqualsEqualsEqualsToken */, "!==": 37 /* ExclamationEqualsEqualsToken */, "=>": 38 /* EqualsGreaterThanToken */, "+": 39 /* PlusToken */, "-": 40 /* MinusToken */, "**": 42 /* AsteriskAsteriskToken */, "*": 41 /* AsteriskToken */, "/": 43 /* SlashToken */, "%": 44 /* PercentToken */, "++": 45 /* PlusPlusToken */, "--": 46 /* MinusMinusToken */, "<<": 47 /* LessThanLessThanToken */, ">": 48 /* GreaterThanGreaterThanToken */, ">>>": 49 /* GreaterThanGreaterThanGreaterThanToken */, "&": 50 /* AmpersandToken */, "|": 51 /* BarToken */, "^": 52 /* CaretToken */, "!": 53 /* ExclamationToken */, "~": 54 /* TildeToken */, "&&": 55 /* AmpersandAmpersandToken */, "||": 56 /* BarBarToken */, "?": 57 /* QuestionToken */, "??": 60 /* QuestionQuestionToken */, "?.": 28 /* QuestionDotToken */, ":": 58 /* ColonToken */, "=": 62 /* EqualsToken */, "+=": 63 /* PlusEqualsToken */, "-=": 64 /* MinusEqualsToken */, "*=": 65 /* AsteriskEqualsToken */, "**=": 66 /* AsteriskAsteriskEqualsToken */, "/=": 67 /* SlashEqualsToken */, "%=": 68 /* PercentEqualsToken */, "<<=": 69 /* LessThanLessThanEqualsToken */, ">>=": 70 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 72 /* AmpersandEqualsToken */, "|=": 73 /* BarEqualsToken */, "^=": 77 /* CaretEqualsToken */, "||=": 74 /* BarBarEqualsToken */, "&&=": 75 /* AmpersandAmpersandEqualsToken */, "??=": 76 /* QuestionQuestionEqualsToken */, "@": 59 /* AtToken */, "`": 61 /* BacktickToken */ }))); @@ -9545,11 +9700,11 @@ var ts; } ts.couldStartTrivia = couldStartTrivia; /* @internal */ - function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) { - if (stopAtComments === void 0) { stopAtComments = false; } + function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments, inJSDoc) { if (ts.positionIsSynthesized(pos)) { return pos; } + var canConsumeStar = false; // Keep in sync with couldStartTrivia while (true) { var ch = text.charCodeAt(pos); @@ -9564,6 +9719,7 @@ var ts; if (stopAfterLineBreak) { return pos; } + canConsumeStar = !!inJSDoc; continue; case 9 /* tab */: case 11 /* verticalTab */: @@ -9583,6 +9739,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { @@ -9594,6 +9751,7 @@ var ts; } pos++; } + canConsumeStar = false; continue; } break; @@ -9603,12 +9761,21 @@ var ts; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos); + canConsumeStar = false; continue; } break; case 35 /* hash */: if (pos === 0 && isShebangTrivia(text, pos)) { pos = scanShebangTrivia(text, pos); + canConsumeStar = false; + continue; + } + break; + case 42 /* asterisk */: + if (canConsumeStar) { + pos++; + canConsumeStar = false; continue; } break; @@ -9913,6 +10080,7 @@ var ts; reScanJsxToken: reScanJsxToken, reScanLessThanToken: reScanLessThanToken, reScanQuestionToken: reScanQuestionToken, + reScanInvalidIdentifier: reScanInvalidIdentifier, scanJsxToken: scanJsxToken, scanJsDocToken: scanJsDocToken, scan: scan, @@ -10915,15 +11083,9 @@ var ts; } return token = 79 /* PrivateIdentifier */; default: - if (isIdentifierStart(ch, languageVersion)) { - pos += charSize(ch); - while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) - pos += charSize(ch); - tokenValue = text.substring(tokenPos, pos); - if (ch === 92 /* backslash */) { - tokenValue += scanIdentifierParts(); - } - return token = getIdentifierToken(); + var identifierKind = scanIdentifier(ch, languageVersion); + if (identifierKind) { + return token = identifierKind; } else if (isWhiteSpaceSingleLine(ch)) { pos += charSize(ch); @@ -10940,6 +11102,31 @@ var ts; } } } + function reScanInvalidIdentifier() { + ts.Debug.assert(token === 0 /* Unknown */, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'."); + pos = tokenPos = startPos; + tokenFlags = 0; + var ch = codePointAt(text, pos); + var identifierKind = scanIdentifier(ch, 99 /* ESNext */); + if (identifierKind) { + return token = identifierKind; + } + pos += charSize(ch); + return token; // Still `SyntaKind.Unknown` + } + function scanIdentifier(startCharacter, languageVersion) { + var ch = startCharacter; + if (isIdentifierStart(ch, languageVersion)) { + pos += charSize(ch); + while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion)) + pos += charSize(ch); + tokenValue = text.substring(tokenPos, pos); + if (ch === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return getIdentifierToken(); + } + } function reScanGreaterToken() { if (token === 31 /* GreaterThanToken */) { if (text.charCodeAt(pos) === 62 /* greaterThan */) { @@ -11052,9 +11239,10 @@ var ts; pos = tokenPos; return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true); } - function reScanJsxToken() { + function reScanJsxToken(allowMultilineJsxText) { + if (allowMultilineJsxText === void 0) { allowMultilineJsxText = true; } pos = tokenPos = startPos; - return token = scanJsxToken(); + return token = scanJsxToken(allowMultilineJsxText); } function reScanLessThanToken() { if (token === 47 /* LessThanLessThanToken */) { @@ -11068,7 +11256,8 @@ var ts; pos = tokenPos + 1; return token = 57 /* QuestionToken */; } - function scanJsxToken() { + function scanJsxToken(allowMultilineJsxText) { + if (allowMultilineJsxText === void 0) { allowMultilineJsxText = true; } startPos = tokenPos = pos; if (pos >= end) { return token = 1 /* EndOfFileToken */; @@ -11088,15 +11277,9 @@ var ts; } // First non-whitespace character on this line. var firstNonWhitespace = 0; - var lastNonWhitespace = -1; // These initial values are special because the first line is: // firstNonWhitespace = 0 to indicate that we want leading whitespace, while (pos < end) { - // We want to keep track of the last non-whitespace (but including - // newlines character for hitting the end of the JSX Text region) - if (!isWhiteSpaceSingleLine(char)) { - lastNonWhitespace = pos; - } char = text.charCodeAt(pos); if (char === 123 /* openBrace */) { break; @@ -11114,8 +11297,6 @@ var ts; if (char === 125 /* closeBrace */) { error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1); } - if (lastNonWhitespace > 0) - lastNonWhitespace++; // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces. // i.e (- : whitespace) //
---- @@ -11125,13 +11306,17 @@ var ts; if (isLineBreak(char) && firstNonWhitespace === 0) { firstNonWhitespace = -1; } + else if (!allowMultilineJsxText && isLineBreak(char) && firstNonWhitespace > 0) { + // Stop JsxText on each line during formatting. This allows the formatter to + // indent each line correctly. + break; + } else if (!isWhiteSpaceLike(char)) { firstNonWhitespace = pos; } pos++; } - var endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace; - tokenValue = text.substring(startPos, endPosition); + tokenValue = text.substring(startPos, pos); return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */; } // Scans a JSX identifier; these differ from normal identifiers in that @@ -11154,6 +11339,7 @@ var ts; tokenValue += ":"; pos++; namespaceSeparator = true; + token = 78 /* Identifier */; // swap from keyword kind to identifier kind continue; } var oldPos = pos; @@ -11410,6 +11596,8 @@ var ts; switch (options.target) { case 99 /* ESNext */: return "lib.esnext.full.d.ts"; + case 8 /* ES2021 */: + return "lib.es2021.full.d.ts"; case 7 /* ES2020 */: return "lib.es2020.full.d.ts"; case 6 /* ES2019 */: @@ -11628,9 +11816,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 159 /* TypeParameter */) { + if (d && d.kind === 160 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (isFunctionLike(current) || isClassLike(current) || current.kind === 253 /* InterfaceDeclaration */) { + if (isFunctionLike(current) || isClassLike(current) || current.kind === 254 /* InterfaceDeclaration */) { return current; } } @@ -11638,7 +11826,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node, parent) { - return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 166 /* Constructor */; + return ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */) && parent.kind === 167 /* Constructor */; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -11668,14 +11856,14 @@ var ts; node = walkUpBindingElementsAndPatterns(node); } var flags = getFlags(node); - if (node.kind === 249 /* VariableDeclaration */) { + if (node.kind === 250 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 250 /* VariableDeclarationList */) { + if (node && node.kind === 251 /* VariableDeclarationList */) { flags |= getFlags(node); node = node.parent; } - if (node && node.kind === 232 /* VariableStatement */) { + if (node && node.kind === 233 /* VariableStatement */) { flags |= getFlags(node); } return flags; @@ -11693,19 +11881,22 @@ var ts; // nodes like variable declarations and binding elements can returned a view of their flags // that includes the modifiers from their container. i.e. flags like export/declare aren't // stored on the variable declaration directly, but on the containing variable statement - // (if it has one). Similarly, flags for let/const are store on the variable declaration + // (if it has one). Similarly, flags for let/const are stored on the variable declaration // list. By calling this function, all those flags are combined so that the client can treat // the node as if it actually had those flags. function getCombinedNodeFlags(node) { return getCombinedFlags(node, function (n) { return n.flags; }); } ts.getCombinedNodeFlags = getCombinedNodeFlags; + /* @internal */ + ts.supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; /** * Checks to see if the locale is in the appropriate format, * and if it is, attempts to set the appropriate language. */ function validateLocaleAndSetLanguage(locale, sys, errors) { - var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + var lowerCaseLocale = locale.toLowerCase(); + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale); if (!matchResult) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); @@ -11716,7 +11907,7 @@ var ts; var territory = matchResult[3]; // First try the entire locale, then fall back to just language if that's all we have. // Either ways do not fail, and fallback to the English diagnostic strings. - if (!trySetLanguageAndTerritory(language, territory, errors)) { + if (ts.contains(ts.supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) { trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); } // Set the UI locale for string collation @@ -11823,7 +12014,7 @@ var ts; } ts.idText = idText; function symbolName(symbol) { - if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) { + if (symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) { return idText(symbol.valueDeclaration.name); } return unescapeLeadingUnderscores(symbol.escapedName); @@ -11845,30 +12036,30 @@ var ts; } // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } break; - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: var expr = hostNode.expression; - if (expr.kind === 216 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) { + if (expr.kind === 217 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) { expr = expr.left; } switch (expr.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return expr.name; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; } } break; - case 207 /* ParenthesizedExpression */: { + case 208 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } - case 245 /* LabeledStatement */: { + case 246 /* LabeledStatement */: { if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } @@ -11905,16 +12096,16 @@ var ts; switch (declaration.kind) { case 78 /* Identifier */: return declaration; - case 333 /* JSDocPropertyTag */: - case 326 /* JSDocParameterTag */: { + case 337 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: { var name = declaration.name; - if (name.kind === 157 /* QualifiedName */) { + if (name.kind === 158 /* QualifiedName */) { return name.right; } break; } - case 203 /* CallExpression */: - case 216 /* BinaryExpression */: { + case 204 /* CallExpression */: + case 217 /* BinaryExpression */: { var expr_1 = declaration; switch (ts.getAssignmentDeclarationKind(expr_1)) { case 1 /* ExportsProperty */: @@ -11930,15 +12121,15 @@ var ts; return undefined; } } - case 331 /* JSDocTypedefTag */: + case 335 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); - case 325 /* JSDocEnumTag */: + case 329 /* JSDocEnumTag */: return nameForNamelessJSDocTypedef(declaration); - case 266 /* ExportAssignment */: { + case 267 /* ExportAssignment */: { var expression = declaration.expression; return ts.isIdentifier(expression) ? expression : undefined; } - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: var expr = declaration; if (ts.isBindableStaticElementAccessExpression(expr)) { return expr.argumentExpression; @@ -11951,7 +12142,7 @@ var ts; if (declaration === undefined) return undefined; return getNonAssignedNameOfDeclaration(declaration) || - (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + (ts.isFunctionExpression(declaration) || ts.isArrowFunction(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); } ts.getNameOfDeclaration = getNameOfDeclaration; /*@internal*/ @@ -12104,6 +12295,10 @@ var ts; return getFirstJSDocTag(node, ts.isJSDocReadonlyTag, /*noCache*/ true); } ts.getJSDocReadonlyTagNoCache = getJSDocReadonlyTagNoCache; + function getJSDocOverrideTagNoCache(node) { + return getFirstJSDocTag(node, ts.isJSDocOverrideTag, /*noCache*/ true); + } + ts.getJSDocOverrideTagNoCache = getJSDocOverrideTagNoCache; /** Gets the JSDoc deprecated tag for the node if present */ function getJSDocDeprecatedTag(node) { return getFirstJSDocTag(node, ts.isJSDocDeprecatedTag); @@ -12224,6 +12419,14 @@ var ts; return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + /** Gets the text of a jsdoc comment, flattening links to their text. */ + function getTextOfJSDocComment(comment) { + return typeof comment === "string" ? comment + : comment === null || comment === void 0 ? void 0 : comment.map(function (c) { + return c.kind === 313 /* JSDocText */ ? c.text : "{@link " + (c.name ? ts.entityNameToString(c.name) + " " : "") + c.text + "}"; + }).join(""); + } + ts.getTextOfJSDocComment = getTextOfJSDocComment; /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. @@ -12233,7 +12436,7 @@ var ts; return ts.emptyArray; } if (ts.isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 311 /* JSDocComment */); + ts.Debug.assert(node.parent.kind === 312 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } if (node.typeParameters) { @@ -12259,13 +12462,13 @@ var ts; } ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter; // #region - function isIdentifierOrPrivateIdentifier(node) { + function isMemberName(node) { return node.kind === 78 /* Identifier */ || node.kind === 79 /* PrivateIdentifier */; } - ts.isIdentifierOrPrivateIdentifier = isIdentifierOrPrivateIdentifier; + ts.isMemberName = isMemberName; /* @internal */ function isGetOrSetAccessorDeclaration(node) { - return node.kind === 168 /* SetAccessor */ || node.kind === 167 /* GetAccessor */; + return node.kind === 169 /* SetAccessor */ || node.kind === 168 /* GetAccessor */; } ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; function isPropertyAccessChain(node) { @@ -12283,10 +12486,10 @@ var ts; function isOptionalChain(node) { var kind = node.kind; return !!(node.flags & 32 /* OptionalChain */) && - (kind === 201 /* PropertyAccessExpression */ - || kind === 202 /* ElementAccessExpression */ - || kind === 203 /* CallExpression */ - || kind === 225 /* NonNullExpression */); + (kind === 202 /* PropertyAccessExpression */ + || kind === 203 /* ElementAccessExpression */ + || kind === 204 /* CallExpression */ + || kind === 226 /* NonNullExpression */); } ts.isOptionalChain = isOptionalChain; /* @internal */ @@ -12321,7 +12524,7 @@ var ts; } ts.isOutermostOptionalChain = isOutermostOptionalChain; function isNullishCoalesce(node) { - return node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */; + return node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */; } ts.isNullishCoalesce = isNullishCoalesce; function isConstTypeReference(node) { @@ -12338,17 +12541,17 @@ var ts; } ts.isNonNullChain = isNonNullChain; function isBreakOrContinueStatement(node) { - return node.kind === 241 /* BreakStatement */ || node.kind === 240 /* ContinueStatement */; + return node.kind === 242 /* BreakStatement */ || node.kind === 241 /* ContinueStatement */; } ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isNamedExportBindings(node) { - return node.kind === 269 /* NamespaceExport */ || node.kind === 268 /* NamedExports */; + return node.kind === 270 /* NamespaceExport */ || node.kind === 269 /* NamedExports */; } ts.isNamedExportBindings = isNamedExportBindings; function isUnparsedTextLike(node) { switch (node.kind) { - case 294 /* UnparsedText */: - case 295 /* UnparsedInternalText */: + case 295 /* UnparsedText */: + case 296 /* UnparsedInternalText */: return true; default: return false; @@ -12357,12 +12560,12 @@ var ts; ts.isUnparsedTextLike = isUnparsedTextLike; function isUnparsedNode(node) { return isUnparsedTextLike(node) || - node.kind === 292 /* UnparsedPrologue */ || - node.kind === 296 /* UnparsedSyntheticReference */; + node.kind === 293 /* UnparsedPrologue */ || + node.kind === 297 /* UnparsedSyntheticReference */; } ts.isUnparsedNode = isUnparsedNode; function isJSDocPropertyLikeTag(node) { - return node.kind === 333 /* JSDocPropertyTag */ || node.kind === 326 /* JSDocParameterTag */; + return node.kind === 337 /* JSDocPropertyTag */ || node.kind === 330 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; // #endregion @@ -12378,16 +12581,25 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 157 /* FirstNode */; + return kind >= 158 /* FirstNode */; } ts.isNodeKind = isNodeKind; + /** + * True if kind is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + function isTokenKind(kind) { + return kind >= 0 /* FirstToken */ && kind <= 157 /* LastToken */; + } + ts.isTokenKind = isTokenKind; /** * True if node is of some token syntax kind. * For example, this is true for an IfKeyword but not for an IfStatement. * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. */ function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 156 /* LastToken */; + return isTokenKind(n.kind); } ts.isToken = isToken; // Node Arrays @@ -12428,13 +12640,13 @@ var ts; ts.isImportOrExportSpecifier = isImportOrExportSpecifier; function isTypeOnlyImportOrExportDeclaration(node) { switch (node.kind) { - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return node.parent.parent.isTypeOnly; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return node.parent.isTypeOnly; - case 262 /* ImportClause */: - case 260 /* ImportEqualsDeclaration */: + case 263 /* ImportClause */: + case 261 /* ImportEqualsDeclaration */: return node.isTypeOnly; default: return false; @@ -12453,10 +12665,10 @@ var ts; ts.isGeneratedIdentifier = isGeneratedIdentifier; // Private Identifiers /*@internal*/ - function isPrivateIdentifierPropertyDeclaration(node) { - return ts.isPropertyDeclaration(node) && ts.isPrivateIdentifier(node.name); + function isPrivateIdentifierClassElementDeclaration(node) { + return (ts.isPropertyDeclaration(node) || isMethodOrAccessor(node)) && ts.isPrivateIdentifier(node.name); } - ts.isPrivateIdentifierPropertyDeclaration = isPrivateIdentifierPropertyDeclaration; + ts.isPrivateIdentifierClassElementDeclaration = isPrivateIdentifierClassElementDeclaration; /*@internal*/ function isPrivateIdentifierPropertyAccessExpression(node) { return ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name); @@ -12477,6 +12689,7 @@ var ts; case 121 /* ProtectedKeyword */: case 142 /* ReadonlyKeyword */: case 123 /* StaticKeyword */: + case 156 /* OverrideKeyword */: return true; } return false; @@ -12484,12 +12697,12 @@ var ts; ts.isModifierKind = isModifierKind; /* @internal */ function isParameterPropertyModifier(kind) { - return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + return !!(ts.modifierToFlag(kind) & 16476 /* ParameterPropertyModifier */); } ts.isParameterPropertyModifier = isParameterPropertyModifier; /* @internal */ function isClassMemberModifier(idToken) { - return isParameterPropertyModifier(idToken) || idToken === 123 /* StaticKeyword */; + return isParameterPropertyModifier(idToken) || idToken === 123 /* StaticKeyword */ || idToken === 156 /* OverrideKeyword */; } ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { @@ -12498,7 +12711,7 @@ var ts; ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 157 /* QualifiedName */ + return kind === 158 /* QualifiedName */ || kind === 78 /* Identifier */; } ts.isEntityName = isEntityName; @@ -12508,19 +12721,19 @@ var ts; || kind === 79 /* PrivateIdentifier */ || kind === 10 /* StringLiteral */ || kind === 8 /* NumericLiteral */ - || kind === 158 /* ComputedPropertyName */; + || kind === 159 /* ComputedPropertyName */; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; return kind === 78 /* Identifier */ - || kind === 196 /* ObjectBindingPattern */ - || kind === 197 /* ArrayBindingPattern */; + || kind === 197 /* ObjectBindingPattern */ + || kind === 198 /* ArrayBindingPattern */; } ts.isBindingName = isBindingName; // Functions function isFunctionLike(node) { - return node && isFunctionLikeKind(node.kind); + return !!node && isFunctionLikeKind(node.kind); } ts.isFunctionLike = isFunctionLike; /* @internal */ @@ -12530,13 +12743,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; default: return false; @@ -12545,14 +12758,14 @@ var ts; /* @internal */ function isFunctionLikeKind(kind) { switch (kind) { - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 313 /* JSDocSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 174 /* FunctionType */: - case 308 /* JSDocFunctionType */: - case 175 /* ConstructorType */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 315 /* JSDocSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 175 /* FunctionType */: + case 309 /* JSDocFunctionType */: + case 176 /* ConstructorType */: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -12567,29 +12780,29 @@ var ts; // Classes function isClassElement(node) { var kind = node.kind; - return kind === 166 /* Constructor */ - || kind === 163 /* PropertyDeclaration */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 171 /* IndexSignature */ - || kind === 229 /* SemicolonClassElement */; + return kind === 167 /* Constructor */ + || kind === 164 /* PropertyDeclaration */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 172 /* IndexSignature */ + || kind === 230 /* SemicolonClassElement */; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */); + return node && (node.kind === 253 /* ClassDeclaration */ || node.kind === 222 /* ClassExpression */); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 167 /* GetAccessor */ || node.kind === 168 /* SetAccessor */); + return node && (node.kind === 168 /* GetAccessor */ || node.kind === 169 /* SetAccessor */); } ts.isAccessor = isAccessor; /* @internal */ function isMethodOrAccessor(node) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return true; default: return false; @@ -12599,11 +12812,11 @@ var ts; // Type members function isTypeElement(node) { var kind = node.kind; - return kind === 170 /* ConstructSignature */ - || kind === 169 /* CallSignature */ - || kind === 162 /* PropertySignature */ - || kind === 164 /* MethodSignature */ - || kind === 171 /* IndexSignature */; + return kind === 171 /* ConstructSignature */ + || kind === 170 /* CallSignature */ + || kind === 163 /* PropertySignature */ + || kind === 165 /* MethodSignature */ + || kind === 172 /* IndexSignature */; } ts.isTypeElement = isTypeElement; function isClassOrTypeElement(node) { @@ -12612,12 +12825,12 @@ var ts; ts.isClassOrTypeElement = isClassOrTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 288 /* PropertyAssignment */ - || kind === 289 /* ShorthandPropertyAssignment */ - || kind === 290 /* SpreadAssignment */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 289 /* PropertyAssignment */ + || kind === 290 /* ShorthandPropertyAssignment */ + || kind === 291 /* SpreadAssignment */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; // Type @@ -12632,8 +12845,8 @@ var ts; ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return true; } return false; @@ -12644,8 +12857,8 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 197 /* ArrayBindingPattern */ - || kind === 196 /* ObjectBindingPattern */; + return kind === 198 /* ArrayBindingPattern */ + || kind === 197 /* ObjectBindingPattern */; } return false; } @@ -12653,15 +12866,15 @@ var ts; /* @internal */ function isAssignmentPattern(node) { var kind = node.kind; - return kind === 199 /* ArrayLiteralExpression */ - || kind === 200 /* ObjectLiteralExpression */; + return kind === 200 /* ArrayLiteralExpression */ + || kind === 201 /* ObjectLiteralExpression */; } ts.isAssignmentPattern = isAssignmentPattern; /* @internal */ function isArrayBindingElement(node) { var kind = node.kind; - return kind === 198 /* BindingElement */ - || kind === 222 /* OmittedExpression */; + return kind === 199 /* BindingElement */ + || kind === 223 /* OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; /** @@ -12670,9 +12883,9 @@ var ts; /* @internal */ function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: return true; } return false; @@ -12693,8 +12906,8 @@ var ts; /* @internal */ function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 196 /* ObjectBindingPattern */: - case 200 /* ObjectLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 201 /* ObjectLiteralExpression */: return true; } return false; @@ -12706,8 +12919,8 @@ var ts; /* @internal */ function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 197 /* ArrayBindingPattern */: - case 199 /* ArrayLiteralExpression */: + case 198 /* ArrayBindingPattern */: + case 200 /* ArrayLiteralExpression */: return true; } return false; @@ -12716,26 +12929,26 @@ var ts; /* @internal */ function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { var kind = node.kind; - return kind === 201 /* PropertyAccessExpression */ - || kind === 157 /* QualifiedName */ - || kind === 195 /* ImportType */; + return kind === 202 /* PropertyAccessExpression */ + || kind === 158 /* QualifiedName */ + || kind === 196 /* ImportType */; } ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; // Expression function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 201 /* PropertyAccessExpression */ - || kind === 157 /* QualifiedName */; + return kind === 202 /* PropertyAccessExpression */ + || kind === 158 /* QualifiedName */; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 205 /* TaggedTemplateExpression */: - case 161 /* Decorator */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 206 /* TaggedTemplateExpression */: + case 162 /* Decorator */: return true; default: return false; @@ -12743,12 +12956,12 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 203 /* CallExpression */ || node.kind === 204 /* NewExpression */; + return node.kind === 204 /* CallExpression */ || node.kind === 205 /* NewExpression */; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 218 /* TemplateExpression */ + return kind === 219 /* TemplateExpression */ || kind === 14 /* NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; @@ -12759,33 +12972,33 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: - case 204 /* NewExpression */: - case 203 /* CallExpression */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: - case 205 /* TaggedTemplateExpression */: - case 199 /* ArrayLiteralExpression */: - case 207 /* ParenthesizedExpression */: - case 200 /* ObjectLiteralExpression */: - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 205 /* NewExpression */: + case 204 /* CallExpression */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: + case 206 /* TaggedTemplateExpression */: + case 200 /* ArrayLiteralExpression */: + case 208 /* ParenthesizedExpression */: + case 201 /* ObjectLiteralExpression */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: case 78 /* Identifier */: case 13 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: case 9 /* BigIntLiteral */: case 10 /* StringLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: case 94 /* FalseKeyword */: case 103 /* NullKeyword */: case 107 /* ThisKeyword */: case 109 /* TrueKeyword */: case 105 /* SuperKeyword */: - case 225 /* NonNullExpression */: - case 226 /* MetaProperty */: + case 226 /* NonNullExpression */: + case 227 /* MetaProperty */: case 99 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression return true; default: @@ -12799,13 +13012,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: - case 210 /* DeleteExpression */: - case 211 /* TypeOfExpression */: - case 212 /* VoidExpression */: - case 213 /* AwaitExpression */: - case 206 /* TypeAssertionExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 211 /* DeleteExpression */: + case 212 /* TypeOfExpression */: + case 213 /* VoidExpression */: + case 214 /* AwaitExpression */: + case 207 /* TypeAssertionExpression */: return true; default: return isLeftHandSideExpressionKind(kind); @@ -12814,9 +13027,9 @@ var ts; /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return true; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */; default: @@ -12835,15 +13048,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 217 /* ConditionalExpression */: - case 219 /* YieldExpression */: - case 209 /* ArrowFunction */: - case 216 /* BinaryExpression */: - case 220 /* SpreadElement */: - case 224 /* AsExpression */: - case 222 /* OmittedExpression */: - case 337 /* CommaListExpression */: - case 336 /* PartiallyEmittedExpression */: + case 218 /* ConditionalExpression */: + case 220 /* YieldExpression */: + case 210 /* ArrowFunction */: + case 217 /* BinaryExpression */: + case 221 /* SpreadElement */: + case 225 /* AsExpression */: + case 223 /* OmittedExpression */: + case 341 /* CommaListExpression */: + case 340 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -12851,8 +13064,8 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 206 /* TypeAssertionExpression */ - || kind === 224 /* AsExpression */; + return kind === 207 /* TypeAssertionExpression */ + || kind === 225 /* AsExpression */; } ts.isAssertionExpression = isAssertionExpression; /* @internal */ @@ -12863,13 +13076,13 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return true; - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -12898,7 +13111,7 @@ var ts; ts.isExternalModuleIndicator = isExternalModuleIndicator; /* @internal */ function isForInOrOfStatement(node) { - return node.kind === 238 /* ForInStatement */ || node.kind === 239 /* ForOfStatement */; + return node.kind === 239 /* ForInStatement */ || node.kind === 240 /* ForOfStatement */; } ts.isForInOrOfStatement = isForInOrOfStatement; // Element @@ -12922,114 +13135,114 @@ var ts; /* @internal */ function isModuleBody(node) { var kind = node.kind; - return kind === 257 /* ModuleBlock */ - || kind === 256 /* ModuleDeclaration */ + return kind === 258 /* ModuleBlock */ + || kind === 257 /* ModuleDeclaration */ || kind === 78 /* Identifier */; } ts.isModuleBody = isModuleBody; /* @internal */ function isNamespaceBody(node) { var kind = node.kind; - return kind === 257 /* ModuleBlock */ - || kind === 256 /* ModuleDeclaration */; + return kind === 258 /* ModuleBlock */ + || kind === 257 /* ModuleDeclaration */; } ts.isNamespaceBody = isNamespaceBody; /* @internal */ function isJSDocNamespaceBody(node) { var kind = node.kind; return kind === 78 /* Identifier */ - || kind === 256 /* ModuleDeclaration */; + || kind === 257 /* ModuleDeclaration */; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; /* @internal */ function isNamedImportBindings(node) { var kind = node.kind; - return kind === 264 /* NamedImports */ - || kind === 263 /* NamespaceImport */; + return kind === 265 /* NamedImports */ + || kind === 264 /* NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; /* @internal */ function isModuleOrEnumDeclaration(node) { - return node.kind === 256 /* ModuleDeclaration */ || node.kind === 255 /* EnumDeclaration */; + return node.kind === 257 /* ModuleDeclaration */ || node.kind === 256 /* EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 209 /* ArrowFunction */ - || kind === 198 /* BindingElement */ - || kind === 252 /* ClassDeclaration */ - || kind === 221 /* ClassExpression */ - || kind === 166 /* Constructor */ - || kind === 255 /* EnumDeclaration */ - || kind === 291 /* EnumMember */ - || kind === 270 /* ExportSpecifier */ - || kind === 251 /* FunctionDeclaration */ - || kind === 208 /* FunctionExpression */ - || kind === 167 /* GetAccessor */ - || kind === 262 /* ImportClause */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 265 /* ImportSpecifier */ - || kind === 253 /* InterfaceDeclaration */ - || kind === 280 /* JsxAttribute */ - || kind === 165 /* MethodDeclaration */ - || kind === 164 /* MethodSignature */ - || kind === 256 /* ModuleDeclaration */ - || kind === 259 /* NamespaceExportDeclaration */ - || kind === 263 /* NamespaceImport */ - || kind === 269 /* NamespaceExport */ - || kind === 160 /* Parameter */ - || kind === 288 /* PropertyAssignment */ - || kind === 163 /* PropertyDeclaration */ - || kind === 162 /* PropertySignature */ - || kind === 168 /* SetAccessor */ - || kind === 289 /* ShorthandPropertyAssignment */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 159 /* TypeParameter */ - || kind === 249 /* VariableDeclaration */ - || kind === 331 /* JSDocTypedefTag */ - || kind === 324 /* JSDocCallbackTag */ - || kind === 333 /* JSDocPropertyTag */; + return kind === 210 /* ArrowFunction */ + || kind === 199 /* BindingElement */ + || kind === 253 /* ClassDeclaration */ + || kind === 222 /* ClassExpression */ + || kind === 167 /* Constructor */ + || kind === 256 /* EnumDeclaration */ + || kind === 292 /* EnumMember */ + || kind === 271 /* ExportSpecifier */ + || kind === 252 /* FunctionDeclaration */ + || kind === 209 /* FunctionExpression */ + || kind === 168 /* GetAccessor */ + || kind === 263 /* ImportClause */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 266 /* ImportSpecifier */ + || kind === 254 /* InterfaceDeclaration */ + || kind === 281 /* JsxAttribute */ + || kind === 166 /* MethodDeclaration */ + || kind === 165 /* MethodSignature */ + || kind === 257 /* ModuleDeclaration */ + || kind === 260 /* NamespaceExportDeclaration */ + || kind === 264 /* NamespaceImport */ + || kind === 270 /* NamespaceExport */ + || kind === 161 /* Parameter */ + || kind === 289 /* PropertyAssignment */ + || kind === 164 /* PropertyDeclaration */ + || kind === 163 /* PropertySignature */ + || kind === 169 /* SetAccessor */ + || kind === 290 /* ShorthandPropertyAssignment */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 160 /* TypeParameter */ + || kind === 250 /* VariableDeclaration */ + || kind === 335 /* JSDocTypedefTag */ + || kind === 328 /* JSDocCallbackTag */ + || kind === 337 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { - return kind === 251 /* FunctionDeclaration */ - || kind === 271 /* MissingDeclaration */ - || kind === 252 /* ClassDeclaration */ - || kind === 253 /* InterfaceDeclaration */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 255 /* EnumDeclaration */ - || kind === 256 /* ModuleDeclaration */ - || kind === 261 /* ImportDeclaration */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 267 /* ExportDeclaration */ - || kind === 266 /* ExportAssignment */ - || kind === 259 /* NamespaceExportDeclaration */; + return kind === 252 /* FunctionDeclaration */ + || kind === 272 /* MissingDeclaration */ + || kind === 253 /* ClassDeclaration */ + || kind === 254 /* InterfaceDeclaration */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 256 /* EnumDeclaration */ + || kind === 257 /* ModuleDeclaration */ + || kind === 262 /* ImportDeclaration */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 268 /* ExportDeclaration */ + || kind === 267 /* ExportAssignment */ + || kind === 260 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 241 /* BreakStatement */ - || kind === 240 /* ContinueStatement */ - || kind === 248 /* DebuggerStatement */ - || kind === 235 /* DoStatement */ - || kind === 233 /* ExpressionStatement */ - || kind === 231 /* EmptyStatement */ - || kind === 238 /* ForInStatement */ - || kind === 239 /* ForOfStatement */ - || kind === 237 /* ForStatement */ - || kind === 234 /* IfStatement */ - || kind === 245 /* LabeledStatement */ - || kind === 242 /* ReturnStatement */ - || kind === 244 /* SwitchStatement */ - || kind === 246 /* ThrowStatement */ - || kind === 247 /* TryStatement */ - || kind === 232 /* VariableStatement */ - || kind === 236 /* WhileStatement */ - || kind === 243 /* WithStatement */ - || kind === 335 /* NotEmittedStatement */ - || kind === 339 /* EndOfDeclarationMarker */ - || kind === 338 /* MergeDeclarationMarker */; + return kind === 242 /* BreakStatement */ + || kind === 241 /* ContinueStatement */ + || kind === 249 /* DebuggerStatement */ + || kind === 236 /* DoStatement */ + || kind === 234 /* ExpressionStatement */ + || kind === 232 /* EmptyStatement */ + || kind === 239 /* ForInStatement */ + || kind === 240 /* ForOfStatement */ + || kind === 238 /* ForStatement */ + || kind === 235 /* IfStatement */ + || kind === 246 /* LabeledStatement */ + || kind === 243 /* ReturnStatement */ + || kind === 245 /* SwitchStatement */ + || kind === 247 /* ThrowStatement */ + || kind === 248 /* TryStatement */ + || kind === 233 /* VariableStatement */ + || kind === 237 /* WhileStatement */ + || kind === 244 /* WithStatement */ + || kind === 339 /* NotEmittedStatement */ + || kind === 343 /* EndOfDeclarationMarker */ + || kind === 342 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { - if (node.kind === 159 /* TypeParameter */) { - return (node.parent && node.parent.kind !== 330 /* JSDocTemplateTag */) || ts.isInJSFile(node); + if (node.kind === 160 /* TypeParameter */) { + return (node.parent && node.parent.kind !== 334 /* JSDocTemplateTag */) || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -13056,10 +13269,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 230 /* Block */) + if (node.kind !== 231 /* Block */) return false; if (node.parent !== undefined) { - if (node.parent.kind === 247 /* TryStatement */ || node.parent.kind === 287 /* CatchClause */) { + if (node.parent.kind === 248 /* TryStatement */ || node.parent.kind === 288 /* CatchClause */) { return false; } } @@ -13073,15 +13286,15 @@ var ts; var kind = node.kind; return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) - || kind === 230 /* Block */; + || kind === 231 /* Block */; } ts.isStatementOrBlock = isStatementOrBlock; // Module references /* @internal */ function isModuleReference(node) { var kind = node.kind; - return kind === 272 /* ExternalModuleReference */ - || kind === 157 /* QualifiedName */ + return kind === 273 /* ExternalModuleReference */ + || kind === 158 /* QualifiedName */ || kind === 78 /* Identifier */; } ts.isModuleReference = isModuleReference; @@ -13091,70 +13304,76 @@ var ts; var kind = node.kind; return kind === 107 /* ThisKeyword */ || kind === 78 /* Identifier */ - || kind === 201 /* PropertyAccessExpression */; + || kind === 202 /* PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; /* @internal */ function isJsxChild(node) { var kind = node.kind; - return kind === 273 /* JsxElement */ - || kind === 283 /* JsxExpression */ - || kind === 274 /* JsxSelfClosingElement */ + return kind === 274 /* JsxElement */ + || kind === 284 /* JsxExpression */ + || kind === 275 /* JsxSelfClosingElement */ || kind === 11 /* JsxText */ - || kind === 277 /* JsxFragment */; + || kind === 278 /* JsxFragment */; } ts.isJsxChild = isJsxChild; /* @internal */ function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 280 /* JsxAttribute */ - || kind === 282 /* JsxSpreadAttribute */; + return kind === 281 /* JsxAttribute */ + || kind === 283 /* JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; /* @internal */ function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 10 /* StringLiteral */ - || kind === 283 /* JsxExpression */; + || kind === 284 /* JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 275 /* JsxOpeningElement */ - || kind === 274 /* JsxSelfClosingElement */; + return kind === 276 /* JsxOpeningElement */ + || kind === 275 /* JsxSelfClosingElement */; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 284 /* CaseClause */ - || kind === 285 /* DefaultClause */; + return kind === 285 /* CaseClause */ + || kind === 286 /* DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; // JSDoc /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 301 /* FirstJSDocNode */ && node.kind <= 333 /* LastJSDocNode */; + return node.kind >= 302 /* FirstJSDocNode */ && node.kind <= 337 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 311 /* JSDocComment */ || node.kind === 310 /* JSDocNamepathType */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + return node.kind === 312 /* JSDocComment */ + || node.kind === 311 /* JSDocNamepathType */ + || node.kind === 313 /* JSDocText */ + || node.kind === 316 /* JSDocLink */ + || isJSDocTag(node) + || ts.isJSDocTypeLiteral(node) + || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 314 /* FirstJSDocTagNode */ && node.kind <= 333 /* LastJSDocTagNode */; + return node.kind >= 317 /* FirstJSDocTagNode */ && node.kind <= 337 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { - return node.kind === 168 /* SetAccessor */; + return node.kind === 169 /* SetAccessor */; } ts.isSetAccessor = isSetAccessor; function isGetAccessor(node) { - return node.kind === 167 /* GetAccessor */; + return node.kind === 168 /* GetAccessor */; } ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ @@ -13180,13 +13399,13 @@ var ts; /** True if has initializer node attached to it. */ function hasOnlyExpressionInitializer(node) { switch (node.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: - case 162 /* PropertySignature */: - case 163 /* PropertyDeclaration */: - case 288 /* PropertyAssignment */: - case 291 /* EnumMember */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: + case 163 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 289 /* PropertyAssignment */: + case 292 /* EnumMember */: return true; default: return false; @@ -13194,12 +13413,12 @@ var ts; } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { - return node.kind === 280 /* JsxAttribute */ || node.kind === 282 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); + return node.kind === 281 /* JsxAttribute */ || node.kind === 283 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node); } ts.isObjectLiteralElement = isObjectLiteralElement; /* @internal */ function isTypeReferenceType(node) { - return node.kind === 173 /* TypeReference */ || node.kind === 223 /* ExpressionWithTypeArguments */; + return node.kind === 174 /* TypeReference */ || node.kind === 224 /* ExpressionWithTypeArguments */; } ts.isTypeReferenceType = isTypeReferenceType; var MAX_SMI_X86 = 1073741823; @@ -13438,7 +13657,9 @@ var ts; } ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + return oldResolution.resolvedFileName === newResolution.resolvedFileName + && oldResolution.primary === newResolution.primary + && oldResolution.originalPath === newResolution.originalPath; } ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { @@ -13480,7 +13701,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 297 /* SourceFile */) { + while (node && node.kind !== 298 /* SourceFile */) { node = node.parent; } return node; @@ -13488,11 +13709,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 230 /* Block */: - case 258 /* CaseBlock */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 231 /* Block */: + case 259 /* CaseBlock */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: return true; } return false; @@ -13688,10 +13909,12 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 334 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 338 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, + /*stopAfterLineBreak*/ false, + /*stopAtComments*/ false, isInJSDoc(node)); } ts.getTokenPosOfNode = getTokenPosOfNode; function getNonDecoratorTokenPosOfNode(node, sourceFile) { @@ -13810,9 +14033,11 @@ var ts; DataView: ["setBigInt64", "setBigUint64", "getBigInt64", "getBigUint64"], RelativeTimeFormat: ["format", "formatToParts", "resolvedOptions"] }, - esnext: { + es2021: { PromiseConstructor: ["any"], - String: ["replaceAll"], + String: ["replaceAll"] + }, + esnext: { NumberFormat: ["formatToParts"] } }; @@ -13905,7 +14130,7 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 249 /* VariableDeclaration */ && node.parent.kind === 287 /* CatchClause */; + return node.kind === 250 /* VariableDeclaration */ && node.parent.kind === 288 /* CatchClause */; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { @@ -13937,11 +14162,11 @@ var ts; ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. - return node && node.kind === 256 /* ModuleDeclaration */ && (!node.body); + return !!node && node.kind === 257 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 297 /* SourceFile */ || - node.kind === 256 /* ModuleDeclaration */ || + return node.kind === 298 /* SourceFile */ || + node.kind === 257 /* ModuleDeclaration */ || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -13958,16 +14183,17 @@ var ts; // - defined in the top level scope and source file is an external module // - defined inside ambient module declaration located in the top level scope and source file not an external module switch (node.parent.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: return ts.isExternalModule(node.parent); - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; } ts.isModuleAugmentationExternal = isModuleAugmentationExternal; function getNonAugmentationDeclaration(symbol) { - return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); + var _a; + return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); }); } ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration; function isEffectiveExternalModule(node, compilerOptions) { @@ -14013,22 +14239,22 @@ var ts; ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile; function isBlockScope(node, parentNode) { switch (node.kind) { - case 297 /* SourceFile */: - case 258 /* CaseBlock */: - case 287 /* CatchClause */: - case 256 /* ModuleDeclaration */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 298 /* SourceFile */: + case 259 /* CaseBlock */: + case 288 /* CatchClause */: + case 257 /* ModuleDeclaration */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; - case 230 /* Block */: + case 231 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block return !ts.isFunctionLike(parentNode); @@ -14038,9 +14264,9 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: - case 313 /* JSDocSignature */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: + case 315 /* JSDocSignature */: return true; default: ts.assertType(node); @@ -14050,25 +14276,25 @@ var ts; ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function isDeclarationWithTypeParameterChildren(node) { switch (node.kind) { - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 164 /* MethodSignature */: - case 171 /* IndexSignature */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 308 /* JSDocFunctionType */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 330 /* JSDocTemplateTag */: - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 165 /* MethodSignature */: + case 172 /* IndexSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 309 /* JSDocFunctionType */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 334 /* JSDocTemplateTag */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; default: ts.assertType(node); @@ -14078,8 +14304,8 @@ var ts; ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren; function isAnyImportSyntax(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: return true; default: return false; @@ -14088,15 +14314,15 @@ var ts; ts.isAnyImportSyntax = isAnyImportSyntax; function isLateVisibilityPaintedStatement(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 232 /* VariableStatement */: - case 252 /* ClassDeclaration */: - case 251 /* FunctionDeclaration */: - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 233 /* VariableStatement */: + case 253 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: return true; default: return false; @@ -14129,7 +14355,7 @@ var ts; } ts.getNameFromIndexInfo = getNameFromIndexInfo; function isComputedNonLiteralName(name) { - return name.kind === 158 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); + return name.kind === 159 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); } ts.isComputedNonLiteralName = isComputedNonLiteralName; function getTextOfPropertyName(name) { @@ -14141,7 +14367,7 @@ var ts; case 8 /* NumericLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: if (isStringOrNumericLiteralLike(name.expression)) return ts.escapeLeadingUnderscores(name.expression.text); return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames"); @@ -14157,9 +14383,9 @@ var ts; case 79 /* PrivateIdentifier */: case 78 /* Identifier */: return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) { return entityNameToString(name.expression) + "." + entityNameToString(name.name); } @@ -14245,7 +14471,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 230 /* Block */) { + if (node.body && node.body.kind === 231 /* Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -14259,7 +14485,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -14268,28 +14494,28 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 249 /* VariableDeclaration */: - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 254 /* TypeAliasDeclaration */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 250 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 255 /* TypeAliasDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: errorNode = node.name; break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: var start = ts.skipTrivia(sourceFile.text, node.pos); var end = node.statements.length > 0 ? node.statements[0].pos : node.end; return ts.createTextSpanFromBounds(start, end); @@ -14341,11 +14567,11 @@ var ts; } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 203 /* CallExpression */ && n.expression.kind === 105 /* SuperKeyword */; + return n.kind === 204 /* CallExpression */ && n.expression.kind === 105 /* SuperKeyword */; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 203 /* CallExpression */ && n.expression.kind === 99 /* ImportKeyword */; + return n.kind === 204 /* CallExpression */ && n.expression.kind === 99 /* ImportKeyword */; } ts.isImportCall = isImportCall; function isImportMeta(n) { @@ -14359,7 +14585,7 @@ var ts; } ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { - return node.kind === 233 /* ExpressionStatement */ + return node.kind === 234 /* ExpressionStatement */ && node.expression.kind === 10 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; @@ -14387,11 +14613,12 @@ var ts; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 160 /* Parameter */ || - node.kind === 159 /* TypeParameter */ || - node.kind === 208 /* FunctionExpression */ || - node.kind === 209 /* ArrowFunction */ || - node.kind === 207 /* ParenthesizedExpression */) ? + var commentRanges = (node.kind === 161 /* Parameter */ || + node.kind === 160 /* TypeParameter */ || + node.kind === 209 /* FunctionExpression */ || + node.kind === 210 /* ArrowFunction */ || + node.kind === 208 /* ParenthesizedExpression */ || + node.kind === 250 /* VariableDeclaration */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -14407,7 +14634,7 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (172 /* FirstTypeNode */ <= node.kind && node.kind <= 195 /* LastTypeNode */) { + if (173 /* FirstTypeNode */ <= node.kind && node.kind <= 196 /* LastTypeNode */) { return true; } switch (node.kind) { @@ -14423,32 +14650,32 @@ var ts; case 141 /* NeverKeyword */: return true; case 113 /* VoidKeyword */: - return node.parent.kind !== 212 /* VoidExpression */; - case 223 /* ExpressionWithTypeArguments */: + return node.parent.kind !== 213 /* VoidExpression */; + case 224 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 159 /* TypeParameter */: - return node.parent.kind === 190 /* MappedType */ || node.parent.kind === 185 /* InferType */; + case 160 /* TypeParameter */: + return node.parent.kind === 191 /* MappedType */ || node.parent.kind === 186 /* InferType */; // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container case 78 /* Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 157 /* QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 158 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 202 /* PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 78 /* Identifier */ || node.kind === 157 /* QualifiedName */ || node.kind === 201 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + ts.Debug.assert(node.kind === 78 /* Identifier */ || node.kind === 158 /* QualifiedName */ || node.kind === 202 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); // falls through - case 157 /* QualifiedName */: - case 201 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: case 107 /* ThisKeyword */: { var parent = node.parent; - if (parent.kind === 176 /* TypeQuery */) { + if (parent.kind === 177 /* TypeQuery */) { return false; } - if (parent.kind === 195 /* ImportType */) { + if (parent.kind === 196 /* ImportType */) { return !parent.isTypeOf; } // Do not recursively call isPartOfTypeNode on the parent. In the example: @@ -14457,40 +14684,40 @@ var ts; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. // Only C and A.B.C are type nodes. - if (172 /* FirstTypeNode */ <= parent.kind && parent.kind <= 195 /* LastTypeNode */) { + if (173 /* FirstTypeNode */ <= parent.kind && parent.kind <= 196 /* LastTypeNode */) { return true; } switch (parent.kind) { - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return node === parent.constraint; - case 330 /* JSDocTemplateTag */: + case 334 /* JSDocTemplateTag */: return node === parent.constraint; - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 160 /* Parameter */: - case 249 /* VariableDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 161 /* Parameter */: + case 250 /* VariableDeclaration */: return node === parent.type; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return node === parent.type; - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return node === parent.type; - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: return node === parent.type; - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: return ts.contains(parent.typeArguments, node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } @@ -14515,23 +14742,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitor(node); - case 258 /* CaseBlock */: - case 230 /* Block */: - case 234 /* IfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 243 /* WithStatement */: - case 244 /* SwitchStatement */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: - case 245 /* LabeledStatement */: - case 247 /* TryStatement */: - case 287 /* CatchClause */: + case 259 /* CaseBlock */: + case 231 /* Block */: + case 235 /* IfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 244 /* WithStatement */: + case 245 /* SwitchStatement */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 246 /* LabeledStatement */: + case 248 /* TryStatement */: + case 288 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -14541,23 +14768,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 255 /* EnumDeclaration */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: // These are not allowed inside a generator now, but eventually they may be allowed // as local types. Regardless, skip them to avoid the work. return; default: if (ts.isFunctionLike(node)) { - if (node.name && node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 159 /* ComputedPropertyName */) { // Note that we will not include methods/accessors of a class because they would require // first descending into the class. This is by design. traverse(node.name.expression); @@ -14580,10 +14807,10 @@ var ts; * @param node The type node. */ function getRestParameterElementType(node) { - if (node && node.kind === 178 /* ArrayType */) { + if (node && node.kind === 179 /* ArrayType */) { return node.elementType; } - else if (node && node.kind === 173 /* TypeReference */) { + else if (node && node.kind === 174 /* TypeReference */) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -14593,12 +14820,12 @@ var ts; ts.getRestParameterElementType = getRestParameterElementType; function getMembersOfDeclaration(node) { switch (node.kind) { - case 253 /* InterfaceDeclaration */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 177 /* TypeLiteral */: + case 254 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 178 /* TypeLiteral */: return node.members; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return node.properties; } } @@ -14606,14 +14833,14 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 198 /* BindingElement */: - case 291 /* EnumMember */: - case 160 /* Parameter */: - case 288 /* PropertyAssignment */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 289 /* ShorthandPropertyAssignment */: - case 249 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 292 /* EnumMember */: + case 161 /* Parameter */: + case 289 /* PropertyAssignment */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 290 /* ShorthandPropertyAssignment */: + case 250 /* VariableDeclaration */: return true; } } @@ -14625,8 +14852,8 @@ var ts; } ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { - return node.parent.kind === 250 /* VariableDeclarationList */ - && node.parent.parent.kind === 232 /* VariableStatement */; + return node.parent.kind === 251 /* VariableDeclarationList */ + && node.parent.parent.kind === 233 /* VariableStatement */; } ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; function isValidESSymbolDeclaration(node) { @@ -14637,13 +14864,13 @@ var ts; ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return true; } return false; @@ -14654,7 +14881,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 245 /* LabeledStatement */) { + if (node.statement.kind !== 246 /* LabeledStatement */) { return node.statement; } node = node.statement; @@ -14662,17 +14889,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 230 /* Block */ && ts.isFunctionLike(node.parent); + return node && node.kind === 231 /* Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 165 /* MethodDeclaration */ && node.parent.kind === 200 /* ObjectLiteralExpression */; + return node && node.kind === 166 /* MethodDeclaration */ && node.parent.kind === 201 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 165 /* MethodDeclaration */ && - (node.parent.kind === 200 /* ObjectLiteralExpression */ || - node.parent.kind === 221 /* ClassExpression */); + return node.kind === 166 /* MethodDeclaration */ && + (node.parent.kind === 201 /* ObjectLiteralExpression */ || + node.parent.kind === 222 /* ClassExpression */); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -14685,7 +14912,7 @@ var ts; ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { return objectLiteral.properties.filter(function (property) { - if (property.kind === 288 /* PropertyAssignment */) { + if (property.kind === 289 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); return key === propName || (!!key2 && key2 === propName); } @@ -14734,14 +14961,14 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { - ts.Debug.assert(node.kind !== 297 /* SourceFile */); + ts.Debug.assert(node.kind !== 298 /* SourceFile */); while (true) { node = node.parent; if (!node) { return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. } switch (node.kind) { - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: // If the grandparent node is an object literal (as opposed to a class), // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container @@ -14756,9 +14983,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 161 /* Decorator */: + case 162 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 160 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 161 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -14769,26 +14996,26 @@ var ts; node = node.parent; } break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // falls through - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 256 /* ModuleDeclaration */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 255 /* EnumDeclaration */: - case 297 /* SourceFile */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 257 /* ModuleDeclaration */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 256 /* EnumDeclaration */: + case 298 /* SourceFile */: return node; } } @@ -14807,9 +15034,9 @@ var ts; var container = getThisContainer(node, /*includeArrowFunctions*/ false); if (container) { switch (container.kind) { - case 166 /* Constructor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 167 /* Constructor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: return container; } } @@ -14831,27 +15058,27 @@ var ts; return node; } switch (node.kind) { - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: node = node.parent; break; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: if (!stopOnFunctions) { continue; } // falls through - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return node; - case 161 /* Decorator */: + case 162 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 160 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 161 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -14867,14 +15094,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 208 /* FunctionExpression */ || func.kind === 209 /* ArrowFunction */) { + if (func.kind === 209 /* FunctionExpression */ || func.kind === 210 /* ArrowFunction */) { var prev = func; var parent = func.parent; - while (parent.kind === 207 /* ParenthesizedExpression */) { + while (parent.kind === 208 /* ParenthesizedExpression */) { prev = parent; parent = parent.parent; } - if (parent.kind === 203 /* CallExpression */ && parent.expression === prev) { + if (parent.kind === 204 /* CallExpression */ && parent.expression === prev) { return parent; } } @@ -14890,7 +15117,7 @@ var ts; */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 201 /* PropertyAccessExpression */ || kind === 202 /* ElementAccessExpression */) + return (kind === 202 /* PropertyAccessExpression */ || kind === 203 /* ElementAccessExpression */) && node.expression.kind === 105 /* SuperKeyword */; } ts.isSuperProperty = isSuperProperty; @@ -14899,7 +15126,7 @@ var ts; */ function isThisProperty(node) { var kind = node.kind; - return (kind === 201 /* PropertyAccessExpression */ || kind === 202 /* ElementAccessExpression */) + return (kind === 202 /* PropertyAccessExpression */ || kind === 203 /* ElementAccessExpression */) && node.expression.kind === 107 /* ThisKeyword */; } ts.isThisProperty = isThisProperty; @@ -14908,17 +15135,25 @@ var ts; return !!node && ts.isVariableDeclaration(node) && ((_a = node.initializer) === null || _a === void 0 ? void 0 : _a.kind) === 107 /* ThisKeyword */; } ts.isThisInitializedDeclaration = isThisInitializedDeclaration; + function isThisInitializedObjectBindingExpression(node) { + return !!node + && (ts.isShorthandPropertyAssignment(node) || ts.isPropertyAssignment(node)) + && ts.isBinaryExpression(node.parent.parent) + && node.parent.parent.operatorToken.kind === 62 /* EqualsToken */ + && node.parent.parent.right.kind === 107 /* ThisKeyword */; + } + ts.isThisInitializedObjectBindingExpression = isThisInitializedObjectBindingExpression; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return node.typeName; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) ? node.expression : undefined; // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s. case 78 /* Identifier */: - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return node; } return undefined; @@ -14926,10 +15161,10 @@ var ts; ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { switch (node.kind) { - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return node.tag; - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return node.tagName; default: return node.expression; @@ -14942,25 +15177,25 @@ var ts; return false; } switch (node.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: // classes are valid targets return true; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return parent.kind === 252 /* ClassDeclaration */; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: + return parent.kind === 253 /* ClassDeclaration */; + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && parent.kind === 252 /* ClassDeclaration */; - case 160 /* Parameter */: + && parent.kind === 253 /* ClassDeclaration */; + case 161 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; return parent.body !== undefined - && (parent.kind === 166 /* Constructor */ - || parent.kind === 165 /* MethodDeclaration */ - || parent.kind === 168 /* SetAccessor */) - && grandparent.kind === 252 /* ClassDeclaration */; + && (parent.kind === 167 /* Constructor */ + || parent.kind === 166 /* MethodDeclaration */ + || parent.kind === 169 /* SetAccessor */) + && grandparent.kind === 253 /* ClassDeclaration */; } return false; } @@ -14976,10 +15211,10 @@ var ts; ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 - case 165 /* MethodDeclaration */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 169 /* SetAccessor */: return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 default: return false; @@ -14988,9 +15223,9 @@ var ts; ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 275 /* JsxOpeningElement */ || - parent.kind === 274 /* JsxSelfClosingElement */ || - parent.kind === 276 /* JsxClosingElement */) { + if (parent.kind === 276 /* JsxOpeningElement */ || + parent.kind === 275 /* JsxSelfClosingElement */ || + parent.kind === 277 /* JsxClosingElement */) { return parent.tagName === node; } return false; @@ -15003,44 +15238,44 @@ var ts; case 109 /* TrueKeyword */: case 94 /* FalseKeyword */: case 13 /* RegularExpressionLiteral */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 205 /* TaggedTemplateExpression */: - case 224 /* AsExpression */: - case 206 /* TypeAssertionExpression */: - case 225 /* NonNullExpression */: - case 207 /* ParenthesizedExpression */: - case 208 /* FunctionExpression */: - case 221 /* ClassExpression */: - case 209 /* ArrowFunction */: - case 212 /* VoidExpression */: - case 210 /* DeleteExpression */: - case 211 /* TypeOfExpression */: - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: - case 216 /* BinaryExpression */: - case 217 /* ConditionalExpression */: - case 220 /* SpreadElement */: - case 218 /* TemplateExpression */: - case 222 /* OmittedExpression */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: - case 219 /* YieldExpression */: - case 213 /* AwaitExpression */: - case 226 /* MetaProperty */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 206 /* TaggedTemplateExpression */: + case 225 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 226 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 209 /* FunctionExpression */: + case 222 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 213 /* VoidExpression */: + case 211 /* DeleteExpression */: + case 212 /* TypeOfExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 217 /* BinaryExpression */: + case 218 /* ConditionalExpression */: + case 221 /* SpreadElement */: + case 219 /* TemplateExpression */: + case 223 /* OmittedExpression */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: + case 220 /* YieldExpression */: + case 214 /* AwaitExpression */: + case 227 /* MetaProperty */: return true; - case 157 /* QualifiedName */: - while (node.parent.kind === 157 /* QualifiedName */) { + case 158 /* QualifiedName */: + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 176 /* TypeQuery */ || isJSXTagName(node); + return node.parent.kind === 177 /* TypeQuery */ || isJSXTagName(node); case 78 /* Identifier */: - if (node.parent.kind === 176 /* TypeQuery */ || isJSXTagName(node)) { + if (node.parent.kind === 177 /* TypeQuery */ || isJSXTagName(node)) { return true; } // falls through @@ -15058,49 +15293,49 @@ var ts; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 291 /* EnumMember */: - case 288 /* PropertyAssignment */: - case 198 /* BindingElement */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 292 /* EnumMember */: + case 289 /* PropertyAssignment */: + case 199 /* BindingElement */: return parent.initializer === node; - case 233 /* ExpressionStatement */: - case 234 /* IfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 242 /* ReturnStatement */: - case 243 /* WithStatement */: - case 244 /* SwitchStatement */: - case 284 /* CaseClause */: - case 246 /* ThrowStatement */: + case 234 /* ExpressionStatement */: + case 235 /* IfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 243 /* ReturnStatement */: + case 244 /* WithStatement */: + case 245 /* SwitchStatement */: + case 285 /* CaseClause */: + case 247 /* ThrowStatement */: return parent.expression === node; - case 237 /* ForStatement */: + case 238 /* ForStatement */: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 250 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 251 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 250 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 251 /* VariableDeclarationList */) || forInStatement.expression === node; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return node === parent.expression; - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return node === parent.expression; - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return node === parent.expression; - case 161 /* Decorator */: - case 283 /* JsxExpression */: - case 282 /* JsxSpreadAttribute */: - case 290 /* SpreadAssignment */: + case 162 /* Decorator */: + case 284 /* JsxExpression */: + case 283 /* JsxSpreadAttribute */: + case 291 /* SpreadAssignment */: return true; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return parent.objectAssignmentInitializer === node; default: return isExpressionNode(parent); @@ -15108,14 +15343,18 @@ var ts; } ts.isInExpressionContext = isInExpressionContext; function isPartOfTypeQuery(node) { - while (node.kind === 157 /* QualifiedName */ || node.kind === 78 /* Identifier */) { + while (node.kind === 158 /* QualifiedName */ || node.kind === 78 /* Identifier */) { node = node.parent; } - return node.kind === 176 /* TypeQuery */; + return node.kind === 177 /* TypeQuery */; } ts.isPartOfTypeQuery = isPartOfTypeQuery; + function isNamespaceReexportDeclaration(node) { + return ts.isNamespaceExport(node) && !!node.parent.moduleSpecifier; + } + ts.isNamespaceReexportDeclaration = isNamespaceReexportDeclaration; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 272 /* ExternalModuleReference */; + return node.kind === 261 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 273 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -15124,12 +15363,11 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function getExternalModuleRequireArgument(node) { - return isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true) - && getLeftmostAccessExpression(node.initializer).arguments[0]; + return isRequireVariableDeclaration(node) && getLeftmostAccessExpression(node.initializer).arguments[0]; } ts.getExternalModuleRequireArgument = getExternalModuleRequireArgument; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 272 /* ExternalModuleReference */; + return node.kind === 261 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 273 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJS(file) { @@ -15165,7 +15403,7 @@ var ts; } ts.isJSDocIndexSignature = isJSDocIndexSignature; function isRequireCall(callExpression, requireStringLiteralLikeArgument) { - if (callExpression.kind !== 203 /* CallExpression */) { + if (callExpression.kind !== 204 /* CallExpression */) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; @@ -15179,18 +15417,21 @@ var ts; return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; - function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) { - if (node.kind === 198 /* BindingElement */) { + /** + * Returns true if the node is a VariableDeclaration initialized to a require call (see `isRequireCall`). + * This function does not test if the node is in a JavaScript file or not. + */ + function isRequireVariableDeclaration(node) { + if (node.kind === 199 /* BindingElement */) { node = node.parent.parent; } - return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), requireStringLiteralLikeArgument); + return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), /*requireStringLiteralLikeArgument*/ true); } ts.isRequireVariableDeclaration = isRequireVariableDeclaration; - function isRequireVariableStatement(node, requireStringLiteralLikeArgument) { - if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; } + function isRequireVariableStatement(node) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 - && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); }); + && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl); }); } ts.isRequireVariableStatement = isRequireVariableStatement; function isSingleOrDoubleQuote(charCode) { @@ -15262,11 +15503,11 @@ var ts; function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); - return e.kind === 208 /* FunctionExpression */ || e.kind === 209 /* ArrowFunction */ ? initializer : undefined; + return e.kind === 209 /* FunctionExpression */ || e.kind === 210 /* ArrowFunction */ ? initializer : undefined; } - if (initializer.kind === 208 /* FunctionExpression */ || - initializer.kind === 221 /* ClassExpression */ || - initializer.kind === 209 /* ArrowFunction */) { + if (initializer.kind === 209 /* FunctionExpression */ || + initializer.kind === 222 /* ClassExpression */ || + initializer.kind === 210 /* ArrowFunction */) { return initializer; } if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { @@ -15387,8 +15628,7 @@ var ts; ts.isLiteralLikeAccess = isLiteralLikeAccess; /** x[0] OR x['a'] OR x[Symbol.y] */ function isLiteralLikeElementAccess(node) { - return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) || - isWellKnownSymbolSyntactically(node.argumentExpression)); + return ts.isElementAccessExpression(node) && isStringOrNumericLiteralLike(node.argumentExpression); } ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess; /** Any series of property and element accesses. */ @@ -15468,9 +15708,6 @@ var ts; return ts.escapeLeadingUnderscores(name.text); } } - if (ts.isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) { - return getPropertyNameForKnownSymbolName(ts.idText(node.argumentExpression.name)); - } return undefined; } ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName; @@ -15520,7 +15757,7 @@ var ts; ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { return isInJSFile(expr) && - expr.parent && expr.parent.kind === 233 /* ExpressionStatement */ && + expr.parent && expr.parent.kind === 234 /* ExpressionStatement */ && (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) && !!ts.getJSDocTypeTag(expr.parent); } @@ -15541,23 +15778,37 @@ var ts; return false; } var decl = symbol.valueDeclaration; - return decl.kind === 251 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); + return decl.kind === 252 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); } ts.isFunctionSymbol = isFunctionSymbol; + function tryGetModuleSpecifierFromDeclaration(node) { + var _a, _b, _c; + switch (node.kind) { + case 250 /* VariableDeclaration */: + return node.initializer.arguments[0].text; + case 262 /* ImportDeclaration */: + return (_a = ts.tryCast(node.moduleSpecifier, ts.isStringLiteralLike)) === null || _a === void 0 ? void 0 : _a.text; + case 261 /* ImportEqualsDeclaration */: + return (_c = ts.tryCast((_b = ts.tryCast(node.moduleReference, ts.isExternalModuleReference)) === null || _b === void 0 ? void 0 : _b.expression, ts.isStringLiteralLike)) === null || _c === void 0 ? void 0 : _c.text; + default: + ts.Debug.assertNever(node); + } + } + ts.tryGetModuleSpecifierFromDeclaration = tryGetModuleSpecifierFromDeclaration; function importFromModuleSpecifier(node) { return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent); } ts.importFromModuleSpecifier = importFromModuleSpecifier; function tryGetImportFromModuleSpecifier(node) { switch (node.parent.kind) { - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: return node.parent; - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: return node.parent.parent; - case 203 /* CallExpression */: + case 204 /* CallExpression */: return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined; - case 191 /* LiteralType */: + case 192 /* LiteralType */: ts.Debug.assert(ts.isStringLiteral(node)); return ts.tryCast(node.parent.parent, ts.isImportTypeNode); default: @@ -15567,15 +15818,17 @@ var ts; ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: return node.moduleSpecifier; - case 260 /* ImportEqualsDeclaration */: - return node.moduleReference.kind === 272 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; - case 195 /* ImportType */: + case 261 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 273 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 196 /* ImportType */: return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; - case 203 /* CallExpression */: + case 204 /* CallExpression */: return node.arguments[0]; + case 257 /* ModuleDeclaration */: + return node.name.kind === 10 /* StringLiteral */ ? node.name : undefined; default: return ts.Debug.assertNever(node); } @@ -15583,11 +15836,11 @@ var ts; ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return node; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport); default: return ts.Debug.assertNever(node); @@ -15595,7 +15848,7 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 261 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; + return node.kind === 262 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function forEachImportClauseDeclaration(node, action) { @@ -15616,13 +15869,13 @@ var ts; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 160 /* Parameter */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 289 /* ShorthandPropertyAssignment */: - case 288 /* PropertyAssignment */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 161 /* Parameter */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 290 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -15636,7 +15889,7 @@ var ts; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 331 /* JSDocTypedefTag */ || node.kind === 324 /* JSDocCallbackTag */ || node.kind === 325 /* JSDocEnumTag */; + return node.kind === 335 /* JSDocTypedefTag */ || node.kind === 328 /* JSDocCallbackTag */ || node.kind === 329 /* JSDocEnumTag */; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -15661,12 +15914,12 @@ var ts; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: var v = getSingleVariableOfVariableStatement(node); return v && v.initializer; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return node.initializer; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return node.initializer; } } @@ -15678,7 +15931,7 @@ var ts; function getNestedModuleDeclaration(node) { return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 256 /* ModuleDeclaration */ + node.body.kind === 257 /* ModuleDeclaration */ ? node.body : undefined; } @@ -15693,11 +15946,11 @@ var ts; if (ts.hasJSDocNodes(node)) { result = ts.append(result, ts.last(node.jsDoc)); } - if (node.kind === 160 /* Parameter */) { + if (node.kind === 161 /* Parameter */) { result = ts.addRange(result, (noCache ? ts.getJSDocParameterTagsNoCache : ts.getJSDocParameterTags)(node)); break; } - if (node.kind === 159 /* TypeParameter */) { + if (node.kind === 160 /* TypeParameter */) { result = ts.addRange(result, (noCache ? ts.getJSDocTypeParameterTagsNoCache : ts.getJSDocTypeParameterTags)(node)); break; } @@ -15708,10 +15961,11 @@ var ts; ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; function getNextJSDocCommentLocation(node) { var parent = node.parent; - if (parent.kind === 288 /* PropertyAssignment */ || - parent.kind === 266 /* ExportAssignment */ || - parent.kind === 163 /* PropertyDeclaration */ || - parent.kind === 233 /* ExpressionStatement */ && node.kind === 201 /* PropertyAccessExpression */ || + if (parent.kind === 289 /* PropertyAssignment */ || + parent.kind === 267 /* ExportAssignment */ || + parent.kind === 164 /* PropertyDeclaration */ || + parent.kind === 234 /* ExpressionStatement */ && node.kind === 202 /* PropertyAccessExpression */ || + parent.kind === 243 /* ReturnStatement */ || getNestedModuleDeclaration(parent) || ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) { return parent; @@ -15798,7 +16052,7 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 309 /* JSDocVariadicType */; + return node.dotDotDotToken !== undefined || !!type && type.kind === 310 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; function hasTypeArguments(node) { @@ -15815,31 +16069,34 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? binaryOperator === 62 /* EqualsToken */ || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? 1 /* Definite */ : 2 /* Compound */ : 0 /* None */; - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: var unaryOperator = parent.operator; return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; - case 207 /* ParenthesizedExpression */: - case 199 /* ArrayLiteralExpression */: - case 220 /* SpreadElement */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 200 /* ArrayLiteralExpression */: + case 221 /* SpreadElement */: + case 226 /* NonNullExpression */: node = parent; break; - case 289 /* ShorthandPropertyAssignment */: + case 291 /* SpreadAssignment */: + node = parent.parent; + break; + case 290 /* ShorthandPropertyAssignment */: if (parent.name !== node) { return 0 /* None */; } node = parent.parent; break; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: if (parent.name === node) { return 0 /* None */; } @@ -15866,22 +16123,22 @@ var ts; */ function isNodeWithPossibleHoistedDeclaration(node) { switch (node.kind) { - case 230 /* Block */: - case 232 /* VariableStatement */: - case 243 /* WithStatement */: - case 234 /* IfStatement */: - case 244 /* SwitchStatement */: - case 258 /* CaseBlock */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: - case 245 /* LabeledStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 247 /* TryStatement */: - case 287 /* CatchClause */: + case 231 /* Block */: + case 233 /* VariableStatement */: + case 244 /* WithStatement */: + case 235 /* IfStatement */: + case 245 /* SwitchStatement */: + case 259 /* CaseBlock */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 246 /* LabeledStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 248 /* TryStatement */: + case 288 /* CatchClause */: return true; } return false; @@ -15898,11 +16155,11 @@ var ts; return node; } function walkUpParenthesizedTypes(node) { - return walkUp(node, 186 /* ParenthesizedType */); + return walkUp(node, 187 /* ParenthesizedType */); } ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; function walkUpParenthesizedExpressions(node) { - return walkUp(node, 207 /* ParenthesizedExpression */); + return walkUp(node, 208 /* ParenthesizedExpression */); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; /** @@ -15912,7 +16169,7 @@ var ts; */ function walkUpParenthesizedTypesAndGetParentAndChild(node) { var child; - while (node && node.kind === 186 /* ParenthesizedType */) { + while (node && node.kind === 187 /* ParenthesizedType */) { child = node; node = node.parent; } @@ -15924,18 +16181,18 @@ var ts; } ts.skipParentheses = skipParentheses; function skipParenthesesUp(node) { - while (node.kind === 207 /* ParenthesizedExpression */) { + while (node.kind === 208 /* 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 !== 201 /* PropertyAccessExpression */ && node.kind !== 202 /* ElementAccessExpression */) { + if (node.kind !== 202 /* PropertyAccessExpression */ && node.kind !== 203 /* ElementAccessExpression */) { return false; } node = walkUpParenthesizedExpressions(node.parent); - return node && node.kind === 210 /* DeleteExpression */; + return node && node.kind === 211 /* DeleteExpression */; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -15988,7 +16245,7 @@ var ts; ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return isStringOrNumericLiteralLike(node) && - node.parent.kind === 158 /* ComputedPropertyName */ && + node.parent.kind === 159 /* ComputedPropertyName */ && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; @@ -15996,26 +16253,26 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 291 /* EnumMember */: - case 288 /* PropertyAssignment */: - case 201 /* PropertyAccessExpression */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 292 /* EnumMember */: + case 289 /* PropertyAssignment */: + case 202 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: // Name on right hand side of dot in a type query or type reference return parent.right === node; - case 198 /* BindingElement */: - case 265 /* ImportSpecifier */: + case 199 /* BindingElement */: + case 266 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 270 /* ExportSpecifier */: - case 280 /* JsxAttribute */: + case 271 /* ExportSpecifier */: + case 281 /* JsxAttribute */: // Any name in an export specifier or JSX Attribute return true; } @@ -16035,33 +16292,33 @@ var ts; // {} // {name: } function isAliasSymbolDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ || - node.kind === 259 /* NamespaceExportDeclaration */ || - node.kind === 262 /* ImportClause */ && !!node.name || - node.kind === 263 /* NamespaceImport */ || - node.kind === 269 /* NamespaceExport */ || - node.kind === 265 /* ImportSpecifier */ || - node.kind === 270 /* ExportSpecifier */ || - node.kind === 266 /* ExportAssignment */ && exportAssignmentIsAlias(node) || + return node.kind === 261 /* ImportEqualsDeclaration */ || + node.kind === 260 /* NamespaceExportDeclaration */ || + node.kind === 263 /* ImportClause */ && !!node.name || + node.kind === 264 /* NamespaceImport */ || + node.kind === 270 /* NamespaceExport */ || + node.kind === 266 /* ImportSpecifier */ || + node.kind === 271 /* ExportSpecifier */ || + node.kind === 267 /* ExportAssignment */ && exportAssignmentIsAlias(node) || ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) || ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableExpression(node.parent.right) || - node.kind === 289 /* ShorthandPropertyAssignment */ || - node.kind === 288 /* PropertyAssignment */ && isAliasableExpression(node.initializer); + node.kind === 290 /* ShorthandPropertyAssignment */ || + node.kind === 289 /* PropertyAssignment */ && isAliasableExpression(node.initializer); } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function getAliasDeclarationFromName(node) { switch (node.parent.kind) { - case 262 /* ImportClause */: - case 265 /* ImportSpecifier */: - case 263 /* NamespaceImport */: - case 270 /* ExportSpecifier */: - case 266 /* ExportAssignment */: - case 260 /* ImportEqualsDeclaration */: + case 263 /* ImportClause */: + case 266 /* ImportSpecifier */: + case 264 /* NamespaceImport */: + case 271 /* ExportSpecifier */: + case 267 /* ExportAssignment */: + case 261 /* ImportEqualsDeclaration */: return node.parent; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: do { node = node.parent; - } while (node.parent.kind === 157 /* QualifiedName */); + } while (node.parent.kind === 158 /* QualifiedName */); return getAliasDeclarationFromName(node); } } @@ -16080,7 +16337,7 @@ var ts; } ts.getExportAssignmentExpression = getExportAssignmentExpression; function getPropertyAssignmentAliasLikeExpression(node) { - return node.kind === 289 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 288 /* PropertyAssignment */ ? node.initializer : + return node.kind === 290 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 289 /* PropertyAssignment */ ? node.initializer : node.parent.right; } ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression; @@ -16146,11 +16403,11 @@ var ts; } ts.getAncestor = getAncestor; function isKeyword(token) { - return 80 /* FirstKeyword */ <= token && token <= 156 /* LastKeyword */; + return 80 /* FirstKeyword */ <= token && token <= 157 /* LastKeyword */; } ts.isKeyword = isKeyword; function isContextualKeyword(token) { - return 125 /* FirstContextualKeyword */ <= token && token <= 156 /* LastContextualKeyword */; + return 125 /* FirstContextualKeyword */ <= token && token <= 157 /* LastContextualKeyword */; } ts.isContextualKeyword = isContextualKeyword; function isNonContextualKeyword(token) { @@ -16194,14 +16451,14 @@ var ts; } var flags = 0 /* Normal */; switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 165 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 166 /* MethodDeclaration */: if (node.asteriskToken) { flags |= 1 /* Generator */; } // falls through - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: if (hasSyntacticModifier(node, 256 /* Async */)) { flags |= 2 /* Async */; } @@ -16215,10 +16472,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: return node.body !== undefined && node.asteriskToken === undefined && hasSyntacticModifier(node, 256 /* Async */); @@ -16241,9 +16498,6 @@ var ts; * 3. The computed name is *not* expressed as a NumericLiteral. * 4. The computed name is *not* expressed as a PlusToken or MinusToken * immediately followed by a NumericLiteral. - * 5. The computed name is *not* expressed as `Symbol.`, where `` - * is a property of the Symbol constructor that denotes a built-in - * Symbol. */ function hasDynamicName(declaration) { var name = ts.getNameOfDeclaration(declaration); @@ -16251,24 +16505,14 @@ var ts; } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - if (!(name.kind === 158 /* ComputedPropertyName */ || name.kind === 202 /* ElementAccessExpression */)) { + if (!(name.kind === 159 /* ComputedPropertyName */ || name.kind === 203 /* ElementAccessExpression */)) { return false; } var expr = ts.isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression; return !isStringOrNumericLiteralLike(expr) && - !isSignedNumericLiteral(expr) && - !isWellKnownSymbolSyntactically(expr); + !isSignedNumericLiteral(expr); } ts.isDynamicName = isDynamicName; - /** - * Checks if the expression is of the form: - * Symbol.name - * where Symbol is literally the word "Symbol", and name is any identifierName - */ - function isWellKnownSymbolSyntactically(node) { - return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); - } - ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { switch (name.kind) { case 78 /* Identifier */: @@ -16277,12 +16521,9 @@ var ts; case 10 /* StringLiteral */: case 8 /* NumericLiteral */: return ts.escapeLeadingUnderscores(name.text); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: var nameExpression = name.expression; - if (isWellKnownSymbolSyntactically(nameExpression)) { - return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - else if (isStringOrNumericLiteralLike(nameExpression)) { + if (isStringOrNumericLiteralLike(nameExpression)) { return ts.escapeLeadingUnderscores(nameExpression.text); } else if (isSignedNumericLiteral(nameExpression)) { @@ -16310,21 +16551,17 @@ var ts; } ts.isPropertyNameLiteral = isPropertyNameLiteral; function getTextOfIdentifierOrLiteral(node) { - return ts.isIdentifierOrPrivateIdentifier(node) ? ts.idText(node) : node.text; + return ts.isMemberName(node) ? ts.idText(node) : node.text; } ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; function getEscapedTextOfIdentifierOrLiteral(node) { - return ts.isIdentifierOrPrivateIdentifier(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text); + return ts.isMemberName(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForUniqueESSymbol(symbol) { return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName; } ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol; - function getPropertyNameForKnownSymbolName(symbolName) { - return "__@" + symbolName; - } - ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) { return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description; } @@ -16346,11 +16583,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 160 /* Parameter */; + return root.kind === 161 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 198 /* BindingElement */) { + while (node.kind === 199 /* BindingElement */) { node = node.parent.parent; } return node; @@ -16358,15 +16595,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 166 /* Constructor */ - || kind === 208 /* FunctionExpression */ - || kind === 251 /* FunctionDeclaration */ - || kind === 209 /* ArrowFunction */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 256 /* ModuleDeclaration */ - || kind === 297 /* SourceFile */; + return kind === 167 /* Constructor */ + || kind === 209 /* FunctionExpression */ + || kind === 252 /* FunctionDeclaration */ + || kind === 210 /* ArrowFunction */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 257 /* ModuleDeclaration */ + || kind === 298 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -16385,23 +16622,23 @@ var ts; })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 204 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 205 /* NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 204 /* NewExpression */: + case 205 /* NewExpression */: return hasArguments ? 0 /* Left */ : 1 /* Right */; - case 214 /* PrefixUnaryExpression */: - case 211 /* TypeOfExpression */: - case 212 /* VoidExpression */: - case 210 /* DeleteExpression */: - case 213 /* AwaitExpression */: - case 217 /* ConditionalExpression */: - case 219 /* YieldExpression */: + case 215 /* PrefixUnaryExpression */: + case 212 /* TypeOfExpression */: + case 213 /* VoidExpression */: + case 211 /* DeleteExpression */: + case 214 /* AwaitExpression */: + case 218 /* ConditionalExpression */: + case 220 /* YieldExpression */: return 1 /* Right */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (operator) { case 42 /* AsteriskAsteriskToken */: case 62 /* EqualsToken */: @@ -16428,15 +16665,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 204 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 205 /* NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 216 /* BinaryExpression */) { + if (expression.kind === 217 /* BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 214 /* PrefixUnaryExpression */ || expression.kind === 215 /* PostfixUnaryExpression */) { + else if (expression.kind === 215 /* PrefixUnaryExpression */ || expression.kind === 216 /* PostfixUnaryExpression */) { return expression.operator; } else { @@ -16615,15 +16852,15 @@ var ts; })(OperatorPrecedence = ts.OperatorPrecedence || (ts.OperatorPrecedence = {})); function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return 0 /* Comma */; - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return 1 /* Spread */; - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return 2 /* Yield */; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return 4 /* Conditional */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (operatorKind) { case 27 /* CommaToken */: return 0 /* Comma */; @@ -16648,25 +16885,26 @@ var ts; return getBinaryOperatorPrecedence(operatorKind); } // TODO: Should prefix `++` and `--` be moved to the `Update` precedence? - case 206 /* TypeAssertionExpression */: - case 225 /* NonNullExpression */: - case 214 /* PrefixUnaryExpression */: - case 211 /* TypeOfExpression */: - case 212 /* VoidExpression */: - case 210 /* DeleteExpression */: - case 213 /* AwaitExpression */: + case 207 /* TypeAssertionExpression */: + case 226 /* NonNullExpression */: + case 215 /* PrefixUnaryExpression */: + case 212 /* TypeOfExpression */: + case 213 /* VoidExpression */: + case 211 /* DeleteExpression */: + case 214 /* AwaitExpression */: return 16 /* Unary */; - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return 17 /* Update */; - case 203 /* CallExpression */: + case 204 /* CallExpression */: return 18 /* LeftHandSide */; - case 204 /* NewExpression */: + case 205 /* NewExpression */: return hasArguments ? 19 /* Member */ : 18 /* LeftHandSide */; - case 205 /* TaggedTemplateExpression */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 206 /* TaggedTemplateExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 227 /* MetaProperty */: return 19 /* Member */; - case 224 /* AsExpression */: + case 225 /* AsExpression */: return 11 /* Relational */; case 107 /* ThisKeyword */: case 105 /* SuperKeyword */: @@ -16677,19 +16915,19 @@ var ts; case 8 /* NumericLiteral */: case 9 /* BigIntLiteral */: case 10 /* StringLiteral */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 221 /* ClassExpression */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 222 /* ClassExpression */: case 13 /* RegularExpressionLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: - case 218 /* TemplateExpression */: - case 207 /* ParenthesizedExpression */: - case 222 /* OmittedExpression */: - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: + case 219 /* TemplateExpression */: + case 208 /* ParenthesizedExpression */: + case 223 /* OmittedExpression */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: return 20 /* Primary */; default: return -1 /* Invalid */; @@ -16745,7 +16983,7 @@ var ts; function getSemanticJsxChildren(children) { return ts.filter(children, function (i) { switch (i.kind) { - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return !!i.expression; case 11 /* JsxText */: return !i.containsOnlyTriviaWhiteSpaces; @@ -17139,11 +17377,20 @@ var ts; return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getCanonicalAbsolutePath(host, path) { + return host.getCanonicalFileName(ts.getNormalizedAbsolutePath(path, host.getCurrentDirectory())); + } function getExternalModuleNameFromDeclaration(host, resolver, declaration) { var file = resolver.getExternalModuleFileFromDeclaration(declaration); if (!file || file.isDeclarationFile) { return undefined; } + // If the declaration already uses a non-relative name, and is outside the common source directory, continue to use it + var specifier = getExternalModuleName(declaration); + if (specifier && ts.isStringLiteralLike(specifier) && !ts.pathIsRelative(specifier.text) && + getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ts.ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1) { + return undefined; + } return getResolvedExternalModuleName(host, file); } ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; @@ -17227,8 +17474,8 @@ var ts; return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !host.isSourceFileFromExternalLibrary(sourceFile) && - !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) && - (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName)); + (forceDtsEmit || (!(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) && + !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName))); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -17323,10 +17570,10 @@ var ts; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 167 /* GetAccessor */) { + if (accessor.kind === 168 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 168 /* SetAccessor */) { + else if (accessor.kind === 169 /* SetAccessor */) { setAccessor = accessor; } else { @@ -17346,10 +17593,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 167 /* GetAccessor */ && !getAccessor) { + if (member.kind === 168 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 168 /* SetAccessor */ && !setAccessor) { + if (member.kind === 169 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -17398,7 +17645,7 @@ var ts; ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** template tags are only available when a typedef isn't already using them */ function isNonTypeAliasTemplate(tag) { - return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 311 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 312 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); } /** * Gets the effective type annotation of the value parameter of a set accessor. If the node @@ -17621,6 +17868,18 @@ var ts; return hasSyntacticModifier(node, 32 /* Static */); } ts.hasStaticModifier = hasStaticModifier; + function hasOverrideModifier(node) { + return hasEffectiveModifier(node, 16384 /* Override */); + } + ts.hasOverrideModifier = hasOverrideModifier; + function hasAbstractModifier(node) { + return hasSyntacticModifier(node, 128 /* Abstract */); + } + ts.hasAbstractModifier = hasAbstractModifier; + function hasAmbientModifier(node) { + return hasSyntacticModifier(node, 2 /* Ambient */); + } + ts.hasAmbientModifier = hasAmbientModifier; function hasEffectiveReadonlyModifier(node) { return hasEffectiveModifier(node, 64 /* Readonly */); } @@ -17634,7 +17893,7 @@ var ts; } ts.getSelectedSyntacticModifierFlags = getSelectedSyntacticModifierFlags; function getModifierFlagsWorker(node, includeJSDoc, alwaysIncludeJSDoc) { - if (node.kind >= 0 /* FirstToken */ && node.kind <= 156 /* LastToken */) { + if (node.kind >= 0 /* FirstToken */ && node.kind <= 157 /* LastToken */) { return 0 /* None */; } if (!(node.modifierFlagsCache & 536870912 /* HasComputedFlags */)) { @@ -17679,6 +17938,8 @@ var ts; flags |= 16 /* Protected */; if (ts.getJSDocReadonlyTagNoCache(node)) flags |= 64 /* Readonly */; + if (ts.getJSDocOverrideTagNoCache(node)) + flags |= 16384 /* Override */; } if (ts.getJSDocDeprecatedTagNoCache(node)) flags |= 8192 /* Deprecated */; @@ -17731,10 +17992,15 @@ var ts; case 87 /* DefaultKeyword */: return 512 /* Default */; case 129 /* AsyncKeyword */: return 256 /* Async */; case 142 /* ReadonlyKeyword */: return 64 /* Readonly */; + case 156 /* OverrideKeyword */: return 16384 /* Override */; } return 0 /* None */; } ts.modifierToFlag = modifierToFlag; + function createModifiers(modifierFlags) { + return modifierFlags ? ts.factory.createNodeArray(ts.factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; + } + ts.createModifiers = createModifiers; function isLogicalOperator(token) { return token === 56 /* BarBarToken */ || token === 55 /* AmpersandAmpersandToken */ @@ -17777,11 +18043,15 @@ var ts; && ts.isLeftHandSideExpression(node.left); } ts.isAssignmentExpression = isAssignmentExpression; + function isLeftHandSideOfAssignment(node) { + return isAssignmentExpression(node.parent) && node.parent.left === node; + } + ts.isLeftHandSideOfAssignment = isLeftHandSideOfAssignment; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { var kind = node.left.kind; - return kind === 200 /* ObjectLiteralExpression */ - || kind === 199 /* ArrayLiteralExpression */; + return kind === 201 /* ObjectLiteralExpression */ + || kind === 200 /* ArrayLiteralExpression */; } return false; } @@ -17798,12 +18068,12 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: do { node = node.left; } while (node.kind !== 78 /* Identifier */); return node; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: do { node = node.expression; } while (node.kind !== 78 /* Identifier */); @@ -17812,9 +18082,12 @@ var ts; } ts.getFirstIdentifier = getFirstIdentifier; function isDottedName(node) { - return node.kind === 78 /* Identifier */ || node.kind === 107 /* ThisKeyword */ || node.kind === 105 /* SuperKeyword */ || - node.kind === 201 /* PropertyAccessExpression */ && isDottedName(node.expression) || - node.kind === 207 /* ParenthesizedExpression */ && isDottedName(node.expression); + return node.kind === 78 /* Identifier */ + || node.kind === 107 /* ThisKeyword */ + || node.kind === 105 /* SuperKeyword */ + || node.kind === 227 /* MetaProperty */ + || node.kind === 202 /* PropertyAccessExpression */ && isDottedName(node.expression) + || node.kind === 208 /* ParenthesizedExpression */ && isDottedName(node.expression); } ts.isDottedName = isDottedName; function isPropertyAccessEntityNameExpression(node) { @@ -17828,6 +18101,12 @@ var ts; return baseStr + "." + entityNameToString(expr.name); } } + else if (ts.isElementAccessExpression(expr)) { + var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); + if (baseStr !== undefined && ts.isPropertyName(expr.argumentExpression)) { + return baseStr + "." + getPropertyNameForPropertyNameNode(expr.argumentExpression); + } + } else if (ts.isIdentifier(expr)) { return ts.unescapeLeadingUnderscores(expr.escapedText); } @@ -17839,22 +18118,22 @@ var ts; } ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 157 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 158 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 202 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 200 /* ObjectLiteralExpression */ && + return expression.kind === 201 /* ObjectLiteralExpression */ && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 199 /* ArrayLiteralExpression */ && + return expression.kind === 200 /* ArrayLiteralExpression */ && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - if (!isExportDefaultSymbol(symbol)) + if (!isExportDefaultSymbol(symbol) || !symbol.declarations) return undefined; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; @@ -18181,8 +18460,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 255 /* EnumDeclaration */: - case 256 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: + case 257 /* ModuleDeclaration */: return parseNode === parseNode.parent.name; } } @@ -18209,9 +18488,11 @@ var ts; return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0; } ts.getCheckFlags = getCheckFlags; - function getDeclarationModifierFlagsFromSymbol(s) { + function getDeclarationModifierFlagsFromSymbol(s, isWrite) { + if (isWrite === void 0) { isWrite = false; } if (s.valueDeclaration) { - var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + var declaration = (isWrite && s.declarations && ts.find(s.declarations, function (d) { return d.kind === 169 /* SetAccessor */; })) || s.valueDeclaration; + var flags = ts.getCombinedModifierFlags(declaration); return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; } if (getCheckFlags(s) & 6 /* Synthetic */) { @@ -18259,35 +18540,35 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return accessKind(parent); - case 215 /* PostfixUnaryExpression */: - case 214 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: var operator = parent.operator; return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? operatorToken.kind === 62 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite() : 0 /* Read */; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); - case 288 /* PropertyAssignment */: { + case 289 /* 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 289 /* ShorthandPropertyAssignment */: + case 290 /* 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 199 /* ArrayLiteralExpression */: + case 200 /* 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 && skipParenthesesUp(parent.parent).kind === 233 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 234 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; } } function reverseAccessKind(a) { @@ -18375,7 +18656,8 @@ var ts; } ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol; function getClassLikeDeclarationOfSymbol(symbol) { - return ts.find(symbol.declarations, ts.isClassLike); + var _a; + return (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isClassLike); } ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; function getObjectFlags(type) { @@ -18418,7 +18700,6 @@ var ts; ts.getLastChild = getLastChild; function addToSeen(seen, key, value) { if (value === void 0) { value = true; } - key = String(key); if (seen.has(key)) { return false; } @@ -18431,7 +18712,7 @@ var ts; } ts.isObjectTypeDeclaration = isObjectTypeDeclaration; function isTypeNodeKind(kind) { - return (kind >= 172 /* FirstTypeNode */ && kind <= 195 /* LastTypeNode */) + return (kind >= 173 /* FirstTypeNode */ && kind <= 196 /* LastTypeNode */) || kind === 128 /* AnyKeyword */ || kind === 152 /* UnknownKeyword */ || kind === 144 /* NumberKeyword */ @@ -18443,25 +18724,25 @@ var ts; || kind === 113 /* VoidKeyword */ || kind === 150 /* UndefinedKeyword */ || kind === 141 /* NeverKeyword */ - || kind === 223 /* ExpressionWithTypeArguments */ - || kind === 303 /* JSDocAllType */ - || kind === 304 /* JSDocUnknownType */ - || kind === 305 /* JSDocNullableType */ - || kind === 306 /* JSDocNonNullableType */ - || kind === 307 /* JSDocOptionalType */ - || kind === 308 /* JSDocFunctionType */ - || kind === 309 /* JSDocVariadicType */; + || kind === 224 /* ExpressionWithTypeArguments */ + || kind === 304 /* JSDocAllType */ + || kind === 305 /* JSDocUnknownType */ + || kind === 306 /* JSDocNullableType */ + || kind === 307 /* JSDocNonNullableType */ + || kind === 308 /* JSDocOptionalType */ + || kind === 309 /* JSDocFunctionType */ + || kind === 310 /* JSDocVariadicType */; } ts.isTypeNodeKind = isTypeNodeKind; function isAccessExpression(node) { - return node.kind === 201 /* PropertyAccessExpression */ || node.kind === 202 /* ElementAccessExpression */; + return node.kind === 202 /* PropertyAccessExpression */ || node.kind === 203 /* ElementAccessExpression */; } ts.isAccessExpression = isAccessExpression; function getNameOfAccessExpression(node) { - if (node.kind === 201 /* PropertyAccessExpression */) { + if (node.kind === 202 /* PropertyAccessExpression */) { return node.name; } - ts.Debug.assert(node.kind === 202 /* ElementAccessExpression */); + ts.Debug.assert(node.kind === 203 /* ElementAccessExpression */); return node.argumentExpression; } ts.getNameOfAccessExpression = getNameOfAccessExpression; @@ -18476,7 +18757,7 @@ var ts; } ts.isBundleFileTextLike = isBundleFileTextLike; function isNamedImportsOrExports(node) { - return node.kind === 264 /* NamedImports */ || node.kind === 268 /* NamedExports */; + return node.kind === 265 /* NamedImports */ || node.kind === 269 /* NamedExports */; } ts.isNamedImportsOrExports = isNamedImportsOrExports; function getLeftmostAccessExpression(expr) { @@ -18489,28 +18770,28 @@ var ts; function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: node = node.operand; continue; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: node = node.left; continue; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: node = node.condition; continue; - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: node = node.tag; continue; - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (stopAtCallExpressions) { return node; } // falls through - case 224 /* AsExpression */: - case 202 /* ElementAccessExpression */: - case 201 /* PropertyAccessExpression */: - case 225 /* NonNullExpression */: - case 336 /* PartiallyEmittedExpression */: + case 225 /* AsExpression */: + case 203 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 226 /* NonNullExpression */: + case 340 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -18529,7 +18810,7 @@ var ts; } function Type(checker, flags) { this.flags = flags; - if (ts.Debug.isDebugging || ts.tracing.isTracing()) { + if (ts.Debug.isDebugging || ts.tracing) { this.checker = checker; } } @@ -18873,6 +19154,10 @@ var ts; return !!(compilerOptions.declaration || compilerOptions.composite); } ts.getEmitDeclarations = getEmitDeclarations; + function shouldPreserveConstEnums(compilerOptions) { + return !!(compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + } + ts.shouldPreserveConstEnums = shouldPreserveConstEnums; function isIncrementalCompilation(options) { return !!(options.incremental || options.composite); } @@ -18885,6 +19170,10 @@ var ts; return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs; } ts.getAllowJSCompilerOption = getAllowJSCompilerOption; + function getUseDefineForClassFields(compilerOptions) { + return compilerOptions.useDefineForClassFields === undefined ? compilerOptions.target === 99 /* ESNext */ : compilerOptions.useDefineForClassFields; + } + ts.getUseDefineForClassFields = getUseDefineForClassFields; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { return oldOptions !== newOptions && ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); @@ -18906,7 +19195,7 @@ var ts; ts.getJSXTransformEnabled = getJSXTransformEnabled; function getJSXImplicitImportBase(compilerOptions, file) { var jsxImportSourcePragmas = file === null || file === void 0 ? void 0 : file.pragmas.get("jsximportsource"); - var jsxImportSourcePragma = ts.isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[0] : jsxImportSourcePragmas; + var jsxImportSourcePragma = ts.isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[jsxImportSourcePragmas.length - 1] : jsxImportSourcePragmas; return compilerOptions.jsx === 4 /* ReactJSX */ || compilerOptions.jsx === 5 /* ReactJSXDev */ || compilerOptions.jsxImportSource || @@ -18935,37 +19224,65 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createSymlinkCache() { + function createSymlinkCache(cwd, getCanonicalFileName) { var symlinkedDirectories; + var symlinkedDirectoriesByRealpath; var symlinkedFiles; return { getSymlinkedFiles: function () { return symlinkedFiles; }, getSymlinkedDirectories: function () { return symlinkedDirectories; }, + getSymlinkedDirectoriesByRealpath: function () { return symlinkedDirectoriesByRealpath; }, setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); }, - setSymlinkedDirectory: function (path, directory) { return (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(path, directory); }, + setSymlinkedDirectory: function (symlink, real) { + // Large, interconnected dependency graphs in pnpm will have a huge number of symlinks + // where both the realpath and the symlink path are inside node_modules/.pnpm. Since + // this path is never a candidate for a module specifier, we can ignore it entirely. + var symlinkPath = ts.toPath(symlink, cwd, getCanonicalFileName); + if (!containsIgnoredPath(symlinkPath)) { + symlinkPath = ts.ensureTrailingDirectorySeparator(symlinkPath); + if (real !== false && !(symlinkedDirectories === null || symlinkedDirectories === void 0 ? void 0 : symlinkedDirectories.has(symlinkPath))) { + (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = ts.createMultiMap())).add(ts.ensureTrailingDirectorySeparator(real.realPath), symlink); + } + (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); + } + }, + setSymlinkedDirectoryFromSymlinkedFile: function (symlink, real) { + this.setSymlinkedFile(ts.toPath(symlink, cwd, getCanonicalFileName), real); + var _a = guessDirectorySymlink(real, symlink, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _a[0], commonOriginal = _a[1]; + if (commonResolved && commonOriginal) { + this.setSymlinkedDirectory(commonOriginal, { + real: commonResolved, + realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName), + }); + } + }, }; } ts.createSymlinkCache = createSymlinkCache; function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { - var cache = createSymlinkCache(); - var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { - return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) { - return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + var cache = createSymlinkCache(cwd, getCanonicalFileName); + var symlinks = ts.flatMap(files, function (sf) { + var pairs = sf.resolvedModules && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedModules.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) ? [res.resolvedFileName, res.originalPath] : undefined; + })); + return ts.concatenate(pairs, sf.resolvedTypeReferenceDirectiveNames && ts.arrayFrom(ts.mapDefinedIterator(sf.resolvedTypeReferenceDirectiveNames.values(), function (res) { + return (res === null || res === void 0 ? void 0 : res.originalPath) && res.resolvedFileName ? [res.resolvedFileName, res.originalPath] : undefined; }))); - })); + }); for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + cache.setSymlinkedFile(ts.toPath(originalPath, cwd, getCanonicalFileName), resolvedPath); var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1]; if (commonResolved && commonOriginal) { - cache.setSymlinkedDirectory(ts.toPath(commonOriginal, cwd, getCanonicalFileName), { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); + cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) }); } } return cache; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(a, cwd)); + var bParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(b, cwd)); var isDirectory = false; while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && @@ -19349,6 +19666,14 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + function numberOfDirectorySeparators(str) { + var match = str.match(/\//g); + return match ? match.length : 0; + } + function compareNumberOfDirectorySeparators(path1, path2) { + return ts.compareValues(numberOfDirectorySeparators(path1), numberOfDirectorySeparators(path2)); + } + ts.compareNumberOfDirectorySeparators = compareNumberOfDirectorySeparators; /** * Extension boundaries by priority. Lower numbers indicate higher priorities, and are * aligned to the offset of the highest priority extension in the @@ -19645,21 +19970,21 @@ var ts; } ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite; function typeOnlyDeclarationIsExport(typeOnlyDeclaration) { - return typeOnlyDeclaration.kind === 270 /* ExportSpecifier */; + return typeOnlyDeclaration.kind === 271 /* ExportSpecifier */; } ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport; function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) { - while (node.kind === 78 /* Identifier */ || node.kind === 201 /* PropertyAccessExpression */) { + while (node.kind === 78 /* Identifier */ || node.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - if (node.kind !== 158 /* ComputedPropertyName */) { + if (node.kind !== 159 /* ComputedPropertyName */) { return false; } if (hasSyntacticModifier(node.parent, 128 /* Abstract */)) { return true; } var containerKind = node.parent.parent.kind; - return containerKind === 253 /* InterfaceDeclaration */ || containerKind === 177 /* TypeLiteral */; + return containerKind === 254 /* InterfaceDeclaration */ || containerKind === 178 /* TypeLiteral */; } /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */ function isIdentifierInNonEmittingHeritageClause(node) { @@ -19667,16 +19992,16 @@ var ts; return false; var heritageClause = ts.findAncestor(node.parent, function (parent) { switch (parent.kind) { - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: return true; - case 201 /* PropertyAccessExpression */: - case 223 /* ExpressionWithTypeArguments */: + case 202 /* PropertyAccessExpression */: + case 224 /* ExpressionWithTypeArguments */: return false; default: return "quit"; } }); - return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 116 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 253 /* InterfaceDeclaration */; + return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 116 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 254 /* InterfaceDeclaration */; } function isIdentifierTypeReference(node) { return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName); @@ -19829,6 +20154,76 @@ var ts; } } ts.expressionResultIsUnused = expressionResultIsUnused; + function containsIgnoredPath(path) { + return ts.some(ts.ignoredPaths, function (p) { return ts.stringContains(path, p); }); + } + ts.containsIgnoredPath = containsIgnoredPath; + function getContainingNodeArray(node) { + if (!node.parent) + return undefined; + switch (node.kind) { + case 160 /* TypeParameter */: + var parent_1 = node.parent; + return parent_1.kind === 186 /* InferType */ ? undefined : parent_1.typeParameters; + case 161 /* Parameter */: + return node.parent.parameters; + case 195 /* TemplateLiteralTypeSpan */: + return node.parent.templateSpans; + case 229 /* TemplateSpan */: + return node.parent.templateSpans; + case 162 /* Decorator */: + return node.parent.decorators; + case 287 /* HeritageClause */: + return node.parent.heritageClauses; + } + var parent = node.parent; + if (ts.isJSDocTag(node)) { + return ts.isJSDocTypeLiteral(node.parent) ? undefined : node.parent.tags; + } + switch (parent.kind) { + case 178 /* TypeLiteral */: + case 254 /* InterfaceDeclaration */: + return ts.isTypeElement(node) ? parent.members : undefined; + case 183 /* UnionType */: + case 184 /* IntersectionType */: + return parent.types; + case 180 /* TupleType */: + case 200 /* ArrayLiteralExpression */: + case 341 /* CommaListExpression */: + case 265 /* NamedImports */: + case 269 /* NamedExports */: + return parent.elements; + case 201 /* ObjectLiteralExpression */: + case 282 /* JsxAttributes */: + return parent.properties; + case 204 /* CallExpression */: + case 205 /* NewExpression */: + return ts.isTypeNode(node) ? parent.typeArguments : + parent.expression === node ? undefined : + parent.arguments; + case 274 /* JsxElement */: + case 278 /* JsxFragment */: + return ts.isJsxChild(node) ? parent.children : undefined; + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + return ts.isTypeNode(node) ? parent.typeArguments : undefined; + case 231 /* Block */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 258 /* ModuleBlock */: + return parent.statements; + case 259 /* CaseBlock */: + return parent.clauses; + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + return ts.isClassElement(node) ? parent.members : undefined; + case 256 /* EnumDeclaration */: + return ts.isEnumMember(node) ? parent.members : undefined; + case 298 /* SourceFile */: + return parent.statements; + } + } + ts.getContainingNodeArray = getContainingNodeArray; })(ts || (ts = {})); /* @internal */ var ts; @@ -19873,7 +20268,11 @@ var ts; var ts; (function (ts) { function createParenthesizerRules(factory) { + var binaryLeftOperandParenthesizerCache; + var binaryRightOperandParenthesizerCache; return { + getParenthesizeLeftSideOfBinaryForOperator: getParenthesizeLeftSideOfBinaryForOperator, + getParenthesizeRightSideOfBinaryForOperator: getParenthesizeRightSideOfBinaryForOperator, parenthesizeLeftSideOfBinary: parenthesizeLeftSideOfBinary, parenthesizeRightSideOfBinary: parenthesizeRightSideOfBinary, parenthesizeExpressionOfComputedPropertyName: parenthesizeExpressionOfComputedPropertyName, @@ -19894,6 +20293,24 @@ var ts; parenthesizeConstituentTypesOfUnionOrIntersectionType: parenthesizeConstituentTypesOfUnionOrIntersectionType, parenthesizeTypeArguments: parenthesizeTypeArguments, }; + function getParenthesizeLeftSideOfBinaryForOperator(operatorKind) { + binaryLeftOperandParenthesizerCache || (binaryLeftOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeLeftSideOfBinary(operatorKind, node); }; + binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } + function getParenthesizeRightSideOfBinaryForOperator(operatorKind) { + binaryRightOperandParenthesizerCache || (binaryRightOperandParenthesizerCache = new ts.Map()); + var parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = function (node) { return parenthesizeRightSideOfBinary(operatorKind, /*leftSide*/ undefined, node); }; + binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } /** * Determines whether the operand to a BinaryExpression needs to be parenthesized. * @@ -19920,10 +20337,10 @@ var ts; // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - var binaryOperatorPrecedence = ts.getOperatorPrecedence(216 /* BinaryExpression */, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(216 /* BinaryExpression */, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(217 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(217 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); - if (!isLeftSideOfBinary && operand.kind === 209 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */) { + if (!isLeftSideOfBinary && operand.kind === 210 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */) { // We need to parenthesize arrow functions on the right side to avoid it being // parsed as parenthesized expression: `a && (() => {})` return true; @@ -19935,7 +20352,7 @@ var ts; // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ - && operand.kind === 219 /* YieldExpression */) { + && operand.kind === 220 /* YieldExpression */) { return false; } return true; @@ -20023,7 +20440,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) { + if (node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -20049,7 +20466,7 @@ var ts; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. - if (skipped.kind === 207 /* ParenthesizedExpression */) { + if (skipped.kind === 208 /* ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -20066,7 +20483,7 @@ var ts; return ts.isCommaSequence(expression) ? factory.createParenthesizedExpression(expression) : expression; } function parenthesizeConditionOfConditionalExpression(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(217 /* ConditionalExpression */, 57 /* QuestionToken */); + var conditionalPrecedence = ts.getOperatorPrecedence(218 /* ConditionalExpression */, 57 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) { @@ -20099,8 +20516,8 @@ var ts; var needsParens = ts.isCommaSequence(check); if (!needsParens) { switch (ts.getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: needsParens = true; } } @@ -20113,9 +20530,9 @@ var ts; function parenthesizeExpressionOfNew(expression) { var leftmostExpr = ts.getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); switch (leftmostExpr.kind) { - case 203 /* CallExpression */: + case 204 /* CallExpression */: return factory.createParenthesizedExpression(expression); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return !leftmostExpr.arguments ? factory.createParenthesizedExpression(expression) : expression; // TODO(rbuckton): Verify this assertion holds @@ -20135,7 +20552,7 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 204 /* NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 205 /* NewExpression */ || emittedExpression.arguments)) { // TODO(rbuckton): Verify whether this assertion holds. return expression; } @@ -20157,7 +20574,7 @@ var ts; function parenthesizeExpressionForDisallowedComma(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(216 /* BinaryExpression */, 27 /* CommaToken */); + var commaPrecedence = ts.getOperatorPrecedence(217 /* BinaryExpression */, 27 /* CommaToken */); // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(factory.createParenthesizedExpression(expression), expression); } @@ -20166,44 +20583,44 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 208 /* FunctionExpression */ || kind === 209 /* ArrowFunction */) { + if (kind === 209 /* FunctionExpression */ || kind === 210 /* ArrowFunction */) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. var updated = factory.updateCallExpression(emittedExpression, ts.setTextRange(factory.createParenthesizedExpression(callee), callee), emittedExpression.typeArguments, emittedExpression.arguments); return factory.restoreOuterExpressions(expression, updated, 8 /* PartiallyEmittedExpressions */); } } var leftmostExpressionKind = ts.getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; - if (leftmostExpressionKind === 200 /* ObjectLiteralExpression */ || leftmostExpressionKind === 208 /* FunctionExpression */) { + if (leftmostExpressionKind === 201 /* ObjectLiteralExpression */ || leftmostExpressionKind === 209 /* FunctionExpression */) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return ts.setTextRange(factory.createParenthesizedExpression(expression), expression); } return expression; } function parenthesizeConciseBodyOfArrowFunction(body) { - if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 200 /* ObjectLiteralExpression */)) { + if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 201 /* ObjectLiteralExpression */)) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. return ts.setTextRange(factory.createParenthesizedExpression(body), body); } return body; } function parenthesizeMemberOfConditionalType(member) { - return member.kind === 184 /* ConditionalType */ ? factory.createParenthesizedType(member) : member; + return member.kind === 185 /* ConditionalType */ ? factory.createParenthesizedType(member) : member; } function parenthesizeMemberOfElementType(member) { switch (member.kind) { - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return factory.createParenthesizedType(member); } return parenthesizeMemberOfConditionalType(member); } function parenthesizeElementTypeOfArrayType(member) { switch (member.kind) { - case 176 /* TypeQuery */: - case 188 /* TypeOperator */: - case 185 /* InferType */: + case 177 /* TypeQuery */: + case 189 /* TypeOperator */: + case 186 /* InferType */: return factory.createParenthesizedType(member); } return parenthesizeMemberOfElementType(member); @@ -20222,6 +20639,8 @@ var ts; } ts.createParenthesizerRules = createParenthesizerRules; ts.nullParenthesizerRules = { + getParenthesizeLeftSideOfBinaryForOperator: function (_) { return ts.identity; }, + getParenthesizeRightSideOfBinaryForOperator: function (_) { return ts.identity; }, parenthesizeLeftSideOfBinary: function (_binaryOperator, leftSide) { return leftSide; }, parenthesizeRightSideOfBinary: function (_binaryOperator, _leftSide, rightSide) { return rightSide; }, parenthesizeExpressionOfComputedPropertyName: ts.identity, @@ -20307,11 +20726,11 @@ var ts; } function convertToAssignmentPattern(node) { switch (node.kind) { - case 197 /* ArrayBindingPattern */: - case 199 /* ArrayLiteralExpression */: + case 198 /* ArrayBindingPattern */: + case 200 /* ArrayLiteralExpression */: return convertToArrayAssignmentPattern(node); - case 196 /* ObjectBindingPattern */: - case 200 /* ObjectLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 201 /* ObjectLiteralExpression */: return convertToObjectAssignmentPattern(node); } } @@ -20652,18 +21071,18 @@ var ts; createExternalModuleReference: createExternalModuleReference, updateExternalModuleReference: updateExternalModuleReference, // lazily load factory members for JSDoc types with similar structure - get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(303 /* JSDocAllType */); }, - get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(304 /* JSDocUnknownType */); }, - get createJSDocNonNullableType() { return getJSDocUnaryTypeCreateFunction(306 /* JSDocNonNullableType */); }, - get updateJSDocNonNullableType() { return getJSDocUnaryTypeUpdateFunction(306 /* JSDocNonNullableType */); }, - get createJSDocNullableType() { return getJSDocUnaryTypeCreateFunction(305 /* JSDocNullableType */); }, - get updateJSDocNullableType() { return getJSDocUnaryTypeUpdateFunction(305 /* JSDocNullableType */); }, - get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(307 /* JSDocOptionalType */); }, - get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(307 /* JSDocOptionalType */); }, - get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(309 /* JSDocVariadicType */); }, - get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(309 /* JSDocVariadicType */); }, - get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(310 /* JSDocNamepathType */); }, - get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(310 /* JSDocNamepathType */); }, + get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(304 /* JSDocAllType */); }, + get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(305 /* JSDocUnknownType */); }, + get createJSDocNonNullableType() { return getJSDocUnaryTypeCreateFunction(307 /* JSDocNonNullableType */); }, + get updateJSDocNonNullableType() { return getJSDocUnaryTypeUpdateFunction(307 /* JSDocNonNullableType */); }, + get createJSDocNullableType() { return getJSDocUnaryTypeCreateFunction(306 /* JSDocNullableType */); }, + get updateJSDocNullableType() { return getJSDocUnaryTypeUpdateFunction(306 /* JSDocNullableType */); }, + get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(308 /* JSDocOptionalType */); }, + get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(308 /* JSDocOptionalType */); }, + get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(310 /* JSDocVariadicType */); }, + get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(310 /* JSDocVariadicType */); }, + get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(311 /* JSDocNamepathType */); }, + get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(311 /* JSDocNamepathType */); }, createJSDocFunctionType: createJSDocFunctionType, updateJSDocFunctionType: updateJSDocFunctionType, createJSDocTypeLiteral: createJSDocTypeLiteral, @@ -20690,31 +21109,37 @@ var ts; updateJSDocSeeTag: updateJSDocSeeTag, createJSDocNameReference: createJSDocNameReference, updateJSDocNameReference: updateJSDocNameReference, + createJSDocLink: createJSDocLink, + updateJSDocLink: updateJSDocLink, // lazily load factory members for JSDoc tags with similar structure - get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(329 /* JSDocTypeTag */); }, - get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(329 /* JSDocTypeTag */); }, - get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(327 /* JSDocReturnTag */); }, - get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(327 /* JSDocReturnTag */); }, - get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(328 /* JSDocThisTag */); }, - get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(328 /* JSDocThisTag */); }, - get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(325 /* JSDocEnumTag */); }, - get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(325 /* JSDocEnumTag */); }, - get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(317 /* JSDocAuthorTag */); }, - get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(317 /* JSDocAuthorTag */); }, - get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(319 /* JSDocClassTag */); }, - get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(319 /* JSDocClassTag */); }, - get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(320 /* JSDocPublicTag */); }, - get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(320 /* JSDocPublicTag */); }, - get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(321 /* JSDocPrivateTag */); }, - get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(321 /* JSDocPrivateTag */); }, - get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(322 /* JSDocProtectedTag */); }, - get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(322 /* JSDocProtectedTag */); }, - get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(323 /* JSDocReadonlyTag */); }, - get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(323 /* JSDocReadonlyTag */); }, - get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(318 /* JSDocDeprecatedTag */); }, - get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(318 /* JSDocDeprecatedTag */); }, + get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(333 /* JSDocTypeTag */); }, + get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(333 /* JSDocTypeTag */); }, + get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(331 /* JSDocReturnTag */); }, + get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(331 /* JSDocReturnTag */); }, + get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(332 /* JSDocThisTag */); }, + get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(332 /* JSDocThisTag */); }, + get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(329 /* JSDocEnumTag */); }, + get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(329 /* JSDocEnumTag */); }, + get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(320 /* JSDocAuthorTag */); }, + get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(320 /* JSDocAuthorTag */); }, + get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(322 /* JSDocClassTag */); }, + get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(322 /* JSDocClassTag */); }, + get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(323 /* JSDocPublicTag */); }, + get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(323 /* JSDocPublicTag */); }, + get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(324 /* JSDocPrivateTag */); }, + get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(324 /* JSDocPrivateTag */); }, + get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(325 /* JSDocProtectedTag */); }, + get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(325 /* JSDocProtectedTag */); }, + get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(326 /* JSDocReadonlyTag */); }, + get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(326 /* JSDocReadonlyTag */); }, + get createJSDocOverrideTag() { return getJSDocSimpleTagCreateFunction(327 /* JSDocOverrideTag */); }, + get updateJSDocOverrideTag() { return getJSDocSimpleTagUpdateFunction(327 /* JSDocOverrideTag */); }, + get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(321 /* JSDocDeprecatedTag */); }, + get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(321 /* JSDocDeprecatedTag */); }, createJSDocUnknownTag: createJSDocUnknownTag, updateJSDocUnknownTag: updateJSDocUnknownTag, + createJSDocText: createJSDocText, + updateJSDocText: updateJSDocText, createJSDocComment: createJSDocComment, updateJSDocComment: updateJSDocComment, createJsxElement: createJsxElement, @@ -20898,11 +21323,11 @@ var ts; // don't propagate child flags. if (name) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 163 /* PropertyDeclaration */: - case 288 /* PropertyAssignment */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 289 /* PropertyAssignment */: if (ts.isIdentifier(name)) { node.transformFlags |= propagateIdentifierNameFlags(name); break; @@ -20943,7 +21368,7 @@ var ts; function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) { var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type); node.body = body; - node.transformFlags |= propagateChildFlags(node.body) & ~8388608 /* ContainsPossibleTopLevelAwait */; + node.transformFlags |= propagateChildFlags(node.body) & ~16777216 /* ContainsPossibleTopLevelAwait */; if (!body) node.transformFlags |= 1 /* ContainsTypeScript */; return node; @@ -20996,7 +21421,7 @@ var ts; var node = createBaseLiteral(8 /* NumericLiteral */, typeof value === "number" ? value + "" : value); node.numericLiteralFlags = numericLiteralFlags; if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -21015,7 +21440,7 @@ var ts; var node = createBaseStringLiteral(text, isSingleQuote); node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; if (hasExtendedUnicodeEscape) - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -21071,7 +21496,7 @@ var ts; node.typeArguments = createNodeArray(typeArguments); } if (node.originalKeywordKind === 130 /* AwaitKeyword */) { - node.transformFlags |= 8388608 /* ContainsPossibleTopLevelAwait */; + node.transformFlags |= 16777216 /* ContainsPossibleTopLevelAwait */; } return node; } @@ -21094,8 +21519,11 @@ var ts; } /** Create a unique temporary variable for use in a loop. */ // @api - function createLoopVariable() { - return createBaseGeneratedIdentifier("", 2 /* Loop */); + function createLoopVariable(reservedInNestedScopes) { + var flags = 2 /* Loop */; + if (reservedInNestedScopes) + flags |= 8 /* ReservedInNestedScopes */; + return createBaseGeneratedIdentifier("", flags); } /** Create a unique name based on the supplied text. */ // @api @@ -21120,7 +21548,7 @@ var ts; ts.Debug.fail("First character of private identifier must be #: " + text); var node = baseFactory.createBasePrivateIdentifierNode(79 /* PrivateIdentifier */); node.escapedText = ts.escapeLeadingUnderscores(text); - node.transformFlags |= 4194304 /* ContainsClassFields */; + node.transformFlags |= 8388608 /* ContainsClassFields */; return node; } // @@ -21130,7 +21558,7 @@ var ts; return baseFactory.createBaseTokenNode(kind); } function createToken(token) { - ts.Debug.assert(token >= 0 /* FirstToken */ && token <= 156 /* LastToken */, "Invalid token"); + ts.Debug.assert(token >= 0 /* FirstToken */ && token <= 157 /* LastToken */, "Invalid token"); ts.Debug.assert(token <= 14 /* FirstTemplateToken */ || token >= 17 /* LastTemplateToken */, "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals."); ts.Debug.assert(token <= 8 /* FirstLiteralToken */ || token >= 14 /* LastLiteralToken */, "Invalid token. Use 'createLiteralLikeNode' to create literals."); ts.Debug.assert(token !== 78 /* Identifier */, "Invalid token. Use 'createIdentifier' to create identifiers"); @@ -21140,8 +21568,8 @@ var ts; case 129 /* AsyncKeyword */: // 'async' modifier is ES2017 (async functions) or ES2018 (async generators) transformFlags = - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */; break; case 122 /* PublicKeyword */: case 120 /* PrivateKeyword */: @@ -21155,6 +21583,7 @@ var ts; case 155 /* BigIntKeyword */: case 141 /* NeverKeyword */: case 145 /* ObjectKeyword */: + case 156 /* OverrideKeyword */: case 147 /* StringKeyword */: case 131 /* BooleanKeyword */: case 148 /* SymbolKeyword */: @@ -21165,11 +21594,11 @@ var ts; break; case 123 /* StaticKeyword */: case 105 /* SuperKeyword */: - transformFlags = 256 /* ContainsES2015 */; + transformFlags = 512 /* ContainsES2015 */; break; case 107 /* ThisKeyword */: // 'this' indicates a lexical 'this' - transformFlags = 4096 /* ContainsLexicalThis */; + transformFlags = 8192 /* ContainsLexicalThis */; break; } if (transformFlags) { @@ -21237,6 +21666,9 @@ var ts; if (flags & 32 /* Static */) { result.push(createModifier(123 /* StaticKeyword */)); } + if (flags & 16384 /* Override */) { + result.push(createModifier(156 /* OverrideKeyword */)); + } if (flags & 64 /* Readonly */) { result.push(createModifier(142 /* ReadonlyKeyword */)); } @@ -21250,7 +21682,7 @@ var ts; // // @api function createQualifiedName(left, right) { - var node = createBaseNode(157 /* QualifiedName */); + var node = createBaseNode(158 /* QualifiedName */); node.left = left; node.right = asName(right); node.transformFlags |= @@ -21267,12 +21699,12 @@ var ts; } // @api function createComputedPropertyName(expression) { - var node = createBaseNode(158 /* ComputedPropertyName */); + var node = createBaseNode(159 /* ComputedPropertyName */); node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 256 /* ContainsES2015 */ | - 32768 /* ContainsComputedPropertyName */; + 512 /* ContainsES2015 */ | + 65536 /* ContainsComputedPropertyName */; return node; } // @api @@ -21286,7 +21718,7 @@ var ts; // // @api function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createBaseNamedDeclaration(159 /* TypeParameter */, + var node = createBaseNamedDeclaration(160 /* TypeParameter */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.constraint = constraint; @@ -21304,7 +21736,7 @@ var ts; } // @api function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(160 /* Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); + var node = createBaseVariableLikeDeclaration(161 /* Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.dotDotDotToken = dotDotDotToken; node.questionToken = questionToken; if (ts.isThisIdentifier(node.name)) { @@ -21316,10 +21748,10 @@ var ts; propagateChildFlags(node.questionToken); if (questionToken) node.transformFlags |= 1 /* ContainsTypeScript */; - if (ts.modifiersToFlags(node.modifiers) & 92 /* ParameterPropertyModifier */) - node.transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */; + if (ts.modifiersToFlags(node.modifiers) & 16476 /* ParameterPropertyModifier */) + node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; if (initializer || dotDotDotToken) - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; } return node; } @@ -21337,12 +21769,12 @@ var ts; } // @api function createDecorator(expression) { - var node = createBaseNode(161 /* Decorator */); + var node = createBaseNode(162 /* Decorator */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */ | - 2048 /* ContainsTypeScriptClassSyntax */; + 4096 /* ContainsTypeScriptClassSyntax */; return node; } // @api @@ -21356,7 +21788,7 @@ var ts; // // @api function createPropertySignature(modifiers, name, questionToken, type) { - var node = createBaseNamedDeclaration(162 /* PropertySignature */, + var node = createBaseNamedDeclaration(163 /* PropertySignature */, /*decorators*/ undefined, modifiers, name); node.type = type; node.questionToken = questionToken; @@ -21374,15 +21806,15 @@ var ts; } // @api function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(163 /* PropertyDeclaration */, decorators, modifiers, name, type, initializer); + var node = createBaseVariableLikeDeclaration(164 /* PropertyDeclaration */, decorators, modifiers, name, type, initializer); node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; node.transformFlags |= propagateChildFlags(node.questionToken) | propagateChildFlags(node.exclamationToken) | - 4194304 /* ContainsClassFields */; + 8388608 /* ContainsClassFields */; if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) { - node.transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */; + node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) { node.transformFlags |= 1 /* ContainsTypeScript */; @@ -21403,7 +21835,7 @@ var ts; } // @api function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(164 /* MethodSignature */, + var node = createBaseSignatureDeclaration(165 /* MethodSignature */, /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type); node.questionToken = questionToken; node.transformFlags = 1 /* ContainsTypeScript */; @@ -21422,26 +21854,26 @@ var ts; } // @api function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(165 /* MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(166 /* MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.questionToken = questionToken; node.transformFlags |= propagateChildFlags(node.asteriskToken) | propagateChildFlags(node.questionToken) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (questionToken) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (asteriskToken) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } else { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } } else if (asteriskToken) { - node.transformFlags |= 512 /* ContainsGenerator */; + node.transformFlags |= 1024 /* ContainsGenerator */; } return node; } @@ -21461,11 +21893,11 @@ var ts; } // @api function createConstructorDeclaration(decorators, modifiers, parameters, body) { - var node = createBaseFunctionLikeDeclaration(166 /* Constructor */, decorators, modifiers, + var node = createBaseFunctionLikeDeclaration(167 /* Constructor */, decorators, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -21479,7 +21911,7 @@ var ts; } // @api function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) { - return createBaseFunctionLikeDeclaration(167 /* GetAccessor */, decorators, modifiers, name, + return createBaseFunctionLikeDeclaration(168 /* GetAccessor */, decorators, modifiers, name, /*typeParameters*/ undefined, parameters, type, body); } // @api @@ -21495,7 +21927,7 @@ var ts; } // @api function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) { - return createBaseFunctionLikeDeclaration(168 /* SetAccessor */, decorators, modifiers, name, + return createBaseFunctionLikeDeclaration(169 /* SetAccessor */, decorators, modifiers, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); } @@ -21511,7 +21943,7 @@ var ts; } // @api function createCallSignature(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(169 /* CallSignature */, + var node = createBaseSignatureDeclaration(170 /* CallSignature */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); @@ -21528,7 +21960,7 @@ var ts; } // @api function createConstructSignature(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(170 /* ConstructSignature */, + var node = createBaseSignatureDeclaration(171 /* ConstructSignature */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); @@ -21545,7 +21977,7 @@ var ts; } // @api function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createBaseSignatureDeclaration(171 /* IndexSignature */, decorators, modifiers, + var node = createBaseSignatureDeclaration(172 /* IndexSignature */, decorators, modifiers, /*name*/ undefined, /*typeParameters*/ undefined, parameters, type); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21562,7 +21994,7 @@ var ts; } // @api function createTemplateLiteralTypeSpan(type, literal) { - var node = createBaseNode(194 /* TemplateLiteralTypeSpan */); + var node = createBaseNode(195 /* TemplateLiteralTypeSpan */); node.type = type; node.literal = literal; node.transformFlags = 1 /* ContainsTypeScript */; @@ -21584,7 +22016,7 @@ var ts; } // @api function createTypePredicateNode(assertsModifier, parameterName, type) { - var node = createBaseNode(172 /* TypePredicate */); + var node = createBaseNode(173 /* TypePredicate */); node.assertsModifier = assertsModifier; node.parameterName = asName(parameterName); node.type = type; @@ -21601,7 +22033,7 @@ var ts; } // @api function createTypeReferenceNode(typeName, typeArguments) { - var node = createBaseNode(173 /* TypeReference */); + var node = createBaseNode(174 /* TypeReference */); node.typeName = asName(typeName); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(createNodeArray(typeArguments)); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21616,7 +22048,7 @@ var ts; } // @api function createFunctionTypeNode(typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(174 /* FunctionType */, + var node = createBaseSignatureDeclaration(175 /* FunctionType */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, typeParameters, parameters, type); @@ -21642,7 +22074,7 @@ var ts; ts.Debug.fail("Incorrect number of arguments specified."); } function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) { - var node = createBaseSignatureDeclaration(175 /* ConstructorType */, + var node = createBaseSignatureDeclaration(176 /* ConstructorType */, /*decorators*/ undefined, modifiers, /*name*/ undefined, typeParameters, parameters, type); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21676,7 +22108,7 @@ var ts; } // @api function createTypeQueryNode(exprName) { - var node = createBaseNode(176 /* TypeQuery */); + var node = createBaseNode(177 /* TypeQuery */); node.exprName = exprName; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21689,7 +22121,7 @@ var ts; } // @api function createTypeLiteralNode(members) { - var node = createBaseNode(177 /* TypeLiteral */); + var node = createBaseNode(178 /* TypeLiteral */); node.members = createNodeArray(members); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21702,7 +22134,7 @@ var ts; } // @api function createArrayTypeNode(elementType) { - var node = createBaseNode(178 /* ArrayType */); + var node = createBaseNode(179 /* ArrayType */); node.elementType = parenthesizerRules().parenthesizeElementTypeOfArrayType(elementType); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21715,7 +22147,7 @@ var ts; } // @api function createTupleTypeNode(elements) { - var node = createBaseNode(179 /* TupleType */); + var node = createBaseNode(180 /* TupleType */); node.elements = createNodeArray(elements); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21728,7 +22160,7 @@ var ts; } // @api function createNamedTupleMember(dotDotDotToken, name, questionToken, type) { - var node = createBaseNode(192 /* NamedTupleMember */); + var node = createBaseNode(193 /* NamedTupleMember */); node.dotDotDotToken = dotDotDotToken; node.name = name; node.questionToken = questionToken; @@ -21747,7 +22179,7 @@ var ts; } // @api function createOptionalTypeNode(type) { - var node = createBaseNode(180 /* OptionalType */); + var node = createBaseNode(181 /* OptionalType */); node.type = parenthesizerRules().parenthesizeElementTypeOfArrayType(type); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21760,7 +22192,7 @@ var ts; } // @api function createRestTypeNode(type) { - var node = createBaseNode(181 /* RestType */); + var node = createBaseNode(182 /* RestType */); node.type = type; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21784,7 +22216,7 @@ var ts; } // @api function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(182 /* UnionType */, types); + return createUnionOrIntersectionTypeNode(183 /* UnionType */, types); } // @api function updateUnionTypeNode(node, types) { @@ -21792,7 +22224,7 @@ var ts; } // @api function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(183 /* IntersectionType */, types); + return createUnionOrIntersectionTypeNode(184 /* IntersectionType */, types); } // @api function updateIntersectionTypeNode(node, types) { @@ -21800,7 +22232,7 @@ var ts; } // @api function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { - var node = createBaseNode(184 /* ConditionalType */); + var node = createBaseNode(185 /* ConditionalType */); node.checkType = parenthesizerRules().parenthesizeMemberOfConditionalType(checkType); node.extendsType = parenthesizerRules().parenthesizeMemberOfConditionalType(extendsType); node.trueType = trueType; @@ -21819,7 +22251,7 @@ var ts; } // @api function createInferTypeNode(typeParameter) { - var node = createBaseNode(185 /* InferType */); + var node = createBaseNode(186 /* InferType */); node.typeParameter = typeParameter; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21832,7 +22264,7 @@ var ts; } // @api function createTemplateLiteralType(head, templateSpans) { - var node = createBaseNode(193 /* TemplateLiteralType */); + var node = createBaseNode(194 /* TemplateLiteralType */); node.head = head; node.templateSpans = createNodeArray(templateSpans); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21848,7 +22280,7 @@ var ts; // @api function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { if (isTypeOf === void 0) { isTypeOf = false; } - var node = createBaseNode(195 /* ImportType */); + var node = createBaseNode(196 /* ImportType */); node.argument = argument; node.qualifier = qualifier; node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); @@ -21868,7 +22300,7 @@ var ts; } // @api function createParenthesizedType(type) { - var node = createBaseNode(186 /* ParenthesizedType */); + var node = createBaseNode(187 /* ParenthesizedType */); node.type = type; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21881,13 +22313,13 @@ var ts; } // @api function createThisTypeNode() { - var node = createBaseNode(187 /* ThisType */); + var node = createBaseNode(188 /* ThisType */); node.transformFlags = 1 /* ContainsTypeScript */; return node; } // @api function createTypeOperatorNode(operator, type) { - var node = createBaseNode(188 /* TypeOperator */); + var node = createBaseNode(189 /* TypeOperator */); node.operator = operator; node.type = parenthesizerRules().parenthesizeMemberOfElementType(type); node.transformFlags = 1 /* ContainsTypeScript */; @@ -21901,7 +22333,7 @@ var ts; } // @api function createIndexedAccessTypeNode(objectType, indexType) { - var node = createBaseNode(189 /* IndexedAccessType */); + var node = createBaseNode(190 /* IndexedAccessType */); node.objectType = parenthesizerRules().parenthesizeMemberOfElementType(objectType); node.indexType = indexType; node.transformFlags = 1 /* ContainsTypeScript */; @@ -21916,7 +22348,7 @@ var ts; } // @api function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type) { - var node = createBaseNode(190 /* MappedType */); + var node = createBaseNode(191 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.nameType = nameType; @@ -21937,7 +22369,7 @@ var ts; } // @api function createLiteralTypeNode(literal) { - var node = createBaseNode(191 /* LiteralType */); + var node = createBaseNode(192 /* LiteralType */); node.literal = literal; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -21953,16 +22385,16 @@ var ts; // // @api function createObjectBindingPattern(elements) { - var node = createBaseNode(196 /* ObjectBindingPattern */); + var node = createBaseNode(197 /* ObjectBindingPattern */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | - 256 /* ContainsES2015 */ | - 131072 /* ContainsBindingPattern */; - if (node.transformFlags & 8192 /* ContainsRestOrSpread */) { + 512 /* ContainsES2015 */ | + 262144 /* ContainsBindingPattern */; + if (node.transformFlags & 16384 /* ContainsRestOrSpread */) { node.transformFlags |= - 32 /* ContainsES2018 */ | - 16384 /* ContainsObjectRestOrSpread */; + 64 /* ContainsES2018 */ | + 32768 /* ContainsObjectRestOrSpread */; } return node; } @@ -21974,12 +22406,12 @@ var ts; } // @api function createArrayBindingPattern(elements) { - var node = createBaseNode(197 /* ArrayBindingPattern */); + var node = createBaseNode(198 /* ArrayBindingPattern */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | - 256 /* ContainsES2015 */ | - 131072 /* ContainsBindingPattern */; + 512 /* ContainsES2015 */ | + 262144 /* ContainsBindingPattern */; return node; } // @api @@ -21990,21 +22422,21 @@ var ts; } // @api function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createBaseBindingLikeDeclaration(198 /* BindingElement */, + var node = createBaseBindingLikeDeclaration(199 /* BindingElement */, /*decorators*/ undefined, - /*modifiers*/ undefined, name, initializer); + /*modifiers*/ undefined, name, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; node.transformFlags |= propagateChildFlags(node.dotDotDotToken) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (node.propertyName) { node.transformFlags |= ts.isIdentifier(node.propertyName) ? propagateIdentifierNameFlags(node.propertyName) : propagateChildFlags(node.propertyName); } if (dotDotDotToken) - node.transformFlags |= 8192 /* ContainsRestOrSpread */; + node.transformFlags |= 16384 /* ContainsRestOrSpread */; return node; } // @api @@ -22026,7 +22458,7 @@ var ts; } // @api function createArrayLiteralExpression(elements, multiLine) { - var node = createBaseExpression(199 /* ArrayLiteralExpression */); + var node = createBaseExpression(200 /* ArrayLiteralExpression */); node.elements = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(elements)); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.elements); @@ -22040,7 +22472,7 @@ var ts; } // @api function createObjectLiteralExpression(properties, multiLine) { - var node = createBaseExpression(200 /* ObjectLiteralExpression */); + var node = createBaseExpression(201 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.properties); @@ -22054,7 +22486,7 @@ var ts; } // @api function createPropertyAccessExpression(expression, name) { - var node = createBaseExpression(201 /* PropertyAccessExpression */); + var node = createBaseExpression(202 /* PropertyAccessExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.name = asName(name); node.transformFlags = @@ -22066,8 +22498,8 @@ var ts; // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators node.transformFlags |= - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */; } return node; } @@ -22083,13 +22515,13 @@ var ts; } // @api function createPropertyAccessChain(expression, questionDotToken, name) { - var node = createBaseExpression(201 /* PropertyAccessExpression */); + var node = createBaseExpression(202 /* PropertyAccessExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.questionDotToken = questionDotToken; node.name = asName(name); node.transformFlags |= - 8 /* ContainsES2020 */ | + 16 /* ContainsES2020 */ | propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | (ts.isIdentifier(node.name) ? @@ -22110,7 +22542,7 @@ var ts; } // @api function createElementAccessExpression(expression, index) { - var node = createBaseExpression(202 /* ElementAccessExpression */); + var node = createBaseExpression(203 /* ElementAccessExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.argumentExpression = asExpression(index); node.transformFlags |= @@ -22120,8 +22552,8 @@ var ts; // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators node.transformFlags |= - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */; } return node; } @@ -22137,7 +22569,7 @@ var ts; } // @api function createElementAccessChain(expression, questionDotToken, index) { - var node = createBaseExpression(202 /* ElementAccessExpression */); + var node = createBaseExpression(203 /* ElementAccessExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.questionDotToken = questionDotToken; @@ -22146,7 +22578,7 @@ var ts; propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | propagateChildFlags(node.argumentExpression) | - 8 /* ContainsES2020 */; + 16 /* ContainsES2020 */; return node; } // @api @@ -22162,7 +22594,7 @@ var ts; } // @api function createCallExpression(expression, typeArguments, argumentsArray) { - var node = createBaseExpression(203 /* CallExpression */); + var node = createBaseExpression(204 /* CallExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)); @@ -22174,10 +22606,10 @@ var ts; node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.isImportKeyword(node.expression)) { - node.transformFlags |= 2097152 /* ContainsDynamicImport */; + node.transformFlags |= 4194304 /* ContainsDynamicImport */; } else if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 4096 /* ContainsLexicalThis */; + node.transformFlags |= 8192 /* ContainsLexicalThis */; } return node; } @@ -22194,7 +22626,7 @@ var ts; } // @api function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) { - var node = createBaseExpression(203 /* CallExpression */); + var node = createBaseExpression(204 /* CallExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.questionDotToken = questionDotToken; @@ -22205,12 +22637,12 @@ var ts; propagateChildFlags(node.questionDotToken) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | - 8 /* ContainsES2020 */; + 16 /* ContainsES2020 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.isSuperProperty(node.expression)) { - node.transformFlags |= 4096 /* ContainsLexicalThis */; + node.transformFlags |= 8192 /* ContainsLexicalThis */; } return node; } @@ -22226,7 +22658,7 @@ var ts; } // @api function createNewExpression(expression, typeArguments, argumentsArray) { - var node = createBaseExpression(204 /* NewExpression */); + var node = createBaseExpression(205 /* NewExpression */); node.expression = parenthesizerRules().parenthesizeExpressionOfNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(argumentsArray) : undefined; @@ -22234,7 +22666,7 @@ var ts; propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | - 8 /* ContainsES2020 */; + 16 /* ContainsES2020 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } @@ -22250,7 +22682,7 @@ var ts; } // @api function createTaggedTemplateExpression(tag, typeArguments, template) { - var node = createBaseExpression(205 /* TaggedTemplateExpression */); + var node = createBaseExpression(206 /* TaggedTemplateExpression */); node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag); node.typeArguments = asNodeArray(typeArguments); node.template = template; @@ -22258,12 +22690,12 @@ var ts; propagateChildFlags(node.tag) | propagateChildrenFlags(node.typeArguments) | propagateChildFlags(node.template) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.hasInvalidEscape(node.template)) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } return node; } @@ -22277,7 +22709,7 @@ var ts; } // @api function createTypeAssertion(type, expression) { - var node = createBaseExpression(206 /* TypeAssertionExpression */); + var node = createBaseExpression(207 /* TypeAssertionExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.type = type; node.transformFlags |= @@ -22295,7 +22727,7 @@ var ts; } // @api function createParenthesizedExpression(expression) { - var node = createBaseExpression(207 /* ParenthesizedExpression */); + var node = createBaseExpression(208 /* ParenthesizedExpression */); node.expression = expression; node.transformFlags = propagateChildFlags(node.expression); return node; @@ -22308,7 +22740,7 @@ var ts; } // @api function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(208 /* FunctionExpression */, + var node = createBaseFunctionLikeDeclaration(209 /* FunctionExpression */, /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.asteriskToken); @@ -22317,14 +22749,14 @@ var ts; } if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (node.asteriskToken) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } else { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } } else if (node.asteriskToken) { - node.transformFlags |= 512 /* ContainsGenerator */; + node.transformFlags |= 1024 /* ContainsGenerator */; } return node; } @@ -22342,15 +22774,15 @@ var ts; } // @api function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createBaseFunctionLikeDeclaration(209 /* ArrowFunction */, + var node = createBaseFunctionLikeDeclaration(210 /* ArrowFunction */, /*decorators*/ undefined, modifiers, /*name*/ undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body)); node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* EqualsGreaterThanToken */); node.transformFlags |= propagateChildFlags(node.equalsGreaterThanToken) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } return node; } @@ -22367,7 +22799,7 @@ var ts; } // @api function createDeleteExpression(expression) { - var node = createBaseExpression(210 /* DeleteExpression */); + var node = createBaseExpression(211 /* DeleteExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -22380,7 +22812,7 @@ var ts; } // @api function createTypeOfExpression(expression) { - var node = createBaseExpression(211 /* TypeOfExpression */); + var node = createBaseExpression(212 /* TypeOfExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -22393,7 +22825,7 @@ var ts; } // @api function createVoidExpression(expression) { - var node = createBaseExpression(212 /* VoidExpression */); + var node = createBaseExpression(213 /* VoidExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -22406,13 +22838,13 @@ var ts; } // @api function createAwaitExpression(expression) { - var node = createBaseExpression(213 /* AwaitExpression */); + var node = createBaseExpression(214 /* AwaitExpression */); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 64 /* ContainsES2017 */ | - 32 /* ContainsES2018 */ | - 524288 /* ContainsAwait */; + 128 /* ContainsES2017 */ | + 64 /* ContainsES2018 */ | + 1048576 /* ContainsAwait */; return node; } // @api @@ -22423,7 +22855,7 @@ var ts; } // @api function createPrefixUnaryExpression(operator, operand) { - var node = createBaseExpression(214 /* PrefixUnaryExpression */); + var node = createBaseExpression(215 /* PrefixUnaryExpression */); node.operator = operator; node.operand = parenthesizerRules().parenthesizeOperandOfPrefixUnary(operand); node.transformFlags |= propagateChildFlags(node.operand); @@ -22437,7 +22869,7 @@ var ts; } // @api function createPostfixUnaryExpression(operand, operator) { - var node = createBaseExpression(215 /* PostfixUnaryExpression */); + var node = createBaseExpression(216 /* PostfixUnaryExpression */); node.operator = operator; node.operand = parenthesizerRules().parenthesizeOperandOfPostfixUnary(operand); node.transformFlags = propagateChildFlags(node.operand); @@ -22451,7 +22883,7 @@ var ts; } // @api function createBinaryExpression(left, operator, right) { - var node = createBaseExpression(216 /* BinaryExpression */); + var node = createBaseExpression(217 /* BinaryExpression */); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = parenthesizerRules().parenthesizeLeftSideOfBinary(operatorKind, left); @@ -22462,45 +22894,45 @@ var ts; propagateChildFlags(node.operatorToken) | propagateChildFlags(node.right); if (operatorKind === 60 /* QuestionQuestionToken */) { - node.transformFlags |= 8 /* ContainsES2020 */; + node.transformFlags |= 16 /* ContainsES2020 */; } else if (operatorKind === 62 /* EqualsToken */) { if (ts.isObjectLiteralExpression(node.left)) { node.transformFlags |= - 256 /* ContainsES2015 */ | - 32 /* ContainsES2018 */ | - 1024 /* ContainsDestructuringAssignment */ | + 512 /* ContainsES2015 */ | + 64 /* ContainsES2018 */ | + 2048 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left); } else if (ts.isArrayLiteralExpression(node.left)) { node.transformFlags |= - 256 /* ContainsES2015 */ | - 1024 /* ContainsDestructuringAssignment */ | + 512 /* ContainsES2015 */ | + 2048 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left); } } else if (operatorKind === 42 /* AsteriskAsteriskToken */ || operatorKind === 66 /* AsteriskAsteriskEqualsToken */) { - node.transformFlags |= 128 /* ContainsES2016 */; + node.transformFlags |= 256 /* ContainsES2016 */; } else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) { - node.transformFlags |= 4 /* ContainsESNext */; + node.transformFlags |= 8 /* ContainsES2021 */; } return node; } function propagateAssignmentPatternFlags(node) { - if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) - return 16384 /* ContainsObjectRestOrSpread */; - if (node.transformFlags & 32 /* ContainsES2018 */) { + if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) + return 32768 /* ContainsObjectRestOrSpread */; + if (node.transformFlags & 64 /* ContainsES2018 */) { // check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c' // will not be correctly interpreted by the ES2018 transformer for (var _i = 0, _a = ts.getElementsOfBindingOrAssignmentPattern(node); _i < _a.length; _i++) { var element = _a[_i]; var target = ts.getTargetOfBindingOrAssignmentElement(element); if (target && ts.isAssignmentPattern(target)) { - if (target.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { - return 16384 /* ContainsObjectRestOrSpread */; + if (target.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { + return 32768 /* ContainsObjectRestOrSpread */; } - if (target.transformFlags & 32 /* ContainsES2018 */) { + if (target.transformFlags & 64 /* ContainsES2018 */) { var flags_1 = propagateAssignmentPatternFlags(target); if (flags_1) return flags_1; @@ -22520,7 +22952,7 @@ var ts; } // @api function createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse) { - var node = createBaseExpression(217 /* ConditionalExpression */); + var node = createBaseExpression(218 /* ConditionalExpression */); node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression(condition); node.questionToken = questionToken !== null && questionToken !== void 0 ? questionToken : createToken(57 /* QuestionToken */); node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue); @@ -22546,13 +22978,13 @@ var ts; } // @api function createTemplateExpression(head, templateSpans) { - var node = createBaseExpression(218 /* TemplateExpression */); + var node = createBaseExpression(219 /* TemplateExpression */); node.head = head; node.templateSpans = createNodeArray(templateSpans); node.transformFlags |= propagateChildFlags(node.head) | propagateChildrenFlags(node.templateSpans) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } // @api @@ -22591,9 +23023,9 @@ var ts; node.text = text; node.rawText = rawText; node.templateFlags = templateFlags & 2048 /* TemplateLiteralLikeFlags */; - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; if (node.templateFlags) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } return node; } @@ -22616,15 +23048,15 @@ var ts; // @api function createYieldExpression(asteriskToken, expression) { ts.Debug.assert(!asteriskToken || !!expression, "A `YieldExpression` with an asteriskToken must have an expression."); - var node = createBaseExpression(219 /* YieldExpression */); + var node = createBaseExpression(220 /* YieldExpression */); node.expression = expression && parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.asteriskToken) | - 256 /* ContainsES2015 */ | - 32 /* ContainsES2018 */ | - 262144 /* ContainsYield */; + 512 /* ContainsES2015 */ | + 64 /* ContainsES2018 */ | + 524288 /* ContainsYield */; return node; } // @api @@ -22636,12 +23068,12 @@ var ts; } // @api function createSpreadElement(expression) { - var node = createBaseExpression(220 /* SpreadElement */); + var node = createBaseExpression(221 /* SpreadElement */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 256 /* ContainsES2015 */ | - 8192 /* ContainsRestOrSpread */; + 512 /* ContainsES2015 */ | + 16384 /* ContainsRestOrSpread */; return node; } // @api @@ -22652,8 +23084,8 @@ var ts; } // @api function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(221 /* ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members); - node.transformFlags |= 256 /* ContainsES2015 */; + var node = createBaseClassLikeDeclaration(222 /* ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members); + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @api @@ -22669,17 +23101,17 @@ var ts; } // @api function createOmittedExpression() { - return createBaseExpression(222 /* OmittedExpression */); + return createBaseExpression(223 /* OmittedExpression */); } // @api function createExpressionWithTypeArguments(expression, typeArguments) { - var node = createBaseNode(223 /* ExpressionWithTypeArguments */); + var node = createBaseNode(224 /* ExpressionWithTypeArguments */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } // @api @@ -22691,7 +23123,7 @@ var ts; } // @api function createAsExpression(expression, type) { - var node = createBaseExpression(224 /* AsExpression */); + var node = createBaseExpression(225 /* AsExpression */); node.expression = expression; node.type = type; node.transformFlags |= @@ -22709,7 +23141,7 @@ var ts; } // @api function createNonNullExpression(expression) { - var node = createBaseExpression(225 /* NonNullExpression */); + var node = createBaseExpression(226 /* NonNullExpression */); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.transformFlags |= propagateChildFlags(node.expression) | @@ -22727,7 +23159,7 @@ var ts; } // @api function createNonNullChain(expression) { - var node = createBaseExpression(225 /* NonNullExpression */); + var node = createBaseExpression(226 /* NonNullExpression */); node.flags |= 32 /* OptionalChain */; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression); node.transformFlags |= @@ -22744,13 +23176,13 @@ var ts; } // @api function createMetaProperty(keywordToken, name) { - var node = createBaseExpression(226 /* MetaProperty */); + var node = createBaseExpression(227 /* MetaProperty */); node.keywordToken = keywordToken; node.name = name; node.transformFlags |= propagateChildFlags(node.name); switch (keywordToken) { case 102 /* NewKeyword */: - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; break; case 99 /* ImportKeyword */: node.transformFlags |= 4 /* ContainsESNext */; @@ -22771,13 +23203,13 @@ var ts; // // @api function createTemplateSpan(expression, literal) { - var node = createBaseNode(228 /* TemplateSpan */); + var node = createBaseNode(229 /* TemplateSpan */); node.expression = expression; node.literal = literal; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.literal) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } // @api @@ -22789,8 +23221,8 @@ var ts; } // @api function createSemicolonClassElement() { - var node = createBaseNode(229 /* SemicolonClassElement */); - node.transformFlags |= 256 /* ContainsES2015 */; + var node = createBaseNode(230 /* SemicolonClassElement */); + node.transformFlags |= 512 /* ContainsES2015 */; return node; } // @@ -22798,7 +23230,7 @@ var ts; // // @api function createBlock(statements, multiLine) { - var node = createBaseNode(230 /* Block */); + var node = createBaseNode(231 /* Block */); node.statements = createNodeArray(statements); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.statements); @@ -22812,7 +23244,7 @@ var ts; } // @api function createVariableStatement(modifiers, declarationList) { - var node = createBaseDeclaration(232 /* VariableStatement */, /*decorators*/ undefined, modifiers); + var node = createBaseDeclaration(233 /* VariableStatement */, /*decorators*/ undefined, modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; node.transformFlags |= propagateChildFlags(node.declarationList); @@ -22830,11 +23262,11 @@ var ts; } // @api function createEmptyStatement() { - return createBaseNode(231 /* EmptyStatement */); + return createBaseNode(232 /* EmptyStatement */); } // @api function createExpressionStatement(expression) { - var node = createBaseNode(233 /* ExpressionStatement */); + var node = createBaseNode(234 /* ExpressionStatement */); node.expression = parenthesizerRules().parenthesizeExpressionOfExpressionStatement(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -22847,7 +23279,7 @@ var ts; } // @api function createIfStatement(expression, thenStatement, elseStatement) { - var node = createBaseNode(234 /* IfStatement */); + var node = createBaseNode(235 /* IfStatement */); node.expression = expression; node.thenStatement = asEmbeddedStatement(thenStatement); node.elseStatement = asEmbeddedStatement(elseStatement); @@ -22867,7 +23299,7 @@ var ts; } // @api function createDoStatement(statement, expression) { - var node = createBaseNode(235 /* DoStatement */); + var node = createBaseNode(236 /* DoStatement */); node.statement = asEmbeddedStatement(statement); node.expression = expression; node.transformFlags |= @@ -22884,7 +23316,7 @@ var ts; } // @api function createWhileStatement(expression, statement) { - var node = createBaseNode(236 /* WhileStatement */); + var node = createBaseNode(237 /* WhileStatement */); node.expression = expression; node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -22901,7 +23333,7 @@ var ts; } // @api function createForStatement(initializer, condition, incrementor, statement) { - var node = createBaseNode(237 /* ForStatement */); + var node = createBaseNode(238 /* ForStatement */); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -22924,7 +23356,7 @@ var ts; } // @api function createForInStatement(initializer, expression, statement) { - var node = createBaseNode(238 /* ForInStatement */); + var node = createBaseNode(239 /* ForInStatement */); node.initializer = initializer; node.expression = expression; node.statement = asEmbeddedStatement(statement); @@ -22944,7 +23376,7 @@ var ts; } // @api function createForOfStatement(awaitModifier, initializer, expression, statement) { - var node = createBaseNode(239 /* ForOfStatement */); + var node = createBaseNode(240 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); @@ -22954,9 +23386,9 @@ var ts; propagateChildFlags(node.initializer) | propagateChildFlags(node.expression) | propagateChildFlags(node.statement) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; if (awaitModifier) - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; return node; } // @api @@ -22970,11 +23402,11 @@ var ts; } // @api function createContinueStatement(label) { - var node = createBaseNode(240 /* ContinueStatement */); + var node = createBaseNode(241 /* ContinueStatement */); node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -22985,11 +23417,11 @@ var ts; } // @api function createBreakStatement(label) { - var node = createBaseNode(241 /* BreakStatement */); + var node = createBaseNode(242 /* BreakStatement */); node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -23000,13 +23432,13 @@ var ts; } // @api function createReturnStatement(expression) { - var node = createBaseNode(242 /* ReturnStatement */); + var node = createBaseNode(243 /* ReturnStatement */); node.expression = expression; // return in an ES2018 async generator must be awaited node.transformFlags |= propagateChildFlags(node.expression) | - 32 /* ContainsES2018 */ | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 64 /* ContainsES2018 */ | + 2097152 /* ContainsHoistedDeclarationOrCompletion */; return node; } // @api @@ -23017,7 +23449,7 @@ var ts; } // @api function createWithStatement(expression, statement) { - var node = createBaseNode(243 /* WithStatement */); + var node = createBaseNode(244 /* WithStatement */); node.expression = expression; node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -23034,7 +23466,7 @@ var ts; } // @api function createSwitchStatement(expression, caseBlock) { - var node = createBaseNode(244 /* SwitchStatement */); + var node = createBaseNode(245 /* SwitchStatement */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.caseBlock = caseBlock; node.transformFlags |= @@ -23051,7 +23483,7 @@ var ts; } // @api function createLabeledStatement(label, statement) { - var node = createBaseNode(245 /* LabeledStatement */); + var node = createBaseNode(246 /* LabeledStatement */); node.label = asName(label); node.statement = asEmbeddedStatement(statement); node.transformFlags |= @@ -23068,7 +23500,7 @@ var ts; } // @api function createThrowStatement(expression) { - var node = createBaseNode(246 /* ThrowStatement */); + var node = createBaseNode(247 /* ThrowStatement */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); return node; @@ -23081,7 +23513,7 @@ var ts; } // @api function createTryStatement(tryBlock, catchClause, finallyBlock) { - var node = createBaseNode(247 /* TryStatement */); + var node = createBaseNode(248 /* TryStatement */); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -23101,11 +23533,11 @@ var ts; } // @api function createDebuggerStatement() { - return createBaseNode(248 /* DebuggerStatement */); + return createBaseNode(249 /* DebuggerStatement */); } // @api function createVariableDeclaration(name, exclamationToken, type, initializer) { - var node = createBaseVariableLikeDeclaration(249 /* VariableDeclaration */, + var node = createBaseVariableLikeDeclaration(250 /* VariableDeclaration */, /*decorators*/ undefined, /*modifiers*/ undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer)); node.exclamationToken = exclamationToken; @@ -23127,16 +23559,16 @@ var ts; // @api function createVariableDeclarationList(declarations, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createBaseNode(250 /* VariableDeclarationList */); + var node = createBaseNode(251 /* VariableDeclarationList */); node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); node.transformFlags |= propagateChildrenFlags(node.declarations) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; if (flags & 3 /* BlockScoped */) { node.transformFlags |= - 256 /* ContainsES2015 */ | - 65536 /* ContainsBlockScopedBinding */; + 512 /* ContainsES2015 */ | + 131072 /* ContainsBlockScopedBinding */; } return node; } @@ -23148,7 +23580,7 @@ var ts; } // @api function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createBaseFunctionLikeDeclaration(251 /* FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); + var node = createBaseFunctionLikeDeclaration(252 /* FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body); node.asteriskToken = asteriskToken; if (!node.body || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) { node.transformFlags = 1 /* ContainsTypeScript */; @@ -23156,17 +23588,17 @@ var ts; else { node.transformFlags |= propagateChildFlags(node.asteriskToken) | - 1048576 /* ContainsHoistedDeclarationOrCompletion */; + 2097152 /* ContainsHoistedDeclarationOrCompletion */; if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (node.asteriskToken) { - node.transformFlags |= 32 /* ContainsES2018 */; + node.transformFlags |= 64 /* ContainsES2018 */; } else { - node.transformFlags |= 64 /* ContainsES2017 */; + node.transformFlags |= 128 /* ContainsES2017 */; } } else if (node.asteriskToken) { - node.transformFlags |= 512 /* ContainsGenerator */; + node.transformFlags |= 1024 /* ContainsGenerator */; } } return node; @@ -23186,13 +23618,13 @@ var ts; } // @api function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseClassLikeDeclaration(252 /* ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members); + var node = createBaseClassLikeDeclaration(253 /* ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members); if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) { node.transformFlags = 1 /* ContainsTypeScript */; } else { - node.transformFlags |= 256 /* ContainsES2015 */; - if (node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */) { + node.transformFlags |= 512 /* ContainsES2015 */; + if (node.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */) { node.transformFlags |= 1 /* ContainsTypeScript */; } } @@ -23211,7 +23643,7 @@ var ts; } // @api function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createBaseInterfaceOrClassLikeDeclaration(253 /* InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses); + var node = createBaseInterfaceOrClassLikeDeclaration(254 /* InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses); node.members = createNodeArray(members); node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -23229,7 +23661,7 @@ var ts; } // @api function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createBaseGenericNamedDeclaration(254 /* TypeAliasDeclaration */, decorators, modifiers, name, typeParameters); + var node = createBaseGenericNamedDeclaration(255 /* TypeAliasDeclaration */, decorators, modifiers, name, typeParameters); node.type = type; node.transformFlags = 1 /* ContainsTypeScript */; return node; @@ -23246,12 +23678,12 @@ var ts; } // @api function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createBaseNamedDeclaration(255 /* EnumDeclaration */, decorators, modifiers, name); + var node = createBaseNamedDeclaration(256 /* EnumDeclaration */, decorators, modifiers, name); node.members = createNodeArray(members); node.transformFlags |= propagateChildrenFlags(node.members) | 1 /* ContainsTypeScript */; - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await` return node; } // @api @@ -23266,7 +23698,7 @@ var ts; // @api function createModuleDeclaration(decorators, modifiers, name, body, flags) { if (flags === void 0) { flags = 0 /* None */; } - var node = createBaseDeclaration(256 /* ModuleDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(257 /* ModuleDeclaration */, decorators, modifiers); node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 1024 /* GlobalAugmentation */); node.name = name; node.body = body; @@ -23279,7 +23711,7 @@ var ts; propagateChildFlags(node.body) | 1 /* ContainsTypeScript */; } - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`. return node; } // @api @@ -23293,7 +23725,7 @@ var ts; } // @api function createModuleBlock(statements) { - var node = createBaseNode(257 /* ModuleBlock */); + var node = createBaseNode(258 /* ModuleBlock */); node.statements = createNodeArray(statements); node.transformFlags |= propagateChildrenFlags(node.statements); return node; @@ -23306,7 +23738,7 @@ var ts; } // @api function createCaseBlock(clauses) { - var node = createBaseNode(258 /* CaseBlock */); + var node = createBaseNode(259 /* CaseBlock */); node.clauses = createNodeArray(clauses); node.transformFlags |= propagateChildrenFlags(node.clauses); return node; @@ -23319,7 +23751,7 @@ var ts; } // @api function createNamespaceExportDeclaration(name) { - var node = createBaseNamedDeclaration(259 /* NamespaceExportDeclaration */, + var node = createBaseNamedDeclaration(260 /* NamespaceExportDeclaration */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.transformFlags = 1 /* ContainsTypeScript */; @@ -23333,13 +23765,13 @@ var ts; } // @api function createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference) { - var node = createBaseNamedDeclaration(260 /* ImportEqualsDeclaration */, decorators, modifiers, name); + var node = createBaseNamedDeclaration(261 /* ImportEqualsDeclaration */, decorators, modifiers, name); node.isTypeOnly = isTypeOnly; node.moduleReference = moduleReference; node.transformFlags |= propagateChildFlags(node.moduleReference); if (!ts.isExternalModuleReference(node.moduleReference)) node.transformFlags |= 1 /* ContainsTypeScript */; - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context return node; } // @api @@ -23354,13 +23786,13 @@ var ts; } // @api function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createBaseDeclaration(261 /* ImportDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(262 /* ImportDeclaration */, decorators, modifiers); node.importClause = importClause; node.moduleSpecifier = moduleSpecifier; node.transformFlags |= propagateChildFlags(node.importClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23374,7 +23806,7 @@ var ts; } // @api function createImportClause(isTypeOnly, name, namedBindings) { - var node = createBaseNode(262 /* ImportClause */); + var node = createBaseNode(263 /* ImportClause */); node.isTypeOnly = isTypeOnly; node.name = name; node.namedBindings = namedBindings; @@ -23384,7 +23816,7 @@ var ts; if (isTypeOnly) { node.transformFlags |= 1 /* ContainsTypeScript */; } - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23397,10 +23829,10 @@ var ts; } // @api function createNamespaceImport(name) { - var node = createBaseNode(263 /* NamespaceImport */); + var node = createBaseNode(264 /* NamespaceImport */); node.name = name; node.transformFlags |= propagateChildFlags(node.name); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23411,12 +23843,12 @@ var ts; } // @api function createNamespaceExport(name) { - var node = createBaseNode(269 /* NamespaceExport */); + var node = createBaseNode(270 /* NamespaceExport */); node.name = name; node.transformFlags |= propagateChildFlags(node.name) | 4 /* ContainsESNext */; - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23427,10 +23859,10 @@ var ts; } // @api function createNamedImports(elements) { - var node = createBaseNode(264 /* NamedImports */); + var node = createBaseNode(265 /* NamedImports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23441,13 +23873,13 @@ var ts; } // @api function createImportSpecifier(propertyName, name) { - var node = createBaseNode(265 /* ImportSpecifier */); + var node = createBaseNode(266 /* ImportSpecifier */); node.propertyName = propertyName; node.name = name; node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23459,13 +23891,13 @@ var ts; } // @api function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createBaseDeclaration(266 /* ExportAssignment */, decorators, modifiers); + var node = createBaseDeclaration(267 /* ExportAssignment */, decorators, modifiers); node.isExportEquals = isExportEquals; node.expression = isExportEquals ? parenthesizerRules().parenthesizeRightSideOfBinary(62 /* EqualsToken */, /*leftSide*/ undefined, expression) : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23478,14 +23910,14 @@ var ts; } // @api function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier) { - var node = createBaseDeclaration(267 /* ExportDeclaration */, decorators, modifiers); + var node = createBaseDeclaration(268 /* ExportDeclaration */, decorators, modifiers); node.isTypeOnly = isTypeOnly; node.exportClause = exportClause; node.moduleSpecifier = moduleSpecifier; node.transformFlags |= propagateChildFlags(node.exportClause) | propagateChildFlags(node.moduleSpecifier); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23500,10 +23932,10 @@ var ts; } // @api function createNamedExports(elements) { - var node = createBaseNode(268 /* NamedExports */); + var node = createBaseNode(269 /* NamedExports */); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23514,13 +23946,13 @@ var ts; } // @api function createExportSpecifier(propertyName, name) { - var node = createBaseNode(270 /* ExportSpecifier */); + var node = createBaseNode(271 /* ExportSpecifier */); node.propertyName = asName(propertyName); node.name = asName(name); node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23532,7 +23964,7 @@ var ts; } // @api function createMissingDeclaration() { - var node = createBaseDeclaration(271 /* MissingDeclaration */, + var node = createBaseDeclaration(272 /* MissingDeclaration */, /*decorators*/ undefined, /*modifiers*/ undefined); return node; @@ -23542,10 +23974,10 @@ var ts; // // @api function createExternalModuleReference(expression) { - var node = createBaseNode(272 /* ExternalModuleReference */); + var node = createBaseNode(273 /* ExternalModuleReference */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); - node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context + node.transformFlags &= ~16777216 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context return node; } // @api @@ -23587,7 +24019,7 @@ var ts; } // @api function createJSDocFunctionType(parameters, type) { - var node = createBaseSignatureDeclaration(308 /* JSDocFunctionType */, + var node = createBaseSignatureDeclaration(309 /* JSDocFunctionType */, /*decorators*/ undefined, /*modifiers*/ undefined, /*name*/ undefined, @@ -23604,7 +24036,7 @@ var ts; // @api function createJSDocTypeLiteral(propertyTags, isArrayType) { if (isArrayType === void 0) { isArrayType = false; } - var node = createBaseNode(312 /* JSDocTypeLiteral */); + var node = createBaseNode(314 /* JSDocTypeLiteral */); node.jsDocPropertyTags = asNodeArray(propertyTags); node.isArrayType = isArrayType; return node; @@ -23618,7 +24050,7 @@ var ts; } // @api function createJSDocTypeExpression(type) { - var node = createBaseNode(301 /* JSDocTypeExpression */); + var node = createBaseNode(302 /* JSDocTypeExpression */); node.type = type; return node; } @@ -23630,7 +24062,7 @@ var ts; } // @api function createJSDocSignature(typeParameters, parameters, type) { - var node = createBaseNode(313 /* JSDocSignature */); + var node = createBaseNode(315 /* JSDocSignature */); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; @@ -23659,7 +24091,7 @@ var ts; } // @api function createJSDocTemplateTag(tagName, constraint, typeParameters, comment) { - var node = createBaseJSDocTag(330 /* JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment); + var node = createBaseJSDocTag(334 /* JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment); node.constraint = constraint; node.typeParameters = createNodeArray(typeParameters); return node; @@ -23676,7 +24108,7 @@ var ts; } // @api function createJSDocTypedefTag(tagName, typeExpression, fullName, comment) { - var node = createBaseJSDocTag(331 /* JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment); + var node = createBaseJSDocTag(335 /* JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment); node.typeExpression = typeExpression; node.fullName = fullName; node.name = ts.getJSDocTypeAliasName(fullName); @@ -23694,7 +24126,7 @@ var ts; } // @api function createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { - var node = createBaseJSDocTag(326 /* JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment); + var node = createBaseJSDocTag(330 /* JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -23715,7 +24147,7 @@ var ts; } // @api function createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) { - var node = createBaseJSDocTag(333 /* JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment); + var node = createBaseJSDocTag(337 /* JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -23736,7 +24168,7 @@ var ts; } // @api function createJSDocCallbackTag(tagName, typeExpression, fullName, comment) { - var node = createBaseJSDocTag(324 /* JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment); + var node = createBaseJSDocTag(328 /* JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment); node.typeExpression = typeExpression; node.fullName = fullName; node.name = ts.getJSDocTypeAliasName(fullName); @@ -23754,7 +24186,7 @@ var ts; } // @api function createJSDocAugmentsTag(tagName, className, comment) { - var node = createBaseJSDocTag(315 /* JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment); + var node = createBaseJSDocTag(318 /* JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment); node.class = className; return node; } @@ -23769,13 +24201,13 @@ var ts; } // @api function createJSDocImplementsTag(tagName, className, comment) { - var node = createBaseJSDocTag(316 /* JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment); + var node = createBaseJSDocTag(319 /* JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment); node.class = className; return node; } // @api function createJSDocSeeTag(tagName, name, comment) { - var node = createBaseJSDocTag(332 /* JSDocSeeTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment); + var node = createBaseJSDocTag(336 /* JSDocSeeTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment); node.name = name; return node; } @@ -23789,7 +24221,7 @@ var ts; } // @api function createJSDocNameReference(name) { - var node = createBaseNode(302 /* JSDocNameReference */); + var node = createBaseNode(303 /* JSDocNameReference */); node.name = name; return node; } @@ -23800,6 +24232,19 @@ var ts; : node; } // @api + function createJSDocLink(name, text) { + var node = createBaseNode(316 /* JSDocLink */); + node.name = name; + node.text = text; + return node; + } + // @api + function updateJSDocLink(node, name, text) { + return node.name !== name + ? update(createJSDocLink(name, text), node) + : node; + } + // @api function updateJSDocImplementsTag(node, tagName, className, comment) { if (tagName === void 0) { tagName = getDefaultTagName(node); } return node.tagName !== tagName @@ -23860,7 +24305,7 @@ var ts; } // @api function createJSDocUnknownTag(tagName, comment) { - var node = createBaseJSDocTag(314 /* JSDocTag */, tagName, comment); + var node = createBaseJSDocTag(317 /* JSDocTag */, tagName, comment); return node; } // @api @@ -23871,8 +24316,20 @@ var ts; : node; } // @api + function createJSDocText(text) { + var node = createBaseNode(313 /* JSDocText */); + node.text = text; + return node; + } + // @api + function updateJSDocText(node, text) { + return node.text !== text + ? update(createJSDocText(text), node) + : node; + } + // @api function createJSDocComment(comment, tags) { - var node = createBaseNode(311 /* JSDocComment */); + var node = createBaseNode(312 /* JSDocComment */); node.comment = comment; node.tags = asNodeArray(tags); return node; @@ -23889,7 +24346,7 @@ var ts; // // @api function createJsxElement(openingElement, children, closingElement) { - var node = createBaseNode(273 /* JsxElement */); + var node = createBaseNode(274 /* JsxElement */); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -23910,7 +24367,7 @@ var ts; } // @api function createJsxSelfClosingElement(tagName, typeArguments, attributes) { - var node = createBaseNode(274 /* JsxSelfClosingElement */); + var node = createBaseNode(275 /* JsxSelfClosingElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -23934,7 +24391,7 @@ var ts; } // @api function createJsxOpeningElement(tagName, typeArguments, attributes) { - var node = createBaseNode(275 /* JsxOpeningElement */); + var node = createBaseNode(276 /* JsxOpeningElement */); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -23958,7 +24415,7 @@ var ts; } // @api function createJsxClosingElement(tagName) { - var node = createBaseNode(276 /* JsxClosingElement */); + var node = createBaseNode(277 /* JsxClosingElement */); node.tagName = tagName; node.transformFlags |= propagateChildFlags(node.tagName) | @@ -23973,7 +24430,7 @@ var ts; } // @api function createJsxFragment(openingFragment, children, closingFragment) { - var node = createBaseNode(277 /* JsxFragment */); + var node = createBaseNode(278 /* JsxFragment */); node.openingFragment = openingFragment; node.children = createNodeArray(children); node.closingFragment = closingFragment; @@ -24009,19 +24466,19 @@ var ts; } // @api function createJsxOpeningFragment() { - var node = createBaseNode(278 /* JsxOpeningFragment */); + var node = createBaseNode(279 /* JsxOpeningFragment */); node.transformFlags |= 2 /* ContainsJsx */; return node; } // @api function createJsxJsxClosingFragment() { - var node = createBaseNode(279 /* JsxClosingFragment */); + var node = createBaseNode(280 /* JsxClosingFragment */); node.transformFlags |= 2 /* ContainsJsx */; return node; } // @api function createJsxAttribute(name, initializer) { - var node = createBaseNode(280 /* JsxAttribute */); + var node = createBaseNode(281 /* JsxAttribute */); node.name = name; node.initializer = initializer; node.transformFlags |= @@ -24039,7 +24496,7 @@ var ts; } // @api function createJsxAttributes(properties) { - var node = createBaseNode(281 /* JsxAttributes */); + var node = createBaseNode(282 /* JsxAttributes */); node.properties = createNodeArray(properties); node.transformFlags |= propagateChildrenFlags(node.properties) | @@ -24054,7 +24511,7 @@ var ts; } // @api function createJsxSpreadAttribute(expression) { - var node = createBaseNode(282 /* JsxSpreadAttribute */); + var node = createBaseNode(283 /* JsxSpreadAttribute */); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression) | @@ -24069,7 +24526,7 @@ var ts; } // @api function createJsxExpression(dotDotDotToken, expression) { - var node = createBaseNode(283 /* JsxExpression */); + var node = createBaseNode(284 /* JsxExpression */); node.dotDotDotToken = dotDotDotToken; node.expression = expression; node.transformFlags |= @@ -24089,7 +24546,7 @@ var ts; // // @api function createCaseClause(expression, statements) { - var node = createBaseNode(284 /* CaseClause */); + var node = createBaseNode(285 /* CaseClause */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.statements = createNodeArray(statements); node.transformFlags |= @@ -24106,7 +24563,7 @@ var ts; } // @api function createDefaultClause(statements) { - var node = createBaseNode(285 /* DefaultClause */); + var node = createBaseNode(286 /* DefaultClause */); node.statements = createNodeArray(statements); node.transformFlags = propagateChildrenFlags(node.statements); return node; @@ -24119,13 +24576,13 @@ var ts; } // @api function createHeritageClause(token, types) { - var node = createBaseNode(286 /* HeritageClause */); + var node = createBaseNode(287 /* HeritageClause */); node.token = token; node.types = createNodeArray(types); node.transformFlags |= propagateChildrenFlags(node.types); switch (token) { case 93 /* ExtendsKeyword */: - node.transformFlags |= 256 /* ContainsES2015 */; + node.transformFlags |= 512 /* ContainsES2015 */; break; case 116 /* ImplementsKeyword */: node.transformFlags |= 1 /* ContainsTypeScript */; @@ -24143,7 +24600,7 @@ var ts; } // @api function createCatchClause(variableDeclaration, block) { - var node = createBaseNode(287 /* CatchClause */); + var node = createBaseNode(288 /* CatchClause */); variableDeclaration = !ts.isString(variableDeclaration) ? variableDeclaration : createVariableDeclaration(variableDeclaration, /*exclamationToken*/ undefined, /*type*/ undefined, @@ -24154,7 +24611,7 @@ var ts; propagateChildFlags(node.variableDeclaration) | propagateChildFlags(node.block); if (!variableDeclaration) - node.transformFlags |= 16 /* ContainsES2019 */; + node.transformFlags |= 32 /* ContainsES2019 */; return node; } // @api @@ -24169,7 +24626,7 @@ var ts; // // @api function createPropertyAssignment(name, initializer) { - var node = createBaseNamedDeclaration(288 /* PropertyAssignment */, + var node = createBaseNamedDeclaration(289 /* PropertyAssignment */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); @@ -24199,13 +24656,13 @@ var ts; } // @api function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createBaseNamedDeclaration(289 /* ShorthandPropertyAssignment */, + var node = createBaseNamedDeclaration(290 /* ShorthandPropertyAssignment */, /*decorators*/ undefined, /*modifiers*/ undefined, name); node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); node.transformFlags |= propagateChildFlags(node.objectAssignmentInitializer) | - 256 /* ContainsES2015 */; + 512 /* ContainsES2015 */; return node; } function finishUpdateShorthandPropertyAssignment(updated, original) { @@ -24231,12 +24688,12 @@ var ts; } // @api function createSpreadAssignment(expression) { - var node = createBaseNode(290 /* SpreadAssignment */); + var node = createBaseNode(291 /* SpreadAssignment */); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 32 /* ContainsES2018 */ | - 16384 /* ContainsObjectRestOrSpread */; + 64 /* ContainsES2018 */ | + 32768 /* ContainsObjectRestOrSpread */; return node; } // @api @@ -24250,7 +24707,7 @@ var ts; // // @api function createEnumMember(name, initializer) { - var node = createBaseNode(291 /* EnumMember */); + var node = createBaseNode(292 /* EnumMember */); node.name = asName(name); node.initializer = initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); node.transformFlags |= @@ -24271,7 +24728,7 @@ var ts; // // @api function createSourceFile(statements, endOfFileToken, flags) { - var node = baseFactory.createBaseSourceFileNode(297 /* SourceFile */); + var node = baseFactory.createBaseSourceFileNode(298 /* SourceFile */); node.statements = createNodeArray(statements); node.endOfFileToken = endOfFileToken; node.flags |= flags; @@ -24288,7 +24745,7 @@ var ts; return node; } function cloneSourceFileWithChanges(source, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) { - var node = baseFactory.createBaseSourceFileNode(297 /* SourceFile */); + var node = baseFactory.createBaseSourceFileNode(298 /* SourceFile */); for (var p in source) { if (p === "emitNode" || ts.hasProperty(node, p) || !ts.hasProperty(source, p)) continue; @@ -24326,7 +24783,7 @@ var ts; // @api function createBundle(sourceFiles, prepends) { if (prepends === void 0) { prepends = ts.emptyArray; } - var node = createBaseNode(298 /* Bundle */); + var node = createBaseNode(299 /* Bundle */); node.prepends = prepends; node.sourceFiles = sourceFiles; return node; @@ -24341,7 +24798,7 @@ var ts; } // @api function createUnparsedSource(prologues, syntheticReferences, texts) { - var node = createBaseNode(299 /* UnparsedSource */); + var node = createBaseNode(300 /* UnparsedSource */); node.prologues = prologues; node.syntheticReferences = syntheticReferences; node.texts = texts; @@ -24359,28 +24816,28 @@ var ts; } // @api function createUnparsedPrologue(data) { - return createBaseUnparsedNode(292 /* UnparsedPrologue */, data); + return createBaseUnparsedNode(293 /* UnparsedPrologue */, data); } // @api function createUnparsedPrepend(data, texts) { - var node = createBaseUnparsedNode(293 /* UnparsedPrepend */, data); + var node = createBaseUnparsedNode(294 /* UnparsedPrepend */, data); node.texts = texts; return node; } // @api function createUnparsedTextLike(data, internal) { - return createBaseUnparsedNode(internal ? 295 /* UnparsedInternalText */ : 294 /* UnparsedText */, data); + return createBaseUnparsedNode(internal ? 296 /* UnparsedInternalText */ : 295 /* UnparsedText */, data); } // @api function createUnparsedSyntheticReference(section) { - var node = createBaseNode(296 /* UnparsedSyntheticReference */); + var node = createBaseNode(297 /* UnparsedSyntheticReference */); node.data = section.data; node.section = section; return node; } // @api function createInputFiles() { - var node = createBaseNode(300 /* InputFiles */); + var node = createBaseNode(301 /* InputFiles */); node.javascriptText = ""; node.declarationText = ""; return node; @@ -24391,7 +24848,7 @@ var ts; // @api function createSyntheticExpression(type, isSpread, tupleNameSource) { if (isSpread === void 0) { isSpread = false; } - var node = createBaseNode(227 /* SyntheticExpression */); + var node = createBaseNode(228 /* SyntheticExpression */); node.type = type; node.isSpread = isSpread; node.tupleNameSource = tupleNameSource; @@ -24399,7 +24856,7 @@ var ts; } // @api function createSyntaxList(children) { - var node = createBaseNode(334 /* SyntaxList */); + var node = createBaseNode(338 /* SyntaxList */); node._children = children; return node; } @@ -24414,7 +24871,7 @@ var ts; */ // @api function createNotEmittedStatement(original) { - var node = createBaseNode(335 /* NotEmittedStatement */); + var node = createBaseNode(339 /* NotEmittedStatement */); node.original = original; ts.setTextRange(node, original); return node; @@ -24428,7 +24885,7 @@ var ts; */ // @api function createPartiallyEmittedExpression(expression, original) { - var node = createBaseNode(336 /* PartiallyEmittedExpression */); + var node = createBaseNode(340 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; node.transformFlags |= @@ -24456,7 +24913,7 @@ var ts; } // @api function createCommaListExpression(elements) { - var node = createBaseNode(337 /* CommaListExpression */); + var node = createBaseNode(341 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); node.transformFlags |= propagateChildrenFlags(node.elements); return node; @@ -24473,7 +24930,7 @@ var ts; */ // @api function createEndOfDeclarationMarker(original) { - var node = createBaseNode(339 /* EndOfDeclarationMarker */); + var node = createBaseNode(343 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -24484,14 +24941,14 @@ var ts; */ // @api function createMergeDeclarationMarker(original) { - var node = createBaseNode(338 /* MergeDeclarationMarker */); + var node = createBaseNode(342 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; } // @api function createSyntheticReferenceExpression(expression, thisArg) { - var node = createBaseNode(340 /* SyntheticReferenceExpression */); + var node = createBaseNode(344 /* SyntheticReferenceExpression */); node.expression = expression; node.thisArg = thisArg; node.transformFlags |= @@ -24513,7 +24970,7 @@ var ts; if (node === undefined) { return node; } - var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(297 /* SourceFile */) : + var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(298 /* SourceFile */) : ts.isIdentifier(node) ? baseFactory.createBaseIdentifierNode(78 /* Identifier */) : ts.isPrivateIdentifier(node) ? baseFactory.createBasePrivateIdentifierNode(79 /* PrivateIdentifier */) : !ts.isNodeKind(node.kind) ? baseFactory.createBaseTokenNode(node.kind) : @@ -24620,11 +25077,11 @@ var ts; } function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 207 /* ParenthesizedExpression */: return updateParenthesizedExpression(outerExpression, expression); - case 206 /* TypeAssertionExpression */: return updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 224 /* AsExpression */: return updateAsExpression(outerExpression, expression, outerExpression.type); - case 225 /* NonNullExpression */: return updateNonNullExpression(outerExpression, expression); - case 336 /* PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression); + case 208 /* ParenthesizedExpression */: return updateParenthesizedExpression(outerExpression, expression); + case 207 /* TypeAssertionExpression */: return updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 225 /* AsExpression */: return updateAsExpression(outerExpression, expression, outerExpression.type); + case 226 /* NonNullExpression */: return updateNonNullExpression(outerExpression, expression); + case 340 /* PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -24678,13 +25135,13 @@ var ts; case 9 /* BigIntLiteral */: case 10 /* StringLiteral */: return false; - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return target.properties.length > 0; default: return true; @@ -25087,23 +25544,24 @@ var ts; } function getDefaultTagNameForKind(kind) { switch (kind) { - case 329 /* JSDocTypeTag */: return "type"; - case 327 /* JSDocReturnTag */: return "returns"; - case 328 /* JSDocThisTag */: return "this"; - case 325 /* JSDocEnumTag */: return "enum"; - case 317 /* JSDocAuthorTag */: return "author"; - case 319 /* JSDocClassTag */: return "class"; - case 320 /* JSDocPublicTag */: return "public"; - case 321 /* JSDocPrivateTag */: return "private"; - case 322 /* JSDocProtectedTag */: return "protected"; - case 323 /* JSDocReadonlyTag */: return "readonly"; - case 330 /* JSDocTemplateTag */: return "template"; - case 331 /* JSDocTypedefTag */: return "typedef"; - case 326 /* JSDocParameterTag */: return "param"; - case 333 /* JSDocPropertyTag */: return "prop"; - case 324 /* JSDocCallbackTag */: return "callback"; - case 315 /* JSDocAugmentsTag */: return "augments"; - case 316 /* JSDocImplementsTag */: return "implements"; + case 333 /* JSDocTypeTag */: return "type"; + case 331 /* JSDocReturnTag */: return "returns"; + case 332 /* JSDocThisTag */: return "this"; + case 329 /* JSDocEnumTag */: return "enum"; + case 320 /* JSDocAuthorTag */: return "author"; + case 322 /* JSDocClassTag */: return "class"; + case 323 /* JSDocPublicTag */: return "public"; + case 324 /* JSDocPrivateTag */: return "private"; + case 325 /* JSDocProtectedTag */: return "protected"; + case 326 /* JSDocReadonlyTag */: return "readonly"; + case 327 /* JSDocOverrideTag */: return "override"; + case 334 /* JSDocTemplateTag */: return "template"; + case 335 /* JSDocTypedefTag */: return "typedef"; + case 330 /* JSDocParameterTag */: return "param"; + case 337 /* JSDocPropertyTag */: return "prop"; + case 328 /* JSDocCallbackTag */: return "callback"; + case 318 /* JSDocAugmentsTag */: return "augments"; + case 319 /* JSDocImplementsTag */: return "implements"; default: return ts.Debug.fail("Unsupported kind: " + ts.Debug.formatSyntaxKind(kind)); } @@ -25156,10 +25614,10 @@ var ts; } function propagateIdentifierNameFlags(node) { // An IdentifierName is allowed to be `await` - return propagateChildFlags(node) & ~8388608 /* ContainsPossibleTopLevelAwait */; + return propagateChildFlags(node) & ~16777216 /* ContainsPossibleTopLevelAwait */; } function propagatePropertyNameFlagsOfChild(node, transformFlags) { - return transformFlags | (node.transformFlags & 4096 /* PropertyNamePropagatingFlags */); + return transformFlags | (node.transformFlags & 8192 /* PropertyNamePropagatingFlags */); } function propagateChildFlags(child) { if (!child) @@ -25183,36 +25641,36 @@ var ts; */ /* @internal */ function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 172 /* FirstTypeNode */ && kind <= 195 /* LastTypeNode */) { + if (kind >= 173 /* FirstTypeNode */ && kind <= 196 /* LastTypeNode */) { return -2 /* TypeExcludes */; } switch (kind) { - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 199 /* ArrayLiteralExpression */: - return 536879104 /* ArrayLiteralOrCallOrNewExcludes */; - case 256 /* ModuleDeclaration */: - return 546379776 /* ModuleExcludes */; - case 160 /* Parameter */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 200 /* ArrayLiteralExpression */: + return 536887296 /* ArrayLiteralOrCallOrNewExcludes */; + case 257 /* ModuleDeclaration */: + return 555888640 /* ModuleExcludes */; + case 161 /* Parameter */: return 536870912 /* ParameterExcludes */; - case 209 /* ArrowFunction */: - return 547309568 /* ArrowFunctionExcludes */; - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - return 547313664 /* FunctionExcludes */; - case 250 /* VariableDeclarationList */: - return 537018368 /* VariableDeclarationListExcludes */; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - return 536905728 /* ClassExcludes */; - case 166 /* Constructor */: - return 547311616 /* ConstructorExcludes */; - case 163 /* PropertyDeclaration */: - return 536875008 /* PropertyExcludes */; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - return 538923008 /* MethodOrAccessorExcludes */; + case 210 /* ArrowFunction */: + return 557748224 /* ArrowFunctionExcludes */; + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + return 557756416 /* FunctionExcludes */; + case 251 /* VariableDeclarationList */: + return 537165824 /* VariableDeclarationListExcludes */; + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + return 536940544 /* ClassExcludes */; + case 167 /* Constructor */: + return 557752320 /* ConstructorExcludes */; + case 164 /* PropertyDeclaration */: + return 536879104 /* PropertyExcludes */; + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return 540975104 /* MethodOrAccessorExcludes */; case 128 /* AnyKeyword */: case 144 /* NumberKeyword */: case 155 /* BigIntKeyword */: @@ -25222,30 +25680,30 @@ var ts; case 131 /* BooleanKeyword */: case 148 /* SymbolKeyword */: case 113 /* VoidKeyword */: - case 159 /* TypeParameter */: - case 162 /* PropertySignature */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 160 /* TypeParameter */: + case 163 /* PropertySignature */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return -2 /* TypeExcludes */; - case 200 /* ObjectLiteralExpression */: - return 536922112 /* ObjectLiteralExcludes */; - case 287 /* CatchClause */: - return 536887296 /* CatchClauseExcludes */; - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: - return 536879104 /* BindingPatternExcludes */; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: - case 336 /* PartiallyEmittedExpression */: - case 207 /* ParenthesizedExpression */: + case 201 /* ObjectLiteralExpression */: + return 536973312 /* ObjectLiteralExcludes */; + case 288 /* CatchClause */: + return 536903680 /* CatchClauseExcludes */; + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + return 536887296 /* BindingPatternExcludes */; + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: + case 340 /* PartiallyEmittedExpression */: + case 208 /* ParenthesizedExpression */: case 105 /* SuperKeyword */: return 536870912 /* OuterExpressionExcludes */; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return 536870912 /* PropertyAccessExcludes */; default: return 536870912 /* NodeExcludes */; @@ -25544,7 +26002,7 @@ var ts; // To avoid holding onto transformation artifacts, we keep track of any // parse tree node we are annotating. This allows us to clean them up after // all transformations have completed. - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = (_a = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)))) !== null && _a !== void 0 ? _a : ts.Debug.fail("Could not determine parsed source file."); @@ -26031,13 +26489,27 @@ var ts; /*typeArguments*/ undefined, [moduleExpression, exportsExpression]); } // Class Fields Helpers - function createClassPrivateFieldGetHelper(receiver, privateField) { + function createClassPrivateFieldGetHelper(receiver, state, kind, f) { context.requestEmitHelper(ts.classPrivateFieldGetHelper); - return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ undefined, [receiver, privateField]); + var args; + if (!f) { + args = [receiver, state, factory.createStringLiteral(kind)]; + } + else { + args = [receiver, state, factory.createStringLiteral(kind), f]; + } + return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ undefined, args); } - function createClassPrivateFieldSetHelper(receiver, privateField, value) { + function createClassPrivateFieldSetHelper(receiver, state, value, kind, f) { context.requestEmitHelper(ts.classPrivateFieldSetHelper); - return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, [receiver, privateField, value]); + var args; + if (!f) { + args = [receiver, state, value, factory.createStringLiteral(kind)]; + } + else { + args = [receiver, state, value, factory.createStringLiteral(kind), f]; + } + return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, args); } } ts.createEmitHelperFactory = createEmitHelperFactory; @@ -26277,7 +26749,6 @@ var ts; scoped: false, text: "\n var __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n };" }; - // emit output for the __export helper function ts.exportStarHelper = { name: "typescript:export-star", importName: "__exportStar", @@ -26286,18 +26757,116 @@ var ts; priority: 2, text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n };" }; - // Class fields helpers + /** + * Parameters: + * @param receiver — The object from which the private member will be read. + * @param state — One of the following: + * - A WeakMap used to read a private instance field. + * - A WeakSet used as an instance brand for private instance methods and accessors. + * - A function value that should be the undecorated class constructor used to brand check private static fields, methods, and accessors. + * @param kind — (optional pre TS 4.3, required for TS 4.3+) One of the following values: + * - undefined — Indicates a private instance field (pre TS 4.3). + * - "f" — Indicates a private field (instance or static). + * - "m" — Indicates a private method (instance or static). + * - "a" — Indicates a private accessor (instance or static). + * @param f — (optional pre TS 4.3) Depends on the arguments for state and kind: + * - If kind is "m", this should be the function corresponding to the static or instance method. + * - If kind is "a", this should be the function corresponding to the getter method, or undefined if the getter was not defined. + * - If kind is "f" and state is a function, this should be an object holding the value of a static field, or undefined if the static field declaration has not yet been evaluated. + * Usage: + * This helper will only ever be used by the compiler in the following ways: + * + * Reading from a private instance field (pre TS 4.3): + * __classPrivateFieldGet(, ) + * + * Reading from a private instance field (TS 4.3+): + * __classPrivateFieldGet(, , "f") + * + * Reading from a private instance get accessor (when defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", ) + * + * Reading from a private instance get accessor (when not defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Reading from a private instance method (TS 4.3+): + * __classPrivateFieldGet(, , "m", ) + * + * Reading from a private static field (TS 4.3+): + * __classPrivateFieldGet(, , "f", <{ value: any }>) + * + * Reading from a private static get accessor (when defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", ) + * + * Reading from a private static get accessor (when not defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Reading from a private static method (TS 4.3+): + * __classPrivateFieldGet(, , "m", ) + */ ts.classPrivateFieldGetHelper = { name: "typescript:classPrivateFieldGet", importName: "__classPrivateFieldGet", scoped: false, - text: "\n var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, privateMap) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to get private field on non-instance\");\n }\n return privateMap.get(receiver);\n };" + text: "\n var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n };" }; + /** + * Parameters: + * @param receiver — The object on which the private member will be set. + * @param state — One of the following: + * - A WeakMap used to store a private instance field. + * - A WeakSet used as an instance brand for private instance methods and accessors. + * - A function value that should be the undecorated class constructor used to brand check private static fields, methods, and accessors. + * @param value — The value to set. + * @param kind — (optional pre TS 4.3, required for TS 4.3+) One of the following values: + * - undefined — Indicates a private instance field (pre TS 4.3). + * - "f" — Indicates a private field (instance or static). + * - "m" — Indicates a private method (instance or static). + * - "a" — Indicates a private accessor (instance or static). + * @param f — (optional pre TS 4.3) Depends on the arguments for state and kind: + * - If kind is "m", this should be the function corresponding to the static or instance method. + * - If kind is "a", this should be the function corresponding to the setter method, or undefined if the setter was not defined. + * - If kind is "f" and state is a function, this should be an object holding the value of a static field, or undefined if the static field declaration has not yet been evaluated. + * Usage: + * This helper will only ever be used by the compiler in the following ways: + * + * Writing to a private instance field (pre TS 4.3): + * __classPrivateFieldSet(, , ) + * + * Writing to a private instance field (TS 4.3+): + * __classPrivateFieldSet(, , , "f") + * + * Writing to a private instance set accessor (when defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", ) + * + * Writing to a private instance set accessor (when not defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Writing to a private instance method (TS 4.3+): + * __classPrivateFieldSet(, , , "m", ) + * NOTE: This always results in a runtime error. + * + * Writing to a private static field (TS 4.3+): + * __classPrivateFieldSet(, , , "f", <{ value: any }>) + * + * Writing to a private static set accessor (when defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", ) + * + * Writing to a private static set accessor (when not defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Writing to a private static method (TS 4.3+): + * __classPrivateFieldSet(, , , "m", ) + * NOTE: This always results in a runtime error. + */ ts.classPrivateFieldSetHelper = { name: "typescript:classPrivateFieldSet", importName: "__classPrivateFieldSet", scoped: false, - text: "\n var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, privateMap, value) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to set private field on non-instance\");\n }\n privateMap.set(receiver, value);\n return value;\n };" + text: "\n var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n };" }; var allUnscopedEmitHelpers; function getAllUnscopedEmitHelpers() { @@ -26386,25 +26955,93 @@ var ts; return node.kind === 17 /* TemplateTail */; } ts.isTemplateTail = isTemplateTail; + // Punctuation + function isDotDotDotToken(node) { + return node.kind === 25 /* DotDotDotToken */; + } + ts.isDotDotDotToken = isDotDotDotToken; + /*@internal*/ + function isCommaToken(node) { + return node.kind === 27 /* CommaToken */; + } + ts.isCommaToken = isCommaToken; + function isPlusToken(node) { + return node.kind === 39 /* PlusToken */; + } + ts.isPlusToken = isPlusToken; + function isMinusToken(node) { + return node.kind === 40 /* MinusToken */; + } + ts.isMinusToken = isMinusToken; + function isAsteriskToken(node) { + return node.kind === 41 /* AsteriskToken */; + } + ts.isAsteriskToken = isAsteriskToken; + /*@internal*/ + function isExclamationToken(node) { + return node.kind === 53 /* ExclamationToken */; + } + ts.isExclamationToken = isExclamationToken; + /*@internal*/ + function isQuestionToken(node) { + return node.kind === 57 /* QuestionToken */; + } + ts.isQuestionToken = isQuestionToken; + /*@internal*/ + function isColonToken(node) { + return node.kind === 58 /* ColonToken */; + } + ts.isColonToken = isColonToken; + /*@internal*/ + function isQuestionDotToken(node) { + return node.kind === 28 /* QuestionDotToken */; + } + ts.isQuestionDotToken = isQuestionDotToken; + /*@internal*/ + function isEqualsGreaterThanToken(node) { + return node.kind === 38 /* EqualsGreaterThanToken */; + } + ts.isEqualsGreaterThanToken = isEqualsGreaterThanToken; // Identifiers function isIdentifier(node) { return node.kind === 78 /* Identifier */; } ts.isIdentifier = isIdentifier; - // Names - function isQualifiedName(node) { - return node.kind === 157 /* QualifiedName */; - } - ts.isQualifiedName = isQualifiedName; - function isComputedPropertyName(node) { - return node.kind === 158 /* ComputedPropertyName */; - } - ts.isComputedPropertyName = isComputedPropertyName; function isPrivateIdentifier(node) { return node.kind === 79 /* PrivateIdentifier */; } ts.isPrivateIdentifier = isPrivateIdentifier; - // Tokens + // Reserved Words + /* @internal */ + function isExportModifier(node) { + return node.kind === 92 /* ExportKeyword */; + } + ts.isExportModifier = isExportModifier; + /* @internal */ + function isAsyncModifier(node) { + return node.kind === 129 /* AsyncKeyword */; + } + ts.isAsyncModifier = isAsyncModifier; + /* @internal */ + function isAssertsKeyword(node) { + return node.kind === 127 /* AssertsKeyword */; + } + ts.isAssertsKeyword = isAssertsKeyword; + /* @internal */ + function isAwaitKeyword(node) { + return node.kind === 130 /* AwaitKeyword */; + } + ts.isAwaitKeyword = isAwaitKeyword; + /* @internal */ + function isReadonlyKeyword(node) { + return node.kind === 142 /* ReadonlyKeyword */; + } + ts.isReadonlyKeyword = isReadonlyKeyword; + /* @internal */ + function isStaticModifier(node) { + return node.kind === 123 /* StaticKeyword */; + } + ts.isStaticModifier = isStaticModifier; /*@internal*/ function isSuperKeyword(node) { return node.kind === 105 /* SuperKeyword */; @@ -26415,597 +27052,591 @@ var ts; return node.kind === 99 /* ImportKeyword */; } ts.isImportKeyword = isImportKeyword; - /*@internal*/ - function isCommaToken(node) { - return node.kind === 27 /* CommaToken */; - } - ts.isCommaToken = isCommaToken; - /*@internal*/ - function isQuestionToken(node) { - return node.kind === 57 /* QuestionToken */; + // Names + function isQualifiedName(node) { + return node.kind === 158 /* QualifiedName */; } - ts.isQuestionToken = isQuestionToken; - /*@internal*/ - function isExclamationToken(node) { - return node.kind === 53 /* ExclamationToken */; + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 159 /* ComputedPropertyName */; } - ts.isExclamationToken = isExclamationToken; + ts.isComputedPropertyName = isComputedPropertyName; // Signature elements function isTypeParameterDeclaration(node) { - return node.kind === 159 /* TypeParameter */; + return node.kind === 160 /* TypeParameter */; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; // TODO(rbuckton): Rename to 'isParameterDeclaration' function isParameter(node) { - return node.kind === 160 /* Parameter */; + return node.kind === 161 /* Parameter */; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 161 /* Decorator */; + return node.kind === 162 /* Decorator */; } ts.isDecorator = isDecorator; // TypeMember function isPropertySignature(node) { - return node.kind === 162 /* PropertySignature */; + return node.kind === 163 /* PropertySignature */; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 163 /* PropertyDeclaration */; + return node.kind === 164 /* PropertyDeclaration */; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 164 /* MethodSignature */; + return node.kind === 165 /* MethodSignature */; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 165 /* MethodDeclaration */; + return node.kind === 166 /* MethodDeclaration */; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 166 /* Constructor */; + return node.kind === 167 /* Constructor */; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 167 /* GetAccessor */; + return node.kind === 168 /* GetAccessor */; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 168 /* SetAccessor */; + return node.kind === 169 /* SetAccessor */; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 169 /* CallSignature */; + return node.kind === 170 /* CallSignature */; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 170 /* ConstructSignature */; + return node.kind === 171 /* ConstructSignature */; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 171 /* IndexSignature */; + return node.kind === 172 /* IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; // Type function isTypePredicateNode(node) { - return node.kind === 172 /* TypePredicate */; + return node.kind === 173 /* TypePredicate */; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 173 /* TypeReference */; + return node.kind === 174 /* TypeReference */; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 174 /* FunctionType */; + return node.kind === 175 /* FunctionType */; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 175 /* ConstructorType */; + return node.kind === 176 /* ConstructorType */; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 176 /* TypeQuery */; + return node.kind === 177 /* TypeQuery */; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 177 /* TypeLiteral */; + return node.kind === 178 /* TypeLiteral */; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 178 /* ArrayType */; + return node.kind === 179 /* ArrayType */; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 179 /* TupleType */; + return node.kind === 180 /* TupleType */; } ts.isTupleTypeNode = isTupleTypeNode; function isNamedTupleMember(node) { - return node.kind === 192 /* NamedTupleMember */; + return node.kind === 193 /* NamedTupleMember */; } ts.isNamedTupleMember = isNamedTupleMember; function isOptionalTypeNode(node) { - return node.kind === 180 /* OptionalType */; + return node.kind === 181 /* OptionalType */; } ts.isOptionalTypeNode = isOptionalTypeNode; function isRestTypeNode(node) { - return node.kind === 181 /* RestType */; + return node.kind === 182 /* RestType */; } ts.isRestTypeNode = isRestTypeNode; function isUnionTypeNode(node) { - return node.kind === 182 /* UnionType */; + return node.kind === 183 /* UnionType */; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 183 /* IntersectionType */; + return node.kind === 184 /* IntersectionType */; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isConditionalTypeNode(node) { - return node.kind === 184 /* ConditionalType */; + return node.kind === 185 /* ConditionalType */; } ts.isConditionalTypeNode = isConditionalTypeNode; function isInferTypeNode(node) { - return node.kind === 185 /* InferType */; + return node.kind === 186 /* InferType */; } ts.isInferTypeNode = isInferTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 186 /* ParenthesizedType */; + return node.kind === 187 /* ParenthesizedType */; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 187 /* ThisType */; + return node.kind === 188 /* ThisType */; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 188 /* TypeOperator */; + return node.kind === 189 /* TypeOperator */; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 189 /* IndexedAccessType */; + return node.kind === 190 /* IndexedAccessType */; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 190 /* MappedType */; + return node.kind === 191 /* MappedType */; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 191 /* LiteralType */; + return node.kind === 192 /* LiteralType */; } ts.isLiteralTypeNode = isLiteralTypeNode; function isImportTypeNode(node) { - return node.kind === 195 /* ImportType */; + return node.kind === 196 /* ImportType */; } ts.isImportTypeNode = isImportTypeNode; function isTemplateLiteralTypeSpan(node) { - return node.kind === 194 /* TemplateLiteralTypeSpan */; + return node.kind === 195 /* TemplateLiteralTypeSpan */; } ts.isTemplateLiteralTypeSpan = isTemplateLiteralTypeSpan; function isTemplateLiteralTypeNode(node) { - return node.kind === 193 /* TemplateLiteralType */; + return node.kind === 194 /* TemplateLiteralType */; } ts.isTemplateLiteralTypeNode = isTemplateLiteralTypeNode; // Binding patterns function isObjectBindingPattern(node) { - return node.kind === 196 /* ObjectBindingPattern */; + return node.kind === 197 /* ObjectBindingPattern */; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 197 /* ArrayBindingPattern */; + return node.kind === 198 /* ArrayBindingPattern */; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 198 /* BindingElement */; + return node.kind === 199 /* BindingElement */; } ts.isBindingElement = isBindingElement; // Expression function isArrayLiteralExpression(node) { - return node.kind === 199 /* ArrayLiteralExpression */; + return node.kind === 200 /* ArrayLiteralExpression */; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 200 /* ObjectLiteralExpression */; + return node.kind === 201 /* ObjectLiteralExpression */; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 201 /* PropertyAccessExpression */; + return node.kind === 202 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 202 /* ElementAccessExpression */; + return node.kind === 203 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 203 /* CallExpression */; + return node.kind === 204 /* CallExpression */; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 204 /* NewExpression */; + return node.kind === 205 /* NewExpression */; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 205 /* TaggedTemplateExpression */; + return node.kind === 206 /* TaggedTemplateExpression */; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertionExpression(node) { - return node.kind === 206 /* TypeAssertionExpression */; + return node.kind === 207 /* TypeAssertionExpression */; } ts.isTypeAssertionExpression = isTypeAssertionExpression; function isParenthesizedExpression(node) { - return node.kind === 207 /* ParenthesizedExpression */; + return node.kind === 208 /* ParenthesizedExpression */; } ts.isParenthesizedExpression = isParenthesizedExpression; function isFunctionExpression(node) { - return node.kind === 208 /* FunctionExpression */; + return node.kind === 209 /* FunctionExpression */; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 209 /* ArrowFunction */; + return node.kind === 210 /* ArrowFunction */; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 210 /* DeleteExpression */; + return node.kind === 211 /* DeleteExpression */; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 211 /* TypeOfExpression */; + return node.kind === 212 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 212 /* VoidExpression */; + return node.kind === 213 /* VoidExpression */; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 213 /* AwaitExpression */; + return node.kind === 214 /* AwaitExpression */; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 214 /* PrefixUnaryExpression */; + return node.kind === 215 /* PrefixUnaryExpression */; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 215 /* PostfixUnaryExpression */; + return node.kind === 216 /* PostfixUnaryExpression */; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 216 /* BinaryExpression */; + return node.kind === 217 /* BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 217 /* ConditionalExpression */; + return node.kind === 218 /* ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 218 /* TemplateExpression */; + return node.kind === 219 /* TemplateExpression */; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 219 /* YieldExpression */; + return node.kind === 220 /* YieldExpression */; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 220 /* SpreadElement */; + return node.kind === 221 /* SpreadElement */; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 221 /* ClassExpression */; + return node.kind === 222 /* ClassExpression */; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 222 /* OmittedExpression */; + return node.kind === 223 /* OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 223 /* ExpressionWithTypeArguments */; + return node.kind === 224 /* ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 224 /* AsExpression */; + return node.kind === 225 /* AsExpression */; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 225 /* NonNullExpression */; + return node.kind === 226 /* NonNullExpression */; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 226 /* MetaProperty */; + return node.kind === 227 /* MetaProperty */; } ts.isMetaProperty = isMetaProperty; function isSyntheticExpression(node) { - return node.kind === 227 /* SyntheticExpression */; + return node.kind === 228 /* SyntheticExpression */; } ts.isSyntheticExpression = isSyntheticExpression; function isPartiallyEmittedExpression(node) { - return node.kind === 336 /* PartiallyEmittedExpression */; + return node.kind === 340 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; function isCommaListExpression(node) { - return node.kind === 337 /* CommaListExpression */; + return node.kind === 341 /* CommaListExpression */; } ts.isCommaListExpression = isCommaListExpression; // Misc function isTemplateSpan(node) { - return node.kind === 228 /* TemplateSpan */; + return node.kind === 229 /* TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 229 /* SemicolonClassElement */; + return node.kind === 230 /* SemicolonClassElement */; } ts.isSemicolonClassElement = isSemicolonClassElement; // Elements function isBlock(node) { - return node.kind === 230 /* Block */; + return node.kind === 231 /* Block */; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 232 /* VariableStatement */; + return node.kind === 233 /* VariableStatement */; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 231 /* EmptyStatement */; + return node.kind === 232 /* EmptyStatement */; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 233 /* ExpressionStatement */; + return node.kind === 234 /* ExpressionStatement */; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 234 /* IfStatement */; + return node.kind === 235 /* IfStatement */; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 235 /* DoStatement */; + return node.kind === 236 /* DoStatement */; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 236 /* WhileStatement */; + return node.kind === 237 /* WhileStatement */; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 237 /* ForStatement */; + return node.kind === 238 /* ForStatement */; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 238 /* ForInStatement */; + return node.kind === 239 /* ForInStatement */; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 239 /* ForOfStatement */; + return node.kind === 240 /* ForOfStatement */; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 240 /* ContinueStatement */; + return node.kind === 241 /* ContinueStatement */; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 241 /* BreakStatement */; + return node.kind === 242 /* BreakStatement */; } ts.isBreakStatement = isBreakStatement; function isReturnStatement(node) { - return node.kind === 242 /* ReturnStatement */; + return node.kind === 243 /* ReturnStatement */; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 243 /* WithStatement */; + return node.kind === 244 /* WithStatement */; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 244 /* SwitchStatement */; + return node.kind === 245 /* SwitchStatement */; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 245 /* LabeledStatement */; + return node.kind === 246 /* LabeledStatement */; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 246 /* ThrowStatement */; + return node.kind === 247 /* ThrowStatement */; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 247 /* TryStatement */; + return node.kind === 248 /* TryStatement */; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 248 /* DebuggerStatement */; + return node.kind === 249 /* DebuggerStatement */; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 249 /* VariableDeclaration */; + return node.kind === 250 /* VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 250 /* VariableDeclarationList */; + return node.kind === 251 /* VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 251 /* FunctionDeclaration */; + return node.kind === 252 /* FunctionDeclaration */; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 252 /* ClassDeclaration */; + return node.kind === 253 /* ClassDeclaration */; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 253 /* InterfaceDeclaration */; + return node.kind === 254 /* InterfaceDeclaration */; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 254 /* TypeAliasDeclaration */; + return node.kind === 255 /* TypeAliasDeclaration */; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 255 /* EnumDeclaration */; + return node.kind === 256 /* EnumDeclaration */; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 256 /* ModuleDeclaration */; + return node.kind === 257 /* ModuleDeclaration */; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 257 /* ModuleBlock */; + return node.kind === 258 /* ModuleBlock */; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 258 /* CaseBlock */; + return node.kind === 259 /* CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 259 /* NamespaceExportDeclaration */; + return node.kind === 260 /* NamespaceExportDeclaration */; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */; + return node.kind === 261 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 261 /* ImportDeclaration */; + return node.kind === 262 /* ImportDeclaration */; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 262 /* ImportClause */; + return node.kind === 263 /* ImportClause */; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 263 /* NamespaceImport */; + return node.kind === 264 /* NamespaceImport */; } ts.isNamespaceImport = isNamespaceImport; function isNamespaceExport(node) { - return node.kind === 269 /* NamespaceExport */; + return node.kind === 270 /* NamespaceExport */; } ts.isNamespaceExport = isNamespaceExport; function isNamedImports(node) { - return node.kind === 264 /* NamedImports */; + return node.kind === 265 /* NamedImports */; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 265 /* ImportSpecifier */; + return node.kind === 266 /* ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 266 /* ExportAssignment */; + return node.kind === 267 /* ExportAssignment */; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 267 /* ExportDeclaration */; + return node.kind === 268 /* ExportDeclaration */; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 268 /* NamedExports */; + return node.kind === 269 /* NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 270 /* ExportSpecifier */; + return node.kind === 271 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 271 /* MissingDeclaration */; + return node.kind === 272 /* MissingDeclaration */; } ts.isMissingDeclaration = isMissingDeclaration; function isNotEmittedStatement(node) { - return node.kind === 335 /* NotEmittedStatement */; + return node.kind === 339 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ function isSyntheticReference(node) { - return node.kind === 340 /* SyntheticReferenceExpression */; + return node.kind === 344 /* SyntheticReferenceExpression */; } ts.isSyntheticReference = isSyntheticReference; /* @internal */ function isMergeDeclarationMarker(node) { - return node.kind === 338 /* MergeDeclarationMarker */; + return node.kind === 342 /* MergeDeclarationMarker */; } ts.isMergeDeclarationMarker = isMergeDeclarationMarker; /* @internal */ function isEndOfDeclarationMarker(node) { - return node.kind === 339 /* EndOfDeclarationMarker */; + return node.kind === 343 /* EndOfDeclarationMarker */; } ts.isEndOfDeclarationMarker = isEndOfDeclarationMarker; // Module References function isExternalModuleReference(node) { - return node.kind === 272 /* ExternalModuleReference */; + return node.kind === 273 /* ExternalModuleReference */; } ts.isExternalModuleReference = isExternalModuleReference; // JSX function isJsxElement(node) { - return node.kind === 273 /* JsxElement */; + return node.kind === 274 /* JsxElement */; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 274 /* JsxSelfClosingElement */; + return node.kind === 275 /* JsxSelfClosingElement */; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 275 /* JsxOpeningElement */; + return node.kind === 276 /* JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 276 /* JsxClosingElement */; + return node.kind === 277 /* JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxFragment(node) { - return node.kind === 277 /* JsxFragment */; + return node.kind === 278 /* JsxFragment */; } ts.isJsxFragment = isJsxFragment; function isJsxOpeningFragment(node) { - return node.kind === 278 /* JsxOpeningFragment */; + return node.kind === 279 /* JsxOpeningFragment */; } ts.isJsxOpeningFragment = isJsxOpeningFragment; function isJsxClosingFragment(node) { - return node.kind === 279 /* JsxClosingFragment */; + return node.kind === 280 /* JsxClosingFragment */; } ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 280 /* JsxAttribute */; + return node.kind === 281 /* JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 281 /* JsxAttributes */; + return node.kind === 282 /* JsxAttributes */; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 282 /* JsxSpreadAttribute */; + return node.kind === 283 /* JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 283 /* JsxExpression */; + return node.kind === 284 /* JsxExpression */; } ts.isJsxExpression = isJsxExpression; // Clauses function isCaseClause(node) { - return node.kind === 284 /* CaseClause */; + return node.kind === 285 /* CaseClause */; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 285 /* DefaultClause */; + return node.kind === 286 /* DefaultClause */; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 286 /* HeritageClause */; + return node.kind === 287 /* HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 287 /* CatchClause */; + return node.kind === 288 /* CatchClause */; } ts.isCatchClause = isCatchClause; // Property assignments function isPropertyAssignment(node) { - return node.kind === 288 /* PropertyAssignment */; + return node.kind === 289 /* PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 289 /* ShorthandPropertyAssignment */; + return node.kind === 290 /* ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 290 /* SpreadAssignment */; + return node.kind === 291 /* SpreadAssignment */; } ts.isSpreadAssignment = isSpreadAssignment; // Enum function isEnumMember(node) { - return node.kind === 291 /* EnumMember */; + return node.kind === 292 /* EnumMember */; } ts.isEnumMember = isEnumMember; // Unparsed // TODO(rbuckton): isUnparsedPrologue function isUnparsedPrepend(node) { - return node.kind === 293 /* UnparsedPrepend */; + return node.kind === 294 /* UnparsedPrepend */; } ts.isUnparsedPrepend = isUnparsedPrepend; // TODO(rbuckton): isUnparsedText @@ -27013,156 +27644,164 @@ var ts; // TODO(rbuckton): isUnparsedSyntheticReference // Top-level nodes function isSourceFile(node) { - return node.kind === 297 /* SourceFile */; + return node.kind === 298 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 298 /* Bundle */; + return node.kind === 299 /* Bundle */; } ts.isBundle = isBundle; function isUnparsedSource(node) { - return node.kind === 299 /* UnparsedSource */; + return node.kind === 300 /* UnparsedSource */; } ts.isUnparsedSource = isUnparsedSource; // TODO(rbuckton): isInputFiles // JSDoc Elements function isJSDocTypeExpression(node) { - return node.kind === 301 /* JSDocTypeExpression */; + return node.kind === 302 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocNameReference(node) { - return node.kind === 302 /* JSDocNameReference */; + return node.kind === 303 /* JSDocNameReference */; } ts.isJSDocNameReference = isJSDocNameReference; + function isJSDocLink(node) { + return node.kind === 316 /* JSDocLink */; + } + ts.isJSDocLink = isJSDocLink; function isJSDocAllType(node) { - return node.kind === 303 /* JSDocAllType */; + return node.kind === 304 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 304 /* JSDocUnknownType */; + return node.kind === 305 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 305 /* JSDocNullableType */; + return node.kind === 306 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 306 /* JSDocNonNullableType */; + return node.kind === 307 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 307 /* JSDocOptionalType */; + return node.kind === 308 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 308 /* JSDocFunctionType */; + return node.kind === 309 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 309 /* JSDocVariadicType */; + return node.kind === 310 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDocNamepathType(node) { - return node.kind === 310 /* JSDocNamepathType */; + return node.kind === 311 /* JSDocNamepathType */; } ts.isJSDocNamepathType = isJSDocNamepathType; function isJSDoc(node) { - return node.kind === 311 /* JSDocComment */; + return node.kind === 312 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocTypeLiteral(node) { - return node.kind === 312 /* JSDocTypeLiteral */; + return node.kind === 314 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; function isJSDocSignature(node) { - return node.kind === 313 /* JSDocSignature */; + return node.kind === 315 /* JSDocSignature */; } ts.isJSDocSignature = isJSDocSignature; // JSDoc Tags function isJSDocAugmentsTag(node) { - return node.kind === 315 /* JSDocAugmentsTag */; + return node.kind === 318 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocAuthorTag(node) { - return node.kind === 317 /* JSDocAuthorTag */; + return node.kind === 320 /* JSDocAuthorTag */; } ts.isJSDocAuthorTag = isJSDocAuthorTag; function isJSDocClassTag(node) { - return node.kind === 319 /* JSDocClassTag */; + return node.kind === 322 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocCallbackTag(node) { - return node.kind === 324 /* JSDocCallbackTag */; + return node.kind === 328 /* JSDocCallbackTag */; } ts.isJSDocCallbackTag = isJSDocCallbackTag; function isJSDocPublicTag(node) { - return node.kind === 320 /* JSDocPublicTag */; + return node.kind === 323 /* JSDocPublicTag */; } ts.isJSDocPublicTag = isJSDocPublicTag; function isJSDocPrivateTag(node) { - return node.kind === 321 /* JSDocPrivateTag */; + return node.kind === 324 /* JSDocPrivateTag */; } ts.isJSDocPrivateTag = isJSDocPrivateTag; function isJSDocProtectedTag(node) { - return node.kind === 322 /* JSDocProtectedTag */; + return node.kind === 325 /* JSDocProtectedTag */; } ts.isJSDocProtectedTag = isJSDocProtectedTag; function isJSDocReadonlyTag(node) { - return node.kind === 323 /* JSDocReadonlyTag */; + return node.kind === 326 /* JSDocReadonlyTag */; } ts.isJSDocReadonlyTag = isJSDocReadonlyTag; + function isJSDocOverrideTag(node) { + return node.kind === 327 /* JSDocOverrideTag */; + } + ts.isJSDocOverrideTag = isJSDocOverrideTag; function isJSDocDeprecatedTag(node) { - return node.kind === 318 /* JSDocDeprecatedTag */; + return node.kind === 321 /* JSDocDeprecatedTag */; } ts.isJSDocDeprecatedTag = isJSDocDeprecatedTag; function isJSDocSeeTag(node) { - return node.kind === 332 /* JSDocSeeTag */; + return node.kind === 336 /* JSDocSeeTag */; } ts.isJSDocSeeTag = isJSDocSeeTag; function isJSDocEnumTag(node) { - return node.kind === 325 /* JSDocEnumTag */; + return node.kind === 329 /* JSDocEnumTag */; } ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocParameterTag(node) { - return node.kind === 326 /* JSDocParameterTag */; + return node.kind === 330 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 327 /* JSDocReturnTag */; + return node.kind === 331 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocThisTag(node) { - return node.kind === 328 /* JSDocThisTag */; + return node.kind === 332 /* JSDocThisTag */; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocTypeTag(node) { - return node.kind === 329 /* JSDocTypeTag */; + return node.kind === 333 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 330 /* JSDocTemplateTag */; + return node.kind === 334 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 331 /* JSDocTypedefTag */; + return node.kind === 335 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocUnknownTag(node) { - return node.kind === 314 /* JSDocTag */; + return node.kind === 317 /* JSDocTag */; } ts.isJSDocUnknownTag = isJSDocUnknownTag; function isJSDocPropertyTag(node) { - return node.kind === 333 /* JSDocPropertyTag */; + return node.kind === 337 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocImplementsTag(node) { - return node.kind === 316 /* JSDocImplementsTag */; + return node.kind === 319 /* JSDocImplementsTag */; } ts.isJSDocImplementsTag = isJSDocImplementsTag; // Synthesized list /* @internal */ function isSyntaxList(n) { - return n.kind === 334 /* SyntaxList */; + return n.kind === 338 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; })(ts || (ts = {})); @@ -27179,7 +27818,7 @@ var ts; return ts.setTextRange(factory.createElementAccessExpression(target, memberName.expression), location); } else { - var expression = ts.setTextRange(ts.isIdentifierOrPrivateIdentifier(memberName) + var expression = ts.setTextRange(ts.isMemberName(memberName) ? factory.createPropertyAccessExpression(target, memberName) : factory.createElementAccessExpression(target, memberName), memberName); ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */; @@ -27361,14 +28000,14 @@ var ts; ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals."); } switch (property.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return createExpressionForAccessorDeclaration(factory, node.properties, property, receiver, !!node.multiLine); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return createExpressionForPropertyAssignment(factory, property, receiver); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(factory, property, receiver); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return createExpressionForMethodDeclaration(factory, property, receiver); } } @@ -27421,21 +28060,21 @@ var ts; } ts.startsWithUseStrict = startsWithUseStrict; function isCommaSequence(node) { - return node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || - node.kind === 337 /* CommaListExpression */; + return node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || + node.kind === 341 /* CommaListExpression */; } ts.isCommaSequence = isCommaSequence; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 15 /* All */; } switch (node.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return (kinds & 1 /* Parentheses */) !== 0; - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return (kinds & 2 /* TypeAssertions */) !== 0; - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return (kinds & 4 /* NonNullAssertions */) !== 0; - case 336 /* PartiallyEmittedExpression */: + case 340 /* PartiallyEmittedExpression */: return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -27556,10 +28195,10 @@ var ts; var name = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name) ? name : factory.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 261 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 262 /* ImportDeclaration */ && node.importClause) { return factory.getGeneratedNameForNode(node); } - if (node.kind === 267 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 268 /* ExportDeclaration */ && node.moduleSpecifier) { return factory.getGeneratedNameForNode(node); } return undefined; @@ -27678,7 +28317,7 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // `b` in `({ a: b } = ...)` // `b` in `({ a: b = 1 } = ...)` // `{b}` in `({ a: {b} } = ...)` @@ -27690,11 +28329,11 @@ var ts; // `b[0]` in `({ a: b[0] } = ...)` // `b[0]` in `({ a: b[0] = 1 } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: // `a` in `({ a } = ...)` // `a` in `({ a = 1 } = ...)` return bindingElement.name; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } @@ -27726,12 +28365,12 @@ var ts; */ function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 160 /* Parameter */: - case 198 /* BindingElement */: + case 161 /* Parameter */: + case 199 /* BindingElement */: // `...` in `let [...a] = ...` return bindingElement.dotDotDotToken; - case 220 /* SpreadElement */: - case 290 /* SpreadAssignment */: + case 221 /* SpreadElement */: + case 291 /* SpreadAssignment */: // `...` in `[...a] = ...` return bindingElement; } @@ -27749,7 +28388,7 @@ var ts; ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement; function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 198 /* BindingElement */: + case 199 /* BindingElement */: // `a` in `let { a: b } = ...` // `[a]` in `let { [a]: b } = ...` // `"a"` in `let { "a": b } = ...` @@ -27764,7 +28403,7 @@ var ts; : propertyName; } break; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // `a` in `({ a: b } = ...)` // `[a]` in `({ [a]: b } = ...)` // `"a"` in `({ "a": b } = ...)` @@ -27779,7 +28418,7 @@ var ts; : propertyName; } break; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) { return ts.Debug.failBadSyntaxKind(bindingElement.name); @@ -27802,13 +28441,13 @@ var ts; */ function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: - case 199 /* ArrayLiteralExpression */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + case 200 /* ArrayLiteralExpression */: // `a` in `{a}` // `a` in `[a]` return name.elements; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: // `a` in `{a}` return name.properties; } @@ -27829,46 +28468,294 @@ var ts; ts.getJSDocTypeAliasName = getJSDocTypeAliasName; function canHaveModifiers(node) { var kind = node.kind; - return kind === 160 /* Parameter */ - || kind === 162 /* PropertySignature */ - || kind === 163 /* PropertyDeclaration */ - || kind === 164 /* MethodSignature */ - || kind === 165 /* MethodDeclaration */ - || kind === 166 /* Constructor */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 171 /* IndexSignature */ - || kind === 208 /* FunctionExpression */ - || kind === 209 /* ArrowFunction */ - || kind === 221 /* ClassExpression */ - || kind === 232 /* VariableStatement */ - || kind === 251 /* FunctionDeclaration */ - || kind === 252 /* ClassDeclaration */ - || kind === 253 /* InterfaceDeclaration */ - || kind === 254 /* TypeAliasDeclaration */ - || kind === 255 /* EnumDeclaration */ - || kind === 256 /* ModuleDeclaration */ - || kind === 260 /* ImportEqualsDeclaration */ - || kind === 261 /* ImportDeclaration */ - || kind === 266 /* ExportAssignment */ - || kind === 267 /* ExportDeclaration */; + return kind === 161 /* Parameter */ + || kind === 163 /* PropertySignature */ + || kind === 164 /* PropertyDeclaration */ + || kind === 165 /* MethodSignature */ + || kind === 166 /* MethodDeclaration */ + || kind === 167 /* Constructor */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 172 /* IndexSignature */ + || kind === 209 /* FunctionExpression */ + || kind === 210 /* ArrowFunction */ + || kind === 222 /* ClassExpression */ + || kind === 233 /* VariableStatement */ + || kind === 252 /* FunctionDeclaration */ + || kind === 253 /* ClassDeclaration */ + || kind === 254 /* InterfaceDeclaration */ + || kind === 255 /* TypeAliasDeclaration */ + || kind === 256 /* EnumDeclaration */ + || kind === 257 /* ModuleDeclaration */ + || kind === 261 /* ImportEqualsDeclaration */ + || kind === 262 /* ImportDeclaration */ + || kind === 267 /* ExportAssignment */ + || kind === 268 /* ExportDeclaration */; } ts.canHaveModifiers = canHaveModifiers; - /* @internal */ - function isExportModifier(node) { - return node.kind === 92 /* ExportKeyword */; - } - ts.isExportModifier = isExportModifier; - /* @internal */ - function isAsyncModifier(node) { - return node.kind === 129 /* AsyncKeyword */; - } - ts.isAsyncModifier = isAsyncModifier; - /* @internal */ - function isStaticModifier(node) { - return node.kind === 123 /* StaticKeyword */; + ts.isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); + ts.isQuestionOrExclamationToken = ts.or(ts.isQuestionToken, ts.isExclamationToken); + ts.isIdentifierOrThisTypeNode = ts.or(ts.isIdentifier, ts.isThisTypeNode); + ts.isReadonlyKeywordOrPlusOrMinusToken = ts.or(ts.isReadonlyKeyword, ts.isPlusToken, ts.isMinusToken); + ts.isQuestionOrPlusOrMinusToken = ts.or(ts.isQuestionToken, ts.isPlusToken, ts.isMinusToken); + ts.isModuleName = ts.or(ts.isIdentifier, ts.isStringLiteral); + function isLiteralTypeLikeExpression(node) { + var kind = node.kind; + return kind === 103 /* NullKeyword */ + || kind === 109 /* TrueKeyword */ + || kind === 94 /* FalseKeyword */ + || ts.isLiteralExpression(node) + || ts.isPrefixUnaryExpression(node); + } + ts.isLiteralTypeLikeExpression = isLiteralTypeLikeExpression; + function isExponentiationOperator(kind) { + return kind === 42 /* AsteriskAsteriskToken */; + } + function isMultiplicativeOperator(kind) { + return kind === 41 /* AsteriskToken */ + || kind === 43 /* SlashToken */ + || kind === 44 /* PercentToken */; + } + function isMultiplicativeOperatorOrHigher(kind) { + return isExponentiationOperator(kind) + || isMultiplicativeOperator(kind); + } + function isAdditiveOperator(kind) { + return kind === 39 /* PlusToken */ + || kind === 40 /* MinusToken */; + } + function isAdditiveOperatorOrHigher(kind) { + return isAdditiveOperator(kind) + || isMultiplicativeOperatorOrHigher(kind); + } + function isShiftOperator(kind) { + return kind === 47 /* LessThanLessThanToken */ + || kind === 48 /* GreaterThanGreaterThanToken */ + || kind === 49 /* GreaterThanGreaterThanGreaterThanToken */; + } + function isShiftOperatorOrHigher(kind) { + return isShiftOperator(kind) + || isAdditiveOperatorOrHigher(kind); + } + function isRelationalOperator(kind) { + return kind === 29 /* LessThanToken */ + || kind === 32 /* LessThanEqualsToken */ + || kind === 31 /* GreaterThanToken */ + || kind === 33 /* GreaterThanEqualsToken */ + || kind === 101 /* InstanceOfKeyword */ + || kind === 100 /* InKeyword */; + } + function isRelationalOperatorOrHigher(kind) { + return isRelationalOperator(kind) + || isShiftOperatorOrHigher(kind); + } + function isEqualityOperator(kind) { + return kind === 34 /* EqualsEqualsToken */ + || kind === 36 /* EqualsEqualsEqualsToken */ + || kind === 35 /* ExclamationEqualsToken */ + || kind === 37 /* ExclamationEqualsEqualsToken */; + } + function isEqualityOperatorOrHigher(kind) { + return isEqualityOperator(kind) + || isRelationalOperatorOrHigher(kind); + } + function isBitwiseOperator(kind) { + return kind === 50 /* AmpersandToken */ + || kind === 51 /* BarToken */ + || kind === 52 /* CaretToken */; + } + function isBitwiseOperatorOrHigher(kind) { + return isBitwiseOperator(kind) + || isEqualityOperatorOrHigher(kind); + } + // NOTE: The version in utilities includes ExclamationToken, which is not a binary operator. + function isLogicalOperator(kind) { + return kind === 55 /* AmpersandAmpersandToken */ + || kind === 56 /* BarBarToken */; + } + function isLogicalOperatorOrHigher(kind) { + return isLogicalOperator(kind) + || isBitwiseOperatorOrHigher(kind); + } + function isAssignmentOperatorOrHigher(kind) { + return kind === 60 /* QuestionQuestionToken */ + || isLogicalOperatorOrHigher(kind) + || ts.isAssignmentOperator(kind); + } + function isBinaryOperator(kind) { + return isAssignmentOperatorOrHigher(kind) + || kind === 27 /* CommaToken */; + } + function isBinaryOperatorToken(node) { + return isBinaryOperator(node.kind); + } + ts.isBinaryOperatorToken = isBinaryOperatorToken; + var BinaryExpressionState; + (function (BinaryExpressionState) { + /** + * Handles walking into a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function enter(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, outerState) { + var prevUserState = stackIndex > 0 ? userStateStack[stackIndex - 1] : undefined; + ts.Debug.assertEqual(stateStack[stackIndex], enter); + userStateStack[stackIndex] = machine.onEnter(nodeStack[stackIndex], prevUserState, outerState); + stateStack[stackIndex] = nextState(machine, enter); + return stackIndex; + } + BinaryExpressionState.enter = enter; + /** + * Handles walking the `left` side of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function left(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], left); + ts.Debug.assertIsDefined(machine.onLeft); + stateStack[stackIndex] = nextState(machine, left); + var nextNode = machine.onLeft(nodeStack[stackIndex].left, userStateStack[stackIndex], nodeStack[stackIndex]); + if (nextNode) { + checkCircularity(stackIndex, nodeStack, nextNode); + return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode); + } + return stackIndex; + } + BinaryExpressionState.left = left; + /** + * Handles walking the `operatorToken` of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function operator(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], operator); + ts.Debug.assertIsDefined(machine.onOperator); + stateStack[stackIndex] = nextState(machine, operator); + machine.onOperator(nodeStack[stackIndex].operatorToken, userStateStack[stackIndex], nodeStack[stackIndex]); + return stackIndex; + } + BinaryExpressionState.operator = operator; + /** + * Handles walking the `right` side of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function right(machine, stackIndex, stateStack, nodeStack, userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], right); + ts.Debug.assertIsDefined(machine.onRight); + stateStack[stackIndex] = nextState(machine, right); + var nextNode = machine.onRight(nodeStack[stackIndex].right, userStateStack[stackIndex], nodeStack[stackIndex]); + if (nextNode) { + checkCircularity(stackIndex, nodeStack, nextNode); + return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode); + } + return stackIndex; + } + BinaryExpressionState.right = right; + /** + * Handles walking out of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + function exit(machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], exit); + stateStack[stackIndex] = nextState(machine, exit); + var result = machine.onExit(nodeStack[stackIndex], userStateStack[stackIndex]); + if (stackIndex > 0) { + stackIndex--; + if (machine.foldState) { + var side = stateStack[stackIndex] === exit ? "right" : "left"; + userStateStack[stackIndex] = machine.foldState(userStateStack[stackIndex], result, side); + } + } + else { + resultHolder.value = result; + } + return stackIndex; + } + BinaryExpressionState.exit = exit; + /** + * Handles a frame that is already done. + * @returns The `done` state. + */ + function done(_machine, stackIndex, stateStack, _nodeStack, _userStateStack, _resultHolder, _outerState) { + ts.Debug.assertEqual(stateStack[stackIndex], done); + return stackIndex; + } + BinaryExpressionState.done = done; + function nextState(machine, currentState) { + switch (currentState) { + case enter: + if (machine.onLeft) + return left; + // falls through + case left: + if (machine.onOperator) + return operator; + // falls through + case operator: + if (machine.onRight) + return right; + // falls through + case right: return exit; + case exit: return done; + case done: return done; + default: ts.Debug.fail("Invalid state"); + } + } + BinaryExpressionState.nextState = nextState; + function pushStack(stackIndex, stateStack, nodeStack, userStateStack, node) { + stackIndex++; + stateStack[stackIndex] = enter; + nodeStack[stackIndex] = node; + userStateStack[stackIndex] = undefined; + return stackIndex; + } + function checkCircularity(stackIndex, nodeStack, node) { + if (ts.Debug.shouldAssert(2 /* Aggressive */)) { + while (stackIndex >= 0) { + ts.Debug.assert(nodeStack[stackIndex] !== node, "Circular traversal detected."); + stackIndex--; + } + } + } + })(BinaryExpressionState || (BinaryExpressionState = {})); + /** + * Holds state machine handler functions + */ + var BinaryExpressionStateMachine = /** @class */ (function () { + function BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState) { + this.onEnter = onEnter; + this.onLeft = onLeft; + this.onOperator = onOperator; + this.onRight = onRight; + this.onExit = onExit; + this.foldState = foldState; + } + return BinaryExpressionStateMachine; + }()); + function createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState) { + var machine = new BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState); + return trampoline; + function trampoline(node, outerState) { + var resultHolder = { value: undefined }; + var stateStack = [BinaryExpressionState.enter]; + var nodeStack = [node]; + var userStateStack = [undefined]; + var stackIndex = 0; + while (stateStack[stackIndex] !== BinaryExpressionState.done) { + stackIndex = stateStack[stackIndex](machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, outerState); + } + ts.Debug.assertEqual(stackIndex, 0); + return resultHolder.value; + } } - ts.isStaticModifier = isStaticModifier; + ts.createBinaryExpressionTrampoline = createBinaryExpressionTrampoline; })(ts || (ts = {})); var ts; (function (ts) { @@ -27950,19 +28837,19 @@ var ts; * that they appear in the source code. The language service depends on this property to locate nodes by position. */ function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 156 /* LastToken */) { + if (!node || node.kind <= 157 /* LastToken */) { return; } switch (node.kind) { - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -27970,9 +28857,9 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: return visitNode(cbNode, node.expression); - case 160 /* Parameter */: + case 161 /* Parameter */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || @@ -27980,7 +28867,7 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -27988,51 +28875,51 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.initializer); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -28044,374 +28931,390 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return visitNode(cbNode, node.assertsModifier) || visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return visitNodes(cbNode, cbNodes, node.members); - case 178 /* ArrayType */: + case 179 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 179 /* TupleType */: + case 180 /* TupleType */: return visitNodes(cbNode, cbNodes, node.elements); - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: return visitNodes(cbNode, cbNodes, node.types); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return visitNode(cbNode, node.checkType) || visitNode(cbNode, node.extendsType) || visitNode(cbNode, node.trueType) || visitNode(cbNode, node.falseType); - case 185 /* InferType */: + case 186 /* InferType */: return visitNode(cbNode, node.typeParameter); - case 195 /* ImportType */: + case 196 /* ImportType */: return visitNode(cbNode, node.argument) || visitNode(cbNode, node.qualifier) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 186 /* ParenthesizedType */: - case 188 /* TypeOperator */: + case 187 /* ParenthesizedType */: + case 189 /* TypeOperator */: return visitNode(cbNode, node.type); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 190 /* MappedType */: + case 191 /* MappedType */: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.nameType) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 191 /* LiteralType */: + case 192 /* LiteralType */: return visitNode(cbNode, node.literal); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: return visitNodes(cbNode, cbNodes, node.elements); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitNodes(cbNode, cbNodes, node.properties); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || visitNode(cbNode, node.name); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || visitNode(cbNode, node.argumentExpression); - case 203 /* CallExpression */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.template); - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 224 /* AsExpression */: + case 225 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return visitNode(cbNode, node.expression); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return visitNode(cbNode, node.name); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return visitNode(cbNode, node.expression); - case 230 /* Block */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 258 /* ModuleBlock */: return visitNodes(cbNode, cbNodes, node.statements); - case 297 /* SourceFile */: + case 298 /* SourceFile */: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return visitNodes(cbNode, cbNodes, node.declarations); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 240 /* ContinueStatement */: - case 241 /* BreakStatement */: + case 241 /* ContinueStatement */: + case 242 /* BreakStatement */: return visitNode(cbNode, node.label); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return visitNodes(cbNode, cbNodes, node.clauses); - case 284 /* CaseClause */: + case 285 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: return visitNodes(cbNode, cbNodes, node.statements); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 161 /* Decorator */: + case 162 /* Decorator */: return visitNode(cbNode, node.expression); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 291 /* EnumMember */: + case 292 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: return visitNode(cbNode, node.name); - case 264 /* NamedImports */: - case 268 /* NamedExports */: + case 265 /* NamedImports */: + case 269 /* NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 194 /* TemplateLiteralTypeSpan */: + case 195 /* TemplateLiteralTypeSpan */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.literal); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: return visitNodes(cbNode, cbNodes, node.types); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 271 /* MissingDeclaration */: + case 272 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return visitNode(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingFragment); - case 274 /* JsxSelfClosingElement */: - case 275 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 282 /* JsxSpreadAttribute */: + case 283 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 276 /* JsxClosingElement */: + case 277 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 180 /* OptionalType */: - case 181 /* RestType */: - case 301 /* JSDocTypeExpression */: - case 306 /* JSDocNonNullableType */: - case 305 /* JSDocNullableType */: - case 307 /* JSDocOptionalType */: - case 309 /* JSDocVariadicType */: + case 181 /* OptionalType */: + case 182 /* RestType */: + case 302 /* JSDocTypeExpression */: + case 307 /* JSDocNonNullableType */: + case 306 /* JSDocNullableType */: + case 308 /* JSDocOptionalType */: + case 310 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 311 /* JSDocComment */: - return visitNodes(cbNode, cbNodes, node.tags); - case 332 /* JSDocSeeTag */: + case 312 /* JSDocComment */: + return (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) + || visitNodes(cbNode, cbNodes, node.tags); + case 336 /* JSDocSeeTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.name); - case 302 /* JSDocNameReference */: + visitNode(cbNode, node.name) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 303 /* JSDocNameReference */: return visitNode(cbNode, node.name); - case 326 /* JSDocParameterTag */: - case 333 /* JSDocPropertyTag */: + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: return visitNode(cbNode, node.tagName) || (node.isNameFirst ? visitNode(cbNode, node.name) || - visitNode(cbNode, node.typeExpression) + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) : visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.name)); - case 317 /* JSDocAuthorTag */: - return visitNode(cbNode, node.tagName); - case 316 /* JSDocImplementsTag */: + visitNode(cbNode, node.name)) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 320 /* JSDocAuthorTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.class); - case 315 /* JSDocAugmentsTag */: + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 319 /* JSDocImplementsTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.class); - case 330 /* JSDocTemplateTag */: + visitNode(cbNode, node.class) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 318 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 334 /* JSDocTemplateTag */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.constraint) || - visitNodes(cbNode, cbNodes, node.typeParameters); - case 331 /* JSDocTypedefTag */: + visitNodes(cbNode, cbNodes, node.typeParameters) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 335 /* JSDocTypedefTag */: return visitNode(cbNode, node.tagName) || (node.typeExpression && - node.typeExpression.kind === 301 /* JSDocTypeExpression */ + node.typeExpression.kind === 302 /* JSDocTypeExpression */ ? visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName) + visitNode(cbNode, node.fullName) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) : visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression)); - case 324 /* JSDocCallbackTag */: + visitNode(cbNode, node.typeExpression)) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 328 /* JSDocCallbackTag */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression); - case 327 /* JSDocReturnTag */: - case 329 /* JSDocTypeTag */: - case 328 /* JSDocThisTag */: - case 325 /* JSDocEnumTag */: + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 331 /* JSDocReturnTag */: + case 333 /* JSDocTypeTag */: + case 332 /* JSDocThisTag */: + case 329 /* JSDocEnumTag */: return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.typeExpression); - case 313 /* JSDocSignature */: + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 315 /* JSDocSignature */: return ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 312 /* JSDocTypeLiteral */: + case 316 /* JSDocLink */: + return visitNode(cbNode, node.name); + case 314 /* JSDocTypeLiteral */: return ts.forEach(node.jsDocPropertyTags, cbNode); - case 314 /* JSDocTag */: - case 319 /* JSDocClassTag */: - case 320 /* JSDocPublicTag */: - case 321 /* JSDocPrivateTag */: - case 322 /* JSDocProtectedTag */: - case 323 /* JSDocReadonlyTag */: - return visitNode(cbNode, node.tagName); - case 336 /* PartiallyEmittedExpression */: + case 317 /* JSDocTag */: + case 322 /* JSDocClassTag */: + case 323 /* JSDocPublicTag */: + case 324 /* JSDocPrivateTag */: + case 325 /* JSDocProtectedTag */: + case 326 /* JSDocReadonlyTag */: + case 321 /* JSDocDeprecatedTag */: + return visitNode(cbNode, node.tagName) + || (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + case 340 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -28431,62 +29334,58 @@ var ts; * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure. */ function forEachChildRecursively(rootNode, cbNode, cbNodes) { - var stack = [rootNode]; - while (stack.length) { - var parent = stack.pop(); - var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent)); - if (res) { - return res; - } - } - return; - function gatherPossibleChildren(node) { - var children = []; - forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal - return children; - function addWorkItem(n) { - children.unshift(n); - } - } - function visitAllPossibleChildren(parent, children) { - for (var _i = 0, children_5 = children; _i < children_5.length; _i++) { - var child = children_5[_i]; - if (ts.isArray(child)) { - if (cbNodes) { - var res = cbNodes(child, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - } - for (var i = child.length - 1; i >= 0; i--) { - var realChild = child[i]; - var res = cbNode(realChild, parent); - if (res) { - if (res === "skip") - continue; - return res; - } - stack.push(realChild); - } - } - else { - stack.push(child); - var res = cbNode(child, parent); + var queue = gatherPossibleChildren(rootNode); + var parents = []; // tracks parent references for elements in queue + while (parents.length < queue.length) { + parents.push(rootNode); + } + while (queue.length !== 0) { + var current = queue.pop(); + var parent = parents.pop(); + if (ts.isArray(current)) { + if (cbNodes) { + var res = cbNodes(current, parent); if (res) { if (res === "skip") continue; return res; } } + for (var i = current.length - 1; i >= 0; --i) { + queue.push(current[i]); + parents.push(parent); + } + } + else { + var res = cbNode(current, parent); + if (res) { + if (res === "skip") + continue; + return res; + } + if (current.kind >= 158 /* FirstNode */) { + // add children in reverse order to the queue, so popping gives the first child + for (var _i = 0, _a = gatherPossibleChildren(current); _i < _a.length; _i++) { + var child = _a[_i]; + queue.push(child); + parents.push(current); + } + } } } } ts.forEachChildRecursively = forEachChildRecursively; + function gatherPossibleChildren(node) { + var children = []; + forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal + return children; + function addWorkItem(n) { + children.unshift(n); + } + } function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } - ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeParse"); var result; ts.perfLogger.logStartParseSourceFile(fileName); @@ -28499,7 +29398,7 @@ var ts; ts.perfLogger.logStopParseSourceFile(); ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } ts.createSourceFile = createSourceFile; @@ -28681,11 +29580,12 @@ var ts; // attached to the EOF token. var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + var _a; if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); if (scriptKind === 6 /* JSON */) { var result_3 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); - ts.convertToObjectWorker(result_3, result_3.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + ts.convertToObjectWorker(result_3, (_a = result_3.statements[0]) === null || _a === void 0 ? void 0 : _a.expression, result_3.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); result_3.referencedFiles = ts.emptyArray; result_3.typeReferenceDirectives = ts.emptyArray; result_3.libReferenceDirectives = ts.emptyArray; @@ -28725,35 +29625,54 @@ var ts; endOfFileToken = parseTokenNode(); } else { - var expression = void 0; - switch (token()) { - case 22 /* OpenBracketToken */: - expression = parseArrayLiteralExpression(); - break; - case 109 /* TrueKeyword */: - case 94 /* FalseKeyword */: - case 103 /* NullKeyword */: - expression = parseTokenNode(); - break; - case 40 /* MinusToken */: - if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) { - expression = parsePrefixUnaryExpression(); - } - else { - expression = parseObjectLiteralExpression(); - } - break; - case 8 /* NumericLiteral */: - case 10 /* StringLiteral */: - if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) { - expression = parseLiteralNode(); + // Loop and synthesize an ArrayLiteralExpression if there are more than + // one top-level expressions to ensure all input text is consumed. + var expressions = void 0; + while (token() !== 1 /* EndOfFileToken */) { + var expression_1 = void 0; + switch (token()) { + case 22 /* OpenBracketToken */: + expression_1 = parseArrayLiteralExpression(); break; + case 109 /* TrueKeyword */: + case 94 /* FalseKeyword */: + case 103 /* NullKeyword */: + expression_1 = parseTokenNode(); + break; + case 40 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) { + expression_1 = parsePrefixUnaryExpression(); + } + else { + expression_1 = parseObjectLiteralExpression(); + } + break; + case 8 /* NumericLiteral */: + case 10 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) { + expression_1 = parseLiteralNode(); + break; + } + // falls through + default: + expression_1 = parseObjectLiteralExpression(); + break; + } + // Error recovery: collect multiple top-level expressions + if (expressions && ts.isArray(expressions)) { + expressions.push(expression_1); + } + else if (expressions) { + expressions = [expressions, expression_1]; + } + else { + expressions = expression_1; + if (token() !== 1 /* EndOfFileToken */) { + parseErrorAtCurrentToken(ts.Diagnostics.Unexpected_token); } - // falls through - default: - expression = parseObjectLiteralExpression(); - break; + } } + var expression = ts.isArray(expressions) ? finishNode(factory.createArrayLiteralExpression(expressions), pos) : ts.Debug.checkDefined(expressions); var statement = factory.createExpressionStatement(expression); finishNode(statement, pos); statements = createNodeArray([statement], pos); @@ -28948,7 +29867,7 @@ var ts; return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements)); function containsPossibleTopLevelAwait(node) { return !(node.flags & 32768 /* AwaitContext */) - && !!(node.transformFlags & 8388608 /* ContainsPossibleTopLevelAwait */); + && !!(node.transformFlags & 16777216 /* ContainsPossibleTopLevelAwait */); } function findNextStatementWithAwait(statements, start) { for (var i = start; i < statements.length; i++) { @@ -28989,7 +29908,7 @@ var ts; ts.setTextRangePosWidth(sourceFile, 0, sourceText.length); setExternalModuleIndicator(sourceFile); // If we parsed this as an external module, it may contain top-level await - if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 8388608 /* ContainsPossibleTopLevelAwait */) { + if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 16777216 /* ContainsPossibleTopLevelAwait */) { sourceFile = reparseTopLevelAwait(sourceFile); } sourceFile.text = sourceText; @@ -29360,7 +30279,7 @@ var ts; ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, "", "", /*templateFlags*/ undefined) : kind === 8 /* NumericLiteral */ ? factory.createNumericLiteral("", /*numericLiteralFlags*/ undefined) : kind === 10 /* StringLiteral */ ? factory.createStringLiteral("", /*isSingleQuote*/ undefined) : - kind === 271 /* MissingDeclaration */ ? factory.createMissingDeclaration() : + kind === 272 /* MissingDeclaration */ ? factory.createMissingDeclaration() : factory.createToken(kind); return finishNode(result, pos); } @@ -29375,8 +30294,8 @@ var ts; // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for // each identifier in order to reduce memory consumption. function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) { - identifierCount++; if (isIdentifier) { + identifierCount++; var pos = getNodePos(); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker var originalKeywordKind = token(); @@ -29388,6 +30307,11 @@ var ts; parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); return createIdentifier(/*isIdentifier*/ true); } + if (token() === 0 /* Unknown */ && scanner.tryScan(function () { return scanner.reScanInvalidIdentifier() === 78 /* Identifier */; })) { + // Scanner has already recorded an 'Invalid character' error, so no need to add another from the parser. + return createIdentifier(/*isIdentifier*/ true); + } + identifierCount++; // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; var isReservedWord = scanner.isReservedWord(); @@ -29742,8 +30666,7 @@ var ts; var listPos = getNodePos(); while (!isListTerminator(kind)) { if (isListElement(kind, /*inErrorRecovery*/ false)) { - var element = parseListElement(kind, parseElement); - list.push(element); + list.push(parseListElement(kind, parseElement)); continue; } if (abortParsingListOrMoveToNextToken(kind)) { @@ -29893,14 +30816,14 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 166 /* Constructor */: - case 171 /* IndexSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 163 /* PropertyDeclaration */: - case 229 /* SemicolonClassElement */: + case 167 /* Constructor */: + case 172 /* IndexSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 230 /* SemicolonClassElement */: return true; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. @@ -29915,8 +30838,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: return true; } } @@ -29925,58 +30848,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 232 /* VariableStatement */: - case 230 /* Block */: - case 234 /* IfStatement */: - case 233 /* ExpressionStatement */: - case 246 /* ThrowStatement */: - case 242 /* ReturnStatement */: - case 244 /* SwitchStatement */: - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 237 /* ForStatement */: - case 236 /* WhileStatement */: - case 243 /* WithStatement */: - case 231 /* EmptyStatement */: - case 247 /* TryStatement */: - case 245 /* LabeledStatement */: - case 235 /* DoStatement */: - case 248 /* DebuggerStatement */: - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 252 /* FunctionDeclaration */: + case 233 /* VariableStatement */: + case 231 /* Block */: + case 235 /* IfStatement */: + case 234 /* ExpressionStatement */: + case 247 /* ThrowStatement */: + case 243 /* ReturnStatement */: + case 245 /* SwitchStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 238 /* ForStatement */: + case 237 /* WhileStatement */: + case 244 /* WithStatement */: + case 232 /* EmptyStatement */: + case 248 /* TryStatement */: + case 246 /* LabeledStatement */: + case 236 /* DoStatement */: + case 249 /* DebuggerStatement */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 291 /* EnumMember */; + return node.kind === 292 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 170 /* ConstructSignature */: - case 164 /* MethodSignature */: - case 171 /* IndexSignature */: - case 162 /* PropertySignature */: - case 169 /* CallSignature */: + case 171 /* ConstructSignature */: + case 165 /* MethodSignature */: + case 172 /* IndexSignature */: + case 163 /* PropertySignature */: + case 170 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 249 /* VariableDeclaration */) { + if (node.kind !== 250 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -29997,7 +30920,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 160 /* Parameter */) { + if (node.kind !== 161 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -30278,14 +31201,14 @@ var ts; // If true, we should abort parsing an error function. function typeHasArrowFunctionBlockingParseError(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return ts.nodeIsMissing(node.typeName); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: { + case 175 /* FunctionType */: + case 176 /* ConstructorType */: { var _a = node, parameters = _a.parameters, type = _a.type; return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); } - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return typeHasArrowFunctionBlockingParseError(node.type); default: return false; @@ -30466,19 +31389,21 @@ var ts; function parseParameterWorker(inOuterAwaitContext) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); + // FormalParameter [Yield,Await]: + // BindingElement[?Yield,?Await] + // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. + var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); if (token() === 107 /* ThisKeyword */) { - var node_1 = factory.createParameterDeclaration( - /*decorators*/ undefined, + var node_1 = factory.createParameterDeclaration(decorators, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), /*questionToken*/ undefined, parseTypeAnnotation(), /*initializer*/ undefined); + if (decorators) { + parseErrorAtRange(decorators[0], ts.Diagnostics.Decorators_may_not_be_applied_to_this_parameters); + } return withJSDoc(finishNode(node_1, pos), hasJSDoc); } - // FormalParameter [Yield,Await]: - // BindingElement[?Yield,?Await] - // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. - var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); var savedTopLevel = topLevel; topLevel = false; var modifiers = parseModifiers(); @@ -30565,14 +31490,14 @@ var ts; function parseSignatureMember(kind) { var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); - if (kind === 170 /* ConstructSignature */) { + if (kind === 171 /* ConstructSignature */) { parseExpected(102 /* NewKeyword */); } var typeParameters = parseTypeParameters(); var parameters = parseParameters(4 /* Type */); var type = parseReturnType(58 /* ColonToken */, /*isType*/ true); parseTypeMemberSemicolon(); - var node = kind === 169 /* CallSignature */ + var node = kind === 170 /* CallSignature */ ? factory.createCallSignature(typeParameters, parameters, type) : factory.createConstructSignature(typeParameters, parameters, type); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -30663,7 +31588,10 @@ var ts; } function isTypeMemberStart() { // Return true if we have the start of a signature member - if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) { + if (token() === 20 /* OpenParenToken */ || + token() === 29 /* LessThanToken */ || + token() === 134 /* GetKeyword */ || + token() === 146 /* SetKeyword */) { return true; } var idToken = false; @@ -30695,14 +31623,20 @@ var ts; } function parseTypeMember() { if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) { - return parseSignatureMember(169 /* CallSignature */); + return parseSignatureMember(170 /* CallSignature */); } if (token() === 102 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(170 /* ConstructSignature */); + return parseSignatureMember(171 /* ConstructSignature */); } var pos = getNodePos(); var hasJSDoc = hasPrecedingJSDocComment(); var modifiers = parseModifiers(); + if (parseContextualModifier(134 /* GetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 168 /* GetAccessor */); + } + if (parseContextualModifier(146 /* SetKeyword */)) { + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, 169 /* SetAccessor */); + } if (isIndexSignature()) { return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers); } @@ -31735,7 +32669,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand, pos); } function isInOrOfKeyword(t) { - return t === 100 /* InKeyword */ || t === 156 /* OfKeyword */; + return t === 100 /* InKeyword */ || t === 157 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand, pos) { while (true) { @@ -31875,7 +32809,7 @@ var ts; if (token() === 42 /* AsteriskAsteriskToken */) { var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); var end = simpleUnaryExpression.end; - if (simpleUnaryExpression.kind === 206 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 207 /* TypeAssertionExpression */) { parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { @@ -32126,7 +33060,7 @@ var ts; var pos = getNodePos(); var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 275 /* JsxOpeningElement */) { + if (opening.kind === 276 /* JsxOpeningElement */) { var children = parseJsxChildren(opening); var closingElement = parseJsxClosingElement(inExpressionContext); if (!tagNamesAreEquivalent(opening.tagName, closingElement.tagName)) { @@ -32134,11 +33068,11 @@ var ts; } result = finishNode(factory.createJsxElement(opening, children, closingElement), pos); } - else if (opening.kind === 278 /* JsxOpeningFragment */) { + else if (opening.kind === 279 /* JsxOpeningFragment */) { result = finishNode(factory.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos); } else { - ts.Debug.assert(opening.kind === 274 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 275 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -32638,10 +33572,10 @@ var ts; var decorators = parseDecorators(); var modifiers = parseModifiers(); if (parseContextualModifier(134 /* GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167 /* GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* GetAccessor */); } if (parseContextualModifier(146 /* SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 169 /* SetAccessor */); } var asteriskToken = parseOptionalToken(41 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); @@ -32759,6 +33693,7 @@ var ts; // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); var openBracePosition = scanner.getTokenPos(); if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { var multiLine = scanner.hasPrecedingLineBreak(); @@ -32769,11 +33704,16 @@ var ts; ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); } } - return finishNode(factory.createBlock(statements, multiLine), pos); + var result = withJSDoc(finishNode(factory.createBlock(statements, multiLine), pos), hasJSDoc); + if (token() === 62 /* EqualsToken */) { + parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses); + nextToken(); + } + return result; } else { var statements = createMissingList(); - return finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos); + return withJSDoc(finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos), hasJSDoc); } } function parseFunctionBlock(flags, diagnosticMessage) { @@ -32800,21 +33740,24 @@ var ts; } function parseEmptyStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(26 /* SemicolonToken */); - return finishNode(factory.createEmptyStatement(), pos); + return withJSDoc(finishNode(factory.createEmptyStatement(), pos), hasJSDoc); } function parseIfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(98 /* IfKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var thenStatement = parseStatement(); var elseStatement = parseOptional(90 /* ElseKeyword */) ? parseStatement() : undefined; - return finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos); + return withJSDoc(finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc); } function parseDoStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(89 /* DoKeyword */); var statement = parseStatement(); parseExpected(114 /* WhileKeyword */); @@ -32826,19 +33769,21 @@ var ts; // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. parseOptional(26 /* SemicolonToken */); - return finishNode(factory.createDoStatement(statement, expression), pos); + return withJSDoc(finishNode(factory.createDoStatement(statement, expression), pos), hasJSDoc); } function parseWhileStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(114 /* WhileKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var statement = parseStatement(); - return finishNode(factory.createWhileStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWhileStatement(expression, statement), pos), hasJSDoc); } function parseForOrForInOrForOfStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(96 /* ForKeyword */); var awaitToken = parseOptionalToken(130 /* AwaitKeyword */); parseExpected(20 /* OpenParenToken */); @@ -32852,7 +33797,7 @@ var ts; } } var node; - if (awaitToken ? parseExpected(156 /* OfKeyword */) : parseOptional(156 /* OfKeyword */)) { + if (awaitToken ? parseExpected(157 /* OfKeyword */) : parseOptional(157 /* OfKeyword */)) { var expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(21 /* CloseParenToken */); node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement()); @@ -32874,33 +33819,36 @@ var ts; parseExpected(21 /* CloseParenToken */); node = factory.createForStatement(initializer, condition, incrementor, parseStatement()); } - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseBreakOrContinueStatement(kind) { var pos = getNodePos(); - parseExpected(kind === 241 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */); + var hasJSDoc = hasPrecedingJSDocComment(); + parseExpected(kind === 242 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */); var label = canParseSemicolon() ? undefined : parseIdentifier(); parseSemicolon(); - var node = kind === 241 /* BreakStatement */ + var node = kind === 242 /* BreakStatement */ ? factory.createBreakStatement(label) : factory.createContinueStatement(label); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseReturnStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(104 /* ReturnKeyword */); var expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression); parseSemicolon(); - return finishNode(factory.createReturnStatement(expression), pos); + return withJSDoc(finishNode(factory.createReturnStatement(expression), pos), hasJSDoc); } function parseWithStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(115 /* WithKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement); - return finishNode(factory.createWithStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWithStatement(expression, statement), pos), hasJSDoc); } function parseCaseClause() { var pos = getNodePos(); @@ -32929,17 +33877,19 @@ var ts; } function parseSwitchStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(106 /* SwitchKeyword */); parseExpected(20 /* OpenParenToken */); var expression = allowInAnd(parseExpression); parseExpected(21 /* CloseParenToken */); var caseBlock = parseCaseBlock(); - return finishNode(factory.createSwitchStatement(expression, caseBlock), pos); + return withJSDoc(finishNode(factory.createSwitchStatement(expression, caseBlock), pos), hasJSDoc); } function parseThrowStatement() { // ThrowStatement[Yield] : // throw [no LineTerminator here]Expression[In, ?Yield]; var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(108 /* ThrowKeyword */); // Because of automatic semicolon insertion, we need to report error if this // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' @@ -32952,11 +33902,12 @@ var ts; expression = finishNode(factory.createIdentifier(""), getNodePos()); } parseSemicolon(); - return finishNode(factory.createThrowStatement(expression), pos); + return withJSDoc(finishNode(factory.createThrowStatement(expression), pos), hasJSDoc); } // TODO: Review for error recovery function parseTryStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(110 /* TryKeyword */); var tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); var catchClause = token() === 82 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -32967,7 +33918,7 @@ var ts; parseExpected(95 /* FinallyKeyword */); finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } - return finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos); + return withJSDoc(finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); } function parseCatchClause() { var pos = getNodePos(); @@ -32986,9 +33937,10 @@ var ts; } function parseDebuggerStatement() { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); parseExpected(86 /* DebuggerKeyword */); parseSemicolon(); - return finishNode(factory.createDebuggerStatement(), pos); + return withJSDoc(finishNode(factory.createDebuggerStatement(), pos), hasJSDoc); } function parseExpressionOrLabeledStatement() { // Avoiding having to do the lookahead for a labeled statement by just trying to parse @@ -33196,9 +34148,9 @@ var ts; case 96 /* ForKeyword */: return parseForOrForInOrForOfStatement(); case 85 /* ContinueKeyword */: - return parseBreakOrContinueStatement(240 /* ContinueStatement */); + return parseBreakOrContinueStatement(241 /* ContinueStatement */); case 80 /* BreakKeyword */: - return parseBreakOrContinueStatement(241 /* BreakStatement */); + return parseBreakOrContinueStatement(242 /* BreakStatement */); case 104 /* ReturnKeyword */: return parseReturnStatement(); case 115 /* WithKeyword */: @@ -33318,7 +34270,7 @@ var ts; if (decorators || modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - var missing = createMissingNode(271 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var missing = createMissingNode(272 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); ts.setTextRangePos(missing, pos); missing.decorators = decorators; missing.modifiers = modifiers; @@ -33400,6 +34352,7 @@ var ts; } function parseVariableDeclaration(allowExclamation) { var pos = getNodePos(); + var hasJSDoc = hasPrecedingJSDocComment(); var name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations); var exclamationToken; if (allowExclamation && name.kind === 78 /* Identifier */ && @@ -33409,7 +34362,7 @@ var ts; var type = parseTypeAnnotation(); var initializer = isInOrOfKeyword(token()) ? undefined : parseInitializer(); var node = factory.createVariableDeclaration(name, exclamationToken, type, initializer); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseVariableDeclarationList(inForStatementInitializer) { var pos = getNodePos(); @@ -33437,7 +34390,7 @@ var ts; // this context. // The checker will then give an error that there is an empty declaration list. var declarations; - if (token() === 156 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 157 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { declarations = createMissingList(); } else { @@ -33541,12 +34494,12 @@ var ts; var parameters = parseParameters(0 /* None */); var type = parseReturnType(58 /* ColonToken */, /*isType*/ false); var body = parseFunctionBlockOrSemicolon(0 /* None */); - var node = kind === 167 /* GetAccessor */ + var node = kind === 168 /* GetAccessor */ ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body); // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors node.typeParameters = typeParameters; - if (type && node.kind === 168 /* SetAccessor */) + if (type && node.kind === 169 /* SetAccessor */) node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -33689,10 +34642,10 @@ var ts; var decorators = parseDecorators(); var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); if (parseContextualModifier(134 /* GetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167 /* GetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* GetAccessor */); } if (parseContextualModifier(146 /* SetKeyword */)) { - return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* SetAccessor */); + return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 169 /* SetAccessor */); } if (token() === 132 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) { var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers); @@ -33731,10 +34684,10 @@ var ts; return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, 221 /* ClassExpression */); + return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, 222 /* ClassExpression */); } function parseClassDeclaration(pos, hasJSDoc, decorators, modifiers) { - return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 252 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 253 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, kind) { var savedAwaitContext = inAwaitContext(); @@ -33756,7 +34709,7 @@ var ts; members = createMissingList(); } setAwaitContext(savedAwaitContext); - var node = kind === 252 /* ClassDeclaration */ + var node = kind === 253 /* ClassDeclaration */ ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -33995,7 +34948,7 @@ var ts; var namedBindings; if (!identifier || parseOptional(27 /* CommaToken */)) { - namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(264 /* NamedImports */); + namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(265 /* NamedImports */); } return finishNode(factory.createImportClause(isTypeOnly, identifier, namedBindings), pos); } @@ -34043,16 +34996,16 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - var node = kind === 264 /* NamedImports */ + var node = kind === 265 /* NamedImports */ ? factory.createNamedImports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseImportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */)) : factory.createNamedExports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */)); return finishNode(node, pos); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(270 /* ExportSpecifier */); + return parseImportOrExportSpecifier(271 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(265 /* ImportSpecifier */); + return parseImportOrExportSpecifier(266 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var pos = getNodePos(); @@ -34079,10 +35032,10 @@ var ts; else { name = identifierName; } - if (kind === 265 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + if (kind === 266 /* ImportSpecifier */ && checkIdentifierIsKeyword) { parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } - var node = kind === 265 /* ImportSpecifier */ + var node = kind === 266 /* ImportSpecifier */ ? factory.createImportSpecifier(propertyName, name) : factory.createExportSpecifier(propertyName, name); return finishNode(node, pos); @@ -34105,7 +35058,7 @@ var ts; moduleSpecifier = parseModuleSpecifier(); } else { - exportClause = parseNamedImportsOrExports(268 /* NamedExports */); + exportClause = parseNamedImportsOrExports(269 /* NamedExports */); // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. @@ -34294,7 +35247,10 @@ var ts; var tags; var tagsPos; var tagsEnd; + var linkEnd; + var commentsPos; var comments = []; + var parts = []; // + 3 for leading /**, - 5 in total for /** */ return scanner.scanRange(start + 3, length - 5, function () { // Initially we can parse out a tag. We also have seen a starting asterisk. @@ -34323,6 +35279,8 @@ var ts; case 59 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingWhitespace(comments); + if (!commentsPos) + commentsPos = getNodePos(); addTag(parseTag(indent)); // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning @@ -34365,6 +35323,22 @@ var ts; break; case 1 /* EndOfFileToken */: break loop; + case 18 /* OpenBraceToken */: + state = 2 /* SavingComments */; + var commentEnd = scanner.getStartPos(); + var linkStart = scanner.getTextPos() - 1; + var link = parseJSDocLink(linkStart); + if (link) { + if (!linkEnd) { + removeLeadingNewlines(comments); + } + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : start, commentEnd)); + parts.push(link); + comments = []; + linkEnd = scanner.getTextPos(); + break; + } + // fallthrough if it's not a {@link sequence default: // 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 @@ -34375,9 +35349,14 @@ var ts; } nextTokenJSDoc(); } - removeLeadingNewlines(comments); removeTrailingWhitespace(comments); - return createJSDocComment(); + if (parts.length && comments.length) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : start, commentsPos)); + } + if (parts.length && tags) + ts.Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); + var tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); + return finishNode(factory.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : comments.length ? comments.join("") : undefined, tagsArray), start, end); }); function removeLeadingNewlines(comments) { while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { @@ -34389,11 +35368,6 @@ var ts; comments.pop(); } } - function createJSDocComment() { - var comment = comments.length ? comments.join("") : undefined; - var tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); - return finishNode(factory.createJSDocComment(comment, tagsArray), start, end); - } function isNextNonwhitespaceTokenEndOfFile() { // We must use infinite lookahead, as there could be any number of newlines :( while (true) { @@ -34473,6 +35447,9 @@ var ts; case "readonly": tag = parseSimpleTag(start, factory.createJSDocReadonlyTag, tagName, margin, indentText); break; + case "override": + tag = parseSimpleTag(start, factory.createJSDocOverrideTag, tagName, margin, indentText); + break; case "deprecated": hasDeprecatedTag = true; tag = parseSimpleTag(start, factory.createJSDocDeprecatedTag, tagName, margin, indentText); @@ -34520,8 +35497,12 @@ var ts; return parseTagComments(margin, indentText.slice(margin)); } function parseTagComments(indent, initialMargin) { + var commentsPos = getNodePos(); var comments = []; + var parts = []; + var linkEnd; var state = 0 /* BeginningOfLine */; + var previousWhitespace = true; var margin; function pushComment(text) { if (!margin) { @@ -34547,7 +35528,9 @@ var ts; indent = 0; break; case 59 /* AtToken */: - if (state === 3 /* SavingBackticks */) { + if (state === 3 /* SavingBackticks */ + || state === 2 /* SavingComments */ && (!previousWhitespace || lookAhead(isNextJSDocTokenWhitespace))) { + // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace or not before whitespace comments.push(scanner.getTokenText()); break; } @@ -34571,13 +35554,18 @@ var ts; break; case 18 /* OpenBraceToken */: state = 2 /* SavingComments */; - if (lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) { - pushComment(scanner.getTokenText()); - nextTokenJSDoc(); + var commentEnd = scanner.getStartPos(); + var linkStart = scanner.getTextPos() - 1; + var link = parseJSDocLink(linkStart); + if (link) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : commentsPos, commentEnd)); + parts.push(link); + comments = []; + linkEnd = scanner.getTextPos(); + } + else { pushComment(scanner.getTokenText()); - nextTokenJSDoc(); } - pushComment(scanner.getTokenText()); break; case 61 /* BacktickToken */: if (state === 3 /* SavingBackticks */) { @@ -34604,15 +35592,51 @@ var ts; pushComment(scanner.getTokenText()); break; } + previousWhitespace = token() === 5 /* WhitespaceTrivia */; tok = nextTokenJSDoc(); } removeLeadingNewlines(comments); removeTrailingWhitespace(comments); - return comments.length === 0 ? undefined : comments.join(""); + if (parts.length) { + if (comments.length) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd !== null && linkEnd !== void 0 ? linkEnd : commentsPos)); + } + return createNodeArray(parts, commentsPos, scanner.getTextPos()); + } + else if (comments.length) { + return comments.join(""); + } + } + function isNextJSDocTokenWhitespace() { + var next = nextTokenJSDoc(); + return next === 5 /* WhitespaceTrivia */ || next === 4 /* NewLineTrivia */; + } + function parseJSDocLink(start) { + if (!tryParse(parseJSDocLinkPrefix)) { + return undefined; + } + nextTokenJSDoc(); // start at token after link, then skip any whitespace + skipWhitespace(); + // parseEntityName logs an error for non-identifier, so create a MissingNode ourselves to avoid the error + var name = ts.tokenIsIdentifierOrKeyword(token()) + ? parseEntityName(/*allowReservedWords*/ true) + : undefined; + var text = []; + while (token() !== 19 /* CloseBraceToken */ && token() !== 4 /* NewLineTrivia */ && token() !== 1 /* EndOfFileToken */) { + text.push(scanner.getTokenText()); + nextTokenJSDoc(); + } + return finishNode(factory.createJSDocLink(name, text.join("")), start, scanner.getTextPos()); + } + function parseJSDocLinkPrefix() { + skipWhitespaceOrAsterisk(); + return token() === 18 /* OpenBraceToken */ + && nextTokenJSDoc() === 59 /* AtToken */ + && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) + && scanner.getTokenValue() === "link"; } function parseUnknownTag(start, tagName, indent, indentText) { - var end = getNodePos(); - return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function addTag(tag) { if (!tag) { @@ -34657,7 +35681,7 @@ var ts; switch (node.kind) { case 145 /* ObjectKeyword */: return true; - case 178 /* ArrayType */: + case 179 /* ArrayType */: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments; @@ -34668,11 +35692,11 @@ var ts; var isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; - skipWhitespace(); - if (isNameFirst) { + var indentText = skipWhitespaceOrAsterisk(); + if (isNameFirst && !lookAhead(parseJSDocLinkPrefix)) { typeExpression = tryParseTypeExpression(); } - var comment = parseTagComments(indent + scanner.getStartPos() - start); + var comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; @@ -34689,12 +35713,12 @@ var ts; var child = void 0; var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { - if (child.kind === 326 /* JSDocParameterTag */ || child.kind === 333 /* JSDocPropertyTag */) { + if (child.kind === 330 /* JSDocParameterTag */ || child.kind === 337 /* JSDocPropertyTag */) { children = ts.append(children, child); } } if (children) { - var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 178 /* ArrayType */), pos); + var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 179 /* ArrayType */), pos); return finishNode(factory.createJSDocTypeExpression(literal), pos); } } @@ -34704,27 +35728,34 @@ var ts; parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeExpression = tryParseTypeExpression(); - var end = getNodePos(); - return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function parseTypeTag(start, tagName, indent, indentText) { if (ts.some(tags, ts.isJSDocTypeTag)) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); - var end = getNodePos(); - var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined; - return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start, end); + var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; + return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start); } function parseSeeTag(start, tagName, indent, indentText) { - var nameExpression = parseJSDocNameReference(); - var end = getNodePos(); - var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined; - return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start, end); + var isLink = lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"; }); + var nameExpression = isLink ? undefined : parseJSDocNameReference(); + var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; + return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start); } function parseAuthorTag(start, tagName, indent, indentText) { - var comments = parseAuthorNameAndEmail() + (parseTrailingTagComments(start, end, indent, indentText) || ""); - return finishNode(factory.createJSDocAuthorTag(tagName, comments || undefined), start); + var commentStart = getNodePos(); + var textOnly = parseAuthorNameAndEmail(); + var commentEnd = scanner.getStartPos(); + var comments = parseTrailingTagComments(start, commentEnd, indent, indentText); + if (!comments) { + commentEnd = scanner.getStartPos(); + } + var allParts = typeof comments !== "string" + ? createNodeArray(ts.concatenate([finishNode(textOnly, commentStart, commentEnd)], comments), commentStart) // cast away readonly + : textOnly.text + comments; + return finishNode(factory.createJSDocAuthorTag(tagName, allParts), start); } function parseAuthorNameAndEmail() { var comments = []; @@ -34745,17 +35776,15 @@ var ts; comments.push(scanner.getTokenText()); token = nextTokenJSDoc(); } - return comments.join(""); + return factory.createJSDocText(comments.join("")); } function parseImplementsTag(start, tagName, margin, indentText) { var className = parseExpressionWithTypeArgumentsForAugments(); - var end = getNodePos(); - return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseAugmentsTag(start, tagName, margin, indentText) { var className = parseExpressionWithTypeArgumentsForAugments(); - var end = getNodePos(); - return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseExpressionWithTypeArgumentsForAugments() { var usedBrace = parseOptional(18 /* OpenBraceToken */); @@ -34779,20 +35808,17 @@ var ts; return node; } function parseSimpleTag(start, createTag, tagName, margin, indentText) { - var end = getNodePos(); - return finishNode(createTag(tagName, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(createTag(tagName, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseThisTag(start, tagName, margin, indentText) { var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); - var end = getNodePos(); - return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseEnumTag(start, tagName, margin, indentText) { var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); - var end = getNodePos(); - return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseTypedefTag(start, tagName, indent, indentText) { var _a; @@ -34809,7 +35835,7 @@ var ts; var hasChildren = false; while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { hasChildren = true; - if (child.kind === 329 /* JSDocTypeTag */) { + if (child.kind === 333 /* JSDocTypeTag */) { if (childTypeTag) { parseErrorAtCurrentToken(ts.Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags); var lastError = ts.lastOrUndefined(parseDiagnostics); @@ -34827,7 +35853,7 @@ var ts; } } if (hasChildren) { - var isArrayType = typeExpression && typeExpression.type.kind === 178 /* ArrayType */; + var isArrayType = typeExpression && typeExpression.type.kind === 179 /* ArrayType */; var jsdocTypeLiteral = factory.createJSDocTypeLiteral(jsDocPropertyTags, isArrayType); typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : @@ -34880,17 +35906,16 @@ var ts; var returnTag = tryParse(function () { if (parseOptionalJsdoc(59 /* AtToken */)) { var tag = parseTag(indent); - if (tag && tag.kind === 327 /* JSDocReturnTag */) { + if (tag && tag.kind === 331 /* JSDocReturnTag */) { return tag; } } }); var typeExpression = finishNode(factory.createJSDocSignature(/*typeParameters*/ undefined, parameters, returnTag), start); - var end = getNodePos(); if (!comment) { - comment = parseTrailingTagComments(start, end, indent, indentText); + comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); } - return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start, end); + return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start); } function escapedTextsEqual(a, b) { while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { @@ -34915,7 +35940,7 @@ var ts; case 59 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target, indent); - if (child && (child.kind === 326 /* JSDocParameterTag */ || child.kind === 333 /* JSDocPropertyTag */) && + if (child && (child.kind === 330 /* JSDocParameterTag */ || child.kind === 337 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -34972,6 +35997,9 @@ var ts; function parseTemplateTagTypeParameter() { var typeParameterPos = getNodePos(); var name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); + if (ts.nodeIsMissing(name)) { + return undefined; + } return finishNode(factory.createTypeParameterDeclaration(name, /*constraint*/ undefined, /*defaultType*/ undefined), typeParameterPos); } function parseTemplateTagTypeParameters() { @@ -34979,7 +36007,10 @@ var ts; var typeParameters = []; do { skipWhitespace(); - typeParameters.push(parseTemplateTagTypeParameter()); + var node = parseTemplateTagTypeParameter(); + if (node !== undefined) { + typeParameters.push(node); + } skipWhitespaceOrAsterisk(); } while (parseOptionalJsdoc(27 /* CommaToken */)); return createNodeArray(typeParameters, pos); @@ -34998,8 +36029,7 @@ var ts; // TODO: Consider only parsing a single type parameter if there is a constraint. var constraint = token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; var typeParameters = parseTemplateTagTypeParameters(); - var end = getNodePos(); - return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function parseOptionalJsdoc(t) { if (token() === t) { @@ -35814,6 +36844,7 @@ var ts; ["es2018", "lib.es2018.d.ts"], ["es2019", "lib.es2019.d.ts"], ["es2020", "lib.es2020.d.ts"], + ["es2021", "lib.es2021.d.ts"], ["esnext", "lib.esnext.d.ts"], // Host only ["dom", "lib.dom.d.ts"], @@ -35853,14 +36884,17 @@ var ts; ["es2020.string", "lib.es2020.string.d.ts"], ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"], ["es2020.intl", "lib.es2020.intl.d.ts"], + ["es2021.promise", "lib.es2021.promise.d.ts"], + ["es2021.string", "lib.es2021.string.d.ts"], + ["es2021.weakref", "lib.es2021.weakref.d.ts"], ["esnext.array", "lib.es2019.array.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"], ["esnext.intl", "lib.esnext.intl.d.ts"], ["esnext.bigint", "lib.es2020.bigint.d.ts"], - ["esnext.string", "lib.esnext.string.d.ts"], - ["esnext.promise", "lib.esnext.promise.d.ts"], - ["esnext.weakref", "lib.esnext.weakref.d.ts"] + ["esnext.string", "lib.es2021.string.d.ts"], + ["esnext.promise", "lib.es2021.promise.d.ts"], + ["esnext.weakref", "lib.es2021.weakref.d.ts"] ]; /** * An array of supported "lib" reference file names used to determine the order for inclusion @@ -35884,11 +36918,12 @@ var ts; fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval, prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval, dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling, + fixedchunksizepolling: ts.WatchFileKind.FixedChunkSizePolling, usefsevents: ts.WatchFileKind.UseFsEvents, usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory, })), category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory, + description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling_UseFsEvents_UseFsEventsOnParentDirectory, }, { name: "watchDirectory", @@ -35896,9 +36931,10 @@ var ts; usefsevents: ts.WatchDirectoryKind.UseFsEvents, fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval, dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling, + fixedchunksizepolling: ts.WatchDirectoryKind.FixedChunkSizePolling, })), category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling, + description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling, }, { name: "fallbackPolling", @@ -35906,9 +36942,10 @@ var ts; fixedinterval: ts.PollingWatchKind.FixedInterval, priorityinterval: ts.PollingWatchKind.PriorityInterval, dynamicpriority: ts.PollingWatchKind.DynamicPriority, + fixedchunksize: ts.PollingWatchKind.FixedChunkSize, })), category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority, + description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority_FixedChunkSize, }, { name: "synchronousWatchDirectory", @@ -36067,6 +37104,7 @@ var ts; es2018: 5 /* ES2018 */, es2019: 6 /* ES2019 */, es2020: 7 /* ES2020 */, + es2021: 8 /* ES2021 */, esnext: 99 /* ESNext */, })), affectsSourceFile: true, @@ -36075,10 +37113,10 @@ var ts; paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT, }; - /* @internal */ - ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsWithoutBuild = [ + // CommandLine only options { name: "all", type: "boolean", @@ -36441,6 +37479,14 @@ var ts; category: ts.Diagnostics.Additional_Checks, description: ts.Diagnostics.Include_undefined_in_index_signature_results }, + { + name: "noImplicitOverride", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier + }, { name: "noPropertyAccessFromIndexSignature", type: "boolean", @@ -36856,7 +37902,9 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins }, - ]); + ]; + /* @internal */ + ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsWithoutBuild); /* @internal */ ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); /* @internal */ @@ -36871,8 +37919,7 @@ var ts; ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) { return ts.hasProperty(option, "transpileOptionValue"); }); - /* @internal */ - ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [ + var commandOptionsOnlyBuild = [ { name: "verbose", shortName: "v", @@ -36900,7 +37947,9 @@ var ts; description: ts.Diagnostics.Delete_the_outputs_of_all_projects, type: "boolean" } - ]); + ]; + /* @internal */ + ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), commandOptionsOnlyBuild); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -36954,6 +38003,10 @@ var ts; return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations)); } ts.getOptionsNameMap = getOptionsNameMap; + var compilerOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_only_be_used_with_build, + getOptionsNameMap: getBuildOptionsNameMap + }; /* @internal */ ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, @@ -37015,6 +38068,10 @@ var ts; return option.name; } function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) { + var _a; + if ((_a = diagnostics.alternateMode) === null || _a === void 0 ? void 0 : _a.getOptionsNameMap().optionsNameMap.has(unknownOption.toLowerCase())) { + return createDiagnostics(diagnostics.alternateMode.diagnostic, unknownOption); + } var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName); return possibleOption ? createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : @@ -37169,6 +38226,7 @@ var ts; } /*@internal*/ ts.compilerOptionsDidYouMeanDiagnostics = { + alternateMode: compilerOptionsAlternateMode, getOptionsNameMap: getOptionsNameMap, optionDeclarations: ts.optionDeclarations, unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, @@ -37201,7 +38259,12 @@ var ts; function getBuildOptionsNameMap() { return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts)); } + var buildOptionsAlternateMode = { + diagnostic: ts.Diagnostics.Compiler_option_0_may_not_be_used_with_build, + getOptionsNameMap: getOptionsNameMap + }; var buildOptionsDidYouMeanDiagnostics = { + alternateMode: buildOptionsAlternateMode, getOptionsNameMap: getBuildOptionsNameMap, optionDeclarations: ts.buildOpts, unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0, @@ -37277,7 +38340,7 @@ var ts; function parseConfigFileTextToJson(fileName, jsonText) { var jsonSourceFile = ts.parseJsonText(fileName, jsonText); return { - config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + config: convertConfigFileToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics, /*reportOptionsErrors*/ false, /*optionsIterator*/ undefined), error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined }; } @@ -37407,11 +38470,31 @@ var ts; } return _tsconfigRootOptions; } + function convertConfigFileToObject(sourceFile, errors, reportOptionsErrors, optionsIterator) { + var _a; + var rootExpression = (_a = sourceFile.statements[0]) === null || _a === void 0 ? void 0 : _a.expression; + var knownRootOptions = reportOptionsErrors ? getTsconfigRootOptionsMap() : undefined; + if (rootExpression && rootExpression.kind !== 201 /* ObjectLiteralExpression */) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, rootExpression, ts.Diagnostics.The_root_value_of_a_0_file_must_be_an_object, ts.getBaseFileName(sourceFile.fileName) === "jsconfig.json" ? "jsconfig.json" : "tsconfig.json")); + // Last-ditch error recovery. Somewhat useful because the JSON parser will recover from some parse errors by + // synthesizing a top-level array literal expression. There's a reasonable chance the first element of that + // array is a well-formed configuration object, made into an array element by stray characters. + if (ts.isArrayLiteralExpression(rootExpression)) { + var firstObject = ts.find(rootExpression.elements, ts.isObjectLiteralExpression); + if (firstObject) { + return convertToObjectWorker(sourceFile, firstObject, errors, /*returnValue*/ true, knownRootOptions, optionsIterator); + } + } + return {}; + } + return convertToObjectWorker(sourceFile, rootExpression, errors, /*returnValue*/ true, knownRootOptions, optionsIterator); + } /** * Convert the json syntax tree into the json value */ function convertToObject(sourceFile, errors) { - return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + var _a; + return convertToObjectWorker(sourceFile, (_a = sourceFile.statements[0]) === null || _a === void 0 ? void 0 : _a.expression, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); } ts.convertToObject = convertToObject; /** @@ -37420,18 +38503,18 @@ var ts; * Otherwise it just checks the errors and returns undefined */ /*@internal*/ - function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { - if (!sourceFile.statements.length) { + function convertToObjectWorker(sourceFile, rootExpression, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!rootExpression) { return returnValue ? {} : undefined; } - return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + return convertPropertyValueToJson(rootExpression, knownRootOptions); function isRootOptionMap(knownOptions) { return knownRootOptions && knownRootOptions.elementOptions === knownOptions; } function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) { var result = returnValue ? {} : undefined; var _loop_4 = function (element) { - if (element.kind !== 288 /* PropertyAssignment */) { + if (element.kind !== 289 /* PropertyAssignment */) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); return "continue"; } @@ -37525,13 +38608,13 @@ var ts; case 8 /* NumericLiteral */: reportInvalidOptionValue(option && option.type !== "number"); return validateValue(Number(valueExpression.text)); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { break; // not valid JSON syntax } reportInvalidOptionValue(option && option.type !== "number"); return validateValue(-Number(valueExpression.operand.text)); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: reportInvalidOptionValue(option && option.type !== "object"); var objectLiteralExpression = valueExpression; // Currently having element option declaration in the tsconfig with type "object" @@ -37548,7 +38631,7 @@ var ts; return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined)); } - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: reportInvalidOptionValue(option && option.type !== "list"); return validateValue(convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element)); } @@ -38096,14 +39179,14 @@ var ts; if (ownConfig.extendedConfigPath) { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, resolutionStack, errors, extendedConfigCache); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { var baseRaw_1 = extendedConfig.raw; var raw_1 = ownConfig.raw; + var relativeDifference_1; var setPropertyInRawIfNotUndefined = function (propertyName) { - var value = raw_1[propertyName] || baseRaw_1[propertyName]; - if (value) { - raw_1[propertyName] = value; + if (!raw_1[propertyName] && baseRaw_1[propertyName]) { + raw_1[propertyName] = ts.map(baseRaw_1[propertyName], function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1 || (relativeDifference_1 = ts.convertToRelativePath(ts.getDirectoryPath(ownConfig.extendedConfigPath), basePath, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames))), path); }); } }; setPropertyInRawIfNotUndefined("include"); @@ -38185,7 +39268,7 @@ var ts; } } }; - var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); + var json = convertConfigFileToObject(sourceFile, errors, /*reportOptionsErrors*/ true, optionsIterator); if (!typeAcquisition) { if (typingOptionstypeAcquisition) { typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? @@ -38223,7 +39306,7 @@ var ts; errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig)); return undefined; } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) { + function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache) { var _a; var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath); var value; @@ -38235,22 +39318,7 @@ var ts; else { extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (!extendedResult.parseDiagnostics.length) { - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); - if (isSuccessfulParsedTsconfig(extendedConfig)) { - // Update the paths to reflect base path - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); - var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; - var mapPropertiesInRawIfNotUndefined = function (propertyName) { - if (raw_2[propertyName]) { - raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); - } - }; - var raw_2 = extendedConfig.raw; - mapPropertiesInRawIfNotUndefined("include"); - mapPropertiesInRawIfNotUndefined("exclude"); - mapPropertiesInRawIfNotUndefined("files"); - } + extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, ts.getDirectoryPath(extendedConfigPath), ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); } if (extendedConfigCache) { extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig }); @@ -38947,13 +40015,24 @@ var ts; * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, cache) { var traceEnabled = isTraceEnabled(options, host); if (redirectedReference) { options = redirectedReference.commandLine.options; } - var failedLookupLocations = []; - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var containingDirectory = containingFile ? ts.getDirectoryPath(containingFile) : undefined; + var perFolderCache = containingDirectory ? cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference) : undefined; + var result = perFolderCache && perFolderCache.get(typeReferenceDirectiveName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile); + if (redirectedReference) + trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + trace(host, ts.Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory); + traceResult(result); + } + return result; + } var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -38976,6 +40055,8 @@ var ts; trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); } } + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -38986,17 +40067,31 @@ var ts; if (resolved) { var fileName = resolved.fileName, packageId = resolved.packageId; var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); - if (traceEnabled) { - if (packageId) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, ts.packageIdToString(packageId), primary); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); - } + resolvedTypeReferenceDirective = { + primary: primary, + resolvedFileName: resolvedFileName, + originalPath: fileName === resolvedFileName ? undefined : fileName, + packageId: packageId, + isExternalLibraryImport: pathContainsNodeModules(fileName), + }; + } + result = { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + perFolderCache === null || perFolderCache === void 0 ? void 0 : perFolderCache.set(typeReferenceDirectiveName, result); + if (traceEnabled) + traceResult(result); + return result; + function traceResult(result) { + var _a; + if (!((_a = result.resolvedTypeReferenceDirective) === null || _a === void 0 ? void 0 : _a.resolvedFileName)) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + else if (result.resolvedTypeReferenceDirective.packageId) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, ts.packageIdToString(result.resolvedTypeReferenceDirective.packageId), result.resolvedTypeReferenceDirective.primary); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, result.resolvedTypeReferenceDirective.primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } - return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { // Check primary library paths if (typeRoots && typeRoots.length) { @@ -39026,20 +40121,16 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = void 0; + var result_4; if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); - result = searchResult && searchResult.value; + result_4 = searchResult && searchResult.value; } else { var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; - result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); + result_4 = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); } - var resolvedFile = resolvedTypeScriptOnly(result); - if (!resolvedFile && traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - return resolvedFile; + return resolvedTypeScriptOnly(result_4); } else { if (traceEnabled) { @@ -39094,22 +40185,21 @@ var ts; return result; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; - function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) { - return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName); - } - ts.createModuleResolutionCache = createModuleResolutionCache; /*@internal*/ function createCacheWithRedirects(options) { var ownMap = new ts.Map(); var redirectsMap = new ts.Map(); return { - ownMap: ownMap, + getOwnMap: getOwnMap, redirectsMap: redirectsMap, getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects, clear: clear, setOwnOptions: setOwnOptions, setOwnMap: setOwnMap }; + function getOwnMap() { + return ownMap; + } function setOwnOptions(newOptions) { options = newOptions; } @@ -39135,26 +40225,88 @@ var ts; } } ts.createCacheWithRedirects = createCacheWithRedirects; - /*@internal*/ - function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) { - return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap }; + function createPackageJsonInfoCache(currentDirectory, getCanonicalFileName) { + var cache; + return { getPackageJsonInfo: getPackageJsonInfo, setPackageJsonInfo: setPackageJsonInfo, clear: clear }; + function getPackageJsonInfo(packageJsonPath) { + return cache === null || cache === void 0 ? void 0 : cache.get(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); + } + function setPackageJsonInfo(packageJsonPath, info) { + (cache || (cache = new ts.Map())).set(ts.toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info); + } + function clear() { + cache = undefined; + } + } + function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { + var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + var result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + function updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + if (!options.configFile) + return; + if (directoryToModuleNameMap.redirectsMap.size === 0) { + // The own map will be for projectCompilerOptions + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size === 0); + ts.Debug.assert(directoryToModuleNameMap.getOwnMap().size === 0); + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.getOwnMap().size === 0); + directoryToModuleNameMap.redirectsMap.set(options.configFile.path, directoryToModuleNameMap.getOwnMap()); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.redirectsMap.set(options.configFile.path, moduleNameToDirectoryMap.getOwnMap()); + } + else { + // Set correct own map + ts.Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size > 0); + var ref = { + sourceFile: options.configFile, + commandLine: { options: options } + }; + directoryToModuleNameMap.setOwnMap(directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnMap(moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); + } + directoryToModuleNameMap.setOwnOptions(options); + moduleNameToDirectoryMap === null || moduleNameToDirectoryMap === void 0 ? void 0 : moduleNameToDirectoryMap.setOwnOptions(options); + } + function createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap) { + return { + getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, + clear: clear, + update: update, + }; + function clear() { + directoryToModuleNameMap.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap); + } function getOrCreateCacheForDirectory(directoryName, redirectedReference) { var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, function () { return new ts.Map(); }); } + } + function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, directoryToModuleNameMap, moduleNameToDirectoryMap) { + var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + moduleNameToDirectoryMap || (moduleNameToDirectoryMap = createCacheWithRedirects(options)); + var packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName); + return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, + clear: clear, + update: update, getPackageJsonInfoCache: function () { return packageJsonInfoCache; } }); + function clear() { + preDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap.clear(); + packageJsonInfoCache.clear(); + } + function update(options) { + updateRedirectsMap(options, directoryToModuleNameMap, moduleNameToDirectoryMap); + } function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); } - function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) { - var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); - var result = cache.get(key); - if (!result) { - result = create(); - cache.set(key, result); - } - return result; - } function createPerModuleNameCache() { var directoryPathMap = new ts.Map(); return { get: get, set: set }; @@ -39221,7 +40373,17 @@ var ts; } } } - ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + ts.createModuleResolutionCache = createModuleResolutionCache; + function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, directoryToModuleNameMap) { + var preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap || (directoryToModuleNameMap = createCacheWithRedirects(options))); + packageJsonInfoCache || (packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName)); + return __assign(__assign(__assign({}, packageJsonInfoCache), preDirectoryResolutionCache), { clear: clear }); + function clear() { + preDirectoryResolutionCache.clear(); + packageJsonInfoCache.clear(); + } + } + ts.createTypeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache; function resolveModuleNameFromCache(moduleName, containingFile, cache) { var containingDirectory = ts.getDirectoryPath(containingFile); var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); @@ -39499,7 +40661,7 @@ var ts; var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, state.resultFromCache); function tryResolve(extensions) { @@ -39559,7 +40721,7 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { - var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined; return withPackageId(packageInfo, resolvedFromFile); } @@ -39592,8 +40754,9 @@ var ts; * For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo" * For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo" */ + /* @internal */ function parseNodeModuleFromPath(resolved) { - var path = ts.normalizePath(resolved.path); + var path = ts.normalizePath(resolved); var idx = path.lastIndexOf(ts.nodeModulesPathPart); if (idx === -1) { return undefined; @@ -39605,6 +40768,7 @@ var ts; } return path.slice(0, indexAfterPackageName); } + ts.parseNodeModuleFromPath = parseNodeModuleFromPath; function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; @@ -39688,21 +40852,43 @@ var ts; return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { + var _a, _b, _c; var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); + if (onlyRecordFailures) { + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + var existing = (_a = state.packageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfo(packageJsonPath); + if (existing !== undefined) { + if (typeof existing !== "boolean") { + if (traceEnabled) + trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + return existing; + } + else { + if (existing && traceEnabled) + trace(host, ts.Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + } + var directoryExists = ts.directoryProbablyExists(packageDirectory, host); if (directoryExists && host.fileExists(packageJsonPath)) { var packageJsonContent = ts.readJson(packageJsonPath, host); if (traceEnabled) { trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); - return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); + return result; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + (_c = state.packageJsonInfoCache) === null || _c === void 0 ? void 0 : _c.setPackageJsonInfo(packageJsonPath, directoryExists); // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results state.failedLookupLocations.push(packageJsonPath); } @@ -39951,7 +41137,7 @@ var ts; function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath @@ -39992,13 +41178,13 @@ var ts; * This is the minumum code needed to expose that functionality; the rest is in the host. */ /* @internal */ - function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache, packageJsonInfoCache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: packageJsonInfoCache }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache); } @@ -40044,26 +41230,26 @@ var ts; // A module is uninstantiated if it contains only switch (node.kind) { // 1. interface declarations, type alias declarations - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return 0 /* NonInstantiated */; // 2. const enum declarations - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: if (ts.isEnumConst(node)) { return 2 /* ConstEnumOnly */; } break; // 3. non-exported import declarations - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: if (!(ts.hasSyntacticModifier(node, 1 /* Export */))) { return 0 /* NonInstantiated */; } break; // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: var exportDeclaration = node; - if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 268 /* NamedExports */) { + if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 269 /* NamedExports */) { var state = 0 /* NonInstantiated */; for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; @@ -40079,7 +41265,7 @@ var ts; } break; // 5. other uninstantiated module declarations. - case 257 /* ModuleBlock */: { + case 258 /* ModuleBlock */: { var state_1 = 0 /* NonInstantiated */; ts.forEachChild(node, function (n) { var childState = getModuleInstanceStateCached(n, visited); @@ -40101,7 +41287,7 @@ var ts; }); return state_1; } - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return getModuleInstanceState(node, visited); case 78 /* Identifier */: // Only jsdoc typedef definition can exist in jsdoc namespace, and it should @@ -40173,14 +41359,14 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { - ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); ts.performance.measure("Bind", "beforeBind", "afterBind"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -40219,6 +41405,7 @@ var ts; var classifiableNames; var unreachableFlow = { flags: 1 /* Unreachable */ }; var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; + var bindBinaryExpressionFlow = createBindBinaryExpressionFlow(); /** * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) @@ -40301,7 +41488,7 @@ var ts; // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { - if (node.kind === 266 /* ExportAssignment */) { + if (node.kind === 267 /* ExportAssignment */) { return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; } var name = ts.getNameOfDeclaration(node); @@ -40310,7 +41497,7 @@ var ts; var moduleName = ts.getTextOfIdentifierOrLiteral(name); return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); } - if (name.kind === 158 /* ComputedPropertyName */) { + if (name.kind === 159 /* ComputedPropertyName */) { var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteralLike(nameExpression)) { @@ -40319,11 +41506,9 @@ var ts; if (ts.isSignedNumericLiteral(nameExpression)) { return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text; } - ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); - return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - if (ts.isWellKnownSymbolSyntactically(name)) { - return ts.getPropertyNameForKnownSymbolName(ts.idText(name.name)); + else { + ts.Debug.fail("Only computed properties with literal names have declaration names"); + } } if (ts.isPrivateIdentifier(name)) { // containingClass exists because private names only allowed inside classes @@ -40338,36 +41523,36 @@ var ts; return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return "__constructor" /* Constructor */; - case 174 /* FunctionType */: - case 169 /* CallSignature */: - case 313 /* JSDocSignature */: + case 175 /* FunctionType */: + case 170 /* CallSignature */: + case 315 /* JSDocSignature */: return "__call" /* Call */; - case 175 /* ConstructorType */: - case 170 /* ConstructSignature */: + case 176 /* ConstructorType */: + case 171 /* ConstructSignature */: return "__new" /* New */; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: return "__index" /* Index */; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return "__export" /* ExportStar */; - case 297 /* SourceFile */: + case 298 /* SourceFile */: // json file should behave as // module.exports = ... return "export=" /* ExportEquals */; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); - case 160 /* Parameter */: + case 161 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 308 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + ts.Debug.assert(node.parent.kind === 309 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -40467,7 +41652,7 @@ var ts; // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if (symbol.declarations && symbol.declarations.length && - (node.kind === 266 /* ExportAssignment */ && !node.isExportEquals)) { + (node.kind === 267 /* ExportAssignment */ && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName_1 = false; multipleDefaultExports_1 = true; @@ -40506,7 +41691,7 @@ var ts; function declareModuleMember(node, symbolFlags, symbolExcludes) { var hasExportModifier = !!(ts.getCombinedModifierFlags(node) & 1 /* Export */) || jsdocTreatAsExported(node); if (symbolFlags & 2097152 /* Alias */) { - if (node.kind === 270 /* ExportSpecifier */ || (node.kind === 260 /* ImportEqualsDeclaration */ && hasExportModifier)) { + if (node.kind === 271 /* ExportSpecifier */ || (node.kind === 261 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } else { @@ -40595,7 +41780,7 @@ var ts; // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. if (containerFlags & 1 /* IsContainer */) { - if (node.kind !== 209 /* ArrowFunction */) { + if (node.kind !== 210 /* ArrowFunction */) { thisParentContainer = container; } container = blockScopeContainer = node; @@ -40628,7 +41813,7 @@ var ts; } // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property initialization checks. - currentReturnTarget = isIIFE || node.kind === 166 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */)) ? createBranchLabel() : undefined; + currentReturnTarget = isIIFE || node.kind === 167 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 252 /* FunctionDeclaration */ || node.kind === 209 /* FunctionExpression */)) ? createBranchLabel() : undefined; currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; @@ -40643,13 +41828,14 @@ var ts; node.flags |= 512 /* HasExplicitReturn */; node.endFlowNode = currentFlow; } - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { node.flags |= emitFlags; + node.endFlowNode = currentFlow; } if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 166 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */))) { + if (node.kind === 167 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 252 /* FunctionDeclaration */ || node.kind === 209 /* FunctionExpression */))) { node.returnFlowNode = currentFlow; } } @@ -40676,8 +41862,8 @@ var ts; blockScopeContainer = savedBlockScopeContainer; } function bindEachFunctionsFirst(nodes) { - bindEach(nodes, function (n) { return n.kind === 251 /* FunctionDeclaration */ ? bind(n) : undefined; }); - bindEach(nodes, function (n) { return n.kind !== 251 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind === 252 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 252 /* FunctionDeclaration */ ? bind(n) : undefined; }); } function bindEach(nodes, bindFunction) { if (bindFunction === void 0) { bindFunction = bind; } @@ -40700,59 +41886,59 @@ var ts; inAssignmentPattern = saveInAssignmentPattern; return; } - if (node.kind >= 232 /* FirstStatement */ && node.kind <= 248 /* LastStatement */ && !options.allowUnreachableCode) { + if (node.kind >= 233 /* FirstStatement */ && node.kind <= 249 /* LastStatement */ && !options.allowUnreachableCode) { node.flowNode = currentFlow; } switch (node.kind) { - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: bindWhileStatement(node); break; - case 235 /* DoStatement */: + case 236 /* DoStatement */: bindDoStatement(node); break; - case 237 /* ForStatement */: + case 238 /* ForStatement */: bindForStatement(node); break; - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: bindForInOrForOfStatement(node); break; - case 234 /* IfStatement */: + case 235 /* IfStatement */: bindIfStatement(node); break; - case 242 /* ReturnStatement */: - case 246 /* ThrowStatement */: + case 243 /* ReturnStatement */: + case 247 /* ThrowStatement */: bindReturnOrThrow(node); break; - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: bindBreakOrContinueStatement(node); break; - case 247 /* TryStatement */: + case 248 /* TryStatement */: bindTryStatement(node); break; - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: bindSwitchStatement(node); break; - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: bindCaseBlock(node); break; - case 284 /* CaseClause */: + case 285 /* CaseClause */: bindCaseClause(node); break; - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: bindExpressionStatement(node); break; - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: bindLabeledStatement(node); break; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: bindPrefixUnaryExpressionFlow(node); break; - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: bindPostfixUnaryExpressionFlow(node); break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.isDestructuringAssignment(node)) { // Carry over whether we are in an assignment pattern to // binary expressions that could actually be an initializer @@ -40762,47 +41948,47 @@ var ts; } bindBinaryExpressionFlow(node); break; - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: bindDeleteExpressionFlow(node); break; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: bindConditionalExpressionFlow(node); break; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: bindVariableDeclarationFlow(node); break; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: bindAccessExpressionFlow(node); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: bindCallExpressionFlow(node); break; - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: bindNonNullExpressionFlow(node); break; - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: bindJSDocTypeAlias(node); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime - case 297 /* SourceFile */: { + case 298 /* SourceFile */: { bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); break; } - case 230 /* Block */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 258 /* ModuleBlock */: bindEachFunctionsFirst(node.statements); break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: bindBindingElementFlow(node); break; - case 200 /* ObjectLiteralExpression */: - case 199 /* ArrayLiteralExpression */: - case 288 /* PropertyAssignment */: - case 220 /* SpreadElement */: + case 201 /* ObjectLiteralExpression */: + case 200 /* ArrayLiteralExpression */: + case 289 /* PropertyAssignment */: + case 221 /* SpreadElement */: // Carry over whether we are in an assignment pattern of Object and Array literals // as well as their children that are valid assignment targets. inAssignmentPattern = saveInAssignmentPattern; @@ -40819,29 +42005,29 @@ var ts; case 78 /* Identifier */: case 79 /* PrivateIdentifier */: case 107 /* ThisKeyword */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return containsNarrowableReference(expr); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return hasNarrowableArgument(expr); - case 207 /* ParenthesizedExpression */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: return isNarrowingExpression(expr.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return isNarrowingBinaryExpression(expr); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return isNarrowingExpression(expr.expression); } return false; } function isNarrowableReference(expr) { - return expr.kind === 78 /* Identifier */ || expr.kind === 79 /* PrivateIdentifier */ || expr.kind === 107 /* ThisKeyword */ || expr.kind === 105 /* SuperKeyword */ || - (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isBinaryExpression(expr) && expr.operatorToken.kind === 27 /* CommaToken */ && isNarrowableReference(expr.right) || - ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || - ts.isAssignmentExpression(expr) && isNarrowableReference(expr.left); + return ts.isDottedName(expr) + || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) + || ts.isBinaryExpression(expr) && expr.operatorToken.kind === 27 /* CommaToken */ && isNarrowableReference(expr.right) + || ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) + || ts.isAssignmentExpression(expr) && isNarrowableReference(expr.left); } function containsNarrowableReference(expr) { return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression); @@ -40855,7 +42041,7 @@ var ts; } } } - if (expr.expression.kind === 201 /* PropertyAccessExpression */ && + if (expr.expression.kind === 202 /* PropertyAccessExpression */ && containsNarrowableReference(expr.expression.expression)) { return true; } @@ -40891,9 +42077,9 @@ var ts; } function isNarrowableOperand(expr) { switch (expr.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isNarrowableOperand(expr.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (expr.operatorToken.kind) { case 62 /* EqualsToken */: return isNarrowableOperand(expr.left); @@ -40969,26 +42155,26 @@ var ts; function isStatementCondition(node) { var parent = node.parent; switch (parent.kind) { - case 234 /* IfStatement */: - case 236 /* WhileStatement */: - case 235 /* DoStatement */: + case 235 /* IfStatement */: + case 237 /* WhileStatement */: + case 236 /* DoStatement */: return parent.expression === node; - case 237 /* ForStatement */: - case 217 /* ConditionalExpression */: + case 238 /* ForStatement */: + case 218 /* ConditionalExpression */: return parent.condition === node; } return false; } function isLogicalExpression(node) { while (true) { - if (node.kind === 207 /* ParenthesizedExpression */) { + if (node.kind === 208 /* ParenthesizedExpression */) { node = node.expression; } - else if (node.kind === 214 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) { + else if (node.kind === 215 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) { node = node.operand; } else { - return node.kind === 216 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ || + return node.kind === 217 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */); } @@ -41035,7 +42221,7 @@ var ts; } function setContinueTarget(node, target) { var label = activeLabelList; - while (label && node.parent.kind === 245 /* LabeledStatement */) { + while (label && node.parent.kind === 246 /* LabeledStatement */) { label.continueTarget = target; label = label.next; node = node.parent; @@ -41086,12 +42272,12 @@ var ts; bind(node.expression); addAntecedent(preLoopLabel, currentFlow); currentFlow = preLoopLabel; - if (node.kind === 239 /* ForOfStatement */) { + if (node.kind === 240 /* ForOfStatement */) { bind(node.awaitModifier); } addAntecedent(postLoopLabel, currentFlow); bind(node.initializer); - if (node.initializer.kind !== 250 /* VariableDeclarationList */) { + if (node.initializer.kind !== 251 /* VariableDeclarationList */) { bindAssignmentTargetFlow(node.initializer); } bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); @@ -41113,7 +42299,7 @@ var ts; } function bindReturnOrThrow(node) { bind(node.expression); - if (node.kind === 242 /* ReturnStatement */) { + if (node.kind === 243 /* ReturnStatement */) { hasExplicitReturn = true; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); @@ -41130,7 +42316,7 @@ var ts; return undefined; } function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 241 /* BreakStatement */ ? breakTarget : continueTarget; + var flowLabel = node.kind === 242 /* BreakStatement */ ? breakTarget : continueTarget; if (flowLabel) { addAntecedent(flowLabel, currentFlow); currentFlow = unreachableFlow; @@ -41235,7 +42421,7 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 285 /* DefaultClause */; }); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 286 /* DefaultClause */; }); // We mark a switch statement as possibly exhaustive if it has no default clause and if all // case clauses have unreachable end points (e.g. they all return). Note, we no longer need // this property in control flow analysis, it's there only for backwards compatibility. @@ -41283,9 +42469,9 @@ var ts; function maybeBindExpressionFlowIfCall(node) { // A top level or LHS of comma expression call expression with a dotted function name and at least one argument // is potentially an assertion and is therefore included in the control flow. - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { var call = node; - if (ts.isDottedName(call.expression) && call.expression.kind !== 105 /* SuperKeyword */) { + if (call.expression.kind !== 105 /* SuperKeyword */ && ts.isDottedName(call.expression)) { currentFlow = createFlowCall(currentFlow, call); } } @@ -41309,7 +42495,7 @@ var ts; currentFlow = finishFlowLabel(postStatementLabel); } function bindDestructuringTargetFlow(node) { - if (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) { + if (node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) { bindAssignmentTargetFlow(node.left); } else { @@ -41320,10 +42506,10 @@ var ts; if (isNarrowableReference(node)) { currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node); } - else if (node.kind === 199 /* ArrayLiteralExpression */) { + else if (node.kind === 200 /* ArrayLiteralExpression */) { for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { var e = _a[_i]; - if (e.kind === 220 /* SpreadElement */) { + if (e.kind === 221 /* SpreadElement */) { bindAssignmentTargetFlow(e.expression); } else { @@ -41331,16 +42517,16 @@ var ts; } } } - else if (node.kind === 200 /* ObjectLiteralExpression */) { + else if (node.kind === 201 /* ObjectLiteralExpression */) { for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var p = _c[_b]; - if (p.kind === 288 /* PropertyAssignment */) { + if (p.kind === 289 /* PropertyAssignment */) { bindDestructuringTargetFlow(p.initializer); } - else if (p.kind === 289 /* ShorthandPropertyAssignment */) { + else if (p.kind === 290 /* ShorthandPropertyAssignment */) { bindAssignmentTargetFlow(p.name); } - else if (p.kind === 290 /* SpreadAssignment */) { + else if (p.kind === 291 /* SpreadAssignment */) { bindAssignmentTargetFlow(p.expression); } } @@ -41405,128 +42591,102 @@ var ts; } bindAssignmentTargetFlow(node.left); } - var BindBinaryExpressionFlowState; - (function (BindBinaryExpressionFlowState) { - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindThenBindChildren"] = 0] = "BindThenBindChildren"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["MaybeBindLeft"] = 1] = "MaybeBindLeft"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindToken"] = 2] = "BindToken"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindRight"] = 3] = "BindRight"; - BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["FinishBind"] = 4] = "FinishBind"; - })(BindBinaryExpressionFlowState || (BindBinaryExpressionFlowState = {})); - function bindBinaryExpressionFlow(node) { - var workStacks = { - expr: [node], - state: [1 /* MaybeBindLeft */], - inStrictMode: [undefined], - parent: [undefined], - }; - var stackIndex = 0; - while (stackIndex >= 0) { - node = workStacks.expr[stackIndex]; - switch (workStacks.state[stackIndex]) { - case 0 /* BindThenBindChildren */: { - // This state is used only when recuring, to emulate the work that `bind` does before - // reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work. - ts.setParent(node, parent); - var saveInStrictMode = inStrictMode; - bindWorker(node); - var saveParent = parent; - parent = node; - advanceState(1 /* MaybeBindLeft */, saveInStrictMode, saveParent); - break; - } - case 1 /* MaybeBindLeft */: { - var operator = node.operatorToken.kind; - // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions - // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too - // For now, though, since the common cases are chained `+`, leaving it recursive is fine - if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */ || - ts.isLogicalOrCoalescingAssignmentOperator(operator)) { - if (isTopLevelLogicalExpression(node)) { - var postExpressionLabel = createBranchLabel(); - bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel); - currentFlow = finishFlowLabel(postExpressionLabel); - } - else { - bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget); - } - completeNode(); - } - else { - advanceState(2 /* BindToken */); - maybeBind(node.left); - } - break; + function createBindBinaryExpressionFlow() { + return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined); + function onEnter(node, state) { + if (state) { + state.stackIndex++; + // Emulate the work that `bind` does before reaching `bindChildren`. A normal call to + // `bindBinaryExpressionFlow` will already have done this work. + ts.setParent(node, parent); + var saveInStrictMode = inStrictMode; + bindWorker(node); + var saveParent = parent; + parent = node; + state.skip = false; + state.inStrictModeStack[state.stackIndex] = saveInStrictMode; + state.parentStack[state.stackIndex] = saveParent; + } + else { + state = { + stackIndex: 0, + skip: false, + inStrictModeStack: [undefined], + parentStack: [undefined] + }; + } + // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions + // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too + // For now, though, since the common cases are chained `+`, leaving it recursive is fine + var operator = node.operatorToken.kind; + if (operator === 55 /* AmpersandAmpersandToken */ || + operator === 56 /* BarBarToken */ || + operator === 60 /* QuestionQuestionToken */ || + ts.isLogicalOrCoalescingAssignmentOperator(operator)) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); } - case 2 /* BindToken */: { - if (node.operatorToken.kind === 27 /* CommaToken */) { - maybeBindExpressionFlowIfCall(node.left); - } - advanceState(3 /* BindRight */); - maybeBind(node.operatorToken); - break; + else { + bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget); } - case 3 /* BindRight */: { - advanceState(4 /* FinishBind */); - maybeBind(node.right); - break; + state.skip = true; + } + return state; + } + function onLeft(left, state, _node) { + if (!state.skip) { + return maybeBind(left); + } + } + function onOperator(operatorToken, state, node) { + if (!state.skip) { + if (operatorToken.kind === 27 /* CommaToken */) { + maybeBindExpressionFlowIfCall(node.left); } - case 4 /* FinishBind */: { - var operator = node.operatorToken.kind; - if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { - bindAssignmentTargetFlow(node.left); - if (operator === 62 /* EqualsToken */ && node.left.kind === 202 /* ElementAccessExpression */) { - var elementAccess = node.left; - if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); - } + bind(operatorToken); + } + } + function onRight(right, state, _node) { + if (!state.skip) { + return maybeBind(right); + } + } + function onExit(node, state) { + if (!state.skip) { + var operator = node.operatorToken.kind; + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 62 /* EqualsToken */ && node.left.kind === 203 /* ElementAccessExpression */) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); } } - completeNode(); - break; } - default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for bindBinaryExpressionFlow"); } - } - /** - * Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new - * head state; so `advanceState` must be called before any `maybeBind` during a state's execution. - */ - function advanceState(state, isInStrictMode, parent) { - workStacks.state[stackIndex] = state; - if (isInStrictMode !== undefined) { - workStacks.inStrictMode[stackIndex] = isInStrictMode; + var savedInStrictMode = state.inStrictModeStack[state.stackIndex]; + var savedParent = state.parentStack[state.stackIndex]; + if (savedInStrictMode !== undefined) { + inStrictMode = savedInStrictMode; } - if (parent !== undefined) { - workStacks.parent[stackIndex] = parent; + if (savedParent !== undefined) { + parent = savedParent; } + state.skip = false; + state.stackIndex--; } - function completeNode() { - if (workStacks.inStrictMode[stackIndex] !== undefined) { - inStrictMode = workStacks.inStrictMode[stackIndex]; - parent = workStacks.parent[stackIndex]; - } - stackIndex--; - } - /** - * If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it - */ function maybeBind(node) { if (node && ts.isBinaryExpression(node) && !ts.isDestructuringAssignment(node)) { - stackIndex++; - workStacks.expr[stackIndex] = node; - workStacks.state[stackIndex] = 0 /* BindThenBindChildren */; - workStacks.inStrictMode[stackIndex] = undefined; - workStacks.parent[stackIndex] = undefined; - } - else { - bind(node); + return node; } + bind(node); } } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 201 /* PropertyAccessExpression */) { + if (node.expression.kind === 202 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -41583,7 +42743,7 @@ var ts; } function bindJSDocTypeAlias(node) { ts.setParent(node.tagName, node); - if (node.kind !== 325 /* JSDocEnumTag */ && node.fullName) { + if (node.kind !== 329 /* JSDocEnumTag */ && node.fullName) { ts.setParent(node.fullName, node); ts.setParentRecursive(node.fullName, /*incremental*/ false); } @@ -41591,7 +42751,7 @@ var ts; function bindJSDocClassTag(node) { bindEachChild(node); var host = ts.getHostSignatureFromJSDoc(node); - if (host && host.kind !== 165 /* MethodDeclaration */) { + if (host && host.kind !== 166 /* MethodDeclaration */) { addDeclarationToSymbol(host.symbol, host, 32 /* Class */); } } @@ -41604,15 +42764,15 @@ var ts; } function bindOptionalChainRest(node) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: bind(node.questionDotToken); bind(node.name); break; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: bind(node.questionDotToken); bind(node.argumentExpression); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: bind(node.questionDotToken); bindEach(node.typeArguments); bindEach(node.arguments); @@ -41677,7 +42837,7 @@ var ts; // an immediately invoked function expression (IIFE). Initialize the flowNode property to // the current control flow (which includes evaluation of the IIFE arguments). var expr = ts.skipParentheses(node.expression); - if (expr.kind === 208 /* FunctionExpression */ || expr.kind === 209 /* ArrowFunction */) { + if (expr.kind === 209 /* FunctionExpression */ || expr.kind === 210 /* ArrowFunction */) { bindEach(node.typeArguments); bindEach(node.arguments); bind(node.expression); @@ -41689,7 +42849,7 @@ var ts; } } } - if (node.expression.kind === 201 /* PropertyAccessExpression */) { + if (node.expression.kind === 202 /* PropertyAccessExpression */) { var propertyAccess = node.expression; if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node); @@ -41698,54 +42858,54 @@ var ts; } function getContainerFlags(node) { switch (node.kind) { - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 200 /* ObjectLiteralExpression */: - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 281 /* JsxAttributes */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 201 /* ObjectLiteralExpression */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 282 /* JsxAttributes */: return 1 /* IsContainer */; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return 1 /* IsContainer */ | 64 /* IsInterface */; - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 190 /* MappedType */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 191 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 297 /* SourceFile */: + case 298 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; } // falls through - case 166 /* Constructor */: - case 251 /* FunctionDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 169 /* CallSignature */: - case 313 /* JSDocSignature */: - case 308 /* JSDocFunctionType */: - case 174 /* FunctionType */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: - case 175 /* ConstructorType */: + case 167 /* Constructor */: + case 252 /* FunctionDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 170 /* CallSignature */: + case 315 /* JSDocSignature */: + case 309 /* JSDocFunctionType */: + case 175 /* FunctionType */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: + case 176 /* ConstructorType */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return 4 /* IsControlFlowContainer */; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 287 /* CatchClause */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: - case 258 /* CaseBlock */: + case 288 /* CatchClause */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: + case 259 /* CaseBlock */: return 2 /* IsBlockScopedContainer */; - case 230 /* Block */: + case 231 /* Block */: // do not treat blocks directly inside a function as a block-scoped-container. // Locals that reside in this block should go to the function locals. Otherwise 'x' // would not appear to be a redeclaration of a block scoped local in the following @@ -41778,45 +42938,45 @@ var ts; // members are declared (for example, a member of a class will go into a specific // symbol table depending on if it is static or not). We defer to specialized // handlers to take care of declaring these child members. - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 297 /* SourceFile */: + case 298 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: return declareClassMember(node, symbolFlags, symbolExcludes); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 200 /* ObjectLiteralExpression */: - case 253 /* InterfaceDeclaration */: - case 281 /* JsxAttributes */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 201 /* ObjectLiteralExpression */: + case 254 /* InterfaceDeclaration */: + case 282 /* JsxAttributes */: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the // object / type / interface declaring them). An exception is type parameters, // which are in scope without qualification (similar to 'locals'). return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 313 /* JSDocSignature */: - case 171 /* IndexSignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 308 /* JSDocFunctionType */: - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 254 /* TypeAliasDeclaration */: - case 190 /* MappedType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 315 /* JSDocSignature */: + case 172 /* IndexSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 309 /* JSDocFunctionType */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 255 /* TypeAliasDeclaration */: + case 191 /* MappedType */: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath @@ -41917,7 +43077,7 @@ var ts; var seen = new ts.Map(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 290 /* SpreadAssignment */ || prop.name.kind !== 78 /* Identifier */) { + if (prop.kind === 291 /* SpreadAssignment */ || prop.name.kind !== 78 /* Identifier */) { continue; } var identifier = prop.name; @@ -41929,7 +43089,7 @@ var ts; // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 288 /* PropertyAssignment */ || prop.kind === 289 /* ShorthandPropertyAssignment */ || prop.kind === 165 /* MethodDeclaration */ + var currentKind = prop.kind === 289 /* PropertyAssignment */ || prop.kind === 290 /* ShorthandPropertyAssignment */ || prop.kind === 166 /* MethodDeclaration */ ? 1 /* Property */ : 2 /* Accessor */; var existingKind = seen.get(identifier.escapedText); @@ -41961,10 +43121,10 @@ var ts; } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { switch (blockScopeContainer.kind) { - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (ts.isExternalOrCommonJsModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -41989,9 +43149,9 @@ var ts; var saveCurrentFlow = currentFlow; for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { var typeAlias = delayedTypeAliases_1[_i]; - var host = ts.getJSDocHost(typeAlias); - container = (host && ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); })) || file; - blockScopeContainer = (host && ts.getEnclosingBlockScopeContainer(host)) || file; + var host = typeAlias.parent.parent; + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); @@ -42163,8 +43323,8 @@ var ts; function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2 /* ES2015 */) { // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 297 /* SourceFile */ && - blockScopeContainer.kind !== 256 /* ModuleDeclaration */ && + if (blockScopeContainer.kind !== 298 /* SourceFile */ && + blockScopeContainer.kind !== 257 /* ModuleDeclaration */ && !ts.isFunctionLike(blockScopeContainer)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. @@ -42259,7 +43419,7 @@ var ts; // the current 'container' node when it changes. This helps us know which symbol table // a local should go into for example. Since terminal nodes are known not to have // children, as an optimization we don't process those. - if (node.kind > 156 /* LastToken */) { + if (node.kind > 157 /* LastToken */) { var saveParent = parent; parent = node; var containerFlags = getContainerFlags(node); @@ -42335,17 +43495,23 @@ var ts; } // falls through case 107 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 289 /* ShorthandPropertyAssignment */)) { + if (currentFlow && (ts.isExpression(node) || parent.kind === 290 /* ShorthandPropertyAssignment */)) { node.flowNode = currentFlow; } return checkContextualIdentifier(node); + case 158 /* QualifiedName */: + if (currentFlow && parent.kind === 177 /* TypeQuery */) { + node.flowNode = currentFlow; + } + break; + case 227 /* MetaProperty */: case 105 /* SuperKeyword */: node.flowNode = currentFlow; break; case 79 /* PrivateIdentifier */: return checkPrivateIdentifier(node); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: var expr = node; if (currentFlow && isNarrowableReference(expr)) { expr.flowNode = currentFlow; @@ -42360,7 +43526,7 @@ var ts; declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */); } break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: @@ -42396,78 +43562,78 @@ var ts; ts.Debug.fail("Unknown binary expression special property assignment kind"); } return checkStrictModeBinaryExpression(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return checkStrictModeCatchClause(node); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return checkStrictModeDeleteExpression(node); case 8 /* NumericLiteral */: return checkStrictModeNumericLiteral(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return checkStrictModePostfixUnaryExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return checkStrictModePrefixUnaryExpression(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return checkStrictModeWithStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return checkStrictModeLabeledStatement(node); - case 187 /* ThisType */: + case 188 /* ThisType */: seenThisKeyword = true; return; - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: break; // Binding the children will handle everything - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return bindTypeParameter(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return bindParameter(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return bindVariableDeclarationOrBindingElement(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: node.flowNode = currentFlow; return bindVariableDeclarationOrBindingElement(node); - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return bindPropertyWorker(node); - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 291 /* EnumMember */: + case 292 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: // If this is an ObjectLiteralExpression method, then it sits in the same space // 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 */ : 103359 /* MethodExcludes */); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return bindFunctionDeclaration(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */); - case 174 /* FunctionType */: - case 308 /* JSDocFunctionType */: - case 313 /* JSDocSignature */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 309 /* JSDocFunctionType */: + case 315 /* JSDocSignature */: + case 176 /* ConstructorType */: return bindFunctionOrConstructorType(node); - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 190 /* MappedType */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 191 /* MappedType */: return bindAnonymousTypeWorker(node); - case 319 /* JSDocClassTag */: + case 322 /* JSDocClassTag */: return bindJSDocClassTag(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return bindFunctionExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: var assignmentKind = ts.getAssignmentDeclarationKind(node); switch (assignmentKind) { case 7 /* ObjectDefinePropertyValue */: @@ -42486,65 +43652,65 @@ var ts; } break; // Members of classes, interfaces, and modules - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: // All classes are automatically in strict mode in ES6. inStrictMode = true; return bindClassLikeDeclaration(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return bindEnumDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return bindModuleDeclaration(node); // Jsx-attributes - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return bindJsxAttributes(node); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); // Imports and exports - case 260 /* ImportEqualsDeclaration */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 261 /* ImportEqualsDeclaration */: + case 264 /* NamespaceImport */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return bindNamespaceExportDeclaration(node); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return bindImportClause(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return bindExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return bindExportAssignment(node); - case 297 /* SourceFile */: + case 298 /* SourceFile */: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); - case 230 /* Block */: + case 231 /* Block */: if (!ts.isFunctionLike(node.parent)) { return; } // falls through - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 326 /* JSDocParameterTag */: - if (node.parent.kind === 313 /* JSDocSignature */) { + case 330 /* JSDocParameterTag */: + if (node.parent.kind === 315 /* JSDocSignature */) { return bindParameter(node); } - if (node.parent.kind !== 312 /* JSDocTypeLiteral */) { + if (node.parent.kind !== 314 /* JSDocTypeLiteral */) { break; } // falls through - case 333 /* JSDocPropertyTag */: + case 337 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 307 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 308 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } @@ -42572,8 +43738,8 @@ var ts; } function bindExportAssignment(node) { if (!container.symbol || !container.symbol.exports) { - // Export assignment in some sort of block construct - bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + // Incorrect export assignment in some sort of block construct + bindAnonymousDeclaration(node, 111551 /* Value */, getDeclarationName(node)); } else { var flags = ts.exportAssignmentIsAlias(node) @@ -42707,8 +43873,8 @@ var ts; } var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: var constructorSymbol = thisContainer.symbol; // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 62 /* EqualsToken */) { @@ -42730,11 +43896,11 @@ var ts; addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */); } break; - case 166 /* Constructor */: - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 167 /* Constructor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // this.foo assignment in a JavaScript class // Bind this property to the containing class var containingClass = thisContainer.parent; @@ -42746,7 +43912,7 @@ var ts; declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true); } break; - case 297 /* SourceFile */: + case 298 /* SourceFile */: // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script if (ts.hasDynamicName(node)) { break; @@ -42775,7 +43941,7 @@ var ts; if (node.expression.kind === 107 /* ThisKeyword */) { bindThisPropertyAssignment(node); } - else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 297 /* SourceFile */) { + else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 298 /* SourceFile */) { if (ts.isPrototypeAccess(node.expression)) { bindPrototypePropertyAssignment(node, node.parent); } @@ -42815,7 +43981,7 @@ var ts; } function bindObjectDefinePropertyAssignment(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); - var isToplevel = node.parent.parent.kind === 297 /* SourceFile */; + var isToplevel = node.parent.parent.kind === 298 /* SourceFile */; namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false); bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); } @@ -42924,8 +44090,8 @@ var ts; } function isTopLevelNamespaceAssignment(propertyAccess) { return ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 297 /* SourceFile */ - : propertyAccess.parent.parent.kind === 297 /* SourceFile */; + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 298 /* SourceFile */ + : propertyAccess.parent.parent.kind === 298 /* SourceFile */; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) { var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer); @@ -43004,7 +44170,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 252 /* ClassDeclaration */) { + if (node.kind === 253 /* ClassDeclaration */) { bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */); } else { @@ -43046,7 +44212,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { - if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true) && !ts.getJSDocTypeTag(node)) { + if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node) && !ts.getJSDocTypeTag(node)) { declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } else if (ts.isBlockOrCatchScoped(node)) { @@ -43070,7 +44236,7 @@ var ts; } } function bindParameter(node) { - if (node.kind === 326 /* JSDocParameterTag */ && container.kind !== 313 /* JSDocSignature */) { + if (node.kind === 330 /* JSDocParameterTag */ && container.kind !== 315 /* JSDocSignature */) { return; } if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) { @@ -43147,7 +44313,7 @@ var ts; declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */); } } - else if (node.parent.kind === 185 /* InferType */) { + else if (node.parent.kind === 186 /* InferType */) { var container_2 = getInferTypeContainer(node.parent); if (container_2) { if (!container_2.locals) { @@ -43166,7 +44332,7 @@ var ts; // reachability checks function shouldReportErrorOnModuleDeclaration(node) { var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && ts.shouldPreserveConstEnums(options)); } function checkUnreachable(node) { if (!(currentFlow.flags & 1 /* Unreachable */)) { @@ -43175,11 +44341,11 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 231 /* EmptyStatement */) || + (ts.isStatementButNotDeclaration(node) && node.kind !== 232 /* EmptyStatement */) || // report error on class declarations - node.kind === 252 /* ClassDeclaration */ || + node.kind === 253 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 256 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); + (node.kind === 257 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -43223,12 +44389,12 @@ var ts; } function isPurelyTypeDeclaration(s) { switch (s.kind) { - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: return true; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return getModuleInstanceState(s) !== 1 /* Instantiated */; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return ts.hasSyntacticModifier(s, 2048 /* Const */); default: return false; @@ -43428,7 +44594,7 @@ var ts; // (their type resolved directly to the member deeply referenced) // So to get the intervening symbols, we need to check if there's a type // query node on any of the symbol's declarations and get symbols there - if (d.type && d.type.kind === 176 /* TypeQuery */) { + if (d.type && d.type.kind === 177 /* TypeQuery */) { var query = d.type; var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); visitSymbol(entity); @@ -43655,6 +44821,7 @@ var ts; DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor"; DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment"; DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method"; + DeclarationMeaning[DeclarationMeaning["PrivateStatic"] = 16] = "PrivateStatic"; DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor"; DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod"; })(DeclarationMeaning || (DeclarationMeaning = {})); @@ -43746,12 +44913,12 @@ var ts; var instantiationCount = 0; var instantiationDepth = 0; var currentNode; - var typeCatalog = []; // NB: id is index + 1 var emptySymbols = ts.createSymbolTable(); var arrayVariances = [1 /* Covariant */]; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); @@ -43760,7 +44927,8 @@ var ts; var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16384 /* FreshLiteral */; + var checkBinaryExpression = createCheckBinaryExpression(); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); var globals = ts.createSymbolTable(); @@ -43783,7 +44951,6 @@ var ts; getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, - getTypeCatalog: function () { return typeCatalog; }, getTypeCount: function () { return typeCount; }, getInstantiationCount: function () { return totalInstantiationCount; }, getRelationCacheSizes: function () { return ({ @@ -43947,6 +45114,7 @@ var ts; return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, + getTypeOfPropertyOfContextualType: getTypeOfPropertyOfContextualType, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: function (node, candidatesOutArray, argumentCount) { return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */); @@ -43990,6 +45158,7 @@ var ts; }, tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); }, + tryFindAmbientModule: function (moduleName) { return tryFindAmbientModule(moduleName, /*withAugmentations*/ true); }, tryFindAmbientModuleWithoutAugmentations: function (moduleName) { // we deliberately exclude augmentations // since we are only interested in declarations of the module itself @@ -44108,6 +45277,7 @@ var ts; var templateLiteralTypes = new ts.Map(); var stringMappingTypes = new ts.Map(); var substitutionTypes = new ts.Map(); + var subtypeReductionCache = new ts.Map(); var evolvingArrayTypes = []; var undefinedProperties = new ts.Map(); var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -44116,14 +45286,14 @@ var ts; var autoType = createIntrinsicType(1 /* Any */, "any"); var wildcardType = createIntrinsicType(1 /* Any */, "any"); var errorType = createIntrinsicType(1 /* Any */, "error"); - var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */); + var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 131072 /* ContainsWideningType */); var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */); var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined"); var nullType = createIntrinsicType(65536 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 131072 /* ContainsWideningType */); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); @@ -44149,7 +45319,7 @@ var ts; var voidType = createIntrinsicType(16384 /* Void */, "void"); var neverType = createIntrinsicType(131072 /* Never */, "never"); var silentNeverType = createIntrinsicType(131072 /* Never */, "never"); - var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */); + var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 524288 /* NonInferrableType */); var implicitNeverType = createIntrinsicType(131072 /* Never */, "never"); var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never"); var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object"); @@ -44161,7 +45331,7 @@ var ts; var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; + emptyJsxObjectType.objectFlags |= 2048 /* JsxAttributes */; var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -44170,7 +45340,7 @@ var ts; var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */; + anyFunctionType.objectFlags |= 524288 /* NonInferrableType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -44250,6 +45420,7 @@ var ts; // This allows users to just specify library files they want to used through --lib // and they will not get an error from not having unrelated library files var deferredGlobalESSymbolConstructorSymbol; + var deferredGlobalESSymbolConstructorTypeSymbol; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; @@ -44301,7 +45472,7 @@ var ts; var flowNodePostSuper = []; var potentialThisCollisions = []; var potentialNewTargetCollisions = []; - var potentialWeakMapCollisions = []; + var potentialWeakMapSetCollisions = []; var awaitedTypeStack = []; var diagnostics = ts.createDiagnosticCollection(); var suggestionDiagnostics = ts.createDiagnosticCollection(); @@ -44448,6 +45619,25 @@ var ts; } return diagnostic; } + function addDeprecatedSuggestionWorker(declarations, diagnostic) { + var deprecatedTag = Array.isArray(declarations) ? ts.forEach(declarations, ts.getJSDocDeprecatedTag) : ts.getJSDocDeprecatedTag(declarations); + if (deprecatedTag) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(deprecatedTag, ts.Diagnostics.The_declaration_was_marked_as_deprecated_here)); + } + // We call `addRelatedInfo()` before adding the diagnostic to prevent duplicates. + suggestionDiagnostics.add(diagnostic); + return diagnostic; + } + function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { + var diagnostic = ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, deprecatedEntity); + return addDeprecatedSuggestionWorker(declarations, diagnostic); + } + function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) { + var diagnostic = deprecatedEntity + ? ts.createDiagnosticForNode(location, ts.Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity) + : ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, signatureString); + return addDeprecatedSuggestionWorker(declaration, diagnostic); + } function createSymbol(flags, name, checkFlags) { symbolCount++; var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); @@ -44561,7 +45751,7 @@ var ts; // as we will already report a "Declaration name conflicts..." error, and this error // won't make much sense. if (target !== globalThisSymbol) { - error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(source.declarations && ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } } else { // error @@ -44595,9 +45785,11 @@ var ts; } return target; function addDuplicateLocations(locs, symbol) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - ts.pushIfUnique(locs, decl); + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, decl); + } } } } @@ -44643,9 +45835,9 @@ var ts; }); } function mergeModuleAugmentation(moduleName) { - var _a, _b; + var _a, _b, _c; var moduleAugmentation = moduleName.parent; - if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + if (((_a = moduleAugmentation.symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]) !== moduleAugmentation) { // this is a combined symbol for multiple augmentations within the same file. // its symbol already has accumulated information for all declarations // so we need to add it just once - do the work only for first declaration @@ -44682,11 +45874,11 @@ var ts; patternAmbientModuleAugmentations.set(moduleName.text, merged); } else { - if (((_a = mainModule_1.exports) === null || _a === void 0 ? void 0 : _a.get("__export" /* ExportStar */)) && ((_b = moduleAugmentation.symbol.exports) === null || _b === void 0 ? void 0 : _b.size)) { + if (((_b = mainModule_1.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */)) && ((_c = moduleAugmentation.symbol.exports) === null || _c === void 0 ? void 0 : _c.size)) { // We may need to merge the module augmentation's exports into the target symbols of the resolved exports var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */); - for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) { - var _d = _c[_i], key = _d[0], value = _d[1]; + for (var _i = 0, _d = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _d.length; _i++) { + var _e = _d[_i], key = _e[0], value = _e[1]; if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) { mergeSymbol(resolvedExports.get(key), value); } @@ -44727,7 +45919,7 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks()); } function isGlobalSourceFile(node) { - return node.kind === 297 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 298 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -44786,17 +45978,17 @@ var ts; } if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) { // declaration is before usage - if (declaration.kind === 198 /* BindingElement */) { + if (declaration.kind === 199 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) - var errorBindingElement = ts.getAncestor(usage, 198 /* BindingElement */); + var errorBindingElement = ts.getAncestor(usage, 199 /* BindingElement */); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 249 /* VariableDeclaration */), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 250 /* VariableDeclaration */), usage); } - else if (declaration.kind === 249 /* VariableDeclaration */) { + else if (declaration.kind === 250 /* VariableDeclaration */) { // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } @@ -44810,7 +46002,7 @@ var ts; } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property - return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + return !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); } @@ -44826,19 +46018,19 @@ var ts; // or if usage is in a type context: // 1. inside a type query (typeof in type position) // 2. inside a jsdoc comment - if (usage.parent.kind === 270 /* ExportSpecifier */ || (usage.parent.kind === 266 /* ExportAssignment */ && usage.parent.isExportEquals)) { + if (usage.parent.kind === 271 /* ExportSpecifier */ || (usage.parent.kind === 267 /* ExportAssignment */ && usage.parent.isExportEquals)) { // export specifiers do not use the variable, they only make it available for use return true; } // When resolving symbols for exports, the `usage` location passed in can be the export site directly - if (usage.kind === 266 /* ExportAssignment */ && usage.isExportEquals) { + if (usage.kind === 267 /* ExportAssignment */ && usage.isExportEquals) { return true; } if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + if (compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields && ts.getContainingClass(declaration) && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); @@ -44853,9 +46045,9 @@ var ts; } function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { switch (declaration.parent.parent.kind) { - case 232 /* VariableStatement */: - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: + case 233 /* VariableStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, declContainer)) { @@ -44876,16 +46068,16 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 163 /* PropertyDeclaration */ && + current.parent.kind === 164 /* PropertyDeclaration */ && current.parent.initializer === current; if (initializerOfProperty) { if (ts.hasSyntacticModifier(current.parent, 32 /* Static */)) { - if (declaration.kind === 165 /* MethodDeclaration */) { + if (declaration.kind === 166 /* MethodDeclaration */) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 163 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(declaration, 32 /* Static */); + var isDeclarationInstanceProperty = declaration.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(declaration, 32 /* Static */); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } @@ -44907,19 +46099,19 @@ var ts; return "quit"; } switch (node.kind) { - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return true; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // even when stopping at any property declaration, they need to come from the same class return stopAtAnyPropertyDeclaration && (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent) ? "quit" : true; - case 230 /* Block */: + case 231 /* Block */: switch (node.parent.kind) { - case 167 /* GetAccessor */: - case 165 /* MethodDeclaration */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 166 /* MethodDeclaration */: + case 169 /* SetAccessor */: return true; default: return false; @@ -44934,7 +46126,11 @@ var ts; function useOuterVariableScopeInParameter(result, location, lastLocation) { var target = ts.getEmitScriptTarget(compilerOptions); var functionLocation = location; - if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + if (ts.isParameter(lastLocation) + && functionLocation.body + && result.valueDeclaration + && result.valueDeclaration.pos >= functionLocation.body.pos + && result.valueDeclaration.end <= functionLocation.body.end) { // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body // - static field in a class expression // - optional chaining pre-es2020 @@ -44955,21 +46151,21 @@ var ts; } function requiresScopeChangeWorker(node) { switch (node.kind) { - case 209 /* ArrowFunction */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 166 /* Constructor */: + case 210 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 167 /* Constructor */: // do not descend into these return false; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 288 /* PropertyAssignment */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 289 /* PropertyAssignment */: return requiresScopeChangeWorker(node.name); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // static properties in classes introduce temporary variables if (ts.hasStaticModifier(node)) { - return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields; + return target < 99 /* ESNext */ || !useDefineForClassFields; } return requiresScopeChangeWorker(node.name); default: @@ -44998,6 +46194,7 @@ var ts; return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); } function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) { + var _a; var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; @@ -45020,12 +46217,12 @@ 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 & 788968 /* Type */ && lastLocation.kind !== 311 /* JSDocComment */) { + if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 312 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || - lastLocation.kind === 160 /* Parameter */ || - lastLocation.kind === 159 /* TypeParameter */ + lastLocation.kind === 161 /* Parameter */ || + lastLocation.kind === 160 /* TypeParameter */ // local types not visible outside the function body : false; } @@ -45040,13 +46237,13 @@ var ts; // however it is detected separately when checking initializers of parameters // to make sure that they reference no variables declared after them. useResult = - lastLocation.kind === 160 /* Parameter */ || + lastLocation.kind === 161 /* Parameter */ || (lastLocation === location.type && !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); } } } - else if (location.kind === 184 /* ConditionalType */) { + else if (location.kind === 185 /* ConditionalType */) { // A type parameter declared using 'infer T' in a conditional type is visible only in // the true branch of the conditional type. useResult = lastLocation === location.trueType; @@ -45061,14 +46258,14 @@ var ts; } withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation); switch (location.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; // falls through - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports || emptySymbols; - if (location.kind === 297 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) { + if (location.kind === 298 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports.get("default" /* Default */)) { @@ -45092,13 +46289,13 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && - (ts.getDeclarationOfKind(moduleExport, 270 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 269 /* NamespaceExport */))) { + (ts.getDeclarationOfKind(moduleExport, 271 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 270 /* NamespaceExport */))) { break; } } // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs) if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) { - if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !((_a = result.declarations) === null || _a === void 0 ? void 0 : _a.some(ts.isJSDocTypeAlias))) { result = undefined; } else { @@ -45106,12 +46303,12 @@ var ts; } } break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // TypeScript 1.0 spec (April 2014): 8.4.1 // Initializer expressions for instance member variables are evaluated in the scope // of the class constructor body but are not permitted to reference parameters or @@ -45128,9 +46325,9 @@ var ts; } } break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: // 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! @@ -45149,7 +46346,7 @@ var ts; } break loop; } - if (location.kind === 221 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 222 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -45157,7 +46354,7 @@ var ts; } } break; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 93 /* ExtendsKeyword */) { var container = location.parent.parent; @@ -45177,9 +46374,9 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 253 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 254 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -45187,24 +46384,24 @@ var ts; } } break; - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: // when targeting ES6 or higher there is no 'arguments' in an arrow function // for lower compile targets the resolved symbol is used to emit an error if (compilerOptions.target >= 2 /* ES2015 */) { break; } // falls through - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 251 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 252 /* FunctionDeclaration */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -45217,7 +46414,7 @@ var ts; } } break; - case 161 /* Decorator */: + case 162 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -45226,7 +46423,7 @@ var ts; // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. // } // - if (location.parent && location.parent.kind === 160 /* Parameter */) { + if (location.parent && location.parent.kind === 161 /* Parameter */) { location = location.parent; } // @@ -45241,20 +46438,20 @@ var ts; // declare function y(x: T): any; // @param(1 as T) // <-- T should resolve to the type alias outside of class C // class C {} - if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 252 /* ClassDeclaration */)) { + if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 253 /* ClassDeclaration */)) { location = location.parent; } break; - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: // js type aliases do not resolve names from their host, so skip past it var root = ts.getJSDocRoot(location); if (root) { location = root.parent; } break; - case 160 /* Parameter */: + case 161 /* Parameter */: if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && ts.isBindingPattern(lastLocation))) { if (!associatedDeclarationForContainingInitializerOrBindingName) { @@ -45262,7 +46459,7 @@ var ts; } } break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: if (lastLocation && (lastLocation === location.initializer || lastLocation === location.name && ts.isBindingPattern(lastLocation))) { if (ts.isParameterDeclaration(location) && !associatedDeclarationForContainingInitializerOrBindingName) { @@ -45270,7 +46467,7 @@ var ts; } } break; - case 185 /* InferType */: + case 186 /* InferType */: if (meaning & 262144 /* TypeParameter */) { var parameterName = location.typeParameter.name; if (parameterName && name === parameterName.escapedText) { @@ -45294,7 +46491,7 @@ var ts; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 297 /* SourceFile */); + ts.Debug.assert(lastLocation.kind === 298 /* SourceFile */); if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } @@ -45323,6 +46520,10 @@ var ts; var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); + var isGlobalScopeAugmentationDeclaration = suggestion && suggestion.valueDeclaration && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); + if (isGlobalScopeAugmentationDeclaration) { + suggestion = undefined; + } if (suggestion) { var suggestionName = symbolToString(suggestion); var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); @@ -45349,7 +46550,7 @@ var ts; } // Perform extra checks only if error reporting was requested if (nameNotFoundMessage) { - if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields)) { // We have a match, but the reference occurred within a property initializer and the identifier also binds // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed // with ESNext+useDefineForClassFields because the scope semantics are different. @@ -45419,10 +46620,10 @@ var ts; } } function getIsDeferredContext(location, lastLocation) { - if (location.kind !== 209 /* ArrowFunction */ && location.kind !== 208 /* FunctionExpression */) { + if (location.kind !== 210 /* ArrowFunction */ && location.kind !== 209 /* FunctionExpression */) { // initializers in instance property declaration of class like entities are executed in constructor and thus deferred return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) || - (location.kind === 163 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(location, 32 /* Static */))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred + (location.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(location, 32 /* Static */))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred } if (lastLocation && lastLocation === location.name) { return false; @@ -45435,12 +46636,12 @@ var ts; } function isSelfReferenceLocation(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 256 /* ModuleDeclaration */: // For `namespace N { N; }` + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 257 /* ModuleDeclaration */: // For `namespace N { N; }` return true; default: return false; @@ -45450,12 +46651,14 @@ var ts; return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } function isTypeParameterSymbolDeclaredInContainer(symbol, container) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (decl.kind === 159 /* TypeParameter */) { - var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; - if (parent === container) { - return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.kind === 160 /* TypeParameter */) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + } } } } @@ -45508,9 +46711,9 @@ var ts; function getEntityNameForExtendingInterface(node) { switch (node.kind) { case 78 /* Identifier */: - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: if (ts.isEntityNameExpression(node.expression)) { return node.expression; } @@ -45554,7 +46757,7 @@ var ts; return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown"; } function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) { - if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 270 /* ExportSpecifier */) { + if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 271 /* ExportSpecifier */) { error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name); return true; } @@ -45623,13 +46826,14 @@ var ts; return false; } function checkResolvedBlockScopedVariable(result, errorLocation) { + var _a; ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) { // constructor functions aren't block scoped return; } // Block-scoped variables cannot be used before their definition - var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 255 /* EnumDeclaration */); }); + var declaration = (_a = result.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 256 /* EnumDeclaration */); }); if (declaration === undefined) return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration"); if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -45646,7 +46850,7 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); - if (compilerOptions.preserveConstEnums) { + if (ts.shouldPreserveConstEnums(compilerOptions)) { diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); } } @@ -45664,20 +46868,20 @@ var ts; } function getAnyImportSyntax(node) { switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return node; - case 262 /* ImportClause */: + case 263 /* ImportClause */: return node.parent; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return node.parent.parent; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: return node.parent.parent.parent; default: return undefined; } } function getDeclarationOfAliasSymbol(symbol) { - return ts.find(symbol.declarations, isAliasSymbolDeclaration); + return symbol.declarations && ts.findLast(symbol.declarations, isAliasSymbolDeclaration); } /** * An alias symbol is created by one of the following declarations: @@ -45692,25 +46896,26 @@ var ts; * module.exports = * {} * {name: } + * const { x } = require ... */ function isAliasSymbolDeclaration(node) { - return node.kind === 260 /* ImportEqualsDeclaration */ - || node.kind === 259 /* NamespaceExportDeclaration */ - || node.kind === 262 /* ImportClause */ && !!node.name - || node.kind === 263 /* NamespaceImport */ - || node.kind === 269 /* NamespaceExport */ - || node.kind === 265 /* ImportSpecifier */ - || node.kind === 270 /* ExportSpecifier */ - || node.kind === 266 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + return node.kind === 261 /* ImportEqualsDeclaration */ + || node.kind === 260 /* NamespaceExportDeclaration */ + || node.kind === 263 /* ImportClause */ && !!node.name + || node.kind === 264 /* NamespaceImport */ + || node.kind === 270 /* NamespaceExport */ + || node.kind === 266 /* ImportSpecifier */ + || node.kind === 271 /* ExportSpecifier */ + || node.kind === 267 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) || ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && ts.exportAssignmentIsAlias(node) || ts.isAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableOrJsExpression(node.parent.right) - || node.kind === 289 /* ShorthandPropertyAssignment */ - || node.kind === 288 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) - || ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true); + || node.kind === 290 /* ShorthandPropertyAssignment */ + || node.kind === 289 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) + || ts.isRequireVariableDeclaration(node); } function isAliasableOrJsExpression(e) { return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e); @@ -45723,7 +46928,7 @@ var ts; ? resolveSymbol(getPropertyOfType(resolveExternalModuleTypeByLiteral(name), commonJSPropertyAccess.name.escapedText)) : undefined; } - if (ts.isVariableDeclaration(node) || node.moduleReference.kind === 272 /* ExternalModuleReference */) { + if (ts.isVariableDeclaration(node) || node.moduleReference.kind === 273 /* ExternalModuleReference */) { var immediate = resolveExternalModuleName(node, ts.getExternalModuleRequireArgument(node) || ts.getExternalModuleImportEqualsDeclarationExpression(node)); var resolved_4 = resolveExternalModuleSymbol(immediate); markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false); @@ -45790,6 +46995,7 @@ var ts; return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias); } function getTargetOfImportClause(node, dontResolveAlias) { + var _a; var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { var exportDefaultSymbol = void 0; @@ -45799,7 +47005,7 @@ var ts; else { exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias); } - var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); if (!exportDefaultSymbol && !hasSyntheticDefault) { if (hasExportAssignmentSymbol(moduleSymbol)) { @@ -45807,7 +47013,9 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */); var exportAssignment = exportEqualsSymbol.valueDeclaration; var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName); - ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); + if (exportAssignment) { + ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); + } } else { reportNonDefaultExport(moduleSymbol, node); @@ -45824,7 +47032,7 @@ var ts; } } function reportNonDefaultExport(moduleSymbol, node) { - var _a, _b; + var _a, _b, _c; if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); } @@ -45832,7 +47040,7 @@ var ts; var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */); if (exportStar) { - var defaultExport = ts.find(exportStar.declarations, function (decl) { + var defaultExport = (_c = exportStar.declarations) === null || _c === void 0 ? void 0 : _c.find(function (decl) { var _a, _b; return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier && ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */))); @@ -45910,7 +47118,7 @@ var ts; } } function getExternalModuleMember(node, specifier, dontResolveAlias) { - var _a; + var _a, _b; if (dontResolveAlias === void 0) { dontResolveAlias = false; } var moduleSpecifier = ts.getExternalModuleRequireArgument(node) || node.moduleSpecifier; var moduleSymbol = resolveExternalModuleName(node, moduleSpecifier); // TODO: GH#18217 @@ -45919,7 +47127,7 @@ var ts; return undefined; } var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop); - var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, dontResolveAlias, suppressInteropError); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, /*dontResolveAlias*/ false, suppressInteropError); if (targetSymbol) { if (name.escapedText) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { @@ -45937,7 +47145,7 @@ var ts; symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); var symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias); if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) { - var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var file = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } @@ -45957,7 +47165,7 @@ var ts; } } else { - if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default" /* Default */)) { + if ((_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */)) { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); } else { @@ -45970,8 +47178,8 @@ var ts; } } function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) { - var _a; - var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText); + var _a, _b; + var localSymbol = (_b = (_a = moduleSymbol.valueDeclaration) === null || _a === void 0 ? void 0 : _a.locals) === null || _b === void 0 ? void 0 : _b.get(name.escapedText); var exports = moduleSymbol.exports; if (localSymbol) { var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */); @@ -45983,9 +47191,11 @@ var ts; var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined; var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); - ts.addRelatedInfo.apply(void 0, __spreadArray([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { - return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); - }))); + if (localSymbol.declarations) { + ts.addRelatedInfo.apply(void 0, __spreadArray([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { + return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); + }))); + } } } else { @@ -46072,31 +47282,31 @@ var ts; function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: - case 249 /* VariableDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 250 /* VariableDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return getTargetOfImportClause(node, dontRecursivelyResolve); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: return getTargetOfNamespaceExport(node, dontRecursivelyResolve); - case 265 /* ImportSpecifier */: - case 198 /* BindingElement */: + case 266 /* ImportSpecifier */: + case 199 /* BindingElement */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); - case 266 /* ExportAssignment */: - case 216 /* BinaryExpression */: + case 267 /* ExportAssignment */: + case 217 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return getTargetOfPropertyAssignment(node, dontRecursivelyResolve); - case 202 /* ElementAccessExpression */: - case 201 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: return getTargetOfAccessExpression(node, dontRecursivelyResolve); default: return ts.Debug.fail(); @@ -46248,13 +47458,13 @@ var ts; entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 78 /* Identifier */ || entityName.parent.kind === 157 /* QualifiedName */) { + if (entityName.kind === 78 /* Identifier */ || entityName.parent.kind === 158 /* QualifiedName */) { return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 260 /* ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 261 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } @@ -46278,9 +47488,9 @@ var ts; return getMergedSymbol(symbolFromJSPrototype); } } - else if (name.kind === 157 /* QualifiedName */ || name.kind === 201 /* PropertyAccessExpression */) { - var left = name.kind === 157 /* QualifiedName */ ? name.left : name.expression; - var right = name.kind === 157 /* QualifiedName */ ? name.right : name.name; + else if (name.kind === 158 /* QualifiedName */ || name.kind === 202 /* PropertyAccessExpression */) { + var left = name.kind === 158 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 158 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -46288,18 +47498,17 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJSFile(name)) { - if (namespace.valueDeclaration && - ts.isVariableDeclaration(namespace.valueDeclaration) && - namespace.valueDeclaration.initializer && - isCommonJsRequire(namespace.valueDeclaration.initializer)) { - var moduleName = namespace.valueDeclaration.initializer.arguments[0]; - var moduleSym = resolveExternalModuleName(moduleName, moduleName); - if (moduleSym) { - var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); - if (resolvedModuleSymbol) { - namespace = resolvedModuleSymbol; - } + if (namespace.valueDeclaration && + ts.isInJSFile(namespace.valueDeclaration) && + ts.isVariableDeclaration(namespace.valueDeclaration) && + namespace.valueDeclaration.initializer && + isCommonJsRequire(namespace.valueDeclaration.initializer)) { + var moduleName = namespace.valueDeclaration.initializer.arguments[0]; + var moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; } } } @@ -46320,7 +47529,7 @@ var ts; throw ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); - if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 266 /* ExportAssignment */)) { + if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 267 /* ExportAssignment */)) { markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true); } return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); @@ -46557,7 +47766,7 @@ var ts; function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { - if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 297 /* SourceFile */)) { + if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 298 /* SourceFile */)) { var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop"; @@ -46608,7 +47817,10 @@ var ts; var exports = getExportsOfModuleAsArray(moduleSymbol); var exportEquals = resolveExternalModuleSymbol(moduleSymbol); if (exportEquals !== moduleSymbol) { - ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); + var type = getTypeOfSymbol(exportEquals); + if (shouldTreatPropertiesOfExternalModuleAsExports(type)) { + ts.addRange(exports, getPropertiesOfType(type)); + } } return exports; } @@ -46628,11 +47840,14 @@ var ts; return undefined; } var type = getTypeOfSymbol(exportEquals); - return type.flags & 131068 /* Primitive */ || - ts.getObjectFlags(type) & 1 /* Class */ || - isArrayOrTupleLikeType(type) - ? undefined - : getPropertyOfType(type, memberName); + return shouldTreatPropertiesOfExternalModuleAsExports(type) ? getPropertyOfType(type, memberName) : undefined; + } + function shouldTreatPropertiesOfExternalModuleAsExports(resolvedExternalModuleType) { + return !(resolvedExternalModuleType.flags & 131068 /* Primitive */ || + ts.getObjectFlags(resolvedExternalModuleType) & 1 /* Class */ || + // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path + isArrayType(resolvedExternalModuleType) || + isTupleType(resolvedExternalModuleType)); } function getExportsOfSymbol(symbol) { return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : @@ -46690,11 +47905,13 @@ var ts; if (exportStars) { var nestedSymbols = ts.createSymbolTable(); var lookupTable_1 = new ts.Map(); - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - var exportedSymbols = visit(resolvedModule); - extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + if (exportStars.declarations) { + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + } } lookupTable_1.forEach(function (_a, id) { var exportsWithDuplicate = _a.exportsWithDuplicate; @@ -46777,11 +47994,28 @@ var ts; var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); var objectLiteralContainer = getVariableDeclarationOfObjectLiteral(container, meaning); - if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { + if (enclosingDeclaration && + container.flags & getQualifiedLeftMeaning(meaning) && + getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { return ts.append(ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers), objectLiteralContainer); // This order expresses a preference for the real container if it is in scope } - var res = ts.append(ts.append(additionalContainers, container), objectLiteralContainer); - return ts.concatenate(res, reexportContainers); + // we potentially have a symbol which is a member of the instance side of something - look for a variable in scope with the container's type + // which may be acting like a namespace (eg, `Symbol` acts like a namespace when looking up `Symbol.toStringTag`) + var firstVariableMatch = !(container.flags & getQualifiedLeftMeaning(meaning)) + && container.flags & 788968 /* Type */ + && getDeclaredTypeOfSymbol(container).flags & 524288 /* Object */ + && meaning === 111551 /* Value */ + ? forEachSymbolTableInScope(enclosingDeclaration, function (t) { + return ts.forEachEntry(t, function (s) { + if (s.flags & getQualifiedLeftMeaning(meaning) && getTypeOfSymbol(s) === getDeclaredTypeOfSymbol(container)) { + return s; + } + }); + }) : undefined; + var res = firstVariableMatch ? __spreadArray(__spreadArray([firstVariableMatch], additionalContainers), [container]) : __spreadArray(__spreadArray([], additionalContainers), [container]); + res = ts.append(res, objectLiteralContainer); + res = ts.addRange(res, reexportContainers); + return res; } var candidates = ts.mapDefined(symbol.declarations, function (d) { if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) { @@ -46859,7 +48093,7 @@ var ts; var members = node.members; for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { var member = members_3[_i]; - if (member.kind === 166 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 167 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -46868,7 +48102,9 @@ var ts; var result = new Type(checker, flags); typeCount++; result.id = typeCount; - typeCatalog.push(result); + if (produceDiagnostics) { // Only record types from one checker + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.recordType(result); + } return result; } function createOriginType(flags) { @@ -46928,14 +48164,23 @@ var ts; }); return result || ts.emptyArray; } + function getNamedOrIndexSignatureMembers(members) { + var result = getNamedMembers(members); + var index = getIndexSymbolFromSymbolTable(members); + return index ? ts.concatenate(result, [index]) : result; + } function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - type.members = members; - type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members); - type.callSignatures = callSignatures; - type.constructSignatures = constructSignatures; - type.stringIndexInfo = stringIndexInfo; - type.numberIndexInfo = numberIndexInfo; - return type; + var resolved = type; + resolved.members = members; + resolved.properties = ts.emptyArray; + resolved.callSignatures = callSignatures; + resolved.constructSignatures = constructSignatures; + resolved.stringIndexInfo = stringIndexInfo; + resolved.numberIndexInfo = numberIndexInfo; + // This can loop back to getPropertyOfType() which would crash if `callSignatures` & `constructSignatures` are not initialized. + if (members !== emptySymbols) + resolved.properties = getNamedMembers(members); + return resolved; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); @@ -46958,28 +48203,28 @@ var ts; var _loop_8 = function (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { - if (result = callback(location.locals)) { + if (result = callback(location.locals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } } switch (location.kind) { - case 297 /* SourceFile */: + case 298 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } // falls through - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var sym = getSymbolOfNode(location); // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred // to one another anyway) - if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) { + if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return { value: result }; } break; - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: // Type parameters are bound into `members` lists so they can merge across declarations // This is troublesome, since in all other respects, they behave like locals :cries: // TODO: the below is shared with similar code in `resolveName` - in fact, rephrasing all this symbol @@ -47005,7 +48250,7 @@ var ts; if (typeof state_2 === "object") return state_2.value; } - return callback(globals); + return callback(globals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true); } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace @@ -47025,11 +48270,11 @@ var ts; /** * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) */ - function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) { + function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification, isLocalNameLookup) { if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - var result = trySymbolTable(symbols, ignoreQualification); + var result = trySymbolTable(symbols, ignoreQualification, isLocalNameLookup); visitedSymbolTables.pop(); return result; } @@ -47047,7 +48292,7 @@ var ts; !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning)); } - function trySymbolTable(symbols, ignoreQualification) { + function trySymbolTable(symbols, ignoreQualification, isLocalNameLookup) { // If symbol is directly available by its name in the symbol table if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { return [symbol]; @@ -47060,9 +48305,11 @@ var ts; && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // If we're looking up a local name to reference directly, omit namespace reexports, otherwise when we're trawling through an export list to make a dotted name, we can keep it + && (isLocalNameLookup ? !ts.some(symbolFromSymbolTable.declarations, ts.isNamespaceReexportDeclaration) : true) // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ // See similar comment in `resolveName` for details - && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 270 /* ExportSpecifier */))) { + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 271 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification); if (candidate) { @@ -47106,7 +48353,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 270 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 271 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -47121,10 +48368,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: continue; default: return false; @@ -47162,7 +48409,7 @@ var ts; return hasAccessibleDeclarations; } } - else if (allowModules) { + if (allowModules) { if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { if (shouldComputeAliasesToMakeVisible) { earlyModuleBail = true; @@ -47236,7 +48483,8 @@ var ts; return { accessibility: 2 /* CannotBeNamed */, errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), - errorModuleName: symbolToString(symbolExternalModule) + errorModuleName: symbolToString(symbolExternalModule), + errorNode: ts.isInJSFile(enclosingDeclaration) ? enclosingDeclaration : undefined, }; } } @@ -47253,10 +48501,10 @@ var ts; return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { - return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -47312,14 +48560,14 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 176 /* TypeQuery */ || + if (entityName.parent.kind === 177 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || - entityName.parent.kind === 158 /* ComputedPropertyName */) { + entityName.parent.kind === 159 /* ComputedPropertyName */) { // Typeof value meaning = 111551 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 157 /* QualifiedName */ || entityName.kind === 201 /* PropertyAccessExpression */ || - entityName.parent.kind === 260 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 158 /* QualifiedName */ || entityName.kind === 202 /* PropertyAccessExpression */ || + entityName.parent.kind === 261 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1920 /* Namespace */; @@ -47360,7 +48608,7 @@ var ts; function symbolToStringWorker(writer) { var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217 // add neverAsciiEscape for GH#39027 - var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 297 /* SourceFile */ ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true }); + var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 298 /* SourceFile */ ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); return writer; @@ -47372,10 +48620,10 @@ var ts; function signatureToStringWorker(writer) { var sigOutput; if (flags & 262144 /* WriteArrowStyleSignature */) { - sigOutput = kind === 1 /* Construct */ ? 175 /* ConstructorType */ : 174 /* FunctionType */; + sigOutput = kind === 1 /* Construct */ ? 176 /* ConstructorType */ : 175 /* FunctionType */; } else { - sigOutput = kind === 1 /* Construct */ ? 170 /* ConstructSignature */ : 169 /* CallSignature */; + sigOutput = kind === 1 /* Construct */ ? 171 /* ConstructSignature */ : 170 /* CallSignature */; } var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); @@ -47415,14 +48663,14 @@ var ts; return typeToString(type, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); } function symbolValueDeclarationIsContextSensitive(symbol) { - return symbol && symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration); + return symbol && !!symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration); } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0 /* None */; } return flags & 814775659 /* NodeBuilderFlagsMask */; } function isClassInstanceSide(type) { - return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(ts.getObjectFlags(type) & 1073741824 /* IsClassInstanceClone */)); + return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & 524288 /* Object */) && !!(ts.getObjectFlags(type) & 16777216 /* IsClassInstanceClone */))); } function createNodeBuilder() { return { @@ -47756,7 +49004,9 @@ var ts; 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 === 221 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || + else if (symbol.flags & 32 /* Class */ + && !getBaseTypeVariableOfClass(symbol) + && !(symbol.valueDeclaration && symbol.valueDeclaration.kind === 222 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, isInstanceType); @@ -47787,7 +49037,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 297 /* SourceFile */ || declaration.parent.kind === 257 /* ModuleBlock */; + return declaration.parent.kind === 298 /* SourceFile */ || declaration.parent.kind === 258 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -47838,12 +49088,12 @@ var ts; } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 174 /* FunctionType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 175 /* FunctionType */, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 175 /* ConstructorType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 176 /* ConstructorType */, context); return signatureNode; } } @@ -48023,17 +49273,17 @@ var ts; var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 169 /* CallSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 170 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; if (signature.flags & 4 /* Abstract */) continue; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 170 /* ConstructSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 171 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { var indexSignature = void 0; - if (resolvedType.objectFlags & 2048 /* ReverseMapped */) { + if (resolvedType.objectFlags & 1024 /* ReverseMapped */) { indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context, createElidedInformationPlaceholder(context)); } else { @@ -48077,15 +49327,29 @@ var ts; } return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } + function shouldUsePlaceholderForProperty(propertySymbol, context) { + var _a; + // Use placeholders for reverse mapped types we've either already descended into, or which + // are nested reverse mappings within a mapping over a non-anonymous type. The later is a restriction mostly just to + // reduce the blowup in printback size from doing, eg, a deep reverse mapping over `Window`. + // Since anonymous types usually come from expressions, this allows us to preserve the output + // for deep mappings which likely come from expressions, while truncating those parts which + // come from mappings over library functions. + return !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */) + && (ts.contains(context.reverseMappedStack, propertySymbol) + || (((_a = context.reverseMappedStack) === null || _a === void 0 ? void 0 : _a[0]) + && !(ts.getObjectFlags(ts.last(context.reverseMappedStack).propertyType) & 16 /* Anonymous */))); + } function addPropertyToElementList(propertySymbol, context, typeElements) { + var _a; var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */); - var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? + var propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */ && isLateBoundName(propertySymbol.escapedName)) { var decl = ts.first(propertySymbol.declarations); - if (hasLateBindableName(decl)) { + if (propertySymbol.declarations && hasLateBindableName(decl)) { if (ts.isBinaryExpression(decl)) { var name = ts.getNameOfDeclaration(decl); if (name && ts.isElementAccessExpression(name) && ts.isPropertyAccessEntityNameExpression(name.argumentExpression)) { @@ -48097,29 +49361,34 @@ var ts; } } } - context.enclosingDeclaration = saveEnclosingDeclaration; + context.enclosingDeclaration = propertySymbol.valueDeclaration || ((_a = propertySymbol.declarations) === null || _a === void 0 ? void 0 : _a[0]) || saveEnclosingDeclaration; var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context); + context.enclosingDeclaration = saveEnclosingDeclaration; context.approximateLength += (ts.symbolName(propertySymbol).length + 1); var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined; if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */); for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { var signature = signatures_1[_i]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 164 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken }); + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 165 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken }); typeElements.push(preserveCommentsOn(methodDeclaration)); } } else { - var savedFlags = context.flags; - context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0; var propertyTypeNode = void 0; - if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) { + if (shouldUsePlaceholderForProperty(propertySymbol, context)) { propertyTypeNode = createElidedInformationPlaceholder(context); } else { + if (propertyIsReverseMapped) { + context.reverseMappedStack || (context.reverseMappedStack = []); + context.reverseMappedStack.push(propertySymbol); + } propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); + if (propertyIsReverseMapped) { + context.reverseMappedStack.pop(); + } } - context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(142 /* ReadonlyKeyword */)] : undefined; if (modifiers) { context.approximateLength += 9; @@ -48128,9 +49397,10 @@ var ts; typeElements.push(preserveCommentsOn(propertySignature)); } function preserveCommentsOn(node) { - if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 333 /* JSDocPropertyTag */; })) { - var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 333 /* JSDocPropertyTag */; }); - var commentText = d.comment; + var _a; + if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 337 /* JSDocPropertyTag */; })) { + var d = (_a = propertySymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 337 /* JSDocPropertyTag */; }); + var commentText = ts.getTextOfJSDocComment(d.comment); if (commentText) { ts.setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]); } @@ -48159,25 +49429,25 @@ var ts; var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */); /** Map from type reference identifier text to [type, index in `result` where the type node is] */ var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; - var result_4 = []; + var result_5 = []; var i = 0; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var type = types_2[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result_4.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + result_5.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result_4.push(typeNode_1); + result_5.push(typeNode_1); } break; } context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result_4.push(typeNode); + result_5.push(typeNode); if (seenNames && ts.isIdentifierTypeReference(typeNode)) { - seenNames.add(typeNode.typeName.escapedText, [type, result_4.length - 1]); + seenNames.add(typeNode.typeName.escapedText, [type, result_5.length - 1]); } } } @@ -48199,13 +49469,13 @@ var ts; })) { for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { var _a = types_3[_i], type = _a[0], resultIndex = _a[1]; - result_4[resultIndex] = typeToTypeNodeHelper(type, context); + result_5[resultIndex] = typeToTypeNodeHelper(type, context); } } }); context.flags = saveContextFlags; } - return result_4; + return result_5; } } function typesAreSameReference(a, b) { @@ -48247,7 +49517,7 @@ var ts; } var expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0]; // If the expanded parameter list had a variadic in a non-trailing position, don't expand it - var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 166 /* Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); + var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 167 /* Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -48274,25 +49544,25 @@ var ts; } } var modifiers = options === null || options === void 0 ? void 0 : options.modifiers; - if ((kind === 175 /* ConstructorType */) && signature.flags & 4 /* Abstract */) { + if ((kind === 176 /* ConstructorType */) && signature.flags & 4 /* Abstract */) { var flags = ts.modifiersToFlags(modifiers); modifiers = ts.factory.createModifiersFromModifierFlags(flags | 128 /* Abstract */); } context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum - var node = kind === 169 /* CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : - kind === 170 /* ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : - kind === 164 /* MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : - kind === 165 /* MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === 166 /* Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) : - kind === 167 /* GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : - kind === 168 /* SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : - kind === 171 /* IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) : - kind === 308 /* JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : - kind === 174 /* FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 175 /* ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : - kind === 251 /* FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : - kind === 208 /* FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : - kind === 209 /* ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) : + var node = kind === 170 /* CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) : + kind === 171 /* ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : + kind === 165 /* MethodSignature */ ? ts.factory.createMethodSignature(modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : + kind === 166 /* MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 167 /* Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) : + kind === 168 /* GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) : + kind === 169 /* SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) : + kind === 172 /* IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) : + kind === 309 /* JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) : + kind === 175 /* FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : + kind === 176 /* ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) : + kind === 252 /* FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) : + kind === 209 /* FunctionExpression */ ? ts.factory.createFunctionExpression(modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) : + kind === 210 /* ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) : ts.Debug.assertNever(kind); if (typeArguments) { node.typeArguments = ts.factory.createNodeArray(typeArguments); @@ -48314,9 +49584,9 @@ var ts; return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 160 /* Parameter */); + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 161 /* Parameter */); if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 326 /* JSDocParameterTag */); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 330 /* JSDocParameterTag */); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -48331,7 +49601,7 @@ var ts; var dotDotDotToken = isRest ? ts.factory.createToken(25 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 78 /* Identifier */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : - parameterDeclaration.name.kind === 157 /* QualifiedName */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 158 /* QualifiedName */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); @@ -48496,11 +49766,11 @@ var ts; } function getSpecifierForModuleSymbol(symbol, context) { var _a; - var file = ts.getDeclarationOfKind(symbol, 297 /* SourceFile */); + var file = ts.getDeclarationOfKind(symbol, 298 /* SourceFile */); if (!file) { var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); }); if (equivalentFileSymbol) { - file = ts.getDeclarationOfKind(equivalentFileSymbol, 297 /* SourceFile */); + file = ts.getDeclarationOfKind(equivalentFileSymbol, 298 /* SourceFile */); } } if (file && file.moduleName !== undefined) { @@ -48511,8 +49781,8 @@ var ts; if (context.tracker.trackReferencedAmbientModule) { var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); if (ts.length(ambientDecls)) { - for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { - var decl = ambientDecls_1[_i]; + for (var _i = 0, _b = ambientDecls; _i < _b.length; _i++) { + var decl = _b[_i]; context.tracker.trackReferencedAmbientModule(decl, symbol); } } @@ -48539,7 +49809,7 @@ var ts; // specifier preference var moduleResolverHost = context.tracker.moduleResolverHost; var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; - specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "project-relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined })); (_a = links.specifierCache) !== null && _a !== void 0 ? _a : (links.specifierCache = new ts.Map()); links.specifierCache.set(contextFile.path, specifier); } @@ -48683,7 +49953,7 @@ var ts; var chain = lookupSymbolChain(symbol, context, meaning); if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) { + && !(context.flags & 65536 /* AllowQualifiedNameInPlaceOfIdentifier */)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); @@ -48763,9 +50033,6 @@ var ts; if (fromNameType) { return fromNameType; } - if (ts.isKnownSymbol(symbol)) { - return ts.factory.createComputedPropertyName(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("Symbol"), symbol.escapedName.substr(3))); - } var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName); var stringNamed = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isStringNamed); return createPropertyNameNodeForIdentifierOrLiteral(rawName, stringNamed, singleQuote); @@ -48832,13 +50099,13 @@ var ts; function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { if (type !== errorType && enclosingDeclaration) { var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation) && !ts.isGetAccessorDeclaration(declWithExistingAnnotation)) { // try to reuse the existing annotation var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { - var result_5 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); - if (result_5) { - return result_5; + var result_6 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_6) { + return result_6; } } } @@ -48855,10 +50122,14 @@ var ts; function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { if (type !== errorType && context.enclosingDeclaration) { var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); - if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { - var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); - if (result) { - return result; + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation) { + var annotated = getTypeFromTypeNode(annotation); + var thisInstantiated = annotated.flags & 262144 /* TypeParameter */ && annotated.isThisType ? instantiateType(annotated, signature.mapper) : annotated; + if (thisInstantiated === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } } } } @@ -48902,7 +50173,7 @@ var ts; return transformed === existing ? ts.setTextRange(ts.factory.cloneNode(existing), existing) : transformed; function visitExistingNodeTreeSymbols(node) { // We don't _actually_ support jsdoc namepath types, emit `any` instead - if (ts.isJSDocAllType(node) || node.kind === 310 /* JSDocNamepathType */) { + if (ts.isJSDocAllType(node) || node.kind === 311 /* JSDocNamepathType */) { return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */); } if (ts.isJSDocUnknownType(node)) { @@ -49021,8 +50292,8 @@ var ts; } } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { - var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 165 /* MethodDeclaration */, /*useAcessors*/ true); - var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 164 /* MethodSignature */, /*useAcessors*/ false); + var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 166 /* MethodDeclaration */, /*useAcessors*/ true); + var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 165 /* MethodSignature */, /*useAcessors*/ false); // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of // declaration mapping // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration @@ -49034,7 +50305,7 @@ var ts; var deferredPrivatesStack = []; var oldcontext = context; context = __assign(__assign({}, oldcontext), { usedSymbolNames: new ts.Set(oldcontext.usedSymbolNames), remappedSymbolNames: new ts.Map(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) { - var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false); + var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeAliases*/ false); if (accessibleResult.accessibility === 0 /* Accessible */) { // Lookup the root symbol of the chain of refs we'll use to access it and serialize it var chain = lookupSymbolChainWorker(sym, context, meaning); @@ -49243,6 +50514,7 @@ var ts; // If it's a class/interface/function: emit a class/interface/function with a `default` modifier // These forms can merge, eg (`export default 12; export default interface A {}`) function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) { + var _a, _b; var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName); var isDefault = symbol.escapedName === "default" /* Default */; if (isPrivate && !(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) { @@ -49301,9 +50573,9 @@ var ts; if (textRange && ts.isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) { textRange = textRange.parent.parent; } - var propertyAccessRequire = ts.find(symbol.declarations, ts.isPropertyAccessExpression); + var propertyAccessRequire = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isPropertyAccessExpression); if (propertyAccessRequire && ts.isBinaryExpression(propertyAccessRequire.parent) && ts.isIdentifier(propertyAccessRequire.parent.right) - && type.symbol && ts.isSourceFile(type.symbol.valueDeclaration)) { + && ((_b = type.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration) && ts.isSourceFile(type.symbol.valueDeclaration)) { var alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right; addResult(ts.factory.createExportDeclaration( /*decorators*/ undefined, @@ -49353,7 +50625,10 @@ var ts; serializeEnum(symbol, symbolName, modifierFlags); } if (symbol.flags & 32 /* Class */) { - if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { + if (symbol.flags & 4 /* Property */ + && symbol.valueDeclaration + && ts.isBinaryExpression(symbol.valueDeclaration.parent) + && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members, // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today. @@ -49379,12 +50654,14 @@ var ts; if (symbol.flags & 8388608 /* ExportStar */) { // synthesize export * from "moduleReference" // Straightforward - only one thing to do - make an export declaration - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - if (!resolvedModule) - continue; - addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */); + if (symbol.declarations) { + for (var _i = 0, _c = symbol.declarations; _i < _c.length; _i++) { + var node = _c[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + if (!resolvedModule) + continue; + addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */); + } } } if (needsPostExportDefault) { @@ -49422,15 +50699,16 @@ var ts; function addResult(node, additionalModifierFlags) { if (ts.canHaveModifiers(node)) { var newModifierFlags = 0 /* None */; + var enclosingDeclaration_1 = context.enclosingDeclaration && + (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 /* Export */ && - context.enclosingDeclaration && - (isExportingScope(context.enclosingDeclaration) || ts.isModuleDeclaration(context.enclosingDeclaration)) && + enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && canHaveExportModifier(node)) { // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private newModifierFlags |= 1 /* Export */; } if (addingDeclare && !(newModifierFlags & 1 /* Export */) && - (!context.enclosingDeclaration || !(context.enclosingDeclaration.flags & 8388608 /* Ambient */)) && + (!enclosingDeclaration_1 || !(enclosingDeclaration_1.flags & 8388608 /* Ambient */)) && (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) { // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope newModifierFlags |= 2 /* Ambient */; @@ -49445,19 +50723,23 @@ var ts; results.push(node); } function serializeTypeAlias(symbol, symbolName, modifierFlags) { + var _a; var aliasType = getDeclaredTypeOfTypeAlias(symbol); var typeParams = getSymbolLinks(symbol).typeParameters; var typeParamDecls = ts.map(typeParams, function (p) { return typeParameterToDeclaration(p, context); }); - var jsdocAliasDecl = ts.find(symbol.declarations, ts.isJSDocTypeAlias); - var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined; + var jsdocAliasDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isJSDocTypeAlias); + var commentText = ts.getTextOfJSDocComment(jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined); var oldFlags = context.flags; context.flags |= 8388608 /* InTypeAlias */; + var oldEnclosingDecl = context.enclosingDeclaration; + context.enclosingDeclaration = jsdocAliasDecl; var typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); addResult(ts.setSyntheticLeadingComments(ts.factory.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags); context.flags = oldFlags; + context.enclosingDeclaration = oldEnclosingDecl; } function serializeInterface(symbol, symbolName, modifierFlags) { var interfaceType = getDeclaredTypeOfClassOrInterface(symbol); @@ -49466,8 +50748,8 @@ var ts; var baseTypes = getBaseTypes(interfaceType); var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined; var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); }); - var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 169 /* CallSignature */); - var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 170 /* ConstructSignature */); + var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 170 /* CallSignature */); + var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 171 /* ConstructSignature */); var indexSignatures = serializeIndexSignatures(interfaceType, baseType); var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(93 /* ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551 /* Value */); }))]; addResult(ts.factory.createInterfaceDeclaration( @@ -49536,9 +50818,8 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; // Each overload becomes a separate function declaration, in order - var decl = signatureToSignatureDeclarationHelper(sig, 251 /* FunctionDeclaration */, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled }); - // for expressions assigned to `var`s, use the `var` as the text range - addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags); + var decl = signatureToSignatureDeclarationHelper(sig, 252 /* FunctionDeclaration */, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled }); + addResult(ts.setTextRange(decl, getSignatureTextRangeLocation(sig)), modifierFlags); } // Module symbol emit will take care of module-y members, provided it has exports if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) { @@ -49546,6 +50827,18 @@ var ts; serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true); } } + function getSignatureTextRangeLocation(signature) { + if (signature.declaration && signature.declaration.parent) { + if (ts.isBinaryExpression(signature.declaration.parent) && ts.getAssignmentDeclarationKind(signature.declaration.parent) === 5 /* Property */) { + return signature.declaration.parent; + } + // for expressions assigned to `var`s, use the `var` as the text range + if (ts.isVariableDeclaration(signature.declaration.parent) && signature.declaration.parent.parent) { + return signature.declaration.parent.parent; + } + } + return signature.declaration; + } function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) { if (ts.length(props)) { var localVsRemoteMap = ts.arrayToMultiMap(props, function (p) { @@ -49632,8 +50925,8 @@ var ts; return undefined; } function serializeAsClass(symbol, localName, modifierFlags) { - var _a; - var originalDecl = ts.find(symbol.declarations, ts.isClassLike); + var _a, _b; + var originalDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isClassLike); var oldEnclosing = context.enclosingDeclaration; context.enclosingDeclaration = originalDecl || oldEnclosing; var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -49644,7 +50937,7 @@ var ts; var implementsExpressions = originalImplements && sanitizeJSDocImplements(originalImplements) || ts.mapDefined(getImplementsTypes(classType), serializeImplementedType); var staticType = getTypeOfSymbol(symbol); - var isClass = !!((_a = staticType.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration) && ts.isClassLike(staticType.symbol.valueDeclaration); + var isClass = !!((_b = staticType.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration) && ts.isClassLike(staticType.symbol.valueDeclaration); var staticBaseType = isClass ? getBaseConstructorTypeOfClass(staticType) : anyType; @@ -49655,14 +50948,14 @@ var ts; // a union/intersection base type, but inherited properties // don't matter here. var valueDecl = s.valueDeclaration; - return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); + return !!valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); }); var hasPrivateIdentifier = ts.some(symbolProps, function (s) { // `valueDeclaration` could be undefined if inherited from // a union/intersection base type, but inherited properties // don't matter here. var valueDecl = s.valueDeclaration; - return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); + return !!valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); }); // Boil down all private properties into a single one. var privateProperties = hasPrivateIdentifier ? @@ -49685,7 +50978,7 @@ var ts; !ts.some(getSignaturesOfType(staticType, 1 /* Construct */)); var constructors = isNonConstructableClassLikeInJsFile ? [ts.factory.createConstructorDeclaration(/*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(8 /* Private */), [], /*body*/ undefined)] : - serializeSignatures(1 /* Construct */, staticType, staticBaseType, 166 /* Constructor */); + serializeSignatures(1 /* Construct */, staticType, staticBaseType, 167 /* Constructor */); var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); context.enclosingDeclaration = oldEnclosing; addResult(ts.setTextRange(ts.factory.createClassDeclaration( @@ -49712,8 +51005,8 @@ var ts; var targetName = getInternalSymbolName(target, verbatimTargetName); includePrivateSymbol(target); // the target may be within the same scope - attempt to serialize it first switch (node.kind) { - case 198 /* BindingElement */: - if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 249 /* VariableDeclaration */) { + case 199 /* BindingElement */: + if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 250 /* VariableDeclaration */) { // const { SomeClass } = require('./lib'); var specifier_1 = getSpecifierForModuleSymbol(target.parent || target, context); // './lib' var propertyName = node.propertyName; @@ -49725,13 +51018,13 @@ var ts; // We don't know how to serialize this (nested?) binding element ts.Debug.failBadSyntaxKind(((_c = node.parent) === null || _c === void 0 ? void 0 : _c.parent) || node, "Unhandled binding element grandparent kind in declaration serialization"); break; - case 289 /* ShorthandPropertyAssignment */: - if (((_e = (_d = node.parent) === null || _d === void 0 ? void 0 : _d.parent) === null || _e === void 0 ? void 0 : _e.kind) === 216 /* BinaryExpression */) { + case 290 /* ShorthandPropertyAssignment */: + if (((_e = (_d = node.parent) === null || _d === void 0 ? void 0 : _d.parent) === null || _e === void 0 ? void 0 : _e.kind) === 217 /* BinaryExpression */) { // module.exports = { SomeClass } serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), targetName); } break; - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: // commonjs require: const x = require('y') if (ts.isPropertyAccessExpression(node.initializer)) { // const x = require('y').z @@ -49751,7 +51044,7 @@ var ts; break; } // else fall through and treat commonjs require just like import= - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // This _specifically_ only exists to handle json declarations - where we make aliases, but since // we emit no declarations for the json document, must not refer to it in the declarations if (target.escapedName === "export=" /* ExportEquals */ && ts.some(target.declarations, ts.isJsonSourceFile)) { @@ -49768,13 +51061,13 @@ var ts; ? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false) : ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)))), isLocalImport ? modifierFlags : 0 /* None */); break; - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: // export as namespace foo // TODO: Not part of a file's local or export symbol tables // Is bound into file.symbol.globalExports instead, which we don't currently traverse addResult(ts.factory.createNamespaceExportDeclaration(ts.idText(node.name)), 0 /* None */); break; - case 262 /* ImportClause */: + case 263 /* ImportClause */: addResult(ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, ts.factory.createIdentifier(localName), /*namedBindings*/ undefined), @@ -49783,18 +51076,18 @@ var ts; // In such cases, the `target` refers to the module itself already ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: addResult(ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */); break; - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: addResult(ts.factory.createExportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */); break; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: addResult(ts.factory.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause( @@ -49803,7 +51096,7 @@ var ts; ts.factory.createImportSpecifier(localName !== verbatimTargetName ? ts.factory.createIdentifier(verbatimTargetName) : undefined, ts.factory.createIdentifier(localName)) ])), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: // does not use localName because the symbol name in this case refers to the name in the exports table, // which we must exactly preserve var specifier = node.parent.parent.moduleSpecifier; @@ -49811,12 +51104,12 @@ var ts; // another file serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.factory.createStringLiteral(specifier.text) : undefined); break; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: serializeMaybeAliasAssignment(symbol); break; - case 216 /* BinaryExpression */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 217 /* BinaryExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: // Could be best encoded as though an export specifier or as though an export assignment // If name is default or export=, do an export assignment // Otherwise do an export specifier @@ -49950,6 +51243,7 @@ var ts; } function makeSerializePropertySymbol(createProperty, methodKind, useAccessors) { return function serializePropertySymbol(p, isStatic, baseType) { + var _a, _b, _c, _d, _e; var modifierFlags = ts.getDeclarationModifierFlagsFromSymbol(p); var isPrivate = !!(modifierFlags & 8 /* Private */); if (isStatic && (p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */))) { @@ -49966,7 +51260,7 @@ var ts; } var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0); var name = getPropertyNameNodeForSymbol(p, context); - var firstPropertyLikeDecl = ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression)); + var firstPropertyLikeDecl = (_a = p.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression)); if (p.flags & 98304 /* Accessor */ && useAccessors) { var result = []; if (p.flags & 65536 /* SetAccessor */) { @@ -49976,13 +51270,13 @@ var ts; /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "arg", /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], - /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl)); + /*body*/ undefined), ((_b = p.declarations) === null || _b === void 0 ? void 0 : _b.find(ts.isSetAccessor)) || firstPropertyLikeDecl)); } if (p.flags & 32768 /* GetAccessor */) { var isPrivate_1 = modifierFlags & 8 /* Private */; result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration( /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), - /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl)); + /*body*/ undefined), ((_c = p.declarations) === null || _c === void 0 ? void 0 : _c.find(ts.isGetAccessor)) || firstPropertyLikeDecl)); } return result; } @@ -49993,7 +51287,7 @@ var ts; /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ - /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl); + /*initializer*/ undefined), ((_d = p.declarations) === null || _d === void 0 ? void 0 : _d.find(ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration))) || firstPropertyLikeDecl); } if (p.flags & (8192 /* Method */ | 16 /* Function */)) { var type = getTypeOfSymbol(p); @@ -50002,7 +51296,7 @@ var ts; return ts.setTextRange(createProperty( /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, /*type*/ undefined, - /*initializer*/ undefined), ts.find(p.declarations, ts.isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations[0]); + /*initializer*/ undefined), ((_e = p.declarations) === null || _e === void 0 ? void 0 : _e.find(ts.isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); } var results_1 = []; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { @@ -50013,7 +51307,8 @@ var ts; questionToken: p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, modifiers: flag ? ts.factory.createModifiersFromModifierFlags(flag) : undefined }); - results_1.push(ts.setTextRange(decl, sig.declaration)); + var location = sig.declaration && ts.isPrototypePropertyAssignment(sig.declaration.parent) ? sig.declaration.parent : sig.declaration; + results_1.push(ts.setTextRange(decl, location)); } return results_1; } @@ -50229,9 +51524,9 @@ var ts; return "public"; } function getTypeAliasForTypeLiteral(type) { - if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { + if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */ && type.symbol.declarations) { var node = ts.walkUpParenthesizedTypes(type.symbol.declarations[0].parent); - if (node.kind === 254 /* TypeAliasDeclaration */) { + if (node.kind === 255 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -50239,11 +51534,11 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 257 /* ModuleBlock */ && + node.parent.kind === 258 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } function isDefaultBindingContext(location) { - return location.kind === 297 /* SourceFile */ || ts.isAmbientModule(location); + return location.kind === 298 /* SourceFile */ || ts.isAmbientModule(location); } function getNameOfSymbolFromNameType(symbol, context) { var nameType = getSymbolLinks(symbol).nameType; @@ -50302,17 +51597,17 @@ var ts; if (!declaration) { declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway } - if (declaration.parent && declaration.parent.kind === 249 /* VariableDeclaration */) { + if (declaration.parent && declaration.parent.kind === 250 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } switch (declaration.kind) { - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { context.encounteredError = true; } - return declaration.kind === 221 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; + return declaration.kind === 222 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } var name = getNameOfSymbolFromNameType(symbol, context); @@ -50329,28 +51624,28 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 324 /* JSDocCallbackTag */: - case 331 /* JSDocTypedefTag */: - case 325 /* JSDocEnumTag */: + case 328 /* JSDocCallbackTag */: + case 335 /* JSDocTypedefTag */: + case 329 /* JSDocEnumTag */: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // falls through - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 251 /* FunctionDeclaration */: - case 255 /* EnumDeclaration */: - case 260 /* ImportEqualsDeclaration */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 252 /* FunctionDeclaration */: + case 256 /* EnumDeclaration */: + case 261 /* ImportEqualsDeclaration */: // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; @@ -50358,55 +51653,55 @@ var ts; var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 260 /* ImportEqualsDeclaration */ && parent.kind !== 297 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) { + !(node.kind !== 261 /* ImportEqualsDeclaration */ && parent.kind !== 298 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible return isDeclarationVisible(parent); - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasEffectiveModifier(node, 8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so: // falls through - case 166 /* Constructor */: - case 170 /* ConstructSignature */: - case 169 /* CallSignature */: - case 171 /* IndexSignature */: - case 160 /* Parameter */: - case 257 /* ModuleBlock */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 177 /* TypeLiteral */: - case 173 /* TypeReference */: - case 178 /* ArrayType */: - case 179 /* TupleType */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 186 /* ParenthesizedType */: - case 192 /* NamedTupleMember */: + case 167 /* Constructor */: + case 171 /* ConstructSignature */: + case 170 /* CallSignature */: + case 172 /* IndexSignature */: + case 161 /* Parameter */: + case 258 /* ModuleBlock */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 178 /* TypeLiteral */: + case 174 /* TypeReference */: + case 179 /* ArrayType */: + case 180 /* TupleType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 187 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: return isDeclarationVisible(node.parent); // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: + case 266 /* ImportSpecifier */: return false; // Type parameters are always visible - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: // Source file and namespace export are always visible // falls through - case 297 /* SourceFile */: - case 259 /* NamespaceExportDeclaration */: + case 298 /* SourceFile */: + case 260 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return false; default: return false; @@ -50415,10 +51710,10 @@ var ts; } function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 266 /* ExportAssignment */) { + if (node.parent && node.parent.kind === 267 /* ExportAssignment */) { exportSymbol = resolveName(node, node.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } - else if (node.parent.kind === 270 /* ExportSpecifier */) { + else if (node.parent.kind === 271 /* ExportSpecifier */) { exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; @@ -50523,12 +51818,12 @@ var ts; function getDeclarationContainer(node) { return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 249 /* VariableDeclaration */: - case 250 /* VariableDeclarationList */: - case 265 /* ImportSpecifier */: - case 264 /* NamedImports */: - case 263 /* NamespaceImport */: - case 262 /* ImportClause */: + case 250 /* VariableDeclaration */: + case 251 /* VariableDeclarationList */: + case 266 /* ImportSpecifier */: + case 265 /* NamedImports */: + case 264 /* NamespaceImport */: + case 263 /* ImportClause */: return false; default: return true; @@ -50591,9 +51886,16 @@ var ts; var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= 131072 /* ObjectRestType */; + result.objectFlags |= 8388608 /* ObjectRestType */; return result; } + function isGenericTypeWithUndefinedConstraint(type) { + return !!(type.flags & 465829888 /* Instantiable */) && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 32768 /* Undefined */); + } + function getNonUndefinedType(type) { + var typeOrConstraint = someType(type, isGenericTypeWithUndefinedConstraint) ? mapType(type, function (t) { return t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type; + return getTypeWithFacts(typeOrConstraint, 524288 /* NEUndefined */); + } // Determine the control flow type associated with a destructuring declaration or assignment. The following // forms of destructuring are possible: // let { x } = obj; // BindingElement @@ -50628,23 +51930,23 @@ var ts; function getParentElementAccess(node) { var ancestor = node.parent.parent; switch (ancestor.kind) { - case 198 /* BindingElement */: - case 288 /* PropertyAssignment */: + case 199 /* BindingElement */: + case 289 /* PropertyAssignment */: return getSyntheticElementAccess(ancestor); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return getSyntheticElementAccess(node.parent); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return ancestor.initializer; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return ancestor.right; } } function getDestructuringPropertyName(node) { var parent = node.parent; - if (node.kind === 198 /* BindingElement */ && parent.kind === 196 /* ObjectBindingPattern */) { + if (node.kind === 199 /* BindingElement */ && parent.kind === 197 /* ObjectBindingPattern */) { return getLiteralPropertyNameText(node.propertyName || node.name); } - if (node.kind === 288 /* PropertyAssignment */ || node.kind === 289 /* ShorthandPropertyAssignment */) { + if (node.kind === 289 /* PropertyAssignment */ || node.kind === 290 /* ShorthandPropertyAssignment */) { return getLiteralPropertyNameText(node.name); } return "" + parent.elements.indexOf(node); @@ -50670,7 +51972,7 @@ var ts; parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */); } var type; - if (pattern.kind === 196 /* ObjectBindingPattern */) { + if (pattern.kind === 197 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { parentType = getReducedType(parentType); if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { @@ -50690,7 +51992,7 @@ var ts; // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name = declaration.propertyName || declaration.name; var indexType = getLiteralTypeFromPropertyName(name); - var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */), declaration.name); + var declaredType = getIndexedAccessType(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */); type = getFlowTypeOfDestructuring(declaration, declaredType); } } @@ -50711,7 +52013,7 @@ var ts; else if (isArrayLikeType(parentType)) { var indexType = getLiteralType(index_2); var accessFlags = hasDefaultValue(declaration) ? 8 /* NoTupleBoundsCheck */ : 0; - var declaredType = getConstraintForLocation(getIndexedAccessTypeOrUndefined(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, declaration.name, accessFlags | 16 /* ExpressionPosition */) || errorType, declaration.name); + var declaredType = getIndexedAccessTypeOrUndefined(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, declaration.name, accessFlags | 16 /* ExpressionPosition */) || errorType; type = getFlowTypeOfDestructuring(declaration, declaredType); } else { @@ -50724,11 +52026,9 @@ var ts; if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ? - getTypeWithFacts(type, 524288 /* NEUndefined */) : - type; + return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ? getNonUndefinedType(type) : type; } - return widenTypeInferredFromInitializer(declaration, getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), checkDeclarationInitializer(declaration)], 2 /* Subtype */)); + return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration)], 2 /* Subtype */)); } function getTypeForDeclarationFromJSDocComment(declaration) { var jsdocType = ts.getJSDocType(declaration); @@ -50743,7 +52043,7 @@ var ts; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 199 /* ArrayLiteralExpression */ && expr.elements.length === 0; + return expr.kind === 200 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { if (optional === void 0) { optional = true; } @@ -50753,11 +52053,11 @@ var ts; function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 238 /* ForInStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForInStatement */) { var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 240 /* ForOfStatement */) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -50794,8 +52094,8 @@ var ts; if (ts.isParameter(declaration)) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 168 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { - var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 167 /* GetAccessor */); + if (func.kind === 169 /* SetAccessor */ && hasBindableName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 168 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -50866,7 +52166,7 @@ var ts; links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && ts.every(symbol.declarations, function (declaration) { return ts.isBinaryExpression(declaration) && isPossiblyAliasedThisProperty(declaration) && - (declaration.left.kind !== 202 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && + (declaration.left.kind !== 203 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ undefined, declaration, symbol, declaration); }); } @@ -50882,13 +52182,33 @@ var ts; !declaration.initializer && (noImplicitAny || ts.isInJSFile(declaration)); } function getDeclaringConstructor(symbol) { + if (!symbol.declarations) { + return; + } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var container = ts.getThisContainer(declaration, /*includeArrowFunctions*/ false); - if (container && (container.kind === 166 /* Constructor */ || isJSConstructor(container))) { + if (container && (container.kind === 167 /* Constructor */ || isJSConstructor(container))) { return container; } } + ; + } + /** Create a synthetic property access flow node after the last statement of the file */ + function getFlowTypeFromCommonJSExport(symbol) { + var file = ts.getSourceFileOfNode(symbol.declarations[0]); + var accessName = ts.unescapeLeadingUnderscores(symbol.escapedName); + var areAllModuleExports = symbol.declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && ts.isModuleExportsAccessExpression(d.expression); }); + var reference = areAllModuleExports + ? ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("module"), ts.factory.createIdentifier("exports")), accessName) + : ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("exports"), accessName); + if (areAllModuleExports) { + ts.setParent(reference.expression.expression, reference.expression); + } + ts.setParent(reference.expression, reference); + ts.setParent(reference, file); + reference.flowNode = file.endFlowNode; + return getFlowTypeOfReference(reference, autoType, undefinedType); } function getFlowTypeInConstructor(symbol, constructor) { var accessName = ts.startsWith(symbol.escapedName, "__#") @@ -50906,7 +52226,10 @@ var ts; return everyType(flowType, isNullableType) ? undefined : convertAutoToAny(flowType); } function getFlowTypeOfProperty(reference, prop) { - var initialType = prop && (!isAutoTypedProperty(prop) || ts.getEffectiveModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType; + var initialType = (prop === null || prop === void 0 ? void 0 : prop.valueDeclaration) + && (!isAutoTypedProperty(prop) || ts.getEffectiveModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) + && getTypeOfPropertyInBaseClass(prop) + || undefinedType; return getFlowTypeOfReference(reference, autoType, initialType); } function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) { @@ -50917,7 +52240,7 @@ var ts; if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + var containerObjectType = symbol.valueDeclaration && getJSContainerObjectType(symbol.valueDeclaration, symbol, container); return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var type; @@ -50929,40 +52252,42 @@ var ts; type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol)); } if (!type) { - var jsdocType = void 0; var types = void 0; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : - ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : - undefined; - if (!expression) { - continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere - } - var kind = ts.isAccessExpression(expression) - ? ts.getAssignmentDeclarationPropertyAccessKind(expression) - : ts.getAssignmentDeclarationKind(expression); - if (kind === 4 /* ThisProperty */ || ts.isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) { - if (isDeclarationInConstructor(expression)) { - definedInConstructor = true; + if (symbol.declarations) { + var jsdocType = void 0; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : + ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere + } + var kind = ts.isAccessExpression(expression) + ? ts.getAssignmentDeclarationPropertyAccessKind(expression) + : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */ || ts.isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } } - else { - definedInMethod = true; + if (!ts.isCallExpression(expression)) { + jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } - if (!ts.isCallExpression(expression)) { - jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); - } - if (!jsdocType) { - (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); - } + type = jsdocType; } - type = jsdocType; if (!type) { if (!ts.length(types)) { return errorType; // No types from any declarations :( } - var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; + var constructorTypes = definedInConstructor && symbol.declarations ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { var propType = getTypeOfPropertyInBaseClass(symbol); @@ -50976,7 +52301,7 @@ var ts; } } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); - if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { + if (symbol.valueDeclaration && filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } @@ -51000,10 +52325,11 @@ var ts; mergeSymbolTable(exports, s.exports); } var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - type.objectFlags |= 16384 /* JSLiteral */; + type.objectFlags |= 8192 /* JSLiteral */; return type; } function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) { + var _a; var typeNode = ts.getEffectiveTypeAnnotationNode(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -51014,7 +52340,7 @@ var ts; errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type); } } - if (symbol.parent) { + if ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) { var typeNode_2 = ts.getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration); if (typeNode_2) { return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode_2), symbol.escapedName); @@ -51078,7 +52404,7 @@ var ts; // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because // it's unclear what that's supposed to mean, so it's probably a mistake. - if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { + if (s.valueDeclaration && exportedMember.valueDeclaration && ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName); var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration; ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName)); @@ -51100,9 +52426,9 @@ var ts; }); var result = createAnonymousType(initialSize !== members_4.size ? undefined : exportedType.symbol, // Only set the type's symbol if it looks to be the same as the original type members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo); - result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag + result.objectFlags |= (ts.getObjectFlags(type) & 8192 /* JSLiteral */); // Propagate JSLiteral flag if (result.symbol && result.symbol.flags & 32 /* Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { - result.objectFlags |= 1073741824 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type + result.objectFlags |= 16777216 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type } return result; } @@ -51121,9 +52447,9 @@ var ts; var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. // Function expressions that are assigned to the prototype count as methods. - return thisContainer.kind === 166 /* Constructor */ || - thisContainer.kind === 251 /* FunctionDeclaration */ || - (thisContainer.kind === 208 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + return thisContainer.kind === 167 /* Constructor */ || + thisContainer.kind === 252 /* FunctionDeclaration */ || + (thisContainer.kind === 209 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); } function getConstructorDefinedThisAssignmentTypes(types, declarations) { ts.Debug.assert(types.length === declarations.length); @@ -51161,7 +52487,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -51185,7 +52511,7 @@ var ts; result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -51193,7 +52519,7 @@ var ts; function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - var restElement = lastElement && lastElement.kind === 198 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : undefined; + var restElement = lastElement && lastElement.kind === 199 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : undefined; if (elements.length === 0 || elements.length === 1 && restElement) { return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } @@ -51204,7 +52530,7 @@ var ts; if (includePatternInType) { result = cloneTypeReference(result); result.pattern = pattern; - result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= 262144 /* ContainsObjectOrArrayLiteral */; } return result; } @@ -51218,7 +52544,7 @@ var ts; function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { if (includePatternInType === void 0) { includePatternInType = false; } if (reportErrors === void 0) { reportErrors = false; } - return pattern.kind === 196 /* ObjectBindingPattern */ + return pattern.kind === 197 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -51234,8 +52560,17 @@ var ts; function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors); } + function isGlobalSymbolConstructor(node) { + var symbol = getSymbolOfNode(node); + var globalSymbol = getGlobalESSymbolConstructorTypeSymbol(/*reportErrors*/ false); + return globalSymbol && symbol && symbol === globalSymbol; + } function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) { if (type) { + // TODO: If back compat with pre-3.0/4.0 libs isn't required, remove the following SymbolConstructor special case transforming `symbol` into `unique symbol` + if (type.flags & 4096 /* ESSymbol */ && isGlobalSymbolConstructor(declaration.parent)) { + type = getESSymbolLikeTypeForNode(declaration); + } if (reportErrors) { reportErrorsFromWidening(declaration, type); } @@ -51257,7 +52592,7 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 160 /* Parameter */ ? root.parent : root; + var memberDeclaration = root.kind === 161 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function tryGetTypeFromEffectiveTypeNode(declaration) { @@ -51288,19 +52623,31 @@ var ts; if (symbol === requireSymbol) { return anyType; } - if (symbol.flags & 134217728 /* ModuleExports */) { + if (symbol.flags & 134217728 /* ModuleExports */ && symbol.valueDeclaration) { var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration)); + var result = createSymbol(fileSymbol.flags, "exports"); + result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : []; + result.parent = symbol; + result.target = fileSymbol; + if (fileSymbol.valueDeclaration) + result.valueDeclaration = fileSymbol.valueDeclaration; + if (fileSymbol.members) + result.members = new ts.Map(fileSymbol.members); + if (fileSymbol.exports) + result.exports = new ts.Map(fileSymbol.exports); var members = ts.createSymbolTable(); - members.set("exports", fileSymbol); + members.set("exports", result); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined); } // Handle catch clause variables + ts.Debug.assertIsDefined(symbol.valueDeclaration); var declaration = symbol.valueDeclaration; if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { - var decl = declaration; - if (!decl.type) + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode === undefined) { return anyType; - var type_1 = getTypeOfNode(decl.type); + } + var type_1 = getTypeOfNode(typeNode); // an errorType will make `checkTryStatement` issue an error return isTypeAny(type_1) || type_1 === unknownType ? type_1 : errorType; } @@ -51320,7 +52667,7 @@ var ts; return reportCircularityError(symbol); } var type; - if (declaration.kind === 266 /* ExportAssignment */) { + if (declaration.kind === 267 /* ExportAssignment */) { type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } else if (ts.isBinaryExpression(declaration) || @@ -51375,7 +52722,7 @@ var ts; type = getTypeOfEnumMember(symbol); } else if (ts.isAccessor(declaration)) { - type = resolveTypeOfAccessors(symbol); + type = resolveTypeOfAccessors(symbol) || ts.Debug.fail("Non-write accessor resolution must always produce a type"); } else { return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol)); @@ -51391,7 +52738,7 @@ var ts; } function getAnnotatedAccessorTypeNode(accessor) { if (accessor) { - if (accessor.kind === 167 /* GetAccessor */) { + if (accessor.kind === 168 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation; } @@ -51415,63 +52762,78 @@ var ts; } function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); - return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + return links.type || (links.type = getTypeOfAccessorsWorker(symbol) || ts.Debug.fail("Read type of accessor must always produce a type")); + } + function getTypeOfSetAccessor(symbol) { + var links = getSymbolLinks(symbol); + return links.writeType || (links.writeType = getTypeOfAccessorsWorker(symbol, /*writing*/ true)); } - function getTypeOfAccessorsWorker(symbol) { + function getTypeOfAccessorsWorker(symbol, writing) { + if (writing === void 0) { writing = false; } if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } - var type = resolveTypeOfAccessors(symbol); + var type = resolveTypeOfAccessors(symbol, writing); if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter = ts.getDeclarationOfKind(symbol, 167 /* GetAccessor */); + var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); error(getter, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } return type; } - function resolveTypeOfAccessors(symbol) { - var getter = ts.getDeclarationOfKind(symbol, 167 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 168 /* SetAccessor */); + function resolveTypeOfAccessors(symbol, writing) { + if (writing === void 0) { writing = false; } + var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); + var setterType = getAnnotatedAccessorType(setter); + // For write operations, prioritize type annotations on the setter + if (writing && setterType) { + return instantiateTypeIfNeeded(setterType, symbol); + } + // Else defer to the getter type if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { - return jsDocType; + return instantiateTypeIfNeeded(jsDocType, symbol); } } - // First try to see if the user specified a return type on the get-accessor. - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - return getterReturnType; + // Try to see if the user specified a return type on the get-accessor. + var getterType = getAnnotatedAccessorType(getter); + if (getterType) { + return instantiateTypeIfNeeded(getterType, symbol); } - else { - // If the user didn't specify a return type, try to use the set-accessor's parameter type. - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - return setterParameterType; + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + if (setterType) { + return setterType; + } + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + var returnTypeFromBody = getReturnTypeFromBody(getter); + return instantiateTypeIfNeeded(returnTypeFromBody, symbol); + } + // Otherwise, fall back to 'any'. + if (setter) { + if (!isPrivateWithinAmbient(setter)) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); } - else { - // If there are no specified types, try to infer it from the body of the get accessor if it exists. - if (getter && getter.body) { - return getReturnTypeFromBody(getter); - } - // Otherwise, fall back to 'any'. - else { - if (setter) { - if (!isPrivateWithinAmbient(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 exist a getter as we are current checking either setter or getter in this function"); - if (!isPrivateWithinAmbient(getter)) { - errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } - } - return anyType; - } + return anyType; + } + else if (getter) { + ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } + return anyType; + } + return undefined; + function instantiateTypeIfNeeded(type, symbol) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + var links = getSymbolLinks(symbol); + return instantiateType(type, links.mapper); } + return type; } } function getBaseTypeVariableOfClass(symbol) { @@ -51501,9 +52863,9 @@ var ts; if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration && (declaration.kind === 216 /* BinaryExpression */ || + else if (declaration && (declaration.kind === 217 /* BinaryExpression */ || ts.isAccessExpression(declaration) && - declaration.parent.kind === 216 /* BinaryExpression */)) { + declaration.parent.kind === 217 /* BinaryExpression */)) { return getWidenedTypeForAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { @@ -51537,14 +52899,16 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); + var exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(getDeclarationOfAliasSymbol(symbol), /*dontResolveAlias*/ true); // It only makes sense to get the type of a value symbol. If the result of resolving // the alias is not a value, then it has no type. To get the type associated with a // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 111551 /* Value */ - ? getTypeOfSymbol(targetSymbol) - : errorType; + links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) + : isDuplicatedCommonJSExport(symbol.declarations) ? autoType + : targetSymbol.flags & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) + : errorType; } return links.type; } @@ -51570,7 +52934,7 @@ var ts; return errorType; } // Check if variable has initializer that circularly references the variable itself - if (noImplicitAny && (declaration.kind !== 160 /* Parameter */ || declaration.initializer)) { + if (noImplicitAny && (declaration.kind !== 161 /* Parameter */ || declaration.initializer)) { error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); } // Circularities could also result from parameters in function expressions that end up @@ -51587,6 +52951,15 @@ var ts; } return links.type; } + function getSetAccessorTypeOfSymbol(symbol) { + if (symbol.flags & 98304 /* Accessor */) { + var type = getTypeOfSetAccessor(symbol); + if (type) { + return type; + } + } + return getTypeOfSymbol(symbol); + } function getTypeOfSymbol(symbol) { var checkFlags = ts.getCheckFlags(symbol); if (checkFlags & 65536 /* DeferredType */) { @@ -51669,66 +53042,72 @@ var ts; return undefined; } switch (node.kind) { - case 232 /* VariableStatement */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 253 /* InterfaceDeclaration */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 164 /* MethodSignature */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 308 /* JSDocFunctionType */: - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 254 /* TypeAliasDeclaration */: - case 330 /* JSDocTemplateTag */: - case 331 /* JSDocTypedefTag */: - case 325 /* JSDocEnumTag */: - case 324 /* JSDocCallbackTag */: - case 190 /* MappedType */: - case 184 /* ConditionalType */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 254 /* InterfaceDeclaration */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 165 /* MethodSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 309 /* JSDocFunctionType */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 255 /* TypeAliasDeclaration */: + case 334 /* JSDocTemplateTag */: + case 335 /* JSDocTypedefTag */: + case 329 /* JSDocEnumTag */: + case 328 /* JSDocCallbackTag */: + case 191 /* MappedType */: + case 185 /* ConditionalType */: { var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 190 /* MappedType */) { + if (node.kind === 191 /* MappedType */) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } - else if (node.kind === 184 /* ConditionalType */) { + else if (node.kind === 185 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } - else if (node.kind === 232 /* VariableStatement */ && !ts.isInJSFile(node)) { - break; - } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && - (node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */ || node.kind === 253 /* InterfaceDeclaration */ || isJSConstructor(node)) && + (node.kind === 253 /* ClassDeclaration */ || node.kind === 222 /* ClassExpression */ || node.kind === 254 /* InterfaceDeclaration */ || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; - case 326 /* JSDocParameterTag */: + } + case 330 /* JSDocParameterTag */: var paramSymbol = ts.getParameterSymbolFromJSDoc(node); if (paramSymbol) { node = paramSymbol.valueDeclaration; } break; + case 312 /* JSDocComment */: { + var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + return node.tags + ? appendTypeParameters(outerTypeParameters, ts.flatMap(node.tags, function (t) { return ts.isJSDocTemplateTag(t) ? t.typeParameters : undefined; })) + : outerTypeParameters; + } } } } // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 253 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 254 /* InterfaceDeclaration */); ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, // interface, or type alias. function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + if (!symbol.declarations) { + return; + } var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 253 /* InterfaceDeclaration */ || - node.kind === 252 /* ClassDeclaration */ || - node.kind === 221 /* ClassExpression */ || + if (node.kind === 254 /* InterfaceDeclaration */ || + node.kind === 253 /* ClassDeclaration */ || + node.kind === 222 /* ClassExpression */ || isJSConstructor(node) || ts.isTypeAlias(node)) { var declaration = node; @@ -51822,7 +53201,9 @@ var ts; ctorReturn = getReturnTypeOfSignature(ctorSig[0]); } } - ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + if (baseConstructorType.symbol.declarations) { + ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } } return type.resolvedBaseConstructorType = errorType; } @@ -51832,20 +53213,22 @@ var ts; } function getImplementsTypes(type) { var resolvedImplementsTypes = ts.emptyArray; - for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration); - if (!implementsTypeNodes) - continue; - for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) { - var node = implementsTypeNodes_1[_b]; - var implementsType = getTypeFromTypeNode(node); - if (implementsType !== errorType) { - if (resolvedImplementsTypes === ts.emptyArray) { - resolvedImplementsTypes = [implementsType]; - } - else { - resolvedImplementsTypes.push(implementsType); + if (type.symbol.declarations) { + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration); + if (!implementsTypeNodes) + continue; + for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) { + var node = implementsTypeNodes_1[_b]; + var implementsType = getTypeFromTypeNode(node); + if (implementsType !== errorType) { + if (resolvedImplementsTypes === ts.emptyArray) { + resolvedImplementsTypes = [implementsType]; + } + else { + resolvedImplementsTypes.push(implementsType); + } } } } @@ -51872,10 +53255,10 @@ var ts; else { ts.Debug.fail("type must be class or interface"); } - if (!popTypeResolution()) { + if (!popTypeResolution() && type.symbol.declarations) { for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 252 /* ClassDeclaration */ || declaration.kind === 253 /* InterfaceDeclaration */) { + if (declaration.kind === 253 /* ClassDeclaration */ || declaration.kind === 254 /* InterfaceDeclaration */) { reportCircularBaseType(declaration, type); } } @@ -51968,29 +53351,31 @@ var ts; } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; - for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 253 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { - for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { - var node = _c[_b]; - var baseType = getReducedType(getTypeFromTypeNode(node)); - if (baseType !== errorType) { - if (isValidBaseType(baseType)) { - if (type !== baseType && !hasBaseType(baseType, type)) { - if (type.resolvedBaseTypes === ts.emptyArray) { - type.resolvedBaseTypes = [baseType]; + if (type.symbol.declarations) { + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 254 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { + var node = _c[_b]; + var baseType = getReducedType(getTypeFromTypeNode(node)); + if (baseType !== errorType) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } } else { - type.resolvedBaseTypes.push(baseType); + reportCircularBaseType(declaration, type); } } else { - reportCircularBaseType(declaration, type); + error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } - else { - error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); - } } } } @@ -52004,9 +53389,12 @@ var ts; * and if none of the base interfaces have a "this" type. */ function isThislessInterface(symbol) { + if (!symbol.declarations) { + return true; + } for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 253 /* InterfaceDeclaration */) { + if (declaration.kind === 254 /* InterfaceDeclaration */) { if (declaration.flags & 128 /* ContainsThis */) { return false; } @@ -52031,7 +53419,7 @@ var ts; var originalLinks = links; if (!links.declaredType) { var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */; - var merged = mergeJSSymbols(symbol, getAssignedClassSymbol(symbol.valueDeclaration)); + var merged = mergeJSSymbols(symbol, symbol.valueDeclaration && getAssignedClassSymbol(symbol.valueDeclaration)); if (merged) { // note:we overwrite links because we just cloned the symbol symbol = links = merged; @@ -52061,6 +53449,7 @@ var ts; return links.declaredType; } function getDeclaredTypeOfTypeAlias(symbol) { + var _a; var links = getSymbolLinks(symbol); if (!links.declaredType) { // Note that we use the links object as the target here because the symbol object is used as the unique @@ -52068,7 +53457,7 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return errorType; } - var declaration = ts.Debug.checkDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found"); + var declaration = ts.Debug.checkDefined((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias), "Type alias symbol with no valid declaration found"); var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; @@ -52094,7 +53483,7 @@ var ts; if (ts.isStringLiteralLike(expr)) { return true; } - else if (expr.kind === 216 /* BinaryExpression */) { + else if (expr.kind === 217 /* BinaryExpression */) { return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); } return false; @@ -52109,12 +53498,12 @@ var ts; case 8 /* NumericLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: return true; - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return expr.operator === 40 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; case 78 /* Identifier */: return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return isStringConcatExpression(expr); default: return false; @@ -52126,16 +53515,18 @@ var ts; return links.enumKind; } var hasNonLiteralMember = false; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 255 /* EnumDeclaration */) { - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - if (member.initializer && ts.isStringLiteralLike(member.initializer)) { - return links.enumKind = 1 /* Literal */; - } - if (!isLiteralEnumMember(member)) { - hasNonLiteralMember = true; + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 256 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + if (member.initializer && ts.isStringLiteralLike(member.initializer)) { + return links.enumKind = 1 /* Literal */; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; + } } } } @@ -52153,15 +53544,17 @@ var ts; if (getEnumKind(symbol) === 1 /* Literal */) { enumCount++; var memberTypeList = []; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 255 /* EnumDeclaration */) { - for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { - var member = _c[_b]; - var value = getEnumMemberValue(member); - var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member))); - getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 256 /* EnumDeclaration */) { + for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { + var member = _c[_b]; + var value = getEnumMemberValue(member); + var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member))); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + } } } } @@ -52238,11 +53631,11 @@ var ts; case 113 /* VoidKeyword */: case 150 /* UndefinedKeyword */: case 141 /* NeverKeyword */: - case 191 /* LiteralType */: + case 192 /* LiteralType */: return true; - case 178 /* ArrayType */: + case 179 /* ArrayType */: return isThislessType(node.elementType); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; @@ -52268,7 +53661,7 @@ var ts; function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - return (node.kind === 166 /* Constructor */ || (!!returnType && isThislessType(returnType))) && + return (node.kind === 167 /* Constructor */ || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && typeParameters.every(isThislessTypeParameter); } @@ -52284,14 +53677,14 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return isThislessVariableLikeDeclaration(declaration); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return isThislessFunctionLikeDeclaration(declaration); } } @@ -52317,7 +53710,7 @@ var ts; } } function isStaticPrivateIdentifierProperty(s) { - return !!s.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(s.valueDeclaration) && ts.hasSyntacticModifier(s.valueDeclaration, 32 /* Static */); + return !!s.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(s.valueDeclaration) && ts.hasSyntacticModifier(s.valueDeclaration, 32 /* Static */); } function resolveDeclaredMembers(type) { if (!type.declaredProperties) { @@ -52369,10 +53762,10 @@ var ts; return !!name && isLateBindableName(name); } /** - * Indicates whether a declaration has a dynamic name that cannot be late-bound. + * Indicates whether a declaration has an early-bound name or a dynamic name that can be late-bound. */ - function hasNonBindableDynamicName(node) { - return ts.hasDynamicName(node) && !hasLateBindableName(node); + function hasBindableName(node) { + return !ts.hasDynamicName(node) || hasLateBindableName(node); } /** * Indicates whether a declaration name is a dynamic name that cannot be late-bound. @@ -52642,7 +54035,8 @@ var ts; sig.resolvedMinArgumentCount = undefined; sig.target = undefined; sig.mapper = undefined; - sig.unionSignatures = undefined; + sig.compositeSignatures = undefined; + sig.compositeKind = undefined; return sig; } function cloneSignature(sig) { @@ -52650,12 +54044,14 @@ var ts; /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 39 /* PropagatingFlags */); result.target = sig.target; result.mapper = sig.mapper; - result.unionSignatures = sig.unionSignatures; + result.compositeSignatures = sig.compositeSignatures; + result.compositeKind = sig.compositeKind; return result; } function createUnionSignature(signature, unionSignatures) { var result = cloneSignature(signature); - result.unionSignatures = unionSignatures; + result.compositeSignatures = unionSignatures; + result.compositeKind = 1048576 /* Union */; result.target = undefined; result.mapper = undefined; return result; @@ -52814,7 +54210,7 @@ var ts; if (signatures !== masterList) { var signature_1 = signatures[0]; ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); - results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters && !compareTypeParametersIdentical(signature_1.typeParameters, s.typeParameters); }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); }); + results = !!signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters && !compareTypeParametersIdentical(signature_1.typeParameters, s.typeParameters); }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); }); if (!results) { return "break"; } @@ -52831,9 +54227,12 @@ var ts; return result || ts.emptyArray; } function compareTypeParametersIdentical(sourceParams, targetParams) { - if (sourceParams.length !== targetParams.length) { + if (ts.length(sourceParams) !== ts.length(targetParams)) { return false; } + if (!sourceParams || !targetParams) { + return true; + } var mapper = createTypeMapper(targetParams, sourceParams); for (var i = 0; i < sourceParams.length; i++) { var source = sourceParams[i]; @@ -52915,9 +54314,10 @@ var ts; var result = createSignature(declaration, typeParams, thisParam, params, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 39 /* PropagatingFlags */); - result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); + result.compositeKind = 1048576 /* Union */; + result.compositeSignatures = ts.concatenate(left.compositeKind !== 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); if (paramMapper) { - result.mapper = left.mapper && left.unionSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; + result.mapper = left.compositeKind !== 2097152 /* Intersection */ && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; } return result; } @@ -53050,6 +54450,7 @@ var ts; // Combinations of function, class, enum and module var members = emptySymbols; var stringIndexInfo = void 0; + var numberIndexInfo = void 0; if (symbol.exports) { members = getExportsOfSymbol(symbol); if (symbol === globalThisSymbol) { @@ -53062,20 +54463,31 @@ var ts; members = varsOnly_1; } } + var baseConstructorIndexInfo = void 0; setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) { - members = ts.createSymbolTable(getNamedMembers(members)); + members = ts.createSymbolTable(getNamedOrIndexSignatureMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } else if (baseConstructorType === anyType) { - stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + baseConstructorIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + } + } + var indexSymbol = getIndexSymbolFromSymbolTable(members); + if (indexSymbol) { + stringIndexInfo = getIndexInfoOfIndexSymbol(indexSymbol, 0 /* String */); + numberIndexInfo = getIndexInfoOfIndexSymbol(indexSymbol, 1 /* Number */); + } + else { + stringIndexInfo = baseConstructorIndexInfo; + if (symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ || + ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); }))) { + numberIndexInfo = enumNumberIndexInfo; } } - var numberIndexInfo = symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ || - ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); })) ? enumNumberIndexInfo : undefined; setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); // We resolve the members before computing the signatures because a signature may use // typeof with a qualified name expression that circularly references the type we are @@ -53100,6 +54512,18 @@ var ts; } } } + function replaceIndexedAccess(instantiable, type, replacement) { + // map type.indexType to 0 + // map type.objectType to `[TReplacement]` + // thus making the indexed access `[TReplacement][0]` or `TReplacement` + return instantiateType(instantiable, createTypeMapper([type.indexType, type.objectType], [getLiteralType(0), createTupleType([replacement])])); + } + function getIndexInfoOfIndexSymbol(indexSymbol, indexKind) { + var declaration = getIndexDeclarationOfIndexSymbol(indexSymbol, indexKind); + if (!declaration) + return undefined; + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasEffectiveModifier(declaration, 64 /* Readonly */), declaration); + } function resolveReverseMappedTypeMembers(type) { var indexInfo = getIndexInfoOfType(type.source, 0 /* String */); var modifiers = getMappedTypeModifiers(type.mappedType); @@ -53114,8 +54538,21 @@ var ts; inferredProp.declarations = prop.declarations; inferredProp.nameType = getSymbolLinks(prop).nameType; inferredProp.propertyType = getTypeOfSymbol(prop); - inferredProp.mappedType = type.mappedType; - inferredProp.constraintType = type.constraintType; + if (type.constraintType.type.flags & 8388608 /* IndexedAccess */ + && type.constraintType.type.objectType.flags & 262144 /* TypeParameter */ + && type.constraintType.type.indexType.flags & 262144 /* TypeParameter */) { + // A reverse mapping of `{[K in keyof T[K_1]]: T[K_1]}` is the same as that of `{[K in keyof T]: T}`, since all we care about is + // inferring to the "type parameter" (or indexed access) shared by the constraint and template. So, to reduce the number of + // type identities produced, we simplify such indexed access occurences + var newTypeParam = type.constraintType.type.objectType; + var newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type, newTypeParam); + inferredProp.mappedType = newMappedType; + inferredProp.constraintType = getIndexType(newTypeParam); + } + else { + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + } members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); @@ -53277,7 +54714,7 @@ var ts; } function isMappedTypeWithKeyofConstraintDeclaration(type) { var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 - return constraintDeclaration.kind === 188 /* TypeOperator */ && + return constraintDeclaration.kind === 189 /* TypeOperator */ && constraintDeclaration.operator === 138 /* KeyOfKeyword */; } function getModifiersTypeFromMappedType(type) { @@ -53329,7 +54766,7 @@ var ts; else if (type.objectFlags & 3 /* ClassOrInterface */) { resolveClassOrInterfaceMembers(type); } - else if (type.objectFlags & 2048 /* ReverseMapped */) { + else if (type.objectFlags & 1024 /* ReverseMapped */) { resolveReverseMappedTypeMembers(type); } else if (type.objectFlags & 16 /* Anonymous */) { @@ -53613,12 +55050,22 @@ var ts; if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; + var different = false; for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { var type_3 = types_8[_i]; var baseType = getBaseConstraint(type_3); if (baseType) { + if (baseType !== type_3) { + different = true; + } baseTypes.push(baseType); } + else { + different = true; + } + } + if (!different) { + return t; } return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : @@ -53738,6 +55185,7 @@ var ts; return getReducedType(getApparentType(getReducedType(type))); } function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) { + var _a, _b; var singleProp; var propSet; var indexTypes; @@ -53746,8 +55194,9 @@ var ts; var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { - var current = _a[_i]; + var mergedInstantiations = false; + for (var _i = 0, _c = containingType.types; _i < _c.length; _i++) { + var current = _c[_i]; var type = getApparentType(current); if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); @@ -53763,13 +55212,25 @@ var ts; singleProp = prop; } else if (prop !== singleProp) { - if (!propSet) { - propSet = new ts.Map(); - propSet.set(getSymbolId(singleProp), singleProp); + var isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp); + // If the symbols are instances of one another with identical types - consider the symbols + // equivalent and just use the first one, which thus allows us to avoid eliding private + // members when intersecting a (this-)instantiations of a class with it's raw base or another instance + if (isInstantiation && compareProperties(singleProp, prop, function (a, b) { return a === b ? -1 /* True */ : 0 /* False */; }) === -1 /* True */) { + // If we merged instantiations of a generic type, we replicate the symbol parent resetting behavior we used + // to do when we recorded multiple distinct symbols so that we still get, eg, `Array.length` printed + // back and not `Array.length` when we're looking at a `.length` access on a `string[] | number[]` + mergedInstantiations = !!singleProp.parent && !!ts.length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent)); } - var id = getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + else { + if (!propSet) { + propSet = new ts.Map(); + propSet.set(getSymbolId(singleProp), singleProp); + } + var id = getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | @@ -53787,7 +55248,7 @@ var ts; checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0); indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } - else if (isObjectLiteralType(type)) { + else if (isObjectLiteralType(type) && !(ts.getObjectFlags(type) & 4194304 /* ContainsSpread */)) { checkFlags |= 32 /* WritePartial */; indexTypes = ts.append(indexTypes, undefinedType); } @@ -53803,7 +55264,19 @@ var ts; return undefined; } if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { - return singleProp; + if (mergedInstantiations) { + // No symbol from a union/intersection should have a `.parent` set (since unions/intersections don't act as symbol parents) + // Unless that parent is "reconstituted" from the "first value declaration" on the symbol (which is likely different than its instantiated parent!) + // They also have a `.containingType` set, which affects some services endpoints behavior, like `getRootSymbol` + var clone_1 = createSymbolWithType(singleProp, singleProp.type); + clone_1.parent = (_b = (_a = singleProp.valueDeclaration) === null || _a === void 0 ? void 0 : _a.symbol) === null || _b === void 0 ? void 0 : _b.parent; + clone_1.containingType = containingType; + clone_1.mapper = singleProp.mapper; + return clone_1; + } + else { + return singleProp; + } } var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; @@ -53812,8 +55285,8 @@ var ts; var propTypes = []; var firstValueDeclaration; var hasNonUniformValueDeclaration = false; - for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { - var prop = props_1[_b]; + for (var _d = 0, props_1 = props; _d < props_1.length; _d++) { + var prop = props_1[_d]; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } @@ -53890,15 +55363,15 @@ var ts; * no constituent property has type 'never', but the intersection of the constituent property types is 'never'. */ function getReducedType(type) { - if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) { + if (type.flags & 1048576 /* Union */ && type.objectFlags & 67108864 /* ContainsIntersections */) { return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); } else if (type.flags & 2097152 /* Intersection */) { - if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { - type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | - (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0); + if (!(type.objectFlags & 67108864 /* IsNeverIntersectionComputed */)) { + type.objectFlags |= 67108864 /* IsNeverIntersectionComputed */ | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 134217728 /* IsNeverIntersection */ : 0); } - return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; + return type.objectFlags & 134217728 /* IsNeverIntersection */ ? neverType : type; } return type; } @@ -53928,7 +55401,7 @@ var ts; return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */); } function elaborateNeverIntersection(errorInfo, type) { - if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) { + if (type.flags & 2097152 /* Intersection */ && ts.getObjectFlags(type) & 134217728 /* IsNeverIntersection */) { var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); if (neverProp) { return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(neverProp)); @@ -54015,7 +55488,8 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var prop = _a[_i]; if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { - propTypes.push(getTypeOfSymbol(prop)); + var propType = getTypeOfSymbol(prop); + propTypes.push(prop.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType); } } if (kind === 0 /* String */) { @@ -54049,10 +55523,10 @@ var ts; function isJSDocOptionalParameter(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 === 307 /* JSDocOptionalType */ + node.type && node.type.kind === 308 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 307 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 308 /* JSDocOptionalType */; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -54084,12 +55558,15 @@ var ts; } return false; } + function isOptionalPropertyDeclaration(node) { + return ts.isPropertyDeclaration(node) && node.questionToken; + } function isOptionalJSDocPropertyLikeTag(node) { if (!ts.isJSDocPropertyLikeTag(node)) { return false; } var isBracketed = node.isBracketed, typeExpression = node.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 307 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 308 /* JSDocOptionalType */; } function createTypePredicate(kind, parameterName, parameterIndex, type) { return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; @@ -54171,7 +55648,7 @@ var ts; else { parameters.push(paramSymbol); } - if (type && type.kind === 191 /* LiteralType */) { + if (type && type.kind === 192 /* LiteralType */) { flags |= 2 /* HasLiteralTypes */; } // Record a new minimum argument count if this is not an optional parameter @@ -54184,16 +55661,16 @@ var ts; } } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 167 /* GetAccessor */ || declaration.kind === 168 /* SetAccessor */) && - !hasNonBindableDynamicName(declaration) && + if ((declaration.kind === 168 /* GetAccessor */ || declaration.kind === 169 /* SetAccessor */) && + hasBindableName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; + var otherKind = declaration.kind === 168 /* GetAccessor */ ? 169 /* SetAccessor */ : 168 /* GetAccessor */; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 166 /* Constructor */ ? + var classType = declaration.kind === 167 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); @@ -54238,8 +55715,7 @@ var ts; if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node))) return undefined; var typeTag = ts.getJSDocTypeTag(node); - var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); - return signature && getErasedSignature(signature); + return (typeTag === null || typeTag === void 0 ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); } function getReturnTypeOfTypeTag(node) { var signature = getSignatureOfTypeTag(node); @@ -54262,14 +55738,14 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node.escapedText === argumentsSymbol.escapedName && getResolvedSymbol(node) === argumentsSymbol; - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - return node.name.kind === 158 /* ComputedPropertyName */ + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + return node.name.kind === 159 /* ComputedPropertyName */ && traverse(node.name); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return traverse(node.expression); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); @@ -54277,7 +55753,7 @@ var ts; } } function getSignaturesOfSymbol(symbol) { - if (!symbol) + if (!symbol || !symbol.declarations) return ts.emptyArray; var result = []; for (var i = 0; i < symbol.declarations.length; i++) { @@ -54318,8 +55794,8 @@ var ts; var targetTypePredicate = getTypePredicateOfSignature(signature.target); signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate; } - else if (signature.unionSignatures) { - signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + else if (signature.compositeSignatures) { + signature.resolvedTypePredicate = getUnionOrIntersectionTypePredicate(signature.compositeSignatures, signature.compositeKind) || noTypePredicate; } else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); @@ -54341,17 +55817,20 @@ var ts; function createTypePredicateFromTypePredicateNode(node, signature) { var parameterName = node.parameterName; var type = node.type && getTypeFromTypeNode(node.type); - return parameterName.kind === 187 /* ThisType */ ? + return parameterName.kind === 188 /* ThisType */ ? createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) : createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type); } + function getUnionOrIntersectionType(types, kind, unionReduction) { + return kind !== 2097152 /* Intersection */ ? getUnionType(types, unionReduction) : getIntersectionType(types); + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { return errorType; } var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : - signature.unionSignatures ? instantiateType(getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */), signature.mapper) : + signature.compositeSignatures ? instantiateType(getUnionOrIntersectionType(ts.map(signature.compositeSignatures, getReturnTypeOfSignature), signature.compositeKind, 2 /* Subtype */), signature.mapper) : getReturnTypeFromAnnotation(signature.declaration) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (signature.flags & 8 /* IsInnerCallChain */) { @@ -54384,7 +55863,7 @@ var ts; return signature.resolvedReturnType; } function getReturnTypeFromAnnotation(declaration) { - if (declaration.kind === 166 /* Constructor */) { + if (declaration.kind === 167 /* Constructor */) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); } if (ts.isJSDocConstructSignature(declaration)) { @@ -54394,12 +55873,12 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 167 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + if (declaration.kind === 168 /* GetAccessor */ && hasBindableName(declaration)) { var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 168 /* SetAccessor */); + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 169 /* SetAccessor */); var setterType = getAnnotatedAccessorType(setter); if (setterType) { return setterType; @@ -54476,9 +55955,20 @@ var ts; function getBaseSignature(signature) { var typeParameters = signature.typeParameters; if (typeParameters) { - var typeEraser_1 = createTypeEraser(typeParameters); - var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || unknownType; }); - return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); + if (signature.baseSignatureCache) { + return signature.baseSignatureCache; + } + var typeEraser = createTypeEraser(typeParameters); + var baseConstraintMapper_1 = createTypeMapper(typeParameters, ts.map(typeParameters, function (tp) { return getConstraintOfTypeParameter(tp) || unknownType; })); + var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(tp, baseConstraintMapper_1) || unknownType; }); + // Run N type params thru the immediate constraint mapper up to N times + // This way any noncircular interdependent type parameters are definitely resolved to their external dependencies + for (var i = 0; i < typeParameters.length - 1; i++) { + baseConstraints = instantiateTypes(baseConstraints, baseConstraintMapper_1); + } + // and then apply a type eraser to remove any remaining circularly dependent type parameters + baseConstraints = instantiateTypes(baseConstraints, typeEraser); + return signature.baseSignatureCache = instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); } return signature; } @@ -54489,7 +55979,7 @@ var ts; // will result in a different declaration kind. if (!signature.isolatedSignatureType) { var kind = signature.declaration ? signature.declaration.kind : 0 /* Unknown */; - var isConstructor = kind === 166 /* Constructor */ || kind === 170 /* ConstructSignature */ || kind === 175 /* ConstructorType */; + var isConstructor = kind === 167 /* Constructor */ || kind === 171 /* ConstructSignature */ || kind === 176 /* ConstructorType */; var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -54500,12 +55990,22 @@ var ts; return signature.isolatedSignatureType; } function getIndexSymbol(symbol) { - return symbol.members.get("__index" /* Index */); + return symbol.members ? getIndexSymbolFromSymbolTable(symbol.members) : undefined; + } + function getIndexSymbolFromSymbolTable(symbolTable) { + return symbolTable.get("__index" /* Index */); } function getIndexDeclarationOfSymbol(symbol, kind) { + var indexSymbol = symbol && getIndexSymbol(symbol); + return indexSymbol && getIndexDeclarationOfIndexSymbol(indexSymbol, kind); + } + function getIndexDeclarationOfSymbolTable(symbolTable, kind) { + var indexSymbol = symbolTable && getIndexSymbolFromSymbolTable(symbolTable); + return indexSymbol && getIndexDeclarationOfIndexSymbol(indexSymbol, kind); + } + function getIndexDeclarationOfIndexSymbol(indexSymbol, kind) { var syntaxKind = kind === 1 /* Number */ ? 144 /* NumberKeyword */ : 147 /* StringKeyword */; - var indexSymbol = getIndexSymbol(symbol); - if (indexSymbol) { + if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; var node = ts.cast(decl, ts.isIndexSignatureDeclaration); @@ -54533,17 +56033,18 @@ var ts; return ts.mapDefined(ts.filter(type.symbol && type.symbol.declarations, ts.isTypeParameterDeclaration), ts.getEffectiveConstraintOfTypeParameter)[0]; } function getInferredTypeParameterConstraint(typeParameter) { + var _a; var inferences; - if (typeParameter.symbol) { - for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.parent.kind === 185 /* InferType */) { + if ((_a = typeParameter.symbol) === null || _a === void 0 ? void 0 : _a.declarations) { + for (var _i = 0, _b = typeParameter.symbol.declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (declaration.parent.kind === 186 /* InferType */) { // When an 'infer T' declaration is immediately contained in a type reference node // (such as 'Foo'), T's constraint is inferred from the constraint of the // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are // present, we form an intersection of the inferred constraint types. - var _b = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _c = _b[0], childTypeParameter = _c === void 0 ? declaration.parent : _c, grandParent = _b[1]; - if (grandParent.kind === 173 /* TypeReference */) { + var _c = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _d = _c[0], childTypeParameter = _d === void 0 ? declaration.parent : _d, grandParent = _c[1]; + if (grandParent.kind === 174 /* TypeReference */) { var typeReference = grandParent; var typeParameters = getTypeParametersForTypeReference(typeReference); if (typeParameters) { @@ -54568,21 +56069,32 @@ var ts; } // When an 'infer T' declaration is immediately contained in a rest parameter declaration, a rest type // or a named rest tuple element, we infer an 'unknown[]' constraint. - else if (grandParent.kind === 160 /* Parameter */ && grandParent.dotDotDotToken || - grandParent.kind === 181 /* RestType */ || - grandParent.kind === 192 /* NamedTupleMember */ && grandParent.dotDotDotToken) { + else if (grandParent.kind === 161 /* Parameter */ && grandParent.dotDotDotToken || + grandParent.kind === 182 /* RestType */ || + grandParent.kind === 193 /* NamedTupleMember */ && grandParent.dotDotDotToken) { inferences = ts.append(inferences, createArrayType(unknownType)); } // When an 'infer T' declaration is immediately contained in a string template type, we infer a 'string' // constraint. - else if (grandParent.kind === 194 /* TemplateLiteralTypeSpan */) { + else if (grandParent.kind === 195 /* TemplateLiteralTypeSpan */) { inferences = ts.append(inferences, stringType); } // When an 'infer T' declaration is in the constraint position of a mapped type, we infer a 'keyof any' // constraint. - else if (grandParent.kind === 159 /* TypeParameter */ && grandParent.parent.kind === 190 /* MappedType */) { + else if (grandParent.kind === 160 /* TypeParameter */ && grandParent.parent.kind === 191 /* MappedType */) { inferences = ts.append(inferences, keyofConstraintType); } + // When an 'infer T' declaration is the template of a mapped type, and that mapped type is the extends + // clause of a conditional whose check type is also a mapped type, give it a constraint equal to the template + // of the check type's mapped type + else if (grandParent.kind === 191 /* MappedType */ && grandParent.type && + ts.skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === 185 /* ConditionalType */ && + grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === 191 /* MappedType */ && + grandParent.parent.checkType.type) { + var checkMappedType_1 = grandParent.parent.checkType; + var nodeType = getTypeFromTypeNode(checkMappedType_1.type); + inferences = ts.append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType_1.typeParameter)), checkMappedType_1.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType_1.typeParameter.constraint) : keyofConstraintType))); + } } } } @@ -54605,7 +56117,7 @@ var ts; if (type.flags & 1 /* Any */ && type !== errorType) { // Allow errorType to propegate to keep downstream errors suppressed // use keyofConstraintType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was), // use unknown otherwise - type = constraintDeclaration.parent.parent.kind === 190 /* MappedType */ ? keyofConstraintType : unknownType; + type = constraintDeclaration.parent.parent.kind === 191 /* MappedType */ ? keyofConstraintType : unknownType; } typeParameter.constraint = type; } @@ -54614,7 +56126,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - var tp = ts.getDeclarationOfKind(typeParameter.symbol, 159 /* TypeParameter */); + var tp = ts.getDeclarationOfKind(typeParameter.symbol, 160 /* TypeParameter */); var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent; return host && getSymbolOfNode(host); } @@ -54641,6 +56153,9 @@ var ts; } return result; } + function getAliasId(aliasSymbol, aliasTypeArguments) { + return aliasSymbol ? "@" + getSymbolId(aliasSymbol) + (aliasTypeArguments ? ":" + getTypeListId(aliasTypeArguments) : "") : ""; + } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type // of an object literal or the anyFunctionType. This is because there are operations in the type checker @@ -54653,7 +56168,7 @@ var ts; result |= ts.getObjectFlags(type); } } - return result & 3670016 /* PropagatingFlags */; + return result & 917504 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -54675,15 +56190,18 @@ var ts; type.resolvedTypeArguments = source.resolvedTypeArguments; return type; } - function createDeferredTypeReference(target, node, mapper) { - var aliasSymbol = getAliasSymbolForTypeNode(node); - var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + function createDeferredTypeReference(target, node, mapper, aliasSymbol, aliasTypeArguments) { + if (!aliasSymbol) { + aliasSymbol = getAliasSymbolForTypeNode(node); + var localAliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); + aliasTypeArguments = mapper ? instantiateTypes(localAliasTypeArguments, mapper) : localAliasTypeArguments; + } var type = createObjectType(4 /* Reference */, target.symbol); type.target = target; type.node = node; type.mapper = mapper; type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = mapper ? instantiateTypes(aliasTypeArguments, mapper) : aliasTypeArguments; + type.aliasTypeArguments = aliasTypeArguments; return type; } function getTypeArguments(type) { @@ -54694,8 +56212,8 @@ var ts; } var node = type.node; var typeArguments = !node ? ts.emptyArray : - node.kind === 173 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : - node.kind === 178 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : + node.kind === 174 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : + node.kind === 179 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); if (popTypeResolution()) { type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; @@ -54737,7 +56255,7 @@ var ts; return errorType; } } - if (node.kind === 173 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) { + if (node.kind === 174 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) { return createDeferredTypeReference(type, node, /*mapper*/ undefined); } // In a type reference, the outer type parameters of the referenced class or interface are automatically @@ -54748,17 +56266,17 @@ var ts; } return checkNoTypeArguments(node, symbol) ? type : errorType; } - function getTypeAliasInstantiation(symbol, typeArguments) { + function getTypeAliasInstantiation(symbol, typeArguments, aliasSymbol, aliasTypeArguments) { var type = getDeclaredTypeOfSymbol(symbol); if (type === intrinsicMarkerType && intrinsicTypeKinds.has(symbol.escapedName) && typeArguments && typeArguments.length === 1) { return getStringMappingType(symbol, typeArguments[0]); } var links = getSymbolLinks(symbol); var typeParameters = links.typeParameters; - var id = getTypeListId(typeArguments); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments)); } return instantiation; } @@ -54779,15 +56297,26 @@ var ts; ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); return errorType; } - return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node)); + // We refrain from associating a local type alias with an instantiation of a top-level type alias + // because the local alias may end up being referenced in an inferred return type where it is not + // accessible--which in turn may lead to a large structural expansion of the type when generating + // a .d.ts file. See #43622 for an example. + var aliasSymbol = getAliasSymbolForTypeNode(node); + var newAliasSymbol = aliasSymbol && (isLocalTypeAlias(symbol) || !isLocalTypeAlias(aliasSymbol)) ? aliasSymbol : undefined; + return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), newAliasSymbol, getTypeArgumentsForAliasSymbol(newAliasSymbol)); } return checkNoTypeArguments(node, symbol) ? type : errorType; } + function isLocalTypeAlias(symbol) { + var _a; + var declaration = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isTypeAlias); + return !!(declaration && ts.getContainingFunction(declaration)); + } function getTypeReferenceName(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return node.typeName; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. var expr = node.expression; @@ -54843,7 +56372,7 @@ var ts; var valueType = getTypeOfSymbol(symbol); var typeType = valueType; if (symbol.valueDeclaration) { - var isImportTypeWithQualifier = node.kind === 195 /* ImportType */ && node.qualifier; + var isImportTypeWithQualifier = node.kind === 196 /* ImportType */ && node.qualifier; // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL} if (valueType.symbol && valueType.symbol !== symbol && isImportTypeWithQualifier) { typeType = getTypeReferenceType(node, valueType.symbol); @@ -54869,7 +56398,7 @@ var ts; return result; } function isUnaryTupleTypeNode(node) { - return node.kind === 179 /* TupleType */ && node.elements.length === 1; + return node.kind === 180 /* TupleType */ && node.elements.length === 1; } function getImpliedConstraint(type, checkNode, extendsNode) { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elements[0], extendsNode.elements[0]) : @@ -54878,9 +56407,17 @@ var ts; } function getConditionalFlowTypeOfType(type, node) { var constraints; - while (node && !ts.isStatement(node) && node.kind !== 311 /* JSDocComment */) { + var covariant = true; + while (node && !ts.isStatement(node) && node.kind !== 312 /* JSDocComment */) { var parent = node.parent; - if (parent.kind === 184 /* ConditionalType */ && node === parent.trueType) { + // only consider variance flipped by parameter locations - `keyof` types would usually be considered variance inverting, but + // often get used in indexed accesses where they behave sortof invariantly, but our checking is lax + if (parent.kind === 161 /* Parameter */) { + covariant = !covariant; + } + // Always substitute on type parameters, regardless of variance, since even + // in contravariant positions, they may rely on substituted constraints to be valid + if ((covariant || type.flags & 8650752 /* TypeVariable */) && parent.kind === 185 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -54891,7 +56428,7 @@ var ts; return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type; } function isJSDocTypeReference(node) { - return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 173 /* TypeReference */ || node.kind === 195 /* ImportType */); + return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 174 /* TypeReference */ || node.kind === 196 /* ImportType */); } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { @@ -55001,13 +56538,15 @@ var ts; function getTypeOfGlobalSymbol(symbol, arity) { function getTypeDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { - var declaration = declarations_3[_i]; - switch (declaration.kind) { - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 255 /* EnumDeclaration */: - return declaration; + if (declarations) { + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; + switch (declaration.kind) { + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 256 /* EnumDeclaration */: + return declaration; + } } } } @@ -55051,6 +56590,9 @@ var ts; function getGlobalESSymbolConstructorSymbol(reportErrors) { return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); } + function getGlobalESSymbolConstructorTypeSymbol(reportErrors) { + return deferredGlobalESSymbolConstructorTypeSymbol || (deferredGlobalESSymbolConstructorTypeSymbol = getGlobalTypeSymbol("SymbolConstructor", reportErrors)); + } function getGlobalESSymbolType(reportErrors) { return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType; } @@ -55127,11 +56669,11 @@ var ts; } function getTupleElementFlags(node) { switch (node.kind) { - case 180 /* OptionalType */: + case 181 /* OptionalType */: return 2 /* Optional */; - case 181 /* RestType */: + case 182 /* RestType */: return getRestTypeElementFlags(node); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return node.questionToken ? 2 /* Optional */ : node.dotDotDotToken ? getRestTypeElementFlags(node) : 1 /* Required */; @@ -55149,14 +56691,14 @@ var ts; return readonly ? globalReadonlyArrayType : globalArrayType; } var elementFlags = ts.map(node.elements, getTupleElementFlags); - var missingName = ts.some(node.elements, function (e) { return e.kind !== 192 /* NamedTupleMember */; }); + var missingName = ts.some(node.elements, function (e) { return e.kind !== 193 /* NamedTupleMember */; }); return getTupleTargetType(elementFlags, readonly, /*associatedNames*/ missingName ? undefined : node.elements); } // Return true if the given type reference node is directly aliased or if it needs to be deferred // because it is possibly contained in a circular chain of eagerly resolved types. function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) { - return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 178 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) : - node.kind === 179 /* TupleType */ ? ts.some(node.elements, mayResolveTypeAlias) : + return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 179 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) : + node.kind === 180 /* TupleType */ ? ts.some(node.elements, mayResolveTypeAlias) : hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias)); } // Return true when the given node is transitively contained in type constructs that eagerly @@ -55165,18 +56707,18 @@ var ts; function isResolvedByTypeAlias(node) { var parent = node.parent; switch (parent.kind) { - case 186 /* ParenthesizedType */: - case 192 /* NamedTupleMember */: - case 173 /* TypeReference */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 189 /* IndexedAccessType */: - case 184 /* ConditionalType */: - case 188 /* TypeOperator */: - case 178 /* ArrayType */: - case 179 /* TupleType */: + case 187 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: + case 174 /* TypeReference */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 190 /* IndexedAccessType */: + case 185 /* ConditionalType */: + case 189 /* TypeOperator */: + case 179 /* ArrayType */: + case 180 /* TupleType */: return isResolvedByTypeAlias(parent); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return true; } return false; @@ -55185,28 +56727,28 @@ var ts; // of a type alias. function mayResolveTypeAlias(node) { switch (node.kind) { - case 173 /* TypeReference */: + case 174 /* TypeReference */: return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node.typeName, 788968 /* Type */).flags & 524288 /* TypeAlias */); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return true; - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return node.operator !== 151 /* UniqueKeyword */ && mayResolveTypeAlias(node.type); - case 186 /* ParenthesizedType */: - case 180 /* OptionalType */: - case 192 /* NamedTupleMember */: - case 307 /* JSDocOptionalType */: - case 305 /* JSDocNullableType */: - case 306 /* JSDocNonNullableType */: - case 301 /* JSDocTypeExpression */: + case 187 /* ParenthesizedType */: + case 181 /* OptionalType */: + case 193 /* NamedTupleMember */: + case 308 /* JSDocOptionalType */: + case 306 /* JSDocNullableType */: + case 307 /* JSDocNonNullableType */: + case 302 /* JSDocTypeExpression */: return mayResolveTypeAlias(node.type); - case 181 /* RestType */: - return node.type.kind !== 178 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType); - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 182 /* RestType */: + return node.type.kind !== 179 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType); + case 183 /* UnionType */: + case 184 /* IntersectionType */: return ts.some(node.types, mayResolveTypeAlias); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) || mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType); } @@ -55219,12 +56761,12 @@ var ts; if (target === emptyGenericType) { links.resolvedType = emptyObjectType; } - else if (!(node.kind === 179 /* TupleType */ && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8 /* Variadic */); })) && isDeferredTypeReferenceNode(node)) { - links.resolvedType = node.kind === 179 /* TupleType */ && node.elements.length === 0 ? target : + else if (!(node.kind === 180 /* TupleType */ && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8 /* Variadic */); })) && isDeferredTypeReferenceNode(node)) { + links.resolvedType = node.kind === 180 /* TupleType */ && node.elements.length === 0 ? target : createDeferredTypeReference(target, node, /*mapper*/ undefined); } else { - var elementTypes = node.kind === 178 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); + var elementTypes = node.kind === 179 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode); links.resolvedType = createNormalizedTypeReference(target, elementTypes); } } @@ -55356,8 +56898,15 @@ var ts; addElement(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]); } else if (isTupleType(type)) { + var elements = getTypeArguments(type); + if (elements.length + expandedTypes.length >= 10000) { + error(currentNode, ts.isPartOfTypeNode(currentNode) + ? ts.Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent + : ts.Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent); + return { value: errorType }; + } // Spread variadic elements with tuple types into the resulting tuple. - ts.forEach(getTypeArguments(type), function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); + ts.forEach(elements, function (t, n) { var _a; return addElement(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); }); } else { // Treat everything else as an array type and create a rest element. @@ -55370,7 +56919,9 @@ var ts; } }; for (var i = 0; i < elementTypes.length; i++) { - _loop_13(i); + var state_4 = _loop_13(i); + if (typeof state_4 === "object") + return state_4.value; } // Turn optional elements preceding the last required element into required elements for (var i = 0; i < lastRequiredIndex; i++) { @@ -55459,7 +57010,7 @@ var ts; if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { - if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) + if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */)) includes |= 4194304 /* IncludesNonWideningType */; } else { @@ -55481,67 +57032,76 @@ var ts; } return includes; } - function isSetOfLiteralsFromSameEnum(types) { - var first = types[0]; - if (first.flags & 1024 /* EnumLiteral */) { - var firstEnum = getParentOfSymbol(first.symbol); - for (var i = 1; i < types.length; i++) { - var other = types[i]; - if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { - return false; - } - } - return true; + function removeSubtypes(types, hasObjectTypes) { + var id = getTypeListId(types); + var match = subtypeReductionCache.get(id); + if (match) { + return match; } - return false; - } - function removeSubtypes(types, primitivesOnly) { + // We assume that redundant primitive types have already been removed from the types array and that there + // are no any and unknown types in the array. Thus, the only possible supertypes for primitive types are empty + // object types, and if none of those are present we can exclude primitive types from the subtype check. + var hasEmptyObject = hasObjectTypes && ts.some(types, function (t) { return !!(t.flags & 524288 /* Object */) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t)); }); var len = types.length; - if (len === 0 || isSetOfLiteralsFromSameEnum(types)) { - return true; - } var i = len; var count = 0; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var target = types_11[_i]; - if (source !== target) { - if (count === 100000) { - // After 100000 subtype checks we estimate the remaining amount of work by assuming the - // same ratio of checks per element. If the estimated number of remaining type checks is - // greater than an upper limit we deem the union type too complex to represent. The - // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example - // caps union types at 5000 unique literal types and 1000 unique object types. - var estimatedCount = (count / (len - i)) * len; - if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); - error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); - return false; + if (hasEmptyObject || source.flags & 469499904 /* StructuredOrInstantiable */) { + // Find the first property with a unit type, if any. When constituents have a property by the same name + // but of a different unit type, we can quickly disqualify them from subtype checks. This helps subtype + // reduction of large discriminated union types. + var keyProperty = source.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */) ? + ts.find(getPropertiesOfType(source), function (p) { return isUnitType(getTypeOfSymbol(p)); }) : + undefined; + var keyPropertyType = keyProperty && getRegularTypeOfLiteralType(getTypeOfSymbol(keyProperty)); + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var target = types_11[_i]; + if (source !== target) { + if (count === 100000) { + // After 100000 subtype checks we estimate the remaining amount of work by assuming the + // same ratio of checks per element. If the estimated number of remaining type checks is + // greater than 1M we deem the union type too complex to represent. This for example + // caps union types at 1000 unique object types. + var estimatedCount = (count / (len - i)) * len; + if (estimatedCount > 1000000) { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) }); + error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); + return undefined; + } + } + count++; + if (keyProperty && target.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */)) { + var t = getTypeOfPropertyOfType(target, keyProperty.escapedName); + if (t && isUnitType(t) && getRegularTypeOfLiteralType(t) !== keyPropertyType) { + continue; + } + } + if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { + ts.orderedRemoveItemAt(types, i); + break; } - } - count++; - if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || - !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || - isTypeDerivedFrom(source, target))) { - ts.orderedRemoveItemAt(types, i); - break; } } } } - return true; + subtypeReductionCache.set(id, types); + return types; } - function removeRedundantLiteralTypes(types, includes) { + function removeRedundantLiteralTypes(types, includes, reduceVoidUndefined) { var i = types.length; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 134217856 /* StringLikeLiteral */ && includes & 4 /* String */ || - t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || - t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || - t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + var flags = t.flags; + var remove = flags & 128 /* StringLiteral */ && includes & 4 /* String */ || + flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ || + flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ || + flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ || + reduceVoidUndefined && flags & 32768 /* Undefined */ && includes & 16384 /* Void */ || isFreshLiteralType(t) && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); @@ -55573,7 +57133,7 @@ var ts; if (t.flags & 1048576 /* Union */) { var origin = t.origin; if (t.aliasSymbol || origin && !(origin.flags & 1048576 /* Union */)) { - namedUnions.push(t); + ts.pushIfUnique(namedUnions, t); } else if (origin && origin.flags & 1048576 /* Union */) { addNamedUnions(namedUnions, origin.types); @@ -55607,20 +57167,17 @@ var ts; if (includes & 3 /* AnyOrUnknown */) { return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; } - switch (unionReduction) { - case 1 /* Literal */: - if (includes & (134220672 /* FreshableLiteral */ | 8192 /* UniqueESSymbol */)) { - removeRedundantLiteralTypes(typeSet, includes); - } - if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { - removeStringLiteralsMatchedByTemplateLiterals(typeSet); - } - break; - case 2 /* Subtype */: - if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) { - return errorType; - } - break; + if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */) || includes & 16384 /* Void */ && includes & 32768 /* Undefined */) { + removeRedundantLiteralTypes(typeSet, includes, !!(unionReduction & 2 /* Subtype */)); + } + if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) { + removeStringLiteralsMatchedByTemplateLiterals(typeSet); + } + if (unionReduction === 2 /* Subtype */) { + typeSet = removeSubtypes(typeSet, !!(includes & 524288 /* Object */)); + if (!typeSet) { + return errorType; + } } if (typeSet.length === 0) { return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType : @@ -55655,18 +57212,23 @@ var ts; origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes); } } - var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) | - (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0); + var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */) | + (includes & 2097152 /* Intersection */ ? 67108864 /* ContainsIntersections */ : 0); return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } - function getUnionTypePredicate(signatures) { + function getUnionOrIntersectionTypePredicate(signatures, kind) { var first; var types = []; for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { var sig = signatures_6[_i]; var pred = getTypePredicateOfSignature(sig); if (!pred || pred.kind === 2 /* AssertsThis */ || pred.kind === 3 /* AssertsIdentifier */) { - continue; + if (kind !== 2097152 /* Intersection */) { + continue; + } + else { + return; // intersections demand all members be type predicates for the result to have a predicate + } } if (first) { if (!typePredicateKindsMatch(first, pred)) { @@ -55680,11 +57242,11 @@ var ts; types.push(pred.type); } if (!first) { - // No union signatures had a type predicate. + // No signatures had a type predicate. return undefined; } - var unionType = getUnionType(types); - return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, unionType); + var compositeType = getUnionOrIntersectionType(types, kind); + return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, compositeType); } function typePredicateKindsMatch(a, b) { return a.kind === b.kind && a.parameterIndex === b.parameterIndex; @@ -55709,8 +57271,8 @@ var ts; var typeKey = !origin ? getTypeListId(types) : origin.flags & 1048576 /* Union */ ? "|" + getTypeListId(origin.types) : origin.flags & 2097152 /* Intersection */ ? "&" + getTypeListId(origin.types) : - "#" + origin.type.id; - var id = typeKey + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + "#" + origin.type.id + "|" + getTypeListId(types); // origin type id alone is insufficient, as `keyof x` may resolve to multiple WIP values while `x` is still resolving + var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { type = createUnionType(types, aliasSymbol, aliasTypeArguments, origin); @@ -55836,7 +57398,7 @@ var ts; // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); }); if (index < 0) { return false; } @@ -55845,7 +57407,7 @@ var ts; // the unionTypes array. while (i < types.length) { var t = types[i]; - if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) { + if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -55874,14 +57436,14 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */); + types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */); return true; } function createIntersectionType(types, aliasSymbol, aliasTypeArguments) { var result = createType(2097152 /* Intersection */); result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */); result.types = types; - result.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. + result.aliasSymbol = aliasSymbol; result.aliasTypeArguments = aliasTypeArguments; return result; } @@ -55942,7 +57504,7 @@ var ts; if (typeSet.length === 1) { return typeSet[0]; } - var id = getTypeListId(typeSet) + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = getTypeListId(typeSet) + getAliasId(aliasSymbol, aliasTypeArguments); var result = intersectionTypes.get(id); if (!result) { if (includes & 1048576 /* Union */) { @@ -55985,7 +57547,7 @@ var ts; function checkCrossProductUnion(types) { var size = getCrossProductUnionSize(types); if (size >= 100000) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size }); error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); return false; } @@ -56035,11 +57597,17 @@ var ts; type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } + function instantiateTypeAsMappedNameType(nameType, type, t) { + return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); + } function getIndexTypeForMappedType(type, noIndexSignatures) { var constraint = filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); }); var nameType = type.declaration.nameType && getTypeFromTypeNode(type.declaration.nameType); + // If the constraint is exclusively string/number/never type(s), we need to pull the property names from the modified type and run them through the `nameType` mapper as well + // since they won't appear in the constraint, due to subtype reducing with the string/number index types + var properties = nameType && everyType(constraint, function (t) { return !!(t.flags & (4 /* String */ | 8 /* Number */ | 131072 /* Never */)); }) && getPropertiesOfType(getApparentType(getModifiersTypeFromMappedType(type))); return nameType ? - mapType(constraint, function (t) { return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); }) : + getUnionType([mapType(constraint, function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); }), mapType(getUnionType(ts.map(properties || ts.emptyArray, function (p) { return getLiteralTypeFromProperty(p, 8576 /* StringOrNumberLiteralOrUnique */); })), function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); })]) : constraint; } // Ordinarily we reduce a keyof M, where M is a mapped type { [P in K as N

]: X }, to simply N. This however presumes @@ -56069,13 +57637,13 @@ var ts; function getLiteralTypeFromProperty(prop, include) { if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { var type = getSymbolLinks(getLateBoundSymbol(prop)).nameType; - if (!type && !ts.isKnownSymbol(prop)) { + if (!type) { if (prop.escapedName === "default" /* Default */) { type = getLiteralType("default"); } else { var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); - type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + type = name && getLiteralTypeFromPropertyName(name) || (!ts.isKnownSymbol(prop) ? getLiteralType(ts.symbolName(prop)) : undefined); } } if (type && type.flags & include) { @@ -56175,7 +57743,6 @@ var ts; var type = templateLiteralTypes.get(id); if (!type) { templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes)); - type.regularType = type; } return type; function addSpans(texts, types) { @@ -56207,10 +57774,8 @@ var ts; return type.flags & 128 /* StringLiteral */ ? type.value : type.flags & 256 /* NumberLiteral */ ? "" + type.value : type.flags & 2048 /* BigIntLiteral */ ? ts.pseudoBigIntToString(type.value) : - type.flags & 512 /* BooleanLiteral */ ? type.intrinsicName : - type.flags & 65536 /* Null */ ? "null" : - type.flags & 32768 /* Undefined */ ? "undefined" : - undefined; + type.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) ? type.intrinsicName : + undefined; } function createTemplateLiteralType(texts, types) { var type = createType(134217728 /* TemplateLiteral */); @@ -56269,7 +57834,7 @@ var ts; if (noImplicitAny) { return false; // Flag is meaningless under `noImplicitAny` mode } - if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) { + if (ts.getObjectFlags(type) & 8192 /* JSLiteral */) { return true; } if (type.flags & 1048576 /* Union */) { @@ -56279,20 +57844,18 @@ var ts; return ts.some(type.types, isJSLiteralType); } if (type.flags & 465829888 /* Instantiable */) { - return isJSLiteralType(getResolvedBaseConstraint(type)); + var constraint = getResolvedBaseConstraint(type); + return constraint !== type && isJSLiteralType(constraint); } return false; } function getPropertyNameFromIndex(indexType, accessNode) { - var accessExpression = accessNode && accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode : undefined; return isTypeUsableAsPropertyName(indexType) ? getPropertyNameFromType(indexType) : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : - accessNode && ts.isPropertyName(accessNode) ? - // late bound names are handled in the first branch, so here we only need to handle normal names - ts.getPropertyNameForPropertyNameNode(accessNode) : - undefined; + accessNode && ts.isPropertyName(accessNode) ? + // late bound names are handled in the first branch, so here we only need to handle normal names + ts.getPropertyNameForPropertyNameNode(accessNode) : + undefined; } function isUncalledFunctionReference(node, symbol) { if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { @@ -56306,17 +57869,17 @@ var ts; } function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, suppressNoImplicitAnyError, accessNode, accessFlags, noUncheckedIndexedAccessCandidate, reportDeprecated) { var _a; - var accessExpression = accessNode && accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode : undefined; + var accessExpression = accessNode && accessNode.kind === 203 /* ElementAccessExpression */ ? accessNode : undefined; var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode); if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { - if (reportDeprecated && accessNode && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) { + if (reportDeprecated && accessNode && prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) { var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); - errorOrSuggestion(/* isError */ false, deprecatedNode, ts.Diagnostics._0_is_deprecated, propName); + addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName); } if (accessExpression) { - markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 107 /* ThisKeyword */); + markPropertyAsReferenced(prop, accessExpression, isSelfTypeAccess(accessExpression.expression, objectType.symbol)); if (isAssignmentToReadonlyEntity(accessExpression, prop, ts.getAssignmentTargetKind(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); return undefined; @@ -56466,13 +58029,13 @@ var ts; } } function getIndexNodeForAccessExpression(accessNode) { - return accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode.argumentExpression : - accessNode.kind === 189 /* IndexedAccessType */ ? accessNode.indexType : - accessNode.kind === 158 /* ComputedPropertyName */ ? accessNode.expression : + return accessNode.kind === 203 /* ElementAccessExpression */ ? accessNode.argumentExpression : + accessNode.kind === 190 /* IndexedAccessType */ ? accessNode.indexType : + accessNode.kind === 159 /* ComputedPropertyName */ ? accessNode.expression : accessNode; } function isPatternLiteralPlaceholderType(type) { - return templateConstraintType.types.indexOf(type) !== -1 || !!(type.flags & 1 /* Any */); + return !!(type.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 64 /* BigInt */)); } function isPatternLiteralType(type) { return !!(type.flags & 134217728 /* TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType); @@ -56485,6 +58048,13 @@ var ts; } return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) { + type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ | + (isGenericObjectType(type.substitute) || isGenericObjectType(type.baseType) ? 8388608 /* IsGenericObjectType */ : 0); + } + return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); + } return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type) || isGenericTupleType(type); } function isGenericIndexType(type) { @@ -56495,6 +58065,13 @@ var ts; } return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); } + if (type.flags & 33554432 /* Substitution */) { + if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) { + type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ | + (isGenericIndexType(type.substitute) || isGenericIndexType(type.baseType) ? 33554432 /* IsGenericIndexType */ : 0); + } + return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); + } return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) && !isPatternLiteralType(type); } function isThisTypeParameter(type) { @@ -56570,6 +58147,12 @@ var ts; } return type[cache] = type; } + function isConditionalTypeAlwaysTrueDisregardingInferTypes(type) { + var extendsInferParamMapper = type.root.inferTypeParameters && createTypeMapper(type.root.inferTypeParameters, ts.map(type.root.inferTypeParameters, function () { return wildcardType; })); + var checkType = type.checkType; + var extendsType = type.extendsType; + return isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(instantiateType(extendsType, extendsInferParamMapper))); + } function getSimplifiedConditionalType(type, writing) { var checkType = type.checkType; var extendsType = type.extendsType; @@ -56640,14 +58223,14 @@ var ts; // for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved // eagerly using the constraint type of 'this' at the given location. - if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 189 /* IndexedAccessType */ ? + if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 190 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, objectType.target.fixedLength) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, objectType.target.fixedLength)))) { if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; } // Defer the operation by creating an indexed access type. - var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + (aliasSymbol ? "@" + getSymbolId(aliasSymbol) : ""); + var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + getAliasId(aliasSymbol, aliasTypeArguments); var type = indexedAccessTypes.get(id); if (!type) { indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined)); @@ -56723,16 +58306,32 @@ var ts; } return type; } - function getConditionalType(root, mapper) { + function isTypicalNondistributiveConditional(root) { + return !root.isDistributive + && root.node.checkType.kind === 180 /* TupleType */ + && ts.length(root.node.checkType.elements) === 1 + && root.node.extendsType.kind === 180 /* TupleType */ + && ts.length(root.node.extendsType.elements) === 1; + } + /** + * We syntactually check for common nondistributive conditional shapes and unwrap them into + * the intended comparison - we do this so we can check if the unwrapped types are generic or + * not and appropriately defer condition calculation + */ + function unwrapNondistributiveConditionalTuple(root, type) { + return isTypicalNondistributiveConditional(root) && isTupleType(type) ? getTypeArguments(type)[0] : type; + } + function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { var result; var extraTypes; // We loop here for an immediately nested conditional type in the false position, effectively treating // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { - var checkType = instantiateType(root.checkType, mapper); + var isUnwrapped = isTypicalNondistributiveConditional(root); + var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); - var extendsType = instantiateType(root.extendsType, mapper); + var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } @@ -56743,21 +58342,24 @@ var ts; // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. - inferTypes(context.inferences, checkType, extendsType, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(context.inferences, checkType, extendsType, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); } - combinedMapper = mergeTypeMappers(mapper, context.mapper); + // It's possible for 'infer T' type paramteters to be given uninstantiated constraints when the + // those type parameters are used in type references (see getInferredTypeParameterConstraint). For + // that reason we need context.mapper to be first in the combined mapper. See #42636 for examples. + combinedMapper = mapper ? combineTypeMappers(context.mapper, mapper) : context.mapper; } // Instantiate the extends type including inferences for 'infer T' type parameters - var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + var inferredExtendsType = combinedMapper ? instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), combinedMapper) : extendsType; // We attempt to resolve the conditional type only when the check and extends types are non-generic if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) { // Return falseType for a definitely false extends check. We check an instantiations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instantiations will be and we can just return the false branch type. - if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { + if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && ((checkType.flags & 1 /* Any */ && !isUnwrapped) || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { // Return union of trueType and falseType for 'any' since it matches anything - if (checkType.flags & 1 /* Any */) { + if (checkType.flags & 1 /* Any */ && !isUnwrapped) { (extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper)); } // If falseType is an immediately nested conditional type that isn't distributive or has an @@ -56786,12 +58388,12 @@ var ts; // Return a deferred type for a check that is neither definitely true nor definitely false result = createType(16777216 /* Conditional */); result.root = root; - result.checkType = checkType; - result.extendsType = extendsType; + result.checkType = instantiateType(root.checkType, mapper); + result.extendsType = instantiateType(root.extendsType, mapper); result.mapper = mapper; result.combinedMapper = combinedMapper; - result.aliasSymbol = root.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 + result.aliasSymbol = aliasSymbol || root.aliasSymbol; + result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 break; } return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result; @@ -56997,7 +58599,7 @@ var ts; } } var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return spread; } } @@ -57103,14 +58705,15 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */ | 4194304 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ function isSpreadableProperty(prop) { - return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) && + var _a; + return !ts.some(prop.declarations, ts.isPrivateIdentifierClassElementDeclaration) && (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || - !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); })); + !((_a = prop.declarations) === null || _a === void 0 ? void 0 : _a.some(function (decl) { return ts.isClassLike(decl.parent); }))); } function getSpreadSymbol(prop, readonly) { var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); @@ -57135,11 +58738,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 134220672 /* FreshableLiteral */) { + if (type.flags & 2944 /* Literal */) { if (!type.freshType) { - var freshType = type.flags & 134217728 /* TemplateLiteral */ ? - createTemplateLiteralType(type.texts, type.types) : - createLiteralType(type.flags, type.value, type.symbol); + var freshType = createLiteralType(type.flags, type.value, type.symbol); freshType.regularType = type; freshType.freshType = freshType; type.freshType = freshType; @@ -57149,12 +58750,12 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 134220672 /* FreshableLiteral */ ? type.regularType : + return type.flags & 2944 /* Literal */ ? type.regularType : type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = mapType(type, getRegularTypeOfLiteralType))) : type; } function isFreshLiteralType(type) { - return !!(type.flags & 134220672 /* FreshableLiteral */) && type.freshType === type; + return !!(type.flags & 2944 /* Literal */) && type.freshType === type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -57200,7 +58801,7 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 253 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 254 /* InterfaceDeclaration */)) { if (!ts.hasSyntacticModifier(container, 32 /* Static */) && (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; @@ -57235,17 +58836,17 @@ var ts; } function getArrayElementTypeNode(node) { switch (node.kind) { - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return getArrayElementTypeNode(node.type); - case 179 /* TupleType */: + case 180 /* TupleType */: if (node.elements.length === 1) { node = node.elements[0]; - if (node.kind === 181 /* RestType */ || node.kind === 192 /* NamedTupleMember */ && node.dotDotDotToken) { + if (node.kind === 182 /* RestType */ || node.kind === 193 /* NamedTupleMember */ && node.dotDotDotToken) { return getArrayElementTypeNode(node.type); } } break; - case 178 /* ArrayType */: + case 179 /* ArrayType */: return node.elementType; } return undefined; @@ -57263,8 +58864,8 @@ var ts; function getTypeFromTypeNodeWorker(node) { switch (node.kind) { case 128 /* AnyKeyword */: - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: return anyType; case 152 /* UnknownKeyword */: return unknownType; @@ -57291,70 +58892,70 @@ var ts; return node.flags & 131072 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType; case 136 /* IntrinsicKeyword */: return intrinsicMarkerType; - case 187 /* ThisType */: + case 188 /* ThisType */: case 107 /* ThisKeyword */: // TODO(rbuckton): `ThisKeyword` is no longer a `TypeNode`, but we defensively allow it here because of incorrect casts in the Language Service and because of `isPartOfTypeNode`. return getTypeFromThisTypeNode(node); - case 191 /* LiteralType */: + case 192 /* LiteralType */: return getTypeFromLiteralTypeNode(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return getTypeFromTypeReference(node); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return node.assertsModifier ? voidType : booleanType; - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 178 /* ArrayType */: - case 179 /* TupleType */: + case 179 /* ArrayType */: + case 180 /* TupleType */: return getTypeFromArrayOrTupleTypeNode(node); - case 180 /* OptionalType */: + case 181 /* OptionalType */: return getTypeFromOptionalTypeNode(node); - case 182 /* UnionType */: + case 183 /* UnionType */: return getTypeFromUnionTypeNode(node); - case 183 /* IntersectionType */: + case 184 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 305 /* JSDocNullableType */: + case 306 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 307 /* JSDocOptionalType */: + case 308 /* JSDocOptionalType */: return addOptionality(getTypeFromTypeNode(node.type)); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return getTypeFromNamedTupleTypeNode(node); - case 186 /* ParenthesizedType */: - case 306 /* JSDocNonNullableType */: - case 301 /* JSDocTypeExpression */: + case 187 /* ParenthesizedType */: + case 307 /* JSDocNonNullableType */: + case 302 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 181 /* RestType */: + case 182 /* RestType */: return getTypeFromRestTypeNode(node); - case 309 /* JSDocVariadicType */: + case 310 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 177 /* TypeLiteral */: - case 312 /* JSDocTypeLiteral */: - case 308 /* JSDocFunctionType */: - case 313 /* JSDocSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 178 /* TypeLiteral */: + case 314 /* JSDocTypeLiteral */: + case 309 /* JSDocFunctionType */: + case 315 /* JSDocSignature */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return getTypeFromIndexedAccessTypeNode(node); - case 190 /* MappedType */: + case 191 /* MappedType */: return getTypeFromMappedTypeNode(node); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return getTypeFromConditionalTypeNode(node); - case 185 /* InferType */: + case 186 /* InferType */: return getTypeFromInferTypeNode(node); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: return getTypeFromTemplateTypeNode(node); - case 195 /* ImportType */: + case 196 /* ImportType */: return getTypeFromImportTypeNode(node); // This function assumes that an identifier, qualified name, or property access expression is a type expression // Callers should first ensure this by calling `isPartOfTypeNode` // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s. case 78 /* Identifier */: - case 157 /* QualifiedName */: - case 201 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: var symbol = getSymbolAtLocation(node); return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; default: @@ -57507,7 +59108,7 @@ var ts; } return result; } - function getObjectTypeInstantiation(type, mapper) { + function getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { var declaration = type.objectFlags & 4 /* Reference */ ? type.node : type.symbol.declarations[0]; var links = getNodeLinks(declaration); var target = type.objectFlags & 4 /* Reference */ ? links.resolvedType : @@ -57524,8 +59125,9 @@ var ts; outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } typeParameters = outerTypeParameters || ts.emptyArray; - typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? - ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration); }) : + var allDeclarations_1 = type.objectFlags & 4 /* Reference */ ? [declaration] : type.symbol.declarations; + typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 8192 /* Method */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ? + ts.filter(typeParameters, function (tp) { return ts.some(allDeclarations_1, function (d) { return isTypeParameterPossiblyReferenced(tp, d); }); }) : typeParameters; links.outerTypeParameters = typeParameters; } @@ -57535,17 +59137,19 @@ var ts; // instantiation cache key from the type IDs of the type arguments. var combinedMapper_1 = combineTypeMappers(type.mapper, mapper); var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); }); - var id = getTypeListId(typeArguments); + var newAliasSymbol = aliasSymbol || type.aliasSymbol; + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + var id = getTypeListId(typeArguments) + getAliasId(newAliasSymbol, newAliasTypeArguments); if (!target.instantiations) { target.instantiations = new ts.Map(); - target.instantiations.set(getTypeListId(typeParameters), target); + target.instantiations.set(getTypeListId(typeParameters) + getAliasId(target.aliasSymbol, target.aliasTypeArguments), target); } var result = target.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(typeParameters, typeArguments); - result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper) : - target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) : - instantiateAnonymousType(target, newMapper); + result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) : + target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) : + instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments); target.instantiations.set(id, result); } return result; @@ -57553,9 +59157,9 @@ var ts; return type; } function maybeTypeParameterReference(node) { - return !(node.kind === 157 /* QualifiedName */ || - node.parent.kind === 173 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName || - node.parent.kind === 195 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier); + return !(node.kind === 158 /* QualifiedName */ || + node.parent.kind === 174 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName || + node.parent.kind === 196 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier); } function isTypeParameterPossiblyReferenced(tp, node) { // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks @@ -57564,22 +59168,25 @@ var ts; if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { var container = tp.symbol.declarations[0].parent; for (var n = node; n !== container; n = n.parent) { - if (!n || n.kind === 230 /* Block */ || n.kind === 184 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) { + if (!n || n.kind === 231 /* Block */ || n.kind === 185 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) { return true; } } - return !!ts.forEachChild(node, containsReference); + return containsReference(node); } return true; function containsReference(node) { switch (node.kind) { - case 187 /* ThisType */: + case 188 /* ThisType */: return !!tp.isThisType; case 78 /* Identifier */: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return true; + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + return (!node.type && !!node.body) || !!ts.forEachChild(node, containsReference); } return !!ts.forEachChild(node, containsReference); } @@ -57594,7 +59201,7 @@ var ts; } return undefined; } - function instantiateMappedType(type, mapper) { + function instantiateMappedType(type, mapper, aliasSymbol, aliasTypeArguments) { // 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. @@ -57609,7 +59216,7 @@ var ts; if (typeVariable) { var mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapType(getReducedType(mappedTypeVariable), function (t) { + return mapTypeWithAlias(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) { if (!type.declaration.nameType) { if (isArrayType(t)) { @@ -57625,11 +59232,11 @@ var ts; return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper)); } return t; - }); + }, aliasSymbol, aliasTypeArguments); } } // If the constraint type of the instantiation is the wildcard type, return the wildcard type. - return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper); + return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments); } function getModifiedReadonlyState(state, modifiers) { return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state; @@ -57676,7 +59283,7 @@ var ts; strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; } - function instantiateAnonymousType(type, mapper) { + function instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; @@ -57689,29 +59296,29 @@ var ts; } result.target = type; result.mapper = mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + result.aliasSymbol = aliasSymbol || type.aliasSymbol; + result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); return result; } - function getConditionalTypeInstantiation(type, mapper) { + function getConditionalTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) { var root = type.root; if (root.outerTypeParameters) { // We are instantiating a conditional type that has one or more type parameters in scope. Apply the // mapper to the type parameters to produce the effective list of type arguments, and compute the // instantiation cache key from the type IDs of the type arguments. var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); }); - var id = getTypeListId(typeArguments); + var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); var result = root.instantiations.get(id); if (!result) { var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments); - result = instantiateConditionalType(root, newMapper); + result = instantiateConditionalType(root, newMapper, aliasSymbol, aliasTypeArguments); root.instantiations.set(id, result); } return result; } return type; } - function instantiateConditionalType(root, mapper) { + function instantiateConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { // Check if we have a conditional type where the check type is a naked type parameter. If so, // the conditional type is distributive over union types and when T is instantiated to a union // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y). @@ -57719,31 +59326,34 @@ var ts; var checkType_1 = root.checkType; var instantiatedType = getMappedType(checkType_1, mapper); if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) { - return mapType(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); }); + return mapTypeWithAlias(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); }, aliasSymbol, aliasTypeArguments); } } - return getConditionalType(root, mapper); + return getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments); } function instantiateType(type, mapper) { - if (!(type && mapper && couldContainTypeVariables(type))) { + return type && mapper ? instantiateTypeWithAlias(type, mapper, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined) : type; + } + function instantiateTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) { + if (!couldContainTypeVariables(type)) { return type; } if (instantiationDepth === 50 || instantiationCount >= 5000000) { // 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. - ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount }); error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); return errorType; } totalInstantiationCount++; instantiationCount++; instantiationDepth++; - var result = instantiateTypeWorker(type, mapper); + var result = instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments); instantiationDepth--; return result; } - function instantiateTypeWorker(type, mapper) { + function instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments) { var flags = type.flags; if (flags & 262144 /* TypeParameter */) { return getMappedType(type, mapper); @@ -57751,12 +59361,15 @@ var ts; if (flags & 524288 /* Object */) { var objectFlags = type.objectFlags; if (objectFlags & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */)) { - if (objectFlags & 4 /* Reference */ && !(type.node)) { + if (objectFlags & 4 /* Reference */ && !type.node) { var resolvedTypeArguments = type.resolvedTypeArguments; var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type; } - return getObjectTypeInstantiation(type, mapper); + if (objectFlags & 1024 /* ReverseMapped */) { + return instantiateReverseMappedType(type, mapper); + } + return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments); } return type; } @@ -57764,10 +59377,14 @@ var ts; var origin = type.flags & 1048576 /* Union */ ? type.origin : undefined; var types = origin && origin.flags & 3145728 /* UnionOrIntersection */ ? origin.types : type.types; var newTypes = instantiateTypes(types, mapper); - return newTypes === types ? type : - flags & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ? - getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : - getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + if (newTypes === types && aliasSymbol === type.aliasSymbol) { + return type; + } + var newAliasSymbol = aliasSymbol || type.aliasSymbol; + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + return flags & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ? + getIntersectionType(newTypes, newAliasSymbol, newAliasTypeArguments) : + getUnionType(newTypes, 1 /* Literal */, newAliasSymbol, newAliasTypeArguments); } if (flags & 4194304 /* Index */) { return getIndexType(instantiateType(type.type, mapper)); @@ -57779,10 +59396,12 @@ var ts; return getStringMappingType(type.symbol, instantiateType(type.type, mapper)); } if (flags & 8388608 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + var newAliasSymbol = aliasSymbol || type.aliasSymbol; + var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, newAliasSymbol, newAliasTypeArguments); } if (flags & 16777216 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper), aliasSymbol, aliasTypeArguments); } if (flags & 33554432 /* Substitution */) { var maybeVariable = instantiateType(type.baseType, mapper); @@ -57799,6 +59418,21 @@ var ts; } return type; } + function instantiateReverseMappedType(type, mapper) { + var innerMappedType = instantiateType(type.mappedType, mapper); + if (!(ts.getObjectFlags(innerMappedType) & 32 /* Mapped */)) { + return type; + } + var innerIndexType = instantiateType(type.constraintType, mapper); + if (!(innerIndexType.flags & 4194304 /* Index */)) { + return type; + } + var instantiated = inferTypeForHomomorphicMappedType(instantiateType(type.source, mapper), innerMappedType, innerIndexType); + if (instantiated) { + return instantiated; + } + return type; // Nested invocation of `inferTypeForHomomorphicMappedType` or the `source` instantiated into something unmappable + } function getPermissiveInstantiation(type) { return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); @@ -57825,35 +59459,35 @@ var 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) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 251 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type return isContextSensitiveFunctionLikeDeclaration(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return ts.some(node.properties, isContextSensitive); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return ts.some(node.elements, isContextSensitive); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return (node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */) && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isContextSensitive(node.expression); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive); - case 280 /* JsxAttribute */: { + case 281 /* JsxAttribute */: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. var initializer = node.initializer; return !!initializer && isContextSensitive(initializer); } - case 283 /* JsxExpression */: { + case 284 /* JsxExpression */: { // It is possible to that node.expression is undefined (e.g

) var expression = node.expression; return !!expression && isContextSensitive(expression); @@ -57872,7 +59506,7 @@ var ts; if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 209 /* ArrowFunction */) { + if (node.kind !== 210 /* ArrowFunction */) { // If the first parameter is not an explicit 'this' parameter, then the function has // an implicit 'this' parameter which is subject to contextual typing. var parameter = ts.firstOrUndefined(node.parameters); @@ -57885,7 +59519,7 @@ var ts; } function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 230 /* Block */ && isContextSensitive(node.body); + return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 231 /* Block */ && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -57988,23 +59622,23 @@ var ts; return true; } switch (node.kind) { - case 283 /* JsxExpression */: - case 207 /* ParenthesizedExpression */: + case 284 /* JsxExpression */: + case 208 /* ParenthesizedExpression */: return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (node.operatorToken.kind) { case 62 /* EqualsToken */: case 27 /* CommaToken */: return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); } break; - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer); } return false; @@ -58204,7 +59838,7 @@ var ts; } function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) { switch (child.kind) { - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: // child is of the type of the expression return { errorNode: child, innerExpression: child.expression, nameType: nameType }; case 11 /* JsxText */: @@ -58213,9 +59847,9 @@ var ts; } // child is a string return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() }; - case 273 /* JsxElement */: - case 274 /* JsxSelfClosingElement */: - case 277 /* JsxFragment */: + case 274 /* JsxElement */: + case 275 /* JsxSelfClosingElement */: + case 278 /* JsxFragment */: // child is of type JSX.Element return { errorNode: child, innerExpression: child, nameType: nameType }; default: @@ -58363,11 +59997,11 @@ var ts; } _b = prop.kind; switch (_b) { - case 168 /* SetAccessor */: return [3 /*break*/, 2]; - case 167 /* GetAccessor */: return [3 /*break*/, 2]; - case 165 /* MethodDeclaration */: return [3 /*break*/, 2]; - case 289 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; - case 288 /* PropertyAssignment */: return [3 /*break*/, 4]; + case 169 /* SetAccessor */: return [3 /*break*/, 2]; + case 168 /* GetAccessor */: return [3 /*break*/, 2]; + case 166 /* MethodDeclaration */: return [3 /*break*/, 2]; + case 290 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 289 /* PropertyAssignment */: return [3 /*break*/, 4]; } return [3 /*break*/, 6]; case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; @@ -58444,8 +60078,8 @@ var ts; return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; - var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 165 /* MethodDeclaration */ && - kind !== 164 /* MethodSignature */ && kind !== 166 /* Constructor */; + var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 166 /* MethodDeclaration */ && + kind !== 165 /* MethodSignature */ && kind !== 167 /* Constructor */; var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { @@ -58678,7 +60312,7 @@ var ts; // Type number or any numeric literal type is assignable to any numeric enum type or any // numeric enum literal type. This rule exists for backwards compatibility reasons because // bit-flag enum types sometimes look like literal enum types with numeric literal values. - if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) + if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || relation === assignableRelation && t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) return true; } return false; @@ -58715,7 +60349,7 @@ var ts; return false; } function isIgnoredJsxProperty(source, sourceProp) { - return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); + return ts.getObjectFlags(source) & 2048 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { while (true) { @@ -58725,6 +60359,7 @@ var ts; type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute : type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : type; + t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) break; type = t; @@ -58762,7 +60397,7 @@ var ts; reportIncompatibleStack(); } if (overflow) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth }); var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); @@ -58898,6 +60533,14 @@ var ts; } break; } + case ts.Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target.code: { + secondaryRootErrors.unshift([ts.Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target, args[0], args[1]]); + break; + } + case ts.Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target.code: { + secondaryRootErrors.unshift([ts.Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target, args[0], args[1], args[2]]); + break; + } default: return ts.Debug.fail("Unhandled Diagnostic: " + msg.code); } @@ -58958,6 +60601,7 @@ var ts; reportError(ts.Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2, needsOriginalSource ? sourceType : generalizedSourceType, targetType, typeToString(constraint)); } else { + errorInfo = undefined; reportError(ts.Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, generalizedSourceType); } } @@ -59033,7 +60677,7 @@ var ts; if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { return -1 /* True */; } - reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */)); + reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 2048 /* JsxAttributes */)); return 0 /* False */; } // Normalize the source and target types: Turn fresh literal types into regular literal types, @@ -59068,16 +60712,16 @@ var ts; target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) { var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */); if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) { - if (source === nullStrippedTarget) - return -1 /* True */; - target = nullStrippedTarget; + target = getNormalizedType(nullStrippedTarget, /*writing*/ true); } + if (source === nullStrippedTarget) + return -1 /* True */; } if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); + var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384 /* FreshLiteral */); if (isPerformingExcessPropertyChecks) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -59162,7 +60806,7 @@ var ts; // We suppress recursive intersection property checks because they can generate lots of work when relating // recursive intersections that are structurally similar but not exactly identical. See #37854. if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) { + isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 524288 /* NonInferrableType */); }))) { inPropertyCheck = true; result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */); inPropertyCheck = false; @@ -59171,8 +60815,10 @@ var ts; return result; function reportErrorResults(source, target, result, isComparingJsxAttributes) { if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; + var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); + var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); + source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; + target = (originalTarget.aliasSymbol || targetHasBase) ? originalTarget : target; var maybeSuppress = overrideNextErrorInfo > 0; if (maybeSuppress) { overrideNextErrorInfo--; @@ -59213,13 +60859,13 @@ var ts; } } function traceUnionsOrIntersectionsTooLarge(source, target) { - if (!ts.tracing.isTracing()) { + if (!ts.tracing) { return; } if ((source.flags & 3145728 /* UnionOrIntersection */) && (target.flags & 3145728 /* UnionOrIntersection */)) { var sourceUnionOrIntersection = source; var targetUnionOrIntersection = target; - if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 262144 /* PrimitiveUnion */) { + if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 65536 /* PrimitiveUnion */) { // There's a fast path for comparing primitive unions return; } @@ -59244,11 +60890,11 @@ var ts; } traceUnionsOrIntersectionsTooLarge(source, target); if (flags & 3145728 /* UnionOrIntersection */) { - var result_6 = eachTypeRelatedToSomeType(source, target); - if (result_6) { - result_6 &= eachTypeRelatedToSomeType(target, source); + var result_7 = eachTypeRelatedToSomeType(source, target); + if (result_7) { + result_7 &= eachTypeRelatedToSomeType(target, source); } - return result_6; + return result_7; } return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */); } @@ -59262,10 +60908,11 @@ var ts; return getUnionType(ts.reduceLeft(types, appendPropType, /*initial*/ undefined) || ts.emptyArray); } function hasExcessProperties(source, target, reportErrors) { - if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { + var _a; + if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 8192 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; @@ -59308,7 +60955,7 @@ var ts; } else { // use the property's value declaration if the property is assigned inside the literal itself - var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + var objectLiteralDeclaration_1 = ((_a = source.symbol) === null || _a === void 0 ? void 0 : _a.declarations) && ts.firstOrUndefined(source.symbol.declarations); var suggestion = void 0; if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) { var propDeclaration = prop.valueDeclaration; @@ -59337,11 +60984,11 @@ var ts; } } }; - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - var state_4 = _loop_16(prop); - if (typeof state_4 === "object") - return state_4.value; + for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { + var prop = _b[_i]; + var state_5 = _loop_16(prop); + if (typeof state_5 === "object") + return state_5.value; } return false; } @@ -59363,8 +61010,17 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) { - return -1 /* True */; + if (target.flags & 1048576 /* Union */) { + if (containsType(targetTypes, source)) { + return -1 /* True */; + } + var match = getMatchingUnionConstituentForType(target, source); + if (match) { + var related = isRelatedTo(source, match, /*reportErrors*/ false); + if (related) { + return related; + } + } } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { var type = targetTypes_1[_i]; @@ -59538,9 +61194,16 @@ var ts; targetStack = []; } else { + // generate a key where all type parameter id positions are replaced with unconstrained type parameter ids + // this isn't perfect - nested type references passed as type arguments will muck up the indexes and thus + // prevent finding matches- but it should hit up the common cases + var broadestEquivalentId = id.split(",").map(function (i) { return i.replace(/-\d+/g, function (_match, offset) { + var index = ts.length(id.slice(0, offset).match(/[-=]/g) || undefined); + return "=" + index; + }); }).join(","); for (var i = 0; i < maybeCount; i++) { // If source and target are already being compared, consider them related with assumptions - if (id === maybeKeys[i]) { + if (id === maybeKeys[i] || broadestEquivalentId === maybeKeys[i]) { return 3 /* Maybe */; } } @@ -59570,7 +61233,7 @@ var ts; }; } if (expandingFlags === 3 /* Both */) { - ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { sourceId: source.id, sourceIdStack: sourceStack.map(function (t) { return t.id; }), targetId: target.id, @@ -59605,9 +61268,9 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { - ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) { @@ -59629,8 +61292,21 @@ var ts; if (target.flags & 2097152 /* Intersection */) { return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */); } - // Source is an intersection. Check to see if any constituents of the intersection are immediately related - // to the target. + // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the + // constraints of all non-primitive types in the source into a new intersection. We do this because the + // intersection may further constrain the constraints of the non-primitive types. For example, given a type + // parameter 'T extends 1 | 2', the intersection 'T & 1' should be reduced to '1' such that it doesn't + // appear to be comparable to '2'. + if (relation === comparableRelation && target.flags & 131068 /* Primitive */) { + var constraints = ts.sameMap(source.types, function (t) { return t.flags & 131068 /* Primitive */ ? t : getBaseConstraintOfType(t) || unknownType; }); + if (constraints !== source.types) { + source = getIntersectionType(constraints); + if (!(source.flags & 2097152 /* Intersection */)) { + return isRelatedTo(source, target, /*reportErrors*/ false); + } + } + } + // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually // useful and leads to some confusing error messages. Instead it is better to let the below checks @@ -59650,21 +61326,21 @@ var ts; if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_7 = 0 /* False */; + var result_8 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_7 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_8; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_7 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_7 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_7; + if (result_8 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_8 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_8; } } } @@ -59744,6 +61420,20 @@ var ts; } } else if (target.flags & 8388608 /* IndexedAccess */) { + if (source.flags & 8388608 /* IndexedAccess */) { + // Relate components directly before falling back to constraint relationships + // A type S[K] is related to a type T[J] if S is related to T and K is related to J. + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + if (reportErrors) { + originalErrorInfo = errorInfo; + } + } // A type S is related to a type T[K] if S is related to C, where C is the base // constraint of T[K] for writing. if (relation === assignableRelation || relation === comparableRelation) { @@ -59754,11 +61444,24 @@ var ts; if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) { var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0); var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, target.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, accessFlags); - if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) { - return result; + if (constraint) { + if (reportErrors && originalErrorInfo) { + // create a new chain for the constraint error + resetErrorInfo(saveErrorInfo); + } + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + // prefer the shorter chain of the constraint comparison chain, and the direct comparison chain + if (reportErrors && originalErrorInfo && errorInfo) { + errorInfo = countMessageChainBreadth([originalErrorInfo]) <= countMessageChainBreadth([errorInfo]) ? originalErrorInfo : errorInfo; + } } } } + if (reportErrors) { + originalErrorInfo = undefined; + } } else if (isGenericMappedType(target) && !target.declaration.nameType) { // A source type T is related to a target type { [P in X]: T[P] } @@ -59802,27 +61505,48 @@ var ts; } } } - else if (target.flags & 134217728 /* TemplateLiteral */ && source.flags & 128 /* StringLiteral */) { - if (isPatternLiteralType(target)) { - // match all non-`string` segments - var result_8 = inferLiteralsFromTemplateLiteralType(source, target); - if (result_8 && ts.every(result_8, function (r, i) { return isStringLiteralTypeValueParsableAsType(r, target.types[i]); })) { - return -1 /* True */; - } + else if (target.flags & 16777216 /* Conditional */) { + var c = target; + // Check if the conditional is always true or always false but still deferred for distribution purposes + var skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); + var skipFalse = !skipTrue && isConditionalTypeAlwaysTrueDisregardingInferTypes(c); + // Instantiate with a replacement mapper if the conditional is distributive, replacing the check type with a clone of itself, + // this way {x: string | number, y: string | number} -> (T extends T ? { x: T, y: T } : never) appropriately _fails_ when + // T = string | number (since that will end up distributing and producing `{x: string, y: string} | {x: number, y: number}`, + // to which `{x: string | number, y: string | number}` isn't assignable) + var distributionMapper = void 0; + var checkVar = getActualTypeVariable(c.root.checkType); + if (c.root.isDistributive && checkVar.flags & 262144 /* TypeParameter */) { + var newParam = cloneTypeParameter(checkVar); + distributionMapper = prependTypeMapping(checkVar, newParam, c.mapper); + newParam.mapper = distributionMapper; + } + // TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't) + var localResult = void 0; + if (skipTrue || (localResult = isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.trueType), distributionMapper) : getTrueTypeFromConditionalType(c), /*reportErrors*/ false))) { + if (!skipFalse) { + localResult = (localResult || 3 /* Maybe */) & isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.falseType), distributionMapper) : getFalseTypeFromConditionalType(c), /*reportErrors*/ false); + } + } + if (localResult) { + resetErrorInfo(saveErrorInfo); + return localResult; } } - if (source.flags & 8650752 /* TypeVariable */) { - if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { - // A type S[K] is related to a type T[J] if S is related to T and K is related to J. - if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { - result &= isRelatedTo(source.indexType, target.indexType, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } + else if (target.flags & 134217728 /* TemplateLiteral */) { + if (source.flags & 134217728 /* TemplateLiteral */) { + // Report unreliable variance for type variables referenced in template literal type placeholders. + // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. + instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } - else { + var result_9 = inferTypesFromTemplateLiteralType(source, target); + if (result_9 && ts.every(result_9, function (r, i) { return isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]); })) { + return -1 /* True */; + } + } + if (source.flags & 8650752 /* TypeVariable */) { + // IndexedAccess comparisons are handled above in the `target.flags & TypeFlage.IndexedAccess` branch + if (!(source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */)) { var constraint = getConstraintOfType(source); if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. @@ -59837,7 +61561,7 @@ var ts; return result; } // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example - else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, intersectionState)) { + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors && !(target.flags & source.flags & 262144 /* TypeParameter */), /*headMessage*/ undefined, intersectionState)) { resetErrorInfo(saveErrorInfo); return result; } @@ -59850,17 +61574,10 @@ var ts; } } else if (source.flags & 134217728 /* TemplateLiteral */) { - if (target.flags & 134217728 /* TemplateLiteral */) { - if (source.texts.length === target.texts.length && - source.types.length === target.types.length && - ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) && - ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 /* Any */ | 4 /* String */)) || !!isRelatedTo(t, target.types[i], /*reportErrors*/ false); })) { - return -1 /* True */; - } - } - else { - var constraint = getBaseConstraintOfType(source); - if (result = isRelatedTo(constraint && constraint !== source ? constraint : stringType, target, reportErrors)) { + if (!(target.flags & 134217728 /* TemplateLiteral */)) { + var baseConstraint = getBaseConstraintOfType(source); + var constraint = baseConstraint && baseConstraint !== source ? baseConstraint : stringType; + if (result = isRelatedTo(constraint, target, reportErrors)) { resetErrorInfo(saveErrorInfo); return result; } @@ -59892,7 +61609,7 @@ var ts; if (sourceParams) { // If the source has infer type parameters, we instantiate them in the context of the target var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo); - inferTypes(ctx.inferences, target.extendsType, sourceExtends, 256 /* NoConstraints */ | 512 /* AlwaysStrict */); + inferTypes(ctx.inferences, target.extendsType, sourceExtends, 512 /* NoConstraints */ | 1024 /* AlwaysStrict */); sourceExtends = instantiateType(sourceExtends, ctx.mapper); mapper = ctx.mapper; } @@ -59950,7 +61667,7 @@ var ts; return 0 /* False */; } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && - !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { + !(ts.getObjectFlags(source) & 4096 /* MarkerType */ || ts.getObjectFlags(target) & 4096 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. @@ -59978,7 +61695,7 @@ var ts; } // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})` // and not `{} <- fresh({}) <- {[idx: string]: any}` - else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) { + else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 16384 /* FreshLiteral */ && !isEmptyObjectType(source)) { return 0 /* False */; } // Even if relationship doesn't hold for unions, intersections, or generic type references, @@ -60016,14 +61733,19 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_9) { - return result_9; + var result_10 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_10) { + return result_10; } } } } return 0 /* False */; + function countMessageChainBreadth(info) { + if (!info) + return 0; + return ts.reduceLeft(info, function (value, chain) { return value + 1 + countMessageChainBreadth(chain.next); }, 0); + } function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) { if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) { return result; @@ -60085,13 +61807,13 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_10; + var result_11; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + if (result_11 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) { - return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_11 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } } @@ -60122,7 +61844,7 @@ var ts; numCombinations *= countTypes(getTypeOfSymbol(sourceProperty)); if (numCombinations > 25) { // We've reached the complexity limit. - ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations }); return 0 /* False */; } } @@ -60161,8 +61883,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_6 = _loop_18(i); - switch (state_6) { + var state_7 = _loop_18(i); + switch (state_7) { case "continue-outer": continue outer; } } @@ -60175,9 +61897,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_5 = _loop_17(combination); - if (typeof state_5 === "object") - return state_5.value; + var state_6 = _loop_17(combination); + if (typeof state_6 === "object") + return state_6.value; } // Compare the remaining non-discriminant properties of each match. var result = -1 /* True */; @@ -60231,7 +61953,7 @@ var ts; ts.Debug.assertIsDefined(links.deferralParent); ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */); - var result_11 = unionParent ? 0 /* False */ : -1 /* True */; + var result_12 = unionParent ? 0 /* False */ : -1 /* True */; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -60241,7 +61963,7 @@ var ts; // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_11 &= related; + result_12 &= related; } else { if (related) { @@ -60249,17 +61971,17 @@ var ts; } } } - if (unionParent && !result_11 && targetIsOptional) { - result_11 = isRelatedTo(source, undefinedType); + if (unionParent && !result_12 && targetIsOptional) { + result_12 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_11 && reportErrors) { + if (unionParent && !result_12 && reportErrors) { // The easiest way to get the right errors here is to un-defer (which may be costly) // If it turns out this is too costly too often, we can replicate the error handling logic within // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union // type on which to hand discriminable properties, which we are expressly trying to avoid here) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_11; + return result_12; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState); @@ -60590,7 +62312,7 @@ var ts; var targetSignature = ts.first(targetSignatures); result = signatureRelatedTo(sourceSignature, targetSignature, eraseGenerics, reportErrors, incompatibleReporter(sourceSignature, targetSignature)); if (!result && reportErrors && kind === 1 /* Construct */ && (sourceObjectFlags & targetObjectFlags) && - (((_a = targetSignature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 166 /* Constructor */ || ((_b = sourceSignature.declaration) === null || _b === void 0 ? void 0 : _b.kind) === 166 /* Constructor */)) { + (((_a = targetSignature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 167 /* Constructor */ || ((_b = sourceSignature.declaration) === null || _b === void 0 ? void 0 : _b.kind) === 167 /* Constructor */)) { var constructSignatureToString = function (signature) { return signatureToString(signature, /*enclosingDeclaration*/ undefined, 262144 /* WriteArrowStyleSignature */, kind); }; @@ -60698,10 +62420,17 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetType = getIndexTypeOfType(target, kind); - if (!targetType || targetType.flags & 1 /* Any */ && !sourceIsPrimitive) { - // Index signature of type any permits assignment from everything but primitives + if (!targetType) { return -1 /* True */; } + if (targetType.flags & 1 /* Any */ && !sourceIsPrimitive) { + // An index signature of type `any` permits assignment from everything but primitives, + // provided that there is also a `string` index signature of type `any`. + var stringIndexType = kind === 0 /* String */ ? targetType : getIndexTypeOfType(target, 0 /* String */); + if (stringIndexType && stringIndexType.flags & 1 /* Any */) { + return -1 /* True */; + } + } if (isGenericMappedType(source)) { // A generic mapped type { [P in K]: T } is related to a type with an index signature // { [x: string]: U }, and optionally with an index signature { [x: number]: V }, @@ -60856,7 +62585,7 @@ var ts; // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); - result.objectFlags |= 8192 /* MarkerType */; + result.objectFlags |= 4096 /* MarkerType */; return result; } function getAliasVariances(symbol) { @@ -60877,7 +62606,7 @@ var ts; if (typeParameters === void 0) { typeParameters = ts.emptyArray; } var variances = cache.variances; if (!variances) { - ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 }); // The emptyArray singleton is used to signal a recursive invocation. cache.variances = ts.emptyArray; variances = []; @@ -60916,7 +62645,7 @@ var ts; _loop_19(tp); } cache.variances = variances; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } return variances; } @@ -60944,7 +62673,7 @@ var ts; return !!(ts.getObjectFlags(type) & 4 /* Reference */) && !type.node; } function isTypeReferenceWithGenericArguments(type) { - return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return !!(t.flags & 262144 /* TypeParameter */) || isTypeReferenceWithGenericArguments(t); }); } /** * getTypeReferenceId(A) returns "111=0-12=1" @@ -61030,8 +62759,8 @@ var ts; } // Return true if the given class derives from each of the declaring classes of the protected // constituents of the given property. - function isClassDerivedFromDeclaringClasses(checkClass, prop) { - return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) { + return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p, writing) & 16 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons @@ -61049,23 +62778,26 @@ var ts; function isDeeplyNestedType(type, stack, depth) { if (depth >= 5) { var identity_1 = getRecursionIdentity(type); - if (identity_1) { - var count = 0; - for (var i = 0; i < depth; i++) { - if (getRecursionIdentity(stack[i]) === identity_1) { - count++; - if (count >= 5) { - return true; - } + var count = 0; + for (var i = 0; i < depth; i++) { + if (getRecursionIdentity(stack[i]) === identity_1) { + count++; + if (count >= 5) { + return true; } } } } return false; } - // Types with constituents that could circularly reference the type have a recursion identity. The recursion - // identity is some object that is common to instantiations of the type with the same origin. + // The recursion identity of a type is an object identity that is shared among multiple instantiations of the type. + // We track recursion identities in order to identify deeply nested and possibly infinite type instantiations with + // the same origin. For example, when type parameters are in scope in an object type such as { x: T }, all + // instantiations of that type have the same recursion identity. The default recursion identity is the object + // identity of the type, meaning that every type is unique. Generally, types with constituents that could circularly + // reference the type have a recursion identity that differs from the object identity. function getRecursionIdentity(type) { + // Object and array literals are known not to contain recursive references and don't need a recursion identity. if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) { if (ts.getObjectFlags(type) && 4 /* Reference */ && type.node) { // Deferred type references are tracked through their associated AST node. This gives us finer @@ -61083,6 +62815,9 @@ var ts; return type.target; } } + if (type.flags & 262144 /* TypeParameter */) { + return type.symbol; + } if (type.flags & 8388608 /* IndexedAccess */) { // Identity is the leftmost object type in a chain of indexed accesses, eg, in A[P][Q] it is A do { @@ -61094,7 +62829,7 @@ var ts; // The root object represents the origin of the conditional type return type.root; } - return undefined; + return type; } function isPropertyIdenticalTo(sourceProp, targetProp) { return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; @@ -61233,6 +62968,9 @@ var ts; // of those literal types. Otherwise, return the leftmost type for which no type to the // right is a supertype. function getSupertypeOrUnion(types) { + if (types.length === 1) { + return types[0]; + } return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); @@ -61267,9 +63005,32 @@ var ts; // or if it is not the undefined or null type and if it is assignable to ReadonlyArray return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } + function getSingleBaseForNonAugmentingSubtype(type) { + if (!(ts.getObjectFlags(type) & 4 /* Reference */) || !(ts.getObjectFlags(type.target) & 3 /* ClassOrInterface */)) { + return undefined; + } + if (ts.getObjectFlags(type) & 33554432 /* IdenticalBaseTypeCalculated */) { + return ts.getObjectFlags(type) & 67108864 /* IdenticalBaseTypeExists */ ? type.cachedEquivalentBaseType : undefined; + } + type.objectFlags |= 33554432 /* IdenticalBaseTypeCalculated */; + var target = type.target; + var bases = getBaseTypes(target); + if (bases.length !== 1) { + return undefined; + } + if (getMembersOfSymbol(type.symbol).size) { + return undefined; // If the interface has any members, they may subtype members in the base, so we should do a full structural comparison + } + var instantiatedBase = !ts.length(target.typeParameters) ? bases[0] : instantiateType(bases[0], createTypeMapper(target.typeParameters, getTypeArguments(type).slice(0, target.typeParameters.length))); + if (ts.length(getTypeArguments(type)) > ts.length(target.typeParameters)) { + instantiatedBase = getTypeWithThisArgument(instantiatedBase, ts.last(getTypeArguments(type))); + } + type.objectFlags |= 67108864 /* IdenticalBaseTypeExists */; + return type.cachedEquivalentBaseType = instantiatedBase; + } function isEmptyArrayLiteralType(type) { - var elementType = isArrayType(type) ? getTypeArguments(type)[0] : undefined; - return elementType === undefinedWideningType || elementType === implicitNeverType; + var elementType = getElementTypeOfArrayType(type); + return strictNullChecks ? elementType === implicitNeverType : elementType === undefinedWideningType; } function isTupleLikeType(type) { return isTupleType(type) || !!getPropertyOfType(type, "0"); @@ -61293,6 +63054,13 @@ var ts; function isUnitType(type) { return !!(type.flags & 109440 /* Unit */); } + function isUnitLikeType(type) { + return type.flags & 2097152 /* Intersection */ ? ts.some(type.types, isUnitType) : + !!(type.flags & 109440 /* Unit */); + } + function extractUnitType(type) { + return type.flags & 2097152 /* Intersection */ ? ts.find(type.types, isUnitType) || type : type; + } function isLiteralType(type) { return type.flags & 16 /* Boolean */ ? true : type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : @@ -61300,7 +63068,7 @@ var ts; } function getBaseTypeOfLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ ? stringType : + type.flags & 128 /* StringLiteral */ ? stringType : type.flags & 256 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : @@ -61309,7 +63077,7 @@ var ts; } function getWidenedLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 134217856 /* StringLikeLiteral */ && isFreshLiteralType(type) ? stringType : + type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : @@ -61443,14 +63211,17 @@ var ts; return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { + // First reduce away any constituents that are assignable to 'undefined' or 'null'. This not only eliminates + // 'undefined' and 'null', but also higher-order types such as a type parameter 'U extends undefined | null' + // that isn't eliminated by a NonNullable instantiation. + var reducedType = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); if (!deferredGlobalNonNullableTypeAlias) { deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol; } - // Use NonNullable global type alias if available to improve quick info/declaration emit - if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { - return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); - } - return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior + // If the NonNullable type is available, return an instantiation. Otherwise just return the reduced type. + return deferredGlobalNonNullableTypeAlias !== unknownSymbol ? + getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [reducedType]) : + reducedType; } function getNonNullableType(type) { return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; @@ -61503,7 +63274,7 @@ var ts; function isObjectTypeWithInferableIndex(type) { return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 && - !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */); @@ -61536,7 +63307,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 16384 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -61547,7 +63318,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags; - regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */; + regularNew.objectFlags |= resolved.objectFlags & ~16384 /* FreshLiteral */; type.regularType = regularNew; return regularNew; } @@ -61577,7 +63348,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { var t = _a[_i]; - if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { + if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 4194304 /* ContainsSpread */)) { for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { var prop = _c[_b]; names.set(prop.escapedName, prop); @@ -61626,14 +63397,14 @@ var ts; var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); - result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening + result.objectFlags |= (ts.getObjectFlags(type) & (8192 /* JSLiteral */ | 524288 /* NonInferrableType */)); // Retain js literal flag through widening return result; } function getWidenedType(type) { return getWidenedTypeWithContext(type, /*context*/ undefined); } function getWidenedTypeWithContext(type, context) { - if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) { + if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) { if (context === undefined && type.widened) { return type.widened; } @@ -61678,7 +63449,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) { if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -61704,7 +63475,7 @@ var ts; for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) { + if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -61723,12 +63494,12 @@ var ts; } var diagnostic; switch (declaration.kind) { - case 216 /* BinaryExpression */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 217 /* BinaryExpression */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: diagnostic = noImplicitAny ? ts.Diagnostics.Member_0_implicitly_has_an_1_type : ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 160 /* Parameter */: + case 161 /* Parameter */: var param = declaration; if (ts.isIdentifier(param.name) && (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) && @@ -61743,23 +63514,23 @@ var ts; noImplicitAny ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : noImplicitAny ? ts.Diagnostics.Parameter_0_implicitly_has_an_1_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; - case 198 /* BindingElement */: + case 199 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; if (!noImplicitAny) { // Don't issue a suggestion for binding elements since the codefix doesn't yet support them. return; } break; - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; - case 251 /* FunctionDeclaration */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 252 /* FunctionDeclaration */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: if (noImplicitAny && !declaration.name) { if (wideningKind === 3 /* GeneratorYield */) { error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString); @@ -61773,7 +63544,7 @@ var ts; wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; - case 190 /* MappedType */: + case 191 /* MappedType */: if (noImplicitAny) { error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); } @@ -61784,7 +63555,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -61900,23 +63671,23 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) { - return !!(objectFlags & 134217728 /* CouldContainTypeVariables */); + if (objectFlags & 1048576 /* CouldContainTypeVariablesComputed */) { + return !!(objectFlags & 2097152 /* CouldContainTypeVariables */); } var result = !!(type.flags & 465829888 /* Instantiable */ || type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || - objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) || + objectFlags & (32 /* Mapped */ | 1024 /* ReverseMapped */ | 8388608 /* ObjectRestType */)) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables)); if (type.flags & 3899393 /* ObjectFlagsType */) { - type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0); + type.objectFlags |= 1048576 /* CouldContainTypeVariablesComputed */ | (result ? 2097152 /* CouldContainTypeVariables */ : 0); } return result; } function isNonGenericTopLevelType(type) { if (type.aliasSymbol && !type.aliasTypeArguments) { - var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 254 /* TypeAliasDeclaration */); - return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 297 /* SourceFile */ ? true : n.kind === 256 /* ModuleDeclaration */ ? false : "quit"; })); + var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 255 /* TypeAliasDeclaration */); + return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 298 /* SourceFile */ ? true : n.kind === 257 /* ModuleDeclaration */ ? false : "quit"; })); } return false; } @@ -61969,7 +63740,7 @@ var ts; // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive // arrow function, but is considered partially inferable because property 'a' has an inferable type. function isPartiallyInferableType(type) { - return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) || + return !(ts.getObjectFlags(type) & 524288 /* NonInferrableType */) || isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }) || isTupleType(type) && ts.some(getTypeArguments(type), isPartiallyInferableType); } @@ -61993,14 +63764,18 @@ var ts; } // For all other object types we infer a new object type where the reverse mapping has been // applied to the type of each property. - var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); + var reversed = createObjectType(1024 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined); reversed.source = source; reversed.mappedType = target; reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + return links.type; } function inferReverseMappedType(sourceType, target, constraint) { var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); @@ -62092,51 +63867,113 @@ var ts; // * it does not contain a numeric seperator (the `BigInt` constructor does not accept a numeric seperator in its input) return success && result === 9 /* BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* ContainsSeparator */); } - function isStringLiteralTypeValueParsableAsType(s, target) { - if (target.flags & 1048576 /* Union */) { - return !!forEachType(target, function (t) { return isStringLiteralTypeValueParsableAsType(s, t); }); - } - switch (target) { - case stringType: return true; - case numberType: return s.value !== "" && isFinite(+(s.value)); - case bigintType: return s.value !== "" && isValidBigIntString(s.value); - // the next 4 should be handled in `getTemplateLiteralType`, as they are all exactly one value, but are here for completeness, just in case - // this function is ever used on types which don't come from template literal holes - case trueType: return s.value === "true"; - case falseType: return s.value === "false"; - case undefinedType: return s.value === "undefined"; - case nullType: return s.value === "null"; - default: return !!(target.flags & 1 /* Any */); - } - } - function inferLiteralsFromTemplateLiteralType(source, target) { - var value = source.value; - var texts = target.texts; - var lastIndex = texts.length - 1; - var startText = texts[0]; - var endText = texts[lastIndex]; - if (!(value.startsWith(startText) && value.slice(startText.length).endsWith(endText))) + function isValidTypeForTemplateLiteralPlaceholder(source, target) { + if (source === target || target.flags & (1 /* Any */ | 4 /* String */)) { + return true; + } + if (source.flags & 128 /* StringLiteral */) { + var value = source.value; + return !!(target.flags & 8 /* Number */ && value !== "" && isFinite(+value) || + target.flags & 64 /* BigInt */ && value !== "" && isValidBigIntString(value) || + target.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) && value === target.intrinsicName); + } + if (source.flags & 134217728 /* TemplateLiteral */) { + var texts = source.texts; + return texts.length === 2 && texts[0] === "" && texts[1] === "" && isTypeAssignableTo(source.types[0], target); + } + return isTypeAssignableTo(source, target); + } + function inferTypesFromTemplateLiteralType(source, target) { + return source.flags & 128 /* StringLiteral */ ? inferFromLiteralPartsToTemplateLiteral([source.value], ts.emptyArray, target) : + source.flags & 134217728 /* TemplateLiteral */ ? + ts.arraysEqual(source.texts, target.texts) ? ts.map(source.types, getStringLikeTypeForType) : + inferFromLiteralPartsToTemplateLiteral(source.texts, source.types, target) : + undefined; + } + function getStringLikeTypeForType(type) { + return type.flags & (1 /* Any */ | 402653316 /* StringLike */) ? type : getTemplateLiteralType(["", ""], [type]); + } + // This function infers from the text parts and type parts of a source literal to a target template literal. The number + // of text parts is always one more than the number of type parts, and a source string literal is treated as a source + // with one text part and zero type parts. The function returns an array of inferred string or template literal types + // corresponding to the placeholders in the target template literal, or undefined if the source doesn't match the target. + // + // We first check that the starting source text part matches the starting target text part, and that the ending source + // text part ends matches the ending target text part. We then iterate through the remaining target text parts, finding + // a match for each in the source and inferring string or template literal types created from the segments of the source + // that occur between the matches. During this iteration, seg holds the index of the current text part in the sourceTexts + // array and pos holds the current character position in the current text part. + // + // Consider inference from type `<<${string}>.<${number}-${number}>>` to type `<${string}.${string}>`, i.e. + // sourceTexts = ['<<', '>.<', '-', '>>'] + // sourceTypes = [string, number, number] + // target.texts = ['<', '.', '>'] + // We first match '<' in the target to the start of '<<' in the source and '>' in the target to the end of '>>' in + // the source. The first match for the '.' in target occurs at character 1 in the source text part at index 1, and thus + // the first inference is the template literal type `<${string}>`. The remainder of the source makes up the second + // inference, the template literal type `<${number}-${number}>`. + function inferFromLiteralPartsToTemplateLiteral(sourceTexts, sourceTypes, target) { + var lastSourceIndex = sourceTexts.length - 1; + var sourceStartText = sourceTexts[0]; + var sourceEndText = sourceTexts[lastSourceIndex]; + var targetTexts = target.texts; + var lastTargetIndex = targetTexts.length - 1; + var targetStartText = targetTexts[0]; + var targetEndText = targetTexts[lastTargetIndex]; + if (lastSourceIndex === 0 && sourceStartText.length < targetStartText.length + targetEndText.length || + !sourceStartText.startsWith(targetStartText) || !sourceEndText.endsWith(targetEndText)) return undefined; + var remainingEndText = sourceEndText.slice(0, sourceEndText.length - targetEndText.length); var matches = []; - var str = value.slice(startText.length, value.length - endText.length); - var pos = 0; - for (var i = 1; i < lastIndex; i++) { - var delim = texts[i]; - var delimPos = delim.length > 0 ? str.indexOf(delim, pos) : pos < str.length ? pos + 1 : -1; - if (delimPos < 0) + var seg = 0; + var pos = targetStartText.length; + for (var i = 1; i < lastTargetIndex; i++) { + var delim = targetTexts[i]; + if (delim.length > 0) { + var s = seg; + var p = pos; + while (true) { + p = getSourceText(s).indexOf(delim, p); + if (p >= 0) + break; + s++; + if (s === sourceTexts.length) + return undefined; + p = 0; + } + addMatch(s, p); + pos += delim.length; + } + else if (pos < getSourceText(seg).length) { + addMatch(seg, pos + 1); + } + else if (seg < lastSourceIndex) { + addMatch(seg + 1, 0); + } + else { return undefined; - matches.push(getLiteralType(str.slice(pos, delimPos))); - pos = delimPos + delim.length; + } } - matches.push(getLiteralType(str.slice(pos))); + addMatch(lastSourceIndex, getSourceText(lastSourceIndex).length); return matches; + function getSourceText(index) { + return index < lastSourceIndex ? sourceTexts[index] : remainingEndText; + } + function addMatch(s, p) { + var matchType = s === seg ? + getLiteralType(getSourceText(s).slice(pos, p)) : + getTemplateLiteralType(__spreadArray(__spreadArray([sourceTexts[seg].slice(pos)], sourceTexts.slice(seg + 1, s)), [getSourceText(s).slice(0, p)]), sourceTypes.slice(seg, s)); + matches.push(matchType); + seg = s; + pos = p; + } } function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) { if (priority === void 0) { priority = 0; } if (contravariant === void 0) { contravariant = false; } var bivariant = false; var propagationType; - var inferencePriority = 1024 /* MaxValue */; + var inferencePriority = 2048 /* MaxValue */; var allowComplexConstraintInference = true; var visited; var sourceStack; @@ -62223,8 +64060,8 @@ var ts; // not contain anyFunctionType when we come back to this argument for its second round // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard // when constructing types from type parameters that had no inference candidates). - if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || - (priority & 64 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || + (priority & 128 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); @@ -62251,7 +64088,7 @@ var ts; clearCachedInferences(inferences); } } - if (!(priority & 64 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 128 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; clearCachedInferences(inferences); } @@ -62291,7 +64128,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - inferWithPriority(empty, target.type, 128 /* LiteralKeyof */); + inferWithPriority(empty, target.type, 256 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -62303,6 +64140,13 @@ var ts; inferFromTypes(source.type, target.type); } } + else if (source.flags & 33554432 /* Substitution */) { + inferFromTypes(source.baseType, target); + var oldPriority = priority; + priority |= 4 /* SubstituteSource */; + inferFromTypes(source.substitute, target); // Make substitute inference at a lower priority + priority = oldPriority; + } else if (target.flags & 16777216 /* Conditional */) { invokeOnce(source, target, inferToConditionalType); } @@ -62322,7 +64166,7 @@ var ts; } else { source = getReducedType(source); - if (!(priority & 256 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { + if (!(priority & 512 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) { var apparentSource = getApparentType(source); // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` @@ -62360,26 +64204,22 @@ var ts; } (visited || (visited = new ts.Map())).set(key, -1 /* Circularity */); var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; // We stop inferring and report a circularity if we encounter duplicate recursion identities on both // the source side and the target side. var saveExpandingFlags = expandingFlags; - var sourceIdentity = getRecursionIdentity(source) || source; - var targetIdentity = getRecursionIdentity(target) || target; - if (sourceIdentity && ts.contains(sourceStack, sourceIdentity)) + var sourceIdentity = getRecursionIdentity(source); + var targetIdentity = getRecursionIdentity(target); + if (ts.contains(sourceStack, sourceIdentity)) expandingFlags |= 1 /* Source */; - if (targetIdentity && ts.contains(targetStack, targetIdentity)) + if (ts.contains(targetStack, targetIdentity)) expandingFlags |= 2 /* Target */; if (expandingFlags !== 3 /* Both */) { - if (sourceIdentity) - (sourceStack || (sourceStack = [])).push(sourceIdentity); - if (targetIdentity) - (targetStack || (targetStack = [])).push(targetIdentity); + (sourceStack || (sourceStack = [])).push(sourceIdentity); + (targetStack || (targetStack = [])).push(targetIdentity); action(source, target); - if (targetIdentity) - targetStack.pop(); - if (sourceIdentity) - sourceStack.pop(); + targetStack.pop(); + sourceStack.pop(); } else { inferencePriority = -1 /* Circularity */; @@ -62419,7 +64259,7 @@ var ts; } } function inferFromContravariantTypes(source, target) { - if (strictFunctionTypes || priority & 512 /* AlwaysStrict */) { + if (strictFunctionTypes || priority & 1024 /* AlwaysStrict */) { contravariant = !contravariant; inferFromTypes(source, target); contravariant = !contravariant; @@ -62471,7 +64311,7 @@ var ts; else { for (var i = 0; i < sources.length; i++) { var saveInferencePriority = inferencePriority; - inferencePriority = 1024 /* MaxValue */; + inferencePriority = 2048 /* MaxValue */; inferFromTypes(sources[i], t); if (inferencePriority === priority) matched_1[i] = true; @@ -62550,9 +64390,9 @@ var ts; // We assign a lower priority to inferences made from types containing non-inferrable // types because we may only have a partial result (i.e. we may have failed to make // reverse inferences for some properties). - inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ? - 8 /* PartialHomomorphicMappedType */ : - 4 /* HomomorphicMappedType */); + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 524288 /* NonInferrableType */ ? + 16 /* PartialHomomorphicMappedType */ : + 8 /* HomomorphicMappedType */); } } return true; @@ -62560,7 +64400,7 @@ var ts; if (constraintType.flags & 262144 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type // parameter. First infer from 'keyof S' to K. - inferWithPriority(getIndexType(source), constraintType, 16 /* MappedTypeConstraint */); + inferWithPriority(getIndexType(source), constraintType, 32 /* MappedTypeConstraint */); // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X }, // where K extends keyof T, we make the same inferences as for a homomorphic mapped type // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a @@ -62589,16 +64429,14 @@ var ts; } else { var savePriority = priority; - priority |= contravariant ? 32 /* ContravariantConditional */ : 0; + priority |= contravariant ? 64 /* ContravariantConditional */ : 0; var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)]; inferToMultipleTypes(source, targetTypes, target.flags); priority = savePriority; } } function inferToTemplateLiteralType(source, target) { - var matches = source.flags & 128 /* StringLiteral */ ? inferLiteralsFromTemplateLiteralType(source, target) : - source.flags & 134217728 /* TemplateLiteral */ && ts.arraysEqual(source.texts, target.texts) ? source.types : - undefined; + var matches = inferTypesFromTemplateLiteralType(source, target); var types = target.types; for (var i = 0; i < types.length; i++) { inferFromTypes(matches ? matches[i] : neverType, types[i]); @@ -62714,7 +64552,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */); + var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* NonInferrableType */); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -62724,7 +64562,7 @@ var ts; 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 === 165 /* MethodDeclaration */ || kind === 164 /* MethodSignature */ || kind === 166 /* Constructor */; + bivariant = bivariant || kind === 166 /* MethodDeclaration */ || kind === 165 /* MethodSignature */ || kind === 167 /* Constructor */; applyToParameterTypes(source, target, inferFromContravariantTypes); bivariant = saveBivariant; } @@ -62751,7 +64589,7 @@ var ts; } } function isTypeOrBaseIdenticalTo(s, t) { - return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 134217856 /* StringLikeLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); + return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); } function isTypeCloselyMatchedBy(s, t) { return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol || @@ -62765,7 +64603,7 @@ var ts; return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); } function isObjectOrArrayLiteralType(type) { - return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */)); + return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 32768 /* ArrayLiteral */)); } function unionObjectAndArrayLiteralCandidates(candidates) { if (candidates.length > 1) { @@ -62778,7 +64616,7 @@ var ts; return candidates; } function getContravariantInference(inference) { - return inference.priority & 208 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); + return inference.priority & 416 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } function getCovariantInference(inference, signature) { // Extract all object and array literal types and replace them with a single widened and normalized type. @@ -62795,7 +64633,7 @@ var ts; candidates; // If all inferences were made from a position that implies a combined result, infer a union type. // Otherwise, infer a common supertype. - var unwidenedType = inference.priority & 208 /* PriorityImpliesCombination */ ? + var unwidenedType = inference.priority & 416 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -62904,7 +64742,7 @@ var ts; case "BigUint64Array": return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later; default: - if (node.parent.kind === 289 /* ShorthandPropertyAssignment */) { + if (node.parent.kind === 290 /* ShorthandPropertyAssignment */) { return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer; } else { @@ -62925,26 +64763,24 @@ var ts; // TypeScript 1.0 spec (April 2014): 3.6.3 // A type query consists of the keyword typeof followed by an expression. // The expression is restricted to a single identifier or a sequence of identifiers separated by periods - return !!ts.findAncestor(node, function (n) { return n.kind === 176 /* TypeQuery */ ? true : n.kind === 78 /* Identifier */ || n.kind === 157 /* QualifiedName */ ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 177 /* TypeQuery */ ? true : n.kind === 78 /* Identifier */ || n.kind === 158 /* QualifiedName */ ? false : "quit"; }); } // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the // leftmost identifier followed by zero or more property names separated by dots. - // The result is undefined if the reference isn't a dotted name. We prefix nodes - // occurring in an apparent type position with '@' because the control flow type - // of such nodes may be based on the apparent type instead of the declared type. + // The result is undefined if the reference isn't a dotted name. function getFlowCacheKey(node, declaredType, initialType, flowContainer) { switch (node.kind) { case 78 /* Identifier */: var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; case 107 /* ThisKeyword */: return "0|" + (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType); - case 225 /* NonNullExpression */: - case 207 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: var propName = getAccessedPropertyName(node); if (propName !== undefined) { var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); @@ -62955,32 +64791,40 @@ var ts; } function isMatchingReference(source, target) { switch (target.kind) { - case 207 /* ParenthesizedExpression */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: return isMatchingReference(source, target.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return (ts.isAssignmentExpression(target) && isMatchingReference(source, target.left)) || (ts.isBinaryExpression(target) && target.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source, target.right)); } switch (source.kind) { + case 227 /* MetaProperty */: + return target.kind === 227 /* MetaProperty */ + && source.keywordToken === target.keywordToken + && source.name.escapedText === target.name.escapedText; case 78 /* Identifier */: case 79 /* PrivateIdentifier */: return target.kind === 78 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 249 /* VariableDeclaration */ || target.kind === 198 /* BindingElement */) && + (target.kind === 250 /* VariableDeclaration */ || target.kind === 199 /* BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); case 107 /* ThisKeyword */: return target.kind === 107 /* ThisKeyword */; case 105 /* SuperKeyword */: return target.kind === 105 /* SuperKeyword */; - case 225 /* NonNullExpression */: - case 207 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: return isMatchingReference(source.expression, target); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return ts.isAccessExpression(target) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 216 /* BinaryExpression */: + case 158 /* QualifiedName */: + return ts.isAccessExpression(target) && + source.right.escapedText === getAccessedPropertyName(target) && + isMatchingReference(source.left, target.expression); + case 217 /* BinaryExpression */: return (ts.isBinaryExpression(source) && source.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source.right, target)); } return false; @@ -62988,11 +64832,11 @@ var ts; // Given a source x, check if target matches x or is an && operation with an operand that matches x. function containsTruthyCheck(source, target) { return isMatchingReference(source, target) || - (target.kind === 216 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && + (target.kind === 217 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (containsTruthyCheck(source, target.left) || containsTruthyCheck(source, target.right))); } function getAccessedPropertyName(access) { - return access.kind === 201 /* PropertyAccessExpression */ ? access.name.escapedText : + return access.kind === 202 /* PropertyAccessExpression */ ? access.name.escapedText : ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : undefined; } @@ -63042,6 +64886,86 @@ var ts; } return result; } + // Given a set of constituent types and a property name, create and return a map keyed by the literal + // types of the property by that name in each constituent type. No map is returned if some key property + // has a non-literal type or if less than 10 or less than 50% of the constituents have a unique key. + // Entries with duplicate keys have unknownType as the value. + function mapTypesByKeyProperty(types, name) { + var map = new ts.Map(); + var count = 0; + var _loop_20 = function (type) { + if (type.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */)) { + var discriminant = getTypeOfPropertyOfType(type, name); + if (discriminant) { + if (!isLiteralType(discriminant)) { + return { value: undefined }; + } + var duplicate_1 = false; + forEachType(discriminant, function (t) { + var id = getTypeId(getRegularTypeOfLiteralType(t)); + var existing = map.get(id); + if (!existing) { + map.set(id, type); + } + else if (existing !== unknownType) { + map.set(id, unknownType); + duplicate_1 = true; + } + }); + if (!duplicate_1) + count++; + } + } + }; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; + var state_8 = _loop_20(type); + if (typeof state_8 === "object") + return state_8.value; + } + return count >= 10 && count * 2 >= types.length ? map : undefined; + } + // Return the name of a discriminant property for which it was possible and feasible to construct a map of + // constituent types keyed by the literal types of the property by that name in each constituent type. + function getKeyPropertyName(unionType) { + var types = unionType.types; + // We only construct maps for large unions with non-primitive constituents. + if (types.length < 10 || ts.getObjectFlags(unionType) & 65536 /* PrimitiveUnion */) { + return undefined; + } + if (unionType.keyPropertyName === undefined) { + // The candidate key property name is the name of the first property with a unit type in one of the + // constituent types. + var keyPropertyName = ts.forEach(types, function (t) { + return t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ? + ts.forEach(getPropertiesOfType(t), function (p) { return isUnitType(getTypeOfSymbol(p)) ? p.escapedName : undefined; }) : + undefined; + }); + var mapByKeyProperty = keyPropertyName && mapTypesByKeyProperty(types, keyPropertyName); + unionType.keyPropertyName = mapByKeyProperty ? keyPropertyName : ""; + unionType.constituentMap = mapByKeyProperty; + } + return unionType.keyPropertyName.length ? unionType.keyPropertyName : undefined; + } + // Given a union type for which getKeyPropertyName returned a non-undefined result, return the constituent + // that corresponds to the given key type for that property name. + function getConstituentTypeForKeyType(unionType, keyType) { + var _a; + var result = (_a = unionType.constituentMap) === null || _a === void 0 ? void 0 : _a.get(getTypeId(getRegularTypeOfLiteralType(keyType))); + return result !== unknownType ? result : undefined; + } + function getMatchingUnionConstituentForType(unionType, type) { + var keyPropertyName = getKeyPropertyName(unionType); + var propType = keyPropertyName && getTypeOfPropertyOfType(type, keyPropertyName); + return propType && getConstituentTypeForKeyType(unionType, propType); + } + function getMatchingUnionConstituentForObjectLiteral(unionType, node) { + var keyPropertyName = getKeyPropertyName(unionType); + var propNode = keyPropertyName && ts.find(node.properties, function (p) { return p.symbol && p.kind === 289 /* PropertyAssignment */ && + p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer); }); + var propType = propNode && getTypeOfExpression(propNode.initializer); + return propType && getConstituentTypeForKeyType(unionType, propType); + } function isOrContainsMatchingReference(source, target) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -63054,7 +64978,7 @@ var ts; } } } - if (expression.expression.kind === 201 /* PropertyAccessExpression */ && + if (expression.expression.kind === 202 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, expression.expression.expression)) { return true; } @@ -63101,14 +65025,6 @@ var ts; } return declaredType; } - function getTypeFactsOfTypes(types) { - var result = 0 /* None */; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; - result |= getTypeFacts(t); - } - return result; - } function isFunctionObjectType(type) { // We do a quick check for a "bind" property before performing the more expensive subtype // check. This gives us a quicker out in the common case where an object type is not a function. @@ -63116,7 +65032,8 @@ var ts; return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type) { + function getTypeFacts(type, ignoreObjects) { + if (ignoreObjects === void 0) { ignoreObjects = false; } var flags = type.flags; if (flags & 4 /* String */) { return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */; @@ -63153,7 +65070,7 @@ var ts; (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } - if (flags & 524288 /* Object */) { + if (flags & 524288 /* Object */ && !ignoreObjects) { return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : isFunctionObjectType(type) ? @@ -63176,11 +65093,17 @@ var ts; return 0 /* None */; } if (flags & 465829888 /* Instantiable */) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType) : + return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : strictNullChecks ? 7929345 /* NonEmptyStringStrictFacts */ : 16776705 /* NonEmptyStringFacts */; } - if (flags & 3145728 /* UnionOrIntersection */) { - return getTypeFactsOfTypes(type.types); + if (flags & 1048576 /* Union */) { + return ts.reduceLeft(type.types, function (facts, t) { return facts | getTypeFacts(t, ignoreObjects); }, 0 /* None */); + } + if (flags & 2097152 /* Intersection */) { + // When an intersection contains a primitive type we ignore object type constituents as they are + // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. + ignoreObjects || (ignoreObjects = maybeTypeOfKind(type, 131068 /* Primitive */)); + return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t, ignoreObjects); }, 16777215 /* All */); } return 16777215 /* All */; } @@ -63188,18 +65111,16 @@ var ts; return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { - if (defaultExpression) { - var defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]); - } - return type; + return defaultExpression ? + getUnionType([getNonUndefinedType(type), getTypeOfExpression(defaultExpression)]) : + type; } function getTypeOfDestructuredProperty(type, name) { var nameType = getLiteralTypeFromPropertyName(name); if (!isTypeUsableAsPropertyName(nameType)) return errorType; var text = getPropertyNameFromType(nameType); - return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || + return getTypeOfPropertyOfType(type, text) || isNumericLiteralName(text) && includeUndefinedInIndexSignature(getIndexTypeOfType(type, 1 /* Number */)) || includeUndefinedInIndexSignature(getIndexTypeOfType(type, 0 /* String */)) || errorType; @@ -63220,15 +65141,15 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) || errorType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 199 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 288 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 200 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 289 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 216 /* BinaryExpression */ && parent.parent.left === parent || - parent.parent.kind === 239 /* ForOfStatement */ && parent.parent.initializer === parent; + return parent.parent.kind === 217 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 240 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); @@ -63245,21 +65166,21 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return stringType; - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return checkRightHandSideOfForOf(parent) || errorType; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return undefinedType; - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return getAssignedTypeOfSpreadExpression(parent); - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } return errorType; @@ -63267,7 +65188,7 @@ var ts; function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 196 /* ObjectBindingPattern */ ? + var type = pattern.kind === 197 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : @@ -63285,30 +65206,30 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 238 /* ForInStatement */) { + if (node.parent.parent.kind === 239 /* ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 239 /* ForOfStatement */) { + if (node.parent.parent.kind === 240 /* ForOfStatement */) { return checkRightHandSideOfForOf(node.parent.parent) || errorType; } return errorType; } function getInitialType(node) { - return node.kind === 249 /* VariableDeclaration */ ? + return node.kind === 250 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function isEmptyArrayAssignment(node) { - return node.kind === 249 /* VariableDeclaration */ && node.initializer && + return node.kind === 250 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 198 /* BindingElement */ && node.parent.kind === 216 /* BinaryExpression */ && + node.kind !== 199 /* BindingElement */ && node.parent.kind === 217 /* BinaryExpression */ && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: switch (node.operatorToken.kind) { case 62 /* EqualsToken */: case 74 /* BarBarEqualsToken */: @@ -63323,13 +65244,13 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 207 /* ParenthesizedExpression */ || - parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node || - parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? + return parent.kind === 208 /* ParenthesizedExpression */ || + parent.kind === 217 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node || + parent.kind === 217 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 284 /* CaseClause */) { + if (clause.kind === 285 /* CaseClause */) { return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); } return neverType; @@ -63349,7 +65270,7 @@ var ts; var witnesses = []; for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { var clause = _a[_i]; - if (clause.kind === 284 /* CaseClause */) { + if (clause.kind === 285 /* CaseClause */) { if (ts.isStringLiteralLike(clause.expression)) { witnesses.push(clause.expression.text); continue; @@ -63385,14 +65306,40 @@ var ts; function forEachType(type, f) { return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type); } + function someType(type, f) { + return type.flags & 1048576 /* Union */ ? ts.some(type.types, f) : f(type); + } function everyType(type, f) { return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type); } + function everyContainedType(type, f) { + return type.flags & 3145728 /* UnionOrIntersection */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 1048576 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); + if (filtered === types) { + return type; + } + var origin = type.origin; + var newOrigin = void 0; + if (origin && origin.flags & 1048576 /* Union */) { + // If the origin type is a (denormalized) union type, filter its non-union constituents. If that ends + // up removing a smaller number of types than in the normalized constituent set (meaning some of the + // filtered types are within nested unions in the origin), then we can't construct a new origin type. + // Otherwise, if we have exactly one type left in the origin set, return that as the filtered type. + // Otherwise, construct a new filtered origin type. + var originTypes = origin.types; + var originFiltered = ts.filter(originTypes, function (t) { return !!(t.flags & 1048576 /* Union */) || f(t); }); + if (originTypes.length - originFiltered.length === types.length - filtered.length) { + if (originFiltered.length === 1) { + return originFiltered[0]; + } + newOrigin = createOriginUnionOrIntersectionType(1048576 /* Union */, originFiltered); + } + } + return getUnionTypeFromSortedList(filtered, type.objectFlags, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, newOrigin); } return type.flags & 131072 /* Never */ || f(type) ? type : neverType; } @@ -63425,6 +65372,11 @@ var ts; } return changed ? mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : type; } + function mapTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) { + return type.flags & 1048576 /* Union */ && aliasSymbol ? + getUnionType(ts.map(type.types, mapper), 1 /* Literal */, aliasSymbol, aliasTypeArguments) : + mapType(type, mapper); + } function getConstituentCount(type) { return type.flags & 3145728 /* UnionOrIntersection */ ? type.types.length : 1; } @@ -63510,12 +65462,12 @@ var ts; var root = getReferenceRoot(node); var parent = root.parent; var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" || - parent.parent.kind === 203 /* CallExpression */ + parent.parent.kind === 204 /* CallExpression */ && ts.isIdentifier(parent.name) && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 202 /* ElementAccessExpression */ && + var isElementAssignment = parent.kind === 203 /* ElementAccessExpression */ && parent.expression === root && - parent.parent.kind === 216 /* BinaryExpression */ && + parent.parent.kind === 217 /* BinaryExpression */ && parent.parent.operatorToken.kind === 62 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && @@ -63523,8 +65475,8 @@ var ts; return isLengthPushOrUnshift || isElementAssignment; } function isDeclarationWithExplicitTypeAnnotation(declaration) { - return (declaration.kind === 249 /* VariableDeclaration */ || declaration.kind === 160 /* Parameter */ || - declaration.kind === 163 /* PropertyDeclaration */ || declaration.kind === 162 /* PropertySignature */) && + return (declaration.kind === 250 /* VariableDeclaration */ || declaration.kind === 161 /* Parameter */ || + declaration.kind === 164 /* PropertyDeclaration */ || declaration.kind === 163 /* PropertySignature */) && !!ts.getEffectiveTypeAnnotationNode(declaration); } function getExplicitTypeOfSymbol(symbol, diagnostic) { @@ -63543,7 +65495,7 @@ var ts; if (isDeclarationWithExplicitTypeAnnotation(declaration)) { return getTypeOfSymbol(symbol); } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 240 /* ForOfStatement */) { var statement = declaration.parent.parent; var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined); if (expressionType) { @@ -63571,11 +65523,25 @@ var ts; return getExplicitThisType(node); case 105 /* SuperKeyword */: return checkSuperExpression(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: { var type = getTypeOfDottedName(node.expression, diagnostic); - var prop = type && getPropertyOfType(type, node.name.escapedText); - return prop && getExplicitTypeOfSymbol(prop, diagnostic); - case 207 /* ParenthesizedExpression */: + if (type) { + var name = node.name; + var prop = void 0; + if (ts.isPrivateIdentifier(name)) { + if (!type.symbol) { + return undefined; + } + prop = getPropertyOfType(type, ts.getSymbolNameForPrivateIdentifier(type.symbol, name.escapedText)); + } + else { + prop = getPropertyOfType(type, name.escapedText); + } + return prop && getExplicitTypeOfSymbol(prop, diagnostic); + } + return undefined; + } + case 208 /* ParenthesizedExpression */: return getTypeOfDottedName(node.expression, diagnostic); } } @@ -63589,7 +65555,7 @@ var ts; // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call // target expression of an assertion. var funcType = void 0; - if (node.parent.kind === 233 /* ExpressionStatement */) { + if (node.parent.kind === 234 /* ExpressionStatement */) { funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined); } else if (node.expression.kind !== 105 /* SuperKeyword */) { @@ -63633,7 +65599,7 @@ var ts; } function isFalseExpression(expr) { var node = ts.skipParentheses(expr); - return node.kind === 94 /* FalseKeyword */ || node.kind === 216 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + return node.kind === 94 /* FalseKeyword */ || node.kind === 217 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); } function isReachableFlowNodeWorker(flow, noCacheCheck) { @@ -63768,7 +65734,7 @@ var ts; // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); - if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 225 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { + if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 226 /* NonNullExpression */ && !(resultType.flags & 131072 /* Never */) && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) { return declaredType; } return resultType; @@ -63783,7 +65749,7 @@ var ts; 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. - ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id }); flowAnalysisDisabled = true; reportFlowControlError(reference); return errorType; @@ -63852,8 +65818,8 @@ var ts; // Check if we should continue with the control flow of the containing function. var container = flow.node; if (container && container !== flowContainer && - reference.kind !== 201 /* PropertyAccessExpression */ && - reference.kind !== 202 /* ElementAccessExpression */ && + reference.kind !== 202 /* PropertyAccessExpression */ && + reference.kind !== 203 /* ElementAccessExpression */ && reference.kind !== 107 /* ThisKeyword */) { flow = container.flowNode; continue; @@ -63878,7 +65844,7 @@ var ts; } function getInitialOrAssignedType(flow) { var node = flow.node; - return getConstraintForLocation(node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */ ? + return getNarrowableTypeForReference(node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */ ? getInitialType(node) : getAssignedType(node), reference); } @@ -63918,14 +65884,14 @@ var ts; // 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 === 208 /* FunctionExpression */ || init.kind === 209 /* ArrowFunction */)) { + if (init && (init.kind === 209 /* FunctionExpression */ || init.kind === 210 /* ArrowFunction */)) { return getTypeAtFlowNode(flow.antecedent); } } return declaredType; } // for (const _ in ref) acts as a nonnull on ref - if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 238 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { + if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 239 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) { return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); } // Assignment doesn't affect reference @@ -63936,7 +65902,7 @@ var ts; if (node.kind === 94 /* FalseKeyword */) { return unreachableNeverType; } - if (node.kind === 216 /* BinaryExpression */) { + if (node.kind === 217 /* BinaryExpression */) { if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); } @@ -63967,7 +65933,7 @@ var ts; function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 203 /* CallExpression */ ? + var expr = node.kind === 204 /* CallExpression */ ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { @@ -63975,7 +65941,7 @@ var ts; var type = getTypeFromFlowType(flowType); if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { var evolvedType_1 = type; - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); @@ -64023,7 +65989,7 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (expr.kind === 211 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + else if (expr.kind === 212 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else { @@ -64031,12 +65997,12 @@ var ts; if (optionalChainContainsReference(expr, reference)) { type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); }); } - else if (expr.kind === 211 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { + else if (expr.kind === 212 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); }); } } if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + type = narrowTypeBySwitchOnDiscriminantProperty(type, expr, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } } return createFlowType(type, isIncomplete(flowType)); @@ -64207,16 +66173,42 @@ var ts; if (propName === undefined) { return type; } - var propType = getTypeOfPropertyOfType(type, propName); + var removeNullable = strictNullChecks && ts.isOptionalChain(access) && maybeTypeOfKind(type, 98304 /* Nullable */); + var propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type, propName); if (!propType) { return type; } + propType = removeNullable ? getOptionalType(propType) : propType; var narrowedPropType = narrowType(propType); return filterType(type, function (t) { var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName); return !(discriminantType.flags & 131072 /* Never */) && isTypeComparableTo(discriminantType, narrowedPropType); }); } + function narrowTypeByDiscriminantProperty(type, access, operator, value, assumeTrue) { + if ((operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) && type.flags & 1048576 /* Union */) { + var keyPropertyName = getKeyPropertyName(type); + if (keyPropertyName && keyPropertyName === getAccessedPropertyName(access)) { + var candidate_2 = getConstituentTypeForKeyType(type, getTypeOfExpression(value)); + if (candidate_2) { + return operator === (assumeTrue ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */) ? candidate_2 : + isUnitType(getTypeOfPropertyOfType(candidate_2, keyPropertyName) || unknownType) ? filterType(type, function (t) { return t !== candidate_2; }) : + type; + } + } + } + return narrowTypeByDiscriminant(type, access, function (t) { return narrowTypeByEquality(t, operator, value, assumeTrue); }); + } + function narrowTypeBySwitchOnDiscriminantProperty(type, access, switchStatement, clauseStart, clauseEnd) { + if (clauseStart < clauseEnd && type.flags & 1048576 /* Union */ && getKeyPropertyName(type) === getAccessedPropertyName(access)) { + var clauseTypes = getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd); + var candidate = getUnionType(ts.map(clauseTypes, function (t) { return getConstituentTypeForKeyType(type, t) || unknownType; })); + if (candidate !== unknownType) { + return candidate; + } + } + return narrowTypeByDiscriminant(type, access, function (t) { return narrowTypeBySwitchOnDiscriminant(t, switchStatement, clauseStart, clauseEnd); }); + } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); @@ -64240,7 +66232,8 @@ var ts; return !assumeTrue; } function narrowByInKeyword(type, literal, assumeTrue) { - if (type.flags & (1048576 /* Union */ | 524288 /* Object */) + if (type.flags & 1048576 /* Union */ + || type.flags & 524288 /* Object */ && declaredType !== type || isThisTypeParameter(type) || type.flags & 2097152 /* Intersection */ && ts.every(type.types, function (t) { return t.symbol !== globalThisSymbol; })) { var propName_1 = ts.escapeLeadingUnderscores(literal.text); @@ -64259,40 +66252,40 @@ var ts; case 35 /* ExclamationEqualsToken */: case 36 /* EqualsEqualsEqualsToken */: case 37 /* ExclamationEqualsEqualsToken */: - var operator_1 = expr.operatorToken.kind; - var left_1 = getReferenceCandidate(expr.left); - var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 211 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { - return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + var operator = expr.operatorToken.kind; + var left = getReferenceCandidate(expr.left); + var right = getReferenceCandidate(expr.right); + if (left.kind === 212 /* TypeOfExpression */ && ts.isStringLiteralLike(right)) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); } - if (right_1.kind === 211 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { - return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + if (right.kind === 212 /* TypeOfExpression */ && ts.isStringLiteralLike(left)) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); } - if (isMatchingReference(reference, left_1)) { - return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + if (isMatchingReference(reference, left)) { + return narrowTypeByEquality(type, operator, right, assumeTrue); } - if (isMatchingReference(reference, right_1)) { - return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + if (isMatchingReference(reference, right)) { + return narrowTypeByEquality(type, operator, left, assumeTrue); } if (strictNullChecks) { - if (optionalChainContainsReference(left_1, reference)) { - type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue); + if (optionalChainContainsReference(left, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator, right, assumeTrue); } - else if (optionalChainContainsReference(right_1, reference)) { - type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); + else if (optionalChainContainsReference(right, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator, left, assumeTrue); } } - if (isMatchingReferenceDiscriminant(left_1, type)) { - return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + if (isMatchingReferenceDiscriminant(left, type)) { + return narrowTypeByDiscriminantProperty(type, left, operator, right, assumeTrue); } - if (isMatchingReferenceDiscriminant(right_1, type)) { - return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + if (isMatchingReferenceDiscriminant(right, type)) { + return narrowTypeByDiscriminantProperty(type, right, operator, left, assumeTrue); } - if (isMatchingConstructorReference(left_1)) { - return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue); + if (isMatchingConstructorReference(left)) { + return narrowTypeByConstructor(type, operator, right, assumeTrue); } - if (isMatchingConstructorReference(right_1)) { - return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue); + if (isMatchingConstructorReference(right)) { + return narrowTypeByConstructor(type, operator, left, assumeTrue); } break; case 101 /* InstanceOfKeyword */: @@ -64357,13 +66350,12 @@ var ts; } if (assumeTrue) { var filterFn = operator === 34 /* EqualsEqualsToken */ ? - (function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); }) : + function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); } : function (t) { return areTypesComparable(t, valueType); }; return replacePrimitivesWithLiterals(filterType(type, filterFn), valueType); } if (isUnitType(valueType)) { - var regularType_1 = getRegularTypeOfLiteralType(valueType); - return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; }); + return filterType(type, function (t) { return !(isUnitLikeType(t) && areTypesComparable(t, valueType)); }); } return type; } @@ -64385,7 +66377,7 @@ var ts; if (assumeTrue && type.flags & 2 /* Unknown */ && literal.text === "object") { // The pattern x && typeof x === 'object', where x is of type unknown, narrows x to type object. We don't // need to check for the reverse typeof x === 'object' && x since that already narrows correctly. - if (typeOfExpr.parent.parent.kind === 216 /* BinaryExpression */) { + if (typeOfExpr.parent.parent.kind === 217 /* BinaryExpression */) { var expr = typeOfExpr.parent.parent; if (expr.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && expr.right === typeOfExpr.parent && containsTruthyCheck(reference, expr.left)) { return nonPrimitiveType; @@ -64441,7 +66433,7 @@ var ts; if (!hasDefaultClause) { return caseType; } - var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + var defaultType = filterType(type, function (t) { return !(isUnitLikeType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(extractUnitType(t)))); }); return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } function getImpliedTypeFromTypeofGuard(type, text) { @@ -64623,7 +66615,16 @@ var ts; } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { - return filterType(type, function (t) { return !isRelated(t, candidate); }); + return filterType(type, function (t) { + if (!isRelated(t, candidate)) { + return true; + } + var constraint = getBaseConstraintOfType(t); + if (constraint && constraint !== t) { + return !isRelated(constraint, candidate); + } + return false; + }); } // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. @@ -64633,10 +66634,15 @@ var ts; return assignableType; } } - // If the candidate type is a subtype of the target type, narrow to the candidate type, - // if the target type is a subtype of the candidate type, narrow to the target type, - // otherwise, narrow to an intersection of the two types. - return isTypeSubtypeOf(candidate, type) ? candidate : isTypeSubtypeOf(type, candidate) ? type : getIntersectionType([type, candidate]); + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByCallExpression(type, callExpression, assumeTrue) { if (hasMatchingArgument(callExpression, reference)) { @@ -64679,17 +66685,17 @@ var ts; case 78 /* Identifier */: case 107 /* ThisKeyword */: case 105 /* SuperKeyword */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return narrowTypeByCallExpression(type, expr, assumeTrue); - case 207 /* ParenthesizedExpression */: - case 225 /* NonNullExpression */: + case 208 /* ParenthesizedExpression */: + case 226 /* NonNullExpression */: return narrowType(type, expr.expression, assumeTrue); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: if (expr.operator === 53 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } @@ -64713,17 +66719,20 @@ var ts; // an dotted name expression, and if the location is not an assignment target, obtain the type // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. - if (location.kind === 78 /* Identifier */) { + if (location.kind === 78 /* Identifier */ || location.kind === 79 /* PrivateIdentifier */) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) { + if (ts.isExpressionNode(location) && (!ts.isAssignmentTarget(location) || ts.isWriteAccess(location))) { var type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } } } + if (ts.isDeclarationName(location) && ts.isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) { + return resolveTypeOfAccessors(location.parent.symbol, /*writing*/ true); + } // The location isn't a reference to the given symbol, meaning we're being asked // a hypothetical question of what type the symbol would have if there was a reference // to it at the given location. Since we have no control flow information for the @@ -64734,13 +66743,16 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 257 /* ModuleBlock */ || - node.kind === 297 /* SourceFile */ || - node.kind === 163 /* PropertyDeclaration */; + node.kind === 258 /* ModuleBlock */ || + node.kind === 298 /* SourceFile */ || + node.kind === 164 /* PropertyDeclaration */; }); } // Check if a parameter is assigned anywhere within its declaring function. function isParameterAssigned(symbol) { + if (!symbol.valueDeclaration) { + return false; + } var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); if (!(links.flags & 8388608 /* AssignmentsMarked */)) { @@ -64758,7 +66770,7 @@ var ts; if (node.kind === 78 /* Identifier */) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 160 /* Parameter */) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 161 /* Parameter */) { symbol.isAssigned = true; } } @@ -64774,7 +66786,7 @@ var ts; function removeOptionalityFromDeclaredType(declaredType, declaration) { if (pushTypeResolution(declaration.symbol, 2 /* DeclaredType */)) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 160 /* Parameter */ && + declaration.kind === 161 /* Parameter */ && declaration.initializer && getFalsyFlags(declaredType) & 32768 /* Undefined */ && !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */); @@ -64788,23 +66800,40 @@ var ts; } function isConstraintPosition(node) { var parent = node.parent; - return parent.kind === 201 /* PropertyAccessExpression */ || - parent.kind === 203 /* CallExpression */ && parent.expression === node || - parent.kind === 202 /* ElementAccessExpression */ && parent.expression === node || - parent.kind === 198 /* BindingElement */ && parent.name === node && !!parent.initializer; - } - function typeHasNullableConstraint(type) { - return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 98304 /* Nullable */); - } - function getConstraintForLocation(type, node) { - // When a node is the left hand expression of a property access, element access, or call expression, - // and the type of the node includes type variables with constraints that are nullable, we fetch the - // apparent type of the node *before* performing control flow analysis such that narrowings apply to - // the constraint type. - if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { - return mapType(getWidenedType(type), getBaseConstraintOrType); - } - return type; + // In an element access obj[x], we consider obj to be in a constraint position only when x is not + // of a generic type. This is because when both obj and x are of generic types T and K, we want + // the resulting type to be T[K]. + return parent.kind === 202 /* PropertyAccessExpression */ || + parent.kind === 204 /* CallExpression */ && parent.expression === node || + parent.kind === 203 /* ElementAccessExpression */ && parent.expression === node && + !isGenericIndexType(getTypeOfExpression(parent.argumentExpression)); + } + function isGenericTypeWithUnionConstraint(type) { + return !!(type.flags & 465829888 /* Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* Nullable */ | 1048576 /* Union */)); + } + function containsGenericType(type) { + return !!(type.flags & 465829888 /* Instantiable */ || type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, containsGenericType)); + } + function hasContextualTypeWithNoGenericTypes(node) { + // Computing the contextual type for a child of a JSX element involves resolving the type of the + // element's tag name, so we exclude that here to avoid circularities. + var contextualType = (ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && + !((ts.isJsxOpeningElement(node.parent) || ts.isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && + getContextualType(node); + return contextualType && !someType(contextualType, containsGenericType); + } + function getNarrowableTypeForReference(type, reference, checkMode) { + // When the type of a reference is or contains an instantiable type with a union type constraint, and + // when the reference is in a constraint position (where it is known we'll obtain the apparent type) or + // has a contextual type containing no top-level instantiables (meaning constraints will determine + // assignability), we substitute constraints for all instantiables in the type of the reference to give + // control flow analysis an opportunity to narrow it further. For example, for a reference of a type + // parameter type 'T extends string | undefined' with a contextual type 'string', we substitute + // 'string | undefined' to give control flow analysis the opportunity to narrow to type 'string'. + var substituteConstraints = !(checkMode && checkMode & 2 /* Inferential */) && + someType(type, isGenericTypeWithUnionConstraint) && + (isConstraintPosition(reference) || hasContextualTypeWithNoGenericTypes(reference)); + return substituteConstraints ? mapType(type, function (t) { return t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type; } function isExportOrExportExpression(location) { return !!ts.findAncestor(location, function (e) { return e.parent && ts.isExportAssignment(e.parent) && e.parent.expression === e && ts.isEntityNameExpression(e); }); @@ -64813,7 +66842,12 @@ var ts; if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { var target = resolveAlias(symbol); if (target.flags & 111551 /* Value */) { - if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(target)) { + // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled + // (because the const enum value will not be inlined), or if (2) the alias is an export + // of a const enum declaration that will be preserved. + if (compilerOptions.isolatedModules || + ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || + !isConstEnumOrConstEnumOnlyModule(target)) { markAliasSymbolAsReferenced(symbol); } else { @@ -64822,7 +66856,7 @@ var ts; } } } - function checkIdentifier(node) { + function checkIdentifier(node, checkMode) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { return errorType; @@ -64836,7 +66870,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2 /* ES2015 */) { - if (container.kind === 209 /* ArrowFunction */) { + if (container.kind === 210 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasSyntacticModifier(container, 256 /* Async */)) { @@ -64853,15 +66887,15 @@ var ts; } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); var sourceSymbol = localOrExportSymbol.flags & 2097152 /* Alias */ ? resolveAlias(localOrExportSymbol) : localOrExportSymbol; - if (getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) { - errorOrSuggestion(/* isError */ false, node, ts.Diagnostics._0_is_deprecated, node.escapedText); + if (sourceSymbol.declarations && getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) { + addDeprecatedSuggestion(node, sourceSymbol.declarations, node.escapedText); } var declaration = localOrExportSymbol.valueDeclaration; - if (localOrExportSymbol.flags & 32 /* Class */) { + if (declaration && localOrExportSymbol.flags & 32 /* Class */) { // 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. - if (declaration.kind === 252 /* ClassDeclaration */ + if (declaration.kind === 253 /* ClassDeclaration */ && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -64873,14 +66907,14 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration.kind === 221 /* ClassExpression */) { + else if (declaration.kind === 222 /* ClassExpression */) { // When we emit a class expression with static members that contain a reference // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container.kind !== 297 /* SourceFile */) { + while (container.kind !== 298 /* SourceFile */) { if (container.parent === declaration) { - if (container.kind === 163 /* PropertyDeclaration */ && ts.hasSyntacticModifier(container, 32 /* Static */)) { + if (container.kind === 164 /* PropertyDeclaration */ && ts.hasSyntacticModifier(container, 32 /* Static */)) { getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } @@ -64891,12 +66925,18 @@ var ts; } } checkNestedBlockScopedBinding(node, symbol); - var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); + var type = getTypeOfSymbol(localOrExportSymbol); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + var assignmentError = localOrExportSymbol.flags & 384 /* Enum */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_an_enum + : localOrExportSymbol.flags & 32 /* Class */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_class + : localOrExportSymbol.flags & 1536 /* Module */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_namespace + : localOrExportSymbol.flags & 16 /* Function */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_function + : localOrExportSymbol.flags & 2097152 /* Alias */ ? ts.Diagnostics.Cannot_assign_to_0_because_it_is_an_import + : ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable; + error(node, assignmentError, symbolToString(symbol)); return errorType; } if (isReadonlySymbol(localOrExportSymbol)) { @@ -64918,7 +66958,7 @@ var ts; } } else if (isAlias) { - declaration = ts.find(symbol.declarations, isSomeImportDeclaration); + declaration = getDeclarationOfAliasSymbol(symbol); } else { return type; @@ -64926,10 +66966,11 @@ var ts; if (!declaration) { return type; } + type = getNarrowableTypeForReference(type, node, checkMode); // The declaration container is the innermost function that encloses the declaration of the variable // or parameter. The flow container is the innermost function starting with which we analyze the control // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 160 /* Parameter */; + var isParameter = ts.getRootDeclaration(declaration).kind === 161 /* Parameter */; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; @@ -64938,8 +66979,8 @@ var ts; // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === 208 /* FunctionExpression */ || - flowContainer.kind === 209 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 209 /* FunctionExpression */ || + flowContainer.kind === 210 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } @@ -64948,9 +66989,9 @@ var ts; // declaration container are the same). var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 || - isInTypeQuery(node) || node.parent.kind === 270 /* ExportSpecifier */) || - node.parent.kind === 225 /* NonNullExpression */ || - declaration.kind === 249 /* VariableDeclaration */ && declaration.exclamationToken || + isInTypeQuery(node) || node.parent.kind === 271 /* ExportSpecifier */) || + node.parent.kind === 226 /* NonNullExpression */ || + declaration.kind === 250 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 8388608 /* Ambient */; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : type === autoType || type === autoArrayType ? undefinedType : @@ -64975,17 +67016,21 @@ var ts; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } - function isInsideFunction(node, threshold) { - return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); + function isInsideFunctionOrInstancePropertyInitializer(node, threshold) { + return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n) || (n.parent && ts.isPropertyDeclaration(n.parent) && !ts.hasStaticModifier(n.parent) && n.parent.initializer === n); }); } 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 getEnclosingIterationStatement(node) { + return ts.findAncestor(node, function (n) { return (!n || ts.nodeStartsNewLexicalEnvironment(n)) ? "quit" : ts.isIterationStatement(n, /*lookInLabeledStatements*/ false); }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || + !symbol.valueDeclaration || ts.isSourceFile(symbol.valueDeclaration) || - symbol.valueDeclaration.parent.kind === 287 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 288 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -64993,22 +67038,14 @@ var ts; // 2. walk from the declaration up to the boundary of lexical environment and check // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - var usedInFunction = isInsideFunction(node.parent, container); - var current = container; - var containedInIterationStatement = false; - while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { - if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) { - containedInIterationStatement = true; - break; - } - current = current.parent; - } - if (containedInIterationStatement) { - if (usedInFunction) { + var isCaptured = isInsideFunctionOrInstancePropertyInitializer(node, container); + var enclosingIterationStatement = getEnclosingIterationStatement(container); + if (enclosingIterationStatement) { + if (isCaptured) { // mark iteration statement as containing block-scoped binding captured in some function var capturesBlockScopeBindingInLoopBody = true; if (ts.isForStatement(container)) { - var varDeclList = ts.getAncestor(symbol.valueDeclaration, 250 /* VariableDeclarationList */); + var varDeclList = ts.getAncestor(symbol.valueDeclaration, 251 /* VariableDeclarationList */); if (varDeclList && varDeclList.parent === container) { var part = getPartOfForStatementContainingNode(node.parent, container); if (part) { @@ -65023,13 +67060,13 @@ var ts; } } if (capturesBlockScopeBindingInLoopBody) { - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + getNodeLinks(enclosingIterationStatement).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 (ts.isForStatement(container)) { - var varDeclList = ts.getAncestor(symbol.valueDeclaration, 250 /* VariableDeclarationList */); + var varDeclList = ts.getAncestor(symbol.valueDeclaration, 251 /* VariableDeclarationList */); if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } @@ -65037,7 +67074,7 @@ var ts; // set 'declared inside loop' bit on the block-scoped binding getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } - if (usedInFunction) { + if (isCaptured) { getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } @@ -65048,7 +67085,7 @@ var ts; function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; - while (current.parent.kind === 207 /* ParenthesizedExpression */) { + while (current.parent.kind === 208 /* ParenthesizedExpression */) { current = current.parent; } // check if node is used as LHS in some assignment expression @@ -65056,7 +67093,7 @@ var ts; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 214 /* PrefixUnaryExpression */ || current.parent.kind === 215 /* PostfixUnaryExpression */)) { + else if ((current.parent.kind === 215 /* PrefixUnaryExpression */ || current.parent.kind === 216 /* PostfixUnaryExpression */)) { var expr = current.parent; isAssigned = expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */; } @@ -65069,7 +67106,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 163 /* PropertyDeclaration */ || container.kind === 166 /* Constructor */) { + if (container.kind === 164 /* PropertyDeclaration */ || container.kind === 167 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -65109,37 +67146,37 @@ var ts; // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var capturedByArrowFunction = false; - if (container.kind === 166 /* Constructor */) { + if (container.kind === 167 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 209 /* ArrowFunction */) { + if (container.kind === 210 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); capturedByArrowFunction = true; } switch (container.kind) { - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 166 /* Constructor */: + case 167 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && useDefineForClassFields)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -65227,7 +67264,7 @@ var ts; } function getClassNameFromPrototypeMethod(container) { // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 208 /* FunctionExpression */ && + if (container.kind === 209 /* FunctionExpression */ && ts.isBinaryExpression(container.parent) && ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { // Get the 'x' of 'x.prototype.y = container' @@ -65237,16 +67274,16 @@ var ts; .expression; // x } // x.prototype = { method() { } } - else if (container.kind === 165 /* MethodDeclaration */ && - container.parent.kind === 200 /* ObjectLiteralExpression */ && + else if (container.kind === 166 /* MethodDeclaration */ && + container.parent.kind === 201 /* 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 === 208 /* FunctionExpression */ && - container.parent.kind === 288 /* PropertyAssignment */ && - container.parent.parent.kind === 200 /* ObjectLiteralExpression */ && + else if (container.kind === 209 /* FunctionExpression */ && + container.parent.kind === 289 /* PropertyAssignment */ && + container.parent.parent.kind === 201 /* ObjectLiteralExpression */ && ts.isBinaryExpression(container.parent.parent.parent) && ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { return container.parent.parent.parent.left.expression; @@ -65254,7 +67291,7 @@ var ts; // Object.defineProperty(x, "method", { value: function() { } }); // Object.defineProperty(x, "method", { set: (x: () => void) => void }); // Object.defineProperty(x, "method", { get: () => function() { }) }); - else if (container.kind === 208 /* FunctionExpression */ && + else if (container.kind === 209 /* FunctionExpression */ && ts.isPropertyAssignment(container.parent) && ts.isIdentifier(container.parent.name) && (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && @@ -65279,7 +67316,7 @@ var ts; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 308 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 309 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -65293,16 +67330,16 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 160 /* Parameter */ && n.parent === constructorDecl; }); + return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 161 /* Parameter */ && n.parent === constructorDecl; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 203 /* CallExpression */ && node.parent.expression === node; + var isCallExpression = node.parent.kind === 204 /* CallExpression */ && node.parent.expression === node; var immediateContainer = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var container = immediateContainer; var needToCaptureLexicalThis = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - while (container && container.kind === 209 /* ArrowFunction */) { + while (container && container.kind === 210 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } @@ -65315,14 +67352,14 @@ var ts; // class B { // [super.foo()]() {} // } - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 158 /* ComputedPropertyName */; }); - if (current && current.kind === 158 /* ComputedPropertyName */) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 159 /* ComputedPropertyName */; }); + if (current && current.kind === 159 /* ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 200 /* ObjectLiteralExpression */)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 201 /* ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { @@ -65330,7 +67367,7 @@ var ts; } return errorType; } - if (!isCallExpression && immediateContainer.kind === 166 /* Constructor */) { + if (!isCallExpression && immediateContainer.kind === 167 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } if (ts.hasSyntacticModifier(container, 32 /* Static */) || isCallExpression) { @@ -65399,7 +67436,7 @@ var ts; // 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 === 165 /* MethodDeclaration */ && ts.hasSyntacticModifier(container, 256 /* Async */)) { + if (container.kind === 166 /* MethodDeclaration */ && ts.hasSyntacticModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } @@ -65413,7 +67450,7 @@ var ts; // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 200 /* ObjectLiteralExpression */) { + if (container.parent.kind === 201 /* ObjectLiteralExpression */) { if (languageVersion < 2 /* ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return errorType; @@ -65434,7 +67471,7 @@ var ts; if (!baseClassType) { return errorType; } - if (container.kind === 166 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 167 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); return errorType; @@ -65449,7 +67486,7 @@ var ts; if (isCallExpression) { // TS 1.0 SPEC (April 2014): 4.8.1 // Super calls are only permitted in constructors of derived classes - return container.kind === 166 /* Constructor */; + return container.kind === 167 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -65457,21 +67494,21 @@ var ts; // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance // - In a static member function or static member accessor // topmost container must be something that is directly nested in the class declaration\object literal expression - if (ts.isClassLike(container.parent) || container.parent.kind === 200 /* ObjectLiteralExpression */) { + if (ts.isClassLike(container.parent) || container.parent.kind === 201 /* ObjectLiteralExpression */) { if (ts.hasSyntacticModifier(container, 32 /* Static */)) { - return container.kind === 165 /* MethodDeclaration */ || - container.kind === 164 /* MethodSignature */ || - container.kind === 167 /* GetAccessor */ || - container.kind === 168 /* SetAccessor */; + return container.kind === 166 /* MethodDeclaration */ || + container.kind === 165 /* MethodSignature */ || + container.kind === 168 /* GetAccessor */ || + container.kind === 169 /* SetAccessor */; } else { - return container.kind === 165 /* MethodDeclaration */ || - container.kind === 164 /* MethodSignature */ || - container.kind === 167 /* GetAccessor */ || - container.kind === 168 /* SetAccessor */ || - container.kind === 163 /* PropertyDeclaration */ || - container.kind === 162 /* PropertySignature */ || - container.kind === 166 /* Constructor */; + return container.kind === 166 /* MethodDeclaration */ || + container.kind === 165 /* MethodSignature */ || + container.kind === 168 /* GetAccessor */ || + container.kind === 169 /* SetAccessor */ || + container.kind === 164 /* PropertyDeclaration */ || + container.kind === 163 /* PropertySignature */ || + container.kind === 167 /* Constructor */; } } } @@ -65479,10 +67516,10 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 165 /* MethodDeclaration */ || - func.kind === 167 /* GetAccessor */ || - func.kind === 168 /* SetAccessor */) && func.parent.kind === 200 /* ObjectLiteralExpression */ ? func.parent : - func.kind === 208 /* FunctionExpression */ && func.parent.kind === 288 /* PropertyAssignment */ ? func.parent.parent : + return (func.kind === 166 /* MethodDeclaration */ || + func.kind === 168 /* GetAccessor */ || + func.kind === 169 /* SetAccessor */) && func.parent.kind === 201 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 209 /* FunctionExpression */ && func.parent.kind === 289 /* PropertyAssignment */ ? func.parent.parent : undefined; } function getThisTypeArgument(type) { @@ -65494,7 +67531,7 @@ var ts; }); } function getContextualThisParameterType(func) { - if (func.kind === 209 /* ArrowFunction */) { + if (func.kind === 210 /* ArrowFunction */) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -65521,7 +67558,7 @@ var ts; if (thisType) { return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral))); } - if (literal.parent.kind !== 288 /* PropertyAssignment */) { + if (literal.parent.kind !== 289 /* PropertyAssignment */) { break; } literal = literal.parent.parent; @@ -65535,7 +67572,7 @@ var ts; // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. var parent = ts.walkUpParenthesizedExpressions(func.parent); - if (parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) { + if (parent.kind === 217 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) { var target = parent.left; if (ts.isAccessExpression(target)) { var expression = target.expression; @@ -65588,11 +67625,11 @@ var ts; return getTypeFromTypeNode(typeNode); } switch (declaration.kind) { - case 160 /* Parameter */: + case 161 /* Parameter */: return getContextuallyTypedParameterType(declaration); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return getContextualTypeForBindingElement(declaration); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: if (ts.hasSyntacticModifier(declaration, 32 /* Static */)) { return getContextualTypeForStaticPropertyDeclaration(declaration); } @@ -65603,10 +67640,10 @@ var ts; var parent = declaration.parent.parent; var name = declaration.propertyName || declaration.name; var parentType = getContextualTypeForVariableLikeDeclaration(parent) || - parent.kind !== 198 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent); + parent.kind !== 199 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent); if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name)) return undefined; - if (parent.name.kind === 197 /* ArrayBindingPattern */) { + if (parent.name.kind === 198 /* ArrayBindingPattern */) { var index = ts.indexOfNode(declaration.parent.elements, declaration); if (index < 0) return undefined; @@ -65743,7 +67780,7 @@ var ts; return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 205 /* TaggedTemplateExpression */) { + if (template.parent.kind === 206 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -65777,16 +67814,16 @@ var ts; // In an assignment expression, the right operand is contextually typed by the type of the left operand. // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. function getContextualTypeForAssignmentDeclaration(binaryExpression) { + var _a, _b; var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return getTypeOfExpression(binaryExpression.left); + case 4 /* ThisProperty */: + return getContextualTypeForThisPropertyAssignment(binaryExpression); case 5 /* Property */: - case 1 /* ExportsProperty */: - case 6 /* Prototype */: - case 3 /* PrototypeProperty */: if (isPossiblyAliasedThisProperty(binaryExpression, kind)) { - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + return getContextualTypeForThisPropertyAssignment(binaryExpression); } // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. // See `bindStaticPropertyAssignment` in `binder.ts`. @@ -65807,11 +67844,11 @@ var ts; var id = lhs.expression; var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true); if (parentSymbol) { - var annotated = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); - if (annotated) { + var annotated_1 = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated_1) { var nameStr = ts.getElementOrPropertyAccessName(lhs); if (nameStr !== undefined) { - return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr); + return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated_1), nameStr); } } return undefined; @@ -65819,9 +67856,15 @@ var ts; } return ts.isInJSFile(decl) ? undefined : getTypeOfExpression(binaryExpression.left); } + case 1 /* ExportsProperty */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + var valueDeclaration = (_a = binaryExpression.left.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration; + // falls through case 2 /* ModuleExports */: - case 4 /* ThisProperty */: - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + valueDeclaration || (valueDeclaration = (_b = binaryExpression.symbol) === null || _b === void 0 ? void 0 : _b.valueDeclaration); + var annotated = valueDeclaration && ts.getEffectiveTypeAnnotationNode(valueDeclaration); + return annotated ? getTypeFromTypeNode(annotated) : undefined; case 7 /* ObjectDefinePropertyValue */: case 8 /* ObjectDefinePropertyExports */: case 9 /* ObjectDefinePrototypeProperty */: @@ -65842,7 +67885,7 @@ var ts; var symbol = resolveName(declaration.left, name, 111551 /* Value */, undefined, undefined, /*isUse*/ true, /*excludeGlobals*/ true); return ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration); } - function getContextualTypeForThisPropertyAssignment(binaryExpression, kind) { + function getContextualTypeForThisPropertyAssignment(binaryExpression) { if (!binaryExpression.symbol) return getTypeOfExpression(binaryExpression.left); if (binaryExpression.symbol.valueDeclaration) { @@ -65854,8 +67897,6 @@ var ts; } } } - if (kind === 2 /* ModuleExports */) - return undefined; var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression); if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { return undefined; @@ -65910,9 +67951,13 @@ var ts; } function getContextualTypeForObjectLiteralElement(element, contextFlags) { var objectLiteral = element.parent; + var propertyAssignmentType = ts.isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + if (propertyAssignmentType) { + return propertyAssignmentType; + } var type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { - if (!hasNonBindableDynamicName(element)) { + if (hasBindableName(element)) { // 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. @@ -65998,19 +68043,19 @@ var ts; case 78 /* Identifier */: case 150 /* UndefinedKeyword */: return true; - case 201 /* PropertyAccessExpression */: - case 207 /* ParenthesizedExpression */: + case 202 /* PropertyAccessExpression */: + case 208 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); - case 283 /* JsxExpression */: + case 284 /* 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 === 288 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 289 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return getContextFreeTypeOfExpression(prop.initializer); }, prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { - return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 280 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + return discriminateTypeByDiscriminableItems(contextualType, ts.concatenate(ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), ts.map(ts.filter(getPropertiesOfType(contextualType), function (s) { var _a; return !!(s.flags & 16777216 /* Optional */) && !!((_a = node === null || node === void 0 ? void 0 : node.symbol) === null || _a === void 0 ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), function (s) { return [function () { return undefinedType; }, s.escapedName]; })), isTypeAssignableTo, contextualType); } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. @@ -66021,15 +68066,9 @@ var ts; var instantiatedType = instantiateContextualType(contextualType, node, contextFlags); if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) { var apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true); - if (apparentType.flags & 1048576 /* Union */) { - if (ts.isObjectLiteralExpression(node)) { - return discriminateContextualTypeByObjectMembers(node, apparentType); - } - else if (ts.isJsxAttributes(node)) { - return discriminateContextualTypeByJSXAttributes(node, apparentType); - } - } - return apparentType; + return apparentType.flags & 1048576 /* Union */ && ts.isObjectLiteralExpression(node) ? discriminateContextualTypeByObjectMembers(node, apparentType) : + apparentType.flags & 1048576 /* Union */ && ts.isJsxAttributes(node) ? discriminateContextualTypeByJSXAttributes(node, apparentType) : + apparentType; } } // If the given contextual type contains instantiable types and if a mapper representing @@ -66096,58 +68135,60 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 198 /* BindingElement */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 199 /* BindingElement */: return getContextualTypeForInitializerExpression(node, contextFlags); - case 209 /* ArrowFunction */: - case 242 /* ReturnStatement */: + case 210 /* ArrowFunction */: + case 243 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return getContextualTypeForAwaitOperand(parent, contextFlags); - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (parent.expression.kind === 99 /* ImportKeyword */) { return stringType; } /* falls through */ - case 204 /* NewExpression */: + case 205 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return ts.isConstTypeReference(parent.type) ? tryFindWhenConstTypeReference(parent) : getTypeFromTypeNode(parent.type); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node, contextFlags); - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent, contextFlags); - case 290 /* SpreadAssignment */: - return getApparentTypeOfContextualType(parent.parent, contextFlags); - case 199 /* ArrayLiteralExpression */: { + case 291 /* SpreadAssignment */: + return getContextualType(parent.parent, contextFlags); + case 200 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node, contextFlags); - case 228 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 218 /* TemplateExpression */); + case 229 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 219 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 207 /* ParenthesizedExpression */: { + case 208 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags); } - case 283 /* JsxExpression */: + case 226 /* NonNullExpression */: + return getContextualType(parent, contextFlags); + case 284 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); - case 280 /* JsxAttribute */: - case 282 /* JsxSpreadAttribute */: + case 281 /* JsxAttribute */: + case 283 /* JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent); - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent, contextFlags); } return undefined; @@ -66183,14 +68224,14 @@ var ts; return propsType; } function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { - if (sig.unionSignatures) { + if (sig.compositeSignatures) { // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature, // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur // for a union signature). It's an unfortunate quirk of looking in the output of the signature for the type we want to use for the input. // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane. var results = []; - for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) { + for (var _i = 0, _a = sig.compositeSignatures; _i < _a.length; _i++) { var signature = _a[_i]; var instance = getReturnTypeOfSignature(signature); if (isTypeAny(instance)) { @@ -66202,7 +68243,7 @@ var ts; } results.push(propType); } - return getIntersectionType(results); + return getIntersectionType(results); // Same result for both union and intersection signatures } var instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); @@ -66227,16 +68268,19 @@ var ts; function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { var managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { - var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); // fetches interface type, or initializes symbol links type parmaeters var ctorType = getStaticTypeOfReferencedJsxConstructor(context); + if (managedSym.flags & 524288 /* TypeAlias */) { + var params = getSymbolLinks(managedSym).typeParameters; + if (ts.length(params) >= 2) { + var args = fillMissingTypeArguments([ctorType, attributesType], params, 2, ts.isInJSFile(context)); + return getTypeAliasInstantiation(managedSym, args); + } + } if (ts.length(declaredManagedType.typeParameters) >= 2) { var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } - else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); - return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); - } } return attributesType; } @@ -66281,16 +68325,93 @@ var ts; return apparentAttributesType; } } + function getIntersectedSignatures(signatures) { + return ts.getStrictOptionValue(compilerOptions, "noImplicitAny") + ? ts.reduceLeft(signatures, function (left, right) { + return left === right || !left ? left + : compareTypeParametersIdentical(left.typeParameters, right.typeParameters) ? combineSignaturesOfIntersectionMembers(left, right) + : undefined; + }) + : undefined; + } + function combineIntersectionThisParam(left, right, mapper) { + if (!left || !right) { + return left || right; + } + // A signature `this` type might be a read or a write position... It's very possible that it should be invariant + // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be + // pessimistic when contextual typing, for now, we'll union the `this` types. + var thisType = getUnionType([getTypeOfSymbol(left), instantiateType(getTypeOfSymbol(right), mapper)]); + return createSymbolWithType(left, thisType); + } + function combineIntersectionParameters(left, right, mapper) { + var leftCount = getParameterCount(left); + var rightCount = getParameterCount(right); + var longest = leftCount >= rightCount ? left : right; + var shorter = longest === left ? right : left; + var longestCount = longest === left ? leftCount : rightCount; + var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right)); + var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest); + var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0)); + for (var i = 0; i < longestCount; i++) { + var longestParamType = tryGetTypeAtPosition(longest, i); + if (longest === right) { + longestParamType = instantiateType(longestParamType, mapper); + } + var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType; + if (shorter === right) { + shorterParamType = instantiateType(shorterParamType, mapper); + } + var unionParamType = getUnionType([longestParamType, shorterParamType]); + var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1); + var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter); + var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i); + var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i); + var paramName = leftName === rightName ? leftName : + !leftName ? rightName : + !rightName ? leftName : + undefined; + var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg" + i); + paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType; + params[i] = paramSymbol; + } + if (needsExtraRestElement) { + var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args"); + restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount)); + if (shorter === right) { + restParamSymbol.type = instantiateType(restParamSymbol.type, mapper); + } + params[longestCount] = restParamSymbol; + } + return params; + } + function combineSignaturesOfIntersectionMembers(left, right) { + var typeParams = left.typeParameters || right.typeParameters; + var paramMapper; + if (left.typeParameters && right.typeParameters) { + paramMapper = createTypeMapper(right.typeParameters, left.typeParameters); + // We just use the type parameter defaults from the first signature + } + var declaration = left.declaration; + var params = combineIntersectionParameters(left, right, paramMapper); + var thisParam = combineIntersectionThisParam(left.thisParameter, right.thisParameter, paramMapper); + var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); + var result = createSignature(declaration, typeParams, thisParam, params, + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 39 /* PropagatingFlags */); + result.compositeKind = 2097152 /* Intersection */; + result.compositeSignatures = ts.concatenate(left.compositeKind === 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); + if (paramMapper) { + result.mapper = left.compositeKind === 2097152 /* Intersection */ && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; + } + return result; + } // If the given type is an object or union type with a single signature, and if that signature has at // least as many parameters as the given function, return the signature. Otherwise return undefined. function getContextualCallSignature(type, node) { var signatures = getSignaturesOfType(type, 0 /* Call */); - if (signatures.length === 1) { - var signature = signatures[0]; - if (!isAritySmaller(signature, node)) { - return signature; - } - } + var applicableByArity = ts.filter(signatures, function (s) { return !isAritySmaller(s, node); }); + return applicableByArity.length === 1 ? applicableByArity[0] : getIntersectedSignatures(applicableByArity); } /** If the contextual signature has fewer parameters than the function expression, do not use it */ function isAritySmaller(signature, target) { @@ -66307,7 +68428,7 @@ var ts; return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 208 /* FunctionExpression */ || node.kind === 209 /* ArrowFunction */; + return node.kind === 209 /* FunctionExpression */ || node.kind === 210 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -66321,7 +68442,7 @@ var ts; // all identical ignoring their return type, the result is same signature but with return type as // union type of return types from these signatures function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var typeTagSignature = getSignatureOfTypeTag(node); if (typeTagSignature) { return typeTagSignature; @@ -66369,8 +68490,8 @@ var ts; return node.isSpread ? getIndexedAccessType(node.type, numberType) : node.type; } function hasDefaultValue(node) { - return (node.kind === 198 /* BindingElement */ && !!node.initializer) || - (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */); + return (node.kind === 199 /* BindingElement */ && !!node.initializer) || + (node.kind === 217 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */); } function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; @@ -66382,7 +68503,7 @@ var ts; var inConstContext = isConstContext(node); for (var i = 0; i < elementCount; i++) { var e = elements[i]; - if (e.kind === 220 /* SpreadElement */) { + if (e.kind === 221 /* SpreadElement */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */); } @@ -66425,7 +68546,7 @@ var ts; if (inDestructuringPattern) { return createTupleType(elementTypes, elementFlags); } - if (forceTuple || inConstContext || contextualType && forEachType(contextualType, isTupleLikeType)) { + if (forceTuple || inConstContext || contextualType && someType(contextualType, isTupleLikeType)) { return createArrayLiteralType(createTupleType(elementTypes, elementFlags, /*readonly*/ inConstContext)); } return createArrayLiteralType(createArrayType(elementTypes.length ? @@ -66439,13 +68560,13 @@ var ts; var literalType = type.literalType; if (!literalType) { literalType = type.literalType = cloneTypeReference(type); - literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + literalType.objectFlags |= 32768 /* ArrayLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; } return literalType; } function isNumericName(name) { switch (name.kind) { - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return isNumericComputedName(name); case 78 /* Identifier */: return isNumericLiteralName(name.escapedText); @@ -66492,6 +68613,20 @@ var ts; var links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); + // The computed property name of a non-static class field within a loop must be stored in a block-scoped binding. + // (It needs to be bound at class evaluation time.) + if (ts.isPropertyDeclaration(node.parent) && !ts.hasStaticModifier(node.parent) && ts.isClassExpression(node.parent.parent)) { + var container = ts.getEnclosingBlockScopeContainer(node.parent.parent); + var enclosingIterationStatement = getEnclosingIterationStatement(container); + if (enclosingIterationStatement) { + // The computed field name will use a block scoped binding which can be unique for each iteration of the loop. + getNodeLinks(enclosingIterationStatement).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + // The generated variable which stores the computed field name must be block-scoped. + getNodeLinks(node).flags |= 524288 /* BlockScopedBindingInLoop */; + // The generated variable which stores the class must be block-scoped. + getNodeLinks(node.parent.parent).flags |= 524288 /* BlockScopedBindingInLoop */; + } + } // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). if (links.resolvedType.flags & 98304 /* Nullable */ || @@ -66499,9 +68634,6 @@ var ts; !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } - else { - checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true); - } } return links.resolvedType; } @@ -66541,7 +68673,7 @@ var ts; var spread = emptyObjectType; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 196 /* ObjectBindingPattern */ || contextualType.pattern.kind === 200 /* ObjectLiteralExpression */); + (contextualType.pattern.kind === 197 /* ObjectBindingPattern */ || contextualType.pattern.kind === 201 /* ObjectLiteralExpression */); var inConstContext = isConstContext(node); var checkFlags = inConstContext ? 8 /* Readonly */ : 0; var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); @@ -66556,7 +68688,7 @@ var ts; // which may never occur. for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; - if (elem.name && ts.isComputedPropertyName(elem.name) && !ts.isWellKnownSymbolSyntactically(elem.name)) { + if (elem.name && ts.isComputedPropertyName(elem.name)) { checkComputedPropertyName(elem.name); } } @@ -66564,16 +68696,16 @@ var ts; for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { var memberDecl = _c[_b]; var member = getSymbolOfNode(memberDecl); - var computedNameType = memberDecl.name && memberDecl.name.kind === 158 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + var computedNameType = memberDecl.name && memberDecl.name.kind === 159 /* ComputedPropertyName */ ? checkComputedPropertyName(memberDecl.name) : undefined; - if (memberDecl.kind === 288 /* PropertyAssignment */ || - memberDecl.kind === 289 /* ShorthandPropertyAssignment */ || + if (memberDecl.kind === 289 /* PropertyAssignment */ || + memberDecl.kind === 290 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { - var type = memberDecl.kind === 288 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + var type = memberDecl.kind === 289 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`. // we don't want to say "could not find 'a'". - memberDecl.kind === 289 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : + memberDecl.kind === 290 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); @@ -66585,7 +68717,7 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) : @@ -66596,8 +68728,8 @@ var ts; if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. - var isOptional = (memberDecl.kind === 288 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 289 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 289 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 290 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216 /* Optional */; } @@ -66623,7 +68755,7 @@ var ts; member = prop; allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop); } - else if (memberDecl.kind === 290 /* SpreadAssignment */) { + else if (memberDecl.kind === 291 /* SpreadAssignment */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } @@ -66635,15 +68767,20 @@ var ts; hasComputedNumberProperty = false; } var type = getReducedType(checkExpression(memberDecl.expression)); - if (!isValidSpreadType(type)) { - error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return errorType; + if (isValidSpreadType(type)) { + if (allPropertiesTable) { + checkSpreadPropOverrides(type, allPropertiesTable, memberDecl); + } + offset = propertiesArray.length; + if (spread === errorType) { + continue; + } + spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext); } - if (allPropertiesTable) { - checkSpreadPropOverrides(type, allPropertiesTable, memberDecl); + else { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + spread = errorType; } - spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext); - offset = propertiesArray.length; continue; } else { @@ -66652,7 +68789,7 @@ var ts; // an ordinary function declaration(section 6.1) with no parameters. // A set accessor declaration is processed in the same manner // as an ordinary function declaration with a single parameter and a Void return type. - ts.Debug.assert(memberDecl.kind === 167 /* GetAccessor */ || memberDecl.kind === 168 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 168 /* GetAccessor */ || memberDecl.kind === 169 /* SetAccessor */); checkNodeDeferred(memberDecl); } if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) { @@ -66677,7 +68814,7 @@ var ts; // type with those properties for which the binding pattern specifies a default value. // If the object literal is spread into another object literal, skip this step and let the top-level object // literal handle it instead. - if (contextualTypeHasPattern && node.parent.kind !== 290 /* SpreadAssignment */) { + if (contextualTypeHasPattern && node.parent.kind !== 291 /* SpreadAssignment */) { for (var _d = 0, _e = getPropertiesOfType(contextualType); _d < _e.length; _d++) { var prop = _e[_d]; if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) { @@ -66689,6 +68826,9 @@ var ts; } } } + if (spread === errorType) { + return errorType; + } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext); @@ -66705,9 +68845,9 @@ var ts; var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; if (isJSObjectLiteral) { - result.objectFlags |= 16384 /* JSLiteral */; + result.objectFlags |= 8192 /* JSLiteral */; } if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; @@ -66797,14 +68937,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var objectFlags = 4096 /* JsxAttributes */; + var objectFlags = 2048 /* JsxAttributes */; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -66820,7 +68960,7 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 282 /* JsxSpreadAttribute */); + ts.Debug.assert(attributeDecl.kind === 283 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false); attributesTable = ts.createSymbolTable(); @@ -66846,7 +68986,7 @@ var ts; } } // Handle children attribute - var parent = openingLikeElement.parent.kind === 273 /* JsxElement */ ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 274 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = checkJsxChildren(parent, checkMode); @@ -66862,7 +69002,7 @@ var ts; // 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 */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - childrenContextualType && forEachType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : + childrenContextualType && someType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : createArrayType(getUnionType(childrenTypes)); // Fake up a property declaration for the children childrenPropSymbol.valueDeclaration = ts.factory.createPropertySignature(/*modifiers*/ undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined); @@ -66888,7 +69028,7 @@ var ts; function createJsxAttributesType() { objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectOrArrayLiteral */; return result; } } @@ -66903,7 +69043,7 @@ var ts; childrenTypes.push(stringType); } } - else if (child.kind === 283 /* JsxExpression */ && !child.expression) { + else if (child.kind === 284 /* JsxExpression */ && !child.expression) { continue; // empty jsx expressions don't *really* count as present children } else { @@ -67054,7 +69194,7 @@ var ts; else if (propertiesOfJsxElementAttribPropInterface.length === 1) { return propertiesOfJsxElementAttribPropInterface[0].escapedName; } - else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + else if (propertiesOfJsxElementAttribPropInterface.length > 1 && jsxElementAttribPropInterfaceSym.declarations) { // More than one property on ElementAttributesProperty is an error error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer)); } @@ -67164,11 +69304,11 @@ var ts; if (!links.resolvedJsxElementAttributesType) { var symbol = getIntrinsicTagSymbol(node); if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { - return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol) || errorType; } else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { return links.resolvedJsxElementAttributesType = - getIndexTypeOfType(getDeclaredTypeOfSymbol(symbol), 0 /* String */); + getIndexTypeOfType(getJsxType(JsxNames.IntrinsicElements, node), 0 /* String */) || errorType; } else { return links.resolvedJsxElementAttributesType = errorType; @@ -67321,9 +69461,12 @@ var ts; * @param type The type of the object whose property is being accessed. (Not the type of the property.) * @param prop The symbol for the property being accessed. */ - function checkPropertyAccessibility(node, isSuper, type, prop) { - var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 157 /* QualifiedName */ ? node.right : node.kind === 195 /* ImportType */ ? node : node.name; + function checkPropertyAccessibility(node, isSuper, writing, type, prop, reportError) { + if (reportError === void 0) { reportError = true; } + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop, writing); + var errorNode = node.kind === 158 /* QualifiedName */ ? node.right : + node.kind === 196 /* ImportType */ ? node : + node.kind === 199 /* BindingElement */ && node.propertyName ? node.propertyName : node.name; if (isSuper) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or @@ -67334,7 +69477,9 @@ var ts; // a super property access is permitted and must specify a public static member function of the base class. if (languageVersion < 2 /* ES2015 */) { if (symbolHasNonMethodDeclaration(prop)) { - error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + if (reportError) { + error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + } return false; } } @@ -67343,24 +69488,22 @@ var ts; // This error could mask a private property access error. But, a member // cannot simultaneously be private and abstract, so this will trigger an // additional error elsewhere. - error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + if (reportError) { + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + } return false; } } // Referencing abstract properties within their own constructors is not allowed - if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { + if ((flags & 128 /* Abstract */) && symbolHasNonMethodDeclaration(prop) && + (ts.isThisProperty(node) || ts.isThisInitializedObjectBindingExpression(node) || ts.isObjectBindingPattern(node.parent) && ts.isThisInitializedDeclaration(node.parent.parent))) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); 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; - } - } - if (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name)) { - if (!ts.getContainingClass(node)) { - error(errorNode, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + if (reportError) { + 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; } - return true; } // Public properties are otherwise accessible. if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { @@ -67371,7 +69514,9 @@ var ts; if (flags & 8 /* Private */) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + if (reportError) { + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + } return false; } return true; @@ -67385,7 +69530,7 @@ var ts; // of the property as base classes var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + return isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing) ? enclosingClass : undefined; }); // A protected property is accessible if the property is within the declaring class or classes derived from it if (!enclosingClass) { @@ -67393,7 +69538,9 @@ var ts; // static member access is disallow var thisParameter = void 0; if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + if (reportError) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + } return false; } var thisType = getTypeFromTypeNode(thisParameter.type); @@ -67408,7 +69555,9 @@ var ts; type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined } if (!type || !hasBaseType(type, enclosingClass)) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + if (reportError) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2, symbolToString(prop), typeToString(enclosingClass), typeToString(type)); + } return false; } return true; @@ -67464,20 +69613,20 @@ var ts; } return nonNullType; } - function checkPropertyAccessExpression(node) { - return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) : - checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + function checkPropertyAccessExpression(node, checkMode) { + return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node, checkMode) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name, checkMode); } - function checkPropertyAccessChain(node) { + function checkPropertyAccessChain(node, checkMode) { var leftType = checkExpression(node.expression); var nonOptionalType = getOptionalExpressionType(leftType, node.expression); - return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name, checkMode), node, nonOptionalType !== leftType); } - function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); + function checkQualifiedName(node, checkMode) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right, checkMode); } function isMethodAccessForCall(node) { - while (node.parent.kind === 207 /* ParenthesizedExpression */) { + while (node.parent.kind === 208 /* ParenthesizedExpression */) { node = node.parent; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; @@ -67512,14 +69661,13 @@ var ts; } var diagName = diagnosticName(right); if (propertyOnType) { - var typeValueDecl = propertyOnType.valueDeclaration; - var typeClass_1 = ts.getContainingClass(typeValueDecl); - ts.Debug.assert(!!typeClass_1); + var typeValueDecl = ts.Debug.checkDefined(propertyOnType.valueDeclaration); + var typeClass_1 = ts.Debug.checkDefined(ts.getContainingClass(typeValueDecl)); // We found a private identifier property with the same description. // Either: // - There is a lexically scoped private identifier AND it shadows the one we found on the type. // - It is an attempt to access the private identifier outside of the class. - if (lexicallyScopedIdentifier) { + if (lexicallyScopedIdentifier === null || lexicallyScopedIdentifier === void 0 ? void 0 : lexicallyScopedIdentifier.valueDeclaration) { var lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration; var lexicalClass = ts.getContainingClass(lexicalValueDecl); ts.Debug.assert(!!lexicalClass); @@ -67538,17 +69686,42 @@ var ts; return (isConstructorDeclaredProperty(prop) || ts.isThisProperty(node) && isAutoTypedProperty(prop)) && ts.getThisContainer(node, /*includeArrowFunctions*/ true) === getDeclaringConstructor(prop); } - function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right, checkMode) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); - if (ts.isPrivateIdentifier(right)) { - checkExternalEmitHelpers(node, 524288 /* ClassPrivateFieldGet */); - } var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType; var prop; if (ts.isPrivateIdentifier(right)) { + if (languageVersion < 99 /* ESNext */) { + if (assignmentKind !== 0 /* None */) { + checkExternalEmitHelpers(node, 1048576 /* ClassPrivateFieldSet */); + } + if (assignmentKind !== 1 /* Definite */) { + checkExternalEmitHelpers(node, 524288 /* ClassPrivateFieldGet */); + } + } var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right); + if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && ts.isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) { + grammarErrorOnNode(right, ts.Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, ts.idText(right)); + } + if ((lexicallyScopedSymbol === null || lexicallyScopedSymbol === void 0 ? void 0 : lexicallyScopedSymbol.valueDeclaration) && (compilerOptions.target === 99 /* ESNext */ && !useDefineForClassFields)) { + var lexicalClass_1 = ts.getContainingClass(lexicallyScopedSymbol.valueDeclaration); + var parentStaticFieldInitializer = ts.findAncestor(node, function (n) { + if (n === lexicalClass_1) + return "quit"; + if (ts.isPropertyDeclaration(n.parent) && ts.hasStaticModifier(n.parent) && n.parent.initializer === n && n.parent.parent === lexicalClass_1) { + return true; + } + return false; + }); + if (parentStaticFieldInitializer) { + var parentStaticFieldInitializerSymbol = getSymbolOfNode(parentStaticFieldInitializer.parent); + ts.Debug.assert(parentStaticFieldInitializerSymbol, "Initializer without declaration symbol"); + var diagnostic = error(node, ts.Diagnostics.Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false, ts.symbolName(lexicallyScopedSymbol)); + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(parentStaticFieldInitializer.parent, ts.Diagnostics.Initializer_for_property_0, ts.symbolName(parentStaticFieldInitializerSymbol))); + } + } if (isAnyLike) { if (lexicallyScopedSymbol) { return apparentType; @@ -67563,6 +69736,12 @@ var ts; if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) { return errorType; } + else { + var isSetonlyAccessor = prop && prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); + if (isSetonlyAccessor && assignmentKind !== 1 /* Definite */) { + error(node, ts.Diagnostics.Private_accessor_was_defined_without_a_getter); + } + } } else { if (isAnyLike) { @@ -67573,7 +69752,11 @@ var ts; } prop = getPropertyOfType(apparentType, right.escapedText); } - if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) { + // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums. + // The exceptions are: + // 1. if 'isolatedModules' is enabled, because the const enum value will not be inlined, and + // 2. if 'preserveConstEnums' is enabled and the expression is itself an export, e.g. `export = Foo.Bar.Baz`. + if (ts.isIdentifier(left) && parentSymbol && (compilerOptions.isolatedModules || !(prop && isConstEnumOrConstEnumOnlyModule(prop)) || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) { markAliasReferenced(parentSymbol, node); } var propType; @@ -67606,44 +69789,48 @@ var ts; } } else { - if (getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) { - errorOrSuggestion(/* isError */ false, right, ts.Diagnostics._0_is_deprecated, right.escapedText); + if (prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) { + addDeprecatedSuggestion(right, prop.declarations, right.escapedText); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node, left.kind === 107 /* ThisKeyword */); + markPropertyAsReferenced(prop, node, isSelfTypeAccess(left, parentSymbol)); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left.kind === 105 /* SuperKeyword */, apparentType, prop); + var writing = ts.isWriteAccess(node); + checkPropertyAccessibility(node, left.kind === 105 /* SuperKeyword */, writing, apparentType, prop); if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) { error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } - propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : getConstraintForLocation(getTypeOfSymbol(prop), node); + propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : writing ? getSetAccessorTypeOfSymbol(prop) : getTypeOfSymbol(prop); } - return getFlowTypeOfAccessExpression(node, prop, propType, right); + return getFlowTypeOfAccessExpression(node, prop, propType, right, checkMode); } - function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { + function getFlowTypeOfAccessExpression(node, prop, propType, errorNode, checkMode) { // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. var assignmentKind = ts.getAssignmentTargetKind(node); - if (!ts.isAccessExpression(node) || - assignmentKind === 1 /* Definite */ || - prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { + if (assignmentKind === 1 /* Definite */ || + prop && + !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) + && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */) + && !isDuplicatedCommonJSExport(prop.declarations)) { return propType; } if (propType === autoType) { return getFlowTypeOfProperty(node, prop); } + propType = getNarrowableTypeForReference(propType, node, checkMode); // If strict null checks and strict property initialization checks are enabled, if we have // a this.xxx property access, if the property is an instance property without an initializer, // and if we are in a constructor of the same class as the property declaration, assume that // the property is uninitialized at the top of the control flow. var assumeUninitialized = false; - if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 107 /* ThisKeyword */) { + if (strictNullChecks && strictPropertyInitialization && ts.isAccessExpression(node) && node.expression.kind === 107 /* ThisKeyword */) { var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); - if (flowContainer.kind === 166 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) { + if (flowContainer.kind === 167 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) { assumeUninitialized = true; } } @@ -67670,13 +69857,14 @@ var ts; var diagnosticMessage; var declarationName = ts.idText(right); if (isInPropertyInitializer(node) + && !isOptionalPropertyDeclaration(valueDeclaration) && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) - && !isPropertyDeclaredInAncestorClass(prop)) { + && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } - else if (valueDeclaration.kind === 252 /* ClassDeclaration */ && - node.parent.kind !== 173 /* TypeReference */ && + else if (valueDeclaration.kind === 253 /* ClassDeclaration */ && + node.parent.kind !== 174 /* TypeReference */ && !(valueDeclaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); @@ -67688,22 +69876,22 @@ var ts; function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return true; - case 288 /* PropertyAssignment */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 290 /* SpreadAssignment */: - case 158 /* ComputedPropertyName */: - case 228 /* TemplateSpan */: - case 283 /* JsxExpression */: - case 280 /* JsxAttribute */: - case 281 /* JsxAttributes */: - case 282 /* JsxSpreadAttribute */: - case 275 /* JsxOpeningElement */: - case 223 /* ExpressionWithTypeArguments */: - case 286 /* HeritageClause */: + case 289 /* PropertyAssignment */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 291 /* SpreadAssignment */: + case 159 /* ComputedPropertyName */: + case 229 /* TemplateSpan */: + case 284 /* JsxExpression */: + case 281 /* JsxAttribute */: + case 282 /* JsxAttributes */: + case 283 /* JsxSpreadAttribute */: + case 276 /* JsxOpeningElement */: + case 224 /* ExpressionWithTypeArguments */: + case 287 /* HeritageClause */: return false; default: return ts.isExpressionNode(node) ? false : "quit"; @@ -67775,7 +69963,10 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, missingProperty, container); + var diagnostic = containerSeemsToBeEmptyDomElement(containingType) + ? ts.Diagnostics.Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom + : ts.Diagnostics.Property_0_does_not_exist_on_type_1; + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), diagnostic, missingProperty, container); } } } @@ -67786,9 +69977,14 @@ var ts; } diagnostics.add(resultDiagnostic); } + function containerSeemsToBeEmptyDomElement(containingType) { + return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && + everyContainedType(containingType, function (type) { return type.symbol && /^(EventTarget|Node|((HTML[a-zA-Z]*)?Element))$/.test(ts.unescapeLeadingUnderscores(type.symbol.escapedName)); }) && + isEmptyObjectType(containingType); + } function typeHasStaticProperty(propName, containingType) { var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); - return prop !== undefined && prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */); + return prop !== undefined && !!prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedLibForNonExistentName(name) { var missingName = diagnosticName(name); @@ -67819,7 +70015,15 @@ var ts; } } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 111551 /* Value */); + var props = getPropertiesOfType(containingType); + if (typeof name !== "string") { + var parent_2 = name.parent; + if (ts.isPropertyAccessExpression(parent_2)) { + props = ts.filter(props, function (prop) { return isValidPropertyAccessForCompletions(parent_2, containingType, prop); }); + } + name = ts.idText(name); + } + return getSpellingSuggestionForName(name, props, 111551 /* Value */); } function getSuggestedSymbolForNonexistentJSXAttribute(name, containingType) { var strName = ts.isString(name) ? name : ts.idText(name); @@ -67914,20 +70118,20 @@ var ts; return undefined; } } - function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isSelfTypeAccess) { var valueDeclaration = prop && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration; if (!valueDeclaration) { return; } var hasPrivateModifier = ts.hasEffectiveModifier(valueDeclaration, 8 /* Private */); - var hasPrivateIdentifier = ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name); + var hasPrivateIdentifier = prop.valueDeclaration && ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name); if (!hasPrivateModifier && !hasPrivateIdentifier) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) { return; } - if (isThisAccess) { + if (isSelfTypeAccess) { // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration); if (containingMethod && containingMethod.symbol === prop) { @@ -67936,18 +70140,22 @@ var ts; } (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */; } + function isSelfTypeAccess(name, parent) { + return name.kind === 107 /* ThisKeyword */ + || !!parent && ts.isEntityNameExpression(name) && parent === getResolvedSymbol(ts.getFirstIdentifier(name)); + } function isValidPropertyAccess(node, propertyName) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return isValidPropertyAccessWithType(node, node.expression.kind === 105 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression))); - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left))); - case 195 /* ImportType */: + case 196 /* ImportType */: return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node)); } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind === 201 /* PropertyAccessExpression */ && node.expression.kind === 105 /* SuperKeyword */, property.escapedName, type); + return isValidPropertyAccessWithType(node, node.kind === 202 /* PropertyAccessExpression */ && node.expression.kind === 105 /* SuperKeyword */, property.escapedName, type); // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context. } function isValidPropertyAccessWithType(node, isSuper, propertyName, type) { @@ -67956,11 +70164,11 @@ var ts; } var prop = getPropertyOfType(type, propertyName); if (prop) { - if (ts.isPropertyAccessExpression(node) && prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)) { + if (prop.valueDeclaration && ts.isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration)) { var declClass_1 = ts.getContainingClass(prop.valueDeclaration); return !ts.isOptionalChain(node) && !!ts.findAncestor(node, function (parent) { return parent === declClass_1; }); } - return checkPropertyAccessibility(node, isSuper, type, prop); + return checkPropertyAccessibility(node, isSuper, /*writing*/ false, type, prop, /* reportError */ false); } // In js files properties of unions are allowed in completion return ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); @@ -67970,7 +70178,7 @@ var ts; */ function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 250 /* VariableDeclarationList */) { + if (initializer.kind === 251 /* VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); @@ -67999,7 +70207,7 @@ var ts; var child = expr; var node = expr.parent; while (node) { - if (node.kind === 238 /* ForInStatement */ && + if (node.kind === 239 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -68012,16 +70220,16 @@ var ts; } return false; } - function checkIndexedAccess(node) { - return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) : - checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + function checkIndexedAccess(node, checkMode) { + return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node, checkMode) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression), checkMode); } - function checkElementAccessChain(node) { + function checkElementAccessChain(node, checkMode) { var exprType = checkExpression(node.expression); var nonOptionalType = getOptionalExpressionType(exprType, node.expression); - return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression), checkMode), node, nonOptionalType !== exprType); } - function checkElementAccessExpression(node, exprType) { + function checkElementAccessExpression(node, exprType, checkMode) { var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; var indexExpression = node.argumentExpression; var indexType = checkExpression(indexExpression); @@ -68037,42 +70245,7 @@ var ts; 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) : 0 /* None */; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, /*noUncheckedIndexedAccessCandidate*/ undefined, node, accessFlags | 16 /* ExpressionPosition */) || errorType; - return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); - } - function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { - if (expressionType === errorType) { - // There is already an error, so no need to report one. - return false; - } - if (!ts.isWellKnownSymbolSyntactically(expression)) { - return false; - } - // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) { - if (reportError) { - error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); - } - return false; - } - // The name is Symbol., so make sure Symbol actually resolves to the - // global Symbol object - var leftHandSide = expression.expression; - var leftHandSideSymbol = getResolvedSymbol(leftHandSide); - if (!leftHandSideSymbol) { - return false; - } - var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true); - if (!globalESSymbol) { - // Already errored when we tried to look up the symbol - return false; - } - if (leftHandSideSymbol !== globalESSymbol) { - if (reportError) { - error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); - } - return false; - } - return true; + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, getNodeLinks(node).resolvedSymbol, indexedAccessType, indexExpression, checkMode), node); } function callLikeExpressionMayHaveTypeArguments(node) { return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node); @@ -68083,13 +70256,13 @@ var ts; // This gets us diagnostics for the type arguments and marks them as referenced. ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 205 /* TaggedTemplateExpression */) { + if (node.kind === 206 /* TaggedTemplateExpression */) { checkExpression(node.template); } else if (ts.isJsxOpeningLikeElement(node)) { checkExpression(node.attributes); } - else if (node.kind !== 161 /* Decorator */) { + else if (node.kind !== 162 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -68153,7 +70326,7 @@ var ts; } } function isSpreadArgument(arg) { - return !!arg && (arg.kind === 220 /* SpreadElement */ || arg.kind === 227 /* SyntheticExpression */ && arg.isSpread); + return !!arg && (arg.kind === 221 /* SpreadElement */ || arg.kind === 228 /* SyntheticExpression */ && arg.isSpread); } function getSpreadArgumentIndex(args) { return ts.findIndex(args, isSpreadArgument); @@ -68170,9 +70343,9 @@ var ts; var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments var effectiveParameterCount = getParameterCount(signature); var effectiveMinimumArguments = getMinArgumentCount(signature); - if (node.kind === 205 /* TaggedTemplateExpression */) { + if (node.kind === 206 /* TaggedTemplateExpression */) { argCount = args.length; - if (node.template.kind === 218 /* TemplateExpression */) { + if (node.template.kind === 219 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. @@ -68187,7 +70360,7 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 161 /* Decorator */) { + else if (node.kind === 162 /* Decorator */) { argCount = getDecoratorArgumentCount(node, signature); } else if (ts.isJsxOpeningLikeElement(node)) { @@ -68201,7 +70374,7 @@ var ts; } else if (!node.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(node.kind === 204 /* NewExpression */); + ts.Debug.assert(node.kind === 205 /* NewExpression */); return getMinArgumentCount(signature) === 0; } else { @@ -68276,7 +70449,7 @@ var ts; }); if (!inferenceContext) { applyToReturnTypes(contextualSignature, signature, function (source, target) { - inferTypes(context.inferences, source, target, 64 /* ReturnType */); + inferTypes(context.inferences, source, target, 128 /* ReturnType */); }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); @@ -68287,6 +70460,15 @@ var ts; inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } + function getThisArgumentType(thisArgumentNode) { + if (!thisArgumentNode) { + return voidType; + } + var thisArgumentType = checkExpression(thisArgumentNode); + return ts.isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) : + ts.isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) : + thisArgumentType; + } function inferTypeArguments(node, signature, args, checkMode, context) { if (ts.isJsxOpeningLikeElement(node)) { return inferJsxTypeArguments(node, signature, checkMode, context); @@ -68295,7 +70477,7 @@ var ts; // 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 // return type of 'wrap'. - if (node.kind !== 161 /* Decorator */) { + if (node.kind !== 162 /* Decorator */) { var contextualType = getContextualType(node, ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }) ? 8 /* SkipBindingPatterns */ : 0 /* None */); if (contextualType) { // We clone the inference context to avoid disturbing a resolution in progress for an @@ -68317,7 +70499,7 @@ var ts; instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 64 /* ReturnType */); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* ReturnType */); // Create a type mapper for instantiating generic contextual types using the inferences made // from the return type. We need a separate inference pass here because (a) instantiation of // the source type uses the outer context's return mapper (which excludes inferences made from @@ -68339,12 +70521,11 @@ var ts; var thisType = getThisTypeOfSignature(signature); if (thisType) { var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context.inferences, thisArgumentType, thisType); + inferTypes(context.inferences, getThisArgumentType(thisArgumentNode), thisType); } for (var i = 0; i < argCount; i++) { var arg = args[i]; - if (arg.kind !== 222 /* OmittedExpression */) { + if (arg.kind !== 223 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode); inferTypes(context.inferences, argType, paramType); @@ -68368,7 +70549,7 @@ var ts; 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 getMutableArrayOrTupleType(arg.kind === 227 /* SyntheticExpression */ ? arg.type : + return getMutableArrayOrTupleType(arg.kind === 228 /* SyntheticExpression */ ? arg.type : checkExpressionWithContextualType(arg.expression, restType, context, checkMode)); } } @@ -68378,13 +70559,13 @@ var ts; for (var i = index; i < argCount; i++) { var arg = args[i]; if (isSpreadArgument(arg)) { - var spreadType = arg.kind === 227 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression); + var spreadType = arg.kind === 228 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression); if (isArrayLikeType(spreadType)) { types.push(spreadType); flags.push(8 /* Variadic */); } else { - types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 220 /* SpreadElement */ ? arg.expression : arg)); + types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 221 /* SpreadElement */ ? arg.expression : arg)); flags.push(4 /* Rest */); } } @@ -68395,7 +70576,7 @@ var ts; types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); flags.push(1 /* Required */); } - if (arg.kind === 227 /* SyntheticExpression */ && arg.tupleNameSource) { + if (arg.kind === 228 /* SyntheticExpression */ && arg.tupleNameSource) { names.push(arg.tupleNameSource); } } @@ -68539,24 +70720,12 @@ var ts; return undefined; } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 204 /* NewExpression */) { + if (thisType && thisType !== voidType && node.kind !== 205 /* NewExpression */) { // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = void 0; - if (thisArgumentNode) { - thisArgumentType = checkExpression(thisArgumentNode); - if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { - thisArgumentType = getNonNullableType(thisArgumentType); - } - else if (ts.isOptionalChain(thisArgumentNode.parent)) { - thisArgumentType = removeOptionalTypeMarker(thisArgumentType); - } - } - else { - thisArgumentType = voidType; - } + var thisArgumentType = getThisArgumentType(thisArgumentNode); var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -68569,7 +70738,7 @@ var ts; var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { var arg = args[i]; - if (arg.kind !== 222 /* OmittedExpression */) { + if (arg.kind !== 223 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode); // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive), @@ -68614,7 +70783,7 @@ var ts; * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. */ function getThisArgumentOfCall(node) { - if (node.kind === 203 /* CallExpression */) { + if (node.kind === 204 /* CallExpression */) { var callee = ts.skipOuterExpressions(node.expression); if (ts.isAccessExpression(callee)) { return callee.expression; @@ -68631,17 +70800,17 @@ var ts; * Returns the effective arguments for an expression that works like a function invocation. */ function getEffectiveCallArguments(node) { - if (node.kind === 205 /* TaggedTemplateExpression */) { + if (node.kind === 206 /* TaggedTemplateExpression */) { var template = node.template; var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; - if (template.kind === 218 /* TemplateExpression */) { + if (template.kind === 219 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_3.push(span.expression); }); } return args_3; } - if (node.kind === 161 /* Decorator */) { + if (node.kind === 162 /* Decorator */) { return getEffectiveDecoratorArguments(node); } if (ts.isJsxOpeningLikeElement(node)) { @@ -68652,10 +70821,10 @@ var ts; if (spreadIndex >= 0) { // Create synthetic arguments from spreads of tuple types. var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_20 = function (i) { + var _loop_21 = function (i) { var arg = args[i]; // We can call checkExpressionCached because spread expressions never have a contextual type. - var spreadType = arg.kind === 220 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); + var spreadType = arg.kind === 221 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); if (spreadType && isTupleType(spreadType)) { ts.forEach(getTypeArguments(spreadType), function (t, i) { var _a; @@ -68669,7 +70838,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_20(i); + _loop_21(i); } return effectiveArgs_1; } @@ -68682,30 +70851,30 @@ var ts; var parent = node.parent; var expr = node.expression; switch (parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* 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 160 /* Parameter */: + case 161 /* 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 === 166 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, parent.parent.kind === 167 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), createSyntheticExpression(expr, anyType), createSyntheticExpression(expr, numberType) ]; - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* 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 !== 163 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + var hasPropDesc = parent.kind !== 164 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; return [ createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), @@ -68719,17 +70888,17 @@ var ts; */ function getDecoratorArgumentCount(node, signature) { switch (node.parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return 1; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return 2; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* 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 160 /* Parameter */: + case 161 /* Parameter */: return 3; default: return ts.Debug.fail(); @@ -68775,77 +70944,66 @@ var ts; return constructorSymbol === globalPromiseSymbol; } function getArgumentArityError(node, signatures, args) { - var min = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - var belowArgCount = Number.NEGATIVE_INFINITY; - var aboveArgCount = Number.POSITIVE_INFINITY; - var argCount = args.length; + var _a; + var spreadIndex = getSpreadArgumentIndex(args); + if (spreadIndex > -1) { + return ts.createDiagnosticForNode(args[spreadIndex], ts.Diagnostics.A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter); + } + var min = Number.POSITIVE_INFINITY; // smallest parameter count + var max = Number.NEGATIVE_INFINITY; // largest parameter count + var maxBelow = Number.NEGATIVE_INFINITY; // largest parameter count that is smaller than the number of arguments + var minAbove = Number.POSITIVE_INFINITY; // smallest parameter count that is larger than the number of arguments var closestSignature; for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { var sig = signatures_8[_i]; - var minCount = getMinArgumentCount(sig); - var maxCount = getParameterCount(sig); - if (minCount < argCount && minCount > belowArgCount) - belowArgCount = minCount; - if (argCount < maxCount && maxCount < aboveArgCount) - aboveArgCount = maxCount; - if (minCount < min) { - min = minCount; + var minParameter = getMinArgumentCount(sig); + var maxParameter = getParameterCount(sig); + // smallest/largest parameter counts + if (minParameter < min) { + min = minParameter; closestSignature = sig; } - max = Math.max(max, maxCount); + max = Math.max(max, maxParameter); + // shortest parameter count *longer than the call*/longest parameter count *shorter than the call* + if (minParameter < args.length && minParameter > maxBelow) + maxBelow = minParameter; + if (args.length < maxParameter && maxParameter < minAbove) + minAbove = maxParameter; } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); - var paramRange = hasRestParameter ? min : - min < max ? min + "-" + max : - min; - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var spanArray; - var related; - var error = hasRestParameter || hasSpreadArgument ? - hasRestParameter && hasSpreadArgument ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter ? - ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - paramRange === 1 && argCount === 0 && isPromiseResolveArityError(node) ? - ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : - ts.Diagnostics.Expected_0_arguments_but_got_1; - if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { - var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; - if (paramDecl) { - related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : - ts.isRestParameter(paramDecl) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined); - } - } - if (min < argCount && argCount < max) { - return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); - } - if (!hasSpreadArgument && argCount < min) { - var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1; - } - if (hasRestParameter || hasSpreadArgument) { - spanArray = ts.factory.createNodeArray(args); - if (hasSpreadArgument && argCount) { - var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined; - spanArray = ts.factory.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1))); + var parameterRange = hasRestParameter ? min + : min < max ? min + "-" + max + : min; + var error = hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 + : parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node) ? ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise + : ts.Diagnostics.Expected_0_arguments_but_got_1; + if (min < args.length && args.length < max) { + // between min and max, but with no matching overload + return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove); + } + else if (args.length < min) { + // too short: put the error span on the call expression, not any of the args + var diagnostic = getDiagnosticForCallNode(node, error, parameterRange, args.length); + var parameter = (_a = closestSignature === null || closestSignature === void 0 ? void 0 : closestSignature.declaration) === null || _a === void 0 ? void 0 : _a.parameters[closestSignature.thisParameter ? args.length + 1 : args.length]; + if (parameter) { + var parameterError = ts.createDiagnosticForNode(parameter, ts.isBindingPattern(parameter.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided + : ts.isRestParameter(parameter) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided + : ts.Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : !ts.isBindingPattern(parameter.name) ? ts.idText(ts.getFirstIdentifier(parameter.name)) : undefined); + return ts.addRelatedInfo(diagnostic, parameterError); } + return diagnostic; } else { - spanArray = ts.factory.createNodeArray(args.slice(max)); - } - var pos = ts.first(spanArray).pos; - var end = ts.last(spanArray).end; - if (end === pos) { - end++; + // too long; error goes on the excess parameters + var errorSpan = ts.factory.createNodeArray(args.slice(max)); + var pos = ts.first(errorSpan).pos; + var end = ts.last(errorSpan).end; + if (end === pos) { + end++; + } + ts.setTextRangePosEnd(errorSpan, pos, end); + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), errorSpan, error, parameterRange, args.length); } - ts.setTextRangePosEnd(spanArray, pos, end); - var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount); - return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var argCount = typeArguments.length; @@ -68876,8 +71034,8 @@ var ts; return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) { - var isTaggedTemplate = node.kind === 205 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 161 /* Decorator */; + var isTaggedTemplate = node.kind === 206 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 162 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var reportErrors = !candidatesOutArray && produceDiagnostics; var typeArguments; @@ -68939,7 +71097,7 @@ var ts; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 203 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 204 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -68993,7 +71151,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_21 = function (c) { + var _loop_22 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2); if (diags_2) { @@ -69011,7 +71169,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_21(c); + _loop_22(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); @@ -69169,7 +71327,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_22 = function (i) { + var _loop_23 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -69177,7 +71335,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_22(i); + _loop_23(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* None */; @@ -69369,7 +71527,7 @@ var ts; function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have no common signatures. return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) || - !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & 1048576 /* Union */) && !(getReducedType(apparentFuncType).flags & 131072 /* Never */) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray, checkMode) { if (node.arguments && languageVersion < 1 /* ES5 */) { @@ -69484,7 +71642,7 @@ var ts; var declaration = signature.declaration; var modifiers = ts.getSelectedEffectiveModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */); // (1) Public constructors and (2) constructor functions are always accessible. - if (!modifiers || declaration.kind !== 166 /* Constructor */) { + if (!modifiers || declaration.kind !== 167 /* Constructor */) { return true; } var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol); @@ -69628,16 +71786,16 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 160 /* Parameter */: + case 161 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; default: return ts.Debug.fail(); @@ -69732,16 +71890,16 @@ var ts; } function resolveSignature(node, candidatesOutArray, checkMode) { switch (node.kind) { - case 203 /* CallExpression */: + case 204 /* CallExpression */: return resolveCallExpression(node, candidatesOutArray, checkMode); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return resolveNewExpression(node, candidatesOutArray, checkMode); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode); - case 161 /* Decorator */: + case 162 /* Decorator */: return resolveDecorator(node, candidatesOutArray, checkMode); - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode); } throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); @@ -69873,7 +72031,7 @@ var ts; return false; } var parent = node.parent; - while (parent && parent.kind === 201 /* PropertyAccessExpression */) { + while (parent && parent.kind === 202 /* PropertyAccessExpression */) { parent = parent.parent; } if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 62 /* EqualsToken */) { @@ -69900,12 +72058,12 @@ var ts; if (node.expression.kind === 105 /* SuperKeyword */) { return voidType; } - if (node.kind === 204 /* NewExpression */) { + if (node.kind === 205 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 166 /* Constructor */ && - declaration.kind !== 170 /* ConstructSignature */ && - declaration.kind !== 175 /* ConstructorType */ && + declaration.kind !== 167 /* Constructor */ && + declaration.kind !== 171 /* ConstructSignature */ && + declaration.kind !== 176 /* ConstructorType */ && !ts.isJSDocConstructSignature(declaration) && !isJSConstructor(declaration)) { // When resolved signature is a call signature (and not a construct signature) the result type is any @@ -69925,7 +72083,7 @@ var ts; if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } - if (node.kind === 203 /* CallExpression */ && node.parent.kind === 233 /* ExpressionStatement */ && + if (node.kind === 204 /* CallExpression */ && !node.questionDotToken && node.parent.kind === 234 /* ExpressionStatement */ && returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) { if (!ts.isDottedName(node.expression)) { error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name); @@ -69939,7 +72097,7 @@ var ts; var jsSymbol = getSymbolOfExpando(node, /*allowDeclaration*/ false); if ((_a = jsSymbol === null || jsSymbol === void 0 ? void 0 : jsSymbol.exports) === null || _a === void 0 ? void 0 : _a.size) { var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined); - jsAssignmentType.objectFlags |= 16384 /* JSLiteral */; + jsAssignmentType.objectFlags |= 8192 /* JSLiteral */; return getIntersectionType([returnType, jsAssignmentType]); } } @@ -69948,26 +72106,27 @@ var ts; function checkDeprecatedSignature(signature, node) { if (signature.declaration && signature.declaration.flags & 134217728 /* Deprecated */) { var suggestionNode = getDeprecatedSuggestionNode(node); - errorOrSuggestion(/*isError*/ false, suggestionNode, ts.Diagnostics._0_is_deprecated, signatureToString(signature)); + var name = ts.tryGetPropertyAccessOrIdentifierToString(ts.getInvokedExpression(node)); + addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature)); } } function getDeprecatedSuggestionNode(node) { node = ts.skipParentheses(node); switch (node.kind) { - case 203 /* CallExpression */: - case 161 /* Decorator */: - case 204 /* NewExpression */: + case 204 /* CallExpression */: + case 162 /* Decorator */: + case 205 /* NewExpression */: return getDeprecatedSuggestionNode(node.expression); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return getDeprecatedSuggestionNode(node.tag); - case 275 /* JsxOpeningElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 275 /* JsxSelfClosingElement */: return getDeprecatedSuggestionNode(node.tagName); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return node.argumentExpression; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return node.name; - case 173 /* TypeReference */: + case 174 /* TypeReference */: var typeReference = node; return ts.isQualifiedName(typeReference.typeName) ? typeReference.typeName.right : typeReference; default: @@ -70018,10 +72177,11 @@ var ts; return createPromiseReturnType(node, anyType); } function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { + var _a; if (allowSyntheticDefaultImports && type && type !== errorType) { var synthType = type; if (!synthType.syntheticType) { - var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var file = (_a = originalSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(ts.isSourceFile); var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); @@ -70059,9 +72219,9 @@ var ts; return false; } var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ - ? 251 /* FunctionDeclaration */ + ? 252 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ - ? 249 /* VariableDeclaration */ + ? 250 /* VariableDeclaration */ : 0 /* Unknown */; if (targetDeclarationKind !== 0 /* Unknown */) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); @@ -70091,19 +72251,19 @@ var ts; case 9 /* BigIntLiteral */: case 109 /* TrueKeyword */: case 94 /* FalseKeyword */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 218 /* TemplateExpression */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 219 /* TemplateExpression */: return true; - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return isValidConstAssertionArgument(node.expression); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: var op = node.operator; var arg = node.operand; return op === 40 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) || op === 39 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */; - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: var expr = node.expression; if (ts.isIdentifier(expr)) { var symbol = getSymbolAtLocation(expr); @@ -70159,7 +72319,7 @@ var ts; error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); return errorType; } - else if (container.kind === 166 /* Constructor */) { + else if (container.kind === 167 /* Constructor */) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -70206,7 +72366,7 @@ var ts; return restParameter.escapedName; } function isValidDeclarationForTupleLabel(d) { - return d.kind === 192 /* NamedTupleMember */ || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name)); + return d.kind === 193 /* NamedTupleMember */ || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name)); } function getNameableDeclarationAtPosition(signature, pos) { var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); @@ -70371,7 +72531,14 @@ var ts; } } function assignContextualParameterTypes(signature, context) { - signature.typeParameters = context.typeParameters; + if (context.typeParameters) { + if (!signature.typeParameters) { + signature.typeParameters = context.typeParameters; + } + else { + return; // This signature has already has a contextual inference performed and cached on it! + } + } if (context.thisParameter) { var parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { @@ -70482,7 +72649,7 @@ var ts; var yieldType; var nextType; var fallbackReturnType = voidType; - if (func.body.kind !== 230 /* Block */) { // Async or normal arrow function + if (func.body.kind !== 231 /* Block */) { // Async or normal arrow function returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */); if (isAsync) { // From within an async function you can return either a non-promise value or a promise. Any @@ -70667,7 +72834,7 @@ var ts; return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node)); } function computeExhaustiveSwitchStatement(node) { - if (node.expression.kind === 211 /* TypeOfExpression */) { + if (node.expression.kind === 212 /* TypeOfExpression */) { var operandType = getTypeOfExpression(node.expression.expression); var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); // notEqualFacts states that the type of the switched value is not equal to every type in the switch. @@ -70730,11 +72897,11 @@ var ts; } function mayReturnNever(func) { switch (func.kind) { - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return true; - case 165 /* MethodDeclaration */: - return func.parent.kind === 200 /* ObjectLiteralExpression */; + case 166 /* MethodDeclaration */: + return func.parent.kind === 201 /* ObjectLiteralExpression */; default: return false; } @@ -70760,21 +72927,21 @@ var ts; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (func.kind === 164 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 230 /* Block */ || !functionHasImplicitReturn(func)) { + if (func.kind === 165 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 231 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */; + var errorNode = ts.getEffectiveReturnTypeNode(func) || func; if (type && type.flags & 131072 /* Never */) { - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + error(errorNode, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (type && !hasExplicitReturn) { // minimal check: function has syntactic return type annotation and no explicit return statements in the body // this function does not conform to the specification. - // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present - error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + error(errorNode, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) { - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + error(errorNode, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); } else if (compilerOptions.noImplicitReturns) { if (!type) { @@ -70789,11 +72956,11 @@ var ts; return; } } - error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + error(errorNode, ts.Diagnostics.Not_all_code_paths_return_a_value); } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) { @@ -70809,7 +72976,7 @@ var ts; var returnType = getReturnTypeFromBody(node, checkMode); var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); - returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */; + returnOnlyType.objectFlags |= 524288 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; } } @@ -70817,7 +72984,7 @@ var ts; } // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 208 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 209 /* FunctionExpression */) { checkGrammarForGenerator(node); } contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -70863,7 +73030,7 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 166 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnType = getReturnTypeFromAnnotation(node); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); @@ -70876,7 +73043,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 230 /* Block */) { + if (node.body.kind === 231 /* Block */) { checkSourceElement(node.body); } else { @@ -70966,7 +73133,7 @@ var ts; expr.expression.kind === 107 /* ThisKeyword */) { // Look for if this is the constructor for the class that `symbol` is a property of. var ctor = ts.getContainingFunction(expr); - if (!(ctor && (ctor.kind === 166 /* Constructor */ || isJSConstructor(ctor)))) { + if (!(ctor && (ctor.kind === 167 /* Constructor */ || isJSConstructor(ctor)))) { return true; } if (symbol.valueDeclaration) { @@ -70991,7 +73158,7 @@ var ts; var symbol_2 = getNodeLinks(node).resolvedSymbol; if (symbol_2.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol_2); - return !!declaration && declaration.kind === 263 /* NamespaceImport */; + return !!declaration && declaration.kind === 264 /* NamespaceImport */; } } } @@ -71072,7 +73239,7 @@ var ts; var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); var func = ts.getContainingFunction(node); - if (func && func.kind !== 166 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { + if (func && func.kind !== 167 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); ts.addRelatedInfo(diagnostic, relatedInfo); } @@ -71239,14 +73406,33 @@ var ts; rightType = checkNonNullType(rightType, right); // TypeScript 1.0 spec (April 2014): 4.15.5 // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, - // and the right operand to be of type Any, an object type, or a type parameter type. + // and the right operand to be + // + // 1. assignable to the non-primitive type, + // 2. an unconstrained type parameter, + // 3. a union or intersection including one or more type parameters, whose constituents are all assignable to the + // the non-primitive type, or are unconstrainted type parameters, or have constraints assignable to the + // non-primitive type, or + // 4. a type parameter whose constraint is + // i. an object type, + // ii. the non-primitive type, or + // iii. a union or intersection with at least one constituent assignable to an object or non-primitive type. + // + // The divergent behavior for type parameters and unions containing type parameters is a workaround for type + // parameters not being narrowable. If the right operand is a concrete type, we can error if there is any chance + // it is a primitive. But if the operand is a type parameter, it cannot be narrowed, so we don't issue an error + // unless *all* instantiations would result in an error. + // // The result is always of the Boolean primitive type. if (!(allTypesAssignableToKind(leftType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) || isTypeAssignableToKind(leftType, 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */ | 262144 /* TypeParameter */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { - error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + var rightTypeConstraint = getConstraintOfType(rightType); + if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */) || + rightTypeConstraint && (isTypeAssignableToKind(rightType, 3145728 /* UnionOrIntersection */) && !allTypesAssignableToKind(rightTypeConstraint, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */) || + !maybeTypeOfKind(rightTypeConstraint, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */))) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_not_be_a_primitive); } return booleanType; } @@ -71265,7 +73451,7 @@ var ts; if (rightIsThis === void 0) { rightIsThis = false; } var properties = node.properties; var property = properties[propertyIndex]; - if (property.kind === 288 /* PropertyAssignment */ || property.kind === 289 /* ShorthandPropertyAssignment */) { + if (property.kind === 289 /* PropertyAssignment */ || property.kind === 290 /* ShorthandPropertyAssignment */) { var name = property.name; var exprType = getLiteralTypeFromPropertyName(name); if (isTypeUsableAsPropertyName(exprType)) { @@ -71273,14 +73459,14 @@ var ts; var prop = getPropertyOfType(objectLiteralType, text); if (prop) { markPropertyAsReferenced(prop, property, rightIsThis); - checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + checkPropertyAccessibility(property, /*isSuper*/ false, /*writing*/ true, objectLiteralType, prop); } } var elementType = getIndexedAccessType(objectLiteralType, exprType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */); var type = getFlowTypeOfDestructuring(property, elementType); - return checkDestructuringAssignment(property.kind === 289 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); + return checkDestructuringAssignment(property.kind === 290 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } - else if (property.kind === 290 /* SpreadAssignment */) { + else if (property.kind === 291 /* SpreadAssignment */) { if (propertyIndex < properties.length - 1) { error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } @@ -71318,7 +73504,7 @@ var ts; var inBoundsType = compilerOptions.noUncheckedIndexedAccess ? undefined : possiblyOutOfBoundsType; for (var i = 0; i < elements.length; i++) { var type = possiblyOutOfBoundsType; - if (node.elements[i].kind === 220 /* SpreadElement */) { + if (node.elements[i].kind === 221 /* SpreadElement */) { type = inBoundsType = inBoundsType !== null && inBoundsType !== void 0 ? inBoundsType : (checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType); } checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, type, checkMode); @@ -71328,8 +73514,8 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 222 /* OmittedExpression */) { - if (element.kind !== 220 /* SpreadElement */) { + if (element.kind !== 223 /* OmittedExpression */) { + if (element.kind !== 221 /* SpreadElement */) { var indexType = getLiteralType(elementIndex); if (isArrayLikeType(sourceType)) { // We create a synthetic expression so that getIndexedAccessType doesn't get confused @@ -71347,7 +73533,7 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 216 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) { + if (restExpression.kind === 217 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -71363,7 +73549,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) { var target; - if (exprOrAssignment.kind === 289 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 290 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove @@ -71379,24 +73565,24 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 216 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) { + if (target.kind === 217 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 200 /* ObjectLiteralExpression */) { + if (target.kind === 201 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } - if (target.kind === 199 /* ArrayLiteralExpression */) { + if (target.kind === 200 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 290 /* SpreadAssignment */ ? + var error = target.parent.kind === 291 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; - var optionalError = target.parent.kind === 290 /* SpreadAssignment */ ? + var optionalError = target.parent.kind === 291 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access; if (checkReferenceExpression(target, error, optionalError)) { @@ -71421,8 +73607,8 @@ var ts; case 78 /* Identifier */: case 10 /* StringLiteral */: case 13 /* RegularExpressionLiteral */: - case 205 /* TaggedTemplateExpression */: - case 218 /* TemplateExpression */: + case 206 /* TaggedTemplateExpression */: + case 219 /* TemplateExpression */: case 14 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: case 9 /* BigIntLiteral */: @@ -71430,27 +73616,27 @@ var ts; case 94 /* FalseKeyword */: case 103 /* NullKeyword */: case 150 /* UndefinedKeyword */: - case 208 /* FunctionExpression */: - case 221 /* ClassExpression */: - case 209 /* ArrowFunction */: - case 199 /* ArrayLiteralExpression */: - case 200 /* ObjectLiteralExpression */: - case 211 /* TypeOfExpression */: - case 225 /* NonNullExpression */: - case 274 /* JsxSelfClosingElement */: - case 273 /* JsxElement */: + case 209 /* FunctionExpression */: + case 222 /* ClassExpression */: + case 210 /* ArrowFunction */: + case 200 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 212 /* TypeOfExpression */: + case 226 /* NonNullExpression */: + case 275 /* JsxSelfClosingElement */: + case 274 /* JsxElement */: return true; - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: // Unary operators ~, !, +, and - have no side effects. // The rest do. switch (node.operator) { @@ -71462,9 +73648,9 @@ var ts; } return false; // Some forms listed here for clarity - case 212 /* VoidExpression */: // Explicit opt-out - case 206 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 224 /* AsExpression */: // Not SEF, but can produce useful type warnings + case 213 /* VoidExpression */: // Explicit opt-out + case 207 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 225 /* AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } @@ -71472,84 +73658,111 @@ var ts; function isTypeEqualityComparableTo(source, target) { return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } - var CheckBinaryExpressionState; - (function (CheckBinaryExpressionState) { - CheckBinaryExpressionState[CheckBinaryExpressionState["MaybeCheckLeft"] = 0] = "MaybeCheckLeft"; - CheckBinaryExpressionState[CheckBinaryExpressionState["CheckRight"] = 1] = "CheckRight"; - CheckBinaryExpressionState[CheckBinaryExpressionState["FinishCheck"] = 2] = "FinishCheck"; - })(CheckBinaryExpressionState || (CheckBinaryExpressionState = {})); - function checkBinaryExpression(node, checkMode) { - var workStacks = { - expr: [node], - state: [0 /* MaybeCheckLeft */], - leftType: [undefined] + function createCheckBinaryExpression() { + var trampoline = ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState); + return function (node, checkMode) { + var result = trampoline(node, checkMode); + ts.Debug.assertIsDefined(result); + return result; }; - var stackIndex = 0; - var lastResult; - while (stackIndex >= 0) { - node = workStacks.expr[stackIndex]; - switch (workStacks.state[stackIndex]) { - case 0 /* MaybeCheckLeft */: { - if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { - finishInvocation(checkExpression(node.right, checkMode)); - break; - } - checkGrammarNullishCoalesceWithLogicalExpression(node); - var operator = node.operatorToken.kind; - if (operator === 62 /* EqualsToken */ && (node.left.kind === 200 /* ObjectLiteralExpression */ || node.left.kind === 199 /* ArrayLiteralExpression */)) { - finishInvocation(checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 107 /* ThisKeyword */)); - break; - } - advanceState(1 /* CheckRight */); - maybeCheckExpression(node.left); - break; - } - case 1 /* CheckRight */: { - var leftType = lastResult; - workStacks.leftType[stackIndex] = leftType; - var operator = node.operatorToken.kind; - if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) { - if (operator === 55 /* AmpersandAmpersandToken */) { - var parent = ts.walkUpParenthesizedExpressions(node.parent); - checkTestingKnownTruthyCallableType(node.left, leftType, ts.isIfStatement(parent) ? parent.thenStatement : undefined); - } - checkTruthinessOfType(leftType, node.left); + function onEnter(node, state, checkMode) { + if (state) { + state.stackIndex++; + state.skip = false; + setLeftType(state, /*type*/ undefined); + setLastResult(state, /*type*/ undefined); + } + else { + state = { + checkMode: checkMode, + skip: false, + stackIndex: 0, + typeStack: [undefined, undefined], + }; + } + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { + state.skip = true; + setLastResult(state, checkExpression(node.right, checkMode)); + return state; + } + checkGrammarNullishCoalesceWithLogicalExpression(node); + var operator = node.operatorToken.kind; + if (operator === 62 /* EqualsToken */ && (node.left.kind === 201 /* ObjectLiteralExpression */ || node.left.kind === 200 /* ArrayLiteralExpression */)) { + state.skip = true; + setLastResult(state, checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 107 /* ThisKeyword */)); + return state; + } + return state; + } + function onLeft(left, state, _node) { + if (!state.skip) { + return maybeCheckExpression(state, left); + } + } + function onOperator(operatorToken, state, node) { + if (!state.skip) { + var leftType = getLastResult(state); + ts.Debug.assertIsDefined(leftType); + setLeftType(state, leftType); + setLastResult(state, /*type*/ undefined); + var operator = operatorToken.kind; + if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) { + if (operator === 55 /* AmpersandAmpersandToken */) { + var parent = ts.walkUpParenthesizedExpressions(node.parent); + checkTestingKnownTruthyCallableOrAwaitableType(node.left, leftType, ts.isIfStatement(parent) ? parent.thenStatement : undefined); } - advanceState(2 /* FinishCheck */); - maybeCheckExpression(node.right); - break; + checkTruthinessOfType(leftType, node.left); } - case 2 /* FinishCheck */: { - var leftType = workStacks.leftType[stackIndex]; - var rightType = lastResult; - finishInvocation(checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node)); - break; - } - default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for checkBinaryExpression"); } } - return lastResult; - function finishInvocation(result) { - lastResult = result; - stackIndex--; - } - /** - * Note that `advanceState` sets the _current_ head state, and that `maybeCheckExpression` potentially pushes on a new - * head state; so `advanceState` must be called before any `maybeCheckExpression` during a state's execution. - */ - function advanceState(nextState) { - workStacks.state[stackIndex] = nextState; + function onRight(right, state, _node) { + if (!state.skip) { + return maybeCheckExpression(state, right); + } } - function maybeCheckExpression(node) { - if (ts.isBinaryExpression(node)) { - stackIndex++; - workStacks.expr[stackIndex] = node; - workStacks.state[stackIndex] = 0 /* MaybeCheckLeft */; - workStacks.leftType[stackIndex] = undefined; + function onExit(node, state) { + var result; + if (state.skip) { + result = getLastResult(state); } else { - lastResult = checkExpression(node, checkMode); + var leftType = getLeftType(state); + ts.Debug.assertIsDefined(leftType); + var rightType = getLastResult(state); + ts.Debug.assertIsDefined(rightType); + result = checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node); + } + state.skip = false; + setLeftType(state, /*type*/ undefined); + setLastResult(state, /*type*/ undefined); + state.stackIndex--; + return result; + } + function foldState(state, result, _side) { + setLastResult(state, result); + return state; + } + function maybeCheckExpression(state, node) { + if (ts.isBinaryExpression(node)) { + return node; } + setLastResult(state, checkExpression(node, state.checkMode)); + } + function getLeftType(state) { + return state.typeStack[state.stackIndex]; + } + function setLeftType(state, type) { + state.typeStack[state.stackIndex] = type; + } + function getLastResult(state) { + return state.typeStack[state.stackIndex + 1]; + } + function setLastResult(state, type) { + // To reduce overhead, reuse the next stack entry to store the + // last result. This avoids the overhead of an additional property + // on `WorkArea` and reuses empty stack entries as we walk back up + // the stack. + state.typeStack[state.stackIndex + 1] = type; } } function checkGrammarNullishCoalesceWithLogicalExpression(node) { @@ -71567,7 +73780,7 @@ var ts; // expression-wide checks and does not use a work stack to fold nested binary expressions into the same callstack frame function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 62 /* EqualsToken */ && (left.kind === 200 /* ObjectLiteralExpression */ || left.kind === 199 /* ArrayLiteralExpression */)) { + if (operator === 62 /* EqualsToken */ && (left.kind === 201 /* ObjectLiteralExpression */ || left.kind === 200 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 107 /* ThisKeyword */); } var leftType; @@ -71802,7 +74015,7 @@ var ts; if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false); - if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { + if ((symbol === null || symbol === void 0 ? void 0 : symbol.declarations) && symbol.declarations.some(ts.isJSDocTypedefTag)) { addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop); addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol); } @@ -71997,7 +74210,7 @@ var ts; } function checkConditionalExpression(node, checkMode) { var type = checkTruthinessExpression(node.condition); - checkTestingKnownTruthyCallableType(node.condition, type, node.whenTrue); + checkTestingKnownTruthyCallableOrAwaitableType(node.condition, type, node.whenTrue); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); return getUnionType([type1, type2], 2 /* Subtype */); @@ -72014,10 +74227,14 @@ var ts; texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return getFreshTypeOfLiteralType(getTemplateLiteralType(texts, types)); + return isConstContext(node) || someType(getContextualType(node) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; + } + function isTemplateLiteralContextualType(type) { + return !!(type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */) || + type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 402653316 /* StringLike */)); } function getContextNode(node) { - if (node.kind === 281 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { + if (node.kind === 282 /* 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; @@ -72033,7 +74250,7 @@ var ts; // We strip literal freshness when an appropriate contextual type is present such that contextually typed // literals always preserve their literal types (otherwise they might widen during type inference). An alternative // here would be to not mark contextually typed literals as fresh in the first place. - var result = maybeTypeOfKind(type, 134220672 /* FreshableLiteral */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? getRegularTypeOfLiteralType(type) : type; return result; } @@ -72066,13 +74283,13 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 206 /* TypeAssertionExpression */ || node.kind === 224 /* AsExpression */; + return node.kind === 207 /* TypeAssertionExpression */ || node.kind === 225 /* AsExpression */; } function checkDeclarationInitializer(declaration, contextualType) { var initializer = ts.getEffectiveInitializer(declaration); var type = getQuickTypeOfExpression(initializer) || (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer)); - return ts.isParameter(declaration) && declaration.name.kind === 197 /* ArrayBindingPattern */ && + return ts.isParameter(declaration) && declaration.name.kind === 198 /* ArrayBindingPattern */ && isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ? padTupleType(type, declaration.name) : type; } @@ -72082,7 +74299,7 @@ var ts; var elementFlags = type.target.elementFlags.slice(); for (var i = getTypeReferenceArity(type); i < patternElements.length; i++) { var e = patternElements[i]; - if (i < patternElements.length - 1 || !(e.kind === 198 /* BindingElement */ && e.dotDotDotToken)) { + if (i < patternElements.length - 1 || !(e.kind === 199 /* BindingElement */ && e.dotDotDotToken)) { elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType); elementFlags.push(2 /* Optional */); if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) { @@ -72117,7 +74334,7 @@ var ts; // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || unknownType; - return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || @@ -72125,7 +74342,7 @@ var ts; } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return !!(contextualType.flags & (134217856 /* StringLikeLiteral */ | 4194304 /* Index */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 134217856 /* StringLikeLiteral */) || + return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || @@ -72149,7 +74366,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); @@ -72160,7 +74377,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -72378,7 +74595,7 @@ var ts; } } function checkExpression(node, checkMode, forceTuple) { - ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -72388,7 +74605,7 @@ var ts; checkConstEnumAccess(node, type); } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return type; } function checkConstEnumAccess(node, type) { @@ -72396,11 +74613,11 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 202 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 78 /* Identifier */ || node.kind === 157 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || - (node.parent.kind === 176 /* TypeQuery */ && node.parent.exprName === node)) || - (node.parent.kind === 270 /* ExportSpecifier */); // We allow reexporting const enums + var ok = (node.parent.kind === 202 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 203 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 78 /* Identifier */ || node.kind === 158 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 177 /* TypeQuery */ && node.parent.exprName === node)) || + (node.parent.kind === 271 /* ExportSpecifier */); // We allow reexporting const enums if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } @@ -72425,15 +74642,15 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 221 /* ClassExpression */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 222 /* ClassExpression */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { case 78 /* Identifier */: - return checkIdentifier(node); + return checkIdentifier(node, checkMode); case 107 /* ThisKeyword */: return checkThisExpression(node); case 105 /* SuperKeyword */: @@ -72453,78 +74670,78 @@ var ts; return trueType; case 94 /* FalseKeyword */: return falseType; - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return checkTemplateExpression(node); case 13 /* RegularExpressionLiteral */: return globalRegExpType; - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return checkArrayLiteral(node, checkMode, forceTuple); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); - case 201 /* PropertyAccessExpression */: - return checkPropertyAccessExpression(node); - case 157 /* QualifiedName */: - return checkQualifiedName(node); - case 202 /* ElementAccessExpression */: - return checkIndexedAccess(node); - case 203 /* CallExpression */: + case 202 /* PropertyAccessExpression */: + return checkPropertyAccessExpression(node, checkMode); + case 158 /* QualifiedName */: + return checkQualifiedName(node, checkMode); + case 203 /* ElementAccessExpression */: + return checkIndexedAccess(node, checkMode); + case 204 /* CallExpression */: if (node.expression.kind === 99 /* ImportKeyword */) { return checkImportCallExpression(node); } // falls through - case 204 /* NewExpression */: + case 205 /* NewExpression */: return checkCallExpression(node, checkMode); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return checkParenthesizedExpression(node, checkMode); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return checkClassExpression(node); - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: return checkAssertion(node); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return checkNonNullAssertion(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return checkMetaProperty(node); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return checkDeleteExpression(node); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return checkVoidExpression(node); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return checkAwaitExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return checkBinaryExpression(node, checkMode); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return checkConditionalExpression(node, checkMode); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return checkSpreadExpression(node, checkMode); - case 222 /* OmittedExpression */: + case 223 /* OmittedExpression */: return undefinedWideningType; - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return checkYieldExpression(node); - case 227 /* SyntheticExpression */: + case 228 /* SyntheticExpression */: return checkSyntheticExpression(node); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return checkJsxExpression(node, checkMode); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return checkJsxElement(node, checkMode); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node, checkMode); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return checkJsxFragment(node); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return errorType; @@ -72560,11 +74777,11 @@ var ts; checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) { - if (!(func.kind === 166 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (ts.hasSyntacticModifier(node, 16476 /* ParameterPropertyModifier */)) { + if (!(func.kind === 167 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } - if (func.kind === 166 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") { + if (func.kind === 167 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") { error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name); } } @@ -72575,13 +74792,13 @@ var ts; if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 166 /* Constructor */ || func.kind === 170 /* ConstructSignature */ || func.kind === 175 /* ConstructorType */) { + if (func.kind === 167 /* Constructor */ || func.kind === 171 /* ConstructSignature */ || func.kind === 176 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } - if (func.kind === 209 /* ArrowFunction */) { + if (func.kind === 210 /* ArrowFunction */) { error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); } - if (func.kind === 167 /* GetAccessor */ || func.kind === 168 /* SetAccessor */) { + if (func.kind === 168 /* GetAccessor */ || func.kind === 169 /* SetAccessor */) { error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters); } } @@ -72639,13 +74856,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 209 /* ArrowFunction */: - case 169 /* CallSignature */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 174 /* FunctionType */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 210 /* ArrowFunction */: + case 170 /* CallSignature */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 175 /* FunctionType */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: var parent = node.parent; if (node === parent.type) { return parent; @@ -72663,7 +74880,7 @@ var ts; error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 197 /* ArrayBindingPattern */ || name.kind === 196 /* ObjectBindingPattern */) { + else if (name.kind === 198 /* ArrayBindingPattern */ || name.kind === 197 /* ObjectBindingPattern */) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -72672,13 +74889,13 @@ var ts; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 171 /* IndexSignature */) { + if (node.kind === 172 /* IndexSignature */) { checkGrammarIndexSignature(node); } // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled - else if (node.kind === 174 /* FunctionType */ || node.kind === 251 /* FunctionDeclaration */ || node.kind === 175 /* ConstructorType */ || - node.kind === 169 /* CallSignature */ || node.kind === 166 /* Constructor */ || - node.kind === 170 /* ConstructSignature */) { + else if (node.kind === 175 /* FunctionType */ || node.kind === 252 /* FunctionDeclaration */ || node.kind === 176 /* ConstructorType */ || + node.kind === 170 /* CallSignature */ || node.kind === 167 /* Constructor */ || + node.kind === 171 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); @@ -72708,10 +74925,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 169 /* CallSignature */: + case 170 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -72741,7 +74958,7 @@ var ts; checkAsyncFunctionReturnType(node, returnTypeNode); } } - if (node.kind !== 171 /* IndexSignature */ && node.kind !== 308 /* JSDocFunctionType */) { + if (node.kind !== 172 /* IndexSignature */ && node.kind !== 309 /* JSDocFunctionType */) { registerForUnusedIdentifiersCheck(node); } } @@ -72753,7 +74970,7 @@ var ts; var privateIdentifiers = new ts.Map(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 166 /* Constructor */) { + if (member.kind === 167 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) { @@ -72765,25 +74982,27 @@ var ts; var isStatic = ts.hasSyntacticModifier(member, 32 /* Static */); var name = member.name; if (!name) { - return; + continue; } - var names = ts.isPrivateIdentifier(name) ? privateIdentifiers : + var isPrivate = ts.isPrivateIdentifier(name); + var privateStaticFlags = isPrivate && isStatic ? 16 /* PrivateStatic */ : 0; + var names = isPrivate ? privateIdentifiers : isStatic ? staticNames : instanceNames; var memberName = name && ts.getPropertyNameForPropertyNameNode(name); if (memberName) { switch (member.kind) { - case 167 /* GetAccessor */: - addName(names, name, memberName, 1 /* GetAccessor */); + case 168 /* GetAccessor */: + addName(names, name, memberName, 1 /* GetAccessor */ | privateStaticFlags); break; - case 168 /* SetAccessor */: - addName(names, name, memberName, 2 /* SetAccessor */); + case 169 /* SetAccessor */: + addName(names, name, memberName, 2 /* SetAccessor */ | privateStaticFlags); break; - case 163 /* PropertyDeclaration */: - addName(names, name, memberName, 3 /* GetOrSetAccessor */); + case 164 /* PropertyDeclaration */: + addName(names, name, memberName, 3 /* GetOrSetAccessor */ | privateStaticFlags); break; - case 165 /* MethodDeclaration */: - addName(names, name, memberName, 8 /* Method */); + case 166 /* MethodDeclaration */: + addName(names, name, memberName, 8 /* Method */ | privateStaticFlags); break; } } @@ -72792,16 +75011,25 @@ var ts; function addName(names, location, name, meaning) { var prev = names.get(name); if (prev) { - if (prev & 8 /* Method */) { - if (meaning !== 8 /* Method */) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); - } - } - else if (prev & meaning) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + // For private identifiers, do not allow mixing of static and instance members with the same name + if ((prev & 16 /* PrivateStatic */) !== (meaning & 16 /* PrivateStatic */)) { + error(location, ts.Diagnostics.Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name, ts.getTextOfNode(location)); } else { - names.set(name, prev | meaning); + var prevIsMethod = !!(prev & 8 /* Method */); + var isMethod = !!(meaning & 8 /* Method */); + if (prevIsMethod || isMethod) { + if (prevIsMethod !== isMethod) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + // If this is a method/method duplication is might be an overload, so this will be handled when overloads are considered + } + else if (prev & meaning & ~16 /* PrivateStatic */) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names.set(name, prev | meaning); + } } } else { @@ -72845,7 +75073,7 @@ var ts; var names = new ts.Map(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 162 /* PropertySignature */) { + if (member.kind === 163 /* PropertySignature */) { var memberName = void 0; var name = member.name; switch (name.kind) { @@ -72870,11 +75098,11 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 253 /* InterfaceDeclaration */) { + if (node.kind === 254 /* InterfaceDeclaration */) { var nodeSymbol = getSymbolOfNode(node); // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration // to prevent this run check only for the first declaration of a given kind - if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + if (nodeSymbol.declarations && nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; } } @@ -72882,7 +75110,7 @@ var ts; // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); - if (indexSymbol) { + if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { var seenNumericIndexer = false; var seenStringIndexer = false; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { @@ -72916,11 +75144,9 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); - // Private class fields transformation relies on WeakMaps. - if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) { - for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) { - getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */; - } + setNodeLinksForPrivateIdentifierScope(node); + if (ts.isPrivateIdentifier(node.name) && ts.hasStaticModifier(node) && node.initializer && languageVersion === 99 /* ESNext */ && !compilerOptions.useDefineForClassFields) { + error(node.initializer, ts.Diagnostics.Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag); } } function checkPropertySignature(node) { @@ -72933,16 +75159,35 @@ var ts; // Grammar checking if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); - if (ts.isPrivateIdentifier(node.name)) { - error(node, ts.Diagnostics.A_method_cannot_be_named_with_a_private_identifier); - } // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration checkFunctionOrMethodDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (ts.hasSyntacticModifier(node, 128 /* Abstract */) && node.kind === 165 /* MethodDeclaration */ && node.body) { + if (ts.hasSyntacticModifier(node, 128 /* Abstract */) && node.kind === 166 /* MethodDeclaration */ && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } + // Private named methods are only allowed in class declarations + if (ts.isPrivateIdentifier(node.name) && !ts.getContainingClass(node)) { + error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + } + setNodeLinksForPrivateIdentifierScope(node); + } + function setNodeLinksForPrivateIdentifierScope(node) { + if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) { + for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) { + getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */; + } + // If this is a private element in a class expression inside the body of a loop, + // then we must use a block-scoped binding to store the additional variables required + // to transform private elements. + if (ts.isClassExpression(node.parent)) { + var enclosingIterationStatement = getEnclosingIterationStatement(node.parent); + if (enclosingIterationStatement) { + getNodeLinks(node.name).flags |= 524288 /* BlockScopedBindingInLoop */; + getNodeLinks(enclosingIterationStatement).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } + } + } } function checkConstructorDeclaration(node) { // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. @@ -72965,10 +75210,10 @@ var ts; return; } function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) { - if (ts.isPrivateIdentifierPropertyDeclaration(n)) { + if (ts.isPrivateIdentifierClassElementDeclaration(n)) { return true; } - return n.kind === 163 /* PropertyDeclaration */ && + return n.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(n, 32 /* Static */) && !!n.initializer; } @@ -72989,9 +75234,9 @@ var ts; // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) && + var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !useDefineForClassFields) && (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 92 /* ParameterPropertyModifier */); })); + ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */); })); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -72999,7 +75244,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) { var statement = statements_4[_i]; - if (statement.kind === 233 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 234 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -73024,7 +75269,7 @@ var ts; checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 167 /* GetAccessor */) { + if (node.kind === 168 /* GetAccessor */) { if (!(node.flags & 8388608 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 256 /* HasImplicitReturn */)) { if (!(node.flags & 512 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); @@ -73034,45 +75279,42 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } - if (ts.isPrivateIdentifier(node.name)) { - error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier); - } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. - var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; - var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); - if (otherAccessor) { - var nodeFlags = ts.getEffectiveModifierFlags(node); - var otherFlags = ts.getEffectiveModifierFlags(otherAccessor); - if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) { - error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + var symbol = getSymbolOfNode(node); + var getter = ts.getDeclarationOfKind(symbol, 168 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 169 /* SetAccessor */); + if (getter && setter && !(getNodeCheckFlags(getter) & 1 /* TypeChecked */)) { + getNodeLinks(getter).flags |= 1 /* TypeChecked */; + var getterFlags = ts.getEffectiveModifierFlags(getter); + var setterFlags = ts.getEffectiveModifierFlags(setter); + if ((getterFlags & 128 /* Abstract */) !== (setterFlags & 128 /* Abstract */)) { + error(getter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(setter.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } + if (((getterFlags & 16 /* Protected */) && !(setterFlags & (16 /* Protected */ | 8 /* Private */))) || + ((getterFlags & 8 /* Private */) && !(setterFlags & 8 /* Private */))) { + error(getter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(setter.name, ts.Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); } - if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) { - error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + var getterType = getAnnotatedAccessorType(getter); + var setterType = getAnnotatedAccessorType(setter); + if (getterType && setterType) { + checkTypeAssignableTo(getterType, setterType, getter, ts.Diagnostics.The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type); } - // TypeScript 1.0 spec (April 2014): 4.5 - // If both accessors include type annotations, the specified types must be identical. - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 167 /* GetAccessor */) { + if (node.kind === 168 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } checkSourceElement(node.body); - } - function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { - var firstType = getAnnotatedType(first); - var secondType = getAnnotatedType(second); - if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { - error(first, message); - } + setNodeLinksForPrivateIdentifierScope(node); } function checkMissingDeclaration(node) { checkDecorators(node); @@ -73109,7 +75351,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 173 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 174 /* 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); } ts.forEach(node.typeArguments, checkSourceElement); @@ -73124,7 +75366,7 @@ var ts; var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, getDeprecatedSuggestionNode(node), ts.Diagnostics._0_is_deprecated, symbol.escapedName); + addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 /* Enum */ && symbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); @@ -73162,7 +75404,7 @@ var ts; var hasNamedElement = ts.some(elementTypes, ts.isNamedTupleMember); for (var _i = 0, elementTypes_1 = elementTypes; _i < elementTypes_1.length; _i++) { var e = elementTypes_1[_i]; - if (e.kind !== 192 /* NamedTupleMember */ && hasNamedElement) { + if (e.kind !== 193 /* NamedTupleMember */ && hasNamedElement) { grammarErrorOnNode(e, ts.Diagnostics.Tuple_members_must_all_have_names_or_all_not_have_names); break; } @@ -73211,7 +75453,7 @@ var ts; var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { - if (accessNode.kind === 202 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + if (accessNode.kind === 203 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } @@ -73269,7 +75511,7 @@ var ts; ts.forEachChild(node, checkSourceElement); } function checkInferType(node) { - if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 184 /* ConditionalType */ && n.parent.extendsType === n; })) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 185 /* ConditionalType */ && n.parent.extendsType === n; })) { grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); @@ -73292,25 +75534,25 @@ var ts; if (node.dotDotDotToken && node.questionToken) { grammarErrorOnNode(node, ts.Diagnostics.A_tuple_member_cannot_be_both_optional_and_rest); } - if (node.type.kind === 180 /* OptionalType */) { + if (node.type.kind === 181 /* OptionalType */) { grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type); } - if (node.type.kind === 181 /* RestType */) { + if (node.type.kind === 182 /* RestType */) { grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type); } checkSourceElement(node.type); getTypeFromTypeNode(node); } function isPrivateWithinAmbient(node) { - return (ts.hasEffectiveModifier(node, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */); + return (ts.hasEffectiveModifier(node, 8 /* Private */) || ts.isPrivateIdentifierClassElementDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 253 /* InterfaceDeclaration */ && - n.parent.kind !== 252 /* ClassDeclaration */ && - n.parent.kind !== 221 /* ClassExpression */ && + if (n.parent.kind !== 254 /* InterfaceDeclaration */ && + n.parent.kind !== 253 /* ClassDeclaration */ && + n.parent.kind !== 222 /* ClassExpression */ && n.flags & 8388608 /* Ambient */) { if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { // It is nested in an ambient context, which means it is automatically exported @@ -73406,7 +75648,7 @@ var ts; // Both are literal property names that are the same. ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { - var reportError = (node.kind === 165 /* MethodDeclaration */ || node.kind === 164 /* MethodSignature */) && + var reportError = (node.kind === 166 /* MethodDeclaration */ || node.kind === 165 /* MethodSignature */) && ts.hasSyntacticModifier(node, 32 /* Static */) !== ts.hasSyntacticModifier(subsequentNode, 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members @@ -73443,55 +75685,57 @@ var ts; var multipleConstructorImplementation = false; var hasNonAmbientClass = false; var functionDeclarations = []; - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var current = declarations_4[_i]; - var node = current; - var inAmbientContext = node.flags & 8388608 /* Ambient */; - var inAmbientContextOrInterface = node.parent && (node.parent.kind === 253 /* InterfaceDeclaration */ || node.parent.kind === 177 /* TypeLiteral */) || inAmbientContext; - if (inAmbientContextOrInterface) { - // check if declarations are consecutive only if they are non-ambient - // 1. ambient declarations can be interleaved - // i.e. this is legal - // declare function foo(); - // declare function bar(); - // declare function foo(); - // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one - previousDeclaration = undefined; - } - if ((node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */) && !inAmbientContext) { - hasNonAmbientClass = true; - } - if (node.kind === 251 /* FunctionDeclaration */ || node.kind === 165 /* MethodDeclaration */ || node.kind === 164 /* MethodSignature */ || node.kind === 166 /* Constructor */) { - functionDeclarations.push(node); - var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); - someNodeFlags |= currentNodeFlags; - allNodeFlags &= currentNodeFlags; - someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); - allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); - var bodyIsPresent = ts.nodeIsPresent(node.body); - if (bodyIsPresent && bodyDeclaration) { - if (isConstructor) { - multipleConstructorImplementation = true; + if (declarations) { + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; + var node = current; + var inAmbientContext = node.flags & 8388608 /* Ambient */; + var inAmbientContextOrInterface = node.parent && (node.parent.kind === 254 /* InterfaceDeclaration */ || node.parent.kind === 178 /* TypeLiteral */) || inAmbientContext; + if (inAmbientContextOrInterface) { + // check if declarations are consecutive only if they are non-ambient + // 1. ambient declarations can be interleaved + // i.e. this is legal + // declare function foo(); + // declare function bar(); + // declare function foo(); + // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one + previousDeclaration = undefined; + } + if ((node.kind === 253 /* ClassDeclaration */ || node.kind === 222 /* ClassExpression */) && !inAmbientContext) { + hasNonAmbientClass = true; + } + if (node.kind === 252 /* FunctionDeclaration */ || node.kind === 166 /* MethodDeclaration */ || node.kind === 165 /* MethodSignature */ || node.kind === 167 /* Constructor */) { + functionDeclarations.push(node); + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); + var bodyIsPresent = ts.nodeIsPresent(node.body); + if (bodyIsPresent && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } + } + else if ((previousDeclaration === null || previousDeclaration === void 0 ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (bodyIsPresent) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } } else { - duplicateFunctionDeclaration = true; + hasOverloads = true; } - } - else if ((previousDeclaration === null || previousDeclaration === void 0 ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) { - reportImplementationExpectedError(previousDeclaration); - } - if (bodyIsPresent) { - if (!bodyDeclaration) { - bodyDeclaration = node; + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; } } - else { - hasOverloads = true; - } - previousDeclaration = node; - if (!inAmbientContextOrInterface) { - lastSeenNonAmbientDeclaration = node; - } } } if (multipleConstructorImplementation) { @@ -73519,8 +75763,10 @@ var ts; reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { - checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); - checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (declarations) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + } if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); @@ -73594,43 +75840,46 @@ var ts; function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: // A jsdoc typedef and callback are, by definition, type aliases. // falls through - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return 2 /* ExportType */; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4 /* ExportNamespace */ | 1 /* ExportValue */ : 4 /* ExportNamespace */; - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 291 /* EnumMember */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 292 /* EnumMember */: return 2 /* ExportType */ | 1 /* ExportValue */; - case 297 /* SourceFile */: + case 298 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: + case 217 /* BinaryExpression */: + var node_2 = d; + var expression = ts.isExportAssignment(node_2) ? node_2.expression : node_2.right; // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values - if (!ts.isEntityNameExpression(d.expression)) { + if (!ts.isEntityNameExpression(expression)) { return 1 /* ExportValue */; } - d = d.expression; + d = expression; // The below options all declare an Alias, which is allowed to merge with other values within the importing module. // falls through - case 260 /* ImportEqualsDeclaration */: - case 263 /* NamespaceImport */: - case 262 /* ImportClause */: - var result_12 = 0 /* None */; + case 261 /* ImportEqualsDeclaration */: + case 264 /* NamespaceImport */: + case 263 /* ImportClause */: + var result_13 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_12 |= getDeclarationSpaces(d); }); - return result_12; - case 249 /* VariableDeclaration */: - case 198 /* BindingElement */: - case 251 /* FunctionDeclaration */: - case 265 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + ts.forEach(target.declarations, function (d) { result_13 |= getDeclarationSpaces(d); }); + return result_13; + case 250 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 252 /* FunctionDeclaration */: + case 266 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 case 78 /* Identifier */: // https://github.com/microsoft/TypeScript/issues/36098 // Identifiers are used as declarations of assignment declarations whose parents may be // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});` @@ -73923,24 +76172,24 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 160 /* Parameter */: + case 161 /* Parameter */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: expectedReturnType = voidType; errorInfo = ts.chainDiagnosticMessages( /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -73987,15 +76236,15 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { - case 183 /* IntersectionType */: - case 182 /* UnionType */: + case 184 /* IntersectionType */: + case 183 /* UnionType */: return getEntityNameForDecoratorMetadataFromTypeList(node.types); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); - case 186 /* ParenthesizedType */: - case 192 /* NamedTupleMember */: + case 187 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: return getEntityNameForDecoratorMetadata(node.type); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return node.typeName; } } @@ -74004,13 +76253,13 @@ var ts; var commonEntityName; for (var _i = 0, types_23 = types; _i < types_23.length; _i++) { var typeNode = types_23[_i]; - while (typeNode.kind === 186 /* ParenthesizedType */ || typeNode.kind === 192 /* NamedTupleMember */) { + while (typeNode.kind === 187 /* ParenthesizedType */ || typeNode.kind === 193 /* NamedTupleMember */) { typeNode = typeNode.type; // Skip parens if need be } if (typeNode.kind === 141 /* NeverKeyword */) { continue; // Always elide `never` from the union/intersection if possible } - if (!strictNullChecks && (typeNode.kind === 191 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { + if (!strictNullChecks && (typeNode.kind === 192 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } var individualEntityName = getEntityNameForDecoratorMetadata(typeNode); @@ -74056,14 +76305,14 @@ var ts; } var firstDecorator = node.decorators[0]; checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); - if (node.kind === 160 /* Parameter */) { + if (node.kind === 161 /* Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* Param */); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -74072,23 +76321,23 @@ var ts; } } break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */; + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + var otherKind = node.kind === 168 /* GetAccessor */ ? 169 /* SetAccessor */ : 168 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 160 /* Parameter */: + case 161 /* Parameter */: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); var containingSignature = node.parent; for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { @@ -74151,7 +76400,7 @@ var ts; else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 157 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 158 /* QualifiedName */ ? node.name.right : node.name)); } } } @@ -74195,25 +76444,26 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return node.name; default: return undefined; } } function checkFunctionOrMethodDeclaration(node) { + var _a; checkDecorators(node); checkSignatureDeclaration(node); var functionFlags = ts.getFunctionFlags(node); // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name && node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 159 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); } - if (!hasNonBindableDynamicName(node)) { + if (hasBindableName(node)) { // first we want to check the local symbol that contain this declaration // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode @@ -74222,7 +76472,7 @@ var ts; // Since the javascript won't do semantic analysis like typescript, // if the javascript file comes before the typescript file and both contain same name functions, // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. - var firstDeclaration = ts.find(localSymbol.declarations, + var firstDeclaration = (_a = localSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find( // Get first non javascript function declaration function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072 /* JavaScriptFile */); }); // Only type check the symbol once @@ -74234,7 +76484,7 @@ var ts; checkFunctionOrConstructorSymbol(symbol); } } - var body = node.kind === 164 /* MethodSignature */ ? undefined : node.body; + var body = node.kind === 165 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node)); if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { @@ -74276,42 +76526,42 @@ var ts; for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { var node = potentiallyUnusedIdentifiers_1[_i]; switch (node.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: checkUnusedClassMembers(node, addDiagnostic); checkUnusedTypeParameters(node, addDiagnostic); break; - case 297 /* SourceFile */: - case 256 /* ModuleDeclaration */: - case 230 /* Block */: - case 258 /* CaseBlock */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 298 /* SourceFile */: + case 257 /* ModuleDeclaration */: + case 231 /* Block */: + case 259 /* CaseBlock */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: checkUnusedLocalsAndParameters(node, addDiagnostic); break; - case 166 /* Constructor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 167 /* Constructor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: if (node.body) { // Don't report unused parameters in overloads checkUnusedLocalsAndParameters(node, addDiagnostic); } checkUnusedTypeParameters(node, addDiagnostic); break; - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 254 /* TypeAliasDeclaration */: - case 253 /* InterfaceDeclaration */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 255 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: checkUnusedTypeParameters(node, addDiagnostic); break; - case 185 /* InferType */: + case 186 /* InferType */: checkUnusedInferTypeParameter(node, addDiagnostic); break; default: @@ -74331,11 +76581,11 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 165 /* MethodDeclaration */: - case 163 /* PropertyDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - if (member.kind === 168 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + case 166 /* MethodDeclaration */: + case 164 /* PropertyDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + if (member.kind === 169 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { // Already would have reported an error on the getter. break; } @@ -74346,7 +76596,7 @@ var ts; addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; - case 166 /* Constructor */: + case 167 /* Constructor */: for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasSyntacticModifier(parameter, 8 /* Private */)) { @@ -74354,8 +76604,8 @@ var ts; } } break; - case 171 /* IndexSignature */: - case 229 /* SemicolonClassElement */: + case 172 /* IndexSignature */: + case 230 /* SemicolonClassElement */: // Can't be private break; default: @@ -74372,7 +76622,8 @@ var ts; function checkUnusedTypeParameters(node, addDiagnostic) { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. - if (ts.last(getSymbolOfNode(node).declarations) !== node) + var declarations = getSymbolOfNode(node).declarations; + if (!declarations || ts.last(declarations) !== node) return; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); var seenParentsWithEveryUnused = new ts.Set(); @@ -74382,7 +76633,7 @@ var ts; continue; var name = ts.idText(typeParameter.name); var parent = typeParameter.parent; - if (parent.kind !== 185 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (parent.kind !== 186 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { if (ts.tryAddToSet(seenParentsWithEveryUnused, parent)) { var sourceFile = ts.getSourceFileOfNode(parent); var range = ts.isJSDocTemplateTag(parent) @@ -74418,11 +76669,15 @@ var ts; return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } function isValidUnusedLocalDeclaration(declaration) { - if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { - return !!ts.findAncestor(declaration.parent, function (ancestor) { - return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : - ts.isForOfStatement(ancestor) ? true : "quit"; - }); + if (ts.isBindingElement(declaration)) { + if (ts.isObjectBindingPattern(declaration.parent)) { + /** + * ignore starts with underscore names _ + * const { a: _a } = { a: 1 } + */ + return !!(declaration.propertyName && isIdentifierThatStartsWithUnderscore(declaration.name)); + } + return isIdentifierThatStartsWithUnderscore(declaration.name); } return ts.isAmbientModule(declaration) || (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); @@ -74438,39 +76693,41 @@ var ts; if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) { return; } - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (isValidUnusedLocalDeclaration(declaration)) { - continue; - } - if (isImportedDeclaration(declaration)) { - addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); - } - else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { - // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. - var lastElement = ts.last(declaration.parent.elements); - if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { - addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + if (local.declarations) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (isValidUnusedLocalDeclaration(declaration)) { + continue; } - } - else if (ts.isVariableDeclaration(declaration)) { - addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); - } - else { - var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); - var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); - if (parameter && name) { - if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { - if (ts.isBindingElement(declaration) && ts.isArrayBindingPattern(declaration.parent)) { - addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); - } - else { - addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); - } + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); } } + else if (ts.isVariableDeclaration(declaration)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } else { - errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); + if (parameter && name) { + if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { + if (ts.isBindingElement(declaration) && ts.isArrayBindingPattern(declaration.parent)) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + else { + addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); + } + } + } + else { + errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); + } } } } @@ -74480,7 +76737,7 @@ var ts; var importDecl = importClause.parent; var nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? - (importClause.namedBindings.kind === 263 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + (importClause.namedBindings.kind === 264 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 @@ -74498,7 +76755,7 @@ var ts; var bindingPattern = _a[0], bindingElements = _a[1]; var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; if (bindingPattern.elements.length === bindingElements.length) { - if (bindingElements.length === 1 && bindingPattern.parent.kind === 249 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 250 /* VariableDeclarationList */) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 250 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 251 /* VariableDeclarationList */) { addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { @@ -74519,7 +76776,7 @@ var ts; if (declarationList.declarations.length === declarations.length) { addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) - : ts.createDiagnosticForNode(declarationList.parent.kind === 232 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + : ts.createDiagnosticForNode(declarationList.parent.kind === 233 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); } else { for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { @@ -74533,22 +76790,22 @@ var ts; switch (name.kind) { case 78 /* Identifier */: return ts.idText(name); - case 197 /* ArrayBindingPattern */: - case 196 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); default: return ts.Debug.assertNever(name); } } function isImportedDeclaration(node) { - return node.kind === 262 /* ImportClause */ || node.kind === 265 /* ImportSpecifier */ || node.kind === 263 /* NamespaceImport */; + return node.kind === 263 /* ImportClause */ || node.kind === 266 /* ImportSpecifier */ || node.kind === 264 /* NamespaceImport */; } function importClauseFromImported(decl) { - return decl.kind === 262 /* ImportClause */ ? decl : decl.kind === 263 /* NamespaceImport */ ? decl.parent : decl.parent.parent; + return decl.kind === 263 /* ImportClause */ ? decl : decl.kind === 264 /* NamespaceImport */ ? decl.parent : decl.parent.parent; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 230 /* Block */) { + if (node.kind === 231 /* Block */) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -74578,12 +76835,12 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 163 /* PropertyDeclaration */ || - node.kind === 162 /* PropertySignature */ || - node.kind === 165 /* MethodDeclaration */ || - node.kind === 164 /* MethodSignature */ || - node.kind === 167 /* GetAccessor */ || - node.kind === 168 /* SetAccessor */) { + if (node.kind === 164 /* PropertyDeclaration */ || + node.kind === 163 /* PropertySignature */ || + node.kind === 166 /* MethodDeclaration */ || + node.kind === 165 /* MethodSignature */ || + node.kind === 168 /* GetAccessor */ || + node.kind === 169 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } @@ -74592,7 +76849,7 @@ var ts; return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 160 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 161 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -74629,10 +76886,11 @@ var ts; return false; }); } - function checkWeakMapCollision(node) { + function checkWeakMapSetCollision(node) { var enclosingBlockScope = ts.getEnclosingBlockScopeContainer(node); if (getNodeCheckFlags(enclosingBlockScope) & 67108864 /* ContainsClassWithPrivateIdentifiers */) { - errorSkippedOn("noEmit", node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, "WeakMap"); + ts.Debug.assert(ts.isNamedDeclaration(node) && ts.isIdentifier(node.name) && typeof node.name.escapedText === "string", "The target of a WeakMap/WeakSet collision check should be an identifier"); + errorSkippedOn("noEmit", node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, node.name.escapedText); } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { @@ -74649,7 +76907,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords errorSkippedOn("noEmit", name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -74664,7 +76922,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) { + if (parent.kind === 298 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. errorSkippedOn("noEmit", name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -74699,7 +76957,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 249 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 250 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -74711,17 +76969,17 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 250 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 232 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 251 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 233 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) var namesShareScope = container && - (container.kind === 230 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 257 /* ModuleBlock */ || - container.kind === 256 /* ModuleDeclaration */ || - container.kind === 297 /* SourceFile */); + (container.kind === 231 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 258 /* ModuleBlock */ || + container.kind === 257 /* ModuleDeclaration */ || + container.kind === 298 /* SourceFile */); // here we know that function scoped variable is shadowed by block scoped one // if they are defined in the same scope - binder has already reported redeclaration error // otherwise if variable has an initializer - show error that initialization will fail @@ -74752,18 +77010,18 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 158 /* ComputedPropertyName */) { + if (node.name.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 198 /* BindingElement */) { - if (node.parent.kind === 196 /* ObjectBindingPattern */ && languageVersion < 99 /* ESNext */) { + if (ts.isBindingElement(node)) { + if (ts.isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < 5 /* ES2018 */) { checkExternalEmitHelpers(node, 4 /* Rest */); } // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 158 /* ComputedPropertyName */) { + if (node.propertyName && node.propertyName.kind === 159 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } // check private/protected variable access @@ -74776,15 +77034,15 @@ var ts; var nameText = getPropertyNameFromType(exprType); var property = getPropertyOfType(parentType, nameText); if (property) { - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 105 /* SuperKeyword */, parentType, property); + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isSelfTypeAccess*/ false); // A destructuring is never a write-only reference. + checkPropertyAccessibility(node, !!parent.initializer && parent.initializer.kind === 105 /* SuperKeyword */, /*writing*/ false, parentType, property); } } } } // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 197 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + if (node.name.kind === 198 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } ts.forEach(node.name.elements, checkSourceElement); @@ -74796,7 +77054,7 @@ var ts; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { - var needCheckInitializer = node.initializer && node.parent.parent.kind !== 238 /* ForInStatement */; + var needCheckInitializer = node.initializer && node.parent.parent.kind !== 239 /* ForInStatement */; var needCheckWidenedType = node.name.elements.length === 0; if (needCheckInitializer || needCheckWidenedType) { // Don't validate for-in initializer as it is already an error @@ -74824,7 +77082,7 @@ var ts; } // For a commonjs `const x = require`, validate the alias and exit var symbol = getSymbolOfNode(node); - if (symbol.flags & 2097152 /* Alias */ && ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true)) { + if (symbol.flags & 2097152 /* Alias */ && ts.isRequireVariableDeclaration(node)) { checkAliasSymbol(node); return; } @@ -74838,11 +77096,11 @@ var ts; ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && !!((_a = symbol.exports) === null || _a === void 0 ? void 0 : _a.size); - if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 238 /* ForInStatement */) { + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 239 /* ForInStatement */) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); } } - if (symbol.declarations.length > 1) { + if (symbol.declarations && symbol.declarations.length > 1) { if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) { error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } @@ -74860,26 +77118,27 @@ var ts; if (node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } - if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 163 /* PropertyDeclaration */ && node.kind !== 162 /* PropertySignature */) { + if (node.kind !== 164 /* PropertyDeclaration */ && node.kind !== 163 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) { + if (node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - if (languageVersion < 99 /* ESNext */ && needCollisionCheckForIdentifier(node, node.name, "WeakMap")) { - potentialWeakMapCollisions.push(node); + if (languageVersion < 99 /* ESNext */ + && (needCollisionCheckForIdentifier(node, node.name, "WeakMap") || needCollisionCheckForIdentifier(node, node.name, "WeakSet"))) { + potentialWeakMapSetCollisions.push(node); } } } function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) { var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); - var message = nextDeclaration.kind === 163 /* PropertyDeclaration */ || nextDeclaration.kind === 162 /* PropertySignature */ + var message = nextDeclaration.kind === 164 /* PropertyDeclaration */ || nextDeclaration.kind === 163 /* PropertySignature */ ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; var declName = ts.declarationNameToString(nextDeclarationName); @@ -74889,8 +77148,8 @@ var ts; } } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 160 /* Parameter */ && right.kind === 249 /* VariableDeclaration */) || - (left.kind === 249 /* VariableDeclaration */ && right.kind === 160 /* Parameter */)) { + if ((left.kind === 161 /* Parameter */ && right.kind === 250 /* VariableDeclaration */) || + (left.kind === 250 /* VariableDeclaration */ && right.kind === 161 /* Parameter */)) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -74906,10 +77165,10 @@ var ts; return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { - ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); checkGrammarVariableDeclaration(node); checkVariableLikeDeclaration(node); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkBindingElement(node) { checkGrammarBindingElement(node); @@ -74930,49 +77189,55 @@ var ts; // Grammar checking checkGrammarStatementInAmbientContext(node); var type = checkTruthinessExpression(node.expression); - checkTestingKnownTruthyCallableType(node.expression, type, node.thenStatement); + checkTestingKnownTruthyCallableOrAwaitableType(node.expression, type, node.thenStatement); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 231 /* EmptyStatement */) { + if (node.thenStatement.kind === 232 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); } - function checkTestingKnownTruthyCallableType(condExpr, type, body) { - if (!strictNullChecks) { + function checkTestingKnownTruthyCallableOrAwaitableType(condExpr, type, body) { + if (!strictNullChecks) + return; + if (getFalsyFlags(type)) return; - } var location = ts.isBinaryExpression(condExpr) ? condExpr.right : condExpr; var testedNode = ts.isIdentifier(location) ? location : ts.isPropertyAccessExpression(location) ? location.name : ts.isBinaryExpression(location) && ts.isIdentifier(location.right) ? location.right : undefined; - if (!testedNode) { - return; - } - var possiblyFalsy = getFalsyFlags(type); - if (possiblyFalsy) { + var isPropertyExpressionCast = ts.isPropertyAccessExpression(location) + && ts.isAssertionExpression(ts.skipParentheses(location.expression)); + if (!testedNode || isPropertyExpressionCast) { return; } // While it technically should be invalid for any known-truthy value - // to be tested, we de-scope to functions unrefenced in the block as a - // heuristic to identify the most common bugs. There are too many - // false positives for values sourced from type definitions without - // strictNullChecks otherwise. + // to be tested, we de-scope to functions and Promises unreferenced in + // the block as a heuristic to identify the most common bugs. There + // are too many false positives for values sourced from type + // definitions without strictNullChecks otherwise. var callSignatures = getSignaturesOfType(type, 0 /* Call */); - if (callSignatures.length === 0) { + var isPromise = !!getAwaitedTypeOfPromise(type); + if (callSignatures.length === 0 && !isPromise) { return; } var testedSymbol = getSymbolAtLocation(testedNode); if (!testedSymbol) { return; } - var isUsed = ts.isBinaryExpression(condExpr.parent) && isFunctionUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) - || body && isFunctionUsedInConditionBody(condExpr, body, testedNode, testedSymbol); + var isUsed = ts.isBinaryExpression(condExpr.parent) && isSymbolUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) + || body && isSymbolUsedInConditionBody(condExpr, body, testedNode, testedSymbol); if (!isUsed) { - error(location, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead); + if (isPromise) { + errorAndMaybeSuggestAwait(location, + /*maybeMissingAwait*/ true, ts.Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, getTypeNameForErrorDisplay(type)); + } + else { + error(location, ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead); + } } } - function isFunctionUsedInConditionBody(expr, body, testedNode, testedSymbol) { + function isSymbolUsedInConditionBody(expr, body, testedNode, testedSymbol) { return !!ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); @@ -75009,7 +77274,7 @@ var ts; return ts.forEachChild(childNode, check); }); } - function isFunctionUsedInBinaryExpressionChain(node, testedSymbol) { + function isSymbolUsedInBinaryExpressionChain(node, testedSymbol) { while (ts.isBinaryExpression(node) && node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { var isUsed = ts.forEachChild(node.right, function visit(child) { if (ts.isIdentifier(child)) { @@ -75051,12 +77316,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 251 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer.kind === 251 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -75090,14 +77355,14 @@ var ts; // via checkRightHandSideOfForOf. // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. // Then check that the RHS is assignable to it. - if (node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer.kind === 251 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node); // There may be a destructuring assignment on the left side - if (varExpr.kind === 199 /* ArrayLiteralExpression */ || varExpr.kind === 200 /* ObjectLiteralExpression */) { + if (varExpr.kind === 200 /* ArrayLiteralExpression */ || varExpr.kind === 201 /* ObjectLiteralExpression */) { // iteratedType may be undefined. In this case, we still want to check the structure of // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like // to short circuit the type relation checking as much as possible, so we pass the unknownType. @@ -75129,7 +77394,7 @@ var ts; // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 250 /* VariableDeclarationList */) { + if (node.initializer.kind === 251 /* VariableDeclarationList */) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -75143,7 +77408,7 @@ var ts; // and Expr must be an expression of type Any, an object type, or a type parameter type. var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 199 /* ArrayLiteralExpression */ || varExpr.kind === 200 /* ObjectLiteralExpression */) { + if (varExpr.kind === 200 /* ArrayLiteralExpression */ || varExpr.kind === 201 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -75259,18 +77524,8 @@ var ts; // want to say that number is not an array type. But if the input was just // number and string input is allowed, we want to say that number is not an // array type or a string type. - var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined); - var _a = !(use & 4 /* AllowsStringInputFlag */) || hasStringConstituent - ? downlevelIteration - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] - : yieldType - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false] - : [ts.Diagnostics.Type_0_is_not_an_array_type, true] - : downlevelIteration - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] - : yieldType - ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false] - : [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true], defaultDiagnostic = _a[0], maybeMissingAwait = _a[1]; + var allowsStrings = !!(use & 4 /* AllowsStringInputFlag */) && !hasStringConstituent; + var _a = getIterationDiagnosticDetails(allowsStrings, downlevelIteration), defaultDiagnostic = _a[0], maybeMissingAwait = _a[1]; errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType)); } return hasStringConstituent ? possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType : undefined; @@ -75284,6 +77539,40 @@ var ts; return getUnionType(possibleOutOfBounds ? [arrayElementType, stringType, undefinedType] : [arrayElementType, stringType], 2 /* Subtype */); } return (use & 128 /* PossiblyOutOfBounds */) ? includeUndefinedInIndexSignature(arrayElementType) : arrayElementType; + function getIterationDiagnosticDetails(allowsStrings, downlevelIteration) { + var _a; + if (downlevelIteration) { + return allowsStrings + ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] + : [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]; + } + var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined); + if (yieldType) { + return [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]; + } + if (isES2015OrLaterIterable((_a = inputType.symbol) === null || _a === void 0 ? void 0 : _a.escapedName)) { + return [ts.Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, true]; + } + return allowsStrings + ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true] + : [ts.Diagnostics.Type_0_is_not_an_array_type, true]; + } + } + function isES2015OrLaterIterable(n) { + switch (n) { + case "Float32Array": + case "Float64Array": + case "Int16Array": + case "Int32Array": + case "Int8Array": + case "NodeList": + case "Uint16Array": + case "Uint32Array": + case "Uint8Array": + case "Uint8ClampedArray": + return true; + } + return false; } /** * Gets the requested "iteration type" from an `Iterable`-like or `AsyncIterable`-like type. @@ -75527,6 +77816,11 @@ var ts; return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType)); } } + function getPropertyNameForKnownSymbolName(symbolName) { + var ctorType = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false); + var uniqueType = ctorType && getTypeOfPropertyOfType(getTypeOfSymbol(ctorType), ts.escapeLeadingUnderscores(symbolName)); + return uniqueType && isTypeUsableAsPropertyName(uniqueType) ? getPropertyNameFromType(uniqueType) : "__@" + symbolName; + } /** * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like * type from its members. @@ -75539,7 +77833,7 @@ var ts; */ function getIterationTypesOfIterableSlow(type, resolver, errorNode) { var _a; - var method = getPropertyOfType(type, ts.getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); + var method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); var methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : undefined; if (isTypeAny(methodType)) { return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); @@ -75838,12 +78132,12 @@ var ts; var functionFlags = ts.getFunctionFlags(func); if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - if (func.kind === 168 /* SetAccessor */) { + if (func.kind === 169 /* SetAccessor */) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 166 /* Constructor */) { + else if (func.kind === 167 /* Constructor */) { if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } @@ -75861,7 +78155,7 @@ var ts; } } } - else if (func.kind !== 166 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + else if (func.kind !== 167 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { // The function has a return type, but the return statement doesn't have an expression. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -75890,7 +78184,7 @@ var ts; var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 285 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 286 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -75899,7 +78193,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 284 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 285 /* CaseClause */) { // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable // to or from the type of the 'switch' expression. @@ -75931,7 +78225,7 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 245 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + if (current.kind === 246 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } @@ -75961,10 +78255,11 @@ var ts; // Grammar checking if (catchClause.variableDeclaration) { var declaration = catchClause.variableDeclaration; - if (declaration.type) { + var typeNode = ts.getEffectiveTypeAnnotationNode(ts.getRootDeclaration(declaration)); + if (typeNode) { var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ false); if (type && !(type.flags & 3 /* AnyOrUnknown */)) { - grammarErrorOnFirstToken(declaration.type, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified); + grammarErrorOnFirstToken(typeNode, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified); } } else if (declaration.initializer) { @@ -75975,7 +78270,7 @@ var ts; if (blockLocals_1) { ts.forEachKey(catchClause.locals, function (caughtName) { var blockLocal = blockLocals_1.get(caughtName); - if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { + if ((blockLocal === null || blockLocal === void 0 ? void 0 : blockLocal.valueDeclaration) && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); } }); @@ -75988,25 +78283,28 @@ var ts; checkBlock(node.finallyBlock); } } - function checkIndexConstraints(type) { - var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); - var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); + function checkIndexConstraints(type, isStatic) { + var _a, _b, _c, _d; + var declaredNumberIndexer = getIndexDeclarationOfSymbolTable(isStatic ? (_a = type.symbol) === null || _a === void 0 ? void 0 : _a.exports : (_b = type.symbol) === null || _b === void 0 ? void 0 : _b.members, 1 /* Number */); + var declaredStringIndexer = getIndexDeclarationOfSymbolTable(isStatic ? (_c = type.symbol) === null || _c === void 0 ? void 0 : _c.exports : (_d = type.symbol) === null || _d === void 0 ? void 0 : _d.members, 0 /* String */); var stringIndexType = getIndexTypeOfType(type, 0 /* String */); var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); if (stringIndexType || numberIndexType) { ts.forEach(getPropertiesOfObjectType(type), function (prop) { + if (isStatic && prop.flags & 4194304 /* Prototype */) + return; var propType = getTypeOfSymbol(prop); checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); var classDeclaration = type.symbol.valueDeclaration; - if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) { - for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { - var member = _a[_i]; + if (ts.getObjectFlags(type) & 1 /* Class */ && classDeclaration && ts.isClassLike(classDeclaration)) { + for (var _i = 0, _e = classDeclaration.members; _i < _e.length; _i++) { + var member = _e[_i]; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!ts.hasSyntacticModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) { + if (!ts.hasSyntacticModifier(member, 32 /* Static */) && !hasBindableName(member)) { var symbol = getSymbolOfNode(member); var propType = getTypeOfSymbol(symbol); checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); @@ -76021,7 +78319,7 @@ var ts; // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) { var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); - errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + errorNode = someBaseTypeHasBothIndexers || !type.symbol.declarations ? undefined : type.symbol.declarations[0]; } } if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217 @@ -76045,8 +78343,8 @@ var ts; // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; if (propDeclaration && name && - (propDeclaration.kind === 216 /* BinaryExpression */ || - name.kind === 158 /* ComputedPropertyName */ || + (propDeclaration.kind === 217 /* BinaryExpression */ || + name.kind === 159 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } @@ -76058,7 +78356,7 @@ var ts; // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); - errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + errorNode = someBaseClassHasBothPropertyAndIndexer || !containingType.symbol.declarations ? undefined : containingType.symbol.declarations[0]; } if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { var errorMessage = indexKind === 0 /* String */ @@ -76074,6 +78372,7 @@ var ts; switch (name.escapedText) { case "any": case "unknown": + case "never": case "number": case "bigint": case "boolean": @@ -76123,7 +78422,7 @@ var ts; function checkTypeParametersNotReferenced(root, typeParameters, index) { visit(root); function visit(node) { - if (node.kind === 173 /* TypeReference */) { + if (node.kind === 174 /* TypeReference */) { var type = getTypeFromTypeReference(node); if (type.flags & 262144 /* TypeParameter */) { for (var i = index; i < typeParameters.length; i++) { @@ -76138,14 +78437,14 @@ var ts; } /** Check that type parameter lists are identical across multiple declarations */ function checkTypeParameterListsIdentical(symbol) { - if (symbol.declarations.length === 1) { + if (symbol.declarations && symbol.declarations.length === 1) { return; } var links = getSymbolLinks(symbol); if (!links.typeParametersChecked) { links.typeParametersChecked = true; var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); - if (declarations.length <= 1) { + if (!declarations || declarations.length <= 1) { return; } var type = getDeclaredTypeOfSymbol(symbol); @@ -76209,6 +78508,9 @@ var ts; registerForUnusedIdentifiersCheck(node); } function checkClassDeclaration(node) { + if (ts.some(node.decorators) && ts.some(node.members, function (p) { return ts.hasStaticModifier(p) && ts.isPrivateIdentifierClassElementDeclaration(p); })) { + grammarErrorOnNode(node.decorators[0], ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); + } if (!node.name && !ts.hasSyntacticModifier(node, 512 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } @@ -76237,7 +78539,8 @@ var ts; checkFunctionOrConstructorSymbol(symbol); checkClassForDuplicateDeclarations(node); // Only check for reserved static identifiers on non-ambient context. - if (!(node.flags & 8388608 /* Ambient */)) { + var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + if (!nodeInAmbientContext) { checkClassForStaticPropertyNameConflicts(node); } var baseTypeNode = ts.getEffectiveBaseTypeNode(node); @@ -76297,6 +78600,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } + checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { @@ -76326,14 +78630,76 @@ var ts; } if (produceDiagnostics) { checkIndexConstraints(type); + checkIndexConstraints(staticType, /*isStatic*/ true); checkTypeForDuplicateIndexSignatures(node); checkPropertyInitialization(node); } } + function checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType) { + var nodeInAmbientContext = !!(node.flags & 8388608 /* Ambient */); + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); + var baseTypes = baseTypeNode && getBaseTypes(type); + var baseWithThis = (baseTypes === null || baseTypes === void 0 ? void 0 : baseTypes.length) ? getTypeWithThisArgument(ts.first(baseTypes), type.thisType) : undefined; + var baseStaticType = getBaseConstructorTypeOfClass(type); + var _loop_24 = function (member) { + if (ts.hasAmbientModifier(member)) { + return "continue"; + } + if (ts.isConstructorDeclaration(member)) { + ts.forEach(member.parameters, function (param) { + if (ts.isParameterPropertyDeclaration(param, member)) { + checkClassMember(param, /*memberIsParameterProperty*/ true); + } + }); + } + checkClassMember(member); + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_24(member); + } + function checkClassMember(member, memberIsParameterProperty) { + var hasOverride = ts.hasOverrideModifier(member); + var hasStatic = ts.hasStaticModifier(member); + if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (!declaredProp) { + return; + } + var thisType = hasStatic ? staticType : typeWithThis; + var baseType = hasStatic ? baseStaticType : baseWithThis; + var prop = getPropertyOfType(thisType, declaredProp.escapedName); + var baseProp = getPropertyOfType(baseType, declaredProp.escapedName); + var baseClassName = typeToString(baseWithThis); + if (prop && !baseProp && hasOverride) { + error(member, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); + } + else if (prop && (baseProp === null || baseProp === void 0 ? void 0 : baseProp.valueDeclaration) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { + var baseHasAbstract = ts.hasAbstractModifier(baseProp.valueDeclaration); + if (hasOverride) { + return; + } + if (!baseHasAbstract) { + var diag = memberIsParameterProperty ? + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : + ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; + error(member, diag, baseClassName); + } + else if (ts.hasAbstractModifier(member) && baseHasAbstract) { + error(member, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); + } + } + } + else if (hasOverride) { + var className = typeToString(type); + error(member, ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, className); + } + } + } 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_23 = function (member) { + var _loop_25 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -76352,7 +78718,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_23(member); + _loop_25(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -76378,7 +78744,7 @@ var ts; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 252 /* ClassDeclaration */ || d.kind === 253 /* InterfaceDeclaration */; + return d.kind === 253 /* ClassDeclaration */ || d.kind === 254 /* InterfaceDeclaration */; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -76395,6 +78761,7 @@ var ts; // but not by other kinds of members. // Base class instance member variables and accessors can be overridden by // derived class instance member variables and accessors, but not by other kinds of members. + var _a, _b; // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfType(baseType); basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { @@ -76423,8 +78790,8 @@ var ts; // Searches other base types for a declaration that would satisfy the inherited abstract member. // (The class may have more than one base type via declaration merging with an interface with the // same name.) - for (var _a = 0, _b = getBaseTypes(type); _a < _b.length; _a++) { - var otherBaseType = _b[_a]; + for (var _c = 0, _d = getBaseTypes(type); _c < _d.length; _c++) { + var otherBaseType = _d[_c]; if (otherBaseType === baseType) continue; var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName); @@ -76433,7 +78800,7 @@ var ts; continue basePropertyCheck; } } - if (derivedClassDecl.kind === 221 /* ClassExpression */) { + if (derivedClassDecl.kind === 222 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -76454,7 +78821,7 @@ var ts; if (basePropertyFlags && derivedPropertyFlags) { // property/accessor is overridden with property/accessor if (baseDeclarationFlags & 128 /* Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer) - || base.valueDeclaration && base.valueDeclaration.parent.kind === 253 /* InterfaceDeclaration */ + || base.valueDeclaration && base.valueDeclaration.parent.kind === 254 /* InterfaceDeclaration */ || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) { // when the base property is abstract or from an interface, base/derived flags don't need to match // same when the derived property is from an assignment @@ -76468,13 +78835,13 @@ var ts; ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type)); } - else if (compilerOptions.useDefineForClassFields) { - var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 163 /* PropertyDeclaration */ && !d.initializer; }); + else if (useDefineForClassFields) { + var uninitialized = (_a = derived.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.kind === 164 /* PropertyDeclaration */ && !d.initializer; }); if (uninitialized && !(derived.flags & 33554432 /* Transient */) && !(baseDeclarationFlags & 128 /* Abstract */) && !(derivedDeclarationFlags & 128 /* Abstract */) - && !derived.declarations.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); })) { + && !((_b = derived.declarations) === null || _b === void 0 ? void 0 : _b.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); }))) { var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol)); var propName = uninitialized.name; if (uninitialized.exclamationToken @@ -76585,7 +78952,7 @@ var ts; } } function isInstancePropertyWithoutInitializer(node) { - return node.kind === 163 /* PropertyDeclaration */ && + return node.kind === 164 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(node, 32 /* Static */ | 128 /* Abstract */) && !node.exclamationToken && !node.initializer; @@ -76609,7 +78976,7 @@ var ts; var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 253 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 254 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -76728,7 +79095,7 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: var value_2 = evaluate(expr.operand); if (typeof value_2 === "number") { switch (expr.operator) { @@ -76738,7 +79105,7 @@ var ts; } } break; - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { @@ -76767,7 +79134,7 @@ var ts; case 8 /* NumericLiteral */: checkGrammarNumericLiteral(expr); return +expr.text; - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return evaluate(expr.expression); case 78 /* Identifier */: var identifier = expr; @@ -76775,14 +79142,14 @@ var ts; return +(identifier.escapedText); } return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); - case 202 /* ElementAccessExpression */: - case 201 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384 /* Enum */) { var name = void 0; - if (ex.kind === 201 /* PropertyAccessExpression */) { + if (ex.kind === 202 /* PropertyAccessExpression */) { name = ex.name.escapedText; } else { @@ -76800,7 +79167,7 @@ var ts; if (memberSymbol) { var declaration = memberSymbol.valueDeclaration; if (declaration !== member) { - if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + if (declaration && isBlockScopedNameDeclaredBeforeUse(declaration, member)) { return getEnumMemberValue(declaration); } error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); @@ -76815,8 +79182,8 @@ var ts; } function isConstantMemberAccess(node) { return node.kind === 78 /* Identifier */ || - node.kind === 201 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || - node.kind === 202 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.kind === 202 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 203 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && ts.isStringLiteralLike(node.argumentExpression); } function checkEnumDeclaration(node) { @@ -76840,7 +79207,7 @@ var ts; var enumSymbol = getSymbolOfNode(node); var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); if (node === firstDeclaration) { - if (enumSymbol.declarations.length > 1) { + if (enumSymbol.declarations && enumSymbol.declarations.length > 1) { var enumIsConst_1 = ts.isEnumConst(node); // check that const is placed\omitted on all enum declarations ts.forEach(enumSymbol.declarations, function (decl) { @@ -76852,7 +79219,7 @@ var ts; var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 255 /* EnumDeclaration */) { + if (declaration.kind !== 256 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -76878,12 +79245,14 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; - if ((declaration.kind === 252 /* ClassDeclaration */ || - (declaration.kind === 251 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && - !(declaration.flags & 8388608 /* Ambient */)) { - return declaration; + if (declarations) { + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 253 /* ClassDeclaration */ || + (declaration.kind === 252 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 8388608 /* Ambient */)) { + return declaration; + } } } return undefined; @@ -76931,8 +79300,9 @@ var ts; // The following checks only apply on a non-ambient instantiated module declaration. if (symbol.flags & 512 /* ValueModule */ && !inAmbientContext + && symbol.declarations && symbol.declarations.length > 1 - && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions))) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -76944,7 +79314,7 @@ var ts; } // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. - var mergedClass = ts.getDeclarationOfKind(symbol, 252 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 253 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -76993,40 +79363,41 @@ var ts; } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { + var _a; switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // error each individual name in variable statement instead of marking the entire variable statement - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; + for (var _i = 0, _b = node.declarationList.declarations; _i < _b.length; _i++) { + var decl = _b[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 266 /* ExportAssignment */: - case 267 /* ExportDeclaration */: + case 267 /* ExportAssignment */: + case 268 /* ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 260 /* ImportEqualsDeclaration */: - case 261 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 198 /* BindingElement */: - case 249 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 250 /* VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { - for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { - var el = _c[_b]; + for (var _c = 0, _d = name.elements; _c < _d.length; _c++) { + var el = _d[_c]; // mark individual names in binding pattern checkModuleAugmentationElement(el, isGlobalAugmentation); } break; } // falls through - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 251 /* FunctionDeclaration */: - case 253 /* InterfaceDeclaration */: - case 256 /* ModuleDeclaration */: - case 254 /* TypeAliasDeclaration */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 252 /* FunctionDeclaration */: + case 254 /* InterfaceDeclaration */: + case 257 /* ModuleDeclaration */: + case 255 /* TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } @@ -77039,7 +79410,7 @@ var ts; var reportError = !(symbol.flags & 33554432 /* Transient */); if (!reportError) { // symbol should not originate in augmentation - reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + reportError = !!((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.declarations) && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); } } break; @@ -77049,12 +79420,12 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return node; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: do { node = node.left; } while (node.kind !== 78 /* Identifier */); return node; - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: do { if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) { return node.name; @@ -77074,9 +79445,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 257 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 297 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 267 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 258 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 298 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 268 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -77096,6 +79467,7 @@ var ts; return true; } function checkAliasSymbol(node) { + var _a; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { @@ -77110,21 +79482,21 @@ var ts; (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 270 /* ExportSpecifier */ ? + var message = node.kind === 271 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules - && node.kind === 270 /* ExportSpecifier */ + && node.kind === 271 /* ExportSpecifier */ && !node.parent.parent.isTypeOnly && !(target.flags & 111551 /* Value */) && !(node.flags & 8388608 /* Ambient */)) { error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type); } - if (ts.isImportSpecifier(node) && ts.every(target.declarations, function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); })) { - errorOrSuggestion(/* isError */ false, node.name, ts.Diagnostics._0_is_deprecated, symbol.escapedName); + if (ts.isImportSpecifier(node) && ((_a = target.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); }))) { + addDeprecatedSuggestion(node.name, target.declarations, symbol.escapedName); } } } @@ -77132,7 +79504,7 @@ var ts; checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkAliasSymbol(node); - if (node.kind === 265 /* ImportSpecifier */ && + if (node.kind === 266 /* ImportSpecifier */ && ts.idText(node.propertyName || node.name) === "default" && compilerOptions.esModuleInterop && moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) { @@ -77154,7 +79526,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 263 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 264 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015 && compilerOptions.esModuleInterop) { // import * as ns from "foo"; @@ -77182,7 +79554,7 @@ var ts; if (ts.hasSyntacticModifier(node, 1 /* Export */)) { markExportAsReferenced(node); } - if (node.moduleReference.kind !== 272 /* ExternalModuleReference */) { + if (node.moduleReference.kind !== 273 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { if (target.flags & 111551 /* Value */) { @@ -77225,10 +79597,10 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 257 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 257 /* ModuleBlock */ && + var inAmbientExternalModule = node.parent.kind === 258 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 258 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 8388608 /* Ambient */; - if (node.parent.kind !== 297 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + if (node.parent.kind !== 298 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -77261,14 +79633,14 @@ var ts; } function checkGrammarExportDeclaration(node) { var _a; - var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 268 /* NamedExports */; + var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 269 /* NamedExports */; if (isTypeOnlyExportStar) { grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type); } return !isTypeOnlyExportStar; } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 297 /* SourceFile */ || node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 256 /* ModuleDeclaration */; + var isInAppropriateContext = node.parent.kind === 298 /* SourceFile */ || node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 257 /* ModuleDeclaration */; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -77318,7 +79690,7 @@ var ts; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { @@ -77339,12 +79711,15 @@ var ts; } } function checkExportAssignment(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + var illegalContextMessage = node.isExportEquals + ? ts.Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration + : ts.Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration; + if (checkGrammarModuleElementContext(node, illegalContextMessage)) { // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 297 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 256 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 298 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 257 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -77404,7 +79779,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { + if (declaration && !isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -77428,10 +79803,12 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + if (!isDuplicatedCommonJSExport(declarations)) { + for (var _i = 0, _b = declarations; _i < _b.length; _i++) { + var declaration = _b[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } } } } @@ -77440,6 +79817,11 @@ var ts; links.exportsChecked = true; } } + function isDuplicatedCommonJSExport(declarations) { + return declarations + && declarations.length > 1 + && declarations.every(function (d) { return ts.isInJSFile(d) && ts.isAccessExpression(d) && (ts.isExportsIdentifier(d.expression) || ts.isModuleExportsAccessExpression(d.expression)); }); + } function checkSourceElement(node) { if (node) { var saveCurrentNode = currentNode; @@ -77461,171 +79843,171 @@ var ts; // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 256 /* ModuleDeclaration */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 251 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 252 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } - if (kind >= 232 /* FirstStatement */ && kind <= 248 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) { + if (kind >= 233 /* FirstStatement */ && kind <= 249 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) { errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected); } switch (kind) { - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return checkTypeParameter(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return checkParameter(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return checkPropertyDeclaration(node); - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: return checkPropertySignature(node); - case 175 /* ConstructorType */: - case 174 /* FunctionType */: - case 169 /* CallSignature */: - case 170 /* ConstructSignature */: - case 171 /* IndexSignature */: + case 176 /* ConstructorType */: + case 175 /* FunctionType */: + case 170 /* CallSignature */: + case 171 /* ConstructSignature */: + case 172 /* IndexSignature */: return checkSignatureDeclaration(node); - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: return checkMethodDeclaration(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return checkConstructorDeclaration(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return checkAccessorDeclaration(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return checkTypeReferenceNode(node); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return checkTypePredicate(node); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return checkTypeQuery(node); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return checkTypeLiteral(node); - case 178 /* ArrayType */: + case 179 /* ArrayType */: return checkArrayType(node); - case 179 /* TupleType */: + case 180 /* TupleType */: return checkTupleType(node); - case 182 /* UnionType */: - case 183 /* IntersectionType */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 186 /* ParenthesizedType */: - case 180 /* OptionalType */: - case 181 /* RestType */: + case 187 /* ParenthesizedType */: + case 181 /* OptionalType */: + case 182 /* RestType */: return checkSourceElement(node.type); - case 187 /* ThisType */: + case 188 /* ThisType */: return checkThisType(node); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return checkTypeOperator(node); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return checkConditionalType(node); - case 185 /* InferType */: + case 186 /* InferType */: return checkInferType(node); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: return checkTemplateLiteralType(node); - case 195 /* ImportType */: + case 196 /* ImportType */: return checkImportType(node); - case 192 /* NamedTupleMember */: + case 193 /* NamedTupleMember */: return checkNamedTupleMember(node); - case 315 /* JSDocAugmentsTag */: + case 318 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 316 /* JSDocImplementsTag */: + case 319 /* JSDocImplementsTag */: return checkJSDocImplementsTag(node); - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return checkJSDocTypeAliasTag(node); - case 330 /* JSDocTemplateTag */: + case 334 /* JSDocTemplateTag */: return checkJSDocTemplateTag(node); - case 329 /* JSDocTypeTag */: + case 333 /* JSDocTypeTag */: return checkJSDocTypeTag(node); - case 326 /* JSDocParameterTag */: + case 330 /* JSDocParameterTag */: return checkJSDocParameterTag(node); - case 333 /* JSDocPropertyTag */: + case 337 /* JSDocPropertyTag */: return checkJSDocPropertyTag(node); - case 308 /* JSDocFunctionType */: + case 309 /* JSDocFunctionType */: checkJSDocFunctionType(node); // falls through - case 306 /* JSDocNonNullableType */: - case 305 /* JSDocNullableType */: - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: - case 312 /* JSDocTypeLiteral */: + case 307 /* JSDocNonNullableType */: + case 306 /* JSDocNullableType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: + case 314 /* JSDocTypeLiteral */: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 309 /* JSDocVariadicType */: + case 310 /* JSDocVariadicType */: checkJSDocVariadicType(node); return; - case 301 /* JSDocTypeExpression */: + case 302 /* JSDocTypeExpression */: return checkSourceElement(node.type); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return checkIndexedAccessType(node); - case 190 /* MappedType */: + case 191 /* MappedType */: return checkMappedType(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 230 /* Block */: - case 257 /* ModuleBlock */: + case 231 /* Block */: + case 258 /* ModuleBlock */: return checkBlock(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return checkVariableStatement(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return checkExpressionStatement(node); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return checkIfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return checkDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return checkWhileStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return checkForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return checkForInStatement(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return checkForOfStatement(node); - case 240 /* ContinueStatement */: - case 241 /* BreakStatement */: + case 241 /* ContinueStatement */: + case 242 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return checkReturnStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return checkWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return checkSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return checkLabeledStatement(node); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return checkThrowStatement(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return checkTryStatement(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return checkBindingElement(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return checkClassDeclaration(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return checkImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return checkExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return checkExportAssignment(node); - case 231 /* EmptyStatement */: - case 248 /* DebuggerStatement */: + case 232 /* EmptyStatement */: + case 249 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 271 /* MissingDeclaration */: + case 272 /* MissingDeclaration */: return checkMissingDeclaration(node); } } @@ -77670,7 +80052,8 @@ var ts; if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. var host_1 = ts.getHostSignatureFromJSDoc(paramTag); - if (host_1) { + var isCallbackTag = ts.isJSDocCallbackTag(paramTag.parent.parent); + if (host_1 || isCallbackTag) { /* Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. So in the following situation we will not create an array type: @@ -77678,7 +80061,9 @@ var ts; function f(a) {} Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. */ - var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters); + var lastParamDeclaration = isCallbackTag + ? ts.lastOrUndefined(paramTag.parent.parent.typeExpression.parameters) + : ts.lastOrUndefined(host_1.parameters); var symbol = ts.getParameterSymbolFromJSDoc(paramTag); if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) { @@ -77716,51 +80101,51 @@ var ts; } } function checkDeferredNode(node) { - ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; switch (node.kind) { - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 205 /* TaggedTemplateExpression */: - case 161 /* Decorator */: - case 275 /* JsxOpeningElement */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 206 /* TaggedTemplateExpression */: + case 162 /* Decorator */: + case 276 /* JsxOpeningElement */: // These node kinds are deferred checked when overload resolution fails // To save on work, we ensure the arguments are checked just once, in // a deferred way resolveUntypedCall(node); break; - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: checkAccessorDeclaration(node); break; - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: checkClassExpressionDeferred(node); break; - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: checkJsxSelfClosingElementDeferred(node); break; - case 273 /* JsxElement */: + case 274 /* JsxElement */: checkJsxElementDeferred(node); break; } currentNode = saveCurrentNode; - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function checkSourceFile(node) { - ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeCheck"); checkSourceFileWorker(node); ts.performance.mark("afterCheck"); ts.performance.measure("Check", "beforeCheck", "afterCheck"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function unusedIsError(kind, isAmbient) { if (isAmbient) { @@ -77789,7 +80174,7 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - ts.clear(potentialWeakMapCollisions); + ts.clear(potentialWeakMapSetCollisions); ts.forEach(node.statements, checkSourceElement); checkSourceElement(node.endOfFileToken); checkDeferredNodes(node); @@ -77819,9 +80204,9 @@ var ts; ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); ts.clear(potentialNewTargetCollisions); } - if (potentialWeakMapCollisions.length) { - ts.forEach(potentialWeakMapCollisions, checkWeakMapCollision); - ts.clear(potentialWeakMapCollisions); + if (potentialWeakMapSetCollisions.length) { + ts.forEach(potentialWeakMapSetCollisions, checkWeakMapSetCollision); + ts.clear(potentialWeakMapSetCollisions); } links.flags |= 1 /* TypeChecked */; } @@ -77893,17 +80278,17 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 297 /* SourceFile */: - if (!ts.isExternalOrCommonJsModule(location)) + case 298 /* SourceFile */: + if (!ts.isExternalModule(location)) break; // falls through - case 256 /* ModuleDeclaration */: - copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); + case 257 /* ModuleDeclaration */: + copyLocallyVisibleExportSymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); @@ -77911,8 +80296,8 @@ var ts; // this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration. // falls through - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: // If we didn't come from static member of class or interface, // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. @@ -77921,7 +80306,7 @@ var ts; copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968 /* Type */); } break; - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -77961,6 +80346,16 @@ var ts; }); } } + function copyLocallyVisibleExportSymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + // Similar condition as in `resolveNameHelper` + if (!ts.getDeclarationOfKind(symbol, 271 /* ExportSpecifier */) && !ts.getDeclarationOfKind(symbol, 270 /* NamespaceExport */)) { + copySymbol(symbol, meaning); + } + }); + } + } } function isTypeDeclarationName(name) { return name.kind === 78 /* Identifier */ && @@ -77969,19 +80364,19 @@ var ts; } function isTypeDeclaration(node) { switch (node.kind) { - case 159 /* TypeParameter */: - case 252 /* ClassDeclaration */: - case 253 /* InterfaceDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: - case 331 /* JSDocTypedefTag */: - case 324 /* JSDocCallbackTag */: - case 325 /* JSDocEnumTag */: + case 160 /* TypeParameter */: + case 253 /* ClassDeclaration */: + case 254 /* InterfaceDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 335 /* JSDocTypedefTag */: + case 328 /* JSDocCallbackTag */: + case 329 /* JSDocEnumTag */: return true; - case 262 /* ImportClause */: + case 263 /* ImportClause */: return node.isTypeOnly; - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return node.parent.parent.isTypeOnly; default: return false; @@ -77989,25 +80384,25 @@ var ts; } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(node) { - while (node.parent.kind === 157 /* QualifiedName */) { + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 173 /* TypeReference */; + return node.parent.kind === 174 /* TypeReference */; } function isHeritageClauseElementIdentifier(node) { - while (node.parent.kind === 201 /* PropertyAccessExpression */) { + while (node.parent.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 223 /* ExpressionWithTypeArguments */; + return node.parent.kind === 224 /* ExpressionWithTypeArguments */; } - function isJSDocEntryNameReference(node) { - while (node.parent.kind === 157 /* QualifiedName */) { + function getJSDocEntryNameReference(node) { + while (node.parent.kind === 158 /* QualifiedName */) { node = node.parent; } - while (node.parent.kind === 201 /* PropertyAccessExpression */) { + while (node.parent.kind === 202 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent.kind === 302 /* JSDocNameReference */; + return ts.isJSDocNameReference(node.parent) ? node.parent : undefined; } function forEachEnclosingClass(node, callback) { var result; @@ -78035,13 +80430,13 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 157 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 158 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 260 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 261 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } - if (nodeOnRightSide.parent.kind === 266 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 267 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; @@ -78067,7 +80462,7 @@ var ts; node = parent; parent = parent.parent; } - if (parent && parent.kind === 195 /* ImportType */ && parent.qualifier === node) { + if (parent && parent.kind === 196 /* ImportType */ && parent.qualifier === node) { return parent; } return undefined; @@ -78077,7 +80472,7 @@ var ts; return getSymbolOfNode(name.parent); } if (ts.isInJSFile(name) && - name.parent.kind === 201 /* PropertyAccessExpression */ && + name.parent.kind === 202 /* PropertyAccessExpression */ && name.parent === name.parent.parent.left) { // Check if this is a special property assignment if (!ts.isPrivateIdentifier(name)) { @@ -78087,7 +80482,7 @@ var ts; } } } - if (name.parent.kind === 266 /* ExportAssignment */ && ts.isEntityNameExpression(name)) { + if (name.parent.kind === 267 /* ExportAssignment */ && ts.isEntityNameExpression(name)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(name, /*all meanings*/ 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); @@ -78097,7 +80492,7 @@ var ts; } else if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name) && isInRightSideOfImportOrExportAssignment(name)) { // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(name, 260 /* ImportEqualsDeclaration */); + var importEqualsDeclaration = ts.getAncestor(name, 261 /* ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true); } @@ -78115,7 +80510,7 @@ var ts; if (isHeritageClauseElementIdentifier(name)) { var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. - if (name.parent.kind === 223 /* ExpressionWithTypeArguments */) { + if (name.parent.kind === 224 /* ExpressionWithTypeArguments */) { meaning = 788968 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) { @@ -78131,10 +80526,10 @@ var ts; return entityNameSymbol; } } - if (name.parent.kind === 326 /* JSDocParameterTag */) { + if (name.parent.kind === 330 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(name.parent); } - if (name.parent.kind === 159 /* TypeParameter */ && name.parent.parent.kind === 330 /* JSDocTemplateTag */) { + if (name.parent.kind === 160 /* TypeParameter */ && name.parent.parent.kind === 334 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(name.parent); return typeParameter && typeParameter.symbol; @@ -78151,36 +80546,56 @@ var ts; } return resolveEntityName(name, 111551 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (name.kind === 201 /* PropertyAccessExpression */ || name.kind === 157 /* QualifiedName */) { + else if (name.kind === 202 /* PropertyAccessExpression */ || name.kind === 158 /* QualifiedName */) { var links = getNodeLinks(name); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (name.kind === 201 /* PropertyAccessExpression */) { - checkPropertyAccessExpression(name); + if (name.kind === 202 /* PropertyAccessExpression */) { + checkPropertyAccessExpression(name, 0 /* Normal */); } else { - checkQualifiedName(name); + checkQualifiedName(name, 0 /* Normal */); } return links.resolvedSymbol; } } else if (isTypeReferenceIdentifier(name)) { - var meaning = name.parent.kind === 173 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */; + var meaning = name.parent.kind === 174 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */; return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (isJSDocEntryNameReference(name)) { + var jsdocReference = getJSDocEntryNameReference(name); + if (jsdocReference || ts.isJSDocLink(name.parent)) { var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */; - return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name)); + var symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ false, ts.getHostSignatureFromJSDoc(name)); + if (symbol) { + return symbol; + } + else if (ts.isQualifiedName(name) && ts.isIdentifier(name.left)) { + // resolve C.m as a static member first + var links = getNodeLinks(name); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + checkQualifiedName(name, 0 /* Normal */); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + // then resolve it as an instance member + var s = resolveEntityName(name.left, meaning, /*ignoreErrors*/ false); + if (s) { + var t = getDeclaredTypeOfSymbol(s); + return getPropertyOfType(t, name.right.escapedText); + } + } } - if (name.parent.kind === 172 /* TypePredicate */) { + if (name.parent.kind === 173 /* TypePredicate */) { return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */); } - // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node, ignoreErrors) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } var parent = node.parent; @@ -78203,8 +80618,8 @@ var ts; if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfNameOrPropertyAccessExpression(node); } - else if (parent.kind === 198 /* BindingElement */ && - grandParent.kind === 196 /* ObjectBindingPattern */ && + else if (parent.kind === 199 /* BindingElement */ && + grandParent.kind === 197 /* ObjectBindingPattern */ && node === parent.propertyName) { var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); @@ -78216,8 +80631,8 @@ var ts; switch (node.kind) { case 78 /* Identifier */: case 79 /* PrivateIdentifier */: - case 201 /* PropertyAccessExpression */: - case 157 /* QualifiedName */: + case 202 /* PropertyAccessExpression */: + case 158 /* QualifiedName */: return getSymbolOfNameOrPropertyAccessExpression(node); case 107 /* ThisKeyword */: var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); @@ -78231,14 +80646,14 @@ var ts; return checkExpression(node).symbol; } // falls through - case 187 /* ThisType */: + case 188 /* ThisType */: return getTypeFromThisTypeNode(node).symbol; case 105 /* SuperKeyword */: return checkExpression(node).symbol; case 132 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 166 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 167 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; @@ -78249,7 +80664,7 @@ var ts; // 3). Dynamic import call or require in javascript // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 261 /* ImportDeclaration */ || node.parent.kind === 267 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((node.parent.kind === 262 /* ImportDeclaration */ || node.parent.kind === 268 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || ((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, ignoreErrors); @@ -78271,7 +80686,7 @@ var ts; case 38 /* EqualsGreaterThanToken */: case 83 /* ClassKeyword */: return getSymbolOfNode(node.parent); - case 195 /* ImportType */: + case 196 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined; case 92 /* ExportKeyword */: return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined; @@ -78280,7 +80695,7 @@ var ts; } } function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 289 /* ShorthandPropertyAssignment */) { + if (location && location.kind === 290 /* ShorthandPropertyAssignment */) { return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */); } return undefined; @@ -78359,27 +80774,27 @@ var ts; // [ a ] from // [a] = [ some array ...] function getTypeOfAssignmentPattern(expr) { - ts.Debug.assert(expr.kind === 200 /* ObjectLiteralExpression */ || expr.kind === 199 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.kind === 201 /* ObjectLiteralExpression */ || expr.kind === 200 /* ArrayLiteralExpression */); // If this is from "for of" // for ( { a } of elems) { // } - if (expr.parent.kind === 239 /* ForOfStatement */) { + if (expr.parent.kind === 240 /* ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 216 /* BinaryExpression */) { + if (expr.parent.kind === 217 /* BinaryExpression */) { var iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 288 /* PropertyAssignment */) { - var node_2 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); - var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_2) || errorType; - var propertyIndex = ts.indexOfNode(node_2.properties, expr.parent); - return checkObjectLiteralDestructuringPropertyAssignment(node_2, typeOfParentObjectLiteral, propertyIndex); + if (expr.parent.kind === 289 /* PropertyAssignment */) { + var node_3 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression); + var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_3) || errorType; + var propertyIndex = ts.indexOfNode(node_3.properties, expr.parent); + return checkObjectLiteralDestructuringPropertyAssignment(node_3, typeOfParentObjectLiteral, propertyIndex); } // Array literal assignment - array destructuring pattern var node = ts.cast(expr.parent, ts.isArrayLiteralExpression); @@ -78423,7 +80838,7 @@ var ts; case 8 /* NumericLiteral */: case 10 /* StringLiteral */: return getLiteralType(name.text); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(name); return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType; default: @@ -78520,6 +80935,7 @@ var ts; // When resolved as an expression identifier, if the given node references an exported entity, return the declaration // node of the exported entity's container. Otherwise, return undefined. function getReferencedExportContainer(nodeIn, prefixLocals) { + var _a; var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { // When resolving the export container for the name of a module or enum @@ -78540,7 +80956,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 297 /* SourceFile */) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && ((_a = parentSymbol_1.valueDeclaration) === null || _a === void 0 ? void 0 : _a.kind) === 298 /* SourceFile */) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -78570,11 +80986,12 @@ var ts; return undefined; } function isSymbolOfDestructuredElementOfCatchBinding(symbol) { - return ts.isBindingElement(symbol.valueDeclaration) - && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 287 /* CatchClause */; + return symbol.valueDeclaration + && ts.isBindingElement(symbol.valueDeclaration) + && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 288 /* CatchClause */; } function isSymbolOfDeclarationWithCollidingName(symbol) { - if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) { + if (symbol.flags & 418 /* BlockScoped */ && symbol.valueDeclaration && !ts.isSourceFile(symbol.valueDeclaration)) { var links = getSymbolLinks(symbol); if (links.isDeclarationWithCollidingName === undefined) { var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); @@ -78602,7 +81019,7 @@ var ts; // they will not collide with anything var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 230 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 231 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -78643,19 +81060,19 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 262 /* ImportClause */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 263 /* ImportClause */: + case 264 /* NamespaceImport */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: var symbol = getSymbolOfNode(node) || unknownSymbol; return isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: var exportClause = node.exportClause; return !!exportClause && (ts.isNamespaceExport(exportClause) || ts.some(exportClause.elements, isValueAliasDeclaration)); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return node.expression && node.expression.kind === 78 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : true; @@ -78664,7 +81081,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 297 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 298 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -78679,7 +81096,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 & 111551 /* Value */) && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; @@ -78687,13 +81104,14 @@ var ts; function isReferencedAliasDeclaration(node, checkChildren) { if (isAliasSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); - if (symbol && getSymbolLinks(symbol).referenced) { + var links = symbol && getSymbolLinks(symbol); + if (links === null || links === void 0 ? void 0 : links.referenced) { return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 if (target && ts.getEffectiveModifierFlags(node) & 1 /* Export */ && target.flags & 111551 /* Value */ && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { + (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -78730,13 +81148,13 @@ var ts; !isOptionalParameter(parameter) && !ts.isJSDocParameterTag(parameter) && !!parameter.initializer && - !ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + !ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && !parameter.initializer && - ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */); + ts.hasSyntacticModifier(parameter, 16476 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameter(parameter) { return !!strictNullChecks && @@ -78771,15 +81189,15 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 291 /* EnumMember */: - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 292 /* EnumMember */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return true; } return false; } function getConstantValue(node) { - if (node.kind === 291 /* EnumMember */) { + if (node.kind === 292 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -78932,8 +81350,7 @@ var ts; } function isLiteralConstDeclaration(node) { if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 2944 /* Literal */) && isFreshLiteralType(type); + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } @@ -79052,12 +81469,12 @@ var ts; getJsxFragmentFactoryEntity: getJsxFragmentFactoryEntity, getAllAccessorDeclarations: function (accessor) { accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 - var otherKind = accessor.kind === 168 /* SetAccessor */ ? 167 /* GetAccessor */ : 168 /* SetAccessor */; + var otherKind = accessor.kind === 169 /* SetAccessor */ ? 168 /* GetAccessor */ : 169 /* SetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; - var setAccessor = accessor.kind === 168 /* SetAccessor */ ? accessor : otherAccessor; - var getAccessor = accessor.kind === 167 /* GetAccessor */ ? accessor : otherAccessor; + var setAccessor = accessor.kind === 169 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 168 /* GetAccessor */ ? accessor : otherAccessor; return { firstAccessor: firstAccessor, secondAccessor: secondAccessor, @@ -79073,7 +81490,7 @@ var ts; }, getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) { var n = ts.getParseTreeNode(node); - ts.Debug.assert(n && n.kind === 297 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile"); + ts.Debug.assert(n && n.kind === 298 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile"); var sym = getSymbolOfNode(node); if (!sym) { return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled); @@ -79096,11 +81513,13 @@ var ts; var s = _a[_i]; if (s.mergeId) { var merged = getMergedSymbol(s); - for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { - var d = _c[_b]; - var declFile = ts.getSourceFileOfNode(d); - if (declFile === importTarget) { - return true; + if (merged.declarations) { + for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declFile = ts.getSourceFileOfNode(d); + if (declFile === importTarget) { + return true; + } } } } @@ -79108,7 +81527,7 @@ var ts; return false; } function isInHeritageClause(node) { - return node.parent && node.parent.kind === 223 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 286 /* HeritageClause */; + return node.parent && node.parent.kind === 224 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 287 /* HeritageClause */; } // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { @@ -79120,7 +81539,7 @@ var ts; // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries var meaning = 788968 /* Type */ | 1920 /* Namespace */; - if ((node.kind === 78 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 201 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { + if ((node.kind === 78 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 202 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { meaning = 111551 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); @@ -79129,10 +81548,7 @@ var ts; // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForSymbol(symbol, meaning) { // program does not have any files with type reference directives - bail out - if (!fileToDirective) { - return undefined; - } - if (!isSymbolFromTypeDeclarationFile(symbol)) { + if (!fileToDirective || !isSymbolFromTypeDeclarationFile(symbol)) { return undefined; } // check what declarations in the symbol can contribute to the target meaning @@ -79171,7 +81587,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 297 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 298 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -79199,12 +81615,12 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = declaration.kind === 256 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var specifier = declaration.kind === 257 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 297 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 298 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -79224,7 +81640,7 @@ var ts; // It is an error for a non-external-module (i.e. script) to declare its own `globalThis`. // We can't use `builtinGlobals` for this due to synthetic expando-namespace generation in JS files. var fileGlobalThisSymbol = file.locals.get("globalThis"); - if (fileGlobalThisSymbol) { + if (fileGlobalThisSymbol === null || fileGlobalThisSymbol === void 0 ? void 0 : fileGlobalThisSymbol.declarations) { for (var _d = 0, _e = fileGlobalThisSymbol.declarations; _d < _e.length; _d++) { var declaration = _e[_d]; diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis")); @@ -79348,6 +81764,16 @@ var ts; if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name); } + else if (helper & 524288 /* ClassPrivateFieldGet */) { + if (!ts.some(getSignaturesOfSymbol(symbol), function (signature) { return getParameterCount(signature) > 3; })) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name, 4); + } + } + else if (helper & 1048576 /* ClassPrivateFieldSet */) { + if (!ts.some(getSignaturesOfSymbol(symbol), function (signature) { return getParameterCount(signature) > 4; })) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, ts.externalHelpersModuleNameText, name, 5); + } + } } } } @@ -79397,14 +81823,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { - if (node.kind === 165 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + if (node.kind === 166 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 167 /* GetAccessor */ || node.kind === 168 /* SetAccessor */) { + else if (node.kind === 168 /* GetAccessor */ || node.kind === 169 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -79417,24 +81843,41 @@ var ts; if (quickResult !== undefined) { return quickResult; } - var lastStatic, lastDeclare, lastAsync, lastReadonly; + var lastStatic, lastDeclare, lastAsync, lastReadonly, lastOverride; var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; if (modifier.kind !== 142 /* ReadonlyKeyword */) { - if (node.kind === 162 /* PropertySignature */ || node.kind === 164 /* MethodSignature */) { + if (node.kind === 163 /* PropertySignature */ || node.kind === 165 /* MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 171 /* IndexSignature */) { + if (node.kind === 172 /* IndexSignature */ && (modifier.kind !== 123 /* StaticKeyword */ || !ts.isClassLike(node.parent))) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { case 84 /* ConstKeyword */: - if (node.kind !== 255 /* EnumDeclaration */) { + if (node.kind !== 256 /* EnumDeclaration */) { return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(84 /* ConstKeyword */)); } break; + case 156 /* OverrideKeyword */: + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "override"); + } + else if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "override", "async"); + } + flags |= 16384 /* Override */; + lastOverride = modifier; + break; case 122 /* PublicKeyword */: case 121 /* ProtectedKeyword */: case 120 /* PrivateKeyword */: @@ -79442,6 +81885,9 @@ var ts; if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "override"); + } else if (flags & 32 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } @@ -79451,7 +81897,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + else if (node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { @@ -79462,7 +81908,7 @@ var ts; return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); } } - else if (ts.isPrivateIdentifierPropertyDeclaration(node)) { + else if (ts.isPrivateIdentifierClassElementDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier); } flags |= ts.modifierToFlag(modifier.kind); @@ -79477,17 +81923,17 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + else if (node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - else if (ts.isPrivateIdentifierPropertyDeclaration(node)) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "static"); + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "override"); } flags |= 32 /* Static */; lastStatic = modifier; @@ -79496,8 +81942,8 @@ var ts; if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 163 /* PropertyDeclaration */ && node.kind !== 162 /* PropertySignature */ && node.kind !== 171 /* IndexSignature */ && node.kind !== 160 /* Parameter */) { - // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. + else if (node.kind !== 164 /* PropertyDeclaration */ && node.kind !== 163 /* PropertySignature */ && node.kind !== 172 /* IndexSignature */ && node.kind !== 161 /* Parameter */) { + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; @@ -79519,14 +81965,14 @@ var ts; else if (ts.isClassLike(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "export"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* Export */; break; case 87 /* DefaultKeyword */: - var container = node.parent.kind === 297 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 256 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 298 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 257 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512 /* Default */; @@ -79538,16 +81984,19 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } + else if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override"); + } else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 257 /* ModuleBlock */) { + else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 258 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } - else if (ts.isPrivateIdentifierPropertyDeclaration(node)) { + else if (ts.isPrivateIdentifierClassElementDeclaration(node)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare"); } flags |= 2 /* Ambient */; @@ -79557,15 +82006,15 @@ var ts; if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 252 /* ClassDeclaration */ && - node.kind !== 175 /* ConstructorType */) { - if (node.kind !== 165 /* MethodDeclaration */ && - node.kind !== 163 /* PropertyDeclaration */ && - node.kind !== 167 /* GetAccessor */ && - node.kind !== 168 /* SetAccessor */) { + if (node.kind !== 253 /* ClassDeclaration */ && + node.kind !== 176 /* ConstructorType */) { + if (node.kind !== 166 /* MethodDeclaration */ && + node.kind !== 164 /* PropertyDeclaration */ && + node.kind !== 168 /* GetAccessor */ && + node.kind !== 169 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 252 /* ClassDeclaration */ && ts.hasSyntacticModifier(node.parent, 128 /* Abstract */))) { + if (!(node.parent.kind === 253 /* ClassDeclaration */ && ts.hasSyntacticModifier(node.parent, 128 /* Abstract */))) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } if (flags & 32 /* Static */) { @@ -79577,6 +82026,9 @@ var ts; if (flags & 256 /* Async */ && lastAsync) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); } + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override"); + } } if (ts.isNamedDeclaration(node) && node.name.kind === 79 /* PrivateIdentifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract"); @@ -79590,7 +82042,7 @@ var ts; else if (flags & 2 /* Ambient */ || node.parent.flags & 8388608 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 160 /* Parameter */) { + else if (node.kind === 161 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } if (flags & 128 /* Abstract */) { @@ -79601,13 +82053,16 @@ var ts; break; } } - if (node.kind === 166 /* Constructor */) { + if (node.kind === 167 /* Constructor */) { if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } if (flags & 128 /* Abstract */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 } + if (flags & 16384 /* Override */) { + return grammarErrorOnNode(lastOverride, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); // TODO: GH#18217 + } else if (flags & 256 /* Async */) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } @@ -79616,13 +82071,13 @@ var ts; } return false; } - else if ((node.kind === 261 /* ImportDeclaration */ || node.kind === 260 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 262 /* ImportDeclaration */ || node.kind === 261 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 160 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 160 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 161 /* Parameter */ && (flags & 16476 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { @@ -79643,38 +82098,38 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 166 /* Constructor */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: - case 171 /* IndexSignature */: - case 256 /* ModuleDeclaration */: - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: - case 160 /* Parameter */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 167 /* Constructor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: + case 172 /* IndexSignature */: + case 257 /* ModuleDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: + case 161 /* Parameter */: return false; default: - if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + if (node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { return false; } switch (node.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return nodeHasAnyModifiersExcept(node, 129 /* AsyncKeyword */); - case 252 /* ClassDeclaration */: - case 175 /* ConstructorType */: + case 253 /* ClassDeclaration */: + case 176 /* ConstructorType */: return nodeHasAnyModifiersExcept(node, 125 /* AbstractKeyword */); - case 253 /* InterfaceDeclaration */: - case 232 /* VariableStatement */: - case 254 /* TypeAliasDeclaration */: + case 254 /* InterfaceDeclaration */: + case 233 /* VariableStatement */: + case 255 /* TypeAliasDeclaration */: return true; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return nodeHasAnyModifiersExcept(node, 84 /* ConstKeyword */); default: ts.Debug.fail(); @@ -79686,10 +82141,10 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 165 /* MethodDeclaration */: - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: - case 209 /* ArrowFunction */: + case 166 /* MethodDeclaration */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: + case 210 /* ArrowFunction */: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); @@ -79850,7 +82305,7 @@ var ts; if (args) { for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { var arg = args_4[_i]; - if (arg.kind === 222 /* OmittedExpression */) { + if (arg.kind === 223 /* OmittedExpression */) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -79927,20 +82382,20 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 158 /* ComputedPropertyName */) { + if (node.kind !== 159 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 216 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { + if (computedPropertyName.expression.kind === 217 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 251 /* FunctionDeclaration */ || - node.kind === 208 /* FunctionExpression */ || - node.kind === 165 /* MethodDeclaration */); + ts.Debug.assert(node.kind === 252 /* FunctionDeclaration */ || + node.kind === 209 /* FunctionExpression */ || + node.kind === 166 /* MethodDeclaration */); if (node.flags & 8388608 /* Ambient */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -79959,7 +82414,7 @@ var ts; var seen = new ts.Map(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 290 /* SpreadAssignment */) { + if (prop.kind === 291 /* SpreadAssignment */) { if (inDestructuring) { // a rest property cannot be destructured any further var expression = ts.skipParentheses(prop.expression); @@ -79970,24 +82425,24 @@ var ts; continue; } var name = prop.name; - if (name.kind === 158 /* ComputedPropertyName */) { + if (name.kind === 159 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name); } - if (prop.kind === 289 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 290 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern); } if (name.kind === 79 /* PrivateIdentifier */) { - return grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); } // Modifiers are never allowed on properties except for 'async' on a method declaration if (prop.modifiers) { // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 var mod = _c[_b]; - if (mod.kind !== 129 /* AsyncKeyword */ || prop.kind !== 165 /* MethodDeclaration */) { + if (mod.kind !== 129 /* AsyncKeyword */ || prop.kind !== 166 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } @@ -80002,10 +82457,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 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); // falls through - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -80013,13 +82468,13 @@ var ts; } currentKind = 4 /* PropertyAssignment */; break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: currentKind = 8 /* Method */; break; - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: currentKind = 1 /* GetAccessor */; break; - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: currentKind = 2 /* SetAccessor */; break; default: @@ -80054,11 +82509,12 @@ var ts; } } function checkGrammarJsxElement(node) { + checkGrammarJsxName(node.tagName); checkGrammarTypeArguments(node, node.typeArguments); var seen = new ts.Map(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 282 /* JsxSpreadAttribute */) { + if (attr.kind === 283 /* JsxSpreadAttribute */) { continue; } var name = attr.name, initializer = attr.initializer; @@ -80068,11 +82524,32 @@ var ts; else { return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - if (initializer && initializer.kind === 283 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 284 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } } + function checkGrammarJsxName(node) { + if (ts.isPropertyAccessExpression(node)) { + var propName = node; + do { + var check_1 = checkGrammarJsxNestedIdentifier(propName.name); + if (check_1) { + return check_1; + } + propName = propName.expression; + } while (ts.isPropertyAccessExpression(propName)); + var check = checkGrammarJsxNestedIdentifier(propName); + if (check) { + return check; + } + } + function checkGrammarJsxNestedIdentifier(name) { + if (ts.isIdentifier(name) && ts.idText(name).indexOf(":") !== -1) { + return grammarErrorOnNode(name, ts.Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names); + } + } + } function checkGrammarJsxExpression(node) { if (node.expression && ts.isCommaSequence(node.expression)) { return grammarErrorOnNode(node.expression, ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array); @@ -80082,25 +82559,37 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 239 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { - if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) { - // use of 'for-await-of' in non-async function + if (forInOrOfStatement.kind === 240 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if (!(forInOrOfStatement.flags & 32768 /* AwaitContext */)) { var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement); - if (!hasParseDiagnostics(sourceFile)) { - var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); - var func = ts.getContainingFunction(forInOrOfStatement); - if (func && func.kind !== 166 /* Constructor */) { - ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); - var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); - ts.addRelatedInfo(diagnostic, relatedInfo); - } - diagnostics.add(diagnostic); - return true; + if (ts.isInTopLevelContext(forInOrOfStatement)) { + if (!hasParseDiagnostics(sourceFile)) { + if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module)); + } + if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) { + diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher)); + } + } + } + else { + // use of 'for-await-of' in non-async function + if (!hasParseDiagnostics(sourceFile)) { + var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); + var func = ts.getContainingFunction(forInOrOfStatement); + if (func && func.kind !== 167 /* Constructor */) { + ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function."); + var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); + ts.addRelatedInfo(diagnostic, relatedInfo); + } + diagnostics.add(diagnostic); + return true; + } } return false; } } - if (forInOrOfStatement.initializer.kind === 250 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 251 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -80115,20 +82604,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 239 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 239 /* ForInStatement */ ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 239 /* ForInStatement */ ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -80138,26 +82627,34 @@ var ts; return false; } function checkGrammarAccessor(accessor) { - if (!(accessor.flags & 8388608 /* Ambient */)) { + if (!(accessor.flags & 8388608 /* Ambient */) && (accessor.parent.kind !== 178 /* TypeLiteral */) && (accessor.parent.kind !== 254 /* InterfaceDeclaration */)) { if (languageVersion < 1 /* ES5 */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } + if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(accessor.name)) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } if (accessor.body === undefined && !ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) { return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } - if (accessor.body && ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) { - return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + if (accessor.body) { + if (ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + if (accessor.parent.kind === 178 /* TypeLiteral */ || accessor.parent.kind === 254 /* InterfaceDeclaration */) { + return grammarErrorOnNode(accessor.body, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } } if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, accessor.kind === 167 /* GetAccessor */ ? + return grammarErrorOnNode(accessor.name, accessor.kind === 168 /* GetAccessor */ ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - if (accessor.kind === 168 /* SetAccessor */) { + if (accessor.kind === 169 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -80179,10 +82676,10 @@ var ts; * A set accessor has one parameter or a `this` parameter and one more parameter. */ function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 167 /* GetAccessor */ ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 168 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 167 /* GetAccessor */ ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 168 /* GetAccessor */ ? 1 : 2)) { return ts.getThisParameter(accessor); } } @@ -80200,7 +82697,7 @@ var ts; } } switch (parent.kind) { - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: var decl = parent; if (decl.name.kind !== 78 /* Identifier */) { return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); @@ -80212,13 +82709,13 @@ var ts; return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); } break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: if (!ts.hasSyntacticModifier(parent, 32 /* Static */) || !ts.hasEffectiveModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: if (!ts.hasSyntacticModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } @@ -80228,7 +82725,7 @@ var ts; } } else if (node.operator === 142 /* ReadonlyKeyword */) { - if (node.type.kind !== 178 /* ArrayType */ && node.type.kind !== 179 /* TupleType */) { + if (node.type.kind !== 179 /* ArrayType */ && node.type.kind !== 180 /* TupleType */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(148 /* SymbolKeyword */)); } } @@ -80242,8 +82739,8 @@ var ts; if (checkGrammarFunctionLikeDeclaration(node)) { return true; } - if (node.kind === 165 /* MethodDeclaration */) { - if (node.parent.kind === 200 /* ObjectLiteralExpression */) { + if (node.kind === 166 /* MethodDeclaration */) { + if (node.parent.kind === 201 /* ObjectLiteralExpression */) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 129 /* AsyncKeyword */)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -80263,6 +82760,9 @@ var ts; } } if (ts.isClassLike(node.parent)) { + if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) { + return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } // Technically, computed properties in ambient contexts is disallowed // for property declarations and accessors too, not just methods. // However, property declarations disallow computed names in general, @@ -80271,14 +82771,14 @@ var ts; if (node.flags & 8388608 /* Ambient */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.kind === 165 /* MethodDeclaration */ && !node.body) { + else if (node.kind === 166 /* MethodDeclaration */ && !node.body) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 253 /* InterfaceDeclaration */) { + else if (node.parent.kind === 254 /* InterfaceDeclaration */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 177 /* TypeLiteral */) { + else if (node.parent.kind === 178 /* TypeLiteral */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } @@ -80289,11 +82789,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: if (node.label && current.label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 240 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 241 /* ContinueStatement */ && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -80301,8 +82801,8 @@ var ts; return false; } break; - case 244 /* SwitchStatement */: - if (node.kind === 241 /* BreakStatement */ && !node.label) { + case 245 /* SwitchStatement */: + if (node.kind === 242 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -80317,13 +82817,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 241 /* BreakStatement */ + var message = node.kind === 242 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 241 /* BreakStatement */ + var message = node.kind === 242 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -80347,12 +82847,12 @@ var ts; } function isStringOrNumberLiteralExpression(expr) { return ts.isStringOrNumericLiteralLike(expr) || - expr.kind === 214 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && + expr.kind === 215 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } function isBigIntLiteralExpression(expr) { return expr.kind === 9 /* BigIntLiteral */ || - expr.kind === 214 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && + expr.kind === 215 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ && expr.operand.kind === 9 /* BigIntLiteral */; } function isSimpleLiteralEnumReference(expr) { @@ -80383,7 +82883,7 @@ var ts; } } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 238 /* ForInStatement */ && node.parent.parent.kind !== 239 /* ForOfStatement */) { + if (node.parent.parent.kind !== 239 /* ForInStatement */ && node.parent.parent.kind !== 240 /* ForOfStatement */) { if (node.flags & 8388608 /* Ambient */) { checkAmbientInitializer(node); } @@ -80396,7 +82896,7 @@ var ts; } } } - if (node.exclamationToken && (node.parent.parent.kind !== 232 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) { + if (node.exclamationToken && (node.parent.parent.kind !== 233 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) { var message = node.initializer ? ts.Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type @@ -80464,15 +82964,15 @@ var ts; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 234 /* IfStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 243 /* WithStatement */: - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 235 /* IfStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 244 /* WithStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: return false; - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -80557,14 +83057,14 @@ var ts; if (ts.isStringLiteral(node.name) && node.name.text === "constructor") { return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor); } - if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type)) { return true; } if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) { return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); } } - else if (node.parent.kind === 253 /* InterfaceDeclaration */) { + else if (node.parent.kind === 254 /* InterfaceDeclaration */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -80572,7 +83072,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 177 /* TypeLiteral */) { + else if (node.parent.kind === 178 /* TypeLiteral */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -80606,13 +83106,13 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 253 /* InterfaceDeclaration */ || - node.kind === 254 /* TypeAliasDeclaration */ || - node.kind === 261 /* ImportDeclaration */ || - node.kind === 260 /* ImportEqualsDeclaration */ || - node.kind === 267 /* ExportDeclaration */ || - node.kind === 266 /* ExportAssignment */ || - node.kind === 259 /* NamespaceExportDeclaration */ || + if (node.kind === 254 /* InterfaceDeclaration */ || + node.kind === 255 /* TypeAliasDeclaration */ || + node.kind === 262 /* ImportDeclaration */ || + node.kind === 261 /* ImportEqualsDeclaration */ || + node.kind === 268 /* ExportDeclaration */ || + node.kind === 267 /* ExportAssignment */ || + node.kind === 260 /* NamespaceExportDeclaration */ || ts.hasSyntacticModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } @@ -80621,7 +83121,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 232 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 233 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -80644,7 +83144,7 @@ var ts; // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if (node.parent.kind === 230 /* Block */ || node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) { + if (node.parent.kind === 231 /* Block */ || node.parent.kind === 258 /* ModuleBlock */ || node.parent.kind === 298 /* SourceFile */) { var links_2 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_2.hasReportedStatementInAmbientContext) { @@ -80666,10 +83166,10 @@ var ts; if (languageVersion >= 1 /* ES5 */) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 191 /* LiteralType */)) { + else if (ts.isChildOfNodeWithKind(node, 192 /* LiteralType */)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 291 /* EnumMember */)) { + else if (ts.isChildOfNodeWithKind(node, 292 /* EnumMember */)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { @@ -80775,7 +83275,7 @@ var ts; } } function findBestTypeForObjectLiteral(source, unionTarget) { - if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) { + if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && someType(unionTarget, isArrayLikeType)) { return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } @@ -80827,6 +83327,10 @@ var ts; // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) { if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) { + var match = getMatchingUnionConstituentForType(target, source); + if (match) { + return match; + } var sourceProperties = getPropertiesOfType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); @@ -80844,33 +83348,19 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 251 /* FunctionDeclaration */ && declaration.kind !== 165 /* MethodDeclaration */) || + return (declaration.kind !== 252 /* FunctionDeclaration */ && declaration.kind !== 166 /* MethodDeclaration */) || !!declaration.body; } /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 265 /* ImportSpecifier */: - case 270 /* ExportSpecifier */: + case 266 /* ImportSpecifier */: + case 271 /* ExportSpecifier */: return ts.isIdentifier(name); default: return ts.isDeclarationName(name); } } - function isSomeImportDeclaration(decl) { - switch (decl.kind) { - case 262 /* ImportClause */: // For default import - case 260 /* ImportEqualsDeclaration */: - case 263 /* NamespaceImport */: - case 265 /* ImportSpecifier */: // For rename import `x as y` - return true; - case 78 /* Identifier */: - // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 265 /* ImportSpecifier */; - default: - return false; - } - } var JsxNames; (function (JsxNames) { JsxNames.JSX = "JSX"; @@ -80901,7 +83391,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); function visitNode(node, visitor, test, lift) { if (node === undefined || visitor === undefined) { return node; @@ -81090,6 +83579,24 @@ var ts; return updated; } ts.visitFunctionBody = visitFunctionBody; + /** + * Visits an iteration body, adding any block-scoped variables required by the transformation. + */ + function visitIterationBody(body, visitor, context) { + context.startBlockScope(); + var updated = visitNode(body, visitor, ts.isStatement, context.factory.liftToBlock); + var declarations = context.endBlockScope(); + if (ts.some(declarations)) { + if (ts.isBlock(updated)) { + declarations.push.apply(declarations, updated.statements); + return context.factory.updateBlock(updated, declarations); + } + declarations.push(updated); + return context.factory.createBlock(declarations); + } + return updated; + } + ts.visitIterationBody = visitIterationBody; function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor, nodeVisitor) { if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } if (nodeVisitor === void 0) { nodeVisitor = visitNode; } @@ -81098,299 +83605,433 @@ var ts; } var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 156 /* LastToken */) || kind === 187 /* ThisType */) { + if ((kind > 0 /* FirstToken */ && kind <= 157 /* LastToken */) || kind === 188 /* ThisType */) { return node; } var factory = context.factory; switch (kind) { // Names case 78 /* Identifier */: - return factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); - case 157 /* QualifiedName */: + ts.Debug.type(node); + return factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNodeOrTypeParameterDeclaration)); + case 158 /* QualifiedName */: + ts.Debug.type(node); return factory.updateQualifiedName(node, nodeVisitor(node.left, visitor, ts.isEntityName), nodeVisitor(node.right, visitor, ts.isIdentifier)); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: + ts.Debug.type(node); return factory.updateComputedPropertyName(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Signature elements - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: + ts.Debug.type(node); return factory.updateTypeParameterDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode)); - case 160 /* Parameter */: - return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 161 /* Decorator */: + case 161 /* Parameter */: + ts.Debug.type(node); + return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 162 /* Decorator */: + ts.Debug.type(node); return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Type elements - case 162 /* PropertySignature */: - return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 163 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + ts.Debug.type(node); + return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 164 /* PropertyDeclaration */: + ts.Debug.type(node); return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too - nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 164 /* MethodSignature */: - return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 165 /* MethodDeclaration */: - return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 166 /* Constructor */: + nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isQuestionOrExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 165 /* MethodSignature */: + ts.Debug.type(node); + return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 166 /* MethodDeclaration */: + ts.Debug.type(node); + return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 167 /* Constructor */: + ts.Debug.type(node); return factory.updateConstructorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: + ts.Debug.type(node); return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: + ts.Debug.type(node); return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 169 /* CallSignature */: + case 170 /* CallSignature */: + ts.Debug.type(node); return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: + ts.Debug.type(node); return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: + ts.Debug.type(node); return factory.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); // Types - case 172 /* TypePredicate */: - return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor), nodeVisitor(node.parameterName, visitor), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 173 /* TypeReference */: + case 173 /* TypePredicate */: + ts.Debug.type(node); + return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor, ts.isAssertsKeyword), nodeVisitor(node.parameterName, visitor, ts.isIdentifierOrThisTypeNode), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 174 /* TypeReference */: + ts.Debug.type(node); return factory.updateTypeReferenceNode(node, nodeVisitor(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 174 /* FunctionType */: + case 175 /* FunctionType */: + ts.Debug.type(node); return factory.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 175 /* ConstructorType */: + case 176 /* ConstructorType */: + ts.Debug.type(node); return factory.updateConstructorTypeNode(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: + ts.Debug.type(node); return factory.updateTypeQueryNode(node, nodeVisitor(node.exprName, visitor, ts.isEntityName)); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: + ts.Debug.type(node); return factory.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 178 /* ArrayType */: + case 179 /* ArrayType */: + ts.Debug.type(node); return factory.updateArrayTypeNode(node, nodeVisitor(node.elementType, visitor, ts.isTypeNode)); - case 179 /* TupleType */: + case 180 /* TupleType */: + ts.Debug.type(node); return factory.updateTupleTypeNode(node, nodesVisitor(node.elements, visitor, ts.isTypeNode)); - case 180 /* OptionalType */: + case 181 /* OptionalType */: + ts.Debug.type(node); return factory.updateOptionalTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 181 /* RestType */: + case 182 /* RestType */: + ts.Debug.type(node); return factory.updateRestTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 182 /* UnionType */: + case 183 /* UnionType */: + ts.Debug.type(node); return factory.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 183 /* IntersectionType */: + case 184 /* IntersectionType */: + ts.Debug.type(node); return factory.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: + ts.Debug.type(node); return factory.updateConditionalTypeNode(node, nodeVisitor(node.checkType, visitor, ts.isTypeNode), nodeVisitor(node.extendsType, visitor, ts.isTypeNode), nodeVisitor(node.trueType, visitor, ts.isTypeNode), nodeVisitor(node.falseType, visitor, ts.isTypeNode)); - case 185 /* InferType */: + case 186 /* InferType */: + ts.Debug.type(node); return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); - case 195 /* ImportType */: + case 196 /* ImportType */: + ts.Debug.type(node); return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); - case 192 /* NamedTupleMember */: - return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); - case 186 /* ParenthesizedType */: + case 193 /* NamedTupleMember */: + ts.Debug.type(node); + return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isDotDotDotToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isQuestionToken), visitNode(node.type, visitor, ts.isTypeNode)); + case 187 /* ParenthesizedType */: + ts.Debug.type(node); return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: + ts.Debug.type(node); return factory.updateTypeOperatorNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: + ts.Debug.type(node); return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode)); - case 190 /* MappedType */: - return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 191 /* LiteralType */: + case 191 /* MappedType */: + ts.Debug.type(node); + return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isReadonlyKeywordOrPlusOrMinusToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionOrPlusOrMinusToken), nodeVisitor(node.type, visitor, ts.isTypeNode)); + case 192 /* LiteralType */: + ts.Debug.type(node); return factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression)); - case 193 /* TemplateLiteralType */: + case 194 /* TemplateLiteralType */: + ts.Debug.type(node); return factory.updateTemplateLiteralType(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateLiteralTypeSpan)); - case 194 /* TemplateLiteralTypeSpan */: + case 195 /* TemplateLiteralTypeSpan */: + ts.Debug.type(node); return factory.updateTemplateLiteralTypeSpan(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Binding patterns - case 196 /* ObjectBindingPattern */: + case 197 /* ObjectBindingPattern */: + ts.Debug.type(node); return factory.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: + ts.Debug.type(node); return factory.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); - case 198 /* BindingElement */: - return factory.updateBindingElement(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.propertyName, visitor, ts.isPropertyName), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 199 /* BindingElement */: + ts.Debug.type(node); + return factory.updateBindingElement(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isDotDotDotToken), nodeVisitor(node.propertyName, visitor, ts.isPropertyName), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.initializer, visitor, ts.isExpression)); // Expression - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: + ts.Debug.type(node); return factory.updateArrayLiteralExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression)); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + ts.Debug.type(node); return factory.updateObjectLiteralExpression(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (node.flags & 32 /* OptionalChain */) { - return factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier)); + ts.Debug.type(node); + return factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodeVisitor(node.name, visitor, ts.isMemberName)); } - return factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isIdentifierOrPrivateIdentifier)); - case 202 /* ElementAccessExpression */: + ts.Debug.type(node); + return factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isMemberName)); + case 203 /* ElementAccessExpression */: if (node.flags & 32 /* OptionalChain */) { - return factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); } + ts.Debug.type(node); return factory.updateElementAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.argumentExpression, visitor, ts.isExpression)); - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (node.flags & 32 /* OptionalChain */) { - return factory.updateCallChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + ts.Debug.type(node); + return factory.updateCallChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isQuestionDotToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); } + ts.Debug.type(node); return factory.updateCallExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 204 /* NewExpression */: + case 205 /* NewExpression */: + ts.Debug.type(node); return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 205 /* TaggedTemplateExpression */: - return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); - case 206 /* TypeAssertionExpression */: + case 206 /* TaggedTemplateExpression */: + ts.Debug.type(node); + return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.template, visitor, ts.isTemplateLiteral)); + case 207 /* TypeAssertionExpression */: + ts.Debug.type(node); return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: + ts.Debug.type(node); return factory.updateParenthesizedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 208 /* FunctionExpression */: - return factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 209 /* ArrowFunction */: - return factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, ts.isToken), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 210 /* DeleteExpression */: + case 209 /* FunctionExpression */: + ts.Debug.type(node); + return factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 210 /* ArrowFunction */: + ts.Debug.type(node); + return factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, ts.isEqualsGreaterThanToken), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 211 /* DeleteExpression */: + ts.Debug.type(node); return factory.updateDeleteExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: + ts.Debug.type(node); return factory.updateTypeOfExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: + ts.Debug.type(node); return factory.updateVoidExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: + ts.Debug.type(node); return factory.updateAwaitExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + ts.Debug.type(node); return factory.updatePrefixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression)); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + ts.Debug.type(node); return factory.updatePostfixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression)); - case 216 /* BinaryExpression */: - return factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isToken), nodeVisitor(node.right, visitor, ts.isExpression)); - case 217 /* ConditionalExpression */: - return factory.updateConditionalExpression(node, nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.whenTrue, visitor, ts.isExpression), nodeVisitor(node.colonToken, tokenVisitor, ts.isToken), nodeVisitor(node.whenFalse, visitor, ts.isExpression)); - case 218 /* TemplateExpression */: + case 217 /* BinaryExpression */: + ts.Debug.type(node); + return factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isBinaryOperatorToken), nodeVisitor(node.right, visitor, ts.isExpression)); + case 218 /* ConditionalExpression */: + ts.Debug.type(node); + return factory.updateConditionalExpression(node, nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.questionToken, tokenVisitor, ts.isQuestionToken), nodeVisitor(node.whenTrue, visitor, ts.isExpression), nodeVisitor(node.colonToken, tokenVisitor, ts.isColonToken), nodeVisitor(node.whenFalse, visitor, ts.isExpression)); + case 219 /* TemplateExpression */: + ts.Debug.type(node); return factory.updateTemplateExpression(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); - case 219 /* YieldExpression */: - return factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 220 /* SpreadElement */: + case 220 /* YieldExpression */: + ts.Debug.type(node); + return factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.expression, visitor, ts.isExpression)); + case 221 /* SpreadElement */: + ts.Debug.type(node); return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: + ts.Debug.type(node); return factory.updateClassExpression(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: + ts.Debug.type(node); return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 224 /* AsExpression */: + case 225 /* AsExpression */: + ts.Debug.type(node); return factory.updateAsExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: if (node.flags & 32 /* OptionalChain */) { + ts.Debug.type(node); return factory.updateNonNullChain(node, nodeVisitor(node.expression, visitor, ts.isExpression)); } + ts.Debug.type(node); return factory.updateNonNullExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: + ts.Debug.type(node); return factory.updateMetaProperty(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); // Misc - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: + ts.Debug.type(node); return factory.updateTemplateSpan(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element - case 230 /* Block */: + case 231 /* Block */: + ts.Debug.type(node); return factory.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: + ts.Debug.type(node); return factory.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: + ts.Debug.type(node); return factory.updateExpressionStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 234 /* IfStatement */: + case 235 /* IfStatement */: + ts.Debug.type(node); return factory.updateIfStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.thenStatement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.elseStatement, visitor, ts.isStatement, factory.liftToBlock)); - case 235 /* DoStatement */: - return factory.updateDoStatement(node, nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 236 /* WhileStatement */: - return factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 237 /* ForStatement */: - return factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.incrementor, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 238 /* ForInStatement */: - return factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 239 /* ForOfStatement */: - return factory.updateForOfStatement(node, nodeVisitor(node.awaitModifier, tokenVisitor, ts.isToken), nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 240 /* ContinueStatement */: + case 236 /* DoStatement */: + ts.Debug.type(node); + return factory.updateDoStatement(node, visitIterationBody(node.statement, visitor, context), nodeVisitor(node.expression, visitor, ts.isExpression)); + case 237 /* WhileStatement */: + ts.Debug.type(node); + return factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 238 /* ForStatement */: + ts.Debug.type(node); + return factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.incrementor, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 239 /* ForInStatement */: + ts.Debug.type(node); + return factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 240 /* ForOfStatement */: + ts.Debug.type(node); + return factory.updateForOfStatement(node, nodeVisitor(node.awaitModifier, tokenVisitor, ts.isAwaitKeyword), nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), visitIterationBody(node.statement, visitor, context)); + case 241 /* ContinueStatement */: + ts.Debug.type(node); return factory.updateContinueStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier)); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: + ts.Debug.type(node); return factory.updateBreakStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier)); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: + ts.Debug.type(node); return factory.updateReturnStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 243 /* WithStatement */: + case 244 /* WithStatement */: + ts.Debug.type(node); return factory.updateWithStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: + ts.Debug.type(node); return factory.updateSwitchStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.caseBlock, visitor, ts.isCaseBlock)); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: + ts.Debug.type(node); return factory.updateLabeledStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: + ts.Debug.type(node); return factory.updateThrowStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 247 /* TryStatement */: + case 248 /* TryStatement */: + ts.Debug.type(node); return factory.updateTryStatement(node, nodeVisitor(node.tryBlock, visitor, ts.isBlock), nodeVisitor(node.catchClause, visitor, ts.isCatchClause), nodeVisitor(node.finallyBlock, visitor, ts.isBlock)); - case 249 /* VariableDeclaration */: - return factory.updateVariableDeclaration(node, nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 250 /* VariableDeclarationList */: + case 250 /* VariableDeclaration */: + ts.Debug.type(node); + return factory.updateVariableDeclaration(node, nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.exclamationToken, tokenVisitor, ts.isExclamationToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression)); + case 251 /* VariableDeclarationList */: + ts.Debug.type(node); return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); - case 251 /* FunctionDeclaration */: - return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); - case 252 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: + ts.Debug.type(node); + return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isAsteriskToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor)); + case 253 /* ClassDeclaration */: + ts.Debug.type(node); return factory.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: + ts.Debug.type(node); return factory.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: + ts.Debug.type(node); return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode)); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: + ts.Debug.type(node); return factory.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); - case 256 /* ModuleDeclaration */: - return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.body, visitor, ts.isModuleBody)); - case 257 /* ModuleBlock */: + case 257 /* ModuleDeclaration */: + ts.Debug.type(node); + return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isModuleName), nodeVisitor(node.body, visitor, ts.isModuleBody)); + case 258 /* ModuleBlock */: + ts.Debug.type(node); return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: + ts.Debug.type(node); return factory.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: + ts.Debug.type(node); return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: + ts.Debug.type(node); return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference)); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: + ts.Debug.type(node); return factory.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression)); - case 262 /* ImportClause */: + case 263 /* ImportClause */: + ts.Debug.type(node); return factory.updateImportClause(node, node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.namedBindings, visitor, ts.isNamedImportBindings)); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: + ts.Debug.type(node); return factory.updateNamespaceImport(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: + ts.Debug.type(node); return factory.updateNamespaceExport(node, nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 264 /* NamedImports */: + case 265 /* NamedImports */: + ts.Debug.type(node); return factory.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: + ts.Debug.type(node); return factory.updateImportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: + ts.Debug.type(node); return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression)); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: + ts.Debug.type(node); return factory.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression)); - case 268 /* NamedExports */: + case 269 /* NamedExports */: + ts.Debug.type(node); return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: + ts.Debug.type(node); return factory.updateExportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier)); // Module references - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: + ts.Debug.type(node); return factory.updateExternalModuleReference(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // JSX - case 273 /* JsxElement */: + case 274 /* JsxElement */: + ts.Debug.type(node); return factory.updateJsxElement(node, nodeVisitor(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingElement, visitor, ts.isJsxClosingElement)); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: + ts.Debug.type(node); return factory.updateJsxSelfClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes)); - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: + ts.Debug.type(node); return factory.updateJsxOpeningElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes)); - case 276 /* JsxClosingElement */: + case 277 /* JsxClosingElement */: + ts.Debug.type(node); return factory.updateJsxClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: + ts.Debug.type(node); return factory.updateJsxFragment(node, nodeVisitor(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingFragment, visitor, ts.isJsxClosingFragment)); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: + ts.Debug.type(node); return factory.updateJsxAttribute(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: + ts.Debug.type(node); return factory.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 282 /* JsxSpreadAttribute */: + case 283 /* JsxSpreadAttribute */: + ts.Debug.type(node); return factory.updateJsxSpreadAttribute(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: + ts.Debug.type(node); return factory.updateJsxExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Clauses - case 284 /* CaseClause */: + case 285 /* CaseClause */: + ts.Debug.type(node); return factory.updateCaseClause(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: + ts.Debug.type(node); return factory.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: + ts.Debug.type(node); return factory.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 287 /* CatchClause */: + case 288 /* CatchClause */: + ts.Debug.type(node); return factory.updateCatchClause(node, nodeVisitor(node.variableDeclaration, visitor, ts.isVariableDeclaration), nodeVisitor(node.block, visitor, ts.isBlock)); // Property assignments - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: + ts.Debug.type(node); return factory.updatePropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression)); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + ts.Debug.type(node); return factory.updateShorthandPropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: + ts.Debug.type(node); return factory.updateSpreadAssignment(node, nodeVisitor(node.expression, visitor, ts.isExpression)); // Enum - case 291 /* EnumMember */: + case 292 /* EnumMember */: + ts.Debug.type(node); return factory.updateEnumMember(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression)); // Top-level nodes - case 297 /* SourceFile */: + case 298 /* SourceFile */: + ts.Debug.type(node); return factory.updateSourceFile(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 336 /* PartiallyEmittedExpression */: + case 340 /* PartiallyEmittedExpression */: + ts.Debug.type(node); return factory.updatePartiallyEmittedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression)); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: + ts.Debug.type(node); return factory.updateCommaListExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -82065,7 +84706,7 @@ var ts; function chainBundle(context, transformSourceFile) { return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - return node.kind === 297 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + return node.kind === 298 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); } function transformBundle(node) { return context.factory.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); @@ -82116,7 +84757,7 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: // import "mod" // import x from "mod" // import * as x from "mod" @@ -82129,13 +84770,13 @@ var ts; hasImportDefault = true; } break; - case 260 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 272 /* ExternalModuleReference */) { + case 261 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 273 /* ExternalModuleReference */) { // import x = require("mod") externalImports.push(node); } break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" @@ -82166,13 +84807,13 @@ var ts; addExportedNamesForExportDeclaration(node); } break; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; } break; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: if (ts.hasSyntacticModifier(node, 1 /* Export */)) { for (var _b = 0, _c = node.declarationList.declarations; _b < _c.length; _b++) { var decl = _c[_b]; @@ -82180,7 +84821,7 @@ var ts; } } break; - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: if (ts.hasSyntacticModifier(node, 1 /* Export */)) { if (ts.hasSyntacticModifier(node, 512 /* Default */)) { // export default function() { } @@ -82200,7 +84841,7 @@ var ts; } } break; - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: if (ts.hasSyntacticModifier(node, 1 /* Export */)) { if (ts.hasSyntacticModifier(node, 512 /* Default */)) { // export default class { } @@ -82294,8 +84935,7 @@ var ts; * any such locations */ function isSimpleInlineableExpression(expression) { - return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression) || - ts.isWellKnownSymbolSyntactically(expression); + return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression); } ts.isSimpleInlineableExpression = isSimpleInlineableExpression; function isCompoundAssignment(kind) { @@ -82374,10 +85014,19 @@ var ts; * @param isStatic A value indicating whether the member should be a static or instance member. */ function isInitializedProperty(member) { - return member.kind === 163 /* PropertyDeclaration */ + return member.kind === 164 /* PropertyDeclaration */ && member.initializer !== undefined; } ts.isInitializedProperty = isInitializedProperty; + /** + * Gets a value indicating whether a class element is a private instance method or accessor. + * + * @param member The class element node. + */ + function isNonStaticMethodOrAccessorWithPrivateName(member) { + return !ts.hasStaticModifier(member) && ts.isMethodOrAccessor(member) && ts.isPrivateIdentifier(member.name); + } + ts.isNonStaticMethodOrAccessorWithPrivateName = isNonStaticMethodOrAccessorWithPrivateName; })(ts || (ts = {})); /*@internal*/ var ts; @@ -82651,8 +85300,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */)) + && !(element.transformFlags & (16384 /* ContainsRestOrSpread */ | 32768 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (16384 /* ContainsRestOrSpread */ | 32768 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor)); } @@ -82718,7 +85367,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 & 16384 /* ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { + if (element.transformFlags & 32768 /* ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { flattenContext.hasTransformedPriorElement = true; var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { @@ -82976,8 +85625,8 @@ var ts; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; // Enable substitution for property/element access to emit const enum values. - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(202 /* ElementAccessExpression */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(203 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; @@ -83003,14 +85652,14 @@ var ts; var applicableSubstitutions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - if (node.kind === 298 /* Bundle */) { + if (node.kind === 299 /* Bundle */) { return transformBundle(node); } return transformSourceFile(node); } function transformBundle(node) { return factory.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 300 /* InputFiles */) { + if (prepend.kind === 301 /* InputFiles */) { return ts.createUnparsedSourceFile(prepend, "js"); } return prepend; @@ -83061,16 +85710,16 @@ var ts; */ function onBeforeVisitNode(node) { switch (node.kind) { - case 297 /* SourceFile */: - case 258 /* CaseBlock */: - case 257 /* ModuleBlock */: - case 230 /* Block */: + case 298 /* SourceFile */: + case 259 /* CaseBlock */: + case 258 /* ModuleBlock */: + case 231 /* Block */: currentLexicalScope = node; currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; - case 252 /* ClassDeclaration */: - case 251 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 252 /* FunctionDeclaration */: if (ts.hasSyntacticModifier(node, 2 /* Ambient */)) { break; } @@ -83082,7 +85731,7 @@ var ts; // These nodes should always have names unless they are default-exports; // however, class declaration parsing allows for undefined names, so syntactically invalid // programs may also have an undefined name. - ts.Debug.assert(node.kind === 252 /* ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* Default */)); + ts.Debug.assert(node.kind === 253 /* ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* Default */)); } if (ts.isClassDeclaration(node)) { // XXX: should probably also cover interfaces and type aliases that can have type variables? @@ -83125,10 +85774,10 @@ var ts; */ function sourceElementVisitorWorker(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 266 /* ExportAssignment */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 267 /* ExportAssignment */: + case 268 /* ExportDeclaration */: return visitElidableStatement(node); default: return visitorWorker(node); @@ -83149,13 +85798,13 @@ var ts; return node; } switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -83175,11 +85824,11 @@ var ts; * @param node The node to visit. */ function namespaceElementVisitorWorker(node) { - if (node.kind === 267 /* ExportDeclaration */ || - node.kind === 261 /* ImportDeclaration */ || - node.kind === 262 /* ImportClause */ || - (node.kind === 260 /* ImportEqualsDeclaration */ && - node.moduleReference.kind === 272 /* ExternalModuleReference */)) { + if (node.kind === 268 /* ExportDeclaration */ || + node.kind === 262 /* ImportDeclaration */ || + node.kind === 263 /* ImportClause */ || + (node.kind === 261 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 273 /* ExternalModuleReference */)) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -83203,26 +85852,26 @@ var ts; */ function classElementVisitorWorker(node) { switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return visitConstructor(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // Property declarations are not TypeScript syntax, but they must be visited // for the decorator transformation. return visitPropertyDeclaration(node); - case 171 /* IndexSignature */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: + case 172 /* IndexSignature */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: // Fallback to the default visit behavior. return visitorWorker(node); - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: return node; default: return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { - if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) { + if (ts.modifierToFlag(node.kind) & 18654 /* TypeScriptModifier */) { return undefined; } else if (currentNamespace && node.kind === 92 /* ExportKeyword */) { @@ -83255,13 +85904,13 @@ var ts; case 142 /* ReadonlyKeyword */: // TypeScript accessibility and readonly modifiers are elided // falls through - case 178 /* ArrayType */: - case 179 /* TupleType */: - case 180 /* OptionalType */: - case 181 /* RestType */: - case 177 /* TypeLiteral */: - case 172 /* TypePredicate */: - case 159 /* TypeParameter */: + case 179 /* ArrayType */: + case 180 /* TupleType */: + case 181 /* OptionalType */: + case 182 /* RestType */: + case 178 /* TypeLiteral */: + case 173 /* TypePredicate */: + case 160 /* TypeParameter */: case 128 /* AnyKeyword */: case 152 /* UnknownKeyword */: case 131 /* BooleanKeyword */: @@ -83270,43 +85919,43 @@ var ts; case 141 /* NeverKeyword */: case 113 /* VoidKeyword */: case 148 /* SymbolKeyword */: - case 175 /* ConstructorType */: - case 174 /* FunctionType */: - case 176 /* TypeQuery */: - case 173 /* TypeReference */: - case 182 /* UnionType */: - case 183 /* IntersectionType */: - case 184 /* ConditionalType */: - case 186 /* ParenthesizedType */: - case 187 /* ThisType */: - case 188 /* TypeOperator */: - case 189 /* IndexedAccessType */: - case 190 /* MappedType */: - case 191 /* LiteralType */: + case 176 /* ConstructorType */: + case 175 /* FunctionType */: + case 177 /* TypeQuery */: + case 174 /* TypeReference */: + case 183 /* UnionType */: + case 184 /* IntersectionType */: + case 185 /* ConditionalType */: + case 187 /* ParenthesizedType */: + case 188 /* ThisType */: + case 189 /* TypeOperator */: + case 190 /* IndexedAccessType */: + case 191 /* MappedType */: + case 192 /* LiteralType */: // TypeScript type nodes are elided. // falls through - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: // TypeScript index signatures are elided. // falls through - case 161 /* Decorator */: + case 162 /* Decorator */: // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. // falls through - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return undefined; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects return visitPropertyDeclaration(node); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 166 /* Constructor */: + case 167 /* Constructor */: return visitConstructor(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return factory.createNotEmittedStatement(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: // This may be a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -83316,7 +85965,7 @@ var ts; // - index signatures // - method overload signatures return visitClassDeclaration(node); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: // This may be a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -83326,35 +85975,35 @@ var ts; // - index signatures // - method overload signatures return visitClassExpression(node); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: // This may be a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause return visitHeritageClause(node); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); - case 160 /* Parameter */: + case 161 /* Parameter */: // This may be a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: @@ -83364,40 +86013,40 @@ var ts; // - type annotations // - this parameters return visitParameter(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: // ParenthesizedExpressions are TypeScript if their expression is a // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 206 /* TypeAssertionExpression */: - case 224 /* AsExpression */: + case 207 /* TypeAssertionExpression */: + case 225 /* AsExpression */: // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return visitNewExpression(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node); - case 275 /* JsxOpeningElement */: + case 276 /* JsxOpeningElement */: return visitJsxJsxOpeningElement(node); default: // node contains some other TypeScript syntax @@ -83451,7 +86100,7 @@ var ts; return facts; } function hasTypeScriptClassSyntax(node) { - return !!(node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */); + return !!(node.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */); } function isClassLikeDeclarationWithTypeScriptSyntax(node) { return ts.some(node.decorators) @@ -83806,12 +86455,12 @@ var ts; */ function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return getAllDecoratorsOfAccessors(node, member); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return getAllDecoratorsOfMethod(member); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -83964,7 +86613,7 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); var descriptor = languageVersion > 0 /* ES3 */ - ? member.kind === 163 /* PropertyDeclaration */ + ? member.kind === 164 /* PropertyDeclaration */ // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it // should not invoke `Object.getOwnPropertyDescriptor`. ? factory.createVoidZero() @@ -84088,10 +86737,10 @@ var ts; */ function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */ - || kind === 163 /* PropertyDeclaration */; + return kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */ + || kind === 164 /* PropertyDeclaration */; } /** * Determines whether to emit the "design:returntype" metadata based on the node's kind. @@ -84101,7 +86750,7 @@ var ts; * @param node The node to test. */ function shouldAddReturnTypeMetadata(node) { - return node.kind === 165 /* MethodDeclaration */; + return node.kind === 166 /* MethodDeclaration */; } /** * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. @@ -84112,12 +86761,12 @@ var ts; */ function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return ts.getFirstConstructorWithBody(node) !== undefined; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return true; } return false; @@ -84134,15 +86783,15 @@ var ts; */ function serializeTypeOfNode(node) { switch (node.kind) { - case 163 /* PropertyDeclaration */: - case 160 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 161 /* Parameter */: return serializeTypeNode(node.type); - case 168 /* SetAccessor */: - case 167 /* GetAccessor */: + case 169 /* SetAccessor */: + case 168 /* GetAccessor */: return serializeTypeNode(getAccessorTypeNode(node)); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 165 /* MethodDeclaration */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 166 /* MethodDeclaration */: return factory.createIdentifier("Function"); default: return factory.createVoidZero(); @@ -84179,7 +86828,7 @@ var ts; return factory.createArrayLiteralExpression(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 167 /* GetAccessor */) { + if (container && node.kind === 168 /* GetAccessor */) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -84228,27 +86877,27 @@ var ts; case 150 /* UndefinedKeyword */: case 141 /* NeverKeyword */: return factory.createVoidZero(); - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return serializeTypeNode(node.type); - case 174 /* FunctionType */: - case 175 /* ConstructorType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: return factory.createIdentifier("Function"); - case 178 /* ArrayType */: - case 179 /* TupleType */: + case 179 /* ArrayType */: + case 180 /* TupleType */: return factory.createIdentifier("Array"); - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: case 131 /* BooleanKeyword */: return factory.createIdentifier("Boolean"); case 147 /* StringKeyword */: return factory.createIdentifier("String"); case 145 /* ObjectKeyword */: return factory.createIdentifier("Object"); - case 191 /* LiteralType */: + case 192 /* LiteralType */: switch (node.literal.kind) { case 10 /* StringLiteral */: case 14 /* NoSubstitutionTemplateLiteral */: return factory.createIdentifier("String"); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: case 8 /* NumericLiteral */: return factory.createIdentifier("Number"); case 9 /* BigIntLiteral */: @@ -84269,37 +86918,37 @@ var ts; return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : factory.createIdentifier("Symbol"); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return serializeTypeReferenceNode(node); - case 183 /* IntersectionType */: - case 182 /* UnionType */: + case 184 /* IntersectionType */: + case 183 /* UnionType */: return serializeTypeList(node.types); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return serializeTypeList([node.trueType, node.falseType]); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: if (node.operator === 142 /* ReadonlyKeyword */) { return serializeTypeNode(node.type); } break; - case 176 /* TypeQuery */: - case 189 /* IndexedAccessType */: - case 190 /* MappedType */: - case 177 /* TypeLiteral */: + case 177 /* TypeQuery */: + case 190 /* IndexedAccessType */: + case 191 /* MappedType */: + case 178 /* TypeLiteral */: case 128 /* AnyKeyword */: case 152 /* UnknownKeyword */: - case 187 /* ThisType */: - case 195 /* ImportType */: + case 188 /* ThisType */: + case 196 /* ImportType */: break; // handle JSDoc types from an invalid parse - case 303 /* JSDocAllType */: - case 304 /* JSDocUnknownType */: - case 308 /* JSDocFunctionType */: - case 309 /* JSDocVariadicType */: - case 310 /* JSDocNamepathType */: + case 304 /* JSDocAllType */: + case 305 /* JSDocUnknownType */: + case 309 /* JSDocFunctionType */: + case 310 /* JSDocVariadicType */: + case 311 /* JSDocNamepathType */: break; - case 305 /* JSDocNullableType */: - case 306 /* JSDocNonNullableType */: - case 307 /* JSDocOptionalType */: + case 306 /* JSDocNullableType */: + case 307 /* JSDocNonNullableType */: + case 308 /* JSDocOptionalType */: return serializeTypeNode(node.type); default: return ts.Debug.failBadSyntaxKind(node); @@ -84312,13 +86961,13 @@ var ts; var serializedUnion; for (var _i = 0, types_24 = types; _i < types_24.length; _i++) { var typeNode = types_24[_i]; - while (typeNode.kind === 186 /* ParenthesizedType */) { + while (typeNode.kind === 187 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } if (typeNode.kind === 141 /* NeverKeyword */) { continue; // Always elide `never` from the union/intersection if possible } - if (!strictNullChecks && (typeNode.kind === 191 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { + if (!strictNullChecks && (typeNode.kind === 192 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) { continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } var serializedIndividual = serializeTypeNode(typeNode); @@ -84428,7 +87077,7 @@ var ts; name.original = undefined; ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node. return name; - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return serializeQualifiedNameAsExpression(node); } } @@ -84816,8 +87465,7 @@ var ts; */ function shouldEmitEnumDeclaration(node) { return !ts.isEnumConst(node) - || compilerOptions.preserveConstEnums - || compilerOptions.isolatedModules; + || ts.shouldPreserveConstEnums(compilerOptions); } /** * Visits an enum declaration. @@ -84951,7 +87599,7 @@ var ts; // If we can't find a parse tree node, assume the node is instantiated. return true; } - return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions)); } /** * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` @@ -85002,12 +87650,12 @@ var ts; // enums in any other scope are emitted as a `let` declaration. var statement = factory.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.createVariableDeclarationList([ factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ], currentLexicalScope.kind === 297 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ], currentLexicalScope.kind === 298 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { // Adjust the source map emit to match the old emitter. - if (node.kind === 255 /* EnumDeclaration */) { + if (node.kind === 256 /* EnumDeclaration */) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -85132,7 +87780,7 @@ var ts; var statementsLocation; var blockLocation; if (node.body) { - if (node.body.kind === 257 /* ModuleBlock */) { + if (node.body.kind === 258 /* ModuleBlock */) { saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = node.body.statements; blockLocation = node.body; @@ -85179,13 +87827,13 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (!node.body || node.body.kind !== 257 /* ModuleBlock */) { + if (!node.body || node.body.kind !== 258 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 256 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 257 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -85235,7 +87883,7 @@ var ts; * @param node The named import bindings node. */ function visitNamedImportBindings(node) { - if (node.kind === 263 /* NamespaceImport */) { + if (node.kind === 264 /* NamespaceImport */) { // Elide a namespace import if it is not referenced. return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } @@ -85488,16 +88136,16 @@ var ts; // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to // substitute the names of exported members of a namespace. context.enableSubstitution(78 /* Identifier */); - context.enableSubstitution(289 /* ShorthandPropertyAssignment */); + context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // We need to be notified when entering and exiting namespaces. - context.enableEmitNotification(256 /* ModuleDeclaration */); + context.enableEmitNotification(257 /* ModuleDeclaration */); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 256 /* ModuleDeclaration */; + return ts.getOriginalNode(node).kind === 257 /* ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 255 /* EnumDeclaration */; + return ts.getOriginalNode(node).kind === 256 /* EnumDeclaration */; } /** * Hook for node emit. @@ -85558,9 +88206,9 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return substituteExpressionIdentifier(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return substituteElementAccessExpression(node); } return node; @@ -85582,10 +88230,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_1 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_1, node); - ts.setCommentRange(clone_1, node); - return clone_1; + var clone_2 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_2, node); + ts.setCommentRange(clone_2, node); + return clone_2; } } } @@ -85598,9 +88246,9 @@ var ts; // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container && container.kind !== 297 /* SourceFile */) { - var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 256 /* ModuleDeclaration */) || - (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 255 /* EnumDeclaration */); + if (container && container.kind !== 298 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 257 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 256 /* EnumDeclaration */); if (substitute) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(container), node), /*location*/ node); @@ -85652,10 +88300,12 @@ var ts; */ ClassPropertySubstitutionFlags[ClassPropertySubstitutionFlags["ClassAliases"] = 1] = "ClassAliases"; })(ClassPropertySubstitutionFlags || (ClassPropertySubstitutionFlags = {})); - var PrivateIdentifierPlacement; - (function (PrivateIdentifierPlacement) { - PrivateIdentifierPlacement[PrivateIdentifierPlacement["InstanceField"] = 0] = "InstanceField"; - })(PrivateIdentifierPlacement || (PrivateIdentifierPlacement = {})); + var PrivateIdentifierKind; + (function (PrivateIdentifierKind) { + PrivateIdentifierKind["Field"] = "f"; + PrivateIdentifierKind["Method"] = "m"; + PrivateIdentifierKind["Accessor"] = "a"; + })(PrivateIdentifierKind = ts.PrivateIdentifierKind || (ts.PrivateIdentifierKind = {})); /** * Transforms ECMAScript Class Syntax. * TypeScript parameter property syntax is transformed in the TypeScript transformer. @@ -85664,11 +88314,12 @@ var ts; * When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty. */ function transformClassFields(context) { - var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment; + var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, addBlockScopedVariable = context.addBlockScopedVariable; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var shouldTransformPrivateFields = languageVersion < 99 /* ESNext */; + var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); + var shouldTransformPrivateElements = languageVersion < 99 /* ESNext */; var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; var enabledSubstitutions; @@ -85689,7 +88340,7 @@ var ts; function transformSourceFile(node) { var options = context.getCompilerOptions(); if (node.isDeclarationFile - || options.useDefineForClassFields && options.target === 99 /* ESNext */) { + || useDefineForClassFields && options.target === 99 /* ESNext */) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -85697,41 +88348,41 @@ var ts; return visited; } function visitor(node) { - if (!(node.transformFlags & 4194304 /* ContainsClassFields */)) + if (!(node.transformFlags & 8388608 /* ContainsClassFields */)) return node; switch (node.kind) { - case 221 /* ClassExpression */: - case 252 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 253 /* ClassDeclaration */: return visitClassLike(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return visitPropertyDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return visitPropertyAccessExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return visitPrefixUnaryExpression(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return visitPostfixUnaryExpression(node, /*valueIsDiscarded*/ false); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node); case 79 /* PrivateIdentifier */: return visitPrivateIdentifier(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitExpressionStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); } return ts.visitEachChild(node, visitor, context); } function visitorDestructuringTarget(node) { switch (node.kind) { - case 200 /* ObjectLiteralExpression */: - case 199 /* ArrayLiteralExpression */: + case 201 /* ObjectLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitAssignmentPattern(node); default: return visitor(node); @@ -85742,7 +88393,7 @@ var ts; * Replace it with an empty identifier to indicate a problem with the code. */ function visitPrivateIdentifier(node) { - if (!shouldTransformPrivateFields) { + if (!shouldTransformPrivateElements) { return node; } return ts.setOriginalNode(factory.createIdentifier(""), node); @@ -85754,20 +88405,19 @@ var ts; */ function classElementVisitor(node) { switch (node.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: // Constructors for classes using class fields are transformed in // `visitClassDeclaration` or `visitClassExpression`. return undefined; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 165 /* MethodDeclaration */: - // Visit the name of the member (if it's a computed property name). - return ts.visitEachChild(node, classElementVisitor, context); - case 163 /* PropertyDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 166 /* MethodDeclaration */: + return visitMethodOrAccessorDeclaration(node); + case 164 /* PropertyDeclaration */: return visitPropertyDeclaration(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: return node; default: return visitor(node); @@ -85792,44 +88442,96 @@ var ts; } return node; } + function visitMethodOrAccessorDeclaration(node) { + ts.Debug.assert(!ts.some(node.decorators)); + if (!shouldTransformPrivateElements || !ts.isPrivateIdentifier(node.name)) { + return ts.visitEachChild(node, classElementVisitor, context); + } + // leave invalid code untransformed + var info = accessPrivateIdentifier(node.name); + ts.Debug.assert(info, "Undeclared private name for property declaration."); + if (!info.isValid) { + return node; + } + var functionName = getHoistedFunctionName(node); + if (functionName) { + getPendingExpressions().push(factory.createAssignment(functionName, factory.createFunctionExpression(ts.filter(node.modifiers, function (m) { return !ts.isStaticModifier(m); }), node.asteriskToken, functionName, + /* typeParameters */ undefined, ts.visitParameterList(node.parameters, classElementVisitor, context), + /* type */ undefined, ts.visitFunctionBody(node.body, classElementVisitor, context)))); + } + // remove method declaration from class + return undefined; + } + function getHoistedFunctionName(node) { + ts.Debug.assert(ts.isPrivateIdentifier(node.name)); + var info = accessPrivateIdentifier(node.name); + ts.Debug.assert(info, "Undeclared private name for property declaration."); + if (info.kind === "m" /* Method */) { + return info.methodName; + } + if (info.kind === "a" /* Accessor */) { + if (ts.isGetAccessor(node)) { + return info.getterName; + } + if (ts.isSetAccessor(node)) { + return info.setterName; + } + } + } function visitPropertyDeclaration(node) { ts.Debug.assert(!ts.some(node.decorators)); - if (!shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) { - // Initializer is elided as the field is initialized in transformConstructor. - return factory.updatePropertyDeclaration(node, - /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, - /*questionOrExclamationToken*/ undefined, - /*type*/ undefined, - /*initializer*/ undefined); + if (ts.isPrivateIdentifier(node.name)) { + if (!shouldTransformPrivateElements) { + // Initializer is elided as the field is initialized in transformConstructor. + return factory.updatePropertyDeclaration(node, + /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined); + } + // leave invalid code untransformed + var info = accessPrivateIdentifier(node.name); + ts.Debug.assert(info, "Undeclared private name for property declaration."); + if (!info.isValid) { + return node; + } } // Create a temporary variable to store a computed property name (if necessary). // If it's not inlineable, then we emit an expression after the class which assigns // the property name to the temporary variable. - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { getPendingExpressions().push(expr); } return undefined; } function createPrivateIdentifierAccess(info, receiver) { - receiver = ts.visitNode(receiver, visitor, ts.isExpression); - switch (info.placement) { - case 0 /* InstanceField */: - return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(ts.nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver), info.weakMapName); - default: return ts.Debug.fail("Unexpected private identifier placement"); + return createPrivateIdentifierAccessHelper(info, ts.visitNode(receiver, visitor, ts.isExpression)); + } + function createPrivateIdentifierAccessHelper(info, receiver) { + ts.setCommentRange(receiver, ts.moveRangePos(receiver, -1)); + switch (info.kind) { + case "a" /* Accessor */: + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.getterName); + case "m" /* Method */: + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.methodName); + case "f" /* Field */: + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(receiver, info.brandCheckIdentifier, info.kind, info.variableName); + default: + ts.Debug.assertNever(info, "Unknown private element type"); } } function visitPropertyAccessExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifier(node.name)) { var privateIdentifierInfo = accessPrivateIdentifier(node.name); if (privateIdentifierInfo) { - return ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node); + return ts.setTextRange(ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node), node); } } return ts.visitEachChild(node, visitor, context); } function visitPrefixUnaryExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { var operator = node.operator === 45 /* PlusPlusToken */ ? 39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ? 40 /* MinusToken */ : undefined; @@ -85844,7 +88546,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitPostfixUnaryExpression(node, valueIsDiscarded) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) { var operator = node.operator === 45 /* PlusPlusToken */ ? 39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ? 40 /* MinusToken */ : undefined; @@ -85865,7 +88567,7 @@ var ts; } function visitForStatement(node) { if (node.incrementor && ts.isPostfixUnaryExpression(node.incrementor)) { - return factory.updateForStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), visitPostfixUnaryExpression(node.incrementor, /*valueIsDiscarded*/ true), ts.visitNode(node.statement, visitor, ts.isStatement)); + return factory.updateForStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), visitPostfixUnaryExpression(node.incrementor, /*valueIsDiscarded*/ true), ts.visitIterationBody(node.statement, visitor, context)); } return ts.visitEachChild(node, visitor, context); } @@ -85885,16 +88587,21 @@ var ts; return { readExpression: readExpression, initializeExpression: initializeExpression }; } function visitCallExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) { // Transform call expressions of private names to properly bind the `this` parameter. var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; + if (ts.isCallChain(node)) { + return factory.updateCallChain(node, factory.createPropertyAccessChain(ts.visitNode(target, visitor), node.questionDotToken, "call"), + /*questionDotToken*/ undefined, + /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); + } return factory.updateCallExpression(node, factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "call"), /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression))); } return ts.visitEachChild(node, visitor, context); } function visitTaggedTemplateExpression(node) { - if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) { // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access. var _a = factory.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target; return factory.updateTaggedTemplateExpression(node, factory.createCallExpression(factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "bind"), @@ -85904,7 +88611,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitBinaryExpression(node) { - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { if (ts.isDestructuringAssignment(node)) { var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; @@ -85918,29 +88625,31 @@ var ts; if (ts.isAssignmentExpression(node) && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) { var info = accessPrivateIdentifier(node.left.name); if (info) { - return ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node); + return ts.setTextRange(ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node), node); } } } return ts.visitEachChild(node, visitor, context); } function createPrivateIdentifierAssignment(info, receiver, right, operator) { - switch (info.placement) { - case 0 /* InstanceField */: { - return createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator); - } - default: return ts.Debug.fail("Unexpected private identifier placement"); - } - } - function createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator) { receiver = ts.visitNode(receiver, visitor, ts.isExpression); right = ts.visitNode(right, visitor, ts.isExpression); if (ts.isCompoundAssignment(operator)) { var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression; - return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(initializeExpression || readExpression, info.weakMapName, factory.createBinaryExpression(context.getEmitHelperFactory().createClassPrivateFieldGetHelper(readExpression, info.weakMapName), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right)); - } - else { - return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.weakMapName, right); + receiver = initializeExpression || readExpression; + right = factory.createBinaryExpression(createPrivateIdentifierAccessHelper(info, readExpression), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right); + } + ts.setCommentRange(receiver, ts.moveRangePos(receiver, -1)); + switch (info.kind) { + case "a" /* Accessor */: + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, info.setterName); + case "m" /* Method */: + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, + /* f */ undefined); + case "f" /* Field */: + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.brandCheckIdentifier, right, info.kind, info.variableName); + default: + ts.Debug.assertNever(info, "Unknown private element type"); } } /** @@ -85949,25 +88658,43 @@ var ts; function visitClassLike(node) { var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { startPrivateIdentifierEnvironment(); + var name = ts.getNameOfDeclaration(node); + if (name && ts.isIdentifier(name)) { + getPrivateIdentifierEnvironment().className = ts.idText(name); + } + var privateInstanceMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); + if (ts.some(privateInstanceMethodsAndAccessors)) { + getPrivateIdentifierEnvironment().weakSetName = createHoistedVariableForClass("instances", privateInstanceMethodsAndAccessors[0].name); + } } var result = ts.isClassDeclaration(node) ? visitClassDeclaration(node) : visitClassExpression(node); - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { endPrivateIdentifierEnvironment(); } pendingExpressions = savedPendingExpressions; return result; } function doesClassElementNeedTransform(node) { - return ts.isPropertyDeclaration(node) || (shouldTransformPrivateFields && node.name && ts.isPrivateIdentifier(node.name)); + return ts.isPropertyDeclaration(node) || (shouldTransformPrivateElements && node.name && ts.isPrivateIdentifier(node.name)); + } + function getPrivateInstanceMethodsAndAccessors(node) { + return ts.filter(node.members, ts.isNonStaticMethodOrAccessorWithPrivateName); } function visitClassDeclaration(node) { if (!ts.forEach(node.members, doesClassElementNeedTransform)) { return ts.visitEachChild(node, visitor, context); } + var staticProperties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ true); + var pendingPrivateStateAssignment; + if (shouldTransformPrivateElements && ts.some(node.members, function (m) { return ts.hasStaticModifier(m) && !!m.name && ts.isPrivateIdentifier(m.name); })) { + var temp = factory.createTempVariable(hoistVariableDeclaration, /* reservedInNestedScopes */ true); + getPrivateIdentifierEnvironment().classConstructor = factory.cloneNode(temp); + pendingPrivateStateAssignment = factory.createAssignment(temp, factory.getInternalName(node)); + } var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */); var statements = [ @@ -85975,6 +88702,9 @@ var ts; /*decorators*/ undefined, node.modifiers, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)) ]; + if (pendingPrivateStateAssignment) { + getPendingExpressions().unshift(pendingPrivateStateAssignment); + } // Write any pending expressions from elided or moved computed property names if (ts.some(pendingExpressions)) { statements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))); @@ -85984,7 +88714,6 @@ var ts; // From ES6 specification: // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. - var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); if (ts.some(staticProperties)) { addPropertyStatements(statements, staticProperties, factory.getInternalName(node)); } @@ -86002,12 +88731,25 @@ var ts; // class declaration transformation. The VariableStatement visitor will insert // these statements after the class expression variable statement. var isDecoratedClassDeclaration = ts.isClassDeclaration(ts.getOriginalNode(node)); - var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); + var staticProperties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ true); var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */); + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; + var temp; + function createClassTempVar() { + var classCheckFlags = resolver.getNodeCheckFlags(node); + var isClassWithConstructorReference = classCheckFlags & 16777216 /* ClassWithConstructorReference */; + var requiresBlockScopedVar = classCheckFlags & 524288 /* BlockScopedBindingInLoop */; + return factory.createTempVariable(requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, !!isClassWithConstructorReference); + } + if (shouldTransformPrivateElements && ts.some(node.members, function (m) { return ts.hasStaticModifier(m) && !!m.name && ts.isPrivateIdentifier(m.name); })) { + temp = createClassTempVar(); + getPrivateIdentifierEnvironment().classConstructor = factory.cloneNode(temp); + } var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)); - if (ts.some(staticProperties) || ts.some(pendingExpressions)) { + var hasTransformableStatics = ts.some(staticProperties, function (p) { return !!p.initializer || (shouldTransformPrivateElements && ts.isPrivateIdentifier(p.name)); }); + if (hasTransformableStatics || ts.some(pendingExpressions)) { if (isDecoratedClassDeclaration) { ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration."); // Write any pending expressions from elided or moved computed property names @@ -86017,12 +88759,14 @@ var ts; if (pendingStatements && ts.some(staticProperties)) { addPropertyStatements(pendingStatements, staticProperties, factory.getInternalName(node)); } + if (temp) { + return factory.inlineExpressions([factory.createAssignment(temp, classExpression), temp]); + } return classExpression; } else { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; - var temp = factory.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + temp || (temp = createClassTempVar()); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); @@ -86044,14 +88788,17 @@ var ts; return classExpression; } function transformClassMembers(node, isDerivedClass) { - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { // Declare private names. for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (ts.isPrivateIdentifierPropertyDeclaration(member)) { - addPrivateIdentifierToEnvironment(member.name); + if (ts.isPrivateIdentifierClassElementDeclaration(member)) { + addPrivateIdentifierToEnvironment(member); } } + if (ts.some(getPrivateInstanceMethodsAndAccessors(node))) { + createBrandCheckWeakSetForPrivateMethods(); + } } var members = []; var constructor = transformConstructor(node, isDerivedClass); @@ -86061,21 +88808,27 @@ var ts; ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members); } - function isPropertyDeclarationThatRequiresConstructorStatement(member) { - if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* Abstract */)) { + function createBrandCheckWeakSetForPrivateMethods() { + var weakSetName = getPrivateIdentifierEnvironment().weakSetName; + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + getPendingExpressions().push(factory.createAssignment(weakSetName, factory.createNewExpression(factory.createIdentifier("WeakSet"), + /*typeArguments*/ undefined, []))); + } + function isClassElementThatRequiresConstructorStatement(member) { + if (ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* Abstract */)) { return false; } - if (context.getCompilerOptions().useDefineForClassFields) { + if (useDefineForClassFields) { // If we are using define semantics and targeting ESNext or higher, // then we don't need to transform any class properties. return languageVersion < 99 /* ESNext */; } - return ts.isInitializedProperty(member) || shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyDeclaration(member); + return ts.isInitializedProperty(member) || shouldTransformPrivateElements && ts.isPrivateIdentifierClassElementDeclaration(member); } function transformConstructor(node, isDerivedClass) { var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration); - var properties = node.members.filter(isPropertyDeclarationThatRequiresConstructorStatement); - if (!ts.some(properties)) { + var elements = node.members.filter(isClassElementThatRequiresConstructorStatement); + if (!ts.some(elements)) { return constructor; } var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context); @@ -86088,13 +88841,14 @@ var ts; /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { - var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false); if (!useDefineForClassFields) { properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); }); } + var privateMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); + var needsConstructorBody = ts.some(properties) || ts.some(privateMethodsAndAccessors); // Only generate synthetic constructor when there are property initializers to move. - if (!constructor && !ts.some(properties)) { + if (!constructor && !needsConstructorBody) { return ts.visitFunctionBody(/*node*/ undefined, visitor, context); } resumeLexicalEnvironment(); @@ -86133,7 +88887,10 @@ var ts; indexOfFirstStatement = afterParameterProperties; } } - addPropertyStatements(statements, properties, factory.createThis()); + var receiver = factory.createThis(); + // private methods can be called in property initializers, they should execute first. + addMethodStatements(statements, privateMethodsAndAccessors, receiver); + addPropertyStatements(statements, properties, receiver); // Add existing statements, skipping the initial super call. if (constructor) { ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); @@ -86195,27 +88952,30 @@ var ts; function transformProperty(property, receiver) { var _a; // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) - var emitAssignment = !context.getCompilerOptions().useDefineForClassFields; + var emitAssignment = !useDefineForClassFields; var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression) ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name)) : property.name; - if (shouldTransformPrivateFields && ts.isPrivateIdentifier(propertyName)) { + if (shouldTransformPrivateElements && ts.isPrivateIdentifier(propertyName)) { var privateIdentifierInfo = accessPrivateIdentifier(propertyName); if (privateIdentifierInfo) { - switch (privateIdentifierInfo.placement) { - case 0 /* InstanceField */: { - return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.weakMapName); + if (privateIdentifierInfo.kind === "f" /* Field */) { + if (!privateIdentifierInfo.isStatic) { + return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.brandCheckIdentifier); } + else { + return createPrivateStaticFieldInitializer(privateIdentifierInfo.variableName, ts.visitNode(property.initializer, visitor, ts.isExpression)); + } + } + else { + return undefined; } } else { ts.Debug.fail("Undeclared private name for property declaration."); } } - if (ts.isPrivateIdentifier(propertyName) && !property.initializer) { - return undefined; - } - if (ts.isPrivateIdentifier(propertyName) && !property.initializer) { + if ((ts.isPrivateIdentifier(propertyName) || ts.hasStaticModifier(property)) && !property.initializer) { return undefined; } var propertyOriginalNode = ts.getOriginalNode(property); @@ -86247,6 +89007,21 @@ var ts; classAliases = []; } } + /** + * Generates brand-check initializer for private methods. + * + * @param statements Statement list that should be used to append new statements. + * @param methods An array of method declarations. + * @param receiver The receiver on which each method should be assigned. + */ + function addMethodStatements(statements, methods, receiver) { + if (!shouldTransformPrivateElements || !ts.some(methods)) { + return; + } + var weakSetName = getPrivateIdentifierEnvironment().weakSetName; + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + statements.push(factory.createExpressionStatement(createPrivateInstanceMethodInitializer(receiver, weakSetName))); + } /** * Hooks node substitutions. * @@ -86282,10 +89057,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { - var clone_2 = factory.cloneNode(classAlias); - ts.setSourceMapRange(clone_2, node); - ts.setCommentRange(clone_2, node); - return clone_2; + var clone_3 = factory.cloneNode(classAlias); + ts.setSourceMapRange(clone_3, node); + ts.setCommentRange(clone_3, node); + return clone_3; } } } @@ -86305,7 +89080,12 @@ var ts; var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left); if (!alreadyTransformed && !inlinable && shouldHoist) { var generatedName = factory.getGeneratedNameForNode(name); - hoistVariableDeclaration(generatedName); + if (resolver.getNodeCheckFlags(name) & 524288 /* BlockScopedBindingInLoop */) { + addBlockScopedVariable(generatedName); + } + else { + hoistVariableDeclaration(generatedName); + } return factory.createAssignment(generatedName, expression); } return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression; @@ -86319,22 +89099,164 @@ var ts; currentPrivateIdentifierEnvironment = privateIdentifierEnvironmentStack.pop(); } function getPrivateIdentifierEnvironment() { - return currentPrivateIdentifierEnvironment || (currentPrivateIdentifierEnvironment = new ts.Map()); + if (!currentPrivateIdentifierEnvironment) { + currentPrivateIdentifierEnvironment = { + className: "", + identifiers: new ts.Map() + }; + } + return currentPrivateIdentifierEnvironment; } function getPendingExpressions() { return pendingExpressions || (pendingExpressions = []); } - function addPrivateIdentifierToEnvironment(name) { - var text = ts.getTextOfPropertyName(name); - var weakMapName = factory.createUniqueName("_" + text.substring(1), 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */); - hoistVariableDeclaration(weakMapName); - getPrivateIdentifierEnvironment().set(name.escapedText, { placement: 0 /* InstanceField */, weakMapName: weakMapName }); - getPendingExpressions().push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), - /*typeArguments*/ undefined, []))); + function addPrivateIdentifierToEnvironment(node) { + var _a; + var text = ts.getTextOfPropertyName(node.name); + var env = getPrivateIdentifierEnvironment(); + var weakSetName = env.weakSetName, classConstructor = env.classConstructor; + var assignmentExpressions = []; + var privateName = node.name.escapedText; + var previousInfo = env.identifiers.get(privateName); + var isValid = !isReservedPrivateName(node.name) && previousInfo === undefined; + if (ts.hasStaticModifier(node)) { + ts.Debug.assert(classConstructor, "weakSetName should be set in private identifier environment"); + if (ts.isPropertyDeclaration(node)) { + var variableName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: "f" /* Field */, + variableName: variableName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + else if (ts.isMethodDeclaration(node)) { + var functionName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: "m" /* Method */, + methodName: functionName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + else if (ts.isGetAccessorDeclaration(node)) { + var getterName = createHoistedVariableForPrivateName(text + "_get", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic && !previousInfo.getterName) { + previousInfo.getterName = getterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: getterName, + setterName: undefined, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + } + else if (ts.isSetAccessorDeclaration(node)) { + var setterName = createHoistedVariableForPrivateName(text + "_set", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && previousInfo.isStatic && !previousInfo.setterName) { + previousInfo.setterName = setterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: undefined, + setterName: setterName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid: isValid, + }); + } + } + else { + ts.Debug.assertNever(node, "Unknown class element type."); + } + } + else if (ts.isPropertyDeclaration(node)) { + var weakMapName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: "f" /* Field */, + brandCheckIdentifier: weakMapName, + isStatic: false, + variableName: undefined, + isValid: isValid, + }); + assignmentExpressions.push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), + /*typeArguments*/ undefined, []))); + } + else if (ts.isMethodDeclaration(node)) { + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + env.identifiers.set(privateName, { + kind: "m" /* Method */, + methodName: createHoistedVariableForPrivateName(text, node), + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + else if (ts.isAccessor(node)) { + ts.Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + if (ts.isGetAccessor(node)) { + var getterName = createHoistedVariableForPrivateName(text + "_get", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && !previousInfo.isStatic && !previousInfo.getterName) { + previousInfo.getterName = getterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: getterName, + setterName: undefined, + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + } + else { + var setterName = createHoistedVariableForPrivateName(text + "_set", node); + if ((previousInfo === null || previousInfo === void 0 ? void 0 : previousInfo.kind) === "a" /* Accessor */ && !previousInfo.isStatic && !previousInfo.setterName) { + previousInfo.setterName = setterName; + } + else { + env.identifiers.set(privateName, { + kind: "a" /* Accessor */, + getterName: undefined, + setterName: setterName, + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid: isValid, + }); + } + } + } + else { + ts.Debug.assertNever(node, "Unknown class element type."); + } + (_a = getPendingExpressions()).push.apply(_a, assignmentExpressions); + } + function createHoistedVariableForClass(name, node) { + var className = getPrivateIdentifierEnvironment().className; + var prefix = className ? "_" + className : ""; + var identifier = factory.createUniqueName(prefix + "_" + name, 16 /* Optimistic */); + if (resolver.getNodeCheckFlags(node) & 524288 /* BlockScopedBindingInLoop */) { + addBlockScopedVariable(identifier); + } + else { + hoistVariableDeclaration(identifier); + } + return identifier; + } + function createHoistedVariableForPrivateName(privateName, node) { + return createHoistedVariableForClass(privateName.substring(1), node.name); } function accessPrivateIdentifier(name) { if (currentPrivateIdentifierEnvironment) { - var info = currentPrivateIdentifierEnvironment.get(name.escapedText); + var info = currentPrivateIdentifierEnvironment.identifiers.get(name.escapedText); if (info) { return info; } @@ -86344,7 +89266,7 @@ var ts; if (!env) { continue; } - var info = env.get(name.escapedText); + var info = env.identifiers.get(name.escapedText); if (info) { return info; } @@ -86430,10 +89352,22 @@ var ts; } } ts.transformClassFields = transformClassFields; + function createPrivateStaticFieldInitializer(variableName, initializer) { + return ts.factory.createAssignment(variableName, ts.factory.createObjectLiteralExpression([ + ts.factory.createPropertyAssignment("value", initializer || ts.factory.createVoidZero()) + ])); + } function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) { return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakMapName, "set"), /*typeArguments*/ undefined, [receiver, initializer || ts.factory.createVoidZero()]); } + function createPrivateInstanceMethodInitializer(receiver, weakSetName) { + return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakSetName, "add"), + /*typeArguments*/ undefined, [receiver]); + } + function isReservedPrivateName(node) { + return node.escapedText === "#constructor"; + } })(ts || (ts = {})); /*@internal*/ var ts; @@ -86516,38 +89450,38 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 64 /* ContainsES2017 */) === 0) { + if ((node.transformFlags & 128 /* ContainsES2017 */) === 0) { return node; } switch (node.kind) { case 129 /* AsyncKeyword */: // ES2017 async modifier should be elided for targets < ES2017 return undefined; - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return visitAwaitExpression(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105 /* SuperKeyword */) { capturedSuperProperties.add(node.name.escapedText); } return ts.visitEachChild(node, visitor, context); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: if (capturedSuperProperties && node.expression.kind === 105 /* SuperKeyword */) { hasSuperElementAccess = true; } return ts.visitEachChild(node, visitor, context); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 166 /* Constructor */: - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 167 /* Constructor */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node); default: return ts.visitEachChild(node, visitor, context); @@ -86556,27 +89490,27 @@ var ts; function asyncBodyVisitor(node) { if (ts.isNodeWithPossibleHoistedDeclaration(node)) { switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatementInAsyncBody(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatementInAsyncBody(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatementInAsyncBody(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatementInAsyncBody(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClauseInAsyncBody(node); - case 230 /* Block */: - case 244 /* SwitchStatement */: - case 258 /* CaseBlock */: - case 284 /* CaseClause */: - case 285 /* DefaultClause */: - case 247 /* TryStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 234 /* IfStatement */: - case 243 /* WithStatement */: - case 245 /* LabeledStatement */: + case 231 /* Block */: + case 245 /* SwitchStatement */: + case 259 /* CaseBlock */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: + case 248 /* TryStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 235 /* IfStatement */: + case 244 /* WithStatement */: + case 246 /* LabeledStatement */: return ts.visitEachChild(node, asyncBodyVisitor, context); default: return ts.Debug.assertNever(node, "Unhandled node."); @@ -86618,18 +89552,18 @@ var ts; function visitForInStatementInAsyncBody(node) { return factory.updateForInStatement(node, isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) - : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock)); + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context)); } function visitForOfStatementInAsyncBody(node) { return factory.updateForOfStatement(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) - : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock)); + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context)); } function visitForStatementInAsyncBody(node) { var initializer = node.initializer; // TODO: GH#18217 return factory.updateForStatement(node, isVariableDeclarationListWithCollidingName(initializer) ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false) - : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock)); + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitIterationBody(node.statement, asyncBodyVisitor, context)); } /** * Visits an AwaitExpression node. @@ -86781,7 +89715,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 209 /* ArrowFunction */; + var isArrowFunction = node.kind === 210 /* ArrowFunction */; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current @@ -86872,17 +89806,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(203 /* CallExpression */); - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(202 /* ElementAccessExpression */); + context.enableSubstitution(204 /* CallExpression */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(203 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(252 /* ClassDeclaration */); - context.enableEmitNotification(165 /* MethodDeclaration */); - context.enableEmitNotification(167 /* GetAccessor */); - context.enableEmitNotification(168 /* SetAccessor */); - context.enableEmitNotification(166 /* Constructor */); + context.enableEmitNotification(253 /* ClassDeclaration */); + context.enableEmitNotification(166 /* MethodDeclaration */); + context.enableEmitNotification(168 /* GetAccessor */); + context.enableEmitNotification(169 /* SetAccessor */); + context.enableEmitNotification(167 /* Constructor */); // We need to be notified when entering the generated accessor arrow functions. - context.enableEmitNotification(232 /* VariableStatement */); + context.enableEmitNotification(233 /* VariableStatement */); } } /** @@ -86930,11 +89864,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return substituteCallExpression(node); } return node; @@ -86966,11 +89900,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 252 /* ClassDeclaration */ - || kind === 166 /* Constructor */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 253 /* ClassDeclaration */ + || kind === 167 /* Constructor */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { @@ -87149,74 +90083,74 @@ var ts; * expression of an `ExpressionStatement`). */ function visitorWorker(node, expressionResultIsUnused) { - if ((node.transformFlags & 32 /* ContainsES2018 */) === 0) { + if ((node.transformFlags & 64 /* ContainsES2018 */) === 0) { return node; } switch (node.kind) { - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return visitAwaitExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitYieldExpression(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitReturnStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node, expressionResultIsUnused); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitCommaListExpression(node, expressionResultIsUnused); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 235 /* DoStatement */: - case 236 /* WhileStatement */: - case 238 /* ForInStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: + case 239 /* ForInStatement */: return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return visitVoidExpression(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 167 /* GetAccessor */: + case 168 /* GetAccessor */: return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 168 /* SetAccessor */: + case 169 /* SetAccessor */: return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */); - case 160 /* Parameter */: + case 161 /* Parameter */: return visitParameter(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitExpressionStatement(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, expressionResultIsUnused); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105 /* SuperKeyword */) { capturedSuperProperties.add(node.name.escapedText); } return ts.visitEachChild(node, visitor, context); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: if (capturedSuperProperties && node.expression.kind === 105 /* SuperKeyword */) { hasSuperElementAccess = true; } return ts.visitEachChild(node, visitor, context); - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); default: return ts.visitEachChild(node, visitor, context); @@ -87252,7 +90186,7 @@ var ts; function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 239 /* ForOfStatement */ && statement.awaitModifier) { + if (statement.kind === 240 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } return factory.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, factory.liftToBlock), node); @@ -87264,7 +90198,7 @@ var ts; var objects = []; for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { var e = elements_4[_i]; - if (e.kind === 290 /* SpreadAssignment */) { + if (e.kind === 291 /* SpreadAssignment */) { if (chunkObject) { objects.push(factory.createObjectLiteralExpression(chunkObject)); chunkObject = undefined; @@ -87273,7 +90207,7 @@ var ts; objects.push(ts.visitNode(target, visitor, ts.isExpression)); } else { - chunkObject = ts.append(chunkObject, e.kind === 288 /* PropertyAssignment */ + chunkObject = ts.append(chunkObject, e.kind === 289 /* PropertyAssignment */ ? factory.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } @@ -87284,7 +90218,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign(__assign({a}, o), {b}); @@ -87307,7 +90241,7 @@ var ts; // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we // end up with `{ a: 1, b: 2, c: 3 }` var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 200 /* ObjectLiteralExpression */) { + if (objects.length && objects[0].kind !== 201 /* ObjectLiteralExpression */) { objects.unshift(factory.createObjectLiteralExpression()); } var expression = objects[0]; @@ -87357,7 +90291,7 @@ var ts; * expression of an `ExpressionStatement`). */ function visitBinaryExpression(node, expressionResultIsUnused) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !expressionResultIsUnused); } if (node.operatorToken.kind === 27 /* CommaToken */) { @@ -87388,7 +90322,7 @@ var ts; function visitCatchClause(node) { if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name) && - node.variableDeclaration.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + node.variableDeclaration.name.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { var name = factory.getGeneratedNameForNode(node.variableDeclaration.name); var updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name); var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */); @@ -87429,14 +90363,14 @@ var ts; } function visitVariableDeclarationWorker(node, exportedVariableStatement) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */, /*rval*/ undefined, exportedVariableStatement); } return ts.visitEachChild(node, visitor, context); } function visitForStatement(node) { - return factory.updateForStatement(node, ts.visitNode(node.initializer, visitorWithUnusedExpressionResult, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitorWithUnusedExpressionResult, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement)); + return factory.updateForStatement(node, ts.visitNode(node.initializer, visitorWithUnusedExpressionResult, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitorWithUnusedExpressionResult, ts.isExpression), ts.visitIterationBody(node.statement, visitor, context)); } function visitVoidExpression(node) { return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context); @@ -87448,7 +90382,7 @@ var ts; */ function visitForOfStatement(node, outermostLabeledStatement) { var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); - if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (node.initializer.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } var result = node.awaitModifier ? @@ -87486,7 +90420,7 @@ var ts; var bodyLocation; var statementsLocation; var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; - var statement = ts.visitNode(node.statement, visitor, ts.isStatement); + var statement = ts.visitIterationBody(node.statement, visitor, context); if (ts.isBlock(statement)) { ts.addRange(statements, statement.statements); bodyLocation = statement; @@ -87548,7 +90482,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return factory.updateParameterDeclaration(node, @@ -87700,7 +90634,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 & 16384 /* ContainsObjectRestOrSpread */) { + if (parameter.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { var temp = factory.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -87720,17 +90654,17 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(203 /* CallExpression */); - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(202 /* ElementAccessExpression */); + context.enableSubstitution(204 /* CallExpression */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(203 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(252 /* ClassDeclaration */); - context.enableEmitNotification(165 /* MethodDeclaration */); - context.enableEmitNotification(167 /* GetAccessor */); - context.enableEmitNotification(168 /* SetAccessor */); - context.enableEmitNotification(166 /* Constructor */); + context.enableEmitNotification(253 /* ClassDeclaration */); + context.enableEmitNotification(166 /* MethodDeclaration */); + context.enableEmitNotification(168 /* GetAccessor */); + context.enableEmitNotification(169 /* SetAccessor */); + context.enableEmitNotification(167 /* Constructor */); // We need to be notified when entering the generated accessor arrow functions. - context.enableEmitNotification(232 /* VariableStatement */); + context.enableEmitNotification(233 /* VariableStatement */); } } /** @@ -87778,11 +90712,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return substituteCallExpression(node); } return node; @@ -87814,11 +90748,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 252 /* ClassDeclaration */ - || kind === 166 /* Constructor */ - || kind === 165 /* MethodDeclaration */ - || kind === 167 /* GetAccessor */ - || kind === 168 /* SetAccessor */; + return kind === 253 /* ClassDeclaration */ + || kind === 167 /* Constructor */ + || kind === 166 /* MethodDeclaration */ + || kind === 168 /* GetAccessor */ + || kind === 169 /* SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { @@ -87846,11 +90780,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 16 /* ContainsES2019 */) === 0) { + if ((node.transformFlags & 32 /* ContainsES2019 */) === 0) { return node; } switch (node.kind) { - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); @@ -87878,25 +90812,29 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 8 /* ContainsES2020 */) === 0) { + if ((node.transformFlags & 16 /* ContainsES2020 */) === 0) { return node; } switch (node.kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: - case 203 /* CallExpression */: - if (node.flags & 32 /* OptionalChain */) { + case 204 /* CallExpression */: { + var updated = visitNonOptionalCallExpression(node, /*captureThisArg*/ false); + ts.Debug.assertNotNode(updated, ts.isSyntheticReference); + return updated; + } + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: + if (ts.isOptionalChain(node)) { var updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false); ts.Debug.assertNotNode(updated, ts.isSyntheticReference); return updated; } return ts.visitEachChild(node, visitor, context); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: if (node.operatorToken.kind === 60 /* QuestionQuestionToken */) { return transformNullishCoalescingExpression(node); } return ts.visitEachChild(node, visitor, context); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return visitDeleteExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -87938,7 +90876,7 @@ var ts; thisArg = expression; } } - expression = node.kind === 201 /* PropertyAccessExpression */ + expression = node.kind === 202 /* PropertyAccessExpression */ ? factory.updatePropertyAccessExpression(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier)) : factory.updateElementAccessExpression(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression)); return thisArg ? factory.createSyntheticReferenceExpression(expression, thisArg) : expression; @@ -87948,14 +90886,23 @@ var ts; // If `node` is an optional chain, then it is the outermost chain of an optional expression. return visitOptionalExpression(node, captureThisArg, /*isDelete*/ false); } + if (ts.isParenthesizedExpression(node.expression) && ts.isOptionalChain(ts.skipParentheses(node.expression))) { + // capture thisArg for calls of parenthesized optional chains like `(foo?.bar)()` + var expression = visitNonOptionalParenthesizedExpression(node.expression, /*captureThisArg*/ true, /*isDelete*/ false); + var args = ts.visitNodes(node.arguments, visitor, ts.isExpression); + if (ts.isSyntheticReference(expression)) { + return ts.setTextRange(factory.createFunctionCallCall(expression.expression, expression.thisArg, args), node); + } + return factory.updateCallExpression(node, expression, /*typeArguments*/ undefined, args); + } return ts.visitEachChild(node, visitor, context); } function visitNonOptionalExpression(node, captureThisArg, isDelete) { switch (node.kind) { - case 207 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete); - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete); - case 203 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg); + case 208 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete); + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete); + case 204 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg); default: return ts.visitNode(node, visitor, ts.isExpression); } } @@ -87974,8 +90921,8 @@ var ts; for (var i = 0; i < chain.length; i++) { var segment = chain[i]; switch (segment.kind) { - case 201 /* PropertyAccessExpression */: - case 202 /* ElementAccessExpression */: + case 202 /* PropertyAccessExpression */: + case 203 /* ElementAccessExpression */: if (i === chain.length - 1 && captureThisArg) { if (!ts.isSimpleCopiableExpression(rightExpression)) { thisArg = factory.createTempVariable(hoistVariableDeclaration); @@ -87985,11 +90932,11 @@ var ts; thisArg = rightExpression; } } - rightExpression = segment.kind === 201 /* PropertyAccessExpression */ + rightExpression = segment.kind === 202 /* PropertyAccessExpression */ ? factory.createPropertyAccessExpression(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier)) : factory.createElementAccessExpression(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression)); break; - case 203 /* CallExpression */: + case 204 /* CallExpression */: if (i === 0 && leftThisArg) { rightExpression = factory.createFunctionCallCall(rightExpression, leftThisArg.kind === 105 /* SuperKeyword */ ? factory.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); } @@ -88032,7 +90979,7 @@ var ts; /*@internal*/ var ts; (function (ts) { - function transformESNext(context) { + function transformES2021(context) { var hoistVariableDeclaration = context.hoistVariableDeclaration, factory = context.factory; return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { @@ -88042,11 +90989,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 4 /* ContainsESNext */) === 0) { + if ((node.transformFlags & 8 /* ContainsES2021 */) === 0) { return node; } switch (node.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: var binaryExpression = node; if (ts.isLogicalOrCoalescingAssignmentExpression(binaryExpression)) { return transformLogicalAssignment(binaryExpression); @@ -88082,6 +91029,29 @@ var ts; return factory.createBinaryExpression(left, nonAssignmentOperator, factory.createParenthesizedExpression(factory.createAssignment(assignmentTarget, right))); } } + ts.transformES2021 = transformES2021; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformESNext(context) { + return ts.chainBundle(context, transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if ((node.transformFlags & 4 /* ContainsESNext */) === 0) { + return node; + } + switch (node.kind) { + default: + return ts.visitEachChild(node, visitor, context); + } + } + } ts.transformESNext = transformESNext; })(ts || (ts = {})); /*@internal*/ @@ -88192,13 +91162,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 273 /* JsxElement */: + case 274 /* JsxElement */: return visitJsxElement(node, /*isChild*/ false); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ false); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -88208,13 +91178,13 @@ var ts; switch (node.kind) { case 11 /* JsxText */: return visitJsxText(node); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return visitJsxExpression(node); - case 273 /* JsxElement */: + case 274 /* JsxElement */: return visitJsxElement(node, /*isChild*/ true); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ true); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ true); default: return ts.Debug.failBadSyntaxKind(node); @@ -88254,9 +91224,9 @@ var ts; function convertJsxChildrenToChildrenPropObject(children) { var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); if (ts.length(nonWhitespaceChildren) === 1) { - var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]); - return result_13 && factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("children", result_13) + var result_14 = transformJsxChildToExpression(nonWhitespaceChildren[0]); + return result_14 && factory.createObjectLiteralExpression([ + factory.createPropertyAssignment("children", result_14) ]); } var result = ts.mapDefined(children, transformJsxChildToExpression); @@ -88332,21 +91302,29 @@ var ts; // When there are no attributes, React wants "null" } else { - // Map spans of JsxAttribute nodes into object literals and spans - // of JsxSpreadAttribute nodes into expressions. - var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread - ? ts.map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); - if (ts.isJsxSpreadAttribute(attrs[0])) { - // We must always emit at least one object literal before a spread - // argument.factory.createObjectLiteral - segments.unshift(factory.createObjectLiteralExpression()); + var target = compilerOptions.target; + if (target && target >= 5 /* ES2018 */) { + objectProperties = factory.createObjectLiteralExpression(ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { + return isSpread ? ts.map(attrs, transformJsxSpreadAttributeToSpreadAssignment) : ts.map(attrs, transformJsxAttributeToObjectLiteralElement); + }))); } - // Either emit one big object literal (no spread attribs), or - // a call to the __assign helper. - objectProperties = ts.singleOrUndefined(segments); - if (!objectProperties) { - objectProperties = emitHelpers().createAssignHelper(segments); + else { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. + var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread + ? ts.map(attrs, transformJsxSpreadAttributeToExpression) + : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); })); + if (ts.isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument.factory.createObjectLiteral + segments.unshift(factory.createObjectLiteralExpression()); + } + // Either emit one big object literal (no spread attribs), or + // a call to the __assign helper. + objectProperties = ts.singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = emitHelpers().createAssignHelper(segments); + } } } var callee = currentFileState.importSpecifier === undefined @@ -88378,6 +91356,9 @@ var ts; } return element; } + function transformJsxSpreadAttributeToSpreadAssignment(node) { + return factory.createSpreadAssignment(ts.visitNode(node.expression, visitor, ts.isExpression)); + } function transformJsxSpreadAttributeToExpression(node) { return ts.visitNode(node.expression, visitor, ts.isExpression); } @@ -88397,7 +91378,7 @@ var ts; var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote); return ts.setTextRange(literal, node); } - else if (node.kind === 283 /* JsxExpression */) { + else if (node.kind === 284 /* JsxExpression */) { if (node.expression === undefined) { return factory.createTrue(); } @@ -88491,7 +91472,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 273 /* JsxElement */) { + if (node.kind === 274 /* JsxElement */) { return getTagName(node.openingElement); } else { @@ -88793,11 +91774,11 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 128 /* ContainsES2016 */) === 0) { + if ((node.transformFlags & 256 /* ContainsES2016 */) === 0) { return node; } switch (node.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -89010,11 +91991,11 @@ var ts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0 - && node.kind === 242 /* ReturnStatement */ + && node.kind === 243 /* ReturnStatement */ && !node.expression; } function isOrMayContainReturnCompletion(node) { - return node.transformFlags & 1048576 /* ContainsHoistedDeclarationOrCompletion */ + return node.transformFlags & 2097152 /* ContainsHoistedDeclarationOrCompletion */ && (ts.isReturnStatement(node) || ts.isIfStatement(node) || ts.isWithStatement(node) @@ -89029,7 +92010,7 @@ var ts; || ts.isBlock(node)); } function shouldVisitNode(node) { - return (node.transformFlags & 256 /* ContainsES2015 */) !== 0 + return (node.transformFlags & 512 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && isOrMayContainReturnCompletion(node)) || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) @@ -89051,65 +92032,65 @@ var ts; switch (node.kind) { case 123 /* StaticKeyword */: return undefined; // elide static keyword - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return visitClassDeclaration(node); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return visitClassExpression(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return visitParameter(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return visitArrowFunction(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return visitFunctionExpression(node); - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return visitVariableDeclaration(node); case 78 /* Identifier */: return visitIdentifier(node); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return visitVariableDeclarationList(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitSwitchStatement(node); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return visitCaseBlock(node); - case 230 /* Block */: + case 231 /* Block */: return visitBlock(node, /*isFunctionBody*/ false); - case 241 /* BreakStatement */: - case 240 /* ContinueStatement */: + case 242 /* BreakStatement */: + case 241 /* ContinueStatement */: return visitBreakOrContinueStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node, /*outermostLabeledStatement*/ undefined); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return visitExpressionStatement(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return visitShorthandPropertyAssignment(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return visitNewExpression(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, expressionResultIsUnused); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node, expressionResultIsUnused); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitCommaListExpression(node, expressionResultIsUnused); case 14 /* NoSubstitutionTemplateLiteral */: case 15 /* TemplateHead */: @@ -89120,30 +92101,30 @@ var ts; return visitStringLiteral(node); case 8 /* NumericLiteral */: return visitNumericLiteral(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return visitTemplateExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitYieldExpression(node); - case 220 /* SpreadElement */: + case 221 /* SpreadElement */: return visitSpreadElement(node); case 105 /* SuperKeyword */: return visitSuperKeyword(/*isExpressionOfCall*/ false); case 107 /* ThisKeyword */: return visitThisKeyword(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return visitMetaProperty(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return visitAccessorDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitReturnStatement(node); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return visitVoidExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -89233,14 +92214,14 @@ var ts; // it is possible if either // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement - var jump = node.kind === 241 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var jump = node.kind === 242 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; var label = node.label; if (!label) { - if (node.kind === 241 /* BreakStatement */) { + if (node.kind === 242 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; } @@ -89251,7 +92232,7 @@ var ts; } } else { - if (node.kind === 241 /* BreakStatement */) { + if (node.kind === 242 /* BreakStatement */) { labelMarker = "break-" + label.escapedText; setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); } @@ -89563,7 +92544,7 @@ var ts; factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); if (isDerivedClass) { - if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 4096 /* ContainsLexicalThis */)) { + if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 8192 /* ContainsLexicalThis */)) { // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the // following representation: // @@ -89649,11 +92630,11 @@ var ts; */ function isSufficientlyCoveredByReturnStatements(statement) { // A return statement is considered covered. - if (statement.kind === 242 /* ReturnStatement */) { + if (statement.kind === 243 /* ReturnStatement */) { return true; } // An if-statement with two covered branches is covered. - else if (statement.kind === 234 /* IfStatement */) { + else if (statement.kind === 235 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && @@ -89661,7 +92642,7 @@ var ts; } } // A block is covered if it has a last statement which is covered. - else if (statement.kind === 230 /* Block */) { + else if (statement.kind === 231 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -89863,7 +92844,7 @@ var ts; * @param node A node. */ function insertCaptureThisForNodeIfNeeded(statements, node) { - if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 209 /* ArrowFunction */) { + if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 210 /* ArrowFunction */) { insertCaptureThisForNode(statements, node, factory.createThis()); return true; } @@ -89885,22 +92866,22 @@ var ts; if (hierarchyFacts & 16384 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return statements; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: // Methods and accessors cannot be constructors, so 'new.target' will // always return 'undefined'. newTarget = factory.createVoidZero(); break; - case 166 /* Constructor */: + case 167 /* Constructor */: // Class constructors can only be called with `new`, so `this.constructor` // should be relatively safe to use. newTarget = factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), "constructor"); break; - case 251 /* FunctionDeclaration */: - case 208 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 209 /* FunctionExpression */: // Functions can be called or constructed, and may have a `this` due to // being a member or when calling an imported function via `other_1.f()`. newTarget = factory.createConditionalExpression(factory.createLogicalAnd(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), factory.createBinaryExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), 101 /* InstanceOfKeyword */, factory.getLocalName(node))), @@ -89935,20 +92916,20 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 166 /* Constructor */: + case 167 /* Constructor */: // Constructors are handled in visitClassExpression/visitClassDeclaration break; default: @@ -89977,7 +92958,7 @@ var ts; var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName); var e; - if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) { + if (!ts.isPrivateIdentifier(propertyName) && ts.getUseDefineForClassFields(context.getCompilerOptions())) { var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName; @@ -90069,7 +93050,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 4096 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { hierarchyFacts |= 32768 /* CapturedLexicalThis */; } var savedConvertedLoopState = convertedLoopState; @@ -90151,7 +93132,7 @@ var ts; : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */)) { + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 252 /* FunctionDeclaration */ || node.kind === 209 /* FunctionExpression */)) { name = factory.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */); @@ -90197,7 +93178,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 209 /* ArrowFunction */); + ts.Debug.assert(node.kind === 210 /* ArrowFunction */); // To align with the old emitter, we use a synthetic end position on the location // for the statement list we synthesize when we down-level an arrow function with // an expression function body. This prevents both comments and source maps from @@ -90358,7 +93339,7 @@ var ts; * @param node A VariableDeclarationList node. */ function visitVariableDeclarationList(node) { - if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 131072 /* ContainsBindingPattern */) { + if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 262144 /* ContainsBindingPattern */) { if (node.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } @@ -90371,7 +93352,7 @@ var ts; ts.setCommentRange(declarationList, node); // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. - if (node.transformFlags & 131072 /* ContainsBindingPattern */ + if (node.transformFlags & 262144 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -90383,8 +93364,8 @@ var ts; // 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]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var node = declarations_9[_i]; pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); end = Math.max(end, node.end); } @@ -90504,14 +93485,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: return visitDoOrWhileStatement(node, outermostLabeledStatement); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node, outermostLabeledStatement); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node, outermostLabeledStatement); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -90695,9 +93676,9 @@ var ts; var numInitialProperties = -1, hasComputed = false; for (var i = 0; i < properties.length; i++) { var property = properties[i]; - if ((property.transformFlags & 262144 /* ContainsYield */ && + if ((property.transformFlags & 524288 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) - || (hasComputed = ts.Debug.checkDefined(property.name).kind === 158 /* ComputedPropertyName */)) { + || (hasComputed = ts.Debug.checkDefined(property.name).kind === 159 /* ComputedPropertyName */)) { numInitialProperties = i; break; } @@ -90800,24 +93781,24 @@ var ts; loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts); } else { - var clone_3 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); - loop = factory.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_4 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true)); + loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); } } else { - var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); - loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + loop = factory.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel); } statements.push(loop); return statements; } function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { switch (node.kind) { - case 237 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); - case 238 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); - case 239 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); - case 235 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); - case 236 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + case 238 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 239 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 240 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 236 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 237 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); } } @@ -90842,11 +93823,11 @@ var ts; function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { - case 237 /* ForStatement */: - case 238 /* ForInStatement */: - case 239 /* ForOfStatement */: + case 238 /* ForStatement */: + case 239 /* ForInStatement */: + case 240 /* ForOfStatement */: var initializer = node.initializer; - if (initializer && initializer.kind === 250 /* VariableDeclarationList */) { + if (initializer && initializer.kind === 251 /* VariableDeclarationList */) { loopInitializer = initializer; } break; @@ -90966,7 +93947,7 @@ var ts; */ function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = factory.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 262144 /* ContainsYield */) !== 0; + var containsYield = (node.initializer.transformFlags & 524288 /* ContainsYield */) !== 0; var emitFlags = 0 /* None */; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -91081,7 +94062,7 @@ var ts; var loopBody = factory.createBlock(statements, /*multiLine*/ true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 262144 /* ContainsYield */) !== 0; + var containsYield = (node.statement.transformFlags & 524288 /* ContainsYield */) !== 0; var emitFlags = 524288 /* ReuseTempVariableScope */; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -91254,20 +94235,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -91374,7 +94355,7 @@ var ts; var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (node.kind === 167 /* GetAccessor */) { + if (node.kind === 168 /* GetAccessor */) { updated = factory.updateGetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { @@ -91554,7 +94535,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 & 8192 /* ContainsRestOrSpread */ || + if (node.transformFlags & 16384 /* ContainsRestOrSpread */ || node.expression.kind === 105 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -91562,7 +94543,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 8192 /* ContainsRestOrSpread */) { + if (node.transformFlags & 16384 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -91880,13 +94861,13 @@ var ts; if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { enabledSubstitutions |= 1 /* CapturedThis */; context.enableSubstitution(107 /* ThisKeyword */); - context.enableEmitNotification(166 /* Constructor */); - context.enableEmitNotification(165 /* MethodDeclaration */); - context.enableEmitNotification(167 /* GetAccessor */); - context.enableEmitNotification(168 /* SetAccessor */); - context.enableEmitNotification(209 /* ArrowFunction */); - context.enableEmitNotification(208 /* FunctionExpression */); - context.enableEmitNotification(251 /* FunctionDeclaration */); + context.enableEmitNotification(167 /* Constructor */); + context.enableEmitNotification(166 /* MethodDeclaration */); + context.enableEmitNotification(168 /* GetAccessor */); + context.enableEmitNotification(169 /* SetAccessor */); + context.enableEmitNotification(210 /* ArrowFunction */); + context.enableEmitNotification(209 /* FunctionExpression */); + context.enableEmitNotification(252 /* FunctionDeclaration */); } } /** @@ -91927,10 +94908,10 @@ var ts; */ function isNameOfDeclarationWithCollidingName(node) { switch (node.parent.kind) { - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: - case 255 /* EnumDeclaration */: - case 249 /* VariableDeclaration */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: + case 256 /* EnumDeclaration */: + case 250 /* VariableDeclaration */: return node.parent.name === node && resolver.isDeclarationWithCollidingName(node.parent); } @@ -92012,11 +94993,11 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 233 /* ExpressionStatement */) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 234 /* ExpressionStatement */) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 203 /* CallExpression */) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 204 /* CallExpression */) { return false; } var callTarget = statementExpression.expression; @@ -92024,7 +95005,7 @@ var ts; return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 220 /* SpreadElement */) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 221 /* SpreadElement */) { return false; } var expression = callArgument.expression; @@ -92050,15 +95031,15 @@ var ts; if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(275 /* JsxOpeningElement */); - context.enableEmitNotification(276 /* JsxClosingElement */); - context.enableEmitNotification(274 /* JsxSelfClosingElement */); + context.enableEmitNotification(276 /* JsxOpeningElement */); + context.enableEmitNotification(277 /* JsxClosingElement */); + context.enableEmitNotification(275 /* JsxSelfClosingElement */); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(201 /* PropertyAccessExpression */); - context.enableSubstitution(288 /* PropertyAssignment */); + context.enableSubstitution(202 /* PropertyAccessExpression */); + context.enableSubstitution(289 /* PropertyAssignment */); return ts.chainBundle(context, transformSourceFile); /** * Transforms an ES5 source file to ES3. @@ -92077,9 +95058,9 @@ var ts; */ function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 275 /* JsxOpeningElement */: - case 276 /* JsxClosingElement */: - case 274 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 277 /* JsxClosingElement */: + case 275 /* JsxSelfClosingElement */: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -92377,7 +95358,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 1024 /* ContainsGenerator */) === 0) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -92400,7 +95381,7 @@ var ts; else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) { return visitGenerator(node); } - else if (transformFlags & 512 /* ContainsGenerator */) { + else if (transformFlags & 1024 /* ContainsGenerator */) { return ts.visitEachChild(node, visitor, context); } else { @@ -92414,13 +95395,13 @@ var ts; */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 235 /* DoStatement */: + case 236 /* DoStatement */: return visitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return visitWhileStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -92433,30 +95414,30 @@ var ts; */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return visitFunctionExpression(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return visitAccessorDeclaration(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: return visitBreakStatement(node); - case 240 /* ContinueStatement */: + case 241 /* ContinueStatement */: return visitContinueStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 262144 /* ContainsYield */) { + if (node.transformFlags & 524288 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 1048576 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (1024 /* ContainsGenerator */ | 2097152 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -92471,23 +95452,23 @@ var ts; */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return visitBinaryExpression(node); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return visitCommaListExpression(node); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return visitConditionalExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return visitYieldExpression(node); - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return visitElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return visitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -92500,9 +95481,9 @@ var ts; */ function visitGenerator(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return visitFunctionExpression(node); default: return ts.Debug.failBadSyntaxKind(node); @@ -92661,7 +95642,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 262144 /* ContainsYield */) { + if (node.transformFlags & 524288 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -92710,7 +95691,7 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: // [source] // a.b = yield; // @@ -92722,7 +95703,7 @@ var ts; // _a.b = %sent%; target = factory.updatePropertyAccessExpression(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: // [source] // a[b] = yield; // @@ -93116,35 +96097,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 230 /* Block */: + case 231 /* Block */: return transformAndEmitBlock(node); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return transformAndEmitIfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return transformAndEmitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return transformAndEmitWhileStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return transformAndEmitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return transformAndEmitForInStatement(node); - case 240 /* ContinueStatement */: + case 241 /* ContinueStatement */: return transformAndEmitContinueStatement(node); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: return transformAndEmitBreakStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return transformAndEmitReturnStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return transformAndEmitWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return transformAndEmitThrowStatement(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -93364,7 +96345,7 @@ var ts; var variables = ts.getInitializedVariables(initializer); node = factory.updateForStatement(node, variables.length > 0 ? factory.inlineExpressions(ts.map(variables, transformInitializedVariable)) - : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock)); + : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitIterationBody(node.statement, visitor, context)); } else { node = ts.visitEachChild(node, visitor, context); @@ -93574,7 +96555,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 285 /* DefaultClause */ && defaultClauseIndex === -1) { + if (clause.kind === 286 /* DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -93587,7 +96568,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 284 /* CaseClause */) { + if (clause.kind === 285 /* CaseClause */) { if (containsYield(clause.expression) && pendingClauses.length > 0) { break; } @@ -93719,7 +96700,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 262144 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 524288 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -93752,10 +96733,10 @@ var ts; var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { // TODO(rbuckton): Does this need to be parented? - var clone_5 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); - ts.setSourceMapRange(clone_5, node); - ts.setCommentRange(clone_5, node); - return clone_5; + var clone_6 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -94748,11 +97729,11 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(216 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(214 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(215 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(289 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. - context.enableEmitNotification(297 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(217 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(215 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(216 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(298 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var currentSourceFile; // The current file. @@ -94768,7 +97749,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 2097152 /* ContainsDynamicImport */ || + node.transformFlags & 4194304 /* ContainsDynamicImport */ || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && ts.outFile(compilerOptions)))) { return node; } @@ -95080,23 +98061,23 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return visitClassDeclaration(node); - case 338 /* MergeDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 339 /* EndOfDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); @@ -95105,7 +98086,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 & 2097152 /* ContainsDynamicImport */) && !(node.transformFlags & 1024 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 4194304 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -95123,24 +98104,24 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var elem = _a[_i]; switch (elem.kind) { - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: if (destructuringNeedsFlattening(elem.initializer)) { return true; } break; - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: if (destructuringNeedsFlattening(elem.name)) { return true; } break; - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: if (destructuringNeedsFlattening(elem.expression)) { return true; } break; - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return false; default: ts.Debug.assertNever(elem, "Unhandled object member kind"); } @@ -95175,7 +98156,7 @@ var ts; var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); // Only use the external module name if it differs from the first argument. This allows us to preserve the quote style of the argument on output. var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument; - var containsLexicalThis = !!(node.transformFlags & 4096 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -95668,7 +98649,7 @@ var ts; // // To balance the declaration, add the exports of the elided variable // statement. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 232 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 233 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -95723,10 +98704,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true); @@ -95939,7 +98920,7 @@ var ts; * @param emit A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -96003,10 +98984,10 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return substituteExpressionIdentifier(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return substituteBinaryExpression(node); - case 215 /* PostfixUnaryExpression */: - case 214 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -96026,9 +99007,9 @@ var ts; } return node; } - if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) { + else if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 297 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 298 /* SourceFile */) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), /*location*/ node); } @@ -96103,8 +99084,8 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 215 /* PostfixUnaryExpression */ - ? ts.setTextRange(factory.createBinaryExpression(node.operand, factory.createToken(node.operator === 45 /* PlusPlusToken */ ? 63 /* PlusEqualsToken */ : 64 /* MinusEqualsToken */), factory.createNumericLiteral(1)), + var expression = node.kind === 216 /* PostfixUnaryExpression */ + ? ts.setTextRange(factory.createPrefixUnaryExpression(node.operator, node.operand), /*location*/ node) : node; for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { @@ -96113,6 +99094,12 @@ var ts; noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression); } + if (node.kind === 216 /* PostfixUnaryExpression */) { + noSubstitution[ts.getNodeId(expression)] = true; + expression = node.operator === 45 /* PlusPlusToken */ + ? factory.createSubtract(expression, factory.createNumericLiteral(1)) + : factory.createAdd(expression, factory.createNumericLiteral(1)); + } return expression; } } @@ -96155,12 +99142,12 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers for imported symbols. - context.enableSubstitution(289 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols - context.enableSubstitution(216 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(214 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(215 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(226 /* MetaProperty */); // Substitutes 'import.meta' - context.enableEmitNotification(297 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(290 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(217 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(215 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(216 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(227 /* MetaProperty */); // Substitutes 'import.meta' + context.enableEmitNotification(298 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var exportFunctionsMap = []; // The export function associated with a source file. @@ -96180,7 +99167,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 2097152 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 4194304 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -96349,7 +99336,7 @@ var ts; // - Temporary variables will appear at the top rather than at the bottom of the file ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 - var modifiers = node.transformFlags & 524288 /* ContainsAwait */ ? + var modifiers = node.transformFlags & 1048576 /* ContainsAwait */ ? factory.createModifiersFromModifierFlags(256 /* Async */) : undefined; var moduleObject = factory.createObjectLiteralExpression([ @@ -96384,7 +99371,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 267 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 268 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -96474,19 +99461,19 @@ var ts; var entry = _b[_a]; var importVariableName = ts.getLocalNameForExternalImport(factory, entry, currentSourceFile); // TODO: GH#18217 switch (entry.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // falls through - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== undefined); // save import into the local statements.push(factory.createExpressionStatement(factory.createAssignment(importVariableName, parameterName))); break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { if (ts.isNamedExports(entry.exportClause)) { @@ -96545,13 +99532,13 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return visitImportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return visitExportDeclaration(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -96731,7 +99718,7 @@ var ts; function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 - && (enclosingBlockScopedContainer.kind === 297 /* SourceFile */ + && (enclosingBlockScopedContainer.kind === 298 /* SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); } /** @@ -96795,7 +99782,7 @@ var ts; // // To balance the declaration, we defer the exports of the elided variable // statement until we visit this declaration's `EndOfDeclarationMarker`. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 232 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 233 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasSyntacticModifier(node.original, 1 /* Export */); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -96857,10 +99844,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -97040,43 +100027,43 @@ var ts; */ function nestedElementVisitor(node) { switch (node.kind) { - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return visitVariableStatement(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return visitClassDeclaration(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return visitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return visitForInStatement(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return visitForOfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return visitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return visitWhileStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return visitLabeledStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return visitWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return visitSwitchStatement(node); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return visitCaseBlock(node); - case 284 /* CaseClause */: + case 285 /* CaseClause */: return visitCaseClause(node); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: return visitDefaultClause(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return visitTryStatement(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return visitCatchClause(node); - case 230 /* Block */: + case 231 /* Block */: return visitBlock(node); - case 338 /* MergeDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 339 /* EndOfDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -97090,7 +100077,7 @@ var ts; function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory.updateForStatement(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + node = factory.updateForStatement(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -97102,7 +100089,7 @@ var ts; function visitForInStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory.updateForInStatement(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); + node = factory.updateForInStatement(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -97114,7 +100101,7 @@ var ts; function visitForOfStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = factory.updateForOfStatement(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); + node = factory.updateForOfStatement(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -97155,7 +100142,7 @@ var ts; * @param node The node to visit. */ function visitDoStatement(node) { - return factory.updateDoStatement(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); + return factory.updateDoStatement(node, ts.visitIterationBody(node.statement, nestedElementVisitor, context), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); } /** * Visits the body of a WhileStatement to hoist declarations. @@ -97163,7 +100150,7 @@ var ts; * @param node The node to visit. */ function visitWhileStatement(node) { - return factory.updateWhileStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock)); + return factory.updateWhileStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitIterationBody(node.statement, nestedElementVisitor, context)); } /** * Visits the body of a LabeledStatement to hoist declarations. @@ -97264,7 +100251,7 @@ var ts; else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 1024 /* ContainsDestructuringAssignment */) || (node.transformFlags & 2097152 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 4194304 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -97302,7 +100289,7 @@ var ts; return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } /** - * Determines whether the target of a destructuring assigment refers to an exported symbol. + * Determines whether the target of a destructuring assignment refers to an exported symbol. * * @param node The destructuring target. */ @@ -97327,7 +100314,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 297 /* SourceFile */; + return container !== undefined && container.kind === 298 /* SourceFile */; } else { return false; @@ -97360,7 +100347,7 @@ var ts; * @param emitCallback A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 297 /* SourceFile */) { + if (node.kind === 298 /* SourceFile */) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -97410,7 +100397,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -97447,12 +100434,12 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return substituteExpressionIdentifier(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return substituteBinaryExpression(node); - case 214 /* PrefixUnaryExpression */: - case 215 /* PostfixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return substituteUnaryExpression(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return substituteMetaProperty(node); } return node; @@ -97546,14 +100533,14 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 215 /* PostfixUnaryExpression */ + var expression = node.kind === 216 /* PostfixUnaryExpression */ ? ts.setTextRange(factory.createPrefixUnaryExpression(node.operator, node.operand), node) : node; for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 215 /* PostfixUnaryExpression */) { + if (node.kind === 216 /* PostfixUnaryExpression */) { expression = node.operator === 45 /* PlusPlusToken */ ? factory.createSubtract(preventSubstitution(expression), factory.createNumericLiteral(1)) : factory.createAdd(preventSubstitution(expression), factory.createNumericLiteral(1)); @@ -97581,7 +100568,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); - if (exportContainer && exportContainer.kind === 297 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 298 /* SourceFile */) { exportedNames = ts.append(exportedNames, factory.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -97621,7 +100608,7 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(297 /* SourceFile */); + context.enableEmitNotification(298 /* SourceFile */); context.enableSubstitution(78 /* Identifier */); var helperNameSubstitutions; return ts.chainBundle(context, transformSourceFile); @@ -97653,12 +100640,12 @@ var ts; } function visitor(node) { switch (node.kind) { - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: // Elide `import=` as it is not legal with --module ES6 return undefined; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return visitExportAssignment(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: var exportDecl = node; return visitExportDeclaration(exportDecl); } @@ -97763,7 +100750,8 @@ var ts; ts.isTypeAliasDeclaration(node) || ts.isConstructorDeclaration(node) || ts.isIndexSignatureDeclaration(node) || - ts.isPropertyAccessExpression(node); + ts.isPropertyAccessExpression(node) || + ts.isJSDocTypeAlias(node); } ts.canProduceDiagnostics = canProduceDiagnostics; function createGetSymbolAccessibilityDiagnosticForNodeName(node) { @@ -97792,7 +100780,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.kind === 253 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -97821,7 +100809,7 @@ var ts; ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.kind === 253 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -97861,14 +100849,14 @@ var ts; else if (ts.isImportEqualsDeclaration(node)) { return getImportEntityNameVisibilityError; } - else if (ts.isTypeAliasDeclaration(node)) { + else if (ts.isTypeAliasDeclaration(node) || ts.isJSDocTypeAlias(node)) { return getTypeAliasDeclarationVisibilityError; } else { return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) { + if (node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -97877,8 +100865,8 @@ var ts; } // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. - else if (node.kind === 163 /* PropertyDeclaration */ || node.kind === 201 /* PropertyAccessExpression */ || node.kind === 162 /* PropertySignature */ || - (node.kind === 160 /* Parameter */ && ts.hasSyntacticModifier(node.parent, 8 /* Private */))) { + else if (node.kind === 164 /* PropertyDeclaration */ || node.kind === 202 /* PropertyAccessExpression */ || node.kind === 163 /* PropertySignature */ || + (node.kind === 161 /* Parameter */ && ts.hasSyntacticModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasSyntacticModifier(node, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? @@ -97887,7 +100875,7 @@ var ts; ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.kind === 252 /* ClassDeclaration */ || node.kind === 160 /* Parameter */) { + else if (node.parent.kind === 253 /* ClassDeclaration */ || node.kind === 161 /* Parameter */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -97912,7 +100900,7 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; - if (node.kind === 168 /* SetAccessor */) { + if (node.kind === 169 /* SetAccessor */) { // Getters can infer the return type from the returned expression, but setters cannot, so the // "_from_external_module_1_but_cannot_be_named" case cannot occur. if (ts.hasSyntacticModifier(node, 32 /* Static */)) { @@ -97951,26 +100939,26 @@ var ts; function getReturnTypeVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; switch (node.kind) { - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 169 /* CallSignature */: + case 170 /* CallSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: // Interfaces cannot have return types that cannot be named diagnosticMessage = symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasSyntacticModifier(node, 32 /* Static */)) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -97978,7 +100966,7 @@ var ts; ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } - else if (node.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.kind === 253 /* ClassDeclaration */) { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -97992,7 +100980,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -98017,30 +101005,30 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { switch (node.parent.kind) { - case 166 /* Constructor */: + case 167 /* Constructor */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 170 /* ConstructSignature */: - case 175 /* ConstructorType */: + case 171 /* ConstructSignature */: + case 176 /* ConstructorType */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 169 /* CallSignature */: + case 170 /* CallSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: // Interfaces cannot have parameter types that cannot be named return symbolAccessibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasSyntacticModifier(node.parent, 32 /* Static */)) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? @@ -98048,7 +101036,7 @@ var ts; ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 253 /* ClassDeclaration */) { return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98061,15 +101049,15 @@ var ts; ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } - case 251 /* FunctionDeclaration */: - case 174 /* FunctionType */: + case 252 /* FunctionDeclaration */: + case 175 /* FunctionType */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; - case 168 /* SetAccessor */: - case 167 /* GetAccessor */: + case 169 /* SetAccessor */: + case 168 /* GetAccessor */: return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -98083,39 +101071,39 @@ var ts; // Type parameter constraints are named by user so we should always be able to name it var diagnosticMessage; switch (node.parent.kind) { - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 190 /* MappedType */: + case 191 /* MappedType */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1; break; - case 175 /* ConstructorType */: - case 170 /* ConstructSignature */: + case 176 /* ConstructorType */: + case 171 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 169 /* CallSignature */: + case 170 /* CallSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 165 /* MethodDeclaration */: - case 164 /* MethodSignature */: + case 166 /* MethodDeclaration */: + case 165 /* MethodSignature */: if (ts.hasSyntacticModifier(node.parent, 32 /* Static */)) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } - else if (node.parent.parent.kind === 252 /* ClassDeclaration */) { + else if (node.parent.parent.kind === 253 /* ClassDeclaration */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; - case 174 /* FunctionType */: - case 251 /* FunctionDeclaration */: + case 175 /* FunctionType */: + case 252 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; break; default: @@ -98154,11 +101142,13 @@ var ts; typeName: node.name }; } - function getTypeAliasDeclarationVisibilityError() { + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) { return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name + diagnosticMessage: symbolAccessibilityResult.errorModuleName + ? ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2 + : ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: ts.isJSDocTypeAlias(node) ? ts.Debug.checkDefined(node.typeExpression) : node.type, + typeName: ts.isJSDocTypeAlias(node) ? ts.getNameOfDeclaration(node) : node.name, }; } } @@ -98179,7 +101169,7 @@ var ts; } function isInternalDeclaration(node, currentSourceFile) { var parseTreeNode = ts.getParseTreeNode(node); - if (parseTreeNode && parseTreeNode.kind === 160 /* Parameter */) { + if (parseTreeNode && parseTreeNode.kind === 161 /* Parameter */) { var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode); var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined; var text = currentSourceFile.text; @@ -98241,6 +101231,7 @@ var ts; reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; + var errorFallbackNode; var currentSourceFile; var refs; var libs; @@ -98310,8 +101301,8 @@ var ts; recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } function reportInaccessibleUniqueSymbolError() { @@ -98335,35 +101326,38 @@ var ts; } } function reportTruncationError() { - if (errorNameNode) { - context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); + if (errorNameNode || errorFallbackNode) { + context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed)); } } function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { - var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); + var _a; + var primaryDeclaration = (_a = parentSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; }); - for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { - var augmentations = augmentingDeclarations_1[_i]; - context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + if (augmentingDeclarations) { + for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { + var augmentations = augmentingDeclarations_1[_i]; + context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + } } } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; - getSymbolAccessibilityDiagnostic = function (s) { return ({ + getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ diagnosticMessage: s.errorModuleName ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit, errorNode: s.errorNode || sourceFile - }); }; + })); }; var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled); getSymbolAccessibilityDiagnostic = oldDiag; return result; } function transformRoot(node) { - if (node.kind === 297 /* SourceFile */ && node.isDeclarationFile) { + if (node.kind === 298 /* SourceFile */ && node.isDeclarationFile) { return node; } - if (node.kind === 298 /* Bundle */) { + if (node.kind === 299 /* Bundle */) { isBundledEmit = true; refs = new ts.Map(); libs = new ts.Map(); @@ -98393,7 +101387,7 @@ var ts; var updated = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements); return factory.updateSourceFile(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); }), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 300 /* InputFiles */) { + if (prepend.kind === 301 /* InputFiles */) { var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal); hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib; collectReferences(sourceFile, refs); @@ -98485,7 +101479,7 @@ var ts; declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { - var specifier = ts.moduleSpecifiers.getModuleSpecifier(__assign(__assign({}, options), { baseUrl: options.baseUrl && ts.toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }), currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, + var specifier = ts.moduleSpecifiers.getModuleSpecifier(options, currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, /*preferences*/ undefined); if (!ts.pathIsRelative(specifier)) { // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration @@ -98534,7 +101528,7 @@ var ts; return name; } else { - if (name.kind === 197 /* ArrayBindingPattern */) { + if (name.kind === 198 /* ArrayBindingPattern */) { return factory.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); } else { @@ -98542,7 +101536,7 @@ var ts; } } function visitBindingElement(elem) { - if (elem.kind === 222 /* OmittedExpression */) { + if (elem.kind === 223 /* OmittedExpression */) { return elem; } return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); @@ -98580,7 +101574,7 @@ var ts; // Literal const declarations will have an initializer ensured rather than a type return; } - var shouldUseResolverType = node.kind === 160 /* Parameter */ && + var shouldUseResolverType = node.kind === 161 /* Parameter */ && (resolver.isRequiredInitializedParameter(node) || resolver.isOptionalUninitializedParameterProperty(node)); if (type && !shouldUseResolverType) { @@ -98589,7 +101583,7 @@ var ts; if (!ts.getParseTreeNode(node)) { return type ? ts.visitNode(type, visitDeclarationSubtree) : factory.createKeywordTypeNode(128 /* AnyKeyword */); } - if (node.kind === 168 /* SetAccessor */) { + if (node.kind === 169 /* SetAccessor */) { // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) return factory.createKeywordTypeNode(128 /* AnyKeyword */); @@ -98600,12 +101594,12 @@ var ts; oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); } - if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) { + if (node.kind === 250 /* VariableDeclaration */ || node.kind === 199 /* BindingElement */) { return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } - if (node.kind === 160 /* Parameter */ - || node.kind === 163 /* PropertyDeclaration */ - || node.kind === 162 /* PropertySignature */) { + if (node.kind === 161 /* Parameter */ + || node.kind === 164 /* PropertyDeclaration */ + || node.kind === 163 /* PropertySignature */) { if (!node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); @@ -98622,20 +101616,20 @@ var ts; function isDeclarationAndNotVisible(node) { node = ts.getParseTreeNode(node); switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 256 /* ModuleDeclaration */: - case 253 /* InterfaceDeclaration */: - case 252 /* ClassDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: + case 252 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 254 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: return !resolver.isDeclarationVisible(node); // The following should be doing their own visibility checks based on filtering their members - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return !getBindingNameVisible(node); - case 260 /* ImportEqualsDeclaration */: - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: + case 261 /* ImportEqualsDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: return false; } return false; @@ -98716,7 +101710,7 @@ var ts; function rewriteModuleSpecifier(parent, input) { if (!input) return undefined; // TODO: GH#18217 - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 256 /* ModuleDeclaration */ && parent.kind !== 195 /* ImportType */); + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 257 /* ModuleDeclaration */ && parent.kind !== 196 /* ImportType */); if (ts.isStringLiteralLike(input)) { if (isBundledEmit) { var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); @@ -98736,7 +101730,7 @@ var ts; function transformImportEqualsDeclaration(decl) { if (!resolver.isDeclarationVisible(decl)) return; - if (decl.moduleReference.kind === 272 /* ExternalModuleReference */) { + if (decl.moduleReference.kind === 273 /* ExternalModuleReference */) { // Rewrite external module names if necessary var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); return factory.updateImportEqualsDeclaration(decl, @@ -98763,7 +101757,7 @@ var ts; return visibleDefaultBinding && factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } - if (decl.importClause.namedBindings.kind === 263 /* NamespaceImport */) { + if (decl.importClause.namedBindings.kind === 264 /* NamespaceImport */) { // Namespace import (optionally with visible default) var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; @@ -98858,7 +101852,7 @@ var ts; // We'd see a TDZ violation at runtime var canProduceDiagnostic = ts.canProduceDiagnostics(input); var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; - var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 177 /* TypeLiteral */ || input.kind === 190 /* MappedType */) && input.parent.kind !== 254 /* TypeAliasDeclaration */); + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 178 /* TypeLiteral */ || input.kind === 191 /* MappedType */) && input.parent.kind !== 255 /* TypeAliasDeclaration */); // Emit methods which are private as properties with no type information if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { if (ts.hasEffectiveModifier(input, 8 /* Private */)) { @@ -98879,21 +101873,21 @@ var ts; } if (isProcessedComponent(input)) { switch (input.kind) { - case 223 /* ExpressionWithTypeArguments */: { + case 224 /* ExpressionWithTypeArguments */: { if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { checkEntityNameVisibility(input.expression, enclosingDeclaration); } var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(factory.updateExpressionWithTypeArguments(node, node.expression, node.typeArguments)); } - case 173 /* TypeReference */: { + case 174 /* TypeReference */: { checkEntityNameVisibility(input.typeName, enclosingDeclaration); var node = ts.visitEachChild(input, visitDeclarationSubtree, context); return cleanup(factory.updateTypeReferenceNode(node, node.typeName, node.typeArguments)); } - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: return cleanup(factory.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); - case 166 /* Constructor */: { + case 167 /* Constructor */: { // A constructor declaration may not have a type annotation var ctor = factory.createConstructorDeclaration( /*decorators*/ undefined, @@ -98901,7 +101895,7 @@ var ts; /*body*/ undefined); return cleanup(ctor); } - case 165 /* MethodDeclaration */: { + case 166 /* MethodDeclaration */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } @@ -98911,7 +101905,7 @@ var ts; /*body*/ undefined); return cleanup(sig); } - case 167 /* GetAccessor */: { + case 168 /* GetAccessor */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } @@ -98920,7 +101914,7 @@ var ts; /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), ensureType(input, accessorType), /*body*/ undefined)); } - case 168 /* SetAccessor */: { + case 169 /* SetAccessor */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } @@ -98928,31 +101922,31 @@ var ts; /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), /*body*/ undefined)); } - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updatePropertyDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input))); - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type))); - case 164 /* MethodSignature */: { + case 165 /* MethodSignature */: { if (ts.isPrivateIdentifier(input.name)) { return cleanup(/*returnValue*/ undefined); } return cleanup(factory.updateMethodSignature(input, ensureModifiers(input), input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 169 /* CallSignature */: { + case 170 /* CallSignature */: { return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); } - case 171 /* IndexSignature */: { + case 172 /* IndexSignature */: { return cleanup(factory.updateIndexSignature(input, /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(128 /* AnyKeyword */))); } - case 249 /* VariableDeclaration */: { + case 250 /* VariableDeclaration */: { if (ts.isBindingPattern(input.name)) { return recreateBindingPattern(input.name); } @@ -98960,13 +101954,13 @@ var ts; suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types return cleanup(factory.updateVariableDeclaration(input, input.name, /*exclamationToken*/ undefined, ensureType(input, input.type), ensureNoInitializer(input))); } - case 159 /* TypeParameter */: { + case 160 /* TypeParameter */: { if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { return cleanup(factory.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); } return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); } - case 184 /* ConditionalType */: { + case 185 /* ConditionalType */: { // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); @@ -98978,13 +101972,13 @@ var ts; var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); return cleanup(factory.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); } - case 174 /* FunctionType */: { + case 175 /* FunctionType */: { return cleanup(factory.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 175 /* ConstructorType */: { + case 176 /* ConstructorType */: { return cleanup(factory.updateConstructorTypeNode(input, ensureModifiers(input), ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); } - case 195 /* ImportType */: { + case 196 /* ImportType */: { if (!ts.isLiteralImportTypeNode(input)) return cleanup(input); return cleanup(factory.updateImportTypeNode(input, factory.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); @@ -99016,7 +102010,7 @@ var ts; } } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 165 /* MethodDeclaration */ && ts.hasEffectiveModifier(node.parent, 8 /* Private */); + return node.parent.kind === 166 /* MethodDeclaration */ && ts.hasEffectiveModifier(node.parent, 8 /* Private */); } function visitDeclarationStatements(input) { if (!isPreservedDeclarationStatement(input)) { @@ -99026,7 +102020,7 @@ var ts; if (shouldStripInternal(input)) return; switch (input.kind) { - case 267 /* ExportDeclaration */: { + case 268 /* ExportDeclaration */: { if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; } @@ -99036,7 +102030,7 @@ var ts; return factory.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); } - case 266 /* ExportAssignment */: { + case 267 /* ExportAssignment */: { // Always visible if the parent node isn't dropped for being not visible if (ts.isSourceFile(input.parent)) { resultHasExternalModuleIndicator = true; @@ -99051,7 +102045,9 @@ var ts; diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: input }); }; + errorFallbackNode = input; var varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + errorFallbackNode = undefined; var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */)); return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; } @@ -99068,17 +102064,17 @@ var ts; // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too return statement; } - var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (11263 /* All */ ^ 1 /* Export */)); + var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (27647 /* All */ ^ 1 /* Export */)); return factory.updateModifiers(statement, modifiers); } function transformTopLevelDeclaration(input) { if (shouldStripInternal(input)) return; switch (input.kind) { - case 260 /* ImportEqualsDeclaration */: { + case 261 /* ImportEqualsDeclaration */: { return transformImportEqualsDeclaration(input); } - case 261 /* ImportDeclaration */: { + case 262 /* ImportDeclaration */: { return transformImportDeclaration(input); } } @@ -99099,14 +102095,14 @@ var ts; } var previousNeedsDeclare = needsDeclare; switch (input.kind) { - case 254 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + case 255 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all return cleanup(factory.updateTypeAliasDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); - case 253 /* InterfaceDeclaration */: { + case 254 /* InterfaceDeclaration */: { return cleanup(factory.updateInterfaceDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } - case 251 /* FunctionDeclaration */: { + case 252 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type var clean = cleanup(factory.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input), @@ -99121,7 +102117,7 @@ var ts; fakespace_1.symbol = props[0].parent; var exportMappings_1 = []; var declarations = ts.mapDefined(props, function (p) { - if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + if (!p.valueDeclaration || !ts.isPropertyAccessExpression(p.valueDeclaration)) { return undefined; // TODO GH#33569: Handle element access expressions that created late bound names (rather than silently omitting them) } getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration); @@ -99173,10 +102169,10 @@ var ts; return clean; } } - case 256 /* ModuleDeclaration */: { + case 257 /* ModuleDeclaration */: { needsDeclare = false; var inner = input.body; - if (inner && inner.kind === 257 /* ModuleBlock */) { + if (inner && inner.kind === 258 /* ModuleBlock */) { var oldNeedsScopeFix = needsScopeFixMarker; var oldHasScopeFix = resultHasScopeMarker; resultHasScopeMarker = false; @@ -99219,7 +102215,9 @@ var ts; /*decorators*/ undefined, mods, input.name, body)); } } - case 252 /* ClassDeclaration */: { + case 253 /* ClassDeclaration */: { + errorNameNode = input.name; + errorFallbackNode = input; var modifiers = factory.createNodeArray(ensureModifiers(input)); var typeParameters = ensureTypeParams(input, input.typeParameters); var ctor = ts.getFirstConstructorWithBody(input); @@ -99227,7 +102225,7 @@ var ts; if (ctor) { var oldDiag_1 = getSymbolAccessibilityDiagnostic; parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { - if (!ts.hasSyntacticModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param)) + if (!ts.hasSyntacticModifier(param, 16476 /* ParameterPropertyModifier */) || shouldStripInternal(param)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 78 /* Identifier */) { @@ -99302,10 +102300,10 @@ var ts; /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); } } - case 232 /* VariableStatement */: { + case 233 /* VariableStatement */: { return cleanup(transformVariableStatement(input)); } - case 255 /* EnumDeclaration */: { + case 256 /* EnumDeclaration */: { return cleanup(factory.updateEnumDeclaration(input, /*decorators*/ undefined, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) { if (shouldStripInternal(m)) return; @@ -99324,12 +102322,14 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 256 /* ModuleDeclaration */) { + if (input.kind === 257 /* ModuleDeclaration */) { needsDeclare = previousNeedsDeclare; } if (node === input) { return node; } + errorFallbackNode = undefined; + errorNameNode = undefined; return node && ts.setOriginalNode(preserveJsDoc(node, input), input); } } @@ -99345,7 +102345,7 @@ var ts; return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); } function recreateBindingElement(e) { - if (e.kind === 222 /* OmittedExpression */) { + if (e.kind === 223 /* OmittedExpression */) { return; } if (e.name) { @@ -99393,9 +102393,9 @@ var ts; return factory.createModifiersFromModifierFlags(newFlags); } function ensureModifierFlags(node) { - var mask = 11263 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files + var mask = 27647 /* All */ ^ (4 /* Public */ | 256 /* Async */ | 16384 /* Override */); // No async and override modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; - var parentIsFile = node.parent.kind === 297 /* SourceFile */; + var parentIsFile = node.parent.kind === 298 /* SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { mask ^= 2 /* Ambient */; additions = 0 /* None */; @@ -99424,7 +102424,7 @@ var ts; } ts.transformDeclarations = transformDeclarations; function isAlwaysType(node) { - if (node.kind === 253 /* InterfaceDeclaration */) { + if (node.kind === 254 /* InterfaceDeclaration */) { return true; } return false; @@ -99434,7 +102434,7 @@ var ts; return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); } function maskModifierFlags(node, modifierMask, modifierAdditions) { - if (modifierMask === void 0) { modifierMask = 11263 /* All */ ^ 4 /* Public */; } + if (modifierMask === void 0) { modifierMask = 27647 /* All */ ^ 4 /* Public */; } if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions; if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) { @@ -99449,7 +102449,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 167 /* GetAccessor */ + return accessor.kind === 168 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type @@ -99458,52 +102458,52 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: return !ts.hasEffectiveModifier(node, 8 /* Private */); - case 160 /* Parameter */: - case 249 /* VariableDeclaration */: + case 161 /* Parameter */: + case 250 /* VariableDeclaration */: return true; } return false; } function isPreservedDeclarationStatement(node) { switch (node.kind) { - case 251 /* FunctionDeclaration */: - case 256 /* ModuleDeclaration */: - case 260 /* ImportEqualsDeclaration */: - case 253 /* InterfaceDeclaration */: - case 252 /* ClassDeclaration */: - case 254 /* TypeAliasDeclaration */: - case 255 /* EnumDeclaration */: - case 232 /* VariableStatement */: - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: - case 266 /* ExportAssignment */: + case 252 /* FunctionDeclaration */: + case 257 /* ModuleDeclaration */: + case 261 /* ImportEqualsDeclaration */: + case 254 /* InterfaceDeclaration */: + case 253 /* ClassDeclaration */: + case 255 /* TypeAliasDeclaration */: + case 256 /* EnumDeclaration */: + case 233 /* VariableStatement */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: + case 267 /* ExportAssignment */: return true; } return false; } function isProcessedComponent(node) { switch (node.kind) { - case 170 /* ConstructSignature */: - case 166 /* Constructor */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 163 /* PropertyDeclaration */: - case 162 /* PropertySignature */: - case 164 /* MethodSignature */: - case 169 /* CallSignature */: - case 171 /* IndexSignature */: - case 249 /* VariableDeclaration */: - case 159 /* TypeParameter */: - case 223 /* ExpressionWithTypeArguments */: - case 173 /* TypeReference */: - case 184 /* ConditionalType */: - case 174 /* FunctionType */: - case 175 /* ConstructorType */: - case 195 /* ImportType */: + case 171 /* ConstructSignature */: + case 167 /* Constructor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 164 /* PropertyDeclaration */: + case 163 /* PropertySignature */: + case 165 /* MethodSignature */: + case 170 /* CallSignature */: + case 172 /* IndexSignature */: + case 250 /* VariableDeclaration */: + case 160 /* TypeParameter */: + case 224 /* ExpressionWithTypeArguments */: + case 174 /* TypeReference */: + case 185 /* ConditionalType */: + case 175 /* FunctionType */: + case 176 /* ConstructorType */: + case 196 /* ImportType */: return true; } return false; @@ -99559,6 +102559,9 @@ var ts; if (languageVersion < 99 /* ESNext */) { transformers.push(ts.transformESNext); } + if (languageVersion < 8 /* ES2021 */) { + transformers.push(ts.transformES2021); + } if (languageVersion < 7 /* ES2020 */) { transformers.push(ts.transformES2020); } @@ -99635,7 +102638,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, factory, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(341 /* Count */); + var enabledSyntaxKindFeatures = new Array(345 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentStatements; @@ -99646,6 +102649,9 @@ var ts; var lexicalEnvironmentFlagsStack = []; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; + var blockScopedVariableDeclarationsStack = []; + var blockScopeStackOffset = 0; + var blockScopedVariableDeclarations; var emitHelpers; var onSubstituteNode = noEmitSubstitution; var onEmitNode = noEmitNotification; @@ -99668,6 +102674,9 @@ var ts; hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, addInitializationStatement: addInitializationStatement, + startBlockScope: startBlockScope, + endBlockScope: endBlockScope, + addBlockScopedVariable: addBlockScopedVariable, requestEmitHelper: requestEmitHelper, readEmitHelpers: readEmitHelpers, enableSubstitution: enableSubstitution, @@ -99711,9 +102720,9 @@ var ts; var transformed = []; for (var _a = 0, nodes_3 = nodes; _a < nodes_3.length; _a++) { var node = nodes_3[_a]; - ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 298 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end }); transformed.push((allowDtsFiles ? transformation : transformRoot)(node)); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // prevent modification of the lexical environment. state = 2 /* Completed */; @@ -99928,6 +102937,38 @@ var ts; function getLexicalEnvironmentFlags() { return lexicalEnvironmentFlags; } + /** + * Starts a block scope. Any existing block hoisted variables are pushed onto the stack and the related storage variables are reset. + */ + function startBlockScope() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot start a block scope during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot start a block scope after transformation has completed."); + blockScopedVariableDeclarationsStack[blockScopeStackOffset] = blockScopedVariableDeclarations; + blockScopeStackOffset++; + blockScopedVariableDeclarations = undefined; + } + /** + * Ends a block scope. The previous set of block hoisted variables are restored. Any hoisted declarations are returned. + */ + function endBlockScope() { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot end a block scope during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot end a block scope after transformation has completed."); + var statements = ts.some(blockScopedVariableDeclarations) ? + [ + factory.createVariableStatement( + /*modifiers*/ undefined, factory.createVariableDeclarationList(blockScopedVariableDeclarations.map(function (identifier) { return factory.createVariableDeclaration(identifier); }), 1 /* Let */)) + ] : undefined; + blockScopeStackOffset--; + blockScopedVariableDeclarations = blockScopedVariableDeclarationsStack[blockScopeStackOffset]; + if (blockScopeStackOffset === 0) { + blockScopedVariableDeclarationsStack = []; + } + return statements; + } + function addBlockScopedVariable(name) { + ts.Debug.assert(blockScopeStackOffset > 0, "Cannot add a block scoped variable outside of an iteration body."); + (blockScopedVariableDeclarations || (blockScopedVariableDeclarations = [])).push(name); + } function requestEmitHelper(helper) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); @@ -99969,35 +103010,37 @@ var ts; } ts.transformNodes = transformNodes; ts.nullTransformationContext = { - get factory() { return ts.factory; }, - enableEmitNotification: ts.noop, - enableSubstitution: ts.noop, - endLexicalEnvironment: ts.returnUndefined, + factory: ts.factory, getCompilerOptions: function () { return ({}); }, - getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + getEmitHost: ts.notImplemented, getEmitHelperFactory: ts.notImplemented, + startLexicalEnvironment: ts.noop, + resumeLexicalEnvironment: ts.noop, + suspendLexicalEnvironment: ts.noop, + endLexicalEnvironment: ts.returnUndefined, setLexicalEnvironmentFlags: ts.noop, getLexicalEnvironmentFlags: function () { return 0; }, - hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + hoistFunctionDeclaration: ts.noop, addInitializationStatement: ts.noop, - isEmitNotificationEnabled: ts.notImplemented, - isSubstitutionEnabled: ts.notImplemented, - onEmitNode: ts.noop, - onSubstituteNode: ts.notImplemented, - readEmitHelpers: ts.notImplemented, + startBlockScope: ts.noop, + endBlockScope: ts.returnUndefined, + addBlockScopedVariable: ts.noop, requestEmitHelper: ts.noop, - resumeLexicalEnvironment: ts.noop, - startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop, + readEmitHelpers: ts.notImplemented, + enableSubstitution: ts.noop, + enableEmitNotification: ts.noop, + isSubstitutionEnabled: ts.notImplemented, + isEmitNotificationEnabled: ts.notImplemented, + onSubstituteNode: noEmitSubstitution, + onEmitNode: noEmitNotification, addDiagnostic: ts.noop, }; })(ts || (ts = {})); var ts; (function (ts) { var brackets = createBracketsMap(); - var syntheticParent = { pos: -1, end: -1 }; /*@internal*/ function isBuildInfoFile(file) { return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */); @@ -100083,7 +103126,7 @@ var ts; /*@internal*/ function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); - if (sourceFile.kind === 298 /* Bundle */) { + if (sourceFile.kind === 299 /* Bundle */) { return getOutputPathsForBundle(options, forceDtsPaths); } else { @@ -100309,15 +103352,15 @@ var ts; sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); }) }; } - ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath }); emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath }); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo); - ts.tracing.pop(); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath }); emitBuildInfo(bundleBuildInfo, buildInfoPath); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { if (jsFilePath) { @@ -100444,13 +103487,13 @@ var ts; if (!declBlocked || forceDtsEmit) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, { - sourceMap: compilerOptions.declarationMap, + sourceMap: !forceDtsEmit && compilerOptions.declarationMap, sourceRoot: compilerOptions.sourceRoot, mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, // Explicitly do not passthru either `inline` option }); - if (forceDtsEmit && declarationTransform.transformed[0].kind === 297 /* SourceFile */) { + if (forceDtsEmit && declarationTransform.transformed[0].kind === 298 /* SourceFile */) { var sourceFile = declarationTransform.transformed[0]; exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; } @@ -100473,8 +103516,8 @@ var ts; ts.forEachChild(node, collectLinkedAliases); } function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) { - var bundle = sourceFileOrBundle.kind === 298 /* Bundle */ ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 297 /* SourceFile */ ? sourceFileOrBundle : undefined; + var bundle = sourceFileOrBundle.kind === 299 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 298 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; var sourceMapGenerator; if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { @@ -100515,7 +103558,7 @@ var ts; } function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { return (mapOptions.sourceMap || mapOptions.inlineSourceMap) - && (sourceFileOrBundle.kind !== 297 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); + && (sourceFileOrBundle.kind !== 298 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); } function getSourceRoot(mapOptions) { // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the @@ -100574,7 +103617,7 @@ var ts; ts.emitFiles = emitFiles; /*@internal*/ function getBuildInfoText(buildInfo) { - return JSON.stringify(buildInfo, undefined, 2); + return JSON.stringify(buildInfo); } ts.getBuildInfoText = getBuildInfoText; /*@internal*/ @@ -100755,7 +103798,7 @@ var ts; function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNode = handlers.onBeforeEmitNode, onAfterEmitNode = handlers.onAfterEmitNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var extendedDiagnostics = !!printerOptions.extendedDiagnostics; var newLine = ts.getNewLineCharacter(printerOptions); var moduleKind = ts.getEmitModuleKind(printerOptions); @@ -100794,9 +103837,11 @@ var ts; var detachedCommentsInfo; var hasWrittenComment = false; var commentsDisabled = !!printerOptions.removeComments; - var lastNode; var lastSubstitution; + var currentParenthesizerRule; var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit; + var parenthesizer = ts.factory.parenthesizer; + var emitBinaryExpression = createEmitBinaryExpression(); reset(); return { // public API @@ -100824,9 +103869,9 @@ var ts; break; } switch (node.kind) { - case 297 /* SourceFile */: return printFile(node); - case 298 /* Bundle */: return printBundle(node); - case 299 /* UnparsedSource */: return printUnparsedSource(node); + case 298 /* SourceFile */: return printFile(node); + case 299 /* Bundle */: return printBundle(node); + case 300 /* UnparsedSource */: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -100860,7 +103905,7 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - emitList(syntheticParent, nodes, format); + emitList(/*parentNode*/ undefined, nodes, format); reset(); writer = previousWriter; } @@ -100995,7 +104040,7 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - pipelineEmit(hint, node); + pipelineEmit(hint, node, /*parenthesizerRule*/ undefined); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -101023,51 +104068,54 @@ var ts; currentSourceFile = undefined; currentLineMap = undefined; detachedCommentsInfo = undefined; - lastNode = undefined; - lastSubstitution = undefined; setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined); } function getCurrentLineMap() { return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile)); } - function emit(node) { + function emit(node, parenthesizerRule) { if (node === undefined) return; var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node); - var substitute = pipelineEmit(4 /* Unspecified */, node); + pipelineEmit(4 /* Unspecified */, node, parenthesizerRule); recordBundleFileInternalSectionEnd(prevSourceFileTextKind); - return substitute; } function emitIdentifierName(node) { if (node === undefined) return; - return pipelineEmit(2 /* IdentifierName */, node); + pipelineEmit(2 /* IdentifierName */, node, /*parenthesizerRule*/ undefined); } - function emitExpression(node) { + function emitExpression(node, parenthesizerRule) { if (node === undefined) return; - return pipelineEmit(1 /* Expression */, node); + pipelineEmit(1 /* Expression */, node, parenthesizerRule); } function emitJsxAttributeValue(node) { - return pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); + pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node); } - function pipelineEmit(emitHint, node) { - var savedLastNode = lastNode; - var savedLastSubstitution = lastSubstitution; - var savedPreserveSourceNewlines = preserveSourceNewlines; - lastNode = node; - lastSubstitution = undefined; - if (preserveSourceNewlines && !!(ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) { + function beforeEmitNode(node) { + if (preserveSourceNewlines && (ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) { preserveSourceNewlines = false; } + } + function afterEmitNode(savedPreserveSourceNewlines) { + preserveSourceNewlines = savedPreserveSourceNewlines; + } + function pipelineEmit(emitHint, node, parenthesizerRule) { + currentParenthesizerRule = parenthesizerRule; var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node); pipelinePhase(emitHint, node); - ts.Debug.assert(lastNode === node); - var substitute = lastSubstitution; - lastNode = savedLastNode; - lastSubstitution = savedLastSubstitution; - preserveSourceNewlines = savedPreserveSourceNewlines; - return substitute || node; + currentParenthesizerRule = undefined; + } + function shouldEmitComments(node) { + return !commentsDisabled && !ts.isSourceFile(node); + } + function shouldEmitSourceMaps(node) { + return !sourceMapsDisabled && + !ts.isSourceFile(node) && + !ts.isInJsonFile(node) && + !ts.isUnparsedSource(node) && + !ts.isUnparsedPrepend(node); } function getPipelinePhase(phase, emitHint, node) { switch (phase) { @@ -101077,18 +104125,21 @@ var ts; } // falls through case 1 /* Substitution */: - if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) { + if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) { + if (currentParenthesizerRule) { + lastSubstitution = currentParenthesizerRule(lastSubstitution); + } return pipelineEmitWithSubstitution; } // falls through case 2 /* Comments */: - if (!commentsDisabled && node.kind !== 297 /* SourceFile */) { + if (shouldEmitComments(node)) { return pipelineEmitWithComments; } // falls through case 3 /* SourceMaps */: - if (!sourceMapsDisabled && node.kind !== 297 /* SourceFile */ && !ts.isInJsonFile(node)) { - return pipelineEmitWithSourceMap; + if (shouldEmitSourceMaps(node)) { + return pipelineEmitWithSourceMaps; } // falls through case 4 /* Emit */: @@ -101101,13 +104152,25 @@ var ts; return getPipelinePhase(currentPhase + 1, emitHint, node); } function pipelineEmitWithNotification(hint, node) { - ts.Debug.assert(lastNode === node); var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node); onEmitNode(hint, node, pipelinePhase); - ts.Debug.assert(lastNode === node); } function pipelineEmitWithHint(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (preserveSourceNewlines) { + var savedPreserveSourceNewlines = preserveSourceNewlines; + beforeEmitNode(node); + pipelineEmitWithHintWorker(hint, node); + afterEmitNode(savedPreserveSourceNewlines); + } + else { + pipelineEmitWithHintWorker(hint, node); + } + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); + // clear the parenthesizer rule as we ascend + currentParenthesizerRule = undefined; + } + function pipelineEmitWithHintWorker(hint, node) { if (hint === 0 /* SourceFile */) return emitSourceFile(ts.cast(node, ts.isSourceFile)); if (hint === 2 /* IdentifierName */) @@ -101121,24 +104184,12 @@ var ts; return emitEmptyStatement(/*isEmbeddedStatement*/ true); } if (hint === 4 /* Unspecified */) { - if (ts.isKeyword(node.kind)) - return writeTokenNode(node, writeKeyword); switch (node.kind) { // Pseudo-literals case 15 /* TemplateHead */: case 16 /* TemplateMiddle */: case 17 /* TemplateTail */: return emitLiteral(node, /*jsxAttributeEscape*/ false); - case 299 /* UnparsedSource */: - case 293 /* UnparsedPrepend */: - return emitUnparsedSourceOrPrepend(node); - case 292 /* UnparsedPrologue */: - return writeUnparsedNode(node); - case 294 /* UnparsedText */: - case 295 /* UnparsedInternalText */: - return emitUnparsedTextLike(node); - case 296 /* UnparsedSyntheticReference */: - return emitUnparsedSyntheticReference(node); // Identifiers case 78 /* Identifier */: return emitIdentifier(node); @@ -101147,282 +104198,323 @@ var ts; return emitPrivateIdentifier(node); // Parse tree nodes // Names - case 157 /* QualifiedName */: + case 158 /* QualifiedName */: return emitQualifiedName(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return emitComputedPropertyName(node); // Signature elements - case 159 /* TypeParameter */: + case 160 /* TypeParameter */: return emitTypeParameter(node); - case 160 /* Parameter */: + case 161 /* Parameter */: return emitParameter(node); - case 161 /* Decorator */: + case 162 /* Decorator */: return emitDecorator(node); // Type members - case 162 /* PropertySignature */: + case 163 /* PropertySignature */: return emitPropertySignature(node); - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: return emitPropertyDeclaration(node); - case 164 /* MethodSignature */: + case 165 /* MethodSignature */: return emitMethodSignature(node); - case 165 /* MethodDeclaration */: + case 166 /* MethodDeclaration */: return emitMethodDeclaration(node); - case 166 /* Constructor */: + case 167 /* Constructor */: return emitConstructor(node); - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return emitAccessorDeclaration(node); - case 169 /* CallSignature */: + case 170 /* CallSignature */: return emitCallSignature(node); - case 170 /* ConstructSignature */: + case 171 /* ConstructSignature */: return emitConstructSignature(node); - case 171 /* IndexSignature */: + case 172 /* IndexSignature */: return emitIndexSignature(node); - case 194 /* TemplateLiteralTypeSpan */: - return emitTemplateTypeSpan(node); // Types - case 172 /* TypePredicate */: + case 173 /* TypePredicate */: return emitTypePredicate(node); - case 173 /* TypeReference */: + case 174 /* TypeReference */: return emitTypeReference(node); - case 174 /* FunctionType */: + case 175 /* FunctionType */: return emitFunctionType(node); - case 308 /* JSDocFunctionType */: - return emitJSDocFunctionType(node); - case 175 /* ConstructorType */: + case 176 /* ConstructorType */: return emitConstructorType(node); - case 176 /* TypeQuery */: + case 177 /* TypeQuery */: return emitTypeQuery(node); - case 177 /* TypeLiteral */: + case 178 /* TypeLiteral */: return emitTypeLiteral(node); - case 178 /* ArrayType */: + case 179 /* ArrayType */: return emitArrayType(node); - case 179 /* TupleType */: + case 180 /* TupleType */: return emitTupleType(node); - case 180 /* OptionalType */: + case 181 /* OptionalType */: return emitOptionalType(node); - case 182 /* UnionType */: + // SyntaxKind.RestType is handled below + case 183 /* UnionType */: return emitUnionType(node); - case 183 /* IntersectionType */: + case 184 /* IntersectionType */: return emitIntersectionType(node); - case 184 /* ConditionalType */: + case 185 /* ConditionalType */: return emitConditionalType(node); - case 185 /* InferType */: + case 186 /* InferType */: return emitInferType(node); - case 186 /* ParenthesizedType */: + case 187 /* ParenthesizedType */: return emitParenthesizedType(node); - case 223 /* ExpressionWithTypeArguments */: + case 224 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(node); - case 187 /* ThisType */: + case 188 /* ThisType */: return emitThisType(); - case 188 /* TypeOperator */: + case 189 /* TypeOperator */: return emitTypeOperator(node); - case 189 /* IndexedAccessType */: + case 190 /* IndexedAccessType */: return emitIndexedAccessType(node); - case 190 /* MappedType */: + case 191 /* MappedType */: return emitMappedType(node); - case 191 /* LiteralType */: + case 192 /* LiteralType */: return emitLiteralType(node); - case 193 /* TemplateLiteralType */: + case 193 /* NamedTupleMember */: + return emitNamedTupleMember(node); + case 194 /* TemplateLiteralType */: return emitTemplateType(node); - case 195 /* ImportType */: + case 195 /* TemplateLiteralTypeSpan */: + return emitTemplateTypeSpan(node); + case 196 /* ImportType */: return emitImportTypeNode(node); - case 303 /* JSDocAllType */: - writePunctuation("*"); - return; - case 304 /* JSDocUnknownType */: - writePunctuation("?"); - return; - case 305 /* JSDocNullableType */: - return emitJSDocNullableType(node); - case 306 /* JSDocNonNullableType */: - return emitJSDocNonNullableType(node); - case 307 /* JSDocOptionalType */: - return emitJSDocOptionalType(node); - case 181 /* RestType */: - case 309 /* JSDocVariadicType */: - return emitRestOrJSDocVariadicType(node); - case 192 /* NamedTupleMember */: - return emitNamedTupleMember(node); // Binding patterns - case 196 /* ObjectBindingPattern */: + case 197 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 197 /* ArrayBindingPattern */: + case 198 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 198 /* BindingElement */: + case 199 /* BindingElement */: return emitBindingElement(node); // Misc - case 228 /* TemplateSpan */: + case 229 /* TemplateSpan */: return emitTemplateSpan(node); - case 229 /* SemicolonClassElement */: + case 230 /* SemicolonClassElement */: return emitSemicolonClassElement(); // Statements - case 230 /* Block */: + case 231 /* Block */: return emitBlock(node); - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: return emitVariableStatement(node); - case 231 /* EmptyStatement */: + case 232 /* EmptyStatement */: return emitEmptyStatement(/*isEmbeddedStatement*/ false); - case 233 /* ExpressionStatement */: + case 234 /* ExpressionStatement */: return emitExpressionStatement(node); - case 234 /* IfStatement */: + case 235 /* IfStatement */: return emitIfStatement(node); - case 235 /* DoStatement */: + case 236 /* DoStatement */: return emitDoStatement(node); - case 236 /* WhileStatement */: + case 237 /* WhileStatement */: return emitWhileStatement(node); - case 237 /* ForStatement */: + case 238 /* ForStatement */: return emitForStatement(node); - case 238 /* ForInStatement */: + case 239 /* ForInStatement */: return emitForInStatement(node); - case 239 /* ForOfStatement */: + case 240 /* ForOfStatement */: return emitForOfStatement(node); - case 240 /* ContinueStatement */: + case 241 /* ContinueStatement */: return emitContinueStatement(node); - case 241 /* BreakStatement */: + case 242 /* BreakStatement */: return emitBreakStatement(node); - case 242 /* ReturnStatement */: + case 243 /* ReturnStatement */: return emitReturnStatement(node); - case 243 /* WithStatement */: + case 244 /* WithStatement */: return emitWithStatement(node); - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: return emitSwitchStatement(node); - case 245 /* LabeledStatement */: + case 246 /* LabeledStatement */: return emitLabeledStatement(node); - case 246 /* ThrowStatement */: + case 247 /* ThrowStatement */: return emitThrowStatement(node); - case 247 /* TryStatement */: + case 248 /* TryStatement */: return emitTryStatement(node); - case 248 /* DebuggerStatement */: + case 249 /* DebuggerStatement */: return emitDebuggerStatement(node); // Declarations - case 249 /* VariableDeclaration */: + case 250 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: return emitVariableDeclarationList(node); - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: return emitFunctionDeclaration(node); - case 252 /* ClassDeclaration */: + case 253 /* ClassDeclaration */: return emitClassDeclaration(node); - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: return emitTypeAliasDeclaration(node); - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 257 /* ModuleBlock */: + case 258 /* ModuleBlock */: return emitModuleBlock(node); - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: return emitCaseBlock(node); - case 259 /* NamespaceExportDeclaration */: + case 260 /* NamespaceExportDeclaration */: return emitNamespaceExportDeclaration(node); - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: return emitImportDeclaration(node); - case 262 /* ImportClause */: + case 263 /* ImportClause */: return emitImportClause(node); - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: return emitNamespaceImport(node); - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: return emitNamespaceExport(node); - case 264 /* NamedImports */: + case 265 /* NamedImports */: return emitNamedImports(node); - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: return emitImportSpecifier(node); - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: return emitExportAssignment(node); - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: return emitExportDeclaration(node); - case 268 /* NamedExports */: + case 269 /* NamedExports */: return emitNamedExports(node); - case 270 /* ExportSpecifier */: + case 271 /* ExportSpecifier */: return emitExportSpecifier(node); - case 271 /* MissingDeclaration */: + case 272 /* MissingDeclaration */: return; // Module references - case 272 /* ExternalModuleReference */: + case 273 /* ExternalModuleReference */: return emitExternalModuleReference(node); // JSX (non-expression) case 11 /* JsxText */: return emitJsxText(node); - case 275 /* JsxOpeningElement */: - case 278 /* JsxOpeningFragment */: + case 276 /* JsxOpeningElement */: + case 279 /* JsxOpeningFragment */: return emitJsxOpeningElementOrFragment(node); - case 276 /* JsxClosingElement */: - case 279 /* JsxClosingFragment */: + case 277 /* JsxClosingElement */: + case 280 /* JsxClosingFragment */: return emitJsxClosingElementOrFragment(node); - case 280 /* JsxAttribute */: + case 281 /* JsxAttribute */: return emitJsxAttribute(node); - case 281 /* JsxAttributes */: + case 282 /* JsxAttributes */: return emitJsxAttributes(node); - case 282 /* JsxSpreadAttribute */: + case 283 /* JsxSpreadAttribute */: return emitJsxSpreadAttribute(node); - case 283 /* JsxExpression */: + case 284 /* JsxExpression */: return emitJsxExpression(node); // Clauses - case 284 /* CaseClause */: + case 285 /* CaseClause */: return emitCaseClause(node); - case 285 /* DefaultClause */: + case 286 /* DefaultClause */: return emitDefaultClause(node); - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: return emitHeritageClause(node); - case 287 /* CatchClause */: + case 288 /* CatchClause */: return emitCatchClause(node); // Property assignments - case 288 /* PropertyAssignment */: + case 289 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 289 /* ShorthandPropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 290 /* SpreadAssignment */: + case 291 /* SpreadAssignment */: return emitSpreadAssignment(node); // Enum - case 291 /* EnumMember */: + case 292 /* EnumMember */: return emitEnumMember(node); + // Unparsed + case 293 /* UnparsedPrologue */: + return writeUnparsedNode(node); + case 300 /* UnparsedSource */: + case 294 /* UnparsedPrepend */: + return emitUnparsedSourceOrPrepend(node); + case 295 /* UnparsedText */: + case 296 /* UnparsedInternalText */: + return emitUnparsedTextLike(node); + case 297 /* UnparsedSyntheticReference */: + return emitUnparsedSyntheticReference(node); + // Top-level nodes + case 298 /* SourceFile */: + return emitSourceFile(node); + case 299 /* Bundle */: + return ts.Debug.fail("Bundles should be printed using printBundle"); + // SyntaxKind.UnparsedSource (handled above) + case 301 /* InputFiles */: + return ts.Debug.fail("InputFiles should not be printed"); // JSDoc nodes (only used in codefixes currently) - case 326 /* JSDocParameterTag */: - case 333 /* JSDocPropertyTag */: + case 302 /* JSDocTypeExpression */: + return emitJSDocTypeExpression(node); + case 303 /* JSDocNameReference */: + return emitJSDocNameReference(node); + case 304 /* JSDocAllType */: + return writePunctuation("*"); + case 305 /* JSDocUnknownType */: + return writePunctuation("?"); + case 306 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 307 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 308 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 309 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 182 /* RestType */: + case 310 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + case 311 /* JSDocNamepathType */: + return; + case 312 /* JSDocComment */: + return emitJSDoc(node); + case 314 /* JSDocTypeLiteral */: + return emitJSDocTypeLiteral(node); + case 315 /* JSDocSignature */: + return emitJSDocSignature(node); + case 317 /* JSDocTag */: + case 322 /* JSDocClassTag */: + return emitJSDocSimpleTag(node); + case 318 /* JSDocAugmentsTag */: + case 319 /* JSDocImplementsTag */: + return emitJSDocHeritageTag(node); + case 320 /* JSDocAuthorTag */: + case 321 /* JSDocDeprecatedTag */: + return; + // SyntaxKind.JSDocClassTag (see JSDocTag, above) + case 323 /* JSDocPublicTag */: + case 324 /* JSDocPrivateTag */: + case 325 /* JSDocProtectedTag */: + case 326 /* JSDocReadonlyTag */: + case 327 /* JSDocOverrideTag */: + return; + case 328 /* JSDocCallbackTag */: + return emitJSDocCallbackTag(node); + // SyntaxKind.JSDocEnumTag (see below) + case 330 /* JSDocParameterTag */: + case 337 /* JSDocPropertyTag */: return emitJSDocPropertyLikeTag(node); - case 327 /* JSDocReturnTag */: - case 329 /* JSDocTypeTag */: - case 328 /* JSDocThisTag */: - case 325 /* JSDocEnumTag */: + case 329 /* JSDocEnumTag */: + case 331 /* JSDocReturnTag */: + case 332 /* JSDocThisTag */: + case 333 /* JSDocTypeTag */: return emitJSDocSimpleTypedTag(node); - case 316 /* JSDocImplementsTag */: - case 315 /* JSDocAugmentsTag */: - return emitJSDocHeritageTag(node); - case 330 /* JSDocTemplateTag */: + case 334 /* JSDocTemplateTag */: return emitJSDocTemplateTag(node); - case 331 /* JSDocTypedefTag */: + case 335 /* JSDocTypedefTag */: return emitJSDocTypedefTag(node); - case 324 /* JSDocCallbackTag */: - return emitJSDocCallbackTag(node); - case 313 /* JSDocSignature */: - return emitJSDocSignature(node); - case 312 /* JSDocTypeLiteral */: - return emitJSDocTypeLiteral(node); - case 319 /* JSDocClassTag */: - case 314 /* JSDocTag */: - return emitJSDocSimpleTag(node); - case 332 /* JSDocSeeTag */: + case 336 /* JSDocSeeTag */: return emitJSDocSeeTag(node); - case 302 /* JSDocNameReference */: - return emitJSDocNameReference(node); - case 311 /* JSDocComment */: - return emitJSDoc(node); - // Transformation nodes (ignored) + // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) + // Transformation nodes + case 339 /* NotEmittedStatement */: + case 343 /* EndOfDeclarationMarker */: + case 342 /* MergeDeclarationMarker */: + return; } if (ts.isExpression(node)) { hint = 1 /* Expression */; if (substituteNode !== ts.noEmitSubstitution) { - lastSubstitution = node = substituteNode(hint, node); + var substitute = substituteNode(hint, node) || node; + if (substitute !== node) { + node = substitute; + if (currentParenthesizerRule) { + node = currentParenthesizerRule(node); + } + } } } - else if (ts.isToken(node)) { - return writeTokenNode(node, writePunctuation); - } } if (hint === 1 /* Expression */) { switch (node.kind) { @@ -101437,84 +104529,92 @@ var ts; // Identifiers case 78 /* Identifier */: return emitIdentifier(node); - // Reserved words - case 94 /* FalseKeyword */: - case 103 /* NullKeyword */: - case 105 /* SuperKeyword */: - case 109 /* TrueKeyword */: - case 107 /* ThisKeyword */: - case 99 /* ImportKeyword */: - writeTokenNode(node, writeKeyword); - return; // Expressions - case 199 /* ArrayLiteralExpression */: + case 200 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); - case 200 /* ObjectLiteralExpression */: + case 201 /* ObjectLiteralExpression */: return emitObjectLiteralExpression(node); - case 201 /* PropertyAccessExpression */: + case 202 /* PropertyAccessExpression */: return emitPropertyAccessExpression(node); - case 202 /* ElementAccessExpression */: + case 203 /* ElementAccessExpression */: return emitElementAccessExpression(node); - case 203 /* CallExpression */: + case 204 /* CallExpression */: return emitCallExpression(node); - case 204 /* NewExpression */: + case 205 /* NewExpression */: return emitNewExpression(node); - case 205 /* TaggedTemplateExpression */: + case 206 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: return emitTypeAssertionExpression(node); - case 207 /* ParenthesizedExpression */: + case 208 /* ParenthesizedExpression */: return emitParenthesizedExpression(node); - case 208 /* FunctionExpression */: + case 209 /* FunctionExpression */: return emitFunctionExpression(node); - case 209 /* ArrowFunction */: + case 210 /* ArrowFunction */: return emitArrowFunction(node); - case 210 /* DeleteExpression */: + case 211 /* DeleteExpression */: return emitDeleteExpression(node); - case 211 /* TypeOfExpression */: + case 212 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 212 /* VoidExpression */: + case 213 /* VoidExpression */: return emitVoidExpression(node); - case 213 /* AwaitExpression */: + case 214 /* AwaitExpression */: return emitAwaitExpression(node); - case 214 /* PrefixUnaryExpression */: + case 215 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 215 /* PostfixUnaryExpression */: + case 216 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 216 /* BinaryExpression */: + case 217 /* BinaryExpression */: return emitBinaryExpression(node); - case 217 /* ConditionalExpression */: + case 218 /* ConditionalExpression */: return emitConditionalExpression(node); - case 218 /* TemplateExpression */: + case 219 /* TemplateExpression */: return emitTemplateExpression(node); - case 219 /* YieldExpression */: + case 220 /* YieldExpression */: return emitYieldExpression(node); - case 220 /* SpreadElement */: - return emitSpreadExpression(node); - case 221 /* ClassExpression */: + case 221 /* SpreadElement */: + return emitSpreadElement(node); + case 222 /* ClassExpression */: return emitClassExpression(node); - case 222 /* OmittedExpression */: + case 223 /* OmittedExpression */: return; - case 224 /* AsExpression */: + case 225 /* AsExpression */: return emitAsExpression(node); - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: return emitNonNullExpression(node); - case 226 /* MetaProperty */: + case 227 /* MetaProperty */: return emitMetaProperty(node); + case 228 /* SyntheticExpression */: + return ts.Debug.fail("SyntheticExpression should never be printed."); // JSX - case 273 /* JsxElement */: + case 274 /* JsxElement */: return emitJsxElement(node); - case 274 /* JsxSelfClosingElement */: + case 275 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); - case 277 /* JsxFragment */: + case 278 /* JsxFragment */: return emitJsxFragment(node); + // Synthesized list + case 338 /* SyntaxList */: + return ts.Debug.fail("SyntaxList should not be printed"); // Transformation nodes - case 336 /* PartiallyEmittedExpression */: + case 339 /* NotEmittedStatement */: + return; + case 340 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 337 /* CommaListExpression */: + case 341 /* CommaListExpression */: return emitCommaList(node); + case 342 /* MergeDeclarationMarker */: + case 343 /* EndOfDeclarationMarker */: + return; + case 344 /* SyntheticReferenceExpression */: + return ts.Debug.fail("SyntheticReferenceExpression should not be printed"); } } + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + if (ts.isTokenKind(node.kind)) + return writeTokenNode(node, writePunctuation); + ts.Debug.fail("Unhandled SyntaxKind: " + ts.Debug.formatSyntaxKind(node.kind) + "."); } function emitMappedTypeParameter(node) { emit(node.name); @@ -101524,10 +104624,11 @@ var ts; emit(node.constraint); } function pipelineEmitWithSubstitution(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node); - pipelinePhase(hint, lastSubstitution); - ts.Debug.assert(lastNode === node || lastSubstitution === node); + ts.Debug.assertIsDefined(lastSubstitution); + node = lastSubstitution; + lastSubstitution = undefined; + pipelinePhase(hint, node); } function getHelpersFromBundledSourceFiles(bundle) { var result; @@ -101553,7 +104654,7 @@ var ts; } function emitHelpers(node) { var helpersEmitted = false; - var bundle = node.kind === 298 /* Bundle */ ? node : undefined; + var bundle = node.kind === 299 /* Bundle */ ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } @@ -101653,7 +104754,7 @@ var ts; var pos = getTextPosWithWriteLine(); writeUnparsedNode(unparsed); if (bundleFileInfo) { - updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 294 /* UnparsedText */ ? + updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 295 /* UnparsedText */ ? "text" /* Text */ : "internal" /* Internal */); } @@ -101699,7 +104800,7 @@ var ts; } function emitComputedPropertyName(node) { writePunctuation("["); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName); writePunctuation("]"); } // @@ -101726,18 +104827,18 @@ var ts; emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); - if (node.parent && node.parent.kind === 308 /* JSDocFunctionType */ && !node.name) { + if (node.parent && node.parent.kind === 309 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { emitTypeAnnotation(node.type); } // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. - emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitDecorator(decorator) { writePunctuation("@"); - emitExpression(decorator.expression); + emitExpression(decorator.expression, parenthesizer.parenthesizeLeftSideOfAccess); } // // Type members @@ -101788,7 +104889,7 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeKeyword(node.kind === 167 /* GetAccessor */ ? "get" : "set"); + writeKeyword(node.kind === 168 /* GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); @@ -101902,7 +105003,7 @@ var ts; writePunctuation("}"); } function emitArrayType(node) { - emit(node.elementType); + emit(node.elementType, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("["); writePunctuation("]"); } @@ -101925,21 +105026,21 @@ var ts; emit(node.type); } function emitOptionalType(node) { - emit(node.type); + emit(node.type, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("?"); } function emitUnionType(node) { - emitList(node, node.types, 516 /* UnionTypeConstituents */); + emitList(node, node.types, 516 /* UnionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitIntersectionType(node) { - emitList(node, node.types, 520 /* IntersectionTypeConstituents */); + emitList(node, node.types, 520 /* IntersectionTypeConstituents */, parenthesizer.parenthesizeMemberOfElementType); } function emitConditionalType(node) { - emit(node.checkType); + emit(node.checkType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writeKeyword("extends"); writeSpace(); - emit(node.extendsType); + emit(node.extendsType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writePunctuation("?"); writeSpace(); @@ -101965,10 +105066,10 @@ var ts; function emitTypeOperator(node) { writeTokenText(node.operator, writeKeyword); writeSpace(); - emit(node.type); + emit(node.type, parenthesizer.parenthesizeMemberOfElementType); } function emitIndexedAccessType(node) { - emit(node.objectType); + emit(node.objectType, parenthesizer.parenthesizeMemberOfElementType); writePunctuation("["); emit(node.indexType); writePunctuation("]"); @@ -102061,7 +105162,7 @@ var ts; writeSpace(); } emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // Expressions @@ -102069,7 +105170,7 @@ var ts; function emitArrayLiteralExpression(node) { var elements = node.elements; var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */; - emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine); + emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitObjectLiteralExpression(node) { ts.forEach(node.properties, generateMemberNames); @@ -102085,13 +105186,13 @@ var ts; } } function emitPropertyAccessExpression(node) { - var expression = ts.cast(emitExpression(node.expression), ts.isExpression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); var token = node.questionDotToken || ts.setTextRangePosEnd(ts.factory.createToken(24 /* DotToken */), node.expression.end, node.name.pos); var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token); var linesAfterDot = getLinesBetweenNodes(node, token, node.name); writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false); var shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ && - mayNeedDotDotForPropertyAccess(expression) && + mayNeedDotDotForPropertyAccess(node.expression) && !writer.hasTrailingComment() && !writer.hasTrailingWhitespace(); if (shouldEmitDotDot) { @@ -102127,27 +105228,27 @@ var ts; } } function emitElementAccessExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */); + emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitNewExpression(node) { emitTokenWithComment(102 /* NewKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfNew); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */); + emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitTaggedTemplateExpression(node) { - emitExpression(node.tag); + emitExpression(node.tag, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); writeSpace(); emitExpression(node.template); @@ -102156,12 +105257,12 @@ var ts; writePunctuation("<"); emit(node.type); writePunctuation(">"); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); - emitExpression(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); writeLineSeparatorsAfter(node.expression, node); decreaseIndentIf(indented); emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); @@ -102185,29 +105286,29 @@ var ts; function emitDeleteExpression(node) { emitTokenWithComment(88 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitTypeOfExpression(node) { emitTokenWithComment(111 /* TypeOfKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitVoidExpression(node) { emitTokenWithComment(113 /* VoidKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitAwaitExpression(node) { emitTokenWithComment(130 /* AwaitKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitPrefixUnaryExpression(node) { writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { writeSpace(); } - emitExpression(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPrefixUnary); } function shouldEmitWhitespaceBeforeOperand(node) { // In some cases, we need to emit a space between the operator and the operand. One obvious case @@ -102223,84 +105324,101 @@ var ts; // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. var operand = node.operand; - return operand.kind === 214 /* PrefixUnaryExpression */ + return operand.kind === 215 /* PrefixUnaryExpression */ && ((node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */)) || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */))); } function emitPostfixUnaryExpression(node) { - emitExpression(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary); writeTokenText(node.operator, writeOperator); } - var EmitBinaryExpressionState; - (function (EmitBinaryExpressionState) { - EmitBinaryExpressionState[EmitBinaryExpressionState["EmitLeft"] = 0] = "EmitLeft"; - EmitBinaryExpressionState[EmitBinaryExpressionState["EmitRight"] = 1] = "EmitRight"; - EmitBinaryExpressionState[EmitBinaryExpressionState["FinishEmit"] = 2] = "FinishEmit"; - })(EmitBinaryExpressionState || (EmitBinaryExpressionState = {})); - /** - * emitBinaryExpression includes an embedded work stack to attempt to handle as many nested binary expressions - * as possible without creating any additional stack frames. This can only be done when the emit pipeline does - * not require notification/substitution/comment/sourcemap decorations. - */ - function emitBinaryExpression(node) { - var nodeStack = [node]; - var stateStack = [0 /* EmitLeft */]; - var stackIndex = 0; - while (stackIndex >= 0) { - node = nodeStack[stackIndex]; - switch (stateStack[stackIndex]) { - case 0 /* EmitLeft */: { - maybePipelineEmitExpression(node.left); - break; - } - case 1 /* EmitRight */: { - var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */; - var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); - var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); - writeLinesAndIndent(linesBeforeOperator, isCommaOperator); - emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken, node.operatorToken.kind === 100 /* InKeyword */ ? writeKeyword : writeOperator); - emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts - writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); - maybePipelineEmitExpression(node.right); - break; - } - case 2 /* FinishEmit */: { - var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); - var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); - decreaseIndentIf(linesBeforeOperator, linesAfterOperator); - stackIndex--; - break; - } - default: return ts.Debug.fail("Invalid state " + stateStack[stackIndex] + " for emitBinaryExpressionWorker"); + function createEmitBinaryExpression() { + return ts.createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined); + function onEnter(node, state) { + if (state) { + state.stackIndex++; + state.preserveSourceNewlinesStack[state.stackIndex] = preserveSourceNewlines; + state.containerPosStack[state.stackIndex] = containerPos; + state.containerEndStack[state.stackIndex] = containerEnd; + state.declarationListContainerEndStack[state.stackIndex] = declarationListContainerEnd; + var emitComments_1 = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node); + var emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node); + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(node); + if (emitComments_1) + emitCommentsBeforeNode(node); + if (emitSourceMaps) + emitSourceMapsBeforeNode(node); + beforeEmitNode(node); } - } - function maybePipelineEmitExpression(next) { - // Advance the state of this unit of work, - stateStack[stackIndex]++; - // Then actually do the work of emitting the node `next` returned by the prior state - // The following section should be identical to `pipelineEmit` save it assumes EmitHint.Expression and offloads - // binary expression handling, where possible, to the contained work queue - // #region trampolinePipelineEmit - var savedLastNode = lastNode; - var savedLastSubstitution = lastSubstitution; - lastNode = next; - lastSubstitution = undefined; + else { + state = { + stackIndex: 0, + preserveSourceNewlinesStack: [undefined], + containerPosStack: [-1], + containerEndStack: [-1], + declarationListContainerEndStack: [-1], + shouldEmitCommentsStack: [false], + shouldEmitSourceMapsStack: [false], + }; + } + return state; + } + function onLeft(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "left"); + } + function onOperator(operatorToken, _state, node) { + var isCommaOperator = operatorToken.kind !== 27 /* CommaToken */; + var linesBeforeOperator = getLinesBetweenNodes(node, node.left, operatorToken); + var linesAfterOperator = getLinesBetweenNodes(node, operatorToken, node.right); + writeLinesAndIndent(linesBeforeOperator, isCommaOperator); + emitLeadingCommentsOfPosition(operatorToken.pos); + writeTokenNode(operatorToken, operatorToken.kind === 100 /* InKeyword */ ? writeKeyword : writeOperator); + emitTrailingCommentsOfPosition(operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts + writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); + } + function onRight(next, _workArea, parent) { + return maybeEmitExpression(next, parent, "right"); + } + function onExit(node, state) { + var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); + var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); + decreaseIndentIf(linesBeforeOperator, linesAfterOperator); + if (state.stackIndex > 0) { + var savedPreserveSourceNewlines = state.preserveSourceNewlinesStack[state.stackIndex]; + var savedContainerPos = state.containerPosStack[state.stackIndex]; + var savedContainerEnd = state.containerEndStack[state.stackIndex]; + var savedDeclarationListContainerEnd = state.declarationListContainerEndStack[state.stackIndex]; + var shouldEmitComments_1 = state.shouldEmitCommentsStack[state.stackIndex]; + var shouldEmitSourceMaps_1 = state.shouldEmitSourceMapsStack[state.stackIndex]; + afterEmitNode(savedPreserveSourceNewlines); + if (shouldEmitSourceMaps_1) + emitSourceMapsAfterNode(node); + if (shouldEmitComments_1) + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(node); + state.stackIndex--; + } + } + function maybeEmitExpression(next, parent, side) { + var parenthesizerRule = side === "left" ? + parenthesizer.getParenthesizeLeftSideOfBinaryForOperator(parent.operatorToken.kind) : + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(parent.operatorToken.kind); var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next); - if (pipelinePhase === pipelineEmitWithHint && ts.isBinaryExpression(next)) { - // If the target pipeline phase is emit directly, and the next node's also a binary expression, - // skip all the intermediate indirection and push the expression directly onto the work stack - stackIndex++; - stateStack[stackIndex] = 0 /* EmitLeft */; - nodeStack[stackIndex] = next; + if (pipelinePhase === pipelineEmitWithSubstitution) { + ts.Debug.assertIsDefined(lastSubstitution); + next = parenthesizerRule(ts.cast(lastSubstitution, ts.isExpression)); + pipelinePhase = getNextPipelinePhase(1 /* Substitution */, 1 /* Expression */, next); + lastSubstitution = undefined; } - else { - pipelinePhase(1 /* Expression */, next); + if (pipelinePhase === pipelineEmitWithComments || + pipelinePhase === pipelineEmitWithSourceMaps || + pipelinePhase === pipelineEmitWithHint) { + if (ts.isBinaryExpression(next)) { + return next; + } } - ts.Debug.assert(lastNode === next); - lastNode = savedLastNode; - lastSubstitution = savedLastSubstitution; - // #endregion trampolinePipelineEmit + currentParenthesizerRule = parenthesizerRule; + pipelinePhase(1 /* Expression */, next); } } function emitConditionalExpression(node) { @@ -102308,16 +105426,16 @@ var ts; var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue); var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken); var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse); - emitExpression(node.condition); + emitExpression(node.condition, parenthesizer.parenthesizeConditionOfConditionalExpression); writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); emit(node.questionToken); writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true); - emitExpression(node.whenTrue); + emitExpression(node.whenTrue, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion); writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true); emit(node.colonToken); writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true); - emitExpression(node.whenFalse); + emitExpression(node.whenFalse, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeColon, linesAfterColon); } function emitTemplateExpression(node) { @@ -102327,22 +105445,22 @@ var ts; function emitYieldExpression(node) { emitTokenWithComment(124 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); - emitExpressionWithLeadingSpace(node.expression); + emitExpressionWithLeadingSpace(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } - function emitSpreadExpression(node) { + function emitSpreadElement(node) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitClassExpression(node) { generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); } function emitAsExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); if (node.type) { writeSpace(); writeKeyword("as"); @@ -102351,7 +105469,7 @@ var ts; } } function emitNonNullExpression(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); writeOperator("!"); } function emitMetaProperty(node) { @@ -102394,7 +105512,7 @@ var ts; } } function emitExpressionStatement(node) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfExpressionStatement); // Emit semicolon in non json files // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { @@ -102411,7 +105529,7 @@ var ts; if (node.elseStatement) { writeLineOrSpace(node, node.thenStatement, node.elseStatement); emitTokenWithComment(90 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); - if (node.elseStatement.kind === 234 /* IfStatement */) { + if (node.elseStatement.kind === 235 /* IfStatement */) { writeSpace(); emit(node.elseStatement); } @@ -102474,7 +105592,7 @@ var ts; emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(156 /* OfKeyword */, node.initializer.end, writeKeyword, node); + emitTokenWithComment(157 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node); @@ -102482,7 +105600,7 @@ var ts; } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 250 /* VariableDeclarationList */) { + if (node.kind === 251 /* VariableDeclarationList */) { emit(node); } else { @@ -102519,7 +105637,7 @@ var ts; } pos = writeTokenText(token, writer, pos); if (isSimilarNode && contextNode.end !== pos) { - var isJsxExprContext = contextNode.kind === 283 /* JsxExpression */; + var isJsxExprContext = contextNode.kind === 284 /* JsxExpression */; emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ !isJsxExprContext, /*forceNoNewline*/ isJsxExprContext); } return pos; @@ -102583,7 +105701,7 @@ var ts; emit(node.name); emit(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitVariableDeclarationList(node) { writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); @@ -102602,9 +105720,6 @@ var ts; emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } - function emitBlockCallback(_hint, body) { - emitBlockFunctionBody(body); - } function emitSignatureAndBody(node, emitSignatureHead) { var body = node.body; if (body) { @@ -102617,12 +105732,7 @@ var ts; ts.forEach(node.parameters, generateNames); generateNames(node.body); emitSignatureHead(node); - if (onEmitNode) { - onEmitNode(4 /* Unspecified */, body, emitBlockCallback); - } - else { - emitBlockFunctionBody(body); - } + emitBlockFunctionBody(body); popNameGenerationScope(node); if (indentedFlag) { decreaseIndent(); @@ -102631,7 +105741,7 @@ var ts; else { emitSignatureHead(node); writeSpace(); - emitExpression(body); + emitExpression(body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); } } else { @@ -102675,6 +105785,7 @@ var ts; return true; } function emitBlockFunctionBody(body) { + onBeforeEmitNode === null || onBeforeEmitNode === void 0 ? void 0 : onBeforeEmitNode(body); writeSpace(); writePunctuation("{"); increaseIndent(); @@ -102689,6 +105800,7 @@ var ts; } decreaseIndent(); writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body); + onAfterEmitNode === null || onAfterEmitNode === void 0 ? void 0 : onAfterEmitNode(body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); @@ -102704,7 +105816,7 @@ var ts; increaseIndent(); } else { - emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset); + emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, /*parenthesizerRule*/ undefined, statementOffset); } } function emitClassDeclaration(node) { @@ -102779,7 +105891,7 @@ var ts; var body = node.body; if (!body) return writeTrailingSemicolon(); - while (body.kind === 256 /* ModuleDeclaration */) { + while (body && ts.isModuleDeclaration(body)) { writePunctuation("."); emit(body.name); body = body.body; @@ -102869,7 +105981,9 @@ var ts; emitTokenWithComment(87 /* DefaultKeyword */, nextPos, writeKeyword, node); } writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, node.isExportEquals ? + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(62 /* EqualsToken */) : + parenthesizer.parenthesizeExpressionOfExportDefault); writeTrailingSemicolon(); } function emitExportDeclaration(node) { @@ -103041,7 +106155,7 @@ var ts; function emitCaseClause(node) { emitTokenWithComment(81 /* CaseKeyword */, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } function emitDefaultClause(node) { @@ -103102,7 +106216,7 @@ var ts; var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } - emitExpression(initializer); + emitExpression(initializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitShorthandPropertyAssignment(node) { emit(node.name); @@ -103110,13 +106224,13 @@ var ts; writeSpace(); writePunctuation("="); writeSpace(); - emitExpression(node.objectAssignmentInitializer); + emitExpression(node.objectAssignmentInitializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } } function emitSpreadAssignment(node) { if (node.expression) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } } // @@ -103124,7 +106238,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // // JSDoc @@ -103132,18 +106246,21 @@ var ts; function emitJSDoc(node) { write("/**"); if (node.comment) { - var lines = node.comment.split(/\r\n?|\n/g); - for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { - var line = lines_2[_a]; - writeLine(); - writeSpace(); - writePunctuation("*"); - writeSpace(); - write(line); + var text = ts.getTextOfJSDocComment(node.comment); + if (text) { + var lines = text.split(/\r\n?|\n/g); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var line = lines_2[_a]; + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } } } if (node.tags) { - if (node.tags.length === 1 && node.tags[0].kind === 329 /* JSDocTypeTag */ && !node.comment) { + if (node.tags.length === 1 && node.tags[0].kind === 333 /* JSDocTypeTag */ && !node.comment) { writeSpace(); emit(node.tags[0]); } @@ -103188,7 +106305,7 @@ var ts; function emitJSDocTypedefTag(tag) { emitJSDocTagName(tag.tagName); if (tag.typeExpression) { - if (tag.typeExpression.kind === 301 /* JSDocTypeExpression */) { + if (tag.typeExpression.kind === 302 /* JSDocTypeExpression */) { emitJSDocTypeExpression(tag.typeExpression); } else { @@ -103207,7 +106324,7 @@ var ts; emit(tag.fullName); } emitJSDocComment(tag.comment); - if (tag.typeExpression && tag.typeExpression.kind === 312 /* JSDocTypeLiteral */) { + if (tag.typeExpression && tag.typeExpression.kind === 314 /* JSDocTypeLiteral */) { emitJSDocTypeLiteral(tag.typeExpression); } } @@ -103260,9 +106377,10 @@ var ts; emit(tagName); } function emitJSDocComment(comment) { - if (comment) { + var text = ts.getTextOfJSDocComment(comment); + if (text) { writeSpace(); - write(comment); + write(text); } } function emitJSDocTypeExpression(typeExpression) { @@ -103365,7 +106483,7 @@ var ts; emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); emitTripleSlashDirectivesIfNeeded(node); - emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); + emitList(node, statements, 1 /* MultiLine */, /*parenthesizerRule*/ undefined, index === -1 ? statements.length : index); popNameGenerationScope(node); } // Transformation nodes @@ -103373,7 +106491,7 @@ var ts; emitExpression(node.expression); } function emitCommaList(node) { - emitExpressionList(node, node.elements, 528 /* CommaListElements */); + emitExpressionList(node, node.elements, 528 /* CommaListElements */, /*parenthesizerRule*/ undefined); } /** * Emits any prologue directives at the start of a Statement list, returning the @@ -103519,12 +106637,12 @@ var ts; emit(node); } } - function emitInitializer(node, equalCommentStartPos, container) { + function emitInitializer(node, equalCommentStartPos, container, parenthesizerRule) { if (node) { writeSpace(); emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container); writeSpace(); - emitExpression(node); + emitExpression(node, parenthesizerRule); } } function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { @@ -103539,10 +106657,10 @@ var ts; emit(node); } } - function emitExpressionWithLeadingSpace(node) { + function emitExpressionWithLeadingSpace(node, parenthesizerRule) { if (node) { writeSpace(); - emitExpression(node); + emitExpression(node, parenthesizerRule); } } function emitWithTrailingSpace(node) { @@ -103572,7 +106690,7 @@ var ts; emitList(parentNode, decorators, 2146305 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 53776 /* TypeArguments */); + emitList(parentNode, typeArguments, 53776 /* TypeArguments */, parenthesizer.parenthesizeMemberOfElementType); } function emitTypeParameters(parentNode, typeParameters) { if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures @@ -103611,12 +106729,6 @@ var ts; function emitParametersForIndexSignature(parentNode, parameters) { emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */); } - function emitList(parentNode, children, format, start, count) { - emitNodeList(emit, parentNode, children, format, start, count); - } - function emitExpressionList(parentNode, children, format, start, count) { - emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 - } function writeDelimiter(format) { switch (format & 60 /* DelimitersMask */) { case 0 /* None */: @@ -103639,7 +106751,13 @@ var ts; break; } } - function emitNodeList(emit, parentNode, children, format, start, count) { + function emitList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count); + } + function emitExpressionList(parentNode, children, format, parenthesizerRule, start, count) { + emitNodeList(emitExpression, parentNode, children, format, parenthesizerRule, start, count); + } + function emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } var isUndefined = children === undefined; @@ -103658,8 +106776,7 @@ var ts; } if (format & 15360 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); - if (isEmpty && !isUndefined) { - // TODO: GH#18217 + if (isEmpty && children) { emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists } } @@ -103668,7 +106785,7 @@ var ts; } if (isEmpty) { // Write a line terminator if the parent node was multi-line - if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && ts.rangeIsOnSingleLine(parentNode, currentSourceFile))) { + if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && (!parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile)))) { writeLine(); } else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) { @@ -103676,6 +106793,7 @@ var ts; } } else { + ts.Debug.type(children); // Write the opening line terminator or leading whitespace. var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; @@ -103710,7 +106828,7 @@ var ts; // a // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline // , - if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { + if (format & 60 /* DelimitersMask */ && previousSibling.end !== (parentNode ? parentNode.end : -1)) { emitLeadingCommentsOfPosition(previousSibling.end); } writeDelimiter(format); @@ -103743,7 +106861,12 @@ var ts; shouldEmitInterveningComments = mayEmitInterveningComments; } nextListElementPos = child.pos; - emit(child); + if (emit.length === 1) { + emit(child); + } + else { + emit(child, parenthesizerRule); + } if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); shouldDecreaseIndentAfterEmit = false; @@ -103768,7 +106891,7 @@ var ts; // 2 // /* end of element 2 */ // ]; - if (previousSibling && parentNode.end !== previousSibling.end && (format & 60 /* DelimitersMask */) && !skipTrailingComments) { + if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & 60 /* DelimitersMask */) && !skipTrailingComments) { emitLeadingCommentsOfPosition(hasTrailingComma && (children === null || children === void 0 ? void 0 : children.end) ? children.end : previousSibling.end); } // Decrease the indent, if requested. @@ -103789,8 +106912,7 @@ var ts; onAfterEmitNodeArray(children); } if (format & 15360 /* BracketsMask */) { - if (isEmpty && !isUndefined) { - // TODO: GH#18217 + if (isEmpty && children) { emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists } writePunctuation(getClosingBracket(format)); @@ -103921,7 +107043,7 @@ var ts; } var firstChild_1 = children[0]; if (firstChild_1 === undefined) { - return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; + return !parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } if (firstChild_1.pos === nextListElementPos) { // If this child starts at the beginning of a list item in a parent list, its leading @@ -103945,7 +107067,8 @@ var ts; // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } - if (!ts.positionIsSynthesized(parentNode.pos) && + if (parentNode && + !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || ts.getOriginalNode(firstChild_1.parent) === ts.getOriginalNode(parentNode))) { if (preserveSourceNewlines) { @@ -103968,10 +107091,10 @@ var ts; // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } - else if (!ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode) && previousNode.parent === nextNode.parent) { - if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); }); - } + else if (preserveSourceNewlines && siblingNodePositionsAreComparable(previousNode, nextNode)) { + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); }); + } + else if (!preserveSourceNewlines && !ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode)) { return ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1; } else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) { @@ -103990,9 +107113,9 @@ var ts; } var lastChild = ts.lastOrUndefined(children); if (lastChild === undefined) { - return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; + return !parentNode || ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } - if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { + if (parentNode && !ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { if (preserveSourceNewlines) { var end_1 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end; return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_1, parentNode.end, currentSourceFile, includeComments); }); @@ -104078,7 +107201,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 207 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + while (node.kind === 208 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -104148,84 +107271,84 @@ var ts; if (!node) return; switch (node.kind) { - case 230 /* Block */: + case 231 /* Block */: ts.forEach(node.statements, generateNames); break; - case 245 /* LabeledStatement */: - case 243 /* WithStatement */: - case 235 /* DoStatement */: - case 236 /* WhileStatement */: + case 246 /* LabeledStatement */: + case 244 /* WithStatement */: + case 236 /* DoStatement */: + case 237 /* WhileStatement */: generateNames(node.statement); break; - case 234 /* IfStatement */: + case 235 /* IfStatement */: generateNames(node.thenStatement); generateNames(node.elseStatement); break; - case 237 /* ForStatement */: - case 239 /* ForOfStatement */: - case 238 /* ForInStatement */: + case 238 /* ForStatement */: + case 240 /* ForOfStatement */: + case 239 /* ForInStatement */: generateNames(node.initializer); generateNames(node.statement); break; - case 244 /* SwitchStatement */: + case 245 /* SwitchStatement */: generateNames(node.caseBlock); break; - case 258 /* CaseBlock */: + case 259 /* CaseBlock */: ts.forEach(node.clauses, generateNames); break; - case 284 /* CaseClause */: - case 285 /* DefaultClause */: + case 285 /* CaseClause */: + case 286 /* DefaultClause */: ts.forEach(node.statements, generateNames); break; - case 247 /* TryStatement */: + case 248 /* TryStatement */: generateNames(node.tryBlock); generateNames(node.catchClause); generateNames(node.finallyBlock); break; - case 287 /* CatchClause */: + case 288 /* CatchClause */: generateNames(node.variableDeclaration); generateNames(node.block); break; - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: generateNames(node.declarationList); break; - case 250 /* VariableDeclarationList */: + case 251 /* VariableDeclarationList */: ts.forEach(node.declarations, generateNames); break; - case 249 /* VariableDeclaration */: - case 160 /* Parameter */: - case 198 /* BindingElement */: - case 252 /* ClassDeclaration */: + case 250 /* VariableDeclaration */: + case 161 /* Parameter */: + case 199 /* BindingElement */: + case 253 /* ClassDeclaration */: generateNameIfNeeded(node.name); break; - case 251 /* FunctionDeclaration */: + case 252 /* FunctionDeclaration */: generateNameIfNeeded(node.name); if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { ts.forEach(node.parameters, generateNames); generateNames(node.body); } break; - case 196 /* ObjectBindingPattern */: - case 197 /* ArrayBindingPattern */: + case 197 /* ObjectBindingPattern */: + case 198 /* ArrayBindingPattern */: ts.forEach(node.elements, generateNames); break; - case 261 /* ImportDeclaration */: + case 262 /* ImportDeclaration */: generateNames(node.importClause); break; - case 262 /* ImportClause */: + case 263 /* ImportClause */: generateNameIfNeeded(node.name); generateNames(node.namedBindings); break; - case 263 /* NamespaceImport */: + case 264 /* NamespaceImport */: generateNameIfNeeded(node.name); break; - case 269 /* NamespaceExport */: + case 270 /* NamespaceExport */: generateNameIfNeeded(node.name); break; - case 264 /* NamedImports */: + case 265 /* NamedImports */: ts.forEach(node.elements, generateNames); break; - case 265 /* ImportSpecifier */: + case 266 /* ImportSpecifier */: generateNameIfNeeded(node.propertyName || node.name); break; } @@ -104234,12 +107357,12 @@ var ts; if (!node) return; switch (node.kind) { - case 288 /* PropertyAssignment */: - case 289 /* ShorthandPropertyAssignment */: - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 289 /* PropertyAssignment */: + case 290 /* ShorthandPropertyAssignment */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: generateNameIfNeeded(node.name); break; } @@ -104421,23 +107544,23 @@ var ts; switch (node.kind) { case 78 /* Identifier */: return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); - case 256 /* ModuleDeclaration */: - case 255 /* EnumDeclaration */: + case 257 /* ModuleDeclaration */: + case 256 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 261 /* ImportDeclaration */: - case 267 /* ExportDeclaration */: + case 262 /* ImportDeclaration */: + case 268 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 251 /* FunctionDeclaration */: - case 252 /* ClassDeclaration */: - case 266 /* ExportAssignment */: + case 252 /* FunctionDeclaration */: + case 253 /* ClassDeclaration */: + case 267 /* ExportAssignment */: return generateNameForExportDefault(); - case 221 /* ClassExpression */: + case 222 /* ClassExpression */: return generateNameForClassExpression(); - case 165 /* MethodDeclaration */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: + case 166 /* MethodDeclaration */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: return generateNameForMethodOrAccessor(node); - case 158 /* ComputedPropertyName */: + case 159 /* ComputedPropertyName */: return makeTempVariableName(0 /* Auto */, /*reserveInNestedScopes*/ true); default: return makeTempVariableName(0 /* Auto */); @@ -104480,25 +107603,45 @@ var ts; } // Comments function pipelineEmitWithComments(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); + var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node); + var savedContainerPos = containerPos; + var savedContainerEnd = containerEnd; + var savedDeclarationListContainerEnd = declarationListContainerEnd; + emitCommentsBeforeNode(node); + pipelinePhase(hint, node); + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitCommentsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit leading comments + emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = true; + } + } + function emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { + var emitFlags = ts.getEmitFlags(node); + var commentRange = ts.getCommentRange(node); + // Emit trailing comments + if (emitFlags & 2048 /* NoNestedComments */) { + commentsDisabled = false; + } + emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + function emitLeadingCommentsOfNode(node, emitFlags, pos, end) { enterComment(); hasWrittenComment = false; - var emitFlags = ts.getEmitFlags(node); - var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; - var isEmittedNode = node.kind !== 335 /* NotEmittedStatement */; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */; var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; // Save current container state on the stack. - var savedContainerPos = containerPos; - var savedContainerEnd = containerEnd; - var savedDeclarationListContainerEnd = declarationListContainerEnd; if ((pos > 0 || end > 0) && pos !== end) { // Emit leading comments if the position is not synthesized and the node // has not opted out from emitting leading comments. if (!skipLeadingComments) { - emitLeadingComments(pos, isEmittedNode); + emitLeadingComments(pos, /*isEmittedNode*/ node.kind !== 339 /* NotEmittedStatement */); } if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) { // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments. @@ -104509,23 +107652,17 @@ var ts; containerEnd = end; // To avoid invalid comment emit in a down-level binding pattern, we // keep track of the last declaration list container's end - if (node.kind === 250 /* VariableDeclarationList */) { + if (node.kind === 251 /* VariableDeclarationList */) { declarationListContainerEnd = end; } } } ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); exitComment(); - var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node); - if (emitFlags & 2048 /* NoNestedComments */) { - commentsDisabled = true; - pipelinePhase(hint, node); - commentsDisabled = false; - } - else { - pipelinePhase(hint, node); - } + } + function emitTrailingCommentsOfNode(node, emitFlags, pos, end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd) { enterComment(); + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */; ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); if ((pos > 0 || end > 0) && pos !== end) { // Restore previous container state. @@ -104534,12 +107671,11 @@ var ts; declarationListContainerEnd = savedDeclarationListContainerEnd; // Emit trailing comments if the position is not synthesized and the node // has not opted out from emitting leading comments and is an emitted node. - if (!skipTrailingComments && isEmittedNode) { + if (!skipTrailingComments && node.kind !== 339 /* NotEmittedStatement */) { emitTrailingComments(end); } } exitComment(); - ts.Debug.assert(lastNode === node || lastSubstitution === node); } function emitLeadingSynthesizedComment(comment) { if (comment.hasLeadingNewline || comment.kind === 2 /* SingleLineCommentTrivia */) { @@ -104599,6 +107735,23 @@ var ts; } exitComment(); } + function siblingNodePositionsAreComparable(previousNode, nextNode) { + if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) { + return false; + } + if (nextNode.pos < previousNode.end) { + return false; + } + previousNode = ts.getOriginalNode(previousNode); + nextNode = ts.getOriginalNode(nextNode); + var parent = previousNode.parent; + if (!parent || parent !== nextNode.parent) { + return false; + } + var parentNodeArray = ts.getContainingNodeArray(previousNode); + var prevNodeIndex = parentNodeArray === null || parentNodeArray === void 0 ? void 0 : parentNodeArray.indexOf(previousNode); + return prevNodeIndex !== undefined && prevNodeIndex > -1 && parentNodeArray.indexOf(nextNode) === prevNodeIndex + 1; + } function emitLeadingComments(pos, isEmittedNode) { hasWrittenComment = false; if (isEmittedNode) { @@ -104771,42 +107924,49 @@ var ts; } return node.parsedSourceMap || undefined; } - function pipelineEmitWithSourceMap(hint, node) { - ts.Debug.assert(lastNode === node || lastSubstitution === node); + function pipelineEmitWithSourceMaps(hint, node) { var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node); - if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) { - pipelinePhase(hint, node); - } - else if (ts.isUnparsedNode(node)) { + emitSourceMapsBeforeNode(node); + pipelinePhase(hint, node); + emitSourceMapsAfterNode(node); + } + function emitSourceMapsBeforeNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit leading sourcemap + if (ts.isUnparsedNode(node)) { + ts.Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); var parsed = getParsedSourceMap(node.parent); if (parsed && sourceMapGenerator) { sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); } - pipelinePhase(hint, node); } else { - var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; - var emitFlags = ts.getEmitFlags(node); - if (node.kind !== 335 /* NotEmittedStatement */ + var source = sourceMapRange.source || sourceMapSource; + if (node.kind !== 339 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 - && pos >= 0) { - emitSourcePos(source, skipSourceTrivia(source, pos)); + && sourceMapRange.pos >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); } if (emitFlags & 64 /* NoNestedSourceMaps */) { sourceMapsDisabled = true; - pipelinePhase(hint, node); - sourceMapsDisabled = false; } - else { - pipelinePhase(hint, node); + } + } + function emitSourceMapsAfterNode(node) { + var emitFlags = ts.getEmitFlags(node); + var sourceMapRange = ts.getSourceMapRange(node); + // Emit trailing sourcemap + if (!ts.isUnparsedNode(node)) { + if (emitFlags & 64 /* NoNestedSourceMaps */) { + sourceMapsDisabled = false; } - if (node.kind !== 335 /* NotEmittedStatement */ + if (node.kind !== 339 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 - && end >= 0) { - emitSourcePos(source, end); + && sourceMapRange.end >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); } } - ts.Debug.assert(lastNode === node || lastSubstitution === node); } /** * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source @@ -104958,12 +108118,22 @@ var ts; return ts.getBaseFileName(ts.normalizePath(fileName)); } function createCachedFileSystemEntries(rootDir, rootDirPath) { - var resultFromHost = { - files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories(rootDir) || [] - }; - cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); - return resultFromHost; + var _a; + if (!host.realpath || ts.ensureTrailingDirectorySeparator(toPath(host.realpath(rootDir))) === rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); + return resultFromHost; + } + // If the directory is symlink do not cache the result + if ((_a = host.directoryExists) === null || _a === void 0 ? void 0 : _a.call(host, rootDir)) { + cachedReadDirectoryResult.set(rootDirPath, false); + return false; + } + // Non existing directory + return undefined; } /** * If the readDirectory result was already cached, it returns that @@ -105038,17 +108208,32 @@ var ts; } function readDirectory(rootDir, extensions, excludes, includes, depth) { var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { + var rootResult = tryReadDirectory(rootDir, rootDirPath); + var rootSymLinkResult; + if (rootResult !== undefined) { return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir) { var path = toPath(dir); if (path === rootDirPath) { - return result; - } - return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + return rootResult || getFileSystemEntriesFromHost(dir, path); + } + var result = tryReadDirectory(dir, path); + return result !== undefined ? + result || getFileSystemEntriesFromHost(dir, path) : + ts.emptyFileSystemEntries; + } + function getFileSystemEntriesFromHost(dir, path) { + if (rootSymLinkResult && path === rootDirPath) + return rootSymLinkResult; + var result = { + files: ts.map(host.readDirectory(dir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || ts.emptyArray, + directories: host.getDirectories(dir) || ts.emptyArray + }; + if (path === rootDirPath) + rootSymLinkResult = result; + return result; } } function realpath(s) { @@ -105056,7 +108241,7 @@ var ts; } function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { + if (existingResult !== undefined) { // Just clear the cache for now // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated clearCache(); @@ -105116,9 +108301,9 @@ var ts; /** * Updates the map of shared extended config file watches with a new set of extended config files from a base config file of the project */ - function updateSharedExtendedConfigFileWatcher(projectPath, parsed, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath) { + function updateSharedExtendedConfigFileWatcher(projectPath, options, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath) { var _a; - var extendedConfigs = ts.arrayToMap(((_a = parsed === null || parsed === void 0 ? void 0 : parsed.options.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath); + var extendedConfigs = ts.arrayToMap(((_a = options === null || options === void 0 ? void 0 : options.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath); // remove project from all unrelated watchers extendedConfigFilesMap.forEach(function (watcher, extendedConfigFilePath) { if (!extendedConfigs.has(extendedConfigFilePath)) { @@ -105136,12 +108321,12 @@ var ts; // start watching previously unseen extended config extendedConfigFilesMap.set(extendedConfigFilePath, { projects: new ts.Set([projectPath]), - fileWatcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath), + watcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath), close: function () { var existing = extendedConfigFilesMap.get(extendedConfigFilePath); if (!existing || existing.projects.size !== 0) return; - existing.fileWatcher.close(); + existing.watcher.close(); extendedConfigFilesMap.delete(extendedConfigFilePath); }, }); @@ -105149,6 +108334,31 @@ var ts; }); } ts.updateSharedExtendedConfigFileWatcher = updateSharedExtendedConfigFileWatcher; + /** + * Remove the project from the extended config file watchers and close not needed watches + */ + function clearSharedExtendedConfigFileWatcher(projectPath, extendedConfigFilesMap) { + extendedConfigFilesMap.forEach(function (watcher) { + if (watcher.projects.delete(projectPath)) + watcher.close(); + }); + } + ts.clearSharedExtendedConfigFileWatcher = clearSharedExtendedConfigFileWatcher; + /** + * Clean the extendsConfigCache when extended config file has changed + */ + function cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath) { + if (!extendedConfigCache.delete(extendedConfigFilePath)) + return; + extendedConfigCache.forEach(function (_a, key) { + var _b; + var extendedResult = _a.extendedResult; + if ((_b = extendedResult.extendedSourceFiles) === null || _b === void 0 ? void 0 : _b.some(function (extendedFile) { return toPath(extendedFile) === extendedConfigFilePath; })) { + cleanExtendedConfigCache(extendedConfigCache, key, toPath); + } + }); + } + ts.cleanExtendedConfigCache = cleanExtendedConfigCache; /** * Updates the existing missing file watches with the new set of missing files after new program is created */ @@ -105200,7 +108410,7 @@ var ts; ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; /* @internal */ function isIgnoredFileFromWildCardWatching(_a) { - var watchedDirPath = _a.watchedDirPath, fileOrDirectory = _a.fileOrDirectory, fileOrDirectoryPath = _a.fileOrDirectoryPath, configFileName = _a.configFileName, options = _a.options, program = _a.program, extraFileExtensions = _a.extraFileExtensions, currentDirectory = _a.currentDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, writeLog = _a.writeLog; + var watchedDirPath = _a.watchedDirPath, fileOrDirectory = _a.fileOrDirectory, fileOrDirectoryPath = _a.fileOrDirectoryPath, configFileName = _a.configFileName, options = _a.options, program = _a.program, extraFileExtensions = _a.extraFileExtensions, currentDirectory = _a.currentDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, writeLog = _a.writeLog, toPath = _a.toPath; var newPath = ts.removeIgnoredPath(fileOrDirectoryPath); if (!newPath) { writeLog("Project: " + configFileName + " Detected ignored path: " + fileOrDirectory); @@ -105236,7 +108446,8 @@ var ts; } // just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(fileOrDirectoryPath); - var realProgram = isBuilderProgram(program) ? program.getProgramOrUndefined() : program; + var realProgram = ts.isArray(program) ? undefined : isBuilderProgram(program) ? program.getProgramOrUndefined() : program; + var builderProgram = !realProgram && !ts.isArray(program) ? program : undefined; if (hasSourceFile((filePathWithoutExtension + ".ts" /* Ts */)) || hasSourceFile((filePathWithoutExtension + ".tsx" /* Tsx */))) { writeLog("Project: " + configFileName + " Detected output file: " + fileOrDirectory); @@ -105246,7 +108457,9 @@ var ts; function hasSourceFile(file) { return realProgram ? !!realProgram.getSourceFileByPath(file) : - program.getState().fileInfos.has(file); + builderProgram ? + builderProgram.getState().fileInfos.has(file) : + !!ts.find(program, function (rootFile) { return toPath(rootFile) === file; }); } } ts.isIgnoredFileFromWildCardWatching = isIgnoredFileFromWildCardWatching; @@ -105720,7 +108933,7 @@ var ts; var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; var lineContent = file.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); // trim from end - lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + lineContent = lineContent.replace(/\t/g, " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); @@ -105925,38 +109138,31 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, 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 === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames())) { + if (!program || (hasChangedAutomaticTypeDirectiveNames === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames())) return false; - } // If root file names don't match - if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) { + if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) return false; - } var seenResolvedRefs; // If project references don't match - if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + 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)) { + if (program.getSourceFiles().some(sourceFileNotUptoDate)) return false; - } // If any of the missing file paths are now created - if (program.getMissingFilePaths().some(fileExists)) { + if (program.getMissingFilePaths().some(fileExists)) return false; - } var currentOptions = program.getCompilerOptions(); // If the compilation settings do no match, then the program is not up-to-date - if (!ts.compareDataObjects(currentOptions, newOptions)) { + if (!ts.compareDataObjects(currentOptions, newOptions)) return false; - } // If everything matches but the text of config file is changed, // error locations can change for program options, so update the program - if (currentOptions.configFile && newOptions.configFile) { + if (currentOptions.configFile && newOptions.configFile) return currentOptions.configFile.text === newOptions.configFile.text; - } return true; function sourceFileNotUptoDate(sourceFile) { return !sourceFileVersionUptoDate(sourceFile) || @@ -105966,21 +109172,25 @@ var ts; return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName); } function projectReferenceUptoDate(oldRef, newRef, index) { - if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { - return false; - } - return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); + return ts.projectReferenceIsEqualTo(oldRef, newRef) && + resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef); } function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { if (oldResolvedRef) { - if (ts.contains(seenResolvedRefs, oldResolvedRef)) { - // Assume true + // Assume true + if (ts.contains(seenResolvedRefs, oldResolvedRef)) return true; - } - // If sourceFile for the oldResolvedRef existed, check the version for uptodate - if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + var refPath_1 = resolveProjectReferencePath(oldRef); + var newParsedCommandLine = getParsedCommandLine(refPath_1); + // Check if config file exists + if (!newParsedCommandLine) + return false; + // If change in source file + if (oldResolvedRef.commandLine.options.configFile !== newParsedCommandLine.options.configFile) + return false; + // check file names + if (!ts.arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newParsedCommandLine.fileNames)) return false; - } // Add to seen before checking the referenced paths of this config file (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); // If child project references are upto date, this project reference is uptodate @@ -105990,7 +109200,8 @@ var ts; } // In old program, not able to resolve project reference path, // so if config file doesnt exist, it is uptodate. - return !fileExists(resolveProjectReferencePath(oldRef)); + var refPath = resolveProjectReferencePath(oldRef); + return !getParsedCommandLine(refPath); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -106054,7 +109265,7 @@ var ts; var modulesWithElidedImports = new ts.Map(); // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. var sourceFilesFoundSearchingNodeModules = new ts.Map(); - ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeProgram"); var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHostLike(host); @@ -106069,6 +109280,7 @@ var ts; var hasEmitBlockingDiagnostics = new ts.Map(); var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; + var typeReferenceDirectiveResolutionCache; var actualResolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { @@ -106083,7 +109295,7 @@ var ts; }); }; } else { - moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options); + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName, options); var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } @@ -106092,7 +109304,8 @@ var ts; actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); }; } else { - var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; // TODO: GH#18217 actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } // Map from a stringified PackageId to the source file with that id. @@ -106130,15 +109343,15 @@ var ts; getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect, forEachResolvedProjectReference: forEachResolvedProjectReference }), onProgramCreateComplete = _d.onProgramCreateComplete, fileExists = _d.fileExists, directoryExists = _d.directoryExists; - ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram }); var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`. var structureIsReused; - ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {}); structureIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); if (structureIsReused !== 2 /* Completely */) { processingDefaultLibFiles = []; processingOtherFiles = []; @@ -106176,13 +109389,13 @@ var ts; }); } } - ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length }); ts.forEach(rootNames, function (name, index) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.RootFile, index: index }); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { - ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length }); // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile); @@ -106190,7 +109403,7 @@ var ts; for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i], { kind: ts.FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: (_b = resolutions[i]) === null || _b === void 0 ? void 0 : _b.packageId }); } - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } // Do not process the default library if: // - The '--noLib' flag is used. @@ -106231,12 +109444,25 @@ var ts; host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); } } - oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference) { - if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { - host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + if (!host.getParsedCommandLine) { + oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference) { + if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { + host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false); + } + }); + } + } + // Release commandlines that new program does not use + if (oldProgram && host.onReleaseParsedCommandLine) { + forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, parent, index) { + var oldReference = (parent === null || parent === void 0 ? void 0 : parent.commandLine.projectReferences[index]) || oldProgram.getProjectReferences()[index]; + var oldRefPath = resolveProjectReferencePath(oldReference); + if (!(projectReferenceRedirects === null || projectReferenceRedirects === void 0 ? void 0 : projectReferenceRedirects.has(toPath(oldRefPath)))) { + host.onReleaseParsedCommandLine(oldRefPath, oldResolvedRef, oldProgram.getCompilerOptions()); } }); } + typeReferenceDirectiveResolutionCache = undefined; // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; var program = { @@ -106265,7 +109491,6 @@ var ts; getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, - getTypeCatalog: function () { return getDiagnosticsProducingTypeChecker().getTypeCatalog(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getInstantiationCount: function () { return getDiagnosticsProducingTypeChecker().getInstantiationCount(); }, getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); }, @@ -106313,19 +109538,19 @@ var ts; verifyCompilerOptions(); ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return program; function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) { if (!moduleNames.length) return ts.emptyArray; var containingFileName = ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); var redirectedReference = getRedirectReferenceForResolution(containingFile); - ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveModule"); var result = actualResolveModuleNamesWorker(moduleNames, containingFileName, reusedNames, redirectedReference); ts.performance.mark("afterResolveModule"); ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile) { @@ -106333,12 +109558,12 @@ var ts; return []; var containingFileName = !ts.isString(containingFile) ? ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile; var redirectedReference = !ts.isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined; - ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName }); ts.performance.mark("beforeResolveTypeReference"); var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference); ts.performance.mark("afterResolveTypeReference"); ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function getRedirectReferenceForResolution(file) { @@ -106431,13 +109656,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_14 = []; + var result_15 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_14.push(resolvedModule); + result_15.push(resolvedModule); } - return result_14; + return result_15; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -106548,7 +109773,9 @@ var ts; var newResolvedRef = parseProjectReferenceConfigFile(newRef); if (oldResolvedRef) { // Resolved project reference has gone missing or changed - return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + return !newResolvedRef || + newResolvedRef.sourceFile !== oldResolvedRef.sourceFile || + !ts.arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newResolvedRef.commandLine.fileNames); } else { // A previously-unresolved reference may be resolved now @@ -106810,7 +110037,7 @@ var ts; } function emitBuildInfo(writeFileCallback) { ts.Debug.assert(!ts.outFile(options)); - ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeEmit"); var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), /*targetSourceFile*/ undefined, @@ -106819,7 +110046,7 @@ var ts; /*onlyBuildInfo*/ true); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return emitResult; } function getResolvedProjectReferences() { @@ -106865,9 +110092,9 @@ var ts; return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) { - ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }, /*separateBeginAndEnd*/ true); var result = runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); }); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function isEmitBlocked(emitFileName) { @@ -107071,22 +110298,22 @@ var ts; // Return directly from the case if the given node doesnt want to visit each child // Otherwise break to visit each child switch (parent.kind) { - case 160 /* Parameter */: - case 163 /* PropertyDeclaration */: - case 165 /* MethodDeclaration */: + case 161 /* Parameter */: + case 164 /* PropertyDeclaration */: + case 166 /* MethodDeclaration */: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?")); return "skip"; } // falls through - case 164 /* MethodSignature */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: - case 249 /* VariableDeclaration */: + case 165 /* MethodSignature */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: + case 250 /* VariableDeclaration */: // type annotation if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files)); @@ -107094,58 +110321,58 @@ var ts; } } switch (node.kind) { - case 262 /* ImportClause */: + case 263 /* ImportClause */: if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type")); return "skip"; } break; - case 267 /* ExportDeclaration */: + case 268 /* ExportDeclaration */: if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type")); return "skip"; } break; - case 260 /* ImportEqualsDeclaration */: + case 261 /* ImportEqualsDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files)); return "skip"; - case 266 /* ExportAssignment */: + case 267 /* ExportAssignment */: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 286 /* HeritageClause */: + case 287 /* HeritageClause */: var heritageClause = node; if (heritageClause.token === 116 /* ImplementsKeyword */) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 253 /* InterfaceDeclaration */: + case 254 /* InterfaceDeclaration */: var interfaceKeyword = ts.tokenToString(117 /* InterfaceKeyword */); ts.Debug.assertIsDefined(interfaceKeyword); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword)); return "skip"; - case 256 /* ModuleDeclaration */: + case 257 /* ModuleDeclaration */: var moduleKeyword = node.flags & 16 /* Namespace */ ? ts.tokenToString(140 /* NamespaceKeyword */) : ts.tokenToString(139 /* ModuleKeyword */); ts.Debug.assertIsDefined(moduleKeyword); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword)); return "skip"; - case 254 /* TypeAliasDeclaration */: + case 255 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files)); return "skip"; - case 255 /* EnumDeclaration */: + case 256 /* EnumDeclaration */: var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(91 /* EnumKeyword */)); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword)); return "skip"; - case 225 /* NonNullExpression */: + case 226 /* NonNullExpression */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files)); return "skip"; - case 224 /* AsExpression */: + case 225 /* AsExpression */: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files)); return "skip"; - case 206 /* TypeAssertionExpression */: + case 207 /* TypeAssertionExpression */: ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } } @@ -107154,29 +110381,29 @@ var ts; diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning)); } switch (parent.kind) { - case 252 /* ClassDeclaration */: - case 221 /* ClassExpression */: - case 165 /* MethodDeclaration */: - case 166 /* Constructor */: - case 167 /* GetAccessor */: - case 168 /* SetAccessor */: - case 208 /* FunctionExpression */: - case 251 /* FunctionDeclaration */: - case 209 /* ArrowFunction */: + case 253 /* ClassDeclaration */: + case 222 /* ClassExpression */: + case 166 /* MethodDeclaration */: + case 167 /* Constructor */: + case 168 /* GetAccessor */: + case 169 /* SetAccessor */: + case 209 /* FunctionExpression */: + case 252 /* FunctionDeclaration */: + case 210 /* ArrowFunction */: // Check type parameters if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files)); return "skip"; } // falls through - case 232 /* VariableStatement */: + case 233 /* VariableStatement */: // Check modifiers if (nodes === parent.modifiers) { - checkModifiers(parent.modifiers, parent.kind === 232 /* VariableStatement */); + checkModifiers(parent.modifiers, parent.kind === 233 /* VariableStatement */); return "skip"; } break; - case 163 /* PropertyDeclaration */: + case 164 /* PropertyDeclaration */: // Check modifiers of property declaration if (nodes === parent.modifiers) { for (var _i = 0, _a = nodes; _i < _a.length; _i++) { @@ -107188,19 +110415,19 @@ var ts; return "skip"; } break; - case 160 /* Parameter */: + case 161 /* Parameter */: // Check modifiers of parameter declaration if (nodes === parent.modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); return "skip"; } break; - case 203 /* CallExpression */: - case 204 /* NewExpression */: - case 223 /* ExpressionWithTypeArguments */: - case 274 /* JsxSelfClosingElement */: - case 275 /* JsxOpeningElement */: - case 205 /* TaggedTemplateExpression */: + case 204 /* CallExpression */: + case 205 /* NewExpression */: + case 224 /* ExpressionWithTypeArguments */: + case 275 /* JsxSelfClosingElement */: + case 276 /* JsxOpeningElement */: + case 206 /* TaggedTemplateExpression */: // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files)); @@ -107225,6 +110452,7 @@ var ts; case 142 /* ReadonlyKeyword */: case 133 /* DeclareKeyword */: case 125 /* AbstractKeyword */: + case 156 /* OverrideKeyword */: diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind))); break; // These are all legal modifiers. @@ -107528,13 +110756,13 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { - ts.tracing.push("program" /* Program */, "findSourceFile", { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "findSourceFile", { fileName: fileName, isDefaultLib: isDefaultLib || undefined, fileIncludeKind: ts.FileIncludeKind[reason.kind], }); var result = findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; } function findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) { @@ -107793,9 +111021,9 @@ var ts; } } function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { - ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason); - ts.tracing.pop(); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason) { // If we already found this library as a primary reference - nothing to do @@ -107866,12 +111094,14 @@ var ts; return host.getCanonicalFileName(fileName); } function processImportedModules(file) { + var _a; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var resolutions = resolveModuleNamesReusingOldState(moduleNames, file); ts.Debug.assert(resolutions.length === moduleNames.length); + var optionsForFile = (useSourceOfProjectReferenceRedirect ? (_a = getRedirectReferenceForResolution(file)) === null || _a === void 0 ? void 0 : _a.commandLine.options : undefined) || options; for (var index = 0; index < moduleNames.length; index++) { var resolution = resolutions[index]; ts.setResolvedModule(file, moduleNames[index], resolution); @@ -107894,11 +111124,11 @@ var ts; // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') // This may still end up being an untyped module -- the file won't be included but imports will be allowed. var shouldAddFile = resolvedFileName - && !getResolutionDiagnostic(options, resolution) - && !options.noResolve + && !getResolutionDiagnostic(optionsForFile, resolution) + && !optionsForFile.noResolve && index < file.imports.length && !elideImport - && !(isJsFile && !ts.getAllowJSCompilerOption(options)) + && !(isJsFile && !ts.getAllowJSCompilerOption(optionsForFile)) && (ts.isInJSFile(file.imports[index]) || !(file.imports[index].flags & 4194304 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); @@ -108101,6 +111331,9 @@ var ts; if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } + if (options.preserveConstEnums === false) { + createDiagnosticForOptionName(ts.Diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled, "preserveConstEnums", "isolatedModules"); + } var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; }); if (firstNonExternalModuleSourceFile) { var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); @@ -108131,9 +111364,10 @@ var ts; 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 + // there has to be common source directory if user specified --outdir || --rootDir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted if (options.outDir || // there is --outDir specified + options.rootDir || // there is --rootDir specified options.sourceRoot || // there is --sourceRoot specified options.mapRoot) { // there is --mapRoot specified // Precalculate and cache the common source directory @@ -108630,7 +111864,7 @@ var ts; } function handleDirectoryCouldBeSymlink(directory) { var _a; - if (!host.getResolvedProjectReferences()) + if (!host.getResolvedProjectReferences() || ts.containsIgnoredPath(directory)) return; // Because we already watch node_modules, handle symlinks in there if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart)) @@ -108647,7 +111881,7 @@ var ts; symlinkCache.setSymlinkedDirectory(directoryPath, false); return; } - symlinkCache.setSymlinkedDirectory(directoryPath, { + symlinkCache.setSymlinkedDirectory(directory, { real: ts.ensureTrailingDirectorySeparator(real), realPath: realPath }); @@ -108923,12 +112157,15 @@ var ts; // From ambient modules for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { var ambientModule = _g[_f]; - if (ambientModule.declarations.length > 1) { + if (ambientModule.declarations && ambientModule.declarations.length > 1) { addReferenceFromAmbientModule(ambientModule); } } return referencedFiles; function addReferenceFromAmbientModule(symbol) { + if (!symbol.declarations) { + return; + } // Add any file other than our own as reference for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; @@ -108953,7 +112190,7 @@ var ts; /** * Creates the state of file references and signature for the new program from oldState if it is safe */ - function create(newProgram, getCanonicalFileName, oldState) { + function create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { var fileInfos = new ts.Map(); var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? new ts.Map() : undefined; var exportedModulesMap = referencedMap ? new ts.Map() : undefined; @@ -108979,13 +112216,14 @@ var ts; } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) }); + fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined }); } return { fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState }; } BuilderState.create = create; @@ -109007,6 +112245,7 @@ var ts; referencedMap: state.referencedMap && new ts.Map(state.referencedMap), exportedModulesMap: state.exportedModulesMap && new ts.Map(state.exportedModulesMap), hasCalledUpdateShapeSignature: new ts.Set(state.hasCalledUpdateShapeSignature), + useFileVersionAsSignature: state.useFileVersionAsSignature, }; } BuilderState.clone = clone; @@ -109062,23 +112301,12 @@ var ts; return ts.Debug.fail(); var prevSignature = info.signature; var latestSignature; - if (sourceFile.isDeclarationFile) { - latestSignature = sourceFile.version; - if (exportedModulesMapCache && latestSignature !== prevSignature) { - // All the references in this file are exported - var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined; - exportedModulesMapCache.set(sourceFile.resolvedPath, references || false); - } - } - else { + if (!sourceFile.isDeclarationFile && !state.useFileVersionAsSignature) { var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken, /*customTransformers*/ undefined, /*forceDtsEmit*/ true); - var firstDts_1 = emitOutput_1.outputFiles && - programOfThisState.getCompilerOptions().declarationMap ? - emitOutput_1.outputFiles.length > 1 ? emitOutput_1.outputFiles[1] : undefined : - emitOutput_1.outputFiles.length > 0 ? emitOutput_1.outputFiles[0] : undefined; + var firstDts_1 = ts.firstOrUndefined(emitOutput_1.outputFiles); if (firstDts_1) { ts.Debug.assert(ts.fileExtensionIs(firstDts_1.name, ".d.ts" /* Dts */), "File extension for signature expected to be dts", function () { return "Found: " + ts.getAnyExtensionFromPath(firstDts_1.name) + " for " + firstDts_1.name + ":: All output files: " + JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; })); }); latestSignature = (computeHash || ts.generateDjb2Hash)(firstDts_1.text); @@ -109086,12 +112314,18 @@ var ts; updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache); } } - else { - latestSignature = prevSignature; // TODO: GH#18217 + } + // Default is to use file version as signature + if (latestSignature === undefined) { + latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + // All the references in this file are exported + var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined; + exportedModulesMapCache.set(sourceFile.resolvedPath, references || false); } } cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature); - return !prevSignature || latestSignature !== prevSignature; + return latestSignature !== prevSignature; } BuilderState.updateShapeSignature = updateShapeSignature; /** @@ -109211,7 +112445,7 @@ var ts; */ function isFileAffectingGlobalScope(sourceFile) { return containsGlobalScopeAugmentation(sourceFile) || - !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + !ts.isExternalOrCommonJsModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); } /** * Gets all files of the program excluding the default library file @@ -109299,8 +112533,8 @@ var ts; /** * Create the state so that we can iterate on changedFiles/affected files */ - function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { - var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); state.compilerOptions = compilerOptions; @@ -109538,6 +112772,7 @@ var ts; * This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change */ function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash) { + var _a; removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath); // If affected files is everything except default library, then nothing more to do if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) { @@ -109551,8 +112786,15 @@ var ts; removeSemanticDiagnosticsOf(state, f.resolvedPath); }); } + // When a change affects the global scope, all files are considered to be affected without updating their signature + // That means when affected file is handled, its signature can be out of date + // To avoid this, ensure that we update the signature for any affected file in this scenario. + ts.BuilderState.updateShapeSignature(state, ts.Debug.checkDefined(state.program), affectedFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap); return; } + else { + ts.Debug.assert(state.hasCalledUpdateShapeSignature.has(affectedFile.resolvedPath) || ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.has(affectedFile.resolvedPath)), "Signature not updated for affected file: " + affectedFile.fileName); + } if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) { forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); }); } @@ -109764,83 +113006,116 @@ var ts; return undefined; var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory(); var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); - var fileInfos = {}; - state.fileInfos.forEach(function (value, key) { + var fileNames = []; + var fileNameToFileId = new ts.Map(); + var fileIdsList; + var fileNamesToFileIdListId; + var fileInfos = ts.arrayFrom(state.fileInfos.entries(), function (_a) { + var key = _a[0], value = _a[1]; + // Ensure fileId + var fileId = toFileId(key); + ts.Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope }; + var actualSignature = signature !== null && signature !== void 0 ? signature : value.signature; + return value.version === actualSignature ? + value.affectsGlobalScope ? + { version: value.version, signature: undefined, affectsGlobalScope: true } : + value.version : + actualSignature !== undefined ? + signature === undefined ? + value : + { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope } : + { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope }; }); - var result = { - fileInfos: fileInfos, - options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath) - }; + var referencedMap; if (state.referencedMap) { - var referencedMap = {}; - for (var _i = 0, _a = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { - var key = _a[_i]; - referencedMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.referencedMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); - } - result.referencedMap = referencedMap; + referencedMap = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive).map(function (key) { return [ + toFileId(key), + toFileIdListId(state.referencedMap.get(key)) + ]; }); } + var exportedModulesMap; if (state.exportedModulesMap) { - var exportedModulesMap = {}; - for (var _b = 0, _c = ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) { - var key = _c[_b]; + exportedModulesMap = ts.mapDefined(ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive), function (key) { var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key); // Not in temporary cache, use existing value if (newValue === undefined) - exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.exportedModulesMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); + return [toFileId(key), toFileIdListId(state.exportedModulesMap.get(key))]; // Value in cache and has updated value map, use that else if (newValue) - exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); - } - result.exportedModulesMap = exportedModulesMap; + return [toFileId(key), toFileIdListId(newValue)]; + }); } + var semanticDiagnosticsPerFile; if (state.semanticDiagnosticsPerFile) { - var semanticDiagnosticsPerFile = []; - for (var _d = 0, _e = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) { - var key = _e[_d]; + for (var _i = 0, _a = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var key = _a[_i]; var value = state.semanticDiagnosticsPerFile.get(key); - semanticDiagnosticsPerFile.push(value.length ? + (semanticDiagnosticsPerFile || (semanticDiagnosticsPerFile = [])).push(value.length ? [ - relativeToBuildInfo(key), + toFileId(key), state.hasReusableDiagnostic ? value : convertToReusableDiagnostics(value, relativeToBuildInfo) ] : - relativeToBuildInfo(key)); + toFileId(key)); } - result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile; } + var affectedFilesPendingEmit; if (state.affectedFilesPendingEmit) { - var affectedFilesPendingEmit = []; var seenFiles = new ts.Set(); - for (var _f = 0, _g = state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(ts.compareStringsCaseSensitive); _f < _g.length; _f++) { - var path = _g[_f]; + for (var _b = 0, _c = state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) { + var path = _c[_b]; if (ts.tryAddToSet(seenFiles, path)) { - affectedFilesPendingEmit.push([relativeToBuildInfo(path), state.affectedFilesPendingEmitKind.get(path)]); + (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push([toFileId(path), state.affectedFilesPendingEmitKind.get(path)]); } } - result.affectedFilesPendingEmit = affectedFilesPendingEmit; } - return result; + return { + fileNames: fileNames, + fileInfos: fileInfos, + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + fileIdsList: fileIdsList, + referencedMap: referencedMap, + exportedModulesMap: exportedModulesMap, + semanticDiagnosticsPerFile: semanticDiagnosticsPerFile, + affectedFilesPendingEmit: affectedFilesPendingEmit, + }; function relativeToBuildInfoEnsuringAbsolutePath(path) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory)); } function relativeToBuildInfo(path) { return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName)); } + function toFileId(path) { + var fileId = fileNameToFileId.get(path); + if (fileId === undefined) { + fileNames.push(relativeToBuildInfo(path)); + fileNameToFileId.set(path, fileId = fileNames.length); + } + return fileId; + } + function toFileIdListId(set) { + var fileIds = ts.arrayFrom(set.keys(), toFileId).sort(ts.compareValues); + var key = fileIds.join(); + var fileIdListId = fileNamesToFileIdListId === null || fileNamesToFileIdListId === void 0 ? void 0 : fileNamesToFileIdListId.get(key); + if (fileIdListId === undefined) { + (fileIdsList || (fileIdsList = [])).push(fileIds); + (fileNamesToFileIdListId || (fileNamesToFileIdListId = new ts.Map())).set(key, fileIdListId = fileIdsList.length); + } + return fileIdListId; + } } - function convertToReusableCompilerOptions(options, relativeToBuildInfo) { - var result = {}; + function convertToProgramBuildInfoCompilerOptions(options, relativeToBuildInfo) { + var result; var optionsNameMap = ts.getOptionsNameMap().optionsNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo); + for (var _i = 0, _a = ts.getOwnKeys(options).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var name = _a[_i]; + var optionInfo = optionsNameMap.get(name.toLowerCase()); + if ((optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsEmit) || (optionInfo === null || optionInfo === void 0 ? void 0 : optionInfo.affectsSemanticDiagnostics) || name === "skipLibCheck" || name === "skipDefaultLibCheck") { + (result || (result = {}))[name] = convertToReusableCompilerOptionValue(optionInfo, options[name], relativeToBuildInfo); } } - if (result.configFilePath) { - result.configFilePath = relativeToBuildInfo(result.configFilePath); - } return result; } function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) { @@ -109932,7 +113207,7 @@ var ts; * Computing hash to for signature verification */ var computeHash = ts.maybeBind(host, host.createHash); - var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState, host.disableUseFileVersionAsSignature); var backupState; newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); }; // To ensure that we arent storing any references to old program or new program without state @@ -110156,37 +113431,31 @@ var ts; state.affectedFilesPendingEmitIndex = 0; } } - function getMapOfReferencedSet(mapLike, toPath) { - if (!mapLike) - return undefined; - var map = new ts.Map(); - // Copies keys/values from template. Note that for..in will not throw if - // template is undefined, and instead will just exit the loop. - for (var key in mapLike) { - if (ts.hasProperty(mapLike, key)) { - map.set(toPath(key), new ts.Set(mapLike[key].map(toPath))); - } - } - return map; + function toBuilderStateFileInfo(fileInfo) { + return ts.isString(fileInfo) ? + { version: fileInfo, signature: fileInfo, affectsGlobalScope: undefined } : + ts.isString(fileInfo.signature) ? + fileInfo : + { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope }; } + ts.toBuilderStateFileInfo = toBuilderStateFileInfo; function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) { + var _a; var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var filePaths = program.fileNames.map(toPath); + var filePathsSetList = (_a = program.fileIdsList) === null || _a === void 0 ? void 0 : _a.map(function (fileIds) { return new ts.Set(fileIds.map(toFilePath)); }); var fileInfos = new ts.Map(); - for (var key in program.fileInfos) { - if (ts.hasProperty(program.fileInfos, key)) { - fileInfos.set(toPath(key), program.fileInfos[key]); - } - } + program.fileInfos.forEach(function (fileInfo, index) { return fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo)); }); var state = { fileInfos: fileInfos, - compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), - referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), - exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), - semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), + compilerOptions: program.options ? ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + referencedMap: toMapOfReferencedSet(program.referencedMap), + exportedModulesMap: toMapOfReferencedSet(program.exportedModulesMap), + semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toFilePath(ts.isNumber(value) ? value : value[0]); }, function (value) { return ts.isNumber(value) ? ts.emptyArray : value[1]; }), hasReusableDiagnostic: true, - affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }), - affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }, function (value) { return value[1]; }), + affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }), + affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toFilePath(value[0]); }, function (value) { return value[1]; }), affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, }; return { @@ -110219,6 +113488,15 @@ var ts; function toAbsolutePath(path) { return ts.getNormalizedAbsolutePath(path, buildInfoDirectory); } + function toFilePath(fileId) { + return filePaths[fileId - 1]; + } + function toFilePathsSet(fileIdsListId) { + return filePathsSetList[fileIdsListId - 1]; + } + function toMapOfReferencedSet(referenceMap) { + return referenceMap && ts.arrayToMap(referenceMap, function (value) { return toFilePath(value[0]); }, function (value) { return toFilePathsSet(value[1]); }); + } } ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { @@ -110331,9 +113609,9 @@ var ts; var resolutionsWithFailedLookups = []; var resolvedFileToResolution = ts.createMultiMap(); var hasChangedAutomaticTypeDirectiveNames = false; - var failedLookupChecks = []; - var startsWithPathChecks = []; - var isInDirectoryChecks = []; + var failedLookupChecks; + var startsWithPathChecks; + var isInDirectoryChecks; var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. @@ -110342,9 +113620,12 @@ var ts; var resolvedModuleNames = new ts.Map(); var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects(); var nonRelativeModuleNameCache = ts.createCacheWithRedirects(); - var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName); + var moduleResolutionCache = ts.createModuleResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, perDirectoryResolvedModuleNames, nonRelativeModuleNameCache); var resolvedTypeReferenceDirectives = new ts.Map(); var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects(); + var typeReferenceDirectiveResolutionCache = ts.createTypeReferenceDirectiveResolutionCache(getCurrentDirectory(), resolutionHost.getCanonicalFileName, + /*options*/ undefined, moduleResolutionCache.getPackageJsonInfoCache(), perDirectoryResolvedTypeReferenceDirectives); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -110376,6 +113657,7 @@ var ts; invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, createHasInvalidatedResolution: createHasInvalidatedResolution, + isFileWithInvalidatedNonRelativeUnresolvedImports: isFileWithInvalidatedNonRelativeUnresolvedImports, updateTypeRootsWatch: updateTypeRootsWatch, closeTypeRootsWatch: closeTypeRootsWatch, clear: clear @@ -110401,9 +113683,9 @@ var ts; resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) clearPerDirectoryResolutions(); @@ -110439,9 +113721,8 @@ var ts; isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { - perDirectoryResolvedModuleNames.clear(); - nonRelativeModuleNameCache.clear(); - perDirectoryResolvedTypeReferenceDirectives.clear(); + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } @@ -110468,7 +113749,7 @@ var ts; if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results - var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; + var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache, moduleResolutionCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; if (resolvedModule) { // Modify existing resolution so its saved in the directory cache as well primaryResult.resolvedModule = resolvedModule; @@ -110479,6 +113760,9 @@ var ts; // Default return the result from the first pass return primaryResult; } + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) { + return ts.resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache); + } function resolveNamesWithLocalCache(_a) { var _b; var names = _a.names, containingFile = _a.containingFile, redirectedReference = _a.redirectedReference, cache = _a.cache, perDirectoryCacheWithRedirects = _a.perDirectoryCacheWithRedirects, loader = _a.loader, getResolutionWithResolvedFileName = _a.getResolutionWithResolvedFileName, shouldRetryResolution = _a.shouldRetryResolution, reusedNames = _a.reusedNames, logChanges = _a.logChanges; @@ -110566,7 +113850,7 @@ var ts; redirectedReference: redirectedReference, cache: resolvedTypeReferenceDirectives, perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives, - loader: ts.resolveTypeReferenceDirective, + loader: resolveTypeReferenceDirective, getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective, shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, }); @@ -110841,7 +114125,7 @@ var ts; if (isCreatingWatchedDirectory) { // Watching directory is created // Invalidate any resolution has failed lookup in this directory - isInDirectoryChecks.push(fileOrDirectoryPath); + (isInDirectoryChecks || (isInDirectoryChecks = [])).push(fileOrDirectoryPath); } else { // If something to do with folder/file starting with "." in node_modules folder, skip it @@ -110859,8 +114143,8 @@ var ts; if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory - failedLookupChecks.push(fileOrDirectoryPath); - startsWithPathChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(fileOrDirectoryPath); } else { if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { @@ -110871,27 +114155,33 @@ var ts; return false; } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created - failedLookupChecks.push(fileOrDirectoryPath); + (failedLookupChecks || (failedLookupChecks = [])).push(fileOrDirectoryPath); + // If the invalidated file is from a node_modules package, invalidate everything else + // in the package since we might not get notifications for other files in the package. + // This hardens our logic against unreliable file watchers. + var packagePath = ts.parseNodeModuleFromPath(fileOrDirectoryPath); + if (packagePath) + (startsWithPathChecks || (startsWithPathChecks = new ts.Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks.length && !startsWithPathChecks.length && !isInDirectoryChecks.length) { + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { return false; } var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; return invalidated; } function canInvalidateFailedLookupResolution(resolution) { return resolution.failedLookupLocations.some(function (location) { var locationPath = resolutionHost.toPath(location); return ts.contains(failedLookupChecks, locationPath) || - startsWithPathChecks.some(function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath); }) || - isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); }); + ts.firstDefinedIterator((startsWithPathChecks === null || startsWithPathChecks === void 0 ? void 0 : startsWithPathChecks.keys()) || ts.emptyIterator, function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath) ? true : undefined; }) || + (isInDirectoryChecks === null || isInDirectoryChecks === void 0 ? void 0 : isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); })); }); } function closeTypeRootsWatch() { @@ -111042,6 +114332,9 @@ var ts; return [ambient]; var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); + if (!moduleSourceFile) { + return []; + } var modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host); var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); var existingSpecifier = ts.forEach(modulePaths, function (modulePath) { return ts.forEach(host.getFileIncludeReasons().get(ts.toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)), function (reason) { @@ -111112,7 +114405,7 @@ var ts; if (!baseUrl && !paths || relativePreference === 0 /* Relative */) { return relativePath; } - var baseDirectory = ts.getPathsBasePath(compilerOptions, host) || baseUrl; + var baseDirectory = ts.getNormalizedAbsolutePath(ts.getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory()); var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName); if (!relativeToBaseUrl) { return relativePath; @@ -111127,7 +114420,9 @@ var ts; return nonRelative; } if (relativePreference === 3 /* ExternalNonRelative */) { - var projectDirectory = host.getCurrentDirectory(); + var projectDirectory = compilerOptions.configFilePath ? + ts.toPath(ts.getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) : + info.getCanonicalFileName(host.getCurrentDirectory()); var modulePath = ts.toPath(moduleFileName, projectDirectory, getCanonicalFileName); var sourceIsInternal = ts.startsWith(sourceDirectory, projectDirectory); var targetIsInternal = ts.startsWith(modulePath, projectDirectory); @@ -111179,12 +114474,8 @@ var ts; return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined; }) || false; } - function numberOfDirectorySeparators(str) { - var match = str.match(/\//g); - return match ? match.length : 0; - } function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) { - return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareValues(numberOfDirectorySeparators(a.path), numberOfDirectorySeparators(b.path)); + return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareNumberOfDirectorySeparators(a.path, b.path); } function getNearestAncestorDirectoryWithPackageJson(host, fileName) { if (host.getNearestAncestorDirectoryWithPackageJson) { @@ -111198,40 +114489,49 @@ var ts; var getCanonicalFileName = ts.hostGetCanonicalFileName(host); var cwd = host.getCurrentDirectory(); var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined; - var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray; + var importedPath = ts.toPath(importedFileName, cwd, getCanonicalFileName); + var redirects = host.redirectTargetsMap.get(importedPath) || ts.emptyArray; var importedFileNames = __spreadArray(__spreadArray(__spreadArray([], (referenceRedirect ? [referenceRedirect] : ts.emptyArray)), [importedFileName]), redirects); var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + var shouldFilterIgnoredPaths = !ts.every(targets, ts.containsIgnoredPath); if (!preferSymlinks) { - var result_15 = ts.forEach(targets, function (p) { return cb(p, referenceRedirect === p); }); - if (result_15) - return result_15; + // Symlinks inside ignored paths are already filtered out of the symlink cache, + // so we only need to remove them from the realpath filenames. + var result_16 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); }); + if (result_16) + return result_16; } var links = host.getSymlinkCache ? host.getSymlinkCache() : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd); - var symlinkedDirectories = links.getSymlinkedDirectories(); - var useCaseSensitiveFileNames = !host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames(); - var result = symlinkedDirectories && ts.forEachEntry(symlinkedDirectories, function (resolved, path) { - if (resolved === false) - return undefined; - if (ts.startsWithDirectory(importingFileName, resolved.realPath, getCanonicalFileName)) { - return undefined; // Don't want to a package to globally import from itself + var symlinkedDirectories = links.getSymlinkedDirectoriesByRealpath(); + var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd); + var result = symlinkedDirectories && ts.forEachAncestorDirectory(ts.getDirectoryPath(fullImportedFileName), function (realPathDirectory) { + var symlinkDirectories = symlinkedDirectories.get(ts.ensureTrailingDirectorySeparator(ts.toPath(realPathDirectory, cwd, getCanonicalFileName))); + if (!symlinkDirectories) + return undefined; // Continue to ancestor directory + // Don't want to a package to globally import from itself (importNameCodeFix_symlink_own_package.ts) + if (ts.startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) { + return false; // Stop search, each ancestor directory will also hit this condition } return ts.forEach(targets, function (target) { - if (!ts.containsPath(resolved.real, target, !useCaseSensitiveFileNames)) { + if (!ts.startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) { return; } - var relative = ts.getRelativePathFromDirectory(resolved.real, target, getCanonicalFileName); - var option = ts.resolvePath(path, relative); - if (!host.fileExists || host.fileExists(option)) { - var result_16 = cb(option, target === referenceRedirect); - if (result_16) - return result_16; + var relative = ts.getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName); + for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) { + var symlinkDirectory = symlinkDirectories_1[_i]; + var option = ts.resolvePath(symlinkDirectory, relative); + var result_17 = cb(option, target === referenceRedirect); + shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths + if (result_17) + return result_17; } }); }); - return result || - (preferSymlinks ? ts.forEach(targets, function (p) { return cb(p, p === referenceRedirect); }) : undefined); + return result || (preferSymlinks + ? ts.forEach(targets, function (p) { return shouldFilterIgnoredPaths && ts.containsIgnoredPath(p) ? undefined : cb(p, p === referenceRedirect); }) + : undefined); } moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule; /** @@ -111239,8 +114539,14 @@ var ts; * Symlinks will be returned first so they are preferred over the real path. */ function getAllModulePaths(importingFileName, importedFileName, host) { - var cwd = host.getCurrentDirectory(); + var _a; + var cache = (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host); var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + if (cache) { + var cached = cache.get(importingFileName, ts.toPath(importedFileName, host.getCurrentDirectory(), getCanonicalFileName)); + if (typeof cached === "object") + return cached; + } var allFileNames = new ts.Map(); var importedFileFromNodeModules = false; forEachFileNameOfModule(importingFileName, importedFileName, host, @@ -111252,7 +114558,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_24 = function (directory) { + var _loop_26 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -111275,10 +114581,10 @@ var ts; out_directory_1 = directory; }; var out_directory_1; - for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_7 = _loop_24(directory); + for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { + var state_9 = _loop_26(directory); directory = out_directory_1; - if (state_7 === "break") + if (state_9 === "break") break; } if (allFileNames.size) { @@ -111287,10 +114593,14 @@ var ts; remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators); sortedPaths.push.apply(sortedPaths, remainingPaths); } + if (cache) { + cache.set(importingFileName, ts.toPath(importedFileName, host.getCurrentDirectory(), getCanonicalFileName), sortedPaths); + } return sortedPaths; } function tryGetModuleNameFromAmbientModule(moduleSymbol, checker) { - var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); + var _a; + var decl = (_a = moduleSymbol.declarations) === null || _a === void 0 ? void 0 : _a.find(function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { return decl.name.text; } @@ -111346,7 +114656,7 @@ var ts; ts.startsWith(relativeToBaseUrl, prefix) && ts.endsWith(relativeToBaseUrl, suffix) || !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); return key.replace("*", matchedStar); } } @@ -111650,10 +114960,10 @@ var ts; } ts.createWatchStatusReporter = createWatchStatusReporter; /** Parses config file using System interface */ - function parseConfigFileWithSystem(configFileName, optionsToExtend, watchOptionsToExtend, system, reportDiagnostic) { + function parseConfigFileWithSystem(configFileName, optionsToExtend, extendedConfigCache, watchOptionsToExtend, system, reportDiagnostic) { var host = system; host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; - var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, /*extendedConfigCache*/ undefined, watchOptionsToExtend); + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend); host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; } @@ -111921,7 +115231,10 @@ var ts; MissingFile: "Missing file", WildcardDirectory: "Wild card directory", FailedLookupLocations: "Failed Lookup Locations", - TypeRoots: "Type roots" + TypeRoots: "Type roots", + ConfigFileOfReferencedProject: "Config file of referened project", + ExtendedConfigOfReferencedProject: "Extended config file of referenced project", + WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project", }; function createWatchFactory(host, options) { var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; @@ -111968,6 +115281,7 @@ var ts; getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }), createHash: ts.maybeBind(host, host.createHash), readDirectory: ts.maybeBind(host, host.readDirectory), + disableUseFileVersionAsSignature: host.disableUseFileVersionAsSignature, }; function writeFile(fileName, text, writeByteOrderMark, onError) { try { @@ -112025,7 +115339,8 @@ var ts; createDirectory: function (path) { return system.createDirectory(path); }, writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, createHash: ts.maybeBind(system, system.createHash), - createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram + createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, + disableUseFileVersionAsSignature: system.disableUseFileVersionAsSignature, }; } ts.createProgramHost = createProgramHost; @@ -112113,6 +115428,7 @@ var ts; if (system === void 0) { system = ts.sys; } var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system); host.createHash = ts.maybeBind(system, system.createHash); + host.disableUseFileVersionAsSignature = system.disableUseFileVersionAsSignature; ts.setGetSourceFileAsHashVersioned(host, system); ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); }); return host; @@ -112156,11 +115472,13 @@ var ts; function createWatchProgram(host) { var builderProgram; var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc - var extendedConfigFilesMap; // Map of file watchers for the extended config files var missingFilesMap; // Map of file watchers for the missing files var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file var timerToUpdateProgram; // timer callback to recompile the program var timerToInvalidateFailedLookupResolutions; // timer callback to invalidate resolutions for changes in failed lookup locations + var parsedConfigs; // Parsed commandline and watching cached for referenced projects + var sharedExtendedConfigFileWatchers; // Map of file watchers for extended files, shared between different referenced projects + var extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info var missingFilePathsRequestedForRelease; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations @@ -112210,6 +115528,7 @@ var ts; compilerHost.getNewLine = function () { return newLine; }; compilerHost.fileExists = fileExists; compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile; + compilerHost.onReleaseParsedCommandLine = onReleaseParsedCommandLine; // Members for ResolutionCacheHost compilerHost.toPath = toPath; compilerHost.getCompilationSettings = function () { return compilerOptions; }; @@ -112223,6 +115542,7 @@ var ts; compilerHost.fileIsOpen = ts.returnFalse; compilerHost.getCurrentProgram = getCurrentProgram; compilerHost.writeLog = writeLog; + compilerHost.getParsedCommandLine = getParsedCommandLine; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : @@ -112253,7 +115573,8 @@ var ts; // Update the wild card directory watch watchConfigFileWildCardDirectories(); // Update extended config file watch - watchExtendedConfigFiles(); + if (configFileName) + updateExtendedConfigFilesWatches(toPath(configFileName), compilerOptions, watchOptions, ts.WatchType.ExtendedConfigFile); return configFileName ? { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } : { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close }; @@ -112270,9 +115591,11 @@ var ts; configFileWatcher.close(); configFileWatcher = undefined; } - if (extendedConfigFilesMap) { - ts.clearMap(extendedConfigFilesMap, ts.closeFileWatcher); - extendedConfigFilesMap = undefined; + extendedConfigCache === null || extendedConfigCache === void 0 ? void 0 : extendedConfigCache.clear(); + extendedConfigCache = undefined; + if (sharedExtendedConfigFileWatchers) { + ts.clearMap(sharedExtendedConfigFileWatchers, ts.closeFileWatcherOf); + sharedExtendedConfigFileWatchers = undefined; } if (watchedWildcardDirectories) { ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); @@ -112282,6 +115605,17 @@ var ts; ts.clearMap(missingFilesMap, ts.closeFileWatcher); missingFilesMap = undefined; } + if (parsedConfigs) { + ts.clearMap(parsedConfigs, function (config) { + var _a; + (_a = config.watcher) === null || _a === void 0 ? void 0 : _a.close(); + config.watcher = undefined; + if (config.watchedDirectories) + ts.clearMap(config.watchedDirectories, ts.closeFileWatcherOf); + config.watchedDirectories = undefined; + }); + parsedConfigs = undefined; + } } function getCurrentBuilderProgram() { return builderProgram; @@ -112301,7 +115635,7 @@ 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, projectReferences)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; @@ -112320,6 +115654,8 @@ var ts; writeLog("CreatingProgramWith::"); writeLog(" roots: " + JSON.stringify(rootFileNames)); writeLog(" options: " + JSON.stringify(compilerOptions)); + if (projectReferences) + writeLog(" projectReferences: " + JSON.stringify(projectReferences)); var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; @@ -112542,10 +115878,10 @@ var ts; // Update the wild card directory watch watchConfigFileWildCardDirectories(); // Update extended config file watch - watchExtendedConfigFiles(); + updateExtendedConfigFilesWatches(toPath(configFileName), compilerOptions, watchOptions, ts.WatchType.ExtendedConfigFile); } function parseConfigFile() { - setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217 + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, extendedConfigCache || (extendedConfigCache = new ts.Map()), watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217 } function setConfigFileParsingResult(configFileParseResult) { rootFileNames = configFileParseResult.fileNames; @@ -112557,6 +115893,56 @@ var ts; canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInputFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } + function getParsedCommandLine(configFileName) { + var configPath = toPath(configFileName); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath); + if (config) { + if (!config.reloadLevel) + return config.parsedCommandLine; + // With host implementing getParsedCommandLine we cant just update file names + if (config.parsedCommandLine && config.reloadLevel === ts.ConfigFileProgramReloadLevel.Partial && !host.getParsedCommandLine) { + writeLog("Reloading new file names and options"); + var fileNames = ts.getFileNamesFromConfigSpecs(config.parsedCommandLine.options.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost); + config.parsedCommandLine = __assign(__assign({}, config.parsedCommandLine), { fileNames: fileNames }); + config.reloadLevel = undefined; + return config.parsedCommandLine; + } + } + writeLog("Loading config file: " + configFileName); + var parsedCommandLine = host.getParsedCommandLine ? + host.getParsedCommandLine(configFileName) : + getParsedCommandLineFromConfigFileHost(configFileName); + if (config) { + config.parsedCommandLine = parsedCommandLine; + config.reloadLevel = undefined; + } + else { + (parsedConfigs || (parsedConfigs = new ts.Map())).set(configPath, config = { parsedCommandLine: parsedCommandLine }); + } + watchReferencedProject(configFileName, configPath, config); + return parsedCommandLine; + } + function getParsedCommandLineFromConfigFileHost(configFileName) { + // Ignore the file absent errors + var onUnRecoverableConfigFileDiagnostic = parseConfigFileHost.onUnRecoverableConfigFileDiagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + var parsedCommandLine = ts.getParsedCommandLineOfConfigFile(configFileName, + /*optionsToExtend*/ undefined, parseConfigFileHost, extendedConfigCache || (extendedConfigCache = new ts.Map()), watchOptionsToExtend); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = onUnRecoverableConfigFileDiagnostic; + return parsedCommandLine; + } + function onReleaseParsedCommandLine(fileName) { + var _a; + var path = toPath(fileName); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(path); + if (!config) + return; + parsedConfigs.delete(path); + if (config.watchedDirectories) + ts.clearMap(config.watchedDirectories, ts.closeFileWatcherOf); + (_a = config.watcher) === null || _a === void 0 ? void 0 : _a.close(); + ts.clearSharedExtendedConfigFileWatcher(path, sharedExtendedConfigFileWatchers); + } function watchFilePath(path, file, callback, pollingInterval, options, watchType) { return watchFile(file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options, watchType); } @@ -112566,7 +115952,6 @@ var ts; if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) { resolutionCache.invalidateResolutionOfFile(path); } - resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); nextSourceFileVersion(path); // Update the program scheduleProgramUpdate(); @@ -112577,7 +115962,10 @@ var ts; } } function watchMissingFilePath(missingFilePath) { - return watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); + // If watching missing referenced config file, we are already watching it so no need for separate watcher + return (parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.has(missingFilePath)) ? + ts.noopFileWatcher : + watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile); } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); @@ -112614,10 +116002,11 @@ var ts; configFileName: configFileName, extraFileExtensions: extraFileExtensions, options: compilerOptions, - program: getCurrentBuilderProgram(), + program: getCurrentBuilderProgram() || rootFileNames, currentDirectory: currentDirectory, useCaseSensitiveFileNames: useCaseSensitiveFileNames, - writeLog: writeLog + writeLog: writeLog, + toPath: toPath, })) return; // Reload is pending, do the reload @@ -112628,18 +116017,87 @@ var ts; } }, flags, watchOptions, ts.WatchType.WildcardDirectory); } - function watchExtendedConfigFiles() { - var _a; - // Update the extended config files watcher - ts.mutateMap(extendedConfigFilesMap || (extendedConfigFilesMap = new ts.Map()), ts.arrayToMap(((_a = compilerOptions.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath), { - // Watch the extended config files - createNewValue: watchExtendedConfigFile, - // Config files that are no longer extended should no longer be watched. - onDeleteValue: ts.closeFileWatcher - }); - } - function watchExtendedConfigFile(extendedConfigFile) { - return watchFile(extendedConfigFile, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ExtendedConfigFile); + function updateExtendedConfigFilesWatches(forProjectPath, options, watchOptions, watchType) { + ts.updateSharedExtendedConfigFileWatcher(forProjectPath, options, sharedExtendedConfigFileWatchers || (sharedExtendedConfigFileWatchers = new ts.Map()), function (extendedConfigFileName, extendedConfigFilePath) { return watchFile(extendedConfigFileName, function (_fileName, eventKind) { + var _a; + updateCachedSystemWithFile(extendedConfigFileName, extendedConfigFilePath, eventKind); + // Update extended config cache + if (extendedConfigCache) + ts.cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath); + // Update projects + var projects = (_a = sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects; + // If there are no referenced projects this extended config file watcher depend on ignore + if (!(projects === null || projects === void 0 ? void 0 : projects.size)) + return; + projects.forEach(function (projectPath) { + if (toPath(configFileName) === projectPath) { + // If this is the config file of the project, reload completely + reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + } + else { + // Reload config for the referenced projects and remove the resolutions from referenced projects since the config file changed + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(projectPath); + if (config) + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(projectPath); + } + scheduleProgramUpdate(); + }); + }, ts.PollingInterval.High, watchOptions, watchType); }, toPath); + } + function watchReferencedProject(configFileName, configPath, commandLine) { + var _a, _b, _c, _d, _e; + // Watch file + commandLine.watcher || (commandLine.watcher = watchFile(configFileName, function (_fileName, eventKind) { + updateCachedSystemWithFile(configFileName, configPath, eventKind); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath); + if (config) + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(configPath); + scheduleProgramUpdate(); + }, ts.PollingInterval.High, ((_a = commandLine.parsedCommandLine) === null || _a === void 0 ? void 0 : _a.watchOptions) || watchOptions, ts.WatchType.ConfigFileOfReferencedProject)); + // Watch Wild card + if ((_b = commandLine.parsedCommandLine) === null || _b === void 0 ? void 0 : _b.wildcardDirectories) { + ts.updateWatchingWildcardDirectories(commandLine.watchedDirectories || (commandLine.watchedDirectories = new ts.Map()), new ts.Map(ts.getEntries((_c = commandLine.parsedCommandLine) === null || _c === void 0 ? void 0 : _c.wildcardDirectories)), function (directory, flags) { + var _a; + return watchDirectory(directory, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + // Since the file existence changed, update the sourceFiles cache + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + nextSourceFileVersion(fileOrDirectoryPath); + var config = parsedConfigs === null || parsedConfigs === void 0 ? void 0 : parsedConfigs.get(configPath); + if (!(config === null || config === void 0 ? void 0 : config.parsedCommandLine)) + return; + if (ts.isIgnoredFileFromWildCardWatching({ + watchedDirPath: toPath(directory), + fileOrDirectory: fileOrDirectory, + fileOrDirectoryPath: fileOrDirectoryPath, + configFileName: configFileName, + options: config.parsedCommandLine.options, + program: config.parsedCommandLine.fileNames, + currentDirectory: currentDirectory, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + writeLog: writeLog, + toPath: toPath, + })) + return; + // Reload is pending, do the reload + if (config.reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) { + config.reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + // Schedule Update the program + scheduleProgramUpdate(); + } + }, flags, ((_a = commandLine.parsedCommandLine) === null || _a === void 0 ? void 0 : _a.watchOptions) || watchOptions, ts.WatchType.WildcardDirectoryOfReferencedProject); + }); + } + else if (commandLine.watchedDirectories) { + ts.clearMap(commandLine.watchedDirectories, ts.closeFileWatcherOf); + commandLine.watchedDirectories = undefined; + } + // Watch extended config files + updateExtendedConfigFilesWatches(configPath, (_d = commandLine.parsedCommandLine) === null || _d === void 0 ? void 0 : _d.options, ((_e = commandLine.parsedCommandLine) === null || _e === void 0 ? void 0 : _e.watchOptions) || watchOptions, ts.WatchType.ExtendedConfigOfReferencedProject); } } ts.createWatchProgram = createWatchProgram; @@ -112799,12 +116257,19 @@ var ts; compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives); var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined; + var typeReferenceDirectiveResolutionCache = !compilerHost.resolveTypeReferenceDirectives ? ts.createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()) : undefined; if (!compilerHost.resolveModuleNames) { var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; }; compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3); }; } + if (!compilerHost.resolveTypeReferenceDirectives) { + var loader_4 = function (moduleName, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(moduleName, containingFile, state.projectCompilerOptions, compilerHost, redirectedReference, state.typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective; }; + compilerHost.resolveTypeReferenceDirectives = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { + return ts.loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_4); + }; + } var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var state = { host: host, @@ -112829,6 +116294,7 @@ var ts; projectErrorsReported: new ts.Map(), compilerHost: compilerHost, moduleResolutionCache: moduleResolutionCache, + typeReferenceDirectiveResolutionCache: typeReferenceDirectiveResolutionCache, // Mutable state buildOrder: undefined, readFileWithCache: function (f) { return host.readFile(f); }, @@ -112867,6 +116333,10 @@ var ts; function isParsedCommandLine(entry) { return !!entry.options; } + function getCachedParsedConfigFile(state, configFilePath) { + var value = state.configFileCache.get(configFilePath); + return value && isParsedCommandLine(value) ? value : undefined; + } function parseConfigFile(state, configFileName, configFilePath) { var configFileCache = state.configFileCache; var value = configFileCache.get(configFilePath); @@ -113012,7 +116482,7 @@ var ts; function disableCache(state) { if (!state.cache) return; - var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache; + var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache, typeReferenceDirectiveResolutionCache = state.typeReferenceDirectiveResolutionCache; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; host.directoryExists = cache.originalDirectoryExists; @@ -113021,10 +116491,8 @@ var ts; compilerHost.getSourceFile = cache.originalGetSourceFile; state.readFileWithCache = cache.originalReadFileWithCache; extendedConfigCache.clear(); - if (moduleResolutionCache) { - moduleResolutionCache.directoryToModuleNameMap.clear(); - moduleResolutionCache.moduleNameToDirectoryMap.clear(); - } + moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache === null || typeReferenceDirectiveResolutionCache === void 0 ? void 0 : typeReferenceDirectiveResolutionCache.clear(); state.cache = undefined; } function clearProjectStatus(state, resolved) { @@ -113191,6 +116659,7 @@ var ts; return withProgramOrUndefined(action) || ts.emptyArray; } function createProgram() { + var _a, _b; ts.Debug.assert(program === undefined); if (state.options.dry) { reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project); @@ -113210,7 +116679,8 @@ var ts; var host = state.host, compilerHost = state.compilerHost; state.projectCompilerOptions = config.options; // Update module resolution cache if needed - updateModuleResolutionCache(state, project, config); + (_a = state.moduleResolutionCache) === null || _a === void 0 ? void 0 : _a.update(config.options); + (_b = state.typeReferenceDirectiveResolutionCache) === null || _b === void 0 ? void 0 : _b.update(config.options); // Create program program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences); if (state.watch) { @@ -113385,7 +116855,7 @@ var ts; emitBundle(writeFile, customTransformers); break; case BuildStep.BuildInvalidatedProjectOfBundle: - ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken); + ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken, writeFile, customTransformers); step = BuildStep.Done; break; case BuildStep.QueueReferencingProjects: @@ -113527,34 +116997,9 @@ var ts; afterProgramDone(state, program, config); return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects }; } - function updateModuleResolutionCache(state, proj, config) { - if (!state.moduleResolutionCache) - return; - // Update module resolution cache if needed - var moduleResolutionCache = state.moduleResolutionCache; - var projPath = toPath(state, proj); - if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) { - // The own map will be for projectCompilerOptions - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0); - moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap); - moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap); - } - else { - // Set correct own map - ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0); - var ref = { - sourceFile: config.options.configFile, - commandLine: config - }; - moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); - } - moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options); - } function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) { // Check tsconfig time - var tsconfigTime = state.host.getModifiedTime(configFile) || ts.missingFileModifiedTime; + var tsconfigTime = ts.getModifiedTime(state.host, configFile); if (oldestOutputFileTime < tsconfigTime) { return { type: ts.UpToDateStatusType.OutOfDateWithSelf, @@ -113564,6 +117009,7 @@ var ts; } } function getUpToDateStatusWorker(state, project, resolvedPath) { + var force = !!state.options.force; var newestInputFileName = undefined; var newestInputFileTime = minimumDate; var host = state.host; @@ -113576,10 +117022,13 @@ var ts; reason: inputFile + " does not exist" }; } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; + if (!force) { + var inputTime = ts.getModifiedTime(host, inputFile); + host.getModifiedTime(inputFile); + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } } // Container if no files are specified in the project @@ -113598,36 +117047,38 @@ var ts; var missingOutputFileName; var newestDeclarationFileContentChangedTime = minimumDate; var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { - var output = outputs_1[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = 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 outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + if (!force) { + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = ts.getModifiedTime(host, output); + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var outputModifiedTime = ts.getModifiedTime(host, output); + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } } } var pseudoUpToDate = false; @@ -113663,7 +117114,8 @@ var ts; }; } // Check oldest output file name only if there is no missing output file name - if (!missingOutputFileName) { + // (a check we will have skipped if this is a forced build) + if (!force && !missingOutputFileName) { // If the upstream project's newest file is older than our oldest output, we // can't be out of date because of it if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { @@ -113709,7 +117161,7 @@ var ts; if (extendedConfigStatus) return extendedConfigStatus; } - if (!state.buildInfoChecked.has(resolvedPath)) { + if (!force && !state.buildInfoChecked.has(resolvedPath)) { state.buildInfoChecked.set(resolvedPath, true); var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options); if (buildInfoPath) { @@ -113769,7 +117221,7 @@ var ts; reportStatus(state, verboseMessage, proj.options.configFilePath); } if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, ts.getModifiedTime(host, file)); } host.setModifiedTime(file, now); } @@ -113851,7 +117303,7 @@ var ts; } } } - function build(state, project, cancellationToken, onlyReferences) { + function build(state, project, cancellationToken, writeFile, getCustomTransformers, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); if (!buildOrder) return ts.ExitStatus.InvalidProject_OutputsSkipped; @@ -113863,7 +117315,7 @@ var ts; if (!invalidatedProject) break; reportQueue = false; - invalidatedProject.done(cancellationToken); + invalidatedProject.done(cancellationToken, writeFile, getCustomTransformers === null || getCustomTransformers === void 0 ? void 0 : getCustomTransformers(invalidatedProject.project)); if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; } @@ -113898,8 +117350,14 @@ var ts; continue; } var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames()); + if (!outputs.length) + continue; + var inputFileNames = new ts.Set(parsed.fileNames.map(function (f) { return toPath(state, f); })); for (var _a = 0, outputs_3 = outputs; _a < outputs_3.length; _a++) { var output = outputs_3[_a]; + // If output name is same as input file name, do not delete and ignore the error + if (inputFileNames.has(toPath(state, output))) + continue; if (host.fileExists(output)) { if (filesToDelete) { filesToDelete.push(output); @@ -113975,7 +117433,7 @@ var ts; }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved)); } function watchExtendedConfigFiles(state, resolvedPath, parsed) { - ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { + ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed === null || parsed === void 0 ? void 0 : parsed.options, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () { var _a; return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (projectConfigFilePath) { return invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ts.ConfigFileProgramReloadLevel.Full); @@ -113986,6 +117444,7 @@ var ts; if (!state.watch) return; ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), new ts.Map(ts.getEntries(parsed.wildcardDirectories)), function (dir, flags) { return state.watchDirectory(dir, function (fileOrDirectory) { + var _a; if (ts.isIgnoredFileFromWildCardWatching({ watchedDirPath: toPath(state, dir), fileOrDirectory: fileOrDirectory, @@ -113993,9 +117452,10 @@ var ts; configFileName: resolved, currentDirectory: state.currentDirectory, options: parsed.options, - program: state.builderPrograms.get(resolvedPath), + program: state.builderPrograms.get(resolvedPath) || ((_a = getCachedParsedConfigFile(state, resolvedPath)) === null || _a === void 0 ? void 0 : _a.fileNames), useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames, - writeLog: function (s) { return state.writeLog(s); } + writeLog: function (s) { return state.writeLog(s); }, + toPath: function (fileName) { return toPath(state, fileName); } })) return; invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Partial); @@ -114030,19 +117490,16 @@ var ts; } function stopWatching(state) { ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher); - ts.clearMap(state.allWatchedExtendedConfigFiles, function (watcher) { - watcher.projects.clear(); - watcher.close(); - }); + ts.clearMap(state.allWatchedExtendedConfigFiles, ts.closeFileWatcherOf); ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); }); ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); }); } function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) { var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions); return { - build: function (project, cancellationToken) { return build(state, project, cancellationToken); }, + build: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers); }, clean: function (project) { return clean(state, project); }, - buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); }, + buildReferences: function (project, cancellationToken, writeFile, getCustomTransformers) { return build(state, project, cancellationToken, writeFile, getCustomTransformers, /*onlyReferences*/ true); }, cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); }, getNextInvalidatedProject: function (cancellationToken) { setupInitialBuild(state, cancellationToken); @@ -114132,6 +117589,9 @@ var ts; } } function reportUpToDateStatus(state, configFileName, status) { + if (state.options.force && (status.type === ts.UpToDateStatusType.UpToDate || status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes)) { + return reportStatus(state, ts.Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName)); + } switch (status.type) { case ts.UpToDateStatusType.OutOfDateWithSelf: return reportStatus(state, ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), relName(state, status.newerInputFileName)); diff --git a/lib/zh-cn/diagnosticMessages.generated.json b/lib/zh-cn/diagnosticMessages.generated.json index 4c9eb13c992e4..1fd2fa83bc187 100644 --- a/lib/zh-cn/diagnosticMessages.generated.json +++ b/lib/zh-cn/diagnosticMessages.generated.json @@ -199,6 +199,7 @@ "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "不能在环境上下文中声明实现。", "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "导入别名不能引用使用 \"export type\" 导出的声明。", "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "导入别名不能引用使用 \"import type\" 导入的声明。", + "An_import_alias_cannot_use_import_type_1392": "导入别名不能使用“导入类型”", "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "导入声明只能在命名空间或模块中使用。", "An_import_declaration_cannot_have_modifiers_1191": "导入声明不能有修饰符。", "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "导入路径不能以“{0}”扩展名结束。考虑改为导入“{1}”。", @@ -443,6 +444,7 @@ "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "模块的默认导出具有或正在使用专用名称“{0}”。", "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "以下标识符的定义与另一个文件中的定义冲突: {0}", "Delete_all_unused_declarations_95024": "删除未使用的所有声明", + "Delete_all_unused_imports_95147": "删除所有未使用的导入", "Delete_the_outputs_of_all_projects_6365": "删除所有项目的输出", "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[已弃用] 请改用 \"--jsxFactory\"。已 \"react\" JSX 发出设为目标时,请指定要为 createElement 调用的对象", "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[已弃用] 请改用 \"--outFile\"。连接并发出到单个文件的输出", @@ -668,6 +670,7 @@ "Index_signatures_are_incompatible_2330": "索引签名不兼容。", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "合并声明“{0}”中的单独声明必须全为导出或全为局部声明。", "Infer_all_types_from_usage_95023": "从使用情况推导所有类型", + "Infer_function_return_type_95148": "推断函数返回类型", "Infer_parameter_types_from_usage_95012": "根据使用情况推断参数类型", "Infer_this_type_of_0_from_usage_95080": "从用法中推断出 \"{0}\" 的 \"this\" 类型", "Infer_type_of_0_from_usage_95011": "根据使用情况推断“{0}”的类型", @@ -814,7 +817,6 @@ "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "枚举成员初始值设定项中不允许有八进制文本。请使用语法“{0}”。", "Octal_literals_are_not_allowed_in_strict_mode_1121": "严格模式下不允许使用八进制文本。", "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "当面向 ECMAScript 5 及更高版本时,不能使用八进制文本。请使用语法“{0}”。", - "Only_ECMAScript_imports_may_use_import_type_1370": "仅 ECMAScript 导入可使用 \"import type\"。", "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "\"for...in\" 语句中只允许单个变量声明。", "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "\"for...of\" 语句中只允许单个变量声明。", "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "使用 \"new\" 关键字只能调用 void 函数。", @@ -920,9 +922,11 @@ "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": "要引用的项目", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "属性“{0}”来自索引签名,因此必须使用[“{0}”]访问它。", "Property_0_does_not_exist_on_const_enum_1_2479": "\"const\" 枚举“{1}”上不存在属性“{0}”。", "Property_0_does_not_exist_on_type_1_2339": "类型“{1}”上不存在属性“{0}”。", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "属性“{0}”在类型“{1}”上不存在。你是否指的是“{2}”?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "属性“{0}”在类型“{1}”上不存在。你的意思是改为访问静态成员“{2}”吗?", "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "在“{1}”上没有“{0}”属性。是否需要更改目标库? 请尝试将 `lib` 编译器选项更改为 {2} 或更高版本。", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "属性“{0}”没有初始化表达式,且未在构造函数中明确赋值。", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "属性“{0}”隐式具有类型 \"any\",因为其 get 访问器缺少返回类型批注。", @@ -932,7 +936,6 @@ "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "类型“{1}”中的属性“{0}”不可分配给基类型“{2}”中的同一属性。", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "类型“{1}”中的属性“{0}”不可分配给类型“{2}”。", "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "类型 \"{1}\" 中的属性 \"{0}\" 引用了不能从类型 \"{2}\" 内访问的其他成员。", - "Property_0_is_a_static_member_of_type_1_2576": "属性“{0}”不是类型为“{1}”的静态成员。", "Property_0_is_declared_but_its_value_is_never_read_6138": "已声明属性“{0}”,但从未读取其值。", "Property_0_is_incompatible_with_index_signature_2530": "属性“{0}”与索引签名不兼容。", "Property_0_is_incompatible_with_rest_element_type_2573": "属性 \"{0}\" 与 rest 元素类型不兼容。", @@ -1007,6 +1010,7 @@ "Report_errors_in_js_files_8019": ".js 文件中的报表出错。", "Report_errors_on_unused_locals_6134": "报告未使用的局部变量上的错误。", "Report_errors_on_unused_parameters_6135": "报告未使用的参数上的错误。", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803": "要求索引签名中有未声明的属性以使用元素访问。", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "所需的类型参数可能不遵循可选类型参数。", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "在位置“{1}”的缓存中找到模块“{0}”的解析。", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "只将 \"keyof\" 解析为字符串值的属性名称(不含数字或符号)。", @@ -1216,7 +1220,7 @@ "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "此表达式是 \"get\" 访问器,因此不可调用。你想在不使用 \"()\" 的情况下使用它吗?", "This_expression_is_not_constructable_2351": "此表达式不可构造。", "This_file_already_has_a_default_export_95130": "此文件已具有默认导出", - "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "此导入从不用作值,必须使用 \"import type\" ,因为 \"importsNotUsedAsValues\" 设置为 \"error\"。", + "This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set__1371": "此导入从不用作值,必须使用 \"import type\" ,因为 \"importsNotUsedAsValues\" 设置为 \"error\"。", "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "这是正在扩充的声明。请考虑将扩充声明移到同一个文件中。", "This_may_be_converted_to_an_async_function_80006": "可将此转换为异步函数。", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "只能通过启用 \"{0}\" 标志并引用其默认导出,使用 ECMAScript 导入/导出来引用此模块。", @@ -1342,6 +1346,8 @@ "Updating_output_of_project_0_6373": "正在更新项目 \"{0}\" 的输出…", "Updating_output_timestamps_of_project_0_6359": "正在更新项目“{0}”的输出时间戳...", "Updating_unchanged_output_timestamps_of_project_0_6371": "正在更新项目 \"{0}\" 未更改的输出时间戳…", + "Use_element_access_for_0_95145": "对“{0}”使用元素访问", + "Use_element_access_for_all_undeclared_properties_95146": "对所有未声明的属性使用元素访问。", "Use_synthetic_default_member_95016": "使用综合的“默认”成员。", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "仅 ECMAScript 5 和更高版本支持在 \"for...of\" 语句中使用字符串。", "Using_compiler_options_of_project_reference_redirect_0_6215": "使用项目引用重定向“{0}”的编译器选项。", diff --git a/lib/zh-tw/diagnosticMessages.generated.json b/lib/zh-tw/diagnosticMessages.generated.json index 7663d9cb84404..0b22d6aebc709 100644 --- a/lib/zh-tw/diagnosticMessages.generated.json +++ b/lib/zh-tw/diagnosticMessages.generated.json @@ -199,6 +199,7 @@ "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "不得在環境內容中宣告實作。", "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379": "匯入別名不能參考使用 'export type' 匯出的宣告。", "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380": "匯入別名不能參考使用 'import type' 匯入的宣告。", + "An_import_alias_cannot_use_import_type_1392": "匯入別名不能使用 'import type'", "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "匯入宣告只可用於命名空間或模組中。", "An_import_declaration_cannot_have_modifiers_1191": "匯入宣告不得有修飾元。", "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "匯入路徑的結尾不得為 '{0}' 副檔名。請考慮改為匯入 '{1}'。", @@ -443,6 +444,7 @@ "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "模組的預設匯出具有或正在使用私用名稱 '{0}'。", "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200": "下列識別碼的定義與其他檔案中的定義衝突: {0}", "Delete_all_unused_declarations_95024": "刪除所有未使用的宣告", + "Delete_all_unused_imports_95147": "刪除所有未使用的匯入", "Delete_the_outputs_of_all_projects_6365": "刪除所有專案的輸出", "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[即將淘汰] 請改用 '--jsxFactory'。當目標為 'react' JSX 發出時,為 createElement 指定所叫用的物件", "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[即將淘汰] 請改用 '--outFile'。 串連輸出並將其發出到單一檔案", @@ -668,6 +670,7 @@ "Index_signatures_are_incompatible_2330": "索引簽章不相容。", "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395": "合併宣告 '{0}' 中的個別宣告必須全部匯出或全在本機上。", "Infer_all_types_from_usage_95023": "從用法推斷所有類型", + "Infer_function_return_type_95148": "推斷函式傳回型別", "Infer_parameter_types_from_usage_95012": "從使用方式推斷參數類型", "Infer_this_type_of_0_from_usage_95080": "從使用方式推斷 '{0}' 的 'this' 類型", "Infer_type_of_0_from_usage_95011": "從使用方式推斷 '{0}' 的類型", @@ -814,7 +817,6 @@ "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018": "列舉成員初始設定式中不允許八進位常值。請使用語法 '{0}'。", "Octal_literals_are_not_allowed_in_strict_mode_1121": "strict 模式中不允許八進位常值。", "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085": "當目標為 ECMAScript 5 及更高版本時,不可使用八進位的常值。請使用語法 '{0}'。", - "Only_ECMAScript_imports_may_use_import_type_1370": "只有 ECMAScript 匯入可以使用 'import type'。", "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091": "'for...in' 陳述式中只可包含一個變數宣告。", "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188": "'for...of' 陳述式只能包含一個變數宣告。", "Only_a_void_function_can_be_called_with_the_new_keyword_2350": "只有 void 函式可以使用 'new' 關鍵字進行呼叫。", @@ -920,9 +922,11 @@ "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": "專案至參考", + "Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0_4111": "屬性 '{0}' 來自索引簽章,因此必須使用 ['{0}'] 存取。", "Property_0_does_not_exist_on_const_enum_1_2479": "'const' 列舉 '{1}' 上並沒有屬性 '{0}'。", "Property_0_does_not_exist_on_type_1_2339": "類型 '{1}' 沒有屬性 '{0}'。", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "類型 '{1}' 沒有屬性 '{0}'。您指的是 '{2}' 嗎?", + "Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead_2576": "屬性 '{0}' 不存在於類型 '{1}' 上。您要存取的是靜態成員 '{2}' 嗎?", "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550": "類型 '{1}' 沒有屬性 '{0}'。要變更您的目標程式庫嗎? 請嘗試將 'lib' 編譯器選項變更為 '{2}' 或更新版本。", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "屬性 '{0}' 沒有初始設定式,且未在建構函式中明確指派。", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "因為屬性 '{0}' 的 get 存取子沒有傳回類型註釋,致使該屬性意味著類型 'any'。", @@ -932,7 +936,6 @@ "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "類型 '{1}' 中的屬性 '{0}' 無法指派給基底類型 '{2}' 中的相同屬性。", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "不得將類型 '{1}' 的屬性 '{0}' 指派給類型 '{2}'。", "Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2_18015": "類型 '{1}' 中的屬性 '{0}' 是無法從類型 '{2}' 中存取的其他成員。", - "Property_0_is_a_static_member_of_type_1_2576": "屬性 '{0}' 為 '{1}' 類型的靜態成員。", "Property_0_is_declared_but_its_value_is_never_read_6138": "屬性 '{0}' 已宣告但從未讀取其值。", "Property_0_is_incompatible_with_index_signature_2530": "屬性 '{0}' 和索引簽章不相容。", "Property_0_is_incompatible_with_rest_element_type_2573": "屬性 '{0}' 與其餘項目類型不相容。", @@ -1007,6 +1010,7 @@ "Report_errors_in_js_files_8019": "報告 .js 檔案中的錯誤。", "Report_errors_on_unused_locals_6134": "回報未使用之區域變數的錯誤。", "Report_errors_on_unused_parameters_6135": "回報未使用之參數的錯誤。", + "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803": "需要來自索引簽章的未宣告屬性,才能使用元素存取。", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "必要型別參數可能未遵循選擇性型別參數。", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "從位置 '{1}' 的快取中找到模組 '{0}' 的解析。", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "只將 'keyof' 解析為字串值的屬性名稱 (無任何數字或符號)。", @@ -1146,7 +1150,7 @@ "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise 的 'then' 方法第一個參數必須為回撥。", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "全域類型 'JSX.{0}' 的屬性不得超過一個。", "The_implementation_signature_is_declared_here_2750": "實作簽章宣告於此處。", - "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "只有當 '--module' 選項為 'esnext' 或 'system' 時,才允許 'import.meta' 中繼屬性。", + "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system_1343": "只有當 '--module' 選項為 'es2020'、'esnext' 或 'system' 時,才允許 'import.meta' 中繼屬性。", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "'{0}' 的推斷類型無法在沒有 '{1}' 參考的情況下命名。其可能非可攜式。必須有型別註解。", "The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialize_5088": "'{0}' 的推斷型別參考了具有迴圈結構且不是可完整序列化的型別。必須有型別註解。", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}' 的推斷型別參考了無法存取的 '{1}' 型別。必須有型別註解。", @@ -1216,7 +1220,7 @@ "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234": "因為此運算式為 'get' 存取子,所以無法呼叫。要在沒有 '()' 的情況下,使用該運算式嗎?", "This_expression_is_not_constructable_2351": "無法建構此運算式。", "This_file_already_has_a_default_export_95130": "此檔案已有預設匯出", - "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "因為 'importsNotUsedAsValues' 設定為 'error',所以此匯入永遠不會作為值使用,而且必須使用 'import type'。", + "This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set__1371": "因為 'importsNotUsedAsValues' 設為 'error',所以永遠不會使用此匯入作為值,且必須使用 'import type'。", "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "此宣告正在增加中。請考慮將正在增加的宣告移至相同的檔案中。", "This_may_be_converted_to_an_async_function_80006": "這可以轉換為非同步函式。", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "只能以 ECMAScript 匯入/匯出來參考此模組,方法為開啟 '{0}' 旗標並參考其預設匯出。", @@ -1342,6 +1346,8 @@ "Updating_output_of_project_0_6373": "正在更新專案 '{0}' 的輸出...", "Updating_output_timestamps_of_project_0_6359": "正在更新專案 '{0}' 的輸出時間戳記...", "Updating_unchanged_output_timestamps_of_project_0_6371": "正在更新專案 '{0}' 的未更變輸出時間戳記...", + "Use_element_access_for_0_95145": "對 '{0}' 使用元素存取", + "Use_element_access_for_all_undeclared_properties_95146": "對所有未宣告的屬性使用元素存取。", "Use_synthetic_default_member_95016": "使用綜合 'default' 成員。", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "只有在 ECMAScript 5 及更高版本中,才可在 'for...of' 陳述式中使用字串。", "Using_compiler_options_of_project_reference_redirect_0_6215": "正在使用專案參考重新導向 '{0}' 的編譯器選項。", diff --git a/package-lock.json b/package-lock.json index 32c759fbc4463..bcbb39e9a3e9c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "typescript", - "version": "4.2.0", + "version": "4.3.0", "lockfileVersion": 1, "requires": true, "dependencies": { @@ -288,16 +288,17 @@ } }, "@octokit/core": { - "version": "3.2.5", - "resolved": "https://registry.npmjs.org/@octokit/core/-/core-3.2.5.tgz", - "integrity": "sha512-+DCtPykGnvXKWWQI0E1XD+CCeWSBhB6kwItXqfFmNBlIlhczuDPbg+P6BtLnVBaRJDAjv+1mrUJuRsFSjktopg==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@octokit/core/-/core-3.4.0.tgz", + "integrity": "sha512-6/vlKPP8NF17cgYXqucdshWqmMZGXkuvtcrWCgU5NOI0Pl2GjlmZyWgBMrU8zJ3v2MJlM6++CiB45VKYmhiWWg==", "dev": true, "requires": { "@octokit/auth-token": "^2.4.4", "@octokit/graphql": "^4.5.8", "@octokit/request": "^5.4.12", + "@octokit/request-error": "^2.0.5", "@octokit/types": "^6.0.3", - "before-after-hook": "^2.1.0", + "before-after-hook": "^2.2.0", "universal-user-agent": "^6.0.0" } }, @@ -313,9 +314,9 @@ } }, "@octokit/graphql": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.6.0.tgz", - "integrity": "sha512-CJ6n7izLFXLvPZaWzCQDjU/RP+vHiZmWdOunaCS87v+2jxMsW9FB5ktfIxybRBxZjxuJGRnxk7xJecWTVxFUYQ==", + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.6.1.tgz", + "integrity": "sha512-2lYlvf4YTDgZCTXTW4+OX+9WTLFtEUc6hGm4qM1nlZjzxj+arizM4aHWzBVBCxY9glh7GIs0WEuiSgbVzv8cmA==", "dev": true, "requires": { "@octokit/request": "^5.3.0", @@ -324,18 +325,18 @@ } }, "@octokit/openapi-types": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-4.0.1.tgz", - "integrity": "sha512-k2hRcfcLRyPJjtYfJLzg404n7HZ6sUpAWAR/uNI8tf96NgatWOpw1ocdF+WFfx/trO1ivBh7ckynO1rn+xAw/Q==", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-7.0.0.tgz", + "integrity": "sha512-gV/8DJhAL/04zjTI95a7FhQwS6jlEE0W/7xeYAzuArD0KVAVWDLP2f3vi98hs3HLTczxXdRK/mF0tRoQPpolEw==", "dev": true }, "@octokit/plugin-paginate-rest": { - "version": "2.9.1", - "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.9.1.tgz", - "integrity": "sha512-8wnuWGjwDIEobbBet2xAjZwgiMVTgIer5wBsnGXzV3lJ4yqphLU2FEMpkhSrDx7y+WkZDfZ+V+1cFMZ1mAaFag==", + "version": "2.13.3", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.13.3.tgz", + "integrity": "sha512-46lptzM9lTeSmIBt/sVP/FLSTPGx6DCzAdSX3PfeJ3mTf4h9sGC26WpaQzMEq/Z44cOcmx8VsOhO+uEgE3cjYg==", "dev": true, "requires": { - "@octokit/types": "^6.8.0" + "@octokit/types": "^6.11.0" } }, "@octokit/plugin-request-log": { @@ -345,28 +346,26 @@ "dev": true }, "@octokit/plugin-rest-endpoint-methods": { - "version": "4.10.1", - "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-4.10.1.tgz", - "integrity": "sha512-YGMiEidTORzgUmYZu0eH4q2k8kgQSHQMuBOBYiKxUYs/nXea4q/Ze6tDzjcRAPmHNJYXrENs1bEMlcdGKT+8ug==", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-5.0.1.tgz", + "integrity": "sha512-vvWbPtPqLyIzJ7A4IPdTl+8IeuKAwMJ4LjvmqWOOdfSuqWQYZXq2CEd0hsnkidff2YfKlguzujHs/reBdAx8Sg==", "dev": true, "requires": { - "@octokit/types": "^6.8.2", + "@octokit/types": "^6.13.1", "deprecation": "^2.3.1" } }, "@octokit/request": { - "version": "5.4.14", - "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.4.14.tgz", - "integrity": "sha512-VkmtacOIQp9daSnBmDI92xNIeLuSRDOIuplp/CJomkvzt7M18NXgG044Cx/LFKLgjKt9T2tZR6AtJayba9GTSA==", + "version": "5.4.15", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.4.15.tgz", + "integrity": "sha512-6UnZfZzLwNhdLRreOtTkT9n57ZwulCve8q3IT/Z477vThu6snfdkBuhxnChpOKNGxcQ71ow561Qoa6uqLdPtag==", "dev": true, "requires": { "@octokit/endpoint": "^6.0.1", "@octokit/request-error": "^2.0.0", "@octokit/types": "^6.7.1", - "deprecation": "^2.0.0", "is-plain-object": "^5.0.0", "node-fetch": "^2.6.1", - "once": "^1.4.0", "universal-user-agent": "^6.0.0" }, "dependencies": { @@ -390,25 +389,24 @@ } }, "@octokit/rest": { - "version": "18.1.0", - "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-18.1.0.tgz", - "integrity": "sha512-YQfpTzWV3jdzDPyXQVO54f5I2t1zxk/S53Vbe+Aa5vQj6MdTx6sNEWzmUzUO8lSVowbGOnjcQHzW1A8ATr+/7g==", + "version": "18.5.3", + "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-18.5.3.tgz", + "integrity": "sha512-KPAsUCr1DOdLVbZJgGNuE/QVLWEaVBpFQwDAz/2Cnya6uW2wJ/P5RVGk0itx7yyN1aGa8uXm2pri4umEqG1JBA==", "dev": true, "requires": { "@octokit/core": "^3.2.3", "@octokit/plugin-paginate-rest": "^2.6.2", "@octokit/plugin-request-log": "^1.0.2", - "@octokit/plugin-rest-endpoint-methods": "4.10.1" + "@octokit/plugin-rest-endpoint-methods": "5.0.1" } }, "@octokit/types": { - "version": "6.8.2", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.8.2.tgz", - "integrity": "sha512-RpG0NJd7OKSkWptiFhy1xCLkThs5YoDIKM21lEtDmUvSpbaIEfrxzckWLUGDFfF8RydSyngo44gDv8m2hHruUg==", + "version": "6.14.2", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.14.2.tgz", + "integrity": "sha512-wiQtW9ZSy4OvgQ09iQOdyXYNN60GqjCL/UdMsepDr1Gr0QzpW6irIKbH3REuAHXAhxkEk9/F2a3Gcs1P6kW5jA==", "dev": true, "requires": { - "@octokit/openapi-types": "^4.0.0", - "@types/node": ">= 8" + "@octokit/openapi-types": "^7.0.0" } }, "@types/browserify": { @@ -422,9 +420,9 @@ } }, "@types/chai": { - "version": "4.2.14", - "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.2.14.tgz", - "integrity": "sha512-G+ITQPXkwTrslfG5L/BksmbLUA0M1iybEsmCWPqzSxsRRhJZimBKJkoMi8fr/CPygPTj4zO5pJH7I2/cm9M7SQ==", + "version": "4.2.18", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.2.18.tgz", + "integrity": "sha512-rS27+EkB/RE1Iz3u0XtVL5q36MGDWbgYe7zWiodyKNUnthxY0rukK5V36eiUCtCisB7NN8zKYH6DO2M37qxFEQ==", "dev": true }, "@types/convert-source-map": { @@ -525,9 +523,9 @@ } }, "@types/json-schema": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.6.tgz", - "integrity": "sha512-3c+yGKvVP5Y9TYBEibGNR+kLtijnj7mYrXRg+WpFb2X9xm04g/DXYkfg4hmzJQosc9snFNUPkbYIhu+KAm6jJw==", + "version": "7.0.7", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.7.tgz", + "integrity": "sha512-cxWFQVseBm6O9Gbw1IWb8r6OS4OhSt3hPZLkFApLjM8TEXROBuQGLAH2i2gZpcXdLBIrpXuTDhH7Vbm1iXmNGA==", "dev": true }, "@types/json5": { @@ -552,9 +550,9 @@ "dev": true }, "@types/minimatch": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", - "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-1z8k4wzFnNjVK/tlxvrWuK5WMt6mydWWP7+zvH5eFep4oj+UkrfiJTRtjCeBXNpwaA/FYqqtb4/QS4ianFpIRA==", "dev": true }, "@types/minimist": { @@ -573,9 +571,9 @@ } }, "@types/mocha": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-8.2.0.tgz", - "integrity": "sha512-/Sge3BymXo4lKc31C8OINJgXLaw+7vL1/L1pGiBNpGrBiT8FQiaFpSYV0uhTaG4y78vcMBTMFsWaHDvuD+xGzQ==", + "version": "8.2.2", + "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-8.2.2.tgz", + "integrity": "sha512-Lwh0lzzqT5Pqh6z61P3c3P5nm6fzQK/MMHl9UKeneAeInVflBSz1O2EkX6gM6xfJd7FBXBY5purtLx7fUiZ7Hw==", "dev": true }, "@types/ms": { @@ -585,9 +583,9 @@ "dev": true }, "@types/node": { - "version": "14.14.25", - "resolved": "https://registry.npmjs.org/@types/node/-/node-14.14.25.tgz", - "integrity": "sha512-EPpXLOVqDvisVxtlbvzfyqSsFeQxltFbluZNRndIb8tr9KiBnYNLzrc1N3pyKUCww2RNrfHDViqDWWE1LCJQtQ==", + "version": "15.0.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-15.0.2.tgz", + "integrity": "sha512-p68+a+KoxpoB47015IeYZYRrdqMUcpbK8re/zpFB8Ld46LHC1lPEbp3EXgkEhAYEcPvjJF6ZO+869SQ0aH1dcA==", "dev": true }, "@types/node-fetch": { @@ -679,15 +677,16 @@ } }, "@typescript-eslint/eslint-plugin": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-4.5.0.tgz", - "integrity": "sha512-mjb/gwNcmDKNt+6mb7Aj/TjKzIJjOPcoCJpjBQC9ZnTRnBt1p4q5dJSSmIqAtsZ/Pff5N+hJlbiPc5bl6QN4OQ==", + "version": "4.19.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-4.19.0.tgz", + "integrity": "sha512-CRQNQ0mC2Pa7VLwKFbrGVTArfdVDdefS+gTw0oC98vSI98IX5A8EVH4BzJ2FOB0YlCmm8Im36Elad/Jgtvveaw==", "dev": true, "requires": { - "@typescript-eslint/experimental-utils": "4.5.0", - "@typescript-eslint/scope-manager": "4.5.0", + "@typescript-eslint/experimental-utils": "4.19.0", + "@typescript-eslint/scope-manager": "4.19.0", "debug": "^4.1.1", "functional-red-black-tree": "^1.0.1", + "lodash": "^4.17.15", "regexpp": "^3.0.0", "semver": "^7.3.2", "tsutils": "^3.17.1" @@ -713,28 +712,28 @@ } }, "@typescript-eslint/experimental-utils": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-4.5.0.tgz", - "integrity": "sha512-bW9IpSAKYvkqDGRZzayBXIgPsj2xmmVHLJ+flGSoN0fF98pGoKFhbunIol0VF2Crka7z984EEhFi623Rl7e6gg==", + "version": "4.19.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-4.19.0.tgz", + "integrity": "sha512-9/23F1nnyzbHKuoTqFN1iXwN3bvOm/PRIXSBR3qFAYotK/0LveEOHr5JT1WZSzcD6BESl8kPOG3OoDRKO84bHA==", "dev": true, "requires": { "@types/json-schema": "^7.0.3", - "@typescript-eslint/scope-manager": "4.5.0", - "@typescript-eslint/types": "4.5.0", - "@typescript-eslint/typescript-estree": "4.5.0", + "@typescript-eslint/scope-manager": "4.19.0", + "@typescript-eslint/types": "4.19.0", + "@typescript-eslint/typescript-estree": "4.19.0", "eslint-scope": "^5.0.0", "eslint-utils": "^2.0.0" } }, "@typescript-eslint/parser": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-4.5.0.tgz", - "integrity": "sha512-xb+gmyhQcnDWe+5+xxaQk5iCw6KqXd8VQxGiTeELTMoYeRjpocZYYRP1gFVM2C8Yl0SpUvLa1lhprwqZ00w3Iw==", + "version": "4.19.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-4.19.0.tgz", + "integrity": "sha512-/uabZjo2ZZhm66rdAu21HA8nQebl3lAIDcybUoOxoI7VbZBYavLIwtOOmykKCJy+Xq6Vw6ugkiwn8Js7D6wieA==", "dev": true, "requires": { - "@typescript-eslint/scope-manager": "4.5.0", - "@typescript-eslint/types": "4.5.0", - "@typescript-eslint/typescript-estree": "4.5.0", + "@typescript-eslint/scope-manager": "4.19.0", + "@typescript-eslint/types": "4.19.0", + "@typescript-eslint/typescript-estree": "4.19.0", "debug": "^4.1.1" }, "dependencies": { @@ -758,58 +757,49 @@ } }, "@typescript-eslint/scope-manager": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-4.5.0.tgz", - "integrity": "sha512-C0cEO0cTMPJ/w4RA/KVe4LFFkkSh9VHoFzKmyaaDWAnPYIEzVCtJ+Un8GZoJhcvq+mPFXEsXa01lcZDHDG6Www==", + "version": "4.19.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-4.19.0.tgz", + "integrity": "sha512-GGy4Ba/hLXwJXygkXqMzduqOMc+Na6LrJTZXJWVhRrSuZeXmu8TAnniQVKgj8uTRKe4igO2ysYzH+Np879G75g==", "dev": true, "requires": { - "@typescript-eslint/types": "4.5.0", - "@typescript-eslint/visitor-keys": "4.5.0" + "@typescript-eslint/types": "4.19.0", + "@typescript-eslint/visitor-keys": "4.19.0" } }, "@typescript-eslint/types": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-4.5.0.tgz", - "integrity": "sha512-n2uQoXnyWNk0Les9MtF0gCK3JiWd987JQi97dMSxBOzVoLZXCNtxFckVqt1h8xuI1ix01t+iMY4h4rFMj/303g==", + "version": "4.19.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-4.19.0.tgz", + "integrity": "sha512-A4iAlexVvd4IBsSTNxdvdepW0D4uR/fwxDrKUa+iEY9UWvGREu2ZyB8ylTENM1SH8F7bVC9ac9+si3LWNxcBuA==", "dev": true }, "@typescript-eslint/typescript-estree": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-4.5.0.tgz", - "integrity": "sha512-gN1mffq3zwRAjlYWzb5DanarOPdajQwx5MEWkWCk0XvqC8JpafDTeioDoow2L4CA/RkYZu7xEsGZRhqrTsAG8w==", + "version": "4.19.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-4.19.0.tgz", + "integrity": "sha512-3xqArJ/A62smaQYRv2ZFyTA+XxGGWmlDYrsfZG68zJeNbeqRScnhf81rUVa6QG4UgzHnXw5VnMT5cg75dQGDkA==", "dev": true, "requires": { - "@typescript-eslint/types": "4.5.0", - "@typescript-eslint/visitor-keys": "4.5.0", + "@typescript-eslint/types": "4.19.0", + "@typescript-eslint/visitor-keys": "4.19.0", "debug": "^4.1.1", "globby": "^11.0.1", "is-glob": "^4.0.1", - "lodash": "^4.17.15", "semver": "^7.3.2", "tsutils": "^3.17.1" }, "dependencies": { "debug": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.2.0.tgz", - "integrity": "sha512-IX2ncY78vDTjZMFUdmsvIRFY2Cf4FnD0wRs+nQwJU8Lu99/tPFdb0VybiiMTPe3I6rQmwsqQqRBvxU+bZ/I8sg==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz", + "integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==", "dev": true, "requires": { "ms": "2.1.2" - }, - "dependencies": { - "ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true - } } }, "globby": { - "version": "11.0.1", - "resolved": "https://registry.npmjs.org/globby/-/globby-11.0.1.tgz", - "integrity": "sha512-iH9RmgwCmUJHi2z5o2l3eTtGBtXek1OYlHrbcxOYugyHLmAsZrPj43OtHThd62Buh/Vv6VyCBD2bdyWcGNQqoQ==", + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/globby/-/globby-11.0.3.tgz", + "integrity": "sha512-ffdmosjA807y7+lA1NM0jELARVmYul/715xiILEjo3hBLPTcirgQNnXECn5g3mtR8TOLCVbkfua1Hpen25/Xcg==", "dev": true, "requires": { "array-union": "^2.1.0", @@ -819,16 +809,22 @@ "merge2": "^1.3.0", "slash": "^3.0.0" } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true } } }, "@typescript-eslint/visitor-keys": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-4.5.0.tgz", - "integrity": "sha512-UHq4FSa55NDZqscRU//O5ROFhHa9Hqn9KWTEvJGTArtTQp5GKv9Zqf6d/Q3YXXcFv4woyBml7fJQlQ+OuqRcHA==", + "version": "4.19.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-4.19.0.tgz", + "integrity": "sha512-aGPS6kz//j7XLSlgpzU2SeTqHPsmRYxFztj2vPuMMFJXZudpRSehE3WCV+BaxwZFvfAqMoSd86TEuM0PQ59E/A==", "dev": true, "requires": { - "@typescript-eslint/types": "4.5.0", + "@typescript-eslint/types": "4.19.0", "eslint-visitor-keys": "^2.0.0" } }, @@ -1168,9 +1164,9 @@ }, "dependencies": { "bn.js": { - "version": "4.11.9", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.9.tgz", - "integrity": "sha512-E6QoYqCKZfgatHTdHzs1RRKP7ip4vvm+EyRUeE2RF0NblwVvb0p6jSVeNTOFxPn26QXN2o6SMfNxKp6kU8zQaw==", + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", "dev": true } } @@ -1376,9 +1372,9 @@ "dev": true }, "before-after-hook": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.1.1.tgz", - "integrity": "sha512-5ekuQOvO04MDj7kYZJaMab2S8SPjGJbotVNyv7QYFCOAwrGZs/YnoDNlh1U+m5hl7H2D/+n0taaAV/tfyd3KMA==", + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.1.tgz", + "integrity": "sha512-/6FKxSTWoJdbsLDF8tdIjaRiFXiE6UHsEHE3OPI/cwPURCVi1ukP0gmLn7XWEiFk5TcwQjjY5PWsU+j+tgXgmw==", "dev": true }, "binary-extensions": { @@ -1398,9 +1394,9 @@ } }, "bn.js": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.1.3.tgz", - "integrity": "sha512-GkTiFpjFtUzU9CbMeJ5iazkCzGL3jrhzerzZIuqLABjbwRaFt33I9tUdSNryIptM+RxDet6OKm2WnLXzW51KsQ==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.2.0.tgz", + "integrity": "sha512-D7iWRBvnZE8ecXiLj/9wbxH7Tk79fAh8IHaTNq1RWRixsS02W+5qS+iE9yq6RYl0asXx5tw0bLhmT5pIfbSquw==", "dev": true }, "brace-expansion": { @@ -1555,21 +1551,21 @@ }, "dependencies": { "resolve": { - "version": "1.19.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.19.0.tgz", - "integrity": "sha512-rArEXAgsBG4UgRGcynxWIWKFvh/XZCcS8UJdHhwy91zwAvCZIbcs+vAbflgBnNjYMs/i/i+/Ux6IZhML1yPvxg==", + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz", + "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", "dev": true, "requires": { - "is-core-module": "^2.1.0", + "is-core-module": "^2.2.0", "path-parse": "^1.0.6" } } } }, "is-core-module": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.2.0.tgz", - "integrity": "sha512-XRAfAdyyY5F5cOXn7hYQDqh2Xmii+DEfIcQGxK/uNwMHhIkPWO0g8msXcbzLe+MpGoR951MlqM/2iIlU4vKDdQ==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.3.0.tgz", + "integrity": "sha512-xSphU2KG9867tsYdLD4RWQ1VqdFl4HTO9Thf3I/3dLEfr0dbPTWKsuCKrgqMljg4nPE+Gq0VCnzT3gr0CyBmsw==", "dev": true, "requires": { "has": "^1.0.3" @@ -1759,23 +1755,23 @@ "dev": true }, "chai": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.0.tgz", - "integrity": "sha512-/BFd2J30EcOwmdOgXvVsmM48l0Br0nmZPlO0uOW4XKh6kpsUumRXBgPV+IlaqFaqr9cYbeoZAM1Npx0i4A+aiA==", + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.4.tgz", + "integrity": "sha512-yS5H68VYOCtN1cjfwumDSuzn/9c+yza4f3reKXlE5rUg7SFcCEy90gJvydNgOYtblyf4Zi6jIWRnXOgErta0KA==", "dev": true, "requires": { "assertion-error": "^1.1.0", "check-error": "^1.0.2", "deep-eql": "^3.0.1", "get-func-name": "^2.0.0", - "pathval": "^1.1.0", + "pathval": "^1.1.1", "type-detect": "^4.0.5" } }, "chalk": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", - "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.1.tgz", + "integrity": "sha512-diHzdDKxcU+bAsUboHLPEDQiw0qEe0qd7SYUn3HgcFlWgbDcfLGswOHYeGrHKzG9z6UYf01d9VFMfZxPM1xZSg==", "dev": true, "requires": { "ansi-styles": "^4.1.0", @@ -2119,9 +2115,9 @@ }, "dependencies": { "bn.js": { - "version": "4.11.9", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.9.tgz", - "integrity": "sha512-E6QoYqCKZfgatHTdHzs1RRKP7ip4vvm+EyRUeE2RF0NblwVvb0p6jSVeNTOFxPn26QXN2o6SMfNxKp6kU8zQaw==", + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", "dev": true } } @@ -2331,6 +2327,7 @@ "version": "1.1.3", "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", + "dev": true, "requires": { "object-keys": "^1.0.12" } @@ -2485,9 +2482,9 @@ }, "dependencies": { "bn.js": { - "version": "4.11.9", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.9.tgz", - "integrity": "sha512-E6QoYqCKZfgatHTdHzs1RRKP7ip4vvm+EyRUeE2RF0NblwVvb0p6jSVeNTOFxPn26QXN2o6SMfNxKp6kU8zQaw==", + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", "dev": true } } @@ -2574,9 +2571,9 @@ }, "dependencies": { "bn.js": { - "version": "4.11.9", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.9.tgz", - "integrity": "sha512-E6QoYqCKZfgatHTdHzs1RRKP7ip4vvm+EyRUeE2RF0NblwVvb0p6jSVeNTOFxPn26QXN2o6SMfNxKp6kU8zQaw==", + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", "dev": true } } @@ -2641,29 +2638,11 @@ "string.prototype.trimstart": "^1.0.1" }, "dependencies": { - "es-abstract": { - "version": "1.18.0-next.1", - "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.1.tgz", - "integrity": "sha512-I4UGspA0wpZXWENrdA0uHbnhte683t3qT/1VFH9aX2dA5PPSf6QW5HHXf5HImaqPmjXaVeVk4RGWnaylmV7uAA==", - "requires": { - "es-to-primitive": "^1.2.1", - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1", - "is-callable": "^1.2.2", - "is-negative-zero": "^2.0.0", - "is-regex": "^1.1.1", - "object-inspect": "^1.8.0", - "object-keys": "^1.1.1", - "object.assign": "^4.1.1", - "string.prototype.trimend": "^1.0.1", - "string.prototype.trimstart": "^1.0.1" - } - }, "object.assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.1.tgz", "integrity": "sha512-VT/cxmx5yaoHSOTSyrCygIDFco+RsibY2NM0a4RdEeY/4KgqezwFtK1yr3U67xYhqJSlASm2pKhLVzPj2lr4bA==", + "dev": true, "requires": { "define-properties": "^1.1.3", "es-abstract": "^1.18.0-next.0", @@ -2675,6 +2654,7 @@ "version": "1.18.0-next.1", "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.1.tgz", "integrity": "sha512-I4UGspA0wpZXWENrdA0uHbnhte683t3qT/1VFH9aX2dA5PPSf6QW5HHXf5HImaqPmjXaVeVk4RGWnaylmV7uAA==", + "dev": true, "requires": { "es-to-primitive": "^1.2.1", "function-bind": "^1.1.1", @@ -2698,6 +2678,7 @@ "version": "1.2.1", "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", + "dev": true, "requires": { "is-callable": "^1.1.4", "is-date-object": "^1.0.1", @@ -2748,6 +2729,12 @@ "es6-symbol": "^3.1.1" } }, + "escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "dev": true + }, "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", @@ -3190,9 +3177,9 @@ } }, "events": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/events/-/events-3.2.0.tgz", - "integrity": "sha512-/46HWwbfCX2xTawVfkKLGxMifJYQBWMwY1mjywRtb4c9x8l5NP3KoJtnIOiL1hfdRkIuYhETxQlo62IF8tcnlg==", + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", "dev": true }, "evp_bytestokey": { @@ -3724,7 +3711,8 @@ "function-bind": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true }, "functional-red-black-tree": { "version": "1.0.1", @@ -3789,9 +3777,9 @@ "dev": true }, "glob": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", - "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", + "version": "7.1.7", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.7.tgz", + "integrity": "sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==", "dev": true, "requires": { "fs.realpath": "^1.0.0", @@ -4147,9 +4135,9 @@ } }, "handlebars": { - "version": "4.7.6", - "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.6.tgz", - "integrity": "sha512-1f2BACcBfiwAfStCKZNrUCgqNZkGsAT7UM3kkYtXuLo0KnaVfjKOyf7PRzB6++aK9STyT1Pd2ZCPe3EGOXleXA==", + "version": "4.7.7", + "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.7.tgz", + "integrity": "sha512-aAcXm5OAfE/8IXkcZvCepKU3VzW1/39Fb5ZuqMtgI/hT8X2YgoMvBY5dLhq/cpOvw7Lk1nK/UF71aLG/ZnVYRA==", "dev": true, "requires": { "minimist": "^1.2.5", @@ -4171,10 +4159,17 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, "requires": { "function-bind": "^1.1.1" } }, + "has-bigints": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.1.tgz", + "integrity": "sha512-LSBS2LjbNBTf6287JEbEzvJgftkF5qFkmCo9hDRpAzKhUOlJ+hx8dd4USs00SgsUNwc4617J9ki5YtEClM2ffA==", + "dev": true + }, "has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", @@ -4184,7 +4179,8 @@ "has-symbols": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz", - "integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==" + "integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==", + "dev": true }, "has-value": { "version": "1.0.0", @@ -4460,6 +4456,12 @@ "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", "dev": true }, + "is-bigint": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.2.tgz", + "integrity": "sha512-0JV5+SOCQkIdzjBK9buARcV804Ddu7A0Qet6sHi3FimE9ne6m4BGQZfRn+NZiXbBk4F4XmHfDZIipLj9pX8dSA==", + "dev": true + }, "is-binary-path": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-1.0.1.tgz", @@ -4469,6 +4471,15 @@ "binary-extensions": "^1.0.0" } }, + "is-boolean-object": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.1.tgz", + "integrity": "sha512-bXdQWkECBUIAcCkeH1unwJLIpZYaa5VvuygSyS/c2lf719mTKZDU5UdDRlpd01UjADgmW8RfqaP+mRaVPdr/Ng==", + "dev": true, + "requires": { + "call-bind": "^1.0.2" + } + }, "is-buffer": { "version": "1.1.6", "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", @@ -4478,7 +4489,8 @@ "is-callable": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.2.tgz", - "integrity": "sha512-dnMqspv5nU3LoewK2N/y7KLtxtakvTuaCsU9FU50/QDmdbHNy/4/JuRtMHqRU22o3q+W89YQndQEeCVwK+3qrA==" + "integrity": "sha512-dnMqspv5nU3LoewK2N/y7KLtxtakvTuaCsU9FU50/QDmdbHNy/4/JuRtMHqRU22o3q+W89YQndQEeCVwK+3qrA==", + "dev": true }, "is-core-module": { "version": "2.0.0", @@ -4512,7 +4524,8 @@ "is-date-object": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.2.tgz", - "integrity": "sha512-USlDT524woQ08aoZFzh3/Z6ch9Y/EWXEHQ/AaRN0SkKq4t2Jw2R2339tSXmwuVoY7LLlBCbOIlx2myP/L5zk0g==" + "integrity": "sha512-USlDT524woQ08aoZFzh3/Z6ch9Y/EWXEHQ/AaRN0SkKq4t2Jw2R2339tSXmwuVoY7LLlBCbOIlx2myP/L5zk0g==", + "dev": true }, "is-descriptor": { "version": "0.1.6", @@ -4552,9 +4565,9 @@ "dev": true }, "is-generator-function": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.0.8.tgz", - "integrity": "sha512-2Omr/twNtufVZFr1GhxjOMFPAj2sjc/dKaIqBhvo4qciXfJmITGH6ZGd8eZYNHza8t1y0e01AuqRhJwfWp26WQ==", + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.0.9.tgz", + "integrity": "sha512-ZJ34p1uvIfptHCN7sFTjGibB9/oBg17sHqzDLfuwhvmN/qLVvIQXRQ8licZQ35WJ8KuEQt/etnnzQFI9C9Ue/A==", "dev": true }, "is-glob": { @@ -4575,7 +4588,8 @@ "is-negative-zero": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.0.tgz", - "integrity": "sha1-lVOxIbD6wohp2p7UWeIMdUN4hGE=" + "integrity": "sha1-lVOxIbD6wohp2p7UWeIMdUN4hGE=", + "dev": true }, "is-number": { "version": "3.0.0", @@ -4597,6 +4611,12 @@ } } }, + "is-number-object": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.5.tgz", + "integrity": "sha512-RU0lI/n95pMoUKu9v1BZP5MBcZuNSVJkMkAG2dJqC4z2GlkGUNeH68SuHuBKBD/XFe+LHZ+f9BKkLET60Niedw==", + "dev": true + }, "is-path-cwd": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-2.2.0.tgz", @@ -4631,6 +4651,7 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.1.tgz", "integrity": "sha512-1+QkEcxiLlB7VEyFtyBg94e08OAsvq7FUBgApTq/w2ymCLyKJgDPsybBENVtA7XCQEgEXxKPonG+mvYRxh/LIg==", + "dev": true, "requires": { "has-symbols": "^1.0.1" } @@ -4660,55 +4681,90 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.3.tgz", "integrity": "sha512-OwijhaRSgqvhm/0ZdAcXNZt9lYdKFpcRDT5ULUuYXPoT794UNOdU+gpT6Rzo7b4V2HUl/op6GqY894AZwv9faQ==", + "dev": true, "requires": { "has-symbols": "^1.0.1" } }, "is-typed-array": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.4.tgz", - "integrity": "sha512-ILaRgn4zaSrVNXNGtON6iFNotXW3hAPF3+0fB1usg2jFlWqo5fEDdmJkz0zBfoi7Dgskr8Khi2xZ8cXqZEfXNA==", + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.5.tgz", + "integrity": "sha512-S+GRDgJlR3PyEbsX/Fobd9cqpZBuvUS+8asRqYDMLCb2qMzt1oz5m5oxQCxOgUDxiWsOVNi4yaF+/uvdlHlYug==", "dev": true, "requires": { "available-typed-arrays": "^1.0.2", - "call-bind": "^1.0.0", - "es-abstract": "^1.18.0-next.1", + "call-bind": "^1.0.2", + "es-abstract": "^1.18.0-next.2", "foreach": "^2.0.5", "has-symbols": "^1.0.1" }, "dependencies": { "es-abstract": { - "version": "1.18.0-next.2", - "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.2.tgz", - "integrity": "sha512-Ih4ZMFHEtZupnUh6497zEL4y2+w8+1ljnCyaTa+adcoafI1GOvMwFlDjBLfWR7y9VLfrjRJe9ocuHY1PSR9jjw==", + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0.tgz", + "integrity": "sha512-LJzK7MrQa8TS0ja2w3YNLzUgJCGPdPOV1yVvezjNnS89D+VR08+Szt2mz3YB2Dck/+w5tfIq/RoUAFqJJGM2yw==", "dev": true, "requires": { "call-bind": "^1.0.2", "es-to-primitive": "^1.2.1", "function-bind": "^1.1.1", - "get-intrinsic": "^1.0.2", + "get-intrinsic": "^1.1.1", "has": "^1.0.3", - "has-symbols": "^1.0.1", - "is-callable": "^1.2.2", + "has-symbols": "^1.0.2", + "is-callable": "^1.2.3", "is-negative-zero": "^2.0.1", - "is-regex": "^1.1.1", + "is-regex": "^1.1.2", + "is-string": "^1.0.5", "object-inspect": "^1.9.0", "object-keys": "^1.1.1", "object.assign": "^4.1.2", - "string.prototype.trimend": "^1.0.3", - "string.prototype.trimstart": "^1.0.3" + "string.prototype.trimend": "^1.0.4", + "string.prototype.trimstart": "^1.0.4", + "unbox-primitive": "^1.0.0" + }, + "dependencies": { + "has-symbols": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", + "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", + "dev": true + } } }, + "is-callable": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", + "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==", + "dev": true + }, "is-negative-zero": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz", "integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==", "dev": true }, + "is-regex": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.3.tgz", + "integrity": "sha512-qSVXFz28HM7y+IWX6vLCsexdlvzT1PJNFSBuaQLQ5o0IEw8UDYW6/2+eCMVyIsbM8CNLX2a/QWmSpyxYEHY7CQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "has-symbols": "^1.0.2" + }, + "dependencies": { + "has-symbols": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", + "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", + "dev": true + } + } + }, "object-inspect": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.9.0.tgz", - "integrity": "sha512-i3Bp9iTqwhaLZBxGkRfo5ZbE07BQRT7MGu8+nNgwW9ItGp1TzCTw2DLEoWwjClxBjOFI/hWljTAmYGCEwmtnOw==", + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.10.3.tgz", + "integrity": "sha512-e5mCJlSH7poANfC8z8S9s9S2IN5/4Zb3aZ33f5s8YqoazCFzNLloLU8r5VCG+G7WoqLvAAZoVMcy3tp/3X0Plw==", "dev": true }, "object.assign": { @@ -4724,22 +4780,22 @@ } }, "string.prototype.trimend": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.3.tgz", - "integrity": "sha512-ayH0pB+uf0U28CtjlLvL7NaohvR1amUvVZk+y3DYb0Ey2PUV5zPkkKy9+U1ndVEIXO8hNg18eIv9Jntbii+dKw==", + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz", + "integrity": "sha512-y9xCjw1P23Awk8EvTpcyL2NIr1j7wJ39f+k6lvRnSMz+mz9CGz9NYPelDk42kOz6+ql8xjfK8oYzy3jAP5QU5A==", "dev": true, "requires": { - "call-bind": "^1.0.0", + "call-bind": "^1.0.2", "define-properties": "^1.1.3" } }, "string.prototype.trimstart": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.3.tgz", - "integrity": "sha512-oBIBUy5lea5tt0ovtOFiEQaBkoBBkyJhZXzJYrSmDo5IUUqbOPvVezuRs/agBIdZ2p2Eo1FD6bD9USyBLfl3xg==", + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.4.tgz", + "integrity": "sha512-jh6e984OBfvxS50tdY2nRZnoC5/mLFKOREQfw8t5yytkoUsJRNxvI/E39qu1sD0OtWI3OC0XgKSmcWwziwYuZw==", "dev": true, "requires": { - "call-bind": "^1.0.0", + "call-bind": "^1.0.2", "define-properties": "^1.1.3" } } @@ -5237,9 +5293,9 @@ }, "dependencies": { "bn.js": { - "version": "4.11.9", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.9.tgz", - "integrity": "sha512-E6QoYqCKZfgatHTdHzs1RRKP7ip4vvm+EyRUeE2RF0NblwVvb0p6jSVeNTOFxPn26QXN2o6SMfNxKp6kU8zQaw==", + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", "dev": true } } @@ -5335,35 +5391,35 @@ "dev": true }, "mocha": { - "version": "8.2.1", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-8.2.1.tgz", - "integrity": "sha512-cuLBVfyFfFqbNR0uUKbDGXKGk+UDFe6aR4os78XIrMQpZl/nv7JYHcvP5MFIAb374b2zFXsdgEGwmzMtP0Xg8w==", + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-8.4.0.tgz", + "integrity": "sha512-hJaO0mwDXmZS4ghXsvPVriOhsxQ7ofcpQdm8dE+jISUOKopitvnXFQmpRR7jd2K6VBG6E26gU3IAbXXGIbu4sQ==", "dev": true, "requires": { "@ungap/promise-all-settled": "1.1.2", "ansi-colors": "4.1.1", "browser-stdout": "1.3.1", - "chokidar": "3.4.3", - "debug": "4.2.0", - "diff": "4.0.2", + "chokidar": "3.5.1", + "debug": "4.3.1", + "diff": "5.0.0", "escape-string-regexp": "4.0.0", "find-up": "5.0.0", "glob": "7.1.6", "growl": "1.10.5", "he": "1.2.0", - "js-yaml": "3.14.0", + "js-yaml": "4.0.0", "log-symbols": "4.0.0", "minimatch": "3.0.4", - "ms": "2.1.2", - "nanoid": "3.1.12", + "ms": "2.1.3", + "nanoid": "3.1.20", "serialize-javascript": "5.0.1", "strip-json-comments": "3.1.1", - "supports-color": "7.2.0", + "supports-color": "8.1.1", "which": "2.0.2", "wide-align": "1.1.3", - "workerpool": "6.0.2", - "yargs": "13.3.2", - "yargs-parser": "13.1.2", + "workerpool": "6.1.0", + "yargs": "16.2.0", + "yargs-parser": "20.2.4", "yargs-unparser": "2.0.0" }, "dependencies": { @@ -5373,31 +5429,22 @@ "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", "dev": true }, - "ansi-regex": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", - "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", - "dev": true - }, - "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "requires": { - "color-convert": "^1.9.0" - } - }, "anymatch": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.1.tgz", - "integrity": "sha512-mM8522psRCqzV+6LhomX5wgp25YVibjh8Wj23I5RPkPppSVSjyKD2A2mBJmWGa+KN7f2D6LNh9jkBCeyLktzjg==", + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz", + "integrity": "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==", "dev": true, "requires": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" } }, + "argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true + }, "binary-extensions": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", @@ -5413,21 +5460,15 @@ "fill-range": "^7.0.1" } }, - "camelcase": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", - "dev": true - }, "chokidar": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.4.3.tgz", - "integrity": "sha512-DtM3g7juCXQxFVSNPNByEC2+NImtBuxQQvWlHunpJIS5Ocr0lG306cC7FCi7cEA0fzmybPUIl4txBIobk1gGOQ==", + "version": "3.5.1", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.1.tgz", + "integrity": "sha512-9+s+Od+W0VJJzawDma/gvBNQqkTiqYTWLuZoyAsivsI4AaWTCzHG06/TMjsf1cYe9Cb97UCEhjz7HvnPk2p/tw==", "dev": true, "requires": { "anymatch": "~3.1.1", "braces": "~3.0.2", - "fsevents": "~2.1.2", + "fsevents": "~2.3.1", "glob-parent": "~5.1.0", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", @@ -5436,39 +5477,44 @@ } }, "cliui": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", - "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", + "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", "dev": true, "requires": { - "string-width": "^3.1.0", - "strip-ansi": "^5.2.0", - "wrap-ansi": "^5.1.0" + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^7.0.0" } }, - "color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "debug": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz", + "integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==", "dev": true, "requires": { - "color-name": "1.1.3" + "ms": "2.1.2" + }, + "dependencies": { + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + } } }, - "color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "diff": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-5.0.0.tgz", + "integrity": "sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w==", "dev": true }, - "debug": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.2.0.tgz", - "integrity": "sha512-IX2ncY78vDTjZMFUdmsvIRFY2Cf4FnD0wRs+nQwJU8Lu99/tPFdb0VybiiMTPe3I6rQmwsqQqRBvxU+bZ/I8sg==", - "dev": true, - "requires": { - "ms": "2.1.2" - } + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true }, "escape-string-regexp": { "version": "4.0.0", @@ -5496,9 +5542,9 @@ } }, "fsevents": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.1.3.tgz", - "integrity": "sha512-Auw9a4AxqWpa9GUfj370BMPzzyncfBABW8Mab7BGWBYDj4Isgq+cDKtx0i6u9jcX9pQDnswsaaOTgTmA5pEjuQ==", + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "dev": true, "optional": true }, @@ -5508,10 +5554,24 @@ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", "dev": true }, + "glob": { + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", + "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, "glob-parent": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.1.tgz", - "integrity": "sha512-FnI+VGOpnlGHWZxthPGR+QhR78fuiK0sNLkHQv+bL9fQi57lNNdquIbna/WrfROrolq8GK5Ek6BiMwqL/voRYQ==", + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "dev": true, "requires": { "is-glob": "^4.0.1" @@ -5526,12 +5586,27 @@ "binary-extensions": "^2.0.0" } }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, "is-number": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "dev": true }, + "js-yaml": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.0.0.tgz", + "integrity": "sha512-pqon0s+4ScYUvX30wxQi3PogGFAlUyH0awepWvwkj4jD4v+ova3RiYw8bmA6x2rDrEaj8i/oWKoRxpVNW+Re8Q==", + "dev": true, + "requires": { + "argparse": "^2.0.1" + } + }, "locate-path": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", @@ -5541,12 +5616,6 @@ "p-locate": "^5.0.0" } }, - "ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true - }, "p-limit": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", @@ -5565,12 +5634,6 @@ "p-limit": "^3.0.2" } }, - "p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "dev": true - }, "path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -5586,19 +5649,24 @@ "picomatch": "^2.2.1" } }, - "require-main-filename": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", - "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", - "dev": true + "string-width": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.2.tgz", + "integrity": "sha512-XBJbT3N4JhVumXE0eoLU9DCjcaF92KLNqTmFCnG1pf8duUxFGwtP6AD6nkjw9a3IdiRtL3E2w3JDiE/xi3vOeA==", + "dev": true, + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.0" + } }, - "strip-ansi": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", "dev": true, "requires": { - "ansi-regex": "^4.1.0" + "has-flag": "^4.0.0" } }, "to-regex-range": { @@ -5619,101 +5687,43 @@ "isexe": "^2.0.0" } }, - "which-module": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", - "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", - "dev": true - }, "wrap-ansi": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", - "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", "dev": true, "requires": { - "ansi-styles": "^3.2.0", - "string-width": "^3.0.0", - "strip-ansi": "^5.0.0" + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" } }, "y18n": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.1.tgz", - "integrity": "sha512-wNcy4NvjMYL8gogWWYAO7ZFWFfHcbdbE57tZO8e4cbpj8tfUcwrwqSl3ad8HxpYWCdXcJUCeKKZS62Av1affwQ==", + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", "dev": true }, "yargs": { - "version": "13.3.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.3.2.tgz", - "integrity": "sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw==", + "version": "16.2.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", + "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", "dev": true, "requires": { - "cliui": "^5.0.0", - "find-up": "^3.0.0", - "get-caller-file": "^2.0.1", + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", - "require-main-filename": "^2.0.0", - "set-blocking": "^2.0.0", - "string-width": "^3.0.0", - "which-module": "^2.0.0", - "y18n": "^4.0.0", - "yargs-parser": "^13.1.2" - }, - "dependencies": { - "find-up": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", - "dev": true, - "requires": { - "locate-path": "^3.0.0" - } - }, - "locate-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", - "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", - "dev": true, - "requires": { - "p-locate": "^3.0.0", - "path-exists": "^3.0.0" - } - }, - "p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, - "requires": { - "p-try": "^2.0.0" - } - }, - "p-locate": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", - "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", - "dev": true, - "requires": { - "p-limit": "^2.0.0" - } - }, - "path-exists": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", - "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", - "dev": true - } + "string-width": "^4.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^20.2.2" } }, "yargs-parser": { - "version": "13.1.2", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.2.tgz", - "integrity": "sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg==", - "dev": true, - "requires": { - "camelcase": "^5.0.0", - "decamelize": "^1.2.0" - } + "version": "20.2.4", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.4.tgz", + "integrity": "sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA==", + "dev": true } } }, @@ -5756,21 +5766,21 @@ } }, "is-core-module": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.2.0.tgz", - "integrity": "sha512-XRAfAdyyY5F5cOXn7hYQDqh2Xmii+DEfIcQGxK/uNwMHhIkPWO0g8msXcbzLe+MpGoR951MlqM/2iIlU4vKDdQ==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.3.0.tgz", + "integrity": "sha512-xSphU2KG9867tsYdLD4RWQ1VqdFl4HTO9Thf3I/3dLEfr0dbPTWKsuCKrgqMljg4nPE+Gq0VCnzT3gr0CyBmsw==", "dev": true, "requires": { "has": "^1.0.3" } }, "resolve": { - "version": "1.19.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.19.0.tgz", - "integrity": "sha512-rArEXAgsBG4UgRGcynxWIWKFvh/XZCcS8UJdHhwy91zwAvCZIbcs+vAbflgBnNjYMs/i/i+/Ux6IZhML1yPvxg==", + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz", + "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", "dev": true, "requires": { - "is-core-module": "^2.1.0", + "is-core-module": "^2.2.0", "path-parse": "^1.0.6" } }, @@ -5806,9 +5816,9 @@ "optional": true }, "nanoid": { - "version": "3.1.12", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.1.12.tgz", - "integrity": "sha512-1qstj9z5+x491jfiC4Nelk+f8XBad7LN20PmyWINJEMRSf3wcAjAWysw1qaA8z6NSKe2sjq1hRSDpBH5paCb6A==", + "version": "3.1.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.1.20.tgz", + "integrity": "sha512-a1cQNyczgKbLX9jwbS/+d7W8fX/RfgYR7lVWwWOGIPNgK2m0MWvrGF6/m4kk6U3QcFMnZf3RIhL0v2Jgh/0Uxw==", "dev": true }, "nanomatch": { @@ -5968,12 +5978,14 @@ "object-inspect": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.8.0.tgz", - "integrity": "sha512-jLdtEOB112fORuypAyl/50VRVIBIdVQOSUUGQHzJ4xBSbit81zRarz7GThkEFZy1RceYrWYcPcBFPQwHyAc1gA==" + "integrity": "sha512-jLdtEOB112fORuypAyl/50VRVIBIdVQOSUUGQHzJ4xBSbit81zRarz7GThkEFZy1RceYrWYcPcBFPQwHyAc1gA==", + "dev": true }, "object-keys": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", - "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==" + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true }, "object-visit": { "version": "1.0.1", @@ -6292,9 +6304,9 @@ "dev": true }, "pbkdf2": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.1.1.tgz", - "integrity": "sha512-4Ejy1OPxi9f2tt1rRV7Go7zmfDQ+ZectEQz3VGUQhgq62HtIRPDyG/JtnwIxs6x3uNMwo2V7q1fMvKjb+Tnpqg==", + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.1.2.tgz", + "integrity": "sha512-iuh7L6jA7JEGu2WxDwtQP1ddOpaJNC4KlDEFfdQajSGgGPNi4OyDc2R7QnbY2bR9QjBVGwgvTdNJZoE7RaxUMA==", "dev": true, "requires": { "create-hash": "^1.1.2", @@ -6502,9 +6514,9 @@ }, "dependencies": { "bn.js": { - "version": "4.11.9", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.9.tgz", - "integrity": "sha512-E6QoYqCKZfgatHTdHzs1RRKP7ip4vvm+EyRUeE2RF0NblwVvb0p6jSVeNTOFxPn26QXN2o6SMfNxKp6kU8zQaw==", + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", "dev": true } } @@ -7422,9 +7434,9 @@ "dev": true }, "stream-http": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/stream-http/-/stream-http-3.1.1.tgz", - "integrity": "sha512-S7OqaYu0EkFpgeGFb/NPOoPLxFko7TPqtEeFg5DXPB4v/KETHG0Ln6fRFrNezoelpaDKmycEmmZ81cC9DAwgYg==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/stream-http/-/stream-http-3.2.0.tgz", + "integrity": "sha512-Oq1bLqisTyK3TSCXpPbT4sdeYNdmyZJv1LxpEm2vu1ZhK89kSE5YXwZc3cWk0MagGaKriBh9mCFbVGtO+vY29A==", "dev": true, "requires": { "builtin-status-codes": "^3.0.0", @@ -7529,6 +7541,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.2.tgz", "integrity": "sha512-8oAG/hi14Z4nOVP0z6mdiVZ/wqjDtWSLygMigTzAb+7aPEDTleeFf+WrF+alzecxIRkckkJVn+dTlwzJXORATw==", + "dev": true, "requires": { "define-properties": "^1.1.3", "es-abstract": "^1.18.0-next.1" @@ -7538,6 +7551,7 @@ "version": "1.18.0-next.1", "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.1.tgz", "integrity": "sha512-I4UGspA0wpZXWENrdA0uHbnhte683t3qT/1VFH9aX2dA5PPSf6QW5HHXf5HImaqPmjXaVeVk4RGWnaylmV7uAA==", + "dev": true, "requires": { "es-to-primitive": "^1.2.1", "function-bind": "^1.1.1", @@ -7557,6 +7571,7 @@ "version": "4.1.1", "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.1.tgz", "integrity": "sha512-VT/cxmx5yaoHSOTSyrCygIDFco+RsibY2NM0a4RdEeY/4KgqezwFtK1yr3U67xYhqJSlASm2pKhLVzPj2lr4bA==", + "dev": true, "requires": { "define-properties": "^1.1.3", "es-abstract": "^1.18.0-next.0", @@ -7570,6 +7585,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.2.tgz", "integrity": "sha512-7F6CdBTl5zyu30BJFdzSTlSlLPwODC23Od+iLoVH8X6+3fvDPPuBVVj9iaB1GOsSTSIgVfsfm27R2FGrAPznWg==", + "dev": true, "requires": { "define-properties": "^1.1.3", "es-abstract": "^1.18.0-next.1" @@ -7579,6 +7595,7 @@ "version": "1.18.0-next.1", "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.1.tgz", "integrity": "sha512-I4UGspA0wpZXWENrdA0uHbnhte683t3qT/1VFH9aX2dA5PPSf6QW5HHXf5HImaqPmjXaVeVk4RGWnaylmV7uAA==", + "dev": true, "requires": { "es-to-primitive": "^1.2.1", "function-bind": "^1.1.1", @@ -7598,6 +7615,7 @@ "version": "4.1.1", "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.1.tgz", "integrity": "sha512-VT/cxmx5yaoHSOTSyrCygIDFco+RsibY2NM0a4RdEeY/4KgqezwFtK1yr3U67xYhqJSlASm2pKhLVzPj2lr4bA==", + "dev": true, "requires": { "define-properties": "^1.1.3", "es-abstract": "^1.18.0-next.0", @@ -7936,15 +7954,15 @@ "dev": true }, "typescript": { - "version": "4.0.0-dev.20200803", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.0.0-dev.20200803.tgz", - "integrity": "sha512-f/jDkFqCs0gbUd5MCUijO9u3AOMx1x1HdRDDHSidlc6uPVEkRduxjeTFhIXbGutO7ivzv+aC2sxH+1FQwsyBcg==", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.2.3.tgz", + "integrity": "sha512-qOcYwxaByStAWrBf4x0fibwZvMRG+r4cQoTjbPtUlrWjBHbmCAww1i448U0GJ+3cNNEtebDteo/cHOR3xJ4wEw==", "dev": true }, "uglify-js": { - "version": "3.12.7", - "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.12.7.tgz", - "integrity": "sha512-SIZhkoh+U/wjW+BHGhVwE9nt8tWJspncloBcFapkpGRwNPqcH8pzX36BXe3TPBjzHWPMUZotpCigak/udWNr1Q==", + "version": "3.13.5", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.13.5.tgz", + "integrity": "sha512-xtB8yEqIkn7zmOyS2zUNBsYCBRhDkvlNxMMY2smuJ/qA8NCHeQvKCF3i9Z4k8FJH4+PJvZRtMrPynfZ75+CSZw==", "dev": true, "optional": true }, @@ -7954,6 +7972,26 @@ "integrity": "sha512-4IcGSufhFshvLNcMCV80UnQVlZ5pMOC8mvNPForqwA4+lzYQuetTESLDQkeLmihq8bRcnpbQa48Wb8Lh16/xow==", "dev": true }, + "unbox-primitive": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.1.tgz", + "integrity": "sha512-tZU/3NqK3dA5gpE1KtyiJUrEB0lxnGkMFHptJ7q6ewdZ8s12QrODwNbhIJStmJkd1QDXa1NRA8aF2A1zk/Ypyw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1", + "has-bigints": "^1.0.1", + "has-symbols": "^1.0.2", + "which-boxed-primitive": "^1.0.2" + }, + "dependencies": { + "has-symbols": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", + "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", + "dev": true + } + } + }, "unc-path-regex": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/unc-path-regex/-/unc-path-regex-0.1.2.tgz", @@ -8290,6 +8328,19 @@ "isexe": "^2.0.0" } }, + "which-boxed-primitive": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", + "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", + "dev": true, + "requires": { + "is-bigint": "^1.0.1", + "is-boolean-object": "^1.1.0", + "is-number-object": "^1.0.4", + "is-string": "^1.0.5", + "is-symbol": "^1.0.3" + } + }, "which-module": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/which-module/-/which-module-1.0.0.tgz", @@ -8312,37 +8363,71 @@ }, "dependencies": { "es-abstract": { - "version": "1.18.0-next.2", - "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0-next.2.tgz", - "integrity": "sha512-Ih4ZMFHEtZupnUh6497zEL4y2+w8+1ljnCyaTa+adcoafI1GOvMwFlDjBLfWR7y9VLfrjRJe9ocuHY1PSR9jjw==", + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0.tgz", + "integrity": "sha512-LJzK7MrQa8TS0ja2w3YNLzUgJCGPdPOV1yVvezjNnS89D+VR08+Szt2mz3YB2Dck/+w5tfIq/RoUAFqJJGM2yw==", "dev": true, "requires": { "call-bind": "^1.0.2", "es-to-primitive": "^1.2.1", "function-bind": "^1.1.1", - "get-intrinsic": "^1.0.2", + "get-intrinsic": "^1.1.1", "has": "^1.0.3", - "has-symbols": "^1.0.1", - "is-callable": "^1.2.2", + "has-symbols": "^1.0.2", + "is-callable": "^1.2.3", "is-negative-zero": "^2.0.1", - "is-regex": "^1.1.1", + "is-regex": "^1.1.2", + "is-string": "^1.0.5", "object-inspect": "^1.9.0", "object-keys": "^1.1.1", "object.assign": "^4.1.2", - "string.prototype.trimend": "^1.0.3", - "string.prototype.trimstart": "^1.0.3" + "string.prototype.trimend": "^1.0.4", + "string.prototype.trimstart": "^1.0.4", + "unbox-primitive": "^1.0.0" + }, + "dependencies": { + "has-symbols": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", + "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", + "dev": true + } } }, + "is-callable": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz", + "integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==", + "dev": true + }, "is-negative-zero": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz", "integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==", "dev": true }, + "is-regex": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.3.tgz", + "integrity": "sha512-qSVXFz28HM7y+IWX6vLCsexdlvzT1PJNFSBuaQLQ5o0IEw8UDYW6/2+eCMVyIsbM8CNLX2a/QWmSpyxYEHY7CQ==", + "dev": true, + "requires": { + "call-bind": "^1.0.2", + "has-symbols": "^1.0.2" + }, + "dependencies": { + "has-symbols": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", + "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", + "dev": true + } + } + }, "object-inspect": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.9.0.tgz", - "integrity": "sha512-i3Bp9iTqwhaLZBxGkRfo5ZbE07BQRT7MGu8+nNgwW9ItGp1TzCTw2DLEoWwjClxBjOFI/hWljTAmYGCEwmtnOw==", + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.10.3.tgz", + "integrity": "sha512-e5mCJlSH7poANfC8z8S9s9S2IN5/4Zb3aZ33f5s8YqoazCFzNLloLU8r5VCG+G7WoqLvAAZoVMcy3tp/3X0Plw==", "dev": true }, "object.assign": { @@ -8358,22 +8443,22 @@ } }, "string.prototype.trimend": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.3.tgz", - "integrity": "sha512-ayH0pB+uf0U28CtjlLvL7NaohvR1amUvVZk+y3DYb0Ey2PUV5zPkkKy9+U1ndVEIXO8hNg18eIv9Jntbii+dKw==", + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz", + "integrity": "sha512-y9xCjw1P23Awk8EvTpcyL2NIr1j7wJ39f+k6lvRnSMz+mz9CGz9NYPelDk42kOz6+ql8xjfK8oYzy3jAP5QU5A==", "dev": true, "requires": { - "call-bind": "^1.0.0", + "call-bind": "^1.0.2", "define-properties": "^1.1.3" } }, "string.prototype.trimstart": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.3.tgz", - "integrity": "sha512-oBIBUy5lea5tt0ovtOFiEQaBkoBBkyJhZXzJYrSmDo5IUUqbOPvVezuRs/agBIdZ2p2Eo1FD6bD9USyBLfl3xg==", + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.4.tgz", + "integrity": "sha512-jh6e984OBfvxS50tdY2nRZnoC5/mLFKOREQfw8t5yytkoUsJRNxvI/E39qu1sD0OtWI3OC0XgKSmcWwziwYuZw==", "dev": true, "requires": { - "call-bind": "^1.0.0", + "call-bind": "^1.0.2", "define-properties": "^1.1.3" } } @@ -8428,9 +8513,9 @@ "dev": true }, "workerpool": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.0.2.tgz", - "integrity": "sha512-DSNyvOpFKrNusaaUwk+ej6cBj1bmhLcBfj80elGk+ZIo5JSkq+unB1dLKEOcNfJDZgjGICfhQ0Q5TbP0PvF4+Q==", + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.1.0.tgz", + "integrity": "sha512-toV7q9rWNYha963Pl/qyeZ6wG+3nnsyvolaNUS8+R5Wtw6qJPTxIlOP1ZSvcGhEJw+l3HMMmtiNo9Gl61G4GVg==", "dev": true }, "wrap-ansi": { diff --git a/package.json b/package.json index 2bb9af1f4ba17..2f3518663a299 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "typescript", "author": "Microsoft Corp.", "homepage": "https://www.typescriptlang.org/", - "version": "4.2.0", + "version": "4.3.2", "license": "Apache-2.0", "description": "TypeScript is a language for application scale JavaScript development", "keywords": [ @@ -53,9 +53,9 @@ "@types/source-map-support": "latest", "@types/through2": "latest", "@types/xml2js": "^0.4.0", - "@typescript-eslint/eslint-plugin": "4.5.0", - "@typescript-eslint/experimental-utils": "4.5.0", - "@typescript-eslint/parser": "4.5.0", + "@typescript-eslint/eslint-plugin": "^4.19.0", + "@typescript-eslint/experimental-utils": "^4.19.0", + "@typescript-eslint/parser": "^4.19.0", "async": "latest", "azure-devops-node-api": "^10.1.0", "browser-resolve": "^1.11.2", @@ -94,7 +94,7 @@ "remove-internal": "^2.9.2", "source-map-support": "latest", "through2": "latest", - "typescript": "^4.0.0-dev.20200624", + "typescript": "^4.2.3", "vinyl": "latest", "vinyl-sourcemaps-apply": "latest", "xml2js": "^0.4.19" @@ -127,5 +127,7 @@ "source-map-support": false, "inspector": false }, - "dependencies": {} + "volta": { + "node": "14.15.5" + } } diff --git a/scripts/build/options.js b/scripts/build/options.js index a5c1413e7d1a4..5d4aad6f5fc8f 100644 --- a/scripts/build/options.js +++ b/scripts/build/options.js @@ -4,12 +4,11 @@ const os = require("os"); /** @type {CommandLineOptions} */ module.exports = minimist(process.argv.slice(2), { - boolean: ["debug", "dirty", "light", "colors", "lint", "lkg", "soft", "fix", "failed", "keepFailed", "force", "built"], - string: ["browser", "tests", "inspect", "host", "reporter", "stackTraceLimit", "timeout", "shards", "shardId"], + boolean: ["dirty", "light", "colors", "lint", "lkg", "soft", "fix", "failed", "keepFailed", "force", "built"], + string: ["browser", "tests", "break", "host", "reporter", "stackTraceLimit", "timeout", "shards", "shardId"], alias: { "b": "browser", - "d": ["debug", "debug-brk"], - "i": ["inspect", "inspect-brk"], + "i": ["inspect", "inspect-brk", "break", "debug", "debug-brk"], "t": ["tests", "test"], "ru": ["runners", "runner"], "r": "reporter", @@ -47,7 +46,6 @@ if (module.exports.built) { /** * @typedef TypedOptions - * @property {boolean} debug * @property {boolean} dirty * @property {boolean} light * @property {boolean} colors @@ -58,7 +56,7 @@ if (module.exports.built) { * @property {boolean} fix * @property {string} browser * @property {string} tests - * @property {string} inspect + * @property {string | boolean} inspect * @property {string} runners * @property {string|number} workers * @property {string} host diff --git a/scripts/build/tests.js b/scripts/build/tests.js index 5a6297768ee57..7fee32566dd79 100644 --- a/scripts/build/tests.js +++ b/scripts/build/tests.js @@ -27,8 +27,7 @@ exports.localTest262Baseline = "internal/baselines/test262/local"; async function runConsoleTests(runJs, defaultReporter, runInParallel, watchMode, cancelToken = CancellationToken.none) { let testTimeout = cmdLineOptions.timeout; let tests = cmdLineOptions.tests; - const debug = cmdLineOptions.debug; - const inspect = cmdLineOptions.inspect; + const inspect = cmdLineOptions.break || cmdLineOptions.inspect; const runners = cmdLineOptions.runners; const light = cmdLineOptions.light; const stackTraceLimit = cmdLineOptions.stackTraceLimit; @@ -101,11 +100,7 @@ async function runConsoleTests(runJs, defaultReporter, runInParallel, watchMode, args.push("--no-colors"); } if (inspect !== undefined) { - args.unshift(inspect == "" ? "--inspect-brk" : "--inspect-brk="+inspect); - args.push("-t", "0"); - } - else if (debug) { - args.unshift("--debug-brk"); + args.unshift((inspect == "" || inspect === true) ? "--inspect-brk" : "--inspect-brk="+inspect); args.push("-t", "0"); } else { diff --git a/scripts/perf-result-post.js b/scripts/perf-result-post.js index 79d90d40c5aab..337729128d261 100644 --- a/scripts/perf-result-post.js +++ b/scripts/perf-result-post.js @@ -3,45 +3,86 @@ // Must reference esnext.asynciterable lib, since octokit uses AsyncIterable internally const { Octokit } = require("@octokit/rest"); const fs = require("fs"); +const ado = require("azure-devops-node-api"); +const { default: fetch } = require("node-fetch"); -const requester = process.env.requesting_user; -const source = process.env.source_issue; -const postedComment = process.env.status_comment; -console.log(`Loading fragment from ${process.argv[3]}...`); -const outputTableText = fs.readFileSync(process.argv[3], { encoding: "utf8" }); -console.log(`Fragment contents: -${outputTableText}`); -const gh = new Octokit({ - auth: process.argv[2] -}); -gh.issues.createComment({ - issue_number: +source, - owner: "Microsoft", - repo: "TypeScript", - body: `@${requester} -The results of the perf run you requested are in! -
Here they are:

-${outputTableText} -

` -}).then(async data => { - console.log(`Results posted!`); - const newCommentUrl = data.data.html_url; - const comment = await gh.issues.getComment({ - owner: "Microsoft", - repo: "TypeScript", - comment_id: +postedComment - }); - const newBody = `${comment.data.body} - -Update: [The results are in!](${newCommentUrl})`; - return await gh.issues.updateComment({ - owner: "Microsoft", - repo: "TypeScript", - comment_id: +postedComment, - body: newBody - }); -}).catch(e => { +async function main() { + const source = process.env.SOURCE_ISSUE; + if (!source) throw new Error("SOURCE_ISSUE environment variable not set."); + + const requester = process.env.REQUESTING_USER; + if (!requester) throw new Error("REQUESTING_USER environment variable not set."); + + const buildId = process.env.BUILD_BUILDID; + if (!requester) throw new Error("BUILD_BUILDID environment variable not set."); + + const postedComment = process.env.STATUS_COMMENT; + if (!postedComment) throw new Error("STATUS_COMMENT environment variable not set."); + + const [auth, fragment, includeArtifact] = process.argv.slice(2); + if (!auth) throw new Error("First argument must be a GitHub auth token."); + if (!fragment) throw new Error("Second argument must be a path to an HTML fragment."); + + const gh = new Octokit({ auth }); + try { + console.log(`Loading fragment from ${fragment}...`); + const outputTableText = fs.readFileSync(fragment, { encoding: "utf8" }); + console.log(`Fragment contents:\n${outputTableText}`); + + let benchmarkText = ""; + if (includeArtifact === "--include-artifact") { + // post a link to the benchmark file + const cli = new ado.WebApi("https://typescript.visualstudio.com/defaultcollection", ado.getHandlerFromToken("")); // Empty token, anon auth + const build = await cli.getBuildApi(); + const artifact = await build.getArtifact("typescript", +buildId, "benchmark"); + const updatedUrl = new URL(artifact.resource.url); + updatedUrl.search = `artifactName=benchmark&fileId=${artifact.resource.data}&fileName=manifest`; + const resp = await (await fetch(`${updatedUrl}`)).json(); + for (const file of resp.items) { + if (/[\\/]linux\.benchmark$/.test(file.path)) { + const benchmarkUrl = new URL(artifact.resource.url); + benchmarkUrl.search = `artifactName=benchmark&fileId=${file.blob.id}&fileName=linux.benchmark`; + benchmarkText = `\n
Developer Information:

Download Benchmark

\n`; + break; + } + } + } + + const data = await gh.issues.createComment({ + issue_number: +source, + owner: "Microsoft", + repo: "TypeScript", + body: `@${requester}\nThe results of the perf run you requested are in!\n
Here they are:

\n${outputTableText}\n

${benchmarkText}
` + }); + + console.log(`Results posted!`); + const newCommentUrl = data.data.html_url; + const comment = await gh.issues.getComment({ + owner: "Microsoft", + repo: "TypeScript", + comment_id: +postedComment + }); + const newBody = `${comment.data.body}\n\nUpdate: [The results are in!](${newCommentUrl})`; + await gh.issues.updateComment({ + owner: "Microsoft", + repo: "TypeScript", + comment_id: +postedComment, + body: newBody + }); + } + catch (e) { + const gh = new Octokit({ auth }); + await gh.issues.createComment({ + issue_number: +source, + owner: "Microsoft", + repo: "TypeScript", + body: `Hey @${requester}, something went wrong when publishing results. ([You can check the log here](https://typescript.visualstudio.com/TypeScript/_build/index?buildId=${buildId}&_a=summary)).` + }); + } +} + +main().catch(e => { console.error(e); process.exit(1); }); diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index bea34807d868f..4e850f4eea9ea 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -227,6 +227,7 @@ namespace ts { const unreachableFlow: FlowNode = { flags: FlowFlags.Unreachable }; const reportedUnreachableFlow: FlowNode = { flags: FlowFlags.Unreachable }; + const bindBinaryExpressionFlow = createBindBinaryExpressionFlow(); /** * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) @@ -344,12 +345,9 @@ namespace ts { if (isSignedNumericLiteral(nameExpression)) { return tokenToString(nameExpression.operator) + nameExpression.operand.text as __String; } - - Debug.assert(isWellKnownSymbolSyntactically(nameExpression)); - return getPropertyNameForKnownSymbolName(idText((nameExpression).name)); - } - if (isWellKnownSymbolSyntactically(name)) { - return getPropertyNameForKnownSymbolName(idText(name.name)); + else { + Debug.fail("Only computed properties with literal names have declaration names"); + } } if (isPrivateIdentifier(name)) { // containingClass exists because private names only allowed inside classes @@ -685,6 +683,7 @@ namespace ts { } if (node.kind === SyntaxKind.SourceFile) { node.flags |= emitFlags; + (node as SourceFile).endFlowNode = currentFlow; } if (currentReturnTarget) { @@ -885,11 +884,11 @@ namespace ts { } function isNarrowableReference(expr: Expression): boolean { - return expr.kind === SyntaxKind.Identifier || expr.kind === SyntaxKind.PrivateIdentifier || expr.kind === SyntaxKind.ThisKeyword || expr.kind === SyntaxKind.SuperKeyword || - (isPropertyAccessExpression(expr) || isNonNullExpression(expr) || isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - isBinaryExpression(expr) && expr.operatorToken.kind === SyntaxKind.CommaToken && isNarrowableReference(expr.right) || - isElementAccessExpression(expr) && isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || - isAssignmentExpression(expr) && isNarrowableReference(expr.left); + return isDottedName(expr) + || (isPropertyAccessExpression(expr) || isNonNullExpression(expr) || isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) + || isBinaryExpression(expr) && expr.operatorToken.kind === SyntaxKind.CommaToken && isNarrowableReference(expr.right) + || isElementAccessExpression(expr) && isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) + || isAssignmentExpression(expr) && isNarrowableReference(expr.left); } function containsNarrowableReference(expr: Expression): boolean { @@ -1372,7 +1371,7 @@ namespace ts { // is potentially an assertion and is therefore included in the control flow. if (node.kind === SyntaxKind.CallExpression) { const call = node; - if (isDottedName(call.expression) && call.expression.kind !== SyntaxKind.SuperKeyword) { + if (call.expression.kind !== SyntaxKind.SuperKeyword && isDottedName(call.expression)) { currentFlow = createFlowCall(currentFlow, call); } } @@ -1500,132 +1499,110 @@ namespace ts { bindAssignmentTargetFlow(node.left); } - const enum BindBinaryExpressionFlowState { - BindThenBindChildren, - MaybeBindLeft, - BindToken, - BindRight, - FinishBind - } - - function bindBinaryExpressionFlow(node: BinaryExpression) { - const workStacks: { - expr: BinaryExpression[], - state: BindBinaryExpressionFlowState[], - inStrictMode: (boolean | undefined)[], - parent: (Node | undefined)[], - } = { - expr: [node], - state: [BindBinaryExpressionFlowState.MaybeBindLeft], - inStrictMode: [undefined], - parent: [undefined], - }; - let stackIndex = 0; - while (stackIndex >= 0) { - node = workStacks.expr[stackIndex]; - switch (workStacks.state[stackIndex]) { - case BindBinaryExpressionFlowState.BindThenBindChildren: { - // This state is used only when recuring, to emulate the work that `bind` does before - // reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work. - setParent(node, parent); - const saveInStrictMode = inStrictMode; - bindWorker(node); - const saveParent = parent; - parent = node; - - advanceState(BindBinaryExpressionFlowState.MaybeBindLeft, saveInStrictMode, saveParent); - break; - } - case BindBinaryExpressionFlowState.MaybeBindLeft: { - const operator = node.operatorToken.kind; - // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions - // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too - // For now, though, since the common cases are chained `+`, leaving it recursive is fine - if (operator === SyntaxKind.AmpersandAmpersandToken || operator === SyntaxKind.BarBarToken || operator === SyntaxKind.QuestionQuestionToken || - isLogicalOrCoalescingAssignmentOperator(operator)) { - if (isTopLevelLogicalExpression(node)) { - const postExpressionLabel = createBranchLabel(); - bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel); - currentFlow = finishFlowLabel(postExpressionLabel); - } - else { - bindLogicalLikeExpression(node, currentTrueTarget!, currentFalseTarget!); - } - completeNode(); - } - else { - advanceState(BindBinaryExpressionFlowState.BindToken); - maybeBind(node.left); - } - break; - } - case BindBinaryExpressionFlowState.BindToken: { - if (node.operatorToken.kind === SyntaxKind.CommaToken) { - maybeBindExpressionFlowIfCall(node.left); - } - advanceState(BindBinaryExpressionFlowState.BindRight); - maybeBind(node.operatorToken); - break; - } - case BindBinaryExpressionFlowState.BindRight: { - advanceState(BindBinaryExpressionFlowState.FinishBind); - maybeBind(node.right); - break; + function createBindBinaryExpressionFlow() { + interface WorkArea { + stackIndex: number; + skip: boolean; + inStrictModeStack: (boolean | undefined)[]; + parentStack: (Node | undefined)[]; + } + + return createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined); + + function onEnter(node: BinaryExpression, state: WorkArea | undefined) { + if (state) { + state.stackIndex++; + // Emulate the work that `bind` does before reaching `bindChildren`. A normal call to + // `bindBinaryExpressionFlow` will already have done this work. + setParent(node, parent); + const saveInStrictMode = inStrictMode; + bindWorker(node); + const saveParent = parent; + parent = node; + state.skip = false; + state.inStrictModeStack[state.stackIndex] = saveInStrictMode; + state.parentStack[state.stackIndex] = saveParent; + } + else { + state = { + stackIndex: 0, + skip: false, + inStrictModeStack: [undefined], + parentStack: [undefined] + }; + } + // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions + // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too + // For now, though, since the common cases are chained `+`, leaving it recursive is fine + const operator = node.operatorToken.kind; + if (operator === SyntaxKind.AmpersandAmpersandToken || + operator === SyntaxKind.BarBarToken || + operator === SyntaxKind.QuestionQuestionToken || + isLogicalOrCoalescingAssignmentOperator(operator)) { + if (isTopLevelLogicalExpression(node)) { + const postExpressionLabel = createBranchLabel(); + bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); } - case BindBinaryExpressionFlowState.FinishBind: { - const operator = node.operatorToken.kind; - if (isAssignmentOperator(operator) && !isAssignmentTarget(node)) { - bindAssignmentTargetFlow(node.left); - if (operator === SyntaxKind.EqualsToken && node.left.kind === SyntaxKind.ElementAccessExpression) { - const elementAccess = node.left; - if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowMutation(FlowFlags.ArrayMutation, currentFlow, node); - } - } - } - completeNode(); - break; + else { + bindLogicalLikeExpression(node, currentTrueTarget!, currentFalseTarget!); } - default: return Debug.fail(`Invalid state ${workStacks.state[stackIndex]} for bindBinaryExpressionFlow`); + state.skip = true; } + return state; } - /** - * Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new - * head state; so `advanceState` must be called before any `maybeBind` during a state's execution. - */ - function advanceState(state: BindBinaryExpressionFlowState, isInStrictMode?: boolean, parent?: Node) { - workStacks.state[stackIndex] = state; - if (isInStrictMode !== undefined) { - workStacks.inStrictMode[stackIndex] = isInStrictMode; + function onLeft(left: Expression, state: WorkArea, _node: BinaryExpression) { + if (!state.skip) { + return maybeBind(left); } - if (parent !== undefined) { - workStacks.parent[stackIndex] = parent; + } + + function onOperator(operatorToken: BinaryOperatorToken, state: WorkArea, node: BinaryExpression) { + if (!state.skip) { + if (operatorToken.kind === SyntaxKind.CommaToken) { + maybeBindExpressionFlowIfCall(node.left); + } + bind(operatorToken); } } - function completeNode() { - if (workStacks.inStrictMode[stackIndex] !== undefined) { - inStrictMode = workStacks.inStrictMode[stackIndex]!; - parent = workStacks.parent[stackIndex]!; + function onRight(right: Expression, state: WorkArea, _node: BinaryExpression) { + if (!state.skip) { + return maybeBind(right); } - stackIndex--; } - /** - * If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it - */ + function onExit(node: BinaryExpression, state: WorkArea) { + if (!state.skip) { + const operator = node.operatorToken.kind; + if (isAssignmentOperator(operator) && !isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === SyntaxKind.EqualsToken && node.left.kind === SyntaxKind.ElementAccessExpression) { + const elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowMutation(FlowFlags.ArrayMutation, currentFlow, node); + } + } + } + } + const savedInStrictMode = state.inStrictModeStack[state.stackIndex]; + const savedParent = state.parentStack[state.stackIndex]; + if (savedInStrictMode !== undefined) { + inStrictMode = savedInStrictMode; + } + if (savedParent !== undefined) { + parent = savedParent; + } + state.skip = false; + state.stackIndex--; + } + function maybeBind(node: Node) { if (node && isBinaryExpression(node) && !isDestructuringAssignment(node)) { - stackIndex++; - workStacks.expr[stackIndex] = node; - workStacks.state[stackIndex] = BindBinaryExpressionFlowState.BindThenBindChildren; - workStacks.inStrictMode[stackIndex] = undefined; - workStacks.parent[stackIndex] = undefined; - } - else { - bind(node); + return node; } + bind(node); } } @@ -2146,9 +2123,9 @@ namespace ts { const saveParent = parent; const saveCurrentFlow = currentFlow; for (const typeAlias of delayedTypeAliases) { - const host = getJSDocHost(typeAlias); - container = (host && findAncestor(host.parent, n => !!(getContainerFlags(n) & ContainerFlags.IsContainer))) || file; - blockScopeContainer = (host && getEnclosingBlockScopeContainer(host)) || file; + const host = typeAlias.parent.parent; + container = findAncestor(host.parent, n => !!(getContainerFlags(n) & ContainerFlags.IsContainer)) || file; + blockScopeContainer = getEnclosingBlockScopeContainer(host) || file; currentFlow = initFlowNode({ flags: FlowFlags.Start }); parent = typeAlias; bind(typeAlias.typeExpression); @@ -2545,6 +2522,7 @@ namespace ts { node.flowNode = currentFlow; } break; + case SyntaxKind.MetaProperty: case SyntaxKind.SuperKeyword: node.flowNode = currentFlow; break; @@ -2790,8 +2768,8 @@ namespace ts { function bindExportAssignment(node: ExportAssignment) { if (!container.symbol || !container.symbol.exports) { - // Export assignment in some sort of block construct - bindAnonymousDeclaration(node, SymbolFlags.Alias, getDeclarationName(node)!); + // Incorrect export assignment in some sort of block construct + bindAnonymousDeclaration(node, SymbolFlags.Value, getDeclarationName(node)!); } else { const flags = exportAssignmentIsAlias(node) @@ -3210,7 +3188,7 @@ namespace ts { undefined; init = init && getRightMostAssignedExpression(init); if (init) { - const isPrototypeAssignment = isPrototypeAccess(isVariableDeclaration(node) ? node.name : isBinaryExpression(node) ? node.left : node); + const isPrototypeAssignment = isPrototypeAccess(isVariableDeclaration(node!) ? node.name : isBinaryExpression(node!) ? node.left : node!); return !!getExpandoInitializer(isBinaryExpression(init) && (init.operatorToken.kind === SyntaxKind.BarBarToken || init.operatorToken.kind === SyntaxKind.QuestionQuestionToken) ? init.right : init, isPrototypeAssignment); } return false; @@ -3289,7 +3267,7 @@ namespace ts { if (node.name) { setParent(node.name, node); } - file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], Diagnostics.Duplicate_identifier_0, symbolName(prototypeSymbol))); + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations![0], Diagnostics.Duplicate_identifier_0, symbolName(prototypeSymbol))); } symbol.exports!.set(prototypeSymbol.escapedName, prototypeSymbol); prototypeSymbol.parent = symbol; @@ -3307,7 +3285,7 @@ namespace ts { } if (!isBindingPattern(node.name)) { - if (isInJSFile(node) && isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true) && !getJSDocTypeTag(node)) { + if (isInJSFile(node) && isRequireVariableDeclaration(node) && !getJSDocTypeTag(node)) { declareSymbolAndAddToSymbolTable(node as Declaration, SymbolFlags.Alias, SymbolFlags.AliasExcludes); } else if (isBlockOrCatchScoped(node)) { diff --git a/src/compiler/builder.ts b/src/compiler/builder.ts index 45db667aa99ea..1b6bdf5eecb4e 100644 --- a/src/compiler/builder.ts +++ b/src/compiler/builder.ts @@ -169,8 +169,8 @@ namespace ts { /** * Create the state so that we can iterate on changedFiles/affected files */ - function createBuilderProgramState(newProgram: Program, getCanonicalFileName: GetCanonicalFileName, oldState?: Readonly): BuilderProgramState { - const state = BuilderState.create(newProgram, getCanonicalFileName, oldState) as BuilderProgramState; + function createBuilderProgramState(newProgram: Program, getCanonicalFileName: GetCanonicalFileName, oldState: Readonly | undefined, disableUseFileVersionAsSignature: boolean | undefined): BuilderProgramState { + const state = BuilderState.create(newProgram, getCanonicalFileName, oldState, disableUseFileVersionAsSignature) as BuilderProgramState; state.program = newProgram; const compilerOptions = newProgram.getCompilerOptions(); state.compilerOptions = compilerOptions; @@ -438,8 +438,23 @@ namespace ts { removeSemanticDiagnosticsOf(state, f.resolvedPath) ); } + // When a change affects the global scope, all files are considered to be affected without updating their signature + // That means when affected file is handled, its signature can be out of date + // To avoid this, ensure that we update the signature for any affected file in this scenario. + BuilderState.updateShapeSignature( + state, + Debug.checkDefined(state.program), + affectedFile, + Debug.checkDefined(state.currentAffectedFilesSignatures), + cancellationToken, + computeHash, + state.currentAffectedFilesExportedModulesMap + ); return; } + else { + Debug.assert(state.hasCalledUpdateShapeSignature.has(affectedFile.resolvedPath) || state.currentAffectedFilesSignatures?.has(affectedFile.resolvedPath), `Signature not updated for affected file: ${affectedFile.fileName}`); + } if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) { forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, (state, path) => handleDtsMayChangeOf(state, path, cancellationToken, computeHash)); @@ -690,13 +705,29 @@ namespace ts { return filterSemanticDiagnotics(diagnostics, state.compilerOptions); } - export type ProgramBuildInfoDiagnostic = string | [string, readonly ReusableDiagnostic[]]; - export type ProgramBuilderInfoFilePendingEmit = [string, BuilderFileEmit]; + export type ProgramBuildInfoDiagnostic = number | [fileId: number, diagnostics: readonly ReusableDiagnostic[]]; + export type ProgramBuilderInfoFilePendingEmit = [fileId: number, emitKind: BuilderFileEmit]; + export type ProgramBuildInfoReferencedMap = [fileId: number, fileIdListId: number][]; + export type ProgramBuildInfoBuilderStateFileInfo = Omit & { + /** + * Signature is + * - undefined if FileInfo.version === FileInfo.signature + * - false if FileInfo has signature as undefined (not calculated) + * - string actual signature + */ + signature: string | false | undefined; + }; + /** + * ProgramBuildInfoFileInfo is string if FileInfo.version === FileInfo.signature && !FileInfo.affectsGlobalScope otherwise encoded FileInfo + */ + export type ProgramBuildInfoFileInfo = string | ProgramBuildInfoBuilderStateFileInfo; export interface ProgramBuildInfo { - fileInfos: MapLike; - options: CompilerOptions; - referencedMap?: MapLike; - exportedModulesMap?: MapLike; + fileNames: readonly string[]; + fileInfos: readonly ProgramBuildInfoFileInfo[]; + options: CompilerOptions | undefined; + fileIdsList?: readonly (readonly number[])[]; + referencedMap?: ProgramBuildInfoReferencedMap; + exportedModulesMap?: ProgramBuildInfoReferencedMap; semanticDiagnosticsPerFile?: ProgramBuildInfoDiagnostic[]; affectedFilesPendingEmit?: ProgramBuilderInfoFilePendingEmit[]; } @@ -708,66 +739,83 @@ namespace ts { if (outFile(state.compilerOptions)) return undefined; const currentDirectory = Debug.checkDefined(state.program).getCurrentDirectory(); const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(state.compilerOptions)!, currentDirectory)); - const fileInfos: MapLike = {}; - state.fileInfos.forEach((value, key) => { + const fileNames: string[] = []; + const fileNameToFileId = new Map(); + let fileIdsList: (readonly number[])[] | undefined; + let fileNamesToFileIdListId: ESMap | undefined; + const fileInfos = arrayFrom(state.fileInfos.entries(), ([key, value]): ProgramBuildInfoFileInfo => { + // Ensure fileId + const fileId = toFileId(key); + Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); const signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature, affectsGlobalScope: value.affectsGlobalScope }; + const actualSignature = signature ?? value.signature; + return value.version === actualSignature ? + value.affectsGlobalScope ? + { version: value.version, signature: undefined, affectsGlobalScope: true } : + value.version : + actualSignature !== undefined ? + signature === undefined ? + value : + { version: value.version, signature, affectsGlobalScope: value.affectsGlobalScope } : + { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope }; }); - const result: ProgramBuildInfo = { - fileInfos, - options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath) - }; + let referencedMap: ProgramBuildInfoReferencedMap | undefined; if (state.referencedMap) { - const referencedMap: MapLike = {}; - for (const key of arrayFrom(state.referencedMap.keys()).sort(compareStringsCaseSensitive)) { - referencedMap[relativeToBuildInfo(key)] = arrayFrom(state.referencedMap.get(key)!.keys(), relativeToBuildInfo).sort(compareStringsCaseSensitive); - } - result.referencedMap = referencedMap; + referencedMap = arrayFrom(state.referencedMap.keys()).sort(compareStringsCaseSensitive).map(key => [ + toFileId(key), + toFileIdListId(state.referencedMap!.get(key)!) + ]); } + let exportedModulesMap: ProgramBuildInfoReferencedMap | undefined; if (state.exportedModulesMap) { - const exportedModulesMap: MapLike = {}; - for (const key of arrayFrom(state.exportedModulesMap.keys()).sort(compareStringsCaseSensitive)) { + exportedModulesMap = mapDefined(arrayFrom(state.exportedModulesMap.keys()).sort(compareStringsCaseSensitive), key => { const newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key); // Not in temporary cache, use existing value - if (newValue === undefined) exportedModulesMap[relativeToBuildInfo(key)] = arrayFrom(state.exportedModulesMap.get(key)!.keys(), relativeToBuildInfo).sort(compareStringsCaseSensitive); + if (newValue === undefined) return [toFileId(key), toFileIdListId(state.exportedModulesMap!.get(key)!)]; // Value in cache and has updated value map, use that - else if (newValue) exportedModulesMap[relativeToBuildInfo(key)] = arrayFrom(newValue.keys(), relativeToBuildInfo).sort(compareStringsCaseSensitive); - } - result.exportedModulesMap = exportedModulesMap; + else if (newValue) return [toFileId(key), toFileIdListId(newValue)]; + }); } + let semanticDiagnosticsPerFile: ProgramBuildInfoDiagnostic[] | undefined; if (state.semanticDiagnosticsPerFile) { - const semanticDiagnosticsPerFile: ProgramBuildInfoDiagnostic[] = []; for (const key of arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(compareStringsCaseSensitive)) { const value = state.semanticDiagnosticsPerFile.get(key)!; - semanticDiagnosticsPerFile.push( + (semanticDiagnosticsPerFile ||= []).push( value.length ? [ - relativeToBuildInfo(key), + toFileId(key), state.hasReusableDiagnostic ? value as readonly ReusableDiagnostic[] : convertToReusableDiagnostics(value as readonly Diagnostic[], relativeToBuildInfo) ] : - relativeToBuildInfo(key) + toFileId(key) ); } - result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile; } + let affectedFilesPendingEmit: ProgramBuilderInfoFilePendingEmit[] | undefined; if (state.affectedFilesPendingEmit) { - const affectedFilesPendingEmit: ProgramBuilderInfoFilePendingEmit[] = []; const seenFiles = new Set(); for (const path of state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(compareStringsCaseSensitive)) { if (tryAddToSet(seenFiles, path)) { - affectedFilesPendingEmit.push([relativeToBuildInfo(path), state.affectedFilesPendingEmitKind!.get(path)!]); + (affectedFilesPendingEmit ||= []).push([toFileId(path), state.affectedFilesPendingEmitKind!.get(path)!]); } } - result.affectedFilesPendingEmit = affectedFilesPendingEmit; } - return result; + return { + fileNames, + fileInfos, + options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath), + fileIdsList, + referencedMap, + exportedModulesMap, + semanticDiagnosticsPerFile, + affectedFilesPendingEmit, + }; function relativeToBuildInfoEnsuringAbsolutePath(path: string) { return relativeToBuildInfo(getNormalizedAbsolutePath(path, currentDirectory)); @@ -776,24 +824,42 @@ namespace ts { function relativeToBuildInfo(path: string) { return ensurePathIsNonModuleName(getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName)); } + + function toFileId(path: Path): number { + let fileId = fileNameToFileId.get(path); + if (fileId === undefined) { + fileNames.push(relativeToBuildInfo(path)); + fileNameToFileId.set(path, fileId = fileNames.length); + } + return fileId; + } + + function toFileIdListId(set: ReadonlySet): number { + const fileIds = arrayFrom(set.keys(), toFileId).sort(compareValues); + const key = fileIds.join(); + let fileIdListId = fileNamesToFileIdListId?.get(key); + if (fileIdListId === undefined) { + (fileIdsList ||= []).push(fileIds); + (fileNamesToFileIdListId ||= new Map()).set(key, fileIdListId = fileIdsList.length); + } + return fileIdListId; + } } - function convertToReusableCompilerOptions(options: CompilerOptions, relativeToBuildInfo: (path: string) => string) { - const result: CompilerOptions = {}; + function convertToProgramBuildInfoCompilerOptions(options: CompilerOptions, relativeToBuildInfo: (path: string) => string) { + let result: CompilerOptions | undefined; const { optionsNameMap } = getOptionsNameMap(); - for (const name in options) { - if (hasProperty(options, name)) { - result[name] = convertToReusableCompilerOptionValue( - optionsNameMap.get(name.toLowerCase()), + for (const name of getOwnKeys(options).sort(compareStringsCaseSensitive)) { + const optionInfo = optionsNameMap.get(name.toLowerCase()); + if (optionInfo?.affectsEmit || optionInfo?.affectsSemanticDiagnostics || name === "skipLibCheck" || name === "skipDefaultLibCheck") { + (result ||= {})[name] = convertToReusableCompilerOptionValue( + optionInfo, options[name] as CompilerOptionsValue, relativeToBuildInfo ); } } - if (result.configFilePath) { - result.configFilePath = relativeToBuildInfo(result.configFilePath); - } return result; } @@ -901,7 +967,7 @@ namespace ts { * Computing hash to for signature verification */ const computeHash = maybeBind(host, host.createHash); - let state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + let state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState, host.disableUseFileVersionAsSignature); let backupState: BuilderProgramState | undefined; newProgram.getProgramBuildInfo = () => getProgramBuildInfo(state, getCanonicalFileName); @@ -1167,39 +1233,31 @@ namespace ts { } } - function getMapOfReferencedSet(mapLike: MapLike | undefined, toPath: (path: string) => Path): ReadonlyESMap | undefined { - if (!mapLike) return undefined; - const map = new Map(); - // Copies keys/values from template. Note that for..in will not throw if - // template is undefined, and instead will just exit the loop. - for (const key in mapLike) { - if (hasProperty(mapLike, key)) { - map.set(toPath(key), new Set(mapLike[key].map(toPath))); - } - } - return map; + export function toBuilderStateFileInfo(fileInfo: ProgramBuildInfoFileInfo): BuilderState.FileInfo { + return isString(fileInfo) ? + { version: fileInfo, signature: fileInfo, affectsGlobalScope: undefined } : + isString(fileInfo.signature) ? + fileInfo as BuilderState.FileInfo : + { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope }; } export function createBuildProgramUsingProgramBuildInfo(program: ProgramBuildInfo, buildInfoPath: string, host: ReadBuildProgramHost): EmitAndSemanticDiagnosticsBuilderProgram { const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + const filePaths = program.fileNames.map(toPath); + const filePathsSetList = program.fileIdsList?.map(fileIds => new Set(fileIds.map(toFilePath))); const fileInfos = new Map(); - for (const key in program.fileInfos) { - if (hasProperty(program.fileInfos, key)) { - fileInfos.set(toPath(key), program.fileInfos[key]); - } - } - + program.fileInfos.forEach((fileInfo, index) => fileInfos.set(toFilePath(index + 1), toBuilderStateFileInfo(fileInfo))); const state: ReusableBuilderProgramState = { fileInfos, - compilerOptions: convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), - referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), - exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), - semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && arrayToMap(program.semanticDiagnosticsPerFile, value => toPath(isString(value) ? value : value[0]), value => isString(value) ? emptyArray : value[1]), + compilerOptions: program.options ? convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + referencedMap: toMapOfReferencedSet(program.referencedMap), + exportedModulesMap: toMapOfReferencedSet(program.exportedModulesMap), + semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && arrayToMap(program.semanticDiagnosticsPerFile, value => toFilePath(isNumber(value) ? value : value[0]), value => isNumber(value) ? emptyArray : value[1]), hasReusableDiagnostic: true, - affectedFilesPendingEmit: map(program.affectedFilesPendingEmit, value => toPath(value[0])), - affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && arrayToMap(program.affectedFilesPendingEmit, value => toPath(value[0]), value => value[1]), + affectedFilesPendingEmit: map(program.affectedFilesPendingEmit, value => toFilePath(value[0])), + affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && arrayToMap(program.affectedFilesPendingEmit, value => toFilePath(value[0]), value => value[1]), affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0, }; return { @@ -1234,6 +1292,18 @@ namespace ts { function toAbsolutePath(path: string) { return getNormalizedAbsolutePath(path, buildInfoDirectory); } + + function toFilePath(fileId: number) { + return filePaths[fileId - 1]; + } + + function toFilePathsSet(fileIdsListId: number) { + return filePathsSetList![fileIdsListId - 1]; + } + + function toMapOfReferencedSet(referenceMap: ProgramBuildInfoReferencedMap | undefined): ReadonlyESMap | undefined { + return referenceMap && arrayToMap(referenceMap, value => toFilePath(value[0]), value => toFilePathsSet(value[1])); + } } export function createRedirectedBuilderProgram(state: { program: Program | undefined; compilerOptions: CompilerOptions; }, configFileParsingDiagnostics: readonly Diagnostic[]): BuilderProgram { diff --git a/src/compiler/builderPublic.ts b/src/compiler/builderPublic.ts index e7b7aff636366..c415ba02f5b12 100644 --- a/src/compiler/builderPublic.ts +++ b/src/compiler/builderPublic.ts @@ -15,6 +15,11 @@ namespace ts { * this callback if present would be used to write files */ writeFile?: WriteFileCallback; + /** + * disable using source file version as signature for testing + */ + /*@internal*/ + disableUseFileVersionAsSignature?: boolean; } /** diff --git a/src/compiler/builderState.ts b/src/compiler/builderState.ts index 72c5c37b23382..c150098fff9fb 100644 --- a/src/compiler/builderState.ts +++ b/src/compiler/builderState.ts @@ -45,6 +45,12 @@ namespace ts { * Otherwise undefined */ readonly exportedModulesMap: ESMap | undefined; + + /** + * true if file version is used as signature + * This helps in delaying the calculation of the d.ts hash as version for the file till reasonable time + */ + useFileVersionAsSignature: boolean; /** * Map of files that have already called update signature. * That means hence forth these files are assumed to have @@ -68,7 +74,7 @@ namespace ts { export interface FileInfo { readonly version: string; signature: string | undefined; - affectsGlobalScope: boolean; + affectsGlobalScope: boolean | undefined; } /** * Referenced files with values for the keys as referenced file's path to be true @@ -166,7 +172,7 @@ namespace ts { // From ambient modules for (const ambientModule of program.getTypeChecker().getAmbientModules()) { - if (ambientModule.declarations.length > 1) { + if (ambientModule.declarations && ambientModule.declarations.length > 1) { addReferenceFromAmbientModule(ambientModule); } } @@ -174,6 +180,9 @@ namespace ts { return referencedFiles; function addReferenceFromAmbientModule(symbol: Symbol) { + if (!symbol.declarations) { + return; + } // Add any file other than our own as reference for (const declaration of symbol.declarations) { const declarationSourceFile = getSourceFileOfNode(declaration); @@ -199,7 +208,7 @@ namespace ts { /** * Creates the state of file references and signature for the new program from oldState if it is safe */ - export function create(newProgram: Program, getCanonicalFileName: GetCanonicalFileName, oldState?: Readonly): BuilderState { + export function create(newProgram: Program, getCanonicalFileName: GetCanonicalFileName, oldState?: Readonly, disableUseFileVersionAsSignature?: boolean): BuilderState { const fileInfos = new Map(); const referencedMap = newProgram.getCompilerOptions().module !== ModuleKind.None ? new Map() : undefined; const exportedModulesMap = referencedMap ? new Map() : undefined; @@ -226,14 +235,15 @@ namespace ts { } } } - fileInfos.set(sourceFile.resolvedPath, { version, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) }); + fileInfos.set(sourceFile.resolvedPath, { version, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined }); } return { fileInfos, referencedMap, exportedModulesMap, - hasCalledUpdateShapeSignature + hasCalledUpdateShapeSignature, + useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState }; } @@ -255,6 +265,7 @@ namespace ts { referencedMap: state.referencedMap && new Map(state.referencedMap), exportedModulesMap: state.exportedModulesMap && new Map(state.exportedModulesMap), hasCalledUpdateShapeSignature: new Set(state.hasCalledUpdateShapeSignature), + useFileVersionAsSignature: state.useFileVersionAsSignature, }; } @@ -313,16 +324,8 @@ namespace ts { if (!info) return Debug.fail(); const prevSignature = info.signature; - let latestSignature: string; - if (sourceFile.isDeclarationFile) { - latestSignature = sourceFile.version; - if (exportedModulesMapCache && latestSignature !== prevSignature) { - // All the references in this file are exported - const references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined; - exportedModulesMapCache.set(sourceFile.resolvedPath, references || false); - } - } - else { + let latestSignature: string | undefined; + if (!sourceFile.isDeclarationFile && !state.useFileVersionAsSignature) { const emitOutput = getFileEmitOutput( programOfThisState, sourceFile, @@ -331,10 +334,7 @@ namespace ts { /*customTransformers*/ undefined, /*forceDtsEmit*/ true ); - const firstDts = emitOutput.outputFiles && - programOfThisState.getCompilerOptions().declarationMap ? - emitOutput.outputFiles.length > 1 ? emitOutput.outputFiles[1] : undefined : - emitOutput.outputFiles.length > 0 ? emitOutput.outputFiles[0] : undefined; + const firstDts = firstOrUndefined(emitOutput.outputFiles); if (firstDts) { Debug.assert(fileExtensionIs(firstDts.name, Extension.Dts), "File extension for signature expected to be dts", () => `Found: ${getAnyExtensionFromPath(firstDts.name)} for ${firstDts.name}:: All output files: ${JSON.stringify(emitOutput.outputFiles.map(f => f.name))}`); latestSignature = (computeHash || generateDjb2Hash)(firstDts.text); @@ -342,14 +342,18 @@ namespace ts { updateExportedModules(sourceFile, emitOutput.exportedModulesFromDeclarationEmit, exportedModulesMapCache); } } - else { - latestSignature = prevSignature!; // TODO: GH#18217 + } + // Default is to use file version as signature + if (latestSignature === undefined) { + latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + // All the references in this file are exported + const references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined; + exportedModulesMapCache.set(sourceFile.resolvedPath, references || false); } - } cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature); - - return !prevSignature || latestSignature !== prevSignature; + return latestSignature !== prevSignature; } /** @@ -476,7 +480,7 @@ namespace ts { */ function isFileAffectingGlobalScope(sourceFile: SourceFile) { return containsGlobalScopeAugmentation(sourceFile) || - !isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); + !isExternalOrCommonJsModule(sourceFile) && !containsOnlyAmbientModules(sourceFile); } /** diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 3de21bebf7681..eb8397a18b019 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -240,6 +240,7 @@ namespace ts { SetAccessor = 2, PropertyAssignment = 4, Method = 8, + PrivateStatic = 16, GetOrSetAccessor = GetAccessor | SetAccessor, PropertyAssignmentOrMethod = PropertyAssignment | Method, } @@ -339,14 +340,13 @@ namespace ts { let instantiationDepth = 0; let currentNode: Node | undefined; - const typeCatalog: Type[] = []; // NB: id is index + 1 - const emptySymbols = createSymbolTable(); const arrayVariances = [VarianceFlags.Covariant]; const compilerOptions = host.getCompilerOptions(); const languageVersion = getEmitScriptTarget(compilerOptions); const moduleKind = getEmitModuleKind(compilerOptions); + const useDefineForClassFields = getUseDefineForClassFields(compilerOptions); const allowSyntheticDefaultImports = getAllowSyntheticDefaultImports(compilerOptions); const strictNullChecks = getStrictOptionValue(compilerOptions, "strictNullChecks"); const strictFunctionTypes = getStrictOptionValue(compilerOptions, "strictFunctionTypes"); @@ -357,6 +357,7 @@ namespace ts { const keyofStringsOnly = !!compilerOptions.keyofStringsOnly; const freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : ObjectFlags.FreshLiteral; + const checkBinaryExpression = createCheckBinaryExpression(); const emitResolver = createResolver(); const nodeBuilder = createNodeBuilder(); @@ -384,7 +385,6 @@ namespace ts { getNodeCount: () => sum(host.getSourceFiles(), "nodeCount"), getIdentifierCount: () => sum(host.getSourceFiles(), "identifierCount"), getSymbolCount: () => sum(host.getSourceFiles(), "symbolCount") + symbolCount, - getTypeCatalog: () => typeCatalog, getTypeCount: () => typeCount, getInstantiationCount: () => totalInstantiationCount, getRelationCacheSizes: () => ({ @@ -547,6 +547,7 @@ namespace ts { return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive, + getTypeOfPropertyOfContextualType, getFullyQualifiedName, getResolvedSignature: (node, candidatesOutArray, argumentCount) => getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, CheckMode.Normal), @@ -600,6 +601,7 @@ namespace ts { }, tryGetMemberInModuleExports: (name, symbol) => tryGetMemberInModuleExports(escapeLeadingUnderscores(name), symbol), tryGetMemberInModuleExportsAndProperties: (name, symbol) => tryGetMemberInModuleExportsAndProperties(escapeLeadingUnderscores(name), symbol), + tryFindAmbientModule: moduleName => tryFindAmbientModule(moduleName, /*withAugmentations*/ true), tryFindAmbientModuleWithoutAugmentations: moduleName => { // we deliberately exclude augmentations // since we are only interested in declarations of the module itself @@ -726,6 +728,7 @@ namespace ts { const templateLiteralTypes = new Map(); const stringMappingTypes = new Map(); const substitutionTypes = new Map(); + const subtypeReductionCache = new Map(); const evolvingArrayTypes: EvolvingArrayType[] = []; const undefinedProperties: SymbolTable = new Map(); @@ -898,6 +901,7 @@ namespace ts { // This allows users to just specify library files they want to used through --lib // and they will not get an error from not having unrelated library files let deferredGlobalESSymbolConstructorSymbol: Symbol | undefined; + let deferredGlobalESSymbolConstructorTypeSymbol: Symbol | undefined; let deferredGlobalESSymbolType: ObjectType; let deferredGlobalTypedPropertyDescriptorType: GenericType; let deferredGlobalPromiseType: GenericType; @@ -954,7 +958,7 @@ namespace ts { const flowNodePostSuper: (boolean | undefined)[] = []; const potentialThisCollisions: Node[] = []; const potentialNewTargetCollisions: Node[] = []; - const potentialWeakMapCollisions: Node[] = []; + const potentialWeakMapSetCollisions: Node[] = []; const awaitedTypeStack: number[] = []; const diagnostics = createDiagnosticCollection(); @@ -1240,7 +1244,10 @@ namespace ts { // as we will already report a "Declaration name conflicts..." error, and this error // won't make much sense. if (target !== globalThisSymbol) { - error(getNameOfDeclaration(source.declarations[0]), Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error( + source.declarations && getNameOfDeclaration(source.declarations[0]), + Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, + symbolToString(target)); } } else { // error @@ -1274,8 +1281,10 @@ namespace ts { return target; function addDuplicateLocations(locs: Declaration[], symbol: Symbol): void { - for (const decl of symbol.declarations) { - pushIfUnique(locs, decl); + if (symbol.declarations) { + for (const decl of symbol.declarations) { + pushIfUnique(locs, decl); + } } } } @@ -1318,11 +1327,11 @@ namespace ts { function mergeModuleAugmentation(moduleName: StringLiteral | Identifier): void { const moduleAugmentation = moduleName.parent; - if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + if (moduleAugmentation.symbol.declarations?.[0] !== moduleAugmentation) { // this is a combined symbol for multiple augmentations within the same file. // its symbol already has accumulated information for all declarations // so we need to add it just once - do the work only for first declaration - Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + Debug.assert(moduleAugmentation.symbol.declarations!.length > 1); return; } @@ -1494,7 +1503,7 @@ namespace ts { } else if (isParameterPropertyDeclaration(declaration, declaration.parent)) { // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property - return !(compilerOptions.target === ScriptTarget.ESNext && !!compilerOptions.useDefineForClassFields + return !(compilerOptions.target === ScriptTarget.ESNext && useDefineForClassFields && getContainingClass(declaration) === getContainingClass(usage) && isUsedInFunctionOrInstanceProperty(usage, declaration)); } @@ -1525,7 +1534,7 @@ namespace ts { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (compilerOptions.target === ScriptTarget.ESNext && !!compilerOptions.useDefineForClassFields + if (compilerOptions.target === ScriptTarget.ESNext && useDefineForClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); @@ -1632,7 +1641,11 @@ namespace ts { function useOuterVariableScopeInParameter(result: Symbol, location: Node, lastLocation: Node) { const target = getEmitScriptTarget(compilerOptions); const functionLocation = location; - if (isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + if (isParameter(lastLocation) + && functionLocation.body + && result.valueDeclaration + && result.valueDeclaration.pos >= functionLocation.body.pos + && result.valueDeclaration.end <= functionLocation.body.end) { // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body // - static field in a class expression // - optional chaining pre-es2020 @@ -1669,7 +1682,7 @@ namespace ts { case SyntaxKind.PropertyDeclaration: // static properties in classes introduce temporary variables if (hasStaticModifier(node)) { - return target < ScriptTarget.ESNext || !compilerOptions.useDefineForClassFields; + return target < ScriptTarget.ESNext || !useDefineForClassFields; } return requiresScopeChangeWorker((node as PropertyDeclaration).name); default: @@ -1821,7 +1834,7 @@ namespace ts { // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs) if (name !== InternalSymbolName.Default && (result = lookup(moduleExports, name, meaning & SymbolFlags.ModuleMember))) { - if (isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(isJSDocTypeAlias)) { + if (isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations?.some(isJSDocTypeAlias)) { result = undefined; } else { @@ -2087,7 +2100,7 @@ namespace ts { // Perform extra checks only if error reporting was requested if (nameNotFoundMessage) { - if (propertyWithInvalidInitializer && !(compilerOptions.target === ScriptTarget.ESNext && compilerOptions.useDefineForClassFields)) { + if (propertyWithInvalidInitializer && !(compilerOptions.target === ScriptTarget.ESNext && useDefineForClassFields)) { // We have a match, but the reference occurred within a property initializer and the identifier also binds // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed // with ESNext+useDefineForClassFields because the scope semantics are different. @@ -2201,11 +2214,13 @@ namespace ts { } function isTypeParameterSymbolDeclaredInContainer(symbol: Symbol, container: Node) { - for (const decl of symbol.declarations) { - if (decl.kind === SyntaxKind.TypeParameter) { - const parent = isJSDocTemplateTag(decl.parent) ? getJSDocHost(decl.parent) : decl.parent; - if (parent === container) { - return !(isJSDocTemplateTag(decl.parent) && find((decl.parent.parent as JSDoc).tags!, isJSDocTypeAlias)); // TODO: GH#18217 + if (symbol.declarations) { + for (const decl of symbol.declarations) { + if (decl.kind === SyntaxKind.TypeParameter) { + const parent = isJSDocTemplateTag(decl.parent) ? getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(isJSDocTemplateTag(decl.parent) && find((decl.parent.parent as JSDoc).tags!, isJSDocTypeAlias)); // TODO: GH#18217 + } } } } @@ -2404,8 +2419,7 @@ namespace ts { return; } // Block-scoped variables cannot be used before their definition - const declaration = find( - result.declarations, + const declaration = result.declarations?.find( d => isBlockOrCatchScoped(d) || isClassLike(d) || (d.kind === SyntaxKind.EnumDeclaration)); if (declaration === undefined) return Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration"); @@ -2461,7 +2475,7 @@ namespace ts { } function getDeclarationOfAliasSymbol(symbol: Symbol): Declaration | undefined { - return find(symbol.declarations, isAliasSymbolDeclaration); + return symbol.declarations && findLast(symbol.declarations, isAliasSymbolDeclaration); } /** @@ -2477,6 +2491,7 @@ namespace ts { * module.exports = * {} * {name: } + * const { x } = require ... */ function isAliasSymbolDeclaration(node: Node): boolean { return node.kind === SyntaxKind.ImportEqualsDeclaration @@ -2495,7 +2510,7 @@ namespace ts { && isAliasableOrJsExpression(node.parent.right) || node.kind === SyntaxKind.ShorthandPropertyAssignment || node.kind === SyntaxKind.PropertyAssignment && isAliasableOrJsExpression((node as PropertyAssignment).initializer) - || isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true); + || isRequireVariableDeclaration(node); } function isAliasableOrJsExpression(e: Expression) { @@ -2595,7 +2610,7 @@ namespace ts { exportDefaultSymbol = resolveExportByName(moduleSymbol, InternalSymbolName.Default, node, dontResolveAlias); } - const file = find(moduleSymbol.declarations, isSourceFile); + const file = moduleSymbol.declarations?.find(isSourceFile); const hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); if (!exportDefaultSymbol && !hasSyntheticDefault) { if (hasExportAssignmentSymbol(moduleSymbol)) { @@ -2604,11 +2619,13 @@ namespace ts { const exportAssignment = exportEqualsSymbol!.valueDeclaration; const err = error(node.name, Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName); - addRelatedInfo(err, createDiagnosticForNode( - exportAssignment, - Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, - compilerOptionName - )); + if (exportAssignment) { + addRelatedInfo(err, createDiagnosticForNode( + exportAssignment, + Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, + compilerOptionName + )); + } } else { reportNonDefaultExport(moduleSymbol, node); @@ -2638,7 +2655,7 @@ namespace ts { const diagnostic = error(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); const exportStar = moduleSymbol.exports?.get(InternalSymbolName.ExportStar); if (exportStar) { - const defaultExport = find(exportStar.declarations, decl => !!( + const defaultExport = exportStar.declarations?.find(decl => !!( isExportDeclaration(decl) && decl.moduleSpecifier && resolveExternalModuleName(decl, decl.moduleSpecifier)?.exports?.has(InternalSymbolName.Default) )); @@ -2725,7 +2742,7 @@ namespace ts { return undefined; } const suppressInteropError = name.escapedText === InternalSymbolName.Default && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop); - const targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, dontResolveAlias, suppressInteropError); + const targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, /*dontResolveAlias*/ false, suppressInteropError); if (targetSymbol) { if (name.escapedText) { if (isShorthandAmbientModuleSymbol(moduleSymbol)) { @@ -2745,7 +2762,7 @@ namespace ts { let symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias); if (symbolFromModule === undefined && name.escapedText === InternalSymbolName.Default) { - const file = find(moduleSymbol.declarations, isSourceFile); + const file = moduleSymbol.declarations?.find(isSourceFile); if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } @@ -2787,7 +2804,7 @@ namespace ts { } function reportNonExportedMember(node: ImportDeclaration | ExportDeclaration | VariableDeclaration, name: Identifier, declarationName: string, moduleSymbol: Symbol, moduleName: string): void { - const localSymbol = moduleSymbol.valueDeclaration.locals?.get(name.escapedText); + const localSymbol = moduleSymbol.valueDeclaration?.locals?.get(name.escapedText); const exports = moduleSymbol.exports; if (localSymbol) { const exportedEqualsSymbol = exports?.get(InternalSymbolName.ExportEquals); @@ -2799,10 +2816,11 @@ namespace ts { const exportedSymbol = exports ? find(symbolsToArray(exports), symbol => !!getSymbolIfSameReference(symbol, localSymbol)) : undefined; const diagnostic = exportedSymbol ? error(name, Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : error(name, Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); - - addRelatedInfo(diagnostic, - ...map(localSymbol.declarations, (decl, index) => - createDiagnosticForNode(decl, index === 0 ? Diagnostics._0_is_declared_here : Diagnostics.and_here, declarationName))); + if (localSymbol.declarations) { + addRelatedInfo(diagnostic, + ...map(localSymbol.declarations, (decl, index) => + createDiagnosticForNode(decl, index === 0 ? Diagnostics._0_is_declared_here : Diagnostics.and_here, declarationName))); + } } } else { @@ -3134,18 +3152,19 @@ namespace ts { else if (namespace === unknownSymbol) { return namespace; } - if (isInJSFile(name)) { - if (namespace.valueDeclaration && - isVariableDeclaration(namespace.valueDeclaration) && - namespace.valueDeclaration.initializer && - isCommonJsRequire(namespace.valueDeclaration.initializer)) { - const moduleName = (namespace.valueDeclaration.initializer as CallExpression).arguments[0] as StringLiteral; - const moduleSym = resolveExternalModuleName(moduleName, moduleName); - if (moduleSym) { - const resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); - if (resolvedModuleSymbol) { - namespace = resolvedModuleSymbol; - } + if ( + namespace.valueDeclaration && + isInJSFile(namespace.valueDeclaration) && + isVariableDeclaration(namespace.valueDeclaration) && + namespace.valueDeclaration.initializer && + isCommonJsRequire(namespace.valueDeclaration.initializer) + ) { + const moduleName = (namespace.valueDeclaration.initializer as CallExpression).arguments[0] as StringLiteral; + const moduleSym = resolveExternalModuleName(moduleName, moduleName); + if (moduleSym) { + const resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + namespace = resolvedModuleSymbol; } } } @@ -3482,7 +3501,10 @@ namespace ts { const exports = getExportsOfModuleAsArray(moduleSymbol); const exportEquals = resolveExternalModuleSymbol(moduleSymbol); if (exportEquals !== moduleSymbol) { - addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); + const type = getTypeOfSymbol(exportEquals); + if (shouldTreatPropertiesOfExternalModuleAsExports(type)) { + addRange(exports, getPropertiesOfType(type)); + } } return exports; } @@ -3506,11 +3528,15 @@ namespace ts { } const type = getTypeOfSymbol(exportEquals); - return type.flags & TypeFlags.Primitive || - getObjectFlags(type) & ObjectFlags.Class || - isArrayOrTupleLikeType(type) - ? undefined - : getPropertyOfType(type, memberName); + return shouldTreatPropertiesOfExternalModuleAsExports(type) ? getPropertyOfType(type, memberName) : undefined; + } + + function shouldTreatPropertiesOfExternalModuleAsExports(resolvedExternalModuleType: Type) { + return !(resolvedExternalModuleType.flags & TypeFlags.Primitive || + getObjectFlags(resolvedExternalModuleType) & ObjectFlags.Class || + // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path + isArrayType(resolvedExternalModuleType) || + isTupleType(resolvedExternalModuleType)); } function getExportsOfSymbol(symbol: Symbol): SymbolTable { @@ -3581,15 +3607,17 @@ namespace ts { if (exportStars) { const nestedSymbols = createSymbolTable(); const lookupTable: ExportCollisionTrackerTable = new Map(); - for (const node of exportStars.declarations) { - const resolvedModule = resolveExternalModuleName(node, (node as ExportDeclaration).moduleSpecifier!); - const exportedSymbols = visit(resolvedModule); - extendExportSymbols( - nestedSymbols, - exportedSymbols, - lookupTable, - node as ExportDeclaration - ); + if (exportStars.declarations) { + for (const node of exportStars.declarations) { + const resolvedModule = resolveExternalModuleName(node, (node as ExportDeclaration).moduleSpecifier!); + const exportedSymbols = visit(resolvedModule); + extendExportSymbols( + nestedSymbols, + exportedSymbols, + lookupTable, + node as ExportDeclaration + ); + } } lookupTable.forEach(({ exportsWithDuplicate }, id) => { // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself @@ -3677,11 +3705,30 @@ namespace ts { const additionalContainers = mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); const reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration); const objectLiteralContainer = getVariableDeclarationOfObjectLiteral(container, meaning); - if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, SymbolFlags.Namespace, /*externalOnly*/ false)) { + if ( + enclosingDeclaration && + container.flags & getQualifiedLeftMeaning(meaning) && + getAccessibleSymbolChain(container, enclosingDeclaration, SymbolFlags.Namespace, /*externalOnly*/ false) + ) { return append(concatenate(concatenate([container], additionalContainers), reexportContainers), objectLiteralContainer); // This order expresses a preference for the real container if it is in scope } - const res = append(append(additionalContainers, container), objectLiteralContainer); - return concatenate(res, reexportContainers); + // we potentially have a symbol which is a member of the instance side of something - look for a variable in scope with the container's type + // which may be acting like a namespace (eg, `Symbol` acts like a namespace when looking up `Symbol.toStringTag`) + const firstVariableMatch = !(container.flags & getQualifiedLeftMeaning(meaning)) + && container.flags & SymbolFlags.Type + && getDeclaredTypeOfSymbol(container).flags & TypeFlags.Object + && meaning === SymbolFlags.Value + ? forEachSymbolTableInScope(enclosingDeclaration, t => { + return forEachEntry(t, s => { + if (s.flags & getQualifiedLeftMeaning(meaning) && getTypeOfSymbol(s) === getDeclaredTypeOfSymbol(container)) { + return s; + } + }); + }) : undefined; + let res = firstVariableMatch ? [firstVariableMatch, ...additionalContainers, container] : [...additionalContainers, container]; + res = append(res, objectLiteralContainer); + res = addRange(res, reexportContainers); + return res; } const candidates = mapDefined(symbol.declarations, d => { if (!isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) { @@ -3709,7 +3756,7 @@ namespace ts { // 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 declaration's visibility, and therefore the literal. - const firstDecl: Node | false = !!length(symbol.declarations) && first(symbol.declarations); + const firstDecl: Node | false = !!length(symbol.declarations) && first(symbol.declarations!); if (meaning & SymbolFlags.Value && firstDecl && firstDecl.parent && isVariableDeclaration(firstDecl.parent)) { if (isObjectLiteralExpression(firstDecl) && firstDecl === firstDecl.parent.initializer || isTypeLiteralNode(firstDecl) && firstDecl === firstDecl.parent.type) { return getSymbolOfNode(firstDecl.parent); @@ -3778,7 +3825,9 @@ namespace ts { const result = new Type(checker, flags); typeCount++; result.id = typeCount; - typeCatalog.push(result); + if (produceDiagnostics) { // Only record types from one checker + tracing?.recordType(result); + } return result; } @@ -3845,14 +3894,23 @@ namespace ts { return result || emptyArray; } + function getNamedOrIndexSignatureMembers(members: SymbolTable): Symbol[] { + const result = getNamedMembers(members); + const index = getIndexSymbolFromSymbolTable(members); + return index ? concatenate(result, [index]) : result; + } + function setStructuredTypeMembers(type: StructuredType, members: SymbolTable, callSignatures: readonly Signature[], constructSignatures: readonly Signature[], stringIndexInfo: IndexInfo | undefined, numberIndexInfo: IndexInfo | undefined): ResolvedType { - (type).members = members; - (type).properties = members === emptySymbols ? emptyArray : getNamedMembers(members); - (type).callSignatures = callSignatures; - (type).constructSignatures = constructSignatures; - (type).stringIndexInfo = stringIndexInfo; - (type).numberIndexInfo = numberIndexInfo; - return type; + const resolved = type; + resolved.members = members; + resolved.properties = emptyArray; + resolved.callSignatures = callSignatures; + resolved.constructSignatures = constructSignatures; + resolved.stringIndexInfo = stringIndexInfo; + resolved.numberIndexInfo = numberIndexInfo; + // This can loop back to getPropertyOfType() which would crash if `callSignatures` & `constructSignatures` are not initialized. + if (members !== emptySymbols) resolved.properties = getNamedMembers(members); + return resolved; } function createAnonymousType(symbol: Symbol | undefined, members: SymbolTable, callSignatures: readonly Signature[], constructSignatures: readonly Signature[], stringIndexInfo: IndexInfo | undefined, numberIndexInfo: IndexInfo | undefined): ResolvedType { @@ -3877,12 +3935,12 @@ namespace ts { return typeCopy; } - function forEachSymbolTableInScope(enclosingDeclaration: Node | undefined, callback: (symbolTable: SymbolTable) => T): T { + function forEachSymbolTableInScope(enclosingDeclaration: Node | undefined, callback: (symbolTable: SymbolTable, ignoreQualification?: boolean, isLocalNameLookup?: boolean) => T): T { let result: T; for (let location = enclosingDeclaration; location; location = location.parent) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { - if (result = callback(location.locals)) { + if (result = callback(location.locals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return result; } } @@ -3897,7 +3955,7 @@ namespace ts { // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred // to one another anyway) - if (result = callback(sym?.exports || emptySymbols)) { + if (result = callback(sym?.exports || emptySymbols, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true)) { return result; } break; @@ -3925,7 +3983,7 @@ namespace ts { } } - return callback(globals); + return callback(globals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true); } function getQualifiedLeftMeaning(rightMeaning: SymbolFlags) { @@ -3948,12 +4006,12 @@ namespace ts { /** * @param {ignoreQualification} boolean Set when a symbol is being looked for through the exports of another symbol (meaning we have a route to qualify it already) */ - function getAccessibleSymbolChainFromSymbolTable(symbols: SymbolTable, ignoreQualification?: boolean): Symbol[] | undefined { + function getAccessibleSymbolChainFromSymbolTable(symbols: SymbolTable, ignoreQualification?: boolean, isLocalNameLookup?: boolean): Symbol[] | undefined { if (!pushIfUnique(visitedSymbolTables!, symbols)) { return undefined; } - const result = trySymbolTable(symbols, ignoreQualification); + const result = trySymbolTable(symbols, ignoreQualification, isLocalNameLookup); visitedSymbolTables!.pop(); return result; } @@ -3974,7 +4032,7 @@ namespace ts { (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning)); } - function trySymbolTable(symbols: SymbolTable, ignoreQualification: boolean | undefined): Symbol[] | undefined { + function trySymbolTable(symbols: SymbolTable, ignoreQualification: boolean | undefined, isLocalNameLookup: boolean | undefined): Symbol[] | undefined { // If symbol is directly available by its name in the symbol table if (isAccessible(symbols.get(symbol!.escapedName)!, /*resolvedAliasSymbol*/ undefined, ignoreQualification)) { return [symbol!]; @@ -3988,6 +4046,8 @@ namespace ts { && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && isExternalModule(getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name && (!useOnlyExternalAliasing || some(symbolFromSymbolTable.declarations, isExternalModuleImportEqualsDeclaration)) + // If we're looking up a local name to reference directly, omit namespace reexports, otherwise when we're trawling through an export list to make a dotted name, we can keep it + && (isLocalNameLookup ? !some(symbolFromSymbolTable.declarations, isNamespaceReexportDeclaration) : true) // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ // See similar comment in `resolveName` for details && (ignoreQualification || !getDeclarationOfKind(symbolFromSymbolTable, SyntaxKind.ExportSpecifier)) @@ -4102,7 +4162,7 @@ namespace ts { return hasAccessibleDeclarations; } } - else if (allowModules) { + if (allowModules) { if (some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { if (shouldComputeAliasesToMakeVisible) { earlyModuleBail = true; @@ -4380,7 +4440,7 @@ namespace ts { } function symbolValueDeclarationIsContextSensitive(symbol: Symbol): boolean { - return symbol && symbol.valueDeclaration && isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration); + return symbol && !!symbol.valueDeclaration && isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration); } function toNodeBuilderFlags(flags = TypeFormatFlags.None): NodeBuilderFlags { @@ -4388,7 +4448,7 @@ namespace ts { } function isClassInstanceSide(type: Type) { - return !!type.symbol && !!(type.symbol.flags & SymbolFlags.Class) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(getObjectFlags(type) & ObjectFlags.IsClassInstanceClone)); + return !!type.symbol && !!(type.symbol.flags & SymbolFlags.Class) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || (!!(type.flags & TypeFlags.Object) && !!(getObjectFlags(type) & ObjectFlags.IsClassInstanceClone))); } function createNodeBuilder() { @@ -4729,7 +4789,9 @@ namespace ts { return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects - else if (symbol.flags & SymbolFlags.Class && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === SyntaxKind.ClassExpression && context.flags & NodeBuilderFlags.WriteClassExpressionAsTypeLiteral) || + else if (symbol.flags & SymbolFlags.Class + && !getBaseTypeVariableOfClass(symbol) + && !(symbol.valueDeclaration && symbol.valueDeclaration.kind === SyntaxKind.ClassExpression && context.flags & NodeBuilderFlags.WriteClassExpressionAsTypeLiteral) || symbol.flags & (SymbolFlags.Enum | SymbolFlags.ValueModule) || shouldWriteTypeOfFunctionSymbol()) { return symbolToTypeNode(symbol, context, isInstanceType); @@ -5084,15 +5146,32 @@ namespace ts { return factory.createKeywordTypeNode(SyntaxKind.AnyKeyword); } + function shouldUsePlaceholderForProperty(propertySymbol: Symbol, context: NodeBuilderContext) { + // Use placeholders for reverse mapped types we've either already descended into, or which + // are nested reverse mappings within a mapping over a non-anonymous type. The later is a restriction mostly just to + // reduce the blowup in printback size from doing, eg, a deep reverse mapping over `Window`. + // Since anonymous types usually come from expressions, this allows us to preserve the output + // for deep mappings which likely come from expressions, while truncating those parts which + // come from mappings over library functions. + return !!(getCheckFlags(propertySymbol) & CheckFlags.ReverseMapped) + && ( + contains(context.reverseMappedStack, propertySymbol as ReverseMappedSymbol) + || ( + context.reverseMappedStack?.[0] + && !(getObjectFlags(last(context.reverseMappedStack).propertyType) & ObjectFlags.Anonymous) + ) + ); + } + function addPropertyToElementList(propertySymbol: Symbol, context: NodeBuilderContext, typeElements: TypeElement[]) { const propertyIsReverseMapped = !!(getCheckFlags(propertySymbol) & CheckFlags.ReverseMapped); - const propertyType = propertyIsReverseMapped && context.flags & NodeBuilderFlags.InReverseMappedType ? + const propertyType = shouldUsePlaceholderForProperty(propertySymbol, context) ? anyType : getTypeOfSymbol(propertySymbol); const saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; if (context.tracker.trackSymbol && getCheckFlags(propertySymbol) & CheckFlags.Late && isLateBoundName(propertySymbol.escapedName)) { - const decl = first(propertySymbol.declarations); - if (hasLateBindableName(decl)) { + const decl = first(propertySymbol.declarations!); + if (propertySymbol.declarations && hasLateBindableName(decl)) { if (isBinaryExpression(decl)) { const name = getNameOfDeclaration(decl); if (name && isElementAccessExpression(name) && isPropertyAccessEntityNameExpression(name.argumentExpression)) { @@ -5104,8 +5183,9 @@ namespace ts { } } } - context.enclosingDeclaration = saveEnclosingDeclaration; + context.enclosingDeclaration = propertySymbol.valueDeclaration || propertySymbol.declarations?.[0] || saveEnclosingDeclaration; const propertyName = getPropertyNameNodeForSymbol(propertySymbol, context); + context.enclosingDeclaration = saveEnclosingDeclaration; context.approximateLength += (symbolName(propertySymbol).length + 1); const optionalToken = propertySymbol.flags & SymbolFlags.Optional ? factory.createToken(SyntaxKind.QuestionToken) : undefined; if (propertySymbol.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { @@ -5116,16 +5196,20 @@ namespace ts { } } else { - const savedFlags = context.flags; - context.flags |= propertyIsReverseMapped ? NodeBuilderFlags.InReverseMappedType : 0; let propertyTypeNode: TypeNode; - if (propertyIsReverseMapped && !!(savedFlags & NodeBuilderFlags.InReverseMappedType)) { + if (shouldUsePlaceholderForProperty(propertySymbol, context)) { propertyTypeNode = createElidedInformationPlaceholder(context); } else { + if (propertyIsReverseMapped) { + context.reverseMappedStack ||= []; + context.reverseMappedStack.push(propertySymbol as ReverseMappedSymbol); + } propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : factory.createKeywordTypeNode(SyntaxKind.AnyKeyword); + if (propertyIsReverseMapped) { + context.reverseMappedStack!.pop(); + } } - context.flags = savedFlags; const modifiers = isReadonlySymbol(propertySymbol) ? [factory.createToken(SyntaxKind.ReadonlyKeyword)] : undefined; if (modifiers) { @@ -5142,8 +5226,8 @@ namespace ts { function preserveCommentsOn(node: T) { if (some(propertySymbol.declarations, d => d.kind === SyntaxKind.JSDocPropertyTag)) { - const d = find(propertySymbol.declarations, d => d.kind === SyntaxKind.JSDocPropertyTag)! as JSDocPropertyTag; - const commentText = d.comment; + const d = propertySymbol.declarations?.find(d => d.kind === SyntaxKind.JSDocPropertyTag)! as JSDocPropertyTag; + const commentText = getTextOfJSDocComment(d.comment); if (commentText) { setSyntheticLeadingComments(node, [{ kind: SyntaxKind.MultiLineCommentTrivia, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]); } @@ -5564,7 +5648,7 @@ namespace ts { if (context.tracker.trackReferencedAmbientModule) { const ambientDecls = filter(symbol.declarations, isAmbientModule); if (length(ambientDecls)) { - for (const decl of ambientDecls) { + for (const decl of ambientDecls!) { context.tracker.trackReferencedAmbientModule(decl, symbol); } } @@ -5597,7 +5681,7 @@ namespace ts { specifierCompilerOptions, contextFile, moduleResolverHost, - { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative", importModuleSpecifierEnding: isBundle ? "minimal" : undefined }, + { importModuleSpecifierPreference: isBundle ? "non-relative" : "project-relative", importModuleSpecifierEnding: isBundle ? "minimal" : undefined }, )); links.specifierCache ??= new Map(); links.specifierCache.set(contextFile.path, specifier); @@ -5754,7 +5838,7 @@ namespace ts { if (expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { + && !(context.flags & NodeBuilderFlags.AllowQualifiedNameInPlaceOfIdentifier)) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); @@ -5849,9 +5933,6 @@ namespace ts { if (fromNameType) { return fromNameType; } - if (isKnownSymbol(symbol)) { - return factory.createComputedPropertyName(factory.createPropertyAccessExpression(factory.createIdentifier("Symbol"), (symbol.escapedName as string).substr(3))); - } const rawName = unescapeLeadingUnderscores(symbol.escapedName); const stringNamed = !!length(symbol.declarations) && every(symbol.declarations, isStringNamed); return createPropertyNameNodeForIdentifierOrLiteral(rawName, stringNamed, singleQuote); @@ -5925,7 +6006,7 @@ namespace ts { function serializeTypeForDeclaration(context: NodeBuilderContext, type: Type, symbol: Symbol, enclosingDeclaration: Node | undefined, includePrivateSymbol?: (s: Symbol) => void, bundled?: boolean) { if (type !== errorType && enclosingDeclaration) { const declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); - if (declWithExistingAnnotation && !isFunctionLikeDeclaration(declWithExistingAnnotation)) { + if (declWithExistingAnnotation && !isFunctionLikeDeclaration(declWithExistingAnnotation) && !isGetAccessorDeclaration(declWithExistingAnnotation)) { // try to reuse the existing annotation const existing = getEffectiveTypeAnnotationNode(declWithExistingAnnotation)!; if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { @@ -5949,10 +6030,14 @@ namespace ts { function serializeReturnTypeForSignature(context: NodeBuilderContext, type: Type, signature: Signature, includePrivateSymbol?: (s: Symbol) => void, bundled?: boolean) { if (type !== errorType && context.enclosingDeclaration) { const annotation = signature.declaration && getEffectiveReturnTypeNode(signature.declaration); - if (!!findAncestor(annotation, n => n === context.enclosingDeclaration) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { - const result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); - if (result) { - return result; + if (!!findAncestor(annotation, n => n === context.enclosingDeclaration) && annotation) { + const annotated = getTypeFromTypeNode(annotation); + const thisInstantiated = annotated.flags & TypeFlags.TypeParameter && (annotated as TypeParameter).isThisType ? instantiateType(annotated, signature.mapper) : annotated; + if (thisInstantiated === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { + const result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } } } } @@ -6493,9 +6578,9 @@ namespace ts { if (textRange && isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) { textRange = textRange.parent.parent; } - const propertyAccessRequire = find(symbol.declarations, isPropertyAccessExpression); + const propertyAccessRequire = symbol.declarations?.find(isPropertyAccessExpression); if (propertyAccessRequire && isBinaryExpression(propertyAccessRequire.parent) && isIdentifier(propertyAccessRequire.parent.right) - && type.symbol && isSourceFile(type.symbol.valueDeclaration)) { + && type.symbol?.valueDeclaration && isSourceFile(type.symbol.valueDeclaration)) { const alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right; addResult( factory.createExportDeclaration( @@ -6555,7 +6640,10 @@ namespace ts { serializeEnum(symbol, symbolName, modifierFlags); } if (symbol.flags & SymbolFlags.Class) { - if (symbol.flags & SymbolFlags.Property && isBinaryExpression(symbol.valueDeclaration.parent) && isClassExpression(symbol.valueDeclaration.parent.right)) { + if (symbol.flags & SymbolFlags.Property + && symbol.valueDeclaration + && isBinaryExpression(symbol.valueDeclaration.parent) + && isClassExpression(symbol.valueDeclaration.parent.right)) { // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members, // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today. @@ -6581,10 +6669,12 @@ namespace ts { if (symbol.flags & SymbolFlags.ExportStar) { // synthesize export * from "moduleReference" // Straightforward - only one thing to do - make an export declaration - for (const node of symbol.declarations) { - const resolvedModule = resolveExternalModuleName(node, (node as ExportDeclaration).moduleSpecifier!); - if (!resolvedModule) continue; - addResult(factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), ModifierFlags.None); + if (symbol.declarations) { + for (const node of symbol.declarations) { + const resolvedModule = resolveExternalModuleName(node, (node as ExportDeclaration).moduleSpecifier!); + if (!resolvedModule) continue; + addResult(factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), ModifierFlags.None); + } } } if (needsPostExportDefault) { @@ -6655,8 +6745,8 @@ namespace ts { const aliasType = getDeclaredTypeOfTypeAlias(symbol); const typeParams = getSymbolLinks(symbol).typeParameters; const typeParamDecls = map(typeParams, p => typeParameterToDeclaration(p, context)); - const jsdocAliasDecl = find(symbol.declarations, isJSDocTypeAlias); - const commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined; + const jsdocAliasDecl = symbol.declarations?.find(isJSDocTypeAlias); + const commentText = getTextOfJSDocComment(jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined); const oldFlags = context.flags; context.flags |= NodeBuilderFlags.InTypeAlias; const oldEnclosingDecl = context.enclosingDeclaration; @@ -6770,8 +6860,7 @@ namespace ts { for (const sig of signatures) { // Each overload becomes a separate function declaration, in order const decl = signatureToSignatureDeclarationHelper(sig, SyntaxKind.FunctionDeclaration, context, { name: factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled }) as FunctionDeclaration; - // for expressions assigned to `var`s, use the `var` as the text range - addResult(setTextRange(decl, sig.declaration && isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags); + addResult(setTextRange(decl, getSignatureTextRangeLocation(sig)), modifierFlags); } // Module symbol emit will take care of module-y members, provided it has exports if (!(symbol.flags & (SymbolFlags.ValueModule | SymbolFlags.NamespaceModule) && !!symbol.exports && !!symbol.exports.size)) { @@ -6780,6 +6869,19 @@ namespace ts { } } + function getSignatureTextRangeLocation(signature: Signature) { + if (signature.declaration && signature.declaration.parent) { + if (isBinaryExpression(signature.declaration.parent) && getAssignmentDeclarationKind(signature.declaration.parent) === AssignmentDeclarationKind.Property) { + return signature.declaration.parent; + } + // for expressions assigned to `var`s, use the `var` as the text range + if (isVariableDeclaration(signature.declaration.parent) && signature.declaration.parent.parent) { + return signature.declaration.parent.parent; + } + } + return signature.declaration; + } + function serializeAsNamespaceDeclaration(props: readonly Symbol[], localName: string, modifierFlags: ModifierFlags, suppressNewPrivateContext: boolean) { if (length(props)) { const localVsRemoteMap = arrayToMultiMap(props, p => @@ -6880,7 +6982,7 @@ namespace ts { } function serializeAsClass(symbol: Symbol, localName: string, modifierFlags: ModifierFlags) { - const originalDecl = find(symbol.declarations, isClassLike); + const originalDecl = symbol.declarations?.find(isClassLike); const oldEnclosing = context.enclosingDeclaration; context.enclosingDeclaration = originalDecl || oldEnclosing; const localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -6905,14 +7007,14 @@ namespace ts { // a union/intersection base type, but inherited properties // don't matter here. const valueDecl = s.valueDeclaration; - return valueDecl && !(isNamedDeclaration(valueDecl) && isPrivateIdentifier(valueDecl.name)); + return !!valueDecl && !(isNamedDeclaration(valueDecl) && isPrivateIdentifier(valueDecl.name)); }); const hasPrivateIdentifier = some(symbolProps, s => { // `valueDeclaration` could be undefined if inherited from // a union/intersection base type, but inherited properties // don't matter here. const valueDecl = s.valueDeclaration; - return valueDecl && isNamedDeclaration(valueDecl) && isPrivateIdentifier(valueDecl.name); + return !!valueDecl && isNamedDeclaration(valueDecl) && isPrivateIdentifier(valueDecl.name); }); // Boil down all private properties into a single one. const privateProperties = hasPrivateIdentifier ? @@ -7303,7 +7405,7 @@ namespace ts { } const flag = (modifierFlags & ~ModifierFlags.Async) | (isStatic ? ModifierFlags.Static : 0); const name = getPropertyNameNodeForSymbol(p, context); - const firstPropertyLikeDecl = find(p.declarations, or(isPropertyDeclaration, isAccessor, isVariableDeclaration, isPropertySignature, isBinaryExpression, isPropertyAccessExpression)); + const firstPropertyLikeDecl = p.declarations?.find(or(isPropertyDeclaration, isAccessor, isVariableDeclaration, isPropertySignature, isBinaryExpression, isPropertyAccessExpression)); if (p.flags & SymbolFlags.Accessor && useAccessors) { const result: AccessorDeclaration[] = []; if (p.flags & SymbolFlags.SetAccessor) { @@ -7320,7 +7422,7 @@ namespace ts { isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled) )], /*body*/ undefined - ), find(p.declarations, isSetAccessor) || firstPropertyLikeDecl)); + ), p.declarations?.find(isSetAccessor) || firstPropertyLikeDecl)); } if (p.flags & SymbolFlags.GetAccessor) { const isPrivate = modifierFlags & ModifierFlags.Private; @@ -7331,7 +7433,7 @@ namespace ts { [], isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), /*body*/ undefined - ), find(p.declarations, isGetAccessor) || firstPropertyLikeDecl)); + ), p.declarations?.find(isGetAccessor) || firstPropertyLikeDecl)); } return result; } @@ -7347,7 +7449,7 @@ namespace ts { // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ /*initializer*/ undefined - ), find(p.declarations, or(isPropertyDeclaration, isVariableDeclaration)) || firstPropertyLikeDecl); + ), p.declarations?.find(or(isPropertyDeclaration, isVariableDeclaration)) || firstPropertyLikeDecl); } if (p.flags & (SymbolFlags.Method | SymbolFlags.Function)) { const type = getTypeOfSymbol(p); @@ -7360,7 +7462,7 @@ namespace ts { p.flags & SymbolFlags.Optional ? factory.createToken(SyntaxKind.QuestionToken) : undefined, /*type*/ undefined, /*initializer*/ undefined - ), find(p.declarations, isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations[0]); + ), p.declarations?.find(isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); } const results = []; @@ -7376,7 +7478,8 @@ namespace ts { modifiers: flag ? factory.createModifiersFromModifierFlags(flag) : undefined } ); - results.push(setTextRange(decl, sig.declaration)); + const location = sig.declaration && isPrototypePropertyAssignment(sig.declaration.parent) ? sig.declaration.parent : sig.declaration; + results.push(setTextRange(decl, location)); } return results as unknown as T[]; } @@ -7606,7 +7709,7 @@ namespace ts { } function getTypeAliasForTypeLiteral(type: Type): Symbol | undefined { - if (type.symbol && type.symbol.flags & SymbolFlags.TypeLiteral) { + if (type.symbol && type.symbol.flags & SymbolFlags.TypeLiteral && type.symbol.declarations) { const node = walkUpParenthesizedTypes(type.symbol.declarations[0].parent); if (node.kind === SyntaxKind.TypeAliasDeclaration) { return getSymbolOfNode(node); @@ -7638,6 +7741,7 @@ namespace ts { typeParameterNamesByText?: Set; usedSymbolNames?: Set; remappedSymbolNames?: ESMap; + reverseMappedStack?: ReverseMappedSymbol[]; } function isDefaultBindingContext(location: Node) { @@ -7841,7 +7945,7 @@ namespace ts { } return result; - function buildVisibleNodeList(declarations: Declaration[]) { + function buildVisibleNodeList(declarations: Declaration[] | undefined) { forEach(declarations, declaration => { const resultNode = getAnyImportSyntax(declaration) || declaration; if (setVisibility) { @@ -8020,6 +8124,15 @@ namespace ts { return result; } + function isGenericTypeWithUndefinedConstraint(type: Type) { + return !!(type.flags & TypeFlags.Instantiable) && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, TypeFlags.Undefined); + } + + function getNonUndefinedType(type: Type) { + const typeOrConstraint = someType(type, isGenericTypeWithUndefinedConstraint) ? mapType(type, t => t.flags & TypeFlags.Instantiable ? getBaseConstraintOrType(t) : t) : type; + return getTypeWithFacts(typeOrConstraint, TypeFacts.NEUndefined); + } + // Determine the control flow type associated with a destructuring declaration or assignment. The following // forms of destructuring are possible: // let { x } = obj; // BindingElement @@ -8121,7 +8234,7 @@ namespace ts { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) const name = declaration.propertyName || declaration.name; const indexType = getLiteralTypeFromPropertyName(name); - const declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, AccessFlags.ExpressionPosition), declaration.name); + const declaredType = getIndexedAccessType(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, AccessFlags.ExpressionPosition); type = getFlowTypeOfDestructuring(declaration, declaredType); } } @@ -8142,7 +8255,7 @@ namespace ts { else if (isArrayLikeType(parentType)) { const indexType = getLiteralType(index); const accessFlags = hasDefaultValue(declaration) ? AccessFlags.NoTupleBoundsCheck : 0; - const declaredType = getConstraintForLocation(getIndexedAccessTypeOrUndefined(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, declaration.name, accessFlags | AccessFlags.ExpressionPosition) || errorType, declaration.name); + const declaredType = getIndexedAccessTypeOrUndefined(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, declaration.name, accessFlags | AccessFlags.ExpressionPosition) || errorType; type = getFlowTypeOfDestructuring(declaration, declaredType); } else { @@ -8155,11 +8268,9 @@ namespace ts { if (getEffectiveTypeAnnotationNode(walkUpBindingElementsAndPatterns(declaration))) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & TypeFlags.Undefined) ? - getTypeWithFacts(type, TypeFacts.NEUndefined) : - type; + return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & TypeFlags.Undefined) ? getNonUndefinedType(type) : type; } - return widenTypeInferredFromInitializer(declaration, getUnionType([getTypeWithFacts(type, TypeFacts.NEUndefined), checkDeclarationInitializer(declaration)], UnionReduction.Subtype)); + return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration)], UnionReduction.Subtype)); } function getTypeForDeclarationFromJSDocComment(declaration: Node) { @@ -8331,12 +8442,32 @@ namespace ts { } function getDeclaringConstructor(symbol: Symbol) { + if (!symbol.declarations) { + return; + } for (const declaration of symbol.declarations) { const container = getThisContainer(declaration, /*includeArrowFunctions*/ false); if (container && (container.kind === SyntaxKind.Constructor || isJSConstructor(container))) { - return container; + return container as ConstructorDeclaration; } + }; + } + + /** Create a synthetic property access flow node after the last statement of the file */ + function getFlowTypeFromCommonJSExport(symbol: Symbol) { + const file = getSourceFileOfNode(symbol.declarations![0]); + const accessName = unescapeLeadingUnderscores(symbol.escapedName); + const areAllModuleExports = symbol.declarations!.every(d => isInJSFile(d) && isAccessExpression(d) && isModuleExportsAccessExpression(d.expression)); + const reference = areAllModuleExports + ? factory.createPropertyAccessExpression(factory.createPropertyAccessExpression(factory.createIdentifier("module"), factory.createIdentifier("exports")), accessName) + : factory.createPropertyAccessExpression(factory.createIdentifier("exports"), accessName); + if (areAllModuleExports) { + setParent((reference.expression as PropertyAccessExpression).expression, reference.expression); } + setParent(reference.expression, reference); + setParent(reference, file); + reference.flowNode = file.endFlowNode; + return getFlowTypeOfReference(reference, autoType, undefinedType); } function getFlowTypeInConstructor(symbol: Symbol, constructor: ConstructorDeclaration) { @@ -8356,7 +8487,10 @@ namespace ts { } function getFlowTypeOfProperty(reference: Node, prop: Symbol | undefined) { - const initialType = prop && (!isAutoTypedProperty(prop) || getEffectiveModifierFlags(prop.valueDeclaration) & ModifierFlags.Ambient) && getTypeOfPropertyInBaseClass(prop) || undefinedType; + const initialType = prop?.valueDeclaration + && (!isAutoTypedProperty(prop) || getEffectiveModifierFlags(prop.valueDeclaration) & ModifierFlags.Ambient) + && getTypeOfPropertyInBaseClass(prop) + || undefinedType; return getFlowTypeOfReference(reference, autoType, initialType); } @@ -8368,7 +8502,7 @@ namespace ts { if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - const containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + const containerObjectType = symbol.valueDeclaration && getJSContainerObjectType(symbol.valueDeclaration, symbol, container); return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } let type; @@ -8380,40 +8514,42 @@ namespace ts { type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol)!); } if (!type) { - let jsdocType: Type | undefined; let types: Type[] | undefined; - for (const declaration of symbol.declarations) { - const expression = (isBinaryExpression(declaration) || isCallExpression(declaration)) ? declaration : - isAccessExpression(declaration) ? isBinaryExpression(declaration.parent) ? declaration.parent : declaration : - undefined; - if (!expression) { - continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere - } + if (symbol.declarations) { + let jsdocType: Type | undefined; + for (const declaration of symbol.declarations) { + const expression = (isBinaryExpression(declaration) || isCallExpression(declaration)) ? declaration : + isAccessExpression(declaration) ? isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere + } - const kind = isAccessExpression(expression) - ? getAssignmentDeclarationPropertyAccessKind(expression) - : getAssignmentDeclarationKind(expression); - if (kind === AssignmentDeclarationKind.ThisProperty || isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) { - if (isDeclarationInConstructor(expression)) { - definedInConstructor = true; + const kind = isAccessExpression(expression) + ? getAssignmentDeclarationPropertyAccessKind(expression) + : getAssignmentDeclarationKind(expression); + if (kind === AssignmentDeclarationKind.ThisProperty || isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } } - else { - definedInMethod = true; + if (!isCallExpression(expression)) { + jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((isBinaryExpression(expression) || isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } - if (!isCallExpression(expression)) { - jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); - } - if (!jsdocType) { - (types || (types = [])).push((isBinaryExpression(expression) || isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); - } + type = jsdocType; } - type = jsdocType; if (!type) { if (!length(types)) { return errorType; // No types from any declarations :( } - let constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types!, symbol.declarations) : undefined; + let constructorTypes = definedInConstructor && symbol.declarations ? getConstructorDefinedThisAssignmentTypes(types!, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { const propType = getTypeOfPropertyInBaseClass(symbol); @@ -8427,7 +8563,7 @@ namespace ts { } } const widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); - if (filterType(widened, t => !!(t.flags & ~TypeFlags.Nullable)) === neverType) { + if (symbol.valueDeclaration && filterType(widened, t => !!(t.flags & ~TypeFlags.Nullable)) === neverType) { reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } @@ -8466,7 +8602,7 @@ namespace ts { errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type); } } - if (symbol.parent) { + if (symbol.parent?.valueDeclaration) { const typeNode = getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration); if (typeNode) { return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode), symbol.escapedName); @@ -8531,7 +8667,7 @@ namespace ts { // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because // it's unclear what that's supposed to mean, so it's probably a mistake. - if (getSourceFileOfNode(s.valueDeclaration) !== getSourceFileOfNode(exportedMember.valueDeclaration)) { + if (s.valueDeclaration && exportedMember.valueDeclaration && getSourceFileOfNode(s.valueDeclaration) !== getSourceFileOfNode(exportedMember.valueDeclaration)) { const unescapedName = unescapeLeadingUnderscores(s.escapedName); const exportedMemberName = tryCast(exportedMember.valueDeclaration, isNamedDeclaration)?.name || exportedMember.valueDeclaration; addRelatedInfo( @@ -8704,8 +8840,18 @@ namespace ts { return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors); } + function isGlobalSymbolConstructor(node: Node) { + const symbol = getSymbolOfNode(node); + const globalSymbol = getGlobalESSymbolConstructorTypeSymbol(/*reportErrors*/ false); + return globalSymbol && symbol && symbol === globalSymbol; + } + function widenTypeForVariableLikeDeclaration(type: Type | undefined, declaration: any, reportErrors?: boolean) { if (type) { + // TODO: If back compat with pre-3.0/4.0 libs isn't required, remove the following SymbolConstructor special case transforming `symbol` into `unique symbol` + if (type.flags & TypeFlags.ESSymbol && isGlobalSymbolConstructor(declaration.parent)) { + type = getESSymbolLikeTypeForNode(declaration); + } if (reportErrors) { reportErrorsFromWidening(declaration, type); } @@ -8757,7 +8903,7 @@ namespace ts { return links.type; } - function getTypeOfVariableOrParameterOrPropertyWorker(symbol: Symbol) { + function getTypeOfVariableOrParameterOrPropertyWorker(symbol: Symbol): Type { // Handle prototype property if (symbol.flags & SymbolFlags.Prototype) { return getTypeOfPrototypeProperty(symbol); @@ -8766,7 +8912,7 @@ namespace ts { if (symbol === requireSymbol) { return anyType; } - if (symbol.flags & SymbolFlags.ModuleExports) { + if (symbol.flags & SymbolFlags.ModuleExports && symbol.valueDeclaration) { const fileSymbol = getSymbolOfNode(getSourceFileOfNode(symbol.valueDeclaration)); const result = createSymbol(fileSymbol.flags, "exports" as __String); result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : []; @@ -8780,11 +8926,14 @@ namespace ts { return createAnonymousType(symbol, members, emptyArray, emptyArray, undefined, undefined); } // Handle catch clause variables + Debug.assertIsDefined(symbol.valueDeclaration); const declaration = symbol.valueDeclaration; if (isCatchClauseVariableDeclarationOrBindingElement(declaration)) { - const decl = declaration as VariableDeclaration; - if (!decl.type) return anyType; - const type = getTypeOfNode(decl.type); + const typeNode = getEffectiveTypeAnnotationNode(declaration); + if (typeNode === undefined) { + return anyType; + } + const type = getTypeOfNode(typeNode); // an errorType will make `checkTryStatement` issue an error return isTypeAny(type) || type === unknownType ? type : errorType; } @@ -8804,7 +8953,7 @@ namespace ts { } return reportCircularityError(symbol); } - let type: Type | undefined; + let type: Type; if (declaration.kind === SyntaxKind.ExportAssignment) { type = widenTypeForVariableLikeDeclaration(checkExpressionCached((declaration).expression), declaration); } @@ -8861,7 +9010,7 @@ namespace ts { type = getTypeOfEnumMember(symbol); } else if (isAccessor(declaration)) { - type = resolveTypeOfAccessors(symbol); + type = resolveTypeOfAccessors(symbol) || Debug.fail("Non-write accessor resolution must always produce a type"); } else { return Debug.fail("Unhandled declaration kind! " + Debug.formatSyntaxKind(declaration.kind) + " for " + Debug.formatSymbol(symbol)); @@ -8907,15 +9056,20 @@ namespace ts { function getTypeOfAccessors(symbol: Symbol): Type { const links = getSymbolLinks(symbol); - return links.type || (links.type = getTypeOfAccessorsWorker(symbol)); + return links.type || (links.type = getTypeOfAccessorsWorker(symbol) || Debug.fail("Read type of accessor must always produce a type")); + } + + function getTypeOfSetAccessor(symbol: Symbol): Type | undefined { + const links = getSymbolLinks(symbol); + return links.writeType || (links.writeType = getTypeOfAccessorsWorker(symbol, /*writing*/ true)); } - function getTypeOfAccessorsWorker(symbol: Symbol): Type { + function getTypeOfAccessorsWorker(symbol: Symbol, writing = false): Type | undefined { if (!pushTypeResolution(symbol, TypeSystemPropertyName.Type)) { return errorType; } - let type = resolveTypeOfAccessors(symbol); + let type = resolveTypeOfAccessors(symbol, writing); if (!popTypeResolution()) { type = anyType; @@ -8927,48 +9081,65 @@ namespace ts { return type; } - function resolveTypeOfAccessors(symbol: Symbol) { + function resolveTypeOfAccessors(symbol: Symbol, writing = false) { const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); + const setterType = getAnnotatedAccessorType(setter); + + // For write operations, prioritize type annotations on the setter + if (writing && setterType) { + return instantiateTypeIfNeeded(setterType, symbol); + } + // Else defer to the getter type + if (getter && isInJSFile(getter)) { const jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { - return jsDocType; + return instantiateTypeIfNeeded(jsDocType, symbol); } } - // First try to see if the user specified a return type on the get-accessor. - const getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - return getterReturnType; + + // Try to see if the user specified a return type on the get-accessor. + const getterType = getAnnotatedAccessorType(getter); + if (getterType) { + return instantiateTypeIfNeeded(getterType, symbol); } - else { - // If the user didn't specify a return type, try to use the set-accessor's parameter type. - const setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - return setterParameterType; + + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + if (setterType) { + return setterType; + } + + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + const returnTypeFromBody = getReturnTypeFromBody(getter); + return instantiateTypeIfNeeded(returnTypeFromBody, symbol); + } + + // Otherwise, fall back to 'any'. + if (setter) { + if (!isPrivateWithinAmbient(setter)) { + errorOrSuggestion(noImplicitAny, setter, Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); } - else { - // If there are no specified types, try to infer it from the body of the get accessor if it exists. - if (getter && getter.body) { - return getReturnTypeFromBody(getter); - } - // Otherwise, fall back to 'any'. - else { - if (setter) { - if (!isPrivateWithinAmbient(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 exist a getter as we are current checking either setter or getter in this function"); - if (!isPrivateWithinAmbient(getter)) { - errorOrSuggestion(noImplicitAny, getter, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } - } - return anyType; - } + return anyType; + } + else if (getter) { + Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } + return anyType; + } + return undefined; + + function instantiateTypeIfNeeded(type: Type, symbol: Symbol) { + if (getCheckFlags(symbol) & CheckFlags.Instantiated) { + const links = getSymbolLinks(symbol); + return instantiateType(type, links.mapper); } + + return type; } } @@ -9039,14 +9210,15 @@ namespace ts { const links = getSymbolLinks(symbol); if (!links.type) { const targetSymbol = resolveAlias(symbol); - + const exportSymbol = symbol.declarations && getTargetOfAliasDeclaration(getDeclarationOfAliasSymbol(symbol)!, /*dontResolveAlias*/ true); // It only makes sense to get the type of a value symbol. If the result of resolving // the alias is not a value, then it has no type. To get the type associated with a // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & SymbolFlags.Value - ? getTypeOfSymbol(targetSymbol) + links.type = exportSymbol?.declarations && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations!.length ? getFlowTypeFromCommonJSExport(exportSymbol) + : isDuplicatedCommonJSExport(symbol.declarations) ? autoType + : targetSymbol.flags & SymbolFlags.Value ? getTypeOfSymbol(targetSymbol) : errorType; } return links.type; @@ -9096,6 +9268,16 @@ namespace ts { return links.type; } + function getSetAccessorTypeOfSymbol(symbol: Symbol): Type { + if (symbol.flags & SymbolFlags.Accessor) { + const type = getTypeOfSetAccessor(symbol); + if (type) { + return type; + } + } + return getTypeOfSymbol(symbol); + } + function getTypeOfSymbol(symbol: Symbol): Type { const checkFlags = getCheckFlags(symbol); if (checkFlags & CheckFlags.DeferredType) { @@ -9174,7 +9356,7 @@ namespace ts { if (assignmentKind === AssignmentDeclarationKind.Prototype || assignmentKind === AssignmentDeclarationKind.PrototypeProperty) { const symbol = getSymbolOfNode(node.left); if (symbol && symbol.parent && !findAncestor(symbol.parent.valueDeclaration, d => node === d)) { - node = symbol.parent.valueDeclaration; + node = symbol.parent.valueDeclaration!; } } } @@ -9182,7 +9364,6 @@ namespace ts { return undefined; } switch (node.kind) { - case SyntaxKind.VariableStatement: case SyntaxKind.ClassDeclaration: case SyntaxKind.ClassExpression: case SyntaxKind.InterfaceDeclaration: @@ -9202,7 +9383,7 @@ namespace ts { case SyntaxKind.JSDocEnumTag: case SyntaxKind.JSDocCallbackTag: case SyntaxKind.MappedType: - case SyntaxKind.ConditionalType: + case SyntaxKind.ConditionalType: { const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); if (node.kind === SyntaxKind.MappedType) { return append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode((node).typeParameter))); @@ -9210,20 +9391,24 @@ namespace ts { else if (node.kind === SyntaxKind.ConditionalType) { return concatenate(outerTypeParameters, getInferTypeParameters(node)); } - else if (node.kind === SyntaxKind.VariableStatement && !isInJSFile(node)) { - break; - } const outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, getEffectiveTypeParameterDeclarations(node)); const thisType = includeThisTypes && (node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression || node.kind === SyntaxKind.InterfaceDeclaration || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node as ClassLikeDeclaration | InterfaceDeclaration)).thisType; return thisType ? append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; + } case SyntaxKind.JSDocParameterTag: const paramSymbol = getParameterSymbolFromJSDoc(node as JSDocParameterTag); if (paramSymbol) { - node = paramSymbol.valueDeclaration; + node = paramSymbol.valueDeclaration!; } break; + case SyntaxKind.JSDocComment: { + const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + return (node as JSDoc).tags + ? appendTypeParameters(outerTypeParameters, flatMap((node as JSDoc).tags, t => isJSDocTemplateTag(t) ? t.typeParameters : undefined)) + : outerTypeParameters; + } } } } @@ -9238,6 +9423,9 @@ namespace ts { // The local type parameters are the combined set of type parameters from all declarations of the class, // interface, or type alias. function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol: Symbol): TypeParameter[] | undefined { + if (!symbol.declarations) { + return; + } let result: TypeParameter[] | undefined; for (const node of symbol.declarations) { if (node.kind === SyntaxKind.InterfaceDeclaration || @@ -9344,7 +9532,9 @@ namespace ts { ctorReturn = getReturnTypeOfSignature(ctorSig[0]); } } - addRelatedInfo(err, createDiagnosticForNode(baseConstructorType.symbol.declarations[0], Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + if (baseConstructorType.symbol.declarations) { + addRelatedInfo(err, createDiagnosticForNode(baseConstructorType.symbol.declarations[0], Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } } return type.resolvedBaseConstructorType = errorType; } @@ -9355,17 +9545,19 @@ namespace ts { function getImplementsTypes(type: InterfaceType): BaseType[] { let resolvedImplementsTypes: BaseType[] = emptyArray; - for (const declaration of type.symbol.declarations) { - const implementsTypeNodes = getEffectiveImplementsTypeNodes(declaration as ClassLikeDeclaration); - if (!implementsTypeNodes) continue; - for (const node of implementsTypeNodes) { - const implementsType = getTypeFromTypeNode(node); - if (implementsType !== errorType) { - if (resolvedImplementsTypes === emptyArray) { - resolvedImplementsTypes = [implementsType]; - } - else { - resolvedImplementsTypes.push(implementsType); + if (type.symbol.declarations) { + for (const declaration of type.symbol.declarations) { + const implementsTypeNodes = getEffectiveImplementsTypeNodes(declaration as ClassLikeDeclaration); + if (!implementsTypeNodes) continue; + for (const node of implementsTypeNodes) { + const implementsType = getTypeFromTypeNode(node); + if (implementsType !== errorType) { + if (resolvedImplementsTypes === emptyArray) { + resolvedImplementsTypes = [implementsType]; + } + else { + resolvedImplementsTypes.push(implementsType); + } } } } @@ -9394,7 +9586,7 @@ namespace ts { else { Debug.fail("type must be class or interface"); } - if (!popTypeResolution()) { + if (!popTypeResolution() && type.symbol.declarations) { for (const declaration of type.symbol.declarations) { if (declaration.kind === SyntaxKind.ClassDeclaration || declaration.kind === SyntaxKind.InterfaceDeclaration) { reportCircularBaseType(declaration, type); @@ -9496,27 +9688,29 @@ namespace ts { function resolveBaseTypesOfInterface(type: InterfaceType): void { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - for (const declaration of type.symbol.declarations) { - if (declaration.kind === SyntaxKind.InterfaceDeclaration && getInterfaceBaseTypeNodes(declaration)) { - for (const node of getInterfaceBaseTypeNodes(declaration)!) { - const baseType = getReducedType(getTypeFromTypeNode(node)); - if (baseType !== errorType) { - if (isValidBaseType(baseType)) { - if (type !== baseType && !hasBaseType(baseType, type)) { - if (type.resolvedBaseTypes === emptyArray) { - type.resolvedBaseTypes = [baseType]; + if (type.symbol.declarations) { + for (const declaration of type.symbol.declarations) { + if (declaration.kind === SyntaxKind.InterfaceDeclaration && getInterfaceBaseTypeNodes(declaration)) { + for (const node of getInterfaceBaseTypeNodes(declaration)!) { + const baseType = getReducedType(getTypeFromTypeNode(node)); + if (baseType !== errorType) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } } else { - type.resolvedBaseTypes.push(baseType); + reportCircularBaseType(declaration, type); } } else { - reportCircularBaseType(declaration, type); + error(node, Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); } } - else { - error(node, Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members); - } } } } @@ -9531,6 +9725,9 @@ namespace ts { * and if none of the base interfaces have a "this" type. */ function isThislessInterface(symbol: Symbol): boolean { + if (!symbol.declarations) { + return true; + } for (const declaration of symbol.declarations) { if (declaration.kind === SyntaxKind.InterfaceDeclaration) { if (declaration.flags & NodeFlags.ContainsThis) { @@ -9557,7 +9754,7 @@ namespace ts { const originalLinks = links; if (!links.declaredType) { const kind = symbol.flags & SymbolFlags.Class ? ObjectFlags.Class : ObjectFlags.Interface; - const merged = mergeJSSymbols(symbol, getAssignedClassSymbol(symbol.valueDeclaration)); + const merged = mergeJSSymbols(symbol, symbol.valueDeclaration && getAssignedClassSymbol(symbol.valueDeclaration)); if (merged) { // note:we overwrite links because we just cloned the symbol symbol = links = merged; @@ -9597,7 +9794,7 @@ namespace ts { return errorType; } - const declaration = Debug.checkDefined(find(symbol.declarations, isTypeAlias), "Type alias symbol with no valid declaration found"); + const declaration = Debug.checkDefined(symbol.declarations?.find(isTypeAlias), "Type alias symbol with no valid declaration found"); const typeNode = isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. let type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; @@ -9659,14 +9856,16 @@ namespace ts { return links.enumKind; } let hasNonLiteralMember = false; - for (const declaration of symbol.declarations) { - if (declaration.kind === SyntaxKind.EnumDeclaration) { - for (const member of (declaration).members) { - if (member.initializer && isStringLiteralLike(member.initializer)) { - return links.enumKind = EnumKind.Literal; - } - if (!isLiteralEnumMember(member)) { - hasNonLiteralMember = true; + if (symbol.declarations) { + for (const declaration of symbol.declarations) { + if (declaration.kind === SyntaxKind.EnumDeclaration) { + for (const member of (declaration).members) { + if (member.initializer && isStringLiteralLike(member.initializer)) { + return links.enumKind = EnumKind.Literal; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; + } } } } @@ -9686,13 +9885,15 @@ namespace ts { if (getEnumKind(symbol) === EnumKind.Literal) { enumCount++; const memberTypeList: Type[] = []; - for (const declaration of symbol.declarations) { - if (declaration.kind === SyntaxKind.EnumDeclaration) { - for (const member of (declaration).members) { - const value = getEnumMemberValue(member); - const memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member))); - getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + if (symbol.declarations) { + for (const declaration of symbol.declarations) { + if (declaration.kind === SyntaxKind.EnumDeclaration) { + for (const member of (declaration).members) { + const value = getEnumMemberValue(member); + const memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member))); + getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); + } } } } @@ -9859,7 +10060,7 @@ namespace ts { } function isStaticPrivateIdentifierProperty(s: Symbol): boolean { - return !!s.valueDeclaration && isPrivateIdentifierPropertyDeclaration(s.valueDeclaration) && hasSyntacticModifier(s.valueDeclaration, ModifierFlags.Static); + return !!s.valueDeclaration && isPrivateIdentifierClassElementDeclaration(s.valueDeclaration) && hasSyntacticModifier(s.valueDeclaration, ModifierFlags.Static); } function resolveDeclaredMembers(type: InterfaceType): InterfaceTypeWithDeclaredMembers { @@ -10213,7 +10414,8 @@ namespace ts { sig.resolvedMinArgumentCount = undefined; sig.target = undefined; sig.mapper = undefined; - sig.unionSignatures = undefined; + sig.compositeSignatures = undefined; + sig.compositeKind = undefined; return sig; } @@ -10222,13 +10424,15 @@ namespace ts { /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & SignatureFlags.PropagatingFlags); result.target = sig.target; result.mapper = sig.mapper; - result.unionSignatures = sig.unionSignatures; + result.compositeSignatures = sig.compositeSignatures; + result.compositeKind = sig.compositeKind; return result; } function createUnionSignature(signature: Signature, unionSignatures: Signature[]) { const result = cloneSignature(signature); - result.unionSignatures = unionSignatures; + result.compositeSignatures = unionSignatures; + result.compositeKind = TypeFlags.Union; result.target = undefined; result.mapper = undefined; return result; @@ -10392,7 +10596,7 @@ namespace ts { if (signatures !== masterList) { const signature = signatures[0]; Debug.assert(!!signature, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); - results = signature.typeParameters && some(results, s => !!s.typeParameters && !compareTypeParametersIdentical(signature.typeParameters!, s.typeParameters)) ? undefined : map(results, sig => combineSignaturesOfUnionMembers(sig, signature)); + results = !!signature.typeParameters && some(results, s => !!s.typeParameters && !compareTypeParametersIdentical(signature.typeParameters, s.typeParameters)) ? undefined : map(results, sig => combineSignaturesOfUnionMembers(sig, signature)); if (!results) { break; } @@ -10403,10 +10607,13 @@ namespace ts { return result || emptyArray; } - function compareTypeParametersIdentical(sourceParams: readonly TypeParameter[], targetParams: readonly TypeParameter[]): boolean { - if (sourceParams.length !== targetParams.length) { + function compareTypeParametersIdentical(sourceParams: readonly TypeParameter[] | undefined, targetParams: readonly TypeParameter[] | undefined): boolean { + if (length(sourceParams) !== length(targetParams)) { return false; } + if (!sourceParams || !targetParams) { + return true; + } const mapper = createTypeMapper(targetParams, sourceParams); for (let i = 0; i < sourceParams.length; i++) { @@ -10502,9 +10709,10 @@ namespace ts { minArgCount, (left.flags | right.flags) & SignatureFlags.PropagatingFlags ); - result.unionSignatures = concatenate(left.unionSignatures || [left], [right]); + result.compositeKind = TypeFlags.Union; + result.compositeSignatures = concatenate(left.compositeKind !== TypeFlags.Intersection && left.compositeSignatures || [left], [right]); if (paramMapper) { - result.mapper = left.mapper && left.unionSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; + result.mapper = left.compositeKind !== TypeFlags.Intersection && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; } return result; } @@ -10643,6 +10851,7 @@ namespace ts { // Combinations of function, class, enum and module let members = emptySymbols; let stringIndexInfo: IndexInfo | undefined; + let numberIndexInfo: IndexInfo | undefined; if (symbol.exports) { members = getExportsOfSymbol(symbol); if (symbol === globalThisSymbol) { @@ -10655,20 +10864,32 @@ namespace ts { members = varsOnly; } } + let baseConstructorIndexInfo: IndexInfo | undefined; setStructuredTypeMembers(type, members, emptyArray, emptyArray, undefined, undefined); if (symbol.flags & SymbolFlags.Class) { const classType = getDeclaredTypeOfClassOrInterface(symbol); const baseConstructorType = getBaseConstructorTypeOfClass(classType); if (baseConstructorType.flags & (TypeFlags.Object | TypeFlags.Intersection | TypeFlags.TypeVariable)) { - members = createSymbolTable(getNamedMembers(members)); + members = createSymbolTable(getNamedOrIndexSignatureMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } else if (baseConstructorType === anyType) { - stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + baseConstructorIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + } + } + + const indexSymbol = getIndexSymbolFromSymbolTable(members); + if (indexSymbol) { + stringIndexInfo = getIndexInfoOfIndexSymbol(indexSymbol, IndexKind.String); + numberIndexInfo = getIndexInfoOfIndexSymbol(indexSymbol, IndexKind.Number); + } + else { + stringIndexInfo = baseConstructorIndexInfo; + if (symbol.flags & SymbolFlags.Enum && (getDeclaredTypeOfSymbol(symbol).flags & TypeFlags.Enum || + some(type.properties, prop => !!(getTypeOfSymbol(prop).flags & TypeFlags.NumberLike)))) { + numberIndexInfo = enumNumberIndexInfo; } } - const numberIndexInfo = symbol.flags & SymbolFlags.Enum && (getDeclaredTypeOfSymbol(symbol).flags & TypeFlags.Enum || - some(type.properties, prop => !!(getTypeOfSymbol(prop).flags & TypeFlags.NumberLike))) ? enumNumberIndexInfo : undefined; setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); // We resolve the members before computing the signatures because a signature may use // typeof with a qualified name expression that circularly references the type we are @@ -10696,6 +10917,21 @@ namespace ts { } } + type ReplaceableIndexedAccessType = IndexedAccessType & { objectType: TypeParameter, indexType: TypeParameter }; + function replaceIndexedAccess(instantiable: Type, type: ReplaceableIndexedAccessType, replacement: Type) { + // map type.indexType to 0 + // map type.objectType to `[TReplacement]` + // thus making the indexed access `[TReplacement][0]` or `TReplacement` + return instantiateType(instantiable, createTypeMapper([type.indexType, type.objectType], [getLiteralType(0), createTupleType([replacement])])); + } + + function getIndexInfoOfIndexSymbol(indexSymbol: Symbol, indexKind: IndexKind) { + const declaration = getIndexDeclarationOfIndexSymbol(indexSymbol, indexKind); + if (!declaration) return undefined; + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, + hasEffectiveModifier(declaration, ModifierFlags.Readonly), declaration); + } + function resolveReverseMappedTypeMembers(type: ReverseMappedType) { const indexInfo = getIndexInfoOfType(type.source, IndexKind.String); const modifiers = getMappedTypeModifiers(type.mappedType); @@ -10709,8 +10945,21 @@ namespace ts { inferredProp.declarations = prop.declarations; inferredProp.nameType = getSymbolLinks(prop).nameType; inferredProp.propertyType = getTypeOfSymbol(prop); - inferredProp.mappedType = type.mappedType; - inferredProp.constraintType = type.constraintType; + if (type.constraintType.type.flags & TypeFlags.IndexedAccess + && (type.constraintType.type as IndexedAccessType).objectType.flags & TypeFlags.TypeParameter + && (type.constraintType.type as IndexedAccessType).indexType.flags & TypeFlags.TypeParameter) { + // A reverse mapping of `{[K in keyof T[K_1]]: T[K_1]}` is the same as that of `{[K in keyof T]: T}`, since all we care about is + // inferring to the "type parameter" (or indexed access) shared by the constraint and template. So, to reduce the number of + // type identities produced, we simplify such indexed access occurences + const newTypeParam = (type.constraintType.type as IndexedAccessType).objectType; + const newMappedType = replaceIndexedAccess(type.mappedType, type.constraintType.type as ReplaceableIndexedAccessType, newTypeParam); + inferredProp.mappedType = newMappedType as MappedType; + inferredProp.constraintType = getIndexType(newTypeParam) as IndexType; + } + else { + inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; + } members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, undefined); @@ -11398,6 +11647,7 @@ namespace ts { let optionalFlag = isUnion ? SymbolFlags.None : SymbolFlags.Optional; let syntheticFlag = CheckFlags.SyntheticMethod; let checkFlags = 0; + let mergedInstantiations = false; for (const current of containingType.types) { const type = getApparentType(current); if (!(type === errorType || type.flags & TypeFlags.Never)) { @@ -11414,13 +11664,25 @@ namespace ts { singleProp = prop; } else if (prop !== singleProp) { - if (!propSet) { - propSet = new Map(); - propSet.set(getSymbolId(singleProp), singleProp); + const isInstantiation = (getTargetSymbol(prop) || prop) === (getTargetSymbol(singleProp) || singleProp); + // If the symbols are instances of one another with identical types - consider the symbols + // equivalent and just use the first one, which thus allows us to avoid eliding private + // members when intersecting a (this-)instantiations of a class with it's raw base or another instance + if (isInstantiation && compareProperties(singleProp, prop, (a, b) => a === b ? Ternary.True : Ternary.False) === Ternary.True) { + // If we merged instantiations of a generic type, we replicate the symbol parent resetting behavior we used + // to do when we recorded multiple distinct symbols so that we still get, eg, `Array.length` printed + // back and not `Array.length` when we're looking at a `.length` access on a `string[] | number[]` + mergedInstantiations = !!singleProp.parent && !!length(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(singleProp.parent)); } - const id = getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + else { + if (!propSet) { + propSet = new Map(); + propSet.set(getSymbolId(singleProp), singleProp); + } + const id = getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } } checkFlags |= (isReadonlySymbol(prop) ? CheckFlags.Readonly : 0) | @@ -11438,7 +11700,7 @@ namespace ts { checkFlags |= CheckFlags.WritePartial | (indexInfo.isReadonly ? CheckFlags.Readonly : 0); indexTypes = append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } - else if (isObjectLiteralType(type)) { + else if (isObjectLiteralType(type) && !(getObjectFlags(type) & ObjectFlags.ContainsSpread)) { checkFlags |= CheckFlags.WritePartial; indexTypes = append(indexTypes, undefinedType); } @@ -11454,7 +11716,19 @@ namespace ts { return undefined; } if (!propSet && !(checkFlags & CheckFlags.ReadPartial) && !indexTypes) { - return singleProp; + if (mergedInstantiations) { + // No symbol from a union/intersection should have a `.parent` set (since unions/intersections don't act as symbol parents) + // Unless that parent is "reconstituted" from the "first value declaration" on the symbol (which is likely different than its instantiated parent!) + // They also have a `.containingType` set, which affects some services endpoints behavior, like `getRootSymbol` + const clone = createSymbolWithType(singleProp, (singleProp as TransientSymbol).type); + clone.parent = singleProp.valueDeclaration?.symbol?.parent; + clone.containingType = containingType; + clone.mapper = (singleProp as TransientSymbol).mapper; + return clone; + } + else { + return singleProp; + } } const props = propSet ? arrayFrom(propSet.values()) : [singleProp]; let declarations: Declaration[] | undefined; @@ -11499,7 +11773,7 @@ namespace ts { } } - result.declarations = declarations!; + result.declarations = declarations; result.nameType = nameType; if (propTypes.length > 2) { // When `propTypes` has the potential to explode in size when normalized, defer normalization until absolutely needed @@ -11589,7 +11863,7 @@ namespace ts { } function elaborateNeverIntersection(errorInfo: DiagnosticMessageChain | undefined, type: Type) { - if (getObjectFlags(type) & ObjectFlags.IsNeverIntersection) { + if (type.flags & TypeFlags.Intersection && getObjectFlags(type) & ObjectFlags.IsNeverIntersection) { const neverProp = find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); if (neverProp) { return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, @@ -11684,7 +11958,8 @@ namespace ts { const propTypes: Type[] = []; for (const prop of getPropertiesOfType(type)) { if (kind === IndexKind.String || isNumericLiteralName(prop.escapedName)) { - propTypes.push(getTypeOfSymbol(prop)); + const propType = getTypeOfSymbol(prop); + propTypes.push(prop.flags & SymbolFlags.Optional ? getTypeWithFacts(propType, TypeFacts.NEUndefined) : propType); } } if (kind === IndexKind.String) { @@ -11758,6 +12033,10 @@ namespace ts { return false; } + function isOptionalPropertyDeclaration(node: Declaration) { + return isPropertyDeclaration(node) && node.questionToken; + } + function isOptionalJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag { if (!isJSDocPropertyLikeTag(node)) { return false; @@ -11934,8 +12213,7 @@ namespace ts { // should be attached to a function declaration or expression if (!(isInJSFile(node) && isFunctionLikeDeclaration(node))) return undefined; const typeTag = getJSDocTypeTag(node); - const signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); - return signature && getErasedSignature(signature); + return typeTag?.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); } function getReturnTypeOfTypeTag(node: SignatureDeclaration | JSDocSignature) { @@ -11979,7 +12257,7 @@ namespace ts { } function getSignaturesOfSymbol(symbol: Symbol | undefined): Signature[] { - if (!symbol) return emptyArray; + if (!symbol || !symbol.declarations) return emptyArray; const result: Signature[] = []; for (let i = 0; i < symbol.declarations.length; i++) { const decl = symbol.declarations[i]; @@ -12022,8 +12300,8 @@ namespace ts { const targetTypePredicate = getTypePredicateOfSignature(signature.target); signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper!) : noTypePredicate; } - else if (signature.unionSignatures) { - signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; + else if (signature.compositeSignatures) { + signature.resolvedTypePredicate = getUnionOrIntersectionTypePredicate(signature.compositeSignatures, signature.compositeKind) || noTypePredicate; } else { const type = signature.declaration && getEffectiveReturnTypeNode(signature.declaration); @@ -12052,13 +12330,17 @@ namespace ts { findIndex(signature.parameters, p => p.escapedName === parameterName.escapedText), type); } + function getUnionOrIntersectionType(types: Type[], kind: TypeFlags | undefined, unionReduction?: UnionReduction) { + return kind !== TypeFlags.Intersection ? getUnionType(types, unionReduction) : getIntersectionType(types); + } + function getReturnTypeOfSignature(signature: Signature): Type { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, TypeSystemPropertyName.ResolvedReturnType)) { return errorType; } let type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : - signature.unionSignatures ? instantiateType(getUnionType(map(signature.unionSignatures, getReturnTypeOfSignature), UnionReduction.Subtype), signature.mapper) : + signature.compositeSignatures ? instantiateType(getUnionOrIntersectionType(map(signature.compositeSignatures, getReturnTypeOfSignature), signature.compositeKind, UnionReduction.Subtype), signature.mapper) : getReturnTypeFromAnnotation(signature.declaration!) || (nodeIsMissing((signature.declaration).body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (signature.flags & SignatureFlags.IsInnerCallChain) { @@ -12199,9 +12481,20 @@ namespace ts { function getBaseSignature(signature: Signature) { const typeParameters = signature.typeParameters; if (typeParameters) { + if (signature.baseSignatureCache) { + return signature.baseSignatureCache; + } const typeEraser = createTypeEraser(typeParameters); - const baseConstraints = map(typeParameters, tp => instantiateType(getBaseConstraintOfType(tp), typeEraser) || unknownType); - return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); + const baseConstraintMapper = createTypeMapper(typeParameters, map(typeParameters, tp => getConstraintOfTypeParameter(tp) || unknownType)); + let baseConstraints: readonly Type[] = map(typeParameters, tp => instantiateType(tp, baseConstraintMapper) || unknownType); + // Run N type params thru the immediate constraint mapper up to N times + // This way any noncircular interdependent type parameters are definitely resolved to their external dependencies + for (let i = 0; i < typeParameters.length - 1; i++) { + baseConstraints = instantiateTypes(baseConstraints, baseConstraintMapper); + } + // and then apply a type eraser to remove any remaining circularly dependent type parameters + baseConstraints = instantiateTypes(baseConstraints, typeEraser); + return signature.baseSignatureCache = instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true); } return signature; } @@ -12226,13 +12519,26 @@ namespace ts { } function getIndexSymbol(symbol: Symbol): Symbol | undefined { - return symbol.members!.get(InternalSymbolName.Index); + return symbol.members ? getIndexSymbolFromSymbolTable(symbol.members) : undefined; + } + + function getIndexSymbolFromSymbolTable(symbolTable: SymbolTable): Symbol | undefined { + return symbolTable.get(InternalSymbolName.Index); + } + + function getIndexDeclarationOfSymbol(symbol: Symbol | undefined, kind: IndexKind): IndexSignatureDeclaration | undefined { + const indexSymbol = symbol && getIndexSymbol(symbol); + return indexSymbol && getIndexDeclarationOfIndexSymbol(indexSymbol, kind); + } + + function getIndexDeclarationOfSymbolTable(symbolTable: SymbolTable | undefined, kind: IndexKind): IndexSignatureDeclaration | undefined { + const indexSymbol = symbolTable && getIndexSymbolFromSymbolTable(symbolTable); + return indexSymbol && getIndexDeclarationOfIndexSymbol(indexSymbol, kind); } - function getIndexDeclarationOfSymbol(symbol: Symbol, kind: IndexKind): IndexSignatureDeclaration | undefined { + function getIndexDeclarationOfIndexSymbol(indexSymbol: Symbol, kind: IndexKind): IndexSignatureDeclaration | undefined { const syntaxKind = kind === IndexKind.Number ? SyntaxKind.NumberKeyword : SyntaxKind.StringKeyword; - const indexSymbol = getIndexSymbol(symbol); - if (indexSymbol) { + if (indexSymbol?.declarations) { for (const decl of indexSymbol.declarations) { const node = cast(decl, isIndexSignatureDeclaration); if (node.parameters.length === 1) { @@ -12266,7 +12572,7 @@ namespace ts { function getInferredTypeParameterConstraint(typeParameter: TypeParameter) { let inferences: Type[] | undefined; - if (typeParameter.symbol) { + if (typeParameter.symbol?.declarations) { for (const declaration of typeParameter.symbol.declarations) { if (declaration.parent.kind === SyntaxKind.InferType) { // When an 'infer T' declaration is immediately contained in a type reference node @@ -12314,6 +12620,19 @@ namespace ts { else if (grandParent.kind === SyntaxKind.TypeParameter && grandParent.parent.kind === SyntaxKind.MappedType) { inferences = append(inferences, keyofConstraintType); } + // When an 'infer T' declaration is the template of a mapped type, and that mapped type is the extends + // clause of a conditional whose check type is also a mapped type, give it a constraint equal to the template + // of the check type's mapped type + else if (grandParent.kind === SyntaxKind.MappedType && (grandParent as MappedTypeNode).type && + skipParentheses((grandParent as MappedTypeNode).type!) === declaration.parent && grandParent.parent.kind === SyntaxKind.ConditionalType && + (grandParent.parent as ConditionalTypeNode).extendsType === grandParent && (grandParent.parent as ConditionalTypeNode).checkType.kind === SyntaxKind.MappedType && + ((grandParent.parent as ConditionalTypeNode).checkType as MappedTypeNode).type) { + const checkMappedType = (grandParent.parent as ConditionalTypeNode).checkType as MappedTypeNode; + const nodeType = getTypeFromTypeNode(checkMappedType.type!); + inferences = append(inferences, instantiateType(nodeType, + makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfNode(checkMappedType.typeParameter)), checkMappedType.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType.typeParameter.constraint) : keyofConstraintType) + )); + } } } } @@ -12539,12 +12858,22 @@ namespace ts { typeParameters.length); return errorType; } + // We refrain from associating a local type alias with an instantiation of a top-level type alias + // because the local alias may end up being referenced in an inferred return type where it is not + // accessible--which in turn may lead to a large structural expansion of the type when generating + // a .d.ts file. See #43622 for an example. const aliasSymbol = getAliasSymbolForTypeNode(node); - return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + const newAliasSymbol = aliasSymbol && (isLocalTypeAlias(symbol) || !isLocalTypeAlias(aliasSymbol)) ? aliasSymbol : undefined; + return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), newAliasSymbol, getTypeArgumentsForAliasSymbol(newAliasSymbol)); } return checkNoTypeArguments(node, symbol) ? type : errorType; } + function isLocalTypeAlias(symbol: Symbol) { + const declaration = symbol.declarations?.find(isTypeAlias); + return !!(declaration && getContainingFunction(declaration)); + } + function getTypeReferenceName(node: TypeReferenceType): EntityNameOrEntityNameExpression | undefined { switch (node.kind) { case SyntaxKind.TypeReference: @@ -12649,9 +12978,17 @@ namespace ts { function getConditionalFlowTypeOfType(type: Type, node: Node) { let constraints: Type[] | undefined; + let covariant = true; while (node && !isStatement(node) && node.kind !== SyntaxKind.JSDocComment) { const parent = node.parent; - if (parent.kind === SyntaxKind.ConditionalType && node === (parent).trueType) { + // only consider variance flipped by parameter locations - `keyof` types would usually be considered variance inverting, but + // often get used in indexed accesses where they behave sortof invariantly, but our checking is lax + if (parent.kind === SyntaxKind.Parameter) { + covariant = !covariant; + } + // Always substitute on type parameters, regardless of variance, since even + // in contravariant positions, they may rely on substituted constraints to be valid + if ((covariant || type.flags & TypeFlags.TypeVariable) && parent.kind === SyntaxKind.ConditionalType && node === (parent).trueType) { const constraint = getImpliedConstraint(type, (parent).checkType, (parent).extendsType); if (constraint) { constraints = append(constraints, constraint); @@ -12781,12 +13118,14 @@ namespace ts { function getTypeDeclaration(symbol: Symbol): Declaration | undefined { const declarations = symbol.declarations; - for (const declaration of declarations) { - switch (declaration.kind) { - case SyntaxKind.ClassDeclaration: - case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.EnumDeclaration: - return declaration; + if (declarations) { + for (const declaration of declarations) { + switch (declaration.kind) { + case SyntaxKind.ClassDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.EnumDeclaration: + return declaration; + } } } } @@ -12842,6 +13181,10 @@ namespace ts { return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol" as __String, reportErrors)); } + function getGlobalESSymbolConstructorTypeSymbol(reportErrors: boolean) { + return deferredGlobalESSymbolConstructorTypeSymbol || (deferredGlobalESSymbolConstructorTypeSymbol = getGlobalTypeSymbol("SymbolConstructor" as __String, reportErrors)); + } + function getGlobalESSymbolType(reportErrors: boolean) { return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol" as __String, /*arity*/ 0, reportErrors)) || emptyObjectType; } @@ -13317,7 +13660,12 @@ namespace ts { return includes; } - function removeSubtypes(types: Type[], hasObjectTypes: boolean): boolean { + function removeSubtypes(types: Type[], hasObjectTypes: boolean): Type[] | undefined { + const id = getTypeListId(types); + const match = subtypeReductionCache.get(id); + if (match) { + return match; + } // We assume that redundant primitive types have already been removed from the types array and that there // are no any and unknown types in the array. Thus, the only possible supertypes for primitive types are empty // object types, and if none of those are present we can exclude primitive types from the subtype check. @@ -13329,6 +13677,13 @@ namespace ts { i--; const source = types[i]; if (hasEmptyObject || source.flags & TypeFlags.StructuredOrInstantiable) { + // Find the first property with a unit type, if any. When constituents have a property by the same name + // but of a different unit type, we can quickly disqualify them from subtype checks. This helps subtype + // reduction of large discriminated union types. + const keyProperty = source.flags & (TypeFlags.Object | TypeFlags.Intersection | TypeFlags.InstantiableNonPrimitive) ? + find(getPropertiesOfType(source), p => isUnitType(getTypeOfSymbol(p))) : + undefined; + const keyPropertyType = keyProperty && getRegularTypeOfLiteralType(getTypeOfSymbol(keyProperty)); for (const target of types) { if (source !== target) { if (count === 100000) { @@ -13340,10 +13695,16 @@ namespace ts { if (estimatedCount > 1000000) { tracing?.instant(tracing.Phase.CheckTypes, "removeSubtypes_DepthLimit", { typeIds: types.map(t => t.id) }); error(currentNode, Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); - return false; + return undefined; } } count++; + if (keyProperty && target.flags & (TypeFlags.Object | TypeFlags.Intersection | TypeFlags.InstantiableNonPrimitive)) { + const t = getTypeOfPropertyOfType(target, keyProperty.escapedName); + if (t && isUnitType(t) && getRegularTypeOfLiteralType(t) !== keyPropertyType) { + continue; + } + } if (isTypeRelatedTo(source, target, strictSubtypeRelation) && ( !(getObjectFlags(getTargetType(source)) & ObjectFlags.Class) || !(getObjectFlags(getTargetType(target)) & ObjectFlags.Class) || @@ -13355,10 +13716,11 @@ namespace ts { } } } - return true; + subtypeReductionCache.set(id, types); + return types; } - function removeRedundantLiteralTypes(types: Type[], includes: TypeFlags) { + function removeRedundantLiteralTypes(types: Type[], includes: TypeFlags, reduceVoidUndefined: boolean) { let i = types.length; while (i > 0) { i--; @@ -13369,7 +13731,7 @@ namespace ts { flags & TypeFlags.NumberLiteral && includes & TypeFlags.Number || flags & TypeFlags.BigIntLiteral && includes & TypeFlags.BigInt || flags & TypeFlags.UniqueESSymbol && includes & TypeFlags.ESSymbol || - flags & TypeFlags.Undefined && includes & TypeFlags.Void || + reduceVoidUndefined && flags & TypeFlags.Undefined && includes & TypeFlags.Void || isFreshLiteralType(t) && containsType(types, (t).regularType); if (remove) { orderedRemoveItemAt(types, i); @@ -13400,7 +13762,7 @@ namespace ts { if (t.flags & TypeFlags.Union) { const origin = (t).origin; if (t.aliasSymbol || origin && !(origin.flags & TypeFlags.Union)) { - namedUnions.push(t); + pushIfUnique(namedUnions, t); } else if (origin && origin.flags & TypeFlags.Union) { addNamedUnions(namedUnions, (origin).types); @@ -13429,22 +13791,21 @@ namespace ts { if (types.length === 1) { return types[0]; } - const typeSet: Type[] = []; + let typeSet: Type[] | undefined = []; const includes = addTypesToUnion(typeSet, 0, types); if (unionReduction !== UnionReduction.None) { if (includes & TypeFlags.AnyOrUnknown) { return includes & TypeFlags.Any ? includes & TypeFlags.IncludesWildcard ? wildcardType : anyType : unknownType; } - if (unionReduction & (UnionReduction.Literal | UnionReduction.Subtype)) { - if (includes & (TypeFlags.Literal | TypeFlags.UniqueESSymbol) || includes & TypeFlags.Void && includes & TypeFlags.Undefined) { - removeRedundantLiteralTypes(typeSet, includes); - } - if (includes & TypeFlags.StringLiteral && includes & TypeFlags.TemplateLiteral) { - removeStringLiteralsMatchedByTemplateLiterals(typeSet); - } + if (includes & (TypeFlags.Literal | TypeFlags.UniqueESSymbol) || includes & TypeFlags.Void && includes & TypeFlags.Undefined) { + removeRedundantLiteralTypes(typeSet, includes, !!(unionReduction & UnionReduction.Subtype)); } - if (unionReduction & UnionReduction.Subtype) { - if (!removeSubtypes(typeSet, !!(includes & TypeFlags.Object))) { + if (includes & TypeFlags.StringLiteral && includes & TypeFlags.TemplateLiteral) { + removeStringLiteralsMatchedByTemplateLiterals(typeSet); + } + if (unionReduction === UnionReduction.Subtype) { + typeSet = removeSubtypes(typeSet, !!(includes & TypeFlags.Object)); + if (!typeSet) { return errorType; } } @@ -13481,13 +13842,18 @@ namespace ts { return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin); } - function getUnionTypePredicate(signatures: readonly Signature[]): TypePredicate | undefined { + function getUnionOrIntersectionTypePredicate(signatures: readonly Signature[], kind: TypeFlags | undefined): TypePredicate | undefined { let first: TypePredicate | undefined; const types: Type[] = []; for (const sig of signatures) { const pred = getTypePredicateOfSignature(sig); if (!pred || pred.kind === TypePredicateKind.AssertsThis || pred.kind === TypePredicateKind.AssertsIdentifier) { - continue; + if (kind !== TypeFlags.Intersection) { + continue; + } + else { + return; // intersections demand all members be type predicates for the result to have a predicate + } } if (first) { @@ -13502,11 +13868,11 @@ namespace ts { types.push(pred.type); } if (!first) { - // No union signatures had a type predicate. + // No signatures had a type predicate. return undefined; } - const unionType = getUnionType(types); - return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, unionType); + const compositeType = getUnionOrIntersectionType(types, kind); + return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, compositeType); } function typePredicateKindsMatch(a: TypePredicate, b: TypePredicate): boolean { @@ -13534,7 +13900,7 @@ namespace ts { const typeKey = !origin ? getTypeListId(types) : origin.flags & TypeFlags.Union ? `|${getTypeListId((origin).types)}` : origin.flags & TypeFlags.Intersection ? `&${getTypeListId((origin).types)}` : - `#${(origin).type.id}`; + `#${(origin).type.id}|${getTypeListId(types)}`; // origin type id alone is insufficient, as `keyof x` may resolve to multiple WIP values while `x` is still resolving const id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); let type = unionTypes.get(id); if (!type) { @@ -13919,13 +14285,13 @@ namespace ts { function getLiteralTypeFromProperty(prop: Symbol, include: TypeFlags) { if (!(getDeclarationModifierFlagsFromSymbol(prop) & ModifierFlags.NonPublicAccessibilityModifier)) { let type = getSymbolLinks(getLateBoundSymbol(prop)).nameType; - if (!type && !isKnownSymbol(prop)) { + if (!type) { if (prop.escapedName === InternalSymbolName.Default) { type = getLiteralType("default"); } else { const name = prop.valueDeclaration && getNameOfDeclaration(prop.valueDeclaration) as PropertyName; - type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(symbolName(prop)); + type = name && getLiteralTypeFromPropertyName(name) || (!isKnownSymbol(prop) ? getLiteralType(symbolName(prop)) : undefined); } } if (type && type.flags & include) { @@ -14066,9 +14432,7 @@ namespace ts { return type.flags & TypeFlags.StringLiteral ? (type).value : type.flags & TypeFlags.NumberLiteral ? "" + (type).value : type.flags & TypeFlags.BigIntLiteral ? pseudoBigIntToString((type).value) : - type.flags & TypeFlags.BooleanLiteral ? (type).intrinsicName : - type.flags & TypeFlags.Null ? "null" : - type.flags & TypeFlags.Undefined ? "undefined" : + type.flags & (TypeFlags.BooleanLiteral | TypeFlags.Nullable) ? (type).intrinsicName : undefined; } @@ -14152,11 +14516,8 @@ namespace ts { } function getPropertyNameFromIndex(indexType: Type, accessNode: StringLiteral | Identifier | PrivateIdentifier | ObjectBindingPattern | ArrayBindingPattern | ComputedPropertyName | NumericLiteral | IndexedAccessTypeNode | ElementAccessExpression | SyntheticExpression | undefined) { - const accessExpression = accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode : undefined; return isTypeUsableAsPropertyName(indexType) ? getPropertyNameFromType(indexType) : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - getPropertyNameForKnownSymbolName(idText((accessExpression.argumentExpression).name)) : accessNode && isPropertyName(accessNode) ? // late bound names are handled in the first branch, so here we only need to handle normal names getPropertyNameForPropertyNameNode(accessNode) : @@ -14181,12 +14542,12 @@ namespace ts { if (propName !== undefined) { const prop = getPropertyOfType(objectType, propName); if (prop) { - if (reportDeprecated && accessNode && getDeclarationNodeFlagsFromSymbol(prop) & NodeFlags.Deprecated && isUncalledFunctionReference(accessNode, prop)) { + if (reportDeprecated && accessNode && prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & NodeFlags.Deprecated && isUncalledFunctionReference(accessNode, prop)) { const deprecatedNode = accessExpression?.argumentExpression ?? (isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName as string); } if (accessExpression) { - markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === SyntaxKind.ThisKeyword); + markPropertyAsReferenced(prop, accessExpression, isSelfTypeAccess(accessExpression.expression, objectType.symbol)); if (isAssignmentToReadonlyEntity(accessExpression, prop, getAssignmentTargetKind(accessExpression))) { error(accessExpression.argumentExpression, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop)); return undefined; @@ -14351,7 +14712,7 @@ namespace ts { } function isPatternLiteralPlaceholderType(type: Type) { - return templateConstraintType.types.indexOf(type) !== -1 || !!(type.flags & TypeFlags.Any); + return !!(type.flags & (TypeFlags.Any | TypeFlags.String | TypeFlags.Number | TypeFlags.BigInt)); } function isPatternLiteralType(type: Type) { @@ -14366,6 +14727,13 @@ namespace ts { } return !!((type).objectFlags & ObjectFlags.IsGenericObjectType); } + if (type.flags & TypeFlags.Substitution) { + if (!((type).objectFlags & ObjectFlags.IsGenericObjectTypeComputed)) { + (type).objectFlags |= ObjectFlags.IsGenericObjectTypeComputed | + (isGenericObjectType((type).substitute) || isGenericObjectType((type).baseType) ? ObjectFlags.IsGenericObjectType : 0); + } + return !!((type).objectFlags & ObjectFlags.IsGenericObjectType); + } return !!(type.flags & TypeFlags.InstantiableNonPrimitive) || isGenericMappedType(type) || isGenericTupleType(type); } @@ -14377,6 +14745,13 @@ namespace ts { } return !!((type).objectFlags & ObjectFlags.IsGenericIndexType); } + if (type.flags & TypeFlags.Substitution) { + if (!((type).objectFlags & ObjectFlags.IsGenericIndexTypeComputed)) { + (type).objectFlags |= ObjectFlags.IsGenericIndexTypeComputed | + (isGenericIndexType((type).substitute) || isGenericIndexType((type).baseType) ? ObjectFlags.IsGenericIndexType : 0); + } + return !!((type).objectFlags & ObjectFlags.IsGenericIndexType); + } return !!(type.flags & (TypeFlags.InstantiableNonPrimitive | TypeFlags.Index | TypeFlags.TemplateLiteral | TypeFlags.StringMapping)) && !isPatternLiteralType(type); } @@ -14459,6 +14834,13 @@ namespace ts { return type[cache] = type; } + function isConditionalTypeAlwaysTrueDisregardingInferTypes(type: ConditionalType) { + const extendsInferParamMapper = type.root.inferTypeParameters && createTypeMapper(type.root.inferTypeParameters, map(type.root.inferTypeParameters, () => wildcardType)); + const checkType = type.checkType; + const extendsType = type.extendsType; + return isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(instantiateType(extendsType, extendsInferParamMapper))); + } + function getSimplifiedConditionalType(type: ConditionalType, writing: boolean) { const checkType = type.checkType; const extendsType = type.extendsType; @@ -14647,7 +15029,7 @@ namespace ts { // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { const isUnwrapped = isTypicalNondistributiveConditional(root); - const checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.checkType), mapper); + const checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); const checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); const extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { @@ -14662,7 +15044,10 @@ namespace ts { // types rules (i.e. proper contravariance) for inferences. inferTypes(context.inferences, checkType, extendsType, InferencePriority.NoConstraints | InferencePriority.AlwaysStrict); } - combinedMapper = mergeTypeMappers(mapper, context.mapper); + // It's possible for 'infer T' type paramteters to be given uninstantiated constraints when the + // those type parameters are used in type references (see getInferredTypeParameterConstraint). For + // that reason we need context.mapper to be first in the combined mapper. See #42636 for examples. + combinedMapper = mapper ? combineTypeMappers(context.mapper, mapper) : context.mapper; } // Instantiate the extends type including inferences for 'infer T' type parameters const inferredExtendsType = combinedMapper ? instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), combinedMapper) : extendsType; @@ -15059,9 +15444,9 @@ namespace ts { /** We approximate own properties as non-methods plus methods that are inside the object literal */ function isSpreadableProperty(prop: Symbol): boolean { - return !some(prop.declarations, isPrivateIdentifierPropertyDeclaration) && + return !some(prop.declarations, isPrivateIdentifierClassElementDeclaration) && (!(prop.flags & (SymbolFlags.Method | SymbolFlags.GetAccessor | SymbolFlags.SetAccessor)) || - !prop.declarations.some(decl => isClassLike(decl.parent))); + !prop.declarations?.some(decl => isClassLike(decl.parent))); } function getSpreadSymbol(prop: Symbol, readonly: boolean) { @@ -15507,7 +15892,7 @@ namespace ts { } function getObjectTypeInstantiation(type: AnonymousType | DeferredTypeReference, mapper: TypeMapper, aliasSymbol?: Symbol, aliasTypeArguments?: readonly Type[]) { - const declaration = type.objectFlags & ObjectFlags.Reference ? (type).node! : type.symbol.declarations[0]; + const declaration = type.objectFlags & ObjectFlags.Reference ? (type).node! : type.symbol.declarations![0]; const links = getNodeLinks(declaration); const target = type.objectFlags & ObjectFlags.Reference ? links.resolvedType! : type.objectFlags & ObjectFlags.Instantiated ? type.target! : type; @@ -15523,8 +15908,9 @@ namespace ts { outerTypeParameters = addRange(outerTypeParameters, templateTagParameters); } typeParameters = outerTypeParameters || emptyArray; - typeParameters = (target.objectFlags & ObjectFlags.Reference || target.symbol.flags & SymbolFlags.TypeLiteral) && !target.aliasTypeArguments ? - filter(typeParameters, tp => isTypeParameterPossiblyReferenced(tp, declaration)) : + const allDeclarations = type.objectFlags & ObjectFlags.Reference ? [declaration] : type.symbol.declarations!; + typeParameters = (target.objectFlags & ObjectFlags.Reference || target.symbol.flags & SymbolFlags.Method || target.symbol.flags & SymbolFlags.TypeLiteral) && !target.aliasTypeArguments ? + filter(typeParameters, tp => some(allDeclarations, d => isTypeParameterPossiblyReferenced(tp, d))) : typeParameters; links.outerTypeParameters = typeParameters; } @@ -15571,7 +15957,7 @@ namespace ts { return true; } } - return !!forEachChild(node, containsReference); + return containsReference(node); } return true; function containsReference(node: Node): boolean { @@ -15583,6 +15969,9 @@ namespace ts { getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality case SyntaxKind.TypeQuery: return true; + case SyntaxKind.MethodDeclaration: + case SyntaxKind.MethodSignature: + return (!(node as FunctionLikeDeclaration).type && !!(node as FunctionLikeDeclaration).body) || !!forEachChild(node, containsReference); } return !!forEachChild(node, containsReference); } @@ -15776,6 +16165,9 @@ namespace ts { const newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference((type).target, newTypeArguments) : type; } + if (objectFlags & ObjectFlags.ReverseMapped) { + return instantiateReverseMappedType(type as ReverseMappedType, mapper); + } return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments); } return type; @@ -15826,6 +16218,26 @@ namespace ts { return type; } + function instantiateReverseMappedType(type: ReverseMappedType, mapper: TypeMapper) { + const innerMappedType = instantiateType(type.mappedType, mapper); + if (!(getObjectFlags(innerMappedType) & ObjectFlags.Mapped)) { + return type; + } + const innerIndexType = instantiateType(type.constraintType, mapper); + if (!(innerIndexType.flags & TypeFlags.Index)) { + return type; + } + const instantiated = inferTypeForHomomorphicMappedType( + instantiateType(type.source, mapper), + innerMappedType as MappedType, + innerIndexType as IndexType + ); + if (instantiated) { + return instantiated; + } + return type; // Nested invocation of `inferTypeForHomomorphicMappedType` or the `source` instantiated into something unmappable + } + function getPermissiveInstantiation(type: Type) { return type.flags & (TypeFlags.Primitive | TypeFlags.AnyOrUnknown | TypeFlags.Never) ? type : type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); @@ -16142,7 +16554,7 @@ namespace ts { if (resultObj.errors) { if (target.symbol && length(target.symbol.declarations)) { addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], createDiagnosticForNode( - target.symbol.declarations[0], + target.symbol.declarations![0], Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature, )); } @@ -16239,7 +16651,7 @@ namespace ts { } if (!issuedElaboration && (targetProp && length(targetProp.declarations) || target.symbol && length(target.symbol.declarations))) { - const targetNode = targetProp && length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + const targetNode = targetProp && length(targetProp.declarations) ? targetProp.declarations![0] : target.symbol.declarations![0]; if (!getSourceFileOfNode(targetNode).hasNoDefaultLib) { addRelatedInfo(reportedDiag, createDiagnosticForNode( targetNode, @@ -16785,7 +17197,7 @@ namespace ts { // numeric enum literal type. This rule exists for backwards compatibility reasons because // bit-flag enum types sometimes look like literal enum types with numeric literal values. if (s & (TypeFlags.Number | TypeFlags.NumberLiteral) && !(s & TypeFlags.EnumLiteral) && ( - t & TypeFlags.Enum || t & TypeFlags.NumberLiteral && t & TypeFlags.EnumLiteral)) return true; + t & TypeFlags.Enum || relation === assignableRelation && t & TypeFlags.NumberLiteral && t & TypeFlags.EnumLiteral)) return true; } return false; } @@ -16827,12 +17239,13 @@ namespace ts { function getNormalizedType(type: Type, writing: boolean): Type { while (true) { - const t = isFreshLiteralType(type) ? (type).regularType : + let t = isFreshLiteralType(type) ? (type).regularType : getObjectFlags(type) & ObjectFlags.Reference && (type).node ? createTypeReference((type).target, getTypeArguments(type)) : type.flags & TypeFlags.UnionOrIntersection ? getReducedType(type) : type.flags & TypeFlags.Substitution ? writing ? (type).baseType : (type).substitute : type.flags & TypeFlags.Simplifiable ? getSimplifiedType(type, writing) : type; + t = getSingleBaseForNonAugmentingSubtype(t) || t; if (t === type) break; type = t; } @@ -17024,6 +17437,14 @@ namespace ts { } break; } + case Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target.code: { + secondaryRootErrors.unshift([Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target, args[0], args[1]]); + break; + } + case Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target.code: { + secondaryRootErrors.unshift([Diagnostics.Type_at_positions_0_through_1_in_source_is_not_compatible_with_type_at_position_2_in_target, args[0], args[1], args[2]]); + break; + } default: return Debug.fail(`Unhandled Diagnostic: ${msg.code}`); } @@ -17092,6 +17513,7 @@ namespace ts { ); } else { + errorInfo = undefined; reportError( Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, @@ -17214,9 +17636,9 @@ namespace ts { (target as UnionType).types.length <= 3 && maybeTypeOfKind(target, TypeFlags.Nullable)) { const nullStrippedTarget = extractTypesOfKind(target, ~TypeFlags.Nullable); if (!(nullStrippedTarget.flags & (TypeFlags.Union | TypeFlags.Never))) { - if (source === nullStrippedTarget) return Ternary.True; - target = nullStrippedTarget; + target = getNormalizedType(nullStrippedTarget, /*writing*/ true); } + if (source === nullStrippedTarget) return Ternary.True; } if (relation === comparableRelation && !(target.flags & TypeFlags.Never) && isSimpleTypeRelatedTo(target, source, relation) || @@ -17325,8 +17747,10 @@ namespace ts { function reportErrorResults(source: Type, target: Type, result: Ternary, isComparingJsxAttributes: boolean) { if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; + const sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); + const targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); + source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; + target = (originalTarget.aliasSymbol || targetHasBase) ? originalTarget : target; let maybeSuppress = overrideNextErrorInfo > 0; if (maybeSuppress) { overrideNextErrorInfo--; @@ -17468,7 +17892,7 @@ namespace ts { } else { // use the property's value declaration if the property is assigned inside the literal itself - const objectLiteralDeclaration = source.symbol && firstOrUndefined(source.symbol.declarations); + const objectLiteralDeclaration = source.symbol?.declarations && firstOrUndefined(source.symbol.declarations); let suggestion: string | undefined; if (prop.valueDeclaration && findAncestor(prop.valueDeclaration, d => d === objectLiteralDeclaration) && getSourceFileOfNode(objectLiteralDeclaration) === getSourceFileOfNode(errorNode)) { const propDeclaration = prop.valueDeclaration as ObjectLiteralElementLike; @@ -17523,8 +17947,17 @@ namespace ts { function typeRelatedToSomeType(source: Type, target: UnionOrIntersectionType, reportErrors: boolean): Ternary { const targetTypes = target.types; - if (target.flags & TypeFlags.Union && containsType(targetTypes, source)) { - return Ternary.True; + if (target.flags & TypeFlags.Union) { + if (containsType(targetTypes, source)) { + return Ternary.True; + } + const match = getMatchingUnionConstituentForType(target, source); + if (match) { + const related = isRelatedTo(source, match, /*reportErrors*/ false); + if (related) { + return related; + } + } } for (const type of targetTypes) { const related = isRelatedTo(source, type, /*reportErrors*/ false); @@ -17699,9 +18132,16 @@ namespace ts { targetStack = []; } else { + // generate a key where all type parameter id positions are replaced with unconstrained type parameter ids + // this isn't perfect - nested type references passed as type arguments will muck up the indexes and thus + // prevent finding matches- but it should hit up the common cases + const broadestEquivalentId = id.split(",").map(i => i.replace(/-\d+/g, (_match, offset: number) => { + const index = length(id.slice(0, offset).match(/[-=]/g) || undefined); + return `=${index}`; + })).join(","); for (let i = 0; i < maybeCount; i++) { // If source and target are already being compared, consider them related with assumptions - if (id === maybeKeys[i]) { + if (id === maybeKeys[i] || broadestEquivalentId === maybeKeys[i]) { return Ternary.Maybe; } } @@ -17792,8 +18232,21 @@ namespace ts { if (target.flags & TypeFlags.Intersection) { return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target as IntersectionType, reportErrors, IntersectionState.Target); } - // Source is an intersection. Check to see if any constituents of the intersection are immediately related - // to the target. + // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the + // constraints of all non-primitive types in the source into a new intersection. We do this because the + // intersection may further constrain the constraints of the non-primitive types. For example, given a type + // parameter 'T extends 1 | 2', the intersection 'T & 1' should be reduced to '1' such that it doesn't + // appear to be comparable to '2'. + if (relation === comparableRelation && target.flags & TypeFlags.Primitive) { + const constraints = sameMap((source).types, t => t.flags & TypeFlags.Primitive ? t : getBaseConstraintOfType(t) || unknownType); + if (constraints !== (source).types) { + source = getIntersectionType(constraints); + if (!(source.flags & TypeFlags.Intersection)) { + return isRelatedTo(source, target, /*reportErrors*/ false); + } + } + } + // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually // useful and leads to some confusing error messages. Instead it is better to let the below checks @@ -17912,6 +18365,20 @@ namespace ts { } } else if (target.flags & TypeFlags.IndexedAccess) { + if (source.flags & TypeFlags.IndexedAccess) { + // Relate components directly before falling back to constraint relationships + // A type S[K] is related to a type T[J] if S is related to T and K is related to J. + if (result = isRelatedTo((source).objectType, (target).objectType, reportErrors)) { + result &= isRelatedTo((source).indexType, (target).indexType, reportErrors); + } + if (result) { + resetErrorInfo(saveErrorInfo); + return result; + } + if (reportErrors) { + originalErrorInfo = errorInfo; + } + } // A type S is related to a type T[K] if S is related to C, where C is the base // constraint of T[K] for writing. if (relation === assignableRelation || relation === comparableRelation) { @@ -17922,11 +18389,24 @@ namespace ts { if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) { const accessFlags = AccessFlags.Writing | (baseObjectType !== objectType ? AccessFlags.NoIndexSignatures : 0); const constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, (target).noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, accessFlags); - if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) { - return result; + if (constraint) { + if (reportErrors && originalErrorInfo) { + // create a new chain for the constraint error + resetErrorInfo(saveErrorInfo); + } + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } + // prefer the shorter chain of the constraint comparison chain, and the direct comparison chain + if (reportErrors && originalErrorInfo && errorInfo) { + errorInfo = countMessageChainBreadth([originalErrorInfo]) <= countMessageChainBreadth([errorInfo]) ? originalErrorInfo : errorInfo; + } } } } + if (reportErrors) { + originalErrorInfo = undefined; + } } else if (isGenericMappedType(target) && !target.declaration.nameType) { // A source type T is related to a target type { [P in X]: T[P] } @@ -17971,28 +18451,51 @@ namespace ts { } } } - else if (target.flags & TypeFlags.TemplateLiteral && source.flags & TypeFlags.StringLiteral) { - if (isPatternLiteralType(target)) { - // match all non-`string` segments - const result = inferLiteralsFromTemplateLiteralType(source as StringLiteralType, target as TemplateLiteralType); - if (result && every(result, (r, i) => isStringLiteralTypeValueParsableAsType(r, (target as TemplateLiteralType).types[i]))) { - return Ternary.True; - } + else if (target.flags & TypeFlags.Conditional) { + const c = target as ConditionalType; + // Check if the conditional is always true or always false but still deferred for distribution purposes + const skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType)); + const skipFalse = !skipTrue && isConditionalTypeAlwaysTrueDisregardingInferTypes(c); + + // Instantiate with a replacement mapper if the conditional is distributive, replacing the check type with a clone of itself, + // this way {x: string | number, y: string | number} -> (T extends T ? { x: T, y: T } : never) appropriately _fails_ when + // T = string | number (since that will end up distributing and producing `{x: string, y: string} | {x: number, y: number}`, + // to which `{x: string | number, y: string | number}` isn't assignable) + let distributionMapper: TypeMapper | undefined; + const checkVar = getActualTypeVariable(c.root.checkType); + if (c.root.isDistributive && checkVar.flags & TypeFlags.TypeParameter) { + const newParam = cloneTypeParameter(checkVar); + distributionMapper = prependTypeMapping(checkVar, newParam, c.mapper); + newParam.mapper = distributionMapper; + } + + // TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't) + let localResult: Ternary | undefined; + if (skipTrue || (localResult = isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.trueType), distributionMapper) : getTrueTypeFromConditionalType(c), /*reportErrors*/ false))) { + if (!skipFalse) { + localResult = (localResult || Ternary.Maybe) & isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.falseType), distributionMapper) : getFalseTypeFromConditionalType(c), /*reportErrors*/ false); + } + } + if (localResult) { + resetErrorInfo(saveErrorInfo); + return localResult; + } + } + else if (target.flags & TypeFlags.TemplateLiteral) { + if (source.flags & TypeFlags.TemplateLiteral) { + // Report unreliable variance for type variables referenced in template literal type placeholders. + // For example, `foo-${number}` is related to `foo-${string}` even though number isn't related to string. + instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); + } + const result = inferTypesFromTemplateLiteralType(source, target as TemplateLiteralType); + if (result && every(result, (r, i) => isValidTypeForTemplateLiteralPlaceholder(r, (target as TemplateLiteralType).types[i]))) { + return Ternary.True; } } if (source.flags & TypeFlags.TypeVariable) { - if (source.flags & TypeFlags.IndexedAccess && target.flags & TypeFlags.IndexedAccess) { - // A type S[K] is related to a type T[J] if S is related to T and K is related to J. - if (result = isRelatedTo((source).objectType, (target).objectType, reportErrors)) { - result &= isRelatedTo((source).indexType, (target).indexType, reportErrors); - } - if (result) { - resetErrorInfo(saveErrorInfo); - return result; - } - } - else { + // IndexedAccess comparisons are handled above in the `target.flags & TypeFlage.IndexedAccess` branch + if (!(source.flags & TypeFlags.IndexedAccess && target.flags & TypeFlags.IndexedAccess)) { const constraint = getConstraintOfType(source); if (!constraint || (source.flags & TypeFlags.TypeParameter && constraint.flags & TypeFlags.Any)) { // A type variable with no constraint is not related to the non-primitive object type. @@ -18007,7 +18510,7 @@ namespace ts { return result; } // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example - else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, intersectionState)) { + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors && !(target.flags & source.flags & TypeFlags.TypeParameter), /*headMessage*/ undefined, intersectionState)) { resetErrorInfo(saveErrorInfo); return result; } @@ -18020,17 +18523,13 @@ namespace ts { } } else if (source.flags & TypeFlags.TemplateLiteral) { - if (target.flags & TypeFlags.TemplateLiteral && - (source as TemplateLiteralType).texts.length === (target as TemplateLiteralType).texts.length && - (source as TemplateLiteralType).types.length === (target as TemplateLiteralType).types.length && - every((source as TemplateLiteralType).texts, (t, i) => t === (target as TemplateLiteralType).texts[i]) && - every((instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)) as TemplateLiteralType).types, (t, i) => !!((target as TemplateLiteralType).types[i].flags & (TypeFlags.Any | TypeFlags.String)) || !!isRelatedTo(t, (target as TemplateLiteralType).types[i], /*reportErrors*/ false))) { - return Ternary.True; - } - const constraint = getBaseConstraintOfType(source); - if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, reportErrors))) { - resetErrorInfo(saveErrorInfo); - return result; + if (!(target.flags & TypeFlags.TemplateLiteral)) { + const baseConstraint = getBaseConstraintOfType(source); + const constraint = baseConstraint && baseConstraint !== source ? baseConstraint : stringType; + if (result = isRelatedTo(constraint, target, reportErrors)) { + resetErrorInfo(saveErrorInfo); + return result; + } } } else if (source.flags & TypeFlags.StringMapping) { @@ -18192,6 +18691,11 @@ namespace ts { } return Ternary.False; + function countMessageChainBreadth(info: DiagnosticMessageChain[] | undefined): number { + if (!info) return 0; + return reduceLeft(info, (value, chain) => value + 1 + countMessageChainBreadth(chain.next), 0); + } + function relateVariances(sourceTypeArguments: readonly Type[] | undefined, targetTypeArguments: readonly Type[] | undefined, variances: VarianceFlags[], intersectionState: IntersectionState) { if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) { return result; @@ -18516,7 +19020,7 @@ namespace ts { const propName = symbolToString(unmatchedProperty); reportError(Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName, ...getTypeNamesForErrorDisplay(source, target)); if (length(unmatchedProperty.declarations)) { - associateRelatedInfo(createDiagnosticForNode(unmatchedProperty.declarations[0], Diagnostics._0_is_declared_here, propName)); + associateRelatedInfo(createDiagnosticForNode(unmatchedProperty.declarations![0], Diagnostics._0_is_declared_here, propName)); } if (shouldSkipElaboration && errorInfo) { overrideNextErrorInfo++; @@ -18879,10 +19383,18 @@ namespace ts { return indexTypesIdenticalTo(source, target, kind); } const targetType = getIndexTypeOfType(target, kind); - if (!targetType || targetType.flags & TypeFlags.Any && !sourceIsPrimitive) { - // Index signature of type any permits assignment from everything but primitives + if (!targetType) { return Ternary.True; } + if (targetType.flags & TypeFlags.Any && !sourceIsPrimitive) { + // An index signature of type `any` permits assignment from everything but primitives, + // provided that there is also a `string` index signature of type `any`. + const stringIndexType = kind === IndexKind.String ? targetType : getIndexTypeOfType(target, IndexKind.String); + if (stringIndexType && stringIndexType.flags & TypeFlags.Any) { + return Ternary.True; + } + + } if (isGenericMappedType(source)) { // A generic mapped type { [P in K]: T } is related to a type with an index signature // { [x: string]: U }, and optionally with an index signature { [x: number]: V }, @@ -19141,7 +19653,7 @@ namespace ts { } function isTypeReferenceWithGenericArguments(type: Type): boolean { - return isNonDeferredTypeReference(type) && some(getTypeArguments(type), t => isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t)); + return isNonDeferredTypeReference(type) && some(getTypeArguments(type), t => !!(t.flags & TypeFlags.TypeParameter) || isTypeReferenceWithGenericArguments(t)); } /** @@ -19232,8 +19744,8 @@ namespace ts { // Return true if the given class derives from each of the declaring classes of the protected // constituents of the given property. - function isClassDerivedFromDeclaringClasses(checkClass: Type, prop: Symbol) { - return forEachProperty(prop, p => getDeclarationModifierFlagsFromSymbol(p) & ModifierFlags.Protected ? + function isClassDerivedFromDeclaringClasses(checkClass: Type, prop: Symbol, writing: boolean) { + return forEachProperty(prop, p => getDeclarationModifierFlagsFromSymbol(p, writing) & ModifierFlags.Protected ? !hasBaseType(checkClass, getDeclaringClass(p)) : false) ? undefined : checkClass; } @@ -19252,14 +19764,12 @@ namespace ts { function isDeeplyNestedType(type: Type, stack: Type[], depth: number): boolean { if (depth >= 5) { const identity = getRecursionIdentity(type); - if (identity) { - let count = 0; - for (let i = 0; i < depth; i++) { - if (getRecursionIdentity(stack[i]) === identity) { - count++; - if (count >= 5) { - return true; - } + let count = 0; + for (let i = 0; i < depth; i++) { + if (getRecursionIdentity(stack[i]) === identity) { + count++; + if (count >= 5) { + return true; } } } @@ -19267,15 +19777,20 @@ namespace ts { return false; } - // Types with constituents that could circularly reference the type have a recursion identity. The recursion - // identity is some object that is common to instantiations of the type with the same origin. - function getRecursionIdentity(type: Type): object | undefined { + // The recursion identity of a type is an object identity that is shared among multiple instantiations of the type. + // We track recursion identities in order to identify deeply nested and possibly infinite type instantiations with + // the same origin. For example, when type parameters are in scope in an object type such as { x: T }, all + // instantiations of that type have the same recursion identity. The default recursion identity is the object + // identity of the type, meaning that every type is unique. Generally, types with constituents that could circularly + // reference the type have a recursion identity that differs from the object identity. + function getRecursionIdentity(type: Type): object { + // Object and array literals are known not to contain recursive references and don't need a recursion identity. if (type.flags & TypeFlags.Object && !isObjectOrArrayLiteralType(type)) { if (getObjectFlags(type) && ObjectFlags.Reference && (type as TypeReference).node) { // Deferred type references are tracked through their associated AST node. This gives us finer // granularity than using their associated target because each manifest type reference has a // unique AST node. - return (type as TypeReference).node; + return (type as TypeReference).node!; } if (type.symbol && !(getObjectFlags(type) & ObjectFlags.Anonymous && type.symbol.flags & SymbolFlags.Class)) { // We track all object types that have an associated symbol (representing the origin of the type), but @@ -19287,6 +19802,9 @@ namespace ts { return type.target; } } + if (type.flags & TypeFlags.TypeParameter) { + return type.symbol; + } if (type.flags & TypeFlags.IndexedAccess) { // Identity is the leftmost object type in a chain of indexed accesses, eg, in A[P][Q] it is A do { @@ -19298,7 +19816,7 @@ namespace ts { // The root object represents the origin of the conditional type return (type as ConditionalType).root; } - return undefined; + return type; } function isPropertyIdenticalTo(sourceProp: Symbol, targetProp: Symbol): boolean { @@ -19443,6 +19961,9 @@ namespace ts { // of those literal types. Otherwise, return the leftmost type for which no type to the // right is a supertype. function getSupertypeOrUnion(types: Type[]): Type { + if (types.length === 1) { + return types[0]; + } return literalTypesWithSameBaseType(types) ? getUnionType(types) : reduceLeft(types, (s, t) => isTypeSubtypeOf(s, t) ? t : s)!; @@ -19485,9 +20006,33 @@ namespace ts { return isArrayType(type) || !(type.flags & TypeFlags.Nullable) && isTypeAssignableTo(type, anyReadonlyArrayType); } + function getSingleBaseForNonAugmentingSubtype(type: Type) { + if (!(getObjectFlags(type) & ObjectFlags.Reference) || !(getObjectFlags((type as TypeReference).target) & ObjectFlags.ClassOrInterface)) { + return undefined; + } + if (getObjectFlags(type) & ObjectFlags.IdenticalBaseTypeCalculated) { + return getObjectFlags(type) & ObjectFlags.IdenticalBaseTypeExists ? (type as TypeReference).cachedEquivalentBaseType : undefined; + } + (type as TypeReference).objectFlags |= ObjectFlags.IdenticalBaseTypeCalculated; + const target = (type as TypeReference).target as InterfaceType; + const bases = getBaseTypes(target); + if (bases.length !== 1) { + return undefined; + } + if (getMembersOfSymbol(type.symbol).size) { + return undefined; // If the interface has any members, they may subtype members in the base, so we should do a full structural comparison + } + let instantiatedBase = !length(target.typeParameters) ? bases[0] : instantiateType(bases[0], createTypeMapper(target.typeParameters!, getTypeArguments(type as TypeReference).slice(0, target.typeParameters!.length))); + if (length(getTypeArguments(type as TypeReference)) > length(target.typeParameters)) { + instantiatedBase = getTypeWithThisArgument(instantiatedBase, last(getTypeArguments(type as TypeReference))); + } + (type as TypeReference).objectFlags |= ObjectFlags.IdenticalBaseTypeExists; + return (type as TypeReference).cachedEquivalentBaseType = instantiatedBase; + } + function isEmptyArrayLiteralType(type: Type): boolean { - const elementType = isArrayType(type) ? getTypeArguments(type)[0] : undefined; - return elementType === undefinedWideningType || elementType === implicitNeverType; + const elementType = getElementTypeOfArrayType(type); + return strictNullChecks ? elementType === implicitNeverType : elementType === undefinedWideningType; } function isTupleLikeType(type: Type): boolean { @@ -19517,6 +20062,15 @@ namespace ts { return !!(type.flags & TypeFlags.Unit); } + function isUnitLikeType(type: Type): boolean { + return type.flags & TypeFlags.Intersection ? some((type).types, isUnitType) : + !!(type.flags & TypeFlags.Unit); + } + + function extractUnitType(type: Type) { + return type.flags & TypeFlags.Intersection ? find((type).types, isUnitType) || type : type; + } + function isLiteralType(type: Type): boolean { return type.flags & TypeFlags.Boolean ? true : type.flags & TypeFlags.Union ? type.flags & TypeFlags.EnumLiteral ? true : every((type).types, isUnitType) : @@ -19685,14 +20239,17 @@ namespace ts { } function getGlobalNonNullableTypeInstantiation(type: Type) { + // First reduce away any constituents that are assignable to 'undefined' or 'null'. This not only eliminates + // 'undefined' and 'null', but also higher-order types such as a type parameter 'U extends undefined | null' + // that isn't eliminated by a NonNullable instantiation. + const reducedType = getTypeWithFacts(type, TypeFacts.NEUndefinedOrNull); if (!deferredGlobalNonNullableTypeAlias) { deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable" as __String, SymbolFlags.TypeAlias, /*diagnostic*/ undefined) || unknownSymbol; } - // Use NonNullable global type alias if available to improve quick info/declaration emit - if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { - return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); - } - return getTypeWithFacts(type, TypeFacts.NEUndefinedOrNull); // Type alias unavailable, fall back to non-higher-order behavior + // If the NonNullable type is available, return an instantiation. Otherwise just return the reduced type. + return deferredGlobalNonNullableTypeAlias !== unknownSymbol ? + getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [reducedType]) : + reducedType; } function getNonNullableType(type: Type): Type { @@ -20180,7 +20737,7 @@ namespace ts { type.flags & TypeFlags.Object && !isNonGenericTopLevelType(type) && ( objectFlags & ObjectFlags.Reference && ((type).node || forEach(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral) && type.symbol.declarations || - objectFlags & (ObjectFlags.Mapped | ObjectFlags.ObjectRestType)) || + objectFlags & (ObjectFlags.Mapped | ObjectFlags.ReverseMapped | ObjectFlags.ObjectRestType)) || type.flags & TypeFlags.UnionOrIntersection && !(type.flags & TypeFlags.EnumLiteral) && !isNonGenericTopLevelType(type) && some((type).types, couldContainTypeVariables)); if (type.flags & TypeFlags.ObjectFlagsType) { (type).objectFlags |= ObjectFlags.CouldContainTypeVariablesComputed | (result ? ObjectFlags.CouldContainTypeVariables : 0); @@ -20281,7 +20838,11 @@ namespace ts { } function getTypeOfReverseMappedSymbol(symbol: ReverseMappedSymbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + const links = getSymbolLinks(symbol); + if (!links.type) { + links.type = inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); + } + return links.type; } function inferReverseMappedType(sourceType: Type, target: MappedType, constraint: IndexType): Type { @@ -20367,43 +20928,108 @@ namespace ts { return success && result === SyntaxKind.BigIntLiteral && scanner.getTextPos() === (s.length + 1) && !(flags & TokenFlags.ContainsSeparator); } - function isStringLiteralTypeValueParsableAsType(s: StringLiteralType, target: Type): boolean { - if (target.flags & TypeFlags.Union) { - return !!forEachType(target, t => isStringLiteralTypeValueParsableAsType(s, t)); - } - switch (target) { - case stringType: return true; - case numberType: return s.value !== "" && isFinite(+(s.value)); - case bigintType: return s.value !== "" && isValidBigIntString(s.value); - // the next 4 should be handled in `getTemplateLiteralType`, as they are all exactly one value, but are here for completeness, just in case - // this function is ever used on types which don't come from template literal holes - case trueType: return s.value === "true"; - case falseType: return s.value === "false"; - case undefinedType: return s.value === "undefined"; - case nullType: return s.value === "null"; - default: return !!(target.flags & TypeFlags.Any); - } - } - - function inferLiteralsFromTemplateLiteralType(source: StringLiteralType, target: TemplateLiteralType): StringLiteralType[] | undefined { - const value = source.value; - const texts = target.texts; - const lastIndex = texts.length - 1; - const startText = texts[0]; - const endText = texts[lastIndex]; - if (!(value.startsWith(startText) && value.slice(startText.length).endsWith(endText))) return undefined; - const matches = []; - const str = value.slice(startText.length, value.length - endText.length); - let pos = 0; - for (let i = 1; i < lastIndex; i++) { - const delim = texts[i]; - const delimPos = delim.length > 0 ? str.indexOf(delim, pos) : pos < str.length ? pos + 1 : -1; - if (delimPos < 0) return undefined; - matches.push(getLiteralType(str.slice(pos, delimPos))); - pos = delimPos + delim.length; - } - matches.push(getLiteralType(str.slice(pos))); + function isValidTypeForTemplateLiteralPlaceholder(source: Type, target: Type): boolean { + if (source === target || target.flags & (TypeFlags.Any | TypeFlags.String)) { + return true; + } + if (source.flags & TypeFlags.StringLiteral) { + const value = (source).value; + return !!(target.flags & TypeFlags.Number && value !== "" && isFinite(+value) || + target.flags & TypeFlags.BigInt && value !== "" && isValidBigIntString(value) || + target.flags & (TypeFlags.BooleanLiteral | TypeFlags.Nullable) && value === (target).intrinsicName); + } + if (source.flags & TypeFlags.TemplateLiteral) { + const texts = (source).texts; + return texts.length === 2 && texts[0] === "" && texts[1] === "" && isTypeAssignableTo((source).types[0], target); + } + return isTypeAssignableTo(source, target); + } + + function inferTypesFromTemplateLiteralType(source: Type, target: TemplateLiteralType): Type[] | undefined { + return source.flags & TypeFlags.StringLiteral ? inferFromLiteralPartsToTemplateLiteral([(source).value], emptyArray, target) : + source.flags & TypeFlags.TemplateLiteral ? + arraysEqual((source).texts, target.texts) ? map((source).types, getStringLikeTypeForType) : + inferFromLiteralPartsToTemplateLiteral((source).texts, (source).types, target) : + undefined; + } + + function getStringLikeTypeForType(type: Type) { + return type.flags & (TypeFlags.Any | TypeFlags.StringLike) ? type : getTemplateLiteralType(["", ""], [type]); + } + + // This function infers from the text parts and type parts of a source literal to a target template literal. The number + // of text parts is always one more than the number of type parts, and a source string literal is treated as a source + // with one text part and zero type parts. The function returns an array of inferred string or template literal types + // corresponding to the placeholders in the target template literal, or undefined if the source doesn't match the target. + // + // We first check that the starting source text part matches the starting target text part, and that the ending source + // text part ends matches the ending target text part. We then iterate through the remaining target text parts, finding + // a match for each in the source and inferring string or template literal types created from the segments of the source + // that occur between the matches. During this iteration, seg holds the index of the current text part in the sourceTexts + // array and pos holds the current character position in the current text part. + // + // Consider inference from type `<<${string}>.<${number}-${number}>>` to type `<${string}.${string}>`, i.e. + // sourceTexts = ['<<', '>.<', '-', '>>'] + // sourceTypes = [string, number, number] + // target.texts = ['<', '.', '>'] + // We first match '<' in the target to the start of '<<' in the source and '>' in the target to the end of '>>' in + // the source. The first match for the '.' in target occurs at character 1 in the source text part at index 1, and thus + // the first inference is the template literal type `<${string}>`. The remainder of the source makes up the second + // inference, the template literal type `<${number}-${number}>`. + function inferFromLiteralPartsToTemplateLiteral(sourceTexts: readonly string[], sourceTypes: readonly Type[], target: TemplateLiteralType): Type[] | undefined { + const lastSourceIndex = sourceTexts.length - 1; + const sourceStartText = sourceTexts[0]; + const sourceEndText = sourceTexts[lastSourceIndex]; + const targetTexts = target.texts; + const lastTargetIndex = targetTexts.length - 1; + const targetStartText = targetTexts[0]; + const targetEndText = targetTexts[lastTargetIndex]; + if (lastSourceIndex === 0 && sourceStartText.length < targetStartText.length + targetEndText.length || + !sourceStartText.startsWith(targetStartText) || !sourceEndText.endsWith(targetEndText)) return undefined; + const remainingEndText = sourceEndText.slice(0, sourceEndText.length - targetEndText.length); + const matches: Type[] = []; + let seg = 0; + let pos = targetStartText.length; + for (let i = 1; i < lastTargetIndex; i++) { + const delim = targetTexts[i]; + if (delim.length > 0) { + let s = seg; + let p = pos; + while (true) { + p = getSourceText(s).indexOf(delim, p); + if (p >= 0) break; + s++; + if (s === sourceTexts.length) return undefined; + p = 0; + } + addMatch(s, p); + pos += delim.length; + } + else if (pos < getSourceText(seg).length) { + addMatch(seg, pos + 1); + } + else if (seg < lastSourceIndex) { + addMatch(seg + 1, 0); + } + else { + return undefined; + } + } + addMatch(lastSourceIndex, getSourceText(lastSourceIndex).length); return matches; + function getSourceText(index: number) { + return index < lastSourceIndex ? sourceTexts[index] : remainingEndText; + } + function addMatch(s: number, p: number) { + const matchType = s === seg ? + getLiteralType(getSourceText(s).slice(pos, p)) : + getTemplateLiteralType( + [sourceTexts[seg].slice(pos), ...sourceTexts.slice(seg + 1, s), getSourceText(s).slice(0, p)], + sourceTypes.slice(seg, s)); + matches.push(matchType); + seg = s; + pos = p; + } } function inferTypes(inferences: InferenceInfo[], originalSource: Type, originalTarget: Type, priority: InferencePriority = 0, contravariant = false) { @@ -20579,6 +21205,13 @@ namespace ts { inferFromTypes((source).type, (target).type); } } + else if (source.flags & TypeFlags.Substitution) { + inferFromTypes((source as SubstitutionType).baseType, target); + const oldPriority = priority; + priority |= InferencePriority.SubstituteSource; + inferFromTypes((source as SubstitutionType).substitute, target); // Make substitute inference at a lower priority + priority = oldPriority; + } else if (target.flags & TypeFlags.Conditional) { invokeOnce(source, target, inferToConditionalType); } @@ -20641,16 +21274,16 @@ namespace ts { // We stop inferring and report a circularity if we encounter duplicate recursion identities on both // the source side and the target side. const saveExpandingFlags = expandingFlags; - const sourceIdentity = getRecursionIdentity(source) || source; - const targetIdentity = getRecursionIdentity(target) || target; - if (sourceIdentity && contains(sourceStack, sourceIdentity)) expandingFlags |= ExpandingFlags.Source; - if (targetIdentity && contains(targetStack, targetIdentity)) expandingFlags |= ExpandingFlags.Target; + const sourceIdentity = getRecursionIdentity(source); + const targetIdentity = getRecursionIdentity(target); + if (contains(sourceStack, sourceIdentity)) expandingFlags |= ExpandingFlags.Source; + if (contains(targetStack, targetIdentity)) expandingFlags |= ExpandingFlags.Target; if (expandingFlags !== ExpandingFlags.Both) { - if (sourceIdentity) (sourceStack || (sourceStack = [])).push(sourceIdentity); - if (targetIdentity) (targetStack || (targetStack = [])).push(targetIdentity); + (sourceStack || (sourceStack = [])).push(sourceIdentity); + (targetStack || (targetStack = [])).push(targetIdentity); action(source, target); - if (targetIdentity) targetStack.pop(); - if (sourceIdentity) sourceStack.pop(); + targetStack.pop(); + sourceStack.pop(); } else { inferencePriority = InferencePriority.Circularity; @@ -20868,9 +21501,7 @@ namespace ts { } function inferToTemplateLiteralType(source: Type, target: TemplateLiteralType) { - const matches = source.flags & TypeFlags.StringLiteral ? inferLiteralsFromTemplateLiteralType(source, target) : - source.flags & TypeFlags.TemplateLiteral && arraysEqual((source).texts, target.texts) ? (source).types : - undefined; + const matches = inferTypesFromTemplateLiteralType(source, target); const types = target.types; for (let i = 0; i < types.length; i++) { inferFromTypes(matches ? matches[i] : neverType, types[i]); @@ -21235,14 +21866,12 @@ namespace ts { // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the // leftmost identifier followed by zero or more property names separated by dots. - // The result is undefined if the reference isn't a dotted name. We prefix nodes - // occurring in an apparent type position with '@' because the control flow type - // of such nodes may be based on the apparent type instead of the declared type. + // The result is undefined if the reference isn't a dotted name. function getFlowCacheKey(node: Node, declaredType: Type, initialType: Type, flowContainer: Node | undefined): string | undefined { switch (node.kind) { case SyntaxKind.Identifier: const symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? `${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}|${isConstraintPosition(node) ? "@" : ""}${getSymbolId(symbol)}` : undefined; + return symbol !== unknownSymbol ? `${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}|${getSymbolId(symbol)}` : undefined; case SyntaxKind.ThisKeyword: return `0|${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}`; case SyntaxKind.NonNullExpression: @@ -21269,6 +21898,10 @@ namespace ts { (isBinaryExpression(target) && target.operatorToken.kind === SyntaxKind.CommaToken && isMatchingReference(source, target.right)); } switch (source.kind) { + case SyntaxKind.MetaProperty: + return target.kind === SyntaxKind.MetaProperty + && (source as MetaProperty).keywordToken === (target as MetaProperty).keywordToken + && (source as MetaProperty).name.escapedText === (target as MetaProperty).name.escapedText; case SyntaxKind.Identifier: case SyntaxKind.PrivateIdentifier: return target.kind === SyntaxKind.Identifier && getResolvedSymbol(source) === getResolvedSymbol(target) || @@ -21358,6 +21991,82 @@ namespace ts { return result; } + // Given a set of constituent types and a property name, create and return a map keyed by the literal + // types of the property by that name in each constituent type. No map is returned if some key property + // has a non-literal type or if less than 10 or less than 50% of the constituents have a unique key. + // Entries with duplicate keys have unknownType as the value. + function mapTypesByKeyProperty(types: Type[], name: __String) { + const map = new Map(); + let count = 0; + for (const type of types) { + if (type.flags & (TypeFlags.Object | TypeFlags.Intersection | TypeFlags.InstantiableNonPrimitive)) { + const discriminant = getTypeOfPropertyOfType(type, name); + if (discriminant) { + if (!isLiteralType(discriminant)) { + return undefined; + } + let duplicate = false; + forEachType(discriminant, t => { + const id = getTypeId(getRegularTypeOfLiteralType(t)); + const existing = map.get(id); + if (!existing) { + map.set(id, type); + } + else if (existing !== unknownType) { + map.set(id, unknownType); + duplicate = true; + } + }); + if (!duplicate) count++; + } + } + } + return count >= 10 && count * 2 >= types.length ? map : undefined; + } + + // Return the name of a discriminant property for which it was possible and feasible to construct a map of + // constituent types keyed by the literal types of the property by that name in each constituent type. + function getKeyPropertyName(unionType: UnionType): __String | undefined { + const types = unionType.types; + // We only construct maps for large unions with non-primitive constituents. + if (types.length < 10 || getObjectFlags(unionType) & ObjectFlags.PrimitiveUnion) { + return undefined; + } + if (unionType.keyPropertyName === undefined) { + // The candidate key property name is the name of the first property with a unit type in one of the + // constituent types. + const keyPropertyName = forEach(types, t => + t.flags & (TypeFlags.Object | TypeFlags.InstantiableNonPrimitive) ? + forEach(getPropertiesOfType(t), p => isUnitType(getTypeOfSymbol(p)) ? p.escapedName : undefined) : + undefined); + const mapByKeyProperty = keyPropertyName && mapTypesByKeyProperty(types, keyPropertyName); + unionType.keyPropertyName = mapByKeyProperty ? keyPropertyName : "" as __String; + unionType.constituentMap = mapByKeyProperty; + } + return (unionType.keyPropertyName as string).length ? unionType.keyPropertyName : undefined; + } + + // Given a union type for which getKeyPropertyName returned a non-undefined result, return the constituent + // that corresponds to the given key type for that property name. + function getConstituentTypeForKeyType(unionType: UnionType, keyType: Type) { + const result = unionType.constituentMap?.get(getTypeId(getRegularTypeOfLiteralType(keyType))); + return result !== unknownType ? result : undefined; + } + + function getMatchingUnionConstituentForType(unionType: UnionType, type: Type) { + const keyPropertyName = getKeyPropertyName(unionType); + const propType = keyPropertyName && getTypeOfPropertyOfType(type, keyPropertyName); + return propType && getConstituentTypeForKeyType(unionType, propType); + } + + function getMatchingUnionConstituentForObjectLiteral(unionType: UnionType, node: ObjectLiteralExpression) { + const keyPropertyName = getKeyPropertyName(unionType); + const propNode = keyPropertyName && find(node.properties, p => p.symbol && p.kind === SyntaxKind.PropertyAssignment && + p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer)); + const propType = propNode && getTypeOfExpression((propNode).initializer); + return propType && getConstituentTypeForKeyType(unionType, propType); + } + function isOrContainsMatchingReference(source: Node, target: Node) { return isMatchingReference(source, target) || containsMatchingReference(source, target); } @@ -21420,14 +22129,6 @@ namespace ts { return declaredType; } - function getTypeFactsOfTypes(types: Type[]): TypeFacts { - let result: TypeFacts = TypeFacts.None; - for (const t of types) { - result |= getTypeFacts(t); - } - return result; - } - function isFunctionObjectType(type: ObjectType): boolean { // We do a quick check for a "bind" property before performing the more expensive subtype // check. This gives us a quicker out in the common case where an object type is not a function. @@ -21436,7 +22137,7 @@ namespace ts { resolved.members.get("bind" as __String) && isTypeSubtypeOf(type, globalFunctionType)); } - function getTypeFacts(type: Type): TypeFacts { + function getTypeFacts(type: Type, ignoreObjects = false): TypeFacts { const flags = type.flags; if (flags & TypeFlags.String) { return strictNullChecks ? TypeFacts.StringStrictFacts : TypeFacts.StringFacts; @@ -21473,7 +22174,7 @@ namespace ts { (type === falseType || type === regularFalseType) ? TypeFacts.FalseStrictFacts : TypeFacts.TrueStrictFacts : (type === falseType || type === regularFalseType) ? TypeFacts.FalseFacts : TypeFacts.TrueFacts; } - if (flags & TypeFlags.Object) { + if (flags & TypeFlags.Object && !ignoreObjects) { return getObjectFlags(type) & ObjectFlags.Anonymous && isEmptyObjectType(type) ? strictNullChecks ? TypeFacts.EmptyObjectStrictFacts : TypeFacts.EmptyObjectFacts : isFunctionObjectType(type) ? @@ -21496,11 +22197,17 @@ namespace ts { return TypeFacts.None; } if (flags & TypeFlags.Instantiable) { - return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType) : + return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType, ignoreObjects) : strictNullChecks ? TypeFacts.NonEmptyStringStrictFacts : TypeFacts.NonEmptyStringFacts; } - if (flags & TypeFlags.UnionOrIntersection) { - return getTypeFactsOfTypes((type).types); + if (flags & TypeFlags.Union) { + return reduceLeft((type).types, (facts, t) => facts | getTypeFacts(t, ignoreObjects), TypeFacts.None); + } + if (flags & TypeFlags.Intersection) { + // When an intersection contains a primitive type we ignore object type constituents as they are + // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. + ignoreObjects ||= maybeTypeOfKind(type, TypeFlags.Primitive); + return reduceLeft((type).types, (facts, t) => facts & getTypeFacts(t, ignoreObjects), TypeFacts.All); } return TypeFacts.All; } @@ -21510,18 +22217,16 @@ namespace ts { } function getTypeWithDefault(type: Type, defaultExpression: Expression) { - if (defaultExpression) { - const defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, TypeFacts.NEUndefined), defaultType]); - } - return type; + return defaultExpression ? + getUnionType([getNonUndefinedType(type), getTypeOfExpression(defaultExpression)]) : + type; } function getTypeOfDestructuredProperty(type: Type, name: PropertyName) { const nameType = getLiteralTypeFromPropertyName(name); if (!isTypeUsableAsPropertyName(nameType)) return errorType; const text = getPropertyNameFromType(nameType); - return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || + return getTypeOfPropertyOfType(type, text) || isNumericLiteralName(text) && includeUndefinedInIndexSignature(getIndexTypeOfType(type, IndexKind.Number)) || includeUndefinedInIndexSignature(getIndexTypeOfType(type, IndexKind.String)) || errorType; @@ -21732,10 +22437,18 @@ namespace ts { return type.flags & TypeFlags.Union ? forEach((type).types, f) : f(type); } + function someType(type: Type, f: (t: Type) => boolean): boolean { + return type.flags & TypeFlags.Union ? some((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 everyContainedType(type: Type, f: (t: Type) => boolean): boolean { + return type.flags & TypeFlags.UnionOrIntersection ? every((type as UnionOrIntersectionType).types, f) : f(type); + } + function filterType(type: Type, f: (t: Type) => boolean): Type { if (type.flags & TypeFlags.Union) { const types = (type).types; @@ -21972,7 +22685,16 @@ namespace ts { const type = getTypeOfDottedName((node).expression, diagnostic); if (type) { const name = (node).name; - const prop = getPropertyOfType(type, isPrivateIdentifier(name) ? getSymbolNameForPrivateIdentifier(type.symbol, name.escapedText) : name.escapedText); + let prop: Symbol | undefined; + if (isPrivateIdentifier(name)) { + if (!type.symbol) { + return undefined; + } + prop = getPropertyOfType(type, getSymbolNameForPrivateIdentifier(type.symbol, name.escapedText)); + } + else { + prop = getPropertyOfType(type, name.escapedText); + } return prop && getExplicitTypeOfSymbol(prop, diagnostic); } return undefined; @@ -22182,7 +22904,7 @@ namespace ts { // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. const resultType = getObjectFlags(evolvedType) & ObjectFlags.EvolvingArray && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); - if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === SyntaxKind.NonNullExpression && getTypeWithFacts(resultType, TypeFacts.NEUndefinedOrNull).flags & TypeFlags.Never) { + if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === SyntaxKind.NonNullExpression && !(resultType.flags & TypeFlags.Never) && getTypeWithFacts(resultType, TypeFacts.NEUndefinedOrNull).flags & TypeFlags.Never) { return declaredType; } return resultType; @@ -22295,7 +23017,7 @@ namespace ts { function getInitialOrAssignedType(flow: FlowAssignment) { const node = flow.node; - return getConstraintForLocation(node.kind === SyntaxKind.VariableDeclaration || node.kind === SyntaxKind.BindingElement ? + return getNarrowableTypeForReference(node.kind === SyntaxKind.VariableDeclaration || node.kind === SyntaxKind.BindingElement ? getInitialType(node) : getAssignedType(node), reference); } @@ -22460,8 +23182,7 @@ namespace ts { } } if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr as AccessExpression, - t => narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd)); + type = narrowTypeBySwitchOnDiscriminantProperty(type, expr as AccessExpression, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } } return createFlowType(type, isIncomplete(flowType)); @@ -22635,8 +23356,7 @@ namespace ts { if (propName === undefined) { return type; } - const includesNullable = strictNullChecks && maybeTypeOfKind(type, TypeFlags.Nullable); - const removeNullable = includesNullable && isOptionalChain(access); + const removeNullable = strictNullChecks && isOptionalChain(access) && maybeTypeOfKind(type, TypeFlags.Nullable); let propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, TypeFacts.NEUndefinedOrNull) : type, propName); if (!propType) { return type; @@ -22649,6 +23369,32 @@ namespace ts { }); } + function narrowTypeByDiscriminantProperty(type: Type, access: AccessExpression, operator: SyntaxKind, value: Expression, assumeTrue: boolean) { + if ((operator === SyntaxKind.EqualsEqualsEqualsToken || operator === SyntaxKind.ExclamationEqualsEqualsToken) && type.flags & TypeFlags.Union) { + const keyPropertyName = getKeyPropertyName(type); + if (keyPropertyName && keyPropertyName === getAccessedPropertyName(access)) { + const candidate = getConstituentTypeForKeyType(type, getTypeOfExpression(value)); + if (candidate) { + return operator === (assumeTrue ? SyntaxKind.EqualsEqualsEqualsToken : SyntaxKind.ExclamationEqualsEqualsToken) ? candidate : + isUnitType(getTypeOfPropertyOfType(candidate, keyPropertyName) || unknownType) ? filterType(type, t => t !== candidate) : + type; + } + } + } + return narrowTypeByDiscriminant(type, access, t => narrowTypeByEquality(t, operator, value, assumeTrue)); + } + + function narrowTypeBySwitchOnDiscriminantProperty(type: Type, access: AccessExpression, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number) { + if (clauseStart < clauseEnd && type.flags & TypeFlags.Union && getKeyPropertyName(type) === getAccessedPropertyName(access)) { + const clauseTypes = getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd); + const candidate = getUnionType(map(clauseTypes, t => getConstituentTypeForKeyType(type, t) || unknownType)); + if (candidate !== unknownType) { + return candidate; + } + } + return narrowTypeByDiscriminant(type, access, t => narrowTypeBySwitchOnDiscriminant(t, switchStatement, clauseStart, clauseEnd)); + } + function narrowTypeByTruthiness(type: Type, expr: Expression, assumeTrue: boolean): Type { if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? TypeFacts.Truthy : TypeFacts.Falsy); @@ -22674,7 +23420,8 @@ namespace ts { } function narrowByInKeyword(type: Type, literal: LiteralExpression, assumeTrue: boolean) { - if (type.flags & (TypeFlags.Union | TypeFlags.Object) + if (type.flags & TypeFlags.Union + || type.flags & TypeFlags.Object && declaredType !== type || isThisTypeParameter(type) || type.flags & TypeFlags.Intersection && every((type as IntersectionType).types, t => t.symbol !== globalThisSymbol)) { const propName = escapeLeadingUnderscores(literal.text); @@ -22718,10 +23465,10 @@ namespace ts { } } if (isMatchingReferenceDiscriminant(left, type)) { - return narrowTypeByDiscriminant(type, left, t => narrowTypeByEquality(t, operator, right, assumeTrue)); + return narrowTypeByDiscriminantProperty(type, left, operator, right, assumeTrue); } if (isMatchingReferenceDiscriminant(right, type)) { - return narrowTypeByDiscriminant(type, right, t => narrowTypeByEquality(t, operator, left, assumeTrue)); + return narrowTypeByDiscriminantProperty(type, right, operator, left, assumeTrue); } if (isMatchingConstructorReference(left)) { return narrowTypeByConstructor(type, operator, right, assumeTrue); @@ -22794,13 +23541,12 @@ namespace ts { } if (assumeTrue) { const filterFn: (t: Type) => boolean = operator === SyntaxKind.EqualsEqualsToken ? - (t => areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType)) : + t => areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType) : t => areTypesComparable(t, valueType); return replacePrimitivesWithLiterals(filterType(type, filterFn), valueType); } if (isUnitType(valueType)) { - const regularType = getRegularTypeOfLiteralType(valueType); - return filterType(type, t => isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType); + return filterType(type, t => !(isUnitLikeType(t) && areTypesComparable(t, valueType))); } return type; } @@ -22882,7 +23628,7 @@ namespace ts { if (!hasDefaultClause) { return caseType; } - const defaultType = filterType(type, t => !(isUnitType(t) && contains(switchTypes, getRegularTypeOfLiteralType(t)))); + const defaultType = filterType(type, t => !(isUnitLikeType(t) && contains(switchTypes, getRegularTypeOfLiteralType(extractUnitType(t))))); return caseType.flags & TypeFlags.Never ? defaultType : getUnionType([caseType, defaultType]); } @@ -23083,7 +23829,16 @@ namespace ts { function getNarrowedType(type: Type, candidate: Type, assumeTrue: boolean, isRelated: (source: Type, target: Type) => boolean) { if (!assumeTrue) { - return filterType(type, t => !isRelated(t, candidate)); + return filterType(type, t => { + if (!isRelated(t, candidate)) { + return true; + } + const constraint = getBaseConstraintOfType(t); + if (constraint && constraint !== t) { + return !isRelated(constraint, candidate); + } + return false; + }); } // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. @@ -23185,17 +23940,20 @@ namespace ts { // an dotted name expression, and if the location is not an assignment target, obtain the type // of the expression (which will reflect control flow analysis). If the expression indeed // resolved to the given symbol, return the narrowed type. - if (location.kind === SyntaxKind.Identifier) { + if (location.kind === SyntaxKind.Identifier || location.kind === SyntaxKind.PrivateIdentifier) { if (isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (isExpressionNode(location) && !isAssignmentTarget(location)) { + if (isExpressionNode(location) && (!isAssignmentTarget(location) || isWriteAccess(location))) { const type = getTypeOfExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } } } + if (isDeclarationName(location) && isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) { + return resolveTypeOfAccessors(location.parent.symbol, /*writing*/ true)!; + } // The location isn't a reference to the given symbol, meaning we're being asked // a hypothetical question of what type the symbol would have if there was a reference // to it at the given location. Since we have no control flow information for the @@ -23214,6 +23972,9 @@ namespace ts { // Check if a parameter is assigned anywhere within its declaring function. function isParameterAssigned(symbol: Symbol) { + if (!symbol.valueDeclaration) { + return false; + } const func = getRootDeclaration(symbol.valueDeclaration).parent; const links = getNodeLinks(func); if (!(links.flags & NodeCheckFlags.AssignmentsMarked)) { @@ -23267,27 +24028,44 @@ namespace ts { function isConstraintPosition(node: Node) { const parent = node.parent; + // In an element access obj[x], we consider obj to be in a constraint position only when x is not + // of a generic type. This is because when both obj and x are of generic types T and K, we want + // the resulting type to be T[K]. return parent.kind === SyntaxKind.PropertyAccessExpression || parent.kind === SyntaxKind.CallExpression && (parent).expression === node || - parent.kind === SyntaxKind.ElementAccessExpression && (parent).expression === node || - parent.kind === SyntaxKind.BindingElement && (parent).name === node && !!(parent).initializer; + parent.kind === SyntaxKind.ElementAccessExpression && (parent).expression === node && + !isGenericIndexType(getTypeOfExpression((parent).argumentExpression)); } - function typeHasNullableConstraint(type: Type) { - return type.flags & TypeFlags.InstantiableNonPrimitive && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, TypeFlags.Nullable); + function isGenericTypeWithUnionConstraint(type: Type) { + return !!(type.flags & TypeFlags.Instantiable && getBaseConstraintOrType(type).flags & (TypeFlags.Nullable | TypeFlags.Union)); } - function getConstraintForLocation(type: Type, node: Node): Type; - function getConstraintForLocation(type: Type | undefined, node: Node): Type | undefined; - function getConstraintForLocation(type: Type, node: Node): Type | undefined { - // When a node is the left hand expression of a property access, element access, or call expression, - // and the type of the node includes type variables with constraints that are nullable, we fetch the - // apparent type of the node *before* performing control flow analysis such that narrowings apply to - // the constraint type. - if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { - return mapType(getWidenedType(type), getBaseConstraintOrType); - } - return type; + function containsGenericType(type: Type): boolean { + return !!(type.flags & TypeFlags.Instantiable || type.flags & TypeFlags.UnionOrIntersection && some((type).types, containsGenericType)); + } + + function hasContextualTypeWithNoGenericTypes(node: Node) { + // Computing the contextual type for a child of a JSX element involves resolving the type of the + // element's tag name, so we exclude that here to avoid circularities. + const contextualType = (isIdentifier(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node)) && + !((isJsxOpeningElement(node.parent) || isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && + getContextualType(node); + return contextualType && !someType(contextualType, containsGenericType); + } + + function getNarrowableTypeForReference(type: Type, reference: Node, checkMode?: CheckMode) { + // When the type of a reference is or contains an instantiable type with a union type constraint, and + // when the reference is in a constraint position (where it is known we'll obtain the apparent type) or + // has a contextual type containing no top-level instantiables (meaning constraints will determine + // assignability), we substitute constraints for all instantiables in the type of the reference to give + // control flow analysis an opportunity to narrow it further. For example, for a reference of a type + // parameter type 'T extends string | undefined' with a contextual type 'string', we substitute + // 'string | undefined' to give control flow analysis the opportunity to narrow to type 'string'. + const substituteConstraints = !(checkMode && checkMode & CheckMode.Inferential) && + someType(type, isGenericTypeWithUnionConstraint) && + (isConstraintPosition(reference) || hasContextualTypeWithNoGenericTypes(reference)); + return substituteConstraints ? mapType(type, t => t.flags & TypeFlags.Instantiable ? getBaseConstraintOrType(t) : t) : type; } function isExportOrExportExpression(location: Node) { @@ -23314,7 +24092,7 @@ namespace ts { } } - function checkIdentifier(node: Identifier): Type { + function checkIdentifier(node: Identifier, checkMode: CheckMode | undefined): Type { const symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { return errorType; @@ -23349,12 +24127,12 @@ namespace ts { const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); const sourceSymbol = localOrExportSymbol.flags & SymbolFlags.Alias ? resolveAlias(localOrExportSymbol) : localOrExportSymbol; - if (getDeclarationNodeFlagsFromSymbol(sourceSymbol) & NodeFlags.Deprecated && isUncalledFunctionReference(node, sourceSymbol)) { + if (sourceSymbol.declarations && getDeclarationNodeFlagsFromSymbol(sourceSymbol) & NodeFlags.Deprecated && isUncalledFunctionReference(node, sourceSymbol)) { addDeprecatedSuggestion(node, sourceSymbol.declarations, node.escapedText as string); } - let declaration: Declaration | undefined = localOrExportSymbol.valueDeclaration; - if (localOrExportSymbol.flags & SymbolFlags.Class) { + let declaration = localOrExportSymbol.valueDeclaration; + if (declaration && localOrExportSymbol.flags & SymbolFlags.Class) { // 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. @@ -23392,13 +24170,20 @@ namespace ts { checkNestedBlockScopedBinding(node, symbol); - const type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); + let type = getTypeOfSymbol(localOrExportSymbol); const assignmentKind = getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & SymbolFlags.Variable) && !(isInJSFile(node) && localOrExportSymbol.flags & SymbolFlags.ValueModule)) { - error(node, Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + const assignmentError = localOrExportSymbol.flags & SymbolFlags.Enum ? Diagnostics.Cannot_assign_to_0_because_it_is_an_enum + : localOrExportSymbol.flags & SymbolFlags.Class ? Diagnostics.Cannot_assign_to_0_because_it_is_a_class + : localOrExportSymbol.flags & SymbolFlags.Module ? Diagnostics.Cannot_assign_to_0_because_it_is_a_namespace + : localOrExportSymbol.flags & SymbolFlags.Function ? Diagnostics.Cannot_assign_to_0_because_it_is_a_function + : localOrExportSymbol.flags & SymbolFlags.Alias ? Diagnostics.Cannot_assign_to_0_because_it_is_an_import + : Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable; + + error(node, assignmentError, symbolToString(symbol)); return errorType; } if (isReadonlySymbol(localOrExportSymbol)) { @@ -23422,7 +24207,7 @@ namespace ts { } } else if (isAlias) { - declaration = find(symbol.declarations, isSomeImportDeclaration); + declaration = getDeclarationOfAliasSymbol(symbol); } else { return type; @@ -23432,6 +24217,8 @@ namespace ts { return type; } + type = getNarrowableTypeForReference(type, node, checkMode); + // The declaration container is the innermost function that encloses the declaration of the variable // or parameter. The flow container is the innermost function starting with which we analyze the control // flow graph to determine the control flow based type. @@ -23482,17 +24269,24 @@ namespace ts { return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } - function isInsideFunction(node: Node, threshold: Node): boolean { - return !!findAncestor(node, n => n === threshold ? "quit" : isFunctionLike(n)); + function isInsideFunctionOrInstancePropertyInitializer(node: Node, threshold: Node): boolean { + return !!findAncestor(node, n => n === threshold ? "quit" : isFunctionLike(n) || ( + n.parent && isPropertyDeclaration(n.parent) && !hasStaticModifier(n.parent) && n.parent.initializer === 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 getEnclosingIterationStatement(node: Node): Node | undefined { + return findAncestor(node, n => (!n || nodeStartsNewLexicalEnvironment(n)) ? "quit" : isIterationStatement(n, /*lookInLabeledStatements*/ false)); + } + function checkNestedBlockScopedBinding(node: Identifier, symbol: Symbol): void { if (languageVersion >= ScriptTarget.ES2015 || (symbol.flags & (SymbolFlags.BlockScopedVariable | SymbolFlags.Class)) === 0 || + !symbol.valueDeclaration || isSourceFile(symbol.valueDeclaration) || symbol.valueDeclaration.parent.kind === SyntaxKind.CatchClause) { return; @@ -23504,20 +24298,11 @@ namespace ts { // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration); - const usedInFunction = isInsideFunction(node.parent, container); - let current = container; + const isCaptured = isInsideFunctionOrInstancePropertyInitializer(node, container); - let containedInIterationStatement = false; - while (current && !nodeStartsNewLexicalEnvironment(current)) { - if (isIterationStatement(current, /*lookInLabeledStatements*/ false)) { - containedInIterationStatement = true; - break; - } - current = current.parent; - } - - if (containedInIterationStatement) { - if (usedInFunction) { + const enclosingIterationStatement = getEnclosingIterationStatement(container); + if (enclosingIterationStatement) { + if (isCaptured) { // mark iteration statement as containing block-scoped binding captured in some function let capturesBlockScopeBindingInLoopBody = true; if (isForStatement(container)) { @@ -23538,7 +24323,7 @@ namespace ts { } } if (capturesBlockScopeBindingInLoopBody) { - getNodeLinks(current).flags |= NodeCheckFlags.LoopWithCapturedBlockScopedBinding; + getNodeLinks(enclosingIterationStatement).flags |= NodeCheckFlags.LoopWithCapturedBlockScopedBinding; } } @@ -23555,7 +24340,7 @@ namespace ts { getNodeLinks(symbol.valueDeclaration).flags |= NodeCheckFlags.BlockScopedBindingInLoop; } - if (usedInFunction) { + if (isCaptured) { getNodeLinks(symbol.valueDeclaration).flags |= NodeCheckFlags.CapturedBlockScopedBinding; } } @@ -23667,7 +24452,7 @@ namespace ts { break; case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: - if (hasSyntacticModifier(container, ModifierFlags.Static) && !(compilerOptions.target === ScriptTarget.ESNext && compilerOptions.useDefineForClassFields)) { + if (hasSyntacticModifier(container, ModifierFlags.Static) && !(compilerOptions.target === ScriptTarget.ESNext && useDefineForClassFields)) { error(node, Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } @@ -24367,12 +25152,11 @@ namespace ts { switch (kind) { case AssignmentDeclarationKind.None: return getTypeOfExpression(binaryExpression.left); + case AssignmentDeclarationKind.ThisProperty: + return getContextualTypeForThisPropertyAssignment(binaryExpression); case AssignmentDeclarationKind.Property: - case AssignmentDeclarationKind.ExportsProperty: - case AssignmentDeclarationKind.Prototype: - case AssignmentDeclarationKind.PrototypeProperty: if (isPossiblyAliasedThisProperty(binaryExpression, kind)) { - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + return getContextualTypeForThisPropertyAssignment(binaryExpression); } // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. // See `bindStaticPropertyAssignment` in `binder.ts`. @@ -24405,9 +25189,15 @@ namespace ts { } return isInJSFile(decl) ? undefined : getTypeOfExpression(binaryExpression.left); } + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.Prototype: + case AssignmentDeclarationKind.PrototypeProperty: + let valueDeclaration = binaryExpression.left.symbol?.valueDeclaration; + // falls through case AssignmentDeclarationKind.ModuleExports: - case AssignmentDeclarationKind.ThisProperty: - return getContextualTypeForThisPropertyAssignment(binaryExpression, kind); + valueDeclaration ||= binaryExpression.symbol?.valueDeclaration; + const annotated = valueDeclaration && getEffectiveTypeAnnotationNode(valueDeclaration); + return annotated ? getTypeFromTypeNode(annotated) : undefined; case AssignmentDeclarationKind.ObjectDefinePropertyValue: case AssignmentDeclarationKind.ObjectDefinePropertyExports: case AssignmentDeclarationKind.ObjectDefinePrototypeProperty: @@ -24429,7 +25219,7 @@ namespace ts { return isThisInitializedDeclaration(symbol?.valueDeclaration); } - function getContextualTypeForThisPropertyAssignment(binaryExpression: BinaryExpression, kind: AssignmentDeclarationKind): Type | undefined { + function getContextualTypeForThisPropertyAssignment(binaryExpression: BinaryExpression): Type | undefined { if (!binaryExpression.symbol) return getTypeOfExpression(binaryExpression.left); if (binaryExpression.symbol.valueDeclaration) { const annotated = getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); @@ -24440,7 +25230,6 @@ namespace ts { } } } - if (kind === AssignmentDeclarationKind.ModuleExports) return undefined; const thisAccess = cast(binaryExpression.left, isAccessExpression); if (!isObjectLiteralMethod(getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { return undefined; @@ -24501,6 +25290,10 @@ namespace ts { function getContextualTypeForObjectLiteralElement(element: ObjectLiteralElementLike, contextFlags?: ContextFlags) { const objectLiteral = element.parent; + const propertyAssignmentType = isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element); + if (propertyAssignmentType) { + return propertyAssignmentType; + } const type = getApparentTypeOfContextualType(objectLiteral, contextFlags); if (type) { if (hasBindableName(element)) { @@ -24608,10 +25401,16 @@ namespace ts { } 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]) + return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, + concatenate( + map( + filter(node.properties, p => !!p.symbol && p.kind === SyntaxKind.PropertyAssignment && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName)), + prop => ([() => getContextFreeTypeOfExpression((prop as PropertyAssignment).initializer), prop.symbol.escapedName] as [() => Type, __String]) + ), + map( + filter(getPropertiesOfType(contextualType), s => !!(s.flags & SymbolFlags.Optional) && !!node?.symbol?.members && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName)), + s => [() => undefinedType, s.escapedName] as [() => Type, __String] + ) ), isTypeAssignableTo, contextualType @@ -24620,9 +25419,15 @@ namespace ts { 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]) + concatenate( + 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]) + ), + map( + filter(getPropertiesOfType(contextualType), s => !!(s.flags & SymbolFlags.Optional) && !!node?.symbol?.members && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName)), + s => [() => undefinedType, s.escapedName] as [() => Type, __String] + ) ), isTypeAssignableTo, contextualType @@ -24638,15 +25443,9 @@ namespace ts { const instantiatedType = instantiateContextualType(contextualType, node, contextFlags); if (instantiatedType && !(contextFlags && contextFlags & ContextFlags.NoConstraints && instantiatedType.flags & TypeFlags.TypeVariable)) { const apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true); - if (apparentType.flags & TypeFlags.Union) { - if (isObjectLiteralExpression(node)) { - return discriminateContextualTypeByObjectMembers(node, apparentType as UnionType); - } - else if (isJsxAttributes(node)) { - return discriminateContextualTypeByJSXAttributes(node, apparentType as UnionType); - } - } - return apparentType; + return apparentType.flags & TypeFlags.Union && isObjectLiteralExpression(node) ? discriminateContextualTypeByObjectMembers(node, apparentType as UnionType) : + apparentType.flags & TypeFlags.Union && isJsxAttributes(node) ? discriminateContextualTypeByJSXAttributes(node, apparentType as UnionType) : + apparentType; } } @@ -24745,7 +25544,7 @@ namespace ts { case SyntaxKind.ShorthandPropertyAssignment: return getContextualTypeForObjectLiteralElement(parent, contextFlags); case SyntaxKind.SpreadAssignment: - return getApparentTypeOfContextualType(parent.parent as ObjectLiteralExpression, contextFlags); + return getContextualType(parent.parent as ObjectLiteralExpression, contextFlags); case SyntaxKind.ArrayLiteralExpression: { const arrayLiteral = parent; const type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); @@ -24811,14 +25610,14 @@ namespace ts { } function getJsxPropsTypeForSignatureFromMember(sig: Signature, forcedLookupLocation: __String) { - if (sig.unionSignatures) { + if (sig.compositeSignatures) { // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature, // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur // for a union signature). It's an unfortunate quirk of looking in the output of the signature for the type we want to use for the input. // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane. const results: Type[] = []; - for (const signature of sig.unionSignatures) { + for (const signature of sig.compositeSignatures) { const instance = getReturnTypeOfSignature(signature); if (isTypeAny(instance)) { return instance; @@ -24829,7 +25628,7 @@ namespace ts { } results.push(propType); } - return getIntersectionType(results); + return getIntersectionType(results); // Same result for both union and intersection signatures } const instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); @@ -24923,16 +25722,109 @@ namespace ts { } } + function getIntersectedSignatures(signatures: readonly Signature[]) { + return getStrictOptionValue(compilerOptions, "noImplicitAny") + ? reduceLeft( + signatures, + (left, right) => + left === right || !left ? left + : compareTypeParametersIdentical(left.typeParameters, right.typeParameters) ? combineSignaturesOfIntersectionMembers(left, right) + : undefined) + : undefined; + } + + function combineIntersectionThisParam(left: Symbol | undefined, right: Symbol | undefined, mapper: TypeMapper | undefined): Symbol | undefined { + if (!left || !right) { + return left || right; + } + // A signature `this` type might be a read or a write position... It's very possible that it should be invariant + // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be + // pessimistic when contextual typing, for now, we'll union the `this` types. + const thisType = getUnionType([getTypeOfSymbol(left), instantiateType(getTypeOfSymbol(right), mapper)]); + return createSymbolWithType(left, thisType); + } + + function combineIntersectionParameters(left: Signature, right: Signature, mapper: TypeMapper | undefined) { + const leftCount = getParameterCount(left); + const rightCount = getParameterCount(right); + const longest = leftCount >= rightCount ? left : right; + const shorter = longest === left ? right : left; + const longestCount = longest === left ? leftCount : rightCount; + const eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right)); + const needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest); + const params = new Array(longestCount + (needsExtraRestElement ? 1 : 0)); + for (let i = 0; i < longestCount; i++) { + let longestParamType = tryGetTypeAtPosition(longest, i)!; + if (longest === right) { + longestParamType = instantiateType(longestParamType, mapper); + } + let shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType; + if (shorter === right) { + shorterParamType = instantiateType(shorterParamType, mapper); + } + const unionParamType = getUnionType([longestParamType, shorterParamType]); + const isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1); + const isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter); + const leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i); + const rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i); + + const paramName = leftName === rightName ? leftName : + !leftName ? rightName : + !rightName ? leftName : + undefined; + const paramSymbol = createSymbol( + SymbolFlags.FunctionScopedVariable | (isOptional && !isRestParam ? SymbolFlags.Optional : 0), + paramName || `arg${i}` as __String + ); + paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType; + params[i] = paramSymbol; + } + if (needsExtraRestElement) { + const restParamSymbol = createSymbol(SymbolFlags.FunctionScopedVariable, "args" as __String); + restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount)); + if (shorter === right) { + restParamSymbol.type = instantiateType(restParamSymbol.type, mapper); + } + params[longestCount] = restParamSymbol; + } + return params; + } + + function combineSignaturesOfIntersectionMembers(left: Signature, right: Signature): Signature { + const typeParams = left.typeParameters || right.typeParameters; + let paramMapper: TypeMapper | undefined; + if (left.typeParameters && right.typeParameters) { + paramMapper = createTypeMapper(right.typeParameters, left.typeParameters); + // We just use the type parameter defaults from the first signature + } + const declaration = left.declaration; + const params = combineIntersectionParameters(left, right, paramMapper); + const thisParam = combineIntersectionThisParam(left.thisParameter, right.thisParameter, paramMapper); + const minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); + const result = createSignature( + declaration, + typeParams, + thisParam, + params, + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, + minArgCount, + (left.flags | right.flags) & SignatureFlags.PropagatingFlags + ); + result.compositeKind = TypeFlags.Intersection; + result.compositeSignatures = concatenate(left.compositeKind === TypeFlags.Intersection && left.compositeSignatures || [left], [right]); + if (paramMapper) { + result.mapper = left.compositeKind === TypeFlags.Intersection && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper; + } + return result; + } + // If the given type is an object or union type with a single signature, and if that signature has at // least as many parameters as the given function, return the signature. Otherwise return undefined. function getContextualCallSignature(type: Type, node: SignatureDeclaration): Signature | undefined { const signatures = getSignaturesOfType(type, SignatureKind.Call); - if (signatures.length === 1) { - const signature = signatures[0]; - if (!isAritySmaller(signature, node)) { - return signature; - } - } + const applicableByArity = filter(signatures, s => !isAritySmaller(s, node)); + return applicableByArity.length === 1 ? applicableByArity[0] : getIntersectedSignatures(applicableByArity); } /** If the contextual signature has fewer parameters than the function expression, do not use it */ @@ -25075,7 +25967,7 @@ namespace ts { if (inDestructuringPattern) { return createTupleType(elementTypes, elementFlags); } - if (forceTuple || inConstContext || contextualType && forEachType(contextualType, isTupleLikeType)) { + if (forceTuple || inConstContext || contextualType && someType(contextualType, isTupleLikeType)) { return createArrayLiteralType(createTupleType(elementTypes, elementFlags, /*readonly*/ inConstContext)); } return createArrayLiteralType(createArrayType(elementTypes.length ? @@ -25148,6 +26040,20 @@ namespace ts { const links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); + // The computed property name of a non-static class field within a loop must be stored in a block-scoped binding. + // (It needs to be bound at class evaluation time.) + if (isPropertyDeclaration(node.parent) && !hasStaticModifier(node.parent) && isClassExpression(node.parent.parent)) { + const container = getEnclosingBlockScopeContainer(node.parent.parent); + const enclosingIterationStatement = getEnclosingIterationStatement(container); + if (enclosingIterationStatement) { + // The computed field name will use a block scoped binding which can be unique for each iteration of the loop. + getNodeLinks(enclosingIterationStatement).flags |= NodeCheckFlags.LoopWithCapturedBlockScopedBinding; + // The generated variable which stores the computed field name must be block-scoped. + getNodeLinks(node).flags |= NodeCheckFlags.BlockScopedBindingInLoop; + // The generated variable which stores the class must be block-scoped. + getNodeLinks(node.parent.parent).flags |= NodeCheckFlags.BlockScopedBindingInLoop; + } + } // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). if (links.resolvedType.flags & TypeFlags.Nullable || @@ -25155,9 +26061,6 @@ namespace ts { !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { error(node, Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } - else { - checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true); - } } return links.resolvedType; @@ -25218,7 +26121,7 @@ namespace ts { // As otherwise they may not be checked until exports for the type at this position are retrieved, // which may never occur. for (const elem of node.properties) { - if (elem.name && isComputedPropertyName(elem.name) && !isWellKnownSymbolSyntactically(elem.name)) { + if (elem.name && isComputedPropertyName(elem.name)) { checkComputedPropertyName(elem.name); } } @@ -25226,7 +26129,7 @@ namespace ts { let offset = 0; for (const memberDecl of node.properties) { let member = getSymbolOfNode(memberDecl); - const computedNameType = memberDecl.name && memberDecl.name.kind === SyntaxKind.ComputedPropertyName && !isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + const computedNameType = memberDecl.name && memberDecl.name.kind === SyntaxKind.ComputedPropertyName ? checkComputedPropertyName(memberDecl.name) : undefined; if (memberDecl.kind === SyntaxKind.PropertyAssignment || memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment || @@ -25303,15 +26206,20 @@ namespace ts { hasComputedNumberProperty = false; } const type = getReducedType(checkExpression(memberDecl.expression)); - if (!isValidSpreadType(type)) { - error(memberDecl, Diagnostics.Spread_types_may_only_be_created_from_object_types); - return errorType; + if (isValidSpreadType(type)) { + if (allPropertiesTable) { + checkSpreadPropOverrides(type, allPropertiesTable, memberDecl); + } + offset = propertiesArray.length; + if (spread === errorType) { + continue; + } + spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext); } - if (allPropertiesTable) { - checkSpreadPropOverrides(type, allPropertiesTable, memberDecl); + else { + error(memberDecl, Diagnostics.Spread_types_may_only_be_created_from_object_types); + spread = errorType; } - spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext); - offset = propertiesArray.length; continue; } else { @@ -25360,6 +26268,10 @@ namespace ts { } } + if (spread === errorType) { + return errorType; + } + if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext); @@ -25555,7 +26467,7 @@ namespace ts { // 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, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - childrenContextualType && forEachType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : + childrenContextualType && someType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : createArrayType(getUnionType(childrenTypes)); // Fake up a property declaration for the children childrenPropSymbol.valueDeclaration = factory.createPropertySignature(/*modifiers*/ undefined, unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined); @@ -25760,7 +26672,7 @@ namespace ts { else if (propertiesOfJsxElementAttribPropInterface.length === 1) { return propertiesOfJsxElementAttribPropInterface[0].escapedName; } - else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + else if (propertiesOfJsxElementAttribPropInterface.length > 1 && jsxElementAttribPropInterfaceSym!.declarations) { // More than one property on ElementAttributesProperty is an error error(jsxElementAttribPropInterfaceSym!.declarations[0], Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, unescapeLeadingUnderscores(nameOfAttribPropContainer)); } @@ -25878,11 +26790,11 @@ namespace ts { if (!links.resolvedJsxElementAttributesType) { const symbol = getIntrinsicTagSymbol(node); if (links.jsxFlags & JsxFlags.IntrinsicNamedElement) { - return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol) || errorType; } else if (links.jsxFlags & JsxFlags.IntrinsicIndexedElement) { return links.resolvedJsxElementAttributesType = - getIndexTypeOfType(getDeclaredTypeOfSymbol(symbol), IndexKind.String)!; + getIndexTypeOfType(getJsxType(JsxNames.IntrinsicElements, node), IndexKind.String) || errorType; } else { return links.resolvedJsxElementAttributesType = errorType; @@ -26039,7 +26951,7 @@ namespace ts { return true; } if (isInJSFile(symbol.valueDeclaration)) { - const parent = symbol.valueDeclaration.parent; + const parent = symbol.valueDeclaration!.parent; return parent && isBinaryExpression(parent) && getAssignmentDeclarationKind(parent) === AssignmentDeclarationKind.PrototypeProperty; } @@ -26055,9 +26967,12 @@ namespace ts { */ function checkPropertyAccessibility( node: PropertyAccessExpression | QualifiedName | PropertyAccessExpression | VariableDeclaration | ParameterDeclaration | ImportTypeNode | PropertyAssignment | ShorthandPropertyAssignment | BindingElement, - isSuper: boolean, type: Type, prop: Symbol): boolean { - const flags = getDeclarationModifierFlagsFromSymbol(prop); - const errorNode = node.kind === SyntaxKind.QualifiedName ? node.right : node.kind === SyntaxKind.ImportType ? node : node.name; + isSuper: boolean, writing: boolean, type: Type, prop: Symbol, reportError = true): boolean { + + const flags = getDeclarationModifierFlagsFromSymbol(prop, writing); + const errorNode = node.kind === SyntaxKind.QualifiedName ? node.right : + node.kind === SyntaxKind.ImportType ? node : + node.kind === SyntaxKind.BindingElement && node.propertyName ? node.propertyName : node.name; if (isSuper) { // TS 1.0 spec (April 2014): 4.8.2 @@ -26069,7 +26984,9 @@ namespace ts { // a super property access is permitted and must specify a public static member function of the base class. if (languageVersion < ScriptTarget.ES2015) { if (symbolHasNonMethodDeclaration(prop)) { - error(errorNode, Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + if (reportError) { + error(errorNode, Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + } return false; } } @@ -26078,26 +26995,23 @@ namespace ts { // This error could mask a private property access error. But, a member // cannot simultaneously be private and abstract, so this will trigger an // additional error elsewhere. - error(errorNode, Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)!)); + if (reportError) { + error(errorNode, Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)!)); + } return false; } } // Referencing abstract properties within their own constructors is not allowed - if ((flags & ModifierFlags.Abstract) && isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { + if ((flags & ModifierFlags.Abstract) && symbolHasNonMethodDeclaration(prop) && + (isThisProperty(node) || isThisInitializedObjectBindingExpression(node) || isObjectBindingPattern(node.parent) && isThisInitializedDeclaration(node.parent.parent))) { const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)!); 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; - } - } - - if (isPropertyAccessExpression(node) && isPrivateIdentifier(node.name)) { - if (!getContainingClass(node)) { - error(errorNode, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + if (reportError) { + 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; } - return true; } // Public properties are otherwise accessible. @@ -26111,7 +27025,9 @@ namespace ts { if (flags & ModifierFlags.Private) { const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)!)!; if (!isNodeWithinClass(node, declaringClassDeclaration)) { - error(errorNode, Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)!)); + if (reportError) { + error(errorNode, Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)!)); + } return false; } return true; @@ -26128,7 +27044,7 @@ namespace ts { // of the property as base classes let enclosingClass = forEachEnclosingClass(node, enclosingDeclaration => { const enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)!); - return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + return isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing) ? enclosingClass : undefined; }); // A protected property is accessible if the property is within the declaring class or classes derived from it if (!enclosingClass) { @@ -26136,7 +27052,9 @@ namespace ts { // static member access is disallow let thisParameter: ParameterDeclaration | undefined; if (flags & ModifierFlags.Static || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) { - error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + if (reportError) { + error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + } return false; } @@ -26152,7 +27070,9 @@ namespace ts { type = (type as TypeParameter).isThisType ? getConstraintOfTypeParameter(type)! : getBaseConstraintOfType(type)!; // TODO: GH#18217 Use a different variable that's allowed to be undefined } if (!type || !hasBaseType(type, enclosingClass)) { - error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + if (reportError) { + error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2, symbolToString(prop), typeToString(enclosingClass), typeToString(type)); + } return false; } return true; @@ -26225,19 +27145,19 @@ namespace ts { return nonNullType; } - function checkPropertyAccessExpression(node: PropertyAccessExpression) { - return node.flags & NodeFlags.OptionalChain ? checkPropertyAccessChain(node as PropertyAccessChain) : - checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + function checkPropertyAccessExpression(node: PropertyAccessExpression, checkMode: CheckMode | undefined) { + return node.flags & NodeFlags.OptionalChain ? checkPropertyAccessChain(node as PropertyAccessChain, checkMode) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name, checkMode); } - function checkPropertyAccessChain(node: PropertyAccessChain) { + function checkPropertyAccessChain(node: PropertyAccessChain, checkMode: CheckMode | undefined) { const leftType = checkExpression(node.expression); const nonOptionalType = getOptionalExpressionType(leftType, node.expression); - return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name, checkMode), node, nonOptionalType !== leftType); } - function checkQualifiedName(node: QualifiedName) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); + function checkQualifiedName(node: QualifiedName, checkMode: CheckMode | undefined) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right, checkMode); } function isMethodAccessForCall(node: Node) { @@ -26279,14 +27199,13 @@ namespace ts { } const diagName = diagnosticName(right); if (propertyOnType) { - const typeValueDecl = propertyOnType.valueDeclaration; - const typeClass = getContainingClass(typeValueDecl); - Debug.assert(!!typeClass); + const typeValueDecl = Debug.checkDefined(propertyOnType.valueDeclaration); + const typeClass = Debug.checkDefined(getContainingClass(typeValueDecl)); // We found a private identifier property with the same description. // Either: // - There is a lexically scoped private identifier AND it shadows the one we found on the type. // - It is an attempt to access the private identifier outside of the class. - if (lexicallyScopedIdentifier) { + if (lexicallyScopedIdentifier?.valueDeclaration) { const lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration; const lexicalClass = getContainingClass(lexicalValueDecl); Debug.assert(!!lexicalClass); @@ -26330,17 +27249,50 @@ namespace ts { && getThisContainer(node, /*includeArrowFunctions*/ true) === getDeclaringConstructor(prop); } - function checkPropertyAccessExpressionOrQualifiedName(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, leftType: Type, right: Identifier | PrivateIdentifier) { + function checkPropertyAccessExpressionOrQualifiedName(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, leftType: Type, right: Identifier | PrivateIdentifier, checkMode: CheckMode | undefined) { const parentSymbol = getNodeLinks(left).resolvedSymbol; const assignmentKind = getAssignmentTargetKind(node); const apparentType = getApparentType(assignmentKind !== AssignmentKind.None || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); - if (isPrivateIdentifier(right)) { - checkExternalEmitHelpers(node, ExternalEmitHelpers.ClassPrivateFieldGet); - } const isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType; let prop: Symbol | undefined; if (isPrivateIdentifier(right)) { + if (languageVersion < ScriptTarget.ESNext) { + if (assignmentKind !== AssignmentKind.None) { + checkExternalEmitHelpers(node, ExternalEmitHelpers.ClassPrivateFieldSet); + } + if (assignmentKind !== AssignmentKind.Definite) { + checkExternalEmitHelpers(node, ExternalEmitHelpers.ClassPrivateFieldGet); + } + } + const lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right); + if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) { + grammarErrorOnNode(right, Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, idText(right)); + } + + if (lexicallyScopedSymbol?.valueDeclaration && (compilerOptions.target === ScriptTarget.ESNext && !useDefineForClassFields)) { + const lexicalClass = getContainingClass(lexicallyScopedSymbol.valueDeclaration); + const parentStaticFieldInitializer = findAncestor(node, (n) => { + if (n === lexicalClass) return "quit"; + if (isPropertyDeclaration(n.parent) && hasStaticModifier(n.parent) && n.parent.initializer === n && n.parent.parent === lexicalClass) { + return true; + } + return false; + }); + if (parentStaticFieldInitializer) { + const parentStaticFieldInitializerSymbol = getSymbolOfNode(parentStaticFieldInitializer.parent); + Debug.assert(parentStaticFieldInitializerSymbol, "Initializer without declaration symbol"); + const diagnostic = error(node, + Diagnostics.Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false, + symbolName(lexicallyScopedSymbol)); + addRelatedInfo(diagnostic, + createDiagnosticForNode(parentStaticFieldInitializer.parent, + Diagnostics.Initializer_for_property_0, + symbolName(parentStaticFieldInitializerSymbol)) + ); + } + } + if (isAnyLike) { if (lexicallyScopedSymbol) { return apparentType; @@ -26355,6 +27307,12 @@ namespace ts { if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) { return errorType; } + else { + const isSetonlyAccessor = prop && prop.flags & SymbolFlags.SetAccessor && !(prop.flags & SymbolFlags.GetAccessor); + if (isSetonlyAccessor && assignmentKind !== AssignmentKind.Definite) { + error(node, Diagnostics.Private_accessor_was_defined_without_a_getter); + } + } } else { if (isAnyLike) { @@ -26404,34 +27362,41 @@ namespace ts { } } else { - if (getDeclarationNodeFlagsFromSymbol(prop) & NodeFlags.Deprecated && isUncalledFunctionReference(node, prop)) { + if (prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & NodeFlags.Deprecated && isUncalledFunctionReference(node, prop)) { addDeprecatedSuggestion(right, prop.declarations, right.escapedText as string); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); - markPropertyAsReferenced(prop, node, left.kind === SyntaxKind.ThisKeyword); + markPropertyAsReferenced(prop, node, isSelfTypeAccess(left, parentSymbol)); getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left.kind === SyntaxKind.SuperKeyword, apparentType, prop); + const writing = isWriteAccess(node); + checkPropertyAccessibility(node, left.kind === SyntaxKind.SuperKeyword, writing, apparentType, prop); if (isAssignmentToReadonlyEntity(node as Expression, prop, assignmentKind)) { error(right, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, idText(right)); return errorType; } - propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : getConstraintForLocation(getTypeOfSymbol(prop), node); + + propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : writing ? getSetAccessorTypeOfSymbol(prop) : getTypeOfSymbol(prop); } - return getFlowTypeOfAccessExpression(node, prop, propType, right); + + return getFlowTypeOfAccessExpression(node, prop, propType, right, checkMode); } - function getFlowTypeOfAccessExpression(node: ElementAccessExpression | PropertyAccessExpression | QualifiedName, prop: Symbol | undefined, propType: Type, errorNode: Node) { + function getFlowTypeOfAccessExpression(node: ElementAccessExpression | PropertyAccessExpression | QualifiedName, prop: Symbol | undefined, propType: Type, errorNode: Node, checkMode: CheckMode | undefined) { // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. const assignmentKind = getAssignmentTargetKind(node); if (assignmentKind === AssignmentKind.Definite || - prop && !(prop.flags & (SymbolFlags.Variable | SymbolFlags.Property | SymbolFlags.Accessor)) && !(prop.flags & SymbolFlags.Method && propType.flags & TypeFlags.Union)) { + prop && + !(prop.flags & (SymbolFlags.Variable | SymbolFlags.Property | SymbolFlags.Accessor)) + && !(prop.flags & SymbolFlags.Method && propType.flags & TypeFlags.Union) + && !isDuplicatedCommonJSExport(prop.declarations)) { return propType; } if (propType === autoType) { return getFlowTypeOfProperty(node, prop); } + propType = getNarrowableTypeForReference(propType, node, checkMode); // If strict null checks and strict property initialization checks are enabled, if we have // a this.xxx property access, if the property is an instance property without an initializer, // and if we are in a constructor of the same class as the property declaration, assume that @@ -26470,9 +27435,10 @@ namespace ts { let diagnosticMessage; const declarationName = idText(right); if (isInPropertyInitializer(node) + && !isOptionalPropertyDeclaration(valueDeclaration) && !(isAccessExpression(node) && isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) - && !isPropertyDeclaredInAncestorClass(prop)) { + && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { diagnosticMessage = error(right, Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } else if (valueDeclaration.kind === SyntaxKind.ClassDeclaration && @@ -26581,7 +27547,10 @@ namespace ts { relatedInfo = suggestion.valueDeclaration && createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), Diagnostics.Property_0_does_not_exist_on_type_1, missingProperty, container); + const diagnostic = containerSeemsToBeEmptyDomElement(containingType) + ? Diagnostics.Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom + : Diagnostics.Property_0_does_not_exist_on_type_1; + errorInfo = chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), diagnostic, missingProperty, container); } } } @@ -26593,9 +27562,15 @@ namespace ts { diagnostics.add(resultDiagnostic); } + function containerSeemsToBeEmptyDomElement(containingType: Type) { + return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && + everyContainedType(containingType, type => type.symbol && /^(EventTarget|Node|((HTML[a-zA-Z]*)?Element))$/.test(unescapeLeadingUnderscores(type.symbol.escapedName))) && + isEmptyObjectType(containingType); + } + function typeHasStaticProperty(propName: __String, containingType: Type): boolean { const prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); - return prop !== undefined && prop.valueDeclaration && hasSyntacticModifier(prop.valueDeclaration, ModifierFlags.Static); + return prop !== undefined && !!prop.valueDeclaration && hasSyntacticModifier(prop.valueDeclaration, ModifierFlags.Static); } function getSuggestedLibForNonExistentName(name: __String | Identifier) { @@ -26627,7 +27602,15 @@ namespace ts { } function getSuggestedSymbolForNonexistentProperty(name: Identifier | PrivateIdentifier | string, containingType: Type): Symbol | undefined { - return getSpellingSuggestionForName(isString(name) ? name : idText(name), getPropertiesOfType(containingType), SymbolFlags.Value); + let props = getPropertiesOfType(containingType); + if (typeof name !== "string") { + const parent = name.parent; + if (isPropertyAccessExpression(parent)) { + props = filter(props, prop => isValidPropertyAccessForCompletions(parent, containingType, prop)); + } + name = idText(name); + } + return getSpellingSuggestionForName(name, props, SymbolFlags.Value); } function getSuggestedSymbolForNonexistentJSXAttribute(name: Identifier | PrivateIdentifier | string, containingType: Type): Symbol | undefined { @@ -26737,21 +27720,20 @@ namespace ts { } } - function markPropertyAsReferenced(prop: Symbol, nodeForCheckWriteOnly: Node | undefined, isThisAccess: boolean) { + function markPropertyAsReferenced(prop: Symbol, nodeForCheckWriteOnly: Node | undefined, isSelfTypeAccess: boolean) { const valueDeclaration = prop && (prop.flags & SymbolFlags.ClassMember) && prop.valueDeclaration; if (!valueDeclaration) { return; } const hasPrivateModifier = hasEffectiveModifier(valueDeclaration, ModifierFlags.Private); - const hasPrivateIdentifier = isNamedDeclaration(prop.valueDeclaration) && isPrivateIdentifier(prop.valueDeclaration.name); + const hasPrivateIdentifier = prop.valueDeclaration && isNamedDeclaration(prop.valueDeclaration) && isPrivateIdentifier(prop.valueDeclaration.name); if (!hasPrivateModifier && !hasPrivateIdentifier) { return; } if (nodeForCheckWriteOnly && isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & SymbolFlags.SetAccessor)) { return; } - - if (isThisAccess) { + if (isSelfTypeAccess) { // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters). const containingMethod = findAncestor(nodeForCheckWriteOnly, isFunctionLikeDeclaration); if (containingMethod && containingMethod.symbol === prop) { @@ -26762,6 +27744,11 @@ namespace ts { (getCheckFlags(prop) & CheckFlags.Instantiated ? getSymbolLinks(prop).target : prop)!.isReferenced = SymbolFlags.All; } + function isSelfTypeAccess(name: Expression | QualifiedName, parent: Symbol | undefined) { + return name.kind === SyntaxKind.ThisKeyword + || !!parent && isEntityNameExpression(name) && parent === getResolvedSymbol(getFirstIdentifier(name)); + } + function isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: __String): boolean { switch (node.kind) { case SyntaxKind.PropertyAccessExpression: @@ -26789,11 +27776,11 @@ namespace ts { } const prop = getPropertyOfType(type, propertyName); if (prop) { - if (isPropertyAccessExpression(node) && prop.valueDeclaration && isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)) { + if (prop.valueDeclaration && isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration)) { const declClass = getContainingClass(prop.valueDeclaration); return !isOptionalChain(node) && !!findAncestor(node, parent => parent === declClass); } - return checkPropertyAccessibility(node, isSuper, type, prop); + return checkPropertyAccessibility(node, isSuper, /*writing*/ false, type, prop, /* reportError */ false); } // In js files properties of unions are allowed in completion return isInJSFile(node) && (type.flags & TypeFlags.Union) !== 0 && (type).types.some(elementType => isValidPropertyAccessWithType(node, isSuper, propertyName, elementType)); @@ -26849,18 +27836,18 @@ namespace ts { return false; } - function checkIndexedAccess(node: ElementAccessExpression): Type { - return node.flags & NodeFlags.OptionalChain ? checkElementAccessChain(node as ElementAccessChain) : - checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + function checkIndexedAccess(node: ElementAccessExpression, checkMode: CheckMode | undefined): Type { + return node.flags & NodeFlags.OptionalChain ? checkElementAccessChain(node as ElementAccessChain, checkMode) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression), checkMode); } - function checkElementAccessChain(node: ElementAccessChain) { + function checkElementAccessChain(node: ElementAccessChain, checkMode: CheckMode | undefined) { const exprType = checkExpression(node.expression); const nonOptionalType = getOptionalExpressionType(exprType, node.expression); - return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression), checkMode), node, nonOptionalType !== exprType); } - function checkElementAccessExpression(node: ElementAccessExpression, exprType: Type): Type { + function checkElementAccessExpression(node: ElementAccessExpression, exprType: Type, checkMode: CheckMode | undefined): Type { const objectType = getAssignmentTargetKind(node) !== AssignmentKind.None || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; const indexExpression = node.argumentExpression; const indexType = checkExpression(indexExpression); @@ -26879,49 +27866,7 @@ namespace ts { AccessFlags.Writing | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? AccessFlags.NoIndexSignatures : 0) : AccessFlags.None; const indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, /*noUncheckedIndexedAccessCandidate*/ undefined, node, accessFlags | AccessFlags.ExpressionPosition) || errorType; - return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); - } - - function checkThatExpressionIsProperSymbolReference(expression: Expression, expressionType: Type, reportError: boolean): boolean { - if (expressionType === errorType) { - // There is already an error, so no need to report one. - return false; - } - - if (!isWellKnownSymbolSyntactically(expression)) { - return false; - } - - // Make sure the property type is the primitive symbol type - if ((expressionType.flags & TypeFlags.ESSymbolLike) === 0) { - if (reportError) { - error(expression, Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, getTextOfNode(expression)); - } - return false; - } - - // The name is Symbol., so make sure Symbol actually resolves to the - // global Symbol object - const leftHandSide = (expression).expression; - const leftHandSideSymbol = getResolvedSymbol(leftHandSide); - if (!leftHandSideSymbol) { - return false; - } - - const globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true); - if (!globalESSymbol) { - // Already errored when we tried to look up the symbol - return false; - } - - if (leftHandSideSymbol !== globalESSymbol) { - if (reportError) { - error(leftHandSide, Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); - } - return false; - } - - return true; + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, getNodeLinks(node).resolvedSymbol, indexedAccessType, indexExpression, checkMode), node); } function callLikeExpressionMayHaveTypeArguments(node: CallLikeExpression): node is CallExpression | NewExpression | TaggedTemplateExpression | JsxOpeningElement { @@ -27690,87 +28635,67 @@ namespace ts { } function getArgumentArityError(node: CallLikeExpression, signatures: readonly Signature[], args: readonly Expression[]) { - let min = Number.POSITIVE_INFINITY; - let max = Number.NEGATIVE_INFINITY; - let belowArgCount = Number.NEGATIVE_INFINITY; - let aboveArgCount = Number.POSITIVE_INFINITY; + const spreadIndex = getSpreadArgumentIndex(args); + if (spreadIndex > -1) { + return createDiagnosticForNode(args[spreadIndex], Diagnostics.A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter); + } + let min = Number.POSITIVE_INFINITY; // smallest parameter count + let max = Number.NEGATIVE_INFINITY; // largest parameter count + let maxBelow = Number.NEGATIVE_INFINITY; // largest parameter count that is smaller than the number of arguments + let minAbove = Number.POSITIVE_INFINITY; // smallest parameter count that is larger than the number of arguments - 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; - if (minCount < min) { - min = minCount; + const minParameter = getMinArgumentCount(sig); + const maxParameter = getParameterCount(sig); + // smallest/largest parameter counts + if (minParameter < min) { + min = minParameter; closestSignature = sig; } - max = Math.max(max, maxCount); + max = Math.max(max, maxParameter); + // shortest parameter count *longer than the call*/longest parameter count *shorter than the call* + if (minParameter < args.length && minParameter > maxBelow) maxBelow = minParameter; + if (args.length < maxParameter && maxParameter < minAbove) minAbove = maxParameter; } - const hasRestParameter = some(signatures, hasEffectiveRestParameter); - const paramRange = hasRestParameter ? min : - min < max ? min + "-" + max : - min; - const hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - - let spanArray: NodeArray; - let related: DiagnosticWithLocation | undefined; - - const error = hasRestParameter || hasSpreadArgument ? - 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 : - paramRange === 1 && argCount === 0 && isPromiseResolveArityError(node) ? - Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : - Diagnostics.Expected_0_arguments_but_got_1; - - 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 : - isRestParameter(paramDecl) ? Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided : Diagnostics.An_argument_for_0_was_not_provided, - !paramDecl.name ? argCount : !isBindingPattern(paramDecl.name) ? idText(getFirstIdentifier(paramDecl.name)) : undefined + const parameterRange = hasRestParameter ? min + : min < max ? min + "-" + max + : min; + const error = hasRestParameter ? Diagnostics.Expected_at_least_0_arguments_but_got_1 + : parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node) ? Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise + : Diagnostics.Expected_0_arguments_but_got_1; + if (min < args.length && args.length < max) { + // between min and max, but with no matching overload + return getDiagnosticForCallNode(node, Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove); + } + else if (args.length < min) { + // too short: put the error span on the call expression, not any of the args + const diagnostic = getDiagnosticForCallNode(node, error, parameterRange, args.length); + const parameter = closestSignature?.declaration?.parameters[closestSignature.thisParameter ? args.length + 1 : args.length]; + if (parameter) { + const parameterError = createDiagnosticForNode( + parameter, + isBindingPattern(parameter.name) ? Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided + : isRestParameter(parameter) ? Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided + : Diagnostics.An_argument_for_0_was_not_provided, + !parameter.name ? args.length : !isBindingPattern(parameter.name) ? idText(getFirstIdentifier(parameter.name)) : undefined ); + return addRelatedInfo(diagnostic, parameterError); } - } - if (min < argCount && argCount < max) { - return getDiagnosticForCallNode(node, Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); - } - - if (!hasSpreadArgument && argCount < min) { - const diagnostic = getDiagnosticForCallNode(node, error, paramRange, argCount); - return related ? addRelatedInfo(diagnostic, related) : diagnostic; - } - - if (hasRestParameter || hasSpreadArgument) { - spanArray = factory.createNodeArray(args); - if (hasSpreadArgument && argCount) { - const nextArg = elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined; - spanArray = factory.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1))); - } + return diagnostic; } else { - spanArray = factory.createNodeArray(args.slice(max)); - } - - const pos = first(spanArray).pos; - let end = last(spanArray).end; - if (end === pos) { - end++; + // too long; error goes on the excess parameters + const errorSpan = factory.createNodeArray(args.slice(max)); + const pos = first(errorSpan).pos; + let end = last(errorSpan).end; + if (end === pos) { + end++; + } + setTextRangePosEnd(errorSpan, pos, end); + return createDiagnosticForNodeArray(getSourceFileOfNode(node), errorSpan, error, parameterRange, args.length); } - setTextRangePosEnd(spanArray, pos, end); - const diagnostic = createDiagnosticForNodeArray( - getSourceFileOfNode(node), spanArray, error, paramRange, argCount); - return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node: Node, signatures: readonly Signature[], typeArguments: NodeArray) { @@ -28343,7 +29268,7 @@ namespace ts { function isUntypedFunctionCall(funcType: Type, apparentFuncType: Type, numCallSignatures: number, numConstructSignatures: number): boolean { // We exclude union types because we may have a union of function types that happen to have no common signatures. return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & TypeFlags.TypeParameter) || - !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (TypeFlags.Union | TypeFlags.Never)) && isTypeAssignableTo(funcType, globalFunctionType); + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & TypeFlags.Union) && !(getReducedType(apparentFuncType).flags & TypeFlags.Never) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node: NewExpression, candidatesOutArray: Signature[] | undefined, checkMode: CheckMode): Signature { @@ -29090,7 +30015,7 @@ namespace ts { if (allowSyntheticDefaultImports && type && type !== errorType) { const synthType = type as SyntheticDefaultModuleType; if (!synthType.syntheticType) { - const file = find(originalSymbol.declarations, isSourceFile); + const file = originalSymbol.declarations?.find(isSourceFile); const hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); if (hasSyntheticDefault) { const memberTable = createSymbolTable(); @@ -29471,7 +30396,14 @@ namespace ts { } function assignContextualParameterTypes(signature: Signature, context: Signature) { - signature.typeParameters = context.typeParameters; + if (context.typeParameters) { + if (!signature.typeParameters) { + signature.typeParameters = context.typeParameters; + } + else { + return; // This signature has already has a contextual inference performed and cached on it! + } + } if (context.thisParameter) { const parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !(parameter.valueDeclaration).type) { @@ -29894,18 +30826,18 @@ namespace ts { } const hasExplicitReturn = func.flags & NodeFlags.HasExplicitReturn; + const errorNode = getEffectiveReturnTypeNode(func) || func; if (type && type.flags & TypeFlags.Never) { - error(getEffectiveReturnTypeNode(func), Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + error(errorNode, Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (type && !hasExplicitReturn) { // minimal check: function has syntactic return type annotation and no explicit return statements in the body // this function does not conform to the specification. - // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present - error(getEffectiveReturnTypeNode(func), Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + error(errorNode, Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) { - error(getEffectiveReturnTypeNode(func) || func, Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + error(errorNode, Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); } else if (compilerOptions.noImplicitReturns) { if (!type) { @@ -29920,7 +30852,7 @@ namespace ts { return; } } - error(getEffectiveReturnTypeNode(func) || func, Diagnostics.Not_all_code_paths_return_a_value); + error(errorNode, Diagnostics.Not_all_code_paths_return_a_value); } } @@ -30473,7 +31405,7 @@ namespace ts { const prop = getPropertyOfType(objectLiteralType, text); if (prop) { markPropertyAsReferenced(prop, property, rightIsThis); - checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + checkPropertyAccessibility(property, /*isSuper*/ false, /*writing*/ true, objectLiteralType, prop); } } const elementType = getIndexedAccessType(objectLiteralType, exprType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, AccessFlags.ExpressionPosition); @@ -30684,92 +31616,142 @@ namespace ts { return (target.flags & TypeFlags.Nullable) !== 0 || isTypeComparableTo(source, target); } - const enum CheckBinaryExpressionState { - MaybeCheckLeft, - CheckRight, - FinishCheck - } + function createCheckBinaryExpression() { + interface WorkArea { + readonly checkMode: CheckMode | undefined; + skip: boolean; + stackIndex: number; + /** + * Holds the types from the left-side of an expression from [0..stackIndex]. + * Holds the type of the result at stackIndex+1. This allows us to reuse existing stack entries + * and avoid storing an extra property on the object (i.e., `lastResult`). + */ + typeStack: (Type | undefined)[]; + } + + const trampoline = createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState); - function checkBinaryExpression(node: BinaryExpression, checkMode?: CheckMode) { - const workStacks: { - expr: BinaryExpression[], - state: CheckBinaryExpressionState[], - leftType: (Type | undefined)[] - } = { - expr: [node], - state: [CheckBinaryExpressionState.MaybeCheckLeft], - leftType: [undefined] + return (node: BinaryExpression, checkMode: CheckMode | undefined) => { + const result = trampoline(node, checkMode); + Debug.assertIsDefined(result); + return result; }; - let stackIndex = 0; - let lastResult: Type | undefined; - while (stackIndex >= 0) { - node = workStacks.expr[stackIndex]; - switch (workStacks.state[stackIndex]) { - case CheckBinaryExpressionState.MaybeCheckLeft: { - if (isInJSFile(node) && getAssignedExpandoInitializer(node)) { - finishInvocation(checkExpression(node.right, checkMode)); - break; - } - checkGrammarNullishCoalesceWithLogicalExpression(node); - const operator = node.operatorToken.kind; - if (operator === SyntaxKind.EqualsToken && (node.left.kind === SyntaxKind.ObjectLiteralExpression || node.left.kind === SyntaxKind.ArrayLiteralExpression)) { - finishInvocation(checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === SyntaxKind.ThisKeyword)); - break; - } - advanceState(CheckBinaryExpressionState.CheckRight); - maybeCheckExpression(node.left); - break; - } - case CheckBinaryExpressionState.CheckRight: { - const leftType = lastResult!; - workStacks.leftType[stackIndex] = leftType; - const operator = node.operatorToken.kind; - if (operator === SyntaxKind.AmpersandAmpersandToken || operator === SyntaxKind.BarBarToken || operator === SyntaxKind.QuestionQuestionToken) { - if (operator === SyntaxKind.AmpersandAmpersandToken) { - const parent = walkUpParenthesizedExpressions(node.parent); - checkTestingKnownTruthyCallableType(node.left, leftType, isIfStatement(parent) ? parent.thenStatement : undefined); - } - checkTruthinessOfType(leftType, node.left); + + function onEnter(node: BinaryExpression, state: WorkArea | undefined, checkMode: CheckMode | undefined) { + if (state) { + state.stackIndex++; + state.skip = false; + setLeftType(state, /*type*/ undefined); + setLastResult(state, /*type*/ undefined); + } + else { + state = { + checkMode, + skip: false, + stackIndex: 0, + typeStack: [undefined, undefined], + }; + } + + if (isInJSFile(node) && getAssignedExpandoInitializer(node)) { + state.skip = true; + setLastResult(state, checkExpression(node.right, checkMode)); + return state; + } + + checkGrammarNullishCoalesceWithLogicalExpression(node); + + const operator = node.operatorToken.kind; + if (operator === SyntaxKind.EqualsToken && (node.left.kind === SyntaxKind.ObjectLiteralExpression || node.left.kind === SyntaxKind.ArrayLiteralExpression)) { + state.skip = true; + setLastResult(state, checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === SyntaxKind.ThisKeyword)); + return state; + } + + return state; + } + + function onLeft(left: Expression, state: WorkArea, _node: BinaryExpression) { + if (!state.skip) { + return maybeCheckExpression(state, left); + } + } + + function onOperator(operatorToken: BinaryOperatorToken, state: WorkArea, node: BinaryExpression) { + if (!state.skip) { + const leftType = getLastResult(state); + Debug.assertIsDefined(leftType); + setLeftType(state, leftType); + setLastResult(state, /*type*/ undefined); + const operator = operatorToken.kind; + if (operator === SyntaxKind.AmpersandAmpersandToken || operator === SyntaxKind.BarBarToken || operator === SyntaxKind.QuestionQuestionToken) { + if (operator === SyntaxKind.AmpersandAmpersandToken) { + const parent = walkUpParenthesizedExpressions(node.parent); + checkTestingKnownTruthyCallableOrAwaitableType(node.left, leftType, isIfStatement(parent) ? parent.thenStatement : undefined); } - advanceState(CheckBinaryExpressionState.FinishCheck); - maybeCheckExpression(node.right); - break; + checkTruthinessOfType(leftType, node.left); } - case CheckBinaryExpressionState.FinishCheck: { - const leftType = workStacks.leftType[stackIndex]!; - const rightType = lastResult!; - finishInvocation(checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node)); - break; - } - default: return Debug.fail(`Invalid state ${workStacks.state[stackIndex]} for checkBinaryExpression`); } } - return lastResult!; + function onRight(right: Expression, state: WorkArea, _node: BinaryExpression) { + if (!state.skip) { + return maybeCheckExpression(state, right); + } + } + + function onExit(node: BinaryExpression, state: WorkArea): Type | undefined { + let result: Type | undefined; + if (state.skip) { + result = getLastResult(state); + } + else { + const leftType = getLeftType(state); + Debug.assertIsDefined(leftType); + + const rightType = getLastResult(state); + Debug.assertIsDefined(rightType); - function finishInvocation(result: Type) { - lastResult = result; - stackIndex--; + result = checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node); + } + + state.skip = false; + setLeftType(state, /*type*/ undefined); + setLastResult(state, /*type*/ undefined); + state.stackIndex--; + return result; } - /** - * Note that `advanceState` sets the _current_ head state, and that `maybeCheckExpression` potentially pushes on a new - * head state; so `advanceState` must be called before any `maybeCheckExpression` during a state's execution. - */ - function advanceState(nextState: CheckBinaryExpressionState) { - workStacks.state[stackIndex] = nextState; + function foldState(state: WorkArea, result: Type | undefined, _side: "left" | "right") { + setLastResult(state, result); + return state; } - function maybeCheckExpression(node: Expression) { + function maybeCheckExpression(state: WorkArea, node: Expression): BinaryExpression | undefined { if (isBinaryExpression(node)) { - stackIndex++; - workStacks.expr[stackIndex] = node; - workStacks.state[stackIndex] = CheckBinaryExpressionState.MaybeCheckLeft; - workStacks.leftType[stackIndex] = undefined; - } - else { - lastResult = checkExpression(node, checkMode); + return node; } + setLastResult(state, checkExpression(node, state.checkMode)); + } + + function getLeftType(state: WorkArea) { + return state.typeStack[state.stackIndex]; + } + + function setLeftType(state: WorkArea, type: Type | undefined) { + state.typeStack[state.stackIndex] = type; + } + + function getLastResult(state: WorkArea) { + return state.typeStack[state.stackIndex + 1]; + } + + function setLastResult(state: WorkArea, type: Type | undefined) { + // To reduce overhead, reuse the next stack entry to store the + // last result. This avoids the overhead of an additional property + // on `WorkArea` and reuses empty stack entries as we walk back up + // the stack. + state.typeStack[state.stackIndex + 1] = type; } } @@ -31041,7 +32023,7 @@ namespace ts { if (propType.symbol && propType.symbol.flags & SymbolFlags.Class) { const name = prop.escapedName; const symbol = resolveName(prop.valueDeclaration, name, SymbolFlags.Type, undefined, name, /*isUse*/ false); - if (symbol && symbol.declarations.some(isJSDocTypedefTag)) { + if (symbol?.declarations && symbol.declarations.some(isJSDocTypedefTag)) { addDuplicateDeclarationErrorsForSymbols(symbol, Diagnostics.Duplicate_identifier_0, unescapeLeadingUnderscores(name), prop); addDuplicateDeclarationErrorsForSymbols(prop, Diagnostics.Duplicate_identifier_0, unescapeLeadingUnderscores(name), symbol); } @@ -31271,7 +32253,7 @@ namespace ts { function checkConditionalExpression(node: ConditionalExpression, checkMode?: CheckMode): Type { const type = checkTruthinessExpression(node.condition); - checkTestingKnownTruthyCallableType(node.condition, type, node.whenTrue); + checkTestingKnownTruthyCallableOrAwaitableType(node.condition, type, node.whenTrue); const type1 = checkExpression(node.whenTrue, checkMode); const type2 = checkExpression(node.whenFalse, checkMode); return getUnionType([type1, type2], UnionReduction.Subtype); @@ -31288,7 +32270,12 @@ namespace ts { texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } - return isConstContext(node) ? getTemplateLiteralType(texts, types) : stringType; + return isConstContext(node) || someType(getContextualType(node) || unknownType, isTemplateLiteralContextualType) ? getTemplateLiteralType(texts, types) : stringType; + } + + function isTemplateLiteralContextualType(type: Type): boolean { + return !!(type.flags & (TypeFlags.StringLiteral | TypeFlags.TemplateLiteral) || + type.flags & TypeFlags.InstantiableNonPrimitive && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, TypeFlags.StringLike)); } function getContextNode(node: Expression): Node { @@ -31739,7 +32726,7 @@ namespace ts { } switch (kind) { case SyntaxKind.Identifier: - return checkIdentifier(node); + return checkIdentifier(node, checkMode); case SyntaxKind.ThisKeyword: return checkThisExpression(node); case SyntaxKind.SuperKeyword: @@ -31768,11 +32755,11 @@ namespace ts { case SyntaxKind.ObjectLiteralExpression: return checkObjectLiteral(node, checkMode); case SyntaxKind.PropertyAccessExpression: - return checkPropertyAccessExpression(node); + return checkPropertyAccessExpression(node, checkMode); case SyntaxKind.QualifiedName: - return checkQualifiedName(node); + return checkQualifiedName(node, checkMode); case SyntaxKind.ElementAccessExpression: - return checkIndexedAccess(node); + return checkIndexedAccess(node, checkMode); case SyntaxKind.CallExpression: if ((node).expression.kind === SyntaxKind.ImportKeyword) { return checkImportCallExpression(node); @@ -32101,29 +33088,32 @@ namespace ts { const isStatic = hasSyntacticModifier(member, ModifierFlags.Static); const name = member.name; if (!name) { - return; + continue; } + const isPrivate = isPrivateIdentifier(name); + const privateStaticFlags = isPrivate && isStatic ? DeclarationMeaning.PrivateStatic : 0; const names = - isPrivateIdentifier(name) ? privateIdentifiers : + isPrivate ? privateIdentifiers : isStatic ? staticNames : instanceNames; + const memberName = name && getPropertyNameForPropertyNameNode(name); if (memberName) { switch (member.kind) { case SyntaxKind.GetAccessor: - addName(names, name, memberName, DeclarationMeaning.GetAccessor); + addName(names, name, memberName, DeclarationMeaning.GetAccessor | privateStaticFlags); break; case SyntaxKind.SetAccessor: - addName(names, name, memberName, DeclarationMeaning.SetAccessor); + addName(names, name, memberName, DeclarationMeaning.SetAccessor | privateStaticFlags); break; case SyntaxKind.PropertyDeclaration: - addName(names, name, memberName, DeclarationMeaning.GetOrSetAccessor); + addName(names, name, memberName, DeclarationMeaning.GetOrSetAccessor | privateStaticFlags); break; case SyntaxKind.MethodDeclaration: - addName(names, name, memberName, DeclarationMeaning.Method); + addName(names, name, memberName, DeclarationMeaning.Method | privateStaticFlags); break; } } @@ -32133,16 +33123,25 @@ namespace ts { function addName(names: UnderscoreEscapedMap, location: Node, name: __String, meaning: DeclarationMeaning) { const prev = names.get(name); if (prev) { - if (prev & DeclarationMeaning.Method) { - if (meaning !== DeclarationMeaning.Method) { - error(location, Diagnostics.Duplicate_identifier_0, getTextOfNode(location)); - } - } - else if (prev & meaning) { - error(location, Diagnostics.Duplicate_identifier_0, getTextOfNode(location)); + // For private identifiers, do not allow mixing of static and instance members with the same name + if ((prev & DeclarationMeaning.PrivateStatic) !== (meaning & DeclarationMeaning.PrivateStatic)) { + error(location, Diagnostics.Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name, getTextOfNode(location)); } else { - names.set(name, prev | meaning); + const prevIsMethod = !!(prev & DeclarationMeaning.Method); + const isMethod = !!(meaning & DeclarationMeaning.Method); + if (prevIsMethod || isMethod) { + if (prevIsMethod !== isMethod) { + error(location, Diagnostics.Duplicate_identifier_0, getTextOfNode(location)); + } + // If this is a method/method duplication is might be an overload, so this will be handled when overloads are considered + } + else if (prev & meaning & ~DeclarationMeaning.PrivateStatic) { + error(location, Diagnostics.Duplicate_identifier_0, getTextOfNode(location)); + } + else { + names.set(name, prev | meaning); + } } } else { @@ -32217,7 +33216,7 @@ namespace ts { const nodeSymbol = getSymbolOfNode(node as InterfaceDeclaration); // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration // to prevent this run check only for the first declaration of a given kind - if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + if (nodeSymbol.declarations && nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { return; } } @@ -32226,7 +33225,7 @@ namespace ts { // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration const indexSymbol = getIndexSymbol(getSymbolOfNode(node)!); - if (indexSymbol) { + if (indexSymbol?.declarations) { let seenNumericIndexer = false; let seenStringIndexer = false; for (const decl of indexSymbol.declarations) { @@ -32260,11 +33259,9 @@ namespace ts { if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); - // Private class fields transformation relies on WeakMaps. - if (isPrivateIdentifier(node.name) && languageVersion < ScriptTarget.ESNext) { - for (let lexicalScope = getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = getEnclosingBlockScopeContainer(lexicalScope)) { - getNodeLinks(lexicalScope).flags |= NodeCheckFlags.ContainsClassWithPrivateIdentifiers; - } + setNodeLinksForPrivateIdentifierScope(node); + if (isPrivateIdentifier(node.name) && hasStaticModifier(node) && node.initializer && languageVersion === ScriptTarget.ESNext && !compilerOptions.useDefineForClassFields) { + error(node.initializer, Diagnostics.Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag); } } @@ -32279,10 +33276,6 @@ namespace ts { // Grammar checking if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); - if (isPrivateIdentifier(node.name)) { - error(node, Diagnostics.A_method_cannot_be_named_with_a_private_identifier); - } - // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration checkFunctionOrMethodDeclaration(node); @@ -32291,6 +33284,32 @@ namespace ts { if (hasSyntacticModifier(node, ModifierFlags.Abstract) && node.kind === SyntaxKind.MethodDeclaration && node.body) { error(node, Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, declarationNameToString(node.name)); } + + // Private named methods are only allowed in class declarations + if (isPrivateIdentifier(node.name) && !getContainingClass(node)) { + error(node, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + } + + setNodeLinksForPrivateIdentifierScope(node); + } + + function setNodeLinksForPrivateIdentifierScope(node: PropertyDeclaration | PropertySignature | MethodDeclaration | MethodSignature | AccessorDeclaration) { + if (isPrivateIdentifier(node.name) && languageVersion < ScriptTarget.ESNext) { + for (let lexicalScope = getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = getEnclosingBlockScopeContainer(lexicalScope)) { + getNodeLinks(lexicalScope).flags |= NodeCheckFlags.ContainsClassWithPrivateIdentifiers; + } + + // If this is a private element in a class expression inside the body of a loop, + // then we must use a block-scoped binding to store the additional variables required + // to transform private elements. + if (isClassExpression(node.parent)) { + const enclosingIterationStatement = getEnclosingIterationStatement(node.parent); + if (enclosingIterationStatement) { + getNodeLinks(node.name).flags |= NodeCheckFlags.BlockScopedBindingInLoop; + getNodeLinks(enclosingIterationStatement).flags |= NodeCheckFlags.LoopWithCapturedBlockScopedBinding; + } + } + } } function checkConstructorDeclaration(node: ConstructorDeclaration) { @@ -32319,7 +33338,7 @@ namespace ts { } function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n: Node): boolean { - if (isPrivateIdentifierPropertyDeclaration(n)) { + if (isPrivateIdentifierClassElementDeclaration(n)) { return true; } return n.kind === SyntaxKind.PropertyDeclaration && @@ -32346,7 +33365,7 @@ namespace ts { // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. const superCallShouldBeFirst = - (compilerOptions.target !== ScriptTarget.ESNext || !compilerOptions.useDefineForClassFields) && + (compilerOptions.target !== ScriptTarget.ESNext || !useDefineForClassFields) && (some((node.parent).members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || some(node.parameters, p => hasSyntacticModifier(p, ModifierFlags.ParameterPropertyModifier))); @@ -32396,28 +33415,32 @@ namespace ts { if (node.name.kind === SyntaxKind.ComputedPropertyName) { checkComputedPropertyName(node.name); } - if (isPrivateIdentifier(node.name)) { - error(node.name, Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier); - } + if (hasBindableName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. - const otherKind = node.kind === SyntaxKind.GetAccessor ? SyntaxKind.SetAccessor : SyntaxKind.GetAccessor; - const otherAccessor = getDeclarationOfKind(getSymbolOfNode(node), otherKind); - if (otherAccessor) { - const nodeFlags = getEffectiveModifierFlags(node); - const otherFlags = getEffectiveModifierFlags(otherAccessor); - if ((nodeFlags & ModifierFlags.AccessibilityModifier) !== (otherFlags & ModifierFlags.AccessibilityModifier)) { - error(node.name, Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + const symbol = getSymbolOfNode(node); + const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); + const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); + if (getter && setter && !(getNodeCheckFlags(getter) & NodeCheckFlags.TypeChecked)) { + getNodeLinks(getter).flags |= NodeCheckFlags.TypeChecked; + const getterFlags = getEffectiveModifierFlags(getter); + const setterFlags = getEffectiveModifierFlags(setter); + if ((getterFlags & ModifierFlags.Abstract) !== (setterFlags & ModifierFlags.Abstract)) { + error(getter.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + error(setter.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } - if ((nodeFlags & ModifierFlags.Abstract) !== (otherFlags & ModifierFlags.Abstract)) { - error(node.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + if (((getterFlags & ModifierFlags.Protected) && !(setterFlags & (ModifierFlags.Protected | ModifierFlags.Private))) || + ((getterFlags & ModifierFlags.Private) && !(setterFlags & ModifierFlags.Private))) { + error(getter.name, Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); + error(setter.name, Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); } - // TypeScript 1.0 spec (April 2014): 4.5 - // If both accessors include type annotations, the specified types must be identical. - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, Diagnostics.get_and_set_accessor_must_have_the_same_type); - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, Diagnostics.get_and_set_accessor_must_have_the_same_this_type); + const getterType = getAnnotatedAccessorType(getter); + const setterType = getAnnotatedAccessorType(setter); + if (getterType && setterType) { + checkTypeAssignableTo(getterType, setterType, getter, Diagnostics.The_return_type_of_a_get_accessor_must_be_assignable_to_its_set_accessor_type); + } } } const returnType = getTypeOfAccessors(getSymbolOfNode(node)); @@ -32426,14 +33449,7 @@ namespace ts { } } checkSourceElement(node.body); - } - - function checkAccessorDeclarationTypesIdentical(first: AccessorDeclaration, second: AccessorDeclaration, getAnnotatedType: (a: AccessorDeclaration) => Type | undefined, message: DiagnosticMessage) { - const firstType = getAnnotatedType(first); - const secondType = getAnnotatedType(second); - if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { - error(first, message); - } + setNodeLinksForPrivateIdentifierScope(node); } function checkMissingDeclaration(node: Node) { @@ -32497,7 +33513,7 @@ namespace ts { if (some(symbol.declarations, d => isTypeDeclaration(d) && !!(d.flags & NodeFlags.Deprecated))) { addDeprecatedSuggestion( getDeprecatedSuggestionNode(node), - symbol.declarations, + symbol.declarations!, symbol.escapedName as string ); } @@ -32693,7 +33709,7 @@ namespace ts { } function isPrivateWithinAmbient(node: Node): boolean { - return (hasEffectiveModifier(node, ModifierFlags.Private) || isPrivateIdentifierPropertyDeclaration(node)) && !!(node.flags & NodeFlags.Ambient); + return (hasEffectiveModifier(node, ModifierFlags.Private) || isPrivateIdentifierClassElementDeclaration(node)) && !!(node.flags & NodeFlags.Ambient); } function getEffectiveDeclarationFlags(n: Declaration, flagsToCheck: ModifierFlags): ModifierFlags { @@ -32848,59 +33864,61 @@ namespace ts { let multipleConstructorImplementation = false; let hasNonAmbientClass = false; const functionDeclarations = [] as Declaration[]; - for (const current of declarations) { - const node = current; - const inAmbientContext = node.flags & NodeFlags.Ambient; - const inAmbientContextOrInterface = node.parent && (node.parent.kind === SyntaxKind.InterfaceDeclaration || node.parent.kind === SyntaxKind.TypeLiteral) || inAmbientContext; - if (inAmbientContextOrInterface) { - // check if declarations are consecutive only if they are non-ambient - // 1. ambient declarations can be interleaved - // i.e. this is legal - // declare function foo(); - // declare function bar(); - // declare function foo(); - // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one - previousDeclaration = undefined; - } - - if ((node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression) && !inAmbientContext) { - hasNonAmbientClass = true; - } - - if (node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature || node.kind === SyntaxKind.Constructor) { - functionDeclarations.push(node); - const currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); - someNodeFlags |= currentNodeFlags; - allNodeFlags &= currentNodeFlags; - someHaveQuestionToken = someHaveQuestionToken || hasQuestionToken(node); - allHaveQuestionToken = allHaveQuestionToken && hasQuestionToken(node); - const bodyIsPresent = nodeIsPresent((node as FunctionLikeDeclaration).body); - - if (bodyIsPresent && bodyDeclaration) { - if (isConstructor) { - multipleConstructorImplementation = true; + if (declarations) { + for (const current of declarations) { + const node = current; + const inAmbientContext = node.flags & NodeFlags.Ambient; + const inAmbientContextOrInterface = node.parent && (node.parent.kind === SyntaxKind.InterfaceDeclaration || node.parent.kind === SyntaxKind.TypeLiteral) || inAmbientContext; + if (inAmbientContextOrInterface) { + // check if declarations are consecutive only if they are non-ambient + // 1. ambient declarations can be interleaved + // i.e. this is legal + // declare function foo(); + // declare function bar(); + // declare function foo(); + // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one + previousDeclaration = undefined; + } + + if ((node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression) && !inAmbientContext) { + hasNonAmbientClass = true; + } + + if (node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature || node.kind === SyntaxKind.Constructor) { + functionDeclarations.push(node); + const currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && hasQuestionToken(node); + const bodyIsPresent = nodeIsPresent((node as FunctionLikeDeclaration).body); + + if (bodyIsPresent && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } } - else { - duplicateFunctionDeclaration = true; + else if (previousDeclaration?.parent === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); } - } - else if (previousDeclaration?.parent === node.parent && previousDeclaration.end !== node.pos) { - reportImplementationExpectedError(previousDeclaration); - } - if (bodyIsPresent) { - if (!bodyDeclaration) { - bodyDeclaration = node as FunctionLikeDeclaration; + if (bodyIsPresent) { + if (!bodyDeclaration) { + bodyDeclaration = node as FunctionLikeDeclaration; + } + } + else { + hasOverloads = true; } - } - else { - hasOverloads = true; - } - previousDeclaration = node; + previousDeclaration = node; - if (!inAmbientContextOrInterface) { - lastSeenNonAmbientDeclaration = node as FunctionLikeDeclaration; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node as FunctionLikeDeclaration; + } } } } @@ -32934,8 +33952,10 @@ namespace ts { } if (hasOverloads) { - checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); - checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (declarations) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + } if (bodyDeclaration) { const signatures = getSignaturesOfSymbol(symbol); @@ -32978,7 +33998,7 @@ namespace ts { let exportedDeclarationSpaces = DeclarationSpaces.None; let nonExportedDeclarationSpaces = DeclarationSpaces.None; let defaultExportedDeclarationSpaces = DeclarationSpaces.None; - for (const d of symbol.declarations) { + for (const d of symbol.declarations!) { const declarationSpaces = getDeclarationSpaces(d); const effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, ModifierFlags.Export | ModifierFlags.Default); @@ -33003,7 +34023,7 @@ namespace ts { if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { // declaration spaces for exported and non-exported declarations intersect - for (const d of symbol.declarations) { + for (const d of symbol.declarations!) { const declarationSpaces = getDeclarationSpaces(d); const name = getNameOfDeclaration(d); @@ -33040,11 +34060,14 @@ namespace ts { case SyntaxKind.SourceFile: return DeclarationSpaces.ExportType | DeclarationSpaces.ExportValue | DeclarationSpaces.ExportNamespace; case SyntaxKind.ExportAssignment: + case SyntaxKind.BinaryExpression: + const node = d as ExportAssignment | BinaryExpression; + const expression = isExportAssignment(node) ? node.expression : node.right; // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values - if (!isEntityNameExpression((d as ExportAssignment).expression)) { + if (!isEntityNameExpression(expression)) { return DeclarationSpaces.ExportValue; } - d = (d as ExportAssignment).expression; + d = expression; // The below options all declare an Alias, which is allowed to merge with other values within the importing module. // falls through @@ -33739,7 +34762,7 @@ namespace ts { // Since the javascript won't do semantic analysis like typescript, // if the javascript file comes before the typescript file and both contain same name functions, // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. - const firstDeclaration = find(localSymbol.declarations, + const firstDeclaration = localSymbol.declarations?.find( // Get first non javascript function declaration declaration => declaration.kind === node.kind && !(declaration.flags & NodeFlags.JavaScriptFile)); @@ -33905,7 +34928,8 @@ namespace ts { function checkUnusedTypeParameters(node: ClassLikeDeclaration | SignatureDeclaration | InterfaceDeclaration | TypeAliasDeclaration, addDiagnostic: AddUnusedDiagnostic): void { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. - if (last(getSymbolOfNode(node).declarations) !== node) return; + const declarations = getSymbolOfNode(node).declarations; + if (!declarations || last(declarations) !== node) return; const typeParameters = getEffectiveTypeParameterDeclarations(node); const seenParentsWithEveryUnused = new Set(); @@ -33980,39 +35004,41 @@ namespace ts { return; } - for (const declaration of local.declarations) { - if (isValidUnusedLocalDeclaration(declaration)) { - continue; - } + if (local.declarations) { + for (const declaration of local.declarations) { + if (isValidUnusedLocalDeclaration(declaration)) { + continue; + } - if (isImportedDeclaration(declaration)) { - addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); - } - else if (isBindingElement(declaration) && isObjectBindingPattern(declaration.parent)) { - // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. - const lastElement = last(declaration.parent.elements); - if (declaration === lastElement || !last(declaration.parent.elements).dotDotDotToken) { - addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); } - } - else if (isVariableDeclaration(declaration)) { - addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); - } - else { - const parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); - const name = local.valueDeclaration && getNameOfDeclaration(local.valueDeclaration); - if (parameter && name) { - if (!isParameterPropertyDeclaration(parameter, parameter.parent) && !parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { - if (isBindingElement(declaration) && isArrayBindingPattern(declaration.parent)) { - addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); - } - else { - addDiagnostic(parameter, UnusedKind.Parameter, createDiagnosticForNode(name, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolName(local))); - } + else if (isBindingElement(declaration) && isObjectBindingPattern(declaration.parent)) { + // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. + const lastElement = last(declaration.parent.elements); + if (declaration === lastElement || !last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); } } + else if (isVariableDeclaration(declaration)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } else { - errorUnusedLocal(declaration, symbolName(local), addDiagnostic); + const parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + const name = local.valueDeclaration && getNameOfDeclaration(local.valueDeclaration); + if (parameter && name) { + if (!isParameterPropertyDeclaration(parameter, parameter.parent) && !parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { + if (isBindingElement(declaration) && isArrayBindingPattern(declaration.parent)) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + else { + addDiagnostic(parameter, UnusedKind.Parameter, createDiagnosticForNode(name, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolName(local))); + } + } + } + else { + errorUnusedLocal(declaration, symbolName(local), addDiagnostic); + } } } } @@ -34177,10 +35203,11 @@ namespace ts { }); } - function checkWeakMapCollision(node: Node) { + function checkWeakMapSetCollision(node: Node) { const enclosingBlockScope = getEnclosingBlockScopeContainer(node); if (getNodeCheckFlags(enclosingBlockScope) & NodeCheckFlags.ContainsClassWithPrivateIdentifiers) { - errorSkippedOn("noEmit", node, Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, "WeakMap"); + Debug.assert(isNamedDeclaration(node) && isIdentifier(node.name) && typeof node.name.escapedText === "string", "The target of a WeakMap/WeakSet collision check should be an identifier"); + errorSkippedOn("noEmit", node, Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, node.name.escapedText); } } @@ -34327,8 +35354,8 @@ namespace ts { } } - if (node.kind === SyntaxKind.BindingElement) { - if (node.parent.kind === SyntaxKind.ObjectBindingPattern && languageVersion < ScriptTarget.ESNext) { + if (isBindingElement(node)) { + if (isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < ScriptTarget.ES2018) { checkExternalEmitHelpers(node, ExternalEmitHelpers.Rest); } // check computed properties inside property names of binding elements @@ -34346,8 +35373,8 @@ namespace ts { const nameText = getPropertyNameFromType(exprType); const property = getPropertyOfType(parentType, nameText); if (property) { - markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === SyntaxKind.SuperKeyword, parentType, property); + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isSelfTypeAccess*/ false); // A destructuring is never a write-only reference. + checkPropertyAccessibility(node, !!parent.initializer && parent.initializer.kind === SyntaxKind.SuperKeyword, /*writing*/ false, parentType, property); } } } @@ -34396,7 +35423,7 @@ namespace ts { } // For a commonjs `const x = require`, validate the alias and exit const symbol = getSymbolOfNode(node); - if (symbol.flags & SymbolFlags.Alias && isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true)) { + if (symbol.flags & SymbolFlags.Alias && isRequireVariableDeclaration(node)) { checkAliasSymbol(node); return; } @@ -34415,7 +35442,7 @@ namespace ts { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); } } - if (symbol.declarations.length > 1) { + if (symbol.declarations && symbol.declarations.length > 1) { if (some(symbol.declarations, d => d !== node && isVariableLike(d) && !areDeclarationFlagsIdentical(d, node))) { error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); } @@ -34434,7 +35461,7 @@ namespace ts { if (node.initializer) { checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } - if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); } } @@ -34446,8 +35473,9 @@ namespace ts { } checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - if (languageVersion < ScriptTarget.ESNext && needCollisionCheckForIdentifier(node, node.name, "WeakMap")) { - potentialWeakMapCollisions.push(node); + if (languageVersion < ScriptTarget.ESNext + && (needCollisionCheckForIdentifier(node, node.name, "WeakMap") || needCollisionCheckForIdentifier(node, node.name, "WeakSet"))) { + potentialWeakMapSetCollisions.push(node); } } } @@ -34522,7 +35550,7 @@ namespace ts { // Grammar checking checkGrammarStatementInAmbientContext(node); const type = checkTruthinessExpression(node.expression); - checkTestingKnownTruthyCallableType(node.expression, type, node.thenStatement); + checkTestingKnownTruthyCallableOrAwaitableType(node.expression, type, node.thenStatement); checkSourceElement(node.thenStatement); if (node.thenStatement.kind === SyntaxKind.EmptyStatement) { @@ -34532,33 +35560,29 @@ namespace ts { checkSourceElement(node.elseStatement); } - function checkTestingKnownTruthyCallableType(condExpr: Expression, type: Type, body: Statement | Expression | undefined) { - if (!strictNullChecks) { - return; - } + function checkTestingKnownTruthyCallableOrAwaitableType(condExpr: Expression, type: Type, body?: Statement | Expression) { + if (!strictNullChecks) return; + if (getFalsyFlags(type)) return; const location = isBinaryExpression(condExpr) ? condExpr.right : condExpr; const testedNode = isIdentifier(location) ? location : isPropertyAccessExpression(location) ? location.name : isBinaryExpression(location) && isIdentifier(location.right) ? location.right : undefined; - - if (!testedNode) { - return; - } - - const possiblyFalsy = getFalsyFlags(type); - if (possiblyFalsy) { + const isPropertyExpressionCast = isPropertyAccessExpression(location) + && isAssertionExpression(skipParentheses(location.expression)); + if (!testedNode || isPropertyExpressionCast) { return; } // While it technically should be invalid for any known-truthy value - // to be tested, we de-scope to functions unrefenced in the block as a - // heuristic to identify the most common bugs. There are too many - // false positives for values sourced from type definitions without - // strictNullChecks otherwise. + // to be tested, we de-scope to functions and Promises unreferenced in + // the block as a heuristic to identify the most common bugs. There + // are too many false positives for values sourced from type + // definitions without strictNullChecks otherwise. const callSignatures = getSignaturesOfType(type, SignatureKind.Call); - if (callSignatures.length === 0) { + const isPromise = !!getAwaitedTypeOfPromise(type); + if (callSignatures.length === 0 && !isPromise) { return; } @@ -34567,14 +35591,23 @@ namespace ts { return; } - const isUsed = isBinaryExpression(condExpr.parent) && isFunctionUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) - || body && isFunctionUsedInConditionBody(condExpr, body, testedNode, testedSymbol); + const isUsed = isBinaryExpression(condExpr.parent) && isSymbolUsedInBinaryExpressionChain(condExpr.parent, testedSymbol) + || body && isSymbolUsedInConditionBody(condExpr, body, testedNode, testedSymbol); if (!isUsed) { - error(location, Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead); + if (isPromise) { + errorAndMaybeSuggestAwait( + location, + /*maybeMissingAwait*/ true, + Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, + getTypeNameForErrorDisplay(type)); + } + else { + error(location, Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead); + } } } - function isFunctionUsedInConditionBody(expr: Expression, body: Statement | Expression, testedNode: Node, testedSymbol: Symbol): boolean { + function isSymbolUsedInConditionBody(expr: Expression, body: Statement | Expression, testedNode: Node, testedSymbol: Symbol): boolean { return !!forEachChild(body, function check(childNode): boolean | undefined { if (isIdentifier(childNode)) { const childSymbol = getSymbolAtLocation(childNode); @@ -34612,7 +35645,7 @@ namespace ts { }); } - function isFunctionUsedInBinaryExpressionChain(node: Node, testedSymbol: Symbol): boolean { + function isSymbolUsedInBinaryExpressionChain(node: Node, testedSymbol: Symbol): boolean { while (isBinaryExpression(node) && node.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) { const isUsed = forEachChild(node.right, function visit(child): boolean | undefined { if (isIdentifier(child)) { @@ -34897,18 +35930,8 @@ namespace ts { // want to say that number is not an array type. But if the input was just // number and string input is allowed, we want to say that number is not an // array type or a string type. - const yieldType = getIterationTypeOfIterable(use, IterationTypeKind.Yield, inputType, /*errorNode*/ undefined); - const [defaultDiagnostic, maybeMissingAwait]: [DiagnosticMessage, boolean] = !(use & IterationUse.AllowsStringInputFlag) || hasStringConstituent - ? downlevelIteration - ? [Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] - : yieldType - ? [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false] - : [Diagnostics.Type_0_is_not_an_array_type, true] - : downlevelIteration - ? [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] - : yieldType - ? [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false] - : [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true]; + const allowsStrings = !!(use & IterationUse.AllowsStringInputFlag) && !hasStringConstituent; + const [defaultDiagnostic, maybeMissingAwait] = getIterationDiagnosticDetails(allowsStrings, downlevelIteration); errorAndMaybeSuggestAwait( errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), @@ -34929,6 +35952,45 @@ namespace ts { } return (use & IterationUse.PossiblyOutOfBounds) ? includeUndefinedInIndexSignature(arrayElementType) : arrayElementType; + + function getIterationDiagnosticDetails(allowsStrings: boolean, downlevelIteration: boolean | undefined): [DiagnosticMessage, boolean] { + if (downlevelIteration) { + return allowsStrings + ? [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] + : [Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]; + } + + const yieldType = getIterationTypeOfIterable(use, IterationTypeKind.Yield, inputType, /*errorNode*/ undefined); + + if (yieldType) { + return [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]; + } + + if (isES2015OrLaterIterable(inputType.symbol?.escapedName)) { + return [Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, true]; + } + + return allowsStrings + ? [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true] + : [Diagnostics.Type_0_is_not_an_array_type, true]; + } + } + + function isES2015OrLaterIterable(n: __String) { + switch (n) { + case "Float32Array": + case "Float64Array": + case "Int16Array": + case "Int32Array": + case "Int8Array": + case "NodeList": + case "Uint16Array": + case "Uint32Array": + case "Uint8Array": + case "Uint8ClampedArray": + return true; + } + return false; } /** @@ -35197,6 +36259,12 @@ namespace ts { } } + function getPropertyNameForKnownSymbolName(symbolName: string): __String { + const ctorType = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false); + const uniqueType = ctorType && getTypeOfPropertyOfType(getTypeOfSymbol(ctorType), escapeLeadingUnderscores(symbolName)); + return uniqueType && isTypeUsableAsPropertyName(uniqueType) ? getPropertyNameFromType(uniqueType) : `__@${symbolName}` as __String; + } + /** * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like * type from its members. @@ -35682,10 +36750,11 @@ namespace ts { // Grammar checking if (catchClause.variableDeclaration) { const declaration = catchClause.variableDeclaration; - if (declaration.type) { + const typeNode = getEffectiveTypeAnnotationNode(getRootDeclaration(declaration)); + if (typeNode) { const type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ false); if (type && !(type.flags & TypeFlags.AnyOrUnknown)) { - grammarErrorOnFirstToken(declaration.type, Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified); + grammarErrorOnFirstToken(typeNode, Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified); } } else if (declaration.initializer) { @@ -35696,7 +36765,7 @@ namespace ts { if (blockLocals) { forEachKey(catchClause.locals!, caughtName => { const blockLocal = blockLocals.get(caughtName); - if (blockLocal && (blockLocal.flags & SymbolFlags.BlockScopedVariable) !== 0) { + if (blockLocal?.valueDeclaration && (blockLocal.flags & SymbolFlags.BlockScopedVariable) !== 0) { grammarErrorOnNode(blockLocal.valueDeclaration, Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); } }); @@ -35712,22 +36781,23 @@ namespace ts { } } - function checkIndexConstraints(type: Type) { - const declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, IndexKind.Number); - const declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, IndexKind.String); + function checkIndexConstraints(type: Type, isStatic?: boolean) { + const declaredNumberIndexer = getIndexDeclarationOfSymbolTable(isStatic ? type.symbol?.exports : type.symbol?.members, IndexKind.Number); + const declaredStringIndexer = getIndexDeclarationOfSymbolTable(isStatic ? type.symbol?.exports : type.symbol?.members, IndexKind.String); const stringIndexType = getIndexTypeOfType(type, IndexKind.String); const numberIndexType = getIndexTypeOfType(type, IndexKind.Number); if (stringIndexType || numberIndexType) { forEach(getPropertiesOfObjectType(type), prop => { + if (isStatic && prop.flags & SymbolFlags.Prototype) return; const propType = getTypeOfSymbol(prop); checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, IndexKind.String); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, IndexKind.Number); }); const classDeclaration = type.symbol.valueDeclaration; - if (getObjectFlags(type) & ObjectFlags.Class && isClassLike(classDeclaration)) { + if (getObjectFlags(type) & ObjectFlags.Class && classDeclaration && isClassLike(classDeclaration)) { for (const member of classDeclaration.members) { // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, @@ -35748,7 +36818,7 @@ namespace ts { // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer if (!errorNode && (getObjectFlags(type) & ObjectFlags.Interface)) { const someBaseTypeHasBothIndexers = forEach(getBaseTypes(type), base => getIndexTypeOfType(base, IndexKind.String) && getIndexTypeOfType(base, IndexKind.Number)); - errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + errorNode = someBaseTypeHasBothIndexers || !type.symbol.declarations ? undefined : type.symbol.declarations[0]; } } @@ -35799,7 +36869,7 @@ namespace ts { // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together const someBaseClassHasBothPropertyAndIndexer = forEach(getBaseTypes(containingType), base => getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind)); - errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + errorNode = someBaseClassHasBothPropertyAndIndexer || !containingType.symbol.declarations ? undefined : containingType.symbol.declarations[0]; } if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { @@ -35818,6 +36888,7 @@ namespace ts { switch (name.escapedText) { case "any": case "unknown": + case "never": case "number": case "bigint": case "boolean": @@ -35887,7 +36958,7 @@ namespace ts { /** Check that type parameter lists are identical across multiple declarations */ function checkTypeParameterListsIdentical(symbol: Symbol) { - if (symbol.declarations.length === 1) { + if (symbol.declarations && symbol.declarations.length === 1) { return; } @@ -35895,7 +36966,7 @@ namespace ts { if (!links.typeParametersChecked) { links.typeParametersChecked = true; const declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); - if (declarations.length <= 1) { + if (!declarations || declarations.length <= 1) { return; } @@ -35968,6 +37039,9 @@ namespace ts { } function checkClassDeclaration(node: ClassDeclaration) { + if (some(node.decorators) && some(node.members, p => hasStaticModifier(p) && isPrivateIdentifierClassElementDeclaration(p))) { + grammarErrorOnNode(node.decorators[0], Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator); + } if (!node.name && !hasSyntacticModifier(node, ModifierFlags.Default)) { grammarErrorOnFirstToken(node, Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } @@ -35999,7 +37073,8 @@ namespace ts { checkClassForDuplicateDeclarations(node); // Only check for reserved static identifiers on non-ambient context. - if (!(node.flags & NodeFlags.Ambient)) { + const nodeInAmbientContext = !!(node.flags & NodeFlags.Ambient); + if (!nodeInAmbientContext) { checkClassForStaticPropertyNameConflicts(node); } @@ -36063,6 +37138,8 @@ namespace ts { } } + checkMembersForMissingOverrideModifier(node, type, typeWithThis, staticType); + const implementedTypeNodes = getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (const typeRefNode of implementedTypeNodes) { @@ -36092,11 +37169,76 @@ namespace ts { if (produceDiagnostics) { checkIndexConstraints(type); + checkIndexConstraints(staticType, /*isStatic*/ true); checkTypeForDuplicateIndexSignatures(node); checkPropertyInitialization(node); } } + function checkMembersForMissingOverrideModifier(node: ClassLikeDeclaration, type: InterfaceType, typeWithThis: Type, staticType: ObjectType) { + const nodeInAmbientContext = !!(node.flags & NodeFlags.Ambient); + const baseTypeNode = getEffectiveBaseTypeNode(node); + const baseTypes = baseTypeNode && getBaseTypes(type); + const baseWithThis = baseTypes?.length ? getTypeWithThisArgument(first(baseTypes), type.thisType) : undefined; + const baseStaticType = getBaseConstructorTypeOfClass(type); + + for (const member of node.members) { + if (hasAmbientModifier(member)) { + continue; + } + + if (isConstructorDeclaration(member)) { + forEach(member.parameters, param => { + if (isParameterPropertyDeclaration(param, member)) { + checkClassMember(param, /*memberIsParameterProperty*/ true); + } + }); + } + checkClassMember(member); + } + + function checkClassMember(member: ClassElement | ParameterPropertyDeclaration, memberIsParameterProperty?: boolean) { + const hasOverride = hasOverrideModifier(member); + const hasStatic = hasStaticModifier(member); + if (baseWithThis && (hasOverride || compilerOptions.noImplicitOverride)) { + const declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (!declaredProp) { + return; + } + + const thisType = hasStatic ? staticType : typeWithThis; + const baseType = hasStatic ? baseStaticType : baseWithThis; + const prop = getPropertyOfType(thisType, declaredProp.escapedName); + const baseProp = getPropertyOfType(baseType, declaredProp.escapedName); + + const baseClassName = typeToString(baseWithThis); + if (prop && !baseProp && hasOverride) { + error(member, Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, baseClassName); + } + else if (prop && baseProp?.valueDeclaration && compilerOptions.noImplicitOverride && !nodeInAmbientContext) { + const baseHasAbstract = hasAbstractModifier(baseProp.valueDeclaration); + if (hasOverride) { + return; + } + + if (!baseHasAbstract) { + const diag = memberIsParameterProperty ? + Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : + Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; + error(member, diag, baseClassName); + } + else if (hasAbstractModifier(member) && baseHasAbstract) { + error(member, Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName); + } + } + } + else if (hasOverride) { + const className = typeToString(type); + error(member, Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, className); + } + } + } + function issueMemberSpecificError(node: ClassLikeDeclaration, typeWithThis: Type, baseWithThis: Type, broadDiag: DiagnosticMessage) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible let issuedMemberError = false; @@ -36246,13 +37388,13 @@ namespace ts { Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, symbolToString(base), typeToString(baseType), typeToString(type)); } - else if (compilerOptions.useDefineForClassFields) { - const uninitialized = find(derived.declarations, d => d.kind === SyntaxKind.PropertyDeclaration && !(d as PropertyDeclaration).initializer); + else if (useDefineForClassFields) { + const uninitialized = derived.declarations?.find(d => d.kind === SyntaxKind.PropertyDeclaration && !(d as PropertyDeclaration).initializer); if (uninitialized && !(derived.flags & SymbolFlags.Transient) && !(baseDeclarationFlags & ModifierFlags.Abstract) && !(derivedDeclarationFlags & ModifierFlags.Abstract) - && !derived.declarations.some(d => !!(d.flags & NodeFlags.Ambient))) { + && !derived.declarations?.some(d => !!(d.flags & NodeFlags.Ambient))) { const constructor = findConstructorDeclaration(getClassLikeDeclarationOfSymbol(type.symbol)!); const propName = (uninitialized as PropertyDeclaration).name; if ((uninitialized as PropertyDeclaration).exclamationToken @@ -36597,7 +37739,7 @@ namespace ts { if (memberSymbol) { const declaration = memberSymbol.valueDeclaration; if (declaration !== member) { - if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + if (declaration && isBlockScopedNameDeclaredBeforeUse(declaration, member)) { return getEnumMemberValue(declaration as EnumMember); } error(expr, Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); @@ -36643,7 +37785,7 @@ namespace ts { const enumSymbol = getSymbolOfNode(node); const firstDeclaration = getDeclarationOfKind(enumSymbol, node.kind); if (node === firstDeclaration) { - if (enumSymbol.declarations.length > 1) { + if (enumSymbol.declarations && enumSymbol.declarations.length > 1) { const enumIsConst = isEnumConst(node); // check that const is placed\omitted on all enum declarations forEach(enumSymbol.declarations, decl => { @@ -36686,11 +37828,13 @@ namespace ts { function getFirstNonAmbientClassOrFunctionDeclaration(symbol: Symbol): Declaration | undefined { const declarations = symbol.declarations; - for (const declaration of declarations) { - if ((declaration.kind === SyntaxKind.ClassDeclaration || - (declaration.kind === SyntaxKind.FunctionDeclaration && nodeIsPresent((declaration).body))) && - !(declaration.flags & NodeFlags.Ambient)) { - return declaration; + if (declarations) { + for (const declaration of declarations) { + if ((declaration.kind === SyntaxKind.ClassDeclaration || + (declaration.kind === SyntaxKind.FunctionDeclaration && nodeIsPresent((declaration).body))) && + !(declaration.flags & NodeFlags.Ambient)) { + return declaration; + } } } return undefined; @@ -36745,6 +37889,7 @@ namespace ts { // The following checks only apply on a non-ambient instantiated module declaration. if (symbol.flags & SymbolFlags.ValueModule && !inAmbientContext + && symbol.declarations && symbol.declarations.length > 1 && isInstantiatedModule(node, shouldPreserveConstEnums(compilerOptions))) { const firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); @@ -36854,7 +37999,7 @@ namespace ts { let reportError = !(symbol.flags & SymbolFlags.Transient); if (!reportError) { // symbol should not originate in augmentation - reportError = !!symbol.parent && isExternalModuleAugmentation(symbol.parent.declarations[0]); + reportError = !!symbol.parent?.declarations && isExternalModuleAugmentation(symbol.parent.declarations[0]); } } break; @@ -36945,7 +38090,7 @@ namespace ts { error(node, Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type); } - if (isImportSpecifier(node) && every(target.declarations, d => !!(getCombinedNodeFlags(d) & NodeFlags.Deprecated))) { + if (isImportSpecifier(node) && target.declarations?.every(d => !!(getCombinedNodeFlags(d) & NodeFlags.Deprecated))) { addDeprecatedSuggestion(node.name, target.declarations, symbol.escapedName as string); } } @@ -37157,7 +38302,7 @@ namespace ts { // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) const symbol = resolveName(exportedName, exportedName.escapedText, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, idText(exportedName)); } else { @@ -37179,7 +38324,10 @@ namespace ts { } function checkExportAssignment(node: ExportAssignment) { - if (checkGrammarModuleElementContext(node, Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + const illegalContextMessage = node.isExportEquals + ? Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration + : Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration; + if (checkGrammarModuleElementContext(node, illegalContextMessage)) { // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } @@ -37253,7 +38401,7 @@ namespace ts { const exportEqualsSymbol = moduleSymbol.exports!.get("export=" as __String); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { const declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !isInJSFile(declaration)) { + if (declaration && !isTopLevelInExternalModuleAugmentation(declaration) && !isInJSFile(declaration)) { error(declaration, Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -37276,9 +38424,11 @@ namespace ts { return; } if (exportedDeclarationsCount > 1) { - for (const declaration of declarations) { - if (isNotOverload(declaration)) { - diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Cannot_redeclare_exported_variable_0, unescapeLeadingUnderscores(id))); + if (!isDuplicatedCommonJSExport(declarations)) { + for (const declaration of declarations!) { + if (isNotOverload(declaration)) { + diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Cannot_redeclare_exported_variable_0, unescapeLeadingUnderscores(id))); + } } } } @@ -37288,6 +38438,12 @@ namespace ts { } } + function isDuplicatedCommonJSExport(declarations: Declaration[] | undefined) { + return declarations + && declarations.length > 1 + && declarations.every(d => isInJSFile(d) && isAccessExpression(d) && (isExportsIdentifier(d.expression) || isModuleExportsAccessExpression(d.expression))); + } + function checkSourceElement(node: Node | undefined): void { if (node) { const saveCurrentNode = currentNode; @@ -37526,7 +38682,8 @@ namespace ts { if (isJSDocTypeExpression(node.parent) && isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. const host = getHostSignatureFromJSDoc(paramTag); - if (host) { + const isCallbackTag = isJSDocCallbackTag(paramTag.parent.parent); + if (host || isCallbackTag) { /* Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters. So in the following situation we will not create an array type: @@ -37534,7 +38691,9 @@ namespace ts { function f(a) {} Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type. */ - const lastParamDeclaration = lastOrUndefined(host.parameters); + const lastParamDeclaration = isCallbackTag + ? lastOrUndefined((paramTag.parent.parent as unknown as JSDocCallbackTag).typeExpression.parameters) + : lastOrUndefined(host!.parameters); const symbol = getParameterSymbolFromJSDoc(paramTag); if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && isRestParameter(lastParamDeclaration)) { @@ -37654,7 +38813,7 @@ namespace ts { clear(potentialThisCollisions); clear(potentialNewTargetCollisions); - clear(potentialWeakMapCollisions); + clear(potentialWeakMapSetCollisions); forEach(node.statements, checkSourceElement); checkSourceElement(node.endOfFileToken); @@ -37694,9 +38853,9 @@ namespace ts { clear(potentialNewTargetCollisions); } - if (potentialWeakMapCollisions.length) { - forEach(potentialWeakMapCollisions, checkWeakMapCollision); - clear(potentialWeakMapCollisions); + if (potentialWeakMapSetCollisions.length) { + forEach(potentialWeakMapSetCollisions, checkWeakMapSetCollision); + clear(potentialWeakMapSetCollisions); } links.flags |= NodeCheckFlags.TypeChecked; @@ -37785,10 +38944,10 @@ namespace ts { switch (location.kind) { case SyntaxKind.SourceFile: - if (!isExternalOrCommonJsModule(location)) break; + if (!isExternalModule(location)) break; // falls through case SyntaxKind.ModuleDeclaration: - copySymbols(getSymbolOfNode(location as ModuleDeclaration | SourceFile).exports!, meaning & SymbolFlags.ModuleMember); + copyLocallyVisibleExportSymbols(getSymbolOfNode(location as ModuleDeclaration | SourceFile).exports!, meaning & SymbolFlags.ModuleMember); break; case SyntaxKind.EnumDeclaration: copySymbols(getSymbolOfNode(location as EnumDeclaration).exports!, meaning & SymbolFlags.EnumMember); @@ -37857,6 +39016,17 @@ namespace ts { }); } } + + function copyLocallyVisibleExportSymbols(source: SymbolTable, meaning: SymbolFlags): void { + if (meaning) { + source.forEach(symbol => { + // Similar condition as in `resolveNameHelper` + if (!getDeclarationOfKind(symbol, SyntaxKind.ExportSpecifier) && !getDeclarationOfKind(symbol, SyntaxKind.NamespaceExport)) { + copySymbol(symbol, meaning); + } + }); + } + } } function isTypeDeclarationName(name: Node): boolean { @@ -37903,15 +39073,14 @@ namespace ts { return node.parent.kind === SyntaxKind.ExpressionWithTypeArguments; } - function isJSDocEntryNameReference(node: Identifier | PrivateIdentifier | PropertyAccessExpression | QualifiedName): boolean { + function getJSDocEntryNameReference(node: Identifier | PrivateIdentifier | PropertyAccessExpression | QualifiedName): JSDocNameReference | undefined { while (node.parent.kind === SyntaxKind.QualifiedName) { node = node.parent as QualifiedName; } while (node.parent.kind === SyntaxKind.PropertyAccessExpression) { node = node.parent as PropertyAccessExpression; } - - return node.parent.kind === SyntaxKind.JSDocNameReference; + return isJSDocNameReference(node.parent) ? node.parent : undefined; } function forEachEnclosingClass(node: Node, callback: (node: Node) => T | undefined): T | undefined { @@ -38076,7 +39245,6 @@ namespace ts { const symbol = getIntrinsicTagSymbol(name.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(name, SymbolFlags.Value, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (name.kind === SyntaxKind.PropertyAccessExpression || name.kind === SyntaxKind.QualifiedName) { @@ -38086,10 +39254,10 @@ namespace ts { } if (name.kind === SyntaxKind.PropertyAccessExpression) { - checkPropertyAccessExpression(name); + checkPropertyAccessExpression(name, CheckMode.Normal); } else { - checkQualifiedName(name); + checkQualifiedName(name, CheckMode.Normal); } return links.resolvedSymbol; } @@ -38098,16 +39266,37 @@ namespace ts { const meaning = name.parent.kind === SyntaxKind.TypeReference ? SymbolFlags.Type : SymbolFlags.Namespace; return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (isJSDocEntryNameReference(name)) { + + const jsdocReference = getJSDocEntryNameReference(name); + if (jsdocReference || isJSDocLink(name.parent)) { const meaning = SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Value; - return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, getHostSignatureFromJSDoc(name)); - } + const symbol = resolveEntityName(name as EntityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ false, getHostSignatureFromJSDoc(name)); + if (symbol) { + return symbol; + } + else if (isQualifiedName(name) && isIdentifier(name.left)) { + // resolve C.m as a static member first + const links = getNodeLinks(name); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + checkQualifiedName(name, CheckMode.Normal); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + // then resolve it as an instance member + const s = resolveEntityName(name.left, meaning, /*ignoreErrors*/ false); + if (s) { + const t = getDeclaredTypeOfSymbol(s); + return getPropertyOfType(t, name.right.escapedText); + } + } + } if (name.parent.kind === SyntaxKind.TypePredicate) { return resolveEntityName(name, /*meaning*/ SymbolFlags.FunctionScopedVariable); } - // Do we want to return undefined here? return undefined; } @@ -38227,7 +39416,7 @@ namespace ts { } } - function getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined { + function getShorthandAssignmentValueSymbol(location: Node | undefined): Symbol | undefined { if (location && location.kind === SyntaxKind.ShorthandPropertyAssignment) { return resolveEntityName((location).name, SymbolFlags.Value | SymbolFlags.Alias); } @@ -38515,7 +39704,7 @@ namespace ts { } const parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { - if (parentSymbol.flags & SymbolFlags.ValueModule && parentSymbol.valueDeclaration.kind === SyntaxKind.SourceFile) { + if (parentSymbol.flags & SymbolFlags.ValueModule && parentSymbol.valueDeclaration?.kind === SyntaxKind.SourceFile) { const symbolFile = parentSymbol.valueDeclaration; const referenceFile = getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -38548,12 +39737,13 @@ namespace ts { } function isSymbolOfDestructuredElementOfCatchBinding(symbol: Symbol) { - return isBindingElement(symbol.valueDeclaration) + return symbol.valueDeclaration + && isBindingElement(symbol.valueDeclaration) && walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === SyntaxKind.CatchClause; } function isSymbolOfDeclarationWithCollidingName(symbol: Symbol): boolean { - if (symbol.flags & SymbolFlags.BlockScoped && !isSourceFile(symbol.valueDeclaration)) { + if (symbol.flags & SymbolFlags.BlockScoped && symbol.valueDeclaration && !isSourceFile(symbol.valueDeclaration)) { const links = getSymbolLinks(symbol); if (links.isDeclarationWithCollidingName === undefined) { const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration); @@ -39117,10 +40307,12 @@ namespace ts { for (const s of arrayFrom(exports.values())) { if (s.mergeId) { const merged = getMergedSymbol(s); - for (const d of merged.declarations) { - const declFile = getSourceFileOfNode(d); - if (declFile === importTarget) { - return true; + if (merged.declarations) { + for (const d of merged.declarations) { + const declFile = getSourceFileOfNode(d); + if (declFile === importTarget) { + return true; + } } } } @@ -39153,15 +40345,12 @@ namespace ts { // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): string[] | undefined { // program does not have any files with type reference directives - bail out - if (!fileToDirective) { - return undefined; - } - if (!isSymbolFromTypeDeclarationFile(symbol)) { + if (!fileToDirective || !isSymbolFromTypeDeclarationFile(symbol)) { return undefined; } // check what declarations in the symbol can contribute to the target meaning let typeReferenceDirectives: string[] | undefined; - for (const decl of symbol.declarations) { + for (const decl of symbol.declarations!) { // check meaning of the local symbol to see if declaration needs to be analyzed further if (decl.symbol && decl.symbol.flags & meaning!) { const file = getSourceFileOfNode(decl); @@ -39251,7 +40440,7 @@ namespace ts { // It is an error for a non-external-module (i.e. script) to declare its own `globalThis`. // We can't use `builtinGlobals` for this due to synthetic expando-namespace generation in JS files. const fileGlobalThisSymbol = file.locals!.get("globalThis" as __String); - if (fileGlobalThisSymbol) { + if (fileGlobalThisSymbol?.declarations) { for (const declaration of fileGlobalThisSymbol.declarations) { diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis")); } @@ -39379,6 +40568,16 @@ namespace ts { if (!symbol) { error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name); } + else if (helper & ExternalEmitHelpers.ClassPrivateFieldGet) { + if (!some(getSignaturesOfSymbol(symbol), signature => getParameterCount(signature) > 3)) { + error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 4); + } + } + else if (helper & ExternalEmitHelpers.ClassPrivateFieldSet) { + if (!some(getSignaturesOfSymbol(symbol), signature => getParameterCount(signature) > 4)) { + error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 5); + } + } } } } @@ -39454,14 +40653,14 @@ namespace ts { return quickResult; } - let lastStatic: Node | undefined, lastDeclare: Node | undefined, lastAsync: Node | undefined, lastReadonly: Node | undefined; + let lastStatic: Node | undefined, lastDeclare: Node | undefined, lastAsync: Node | undefined, lastReadonly: Node | undefined, lastOverride: Node | undefined; let flags = ModifierFlags.None; for (const modifier of node.modifiers!) { if (modifier.kind !== SyntaxKind.ReadonlyKeyword) { if (node.kind === SyntaxKind.PropertySignature || node.kind === SyntaxKind.MethodSignature) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_type_member, tokenToString(modifier.kind)); } - if (node.kind === SyntaxKind.IndexSignature) { + if (node.kind === SyntaxKind.IndexSignature && (modifier.kind !== SyntaxKind.StaticKeyword || !isClassLike(node.parent))) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_index_signature, tokenToString(modifier.kind)); } } @@ -39471,6 +40670,24 @@ namespace ts { return grammarErrorOnNode(node, Diagnostics.A_class_member_cannot_have_the_0_keyword, tokenToString(SyntaxKind.ConstKeyword)); } break; + case SyntaxKind.OverrideKeyword: + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. + if (flags & ModifierFlags.Override) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "override"); + } + else if (flags & ModifierFlags.Ambient) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare"); + } + else if (flags & ModifierFlags.Readonly) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly"); + } + else if (flags & ModifierFlags.Async) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "async"); + } + flags |= ModifierFlags.Override; + lastOverride = modifier; + break; + case SyntaxKind.PublicKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PrivateKeyword: @@ -39479,6 +40696,9 @@ namespace ts { if (flags & ModifierFlags.AccessibilityModifier) { return grammarErrorOnNode(modifier, Diagnostics.Accessibility_modifier_already_seen); } + else if (flags & ModifierFlags.Override) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "override"); + } else if (flags & ModifierFlags.Static) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } @@ -39499,7 +40719,7 @@ namespace ts { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); } } - else if (isPrivateIdentifierPropertyDeclaration(node)) { + else if (isPrivateIdentifierClassElementDeclaration(node)) { return grammarErrorOnNode(modifier, Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier); } flags |= modifierToFlag(modifier.kind); @@ -39524,8 +40744,8 @@ namespace ts { else if (flags & ModifierFlags.Abstract) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - else if (isPrivateIdentifierPropertyDeclaration(node)) { - return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "static"); + else if (flags & ModifierFlags.Override) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "override"); } flags |= ModifierFlags.Static; lastStatic = modifier; @@ -39536,7 +40756,7 @@ namespace ts { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "readonly"); } else if (node.kind !== SyntaxKind.PropertyDeclaration && node.kind !== SyntaxKind.PropertySignature && node.kind !== SyntaxKind.IndexSignature && node.kind !== SyntaxKind.Parameter) { - // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. + // If node.kind === SyntaxKind.Parameter, checkParameter reports an error if it's not a parameter property. return grammarErrorOnNode(modifier, Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= ModifierFlags.Readonly; @@ -39579,6 +40799,9 @@ namespace ts { else if (flags & ModifierFlags.Async) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } + else if (flags & ModifierFlags.Override) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override"); + } else if (isClassLike(node.parent) && !isPropertyDeclaration(node)) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare"); } @@ -39588,7 +40811,7 @@ namespace ts { else if ((node.parent.flags & NodeFlags.Ambient) && node.parent.kind === SyntaxKind.ModuleBlock) { return grammarErrorOnNode(modifier, Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } - else if (isPrivateIdentifierPropertyDeclaration(node)) { + else if (isPrivateIdentifierClassElementDeclaration(node)) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare"); } flags |= ModifierFlags.Ambient; @@ -39619,6 +40842,9 @@ namespace ts { if (flags & ModifierFlags.Async && lastAsync) { return grammarErrorOnNode(lastAsync, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract"); } + if (flags & ModifierFlags.Override) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override"); + } } if (isNamedDeclaration(node) && node.name.kind === SyntaxKind.PrivateIdentifier) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract"); @@ -39653,6 +40879,9 @@ namespace ts { if (flags & ModifierFlags.Abstract) { return grammarErrorOnNode(lastStatic!, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 } + if (flags & ModifierFlags.Override) { + return grammarErrorOnNode(lastOverride!, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); // TODO: GH#18217 + } else if (flags & ModifierFlags.Async) { return grammarErrorOnNode(lastAsync!, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } @@ -40079,7 +41308,7 @@ namespace ts { } if (name.kind === SyntaxKind.PrivateIdentifier) { - return grammarErrorOnNode(name, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + grammarErrorOnNode(name, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); } // Modifiers are never allowed on properties except for 'async' on a method declaration @@ -40157,6 +41386,7 @@ namespace ts { } function checkGrammarJsxElement(node: JsxOpeningLikeElement) { + checkGrammarJsxName(node.tagName); checkGrammarTypeArguments(node, node.typeArguments); const seen = new Map<__String, boolean>(); @@ -40179,6 +41409,29 @@ namespace ts { } } + function checkGrammarJsxName(node: JsxTagNameExpression) { + if (isPropertyAccessExpression(node)) { + let propName: JsxTagNameExpression = node; + do { + const check = checkGrammarJsxNestedIdentifier(propName.name); + if (check) { + return check; + } + propName = propName.expression; + } while (isPropertyAccessExpression(propName)); + const check = checkGrammarJsxNestedIdentifier(propName); + if (check) { + return check; + } + } + + function checkGrammarJsxNestedIdentifier(name: MemberName | ThisExpression) { + if (isIdentifier(name) && idText(name).indexOf(":") !== -1) { + return grammarErrorOnNode(name, Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names); + } + } + } + function checkGrammarJsxExpression(node: JsxExpression) { if (node.expression && isCommaSequence(node.expression)) { return grammarErrorOnNode(node.expression, Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array); @@ -40266,16 +41519,24 @@ namespace ts { } function checkGrammarAccessor(accessor: AccessorDeclaration): boolean { - if (!(accessor.flags & NodeFlags.Ambient)) { + if (!(accessor.flags & NodeFlags.Ambient) && (accessor.parent.kind !== SyntaxKind.TypeLiteral) && (accessor.parent.kind !== SyntaxKind.InterfaceDeclaration)) { if (languageVersion < ScriptTarget.ES5) { return grammarErrorOnNode(accessor.name, Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } + if (languageVersion < ScriptTarget.ES2015 && isPrivateIdentifier(accessor.name)) { + return grammarErrorOnNode(accessor.name, Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } if (accessor.body === undefined && !hasSyntacticModifier(accessor, ModifierFlags.Abstract)) { return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, Diagnostics._0_expected, "{"); } } - if (accessor.body && hasSyntacticModifier(accessor, ModifierFlags.Abstract)) { - return grammarErrorOnNode(accessor, Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + if (accessor.body) { + if (hasSyntacticModifier(accessor, ModifierFlags.Abstract)) { + return grammarErrorOnNode(accessor, Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + if (accessor.parent.kind === SyntaxKind.TypeLiteral || accessor.parent.kind === SyntaxKind.InterfaceDeclaration) { + return grammarErrorOnNode(accessor.body, Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } } if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, Diagnostics.An_accessor_cannot_have_type_parameters); @@ -40403,6 +41664,9 @@ namespace ts { } if (isClassLike(node.parent)) { + if (languageVersion < ScriptTarget.ES2015 && isPrivateIdentifier(node.name)) { + return grammarErrorOnNode(node.name, Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher); + } // Technically, computed properties in ambient contexts is disallowed // for property declarations and accessors too, not just methods. // However, property declarations disallow computed names in general, @@ -40733,7 +41997,7 @@ namespace ts { if (isStringLiteral(node.name) && node.name.text === "constructor") { return grammarErrorOnNode(node.name, Diagnostics.Classes_may_not_have_a_field_named_constructor); } - if (checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { + if (checkGrammarForInvalidDynamicName(node.name, Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type)) { return true; } if (languageVersion < ScriptTarget.ES2015 && isPrivateIdentifier(node.name)) { @@ -40973,7 +42237,7 @@ namespace ts { } function findBestTypeForObjectLiteral(source: Type, unionTarget: UnionOrIntersectionType) { - if (getObjectFlags(source) & ObjectFlags.ObjectLiteral && forEachType(unionTarget, isArrayLikeType)) { + if (getObjectFlags(source) & ObjectFlags.ObjectLiteral && someType(unionTarget, isArrayLikeType)) { return find(unionTarget.types, t => !isArrayLikeType(t)); } } @@ -41028,6 +42292,10 @@ namespace ts { // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source: Type, target: Type, isRelatedTo: (source: Type, target: Type) => Ternary, skipPartial?: boolean) { if (target.flags & TypeFlags.Union && source.flags & (TypeFlags.Intersection | TypeFlags.Object)) { + const match = getMatchingUnionConstituentForType(target, source); + if (match) { + return match; + } const sourceProperties = getPropertiesOfType(source); if (sourceProperties) { const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); @@ -41061,21 +42329,6 @@ namespace ts { } } - function isSomeImportDeclaration(decl: Node): boolean { - switch (decl.kind) { - case SyntaxKind.ImportClause: // For default import - case SyntaxKind.ImportEqualsDeclaration: - case SyntaxKind.NamespaceImport: - case SyntaxKind.ImportSpecifier: // For rename import `x as y` - return true; - case SyntaxKind.Identifier: - // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === SyntaxKind.ImportSpecifier; - default: - return false; - } - } - namespace JsxNames { export const JSX = "JSX" as __String; export const IntrinsicElements = "IntrinsicElements" as __String; @@ -41103,5 +42356,4 @@ namespace ts { export function signatureHasLiteralTypes(s: Signature) { return !!(s.flags & SignatureFlags.HasLiteralTypes); } - } diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index f44eae9455f64..253e38a5295b5 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -28,6 +28,7 @@ namespace ts { ["es2018", "lib.es2018.d.ts"], ["es2019", "lib.es2019.d.ts"], ["es2020", "lib.es2020.d.ts"], + ["es2021", "lib.es2021.d.ts"], ["esnext", "lib.esnext.d.ts"], // Host only ["dom", "lib.dom.d.ts"], @@ -67,14 +68,17 @@ namespace ts { ["es2020.string", "lib.es2020.string.d.ts"], ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"], ["es2020.intl", "lib.es2020.intl.d.ts"], + ["es2021.promise", "lib.es2021.promise.d.ts"], + ["es2021.string", "lib.es2021.string.d.ts"], + ["es2021.weakref", "lib.es2021.weakref.d.ts"], ["esnext.array", "lib.es2019.array.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"], ["esnext.intl", "lib.esnext.intl.d.ts"], ["esnext.bigint", "lib.es2020.bigint.d.ts"], - ["esnext.string", "lib.esnext.string.d.ts"], - ["esnext.promise", "lib.esnext.promise.d.ts"], - ["esnext.weakref", "lib.esnext.weakref.d.ts"] + ["esnext.string", "lib.es2021.string.d.ts"], + ["esnext.promise", "lib.es2021.promise.d.ts"], + ["esnext.weakref", "lib.es2021.weakref.d.ts"] ]; /** @@ -101,11 +105,12 @@ namespace ts { fixedpollinginterval: WatchFileKind.FixedPollingInterval, prioritypollinginterval: WatchFileKind.PriorityPollingInterval, dynamicprioritypolling: WatchFileKind.DynamicPriorityPolling, + fixedchunksizepolling: WatchFileKind.FixedChunkSizePolling, usefsevents: WatchFileKind.UseFsEvents, usefseventsonparentdirectory: WatchFileKind.UseFsEventsOnParentDirectory, })), category: Diagnostics.Advanced_Options, - description: Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory, + description: Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling_UseFsEvents_UseFsEventsOnParentDirectory, }, { name: "watchDirectory", @@ -113,9 +118,10 @@ namespace ts { usefsevents: WatchDirectoryKind.UseFsEvents, fixedpollinginterval: WatchDirectoryKind.FixedPollingInterval, dynamicprioritypolling: WatchDirectoryKind.DynamicPriorityPolling, + fixedchunksizepolling: WatchDirectoryKind.FixedChunkSizePolling, })), category: Diagnostics.Advanced_Options, - description: Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling, + description: Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling_FixedChunkSizePolling, }, { name: "fallbackPolling", @@ -123,9 +129,10 @@ namespace ts { fixedinterval: PollingWatchKind.FixedInterval, priorityinterval: PollingWatchKind.PriorityInterval, dynamicpriority: PollingWatchKind.DynamicPriority, + fixedchunksize: PollingWatchKind.FixedChunkSize, })), category: Diagnostics.Advanced_Options, - description: Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority, + description: Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority_FixedChunkSize, }, { name: "synchronousWatchDirectory", @@ -287,6 +294,7 @@ namespace ts { es2018: ScriptTarget.ES2018, es2019: ScriptTarget.ES2019, es2020: ScriptTarget.ES2020, + es2021: ScriptTarget.ES2021, esnext: ScriptTarget.ESNext, })), affectsSourceFile: true, @@ -295,13 +303,11 @@ namespace ts { paramType: Diagnostics.VERSION, showInSimplifiedHelpView: true, category: Diagnostics.Basic_Options, - description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT, + description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_ES2021_or_ESNEXT, }; - /* @internal */ - export const optionDeclarations: CommandLineOption[] = [ + const commandOptionsWithoutBuild: CommandLineOption[] = [ // CommandLine only options - ...commonOptionsWithBuild, { name: "all", type: "boolean", @@ -667,6 +673,14 @@ namespace ts { category: Diagnostics.Additional_Checks, description: Diagnostics.Include_undefined_in_index_signature_results }, + { + name: "noImplicitOverride", + type: "boolean", + affectsSemanticDiagnostics: true, + showInSimplifiedHelpView: false, + category: Diagnostics.Additional_Checks, + description: Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier + }, { name: "noPropertyAccessFromIndexSignature", type: "boolean", @@ -1090,6 +1104,12 @@ namespace ts { }, ]; + /* @internal */ + export const optionDeclarations: CommandLineOption[] = [ + ...commonOptionsWithBuild, + ...commandOptionsWithoutBuild, + ]; + /* @internal */ export const semanticDiagnosticsOptionDeclarations: readonly CommandLineOption[] = optionDeclarations.filter(option => !!option.affectsSemanticDiagnostics); @@ -1110,9 +1130,7 @@ namespace ts { export const transpileOptionValueCompilerOptions: readonly CommandLineOption[] = optionDeclarations.filter(option => hasProperty(option, "transpileOptionValue")); - /* @internal */ - export const buildOpts: CommandLineOption[] = [ - ...commonOptionsWithBuild, + const commandOptionsOnlyBuild: CommandLineOption[] = [ { name: "verbose", shortName: "v", @@ -1142,6 +1160,12 @@ namespace ts { } ]; + /* @internal */ + export const buildOpts: CommandLineOption[] = [ + ...commonOptionsWithBuild, + ...commandOptionsOnlyBuild, + ]; + /* @internal */ export const typeAcquisitionDeclarations: CommandLineOption[] = [ { @@ -1201,9 +1225,14 @@ namespace ts { /* @internal */ export function getOptionsNameMap(): OptionsNameMap { - return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(optionDeclarations)); + return optionsNameMapCache ||= createOptionNameMap(optionDeclarations); } + const compilerOptionsAlternateMode: AlternateModeDiagnostics = { + diagnostic: Diagnostics.Compiler_option_0_may_only_be_used_with_build, + getOptionsNameMap: getBuildOptionsNameMap + }; + /* @internal */ export const defaultInitCompilerOptions: CompilerOptions = { module: ModuleKind.CommonJS, @@ -1283,6 +1312,10 @@ namespace ts { createDiagnostics: (message: DiagnosticMessage, arg0: string, arg1?: string) => Diagnostic, unknownOptionErrorText?: string ) { + if (diagnostics.alternateMode?.getOptionsNameMap().optionsNameMap.has(unknownOption.toLowerCase())) { + return createDiagnostics(diagnostics.alternateMode.diagnostic, unknownOption); + } + const possibleOption = getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName); return possibleOption ? createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : @@ -1448,6 +1481,7 @@ namespace ts { /*@internal*/ export const compilerOptionsDidYouMeanDiagnostics: ParseCommandLineWorkerDiagnostics = { + alternateMode: compilerOptionsAlternateMode, getOptionsNameMap, optionDeclarations, unknownOptionDiagnostic: Diagnostics.Unknown_compiler_option_0, @@ -1489,7 +1523,13 @@ namespace ts { return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(buildOpts)); } + const buildOptionsAlternateMode: AlternateModeDiagnostics = { + diagnostic: Diagnostics.Compiler_option_0_may_not_be_used_with_build, + getOptionsNameMap + }; + const buildOptionsDidYouMeanDiagnostics: ParseCommandLineWorkerDiagnostics = { + alternateMode: buildOptionsAlternateMode, getOptionsNameMap: getBuildOptionsNameMap, optionDeclarations: buildOpts, unknownOptionDiagnostic: Diagnostics.Unknown_build_option_0, @@ -1556,7 +1596,7 @@ namespace ts { */ export function getParsedCommandLineOfConfigFile( configFileName: string, - optionsToExtend: CompilerOptions, + optionsToExtend: CompilerOptions | undefined, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions, @@ -1603,7 +1643,7 @@ namespace ts { export function parseConfigFileTextToJson(fileName: string, jsonText: string): { config?: any; error?: Diagnostic } { const jsonSourceFile = parseJsonText(fileName, jsonText); return { - config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + config: convertConfigFileToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics, /*reportOptionsErrors*/ false, /*optionsIterator*/ undefined), error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined }; } @@ -1767,11 +1807,35 @@ namespace ts { onSetUnknownOptionKeyValueInRoot(key: string, keyNode: PropertyName, value: CompilerOptionsValue, valueNode: Expression): void; } + function convertConfigFileToObject(sourceFile: JsonSourceFile, errors: Push, reportOptionsErrors: boolean, optionsIterator: JsonConversionNotifier | undefined): any { + const rootExpression: Expression | undefined = sourceFile.statements[0]?.expression; + const knownRootOptions = reportOptionsErrors ? getTsconfigRootOptionsMap() : undefined; + if (rootExpression && rootExpression.kind !== SyntaxKind.ObjectLiteralExpression) { + errors.push(createDiagnosticForNodeInSourceFile( + sourceFile, + rootExpression, + Diagnostics.The_root_value_of_a_0_file_must_be_an_object, + getBaseFileName(sourceFile.fileName) === "jsconfig.json" ? "jsconfig.json" : "tsconfig.json" + )); + // Last-ditch error recovery. Somewhat useful because the JSON parser will recover from some parse errors by + // synthesizing a top-level array literal expression. There's a reasonable chance the first element of that + // array is a well-formed configuration object, made into an array element by stray characters. + if (isArrayLiteralExpression(rootExpression)) { + const firstObject = find(rootExpression.elements, isObjectLiteralExpression); + if (firstObject) { + return convertToObjectWorker(sourceFile, firstObject, errors, /*returnValue*/ true, knownRootOptions, optionsIterator); + } + } + return {}; + } + return convertToObjectWorker(sourceFile, rootExpression, errors, /*returnValue*/ true, knownRootOptions, optionsIterator); + } + /** * Convert the json syntax tree into the json value */ export function convertToObject(sourceFile: JsonSourceFile, errors: Push): any { - return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + return convertToObjectWorker(sourceFile, sourceFile.statements[0]?.expression, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); } /** @@ -1782,15 +1846,16 @@ namespace ts { /*@internal*/ export function convertToObjectWorker( sourceFile: JsonSourceFile, + rootExpression: Expression | undefined, errors: Push, returnValue: boolean, knownRootOptions: CommandLineOption | undefined, jsonConversionNotifier: JsonConversionNotifier | undefined): any { - if (!sourceFile.statements.length) { + if (!rootExpression) { return returnValue ? {} : undefined; } - return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + return convertPropertyValueToJson(rootExpression, knownRootOptions); function isRootOptionMap(knownOptions: ESMap | undefined) { return knownRootOptions && (knownRootOptions as TsConfigOnlyOption).elementOptions === knownOptions; @@ -2733,7 +2798,7 @@ namespace ts { } } }; - const json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); + const json = convertConfigFileToObject(sourceFile, errors, /*reportOptionsErrors*/ true, optionsIterator); if (!typeAcquisition) { if (typingOptionstypeAcquisition) { diff --git a/src/compiler/core.ts b/src/compiler/core.ts index e66ea4c2597bf..dafda8263ad89 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -292,7 +292,7 @@ namespace ts { return -1; } - export function countWhere(array: readonly T[], predicate: (x: T, i: number) => boolean): number { + export function countWhere(array: readonly T[] | undefined, predicate: (x: T, i: number) => boolean): number { let count = 0; if (array) { for (let i = 0; i < array.length; i++) { diff --git a/src/compiler/corePublic.ts b/src/compiler/corePublic.ts index 31c852bdee6d4..ec1ec375ff1d3 100644 --- a/src/compiler/corePublic.ts +++ b/src/compiler/corePublic.ts @@ -1,11 +1,11 @@ namespace ts { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - export const versionMajorMinor = "4.2"; + export const versionMajorMinor = "4.3"; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - export const version: string = `${versionMajorMinor}.0-dev`; + export const version = "4.3.2" as string; /** * Type of objects whose values are all of the same type. diff --git a/src/compiler/debug.ts b/src/compiler/debug.ts index 8d14c9c1ee5d7..adf968fe2c7bd 100644 --- a/src/compiler/debug.ts +++ b/src/compiler/debug.ts @@ -275,6 +275,14 @@ namespace ts { } } + /** + * Asserts a value has the specified type in typespace only (does not perform a runtime assertion). + * This is useful in cases where we switch on `node.kind` and can be reasonably sure the type is accurate, and + * as a result can reduce the number of unnecessary casts. + */ + export function type(value: unknown): asserts value is T; + export function type(_value: unknown) { } + export function getFunctionName(func: AnyFunction) { if (typeof func !== "function") { return ""; diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 035e0b5ceea2f..c63f9b33a9837 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -503,7 +503,7 @@ "category": "Error", "code": 1165 }, - "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type.": { + "A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type.": { "category": "Error", "code": 1166 }, @@ -743,7 +743,7 @@ "category": "Error", "code": 1230 }, - "An export assignment can only be used in a module.": { + "An export assignment must be at the top level of a file or module declaration.": { "category": "Error", "code": 1231 }, @@ -847,6 +847,10 @@ "category": "Error", "code": 1257 }, + "A default export must be at the top level of a file or module declaration.": { + "category": "Error", + "code": 1258 + }, "Module '{0}' can only be default-imported using the '{1}' flag": { "category": "Error", "code": 1259 @@ -1192,7 +1196,7 @@ "category": "Message", "code": 1390 }, - "The `bundledPackageName` option must be provided when using outFile and node module resolution with declaration emit.": { + "The 'bundledPackageName' option must be provided when using outFile and node module resolution with declaration emit.": { "category": "Error", "code": 1391 }, @@ -1360,6 +1364,10 @@ "category": "Error", "code": 1432 }, + "Decorators may not be applied to 'this' parameters.": { + "category": "Error", + "code": 1433 + }, "The types of '{0}' are incompatible between these types.": { "category": "Error", @@ -1706,11 +1714,7 @@ "category": "Error", "code": 2378 }, - "Getter and setter accessors do not agree in visibility.": { - "category": "Error", - "code": 2379 - }, - "'get' and 'set' accessor must have the same type.": { + "The return type of a 'get' accessor must be assignable to its 'set' accessor type": { "category": "Error", "code": 2380 }, @@ -1962,7 +1966,7 @@ "category": "Error", "code": 2445 }, - "Property '{0}' is protected and only accessible through an instance of class '{1}'.": { + "Property '{0}' is protected and only accessible through an instance of class '{1}'. This is an instance of class '{2}'.": { "category": "Error", "code": 2446 }, @@ -2362,7 +2366,7 @@ "category": "Error", "code": 2549 }, - "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the `lib` compiler option to '{2}' or later.": { + "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{2}' or later.": { "category": "Error", "code": 2550 }, @@ -2386,14 +2390,10 @@ "category": "Error", "code": 2555 }, - "Expected {0} arguments, but got {1} or more.": { + "A spread argument must either have a tuple type or be passed to a rest parameter.": { "category": "Error", "code": 2556 }, - "Expected at least {0} arguments, but got {1} or more.": { - "category": "Error", - "code": 2557 - }, "Expected {0} type arguments, but got {1}.": { "category": "Error", "code": 2558 @@ -2482,15 +2482,15 @@ "category": "Error", "code": 2582 }, - "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to '{1}' or later.": { + "Cannot find name '{0}'. Do you need to change your target library? Try changing the 'lib' compiler option to '{1}' 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'.": { + "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.": { + "'{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 }, @@ -2514,15 +2514,15 @@ "category": "Error", "code": 2590 }, - "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add `node` to the types field in your tsconfig.": { + "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig.": { "category": "Error", "code": 2591 }, - "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add `jquery` to the types field in your tsconfig.": { + "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add 'jquery' to the types field in your tsconfig.": { "category": "Error", "code": 2592 }, - "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig.": { + "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig.": { "category": "Error", "code": 2593 }, @@ -2654,6 +2654,30 @@ "category": "Error", "code": 2627 }, + "Cannot assign to '{0}' because it is an enum.": { + "category": "Error", + "code": 2628 + }, + "Cannot assign to '{0}' because it is a class.": { + "category": "Error", + "code": 2629 + }, + "Cannot assign to '{0}' because it is a function.": { + "category": "Error", + "code": 2630 + }, + "Cannot assign to '{0}' because it is a namespace.": { + "category": "Error", + "code": 2631 + }, + "Cannot assign to '{0}' because it is an import.": { + "category": "Error", + "code": 2632 + }, + "JSX property access expressions cannot include JSX namespace names": { + "category": "Error", + "code": 2633 + }, "Cannot augment module '{0}' with value exports because it resolves to a non-module entity.": { "category": "Error", @@ -2840,7 +2864,7 @@ "category": "Error", "code": 2696 }, - "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option.": { + "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option.": { "category": "Error", "code": 2697 }, @@ -2872,7 +2896,7 @@ "category": "Error", "code": 2704 }, - "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option.": { + "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option.": { "category": "Error", "code": 2705 }, @@ -2896,11 +2920,11 @@ "category": "Error", "code": 2710 }, - "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option.": { + "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your '--lib' option.": { "category": "Error", "code": 2711 }, - "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option.": { + "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option.": { "category": "Error", "code": 2712 }, @@ -3148,7 +3172,7 @@ "category": "Error", "code": 2773 }, - "This condition will always return true since the function is always defined. Did you mean to call it instead?": { + "This condition will always return true since this function is always defined. Did you mean to call it instead?": { "category": "Error", "code": 2774 }, @@ -3256,6 +3280,54 @@ "category": "Error", "code": 2800 }, + "This condition will always return true since this '{0}' is always defined.": { + "category": "Error", + "code": 2801 + }, + "Type '{0}' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher.": { + "category": "Error", + "code": 2802 + }, + "Cannot assign to private method '{0}'. Private methods are not writable.": { + "category": "Error", + "code": 2803 + }, + "Duplicate identifier '{0}'. Static and instance elements cannot share the same private name.": { + "category": "Error", + "code": 2804 + }, + "Static fields with private names can't have initializers when the '--useDefineForClassFields' flag is not specified with a '--target' of 'esnext'. Consider adding the '--useDefineForClassFields' flag.": { + "category": "Error", + "code": 2805 + }, + "Private accessor was defined without a getter.": { + "category": "Error", + "code": 2806 + }, + "This syntax requires an imported helper named '{1}' with {2} parameters, which is not compatible with the one in '{0}'. Consider upgrading your version of '{0}'.": { + "category": "Error", + "code": 2807 + }, + "A get accessor must be at least as accessible as the setter": { + "category": "Error", + "code": 2808 + }, + "Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses.": { + "category": "Error", + "code": 2809 + }, + "Property '{0}' may not be used in a static property's initializer in the same class when 'target' is 'esnext' and 'useDefineForClassFields' is 'false'.": { + "category": "Error", + "code": 2810 + }, + "Initializer for property '{0}'": { + "category": "Error", + "code": 2811 + }, + "Property '{0}' does not exist on type '{1}'. Try changing the 'lib' compiler option to include 'dom'.": { + "category": "Error", + "code": 2812 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", @@ -3633,6 +3705,26 @@ "category": "Error", "code": 4111 }, + "This member cannot have an 'override' modifier because its containing class '{0}' does not extend another class.": { + "category": "Error", + "code": 4112 + }, + "This member cannot have an 'override' modifier because it is not declared in the base class '{0}'.": { + "category": "Error", + "code": 4113 + }, + "This member must have an 'override' modifier because it overrides a member in the base class '{0}'.": { + "category": "Error", + "code": 4114 + }, + "This parameter property must have an 'override' modifier because it overrides a member in base class '{0}'.": { + "category": "Error", + "code": 4115 + }, + "This member must have an 'override' modifier because it overrides an abstract method that is declared in the base class '{0}'.": { + "category": "Error", + "code": 4116 + }, "The current host does not support the '{0}' option.": { "category": "Error", @@ -3770,7 +3862,7 @@ "category": "Error", "code": 5073 }, - "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option `--tsBuildInfoFile` is specified.": { + "Option '--incremental' can only be specified using tsconfig, emitting to single file or when option '--tsBuildInfoFile' is specified.": { "category": "Error", "code": 5074 }, @@ -3822,7 +3914,7 @@ "category": "Error", "code": 5086 }, - "A labeled tuple element is declared as rest with a `...` before the name, rather than before the type.": { + "A labeled tuple element is declared as rest with a '...' before the name, rather than before the type.": { "category": "Error", "code": 5087 }, @@ -3842,6 +3934,18 @@ "category": "Error", "code": 5091 }, + "The root value of a '{0}' file must be an object.": { + "category": "Error", + "code": 5092 + }, + "Compiler option '--{0}' may only be used with '--build'.": { + "category": "Error", + "code": 5093 + }, + "Compiler option '--{0}' may not be used with '--build'.": { + "category": "Error", + "code": 5094 + }, "Generates a sourcemap for each corresponding '.d.ts' file.": { "category": "Message", @@ -3903,7 +4007,7 @@ "category": "Message", "code": 6014 }, - "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'.": { + "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'.": { "category": "Message", "code": 6015 }, @@ -4689,15 +4793,15 @@ "category": "Message", "code": 6224 }, - "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'.": { + "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'.": { "category": "Message", "code": 6225 }, - "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling'.": { + "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling', 'FixedChunkSizePolling'.": { "category": "Message", "code": 6226 }, - "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority'.": { + "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority', 'FixedChunkSize'.": { "category": "Message", "code": 6227 }, @@ -4741,10 +4845,26 @@ "category": "Message", "code": 6237 }, - "Specify the module specifier to be used to import the `jsx` and `jsxs` factory functions from. eg, react": { + "Specify the module specifier to be used to import the 'jsx' and 'jsxs' factory functions from. eg, react": { "category": "Error", "code": 6238 }, + "File '{0}' exists according to earlier cached lookups.": { + "category": "Message", + "code": 6239 + }, + "File '{0}' does not exist according to earlier cached lookups.": { + "category": "Message", + "code": 6240 + }, + "Resolution for type reference directive '{0}' was found in cache from location '{1}'.": { + "category": "Message", + "code": 6241 + }, + "======== Resolving type reference directive '{0}', containing file '{1}'. ========": { + "category": "Message", + "code": 6242 + }, "Projects to reference": { "category": "Message", @@ -4937,6 +5057,10 @@ "code": 6387, "reportsDeprecated": true }, + "Project '{0}' is being forcibly rebuilt": { + "category": "Message", + "code": 6388 + }, "The expected type comes from property '{0}' which is declared here on type '{1}'": { "category": "Message", @@ -4962,15 +5086,19 @@ "category": "Message", "code": 6505 }, - "Require undeclared properties from index signatures to use element accesses.": { - "category": "Error", - "code": 6803 - }, "Include 'undefined' in index signature results": { "category": "Message", "code": 6800 }, + "Ensure overriding members in derived classes are marked with an 'override' modifier.": { + "category": "Message", + "code": 6801 + }, + "Require undeclared properties from index signatures to use element accesses.": { + "category": "Message", + "code": 6802 + }, "Variable '{0}' implicitly has an '{1}' type.": { "category": "Error", @@ -5102,7 +5230,7 @@ "category": "Error", "code": 7039 }, - "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`": { + "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}'": { "category": "Error", "code": 7040 }, @@ -5263,7 +5391,7 @@ "category": "Error", "code": 8024 }, - "Class declarations cannot have more than one `@augments` or `@extends` tag.": { + "Class declarations cannot have more than one '@augments' or '@extends' tag.": { "category": "Error", "code": 8025 }, @@ -6245,7 +6373,22 @@ "category": "Message", "code": 95159 }, - + "Add 'override' modifier": { + "category": "Message", + "code": 95160 + }, + "Remove 'override' modifier": { + "category": "Message", + "code": 95161 + }, + "Add all missing 'override' modifiers": { + "category": "Message", + "code": 95162 + }, + "Remove all unnecessary 'override' modifiers": { + "category": "Message", + "code": 95163 + }, "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer.": { "category": "Error", @@ -6303,14 +6446,6 @@ "category": "Error", "code": 18019 }, - "A method cannot be named with a private identifier.": { - "category": "Error", - "code": 18022 - }, - "An accessor cannot be named with a private identifier.": { - "category": "Error", - "code": 18023 - }, "An enum member cannot be named with a private identifier.": { "category": "Error", "code": 18024 @@ -6354,5 +6489,9 @@ "Invalid value for 'jsxFragmentFactory'. '{0}' is not a valid identifier or qualified-name.": { "category": "Error", "code": 18035 + }, + "Class decorators can't be used with static private identifier. Consider removing the experimental decorator.": { + "category": "Error", + "code": 18036 } } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index a2bba125ca8f3..a3007559f0dd9 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1,6 +1,5 @@ namespace ts { const brackets = createBracketsMap(); - const syntheticParent: TextRange = { pos: -1, end: -1 }; /*@internal*/ export function isBuildInfoFile(file: string) { @@ -499,7 +498,7 @@ namespace ts { declarationTransform.transformed[0], declarationPrinter, { - sourceMap: compilerOptions.declarationMap, + sourceMap: !forceDtsEmit && compilerOptions.declarationMap, sourceRoot: compilerOptions.sourceRoot, mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, @@ -664,7 +663,7 @@ namespace ts { /*@internal*/ export function getBuildInfoText(buildInfo: BuildInfo) { - return JSON.stringify(buildInfo, undefined, 2); + return JSON.stringify(buildInfo); } /*@internal*/ @@ -866,7 +865,7 @@ namespace ts { Substitution, Comments, SourceMaps, - Emit + Emit, } export function createPrinter(printerOptions: PrinterOptions = {}, handlers: PrintHandlers = {}): Printer { @@ -875,6 +874,8 @@ namespace ts { onEmitNode = noEmitNotification, isEmitNotificationEnabled, substituteNode = noEmitSubstitution, + onBeforeEmitNode, + onAfterEmitNode, onBeforeEmitNodeArray, onAfterEmitNodeArray, onBeforeEmitToken, @@ -920,12 +921,14 @@ namespace ts { let containerEnd = -1; let declarationListContainerEnd = -1; let currentLineMap: readonly number[] | undefined; - let detachedCommentsInfo: { nodePos: number, detachedCommentEndPos: number}[] | undefined; + let detachedCommentsInfo: { nodePos: number, detachedCommentEndPos: number }[] | undefined; let hasWrittenComment = false; let commentsDisabled = !!printerOptions.removeComments; - let lastNode: Node | undefined; let lastSubstitution: Node | undefined; + let currentParenthesizerRule: ((node: Node) => Node) | undefined; const { enter: enterComment, exit: exitComment } = performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"); + const parenthesizer = factory.parenthesizer; + const emitBinaryExpression = createEmitBinaryExpression(); reset(); return { @@ -1003,7 +1006,7 @@ namespace ts { if (sourceFile) { setSourceFile(sourceFile); } - emitList(syntheticParent, nodes, format); + emitList(/*parentNode*/ undefined, nodes, format); reset(); writer = previousWriter; } @@ -1147,7 +1150,7 @@ namespace ts { setSourceFile(sourceFile); } - pipelineEmit(hint, node); + pipelineEmit(hint, node, /*parenthesizerRule*/ undefined); } function setSourceFile(sourceFile: SourceFile | undefined) { @@ -1176,11 +1179,9 @@ namespace ts { tempFlagsStack = []; tempFlags = TempFlags.Auto; reservedNamesStack = []; - currentSourceFile = undefined!; - currentLineMap = undefined!; + currentSourceFile = undefined; + currentLineMap = undefined; detachedCommentsInfo = undefined; - lastNode = undefined; - lastSubstitution = undefined; setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined); } @@ -1188,56 +1189,60 @@ namespace ts { return currentLineMap || (currentLineMap = getLineStarts(currentSourceFile!)); } - function emit(node: Node): Node; - function emit(node: Node | undefined): Node | undefined; - function emit(node: Node | undefined) { + function emit(node: Node, parenthesizerRule?: (node: Node) => Node): void; + function emit(node: Node | undefined, parenthesizerRule?: (node: Node) => Node): void; + function emit(node: Node | undefined, parenthesizerRule?: (node: Node) => Node) { if (node === undefined) return; - const prevSourceFileTextKind = recordBundleFileInternalSectionStart(node); - const substitute = pipelineEmit(EmitHint.Unspecified, node); + pipelineEmit(EmitHint.Unspecified, node, parenthesizerRule); recordBundleFileInternalSectionEnd(prevSourceFileTextKind); - return substitute; } - function emitIdentifierName(node: Identifier): Node; - function emitIdentifierName(node: Identifier | undefined): Node | undefined; - function emitIdentifierName(node: Identifier | undefined): Node | undefined { + function emitIdentifierName(node: Identifier): void; + function emitIdentifierName(node: Identifier | undefined): void; + function emitIdentifierName(node: Identifier | undefined) { if (node === undefined) return; - return pipelineEmit(EmitHint.IdentifierName, node); + pipelineEmit(EmitHint.IdentifierName, node, /*parenthesizerRule*/ undefined); } - function emitExpression(node: Expression): Node; - function emitExpression(node: Expression | undefined): Node | undefined; - function emitExpression(node: Expression | undefined): Node | undefined { + function emitExpression(node: Expression, parenthesizerRule?: (node: Expression) => Expression): void; + function emitExpression(node: Expression | undefined, parenthesizerRule?: (node: Expression) => Expression): void; + function emitExpression(node: Expression | undefined, parenthesizerRule?: (node: Expression) => Expression) { if (node === undefined) return; - return pipelineEmit(EmitHint.Expression, node); + pipelineEmit(EmitHint.Expression, node, parenthesizerRule); } - function emitJsxAttributeValue(node: StringLiteral | JsxExpression): Node { - return pipelineEmit(isStringLiteral(node) ? EmitHint.JsxAttributeValue : EmitHint.Unspecified, node); + function emitJsxAttributeValue(node: StringLiteral | JsxExpression): void { + pipelineEmit(isStringLiteral(node) ? EmitHint.JsxAttributeValue : EmitHint.Unspecified, node); } - function pipelineEmit(emitHint: EmitHint, node: Node) { - const savedLastNode = lastNode; - const savedLastSubstitution = lastSubstitution; - const savedPreserveSourceNewlines = preserveSourceNewlines; - lastNode = node; - lastSubstitution = undefined; - if (preserveSourceNewlines && !!(getEmitFlags(node) & EmitFlags.IgnoreSourceNewlines)) { + function beforeEmitNode(node: Node) { + if (preserveSourceNewlines && (getEmitFlags(node) & EmitFlags.IgnoreSourceNewlines)) { preserveSourceNewlines = false; } + } + function afterEmitNode(savedPreserveSourceNewlines: boolean | undefined) { + preserveSourceNewlines = savedPreserveSourceNewlines; + } + + function pipelineEmit(emitHint: EmitHint, node: Node, parenthesizerRule?: (node: Node) => Node) { + currentParenthesizerRule = parenthesizerRule; const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, emitHint, node); pipelinePhase(emitHint, node); + currentParenthesizerRule = undefined; + } - Debug.assert(lastNode === node); - - const substitute = lastSubstitution; - lastNode = savedLastNode; - lastSubstitution = savedLastSubstitution; - preserveSourceNewlines = savedPreserveSourceNewlines; + function shouldEmitComments(node: Node) { + return !commentsDisabled && !isSourceFile(node); + } - return substitute || node; + function shouldEmitSourceMaps(node: Node) { + return !sourceMapsDisabled && + !isSourceFile(node) && + !isInJsonFile(node) && + !isUnparsedSource(node) && + !isUnparsedPrepend(node); } function getPipelinePhase(phase: PipelinePhase, emitHint: EmitHint, node: Node) { @@ -1247,28 +1252,26 @@ namespace ts { return pipelineEmitWithNotification; } // falls through - case PipelinePhase.Substitution: - if (substituteNode !== noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) { + if (substituteNode !== noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) { + if (currentParenthesizerRule) { + lastSubstitution = currentParenthesizerRule(lastSubstitution); + } return pipelineEmitWithSubstitution; } // falls through - case PipelinePhase.Comments: - if (!commentsDisabled && node.kind !== SyntaxKind.SourceFile) { + if (shouldEmitComments(node)) { return pipelineEmitWithComments; } // falls through - case PipelinePhase.SourceMaps: - if (!sourceMapsDisabled && node.kind !== SyntaxKind.SourceFile && !isInJsonFile(node)) { - return pipelineEmitWithSourceMap; + if (shouldEmitSourceMaps(node)) { + return pipelineEmitWithSourceMaps; } // falls through - case PipelinePhase.Emit: return pipelineEmitWithHint; - default: return Debug.assertNever(phase); } @@ -1279,14 +1282,27 @@ namespace ts { } function pipelineEmitWithNotification(hint: EmitHint, node: Node) { - Debug.assert(lastNode === node); const pipelinePhase = getNextPipelinePhase(PipelinePhase.Notification, hint, node); onEmitNode(hint, node, pipelinePhase); - Debug.assert(lastNode === node); } function pipelineEmitWithHint(hint: EmitHint, node: Node): void { - Debug.assert(lastNode === node || lastSubstitution === node); + onBeforeEmitNode?.(node); + if (preserveSourceNewlines) { + const savedPreserveSourceNewlines = preserveSourceNewlines; + beforeEmitNode(node); + pipelineEmitWithHintWorker(hint, node); + afterEmitNode(savedPreserveSourceNewlines); + } + else { + pipelineEmitWithHintWorker(hint, node); + } + onAfterEmitNode?.(node); + // clear the parenthesizer rule as we ascend + currentParenthesizerRule = undefined; + } + + function pipelineEmitWithHintWorker(hint: EmitHint, node: Node): void { if (hint === EmitHint.SourceFile) return emitSourceFile(cast(node, isSourceFile)); if (hint === EmitHint.IdentifierName) return emitIdentifier(cast(node, isIdentifier)); if (hint === EmitHint.JsxAttributeValue) return emitLiteral(cast(node, isStringLiteral), /*jsxAttributeEscape*/ true); @@ -1296,8 +1312,6 @@ namespace ts { return emitEmptyStatement(/*isEmbeddedStatement*/ true); } if (hint === EmitHint.Unspecified) { - if (isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); - switch (node.kind) { // Pseudo-literals case SyntaxKind.TemplateHead: @@ -1305,21 +1319,6 @@ namespace ts { case SyntaxKind.TemplateTail: return emitLiteral(node, /*jsxAttributeEscape*/ false); - case SyntaxKind.UnparsedSource: - case SyntaxKind.UnparsedPrepend: - return emitUnparsedSourceOrPrepend(node); - - case SyntaxKind.UnparsedPrologue: - return writeUnparsedNode(node); - - case SyntaxKind.UnparsedText: - case SyntaxKind.UnparsedInternalText: - return emitUnparsedTextLike(node); - - case SyntaxKind.UnparsedSyntheticReference: - return emitUnparsedSyntheticReference(node); - - // Identifiers case SyntaxKind.Identifier: return emitIdentifier(node); @@ -1363,8 +1362,6 @@ namespace ts { return emitConstructSignature(node); case SyntaxKind.IndexSignature: return emitIndexSignature(node); - case SyntaxKind.TemplateLiteralTypeSpan: - return emitTemplateTypeSpan(node); // Types case SyntaxKind.TypePredicate: @@ -1373,8 +1370,6 @@ namespace ts { return emitTypeReference(node); case SyntaxKind.FunctionType: return emitFunctionType(node); - case SyntaxKind.JSDocFunctionType: - return emitJSDocFunctionType(node as JSDocFunctionType); case SyntaxKind.ConstructorType: return emitConstructorType(node); case SyntaxKind.TypeQuery: @@ -1387,6 +1382,7 @@ namespace ts { return emitTupleType(node); case SyntaxKind.OptionalType: return emitOptionalType(node); + // SyntaxKind.RestType is handled below case SyntaxKind.UnionType: return emitUnionType(node); case SyntaxKind.IntersectionType: @@ -1409,27 +1405,14 @@ namespace ts { return emitMappedType(node); case SyntaxKind.LiteralType: return emitLiteralType(node); + case SyntaxKind.NamedTupleMember: + return emitNamedTupleMember(node as NamedTupleMember); case SyntaxKind.TemplateLiteralType: return emitTemplateType(node); + case SyntaxKind.TemplateLiteralTypeSpan: + return emitTemplateTypeSpan(node); case SyntaxKind.ImportType: return emitImportTypeNode(node); - case SyntaxKind.JSDocAllType: - writePunctuation("*"); - return; - case SyntaxKind.JSDocUnknownType: - writePunctuation("?"); - return; - case SyntaxKind.JSDocNullableType: - return emitJSDocNullableType(node as JSDocNullableType); - case SyntaxKind.JSDocNonNullableType: - return emitJSDocNonNullableType(node as JSDocNonNullableType); - case SyntaxKind.JSDocOptionalType: - return emitJSDocOptionalType(node as JSDocOptionalType); - case SyntaxKind.RestType: - case SyntaxKind.JSDocVariadicType: - return emitRestOrJSDocVariadicType(node as RestTypeNode | JSDocVariadicType); - case SyntaxKind.NamedTupleMember: - return emitNamedTupleMember(node as NamedTupleMember); // Binding patterns case SyntaxKind.ObjectBindingPattern: @@ -1577,51 +1560,108 @@ namespace ts { case SyntaxKind.EnumMember: return emitEnumMember(node); + // Unparsed + case SyntaxKind.UnparsedPrologue: + return writeUnparsedNode(node); + case SyntaxKind.UnparsedSource: + case SyntaxKind.UnparsedPrepend: + return emitUnparsedSourceOrPrepend(node); + case SyntaxKind.UnparsedText: + case SyntaxKind.UnparsedInternalText: + return emitUnparsedTextLike(node); + case SyntaxKind.UnparsedSyntheticReference: + return emitUnparsedSyntheticReference(node); + + // Top-level nodes + case SyntaxKind.SourceFile: + return emitSourceFile(node); + case SyntaxKind.Bundle: + return Debug.fail("Bundles should be printed using printBundle"); + // SyntaxKind.UnparsedSource (handled above) + case SyntaxKind.InputFiles: + return Debug.fail("InputFiles should not be printed"); + // JSDoc nodes (only used in codefixes currently) + case SyntaxKind.JSDocTypeExpression: + return emitJSDocTypeExpression(node as JSDocTypeExpression); + case SyntaxKind.JSDocNameReference: + return emitJSDocNameReference(node as JSDocNameReference); + case SyntaxKind.JSDocAllType: + return writePunctuation("*"); + case SyntaxKind.JSDocUnknownType: + return writePunctuation("?"); + case SyntaxKind.JSDocNullableType: + return emitJSDocNullableType(node as JSDocNullableType); + case SyntaxKind.JSDocNonNullableType: + return emitJSDocNonNullableType(node as JSDocNonNullableType); + case SyntaxKind.JSDocOptionalType: + return emitJSDocOptionalType(node as JSDocOptionalType); + case SyntaxKind.JSDocFunctionType: + return emitJSDocFunctionType(node as JSDocFunctionType); + case SyntaxKind.RestType: + case SyntaxKind.JSDocVariadicType: + return emitRestOrJSDocVariadicType(node as RestTypeNode | JSDocVariadicType); + case SyntaxKind.JSDocNamepathType: + return; + case SyntaxKind.JSDocComment: + return emitJSDoc(node as JSDoc); + case SyntaxKind.JSDocTypeLiteral: + return emitJSDocTypeLiteral(node as JSDocTypeLiteral); + case SyntaxKind.JSDocSignature: + return emitJSDocSignature(node as JSDocSignature); + case SyntaxKind.JSDocTag: + case SyntaxKind.JSDocClassTag: + return emitJSDocSimpleTag(node as JSDocTag); + case SyntaxKind.JSDocAugmentsTag: + case SyntaxKind.JSDocImplementsTag: + return emitJSDocHeritageTag(node as JSDocImplementsTag | JSDocAugmentsTag); + case SyntaxKind.JSDocAuthorTag: + case SyntaxKind.JSDocDeprecatedTag: + return; + // SyntaxKind.JSDocClassTag (see JSDocTag, above) + case SyntaxKind.JSDocPublicTag: + case SyntaxKind.JSDocPrivateTag: + case SyntaxKind.JSDocProtectedTag: + case SyntaxKind.JSDocReadonlyTag: + case SyntaxKind.JSDocOverrideTag: + return; + case SyntaxKind.JSDocCallbackTag: + return emitJSDocCallbackTag(node as JSDocCallbackTag); + // SyntaxKind.JSDocEnumTag (see below) case SyntaxKind.JSDocParameterTag: case SyntaxKind.JSDocPropertyTag: return emitJSDocPropertyLikeTag(node as JSDocPropertyLikeTag); + case SyntaxKind.JSDocEnumTag: case SyntaxKind.JSDocReturnTag: - case SyntaxKind.JSDocTypeTag: case SyntaxKind.JSDocThisTag: - case SyntaxKind.JSDocEnumTag: + case SyntaxKind.JSDocTypeTag: return emitJSDocSimpleTypedTag(node as JSDocTypeTag); - case SyntaxKind.JSDocImplementsTag: - case SyntaxKind.JSDocAugmentsTag: - return emitJSDocHeritageTag(node as JSDocImplementsTag | JSDocAugmentsTag); case SyntaxKind.JSDocTemplateTag: return emitJSDocTemplateTag(node as JSDocTemplateTag); case SyntaxKind.JSDocTypedefTag: return emitJSDocTypedefTag(node as JSDocTypedefTag); - case SyntaxKind.JSDocCallbackTag: - return emitJSDocCallbackTag(node as JSDocCallbackTag); - case SyntaxKind.JSDocSignature: - return emitJSDocSignature(node as JSDocSignature); - case SyntaxKind.JSDocTypeLiteral: - return emitJSDocTypeLiteral(node as JSDocTypeLiteral); - case SyntaxKind.JSDocClassTag: - case SyntaxKind.JSDocTag: - return emitJSDocSimpleTag(node as JSDocTag); case SyntaxKind.JSDocSeeTag: return emitJSDocSeeTag(node as JSDocSeeTag); - case SyntaxKind.JSDocNameReference: - return emitJSDocNameReference(node as JSDocNameReference); - - case SyntaxKind.JSDocComment: - return emitJSDoc(node as JSDoc); + // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) - // Transformation nodes (ignored) + // Transformation nodes + case SyntaxKind.NotEmittedStatement: + case SyntaxKind.EndOfDeclarationMarker: + case SyntaxKind.MergeDeclarationMarker: + return; } - if (isExpression(node)) { hint = EmitHint.Expression; if (substituteNode !== noEmitSubstitution) { - lastSubstitution = node = substituteNode(hint, node); + const substitute = substituteNode(hint, node) || node; + if (substitute !== node) { + node = substitute; + if (currentParenthesizerRule) { + node = currentParenthesizerRule(node); + } + } } } - else if (isToken(node)) { - return writeTokenNode(node, writePunctuation); - } } if (hint === EmitHint.Expression) { switch (node.kind) { @@ -1639,16 +1679,6 @@ namespace ts { case SyntaxKind.Identifier: return emitIdentifier(node); - // Reserved words - case SyntaxKind.FalseKeyword: - case SyntaxKind.NullKeyword: - case SyntaxKind.SuperKeyword: - case SyntaxKind.TrueKeyword: - case SyntaxKind.ThisKeyword: - case SyntaxKind.ImportKeyword: - writeTokenNode(node, writeKeyword); - return; - // Expressions case SyntaxKind.ArrayLiteralExpression: return emitArrayLiteralExpression(node); @@ -1693,7 +1723,7 @@ namespace ts { case SyntaxKind.YieldExpression: return emitYieldExpression(node); case SyntaxKind.SpreadElement: - return emitSpreadExpression(node); + return emitSpreadElement(node); case SyntaxKind.ClassExpression: return emitClassExpression(node); case SyntaxKind.OmittedExpression: @@ -1704,6 +1734,8 @@ namespace ts { return emitNonNullExpression(node); case SyntaxKind.MetaProperty: return emitMetaProperty(node); + case SyntaxKind.SyntheticExpression: + return Debug.fail("SyntheticExpression should never be printed."); // JSX case SyntaxKind.JsxElement: @@ -1713,14 +1745,27 @@ namespace ts { case SyntaxKind.JsxFragment: return emitJsxFragment(node); + // Synthesized list + case SyntaxKind.SyntaxList: + return Debug.fail("SyntaxList should not be printed"); + // Transformation nodes + case SyntaxKind.NotEmittedStatement: + return; case SyntaxKind.PartiallyEmittedExpression: return emitPartiallyEmittedExpression(node); - case SyntaxKind.CommaListExpression: return emitCommaList(node); + case SyntaxKind.MergeDeclarationMarker: + case SyntaxKind.EndOfDeclarationMarker: + return; + case SyntaxKind.SyntheticReferenceExpression: + return Debug.fail("SyntheticReferenceExpression should not be printed"); } } + if (isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); + if (isTokenKind(node.kind)) return writeTokenNode(node, writePunctuation); + Debug.fail(`Unhandled SyntaxKind: ${Debug.formatSyntaxKind(node.kind)}.`); } function emitMappedTypeParameter(node: TypeParameterDeclaration): void { @@ -1732,10 +1777,11 @@ namespace ts { } function pipelineEmitWithSubstitution(hint: EmitHint, node: Node) { - Debug.assert(lastNode === node || lastSubstitution === node); const pipelinePhase = getNextPipelinePhase(PipelinePhase.Substitution, hint, node); - pipelinePhase(hint, lastSubstitution!); - Debug.assert(lastNode === node || lastSubstitution === node); + Debug.assertIsDefined(lastSubstitution); + node = lastSubstitution; + lastSubstitution = undefined; + pipelinePhase(hint, node); } function getHelpersFromBundledSourceFiles(bundle: Bundle): string[] | undefined { @@ -1926,7 +1972,7 @@ namespace ts { function emitComputedPropertyName(node: ComputedPropertyName) { writePunctuation("["); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName); writePunctuation("]"); } @@ -1963,12 +2009,12 @@ namespace ts { emitTypeAnnotation(node.type); } // The comment position has to fallback to any present node within the parameterdeclaration because as it turns out, the parser can make parameter declarations with _just_ an initializer. - emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name ? node.name.end : node.modifiers ? node.modifiers.end : node.decorators ? node.decorators.end : node.pos, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitDecorator(decorator: Decorator) { writePunctuation("@"); - emitExpression(decorator.expression); + emitExpression(decorator.expression, parenthesizer.parenthesizeLeftSideOfAccess); } // @@ -2158,7 +2204,7 @@ namespace ts { } function emitArrayType(node: ArrayTypeNode) { - emit(node.elementType); + emit(node.elementType, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("["); writePunctuation("]"); } @@ -2185,24 +2231,24 @@ namespace ts { } function emitOptionalType(node: OptionalTypeNode) { - emit(node.type); + emit(node.type, parenthesizer.parenthesizeElementTypeOfArrayType); writePunctuation("?"); } function emitUnionType(node: UnionTypeNode) { - emitList(node, node.types, ListFormat.UnionTypeConstituents); + emitList(node, node.types, ListFormat.UnionTypeConstituents, parenthesizer.parenthesizeMemberOfElementType); } function emitIntersectionType(node: IntersectionTypeNode) { - emitList(node, node.types, ListFormat.IntersectionTypeConstituents); + emitList(node, node.types, ListFormat.IntersectionTypeConstituents, parenthesizer.parenthesizeMemberOfElementType); } function emitConditionalType(node: ConditionalTypeNode) { - emit(node.checkType); + emit(node.checkType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writeKeyword("extends"); writeSpace(); - emit(node.extendsType); + emit(node.extendsType, parenthesizer.parenthesizeMemberOfConditionalType); writeSpace(); writePunctuation("?"); writeSpace(); @@ -2232,11 +2278,11 @@ namespace ts { function emitTypeOperator(node: TypeOperatorNode) { writeTokenText(node.operator, writeKeyword); writeSpace(); - emit(node.type); + emit(node.type, parenthesizer.parenthesizeMemberOfElementType); } function emitIndexedAccessType(node: IndexedAccessTypeNode) { - emit(node.objectType); + emit(node.objectType, parenthesizer.parenthesizeMemberOfElementType); writePunctuation("["); emit(node.indexType); writePunctuation("]"); @@ -2339,7 +2385,7 @@ namespace ts { writeSpace(); } emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // @@ -2349,7 +2395,7 @@ namespace ts { function emitArrayLiteralExpression(node: ArrayLiteralExpression) { const elements = node.elements; const preferNewLine = node.multiLine ? ListFormat.PreferNewLine : ListFormat.None; - emitExpressionList(node, elements, ListFormat.ArrayLiteralExpressionElements | preferNewLine); + emitExpressionList(node, elements, ListFormat.ArrayLiteralExpressionElements | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitObjectLiteralExpression(node: ObjectLiteralExpression) { @@ -2370,7 +2416,7 @@ namespace ts { } function emitPropertyAccessExpression(node: PropertyAccessExpression) { - const expression = cast(emitExpression(node.expression), isExpression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); const token = node.questionDotToken || setTextRangePosEnd(factory.createToken(SyntaxKind.DotToken) as DotToken, node.expression.end, node.name.pos); const linesBeforeDot = getLinesBetweenNodes(node, node.expression, token); const linesAfterDot = getLinesBetweenNodes(node, token, node.name); @@ -2379,7 +2425,7 @@ namespace ts { const shouldEmitDotDot = token.kind !== SyntaxKind.QuestionDotToken && - mayNeedDotDotForPropertyAccess(expression) && + mayNeedDotDotForPropertyAccess(node.expression) && !writer.hasTrailingComment() && !writer.hasTrailingWhitespace(); @@ -2419,7 +2465,7 @@ namespace ts { } function emitElementAccessExpression(node: ElementAccessExpression) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTokenWithComment(SyntaxKind.OpenBracketToken, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); @@ -2427,22 +2473,22 @@ namespace ts { } function emitCallExpression(node: CallExpression) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emit(node.questionDotToken); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, ListFormat.CallExpressionArguments); + emitExpressionList(node, node.arguments, ListFormat.CallExpressionArguments, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitNewExpression(node: NewExpression) { emitTokenWithComment(SyntaxKind.NewKeyword, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfNew); emitTypeArguments(node, node.typeArguments); - emitExpressionList(node, node.arguments, ListFormat.NewExpressionArguments); + emitExpressionList(node, node.arguments, ListFormat.NewExpressionArguments, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitTaggedTemplateExpression(node: TaggedTemplateExpression) { - emitExpression(node.tag); + emitExpression(node.tag, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); writeSpace(); emitExpression(node.template); @@ -2452,13 +2498,13 @@ namespace ts { writePunctuation("<"); emit(node.type); writePunctuation(">"); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitParenthesizedExpression(node: ParenthesizedExpression) { const openParenPos = emitTokenWithComment(SyntaxKind.OpenParenToken, node.pos, writePunctuation, node); const indented = writeLineSeparatorsAndIndentBefore(node.expression, node); - emitExpression(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); writeLineSeparatorsAfter(node.expression, node); decreaseIndentIf(indented); emitTokenWithComment(SyntaxKind.CloseParenToken, node.expression ? node.expression.end : openParenPos, writePunctuation, node); @@ -2486,25 +2532,25 @@ namespace ts { function emitDeleteExpression(node: DeleteExpression) { emitTokenWithComment(SyntaxKind.DeleteKeyword, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitTypeOfExpression(node: TypeOfExpression) { emitTokenWithComment(SyntaxKind.TypeOfKeyword, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitVoidExpression(node: VoidExpression) { emitTokenWithComment(SyntaxKind.VoidKeyword, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitAwaitExpression(node: AwaitExpression) { emitTokenWithComment(SyntaxKind.AwaitKeyword, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeOperandOfPrefixUnary); } function emitPrefixUnaryExpression(node: PrefixUnaryExpression) { @@ -2512,7 +2558,7 @@ namespace ts { if (shouldEmitWhitespaceBeforeOperand(node)) { writeSpace(); } - emitExpression(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPrefixUnary); } function shouldEmitWhitespaceBeforeOperand(node: PrefixUnaryExpression) { @@ -2535,87 +2581,112 @@ namespace ts { } function emitPostfixUnaryExpression(node: PostfixUnaryExpression) { - emitExpression(node.operand); + emitExpression(node.operand, parenthesizer.parenthesizeOperandOfPostfixUnary); writeTokenText(node.operator, writeOperator); } - const enum EmitBinaryExpressionState { - EmitLeft, - EmitRight, - FinishEmit - } - - /** - * emitBinaryExpression includes an embedded work stack to attempt to handle as many nested binary expressions - * as possible without creating any additional stack frames. This can only be done when the emit pipeline does - * not require notification/substitution/comment/sourcemap decorations. - */ - function emitBinaryExpression(node: BinaryExpression) { - const nodeStack = [node]; - const stateStack = [EmitBinaryExpressionState.EmitLeft]; - let stackIndex = 0; - while (stackIndex >= 0) { - node = nodeStack[stackIndex]; - switch (stateStack[stackIndex]) { - case EmitBinaryExpressionState.EmitLeft: { - maybePipelineEmitExpression(node.left); - break; - } - case EmitBinaryExpressionState.EmitRight: { - const isCommaOperator = node.operatorToken.kind !== SyntaxKind.CommaToken; - const linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); - const linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); - writeLinesAndIndent(linesBeforeOperator, isCommaOperator); - emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken, node.operatorToken.kind === SyntaxKind.InKeyword ? writeKeyword : writeOperator); - emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts - writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); - maybePipelineEmitExpression(node.right); - break; - } - case EmitBinaryExpressionState.FinishEmit: { - const linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); - const linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); - decreaseIndentIf(linesBeforeOperator, linesAfterOperator); - stackIndex--; - break; - } - default: return Debug.fail(`Invalid state ${stateStack[stackIndex]} for emitBinaryExpressionWorker`); + function createEmitBinaryExpression() { + interface WorkArea { + stackIndex: number; + preserveSourceNewlinesStack: (boolean | undefined)[]; + containerPosStack: number[]; + containerEndStack: number[]; + declarationListContainerEndStack: number[]; + shouldEmitCommentsStack: boolean[]; + shouldEmitSourceMapsStack: boolean[]; + } + + return createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, /*foldState*/ undefined); + + function onEnter(node: BinaryExpression, state: WorkArea | undefined) { + if (state) { + state.stackIndex++; + state.preserveSourceNewlinesStack[state.stackIndex] = preserveSourceNewlines; + state.containerPosStack[state.stackIndex] = containerPos; + state.containerEndStack[state.stackIndex] = containerEnd; + state.declarationListContainerEndStack[state.stackIndex] = declarationListContainerEnd; + const emitComments = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node); + const emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node); + onBeforeEmitNode?.(node); + if (emitComments) emitCommentsBeforeNode(node); + if (emitSourceMaps) emitSourceMapsBeforeNode(node); + beforeEmitNode(node); + } + else { + state = { + stackIndex: 0, + preserveSourceNewlinesStack: [undefined], + containerPosStack: [-1], + containerEndStack: [-1], + declarationListContainerEndStack: [-1], + shouldEmitCommentsStack: [false], + shouldEmitSourceMapsStack: [false], + }; + } + return state; + } + + function onLeft(next: Expression, _workArea: WorkArea, parent: BinaryExpression) { + return maybeEmitExpression(next, parent, "left"); + } + + function onOperator(operatorToken: BinaryOperatorToken, _state: WorkArea, node: BinaryExpression) { + const isCommaOperator = operatorToken.kind !== SyntaxKind.CommaToken; + const linesBeforeOperator = getLinesBetweenNodes(node, node.left, operatorToken); + const linesAfterOperator = getLinesBetweenNodes(node, operatorToken, node.right); + writeLinesAndIndent(linesBeforeOperator, isCommaOperator); + emitLeadingCommentsOfPosition(operatorToken.pos); + writeTokenNode(operatorToken, operatorToken.kind === SyntaxKind.InKeyword ? writeKeyword : writeOperator); + emitTrailingCommentsOfPosition(operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts + writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); + } + + function onRight(next: Expression, _workArea: WorkArea, parent: BinaryExpression) { + return maybeEmitExpression(next, parent, "right"); + } + + function onExit(node: BinaryExpression, state: WorkArea) { + const linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); + const linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); + decreaseIndentIf(linesBeforeOperator, linesAfterOperator); + if (state.stackIndex > 0) { + const savedPreserveSourceNewlines = state.preserveSourceNewlinesStack[state.stackIndex]; + const savedContainerPos = state.containerPosStack[state.stackIndex]; + const savedContainerEnd = state.containerEndStack[state.stackIndex]; + const savedDeclarationListContainerEnd = state.declarationListContainerEndStack[state.stackIndex]; + const shouldEmitComments = state.shouldEmitCommentsStack[state.stackIndex]; + const shouldEmitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex]; + afterEmitNode(savedPreserveSourceNewlines); + if (shouldEmitSourceMaps) emitSourceMapsAfterNode(node); + if (shouldEmitComments) emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + onAfterEmitNode?.(node); + state.stackIndex--; } } - function maybePipelineEmitExpression(next: Expression) { - // Advance the state of this unit of work, - stateStack[stackIndex]++; - - // Then actually do the work of emitting the node `next` returned by the prior state + function maybeEmitExpression(next: Expression, parent: BinaryExpression, side: "left" | "right") { + const parenthesizerRule = side === "left" ? + parenthesizer.getParenthesizeLeftSideOfBinaryForOperator(parent.operatorToken.kind) : + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(parent.operatorToken.kind); - // The following section should be identical to `pipelineEmit` save it assumes EmitHint.Expression and offloads - // binary expression handling, where possible, to the contained work queue - - // #region trampolinePipelineEmit - const savedLastNode = lastNode; - const savedLastSubstitution = lastSubstitution; - lastNode = next; - lastSubstitution = undefined; - - const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, EmitHint.Expression, next); - if (pipelinePhase === pipelineEmitWithHint && isBinaryExpression(next)) { - // If the target pipeline phase is emit directly, and the next node's also a binary expression, - // skip all the intermediate indirection and push the expression directly onto the work stack - stackIndex++; - stateStack[stackIndex] = EmitBinaryExpressionState.EmitLeft; - nodeStack[stackIndex] = next; - } - else { - pipelinePhase(EmitHint.Expression, next); + let pipelinePhase = getPipelinePhase(PipelinePhase.Notification, EmitHint.Expression, next); + if (pipelinePhase === pipelineEmitWithSubstitution) { + Debug.assertIsDefined(lastSubstitution); + next = parenthesizerRule(cast(lastSubstitution, isExpression)); + pipelinePhase = getNextPipelinePhase(PipelinePhase.Substitution, EmitHint.Expression, next); + lastSubstitution = undefined; } - Debug.assert(lastNode === next); + if (pipelinePhase === pipelineEmitWithComments || + pipelinePhase === pipelineEmitWithSourceMaps || + pipelinePhase === pipelineEmitWithHint) { + if (isBinaryExpression(next)) { + return next; + } + } - lastNode = savedLastNode; - lastSubstitution = savedLastSubstitution; - // #endregion trampolinePipelineEmit + currentParenthesizerRule = parenthesizerRule; + pipelinePhase(EmitHint.Expression, next); } } @@ -2625,17 +2696,17 @@ namespace ts { const linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken); const linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse); - emitExpression(node.condition); + emitExpression(node.condition, parenthesizer.parenthesizeConditionOfConditionalExpression); writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); emit(node.questionToken); writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true); - emitExpression(node.whenTrue); + emitExpression(node.whenTrue, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion); writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true); emit(node.colonToken); writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true); - emitExpression(node.whenFalse); + emitExpression(node.whenFalse, parenthesizer.parenthesizeBranchOfConditionalExpression); decreaseIndentIf(linesBeforeColon, linesAfterColon); } @@ -2647,12 +2718,12 @@ namespace ts { function emitYieldExpression(node: YieldExpression) { emitTokenWithComment(SyntaxKind.YieldKeyword, node.pos, writeKeyword, node); emit(node.asteriskToken); - emitExpressionWithLeadingSpace(node.expression); + emitExpressionWithLeadingSpace(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } - function emitSpreadExpression(node: SpreadElement) { + function emitSpreadElement(node: SpreadElement) { emitTokenWithComment(SyntaxKind.DotDotDotToken, node.pos, writePunctuation, node); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitClassExpression(node: ClassExpression) { @@ -2661,12 +2732,12 @@ namespace ts { } function emitExpressionWithTypeArguments(node: ExpressionWithTypeArguments) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); emitTypeArguments(node, node.typeArguments); } function emitAsExpression(node: AsExpression) { - emitExpression(node.expression); + emitExpression(node.expression, /*parenthesizerRules*/ undefined); if (node.type) { writeSpace(); writeKeyword("as"); @@ -2676,7 +2747,7 @@ namespace ts { } function emitNonNullExpression(node: NonNullExpression) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); writeOperator("!"); } @@ -2727,9 +2798,8 @@ namespace ts { } } - function emitExpressionStatement(node: ExpressionStatement) { - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfExpressionStatement); // Emit semicolon in non json files // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) if (!isJsonSourceFile(currentSourceFile!) || nodeIsSynthesized(node.expression)) { @@ -2939,7 +3009,7 @@ namespace ts { emit(node.name); emit(node.exclamationToken); emitTypeAnnotation(node.type); - emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); + emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitVariableDeclarationList(node: VariableDeclarationList) { @@ -2962,10 +3032,6 @@ namespace ts { emitSignatureAndBody(node, emitSignatureHead); } - function emitBlockCallback(_hint: EmitHint, body: Node): void { - emitBlockFunctionBody(body); - } - function emitSignatureAndBody(node: FunctionLikeDeclaration, emitSignatureHead: (node: SignatureDeclaration) => void) { const body = node.body; if (body) { @@ -2980,12 +3046,7 @@ namespace ts { generateNames(node.body); emitSignatureHead(node); - if (onEmitNode) { - onEmitNode(EmitHint.Unspecified, body, emitBlockCallback); - } - else { - emitBlockFunctionBody(body); - } + emitBlockFunctionBody(body); popNameGenerationScope(node); if (indentedFlag) { @@ -2995,7 +3056,7 @@ namespace ts { else { emitSignatureHead(node); writeSpace(); - emitExpression(body); + emitExpression(body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); } } else { @@ -3050,6 +3111,7 @@ namespace ts { } function emitBlockFunctionBody(body: Block) { + onBeforeEmitNode?.(body); writeSpace(); writePunctuation("{"); increaseIndent(); @@ -3067,6 +3129,7 @@ namespace ts { decreaseIndent(); writeToken(SyntaxKind.CloseBraceToken, body.statements.end, writePunctuation, body); + onAfterEmitNode?.(body); } function emitBlockFunctionBodyOnSingleLine(body: Block) { @@ -3084,7 +3147,7 @@ namespace ts { increaseIndent(); } else { - emitList(body, body.statements, ListFormat.MultiLineFunctionBodyStatements, statementOffset); + emitList(body, body.statements, ListFormat.MultiLineFunctionBodyStatements, /*parenthesizerRule*/ undefined, statementOffset); } } @@ -3171,10 +3234,10 @@ namespace ts { let body = node.body; if (!body) return writeTrailingSemicolon(); - while (body.kind === SyntaxKind.ModuleDeclaration) { + while (body && isModuleDeclaration(body)) { writePunctuation("."); - emit((body).name); - body = (body).body!; + emit(body.name); + body = body.body; } writeSpace(); @@ -3272,7 +3335,9 @@ namespace ts { emitTokenWithComment(SyntaxKind.DefaultKeyword, nextPos, writeKeyword, node); } writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, node.isExportEquals ? + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(SyntaxKind.EqualsToken) : + parenthesizer.parenthesizeExpressionOfExportDefault); writeTrailingSemicolon(); } @@ -3472,7 +3537,7 @@ namespace ts { function emitCaseClause(node: CaseClause) { emitTokenWithComment(SyntaxKind.CaseKeyword, node.pos, writeKeyword, node); writeSpace(); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end); } @@ -3543,7 +3608,7 @@ namespace ts { const commentRange = getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } - emitExpression(initializer); + emitExpression(initializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitShorthandPropertyAssignment(node: ShorthandPropertyAssignment) { @@ -3552,14 +3617,14 @@ namespace ts { writeSpace(); writePunctuation("="); writeSpace(); - emitExpression(node.objectAssignmentInitializer); + emitExpression(node.objectAssignmentInitializer, parenthesizer.parenthesizeExpressionForDisallowedComma); } } function emitSpreadAssignment(node: SpreadAssignment) { if (node.expression) { emitTokenWithComment(SyntaxKind.DotDotDotToken, node.pos, writePunctuation, node); - emitExpression(node.expression); + emitExpression(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); } } @@ -3569,7 +3634,7 @@ namespace ts { function emitEnumMember(node: EnumMember) { emit(node.name); - emitInitializer(node.initializer, node.name.end, node); + emitInitializer(node.initializer, node.name.end, node, parenthesizer.parenthesizeExpressionForDisallowedComma); } // @@ -3578,13 +3643,16 @@ namespace ts { function emitJSDoc(node: JSDoc) { write("/**"); if (node.comment) { - const lines = node.comment.split(/\r\n?|\n/g); - for (const line of lines) { - writeLine(); - writeSpace(); - writePunctuation("*"); - writeSpace(); - write(line); + const text = getTextOfJSDocComment(node.comment); + if (text) { + const lines = text.split(/\r\n?|\n/g); + for (const line of lines) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } } } if (node.tags) { @@ -3717,10 +3785,11 @@ namespace ts { emit(tagName); } - function emitJSDocComment(comment: string | undefined) { - if (comment) { + function emitJSDocComment(comment: string | NodeArray | undefined) { + const text = getTextOfJSDocComment(comment); + if (text) { writeSpace(); - write(comment); + write(text); } } @@ -3819,7 +3888,7 @@ namespace ts { emitHelpers(node); const index = findIndex(statements, statement => !isPrologueDirective(statement)); emitTripleSlashDirectivesIfNeeded(node); - emitList(node, statements, ListFormat.MultiLine, index === -1 ? statements.length : index); + emitList(node, statements, ListFormat.MultiLine, /*parenthesizerRule*/ undefined, index === -1 ? statements.length : index); popNameGenerationScope(node); } @@ -3830,7 +3899,7 @@ namespace ts { } function emitCommaList(node: CommaListExpression) { - emitExpressionList(node, node.elements, ListFormat.CommaListElements); + emitExpressionList(node, node.elements, ListFormat.CommaListElements, /*parenthesizerRule*/ undefined); } /** @@ -3975,12 +4044,12 @@ namespace ts { } } - function emitInitializer(node: Expression | undefined, equalCommentStartPos: number, container: Node) { + function emitInitializer(node: Expression | undefined, equalCommentStartPos: number, container: Node, parenthesizerRule?: (node: Expression) => Expression) { if (node) { writeSpace(); emitTokenWithComment(SyntaxKind.EqualsToken, equalCommentStartPos, writeOperator, container); writeSpace(); - emitExpression(node); + emitExpression(node, parenthesizerRule); } } @@ -3998,10 +4067,10 @@ namespace ts { } } - function emitExpressionWithLeadingSpace(node: Expression | undefined) { + function emitExpressionWithLeadingSpace(node: Expression | undefined, parenthesizerRule?: (node: Expression) => Expression) { if (node) { writeSpace(); - emitExpression(node); + emitExpression(node, parenthesizerRule); } } @@ -4035,7 +4104,7 @@ namespace ts { } function emitTypeArguments(parentNode: Node, typeArguments: NodeArray | undefined) { - emitList(parentNode, typeArguments, ListFormat.TypeArguments); + emitList(parentNode, typeArguments, ListFormat.TypeArguments, parenthesizer.parenthesizeMemberOfElementType); } function emitTypeParameters(parentNode: SignatureDeclaration | InterfaceDeclaration | TypeAliasDeclaration | ClassDeclaration | ClassExpression, typeParameters: NodeArray | undefined) { @@ -4080,14 +4149,6 @@ namespace ts { emitList(parentNode, parameters, ListFormat.IndexSignatureParameters); } - function emitList(parentNode: TextRange, children: NodeArray | undefined, format: ListFormat, start?: number, count?: number) { - emitNodeList(emit, parentNode, children, format, start, count); - } - - function emitExpressionList(parentNode: TextRange, children: NodeArray | undefined, format: ListFormat, start?: number, count?: number) { - emitNodeList(emitExpression as (node: Node) => void, parentNode, children, format, start, count); // TODO: GH#18217 - } - function writeDelimiter(format: ListFormat) { switch (format & ListFormat.DelimitersMask) { case ListFormat.None: @@ -4111,7 +4172,15 @@ namespace ts { } } - function emitNodeList(emit: (node: Node) => void, parentNode: TextRange, children: NodeArray | undefined, format: ListFormat, start = 0, count = children ? children.length - start : 0) { + function emitList(parentNode: Node | undefined, children: NodeArray | undefined, format: ListFormat, parenthesizerRule?: (node: Node) => Node, start?: number, count?: number) { + emitNodeList(emit, parentNode, children, format, parenthesizerRule, start, count); + } + + function emitExpressionList(parentNode: Node | undefined, children: NodeArray | undefined, format: ListFormat, parenthesizerRule?: (node: Expression) => Expression, start?: number, count?: number) { + emitNodeList(emitExpression, parentNode, children, format, parenthesizerRule, start, count); + } + + function emitNodeList(emit: (node: Node, parenthesizerRule?: ((node: Node) => Node) | undefined) => void, parentNode: Node | undefined, children: NodeArray | undefined, format: ListFormat, parenthesizerRule: ((node: Node) => Node) | undefined, start = 0, count = children ? children.length - start : 0) { const isUndefined = children === undefined; if (isUndefined && format & ListFormat.OptionalIfUndefined) { return; @@ -4130,9 +4199,8 @@ namespace ts { if (format & ListFormat.BracketsMask) { writePunctuation(getOpeningBracket(format)); - if (isEmpty && !isUndefined) { - // TODO: GH#18217 - emitTrailingCommentsOfPosition(children!.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists + if (isEmpty && children) { + emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists } } @@ -4142,7 +4210,7 @@ namespace ts { if (isEmpty) { // Write a line terminator if the parent node was multi-line - if (format & ListFormat.MultiLine && !(preserveSourceNewlines && rangeIsOnSingleLine(parentNode, currentSourceFile!))) { + if (format & ListFormat.MultiLine && !(preserveSourceNewlines && (!parentNode || rangeIsOnSingleLine(parentNode, currentSourceFile!)))) { writeLine(); } else if (format & ListFormat.SpaceBetweenBraces && !(format & ListFormat.NoSpaceIfEmpty)) { @@ -4150,10 +4218,11 @@ namespace ts { } } else { + Debug.type>(children); // Write the opening line terminator or leading whitespace. const mayEmitInterveningComments = (format & ListFormat.NoInterveningComments) === 0; let shouldEmitInterveningComments = mayEmitInterveningComments; - const leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children!, format); // TODO: GH#18217 + const leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217 if (leadingLineTerminatorCount) { writeLine(leadingLineTerminatorCount); shouldEmitInterveningComments = false; @@ -4172,7 +4241,7 @@ namespace ts { let previousSourceFileTextKind: ReturnType; let shouldDecreaseIndentAfterEmit = false; for (let i = 0; i < count; i++) { - const child = children![start + i]; + const child = children[start + i]; // Write the delimiter if this is not the first node. if (format & ListFormat.AsteriskDelimited) { @@ -4187,7 +4256,7 @@ namespace ts { // a // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline // , - if (format & ListFormat.DelimitersMask && previousSibling.end !== parentNode.end) { + if (format & ListFormat.DelimitersMask && previousSibling.end !== (parentNode ? parentNode.end : -1)) { emitLeadingCommentsOfPosition(previousSibling.end); } writeDelimiter(format); @@ -4224,7 +4293,12 @@ namespace ts { } nextListElementPos = child.pos; - emit(child); + if (emit.length === 1) { + emit(child); + } + else { + emit(child, parenthesizerRule); + } if (shouldDecreaseIndentAfterEmit) { decreaseIndent(); @@ -4253,7 +4327,7 @@ namespace ts { // 2 // /* end of element 2 */ // ]; - if (previousSibling && parentNode.end !== previousSibling.end && (format & ListFormat.DelimitersMask) && !skipTrailingComments) { + if (previousSibling && (parentNode ? parentNode.end : -1) !== previousSibling.end && (format & ListFormat.DelimitersMask) && !skipTrailingComments) { emitLeadingCommentsOfPosition(hasTrailingComma && children?.end ? children.end : previousSibling.end); } @@ -4265,7 +4339,7 @@ namespace ts { recordBundleFileInternalSectionEnd(previousSourceFileTextKind); // Write the closing line terminator or closing whitespace. - const closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children!, format); + const closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format); if (closingLineTerminatorCount) { writeLine(closingLineTerminatorCount); } @@ -4279,9 +4353,8 @@ namespace ts { } if (format & ListFormat.BracketsMask) { - if (isEmpty && !isUndefined) { - // TODO: GH#18217 - emitLeadingCommentsOfPosition(children!.end); // Emit leading comments within empty lists + if (isEmpty && children) { + emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists } writePunctuation(getClosingBracket(format)); } @@ -4428,7 +4501,7 @@ namespace ts { } } - function getLeadingLineTerminatorCount(parentNode: TextRange, children: readonly Node[], format: ListFormat): number { + function getLeadingLineTerminatorCount(parentNode: Node | undefined, children: readonly Node[], format: ListFormat): number { if (format & ListFormat.PreserveLines || preserveSourceNewlines) { if (format & ListFormat.PreferNewLine) { return 1; @@ -4436,7 +4509,7 @@ namespace ts { const firstChild = children[0]; if (firstChild === undefined) { - return rangeIsOnSingleLine(parentNode, currentSourceFile!) ? 0 : 1; + return !parentNode || rangeIsOnSingleLine(parentNode, currentSourceFile!) ? 0 : 1; } if (firstChild.pos === nextListElementPos) { // If this child starts at the beginning of a list item in a parent list, its leading @@ -4460,9 +4533,10 @@ namespace ts { // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } - if (!positionIsSynthesized(parentNode.pos) && + if (parentNode && + !positionIsSynthesized(parentNode.pos) && !nodeIsSynthesized(firstChild) && - (!firstChild.parent || getOriginalNode(firstChild.parent) === getOriginalNode(parentNode as Node)) + (!firstChild.parent || getOriginalNode(firstChild.parent) === getOriginalNode(parentNode)) ) { if (preserveSourceNewlines) { return getEffectiveLines( @@ -4490,15 +4564,15 @@ namespace ts { // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } - else if (!nodeIsSynthesized(previousNode) && !nodeIsSynthesized(nextNode) && previousNode.parent === nextNode.parent) { - if (preserveSourceNewlines) { - return getEffectiveLines( - includeComments => getLinesBetweenRangeEndAndRangeStart( - previousNode, - nextNode, - currentSourceFile!, - includeComments)); - } + else if (preserveSourceNewlines && siblingNodePositionsAreComparable(previousNode, nextNode)) { + return getEffectiveLines( + includeComments => getLinesBetweenRangeEndAndRangeStart( + previousNode, + nextNode, + currentSourceFile!, + includeComments)); + } + else if (!preserveSourceNewlines && !nodeIsSynthesized(previousNode) && !nodeIsSynthesized(nextNode)) { return rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile!) ? 0 : 1; } else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) { @@ -4511,7 +4585,7 @@ namespace ts { return format & ListFormat.MultiLine ? 1 : 0; } - function getClosingLineTerminatorCount(parentNode: TextRange, children: readonly Node[], format: ListFormat): number { + function getClosingLineTerminatorCount(parentNode: Node | undefined, children: readonly Node[], format: ListFormat): number { if (format & ListFormat.PreserveLines || preserveSourceNewlines) { if (format & ListFormat.PreferNewLine) { return 1; @@ -4519,9 +4593,9 @@ namespace ts { const lastChild = lastOrUndefined(children); if (lastChild === undefined) { - return rangeIsOnSingleLine(parentNode, currentSourceFile!) ? 0 : 1; + return !parentNode || rangeIsOnSingleLine(parentNode, currentSourceFile!) ? 0 : 1; } - if (!positionIsSynthesized(parentNode.pos) && !nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { + if (parentNode && !positionIsSynthesized(parentNode.pos) && !nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) { if (preserveSourceNewlines) { const end = isNodeArray(children) && !positionIsSynthesized(children.end) ? children.end : lastChild.end; return getEffectiveLines( @@ -5073,12 +5147,40 @@ namespace ts { // Comments function pipelineEmitWithComments(hint: EmitHint, node: Node) { - Debug.assert(lastNode === node || lastSubstitution === node); + const pipelinePhase = getNextPipelinePhase(PipelinePhase.Comments, hint, node); + const savedContainerPos = containerPos; + const savedContainerEnd = containerEnd; + const savedDeclarationListContainerEnd = declarationListContainerEnd; + emitCommentsBeforeNode(node); + pipelinePhase(hint, node); + emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + + function emitCommentsBeforeNode(node: Node) { + const emitFlags = getEmitFlags(node); + const commentRange = getCommentRange(node); + + // Emit leading comments + emitLeadingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end); + if (emitFlags & EmitFlags.NoNestedComments) { + commentsDisabled = true; + } + } + + function emitCommentsAfterNode(node: Node, savedContainerPos: number, savedContainerEnd: number, savedDeclarationListContainerEnd: number) { + const emitFlags = getEmitFlags(node); + const commentRange = getCommentRange(node); + + // Emit trailing comments + if (emitFlags & EmitFlags.NoNestedComments) { + commentsDisabled = false; + } + emitTrailingCommentsOfNode(node, emitFlags, commentRange.pos, commentRange.end, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + } + + function emitLeadingCommentsOfNode(node: Node, emitFlags: EmitFlags, pos: number, end: number) { enterComment(); hasWrittenComment = false; - const emitFlags = getEmitFlags(node); - const { pos, end } = getCommentRange(node); - const isEmittedNode = node.kind !== SyntaxKind.NotEmittedStatement; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. @@ -5086,14 +5188,11 @@ namespace ts { const skipTrailingComments = end < 0 || (emitFlags & EmitFlags.NoTrailingComments) !== 0 || node.kind === SyntaxKind.JsxText; // Save current container state on the stack. - const savedContainerPos = containerPos; - const savedContainerEnd = containerEnd; - const savedDeclarationListContainerEnd = declarationListContainerEnd; if ((pos > 0 || end > 0) && pos !== end) { // Emit leading comments if the position is not synthesized and the node // has not opted out from emitting leading comments. if (!skipLeadingComments) { - emitLeadingComments(pos, isEmittedNode); + emitLeadingComments(pos, /*isEmittedNode*/ node.kind !== SyntaxKind.NotEmittedStatement); } if (!skipLeadingComments || (pos >= 0 && (emitFlags & EmitFlags.NoLeadingComments) !== 0)) { @@ -5114,18 +5213,11 @@ namespace ts { } forEach(getSyntheticLeadingComments(node), emitLeadingSynthesizedComment); exitComment(); + } - const pipelinePhase = getNextPipelinePhase(PipelinePhase.Comments, hint, node); - if (emitFlags & EmitFlags.NoNestedComments) { - commentsDisabled = true; - pipelinePhase(hint, node); - commentsDisabled = false; - } - else { - pipelinePhase(hint, node); - } - + function emitTrailingCommentsOfNode(node: Node, emitFlags: EmitFlags, pos: number, end: number, savedContainerPos: number, savedContainerEnd: number, savedDeclarationListContainerEnd: number) { enterComment(); + const skipTrailingComments = end < 0 || (emitFlags & EmitFlags.NoTrailingComments) !== 0 || node.kind === SyntaxKind.JsxText; forEach(getSyntheticTrailingComments(node), emitTrailingSynthesizedComment); if ((pos > 0 || end > 0) && pos !== end) { // Restore previous container state. @@ -5135,12 +5227,11 @@ namespace ts { // Emit trailing comments if the position is not synthesized and the node // has not opted out from emitting leading comments and is an emitted node. - if (!skipTrailingComments && isEmittedNode) { + if (!skipTrailingComments && node.kind !== SyntaxKind.NotEmittedStatement) { emitTrailingComments(end); } } exitComment(); - Debug.assert(lastNode === node || lastSubstitution === node); } function emitLeadingSynthesizedComment(comment: SynthesizedComment) { @@ -5209,6 +5300,27 @@ namespace ts { } + function siblingNodePositionsAreComparable(previousNode: Node, nextNode: Node) { + if (nodeIsSynthesized(previousNode) || nodeIsSynthesized(nextNode)) { + return false; + } + + if (nextNode.pos < previousNode.end) { + return false; + } + + previousNode = getOriginalNode(previousNode); + nextNode = getOriginalNode(nextNode); + const parent = previousNode.parent; + if (!parent || parent !== nextNode.parent) { + return false; + } + + const parentNodeArray = getContainingNodeArray(previousNode); + const prevNodeIndex = parentNodeArray?.indexOf(previousNode); + return prevNodeIndex !== undefined && prevNodeIndex > -1 && parentNodeArray!.indexOf(nextNode) === prevNodeIndex + 1; + } + function emitLeadingComments(pos: number, isEmittedNode: boolean) { hasWrittenComment = false; @@ -5409,13 +5521,20 @@ namespace ts { return node.parsedSourceMap || undefined; } - function pipelineEmitWithSourceMap(hint: EmitHint, node: Node) { - Debug.assert(lastNode === node || lastSubstitution === node); + function pipelineEmitWithSourceMaps(hint: EmitHint, node: Node) { const pipelinePhase = getNextPipelinePhase(PipelinePhase.SourceMaps, hint, node); - if (isUnparsedSource(node) || isUnparsedPrepend(node)) { - pipelinePhase(hint, node); - } - else if (isUnparsedNode(node)) { + emitSourceMapsBeforeNode(node); + pipelinePhase(hint, node); + emitSourceMapsAfterNode(node); + } + + function emitSourceMapsBeforeNode(node: Node) { + const emitFlags = getEmitFlags(node); + const sourceMapRange = getSourceMapRange(node); + + // Emit leading sourcemap + if (isUnparsedNode(node)) { + Debug.assertIsDefined(node.parent, "UnparsedNodes must have parent pointers"); const parsed = getParsedSourceMap(node.parent); if (parsed && sourceMapGenerator) { sourceMapGenerator.appendSourceMap( @@ -5427,33 +5546,35 @@ namespace ts { node.parent.getLineAndCharacterOfPosition(node.end) ); } - pipelinePhase(hint, node); } else { - const { pos, end, source = sourceMapSource } = getSourceMapRange(node); - const emitFlags = getEmitFlags(node); + const source = sourceMapRange.source || sourceMapSource; if (node.kind !== SyntaxKind.NotEmittedStatement && (emitFlags & EmitFlags.NoLeadingSourceMap) === 0 - && pos >= 0) { - emitSourcePos(source, skipSourceTrivia(source, pos)); + && sourceMapRange.pos >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); } - if (emitFlags & EmitFlags.NoNestedSourceMaps) { sourceMapsDisabled = true; - pipelinePhase(hint, node); - sourceMapsDisabled = false; - } - else { - pipelinePhase(hint, node); } + } + } + + function emitSourceMapsAfterNode(node: Node) { + const emitFlags = getEmitFlags(node); + const sourceMapRange = getSourceMapRange(node); + // Emit trailing sourcemap + if (!isUnparsedNode(node)) { + if (emitFlags & EmitFlags.NoNestedSourceMaps) { + sourceMapsDisabled = false; + } if (node.kind !== SyntaxKind.NotEmittedStatement && (emitFlags & EmitFlags.NoTrailingSourceMap) === 0 - && end >= 0) { - emitSourcePos(source, end); + && sourceMapRange.end >= 0) { + emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); } } - Debug.assert(lastNode === node || lastSubstitution === node); } /** diff --git a/src/compiler/factory/emitHelpers.ts b/src/compiler/factory/emitHelpers.ts index 4333272616da6..f3e0004efd407 100644 --- a/src/compiler/factory/emitHelpers.ts +++ b/src/compiler/factory/emitHelpers.ts @@ -32,8 +32,8 @@ namespace ts { createImportDefaultHelper(expression: Expression): Expression; createExportStarHelper(moduleExpression: Expression, exportsExpression?: Expression): Expression; // Class Fields Helpers - createClassPrivateFieldGetHelper(receiver: Expression, privateField: Identifier): Expression; - createClassPrivateFieldSetHelper(receiver: Expression, privateField: Identifier, value: Expression): Expression; + createClassPrivateFieldGetHelper(receiver: Expression, state: Identifier, kind: PrivateIdentifierKind, f: Identifier | undefined): Expression; + createClassPrivateFieldSetHelper(receiver: Expression, state: Identifier, value: Expression, kind: PrivateIdentifierKind, f: Identifier | undefined): Expression; } export function createEmitHelperFactory(context: TransformationContext): EmitHelperFactory { @@ -368,15 +368,30 @@ namespace ts { // Class Fields Helpers - function createClassPrivateFieldGetHelper(receiver: Expression, privateField: Identifier) { + function createClassPrivateFieldGetHelper(receiver: Expression, state: Identifier, kind: PrivateIdentifierKind, f: Identifier | undefined) { context.requestEmitHelper(classPrivateFieldGetHelper); - return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ undefined, [receiver, privateField]); + let args; + if (!f) { + args = [receiver, state, factory.createStringLiteral(kind)]; + } + else { + args = [receiver, state, factory.createStringLiteral(kind), f]; + } + return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ undefined, args); } - function createClassPrivateFieldSetHelper(receiver: Expression, privateField: Identifier, value: Expression) { + function createClassPrivateFieldSetHelper(receiver: Expression, state: Identifier, value: Expression, kind: PrivateIdentifierKind, f: Identifier | undefined) { context.requestEmitHelper(classPrivateFieldSetHelper); - return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, [receiver, privateField, value]); + let args; + if (!f) { + args = [receiver, state, value, factory.createStringLiteral(kind)]; + } + else { + args = [receiver, state, value, factory.createStringLiteral(kind), f]; + } + return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, args); } + } /* @internal */ @@ -803,7 +818,6 @@ namespace ts { };` }; - // emit output for the __export helper function export const exportStarHelper: UnscopedEmitHelper = { name: "typescript:export-star", importName: "__exportStar", @@ -816,31 +830,127 @@ namespace ts { };` }; - // Class fields helpers + /** + * Parameters: + * @param receiver — The object from which the private member will be read. + * @param state — One of the following: + * - A WeakMap used to read a private instance field. + * - A WeakSet used as an instance brand for private instance methods and accessors. + * - A function value that should be the undecorated class constructor used to brand check private static fields, methods, and accessors. + * @param kind — (optional pre TS 4.3, required for TS 4.3+) One of the following values: + * - undefined — Indicates a private instance field (pre TS 4.3). + * - "f" — Indicates a private field (instance or static). + * - "m" — Indicates a private method (instance or static). + * - "a" — Indicates a private accessor (instance or static). + * @param f — (optional pre TS 4.3) Depends on the arguments for state and kind: + * - If kind is "m", this should be the function corresponding to the static or instance method. + * - If kind is "a", this should be the function corresponding to the getter method, or undefined if the getter was not defined. + * - If kind is "f" and state is a function, this should be an object holding the value of a static field, or undefined if the static field declaration has not yet been evaluated. + * Usage: + * This helper will only ever be used by the compiler in the following ways: + * + * Reading from a private instance field (pre TS 4.3): + * __classPrivateFieldGet(, ) + * + * Reading from a private instance field (TS 4.3+): + * __classPrivateFieldGet(, , "f") + * + * Reading from a private instance get accessor (when defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", ) + * + * Reading from a private instance get accessor (when not defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Reading from a private instance method (TS 4.3+): + * __classPrivateFieldGet(, , "m", ) + * + * Reading from a private static field (TS 4.3+): + * __classPrivateFieldGet(, , "f", <{ value: any }>) + * + * Reading from a private static get accessor (when defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", ) + * + * Reading from a private static get accessor (when not defined, TS 4.3+): + * __classPrivateFieldGet(, , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Reading from a private static method (TS 4.3+): + * __classPrivateFieldGet(, , "m", ) + */ export const classPrivateFieldGetHelper: UnscopedEmitHelper = { name: "typescript:classPrivateFieldGet", importName: "__classPrivateFieldGet", scoped: false, text: ` - var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); + var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); };` }; + /** + * Parameters: + * @param receiver — The object on which the private member will be set. + * @param state — One of the following: + * - A WeakMap used to store a private instance field. + * - A WeakSet used as an instance brand for private instance methods and accessors. + * - A function value that should be the undecorated class constructor used to brand check private static fields, methods, and accessors. + * @param value — The value to set. + * @param kind — (optional pre TS 4.3, required for TS 4.3+) One of the following values: + * - undefined — Indicates a private instance field (pre TS 4.3). + * - "f" — Indicates a private field (instance or static). + * - "m" — Indicates a private method (instance or static). + * - "a" — Indicates a private accessor (instance or static). + * @param f — (optional pre TS 4.3) Depends on the arguments for state and kind: + * - If kind is "m", this should be the function corresponding to the static or instance method. + * - If kind is "a", this should be the function corresponding to the setter method, or undefined if the setter was not defined. + * - If kind is "f" and state is a function, this should be an object holding the value of a static field, or undefined if the static field declaration has not yet been evaluated. + * Usage: + * This helper will only ever be used by the compiler in the following ways: + * + * Writing to a private instance field (pre TS 4.3): + * __classPrivateFieldSet(, , ) + * + * Writing to a private instance field (TS 4.3+): + * __classPrivateFieldSet(, , , "f") + * + * Writing to a private instance set accessor (when defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", ) + * + * Writing to a private instance set accessor (when not defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Writing to a private instance method (TS 4.3+): + * __classPrivateFieldSet(, , , "m", ) + * NOTE: This always results in a runtime error. + * + * Writing to a private static field (TS 4.3+): + * __classPrivateFieldSet(, , , "f", <{ value: any }>) + * + * Writing to a private static set accessor (when defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", ) + * + * Writing to a private static set accessor (when not defined, TS 4.3+): + * __classPrivateFieldSet(, , , "a", void 0) + * NOTE: This always results in a runtime error. + * + * Writing to a private static method (TS 4.3+): + * __classPrivateFieldSet(, , , "m", ) + * NOTE: This always results in a runtime error. + */ export const classPrivateFieldSetHelper: UnscopedEmitHelper = { name: "typescript:classPrivateFieldSet", importName: "__classPrivateFieldSet", scoped: false, text: ` - var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; + var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; };` }; @@ -897,4 +1007,4 @@ namespace ts { && (getEmitFlags(firstSegment.expression) & EmitFlags.HelperName) && firstSegment.expression.escapedText === helperName; } -} \ No newline at end of file +} diff --git a/src/compiler/factory/nodeFactory.ts b/src/compiler/factory/nodeFactory.ts index 5f3a19a8949ac..0989a504e6e5b 100644 --- a/src/compiler/factory/nodeFactory.ts +++ b/src/compiler/factory/nodeFactory.ts @@ -34,10 +34,10 @@ namespace ts { const getJSDocPrimaryTypeCreateFunction = memoizeOne((kind: T["kind"]) => () => createJSDocPrimaryTypeWorker(kind)); const getJSDocUnaryTypeCreateFunction = memoizeOne((kind: T["kind"]) => (type: T["type"]) => createJSDocUnaryTypeWorker(kind, type)); const getJSDocUnaryTypeUpdateFunction = memoizeOne((kind: T["kind"]) => (node: T, type: T["type"]) => updateJSDocUnaryTypeWorker(kind, node, type)); - const getJSDocSimpleTagCreateFunction = memoizeOne((kind: T["kind"]) => (tagName: Identifier | undefined, comment?: string) => createJSDocSimpleTagWorker(kind, tagName, comment)); - const getJSDocSimpleTagUpdateFunction = memoizeOne((kind: T["kind"]) => (node: T, tagName: Identifier | undefined, comment?: string) => updateJSDocSimpleTagWorker(kind, node, tagName, comment)); - const getJSDocTypeLikeTagCreateFunction = memoizeOne((kind: T["kind"]) => (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string) => createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment)); - const getJSDocTypeLikeTagUpdateFunction = memoizeOne((kind: T["kind"]) => (node: T, tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string) => updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment)); + const getJSDocSimpleTagCreateFunction = memoizeOne((kind: T["kind"]) => (tagName: Identifier | undefined, comment?: NodeArray) => createJSDocSimpleTagWorker(kind, tagName, comment)); + const getJSDocSimpleTagUpdateFunction = memoizeOne((kind: T["kind"]) => (node: T, tagName: Identifier | undefined, comment?: NodeArray) => updateJSDocSimpleTagWorker(kind, node, tagName, comment)); + const getJSDocTypeLikeTagCreateFunction = memoizeOne((kind: T["kind"]) => (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: NodeArray) => createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment)); + const getJSDocTypeLikeTagUpdateFunction = memoizeOne((kind: T["kind"]) => (node: T, tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: NodeArray) => updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment)); const factory: NodeFactory = { get parenthesizer() { return parenthesizerRules(); }, @@ -345,6 +345,8 @@ namespace ts { updateJSDocSeeTag, createJSDocNameReference, updateJSDocNameReference, + createJSDocLink, + updateJSDocLink, // lazily load factory members for JSDoc tags with similar structure get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(SyntaxKind.JSDocTypeTag); }, get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(SyntaxKind.JSDocTypeTag); }, @@ -366,10 +368,14 @@ namespace ts { get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocProtectedTag); }, get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocReadonlyTag); }, get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocReadonlyTag); }, + get createJSDocOverrideTag() { return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocOverrideTag); }, + get updateJSDocOverrideTag() { return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocOverrideTag); }, get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocDeprecatedTag); }, get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocDeprecatedTag); }, createJSDocUnknownTag, updateJSDocUnknownTag, + createJSDocText, + updateJSDocText, createJSDocComment, updateJSDocComment, createJsxElement, @@ -551,9 +557,9 @@ namespace ts { // NOTE: The following properties are commonly set by the binder and are added here to // ensure declarations have a stable shape. node.symbol = undefined!; // initialized by binder - node.localSymbol = undefined!; // initialized by binder - node.locals = undefined!; // initialized by binder - node.nextContainer = undefined!; // initialized by binder + node.localSymbol = undefined; // initialized by binder + node.locals = undefined; // initialized by binder + node.nextContainer = undefined; // initialized by binder return node; } @@ -883,8 +889,10 @@ namespace ts { /** Create a unique temporary variable for use in a loop. */ // @api - function createLoopVariable(): Identifier { - return createBaseGeneratedIdentifier("", GeneratedIdentifierFlags.Loop); + function createLoopVariable(reservedInNestedScopes?: boolean): Identifier { + let flags = GeneratedIdentifierFlags.Loop; + if (reservedInNestedScopes) flags |= GeneratedIdentifierFlags.ReservedInNestedScopes; + return createBaseGeneratedIdentifier("", flags); } /** Create a unique name based on the supplied text. */ @@ -960,6 +968,7 @@ namespace ts { case SyntaxKind.BigIntKeyword: case SyntaxKind.NeverKeyword: case SyntaxKind.ObjectKeyword: + case SyntaxKind.OverrideKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.BooleanKeyword: case SyntaxKind.SymbolKeyword: @@ -1033,6 +1042,7 @@ namespace ts { if (flags & ModifierFlags.Protected) { result.push(createModifier(SyntaxKind.ProtectedKeyword)); } if (flags & ModifierFlags.Abstract) { result.push(createModifier(SyntaxKind.AbstractKeyword)); } if (flags & ModifierFlags.Static) { result.push(createModifier(SyntaxKind.StaticKeyword)); } + if (flags & ModifierFlags.Override) { result.push(createModifier(SyntaxKind.OverrideKeyword)); } if (flags & ModifierFlags.Readonly) { result.push(createModifier(SyntaxKind.ReadonlyKeyword)); } if (flags & ModifierFlags.Async) { result.push(createModifier(SyntaxKind.AsyncKeyword)); } return result; @@ -2129,7 +2139,7 @@ namespace ts { /*decorators*/ undefined, /*modifiers*/ undefined, name, - initializer + initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer) ); node.propertyName = asName(propertyName); node.dotDotDotToken = dotDotDotToken; @@ -2711,7 +2721,7 @@ namespace ts { node.transformFlags |= TransformFlags.ContainsES2016; } else if (isLogicalOrCoalescingAssignmentOperator(operatorKind)) { - node.transformFlags |= TransformFlags.ContainsESNext; + node.transformFlags |= TransformFlags.ContainsES2021; } return node; } @@ -4234,7 +4244,7 @@ namespace ts { } // @api - function createBaseJSDocTag(kind: T["kind"], tagName: Identifier, comment: string | undefined) { + function createBaseJSDocTag(kind: T["kind"], tagName: Identifier, comment: string | NodeArray | undefined) { const node = createBaseNode(kind); node.tagName = tagName; node.comment = comment; @@ -4242,7 +4252,7 @@ namespace ts { } // @api - function createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string): JSDocTemplateTag { + function createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray): JSDocTemplateTag { const node = createBaseJSDocTag(SyntaxKind.JSDocTemplateTag, tagName ?? createIdentifier("template"), comment); node.constraint = constraint; node.typeParameters = createNodeArray(typeParameters); @@ -4250,7 +4260,7 @@ namespace ts { } // @api - function updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier = getDefaultTagName(node), constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | undefined): JSDocTemplateTag { + function updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier = getDefaultTagName(node), constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | NodeArray | undefined): JSDocTemplateTag { return node.tagName !== tagName || node.constraint !== constraint || node.typeParameters !== typeParameters @@ -4260,7 +4270,7 @@ namespace ts { } // @api - function createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string): JSDocTypedefTag { + function createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocTypedefTag { const node = createBaseJSDocTag(SyntaxKind.JSDocTypedefTag, tagName ?? createIdentifier("typedef"), comment); node.typeExpression = typeExpression; node.fullName = fullName; @@ -4269,7 +4279,7 @@ namespace ts { } // @api - function updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | undefined): JSDocTypedefTag { + function updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocTypedefTag { return node.tagName !== tagName || node.typeExpression !== typeExpression || node.fullName !== fullName @@ -4279,7 +4289,7 @@ namespace ts { } // @api - function createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string): JSDocParameterTag { + function createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocParameterTag { const node = createBaseJSDocTag(SyntaxKind.JSDocParameterTag, tagName ?? createIdentifier("param"), comment); node.typeExpression = typeExpression; node.name = name; @@ -4289,7 +4299,7 @@ namespace ts { } // @api - function updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier = getDefaultTagName(node), name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | undefined): JSDocParameterTag { + function updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier = getDefaultTagName(node), name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocParameterTag { return node.tagName !== tagName || node.name !== name || node.isBracketed !== isBracketed @@ -4301,7 +4311,7 @@ namespace ts { } // @api - function createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string): JSDocPropertyTag { + function createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocPropertyTag { const node = createBaseJSDocTag(SyntaxKind.JSDocPropertyTag, tagName ?? createIdentifier("prop"), comment); node.typeExpression = typeExpression; node.name = name; @@ -4311,7 +4321,7 @@ namespace ts { } // @api - function updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier = getDefaultTagName(node), name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | undefined): JSDocPropertyTag { + function updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier = getDefaultTagName(node), name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocPropertyTag { return node.tagName !== tagName || node.name !== name || node.isBracketed !== isBracketed @@ -4323,7 +4333,7 @@ namespace ts { } // @api - function createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string): JSDocCallbackTag { + function createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocCallbackTag { const node = createBaseJSDocTag(SyntaxKind.JSDocCallbackTag, tagName ?? createIdentifier("callback"), comment); node.typeExpression = typeExpression; node.fullName = fullName; @@ -4332,7 +4342,7 @@ namespace ts { } // @api - function updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | undefined): JSDocCallbackTag { + function updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocCallbackTag { return node.tagName !== tagName || node.typeExpression !== typeExpression || node.fullName !== fullName @@ -4342,14 +4352,14 @@ namespace ts { } // @api - function createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string): JSDocAugmentsTag { + function createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string | NodeArray): JSDocAugmentsTag { const node = createBaseJSDocTag(SyntaxKind.JSDocAugmentsTag, tagName ?? createIdentifier("augments"), comment); node.class = className; return node; } // @api - function updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier = getDefaultTagName(node), className: JSDocAugmentsTag["class"], comment: string | undefined): JSDocAugmentsTag { + function updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier = getDefaultTagName(node), className: JSDocAugmentsTag["class"], comment: string | NodeArray | undefined): JSDocAugmentsTag { return node.tagName !== tagName || node.class !== className || node.comment !== comment @@ -4358,21 +4368,21 @@ namespace ts { } // @api - function createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string): JSDocImplementsTag { + function createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string | NodeArray): JSDocImplementsTag { const node = createBaseJSDocTag(SyntaxKind.JSDocImplementsTag, tagName ?? createIdentifier("implements"), comment); node.class = className; return node; } // @api - function createJSDocSeeTag(tagName: Identifier | undefined, name: JSDocNameReference | undefined, comment?: string): JSDocSeeTag { + function createJSDocSeeTag(tagName: Identifier | undefined, name: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag { const node = createBaseJSDocTag(SyntaxKind.JSDocSeeTag, tagName ?? createIdentifier("see"), comment); node.name = name; return node; } // @api - function updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, name: JSDocNameReference | undefined, comment?: string): JSDocSeeTag { + function updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, name: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag { return node.tagName !== tagName || node.name !== name || node.comment !== comment @@ -4395,7 +4405,22 @@ namespace ts { } // @api - function updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier = getDefaultTagName(node), className: JSDocImplementsTag["class"], comment: string | undefined): JSDocImplementsTag { + function createJSDocLink(name: EntityName | undefined, text: string): JSDocLink { + const node = createBaseNode(SyntaxKind.JSDocLink); + node.name = name; + node.text = text; + return node; + } + + // @api + function updateJSDocLink(node: JSDocLink, name: EntityName | undefined, text: string): JSDocLink { + return node.name !== name + ? update(createJSDocLink(name, text), node) + : node; + } + + // @api + function updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier = getDefaultTagName(node), className: JSDocImplementsTag["class"], comment: string | NodeArray | undefined): JSDocImplementsTag { return node.tagName !== tagName || node.class !== className || node.comment !== comment @@ -4411,7 +4436,7 @@ namespace ts { // createJSDocProtectedTag // createJSDocReadonlyTag // createJSDocDeprecatedTag - function createJSDocSimpleTagWorker(kind: T["kind"], tagName: Identifier | undefined, comment?: string) { + function createJSDocSimpleTagWorker(kind: T["kind"], tagName: Identifier | undefined, comment?: string | NodeArray) { const node = createBaseJSDocTag(kind, tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), comment); return node; } @@ -4424,7 +4449,7 @@ namespace ts { // updateJSDocProtectedTag // updateJSDocReadonlyTag // updateJSDocDeprecatedTag - function updateJSDocSimpleTagWorker(kind: T["kind"], node: T, tagName: Identifier = getDefaultTagName(node), comment: string | undefined) { + function updateJSDocSimpleTagWorker(kind: T["kind"], node: T, tagName: Identifier = getDefaultTagName(node), comment: string | NodeArray | undefined) { return node.tagName !== tagName || node.comment !== comment ? update(createJSDocSimpleTagWorker(kind, tagName, comment), node) : @@ -4436,7 +4461,7 @@ namespace ts { // createJSDocReturnTag // createJSDocThisTag // createJSDocEnumTag - function createJSDocTypeLikeTagWorker(kind: T["kind"], tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string) { + function createJSDocTypeLikeTagWorker(kind: T["kind"], tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray) { const node = createBaseJSDocTag(kind, tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), comment); node.typeExpression = typeExpression; return node; @@ -4447,7 +4472,7 @@ namespace ts { // updateJSDocReturnTag // updateJSDocThisTag // updateJSDocEnumTag - function updateJSDocTypeLikeTagWorker(kind: T["kind"], node: T, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression | undefined, comment: string | undefined) { + function updateJSDocTypeLikeTagWorker(kind: T["kind"], node: T, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined) { return node.tagName !== tagName || node.typeExpression !== typeExpression || node.comment !== comment @@ -4456,13 +4481,13 @@ namespace ts { } // @api - function createJSDocUnknownTag(tagName: Identifier, comment?: string): JSDocUnknownTag { + function createJSDocUnknownTag(tagName: Identifier, comment?: string | NodeArray): JSDocUnknownTag { const node = createBaseJSDocTag(SyntaxKind.JSDocTag, tagName, comment); return node; } // @api - function updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | undefined): JSDocUnknownTag { + function updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | NodeArray | undefined): JSDocUnknownTag { return node.tagName !== tagName || node.comment !== comment ? update(createJSDocUnknownTag(tagName, comment), node) @@ -4470,7 +4495,21 @@ namespace ts { } // @api - function createJSDocComment(comment?: string | undefined, tags?: readonly JSDocTag[] | undefined) { + function createJSDocText(text: string): JSDocText { + const node = createBaseNode(SyntaxKind.JSDocText); + node.text = text; + return node; + } + + // @api + function updateJSDocText(node: JSDocText, text: string): JSDocText { + return node.text !== text + ? update(createJSDocText(text), node) + : node; + } + + // @api + function createJSDocComment(comment?: string | NodeArray | undefined, tags?: readonly JSDocTag[] | undefined) { const node = createBaseNode(SyntaxKind.JSDocComment); node.comment = comment; node.tags = asNodeArray(tags); @@ -4478,7 +4517,7 @@ namespace ts { } // @api - function updateJSDocComment(node: JSDoc, comment: string | undefined, tags: readonly JSDocTag[] | undefined) { + function updateJSDocComment(node: JSDoc, comment: string | NodeArray | undefined, tags: readonly JSDocTag[] | undefined) { return node.comment !== comment || node.tags !== tags ? update(createJSDocComment(comment, tags), node) @@ -5507,7 +5546,7 @@ namespace ts { : reduceLeft(expressions, factory.createComma)!; } - function getName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean, emitFlags: EmitFlags = 0) { + function getName(node: Declaration | undefined, allowComments?: boolean, allowSourceMaps?: boolean, emitFlags: EmitFlags = 0) { const nodeName = getNameOfDeclaration(node); if (nodeName && isIdentifier(nodeName) && !isGeneratedIdentifier(nodeName)) { // TODO(rbuckton): Does this need to be parented? @@ -5571,7 +5610,7 @@ namespace ts { * @param allowComments A value indicating whether comments may be emitted for the name. * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. */ - function getDeclarationName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean) { + function getDeclarationName(node: Declaration | undefined, allowComments?: boolean, allowSourceMaps?: boolean) { return getName(node, allowComments, allowSourceMaps); } @@ -5899,6 +5938,7 @@ namespace ts { case SyntaxKind.JSDocPrivateTag: return "private"; case SyntaxKind.JSDocProtectedTag: return "protected"; case SyntaxKind.JSDocReadonlyTag: return "readonly"; + case SyntaxKind.JSDocOverrideTag: return "override"; case SyntaxKind.JSDocTemplateTag: return "template"; case SyntaxKind.JSDocTypedefTag: return "typedef"; case SyntaxKind.JSDocParameterTag: return "param"; diff --git a/src/compiler/factory/nodeTests.ts b/src/compiler/factory/nodeTests.ts index 71b329e46d65c..64a88d32d099e 100644 --- a/src/compiler/factory/nodeTests.ts +++ b/src/compiler/factory/nodeTests.ts @@ -39,51 +39,114 @@ namespace ts { return node.kind === SyntaxKind.TemplateTail; } + // Punctuation + + export function isDotDotDotToken(node: Node): node is DotDotDotToken { + return node.kind === SyntaxKind.DotDotDotToken; + } + + /*@internal*/ + export function isCommaToken(node: Node): node is Token { + return node.kind === SyntaxKind.CommaToken; + } + + export function isPlusToken(node: Node): node is PlusToken { + return node.kind === SyntaxKind.PlusToken; + } + + export function isMinusToken(node: Node): node is MinusToken { + return node.kind === SyntaxKind.MinusToken; + } + + export function isAsteriskToken(node: Node): node is AsteriskToken { + return node.kind === SyntaxKind.AsteriskToken; + } + + /*@internal*/ + export function isExclamationToken(node: Node): node is ExclamationToken { + return node.kind === SyntaxKind.ExclamationToken; + } + + /*@internal*/ + export function isQuestionToken(node: Node): node is QuestionToken { + return node.kind === SyntaxKind.QuestionToken; + } + + /*@internal*/ + export function isColonToken(node: Node): node is ColonToken { + return node.kind === SyntaxKind.ColonToken; + } + + /*@internal*/ + export function isQuestionDotToken(node: Node): node is QuestionDotToken { + return node.kind === SyntaxKind.QuestionDotToken; + } + + /*@internal*/ + export function isEqualsGreaterThanToken(node: Node): node is EqualsGreaterThanToken { + return node.kind === SyntaxKind.EqualsGreaterThanToken; + } + // Identifiers export function isIdentifier(node: Node): node is Identifier { return node.kind === SyntaxKind.Identifier; } - // Names + export function isPrivateIdentifier(node: Node): node is PrivateIdentifier { + return node.kind === SyntaxKind.PrivateIdentifier; + } - export function isQualifiedName(node: Node): node is QualifiedName { - return node.kind === SyntaxKind.QualifiedName; + // Reserved Words + + /* @internal */ + export function isExportModifier(node: Node): node is ExportKeyword { + return node.kind === SyntaxKind.ExportKeyword; } - export function isComputedPropertyName(node: Node): node is ComputedPropertyName { - return node.kind === SyntaxKind.ComputedPropertyName; + /* @internal */ + export function isAsyncModifier(node: Node): node is AsyncKeyword { + return node.kind === SyntaxKind.AsyncKeyword; } - export function isPrivateIdentifier(node: Node): node is PrivateIdentifier { - return node.kind === SyntaxKind.PrivateIdentifier; + /* @internal */ + export function isAssertsKeyword(node: Node): node is AssertsKeyword { + return node.kind === SyntaxKind.AssertsKeyword; } - // Tokens + /* @internal */ + export function isAwaitKeyword(node: Node): node is AwaitKeyword { + return node.kind === SyntaxKind.AwaitKeyword; + } + + /* @internal */ + export function isReadonlyKeyword(node: Node): node is ReadonlyKeyword { + return node.kind === SyntaxKind.ReadonlyKeyword; + } + + /* @internal */ + export function isStaticModifier(node: Node): node is StaticKeyword { + return node.kind === SyntaxKind.StaticKeyword; + } /*@internal*/ - export function isSuperKeyword(node: Node): node is Token { + export function isSuperKeyword(node: Node): node is SuperExpression { return node.kind === SyntaxKind.SuperKeyword; } /*@internal*/ - export function isImportKeyword(node: Node): node is Token { + export function isImportKeyword(node: Node): node is ImportExpression { return node.kind === SyntaxKind.ImportKeyword; } - /*@internal*/ - export function isCommaToken(node: Node): node is Token { - return node.kind === SyntaxKind.CommaToken; - } + // Names - /*@internal*/ - export function isQuestionToken(node: Node): node is Token { - return node.kind === SyntaxKind.QuestionToken; + export function isQualifiedName(node: Node): node is QualifiedName { + return node.kind === SyntaxKind.QualifiedName; } - /*@internal*/ - export function isExclamationToken(node: Node): node is Token { - return node.kind === SyntaxKind.ExclamationToken; + export function isComputedPropertyName(node: Node): node is ComputedPropertyName { + return node.kind === SyntaxKind.ComputedPropertyName; } // Signature elements @@ -707,6 +770,10 @@ namespace ts { return node.kind === SyntaxKind.JSDocNameReference; } + export function isJSDocLink(node: Node): node is JSDocLink { + return node.kind === SyntaxKind.JSDocLink; + } + export function isJSDocAllType(node: Node): node is JSDocAllType { return node.kind === SyntaxKind.JSDocAllType; } @@ -785,6 +852,10 @@ namespace ts { return node.kind === SyntaxKind.JSDocReadonlyTag; } + export function isJSDocOverrideTag(node: Node): node is JSDocOverrideTag { + return node.kind === SyntaxKind.JSDocOverrideTag; + } + export function isJSDocDeprecatedTag(node: Node): node is JSDocDeprecatedTag { return node.kind === SyntaxKind.JSDocDeprecatedTag; } diff --git a/src/compiler/factory/parenthesizerRules.ts b/src/compiler/factory/parenthesizerRules.ts index 069df2d60c9ae..89492f82bde48 100644 --- a/src/compiler/factory/parenthesizerRules.ts +++ b/src/compiler/factory/parenthesizerRules.ts @@ -5,7 +5,12 @@ namespace ts { cachedLiteralKind: SyntaxKind; } + let binaryLeftOperandParenthesizerCache: ESMap Expression> | undefined; + let binaryRightOperandParenthesizerCache: ESMap Expression> | undefined; + return { + getParenthesizeLeftSideOfBinaryForOperator, + getParenthesizeRightSideOfBinaryForOperator, parenthesizeLeftSideOfBinary, parenthesizeRightSideOfBinary, parenthesizeExpressionOfComputedPropertyName, @@ -27,6 +32,26 @@ namespace ts { parenthesizeTypeArguments, }; + function getParenthesizeLeftSideOfBinaryForOperator(operatorKind: BinaryOperator) { + binaryLeftOperandParenthesizerCache ||= new Map(); + let parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = node => parenthesizeLeftSideOfBinary(operatorKind, node); + binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } + + function getParenthesizeRightSideOfBinaryForOperator(operatorKind: BinaryOperator) { + binaryRightOperandParenthesizerCache ||= new Map(); + let parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind); + if (!parenthesizerRule) { + parenthesizerRule = node => parenthesizeRightSideOfBinary(operatorKind, /*leftSide*/ undefined, node); + binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + } + return parenthesizerRule; + } + /** * Determines whether the operand to a BinaryExpression needs to be parenthesized. * @@ -210,7 +235,7 @@ namespace ts { return parenthesizeBinaryOperand(binaryOperator, leftSide, /*isLeftSideOfBinary*/ true); } - function parenthesizeRightSideOfBinary(binaryOperator: SyntaxKind, leftSide: Expression, rightSide: Expression): Expression { + function parenthesizeRightSideOfBinary(binaryOperator: SyntaxKind, leftSide: Expression | undefined, rightSide: Expression): Expression { return parenthesizeBinaryOperand(binaryOperator, rightSide, /*isLeftSideOfBinary*/ false, leftSide); } @@ -352,6 +377,8 @@ namespace ts { return expression; } + function parenthesizeConciseBodyOfArrowFunction(body: Expression): Expression; + function parenthesizeConciseBodyOfArrowFunction(body: ConciseBody): ConciseBody; function parenthesizeConciseBodyOfArrowFunction(body: ConciseBody): ConciseBody { if (!isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === SyntaxKind.ObjectLiteralExpression)) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. @@ -403,6 +430,8 @@ namespace ts { } export const nullParenthesizerRules: ParenthesizerRules = { + getParenthesizeLeftSideOfBinaryForOperator: _ => identity, + getParenthesizeRightSideOfBinaryForOperator: _ => identity, parenthesizeLeftSideOfBinary: (_binaryOperator, leftSide) => leftSide, parenthesizeRightSideOfBinary: (_binaryOperator, _leftSide, rightSide) => rightSide, parenthesizeExpressionOfComputedPropertyName: identity, diff --git a/src/compiler/factory/utilities.ts b/src/compiler/factory/utilities.ts index 8b18c3152e3ff..433f13c5c3e29 100644 --- a/src/compiler/factory/utilities.ts +++ b/src/compiler/factory/utilities.ts @@ -13,7 +13,7 @@ namespace ts { } else { const expression = setTextRange( - isIdentifierOrPrivateIdentifier(memberName) + isMemberName(memberName) ? factory.createPropertyAccessExpression(target, memberName) : factory.createElementAccessExpression(target, memberName), memberName @@ -412,7 +412,7 @@ namespace ts { const helperNames: string[] = []; for (const helper of helpers) { if (!helper.scoped) { - const importName = (helper as UnscopedEmitHelper).importName; + const importName = helper.importName; if (importName) { pushIfUnique(helperNames, importName); } @@ -815,18 +815,327 @@ namespace ts { || kind === SyntaxKind.ExportDeclaration; } - /* @internal */ - export function isExportModifier(node: Modifier): node is ExportKeyword { - return node.kind === SyntaxKind.ExportKeyword; + export const isTypeNodeOrTypeParameterDeclaration = or(isTypeNode, isTypeParameterDeclaration) as (node: Node) => node is TypeNode | TypeParameterDeclaration; + export const isQuestionOrExclamationToken = or(isQuestionToken, isExclamationToken) as (node: Node) => node is QuestionToken | ExclamationToken; + export const isIdentifierOrThisTypeNode = or(isIdentifier, isThisTypeNode) as (node: Node) => node is Identifier | ThisTypeNode; + export const isReadonlyKeywordOrPlusOrMinusToken = or(isReadonlyKeyword, isPlusToken, isMinusToken) as (node: Node) => node is ReadonlyKeyword | PlusToken | MinusToken; + export const isQuestionOrPlusOrMinusToken = or(isQuestionToken, isPlusToken, isMinusToken) as (node: Node) => node is QuestionToken | PlusToken | MinusToken; + export const isModuleName = or(isIdentifier, isStringLiteral) as (node: Node) => node is ModuleName; + + export function isLiteralTypeLikeExpression(node: Node): node is NullLiteral | BooleanLiteral | LiteralExpression | PrefixUnaryExpression { + const kind = node.kind; + return kind === SyntaxKind.NullKeyword + || kind === SyntaxKind.TrueKeyword + || kind === SyntaxKind.FalseKeyword + || isLiteralExpression(node) + || isPrefixUnaryExpression(node); } - /* @internal */ - export function isAsyncModifier(node: Modifier): node is AsyncKeyword { - return node.kind === SyntaxKind.AsyncKeyword; + function isExponentiationOperator(kind: SyntaxKind): kind is ExponentiationOperator { + return kind === SyntaxKind.AsteriskAsteriskToken; } - /* @internal */ - export function isStaticModifier(node: Modifier): node is StaticKeyword { - return node.kind === SyntaxKind.StaticKeyword; + function isMultiplicativeOperator(kind: SyntaxKind): kind is MultiplicativeOperator { + return kind === SyntaxKind.AsteriskToken + || kind === SyntaxKind.SlashToken + || kind === SyntaxKind.PercentToken; + } + + function isMultiplicativeOperatorOrHigher(kind: SyntaxKind): kind is MultiplicativeOperatorOrHigher { + return isExponentiationOperator(kind) + || isMultiplicativeOperator(kind); + } + + function isAdditiveOperator(kind: SyntaxKind): kind is AdditiveOperator { + return kind === SyntaxKind.PlusToken + || kind === SyntaxKind.MinusToken; + } + + function isAdditiveOperatorOrHigher(kind: SyntaxKind): kind is AdditiveOperatorOrHigher { + return isAdditiveOperator(kind) + || isMultiplicativeOperatorOrHigher(kind); + } + + function isShiftOperator(kind: SyntaxKind): kind is ShiftOperator { + return kind === SyntaxKind.LessThanLessThanToken + || kind === SyntaxKind.GreaterThanGreaterThanToken + || kind === SyntaxKind.GreaterThanGreaterThanGreaterThanToken; + } + + function isShiftOperatorOrHigher(kind: SyntaxKind): kind is ShiftOperatorOrHigher { + return isShiftOperator(kind) + || isAdditiveOperatorOrHigher(kind); + } + + function isRelationalOperator(kind: SyntaxKind): kind is RelationalOperator { + return kind === SyntaxKind.LessThanToken + || kind === SyntaxKind.LessThanEqualsToken + || kind === SyntaxKind.GreaterThanToken + || kind === SyntaxKind.GreaterThanEqualsToken + || kind === SyntaxKind.InstanceOfKeyword + || kind === SyntaxKind.InKeyword; + } + + function isRelationalOperatorOrHigher(kind: SyntaxKind): kind is RelationalOperatorOrHigher { + return isRelationalOperator(kind) + || isShiftOperatorOrHigher(kind); + } + + function isEqualityOperator(kind: SyntaxKind): kind is EqualityOperator { + return kind === SyntaxKind.EqualsEqualsToken + || kind === SyntaxKind.EqualsEqualsEqualsToken + || kind === SyntaxKind.ExclamationEqualsToken + || kind === SyntaxKind.ExclamationEqualsEqualsToken; + } + + function isEqualityOperatorOrHigher(kind: SyntaxKind): kind is EqualityOperatorOrHigher { + return isEqualityOperator(kind) + || isRelationalOperatorOrHigher(kind); + } + + function isBitwiseOperator(kind: SyntaxKind): kind is BitwiseOperator { + return kind === SyntaxKind.AmpersandToken + || kind === SyntaxKind.BarToken + || kind === SyntaxKind.CaretToken; + } + + function isBitwiseOperatorOrHigher(kind: SyntaxKind): kind is BitwiseOperatorOrHigher { + return isBitwiseOperator(kind) + || isEqualityOperatorOrHigher(kind); + } + + // NOTE: The version in utilities includes ExclamationToken, which is not a binary operator. + function isLogicalOperator(kind: SyntaxKind): kind is LogicalOperator { + return kind === SyntaxKind.AmpersandAmpersandToken + || kind === SyntaxKind.BarBarToken; + } + + function isLogicalOperatorOrHigher(kind: SyntaxKind): kind is LogicalOperatorOrHigher { + return isLogicalOperator(kind) + || isBitwiseOperatorOrHigher(kind); + } + + function isAssignmentOperatorOrHigher(kind: SyntaxKind): kind is AssignmentOperatorOrHigher { + return kind === SyntaxKind.QuestionQuestionToken + || isLogicalOperatorOrHigher(kind) + || isAssignmentOperator(kind); + } + + function isBinaryOperator(kind: SyntaxKind): kind is BinaryOperator { + return isAssignmentOperatorOrHigher(kind) + || kind === SyntaxKind.CommaToken; + } + + export function isBinaryOperatorToken(node: Node): node is BinaryOperatorToken { + return isBinaryOperator(node.kind); + } + + type BinaryExpressionState = (machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], resultHolder: { value: TResult }, outerState: TOuterState) => number; + + namespace BinaryExpressionState { + /** + * Handles walking into a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + export function enter(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], _resultHolder: { value: TResult }, outerState: TOuterState): number { + const prevUserState = stackIndex > 0 ? userStateStack[stackIndex - 1] : undefined; + Debug.assertEqual(stateStack[stackIndex], enter); + userStateStack[stackIndex] = machine.onEnter(nodeStack[stackIndex], prevUserState, outerState); + stateStack[stackIndex] = nextState(machine, enter); + return stackIndex; + } + + /** + * Handles walking the `left` side of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + export function left(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], _resultHolder: { value: TResult }, _outerState: TOuterState): number { + Debug.assertEqual(stateStack[stackIndex], left); + Debug.assertIsDefined(machine.onLeft); + stateStack[stackIndex] = nextState(machine, left); + const nextNode = machine.onLeft(nodeStack[stackIndex].left, userStateStack[stackIndex], nodeStack[stackIndex]); + if (nextNode) { + checkCircularity(stackIndex, nodeStack, nextNode); + return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode); + } + return stackIndex; + } + + /** + * Handles walking the `operatorToken` of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + export function operator(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], _resultHolder: { value: TResult }, _outerState: TOuterState): number { + Debug.assertEqual(stateStack[stackIndex], operator); + Debug.assertIsDefined(machine.onOperator); + stateStack[stackIndex] = nextState(machine, operator); + machine.onOperator(nodeStack[stackIndex].operatorToken, userStateStack[stackIndex], nodeStack[stackIndex]); + return stackIndex; + } + + /** + * Handles walking the `right` side of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + export function right(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], _resultHolder: { value: TResult }, _outerState: TOuterState): number { + Debug.assertEqual(stateStack[stackIndex], right); + Debug.assertIsDefined(machine.onRight); + stateStack[stackIndex] = nextState(machine, right); + const nextNode = machine.onRight(nodeStack[stackIndex].right, userStateStack[stackIndex], nodeStack[stackIndex]); + if (nextNode) { + checkCircularity(stackIndex, nodeStack, nextNode); + return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode); + } + return stackIndex; + } + + /** + * Handles walking out of a `BinaryExpression`. + * @param machine State machine handler functions + * @param frame The current frame + * @returns The new frame + */ + export function exit(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], resultHolder: { value: TResult }, _outerState: TOuterState): number { + Debug.assertEqual(stateStack[stackIndex], exit); + stateStack[stackIndex] = nextState(machine, exit); + const result = machine.onExit(nodeStack[stackIndex], userStateStack[stackIndex]); + if (stackIndex > 0) { + stackIndex--; + if (machine.foldState) { + const side = stateStack[stackIndex] === exit ? "right" : "left"; + userStateStack[stackIndex] = machine.foldState(userStateStack[stackIndex], result, side); + } + } + else { + resultHolder.value = result; + } + return stackIndex; + } + + /** + * Handles a frame that is already done. + * @returns The `done` state. + */ + export function done(_machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], _nodeStack: BinaryExpression[], _userStateStack: TState[], _resultHolder: { value: TResult }, _outerState: TOuterState): number { + Debug.assertEqual(stateStack[stackIndex], done); + return stackIndex; + } + + export function nextState(machine: BinaryExpressionStateMachine, currentState: BinaryExpressionState) { + switch (currentState) { + case enter: + if (machine.onLeft) return left; + // falls through + case left: + if (machine.onOperator) return operator; + // falls through + case operator: + if (machine.onRight) return right; + // falls through + case right: return exit; + case exit: return done; + case done: return done; + default: Debug.fail("Invalid state"); + } + } + + function pushStack(stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], node: BinaryExpression) { + stackIndex++; + stateStack[stackIndex] = enter; + nodeStack[stackIndex] = node; + userStateStack[stackIndex] = undefined!; + return stackIndex; + } + + function checkCircularity(stackIndex: number, nodeStack: BinaryExpression[], node: BinaryExpression) { + if (Debug.shouldAssert(AssertionLevel.Aggressive)) { + while (stackIndex >= 0) { + Debug.assert(nodeStack[stackIndex] !== node, "Circular traversal detected."); + stackIndex--; + } + } + } + } + + /** + * Holds state machine handler functions + */ + class BinaryExpressionStateMachine { + constructor( + readonly onEnter: (node: BinaryExpression, prev: TState | undefined, outerState: TOuterState) => TState, + readonly onLeft: ((left: Expression, userState: TState, node: BinaryExpression) => BinaryExpression | void) | undefined, + readonly onOperator: ((operatorToken: BinaryOperatorToken, userState: TState, node: BinaryExpression) => void) | undefined, + readonly onRight: ((right: Expression, userState: TState, node: BinaryExpression) => BinaryExpression | void) | undefined, + readonly onExit: (node: BinaryExpression, userState: TState) => TResult, + readonly foldState: ((userState: TState, result: TResult, side: "left" | "right") => TState) | undefined, + ) { + } + } + + /** + * Creates a state machine that walks a `BinaryExpression` using the heap to reduce call-stack depth on a large tree. + * @param onEnter Callback evaluated when entering a `BinaryExpression`. Returns new user-defined state to associate with the node while walking. + * @param onLeft Callback evaluated when walking the left side of a `BinaryExpression`. Return a `BinaryExpression` to continue walking, or `void` to advance to the right side. + * @param onRight Callback evaluated when walking the right side of a `BinaryExpression`. Return a `BinaryExpression` to continue walking, or `void` to advance to the end of the node. + * @param onExit Callback evaluated when exiting a `BinaryExpression`. The result returned will either be folded into the parent's state, or returned from the walker if at the top frame. + * @param foldState Callback evaluated when the result from a nested `onExit` should be folded into the state of that node's parent. + * @returns A function that walks a `BinaryExpression` node using the above callbacks, returning the result of the call to `onExit` from the outermost `BinaryExpression` node. + */ + export function createBinaryExpressionTrampoline( + onEnter: (node: BinaryExpression, prev: TState | undefined) => TState, + onLeft: ((left: Expression, userState: TState, node: BinaryExpression) => BinaryExpression | void) | undefined, + onOperator: ((operatorToken: BinaryOperatorToken, userState: TState, node: BinaryExpression) => void) | undefined, + onRight: ((right: Expression, userState: TState, node: BinaryExpression) => BinaryExpression | void) | undefined, + onExit: (node: BinaryExpression, userState: TState) => TResult, + foldState: ((userState: TState, result: TResult, side: "left" | "right") => TState) | undefined, + ): (node: BinaryExpression) => TResult; + /** + * Creates a state machine that walks a `BinaryExpression` using the heap to reduce call-stack depth on a large tree. + * @param onEnter Callback evaluated when entering a `BinaryExpression`. Returns new user-defined state to associate with the node while walking. + * @param onLeft Callback evaluated when walking the left side of a `BinaryExpression`. Return a `BinaryExpression` to continue walking, or `void` to advance to the right side. + * @param onRight Callback evaluated when walking the right side of a `BinaryExpression`. Return a `BinaryExpression` to continue walking, or `void` to advance to the end of the node. + * @param onExit Callback evaluated when exiting a `BinaryExpression`. The result returned will either be folded into the parent's state, or returned from the walker if at the top frame. + * @param foldState Callback evaluated when the result from a nested `onExit` should be folded into the state of that node's parent. + * @returns A function that walks a `BinaryExpression` node using the above callbacks, returning the result of the call to `onExit` from the outermost `BinaryExpression` node. + */ + export function createBinaryExpressionTrampoline( + onEnter: (node: BinaryExpression, prev: TState | undefined, outerState: TOuterState) => TState, + onLeft: ((left: Expression, userState: TState, node: BinaryExpression) => BinaryExpression | void) | undefined, + onOperator: ((operatorToken: BinaryOperatorToken, userState: TState, node: BinaryExpression) => void) | undefined, + onRight: ((right: Expression, userState: TState, node: BinaryExpression) => BinaryExpression | void) | undefined, + onExit: (node: BinaryExpression, userState: TState) => TResult, + foldState: ((userState: TState, result: TResult, side: "left" | "right") => TState) | undefined, + ): (node: BinaryExpression, outerState: TOuterState) => TResult; + export function createBinaryExpressionTrampoline( + onEnter: (node: BinaryExpression, prev: TState | undefined, outerState: TOuterState) => TState, + onLeft: ((left: Expression, userState: TState, node: BinaryExpression) => BinaryExpression | void) | undefined, + onOperator: ((operatorToken: BinaryOperatorToken, userState: TState, node: BinaryExpression) => void) | undefined, + onRight: ((right: Expression, userState: TState, node: BinaryExpression) => BinaryExpression | void) | undefined, + onExit: (node: BinaryExpression, userState: TState) => TResult, + foldState: ((userState: TState, result: TResult, side: "left" | "right") => TState) | undefined, + ) { + const machine = new BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState); + return trampoline; + + function trampoline(node: BinaryExpression, outerState?: TOuterState) { + const resultHolder: { value: TResult } = { value: undefined! }; + const stateStack: BinaryExpressionState[] = [BinaryExpressionState.enter]; + const nodeStack: BinaryExpression[] = [node]; + const userStateStack: TState[] = [undefined!]; + let stackIndex = 0; + while (stateStack[stackIndex] !== BinaryExpressionState.done) { + stackIndex = stateStack[stackIndex](machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, outerState); + } + Debug.assertEqual(stackIndex, 0); + return resultHolder.value; + } } } diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 5348db0973d88..22577901f20ba 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -43,11 +43,12 @@ namespace ts { packageId: PackageId | undefined; /** * When the resolved is not created from cache, the value is - * - string if original Path if it is symbolic link to the resolved path - * - undefined if path is not a symbolic link + * - string if it is symbolic link to the resolved `path` + * - undefined if `path` is not a symbolic link * When the resolved is created using value from cache of ResolvedModuleWithFailedLookupLocations, the value is: - * - string if original Path if it is symbolic link to the resolved path - * - true if path is not a symbolic link - this indicates that the originalPath calculation is already done and needs to be skipped + * - string if it is symbolic link to the resolved `path` + * - true if `path` is not a symbolic link - this indicates that the `originalPath` calculation is already done and needs to be skipped + * Note: This is a file name with preserved original casing, not a normalized `Path`. */ originalPath?: string | true; } @@ -101,9 +102,11 @@ namespace ts { traceEnabled: boolean; failedLookupLocations: Push; resultFromCache?: ResolvedModuleWithFailedLookupLocations; + packageJsonInfoCache: PackageJsonInfoCache | undefined; } /** Just the fields that we use for module resolution. */ + /*@internal*/ interface PackageJsonPathFields { typings?: string; types?: string; @@ -179,6 +182,7 @@ namespace ts { return typesVersions; } + /*@internal*/ interface VersionPaths { version: string; paths: MapLike; @@ -281,13 +285,24 @@ namespace ts { * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations { + export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, cache?: TypeReferenceDirectiveResolutionCache): ResolvedTypeReferenceDirectiveWithFailedLookupLocations { const traceEnabled = isTraceEnabled(options, host); if (redirectedReference) { options = redirectedReference.commandLine.options; } - const failedLookupLocations: string[] = []; - const moduleResolutionState: ModuleResolutionState = { compilerOptions: options, host, traceEnabled, failedLookupLocations }; + + const containingDirectory = containingFile ? getDirectoryPath(containingFile) : undefined; + const perFolderCache = containingDirectory ? cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference) : undefined; + let result = perFolderCache && perFolderCache.get(typeReferenceDirectiveName); + if (result) { + if (traceEnabled) { + trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile); + if (redirectedReference) trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + trace(host, Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory); + traceResult(result); + } + return result; + } const typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { @@ -312,6 +327,8 @@ namespace ts { } } + const failedLookupLocations: string[] = []; + const moduleResolutionState: ModuleResolutionState = { compilerOptions: options, host, traceEnabled, failedLookupLocations, packageJsonInfoCache: cache }; let resolved = primaryLookup(); let primary = true; if (!resolved) { @@ -323,19 +340,31 @@ namespace ts { if (resolved) { const { fileName, packageId } = resolved; const resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); - if (traceEnabled) { - if (packageId) { - trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, packageIdToString(packageId), primary); - } - else { - trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); - } + resolvedTypeReferenceDirective = { + primary, + resolvedFileName, + originalPath: fileName === resolvedFileName ? undefined : fileName, + packageId, + isExternalLibraryImport: pathContainsNodeModules(fileName), + }; + } + result = { resolvedTypeReferenceDirective, failedLookupLocations }; + perFolderCache?.set(typeReferenceDirectiveName, result); + if (traceEnabled) traceResult(result); + return result; + + function traceResult(result: ResolvedTypeReferenceDirectiveWithFailedLookupLocations) { + if (!result.resolvedTypeReferenceDirective?.resolvedFileName) { + trace(host, Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + else if (result.resolvedTypeReferenceDirective.packageId) { + trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, packageIdToString(result.resolvedTypeReferenceDirective.packageId), result.resolvedTypeReferenceDirective.primary); + } + else { + trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, result.resolvedTypeReferenceDirective.primary); } - resolvedTypeReferenceDirective = { primary, resolvedFileName, packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } - return { resolvedTypeReferenceDirective, failedLookupLocations }; - function primaryLookup(): PathAndPackageId | undefined { // Check primary library paths if (typeRoots && typeRoots.length) { @@ -378,11 +407,7 @@ namespace ts { const { path: candidate } = normalizePathAndParts(combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)); result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); } - const resolvedFile = resolvedTypeScriptOnly(result); - if (!resolvedFile && traceEnabled) { - trace(host, Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - return resolvedFile; + return resolvedTypeScriptOnly(result); } else { if (traceEnabled) { @@ -437,22 +462,39 @@ namespace ts { return result; } + export interface TypeReferenceDirectiveResolutionCache extends PerDirectoryResolutionCache, PackageJsonInfoCache { + } + /** - * Cached module resolutions per containing directory. + * Cached resolutions per containing directory. * This assumes that any module id will have the same resolution for sibling files located in the same folder. */ - export interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { - getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; - /*@internal*/ directoryToModuleNameMap: CacheWithRedirects>; + export interface PerDirectoryResolutionCache { + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + clear(): void; + /** + * Updates with the current compilerOptions the cache will operate with. + * This updates the redirects map as well if needed so module resolutions are cached if they can across the projects + */ + update(options: CompilerOptions): void; + } + + export interface ModuleResolutionCache extends PerDirectoryResolutionCache, NonRelativeModuleNameResolutionCache, PackageJsonInfoCache { + getPackageJsonInfoCache(): PackageJsonInfoCache; } /** * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. */ - export interface NonRelativeModuleNameResolutionCache { + export interface NonRelativeModuleNameResolutionCache extends PackageJsonInfoCache { getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; - /*@internal*/ moduleNameToDirectoryMap: CacheWithRedirects; + } + + export interface PackageJsonInfoCache { + /*@internal*/ getPackageJsonInfo(packageJsonPath: string): PackageJsonInfo | boolean | undefined; + /*@internal*/ setPackageJsonInfo(packageJsonPath: string, info: PackageJsonInfo | boolean): void; + clear(): void; } export interface PerModuleNameCache { @@ -460,19 +502,9 @@ namespace ts { set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; } - export function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions): ModuleResolutionCache { - return createModuleResolutionCacheWithMaps( - createCacheWithRedirects(options), - createCacheWithRedirects(options), - currentDirectory, - getCanonicalFileName - ); - } - - /*@internal*/ export interface CacheWithRedirects { - ownMap: ESMap; + getOwnMap: () => ESMap; redirectsMap: ESMap>; getOrCreateMapOfCacheRedirects(redirectedReference: ResolvedProjectReference | undefined): ESMap; clear(): void; @@ -485,7 +517,7 @@ namespace ts { let ownMap: ESMap = new Map(); const redirectsMap = new Map>(); return { - ownMap, + getOwnMap, redirectsMap, getOrCreateMapOfCacheRedirects, clear, @@ -493,6 +525,10 @@ namespace ts { setOwnMap }; + function getOwnMap() { + return ownMap; + } + function setOwnOptions(newOptions: CompilerOptions) { options = newOptions; } @@ -521,33 +557,125 @@ namespace ts { } } + function createPackageJsonInfoCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): PackageJsonInfoCache { + let cache: ESMap | undefined; + return { getPackageJsonInfo, setPackageJsonInfo, clear }; + function getPackageJsonInfo(packageJsonPath: string) { + return cache?.get(toPath(packageJsonPath, currentDirectory, getCanonicalFileName)); + } + function setPackageJsonInfo(packageJsonPath: string, info: PackageJsonInfo | boolean) { + (cache ||= new Map()).set(toPath(packageJsonPath, currentDirectory, getCanonicalFileName), info); + } + function clear() { + cache = undefined; + } + } + + function getOrCreateCache(cacheWithRedirects: CacheWithRedirects, redirectedReference: ResolvedProjectReference | undefined, key: string, create: () => T): T { + const cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + let result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); + } + return result; + } + + function updateRedirectsMap( + options: CompilerOptions, + directoryToModuleNameMap: CacheWithRedirects>, + moduleNameToDirectoryMap?: CacheWithRedirects + ) { + if (!options.configFile) return; + if (directoryToModuleNameMap.redirectsMap.size === 0) { + // The own map will be for projectCompilerOptions + Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size === 0); + Debug.assert(directoryToModuleNameMap.getOwnMap().size === 0); + Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.getOwnMap().size === 0); + directoryToModuleNameMap.redirectsMap.set(options.configFile.path, directoryToModuleNameMap.getOwnMap()); + moduleNameToDirectoryMap?.redirectsMap.set(options.configFile.path, moduleNameToDirectoryMap.getOwnMap()); + } + else { + // Set correct own map + Debug.assert(!moduleNameToDirectoryMap || moduleNameToDirectoryMap.redirectsMap.size > 0); + const ref: ResolvedProjectReference = { + sourceFile: options.configFile, + commandLine: { options } as ParsedCommandLine + }; + directoryToModuleNameMap.setOwnMap(directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); + moduleNameToDirectoryMap?.setOwnMap(moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); + } + directoryToModuleNameMap.setOwnOptions(options); + moduleNameToDirectoryMap?.setOwnOptions(options); + } + + function createPerDirectoryResolutionCache(currentDirectory: string, getCanonicalFileName: GetCanonicalFileName, directoryToModuleNameMap: CacheWithRedirects>): PerDirectoryResolutionCache { + return { + getOrCreateCacheForDirectory, + clear, + update, + }; + + function clear() { + directoryToModuleNameMap.clear(); + } + + function update(options: CompilerOptions) { + updateRedirectsMap(options, directoryToModuleNameMap); + } + + function getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference) { + const path = toPath(directoryName, currentDirectory, getCanonicalFileName); + return getOrCreateCache>(directoryToModuleNameMap, redirectedReference, path, () => new Map()); + } + } + + export function createModuleResolutionCache( + currentDirectory: string, + getCanonicalFileName: (s: string) => string, + options?: CompilerOptions + ): ModuleResolutionCache; /*@internal*/ - export function createModuleResolutionCacheWithMaps( + export function createModuleResolutionCache( + currentDirectory: string, + getCanonicalFileName: GetCanonicalFileName, + options: undefined, directoryToModuleNameMap: CacheWithRedirects>, moduleNameToDirectoryMap: CacheWithRedirects, + ): ModuleResolutionCache; + export function createModuleResolutionCache( currentDirectory: string, - getCanonicalFileName: GetCanonicalFileName): ModuleResolutionCache { + getCanonicalFileName: GetCanonicalFileName, + options?: CompilerOptions, + directoryToModuleNameMap?: CacheWithRedirects>, + moduleNameToDirectoryMap?: CacheWithRedirects, + ): ModuleResolutionCache { + const preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap ||= createCacheWithRedirects(options)); + moduleNameToDirectoryMap ||= createCacheWithRedirects(options); + const packageJsonInfoCache = createPackageJsonInfoCache(currentDirectory, getCanonicalFileName); - return { getOrCreateCacheForDirectory, getOrCreateCacheForModuleName, directoryToModuleNameMap, moduleNameToDirectoryMap }; + return { + ...packageJsonInfoCache, + ...preDirectoryResolutionCache, + getOrCreateCacheForModuleName, + clear, + update, + getPackageJsonInfoCache: () => packageJsonInfoCache, + }; - function getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference) { - const path = toPath(directoryName, currentDirectory, getCanonicalFileName); - return getOrCreateCache>(directoryToModuleNameMap, redirectedReference, path, () => new Map()); + function clear() { + preDirectoryResolutionCache.clear(); + moduleNameToDirectoryMap!.clear(); + packageJsonInfoCache.clear(); } - function getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache { - Debug.assert(!isExternalModuleNameRelative(nonRelativeModuleName)); - return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); + function update(options: CompilerOptions) { + updateRedirectsMap(options, directoryToModuleNameMap!, moduleNameToDirectoryMap); } - function getOrCreateCache(cacheWithRedirects: CacheWithRedirects, redirectedReference: ResolvedProjectReference | undefined, key: string, create: () => T): T { - const cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); - let result = cache.get(key); - if (!result) { - result = create(); - cache.set(key, result); - } - return result; + function getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache { + Debug.assert(!isExternalModuleNameRelative(nonRelativeModuleName)); + return getOrCreateCache(moduleNameToDirectoryMap!, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); } function createPerModuleNameCache(): PerModuleNameCache { @@ -623,6 +751,42 @@ namespace ts { } } + export function createTypeReferenceDirectiveResolutionCache( + currentDirectory: string, + getCanonicalFileName: (s: string) => string, + options?: CompilerOptions, + packageJsonInfoCache?: PackageJsonInfoCache, + ): TypeReferenceDirectiveResolutionCache; + /*@internal*/ + export function createTypeReferenceDirectiveResolutionCache( + currentDirectory: string, + getCanonicalFileName: GetCanonicalFileName, + options: undefined, + packageJsonInfoCache: PackageJsonInfoCache | undefined, + directoryToModuleNameMap: CacheWithRedirects>, + ): TypeReferenceDirectiveResolutionCache; + export function createTypeReferenceDirectiveResolutionCache( + currentDirectory: string, + getCanonicalFileName: GetCanonicalFileName, + options?: CompilerOptions, + packageJsonInfoCache?: PackageJsonInfoCache | undefined, + directoryToModuleNameMap?: CacheWithRedirects>, + ): TypeReferenceDirectiveResolutionCache { + const preDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, directoryToModuleNameMap ||= createCacheWithRedirects(options)); + packageJsonInfoCache ||= createPackageJsonInfoCache(currentDirectory, getCanonicalFileName); + + return { + ...packageJsonInfoCache, + ...preDirectoryResolutionCache, + clear, + }; + + function clear() { + preDirectoryResolutionCache.clear(); + packageJsonInfoCache!.clear(); + } + } + export function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined { const containingDirectory = getDirectoryPath(containingFile); const perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); @@ -931,7 +1095,7 @@ namespace ts { const traceEnabled = isTraceEnabled(compilerOptions, host); const failedLookupLocations: string[] = []; - const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations }; + const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations, packageJsonInfoCache: cache }; const result = forEach(extensions, ext => tryResolve(ext)); return createResolvedModuleWithFailedLookupLocations(result?.value?.resolved, result?.value?.isExternalLibraryImport, failedLookupLocations, state.resultFromCache); @@ -997,7 +1161,7 @@ namespace ts { } const resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { - const packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; + const packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; const packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined; return withPackageId(packageInfo, resolvedFromFile); } @@ -1031,8 +1195,9 @@ namespace ts { * For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo" * For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo" */ - function parseNodeModuleFromPath(resolved: PathAndExtension): string | undefined { - const path = normalizePath(resolved.path); + /* @internal */ + export function parseNodeModuleFromPath(resolved: string): string | undefined { + const path = normalizePath(resolved); const idx = path.lastIndexOf(nodeModulesPathPart); if (idx === -1) { return undefined; @@ -1137,6 +1302,7 @@ namespace ts { return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } + /*@internal*/ interface PackageJsonInfo { packageDirectory: string; packageJsonContent: PackageJsonPathFields; @@ -1145,21 +1311,40 @@ namespace ts { function getPackageJsonInfo(packageDirectory: string, onlyRecordFailures: boolean, state: ModuleResolutionState): PackageJsonInfo | undefined { const { host, traceEnabled } = state; - const directoryExists = !onlyRecordFailures && directoryProbablyExists(packageDirectory, host); const packageJsonPath = combinePaths(packageDirectory, "package.json"); + if (onlyRecordFailures) { + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + + const existing = state.packageJsonInfoCache?.getPackageJsonInfo(packageJsonPath); + if (existing !== undefined) { + if (typeof existing !== "boolean") { + if (traceEnabled) trace(host, Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + return existing; + } + else { + if (existing && traceEnabled) trace(host, Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); + state.failedLookupLocations.push(packageJsonPath); + return undefined; + } + } + const directoryExists = directoryProbablyExists(packageDirectory, host); if (directoryExists && host.fileExists(packageJsonPath)) { const packageJsonContent = readJson(packageJsonPath, host) as PackageJson; if (traceEnabled) { trace(host, Diagnostics.Found_package_json_at_0, packageJsonPath); } const versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); - return { packageDirectory, packageJsonContent, versionPaths }; + const result = { packageDirectory, packageJsonContent, versionPaths }; + state.packageJsonInfoCache?.setPackageJsonInfo(packageJsonPath, result); + return result; } else { if (directoryExists && traceEnabled) { trace(host, Diagnostics.File_0_does_not_exist, packageJsonPath); } - + state.packageJsonInfoCache?.setPackageJsonInfo(packageJsonPath, directoryExists); // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results state.failedLookupLocations.push(packageJsonPath); } @@ -1448,7 +1633,7 @@ namespace ts { export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); const failedLookupLocations: string[] = []; - const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations }; + const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations, packageJsonInfoCache: cache }; const containingDirectory = getDirectoryPath(containingFile); const resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); @@ -1492,13 +1677,13 @@ namespace ts { * This is the minumum code needed to expose that functionality; the rest is in the host. */ /* @internal */ - export function loadModuleFromGlobalCache(moduleName: string, projectName: string | undefined, compilerOptions: CompilerOptions, host: ModuleResolutionHost, globalCache: string): ResolvedModuleWithFailedLookupLocations { + export function loadModuleFromGlobalCache(moduleName: string, projectName: string | undefined, compilerOptions: CompilerOptions, host: ModuleResolutionHost, globalCache: string, packageJsonInfoCache: PackageJsonInfoCache): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); 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 failedLookupLocations: string[] = []; - const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations }; + const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations, packageJsonInfoCache }; const resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache); } diff --git a/src/compiler/moduleSpecifiers.ts b/src/compiler/moduleSpecifiers.ts index e27f63eb29cda..45b31154344c8 100644 --- a/src/compiler/moduleSpecifiers.ts +++ b/src/compiler/moduleSpecifiers.ts @@ -103,6 +103,9 @@ namespace ts.moduleSpecifiers { const info = getInfo(importingSourceFile.path, host); const moduleSourceFile = getSourceFileOfNode(moduleSymbol.valueDeclaration || getNonAugmentationDeclaration(moduleSymbol)); + if (!moduleSourceFile) { + return []; + } const modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host); const preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); @@ -178,14 +181,13 @@ namespace ts.moduleSpecifiers { function getLocalModuleSpecifier(moduleFileName: string, info: Info, compilerOptions: CompilerOptions, host: ModuleSpecifierResolutionHost, { ending, relativePreference }: Preferences): string { const { baseUrl, paths, rootDirs } = compilerOptions; const { sourceDirectory, getCanonicalFileName } = info; - const relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) || removeExtensionAndIndexPostFix(ensurePathIsNonModuleName(getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); if (!baseUrl && !paths || relativePreference === RelativePreference.Relative) { return relativePath; } - const baseDirectory = getPathsBasePath(compilerOptions, host) || baseUrl!; + const baseDirectory = getNormalizedAbsolutePath(getPathsBasePath(compilerOptions, host) || baseUrl!, host.getCurrentDirectory()); const relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName); if (!relativeToBaseUrl) { return relativePath; @@ -203,7 +205,9 @@ namespace ts.moduleSpecifiers { } if (relativePreference === RelativePreference.ExternalNonRelative) { - const projectDirectory = host.getCurrentDirectory(); + const projectDirectory = compilerOptions.configFilePath ? + toPath(getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) : + info.getCanonicalFileName(host.getCurrentDirectory()); const modulePath = toPath(moduleFileName, projectDirectory, getCanonicalFileName); const sourceIsInternal = startsWith(sourceDirectory, projectDirectory); const targetIsInternal = startsWith(modulePath, projectDirectory); @@ -282,10 +286,12 @@ namespace ts.moduleSpecifiers { const redirects = host.redirectTargetsMap.get(importedPath) || emptyArray; const importedFileNames = [...(referenceRedirect ? [referenceRedirect] : emptyArray), importedFileName, ...redirects]; const targets = importedFileNames.map(f => getNormalizedAbsolutePath(f, cwd)); + let shouldFilterIgnoredPaths = !every(targets, containsIgnoredPath); + if (!preferSymlinks) { // Symlinks inside ignored paths are already filtered out of the symlink cache, // so we only need to remove them from the realpath filenames. - const result = forEach(targets, p => !containsIgnoredPath(p) && cb(p, referenceRedirect === p)); + const result = forEach(targets, p => !(shouldFilterIgnoredPaths && containsIgnoredPath(p)) && cb(p, referenceRedirect === p)); if (result) return result; } const links = host.getSymlinkCache @@ -312,28 +318,27 @@ namespace ts.moduleSpecifiers { for (const symlinkDirectory of symlinkDirectories) { const option = resolvePath(symlinkDirectory, relative); const result = cb(option, target === referenceRedirect); + shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths if (result) return result; } }); }); return result || (preferSymlinks - ? forEach(targets, p => containsIgnoredPath(p) ? undefined : cb(p, p === referenceRedirect)) + ? forEach(targets, p => shouldFilterIgnoredPaths && containsIgnoredPath(p) ? undefined : cb(p, p === referenceRedirect)) : undefined); } - interface ModulePath { - path: string; - isInNodeModules: boolean; - isRedirect: boolean; - } - /** * Looks for existing imports that use symlinks to this module. * Symlinks will be returned first so they are preferred over the real path. */ - function getAllModulePaths(importingFileName: string, importedFileName: string, host: ModuleSpecifierResolutionHost): readonly ModulePath[] { - const cwd = host.getCurrentDirectory(); + function getAllModulePaths(importingFileName: Path, importedFileName: string, host: ModuleSpecifierResolutionHost): readonly ModulePath[] { + const cache = host.getModuleSpecifierCache?.(); const getCanonicalFileName = hostGetCanonicalFileName(host); + if (cache) { + const cached = cache.get(importingFileName, toPath(importedFileName, host.getCurrentDirectory(), getCanonicalFileName)); + if (typeof cached === "object") return cached; + } const allFileNames = new Map(); let importedFileFromNodeModules = false; forEachFileNameOfModule( @@ -352,7 +357,7 @@ namespace ts.moduleSpecifiers { // Sort by paths closest to importing file Name directory const sortedPaths: ModulePath[] = []; for ( - let directory = getDirectoryPath(toPath(importingFileName, cwd, getCanonicalFileName)); + let directory = getDirectoryPath(importingFileName); allFileNames.size !== 0; ) { const directoryStart = ensureTrailingDirectorySeparator(directory); @@ -378,11 +383,15 @@ namespace ts.moduleSpecifiers { if (remainingPaths.length > 1) remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators); sortedPaths.push(...remainingPaths); } + + if (cache) { + cache.set(importingFileName, toPath(importedFileName, host.getCurrentDirectory(), getCanonicalFileName), sortedPaths); + } return sortedPaths; } function tryGetModuleNameFromAmbientModule(moduleSymbol: Symbol, checker: TypeChecker): string | undefined { - const decl = find(moduleSymbol.declarations, + const decl = moduleSymbol.declarations?.find( d => isNonGlobalAmbientModule(d) && (!isExternalModuleAugmentation(d) || !isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(d.name))) ) as (ModuleDeclaration & { name: StringLiteral }) | undefined; if (decl) { @@ -438,7 +447,7 @@ namespace ts.moduleSpecifiers { startsWith(relativeToBaseUrl, prefix) && endsWith(relativeToBaseUrl, suffix) || !suffix && relativeToBaseUrl === removeTrailingDirectorySeparator(prefix)) { - const matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + const matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length - prefix.length); return key.replace("*", matchedStar); } } diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index e27215e7a87c9..a8f917d325b11 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -481,10 +481,12 @@ namespace ts { return visitNodes(cbNode, cbNodes, (node).parameters) || visitNode(cbNode, (node).type); case SyntaxKind.JSDocComment: - return visitNodes(cbNode, cbNodes, (node).tags); + return (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)) + || visitNodes(cbNode, cbNodes, (node as JSDoc).tags); case SyntaxKind.JSDocSeeTag: return visitNode(cbNode, (node as JSDocSeeTag).tagName) || - visitNode(cbNode, (node as JSDocSeeTag).name); + visitNode(cbNode, (node as JSDocSeeTag).name) || + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.JSDocNameReference: return visitNode(cbNode, (node as JSDocNameReference).name); case SyntaxKind.JSDocParameterTag: @@ -492,43 +494,55 @@ namespace ts { return visitNode(cbNode, (node as JSDocTag).tagName) || ((node as JSDocPropertyLikeTag).isNameFirst ? visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).typeExpression) + visitNode(cbNode, (node).typeExpression) || + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)) : visitNode(cbNode, (node).typeExpression) || - visitNode(cbNode, (node).name)); + visitNode(cbNode, (node).name)) || + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.JSDocAuthorTag: - return visitNode(cbNode, (node as JSDocTag).tagName); + return visitNode(cbNode, (node as JSDocTag).tagName) || + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.JSDocImplementsTag: return visitNode(cbNode, (node as JSDocTag).tagName) || - visitNode(cbNode, (node).class); + visitNode(cbNode, (node).class) || + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.JSDocAugmentsTag: return visitNode(cbNode, (node as JSDocTag).tagName) || - visitNode(cbNode, (node).class); + visitNode(cbNode, (node).class) || + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.JSDocTemplateTag: return visitNode(cbNode, (node as JSDocTag).tagName) || visitNode(cbNode, (node).constraint) || - visitNodes(cbNode, cbNodes, (node).typeParameters); + visitNodes(cbNode, cbNodes, (node).typeParameters) || + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.JSDocTypedefTag: return visitNode(cbNode, (node as JSDocTag).tagName) || ((node as JSDocTypedefTag).typeExpression && (node as JSDocTypedefTag).typeExpression!.kind === SyntaxKind.JSDocTypeExpression ? visitNode(cbNode, (node).typeExpression) || - visitNode(cbNode, (node).fullName) + visitNode(cbNode, (node).fullName) || + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)) : visitNode(cbNode, (node).fullName) || - visitNode(cbNode, (node).typeExpression)); + visitNode(cbNode, (node).typeExpression)) || + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.JSDocCallbackTag: return visitNode(cbNode, (node as JSDocTag).tagName) || visitNode(cbNode, (node as JSDocCallbackTag).fullName) || - visitNode(cbNode, (node as JSDocCallbackTag).typeExpression); + visitNode(cbNode, (node as JSDocCallbackTag).typeExpression) || + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.JSDocReturnTag: case SyntaxKind.JSDocTypeTag: case SyntaxKind.JSDocThisTag: case SyntaxKind.JSDocEnumTag: return visitNode(cbNode, (node as JSDocTag).tagName) || - visitNode(cbNode, (node as JSDocReturnTag | JSDocTypeTag | JSDocThisTag | JSDocEnumTag).typeExpression); + visitNode(cbNode, (node as JSDocReturnTag | JSDocTypeTag | JSDocThisTag | JSDocEnumTag).typeExpression) || + (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.JSDocSignature: return forEach((node).typeParameters, cbNode) || forEach((node).parameters, cbNode) || visitNode(cbNode, (node).type); + case SyntaxKind.JSDocLink: + return visitNode(cbNode, (node as JSDocLink).name); case SyntaxKind.JSDocTypeLiteral: return forEach((node as JSDocTypeLiteral).jsDocPropertyTags, cbNode); case SyntaxKind.JSDocTag: @@ -537,7 +551,9 @@ namespace ts { case SyntaxKind.JSDocPrivateTag: case SyntaxKind.JSDocProtectedTag: case SyntaxKind.JSDocReadonlyTag: - return visitNode(cbNode, (node as JSDocTag).tagName); + case SyntaxKind.JSDocDeprecatedTag: + return visitNode(cbNode, (node as JSDocTag).tagName) + || (typeof (node as JSDoc).comment === "string" ? undefined : visitNodes(cbNode, cbNodes, (node as JSDoc).comment as NodeArray | undefined)); case SyntaxKind.PartiallyEmittedExpression: return visitNode(cbNode, (node).expression); } @@ -819,7 +835,7 @@ namespace ts { scriptKind = ensureScriptKind(fileName, scriptKind); if (scriptKind === ScriptKind.JSON) { const result = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); - convertToObjectWorker(result, result.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + convertToObjectWorker(result, result.statements[0]?.expression, result.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); result.referencedFiles = emptyArray; result.typeReferenceDirectives = emptyArray; result.libReferenceDirectives = emptyArray; @@ -862,36 +878,56 @@ namespace ts { endOfFileToken = parseTokenNode(); } else { - let expression; - switch (token()) { - case SyntaxKind.OpenBracketToken: - expression = parseArrayLiteralExpression(); - break; - case SyntaxKind.TrueKeyword: - case SyntaxKind.FalseKeyword: - case SyntaxKind.NullKeyword: - expression = parseTokenNode(); - break; - case SyntaxKind.MinusToken: - if (lookAhead(() => nextToken() === SyntaxKind.NumericLiteral && nextToken() !== SyntaxKind.ColonToken)) { - expression = parsePrefixUnaryExpression() as JsonMinusNumericLiteral; - } - else { + // Loop and synthesize an ArrayLiteralExpression if there are more than + // one top-level expressions to ensure all input text is consumed. + let expressions: Expression[] | Expression | undefined; + while (token() !== SyntaxKind.EndOfFileToken) { + let expression; + switch (token()) { + case SyntaxKind.OpenBracketToken: + expression = parseArrayLiteralExpression(); + break; + case SyntaxKind.TrueKeyword: + case SyntaxKind.FalseKeyword: + case SyntaxKind.NullKeyword: + expression = parseTokenNode(); + break; + case SyntaxKind.MinusToken: + if (lookAhead(() => nextToken() === SyntaxKind.NumericLiteral && nextToken() !== SyntaxKind.ColonToken)) { + expression = parsePrefixUnaryExpression() as JsonMinusNumericLiteral; + } + else { + expression = parseObjectLiteralExpression(); + } + break; + case SyntaxKind.NumericLiteral: + case SyntaxKind.StringLiteral: + if (lookAhead(() => nextToken() !== SyntaxKind.ColonToken)) { + expression = parseLiteralNode() as StringLiteral | NumericLiteral; + break; + } + // falls through + default: expression = parseObjectLiteralExpression(); - } - break; - case SyntaxKind.NumericLiteral: - case SyntaxKind.StringLiteral: - if (lookAhead(() => nextToken() !== SyntaxKind.ColonToken)) { - expression = parseLiteralNode() as StringLiteral | NumericLiteral; break; + } + + // Error recovery: collect multiple top-level expressions + if (expressions && isArray(expressions)) { + expressions.push(expression); + } + else if (expressions) { + expressions = [expressions, expression]; + } + else { + expressions = expression; + if (token() !== SyntaxKind.EndOfFileToken) { + parseErrorAtCurrentToken(Diagnostics.Unexpected_token); } - // falls through - default: - expression = parseObjectLiteralExpression(); - break; + } } + const expression = isArray(expressions) ? finishNode(factory.createArrayLiteralExpression(expressions), pos) : Debug.checkDefined(expressions); const statement = factory.createExpressionStatement(expression) as JsonObjectExpressionStatement; finishNode(statement, pos); statements = createNodeArray([statement], pos); @@ -979,7 +1015,7 @@ namespace ts { jsDocDiagnostics = undefined!; parsingContext = 0; identifiers = undefined!; - notParenthesizedArrow = undefined!; + notParenthesizedArrow = undefined; topLevel = true; } @@ -2057,8 +2093,7 @@ namespace ts { while (!isListTerminator(kind)) { if (isListElement(kind, /*inErrorRecovery*/ false)) { - const element = parseListElement(kind, parseElement); - list.push(element); + list.push(parseListElement(kind, parseElement)); continue; } @@ -2939,9 +2974,16 @@ namespace ts { function parseParameterWorker(inOuterAwaitContext: boolean): ParameterDeclaration { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); + + // FormalParameter [Yield,Await]: + // BindingElement[?Yield,?Await] + + // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. + const decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); + if (token() === SyntaxKind.ThisKeyword) { const node = factory.createParameterDeclaration( - /*decorators*/ undefined, + decorators, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), @@ -2949,14 +2991,14 @@ namespace ts { parseTypeAnnotation(), /*initializer*/ undefined ); + + if (decorators) { + parseErrorAtRange(decorators[0], Diagnostics.Decorators_may_not_be_applied_to_this_parameters); + } + return withJSDoc(finishNode(node, pos), hasJSDoc); } - // FormalParameter [Yield,Await]: - // BindingElement[?Yield,?Await] - - // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. - const decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators(); const savedTopLevel = topLevel; topLevel = false; const modifiers = parseModifiers(); @@ -3178,7 +3220,10 @@ namespace ts { function isTypeMemberStart(): boolean { // Return true if we have the start of a signature member - if (token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.LessThanToken) { + if (token() === SyntaxKind.OpenParenToken || + token() === SyntaxKind.LessThanToken || + token() === SyntaxKind.GetKeyword || + token() === SyntaxKind.SetKeyword) { return true; } let idToken = false; @@ -3219,6 +3264,14 @@ namespace ts { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); const modifiers = parseModifiers(); + if (parseContextualModifier(SyntaxKind.GetKeyword)) { + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, SyntaxKind.GetAccessor); + } + + if (parseContextualModifier(SyntaxKind.SetKeyword)) { + return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, SyntaxKind.SetAccessor); + } + if (isIndexSignature()) { return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers); } @@ -5541,6 +5594,7 @@ namespace ts { // STATEMENTS function parseBlock(ignoreMissingOpenBrace: boolean, diagnosticMessage?: DiagnosticMessage): Block { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); const openBracePosition = scanner.getTokenPos(); if (parseExpected(SyntaxKind.OpenBraceToken, diagnosticMessage) || ignoreMissingOpenBrace) { const multiLine = scanner.hasPrecedingLineBreak(); @@ -5554,11 +5608,17 @@ namespace ts { ); } } - return finishNode(factory.createBlock(statements, multiLine), pos); + const result = withJSDoc(finishNode(factory.createBlock(statements, multiLine), pos), hasJSDoc); + if (token() === SyntaxKind.EqualsToken) { + parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses); + nextToken(); + } + + return result; } else { const statements = createMissingList(); - return finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos); + return withJSDoc(finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos), hasJSDoc); } } @@ -5594,23 +5654,26 @@ namespace ts { function parseEmptyStatement(): Statement { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(SyntaxKind.SemicolonToken); - return finishNode(factory.createEmptyStatement(), pos); + return withJSDoc(finishNode(factory.createEmptyStatement(), pos), hasJSDoc); } function parseIfStatement(): IfStatement { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(SyntaxKind.IfKeyword); parseExpected(SyntaxKind.OpenParenToken); const expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.CloseParenToken); const thenStatement = parseStatement(); const elseStatement = parseOptional(SyntaxKind.ElseKeyword) ? parseStatement() : undefined; - return finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos); + return withJSDoc(finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc); } function parseDoStatement(): DoStatement { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(SyntaxKind.DoKeyword); const statement = parseStatement(); parseExpected(SyntaxKind.WhileKeyword); @@ -5623,21 +5686,23 @@ namespace ts { // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. parseOptional(SyntaxKind.SemicolonToken); - return finishNode(factory.createDoStatement(statement, expression), pos); + return withJSDoc(finishNode(factory.createDoStatement(statement, expression), pos), hasJSDoc); } function parseWhileStatement(): WhileStatement { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(SyntaxKind.WhileKeyword); parseExpected(SyntaxKind.OpenParenToken); const expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.CloseParenToken); const statement = parseStatement(); - return finishNode(factory.createWhileStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWhileStatement(expression, statement), pos), hasJSDoc); } function parseForOrForInOrForOfStatement(): Statement { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(SyntaxKind.ForKeyword); const awaitToken = parseOptionalToken(SyntaxKind.AwaitKeyword); parseExpected(SyntaxKind.OpenParenToken); @@ -5676,11 +5741,12 @@ namespace ts { node = factory.createForStatement(initializer, condition, incrementor, parseStatement()); } - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos) as ForStatement | ForInOrOfStatement, hasJSDoc); } function parseBreakOrContinueStatement(kind: SyntaxKind): BreakOrContinueStatement { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(kind === SyntaxKind.BreakStatement ? SyntaxKind.BreakKeyword : SyntaxKind.ContinueKeyword); const label = canParseSemicolon() ? undefined : parseIdentifier(); @@ -5689,25 +5755,27 @@ namespace ts { const node = kind === SyntaxKind.BreakStatement ? factory.createBreakStatement(label) : factory.createContinueStatement(label); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseReturnStatement(): ReturnStatement { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(SyntaxKind.ReturnKeyword); const expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression); parseSemicolon(); - return finishNode(factory.createReturnStatement(expression), pos); + return withJSDoc(finishNode(factory.createReturnStatement(expression), pos), hasJSDoc); } function parseWithStatement(): WithStatement { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(SyntaxKind.WithKeyword); parseExpected(SyntaxKind.OpenParenToken); const expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.CloseParenToken); const statement = doInsideOfContext(NodeFlags.InWithStatement, parseStatement); - return finishNode(factory.createWithStatement(expression, statement), pos); + return withJSDoc(finishNode(factory.createWithStatement(expression, statement), pos), hasJSDoc); } function parseCaseClause(): CaseClause { @@ -5741,12 +5809,13 @@ namespace ts { function parseSwitchStatement(): SwitchStatement { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(SyntaxKind.SwitchKeyword); parseExpected(SyntaxKind.OpenParenToken); const expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.CloseParenToken); const caseBlock = parseCaseBlock(); - return finishNode(factory.createSwitchStatement(expression, caseBlock), pos); + return withJSDoc(finishNode(factory.createSwitchStatement(expression, caseBlock), pos), hasJSDoc); } function parseThrowStatement(): ThrowStatement { @@ -5754,6 +5823,7 @@ namespace ts { // throw [no LineTerminator here]Expression[In, ?Yield]; const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(SyntaxKind.ThrowKeyword); // Because of automatic semicolon insertion, we need to report error if this @@ -5767,12 +5837,13 @@ namespace ts { expression = finishNode(factory.createIdentifier(""), getNodePos()); } parseSemicolon(); - return finishNode(factory.createThrowStatement(expression), pos); + return withJSDoc(finishNode(factory.createThrowStatement(expression), pos), hasJSDoc); } // TODO: Review for error recovery function parseTryStatement(): TryStatement { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(SyntaxKind.TryKeyword); const tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); @@ -5786,7 +5857,7 @@ namespace ts { finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } - return finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos); + return withJSDoc(finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); } function parseCatchClause(): CatchClause { @@ -5809,9 +5880,10 @@ namespace ts { function parseDebuggerStatement(): Statement { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(SyntaxKind.DebuggerKeyword); parseSemicolon(); - return finishNode(factory.createDebuggerStatement(), pos); + return withJSDoc(finishNode(factory.createDebuggerStatement(), pos), hasJSDoc); } function parseExpressionOrLabeledStatement(): ExpressionStatement | LabeledStatement { @@ -6259,6 +6331,7 @@ namespace ts { function parseVariableDeclaration(allowExclamation?: boolean): VariableDeclaration { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); const name = parseIdentifierOrPattern(Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations); let exclamationToken: ExclamationToken | undefined; if (allowExclamation && name.kind === SyntaxKind.Identifier && @@ -6268,7 +6341,7 @@ namespace ts { const type = parseTypeAnnotation(); const initializer = isInOrOfKeyword(token()) ? undefined : parseInitializer(); const node = factory.createVariableDeclaration(name, exclamationToken, type, initializer); - return finishNode(node, pos); + return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseVariableDeclarationList(inForStatementInitializer: boolean): VariableDeclarationList { @@ -7297,7 +7370,10 @@ namespace ts { let tags: JSDocTag[]; let tagsPos: number; let tagsEnd: number; - const comments: string[] = []; + let linkEnd: number; + let commentsPos: number | undefined; + let comments: string[] = []; + const parts: (JSDocLink | JSDocText)[] = []; // + 3 for leading /**, - 5 in total for /** */ return scanner.scanRange(start + 3, length - 5, () => { @@ -7327,6 +7403,7 @@ namespace ts { case SyntaxKind.AtToken: if (state === JSDocState.BeginningOfLine || state === JSDocState.SawAsterisk) { removeTrailingWhitespace(comments); + if (!commentsPos) commentsPos = getNodePos(); addTag(parseTag(indent)); // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning @@ -7369,6 +7446,22 @@ namespace ts { break; case SyntaxKind.EndOfFileToken: break loop; + case SyntaxKind.OpenBraceToken: + state = JSDocState.SavingComments; + const commentEnd = scanner.getStartPos(); + const linkStart = scanner.getTextPos() - 1; + const link = parseJSDocLink(linkStart); + if (link) { + if (!linkEnd) { + removeLeadingNewlines(comments); + } + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd ?? start, commentEnd)); + parts.push(link); + comments = []; + linkEnd = scanner.getTextPos(); + break; + } + // fallthrough if it's not a {@link sequence default: // 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 @@ -7379,9 +7472,13 @@ namespace ts { } nextTokenJSDoc(); } - removeLeadingNewlines(comments); removeTrailingWhitespace(comments); - return createJSDocComment(); + if (parts.length && comments.length) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd ?? start, commentsPos)); + } + if (parts.length && tags) Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); + const tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); + return finishNode(factory.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : comments.length ? comments.join("") : undefined, tagsArray), start, end); }); function removeLeadingNewlines(comments: string[]) { @@ -7396,12 +7493,6 @@ namespace ts { } } - function createJSDocComment(): JSDoc { - const comment = comments.length ? comments.join("") : undefined; - const tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); - return finishNode(factory.createJSDocComment(comment, tagsArray), start, end); - } - function isNextNonwhitespaceTokenEndOfFile(): boolean { // We must use infinite lookahead, as there could be any number of newlines :( while (true) { @@ -7487,6 +7578,9 @@ namespace ts { case "readonly": tag = parseSimpleTag(start, factory.createJSDocReadonlyTag, tagName, margin, indentText); break; + case "override": + tag = parseSimpleTag(start, factory.createJSDocOverrideTag, tagName, margin, indentText); + break; case "deprecated": hasDeprecatedTag = true; tag = parseSimpleTag(start, factory.createJSDocDeprecatedTag, tagName, margin, indentText); @@ -7535,8 +7629,11 @@ namespace ts { return parseTagComments(margin, indentText.slice(margin)); } - function parseTagComments(indent: number, initialMargin?: string): string | undefined { - const comments: string[] = []; + function parseTagComments(indent: number, initialMargin?: string): string | NodeArray | undefined { + const commentsPos = getNodePos(); + let comments: string[] = []; + const parts: (JSDocLink | JSDocText)[] = []; + let linkEnd; let state = JSDocState.BeginningOfLine; let previousWhitespace = true; let margin: number | undefined; @@ -7564,8 +7661,9 @@ namespace ts { indent = 0; break; case SyntaxKind.AtToken: - if (state === JSDocState.SavingBackticks || !previousWhitespace && state === JSDocState.SavingComments) { - // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace + if (state === JSDocState.SavingBackticks + || state === JSDocState.SavingComments && (!previousWhitespace || lookAhead(isNextJSDocTokenWhitespace))) { + // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace or not before whitespace comments.push(scanner.getTokenText()); break; } @@ -7589,13 +7687,18 @@ namespace ts { break; case SyntaxKind.OpenBraceToken: state = JSDocState.SavingComments; - if (lookAhead(() => nextTokenJSDoc() === SyntaxKind.AtToken && tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link")) { - pushComment(scanner.getTokenText()); - nextTokenJSDoc(); + const commentEnd = scanner.getStartPos(); + const linkStart = scanner.getTextPos() - 1; + const link = parseJSDocLink(linkStart); + if (link) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd ?? commentsPos, commentEnd)); + parts.push(link); + comments = []; + linkEnd = scanner.getTextPos(); + } + else { pushComment(scanner.getTokenText()); - nextTokenJSDoc(); } - pushComment(scanner.getTokenText()); break; case SyntaxKind.BacktickToken: if (state === JSDocState.SavingBackticks) { @@ -7628,12 +7731,50 @@ namespace ts { removeLeadingNewlines(comments); removeTrailingWhitespace(comments); - return comments.length === 0 ? undefined : comments.join(""); + if (parts.length) { + if (comments.length) { + parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd ?? commentsPos)); + } + return createNodeArray(parts, commentsPos, scanner.getTextPos()); + } + else if (comments.length) { + return comments.join(""); + } + } + + function isNextJSDocTokenWhitespace() { + const next = nextTokenJSDoc(); + return next === SyntaxKind.WhitespaceTrivia || next === SyntaxKind.NewLineTrivia; + } + + function parseJSDocLink(start: number) { + if (!tryParse(parseJSDocLinkPrefix)) { + return undefined; + } + nextTokenJSDoc(); // start at token after link, then skip any whitespace + skipWhitespace(); + // parseEntityName logs an error for non-identifier, so create a MissingNode ourselves to avoid the error + const name = tokenIsIdentifierOrKeyword(token()) + ? parseEntityName(/*allowReservedWords*/ true) + : undefined; + const text = []; + while (token() !== SyntaxKind.CloseBraceToken && token() !== SyntaxKind.NewLineTrivia && token() !== SyntaxKind.EndOfFileToken) { + text.push(scanner.getTokenText()); + nextTokenJSDoc(); + } + return finishNode(factory.createJSDocLink(name, text.join("")), start, scanner.getTextPos()); + } + + function parseJSDocLinkPrefix() { + skipWhitespaceOrAsterisk(); + return token() === SyntaxKind.OpenBraceToken + && nextTokenJSDoc() === SyntaxKind.AtToken + && tokenIsIdentifierOrKeyword(nextTokenJSDoc()) + && scanner.getTokenValue() === "link"; } function parseUnknownTag(start: number, tagName: Identifier, indent: number, indentText: string) { - const end = getNodePos(); - return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function addTag(tag: JSDocTag | undefined): void { @@ -7699,7 +7840,7 @@ namespace ts { const { name, isBracketed } = parseBracketNameInPropertyAndParamTag(); const indentText = skipWhitespaceOrAsterisk(); - if (isNameFirst) { + if (isNameFirst && !lookAhead(parseJSDocLinkPrefix)) { typeExpression = tryParseTypeExpression(); } @@ -7739,8 +7880,7 @@ namespace ts { } const typeExpression = tryParseTypeExpression(); - const end = getNodePos(); - return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function parseTypeTag(start: number, tagName: Identifier, indent?: number, indentText?: string): JSDocTypeTag { @@ -7749,24 +7889,32 @@ namespace ts { } const typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); - const end = getNodePos(); - const comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined; - return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start, end); + const comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; + return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start); } function parseSeeTag(start: number, tagName: Identifier, indent?: number, indentText?: string): JSDocSeeTag { - const nameExpression = parseJSDocNameReference(); - const end = getNodePos(); - const comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined; - return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start, end); + const isLink = lookAhead(() => nextTokenJSDoc() === SyntaxKind.AtToken && tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link"); + const nameExpression = isLink ? undefined : parseJSDocNameReference(); + const comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; + return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start); } function parseAuthorTag(start: number, tagName: Identifier, indent: number, indentText: string): JSDocAuthorTag { - const comments = parseAuthorNameAndEmail() + (parseTrailingTagComments(start, end, indent, indentText) || ""); - return finishNode(factory.createJSDocAuthorTag(tagName, comments || undefined), start); + const commentStart = getNodePos(); + const textOnly = parseAuthorNameAndEmail(); + let commentEnd = scanner.getStartPos(); + const comments = parseTrailingTagComments(start, commentEnd, indent, indentText); + if (!comments) { + commentEnd = scanner.getStartPos(); + } + const allParts = typeof comments !== "string" + ? createNodeArray(concatenate([finishNode(textOnly, commentStart, commentEnd)], comments) as (JSDocText | JSDocLink)[], commentStart) // cast away readonly + : textOnly.text + comments; + return finishNode(factory.createJSDocAuthorTag(tagName, allParts), start); } - function parseAuthorNameAndEmail(): string { + function parseAuthorNameAndEmail(): JSDocText { const comments: string[] = []; let inEmail = false; let token = scanner.getToken(); @@ -7786,19 +7934,17 @@ namespace ts { token = nextTokenJSDoc(); } - return comments.join(""); + return factory.createJSDocText(comments.join("")); } function parseImplementsTag(start: number, tagName: Identifier, margin: number, indentText: string): JSDocImplementsTag { const className = parseExpressionWithTypeArgumentsForAugments(); - const end = getNodePos(); - return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseAugmentsTag(start: number, tagName: Identifier, margin: number, indentText: string): JSDocAugmentsTag { const className = parseExpressionWithTypeArgumentsForAugments(); - const end = getNodePos(); - return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseExpressionWithTypeArgumentsForAugments(): ExpressionWithTypeArguments & { expression: Identifier | PropertyAccessEntityNameExpression } { @@ -7824,23 +7970,20 @@ namespace ts { return node; } - function parseSimpleTag(start: number, createTag: (tagName: Identifier | undefined, comment?: string) => JSDocTag, tagName: Identifier, margin: number, indentText: string): JSDocTag { - const end = getNodePos(); - return finishNode(createTag(tagName, parseTrailingTagComments(start, end, margin, indentText)), start, end); + function parseSimpleTag(start: number, createTag: (tagName: Identifier | undefined, comment?: string | NodeArray) => JSDocTag, tagName: Identifier, margin: number, indentText: string): JSDocTag { + return finishNode(createTag(tagName, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseThisTag(start: number, tagName: Identifier, margin: number, indentText: string): JSDocThisTag { const typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); - const end = getNodePos(); - return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseEnumTag(start: number, tagName: Identifier, margin: number, indentText: string): JSDocEnumTag { const typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); - const end = getNodePos(); - return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end); + return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); } function parseTypedefTag(start: number, tagName: Identifier, indent: number, indentText: string): JSDocTypedefTag { @@ -7951,11 +8094,10 @@ namespace ts { } }); const typeExpression = finishNode(factory.createJSDocSignature(/*typeParameters*/ undefined, parameters, returnTag), start); - const end = getNodePos(); if (!comment) { - comment = parseTrailingTagComments(start, end, indent, indentText); + comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); } - return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start, end); + return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start); } function escapedTextsEqual(a: EntityName, b: EntityName): boolean { @@ -8043,6 +8185,9 @@ namespace ts { function parseTemplateTagTypeParameter() { const typeParameterPos = getNodePos(); const name = parseJSDocIdentifierName(Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); + if (nodeIsMissing(name)) { + return undefined; + } return finishNode(factory.createTypeParameterDeclaration(name, /*constraint*/ undefined, /*defaultType*/ undefined), typeParameterPos); } @@ -8051,7 +8196,10 @@ namespace ts { const typeParameters = []; do { skipWhitespace(); - typeParameters.push(parseTemplateTagTypeParameter()); + const node = parseTemplateTagTypeParameter(); + if (node !== undefined) { + typeParameters.push(node); + } skipWhitespaceOrAsterisk(); } while (parseOptionalJsdoc(SyntaxKind.CommaToken)); return createNodeArray(typeParameters, pos); @@ -8071,8 +8219,7 @@ namespace ts { // TODO: Consider only parsing a single type parameter if there is a constraint. const constraint = token() === SyntaxKind.OpenBraceToken ? parseJSDocTypeExpression() : undefined; const typeParameters = parseTemplateTagTypeParameters(); - const end = getNodePos(); - return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, end, indent, indentText)), start, end); + return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); } function parseOptionalJsdoc(t: JSDocSyntaxKind): boolean { diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 8cf16a806ecfd..a50b60a3171b2 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -656,46 +656,33 @@ namespace ts { fileExists: (fileName: string) => boolean, hasInvalidatedResolution: HasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: HasChangedAutomaticTypeDirectiveNames | undefined, + getParsedCommandLine: (fileName: string) => ParsedCommandLine | undefined, projectReferences: readonly ProjectReference[] | 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?.()) { - return false; - } + if (!program || hasChangedAutomaticTypeDirectiveNames?.()) return false; // If root file names don't match - if (!arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) { - return false; - } + if (!arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) return false; let seenResolvedRefs: ResolvedProjectReference[] | undefined; // If project references don't match - if (!arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { - return false; - } + 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; - } + if (program.getSourceFiles().some(sourceFileNotUptoDate)) return false; // If any of the missing file paths are now created - if (program.getMissingFilePaths().some(fileExists)) { - return false; - } + if (program.getMissingFilePaths().some(fileExists)) return false; const currentOptions = program.getCompilerOptions(); // If the compilation settings do no match, then the program is not up-to-date - if (!compareDataObjects(currentOptions, newOptions)) { - return false; - } + if (!compareDataObjects(currentOptions, newOptions)) return false; // If everything matches but the text of config file is changed, // error locations can change for program options, so update the program - if (currentOptions.configFile && newOptions.configFile) { - return currentOptions.configFile.text === newOptions.configFile.text; - } + if (currentOptions.configFile && newOptions.configFile) return currentOptions.configFile.text === newOptions.configFile.text; return true; @@ -709,23 +696,26 @@ namespace ts { } function projectReferenceUptoDate(oldRef: ProjectReference, newRef: ProjectReference, index: number) { - if (!projectReferenceIsEqualTo(oldRef, newRef)) { - return false; - } - return resolvedProjectReferenceUptoDate(program!.getResolvedProjectReferences()![index], oldRef); + return projectReferenceIsEqualTo(oldRef, newRef) && + resolvedProjectReferenceUptoDate(program!.getResolvedProjectReferences()![index], oldRef); } function resolvedProjectReferenceUptoDate(oldResolvedRef: ResolvedProjectReference | undefined, oldRef: ProjectReference): boolean { if (oldResolvedRef) { - if (contains(seenResolvedRefs, oldResolvedRef)) { // Assume true - return true; - } + if (contains(seenResolvedRefs, oldResolvedRef)) return true; - // If sourceFile for the oldResolvedRef existed, check the version for uptodate - if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { - return false; - } + const refPath = resolveProjectReferencePath(oldRef); + const newParsedCommandLine = getParsedCommandLine(refPath); + + // Check if config file exists + if (!newParsedCommandLine) return false; + + // If change in source file + if (oldResolvedRef.commandLine.options.configFile !== newParsedCommandLine.options.configFile) return false; + + // check file names + if (!arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newParsedCommandLine.fileNames)) return false; // Add to seen before checking the referenced paths of this config file (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); @@ -737,7 +727,8 @@ namespace ts { // In old program, not able to resolve project reference path, // so if config file doesnt exist, it is uptodate. - return !fileExists(resolveProjectReferencePath(oldRef)); + const refPath = resolveProjectReferencePath(oldRef); + return !getParsedCommandLine(refPath); } } @@ -852,6 +843,7 @@ namespace ts { let _compilerOptionsObjectLiteralSyntax: ObjectLiteralExpression | false | undefined; let moduleResolutionCache: ModuleResolutionCache | undefined; + let typeReferenceDirectiveResolutionCache: TypeReferenceDirectiveResolutionCache | undefined; let actualResolveModuleNamesWorker: (moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference) => ResolvedModuleFull[]; const hasInvalidatedResolution = host.hasInvalidatedResolution || returnFalse; if (host.resolveModuleNames) { @@ -866,7 +858,7 @@ namespace ts { }); } else { - moduleResolutionCache = createModuleResolutionCache(currentDirectory, x => host.getCanonicalFileName(x), options); + moduleResolutionCache = createModuleResolutionCache(currentDirectory, getCanonicalFileName, options); const loader = (moduleName: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule!; // TODO: GH#18217 actualResolveModuleNamesWorker = (moduleNames, containingFile, _reusedNames, redirectedReference) => loadWithLocalCache(Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader); } @@ -876,7 +868,15 @@ namespace ts { actualResolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference) => host.resolveTypeReferenceDirectives!(Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); } else { - const loader = (typesRef: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective!; // TODO: GH#18217 + typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache?.getPackageJsonInfoCache()); + const loader = (typesRef: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveTypeReferenceDirective( + typesRef, + containingFile, + options, + host, + redirectedReference, + typeReferenceDirectiveResolutionCache, + ).resolvedTypeReferenceDirective!; // TODO: GH#18217 actualResolveTypeReferenceDirectiveNamesWorker = (typeReferenceDirectiveNames, containingFile, redirectedReference) => loadWithLocalCache(Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader); } @@ -1021,13 +1021,32 @@ namespace ts { host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); } } - oldProgram.forEachResolvedProjectReference(resolvedProjectReference => { - if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { - host.onReleaseOldSourceFile!(resolvedProjectReference.sourceFile, oldProgram!.getCompilerOptions(), /*hasSourceFileByPath*/ false); + if (!host.getParsedCommandLine) { + oldProgram.forEachResolvedProjectReference(resolvedProjectReference => { + if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { + host.onReleaseOldSourceFile!(resolvedProjectReference.sourceFile, oldProgram!.getCompilerOptions(), /*hasSourceFileByPath*/ false); + } + }); + } + } + + // Release commandlines that new program does not use + if (oldProgram && host.onReleaseParsedCommandLine) { + forEachProjectReference( + oldProgram.getProjectReferences(), + oldProgram.getResolvedProjectReferences(), + (oldResolvedRef, parent, index) => { + const oldReference = parent?.commandLine.projectReferences![index] || oldProgram!.getProjectReferences()![index]; + const oldRefPath = resolveProjectReferencePath(oldReference); + if (!projectReferenceRedirects?.has(toPath(oldRefPath))) { + host.onReleaseParsedCommandLine!(oldRefPath, oldResolvedRef, oldProgram!.getCompilerOptions()); + } } - }); + ); } + typeReferenceDirectiveResolutionCache = undefined; + // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; @@ -1057,7 +1076,6 @@ namespace ts { getNodeCount: () => getDiagnosticsProducingTypeChecker().getNodeCount(), getIdentifierCount: () => getDiagnosticsProducingTypeChecker().getIdentifierCount(), getSymbolCount: () => getDiagnosticsProducingTypeChecker().getSymbolCount(), - getTypeCatalog: () => getDiagnosticsProducingTypeChecker().getTypeCatalog(), getTypeCount: () => getDiagnosticsProducingTypeChecker().getTypeCount(), getInstantiationCount: () => getDiagnosticsProducingTypeChecker().getInstantiationCount(), getRelationCacheSizes: () => getDiagnosticsProducingTypeChecker().getRelationCacheSizes(), @@ -1368,7 +1386,9 @@ namespace ts { const newResolvedRef = parseProjectReferenceConfigFile(newRef); if (oldResolvedRef) { // Resolved project reference has gone missing or changed - return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; + return !newResolvedRef || + newResolvedRef.sourceFile !== oldResolvedRef.sourceFile || + !arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newResolvedRef.commandLine.fileNames); } else { // A previously-unresolved reference may be resolved now @@ -2139,6 +2159,7 @@ namespace ts { case SyntaxKind.ReadonlyKeyword: case SyntaxKind.DeclareKeyword: case SyntaxKind.AbstractKeyword: + case SyntaxKind.OverrideKeyword: diagnostics.push(createDiagnosticForNode(modifier, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, tokenToString(modifier.kind))); break; @@ -2886,6 +2907,7 @@ namespace ts { const moduleNames = getModuleNames(file); const resolutions = resolveModuleNamesReusingOldState(moduleNames, file); Debug.assert(resolutions.length === moduleNames.length); + const optionsForFile = (useSourceOfProjectReferenceRedirect ? getRedirectReferenceForResolution(file)?.commandLine.options : undefined) || options; for (let index = 0; index < moduleNames.length; index++) { const resolution = resolutions[index]; setResolvedModule(file, moduleNames[index], resolution); @@ -2912,11 +2934,11 @@ namespace ts { // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') // This may still end up being an untyped module -- the file won't be included but imports will be allowed. const shouldAddFile = resolvedFileName - && !getResolutionDiagnostic(options, resolution) - && !options.noResolve + && !getResolutionDiagnostic(optionsForFile, resolution) + && !optionsForFile.noResolve && index < file.imports.length && !elideImport - && !(isJsFile && !getAllowJSCompilerOption(options)) + && !(isJsFile && !getAllowJSCompilerOption(optionsForFile)) && (isInJSFile(file.imports[index]) || !(file.imports[index].flags & NodeFlags.JSDoc)); if (elideImport) { @@ -3195,9 +3217,10 @@ namespace ts { } } - // there has to be common source directory if user specified --outdir || --sourceRoot + // there has to be common source directory if user specified --outdir || --rootDir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted if (options.outDir || // there is --outDir specified + options.rootDir || // there is --rootDir specified options.sourceRoot || // there is --sourceRoot specified options.mapRoot) { // there is --mapRoot specified diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index 68c32d26c5930..617fb795ee66f 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -153,9 +153,9 @@ namespace ts { const resolvedFileToResolution = createMultiMap(); let hasChangedAutomaticTypeDirectiveNames = false; - const failedLookupChecks: Path[] = []; - const startsWithPathChecks: Path[] = []; - const isInDirectoryChecks: Path[] = []; + let failedLookupChecks: Path[] | undefined; + let startsWithPathChecks: Set | undefined; + let isInDirectoryChecks: Path[] | undefined; const getCurrentDirectory = memoize(() => resolutionHost.getCurrentDirectory!()); // TODO: GH#18217 const cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); @@ -166,15 +166,23 @@ namespace ts { const resolvedModuleNames = new Map>(); const perDirectoryResolvedModuleNames: CacheWithRedirects> = createCacheWithRedirects(); const nonRelativeModuleNameCache: CacheWithRedirects = createCacheWithRedirects(); - const moduleResolutionCache = createModuleResolutionCacheWithMaps( + const moduleResolutionCache = createModuleResolutionCache( + getCurrentDirectory(), + resolutionHost.getCanonicalFileName, + /*options*/ undefined, perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, - getCurrentDirectory(), - resolutionHost.getCanonicalFileName ); const resolvedTypeReferenceDirectives = new Map>(); const perDirectoryResolvedTypeReferenceDirectives: CacheWithRedirects> = createCacheWithRedirects(); + const typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache( + getCurrentDirectory(), + resolutionHost.getCanonicalFileName, + /*options*/ undefined, + moduleResolutionCache.getPackageJsonInfoCache(), + perDirectoryResolvedTypeReferenceDirectives + ); /** * These are the extensions that failed lookup files will have by default, @@ -240,9 +248,9 @@ namespace ts { resolvedTypeReferenceDirectives.clear(); resolvedFileToResolution.clear(); resolutionsWithFailedLookups.length = 0; - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) clearPerDirectoryResolutions(); @@ -284,9 +292,8 @@ namespace ts { } function clearPerDirectoryResolutions() { - perDirectoryResolvedModuleNames.clear(); - nonRelativeModuleNameCache.clear(); - perDirectoryResolvedTypeReferenceDirectives.clear(); + moduleResolutionCache.clear(); + typeReferenceDirectiveResolutionCache.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } @@ -320,7 +327,9 @@ namespace ts { resolutionHost.projectName, compilerOptions, host, - globalCache); + globalCache, + moduleResolutionCache, + ); if (resolvedModule) { // Modify existing resolution so its saved in the directory cache as well (primaryResult.resolvedModule as any) = resolvedModule; @@ -333,6 +342,10 @@ namespace ts { return primaryResult; } + function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): CachedResolvedTypeReferenceDirectiveWithFailedLookupLocations { + return ts.resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache); + } + interface ResolveNamesWithLocalCacheInput { names: readonly string[]; containingFile: string; @@ -753,7 +766,7 @@ namespace ts { if (isCreatingWatchedDirectory) { // Watching directory is created // Invalidate any resolution has failed lookup in this directory - isInDirectoryChecks.push(fileOrDirectoryPath); + (isInDirectoryChecks ||= []).push(fileOrDirectoryPath); } else { // If something to do with folder/file starting with "." in node_modules folder, skip it @@ -772,8 +785,8 @@ namespace ts { if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory - failedLookupChecks.push(fileOrDirectoryPath); - startsWithPathChecks.push(fileOrDirectoryPath); + (failedLookupChecks ||= []).push(fileOrDirectoryPath); + (startsWithPathChecks ||= new Set()).add(fileOrDirectoryPath); } else { if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { @@ -784,21 +797,27 @@ namespace ts { return false; } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created - failedLookupChecks.push(fileOrDirectoryPath); + (failedLookupChecks ||= []).push(fileOrDirectoryPath); + + // If the invalidated file is from a node_modules package, invalidate everything else + // in the package since we might not get notifications for other files in the package. + // This hardens our logic against unreliable file watchers. + const packagePath = parseNodeModuleFromPath(fileOrDirectoryPath); + if (packagePath) (startsWithPathChecks ||= new Set()).add(packagePath as Path); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } function invalidateResolutionsOfFailedLookupLocations() { - if (!failedLookupChecks.length && !startsWithPathChecks.length && !isInDirectoryChecks.length) { + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) { return false; } const invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution); - failedLookupChecks.length = 0; - startsWithPathChecks.length = 0; - isInDirectoryChecks.length = 0; + failedLookupChecks = undefined; + startsWithPathChecks = undefined; + isInDirectoryChecks = undefined; return invalidated; } @@ -806,8 +825,8 @@ namespace ts { return resolution.failedLookupLocations.some(location => { const locationPath = resolutionHost.toPath(location); return contains(failedLookupChecks, locationPath) || - startsWithPathChecks.some(fileOrDirectoryPath => startsWith(locationPath, fileOrDirectoryPath)) || - isInDirectoryChecks.some(fileOrDirectoryPath => isInDirectoryPath(fileOrDirectoryPath, locationPath)); + firstDefinedIterator(startsWithPathChecks?.keys() || emptyIterator, fileOrDirectoryPath => startsWith(locationPath, fileOrDirectoryPath) ? true : undefined) || + isInDirectoryChecks?.some(fileOrDirectoryPath => isInDirectoryPath(fileOrDirectoryPath, locationPath)); }); } diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index 7b7fc7b9ce353..ba449e81b96e1 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -40,7 +40,7 @@ namespace ts { scanJsxIdentifier(): SyntaxKind; scanJsxAttributeValue(): SyntaxKind; reScanJsxAttributeValue(): SyntaxKind; - reScanJsxToken(): JsxTokenSyntaxKind; + reScanJsxToken(allowMultilineJsxText?: boolean): JsxTokenSyntaxKind; reScanLessThanToken(): SyntaxKind; reScanQuestionToken(): SyntaxKind; reScanInvalidIdentifier(): SyntaxKind; @@ -127,6 +127,7 @@ namespace ts { private: SyntaxKind.PrivateKeyword, protected: SyntaxKind.ProtectedKeyword, public: SyntaxKind.PublicKeyword, + override: SyntaxKind.OverrideKeyword, readonly: SyntaxKind.ReadonlyKeyword, require: SyntaxKind.RequireKeyword, global: SyntaxKind.GlobalKeyword, @@ -553,11 +554,12 @@ namespace ts { } /* @internal */ - export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean, stopAtComments = false): number { + export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean, stopAtComments?: boolean, inJSDoc?: boolean): number { if (positionIsSynthesized(pos)) { return pos; } + let canConsumeStar = false; // Keep in sync with couldStartTrivia while (true) { const ch = text.charCodeAt(pos); @@ -572,6 +574,7 @@ namespace ts { if (stopAfterLineBreak) { return pos; } + canConsumeStar = !!inJSDoc; continue; case CharacterCodes.tab: case CharacterCodes.verticalTab: @@ -591,6 +594,7 @@ namespace ts { } pos++; } + canConsumeStar = false; continue; } if (text.charCodeAt(pos + 1) === CharacterCodes.asterisk) { @@ -602,6 +606,7 @@ namespace ts { } pos++; } + canConsumeStar = false; continue; } break; @@ -612,6 +617,7 @@ namespace ts { case CharacterCodes.greaterThan: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos); + canConsumeStar = false; continue; } break; @@ -619,6 +625,15 @@ namespace ts { case CharacterCodes.hash: if (pos === 0 && isShebangTrivia(text, pos)) { pos = scanShebangTrivia(text, pos); + canConsumeStar = false; + continue; + } + break; + + case CharacterCodes.asterisk: + if (canConsumeStar) { + pos++; + canConsumeStar = false; continue; } break; @@ -2223,9 +2238,9 @@ namespace ts { return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true); } - function reScanJsxToken(): JsxTokenSyntaxKind { + function reScanJsxToken(allowMultilineJsxText = true): JsxTokenSyntaxKind { pos = tokenPos = startPos; - return token = scanJsxToken(); + return token = scanJsxToken(allowMultilineJsxText); } function reScanLessThanToken(): SyntaxKind { @@ -2242,7 +2257,7 @@ namespace ts { return token = SyntaxKind.QuestionToken; } - function scanJsxToken(): JsxTokenSyntaxKind { + function scanJsxToken(allowMultilineJsxText = true): JsxTokenSyntaxKind { startPos = tokenPos = pos; if (pos >= end) { @@ -2266,19 +2281,11 @@ namespace ts { // First non-whitespace character on this line. let firstNonWhitespace = 0; - let lastNonWhitespace = -1; // These initial values are special because the first line is: // firstNonWhitespace = 0 to indicate that we want leading whitespace, while (pos < end) { - - // We want to keep track of the last non-whitespace (but including - // newlines character for hitting the end of the JSX Text region) - if (!isWhiteSpaceSingleLine(char)) { - lastNonWhitespace = pos; - } - char = text.charCodeAt(pos); if (char === CharacterCodes.openBrace) { break; @@ -2297,8 +2304,6 @@ namespace ts { error(Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1); } - if (lastNonWhitespace > 0) lastNonWhitespace++; - // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces. // i.e (- : whitespace) //
---- @@ -2308,6 +2313,11 @@ namespace ts { if (isLineBreak(char) && firstNonWhitespace === 0) { firstNonWhitespace = -1; } + else if (!allowMultilineJsxText && isLineBreak(char) && firstNonWhitespace > 0) { + // Stop JsxText on each line during formatting. This allows the formatter to + // indent each line correctly. + break; + } else if (!isWhiteSpaceLike(char)) { firstNonWhitespace = pos; } @@ -2315,8 +2325,7 @@ namespace ts { pos++; } - const endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace; - tokenValue = text.substring(startPos, endPosition); + tokenValue = text.substring(startPos, pos); return firstNonWhitespace === -1 ? SyntaxKind.JsxTextAllWhiteSpaces : SyntaxKind.JsxText; } @@ -2341,6 +2350,7 @@ namespace ts { tokenValue += ":"; pos++; namespaceSeparator = true; + token = SyntaxKind.Identifier; // swap from keyword kind to identifier kind continue; } const oldPos = pos; diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 5dc4fbe91cc35..37ea6450f7c1f 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -57,6 +57,11 @@ namespace ts { /* @internal */ export const missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time + /* @internal */ + export function getModifiedTime(host: { getModifiedTime: NonNullable; }, fileName: string) { + return host.getModifiedTime(fileName) || missingFileModifiedTime; + } + interface Levels { Low: number; Medium: number; @@ -126,6 +131,64 @@ namespace ts { } } + interface WatchedFileWithIsClosed extends WatchedFile { + isClosed?: boolean; + } + function pollWatchedFileQueue( + host: { getModifiedTime: NonNullable; }, + queue: (T | undefined)[], + pollIndex: number, chunkSize: number, + callbackOnWatchFileStat?: (watchedFile: T, pollIndex: number, fileChanged: boolean) => void + ) { + let definedValueCopyToIndex = pollIndex; + // Max visit would be all elements of the queue + for (let canVisit = queue.length; chunkSize && canVisit; nextPollIndex(), canVisit--) { + const watchedFile = queue[pollIndex]; + if (!watchedFile) { + continue; + } + else if (watchedFile.isClosed) { + queue[pollIndex] = undefined; + continue; + } + + // Only files polled count towards chunkSize + chunkSize--; + const fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(host, watchedFile.fileName)); + if (watchedFile.isClosed) { + // Closed watcher as part of callback + queue[pollIndex] = undefined; + continue; + } + + callbackOnWatchFileStat?.(watchedFile, pollIndex, fileChanged); + // Defragment the queue while we are at it + if (queue[pollIndex]) { + // Copy this file to the non hole location + if (definedValueCopyToIndex < pollIndex) { + queue[definedValueCopyToIndex] = watchedFile; + queue[pollIndex] = undefined; + } + definedValueCopyToIndex++; + } + } + + // Return next poll index + return pollIndex; + + function nextPollIndex() { + pollIndex++; + if (pollIndex === queue.length) { + if (definedValueCopyToIndex < pollIndex) { + // There are holes from definedValueCopyToIndex to end of queue, change queue size + queue.length = definedValueCopyToIndex; + } + pollIndex = 0; + definedValueCopyToIndex = 0; + } + } + } + /* @internal */ export function createDynamicPriorityPollingWatchFile(host: { getModifiedTime: NonNullable; @@ -154,7 +217,7 @@ namespace ts { fileName, callback, unchangedPolls: 0, - mtime: getModifiedTime(fileName) + mtime: getModifiedTime(host, fileName) }; watchedFiles.push(file); @@ -203,26 +266,16 @@ namespace ts { } function pollQueue(queue: (WatchedFile | undefined)[], pollingInterval: PollingInterval, pollIndex: number, chunkSize: number) { - // Max visit would be all elements of the queue - let needsVisit = queue.length; - let definedValueCopyToIndex = pollIndex; - for (let polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) { - const watchedFile = queue[pollIndex]; - if (!watchedFile) { - continue; - } - else if (watchedFile.isClosed) { - queue[pollIndex] = undefined; - continue; - } + return pollWatchedFileQueue( + host, + queue, + pollIndex, + chunkSize, + onWatchFileStat + ); - polled++; - const fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName)); - if (watchedFile.isClosed) { - // Closed watcher as part of callback - queue[pollIndex] = undefined; - } - else if (fileChanged) { + function onWatchFileStat(watchedFile: WatchedFile, pollIndex: number, fileChanged: boolean) { + if (fileChanged) { watchedFile.unchangedPolls = 0; // Changed files go to changedFilesInLastPoll queue if (queue !== changedFilesInLastPoll) { @@ -244,30 +297,6 @@ namespace ts { queue[pollIndex] = undefined; addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High); } - - if (queue[pollIndex]) { - // Copy this file to the non hole location - if (definedValueCopyToIndex < pollIndex) { - queue[definedValueCopyToIndex] = watchedFile; - queue[pollIndex] = undefined; - } - definedValueCopyToIndex++; - } - } - - // Return next poll index - return pollIndex; - - function nextPollIndex() { - pollIndex++; - if (pollIndex === queue.length) { - if (definedValueCopyToIndex < pollIndex) { - // There are holes from nextDefinedValueIndex to end of queue, change queue size - queue.length = definedValueCopyToIndex; - } - pollIndex = 0; - definedValueCopyToIndex = 0; - } } } @@ -301,10 +330,6 @@ namespace ts { function scheduleNextPoll(pollingInterval: PollingInterval) { pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval)); } - - function getModifiedTime(fileName: string) { - return host.getModifiedTime(fileName) || missingFileModifiedTime; - } } function createUseFsEventsOnParentDirectoryWatchFile(fsWatch: FsWatch, useCaseSensitiveFileNames: boolean): HostWatchFile { @@ -361,6 +386,43 @@ namespace ts { } } + function createFixedChunkSizePollingWatchFile(host: { + getModifiedTime: NonNullable; + setTimeout: NonNullable; + }): HostWatchFile { + const watchedFiles: (WatchedFileWithIsClosed | undefined)[] = []; + let pollIndex = 0; + let pollScheduled: any; + return watchFile; + + function watchFile(fileName: string, callback: FileWatcherCallback): FileWatcher { + const file: WatchedFileWithIsClosed = { + fileName, + callback, + mtime: getModifiedTime(host, fileName) + }; + watchedFiles.push(file); + scheduleNextPoll(); + return { + close: () => { + file.isClosed = true; + unorderedRemoveItem(watchedFiles, file); + } + }; + } + + function pollQueue() { + pollScheduled = undefined; + pollIndex = pollWatchedFileQueue(host, watchedFiles, pollIndex, pollingChunkSize[PollingInterval.Low]); + scheduleNextPoll(); + } + + function scheduleNextPoll() { + if (!watchedFiles.length || pollScheduled) return; + pollScheduled = host.setTimeout(pollQueue, PollingInterval.High); + } + } + /* @internal */ export function createSingleFileWatcherPerName( watchFile: HostWatchFile, @@ -795,6 +857,7 @@ namespace ts { tscWatchFile: string | undefined; useNonPollingWatchers?: boolean; tscWatchDirectory: string | undefined; + defaultWatchFileKind: System["defaultWatchFileKind"]; } /*@internal*/ @@ -814,8 +877,10 @@ namespace ts { tscWatchFile, useNonPollingWatchers, tscWatchDirectory, + defaultWatchFileKind, }: CreateSystemWatchFunctions): { watchFile: HostWatchFile; watchDirectory: HostWatchDirectory; } { let dynamicPollingWatchFile: HostWatchFile | undefined; + let fixedChunkSizePollingWatchFile: HostWatchFile | undefined; let nonPollingWatchFile: HostWatchFile | undefined; let hostRecursiveDirectoryWatcher: HostWatchDirectory | undefined; return { @@ -833,6 +898,8 @@ namespace ts { return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined); case WatchFileKind.DynamicPriorityPolling: return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined); + case WatchFileKind.FixedChunkSizePolling: + return ensureFixedChunkSizePollingWatchFile()(fileName, callback, /* pollingInterval */ undefined!, /*options*/ undefined); case WatchFileKind.UseFsEvents: return fsWatch( fileName, @@ -853,8 +920,11 @@ namespace ts { } function ensureDynamicPollingWatchFile() { - return dynamicPollingWatchFile || - (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime, setTimeout })); + return dynamicPollingWatchFile ||= createDynamicPriorityPollingWatchFile({ getModifiedTime, setTimeout }); + } + + function ensureFixedChunkSizePollingWatchFile() { + return fixedChunkSizePollingWatchFile ||= createFixedChunkSizePollingWatchFile({ getModifiedTime, setTimeout }); } function updateOptionsForWatchFile(options: WatchOptions | undefined, useNonPollingWatchers?: boolean): WatchOptions { @@ -880,7 +950,7 @@ namespace ts { // Use notifications from FS to watch with falling back to fs.watchFile generateWatchFileOptions(WatchFileKind.UseFsEventsOnParentDirectory, PollingWatchKind.PriorityInterval, options) : // Default to do not use fixed polling interval - { watchFile: WatchFileKind.FixedPollingInterval }; + { watchFile: defaultWatchFileKind?.() || WatchFileKind.FixedPollingInterval }; } } @@ -944,6 +1014,13 @@ namespace ts { PollingInterval.Medium, /*options*/ undefined ); + case WatchDirectoryKind.FixedChunkSizePolling: + return ensureFixedChunkSizePollingWatchFile()( + directoryName, + () => callback(directoryName), + /* pollingInterval */ undefined!, + /*options*/ undefined + ); case WatchDirectoryKind.UseFsEvents: return fsWatch( directoryName, @@ -1130,7 +1207,9 @@ namespace ts { /*@internal*/ bufferFrom?(input: string, encoding?: string): Buffer; // For testing /*@internal*/ now?(): Date; + /*@internal*/ disableUseFileVersionAsSignature?: boolean; /*@internal*/ require?(baseDir: string, moduleName: string): RequireResult; + /*@internal*/ defaultWatchFileKind?(): WatchFileKind | undefined; } export interface FileWatcher { @@ -1186,7 +1265,6 @@ namespace ts { let activeSession: import("inspector").Session | "stopping" | undefined; let profilePath = "./profile.cpuprofile"; - const realpathSync = _fs.realpathSync.native ?? _fs.realpathSync; const Buffer: { new (input: string, encoding?: string): any; @@ -1199,6 +1277,8 @@ namespace ts { const platform: string = _os.platform(); const useCaseSensitiveFileNames = isFileSystemCaseSensitive(); + const realpathSync = useCaseSensitiveFileNames ? (_fs.realpathSync.native ?? _fs.realpathSync) : _fs.realpathSync; + const fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin"); const getCurrentDirectory = memoize(() => process.cwd()); const { watchFile, watchDirectory } = createSystemWatchFunctions({ @@ -1219,6 +1299,7 @@ namespace ts { tscWatchFile: process.env.TSC_WATCHFILE, useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER, tscWatchDirectory: process.env.TSC_WATCHDIRECTORY, + defaultWatchFileKind: () => sys!.defaultWatchFileKind?.(), }); const nodeSystem: System = { args: process.argv.slice(2), diff --git a/src/compiler/tracing.ts b/src/compiler/tracing.ts index 87c2abf4f4819..31c1c8910cf91 100644 --- a/src/compiler/tracing.ts +++ b/src/compiler/tracing.ts @@ -5,299 +5,340 @@ namespace ts { // eslint-disable-line one-namespace-per-file // should be used as tracing?.___ export let tracing: typeof tracingEnabled | undefined; // enable the above using startTracing() -} -// `tracingEnabled` should never be used directly, only through the above -/* @internal */ -namespace ts.tracingEnabled { // eslint-disable-line one-namespace-per-file - export const enum Mode { - Project, - Build, - Server, - } + // `tracingEnabled` should never be used directly, only through the above + namespace tracingEnabled { // eslint-disable-line one-namespace-per-file + type Mode = "project" | "build" | "server"; - let fs: typeof import("fs"); + let fs: typeof import("fs"); - let traceCount = 0; - let traceFd = 0; + let traceCount = 0; + let traceFd = 0; - let mode: Mode; + let mode: Mode; - let legendPath: string | undefined; - const legend: TraceRecord[] = []; + const typeCatalog: Type[] = []; // NB: id is index + 1 - // The actual constraint is that JSON.stringify be able to serialize it without throwing. - interface Args { - [key: string]: string | number | boolean | null | undefined | Args | readonly (string | number | boolean | null | undefined | Args)[]; - }; + let legendPath: string | undefined; + const legend: TraceRecord[] = []; - /** Starts tracing for the given project. */ - export function startTracing(tracingMode: Mode, traceDir: string, configFilePath?: string) { - Debug.assert(!tracing, "Tracing already started"); + // The actual constraint is that JSON.stringify be able to serialize it without throwing. + interface Args { + [key: string]: string | number | boolean | null | undefined | Args | readonly (string | number | boolean | null | undefined | Args)[]; + }; - if (fs === undefined) { - try { - fs = require("fs"); + /** Starts tracing for the given project. */ + export function startTracing(tracingMode: Mode, traceDir: string, configFilePath?: string) { + Debug.assert(!tracing, "Tracing already started"); + + if (fs === undefined) { + try { + fs = require("fs"); + } + catch (e) { + throw new Error(`tracing requires having fs\n(original error: ${e.message || e})`); + } } - catch (e) { - throw new Error(`tracing requires having fs\n(original error: ${e.message || e})`); + + mode = tracingMode; + typeCatalog.length = 0; + + if (legendPath === undefined) { + legendPath = combinePaths(traceDir, "legend.json"); } - } - mode = tracingMode; + // Note that writing will fail later on if it exists and is not a directory + if (!fs.existsSync(traceDir)) { + fs.mkdirSync(traceDir, { recursive: true }); + } - if (legendPath === undefined) { - legendPath = combinePaths(traceDir, "legend.json"); + const countPart = + mode === "build" ? `.${process.pid}-${++traceCount}` + : mode === "server" ? `.${process.pid}` + : ``; + const tracePath = combinePaths(traceDir, `trace${countPart}.json`); + const typesPath = combinePaths(traceDir, `types${countPart}.json`); + + legend.push({ + configFilePath, + tracePath, + typesPath, + }); + + traceFd = fs.openSync(tracePath, "w"); + tracing = tracingEnabled; // only when traceFd is properly set + + // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import) + const meta = { cat: "__metadata", ph: "M", ts: 1000 * timestamp(), pid: 1, tid: 1 }; + fs.writeSync(traceFd, + "[\n" + + [{ name: "process_name", args: { name: "tsc" }, ...meta }, + { name: "thread_name", args: { name: "Main" }, ...meta }, + { name: "TracingStartedInBrowser", ...meta, cat: "disabled-by-default-devtools.timeline" }] + .map(v => JSON.stringify(v)).join(",\n")); } - // Note that writing will fail later on if it exists and is not a directory - if (!fs.existsSync(traceDir)) { - fs.mkdirSync(traceDir, { recursive: true }); + /** Stops tracing for the in-progress project and dumps the type catalog. */ + export function stopTracing() { + Debug.assert(tracing, "Tracing is not in progress"); + Debug.assert(!!typeCatalog.length === (mode !== "server")); // Have a type catalog iff not in server mode + + fs.writeSync(traceFd, `\n]\n`); + fs.closeSync(traceFd); + tracing = undefined; + + if (typeCatalog.length) { + dumpTypes(typeCatalog); + } + else { + // We pre-computed this path for convenience, but clear it + // now that the file won't be created. + legend[legend.length - 1].typesPath = undefined; + } } - const countPart = - mode === Mode.Build ? `.${process.pid}-${++traceCount}` - : mode === Mode.Server ? `.${process.pid}` - : ``; - const tracePath = combinePaths(traceDir, `trace${countPart}.json`); - const typesPath = combinePaths(traceDir, `types${countPart}.json`); - - legend.push({ - configFilePath, - tracePath, - typesPath, - }); - - traceFd = fs.openSync(tracePath, "w"); - tracing = tracingEnabled; // only when traceFd is properly set - - // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import) - const meta = { cat: "__metadata", ph: "M", ts: 1000 * timestamp(), pid: 1, tid: 1 }; - fs.writeSync(traceFd, - "[\n" - + [{ name: "process_name", args: { name: "tsc" }, ...meta }, - { name: "thread_name", args: { name: "Main" }, ...meta }, - { name: "TracingStartedInBrowser", ...meta, cat: "disabled-by-default-devtools.timeline" }] - .map(v => JSON.stringify(v)).join(",\n")); - } + export function recordType(type: Type): void { + if (mode !== "server") { + typeCatalog.push(type); + } + } - /** Stops tracing for the in-progress project and dumps the type catalog. */ - export function stopTracing(typeCatalog?: readonly Type[]) { - Debug.assert(tracing, "Tracing is not in progress"); - Debug.assert(!!typeCatalog === (mode !== Mode.Server)); // Have a type catalog iff not in server mode + export const enum Phase { + Parse = "parse", + Program = "program", + Bind = "bind", + Check = "check", // Before we get into checking types (e.g. checkSourceFile) + CheckTypes = "checkTypes", + Emit = "emit", + Session = "session", + } - fs.writeSync(traceFd, `\n]\n`); - fs.closeSync(traceFd); - tracing = undefined; + export function instant(phase: Phase, name: string, args?: Args) { + writeEvent("I", phase, name, args, `"s":"g"`); + } - if (typeCatalog) { - dumpTypes(typeCatalog); + const eventStack: { phase: Phase, name: string, args?: Args, time: number, separateBeginAndEnd: boolean }[] = []; + + /** + * @param separateBeginAndEnd - used for special cases where we need the trace point even if the event + * never terminates (typically for reducing a scenario too big to trace to one that can be completed). + * In the future we might implement an exit handler to dump unfinished events which would deprecate + * these operations. + */ + export function push(phase: Phase, name: string, args?: Args, separateBeginAndEnd = false) { + if (separateBeginAndEnd) { + writeEvent("B", phase, name, args); + } + eventStack.push({ phase, name, args, time: 1000 * timestamp(), separateBeginAndEnd }); } - else { - // We pre-computed this path for convenience, but clear it - // now that the file won't be created. - legend[legend.length - 1].typesPath = undefined; + export function pop() { + Debug.assert(eventStack.length > 0); + writeStackEvent(eventStack.length - 1, 1000 * timestamp()); + eventStack.length--; + } + export function popAll() { + const endTime = 1000 * timestamp(); + for (let i = eventStack.length - 1; i >= 0; i--) { + writeStackEvent(i, endTime); + } + eventStack.length = 0; + } + // sample every 10ms + const sampleInterval = 1000 * 10; + function writeStackEvent(index: number, endTime: number) { + const { phase, name, args, time, separateBeginAndEnd } = eventStack[index]; + if (separateBeginAndEnd) { + writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); + } + // test if [time,endTime) straddles a sampling point + else if (sampleInterval - (time % sampleInterval) <= endTime - time) { + writeEvent("X", phase, name, args, `"dur":${endTime - time}`, time); + } } - } - export const enum Phase { - Parse = "parse", - Program = "program", - Bind = "bind", - Check = "check", // Before we get into checking types (e.g. checkSourceFile) - CheckTypes = "checkTypes", - Emit = "emit", - Session = "session", - } + function writeEvent(eventType: string, phase: Phase, name: string, args: Args | undefined, extras?: string, + time: number = 1000 * timestamp()) { - export function instant(phase: Phase, name: string, args?: Args) { - writeEvent("I", phase, name, args, `"s":"g"`); - } + // In server mode, there's no easy way to dump type information, so we drop events that would require it. + if (mode === "server" && phase === Phase.CheckTypes) return; - const eventStack: { phase: Phase, name: string, args?: Args, time: number, separateBeginAndEnd: boolean }[] = []; - - /** - * @param separateBeginAndEnd - used for special cases where we need the trace point even if the event - * never terminates (typically for reducing a scenario too big to trace to one that can be completed). - * In the future we might implement an exit handler to dump unfinished events which would deprecate - * these operations. - */ - export function push(phase: Phase, name: string, args?: Args, separateBeginAndEnd = false) { - if (separateBeginAndEnd) { - writeEvent("B", phase, name, args); - } - eventStack.push({ phase, name, args, time: 1000 * timestamp(), separateBeginAndEnd }); - } - export function pop() { - Debug.assert(eventStack.length > 0); - writeStackEvent(eventStack.length - 1, 1000 * timestamp()); - eventStack.length--; - } - export function popAll() { - const endTime = 1000 * timestamp(); - for (let i = eventStack.length - 1; i >= 0; i--) { - writeStackEvent(i, endTime); - } - eventStack.length = 0; - } - // sample every 10ms - const sampleInterval = 1000 * 10; - function writeStackEvent(index: number, endTime: number) { - const { phase, name, args, time, separateBeginAndEnd } = eventStack[index]; - if (separateBeginAndEnd) { - writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); + performance.mark("beginTracing"); + fs.writeSync(traceFd, `,\n{"pid":1,"tid":1,"ph":"${eventType}","cat":"${phase}","ts":${time},"name":"${name}"`); + if (extras) fs.writeSync(traceFd, `,${extras}`); + if (args) fs.writeSync(traceFd, `,"args":${JSON.stringify(args)}`); + fs.writeSync(traceFd, `}`); + performance.mark("endTracing"); + performance.measure("Tracing", "beginTracing", "endTracing"); } - // test if [time,endTime) straddles a sampling point - else if (sampleInterval - (time % sampleInterval) <= endTime - time) { - writeEvent("X", phase, name, args, `"dur":${endTime - time}`, time); + + function getLocation(node: Node | undefined) { + const file = getSourceFileOfNode(node); + return !file + ? undefined + : { + path: file.path, + start: indexFromOne(getLineAndCharacterOfPosition(file, node!.pos)), + end: indexFromOne(getLineAndCharacterOfPosition(file, node!.end)), + }; + + function indexFromOne(lc: LineAndCharacter): LineAndCharacter { + return { + line: lc.line + 1, + character: lc.character + 1, + }; + } } - } - function writeEvent(eventType: string, phase: Phase, name: string, args: Args | undefined, extras?: string, - time: number = 1000 * timestamp()) { + function dumpTypes(types: readonly Type[]) { + performance.mark("beginDumpTypes"); - // In server mode, there's no easy way to dump type information, so we drop events that would require it. - if (mode === Mode.Server && phase === Phase.CheckTypes) return; + const typesPath = legend[legend.length - 1].typesPath!; + const typesFd = fs.openSync(typesPath, "w"); - performance.mark("beginTracing"); - fs.writeSync(traceFd, `,\n{"pid":1,"tid":1,"ph":"${eventType}","cat":"${phase}","ts":${time},"name":"${name}"`); - if (extras) fs.writeSync(traceFd, `,${extras}`); - if (args) fs.writeSync(traceFd, `,"args":${JSON.stringify(args)}`); - fs.writeSync(traceFd, `}`); - performance.mark("endTracing"); - performance.measure("Tracing", "beginTracing", "endTracing"); - } + const recursionIdentityMap = new Map(); - function indexFromOne(lc: LineAndCharacter): LineAndCharacter { - return { - line: lc.line + 1, - character: lc.character + 1, - }; - } + // Cleverness: no line break here so that the type ID will match the line number + fs.writeSync(typesFd, "["); - function dumpTypes(types: readonly Type[]) { - performance.mark("beginDumpTypes"); + const numTypes = types.length; + for (let i = 0; i < numTypes; i++) { + const type = types[i]; + const objectFlags = (type as any).objectFlags; + const symbol = type.aliasSymbol ?? type.symbol; - const typesPath = legend[legend.length - 1].typesPath!; - const typesFd = fs.openSync(typesPath, "w"); + // It's slow to compute the display text, so skip it unless it's really valuable (or cheap) + let display: string | undefined; + if ((objectFlags & ObjectFlags.Anonymous) | (type.flags & TypeFlags.Literal)) { + try { + display = type.checker?.typeToString(type); + } + catch { + display = undefined; + } + } - const recursionIdentityMap = new Map(); + let indexedAccessProperties: object = {}; + if (type.flags & TypeFlags.IndexedAccess) { + const indexedAccessType = type as IndexedAccessType; + indexedAccessProperties = { + indexedAccessObjectType: indexedAccessType.objectType?.id, + indexedAccessIndexType: indexedAccessType.indexType?.id, + }; + } - // Cleverness: no line break here so that the type ID will match the line number - fs.writeSync(typesFd, "["); + let referenceProperties: object = {}; + if (objectFlags & ObjectFlags.Reference) { + const referenceType = type as TypeReference; + referenceProperties = { + instantiatedType: referenceType.target?.id, + typeArguments: referenceType.resolvedTypeArguments?.map(t => t.id), + referenceLocation: getLocation(referenceType.node), + }; + } - const numTypes = types.length; - for (let i = 0; i < numTypes; i++) { - const type = types[i]; - const objectFlags = (type as any).objectFlags; - const symbol = type.aliasSymbol ?? type.symbol; - const firstDeclaration = symbol?.declarations?.[0]; - const firstFile = firstDeclaration && getSourceFileOfNode(firstDeclaration); + let conditionalProperties: object = {}; + if (type.flags & TypeFlags.Conditional) { + const conditionalType = type as ConditionalType; + conditionalProperties = { + conditionalCheckType: conditionalType.checkType?.id, + conditionalExtendsType: conditionalType.extendsType?.id, + conditionalTrueType: conditionalType.resolvedTrueType?.id ?? -1, + conditionalFalseType: conditionalType.resolvedFalseType?.id ?? -1, + }; + } - // It's slow to compute the display text, so skip it unless it's really valuable (or cheap) - let display: string | undefined; - if ((objectFlags & ObjectFlags.Anonymous) | (type.flags & TypeFlags.Literal)) { - try { - display = type.checker?.typeToString(type); + let substitutionProperties: object = {}; + if (type.flags & TypeFlags.Substitution) { + const substitutionType = type as SubstitutionType; + substitutionProperties = { + substitutionBaseType: substitutionType.baseType?.id, + substituteType: substitutionType.substitute?.id, + }; } - catch { - display = undefined; + + let reverseMappedProperties: object = {}; + if (objectFlags & ObjectFlags.ReverseMapped) { + const reverseMappedType = type as ReverseMappedType; + reverseMappedProperties = { + reverseMappedSourceType: reverseMappedType.source?.id, + reverseMappedMappedType: reverseMappedType.mappedType?.id, + reverseMappedConstraintType: reverseMappedType.constraintType?.id, + }; } - } - let indexedAccessProperties: object = {}; - if (type.flags & TypeFlags.IndexedAccess) { - const indexedAccessType = type as IndexedAccessType; - indexedAccessProperties = { - indexedAccessObjectType: indexedAccessType.objectType?.id, - indexedAccessIndexType: indexedAccessType.indexType?.id, - }; - } + let evolvingArrayProperties: object = {}; + if (objectFlags & ObjectFlags.EvolvingArray) { + const evolvingArrayType = type as EvolvingArrayType; + evolvingArrayProperties = { + evolvingArrayElementType: evolvingArrayType.elementType.id, + evolvingArrayFinalType: evolvingArrayType.finalArrayType?.id, + }; + } - let referenceProperties: object = {}; - if (objectFlags & ObjectFlags.Reference) { - const referenceType = type as TypeReference; - referenceProperties = { - instantiatedType: referenceType.target?.id, - typeArguments: referenceType.resolvedTypeArguments?.map(t => t.id), - }; - } + // We can't print out an arbitrary object, so just assign each one a unique number. + // Don't call it an "id" so people don't treat it as a type id. + let recursionToken: number | undefined; + const recursionIdentity = type.checker.getRecursionIdentity(type); + if (recursionIdentity) { + recursionToken = recursionIdentityMap.get(recursionIdentity); + if (!recursionToken) { + recursionToken = recursionIdentityMap.size; + recursionIdentityMap.set(recursionIdentity, recursionToken); + } + } - let conditionalProperties: object = {}; - if (type.flags & TypeFlags.Conditional) { - const conditionalType = type as ConditionalType; - conditionalProperties = { - conditionalCheckType: conditionalType.checkType?.id, - conditionalExtendsType: conditionalType.extendsType?.id, - conditionalTrueType: conditionalType.resolvedTrueType?.id ?? -1, - conditionalFalseType: conditionalType.resolvedFalseType?.id ?? -1, + const descriptor = { + id: type.id, + intrinsicName: (type as any).intrinsicName, + symbolName: symbol?.escapedName && unescapeLeadingUnderscores(symbol.escapedName), + recursionId: recursionToken, + isTuple: objectFlags & ObjectFlags.Tuple ? true : undefined, + unionTypes: (type.flags & TypeFlags.Union) ? (type as UnionType).types?.map(t => t.id) : undefined, + intersectionTypes: (type.flags & TypeFlags.Intersection) ? (type as IntersectionType).types.map(t => t.id) : undefined, + aliasTypeArguments: type.aliasTypeArguments?.map(t => t.id), + keyofType: (type.flags & TypeFlags.Index) ? (type as IndexType).type?.id : undefined, + ...indexedAccessProperties, + ...referenceProperties, + ...conditionalProperties, + ...substitutionProperties, + ...reverseMappedProperties, + ...evolvingArrayProperties, + destructuringPattern: getLocation(type.pattern), + firstDeclaration: getLocation(symbol?.declarations?.[0]), + flags: Debug.formatTypeFlags(type.flags).split("|"), + display, }; - } - // We can't print out an arbitrary object, so just assign each one a unique number. - // Don't call it an "id" so people don't treat it as a type id. - let recursionToken: number | undefined; - const recursionIdentity = type.checker.getRecursionIdentity(type); - if (recursionIdentity) { - recursionToken = recursionIdentityMap.get(recursionIdentity); - if (!recursionToken) { - recursionToken = recursionIdentityMap.size; - recursionIdentityMap.set(recursionIdentity, recursionToken); + fs.writeSync(typesFd, JSON.stringify(descriptor)); + if (i < numTypes - 1) { + fs.writeSync(typesFd, ",\n"); } } - const descriptor = { - id: type.id, - intrinsicName: (type as any).intrinsicName, - symbolName: symbol?.escapedName && unescapeLeadingUnderscores(symbol.escapedName), - recursionId: recursionToken, - unionTypes: (type.flags & TypeFlags.Union) ? (type as UnionType).types?.map(t => t.id) : undefined, - intersectionTypes: (type.flags & TypeFlags.Intersection) ? (type as IntersectionType).types.map(t => t.id) : undefined, - aliasTypeArguments: type.aliasTypeArguments?.map(t => t.id), - keyofType: (type.flags & TypeFlags.Index) ? (type as IndexType).type?.id : undefined, - ...indexedAccessProperties, - ...referenceProperties, - ...conditionalProperties, - firstDeclaration: firstDeclaration && { - path: firstFile.path, - start: indexFromOne(getLineAndCharacterOfPosition(firstFile, firstDeclaration.pos)), - end: indexFromOne(getLineAndCharacterOfPosition(getSourceFileOfNode(firstDeclaration), firstDeclaration.end)), - }, - flags: Debug.formatTypeFlags(type.flags).split("|"), - display, - }; - - fs.writeSync(typesFd, JSON.stringify(descriptor)); - if (i < numTypes - 1) { - fs.writeSync(typesFd, ",\n"); - } - } + fs.writeSync(typesFd, "]\n"); - fs.writeSync(typesFd, "]\n"); + fs.closeSync(typesFd); - fs.closeSync(typesFd); + performance.mark("endDumpTypes"); + performance.measure("Dump types", "beginDumpTypes", "endDumpTypes"); + } - performance.mark("endDumpTypes"); - performance.measure("Dump types", "beginDumpTypes", "endDumpTypes"); - } + export function dumpLegend() { + if (!legendPath) { + return; + } - export function dumpLegend() { - if (!legendPath) { - return; + fs.writeFileSync(legendPath, JSON.stringify(legend)); } - fs.writeFileSync(legendPath, JSON.stringify(legend)); - } - - interface TraceRecord { - configFilePath?: string; - tracePath: string; - typesPath?: string; + interface TraceRecord { + configFilePath?: string; + tracePath: string; + typesPath?: string; + } } -} -/*@internal*/ -namespace ts { // eslint-disable-line one-namespace-per-file // define after tracingEnabled is initialized export const startTracing = tracingEnabled.startTracing; + export const dumpTracingLegend = tracingEnabled.dumpLegend; } diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts index 4de469afc5724..732205c00a34b 100644 --- a/src/compiler/transformer.ts +++ b/src/compiler/transformer.ts @@ -54,6 +54,10 @@ namespace ts { transformers.push(transformESNext); } + if (languageVersion < ScriptTarget.ES2021) { + transformers.push(transformES2021); + } + if (languageVersion < ScriptTarget.ES2020) { transformers.push(transformES2020); } @@ -155,6 +159,9 @@ namespace ts { let lexicalEnvironmentFlagsStack: LexicalEnvironmentFlags[] = []; let lexicalEnvironmentStackOffset = 0; let lexicalEnvironmentSuspended = false; + let blockScopedVariableDeclarationsStack: Identifier[][] = []; + let blockScopeStackOffset = 0; + let blockScopedVariableDeclarations: Identifier[]; let emitHelpers: EmitHelper[] | undefined; let onSubstituteNode: TransformationContext["onSubstituteNode"] = noEmitSubstitution; let onEmitNode: TransformationContext["onEmitNode"] = noEmitNotification; @@ -178,6 +185,9 @@ namespace ts { hoistVariableDeclaration, hoistFunctionDeclaration, addInitializationStatement, + startBlockScope, + endBlockScope, + addBlockScopedVariable, requestEmitHelper, readEmitHelpers, enableSubstitution, @@ -469,6 +479,46 @@ namespace ts { return lexicalEnvironmentFlags; } + /** + * Starts a block scope. Any existing block hoisted variables are pushed onto the stack and the related storage variables are reset. + */ + function startBlockScope() { + Debug.assert(state > TransformationState.Uninitialized, "Cannot start a block scope during initialization."); + Debug.assert(state < TransformationState.Completed, "Cannot start a block scope after transformation has completed."); + blockScopedVariableDeclarationsStack[blockScopeStackOffset] = blockScopedVariableDeclarations; + blockScopeStackOffset++; + blockScopedVariableDeclarations = undefined!; + } + + /** + * Ends a block scope. The previous set of block hoisted variables are restored. Any hoisted declarations are returned. + */ + function endBlockScope() { + Debug.assert(state > TransformationState.Uninitialized, "Cannot end a block scope during initialization."); + Debug.assert(state < TransformationState.Completed, "Cannot end a block scope after transformation has completed."); + const statements: Statement[] | undefined = some(blockScopedVariableDeclarations) ? + [ + factory.createVariableStatement( + /*modifiers*/ undefined, + factory.createVariableDeclarationList( + blockScopedVariableDeclarations.map(identifier => factory.createVariableDeclaration(identifier)), + NodeFlags.Let + ) + ) + ] : undefined; + blockScopeStackOffset--; + blockScopedVariableDeclarations = blockScopedVariableDeclarationsStack[blockScopeStackOffset]; + if (blockScopeStackOffset === 0) { + blockScopedVariableDeclarationsStack = []; + } + return statements; + } + + function addBlockScopedVariable(name: Identifier): void { + Debug.assert(blockScopeStackOffset > 0, "Cannot add a block scoped variable outside of an iteration body."); + (blockScopedVariableDeclarations || (blockScopedVariableDeclarations = [])).push(name); + } + function requestEmitHelper(helper: EmitHelper): void { Debug.assert(state > TransformationState.Uninitialized, "Cannot modify the transformation context during initialization."); Debug.assert(state < TransformationState.Completed, "Cannot modify the transformation context after transformation has completed."); @@ -512,28 +562,31 @@ namespace ts { } export const nullTransformationContext: TransformationContext = { - get factory() { return factory; }, - enableEmitNotification: noop, - enableSubstitution: noop, - endLexicalEnvironment: returnUndefined, + factory, getCompilerOptions: () => ({}), - getEmitHost: notImplemented, getEmitResolver: notImplemented, + getEmitHost: notImplemented, getEmitHelperFactory: notImplemented, + startLexicalEnvironment: noop, + resumeLexicalEnvironment: noop, + suspendLexicalEnvironment: noop, + endLexicalEnvironment: returnUndefined, setLexicalEnvironmentFlags: noop, getLexicalEnvironmentFlags: () => 0, - hoistFunctionDeclaration: noop, hoistVariableDeclaration: noop, + hoistFunctionDeclaration: noop, addInitializationStatement: noop, - isEmitNotificationEnabled: notImplemented, - isSubstitutionEnabled: notImplemented, - onEmitNode: noop, - onSubstituteNode: notImplemented, - readEmitHelpers: notImplemented, + startBlockScope: noop, + endBlockScope: returnUndefined, + addBlockScopedVariable: noop, requestEmitHelper: noop, - resumeLexicalEnvironment: noop, - startLexicalEnvironment: noop, - suspendLexicalEnvironment: noop, + readEmitHelpers: notImplemented, + enableSubstitution: noop, + enableEmitNotification: noop, + isSubstitutionEnabled: notImplemented, + isEmitNotificationEnabled: notImplemented, + onSubstituteNode: noEmitSubstitution, + onEmitNode: noEmitNotification, addDiagnostic: noop, }; } diff --git a/src/compiler/transformers/classFields.ts b/src/compiler/transformers/classFields.ts index 96ba926dd17db..e820851dde949 100644 --- a/src/compiler/transformers/classFields.ts +++ b/src/compiler/transformers/classFields.ts @@ -7,23 +7,89 @@ namespace ts { */ ClassAliases = 1 << 0, } - - const enum PrivateIdentifierPlacement { - InstanceField + export const enum PrivateIdentifierKind { + Field = "f", + Method = "m", + Accessor = "a" + } + interface PrivateIdentifierInfoBase { + /** + * brandCheckIdentifier can contain: + * - For instance field: The WeakMap that will be the storage for the field. + * - For instance methods or accessors: The WeakSet that will be used for brand checking. + * - For static members: The constructor that will be used for brand checking. + */ + brandCheckIdentifier: Identifier; + /** + * Stores if the identifier is static or not + */ + isStatic: boolean; + /** + * Stores if the identifier declaration is valid or not. Reserved names (e.g. #constructor) + * or duplicate identifiers are considered invalid. + */ + isValid: boolean; + } + interface PrivateIdentifierAccessorInfo extends PrivateIdentifierInfoBase { + kind: PrivateIdentifierKind.Accessor; + /** + * Identifier for a variable that will contain the private get accessor implementation, if any. + */ + getterName?: Identifier; + /** + * Identifier for a variable that will contain the private set accessor implementation, if any. + */ + setterName?: Identifier; + } + interface PrivateIdentifierMethodInfo extends PrivateIdentifierInfoBase { + kind: PrivateIdentifierKind.Method; + /** + * Identifier for a variable that will contain the private method implementation. + */ + methodName: Identifier; + } + interface PrivateIdentifierInstanceFieldInfo extends PrivateIdentifierInfoBase { + kind: PrivateIdentifierKind.Field; + isStatic: false; + /** + * Defined for ease of access when in a union with PrivateIdentifierStaticFieldInfo. + */ + variableName: undefined; + } + interface PrivateIdentifierStaticFieldInfo extends PrivateIdentifierInfoBase { + kind: PrivateIdentifierKind.Field; + isStatic: true; + /** + * Contains the variable that will server as the storage for the field. + */ + variableName: Identifier; } - type PrivateIdentifierInfo = PrivateIdentifierInstanceField; + type PrivateIdentifierInfo = + | PrivateIdentifierMethodInfo + | PrivateIdentifierInstanceFieldInfo + | PrivateIdentifierStaticFieldInfo + | PrivateIdentifierAccessorInfo; - interface PrivateIdentifierInstanceField { - placement: PrivateIdentifierPlacement.InstanceField; - weakMapName: Identifier; + interface PrivateIdentifierEnvironment { + /** + * Used for prefixing generated variable names. + */ + className: string; + /** + * Used for brand check on static members + */ + classConstructor?: Identifier; + /** + * Used for brand check on private methods. + */ + weakSetName?: Identifier; + /** + * A mapping of private names to information needed for transformation. + */ + identifiers: UnderscoreEscapedMap } - /** - * A mapping of private names to information needed for transformation. - */ - type PrivateIdentifierEnvironment = UnderscoreEscapedMap; - /** * Transforms ECMAScript Class Syntax. * TypeScript parameter property syntax is transformed in the TypeScript transformer. @@ -36,13 +102,15 @@ namespace ts { factory, hoistVariableDeclaration, endLexicalEnvironment, - resumeLexicalEnvironment + resumeLexicalEnvironment, + addBlockScopedVariable } = context; const resolver = context.getEmitResolver(); const compilerOptions = context.getCompilerOptions(); const languageVersion = getEmitScriptTarget(compilerOptions); + const useDefineForClassFields = getUseDefineForClassFields(compilerOptions); - const shouldTransformPrivateFields = languageVersion < ScriptTarget.ESNext; + const shouldTransformPrivateElements = languageVersion < ScriptTarget.ESNext; const previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; @@ -71,7 +139,7 @@ namespace ts { function transformSourceFile(node: SourceFile) { const options = context.getCompilerOptions(); if (node.isDeclarationFile - || options.useDefineForClassFields && options.target === ScriptTarget.ESNext) { + || useDefineForClassFields && options.target === ScriptTarget.ESNext) { return node; } const visited = visitEachChild(node, visitor, context); @@ -127,7 +195,7 @@ namespace ts { * Replace it with an empty identifier to indicate a problem with the code. */ function visitPrivateIdentifier(node: PrivateIdentifier) { - if (!shouldTransformPrivateFields) { + if (!shouldTransformPrivateElements) { return node; } return setOriginalNode(factory.createIdentifier(""), node); @@ -148,8 +216,7 @@ namespace ts { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.MethodDeclaration: - // Visit the name of the member (if it's a computed property name). - return visitEachChild(node, classElementVisitor, context); + return visitMethodOrAccessorDeclaration(node as MethodDeclaration | AccessorDeclaration); case SyntaxKind.PropertyDeclaration: return visitPropertyDeclaration(node as PropertyDeclaration); @@ -192,24 +259,89 @@ namespace ts { return node; } - function visitPropertyDeclaration(node: PropertyDeclaration) { + function visitMethodOrAccessorDeclaration(node: MethodDeclaration | AccessorDeclaration) { Debug.assert(!some(node.decorators)); - if (!shouldTransformPrivateFields && isPrivateIdentifier(node.name)) { - // Initializer is elided as the field is initialized in transformConstructor. - return factory.updatePropertyDeclaration( - node, - /*decorators*/ undefined, - visitNodes(node.modifiers, visitor, isModifier), - node.name, - /*questionOrExclamationToken*/ undefined, - /*type*/ undefined, - /*initializer*/ undefined + + if (!shouldTransformPrivateElements || !isPrivateIdentifier(node.name)) { + return visitEachChild(node, classElementVisitor, context); + } + + // leave invalid code untransformed + const info = accessPrivateIdentifier(node.name); + Debug.assert(info, "Undeclared private name for property declaration."); + if (!info.isValid) { + return node; + } + + const functionName = getHoistedFunctionName(node); + if (functionName) { + getPendingExpressions().push( + factory.createAssignment( + functionName, + factory.createFunctionExpression( + filter(node.modifiers, m => !isStaticModifier(m)), + node.asteriskToken, + functionName, + /* typeParameters */ undefined, + visitParameterList(node.parameters, classElementVisitor, context), + /* type */ undefined, + visitFunctionBody(node.body!, classElementVisitor, context) + ) + ) ); } + + // remove method declaration from class + return undefined; + } + + function getHoistedFunctionName(node: MethodDeclaration | AccessorDeclaration) { + Debug.assert(isPrivateIdentifier(node.name)); + const info = accessPrivateIdentifier(node.name); + Debug.assert(info, "Undeclared private name for property declaration."); + + if (info.kind === PrivateIdentifierKind.Method) { + return info.methodName; + } + + if (info.kind === PrivateIdentifierKind.Accessor) { + if (isGetAccessor(node)) { + return info.getterName; + } + if (isSetAccessor(node)) { + return info.setterName; + } + } + } + + function visitPropertyDeclaration(node: PropertyDeclaration) { + Debug.assert(!some(node.decorators)); + + if (isPrivateIdentifier(node.name)) { + if (!shouldTransformPrivateElements) { + // Initializer is elided as the field is initialized in transformConstructor. + return factory.updatePropertyDeclaration( + node, + /*decorators*/ undefined, + visitNodes(node.modifiers, visitor, isModifier), + node.name, + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined + ); + } + + // leave invalid code untransformed + const info = accessPrivateIdentifier(node.name); + Debug.assert(info, "Undeclared private name for property declaration."); + if (!info.isValid) { + return node; + } + } // Create a temporary variable to store a computed property name (if necessary). // If it's not inlineable, then we emit an expression after the class which assigns // the property name to the temporary variable. - const expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); + const expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || useDefineForClassFields); if (expr && !isSimpleInlineableExpression(expr)) { getPendingExpressions().push(expr); } @@ -217,23 +349,48 @@ namespace ts { } function createPrivateIdentifierAccess(info: PrivateIdentifierInfo, receiver: Expression): Expression { - receiver = visitNode(receiver, visitor, isExpression); - switch (info.placement) { - case PrivateIdentifierPlacement.InstanceField: + return createPrivateIdentifierAccessHelper(info, visitNode(receiver, visitor, isExpression)); + } + + function createPrivateIdentifierAccessHelper(info: PrivateIdentifierInfo, receiver: Expression): Expression { + setCommentRange(receiver, moveRangePos(receiver, -1)); + + switch(info.kind) { + case PrivateIdentifierKind.Accessor: + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper( + receiver, + info.brandCheckIdentifier, + info.kind, + info.getterName + ); + case PrivateIdentifierKind.Method: return context.getEmitHelperFactory().createClassPrivateFieldGetHelper( - nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver), - info.weakMapName + receiver, + info.brandCheckIdentifier, + info.kind, + info.methodName ); - default: return Debug.fail("Unexpected private identifier placement"); + case PrivateIdentifierKind.Field: + return context.getEmitHelperFactory().createClassPrivateFieldGetHelper( + receiver, + info.brandCheckIdentifier, + info.kind, + info.variableName + ); + default: + Debug.assertNever(info, "Unknown private element type"); } } function visitPropertyAccessExpression(node: PropertyAccessExpression) { - if (shouldTransformPrivateFields && isPrivateIdentifier(node.name)) { + if (shouldTransformPrivateElements && isPrivateIdentifier(node.name)) { const privateIdentifierInfo = accessPrivateIdentifier(node.name); if (privateIdentifierInfo) { - return setOriginalNode( - createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), + return setTextRange( + setOriginalNode( + createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), + node + ), node ); } @@ -242,7 +399,7 @@ namespace ts { } function visitPrefixUnaryExpression(node: PrefixUnaryExpression) { - if (shouldTransformPrivateFields && isPrivateIdentifierPropertyAccessExpression(node.operand)) { + if (shouldTransformPrivateElements && isPrivateIdentifierPropertyAccessExpression(node.operand)) { const operator = node.operator === SyntaxKind.PlusPlusToken ? SyntaxKind.PlusToken : node.operator === SyntaxKind.MinusMinusToken ? SyntaxKind.MinusToken : undefined; @@ -268,7 +425,7 @@ namespace ts { } function visitPostfixUnaryExpression(node: PostfixUnaryExpression, valueIsDiscarded: boolean) { - if (shouldTransformPrivateFields && isPrivateIdentifierPropertyAccessExpression(node.operand)) { + if (shouldTransformPrivateElements && isPrivateIdentifierPropertyAccessExpression(node.operand)) { const operator = node.operator === SyntaxKind.PlusPlusToken ? SyntaxKind.PlusToken : node.operator === SyntaxKind.MinusMinusToken ? SyntaxKind.MinusToken : undefined; @@ -310,7 +467,7 @@ namespace ts { visitNode(node.initializer, visitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitPostfixUnaryExpression(node.incrementor, /*valueIsDiscarded*/ true), - visitNode(node.statement, visitor, isStatement) + visitIterationBody(node.statement, visitor, context) ); } return visitEachChild(node, visitor, context); @@ -334,7 +491,7 @@ namespace ts { } function visitCallExpression(node: CallExpression) { - if (shouldTransformPrivateFields && isPrivateIdentifierPropertyAccessExpression(node.expression)) { + if (shouldTransformPrivateElements && isPrivateIdentifierPropertyAccessExpression(node.expression)) { // Transform call expressions of private names to properly bind the `this` parameter. const { thisArg, target } = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion); if (isCallChain(node)) { @@ -357,7 +514,7 @@ namespace ts { } function visitTaggedTemplateExpression(node: TaggedTemplateExpression) { - if (shouldTransformPrivateFields && isPrivateIdentifierPropertyAccessExpression(node.tag)) { + if (shouldTransformPrivateElements && isPrivateIdentifierPropertyAccessExpression(node.tag)) { // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access. const { thisArg, target } = factory.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion); return factory.updateTaggedTemplateExpression( @@ -375,10 +532,10 @@ namespace ts { } function visitBinaryExpression(node: BinaryExpression) { - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { if (isDestructuringAssignment(node)) { const savedPendingExpressions = pendingExpressions; - pendingExpressions = undefined!; + pendingExpressions = undefined; node = factory.updateBinaryExpression( node, visitNode(node.left, visitorDestructuringTarget), @@ -394,8 +551,11 @@ namespace ts { if (isAssignmentExpression(node) && isPrivateIdentifierPropertyAccessExpression(node.left)) { const info = accessPrivateIdentifier(node.left.name); if (info) { - return setOriginalNode( - createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), + return setTextRange( + setOriginalNode( + createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), + node + ), node ); } @@ -404,32 +564,49 @@ namespace ts { return visitEachChild(node, visitor, context); } - function createPrivateIdentifierAssignment(info: PrivateIdentifierInfo, receiver: Expression, right: Expression, operator: AssignmentOperator) { - switch (info.placement) { - case PrivateIdentifierPlacement.InstanceField: { - return createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator); - } - default: return Debug.fail("Unexpected private identifier placement"); - } - } - - function createPrivateIdentifierInstanceFieldAssignment(info: PrivateIdentifierInstanceField, receiver: Expression, right: Expression, operator: AssignmentOperator) { + function createPrivateIdentifierAssignment(info: PrivateIdentifierInfo, receiver: Expression, right: Expression, operator: AssignmentOperator): Expression { receiver = visitNode(receiver, visitor, isExpression); right = visitNode(right, visitor, isExpression); + if (isCompoundAssignment(operator)) { const { readExpression, initializeExpression } = createCopiableReceiverExpr(receiver); - return context.getEmitHelperFactory().createClassPrivateFieldSetHelper( - initializeExpression || readExpression, - info.weakMapName, - factory.createBinaryExpression( - context.getEmitHelperFactory().createClassPrivateFieldGetHelper(readExpression, info.weakMapName), - getNonAssignmentOperatorForCompoundAssignment(operator), - right - ) + receiver = initializeExpression || readExpression; + right = factory.createBinaryExpression( + createPrivateIdentifierAccessHelper(info, readExpression), + getNonAssignmentOperatorForCompoundAssignment(operator), + right ); } - else { - return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.weakMapName, right); + + setCommentRange(receiver, moveRangePos(receiver, -1)); + + switch(info.kind) { + case PrivateIdentifierKind.Accessor: + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper( + receiver, + info.brandCheckIdentifier, + right, + info.kind, + info.setterName + ); + case PrivateIdentifierKind.Method: + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper( + receiver, + info.brandCheckIdentifier, + right, + info.kind, + /* f */ undefined + ); + case PrivateIdentifierKind.Field: + return context.getEmitHelperFactory().createClassPrivateFieldSetHelper( + receiver, + info.brandCheckIdentifier, + right, + info.kind, + info.variableName + ); + default: + Debug.assertNever(info, "Unknown private element type"); } } @@ -439,15 +616,28 @@ namespace ts { function visitClassLike(node: ClassLikeDeclaration) { const savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { startPrivateIdentifierEnvironment(); + + const name = getNameOfDeclaration(node); + if (name && isIdentifier(name)) { + getPrivateIdentifierEnvironment().className = idText(name); + } + + const privateInstanceMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); + if (some(privateInstanceMethodsAndAccessors)) { + getPrivateIdentifierEnvironment().weakSetName = createHoistedVariableForClass( + "instances", + privateInstanceMethodsAndAccessors[0].name + ); + } } const result = isClassDeclaration(node) ? visitClassDeclaration(node) : visitClassExpression(node); - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { endPrivateIdentifierEnvironment(); } pendingExpressions = savedPendingExpressions; @@ -455,7 +645,11 @@ namespace ts { } function doesClassElementNeedTransform(node: ClassElement) { - return isPropertyDeclaration(node) || (shouldTransformPrivateFields && node.name && isPrivateIdentifier(node.name)); + return isPropertyDeclaration(node) || (shouldTransformPrivateElements && node.name && isPrivateIdentifier(node.name)); + } + + function getPrivateInstanceMethodsAndAccessors(node: ClassLikeDeclaration) { + return filter(node.members, isNonStaticMethodOrAccessorWithPrivateName); } function visitClassDeclaration(node: ClassDeclaration) { @@ -463,6 +657,17 @@ namespace ts { return visitEachChild(node, visitor, context); } + const staticProperties = getProperties(node, /*requireInitializer*/ false, /*isStatic*/ true); + let pendingPrivateStateAssignment: BinaryExpression | undefined; + if (shouldTransformPrivateElements && some(node.members, m => hasStaticModifier(m) && !!m.name && isPrivateIdentifier(m.name))) { + const temp = factory.createTempVariable(hoistVariableDeclaration, /* reservedInNestedScopes */ true); + getPrivateIdentifierEnvironment().classConstructor = factory.cloneNode(temp); + pendingPrivateStateAssignment = factory.createAssignment( + temp, + factory.getInternalName(node) + ); + } + const extendsClauseElement = getEffectiveBaseTypeNode(node); const isDerivedClass = !!(extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== SyntaxKind.NullKeyword); @@ -478,6 +683,10 @@ namespace ts { ) ]; + if (pendingPrivateStateAssignment) { + getPendingExpressions().unshift(pendingPrivateStateAssignment); + } + // Write any pending expressions from elided or moved computed property names if (some(pendingExpressions)) { statements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))); @@ -488,7 +697,7 @@ namespace ts { // From ES6 specification: // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. - const staticProperties = getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); + if (some(staticProperties)) { addPropertyStatements(statements, staticProperties, factory.getInternalName(node)); } @@ -510,10 +719,24 @@ namespace ts { // these statements after the class expression variable statement. const isDecoratedClassDeclaration = isClassDeclaration(getOriginalNode(node)); - const staticProperties = getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); + const staticProperties = getProperties(node, /*requireInitializer*/ false, /*isStatic*/ true); + const extendsClauseElement = getEffectiveBaseTypeNode(node); const isDerivedClass = !!(extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== SyntaxKind.NullKeyword); + const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & NodeCheckFlags.ClassWithConstructorReference; + let temp: Identifier | undefined; + function createClassTempVar() { + const classCheckFlags = resolver.getNodeCheckFlags(node); + const isClassWithConstructorReference = classCheckFlags & NodeCheckFlags.ClassWithConstructorReference; + const requiresBlockScopedVar = classCheckFlags & NodeCheckFlags.BlockScopedBindingInLoop; + return factory.createTempVariable(requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, !!isClassWithConstructorReference); + } + if (shouldTransformPrivateElements && some(node.members, m => hasStaticModifier(m) && !!m.name && isPrivateIdentifier(m.name))) { + temp = createClassTempVar(); + getPrivateIdentifierEnvironment().classConstructor = factory.cloneNode(temp); + } + const classExpression = factory.updateClassExpression( node, visitNodes(node.decorators, visitor, isDecorator), @@ -523,8 +746,8 @@ namespace ts { visitNodes(node.heritageClauses, visitor, isHeritageClause), transformClassMembers(node, isDerivedClass) ); - - if (some(staticProperties) || some(pendingExpressions)) { + const hasTransformableStatics = some(staticProperties, p => !!p.initializer || (shouldTransformPrivateElements && isPrivateIdentifier(p.name))); + if (hasTransformableStatics || some(pendingExpressions)) { if (isDecoratedClassDeclaration) { Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration."); @@ -536,12 +759,14 @@ namespace ts { if (pendingStatements && some(staticProperties)) { addPropertyStatements(pendingStatements, staticProperties, factory.getInternalName(node)); } + if (temp) { + return factory.inlineExpressions([factory.createAssignment(temp, classExpression), temp]); + } return classExpression; } else { const expressions: Expression[] = []; - const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & NodeCheckFlags.ClassWithConstructorReference; - const temp = factory.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + temp ||= createClassTempVar(); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); @@ -557,6 +782,7 @@ namespace ts { // Add any pending expressions leftover from elided or relocated computed property names addRange(expressions, map(pendingExpressions, startOnNewLine)); addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); + expressions.push(startOnNewLine(temp)); return factory.inlineExpressions(expressions); @@ -567,13 +793,17 @@ namespace ts { } function transformClassMembers(node: ClassDeclaration | ClassExpression, isDerivedClass: boolean) { - if (shouldTransformPrivateFields) { + if (shouldTransformPrivateElements) { // Declare private names. for (const member of node.members) { - if (isPrivateIdentifierPropertyDeclaration(member)) { - addPrivateIdentifierToEnvironment(member.name); + if (isPrivateIdentifierClassElementDeclaration(member)) { + addPrivateIdentifierToEnvironment(member); } } + + if (some(getPrivateInstanceMethodsAndAccessors(node))) { + createBrandCheckWeakSetForPrivateMethods(); + } } const members: ClassElement[] = []; @@ -585,22 +815,38 @@ namespace ts { return setTextRange(factory.createNodeArray(members), /*location*/ node.members); } - function isPropertyDeclarationThatRequiresConstructorStatement(member: ClassElement): member is PropertyDeclaration { - if (!isPropertyDeclaration(member) || hasStaticModifier(member) || hasSyntacticModifier(getOriginalNode(member), ModifierFlags.Abstract)) { + function createBrandCheckWeakSetForPrivateMethods() { + const { weakSetName } = getPrivateIdentifierEnvironment(); + Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + + getPendingExpressions().push( + factory.createAssignment( + weakSetName, + factory.createNewExpression( + factory.createIdentifier("WeakSet"), + /*typeArguments*/ undefined, + [] + ) + ) + ); + } + + function isClassElementThatRequiresConstructorStatement(member: ClassElement) { + if (hasStaticModifier(member) || hasSyntacticModifier(getOriginalNode(member), ModifierFlags.Abstract)) { return false; } - if (context.getCompilerOptions().useDefineForClassFields) { + if (useDefineForClassFields) { // If we are using define semantics and targeting ESNext or higher, // then we don't need to transform any class properties. return languageVersion < ScriptTarget.ESNext; } - return isInitializedProperty(member) || shouldTransformPrivateFields && isPrivateIdentifierPropertyDeclaration(member); + return isInitializedProperty(member) || shouldTransformPrivateElements && isPrivateIdentifierClassElementDeclaration(member); } function transformConstructor(node: ClassDeclaration | ClassExpression, isDerivedClass: boolean) { const constructor = visitNode(getFirstConstructorWithBody(node), visitor, isConstructorDeclaration); - const properties = node.members.filter(isPropertyDeclarationThatRequiresConstructorStatement); - if (!some(properties)) { + const elements = node.members.filter(isClassElementThatRequiresConstructorStatement); + if (!some(elements)) { return constructor; } const parameters = visitParameterList(constructor ? constructor.parameters : undefined, visitor, context); @@ -625,15 +871,16 @@ namespace ts { } function transformConstructorBody(node: ClassDeclaration | ClassExpression, constructor: ConstructorDeclaration | undefined, isDerivedClass: boolean) { - const useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; let properties = getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false); if (!useDefineForClassFields) { properties = filter(properties, property => !!property.initializer || isPrivateIdentifier(property.name)); } + const privateMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); + const needsConstructorBody = some(properties) || some(privateMethodsAndAccessors); // Only generate synthetic constructor when there are property initializers to move. - if (!constructor && !some(properties)) { + if (!constructor && !needsConstructorBody) { return visitFunctionBody(/*node*/ undefined, visitor, context); } @@ -683,7 +930,10 @@ namespace ts { indexOfFirstStatement = afterParameterProperties; } } - addPropertyStatements(statements, properties, factory.createThis()); + const receiver = factory.createThis(); + // private methods can be called in property initializers, they should execute first. + addMethodStatements(statements, privateMethodsAndAccessors, receiver); + addPropertyStatements(statements, properties, receiver); // Add existing statements, skipping the initial super call. if (constructor) { @@ -755,33 +1005,38 @@ namespace ts { */ function transformProperty(property: PropertyDeclaration, receiver: LeftHandSideExpression) { // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) - const emitAssignment = !context.getCompilerOptions().useDefineForClassFields; + const emitAssignment = !useDefineForClassFields; const propertyName = isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name)) : property.name; - if (shouldTransformPrivateFields && isPrivateIdentifier(propertyName)) { + if (shouldTransformPrivateElements && isPrivateIdentifier(propertyName)) { const privateIdentifierInfo = accessPrivateIdentifier(propertyName); if (privateIdentifierInfo) { - switch (privateIdentifierInfo.placement) { - case PrivateIdentifierPlacement.InstanceField: { + if (privateIdentifierInfo.kind === PrivateIdentifierKind.Field) { + if (!privateIdentifierInfo.isStatic) { return createPrivateInstanceFieldInitializer( receiver, visitNode(property.initializer, visitor, isExpression), - privateIdentifierInfo.weakMapName + privateIdentifierInfo.brandCheckIdentifier ); } + else { + return createPrivateStaticFieldInitializer( + privateIdentifierInfo.variableName, + visitNode(property.initializer, visitor, isExpression) + ); + } + } + else { + return undefined; } } else { Debug.fail("Undeclared private name for property declaration."); } } - if (isPrivateIdentifier(propertyName) && !property.initializer) { - return undefined; - } - - if (isPrivateIdentifier(propertyName) && !property.initializer) { + if ((isPrivateIdentifier(propertyName) || hasStaticModifier(property)) && !property.initializer) { return undefined; } @@ -819,6 +1074,27 @@ namespace ts { } } + /** + * Generates brand-check initializer for private methods. + * + * @param statements Statement list that should be used to append new statements. + * @param methods An array of method declarations. + * @param receiver The receiver on which each method should be assigned. + */ + function addMethodStatements(statements: Statement[], methods: readonly (MethodDeclaration | AccessorDeclaration)[], receiver: LeftHandSideExpression) { + if (!shouldTransformPrivateElements || !some(methods)) { + return; + } + + const { weakSetName } = getPrivateIdentifierEnvironment(); + Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + statements.push( + factory.createExpressionStatement( + createPrivateInstanceMethodInitializer(receiver, weakSetName) + ) + ); + } + /** * Hooks node substitutions. * @@ -869,7 +1145,6 @@ namespace ts { return undefined; } - /** * If the name is a computed property, this function transforms it, then either returns an expression which caches the * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations @@ -883,7 +1158,12 @@ namespace ts { const alreadyTransformed = isAssignmentExpression(innerExpression) && isGeneratedIdentifier(innerExpression.left); if (!alreadyTransformed && !inlinable && shouldHoist) { const generatedName = factory.getGeneratedNameForNode(name); - hoistVariableDeclaration(generatedName); + if (resolver.getNodeCheckFlags(name) & NodeCheckFlags.BlockScopedBindingInLoop) { + addBlockScopedVariable(generatedName); + } + else { + hoistVariableDeclaration(generatedName); + } return factory.createAssignment(generatedName, expression); } return (inlinable || isIdentifier(innerExpression)) ? undefined : expression; @@ -900,33 +1180,185 @@ namespace ts { } function getPrivateIdentifierEnvironment() { - return currentPrivateIdentifierEnvironment || (currentPrivateIdentifierEnvironment = new Map()); + if (!currentPrivateIdentifierEnvironment) { + currentPrivateIdentifierEnvironment = { + className: "", + identifiers: new Map() + }; + } + + return currentPrivateIdentifierEnvironment; } function getPendingExpressions() { return pendingExpressions || (pendingExpressions = []); } - function addPrivateIdentifierToEnvironment(name: PrivateIdentifier) { - const text = getTextOfPropertyName(name) as string; - const weakMapName = factory.createUniqueName("_" + text.substring(1), GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.ReservedInNestedScopes); - hoistVariableDeclaration(weakMapName); - getPrivateIdentifierEnvironment().set(name.escapedText, { placement: PrivateIdentifierPlacement.InstanceField, weakMapName }); - getPendingExpressions().push( - factory.createAssignment( + function addPrivateIdentifierToEnvironment(node: PrivateClassElementDeclaration) { + const text = getTextOfPropertyName(node.name) as string; + const env = getPrivateIdentifierEnvironment(); + const { weakSetName, classConstructor } = env; + const assignmentExpressions: Expression[] = []; + + const privateName = node.name.escapedText; + const previousInfo = env.identifiers.get(privateName); + const isValid = !isReservedPrivateName(node.name) && previousInfo === undefined; + + if (hasStaticModifier(node)) { + Debug.assert(classConstructor, "weakSetName should be set in private identifier environment"); + if (isPropertyDeclaration(node)) { + const variableName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: PrivateIdentifierKind.Field, + variableName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid, + }); + } + else if (isMethodDeclaration(node)) { + const functionName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: PrivateIdentifierKind.Method, + methodName: functionName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid, + }); + } + else if (isGetAccessorDeclaration(node)) { + const getterName = createHoistedVariableForPrivateName(text + "_get", node); + if (previousInfo?.kind === PrivateIdentifierKind.Accessor && previousInfo.isStatic && !previousInfo.getterName) { + previousInfo.getterName = getterName; + } + else { + env.identifiers.set(privateName, { + kind: PrivateIdentifierKind.Accessor, + getterName, + setterName: undefined, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid, + }); + } + } + else if (isSetAccessorDeclaration(node)) { + const setterName = createHoistedVariableForPrivateName(text + "_set", node); + if (previousInfo?.kind === PrivateIdentifierKind.Accessor && previousInfo.isStatic && !previousInfo.setterName) { + previousInfo.setterName = setterName; + } + else { + env.identifiers.set(privateName, { + kind: PrivateIdentifierKind.Accessor, + getterName: undefined, + setterName, + brandCheckIdentifier: classConstructor, + isStatic: true, + isValid, + }); + } + } + else { + Debug.assertNever(node, "Unknown class element type."); + } + } + else if (isPropertyDeclaration(node)) { + const weakMapName = createHoistedVariableForPrivateName(text, node); + env.identifiers.set(privateName, { + kind: PrivateIdentifierKind.Field, + brandCheckIdentifier: weakMapName, + isStatic: false, + variableName: undefined, + isValid, + }); + + assignmentExpressions.push(factory.createAssignment( weakMapName, factory.createNewExpression( factory.createIdentifier("WeakMap"), /*typeArguments*/ undefined, [] ) - ) - ); + )); + } + else if (isMethodDeclaration(node)) { + Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + + env.identifiers.set(privateName, { + kind: PrivateIdentifierKind.Method, + methodName: createHoistedVariableForPrivateName(text, node), + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid, + }); + } + else if (isAccessor(node)) { + Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + + if (isGetAccessor(node)) { + const getterName = createHoistedVariableForPrivateName(text + "_get", node); + + if (previousInfo?.kind === PrivateIdentifierKind.Accessor && !previousInfo.isStatic && !previousInfo.getterName) { + previousInfo.getterName = getterName; + } + else { + env.identifiers.set(privateName, { + kind: PrivateIdentifierKind.Accessor, + getterName, + setterName: undefined, + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid, + }); + } + } + else { + const setterName = createHoistedVariableForPrivateName(text + "_set", node); + + if (previousInfo?.kind === PrivateIdentifierKind.Accessor && !previousInfo.isStatic && !previousInfo.setterName) { + previousInfo.setterName = setterName; + } + else { + env.identifiers.set(privateName, { + kind: PrivateIdentifierKind.Accessor, + getterName: undefined, + setterName, + brandCheckIdentifier: weakSetName, + isStatic: false, + isValid, + }); + } + } + } + else { + Debug.assertNever(node, "Unknown class element type."); + } + + getPendingExpressions().push(...assignmentExpressions); + } + + function createHoistedVariableForClass(name: string, node: PrivateIdentifier): Identifier { + const { className } = getPrivateIdentifierEnvironment(); + const prefix = className ? `_${className}` : ""; + const identifier = factory.createUniqueName(`${prefix}_${name}`, GeneratedIdentifierFlags.Optimistic); + + if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.BlockScopedBindingInLoop) { + addBlockScopedVariable(identifier); + } + else { + hoistVariableDeclaration(identifier); + } + + return identifier; + } + + function createHoistedVariableForPrivateName(privateName: string, node: PrivateClassElementDeclaration): Identifier { + return createHoistedVariableForClass(privateName.substring(1), node.name); } function accessPrivateIdentifier(name: PrivateIdentifier) { if (currentPrivateIdentifierEnvironment) { - const info = currentPrivateIdentifierEnvironment.get(name.escapedText); + const info = currentPrivateIdentifierEnvironment.identifiers.get(name.escapedText); if (info) { return info; } @@ -936,7 +1368,7 @@ namespace ts { if (!env) { continue; } - const info = env.get(name.escapedText); + const info = env.identifiers.get(name.escapedText); if (info) { return info; } @@ -1066,6 +1498,15 @@ namespace ts { } } + function createPrivateStaticFieldInitializer(variableName: Identifier, initializer: Expression | undefined) { + return factory.createAssignment( + variableName, + factory.createObjectLiteralExpression([ + factory.createPropertyAssignment("value", initializer || factory.createVoidZero()) + ]) + ); + } + function createPrivateInstanceFieldInitializer(receiver: LeftHandSideExpression, initializer: Expression | undefined, weakMapName: Identifier) { return factory.createCallExpression( factory.createPropertyAccessExpression(weakMapName, "set"), @@ -1073,4 +1514,16 @@ namespace ts { [receiver, initializer || factory.createVoidZero()] ); } + + function createPrivateInstanceMethodInitializer(receiver: LeftHandSideExpression, weakSetName: Identifier) { + return factory.createCallExpression( + factory.createPropertyAccessExpression(weakSetName, "add"), + /*typeArguments*/ undefined, + [receiver] + ); + } + + function isReservedPrivateName(node: PrivateIdentifier) { + return node.escapedText === "#constructor"; + } } diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index 69add2945f4ba..5a56075706720 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -206,13 +206,15 @@ namespace ts { } function reportNonlocalAugmentation(containingFile: SourceFile, parentSymbol: Symbol, symbol: Symbol) { - const primaryDeclaration = find(parentSymbol.declarations, d => getSourceFileOfNode(d) === containingFile)!; + const primaryDeclaration = parentSymbol.declarations?.find(d => getSourceFileOfNode(d) === containingFile)!; const augmentingDeclarations = filter(symbol.declarations, d => getSourceFileOfNode(d) !== containingFile); - for (const augmentations of augmentingDeclarations) { - context.addDiagnostic(addRelatedInfo( - createDiagnosticForNode(augmentations, Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), - createDiagnosticForNode(primaryDeclaration, Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file) - )); + if (augmentingDeclarations) { + for (const augmentations of augmentingDeclarations) { + context.addDiagnostic(addRelatedInfo( + createDiagnosticForNode(augmentations, Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), + createDiagnosticForNode(primaryDeclaration, Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file) + )); + } } } @@ -370,9 +372,7 @@ namespace ts { if (declFileName) { const specifier = moduleSpecifiers.getModuleSpecifier( - // We pathify the baseUrl since we pathify the other paths here, so we can still easily check if the other paths are within the baseUrl - // TODO: Should we _always_ be pathifying the baseUrl as we read it in? - { ...options, baseUrl: options.baseUrl && toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }, + options, currentSourceFile, toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), @@ -1200,7 +1200,7 @@ namespace ts { fakespace.symbol = props[0].parent!; const exportMappings: [Identifier, string][] = []; let declarations: (VariableStatement | ExportDeclaration)[] = mapDefined(props, p => { - if (!isPropertyAccessExpression(p.valueDeclaration)) { + if (!p.valueDeclaration || !isPropertyAccessExpression(p.valueDeclaration)) { return undefined; // TODO GH#33569: Handle element access expressions that created late bound names (rather than silently omitting them) } getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration); @@ -1538,7 +1538,7 @@ namespace ts { } function ensureModifierFlags(node: Node): ModifierFlags { - let mask = ModifierFlags.All ^ (ModifierFlags.Public | ModifierFlags.Async); // No async modifiers in declaration files + let mask = ModifierFlags.All ^ (ModifierFlags.Public | ModifierFlags.Async | ModifierFlags.Override); // No async and override modifiers in declaration files let additions = (needsDeclare && !isAlwaysType(node)) ? ModifierFlags.Ambient : ModifierFlags.None; const parentIsFile = node.parent.kind === SyntaxKind.SourceFile; if (!parentIsFile || (isBundledEmit && parentIsFile && isExternalModule(node.parent as SourceFile))) { diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index 6f28a651190e7..5cb0aa35498ec 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -1626,7 +1626,7 @@ namespace ts { const memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); const propertyName = visitNode(member.name, visitor, isPropertyName); let e: Expression; - if (!isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) { + if (!isPrivateIdentifier(propertyName) && getUseDefineForClassFields(context.getCompilerOptions())) { const name = isComputedPropertyName(propertyName) ? propertyName.expression : isIdentifier(propertyName) ? factory.createStringLiteral(unescapeLeadingUnderscores(propertyName.escapedText)) : propertyName; diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index 6c3c8c1332acf..a2d2985e75b55 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -225,7 +225,7 @@ namespace ts { ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)! : visitNode(node.initializer, visitor, isForInitializer), visitNode(node.expression, visitor, isExpression), - visitNode(node.statement, asyncBodyVisitor, isStatement, factory.liftToBlock) + visitIterationBody(node.statement, asyncBodyVisitor, context) ); } @@ -237,7 +237,7 @@ namespace ts { ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)! : visitNode(node.initializer, visitor, isForInitializer), visitNode(node.expression, visitor, isExpression), - visitNode(node.statement, asyncBodyVisitor, isStatement, factory.liftToBlock) + visitIterationBody(node.statement, asyncBodyVisitor, context) ); } @@ -250,7 +250,7 @@ namespace ts { : visitNode(node.initializer, visitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, visitor, isExpression), - visitNode(node.statement, asyncBodyVisitor, isStatement, factory.liftToBlock) + visitIterationBody(node.statement, asyncBodyVisitor, context) ); } diff --git a/src/compiler/transformers/es2018.ts b/src/compiler/transformers/es2018.ts index 41fcc6c25d9b9..b7b04f191cf62 100644 --- a/src/compiler/transformers/es2018.ts +++ b/src/compiler/transformers/es2018.ts @@ -575,7 +575,7 @@ namespace ts { visitNode(node.initializer, visitorWithUnusedExpressionResult, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, visitorWithUnusedExpressionResult, isExpression), - visitNode(node.statement, visitor, isStatement) + visitIterationBody(node.statement, visitor, context) ); } @@ -648,7 +648,7 @@ namespace ts { let bodyLocation: TextRange | undefined; let statementsLocation: TextRange | undefined; const statements: Statement[] = [visitNode(binding, visitor, isStatement)]; - const statement = visitNode(node.statement, visitor, isStatement); + const statement = visitIterationBody(node.statement, visitor, context); if (isBlock(statement)) { addRange(statements, statement.statements); bodyLocation = statement; diff --git a/src/compiler/transformers/es2020.ts b/src/compiler/transformers/es2020.ts index bd0d12cf8d772..2434e36559be1 100644 --- a/src/compiler/transformers/es2020.ts +++ b/src/compiler/transformers/es2020.ts @@ -21,11 +21,15 @@ namespace ts { return node; } switch (node.kind) { + case SyntaxKind.CallExpression: { + const updated = visitNonOptionalCallExpression(node as CallExpression, /*captureThisArg*/ false); + Debug.assertNotNode(updated, isSyntheticReference); + return updated; + } case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ElementAccessExpression: - case SyntaxKind.CallExpression: - if (node.flags & NodeFlags.OptionalChain) { - const updated = visitOptionalExpression(node as OptionalChain, /*captureThisArg*/ false, /*isDelete*/ false); + if (isOptionalChain(node)) { + const updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false); Debug.assertNotNode(updated, isSyntheticReference); return updated; } @@ -94,6 +98,15 @@ namespace ts { // If `node` is an optional chain, then it is the outermost chain of an optional expression. return visitOptionalExpression(node, captureThisArg, /*isDelete*/ false); } + if (isParenthesizedExpression(node.expression) && isOptionalChain(skipParentheses(node.expression))) { + // capture thisArg for calls of parenthesized optional chains like `(foo?.bar)()` + const expression = visitNonOptionalParenthesizedExpression(node.expression, /*captureThisArg*/ true, /*isDelete*/ false); + const args = visitNodes(node.arguments, visitor, isExpression); + if (isSyntheticReference(expression)) { + return setTextRange(factory.createFunctionCallCall(expression.expression, expression.thisArg, args), node); + } + return factory.updateCallExpression(node, expression, /*typeArguments*/ undefined, args); + } return visitEachChild(node, visitor, context); } diff --git a/src/compiler/transformers/es2021.ts b/src/compiler/transformers/es2021.ts new file mode 100644 index 0000000000000..271ee58e7f214 --- /dev/null +++ b/src/compiler/transformers/es2021.ts @@ -0,0 +1,91 @@ +/*@internal*/ +namespace ts { + export function transformES2021(context: TransformationContext) { + const { + hoistVariableDeclaration, + factory + } = context; + return chainBundle(context, transformSourceFile); + + function transformSourceFile(node: SourceFile) { + if (node.isDeclarationFile) { + return node; + } + + return visitEachChild(node, visitor, context); + } + + function visitor(node: Node): VisitResult { + if ((node.transformFlags & TransformFlags.ContainsES2021) === 0) { + return node; + } + switch (node.kind) { + case SyntaxKind.BinaryExpression: + const binaryExpression = node; + if (isLogicalOrCoalescingAssignmentExpression(binaryExpression)) { + return transformLogicalAssignment(binaryExpression); + } + // falls through + default: + return visitEachChild(node, visitor, context); + } + } + + function transformLogicalAssignment(binaryExpression: AssignmentExpression>): VisitResult { + const operator = binaryExpression.operatorToken; + const nonAssignmentOperator = getNonAssignmentOperatorForCompoundAssignment(operator.kind); + let left = skipParentheses(visitNode(binaryExpression.left, visitor, isLeftHandSideExpression)); + let assignmentTarget = left; + const right = skipParentheses(visitNode(binaryExpression.right, visitor, isExpression)); + + if (isAccessExpression(left)) { + const propertyAccessTargetSimpleCopiable = isSimpleCopiableExpression(left.expression); + const propertyAccessTarget = propertyAccessTargetSimpleCopiable ? left.expression : + factory.createTempVariable(hoistVariableDeclaration); + const propertyAccessTargetAssignment = propertyAccessTargetSimpleCopiable ? left.expression : factory.createAssignment( + propertyAccessTarget, + left.expression + ); + + if (isPropertyAccessExpression(left)) { + assignmentTarget = factory.createPropertyAccessExpression( + propertyAccessTarget, + left.name + ); + left = factory.createPropertyAccessExpression( + propertyAccessTargetAssignment, + left.name + ); + } + else { + const elementAccessArgumentSimpleCopiable = isSimpleCopiableExpression(left.argumentExpression); + const elementAccessArgument = elementAccessArgumentSimpleCopiable ? left.argumentExpression : + factory.createTempVariable(hoistVariableDeclaration); + + assignmentTarget = factory.createElementAccessExpression( + propertyAccessTarget, + elementAccessArgument + ); + left = factory.createElementAccessExpression( + propertyAccessTargetAssignment, + elementAccessArgumentSimpleCopiable ? left.argumentExpression : factory.createAssignment( + elementAccessArgument, + left.argumentExpression + ) + ); + } + } + + return factory.createBinaryExpression( + left, + nonAssignmentOperator, + factory.createParenthesizedExpression( + factory.createAssignment( + assignmentTarget, + right + ) + ) + ); + } + } +} diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index 09b68d57e25b5..d210ed472f34e 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -1,91 +1,24 @@ /*@internal*/ namespace ts { - export function transformESNext(context: TransformationContext) { - const { - hoistVariableDeclaration, - factory - } = context; - return chainBundle(context, transformSourceFile); - - function transformSourceFile(node: SourceFile) { - if (node.isDeclarationFile) { - return node; - } - - return visitEachChild(node, visitor, context); - } - - function visitor(node: Node): VisitResult { - if ((node.transformFlags & TransformFlags.ContainsESNext) === 0) { - return node; - } - switch (node.kind) { - case SyntaxKind.BinaryExpression: - const binaryExpression = node; - if (isLogicalOrCoalescingAssignmentExpression(binaryExpression)) { - return transformLogicalAssignment(binaryExpression); - } - // falls through - default: - return visitEachChild(node, visitor, context); - } - } - - function transformLogicalAssignment(binaryExpression: AssignmentExpression>): VisitResult { - const operator = binaryExpression.operatorToken; - const nonAssignmentOperator = getNonAssignmentOperatorForCompoundAssignment(operator.kind); - let left = skipParentheses(visitNode(binaryExpression.left, visitor, isLeftHandSideExpression)); - let assignmentTarget = left; - const right = skipParentheses(visitNode(binaryExpression.right, visitor, isExpression)); - - if (isAccessExpression(left)) { - const propertyAccessTargetSimpleCopiable = isSimpleCopiableExpression(left.expression); - const propertyAccessTarget = propertyAccessTargetSimpleCopiable ? left.expression : - factory.createTempVariable(hoistVariableDeclaration); - const propertyAccessTargetAssignment = propertyAccessTargetSimpleCopiable ? left.expression : factory.createAssignment( - propertyAccessTarget, - left.expression - ); - - if (isPropertyAccessExpression(left)) { - assignmentTarget = factory.createPropertyAccessExpression( - propertyAccessTarget, - left.name - ); - left = factory.createPropertyAccessExpression( - propertyAccessTargetAssignment, - left.name - ); - } - else { - const elementAccessArgumentSimpleCopiable = isSimpleCopiableExpression(left.argumentExpression); - const elementAccessArgument = elementAccessArgumentSimpleCopiable ? left.argumentExpression : - factory.createTempVariable(hoistVariableDeclaration); - - assignmentTarget = factory.createElementAccessExpression( - propertyAccessTarget, - elementAccessArgument - ); - left = factory.createElementAccessExpression( - propertyAccessTargetAssignment, - elementAccessArgumentSimpleCopiable ? left.argumentExpression : factory.createAssignment( - elementAccessArgument, - left.argumentExpression - ) - ); - } - } - - return factory.createBinaryExpression( - left, - nonAssignmentOperator, - factory.createParenthesizedExpression( - factory.createAssignment( - assignmentTarget, - right - ) - ) - ); - } - } + export function transformESNext(context: TransformationContext) { + return chainBundle(context, transformSourceFile); + + function transformSourceFile(node: SourceFile) { + if (node.isDeclarationFile) { + return node; + } + + return visitEachChild(node, visitor, context); + } + + function visitor(node: Node): VisitResult { + if ((node.transformFlags & TransformFlags.ContainsESNext) === 0) { + return node; + } + switch (node.kind) { + default: + return visitEachChild(node, visitor, context); + } + } + } } diff --git a/src/compiler/transformers/generators.ts b/src/compiler/transformers/generators.ts index 6ae08275e3a02..fca06a8ce22ca 100644 --- a/src/compiler/transformers/generators.ts +++ b/src/compiler/transformers/generators.ts @@ -1502,7 +1502,7 @@ namespace ts { : undefined, visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, visitor, isExpression), - visitNode(node.statement, visitor, isStatement, factory.liftToBlock) + visitIterationBody(node.statement, visitor, context) ); } else { diff --git a/src/compiler/transformers/jsx.ts b/src/compiler/transformers/jsx.ts index 9814f29b2a28f..1759d72bfda4e 100644 --- a/src/compiler/transformers/jsx.ts +++ b/src/compiler/transformers/jsx.ts @@ -292,26 +292,38 @@ namespace ts { // When there are no attributes, React wants "null" } else { - // Map spans of JsxAttribute nodes into object literals and spans - // of JsxSpreadAttribute nodes into expressions. - const segments = flatten( - spanMap(attrs, isJsxSpreadAttribute, (attrs, isSpread) => isSpread - ? map(attrs, transformJsxSpreadAttributeToExpression) - : factory.createObjectLiteralExpression(map(attrs, transformJsxAttributeToObjectLiteralElement)) - ) - ); - - if (isJsxSpreadAttribute(attrs[0])) { - // We must always emit at least one object literal before a spread - // argument.factory.createObjectLiteral - segments.unshift(factory.createObjectLiteralExpression()); + const target = compilerOptions.target; + if (target && target >= ScriptTarget.ES2018) { + objectProperties = factory.createObjectLiteralExpression( + flatten( + spanMap(attrs, isJsxSpreadAttribute, (attrs, isSpread) => + isSpread ? map(attrs, transformJsxSpreadAttributeToSpreadAssignment) : map(attrs, transformJsxAttributeToObjectLiteralElement) + ) + ) + ); } + else { + // Map spans of JsxAttribute nodes into object literals and spans + // of JsxSpreadAttribute nodes into expressions. + const segments = flatten( + spanMap(attrs, isJsxSpreadAttribute, (attrs, isSpread) => isSpread + ? map(attrs, transformJsxSpreadAttributeToExpression) + : factory.createObjectLiteralExpression(map(attrs, transformJsxAttributeToObjectLiteralElement)) + ) + ); + + if (isJsxSpreadAttribute(attrs[0])) { + // We must always emit at least one object literal before a spread + // argument.factory.createObjectLiteral + segments.unshift(factory.createObjectLiteralExpression()); + } - // Either emit one big object literal (no spread attribs), or - // a call to the __assign helper. - objectProperties = singleOrUndefined(segments); - if (!objectProperties) { - objectProperties = emitHelpers().createAssignHelper(segments); + // Either emit one big object literal (no spread attribs), or + // a call to the __assign helper. + objectProperties = singleOrUndefined(segments); + if (!objectProperties) { + objectProperties = emitHelpers().createAssignHelper(segments); + } } } @@ -376,6 +388,10 @@ namespace ts { return element; } + function transformJsxSpreadAttributeToSpreadAssignment(node: JsxSpreadAttribute) { + return factory.createSpreadAssignment(visitNode(node.expression, visitor, isExpression)); + } + function transformJsxSpreadAttributeToExpression(node: JsxSpreadAttribute) { return visitNode(node.expression, visitor, isExpression); } diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts index 24d962c6e2f28..d2c6d806d1309 100644 --- a/src/compiler/transformers/module/module.ts +++ b/src/compiler/transformers/module/module.ts @@ -1,5 +1,6 @@ /*@internal*/ namespace ts { + export function transformModule(context: TransformationContext) { interface AsynchronousDependencies { aliasedModuleNames: Expression[]; @@ -1762,11 +1763,9 @@ namespace ts { if (externalHelpersModuleName) { return factory.createPropertyAccessExpression(externalHelpersModuleName, node); } - return node; } - - if (!(isGeneratedIdentifier(node) && !(node.autoGenerateFlags & GeneratedIdentifierFlags.AllowNameSubstitution)) && !isLocalName(node)) { + else if (!(isGeneratedIdentifier(node) && !(node.autoGenerateFlags & GeneratedIdentifierFlags.AllowNameSubstitution)) && !isLocalName(node)) { const exportContainer = resolver.getReferencedExportContainer(node, isExportName(node)); if (exportContainer && exportContainer.kind === SyntaxKind.SourceFile) { return setTextRange( @@ -1777,7 +1776,6 @@ namespace ts { /*location*/ node ); } - const importDeclaration = resolver.getReferencedImportDeclaration(node); if (importDeclaration) { if (isImportClause(importDeclaration)) { @@ -1864,17 +1862,22 @@ namespace ts { if (exportedNames) { let expression: Expression = node.kind === SyntaxKind.PostfixUnaryExpression ? setTextRange( - factory.createBinaryExpression( - node.operand, - factory.createToken(node.operator === SyntaxKind.PlusPlusToken ? SyntaxKind.PlusEqualsToken : SyntaxKind.MinusEqualsToken), - factory.createNumericLiteral(1) + factory.createPrefixUnaryExpression( + node.operator, + node.operand ), /*location*/ node) : node; for (const exportName of exportedNames) { // Mark the node to prevent triggering this rule again. noSubstitution[getNodeId(expression)] = true; - expression = factory.createParenthesizedExpression(createExportExpression(exportName, expression)); + expression = createExportExpression(exportName, expression); + } + if (node.kind === SyntaxKind.PostfixUnaryExpression) { + noSubstitution[getNodeId(expression)] = true; + expression = node.operator === SyntaxKind.PlusPlusToken + ? factory.createSubtract(expression, factory.createNumericLiteral(1)) + : factory.createAdd(expression, factory.createNumericLiteral(1)); } return expression; } diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts index a5e0c9bbbf4ef..0d7141a4ab5ff 100644 --- a/src/compiler/transformers/module/system.ts +++ b/src/compiler/transformers/module/system.ts @@ -133,7 +133,7 @@ namespace ts { moduleInfo = undefined!; exportFunction = undefined!; contextObject = undefined!; - hoistedStatements = undefined!; + hoistedStatements = undefined; enclosingBlockScopedContainer = undefined!; return updated; } @@ -1231,7 +1231,7 @@ namespace ts { node.initializer && visitForInitializer(node.initializer), visitNode(node.condition, destructuringAndImportCallVisitor, isExpression), visitNode(node.incrementor, destructuringAndImportCallVisitor, isExpression), - visitNode(node.statement, nestedElementVisitor, isStatement) + visitIterationBody(node.statement, nestedElementVisitor, context) ); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; @@ -1251,7 +1251,7 @@ namespace ts { node, visitForInitializer(node.initializer), visitNode(node.expression, destructuringAndImportCallVisitor, isExpression), - visitNode(node.statement, nestedElementVisitor, isStatement, factory.liftToBlock) + visitIterationBody(node.statement, nestedElementVisitor, context) ); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; @@ -1272,7 +1272,7 @@ namespace ts { node.awaitModifier, visitForInitializer(node.initializer), visitNode(node.expression, destructuringAndImportCallVisitor, isExpression), - visitNode(node.statement, nestedElementVisitor, isStatement, factory.liftToBlock) + visitIterationBody(node.statement, nestedElementVisitor, context) ); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; @@ -1320,7 +1320,7 @@ namespace ts { function visitDoStatement(node: DoStatement): VisitResult { return factory.updateDoStatement( node, - visitNode(node.statement, nestedElementVisitor, isStatement, factory.liftToBlock), + visitIterationBody(node.statement, nestedElementVisitor, context), visitNode(node.expression, destructuringAndImportCallVisitor, isExpression) ); } @@ -1334,7 +1334,7 @@ namespace ts { return factory.updateWhileStatement( node, visitNode(node.expression, destructuringAndImportCallVisitor, isExpression), - visitNode(node.statement, nestedElementVisitor, isStatement, factory.liftToBlock) + visitIterationBody(node.statement, nestedElementVisitor, context) ); } @@ -1529,7 +1529,7 @@ namespace ts { } /** - * Determines whether the target of a destructuring assigment refers to an exported symbol. + * Determines whether the target of a destructuring assignment refers to an exported symbol. * * @param node The destructuring target. */ diff --git a/src/compiler/transformers/utilities.ts b/src/compiler/transformers/utilities.ts index a52cf7c68cdf7..e1c3b0b957d6d 100644 --- a/src/compiler/transformers/utilities.ts +++ b/src/compiler/transformers/utilities.ts @@ -269,8 +269,7 @@ namespace ts { * any such locations */ export function isSimpleInlineableExpression(expression: Expression) { - return !isIdentifier(expression) && isSimpleCopiableExpression(expression) || - isWellKnownSymbolSyntactically(expression); + return !isIdentifier(expression) && isSimpleCopiableExpression(expression); } export function isCompoundAssignment(kind: BinaryOperator): kind is CompoundAssignmentOperator { @@ -365,4 +364,13 @@ namespace ts { return member.kind === SyntaxKind.PropertyDeclaration && (member).initializer !== undefined; } + + /** + * Gets a value indicating whether a class element is a private instance method or accessor. + * + * @param member The class element node. + */ + export function isNonStaticMethodOrAccessorWithPrivateName(member: ClassElement): member is PrivateIdentifierMethodDeclaration | PrivateIdentifierAccessorDeclaration { + return !hasStaticModifier(member) && isMethodOrAccessor(member) && isPrivateIdentifier(member.name); + } } diff --git a/src/compiler/tsbuildPublic.ts b/src/compiler/tsbuildPublic.ts index 0f019b3f9c6d3..ec2097dd9552d 100644 --- a/src/compiler/tsbuildPublic.ts +++ b/src/compiler/tsbuildPublic.ts @@ -131,9 +131,9 @@ namespace ts { } export interface SolutionBuilder { - build(project?: string, cancellationToken?: CancellationToken): ExitStatus; + build(project?: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; clean(project?: string): ExitStatus; - buildReferences(project: string, cancellationToken?: CancellationToken): ExitStatus; + buildReferences(project: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; cleanReferences(project?: string): ExitStatus; getNextInvalidatedProject(cancellationToken?: CancellationToken): InvalidatedProject | undefined; @@ -238,6 +238,7 @@ namespace ts { readonly compilerHost: CompilerHost; readonly moduleResolutionCache: ModuleResolutionCache | undefined; + readonly typeReferenceDirectiveResolutionCache: TypeReferenceDirectiveResolutionCache | undefined; // Mutable state buildOrder: AnyBuildOrder | undefined; @@ -275,11 +276,17 @@ namespace ts { compilerHost.resolveModuleNames = maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = maybeBind(host, host.resolveTypeReferenceDirectives); const moduleResolutionCache = !compilerHost.resolveModuleNames ? createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined; + const typeReferenceDirectiveResolutionCache = !compilerHost.resolveTypeReferenceDirectives ? createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache?.getPackageJsonInfoCache()) : undefined; if (!compilerHost.resolveModuleNames) { const loader = (moduleName: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule!; compilerHost.resolveModuleNames = (moduleNames, containingFile, _reusedNames, redirectedReference) => loadWithLocalCache(Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader); } + if (!compilerHost.resolveTypeReferenceDirectives) { + const loader = (moduleName: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveTypeReferenceDirective(moduleName, containingFile, state.projectCompilerOptions, compilerHost, redirectedReference, state.typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective!; + compilerHost.resolveTypeReferenceDirectives = (typeReferenceDirectiveNames, containingFile, redirectedReference) => + loadWithLocalCache(Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader); + } const { watchFile, watchDirectory, writeLog } = createWatchFactory(hostWithWatch, options); @@ -310,6 +317,7 @@ namespace ts { compilerHost, moduleResolutionCache, + typeReferenceDirectiveResolutionCache, // Mutable state buildOrder: undefined, @@ -356,6 +364,11 @@ namespace ts { return !!(entry as ParsedCommandLine).options; } + function getCachedParsedConfigFile(state: SolutionBuilderState, configFilePath: ResolvedConfigFilePath): ParsedCommandLine | undefined { + const value = state.configFileCache.get(configFilePath); + return value && isParsedCommandLine(value) ? value : undefined; + } + function parseConfigFile(state: SolutionBuilderState, configFileName: ResolvedConfigFileName, configFilePath: ResolvedConfigFilePath): ParsedCommandLine | undefined { const { configFileCache } = state; const value = configFileCache.get(configFilePath); @@ -543,7 +556,7 @@ namespace ts { function disableCache(state: SolutionBuilderState) { if (!state.cache) return; - const { cache, host, compilerHost, extendedConfigCache, moduleResolutionCache } = state; + const { cache, host, compilerHost, extendedConfigCache, moduleResolutionCache, typeReferenceDirectiveResolutionCache } = state; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; @@ -553,10 +566,8 @@ namespace ts { compilerHost.getSourceFile = cache.originalGetSourceFile; state.readFileWithCache = cache.originalReadFileWithCache; extendedConfigCache.clear(); - if (moduleResolutionCache) { - moduleResolutionCache.directoryToModuleNameMap.clear(); - moduleResolutionCache.moduleNameToDirectoryMap.clear(); - } + moduleResolutionCache?.clear(); + typeReferenceDirectiveResolutionCache?.clear(); state.cache = undefined; } @@ -837,7 +848,8 @@ namespace ts { const { host, compilerHost } = state; state.projectCompilerOptions = config.options; // Update module resolution cache if needed - updateModuleResolutionCache(state, project, config); + state.moduleResolutionCache?.update(config.options); + state.typeReferenceDirectiveResolutionCache?.update(config.options); // Create program program = host.createProgram( @@ -1114,7 +1126,7 @@ namespace ts { break; case BuildStep.BuildInvalidatedProjectOfBundle: - Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken); + Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken, writeFile, customTransformers); step = BuildStep.Done; break; @@ -1301,40 +1313,9 @@ namespace ts { return { buildResult, step: BuildStep.QueueReferencingProjects }; } - function updateModuleResolutionCache( - state: SolutionBuilderState, - proj: ResolvedConfigFileName, - config: ParsedCommandLine - ) { - if (!state.moduleResolutionCache) return; - - // Update module resolution cache if needed - const { moduleResolutionCache } = state; - const projPath = toPath(state, proj); - if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) { - // The own map will be for projectCompilerOptions - Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0); - moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap); - moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap); - } - else { - // Set correct own map - Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0); - - const ref: ResolvedProjectReference = { - sourceFile: config.options.configFile!, - commandLine: config - }; - moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref)); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref)); - } - moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options); - moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options); - } - function checkConfigFileUpToDateStatus(state: SolutionBuilderState, configFile: string, oldestOutputFileTime: Date, oldestOutputFileName: string): Status.OutOfDateWithSelf | undefined { // Check tsconfig time - const tsconfigTime = state.host.getModifiedTime(configFile) || missingFileModifiedTime; + const tsconfigTime = getModifiedTime(state.host, configFile); if (oldestOutputFileTime < tsconfigTime) { return { type: UpToDateStatusType.OutOfDateWithSelf, @@ -1345,6 +1326,7 @@ namespace ts { } function getUpToDateStatusWorker(state: SolutionBuilderState, project: ParsedCommandLine, resolvedPath: ResolvedConfigFilePath): UpToDateStatus { + const force = !!state.options.force; let newestInputFileName: string = undefined!; let newestInputFileTime = minimumDate; const { host } = state; @@ -1357,10 +1339,12 @@ namespace ts { }; } - const inputTime = host.getModifiedTime(inputFile) || missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; + if (!force) { + const inputTime = getModifiedTime(host, inputFile); host.getModifiedTime(inputFile); + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } } @@ -1382,39 +1366,41 @@ namespace ts { let missingOutputFileName: string | undefined; 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; - } + if (!force) { + 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; - } + const outputTime = getModifiedTime(host, output); + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } + // If 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; - } + 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)) { - const outputModifiedTime = host.getModifiedTime(output) || missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + // 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)) { + const outputModifiedTime = getModifiedTime(host, output); + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); + } } } @@ -1454,7 +1440,8 @@ namespace ts { } // Check oldest output file name only if there is no missing output file name - if (!missingOutputFileName) { + // (a check we will have skipped if this is a forced build) + if (!force && !missingOutputFileName) { // If the upstream project's newest file is older than our oldest output, we // can't be out of date because of it if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { @@ -1504,7 +1491,7 @@ namespace ts { if (extendedConfigStatus) return extendedConfigStatus; } - if (!state.buildInfoChecked.has(resolvedPath)) { + if (!force && !state.buildInfoChecked.has(resolvedPath)) { state.buildInfoChecked.set(resolvedPath, true); const buildInfoPath = getTsBuildInfoEmitOutputFilePath(project.options); if (buildInfoPath) { @@ -1571,7 +1558,7 @@ namespace ts { } if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, getModifiedTime(host, file)); } host.setModifiedTime(file, now); @@ -1663,7 +1650,7 @@ namespace ts { } } - function build(state: SolutionBuilderState, project?: string, cancellationToken?: CancellationToken, onlyReferences?: boolean): ExitStatus { + function build(state: SolutionBuilderState, project?: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers, onlyReferences?: boolean): ExitStatus { const buildOrder = getBuildOrderFor(state, project, onlyReferences); if (!buildOrder) return ExitStatus.InvalidProject_OutputsSkipped; @@ -1675,7 +1662,7 @@ namespace ts { const invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue); if (!invalidatedProject) break; reportQueue = false; - invalidatedProject.done(cancellationToken); + invalidatedProject.done(cancellationToken, writeFile, getCustomTransformers?.(invalidatedProject.project)); if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; } @@ -1712,7 +1699,11 @@ namespace ts { continue; } const outputs = getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames()); + if (!outputs.length) continue; + const inputFileNames = new Set(parsed.fileNames.map(f => toPath(state, f))); for (const output of outputs) { + // If output name is same as input file name, do not delete and ignore the error + if (inputFileNames.has(toPath(state, output))) continue; if (host.fileExists(output)) { if (filesToDelete) { filesToDelete.push(output); @@ -1804,7 +1795,7 @@ namespace ts { function watchExtendedConfigFiles(state: SolutionBuilderState, resolvedPath: ResolvedConfigFilePath, parsed: ParsedCommandLine | undefined) { updateSharedExtendedConfigFileWatcher( resolvedPath, - parsed, + parsed?.options, state.allWatchedExtendedConfigFiles, (extendedConfigFileName, extendedConfigFilePath) => state.watchFile( extendedConfigFileName, @@ -1834,9 +1825,10 @@ namespace ts { configFileName: resolved, currentDirectory: state.currentDirectory, options: parsed.options, - program: state.builderPrograms.get(resolvedPath), + program: state.builderPrograms.get(resolvedPath) || getCachedParsedConfigFile(state, resolvedPath)?.fileNames, useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames, - writeLog: s => state.writeLog(s) + writeLog: s => state.writeLog(s), + toPath: fileName => toPath(state, fileName) })) return; invalidateProjectAndScheduleBuilds(state, resolvedPath, ConfigFileProgramReloadLevel.Partial); @@ -1889,10 +1881,7 @@ namespace ts { function stopWatching(state: SolutionBuilderState) { clearMap(state.allWatchedConfigFiles, closeFileWatcher); - clearMap(state.allWatchedExtendedConfigFiles, watcher => { - watcher.projects.clear(); - watcher.close(); - }); + clearMap(state.allWatchedExtendedConfigFiles, closeFileWatcherOf); clearMap(state.allWatchedWildcardDirectories, watchedWildcardDirectories => clearMap(watchedWildcardDirectories, closeFileWatcherOf)); clearMap(state.allWatchedInputFiles, watchedWildcardDirectories => clearMap(watchedWildcardDirectories, closeFileWatcher)); } @@ -1906,9 +1895,9 @@ namespace ts { function createSolutionBuilderWorker(watch: boolean, hostOrHostWithWatch: SolutionBuilderHost | SolutionBuilderWithWatchHost, rootNames: readonly string[], options: BuildOptions, baseWatchOptions?: WatchOptions): SolutionBuilder { const state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions); return { - build: (project, cancellationToken) => build(state, project, cancellationToken), + build: (project, cancellationToken, writeFile, getCustomTransformers) => build(state, project, cancellationToken, writeFile, getCustomTransformers), clean: project => clean(state, project), - buildReferences: (project, cancellationToken) => build(state, project, cancellationToken, /*onlyReferences*/ true), + buildReferences: (project, cancellationToken, writeFile, getCustomTransformers) => build(state, project, cancellationToken, writeFile, getCustomTransformers, /*onlyReferences*/ true), cleanReferences: project => clean(state, project, /*onlyReferences*/ true), getNextInvalidatedProject: cancellationToken => { setupInitialBuild(state, cancellationToken); @@ -1998,6 +1987,14 @@ namespace ts { } function reportUpToDateStatus(state: SolutionBuilderState, configFileName: string, status: UpToDateStatus) { + if (state.options.force && (status.type === UpToDateStatusType.UpToDate || status.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) { + return reportStatus( + state, + Diagnostics.Project_0_is_being_forcibly_rebuilt, + relName(state, configFileName) + ); + } + switch (status.type) { case UpToDateStatusType.OutOfDateWithSelf: return reportStatus( diff --git a/src/compiler/tsconfig.json b/src/compiler/tsconfig.json index ed64c2c26d593..5f118cf1e47bd 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -53,6 +53,7 @@ "transformers/es2018.ts", "transformers/es2019.ts", "transformers/es2020.ts", + "transformers/es2021.ts", "transformers/esnext.ts", "transformers/jsx.ts", "transformers/es2016.ts", diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 3585ff50a8f3b..e352625ab043f 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -187,6 +187,7 @@ namespace ts { FromKeyword, GlobalKeyword, BigIntKeyword, + OverrideKeyword, OfKeyword, // LastKeyword and LastToken and LastContextualKeyword // Parse tree nodes @@ -361,20 +362,19 @@ namespace ts { // JSDoc nodes JSDocTypeExpression, JSDocNameReference, - // The * type - JSDocAllType, - // The ? type - JSDocUnknownType, + JSDocAllType, // The * type + JSDocUnknownType, // The ? type JSDocNullableType, JSDocNonNullableType, JSDocOptionalType, JSDocFunctionType, JSDocVariadicType, - // https://jsdoc.app/about-namepaths.html - JSDocNamepathType, + JSDocNamepathType, // https://jsdoc.app/about-namepaths.html JSDocComment, + JSDocText, JSDocTypeLiteral, JSDocSignature, + JSDocLink, JSDocTag, JSDocAugmentsTag, JSDocImplementsTag, @@ -385,6 +385,7 @@ namespace ts { JSDocPrivateTag, JSDocProtectedTag, JSDocReadonlyTag, + JSDocOverrideTag, JSDocCallbackTag, JSDocEnumTag, JSDocParameterTag, @@ -587,6 +588,7 @@ namespace ts { | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword + | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword @@ -622,6 +624,7 @@ namespace ts { | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword + | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword ; @@ -798,16 +801,17 @@ namespace ts { HasComputedJSDocModifiers = 1 << 12, // Indicates the computed modifier flags include modifiers from JSDoc. Deprecated = 1 << 13, // Deprecated tag. + Override = 1 << 14, // Override method. HasComputedFlags = 1 << 29, // Modifier flags have been computed AccessibilityModifier = Public | Private | Protected, // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. - ParameterPropertyModifier = AccessibilityModifier | Readonly, + ParameterPropertyModifier = AccessibilityModifier | Readonly | Override, NonPublicAccessibilityModifier = Private | Protected, - TypeScriptModifier = Ambient | Public | Private | Protected | Readonly | Abstract | Const, + TypeScriptModifier = Ambient | Public | Private | Protected | Readonly | Abstract | Const | Override, ExportDefault = Export | Default, - All = Export | Ambient | Public | Private | Protected | Static | Readonly | Abstract | Async | Default | Const | Deprecated + All = Export | Ambient | Public | Private | Protected | Static | Readonly | Abstract | Async | Default | Const | Deprecated | Override } export const enum JsxFlags { @@ -871,12 +875,29 @@ namespace ts { | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression - | LabeledStatement - | ExpressionStatement + | EmptyStatement + | DebuggerStatement + | Block | VariableStatement + | ExpressionStatement + | IfStatement + | DoStatement + | WhileStatement + | ForStatement + | ForInStatement + | ForOfStatement + | BreakStatement + | ContinueStatement + | ReturnStatement + | WithStatement + | SwitchStatement + | LabeledStatement + | ThrowStatement + | TryStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration + | VariableDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration @@ -1027,6 +1048,7 @@ namespace ts { export type ProtectedKeyword = ModifierToken; export type PublicKeyword = ModifierToken; export type ReadonlyKeyword = ModifierToken; + export type OverrideKeyword = ModifierToken; export type StaticKeyword = ModifierToken; /** @deprecated Use `ReadonlyKeyword` instead. */ @@ -1042,6 +1064,7 @@ namespace ts { | PrivateKeyword | ProtectedKeyword | PublicKeyword + | OverrideKeyword | ReadonlyKeyword | StaticKeyword ; @@ -1118,6 +1141,8 @@ namespace ts { export type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | PrivateIdentifier; + export type MemberName = Identifier | PrivateIdentifier; + export type DeclarationName = | Identifier | PrivateIdentifier @@ -1238,7 +1263,7 @@ namespace ts { export type BindingName = Identifier | BindingPattern; - export interface VariableDeclaration extends NamedDeclaration { + export interface VariableDeclaration extends NamedDeclaration, JSDocContainer { readonly kind: SyntaxKind.VariableDeclaration; readonly parent: VariableDeclarationList | CatchClause; readonly name: BindingName; // Declared variable name @@ -1300,6 +1325,26 @@ namespace ts { export interface PrivateIdentifierPropertyDeclaration extends PropertyDeclaration { name: PrivateIdentifier; } + /*@internal*/ + export interface PrivateIdentifierMethodDeclaration extends MethodDeclaration { + name: PrivateIdentifier; + } + /*@internal*/ + export interface PrivateIdentifierGetAccessorDeclaration extends GetAccessorDeclaration { + name: PrivateIdentifier; + } + /*@internal*/ + export interface PrivateIdentifierSetAccessorDeclaration extends SetAccessorDeclaration { + name: PrivateIdentifier; + } + /*@internal*/ + export type PrivateIdentifierAccessorDeclaration = PrivateIdentifierGetAccessorDeclaration | PrivateIdentifierSetAccessorDeclaration; + /*@internal*/ + export type PrivateClassElementDeclaration = + | PrivateIdentifierPropertyDeclaration + | PrivateIdentifierMethodDeclaration + | PrivateIdentifierGetAccessorDeclaration + | PrivateIdentifierSetAccessorDeclaration; /* @internal */ export type InitializedPropertyDeclaration = PropertyDeclaration & { readonly initializer: Expression }; @@ -1453,9 +1498,9 @@ namespace ts { // See the comment on MethodDeclaration for the intuition behind GetAccessorDeclaration being a // ClassElement and an ObjectLiteralElement. - export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.GetAccessor; - readonly parent: ClassLikeDeclaration | ObjectLiteralExpression; + readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; readonly name: PropertyName; readonly body?: FunctionBody; /* @internal */ typeParameters?: NodeArray; // Present for use with reporting a grammar error @@ -1463,9 +1508,9 @@ namespace ts { // See the comment on MethodDeclaration for the intuition behind SetAccessorDeclaration being a // ClassElement and an ObjectLiteralElement. - export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.SetAccessor; - readonly parent: ClassLikeDeclaration | ObjectLiteralExpression; + readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; readonly name: PropertyName; readonly body?: FunctionBody; /* @internal */ typeParameters?: NodeArray; // Present for use with reporting a grammar error @@ -2224,7 +2269,7 @@ namespace ts { readonly kind: SyntaxKind.PropertyAccessExpression; readonly expression: LeftHandSideExpression; readonly questionDotToken?: QuestionDotToken; - readonly name: Identifier | PrivateIdentifier; + readonly name: MemberName; } /*@internal*/ @@ -2234,7 +2279,7 @@ namespace ts { export interface PropertyAccessChain extends PropertyAccessExpression { _optionalChainBrand: any; - readonly name: Identifier | PrivateIdentifier; + readonly name: MemberName; } /* @internal */ @@ -2307,12 +2352,6 @@ namespace ts { | CallChainRoot ; - /** @internal */ - export interface WellKnownSymbolExpression extends PropertyAccessExpression { - readonly expression: Identifier & { readonly escapedText: __String & "Symbol" }; - readonly name: Identifier; - } - /** @internal */ export type BindableObjectDefinePropertyCall = CallExpression & { readonly arguments: readonly [BindableStaticNameExpression, StringLiteralLike | NumericLiteral, ObjectLiteralExpression] & Readonly; @@ -2326,7 +2365,7 @@ namespace ts { /** @internal */ export type LiteralLikeElementAccessExpression = ElementAccessExpression & Declaration & { - readonly argumentExpression: StringLiteralLike | NumericLiteral | WellKnownSymbolExpression; + readonly argumentExpression: StringLiteralLike | NumericLiteral; }; /** @internal */ @@ -2551,7 +2590,7 @@ namespace ts { | JsxFragment ; - export interface Statement extends Node { + export interface Statement extends Node, JSDocContainer { _statementBrand: any; } @@ -2620,13 +2659,13 @@ namespace ts { /*@internal*/ multiLine?: boolean; } - export interface VariableStatement extends Statement, JSDocContainer { + export interface VariableStatement extends Statement { /* @internal*/ decorators?: NodeArray; // Present for use with reporting a grammar error readonly kind: SyntaxKind.VariableStatement; readonly declarationList: VariableDeclarationList; } - export interface ExpressionStatement extends Statement, JSDocContainer { + export interface ExpressionStatement extends Statement { readonly kind: SyntaxKind.ExpressionStatement; readonly expression: Expression; } @@ -2746,7 +2785,7 @@ namespace ts { | DefaultClause ; - export interface LabeledStatement extends Statement, JSDocContainer { + export interface LabeledStatement extends Statement { readonly kind: SyntaxKind.LabeledStatement; readonly label: Identifier; readonly statement: Statement; @@ -2942,7 +2981,7 @@ namespace ts { // import "mod" => importClause = undefined, moduleSpecifier = "mod" // In rest of the cases, module specifier is string literal corresponding to module // ImportClause information is shown at its declaration below. - export interface ImportDeclaration extends Statement, JSDocContainer { + export interface ImportDeclaration extends Statement { readonly kind: SyntaxKind.ImportDeclaration; readonly parent: SourceFile | ModuleBlock; readonly importClause?: ImportClause; @@ -3139,13 +3178,24 @@ namespace ts { readonly kind: SyntaxKind.JSDocComment; readonly parent: HasJSDoc; readonly tags?: NodeArray; - readonly comment?: string; + readonly comment?: string | NodeArray; } export interface JSDocTag extends Node { readonly parent: JSDoc | JSDocTypeLiteral; readonly tagName: Identifier; - readonly comment?: string; + readonly comment?: string | NodeArray; + } + + export interface JSDocLink extends Node { + readonly kind: SyntaxKind.JSDocLink; + readonly name?: EntityName; + text: string; + } + + export interface JSDocText extends Node { + readonly kind: SyntaxKind.JSDocText; + text: string; } export interface JSDocUnknownTag extends JSDocTag { @@ -3194,6 +3244,10 @@ namespace ts { readonly kind: SyntaxKind.JSDocReadonlyTag; } + export interface JSDocOverrideTag extends JSDocTag { + readonly kind: SyntaxKind.JSDocOverrideTag; + } + export interface JSDocEnumTag extends JSDocTag, Declaration { readonly kind: SyntaxKind.JSDocEnumTag; readonly parent: JSDoc; @@ -3507,6 +3561,7 @@ namespace ts { /* @internal */ localJsxFragmentFactory?: EntityName; /* @internal */ exportedModulesFromDeclarationEmit?: ExportedModulesFromDeclarationEmit; + /* @internal */ endFlowNode?: FlowNode; } /* @internal */ @@ -3841,8 +3896,6 @@ namespace ts { /* @internal */ getClassifiableNames(): Set<__String>; - getTypeCatalog(): readonly Type[]; - getNodeCount(): number; getIdentifierCount(): number; getSymbolCount(): number; @@ -3903,9 +3956,9 @@ namespace ts { /* @internal */ export const enum StructureIsReused { - Not = 0, - SafeModules = 1 << 0, - Completely = 1 << 1, + Not, + SafeModules, + Completely, } export type CustomTransformerFactory = (context: TransformationContext) => CustomTransformer; @@ -4053,7 +4106,7 @@ namespace ts { * The function returns the value (local variable) symbol of an identifier in the short-hand property assignment. * This is necessary as an identifier in short-hand property assignment can contains two meaning: property name and property value. */ - getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getShorthandAssignmentValueSymbol(location: Node | undefined): Symbol | undefined; getExportSpecifierLocalTargetSymbol(location: ExportSpecifier | Identifier): Symbol | undefined; /** @@ -4091,6 +4144,7 @@ namespace ts { /* @internal */ getContextualTypeForArgumentAtIndex(call: CallLikeExpression, argIndex: number): Type | undefined; /* @internal */ getContextualTypeForJsxAttribute(attribute: JsxAttribute | JsxSpreadAttribute): Type | undefined; /* @internal */ isContextSensitive(node: Expression | MethodDeclaration | ObjectLiteralElementLike | JsxAttributeLike): boolean; + /* @internal */ getTypeOfPropertyOfContextualType(type: Type, name: __String): Type | undefined; /** * returns unknownSignature in the case of an error. @@ -4130,9 +4184,9 @@ namespace ts { */ /* @internal */ tryGetMemberInModuleExportsAndProperties(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; - /* @internal */ getSuggestedSymbolForNonexistentProperty(name: Identifier | PrivateIdentifier | string, containingType: Type): Symbol | undefined; + /* @internal */ getSuggestedSymbolForNonexistentProperty(name: MemberName | string, containingType: Type): Symbol | undefined; /* @internal */ getSuggestedSymbolForNonexistentJSXAttribute(name: Identifier | string, containingType: Type): Symbol | undefined; - /* @internal */ getSuggestionForNonexistentProperty(name: Identifier | PrivateIdentifier | string, containingType: Type): string | undefined; + /* @internal */ getSuggestionForNonexistentProperty(name: MemberName | string, containingType: Type): string | undefined; /* @internal */ getSuggestedSymbolForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): Symbol | undefined; /* @internal */ getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; /* @internal */ getSuggestedSymbolForNonexistentModule(node: Identifier, target: Symbol): Symbol | undefined; @@ -4172,6 +4226,7 @@ namespace ts { /* @internal */ createSymbol(flags: SymbolFlags, name: __String): TransientSymbol; /* @internal */ createIndexInfo(type: Type, isReadonly: boolean, declaration?: SignatureDeclaration): IndexInfo; /* @internal */ isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node | undefined, meaning: SymbolFlags, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult; + /* @internal */ tryFindAmbientModule(moduleName: string): Symbol | undefined; /* @internal */ tryFindAmbientModuleWithoutAugmentations(moduleName: string): Symbol | undefined; /* @internal */ getSymbolWalker(accept?: (symbol: Symbol) => boolean): SymbolWalker; @@ -4181,8 +4236,6 @@ namespace ts { /* @internal */ getGlobalDiagnostics(): Diagnostic[]; /* @internal */ getEmitResolver(sourceFile?: SourceFile, cancellationToken?: CancellationToken): EmitResolver; - /* @internal */ getTypeCatalog(): readonly Type[]; - /* @internal */ getNodeCount(): number; /* @internal */ getIdentifierCount(): number; /* @internal */ getSymbolCount(): number; @@ -4289,7 +4342,9 @@ namespace ts { // Error handling AllowThisInObjectLiteral = 1 << 15, - AllowQualifedNameInPlaceOfIdentifier = 1 << 16, + AllowQualifiedNameInPlaceOfIdentifier = 1 << 16, + /** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */ + AllowQualifedNameInPlaceOfIdentifier = AllowQualifiedNameInPlaceOfIdentifier, AllowAnonymousIdentifier = 1 << 17, AllowEmptyUnionOrIntersection = 1 << 18, AllowEmptyTuple = 1 << 19, @@ -4300,13 +4355,12 @@ namespace ts { AllowNodeModulesRelativePaths = 1 << 26, /* @internal */ DoNotIncludeSymbolChain = 1 << 27, // Skip looking up and printing an accessible symbol chain - IgnoreErrors = AllowThisInObjectLiteral | AllowQualifedNameInPlaceOfIdentifier | AllowAnonymousIdentifier | AllowEmptyUnionOrIntersection | AllowEmptyTuple | AllowEmptyIndexInfoType | AllowNodeModulesRelativePaths, + IgnoreErrors = AllowThisInObjectLiteral | AllowQualifiedNameInPlaceOfIdentifier | AllowAnonymousIdentifier | AllowEmptyUnionOrIntersection | AllowEmptyTuple | AllowEmptyIndexInfoType | AllowNodeModulesRelativePaths, // State InObjectTypeLiteral = 1 << 22, 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, } // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment @@ -4718,8 +4772,8 @@ namespace ts { export interface Symbol { flags: SymbolFlags; // Symbol flags escapedName: __String; // Name of symbol - declarations: Declaration[]; // Declarations associated with this symbol - valueDeclaration: Declaration; // First value declaration of the symbol + declarations?: Declaration[]; // Declarations associated with this symbol + valueDeclaration?: Declaration; // First value declaration of the symbol members?: SymbolTable; // Class, interface or object literal instance members exports?: SymbolTable; // Module exports globalExports?: SymbolTable; // Conditional global UMD exports @@ -4739,6 +4793,7 @@ namespace ts { immediateTarget?: Symbol; // Immediate target of an alias. May be another alias. Do not access directly, use `checker.getImmediateAliasedSymbol` instead. target?: Symbol; // Resolved (non-alias) target of an alias type?: Type; // Type of value symbol + writeType?: Type; // Type of value symbol in write contexts nameType?: Type; // Type associated with a late-bound symbol uniqueESSymbolType?: Type; // UniqueESSymbol type for a symbol declaredType?: Type; // Type of class, interface, enum, type alias, or type parameter @@ -5098,6 +5153,9 @@ namespace ts { export interface EnumType extends Type { } + // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags + // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check + // for a certain TypeFlags value to determine their meaning. export const enum ObjectFlags { Class = 1 << 0, // Class Interface = 1 << 1, // Interface @@ -5109,51 +5167,64 @@ namespace ts { ObjectLiteral = 1 << 7, // Originates in an object literal EvolvingArray = 1 << 8, // Evolving array type ObjectLiteralPatternWithComputedProperties = 1 << 9, // Object literal pattern with computed properties - ContainsSpread = 1 << 10, // Object literal contains spread operation - ReverseMapped = 1 << 11, // Object contains a property from a reverse-mapped type - JsxAttributes = 1 << 12, // Jsx attributes type - MarkerType = 1 << 13, // Marker type used for variance probing - JSLiteral = 1 << 14, // Object type declared in JS - disables errors on read/write of nonexisting members - FreshLiteral = 1 << 15, // Fresh object literal - ArrayLiteral = 1 << 16, // Originates in an array literal - ObjectRestType = 1 << 17, // Originates in object rest declaration + ReverseMapped = 1 << 10, // Object contains a property from a reverse-mapped type + JsxAttributes = 1 << 11, // Jsx attributes type + MarkerType = 1 << 12, // Marker type used for variance probing + JSLiteral = 1 << 13, // Object type declared in JS - disables errors on read/write of nonexisting members + FreshLiteral = 1 << 14, // Fresh object literal + ArrayLiteral = 1 << 15, // Originates in an array literal /* @internal */ - PrimitiveUnion = 1 << 18, // Union of only primitive types + PrimitiveUnion = 1 << 16, // Union of only primitive types /* @internal */ - ContainsWideningType = 1 << 19, // Type is or contains undefined or null widening type + ContainsWideningType = 1 << 17, // Type is or contains undefined or null widening type /* @internal */ - ContainsObjectOrArrayLiteral = 1 << 20, // Type is or contains object literal type + ContainsObjectOrArrayLiteral = 1 << 18, // Type is or contains object literal type /* @internal */ - NonInferrableType = 1 << 21, // Type is or contains anyFunctionType or silentNeverType + NonInferrableType = 1 << 19, // Type is or contains anyFunctionType or silentNeverType /* @internal */ - IsGenericObjectTypeComputed = 1 << 22, // IsGenericObjectType flag has been computed + CouldContainTypeVariablesComputed = 1 << 20, // CouldContainTypeVariables flag has been computed /* @internal */ - IsGenericObjectType = 1 << 23, // Union or intersection contains generic object type + CouldContainTypeVariables = 1 << 21, // Type could contain a type variable + + ClassOrInterface = Class | Interface, /* @internal */ - IsGenericIndexTypeComputed = 1 << 24, // IsGenericIndexType flag has been computed + RequiresWidening = ContainsWideningType | ContainsObjectOrArrayLiteral, /* @internal */ - IsGenericIndexType = 1 << 25, // Union or intersection contains generic index type + PropagatingFlags = ContainsWideningType | ContainsObjectOrArrayLiteral | NonInferrableType, + // Object flags that uniquely identify the kind of ObjectType + /* @internal */ + ObjectTypeKindMask = ClassOrInterface | Reference | Tuple | Anonymous | Mapped | ReverseMapped | EvolvingArray, + + // Flags that require TypeFlags.Object + ContainsSpread = 1 << 22, // Object literal contains spread operation + ObjectRestType = 1 << 23, // Originates in object rest declaration /* @internal */ - CouldContainTypeVariablesComputed = 1 << 26, // CouldContainTypeVariables flag has been computed + IsClassInstanceClone = 1 << 24, // Type is a clone of a class instance type + // Flags that require TypeFlags.Object and ObjectFlags.Reference /* @internal */ - CouldContainTypeVariables = 1 << 27, // Type could contain a type variable + IdenticalBaseTypeCalculated = 1 << 25, // has had `getSingleBaseForNonAugmentingSubtype` invoked on it already /* @internal */ - ContainsIntersections = 1 << 28, // Union contains intersections + IdenticalBaseTypeExists = 1 << 26, // has a defined cachedEquivalentBaseType member + + // Flags that require TypeFlags.UnionOrIntersection or TypeFlags.Substitution /* @internal */ - IsNeverIntersectionComputed = 1 << 28, // IsNeverLike flag has been computed + IsGenericObjectTypeComputed = 1 << 22, // IsGenericObjectType flag has been computed /* @internal */ - IsNeverIntersection = 1 << 29, // Intersection reduces to never + IsGenericObjectType = 1 << 23, // Union or intersection contains generic object type /* @internal */ - IsClassInstanceClone = 1 << 30, // Type is a clone of a class instance type - ClassOrInterface = Class | Interface, + IsGenericIndexTypeComputed = 1 << 24, // IsGenericIndexType flag has been computed /* @internal */ - RequiresWidening = ContainsWideningType | ContainsObjectOrArrayLiteral, + IsGenericIndexType = 1 << 25, // Union or intersection contains generic index type + + // Flags that require TypeFlags.Union /* @internal */ - PropagatingFlags = ContainsWideningType | ContainsObjectOrArrayLiteral | NonInferrableType, + ContainsIntersections = 1 << 26, // Union contains intersections - // Object flags that uniquely identify the kind of ObjectType + // Flags that require TypeFlags.Intersection /* @internal */ - ObjectTypeKindMask = ClassOrInterface | Reference | Tuple | Anonymous | Mapped | ReverseMapped | EvolvingArray, + IsNeverIntersectionComputed = 1 << 26, // IsNeverLike flag has been computed + /* @internal */ + IsNeverIntersection = 1 << 27, // Intersection reduces to never } /* @internal */ @@ -5215,6 +5286,8 @@ namespace ts { resolvedTypeArguments?: readonly Type[]; // Resolved type reference type arguments /* @internal */ literalType?: TypeReference; // Clone of type with ObjectFlags.ArrayLiteral set + /* @internal */ + cachedEquivalentBaseType?: Type; // Only set on references to class or interfaces with a single base type and no augmentations } export interface DeferredTypeReference extends TypeReference { @@ -5297,6 +5370,10 @@ namespace ts { regularType?: UnionType; /* @internal */ origin?: Type; // Denormalized union, intersection, or index type in which union originates + /* @internal */ + keyPropertyName?: __String; // Property with unique unit type that exists in every object/intersection in union type + /* @internal */ + constituentMap?: ESMap; // Constituents keyed by unit type discriminants } export interface IntersectionType extends UnionOrIntersectionType { @@ -5483,6 +5560,7 @@ namespace ts { // Thus, if Foo has a 'string' constraint on its type parameter, T will satisfy it. Substitution // types disappear upon instantiation (just like type parameters). export interface SubstitutionType extends InstantiableType { + objectFlags: ObjectFlags; baseType: Type; // Target type substitute: Type; // Type to substitute for type parameter } @@ -5546,12 +5624,16 @@ namespace ts { /* @internal */ mapper?: TypeMapper; // Instantiation mapper /* @internal */ - unionSignatures?: Signature[]; // Underlying signatures of a union signature + compositeSignatures?: Signature[]; // Underlying signatures of a union/intersection signature + /* @internal */ + compositeKind?: TypeFlags; // TypeFlags.Union if the underlying signatures are from union members, otherwise TypeFlags.Intersection /* @internal */ erasedSignatureCache?: Signature; // Erased version of signature (deferred) /* @internal */ canonicalSignatureCache?: Signature; // Canonical version of signature (deferred) /* @internal */ + baseSignatureCache?: Signature; // Base version of signature (deferred) + /* @internal */ optionalCallSignatureCache?: { inner?: Signature, outer?: Signature }; // Optional chained call version of signature (deferred) /* @internal */ isolatedSignatureType?: ObjectType; // A manufactured type that just contains the signature for purposes of signature comparison @@ -5589,15 +5671,16 @@ namespace ts { export const enum InferencePriority { NakedTypeVariable = 1 << 0, // Naked type variable in union or intersection type SpeculativeTuple = 1 << 1, // Speculative tuple inference - HomomorphicMappedType = 1 << 2, // Reverse inference for homomorphic mapped type - PartialHomomorphicMappedType = 1 << 3, // Partial reverse inference for homomorphic mapped type - MappedTypeConstraint = 1 << 4, // Reverse inference for mapped type - ContravariantConditional = 1 << 5, // Conditional type in contravariant position - ReturnType = 1 << 6, // Inference made from return type of generic function - LiteralKeyof = 1 << 7, // Inference made from a string literal to a keyof T - NoConstraints = 1 << 8, // Don't infer from constraints of instantiable types - AlwaysStrict = 1 << 9, // Always use strict rules for contravariant inferences - MaxValue = 1 << 10, // Seed for inference priority tracking + SubstituteSource = 1 << 2, // Source of inference originated within a substitution type's substitute + HomomorphicMappedType = 1 << 3, // Reverse inference for homomorphic mapped type + PartialHomomorphicMappedType = 1 << 4, // Partial reverse inference for homomorphic mapped type + MappedTypeConstraint = 1 << 5, // Reverse inference for mapped type + ContravariantConditional = 1 << 6, // Conditional type in contravariant position + ReturnType = 1 << 7, // Inference made from return type of generic function + LiteralKeyof = 1 << 8, // Inference made from a string literal to a keyof T + NoConstraints = 1 << 9, // Don't infer from constraints of instantiable types + AlwaysStrict = 1 << 10, // Always use strict rules for contravariant inferences + MaxValue = 1 << 11, // Seed for inference priority tracking PriorityImpliesCombination = ReturnType | MappedTypeConstraint | LiteralKeyof, // These priorities imply that the resulting type should be a combination of all candidates Circularity = -1, // Inference circularity (value less than all other priorities) @@ -5791,6 +5874,7 @@ namespace ts { FixedPollingInterval, PriorityPollingInterval, DynamicPriorityPolling, + FixedChunkSizePolling, UseFsEvents, UseFsEventsOnParentDirectory, } @@ -5799,12 +5883,14 @@ namespace ts { UseFsEvents, FixedPollingInterval, DynamicPriorityPolling, + FixedChunkSizePolling, } export enum PollingWatchKind { FixedInterval, PriorityInterval, DynamicPriority, + FixedChunkSize, } export type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; @@ -5890,6 +5976,7 @@ namespace ts { /*@internal*/ pathsBasePath?: string; /*@internal*/ plugins?: PluginImport[]; preserveConstEnums?: boolean; + noImplicitOverride?: boolean; preserveSymlinks?: boolean; /* @internal */ preserveWatchOutput?: boolean; project?: string; @@ -6024,6 +6111,7 @@ namespace ts { ES2018 = 5, ES2019 = 6, ES2020 = 7, + ES2021 = 8, ESNext = 99, JSON = 100, Latest = ESNext, @@ -6114,8 +6202,15 @@ namespace ts { type: ESMap; // an object literal mapping named values to actual values } + /* @internal */ + export interface AlternateModeDiagnostics { + diagnostic: DiagnosticMessage; + getOptionsNameMap: () => OptionsNameMap; + } + /* @internal */ export interface DidYouMeanOptionsDiagnostics { + alternateMode?: AlternateModeDiagnostics; optionDeclarations: CommandLineOption[]; unknownOptionDiagnostic: DiagnosticMessage, unknownDidYouMeanDiagnostic: DiagnosticMessage, @@ -6312,7 +6407,10 @@ namespace ts { * If changing this, remember to change `moduleResolutionIsEqualTo`. */ export interface ResolvedModuleFull extends ResolvedModule { - /* @internal */ + /** + * @internal + * This is a file name with preserved original casing, not a normalized `Path`. + */ readonly originalPath?: string; /** * Extension of resolvedFileName. This must match what's at the end of resolvedFileName. @@ -6363,6 +6461,12 @@ namespace ts { primary: boolean; // The location of the .d.ts file we located, or undefined if resolution failed resolvedFileName: string | undefined; + /** + * @internal + * The location of the symlink to the .d.ts file we found, if `resolvedFileName` was the realpath. + * This is a file name with preserved original casing, not a normalized `Path`. + */ + originalPath?: string; packageId?: PackageId; /** True if `resolvedFileName` comes from `node_modules`. */ isExternalLibraryImport?: boolean; @@ -6405,6 +6509,7 @@ namespace ts { resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions): (ResolvedTypeReferenceDirective | undefined)[]; getEnvironmentVariable?(name: string): string | undefined; /* @internal */ onReleaseOldSourceFile?(oldSourceFile: SourceFile, oldOptions: CompilerOptions, hasSourceFileByPath: boolean): void; + /* @internal */ onReleaseParsedCommandLine?(configFileName: string, oldResolvedRef: ResolvedProjectReference | undefined, optionOptions: CompilerOptions): void; /* @internal */ hasInvalidatedResolution?: HasInvalidatedResolution; /* @internal */ hasChangedAutomaticTypeDirectiveNames?: HasChangedAutomaticTypeDirectiveNames; createHash?(data: string): string; @@ -6414,6 +6519,9 @@ namespace ts { // TODO: later handle this in better way in builder host instead once the api for tsbuild finalizes and doesn't use compilerHost as base /*@internal*/createDirectory?(directory: string): void; /*@internal*/getSymlinkCache?(): SymlinkCache; + + // For testing: + /*@internal*/ disableUseFileVersionAsSignature?: boolean; } /** true if --out otherwise source file name */ @@ -6435,30 +6543,31 @@ namespace ts { ContainsTypeScript = 1 << 0, ContainsJsx = 1 << 1, ContainsESNext = 1 << 2, - ContainsES2020 = 1 << 3, - ContainsES2019 = 1 << 4, - ContainsES2018 = 1 << 5, - ContainsES2017 = 1 << 6, - ContainsES2016 = 1 << 7, - ContainsES2015 = 1 << 8, - ContainsGenerator = 1 << 9, - ContainsDestructuringAssignment = 1 << 10, + ContainsES2021 = 1 << 3, + ContainsES2020 = 1 << 4, + ContainsES2019 = 1 << 5, + ContainsES2018 = 1 << 6, + ContainsES2017 = 1 << 7, + ContainsES2016 = 1 << 8, + ContainsES2015 = 1 << 9, + ContainsGenerator = 1 << 10, + ContainsDestructuringAssignment = 1 << 11, // Markers // - Flags used to indicate that a subtree contains a specific transformation. - ContainsTypeScriptClassSyntax = 1 << 11, // Decorators, Property Initializers, Parameter Property Initializers - ContainsLexicalThis = 1 << 12, - ContainsRestOrSpread = 1 << 13, - ContainsObjectRestOrSpread = 1 << 14, - ContainsComputedPropertyName = 1 << 15, - ContainsBlockScopedBinding = 1 << 16, - ContainsBindingPattern = 1 << 17, - ContainsYield = 1 << 18, - ContainsAwait = 1 << 19, - ContainsHoistedDeclarationOrCompletion = 1 << 20, - ContainsDynamicImport = 1 << 21, - ContainsClassFields = 1 << 22, - ContainsPossibleTopLevelAwait = 1 << 23, + ContainsTypeScriptClassSyntax = 1 << 12, // Decorators, Property Initializers, Parameter Property Initializers + ContainsLexicalThis = 1 << 13, + ContainsRestOrSpread = 1 << 14, + ContainsObjectRestOrSpread = 1 << 15, + ContainsComputedPropertyName = 1 << 16, + ContainsBlockScopedBinding = 1 << 17, + ContainsBindingPattern = 1 << 18, + ContainsYield = 1 << 19, + ContainsAwait = 1 << 20, + ContainsHoistedDeclarationOrCompletion = 1 << 21, + ContainsDynamicImport = 1 << 22, + ContainsClassFields = 1 << 23, + ContainsPossibleTopLevelAwait = 1 << 24, // 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. @@ -6470,6 +6579,7 @@ namespace ts { AssertTypeScript = ContainsTypeScript, AssertJsx = ContainsJsx, AssertESNext = ContainsESNext, + AssertES2021 = ContainsES2021, AssertES2020 = ContainsES2020, AssertES2019 = ContainsES2019, AssertES2018 = ContainsES2018, @@ -6570,7 +6680,7 @@ namespace ts { /*@internal*/ IgnoreSourceNewlines = 1 << 27, // Overrides `printerOptions.preserveSourceNewlines` to print this node (and all descendants) with default whitespace. } - export interface EmitHelper { + export interface EmitHelperBase { readonly name: string; // A unique name for this helper. readonly scoped: boolean; // Indicates whether the helper MUST be emitted in the current scope. readonly text: string | ((node: EmitHelperUniqueNameCallback) => string); // ES3-compatible raw script text, or a function yielding such a string @@ -6578,13 +6688,19 @@ namespace ts { readonly dependencies?: EmitHelper[] } - export interface UnscopedEmitHelper extends EmitHelper { + export interface ScopedEmitHelper extends EmitHelperBase { + readonly scoped: true; + } + + export interface UnscopedEmitHelper extends EmitHelperBase { readonly scoped: false; // Indicates whether the helper MUST be emitted in the current scope. /* @internal */ readonly importName?: string; // The name of the helper to use when importing via `--importHelpers`. readonly text: string; // ES3-compatible raw script text, or a function yielding such a string } + export type EmitHelper = ScopedEmitHelper | UnscopedEmitHelper; + /* @internal */ export type UniqueNameHandler = (baseName: string, checkFn?: (name: string) => boolean, optimistic?: boolean) => string; @@ -6715,6 +6831,8 @@ namespace ts { /* @internal */ export interface ParenthesizerRules { + getParenthesizeLeftSideOfBinaryForOperator(binaryOperator: SyntaxKind): (leftSide: Expression) => Expression; + getParenthesizeRightSideOfBinaryForOperator(binaryOperator: SyntaxKind): (rightSide: Expression) => Expression; parenthesizeLeftSideOfBinary(binaryOperator: SyntaxKind, leftSide: Expression): Expression; parenthesizeRightSideOfBinary(binaryOperator: SyntaxKind, leftSide: Expression | undefined, rightSide: Expression): Expression; parenthesizeExpressionOfComputedPropertyName(expression: Expression): Expression; @@ -6728,6 +6846,7 @@ namespace ts { parenthesizeExpressionsOfCommaDelimitedList(elements: readonly Expression[]): NodeArray; parenthesizeExpressionForDisallowedComma(expression: Expression): Expression; parenthesizeExpressionOfExpressionStatement(expression: Expression): Expression; + parenthesizeConciseBodyOfArrowFunction(body: Expression): Expression; parenthesizeConciseBodyOfArrowFunction(body: ConciseBody): ConciseBody; parenthesizeMemberOfConditionalType(member: TypeNode): TypeNode; parenthesizeMemberOfElementType(member: TypeNode): TypeNode; @@ -6772,19 +6891,30 @@ namespace ts { /* @internal */ createIdentifier(text: string, typeArguments?: readonly (TypeNode | TypeParameterDeclaration)[], originalKeywordKind?: SyntaxKind): Identifier; // eslint-disable-line @typescript-eslint/unified-signatures /* @internal */ updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; - /** Create a unique temporary variable. */ - createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; - /* @internal */ createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, reservedInNestedScopes?: boolean): Identifier; // eslint-disable-line @typescript-eslint/unified-signatures + /** + * Create a unique temporary variable. + * @param recordTempVariable An optional callback used to record the temporary variable name. This + * should usually be a reference to `hoistVariableDeclaration` from a `TransformationContext`, but + * can be `undefined` if you plan to record the temporary variable manually. + * @param reservedInNestedScopes When `true`, reserves the temporary variable name in all nested scopes + * during emit so that the variable can be referenced in a nested function body. This is an alternative to + * setting `EmitFlags.ReuseTempVariableScope` on the nested function itself. + */ + createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, reservedInNestedScopes?: boolean): Identifier; - /** Create a unique temporary variable for use in a loop. */ - createLoopVariable(): Identifier; + /** + * Create a unique temporary variable for use in a loop. + * @param reservedInNestedScopes When `true`, reserves the temporary variable name in all nested scopes + * during emit so that the variable can be referenced in a nested function body. This is an alternative to + * setting `EmitFlags.ReuseTempVariableScope` on the nested function itself. + */ + createLoopVariable(reservedInNestedScopes?: boolean): Identifier; /** Create a unique name based on the supplied text. */ createUniqueName(text: string, flags?: GeneratedIdentifierFlags): Identifier; /** Create a unique name generated for a node. */ - getGeneratedNameForNode(node: Node | undefined): Identifier; - /* @internal */ getGeneratedNameForNode(node: Node | undefined, flags?: GeneratedIdentifierFlags): Identifier; // eslint-disable-line @typescript-eslint/unified-signatures + getGeneratedNameForNode(node: Node | undefined, flags?: GeneratedIdentifierFlags): Identifier; createPrivateIdentifier(text: string): PrivateIdentifier @@ -6943,10 +7073,10 @@ namespace ts { updateArrayLiteralExpression(node: ArrayLiteralExpression, elements: readonly Expression[]): ArrayLiteralExpression; createObjectLiteralExpression(properties?: readonly ObjectLiteralElementLike[], multiLine?: boolean): ObjectLiteralExpression; updateObjectLiteralExpression(node: ObjectLiteralExpression, properties: readonly ObjectLiteralElementLike[]): ObjectLiteralExpression; - createPropertyAccessExpression(expression: Expression, name: string | Identifier | PrivateIdentifier): PropertyAccessExpression; - updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: Identifier | PrivateIdentifier): PropertyAccessExpression; - createPropertyAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | Identifier | PrivateIdentifier): PropertyAccessChain; - updatePropertyAccessChain(node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: Identifier | PrivateIdentifier): PropertyAccessChain; + createPropertyAccessExpression(expression: Expression, name: string | MemberName): PropertyAccessExpression; + updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: MemberName): PropertyAccessExpression; + createPropertyAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | MemberName): PropertyAccessChain; + updatePropertyAccessChain(node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: MemberName): PropertyAccessChain; createElementAccessExpression(expression: Expression, index: number | Expression): ElementAccessExpression; updateElementAccessExpression(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; createElementAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, index: number | Expression): ElementAccessChain; @@ -7138,52 +7268,58 @@ namespace ts { updateJSDocTypeExpression(node: JSDocTypeExpression, type: TypeNode): JSDocTypeExpression; createJSDocNameReference(name: EntityName): JSDocNameReference; updateJSDocNameReference(node: JSDocNameReference, name: EntityName): JSDocNameReference; + createJSDocLink(name: EntityName | undefined, text: string): JSDocLink; + updateJSDocLink(node: JSDocLink, name: EntityName | undefined, text: string): JSDocLink; createJSDocTypeLiteral(jsDocPropertyTags?: readonly JSDocPropertyLikeTag[], isArrayType?: boolean): JSDocTypeLiteral; updateJSDocTypeLiteral(node: JSDocTypeLiteral, jsDocPropertyTags: readonly JSDocPropertyLikeTag[] | undefined, isArrayType: boolean | undefined): JSDocTypeLiteral; createJSDocSignature(typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag): JSDocSignature; updateJSDocSignature(node: JSDocSignature, typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type: JSDocReturnTag | undefined): JSDocSignature; - createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string): JSDocTemplateTag; - updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | undefined): JSDocTemplateTag; - createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string): JSDocTypedefTag; - updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | undefined): JSDocTypedefTag; - createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string): JSDocParameterTag; - updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | undefined): JSDocParameterTag; - createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string): JSDocPropertyTag; - updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | undefined): JSDocPropertyTag; - createJSDocTypeTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string): JSDocTypeTag; - updateJSDocTypeTag(node: JSDocTypeTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | undefined): JSDocTypeTag; - createJSDocSeeTag(tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string): JSDocSeeTag; - updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string): JSDocSeeTag; - createJSDocReturnTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string): JSDocReturnTag; - updateJSDocReturnTag(node: JSDocReturnTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | undefined): JSDocReturnTag; - createJSDocThisTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string): JSDocThisTag; - updateJSDocThisTag(node: JSDocThisTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | undefined): JSDocThisTag; - createJSDocEnumTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string): JSDocEnumTag; - updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | undefined): JSDocEnumTag; - createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string): JSDocCallbackTag; - updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | undefined): JSDocCallbackTag; - createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string): JSDocAugmentsTag; - updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment: string | undefined): JSDocAugmentsTag; - createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string): JSDocImplementsTag; - updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment: string | undefined): JSDocImplementsTag; - createJSDocAuthorTag(tagName: Identifier | undefined, comment?: string): JSDocAuthorTag; - updateJSDocAuthorTag(node: JSDocAuthorTag, tagName: Identifier | undefined, comment: string | undefined): JSDocAuthorTag; - createJSDocClassTag(tagName: Identifier | undefined, comment?: string): JSDocClassTag; - updateJSDocClassTag(node: JSDocClassTag, tagName: Identifier | undefined, comment: string | undefined): JSDocClassTag; - createJSDocPublicTag(tagName: Identifier | undefined, comment?: string): JSDocPublicTag; - updateJSDocPublicTag(node: JSDocPublicTag, tagName: Identifier | undefined, comment: string | undefined): JSDocPublicTag; - createJSDocPrivateTag(tagName: Identifier | undefined, comment?: string): JSDocPrivateTag; - updateJSDocPrivateTag(node: JSDocPrivateTag, tagName: Identifier | undefined, comment: string | undefined): JSDocPrivateTag; - createJSDocProtectedTag(tagName: Identifier | undefined, comment?: string): JSDocProtectedTag; - updateJSDocProtectedTag(node: JSDocProtectedTag, tagName: Identifier | undefined, comment: string | undefined): JSDocProtectedTag; - createJSDocReadonlyTag(tagName: Identifier | undefined, comment?: string): JSDocReadonlyTag; - updateJSDocReadonlyTag(node: JSDocReadonlyTag, tagName: Identifier | undefined, comment: string | undefined): JSDocReadonlyTag; - createJSDocUnknownTag(tagName: Identifier, comment?: string): JSDocUnknownTag; - updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | undefined): JSDocUnknownTag; - createJSDocDeprecatedTag(tagName: Identifier, comment?: string): JSDocDeprecatedTag; - updateJSDocDeprecatedTag(node: JSDocDeprecatedTag, tagName: Identifier, comment?: string): JSDocDeprecatedTag; - createJSDocComment(comment?: string | undefined, tags?: readonly JSDocTag[] | undefined): JSDoc; - updateJSDocComment(node: JSDoc, comment: string | undefined, tags: readonly JSDocTag[] | undefined): JSDoc; + createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray): JSDocTemplateTag; + updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | NodeArray | undefined): JSDocTemplateTag; + createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocTypedefTag; + updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocTypedefTag; + createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocParameterTag; + updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocParameterTag; + createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocPropertyTag; + updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocPropertyTag; + createJSDocTypeTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocTypeTag; + updateJSDocTypeTag(node: JSDocTypeTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined): JSDocTypeTag; + createJSDocSeeTag(tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag; + updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag; + createJSDocReturnTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray): JSDocReturnTag; + updateJSDocReturnTag(node: JSDocReturnTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined): JSDocReturnTag; + createJSDocThisTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocThisTag; + updateJSDocThisTag(node: JSDocThisTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined): JSDocThisTag; + createJSDocEnumTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocEnumTag; + updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined): JSDocEnumTag; + createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocCallbackTag; + updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocCallbackTag; + createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string | NodeArray): JSDocAugmentsTag; + updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment: string | NodeArray | undefined): JSDocAugmentsTag; + createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string | NodeArray): JSDocImplementsTag; + updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment: string | NodeArray | undefined): JSDocImplementsTag; + createJSDocAuthorTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocAuthorTag; + updateJSDocAuthorTag(node: JSDocAuthorTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocAuthorTag; + createJSDocClassTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocClassTag; + updateJSDocClassTag(node: JSDocClassTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocClassTag; + createJSDocPublicTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocPublicTag; + updateJSDocPublicTag(node: JSDocPublicTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocPublicTag; + createJSDocPrivateTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocPrivateTag; + updateJSDocPrivateTag(node: JSDocPrivateTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocPrivateTag; + createJSDocProtectedTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocProtectedTag; + updateJSDocProtectedTag(node: JSDocProtectedTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocProtectedTag; + createJSDocReadonlyTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocReadonlyTag; + updateJSDocReadonlyTag(node: JSDocReadonlyTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocReadonlyTag; + createJSDocUnknownTag(tagName: Identifier, comment?: string | NodeArray): JSDocUnknownTag; + updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | NodeArray | undefined): JSDocUnknownTag; + createJSDocDeprecatedTag(tagName: Identifier, comment?: string | NodeArray): JSDocDeprecatedTag; + updateJSDocDeprecatedTag(node: JSDocDeprecatedTag, tagName: Identifier, comment?: string | NodeArray): JSDocDeprecatedTag; + createJSDocOverrideTag(tagName: Identifier, comment?: string | NodeArray): JSDocOverrideTag; + updateJSDocOverrideTag(node: JSDocOverrideTag, tagName: Identifier, comment?: string | NodeArray): JSDocOverrideTag; + createJSDocText(text: string): JSDocText; + updateJSDocText(node: JSDocText, text: string): JSDocText; + createJSDocComment(comment?: string | NodeArray | undefined, tags?: readonly JSDocTag[] | undefined): JSDoc; + updateJSDocComment(node: JSDoc, comment: string | NodeArray | undefined, tags: readonly JSDocTag[] | undefined): JSDoc; // // JSX @@ -7384,7 +7520,7 @@ namespace ts { * @param allowComments A value indicating whether comments may be emitted for the name. * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. */ - /* @internal */ getDeclarationName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier; + /* @internal */ getDeclarationName(node: Declaration | undefined, allowComments?: boolean, allowSourceMaps?: boolean): Identifier; /** * Gets a namespace-qualified name for use in expressions. * @@ -7492,6 +7628,12 @@ namespace ts { /** Hoists a variable declaration to the containing scope. */ hoistVariableDeclaration(node: Identifier): void; + /*@internal*/ startBlockScope(): void; + + /*@internal*/ endBlockScope(): Statement[] | undefined; + + /*@internal*/ addBlockScopedVariable(node: Identifier): void; + /** Adds an initialization statement to the top of the lexical environment. */ /* @internal */ addInitializationStatement(node: Statement): void; @@ -7782,13 +7924,13 @@ namespace ts { * }); * ``` */ - onEmitNode?(hint: EmitHint, node: Node | undefined, emitCallback: (hint: EmitHint, node: Node | undefined) => void): void; + onEmitNode?(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; /** * A hook used to check if an emit notification is required for a node. * @param node The node to emit. */ - isEmitNotificationEnabled?(node: Node | undefined): boolean; + isEmitNotificationEnabled?(node: Node): boolean; /** * A hook used by the Printer to perform just-in-time substitution of a node. This is * primarily used by node transformations that need to substitute one node for another, @@ -7810,6 +7952,8 @@ namespace ts { /*@internal*/ onEmitSourceMapOfToken?: (node: Node | undefined, token: SyntaxKind, writer: (s: string) => void, pos: number, emitCallback: (token: SyntaxKind, writer: (s: string) => void, pos: number) => number) => number; /*@internal*/ onEmitSourceMapOfPosition?: (pos: number) => void; /*@internal*/ onSetSourceFile?: (node: SourceFile) => void; + /*@internal*/ onBeforeEmitNode?: (node: Node | undefined) => void; + /*@internal*/ onAfterEmitNode?: (node: Node | undefined) => void; /*@internal*/ onBeforeEmitNodeArray?: (nodes: NodeArray | undefined) => void; /*@internal*/ onAfterEmitNodeArray?: (nodes: NodeArray | undefined) => void; /*@internal*/ onBeforeEmitToken?: (node: Node) => void; @@ -7942,6 +8086,7 @@ namespace ts { readFile?(path: string): string | undefined; realpath?(path: string): string; getSymlinkCache?(): SymlinkCache; + getModuleSpecifierCache?(): ModuleSpecifierCache; getGlobalTypingsCacheLocation?(): string | undefined; getNearestAncestorDirectoryWithPackageJson?(fileName: string, rootDir?: string): string | undefined; @@ -7952,6 +8097,21 @@ namespace ts { getFileIncludeReasons(): MultiMap; } + /* @internal */ + export interface ModulePath { + path: string; + isInNodeModules: boolean; + isRedirect: boolean; + } + + /* @internal */ + export interface ModuleSpecifierCache { + get(fromFileName: Path, toFileName: Path): boolean | readonly ModulePath[] | undefined; + set(fromFileName: Path, toFileName: Path, moduleSpecifiers: boolean | readonly ModulePath[]): void; + clear(): void; + count(): number; + } + // Note: this used to be deprecated in our public API, but is still used internally /* @internal */ export interface SymbolTracker { @@ -8241,6 +8401,8 @@ namespace ts { readonly disableSuggestions?: boolean; readonly quotePreference?: "auto" | "double" | "single"; readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsForImportStatements?: boolean; + readonly includeCompletionsWithSnippetText?: boolean; readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index d91bbac3b741a..ecc92f8abfd69 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -205,7 +205,9 @@ namespace ts { } export function typeDirectiveIsEqualTo(oldResolution: ResolvedTypeReferenceDirective, newResolution: ResolvedTypeReferenceDirective): boolean { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + return oldResolution.resolvedFileName === newResolution.resolvedFileName + && oldResolution.primary === newResolution.primary + && oldResolution.originalPath === newResolution.originalPath; } export function hasChangesInResolutions( @@ -478,7 +480,12 @@ namespace ts { return getTokenPosOfNode((node)._children[0], sourceFile, includeJsDoc); } - return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + return skipTrivia( + (sourceFile || getSourceFileOfNode(node)).text, + node.pos, + /*stopAfterLineBreak*/ false, + /*stopAtComments*/ false, + isInJSDoc(node)); } export function getNonDecoratorTokenPosOfNode(node: Node, sourceFile?: SourceFileLike): number { @@ -603,9 +610,11 @@ namespace ts { DataView: ["setBigInt64", "setBigUint64", "getBigInt64", "getBigUint64"], RelativeTimeFormat: ["format", "formatToParts", "resolvedOptions"] }, - esnext: { + es2021: { PromiseConstructor: ["any"], - String: ["replaceAll"], + String: ["replaceAll"] + }, + esnext: { NumberFormat: ["formatToParts"] } }; @@ -734,9 +743,9 @@ namespace ts { return isShorthandAmbientModule(moduleSymbol.valueDeclaration); } - function isShorthandAmbientModule(node: Node): boolean { + function isShorthandAmbientModule(node: Node | undefined): boolean { // The only kind of module that can be missing a body is a shorthand ambient module. - return node && node.kind === SyntaxKind.ModuleDeclaration && (!(node).body); + return !!node && node.kind === SyntaxKind.ModuleDeclaration && (!(node).body); } export function isBlockScopedContainerTopLevel(node: Node): boolean { @@ -767,7 +776,7 @@ namespace ts { } export function getNonAugmentationDeclaration(symbol: Symbol) { - return find(symbol.declarations, d => !isExternalModuleAugmentation(d) && !(isModuleDeclaration(d) && isGlobalScopeAugmentation(d))); + return symbol.declarations?.find(d => !isExternalModuleAugmentation(d) && !(isModuleDeclaration(d) && isGlobalScopeAugmentation(d))); } export function isEffectiveExternalModule(node: SourceFile, compilerOptions: CompilerOptions) { @@ -1204,7 +1213,8 @@ namespace ts { node.kind === SyntaxKind.TypeParameter || node.kind === SyntaxKind.FunctionExpression || node.kind === SyntaxKind.ArrowFunction || - node.kind === SyntaxKind.ParenthesizedExpression) ? + node.kind === SyntaxKind.ParenthesizedExpression || + node.kind === SyntaxKind.VariableDeclaration) ? concatenate(getTrailingCommentRanges(text, node.pos), getLeadingCommentRanges(text, node.pos)) : getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -1730,6 +1740,14 @@ namespace ts { return !!node && isVariableDeclaration(node) && node.initializer?.kind === SyntaxKind.ThisKeyword; } + export function isThisInitializedObjectBindingExpression(node: Node | undefined): boolean { + return !!node + && (isShorthandPropertyAssignment(node) || isPropertyAssignment(node)) + && isBinaryExpression(node.parent.parent) + && node.parent.parent.operatorToken.kind === SyntaxKind.EqualsToken + && node.parent.parent.right.kind === SyntaxKind.ThisKeyword; + } + export function getEntityNameFromTypeNode(node: TypeNode): EntityNameOrEntityNameExpression | undefined { switch (node.kind) { case SyntaxKind.TypeReference: @@ -1955,6 +1973,10 @@ namespace ts { return node.kind === SyntaxKind.TypeQuery; } + export function isNamespaceReexportDeclaration(node: Node): boolean { + return isNamespaceExport(node) && !!node.parent.moduleSpecifier; + } + export function isExternalModuleImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration & { moduleReference: ExternalModuleReference } { return node.kind === SyntaxKind.ImportEqualsDeclaration && (node).moduleReference.kind === SyntaxKind.ExternalModuleReference; } @@ -1965,8 +1987,7 @@ namespace ts { } export function getExternalModuleRequireArgument(node: Node) { - return isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true) - && (getLeftmostAccessExpression(node.initializer) as CallExpression).arguments[0] as StringLiteral; + return isRequireVariableDeclaration(node) && (getLeftmostAccessExpression(node.initializer) as CallExpression).arguments[0] as StringLiteral; } export function isInternalModuleImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration { @@ -2033,19 +2054,17 @@ namespace ts { * Returns true if the node is a VariableDeclaration initialized to a require call (see `isRequireCall`). * This function does not test if the node is in a JavaScript file or not. */ - export function isRequireVariableDeclaration(node: Node, requireStringLiteralLikeArgument: true): node is RequireVariableDeclaration; - export function isRequireVariableDeclaration(node: Node, requireStringLiteralLikeArgument: boolean): node is VariableDeclaration; - export function isRequireVariableDeclaration(node: Node, requireStringLiteralLikeArgument: boolean): node is VariableDeclaration { + export function isRequireVariableDeclaration(node: Node): node is RequireVariableDeclaration { if (node.kind === SyntaxKind.BindingElement) { node = node.parent.parent; } - return isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), requireStringLiteralLikeArgument); + return isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), /*requireStringLiteralLikeArgument*/ true); } - export function isRequireVariableStatement(node: Node, requireStringLiteralLikeArgument = true): node is RequireVariableStatement { + export function isRequireVariableStatement(node: Node): node is RequireVariableStatement { return isVariableStatement(node) && node.declarationList.declarations.length > 0 - && every(node.declarationList.declarations, decl => isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument)); + && every(node.declarationList.declarations, decl => isRequireVariableDeclaration(decl)); } export function isSingleOrDoubleQuote(charCode: number) { @@ -2244,9 +2263,7 @@ namespace ts { /** x[0] OR x['a'] OR x[Symbol.y] */ export function isLiteralLikeElementAccess(node: Node): node is LiteralLikeElementAccessExpression { - return isElementAccessExpression(node) && ( - isStringOrNumericLiteralLike(node.argumentExpression) || - isWellKnownSymbolSyntactically(node.argumentExpression)); + return isElementAccessExpression(node) && isStringOrNumericLiteralLike(node.argumentExpression); } /** Any series of property and element accesses. */ @@ -2331,9 +2348,6 @@ namespace ts { return escapeLeadingUnderscores(name.text); } } - if (isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) { - return getPropertyNameForKnownSymbolName(idText((node.argumentExpression).name)); - } return undefined; } @@ -2409,6 +2423,19 @@ namespace ts { return decl.kind === SyntaxKind.FunctionDeclaration || isVariableDeclaration(decl) && decl.initializer && isFunctionLike(decl.initializer); } + export function tryGetModuleSpecifierFromDeclaration(node: AnyImportOrRequire): string | undefined { + switch (node.kind) { + case SyntaxKind.VariableDeclaration: + return node.initializer.arguments[0].text; + case SyntaxKind.ImportDeclaration: + return tryCast(node.moduleSpecifier, isStringLiteralLike)?.text; + case SyntaxKind.ImportEqualsDeclaration: + return tryCast(tryCast(node.moduleReference, isExternalModuleReference)?.expression, isStringLiteralLike)?.text; + default: + Debug.assertNever(node); + } + } + export function importFromModuleSpecifier(node: StringLiteralLike): AnyValidImportOrReExport { return tryGetImportFromModuleSpecifier(node) || Debug.failBadSyntaxKind(node.parent); } @@ -2583,6 +2610,7 @@ namespace ts { parent.kind === SyntaxKind.ExportAssignment || parent.kind === SyntaxKind.PropertyDeclaration || parent.kind === SyntaxKind.ExpressionStatement && node.kind === SyntaxKind.PropertyAccessExpression || + parent.kind === SyntaxKind.ReturnStatement || getNestedModuleDeclaration(parent) || isBinaryExpression(node) && node.operatorToken.kind === SyntaxKind.EqualsToken) { return parent; @@ -2703,6 +2731,9 @@ namespace ts { case SyntaxKind.NonNullExpression: node = parent; break; + case SyntaxKind.SpreadAssignment: + node = parent.parent; + break; case SyntaxKind.ShorthandPropertyAssignment: if ((parent as ShorthandPropertyAssignment).name !== node) { return AssignmentKind.None; @@ -3142,9 +3173,6 @@ namespace ts { * 3. The computed name is *not* expressed as a NumericLiteral. * 4. The computed name is *not* expressed as a PlusToken or MinusToken * immediately followed by a NumericLiteral. - * 5. The computed name is *not* expressed as `Symbol.`, where `` - * is a property of the Symbol constructor that denotes a built-in - * Symbol. */ export function hasDynamicName(declaration: Declaration): declaration is DynamicNamedDeclaration | DynamicNamedBinaryExpression { const name = getNameOfDeclaration(declaration); @@ -3157,17 +3185,7 @@ namespace ts { } const expr = isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression; return !isStringOrNumericLiteralLike(expr) && - !isSignedNumericLiteral(expr) && - !isWellKnownSymbolSyntactically(expr); - } - - /** - * Checks if the expression is of the form: - * Symbol.name - * where Symbol is literally the word "Symbol", and name is any identifierName - */ - export function isWellKnownSymbolSyntactically(node: Node): node is WellKnownSymbolExpression { - return isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); + !isSignedNumericLiteral(expr); } export function getPropertyNameForPropertyNameNode(name: PropertyName): __String | undefined { @@ -3180,10 +3198,7 @@ namespace ts { return escapeLeadingUnderscores(name.text); case SyntaxKind.ComputedPropertyName: const nameExpression = name.expression; - if (isWellKnownSymbolSyntactically(nameExpression)) { - return getPropertyNameForKnownSymbolName(idText((nameExpression).name)); - } - else if (isStringOrNumericLiteralLike(nameExpression)) { + if (isStringOrNumericLiteralLike(nameExpression)) { return escapeLeadingUnderscores(nameExpression.text); } else if (isSignedNumericLiteral(nameExpression)) { @@ -3210,21 +3225,17 @@ namespace ts { } } export function getTextOfIdentifierOrLiteral(node: PropertyNameLiteral): string { - return isIdentifierOrPrivateIdentifier(node) ? idText(node) : node.text; + return isMemberName(node) ? idText(node) : node.text; } export function getEscapedTextOfIdentifierOrLiteral(node: PropertyNameLiteral): __String { - return isIdentifierOrPrivateIdentifier(node) ? node.escapedText : escapeLeadingUnderscores(node.text); + return isMemberName(node) ? node.escapedText : escapeLeadingUnderscores(node.text); } export function getPropertyNameForUniqueESSymbol(symbol: Symbol): __String { return `__@${getSymbolId(symbol)}@${symbol.escapedName}` as __String; } - export function getPropertyNameForKnownSymbolName(symbolName: string): __String { - return "__@" + symbolName as __String; - } - export function getSymbolNameForPrivateIdentifier(containingClassSymbol: Symbol, description: __String): __String { return `__#${getSymbolId(containingClassSymbol)}@${description}` as __String; } @@ -3602,6 +3613,7 @@ namespace ts { case SyntaxKind.TaggedTemplateExpression: case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ElementAccessExpression: + case SyntaxKind.MetaProperty: return OperatorPrecedence.Member; case SyntaxKind.AsExpression: @@ -4231,8 +4243,10 @@ namespace ts { return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !host.isSourceFileFromExternalLibrary(sourceFile) && - !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) && - (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName)); + (forceDtsEmit || ( + !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) && + !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName) + )); } export function getSourceFilePathInNewDir(fileName: string, host: EmitHost, newDirPath: string): string { @@ -4666,6 +4680,18 @@ namespace ts { return hasSyntacticModifier(node, ModifierFlags.Static); } + export function hasOverrideModifier(node: Node): boolean { + return hasEffectiveModifier(node, ModifierFlags.Override); + } + + export function hasAbstractModifier(node: Node): boolean { + return hasSyntacticModifier(node, ModifierFlags.Abstract); + } + + export function hasAmbientModifier(node: Node): boolean { + return hasSyntacticModifier(node, ModifierFlags.Ambient); + } + export function hasEffectiveReadonlyModifier(node: Node): boolean { return hasEffectiveModifier(node, ModifierFlags.Readonly); } @@ -4724,6 +4750,7 @@ namespace ts { if (getJSDocPrivateTagNoCache(node)) flags |= ModifierFlags.Private; if (getJSDocProtectedTagNoCache(node)) flags |= ModifierFlags.Protected; if (getJSDocReadonlyTagNoCache(node)) flags |= ModifierFlags.Readonly; + if (getJSDocOverrideTagNoCache(node)) flags |= ModifierFlags.Override; } if (getJSDocDeprecatedTagNoCache(node)) flags |= ModifierFlags.Deprecated; } @@ -4776,10 +4803,15 @@ namespace ts { case SyntaxKind.DefaultKeyword: return ModifierFlags.Default; case SyntaxKind.AsyncKeyword: return ModifierFlags.Async; case SyntaxKind.ReadonlyKeyword: return ModifierFlags.Readonly; + case SyntaxKind.OverrideKeyword: return ModifierFlags.Override; } return ModifierFlags.None; } + export function createModifiers(modifierFlags: ModifierFlags): ModifiersArray | undefined { + return modifierFlags ? factory.createNodeArray(factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; + } + export function isLogicalOperator(token: SyntaxKind): boolean { return token === SyntaxKind.BarBarToken || token === SyntaxKind.AmpersandAmpersandToken @@ -4828,6 +4860,9 @@ namespace ts { && isLeftHandSideExpression(node.left); } + export function isLeftHandSideOfAssignment(node: Node) { + return isAssignmentExpression(node.parent) && node.parent.left === node; + } export function isDestructuringAssignment(node: Node): node is DestructuringAssignment { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { const kind = node.left.kind; @@ -4864,9 +4899,12 @@ namespace ts { } export function isDottedName(node: Expression): boolean { - return node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.ThisKeyword || node.kind === SyntaxKind.SuperKeyword || - node.kind === SyntaxKind.PropertyAccessExpression && isDottedName((node).expression) || - node.kind === SyntaxKind.ParenthesizedExpression && isDottedName((node).expression); + return node.kind === SyntaxKind.Identifier + || node.kind === SyntaxKind.ThisKeyword + || node.kind === SyntaxKind.SuperKeyword + || node.kind === SyntaxKind.MetaProperty + || node.kind === SyntaxKind.PropertyAccessExpression && isDottedName((node).expression) + || node.kind === SyntaxKind.ParenthesizedExpression && isDottedName((node).expression); } export function isPropertyAccessEntityNameExpression(node: Node): node is PropertyAccessEntityNameExpression { @@ -4912,7 +4950,7 @@ namespace ts { } export function getLocalSymbolForExportDefault(symbol: Symbol) { - if (!isExportDefaultSymbol(symbol)) return undefined; + if (!isExportDefaultSymbol(symbol) || !symbol.declarations) return undefined; for (const decl of symbol.declarations) { if (decl.localSymbol) return decl.localSymbol; } @@ -4920,7 +4958,7 @@ namespace ts { } function isExportDefaultSymbol(symbol: Symbol): boolean { - return symbol && length(symbol.declarations) > 0 && hasSyntacticModifier(symbol.declarations[0], ModifierFlags.Default); + return symbol && length(symbol.declarations) > 0 && hasSyntacticModifier(symbol.declarations![0], ModifierFlags.Default); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ @@ -5280,9 +5318,10 @@ namespace ts { return symbol.flags & SymbolFlags.Transient ? (symbol).checkFlags : 0; } - export function getDeclarationModifierFlagsFromSymbol(s: Symbol): ModifierFlags { + export function getDeclarationModifierFlagsFromSymbol(s: Symbol, isWrite = false): ModifierFlags { if (s.valueDeclaration) { - const flags = getCombinedModifierFlags(s.valueDeclaration); + const declaration = (isWrite && s.declarations && find(s.declarations, d => d.kind === SyntaxKind.SetAccessor)) || s.valueDeclaration; + const flags = getCombinedModifierFlags(declaration); return s.parent && s.parent.flags & SymbolFlags.Class ? flags : flags & ~ModifierFlags.AccessibilityModifier; } if (getCheckFlags(s) & CheckFlags.Synthetic) { @@ -5397,14 +5436,14 @@ namespace ts { /** * clears already present map by calling onDeleteExistingValue callback before deleting that key/value */ - export function clearMap(map: { forEach: ESMap["forEach"]; clear: ESMap["clear"]; }, onDeleteValue: (valueInMap: T, key: string) => void) { + export function clearMap(map: { forEach: ESMap["forEach"]; clear: ESMap["clear"]; }, onDeleteValue: (valueInMap: T, key: K) => void) { // Remove all map.forEach(onDeleteValue); map.clear(); } - export interface MutateMapSkippingNewValuesOptions { - onDeleteValue(existingValue: T, key: string): void; + export interface MutateMapSkippingNewValuesOptions { + onDeleteValue(existingValue: T, key: K): void; /** * If present this is called with the key when there is value for that key both in new map as well as existing map provided @@ -5412,16 +5451,16 @@ namespace ts { * If the key is removed, caller will get callback of createNewValue for that key. * If this callback is not provided, the value of such keys is not updated. */ - onExistingValue?(existingValue: T, valueInNewMap: U, key: string): void; + onExistingValue?(existingValue: T, valueInNewMap: U, key: K): void; } /** * Mutates the map with newMap such that keys in map will be same as newMap. */ - export function mutateMapSkippingNewValues( - map: ESMap, - newMap: ReadonlyESMap, - options: MutateMapSkippingNewValuesOptions + export function mutateMapSkippingNewValues( + map: ESMap, + newMap: ReadonlyESMap, + options: MutateMapSkippingNewValuesOptions ) { const { onDeleteValue, onExistingValue } = options; // Needs update @@ -5439,14 +5478,14 @@ namespace ts { }); } - export interface MutateMapOptions extends MutateMapSkippingNewValuesOptions { - createNewValue(key: string, valueInNewMap: U): T; + export interface MutateMapOptions extends MutateMapSkippingNewValuesOptions { + createNewValue(key: K, valueInNewMap: U): T; } /** * Mutates the map with newMap such that keys in map will be same as newMap. */ - export function mutateMap(map: ESMap, newMap: ReadonlyESMap, options: MutateMapOptions) { + export function mutateMap(map: ESMap, newMap: ReadonlyESMap, options: MutateMapOptions) { // Needs update mutateMapSkippingNewValues(map, newMap, options); @@ -5469,7 +5508,7 @@ namespace ts { } export function getClassLikeDeclarationOfSymbol(symbol: Symbol): ClassLikeDeclaration | undefined { - return find(symbol.declarations, isClassLike); + return symbol.declarations?.find(isClassLike); } export function getObjectFlags(type: Type): ObjectFlags { @@ -5511,10 +5550,9 @@ namespace ts { } /** Add a value to a set, and return true if it wasn't already present. */ - export function addToSeen(seen: ESMap, key: string | number): boolean; - export function addToSeen(seen: ESMap, key: string | number, value: T): boolean; - export function addToSeen(seen: ESMap, key: string | number, value: T = true as any): boolean { - key = String(key); + export function addToSeen(seen: ESMap, key: K): boolean; + export function addToSeen(seen: ESMap, key: K, value: T): boolean; + export function addToSeen(seen: ESMap, key: K, value: T = true as any): boolean { if (seen.has(key)) { return false; } @@ -5634,8 +5672,8 @@ namespace ts { function Symbol(this: Symbol, flags: SymbolFlags, name: __String) { this.flags = flags; this.escapedName = name; - this.declarations = undefined!; - this.valueDeclaration = undefined!; + this.declarations = undefined; + this.valueDeclaration = undefined; this.id = undefined; this.mergeId = undefined; this.parent = undefined; @@ -6045,6 +6083,10 @@ namespace ts { return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs; } + export function getUseDefineForClassFields(compilerOptions: CompilerOptions): boolean { + return compilerOptions.useDefineForClassFields === undefined ? compilerOptions.target === ScriptTarget.ESNext : compilerOptions.useDefineForClassFields; + } + export function compilerOptionsAffectSemanticDiagnostics(newOptions: CompilerOptions, oldOptions: CompilerOptions): boolean { return oldOptions !== newOptions && semanticDiagnosticsOptionDeclarations.some(option => !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option))); @@ -6066,7 +6108,7 @@ namespace ts { export function getJSXImplicitImportBase(compilerOptions: CompilerOptions, file?: SourceFile): string | undefined { const jsxImportSourcePragmas = file?.pragmas.get("jsximportsource"); - const jsxImportSourcePragma = isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[0] : jsxImportSourcePragmas; + const jsxImportSourcePragma = isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[jsxImportSourcePragmas.length - 1] : jsxImportSourcePragmas; return compilerOptions.jsx === JsxEmit.ReactJSX || compilerOptions.jsx === JsxEmit.ReactJSXDev || compilerOptions.jsxImportSource || @@ -6109,6 +6151,8 @@ namespace ts { getSymlinkedFiles(): ReadonlyESMap | undefined; setSymlinkedDirectory(symlink: string, real: SymlinkedDirectory | false): void; setSymlinkedFile(symlinkPath: Path, real: string): void; + /*@internal*/ + setSymlinkedDirectoryFromSymlinkedFile(symlink: string, real: string): void; } export function createSymlinkCache(cwd: string, getCanonicalFileName: GetCanonicalFileName): SymlinkCache { @@ -6132,16 +6176,31 @@ namespace ts { } (symlinkedDirectories || (symlinkedDirectories = new Map())).set(symlinkPath, real); } - } + }, + setSymlinkedDirectoryFromSymlinkedFile(symlink, real) { + this.setSymlinkedFile(toPath(symlink, cwd, getCanonicalFileName), real); + const [commonResolved, commonOriginal] = guessDirectorySymlink(real, symlink, cwd, getCanonicalFileName) || emptyArray; + if (commonResolved && commonOriginal) { + this.setSymlinkedDirectory(commonOriginal, { + real: commonResolved, + realPath: toPath(commonResolved, cwd, getCanonicalFileName), + }); + } + }, }; } export function discoverProbableSymlinks(files: readonly SourceFile[], getCanonicalFileName: GetCanonicalFileName, cwd: string): SymlinkCache { const cache = createSymlinkCache(cwd, getCanonicalFileName); - const symlinks = flatten(mapDefined(files, sf => - sf.resolvedModules && compact(arrayFrom(mapIterator(sf.resolvedModules.values(), res => - res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] as const : undefined))))); + const symlinks = flatMap(files, sf => { + const pairs = sf.resolvedModules && arrayFrom(mapDefinedIterator(sf.resolvedModules.values(), res => + res?.originalPath ? [res.resolvedFileName, res.originalPath] as const : undefined)); + return concatenate(pairs, sf.resolvedTypeReferenceDirectiveNames && arrayFrom(mapDefinedIterator(sf.resolvedTypeReferenceDirectiveNames.values(), res => + res?.originalPath && res.resolvedFileName ? [res.resolvedFileName, res.originalPath] as const : undefined))); + }); + for (const [resolvedPath, originalPath] of symlinks) { + cache.setSymlinkedFile(toPath(originalPath, cwd, getCanonicalFileName), resolvedPath); const [commonResolved, commonOriginal] = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || emptyArray; if (commonResolved && commonOriginal) { cache.setSymlinkedDirectory( @@ -7122,4 +7181,71 @@ namespace ts { export function containsIgnoredPath(path: string) { return some(ignoredPaths, p => stringContains(path, p)); } + + export function getContainingNodeArray(node: Node): NodeArray | undefined { + if (!node.parent) return undefined; + switch (node.kind) { + case SyntaxKind.TypeParameter: + const { parent } = node as TypeParameterDeclaration; + return parent.kind === SyntaxKind.InferType ? undefined : parent.typeParameters; + case SyntaxKind.Parameter: + return (node as ParameterDeclaration).parent.parameters; + case SyntaxKind.TemplateLiteralTypeSpan: + return (node as TemplateLiteralTypeSpan).parent.templateSpans; + case SyntaxKind.TemplateSpan: + return (node as TemplateSpan).parent.templateSpans; + case SyntaxKind.Decorator: + return (node as Decorator).parent.decorators; + case SyntaxKind.HeritageClause: + return (node as HeritageClause).parent.heritageClauses; + } + + const { parent } = node; + if (isJSDocTag(node)) { + return isJSDocTypeLiteral(node.parent) ? undefined : node.parent.tags; + } + + switch (parent.kind) { + case SyntaxKind.TypeLiteral: + case SyntaxKind.InterfaceDeclaration: + return isTypeElement(node) ? (parent as TypeLiteralNode | InterfaceDeclaration).members : undefined; + case SyntaxKind.UnionType: + case SyntaxKind.IntersectionType: + return (parent as UnionOrIntersectionTypeNode).types; + case SyntaxKind.TupleType: + case SyntaxKind.ArrayLiteralExpression: + case SyntaxKind.CommaListExpression: + case SyntaxKind.NamedImports: + case SyntaxKind.NamedExports: + return (parent as TupleTypeNode | ArrayLiteralExpression | CommaListExpression | NamedImports | NamedExports).elements; + case SyntaxKind.ObjectLiteralExpression: + case SyntaxKind.JsxAttributes: + return (parent as ObjectLiteralExpressionBase).properties; + case SyntaxKind.CallExpression: + case SyntaxKind.NewExpression: + return isTypeNode(node) ? (parent as CallExpression | NewExpression).typeArguments : + (parent as CallExpression | NewExpression).expression === node ? undefined : + (parent as CallExpression | NewExpression).arguments; + case SyntaxKind.JsxElement: + case SyntaxKind.JsxFragment: + return isJsxChild(node) ? (parent as JsxElement | JsxFragment).children : undefined; + case SyntaxKind.JsxOpeningElement: + case SyntaxKind.JsxSelfClosingElement: + return isTypeNode(node) ? (parent as JsxOpeningElement | JsxSelfClosingElement).typeArguments : undefined; + case SyntaxKind.Block: + case SyntaxKind.CaseClause: + case SyntaxKind.DefaultClause: + case SyntaxKind.ModuleBlock: + return (parent as Block | CaseOrDefaultClause | ModuleBlock).statements; + case SyntaxKind.CaseBlock: + return (parent as CaseBlock).clauses; + case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: + return isClassElement(node) ? (parent as ClassLikeDeclaration).members : undefined; + case SyntaxKind.EnumDeclaration: + return isEnumMember(node) ? (parent as EnumDeclaration).members : undefined; + case SyntaxKind.SourceFile: + return (parent as SourceFile).statements; + } + } } diff --git a/src/compiler/utilitiesPublic.ts b/src/compiler/utilitiesPublic.ts index d45eb73478d5a..a6ec7bd761747 100644 --- a/src/compiler/utilitiesPublic.ts +++ b/src/compiler/utilitiesPublic.ts @@ -14,6 +14,8 @@ namespace ts { switch (options.target) { case ScriptTarget.ESNext: return "lib.esnext.full.d.ts"; + case ScriptTarget.ES2021: + return "lib.es2021.full.d.ts"; case ScriptTarget.ES2020: return "lib.es2020.full.d.ts"; case ScriptTarget.ES2019: @@ -488,7 +490,7 @@ namespace ts { return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText); } export function symbolName(symbol: Symbol): string { - if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) { + if (symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) { return idText(symbol.valueDeclaration.name); } return unescapeLeadingUnderscores(symbol.escapedName); @@ -614,10 +616,10 @@ namespace ts { return (declaration as NamedDeclaration).name; } - export function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined { + export function getNameOfDeclaration(declaration: Declaration | Expression | undefined): DeclarationName | undefined { if (declaration === undefined) return undefined; return getNonAssignedNameOfDeclaration(declaration) || - (isFunctionExpression(declaration) || isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + (isFunctionExpression(declaration) || isArrowFunction(declaration) || isClassExpression(declaration) ? getAssignedName(declaration) : undefined); } /*@internal*/ @@ -771,6 +773,10 @@ namespace ts { return getFirstJSDocTag(node, isJSDocReadonlyTag, /*noCache*/ true); } + export function getJSDocOverrideTagNoCache(node: Node): JSDocOverrideTag | undefined { + return getFirstJSDocTag(node, isJSDocOverrideTag, /*noCache*/ true); + } + /** Gets the JSDoc deprecated tag for the node if present */ export function getJSDocDeprecatedTag(node: Node): JSDocDeprecatedTag | undefined { return getFirstJSDocTag(node, isJSDocDeprecatedTag); @@ -894,6 +900,13 @@ namespace ts { return getJSDocTags(node).filter(doc => doc.kind === kind); } + /** Gets the text of a jsdoc comment, flattening links to their text. */ + export function getTextOfJSDocComment(comment?: string | NodeArray) { + return typeof comment === "string" ? comment + : comment?.map(c => + c.kind === SyntaxKind.JSDocText ? c.text : `{@link ${c.name ? entityNameToString(c.name) + " " : ""}${c.text}}`).join(""); + } + /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. @@ -930,7 +943,7 @@ namespace ts { // #region - export function isIdentifierOrPrivateIdentifier(node: Node): node is Identifier | PrivateIdentifier { + export function isMemberName(node: Node): node is MemberName { return node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.PrivateIdentifier; } @@ -1055,13 +1068,22 @@ namespace ts { return kind >= SyntaxKind.FirstNode; } + /** + * True if kind is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + export function isTokenKind(kind: SyntaxKind): boolean { + return kind >= SyntaxKind.FirstToken && kind <= SyntaxKind.LastToken; + } + /** * True if node is of some token syntax kind. * For example, this is true for an IfKeyword but not for an IfStatement. * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. */ export function isToken(n: Node): boolean { - return n.kind >= SyntaxKind.FirstToken && n.kind <= SyntaxKind.LastToken; + return isTokenKind(n.kind); } // Node Arrays @@ -1131,8 +1153,8 @@ namespace ts { // Private Identifiers /*@internal*/ - export function isPrivateIdentifierPropertyDeclaration(node: Node): node is PrivateIdentifierPropertyDeclaration { - return isPropertyDeclaration(node) && isPrivateIdentifier(node.name); + export function isPrivateIdentifierClassElementDeclaration(node: Node): node is PrivateClassElementDeclaration { + return (isPropertyDeclaration(node) || isMethodOrAccessor(node)) && isPrivateIdentifier(node.name); } /*@internal*/ @@ -1156,6 +1178,7 @@ namespace ts { case SyntaxKind.ProtectedKeyword: case SyntaxKind.ReadonlyKeyword: case SyntaxKind.StaticKeyword: + case SyntaxKind.OverrideKeyword: return true; } return false; @@ -1168,7 +1191,7 @@ namespace ts { /* @internal */ export function isClassMemberModifier(idToken: SyntaxKind): boolean { - return isParameterPropertyModifier(idToken) || idToken === SyntaxKind.StaticKeyword; + return isParameterPropertyModifier(idToken) || idToken === SyntaxKind.StaticKeyword || idToken === SyntaxKind.OverrideKeyword; } export function isModifier(node: Node): node is Modifier { @@ -1199,8 +1222,8 @@ namespace ts { // Functions - export function isFunctionLike(node: Node): node is SignatureDeclaration { - return node && isFunctionLikeKind(node.kind); + export function isFunctionLike(node: Node | undefined): node is SignatureDeclaration { + return !!node && isFunctionLikeKind(node.kind); } /* @internal */ @@ -1849,7 +1872,13 @@ namespace ts { /** True if node is of a kind that may contain comment text. */ export function isJSDocCommentContainingNode(node: Node): boolean { - return node.kind === SyntaxKind.JSDocComment || node.kind === SyntaxKind.JSDocNamepathType || isJSDocTag(node) || isJSDocTypeLiteral(node) || isJSDocSignature(node); + return node.kind === SyntaxKind.JSDocComment + || node.kind === SyntaxKind.JSDocNamepathType + || node.kind === SyntaxKind.JSDocText + || node.kind === SyntaxKind.JSDocLink + || isJSDocTag(node) + || isJSDocTypeLiteral(node) + || isJSDocSignature(node); } // TODO: determine what this does before making it public. diff --git a/src/compiler/visitorPublic.ts b/src/compiler/visitorPublic.ts index 958b7b1bdd511..960cd16f8479b 100644 --- a/src/compiler/visitorPublic.ts +++ b/src/compiler/visitorPublic.ts @@ -1,6 +1,4 @@ namespace ts { - const isTypeNodeOrTypeParameterDeclaration = or(isTypeNode, isTypeParameterDeclaration); - /** * Visits a Node using the supplied visitor, possibly returning a new Node in its place. * @@ -313,6 +311,24 @@ namespace ts { return updated; } + /** + * Visits an iteration body, adding any block-scoped variables required by the transformation. + */ + export function visitIterationBody(body: Statement, visitor: Visitor, context: TransformationContext): Statement { + context.startBlockScope(); + const updated = visitNode(body, visitor, isStatement, context.factory.liftToBlock); + const declarations = context.endBlockScope(); + if (some(declarations)) { + if (isBlock(updated)) { + declarations.push(...updated.statements); + return context.factory.updateBlock(updated, declarations); + } + declarations.push(updated); + return context.factory.createBlock(declarations); + } + return updated; + } + /** * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place. * @@ -350,755 +366,889 @@ namespace ts { // Names case SyntaxKind.Identifier: - return factory.updateIdentifier(node, - nodesVisitor((node).typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); + Debug.type(node); + return factory.updateIdentifier(node, + nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); case SyntaxKind.QualifiedName: - return factory.updateQualifiedName(node, - nodeVisitor((node).left, visitor, isEntityName), - nodeVisitor((node).right, visitor, isIdentifier)); + Debug.type(node); + return factory.updateQualifiedName(node, + nodeVisitor(node.left, visitor, isEntityName), + nodeVisitor(node.right, visitor, isIdentifier)); case SyntaxKind.ComputedPropertyName: - return factory.updateComputedPropertyName(node, - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateComputedPropertyName(node, + nodeVisitor(node.expression, visitor, isExpression)); // Signature elements case SyntaxKind.TypeParameter: - return factory.updateTypeParameterDeclaration(node, - nodeVisitor((node).name, visitor, isIdentifier), - nodeVisitor((node).constraint, visitor, isTypeNode), - nodeVisitor((node).default, visitor, isTypeNode)); + Debug.type(node); + return factory.updateTypeParameterDeclaration(node, + nodeVisitor(node.name, visitor, isIdentifier), + nodeVisitor(node.constraint, visitor, isTypeNode), + nodeVisitor(node.default, visitor, isTypeNode)); case SyntaxKind.Parameter: - return factory.updateParameterDeclaration(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - nodeVisitor((node).dotDotDotToken, tokenVisitor, isToken), - nodeVisitor((node).name, visitor, isBindingName), - nodeVisitor((node).questionToken, tokenVisitor, isToken), - nodeVisitor((node).type, visitor, isTypeNode), - nodeVisitor((node).initializer, visitor, isExpression)); + Debug.type(node); + return factory.updateParameterDeclaration(node, + nodesVisitor(node.decorators, visitor, isDecorator), + nodesVisitor(node.modifiers, visitor, isModifier), + nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken), + nodeVisitor(node.name, visitor, isBindingName), + nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken), + nodeVisitor(node.type, visitor, isTypeNode), + nodeVisitor(node.initializer, visitor, isExpression)); case SyntaxKind.Decorator: - return factory.updateDecorator(node, - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateDecorator(node, + nodeVisitor(node.expression, visitor, isExpression)); // Type elements case SyntaxKind.PropertySignature: - return factory.updatePropertySignature((node), - nodesVisitor((node).modifiers, visitor, isToken), - nodeVisitor((node).name, visitor, isPropertyName), - nodeVisitor((node).questionToken, tokenVisitor, isToken), - nodeVisitor((node).type, visitor, isTypeNode)); + Debug.type(node); + return factory.updatePropertySignature(node, + nodesVisitor(node.modifiers, visitor, isModifier), + nodeVisitor(node.name, visitor, isPropertyName), + nodeVisitor(node.questionToken, tokenVisitor, isToken), + nodeVisitor(node.type, visitor, isTypeNode)); case SyntaxKind.PropertyDeclaration: - return factory.updatePropertyDeclaration(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - nodeVisitor((node).name, visitor, isPropertyName), + Debug.type(node); + return factory.updatePropertyDeclaration(node, + nodesVisitor(node.decorators, visitor, isDecorator), + nodesVisitor(node.modifiers, visitor, isModifier), + nodeVisitor(node.name, visitor, isPropertyName), // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too - nodeVisitor((node).questionToken || (node).exclamationToken, tokenVisitor, isToken), - nodeVisitor((node).type, visitor, isTypeNode), - nodeVisitor((node).initializer, visitor, isExpression)); + nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, isQuestionOrExclamationToken), + nodeVisitor(node.type, visitor, isTypeNode), + nodeVisitor(node.initializer, visitor, isExpression)); case SyntaxKind.MethodSignature: - return factory.updateMethodSignature(node, - nodesVisitor((node).modifiers, visitor, isModifier), - nodeVisitor((node).name, visitor, isPropertyName), - nodeVisitor((node).questionToken, tokenVisitor, isToken), - nodesVisitor((node).typeParameters, visitor, isTypeParameterDeclaration), - nodesVisitor((node).parameters, visitor, isParameterDeclaration), - nodeVisitor((node).type, visitor, isTypeNode)); + Debug.type(node); + return factory.updateMethodSignature(node, + nodesVisitor(node.modifiers, visitor, isModifier), + nodeVisitor(node.name, visitor, isPropertyName), + nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken), + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + nodesVisitor(node.parameters, visitor, isParameterDeclaration), + nodeVisitor(node.type, visitor, isTypeNode)); case SyntaxKind.MethodDeclaration: - return factory.updateMethodDeclaration(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - nodeVisitor((node).asteriskToken, tokenVisitor, isToken), - nodeVisitor((node).name, visitor, isPropertyName), - nodeVisitor((node).questionToken, tokenVisitor, isToken), - nodesVisitor((node).typeParameters, visitor, isTypeParameterDeclaration), - visitParameterList((node).parameters, visitor, context, nodesVisitor), - nodeVisitor((node).type, visitor, isTypeNode), - visitFunctionBody((node).body!, visitor, context, nodeVisitor)); + Debug.type(node); + return factory.updateMethodDeclaration(node, + nodesVisitor(node.decorators, visitor, isDecorator), + nodesVisitor(node.modifiers, visitor, isModifier), + nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken), + nodeVisitor(node.name, visitor, isPropertyName), + nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken), + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + visitParameterList(node.parameters, visitor, context, nodesVisitor), + nodeVisitor(node.type, visitor, isTypeNode), + visitFunctionBody(node.body!, visitor, context, nodeVisitor)); case SyntaxKind.Constructor: - return factory.updateConstructorDeclaration(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - visitParameterList((node).parameters, visitor, context, nodesVisitor), - visitFunctionBody((node).body!, visitor, context, nodeVisitor)); + Debug.type(node); + return factory.updateConstructorDeclaration(node, + nodesVisitor(node.decorators, visitor, isDecorator), + nodesVisitor(node.modifiers, visitor, isModifier), + visitParameterList(node.parameters, visitor, context, nodesVisitor), + visitFunctionBody(node.body!, visitor, context, nodeVisitor)); case SyntaxKind.GetAccessor: - return factory.updateGetAccessorDeclaration(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - nodeVisitor((node).name, visitor, isPropertyName), - visitParameterList((node).parameters, visitor, context, nodesVisitor), - nodeVisitor((node).type, visitor, isTypeNode), - visitFunctionBody((node).body!, visitor, context, nodeVisitor)); + Debug.type(node); + return factory.updateGetAccessorDeclaration(node, + nodesVisitor(node.decorators, visitor, isDecorator), + nodesVisitor(node.modifiers, visitor, isModifier), + nodeVisitor(node.name, visitor, isPropertyName), + visitParameterList(node.parameters, visitor, context, nodesVisitor), + nodeVisitor(node.type, visitor, isTypeNode), + visitFunctionBody(node.body!, visitor, context, nodeVisitor)); case SyntaxKind.SetAccessor: - return factory.updateSetAccessorDeclaration(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - nodeVisitor((node).name, visitor, isPropertyName), - visitParameterList((node).parameters, visitor, context, nodesVisitor), - visitFunctionBody((node).body!, visitor, context, nodeVisitor)); + Debug.type(node); + return factory.updateSetAccessorDeclaration(node, + nodesVisitor(node.decorators, visitor, isDecorator), + nodesVisitor(node.modifiers, visitor, isModifier), + nodeVisitor(node.name, visitor, isPropertyName), + visitParameterList(node.parameters, visitor, context, nodesVisitor), + visitFunctionBody(node.body!, visitor, context, nodeVisitor)); case SyntaxKind.CallSignature: - return factory.updateCallSignature(node, - nodesVisitor((node).typeParameters, visitor, isTypeParameterDeclaration), - nodesVisitor((node).parameters, visitor, isParameterDeclaration), - nodeVisitor((node).type, visitor, isTypeNode)); + Debug.type(node); + return factory.updateCallSignature(node, + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + nodesVisitor(node.parameters, visitor, isParameterDeclaration), + nodeVisitor(node.type, visitor, isTypeNode)); case SyntaxKind.ConstructSignature: - return factory.updateConstructSignature(node, - nodesVisitor((node).typeParameters, visitor, isTypeParameterDeclaration), - nodesVisitor((node).parameters, visitor, isParameterDeclaration), - nodeVisitor((node).type, visitor, isTypeNode)); + Debug.type(node); + return factory.updateConstructSignature(node, + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + nodesVisitor(node.parameters, visitor, isParameterDeclaration), + nodeVisitor(node.type, visitor, isTypeNode)); case SyntaxKind.IndexSignature: - return factory.updateIndexSignature(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - nodesVisitor((node).parameters, visitor, isParameterDeclaration), - nodeVisitor((node).type, visitor, isTypeNode)); + Debug.type(node); + return factory.updateIndexSignature(node, + nodesVisitor(node.decorators, visitor, isDecorator), + nodesVisitor(node.modifiers, visitor, isModifier), + nodesVisitor(node.parameters, visitor, isParameterDeclaration), + nodeVisitor(node.type, visitor, isTypeNode)); // Types case SyntaxKind.TypePredicate: - return factory.updateTypePredicateNode(node, - nodeVisitor((node).assertsModifier, visitor), - nodeVisitor((node).parameterName, visitor), - nodeVisitor((node).type, visitor, isTypeNode)); + Debug.type(node); + return factory.updateTypePredicateNode(node, + nodeVisitor(node.assertsModifier, visitor, isAssertsKeyword), + nodeVisitor(node.parameterName, visitor, isIdentifierOrThisTypeNode), + nodeVisitor(node.type, visitor, isTypeNode)); case SyntaxKind.TypeReference: - return factory.updateTypeReferenceNode(node, - nodeVisitor((node).typeName, visitor, isEntityName), - nodesVisitor((node).typeArguments, visitor, isTypeNode)); + Debug.type(node); + return factory.updateTypeReferenceNode(node, + nodeVisitor(node.typeName, visitor, isEntityName), + nodesVisitor(node.typeArguments, visitor, isTypeNode)); case SyntaxKind.FunctionType: - return factory.updateFunctionTypeNode(node, - nodesVisitor((node).typeParameters, visitor, isTypeParameterDeclaration), - nodesVisitor((node).parameters, visitor, isParameterDeclaration), - nodeVisitor((node).type, visitor, isTypeNode)); + Debug.type(node); + return factory.updateFunctionTypeNode(node, + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + nodesVisitor(node.parameters, visitor, isParameterDeclaration), + nodeVisitor(node.type, visitor, isTypeNode)); case SyntaxKind.ConstructorType: - return factory.updateConstructorTypeNode(node, - nodesVisitor((node).modifiers, visitor, isModifier), - nodesVisitor((node).typeParameters, visitor, isTypeParameterDeclaration), - nodesVisitor((node).parameters, visitor, isParameterDeclaration), - nodeVisitor((node).type, visitor, isTypeNode)); + Debug.type(node); + return factory.updateConstructorTypeNode(node, + nodesVisitor(node.modifiers, visitor, isModifier), + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + nodesVisitor(node.parameters, visitor, isParameterDeclaration), + nodeVisitor(node.type, visitor, isTypeNode)); case SyntaxKind.TypeQuery: - return factory.updateTypeQueryNode((node), - nodeVisitor((node).exprName, visitor, isEntityName)); + Debug.type(node); + return factory.updateTypeQueryNode(node, + nodeVisitor(node.exprName, visitor, isEntityName)); case SyntaxKind.TypeLiteral: - return factory.updateTypeLiteralNode((node), - nodesVisitor((node).members, visitor, isTypeElement)); + Debug.type(node); + return factory.updateTypeLiteralNode(node, + nodesVisitor(node.members, visitor, isTypeElement)); case SyntaxKind.ArrayType: - return factory.updateArrayTypeNode(node, - nodeVisitor((node).elementType, visitor, isTypeNode)); + Debug.type(node); + return factory.updateArrayTypeNode(node, + nodeVisitor(node.elementType, visitor, isTypeNode)); case SyntaxKind.TupleType: - return factory.updateTupleTypeNode((node), - nodesVisitor((node).elements, visitor, isTypeNode)); + Debug.type(node); + return factory.updateTupleTypeNode(node, + nodesVisitor(node.elements, visitor, isTypeNode)); case SyntaxKind.OptionalType: - return factory.updateOptionalTypeNode((node), - nodeVisitor((node).type, visitor, isTypeNode)); + Debug.type(node); + return factory.updateOptionalTypeNode(node, + nodeVisitor(node.type, visitor, isTypeNode)); case SyntaxKind.RestType: - return factory.updateRestTypeNode((node), - nodeVisitor((node).type, visitor, isTypeNode)); + Debug.type(node); + return factory.updateRestTypeNode(node, + nodeVisitor(node.type, visitor, isTypeNode)); case SyntaxKind.UnionType: - return factory.updateUnionTypeNode(node, - nodesVisitor((node).types, visitor, isTypeNode)); + Debug.type(node); + return factory.updateUnionTypeNode(node, + nodesVisitor(node.types, visitor, isTypeNode)); case SyntaxKind.IntersectionType: - return factory.updateIntersectionTypeNode(node, - nodesVisitor((node).types, visitor, isTypeNode)); + Debug.type(node); + return factory.updateIntersectionTypeNode(node, + nodesVisitor(node.types, visitor, isTypeNode)); case SyntaxKind.ConditionalType: - return factory.updateConditionalTypeNode(node, - nodeVisitor((node).checkType, visitor, isTypeNode), - nodeVisitor((node).extendsType, visitor, isTypeNode), - nodeVisitor((node).trueType, visitor, isTypeNode), - nodeVisitor((node).falseType, visitor, isTypeNode)); + Debug.type(node); + return factory.updateConditionalTypeNode(node, + nodeVisitor(node.checkType, visitor, isTypeNode), + nodeVisitor(node.extendsType, visitor, isTypeNode), + nodeVisitor(node.trueType, visitor, isTypeNode), + nodeVisitor(node.falseType, visitor, isTypeNode)); case SyntaxKind.InferType: - return factory.updateInferTypeNode(node, - nodeVisitor((node).typeParameter, visitor, isTypeParameterDeclaration)); + Debug.type(node); + return factory.updateInferTypeNode(node, + nodeVisitor(node.typeParameter, visitor, isTypeParameterDeclaration)); case SyntaxKind.ImportType: - return factory.updateImportTypeNode(node, - nodeVisitor((node).argument, visitor, isTypeNode), - nodeVisitor((node).qualifier, visitor, isEntityName), - visitNodes((node).typeArguments, visitor, isTypeNode), - (node).isTypeOf + Debug.type(node); + return factory.updateImportTypeNode(node, + nodeVisitor(node.argument, visitor, isTypeNode), + nodeVisitor(node.qualifier, visitor, isEntityName), + visitNodes(node.typeArguments, visitor, isTypeNode), + node.isTypeOf ); case SyntaxKind.NamedTupleMember: - return factory.updateNamedTupleMember(node, - visitNode((node).dotDotDotToken, visitor, isToken), - visitNode((node).name, visitor, isIdentifier), - visitNode((node).questionToken, visitor, isToken), - visitNode((node).type, visitor, isTypeNode), + Debug.type(node); + return factory.updateNamedTupleMember(node, + visitNode(node.dotDotDotToken, visitor, isDotDotDotToken), + visitNode(node.name, visitor, isIdentifier), + visitNode(node.questionToken, visitor, isQuestionToken), + visitNode(node.type, visitor, isTypeNode), ); case SyntaxKind.ParenthesizedType: - return factory.updateParenthesizedType(node, - nodeVisitor((node).type, visitor, isTypeNode)); + Debug.type(node); + return factory.updateParenthesizedType(node, + nodeVisitor(node.type, visitor, isTypeNode)); case SyntaxKind.TypeOperator: - return factory.updateTypeOperatorNode(node, - nodeVisitor((node).type, visitor, isTypeNode)); + Debug.type(node); + return factory.updateTypeOperatorNode(node, + nodeVisitor(node.type, visitor, isTypeNode)); case SyntaxKind.IndexedAccessType: - return factory.updateIndexedAccessTypeNode((node), - nodeVisitor((node).objectType, visitor, isTypeNode), - nodeVisitor((node).indexType, visitor, isTypeNode)); + Debug.type(node); + return factory.updateIndexedAccessTypeNode(node, + nodeVisitor(node.objectType, visitor, isTypeNode), + nodeVisitor(node.indexType, visitor, isTypeNode)); case SyntaxKind.MappedType: - return factory.updateMappedTypeNode((node), - nodeVisitor((node).readonlyToken, tokenVisitor, isToken), - nodeVisitor((node).typeParameter, visitor, isTypeParameterDeclaration), - nodeVisitor((node).nameType, visitor, isTypeNode), - nodeVisitor((node).questionToken, tokenVisitor, isToken), - nodeVisitor((node).type, visitor, isTypeNode)); + Debug.type(node); + return factory.updateMappedTypeNode(node, + nodeVisitor(node.readonlyToken, tokenVisitor, isReadonlyKeywordOrPlusOrMinusToken), + nodeVisitor(node.typeParameter, visitor, isTypeParameterDeclaration), + nodeVisitor(node.nameType, visitor, isTypeNode), + nodeVisitor(node.questionToken, tokenVisitor, isQuestionOrPlusOrMinusToken), + nodeVisitor(node.type, visitor, isTypeNode)); case SyntaxKind.LiteralType: - return factory.updateLiteralTypeNode(node, - nodeVisitor((node).literal, visitor, isExpression)); + Debug.type(node); + return factory.updateLiteralTypeNode(node, + nodeVisitor(node.literal, visitor, isExpression)); case SyntaxKind.TemplateLiteralType: - return factory.updateTemplateLiteralType(node, - nodeVisitor((node).head, visitor, isTemplateHead), - nodesVisitor((node).templateSpans, visitor, isTemplateLiteralTypeSpan)); + Debug.type(node); + return factory.updateTemplateLiteralType(node, + nodeVisitor(node.head, visitor, isTemplateHead), + nodesVisitor(node.templateSpans, visitor, isTemplateLiteralTypeSpan)); case SyntaxKind.TemplateLiteralTypeSpan: - return factory.updateTemplateLiteralTypeSpan(node, - nodeVisitor((node).type, visitor, isTypeNode), - nodeVisitor((node).literal, visitor, isTemplateMiddleOrTemplateTail)); + Debug.type(node); + return factory.updateTemplateLiteralTypeSpan(node, + nodeVisitor(node.type, visitor, isTypeNode), + nodeVisitor(node.literal, visitor, isTemplateMiddleOrTemplateTail)); // Binding patterns case SyntaxKind.ObjectBindingPattern: - return factory.updateObjectBindingPattern(node, - nodesVisitor((node).elements, visitor, isBindingElement)); + Debug.type(node); + return factory.updateObjectBindingPattern(node, + nodesVisitor(node.elements, visitor, isBindingElement)); case SyntaxKind.ArrayBindingPattern: - return factory.updateArrayBindingPattern(node, - nodesVisitor((node).elements, visitor, isArrayBindingElement)); + Debug.type(node); + return factory.updateArrayBindingPattern(node, + nodesVisitor(node.elements, visitor, isArrayBindingElement)); case SyntaxKind.BindingElement: - return factory.updateBindingElement(node, - nodeVisitor((node).dotDotDotToken, tokenVisitor, isToken), - nodeVisitor((node).propertyName, visitor, isPropertyName), - nodeVisitor((node).name, visitor, isBindingName), - nodeVisitor((node).initializer, visitor, isExpression)); + Debug.type(node); + return factory.updateBindingElement(node, + nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken), + nodeVisitor(node.propertyName, visitor, isPropertyName), + nodeVisitor(node.name, visitor, isBindingName), + nodeVisitor(node.initializer, visitor, isExpression)); // Expression case SyntaxKind.ArrayLiteralExpression: - return factory.updateArrayLiteralExpression(node, - nodesVisitor((node).elements, visitor, isExpression)); + Debug.type(node); + return factory.updateArrayLiteralExpression(node, + nodesVisitor(node.elements, visitor, isExpression)); case SyntaxKind.ObjectLiteralExpression: - return factory.updateObjectLiteralExpression(node, - nodesVisitor((node).properties, visitor, isObjectLiteralElementLike)); + Debug.type(node); + return factory.updateObjectLiteralExpression(node, + nodesVisitor(node.properties, visitor, isObjectLiteralElementLike)); case SyntaxKind.PropertyAccessExpression: if (node.flags & NodeFlags.OptionalChain) { - return factory.updatePropertyAccessChain(node, - nodeVisitor((node).expression, visitor, isExpression), - nodeVisitor((node).questionDotToken, tokenVisitor, isToken), - nodeVisitor((node).name, visitor, isIdentifier)); + Debug.type(node); + return factory.updatePropertyAccessChain(node, + nodeVisitor(node.expression, visitor, isExpression), + nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken), + nodeVisitor(node.name, visitor, isMemberName)); } - return factory.updatePropertyAccessExpression(node, - nodeVisitor((node).expression, visitor, isExpression), - nodeVisitor((node).name, visitor, isIdentifierOrPrivateIdentifier)); + Debug.type(node); + return factory.updatePropertyAccessExpression(node, + nodeVisitor(node.expression, visitor, isExpression), + nodeVisitor(node.name, visitor, isMemberName)); case SyntaxKind.ElementAccessExpression: if (node.flags & NodeFlags.OptionalChain) { - return factory.updateElementAccessChain(node, - nodeVisitor((node).expression, visitor, isExpression), - nodeVisitor((node).questionDotToken, tokenVisitor, isToken), - nodeVisitor((node).argumentExpression, visitor, isExpression)); + Debug.type(node); + return factory.updateElementAccessChain(node, + nodeVisitor(node.expression, visitor, isExpression), + nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken), + nodeVisitor(node.argumentExpression, visitor, isExpression)); } - return factory.updateElementAccessExpression(node, - nodeVisitor((node).expression, visitor, isExpression), - nodeVisitor((node).argumentExpression, visitor, isExpression)); + Debug.type(node); + return factory.updateElementAccessExpression(node, + nodeVisitor(node.expression, visitor, isExpression), + nodeVisitor(node.argumentExpression, visitor, isExpression)); case SyntaxKind.CallExpression: if (node.flags & NodeFlags.OptionalChain) { - return factory.updateCallChain(node, - nodeVisitor((node).expression, visitor, isExpression), - nodeVisitor((node).questionDotToken, tokenVisitor, isToken), - nodesVisitor((node).typeArguments, visitor, isTypeNode), - nodesVisitor((node).arguments, visitor, isExpression)); + Debug.type(node); + return factory.updateCallChain(node, + nodeVisitor(node.expression, visitor, isExpression), + nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken), + nodesVisitor(node.typeArguments, visitor, isTypeNode), + nodesVisitor(node.arguments, visitor, isExpression)); } - return factory.updateCallExpression(node, - nodeVisitor((node).expression, visitor, isExpression), - nodesVisitor((node).typeArguments, visitor, isTypeNode), - nodesVisitor((node).arguments, visitor, isExpression)); + Debug.type(node); + return factory.updateCallExpression(node, + nodeVisitor(node.expression, visitor, isExpression), + nodesVisitor(node.typeArguments, visitor, isTypeNode), + nodesVisitor(node.arguments, visitor, isExpression)); case SyntaxKind.NewExpression: - return factory.updateNewExpression(node, - nodeVisitor((node).expression, visitor, isExpression), - nodesVisitor((node).typeArguments, visitor, isTypeNode), - nodesVisitor((node).arguments, visitor, isExpression)); + Debug.type(node); + return factory.updateNewExpression(node, + nodeVisitor(node.expression, visitor, isExpression), + nodesVisitor(node.typeArguments, visitor, isTypeNode), + nodesVisitor(node.arguments, visitor, isExpression)); case SyntaxKind.TaggedTemplateExpression: - return factory.updateTaggedTemplateExpression(node, - nodeVisitor((node).tag, visitor, isExpression), - visitNodes((node).typeArguments, visitor, isExpression), - nodeVisitor((node).template, visitor, isTemplateLiteral)); + Debug.type(node); + return factory.updateTaggedTemplateExpression(node, + nodeVisitor(node.tag, visitor, isExpression), + visitNodes(node.typeArguments, visitor, isTypeNode), + nodeVisitor(node.template, visitor, isTemplateLiteral)); case SyntaxKind.TypeAssertionExpression: - return factory.updateTypeAssertion(node, - nodeVisitor((node).type, visitor, isTypeNode), - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateTypeAssertion(node, + nodeVisitor(node.type, visitor, isTypeNode), + nodeVisitor(node.expression, visitor, isExpression)); case SyntaxKind.ParenthesizedExpression: - return factory.updateParenthesizedExpression(node, - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateParenthesizedExpression(node, + nodeVisitor(node.expression, visitor, isExpression)); case SyntaxKind.FunctionExpression: - return factory.updateFunctionExpression(node, - nodesVisitor((node).modifiers, visitor, isModifier), - nodeVisitor((node).asteriskToken, tokenVisitor, isToken), - nodeVisitor((node).name, visitor, isIdentifier), - nodesVisitor((node).typeParameters, visitor, isTypeParameterDeclaration), - visitParameterList((node).parameters, visitor, context, nodesVisitor), - nodeVisitor((node).type, visitor, isTypeNode), - visitFunctionBody((node).body, visitor, context, nodeVisitor)); + Debug.type(node); + return factory.updateFunctionExpression(node, + nodesVisitor(node.modifiers, visitor, isModifier), + nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken), + nodeVisitor(node.name, visitor, isIdentifier), + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + visitParameterList(node.parameters, visitor, context, nodesVisitor), + nodeVisitor(node.type, visitor, isTypeNode), + visitFunctionBody(node.body, visitor, context, nodeVisitor)); case SyntaxKind.ArrowFunction: - return factory.updateArrowFunction(node, - nodesVisitor((node).modifiers, visitor, isModifier), - nodesVisitor((node).typeParameters, visitor, isTypeParameterDeclaration), - visitParameterList((node).parameters, visitor, context, nodesVisitor), - nodeVisitor((node).type, visitor, isTypeNode), - nodeVisitor((node).equalsGreaterThanToken, tokenVisitor, isToken), - visitFunctionBody((node).body, visitor, context, nodeVisitor)); + Debug.type(node); + return factory.updateArrowFunction(node, + nodesVisitor(node.modifiers, visitor, isModifier), + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + visitParameterList(node.parameters, visitor, context, nodesVisitor), + nodeVisitor(node.type, visitor, isTypeNode), + nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, isEqualsGreaterThanToken), + visitFunctionBody(node.body, visitor, context, nodeVisitor)); case SyntaxKind.DeleteExpression: - return factory.updateDeleteExpression(node, - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateDeleteExpression(node, + nodeVisitor(node.expression, visitor, isExpression)); case SyntaxKind.TypeOfExpression: - return factory.updateTypeOfExpression(node, - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateTypeOfExpression(node, + nodeVisitor(node.expression, visitor, isExpression)); case SyntaxKind.VoidExpression: - return factory.updateVoidExpression(node, - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateVoidExpression(node, + nodeVisitor(node.expression, visitor, isExpression)); case SyntaxKind.AwaitExpression: - return factory.updateAwaitExpression(node, - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateAwaitExpression(node, + nodeVisitor(node.expression, visitor, isExpression)); case SyntaxKind.PrefixUnaryExpression: - return factory.updatePrefixUnaryExpression(node, - nodeVisitor((node).operand, visitor, isExpression)); + Debug.type(node); + return factory.updatePrefixUnaryExpression(node, + nodeVisitor(node.operand, visitor, isExpression)); case SyntaxKind.PostfixUnaryExpression: - return factory.updatePostfixUnaryExpression(node, - nodeVisitor((node).operand, visitor, isExpression)); + Debug.type(node); + return factory.updatePostfixUnaryExpression(node, + nodeVisitor(node.operand, visitor, isExpression)); case SyntaxKind.BinaryExpression: - return factory.updateBinaryExpression(node, - nodeVisitor((node).left, visitor, isExpression), - nodeVisitor((node).operatorToken, tokenVisitor, isToken), - nodeVisitor((node).right, visitor, isExpression)); + Debug.type(node); + return factory.updateBinaryExpression(node, + nodeVisitor(node.left, visitor, isExpression), + nodeVisitor(node.operatorToken, tokenVisitor, isBinaryOperatorToken), + nodeVisitor(node.right, visitor, isExpression)); case SyntaxKind.ConditionalExpression: - return factory.updateConditionalExpression(node, - nodeVisitor((node).condition, visitor, isExpression), - nodeVisitor((node).questionToken, tokenVisitor, isToken), - nodeVisitor((node).whenTrue, visitor, isExpression), - nodeVisitor((node).colonToken, tokenVisitor, isToken), - nodeVisitor((node).whenFalse, visitor, isExpression)); + Debug.type(node); + return factory.updateConditionalExpression(node, + nodeVisitor(node.condition, visitor, isExpression), + nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken), + nodeVisitor(node.whenTrue, visitor, isExpression), + nodeVisitor(node.colonToken, tokenVisitor, isColonToken), + nodeVisitor(node.whenFalse, visitor, isExpression)); case SyntaxKind.TemplateExpression: - return factory.updateTemplateExpression(node, - nodeVisitor((node).head, visitor, isTemplateHead), - nodesVisitor((node).templateSpans, visitor, isTemplateSpan)); + Debug.type(node); + return factory.updateTemplateExpression(node, + nodeVisitor(node.head, visitor, isTemplateHead), + nodesVisitor(node.templateSpans, visitor, isTemplateSpan)); case SyntaxKind.YieldExpression: - return factory.updateYieldExpression(node, - nodeVisitor((node).asteriskToken, tokenVisitor, isToken), - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateYieldExpression(node, + nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken), + nodeVisitor(node.expression, visitor, isExpression)); case SyntaxKind.SpreadElement: - return factory.updateSpreadElement(node, - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateSpreadElement(node, + nodeVisitor(node.expression, visitor, isExpression)); case SyntaxKind.ClassExpression: - return factory.updateClassExpression(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - nodeVisitor((node).name, visitor, isIdentifier), - nodesVisitor((node).typeParameters, visitor, isTypeParameterDeclaration), - nodesVisitor((node).heritageClauses, visitor, isHeritageClause), - nodesVisitor((node).members, visitor, isClassElement)); + Debug.type(node); + return factory.updateClassExpression(node, + nodesVisitor(node.decorators, visitor, isDecorator), + nodesVisitor(node.modifiers, visitor, isModifier), + nodeVisitor(node.name, visitor, isIdentifier), + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + nodesVisitor(node.heritageClauses, visitor, isHeritageClause), + nodesVisitor(node.members, visitor, isClassElement)); case SyntaxKind.ExpressionWithTypeArguments: - return factory.updateExpressionWithTypeArguments(node, - nodeVisitor((node).expression, visitor, isExpression), - nodesVisitor((node).typeArguments, visitor, isTypeNode)); + Debug.type(node); + return factory.updateExpressionWithTypeArguments(node, + nodeVisitor(node.expression, visitor, isExpression), + nodesVisitor(node.typeArguments, visitor, isTypeNode)); case SyntaxKind.AsExpression: - return factory.updateAsExpression(node, - nodeVisitor((node).expression, visitor, isExpression), - nodeVisitor((node).type, visitor, isTypeNode)); + Debug.type(node); + return factory.updateAsExpression(node, + nodeVisitor(node.expression, visitor, isExpression), + nodeVisitor(node.type, visitor, isTypeNode)); case SyntaxKind.NonNullExpression: if (node.flags & NodeFlags.OptionalChain) { - return factory.updateNonNullChain(node, - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateNonNullChain(node, + nodeVisitor(node.expression, visitor, isExpression)); } - return factory.updateNonNullExpression(node, - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateNonNullExpression(node, + nodeVisitor(node.expression, visitor, isExpression)); case SyntaxKind.MetaProperty: - return factory.updateMetaProperty(node, - nodeVisitor((node).name, visitor, isIdentifier)); + Debug.type(node); + return factory.updateMetaProperty(node, + nodeVisitor(node.name, visitor, isIdentifier)); // Misc case SyntaxKind.TemplateSpan: - return factory.updateTemplateSpan(node, - nodeVisitor((node).expression, visitor, isExpression), - nodeVisitor((node).literal, visitor, isTemplateMiddleOrTemplateTail)); + Debug.type(node); + return factory.updateTemplateSpan(node, + nodeVisitor(node.expression, visitor, isExpression), + nodeVisitor(node.literal, visitor, isTemplateMiddleOrTemplateTail)); // Element case SyntaxKind.Block: - return factory.updateBlock(node, - nodesVisitor((node).statements, visitor, isStatement)); + Debug.type(node); + return factory.updateBlock(node, + nodesVisitor(node.statements, visitor, isStatement)); case SyntaxKind.VariableStatement: - return factory.updateVariableStatement(node, - nodesVisitor((node).modifiers, visitor, isModifier), - nodeVisitor((node).declarationList, visitor, isVariableDeclarationList)); + Debug.type(node); + return factory.updateVariableStatement(node, + nodesVisitor(node.modifiers, visitor, isModifier), + nodeVisitor(node.declarationList, visitor, isVariableDeclarationList)); case SyntaxKind.ExpressionStatement: - return factory.updateExpressionStatement(node, - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateExpressionStatement(node, + nodeVisitor(node.expression, visitor, isExpression)); case SyntaxKind.IfStatement: - return factory.updateIfStatement(node, - nodeVisitor((node).expression, visitor, isExpression), - nodeVisitor((node).thenStatement, visitor, isStatement, factory.liftToBlock), - nodeVisitor((node).elseStatement, visitor, isStatement, factory.liftToBlock)); + Debug.type(node); + return factory.updateIfStatement(node, + nodeVisitor(node.expression, visitor, isExpression), + nodeVisitor(node.thenStatement, visitor, isStatement, factory.liftToBlock), + nodeVisitor(node.elseStatement, visitor, isStatement, factory.liftToBlock)); case SyntaxKind.DoStatement: - return factory.updateDoStatement(node, - nodeVisitor((node).statement, visitor, isStatement, factory.liftToBlock), - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateDoStatement(node, + visitIterationBody(node.statement, visitor, context), + nodeVisitor(node.expression, visitor, isExpression)); case SyntaxKind.WhileStatement: - return factory.updateWhileStatement(node, - nodeVisitor((node).expression, visitor, isExpression), - nodeVisitor((node).statement, visitor, isStatement, factory.liftToBlock)); + Debug.type(node); + return factory.updateWhileStatement(node, + nodeVisitor(node.expression, visitor, isExpression), + visitIterationBody(node.statement, visitor, context)); case SyntaxKind.ForStatement: - return factory.updateForStatement(node, - nodeVisitor((node).initializer, visitor, isForInitializer), - nodeVisitor((node).condition, visitor, isExpression), - nodeVisitor((node).incrementor, visitor, isExpression), - nodeVisitor((node).statement, visitor, isStatement, factory.liftToBlock)); + Debug.type(node); + return factory.updateForStatement(node, + nodeVisitor(node.initializer, visitor, isForInitializer), + nodeVisitor(node.condition, visitor, isExpression), + nodeVisitor(node.incrementor, visitor, isExpression), + visitIterationBody(node.statement, visitor, context)); case SyntaxKind.ForInStatement: - return factory.updateForInStatement(node, - nodeVisitor((node).initializer, visitor, isForInitializer), - nodeVisitor((node).expression, visitor, isExpression), - nodeVisitor((node).statement, visitor, isStatement, factory.liftToBlock)); + Debug.type(node); + return factory.updateForInStatement(node, + nodeVisitor(node.initializer, visitor, isForInitializer), + nodeVisitor(node.expression, visitor, isExpression), + visitIterationBody(node.statement, visitor, context)); case SyntaxKind.ForOfStatement: - return factory.updateForOfStatement(node, - nodeVisitor((node).awaitModifier, tokenVisitor, isToken), - nodeVisitor((node).initializer, visitor, isForInitializer), - nodeVisitor((node).expression, visitor, isExpression), - nodeVisitor((node).statement, visitor, isStatement, factory.liftToBlock)); + Debug.type(node); + return factory.updateForOfStatement(node, + nodeVisitor(node.awaitModifier, tokenVisitor, isAwaitKeyword), + nodeVisitor(node.initializer, visitor, isForInitializer), + nodeVisitor(node.expression, visitor, isExpression), + visitIterationBody(node.statement, visitor, context)); case SyntaxKind.ContinueStatement: - return factory.updateContinueStatement(node, - nodeVisitor((node).label, visitor, isIdentifier)); + Debug.type(node); + return factory.updateContinueStatement(node, + nodeVisitor(node.label, visitor, isIdentifier)); case SyntaxKind.BreakStatement: - return factory.updateBreakStatement(node, - nodeVisitor((node).label, visitor, isIdentifier)); + Debug.type(node); + return factory.updateBreakStatement(node, + nodeVisitor(node.label, visitor, isIdentifier)); case SyntaxKind.ReturnStatement: - return factory.updateReturnStatement(node, - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateReturnStatement(node, + nodeVisitor(node.expression, visitor, isExpression)); case SyntaxKind.WithStatement: - return factory.updateWithStatement(node, - nodeVisitor((node).expression, visitor, isExpression), - nodeVisitor((node).statement, visitor, isStatement, factory.liftToBlock)); + Debug.type(node); + return factory.updateWithStatement(node, + nodeVisitor(node.expression, visitor, isExpression), + nodeVisitor(node.statement, visitor, isStatement, factory.liftToBlock)); case SyntaxKind.SwitchStatement: - return factory.updateSwitchStatement(node, - nodeVisitor((node).expression, visitor, isExpression), - nodeVisitor((node).caseBlock, visitor, isCaseBlock)); + Debug.type(node); + return factory.updateSwitchStatement(node, + nodeVisitor(node.expression, visitor, isExpression), + nodeVisitor(node.caseBlock, visitor, isCaseBlock)); case SyntaxKind.LabeledStatement: - return factory.updateLabeledStatement(node, - nodeVisitor((node).label, visitor, isIdentifier), - nodeVisitor((node).statement, visitor, isStatement, factory.liftToBlock)); + Debug.type(node); + return factory.updateLabeledStatement(node, + nodeVisitor(node.label, visitor, isIdentifier), + nodeVisitor(node.statement, visitor, isStatement, factory.liftToBlock)); case SyntaxKind.ThrowStatement: - return factory.updateThrowStatement(node, - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateThrowStatement(node, + nodeVisitor(node.expression, visitor, isExpression)); case SyntaxKind.TryStatement: - return factory.updateTryStatement(node, - nodeVisitor((node).tryBlock, visitor, isBlock), - nodeVisitor((node).catchClause, visitor, isCatchClause), - nodeVisitor((node).finallyBlock, visitor, isBlock)); + Debug.type(node); + return factory.updateTryStatement(node, + nodeVisitor(node.tryBlock, visitor, isBlock), + nodeVisitor(node.catchClause, visitor, isCatchClause), + nodeVisitor(node.finallyBlock, visitor, isBlock)); case SyntaxKind.VariableDeclaration: - return factory.updateVariableDeclaration(node, - nodeVisitor((node).name, visitor, isBindingName), - nodeVisitor((node).exclamationToken, tokenVisitor, isToken), - nodeVisitor((node).type, visitor, isTypeNode), - nodeVisitor((node).initializer, visitor, isExpression)); + Debug.type(node); + return factory.updateVariableDeclaration(node, + nodeVisitor(node.name, visitor, isBindingName), + nodeVisitor(node.exclamationToken, tokenVisitor, isExclamationToken), + nodeVisitor(node.type, visitor, isTypeNode), + nodeVisitor(node.initializer, visitor, isExpression)); case SyntaxKind.VariableDeclarationList: - return factory.updateVariableDeclarationList(node, - nodesVisitor((node).declarations, visitor, isVariableDeclaration)); + Debug.type(node); + return factory.updateVariableDeclarationList(node, + nodesVisitor(node.declarations, visitor, isVariableDeclaration)); case SyntaxKind.FunctionDeclaration: - return factory.updateFunctionDeclaration(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - nodeVisitor((node).asteriskToken, tokenVisitor, isToken), - nodeVisitor((node).name, visitor, isIdentifier), - nodesVisitor((node).typeParameters, visitor, isTypeParameterDeclaration), - visitParameterList((node).parameters, visitor, context, nodesVisitor), - nodeVisitor((node).type, visitor, isTypeNode), - visitFunctionBody((node).body, visitor, context, nodeVisitor)); + Debug.type(node); + return factory.updateFunctionDeclaration(node, + nodesVisitor(node.decorators, visitor, isDecorator), + nodesVisitor(node.modifiers, visitor, isModifier), + nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken), + nodeVisitor(node.name, visitor, isIdentifier), + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + visitParameterList(node.parameters, visitor, context, nodesVisitor), + nodeVisitor(node.type, visitor, isTypeNode), + visitFunctionBody(node.body, visitor, context, nodeVisitor)); case SyntaxKind.ClassDeclaration: - return factory.updateClassDeclaration(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - nodeVisitor((node).name, visitor, isIdentifier), - nodesVisitor((node).typeParameters, visitor, isTypeParameterDeclaration), - nodesVisitor((node).heritageClauses, visitor, isHeritageClause), - nodesVisitor((node).members, visitor, isClassElement)); + Debug.type(node); + return factory.updateClassDeclaration(node, + nodesVisitor(node.decorators, visitor, isDecorator), + nodesVisitor(node.modifiers, visitor, isModifier), + nodeVisitor(node.name, visitor, isIdentifier), + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + nodesVisitor(node.heritageClauses, visitor, isHeritageClause), + nodesVisitor(node.members, visitor, isClassElement)); case SyntaxKind.InterfaceDeclaration: - return factory.updateInterfaceDeclaration(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - nodeVisitor((node).name, visitor, isIdentifier), - nodesVisitor((node).typeParameters, visitor, isTypeParameterDeclaration), - nodesVisitor((node).heritageClauses, visitor, isHeritageClause), - nodesVisitor((node).members, visitor, isTypeElement)); + Debug.type(node); + return factory.updateInterfaceDeclaration(node, + nodesVisitor(node.decorators, visitor, isDecorator), + nodesVisitor(node.modifiers, visitor, isModifier), + nodeVisitor(node.name, visitor, isIdentifier), + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + nodesVisitor(node.heritageClauses, visitor, isHeritageClause), + nodesVisitor(node.members, visitor, isTypeElement)); case SyntaxKind.TypeAliasDeclaration: - return factory.updateTypeAliasDeclaration(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - nodeVisitor((node).name, visitor, isIdentifier), - nodesVisitor((node).typeParameters, visitor, isTypeParameterDeclaration), - nodeVisitor((node).type, visitor, isTypeNode)); + Debug.type(node); + return factory.updateTypeAliasDeclaration(node, + nodesVisitor(node.decorators, visitor, isDecorator), + nodesVisitor(node.modifiers, visitor, isModifier), + nodeVisitor(node.name, visitor, isIdentifier), + nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), + nodeVisitor(node.type, visitor, isTypeNode)); case SyntaxKind.EnumDeclaration: - return factory.updateEnumDeclaration(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - nodeVisitor((node).name, visitor, isIdentifier), - nodesVisitor((node).members, visitor, isEnumMember)); + Debug.type(node); + return factory.updateEnumDeclaration(node, + nodesVisitor(node.decorators, visitor, isDecorator), + nodesVisitor(node.modifiers, visitor, isModifier), + nodeVisitor(node.name, visitor, isIdentifier), + nodesVisitor(node.members, visitor, isEnumMember)); case SyntaxKind.ModuleDeclaration: - return factory.updateModuleDeclaration(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - nodeVisitor((node).name, visitor, isIdentifier), - nodeVisitor((node).body, visitor, isModuleBody)); + Debug.type(node); + return factory.updateModuleDeclaration(node, + nodesVisitor(node.decorators, visitor, isDecorator), + nodesVisitor(node.modifiers, visitor, isModifier), + nodeVisitor(node.name, visitor, isModuleName), + nodeVisitor(node.body, visitor, isModuleBody)); case SyntaxKind.ModuleBlock: - return factory.updateModuleBlock(node, - nodesVisitor((node).statements, visitor, isStatement)); + Debug.type(node); + return factory.updateModuleBlock(node, + nodesVisitor(node.statements, visitor, isStatement)); case SyntaxKind.CaseBlock: - return factory.updateCaseBlock(node, - nodesVisitor((node).clauses, visitor, isCaseOrDefaultClause)); + Debug.type(node); + return factory.updateCaseBlock(node, + nodesVisitor(node.clauses, visitor, isCaseOrDefaultClause)); case SyntaxKind.NamespaceExportDeclaration: - return factory.updateNamespaceExportDeclaration(node, - nodeVisitor((node).name, visitor, isIdentifier)); + Debug.type(node); + return factory.updateNamespaceExportDeclaration(node, + nodeVisitor(node.name, visitor, isIdentifier)); case SyntaxKind.ImportEqualsDeclaration: - return factory.updateImportEqualsDeclaration(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - (node).isTypeOnly, - nodeVisitor((node).name, visitor, isIdentifier), - nodeVisitor((node).moduleReference, visitor, isModuleReference)); + Debug.type(node); + return factory.updateImportEqualsDeclaration(node, + nodesVisitor(node.decorators, visitor, isDecorator), + nodesVisitor(node.modifiers, visitor, isModifier), + node.isTypeOnly, + nodeVisitor(node.name, visitor, isIdentifier), + nodeVisitor(node.moduleReference, visitor, isModuleReference)); case SyntaxKind.ImportDeclaration: - return factory.updateImportDeclaration(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - nodeVisitor((node).importClause, visitor, isImportClause), - nodeVisitor((node).moduleSpecifier, visitor, isExpression)); + Debug.type(node); + return factory.updateImportDeclaration(node, + nodesVisitor(node.decorators, visitor, isDecorator), + nodesVisitor(node.modifiers, visitor, isModifier), + nodeVisitor(node.importClause, visitor, isImportClause), + nodeVisitor(node.moduleSpecifier, visitor, isExpression)); case SyntaxKind.ImportClause: - return factory.updateImportClause(node, - (node).isTypeOnly, - nodeVisitor((node).name, visitor, isIdentifier), - nodeVisitor((node).namedBindings, visitor, isNamedImportBindings)); + Debug.type(node); + return factory.updateImportClause(node, + node.isTypeOnly, + nodeVisitor(node.name, visitor, isIdentifier), + nodeVisitor(node.namedBindings, visitor, isNamedImportBindings)); case SyntaxKind.NamespaceImport: - return factory.updateNamespaceImport(node, - nodeVisitor((node).name, visitor, isIdentifier)); + Debug.type(node); + return factory.updateNamespaceImport(node, + nodeVisitor(node.name, visitor, isIdentifier)); case SyntaxKind.NamespaceExport: - return factory.updateNamespaceExport(node, - nodeVisitor((node).name, visitor, isIdentifier)); + Debug.type(node); + return factory.updateNamespaceExport(node, + nodeVisitor(node.name, visitor, isIdentifier)); case SyntaxKind.NamedImports: - return factory.updateNamedImports(node, - nodesVisitor((node).elements, visitor, isImportSpecifier)); + Debug.type(node); + return factory.updateNamedImports(node, + nodesVisitor(node.elements, visitor, isImportSpecifier)); case SyntaxKind.ImportSpecifier: - return factory.updateImportSpecifier(node, - nodeVisitor((node).propertyName, visitor, isIdentifier), - nodeVisitor((node).name, visitor, isIdentifier)); + Debug.type(node); + return factory.updateImportSpecifier(node, + nodeVisitor(node.propertyName, visitor, isIdentifier), + nodeVisitor(node.name, visitor, isIdentifier)); case SyntaxKind.ExportAssignment: - return factory.updateExportAssignment(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateExportAssignment(node, + nodesVisitor(node.decorators, visitor, isDecorator), + nodesVisitor(node.modifiers, visitor, isModifier), + nodeVisitor(node.expression, visitor, isExpression)); case SyntaxKind.ExportDeclaration: - return factory.updateExportDeclaration(node, - nodesVisitor((node).decorators, visitor, isDecorator), - nodesVisitor((node).modifiers, visitor, isModifier), - (node).isTypeOnly, - nodeVisitor((node).exportClause, visitor, isNamedExportBindings), - nodeVisitor((node).moduleSpecifier, visitor, isExpression)); + Debug.type(node); + return factory.updateExportDeclaration(node, + nodesVisitor(node.decorators, visitor, isDecorator), + nodesVisitor(node.modifiers, visitor, isModifier), + node.isTypeOnly, + nodeVisitor(node.exportClause, visitor, isNamedExportBindings), + nodeVisitor(node.moduleSpecifier, visitor, isExpression)); case SyntaxKind.NamedExports: - return factory.updateNamedExports(node, - nodesVisitor((node).elements, visitor, isExportSpecifier)); + Debug.type(node); + return factory.updateNamedExports(node, + nodesVisitor(node.elements, visitor, isExportSpecifier)); case SyntaxKind.ExportSpecifier: - return factory.updateExportSpecifier(node, - nodeVisitor((node).propertyName, visitor, isIdentifier), - nodeVisitor((node).name, visitor, isIdentifier)); + Debug.type(node); + return factory.updateExportSpecifier(node, + nodeVisitor(node.propertyName, visitor, isIdentifier), + nodeVisitor(node.name, visitor, isIdentifier)); // Module references case SyntaxKind.ExternalModuleReference: - return factory.updateExternalModuleReference(node, - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateExternalModuleReference(node, + nodeVisitor(node.expression, visitor, isExpression)); // JSX case SyntaxKind.JsxElement: - return factory.updateJsxElement(node, - nodeVisitor((node).openingElement, visitor, isJsxOpeningElement), - nodesVisitor((node).children, visitor, isJsxChild), - nodeVisitor((node).closingElement, visitor, isJsxClosingElement)); + Debug.type(node); + return factory.updateJsxElement(node, + nodeVisitor(node.openingElement, visitor, isJsxOpeningElement), + nodesVisitor(node.children, visitor, isJsxChild), + nodeVisitor(node.closingElement, visitor, isJsxClosingElement)); case SyntaxKind.JsxSelfClosingElement: - return factory.updateJsxSelfClosingElement(node, - nodeVisitor((node).tagName, visitor, isJsxTagNameExpression), - nodesVisitor((node).typeArguments, visitor, isTypeNode), - nodeVisitor((node).attributes, visitor, isJsxAttributes)); + Debug.type(node); + return factory.updateJsxSelfClosingElement(node, + nodeVisitor(node.tagName, visitor, isJsxTagNameExpression), + nodesVisitor(node.typeArguments, visitor, isTypeNode), + nodeVisitor(node.attributes, visitor, isJsxAttributes)); case SyntaxKind.JsxOpeningElement: - return factory.updateJsxOpeningElement(node, - nodeVisitor((node).tagName, visitor, isJsxTagNameExpression), - nodesVisitor((node).typeArguments, visitor, isTypeNode), - nodeVisitor((node).attributes, visitor, isJsxAttributes)); + Debug.type(node); + return factory.updateJsxOpeningElement(node, + nodeVisitor(node.tagName, visitor, isJsxTagNameExpression), + nodesVisitor(node.typeArguments, visitor, isTypeNode), + nodeVisitor(node.attributes, visitor, isJsxAttributes)); case SyntaxKind.JsxClosingElement: - return factory.updateJsxClosingElement(node, - nodeVisitor((node).tagName, visitor, isJsxTagNameExpression)); + Debug.type(node); + return factory.updateJsxClosingElement(node, + nodeVisitor(node.tagName, visitor, isJsxTagNameExpression)); case SyntaxKind.JsxFragment: - return factory.updateJsxFragment(node, - nodeVisitor((node).openingFragment, visitor, isJsxOpeningFragment), - nodesVisitor((node).children, visitor, isJsxChild), - nodeVisitor((node).closingFragment, visitor, isJsxClosingFragment)); + Debug.type(node); + return factory.updateJsxFragment(node, + nodeVisitor(node.openingFragment, visitor, isJsxOpeningFragment), + nodesVisitor(node.children, visitor, isJsxChild), + nodeVisitor(node.closingFragment, visitor, isJsxClosingFragment)); case SyntaxKind.JsxAttribute: - return factory.updateJsxAttribute(node, - nodeVisitor((node).name, visitor, isIdentifier), - nodeVisitor((node).initializer, visitor, isStringLiteralOrJsxExpression)); + Debug.type(node); + return factory.updateJsxAttribute(node, + nodeVisitor(node.name, visitor, isIdentifier), + nodeVisitor(node.initializer, visitor, isStringLiteralOrJsxExpression)); case SyntaxKind.JsxAttributes: - return factory.updateJsxAttributes(node, - nodesVisitor((node).properties, visitor, isJsxAttributeLike)); + Debug.type(node); + return factory.updateJsxAttributes(node, + nodesVisitor(node.properties, visitor, isJsxAttributeLike)); case SyntaxKind.JsxSpreadAttribute: - return factory.updateJsxSpreadAttribute(node, - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateJsxSpreadAttribute(node, + nodeVisitor(node.expression, visitor, isExpression)); case SyntaxKind.JsxExpression: - return factory.updateJsxExpression(node, - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateJsxExpression(node, + nodeVisitor(node.expression, visitor, isExpression)); // Clauses case SyntaxKind.CaseClause: - return factory.updateCaseClause(node, - nodeVisitor((node).expression, visitor, isExpression), - nodesVisitor((node).statements, visitor, isStatement)); + Debug.type(node); + return factory.updateCaseClause(node, + nodeVisitor(node.expression, visitor, isExpression), + nodesVisitor(node.statements, visitor, isStatement)); case SyntaxKind.DefaultClause: - return factory.updateDefaultClause(node, - nodesVisitor((node).statements, visitor, isStatement)); + Debug.type(node); + return factory.updateDefaultClause(node, + nodesVisitor(node.statements, visitor, isStatement)); case SyntaxKind.HeritageClause: - return factory.updateHeritageClause(node, - nodesVisitor((node).types, visitor, isExpressionWithTypeArguments)); + Debug.type(node); + return factory.updateHeritageClause(node, + nodesVisitor(node.types, visitor, isExpressionWithTypeArguments)); case SyntaxKind.CatchClause: - return factory.updateCatchClause(node, - nodeVisitor((node).variableDeclaration, visitor, isVariableDeclaration), - nodeVisitor((node).block, visitor, isBlock)); + Debug.type(node); + return factory.updateCatchClause(node, + nodeVisitor(node.variableDeclaration, visitor, isVariableDeclaration), + nodeVisitor(node.block, visitor, isBlock)); // Property assignments case SyntaxKind.PropertyAssignment: - return factory.updatePropertyAssignment(node, - nodeVisitor((node).name, visitor, isPropertyName), - nodeVisitor((node).initializer, visitor, isExpression)); + Debug.type(node); + return factory.updatePropertyAssignment(node, + nodeVisitor(node.name, visitor, isPropertyName), + nodeVisitor(node.initializer, visitor, isExpression)); case SyntaxKind.ShorthandPropertyAssignment: - return factory.updateShorthandPropertyAssignment(node, - nodeVisitor((node).name, visitor, isIdentifier), - nodeVisitor((node).objectAssignmentInitializer, visitor, isExpression)); + Debug.type(node); + return factory.updateShorthandPropertyAssignment(node, + nodeVisitor(node.name, visitor, isIdentifier), + nodeVisitor(node.objectAssignmentInitializer, visitor, isExpression)); case SyntaxKind.SpreadAssignment: - return factory.updateSpreadAssignment(node, - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updateSpreadAssignment(node, + nodeVisitor(node.expression, visitor, isExpression)); // Enum case SyntaxKind.EnumMember: - return factory.updateEnumMember(node, - nodeVisitor((node).name, visitor, isPropertyName), - nodeVisitor((node).initializer, visitor, isExpression)); + Debug.type(node); + return factory.updateEnumMember(node, + nodeVisitor(node.name, visitor, isPropertyName), + nodeVisitor(node.initializer, visitor, isExpression)); // Top-level nodes case SyntaxKind.SourceFile: - return factory.updateSourceFile(node, - visitLexicalEnvironment((node).statements, visitor, context)); + Debug.type(node); + return factory.updateSourceFile(node, + visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes case SyntaxKind.PartiallyEmittedExpression: - return factory.updatePartiallyEmittedExpression(node, - nodeVisitor((node).expression, visitor, isExpression)); + Debug.type(node); + return factory.updatePartiallyEmittedExpression(node, + nodeVisitor(node.expression, visitor, isExpression)); case SyntaxKind.CommaListExpression: - return factory.updateCommaListExpression(node, - nodesVisitor((node).elements, visitor, isExpression)); + Debug.type(node); + return factory.updateCommaListExpression(node, + nodesVisitor(node.elements, visitor, isExpression)); default: // No need to visit nodes with no children. diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 85594b103f01c..74a11dc51cc58 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -89,10 +89,10 @@ namespace ts { } /** Parses config file using System interface */ - export function parseConfigFileWithSystem(configFileName: string, optionsToExtend: CompilerOptions, watchOptionsToExtend: WatchOptions | undefined, system: System, reportDiagnostic: DiagnosticReporter) { + export function parseConfigFileWithSystem(configFileName: string, optionsToExtend: CompilerOptions, extendedConfigCache: Map | undefined, watchOptionsToExtend: WatchOptions | undefined, system: System, reportDiagnostic: DiagnosticReporter) { const host: ParseConfigFileHost = system; host.onUnRecoverableConfigFileDiagnostic = diagnostic => reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); - const result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, /*extendedConfigCache*/ undefined, watchOptionsToExtend); + const result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend); host.onUnRecoverableConfigFileDiagnostic = undefined!; // TODO: GH#18217 return result; } @@ -113,8 +113,8 @@ namespace ts { return `${newLine}${flattenDiagnosticMessageText(d.messageText, newLine)}${newLine}${newLine}`; } - export function isBuilderProgram(program: Program | T): program is T { - return !!(program as T).getState; + export function isBuilderProgram(program: Program | BuilderProgram): program is BuilderProgram { + return !!(program as BuilderProgram).getState; } export function listFiles(program: Program | T, write: (s: string) => void) { @@ -414,7 +414,10 @@ namespace ts { MissingFile: "Missing file", WildcardDirectory: "Wild card directory", FailedLookupLocations: "Failed Lookup Locations", - TypeRoots: "Type roots" + TypeRoots: "Type roots", + ConfigFileOfReferencedProject: "Config file of referened project", + ExtendedConfigOfReferencedProject: "Extended config file of referenced project", + WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project", }; export interface WatchTypeRegistry { @@ -424,7 +427,10 @@ namespace ts { MissingFile: "Missing file", WildcardDirectory: "Wild card directory", FailedLookupLocations: "Failed Lookup Locations", - TypeRoots: "Type roots" + TypeRoots: "Type roots", + ConfigFileOfReferencedProject: "Config file of referened project", + ExtendedConfigOfReferencedProject: "Extended config file of referenced project", + WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project", } interface WatchFactory extends ts.WatchFactory { @@ -476,6 +482,7 @@ namespace ts { getEnvironmentVariable: maybeBind(host, host.getEnvironmentVariable) || (() => ""), createHash: maybeBind(host, host.createHash), readDirectory: maybeBind(host, host.readDirectory), + disableUseFileVersionAsSignature: host.disableUseFileVersionAsSignature, }; function writeFile(fileName: string, text: string, writeByteOrderMark: boolean, onError: (message: string) => void) { @@ -538,7 +545,8 @@ namespace ts { createDirectory: path => system.createDirectory(path), writeFile: (path, data, writeByteOrderMark) => system.writeFile(path, data, writeByteOrderMark), createHash: maybeBind(system, system.createHash), - createProgram: createProgram || createEmitAndSemanticDiagnosticsBuilderProgram as any as CreateProgram + createProgram: createProgram || createEmitAndSemanticDiagnosticsBuilderProgram as any as CreateProgram, + disableUseFileVersionAsSignature: system.disableUseFileVersionAsSignature, }; } diff --git a/src/compiler/watchPublic.ts b/src/compiler/watchPublic.ts index 25bb26332d48e..0296e285b4520 100644 --- a/src/compiler/watchPublic.ts +++ b/src/compiler/watchPublic.ts @@ -19,6 +19,7 @@ namespace ts { export function createIncrementalCompilerHost(options: CompilerOptions, system = sys): CompilerHost { const host = createCompilerHostWorker(options, /*setParentNodes*/ undefined, system); host.createHash = maybeBind(system, system.createHash); + host.disableUseFileVersionAsSignature = system.disableUseFileVersionAsSignature; setGetSourceFileAsHashVersioned(host, system); changeCompilerHostLikeToUseCache(host, fileName => toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName)); return host; @@ -111,12 +112,17 @@ namespace ts { // TODO: GH#18217 Optional methods are frequently asserted createDirectory?(path: string): void; writeFile?(path: string, data: string, writeByteOrderMark?: boolean): void; + // For testing + disableUseFileVersionAsSignature?: boolean; } export interface WatchCompilerHost extends ProgramHost, WatchHost { /** Instead of using output d.ts file from project reference, use its source file */ useSourceOfProjectReferenceRedirect?(): boolean; + /** If provided, use this method to get parsed command lines for referenced projects */ + getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; + /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; } @@ -164,6 +170,7 @@ namespace ts { /*@internal*/ export interface WatchCompilerHostOfConfigFile extends WatchCompilerHost { configFileParsingResult?: ParsedCommandLine; + extendedConfigCache?: Map; } export interface Watch { @@ -222,6 +229,17 @@ namespace ts { } } + interface ParsedConfig { + /** ParsedCommandLine for the config file if present */ + parsedCommandLine: ParsedCommandLine | undefined; + /** File watcher of the config file */ + watcher?: FileWatcher; + /** Wild card directories watched from this config file */ + watchedDirectories?: Map; + /** Reload to be done for this config file */ + reloadLevel?: ConfigFileProgramReloadLevel.Partial | ConfigFileProgramReloadLevel.Full; + } + /** * Creates the watch from the host for root files and compiler options */ @@ -246,14 +264,15 @@ namespace ts { let builderProgram: T; let reloadLevel: ConfigFileProgramReloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc - let extendedConfigFilesMap: ESMap; // Map of file watchers for the extended config files - let missingFilesMap: ESMap; // Map of file watchers for the missing files + let missingFilesMap: ESMap; // Map of file watchers for the missing files let watchedWildcardDirectories: ESMap; // map of watchers for the wild card directories in the config file let timerToUpdateProgram: any; // timer callback to recompile the program let timerToInvalidateFailedLookupResolutions: any; // timer callback to invalidate resolutions for changes in failed lookup locations + let parsedConfigs: ESMap | undefined; // Parsed commandline and watching cached for referenced projects + let sharedExtendedConfigFileWatchers: ESMap>; // Map of file watchers for extended files, shared between different referenced projects + let extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation - - const sourceFilesCache = new Map(); // Cache that stores the source file and version info + const sourceFilesCache = new Map(); // Cache that stores the source file and version info let missingFilePathsRequestedForRelease: Path[] | undefined; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files let hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations @@ -302,6 +321,7 @@ namespace ts { compilerHost.getNewLine = () => newLine; compilerHost.fileExists = fileExists; compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile; + compilerHost.onReleaseParsedCommandLine = onReleaseParsedCommandLine; // Members for ResolutionCacheHost compilerHost.toPath = toPath; compilerHost.getCompilationSettings = () => compilerOptions; @@ -315,6 +335,7 @@ namespace ts { compilerHost.fileIsOpen = returnFalse; compilerHost.getCurrentProgram = getCurrentProgram; compilerHost.writeLog = writeLog; + compilerHost.getParsedCommandLine = getParsedCommandLine; // Cache for the module resolution const resolutionCache = createResolutionCache(compilerHost, @@ -339,7 +360,7 @@ namespace ts { watchConfigFileWildCardDirectories(); // Update extended config file watch - watchExtendedConfigFiles(); + if (configFileName) updateExtendedConfigFilesWatches(toPath(configFileName), compilerOptions, watchOptions, WatchType.ExtendedConfigFile); return configFileName ? { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close } : @@ -358,9 +379,11 @@ namespace ts { configFileWatcher.close(); configFileWatcher = undefined; } - if (extendedConfigFilesMap) { - clearMap(extendedConfigFilesMap, closeFileWatcher); - extendedConfigFilesMap = undefined!; + extendedConfigCache?.clear(); + extendedConfigCache = undefined; + if (sharedExtendedConfigFileWatchers) { + clearMap(sharedExtendedConfigFileWatchers, closeFileWatcherOf); + sharedExtendedConfigFileWatchers = undefined!; } if (watchedWildcardDirectories) { clearMap(watchedWildcardDirectories, closeFileWatcherOf); @@ -370,6 +393,15 @@ namespace ts { clearMap(missingFilesMap, closeFileWatcher); missingFilesMap = undefined!; } + if (parsedConfigs) { + clearMap(parsedConfigs, config => { + config.watcher?.close(); + config.watcher = undefined; + if (config.watchedDirectories) clearMap(config.watchedDirectories, closeFileWatcherOf); + config.watchedDirectories = undefined; + }); + parsedConfigs = undefined; + } } function getCurrentBuilderProgram() { @@ -394,7 +426,7 @@ namespace ts { // All resolutions are invalid if user provided resolutions const hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { + if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; @@ -416,6 +448,7 @@ namespace ts { writeLog("CreatingProgramWith::"); writeLog(` roots: ${JSON.stringify(rootFileNames)}`); writeLog(` options: ${JSON.stringify(compilerOptions)}`); + if (projectReferences) writeLog(` projectReferences: ${JSON.stringify(projectReferences)}`); const needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); hasChangedCompilerOptions = false; @@ -667,11 +700,18 @@ namespace ts { watchConfigFileWildCardDirectories(); // Update extended config file watch - watchExtendedConfigFiles(); + updateExtendedConfigFilesWatches(toPath(configFileName), compilerOptions, watchOptions, WatchType.ExtendedConfigFile); } function parseConfigFile() { - setConfigFileParsingResult(getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)!); // TODO: GH#18217 + setConfigFileParsingResult(getParsedCommandLineOfConfigFile( + configFileName, + optionsToExtendForConfigFile, + parseConfigFileHost, + extendedConfigCache ||= new Map(), + watchOptionsToExtend, + extraFileExtensions + )!); // TODO: GH#18217 } function setConfigFileParsingResult(configFileParseResult: ParsedCommandLine) { @@ -685,6 +725,67 @@ namespace ts { hasChangedConfigFileParsingErrors = true; } + function getParsedCommandLine(configFileName: string): ParsedCommandLine | undefined { + const configPath = toPath(configFileName); + let config = parsedConfigs?.get(configPath); + if (config) { + if (!config.reloadLevel) return config.parsedCommandLine; + // With host implementing getParsedCommandLine we cant just update file names + if (config.parsedCommandLine && config.reloadLevel === ConfigFileProgramReloadLevel.Partial && !host.getParsedCommandLine) { + writeLog("Reloading new file names and options"); + const fileNames = getFileNamesFromConfigSpecs( + config.parsedCommandLine.options.configFile!.configFileSpecs!, + getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), + compilerOptions, + parseConfigFileHost, + ); + config.parsedCommandLine = { ...config.parsedCommandLine, fileNames }; + config.reloadLevel = undefined; + return config.parsedCommandLine; + } + } + + writeLog(`Loading config file: ${configFileName}`); + const parsedCommandLine = host.getParsedCommandLine ? + host.getParsedCommandLine(configFileName) : + getParsedCommandLineFromConfigFileHost(configFileName); + if (config) { + config.parsedCommandLine = parsedCommandLine; + config.reloadLevel = undefined; + } + else { + (parsedConfigs ||= new Map()).set(configPath, config = { parsedCommandLine }); + } + watchReferencedProject(configFileName, configPath, config); + return parsedCommandLine; + } + + function getParsedCommandLineFromConfigFileHost(configFileName: string) { + // Ignore the file absent errors + const onUnRecoverableConfigFileDiagnostic = parseConfigFileHost.onUnRecoverableConfigFileDiagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = noop; + const parsedCommandLine = getParsedCommandLineOfConfigFile( + configFileName, + /*optionsToExtend*/ undefined, + parseConfigFileHost, + extendedConfigCache ||= new Map(), + watchOptionsToExtend + ); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = onUnRecoverableConfigFileDiagnostic; + return parsedCommandLine; + } + + function onReleaseParsedCommandLine(fileName: string) { + const path = toPath(fileName); + const config = parsedConfigs?.get(path); + if (!config) return; + + parsedConfigs!.delete(path); + if (config.watchedDirectories) clearMap(config.watchedDirectories, closeFileWatcherOf); + config.watcher?.close(); + clearSharedExtendedConfigFileWatcher(path, sharedExtendedConfigFileWatchers); + } + function watchFilePath( path: Path, file: string, @@ -703,7 +804,6 @@ namespace ts { if (eventKind === FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) { resolutionCache.invalidateResolutionOfFile(path); } - resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); nextSourceFileVersion(path); // Update the program @@ -717,7 +817,10 @@ namespace ts { } function watchMissingFilePath(missingFilePath: Path) { - return watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, PollingInterval.Medium, watchOptions, WatchType.MissingFile); + // If watching missing referenced config file, we are already watching it so no need for separate watcher + return parsedConfigs?.has(missingFilePath) ? + noopFileWatcher : + watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, PollingInterval.Medium, watchOptions, WatchType.MissingFile); } function onMissingFileChange(fileName: string, eventKind: FileWatcherEventKind, missingFilePath: Path) { @@ -769,10 +872,11 @@ namespace ts { configFileName, extraFileExtensions, options: compilerOptions, - program: getCurrentBuilderProgram(), + program: getCurrentBuilderProgram() || rootFileNames, currentDirectory, useCaseSensitiveFileNames, - writeLog + writeLog, + toPath, })) return; // Reload is pending, do the reload @@ -789,22 +893,113 @@ namespace ts { ); } - function watchExtendedConfigFiles() { - // Update the extended config files watcher - mutateMap( - extendedConfigFilesMap ||= new Map(), - arrayToMap(compilerOptions.configFile?.extendedSourceFiles || emptyArray, toPath), - { - // Watch the extended config files - createNewValue: watchExtendedConfigFile, - // Config files that are no longer extended should no longer be watched. - onDeleteValue: closeFileWatcher - } + function updateExtendedConfigFilesWatches(forProjectPath: Path, options: CompilerOptions | undefined, watchOptions: WatchOptions | undefined, watchType: WatchTypeRegistry["ExtendedConfigFile"] | WatchTypeRegistry["ExtendedConfigOfReferencedProject"]) { + updateSharedExtendedConfigFileWatcher( + forProjectPath, + options, + sharedExtendedConfigFileWatchers ||= new Map(), + (extendedConfigFileName, extendedConfigFilePath) => watchFile( + extendedConfigFileName, + (_fileName, eventKind) => { + updateCachedSystemWithFile(extendedConfigFileName, extendedConfigFilePath, eventKind); + // Update extended config cache + if (extendedConfigCache) cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath); + // Update projects + const projects = sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)?.projects; + // If there are no referenced projects this extended config file watcher depend on ignore + if (!projects?.size) return; + projects.forEach(projectPath => { + if (toPath(configFileName) === projectPath) { + // If this is the config file of the project, reload completely + reloadLevel = ConfigFileProgramReloadLevel.Full; + } + else { + // Reload config for the referenced projects and remove the resolutions from referenced projects since the config file changed + const config = parsedConfigs?.get(projectPath); + if (config) config.reloadLevel = ConfigFileProgramReloadLevel.Full; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(projectPath); + } + scheduleProgramUpdate(); + }); + }, + PollingInterval.High, + watchOptions, + watchType + ), + toPath, ); } - function watchExtendedConfigFile(extendedConfigFile: Path) { - return watchFile(extendedConfigFile, scheduleProgramReload, PollingInterval.High, watchOptions, WatchType.ExtendedConfigFile); + function watchReferencedProject(configFileName: string, configPath: Path, commandLine: ParsedConfig) { + // Watch file + commandLine.watcher ||= watchFile( + configFileName, + (_fileName, eventKind) => { + updateCachedSystemWithFile(configFileName, configPath, eventKind); + const config = parsedConfigs?.get(configPath); + if (config) config.reloadLevel = ConfigFileProgramReloadLevel.Full; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(configPath); + scheduleProgramUpdate(); + }, + PollingInterval.High, + commandLine.parsedCommandLine?.watchOptions || watchOptions, + WatchType.ConfigFileOfReferencedProject + ); + // Watch Wild card + if (commandLine.parsedCommandLine?.wildcardDirectories) { + updateWatchingWildcardDirectories( + commandLine.watchedDirectories ||= new Map(), + new Map(getEntries(commandLine.parsedCommandLine?.wildcardDirectories)), + (directory, flags) => watchDirectory( + directory, + fileOrDirectory => { + const fileOrDirectoryPath = toPath(fileOrDirectory); + // Since the file existence changed, update the sourceFiles cache + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + nextSourceFileVersion(fileOrDirectoryPath); + + const config = parsedConfigs?.get(configPath); + if (!config?.parsedCommandLine) return; + if (isIgnoredFileFromWildCardWatching({ + watchedDirPath: toPath(directory), + fileOrDirectory, + fileOrDirectoryPath, + configFileName, + options: config.parsedCommandLine.options, + program: config.parsedCommandLine.fileNames, + currentDirectory, + useCaseSensitiveFileNames, + writeLog, + toPath, + })) return; + + // Reload is pending, do the reload + if (config.reloadLevel !== ConfigFileProgramReloadLevel.Full) { + config.reloadLevel = ConfigFileProgramReloadLevel.Partial; + + // Schedule Update the program + scheduleProgramUpdate(); + } + }, + flags, + commandLine.parsedCommandLine?.watchOptions || watchOptions, + WatchType.WildcardDirectoryOfReferencedProject + ) + ); + } + else if (commandLine.watchedDirectories) { + clearMap(commandLine.watchedDirectories, closeFileWatcherOf); + commandLine.watchedDirectories = undefined; + } + // Watch extended config files + updateExtendedConfigFilesWatches( + configPath, + commandLine.parsedCommandLine?.options, + commandLine.parsedCommandLine?.watchOptions || watchOptions, + WatchType.ExtendedConfigOfReferencedProject + ); } } } diff --git a/src/compiler/watchUtilities.ts b/src/compiler/watchUtilities.ts index 80fd5fe7a8f98..970f6f2496917 100644 --- a/src/compiler/watchUtilities.ts +++ b/src/compiler/watchUtilities.ts @@ -44,7 +44,7 @@ namespace ts { return undefined; } - const cachedReadDirectoryResult = new Map(); + const cachedReadDirectoryResult = new Map(); const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); return { useCaseSensitiveFileNames, @@ -65,11 +65,11 @@ namespace ts { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } - function getCachedFileSystemEntries(rootDirPath: Path): MutableFileSystemEntries | undefined { + function getCachedFileSystemEntries(rootDirPath: Path) { return cachedReadDirectoryResult.get(ensureTrailingDirectorySeparator(rootDirPath)); } - function getCachedFileSystemEntriesForBaseDir(path: Path): MutableFileSystemEntries | undefined { + function getCachedFileSystemEntriesForBaseDir(path: Path) { return getCachedFileSystemEntries(getDirectoryPath(path)); } @@ -78,13 +78,24 @@ namespace ts { } function createCachedFileSystemEntries(rootDir: string, rootDirPath: Path) { - const resultFromHost: MutableFileSystemEntries = { - files: map(host.readDirectory!(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories!(rootDir) || [] - }; + if (!host.realpath || ensureTrailingDirectorySeparator(toPath(host.realpath(rootDir))) === rootDirPath) { + const resultFromHost: MutableFileSystemEntries = { + files: map(host.readDirectory!(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories!(rootDir) || [] + }; + + cachedReadDirectoryResult.set(ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); + return resultFromHost; + } + + // If the directory is symlink do not cache the result + if (host.directoryExists?.(rootDir)) { + cachedReadDirectoryResult.set(rootDirPath, false); + return false; + } - cachedReadDirectoryResult.set(ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); - return resultFromHost; + // Non existing directory + return undefined; } /** @@ -92,7 +103,7 @@ namespace ts { * Otherwise gets result from host and caches it. * The host request is done under try catch block to avoid caching incorrect result */ - function tryReadDirectory(rootDir: string, rootDirPath: Path): MutableFileSystemEntries | undefined { + function tryReadDirectory(rootDir: string, rootDirPath: Path) { rootDirPath = ensureTrailingDirectorySeparator(rootDirPath); const cachedResult = getCachedFileSystemEntries(rootDirPath); if (cachedResult) { @@ -170,8 +181,9 @@ namespace ts { function readDirectory(rootDir: string, extensions?: readonly string[], excludes?: readonly string[], includes?: readonly string[], depth?: number): string[] { const rootDirPath = toPath(rootDir); - const result = tryReadDirectory(rootDir, rootDirPath); - if (result) { + const rootResult = tryReadDirectory(rootDir, rootDirPath); + let rootSymLinkResult: FileSystemEntries | undefined; + if (rootResult !== undefined) { return matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory!(rootDir, extensions, excludes, includes, depth); @@ -179,9 +191,22 @@ namespace ts { function getFileSystemEntries(dir: string): FileSystemEntries { const path = toPath(dir); if (path === rootDirPath) { - return result!; + return rootResult || getFileSystemEntriesFromHost(dir, path); } - return tryReadDirectory(dir, path) || emptyFileSystemEntries; + const result = tryReadDirectory(dir, path); + return result !== undefined ? + result || getFileSystemEntriesFromHost(dir, path) : + emptyFileSystemEntries; + } + + function getFileSystemEntriesFromHost(dir: string, path: Path): FileSystemEntries { + if (rootSymLinkResult && path === rootDirPath) return rootSymLinkResult; + const result: FileSystemEntries = { + files: map(host.readDirectory!(dir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/["*.*"]), getBaseNameOfFileName) || emptyArray, + directories: host.getDirectories!(dir) || emptyArray + }; + if (path === rootDirPath) rootSymLinkResult = result; + return result; } } @@ -191,7 +216,7 @@ namespace ts { function addOrDeleteFileOrDirectory(fileOrDirectory: string, fileOrDirectoryPath: Path) { const existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { + if (existingResult !== undefined) { // Just clear the cache for now // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated clearCache(); @@ -258,7 +283,7 @@ namespace ts { } export interface SharedExtendedConfigFileWatcher extends FileWatcher { - fileWatcher: FileWatcher; + watcher: FileWatcher; projects: Set; } @@ -267,12 +292,12 @@ namespace ts { */ export function updateSharedExtendedConfigFileWatcher( projectPath: T, - parsed: ParsedCommandLine | undefined, + options: CompilerOptions | undefined, extendedConfigFilesMap: ESMap>, createExtendedConfigFileWatch: (extendedConfigPath: string, extendedConfigFilePath: Path) => FileWatcher, toPath: (fileName: string) => Path, ) { - const extendedConfigs = arrayToMap(parsed?.options.configFile?.extendedSourceFiles || emptyArray, toPath); + const extendedConfigs = arrayToMap(options?.configFile?.extendedSourceFiles || emptyArray, toPath); // remove project from all unrelated watchers extendedConfigFilesMap.forEach((watcher, extendedConfigFilePath) => { if (!extendedConfigs.has(extendedConfigFilePath)) { @@ -290,11 +315,11 @@ namespace ts { // start watching previously unseen extended config extendedConfigFilesMap.set(extendedConfigFilePath, { projects: new Set([projectPath]), - fileWatcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath), + watcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath), close: () => { const existing = extendedConfigFilesMap.get(extendedConfigFilePath); if (!existing || existing.projects.size !== 0) return; - existing.fileWatcher.close(); + existing.watcher.close(); extendedConfigFilesMap.delete(extendedConfigFilePath); }, }); @@ -302,6 +327,34 @@ namespace ts { }); } + /** + * Remove the project from the extended config file watchers and close not needed watches + */ + export function clearSharedExtendedConfigFileWatcher( + projectPath: T, + extendedConfigFilesMap: ESMap>, + ) { + extendedConfigFilesMap.forEach(watcher => { + if (watcher.projects.delete(projectPath)) watcher.close(); + }); + } + + /** + * Clean the extendsConfigCache when extended config file has changed + */ + export function cleanExtendedConfigCache( + extendedConfigCache: ESMap, + extendedConfigFilePath: Path, + toPath: (fileName: string) => Path, + ) { + if (!extendedConfigCache.delete(extendedConfigFilePath)) return; + extendedConfigCache.forEach(({ extendedResult }, key) => { + if (extendedResult.extendedSourceFiles?.some(extendedFile => toPath(extendedFile) === extendedConfigFilePath)) { + cleanExtendedConfigCache(extendedConfigCache, key as Path, toPath); + } + }); + } + /** * Updates the existing missing file watches with the new set of missing files after new program is created */ @@ -381,18 +434,19 @@ namespace ts { fileOrDirectoryPath: Path; configFileName: string; options: CompilerOptions; - program: BuilderProgram | Program | undefined; + program: BuilderProgram | Program | readonly string[] | undefined; extraFileExtensions?: readonly FileExtensionInfo[]; currentDirectory: string; useCaseSensitiveFileNames: boolean; writeLog: (s: string) => void; + toPath: (fileName: string) => Path; } /* @internal */ export function isIgnoredFileFromWildCardWatching({ watchedDirPath, fileOrDirectory, fileOrDirectoryPath, configFileName, options, program, extraFileExtensions, currentDirectory, useCaseSensitiveFileNames, - writeLog, + writeLog, toPath, }: IsIgnoredFileFromWildCardWatchingInput): boolean { const newPath = removeIgnoredPath(fileOrDirectoryPath); if (!newPath) { @@ -432,7 +486,8 @@ namespace ts { // just check if sourceFile with the name exists const filePathWithoutExtension = removeFileExtension(fileOrDirectoryPath); - const realProgram = isBuilderProgram(program) ? program.getProgramOrUndefined() : program; + const realProgram = isArray(program) ? undefined : isBuilderProgram(program) ? program.getProgramOrUndefined() : program; + const builderProgram = !realProgram && !isArray(program) ? program as BuilderProgram : undefined; if (hasSourceFile((filePathWithoutExtension + Extension.Ts) as Path) || hasSourceFile((filePathWithoutExtension + Extension.Tsx) as Path)) { writeLog(`Project: ${configFileName} Detected output file: ${fileOrDirectory}`); @@ -440,10 +495,12 @@ namespace ts { } return false; - function hasSourceFile(file: Path) { + function hasSourceFile(file: Path): boolean { return realProgram ? !!realProgram.getSourceFileByPath(file) : - (program as BuilderProgram).getState().fileInfos.has(file); + builderProgram ? + builderProgram.getState().fileInfos.has(file) : + !!find(program as readonly string[], rootFile => toPath(rootFile) === file); } } diff --git a/src/deprecatedCompat/deprecations.ts b/src/deprecatedCompat/deprecations.ts index b0573ad4ab75d..a70db0d344298 100644 --- a/src/deprecatedCompat/deprecations.ts +++ b/src/deprecatedCompat/deprecations.ts @@ -1229,7 +1229,7 @@ namespace ts { /** @deprecated Use `factory.createJSDocParameterTag` or the factory supplied by your transformation context instead. */ export const createJSDocParamTag = Debug.deprecate(function createJSDocParamTag(name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, comment?: string): JSDocParameterTag { - return factory.createJSDocParameterTag(/*tagName*/ undefined, name, isBracketed, typeExpression, /*isNameFirst*/ false, comment); + return factory.createJSDocParameterTag(/*tagName*/ undefined, name, isBracketed, typeExpression, /*isNameFirst*/ false, comment ? factory.createNodeArray([factory.createJSDocText(comment)]) : undefined); }, factoryDeprecation); /** @deprecated Use `factory.createComma` or the factory supplied by your transformation context instead. */ @@ -1354,4 +1354,24 @@ namespace ts { export interface Map extends ESMap { } // #endregion -} \ No newline at end of file + + // DEPRECATION: Renamed node tests + // DEPRECATION PLAN: + // - soft: 4.2 + // - warn: 4.3 + // - error: TBD + // #region Renamed node Tests + + /** + * @deprecated Use `isMemberName` instead. + */ + export const isIdentifierOrPrivateIdentifier = Debug.deprecate(function isIdentifierOrPrivateIdentifier(node: Node): node is MemberName { + return isMemberName(node); + }, { + since: "4.2", + warnAfter: "4.3", + message: "Use `isMemberName` instead." + }); + + // #endregion Renamed node Tests +} diff --git a/src/executeCommandLine/executeCommandLine.ts b/src/executeCommandLine/executeCommandLine.ts index 09f5230ab8a40..c99bfee08261a 100644 --- a/src/executeCommandLine/executeCommandLine.ts +++ b/src/executeCommandLine/executeCommandLine.ts @@ -286,7 +286,8 @@ namespace ts { fileName => getNormalizedAbsolutePath(fileName, currentDirectory) ); if (configFileName) { - const configParseResult = parseConfigFileWithSystem(configFileName, commandLineOptions, commandLine.watchOptions, sys, reportDiagnostic)!; // TODO: GH#18217 + const extendedConfigCache = new Map(); + const configParseResult = parseConfigFileWithSystem(configFileName, commandLineOptions, extendedConfigCache, commandLine.watchOptions, sys, reportDiagnostic)!; // TODO: GH#18217 if (commandLineOptions.showConfig) { if (configParseResult.errors.length !== 0) { reportDiagnostic = updateReportDiagnostic( @@ -315,6 +316,7 @@ namespace ts { configParseResult, commandLineOptions, commandLine.watchOptions, + extendedConfigCache, ); } else if (isIncrementalCompilation(configParseResult.options)) { @@ -501,7 +503,7 @@ namespace ts { updateSolutionBuilderHost(sys, cb, buildHost); const builder = createSolutionBuilder(buildHost, projects, buildOptions); const exitStatus = buildOptions.clean ? builder.clean() : builder.build(); - tracing?.dumpLegend(); + dumpTracingLegend(); // Will no-op if there hasn't been any tracing return sys.exit(exitStatus); } @@ -618,6 +620,7 @@ namespace ts { configParseResult: ParsedCommandLine, optionsToExtend: CompilerOptions, watchOptionsToExtend: WatchOptions | undefined, + extendedConfigCache: Map, ) { const watchCompilerHost = createWatchCompilerHostOfConfigFile({ configFileName: configParseResult.options.configFilePath!, @@ -629,6 +632,7 @@ namespace ts { }); updateWatchCompilationHost(system, cb, watchCompilerHost); watchCompilerHost.configFileParsingResult = configParseResult; + watchCompilerHost.extendedConfigCache = extendedConfigCache; return createWatchProgram(watchCompilerHost); } @@ -666,7 +670,7 @@ namespace ts { } if (canTrace(system, compilerOptions)) { - startTracing(isBuildMode ? tracingEnabled.Mode.Build : tracingEnabled.Mode.Project, + startTracing(isBuildMode ? "build" : "project", compilerOptions.generateTrace!, compilerOptions.configFilePath); } } @@ -675,7 +679,7 @@ namespace ts { const compilerOptions = program.getCompilerOptions(); if (canTrace(sys, compilerOptions)) { - tracing?.stopTracing(program.getTypeCatalog()); + tracing?.stopTracing(); } let statistics: Statistic[]; diff --git a/src/harness/client.ts b/src/harness/client.ts index f4f703d9164e3..8f56015af2359 100644 --- a/src/harness/client.ts +++ b/src/harness/client.ts @@ -175,8 +175,8 @@ namespace ts.server { kindModifiers: body.kindModifiers, textSpan: this.decodeSpan(body, fileName), displayParts: [{ kind: "text", text: body.displayString }], - documentation: [{ kind: "text", text: body.documentation }], - tags: body.tags + documentation: typeof body.documentation === "string" ? [{ kind: "text", text: body.documentation }] : body.documentation, + tags: this.decodeLinkDisplayParts(body.tags) }; } @@ -205,9 +205,9 @@ namespace ts.server { isNewIdentifierLocation: false, entries: response.body!.map(entry => { // TODO: GH#18217 if (entry.replacementSpan !== undefined) { - const { name, kind, kindModifiers, sortText, replacementSpan, hasAction, source, isRecommended } = entry; + const { name, kind, kindModifiers, sortText, replacementSpan, hasAction, source, data, isRecommended } = entry; // TODO: GH#241 - const res: CompletionEntry = { name, kind, kindModifiers, sortText, replacementSpan: this.decodeSpan(replacementSpan, fileName), hasAction, source, isRecommended }; + const res: CompletionEntry = { name, kind, kindModifiers, sortText, replacementSpan: this.decodeSpan(replacementSpan, fileName), hasAction, source, data: data as any, isRecommended }; return res; } @@ -216,14 +216,13 @@ namespace ts.server { }; } - getCompletionEntryDetails(fileName: string, position: number, entryName: string, _options: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined): CompletionEntryDetails { - const args: protocol.CompletionDetailsRequestArgs = { ...this.createFileLocationRequestArgs(fileName, position), entryNames: [{ name: entryName, source }] }; + getCompletionEntryDetails(fileName: string, position: number, entryName: string, _options: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, _preferences: UserPreferences | undefined, data: unknown): CompletionEntryDetails { + const args: protocol.CompletionDetailsRequestArgs = { ...this.createFileLocationRequestArgs(fileName, position), entryNames: [{ name: entryName, source, data }] }; - const request = this.processRequest(CommandNames.CompletionDetails, args); - const response = this.processResponse(request); - Debug.assert(response.body!.length === 1, "Unexpected length of completion details response body."); - const convertedCodeActions = map(response.body![0].codeActions, ({ description, changes }) => ({ description, changes: this.convertChanges(changes, fileName) })); - return { ...response.body![0], codeActions: convertedCodeActions }; + const request = this.processRequest(CommandNames.CompletionDetailsFull, args); + const response = this.processResponse(request); + Debug.assert(response.body.length === 1, "Unexpected length of completion details response body."); + return response.body[0]; } getCompletionEntrySymbol(_fileName: string, _position: number, _entryName: string): Symbol { @@ -307,7 +306,8 @@ namespace ts.server { fileName: entry.file, textSpan: this.decodeSpan(entry), kind: ScriptElementKind.unknown, - name: "" + name: "", + unverified: entry.unverified, })), textSpan: this.decodeSpan(body.textSpan, request.arguments.file) }; @@ -527,6 +527,9 @@ namespace ts.server { private decodeSpan(span: protocol.TextSpan & { file: string }): TextSpan; private decodeSpan(span: protocol.TextSpan, fileName: string, lineMap?: number[]): TextSpan; private decodeSpan(span: protocol.TextSpan & { file: string }, fileName?: string, lineMap?: number[]): TextSpan { + if (span.start.line === 1 && span.start.offset === 1 && span.end.line === 1 && span.end.offset === 1) { + return { start: 0, length: 0 }; + } fileName = fileName || span.file; lineMap = lineMap || this.getLineMap(fileName); return createTextSpanFromBounds( @@ -534,6 +537,13 @@ namespace ts.server { this.lineOffsetToPosition(fileName, span.end, lineMap)); } + private decodeLinkDisplayParts(tags: (protocol.JSDocTagInfo | JSDocTagInfo)[]): JSDocTagInfo[] { + return tags.map(tag => typeof tag.text === "string" ? { + ...tag, + text: [textPart(tag.text)] + } : (tag as JSDocTagInfo)); + } + getNameOrDottedNameSpan(_fileName: string, _startPos: number, _endPos: number): TextSpan { return notImplemented(); } @@ -552,9 +562,10 @@ namespace ts.server { return undefined; } - const { items, applicableSpan: encodedApplicableSpan, selectedItemIndex, argumentIndex, argumentCount } = response.body; + const { items: encodedItems, applicableSpan: encodedApplicableSpan, selectedItemIndex, argumentIndex, argumentCount } = response.body; - const applicableSpan = this.decodeSpan(encodedApplicableSpan, fileName); + const applicableSpan = encodedApplicableSpan as unknown as TextSpan; + const items = (encodedItems as (SignatureHelpItem | protocol.SignatureHelpItem)[]).map(item => ({ ...item, tags: this.decodeLinkDisplayParts(item.tags) })); return { items, applicableSpan, selectedItemIndex, argumentIndex, argumentCount }; } @@ -699,7 +710,7 @@ namespace ts.server { }; } - organizeImports(_scope: OrganizeImportsScope, _formatOptions: FormatCodeSettings): readonly FileTextChanges[] { + organizeImports(_args: OrganizeImportsArgs, _formatOptions: FormatCodeSettings): readonly FileTextChanges[] { return notImplemented(); } @@ -761,8 +772,10 @@ namespace ts.server { return notImplemented(); } - getEncodedSemanticClassifications(_fileName: string, _span: TextSpan, _format?: SemanticClassificationFormat): Classifications { - return notImplemented(); + getEncodedSemanticClassifications(file: string, span: TextSpan, format?: SemanticClassificationFormat): Classifications { + const request = this.processRequest(protocol.CommandTypes.EncodedSemanticClassificationsFull, { file, start: span.start, length: span.length, format }); + const r = this.processResponse(request); + return r.body!; } private convertCallHierarchyItem(item: protocol.CallHierarchyItem): CallHierarchyItem { diff --git a/src/harness/compilerImpl.ts b/src/harness/compilerImpl.ts index 0d24ee4797f54..badab5c6cbc8c 100644 --- a/src/harness/compilerImpl.ts +++ b/src/harness/compilerImpl.ts @@ -135,8 +135,6 @@ namespace compiler { } } } - - this.diagnostics = diagnostics; } public get vfs(): vfs.FileSystem { diff --git a/src/harness/evaluatorImpl.ts b/src/harness/evaluatorImpl.ts index 260c65567853f..fc89e989eb8a0 100644 --- a/src/harness/evaluatorImpl.ts +++ b/src/harness/evaluatorImpl.ts @@ -4,23 +4,6 @@ namespace evaluator { const sourceFile = vpath.combine(vfs.srcFolder, "source.ts"); const sourceFileJs = vpath.combine(vfs.srcFolder, "source.js"); - function compile(sourceText: string, options?: ts.CompilerOptions) { - const fs = vfs.createFromFileSystem(Harness.IO, /*ignoreCase*/ false); - fs.writeFileSync(sourceFile, sourceText); - const compilerOptions: ts.CompilerOptions = { - target: ts.ScriptTarget.ES5, - module: ts.ModuleKind.CommonJS, - lib: ["lib.esnext.d.ts", "lib.dom.d.ts"], - ...options - }; - const host = new fakes.CompilerHost(fs, compilerOptions); - return compiler.compileFiles(host, [sourceFile], compilerOptions); - } - - function noRequire(id: string) { - throw new Error(`Module '${id}' could not be found.`); - } - // Define a custom "Symbol" constructor to attach missing built-in symbols without // modifying the global "Symbol" constructor const FakeSymbol: SymbolConstructor = ((description?: string) => Symbol(description)) as any; @@ -32,8 +15,17 @@ namespace evaluator { // Add "asyncIterator" if missing if (!ts.hasProperty(FakeSymbol, "asyncIterator")) Object.defineProperty(FakeSymbol, "asyncIterator", { value: Symbol.for("Symbol.asyncIterator"), configurable: true }); - export function evaluateTypeScript(sourceText: string, options?: ts.CompilerOptions, globals?: Record) { - const result = compile(sourceText, options); + export function evaluateTypeScript(source: string | { files: vfs.FileSet, rootFiles: string[], main: string }, options?: ts.CompilerOptions, globals?: Record) { + if (typeof source === "string") source = { files: { [sourceFile]: source }, rootFiles: [sourceFile], main: sourceFile }; + const fs = vfs.createFromFileSystem(Harness.IO, /*ignoreCase*/ false, { files: source.files }); + const compilerOptions: ts.CompilerOptions = { + target: ts.ScriptTarget.ES5, + module: ts.ModuleKind.CommonJS, + lib: ["lib.esnext.d.ts", "lib.dom.d.ts"], + ...options + }; + const host = new fakes.CompilerHost(fs, compilerOptions); + const result = compiler.compileFiles(host, source.rootFiles, compilerOptions); if (ts.some(result.diagnostics)) { assert.ok(/*value*/ false, "Syntax error in evaluation source text:\n" + ts.formatDiagnostics(result.diagnostics, { getCanonicalFileName: file => file, @@ -42,29 +34,100 @@ namespace evaluator { })); } - const output = result.getOutput(sourceFile, "js")!; + const output = result.getOutput(source.main, "js")!; assert.isDefined(output); - return evaluateJavaScript(output.text, globals, output.file); + globals = { Symbol: FakeSymbol, ...globals }; + return createLoader(fs, globals)(output.file); } - export function evaluateJavaScript(sourceText: string, globals?: Record, sourceFile = sourceFileJs) { - globals = { Symbol: FakeSymbol, ...globals }; + function createLoader(fs: vfs.FileSystem, globals: Record) { + interface Module { + exports: any; + } - const globalNames: string[] = []; - const globalArgs: any[] = []; - for (const name in globals) { - if (ts.hasProperty(globals, name)) { - globalNames.push(name); - globalArgs.push(globals[name]); + const moduleCache = new ts.Map(); + return load; + + function evaluate(text: string, file: string, module: Module) { + const globalNames: string[] = []; + const globalArgs: any[] = []; + for (const name in globals) { + if (ts.hasProperty(globals, name)) { + globalNames.push(name); + globalArgs.push(globals[name]); + } + } + const base = vpath.dirname(file); + const localRequire = (id: string) => requireModule(id, base); + const evaluateText = `(function (module, exports, require, __dirname, __filename, ${globalNames.join(", ")}) { ${text} })`; + // eslint-disable-next-line no-eval + const evaluateThunk = (void 0, eval)(evaluateText) as (module: any, exports: any, require: (id: string) => any, dirname: string, filename: string, ...globalArgs: any[]) => void; + evaluateThunk.call(globals, module, module.exports, localRequire, vpath.dirname(file), file, FakeSymbol, ...globalArgs); + } + + function loadModule(file: string): Module { + if (!ts.isExternalModuleNameRelative(file)) throw new Error(`Module '${file}' could not be found.`); + let module = moduleCache.get(file); + if (module) return module; + moduleCache.set(file, module = { exports: {} }); + try { + const sourceText = fs.readFileSync(file, "utf8"); + evaluate(sourceText, file, module); + return module; + } + catch (e) { + moduleCache.delete(file); + throw e; } } - const evaluateText = `(function (module, exports, require, __dirname, __filename, ${globalNames.join(", ")}) { ${sourceText} })`; - // eslint-disable-next-line no-eval - const evaluateThunk = (void 0, eval)(evaluateText) as (module: any, exports: any, require: (id: string) => any, dirname: string, filename: string, ...globalArgs: any[]) => void; - const module: { exports: any; } = { exports: {} }; - evaluateThunk.call(globals, module, module.exports, noRequire, vpath.dirname(sourceFile), sourceFile, FakeSymbol, ...globalArgs); - return module.exports; + function isFile(file: string) { + return fs.existsSync(file) && fs.statSync(file).isFile(); + } + + function loadAsFile(file: string): Module | undefined { + if (isFile(file)) return loadModule(file); + if (isFile(file + ".js")) return loadModule(file + ".js"); + return undefined; + } + + function loadIndex(dir: string): Module | undefined { + const indexFile = vpath.resolve(dir, "index.js"); + if (isFile(indexFile)) return loadModule(indexFile); + return undefined; + } + + function loadAsDirectory(dir: string): Module | undefined { + const packageFile = vpath.resolve(dir, "package.json"); + if (isFile(packageFile)) { + const text = fs.readFileSync(packageFile, "utf8"); + const json = JSON.parse(text); + if (json.main) { + const main = vpath.resolve(dir, json.main); + const result = loadAsFile(main) || loadIndex(main); + if (result === undefined) throw new Error("Module not found"); + } + } + return loadIndex(dir); + } + + function requireModule(id: string, base: string) { + if (!ts.isExternalModuleNameRelative(id)) throw new Error(`Module '${id}' could not be found.`); + const file = vpath.resolve(base, id); + const module = loadAsFile(file) || loadAsDirectory(file); + if (!module) throw new Error(`Module '${id}' could not be found.`); + return module.exports; + } + + function load(file: string) { + return requireModule(file, fs.cwd()); + } + } + + export function evaluateJavaScript(sourceText: string, globals?: Record, sourceFile = sourceFileJs) { + globals = { Symbol: FakeSymbol, ...globals }; + const fs = new vfs.FileSystem(/*ignoreCase*/ false, { files: { [sourceFile]: sourceText } }); + return createLoader(fs, globals)(sourceFile); } } diff --git a/src/harness/fourslashImpl.ts b/src/harness/fourslashImpl.ts index d86f2e904fe65..742dc6bced721 100644 --- a/src/harness/fourslashImpl.ts +++ b/src/harness/fourslashImpl.ts @@ -399,7 +399,7 @@ namespace FourSlash { } const memo = Utils.memoize( (_version: number, _active: string, _caret: number, _selectEnd: number, _marker: string, ...args: any[]) => (ls[key] as Function)(...args), - (...args) => args.join("|,|") + (...args) => args.map(a => a && typeof a === "object" ? JSON.stringify(a) : a).join("|,|") ); proxy[key] = (...args: any[]) => memo( target.languageServiceAdapterHost.getScriptInfo(target.activeFile.fileName)!.version, @@ -685,10 +685,10 @@ namespace FourSlash { } public verifyGoToDefinitionIs(endMarker: ArrayOrSingle) { - this.verifyGoToXWorker(toArray(endMarker), () => this.getGoToDefinition()); + this.verifyGoToXWorker(/*startMarker*/ undefined, toArray(endMarker), () => this.getGoToDefinition()); } - public verifyGoToDefinition(arg0: any, endMarkerNames?: ArrayOrSingle) { + public verifyGoToDefinition(arg0: any, endMarkerNames?: ArrayOrSingle | { file: string, unverified?: boolean }) { this.verifyGoToX(arg0, endMarkerNames, () => this.getGoToDefinitionAndBoundSpan()); } @@ -705,7 +705,7 @@ namespace FourSlash { this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition)); } - private verifyGoToX(arg0: any, endMarkerNames: ArrayOrSingle | undefined, getDefs: () => readonly ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined) { + private verifyGoToX(arg0: any, endMarkerNames: ArrayOrSingle | { file: string, unverified?: boolean } | undefined, getDefs: () => readonly ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined) { if (endMarkerNames) { this.verifyGoToXPlain(arg0, endMarkerNames, getDefs); } @@ -725,7 +725,7 @@ namespace FourSlash { } } - private verifyGoToXPlain(startMarkerNames: ArrayOrSingle, endMarkerNames: ArrayOrSingle, getDefs: () => readonly ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined) { + private verifyGoToXPlain(startMarkerNames: ArrayOrSingle, endMarkerNames: ArrayOrSingle | { file: string, unverified?: boolean }, getDefs: () => readonly ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined) { for (const start of toArray(startMarkerNames)) { this.verifyGoToXSingle(start, endMarkerNames, getDefs); } @@ -737,12 +737,12 @@ namespace FourSlash { } } - private verifyGoToXSingle(startMarkerName: string, endMarkerNames: ArrayOrSingle, getDefs: () => readonly ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined) { + private verifyGoToXSingle(startMarkerName: string, endMarkerNames: ArrayOrSingle | { file: string, unverified?: boolean }, getDefs: () => readonly ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined) { this.goToMarker(startMarkerName); - this.verifyGoToXWorker(toArray(endMarkerNames), getDefs, startMarkerName); + this.verifyGoToXWorker(startMarkerName, toArray(endMarkerNames), getDefs, startMarkerName); } - private verifyGoToXWorker(endMarkers: readonly string[], getDefs: () => readonly ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined, startMarkerName?: string) { + private verifyGoToXWorker(startMarker: string | undefined, endMarkers: readonly (string | { marker?: string, file?: string, unverified?: boolean })[], getDefs: () => readonly ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined, startMarkerName?: string) { const defs = getDefs(); let definitions: readonly ts.DefinitionInfo[]; let testName: string; @@ -762,21 +762,33 @@ namespace FourSlash { this.raiseError(`${testName} failed - expected to find ${endMarkers.length} definitions but got ${definitions.length}`); } - ts.zipWith(endMarkers, definitions, (endMarker, definition, i) => { - const marker = this.getMarkerByName(endMarker); - if (ts.comparePaths(marker.fileName, definition.fileName, /*ignoreCase*/ true) !== ts.Comparison.EqualTo || marker.position !== definition.textSpan.start) { - const filesToDisplay = ts.deduplicate([marker.fileName, definition.fileName], ts.equateValues); - const markers = [{ text: "EXPECTED", fileName: marker.fileName, position: marker.position }, { text: "ACTUAL", fileName: definition.fileName, position: definition.textSpan.start }]; + ts.zipWith(endMarkers, definitions, (endMarkerOrFileResult, definition, i) => { + const markerName = typeof endMarkerOrFileResult === "string" ? endMarkerOrFileResult : endMarkerOrFileResult.marker; + const marker = markerName !== undefined ? this.getMarkerByName(markerName) : undefined; + const expectedFileName = marker?.fileName || typeof endMarkerOrFileResult !== "string" && endMarkerOrFileResult.file; + ts.Debug.assert(typeof expectedFileName === "string"); + const expectedPosition = marker?.position || 0; + if (ts.comparePaths(expectedFileName, definition.fileName, /*ignoreCase*/ true) !== ts.Comparison.EqualTo || expectedPosition !== definition.textSpan.start) { + const filesToDisplay = ts.deduplicate([expectedFileName, definition.fileName], ts.equateValues); + const markers = [{ text: "EXPECTED", fileName: expectedFileName, position: expectedPosition }, { text: "ACTUAL", fileName: definition.fileName, position: definition.textSpan.start }]; const text = filesToDisplay.map(fileName => { const markersToRender = markers.filter(m => m.fileName === fileName).sort((a, b) => b.position - a.position); - let fileContent = this.getFileContent(fileName); + let fileContent = this.tryGetFileContent(fileName) || ""; for (const marker of markersToRender) { fileContent = fileContent.slice(0, marker.position) + `\x1b[1;4m/*${marker.text}*/\x1b[0;31m` + fileContent.slice(marker.position); } return `// @Filename: ${fileName}\n${fileContent}`; }).join("\n\n"); - this.raiseError(`${testName} failed for definition ${endMarker} (${i}): expected ${marker.fileName} at ${marker.position}, got ${definition.fileName} at ${definition.textSpan.start}\n\n${text}\n`); + this.raiseError(`${testName} failed for definition ${markerName || expectedFileName} (${i}): expected ${expectedFileName} at ${expectedPosition}, got ${definition.fileName} at ${definition.textSpan.start}\n\n${text}\n`); + } + if (definition.unverified && (typeof endMarkerOrFileResult === "string" || !endMarkerOrFileResult.unverified)) { + const isFileResult = typeof endMarkerOrFileResult !== "string" && !!endMarkerOrFileResult.file; + this.raiseError( + `${testName} failed for definition ${markerName || expectedFileName} (${i}): The actual definition was an \`unverified\` result. Use:\n\n` + + ` verify.goToDefinition(${startMarker === undefined ? "startMarker" : `"${startMarker}"`}, { ${isFileResult ? `file: "${expectedFileName}"` : `marker: "${markerName}"`}, unverified: true })\n\n` + + `if this is expected.` + ); } }); } @@ -867,7 +879,7 @@ namespace FourSlash { nameToEntries.set(entry.name, [entry]); } else { - if (entries.some(e => e.source === entry.source)) { + if (entries.some(e => e.source === entry.source && this.deepEqual(e.data, entry.data))) { this.raiseError(`Duplicate completions for ${entry.name}`); } entries.push(entry); @@ -885,8 +897,8 @@ namespace FourSlash { const name = typeof include === "string" ? include : include.name; const found = nameToEntries.get(name); if (!found) throw this.raiseError(`Includes: completion '${name}' not found.`); - assert(found.length === 1, `Must use 'exact' for multiple completions with same name: '${name}'`); - this.verifyCompletionEntry(ts.first(found), include); + if (!found.length) throw this.raiseError(`Includes: no completions with name '${name}' remain unmatched.`); + this.verifyCompletionEntry(found.shift()!, include); } } if (options.excludes) { @@ -929,21 +941,28 @@ namespace FourSlash { assert.equal(actual.hasAction, expected.hasAction, `Expected 'hasAction' properties to match`); assert.equal(actual.isRecommended, expected.isRecommended, `Expected 'isRecommended' properties to match'`); + assert.equal(actual.isSnippet, expected.isSnippet, `Expected 'isSnippet' properties to match`); assert.equal(actual.source, expected.source, `Expected 'source' values to match`); - assert.equal(actual.sortText, expected.sortText || ts.Completions.SortText.LocationPriority, this.messageAtLastKnownMarker(`Actual entry: ${JSON.stringify(actual)}`)); + assert.equal(actual.sortText, expected.sortText || ts.Completions.SortText.LocationPriority, `Expected 'sortText' properties to match`); + if (expected.sourceDisplay && actual.sourceDisplay) { + assert.equal(ts.displayPartsToString(actual.sourceDisplay), expected.sourceDisplay, `Expected 'sourceDisplay' properties to match`); + } if (expected.text !== undefined) { - const actualDetails = this.getCompletionEntryDetails(actual.name, actual.source)!; + const actualDetails = ts.Debug.checkDefined(this.getCompletionEntryDetails(actual.name, actual.source, actual.data), `No completion details available for name '${actual.name}' and source '${actual.source}'`); assert.equal(ts.displayPartsToString(actualDetails.displayParts), expected.text, "Expected 'text' property to match 'displayParts' string"); assert.equal(ts.displayPartsToString(actualDetails.documentation), expected.documentation || "", "Expected 'documentation' property to match 'documentation' display parts string"); // TODO: GH#23587 // assert.equal(actualDetails.kind, actual.kind); assert.equal(actualDetails.kindModifiers, actual.kindModifiers, "Expected 'kindModifiers' properties to match"); assert.equal(actualDetails.source && ts.displayPartsToString(actualDetails.source), expected.sourceDisplay, "Expected 'sourceDisplay' property to match 'source' display parts string"); + if (!actual.sourceDisplay) { + assert.equal(actualDetails.sourceDisplay && ts.displayPartsToString(actualDetails.sourceDisplay), expected.sourceDisplay, "Expected 'sourceDisplay' property to match 'sourceDisplay' display parts string"); + } assert.deepEqual(actualDetails.tags, expected.tags); } else { - assert(expected.documentation === undefined && expected.tags === undefined && expected.sourceDisplay === undefined, "If specifying completion details, should specify 'text'"); + assert(expected.documentation === undefined && expected.tags === undefined, "If specifying completion details, should specify 'text'"); } } @@ -961,12 +980,14 @@ namespace FourSlash { } /** Use `getProgram` instead of accessing this directly. */ - private _program: ts.Program | undefined; + private _program: ts.Program | undefined | "missing"; /** Use `getChecker` instead of accessing this directly. */ private _checker: ts.TypeChecker | undefined; private getProgram(): ts.Program { - return this._program || (this._program = this.languageService.getProgram()!); // TODO: GH#18217 + if (!this._program) this._program = this.languageService.getProgram() || "missing"; + if (this._program === "missing") ts.Debug.fail("Could not retrieve program from language service"); + return this._program; } private getChecker() { @@ -1003,8 +1024,8 @@ namespace FourSlash { private verifySymbol(symbol: ts.Symbol, declarationRanges: Range[]) { const { declarations } = symbol; - if (declarations.length !== declarationRanges.length) { - this.raiseError(`Expected to get ${declarationRanges.length} declarations, got ${declarations.length}`); + if (declarations?.length !== declarationRanges.length) { + this.raiseError(`Expected to get ${declarationRanges.length} declarations, got ${declarations?.length}`); } ts.zipWith(declarations, declarationRanges, (decl, range) => { @@ -1163,6 +1184,11 @@ namespace FourSlash { let pos = 0; for (const { textSpan } of refsByFile.find(refs => refs[0].fileName === fileName) ?? ts.emptyArray) { const end = textSpan.start + textSpan.length; + if (fileName === marker?.fileName && pos <= marker.position && marker.position < textSpan.start) { + newContent += content.slice(pos, marker.position); + newContent += "/*FIND ALL REFS*/"; + pos = marker.position; + } newContent += content.slice(pos, textSpan.start); pos = textSpan.start; // It's easier to read if the /*FIND ALL REFS*/ comment is outside the range markers, which makes @@ -1254,6 +1280,16 @@ namespace FourSlash { } + private deepEqual(a: unknown, b: unknown) { + try { + this.assertObjectsEqual(a, b); + return true; + } + catch { + return false; + } + } + public verifyDisplayPartsOfReferencedSymbol(expected: ts.SymbolDisplayPart[]) { const referencedSymbols = this.findReferencesAtCaret()!; @@ -1281,11 +1317,11 @@ namespace FourSlash { return this.languageService.getCompletionsAtPosition(this.activeFile.fileName, this.currentCaretPosition, options); } - private getCompletionEntryDetails(entryName: string, source?: string, preferences?: ts.UserPreferences): ts.CompletionEntryDetails | undefined { + private getCompletionEntryDetails(entryName: string, source: string | undefined, data: ts.CompletionEntryData | undefined, preferences?: ts.UserPreferences): ts.CompletionEntryDetails | undefined { if (preferences) { this.configure(preferences); } - return this.languageService.getCompletionEntryDetails(this.activeFile.fileName, this.currentCaretPosition, entryName, this.formatCodeSettings, source, preferences); + return this.languageService.getCompletionEntryDetails(this.activeFile.fileName, this.currentCaretPosition, entryName, this.formatCodeSettings, source, preferences, data); } private getReferencesAtCaret() { @@ -1572,7 +1608,7 @@ namespace FourSlash { assert.equal(actualTags.length, (options.tags || ts.emptyArray).length, this.assertionMessageAtLastKnownMarker("signature help tags")); ts.zipWith((options.tags || ts.emptyArray), actualTags, (expectedTag, actualTag) => { assert.equal(actualTag.name, expectedTag.name); - assert.equal(actualTag.text, expectedTag.text, this.assertionMessageAtLastKnownMarker("signature help tag " + actualTag.name)); + assert.deepEqual(actualTag.text, expectedTag.text, this.assertionMessageAtLastKnownMarker("signature help tag " + actualTag.name)); }); const allKeys: readonly (keyof FourSlashInterface.VerifySignatureHelpOptions)[] = [ @@ -1906,19 +1942,45 @@ namespace FourSlash { } public baselineQuickInfo() { - const baselineFile = this.getBaselineFileNameForInternalFourslashFile(); - Harness.Baseline.runBaseline( - baselineFile, - stringify( - this.testData.markers.map(marker => ({ - marker, - quickInfo: this.languageService.getQuickInfoAtPosition(marker.fileName, marker.position) - })))); + const baselineFile = this.getBaselineFileNameForContainingTestFile(); + const result = ts.arrayFrom(this.testData.markerPositions.entries(), ([name, marker]) => ({ + marker: { ...marker, name }, + quickInfo: this.languageService.getQuickInfoAtPosition(marker.fileName, marker.position) + })); + Harness.Baseline.runBaseline(baselineFile, stringify(result)); + } + + public baselineSignatureHelp() { + const baselineFile = this.getBaselineFileNameForContainingTestFile(); + const result = ts.arrayFrom(this.testData.markerPositions.entries(), ([name, marker]) => ({ + marker: { ...marker, name }, + signatureHelp: this.languageService.getSignatureHelpItems(marker.fileName, marker.position, /*options*/ undefined) + })); + Harness.Baseline.runBaseline(baselineFile, stringify(result)); + } + + public baselineCompletions(preferences?: ts.UserPreferences) { + const baselineFile = this.getBaselineFileNameForContainingTestFile(); + const result = ts.arrayFrom(this.testData.markerPositions.entries(), ([name, marker]) => { + const completions = this.getCompletionListAtCaret(preferences); + this.goToMarker(marker); + return { + marker: { ...marker, name }, + completionList: { + ...completions, + entries: completions?.entries.map(entry => ({ + ...entry, + ...this.getCompletionEntryDetails(entry.name, entry.source, entry.data, preferences) + })), + } + }; + }); + Harness.Baseline.runBaseline(baselineFile, stringify(result)); } public baselineSmartSelection() { const n = "\n"; - const baselineFile = this.getBaselineFileNameForInternalFourslashFile(); + const baselineFile = this.getBaselineFileNameForContainingTestFile(); const markers = this.getMarkers(); const fileContent = this.activeFile.content; const text = markers.map(marker => { @@ -2684,6 +2746,12 @@ namespace FourSlash { // fs.writeFileSync(testfilePath, newfile); } + public verifyEncodedSemanticClassificationsLength(format: ts.SemanticClassificationFormat, expected: number) { + const actual = this.languageService.getEncodedSemanticClassifications(this.activeFile.fileName, ts.createTextSpan(0, this.activeFile.content.length), format); + if (actual.spans.length !== expected) { + this.raiseError(`encodedSemanticClassificationsLength failed - expected total spans to be ${expected} got ${actual.spans.length}`); + } + } public verifySemanticClassifications(format: ts.SemanticClassificationFormat, expected: { classificationType: string | number; text?: string }[]) { const actual = this.languageService.getSemanticClassifications(this.activeFile.fileName, @@ -2796,14 +2864,14 @@ namespace FourSlash { public applyCodeActionFromCompletion(markerName: string, options: FourSlashInterface.VerifyCompletionActionOptions) { this.goToMarker(markerName); - const details = this.getCompletionEntryDetails(options.name, options.source, options.preferences); + const details = this.getCompletionEntryDetails(options.name, options.source, options.data, options.preferences); if (!details) { const completions = this.getCompletionListAtCaret(options.preferences)?.entries; const matchingName = completions?.filter(e => e.name === options.name); const detailMessage = matchingName?.length ? `\n Found ${matchingName.length} with name '${options.name}' from source(s) ${matchingName.map(e => `'${e.source}'`).join(", ")}.` : ` (In fact, there were no completions with name '${options.name}' at all.)`; - return this.raiseError(`No completions were found for the given name, source, and preferences.` + detailMessage); + return this.raiseError(`No completions were found for the given name, source/data, and preferences.` + detailMessage); } const codeActions = details.codeActions; if (codeActions?.length !== 1) { diff --git a/src/harness/fourslashInterfaceImpl.ts b/src/harness/fourslashInterfaceImpl.ts index 09b52997b1285..0eb1071681a60 100644 --- a/src/harness/fourslashInterfaceImpl.ts +++ b/src/harness/fourslashInterfaceImpl.ts @@ -396,6 +396,14 @@ namespace FourSlashInterface { this.state.baselineQuickInfo(); } + public baselineSignatureHelp() { + this.state.baselineSignatureHelp(); + } + + public baselineCompletions() { + this.state.baselineCompletions(); + } + public baselineSmartSelection() { this.state.baselineSmartSelection(); } @@ -529,6 +537,10 @@ namespace FourSlashInterface { this.state.verifySyntacticClassifications(classifications); } + public encodedSemanticClassificationsLength(format: ts.SemanticClassificationFormat, length: number) { + this.state.verifyEncodedSemanticClassificationsLength(format, length); + } + /** * This method *requires* an ordered stream of classifications for a file, and spans are highly recommended. */ @@ -1150,6 +1162,7 @@ namespace FourSlashInterface { case "symbol": case "type": case "unique": + case "override": case "unknown": case "global": case "bigint": @@ -1161,12 +1174,12 @@ namespace FourSlashInterface { } export const classElementKeywords: readonly ExpectedCompletionEntryObject[] = - ["private", "protected", "public", "static", "abstract", "async", "constructor", "declare", "get", "readonly", "set"].map(keywordEntry); + ["private", "protected", "public", "static", "abstract", "async", "constructor", "declare", "get", "readonly", "set", "override"].map(keywordEntry); export const classElementInJsKeywords = getInJsKeywords(classElementKeywords); export const constructorParameterKeywords: readonly ExpectedCompletionEntryObject[] = - ["private", "protected", "public", "readonly"].map((name): ExpectedCompletionEntryObject => ({ + ["private", "protected", "public", "readonly", "override"].map((name): ExpectedCompletionEntryObject => ({ name, kind: "keyword", sortText: SortText.GlobalsOrKeywords @@ -1591,6 +1604,7 @@ namespace FourSlashInterface { readonly isFromUncheckedFile?: boolean; // If not specified, won't assert about this readonly kind?: string; // If not specified, won't assert about this readonly isPackageJsonImport?: boolean; // If not specified, won't assert about this + readonly isSnippet?: boolean; readonly kindModifiers?: string; // Must be paired with 'kind' readonly text?: string; readonly documentation?: string; @@ -1701,6 +1715,7 @@ namespace FourSlashInterface { export interface VerifyCompletionActionOptions extends NewContentOptions { name: string; source?: string; + data?: ts.CompletionEntryData; description: string; preferences?: ts.UserPreferences; } diff --git a/src/harness/harnessIO.ts b/src/harness/harnessIO.ts index f556b6e47f69c..48ad549d4efae 100644 --- a/src/harness/harnessIO.ts +++ b/src/harness/harnessIO.ts @@ -72,6 +72,7 @@ namespace Harness { for (const file of fs.readdirSync(folder)) { const pathToFile = pathModule.join(folder, file); + if (!fs.existsSync(pathToFile)) continue; // ignore invalid symlinks const stat = fs.statSync(pathToFile); if (options.recursive && stat.isDirectory()) { paths = paths.concat(filesInFolder(pathToFile)); diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index 1a056683f912c..956d8c5ea9825 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -474,8 +474,8 @@ namespace Harness.LanguageService { getCompletionsAtPosition(fileName: string, position: number, preferences: ts.UserPreferences | undefined): ts.CompletionInfo { return unwrapJSONCallResult(this.shim.getCompletionsAtPosition(fileName, position, preferences)); } - getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: ts.FormatCodeOptions | undefined, source: string | undefined, preferences: ts.UserPreferences | undefined): ts.CompletionEntryDetails { - return unwrapJSONCallResult(this.shim.getCompletionEntryDetails(fileName, position, entryName, JSON.stringify(formatOptions), source, preferences)); + getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: ts.FormatCodeOptions | undefined, source: string | undefined, preferences: ts.UserPreferences | undefined, data: ts.CompletionEntryData | undefined): ts.CompletionEntryDetails { + return unwrapJSONCallResult(this.shim.getCompletionEntryDetails(fileName, position, entryName, JSON.stringify(formatOptions), source, preferences, data)); } getCompletionEntrySymbol(): ts.Symbol { throw new Error("getCompletionEntrySymbol not implemented across the shim layer."); @@ -584,7 +584,7 @@ namespace Harness.LanguageService { getApplicableRefactors(): ts.ApplicableRefactorInfo[] { throw new Error("Not supported on the shim."); } - organizeImports(_scope: ts.OrganizeImportsScope, _formatOptions: ts.FormatCodeSettings): readonly ts.FileTextChanges[] { + organizeImports(_args: ts.OrganizeImportsArgs, _formatOptions: ts.FormatCodeSettings): readonly ts.FileTextChanges[] { throw new Error("Not supported on the shim."); } getEditsForFileRename(): readonly ts.FileTextChanges[] { diff --git a/src/harness/virtualFileSystemWithWatch.ts b/src/harness/virtualFileSystemWithWatch.ts index e17136d67e385..acbee4e5f3ef8 100644 --- a/src/harness/virtualFileSystemWithWatch.ts +++ b/src/harness/virtualFileSystemWithWatch.ts @@ -127,7 +127,7 @@ interface Array { length: number; [n: number]: T; }` return { close: () => map.remove(path, callback) }; } - function getDiffInKeys(map: ESMap, expectedKeys: readonly string[]) { + export function getDiffInKeys(map: ESMap, expectedKeys: readonly string[]) { if (map.size === expectedKeys.length) { return ""; } @@ -195,7 +195,7 @@ interface Array { length: number; [n: number]: T; }` checkMap(caption, arrayToMap(actual, identity), expected, /*eachKeyCount*/ undefined); } - export function checkWatchedFiles(host: TestServerHost, expectedFiles: string[], additionalInfo?: string) { + export function checkWatchedFiles(host: TestServerHost, expectedFiles: readonly string[], additionalInfo?: string) { checkMap(`watchedFiles:: ${additionalInfo || ""}::`, host.watchedFiles, expectedFiles, /*eachKeyCount*/ undefined); } @@ -395,6 +395,7 @@ interface Array { length: number; [n: number]: T; }` private readonly executingFilePath: string; private readonly currentDirectory: string; public require: ((initialPath: string, moduleName: string) => RequireResult) | undefined; + public defaultWatchFileKind?: () => WatchFileKind | undefined; watchFile: HostWatchFile; watchDirectory: HostWatchDirectory; constructor( @@ -439,7 +440,8 @@ interface Array { length: number; [n: number]: T; }` getAccessibleSortedChildDirectories: path => this.getDirectories(path), realpath: this.realpath.bind(this), tscWatchFile, - tscWatchDirectory + tscWatchDirectory, + defaultWatchFileKind: () => this.defaultWatchFileKind?.(), }); this.watchFile = watchFile; this.watchDirectory = watchDirectory; @@ -1001,14 +1003,18 @@ interface Array { length: number; [n: number]: T; }` // base folder has to be present const base = getDirectoryPath(file.path); - const folder = this.fs.get(base) as FsFolder; - Debug.assert(isFsFolder(folder)); + const folder = Debug.checkDefined(this.getRealFolder(base)); - if (!this.fs.has(file.path)) { - this.addFileOrFolderInFolder(folder, file); + if (folder.path === base) { + if (!this.fs.has(file.path)) { + this.addFileOrFolderInFolder(folder, file); + } + else { + this.modifyFile(path, content); + } } else { - this.modifyFile(path, content); + this.writeFile(this.realpath(path), content); } } diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts index 7a4a1ea2e000b..3c8af43e812e7 100644 --- a/src/lib/dom.generated.d.ts +++ b/src/lib/dom.generated.d.ts @@ -2,19 +2,24 @@ /// DOM APIs ///////////////////////////// -interface Account { - displayName: string; - id: string; - imageURL?: string; - name?: string; - rpDisplayName: string; -} - interface AddEventListenerOptions extends EventListenerOptions { once?: boolean; passive?: boolean; } +interface AddressErrors { + addressLine?: string; + city?: string; + country?: string; + dependentLocality?: string; + organization?: string; + phone?: string; + postalCode?: string; + recipient?: string; + region?: string; + sortingCode?: string; +} + interface AesCbcParams extends Algorithm { iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer; } @@ -64,13 +69,6 @@ interface AnimationPlaybackEventInit extends EventInit { timelineTime?: number | null; } -interface AssertionOptions { - allowList?: ScopedCredentialDescriptor[]; - extensions?: WebAuthnExtensions; - rpId?: string; - timeoutSeconds?: number; -} - interface AssignedNodesOptions { flatten?: boolean; } @@ -189,15 +187,6 @@ interface ChannelSplitterOptions extends AudioNodeOptions { numberOfOutputs?: number; } -interface ClientData { - challenge: string; - extensions?: WebAuthnExtensions; - hashAlg: string | Algorithm; - origin: string; - rpId: string; - tokenBinding?: string; -} - interface ClientQueryOptions { includeUncontrolled?: boolean; type?: ClientTypes; @@ -345,10 +334,6 @@ interface DelayOptions extends AudioNodeOptions { maxDelayTime?: number; } -interface DeviceLightEventInit extends EventInit { - value?: number; -} - interface DeviceMotionEventAccelerationInit { x?: number | null; y?: number | null; @@ -946,9 +931,14 @@ interface PannerOptions extends AudioNodeOptions { rolloffFactor?: number; } +interface PayerErrors { + email?: string; + name?: string; + phone?: string; +} + interface PaymentCurrencyAmount { currency: string; - currencySystem?: string; value: string; } @@ -972,6 +962,9 @@ interface PaymentDetailsModifier { interface PaymentDetailsUpdate extends PaymentDetailsBase { error?: string; + payerErrors?: PayerErrors; + paymentMethodErrors?: any; + shippingAddressErrors?: AddressErrors; total?: PaymentItem; } @@ -981,17 +974,23 @@ interface PaymentItem { pending?: boolean; } +interface PaymentMethodChangeEventInit extends PaymentRequestUpdateEventInit { + methodDetails?: any; + methodName?: string; +} + interface PaymentMethodData { data?: any; supportedMethods: string | string[]; } interface PaymentOptions { + requestBillingAddress?: boolean; requestPayerEmail?: boolean; requestPayerName?: boolean; requestPayerPhone?: boolean; requestShipping?: boolean; - shippingType?: string; + shippingType?: PaymentShippingType; } interface PaymentRequestUpdateEventInit extends EventInit { @@ -1004,6 +1003,13 @@ interface PaymentShippingOption { selected?: boolean; } +interface PaymentValidationErrors { + error?: string; + payer?: PayerErrors; + paymentMethod?: any; + shippingAddress?: AddressErrors; +} + interface Pbkdf2Params extends Algorithm { hash: HashAlgorithmIdentifier; iterations: number; @@ -1145,7 +1151,7 @@ interface QueuingStrategy { interface QueuingStrategyInit { /** * Creates a new ByteLengthQueuingStrategy with the provided high water mark. - * + * * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. */ highWaterMark: number; @@ -1164,12 +1170,11 @@ interface RTCConfiguration { iceCandidatePoolSize?: number; iceServers?: RTCIceServer[]; iceTransportPolicy?: RTCIceTransportPolicy; - peerIdentity?: string; rtcpMuxPolicy?: RTCRtcpMuxPolicy; } interface RTCDTMFToneChangeEventInit extends EventInit { - tone: string; + tone?: string; } interface RTCDataChannelEventInit extends EventInit { @@ -1182,7 +1187,6 @@ interface RTCDataChannelInit { maxRetransmits?: number; negotiated?: boolean; ordered?: boolean; - priority?: RTCPriorityType; protocol?: string; } @@ -1202,7 +1206,6 @@ interface RTCErrorEventInit extends EventInit { interface RTCErrorInit { errorDetail: RTCErrorDetailType; - httpRequestStatusCode?: number; receivedAlert?: number; sctpCauseCode?: number; sdpLineNumber?: number; @@ -1292,7 +1295,7 @@ interface RTCIceParameters { } interface RTCIceServer { - credential?: string | RTCOAuthCredential; + credential?: string; credentialType?: RTCIceCredentialType; urls: string | string[]; username?: string; @@ -1312,6 +1315,11 @@ interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { packetsReceived?: number; } +interface RTCLocalSessionDescriptionInit { + sdp?: string; + type?: RTCSdpType; +} + interface RTCMediaStreamTrackStats extends RTCStats { audioLevel?: number; echoReturnLoss?: number; @@ -1329,13 +1337,7 @@ interface RTCMediaStreamTrackStats extends RTCStats { trackIdentifier?: string; } -interface RTCOAuthCredential { - accessToken: string; - macKey: string; -} - interface RTCOfferAnswerOptions { - voiceActivityDetection?: boolean; } interface RTCOfferOptions extends RTCOfferAnswerOptions { @@ -1352,8 +1354,9 @@ interface RTCOutboundRTPStreamStats extends RTCRTPStreamStats { } interface RTCPeerConnectionIceErrorEventInit extends EventInit { + address?: string | null; errorCode: number; - hostCandidate?: string; + port?: number | null; statusText?: string; url?: string; } @@ -1418,16 +1421,9 @@ interface RTCRtpContributingSource { timestamp: number; } -interface RTCRtpDecodingParameters extends RTCRtpCodingParameters { -} - interface RTCRtpEncodingParameters extends RTCRtpCodingParameters { active?: boolean; - codecPayloadType?: number; - dtx?: RTCDtxStatus; maxBitrate?: number; - maxFramerate?: number; - ptime?: number; scaleResolutionDownBy?: number; } @@ -1460,7 +1456,6 @@ interface RTCRtpParameters { } interface RTCRtpReceiveParameters extends RTCRtpParameters { - encodings: RTCRtpDecodingParameters[]; } interface RTCRtpRtxParameters { @@ -1468,9 +1463,7 @@ interface RTCRtpRtxParameters { } interface RTCRtpSendParameters extends RTCRtpParameters { - degradationPreference?: RTCDegradationPreference; encodings: RTCRtpEncodingParameters[]; - priority?: RTCPriorityType; transactionId: string; } @@ -1492,7 +1485,7 @@ interface RTCRtpUnhandled { interface RTCSessionDescriptionInit { sdp?: string; - type?: RTCSdpType; + type: RTCSdpType; } interface RTCSrtpKeyParam { @@ -1521,10 +1514,6 @@ interface RTCStats { type?: RTCStatsType; } -interface RTCStatsEventInit extends EventInit { - report: RTCStatsReport; -} - interface RTCStatsReport { } @@ -1567,7 +1556,7 @@ interface ReadableWritablePair { readable: ReadableStream; /** * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. - * + * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. */ writable: WritableStream; @@ -1687,24 +1676,6 @@ interface SVGBoundingBoxOptions { stroke?: boolean; } -interface ScopedCredentialDescriptor { - id: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null; - transports?: Transport[]; - type: ScopedCredentialType; -} - -interface ScopedCredentialOptions { - excludeList?: ScopedCredentialDescriptor[]; - extensions?: WebAuthnExtensions; - rpId?: string; - timeoutSeconds?: number; -} - -interface ScopedCredentialParameters { - algorithm: string | Algorithm; - type: ScopedCredentialType; -} - interface ScrollIntoViewOptions extends ScrollOptions { block?: ScrollLogicalPosition; inline?: ScrollLogicalPosition; @@ -1732,14 +1703,6 @@ interface SecurityPolicyViolationEventInit extends EventInit { violatedDirective?: string; } -interface ServiceWorkerMessageEventInit extends EventInit { - data?: any; - lastEventId?: string; - origin?: string; - ports?: MessagePort[] | null; - source?: ServiceWorker | MessagePort | null; -} - interface ShadowRootInit { delegatesFocus?: boolean; mode: ShadowRootMode; @@ -1812,19 +1775,19 @@ interface StreamPipeOptions { preventCancel?: boolean; /** * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * + * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - * + * * Errors and closures of the source and destination streams propagate as follows: - * + * * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. - * + * * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. - * + * * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - * + * * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. - * + * * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. */ preventClose?: boolean; @@ -1934,9 +1897,6 @@ interface WaveShaperOptions extends AudioNodeOptions { oversample?: OverSampleType; } -interface WebAuthnExtensions { -} - interface WebGLContextAttributes { alpha?: boolean; antialias?: boolean; @@ -3384,7 +3344,7 @@ interface CanvasFilters { interface CanvasGradient { /** * Adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset at one end of the gradient, 1.0 is the offset at the other end. - * + * * Throws an "IndexSizeError" DOMException if the offset is out of range. Throws a "SyntaxError" DOMException if the color cannot be parsed. */ addColorStop(offset: number, color: string): void; @@ -3551,13 +3511,13 @@ declare var CharacterData: { interface ChildNode extends Node { /** * Inserts nodes just after node, while replacing strings in nodes with equivalent Text nodes. - * + * * Throws a "HierarchyRequestError" DOMException if the constraints of the node tree are violated. */ after(...nodes: (Node | string)[]): void; /** * Inserts nodes just before node, while replacing strings in nodes with equivalent Text nodes. - * + * * Throws a "HierarchyRequestError" DOMException if the constraints of the node tree are violated. */ before(...nodes: (Node | string)[]): void; @@ -3567,7 +3527,7 @@ interface ChildNode extends Node { remove(): void; /** * Replaces node with nodes, while replacing strings in nodes with equivalent Text nodes. - * + * * Throws a "HierarchyRequestError" DOMException if the constraints of the node tree are violated. */ replaceWith(...nodes: (Node | string)[]): void; @@ -3871,10 +3831,6 @@ declare var DOMImplementation: { new(): DOMImplementation; }; -interface DOML2DeprecatedColorProperty { - color: string; -} - interface DOMMatrix extends DOMMatrixReadOnly { a: number; b: number; @@ -3985,11 +3941,11 @@ declare var DOMMatrixReadOnly: { interface DOMParser { /** * Parses string using either the HTML or XML parser, according to type, and returns the resulting Document. type can be "text/html" (which will invoke the HTML parser), or any of "text/xml", "application/xml", "application/xhtml+xml", or "image/svg+xml" (which will invoke the XML parser). - * + * * For the XML parser, if string cannot be parsed, then the returned Document will contain elements describing the resulting error. - * + * * Note that script elements are not evaluated during parsing, and the resulting document's encoding will always be UTF-8. - * + * * Values other than the above for type will cause a TypeError exception to be thrown. */ parseFromString(string: string, type: DOMParserSupportedType): Document; @@ -4141,16 +4097,16 @@ interface DOMTokenList { readonly length: number; /** * Returns the associated set as string. - * + * * Can be set, to change the associated attribute. */ value: string; toString(): string; /** * Adds all arguments passed, except those already present. - * + * * Throws a "SyntaxError" DOMException if one of the arguments is the empty string. - * + * * Throws an "InvalidCharacterError" DOMException if one of the arguments contains any ASCII whitespace. */ add(...tokens: string[]): void; @@ -4164,35 +4120,35 @@ interface DOMTokenList { item(index: number): string | null; /** * Removes arguments passed, if they are present. - * + * * Throws a "SyntaxError" DOMException if one of the arguments is the empty string. - * + * * Throws an "InvalidCharacterError" DOMException if one of the arguments contains any ASCII whitespace. */ remove(...tokens: string[]): void; /** * Replaces token with newToken. - * + * * Returns true if token was replaced with newToken, and false otherwise. - * + * * Throws a "SyntaxError" DOMException if one of the arguments is the empty string. - * + * * Throws an "InvalidCharacterError" DOMException if one of the arguments contains any ASCII whitespace. */ replace(oldToken: string, newToken: string): void; /** * Returns true if token is in the associated attribute's supported tokens. Returns false otherwise. - * + * * Throws a TypeError if the associated attribute has no supported tokens defined. */ supports(token: string): boolean; /** * If force is not given, "toggles" token, removing it if it's present and adding it if it's not present. If force is true, adds token (same as add()). If force is false, removes token (same as remove()). - * + * * Returns true if token is now present, and false otherwise. - * + * * Throws a "SyntaxError" DOMException if token is empty. - * + * * Throws an "InvalidCharacterError" DOMException if token contains any spaces. */ toggle(token: string, force?: boolean): boolean; @@ -4222,17 +4178,17 @@ declare var DataCue: { interface DataTransfer { /** * Returns the kind of operation that is currently selected. If the kind of operation isn't one of those that is allowed by the effectAllowed attribute, then the operation will fail. - * + * * Can be set, to change the selected operation. - * + * * The possible values are "none", "copy", "link", and "move". */ dropEffect: "none" | "copy" | "link" | "move"; /** * Returns the kinds of operations that are to be allowed. - * + * * Can be set (during the dragstart event), to change the allowed operations. - * + * * The possible values are "none", "copy", "copyLink", "copyMove", "link", "linkMove", "move", "all", and "uninitialized", */ effectAllowed: "none" | "copy" | "copyLink" | "copyMove" | "link" | "linkMove" | "move" | "all" | "uninitialized"; @@ -4360,16 +4316,6 @@ declare var DeviceAcceleration: { new(): DeviceAcceleration; }; -/** The DeviceLightEvent provides web developers with information from photo sensors or similiar detectors about ambient light levels near the device. For example this may be useful to adjust the screen's brightness based on the current ambient light level in order to save energy or provide better readability. */ -interface DeviceLightEvent extends Event { - readonly value: number; -} - -declare var DeviceLightEvent: { - prototype: DeviceLightEvent; - new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -}; - /** The DeviceMotionEvent provides web developers with information about the speed of changes for the device's position and orientation. */ interface DeviceMotionEvent extends Event { readonly acceleration: DeviceMotionEventAcceleration | null; @@ -4503,15 +4449,15 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad readonly contentType: string; /** * Returns the HTTP cookies that apply to the Document. If there are no cookies or cookies can't be applied to this resource, the empty string will be returned. - * + * * Can be set, to add a new cookie to the element's set of HTTP cookies. - * + * * If the contents are sandboxed into a unique origin (e.g. in an iframe with the sandbox attribute), a "SecurityError" DOMException will be thrown on getting and setting. */ cookie: string; /** * Returns the script element, or the SVG script element, that is currently executing, as long as the element represents a classic script. In the case of reentrant script execution, returns the one that most recently started executing amongst those that have not yet finished executing. - * + * * Returns null if the Document is not currently executing a script or SVG script element (e.g., because the running script is an event handler, or a timeout), or if the currently executing script or SVG script element represents a module script. */ readonly currentScript: HTMLOrSVGScriptElement | null; @@ -4634,7 +4580,7 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad vlinkColor: string; /** * Moves node from another document and returns it. - * + * * If node is a document, throws a "NotSupportedError" DOMException or, if node is a shadow root, throws a "HierarchyRequestError" DOMException. */ adoptNode(source: T): T; @@ -4678,17 +4624,17 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad createElement(tagName: string, options?: ElementCreationOptions): HTMLElement; /** * Returns an element with namespace namespace. Its namespace prefix will be everything before ":" (U+003E) in qualifiedName or null. Its local name will be everything after ":" (U+003E) in qualifiedName or qualifiedName. - * + * * If localName does not match the Name production an "InvalidCharacterError" DOMException will be thrown. - * + * * If one of the following conditions is true a "NamespaceError" DOMException will be thrown: - * + * * localName does not match the QName production. * Namespace prefix is not null and namespace is the empty string. * Namespace prefix is "xml" and namespace is not the XML namespace. * qualifiedName or namespace prefix is "xmlns" and namespace is not the XMLNS namespace. * namespace is the XMLNS namespace and neither qualifiedName nor namespace prefix is "xmlns". - * + * * When supplied, options's is can be used to create a customized built-in element. */ createElementNS(namespaceURI: "http://www.w3.org/1999/xhtml", qualifiedName: string): HTMLElement; @@ -4704,7 +4650,6 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad createEvent(eventInterface: "CloseEvent"): CloseEvent; createEvent(eventInterface: "CompositionEvent"): CompositionEvent; createEvent(eventInterface: "CustomEvent"): CustomEvent; - createEvent(eventInterface: "DeviceLightEvent"): DeviceLightEvent; createEvent(eventInterface: "DeviceMotionEvent"): DeviceMotionEvent; createEvent(eventInterface: "DeviceOrientationEvent"): DeviceOrientationEvent; createEvent(eventInterface: "DragEvent"): DragEvent; @@ -4719,10 +4664,6 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad createEvent(eventInterface: "InputEvent"): InputEvent; createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; createEvent(eventInterface: "ListeningStateChangedEvent"): ListeningStateChangedEvent; - createEvent(eventInterface: "MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; - createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; - createEvent(eventInterface: "MSPointerEvent"): MSPointerEvent; createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; createEvent(eventInterface: "MediaQueryListEvent"): MediaQueryListEvent; @@ -4737,6 +4678,7 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad createEvent(eventInterface: "OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; createEvent(eventInterface: "OverflowEvent"): OverflowEvent; createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface: "PaymentMethodChangeEvent"): PaymentMethodChangeEvent; createEvent(eventInterface: "PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; createEvent(eventInterface: "PermissionRequestedEvent"): PermissionRequestedEvent; createEvent(eventInterface: "PointerEvent"): PointerEvent; @@ -4753,12 +4695,10 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad createEvent(eventInterface: "RTCPeerConnectionIceErrorEvent"): RTCPeerConnectionIceErrorEvent; createEvent(eventInterface: "RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; createEvent(eventInterface: "RTCSsrcConflictEvent"): RTCSsrcConflictEvent; - createEvent(eventInterface: "RTCStatsEvent"): RTCStatsEvent; createEvent(eventInterface: "RTCTrackEvent"): RTCTrackEvent; createEvent(eventInterface: "SVGZoomEvent"): SVGZoomEvent; createEvent(eventInterface: "SVGZoomEvents"): SVGZoomEvent; createEvent(eventInterface: "SecurityPolicyViolationEvent"): SecurityPolicyViolationEvent; - createEvent(eventInterface: "ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; createEvent(eventInterface: "SpeechRecognitionErrorEvent"): SpeechRecognitionErrorEvent; createEvent(eventInterface: "SpeechRecognitionEvent"): SpeechRecognitionEvent; createEvent(eventInterface: "SpeechSynthesisErrorEvent"): SpeechSynthesisErrorEvent; @@ -4849,11 +4789,11 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad getElementsByTagName(qualifiedName: string): HTMLCollectionOf; /** * If namespace and localName are "*" returns a HTMLCollection of all descendant elements. - * + * * If only namespace is "*" returns a HTMLCollection of all descendant elements whose local name is localName. - * + * * If only localName is "*" returns a HTMLCollection of all descendant elements whose namespace is namespace. - * + * * Otherwise, returns a HTMLCollection of all descendant elements whose namespace is namespace and local name is localName. */ getElementsByTagNameNS(namespaceURI: "http://www.w3.org/1999/xhtml", localName: string): HTMLCollectionOf; @@ -4869,7 +4809,7 @@ interface Document extends Node, DocumentAndElementEventHandlers, DocumentOrShad hasFocus(): boolean; /** * Returns a copy of node. If deep is true, the copy also includes the node's descendants. - * + * * If node is a document or a shadow root, throws a "NotSupportedError" DOMException. */ importNode(importedNode: T, deep: boolean): T; @@ -4954,7 +4894,6 @@ interface DocumentEvent { createEvent(eventInterface: "CloseEvent"): CloseEvent; createEvent(eventInterface: "CompositionEvent"): CompositionEvent; createEvent(eventInterface: "CustomEvent"): CustomEvent; - createEvent(eventInterface: "DeviceLightEvent"): DeviceLightEvent; createEvent(eventInterface: "DeviceMotionEvent"): DeviceMotionEvent; createEvent(eventInterface: "DeviceOrientationEvent"): DeviceOrientationEvent; createEvent(eventInterface: "DragEvent"): DragEvent; @@ -4969,10 +4908,6 @@ interface DocumentEvent { createEvent(eventInterface: "InputEvent"): InputEvent; createEvent(eventInterface: "KeyboardEvent"): KeyboardEvent; createEvent(eventInterface: "ListeningStateChangedEvent"): ListeningStateChangedEvent; - createEvent(eventInterface: "MSGestureEvent"): MSGestureEvent; - createEvent(eventInterface: "MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent; - createEvent(eventInterface: "MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent; - createEvent(eventInterface: "MSPointerEvent"): MSPointerEvent; createEvent(eventInterface: "MediaEncryptedEvent"): MediaEncryptedEvent; createEvent(eventInterface: "MediaKeyMessageEvent"): MediaKeyMessageEvent; createEvent(eventInterface: "MediaQueryListEvent"): MediaQueryListEvent; @@ -4987,6 +4922,7 @@ interface DocumentEvent { createEvent(eventInterface: "OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; createEvent(eventInterface: "OverflowEvent"): OverflowEvent; createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; + createEvent(eventInterface: "PaymentMethodChangeEvent"): PaymentMethodChangeEvent; createEvent(eventInterface: "PaymentRequestUpdateEvent"): PaymentRequestUpdateEvent; createEvent(eventInterface: "PermissionRequestedEvent"): PermissionRequestedEvent; createEvent(eventInterface: "PointerEvent"): PointerEvent; @@ -5003,12 +4939,10 @@ interface DocumentEvent { createEvent(eventInterface: "RTCPeerConnectionIceErrorEvent"): RTCPeerConnectionIceErrorEvent; createEvent(eventInterface: "RTCPeerConnectionIceEvent"): RTCPeerConnectionIceEvent; createEvent(eventInterface: "RTCSsrcConflictEvent"): RTCSsrcConflictEvent; - createEvent(eventInterface: "RTCStatsEvent"): RTCStatsEvent; createEvent(eventInterface: "RTCTrackEvent"): RTCTrackEvent; createEvent(eventInterface: "SVGZoomEvent"): SVGZoomEvent; createEvent(eventInterface: "SVGZoomEvents"): SVGZoomEvent; createEvent(eventInterface: "SecurityPolicyViolationEvent"): SecurityPolicyViolationEvent; - createEvent(eventInterface: "ServiceWorkerMessageEvent"): ServiceWorkerMessageEvent; createEvent(eventInterface: "SpeechRecognitionErrorEvent"): SpeechRecognitionErrorEvent; createEvent(eventInterface: "SpeechRecognitionEvent"): SpeechRecognitionEvent; createEvent(eventInterface: "SpeechSynthesisErrorEvent"): SpeechSynthesisErrorEvent; @@ -5256,7 +5190,7 @@ interface Element extends Node, Animatable, ChildNode, InnerHTML, NonDocumentTyp removeAttributeNode(attr: Attr): Attr; /** * Displays element fullscreen and resolves promise when done. - * + * * When supplied, options's navigationUI member indicates whether showing navigation UI while in fullscreen is preferred or not. If set to "show", navigation simplicity is preferred over screen space, and if set to "hide", more screen space is preferred. User agents are always free to honor user preference over the application's. The default value "auto" indicates no application preference. */ requestFullscreen(options?: FullscreenOptions): Promise; @@ -5281,7 +5215,7 @@ interface Element extends Node, Animatable, ChildNode, InnerHTML, NonDocumentTyp setPointerCapture(pointerId: number): void; /** * If force is not given, "toggles" qualifiedName, removing it if it is present and adding it if it is not present. If force is true, adds qualifiedName. If force is false, removes qualifiedName. - * + * * Returns true if qualifiedName is now present, and false otherwise. */ toggleAttribute(qualifiedName: string, force?: boolean): boolean; @@ -5451,15 +5385,15 @@ declare var EventSource: { interface EventTarget { /** * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. - * + * * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. - * + * * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. - * + * * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. - * + * * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. - * + * * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. */ addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; @@ -6126,9 +6060,9 @@ interface HTMLAllCollection { item(nameOrIndex?: string): HTMLCollection | Element | null; /** * Returns the item with ID or name name from the collection. - * + * * If there are multiple matching items, then an HTMLCollection object containing all those elements is returned. - * + * * Only button, form, iframe, input, map, meta, object, select, and textarea elements can have a name for the purpose of this method; their name is given by the value of their name attribute. */ namedItem(name: string): HTMLCollection | Element | null; @@ -6340,29 +6274,6 @@ declare var HTMLBaseElement: { new(): HTMLBaseElement; }; -/** Provides special properties (beyond the regular HTMLElement interface it also has available to it by inheritance) for manipulating elements. */ -interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty { - /** - * Sets or retrieves the current typeface family. - */ - /** @deprecated */ - face: string; - /** - * Sets or retrieves the font size of the object. - */ - /** @deprecated */ - size: number; - addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; - removeEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; - removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; -} - -declare var HTMLBaseFontElement: { - prototype: HTMLBaseFontElement; - new(): HTMLBaseFontElement; -}; - interface HTMLBodyElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap { "orientationchange": Event; } @@ -6789,7 +6700,7 @@ declare var HTMLFontElement: { interface HTMLFormControlsCollection extends HTMLCollectionBase { /** * Returns the item with ID or name name from the collection. - * + * * If there are multiple matching items, then a RadioNodeList object containing all those elements is returned. */ namedItem(name: string): RadioNodeList | Element | null; @@ -8038,25 +7949,25 @@ declare var HTMLOptionElement: { interface HTMLOptionsCollection extends HTMLCollectionOf { /** * Returns the number of elements in the collection. - * + * * When set to a smaller number, truncates the number of option elements in the corresponding container. - * + * * When set to a greater number, adds new blank option elements to that container. */ length: number; /** * Returns the index of the first selected item, if any, or −1 if there is no selected item. - * + * * Can be set, to change the selection. */ selectedIndex: number; /** * Inserts element before the node given by before. - * + * * The before argument can be a number, in which case element is inserted before the item with that number, or an element from the collection, in which case element is inserted before that element. - * + * * If before is omitted, null, or a number out of range, then element will be added at the end of the list. - * + * * This method will throw a "HierarchyRequestError" DOMException if element is an ancestor of the element into which it is to be inserted. */ add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void; @@ -9135,15 +9046,15 @@ interface IDBCursor { continuePrimaryKey(key: IDBValidKey, primaryKey: IDBValidKey): void; /** * Delete the record pointed at by the cursor with a new value. - * + * * If successful, request's result will be undefined. */ delete(): IDBRequest; /** * Updated the record pointed at by the cursor with a new value. - * + * * Throws a "DataError" DOMException if the effective object store uses in-line keys and the key would have changed. - * + * * If successful, request's result will be the record's key. */ update(value: any): IDBRequest; @@ -9198,13 +9109,13 @@ interface IDBDatabase extends EventTarget { close(): void; /** * Creates a new object store with the given name and options and returns a new IDBObjectStore. - * + * * Throws a "InvalidStateError" DOMException if not called within an upgrade transaction. */ createObjectStore(name: string, options?: IDBObjectStoreParameters): IDBObjectStore; /** * Deletes the object store with the given name. - * + * * Throws a "InvalidStateError" DOMException if not called within an upgrade transaction. */ deleteObjectStore(name: string): void; @@ -9227,7 +9138,7 @@ declare var IDBDatabase: { interface IDBFactory { /** * Compares two values as keys. Returns -1 if key1 precedes key2, 1 if key2 precedes key1, and 0 if the keys are equal. - * + * * Throws a "DataError" DOMException if either input is not a valid key. */ cmp(first: any, second: any): number; @@ -9261,43 +9172,43 @@ interface IDBIndex { readonly unique: boolean; /** * Retrieves the number of records matching the given key or key range in query. - * + * * If successful, request's result will be the count. */ count(key?: IDBValidKey | IDBKeyRange): IDBRequest; /** * Retrieves the value of the first record matching the given key or key range in query. - * + * * If successful, request's result will be the value, or undefined if there was no matching record. */ get(key: IDBValidKey | IDBKeyRange): IDBRequest; /** * Retrieves the values of the records matching the given key or key range in query (up to count if given). - * + * * If successful, request's result will be an Array of the values. */ getAll(query?: IDBValidKey | IDBKeyRange | null, count?: number): IDBRequest; /** * Retrieves the keys of records matching the given key or key range in query (up to count if given). - * + * * If successful, request's result will be an Array of the keys. */ getAllKeys(query?: IDBValidKey | IDBKeyRange | null, count?: number): IDBRequest; /** * Retrieves the key of the first record matching the given key or key range in query. - * + * * If successful, request's result will be the key, or undefined if there was no matching record. */ getKey(key: IDBValidKey | IDBKeyRange): IDBRequest; /** * Opens a cursor over the records matching query, ordered by direction. If query is null, all records in index are matched. - * + * * If successful, request's result will be an IDBCursorWithValue, or null if there were no matching records. */ openCursor(query?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; /** * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in index are matched. - * + * * If successful, request's result will be an IDBCursor, or null if there were no matching records. */ openKeyCursor(query?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; @@ -9377,88 +9288,88 @@ interface IDBObjectStore { readonly transaction: IDBTransaction; /** * Adds or updates a record in store with the given value and key. - * + * * If the store uses in-line keys and key is specified a "DataError" DOMException will be thrown. - * + * * If put() is used, any existing record with the key will be replaced. If add() is used, and if a record with the key already exists the request will fail, with request's error set to a "ConstraintError" DOMException. - * + * * If successful, request's result will be the record's key. */ add(value: any, key?: IDBValidKey): IDBRequest; /** * Deletes all records in store. - * + * * If successful, request's result will be undefined. */ clear(): IDBRequest; /** * Retrieves the number of records matching the given key or key range in query. - * + * * If successful, request's result will be the count. */ count(key?: IDBValidKey | IDBKeyRange): IDBRequest; /** * Creates a new index in store with the given name, keyPath and options and returns a new IDBIndex. If the keyPath and options define constraints that cannot be satisfied with the data already in store the upgrade transaction will abort with a "ConstraintError" DOMException. - * + * * Throws an "InvalidStateError" DOMException if not called within an upgrade transaction. */ createIndex(name: string, keyPath: string | string[], options?: IDBIndexParameters): IDBIndex; /** * Deletes records in store with the given key or in the given key range in query. - * + * * If successful, request's result will be undefined. */ delete(key: IDBValidKey | IDBKeyRange): IDBRequest; /** * Deletes the index in store with the given name. - * + * * Throws an "InvalidStateError" DOMException if not called within an upgrade transaction. */ deleteIndex(name: string): void; /** * Retrieves the value of the first record matching the given key or key range in query. - * + * * If successful, request's result will be the value, or undefined if there was no matching record. */ get(query: IDBValidKey | IDBKeyRange): IDBRequest; /** * Retrieves the values of the records matching the given key or key range in query (up to count if given). - * + * * If successful, request's result will be an Array of the values. */ getAll(query?: IDBValidKey | IDBKeyRange | null, count?: number): IDBRequest; /** * Retrieves the keys of records matching the given key or key range in query (up to count if given). - * + * * If successful, request's result will be an Array of the keys. */ getAllKeys(query?: IDBValidKey | IDBKeyRange | null, count?: number): IDBRequest; /** * Retrieves the key of the first record matching the given key or key range in query. - * + * * If successful, request's result will be the key, or undefined if there was no matching record. */ getKey(query: IDBValidKey | IDBKeyRange): IDBRequest; index(name: string): IDBIndex; /** * Opens a cursor over the records matching query, ordered by direction. If query is null, all records in store are matched. - * + * * If successful, request's result will be an IDBCursorWithValue pointing at the first matching record, or null if there were no matching records. */ openCursor(query?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; /** * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in store are matched. - * + * * If successful, request's result will be an IDBCursor pointing at the first matching record, or null if there were no matching records. */ openKeyCursor(query?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; /** * Adds or updates a record in store with the given value and key. - * + * * If the store uses in-line keys and key is specified a "DataError" DOMException will be thrown. - * + * * If put() is used, any existing record with the key will be replaced. If add() is used, and if a record with the key already exists the request will fail, with request's error set to a "ConstraintError" DOMException. - * + * * If successful, request's result will be the record's key. */ put(value: any, key?: IDBValidKey): IDBRequest; @@ -9778,25 +9689,25 @@ interface Location { readonly ancestorOrigins: DOMStringList; /** * Returns the Location object's URL's fragment (includes leading "#" if non-empty). - * + * * Can be set, to navigate to the same URL with a changed fragment (ignores leading "#"). */ hash: string; /** * Returns the Location object's URL's host and port (if different from the default port for the scheme). - * + * * Can be set, to navigate to the same URL with a changed host and port. */ host: string; /** * Returns the Location object's URL's host. - * + * * Can be set, to navigate to the same URL with a changed host. */ hostname: string; /** * Returns the Location object's URL. - * + * * Can be set, to navigate to the given URL. */ href: string; @@ -9807,25 +9718,25 @@ interface Location { readonly origin: string; /** * Returns the Location object's URL's path. - * + * * Can be set, to navigate to the same URL with a changed path. */ pathname: string; /** * Returns the Location object's URL's port. - * + * * Can be set, to navigate to the same URL with a changed port. */ port: string; /** * Returns the Location object's URL's scheme. - * + * * Can be set, to navigate to the same URL with a changed scheme. */ protocol: string; /** * Returns the Location object's URL's query (includes leading "?" if non-empty). - * + * * Can be set, to navigate to the same URL with a changed query (ignores leading "?"). */ search: string; @@ -9918,43 +9829,6 @@ declare var MSGesture: { new(): MSGesture; }; -/** The MSGestureEvent is a proprietary interface specific to Internet Explorer and Microsoft Edge which represents events that occur due to touch gestures. Events using this interface include MSGestureStart, MSGestureEnd, MSGestureTap, MSGestureHold, MSGestureChange, and MSInertiaStart. */ -interface MSGestureEvent extends UIEvent { - readonly clientX: number; - readonly clientY: number; - readonly expansion: number; - readonly gestureObject: any; - readonly hwTimestamp: number; - readonly offsetX: number; - readonly offsetY: number; - readonly rotation: number; - readonly scale: number; - readonly screenX: number; - readonly screenY: number; - readonly translationX: number; - readonly translationY: number; - readonly velocityAngular: number; - readonly velocityExpansion: number; - readonly velocityX: number; - readonly velocityY: number; - initGestureEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void; - readonly MSGESTURE_FLAG_BEGIN: number; - readonly MSGESTURE_FLAG_CANCEL: number; - readonly MSGESTURE_FLAG_END: number; - readonly MSGESTURE_FLAG_INERTIA: number; - readonly MSGESTURE_FLAG_NONE: number; -} - -declare var MSGestureEvent: { - prototype: MSGestureEvent; - new(): MSGestureEvent; - readonly MSGESTURE_FLAG_BEGIN: number; - readonly MSGESTURE_FLAG_CANCEL: number; - readonly MSGESTURE_FLAG_END: number; - readonly MSGESTURE_FLAG_INERTIA: number; - readonly MSGESTURE_FLAG_NONE: number; -}; - /** The msGraphicsTrust() constructor returns an object that provides properties for info on protected video playback. */ interface MSGraphicsTrust { readonly constrictionActive: boolean; @@ -10016,25 +9890,6 @@ declare var MSMediaKeyError: { readonly MS_MEDIA_KEYERR_UNKNOWN: number; }; -interface MSMediaKeyMessageEvent extends Event { - readonly destinationURL: string | null; - readonly message: Uint8Array; -} - -declare var MSMediaKeyMessageEvent: { - prototype: MSMediaKeyMessageEvent; - new(): MSMediaKeyMessageEvent; -}; - -interface MSMediaKeyNeededEvent extends Event { - readonly initData: Uint8Array | null; -} - -declare var MSMediaKeyNeededEvent: { - prototype: MSMediaKeyNeededEvent; - new(): MSMediaKeyNeededEvent; -}; - interface MSMediaKeySession extends EventTarget { readonly error: MSMediaKeyError | null; readonly keySystem: string; @@ -10069,29 +9924,6 @@ interface MSNavigatorDoNotTrack { storeWebWideTrackingException(args: StoreExceptionsInformation): void; } -interface MSPointerEvent extends MouseEvent { - readonly currentPoint: any; - readonly height: number; - readonly hwTimestamp: number; - readonly intermediatePoints: any; - readonly isPrimary: boolean; - readonly pointerId: number; - readonly pointerType: any; - readonly pressure: number; - readonly rotation: number; - readonly tiltX: number; - readonly tiltY: number; - readonly width: number; - getCurrentPoint(element: Element): void; - getIntermediatePoints(element: Element): void; - initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void; -} - -declare var MSPointerEvent: { - prototype: MSPointerEvent; - new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -}; - interface MSStream { readonly type: string; msClose(): void; @@ -10416,7 +10248,6 @@ declare var MediaStreamEvent: { interface MediaStreamTrackEventMap { "ended": Event; - "isolationchange": Event; "mute": Event; "unmute": Event; } @@ -10425,12 +10256,10 @@ interface MediaStreamTrackEventMap { interface MediaStreamTrack extends EventTarget { enabled: boolean; readonly id: string; - readonly isolated: boolean; readonly kind: string; readonly label: string; readonly muted: boolean; onended: ((this: MediaStreamTrack, ev: Event) => any) | null; - onisolationchange: ((this: MediaStreamTrack, ev: Event) => any) | null; onmute: ((this: MediaStreamTrack, ev: Event) => any) | null; onunmute: ((this: MediaStreamTrack, ev: Event) => any) | null; readonly readyState: MediaStreamTrackState; @@ -10530,7 +10359,7 @@ interface MessagePort extends EventTarget { close(): void; /** * Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side. - * + * * Throws a "DataCloneError" DOMException if transfer contains duplicate objects or port, or if message could not be cloned. */ postMessage(message: any, transfer: Transferable[]): void; @@ -10648,7 +10477,7 @@ interface MutationObserver { disconnect(): void; /** * Instructs the user agent to observe a given target (a node) and report any mutations based on the criteria given by options (an object). - * + * * The options argument allows for setting mutation observation options via object members. */ observe(target: Node, options?: MutationObserverInit): void; @@ -11238,27 +11067,27 @@ declare var OfflineAudioContext: { interface OffscreenCanvas extends EventTarget { /** * These attributes return the dimensions of the OffscreenCanvas object's bitmap. - * + * * They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it). */ height: number; /** * These attributes return the dimensions of the OffscreenCanvas object's bitmap. - * + * * They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it). */ width: number; /** * Returns a promise that will fulfill with a new Blob object representing a file containing the image in the OffscreenCanvas object. - * + * * The argument, if provided, is a dictionary that controls the encoding options of the image file to be created. The type field specifies the file format and has a default value of "image/png"; that type is also used if the requested type isn't supported. If the image format supports variable quality (such as "image/jpeg"), then the quality field is a number in the range 0.0 to 1.0 inclusive indicating the desired quality level for the resulting image. */ convertToBlob(options?: ImageEncodeOptions): Promise; /** * Returns an object that exposes an API for drawing on the OffscreenCanvas object. contextId specifies the desired API: "2d", "bitmaprenderer", "webgl", or "webgl2". options is handled by that API. - * + * * This specification defines the "2d" context below, which is similar but distinct from the "2d" context that is created from a canvas element. The WebGL specifications define the "webgl" and "webgl2" contexts. [WEBGL] - * + * * Returns null if the canvas has already been initialized with another context type (e.g., trying to get a "2d" context after getting a "webgl" context). */ getContext(contextId: "2d", options?: CanvasRenderingContext2DSettings): OffscreenCanvasRenderingContext2D | null; @@ -11334,11 +11163,11 @@ declare var OverflowEvent: { interface PageTransitionEvent extends Event { /** * For the pageshow event, returns false if the page is newly being loaded (and the load event will fire). Otherwise, returns true. - * + * * For the pagehide event, returns false if the page is going away for the last time. Otherwise, returns true, meaning that (if nothing conspires to make the page unsalvageable) the page might be reused if the user navigates back to this page. - * + * * Things that can cause the page to be unsalvageable include: - * + * * Listening for beforeunload events * Listening for unload events * Having iframes that are not salvageable @@ -11396,13 +11225,13 @@ interface ParentNode { readonly lastElementChild: Element | null; /** * Inserts nodes after the last child of node, while replacing strings in nodes with equivalent Text nodes. - * + * * Throws a "HierarchyRequestError" DOMException if the constraints of the node tree are violated. */ append(...nodes: (Node | string)[]): void; /** * Inserts nodes before the first child of node, while replacing strings in nodes with equivalent Text nodes. - * + * * Throws a "HierarchyRequestError" DOMException if the constraints of the node tree are violated. */ prepend(...nodes: (Node | string)[]): void; @@ -11435,11 +11264,10 @@ declare var Path2D: { /** This Payment Request API interface is used to store shipping or payment address information. */ interface PaymentAddress { - readonly addressLine: string[]; + readonly addressLine: ReadonlyArray; readonly city: string; readonly country: string; readonly dependentLocality: string; - readonly languageCode: string; readonly organization: string; readonly phone: string; readonly postalCode: string; @@ -11454,7 +11282,18 @@ declare var PaymentAddress: { new(): PaymentAddress; }; +interface PaymentMethodChangeEvent extends PaymentRequestUpdateEvent { + readonly methodDetails: any; + readonly methodName: string; +} + +declare var PaymentMethodChangeEvent: { + prototype: PaymentMethodChangeEvent; + new(type: string, eventInitDict?: PaymentMethodChangeEventInit): PaymentMethodChangeEvent; +}; + interface PaymentRequestEventMap { + "paymentmethodchange": Event; "shippingaddresschange": Event; "shippingoptionchange": Event; } @@ -11462,6 +11301,7 @@ interface PaymentRequestEventMap { /** This Payment Request API interface is the primary access point into the API, and lets web content and apps accept payments from the end user. */ interface PaymentRequest extends EventTarget { readonly id: string; + onpaymentmethodchange: ((this: PaymentRequest, ev: Event) => any) | null; onshippingaddresschange: ((this: PaymentRequest, ev: Event) => any) | null; onshippingoptionchange: ((this: PaymentRequest, ev: Event) => any) | null; readonly shippingAddress: PaymentAddress | null; @@ -11469,7 +11309,7 @@ interface PaymentRequest extends EventTarget { readonly shippingType: PaymentShippingType | null; abort(): Promise; canMakePayment(): Promise; - show(): Promise; + show(detailsPromise: PaymentDetailsUpdate | Promise): Promise; addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -11491,10 +11331,15 @@ declare var PaymentRequestUpdateEvent: { new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; }; +interface PaymentResponseEventMap { + "payerdetailchange": Event; +} + /** This Payment Request API interface is returned after a user selects a payment method and approves a payment request. */ -interface PaymentResponse { +interface PaymentResponse extends EventTarget { readonly details: any; readonly methodName: string; + onpayerdetailchange: ((this: PaymentResponse, ev: Event) => any) | null; readonly payerEmail: string | null; readonly payerName: string | null; readonly payerPhone: string | null; @@ -11502,7 +11347,12 @@ interface PaymentResponse { readonly shippingAddress: PaymentAddress | null; readonly shippingOption: string | null; complete(result?: PaymentComplete): Promise; + retry(errorFields?: PaymentValidationErrors): Promise; toJSON(): any; + addEventListener(type: K, listener: (this: PaymentResponse, ev: PaymentResponseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: PaymentResponse, ev: PaymentResponseEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var PaymentResponse: { @@ -11956,7 +11806,6 @@ interface RTCCertificate { declare var RTCCertificate: { prototype: RTCCertificate; new(): RTCCertificate; - getSupportedAlgorithms(): AlgorithmIdentifier[]; }; interface RTCDTMFSenderEventMap { @@ -11986,7 +11835,7 @@ interface RTCDTMFToneChangeEvent extends Event { declare var RTCDTMFToneChangeEvent: { prototype: RTCDTMFToneChangeEvent; - new(type: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; + new(type: string, eventInitDict?: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent; }; interface RTCDataChannelEventMap { @@ -11998,7 +11847,7 @@ interface RTCDataChannelEventMap { } interface RTCDataChannel extends EventTarget { - binaryType: string; + binaryType: BinaryType; readonly bufferedAmount: number; bufferedAmountLowThreshold: number; readonly id: number | null; @@ -12012,7 +11861,6 @@ interface RTCDataChannel extends EventTarget { onmessage: ((this: RTCDataChannel, ev: MessageEvent) => any) | null; onopen: ((this: RTCDataChannel, ev: Event) => any) | null; readonly ordered: boolean; - readonly priority: RTCPriorityType; readonly protocol: string; readonly readyState: RTCDataChannelState; close(): void; @@ -12096,7 +11944,6 @@ declare var RTCDtmfSender: { interface RTCError extends DOMException { readonly errorDetail: RTCErrorDetailType; - readonly httpRequestStatusCode: number | null; readonly receivedAlert: number | null; readonly sctpCauseCode: number | null; readonly sdpLineNumber: number | null; @@ -12189,7 +12036,6 @@ interface RTCIceTransportEventMap { /** Provides access to information about the ICE transport layer over which the data is being sent and received. */ interface RTCIceTransport extends EventTarget { - readonly component: RTCIceComponent; readonly gatheringState: RTCIceGathererState; ongatheringstatechange: ((this: RTCIceTransport, ev: Event) => any) | null; onselectedcandidatepairchange: ((this: RTCIceTransport, ev: Event) => any) | null; @@ -12240,7 +12086,6 @@ interface RTCPeerConnectionEventMap { "icegatheringstatechange": Event; "negotiationneeded": Event; "signalingstatechange": Event; - "statsended": RTCStatsEvent; "track": RTCTrackEvent; } @@ -12263,7 +12108,6 @@ interface RTCPeerConnection extends EventTarget { onicegatheringstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; onnegotiationneeded: ((this: RTCPeerConnection, ev: Event) => any) | null; onsignalingstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null; - onstatsended: ((this: RTCPeerConnection, ev: RTCStatsEvent) => any) | null; ontrack: ((this: RTCPeerConnection, ev: RTCTrackEvent) => any) | null; readonly peerIdentity: Promise; readonly pendingLocalDescription: RTCSessionDescription | null; @@ -12285,9 +12129,10 @@ interface RTCPeerConnection extends EventTarget { getStats(selector?: MediaStreamTrack | null): Promise; getTransceivers(): RTCRtpTransceiver[]; removeTrack(sender: RTCRtpSender): void; - setConfiguration(configuration: RTCConfiguration): void; + restartIce(): void; + setConfiguration(configuration?: RTCConfiguration): void; setIdentityProvider(provider: string, options?: RTCIdentityProviderOptions): void; - setLocalDescription(description: RTCSessionDescriptionInit): Promise; + setLocalDescription(description?: RTCSessionDescriptionInit): Promise; setRemoteDescription(description: RTCSessionDescriptionInit): Promise; addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -12299,13 +12144,13 @@ declare var RTCPeerConnection: { prototype: RTCPeerConnection; new(configuration?: RTCConfiguration): RTCPeerConnection; generateCertificate(keygenAlgorithm: AlgorithmIdentifier): Promise; - getDefaultIceServers(): RTCIceServer[]; }; interface RTCPeerConnectionIceErrorEvent extends Event { + readonly address: string | null; readonly errorCode: number; readonly errorText: string; - readonly hostCandidate: string; + readonly port: number | null; readonly url: string; } @@ -12317,7 +12162,6 @@ declare var RTCPeerConnectionIceErrorEvent: { /** Events that occurs in relation to ICE candidates with the target, usually an RTCPeerConnection. Only one event is of this type: icecandidate. */ interface RTCPeerConnectionIceEvent extends Event { readonly candidate: RTCIceCandidate | null; - readonly url: string | null; } declare var RTCPeerConnectionIceEvent: { @@ -12327,7 +12171,6 @@ declare var RTCPeerConnectionIceEvent: { /** This WebRTC API interface manages the reception and decoding of data for a MediaStreamTrack on an RTCPeerConnection. */ interface RTCRtpReceiver { - readonly rtcpTransport: RTCDtlsTransport | null; readonly track: MediaStreamTrack; readonly transport: RTCDtlsTransport | null; getContributingSources(): RTCRtpContributingSource[]; @@ -12345,7 +12188,6 @@ declare var RTCRtpReceiver: { /** Provides the ability to control and obtain details about how a particular MediaStreamTrack is encoded and sent to a remote peer. */ interface RTCRtpSender { readonly dtmf: RTCDTMFSender | null; - readonly rtcpTransport: RTCDtlsTransport | null; readonly track: MediaStreamTrack | null; readonly transport: RTCDtlsTransport | null; getParameters(): RTCRtpSendParameters; @@ -12406,7 +12248,7 @@ interface RTCSessionDescription { declare var RTCSessionDescription: { prototype: RTCSessionDescription; - new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; + new(descriptionInitDict: RTCSessionDescriptionInit): RTCSessionDescription; }; interface RTCSrtpSdesTransportEventMap { @@ -12437,15 +12279,6 @@ declare var RTCSsrcConflictEvent: { new(): RTCSsrcConflictEvent; }; -interface RTCStatsEvent extends Event { - readonly report: RTCStatsReport; -} - -declare var RTCStatsEvent: { - prototype: RTCStatsEvent; - new(type: string, eventInitDict: RTCStatsEventInit): RTCStatsEvent; -}; - interface RTCStatsProvider extends EventTarget { getStats(): Promise; msGetStats(): Promise; @@ -13927,46 +13760,6 @@ declare var SVGNumberList: { interface SVGPathElement extends SVGGraphicsElement { /** @deprecated */ readonly pathSegList: SVGPathSegList; - /** @deprecated */ - createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs; - /** @deprecated */ - createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel; - /** @deprecated */ - createSVGPathSegClosePath(): SVGPathSegClosePath; - /** @deprecated */ - createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; - /** @deprecated */ - createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; - /** @deprecated */ - createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; - /** @deprecated */ - createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; - /** @deprecated */ - createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; - /** @deprecated */ - createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; - /** @deprecated */ - createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; - /** @deprecated */ - createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; - /** @deprecated */ - createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; - /** @deprecated */ - createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; - /** @deprecated */ - createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; - /** @deprecated */ - createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; - /** @deprecated */ - createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; - /** @deprecated */ - createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; - /** @deprecated */ - createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; - /** @deprecated */ - createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; - /** @deprecated */ - getPathSegAtLength(distance: number): number; getPointAtLength(distance: number): SVGPoint; getTotalLength(): number; addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -14404,25 +14197,11 @@ interface SVGSVGElementEventMap extends SVGElementEventMap { /** Provides access to the properties of elements, as well as methods to manipulate them. This interface contains also various miscellaneous commonly-used utility methods, such as matrix operations and the ability to control the time of redraw on visual rendering devices. */ interface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewBox, SVGZoomAndPan { - /** @deprecated */ - contentScriptType: string; - /** @deprecated */ - contentStyleType: string; currentScale: number; readonly currentTranslate: SVGPoint; readonly height: SVGAnimatedLength; onunload: ((this: SVGSVGElement, ev: Event) => any) | null; onzoom: ((this: SVGSVGElement, ev: SVGZoomEvent) => any) | null; - /** @deprecated */ - readonly pixelUnitToMillimeterX: number; - /** @deprecated */ - readonly pixelUnitToMillimeterY: number; - /** @deprecated */ - readonly screenPixelToMillimeterX: number; - /** @deprecated */ - readonly screenPixelToMillimeterY: number; - /** @deprecated */ - readonly viewport: SVGRect; readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; @@ -14750,9 +14529,7 @@ declare var SVGUnitTypes: { /** Corresponds to the element. */ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { - readonly animatedInstanceRoot: SVGElementInstance | null; readonly height: SVGAnimatedLength; - readonly instanceRoot: SVGElementInstance | null; readonly width: SVGAnimatedLength; readonly x: SVGAnimatedLength; readonly y: SVGAnimatedLength; @@ -14785,16 +14562,12 @@ declare var SVGViewElement: { readonly SVG_ZOOMANDPAN_UNKNOWN: number; }; -/** Used to reflect the zoomAndPan attribute, and is mixed in to other interfaces for elements that support this attribute. */ interface SVGZoomAndPan { - readonly zoomAndPan: number; -} - -declare var SVGZoomAndPan: { + zoomAndPan: number; readonly SVG_ZOOMANDPAN_DISABLE: number; readonly SVG_ZOOMANDPAN_MAGNIFY: number; readonly SVG_ZOOMANDPAN_UNKNOWN: number; -}; +} interface SVGZoomEvent extends UIEvent { readonly newScale: number; @@ -14809,26 +14582,6 @@ declare var SVGZoomEvent: { new(): SVGZoomEvent; }; -interface ScopedCredential { - readonly id: ArrayBuffer; - readonly type: ScopedCredentialType; -} - -declare var ScopedCredential: { - prototype: ScopedCredential; - new(): ScopedCredential; -}; - -interface ScopedCredentialInfo { - readonly credential: ScopedCredential; - readonly publicKey: CryptoKey; -} - -declare var ScopedCredentialInfo: { - prototype: ScopedCredentialInfo; - new(): ScopedCredentialInfo; -}; - /** A screen, usually the one on which the current window is being rendered, and is obtained using window.screen. */ interface Screen { readonly availHeight: number; @@ -14996,22 +14749,6 @@ declare var ServiceWorkerContainer: { new(): ServiceWorkerContainer; }; -/** This ServiceWorker API interface contains information about an event sent to a ServiceWorkerContainer target. This extends the default message event to allow setting a ServiceWorker object as the source of a message. The event object is accessed via the handler function of a message event, when fired by a message received from a service worker. - * @deprecated In modern browsers, this interface has been deprecated. Service worker messages will now use the MessageEvent interface, for consistency with other web messaging features. - */ -interface ServiceWorkerMessageEvent extends Event { - readonly data: any; - readonly lastEventId: string; - readonly origin: string; - readonly ports: ReadonlyArray | null; - readonly source: ServiceWorker | MessagePort | null; -} - -declare var ServiceWorkerMessageEvent: { - prototype: ServiceWorkerMessageEvent; - new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent; -}; - interface ServiceWorkerRegistrationEventMap { "updatefound": Event; } @@ -15394,7 +15131,7 @@ interface Storage { removeItem(key: string): void; /** * Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously. - * + * * Throws a "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.) */ setItem(key: string, value: string): void; @@ -15544,7 +15281,7 @@ declare var Text: { interface TextDecoder extends TextDecoderCommon { /** * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. - * + * * ``` * var string = "", decoder = new TextDecoder(encoding), buffer; * while(buffer = next_chunk()) { @@ -15552,7 +15289,7 @@ interface TextDecoder extends TextDecoderCommon { * } * string += decoder.decode(); // end-of-queue * ``` - * + * * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. */ decode(input?: BufferSource, options?: TextDecodeOptions): string; @@ -15670,34 +15407,6 @@ interface TextMetrics { * Returns the measurement described below. */ readonly actualBoundingBoxRight: number; - /** - * Returns the measurement described below. - */ - readonly alphabeticBaseline: number; - /** - * Returns the measurement described below. - */ - readonly emHeightAscent: number; - /** - * Returns the measurement described below. - */ - readonly emHeightDescent: number; - /** - * Returns the measurement described below. - */ - readonly fontBoundingBoxAscent: number; - /** - * Returns the measurement described below. - */ - readonly fontBoundingBoxDescent: number; - /** - * Returns the measurement described below. - */ - readonly hangingBaseline: number; - /** - * Returns the measurement described below. - */ - readonly ideographicBaseline: number; /** * Returns the measurement described below. */ @@ -15725,9 +15434,9 @@ interface TextTrack extends EventTarget { readonly cues: TextTrackCueList | null; /** * Returns the ID of the given track. - * + * * For in-band tracks, this is the ID that can be used with a fragment if the format supports media fragment syntax, and that can be used with the getTrackById() method. - * + * * For TextTrack objects corresponding to track elements, this is the ID of the track element. */ readonly id: string; @@ -15749,12 +15458,11 @@ interface TextTrack extends EventTarget { readonly language: string; /** * Returns the text track mode, represented by a string from the following list: - * + * * Can be set, to change the mode. */ mode: TextTrackMode; oncuechange: ((this: TextTrack, ev: Event) => any) | null; - readonly sourceBuffer: SourceBuffer | null; /** * Adds the given cue to textTrack's text track list of cues. */ @@ -15783,13 +15491,13 @@ interface TextTrackCueEventMap { interface TextTrackCue extends EventTarget { /** * Returns the text track cue end time, in seconds. - * + * * Can be set. */ endTime: number; /** * Returns the text track cue identifier. - * + * * Can be set. */ id: string; @@ -15797,13 +15505,13 @@ interface TextTrackCue extends EventTarget { onexit: ((this: TextTrackCue, ev: Event) => any) | null; /** * Returns true if the text track cue pause-on-exit flag is set, false otherwise. - * + * * Can be set. */ pauseOnExit: boolean; /** * Returns the text track cue start time, in seconds. - * + * * Can be set. */ startTime: number; @@ -15829,7 +15537,7 @@ interface TextTrackCueList { readonly length: number; /** * Returns the first text track cue (in text track cue order) with text track cue identifier id. - * + * * Returns null if none of the cues have the given identifier or if the argument is the empty string. */ getCueById(id: string): TextTrackCue | null; @@ -15873,13 +15581,13 @@ interface TimeRanges { readonly length: number; /** * Returns the time for the end of the range with the given index. - * + * * Throws an "IndexSizeError" DOMException if the index is out of range. */ end(index: number): number; /** * Returns the time for the start of the range with the given index. - * + * * Throws an "IndexSizeError" DOMException if the index is out of range. */ start(index: number): number; @@ -16192,7 +15900,6 @@ interface VRPose { readonly linearVelocity: Float32Array | null; readonly orientation: Float32Array | null; readonly position: Float32Array | null; - readonly timestamp: number; } declare var VRPose: { @@ -16419,28 +16126,6 @@ declare var WaveShaperNode: { new(context: BaseAudioContext, options?: WaveShaperOptions): WaveShaperNode; }; -interface WebAuthentication { - getAssertion(assertionChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: ScopedCredentialOptions): Promise; -} - -declare var WebAuthentication: { - prototype: WebAuthentication; - new(): WebAuthentication; -}; - -interface WebAuthnAssertion { - readonly authenticatorData: ArrayBuffer; - readonly clientData: ArrayBuffer; - readonly credential: ScopedCredential; - readonly signature: ArrayBuffer; -} - -declare var WebAuthnAssertion: { - prototype: WebAuthnAssertion; - new(): WebAuthnAssertion; -}; - interface WebGL2RenderingContext extends WebGL2RenderingContextBase, WebGL2RenderingContextOverloads, WebGLRenderingContextBase { } @@ -17418,7 +17103,7 @@ declare var WebGLActiveInfo: { }; /** Part of the WebGL API and represents an opaque buffer object storing data such as vertices or colors. */ -interface WebGLBuffer extends WebGLObject { +interface WebGLBuffer { } declare var WebGLBuffer: { @@ -17437,7 +17122,7 @@ declare var WebGLContextEvent: { }; /** Part of the WebGL API and represents a collection of buffers that serve as a rendering destination. */ -interface WebGLFramebuffer extends WebGLObject { +interface WebGLFramebuffer { } declare var WebGLFramebuffer: { @@ -17445,16 +17130,8 @@ declare var WebGLFramebuffer: { new(): WebGLFramebuffer; }; -interface WebGLObject { -} - -declare var WebGLObject: { - prototype: WebGLObject; - new(): WebGLObject; -}; - /** The WebGLProgram is part of the WebGL API and is a combination of two compiled WebGLShaders consisting of a vertex shader and a fragment shader (both written in GLSL). */ -interface WebGLProgram extends WebGLObject { +interface WebGLProgram { } declare var WebGLProgram: { @@ -17462,7 +17139,7 @@ declare var WebGLProgram: { new(): WebGLProgram; }; -interface WebGLQuery extends WebGLObject { +interface WebGLQuery { } declare var WebGLQuery: { @@ -17471,7 +17148,7 @@ declare var WebGLQuery: { }; /** Part of the WebGL API and represents a buffer that can contain an image, or can be source or target of an rendering operation. */ -interface WebGLRenderbuffer extends WebGLObject { +interface WebGLRenderbuffer { } declare var WebGLRenderbuffer: { @@ -18250,7 +17927,7 @@ interface WebGLRenderingContextOverloads { uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; } -interface WebGLSampler extends WebGLObject { +interface WebGLSampler { } declare var WebGLSampler: { @@ -18259,7 +17936,7 @@ declare var WebGLSampler: { }; /** The WebGLShader is part of the WebGL API and can either be a vertex or a fragment shader. A WebGLProgram requires both types of shaders. */ -interface WebGLShader extends WebGLObject { +interface WebGLShader { } declare var WebGLShader: { @@ -18279,7 +17956,7 @@ declare var WebGLShaderPrecisionFormat: { new(): WebGLShaderPrecisionFormat; }; -interface WebGLSync extends WebGLObject { +interface WebGLSync { } declare var WebGLSync: { @@ -18288,7 +17965,7 @@ declare var WebGLSync: { }; /** Part of the WebGL API and represents an opaque texture object providing storage and state for texturing operations. */ -interface WebGLTexture extends WebGLObject { +interface WebGLTexture { } declare var WebGLTexture: { @@ -18296,7 +17973,7 @@ declare var WebGLTexture: { new(): WebGLTexture; }; -interface WebGLTransformFeedback extends WebGLObject { +interface WebGLTransformFeedback { } declare var WebGLTransformFeedback: { @@ -18313,7 +17990,7 @@ declare var WebGLUniformLocation: { new(): WebGLUniformLocation; }; -interface WebGLVertexArrayObject extends WebGLObject { +interface WebGLVertexArrayObject { } declare var WebGLVertexArrayObject: { @@ -18321,7 +17998,7 @@ declare var WebGLVertexArrayObject: { new(): WebGLVertexArrayObject; }; -interface WebGLVertexArrayObjectOES extends WebGLObject { +interface WebGLVertexArrayObjectOES { } interface WebKitPoint { @@ -18345,13 +18022,13 @@ interface WebSocketEventMap { interface WebSocket extends EventTarget { /** * Returns a string that indicates how binary data from the WebSocket object is exposed to scripts: - * + * * Can be set, to change how binary data is returned. The default is "blob". */ binaryType: BinaryType; /** * Returns the number of bytes of application data (UTF-8 text and binary data) that have been queued using send() but not yet been transmitted to the network. - * + * * If the WebSocket connection is closed, this attribute's value will only increase with each call to the send() method. (The number does not reset to zero once the connection closes.) */ readonly bufferedAmount: number; @@ -18434,7 +18111,6 @@ interface WindowEventMap extends GlobalEventHandlersEventMap, WindowEventHandler "compassneedscalibration": Event; "contextmenu": MouseEvent; "dblclick": MouseEvent; - "devicelight": DeviceLightEvent; "devicemotion": DeviceMotionEvent; "deviceorientation": DeviceOrientationEvent; "deviceorientationabsolute": DeviceOrientationEvent; @@ -18471,21 +18147,6 @@ interface WindowEventMap extends GlobalEventHandlersEventMap, WindowEventHandler "mouseover": MouseEvent; "mouseup": MouseEvent; "mousewheel": Event; - "MSGestureChange": Event; - "MSGestureDoubleTap": Event; - "MSGestureEnd": Event; - "MSGestureHold": Event; - "MSGestureStart": Event; - "MSGestureTap": Event; - "MSInertiaStart": Event; - "MSPointerCancel": Event; - "MSPointerDown": Event; - "MSPointerEnter": Event; - "MSPointerLeave": Event; - "MSPointerMove": Event; - "MSPointerOut": Event; - "MSPointerOver": Event; - "MSPointerUp": Event; "offline": Event; "online": Event; "orientationchange": Event; @@ -18516,9 +18177,6 @@ interface WindowEventMap extends GlobalEventHandlersEventMap, WindowEventHandler "vrdisplayconnect": Event; "vrdisplaydeactivate": Event; "vrdisplaydisconnect": Event; - "vrdisplayfocus": Event; - "vrdisplaypointerrestricted": Event; - "vrdisplaypointerunrestricted": Event; "vrdisplaypresentchange": Event; "waiting": Event; } @@ -18551,28 +18209,12 @@ interface Window extends EventTarget, AnimationFrameProvider, GlobalEventHandler readonly navigator: Navigator; offscreenBuffering: string | boolean; oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; - ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; ondeviceorientationabsolute: ((this: Window, ev: DeviceOrientationEvent) => any) | null; ongamepadconnected: ((this: Window, ev: GamepadEvent) => any) | null; ongamepaddisconnected: ((this: Window, ev: GamepadEvent) => any) | null; onmousewheel: ((this: Window, ev: Event) => any) | null; - onmsgesturechange: ((this: Window, ev: Event) => any) | null; - onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; - onmsgestureend: ((this: Window, ev: Event) => any) | null; - onmsgesturehold: ((this: Window, ev: Event) => any) | null; - onmsgesturestart: ((this: Window, ev: Event) => any) | null; - onmsgesturetap: ((this: Window, ev: Event) => any) | null; - onmsinertiastart: ((this: Window, ev: Event) => any) | null; - onmspointercancel: ((this: Window, ev: Event) => any) | null; - onmspointerdown: ((this: Window, ev: Event) => any) | null; - onmspointerenter: ((this: Window, ev: Event) => any) | null; - onmspointerleave: ((this: Window, ev: Event) => any) | null; - onmspointermove: ((this: Window, ev: Event) => any) | null; - onmspointerout: ((this: Window, ev: Event) => any) | null; - onmspointerover: ((this: Window, ev: Event) => any) | null; - onmspointerup: ((this: Window, ev: Event) => any) | null; /** @deprecated */ onorientationchange: ((this: Window, ev: Event) => any) | null; onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; @@ -18581,11 +18223,8 @@ interface Window extends EventTarget, AnimationFrameProvider, GlobalEventHandler onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; - onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; - onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; - onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; - opener: any; + opener: WindowProxy | null; /** @deprecated */ readonly orientation: string | number; readonly outerHeight: number; @@ -18832,26 +18471,26 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget { readonly response: any; /** * Returns the text response. - * + * * Throws an "InvalidStateError" DOMException if responseType is not the empty string or "text". */ readonly responseText: string; /** * Returns the response type. - * + * * Can be set to change the response type. Values are: the empty string (default), "arraybuffer", "blob", "document", "json", and "text". - * + * * When set: setting to "document" is ignored if current global object is not a Window object. - * + * * When set: throws an "InvalidStateError" DOMException if state is loading or done. - * + * * When set: throws an "InvalidAccessError" DOMException if the synchronous flag is set and current global object is a Window object. */ responseType: XMLHttpRequestResponseType; readonly responseURL: string; /** * Returns the document response. - * + * * Throws an "InvalidStateError" DOMException if responseType is not the empty string or "document". */ readonly responseXML: Document | null; @@ -18859,7 +18498,7 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget { readonly statusText: string; /** * Can be set to a time in milliseconds. When set to a non-zero value will cause fetching to terminate after the given time has passed. When the time has passed, the request has not yet completed, and the synchronous flag is unset, a timeout event will then be dispatched, or a "TimeoutError" DOMException will be thrown otherwise (for the send() method). - * + * * When set: throws an "InvalidAccessError" DOMException if the synchronous flag is set and current global object is a Window object. */ timeout: number; @@ -18869,7 +18508,7 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget { readonly upload: XMLHttpRequestUpload; /** * True when credentials are to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. Initially false. - * + * * When set: throws an "InvalidStateError" DOMException if state is not unsent or opened, or if the send() flag is set. */ withCredentials: boolean; @@ -18881,32 +18520,32 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget { getResponseHeader(name: string): string | null; /** * Sets the request method, request URL, and synchronous flag. - * + * * Throws a "SyntaxError" DOMException if either method is not a valid HTTP method or url cannot be parsed. - * + * * Throws a "SecurityError" DOMException if method is a case-insensitive match for `CONNECT`, `TRACE`, or `TRACK`. - * + * * Throws an "InvalidAccessError" DOMException if async is false, current global object is a Window object, and the timeout attribute is not zero or the responseType attribute is not the empty string. */ open(method: string, url: string): void; open(method: string, url: string, async: boolean, username?: string | null, password?: string | null): void; /** * Acts as if the `Content-Type` header value for response is mime. (It does not actually change the header though.) - * + * * Throws an "InvalidStateError" DOMException if state is loading or done. */ overrideMimeType(mime: string): void; /** * Initiates the request. The body argument provides the request body, if any, and is ignored if the request method is GET or HEAD. - * + * * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set. */ send(body?: Document | BodyInit | null): void; /** * Combines a header in author request headers. - * + * * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set. - * + * * Throws a "SyntaxError" DOMException if name is not a header name or if value is not a header value. */ setRequestHeader(name: string, value: string): void; @@ -19113,52 +18752,52 @@ declare namespace CSS { declare namespace WebAssembly { interface CompileError { } - + var CompileError: { prototype: CompileError; new(): CompileError; }; - + interface Global { value: any; valueOf(): any; } - + var Global: { prototype: Global; new(descriptor: GlobalDescriptor, v?: any): Global; }; - + interface Instance { readonly exports: Exports; } - + var Instance: { prototype: Instance; new(module: Module, importObject?: Imports): Instance; }; - + interface LinkError { } - + var LinkError: { prototype: LinkError; new(): LinkError; }; - + interface Memory { readonly buffer: ArrayBuffer; grow(delta: number): number; } - + var Memory: { prototype: Memory; new(descriptor: MemoryDescriptor): Memory; }; - + interface Module { } - + var Module: { prototype: Module; new(bytes: BufferSource): Module; @@ -19166,59 +18805,60 @@ declare namespace WebAssembly { exports(moduleObject: Module): ModuleExportDescriptor[]; imports(moduleObject: Module): ModuleImportDescriptor[]; }; - + interface RuntimeError { } - + var RuntimeError: { prototype: RuntimeError; new(): RuntimeError; }; - + interface Table { readonly length: number; get(index: number): Function | null; grow(delta: number): number; set(index: number, value: Function | null): void; } - + var Table: { prototype: Table; new(descriptor: TableDescriptor): Table; }; - + interface GlobalDescriptor { mutable?: boolean; value: ValueType; } - + interface MemoryDescriptor { initial: number; maximum?: number; + shared?: boolean; } - + interface ModuleExportDescriptor { kind: ImportExportKind; name: string; } - + interface ModuleImportDescriptor { kind: ImportExportKind; module: string; name: string; } - + interface TableDescriptor { element: TableKind; initial: number; maximum?: number; } - + interface WebAssemblyInstantiatedSource { instance: Instance; module: Module; } - + type ImportExportKind = "function" | "global" | "memory" | "table"; type TableKind = "anyfunc"; type ValueType = "f32" | "f64" | "i32" | "i64"; @@ -19386,7 +19026,6 @@ interface HTMLElementTagNameMap { "audio": HTMLAudioElement; "b": HTMLElement; "base": HTMLBaseElement; - "basefont": HTMLBaseFontElement; "bdi": HTMLElement; "bdo": HTMLElement; "blockquote": HTMLQuoteElement; @@ -19601,28 +19240,12 @@ declare const name: void; declare var navigator: Navigator; declare var offscreenBuffering: string | boolean; declare var oncompassneedscalibration: ((this: Window, ev: Event) => any) | null; -declare var ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null; declare var ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null; declare var ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null; declare var ondeviceorientationabsolute: ((this: Window, ev: DeviceOrientationEvent) => any) | null; declare var ongamepadconnected: ((this: Window, ev: GamepadEvent) => any) | null; declare var ongamepaddisconnected: ((this: Window, ev: GamepadEvent) => any) | null; declare var onmousewheel: ((this: Window, ev: Event) => any) | null; -declare var onmsgesturechange: ((this: Window, ev: Event) => any) | null; -declare var onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null; -declare var onmsgestureend: ((this: Window, ev: Event) => any) | null; -declare var onmsgesturehold: ((this: Window, ev: Event) => any) | null; -declare var onmsgesturestart: ((this: Window, ev: Event) => any) | null; -declare var onmsgesturetap: ((this: Window, ev: Event) => any) | null; -declare var onmsinertiastart: ((this: Window, ev: Event) => any) | null; -declare var onmspointercancel: ((this: Window, ev: Event) => any) | null; -declare var onmspointerdown: ((this: Window, ev: Event) => any) | null; -declare var onmspointerenter: ((this: Window, ev: Event) => any) | null; -declare var onmspointerleave: ((this: Window, ev: Event) => any) | null; -declare var onmspointermove: ((this: Window, ev: Event) => any) | null; -declare var onmspointerout: ((this: Window, ev: Event) => any) | null; -declare var onmspointerover: ((this: Window, ev: Event) => any) | null; -declare var onmspointerup: ((this: Window, ev: Event) => any) | null; /** @deprecated */ declare var onorientationchange: ((this: Window, ev: Event) => any) | null; declare var onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null; @@ -19631,11 +19254,8 @@ declare var onvrdisplayblur: ((this: Window, ev: Event) => any) | null; declare var onvrdisplayconnect: ((this: Window, ev: Event) => any) | null; declare var onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null; declare var onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null; -declare var onvrdisplayfocus: ((this: Window, ev: Event) => any) | null; -declare var onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null; -declare var onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null; declare var onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null; -declare var opener: any; +declare var opener: WindowProxy | null; /** @deprecated */ declare var orientation: string | number; declare var outerHeight: number; @@ -20148,15 +19768,13 @@ type PushEncryptionKeyName = "auth" | "p256dh"; type PushPermissionState = "denied" | "granted" | "prompt"; type RTCBundlePolicy = "balanced" | "max-bundle" | "max-compat"; type RTCDataChannelState = "closed" | "closing" | "connecting" | "open"; -type RTCDegradationPreference = "balanced" | "maintain-framerate" | "maintain-resolution"; type RTCDtlsRole = "auto" | "client" | "server"; type RTCDtlsTransportState = "closed" | "connected" | "connecting" | "failed" | "new"; -type RTCDtxStatus = "disabled" | "enabled"; -type RTCErrorDetailType = "data-channel-failure" | "dtls-failure" | "fingerprint-failure" | "hardware-encoder-error" | "hardware-encoder-not-available" | "idp-bad-script-failure" | "idp-execution-failure" | "idp-load-failure" | "idp-need-login" | "idp-timeout" | "idp-tls-failure" | "idp-token-expired" | "idp-token-invalid" | "sctp-failure" | "sdp-syntax-error"; +type RTCErrorDetailType = "data-channel-failure" | "dtls-failure" | "fingerprint-failure" | "hardware-encoder-error" | "hardware-encoder-not-available" | "sctp-failure" | "sdp-syntax-error"; type RTCIceCandidateType = "host" | "prflx" | "relay" | "srflx"; type RTCIceComponent = "rtcp" | "rtp"; type RTCIceConnectionState = "checking" | "closed" | "completed" | "connected" | "disconnected" | "failed" | "new"; -type RTCIceCredentialType = "oauth" | "password"; +type RTCIceCredentialType = "password"; type RTCIceGatherPolicy = "all" | "nohost" | "relay"; type RTCIceGathererState = "complete" | "gathering" | "new"; type RTCIceGatheringState = "complete" | "gathering" | "new"; @@ -20166,8 +19784,7 @@ type RTCIceTcpCandidateType = "active" | "passive" | "so"; type RTCIceTransportPolicy = "all" | "relay"; type RTCIceTransportState = "checking" | "closed" | "completed" | "connected" | "disconnected" | "failed" | "new"; type RTCPeerConnectionState = "closed" | "connected" | "connecting" | "disconnected" | "failed" | "new"; -type RTCPriorityType = "high" | "low" | "medium" | "very-low"; -type RTCRtcpMuxPolicy = "negotiate" | "require"; +type RTCRtcpMuxPolicy = "require"; type RTCRtpTransceiverDirection = "inactive" | "recvonly" | "sendonly" | "sendrecv" | "stopped"; type RTCSctpTransportState = "closed" | "connected" | "connecting"; type RTCSdpType = "answer" | "offer" | "pranswer" | "rollback"; @@ -20186,7 +19803,6 @@ type ResidentKeyRequirement = "discouraged" | "preferred" | "required"; type ResizeObserverBoxOptions = "border-box" | "content-box" | "device-pixel-content-box"; type ResizeQuality = "high" | "low" | "medium" | "pixelated"; type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; -type ScopedCredentialType = "ScopedCred"; type ScrollBehavior = "auto" | "smooth"; type ScrollLogicalPosition = "center" | "end" | "nearest" | "start"; type ScrollRestoration = "auto" | "manual"; @@ -20200,7 +19816,6 @@ type SpeechSynthesisErrorCode = "audio-busy" | "audio-hardware" | "canceled" | " type TextTrackKind = "captions" | "chapters" | "descriptions" | "metadata" | "subtitles"; type TextTrackMode = "disabled" | "hidden" | "showing"; type TouchType = "direct" | "stylus"; -type Transport = "ble" | "nfc" | "usb"; type UserVerificationRequirement = "discouraged" | "preferred" | "required"; type VRDisplayEventReason = "mounted" | "navigation" | "requested" | "unmounted"; type VideoFacingModeEnum = "environment" | "left" | "right" | "user"; diff --git a/src/lib/dom.iterable.generated.d.ts b/src/lib/dom.iterable.generated.d.ts index d7787b97daa47..a8002af91db31 100644 --- a/src/lib/dom.iterable.generated.d.ts +++ b/src/lib/dom.iterable.generated.d.ts @@ -119,7 +119,7 @@ interface IDBDatabase { interface IDBObjectStore { /** * Creates a new index in store with the given name, keyPath and options and returns a new IDBIndex. If the keyPath and options define constraints that cannot be satisfied with the data already in store the upgrade transaction will abort with a "ConstraintError" DOMException. - * + * * Throws an "InvalidStateError" DOMException if not called within an upgrade transaction. */ createIndex(name: string, keyPath: string | Iterable, options?: IDBIndexParameters): IDBIndex; @@ -267,10 +267,6 @@ interface WEBGL_draw_buffers { drawBuffersWEBGL(buffers: Iterable): void; } -interface WebAuthentication { - makeCredential(accountInformation: Account, cryptoParameters: Iterable, attestationChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: ScopedCredentialOptions): Promise; -} - interface WebGL2RenderingContextBase { clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Iterable, srcOffset?: GLuint): void; clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Iterable, srcOffset?: GLuint): void; diff --git a/src/lib/es2015.core.d.ts b/src/lib/es2015.core.d.ts index 032a7afc0ecf9..b202f3e01decd 100644 --- a/src/lib/es2015.core.d.ts +++ b/src/lib/es2015.core.d.ts @@ -248,8 +248,8 @@ interface NumberConstructor { /** * Converts A string to an integer. - * @param s A string to convert into a number. - * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * @param string A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in `string`. * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. * All other strings are considered decimal. */ diff --git a/src/lib/es2015.iterable.d.ts b/src/lib/es2015.iterable.d.ts index da6bec04adf8e..b5f0132c1d9cc 100644 --- a/src/lib/es2015.iterable.d.ts +++ b/src/lib/es2015.iterable.d.ts @@ -5,7 +5,7 @@ interface SymbolConstructor { * A method that returns the default iterator for an object. Called by the semantics of the * for-of statement. */ - readonly iterator: symbol; + readonly iterator: unique symbol; } interface IteratorYieldResult { diff --git a/src/lib/es2015.symbol.wellknown.d.ts b/src/lib/es2015.symbol.wellknown.d.ts index dce75ddab70c5..284c61f61c348 100644 --- a/src/lib/es2015.symbol.wellknown.d.ts +++ b/src/lib/es2015.symbol.wellknown.d.ts @@ -5,61 +5,61 @@ interface SymbolConstructor { * A method that determines if a constructor object recognizes an object as one of the * constructor’s instances. Called by the semantics of the instanceof operator. */ - readonly hasInstance: symbol; + readonly hasInstance: unique symbol; /** * A Boolean value that if true indicates that an object should flatten to its array elements * by Array.prototype.concat. */ - readonly isConcatSpreadable: symbol; + readonly isConcatSpreadable: unique symbol; /** * A regular expression method that matches the regular expression against a string. Called * by the String.prototype.match method. */ - readonly match: symbol; + readonly match: unique symbol; /** * A regular expression method that replaces matched substrings of a string. Called by the * String.prototype.replace method. */ - readonly replace: symbol; + readonly replace: unique symbol; /** * A regular expression method that returns the index within a string that matches the * regular expression. Called by the String.prototype.search method. */ - readonly search: symbol; + readonly search: unique symbol; /** * A function valued property that is the constructor function that is used to create * derived objects. */ - readonly species: symbol; + readonly species: unique symbol; /** * A regular expression method that splits a string at the indices that match the regular * expression. Called by the String.prototype.split method. */ - readonly split: symbol; + readonly split: unique symbol; /** * A method that converts an object to a corresponding primitive value. * Called by the ToPrimitive abstract operation. */ - readonly toPrimitive: symbol; + readonly toPrimitive: unique symbol; /** * A String value that is used in the creation of the default string description of an object. * Called by the built-in method Object.prototype.toString. */ - readonly toStringTag: symbol; + readonly toStringTag: unique symbol; /** * An Object whose own property names are property names that are excluded from the 'with' * environment bindings of the associated objects. */ - readonly unscopables: symbol; + readonly unscopables: unique symbol; } interface Symbol { diff --git a/src/lib/es2018.asynciterable.d.ts b/src/lib/es2018.asynciterable.d.ts index 19a31c72ca4a9..c19b8d34cd538 100644 --- a/src/lib/es2018.asynciterable.d.ts +++ b/src/lib/es2018.asynciterable.d.ts @@ -6,7 +6,7 @@ interface SymbolConstructor { * A method that returns the default async iterator for an object. Called by the semantics of * the for-await-of statement. */ - readonly asyncIterator: symbol; + readonly asyncIterator: unique symbol; } interface AsyncIterator { diff --git a/src/lib/es2020.bigint.d.ts b/src/lib/es2020.bigint.d.ts index 15c92f072fca5..31844087eb425 100644 --- a/src/lib/es2020.bigint.d.ts +++ b/src/lib/es2020.bigint.d.ts @@ -101,7 +101,7 @@ interface BigInt { } interface BigIntConstructor { - (value?: any): bigint; + (value: bigint | boolean | number | string): bigint; readonly prototype: BigInt; /** diff --git a/src/lib/es2020.intl.d.ts b/src/lib/es2020.intl.d.ts index 0db148085d579..cf75a593f2a0e 100644 --- a/src/lib/es2020.intl.d.ts +++ b/src/lib/es2020.intl.d.ts @@ -1,13 +1,12 @@ declare namespace Intl { /** - * [BCP 47 language tag](http://tools.ietf.org/html/rfc5646) definition. + * [Unicode BCP 47 Locale Identifiers](https://unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers) definition. * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument). * - * [Wikipedia](https://en.wikipedia.org/wiki/IETF_language_tag). */ - type BCP47LanguageTag = string; + type UnicodeBCP47LocaleIdentifier = string; /** * Unit to use in the relative time internationalized message. @@ -54,239 +53,6 @@ declare namespace Intl { */ type RelativeTimeFormatStyle = "long" | "short" | "narrow"; - /** - * Unicode Calendar Identifier - * - * [Reference](http://unicode.org/reports/tr35/#UnicodeCalendarIdentifier) - * - * [Source](https://github.com/unicode-org/cldr/blob/b805d0b/common/bcp47/calendar.xml) - */ - type Calendar = - // Thai Buddhist calendar - | "buddhist" - // Traditional Chinese calendar - | "chinese" - // Coptic calendar - | "coptic" - // Traditional Korean calendar - | "dangi" - // Ethiopic calendar, Amete Alem (epoch approx. 5493 B.C.E) - | "ethiopic-amete-alem" | "ethioaa" - // Ethiopic calendar, Amete Mihret (epoch approx, 8 C.E.) - | "ethiopic" - // Gregorian calendar - | "gregorian" - // Gregorian calendar (alias) - | "gregory" - // Traditional Hebrew calendar - | "hebrew" - // Indian calendar - | "indian" - // Islamic calendar - | "islamic" - // Islamic calendar, Umm al-Qura - | "islamic-umalqura" - // Islamic calendar, tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29] - astronomical epoch) - | "islamic-tbla" - // Islamic calendar, tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29] - civil epoch) - | "islamic-civil" - | "islamicc" // Deprecated alias - // Islamic calendar, Saudi Arabia sighting - | "islamic-rgsa" - // ISO calendar (Gregorian calendar using the ISO 8601 calendar week rules) - | "iso8601" - // Japanese Imperial calendar - | "japanese" - // Persian calendar - | "persian" - // Republic of China calendar - | "roc" - ; - - /** - * Unicode Number System Identifier - * - * [Reference](http://unicode.org/reports/tr35/#UnicodeNumberSystemIdentifier) - * - * [Source](https://github.com/unicode-org/cldr/blob/be7a953/common/bcp47/number.xml) - */ - type NumberingSystem = - // Adlam digits - | "adlm" - // Ahom digits - | "ahom" - // Arabic-Indic digits - | "arab" - // Extended Arabic-Indic digits - | "arabext" - // Armenian upper case numerals — algorithmic - | "armn" - // Armenian lower case numerals — algorithmic - | "armnlow" - // Balinese digits - | "bali" - // Bengali digits - | "beng" - // Bhaiksuki digits - | "bhks" - // Brahmi digits - | "brah" - // Chakma digits - | "cakm" - // Cham digits - | "cham" - // Cyrillic numerals — algorithmic - | "cyrl" - // Devanagari digits - | "deva" - // Dives Akuru digits - | "diak" - // Ethiopic numerals — algorithmic - | "ethi" - // Financial numerals — may be algorithmic - | "finance" - // Full width digits - | "fullwide" - // Georgian numerals — algorithmic - | "geor" - // Gunjala Gondi digits - | "gong" - // Masaram Gondi digits - | "gonm" - // Greek upper case numerals — algorithmic - | "grek" - // Greek lower case numerals — algorithmic - | "greklow" - // Gujarati digits - | "gujr" - // Gurmukhi digits - | "guru" - // Han-character day-of-month numbering for lunar/other traditional calendars" - | "hanidays" - // Positional decimal system using Chinese number ideographs as digits - | "hanidec" - // Simplified Chinese numerals — algorithmic - | "hans" - // Simplified Chinese financial numerals — algorithmic - | "hansfin" - // Traditional Chinese numerals — algorithmic - | "hant" - // Traditional Chinese financial numerals — algorithmic - | "hantfin" - // Hebrew numerals — algorithmic - | "hebr" - // Pahawh Hmong digits - | "hmng" - // Nyiakeng Puachue Hmong digits - | "hmnp" - // Javanese digits - | "java" - // Japanese numerals — algorithmic - | "jpan" - // Japanese financial numerals — algorithmic - | "jpanfin" - // Japanese first-year Gannen numbering for Japanese calendar - | "jpanyear" - // Kayah Li digits - | "kali" - // Khmer digits - | "khmr" - // Kannada digits - | "knda" - // Tai Tham Hora (secular) digits - | "lana" - // Tai Tham Tham (ecclesiastical) digits - | "lanatham" - // Lao digits - | "laoo" - // Latin digits - | "latn" - // Lepcha digits - | "lepc" - // Limbu digits - | "limb" - // Mathematical bold digits - | "mathbold" - // Mathematical double-struck digits - | "mathdbl" - // Mathematical monospace digits - | "mathmono" - // Mathematical sans-serif bold digits - | "mathsanb" - // Mathematical sans-serif digits - | "mathsans" - // Malayalam digits - | "mlym" - // Modi digits - | "modi" - // Mongolian digits - | "mong" - // Mro digits - | "mroo" - // Meetei Mayek digits - | "mtei" - // Myanmar digits - | "mymr" - // Myanmar Shan digits - | "mymrshan" - // Myanmar Tai Laing digits - | "mymrtlng" - // Native digits - | "native" - // Newa digits - | "newa" - // N'Ko digits - | "nkoo" - // Ol Chiki digits - | "olck" - // Oriya digits - | "orya" - // Osmanya digits - | "osma" - // Hanifi Rohingya digits - | "rohg" - // Roman upper case numerals — algorithmic - | "roman" - // Roman lowercase numerals — algorithmic - | "romanlow" - // Saurashtra digits - | "saur" - // Sharada digits - | "shrd" - // Khudawadi digits - | "sind" - // Sinhala Lith digits - | "sinh" - // Sora_Sompeng digits - | "sora" - // Sundanese digits - | "sund" - // Takri digits - | "takr" - // New Tai Lue digits - | "talu" - // Tamil numerals — algorithmic - | "taml" - // Modern Tamil decimal digits - | "tamldec" - // Telugu digits - | "telu" - // Thai digits - | "thai" - // Tirhuta digits - | "tirh" - // Tibetan digits - | "tibt" - // Traditional numerals — may be algorithmic - | "traditional" | "traditio" - // Vai digits - | "vaii" - // Warang Citi digits - | "wara" - // Wancho digits - | "wcho" - ; - /** * An object with some or all of properties of `options` parameter * of `Intl.RelativeTimeFormat` constructor. @@ -311,7 +77,7 @@ declare namespace Intl { * [Specification](https://tc39.es/ecma402/#table-relativetimeformat-resolvedoptions-properties) */ interface ResolvedRelativeTimeFormatOptions { - locale: BCP47LanguageTag; + locale: UnicodeBCP47LocaleIdentifier; style: RelativeTimeFormatStyle; numeric: RelativeTimeFormatNumeric; numberingSystem: string; @@ -454,7 +220,7 @@ declare namespace Intl { * [Specification](https://tc39.es/ecma402/#sec-intl-relativetimeformat-constructor). */ new( - locales?: BCP47LanguageTag | BCP47LanguageTag[], + locales?: UnicodeBCP47LocaleIdentifier | UnicodeBCP47LocaleIdentifier[], options?: RelativeTimeFormatOptions, ): RelativeTimeFormat; @@ -490,9 +256,9 @@ declare namespace Intl { * [Specification](https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.supportedLocalesOf). */ supportedLocalesOf( - locales: BCP47LanguageTag | BCP47LanguageTag[], + locales?: UnicodeBCP47LocaleIdentifier | UnicodeBCP47LocaleIdentifier[], options?: RelativeTimeFormatOptions, - ): BCP47LanguageTag[]; + ): UnicodeBCP47LocaleIdentifier[]; }; interface NumberFormatOptions { @@ -514,9 +280,9 @@ declare namespace Intl { interface DateTimeFormatOptions { dateStyle?: "full" | "long" | "medium" | "short"; timeStyle?: "full" | "long" | "medium" | "short"; - calendar?: Calendar; + calendar?: string; dayPeriod?: "narrow" | "short" | "long"; - numberingSystem?: NumberingSystem; + numberingSystem?: string; hourCycle?: "h11" | "h12" | "h23" | "h24"; fractionalSecondDigits?: 0 | 1 | 2 | 3; } diff --git a/src/lib/es2020.symbol.wellknown.d.ts b/src/lib/es2020.symbol.wellknown.d.ts index 08e1fa2c913fe..94a11768256c7 100644 --- a/src/lib/es2020.symbol.wellknown.d.ts +++ b/src/lib/es2020.symbol.wellknown.d.ts @@ -6,7 +6,7 @@ interface SymbolConstructor { * A regular expression method that matches the regular expression against a string. Called * by the String.prototype.matchAll method. */ - readonly matchAll: symbol; + readonly matchAll: unique symbol; } interface RegExp { diff --git a/src/lib/es2021.d.ts b/src/lib/es2021.d.ts new file mode 100644 index 0000000000000..b36544589153c --- /dev/null +++ b/src/lib/es2021.d.ts @@ -0,0 +1,4 @@ +/// +/// +/// +/// diff --git a/src/lib/es2021.full.d.ts b/src/lib/es2021.full.d.ts new file mode 100644 index 0000000000000..c62d63ca7a13d --- /dev/null +++ b/src/lib/es2021.full.d.ts @@ -0,0 +1,5 @@ +/// +/// +/// +/// +/// diff --git a/src/lib/esnext.promise.d.ts b/src/lib/es2021.promise.d.ts similarity index 100% rename from src/lib/esnext.promise.d.ts rename to src/lib/es2021.promise.d.ts diff --git a/src/lib/esnext.string.d.ts b/src/lib/es2021.string.d.ts similarity index 100% rename from src/lib/esnext.string.d.ts rename to src/lib/es2021.string.d.ts diff --git a/src/lib/esnext.weakref.d.ts b/src/lib/es2021.weakref.d.ts similarity index 82% rename from src/lib/esnext.weakref.d.ts rename to src/lib/es2021.weakref.d.ts index 337aa11f3e319..d36ddb6a19cfd 100644 --- a/src/lib/esnext.weakref.d.ts +++ b/src/lib/es2021.weakref.d.ts @@ -15,12 +15,12 @@ interface WeakRefConstructor { * Creates a WeakRef instance for the given target object. * @param target The target object for the WeakRef instance. */ - new(target?: T): WeakRef; + new(target: T): WeakRef; } declare var WeakRef: WeakRefConstructor; -interface FinalizationRegistry { +interface FinalizationRegistry { readonly [Symbol.toStringTag]: "FinalizationRegistry"; /** @@ -32,7 +32,7 @@ interface FinalizationRegistry { * object. If provided (and not undefined), this must be an object. If not provided, the target * cannot be unregistered. */ - register(target: object, heldValue: any, unregisterToken?: object): void; + register(target: object, heldValue: T, unregisterToken?: object): void; /** * Unregisters an object from the registry. @@ -43,13 +43,13 @@ interface FinalizationRegistry { } interface FinalizationRegistryConstructor { - readonly prototype: FinalizationRegistry; + readonly prototype: FinalizationRegistry; /** * Creates a finalization registry with an associated cleanup callback * @param cleanupCallback The callback to call after an object in the registry has been reclaimed. */ - new(cleanupCallback: (heldValue: any) => void): FinalizationRegistry; + new(cleanupCallback: (heldValue: T) => void): FinalizationRegistry; } declare var FinalizationRegistry: FinalizationRegistryConstructor; diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index 98bb0ee676e5d..bfa5241a84d94 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -13,12 +13,12 @@ declare function eval(x: string): any; /** * Converts a string to an integer. - * @param s A string to convert into a number. - * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * @param string A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in `string`. * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. * All other strings are considered decimal. */ -declare function parseInt(s: string, radix?: number): number; +declare function parseInt(string: string, radix?: number): number; /** * Converts a string to a floating-point number. @@ -177,14 +177,14 @@ interface ObjectConstructor { * @param p The property name. * @param attributes Descriptor for the property. It can be for a data property or an accessor property. */ - defineProperty(o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType): any; + defineProperty(o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType): T; /** * Adds one or more properties to an object, and/or modifies attributes of existing properties. * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. */ - defineProperties(o: any, properties: PropertyDescriptorMap & ThisType): any; + defineProperties(o: T, properties: PropertyDescriptorMap & ThisType): T; /** * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. @@ -1073,7 +1073,7 @@ interface ReadonlyArray { */ toString(): string; /** - * Returns a string representation of an array. The elements are converted to string using their toLocalString methods. + * Returns a string representation of an array. The elements are converted to string using their toLocaleString methods. */ toLocaleString(): string; /** @@ -1207,7 +1207,7 @@ interface Array { */ toString(): string; /** - * Returns a string representation of an array. The elements are converted to string using their toLocalString methods. + * Returns a string representation of an array. The elements are converted to string using their toLocaleString methods. */ toLocaleString(): string; /** @@ -1508,7 +1508,7 @@ type Parameters any> = T extends (...args: infer P) /** * Obtain the parameters of a constructor function type in a tuple */ -type ConstructorParameters any> = T extends new (...args: infer P) => any ? P : never; +type ConstructorParameters any> = T extends abstract new (...args: infer P) => any ? P : never; /** * Obtain the return type of a function type @@ -1518,7 +1518,7 @@ type ReturnType any> = T extends (...args: any) => i /** * Obtain the return type of a constructor function type */ -type InstanceType any> = T extends new (...args: any) => infer R ? R : any; +type InstanceType any> = T extends abstract new (...args: any) => infer R ? R : any; /** * Convert string literal type to uppercase diff --git a/src/lib/esnext.d.ts b/src/lib/esnext.d.ts index d42e73cad9f1e..4a3ac819c1900 100644 --- a/src/lib/esnext.d.ts +++ b/src/lib/esnext.d.ts @@ -1,5 +1,2 @@ -/// +/// /// -/// -/// -/// diff --git a/src/lib/libs.json b/src/lib/libs.json index 0de9568bd4a85..0eb3d7b657a34 100644 --- a/src/lib/libs.json +++ b/src/lib/libs.json @@ -8,6 +8,7 @@ "es2018", "es2019", "es2020", + "es2021", "esnext", // Host only "dom.generated", @@ -47,10 +48,10 @@ "es2020.string", "es2020.symbol.wellknown", "es2020.intl", + "es2021.string", + "es2021.promise", + "es2021.weakref", "esnext.intl", - "esnext.string", - "esnext.promise", - "esnext.weakref", // Default libraries "es5.full", "es2015.full", @@ -59,6 +60,7 @@ "es2018.full", "es2019.full", "es2020.full", + "es2021.full", "esnext.full" ], "paths": { diff --git a/src/lib/webworker.generated.d.ts b/src/lib/webworker.generated.d.ts index 0a3423681a326..378670cad3759 100644 --- a/src/lib/webworker.generated.d.ts +++ b/src/lib/webworker.generated.d.ts @@ -362,11 +362,6 @@ interface PushPermissionDescriptor extends PermissionDescriptor { userVisibleOnly?: boolean; } -interface PushSubscriptionChangeEventInit extends ExtendableEventInit { - newSubscription?: PushSubscription; - oldSubscription?: PushSubscription; -} - interface PushSubscriptionJSON { endpoint?: string; expirationTime?: number | null; @@ -386,7 +381,7 @@ interface QueuingStrategy { interface QueuingStrategyInit { /** * Creates a new ByteLengthQueuingStrategy with the provided high water mark. - * + * * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. */ highWaterMark: number; @@ -406,7 +401,7 @@ interface ReadableWritablePair { readable: ReadableStream; /** * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. - * + * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. */ writable: WritableStream; @@ -516,19 +511,19 @@ interface StreamPipeOptions { preventCancel?: boolean; /** * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * + * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - * + * * Errors and closures of the source and destination streams propagate as follows: - * + * * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. - * + * * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. - * + * * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - * + * * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. - * + * * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. */ preventClose?: boolean; @@ -813,7 +808,7 @@ interface CanvasFilters { interface CanvasGradient { /** * Adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset at one end of the gradient, 1.0 is the offset at the other end. - * + * * Throws an "IndexSizeError" DOMException if the offset is out of range. Throws a "SyntaxError" DOMException if the color cannot be parsed. */ addColorStop(offset: number, color: string): void; @@ -1495,15 +1490,15 @@ declare var EventSource: { interface EventTarget { /** * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. - * + * * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. - * + * * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. - * + * * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. - * + * * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. - * + * * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. */ addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; @@ -1550,7 +1545,6 @@ declare var ExtendableMessageEvent: { interface FetchEvent extends ExtendableEvent { readonly clientId: string; readonly preloadResponse: Promise; - readonly replacesClientId: string; readonly request: Request; readonly resultingClientId: string; respondWith(r: Response | Promise): void; @@ -1710,15 +1704,15 @@ interface IDBCursor { continuePrimaryKey(key: IDBValidKey, primaryKey: IDBValidKey): void; /** * Delete the record pointed at by the cursor with a new value. - * + * * If successful, request's result will be undefined. */ delete(): IDBRequest; /** * Updated the record pointed at by the cursor with a new value. - * + * * Throws a "DataError" DOMException if the effective object store uses in-line keys and the key would have changed. - * + * * If successful, request's result will be the record's key. */ update(value: any): IDBRequest; @@ -1773,13 +1767,13 @@ interface IDBDatabase extends EventTarget { close(): void; /** * Creates a new object store with the given name and options and returns a new IDBObjectStore. - * + * * Throws a "InvalidStateError" DOMException if not called within an upgrade transaction. */ createObjectStore(name: string, options?: IDBObjectStoreParameters): IDBObjectStore; /** * Deletes the object store with the given name. - * + * * Throws a "InvalidStateError" DOMException if not called within an upgrade transaction. */ deleteObjectStore(name: string): void; @@ -1802,7 +1796,7 @@ declare var IDBDatabase: { interface IDBFactory { /** * Compares two values as keys. Returns -1 if key1 precedes key2, 1 if key2 precedes key1, and 0 if the keys are equal. - * + * * Throws a "DataError" DOMException if either input is not a valid key. */ cmp(first: any, second: any): number; @@ -1836,43 +1830,43 @@ interface IDBIndex { readonly unique: boolean; /** * Retrieves the number of records matching the given key or key range in query. - * + * * If successful, request's result will be the count. */ count(key?: IDBValidKey | IDBKeyRange): IDBRequest; /** * Retrieves the value of the first record matching the given key or key range in query. - * + * * If successful, request's result will be the value, or undefined if there was no matching record. */ get(key: IDBValidKey | IDBKeyRange): IDBRequest; /** * Retrieves the values of the records matching the given key or key range in query (up to count if given). - * + * * If successful, request's result will be an Array of the values. */ getAll(query?: IDBValidKey | IDBKeyRange | null, count?: number): IDBRequest; /** * Retrieves the keys of records matching the given key or key range in query (up to count if given). - * + * * If successful, request's result will be an Array of the keys. */ getAllKeys(query?: IDBValidKey | IDBKeyRange | null, count?: number): IDBRequest; /** * Retrieves the key of the first record matching the given key or key range in query. - * + * * If successful, request's result will be the key, or undefined if there was no matching record. */ getKey(key: IDBValidKey | IDBKeyRange): IDBRequest; /** * Opens a cursor over the records matching query, ordered by direction. If query is null, all records in index are matched. - * + * * If successful, request's result will be an IDBCursorWithValue, or null if there were no matching records. */ openCursor(query?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; /** * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in index are matched. - * + * * If successful, request's result will be an IDBCursor, or null if there were no matching records. */ openKeyCursor(query?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; @@ -1952,88 +1946,88 @@ interface IDBObjectStore { readonly transaction: IDBTransaction; /** * Adds or updates a record in store with the given value and key. - * + * * If the store uses in-line keys and key is specified a "DataError" DOMException will be thrown. - * + * * If put() is used, any existing record with the key will be replaced. If add() is used, and if a record with the key already exists the request will fail, with request's error set to a "ConstraintError" DOMException. - * + * * If successful, request's result will be the record's key. */ add(value: any, key?: IDBValidKey): IDBRequest; /** * Deletes all records in store. - * + * * If successful, request's result will be undefined. */ clear(): IDBRequest; /** * Retrieves the number of records matching the given key or key range in query. - * + * * If successful, request's result will be the count. */ count(key?: IDBValidKey | IDBKeyRange): IDBRequest; /** * Creates a new index in store with the given name, keyPath and options and returns a new IDBIndex. If the keyPath and options define constraints that cannot be satisfied with the data already in store the upgrade transaction will abort with a "ConstraintError" DOMException. - * + * * Throws an "InvalidStateError" DOMException if not called within an upgrade transaction. */ createIndex(name: string, keyPath: string | string[], options?: IDBIndexParameters): IDBIndex; /** * Deletes records in store with the given key or in the given key range in query. - * + * * If successful, request's result will be undefined. */ delete(key: IDBValidKey | IDBKeyRange): IDBRequest; /** * Deletes the index in store with the given name. - * + * * Throws an "InvalidStateError" DOMException if not called within an upgrade transaction. */ deleteIndex(name: string): void; /** * Retrieves the value of the first record matching the given key or key range in query. - * + * * If successful, request's result will be the value, or undefined if there was no matching record. */ get(query: IDBValidKey | IDBKeyRange): IDBRequest; /** * Retrieves the values of the records matching the given key or key range in query (up to count if given). - * + * * If successful, request's result will be an Array of the values. */ getAll(query?: IDBValidKey | IDBKeyRange | null, count?: number): IDBRequest; /** * Retrieves the keys of records matching the given key or key range in query (up to count if given). - * + * * If successful, request's result will be an Array of the keys. */ getAllKeys(query?: IDBValidKey | IDBKeyRange | null, count?: number): IDBRequest; /** * Retrieves the key of the first record matching the given key or key range in query. - * + * * If successful, request's result will be the key, or undefined if there was no matching record. */ getKey(query: IDBValidKey | IDBKeyRange): IDBRequest; index(name: string): IDBIndex; /** * Opens a cursor over the records matching query, ordered by direction. If query is null, all records in store are matched. - * + * * If successful, request's result will be an IDBCursorWithValue pointing at the first matching record, or null if there were no matching records. */ openCursor(query?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; /** * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in store are matched. - * + * * If successful, request's result will be an IDBCursor pointing at the first matching record, or null if there were no matching records. */ openKeyCursor(query?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; /** * Adds or updates a record in store with the given value and key. - * + * * If the store uses in-line keys and key is specified a "DataError" DOMException will be thrown. - * + * * If put() is used, any existing record with the key will be replaced. If add() is used, and if a record with the key already exists the request will fail, with request's error set to a "ConstraintError" DOMException. - * + * * If successful, request's result will be the record's key. */ put(value: any, key?: IDBValidKey): IDBRequest; @@ -2279,7 +2273,7 @@ interface MessagePort extends EventTarget { close(): void; /** * Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side. - * + * * Throws a "DataCloneError" DOMException if transfer contains duplicate objects or port, or if message could not be cloned. */ postMessage(message: any, transfer: Transferable[]): void; @@ -2427,27 +2421,27 @@ interface OES_vertex_array_object { interface OffscreenCanvas extends EventTarget { /** * These attributes return the dimensions of the OffscreenCanvas object's bitmap. - * + * * They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it). */ height: number; /** * These attributes return the dimensions of the OffscreenCanvas object's bitmap. - * + * * They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it). */ width: number; /** * Returns a promise that will fulfill with a new Blob object representing a file containing the image in the OffscreenCanvas object. - * + * * The argument, if provided, is a dictionary that controls the encoding options of the image file to be created. The type field specifies the file format and has a default value of "image/png"; that type is also used if the requested type isn't supported. If the image format supports variable quality (such as "image/jpeg"), then the quality field is a number in the range 0.0 to 1.0 inclusive indicating the desired quality level for the resulting image. */ convertToBlob(options?: ImageEncodeOptions): Promise; /** * Returns an object that exposes an API for drawing on the OffscreenCanvas object. contextId specifies the desired API: "2d", "bitmaprenderer", "webgl", or "webgl2". options is handled by that API. - * + * * This specification defines the "2d" context below, which is similar but distinct from the "2d" context that is created from a canvas element. The WebGL specifications define the "webgl" and "webgl2" contexts. [WEBGL] - * + * * Returns null if the canvas has already been initialized with another context type (e.g., trying to get a "2d" context after getting a "webgl" context). */ getContext(contextId: "2d", options?: CanvasRenderingContext2DSettings): OffscreenCanvasRenderingContext2D | null; @@ -2702,16 +2696,6 @@ declare var PushSubscription: { new(): PushSubscription; }; -interface PushSubscriptionChangeEvent extends ExtendableEvent { - readonly newSubscription: PushSubscription | null; - readonly oldSubscription: PushSubscription | null; -} - -declare var PushSubscriptionChangeEvent: { - prototype: PushSubscriptionChangeEvent; - new(type: string, eventInitDict?: PushSubscriptionChangeEventInit): PushSubscriptionChangeEvent; -}; - interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; readonly userVisibleOnly: boolean; @@ -2913,7 +2897,6 @@ interface ServiceWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { "notificationclick": NotificationEvent; "notificationclose": NotificationEvent; "push": PushEvent; - "pushsubscriptionchange": PushSubscriptionChangeEvent; "sync": SyncEvent; } @@ -2928,7 +2911,6 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { onnotificationclick: ((this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any) | null; onnotificationclose: ((this: ServiceWorkerGlobalScope, ev: NotificationEvent) => any) | null; onpush: ((this: ServiceWorkerGlobalScope, ev: PushEvent) => any) | null; - onpushsubscriptionchange: ((this: ServiceWorkerGlobalScope, ev: PushSubscriptionChangeEvent) => any) | null; onsync: ((this: ServiceWorkerGlobalScope, ev: SyncEvent) => any) | null; readonly registration: ServiceWorkerRegistration; readonly serviceWorker: ServiceWorker; @@ -3078,7 +3060,7 @@ declare var SyncManager: { interface TextDecoder extends TextDecoderCommon { /** * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. - * + * * ``` * var string = "", decoder = new TextDecoder(encoding), buffer; * while(buffer = next_chunk()) { @@ -3086,7 +3068,7 @@ interface TextDecoder extends TextDecoderCommon { * } * string += decoder.decode(); // end-of-queue * ``` - * + * * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. */ decode(input?: BufferSource, options?: TextDecodeOptions): string; @@ -3174,34 +3156,6 @@ interface TextMetrics { * Returns the measurement described below. */ readonly actualBoundingBoxRight: number; - /** - * Returns the measurement described below. - */ - readonly alphabeticBaseline: number; - /** - * Returns the measurement described below. - */ - readonly emHeightAscent: number; - /** - * Returns the measurement described below. - */ - readonly emHeightDescent: number; - /** - * Returns the measurement described below. - */ - readonly fontBoundingBoxAscent: number; - /** - * Returns the measurement described below. - */ - readonly fontBoundingBoxDescent: number; - /** - * Returns the measurement described below. - */ - readonly hangingBaseline: number; - /** - * Returns the measurement described below. - */ - readonly ideographicBaseline: number; /** * Returns the measurement described below. */ @@ -4387,7 +4341,7 @@ declare var WebGLActiveInfo: { }; /** Part of the WebGL API and represents an opaque buffer object storing data such as vertices or colors. */ -interface WebGLBuffer extends WebGLObject { +interface WebGLBuffer { } declare var WebGLBuffer: { @@ -4406,7 +4360,7 @@ declare var WebGLContextEvent: { }; /** Part of the WebGL API and represents a collection of buffers that serve as a rendering destination. */ -interface WebGLFramebuffer extends WebGLObject { +interface WebGLFramebuffer { } declare var WebGLFramebuffer: { @@ -4414,16 +4368,8 @@ declare var WebGLFramebuffer: { new(): WebGLFramebuffer; }; -interface WebGLObject { -} - -declare var WebGLObject: { - prototype: WebGLObject; - new(): WebGLObject; -}; - /** The WebGLProgram is part of the WebGL API and is a combination of two compiled WebGLShaders consisting of a vertex shader and a fragment shader (both written in GLSL). */ -interface WebGLProgram extends WebGLObject { +interface WebGLProgram { } declare var WebGLProgram: { @@ -4431,7 +4377,7 @@ declare var WebGLProgram: { new(): WebGLProgram; }; -interface WebGLQuery extends WebGLObject { +interface WebGLQuery { } declare var WebGLQuery: { @@ -4440,7 +4386,7 @@ declare var WebGLQuery: { }; /** Part of the WebGL API and represents a buffer that can contain an image, or can be source or target of an rendering operation. */ -interface WebGLRenderbuffer extends WebGLObject { +interface WebGLRenderbuffer { } declare var WebGLRenderbuffer: { @@ -5219,7 +5165,7 @@ interface WebGLRenderingContextOverloads { uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Float32List): void; } -interface WebGLSampler extends WebGLObject { +interface WebGLSampler { } declare var WebGLSampler: { @@ -5228,7 +5174,7 @@ declare var WebGLSampler: { }; /** The WebGLShader is part of the WebGL API and can either be a vertex or a fragment shader. A WebGLProgram requires both types of shaders. */ -interface WebGLShader extends WebGLObject { +interface WebGLShader { } declare var WebGLShader: { @@ -5248,7 +5194,7 @@ declare var WebGLShaderPrecisionFormat: { new(): WebGLShaderPrecisionFormat; }; -interface WebGLSync extends WebGLObject { +interface WebGLSync { } declare var WebGLSync: { @@ -5257,7 +5203,7 @@ declare var WebGLSync: { }; /** Part of the WebGL API and represents an opaque texture object providing storage and state for texturing operations. */ -interface WebGLTexture extends WebGLObject { +interface WebGLTexture { } declare var WebGLTexture: { @@ -5265,7 +5211,7 @@ declare var WebGLTexture: { new(): WebGLTexture; }; -interface WebGLTransformFeedback extends WebGLObject { +interface WebGLTransformFeedback { } declare var WebGLTransformFeedback: { @@ -5282,7 +5228,7 @@ declare var WebGLUniformLocation: { new(): WebGLUniformLocation; }; -interface WebGLVertexArrayObject extends WebGLObject { +interface WebGLVertexArrayObject { } declare var WebGLVertexArrayObject: { @@ -5290,7 +5236,7 @@ declare var WebGLVertexArrayObject: { new(): WebGLVertexArrayObject; }; -interface WebGLVertexArrayObjectOES extends WebGLObject { +interface WebGLVertexArrayObjectOES { } interface WebSocketEventMap { @@ -5304,13 +5250,13 @@ interface WebSocketEventMap { interface WebSocket extends EventTarget { /** * Returns a string that indicates how binary data from the WebSocket object is exposed to scripts: - * + * * Can be set, to change how binary data is returned. The default is "blob". */ binaryType: BinaryType; /** * Returns the number of bytes of application data (UTF-8 text and binary data) that have been queued using send() but not yet been transmitted to the network. - * + * * If the WebSocket connection is closed, this attribute's value will only increase with each call to the send() method. (The number does not reset to zero once the connection closes.) */ readonly bufferedAmount: number; @@ -5363,7 +5309,6 @@ declare var WebSocket: { /** This ServiceWorker API interface represents the scope of a service worker client that is a document in a browser context, controlled by an active worker. The service worker client independently selects and uses a service worker for its own loading and sub-resources. */ interface WindowClient extends Client { - readonly ancestorOrigins: ReadonlyArray; readonly focused: boolean; readonly visibilityState: VisibilityState; focus(): Promise; @@ -5486,7 +5431,6 @@ declare var WorkerLocation: { /** A subset of the Navigator interface allowed to be accessed from a Worker. Such an object is initialized for each worker and is available via the WorkerGlobalScope.navigator property obtained by calling window.self.navigator. */ interface WorkerNavigator extends NavigatorConcurrentHardware, NavigatorID, NavigatorLanguage, NavigatorOnLine, NavigatorStorage { readonly permissions: Permissions; - readonly serviceWorker: ServiceWorkerContainer; } declare var WorkerNavigator: { @@ -5549,19 +5493,19 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget { readonly response: any; /** * Returns the text response. - * + * * Throws an "InvalidStateError" DOMException if responseType is not the empty string or "text". */ readonly responseText: string; /** * Returns the response type. - * + * * Can be set to change the response type. Values are: the empty string (default), "arraybuffer", "blob", "document", "json", and "text". - * + * * When set: setting to "document" is ignored if current global object is not a Window object. - * + * * When set: throws an "InvalidStateError" DOMException if state is loading or done. - * + * * When set: throws an "InvalidAccessError" DOMException if the synchronous flag is set and current global object is a Window object. */ responseType: XMLHttpRequestResponseType; @@ -5570,7 +5514,7 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget { readonly statusText: string; /** * Can be set to a time in milliseconds. When set to a non-zero value will cause fetching to terminate after the given time has passed. When the time has passed, the request has not yet completed, and the synchronous flag is unset, a timeout event will then be dispatched, or a "TimeoutError" DOMException will be thrown otherwise (for the send() method). - * + * * When set: throws an "InvalidAccessError" DOMException if the synchronous flag is set and current global object is a Window object. */ timeout: number; @@ -5580,7 +5524,7 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget { readonly upload: XMLHttpRequestUpload; /** * True when credentials are to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. Initially false. - * + * * When set: throws an "InvalidStateError" DOMException if state is not unsent or opened, or if the send() flag is set. */ withCredentials: boolean; @@ -5592,32 +5536,32 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget { getResponseHeader(name: string): string | null; /** * Sets the request method, request URL, and synchronous flag. - * + * * Throws a "SyntaxError" DOMException if either method is not a valid HTTP method or url cannot be parsed. - * + * * Throws a "SecurityError" DOMException if method is a case-insensitive match for `CONNECT`, `TRACE`, or `TRACK`. - * + * * Throws an "InvalidAccessError" DOMException if async is false, current global object is a Window object, and the timeout attribute is not zero or the responseType attribute is not the empty string. */ open(method: string, url: string): void; open(method: string, url: string, async: boolean, username?: string | null, password?: string | null): void; /** * Acts as if the `Content-Type` header value for response is mime. (It does not actually change the header though.) - * + * * Throws an "InvalidStateError" DOMException if state is loading or done. */ overrideMimeType(mime: string): void; /** * Initiates the request. The body argument provides the request body, if any, and is ignored if the request method is GET or HEAD. - * + * * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set. */ send(body?: BodyInit | null): void; /** * Combines a header in author request headers. - * + * * Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set. - * + * * Throws a "SyntaxError" DOMException if name is not a header name or if value is not a header value. */ setRequestHeader(name: string, value: string): void; @@ -5717,34 +5661,34 @@ declare namespace WebAssembly { value: any; valueOf(): any; } - + var Global: { prototype: Global; new(descriptor: GlobalDescriptor, v?: any): Global; }; - + interface Instance { readonly exports: Exports; } - + var Instance: { prototype: Instance; new(module: Module, importObject?: Imports): Instance; }; - + interface Memory { readonly buffer: ArrayBuffer; grow(delta: number): number; } - + var Memory: { prototype: Memory; new(descriptor: MemoryDescriptor): Memory; }; - + interface Module { } - + var Module: { prototype: Module; new(bytes: BufferSource): Module; @@ -5752,51 +5696,52 @@ declare namespace WebAssembly { exports(moduleObject: Module): ModuleExportDescriptor[]; imports(moduleObject: Module): ModuleImportDescriptor[]; }; - + interface Table { readonly length: number; get(index: number): Function | null; grow(delta: number): number; set(index: number, value: Function | null): void; } - + var Table: { prototype: Table; new(descriptor: TableDescriptor): Table; }; - + interface GlobalDescriptor { mutable?: boolean; value: ValueType; } - + interface MemoryDescriptor { initial: number; maximum?: number; + shared?: boolean; } - + interface ModuleExportDescriptor { kind: ImportExportKind; name: string; } - + interface ModuleImportDescriptor { kind: ImportExportKind; module: string; name: string; } - + interface TableDescriptor { element: TableKind; initial: number; maximum?: number; } - + interface WebAssemblyInstantiatedSource { instance: Instance; module: Module; } - + type ImportExportKind = "function" | "global" | "memory" | "table"; type TableKind = "anyfunc"; type ValueType = "f32" | "f64" | "i32" | "i64"; diff --git a/src/lib/webworker.iterable.generated.d.ts b/src/lib/webworker.iterable.generated.d.ts index 249b5b899d9f8..48ab3b9a71258 100644 --- a/src/lib/webworker.iterable.generated.d.ts +++ b/src/lib/webworker.iterable.generated.d.ts @@ -60,7 +60,7 @@ interface IDBDatabase { interface IDBObjectStore { /** * Creates a new index in store with the given name, keyPath and options and returns a new IDBIndex. If the keyPath and options define constraints that cannot be satisfied with the data already in store the upgrade transaction will abort with a "ConstraintError" DOMException. - * + * * Throws an "InvalidStateError" DOMException if not called within an upgrade transaction. */ createIndex(name: string, keyPath: string | Iterable, options?: IDBIndexParameters): IDBIndex; diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 1965cb20c8d49..f012491731867 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -359,15 +359,7 @@ namespace ts.server { } } - const enum ConfigFileWatcherStatus { - ReloadingFiles = "Reloading configured projects for files", - ReloadingInferredRootFiles = "Reloading configured projects for only inferred root files", - UpdatedCallback = "Updated the callback", - OpenFilesImpactedByConfigFileAdd = "File added to open files impacted by this config file", - OpenFilesImpactedByConfigFileRemove = "File removed from open files impacted by this config file", - RootOfInferredProjectTrue = "Open file was set as Inferred root", - RootOfInferredProjectFalse = "Open file was set as not inferred root", - } + const noopConfigFileWatcher: FileWatcher = { close: noop }; /*@internal*/ interface ConfigFileExistenceInfo { @@ -386,13 +378,20 @@ namespace ts.server { * It is false when the open file that would still be impacted by existence of * this config file but it is not the root of inferred project */ - openFilesImpactedByConfigFile: ESMap; + openFilesImpactedByConfigFile?: ESMap; /** * The file watcher watching the config file because there is open script info that is root of * inferred project and will be impacted by change in the status of the config file - * The watcher is present only when there is no open configured project for the config file + * or + * Configured project for this config file is open + * or + * Configured project references this config file + */ + watcher?: FileWatcher; + /** + * Cached parsed command line and other related information like watched directories etc */ - configFileWatcherForRootOfInferredProject?: FileWatcher; + config?: ParsedConfig; } export interface ProjectServiceOptions { @@ -594,8 +593,8 @@ namespace ts.server { refCount: number; } - function getDetailWatchInfo(watchType: WatchType, project: Project | undefined) { - return `Project: ${project ? project.getProjectName() : ""} WatchType: ${watchType}`; + function getDetailWatchInfo(watchType: WatchType, project: Project | NormalizedPath | undefined) { + return `${isString(project) ? `Config: ${project} ` : project ? `Project: ${project.getProjectName()} ` : ""}WatchType: ${watchType}`; } function isScriptInfoWatchedFromNodeModules(info: ScriptInfo) { @@ -641,6 +640,24 @@ namespace ts.server { errors: Diagnostic[] | undefined; } + /*@internal*/ + export interface ParsedConfig{ + cachedDirectoryStructureHost: CachedDirectoryStructureHost; + /** + * The map contains + * - true if project is watching config file as well as wild cards + * - false if just config file is watched + */ + projects: ESMap; + parsedCommandLine?: ParsedCommandLine; + watchedDirectories?: Map; + /** + * true if watchedDirectories need to be updated as per parsedCommandLine's updated watched directories + */ + watchedDirectoriesStale?: boolean; + reloadLevel?: ConfigFileProgramReloadLevel.Partial | ConfigFileProgramReloadLevel.Full; + } + export class ProjectService { /*@internal*/ @@ -714,7 +731,7 @@ namespace ts.server { * - Or it is present if we have configured project open with config file at that location * In this case the exists property is always true */ - private readonly configFileExistenceInfoCache = new Map(); + /*@internal*/ readonly configFileExistenceInfoCache = new Map(); /*@internal*/ readonly throttledOperations: ThrottledOperations; private readonly hostConfiguration: HostConfiguration; @@ -754,10 +771,12 @@ namespace ts.server { private readonly seenProjects = new Map(); /*@internal*/ - readonly watchFactory: WatchFactory; + readonly watchFactory: WatchFactory; /*@internal*/ private readonly sharedExtendedConfigFileWatchers = new Map>(); + /*@internal*/ + private readonly extendedConfigCache = new Map(); /*@internal*/ readonly packageJsonCache: PackageJsonCache; @@ -1185,9 +1204,6 @@ namespace ts.server { } private onSourceFileChanged(info: ScriptInfo, eventKind: FileWatcherEventKind) { - if (info.containingProjects) { - info.containingProjects.forEach(project => project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(info.path)); - } if (eventKind === FileWatcherEventKind.Deleted) { // File was deleted this.handleDeletedFile(info); @@ -1261,21 +1277,20 @@ namespace ts.server { * This is to watch whenever files are added or removed to the wildcard directories */ /*@internal*/ - watchWildcardDirectory(directory: Path, flags: WatchDirectoryFlags, project: ConfiguredProject) { - const watchOptions = this.getWatchOptions(project); + private watchWildcardDirectory(directory: Path, flags: WatchDirectoryFlags, configFileName: NormalizedPath, config: ParsedConfig) { return this.watchFactory.watchDirectory( directory, fileOrDirectory => { const fileOrDirectoryPath = this.toPath(fileOrDirectory); - const fsResult = project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); - const configFileName = project.getConfigFilePath(); + const fsResult = config.cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); if (getBaseFileName(fileOrDirectoryPath) === "package.json" && !isInsideNodeModules(fileOrDirectoryPath) && (fsResult && fsResult.fileExists || !fsResult && this.host.fileExists(fileOrDirectoryPath)) ) { - this.logger.info(`Project: ${configFileName} Detected new package.json: ${fileOrDirectory}`); + this.logger.info(`Config: ${configFileName} Detected new package.json: ${fileOrDirectory}`); this.onAddPackageJson(fileOrDirectoryPath); } + const configuredProjectForConfig = this.findConfiguredProjectByProjectName(configFileName); if (isIgnoredFileFromWildCardWatching({ watchedDirPath: directory, fileOrDirectory, @@ -1283,128 +1298,118 @@ namespace ts.server { configFileName, extraFileExtensions: this.hostConfiguration.extraFileExtensions, currentDirectory: this.currentDirectory, - options: project.getCompilationSettings(), - program: project.getCurrentProgram(), + options: config.parsedCommandLine!.options, + program: configuredProjectForConfig?.getCurrentProgram() || config.parsedCommandLine!.fileNames, useCaseSensitiveFileNames: this.host.useCaseSensitiveFileNames, - writeLog: s => this.logger.info(s) + writeLog: s => this.logger.info(s), + toPath: s => this.toPath(s) })) return; - // don't trigger callback on open, existing files - if (project.fileIsOpen(fileOrDirectoryPath)) { - if (project.pendingReload !== ConfigFileProgramReloadLevel.Full) { + // Reload is pending, do the reload + if (config.reloadLevel !== ConfigFileProgramReloadLevel.Full) config.reloadLevel = ConfigFileProgramReloadLevel.Partial; + config.projects.forEach((watchWildcardDirectories, projectCanonicalPath) => { + if (!watchWildcardDirectories) return; + const project = this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath); + if (!project) return; + + // Load root file names for configured project with the config file name + // But only schedule update if project references this config file + const reloadLevel = configuredProjectForConfig === project ? ConfigFileProgramReloadLevel.Partial : ConfigFileProgramReloadLevel.None; + if (project.pendingReload !== undefined && project.pendingReload > reloadLevel) return; + + // don't trigger callback on open, existing files + if (this.openFiles.has(fileOrDirectoryPath)) { const info = Debug.checkDefined(this.getScriptInfoForPath(fileOrDirectoryPath)); if (info.isAttached(project)) { - project.openFileWatchTriggered.set(fileOrDirectoryPath, true); + const loadLevelToSet = Math.max(reloadLevel, project.openFileWatchTriggered.get(fileOrDirectoryPath) || ConfigFileProgramReloadLevel.None) as ConfigFileProgramReloadLevel; + project.openFileWatchTriggered.set(fileOrDirectoryPath, loadLevelToSet); } else { - project.pendingReload = ConfigFileProgramReloadLevel.Partial; + project.pendingReload = reloadLevel; this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); } } - return; - } - - // Reload is pending, do the reload - if (project.pendingReload !== ConfigFileProgramReloadLevel.Full) { - project.pendingReload = ConfigFileProgramReloadLevel.Partial; - this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); - } + else { + project.pendingReload = reloadLevel; + this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); + } + }); }, flags, - watchOptions, + this.getWatchOptionsFromProjectWatchOptions(config.parsedCommandLine!.watchOptions), WatchType.WildcardDirectory, - project + configFileName ); } - /** Gets the config file existence info for the configured project */ /*@internal*/ - getConfigFileExistenceInfo(project: ConfiguredProject) { - return this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath)!; + private delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalConfigFilePath: NormalizedPath, reloadReason: string) { + const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!configFileExistenceInfo?.config) return false; + let scheduledAnyProjectUpdate = false; + // Update projects watching cached config + configFileExistenceInfo.config.reloadLevel = ConfigFileProgramReloadLevel.Full; + + configFileExistenceInfo.config.projects.forEach((_watchWildcardDirectories, projectCanonicalPath) => { + const project = this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath); + if (!project) return; + + scheduledAnyProjectUpdate = true; + if (projectCanonicalPath === canonicalConfigFilePath) { + // Skip refresh if project is not yet loaded + if (project.isInitialLoadPending()) return; + project.pendingReload = ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reloadReason; + this.delayUpdateProjectGraph(project); + } + else { + // Change in referenced project config file + project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(this.toPath(canonicalConfigFilePath)); + this.delayUpdateProjectGraph(project); + } + }); + return scheduledAnyProjectUpdate; } /*@internal*/ - onConfigChangedForConfiguredProject(project: ConfiguredProject, eventKind: FileWatcherEventKind) { - const configFileExistenceInfo = this.getConfigFileExistenceInfo(project); + private onConfigFileChanged(canonicalConfigFilePath: NormalizedPath, eventKind: FileWatcherEventKind) { + const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath)!; if (eventKind === FileWatcherEventKind.Deleted) { // Update the cached status // We arent updating or removing the cached config file presence info as that will be taken care of by - // setConfigFilePresenceByClosedConfigFile when the project is closed (depending on tracking open files) + // releaseParsedConfig when the project is closed or doesnt need this config any more (depending on tracking open files) configFileExistenceInfo.exists = false; - this.removeProject(project); - // Reload the configured projects for the open files in the map as they are affected by this config file - // Since the configured project was deleted, we want to reload projects for all the open files including files - // that are not root of the inferred project - this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, ConfigFileWatcherStatus.ReloadingFiles); - this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false); + // Remove the configured project for this config file + const project = configFileExistenceInfo.config?.projects.has(canonicalConfigFilePath) ? + this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath) : + undefined; + if (project) this.removeProject(project); } else { - this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, ConfigFileWatcherStatus.ReloadingInferredRootFiles); - // Skip refresh if project is not yet loaded - if (project.isInitialLoadPending()) return; - 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 - this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ true); + // Update the cached status + configFileExistenceInfo.exists = true; } - } - - /*@internal*/ - updateSharedExtendedConfigFileMap({ canonicalConfigFilePath }: ConfiguredProject, parsedCommandLine: ParsedCommandLine) { - updateSharedExtendedConfigFileWatcher( - canonicalConfigFilePath, - parsedCommandLine, - this.sharedExtendedConfigFileWatchers, - (extendedConfigFileName, extendedConfigFilePath) => this.watchFactory.watchFile( - extendedConfigFileName, - () => { - let ensureProjectsForOpenFiles = false; - this.sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)?.projects.forEach(canonicalPath => { - const project = this.configuredProjects.get(canonicalPath); - // Skip refresh if project is not yet loaded - if (!project || project.isInitialLoadPending()) return; - project.pendingReload = ConfigFileProgramReloadLevel.Full; - project.pendingReloadReason = `Change in extended config file ${extendedConfigFileName} detected`; - this.delayUpdateProjectGraph(project); - ensureProjectsForOpenFiles = true; - }); - if (ensureProjectsForOpenFiles) this.delayEnsureProjectForOpenFiles(); - }, - PollingInterval.High, - this.hostConfiguration.watchOptions, - WatchType.ExtendedConfigFile - ), - fileName => this.toPath(fileName), - ); - } - - /*@internal*/ - removeProjectFromSharedExtendedConfigFileMap(project: ConfiguredProject) { - this.sharedExtendedConfigFileWatchers.forEach(watcher => { - watcher.projects.delete(project.canonicalConfigFilePath); - watcher.close(); - }); - } - /** - * This is the callback function for the config file add/remove/change at any location - * that matters to open script info but doesnt have configured project open - * for the config file - */ - private onConfigFileChangeForOpenScriptInfo(configFileName: NormalizedPath, eventKind: FileWatcherEventKind) { - // This callback is called only if we dont have config file project for this config file - const canonicalConfigPath = normalizedPathToPath(configFileName, this.currentDirectory, this.toCanonicalFileName); - const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigPath)!; - configFileExistenceInfo.exists = (eventKind !== FileWatcherEventKind.Deleted); - this.logConfigFileWatchUpdate(configFileName, canonicalConfigPath, configFileExistenceInfo, ConfigFileWatcherStatus.ReloadingFiles); + // Update projects watching config + this.delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalConfigFilePath, "Change in config file detected"); - // Because there is no configured project open for the config file, the tracking open files map - // will only have open files that need the re-detection of the project and hence - // reload projects for all the tracking open files in the map - this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false); + // Reload the configured projects for the open files in the map as they are affected by this config file + // If the configured project was deleted, we want to reload projects for all the open files including files + // that are not root of the inferred project + // Otherwise, we scheduled the update on configured project graph, + // we would need to schedule the project reload for only the root of inferred projects + // Get open files to reload projects for + this.reloadConfiguredProjectForFiles( + configFileExistenceInfo.openFilesImpactedByConfigFile, + /*clearSemanticCache*/ false, + /*delayReload*/ true, + eventKind !== FileWatcherEventKind.Deleted ? + identity : // Reload open files if they are root of inferred project + returnTrue, // Reload all the open files impacted by config file + "Change in config file detected" + ); + this.delayEnsureProjectForOpenFiles(); } private removeProject(project: Project) { @@ -1443,7 +1448,6 @@ namespace ts.server { case ProjectKind.Configured: this.configuredProjects.delete((project).canonicalConfigFilePath); this.projectToSizeMap.delete((project as ConfiguredProject).canonicalConfigFilePath); - this.setConfigFileExistenceInfoByClosedConfiguredProject(project); break; case ProjectKind.Inferred: unorderedRemoveItem(this.inferredProjects, project); @@ -1546,10 +1550,11 @@ namespace ts.server { // If project had open file affecting // Reload the root Files from config if its not already scheduled - if (p.openFileWatchTriggered.has(info.path)) { + const reloadLevel = p.openFileWatchTriggered.get(info.path); + if (reloadLevel !== undefined) { p.openFileWatchTriggered.delete(info.path); - if (!p.pendingReload) { - p.pendingReload = ConfigFileProgramReloadLevel.Partial; + if (p.pendingReload !== undefined && p.pendingReload < reloadLevel) { + p.pendingReload = reloadLevel; p.markFileAsDirty(info.path); } } @@ -1605,14 +1610,13 @@ namespace ts.server { } } - private configFileExists(configFileName: NormalizedPath, canonicalConfigFilePath: string, info: OpenScriptInfoOrClosedOrConfigFileInfo) { + private configFileExists(configFileName: NormalizedPath, canonicalConfigFilePath: NormalizedPath, info: OpenScriptInfoOrClosedOrConfigFileInfo) { let configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (configFileExistenceInfo) { // By default the info would get impacted by presence of config file since its in the detection path // Only adding the info as a root to inferred project will need the existence to be watched by file watcher - if (isOpenScriptInfo(info) && !configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { - configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); - this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, ConfigFileWatcherStatus.OpenFilesImpactedByConfigFileAdd); + if (isOpenScriptInfo(info) && !configFileExistenceInfo.openFilesImpactedByConfigFile?.has(info.path)) { + (configFileExistenceInfo.openFilesImpactedByConfigFile ||= new Map()).set(info.path, false); } return configFileExistenceInfo.exists; } @@ -1628,121 +1632,89 @@ namespace ts.server { // Cache the host value of file exists and add the info to map of open files impacted by this config file const exists = this.host.fileExists(configFileName); - const openFilesImpactedByConfigFile = new Map(); + let openFilesImpactedByConfigFile: ESMap | undefined; if (isOpenScriptInfo(info)) { - openFilesImpactedByConfigFile.set(info.path, false); + (openFilesImpactedByConfigFile ||= new Map()).set(info.path, false); } configFileExistenceInfo = { exists, openFilesImpactedByConfigFile }; this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); - this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, ConfigFileWatcherStatus.OpenFilesImpactedByConfigFileAdd); return exists; } - private setConfigFileExistenceByNewConfiguredProject(project: ConfiguredProject) { - const configFileExistenceInfo = this.getConfigFileExistenceInfo(project); - if (configFileExistenceInfo) { - // The existence might not be set if the file watcher is not invoked by the time config project is created by external project - configFileExistenceInfo.exists = true; - // close existing watcher - if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { - const configFileName = project.getConfigFilePath(); - configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close(); - configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined; - this.logConfigFileWatchUpdate(configFileName, project.canonicalConfigFilePath, configFileExistenceInfo, ConfigFileWatcherStatus.UpdatedCallback); - } - } - else { - // We could be in this scenario if project is the configured project tracked by external project - // Since that route doesnt check if the config file is present or not - this.configFileExistenceInfoCache.set(project.canonicalConfigFilePath, { - exists: true, - openFilesImpactedByConfigFile: new Map() - }); + /*@internal*/ + private createConfigFileWatcherForParsedConfig(configFileName: NormalizedPath, canonicalConfigFilePath: NormalizedPath, forProject: ConfiguredProject) { + const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath)!; + // When watching config file for parsed config, remove the noopFileWatcher that can be created for open files impacted by config file and watch for real + if (!configFileExistenceInfo.watcher || configFileExistenceInfo.watcher === noopConfigFileWatcher) { + configFileExistenceInfo.watcher = this.watchFactory.watchFile( + configFileName, + (_fileName, eventKind) => this.onConfigFileChanged(canonicalConfigFilePath, eventKind), + PollingInterval.High, + this.getWatchOptionsFromProjectWatchOptions(configFileExistenceInfo?.config?.parsedCommandLine?.watchOptions), + WatchType.ConfigFile, + forProject + ); } + // Watching config file for project, update the map + const projects = configFileExistenceInfo.config!.projects; + projects.set(forProject.canonicalConfigFilePath, projects.get(forProject.canonicalConfigFilePath) || false); } /** * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project */ private configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo: ConfigFileExistenceInfo) { - return forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, (isRootOfInferredProject) => isRootOfInferredProject); + return configFileExistenceInfo.openFilesImpactedByConfigFile && + forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, identity); } - private setConfigFileExistenceInfoByClosedConfiguredProject(closedProject: ConfiguredProject) { - const configFileExistenceInfo = this.getConfigFileExistenceInfo(closedProject); - Debug.assert(!!configFileExistenceInfo); - if (configFileExistenceInfo.openFilesImpactedByConfigFile.size) { - const configFileName = closedProject.getConfigFilePath(); + /* @internal */ + releaseParsedConfig(canonicalConfigFilePath: NormalizedPath, forProject: ConfiguredProject) { + const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath)!; + if (!configFileExistenceInfo.config?.projects.delete(forProject.canonicalConfigFilePath)) return; + // If there are still projects watching this config file existence and config, there is nothing to do + if (configFileExistenceInfo.config?.projects.size) return; + + configFileExistenceInfo.config = undefined; + clearSharedExtendedConfigFileWatcher(canonicalConfigFilePath, this.sharedExtendedConfigFileWatchers); + Debug.checkDefined(configFileExistenceInfo.watcher); + if (configFileExistenceInfo.openFilesImpactedByConfigFile?.size) { // If there are open files that are impacted by this config file existence // but none of them are root of inferred project, the config file watcher will be // created when any of the script infos are added as root of inferred project if (this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { - Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject); - this.createConfigFileWatcherOfConfigFileExistence(configFileName, closedProject.canonicalConfigFilePath, configFileExistenceInfo); + // If we cannot watch config file existence without configured project, close the configured file watcher + if (!canWatchDirectory(getDirectoryPath(canonicalConfigFilePath) as Path)) { + configFileExistenceInfo.watcher!.close(); + configFileExistenceInfo.watcher = noopConfigFileWatcher; + } + } + else { + // Close existing watcher + configFileExistenceInfo.watcher!.close(); + configFileExistenceInfo.watcher = undefined; } } else { // There is not a single file open thats tracking the status of this config file. Remove from cache - this.configFileExistenceInfoCache.delete(closedProject.canonicalConfigFilePath); - } - } - - private logConfigFileWatchUpdate(configFileName: NormalizedPath, canonicalConfigFilePath: string, configFileExistenceInfo: ConfigFileExistenceInfo, status: ConfigFileWatcherStatus) { - if (!this.logger.hasLevel(LogLevel.verbose)) { - return; - } - const inferredRoots: string[] = []; - const otherFiles: string[] = []; - configFileExistenceInfo.openFilesImpactedByConfigFile.forEach((isRootOfInferredProject, key) => { - const info = this.getScriptInfoForPath(key)!; - (isRootOfInferredProject ? inferredRoots : otherFiles).push(info.fileName); - }); - - const watches: WatchType[] = []; - if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { - watches.push( - configFileExistenceInfo.configFileWatcherForRootOfInferredProject === noopFileWatcher ? - WatchType.NoopConfigFileForInferredRoot : - WatchType.ConfigFileForInferredRoot - ); - } - if (this.configuredProjects.has(canonicalConfigFilePath)) { - watches.push(WatchType.ConfigFile); + configFileExistenceInfo.watcher!.close(); + this.configFileExistenceInfoCache.delete(canonicalConfigFilePath); } - this.logger.info(`ConfigFilePresence:: Current Watches: ${watches}:: File: ${configFileName} Currently impacted open files: RootsOfInferredProjects: ${inferredRoots} OtherOpenFiles: ${otherFiles} Status: ${status}`); - } - - /** - * Create the watcher for the configFileExistenceInfo - */ - private createConfigFileWatcherOfConfigFileExistence( - configFileName: NormalizedPath, - canonicalConfigFilePath: string, - configFileExistenceInfo: ConfigFileExistenceInfo - ) { - configFileExistenceInfo.configFileWatcherForRootOfInferredProject = - canWatchDirectory(getDirectoryPath(canonicalConfigFilePath) as Path) ? - this.watchFactory.watchFile( - configFileName, - (_filename, eventKind) => this.onConfigFileChangeForOpenScriptInfo(configFileName, eventKind), - PollingInterval.High, - this.hostConfiguration.watchOptions, - WatchType.ConfigFileForInferredRoot - ) : - noopFileWatcher; - this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, ConfigFileWatcherStatus.UpdatedCallback); } /** * Close the config file watcher in the cached ConfigFileExistenceInfo - * if there arent any open files that are root of inferred project + * if there arent any open files that are root of inferred project and there is no parsed config held by any project */ - private closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo: ConfigFileExistenceInfo) { + /*@internal*/ + private closeConfigFileWatcherOnReleaseOfOpenFile(configFileExistenceInfo: ConfigFileExistenceInfo) { // Close the config file watcher if there are no more open files that are root of inferred project - if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject && + // or if there are no projects that need to watch this config file existence info + if (configFileExistenceInfo.watcher && + !configFileExistenceInfo.config && !this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { - configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close(); - configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined; + configFileExistenceInfo.watcher.close(); + configFileExistenceInfo.watcher = undefined; } } @@ -1751,28 +1723,28 @@ namespace ts.server { */ private stopWatchingConfigFilesForClosedScriptInfo(info: ScriptInfo) { Debug.assert(!info.isScriptOpen()); - this.forEachConfigFileLocation(info, (configFileName, canonicalConfigFilePath) => { + this.forEachConfigFileLocation(info, canonicalConfigFilePath => { const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (configFileExistenceInfo) { - const infoIsRootOfInferredProject = configFileExistenceInfo.openFilesImpactedByConfigFile.get(info.path); + const infoIsRootOfInferredProject = configFileExistenceInfo.openFilesImpactedByConfigFile?.get(info.path); // Delete the info from map, since this file is no more open - configFileExistenceInfo.openFilesImpactedByConfigFile.delete(info.path); - this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, ConfigFileWatcherStatus.OpenFilesImpactedByConfigFileRemove); + configFileExistenceInfo.openFilesImpactedByConfigFile?.delete(info.path); // If the script info was not root of inferred project, // there wont be config file watch open because of this script info if (infoIsRootOfInferredProject) { // But if it is a root, it could be the last script info that is root of inferred project // and hence we would need to close the config file watcher - this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); + this.closeConfigFileWatcherOnReleaseOfOpenFile(configFileExistenceInfo); } // If there are no open files that are impacted by configFileExistenceInfo after closing this script info - // there is no configured project present, remove the cached existence info - if (!configFileExistenceInfo.openFilesImpactedByConfigFile.size && - !this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) { - Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject); + // and there is are no projects that need the config file existence or parsed config, + // remove the cached existence info + if (!configFileExistenceInfo.openFilesImpactedByConfigFile?.size && + !configFileExistenceInfo.config) { + Debug.assert(!configFileExistenceInfo.watcher); this.configFileExistenceInfoCache.delete(canonicalConfigFilePath); } } @@ -1785,26 +1757,27 @@ namespace ts.server { /* @internal */ startWatchingConfigFilesForInferredProjectRoot(info: ScriptInfo) { Debug.assert(info.isScriptOpen()); - this.forEachConfigFileLocation(info, (configFileName, canonicalConfigFilePath) => { + this.forEachConfigFileLocation(info, (canonicalConfigFilePath, configFileName) => { let configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (!configFileExistenceInfo) { // Create the cache - configFileExistenceInfo = { - exists: this.host.fileExists(configFileName), - openFilesImpactedByConfigFile: new Map() - }; + configFileExistenceInfo = { exists: this.host.fileExists(configFileName) }; this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); } // Set this file as the root of inferred project - configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, true); - this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, ConfigFileWatcherStatus.RootOfInferredProjectTrue); + (configFileExistenceInfo.openFilesImpactedByConfigFile ||= new Map()).set(info.path, true); // If there is no configured project for this config file, add the file watcher - if (!configFileExistenceInfo.configFileWatcherForRootOfInferredProject && - !this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) { - this.createConfigFileWatcherOfConfigFileExistence(configFileName, canonicalConfigFilePath, configFileExistenceInfo); - } + configFileExistenceInfo.watcher ||= canWatchDirectory(getDirectoryPath(canonicalConfigFilePath) as Path) ? + this.watchFactory.watchFile( + configFileName, + (_filename, eventKind) => this.onConfigFileChanged(canonicalConfigFilePath, eventKind), + PollingInterval.High, + this.hostConfiguration.watchOptions, + WatchType.ConfigFileForInferredRoot + ) : + noopConfigFileWatcher; }); } @@ -1813,17 +1786,16 @@ namespace ts.server { */ /* @internal */ stopWatchingConfigFilesForInferredProjectRoot(info: ScriptInfo) { - this.forEachConfigFileLocation(info, (configFileName, canonicalConfigFilePath) => { + this.forEachConfigFileLocation(info, canonicalConfigFilePath => { const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); - if (configFileExistenceInfo && configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) { + if (configFileExistenceInfo?.openFilesImpactedByConfigFile?.has(info.path)) { Debug.assert(info.isScriptOpen()); // Info is not root of inferred project any more configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); - this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, ConfigFileWatcherStatus.RootOfInferredProjectFalse); // Close the config file watcher - this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); + this.closeConfigFileWatcherOnReleaseOfOpenFile(configFileExistenceInfo); } }); } @@ -1836,7 +1808,7 @@ namespace ts.server { * The server must start searching from the directory containing * the newly opened file. */ - private forEachConfigFileLocation(info: OpenScriptInfoOrClosedOrConfigFileInfo, action: (configFileName: NormalizedPath, canonicalConfigFilePath: string) => boolean | void) { + private forEachConfigFileLocation(info: OpenScriptInfoOrClosedOrConfigFileInfo, action: (canonicalConfigFilePath: NormalizedPath, configFileName: NormalizedPath) => boolean | void) { if (this.serverMode !== LanguageServiceMode.Semantic) { return undefined; } @@ -1857,11 +1829,11 @@ namespace ts.server { if (searchInDirectory) { const canonicalSearchPath = normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName); const tsconfigFileName = asNormalizedPath(combinePaths(searchPath, "tsconfig.json")); - let result = action(tsconfigFileName, combinePaths(canonicalSearchPath, "tsconfig.json")); + let result = action(combinePaths(canonicalSearchPath, "tsconfig.json") as NormalizedPath, tsconfigFileName); if (result) return tsconfigFileName; const jsconfigFileName = asNormalizedPath(combinePaths(searchPath, "jsconfig.json")); - result = action(jsconfigFileName, combinePaths(canonicalSearchPath, "jsconfig.json")); + result = action(combinePaths(canonicalSearchPath, "jsconfig.json") as NormalizedPath, jsconfigFileName); if (result) return jsconfigFileName; // If we started within node_modules, don't look outside node_modules. @@ -1910,7 +1882,7 @@ namespace ts.server { if (result !== undefined) return result || undefined; } this.logger.info(`Search path: ${getDirectoryPath(info.fileName)}`); - const configFileName = this.forEachConfigFileLocation(info, (configFileName, canonicalConfigFilePath) => + const configFileName = this.forEachConfigFileLocation(info, (canonicalConfigFilePath, configFileName) => this.configFileExists(configFileName, canonicalConfigFilePath, info)); if (configFileName) { this.logger.info(`For info: ${info.fileName} :: Config file name: ${configFileName}`); @@ -2072,16 +2044,33 @@ namespace ts.server { /* @internal */ createConfiguredProject(configFileName: NormalizedPath) { - const cachedDirectoryStructureHost = createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames)!; // TODO: GH#18217 - this.logger.info(`Opened configuration file ${configFileName}`); + this.logger.info(`Creating configuration project ${configFileName}`); + const canonicalConfigFilePath = asNormalizedPath(this.toCanonicalFileName(configFileName)); + let configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); + // We could be in this scenario if project is the configured project tracked by external project + // Since that route doesnt check if the config file is present or not + if (!configFileExistenceInfo) { + this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo = { exists: true }); + } + else { + configFileExistenceInfo.exists = true; + } + if (!configFileExistenceInfo.config) { + configFileExistenceInfo.config = { + cachedDirectoryStructureHost: createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames)!, + projects: new Map(), + reloadLevel: ConfigFileProgramReloadLevel.Full + }; + } + const project = new ConfiguredProject( configFileName, + canonicalConfigFilePath, this, this.documentRegistry, - cachedDirectoryStructureHost); - project.createConfigFileWatcher(); - this.configuredProjects.set(project.canonicalConfigFilePath, project); - this.setConfigFileExistenceByNewConfiguredProject(project); + configFileExistenceInfo.config.cachedDirectoryStructureHost); + this.configuredProjects.set(canonicalConfigFilePath, project); + this.createConfigFileWatcherForParsedConfig(configFileName, canonicalConfigFilePath, project); return project; } @@ -2115,33 +2104,14 @@ namespace ts.server { this.sendProjectLoadingStartEvent(project, reason); // Read updated contents from disk - const configFilename = normalizePath(project.getConfigFilePath()); - - const configFileContent = tryReadFile(configFilename, fileName => this.host.readFile(fileName)); - const result = parseJsonText(configFilename, isString(configFileContent) ? configFileContent : ""); - const configFileErrors = result.parseDiagnostics as Diagnostic[]; - if (!isString(configFileContent)) configFileErrors.push(configFileContent); - const parsedCommandLine = parseJsonSourceFileConfigFileContent( - result, - project.getCachedDirectoryStructureHost(), - getDirectoryPath(configFilename), - /*existingOptions*/ {}, + const configFilename = asNormalizedPath(normalizePath(project.getConfigFilePath())); + const configFileExistenceInfo = this.ensureParsedConfigUptoDate( configFilename, - /*resolutionStack*/[], - this.hostConfiguration.extraFileExtensions, - /*extendedConfigCache*/ undefined, + project.canonicalConfigFilePath, + this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath)!, + project ); - - if (parsedCommandLine.errors.length) { - configFileErrors.push(...parsedCommandLine.errors); - } - - this.logger.info(`Config: ${configFilename} : ${JSON.stringify({ - rootNames: parsedCommandLine.fileNames, - options: parsedCommandLine.options, - projectReferences: parsedCommandLine.projectReferences - }, /*replacer*/ undefined, " ")}`); - + const parsedCommandLine = configFileExistenceInfo.config!.parsedCommandLine!; Debug.assert(!!parsedCommandLine.fileNames); const compilerOptions = parsedCommandLine.options; @@ -2155,26 +2125,155 @@ namespace ts.server { }; } project.canConfigFileJsonReportNoInputFiles = canJsonReportNoInputFiles(parsedCommandLine.raw); - project.setProjectErrors(configFileErrors); + project.setProjectErrors(parsedCommandLine.options.configFile!.parseDiagnostics); project.updateReferences(parsedCommandLine.projectReferences); const lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); if (lastFileExceededProgramSize) { project.disableLanguageService(lastFileExceededProgramSize); - project.stopWatchingWildCards(); - this.removeProjectFromSharedExtendedConfigFileMap(project); + this.configFileExistenceInfoCache.forEach((_configFileExistenceInfo, canonicalConfigFilePath) => + this.stopWatchingWildCards(canonicalConfigFilePath, project)); } else { project.setCompilerOptions(compilerOptions); project.setWatchOptions(parsedCommandLine.watchOptions); project.enableLanguageService(); - project.watchWildcards(new Map(getEntries(parsedCommandLine.wildcardDirectories!))); // TODO: GH#18217 - this.updateSharedExtendedConfigFileMap(project, parsedCommandLine); + this.watchWildcards(configFilename, configFileExistenceInfo, project); } project.enablePluginsWithOptions(compilerOptions, this.currentPluginConfigOverrides); const filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition!, parsedCommandLine.compileOnSave, parsedCommandLine.watchOptions); } + /*@internal*/ + ensureParsedConfigUptoDate(configFilename: NormalizedPath, canonicalConfigFilePath: NormalizedPath, configFileExistenceInfo: ConfigFileExistenceInfo, forProject: ConfiguredProject): ConfigFileExistenceInfo { + if (configFileExistenceInfo.config) { + if (!configFileExistenceInfo.config.reloadLevel) return configFileExistenceInfo; + if (configFileExistenceInfo.config.reloadLevel === ConfigFileProgramReloadLevel.Partial) { + this.reloadFileNamesOfParsedConfig(configFilename, configFileExistenceInfo.config); + return configFileExistenceInfo; + } + } + + // Parse the config file and ensure its cached + const cachedDirectoryStructureHost = configFileExistenceInfo.config?.cachedDirectoryStructureHost || + createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames)!; + + // Read updated contents from disk + const configFileContent = tryReadFile(configFilename, fileName => this.host.readFile(fileName)); + const configFile = parseJsonText(configFilename, isString(configFileContent) ? configFileContent : "") as TsConfigSourceFile; + const configFileErrors = configFile.parseDiagnostics as Diagnostic[]; + if (!isString(configFileContent)) configFileErrors.push(configFileContent); + const parsedCommandLine = parseJsonSourceFileConfigFileContent( + configFile, + cachedDirectoryStructureHost, + getDirectoryPath(configFilename), + /*existingOptions*/ {}, + configFilename, + /*resolutionStack*/[], + this.hostConfiguration.extraFileExtensions, + this.extendedConfigCache, + ); + + if (parsedCommandLine.errors.length) { + configFileErrors.push(...parsedCommandLine.errors); + } + + this.logger.info(`Config: ${configFilename} : ${JSON.stringify({ + rootNames: parsedCommandLine.fileNames, + options: parsedCommandLine.options, + watchOptions: parsedCommandLine.watchOptions, + projectReferences: parsedCommandLine.projectReferences + }, /*replacer*/ undefined, " ")}`); + + const oldCommandLine = configFileExistenceInfo.config?.parsedCommandLine; + if (!configFileExistenceInfo.config) { + configFileExistenceInfo.config = { parsedCommandLine, cachedDirectoryStructureHost, projects: new Map() }; + } + else { + configFileExistenceInfo.config.parsedCommandLine = parsedCommandLine; + configFileExistenceInfo.config.watchedDirectoriesStale = true; + configFileExistenceInfo.config.reloadLevel = undefined; + } + + // If watch options different than older options when setting for the first time, update the config file watcher + if (!oldCommandLine && !isJsonEqual( + // Old options + this.getWatchOptionsFromProjectWatchOptions(/*projectOptions*/ undefined), + // New options + this.getWatchOptionsFromProjectWatchOptions(parsedCommandLine.watchOptions) + )) { + // Reset the config file watcher + configFileExistenceInfo.watcher?.close(); + configFileExistenceInfo.watcher = undefined; + } + + // Ensure there is watcher for this config file + this.createConfigFileWatcherForParsedConfig(configFilename, canonicalConfigFilePath, forProject); + // Watch extended config files + updateSharedExtendedConfigFileWatcher( + canonicalConfigFilePath, + parsedCommandLine.options, + this.sharedExtendedConfigFileWatchers, + (extendedConfigFileName, extendedConfigFilePath) => this.watchFactory.watchFile( + extendedConfigFileName, + () => { + // Update extended config cache + cleanExtendedConfigCache(this.extendedConfigCache, extendedConfigFilePath, fileName => this.toPath(fileName)); + // Update projects + let ensureProjectsForOpenFiles = false; + this.sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)?.projects.forEach(canonicalPath => { + ensureProjectsForOpenFiles = this.delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalPath, `Change in extended config file ${extendedConfigFileName} detected`) || ensureProjectsForOpenFiles; + }); + if (ensureProjectsForOpenFiles) this.delayEnsureProjectForOpenFiles(); + }, + PollingInterval.High, + this.hostConfiguration.watchOptions, + WatchType.ExtendedConfigFile, + configFilename + ), + fileName => this.toPath(fileName), + ); + return configFileExistenceInfo; + } + + /*@internal*/ + watchWildcards(configFileName: NormalizedPath, { exists, config }: ConfigFileExistenceInfo, forProject: ConfiguredProject) { + config!.projects.set(forProject.canonicalConfigFilePath, true); + if (exists) { + if (config!.watchedDirectories && !config!.watchedDirectoriesStale) return; + config!.watchedDirectoriesStale = false; + updateWatchingWildcardDirectories( + config!.watchedDirectories ||= new Map(), + new Map(getEntries(config!.parsedCommandLine!.wildcardDirectories!)), + // Create new directory watcher + (directory, flags) => this.watchWildcardDirectory(directory as Path, flags, configFileName, config!), + ); + } + else { + config!.watchedDirectoriesStale = false; + if (!config!.watchedDirectories) return; + clearMap(config!.watchedDirectories, closeFileWatcherOf); + config!.watchedDirectories = undefined; + } + } + + /*@internal*/ + stopWatchingWildCards(canonicalConfigFilePath: NormalizedPath, forProject: ConfiguredProject) { + const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath)!; + if (!configFileExistenceInfo.config || + !configFileExistenceInfo.config.projects.get(forProject.canonicalConfigFilePath)) { + return; + } + + configFileExistenceInfo.config.projects.set(forProject.canonicalConfigFilePath, false); + // If any of the project is still watching wild cards dont close the watcher + if (forEachEntry(configFileExistenceInfo.config.projects, identity)) return; + + clearMap(configFileExistenceInfo.config.watchedDirectories!, closeFileWatcherOf); + configFileExistenceInfo.config.watchedDirectories = undefined; + configFileExistenceInfo.config.watchedDirectoriesStale = undefined; + } + private updateNonInferredProjectFiles(project: ExternalProject | ConfiguredProject | AutoImportProviderProject, files: T[], propertyReader: FilePropertyReader) { const projectRootFilesMap = project.getRootFilesMap(); const newRootScriptInfoMap = new Map(); @@ -2264,14 +2363,28 @@ namespace ts.server { */ /*@internal*/ reloadFileNamesOfConfiguredProject(project: ConfiguredProject) { - const configFileSpecs = project.getCompilerOptions().configFile!.configFileSpecs!; - const configFileName = project.getConfigFilePath(); - const fileNames = getFileNamesFromConfigSpecs(configFileSpecs, getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); + const fileNames = this.reloadFileNamesOfParsedConfig(project.getConfigFilePath(), this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath)!.config!); project.updateErrorOnNoInputFiles(fileNames); this.updateNonInferredProjectFiles(project, fileNames.concat(project.getExternalFiles()), fileNamePropertyReader); return project.updateGraph(); } + /*@internal*/ + private reloadFileNamesOfParsedConfig(configFileName: NormalizedPath, config: ParsedConfig) { + if (config.reloadLevel === undefined) return config.parsedCommandLine!.fileNames; + Debug.assert(config.reloadLevel === ConfigFileProgramReloadLevel.Partial); + const configFileSpecs = config.parsedCommandLine!.options.configFile!.configFileSpecs!; + const fileNames = getFileNamesFromConfigSpecs( + configFileSpecs, + getDirectoryPath(configFileName), + config.parsedCommandLine!.options, + config.cachedDirectoryStructureHost, + this.hostConfiguration.extraFileExtensions + ); + config.parsedCommandLine = { ...config.parsedCommandLine!, fileNames }; + return fileNames; + } + /*@internal*/ setFileNamesOfAutoImportProviderProject(project: AutoImportProviderProject, fileNames: string[]) { this.updateNonInferredProjectFiles(project, fileNames, fileNamePropertyReader); @@ -2707,7 +2820,7 @@ namespace ts.server { sourceMapFileInfo = mapInfo; const snap = mapInfo.getSnapshot(); if (mapInfo.documentPositionMapper !== undefined) return mapInfo.documentPositionMapper; - return snap.getText(0, snap.getLength()); + return getSnapshotText(snap); }; const projectName = project.projectName; const documentPositionMapper = getDocumentPositionMapper( @@ -2845,7 +2958,7 @@ namespace ts.server { }); } if (includePackageJsonAutoImports !== args.preferences.includePackageJsonAutoImports) { - this.invalidateProjectAutoImports(/*packageJsonPath*/ undefined); + this.invalidateProjectPackageJson(/*packageJsonPath*/ undefined); } } if (args.extraFileExtensions) { @@ -2865,7 +2978,11 @@ namespace ts.server { /*@internal*/ getWatchOptions(project: Project) { - const projectOptions = project.getWatchOptions(); + return this.getWatchOptionsFromProjectWatchOptions(project.getWatchOptions()); + } + + /*@internal*/ + private getWatchOptionsFromProjectWatchOptions(projectOptions: WatchOptions | undefined) { return projectOptions && this.hostConfiguration.watchOptions ? { ...this.hostConfiguration.watchOptions, ...projectOptions } : projectOptions || this.hostConfiguration.watchOptions; @@ -2901,6 +3018,11 @@ namespace ts.server { this.throttledOperations.cancel(ensureProjectForOpenFileSchedule); this.pendingEnsureProjectForOpenFiles = false; + // Ensure everything is reloaded for cached configs + this.configFileExistenceInfoCache.forEach(info => { + if (info.config) info.config.reloadLevel = ConfigFileProgramReloadLevel.Full; + }); + // Reload Projects this.reloadConfiguredProjectForFiles(this.openFiles as ESMap, /*clearSemanticCache*/ true, /*delayReload*/ false, returnTrue, "User requested reload projects"); this.externalProjects.forEach(project => { @@ -2911,28 +3033,14 @@ namespace ts.server { this.ensureProjectForOpenFiles(); } - private delayReloadConfiguredProjectForFiles(configFileExistenceInfo: ConfigFileExistenceInfo, ignoreIfNotRootOfInferredProject: boolean) { - // Get open files to reload projects for - this.reloadConfiguredProjectForFiles( - configFileExistenceInfo.openFilesImpactedByConfigFile, - /*clearSemanticCache*/ false, - /*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 - "Change in config file detected" - ); - this.delayEnsureProjectForOpenFiles(); - } - /** * This function goes through all the openFiles and tries to file the config file for them. * If the config file is found and it refers to existing project, it reloads it either immediately * or schedules it for reload depending on delayReload option - * If the there is no existing project it just opens the configured project for the config file + * If 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: ESMap, clearSemanticCache: boolean, delayReload: boolean, shouldReloadProjectFor: (openFileValue: T) => boolean, reason: string) { + private reloadConfiguredProjectForFiles(openFiles: ESMap | undefined, clearSemanticCache: boolean, delayReload: boolean, shouldReloadProjectFor: (openFileValue: T) => boolean, reason: string) { const updatedProjects = new Map(); const reloadChildProject = (child: ConfiguredProject) => { if (!updatedProjects.has(child.canonicalConfigFilePath)) { @@ -2941,7 +3049,7 @@ namespace ts.server { } }; // try to reload config file for all open files - openFiles.forEach((openFileValue, path) => { + openFiles?.forEach((openFileValue, path) => { // Invalidate default config file name for open file this.configFileForOpenFiles.delete(path); // Filter out the files that need to be ignored @@ -3933,7 +4041,7 @@ namespace ts.server { private watchPackageJsonFile(path: Path) { const watchers = this.packageJsonFilesMap || (this.packageJsonFilesMap = new Map()); if (!watchers.has(path)) { - this.invalidateProjectAutoImports(path); + this.invalidateProjectPackageJson(path); watchers.set(path, this.watchFactory.watchFile( path, (fileName, eventKind) => { @@ -3943,11 +4051,11 @@ namespace ts.server { return Debug.fail(); case FileWatcherEventKind.Changed: this.packageJsonCache.addOrUpdate(path); - this.invalidateProjectAutoImports(path); + this.invalidateProjectPackageJson(path); break; case FileWatcherEventKind.Deleted: this.packageJsonCache.delete(path); - this.invalidateProjectAutoImports(path); + this.invalidateProjectPackageJson(path); watchers.get(path)!.close(); watchers.delete(path); } @@ -3975,15 +4083,16 @@ namespace ts.server { } /*@internal*/ - private invalidateProjectAutoImports(packageJsonPath: Path | undefined) { - if (this.includePackageJsonAutoImports()) { - this.configuredProjects.forEach(invalidate); - this.inferredProjects.forEach(invalidate); - this.externalProjects.forEach(invalidate); - } + private invalidateProjectPackageJson(packageJsonPath: Path | undefined) { + this.configuredProjects.forEach(invalidate); + this.inferredProjects.forEach(invalidate); + this.externalProjects.forEach(invalidate); function invalidate(project: Project) { - if (!packageJsonPath || project.packageJsonsForAutoImport?.has(packageJsonPath)) { - project.markAutoImportProviderAsDirty(); + if (packageJsonPath) { + project.onPackageJsonChange(packageJsonPath); + } + else { + project.onAutoImportProviderSettingsChanged(); } } } diff --git a/src/server/project.ts b/src/server/project.ts index ef1a51198178f..60d045ea8ee0b 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -146,6 +146,8 @@ namespace ts.server { lastCachedUnresolvedImportsList: SortedReadonlyArray | undefined; /*@internal*/ private hasAddedorRemovedFiles = false; + /*@internal*/ + private hasAddedOrRemovedSymlinks = false; /*@internal*/ lastFileExceededProgramSize: string | undefined; @@ -204,13 +206,16 @@ namespace ts.server { originalConfiguredProjects: Set | undefined; /*@internal*/ - packageJsonsForAutoImport: Set | undefined; + private packageJsonsForAutoImport: Set | undefined; /*@internal*/ getResolvedProjectReferenceToRedirect(_fileName: string): ResolvedProjectReference | undefined { return undefined; } + /* @internal */ useSourceOfProjectReferenceRedirect?(): boolean; + /* @internal */ getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; + private readonly cancellationToken: ThrottledCancellationToken; public isNonTsProject() { @@ -245,9 +250,11 @@ namespace ts.server { public readonly getCanonicalFileName: GetCanonicalFileName; /*@internal*/ - private importSuggestionsCache = Completions.createImportSuggestionsForFileCache(); + private exportMapCache = createExportMapCache(); + /*@internal*/ + private changedFilesForExportMapCache: Set | undefined; /*@internal*/ - private dirtyFilesForSuggestions: Set | undefined; + private moduleSpecifierCache = createModuleSpecifierCache(); /*@internal*/ private symlinks: SymlinkCache | undefined; /*@internal*/ @@ -640,7 +647,7 @@ namespace ts.server { return []; } updateProjectIfDirty(this); - this.builderState = BuilderState.create(this.program!, this.projectService.toCanonicalFileName, this.builderState); + this.builderState = BuilderState.create(this.program!, this.projectService.toCanonicalFileName, this.builderState, /*disableUseFileVersionAsSignature*/ true); return mapDefined( BuilderState.getFilesAffectedBy( this.builderState, @@ -772,9 +779,9 @@ namespace ts.server { this.rootFiles = undefined!; this.rootFilesMap = undefined!; - this.externalFiles = undefined!; - this.program = undefined!; - this.builderState = undefined!; + this.externalFiles = undefined; + this.program = undefined; + this.builderState = undefined; this.resolutionCache.clear(); this.resolutionCache = undefined!; this.cachedUnresolvedImportsPerFile = undefined!; @@ -784,7 +791,7 @@ namespace ts.server { // Clean up file watchers waiting for missing files if (this.missingFilesMap) { clearMap(this.missingFilesMap, closeFileWatcher); - this.missingFilesMap = undefined!; + this.missingFilesMap = undefined; } this.clearGeneratedFileWatch(); this.clearInvalidateResolutionOfFailedLookupTimer(); @@ -976,8 +983,8 @@ namespace ts.server { /*@internal*/ markFileAsDirty(changedFile: Path) { this.markAsDirty(); - if (!this.importSuggestionsCache.isEmpty()) { - (this.dirtyFilesForSuggestions || (this.dirtyFilesForSuggestions = new Set())).add(changedFile); + if (!this.exportMapCache.isEmpty()) { + (this.changedFilesForExportMapCache ||= new Set()).add(changedFile); } } @@ -989,17 +996,31 @@ namespace ts.server { } /*@internal*/ - markAutoImportProviderAsDirty() { + onAutoImportProviderSettingsChanged() { if (this.autoImportProviderHost === false) { this.autoImportProviderHost = undefined; } - this.autoImportProviderHost?.markAsDirty(); - this.importSuggestionsCache.clear(); + else { + this.autoImportProviderHost?.markAsDirty(); + } + } + + /*@internal*/ + onPackageJsonChange(packageJsonPath: Path) { + if (this.packageJsonsForAutoImport?.has(packageJsonPath)) { + this.moduleSpecifierCache.clear(); + if (this.autoImportProviderHost) { + this.autoImportProviderHost.markAsDirty(); + } + } } /* @internal */ - onFileAddedOrRemoved() { + onFileAddedOrRemoved(isSymlink: boolean | undefined) { this.hasAddedorRemovedFiles = true; + if (isSymlink) { + this.hasAddedOrRemovedSymlinks = true; + } } /** @@ -1013,6 +1034,7 @@ namespace ts.server { const hasNewProgram = this.updateGraphWorker(); const hasAddedorRemovedFiles = this.hasAddedorRemovedFiles; this.hasAddedorRemovedFiles = false; + this.hasAddedOrRemovedSymlinks = false; const changedFiles: readonly Path[] = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || emptyArray; @@ -1087,7 +1109,7 @@ namespace ts.server { const start = timestamp(); this.hasInvalidatedResolution = this.resolutionCache.createHasInvalidatedResolution(); this.resolutionCache.startCachingPerDirectoryResolution(); - this.program = this.languageService.getProgram()!; // TODO: GH#18217 + this.program = this.languageService.getProgram(); // TODO: GH#18217 this.dirty = false; this.resolutionCache.finishCachingPerDirectoryResolution(); @@ -1096,8 +1118,9 @@ namespace ts.server { // bump up the version if // - oldProgram is not set - this is a first time updateGraph is called // - newProgram is different from the old program and structure of the old program was not reused. - const hasNewProgram = this.program && (!oldProgram || (this.program !== oldProgram && !(this.program.structureIsReused & StructureIsReused.Completely))); - if (hasNewProgram) { + let hasNewProgram = false; + if (this.program && (!oldProgram || (this.program !== oldProgram && this.program.structureIsReused !== StructureIsReused.Completely))) { + hasNewProgram = true; if (oldProgram) { for (const f of oldProgram.getSourceFiles()) { const newFile = this.program.getSourceFileByPath(f.resolvedPath); @@ -1162,27 +1185,30 @@ namespace ts.server { } } - if (!this.importSuggestionsCache.isEmpty()) { - if (this.hasAddedorRemovedFiles || oldProgram && !this.program.structureIsReused) { - this.importSuggestionsCache.clear(); + if (!this.exportMapCache.isEmpty()) { + if (this.hasAddedorRemovedFiles || oldProgram && !this.program!.structureIsReused) { + this.exportMapCache.clear(); } - else if (this.dirtyFilesForSuggestions && oldProgram && this.program) { - forEachKey(this.dirtyFilesForSuggestions, fileName => { - const oldSourceFile = oldProgram.getSourceFile(fileName); - const sourceFile = this.program!.getSourceFile(fileName); - if (this.sourceFileHasChangedOwnImportSuggestions(oldSourceFile, sourceFile)) { - this.importSuggestionsCache.clear(); + else if (this.changedFilesForExportMapCache && oldProgram && this.program) { + forEachKey(this.changedFilesForExportMapCache, fileName => { + const oldSourceFile = oldProgram.getSourceFileByPath(fileName); + const sourceFile = this.program!.getSourceFileByPath(fileName); + if (!oldSourceFile || !sourceFile) { + this.exportMapCache.clear(); return true; } + return this.exportMapCache.onFileChanged(oldSourceFile, sourceFile, !!this.getTypeAcquisition().enable); }); } } - if (this.dirtyFilesForSuggestions) { - this.dirtyFilesForSuggestions.clear(); + if (this.changedFilesForExportMapCache) { + this.changedFilesForExportMapCache.clear(); } - if (this.hasAddedorRemovedFiles) { + if (this.hasAddedOrRemovedSymlinks || this.program && !this.program.structureIsReused && this.getCompilerOptions().preserveSymlinks) { + // With --preserveSymlinks, we may not determine that a file is a symlink, so we never set `hasAddedOrRemovedSymlinks` this.symlinks = undefined; + this.moduleSpecifierCache.clear(); } const oldExternalFiles = this.externalFiles || emptyArray as SortedReadonlyArray; @@ -1204,7 +1230,7 @@ namespace ts.server { this.print(/*writeProjectFileNames*/ true); } else if (this.program !== oldProgram) { - this.writeLog(`Different program with same set of files:: structureIsReused:: ${this.program.structureIsReused}`); + this.writeLog(`Different program with same set of files:: structureIsReused:: ${this.program?.structureIsReused}`); } return hasNewProgram; } @@ -1214,54 +1240,6 @@ namespace ts.server { this.projectService.sendPerformanceEvent(kind, durationMs); } - /*@internal*/ - private sourceFileHasChangedOwnImportSuggestions(oldSourceFile: SourceFile | undefined, newSourceFile: SourceFile | undefined) { - if (!oldSourceFile && !newSourceFile) { - return false; - } - // Probably shouldn’t get this far, but on the off chance the file was added or removed, - // we can’t reliably tell anything about it. - if (!oldSourceFile || !newSourceFile) { - return true; - } - - Debug.assertEqual(oldSourceFile.fileName, newSourceFile.fileName); - // If ATA is enabled, auto-imports uses existing imports to guess whether you want auto-imports from node. - // Adding or removing imports from node could change the outcome of that guess, so could change the suggestions list. - if (this.getTypeAcquisition().enable && consumesNodeCoreModules(oldSourceFile) !== consumesNodeCoreModules(newSourceFile)) { - return true; - } - - // Module agumentation and ambient module changes can add or remove exports available to be auto-imported. - // Changes elsewhere in the file can change the *type* of an export in a module augmentation, - // but type info is gathered in getCompletionEntryDetails, which doesn’t use the cache. - if ( - !arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations) || - !this.ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile) - ) { - return true; - } - return false; - } - - /*@internal*/ - private ambientModuleDeclarationsAreEqual(oldSourceFile: SourceFile, newSourceFile: SourceFile) { - if (!arrayIsEqualTo(oldSourceFile.ambientModuleNames, newSourceFile.ambientModuleNames)) { - return false; - } - let oldFileStatementIndex = -1; - let newFileStatementIndex = -1; - for (const ambientModuleName of newSourceFile.ambientModuleNames) { - const isMatchingModuleDeclaration = (node: Statement) => isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName; - oldFileStatementIndex = findIndex(oldSourceFile.statements, isMatchingModuleDeclaration, oldFileStatementIndex + 1); - newFileStatementIndex = findIndex(newSourceFile.statements, isMatchingModuleDeclaration, newFileStatementIndex + 1); - if (oldSourceFile.statements[oldFileStatementIndex] !== newSourceFile.statements[newFileStatementIndex]) { - return false; - } - } - return true; - } - private detachScriptInfoFromProject(uncheckedFileName: string, noRemoveResolution?: boolean) { const scriptInfoToDetach = this.projectService.getScriptInfo(uncheckedFileName); if (scriptInfoToDetach) { @@ -1273,6 +1251,11 @@ namespace ts.server { } private addMissingFileWatcher(missingFilePath: Path) { + if (isConfiguredProject(this)) { + // If this file is referenced config file, we are already watching it, no need to watch again + const configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(missingFilePath as string as NormalizedPath); + if (configFileExistenceInfo?.config?.projects.has(this.canonicalConfigFilePath)) return noopFileWatcher; + } const fileWatcher = this.projectService.watchFactory.watchFile( missingFilePath, (fileName, eventKind) => { @@ -1632,7 +1615,7 @@ namespace ts.server { (newLS as any)[k] = (this.languageService as any)[k]; } } - this.projectService.logger.info(`Plugin validation succeded`); + this.projectService.logger.info(`Plugin validation succeeded`); this.languageService = newLS; this.plugins.push({ name: configEntry.name, module: pluginModule }); } @@ -1674,8 +1657,13 @@ namespace ts.server { } /*@internal*/ - getImportSuggestionsCache() { - return this.importSuggestionsCache; + getExportMapCache() { + return this.exportMapCache; + } + + /*@internal*/ + getModuleSpecifierCache() { + return this.moduleSpecifierCache; } /*@internal*/ @@ -1913,16 +1901,20 @@ namespace ts.server { compilerOptions, moduleResolutionHost)); + const program = hostProject.getCurrentProgram()!; + const symlinkCache = hostProject.getSymlinkCache(); for (const resolution of resolutions) { if (!resolution.resolvedTypeReferenceDirective?.resolvedFileName) continue; - const { resolvedFileName } = resolution.resolvedTypeReferenceDirective; - const fileName = moduleResolutionHost.realpath?.(resolvedFileName) || resolvedFileName; - if (!hostProject.getCurrentProgram()!.getSourceFile(fileName) && !hostProject.getCurrentProgram()!.getSourceFile(resolvedFileName)) { - rootNames = append(rootNames, fileName); + const { resolvedFileName, originalPath } = resolution.resolvedTypeReferenceDirective; + if (!program.getSourceFile(resolvedFileName) && (!originalPath || !program.getSourceFile(originalPath))) { + rootNames = append(rootNames, resolvedFileName); // Avoid creating a large project that would significantly slow down time to editor interactivity if (dependencySelection === PackageJsonAutoImportPreference.Auto && rootNames.length > this.maxDependencies) { return ts.emptyArray; } + if (originalPath) { + symlinkCache.setSymlinkedDirectoryFromSymlinkedFile(originalPath, resolvedFileName); + } } } } @@ -1982,6 +1974,8 @@ namespace ts.server { hostProject.currentDirectory); this.rootFileNames = initialRootNames; + this.useSourceOfProjectReferenceRedirect = maybeBind(this.hostProject, this.hostProject.useSourceOfProjectReferenceRedirect); + this.getParsedCommandLine = maybeBind(this.hostProject, this.hostProject.getParsedCommandLine); } /*@internal*/ @@ -2005,8 +1999,12 @@ namespace ts.server { this.projectService.setFileNamesOfAutoImportProviderProject(this, rootFileNames); this.rootFileNames = rootFileNames; - this.hostProject.getImportSuggestionsCache().clear(); - return super.updateGraph(); + const oldProgram = this.getCurrentProgram(); + const hasSameSetOfFiles = super.updateGraph(); + if (oldProgram && oldProgram !== this.getCurrentProgram()) { + this.hostProject.getExportMapCache().clear(); + } + return hasSameSetOfFiles; } hasRoots() { @@ -2026,10 +2024,16 @@ namespace ts.server { throw new Error("AutoImportProviderProject language service should never be used. To get the program, use `project.getCurrentProgram()`."); } - markAutoImportProviderAsDirty(): never { + /*@internal*/ + onAutoImportProviderSettingsChanged(): never { throw new Error("AutoImportProviderProject is an auto import provider; use `markAsDirty()` instead."); } + /*@internal*/ + onPackageJsonChange(): never { + throw new Error("package.json changes should be notified on an AutoImportProvider's host project"); + } + getModuleResolutionHostForAutoImportProvider(): never { throw new Error("AutoImportProviderProject cannot provide its own host; use `hostProject.getModuleResolutionHostForAutomImportProvider()` instead."); } @@ -2038,10 +2042,6 @@ namespace ts.server { return this.hostProject.getProjectReferences(); } - useSourceOfProjectReferenceRedirect() { - return true; - } - /*@internal*/ includePackageJsonAutoImports() { return PackageJsonAutoImportPreference.Off; @@ -2063,18 +2063,13 @@ namespace ts.server { * Otherwise it will create an InferredProject. */ export class ConfiguredProject extends Project { - /* @internal */ - configFileWatcher: FileWatcher | undefined; - private directoriesWatchedForWildcards: ESMap | undefined; - readonly canonicalConfigFilePath: NormalizedPath; - /* @internal */ pendingReload: ConfigFileProgramReloadLevel | undefined; /* @internal */ pendingReloadReason: string | undefined; /* @internal */ - openFileWatchTriggered = new Map(); + openFileWatchTriggered = new Map(); /*@internal*/ canConfigFileJsonReportNoInputFiles = false; @@ -2102,6 +2097,7 @@ namespace ts.server { /*@internal*/ constructor(configFileName: NormalizedPath, + readonly canonicalConfigFilePath: NormalizedPath, projectService: ProjectService, documentRegistry: DocumentRegistry, cachedDirectoryStructureHost: CachedDirectoryStructureHost) { @@ -2117,7 +2113,6 @@ namespace ts.server { cachedDirectoryStructureHost, getDirectoryPath(configFileName), ); - this.canonicalConfigFilePath = asNormalizedPath(projectService.toCanonicalFileName(configFileName)); } /* @internal */ @@ -2136,28 +2131,32 @@ namespace ts.server { } /* @internal */ - setWatchOptions(watchOptions: WatchOptions | undefined) { - const oldOptions = this.getWatchOptions(); - super.setWatchOptions(watchOptions); - // If watch options different than older options - if (this.isInitialLoadPending() && - !isJsonEqual(oldOptions, this.getWatchOptions())) { - const oldWatcher = this.configFileWatcher; - this.createConfigFileWatcher(); - if (oldWatcher) oldWatcher.close(); + getParsedCommandLine(fileName: string) { + const configFileName = asNormalizedPath(normalizePath(fileName)); + const canonicalConfigFilePath = asNormalizedPath(this.projectService.toCanonicalFileName(configFileName)); + // Ensure the config file existience info is cached + let configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(canonicalConfigFilePath); + if (!configFileExistenceInfo) { + this.projectService.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo = { exists: this.projectService.host.fileExists(configFileName) }); + } + // Ensure we have upto date parsed command line + this.projectService.ensureParsedConfigUptoDate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, this); + // Watch wild cards if LS is enabled + if (this.languageServiceEnabled && this.projectService.serverMode === LanguageServiceMode.Semantic) { + this.projectService.watchWildcards(configFileName, configFileExistenceInfo, this); } + return configFileExistenceInfo.exists ? configFileExistenceInfo.config!.parsedCommandLine : undefined; } /* @internal */ - createConfigFileWatcher() { - this.configFileWatcher = this.projectService.watchFactory.watchFile( - this.getConfigFilePath(), - (_fileName, eventKind) => this.projectService.onConfigChangedForConfiguredProject(this, eventKind), - PollingInterval.High, - this.projectService.getWatchOptions(this), - WatchType.ConfigFile, - this - ); + onReleaseParsedCommandLine(fileName: string) { + this.releaseParsedConfig(asNormalizedPath(this.projectService.toCanonicalFileName(asNormalizedPath(normalizePath(fileName))))); + } + + /* @internal */ + private releaseParsedConfig(canonicalConfigFilePath: NormalizedPath) { + this.projectService.stopWatchingWildCards(canonicalConfigFilePath, this); + this.projectService.releaseParsedConfig(canonicalConfigFilePath, this); } /** @@ -2275,32 +2274,9 @@ namespace ts.server { this.projectErrors = projectErrors; } - /*@internal*/ - watchWildcards(wildcardDirectories: ESMap) { - updateWatchingWildcardDirectories( - this.directoriesWatchedForWildcards || (this.directoriesWatchedForWildcards = new Map()), - wildcardDirectories, - // Create new directory watcher - (directory, flags) => this.projectService.watchWildcardDirectory(directory as Path, flags, this), - ); - } - - /*@internal*/ - stopWatchingWildCards() { - if (this.directoriesWatchedForWildcards) { - clearMap(this.directoriesWatchedForWildcards, closeFileWatcherOf); - this.directoriesWatchedForWildcards = undefined; - } - } - close() { - if (this.configFileWatcher) { - this.configFileWatcher.close(); - this.configFileWatcher = undefined; - } - - this.stopWatchingWildCards(); - this.projectService.removeProjectFromSharedExtendedConfigFileMap(this); + this.projectService.configFileExistenceInfoCache.forEach((_configFileExistenceInfo, canonicalConfigFilePath) => + this.releaseParsedConfig(canonicalConfigFilePath)); this.projectErrors = undefined; this.openFileWatchTriggered.clear(); this.compilerHost = undefined; @@ -2348,18 +2324,18 @@ namespace ts.server { return false; } - const configFileExistenceInfo = this.projectService.getConfigFileExistenceInfo(this); + const configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(this.canonicalConfigFilePath)!; if (this.projectService.hasPendingProjectUpdate(this)) { // If there is pending update for this project, // we dont know if this project would be needed by any of the open files impacted by this config file // In that case keep the project alive if there are open files impacted by this project - return !!configFileExistenceInfo.openFilesImpactedByConfigFile.size; + return !!configFileExistenceInfo.openFilesImpactedByConfigFile?.size; } // If there is no pending update for this project, // We know exact set of open files that get impacted by this configured project as the files in the project // The project is referenced only if open files impacted by this project are present in this project - return forEachEntry( + return !!configFileExistenceInfo.openFilesImpactedByConfigFile && forEachEntry( configFileExistenceInfo.openFilesImpactedByConfigFile, (_value, infoPath) => { const info = this.projectService.getScriptInfoForPath(infoPath)!; diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 1ce0c66019f6d..6f92ebfe7573e 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -681,6 +681,7 @@ namespace ts.server.protocol { export interface OrganizeImportsRequestArgs { scope: OrganizeImportsScope; + skipDestructiveCodeActions?: boolean; } export interface OrganizeImportsResponse extends Response { @@ -843,7 +844,6 @@ namespace ts.server.protocol { /** * A request to get encoded semantic classifications for a span in the file */ - /** @internal */ export interface EncodedSemanticClassificationsRequest extends FileRequest { arguments: EncodedSemanticClassificationsRequestArgs; } @@ -851,7 +851,6 @@ namespace ts.server.protocol { /** * Arguments for EncodedSemanticClassificationsRequest request. */ - /** @internal */ export interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { /** * Start position of the span. @@ -868,6 +867,18 @@ namespace ts.server.protocol { format?: "original" | "2020" } + /** The response for a EncodedSemanticClassificationsRequest */ + export interface EncodedSemanticClassificationsResponse extends Response { + body?: EncodedSemanticClassificationsResponseBody + } + + /** + * Implementation response message. Gives series of text spans depending on the format ar. + */ + export interface EncodedSemanticClassificationsResponseBody { + endOfLineState: EndOfLineState; + spans: number[]; + } /** * Arguments in document highlight request; include: filesToSearch, file, * line, offset. @@ -969,6 +980,16 @@ namespace ts.server.protocol { file: string; } + export interface JSDocTagInfo { + /** Name of the JSDoc tag */ + name: string; + /** + * Comment text after the JSDoc tag -- the text after the tag name until the next tag or end of comment + * Display parts when UserPreferences.displayPartsForJSDoc is true, flattened to string otherwise. + */ + text?: string | SymbolDisplayPart[]; + } + export interface TextSpanWithContext extends TextSpan { contextStart?: Location; contextEnd?: Location; @@ -977,8 +998,15 @@ namespace ts.server.protocol { export interface FileSpanWithContext extends FileSpan, TextSpanWithContext { } + export interface DefinitionInfo extends FileSpanWithContext { + /** + * When true, the file may or may not exist. + */ + unverified?: boolean; + } + export interface DefinitionInfoAndBoundSpan { - definitions: readonly FileSpanWithContext[]; + definitions: readonly DefinitionInfo[]; textSpan: TextSpan; } @@ -986,7 +1014,7 @@ namespace ts.server.protocol { * Definition response message. Gives text range for definition. */ export interface DefinitionResponse extends Response { - body?: FileSpanWithContext[]; + body?: DefinitionInfo[]; } export interface DefinitionInfoAndBoundSpanResponse extends Response { @@ -1521,6 +1549,7 @@ namespace ts.server.protocol { FixedPollingInterval = "FixedPollingInterval", PriorityPollingInterval = "PriorityPollingInterval", DynamicPriorityPolling = "DynamicPriorityPolling", + FixedChunkSizePolling = "FixedChunkSizePolling", UseFsEvents = "UseFsEvents", UseFsEventsOnParentDirectory = "UseFsEventsOnParentDirectory", } @@ -1529,12 +1558,14 @@ namespace ts.server.protocol { UseFsEvents = "UseFsEvents", FixedPollingInterval = "FixedPollingInterval", DynamicPriorityPolling = "DynamicPriorityPolling", + FixedChunkSizePolling = "FixedChunkSizePolling", } export const enum PollingWatchKind { FixedInterval = "FixedInterval", PriorityInterval = "PriorityInterval", DynamicPriority = "DynamicPriority", + FixedChunkSize = "FixedChunkSize", } export interface WatchOptions { @@ -1931,6 +1962,7 @@ namespace ts.server.protocol { */ export interface QuickInfoRequest extends FileLocationRequest { command: CommandTypes.Quickinfo; + arguments: FileLocationRequestArgs; } /** @@ -1964,8 +1996,9 @@ namespace ts.server.protocol { /** * Documentation associated with symbol. + * Display parts when UserPreferences.displayPartsForJSDoc is true, flattened to string otherwise. */ - documentation: string; + documentation: string | SymbolDisplayPart[]; /** * JSDoc tags associated with symbol. @@ -2110,7 +2143,7 @@ namespace ts.server.protocol { arguments: FormatOnKeyRequestArgs; } - export type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#"; + export type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; /** * Arguments for completions messages. @@ -2159,6 +2192,7 @@ namespace ts.server.protocol { export interface CompletionEntryIdentifier { name: string; source?: string; + data?: unknown; } /** @@ -2187,6 +2221,12 @@ namespace ts.server.protocol { kind: string; } + /** A part of a symbol description that links from a jsdoc @link tag to a declaration */ + export interface JSDocLinkDisplayPart extends SymbolDisplayPart { + /** The location of the declaration that the @link tag links to. */ + target: FileSpan; + } + /** * An item found in a completion response. */ @@ -2214,6 +2254,10 @@ namespace ts.server.protocol { * coupled with `replacementSpan` to replace a dotted access with a bracket access. */ insertText?: string; + /** + * `insertText` should be interpreted as a snippet if true. + */ + isSnippet?: true; /** * An optional span that indicates the text to be replaced by this completion item. * If present, this span should be used instead of the default one. @@ -2229,6 +2273,10 @@ namespace ts.server.protocol { * Identifier (not necessarily human-readable) identifying where this completion came from. */ source?: string; + /** + * Human-readable description of the `source`. + */ + sourceDisplay?: SymbolDisplayPart[]; /** * If true, this completion should be highlighted as recommended. There will only be one of these. * This will be set when we know the user should write an expression with a certain type and that type is an enum or constructable class. @@ -2242,9 +2290,20 @@ namespace ts.server.protocol { isFromUncheckedFile?: true; /** * If true, this completion was for an auto-import of a module not yet in the program, but listed - * in the project package.json. + * in the project package.json. Used for telemetry reporting. */ isPackageJsonImport?: true; + /** + * If true, this completion was an auto-import-style completion of an import statement (i.e., the + * module specifier was inserted along with the imported identifier). Used for telemetry reporting. + */ + isImportStatementCompletion?: true; + /** + * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, + * that allows TS Server to look up the symbol represented by the completion item, disambiguating + * items with the same name. + */ + data?: unknown; } /** @@ -2284,9 +2343,14 @@ namespace ts.server.protocol { codeActions?: CodeAction[]; /** - * Human-readable description of the `source` from the CompletionEntry. + * @deprecated Use `sourceDisplay` instead. */ source?: SymbolDisplayPart[]; + + /** + * Human-readable description of the `source` from the CompletionEntry. + */ + sourceDisplay?: SymbolDisplayPart[]; } /** @deprecated Prefer CompletionInfoResponse, which supports several top-level fields in addition to the array of entries. */ @@ -2308,6 +2372,7 @@ namespace ts.server.protocol { * must be used to commit that completion entry. */ readonly optionalReplacementSpan?: TextSpan; + readonly isIncomplete?: boolean; readonly entries: readonly CompletionEntry[]; } @@ -3253,6 +3318,15 @@ namespace ts.server.protocol { * This affects lone identifier completions but not completions on the right hand side of `obj.`. */ readonly includeCompletionsForModuleExports?: boolean; + /** + * Enables auto-import-style completions on partially-typed import statements. E.g., allows + * `import write|` to be completed to `import { writeFile } from "fs"`. + */ + readonly includeCompletionsForImportStatements?: boolean; + /** + * Allows completions to be formatted with snippet text, indicated by `CompletionItem["isSnippet"]`. + */ + readonly includeCompletionsWithSnippetText?: boolean; /** * If enabled, the completion list will include completions with invalid identifier names. * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. @@ -3274,6 +3348,7 @@ namespace ts.server.protocol { readonly allowRenameOfImportPath?: boolean; readonly includePackageJsonAutoImports?: "auto" | "on" | "off"; + readonly displayPartsForJSDoc?: boolean; readonly generateReturnInDocTemplate?: boolean; } @@ -3388,6 +3463,35 @@ namespace ts.server.protocol { ES2018 = "ES2018", ES2019 = "ES2019", ES2020 = "ES2020", + ES2021 = "ES2021", ESNext = "ESNext" } + + export const enum ClassificationType { + comment = 1, + identifier = 2, + keyword = 3, + numericLiteral = 4, + operator = 5, + stringLiteral = 6, + regularExpressionLiteral = 7, + whiteSpace = 8, + text = 9, + punctuation = 10, + className = 11, + enumName = 12, + interfaceName = 13, + moduleName = 14, + typeParameterName = 15, + typeAliasName = 16, + parameterName = 17, + docCommentTagName = 18, + jsxOpenTagName = 19, + jsxCloseTagName = 20, + jsxSelfClosingTagName = 21, + jsxAttribute = 22, + jsxText = 23, + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25, + } } diff --git a/src/server/scriptInfo.ts b/src/server/scriptInfo.ts index 0af6808d892f2..a26fcc6748932 100644 --- a/src/server/scriptInfo.ts +++ b/src/server/scriptInfo.ts @@ -241,7 +241,7 @@ namespace ts.server { this.reloadWithFileText(); } - // At this point if svc is present its valid + // At this point if svc is present it's valid return this.svc; } @@ -415,6 +415,15 @@ namespace ts.server { return this.realpath && this.realpath !== this.path ? this.realpath : undefined; } + /** + * @internal + * Does not compute realpath; uses precomputed result. Use `ensureRealPath` + * first if a definite result is needed. + */ + isSymlink(): boolean | undefined { + return this.realpath && this.realpath !== this.path; + } + getFormatCodeSettings(): FormatCodeSettings | undefined { return this.formatSettings; } getPreferences(): protocol.UserPreferences | undefined { return this.preferences; } @@ -422,10 +431,10 @@ namespace ts.server { const isNew = !this.isAttached(project); if (isNew) { this.containingProjects.push(project); - project.onFileAddedOrRemoved(); if (!project.getCompilerOptions().preserveSymlinks) { this.ensureRealPath(); } + project.onFileAddedOrRemoved(this.isSymlink()); } return isNew; } @@ -447,23 +456,23 @@ namespace ts.server { return; case 1: if (this.containingProjects[0] === project) { - project.onFileAddedOrRemoved(); + project.onFileAddedOrRemoved(this.isSymlink()); this.containingProjects.pop(); } break; case 2: if (this.containingProjects[0] === project) { - project.onFileAddedOrRemoved(); + project.onFileAddedOrRemoved(this.isSymlink()); this.containingProjects[0] = this.containingProjects.pop()!; } else if (this.containingProjects[1] === project) { - project.onFileAddedOrRemoved(); + project.onFileAddedOrRemoved(this.isSymlink()); this.containingProjects.pop(); } break; default: if (unorderedRemoveItem(this.containingProjects, project)) { - project.onFileAddedOrRemoved(); + project.onFileAddedOrRemoved(this.isSymlink()); } break; } @@ -477,6 +486,7 @@ namespace ts.server { const existingRoot = p.getRootFilesMap().get(this.path); // detach is unnecessary since we'll clean the list of containing projects anyways p.removeFile(this, /*fileExists*/ false, /*detachFromProjects*/ false); + p.onFileAddedOrRemoved(this.isSymlink()); // If the info was for the external or configured project's root, // add missing file as the root if (existingRoot && !isInferredProject(p)) { diff --git a/src/server/session.ts b/src/server/session.ts index dc0d4f42f5c79..93013251e1ef4 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -1224,6 +1224,7 @@ namespace ts.server { containerName: info.containerName, kind: info.kind, name: info.name, + ...info.unverified && { unverified: info.unverified }, }; }); } @@ -1274,8 +1275,34 @@ namespace ts.server { result; } - private mapDefinitionInfo(definitions: readonly DefinitionInfo[], project: Project): readonly protocol.FileSpanWithContext[] { - return definitions.map(def => this.toFileSpanWithContext(def.fileName, def.textSpan, def.contextSpan, project)); + private mapJSDocTagInfo(tags: JSDocTagInfo[] | undefined, project: Project, richResponse: boolean): protocol.JSDocTagInfo[] { + return tags ? tags.map(tag => ({ + ...tag, + text: richResponse ? this.mapDisplayParts(tag.text, project) : tag.text?.map(part => part.text).join("") + })) : []; + } + + private mapDisplayParts(parts: SymbolDisplayPart[] | undefined, project: Project): protocol.SymbolDisplayPart[] { + if (!parts) { + return []; + } + return parts.map(part => part.kind !== "linkName" ? part : { + ...part, + target: this.toFileSpan((part as JSDocLinkDisplayPart).target.fileName, (part as JSDocLinkDisplayPart).target.textSpan, project), + }); + } + + private mapSignatureHelpItems(items: SignatureHelpItem[], project: Project, richResponse: boolean): protocol.SignatureHelpItem[] { + return items.map(item => ({ + ...item, + documentation: this.mapDisplayParts(item.documentation, project), + parameters: item.parameters.map(p => ({ ...p, documentation: this.mapDisplayParts(p.documentation, project) })), + tags: this.mapJSDocTagInfo(item.tags, project, richResponse), + })); + } + + private mapDefinitionInfo(definitions: readonly DefinitionInfo[], project: Project): readonly protocol.DefinitionInfo[] { + return definitions.map(def => ({ ...this.toFileSpanWithContext(def.fileName, def.textSpan, def.contextSpan, project), ...def.unverified && { unverified: def.unverified } })); } /* @@ -1367,7 +1394,7 @@ namespace ts.server { emptyArray; } - private getSyntacticDiagnosticsSync(args: protocol.SyntacticDiagnosticsSyncRequestArgs): readonly protocol.Diagnostic[] | readonly protocol.DiagnosticWithLinePosition[] { + private getSyntacticDiagnosticsSync(args: protocol.SyntacticDiagnosticsSyncRequestArgs) { const { configFile } = this.getConfigFileAndProject(args); if (configFile) { // all the config file errors are reported as part of semantic check so nothing to report here @@ -1377,7 +1404,7 @@ namespace ts.server { return this.getDiagnosticsWorker(args, /*isSemantic*/ false, (project, file) => project.getLanguageService().getSyntacticDiagnostics(file), !!args.includeLinePosition); } - private getSemanticDiagnosticsSync(args: protocol.SemanticDiagnosticsSyncRequestArgs): readonly protocol.Diagnostic[] | readonly protocol.DiagnosticWithLinePosition[] { + private getSemanticDiagnosticsSync(args: protocol.SemanticDiagnosticsSyncRequestArgs) { const { configFile, project } = this.getConfigFileAndProject(args); if (configFile) { return this.getConfigFileDiagnostics(configFile, project!, !!args.includeLinePosition); // TODO: GH#18217 @@ -1385,7 +1412,7 @@ namespace ts.server { return this.getDiagnosticsWorker(args, /*isSemantic*/ true, (project, file) => project.getLanguageService().getSemanticDiagnostics(file).filter(d => !!d.file), !!args.includeLinePosition); } - private getSuggestionDiagnosticsSync(args: protocol.SuggestionDiagnosticsSyncRequestArgs): readonly protocol.Diagnostic[] | readonly protocol.DiagnosticWithLinePosition[] { + private getSuggestionDiagnosticsSync(args: protocol.SuggestionDiagnosticsSyncRequestArgs) { const { configFile } = this.getConfigFileAndProject(args); if (configFile) { // Currently there are no info diagnostics for config files. @@ -1685,22 +1712,24 @@ namespace ts.server { return undefined; } + const useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc; if (simplifiedResult) { const displayString = displayPartsToString(quickInfo.displayParts); - const docString = displayPartsToString(quickInfo.documentation); - return { kind: quickInfo.kind, kindModifiers: quickInfo.kindModifiers, start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start), end: scriptInfo.positionToLineOffset(textSpanEnd(quickInfo.textSpan)), displayString, - documentation: docString, - tags: quickInfo.tags || [] + documentation: useDisplayParts ? this.mapDisplayParts(quickInfo.documentation, project) : displayPartsToString(quickInfo.documentation), + tags: this.mapJSDocTagInfo(quickInfo.tags, project, useDisplayParts), }; } else { - return quickInfo; + return useDisplayParts ? quickInfo : { + ...quickInfo, + tags: this.mapJSDocTagInfo(quickInfo.tags, project, /*useDisplayParts*/ false) as JSDocTagInfo[] + }; } } @@ -1808,14 +1837,14 @@ namespace ts.server { if (kind === protocol.CommandTypes.CompletionsFull) return completions; const prefix = args.prefix || ""; - const entries = mapDefined(completions.entries, entry => { + const entries = stableSort(mapDefined(completions.entries, entry => { if (completions.isMemberCompletion || startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { - const { name, kind, kindModifiers, sortText, insertText, replacementSpan, hasAction, source, isRecommended, isPackageJsonImport } = entry; + const { name, kind, kindModifiers, sortText, insertText, replacementSpan, hasAction, source, sourceDisplay, isSnippet, isRecommended, isPackageJsonImport, isImportStatementCompletion, data } = entry; const convertedSpan = replacementSpan ? toProtocolTextSpan(replacementSpan, scriptInfo) : undefined; // Use `hasAction || undefined` to avoid serializing `false`. - return { name, kind, kindModifiers, sortText, insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source, isRecommended, isPackageJsonImport }; + return { name, kind, kindModifiers, sortText, insertText, replacementSpan: convertedSpan, isSnippet, hasAction: hasAction || undefined, source, sourceDisplay, isRecommended, isPackageJsonImport, isImportStatementCompletion, data }; } - }).sort((a, b) => compareStringsCaseSensitiveUI(a.name, b.name)); + }), (a, b) => compareStringsCaseSensitiveUI(a.name, b.name)); if (kind === protocol.CommandTypes.Completions) { if (completions.metadata) (entries as WithMetadata).metadata = completions.metadata; @@ -1830,19 +1859,25 @@ namespace ts.server { return res; } - private getCompletionEntryDetails(args: protocol.CompletionDetailsRequestArgs, simplifiedResult: boolean): readonly protocol.CompletionEntryDetails[] | readonly CompletionEntryDetails[] { + private getCompletionEntryDetails(args: protocol.CompletionDetailsRequestArgs, fullResult: boolean): readonly protocol.CompletionEntryDetails[] | readonly CompletionEntryDetails[] { const { file, project } = this.getFileAndProject(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file)!; const position = this.getPosition(args, scriptInfo); const formattingOptions = project.projectService.getFormatCodeOptions(file); + const useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc; const result = mapDefined(args.entryNames, entryName => { - const { name, source } = typeof entryName === "string" ? { name: entryName, source: undefined } : entryName; - return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source, this.getPreferences(file)); + const { name, source, data } = typeof entryName === "string" ? { name: entryName, source: undefined, data: undefined } : entryName; + return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source, this.getPreferences(file), data ? cast(data, isCompletionEntryData) : undefined); }); - return simplifiedResult - ? result.map(details => ({ ...details, codeActions: map(details.codeActions, action => this.mapCodeAction(action)) })) - : result; + return fullResult + ? (useDisplayParts ? result : result.map(details => ({ ...details, tags: this.mapJSDocTagInfo(details.tags, project, /*richResponse*/ false) as JSDocTagInfo[] }))) + : result.map(details => ({ + ...details, + codeActions: map(details.codeActions, action => this.mapCodeAction(action)), + documentation: this.mapDisplayParts(details.documentation, project), + tags: this.mapJSDocTagInfo(details.tags, project, useDisplayParts), + })); } private getCompileOnSaveAffectedFileList(args: protocol.FileRequestArgs): readonly protocol.CompileOnSaveAffectedFileListSingleProject[] { @@ -1902,26 +1937,27 @@ namespace ts.server { const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file)!; const position = this.getPosition(args, scriptInfo); const helpItems = project.getLanguageService().getSignatureHelpItems(file, position, args); - if (!helpItems) { - return undefined; - } - - if (simplifiedResult) { + const useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc; + if (helpItems && simplifiedResult) { const span = helpItems.applicableSpan; return { - items: helpItems.items, + ...helpItems, applicableSpan: { start: scriptInfo.positionToLineOffset(span.start), end: scriptInfo.positionToLineOffset(span.start + span.length) }, - selectedItemIndex: helpItems.selectedItemIndex, - argumentIndex: helpItems.argumentIndex, - argumentCount: helpItems.argumentCount, + items: this.mapSignatureHelpItems(helpItems.items, project, useDisplayParts), }; } - else { + else if (useDisplayParts || !helpItems) { return helpItems; } + else { + return { + ...helpItems, + items: helpItems.items.map(item => ({ ...item, tags: this.mapJSDocTagInfo(item.tags, project, /*richResponse*/ false) as JSDocTagInfo[] })) + }; + } } private toPendingErrorCheck(uncheckedFileName: string): PendingErrorCheck | undefined { @@ -2165,10 +2201,18 @@ namespace ts.server { } } - private organizeImports({ scope }: protocol.OrganizeImportsRequestArgs, simplifiedResult: boolean): readonly protocol.FileCodeEdits[] | readonly FileTextChanges[] { - Debug.assert(scope.type === "file"); - const { file, project } = this.getFileAndProject(scope.args); - const changes = project.getLanguageService().organizeImports({ type: "file", fileName: file }, this.getFormatOptions(file), this.getPreferences(file)); + private organizeImports(args: protocol.OrganizeImportsRequestArgs, simplifiedResult: boolean): readonly protocol.FileCodeEdits[] | readonly FileTextChanges[] { + Debug.assert(args.scope.type === "file"); + const { file, project } = this.getFileAndProject(args.scope.args); + const changes = project.getLanguageService().organizeImports( + { + fileName: file, + skipDestructiveCodeActions: args.skipDestructiveCodeActions, + type: "file", + }, + this.getFormatOptions(file), + this.getPreferences(file) + ); if (simplifiedResult) { return this.mapTextChangesToCodeEdits(changes); } @@ -2198,7 +2242,25 @@ namespace ts.server { const scriptInfo = project.getScriptInfoForNormalizedPath(file)!; const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo); - const codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file)); + let codeActions: readonly CodeFixAction[]; + try { + codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file)); + } + catch(e) { + const ls = project.getLanguageService(); + const existingDiagCodes = [ + ...ls.getSyntacticDiagnostics(file), + ...ls.getSemanticDiagnostics(file), + ...ls.getSuggestionDiagnostics(file) + ].map(d => + decodedTextSpanIntersectsWith(startPosition, endPosition - startPosition, d.start!, d.length!) + && d.code); + const badCode = args.errorCodes.find(c => !existingDiagCodes.includes(c)); + if (badCode !== undefined) { + e.message = `BADCLIENT: Bad error code, ${badCode} not found in range ${startPosition}..${endPosition} (found: ${existingDiagCodes.join(", ")}); could have caused this error:\n${e.message}`; + } + throw e; + } return simplifiedResult ? codeActions.map(codeAction => this.mapCodeFixAction(codeAction)) : codeActions; } @@ -2700,10 +2762,10 @@ namespace ts.server { return this.requiredResponse(this.getCompletions(request.arguments, CommandNames.CompletionsFull)); }, [CommandNames.CompletionDetails]: (request: protocol.CompletionDetailsRequest) => { - return this.requiredResponse(this.getCompletionEntryDetails(request.arguments, /*simplifiedResult*/ true)); + return this.requiredResponse(this.getCompletionEntryDetails(request.arguments, /*fullResult*/ false)); }, [CommandNames.CompletionDetailsFull]: (request: protocol.CompletionDetailsRequest) => { - return this.requiredResponse(this.getCompletionEntryDetails(request.arguments, /*simplifiedResult*/ false)); + return this.requiredResponse(this.getCompletionEntryDetails(request.arguments, /*fullResult*/ true)); }, [CommandNames.CompileOnSaveAffectedFileList]: (request: protocol.CompileOnSaveAffectedFileListRequest) => { return this.requiredResponse(this.getCompileOnSaveAffectedFileList(request.arguments)); @@ -3118,4 +3180,12 @@ namespace ts.server { isDefinition }; } + + function isCompletionEntryData(data: any): data is CompletionEntryData { + return data === undefined || data && typeof data === "object" + && typeof data.exportName === "string" + && (data.fileName === undefined || typeof data.fileName === "string") + && (data.ambientModuleName === undefined || typeof data.ambientModuleName === "string" + && (data.isPackageJsonImport === undefined || typeof data.isPackageJsonImport === "boolean")); + } } diff --git a/src/services/callHierarchy.ts b/src/services/callHierarchy.ts index ca5a193e78f9c..2c2a83a22cba2 100644 --- a/src/services/callHierarchy.ts +++ b/src/services/callHierarchy.ts @@ -181,7 +181,7 @@ namespace ts.CallHierarchy { const indices = indicesOf(symbol.declarations); const keys = map(symbol.declarations, decl => ({ file: decl.getSourceFile().fileName, pos: decl.pos })); indices.sort((a, b) => compareStringsCaseSensitive(keys[a].file, keys[b].file) || keys[a].pos - keys[b].pos); - const sortedDeclarations = map(indices, i => symbol.declarations[i]); + const sortedDeclarations = map(indices, i => symbol.declarations![i]); let lastDecl: CallHierarchyDeclaration | undefined; for (const decl of sortedDeclarations) { if (isValidCallHierarchyDeclaration(decl)) { diff --git a/src/services/classifier.ts b/src/services/classifier.ts index fc9cad9c5a71d..b9c3b5711bf42 100644 --- a/src/services/classifier.ts +++ b/src/services/classifier.ts @@ -722,23 +722,57 @@ namespace ts { pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, ClassificationType.docCommentTagName); // e.g. "param" pos = tag.tagName.end; + let commentStart = tag.tagName.end; switch (tag.kind) { case SyntaxKind.JSDocParameterTag: - processJSDocParameterTag(tag); + const param = tag as JSDocParameterTag; + processJSDocParameterTag(param); + commentStart = param.isNameFirst && param.typeExpression?.end || param.name.end; + break; + case SyntaxKind.JSDocPropertyTag: + const prop = tag as JSDocPropertyTag; + commentStart = prop.isNameFirst && prop.typeExpression?.end || prop.name.end; break; case SyntaxKind.JSDocTemplateTag: processJSDocTemplateTag(tag); pos = tag.end; + commentStart = (tag as JSDocTemplateTag).typeParameters.end; + break; + case SyntaxKind.JSDocTypedefTag: + const type = tag as JSDocTypedefTag; + commentStart = type.typeExpression?.kind === SyntaxKind.JSDocTypeExpression && type.fullName?.end || type.typeExpression?.end || commentStart; + break; + case SyntaxKind.JSDocCallbackTag: + commentStart = (tag as JSDocCallbackTag).typeExpression.end; break; case SyntaxKind.JSDocTypeTag: processElement((tag).typeExpression); pos = tag.end; + commentStart = (tag as JSDocTypeTag).typeExpression.end; + break; + case SyntaxKind.JSDocThisTag: + case SyntaxKind.JSDocEnumTag: + commentStart = (tag as JSDocThisTag | JSDocEnumTag).typeExpression.end; break; case SyntaxKind.JSDocReturnTag: processElement((tag).typeExpression); pos = tag.end; + commentStart = (tag as JSDocReturnTag).typeExpression?.end || commentStart; break; + case SyntaxKind.JSDocSeeTag: + commentStart = (tag as JSDocSeeTag).name?.end || commentStart; + break; + case SyntaxKind.JSDocAugmentsTag: + case SyntaxKind.JSDocImplementsTag: + commentStart = (tag as JSDocImplementsTag | JSDocAugmentsTag).class.end; + break; + } + if (typeof tag.comment === "object") { + pushCommentRange(tag.comment.pos, tag.comment.end - tag.comment.pos); + } + else if (typeof tag.comment === "string") { + pushCommentRange(commentStart, tag.end - commentStart); } } } diff --git a/src/services/codeFixProvider.ts b/src/services/codeFixProvider.ts index aee5a199fad5b..5baf4734002fc 100644 --- a/src/services/codeFixProvider.ts +++ b/src/services/codeFixProvider.ts @@ -18,6 +18,10 @@ namespace ts.codefix { return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); } + export function createCodeFixActionMaybeFixAll(fixName: string, changes: FileTextChanges[], description: DiagnosticAndArguments, fixId?: {}, fixAllDescription?: DiagnosticAndArguments, command?: CodeActionCommand) { + return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, fixAllDescription && diagnosticToString(fixAllDescription), command); + } + function createCodeFixActionWorker(fixName: string, description: string, changes: FileTextChanges[], fixId?: {}, fixAllDescription?: string, command?: CodeActionCommand): CodeFixAction { return { fixName, description, changes, fixId, fixAllDescription, commands: command ? [command] : undefined }; } diff --git a/src/services/codefixes/addMissingAwait.ts b/src/services/codefixes/addMissingAwait.ts index 1b16a33deb382..e3a15d8864144 100644 --- a/src/services/codefixes/addMissingAwait.ts +++ b/src/services/codefixes/addMissingAwait.ts @@ -14,6 +14,7 @@ namespace ts.codefix { Diagnostics.Operator_0_cannot_be_applied_to_type_1.code, Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2.code, Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap.code, + Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined.code, Diagnostics.Type_0_is_not_an_array_type.code, Diagnostics.Type_0_is_not_an_array_type_or_a_string_type.code, Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators.code, diff --git a/src/services/codefixes/convertConstToLet.ts b/src/services/codefixes/convertConstToLet.ts index 610aaf5daa4e2..ba54cea297a70 100644 --- a/src/services/codefixes/convertConstToLet.ts +++ b/src/services/codefixes/convertConstToLet.ts @@ -18,7 +18,7 @@ namespace ts.codefix { const token = getTokenAtPosition(sourceFile, pos); const checker = program.getTypeChecker(); const symbol = checker.getSymbolAtLocation(token); - if (symbol) { + if (symbol?.valueDeclaration) { return symbol.valueDeclaration.parent.parent as VariableStatement; } } diff --git a/src/services/codefixes/convertFunctionToEs6Class.ts b/src/services/codefixes/convertFunctionToEs6Class.ts index 986eb07c53c07..70de7a1978d14 100644 --- a/src/services/codefixes/convertFunctionToEs6Class.ts +++ b/src/services/codefixes/convertFunctionToEs6Class.ts @@ -16,7 +16,7 @@ namespace ts.codefix { function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, position: number, checker: TypeChecker, preferences: UserPreferences, compilerOptions: CompilerOptions): void { const ctorSymbol = checker.getSymbolAtLocation(getTokenAtPosition(sourceFile, position))!; - if (!ctorSymbol || !(ctorSymbol.flags & (SymbolFlags.Function | SymbolFlags.Variable))) { + if (!ctorSymbol || !ctorSymbol.valueDeclaration || !(ctorSymbol.flags & (SymbolFlags.Function | SymbolFlags.Variable))) { // Bad input return undefined; } @@ -46,7 +46,7 @@ namespace ts.codefix { // all instance members are stored in the "member" array of symbol if (symbol.members) { symbol.members.forEach((member, key) => { - if (key === "constructor") { + if (key === "constructor" && member.valueDeclaration) { // fn.prototype.constructor = fn changes.delete(sourceFile, member.valueDeclaration.parent); return; @@ -61,7 +61,7 @@ namespace ts.codefix { // all static members are stored in the "exports" array of symbol if (symbol.exports) { symbol.exports.forEach(member => { - if (member.name === "prototype") { + if (member.name === "prototype" && member.declarations) { const firstDeclaration = member.declarations[0]; // only one "x.prototype = { ... }" will pass if (member.declarations.length === 1 && diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index 3fc61d8b45d3b..5445ad590f5ad 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -54,7 +54,7 @@ namespace ts.codefix { functionToConvert = tokenAtPosition.parent.initializer; } else { - functionToConvert = tryCast(getContainingFunction(getTokenAtPosition(sourceFile, position)), isFunctionLikeDeclaration); + functionToConvert = tryCast(getContainingFunction(getTokenAtPosition(sourceFile, position)), canBeConvertedToAsync); } if (!functionToConvert) { @@ -65,6 +65,10 @@ namespace ts.codefix { const isInJavascript = isInJSFile(functionToConvert); const setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); const functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap); + if (!returnsPromise(functionToConvertRenamed, checker)) { + return; + } + const returnStatements = functionToConvertRenamed.body && isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body, checker) : emptyArray; const transformer: Transformer = { checker, synthNamesMap, setOfExpressionsToReturn, isInJSFile: isInJavascript }; if (!returnStatements.length) { @@ -168,7 +172,10 @@ namespace ts.codefix { // so we push an entry for 'response'. if (lastCallSignature && !isParameter(node.parent) && !isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { const firstParameter = firstOrUndefined(lastCallSignature.parameters); - const ident = firstParameter && isParameter(firstParameter.valueDeclaration) && tryCast(firstParameter.valueDeclaration.name, isIdentifier) || factory.createUniqueName("result", GeneratedIdentifierFlags.Optimistic); + const ident = firstParameter?.valueDeclaration + && isParameter(firstParameter.valueDeclaration) + && tryCast(firstParameter.valueDeclaration.name, isIdentifier) + || factory.createUniqueName("result", GeneratedIdentifierFlags.Optimistic); const synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); collidingSymbolMap.add(ident.text, symbol); diff --git a/src/services/codefixes/convertToEs6Module.ts b/src/services/codefixes/convertToEs6Module.ts index 963f8923ee6ae..e15c507a4ef65 100644 --- a/src/services/codefixes/convertToEs6Module.ts +++ b/src/services/codefixes/convertToEs6Module.ts @@ -436,7 +436,9 @@ namespace ts.codefix { /** * Convert `import x = require("x").` - * Also converts uses like `x.y()` to `y()` and uses a named import. + * Also: + * - Convert `x.default()` to `x()` to handle ES6 default export + * - Converts uses like `x.y()` to `y()` and uses a named import. */ function convertSingleIdentifierImport(name: Identifier, moduleSpecifier: StringLiteralLike, checker: TypeChecker, identifiers: Identifiers, quotePreference: QuotePreference): ConvertedImports { const nameSymbol = checker.getSymbolAtLocation(name); @@ -454,15 +456,23 @@ namespace ts.codefix { const { parent } = use; if (isPropertyAccessExpression(parent)) { - const { expression, name: { text: propertyName } } = parent; - Debug.assert(expression === use, "Didn't expect expression === use"); // Else shouldn't have been in `collectIdentifiers` - let idName = namedBindingsNames.get(propertyName); - if (idName === undefined) { - idName = makeUniqueName(propertyName, identifiers); - namedBindingsNames.set(propertyName, idName); + const { name: { text: propertyName } } = parent; + if (propertyName === "default") { + needDefaultImport = true; + + const importDefaultName = use.getText(); + (useSitesToUnqualify ??= new Map()).set(parent, factory.createIdentifier(importDefaultName)); } + else { + Debug.assert(parent.expression === use, "Didn't expect expression === use"); // Else shouldn't have been in `collectIdentifiers` + let idName = namedBindingsNames.get(propertyName); + if (idName === undefined) { + idName = makeUniqueName(propertyName, identifiers); + namedBindingsNames.set(propertyName, idName); + } - (useSitesToUnqualify ??= new Map()).set(parent, factory.createIdentifier(idName)); + (useSitesToUnqualify ??= new Map()).set(parent, factory.createIdentifier(idName)); + } } else { needDefaultImport = true; diff --git a/src/services/codefixes/convertToTypeOnlyExport.ts b/src/services/codefixes/convertToTypeOnlyExport.ts index 117aca7b983c8..3f7a0d0983db1 100644 --- a/src/services/codefixes/convertToTypeOnlyExport.ts +++ b/src/services/codefixes/convertToTypeOnlyExport.ts @@ -12,7 +12,7 @@ namespace ts.codefix { }, fixIds: [fixId], getAllCodeActions: context => { - const fixedExportDeclarations = new Map(); + const fixedExportDeclarations = new Map(); return codeFixAll(context, errorCodes, (changes, diag) => { const exportSpecifier = getExportSpecifierForDiagnosticSpan(diag, context.sourceFile); if (exportSpecifier && addToSeen(fixedExportDeclarations, getNodeId(exportSpecifier.parent.parent))) { diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index 3e696435aa967..92a6f7647a1fc 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -276,11 +276,11 @@ namespace ts.codefix { const binaryExpression = token.parent.parent as BinaryExpression; const otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; const widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration, /*flags*/ undefined); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration, NodeBuilderFlags.NoTruncation); } else { const contextualType = checker.getContextualType(token.parent as Expression); - typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined) : undefined; + typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, NodeBuilderFlags.NoTruncation) : undefined; } return typeNode || factory.createKeywordTypeNode(SyntaxKind.AnyKeyword); } @@ -402,7 +402,7 @@ namespace ts.codefix { function addFunctionDeclaration(changes: textChanges.ChangeTracker, context: CodeFixContextBase, info: FunctionInfo) { const importAdder = createImportAdder(context.sourceFile, context.program, context.preferences, context.host); - const functionDeclaration = createSignatureDeclarationFromCallExpression(SyntaxKind.FunctionDeclaration, context, importAdder, info.call, info.token, info.modifierFlags, info.parentDeclaration) as FunctionDeclaration; + const functionDeclaration = createSignatureDeclarationFromCallExpression(SyntaxKind.FunctionDeclaration, context, importAdder, info.call, idText(info.token), info.modifierFlags, info.parentDeclaration) as FunctionDeclaration; changes.insertNodeAtEndOfScope(info.sourceFile, info.parentDeclaration, functionDeclaration); } } diff --git a/src/services/codefixes/fixAwaitInSyncFunction.ts b/src/services/codefixes/fixAwaitInSyncFunction.ts index 84c054fdb887e..bfd68e05d0abf 100644 --- a/src/services/codefixes/fixAwaitInSyncFunction.ts +++ b/src/services/codefixes/fixAwaitInSyncFunction.ts @@ -16,7 +16,7 @@ namespace ts.codefix { }, fixIds: [fixId], getAllCodeActions: context => { - const seen = new Map(); + const seen = new Map(); return codeFixAll(context, errorCodes, (changes, diag) => { const nodes = getNodes(diag.file, diag.start); if (!nodes || !addToSeen(seen, getNodeId(nodes.insertBefore))) return; diff --git a/src/services/codefixes/fixCannotFindModule.ts b/src/services/codefixes/fixCannotFindModule.ts index 482480d84205d..c2cb825b5e03f 100644 --- a/src/services/codefixes/fixCannotFindModule.ts +++ b/src/services/codefixes/fixCannotFindModule.ts @@ -44,7 +44,9 @@ namespace ts.codefix { } function tryGetImportedPackageName(sourceFile: SourceFile, pos: number): string | undefined { - const moduleName = cast(getTokenAtPosition(sourceFile, pos), isStringLiteral).text; + const moduleSpecifierText = tryCast(getTokenAtPosition(sourceFile, pos), isStringLiteral); + if (!moduleSpecifierText) return undefined; + const moduleName = moduleSpecifierText.text; const { packageName } = parsePackageName(moduleName); return isExternalModuleNameRelative(packageName) ? undefined : packageName; } diff --git a/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts b/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts index ae1a2448560de..9e8313f357b14 100644 --- a/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts +++ b/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts @@ -15,7 +15,7 @@ namespace ts.codefix { }, fixIds: [fixId], getAllCodeActions: context => { - const seenClassDeclarations = new Map(); + const seenClassDeclarations = new Map(); return codeFixAll(context, errorCodes, (changes, diag) => { const classDeclaration = getClass(diag.file, diag.start); if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) { diff --git a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts index 2ae9f1b94a9b3..01410672b3f28 100644 --- a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts +++ b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts @@ -17,7 +17,7 @@ namespace ts.codefix { }, fixIds: [fixId], getAllCodeActions(context) { - const seenClassDeclarations = new Map(); + const seenClassDeclarations = new Map(); return codeFixAll(context, errorCodes, (changes, diag) => { const classDeclaration = getClass(diag.file, diag.start); if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) { diff --git a/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts b/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts index dc8f261cc266b..224109f6d1237 100644 --- a/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts +++ b/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts @@ -15,7 +15,7 @@ namespace ts.codefix { fixIds: [fixId], getAllCodeActions(context) { const { sourceFile } = context; - const seenClasses = new Map(); // Ensure we only do this once per class. + const seenClasses = new Map(); // Ensure we only do this once per class. return codeFixAll(context, errorCodes, (changes, diag) => { const nodes = getNodes(diag.file, diag.start); if (!nodes) return; diff --git a/src/services/codefixes/fixMissingCallParentheses.ts b/src/services/codefixes/fixMissingCallParentheses.ts index a144bc40f5045..e86aa129aa40b 100644 --- a/src/services/codefixes/fixMissingCallParentheses.ts +++ b/src/services/codefixes/fixMissingCallParentheses.ts @@ -2,7 +2,7 @@ namespace ts.codefix { const fixId = "fixMissingCallParentheses"; const errorCodes = [ - Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead.code, + Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead.code, ]; registerCodeFix({ diff --git a/src/services/codefixes/fixOverrideModifier.ts b/src/services/codefixes/fixOverrideModifier.ts new file mode 100644 index 0000000000000..a804a5f97dbb9 --- /dev/null +++ b/src/services/codefixes/fixOverrideModifier.ts @@ -0,0 +1,134 @@ +/* @internal */ +namespace ts.codefix { + const fixName = "fixOverrideModifier"; + const fixAddOverrideId = "fixAddOverrideModifier"; + const fixRemoveOverrideId = "fixRemoveOverrideModifier"; + + type ClassElementLikeHasJSDoc = + | ConstructorDeclaration + | PropertyDeclaration + | MethodDeclaration + | GetAccessorDeclaration + | SetAccessorDeclaration + | ParameterPropertyDeclaration; + + const errorCodes = [ + Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code, + Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code, + Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code, + Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code, + Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code + ]; + + const errorCodeFixIdMap: Record = { + [Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code]: [ + Diagnostics.Add_override_modifier, fixAddOverrideId, Diagnostics.Add_all_missing_override_modifiers, + ], + [Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code]: [ + Diagnostics.Remove_override_modifier, fixRemoveOverrideId, Diagnostics.Remove_all_unnecessary_override_modifiers + ], + [Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code]: [ + Diagnostics.Add_override_modifier, fixAddOverrideId, Diagnostics.Add_all_missing_override_modifiers, + ], + [Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code]: [ + Diagnostics.Add_override_modifier, fixAddOverrideId, Diagnostics.Remove_all_unnecessary_override_modifiers + ], + [Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code]: [ + Diagnostics.Remove_override_modifier, fixRemoveOverrideId, Diagnostics.Remove_all_unnecessary_override_modifiers + ] + }; + + registerCodeFix({ + errorCodes, + getCodeActions: context => { + const { errorCode, span, sourceFile } = context; + + const info = errorCodeFixIdMap[errorCode]; + if (!info) return emptyArray; + + const [ descriptions, fixId, fixAllDescriptions ] = info; + if (isSourceFileJS(sourceFile)) return emptyArray; + const changes = textChanges.ChangeTracker.with(context, changes => dispatchChanges(changes, context, errorCode, span.start)); + + return [ + createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId, fixAllDescriptions) + ]; + }, + fixIds: [fixName, fixAddOverrideId, fixRemoveOverrideId], + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, diag) => { + const { code, start, file } = diag; + const info = errorCodeFixIdMap[code]; + if (!info || info[1] !== context.fixId || isSourceFileJS(file)) { + return; + } + + dispatchChanges(changes, context, code, start); + }) + }); + + function dispatchChanges( + changeTracker: textChanges.ChangeTracker, + context: CodeFixContext | CodeFixAllContext, + errorCode: number, + pos: number) { + switch (errorCode) { + case Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code: + case Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code: + case Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code: + return doAddOverrideModifierChange(changeTracker, context.sourceFile, pos); + case Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code: + case Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code: + return doRemoveOverrideModifierChange(changeTracker, context.sourceFile, pos); + default: + Debug.fail("Unexpected error code: " + errorCode); + } + } + + function doAddOverrideModifierChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, pos: number) { + const classElement = findContainerClassElementLike(sourceFile, pos); + const modifiers = classElement.modifiers || emptyArray; + const staticModifier = find(modifiers, isStaticModifier); + const accessibilityModifier = find(modifiers, m => isAccessibilityModifier(m.kind)); + const modifierPos = staticModifier ? staticModifier.end : + accessibilityModifier ? accessibilityModifier.end : + classElement.decorators ? skipTrivia(sourceFile.text, classElement.decorators.end) : classElement.getStart(sourceFile); + const options = accessibilityModifier || staticModifier ? { prefix: " " } : { suffix: " " }; + changeTracker.insertModifierAt(sourceFile, modifierPos, SyntaxKind.OverrideKeyword, options); + } + + function doRemoveOverrideModifierChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, pos: number) { + const classElement = findContainerClassElementLike(sourceFile, pos); + const overrideModifier = classElement.modifiers && find(classElement.modifiers, modifier => modifier.kind === SyntaxKind.OverrideKeyword); + Debug.assertIsDefined(overrideModifier); + + changeTracker.deleteModifier(sourceFile, overrideModifier); + } + + function isClassElementLikeHasJSDoc(node: Node): node is ClassElementLikeHasJSDoc { + switch (node.kind) { + case SyntaxKind.Constructor: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + return true; + case SyntaxKind.Parameter: + return isParameterPropertyDeclaration(node, node.parent); + default: + return false; + } + } + + function findContainerClassElementLike(sourceFile: SourceFile, pos: number) { + const token = getTokenAtPosition(sourceFile, pos); + const classElement = findAncestor(token, node => { + if (isClassLike(node)) return "quit"; + return isClassElementLikeHasJSDoc(node); + }); + + Debug.assert(classElement && isClassElementLikeHasJSDoc(classElement)); + return classElement; + } +} + diff --git a/src/services/codefixes/fixSpelling.ts b/src/services/codefixes/fixSpelling.ts index 78d748589e837..6d80e1f900899 100644 --- a/src/services/codefixes/fixSpelling.ts +++ b/src/services/codefixes/fixSpelling.ts @@ -46,7 +46,7 @@ namespace ts.codefix { let suggestedSymbol: Symbol | undefined; if (isPropertyAccessExpression(parent) && parent.name === node) { - Debug.assert(isIdentifierOrPrivateIdentifier(node), "Expected an identifier for spelling (property access)"); + Debug.assert(isMemberName(node), "Expected an identifier for spelling (property access)"); let containingType = checker.getTypeAtLocation(parent.expression); if (parent.flags & NodeFlags.OptionalChain) { containingType = checker.getNonNullableType(containingType); @@ -87,7 +87,7 @@ namespace ts.codefix { const suggestion = symbolName(suggestedSymbol); if (!isIdentifierText(suggestion, target) && isPropertyAccessExpression(node.parent)) { const valDecl = suggestedSymbol.valueDeclaration; - if (isNamedDeclaration(valDecl) && isPrivateIdentifier(valDecl.name)) { + if (valDecl && isNamedDeclaration(valDecl) && isPrivateIdentifier(valDecl.name)) { changes.replaceNode(sourceFile, node, factory.createIdentifier(suggestion)); } else { diff --git a/src/services/codefixes/fixUnusedIdentifier.ts b/src/services/codefixes/fixUnusedIdentifier.ts index db7e0550e9a38..9c755729c20e8 100644 --- a/src/services/codefixes/fixUnusedIdentifier.ts +++ b/src/services/codefixes/fixUnusedIdentifier.ts @@ -237,8 +237,10 @@ namespace ts.codefix { if (isParameter(parent)) { tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, program, cancellationToken, isFixAll); } - else if (!isFixAll || !(isIdentifier(token) && FindAllReferences.Core.isSymbolReferencedInFile(token, checker, sourceFile))) { - changes.delete(sourceFile, isImportClause(parent) ? token : isComputedPropertyName(parent) ? parent.parent : parent); + else if (!(isFixAll && isIdentifier(token) && FindAllReferences.Core.isSymbolReferencedInFile(token, checker, sourceFile))) { + const node = isImportClause(parent) ? token : isComputedPropertyName(parent) ? parent.parent : parent; + Debug.assert(node !== sourceFile, "should not delete whole source file"); + changes.delete(sourceFile, node); } } diff --git a/src/services/codefixes/generateAccessors.ts b/src/services/codefixes/generateAccessors.ts index 99bd53e29343f..d51d30abda789 100644 --- a/src/services/codefixes/generateAccessors.ts +++ b/src/services/codefixes/generateAccessors.ts @@ -83,10 +83,6 @@ namespace ts.codefix { return isIdentifier(fieldName) ? factory.createPropertyAccessExpression(leftHead, fieldName) : factory.createElementAccessExpression(leftHead, factory.createStringLiteralFromNode(fieldName)); } - function createModifiers(modifierFlags: ModifierFlags): ModifiersArray | undefined { - return modifierFlags ? factory.createNodeArray(factory.createModifiersFromModifierFlags(modifierFlags)) : undefined; - } - function prepareModifierFlagsForAccessor(modifierFlags: ModifierFlags): ModifierFlags { modifierFlags &= ~ModifierFlags.Readonly; // avoid Readonly modifier because it will convert to get accessor modifierFlags &= ~ModifierFlags.Private; @@ -262,7 +258,7 @@ namespace ts.codefix { const superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression); if (!superSymbol) break; const symbol = superSymbol.flags & SymbolFlags.Alias ? checker.getAliasedSymbol(superSymbol) : superSymbol; - const superDecl = find(symbol.declarations, isClassLike); + const superDecl = symbol.declarations && find(symbol.declarations, isClassLike); if (!superDecl) break; res.push(superDecl); decl = superDecl; diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 4e91a28dafadc..c6a982546fa22 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -138,7 +138,7 @@ namespace ts.codefix { } else { Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count"); - addClassElement(createMethodImplementingSignatures(signatures, name, optional, modifiers, quotePreference)); + addClassElement(createMethodImplementingSignatures(checker, context, enclosingDeclaration, signatures, name, optional, modifiers, quotePreference)); } } break; @@ -252,7 +252,7 @@ namespace ts.codefix { context: CodeFixContextBase, importAdder: ImportAdder, call: CallExpression, - name: Identifier, + name: Identifier | string, modifierFlags: ModifierFlags, contextNode: Node ) { @@ -338,6 +338,9 @@ namespace ts.codefix { } function createMethodImplementingSignatures( + checker: TypeChecker, + context: TypeConstructionContext, + enclosingDeclaration: ClassLikeDeclaration, signatures: readonly Signature[], name: PropertyName, optional: boolean, @@ -362,7 +365,6 @@ namespace ts.codefix { } const maxNonRestArgs = maxArgsSignature.parameters.length - (signatureHasRestParameter(maxArgsSignature) ? 1 : 0); const maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(symbol => symbol.name); - const parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { @@ -384,10 +386,17 @@ namespace ts.codefix { optional, /*typeParameters*/ undefined, parameters, - /*returnType*/ undefined, + getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), quotePreference); } + function getReturnTypeFromSignatures(signatures: readonly Signature[], checker: TypeChecker, context: TypeConstructionContext, enclosingDeclaration: ClassLikeDeclaration): TypeNode | undefined { + if (length(signatures)) { + const type = checker.getUnionType(map(signatures, checker.getReturnTypeOfSignature)); + return checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); + } + } + function createStubbedMethod( modifiers: readonly Modifier[] | undefined, name: PropertyName, diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 9700e6b583b3e..061aeaaca7733 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -156,11 +156,13 @@ namespace ts.codefix { readonly kind: ImportFixKind.UseNamespace; readonly namespacePrefix: string; readonly position: number; + readonly moduleSpecifier: string; } interface FixUseImportType { readonly kind: ImportFixKind.ImportType; readonly moduleSpecifier: string; readonly position: number; + readonly exportInfo: SymbolExportInfo; } interface FixAddToExistingImport { readonly kind: ImportFixKind.AddToExisting; @@ -175,21 +177,7 @@ namespace ts.codefix { readonly importKind: ImportKind; readonly typeOnly: boolean; readonly useRequire: boolean; - } - - const enum ImportKind { - Named, - Default, - Namespace, - CommonJS, - } - - /** Information about how a symbol is exported from a module. (We don't need to store the exported symbol, just its module.) */ - interface SymbolExportInfo { - readonly moduleSymbol: Symbol; - readonly importKind: ImportKind; - /** If true, can't use an es6 import from a js file. */ - readonly exportedSymbolIsTypeOnly: boolean; + readonly exportInfo?: SymbolExportInfo; } /** Information needed to augment an existing import declaration. */ @@ -211,42 +199,40 @@ namespace ts.codefix { ): { readonly moduleSpecifier: string, readonly codeAction: CodeAction } { const compilerOptions = program.getCompilerOptions(); const exportInfos = pathIsBareSpecifier(stripQuotes(moduleSymbol.name)) - ? [getSymbolExportInfoForSymbol(exportedSymbol, moduleSymbol, sourceFile, program, host)] + ? [getSymbolExportInfoForSymbol(exportedSymbol, moduleSymbol, program, host)] : getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, host, program, /*useAutoImportProvider*/ true); const useRequire = shouldUseRequire(sourceFile, program); const preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Error && !isSourceFileJS(sourceFile) && isValidTypeOnlyAliasUseSite(getTokenAtPosition(sourceFile, position)); - const moduleSpecifier = getBestFix(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences), sourceFile, program, host).moduleSpecifier; const fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences); - return { moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host, formatContext, preferences }, sourceFile, symbolName, fix, getQuotePreference(sourceFile, preferences))) }; + return { moduleSpecifier: fix.moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host, formatContext, preferences }, sourceFile, symbolName, fix, getQuotePreference(sourceFile, preferences))) }; } function getImportFixForSymbol(sourceFile: SourceFile, exportInfos: readonly SymbolExportInfo[], moduleSymbol: Symbol, symbolName: string, program: Program, position: number | undefined, preferTypeOnlyImport: boolean, useRequire: boolean, host: LanguageServiceHost, preferences: UserPreferences) { Debug.assert(exportInfos.some(info => info.moduleSymbol === moduleSymbol), "Some exportInfo should match the specified moduleSymbol"); - // We sort the best codefixes first, so taking `first` is best. - return getBestFix(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences), sourceFile, program, host); + return getBestFix(getImportFixes(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences), sourceFile, host); } function codeFixActionToCodeAction({ description, changes, commands }: CodeFixAction): CodeAction { return { description, changes, commands }; } - function getSymbolExportInfoForSymbol(symbol: Symbol, moduleSymbol: Symbol, importingFile: SourceFile, program: Program, host: LanguageServiceHost): SymbolExportInfo { + function getSymbolExportInfoForSymbol(symbol: Symbol, moduleSymbol: Symbol, program: Program, host: LanguageServiceHost): SymbolExportInfo { const compilerOptions = program.getCompilerOptions(); - const mainProgramInfo = getInfoWithChecker(program.getTypeChecker()); + const mainProgramInfo = getInfoWithChecker(program.getTypeChecker(), /*isFromPackageJson*/ false); if (mainProgramInfo) { return mainProgramInfo; } const autoImportProvider = host.getPackageJsonAutoImportProvider?.()?.getTypeChecker(); - return Debug.checkDefined(autoImportProvider && getInfoWithChecker(autoImportProvider), `Could not find symbol in specified module for code actions`); + return Debug.checkDefined(autoImportProvider && getInfoWithChecker(autoImportProvider, /*isFromPackageJson*/ true), `Could not find symbol in specified module for code actions`); - function getInfoWithChecker(checker: TypeChecker): SymbolExportInfo | undefined { - const defaultInfo = getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions); + function getInfoWithChecker(checker: TypeChecker, isFromPackageJson: boolean): SymbolExportInfo | undefined { + const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); if (defaultInfo && skipAlias(defaultInfo.symbol, checker) === symbol) { - return { moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker) }; + return { symbol: defaultInfo.symbol, moduleSymbol, exportKind: defaultInfo.exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker), isFromPackageJson }; } const named = checker.tryGetMemberInModuleExportsAndProperties(symbol.name, moduleSymbol); if (named && skipAlias(named, checker) === symbol) { - return { moduleSymbol, importKind: ImportKind.Named, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker) }; + return { symbol: named, moduleSymbol, exportKind: ExportKind.Named, exportedSymbolIsTypeOnly: isTypeOnlySymbol(symbol, checker), isFromPackageJson }; } } } @@ -254,25 +240,92 @@ namespace ts.codefix { function getAllReExportingModules(importingFile: SourceFile, exportedSymbol: Symbol, exportingModuleSymbol: Symbol, symbolName: string, host: LanguageServiceHost, program: Program, useAutoImportProvider: boolean): readonly SymbolExportInfo[] { const result: SymbolExportInfo[] = []; const compilerOptions = program.getCompilerOptions(); - forEachExternalModuleToImportFrom(program, host, importingFile, /*filterByPackageJson*/ false, useAutoImportProvider, (moduleSymbol, moduleFile, program) => { + const getModuleSpecifierResolutionHost = memoizeOne((isFromPackageJson: boolean) => { + return createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider!()! : program, host); + }); + + forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, (moduleSymbol, moduleFile, program, isFromPackageJson) => { const checker = program.getTypeChecker(); // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && startsWith(importingFile.fileName, getDirectoryPath(moduleFile.fileName))) { return; } - const defaultInfo = getDefaultLikeExportInfo(importingFile, moduleSymbol, checker, compilerOptions); - if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { - result.push({ moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && skipAlias(defaultInfo.symbol, checker) === exportedSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + result.push({ symbol: defaultInfo.symbol, moduleSymbol, exportKind: defaultInfo.exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker), isFromPackageJson }); } for (const exported of checker.getExportsAndPropertiesOfModule(moduleSymbol)) { - if (exported.name === symbolName && skipAlias(exported, checker) === exportedSymbol) { - result.push({ moduleSymbol, importKind: ImportKind.Named, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); + if (exported.name === symbolName && skipAlias(exported, checker) === exportedSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + result.push({ symbol: exported, moduleSymbol, exportKind: ExportKind.Named, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker), isFromPackageJson }); } } }); return result; + + function isImportable(program: Program, moduleFile: SourceFile | undefined, isFromPackageJson: boolean) { + return !moduleFile || isImportableFile(program, importingFile, moduleFile, /*packageJsonFilter*/ undefined, getModuleSpecifierResolutionHost(isFromPackageJson), host.getModuleSpecifierCache?.()); + } + } + + export function getModuleSpecifierForBestExportInfo(exportInfo: readonly SymbolExportInfo[], + importingFile: SourceFile, + program: Program, + host: LanguageServiceHost, + preferences: UserPreferences + ): { exportInfo?: SymbolExportInfo, moduleSpecifier: string } { + return getBestFix(getNewImportFixes(program, importingFile, /*position*/ undefined, /*preferTypeOnlyImport*/ false, /*useRequire*/ false, exportInfo, host, preferences), importingFile, host); + } + + export function getSymbolToExportInfoMap(importingFile: SourceFile, host: LanguageServiceHost, program: Program) { + const start = timestamp(); + // Pulling the AutoImportProvider project will trigger its updateGraph if pending, + // which will invalidate the export map cache if things change, so pull it before + // checking the cache. + host.getPackageJsonAutoImportProvider?.(); + const cache = host.getExportMapCache?.(); + if (cache) { + const cached = cache.get(importingFile.path, program.getTypeChecker(), host.getProjectVersion?.()); + if (cached) { + host.log?.("getSymbolToExportInfoMap: cache hit"); + return cached; + } + else { + host.log?.("getSymbolToExportInfoMap: cache miss or empty; calculating new results"); + } + } + + const result: MultiMap = createMultiMap(); + const compilerOptions = program.getCompilerOptions(); + const target = getEmitScriptTarget(compilerOptions); + forEachExternalModuleToImportFrom(program, host, /*useAutoImportProvider*/ true, (moduleSymbol, _moduleFile, program, isFromPackageJson) => { + const checker = program.getTypeChecker(); + const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo) { + const name = getNameForExportedSymbol(getLocalSymbolForExportDefault(defaultInfo.symbol) || defaultInfo.symbol, target); + result.add(key(name, defaultInfo.symbol, moduleSymbol, checker), { symbol: defaultInfo.symbol, moduleSymbol, exportKind: defaultInfo.exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker), isFromPackageJson }); + } + const seenExports = new Map(); + for (const exported of checker.getExportsAndPropertiesOfModule(moduleSymbol)) { + if (exported !== defaultInfo?.symbol && addToSeen(seenExports, exported)) { + result.add(key(getNameForExportedSymbol(exported, target), exported, moduleSymbol, checker), { symbol: exported, moduleSymbol, exportKind: ExportKind.Named, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker), isFromPackageJson }); + } + } + }); + + if (cache) { + host.log?.("getSymbolToExportInfoMap: caching results"); + cache.set(result, host.getProjectVersion?.()); + } + host.log?.(`getSymbolToExportInfoMap: done in ${timestamp() - start} ms`); + return result; + + function key(name: string, alias: Symbol, moduleSymbol: Symbol, checker: TypeChecker) { + const moduleName = stripQuotes(moduleSymbol.name); + const moduleKey = isExternalModuleNameRelative(moduleName) ? "/" : moduleName; + return `${name}|${getSymbolId(skipAlias(alias, checker))}|${moduleKey}`; + } } function isTypeOnlySymbol(s: Symbol, checker: TypeChecker): boolean { @@ -283,7 +336,7 @@ namespace ts.codefix { return isValidTypeOnlyAliasUseSite(getTokenAtPosition(sourceFile, position)); } - function getFixForImport( + function getImportFixes( exportInfos: readonly SymbolExportInfo[], symbolName: string, /** undefined only for missing JSX namespace */ @@ -296,7 +349,7 @@ namespace ts.codefix { preferences: UserPreferences, ): readonly ImportFix[] { const checker = program.getTypeChecker(); - const existingImports = flatMap(exportInfos, info => getExistingImportDeclarations(info, checker, sourceFile)); + const existingImports = flatMap(exportInfos, info => getExistingImportDeclarations(info, checker, sourceFile, program.getCompilerOptions())); const useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); const addToExisting = tryAddToExistingImport(existingImports, position !== undefined && isTypeOnlyPosition(sourceFile, position)); // Don't bother providing an action to add a new import if we can add to an existing one. @@ -319,10 +372,11 @@ namespace ts.codefix { // and it is up to the user to decide which one fits best. return firstDefined(existingImports, ({ declaration }): FixUseNamespaceImport | undefined => { const namespacePrefix = getNamespaceLikeImportText(declaration); - if (namespacePrefix) { + const moduleSpecifier = tryGetModuleSpecifierFromDeclaration(declaration); + if (namespacePrefix && moduleSpecifier) { const moduleSymbol = getTargetModuleFromNamespaceLikeImport(declaration, checker); if (moduleSymbol && moduleSymbol.exports!.has(escapeLeadingUnderscores(symbolName))) { - return { kind: ImportFixKind.UseNamespace, namespacePrefix, position }; + return { kind: ImportFixKind.UseNamespace, namespacePrefix, position, moduleSpecifier }; } } }); @@ -364,19 +418,24 @@ namespace ts.codefix { : undefined; } const { importClause } = declaration; - if (!importClause) return undefined; + if (!importClause || !isStringLiteralLike(declaration.moduleSpecifier)) return undefined; const { name, namedBindings } = importClause; + // A type-only import may not have both a default and named imports, so the only way a name can + // be added to an existing type-only import is adding a named import to existing named bindings. + if (importClause.isTypeOnly && !(importKind === ImportKind.Named && namedBindings)) return undefined; return importKind === ImportKind.Default && !name || importKind === ImportKind.Named && (!namedBindings || namedBindings.kind === SyntaxKind.NamedImports) - ? { kind: ImportFixKind.AddToExisting, importClauseOrBindingPattern: importClause, importKind, moduleSpecifier: declaration.moduleSpecifier.getText(), canUseTypeOnlyImport } + ? { kind: ImportFixKind.AddToExisting, importClauseOrBindingPattern: importClause, importKind, moduleSpecifier: declaration.moduleSpecifier.text, canUseTypeOnlyImport } : undefined; }); } - function getExistingImportDeclarations({ moduleSymbol, importKind, exportedSymbolIsTypeOnly }: SymbolExportInfo, checker: TypeChecker, sourceFile: SourceFile): readonly FixAddToExistingImportInfo[] { + function getExistingImportDeclarations({ moduleSymbol, exportKind, exportedSymbolIsTypeOnly }: SymbolExportInfo, checker: TypeChecker, importingFile: SourceFile, compilerOptions: CompilerOptions): readonly FixAddToExistingImportInfo[] { // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && isSourceFileJS(sourceFile) ? emptyArray : mapDefined(sourceFile.imports, (moduleSpecifier): FixAddToExistingImportInfo | undefined => { + if (exportedSymbolIsTypeOnly && isSourceFileJS(importingFile)) return emptyArray; + const importKind = getImportKind(importingFile, exportKind, compilerOptions); + return mapDefined(importingFile.imports, (moduleSpecifier): FixAddToExistingImportInfo | undefined => { const i = importFromModuleSpecifier(moduleSpecifier); - if (isRequireVariableDeclaration(i.parent, /*requireStringLiteralLikeArgument*/ true)) { + if (isRequireVariableDeclaration(i.parent)) { return checker.resolveExternalModuleName(moduleSpecifier) === moduleSymbol ? { declaration: i.parent, importKind } : undefined; } if (i.kind === SyntaxKind.ImportDeclaration || i.kind === SyntaxKind.ImportEqualsDeclaration) { @@ -412,7 +471,7 @@ namespace ts.codefix { return true; } - function getNewImportInfos( + function getNewImportFixes( program: Program, sourceFile: SourceFile, position: number | undefined, @@ -424,13 +483,14 @@ namespace ts.codefix { ): readonly (FixAddNewImport | FixUseImportType)[] { const isJs = isSourceFileJS(sourceFile); const compilerOptions = program.getCompilerOptions(); - return flatMap(moduleSymbols, ({ moduleSymbol, importKind, exportedSymbolIsTypeOnly }) => - moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getTypeChecker(), compilerOptions, sourceFile, createModuleSpecifierResolutionHost(program, host), preferences) + const moduleSpecifierResolutionHost = createModuleSpecifierResolutionHost(program, host); + return flatMap(moduleSymbols, exportInfo => + moduleSpecifiers.getModuleSpecifiers(exportInfo.moduleSymbol, program.getTypeChecker(), compilerOptions, sourceFile, moduleSpecifierResolutionHost, preferences) .map((moduleSpecifier): FixAddNewImport | FixUseImportType => // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. - exportedSymbolIsTypeOnly && isJs - ? { kind: ImportFixKind.ImportType, moduleSpecifier, position: Debug.checkDefined(position, "position should be defined") } - : { kind: ImportFixKind.AddNew, moduleSpecifier, importKind, useRequire, typeOnly: preferTypeOnlyImport })); + exportInfo.exportedSymbolIsTypeOnly && isJs && position !== undefined + ? { kind: ImportFixKind.ImportType, moduleSpecifier, position, exportInfo } + : { kind: ImportFixKind.AddNew, moduleSpecifier, importKind: getImportKind(sourceFile, exportInfo.exportKind, compilerOptions), useRequire, typeOnly: preferTypeOnlyImport, exportInfo })); } function getFixesForAddImport( @@ -445,16 +505,13 @@ namespace ts.codefix { preferences: UserPreferences, ): readonly (FixAddNewImport | FixUseImportType)[] { const existingDeclaration = firstDefined(existingImports, info => newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport, useRequire)); - return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences); + return existingDeclaration ? [existingDeclaration] : getNewImportFixes(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences); } function newImportInfoFromExistingSpecifier({ declaration, importKind }: FixAddToExistingImportInfo, preferTypeOnlyImport: boolean, useRequire: boolean): FixAddNewImport | undefined { - const moduleSpecifier = declaration.kind === SyntaxKind.ImportDeclaration ? declaration.moduleSpecifier : - declaration.kind === SyntaxKind.VariableDeclaration ? declaration.initializer.arguments[0] : - declaration.moduleReference.kind === SyntaxKind.ExternalModuleReference ? declaration.moduleReference.expression : - undefined; - return moduleSpecifier && isStringLiteral(moduleSpecifier) - ? { kind: ImportFixKind.AddNew, moduleSpecifier: moduleSpecifier.text, importKind, typeOnly: preferTypeOnlyImport, useRequire } + const moduleSpecifier = tryGetModuleSpecifierFromDeclaration(declaration); + return moduleSpecifier + ? { kind: ImportFixKind.AddNew, moduleSpecifier, importKind, typeOnly: preferTypeOnlyImport, useRequire } : undefined; } @@ -464,20 +521,20 @@ namespace ts.codefix { const info = errorCode === Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code ? getFixesInfoForUMDImport(context, symbolToken) : isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider) : undefined; - return info && { ...info, fixes: sortFixes(info.fixes, context.sourceFile, context.program, context.host) }; + return info && { ...info, fixes: sortFixes(info.fixes, context.sourceFile, context.host) }; } - function sortFixes(fixes: readonly ImportFix[], sourceFile: SourceFile, program: Program, host: LanguageServiceHost): readonly ImportFix[] { - const { allowsImportingSpecifier } = createAutoImportFilter(sourceFile, program, host); + function sortFixes(fixes: readonly ImportFix[], sourceFile: SourceFile, host: LanguageServiceHost): readonly ImportFix[] { + const { allowsImportingSpecifier } = createPackageJsonImportFilter(sourceFile, host); return sort(fixes, (a, b) => compareValues(a.kind, b.kind) || compareModuleSpecifiers(a, b, allowsImportingSpecifier)); } - function getBestFix(fixes: readonly T[], sourceFile: SourceFile, program: Program, host: LanguageServiceHost): T { + function getBestFix(fixes: readonly T[], sourceFile: SourceFile, host: LanguageServiceHost): T { // These will always be placed first if available, and are better than other kinds if (fixes[0].kind === ImportFixKind.UseNamespace || fixes[0].kind === ImportFixKind.AddToExisting) { return fixes[0]; } - const { allowsImportingSpecifier } = createAutoImportFilter(sourceFile, program, host); + const { allowsImportingSpecifier } = createPackageJsonImportFilter(sourceFile, host); return fixes.reduce((best, fix) => compareModuleSpecifiers(fix, best, allowsImportingSpecifier) === Comparison.LessThan ? fix : best ); @@ -497,9 +554,9 @@ namespace ts.codefix { if (!umdSymbol) return undefined; const symbol = checker.getAliasedSymbol(umdSymbol); const symbolName = umdSymbol.name; - const exportInfos: readonly SymbolExportInfo[] = [{ moduleSymbol: symbol, importKind: getUmdImportKind(sourceFile, program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; + const exportInfos: readonly SymbolExportInfo[] = [{ symbol: umdSymbol, moduleSymbol: symbol, exportKind: ExportKind.UMD, exportedSymbolIsTypeOnly: false, isFromPackageJson: false }]; const useRequire = shouldUseRequire(sourceFile, program); - const fixes = getFixForImport(exportInfos, symbolName, isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, useRequire, program, sourceFile, host, preferences); + const fixes = getImportFixes(exportInfos, symbolName, isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, useRequire, program, sourceFile, host, preferences); return { fixes, symbolName }; } function getUmdSymbol(token: Node, checker: TypeChecker): Symbol | undefined { @@ -514,6 +571,16 @@ namespace ts.codefix { : undefined; } + export function getImportKind(importingFile: SourceFile, exportKind: ExportKind, compilerOptions: CompilerOptions): ImportKind { + switch (exportKind) { + case ExportKind.Named: return ImportKind.Named; + case ExportKind.Default: return ImportKind.Default; + case ExportKind.ExportEquals: return getExportEqualsImportKind(importingFile, compilerOptions); + case ExportKind.UMD: return getUmdImportKind(importingFile, compilerOptions); + default: return Debug.assertNever(exportKind); + } + } + function getUmdImportKind(importingFile: SourceFile, compilerOptions: CompilerOptions): ImportKind { // Import a synthetic `default` if enabled. if (getAllowSyntheticDefaultImports(compilerOptions)) { @@ -544,22 +611,22 @@ namespace ts.codefix { function getFixesInfoForNonUMDImport({ sourceFile, program, cancellationToken, host, preferences }: CodeFixContextBase, symbolToken: Identifier, useAutoImportProvider: boolean): FixesInfo | undefined { const checker = program.getTypeChecker(); - const symbolName = getSymbolName(sourceFile, checker, symbolToken); + const compilerOptions = program.getCompilerOptions(); + const symbolName = getSymbolName(sourceFile, checker, symbolToken, compilerOptions); // "default" is a keyword and not a legal identifier for the import, so we don't expect it here Debug.assert(symbolName !== InternalSymbolName.Default, "'default' isn't a legal identifier and couldn't occur here"); - const compilerOptions = program.getCompilerOptions(); const preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Error && isValidTypeOnlyAliasUseSite(symbolToken); const useRequire = shouldUseRequire(sourceFile, program); const exportInfos = getExportInfos(symbolName, getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host); const fixes = arrayFrom(flatMapIterator(exportInfos.entries(), ([_, exportInfos]) => - getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences))); + getImportFixes(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences))); return { fixes, symbolName }; } - function getSymbolName(sourceFile: SourceFile, checker: TypeChecker, symbolToken: Identifier): string { + function getSymbolName(sourceFile: SourceFile, checker: TypeChecker, symbolToken: Identifier, compilerOptions: CompilerOptions): string { const parent = symbolToken.parent; - if ((isJsxOpeningLikeElement(parent) || isJsxClosingElement(parent)) && parent.tagName === symbolToken) { + if ((isJsxOpeningLikeElement(parent) || isJsxClosingElement(parent)) && parent.tagName === symbolToken && compilerOptions.jsx !== JsxEmit.ReactJSX && compilerOptions.jsx !== JsxEmit.ReactJSXDev) { const jsxNamespace = checker.getJsxNamespace(sourceFile); if (isIntrinsicJsxName(symbolToken.text) || !checker.resolveName(jsxNamespace, parent, SymbolFlags.Value, /*excludeGlobals*/ true)) { return jsxNamespace; @@ -573,7 +640,7 @@ namespace ts.codefix { symbolName: string, currentTokenMeaning: SemanticMeaning, cancellationToken: CancellationToken, - sourceFile: SourceFile, + fromFile: SourceFile, program: Program, useAutoImportProvider: boolean, host: LanguageServiceHost @@ -581,43 +648,52 @@ namespace ts.codefix { // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. // 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, checker: TypeChecker): void { - originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol, importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); + const packageJsonFilter = createPackageJsonImportFilter(fromFile, host); + const moduleSpecifierCache = host.getModuleSpecifierCache?.(); + const getModuleSpecifierResolutionHost = memoizeOne((isFromPackageJson: boolean) => { + return createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider!()! : program, host); + }); + function addSymbol(moduleSymbol: Symbol, toFile: SourceFile | undefined, exportedSymbol: Symbol, exportKind: ExportKind, program: Program, isFromPackageJson: boolean): void { + const moduleSpecifierResolutionHost = getModuleSpecifierResolutionHost(isFromPackageJson); + if (toFile && isImportableFile(program, fromFile, toFile, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) || + !toFile && packageJsonFilter.allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost) + ) { + const checker = program.getTypeChecker(); + originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { symbol: exportedSymbol, moduleSymbol, exportKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker), isFromPackageJson }); + } } - forEachExternalModuleToImportFrom(program, host, sourceFile, /*filterByPackageJson*/ true, useAutoImportProvider, (moduleSymbol, _, program) => { + forEachExternalModuleToImportFrom(program, host, useAutoImportProvider, (moduleSymbol, sourceFile, program, isFromPackageJson) => { const checker = program.getTypeChecker(); cancellationToken.throwIfCancellationRequested(); const compilerOptions = program.getCompilerOptions(); - const defaultInfo = getDefaultLikeExportInfo(sourceFile, moduleSymbol, checker, compilerOptions); + const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind, checker); + addSymbol(moduleSymbol, sourceFile, defaultInfo.symbol, defaultInfo.exportKind, program, isFromPackageJson); } // check exports with the same name const exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - addSymbol(moduleSymbol, exportSymbolWithIdenticalName, ImportKind.Named, checker); + addSymbol(moduleSymbol, sourceFile, exportSymbolWithIdenticalName, ExportKind.Named, program, isFromPackageJson); } }); return originalSymbolToExportInfos; } - function getDefaultLikeExportInfo( - importingFile: SourceFile, moduleSymbol: Symbol, checker: TypeChecker, compilerOptions: CompilerOptions, - ): { readonly symbol: Symbol, readonly symbolForMeaning: Symbol, readonly name: string, readonly kind: ImportKind } | undefined { - const exported = getDefaultLikeExportWorker(importingFile, moduleSymbol, checker, compilerOptions); + function getDefaultLikeExportInfo(moduleSymbol: Symbol, checker: TypeChecker, compilerOptions: CompilerOptions) { + const exported = getDefaultLikeExportWorker(moduleSymbol, checker); if (!exported) return undefined; - const { symbol, kind } = exported; + const { symbol, exportKind } = exported; const info = getDefaultExportInfoWorker(symbol, checker, compilerOptions); - return info && { symbol, kind, ...info }; + return info && { symbol, exportKind, ...info }; } - function getDefaultLikeExportWorker(importingFile: SourceFile, moduleSymbol: Symbol, checker: TypeChecker, compilerOptions: CompilerOptions): { readonly symbol: Symbol, readonly kind: ImportKind } | undefined { - const defaultExport = checker.tryGetMemberInModuleExports(InternalSymbolName.Default, moduleSymbol); - if (defaultExport) return { symbol: defaultExport, kind: ImportKind.Default }; + function getDefaultLikeExportWorker(moduleSymbol: Symbol, checker: TypeChecker): { readonly symbol: Symbol, readonly exportKind: ExportKind } | undefined { const exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); - return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: getExportEqualsImportKind(importingFile, compilerOptions) }; + if (exportEquals !== moduleSymbol) return { symbol: exportEquals, exportKind: ExportKind.ExportEquals }; + const defaultExport = checker.tryGetMemberInModuleExports(InternalSymbolName.Default, moduleSymbol); + if (defaultExport) return { symbol: defaultExport, exportKind: ExportKind.Default }; } function getExportEqualsImportKind(importingFile: SourceFile, compilerOptions: CompilerOptions): ImportKind { @@ -636,7 +712,8 @@ namespace ts.codefix { // really hate that, so look to see if the importing file has any precedent // on how to handle it. for (const statement of importingFile.statements) { - if (isImportEqualsDeclaration(statement)) { + // `import foo` parses as an ImportEqualsDeclaration even though it could be an ImportDeclaration + if (isImportEqualsDeclaration(statement) && !nodeIsMissing(statement.moduleReference)) { return ImportKind.CommonJS; } } @@ -880,57 +957,23 @@ namespace ts.codefix { export function forEachExternalModuleToImportFrom( program: Program, host: LanguageServiceHost, - from: SourceFile, - filterByPackageJson: boolean, useAutoImportProvider: boolean, cb: (module: Symbol, moduleFile: SourceFile | undefined, program: Program, isFromPackageJson: boolean) => void, ) { - forEachExternalModuleToImportFromInProgram(program, host, from, filterByPackageJson, (module, file) => cb(module, file, program, /*isFromPackageJson*/ false)); + forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), (module, file) => cb(module, file, program, /*isFromPackageJson*/ false)); const autoImportProvider = useAutoImportProvider && host.getPackageJsonAutoImportProvider?.(); if (autoImportProvider) { const start = timestamp(); - forEachExternalModuleToImportFromInProgram(autoImportProvider, host, from, filterByPackageJson, (module, file) => cb(module, file, autoImportProvider, /*isFromPackageJson*/ true)); + forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), (module, file) => cb(module, file, autoImportProvider, /*isFromPackageJson*/ true)); host.log?.(`forEachExternalModuleToImportFrom autoImportProvider: ${timestamp() - start}`); } } - function forEachExternalModuleToImportFromInProgram( - program: Program, - host: LanguageServiceHost, - from: SourceFile, - filterByPackageJson: boolean, - cb: (module: Symbol, moduleFile: SourceFile | undefined) => void, - ) { - let filteredCount = 0; - const moduleSpecifierResolutionHost = createModuleSpecifierResolutionHost(program, host); - const packageJson = filterByPackageJson && createAutoImportFilter(from, program, host, moduleSpecifierResolutionHost); - forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), (module, sourceFile) => { - if (sourceFile === undefined) { - if (!packageJson || packageJson.allowsImportingAmbientModule(module)) { - cb(module, sourceFile); - } - else if (packageJson) { - filteredCount++; - } - } - else if (sourceFile && - sourceFile !== from && - isImportableFile(program, from, sourceFile, moduleSpecifierResolutionHost) - ) { - if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile)) { - cb(module, sourceFile); - } - else if (packageJson) { - filteredCount++; - } - } - }); - host.log?.(`forEachExternalModuleToImportFrom: filtered out ${filteredCount} modules by package.json contents`); - } - function forEachExternalModule(checker: TypeChecker, allSourceFiles: readonly SourceFile[], cb: (module: Symbol, sourceFile: SourceFile | undefined) => void) { for (const ambient of checker.getAmbientModules()) { - cb(ambient, /*sourceFile*/ undefined); + if (!stringContains(ambient.name, "*")) { + cb(ambient, /*sourceFile*/ undefined); + } } for (const sourceFile of allSourceFiles) { if (isExternalOrCommonJsModule(sourceFile)) { @@ -939,42 +982,6 @@ namespace ts.codefix { } } - function isImportableFile( - program: Program, - from: SourceFile, - to: SourceFile, - moduleSpecifierResolutionHost: ModuleSpecifierResolutionHost - ) { - const getCanonicalFileName = hostGetCanonicalFileName(moduleSpecifierResolutionHost); - const globalTypingsCache = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation?.(); - return !!moduleSpecifiers.forEachFileNameOfModule( - from.fileName, - to.fileName, - moduleSpecifierResolutionHost, - /*preferSymlinks*/ false, - toPath => { - const toFile = program.getSourceFile(toPath); - // Determine to import using toPath only if toPath is what we were looking at - // or there doesnt exist the file in the program by the symlink - return (toFile === to || !toFile) && - isImportablePath(from.fileName, toPath, getCanonicalFileName, globalTypingsCache); - } - ); - } - - /** - * Don't include something from a `node_modules` that isn't actually reachable by a global import. - * A relative import to node_modules is usually a bad idea. - */ - function isImportablePath(fromPath: string, toPath: string, getCanonicalFileName: GetCanonicalFileName, globalCachePath?: string): boolean { - // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. - const toNodeModules = forEachAncestorDirectory(toPath, ancestor => getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined); - const toNodeModulesParent = toNodeModules && getDirectoryPath(getCanonicalFileName(toNodeModules)); - return toNodeModulesParent === undefined - || startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) - || (!!globalCachePath && startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); - } - export function moduleSymbolToValidIdentifier(moduleSymbol: Symbol, target: ScriptTarget | undefined): string { return moduleSpecifierToValidIdentifier(removeFileExtension(stripQuotes(moduleSymbol.name)), target); } @@ -1005,117 +1012,4 @@ namespace ts.codefix { // Need `|| "_"` to ensure result isn't empty. return !isStringANonContextualKeyword(res) ? res || "_" : `_${res}`; } - - function createAutoImportFilter(fromFile: SourceFile, program: Program, host: LanguageServiceHost, moduleSpecifierResolutionHost = createModuleSpecifierResolutionHost(program, host)) { - const packageJsons = ( - (host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName)) || getPackageJsonsVisibleToFile(fromFile.fileName, host) - ).filter(p => p.parseable); - - let usesNodeCoreModules: boolean | undefined; - return { allowsImportingAmbientModule, allowsImportingSourceFile, allowsImportingSpecifier, moduleSpecifierResolutionHost }; - - function moduleSpecifierIsCoveredByPackageJson(specifier: string) { - const packageName = getNodeModuleRootSpecifier(specifier); - for (const packageJson of packageJsons) { - if (packageJson.has(packageName) || packageJson.has(getTypesPackageName(packageName))) { - return true; - } - } - return false; - } - - function allowsImportingAmbientModule(moduleSymbol: Symbol): boolean { - if (!packageJsons.length) { - return true; - } - - const declaringSourceFile = moduleSymbol.valueDeclaration.getSourceFile(); - const declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName); - if (typeof declaringNodeModuleName === "undefined") { - return true; - } - - const declaredModuleSpecifier = stripQuotes(moduleSymbol.getName()); - if (isAllowedCoreNodeModulesImport(declaredModuleSpecifier)) { - return true; - } - - return moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName) - || moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier); - } - - function allowsImportingSourceFile(sourceFile: SourceFile): boolean { - if (!packageJsons.length) { - return true; - } - - const moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName); - if (!moduleSpecifier) { - return true; - } - - return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); - } - - /** - * Use for a specific module specifier that has already been resolved. - * Use `allowsImportingAmbientModule` or `allowsImportingSourceFile` to resolve - * the best module specifier for a given module _and_ determine if it’s importable. - */ - function allowsImportingSpecifier(moduleSpecifier: string) { - if (!packageJsons.length || isAllowedCoreNodeModulesImport(moduleSpecifier)) { - return true; - } - if (pathIsRelative(moduleSpecifier) || isRootedDiskPath(moduleSpecifier)) { - return true; - } - return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); - } - - function isAllowedCoreNodeModulesImport(moduleSpecifier: string) { - // If we’re in JavaScript, it can be difficult to tell whether the user wants to import - // from Node core modules or not. We can start by seeing if the user is actually using - // any node core modules, as opposed to simply having @types/node accidentally as a - // dependency of a dependency. - if (isSourceFileJS(fromFile) && JsTyping.nodeCoreModules.has(moduleSpecifier)) { - if (usesNodeCoreModules === undefined) { - usesNodeCoreModules = consumesNodeCoreModules(fromFile); - } - if (usesNodeCoreModules) { - return true; - } - } - return false; - } - - function getNodeModulesPackageNameFromFileName(importedFileName: string): string | undefined { - if (!stringContains(importedFileName, "node_modules")) { - return undefined; - } - const specifier = moduleSpecifiers.getNodeModulesPackageName( - host.getCompilationSettings(), - fromFile.path, - importedFileName, - moduleSpecifierResolutionHost, - ); - - if (!specifier) { - return undefined; - } - // Paths here are not node_modules, so we don’t care about them; - // returning anything will trigger a lookup in package.json. - if (!pathIsRelative(specifier) && !isRootedDiskPath(specifier)) { - return getNodeModuleRootSpecifier(specifier); - } - } - - function getNodeModuleRootSpecifier(fullSpecifier: string): string { - const components = getPathComponents(getPackageNameFromTypesPackageName(fullSpecifier)).slice(1); - // Scoped packages - if (startsWith(components[0], "@")) { - return `${components[0]}/${components[1]}`; - } - return components[0]; - } - } } diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index 0ad7980789739..303e86884f9e3 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -128,7 +128,7 @@ namespace ts.codefix { const typeNode = getTypeNodeIfAccessible(type, parent, program, host); if (typeNode) { // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags - const typeTag = factory.createJSDocTypeTag(/*tagName*/ undefined, factory.createJSDocTypeExpression(typeNode), /*comment*/ ""); + const typeTag = factory.createJSDocTypeTag(/*tagName*/ undefined, factory.createJSDocTypeExpression(typeNode), /*comment*/ undefined); addJSDocTags(changes, sourceFile, cast(parent.parent.parent, isExpressionStatement), [typeTag]); } importAdder.writeFixes(changes); @@ -307,7 +307,7 @@ namespace ts.codefix { return; } const typeExpression = factory.createJSDocTypeExpression(typeNode); - const typeTag = isGetAccessorDeclaration(declaration) ? factory.createJSDocReturnTag(/*tagName*/ undefined, typeExpression, "") : factory.createJSDocTypeTag(/*tagName*/ undefined, typeExpression, ""); + const typeTag = isGetAccessorDeclaration(declaration) ? factory.createJSDocReturnTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined) : factory.createJSDocTypeTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined); addJSDocTags(changes, sourceFile, parent, [typeTag]); } else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, getEmitScriptTarget(program.getCompilerOptions()))) { @@ -374,20 +374,20 @@ namespace ts.codefix { } else { const paramTags = map(inferences, ({ name, typeNode, isOptional }) => - factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!isOptional, factory.createJSDocTypeExpression(typeNode), /* isNameFirst */ false, "")); + factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!isOptional, factory.createJSDocTypeExpression(typeNode), /* isNameFirst */ false, /*comment*/ undefined)); addJSDocTags(changes, sourceFile, signature, paramTags); } } export function addJSDocTags(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parent: HasJSDoc, newTags: readonly JSDocTag[]): void { - const comments = mapDefined(parent.jsDoc, j => j.comment); + const comments = flatMap(parent.jsDoc, j => typeof j.comment === "string" ? factory.createJSDocText(j.comment) : j.comment) as (JSDocText | JSDocLink)[]; const oldTags = flatMapToMutable(parent.jsDoc, j => j.tags); const unmergedNewTags = newTags.filter(newTag => !oldTags || !oldTags.some((tag, i) => { const merged = tryMergeJsdocTags(tag, newTag); if (merged) oldTags[i] = merged; return !!merged; })); - const tag = factory.createJSDocComment(comments.join("\n"), factory.createNodeArray([...(oldTags || emptyArray), ...unmergedNewTags])); + const tag = factory.createJSDocComment(factory.createNodeArray(intersperse(comments, factory.createJSDocText("\n"))), factory.createNodeArray([...(oldTags || emptyArray), ...unmergedNewTags])); const jsDocNode = parent.kind === SyntaxKind.ArrowFunction ? getJsDocNodeForArrowFunction(parent) : parent; jsDocNode.jsDoc = parent.jsDoc; jsDocNode.jsDocCache = parent.jsDocCache; @@ -950,7 +950,7 @@ namespace ts.codefix { const props = createMultiMap(); for (const anon of anons) { for (const p of checker.getPropertiesOfType(anon)) { - props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration)); + props.add(p.name, p.valueDeclaration ? checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration) : checker.getAnyType()); } calls.push(...checker.getSignaturesOfType(anon, SignatureKind.Call)); constructs.push(...checker.getSignaturesOfType(anon, SignatureKind.Construct)); @@ -1104,12 +1104,13 @@ namespace ts.codefix { if (!usageParam) { break; } - let genericParamType = checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration); + let genericParamType = genericParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration) : checker.getAnyType(); const elementType = isRest && checker.getElementTypeOfArrayType(genericParamType); if (elementType) { genericParamType = elementType; } - const targetType = (usageParam as SymbolLinks).type || checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration); + const targetType = (usageParam as SymbolLinks).type + || (usageParam.valueDeclaration ? checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration) : checker.getAnyType()); types.push(...inferTypeParameters(genericParamType, targetType, typeParameter)); } const genericReturn = checker.getReturnTypeOfSignature(genericSig); diff --git a/src/services/completions.ts b/src/services/completions.ts index a3c957442cb0f..5ed1608fbcdcb 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -34,6 +34,7 @@ namespace ts.Completions { Export = 1 << 2, Promise = 1 << 3, Nullable = 1 << 4, + ResolvedExport = 1 << 5, SymbolMemberNoExport = SymbolMember, SymbolMemberExport = SymbolMember | Export, @@ -41,13 +42,24 @@ namespace ts.Completions { interface SymbolOriginInfo { kind: SymbolOriginInfoKind; + symbolName?: string; + moduleSymbol?: Symbol; + isDefaultExport?: boolean; + isFromPackageJson?: boolean; + exportName?: string; + fileName?: string; + moduleSpecifier?: string; } interface SymbolOriginInfoExport extends SymbolOriginInfo { - kind: SymbolOriginInfoKind; + symbolName: string; moduleSymbol: Symbol; isDefaultExport: boolean; - isFromPackageJson?: boolean; + exportName: string; + } + + interface SymbolOriginInfoResolvedExport extends SymbolOriginInfoExport { + moduleSpecifier: string; } function originIsThisType(origin: SymbolOriginInfo): boolean { @@ -62,8 +74,16 @@ namespace ts.Completions { return !!(origin && origin.kind & SymbolOriginInfoKind.Export); } + function originIsResolvedExport(origin: SymbolOriginInfo | undefined): origin is SymbolOriginInfoResolvedExport { + return !!(origin && origin.kind === SymbolOriginInfoKind.ResolvedExport); + } + + function originIncludesSymbolName(origin: SymbolOriginInfo | undefined): origin is SymbolOriginInfoExport | SymbolOriginInfoResolvedExport { + return originIsExport(origin) || originIsResolvedExport(origin); + } + function originIsPackageJsonImport(origin: SymbolOriginInfo | undefined): origin is SymbolOriginInfoExport { - return originIsExport(origin) && !!origin.isFromPackageJson; + return (originIsExport(origin) || originIsResolvedExport(origin)) && !!origin.isFromPackageJson; } function originIsPromise(origin: SymbolOriginInfo): boolean { @@ -80,11 +100,12 @@ namespace ts.Completions { } /** - * Map from symbol id -> SymbolOriginInfo. + * Map from symbol index in `symbols` -> SymbolOriginInfo. * Only populated for symbols that come from other modules. */ - type SymbolOriginInfoMap = (SymbolOriginInfo | SymbolOriginInfoExport | undefined)[]; + type SymbolOriginInfoMap = Record; + /** Map from symbol id -> SortText. */ type SymbolSortTextMap = (SortText | undefined)[]; const enum KeywordCompletionFilters { @@ -101,63 +122,6 @@ namespace ts.Completions { const enum GlobalsSearch { Continue, Success, Fail } - export interface AutoImportSuggestion { - symbol: Symbol; - symbolName: string; - skipFilter: boolean; - origin: SymbolOriginInfoExport; - } - export interface ImportSuggestionsForFileCache { - clear(): void; - get(fileName: string, checker: TypeChecker, projectVersion?: string): readonly AutoImportSuggestion[] | undefined; - set(fileName: string, suggestions: readonly AutoImportSuggestion[], projectVersion?: string): void; - isEmpty(): boolean; - } - export function createImportSuggestionsForFileCache(): ImportSuggestionsForFileCache { - let cache: readonly AutoImportSuggestion[] | undefined; - let projectVersion: string | undefined; - let fileName: string | undefined; - return { - isEmpty() { - return !cache; - }, - clear: () => { - cache = undefined; - fileName = undefined; - projectVersion = undefined; - }, - set: (file, suggestions, version) => { - cache = suggestions; - fileName = file; - if (version) { - projectVersion = version; - } - }, - get: (file, checker, version) => { - if (file !== fileName) { - return undefined; - } - if (version) { - return projectVersion === version ? cache : undefined; - } - forEach(cache, suggestion => { - // If the symbol/moduleSymbol was a merged symbol, it will have a new identity - // in the checker, even though the symbols to merge are the same (guaranteed by - // cache invalidation in synchronizeHostData). - if (suggestion.symbol.declarations?.length) { - suggestion.symbol = checker.getMergedSymbol(suggestion.origin.isDefaultExport - ? suggestion.symbol.declarations[0].localSymbol ?? suggestion.symbol.declarations[0].symbol - : suggestion.symbol.declarations[0].symbol); - } - if (suggestion.origin.moduleSymbol.declarations?.length) { - suggestion.origin.moduleSymbol = checker.getMergedSymbol(suggestion.origin.moduleSymbol.declarations[0].symbol); - } - }); - return cache; - }, - }; - } - export function getCompletionsAtPosition( host: LanguageServiceHost, program: Program, @@ -175,6 +139,15 @@ namespace ts.Completions { return undefined; } + if (triggerCharacter === " ") { + // `isValidTrigger` ensures we are at `import |` + if (preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) { + return { isGlobalCompletion: true, isMemberCompletion: false, isNewIdentifierLocation: true, isIncomplete: true, entries: [] }; + } + return undefined; + + } + const stringCompletions = StringCompletions.getStringLiteralCompletions(sourceFile, position, contextToken, typeChecker, compilerOptions, host, log, preferences); if (stringCompletions) { return stringCompletions; @@ -201,6 +174,8 @@ namespace ts.Completions { return jsdocCompletionInfo(JsDoc.getJSDocTagCompletions()); case CompletionDataKind.JsDocParameterName: return jsdocCompletionInfo(JsDoc.getJSDocParameterNameCompletions(completionData.tag)); + case CompletionDataKind.Keywords: + return specificKeywordCompletionInfo(completionData.keywords); default: return Debug.assertNever(completionData); } @@ -210,6 +185,20 @@ namespace ts.Completions { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries }; } + function specificKeywordCompletionInfo(keywords: readonly SyntaxKind[]): CompletionInfo { + return { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: false, + entries: keywords.map(k => ({ + name: tokenToString(k)!, + kind: ScriptElementKind.keyword, + kindModifiers: ScriptElementKindModifier.none, + sortText: SortText.GlobalsOrKeywords, + })), + }; + } + function getOptionalReplacementSpan(location: Node | undefined) { // StringLiteralLike locations are handled separately in stringCompletions.ts return location?.kind === SyntaxKind.Identifier ? createTextSpanFromNode(location) : undefined; @@ -228,26 +217,19 @@ namespace ts.Completions { symbolToOriginInfoMap, recommendedCompletion, isJsxInitializer, + isTypeOnlyLocation, + isJsxIdentifierExpected, + importCompletionNode, insideJsDocTagTypeExpression, symbolToSortTextMap, } = completionData; - if (location && location.parent && isJsxClosingElement(location.parent)) { - // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, - // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. - // For example: - // var x =
" with type any - // And at `
` (with a closing `>`), the completion list will contain "div". - const tagName = location.parent.parent.openingElement.tagName; - const hasClosingAngleBracket = !!findChildOfKind(location.parent, SyntaxKind.GreaterThanToken, sourceFile); - const entry: CompletionEntry = { - name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), - kind: ScriptElementKind.classElement, - kindModifiers: undefined, - sortText: SortText.LocationPriority, - }; - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, optionalReplacementSpan: getOptionalReplacementSpan(location), entries: [entry] }; + // Verify if the file is JSX language variant + if (getLanguageVariant(sourceFile.scriptKind) === LanguageVariant.JSX) { + const completionInfo = getJsxClosingTagCompletion(location, sourceFile); + if (completionInfo) { + return completionInfo; + } } const entries: CompletionEntry[] = []; @@ -264,14 +246,17 @@ namespace ts.Completions { log, completionKind, preferences, + compilerOptions, + isTypeOnlyLocation, propertyAccessToConvert, - completionData.isJsxIdentifierExpected, + isJsxIdentifierExpected, isJsxInitializer, + importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap ); - getJSCompletionEntries(sourceFile, location!.pos, uniqueNames, compilerOptions.target!, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target!, entries); // TODO: GH#18217 } else { if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === KeywordCompletionFilters.None) { @@ -289,9 +274,12 @@ namespace ts.Completions { log, completionKind, preferences, + compilerOptions, + isTypeOnlyLocation, propertyAccessToConvert, - completionData.isJsxIdentifierExpected, + isJsxIdentifierExpected, isJsxInitializer, + importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap @@ -335,6 +323,52 @@ namespace ts.Completions { } } + function getJsxClosingTagCompletion(location: Node | undefined, sourceFile: SourceFile): CompletionInfo | undefined { + // We wanna walk up the tree till we find a JSX closing element + const jsxClosingElement = findAncestor(location, node => { + switch (node.kind) { + case SyntaxKind.JsxClosingElement: + return true; + case SyntaxKind.SlashToken: + case SyntaxKind.GreaterThanToken: + case SyntaxKind.Identifier: + case SyntaxKind.PropertyAccessExpression: + return false; + default: + return "quit"; + } + }) as JsxClosingElement | undefined; + + if (jsxClosingElement) { + // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, + // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. + // For example: + // var x =
" with type any + // And at `
` (with a closing `>`), the completion list will contain "div". + // And at property access expressions ` ` the completion will + // return full closing tag with an optional replacement span + // For example: + // var x = + // var y = + // the completion list at "1" and "2" will contain "MainComponent.Child" with a replacement span of closing tag name + const hasClosingAngleBracket = !!findChildOfKind(jsxClosingElement, SyntaxKind.GreaterThanToken, sourceFile); + const tagName = jsxClosingElement.parent.openingElement.tagName; + const closingTag = tagName.getText(sourceFile); + const fullClosingTag = closingTag + (hasClosingAngleBracket ? "" : ">"); + const replacementSpan = createTextSpanFromNode(jsxClosingElement.tagName); + + const entry: CompletionEntry = { + name: fullClosingTag, + kind: ScriptElementKind.classElement, + kindModifiers: undefined, + sortText: SortText.LocationPriority, + }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, optionalReplacementSpan: replacementSpan, entries: [entry] }; + } + return; + } + function getJSCompletionEntries( sourceFile: SourceFile, position: number, @@ -373,7 +407,7 @@ namespace ts.Completions { symbol: Symbol, sortText: SortText, contextToken: Node | undefined, - location: Node | undefined, + location: Node, sourceFile: SourceFile, typeChecker: TypeChecker, name: string, @@ -382,10 +416,16 @@ namespace ts.Completions { recommendedCompletion: Symbol | undefined, propertyAccessToConvert: PropertyAccessExpression | undefined, isJsxInitializer: IsJsxInitializer | undefined, + importCompletionNode: Node | undefined, + useSemicolons: boolean, + options: CompilerOptions, preferences: UserPreferences, ): CompletionEntry | undefined { let insertText: string | undefined; let replacementSpan = getReplacementSpanForContextToken(contextToken); + let data: CompletionEntryData | undefined; + let isSnippet: true | undefined; + let sourceDisplay; const insertQuestionDot = origin && originIsNullableMember(origin); const useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; @@ -432,10 +472,27 @@ namespace ts.Completions { replacementSpan = createTextSpanFromBounds(propertyAccessToConvert.getStart(sourceFile), propertyAccessToConvert.end); } + if (originIsResolvedExport(origin)) { + Debug.assertIsDefined(importCompletionNode); + ({ insertText, replacementSpan } = getInsertTextAndReplacementSpanForImportCompletion(name, importCompletionNode, origin, useSemicolons, options, preferences)); + sourceDisplay = [textPart(origin.moduleSpecifier)]; + isSnippet = preferences.includeCompletionsWithSnippetText ? true : undefined; + } + if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { return undefined; } + if (originIsExport(origin) || originIsResolvedExport(origin)) { + data = { + exportName: origin.exportName, + fileName: origin.fileName, + ambientModuleName: origin.fileName ? undefined : stripQuotes(origin.moduleSymbol.name), + isPackageJsonImport: origin.isFromPackageJson ? true : undefined, + moduleSpecifier: originIsResolvedExport(origin) ? origin.moduleSpecifier : undefined, + }; + } + // TODO(drosen): Right now we just permit *all* semantic meanings when calling // 'getSymbolKind' which is permissible given that it is backwards compatible; but // really we should consider passing the meaning for the node so that we don't report @@ -446,7 +503,7 @@ namespace ts.Completions { // entries (like JavaScript identifier entries). return { name, - kind: SymbolDisplay.getSymbolKind(typeChecker, symbol, location!), // TODO: GH#18217 + kind: SymbolDisplay.getSymbolKind(typeChecker, symbol, location), // TODO: GH#18217 kindModifiers: SymbolDisplay.getSymbolModifiers(typeChecker, symbol), sortText, source: getSourceFromOrigin(origin), @@ -454,10 +511,33 @@ namespace ts.Completions { isRecommended: isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker) || undefined, insertText, replacementSpan, + sourceDisplay, + isSnippet, isPackageJsonImport: originIsPackageJsonImport(origin) || undefined, + isImportStatementCompletion: originIsResolvedExport(origin) || undefined, + data, }; } + function getInsertTextAndReplacementSpanForImportCompletion(name: string, importCompletionNode: Node, origin: SymbolOriginInfoResolvedExport, useSemicolons: boolean, options: CompilerOptions, preferences: UserPreferences) { + const sourceFile = importCompletionNode.getSourceFile(); + const replacementSpan = createTextSpanFromNode(importCompletionNode, sourceFile); + const quotedModuleSpecifier = quote(sourceFile, preferences, origin.moduleSpecifier); + const exportKind = + origin.isDefaultExport ? ExportKind.Default : + origin.exportName === InternalSymbolName.ExportEquals ? ExportKind.ExportEquals : + ExportKind.Named; + const tabStop = preferences.includeCompletionsWithSnippetText ? "$1" : ""; + const importKind = codefix.getImportKind(sourceFile, exportKind, options); + const suffix = useSemicolons ? ";" : ""; + switch (importKind) { + case ImportKind.CommonJS: return { replacementSpan, insertText: `import ${name}${tabStop} = require(${quotedModuleSpecifier})${suffix}` }; + case ImportKind.Default: return { replacementSpan, insertText: `import ${name}${tabStop} from ${quotedModuleSpecifier}${suffix}` }; + case ImportKind.Namespace: return { replacementSpan, insertText: `import * as ${name}${tabStop} from ${quotedModuleSpecifier}${suffix}` }; + case ImportKind.Named: return { replacementSpan, insertText: `import { ${name}${tabStop} } from ${quotedModuleSpecifier}${suffix}` }; + } + } + function quotePropertyName(sourceFile: SourceFile, preferences: UserPreferences, name: string,): string { if (/^\d+$/.test(name)) { return name; @@ -475,6 +555,9 @@ namespace ts.Completions { if (originIsExport(origin)) { return stripQuotes(origin.moduleSymbol.name); } + if (originIsResolvedExport(origin)) { + return origin.moduleSpecifier; + } if (origin?.kind === SymbolOriginInfoKind.ThisType) { return CompletionSource.ThisProperty; } @@ -484,37 +567,40 @@ namespace ts.Completions { symbols: readonly Symbol[], entries: Push, contextToken: Node | undefined, - location: Node | undefined, + location: Node, sourceFile: SourceFile, typeChecker: TypeChecker, target: ScriptTarget, log: Log, kind: CompletionKind, preferences: UserPreferences, + compilerOptions: CompilerOptions, + isTypeOnlyLocation?: boolean, propertyAccessToConvert?: PropertyAccessExpression, jsxIdentifierExpected?: boolean, isJsxInitializer?: IsJsxInitializer, + importCompletionNode?: Node, recommendedCompletion?: Symbol, symbolToOriginInfoMap?: SymbolOriginInfoMap, symbolToSortTextMap?: SymbolSortTextMap, ): UniqueNameSet { const start = timestamp(); + const variableDeclaration = getVariableDeclaration(location); + const useSemicolons = probablyUsesSemicolons(sourceFile); // Tracks unique names. // Value is set to false for global variables or completions from external module exports, because we can have multiple of those; // true otherwise. Based on the order we add things we will always see locals first, then globals, then module exports. // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. const uniques = new Map(); - for (const symbol of symbols) { - const origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[getSymbolId(symbol)] : undefined; + for (let i = 0; i < symbols.length; i++) { + const symbol = symbols[i]; + const origin = symbolToOriginInfoMap?.[i]; const info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, !!jsxIdentifierExpected); - if (!info) { - continue; - } - const { name, needsConvertPropertyAccess } = info; - if (uniques.get(name)) { + if (!info || uniques.get(info.name) || kind === CompletionKind.Global && symbolToSortTextMap && !shouldIncludeSymbol(symbol, symbolToSortTextMap)) { continue; } + const { name, needsConvertPropertyAccess } = info; const entry = createCompletionEntry( symbol, symbolToSortTextMap && symbolToSortTextMap[getSymbolId(symbol)] || SortText.LocationPriority, @@ -528,6 +614,9 @@ namespace ts.Completions { recommendedCompletion, propertyAccessToConvert, isJsxInitializer, + importCompletionNode, + useSemicolons, + compilerOptions, preferences ); if (!entry) { @@ -535,9 +624,8 @@ namespace ts.Completions { } /** True for locals; false for globals, module exports from other files, `this.` completions. */ - const shouldShadowLaterSymbols = !origin && !(symbol.parent === undefined && !some(symbol.declarations, d => d.getSourceFile() === location!.getSourceFile())); + const shouldShadowLaterSymbols = !origin && !(symbol.parent === undefined && !some(symbol.declarations, d => d.getSourceFile() === location.getSourceFile())); uniques.set(name, shouldShadowLaterSymbols); - entries.push(entry); } @@ -550,8 +638,55 @@ namespace ts.Completions { has: name => uniques.has(name), add: name => uniques.set(name, true), }; + + function shouldIncludeSymbol(symbol: Symbol, symbolToSortTextMap: SymbolSortTextMap): boolean { + if (!isSourceFile(location)) { + // export = /**/ here we want to get all meanings, so any symbol is ok + if (isExportAssignment(location.parent)) { + return true; + } + // Filter out variables from their own initializers + // `const a = /* no 'a' here */` + if (variableDeclaration && symbol.valueDeclaration === variableDeclaration) { + return false; + } + + // External modules can have global export declarations that will be + // available as global keywords in all scopes. But if the external module + // already has an explicit export and user only wants to user explicit + // module imports then the global keywords will be filtered out so auto + // import suggestions will win in the completion + const symbolOrigin = skipAlias(symbol, typeChecker); + // We only want to filter out the global keywords + // Auto Imports are not available for scripts so this conditional is always false + if (!!sourceFile.externalModuleIndicator + && !compilerOptions.allowUmdGlobalAccess + && symbolToSortTextMap[getSymbolId(symbol)] === SortText.GlobalsOrKeywords + && (symbolToSortTextMap[getSymbolId(symbolOrigin)] === SortText.AutoImportSuggestions + || symbolToSortTextMap[getSymbolId(symbolOrigin)] === SortText.LocationPriority)) { + return false; + } + // Continue with origin symbol + symbol = symbolOrigin; + + // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) + if (isInRightSideOfInternalImportEqualsDeclaration(location)) { + return !!(symbol.flags & SymbolFlags.Namespace); + } + + if (isTypeOnlyLocation) { + // It's a type, but you can reach it by namespace.type as well + return symbolCanBeReferencedAtTypeLocation(symbol, typeChecker); + } + } + + // expressions are value space (which includes the value namespaces) + return !!(getCombinedLocalAndExportSymbolFlags(symbol) & SymbolFlags.Value); + } } + + function getLabelCompletionAtPosition(node: BreakOrContinueStatement): CompletionInfo | undefined { const entries = getLabelStatementCompletions(node); if (entries.length) { @@ -588,8 +723,8 @@ namespace ts.Completions { interface SymbolCompletion { type: "symbol"; symbol: Symbol; - location: Node | undefined; - symbolToOriginInfoMap: SymbolOriginInfoMap; + location: Node; + origin: SymbolOriginInfo | SymbolOriginInfoExport | SymbolOriginInfoResolvedExport | undefined; previousToken: Node | undefined; readonly isJsxInitializer: IsJsxInitializer; readonly isTypeOnlyLocation: boolean; @@ -603,6 +738,21 @@ namespace ts.Completions { host: LanguageServiceHost, preferences: UserPreferences, ): SymbolCompletion | { type: "request", request: Request } | { type: "literal", literal: string | number | PseudoBigInt } | { type: "none" } { + if (entryId.data) { + const autoImport = getAutoImportSymbolFromCompletionEntryData(entryId.name, entryId.data, program, host); + if (autoImport) { + return { + type: "symbol", + symbol: autoImport.symbol, + location: getTouchingPropertyName(sourceFile, position), + previousToken: findPrecedingToken(position, sourceFile, /*startNode*/ undefined)!, + isJsxInitializer: false, + isTypeOnlyLocation: false, + origin: autoImport.origin, + }; + } + } + const compilerOptions = program.getCompilerOptions(); const completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId, host); if (!completionData) { @@ -621,11 +771,11 @@ namespace ts.Completions { // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - return firstDefined(symbols, (symbol): SymbolCompletion | undefined => { - const origin = symbolToOriginInfoMap[getSymbolId(symbol)]; + return firstDefined(symbols, (symbol, index): SymbolCompletion | undefined => { + const origin = symbolToOriginInfoMap[index]; const info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target!, origin, completionKind, completionData.isJsxIdentifierExpected); return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source - ? { type: "symbol" as const, symbol, location, symbolToOriginInfoMap, previousToken, isJsxInitializer, isTypeOnlyLocation } + ? { type: "symbol" as const, symbol, location, origin, previousToken, isJsxInitializer, isTypeOnlyLocation } : undefined; }) || { type: "none" }; } @@ -633,6 +783,7 @@ namespace ts.Completions { export interface CompletionEntryIdentifier { name: string; source?: string; + data?: CompletionEntryData; } export function getCompletionEntryDetails( @@ -652,7 +803,7 @@ namespace ts.Completions { const contextToken = findPrecedingToken(position, sourceFile); if (isInString(sourceFile, position, contextToken)) { - return StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken); + return StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken, preferences); } // Compute all the completion symbols again. @@ -667,14 +818,16 @@ namespace ts.Completions { return JsDoc.getJSDocTagCompletionDetails(name); case CompletionDataKind.JsDocParameterName: return JsDoc.getJSDocParameterNameCompletionDetails(name); + case CompletionDataKind.Keywords: + return request.keywords.indexOf(stringToToken(name)!) > -1 ? createSimpleDetails(name, ScriptElementKind.keyword, SymbolDisplayPartKind.keyword) : undefined; default: return Debug.assertNever(request); } } case "symbol": { - const { symbol, location, symbolToOriginInfoMap, previousToken } = symbolCompletion; - const { codeActions, sourceDisplay } = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences); - return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location!, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 + const { symbol, location, origin, previousToken } = symbolCompletion; + const { codeActions, sourceDisplay } = getCompletionEntryCodeActionsAndSourceDisplay(origin, symbol, program, typeChecker, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, entryId.data); + return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } case "literal": { const { literal } = symbolCompletion; @@ -701,7 +854,7 @@ namespace ts.Completions { } export function createCompletionDetails(name: string, kindModifiers: string, kind: ScriptElementKind, displayParts: SymbolDisplayPart[], documentation?: SymbolDisplayPart[], tags?: JSDocTagInfo[], codeActions?: CodeAction[], source?: SymbolDisplayPart[]): CompletionEntryDetails { - return { name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source }; + return { name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source, sourceDisplay: source }; } interface CodeActionsAndSourceDisplay { @@ -709,7 +862,7 @@ namespace ts.Completions { readonly sourceDisplay: SymbolDisplayPart[] | undefined; } function getCompletionEntryCodeActionsAndSourceDisplay( - symbolToOriginInfoMap: SymbolOriginInfoMap, + origin: SymbolOriginInfo | SymbolOriginInfoExport | SymbolOriginInfoResolvedExport | undefined, symbol: Symbol, program: Program, checker: TypeChecker, @@ -720,13 +873,17 @@ namespace ts.Completions { previousToken: Node | undefined, formatContext: formatting.FormatContext, preferences: UserPreferences, + data: CompletionEntryData | undefined, ): CodeActionsAndSourceDisplay { - const symbolOriginInfo = symbolToOriginInfoMap[getSymbolId(symbol)]; - if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { + if (data?.moduleSpecifier) { + return { codeActions: undefined, sourceDisplay: [textPart(data.moduleSpecifier)] }; + } + + if (!origin || !originIsExport(origin)) { return { codeActions: undefined, sourceDisplay: undefined }; } - const { moduleSymbol } = symbolOriginInfo; + const { moduleSymbol } = origin; const exportedSymbol = checker.getMergedSymbol(skipAlias(symbol.exportSymbol || symbol, checker)); const { moduleSpecifier, codeAction } = codefix.getImportCompletionAction( exportedSymbol, @@ -754,7 +911,7 @@ namespace ts.Completions { return completion.type === "symbol" ? completion.symbol : undefined; } - const enum CompletionDataKind { Data, JsDocTagName, JsDocTag, JsDocParameterName } + const enum CompletionDataKind { Data, JsDocTagName, JsDocTag, JsDocParameterName, Keywords } /** true: after the `=` sign but no identifier has been typed yet. Else is the Identifier after the initializer. */ type IsJsxInitializer = boolean | Identifier; interface CompletionData { @@ -765,7 +922,7 @@ namespace ts.Completions { /** Note that the presence of this alone doesn't mean that we need a conversion. Only do that if the completion is not an ordinary identifier. */ readonly propertyAccessToConvert: PropertyAccessExpression | undefined; readonly isNewIdentifierLocation: boolean; - readonly location: Node | undefined; + readonly location: Node; readonly keywordFilters: KeywordCompletionFilters; readonly literals: readonly (string | number | PseudoBigInt)[]; readonly symbolToOriginInfoMap: SymbolOriginInfoMap; @@ -777,8 +934,12 @@ namespace ts.Completions { readonly isTypeOnlyLocation: boolean; /** In JSX tag name and attribute names, identifiers like "my-tag" or "aria-name" is valid identifier. */ readonly isJsxIdentifierExpected: boolean; + readonly importCompletionNode?: Node; } - type Request = { readonly kind: CompletionDataKind.JsDocTagName | CompletionDataKind.JsDocTag } | { readonly kind: CompletionDataKind.JsDocParameterName, tag: JSDocParameterTag }; + type Request = + | { readonly kind: CompletionDataKind.JsDocTagName | CompletionDataKind.JsDocTag } + | { readonly kind: CompletionDataKind.JsDocParameterName, tag: JSDocParameterTag } + | { readonly kind: CompletionDataKind.Keywords, keywords: readonly SyntaxKind[] }; export const enum CompletionKind { ObjectPropertyDeclaration, @@ -841,7 +1002,7 @@ namespace ts.Completions { } function isModuleSymbol(symbol: Symbol): boolean { - return symbol.declarations.some(d => d.kind === SyntaxKind.SourceFile); + return !!symbol.declarations?.some(d => d.kind === SyntaxKind.SourceFile); } function getCompletionData( @@ -850,12 +1011,11 @@ namespace ts.Completions { sourceFile: SourceFile, isUncheckedFile: boolean, position: number, - preferences: Pick, + preferences: UserPreferences, detailsEntryId: CompletionEntryIdentifier | undefined, host: LanguageServiceHost ): CompletionData | Request | undefined { const typeChecker = program.getTypeChecker(); - const compilerOptions = program.getCompilerOptions(); let start = timestamp(); let currentToken = getTokenAtPosition(sourceFile, position); // TODO: GH#15853 @@ -941,7 +1101,7 @@ namespace ts.Completions { // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. - if (contextToken && position <= contextToken.end && (isIdentifierOrPrivateIdentifier(contextToken) || isKeyword(contextToken.kind))) { + if (contextToken && position <= contextToken.end && (isMemberName(contextToken) || isKeyword(contextToken.kind))) { const start = timestamp(); contextToken = findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined)!; // TODO: GH#18217 log("getCompletionData: Get previous token 2: " + (timestamp() - start)); @@ -958,11 +1118,23 @@ namespace ts.Completions { let isStartingCloseTag = false; let isJsxInitializer: IsJsxInitializer = false; let isJsxIdentifierExpected = false; - + let importCompletionNode: Node | undefined; let location = getTouchingPropertyName(sourceFile, position); + if (contextToken) { + const importCompletionCandidate = getImportCompletionNode(contextToken); + if (importCompletionCandidate === SyntaxKind.FromKeyword) { + return { kind: CompletionDataKind.Keywords, keywords: [SyntaxKind.FromKeyword] }; + } + // Import statement completions use `insertText`, and also require the `data` property of `CompletionEntryIdentifier` + // added in TypeScript 4.3 to be sent back from the client during `getCompletionEntryDetails`. Since this feature + // is not backward compatible with older clients, the language service defaults to disabling it, allowing newer clients + // to opt in with the `includeCompletionsForImportStatements` user preference. + if (importCompletionCandidate && preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) { + importCompletionNode = importCompletionCandidate; + } // Bail out if this is a known invalid completion location - if (isCompletionListBlocker(contextToken)) { + if (!importCompletionNode && isCompletionListBlocker(contextToken)) { log("Returning an empty list because completion was requested in an invalid position."); return undefined; } @@ -1001,7 +1173,7 @@ namespace ts.Completions { return undefined; } } - else if (sourceFile.languageVariant === LanguageVariant.JSX) { + else if (!importCompletionNode && sourceFile.languageVariant === LanguageVariant.JSX) { // // If the tagname is a property access expression, we will then walk up to the top most of property access expression. // Then, try to get a JSX container and its associated attributes type. @@ -1093,8 +1265,11 @@ namespace ts.Completions { let symbols: Symbol[] = []; const symbolToOriginInfoMap: SymbolOriginInfoMap = []; const symbolToSortTextMap: SymbolSortTextMap = []; - const importSuggestionsCache = host.getImportSuggestionsCache && host.getImportSuggestionsCache(); + const seenPropertySymbols = new Map(); const isTypeOnly = isTypeOnlyCompletion(); + const getModuleSpecifierResolutionHost = memoizeOne((isFromPackageJson: boolean) => { + return createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider!()! : program, host); + }); if (isRightOfDot || isRightOfQuestionDot) { getTypeScriptMemberSymbols(); @@ -1104,7 +1279,7 @@ namespace ts.Completions { Debug.assertEachIsDefined(tagSymbols, "getJsxIntrinsicTagNames() should all be defined"); tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); - completionKind = CompletionKind.MemberLike; + completionKind = CompletionKind.Global; keywordFilters = KeywordCompletionFilters.None; } else if (isStartingCloseTag) { @@ -1113,7 +1288,7 @@ namespace ts.Completions { if (tagSymbol) { symbols = [tagSymbol]; } - completionKind = CompletionKind.MemberLike; + completionKind = CompletionKind.Global; keywordFilters = KeywordCompletionFilters.None; } else { @@ -1148,6 +1323,7 @@ namespace ts.Completions { symbolToSortTextMap, isTypeOnlyLocation: isTypeOnly, isJsxIdentifierExpected, + importCompletionNode, }; type JSDocTagWithTypeExpression = JSDocParameterTag | JSDocPropertyTag | JSDocReturnTag | JSDocTypeTag | JSDocTypedefTag; @@ -1187,11 +1363,11 @@ namespace ts.Completions { const exportedSymbols = typeChecker.getExportsOfModule(symbol); Debug.assertEachIsDefined(exportedSymbols, "getExportsOfModule() should all be defined"); const isValidValueAccess = (symbol: Symbol) => typeChecker.isValidPropertyAccess(isImportType ? node : (node.parent), symbol.name); - const isValidTypeAccess = (symbol: Symbol) => symbolCanBeReferencedAtTypeLocation(symbol); + const isValidTypeAccess = (symbol: Symbol) => symbolCanBeReferencedAtTypeLocation(symbol, typeChecker); const isValidAccess: (symbol: Symbol) => boolean = isNamespaceName // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion. - ? symbol => !!(symbol.flags & SymbolFlags.Namespace) && !symbol.declarations.every(d => d.parent === node.parent) + ? symbol => !!(symbol.flags & SymbolFlags.Namespace) && !symbol.declarations?.every(d => d.parent === node.parent) : isRhsOfImportDeclaration ? // Any kind is allowed when dotting off namespace in internal import equals declaration symbol => isValidTypeAccess(symbol) || isValidValueAccess(symbol) : @@ -1300,13 +1476,24 @@ namespace ts.Completions { const nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName); // If this is nested like for `namespace N { export const sym = Symbol(); }`, we'll add the completion for `N`. const firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker); - if (firstAccessibleSymbol && !symbolToOriginInfoMap[getSymbolId(firstAccessibleSymbol)]) { + if (firstAccessibleSymbol && addToSeen(seenPropertySymbols, getSymbolId(firstAccessibleSymbol))) { + const index = symbols.length; symbols.push(firstAccessibleSymbol); const moduleSymbol = firstAccessibleSymbol.parent; - symbolToOriginInfoMap[getSymbolId(firstAccessibleSymbol)] = - !moduleSymbol || !isExternalModuleSymbol(moduleSymbol) - ? { kind: getNullableSymbolOriginInfoKind(SymbolOriginInfoKind.SymbolMemberNoExport) } - : { kind: getNullableSymbolOriginInfoKind(SymbolOriginInfoKind.SymbolMemberExport), moduleSymbol, isDefaultExport: false }; + if (!moduleSymbol || !isExternalModuleSymbol(moduleSymbol)) { + symbolToOriginInfoMap[index] = { kind: getNullableSymbolOriginInfoKind(SymbolOriginInfoKind.SymbolMemberNoExport) }; + } + else { + const origin: SymbolOriginInfoExport = { + kind: getNullableSymbolOriginInfoKind(SymbolOriginInfoKind.SymbolMemberExport), + moduleSymbol, + isDefaultExport: false, + symbolName: firstAccessibleSymbol.name, + exportName: firstAccessibleSymbol.name, + fileName: isExternalModuleNameRelative(stripQuotes(moduleSymbol.name)) ? cast(moduleSymbol.valueDeclaration, isSourceFile).fileName : undefined, + }; + symbolToOriginInfoMap[index] = origin; + } } else if (preferences.includeCompletionsWithInsertText) { addSymbolOriginInfo(symbol); @@ -1328,11 +1515,11 @@ namespace ts.Completions { function addSymbolOriginInfo(symbol: Symbol) { if (preferences.includeCompletionsWithInsertText) { - if (insertAwait && !symbolToOriginInfoMap[getSymbolId(symbol)]) { - symbolToOriginInfoMap[getSymbolId(symbol)] = { kind: getNullableSymbolOriginInfoKind(SymbolOriginInfoKind.Promise) }; + if (insertAwait && addToSeen(seenPropertySymbols, getSymbolId(symbol))) { + symbolToOriginInfoMap[symbols.length] = { kind: getNullableSymbolOriginInfoKind(SymbolOriginInfoKind.Promise) }; } else if (insertQuestionDot) { - symbolToOriginInfoMap[getSymbolId(symbol)] = { kind: SymbolOriginInfoKind.Nullable }; + symbolToOriginInfoMap[symbols.length] = { kind: SymbolOriginInfoKind.Nullable }; } } } @@ -1348,7 +1535,9 @@ namespace ts.Completions { } function tryGetGlobalSymbols(): boolean { - const result: GlobalsSearch = tryGetObjectLikeCompletionSymbols() + const result: GlobalsSearch = tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() + || tryGetObjectLikeCompletionSymbols() + || tryGetImportCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() || tryGetLocalNamedExportCompletionSymbols() || tryGetConstructorCompletion() @@ -1382,6 +1571,12 @@ namespace ts.Completions { return GlobalsSearch.Success; } + function tryGetImportCompletionSymbols(): GlobalsSearch { + if (!importCompletionNode) return GlobalsSearch.Continue; + collectAutoImports(/*resolveModuleSpecifiers*/ true); + return GlobalsSearch.Success; + } + function getGlobalCompletions(): void { keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? KeywordCompletionFilters.FunctionLikeBodyKeywords : KeywordCompletionFilters.All; @@ -1440,39 +1635,23 @@ namespace ts.Completions { const thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { for (const symbol of getPropertiesForCompletion(thisType, typeChecker)) { - symbolToOriginInfoMap[getSymbolId(symbol)] = { kind: SymbolOriginInfoKind.ThisType }; + symbolToOriginInfoMap[symbols.length] = { kind: SymbolOriginInfoKind.ThisType }; symbols.push(symbol); symbolToSortTextMap[getSymbolId(symbol)] = SortText.SuggestedClassMembers; } } } - - if (shouldOfferImportCompletions()) { - const lowerCaseTokenText = previousToken && isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; - const autoImportSuggestions = getSymbolsFromOtherSourceFileExports(program.getCompilerOptions().target!, host); - if (!detailsEntryId && importSuggestionsCache) { - importSuggestionsCache.set(sourceFile.fileName, autoImportSuggestions, host.getProjectVersion && host.getProjectVersion()); - } - autoImportSuggestions.forEach(({ symbol, symbolName, skipFilter, origin }) => { - if (detailsEntryId) { - if (detailsEntryId.source && stripQuotes(origin.moduleSymbol.name) !== detailsEntryId.source) { - return; - } - } - else if (!skipFilter && !stringContainsCharactersInOrder(symbolName.toLowerCase(), lowerCaseTokenText)) { - return; - } - - const symbolId = getSymbolId(symbol); - symbols.push(symbol); - symbolToOriginInfoMap[symbolId] = origin; - symbolToSortTextMap[symbolId] = SortText.AutoImportSuggestions; - }); + collectAutoImports(/*resolveModuleSpecifier*/ false); + if (isTypeOnly) { + keywordFilters = contextToken && isAssertionExpression(contextToken.parent) + ? KeywordCompletionFilters.TypeAssertionKeywords + : KeywordCompletionFilters.TypeKeywords; } - filterGlobalCompletion(symbols); } function shouldOfferImportCompletions(): boolean { + // If already typing an import statement, provide completions for it. + if (importCompletionNode) return true; // If current completion is for non-contextual Object literal shortahands, ignore auto-import symbols if (isNonContextualObjectLiteral) return false; // If not already a module, must have modules enabled. @@ -1497,75 +1676,6 @@ namespace ts.Completions { } } - function filterGlobalCompletion(symbols: Symbol[]): void { - const isTypeOnly = isTypeOnlyCompletion(); - if (isTypeOnly) { - keywordFilters = contextToken && isAssertionExpression(contextToken.parent) - ? KeywordCompletionFilters.TypeAssertionKeywords - : KeywordCompletionFilters.TypeKeywords; - } - - const variableDeclaration = getVariableDeclaration(location); - - filterMutate(symbols, symbol => { - if (!isSourceFile(location)) { - // export = /**/ here we want to get all meanings, so any symbol is ok - if (isExportAssignment(location.parent)) { - return true; - } - - // Filter out variables from their own initializers - // `const a = /* no 'a' here */` - if (variableDeclaration && symbol.valueDeclaration === variableDeclaration) { - return false; - } - - // External modules can have global export declarations that will be - // available as global keywords in all scopes. But if the external module - // already has an explicit export and user only wants to user explicit - // module imports then the global keywords will be filtered out so auto - // import suggestions will win in the completion - const symbolOrigin = skipAlias(symbol, typeChecker); - // We only want to filter out the global keywords - // Auto Imports are not available for scripts so this conditional is always false - if (!!sourceFile.externalModuleIndicator - && !compilerOptions.allowUmdGlobalAccess - && symbolToSortTextMap[getSymbolId(symbol)] === SortText.GlobalsOrKeywords - && symbolToSortTextMap[getSymbolId(symbolOrigin)] === SortText.AutoImportSuggestions) { - return false; - } - // Continue with origin symbol - symbol = symbolOrigin; - - // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) - if (isInRightSideOfInternalImportEqualsDeclaration(location)) { - return !!(symbol.flags & SymbolFlags.Namespace); - } - - if (isTypeOnly) { - // It's a type, but you can reach it by namespace.type as well - return symbolCanBeReferencedAtTypeLocation(symbol); - } - } - - // expressions are value space (which includes the value namespaces) - return !!(getCombinedLocalAndExportSymbolFlags(symbol) & SymbolFlags.Value); - }); - } - - function getVariableDeclaration(property: Node): VariableDeclaration | undefined { - const variableDeclaration = findAncestor(property, node => - isFunctionBlock(node) || isArrowFunctionBody(node) || isBindingPattern(node) - ? "quit" - : isVariableDeclaration(node)); - - return variableDeclaration as VariableDeclaration | undefined; - } - - function isArrowFunctionBody(node: Node) { - return node.parent && isArrowFunction(node.parent) && node.parent.body === node; - }; - function isTypeOnlyCompletion(): boolean { return insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && @@ -1576,8 +1686,9 @@ namespace ts.Completions { function isContextTokenValueLocation(contextToken: Node) { return contextToken && - contextToken.kind === SyntaxKind.TypeOfKeyword && - (contextToken.parent.kind === SyntaxKind.TypeQuery || isTypeOfExpression(contextToken.parent)); + ((contextToken.kind === SyntaxKind.TypeOfKeyword && + (contextToken.parent.kind === SyntaxKind.TypeQuery || isTypeOfExpression(contextToken.parent))) || + (contextToken.kind === SyntaxKind.AssertsKeyword && contextToken.parent.kind === SyntaxKind.TypePredicate)); } function isContextTokenTypeLocation(contextToken: Node): boolean { @@ -1608,173 +1719,84 @@ namespace ts.Completions { return false; } - /** True if symbol is a type or a module containing at least one type. */ - function symbolCanBeReferencedAtTypeLocation(symbol: Symbol, seenModules = new Map()): boolean { - const sym = skipAlias(symbol.exportSymbol || symbol, typeChecker); - return !!(sym.flags & SymbolFlags.Type) || - !!(sym.flags & SymbolFlags.Module) && - addToSeen(seenModules, getSymbolId(sym)) && - typeChecker.getExportsOfModule(sym).some(e => symbolCanBeReferencedAtTypeLocation(e, seenModules)); - } - - /** - * Gathers symbols that can be imported from other files, de-duplicating along the way. Symbols can be "duplicates" - * if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but - * it’s just an alias to the first, and both have the same name, so we generally want to filter those aliases out, - * if and only if the the first can be imported (it may be excluded due to package.json filtering in - * `codefix.forEachExternalModuleToImportFrom`). - * - * Example. Imagine a chain of node_modules re-exporting one original symbol: - * - * ```js - * node_modules/x/index.js node_modules/y/index.js node_modules/z/index.js - * +-----------------------+ +--------------------------+ +--------------------------+ - * | | | | | | - * | export const foo = 0; | <--- | export { foo } from 'x'; | <--- | export { foo } from 'y'; | - * | | | | | | - * +-----------------------+ +--------------------------+ +--------------------------+ - * ``` - * - * Also imagine three buckets, which we’ll reference soon: - * - * ```md - * | | | | | | - * | **Bucket A** | | **Bucket B** | | **Bucket C** | - * | Symbols to | | Aliases to symbols | | Symbols to return | - * | definitely | | in Buckets A or C | | if nothing better | - * | return | | (don’t return these) | | comes along | - * |__________________| |______________________| |___________________| - * ``` - * - * We _probably_ want to show `foo` from 'x', but not from 'y' or 'z'. However, if 'x' is not in a package.json, it - * will not appear in a `forEachExternalModuleToImportFrom` iteration. Furthermore, the order of iterations is not - * guaranteed, as it is host-dependent. Therefore, when presented with the symbol `foo` from module 'y' alone, we - * may not be sure whether or not it should go in the list. So, we’ll take the following steps: - * - * 1. Resolve alias `foo` from 'y' to the export declaration in 'x', get the symbol there, and see if that symbol is - * already in Bucket A (symbols we already know will be returned). If it is, put `foo` from 'y' in Bucket B - * (symbols that are aliases to symbols in Bucket A). If it’s not, put it in Bucket C. - * 2. Next, imagine we see `foo` from module 'z'. Again, we resolve the alias to the nearest export, which is in 'y'. - * At this point, if that nearest export from 'y' is in _any_ of the three buckets, we know the symbol in 'z' - * should never be returned in the final list, so put it in Bucket B. - * 3. Next, imagine we see `foo` from module 'x', the original. Syntactically, it doesn’t look like a re-export, so - * we can just check Bucket C to see if we put any aliases to the original in there. If they exist, throw them out. - * Put this symbol in Bucket A. - * 4. After we’ve iterated through every symbol of every module, any symbol left in Bucket C means that step 3 didn’t - * occur for that symbol---that is, the original symbol is not in Bucket A, so we should include the alias. Move - * everything from Bucket C to Bucket A. - */ - function getSymbolsFromOtherSourceFileExports(target: ScriptTarget, host: LanguageServiceHost): readonly AutoImportSuggestion[] { - const cached = importSuggestionsCache && importSuggestionsCache.get( - sourceFile.fileName, - typeChecker, - detailsEntryId && host.getProjectVersion ? host.getProjectVersion() : undefined); - - if (cached) { - log("getSymbolsFromOtherSourceFileExports: Using cached list"); - return cached; - } - - const startTime = timestamp(); - log(`getSymbolsFromOtherSourceFileExports: Recomputing list${detailsEntryId ? " for details entry" : ""}`); - const seenResolvedModules = new Map(); - const seenExports = new Map(); - /** Bucket B */ - const aliasesToAlreadyIncludedSymbols = new Map(); - /** Bucket C */ - const aliasesToReturnIfOriginalsAreMissing = new Map(); - /** Bucket A */ - const results: AutoImportSuggestion[] = []; - /** Ids present in `results` for faster lookup */ - const resultSymbolIds = new Map(); - - codefix.forEachExternalModuleToImportFrom(program, host, sourceFile, !detailsEntryId, /*useAutoImportProvider*/ true, (moduleSymbol, _, program, isFromPackageJson) => { - // Perf -- ignore other modules if this is a request for details - if (detailsEntryId && detailsEntryId.source && stripQuotes(moduleSymbol.name) !== detailsEntryId.source) { - return; - } - - const typeChecker = program.getTypeChecker(); - const resolvedModuleSymbol = typeChecker.resolveExternalModuleSymbol(moduleSymbol); - // resolvedModuleSymbol may be a namespace. A namespace may be `export =` by multiple module declarations, but only keep the first one. - if (!addToSeen(seenResolvedModules, getSymbolId(resolvedModuleSymbol))) { - return; - } - - // Don't add another completion for `export =` of a symbol that's already global. - // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. - if (resolvedModuleSymbol !== moduleSymbol && every(resolvedModuleSymbol.declarations, isNonGlobalDeclaration)) { - pushSymbol(resolvedModuleSymbol, moduleSymbol, isFromPackageJson, /*skipFilter*/ true); - } - - for (const symbol of typeChecker.getExportsAndPropertiesOfModule(moduleSymbol)) { - const symbolId = getSymbolId(symbol).toString(); - // `getExportsAndPropertiesOfModule` can include duplicates - if (!addToSeen(seenExports, symbolId)) { - continue; - } - // If this is `export { _break as break };` (a keyword) -- skip this and prefer the keyword completion. - if (some(symbol.declarations, d => isExportSpecifier(d) && !!d.propertyName && isIdentifierANonContextualKeyword(d.name))) { - continue; - } - - // If `symbol.parent !== moduleSymbol`, this is an `export * from "foo"` re-export. Those don't create new symbols. - const isExportStarFromReExport = typeChecker.getMergedSymbol(symbol.parent!) !== resolvedModuleSymbol; - // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). - if (isExportStarFromReExport || some(symbol.declarations, d => isExportSpecifier(d) && !d.propertyName && !!d.parent.parent.moduleSpecifier)) { - // Walk the export chain back one module (step 1 or 2 in diagrammed example). - // Or, in the case of `export * from "foo"`, `symbol` already points to the original export, so just use that. - const nearestExportSymbol = isExportStarFromReExport ? symbol : getNearestExportSymbol(symbol); - if (!nearestExportSymbol) continue; - const nearestExportSymbolId = getSymbolId(nearestExportSymbol).toString(); - const symbolHasBeenSeen = resultSymbolIds.has(nearestExportSymbolId) || aliasesToAlreadyIncludedSymbols.has(nearestExportSymbolId); - if (!symbolHasBeenSeen) { - aliasesToReturnIfOriginalsAreMissing.set(nearestExportSymbolId, { alias: symbol, moduleSymbol, isFromPackageJson }); - aliasesToAlreadyIncludedSymbols.set(symbolId, true); - } - else { - // Perf - we know this symbol is an alias to one that’s already covered in `symbols`, so store it here - // in case another symbol re-exports this one; that way we can short-circuit as soon as we see this symbol id. - addToSeen(aliasesToAlreadyIncludedSymbols, symbolId); - } - } - else { - // This is not a re-export, so see if we have any aliases pending and remove them (step 3 in diagrammed example) - aliasesToReturnIfOriginalsAreMissing.delete(symbolId); - pushSymbol(symbol, moduleSymbol, isFromPackageJson, /*skipFilter*/ false); - } + /** Mutates `symbols`, `symbolToOriginInfoMap`, and `symbolToSortTextMap` */ + function collectAutoImports(resolveModuleSpecifiers: boolean) { + if (!shouldOfferImportCompletions()) return; + Debug.assert(!detailsEntryId?.data); + const start = timestamp(); + const moduleSpecifierCache = host.getModuleSpecifierCache?.(); + host.log?.(`collectAutoImports: starting, ${resolveModuleSpecifiers ? "" : "not "}resolving module specifiers`); + if (moduleSpecifierCache) { + host.log?.(`collectAutoImports: module specifier cache size: ${moduleSpecifierCache.count()}`); + } + const lowerCaseTokenText = previousToken && isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; + const exportInfo = codefix.getSymbolToExportInfoMap(sourceFile, host, program); + const packageJsonAutoImportProvider = host.getPackageJsonAutoImportProvider?.(); + const packageJsonFilter = detailsEntryId ? undefined : createPackageJsonImportFilter(sourceFile, host); + exportInfo.forEach((info, key) => { + const symbolName = key.substring(0, key.indexOf("|")); + if (!detailsEntryId && isStringANonContextualKeyword(symbolName)) return; + const isCompletionDetailsMatch = detailsEntryId && some(info, i => detailsEntryId.source === stripQuotes(i.moduleSymbol.name)); + if (isCompletionDetailsMatch || isNameMatch(symbolName)) { + // If we don't need to resolve module specifiers, we can use any re-export that is importable at all + // (We need to ensure that at least one is importable to show a completion.) + const { moduleSpecifier, exportInfo } = resolveModuleSpecifiers + ? codefix.getModuleSpecifierForBestExportInfo(info, sourceFile, program, host, preferences) + : { moduleSpecifier: undefined, exportInfo: find(info, isImportableExportInfo) }; + if (!exportInfo) return; + const moduleFile = tryCast(exportInfo.moduleSymbol.valueDeclaration, isSourceFile); + const isDefaultExport = exportInfo.exportKind === ExportKind.Default; + const symbol = isDefaultExport && getLocalSymbolForExportDefault(exportInfo.symbol) || exportInfo.symbol; + pushAutoImportSymbol(symbol, { + kind: resolveModuleSpecifiers ? SymbolOriginInfoKind.ResolvedExport : SymbolOriginInfoKind.Export, + moduleSpecifier, + symbolName, + exportName: exportInfo.exportKind === ExportKind.ExportEquals ? InternalSymbolName.ExportEquals : exportInfo.symbol.name, + fileName: moduleFile?.fileName, + isDefaultExport, + moduleSymbol: exportInfo.moduleSymbol, + isFromPackageJson: exportInfo.isFromPackageJson, + }); } }); + host.log?.(`collectAutoImports: done in ${timestamp() - start} ms`); - // By this point, any potential duplicates that were actually duplicates have been - // removed, so the rest need to be added. (Step 4 in diagrammed example) - aliasesToReturnIfOriginalsAreMissing.forEach(({ alias, moduleSymbol, isFromPackageJson }) => pushSymbol(alias, moduleSymbol, isFromPackageJson, /*skipFilter*/ false)); - log(`getSymbolsFromOtherSourceFileExports: ${timestamp() - startTime}`); - return results; - - function pushSymbol(symbol: Symbol, moduleSymbol: Symbol, isFromPackageJson: boolean, skipFilter: boolean) { - const isDefaultExport = symbol.escapedName === InternalSymbolName.Default; - if (isDefaultExport) { - symbol = getLocalSymbolForExportDefault(symbol) || symbol; - } - if (typeChecker.isUndefinedSymbol(symbol)) { - return; - } - addToSeen(resultSymbolIds, getSymbolId(symbol)); - const origin: SymbolOriginInfoExport = { kind: SymbolOriginInfoKind.Export, moduleSymbol, isDefaultExport, isFromPackageJson }; - results.push({ - symbol, - symbolName: getNameForExportedSymbol(symbol, target), - origin, - skipFilter, - }); + function isNameMatch(symbolName: string) { + const lowerCaseSymbolName = symbolName.toLowerCase(); + if (resolveModuleSpecifiers && lowerCaseTokenText) { + // Use a more restrictive filter if resolving module specifiers since resolving module specifiers is expensive. + return lowerCaseTokenText[0] === lowerCaseSymbolName[0] && stringContainsCharactersInOrder(lowerCaseSymbolName, lowerCaseTokenText); + } + return stringContainsCharactersInOrder(lowerCaseSymbolName, lowerCaseTokenText); + } + + function isImportableExportInfo(info: SymbolExportInfo) { + const moduleFile = tryCast(info.moduleSymbol.valueDeclaration, isSourceFile); + if (!moduleFile) { + return packageJsonFilter + ? packageJsonFilter.allowsImportingAmbientModule(info.moduleSymbol, getModuleSpecifierResolutionHost(info.isFromPackageJson)) + : true; + } + return isImportableFile( + info.isFromPackageJson ? packageJsonAutoImportProvider! : program, + sourceFile, + moduleFile, + packageJsonFilter, + getModuleSpecifierResolutionHost(info.isFromPackageJson), + moduleSpecifierCache); } } - function getNearestExportSymbol(fromSymbol: Symbol) { - return findAlias(typeChecker, fromSymbol, alias => { - return some(alias.declarations, d => isExportSpecifier(d) || !!d.localSymbol); - }); + + function pushAutoImportSymbol(symbol: Symbol, origin: SymbolOriginInfoResolvedExport | SymbolOriginInfoExport) { + const symbolId = getSymbolId(symbol); + if (symbolToSortTextMap[symbolId] === SortText.GlobalsOrKeywords) { + // If an auto-importable symbol is available as a global, don't add the auto import + return; + } + symbolToOriginInfoMap[symbols.length] = origin; + symbolToSortTextMap[symbolId] = importCompletionNode ? SortText.LocationPriority : SortText.AutoImportSuggestions; + symbols.push(symbol); } /** @@ -1788,7 +1810,8 @@ namespace ts.Completions { } let characterIndex = 0; - for (let strIndex = 0; strIndex < str.length; strIndex++) { + const len = str.length; + for (let strIndex = 0; strIndex < len; strIndex++) { if (str.charCodeAt(strIndex) === characters.charCodeAt(characterIndex)) { characterIndex++; if (characterIndex === characters.length) { @@ -1916,6 +1939,32 @@ namespace ts.Completions { position === contextToken.end && (!!contextToken.isUnterminated || isRegularExpressionLiteral(contextToken))); } + function tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols(): GlobalsSearch | undefined { + const typeLiteralNode = tryGetTypeLiteralNode(contextToken); + if (!typeLiteralNode) return GlobalsSearch.Continue; + + const intersectionTypeNode = isIntersectionTypeNode(typeLiteralNode.parent) ? typeLiteralNode.parent : undefined; + const containerTypeNode = intersectionTypeNode || typeLiteralNode; + + const containerExpectedType = getConstraintOfTypeArgumentProperty(containerTypeNode, typeChecker); + if (!containerExpectedType) return GlobalsSearch.Continue; + + const containerActualType = typeChecker.getTypeFromTypeNode(containerTypeNode); + + const members = getPropertiesForCompletion(containerExpectedType, typeChecker); + const existingMembers = getPropertiesForCompletion(containerActualType, typeChecker); + + const existingMemberEscapedNames: Set<__String> = new Set(); + existingMembers.forEach(s => existingMemberEscapedNames.add(s.escapedName)); + + symbols = filter(members, s => !existingMemberEscapedNames.has(s.escapedName)); + + completionKind = CompletionKind.ObjectPropertyDeclaration; + isNewIdentifierLocation = true; + + return GlobalsSearch.Success; + } + /** * Aggregates relevant symbols for completion in object literals and object binding patterns. * Relevant symbols are stored in the captured 'symbols' variable. @@ -2096,13 +2145,17 @@ namespace ts.Completions { case "static": classElementModifierFlags = classElementModifierFlags | ModifierFlags.Static; break; + case "override": + classElementModifierFlags = classElementModifierFlags | ModifierFlags.Override; + break; } } // No member list for private methods if (!(classElementModifierFlags & ModifierFlags.Private)) { // List of property symbols of base type that are not private and already implemented - const baseSymbols = flatMap(getAllSuperTypeNodes(decl), baseTypeNode => { + const baseTypeNodes = isClassLike(decl) && classElementModifierFlags & ModifierFlags.Override ? singleElementArray(getEffectiveBaseTypeNode(decl)) : getAllSuperTypeNodes(decl); + const baseSymbols = flatMap(baseTypeNodes, baseTypeNode => { const type = typeChecker.getTypeAtLocation(baseTypeNode); return classElementModifierFlags & ModifierFlags.Static ? type?.symbol && typeChecker.getPropertiesOfType(typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl)) : @@ -2332,7 +2385,7 @@ namespace ts.Completions { return isFunctionLike(contextToken.parent) && !isMethodDeclaration(contextToken.parent); } - // If the previous token is keyword correspoding to class member completion keyword + // If the previous token is keyword corresponding to class member completion keyword // there will be completion available here if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { return false; @@ -2370,6 +2423,33 @@ namespace ts.Completions { return isPropertyDeclaration(contextToken.parent); } + // If we are inside a class declaration, and `constructor` is totally not present, + // but we request a completion manually at a whitespace... + const ancestorClassLike = findAncestor(contextToken.parent, isClassLike); + if (ancestorClassLike && contextToken === previousToken && isPreviousPropertyDeclarationTerminated(contextToken, position)) { + return false; // Don't block completions. + } + + const ancestorPropertyDeclaraion = getAncestor(contextToken.parent, SyntaxKind.PropertyDeclaration); + // If we are inside a class declaration and typing `constructor` after property declaration... + if (ancestorPropertyDeclaraion + && contextToken !== previousToken + && isClassLike(previousToken.parent.parent) + // And the cursor is at the token... + && position <= previousToken.end) { + // If we are sure that the previous property declaration is terminated according to newline or semicolon... + if (isPreviousPropertyDeclarationTerminated(contextToken, previousToken.end)) { + return false; // Don't block completions. + } + else if (contextToken.kind !== SyntaxKind.EqualsToken + // Should not block: `class C { blah = c/**/ }` + // But should block: `class C { blah = somewhat c/**/ }` and `class C { blah: SomeType c/**/ }` + && (isInitializedProperty(ancestorPropertyDeclaraion as PropertyDeclaration) + || hasType(ancestorPropertyDeclaraion))) { + return true; + } + } + return isDeclarationName(contextToken) && !isShorthandPropertyAssignment(contextToken.parent) && !isJsxAttribute(contextToken.parent) @@ -2378,6 +2458,12 @@ namespace ts.Completions { && !(isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } + function isPreviousPropertyDeclarationTerminated(contextToken: Node, position: number) { + return contextToken.kind !== SyntaxKind.EqualsToken && + (contextToken.kind === SyntaxKind.SemicolonToken + || !positionsAreOnSameLine(contextToken.end, position, sourceFile)); + } + function isFunctionLikeButNotConstructor(kind: SyntaxKind) { return isFunctionLikeKind(kind) && kind !== SyntaxKind.Constructor; } @@ -2530,7 +2616,7 @@ namespace ts.Completions { !existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && !(getDeclarationModifierFlagsFromSymbol(propertySymbol) & ModifierFlags.Private) && - !(propertySymbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(propertySymbol.valueDeclaration))); + !(propertySymbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(propertySymbol.valueDeclaration))); } /** @@ -2567,6 +2653,34 @@ namespace ts.Completions { } } + function getAutoImportSymbolFromCompletionEntryData(name: string, data: CompletionEntryData, program: Program, host: LanguageServiceHost): { symbol: Symbol, origin: SymbolOriginInfoExport } | undefined { + const containingProgram = data.isPackageJsonImport ? host.getPackageJsonAutoImportProvider!()! : program; + const checker = containingProgram.getTypeChecker(); + const moduleSymbol = + data.ambientModuleName ? checker.tryFindAmbientModule(data.ambientModuleName) : + data.fileName ? checker.getMergedSymbol(Debug.checkDefined(containingProgram.getSourceFile(data.fileName)).symbol) : + undefined; + + if (!moduleSymbol) return undefined; + let symbol = data.exportName === InternalSymbolName.ExportEquals + ? checker.resolveExternalModuleSymbol(moduleSymbol) + : checker.tryGetMemberInModuleExportsAndProperties(data.exportName, moduleSymbol); + if (!symbol) return undefined; + const isDefaultExport = data.exportName === InternalSymbolName.Default; + symbol = isDefaultExport && getLocalSymbolForExportDefault(symbol) || symbol; + return { + symbol, + origin: { + kind: data.moduleSpecifier ? SymbolOriginInfoKind.ResolvedExport : SymbolOriginInfoKind.Export, + moduleSymbol, + symbolName: name, + isDefaultExport, + exportName: data.exportName, + fileName: data.fileName, + } + }; + } + interface CompletionEntryDisplayNameForSymbol { readonly name: string; readonly needsConvertPropertyAccess: boolean; @@ -2578,7 +2692,7 @@ namespace ts.Completions { kind: CompletionKind, jsxIdentifierExpected: boolean, ): CompletionEntryDisplayNameForSymbol | undefined { - const name = originIsExport(origin) ? getNameForExportedSymbol(symbol, target) : symbol.name; + const name = originIncludesSymbolName(origin) ? origin.symbolName : symbol.name; if (name === undefined // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) @@ -2589,7 +2703,7 @@ namespace ts.Completions { } const validNameResult: CompletionEntryDisplayNameForSymbol = { name, needsConvertPropertyAccess: false }; - if (isIdentifierText(name, target, jsxIdentifierExpected ? LanguageVariant.JSX : LanguageVariant.Standard) || symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) { + if (isIdentifierText(name, target, jsxIdentifierExpected ? LanguageVariant.JSX : LanguageVariant.Standard) || symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) { return validNameResult; } switch (kind) { @@ -2685,6 +2799,7 @@ namespace ts.Completions { case SyntaxKind.NeverKeyword: case SyntaxKind.NumberKeyword: case SyntaxKind.ObjectKeyword: + case SyntaxKind.OverrideKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PublicKeyword: @@ -2712,6 +2827,7 @@ namespace ts.Completions { case SyntaxKind.SetKeyword: case SyntaxKind.AsyncKeyword: case SyntaxKind.DeclareKeyword: + case SyntaxKind.OverrideKeyword: return true; default: return isClassMemberModifier(kind); @@ -2801,6 +2917,13 @@ namespace ts.Completions { if (!contextToken) return undefined; + // class C { blah; constructor/**/ } and so on + if (location.kind === SyntaxKind.ConstructorKeyword + // class C { blah \n constructor/**/ } + || (isIdentifier(contextToken) && isPropertyDeclaration(contextToken.parent) && isClassLike(location))) { + return findAncestor(contextToken, isClassLike) as ObjectTypeDeclaration; + } + switch (contextToken.kind) { case SyntaxKind.EqualsToken: // class c { public prop = | /* global completions */ } return undefined; @@ -2828,6 +2951,49 @@ namespace ts.Completions { } } + function tryGetTypeLiteralNode(node: Node): TypeLiteralNode | undefined { + if (!node) return undefined; + + const parent = node.parent; + + switch (node.kind) { + case SyntaxKind.OpenBraceToken: + if (isTypeLiteralNode(parent)) { + return parent; + } + break; + case SyntaxKind.SemicolonToken: + case SyntaxKind.CommaToken: + case SyntaxKind.Identifier: + if (parent.kind === SyntaxKind.PropertySignature && isTypeLiteralNode(parent.parent)) { + return parent.parent; + } + break; + } + + return undefined; + } + + function getConstraintOfTypeArgumentProperty(node: Node, checker: TypeChecker): Type | undefined { + if (!node) return undefined; + + if (isTypeNode(node) && isTypeReferenceType(node.parent)) { + return checker.getTypeArgumentConstraint(node); + } + + const t = getConstraintOfTypeArgumentProperty(node.parent, checker); + if (!t) return undefined; + + switch (node.kind) { + case SyntaxKind.PropertySignature: + return checker.getTypeOfPropertyOfContextualType(t, node.symbol.escapedName); + case SyntaxKind.IntersectionType: + case SyntaxKind.TypeLiteral: + case SyntaxKind.UnionType: + return t; + } + } + // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes function isFromObjectTypeDeclaration(node: Node): boolean { return node.parent && isClassOrTypeElement(node.parent) && isObjectTypeDeclaration(node.parent.parent); @@ -2852,6 +3018,8 @@ namespace ts.Completions { return !!contextToken && (isStringLiteralLike(contextToken) ? !!tryGetImportFromModuleSpecifier(contextToken) : contextToken.kind === SyntaxKind.SlashToken && isJsxClosingElement(contextToken.parent)); + case " ": + return !!contextToken && isImportKeyword(contextToken) && contextToken.parent.kind === SyntaxKind.SourceFile; default: return Debug.assertNever(triggerCharacter); } @@ -2861,15 +3029,6 @@ namespace ts.Completions { return nodeIsMissing(left); } - function findAlias(typeChecker: TypeChecker, symbol: Symbol, predicate: (symbol: Symbol) => boolean): Symbol | undefined { - let currentAlias: Symbol | undefined = symbol; - while (currentAlias.flags & SymbolFlags.Alias && (currentAlias = typeChecker.getImmediateAliasedSymbol(currentAlias))) { - if (predicate(currentAlias)) { - return currentAlias; - } - } - } - /** Determines if a type is exactly the same type resolved by the global 'self', 'global', or 'globalThis'. */ function isProbablyGlobalType(type: Type, sourceFile: SourceFile, checker: TypeChecker) { // The type of `self` and `window` is the same in lib.dom.d.ts, but `window` does not exist in @@ -2898,9 +3057,67 @@ namespace ts.Completions { if (type) { return type; } - if (isBinaryExpression(node.parent) && node.parent.operatorToken.kind === SyntaxKind.EqualsToken) { + if (isBinaryExpression(node.parent) && node.parent.operatorToken.kind === SyntaxKind.EqualsToken && node === node.parent.left) { + // Object literal is assignment pattern: ({ | } = x) return typeChecker.getTypeAtLocation(node.parent); } return undefined; } + + function getImportCompletionNode(contextToken: Node) { + const candidate = getCandidate(); + return candidate === SyntaxKind.FromKeyword || candidate && rangeIsOnSingleLine(candidate, candidate.getSourceFile()) ? candidate : undefined; + + function getCandidate() { + const parent = contextToken.parent; + if (isImportEqualsDeclaration(parent)) { + return isModuleSpecifierMissingOrEmpty(parent.moduleReference) ? parent : undefined; + } + if (isNamedImports(parent) || isNamespaceImport(parent)) { + if (isModuleSpecifierMissingOrEmpty(parent.parent.parent.moduleSpecifier) && (isNamespaceImport(parent) || parent.elements.length < 2) && !parent.parent.name) { + // At `import { ... } |` or `import * as Foo |`, the only possible completion is `from` + return contextToken.kind === SyntaxKind.CloseBraceToken || contextToken.kind === SyntaxKind.Identifier + ? SyntaxKind.FromKeyword + : parent.parent.parent; + } + return undefined; + } + if (isImportKeyword(contextToken) && isSourceFile(parent)) { + // A lone import keyword with nothing following it does not parse as a statement at all + return contextToken as Token; + } + if (isImportKeyword(contextToken) && isImportDeclaration(parent)) { + // `import s| from` + return isModuleSpecifierMissingOrEmpty(parent.moduleSpecifier) ? parent : undefined; + } + return undefined; + } + } + + function isModuleSpecifierMissingOrEmpty(specifier: ModuleReference | Expression) { + if (nodeIsMissing(specifier)) return true; + return !tryCast(isExternalModuleReference(specifier) ? specifier.expression : specifier, isStringLiteralLike)?.text; + } + + function getVariableDeclaration(property: Node): VariableDeclaration | undefined { + const variableDeclaration = findAncestor(property, node => + isFunctionBlock(node) || isArrowFunctionBody(node) || isBindingPattern(node) + ? "quit" + : isVariableDeclaration(node)); + + return variableDeclaration as VariableDeclaration | undefined; + } + + function isArrowFunctionBody(node: Node) { + return node.parent && isArrowFunction(node.parent) && node.parent.body === node; + }; + + /** True if symbol is a type or a module containing at least one type. */ + function symbolCanBeReferencedAtTypeLocation(symbol: Symbol, checker: TypeChecker, seenModules = new Map()): boolean { + const sym = skipAlias(symbol.exportSymbol || symbol, checker); + return !!(sym.flags & SymbolFlags.Type) || + !!(sym.flags & SymbolFlags.Module) && + addToSeen(seenModules, getSymbolId(sym)) && + checker.getExportsOfModule(sym).some(e => symbolCanBeReferencedAtTypeLocation(e, checker, seenModules)); + } } diff --git a/src/services/documentHighlights.ts b/src/services/documentHighlights.ts index b0282393cce6f..a24ac6d02f04e 100644 --- a/src/services/documentHighlights.ts +++ b/src/services/documentHighlights.ts @@ -32,9 +32,11 @@ namespace ts { const referenceEntries = FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken, /*options*/ undefined, sourceFilesSet); if (!referenceEntries) return undefined; const map = arrayToMultiMap(referenceEntries.map(FindAllReferences.toHighlightSpan), e => e.fileName, e => e.span); - return arrayFrom(map.entries(), ([fileName, highlightSpans]) => { + return mapDefined(arrayFrom(map.entries()), ([fileName, highlightSpans]) => { if (!sourceFilesSet.has(fileName)) { - Debug.assert(program.redirectTargetsMap.has(fileName)); + if (!program.redirectTargetsMap.has(fileName)) { + return undefined; + } const redirectTarget = program.getSourceFile(fileName); const redirect = find(sourceFilesToSearch, f => !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget)!; fileName = redirect.fileName; diff --git a/src/services/documentRegistry.ts b/src/services/documentRegistry.ts index 19fd476d87d1b..77e64bf618bd2 100644 --- a/src/services/documentRegistry.ts +++ b/src/services/documentRegistry.ts @@ -83,12 +83,26 @@ namespace ts { * @param fileName The name of the file to be released * @param compilationSettings The compilation settings used to acquire the file */ + /**@deprecated pass scriptKind for correctness */ releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; - + /** + * Informs the DocumentRegistry that a file is not needed any longer. + * + * Note: It is not allowed to call release on a SourceFile that was not acquired from + * this registry originally. + * + * @param fileName The name of the file to be released + * @param compilationSettings The compilation settings used to acquire the file + * @param scriptKind The script kind of the file to be released + */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind: ScriptKind): void; // eslint-disable-line @typescript-eslint/unified-signatures + /** + * @deprecated pass scriptKind for correctness */ releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind: ScriptKind): void; // eslint-disable-line @typescript-eslint/unified-signatures /*@internal*/ - getLanguageServiceRefCounts(path: Path): [string, number | undefined][]; + getLanguageServiceRefCounts(path: Path, scriptKind: ScriptKind): [string, number | undefined][]; reportStats(): string; } @@ -110,6 +124,11 @@ namespace ts { languageServiceRefCount: number; } + type BucketEntry = DocumentRegistryEntry | ESMap; + function isDocumentRegistryEntry(entry: BucketEntry): entry is DocumentRegistryEntry { + return !!(entry as DocumentRegistryEntry).sourceFile; + } + export function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry { return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); } @@ -118,18 +137,24 @@ namespace ts { export function createDocumentRegistryInternal(useCaseSensitiveFileNames?: boolean, currentDirectory = "", externalCache?: ExternalDocumentCache): DocumentRegistry { // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. - const buckets = new Map>(); + const buckets = new Map>(); const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); function reportStats() { const bucketInfoArray = arrayFrom(buckets.keys()).filter(name => name && name.charAt(0) === "_").map(name => { const entries = buckets.get(name)!; - const sourceFiles: { name: string; refCount: number; }[] = []; + const sourceFiles: { name: string; scriptKind: ScriptKind, refCount: number; }[] = []; entries.forEach((entry, name) => { - sourceFiles.push({ - name, - refCount: entry.languageServiceRefCount - }); + if (isDocumentRegistryEntry(entry)) { + sourceFiles.push({ + name, + scriptKind: entry.sourceFile.scriptKind, + refCount: entry.languageServiceRefCount + }); + } + else { + entry.forEach((value, scriptKind) => sourceFiles.push({ name, scriptKind, refCount: value.languageServiceRefCount })); + } }); sourceFiles.sort((x, y) => y.refCount - x.refCount); return { @@ -160,6 +185,12 @@ namespace ts { return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind); } + function getDocumentRegistryEntry(bucketEntry: BucketEntry, scriptKind: ScriptKind | undefined) { + const entry = isDocumentRegistryEntry(bucketEntry) ? bucketEntry : bucketEntry.get(Debug.checkDefined(scriptKind, "If there are more than one scriptKind's for same document the scriptKind should be provided")); + Debug.assert(scriptKind === undefined || !entry || entry.sourceFile.scriptKind === scriptKind, `Script kind should match provided ScriptKind:${scriptKind} and sourceFile.scriptKind: ${entry?.sourceFile.scriptKind}, !entry: ${!entry}`); + return entry; + } + function acquireOrUpdateDocument( fileName: string, path: Path, @@ -169,10 +200,11 @@ namespace ts { version: string, acquiring: boolean, scriptKind?: ScriptKind): SourceFile { - - const bucket = getOrUpdate(buckets, key, () => new Map()); - let entry = bucket.get(path); + scriptKind = ensureScriptKind(fileName, scriptKind); const scriptTarget = scriptKind === ScriptKind.JSON ? ScriptTarget.JSON : compilationSettings.target || ScriptTarget.ES5; + const bucket = getOrUpdate(buckets, key, () => new Map()); + const bucketEntry = bucket.get(path); + let entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); if (!entry && externalCache) { const sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -181,7 +213,7 @@ namespace ts { sourceFile, languageServiceRefCount: 0 }; - bucket.set(path, entry); + setBucketEntry(); } } @@ -195,7 +227,7 @@ namespace ts { sourceFile, languageServiceRefCount: 1, }; - bucket.set(path, entry); + setBucketEntry(); } else { // We have an entry for this file. However, it may be for a different version of @@ -221,28 +253,53 @@ namespace ts { Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; + + function setBucketEntry() { + if (!bucketEntry) { + bucket.set(path, entry!); + } + else if (isDocumentRegistryEntry(bucketEntry)) { + const scriptKindMap = new Map(); + scriptKindMap.set(bucketEntry.sourceFile.scriptKind, bucketEntry); + scriptKindMap.set(scriptKind!, entry!); + bucket.set(path, scriptKindMap); + } + else { + bucketEntry.set(scriptKind!, entry!); + } + } } - function releaseDocument(fileName: string, compilationSettings: CompilerOptions): void { + function releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind?: ScriptKind): void { const path = toPath(fileName, currentDirectory, getCanonicalFileName); const key = getKeyForCompilationSettings(compilationSettings); - return releaseDocumentWithKey(path, key); + return releaseDocumentWithKey(path, key, scriptKind); } - function releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void { + function releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind?: ScriptKind): void { const bucket = Debug.checkDefined(buckets.get(key)); - const entry = bucket.get(path)!; + const bucketEntry = bucket.get(path)!; + const entry = getDocumentRegistryEntry(bucketEntry, scriptKind)!; entry.languageServiceRefCount--; Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - bucket.delete(path); + if (isDocumentRegistryEntry(bucketEntry)) { + bucket.delete(path); + } + else { + bucketEntry.delete(scriptKind!); + if (bucketEntry.size === 1) { + bucket.set(path, firstDefinedIterator(bucketEntry.values(), identity)!); + } + } } } - function getLanguageServiceRefCounts(path: Path) { + function getLanguageServiceRefCounts(path: Path, scriptKind: ScriptKind) { return arrayFrom(buckets.entries(), ([key, bucket]): [string, number | undefined] => { - const entry = bucket.get(path); + const bucketEntry = bucket.get(path); + const entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); return [key, entry && entry.languageServiceRefCount]; }); } diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 12a97433615ca..fa7dfa188e84e 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -231,7 +231,7 @@ namespace ts.FindAllReferences { } else { const queue = entries && [...entries]; - const seenNodes = new Map(); + const seenNodes = new Map(); while (queue && queue.length) { const entry = queue.shift() as NodeEntry; if (!addToSeen(seenNodes, getNodeId(entry.node))) { @@ -624,7 +624,7 @@ namespace ts.FindAllReferences { } if (isSourceFile(node)) { const resolvedRef = GoToDefinition.getReferenceAtPosition(node, position, program); - if (!resolvedRef) { + if (!resolvedRef?.file) { return undefined; } const moduleSymbol = program.getTypeChecker().getMergedSymbol(resolvedRef.file.symbol); @@ -656,7 +656,7 @@ namespace ts.FindAllReferences { if (!symbol) { // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. if (!options.implementations && isStringLiteralLike(node)) { - if (isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ true) || isExternalModuleReference(node.parent) || isImportDeclaration(node.parent) || isImportCall(node.parent)) { + if (isModuleSpecifierLike(node)) { const fileIncludeReasons = program.getFileIncludeReasons(); const referencedFileName = node.getSourceFile().resolvedModules?.get(node.text)?.resolvedFileName; const referencedFile = referencedFileName ? program.getSourceFile(referencedFileName) : undefined; @@ -839,7 +839,7 @@ namespace ts.FindAllReferences { } const exported = symbol.exports!.get(InternalSymbolName.ExportEquals); - if (exported) { + if (exported?.declarations) { for (const decl of exported.declarations) { const sourceFile = decl.getSourceFile(); if (sourceFilesSet.has(sourceFile.fileName)) { @@ -916,14 +916,14 @@ namespace ts.FindAllReferences { const result: SymbolAndEntries[] = []; const state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : SpecialSearchKind.None, checker, cancellationToken, searchMeaning, options, result); - const exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) ? undefined : find(symbol.declarations, isExportSpecifier); + const exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) || !symbol.declarations ? undefined : find(symbol.declarations, isExportSpecifier); if (exportSpecifier) { // When renaming at an export specifier, rename the export and not the thing being exported. getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); } - else if (node && node.kind === SyntaxKind.DefaultKeyword) { + else if (node && node.kind === SyntaxKind.DefaultKeyword && symbol.escapedName === InternalSymbolName.Default && symbol.parent) { addReference(node, symbol, state); - searchForImportsOfExport(node, symbol, { exportingModuleSymbol: Debug.checkDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: ExportKind.Default }, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: ExportKind.Default }, state); } else { const search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === FindReferencesUse.Rename, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); @@ -1180,7 +1180,9 @@ namespace ts.FindAllReferences { for (const indirectUser of indirectUsers) { for (const node of getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName)) { // Import specifiers should be handled by importSearches - if (isIdentifier(node) && !isImportOrExportSpecifier(node.parent) && checker.getSymbolAtLocation(node) === exportSymbol) { + const symbol = checker.getSymbolAtLocation(node); + const hasExportAssignmentDeclaration = some(symbol?.declarations, d => tryCast(d, isExportAssignment) ? true : false); + if (isIdentifier(node) && !isImportOrExportSpecifier(node.parent) && (symbol === exportSymbol || hasExportAssignmentDeclaration)) { cb(node); } } @@ -1242,7 +1244,7 @@ namespace ts.FindAllReferences { // If this is private property or method, the scope is the containing class if (flags & (SymbolFlags.Property | SymbolFlags.Method)) { - const privateDeclaration = find(declarations, d => hasEffectiveModifier(d, ModifierFlags.Private) || isPrivateIdentifierPropertyDeclaration(d)); + const privateDeclaration = find(declarations, d => hasEffectiveModifier(d, ModifierFlags.Private) || isPrivateIdentifierClassElementDeclaration(d)); if (privateDeclaration) { return getAncestor(privateDeclaration, SyntaxKind.ClassDeclaration); } @@ -1475,7 +1477,7 @@ namespace ts.FindAllReferences { if (!hasMatchingMeaning(referenceLocation, state)) return; - const referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation); + let referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation); if (!referenceSymbol) { return; } @@ -1512,6 +1514,11 @@ namespace ts.FindAllReferences { Debug.assertNever(state.specialSearchKind); } + // Use the parent symbol if the location is commonjs require syntax on javascript files only. + referenceSymbol = isInJSFile(referenceLocation) && referenceLocation.parent.kind === SyntaxKind.BindingElement && isRequireVariableDeclaration(referenceLocation.parent) + ? referenceLocation.parent.symbol + : referenceSymbol; + getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } @@ -1922,6 +1929,8 @@ namespace ts.FindAllReferences { case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: if (isObjectLiteralMethod(searchSpaceNode)) { + staticFlag &= getSyntacticModifierFlags(searchSpaceNode); + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning object literals break; } // falls through @@ -1963,7 +1972,8 @@ namespace ts.FindAllReferences { return isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; case SyntaxKind.ClassExpression: case SyntaxKind.ClassDeclaration: - // Make sure the container belongs to the same class + case SyntaxKind.ObjectLiteralExpression: + // Make sure the container belongs to the same class/object literals // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (getSyntacticModifierFlags(container) & ModifierFlags.Static) === staticFlag; case SyntaxKind.SourceFile: @@ -2154,7 +2164,7 @@ namespace ts.FindAllReferences { * The value of previousIterationSymbol is undefined when the function is first called. */ function getPropertySymbolsFromBaseTypes(symbol: Symbol, propertyName: string, checker: TypeChecker, cb: (symbol: Symbol) => T | undefined): T | undefined { - const seen = new Map(); + const seen = new Map(); return recur(symbol); function recur(symbol: Symbol): T | undefined { diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index 5415158422cef..cadb64398df7d 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -659,11 +659,6 @@ namespace ts.formatting { if (tokenInfo.token.end > node.end) { break; } - if (node.kind === SyntaxKind.JsxText) { - // Intentation rules for jsx text are handled by `indentMultilineCommentOrJsxText` inside `processChildNode`; just fastforward past it here - formattingScanner.advance(); - continue; - } consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node); } @@ -756,22 +751,6 @@ namespace ts.formatting { const childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); - if (child.kind === SyntaxKind.JsxText) { - const range: TextRange = { pos: child.getStart(), end: child.getEnd() }; - if (range.pos !== range.end) { // don't indent zero-width jsx text - const siblings = parent.getChildren(sourceFile); - const currentIndex = findIndex(siblings, arg => arg.pos === child.pos); - const previousNode = siblings[currentIndex - 1]; - if (previousNode) { - // The jsx text needs no indentation whatsoever if it ends on the same line the previous sibling ends on - if (sourceFile.getLineAndCharacterOfPosition(range.end).line !== sourceFile.getLineAndCharacterOfPosition(previousNode.end).line) { - // The first line is (already) "indented" if the text starts on the same line as the previous sibling element ends on - const firstLineIsIndented = sourceFile.getLineAndCharacterOfPosition(range.pos).line === sourceFile.getLineAndCharacterOfPosition(previousNode.end).line; - indentMultilineCommentOrJsxText(range, childIndentation.indentation, firstLineIsIndented, /*indentFinalLine*/ false, /*jsxStyle*/ true); - } - } - } - } childContextNode = node; @@ -930,7 +909,7 @@ namespace ts.formatting { switch (triviaItem.kind) { case SyntaxKind.MultiLineCommentTrivia: if (triviaInRange) { - indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); + indentMultilineComment(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); } indentNextTokenOrTrivia = false; break; @@ -1073,7 +1052,7 @@ namespace ts.formatting { return indentationString !== sourceFile.text.substr(startLinePosition, indentationString.length); } - function indentMultilineCommentOrJsxText(commentRange: TextRange, indentation: number, firstLineIsIndented: boolean, indentFinalLine = true, jsxTextStyleIndent?: boolean) { + function indentMultilineComment(commentRange: TextRange, indentation: number, firstLineIsIndented: boolean, indentFinalLine = true) { // split comment in lines let startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; const endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; @@ -1111,19 +1090,13 @@ namespace ts.formatting { } // shift all parts on the delta size - let delta = indentation - nonWhitespaceColumnInFirstPart.column; + const delta = indentation - nonWhitespaceColumnInFirstPart.column; for (let i = startIndex; i < parts.length; i++ , startLine++) { const startLinePos = getStartPositionOfLine(startLine, sourceFile); const nonWhitespaceCharacterAndColumn = i === 0 ? nonWhitespaceColumnInFirstPart : SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options); - if (jsxTextStyleIndent) { - // skip adding indentation to blank lines - if (isLineBreak(sourceFile.text.charCodeAt(getStartPositionOfLine(startLine, sourceFile)))) continue; - // reset delta on every line - delta = indentation - nonWhitespaceCharacterAndColumn.column; - } const newIndentation = nonWhitespaceCharacterAndColumn.column + delta; if (newIndentation > 0) { const indentationString = getIndentationString(newIndentation, options); diff --git a/src/services/formatting/formattingScanner.ts b/src/services/formatting/formattingScanner.ts index 5a6013c4e7518..b619f98eb2b85 100644 --- a/src/services/formatting/formattingScanner.ts +++ b/src/services/formatting/formattingScanner.ts @@ -124,13 +124,7 @@ namespace ts.formatting { } function shouldRescanJsxText(node: Node): boolean { - const isJSXText = isJsxText(node); - if (isJSXText) { - const containingElement = findAncestor(node.parent, p => isJsxElement(p)); - if (!containingElement) return false; // should never happen - return !isParenthesizedExpression(containingElement.parent); - } - return false; + return isJsxText(node); } function shouldRescanSlashToken(container: Node): boolean { @@ -252,7 +246,7 @@ namespace ts.formatting { return scanner.scanJsxIdentifier(); case ScanAction.RescanJsxText: lastScanAction = ScanAction.RescanJsxText; - return scanner.reScanJsxToken(); + return scanner.reScanJsxToken(/* allowMultilineJsxText */ false); case ScanAction.RescanJsxAttributeValue: lastScanAction = ScanAction.RescanJsxAttributeValue; return scanner.reScanJsxAttributeValue(); diff --git a/src/services/getEditsForFileRename.ts b/src/services/getEditsForFileRename.ts index d2b17739824a0..563e10680522a 100644 --- a/src/services/getEditsForFileRename.ts +++ b/src/services/getEditsForFileRename.ts @@ -146,7 +146,7 @@ namespace ts { importLiteral => { const importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); // No need to update if it's an ambient module^M - if (importedModuleSymbol && importedModuleSymbol.declarations.some(d => isAmbientModule(d))) return undefined; + if (importedModuleSymbol?.declarations && importedModuleSymbol.declarations.some(d => isAmbientModule(d))) return undefined; const toImport = oldFromNew !== undefined // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. @@ -185,7 +185,7 @@ namespace ts { ): ToImport | undefined { if (importedModuleSymbol) { // `find` should succeed because we checked for ambient modules before calling this function. - const oldFileName = find(importedModuleSymbol.declarations, isSourceFile)!.fileName; + const oldFileName = find(importedModuleSymbol.declarations!, isSourceFile)!.fileName; const newFileName = oldToNew(oldFileName); return newFileName === undefined ? { newFileName: oldFileName, updated: false } : { newFileName, updated: true }; } diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index faaf1077354a9..d4f317d754314 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -2,8 +2,10 @@ namespace ts.GoToDefinition { export function getDefinitionAtPosition(program: Program, sourceFile: SourceFile, position: number): readonly DefinitionInfo[] | undefined { const resolvedRef = getReferenceAtPosition(sourceFile, position, program); - if (resolvedRef) { - return [getDefinitionInfoForFileReference(resolvedRef.reference.fileName, resolvedRef.file.fileName)]; + const fileReferenceDefinition = resolvedRef && [getDefinitionInfoForFileReference(resolvedRef.reference.fileName, resolvedRef.fileName, resolvedRef.unverified)] || emptyArray; + if (resolvedRef?.file) { + // If `file` is missing, do a symbol-based lookup as well + return fileReferenceDefinition; } const node = getTouchingPropertyName(sourceFile, position); @@ -25,7 +27,7 @@ namespace ts.GoToDefinition { // Could not find a symbol e.g. node is string or number keyword, // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol if (!symbol) { - return getDefinitionInfoForIndexSignatures(node, typeChecker); + return concatenate(fileReferenceDefinition, getDefinitionInfoForIndexSignatures(node, typeChecker)); } const calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); @@ -51,7 +53,8 @@ namespace ts.GoToDefinition { // assignment. This case and others are handled by the following code. if (node.parent.kind === SyntaxKind.ShorthandPropertyAssignment) { const shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); - return shorthandSymbol ? shorthandSymbol.declarations.map(decl => createDefinitionInfo(decl, typeChecker, shorthandSymbol, node)) : []; + const definitions = shorthandSymbol?.declarations ? shorthandSymbol.declarations.map(decl => createDefinitionInfo(decl, typeChecker, shorthandSymbol, node)) : emptyArray; + return concatenate(definitions, getDefinitionFromObjectLiteralElement(typeChecker, node) || emptyArray); } // If the node is the name of a BindingElement within an ObjectBindingPattern instead of just returning the @@ -75,25 +78,7 @@ namespace ts.GoToDefinition { }); } - // If the current location we want to find its definition is in an object literal, try to get the contextual type for the - // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. - // For example - // interface Props{ - // /*first*/prop1: number - // prop2: boolean - // } - // function Foo(arg: Props) {} - // Foo( { pr/*1*/op1: 10, prop2: true }) - const element = getContainingObjectLiteralElement(node); - if (element) { - const contextualType = element && typeChecker.getContextualType(element.parent); - if (contextualType) { - return flatMap(getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), propertySymbol => - getDefinitionFromSymbol(typeChecker, propertySymbol, node)); - } - } - - return getDefinitionFromSymbol(typeChecker, symbol, node); + return concatenate(fileReferenceDefinition, getDefinitionFromObjectLiteralElement(typeChecker, node) || getDefinitionFromSymbol(typeChecker, symbol, node)); } /** @@ -108,24 +93,62 @@ namespace ts.GoToDefinition { || (!isCallLikeExpression(calledDeclaration.parent) && s === calledDeclaration.parent.symbol); } - export function getReferenceAtPosition(sourceFile: SourceFile, position: number, program: Program): { reference: FileReference, file: SourceFile } | undefined { + // If the current location we want to find its definition is in an object literal, try to get the contextual type for the + // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. + // For example + // interface Props{ + // /*first*/prop1: number + // prop2: boolean + // } + // function Foo(arg: Props) {} + // Foo( { pr/*1*/op1: 10, prop2: true }) + function getDefinitionFromObjectLiteralElement(typeChecker: TypeChecker, node: Node) { + const element = getContainingObjectLiteralElement(node); + if (element) { + const contextualType = element && typeChecker.getContextualType(element.parent); + if (contextualType) { + return flatMap(getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), propertySymbol => + getDefinitionFromSymbol(typeChecker, propertySymbol, node)); + } + } + } + + export function getReferenceAtPosition(sourceFile: SourceFile, position: number, program: Program): { reference: FileReference, fileName: string, unverified: boolean, file?: SourceFile } | undefined { const referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); if (referencePath) { const file = program.getSourceFileFromReference(sourceFile, referencePath); - return file && { reference: referencePath, file }; + return file && { reference: referencePath, fileName: file.fileName, file, unverified: false }; } const typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { const reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); const file = reference && program.getSourceFile(reference.resolvedFileName!); // TODO:GH#18217 - return file && { reference: typeReferenceDirective, file }; + return file && { reference: typeReferenceDirective, fileName: file.fileName, file, unverified: false }; } const libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position); if (libReferenceDirective) { const file = program.getLibFileFromReference(libReferenceDirective); - return file && { reference: libReferenceDirective, file }; + return file && { reference: libReferenceDirective, fileName: file.fileName, file, unverified: false }; + } + + if (sourceFile.resolvedModules?.size) { + const node = getTokenAtPosition(sourceFile, position); + if (isModuleSpecifierLike(node) && isExternalModuleNameRelative(node.text) && sourceFile.resolvedModules.has(node.text)) { + const verifiedFileName = sourceFile.resolvedModules.get(node.text)?.resolvedFileName; + const fileName = verifiedFileName || resolvePath(getDirectoryPath(sourceFile.fileName), node.text); + return { + file: program.getSourceFile(fileName), + fileName, + reference: { + pos: node.getStart(), + end: node.getEnd(), + fileName: node.text + }, + unverified: !verifiedFileName, + }; + } } return undefined; @@ -203,7 +226,7 @@ namespace ts.GoToDefinition { // get the aliased symbol instead. This allows for goto def on an import e.g. // import {A, B} from "mod"; // to jump to the implementation directly. - if (symbol && symbol.flags & SymbolFlags.Alias && shouldSkipAlias(node, symbol.declarations[0])) { + if (symbol?.declarations && symbol.flags & SymbolFlags.Alias && shouldSkipAlias(node, symbol.declarations[0])) { const aliased = checker.getAliasedSymbol(symbol); if (aliased.declarations) { return aliased; @@ -232,7 +255,7 @@ namespace ts.GoToDefinition { return declaration.parent.kind === SyntaxKind.NamedImports; case SyntaxKind.BindingElement: case SyntaxKind.VariableDeclaration: - return isInJSFile(declaration) && isRequireVariableDeclaration(declaration, /*requireStringLiteralLikeArgument*/ true); + return isInJSFile(declaration) && isRequireVariableDeclaration(declaration); default: return false; } @@ -251,7 +274,7 @@ namespace ts.GoToDefinition { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class if (symbol.flags & SymbolFlags.Class && !(symbol.flags & (SymbolFlags.Function | SymbolFlags.Variable)) && (isNewExpressionTarget(node) || node.kind === SyntaxKind.ConstructorKeyword)) { - const cls = find(filteredDeclarations, isClassLike) || Debug.fail("Expected declaration to have at least one class-like declaration"); + const cls = find(filteredDeclarations!, isClassLike) || Debug.fail("Expected declaration to have at least one class-like declaration"); return getSignatureDefinition(cls.members, /*selectConstructors*/ true); } } @@ -303,10 +326,41 @@ namespace ts.GoToDefinition { sourceFile, FindAllReferences.getContextNode(declaration) ), - isLocal: !checker.isDeclarationVisible(declaration) + isLocal: !isDefinitionVisible(checker, declaration) }; } + function isDefinitionVisible(checker: TypeChecker, declaration: Declaration): boolean { + if (checker.isDeclarationVisible(declaration)) return true; + if (!declaration.parent) return false; + + // Variable initializers are visible if variable is visible + if (hasInitializer(declaration.parent) && declaration.parent.initializer === declaration) return isDefinitionVisible(checker, declaration.parent as Declaration); + + // Handle some exceptions here like arrow function, members of class and object literal expression which are technically not visible but we want the definition to be determined by its parent + switch (declaration.kind) { + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + case SyntaxKind.MethodDeclaration: + // Private/protected properties/methods are not visible + if (hasEffectiveModifier(declaration, ModifierFlags.Private)) return false; + // Public properties/methods are visible if its parents are visible, so: + // falls through + + case SyntaxKind.Constructor: + case SyntaxKind.PropertyAssignment: + case SyntaxKind.ShorthandPropertyAssignment: + case SyntaxKind.ObjectLiteralExpression: + case SyntaxKind.ClassExpression: + case SyntaxKind.ArrowFunction: + case SyntaxKind.FunctionExpression: + return isDefinitionVisible(checker, declaration.parent as Declaration); + default: + return false; + } + } + function createDefinitionFromSignatureDeclaration(typeChecker: TypeChecker, decl: SignatureDeclaration): DefinitionInfo { return createDefinitionInfo(decl, typeChecker, decl.symbol, decl); } @@ -315,7 +369,7 @@ namespace ts.GoToDefinition { return find(refs, ref => textRangeContainsPositionInclusive(ref, pos)); } - function getDefinitionInfoForFileReference(name: string, targetFileName: string): DefinitionInfo { + function getDefinitionInfoForFileReference(name: string, targetFileName: string, unverified: boolean): DefinitionInfo { return { fileName: targetFileName, textSpan: createTextSpanFromBounds(0, 0), @@ -323,6 +377,7 @@ namespace ts.GoToDefinition { name, containerName: undefined!, containerKind: undefined!, // TODO: GH#18217 + unverified, }; } diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index ccee9c90a02a6..d3c95854f9bbe 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -62,9 +62,11 @@ namespace ts.FindAllReferences { } // Module augmentations may use this module's exports without importing it. - for (const decl of exportingModuleSymbol.declarations) { - if (isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) { - addIndirectUser(decl); + if (exportingModuleSymbol.declarations) { + for (const decl of exportingModuleSymbol.declarations) { + if (isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) { + addIndirectUser(decl); + } } } @@ -358,7 +360,7 @@ namespace ts.FindAllReferences { const checker = program.getTypeChecker(); for (const referencingFile of sourceFiles) { const searchSourceFile = searchModuleSymbol.valueDeclaration; - if (searchSourceFile.kind === SyntaxKind.SourceFile) { + if (searchSourceFile?.kind === SyntaxKind.SourceFile) { for (const ref of referencingFile.referencedFiles) { if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { refs.push({ kind: "reference", referencingFile, ref }); @@ -463,13 +465,13 @@ namespace ts.FindAllReferences { function getExport(): ExportedSymbol | ImportedSymbol | undefined { const { parent } = node; - const grandParent = parent.parent; + const grandparent = parent.parent; if (symbol.exportSymbol) { if (parent.kind === SyntaxKind.PropertyAccessExpression) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. - return symbol.declarations.some(d => d === parent) && isBinaryExpression(grandParent) - ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false) + return symbol.declarations?.some(d => d === parent) && isBinaryExpression(grandparent) + ? getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ false) : undefined; } else { @@ -500,26 +502,26 @@ namespace ts.FindAllReferences { return getExportAssignmentExport(parent); } // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. - else if (isExportAssignment(grandParent)) { - return getExportAssignmentExport(grandParent); + else if (isExportAssignment(grandparent)) { + return getExportAssignmentExport(grandparent); } // Similar for `module.exports =` and `exports.A =`. else if (isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } - else if (isBinaryExpression(grandParent)) { - return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true); + else if (isBinaryExpression(grandparent)) { + return getSpecialPropertyExport(grandparent, /*useLhsSymbol*/ true); } else if (isJSDocTypedefTag(parent)) { return exportInfo(symbol, ExportKind.Named); } } - function getExportAssignmentExport(ex: ExportAssignment): ExportedSymbol { + function getExportAssignmentExport(ex: ExportAssignment): ExportedSymbol | undefined { // Get the symbol for the `export =` node; its parent is the module it's the export of. - const exportingModuleSymbol = Debug.checkDefined(ex.symbol.parent, "Expected export symbol to have a parent"); + if (!ex.symbol.parent) return undefined; const exportKind = ex.isExportEquals ? ExportKind.ExportEquals : ExportKind.Default; - return { kind: ImportExport.Export, symbol, exportInfo: { exportingModuleSymbol, exportKind } }; + return { kind: ImportExport.Export, symbol, exportInfo: { exportingModuleSymbol: ex.symbol.parent, exportKind } }; } function getSpecialPropertyExport(node: BinaryExpression, useLhsSymbol: boolean): ExportedSymbol | undefined { @@ -580,7 +582,7 @@ namespace ts.FindAllReferences { return Debug.checkDefined(checker.getImmediateAliasedSymbol(importedSymbol)); } - const decl = importedSymbol.valueDeclaration; + const decl = Debug.checkDefined(importedSymbol.valueDeclaration); if (isExportAssignment(decl)) { // `export = class {}` return Debug.checkDefined(decl.expression.symbol); } @@ -619,7 +621,7 @@ namespace ts.FindAllReferences { Debug.assert((parent as ImportClause | NamespaceImport).name === node); return true; case SyntaxKind.BindingElement: - return isInJSFile(node) && isRequireVariableDeclaration(parent, /*requireStringLiteralLikeArgument*/ true); + return isInJSFile(node) && isRequireVariableDeclaration(parent); default: return false; } @@ -642,7 +644,8 @@ namespace ts.FindAllReferences { return checker.getExportSpecifierLocalTargetSymbol(declaration)!; } else if (isPropertyAccessExpression(declaration) && isModuleExportsAccessExpression(declaration.expression) && !isPrivateIdentifier(declaration.name)) { - return checker.getExportSpecifierLocalTargetSymbol(declaration.name)!; + // Export of form 'module.exports.propName = expr'; + return checker.getSymbolAtLocation(declaration)!; } else if (isShorthandPropertyAssignment(declaration) && isBinaryExpression(declaration.parent.parent) diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index b0e133521cdf0..5670ce5897695 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -44,6 +44,7 @@ namespace ts.JsDoc { "kind", "lends", "license", + "link", "listens", "member", "memberof", @@ -82,21 +83,28 @@ namespace ts.JsDoc { let jsDocTagNameCompletionEntries: CompletionEntry[]; let jsDocTagCompletionEntries: CompletionEntry[]; - export function getJsDocCommentsFromDeclarations(declarations: readonly Declaration[]): SymbolDisplayPart[] { + export function getJsDocCommentsFromDeclarations(declarations: readonly Declaration[], checker?: TypeChecker): SymbolDisplayPart[] { // Only collect doc comments from duplicate declarations once: // In case of a union property there might be same declaration multiple times // which only varies in type parameter // Eg. const a: Array | Array; a.length // The property length will have two declarations of property length coming // from Array - Array and Array - const documentationComment: string[] = []; + const parts: SymbolDisplayPart[][] = []; forEachUnique(declarations, declaration => { for (const { comment } of getCommentHavingNodes(declaration)) { if (comment === undefined) continue; - pushIfUnique(documentationComment, comment); + const newparts = getDisplayPartsFromComment(comment, checker); + if (!contains(parts, newparts, isIdenticalListOfDisplayParts)) { + parts.push(newparts); + } } }); - return intersperse(map(documentationComment, textPart), lineBreakPart()); + return flatten(intersperse(parts, [lineBreakPart()])); + } + + function isIdenticalListOfDisplayParts(parts1: SymbolDisplayPart[], parts2: SymbolDisplayPart[]) { + return arraysEqual(parts1, parts2, (p1, p2) => p1.kind === p2.kind && p1.text === p2.text); } function getCommentHavingNodes(declaration: Declaration): readonly (JSDoc | JSDocTag)[] { @@ -112,26 +120,37 @@ namespace ts.JsDoc { } } - export function getJsDocTagsFromDeclarations(declarations?: Declaration[]): JSDocTagInfo[] { + export function getJsDocTagsFromDeclarations(declarations?: Declaration[], checker?: TypeChecker): JSDocTagInfo[] { // Only collect doc comments from duplicate declarations once. const tags: JSDocTagInfo[] = []; forEachUnique(declarations, declaration => { for (const tag of getJSDocTags(declaration)) { - tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); + tags.push({ name: tag.tagName.text, text: getCommentDisplayParts(tag, checker) }); } }); return tags; } - function getCommentText(tag: JSDocTag): string | undefined { - const { comment } = tag; - switch (tag.kind) { + function getDisplayPartsFromComment(comment: string | readonly (JSDocText | JSDocLink)[], checker: TypeChecker | undefined): SymbolDisplayPart[] { + if (typeof comment === "string") { + return [textPart(comment)]; + } + return flatMap( + comment, + node => node.kind === SyntaxKind.JSDocText ? [textPart(node.text)] : buildLinkParts(node, checker) + ) as SymbolDisplayPart[]; + } + + function getCommentDisplayParts(tag: JSDocTag, checker?: TypeChecker): SymbolDisplayPart[] | undefined { + const { comment, kind } = tag; + const namePart = getTagNameDisplayPart(kind); + switch (kind) { case SyntaxKind.JSDocImplementsTag: return withNode((tag as JSDocImplementsTag).class); case SyntaxKind.JSDocAugmentsTag: return withNode((tag as JSDocAugmentsTag).class); case SyntaxKind.JSDocTemplateTag: - return withList((tag as JSDocTemplateTag).typeParameters); + return addComment((tag as JSDocTemplateTag).typeParameters.map(tp => tp.getText()).join(", ")); case SyntaxKind.JSDocTypeTag: return withNode((tag as JSDocTypeTag).typeExpression); case SyntaxKind.JSDocTypedefTag: @@ -139,22 +158,46 @@ namespace ts.JsDoc { case SyntaxKind.JSDocPropertyTag: case SyntaxKind.JSDocParameterTag: case SyntaxKind.JSDocSeeTag: - const { name } = tag as JSDocTypedefTag | JSDocPropertyTag | JSDocParameterTag | JSDocSeeTag; - return name ? withNode(name) : comment; + const { name } = tag as JSDocTypedefTag | JSDocCallbackTag | JSDocPropertyTag | JSDocParameterTag | JSDocSeeTag; + return name ? withNode(name) + : comment === undefined ? undefined + : getDisplayPartsFromComment(comment, checker); default: - return comment; + return comment === undefined ? undefined : getDisplayPartsFromComment(comment, checker); } function withNode(node: Node) { return addComment(node.getText()); } - function withList(list: NodeArray): string { - return addComment(list.map(x => x.getText()).join(", ")); + function addComment(s: string) { + if (comment) { + if (s.match(/^https?$/)) { + return [textPart(s), ...getDisplayPartsFromComment(comment, checker)]; + } + else { + return [namePart(s), spacePart(), ...getDisplayPartsFromComment(comment, checker)]; + } + } + else { + return [textPart(s)]; + } } + } - function addComment(s: string) { - return comment === undefined ? s : `${s} ${comment}`; + function getTagNameDisplayPart(kind: SyntaxKind): (text: string) => SymbolDisplayPart { + switch (kind) { + case SyntaxKind.JSDocParameterTag: + return parameterNamePart; + case SyntaxKind.JSDocPropertyTag: + return propertyNamePart; + case SyntaxKind.JSDocTemplateTag: + return typeParameterNamePart; + case SyntaxKind.JSDocTypedefTag: + case SyntaxKind.JSDocCallbackTag: + return typeAliasNamePart; + default: + return textPart; } } diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 2158270142a1e..cfecf51a4150b 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -136,7 +136,7 @@ namespace ts.NavigationBar { for (let i = 0; i < depth; i++) endNode(); } function startNestedNodes(targetNode: Node, entityName: BindableStaticNameExpression) { - const names: (PropertyNameLiteral | WellKnownSymbolExpression)[] = []; + const names: PropertyNameLiteral[] = []; while (!isPropertyNameLiteral(entityName)) { const name = getNameOrArgument(entityName); const nameText = getElementOrPropertyAccessName(entityName); @@ -194,6 +194,21 @@ namespace ts.NavigationBar { } } + /** + * Historically, we've elided dynamic names from the nav tree (including late bound names), + * but included certain "well known" symbol names. While we no longer distinguish those well-known + * symbols from other unique symbols, we do the below to retain those members in the nav tree. + */ + function hasNavigationBarName(node: Declaration) { + return !hasDynamicName(node) || + ( + node.kind !== SyntaxKind.BinaryExpression && + isPropertyAccessExpression(node.name.expression) && + isIdentifier(node.name.expression.expression) && + idText(node.name.expression.expression) === "Symbol" + ); + } + /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ function addChildrenRecursively(node: Node | undefined): void { curCancellationToken.throwIfCancellationRequested(); @@ -220,18 +235,18 @@ namespace ts.NavigationBar { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.MethodSignature: - if (!hasDynamicName((node))) { + if (hasNavigationBarName((node))) { addNodeWithRecursiveChild(node, (node).body); } break; case SyntaxKind.PropertyDeclaration: - if (!hasDynamicName(node)) { + if (hasNavigationBarName(node)) { addNodeWithRecursiveInitializer(node); } break; case SyntaxKind.PropertySignature: - if (!hasDynamicName(node)) { + if (hasNavigationBarName(node)) { addLeafNode(node); } break; @@ -358,7 +373,7 @@ namespace ts.NavigationBar { assignmentTarget; let depth = 0; - let className: PropertyNameLiteral | WellKnownSymbolExpression; + let className: PropertyNameLiteral; // If we see a prototype assignment, start tracking the target as a class // This is only done for simple classes not nested assignments. if (isIdentifier(prototypeAccess.expression)) { @@ -614,7 +629,8 @@ namespace ts.NavigationBar { case SyntaxKind.SetAccessor: return hasSyntacticModifier(a, ModifierFlags.Static) === hasSyntacticModifier(b, ModifierFlags.Static); case SyntaxKind.ModuleDeclaration: - return areSameModule(a, b); + return areSameModule(a, b) + && getFullyQualifiedModuleName(a) === getFullyQualifiedModuleName(b); default: return true; } @@ -634,7 +650,6 @@ namespace ts.NavigationBar { // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a: ModuleDeclaration, b: ModuleDeclaration): boolean { - // TODO: GH#18217 return a.body!.kind === b.body!.kind && (a.body!.kind !== SyntaxKind.ModuleDeclaration || areSameModule(a.body, b.body)); } @@ -854,6 +869,10 @@ namespace ts.NavigationBar { return getTextOfNode(moduleDeclaration.name); } + return getFullyQualifiedModuleName(moduleDeclaration); + } + + function getFullyQualifiedModuleName(moduleDeclaration: ModuleDeclaration): string { // Otherwise, we need to aggregate each identifier to build up the qualified name. const result = [getTextOfIdentifierOrLiteral(moduleDeclaration.name)]; while (moduleDeclaration.body && moduleDeclaration.body.kind === SyntaxKind.ModuleDeclaration) { diff --git a/src/services/organizeImports.ts b/src/services/organizeImports.ts index c67b9df12e419..aabbc90c0938e 100644 --- a/src/services/organizeImports.ts +++ b/src/services/organizeImports.ts @@ -13,12 +13,13 @@ namespace ts.OrganizeImports { host: LanguageServiceHost, program: Program, preferences: UserPreferences, + skipDestructiveCodeActions?: boolean ) { const changeTracker = textChanges.ChangeTracker.fromContext({ host, formatContext, preferences }); const coalesceAndOrganizeImports = (importGroup: readonly ImportDeclaration[]) => stableSort( - coalesceImports(removeUnusedImports(importGroup, sourceFile, program)), + coalesceImports(removeUnusedImports(importGroup, sourceFile, program, skipDestructiveCodeActions)), (s1, s2) => compareImportsOrRequireStatements(s1, s2)); // All of the old ImportDeclarations in the file, in syntactic order. @@ -63,27 +64,36 @@ namespace ts.OrganizeImports { ? coalesce(importGroup) : importGroup); - // Delete or replace the first import. + // Delete all nodes if there are no imports. if (newImportDecls.length === 0) { - changeTracker.delete(sourceFile, oldImportDecls[0]); + // Consider the first node to have trailingTrivia as we want to exclude the + // "header" comment. + changeTracker.deleteNodes(sourceFile, oldImportDecls, { + trailingTriviaOption: textChanges.TrailingTriviaOption.Include, + }, /*hasTrailingComment*/ true); } else { // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. - changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { + const replaceOptions = { leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude, // Leave header comment in place trailingTriviaOption: textChanges.TrailingTriviaOption.Include, suffix: getNewLineOrDefaultFromHost(host, formatContext.options), - }); - } - - // Delete any subsequent imports. - for (let i = 1; i < oldImportDecls.length; i++) { - changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + }; + changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, replaceOptions); + const hasTrailingComment = changeTracker.nodeHasTrailingComment(sourceFile, oldImportDecls[0], replaceOptions); + changeTracker.deleteNodes(sourceFile, oldImportDecls.slice(1), { + trailingTriviaOption: textChanges.TrailingTriviaOption.Include, + }, hasTrailingComment); } } } - function removeUnusedImports(oldImports: readonly ImportDeclaration[], sourceFile: SourceFile, program: Program) { + function removeUnusedImports(oldImports: readonly ImportDeclaration[], sourceFile: SourceFile, program: Program, skipDestructiveCodeActions: boolean | undefined) { + // As a precaution, consider unused import detection to be destructive (GH #43051) + if (skipDestructiveCodeActions) { + return oldImports; + } + const typeChecker = program.getTypeChecker(); const jsxNamespace = typeChecker.getJsxNamespace(sourceFile); const jsxFragmentFactory = typeChecker.getJsxFragmentFactory(sourceFile); diff --git a/src/services/refactors/convertArrowFunctionOrFunctionExpression.ts b/src/services/refactors/convertArrowFunctionOrFunctionExpression.ts index dc5948c89874a..6987fdd491911 100644 --- a/src/services/refactors/convertArrowFunctionOrFunctionExpression.ts +++ b/src/services/refactors/convertArrowFunctionOrFunctionExpression.ts @@ -208,7 +208,10 @@ namespace ts.refactor.convertArrowFunctionOrFunctionExpression { const { variableDeclaration, variableDeclarationList, statement, name } = variableInfo; suppressLeadingTrivia(statement); - const newNode = factory.createFunctionDeclaration(func.decorators, statement.modifiers, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); + + const modifiersFlags = (getCombinedModifierFlags(variableDeclaration) & ModifierFlags.Export) | getEffectiveModifierFlags(func); + const modifiers = factory.createModifiersFromModifierFlags(modifiersFlags); + const newNode = factory.createFunctionDeclaration(func.decorators, length(modifiers) ? modifiers : undefined, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); if (variableDeclarationList.declarations.length === 1) { return textChanges.ChangeTracker.with(context, t => t.replaceNode(file, statement, newNode)); diff --git a/src/services/refactors/convertExport.ts b/src/services/refactors/convertExport.ts index 43096a4d08134..799df2f176a0e 100644 --- a/src/services/refactors/convertExport.ts +++ b/src/services/refactors/convertExport.ts @@ -48,7 +48,7 @@ namespace ts.refactor { }); // If a VariableStatement, will have exactly one VariableDeclaration, with an Identifier for a name. - type ExportToConvert = FunctionDeclaration | ClassDeclaration | InterfaceDeclaration | EnumDeclaration | NamespaceDeclaration | TypeAliasDeclaration | VariableStatement; + type ExportToConvert = FunctionDeclaration | ClassDeclaration | InterfaceDeclaration | EnumDeclaration | NamespaceDeclaration | TypeAliasDeclaration | VariableStatement | ExportAssignment; interface ExportInfo { readonly exportNode: ExportToConvert; readonly exportName: Identifier; // This is exportNode.name except for VariableStatement_s. @@ -67,7 +67,8 @@ namespace ts.refactor { const exportingModuleSymbol = isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol; - const flags = getSyntacticModifierFlags(exportNode); + const flags = getSyntacticModifierFlags(exportNode) || ((isExportAssignment(exportNode) && !exportNode.isExportEquals) ? ModifierFlags.ExportDefault : ModifierFlags.None); + const wasDefault = !!(flags & ModifierFlags.Default); // If source file already has a default export, don't offer refactor. if (!(flags & ModifierFlags.Export) || !wasDefault && exportingModuleSymbol.exports!.has(InternalSymbolName.Default)) { @@ -95,6 +96,11 @@ namespace ts.refactor { Debug.assert(!wasDefault, "Can't have a default flag here"); return isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault, exportingModuleSymbol } : undefined; } + case SyntaxKind.ExportAssignment: { + const node = exportNode as ExportAssignment; + const exp = node.expression as Identifier; + return node.isExportEquals ? undefined : { exportNode: node, exportName: exp, wasDefault, exportingModuleSymbol }; + } default: return undefined; } @@ -107,7 +113,14 @@ namespace ts.refactor { function changeExport(exportingSourceFile: SourceFile, { wasDefault, exportNode, exportName }: ExportInfo, changes: textChanges.ChangeTracker, checker: TypeChecker): void { if (wasDefault) { - changes.delete(exportingSourceFile, Debug.checkDefined(findModifier(exportNode, SyntaxKind.DefaultKeyword), "Should find a default keyword in modifier list")); + if (isExportAssignment(exportNode) && !exportNode.isExportEquals) { + const exp = exportNode.expression as Identifier; + const spec = makeExportSpecifier(exp.text, exp.text); + changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([spec]))); + } + else { + changes.delete(exportingSourceFile, Debug.checkDefined(findModifier(exportNode, SyntaxKind.DefaultKeyword), "Should find a default keyword in modifier list")); + } } else { const exportKeyword = Debug.checkDefined(findModifier(exportNode, SyntaxKind.ExportKeyword), "Should find an export keyword in modifier list"); @@ -134,7 +147,7 @@ namespace ts.refactor { changes.insertNodeAfter(exportingSourceFile, exportNode, factory.createExportDefault(factory.createIdentifier(exportName.text))); break; default: - Debug.assertNever(exportNode, `Unexpected exportNode kind ${(exportNode as ExportToConvert).kind}`); + Debug.fail(`Unexpected exportNode kind ${(exportNode as ExportToConvert).kind}`); } } } diff --git a/src/services/refactors/convertOverloadListToSingleSignature.ts b/src/services/refactors/convertOverloadListToSingleSignature.ts index cd0e4d9cd8ef4..5c49bf06d0970 100644 --- a/src/services/refactors/convertOverloadListToSingleSignature.ts +++ b/src/services/refactors/convertOverloadListToSingleSignature.ts @@ -201,10 +201,10 @@ ${newComment.split("\n").map(c => ` * ${c}`).join("\n")} if (!every(decls, d => getSourceFileOfNode(d) === file)) { return; } - if (!isConvertableSignatureDeclaration(decls[0])) { + if (!isConvertableSignatureDeclaration(decls![0])) { return; } - const kindOne = decls[0].kind; + const kindOne = decls![0].kind; if (!every(decls, d => d.kind === kindOne)) { return; } diff --git a/src/services/refactors/convertParamsToDestructuredObject.ts b/src/services/refactors/convertParamsToDestructuredObject.ts index c9e587837ddd9..28bde59adaef6 100644 --- a/src/services/refactors/convertParamsToDestructuredObject.ts +++ b/src/services/refactors/convertParamsToDestructuredObject.ts @@ -360,7 +360,7 @@ namespace ts.refactor.convertParamsToDestructuredObject { if (isObjectLiteralExpression(functionDeclaration.parent)) { const contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker); // don't offer the refactor when there are multiple signatures since we won't know which ones the user wants to change - return contextualSymbol?.declarations.length === 1 && isSingleImplementation(functionDeclaration, checker); + return contextualSymbol?.declarations?.length === 1 && isSingleImplementation(functionDeclaration, checker); } return isSingleImplementation(functionDeclaration, checker); case SyntaxKind.Constructor: diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 6478ad24d5ba5..b5167124512cf 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -70,7 +70,7 @@ namespace ts.refactor.extractSymbol { let i = 0; for (const { functionExtraction, constantExtraction } of extractions) { const description = functionExtraction.description; - if(refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)){ + if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { if (functionExtraction.errors.length === 0) { // Don't issue refactorings with duplicated names. // Scopes come back in "innermost first" order, so extractions will @@ -94,8 +94,7 @@ namespace ts.refactor.extractSymbol { } } - // Skip these since we don't have a way to report errors yet - if(refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { + if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { if (constantExtraction.errors.length === 0) { // Don't issue refactorings with duplicated names. // Scopes come back in "innermost first" order, so extractions will @@ -265,24 +264,30 @@ namespace ts.refactor.extractSymbol { /** * getRangeToExtract takes a span inside a text file and returns either an expression or an array * of statements representing the minimum set of nodes needed to extract the entire span. This - * process may fail, in which case a set of errors is returned instead (these are currently - * not shown to the user, but can be used by us diagnostically) + * process may fail, in which case a set of errors is returned instead. These errors are shown to + * users if they have the provideRefactorNotApplicableReason option set. */ // exported only for tests - export function getRangeToExtract(sourceFile: SourceFile, span: TextSpan, considerEmptySpans = true): RangeToExtract { + export function getRangeToExtract(sourceFile: SourceFile, span: TextSpan, invoked = true): RangeToExtract { const { length } = span; - if (length === 0 && !considerEmptySpans) { + if (length === 0 && !invoked) { return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] }; } - const cursorRequest = length === 0 && considerEmptySpans; + const cursorRequest = length === 0 && invoked; + + const startToken = findFirstNonJsxWhitespaceToken(sourceFile, span.start); + const endToken = findTokenOnLeftOfPosition(sourceFile, textSpanEnd(span)); + /* If the refactoring command is invoked through a keyboard action it's safe to assume that the user is actively looking for + refactoring actions at the span location. As they may not know the exact range that will trigger a refactoring, we expand the + searched span to cover a real node range making it more likely that something useful will show up. */ + const adjustedSpan = startToken && endToken && invoked ? getAdjustedSpanFromNodes(startToken, endToken, sourceFile) : span; // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span. // This may fail (e.g. you select two statements in the root of a source file) - const startToken = getTokenAtPosition(sourceFile, span.start); - const start = cursorRequest ? getExtractableParent(startToken): getParentNodeInSpan(startToken, sourceFile, span); + const start = cursorRequest ? getExtractableParent(startToken): getParentNodeInSpan(startToken, sourceFile, adjustedSpan); + // Do the same for the ending position - const endToken = findTokenOnLeftOfPosition(sourceFile, textSpanEnd(span)); - const end = cursorRequest ? start : getParentNodeInSpan(endToken, sourceFile, span); + const end = cursorRequest ? start : getParentNodeInSpan(endToken, sourceFile, adjustedSpan); const declarations: Symbol[] = []; @@ -295,6 +300,10 @@ namespace ts.refactor.extractSymbol { return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } + if (isJSDoc(start)) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractJSDoc)] }; + } + if (start.parent !== end.parent) { // start and end nodes belong to different subtrees return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; @@ -332,10 +341,6 @@ namespace ts.refactor.extractSymbol { return { targetRange: { range: statements, facts: rangeFacts, declarations } }; } - if (isJSDoc(start)) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractJSDoc)] }; - } - if (isReturnStatement(start) && !start.expression) { // Makes no sense to extract an expression-less return statement. return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; @@ -605,6 +610,19 @@ namespace ts.refactor.extractSymbol { } } + /** + * Includes the final semicolon so that the span covers statements in cases where it would otherwise + * only cover the declaration list. + */ + function getAdjustedSpanFromNodes(startNode: Node, endNode: Node, sourceFile: SourceFile): TextSpan { + const start = startNode.getStart(sourceFile); + let end = endNode.getEnd(); + if (sourceFile.text.charCodeAt(end) === CharacterCodes.semicolon) { + end++; + } + return { start, length: end - start }; + } + function getStatementOrExpressionRange(node: Node): Statement[] | Expression | undefined { if (isStatement(node)) { return [node]; diff --git a/src/services/refactors/extractType.ts b/src/services/refactors/extractType.ts index ab85bb198cc62..549ff99f4d7ac 100644 --- a/src/services/refactors/extractType.ts +++ b/src/services/refactors/extractType.ts @@ -145,7 +145,7 @@ namespace ts.refactor { if (isTypeReferenceNode(node)) { if (isIdentifier(node.typeName)) { const symbol = checker.resolveName(node.typeName.text, node.typeName, SymbolFlags.TypeParameter, /* excludeGlobals */ true); - if (symbol) { + if (symbol?.declarations) { const declaration = cast(first(symbol.declarations), isTypeParameterDeclaration); if (rangeContainsSkipTrivia(statement, declaration, file) && !rangeContainsSkipTrivia(selection, declaration, file)) { pushIfUnique(result, declaration); @@ -168,7 +168,7 @@ namespace ts.refactor { else if (isTypeQueryNode(node)) { if (isIdentifier(node.exprName)) { const symbol = checker.resolveName(node.exprName.text, node.exprName, SymbolFlags.Value, /* excludeGlobals */ false); - if (symbol && rangeContainsSkipTrivia(statement, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) { + if (symbol?.valueDeclaration && rangeContainsSkipTrivia(statement, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) { return true; } } diff --git a/src/services/refactors/inferFunctionReturnType.ts b/src/services/refactors/inferFunctionReturnType.ts index 4fad099cad029..919aaf5413dfa 100644 --- a/src/services/refactors/inferFunctionReturnType.ts +++ b/src/services/refactors/inferFunctionReturnType.ts @@ -17,8 +17,7 @@ namespace ts.refactor.inferFunctionReturnType { function getEditsForAction(context: RefactorContext): RefactorEditInfo | undefined { const info = getInfo(context); if (info && !isRefactorErrorInfo(info)) { - const edits = textChanges.ChangeTracker.with(context, t => - t.tryInsertTypeAnnotation(context.file, info.declaration, info.returnTypeNode)); + const edits = textChanges.ChangeTracker.with(context, t => doChange(context.file, t, info.declaration, info.returnTypeNode)); return { renameFilename: undefined, renameLocation: undefined, edits }; } return undefined; @@ -55,11 +54,26 @@ namespace ts.refactor.inferFunctionReturnType { returnTypeNode: TypeNode; } + function doChange(sourceFile: SourceFile, changes: textChanges.ChangeTracker, declaration: ConvertibleDeclaration, typeNode: TypeNode) { + const closeParen = findChildOfKind(declaration, SyntaxKind.CloseParenToken, sourceFile); + const needParens = isArrowFunction(declaration) && closeParen === undefined; + const endNode = needParens ? first(declaration.parameters) : closeParen; + if (endNode) { + if (needParens) { + changes.insertNodeBefore(sourceFile, endNode, factory.createToken(SyntaxKind.OpenParenToken)); + changes.insertNodeAfter(sourceFile, endNode, factory.createToken(SyntaxKind.CloseParenToken)); + } + changes.insertNodeAt(sourceFile, endNode.end, typeNode, { prefix: ": " }); + } + } + function getInfo(context: RefactorContext): FunctionInfo | RefactorErrorInfo | undefined { if (isInJSFile(context.file) || !refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind)) return; const token = getTokenAtPosition(context.file, context.startPosition); - const declaration = findAncestor(token, isConvertibleDeclaration); + const declaration = findAncestor(token, n => + isBlock(n) || n.parent && isArrowFunction(n.parent) && (n.kind === SyntaxKind.EqualsGreaterThanToken || n.parent.body === n) ? "quit" : + isConvertibleDeclaration(n)) as ConvertibleDeclaration | undefined; if (!declaration || !declaration.body || declaration.type) { return { error: getLocaleSpecificMessage(Diagnostics.Return_type_must_be_inferred_from_a_function) }; } @@ -68,7 +82,7 @@ namespace ts.refactor.inferFunctionReturnType { const returnType = tryGetReturnType(typeChecker, declaration); if (!returnType) { return { error: getLocaleSpecificMessage(Diagnostics.Could_not_determine_function_return_type) }; - }; + } const returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, NodeBuilderFlags.NoTruncation); if (returnTypeNode) { diff --git a/src/services/refactors/moveToNewFile.ts b/src/services/refactors/moveToNewFile.ts index be93b513244e1..ad707f8d2e7ba 100644 --- a/src/services/refactors/moveToNewFile.ts +++ b/src/services/refactors/moveToNewFile.ts @@ -443,6 +443,9 @@ namespace ts.refactor { const oldFileNamedImports: string[] = []; const markSeenTop = nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`. newFileImportsFromOldFile.forEach(symbol => { + if (!symbol.declarations) { + return; + } for (const decl of symbol.declarations) { if (!isTopLevelDeclaration(decl)) continue; const name = nameOfTopLevelDeclaration(decl); diff --git a/src/services/rename.ts b/src/services/rename.ts index e75de5151cc5a..51eacc56a78b3 100644 --- a/src/services/rename.ts +++ b/src/services/rename.ts @@ -3,7 +3,7 @@ namespace ts.Rename { export function getRenameInfo(program: Program, sourceFile: SourceFile, position: number, options?: RenameInfoOptions): RenameInfo { const node = getAdjustedRenameLocation(getTouchingPropertyName(sourceFile, position)); if (nodeIsEligibleForRename(node)) { - const renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, declaration => program.isSourceFileDefaultLibrary(declaration.getSourceFile()), options); + const renameInfo = getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, program, options); if (renameInfo) { return renameInfo; } @@ -11,7 +11,7 @@ namespace ts.Rename { return getRenameInfoError(Diagnostics.You_cannot_rename_this_element); } - function getRenameInfoForNode(node: Node, typeChecker: TypeChecker, sourceFile: SourceFile, isDefinedInLibraryFile: (declaration: Node) => boolean, options?: RenameInfoOptions): RenameInfo | undefined { + function getRenameInfoForNode(node: Node, typeChecker: TypeChecker, sourceFile: SourceFile, program: Program, options?: RenameInfoOptions): RenameInfo | undefined { const symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) { if (isStringLiteralLike(node)) { @@ -33,7 +33,7 @@ namespace ts.Rename { if (!declarations || declarations.length === 0) return; // Disallow rename for elements that are defined in the standard TypeScript library. - if (declarations.some(isDefinedInLibraryFile)) { + if (declarations.some(declaration => isDefinedInLibraryFile(program, declaration))) { return getRenameInfoError(Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } @@ -55,12 +55,17 @@ namespace ts.Rename { return getRenameInfoSuccess(displayName, fullDisplayName, kind, SymbolDisplay.getSymbolModifiers(typeChecker,symbol), node, sourceFile); } + function isDefinedInLibraryFile(program: Program, declaration: Node) { + const sourceFile = declaration.getSourceFile(); + return program.isSourceFileDefaultLibrary(sourceFile) && fileExtensionIs(sourceFile.fileName, Extension.Dts); + } + 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); + const moduleSourceFile = moduleSymbol.declarations && find(moduleSymbol.declarations, isSourceFile); if (!moduleSourceFile) return undefined; const withoutIndex = endsWith(node.text, "/index") || endsWith(node.text, "/index.js") ? undefined : tryRemoveSuffix(removeFileExtension(moduleSourceFile.fileName), "/index"); const name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; diff --git a/src/services/services.ts b/src/services/services.ts index 1463d81dfdecc..08f6c8897a29d 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -292,14 +292,11 @@ namespace ts { // Undefined is used to indicate the value has not been computed. If, after computing, the // symbol has no doc comment, then the empty array will be returned. documentationComment?: SymbolDisplayPart[]; + tags?: JSDocTagInfo[]; // same contextualGetAccessorDocumentationComment?: SymbolDisplayPart[]; contextualSetAccessorDocumentationComment?: SymbolDisplayPart[]; - // Undefined is used to indicate the value has not been computed. If, after computing, the - // symbol has no JSDoc tags, then the empty array will be returned. - tags?: JSDocTagInfo[]; - constructor(flags: SymbolFlags, name: __String) { this.flags = flags; this.escapedName = name; @@ -359,9 +356,9 @@ namespace ts { } } - getJsDocTags(): JSDocTagInfo[] { + getJsDocTags(checker?: TypeChecker): JSDocTagInfo[] { if (this.tags === undefined) { - this.tags = JsDoc.getJsDocTagsFromDeclarations(this.declarations); + this.tags = JsDoc.getJsDocTagsFromDeclarations(this.declarations, checker); } return this.tags; @@ -521,10 +518,7 @@ namespace ts { // Undefined is used to indicate the value has not been computed. If, after computing, the // symbol has no doc comment, then the empty array will be returned. documentationComment?: SymbolDisplayPart[]; - - // Undefined is used to indicate the value has not been computed. If, after computing, the - // symbol has no doc comment, then the empty array will be returned. - jsDocTags?: JSDocTagInfo[]; + jsDocTags?: JSDocTagInfo[]; // same constructor(checker: TypeChecker, flags: SignatureFlags) { this.checker = checker; @@ -550,7 +544,7 @@ namespace ts { getJsDocTags(): JSDocTagInfo[] { if (this.jsDocTags === undefined) { - this.jsDocTags = this.declaration ? getJsDocTags([this.declaration], this.checker) : []; + this.jsDocTags = this.declaration ? getJsDocTagsOfSignature(this.declaration, this.checker) : []; } return this.jsDocTags; } @@ -565,15 +559,13 @@ namespace ts { return getJSDocTags(node).some(tag => tag.tagName.text === "inheritDoc"); } - function getJsDocTags(declarations: Declaration[], checker: TypeChecker): JSDocTagInfo[] { - let tags = JsDoc.getJsDocTagsFromDeclarations(declarations); - if (tags.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - forEachUnique(declarations, declaration => { - const inheritedTags = findBaseOfDeclaration(checker, declaration, symbol => symbol.getJsDocTags()); - if (inheritedTags) { - tags = [...inheritedTags, ...tags]; - } - }); + function getJsDocTagsOfSignature(declaration: Declaration, checker: TypeChecker): JSDocTagInfo[] { + let tags = JsDoc.getJsDocTagsFromDeclarations([declaration], checker); + if (tags.length === 0 || hasJSDocInheritDocTag(declaration)) { + const inheritedTags = findBaseOfDeclaration(checker, declaration, symbol => symbol.declarations?.length === 1 ? symbol.getJsDocTags() : undefined); + if (inheritedTags) { + tags = [...inheritedTags, ...tags]; + } } return tags; } @@ -581,18 +573,24 @@ namespace ts { function getDocumentationComment(declarations: readonly Declaration[] | undefined, checker: TypeChecker | undefined): SymbolDisplayPart[] { if (!declarations) return emptyArray; - let doc = JsDoc.getJsDocCommentsFromDeclarations(declarations); + let doc = JsDoc.getJsDocCommentsFromDeclarations(declarations, checker); if (checker && (doc.length === 0 || declarations.some(hasJSDocInheritDocTag))) { - forEachUnique(declarations, declaration => { - const inheritedDocs = findBaseOfDeclaration(checker, declaration, symbol => symbol.getDocumentationComment(checker)); + const seenSymbols = new Set(); + for (const declaration of declarations) { + const inheritedDocs = findBaseOfDeclaration(checker, declaration, symbol => { + if (!seenSymbols.has(symbol)) { + seenSymbols.add(symbol); + return symbol.getDocumentationComment(checker); + } + }); // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(lineBreakPart(), doc); - }); + } } return doc; } - function findBaseOfDeclaration(checker: TypeChecker, declaration: Declaration, cb: (symbol: Symbol) => T[]): T[] | undefined { + function findBaseOfDeclaration(checker: TypeChecker, declaration: Declaration, cb: (symbol: Symbol) => T[] | undefined): T[] | undefined { return firstDefined(declaration.parent ? getAllSuperTypeNodes(declaration.parent) : emptyArray, superTypeNode => { const symbol = checker.getPropertyOfType(checker.getTypeAtLocation(superTypeNode), declaration.symbol.name); return symbol ? cb(symbol) : undefined; @@ -940,7 +938,6 @@ namespace ts { // the set of scripts handled by the host changes. class HostCache { private fileNameToEntry: ESMap; - private _compilationSettings: CompilerOptions; private currentDirectory: string; constructor(private host: LanguageServiceHost, getCanonicalFileName: GetCanonicalFileName) { @@ -953,17 +950,6 @@ namespace ts { for (const fileName of rootFileNames) { this.createEntry(fileName, toPath(fileName, this.currentDirectory, getCanonicalFileName)); } - - // store the compilation settings - this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); - } - - public compilationSettings() { - return this._compilationSettings; - } - - public getProjectReferences(): readonly ProjectReference[] | undefined { - return this.host.getProjectReferences && this.host.getProjectReferences(); } private createEntry(fileName: string, path: Path) { @@ -1310,12 +1296,23 @@ namespace ts { // Get a fresh cache of the host information let hostCache: HostCache | undefined = new HostCache(host, getCanonicalFileName); const rootFileNames = hostCache.getRootFileNames(); + const newSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); const hasInvalidatedResolution: HasInvalidatedResolution = host.hasInvalidatedResolution || returnFalse; const hasChangedAutomaticTypeDirectiveNames = maybeBind(host, host.hasChangedAutomaticTypeDirectiveNames); - const projectReferences = hostCache.getProjectReferences(); + const projectReferences = host.getProjectReferences?.(); + let parsedCommandLines: ESMap | undefined; + const parseConfigHost: ParseConfigFileHost = { + useCaseSensitiveFileNames, + fileExists, + readFile, + readDirectory, + trace: maybeBind(host, host.trace), + getCurrentDirectory: () => currentDirectory, + onUnRecoverableConfigFileDiagnostic: noop, + }; // If the program is already up-to-date, we can reuse it - if (isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), (_path, fileName) => host.getScriptVersion(fileName), fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { + if (isProgramUptoDate(program, rootFileNames, newSettings, (_path, fileName) => host.getScriptVersion(fileName), fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { return; } @@ -1325,8 +1322,6 @@ namespace ts { // the program points to old source files that have been invalidated because of // incremental parsing. - const newSettings = hostCache.compilationSettings(); - // Now create a new compiler const compilerHost: CompilerHost = { getSourceFile: getOrCreateSourceFile, @@ -1335,7 +1330,7 @@ namespace ts { getCanonicalFileName, useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, getNewLine: () => getNewLineCharacter(newSettings, () => getNewLineOrDefaultFromHost(host)), - getDefaultLibFileName: (options) => host.getDefaultLibFileName(options), + getDefaultLibFileName: options => host.getDefaultLibFileName(options), writeFile: noop, getCurrentDirectory: () => currentDirectory, fileExists, @@ -1348,17 +1343,16 @@ namespace ts { getDirectories: path => { return host.getDirectories ? host.getDirectories(path) : []; }, - readDirectory(path, extensions, exclude, include, depth) { - Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); - return host.readDirectory!(path, extensions, exclude, include, depth); - }, + readDirectory, onReleaseOldSourceFile, + onReleaseParsedCommandLine, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, - trace: maybeBind(host, host.trace), + trace: parseConfigHost.trace, resolveModuleNames: maybeBind(host, host.resolveModuleNames), resolveTypeReferenceDirectives: maybeBind(host, host.resolveTypeReferenceDirectives), useSourceOfProjectReferenceRedirect: maybeBind(host, host.useSourceOfProjectReferenceRedirect), + getParsedCommandLine, }; host.setCompilerHost?.(compilerHost); @@ -1375,6 +1369,7 @@ namespace ts { // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. // It needs to be cleared to allow all collected snapshots to be released hostCache = undefined; + parsedCommandLines = undefined; // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during @@ -1386,6 +1381,42 @@ namespace ts { program.getTypeChecker(); return; + function getParsedCommandLine(fileName: string): ParsedCommandLine | undefined { + const path = toPath(fileName, currentDirectory, getCanonicalFileName); + const existing = parsedCommandLines?.get(path); + if (existing !== undefined) return existing || undefined; + + const result = host.getParsedCommandLine ? + host.getParsedCommandLine(fileName) : + getParsedCommandLineOfConfigFileUsingSourceFile(fileName); + (parsedCommandLines ||= new Map()).set(path, result || false); + return result; + } + + function getParsedCommandLineOfConfigFileUsingSourceFile(configFileName: string): ParsedCommandLine | undefined { + const result = getOrCreateSourceFile(configFileName, ScriptTarget.JSON) as JsonSourceFile | undefined; + if (!result) return undefined; + result.path = toPath(configFileName, currentDirectory, getCanonicalFileName); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; + return parseJsonSourceFileConfigFileContent( + result, + parseConfigHost, + getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), + /*optionsToExtend*/ undefined, + getNormalizedAbsolutePath(configFileName, currentDirectory), + ); + } + + function onReleaseParsedCommandLine(configFileName: string, oldResolvedRef: ResolvedProjectReference | undefined, oldOptions: CompilerOptions) { + if (host.getParsedCommandLine) { + host.onReleaseParsedCommandLine?.(configFileName, oldResolvedRef, oldOptions); + } + else if (oldResolvedRef) { + onReleaseOldSourceFile(oldResolvedRef.sourceFile, oldOptions); + } + } + function fileExists(fileName: string): boolean { const path = toPath(fileName, currentDirectory, getCanonicalFileName); const entry = hostCache && hostCache.getEntryByPath(path); @@ -1404,11 +1435,16 @@ namespace ts { return host.readFile && host.readFile(fileName); } + function readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number) { + Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory!(path, extensions, exclude, include, depth); + } + // Release any files we have acquired in the old program but are // not part of the new program. function onReleaseOldSourceFile(oldSourceFile: SourceFile, oldOptions: CompilerOptions) { const oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind); } function getOrCreateSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined { @@ -1457,9 +1493,13 @@ namespace ts { // We do not support the scenario where a host can modify a registered // file's script kind, i.e. in one project some file is treated as ".ts" // and in another as ".js" - Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind."); - - return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + if (hostFileInformation.scriptKind === oldSourceFile.scriptKind) { + return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); + } + else { + // Release old source file and fall through to aquire new file with new script kind + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()), oldSourceFile.scriptKind); + } } // We didn't already have the file. Fall through and acquire it from the registry. @@ -1495,7 +1535,7 @@ namespace ts { // Use paths to ensure we are using correct key and paths as document registry could be created with different current directory than host const key = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()); forEach(program.getSourceFiles(), f => - documentRegistry.releaseDocumentWithKey(f.resolvedPath, key)); + documentRegistry.releaseDocumentWithKey(f.resolvedPath, key, f.scriptKind)); program = undefined!; // TODO: GH#18217 } host = undefined!; @@ -1558,14 +1598,14 @@ namespace ts { options.triggerCharacter); } - function getCompletionEntryDetails(fileName: string, position: number, name: string, formattingOptions: FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences = emptyOptions): CompletionEntryDetails | undefined { + function getCompletionEntryDetails(fileName: string, position: number, name: string, formattingOptions: FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences = emptyOptions, data?: CompletionEntryData): CompletionEntryDetails | undefined { synchronizeHostData(); return Completions.getCompletionEntryDetails( program, log, getValidSourceFile(fileName), position, - { name, source }, + { name, source, data }, host, (formattingOptions && formatting.getFormatContext(formattingOptions, host))!, // TODO: GH#18217 preferences, @@ -1600,7 +1640,7 @@ namespace ts { textSpan: createTextSpanFromNode(nodeForQuickInfo, sourceFile), displayParts: typeChecker.runWithCancellationToken(cancellationToken, typeChecker => typeToDisplayParts(typeChecker, type, getContainerNode(nodeForQuickInfo))), documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type.symbol ? type.symbol.getJsDocTags() : undefined + tags: type.symbol ? type.symbol.getJsDocTags(typeChecker) : undefined }; } @@ -1621,13 +1661,16 @@ namespace ts { if (isNewExpression(node.parent) && node.pos === node.parent.pos) { return node.parent.expression; } + if (isNamedTupleMember(node.parent) && node.pos === node.parent.pos) { + return node.parent; + } return node; } function shouldGetType(sourceFile: SourceFile, node: Node, position: number): boolean { switch (node.kind) { case SyntaxKind.Identifier: - return !isLabelName(node) && !isTagName(node); + return !isLabelName(node) && !isTagName(node) && !isConstTypeReference(node.parent); case SyntaxKind.PropertyAccessExpression: case SyntaxKind.QualifiedName: // Don't return quickInfo if inside the comment in `a/**/.b` @@ -1635,6 +1678,7 @@ namespace ts { case SyntaxKind.ThisKeyword: case SyntaxKind.ThisType: case SyntaxKind.SuperKeyword: + case SyntaxKind.NamedTupleMember: return true; default: return false; @@ -1838,17 +1882,8 @@ namespace ts { return NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken); } - function isTsOrTsxFile(fileName: string): boolean { - const kind = getScriptKind(fileName, host); - return kind === ScriptKind.TS || kind === ScriptKind.TSX; - } - function getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; function getSemanticClassifications(fileName: string, span: TextSpan, format?: SemanticClassificationFormat): ClassifiedSpan[] | ClassifiedSpan2020[] { - if (!isTsOrTsxFile(fileName)) { - // do not run semantic classification on non-ts-or-tsx files - return []; - } synchronizeHostData(); const responseFormat = format || SemanticClassificationFormat.Original; @@ -1861,10 +1896,6 @@ namespace ts { } function getEncodedSemanticClassifications(fileName: string, span: TextSpan, format?: SemanticClassificationFormat): Classifications { - if (!isTsOrTsxFile(fileName)) { - // do not run semantic classification on non-ts-or-tsx files - return { spans: [], endOfLineState: EndOfLineState.None }; - } synchronizeHostData(); const responseFormat = format || SemanticClassificationFormat.Original; @@ -1973,13 +2004,13 @@ namespace ts { return codefix.getAllFixes({ fixId, sourceFile, program, host, cancellationToken, formatContext, preferences }); } - function organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences = emptyOptions): readonly FileTextChanges[] { + function organizeImports(args: OrganizeImportsArgs, formatOptions: FormatCodeSettings, preferences: UserPreferences = emptyOptions): readonly FileTextChanges[] { synchronizeHostData(); - Debug.assert(scope.type === "file"); - const sourceFile = getValidSourceFile(scope.fileName); + Debug.assert(args.type === "file"); + const sourceFile = getValidSourceFile(args.fileName); const formatContext = formatting.getFormatContext(formatOptions, host); - return OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); + return OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, args.skipDestructiveCodeActions); } function getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences = emptyOptions): readonly FileTextChanges[] { @@ -2492,6 +2523,17 @@ namespace ts { return refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName); } + function toLineColumnOffset(fileName: string, position: number): LineAndCharacter { + // Go to Definition supports returning a zero-length span at position 0 for + // non-existent files. We need to special-case the conversion of position 0 + // to avoid a crash trying to get the text for that file, since this function + // otherwise assumes that 'fileName' is the name of a file that exists. + if (position === 0) { + return { line: 0, character: 0 }; + } + return sourceMapper.toLineColumnOffset(fileName, position); + } + function prepareCallHierarchy(fileName: string, position: number): CallHierarchyItem | CallHierarchyItem[] | undefined { synchronizeHostData(); const declarations = CallHierarchy.resolveCallHierarchyDeclaration(program, getTouchingPropertyName(getValidSourceFile(fileName), position)); @@ -2567,7 +2609,7 @@ namespace ts { getAutoImportProvider, getApplicableRefactors, getEditsForRefactor, - toLineColumnOffset: sourceMapper.toLineColumnOffset, + toLineColumnOffset, getSourceMapper: () => sourceMapper, clearSourceMapperCache: () => sourceMapper.clearCache(), prepareCallHierarchy, diff --git a/src/services/shims.ts b/src/services/shims.ts index e986820765ad9..fa0bdf459b972 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -150,7 +150,7 @@ namespace ts { getEncodedSemanticClassifications(fileName: string, start: number, length: number, format?: SemanticClassificationFormat): string; getCompletionsAtPosition(fileName: string, position: number, preferences: UserPreferences | undefined): string; - getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: string/*Services.FormatCodeOptions*/ | undefined, source: string | undefined, preferences: UserPreferences | undefined): string; + getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: string/*Services.FormatCodeOptions*/ | undefined, source: string | undefined, preferences: UserPreferences | undefined, data: CompletionEntryData | undefined): string; getQuickInfoAtPosition(fileName: string, position: number): string; @@ -962,12 +962,12 @@ namespace ts { } /** Get a string based representation of a completion list entry details */ - public getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: string/*Services.FormatCodeOptions*/ | undefined, source: string | undefined, preferences: UserPreferences | undefined) { + public getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: string/*Services.FormatCodeOptions*/ | undefined, source: string | undefined, preferences: UserPreferences | undefined, data: CompletionEntryData | undefined) { return this.forwardJSONCall( `getCompletionEntryDetails('${fileName}', ${position}, '${entryName}')`, () => { const localOptions: FormatCodeOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions); - return this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences); + return this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences, data); } ); } @@ -1326,7 +1326,7 @@ namespace ts { public close(): void { // Forget all the registered shims clear(this._shims); - this.documentRegistry = undefined!; + this.documentRegistry = undefined; } public registerShim(shim: Shim): void { diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index 9eb93800605ec..8ab4fa39ba0b9 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -574,7 +574,7 @@ namespace ts.SignatureHelp { const parameters = typeParameters.map(t => createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer)); const documentation = symbol.getDocumentationComment(checker); - const tags = symbol.getJsDocTags(); + const tags = symbol.getJsDocTags(checker); const prefixDisplayParts = [...typeSymbolDisplay, punctuationPart(SyntaxKind.LessThanToken)]; return { isVariadic: false, prefixDisplayParts, suffixDisplayParts: [punctuationPart(SyntaxKind.GreaterThanToken)], separatorDisplayParts, parameters, documentation, tags }; } diff --git a/src/services/smartSelection.ts b/src/services/smartSelection.ts index 3fcab16695979..6cd5c8f94d854 100644 --- a/src/services/smartSelection.ts +++ b/src/services/smartSelection.ts @@ -13,10 +13,16 @@ namespace ts.SmartSelectionRange { const prevNode: Node | undefined = children[i - 1]; const node: Node = children[i]; const nextNode: Node | undefined = children[i + 1]; + if (getTokenPosOfNode(node, sourceFile, /*includeJsDoc*/ true) > pos) { break outer; } + const comment = singleOrUndefined(getTrailingCommentRanges(sourceFile.text, node.end)); + if (comment && comment.kind === SyntaxKind.SingleLineCommentTrivia) { + pushSelectionCommentRange(comment.pos, comment.end); + } + if (positionShouldSnapToNode(sourceFile, pos, node)) { // 1. Blocks are effectively redundant with SyntaxLists. // 2. TemplateSpans, along with the SyntaxLists containing them, are a somewhat unintuitive grouping @@ -89,6 +95,16 @@ namespace ts.SmartSelectionRange { } } } + + function pushSelectionCommentRange(start: number, end: number): void { + pushSelectionRange(start, end); + + let pos = start; + while (sourceFile.text.charCodeAt(pos) === CharacterCodes.slash) { + pos++; + } + pushSelectionRange(pos, end); + } } /** diff --git a/src/services/stringCompletions.ts b/src/services/stringCompletions.ts index de823ad951d0e..3ae41525c58da 100644 --- a/src/services/stringCompletions.ts +++ b/src/services/stringCompletions.ts @@ -7,12 +7,12 @@ namespace ts.Completions.StringCompletions { } if (isInString(sourceFile, position, contextToken)) { if (!contextToken || !isStringLiteralLike(contextToken)) return undefined; - const entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); - return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, preferences); + const entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); + return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, options, preferences); } } - function convertStringLiteralCompletions(completion: StringLiteralCompletion | undefined, contextToken: StringLiteralLike, sourceFile: SourceFile, checker: TypeChecker, log: Log, preferences: UserPreferences): CompletionInfo | undefined { + function convertStringLiteralCompletions(completion: StringLiteralCompletion | undefined, contextToken: StringLiteralLike, sourceFile: SourceFile, checker: TypeChecker, log: Log, options: CompilerOptions, preferences: UserPreferences): CompletionInfo | undefined { if (completion === undefined) { return undefined; } @@ -33,7 +33,8 @@ namespace ts.Completions.StringCompletions { ScriptTarget.ESNext, log, CompletionKind.String, - preferences + preferences, + options, ); // Target will not be used, so arbitrary return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, optionalReplacementSpan, entries }; } @@ -52,9 +53,9 @@ namespace ts.Completions.StringCompletions { } } - export function getStringLiteralCompletionDetails(name: string, sourceFile: SourceFile, position: number, contextToken: Node | undefined, checker: TypeChecker, options: CompilerOptions, host: LanguageServiceHost, cancellationToken: CancellationToken) { + export function getStringLiteralCompletionDetails(name: string, sourceFile: SourceFile, position: number, contextToken: Node | undefined, checker: TypeChecker, options: CompilerOptions, host: LanguageServiceHost, cancellationToken: CancellationToken, preferences: UserPreferences) { if (!contextToken || !isStringLiteralLike(contextToken)) return undefined; - const completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); + const completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken); } @@ -109,7 +110,7 @@ namespace ts.Completions.StringCompletions { readonly isNewIdentifier: boolean; } type StringLiteralCompletion = { readonly kind: StringLiteralCompletionKind.Paths, readonly paths: readonly PathCompletion[] } | StringLiteralCompletionsFromProperties | StringLiteralCompletionsFromTypes; - function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringLiteralLike, position: number, typeChecker: TypeChecker, compilerOptions: CompilerOptions, host: LanguageServiceHost): StringLiteralCompletion | undefined { + function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringLiteralLike, position: number, typeChecker: TypeChecker, compilerOptions: CompilerOptions, host: LanguageServiceHost, preferences: UserPreferences): StringLiteralCompletion | undefined { const parent = walkUpParentheses(node.parent); switch (parent.kind) { case SyntaxKind.LiteralType: { @@ -136,7 +137,7 @@ namespace ts.Completions.StringCompletions { } return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(objectType)); case SyntaxKind.ImportType: - return { kind: StringLiteralCompletionKind.Paths, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + return { kind: StringLiteralCompletionKind.Paths, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; case SyntaxKind.UnionType: { if (!isTypeReferenceNode(grandParent.parent)) { return undefined; @@ -201,7 +202,7 @@ namespace ts.Completions.StringCompletions { // import x = require("/*completion position*/"); // var y = require("/*completion position*/"); // export * from "/*completion position*/"; - return { kind: StringLiteralCompletionKind.Paths, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + return { kind: StringLiteralCompletionKind.Paths, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) }; default: return fromContextualType(); @@ -249,7 +250,7 @@ namespace ts.Completions.StringCompletions { function stringLiteralCompletionsFromProperties(type: Type | undefined): StringLiteralCompletionsFromProperties | undefined { return type && { kind: StringLiteralCompletionKind.Properties, - symbols: filter(type.getApparentProperties(), prop => !(prop.valueDeclaration && isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration))), + symbols: filter(type.getApparentProperties(), prop => !(prop.valueDeclaration && isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration))), hasIndexSignature: hasIndexSignature(type) }; } @@ -303,18 +304,18 @@ namespace ts.Completions.StringCompletions { Math.max(name.indexOf(directorySeparator), name.indexOf(altDirectorySeparator)) !== -1 ? { name, kind, extension, span: wholeSpan } : { name, kind, extension, span }); } - function getStringLiteralCompletionsFromModuleNames(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): readonly PathCompletion[] { - return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); + function getStringLiteralCompletionsFromModuleNames(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker, preferences: UserPreferences): readonly PathCompletion[] { + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker, preferences)); } - function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): readonly NameAndKind[] { + function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker, preferences: UserPreferences): readonly NameAndKind[] { const literalValue = normalizeSlashes(node.text); const scriptPath = sourceFile.path; const scriptDirectory = getDirectoryPath(scriptPath); return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (isRootedDiskPath(literalValue) || isUrl(literalValue)) - ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) + ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, preferences) : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); } @@ -325,8 +326,8 @@ namespace ts.Completions.StringCompletions { function getExtensionOptions(compilerOptions: CompilerOptions, includeExtensions = false): ExtensionOptions { return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions }; } - function getCompletionEntriesForRelativeModules(literalValue: string, scriptDirectory: string, compilerOptions: CompilerOptions, host: LanguageServiceHost, scriptPath: Path) { - const extensionOptions = getExtensionOptions(compilerOptions); + function getCompletionEntriesForRelativeModules(literalValue: string, scriptDirectory: string, compilerOptions: CompilerOptions, host: LanguageServiceHost, scriptPath: Path, preferences: UserPreferences) { + const extensionOptions = getExtensionOptions(compilerOptions, preferences.importModuleSpecifierEnding === "js"); if (compilerOptions.rootDirs) { return getCompletionEntriesForDirectoryFragmentWithRootDirs( compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); diff --git a/src/services/suggestionDiagnostics.ts b/src/services/suggestionDiagnostics.ts index a002f8533e260..ade23ff29e762 100644 --- a/src/services/suggestionDiagnostics.ts +++ b/src/services/suggestionDiagnostics.ts @@ -57,7 +57,7 @@ namespace ts { } } - if (isFunctionLikeDeclaration(node)) { + if (canBeConvertedToAsync(node)) { addConvertToAsyncFunctionDiagnostics(node, checker, diags); } node.forEachChild(check); @@ -118,10 +118,9 @@ namespace ts { returnsPromise(node, checker); } - function returnsPromise(node: FunctionLikeDeclaration, checker: TypeChecker): boolean { - const functionType = checker.getTypeAtLocation(node); - const callSignatures = checker.getSignaturesOfType(functionType, SignatureKind.Call); - const returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; + export function returnsPromise(node: FunctionLikeDeclaration, checker: TypeChecker): boolean { + const signature = checker.getSignatureFromDeclaration(node); + const returnType = signature ? checker.getReturnTypeOfSignature(signature) : undefined; return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); } @@ -214,4 +213,16 @@ namespace ts { return false; } + + export function canBeConvertedToAsync(node: Node): node is FunctionDeclaration | MethodDeclaration | FunctionExpression | ArrowFunction { + switch (node.kind) { + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + return true; + default: + return false; + } + } } diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index 19bfaba4499ef..52085ef72c564 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -174,7 +174,7 @@ namespace ts.SymbolDisplay { } let signature: Signature | undefined; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (location.parent && location.parent.kind === SyntaxKind.PropertyAccessExpression) { const right = (location.parent).name; @@ -197,13 +197,13 @@ namespace ts.SymbolDisplay { } if (callExpressionLike) { - signature = typeChecker.getResolvedSignature(callExpressionLike)!; // TODO: GH#18217 + signature = typeChecker.getResolvedSignature(callExpressionLike); // TODO: GH#18217 const useConstructSignatures = callExpressionLike.kind === SyntaxKind.NewExpression || (isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === SyntaxKind.SuperKeyword); const allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); - if (!contains(allSignatures, signature.target) && !contains(allSignatures, signature)) { + if (signature && !contains(allSignatures, signature.target) && !contains(allSignatures, signature)) { // Get the first signature if there is one -- allSignatures may contain // either the original signature or its target, so check for either signature = allSignatures.length ? allSignatures[0] : undefined; @@ -278,7 +278,7 @@ namespace ts.SymbolDisplay { if (locationIsSymbolDeclaration) { const allSignatures = functionDeclaration.kind === SyntaxKind.Constructor ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { - signature = typeChecker.getSignatureFromDeclaration(functionDeclaration)!; // TODO: GH#18217 + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); // TODO: GH#18217 } else { signature = allSignatures[0]; @@ -294,8 +294,9 @@ namespace ts.SymbolDisplay { addPrefixForAnyFunctionOrVar(functionDeclaration.kind === SyntaxKind.CallSignature && !(type.symbol.flags & SymbolFlags.TypeLiteral || type.symbol.flags & SymbolFlags.ObjectLiteral) ? type.symbol : symbol, symbolKind); } - - addSignatureDisplayParts(signature, allSignatures); + if (signature) { + addSignatureDisplayParts(signature, allSignatures); + } hasAddedSymbolInfo = true; hasMultipleSignatures = allSignatures.length > 1; } @@ -401,8 +402,8 @@ namespace ts.SymbolDisplay { if (symbolFlags & SymbolFlags.EnumMember) { symbolKind = ScriptElementKind.enumMemberElement; addPrefixForAnyFunctionOrVar(symbol, "enum member"); - const declaration = symbol.declarations[0]; - if (declaration.kind === SyntaxKind.EnumMember) { + const declaration = symbol.declarations?.[0]; + if (declaration?.kind === SyntaxKind.EnumMember) { const constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(spacePart()); @@ -441,27 +442,29 @@ namespace ts.SymbolDisplay { } else { documentationFromAlias = resolvedSymbol.getContextualDocumentationComment(resolvedNode, typeChecker); - tagsFromAlias = resolvedSymbol.getJsDocTags(); + tagsFromAlias = resolvedSymbol.getJsDocTags(typeChecker); } } } - switch (symbol.declarations[0].kind) { - case SyntaxKind.NamespaceExportDeclaration: - displayParts.push(keywordPart(SyntaxKind.ExportKeyword)); - displayParts.push(spacePart()); - displayParts.push(keywordPart(SyntaxKind.NamespaceKeyword)); - break; - case SyntaxKind.ExportAssignment: - displayParts.push(keywordPart(SyntaxKind.ExportKeyword)); - displayParts.push(spacePart()); - displayParts.push(keywordPart((symbol.declarations[0] as ExportAssignment).isExportEquals ? SyntaxKind.EqualsToken : SyntaxKind.DefaultKeyword)); - break; - case SyntaxKind.ExportSpecifier: - displayParts.push(keywordPart(SyntaxKind.ExportKeyword)); - break; - default: - displayParts.push(keywordPart(SyntaxKind.ImportKeyword)); + if (symbol.declarations) { + switch (symbol.declarations[0].kind) { + case SyntaxKind.NamespaceExportDeclaration: + displayParts.push(keywordPart(SyntaxKind.ExportKeyword)); + displayParts.push(spacePart()); + displayParts.push(keywordPart(SyntaxKind.NamespaceKeyword)); + break; + case SyntaxKind.ExportAssignment: + displayParts.push(keywordPart(SyntaxKind.ExportKeyword)); + displayParts.push(spacePart()); + displayParts.push(keywordPart((symbol.declarations[0] as ExportAssignment).isExportEquals ? SyntaxKind.EqualsToken : SyntaxKind.DefaultKeyword)); + break; + case SyntaxKind.ExportSpecifier: + displayParts.push(keywordPart(SyntaxKind.ExportKeyword)); + break; + default: + displayParts.push(keywordPart(SyntaxKind.ImportKeyword)); + } } displayParts.push(spacePart()); addFullSymbolName(symbol); @@ -556,7 +559,7 @@ namespace ts.SymbolDisplay { // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && forEach(symbol.parent.declarations, declaration => declaration.kind === SyntaxKind.SourceFile)) { + if (symbol.parent && symbol.declarations && forEach(symbol.parent.declarations, declaration => declaration.kind === SyntaxKind.SourceFile)) { for (const declaration of symbol.declarations) { if (!declaration.parent || declaration.parent.kind !== SyntaxKind.BinaryExpression) { continue; @@ -568,7 +571,7 @@ namespace ts.SymbolDisplay { } documentation = rhsSymbol.getDocumentationComment(typeChecker); - tags = rhsSymbol.getJsDocTags(); + tags = rhsSymbol.getJsDocTags(typeChecker); if (documentation.length > 0) { break; } @@ -577,7 +580,7 @@ namespace ts.SymbolDisplay { } if (tags.length === 0 && !hasMultipleSignatures) { - tags = symbol.getJsDocTags(); + tags = symbol.getJsDocTags(typeChecker); } if (documentation.length === 0 && documentationFromAlias) { diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index 566c4c8c0f272..0d55ef9848f5a 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -168,7 +168,7 @@ namespace ts.textChanges { return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) }; } - function getAdjustedStartPosition(sourceFile: SourceFile, node: Node, options: ConfigurableStart) { + function getAdjustedStartPosition(sourceFile: SourceFile, node: Node, options: ConfigurableStartEnd, hasTrailingComment = false) { const { leadingTriviaOption } = options; if (leadingTriviaOption === LeadingTriviaOption.Exclude) { return node.getStart(sourceFile); @@ -199,6 +199,17 @@ namespace ts.textChanges { // when b is deleted - we delete it return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start; } + + // if node has a trailing comments, use comment end position as the text has already been included. + if (hasTrailingComment) { + // Check first for leading comments as if the node is the first import, we want to exclude the trivia; + // otherwise we get the trailing comments. + const comment = getLeadingCommentRanges(sourceFile.text, fullStart)?.[0] || getTrailingCommentRanges(sourceFile.text, fullStart)?.[0]; + if (comment) { + return skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + } + } + // get start position of the line following the line that contains fullstart position // (but only if the fullstart isn't the very beginning of the file) const nextLineStart = fullStart > 0 ? 1 : 0; @@ -208,7 +219,38 @@ namespace ts.textChanges { return getStartPositionOfLine(getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } - function getAdjustedEndPosition(sourceFile: SourceFile, node: Node, options: ConfigurableEnd) { + /** Return the end position of a multiline comment of it is on another line; otherwise returns `undefined`; */ + function getEndPositionOfMultilineTrailingComment(sourceFile: SourceFile, node: Node, options: ConfigurableEnd): number | undefined { + const { end } = node; + const { trailingTriviaOption } = options; + if (trailingTriviaOption === TrailingTriviaOption.Include) { + // If the trailing comment is a multiline comment that extends to the next lines, + // return the end of the comment and track it for the next nodes to adjust. + const comments = getTrailingCommentRanges(sourceFile.text, end); + if (comments) { + const nodeEndLine = getLineOfLocalPosition(sourceFile, node.end); + for (const comment of comments) { + // Single line can break the loop as trivia will only be this line. + // Comments on subsequest lines are also ignored. + if (comment.kind === SyntaxKind.SingleLineCommentTrivia || getLineOfLocalPosition(sourceFile, comment.pos) > nodeEndLine) { + break; + } + + // Get the end line of the comment and compare against the end line of the node. + // If the comment end line position and the multiline comment extends to multiple lines, + // then is safe to return the end position. + const commentEndLine = getLineOfLocalPosition(sourceFile, comment.end); + if (commentEndLine > nodeEndLine) { + return skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + } + } + } + } + + return undefined; + } + + function getAdjustedEndPosition(sourceFile: SourceFile, node: Node, options: ConfigurableEnd): number { const { end } = node; const { trailingTriviaOption } = options; if (trailingTriviaOption === TrailingTriviaOption.Exclude) { @@ -222,6 +264,12 @@ namespace ts.textChanges { } return end; } + + const multilineEndPosition = getEndPositionOfMultilineTrailingComment(sourceFile, node, options); + if (multilineEndPosition) { + return multilineEndPosition; + } + const newEnd = skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))) @@ -236,14 +284,6 @@ namespace ts.textChanges { return !!candidate && !!node.parent && (candidate.kind === SyntaxKind.CommaToken || (candidate.kind === SyntaxKind.SemicolonToken && node.parent.kind === SyntaxKind.ObjectLiteralExpression)); } - function spaces(count: number) { - let s = ""; - for (let i = 0; i < count; i++) { - s += " "; - } - return s; - } - export interface TextChangesContext { host: LanguageServiceHost; formatContext: formatting.FormatContext; @@ -261,7 +301,7 @@ namespace ts.textChanges { export class ChangeTracker { private readonly changes: Change[] = []; private readonly newFiles: { readonly oldFile: SourceFile | undefined, readonly fileName: string, readonly statements: readonly (Statement | SyntaxKind.NewLineTrivia)[] }[] = []; - private readonly classesWithNodesInsertedAtStart = new Map(); // Set implemented as Map + private readonly classesWithNodesInsertedAtStart = new Map(); // Set implemented as Map private readonly deletedNodes: { readonly sourceFile: SourceFile, readonly node: Node | NodeArray }[] = []; public static fromContext(context: TextChangesContext): ChangeTracker { @@ -301,6 +341,18 @@ namespace ts.textChanges { this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options)); } + public deleteNodes(sourceFile: SourceFile, nodes: readonly Node[], options: ConfigurableStartEnd = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }, hasTrailingComment: boolean): void { + // When deleting multiple nodes we need to track if the end position is including multiline trailing comments. + for (const node of nodes) { + const pos = getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment); + const end = getAdjustedEndPosition(sourceFile, node, options); + + this.deleteRange(sourceFile, { pos, end }); + + hasTrailingComment = !!getEndPositionOfMultilineTrailingComment(sourceFile, node, options); + } + } + public deleteModifier(sourceFile: SourceFile, modifier: Modifier): void { this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); } @@ -345,6 +397,10 @@ namespace ts.textChanges { this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); } + public nodeHasTrailingComment(sourceFile: SourceFile, oldNode: Node, configurableEnd: ConfigurableEnd = useNonAdjustedPositions): boolean { + return !!getEndPositionOfMultilineTrailingComment(sourceFile, oldNode, configurableEnd); + } + private nextCommaToken(sourceFile: SourceFile, node: Node): Node | undefined { const next = findNextToken(node, node.parent, sourceFile); return next && next.kind === SyntaxKind.CommaToken ? next : undefined; @@ -505,6 +561,16 @@ namespace ts.textChanges { } } + public insertNodeAtConstructorStartAfterSuperCall(sourceFile: SourceFile, ctr: ConstructorDeclaration, newStatement: Statement): void { + const superCallStatement = find(ctr.body!.statements, stmt => isExpressionStatement(stmt) && isSuperCall(stmt.expression)); + if (!superCallStatement || !ctr.body!.multiLine) { + this.replaceConstructorBody(sourceFile, ctr, [...ctr.body!.statements, newStatement]); + } + else { + this.insertNodeAfter(sourceFile, superCallStatement, newStatement); + } + } + public insertNodeAtConstructorEnd(sourceFile: SourceFile, ctr: ConstructorDeclaration, newStatement: Statement): void { const lastStatement = lastOrUndefined(ctr.body!.statements); if (!lastStatement || !ctr.body!.multiLine) { @@ -717,49 +783,24 @@ namespace ts.textChanges { // a, b, c // create change for adding 'e' after 'a' as // - find start of next element after a (it is b) - // - use this start as start and end position in final change - // - build text of change by formatting the text of node + separator + whitespace trivia of b + // - use next element start as start and end position in final change + // - build text of change by formatting the text of node + whitespace trivia of b // in multiline case it will work as // a, // b, // c, // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#') - // a,* - // ***insertedtext# + // a, + // insertedtext# // ###b, // c, - // find line and character of the next element - const lineAndCharOfNextElement = getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart())); - // find line and character of the token that precedes next element (usually it is separator) - const lineAndCharOfNextToken = getLineAndCharacterOfPosition(sourceFile, nextToken.end); - let prefix: string | undefined; - let startPos: number; - if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) { - // next element is located on the same line with separator: - // a,$$$$b - // ^ ^ - // | |-next element - // |-separator - // where $$$ is some leading trivia - // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces - // a, x,$$$$b - // ^ ^ ^ - // | | |-next element - // | |-new inserted node padded with spaces - // |-separator - startPos = nextToken.end; - prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character); - } - else { - // next element is located on different line that separator - // let insert position be the beginning of the line that contains next element - startPos = getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile); - } + const nextNode = containingList[index + 1]; + const startPos = skipWhitespacesAndLineBreaks(sourceFile.text, nextNode.getFullStart()); // write separator and leading trivia of the next element as suffix - const suffix = `${tokenToString(nextToken.kind)}${sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile))}`; - this.replaceRange(sourceFile, createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix, suffix }); + const suffix = `${tokenToString(nextToken.kind)}${sourceFile.text.substring(nextToken.end, startPos)}`; + this.insertNodesAt(sourceFile, startPos, [newNode], { suffix }); } } else { @@ -1037,11 +1078,12 @@ namespace ts.textChanges { let lastNonTriviaPosition = 0; const writer = createTextWriter(newLine); - const onEmitNode: PrintHandlers["onEmitNode"] = (hint, node, printCallback) => { + const onBeforeEmitNode: PrintHandlers["onBeforeEmitNode"] = node => { if (node) { setPos(node, lastNonTriviaPosition); } - printCallback(hint, node); + }; + const onAfterEmitNode: PrintHandlers["onAfterEmitNode"] = node => { if (node) { setEnd(node, lastNonTriviaPosition); } @@ -1163,7 +1205,8 @@ namespace ts.textChanges { } return { - onEmitNode, + onBeforeEmitNode, + onAfterEmitNode, onBeforeEmitNodeArray, onAfterEmitNodeArray, onBeforeEmitToken, @@ -1310,8 +1353,9 @@ namespace ts.textChanges { case SyntaxKind.ImportEqualsDeclaration: const isFirstImport = sourceFile.imports.length && node === first(sourceFile.imports).parent || node === find(sourceFile.statements, isAnyImportSyntax); // For first import, leave header comment in place, otherwise only delete JSDoc comments - deleteNode(changes, sourceFile, node, - { leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); + deleteNode(changes, sourceFile, node, { + leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine, + }); break; case SyntaxKind.BindingElement: @@ -1361,7 +1405,11 @@ namespace ts.textChanges { break; default: - if (isImportClause(node.parent) && node.parent.name === node) { + if (!node.parent) { + // a misbehaving client can reach here with the SourceFile node + deleteNode(changes, sourceFile, node); + } + else if (isImportClause(node.parent) && node.parent.name === node) { deleteDefaultImport(changes, sourceFile, node.parent); } else if (isCallExpression(node.parent) && contains(node.parent.arguments, node)) { diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index 0140929340340..1e846b9214d16 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -65,6 +65,7 @@ "codefixes/convertLiteralTypeToMappedType.ts", "codefixes/fixClassIncorrectlyImplementsInterface.ts", "codefixes/importFixes.ts", + "codefixes/fixOverrideModifier.ts", "codefixes/fixNoPropertyAccessFromIndexSignature.ts", "codefixes/fixImplicitThis.ts", "codefixes/fixIncorrectNamedTupleSyntax.ts", diff --git a/src/services/types.ts b/src/services/types.ts index 82563150ecb8e..be1d09ff69c57 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -43,7 +43,7 @@ namespace ts { getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; /* @internal */ getContextualDocumentationComment(context: Node | undefined, checker: TypeChecker | undefined): SymbolDisplayPart[] - getJsDocTags(): JSDocTagInfo[]; + getJsDocTags(checker?: TypeChecker): JSDocTagInfo[]; } export interface Type { @@ -305,7 +305,9 @@ namespace ts { /* @internal */ getPackageJsonsForAutoImport?(rootDir?: string): readonly PackageJsonInfo[]; /* @internal */ - getImportSuggestionsCache?(): Completions.ImportSuggestionsForFileCache; + getExportMapCache?(): ExportMapCache; + /* @internal */ + getModuleSpecifierCache?(): ModuleSpecifierCache; /* @internal */ setCompilerHost?(host: CompilerHost): void; /* @internal */ @@ -314,6 +316,8 @@ namespace ts { getPackageJsonAutoImportProvider?(): Program | undefined; /* @internal */ sendPerformanceEvent?(kind: PerformanceEvent["kind"], durationMs: number): void; + getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; + /* @internal */ onReleaseParsedCommandLine?(configFileName: string, oldResolvedRef: ResolvedProjectReference | undefined, optionOptions: CompilerOptions): void; } /* @internal */ @@ -424,10 +428,11 @@ namespace ts { * * @param fileName The path to the file * @param position A zero based index of the character where you want the entries - * @param entryName The name from an existing completion which came from `getCompletionsAtPosition` + * @param entryName The `name` from an existing completion which came from `getCompletionsAtPosition` * @param formatOptions How should code samples in the completions be formatted, can be undefined for backwards compatibility - * @param source Source code for the current file, can be undefined for backwards compatibility + * @param source `source` property from the completion entry * @param preferences User settings, can be undefined for backwards compatibility + * @param data `data` property from the completion entry */ getCompletionEntryDetails( fileName: string, @@ -436,6 +441,7 @@ namespace ts { formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined, + data: CompletionEntryData | undefined, ): CompletionEntryDetails | undefined; getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; @@ -522,7 +528,7 @@ namespace ts { getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined, triggerReason?: RefactorTriggerReason, kind?: string): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; - organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; + organizeImports(args: OrganizeImportsArgs, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; @@ -546,9 +552,11 @@ namespace ts { export interface CombinedCodeFixScope { type: "file"; fileName: string; } - export type OrganizeImportsScope = CombinedCodeFixScope; + export interface OrganizeImportsArgs extends CombinedCodeFixScope { + skipDestructiveCodeActions?: boolean; + } - export type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#"; + export type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; export interface GetCompletionsAtPositionOptions extends UserPreferences { /** @@ -989,6 +997,7 @@ namespace ts { name: string; containerKind: ScriptElementKind; containerName: string; + unverified?: boolean; /* @internal */ isLocal?: boolean; } @@ -1029,6 +1038,9 @@ namespace ts { enumMemberName, functionName, regularExpressionLiteral, + link, + linkName, + linkText, } export interface SymbolDisplayPart { @@ -1036,9 +1048,13 @@ namespace ts { kind: string; } + export interface JSDocLinkDisplayPart extends SymbolDisplayPart { + target: DocumentSpan; + } + export interface JSDocTagInfo { name: string; - text?: string; + text?: SymbolDisplayPart[]; } export interface QuickInfo { @@ -1128,14 +1144,35 @@ namespace ts { * must be used to commit that completion entry. */ optionalReplacementSpan?: TextSpan; - /** * true when the current location also allows for a new identifier */ isNewIdentifierLocation: boolean; + /** + * Indicates to client to continue requesting completions on subsequent keystrokes. + */ + isIncomplete?: true; entries: CompletionEntry[]; } + export interface CompletionEntryData { + /** The file name declaring the export's module symbol, if it was an external module */ + fileName?: string; + /** The module name (with quotes stripped) of the export's module symbol, if it was an ambient module */ + ambientModuleName?: string; + /** True if the export was found in the package.json AutoImportProvider */ + isPackageJsonImport?: true; + /** + * The name of the property or export in the module's symbol table. Differs from the completion name + * in the case of InternalSymbolName.ExportEquals and InternalSymbolName.Default. + */ + exportName: string; + /** + * Set for auto imports with eagerly resolved module specifiers. + */ + moduleSpecifier?: string; + } + // see comments in protocol.ts export interface CompletionEntry { name: string; @@ -1143,6 +1180,7 @@ namespace ts { kindModifiers?: string; // see ScriptElementKindModifier, comma separated sortText: string; insertText?: string; + isSnippet?: true; /** * An optional span that indicates the text to be replaced by this completion item. * If present, this span should be used instead of the default one. @@ -1151,9 +1189,20 @@ namespace ts { replacementSpan?: TextSpan; hasAction?: true; source?: string; + sourceDisplay?: SymbolDisplayPart[]; isRecommended?: true; isFromUncheckedFile?: true; isPackageJsonImport?: true; + isImportStatementCompletion?: true; + /** + * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, + * that allows TS Server to look up the symbol represented by the completion item, disambiguating + * items with the same name. Currently only defined for auto-import completions, but the type is + * `unknown` in the protocol, so it can be changed as needed to support other kinds of completions. + * The presence of this property should generally not be used to assume that this completion entry + * is an auto-import. + */ + data?: CompletionEntryData; } export interface CompletionEntryDetails { @@ -1164,7 +1213,9 @@ namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; codeActions?: CodeAction[]; + /** @deprecated Use `sourceDisplay` instead. */ source?: SymbolDisplayPart[]; + sourceDisplay?: SymbolDisplayPart[]; } export interface OutliningSpan { @@ -1365,6 +1416,15 @@ namespace ts { /** String literal */ string = "string", + + /** Jsdoc @link: in `{@link C link text}`, the before and after text "{@link " and "}" */ + link = "link", + + /** Jsdoc @link: in `{@link C link text}`, the entity name "C" */ + linkName = "link name", + + /** Jsdoc @link: in `{@link C link text}`, the link text "link text" */ + linkText = "link text", } export const enum ScriptElementKindModifier { diff --git a/src/services/utilities.ts b/src/services/utilities.ts index d57f267ea977c..e5d9b0da77564 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -105,7 +105,7 @@ namespace ts { else if (isDeclarationName(node)) { return getMeaningFromDeclaration(node.parent); } - else if (isEntityName(node) && isJSDocNameReference(node.parent)) { + else if (isEntityName(node) && (isJSDocNameReference(node.parent) || isJSDocLink(node.parent))) { return SemanticMeaning.All; } else if (isTypeReference(node)) { @@ -1141,6 +1141,20 @@ namespace ts { } } + /** + * Returns the first token where position is in [start, end), + * excluding `JsxText` tokens containing only whitespace. + */ + export function findFirstNonJsxWhitespaceToken(sourceFile: SourceFile, position: number): Node | undefined { + let tokenAtPosition = getTokenAtPosition(sourceFile, position); + while (isWhiteSpaceOnlyJsxText(tokenAtPosition)) { + const nextToken = findNextToken(tokenAtPosition, tokenAtPosition.parent, sourceFile); + if (!nextToken) return; + tokenAtPosition = nextToken; + } + return tokenAtPosition; + } + /** * The token on the left of the position is the token that strictly includes the position * or sits to the left of the cursor if it is on a boundary. For example @@ -1821,7 +1835,7 @@ namespace ts { } export function createModuleSpecifierResolutionHost(program: Program, host: LanguageServiceHost): ModuleSpecifierResolutionHost { - // Mix in `getProbableSymlinks` from Program when host doesn't have it + // Mix in `getSymlinkCache` from Program when host doesn't have it // in order for non-Project hosts to have a symlinks cache. return { fileExists: fileName => program.fileExists(fileName), @@ -1829,6 +1843,7 @@ namespace ts { readFile: maybeBind(host, host.readFile), useCaseSensitiveFileNames: maybeBind(host, host.useCaseSensitiveFileNames), getSymlinkCache: maybeBind(host, host.getSymlinkCache) || program.getSymlinkCache, + getModuleSpecifierCache: maybeBind(host, host.getModuleSpecifierCache), getGlobalTypingsCacheLocation: maybeBind(host, host.getGlobalTypingsCacheLocation), getSourceFiles: () => program.getSourceFiles(), redirectTargetsMap: program.redirectTargetsMap, @@ -1906,6 +1921,14 @@ namespace ts { }); } + export function isModuleSpecifierLike(node: Node): node is StringLiteralLike { + return isStringLiteralLike(node) && ( + isExternalModuleReference(node.parent) || + isImportDeclaration(node.parent) || + isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ false) && node.parent.arguments[0] === node || + isImportCall(node.parent) && node.parent.arguments[0] === node); + } + export type ObjectBindingElementWithoutPropertyName = BindingElement & { name: Identifier }; export function isObjectBindingElementWithoutPropertyName(bindingElement: Node): bindingElement is ObjectBindingElementWithoutPropertyName { @@ -2164,6 +2187,14 @@ namespace ts { return displayPart(tokenToString(kind)!, SymbolDisplayPartKind.operator); } + export function parameterNamePart(text: string) { + return displayPart(text, SymbolDisplayPartKind.parameterName); + } + + export function propertyNamePart(text: string) { + return displayPart(text, SymbolDisplayPartKind.propertyName); + } + export function textOrKeywordPart(text: string) { const kind = stringToToken(text); return kind === undefined @@ -2175,6 +2206,53 @@ namespace ts { return displayPart(text, SymbolDisplayPartKind.text); } + export function typeAliasNamePart(text: string) { + return displayPart(text, SymbolDisplayPartKind.aliasName); + } + + export function typeParameterNamePart(text: string) { + return displayPart(text, SymbolDisplayPartKind.typeParameterName); + } + + export function linkTextPart(text: string) { + return displayPart(text, SymbolDisplayPartKind.linkText); + } + + export function linkNamePart(name: EntityName, target: Declaration): JSDocLinkDisplayPart { + return { + text: getTextOfNode(name), + kind: SymbolDisplayPartKind[SymbolDisplayPartKind.linkName], + target: { + fileName: getSourceFileOfNode(target).fileName, + textSpan: createTextSpanFromNode(target), + }, + }; + } + + export function linkPart(text: string) { + return displayPart(text, SymbolDisplayPartKind.link); + } + + export function buildLinkParts(link: JSDocLink, checker?: TypeChecker): SymbolDisplayPart[] { + const parts = [linkPart("{@link ")]; + if (!link.name) { + if (link.text) {parts.push(linkTextPart(link.text));} + } + else { + const symbol = checker?.getSymbolAtLocation(link.name); + const decl = symbol?.valueDeclaration || symbol?.declarations?.[0]; + if (decl) { + parts.push(linkNamePart(link.name, decl)); + if (link.text) {parts.push(linkTextPart(link.text));} + } + else { + parts.push(linkTextPart(getTextOfNode(link.name) + link.text)); + } + } + parts.push(linkPart("}")); + return parts; + } + const carriageReturnLineFeed = "\r\n"; /** * The default is CRLF. @@ -2469,8 +2547,10 @@ namespace ts { } /* @internal */ - export function needsParentheses(expression: Expression) { - return isBinaryExpression(expression) && expression.operatorToken.kind === SyntaxKind.CommaToken || isObjectLiteralExpression(expression); + export function needsParentheses(expression: Expression): boolean { + return isBinaryExpression(expression) && expression.operatorToken.kind === SyntaxKind.CommaToken + || isObjectLiteralExpression(expression) + || isAsExpression(expression) && isObjectLiteralExpression(expression.expression); } export function getContextualTypeFromParent(node: Expression, checker: TypeChecker): Type | undefined { @@ -2800,6 +2880,125 @@ namespace ts { } } + export interface PackageJsonImportFilter { + allowsImportingAmbientModule: (moduleSymbol: Symbol, moduleSpecifierResolutionHost: ModuleSpecifierResolutionHost) => boolean; + allowsImportingSourceFile: (sourceFile: SourceFile, moduleSpecifierResolutionHost: ModuleSpecifierResolutionHost) => boolean; + /** + * Use for a specific module specifier that has already been resolved. + * Use `allowsImportingAmbientModule` or `allowsImportingSourceFile` to resolve + * the best module specifier for a given module _and_ determine if it’s importable. + */ + allowsImportingSpecifier: (moduleSpecifier: string) => boolean; + } + + export function createPackageJsonImportFilter(fromFile: SourceFile, host: LanguageServiceHost): PackageJsonImportFilter { + const packageJsons = ( + (host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName)) || getPackageJsonsVisibleToFile(fromFile.fileName, host) + ).filter(p => p.parseable); + + let usesNodeCoreModules: boolean | undefined; + return { allowsImportingAmbientModule, allowsImportingSourceFile, allowsImportingSpecifier }; + + function moduleSpecifierIsCoveredByPackageJson(specifier: string) { + const packageName = getNodeModuleRootSpecifier(specifier); + for (const packageJson of packageJsons) { + if (packageJson.has(packageName) || packageJson.has(getTypesPackageName(packageName))) { + return true; + } + } + return false; + } + + function allowsImportingAmbientModule(moduleSymbol: Symbol, moduleSpecifierResolutionHost: ModuleSpecifierResolutionHost): boolean { + if (!packageJsons.length || !moduleSymbol.valueDeclaration) { + return true; + } + + const declaringSourceFile = moduleSymbol.valueDeclaration.getSourceFile(); + const declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName, moduleSpecifierResolutionHost); + if (typeof declaringNodeModuleName === "undefined") { + return true; + } + + const declaredModuleSpecifier = stripQuotes(moduleSymbol.getName()); + if (isAllowedCoreNodeModulesImport(declaredModuleSpecifier)) { + return true; + } + + return moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName) + || moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier); + } + + function allowsImportingSourceFile(sourceFile: SourceFile, moduleSpecifierResolutionHost: ModuleSpecifierResolutionHost): boolean { + if (!packageJsons.length) { + return true; + } + + const moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName, moduleSpecifierResolutionHost); + if (!moduleSpecifier) { + return true; + } + + return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); + } + + function allowsImportingSpecifier(moduleSpecifier: string) { + if (!packageJsons.length || isAllowedCoreNodeModulesImport(moduleSpecifier)) { + return true; + } + if (pathIsRelative(moduleSpecifier) || isRootedDiskPath(moduleSpecifier)) { + return true; + } + return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); + } + + function isAllowedCoreNodeModulesImport(moduleSpecifier: string) { + // If we’re in JavaScript, it can be difficult to tell whether the user wants to import + // from Node core modules or not. We can start by seeing if the user is actually using + // any node core modules, as opposed to simply having @types/node accidentally as a + // dependency of a dependency. + if (isSourceFileJS(fromFile) && JsTyping.nodeCoreModules.has(moduleSpecifier)) { + if (usesNodeCoreModules === undefined) { + usesNodeCoreModules = consumesNodeCoreModules(fromFile); + } + if (usesNodeCoreModules) { + return true; + } + } + return false; + } + + function getNodeModulesPackageNameFromFileName(importedFileName: string, moduleSpecifierResolutionHost: ModuleSpecifierResolutionHost): string | undefined { + if (!stringContains(importedFileName, "node_modules")) { + return undefined; + } + const specifier = moduleSpecifiers.getNodeModulesPackageName( + host.getCompilationSettings(), + fromFile.path, + importedFileName, + moduleSpecifierResolutionHost, + ); + + if (!specifier) { + return undefined; + } + // Paths here are not node_modules, so we don’t care about them; + // returning anything will trigger a lookup in package.json. + if (!pathIsRelative(specifier) && !isRootedDiskPath(specifier)) { + return getNodeModuleRootSpecifier(specifier); + } + } + + function getNodeModuleRootSpecifier(fullSpecifier: string): string { + const components = getPathComponents(getPackageNameFromTypesPackageName(fullSpecifier)).slice(1); + // Scoped packages + if (startsWith(components[0], "@")) { + return `${components[0]}/${components[1]}`; + } + return components[0]; + } + } + function tryParseJson(text: string) { try { return JSON.parse(text); @@ -2948,5 +3147,211 @@ namespace ts { return isInJSFile(declaration) || !findAncestor(declaration, isGlobalScopeAugmentation); } + export const enum ImportKind { + Named, + Default, + Namespace, + CommonJS, + } + + export const enum ExportKind { + Named, + Default, + ExportEquals, + UMD, + } + + /** Information about how a symbol is exported from a module. */ + export interface SymbolExportInfo { + symbol: Symbol; + moduleSymbol: Symbol; + exportKind: ExportKind; + /** If true, can't use an es6 import from a js file. */ + exportedSymbolIsTypeOnly: boolean; + /** True if export was only found via the package.json AutoImportProvider (for telemetry). */ + isFromPackageJson: boolean; + } + + export interface ExportMapCache { + clear(): void; + get(file: Path, checker: TypeChecker, projectVersion?: string): MultiMap | undefined; + set(suggestions: MultiMap, projectVersion?: string): void; + isEmpty(): boolean; + /** @returns Whether the change resulted in the cache being cleared */ + onFileChanged(oldSourceFile: SourceFile, newSourceFile: SourceFile, typeAcquisitionEnabled: boolean): boolean; + } + export function createExportMapCache(): ExportMapCache { + let cache: MultiMap | undefined; + let projectVersion: string | undefined; + let usableByFileName: Path | undefined; + const wrapped: ExportMapCache = { + isEmpty() { + return !cache; + }, + clear() { + cache = undefined; + projectVersion = undefined; + }, + set(suggestions, version) { + cache = suggestions; + if (version) { + projectVersion = version; + } + }, + get: (file, checker, version) => { + if (usableByFileName && file !== usableByFileName) { + return undefined; + } + if (version && projectVersion === version) { + return cache; + } + cache?.forEach(infos => { + for (const info of infos) { + // If the symbol/moduleSymbol was a merged symbol, it will have a new identity + // in the checker, even though the symbols to merge are the same (guaranteed by + // cache invalidation in synchronizeHostData). + if (info.symbol.declarations?.length) { + info.symbol = checker.getMergedSymbol(info.exportKind === ExportKind.Default + ? info.symbol.declarations[0].localSymbol ?? info.symbol.declarations[0].symbol + : info.symbol.declarations[0].symbol); + } + if (info.moduleSymbol.declarations?.length) { + info.moduleSymbol = checker.getMergedSymbol(info.moduleSymbol.declarations[0].symbol); + } + } + }); + return cache; + }, + onFileChanged(oldSourceFile: SourceFile, newSourceFile: SourceFile, typeAcquisitionEnabled: boolean) { + if (fileIsGlobalOnly(oldSourceFile) && fileIsGlobalOnly(newSourceFile)) { + // File is purely global; doesn't affect export map + return false; + } + if ( + usableByFileName && usableByFileName !== newSourceFile.path || + // If ATA is enabled, auto-imports uses existing imports to guess whether you want auto-imports from node. + // Adding or removing imports from node could change the outcome of that guess, so could change the suggestions list. + typeAcquisitionEnabled && consumesNodeCoreModules(oldSourceFile) !== consumesNodeCoreModules(newSourceFile) || + // Module agumentation and ambient module changes can add or remove exports available to be auto-imported. + // Changes elsewhere in the file can change the *type* of an export in a module augmentation, + // but type info is gathered in getCompletionEntryDetails, which doesn’t use the cache. + !arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations) || + !ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile) + ) { + this.clear(); + return true; + } + usableByFileName = newSourceFile.path; + return false; + }, + }; + if (Debug.isDebugging) { + Object.defineProperty(wrapped, "__cache", { get: () => cache }); + } + return wrapped; + + function fileIsGlobalOnly(file: SourceFile) { + return !file.commonJsModuleIndicator && !file.externalModuleIndicator && !file.moduleAugmentations && !file.ambientModuleNames; + } + + function ambientModuleDeclarationsAreEqual(oldSourceFile: SourceFile, newSourceFile: SourceFile) { + if (!arrayIsEqualTo(oldSourceFile.ambientModuleNames, newSourceFile.ambientModuleNames)) { + return false; + } + let oldFileStatementIndex = -1; + let newFileStatementIndex = -1; + for (const ambientModuleName of newSourceFile.ambientModuleNames) { + const isMatchingModuleDeclaration = (node: Statement) => isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName; + oldFileStatementIndex = findIndex(oldSourceFile.statements, isMatchingModuleDeclaration, oldFileStatementIndex + 1); + newFileStatementIndex = findIndex(newSourceFile.statements, isMatchingModuleDeclaration, newFileStatementIndex + 1); + if (oldSourceFile.statements[oldFileStatementIndex] !== newSourceFile.statements[newFileStatementIndex]) { + return false; + } + } + return true; + } + } + + export function createModuleSpecifierCache(): ModuleSpecifierCache { + let cache: ESMap | undefined; + let importingFileName: Path | undefined; + const wrapped: ModuleSpecifierCache = { + get(fromFileName, toFileName) { + if (!cache || fromFileName !== importingFileName) return undefined; + return cache.get(toFileName); + }, + set(fromFileName, toFileName, moduleSpecifiers) { + if (cache && fromFileName !== importingFileName) { + cache.clear(); + } + importingFileName = fromFileName; + (cache ||= new Map()).set(toFileName, moduleSpecifiers); + }, + clear() { + cache = undefined; + importingFileName = undefined; + }, + count() { + return cache ? cache.size : 0; + } + }; + if (Debug.isDebugging) { + Object.defineProperty(wrapped, "__cache", { get: () => cache }); + } + return wrapped; + } + + export function isImportableFile( + program: Program, + from: SourceFile, + to: SourceFile, + packageJsonFilter: PackageJsonImportFilter | undefined, + moduleSpecifierResolutionHost: ModuleSpecifierResolutionHost, + moduleSpecifierCache: ModuleSpecifierCache | undefined, + ): boolean { + if (from === to) return false; + const cachedResult = moduleSpecifierCache?.get(from.path, to.path); + if (cachedResult !== undefined) { + return !!cachedResult; + } + + const getCanonicalFileName = hostGetCanonicalFileName(moduleSpecifierResolutionHost); + const globalTypingsCache = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation?.(); + const hasImportablePath = !!moduleSpecifiers.forEachFileNameOfModule( + from.fileName, + to.fileName, + moduleSpecifierResolutionHost, + /*preferSymlinks*/ false, + toPath => { + const toFile = program.getSourceFile(toPath); + // Determine to import using toPath only if toPath is what we were looking at + // or there doesnt exist the file in the program by the symlink + return (toFile === to || !toFile) && + isImportablePath(from.fileName, toPath, getCanonicalFileName, globalTypingsCache); + } + ); + + if (packageJsonFilter) { + const isImportable = hasImportablePath && packageJsonFilter.allowsImportingSourceFile(to, moduleSpecifierResolutionHost); + moduleSpecifierCache?.set(from.path, to.path, isImportable); + return isImportable; + } + + return hasImportablePath; + } + + /** + * Don't include something from a `node_modules` that isn't actually reachable by a global import. + * A relative import to node_modules is usually a bad idea. + */ + function isImportablePath(fromPath: string, toPath: string, getCanonicalFileName: GetCanonicalFileName, globalCachePath?: string): boolean { + // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. + const toNodeModules = forEachAncestorDirectory(toPath, ancestor => getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined); + const toNodeModulesParent = toNodeModules && getDirectoryPath(getCanonicalFileName(toNodeModules)); + return toNodeModulesParent === undefined + || startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) + || (!!globalCachePath && startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); + } + // #endregion } diff --git a/src/testRunner/tsconfig.json b/src/testRunner/tsconfig.json index cfd4dc6f9c456..439b447d6396f 100644 --- a/src/testRunner/tsconfig.json +++ b/src/testRunner/tsconfig.json @@ -66,6 +66,7 @@ "unittests/factory.ts", "unittests/incrementalParser.ts", "unittests/jsDocParsing.ts", + "unittests/jsonParserRecovery.ts", "unittests/moduleResolution.ts", "unittests/parsePseudoBigInt.ts", "unittests/paths.ts", @@ -111,6 +112,7 @@ "unittests/services/textChanges.ts", "unittests/services/transpile.ts", "unittests/tsbuild/amdModulesWithOut.ts", + "unittests/tsbuild/clean.ts", "unittests/tsbuild/configFileErrors.ts", "unittests/tsbuild/configFileExtends.ts", "unittests/tsbuild/containerOnlyReferenced.ts", @@ -128,6 +130,7 @@ "unittests/tsbuild/noEmitOnError.ts", "unittests/tsbuild/outFile.ts", "unittests/tsbuild/outputPaths.ts", + "unittests/tsbuild/publicApi.ts", "unittests/tsbuild/referencesWithRootDirInParent.ts", "unittests/tsbuild/resolveJsonModule.ts", "unittests/tsbuild/sample.ts", @@ -146,6 +149,7 @@ "unittests/tscWatch/forceConsistentCasingInFileNames.ts", "unittests/tscWatch/incremental.ts", "unittests/tscWatch/programUpdates.ts", + "unittests/tscWatch/projectsWithReferences.ts", "unittests/tscWatch/resolutionCache.ts", "unittests/tscWatch/sourceOfProjectReferenceRedirect.ts", "unittests/tscWatch/watchApi.ts", @@ -166,6 +170,7 @@ "unittests/tsserver/events/projectLanguageServiceState.ts", "unittests/tsserver/events/projectLoading.ts", "unittests/tsserver/events/projectUpdatedInBackground.ts", + "unittests/tsserver/exportMapCache.ts", "unittests/tsserver/externalProjects.ts", "unittests/tsserver/forceConsistentCasingInFileNames.ts", "unittests/tsserver/formatSettings.ts", @@ -174,11 +179,12 @@ "unittests/tsserver/getExportReferences.ts", "unittests/tsserver/getFileReferences.ts", "unittests/tsserver/importHelpers.ts", - "unittests/tsserver/importSuggestionsCache.ts", "unittests/tsserver/inferredProjects.ts", + "unittests/tsserver/jsdocTag.ts", "unittests/tsserver/languageService.ts", "unittests/tsserver/maxNodeModuleJsDepth.ts", "unittests/tsserver/metadataInResponse.ts", + "unittests/tsserver/moduleSpecifierCache.ts", "unittests/tsserver/navTo.ts", "unittests/tsserver/occurences.ts", "unittests/tsserver/openFile.ts", @@ -189,7 +195,9 @@ "unittests/tsserver/projectReferenceCompileOnSave.ts", "unittests/tsserver/projectReferenceErrors.ts", "unittests/tsserver/projectReferences.ts", + "unittests/tsserver/projectReferencesSourcemap.ts", "unittests/tsserver/projects.ts", + "unittests/tsserver/projectsWithReferences.ts", "unittests/tsserver/refactors.ts", "unittests/tsserver/reload.ts", "unittests/tsserver/reloadProjects.ts", diff --git a/src/testRunner/unittests/config/commandLineParsing.ts b/src/testRunner/unittests/config/commandLineParsing.ts index 4239829c8c32e..eea2b37c1b4fd 100644 --- a/src/testRunner/unittests/config/commandLineParsing.ts +++ b/src/testRunner/unittests/config/commandLineParsing.ts @@ -46,6 +46,23 @@ namespace ts { }); }); + it("Handles 'may only be used with --build' flags", () => { + const buildFlags = ["--clean", "--dry", "--force", "--verbose"]; + + assertParseResult(buildFlags, { + errors: buildFlags.map(buildFlag => ({ + messageText: `Compiler option '${buildFlag}' may only be used with '--build'.`, + category: Diagnostics.Compiler_option_0_may_only_be_used_with_build.category, + code: Diagnostics.Compiler_option_0_may_only_be_used_with_build.code, + file: undefined, + start: undefined, + length: undefined + })), + fileNames: [], + options: {} + }); + }); + it("Handles 'did you mean?' for misspelt flags", () => { // --declarations --allowTS assertParseResult(["--declarations", "--allowTS"], { @@ -194,7 +211,7 @@ namespace ts { start: undefined, length: undefined, }, { - messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'esnext'.", + messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'esnext'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, @@ -650,7 +667,7 @@ namespace ts { length: undefined }, { - messageText: "Argument for '--fallbackPolling' option must be: 'fixedinterval', 'priorityinterval', 'dynamicpriority'.", + messageText: "Argument for '--fallbackPolling' option must be: 'fixedinterval', 'priorityinterval', 'dynamicpriority', 'fixedchunksize'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, @@ -790,9 +807,9 @@ namespace ts { assertParseResult(["--listFilesOnly"], { errors: [{ - messageText: "Unknown build option '--listFilesOnly'.", - category: Diagnostics.Unknown_build_option_0.category, - code: Diagnostics.Unknown_build_option_0.code, + messageText: "Compiler option '--listFilesOnly' may not be used with '--build'.", + category: Diagnostics.Compiler_option_0_may_not_be_used_with_build.category, + code: Diagnostics.Compiler_option_0_may_not_be_used_with_build.code, file: undefined, start: undefined, length: undefined, @@ -863,9 +880,9 @@ namespace ts { assertParseResult(["--tsBuildInfoFile", "build.tsbuildinfo", "tests"], { errors: [{ - messageText: "Unknown build option '--tsBuildInfoFile'.", - category: Diagnostics.Unknown_build_option_0.category, - code: Diagnostics.Unknown_build_option_0.code, + messageText: "Compiler option '--tsBuildInfoFile' may not be used with '--build'.", + category: Diagnostics.Compiler_option_0_may_not_be_used_with_build.category, + code: Diagnostics.Compiler_option_0_may_not_be_used_with_build.code, file: undefined, start: undefined, length: undefined @@ -876,6 +893,24 @@ namespace ts { }); }); + it("reports other common 'may not be used with --build' flags", () => { + const buildFlags = ["--declaration", "--strict"]; + + assertParseResult(buildFlags, { + errors: buildFlags.map(buildFlag => ({ + messageText: `Compiler option '${buildFlag}' may not be used with '--build'.`, + category: Diagnostics.Compiler_option_0_may_not_be_used_with_build.category, + code: Diagnostics.Compiler_option_0_may_not_be_used_with_build.code, + file: undefined, + start: undefined, + length: undefined + })), + buildOptions: {}, + projects: ["."], + watchOptions: undefined, + }); + }); + describe("Combining options that make no sense together", () => { function verifyInvalidCombination(flag1: keyof BuildOptions, flag2: keyof BuildOptions) { it(`--${flag1} and --${flag2} together is invalid`, () => { @@ -957,7 +992,7 @@ namespace ts { length: undefined }, { - messageText: "Argument for '--fallbackPolling' option must be: 'fixedinterval', 'priorityinterval', 'dynamicpriority'.", + messageText: "Argument for '--fallbackPolling' option must be: 'fixedinterval', 'priorityinterval', 'dynamicpriority', 'fixedchunksize'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, diff --git a/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts b/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts index d007ccf5f8482..71c826351d05a 100644 --- a/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts +++ b/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts @@ -69,7 +69,7 @@ namespace ts { assert.equal(actualError.category, expectedError.category, `Expected error-category: ${JSON.stringify(expectedError.category)}. Actual error-category: ${JSON.stringify(actualError.category)}.`); if (!ignoreLocation) { assert(actualError.file); - assert(actualError.start); + assert.isDefined(actualError.start); assert(actualError.length); } } @@ -603,5 +603,84 @@ namespace ts { hasParseErrors: true }); }); + + it("Convert a tsconfig file with stray trailing characters", () => { + assertCompilerOptionsWithJsonText(`{ + "compilerOptions": { + "target": "esnext" + } + } blah`, "tsconfig.json", { + compilerOptions: { + target: ScriptTarget.ESNext + }, + hasParseErrors: true, + errors: [{ + ...Diagnostics.The_root_value_of_a_0_file_must_be_an_object, + messageText: "The root value of a 'tsconfig.json' file must be an object.", + file: undefined, + start: 0, + length: 0 + }] + }); + }); + + it("Convert a tsconfig file with stray leading characters", () => { + assertCompilerOptionsWithJsonText(`blah { + "compilerOptions": { + "target": "esnext" + } + }`, "tsconfig.json", { + compilerOptions: { + target: ScriptTarget.ESNext + }, + hasParseErrors: true, + errors: [{ + ...Diagnostics.The_root_value_of_a_0_file_must_be_an_object, + messageText: "The root value of a 'tsconfig.json' file must be an object.", + file: undefined, + start: 0, + length: 0 + }] + }); + }); + + it("Convert a tsconfig file as an array", () => { + assertCompilerOptionsWithJsonText(`[{ + "compilerOptions": { + "target": "esnext" + } + }]`, "tsconfig.json", { + compilerOptions: { + target: ScriptTarget.ESNext + }, + errors: [{ + ...Diagnostics.The_root_value_of_a_0_file_must_be_an_object, + messageText: "The root value of a 'tsconfig.json' file must be an object.", + file: undefined, + start: 0, + length: 0 + }] + }); + }); + + it("Don't crash when root expression is not objecty at all", () => { + assertCompilerOptionsWithJsonText(`42`, "tsconfig.json", { + compilerOptions: {}, + errors: [{ + ...Diagnostics.The_root_value_of_a_0_file_must_be_an_object, + messageText: "The root value of a 'tsconfig.json' file must be an object.", + file: undefined, + start: 0, + length: 0 + }] + }); + }); + + it("Allow trailing comments", () => { + assertCompilerOptionsWithJsonText(`{} // no options`, "tsconfig.json", { + compilerOptions: {}, + errors: [] + }); + }); }); } diff --git a/src/testRunner/unittests/evaluation/optionalCall.ts b/src/testRunner/unittests/evaluation/optionalCall.ts index d6317ad0a8ca9..f92190dfb72b9 100644 --- a/src/testRunner/unittests/evaluation/optionalCall.ts +++ b/src/testRunner/unittests/evaluation/optionalCall.ts @@ -188,4 +188,11 @@ describe("unittests:: evaluation:: optionalCall", () => { assert.strictEqual(result.output[1], 2); assert.strictEqual(result.output[2], result.o); }); + it("(o?.f)()", async () => { + const result = evaluator.evaluateTypeScript(` + export const foo = { bar() { return this } }; + export const output = (foo?.bar)(); + `); + assert.strictEqual(result.output, result.foo); + }); }); diff --git a/src/testRunner/unittests/jsDocParsing.ts b/src/testRunner/unittests/jsDocParsing.ts index f346ca8b02db5..e0aa87f2a4cd2 100644 --- a/src/testRunner/unittests/jsDocParsing.ts +++ b/src/testRunner/unittests/jsDocParsing.ts @@ -312,8 +312,23 @@ namespace ts { */`); parsesCorrectly("@link tags", `/** - * {@link first link} + * {@link first } * Inside {@link link text} thing + * @param foo See also {@link A.Reference} + * @param bar Or see {@link http://www.zombocom.com } + * {@link Standalone.Complex } + * This empty one: {@link} is OK. + * This double-space one: {@link doubled } is OK too. + * This should work, despite being badly formatted: {@link +oh.no +} + * Forgot to close this one {@link https://typescriptlang.org + * But it's still OK. + * Although it skips the newline so parses the asterisks in the wrong state. + * This shouldn't work: {@link + * nope + * }, because of the intermediate asterisks. + * @author Alfa Romero See my home page: {@link https://example.com} */`); parsesCorrectly("authorTag", `/** @@ -382,5 +397,9 @@ namespace ts { const root = createSourceFile("foo.ts", "/** */var a = true;", ScriptTarget.ES5, /*setParentNodes*/ false); root.statements[0].getStart(root, /*includeJsdocComment*/ true); }); + describe("missing type parameter in jsDoc doesn't create a 1-element array", () => { + const doc = parseIsolatedJSDocComment("/**\n @template\n*/"); + assert.equal((doc?.jsDoc.tags?.[0] as JSDocTemplateTag).typeParameters.length, 0); + }); }); } diff --git a/src/testRunner/unittests/jsonParserRecovery.ts b/src/testRunner/unittests/jsonParserRecovery.ts new file mode 100644 index 0000000000000..43007a687d349 --- /dev/null +++ b/src/testRunner/unittests/jsonParserRecovery.ts @@ -0,0 +1,39 @@ +namespace ts { + describe("unittests:: jsonParserRecovery", () => { + function parsesToValidSourceFileWithErrors(name: string, text: string) { + it(name, () => { + const file = parseJsonText(name, text); + assert(file.parseDiagnostics.length, "Should have parse errors"); + Harness.Baseline.runBaseline( + `jsonParserRecovery/${name.replace(/[^a-z0-9_-]/ig, "_")}.errors.txt`, + Harness.Compiler.getErrorBaseline([{ + content: text, + unitName: name + }], file.parseDiagnostics)); + + // Will throw if parse tree does not cover full input text + file.getChildren(); + }); + } + + parsesToValidSourceFileWithErrors("trailing identifier", "{} blah"); + parsesToValidSourceFileWithErrors("TypeScript code", "interface Foo {} blah"); + parsesToValidSourceFileWithErrors("Two comma-separated objects", "{}, {}"); + parsesToValidSourceFileWithErrors("Two objects", "{} {}"); + parsesToValidSourceFileWithErrors("JSX", ` + interface Test {} + + const Header = () => ( +
+

Header

+ +
+ )`); + }); +} diff --git a/src/testRunner/unittests/publicApi.ts b/src/testRunner/unittests/publicApi.ts index eb8e5f18c4660..e299f0c339da5 100644 --- a/src/testRunner/unittests/publicApi.ts +++ b/src/testRunner/unittests/publicApi.ts @@ -67,7 +67,9 @@ function test() {}`; const funcDec = testSourceFile.statements.find(ts.isFunctionDeclaration)!; const tags = ts.getJSDocTags(funcDec); assert.isDefined(tags[0].comment); - assert.equal(tags[0].comment, "Some\n text\r\n with newlines."); + assert.isDefined(tags[0].comment![0]); + assert.isString(tags[0].comment); + assert.equal(tags[0].comment as string, "Some\n text\r\n with newlines."); }); }); diff --git a/src/testRunner/unittests/reuseProgramStructure.ts b/src/testRunner/unittests/reuseProgramStructure.ts index 3c21ed2a03581..379c8be11cc52 100644 --- a/src/testRunner/unittests/reuseProgramStructure.ts +++ b/src/testRunner/unittests/reuseProgramStructure.ts @@ -474,7 +474,7 @@ namespace ts { "File 'node_modules/@types/a.d.ts' does not exist.", "File 'node_modules/@types/a/index.d.ts' does not exist.", "Loading module 'a' from 'node_modules' folder, target file type 'JavaScript'.", - "File 'node_modules/a/package.json' does not exist.", + "File 'node_modules/a/package.json' does not exist according to earlier cached lookups.", "File 'node_modules/a.js' does not exist.", "File 'node_modules/a.jsx' does not exist.", "File 'node_modules/a/index.js' does not exist.", @@ -916,6 +916,7 @@ namespace ts { path => program.getSourceFileByPath(path)!.version, /*fileExists*/ returnFalse, /*hasInvalidatedResolution*/ returnFalse, /*hasChangedAutomaticTypeDirectiveNames*/ undefined, + /*getParsedCommandLine*/ returnUndefined, /*projectReferences*/ undefined ); } @@ -951,7 +952,7 @@ namespace ts { configFileName, system })).getCurrentProgram().getProgram(); - const { fileNames, options } = parseConfigFileWithSystem(configFileName, {}, /*watchOptionsToExtend*/ undefined, system, notImplemented)!; // TODO: GH#18217 + const { fileNames, options } = parseConfigFileWithSystem(configFileName, {}, /*extendedConfigCache*/ undefined, /*watchOptionsToExtend*/ undefined, system, notImplemented)!; // TODO: GH#18217 verifyProgramIsUptoDate(program, fileNames, options); } diff --git a/src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts b/src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts index bd8ed2714acd5..26ad16d8ebcef 100644 --- a/src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts +++ b/src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts @@ -47,7 +47,7 @@ namespace ts { placeOpenBraceOnNewLineForControlBlocks: false, }; verifyOperationCancelledAfter(file, 1, service => // The LS doesn't do any top-level checks on the token for completion entry details, so the first check is within the checker - service.getCompletionEntryDetails("file.ts", file.lastIndexOf("f"), "foo", options, /*content*/ undefined, {})!, r => assert.exists(r.displayParts) + service.getCompletionEntryDetails("file.ts", file.lastIndexOf("f"), "foo", options, /*source*/ undefined, {}, /*data*/ undefined)!, r => assert.exists(r.displayParts) ); }); diff --git a/src/testRunner/unittests/services/convertToAsyncFunction.ts b/src/testRunner/unittests/services/convertToAsyncFunction.ts index 0a36a9ebfcfe9..fd2677b029e1f 100644 --- a/src/testRunner/unittests/services/convertToAsyncFunction.ts +++ b/src/testRunner/unittests/services/convertToAsyncFunction.ts @@ -1680,6 +1680,32 @@ import { fn } from "./module"; function [#|f|]() { return Promise.resolve(0).then(fn); } +`); + + _testConvertToAsyncFunctionFailed("convertToAsyncFunction__NoSuggestionInFunctionsWithNonFixableReturnStatements1", ` +function f(x: number): Promise; +function f(): void; +function [#|f|](x?: number): Promise | void { + if (!x) return; + return fetch('').then(() => {}); +} +`); + + _testConvertToAsyncFunctionFailed("convertToAsyncFunction__NoSuggestionInFunctionsWithNonFixableReturnStatements2", ` +function f(x: number): Promise; +function f(): number; +function [#|f|](x?: number): Promise | number { + if (x) return x; + return fetch('').then(() => {}); +} +`); + + _testConvertToAsyncFunctionFailed("convertToAsyncFunction__NoSuggestionInGetters", ` +class Foo { + get [#|m|](): Promise { + return Promise.resolve(1).then(n => n); + } +} `); }); diff --git a/src/testRunner/unittests/services/extract/ranges.ts b/src/testRunner/unittests/services/extract/ranges.ts index 8fe5aeb3c131f..fd7efa79cc588 100644 --- a/src/testRunner/unittests/services/extract/ranges.ts +++ b/src/testRunner/unittests/services/extract/ranges.ts @@ -14,85 +14,100 @@ namespace ts { }); } - function testExtractRange(s: string): void { - const t = extractTest(s); - const f = createSourceFile("a.ts", t.source, ScriptTarget.Latest, /*setParentNodes*/ true); - const selectionRange = t.ranges.get("selection"); - if (!selectionRange) { - throw new Error(`Test ${s} does not specify selection range`); - } - const result = refactor.extractSymbol.getRangeToExtract(f, createTextSpanFromRange(selectionRange)); - const expectedRange = t.ranges.get("extracted"); - if (expectedRange) { - let pos: number, end: number; - const targetRange = result.targetRange!; - if (isArray(targetRange.range)) { - pos = targetRange.range[0].getStart(f); - end = last(targetRange.range).getEnd(); + function testExtractRange(caption: string, s: string) { + return it(caption, () => { + const t = extractTest(s); + const f = createSourceFile("a.ts", t.source, ScriptTarget.Latest, /*setParentNodes*/ true); + const selectionRange = t.ranges.get("selection"); + if (!selectionRange) { + throw new Error(`Test ${s} does not specify selection range`); + } + const result = refactor.extractSymbol.getRangeToExtract(f, createTextSpanFromRange(selectionRange)); + const expectedRange = t.ranges.get("extracted"); + if (expectedRange) { + let pos: number, end: number; + const targetRange = result.targetRange!; + if (isArray(targetRange.range)) { + pos = targetRange.range[0].getStart(f); + end = last(targetRange.range).getEnd(); + } + else { + pos = targetRange.range.getStart(f); + end = targetRange.range.getEnd(); + } + assert.equal(pos, expectedRange.pos, "incorrect pos of range"); + assert.equal(end, expectedRange.end, "incorrect end of range"); } else { - pos = targetRange.range.getStart(f); - end = targetRange.range.getEnd(); + assert.isTrue(!result.targetRange, `expected range to extract to be undefined`); } - assert.equal(pos, expectedRange.pos, "incorrect pos of range"); - assert.equal(end, expectedRange.end, "incorrect end of range"); - } - else { - assert.isTrue(!result.targetRange, `expected range to extract to be undefined`); - } + }); } describe("unittests:: services:: extract:: extractRanges", () => { - it("get extract range from selection", () => { - testExtractRange(` + describe("get extract range from selection", () => { + testExtractRange("extractRange1", ` [#| [$|var x = 1; var y = 2;|]|] `); - testExtractRange(` - [#| - var x = 1; - var y = 2|]; + testExtractRange("extractRange2", ` + [$|[#|var x = 1; + var y = 2|];|] `); - testExtractRange(` - [#|var x = 1|]; + testExtractRange("extractRange3", ` + [#|var x = [$|1|]|]; var y = 2; `); - testExtractRange(` + testExtractRange("extractRange4", ` + var x = [$|10[#|00|]|]; + `); + testExtractRange("extractRange5", ` + [$|va[#|r foo = 1; + var y = 200|]0;|] + `); + testExtractRange("extractRange6", ` + var x = [$|fo[#|o.bar.baz()|]|]; + `); + testExtractRange("extractRange7", ` if ([#|[#extracted|a && b && c && d|]|]) { } `); - testExtractRange(` + testExtractRange("extractRange8", ` if [#|(a && b && c && d|]) { } `); - testExtractRange(` + testExtractRange("extractRange9", ` + if ([$|a[#|a && b && c && d|]d|]) { + } + `); + testExtractRange("extractRange10", ` if (a && b && c && d) { [#| [$|var x = 1; console.log(x);|] |] } `); - testExtractRange(` + testExtractRange("extractRange11", ` [#| if (a) { return 100; } |] `); - testExtractRange(` + testExtractRange("extractRange12", ` function foo() { [#| [$|if (a) { } return 100|] |] } `); - testExtractRange(` + testExtractRange("extractRange13", ` [#| [$|l1: if (x) { break l1; }|]|] `); - testExtractRange(` + testExtractRange("extractRange14", ` [#| [$|l2: { @@ -101,21 +116,21 @@ namespace ts { break l2; }|]|] `); - testExtractRange(` + testExtractRange("extractRange15", ` while (true) { [#| if(x) { } break; |] } `); - testExtractRange(` + testExtractRange("extractRange16", ` while (true) { [#| if(x) { } continue; |] } `); - testExtractRange(` + testExtractRange("extractRange17", ` l3: { [#| @@ -124,7 +139,7 @@ namespace ts { break l3; |] } `); - testExtractRange(` + testExtractRange("extractRange18", ` function f() { while (true) { [#| @@ -134,7 +149,7 @@ namespace ts { } } `); - testExtractRange(` + testExtractRange("extractRange19", ` function f() { while (true) { [#| @@ -145,13 +160,13 @@ namespace ts { } } `); - testExtractRange(` + testExtractRange("extractRange20", ` function f() { return [#| [$|1 + 2|] |]+ 3; } } `); - testExtractRange(` + testExtractRange("extractRange21", ` function f(x: number) { [#|[$|try { x++; @@ -163,17 +178,21 @@ namespace ts { `); // Variable statements - testExtractRange(`[#|let x = [$|1|];|]`); - testExtractRange(`[#|let x = [$|1|], y;|]`); - testExtractRange(`[#|[$|let x = 1, y = 1;|]|]`); + testExtractRange("extractRange22", `[#|let x = [$|1|];|]`); + testExtractRange("extractRange23", `[#|let x = [$|1|], y;|]`); + testExtractRange("extractRange24", `[#|[$|let x = 1, y = 1;|]|]`); // Variable declarations - testExtractRange(`let [#|x = [$|1|]|];`); - testExtractRange(`let [#|x = [$|1|]|], y = 2;`); - testExtractRange(`let x = 1, [#|y = [$|2|]|];`); + testExtractRange("extractRange25", `let [#|x = [$|1|]|];`); + testExtractRange("extractRange26", `let [#|x = [$|1|]|], y = 2;`); + testExtractRange("extractRange27", `let x = 1, [#|y = [$|2|]|];`); // Return statements - testExtractRange(`[#|return [$|1|];|]`); + testExtractRange("extractRange28", `[#|return [$|1|];|]`); + + // For statements + testExtractRange("extractRange29", `for ([#|var i = 1|]; i < 2; i++) {}`); + testExtractRange("extractRange30", `for (var i = [#|[$|1|]|]; i < 2; i++) {}`); }); testExtractRangeFailed("extractRangeFailed1", diff --git a/src/testRunner/unittests/services/languageService.ts b/src/testRunner/unittests/services/languageService.ts index 6aba1018062d6..a1f7e5844b84d 100644 --- a/src/testRunner/unittests/services/languageService.ts +++ b/src/testRunner/unittests/services/languageService.ts @@ -138,5 +138,135 @@ export function Component(x: Config): any;` verifyProgramUptoDate(/*useProjectVersion*/ false); }); }); + + describe("detects program upto date when new file is added to the referenced project", () => { + function setup(useSourceOfProjectReferenceRedirect: (() => boolean) | undefined) { + const config1: TestFSWithWatch.File = { + path: `${tscWatch.projectRoot}/projects/project1/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + module: "none", + composite: true + }, + exclude: ["temp"] + }) + }; + const class1: TestFSWithWatch.File = { + path: `${tscWatch.projectRoot}/projects/project1/class1.ts`, + content: `class class1 {}` + }; + const class1Dts: TestFSWithWatch.File = { + path: `${tscWatch.projectRoot}/projects/project1/class1.d.ts`, + content: `declare class class1 {}` + }; + const config2: TestFSWithWatch.File = { + path: `${tscWatch.projectRoot}/projects/project2/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + module: "none", + composite: true + }, + references: [ + { path: "../project1" } + ] + }) + }; + const class2: TestFSWithWatch.File = { + path: `${tscWatch.projectRoot}/projects/project2/class2.ts`, + content: `class class2 {}` + }; + const system = projectSystem.createServerHost([config1, class1, class1Dts, config2, class2, projectSystem.libFile]); + const result = getParsedCommandLineOfConfigFile(`${tscWatch.projectRoot}/projects/project2/tsconfig.json`, /*optionsToExtend*/ undefined, { + useCaseSensitiveFileNames: true, + fileExists: path => system.fileExists(path), + readFile: path => system.readFile(path), + getCurrentDirectory: () => system.getCurrentDirectory(), + readDirectory: (path, extensions, excludes, includes, depth) => system.readDirectory(path, extensions, excludes, includes, depth), + onUnRecoverableConfigFileDiagnostic: noop, + })!; + const host: LanguageServiceHost = { + useCaseSensitiveFileNames: returnTrue, + useSourceOfProjectReferenceRedirect, + getCompilationSettings: () => result.options, + fileExists: path => system.fileExists(path), + getScriptFileNames: () => result.fileNames, + getScriptVersion: path => { + const text = system.readFile(path); + return text !== undefined ? system.createHash(path) : ""; + }, + getScriptSnapshot: path => { + const text = system.readFile(path); + return text ? ScriptSnapshot.fromString(text) : undefined; + }, + readDirectory: (path, extensions, excludes, includes, depth) => system.readDirectory(path, extensions, excludes, includes, depth), + getCurrentDirectory: () => system.getCurrentDirectory(), + getDefaultLibFileName: () => projectSystem.libFile.path, + getProjectReferences: () => result.projectReferences, + }; + const ls = ts.createLanguageService(host); + return { system, ls, class1, class1Dts, class2 }; + } + it("detects program upto date when new file is added to the referenced project", () => { + const { ls, system, class1, class2 } = setup(returnTrue); + assert.deepEqual( + ls.getProgram()!.getSourceFiles().map(f => f.fileName), + [projectSystem.libFile.path, class1.path, class2.path] + ); + // Add new file to referenced project + const class3 = `${tscWatch.projectRoot}/projects/project1/class3.ts`; + system.writeFile(class3, `class class3 {}`); + const program = ls.getProgram()!; + assert.deepEqual( + program.getSourceFiles().map(f => f.fileName), + [projectSystem.libFile.path, class1.path, class3, class2.path] + ); + // Add excluded file to referenced project + system.ensureFileOrFolder({ path: `${tscWatch.projectRoot}/projects/project1/temp/file.d.ts`, content: `declare class file {}` }); + assert.strictEqual(ls.getProgram(), program); + // Add output from new class to referenced project + system.writeFile(`${tscWatch.projectRoot}/projects/project1/class3.d.ts`, `declare class class3 {}`); + assert.strictEqual(ls.getProgram(), program); + }); + + it("detects program upto date when new file is added to the referenced project without useSourceOfProjectReferenceRedirect", () => { + const { ls, system, class1Dts, class2 } = setup(/*useSourceOfProjectReferenceRedirect*/ undefined); + const program1 = ls.getProgram()!; + assert.deepEqual( + program1.getSourceFiles().map(f => f.fileName), + [projectSystem.libFile.path, class1Dts.path, class2.path] + ); + // Add new file to referenced project + const class3 = `${tscWatch.projectRoot}/projects/project1/class3.ts`; + system.writeFile(class3, `class class3 {}`); + assert.notStrictEqual(ls.getProgram(), program1); + assert.deepEqual( + ls.getProgram()!.getSourceFiles().map(f => f.fileName), + [projectSystem.libFile.path, class1Dts.path, class2.path] + ); + // Add class3 output + const class3Dts = `${tscWatch.projectRoot}/projects/project1/class3.d.ts`; + system.writeFile(class3Dts, `declare class class3 {}`); + const program2 = ls.getProgram()!; + assert.deepEqual( + program2.getSourceFiles().map(f => f.fileName), + [projectSystem.libFile.path, class1Dts.path, class3Dts, class2.path] + ); + // Add excluded file to referenced project + system.ensureFileOrFolder({ path: `${tscWatch.projectRoot}/projects/project1/temp/file.d.ts`, content: `declare class file {}` }); + assert.strictEqual(ls.getProgram(), program2); + // Delete output from new class to referenced project + system.deleteFile(class3Dts); + assert.deepEqual( + ls.getProgram()!.getSourceFiles().map(f => f.fileName), + [projectSystem.libFile.path, class1Dts.path, class2.path] + ); + // Write output again + system.writeFile(class3Dts, `declare class class3 {}`); + assert.deepEqual( + ls.getProgram()!.getSourceFiles().map(f => f.fileName), + [projectSystem.libFile.path, class1Dts.path, class3Dts, class2.path] + ); + }); + }); }); } diff --git a/src/testRunner/unittests/services/organizeImports.ts b/src/testRunner/unittests/services/organizeImports.ts index 13f3f126c9e46..496f2d401d38b 100644 --- a/src/testRunner/unittests/services/organizeImports.ts +++ b/src/testRunner/unittests/services/organizeImports.ts @@ -339,6 +339,7 @@ export const Other = 1; }); testOrganizeImports("Renamed_used", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -349,6 +350,7 @@ EffOne(); libFile); testOrganizeImports("Simple", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -365,6 +367,7 @@ F2(); libFile); testOrganizeImports("Unused_Some", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -377,6 +380,70 @@ D(); }, libFile); + describe("skipDestructiveCodeActions=true", () => { + testOrganizeImports("Syntax_Error_Body_skipDestructiveCodeActions", + /*skipDestructiveCodeActions*/ true, + { + path: "/test.ts", + content: ` +import { F1, F2 } from "lib"; +import * as NS from "lib"; +import D from "lib"; + +class class class; +D; +`, + }, + libFile); + }); + + testOrganizeImports("Syntax_Error_Imports_skipDestructiveCodeActions", + /*skipDestructiveCodeActions*/ true, + { + path: "/test.ts", + content: ` +import { F1, F2 class class class; } from "lib"; +import * as NS from "lib"; +class class class; +import D from "lib"; + +D; +`, + }, + libFile); + + describe("skipDestructiveCodeActions=false", () => { + testOrganizeImports("Syntax_Error_Body", + /*skipDestructiveCodeActions*/ false, + { + path: "/test.ts", + content: ` +import { F1, F2 } from "lib"; +import * as NS from "lib"; +import D from "lib"; + +class class class; +D; +`, + }, + libFile); + + testOrganizeImports("Syntax_Error_Imports", + /*skipDestructiveCodeActions*/ false, + { + path: "/test.ts", + content: ` +import { F1, F2 class class class; } from "lib"; +import * as NS from "lib"; +class class class; +import D from "lib"; + +D; +`, + }, + libFile); + }); + it("doesn't return any changes when the text would be identical", () => { const testFile = { path: "/a.ts", @@ -388,6 +455,7 @@ D(); }); testOrganizeImports("Unused_All", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -411,6 +479,7 @@ import { } from "lib"; }); testOrganizeImports("Unused_false_positive_module_augmentation", + /*skipDestructiveCodeActions*/ false, { path: "/test.d.ts", content: ` @@ -426,6 +495,7 @@ declare module 'caseless' { }); testOrganizeImports("Unused_preserve_imports_for_module_augmentation_in_non_declaration_file", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -467,6 +537,7 @@ export { x }; }); testOrganizeImports("MoveToTop", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -483,6 +554,7 @@ D(); /* eslint-disable no-template-curly-in-string */ testOrganizeImports("MoveToTop_Invalid", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -501,6 +573,7 @@ D(); /* eslint-enable no-template-curly-in-string */ testOrganizeImports("TypeOnly", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -513,6 +586,7 @@ export { A, B, X, Y, Z };` }); testOrganizeImports("CoalesceMultipleModules", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -527,6 +601,7 @@ a + b + c + d; { path: "/lib2.ts", content: "export const a = 3, c = 4;" }); testOrganizeImports("CoalesceTrivia", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -540,6 +615,7 @@ F2(); libFile); testOrganizeImports("SortTrivia", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -551,6 +627,7 @@ F2(); { path: "/lib2.ts", content: "" }); testOrganizeImports("UnusedTrivia1", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -560,6 +637,7 @@ F2(); libFile); testOrganizeImports("UnusedTrivia2", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -571,6 +649,7 @@ F1(); libFile); testOrganizeImports("UnusedHeaderComment", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -581,6 +660,7 @@ import { F1 } from "lib"; libFile); testOrganizeImports("SortHeaderComment", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -593,6 +673,7 @@ import "lib1"; { path: "/lib2.ts", content: "" }); testOrganizeImports("SortComments", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -609,6 +690,7 @@ import "lib1"; { path: "/lib3.ts", content: "" }); testOrganizeImports("AmbientModule", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -624,6 +706,7 @@ declare module "mod" { libFile); testOrganizeImports("TopLevelAndAmbientModule", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -646,6 +729,7 @@ D(); libFile); testOrganizeImports("JsxFactoryUsedJsx", + /*skipDestructiveCodeActions*/ false, { path: "/test.jsx", content: ` @@ -657,6 +741,7 @@ import { React, Other } from "react"; reactLibFile); testOrganizeImports("JsxFactoryUsedJs", + /*skipDestructiveCodeActions*/ false, { path: "/test.js", content: ` @@ -668,6 +753,7 @@ import { React, Other } from "react"; reactLibFile); testOrganizeImports("JsxFactoryUsedTsx", + /*skipDestructiveCodeActions*/ false, { path: "/test.tsx", content: ` @@ -681,6 +767,7 @@ import { React, Other } from "react"; // TS files are not JSX contexts, so the parser does not treat // `
` as a JSX element. testOrganizeImports("JsxFactoryUsedTs", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -692,6 +779,7 @@ import { React, Other } from "react"; reactLibFile); testOrganizeImports("JsxFactoryUnusedJsx", + /*skipDestructiveCodeActions*/ false, { path: "/test.jsx", content: ` @@ -703,6 +791,7 @@ import { React, Other } from "react"; // Note: Since the file extension does not end with "x", the jsx compiler option // will not be enabled. The import should be retained regardless. testOrganizeImports("JsxFactoryUnusedJs", + /*skipDestructiveCodeActions*/ false, { path: "/test.js", content: ` @@ -712,6 +801,7 @@ import { React, Other } from "react"; reactLibFile); testOrganizeImports("JsxFactoryUnusedTsx", + /*skipDestructiveCodeActions*/ false, { path: "/test.tsx", content: ` @@ -721,6 +811,7 @@ import { React, Other } from "react"; reactLibFile); testOrganizeImports("JsxFactoryUnusedTs", + /*skipDestructiveCodeActions*/ false, { path: "/test.ts", content: ` @@ -730,6 +821,7 @@ import { React, Other } from "react"; reactLibFile); testOrganizeImports("JsxPragmaTsx", + /*skipDestructiveCodeActions*/ false, { path: "/test.tsx", content: `/** @jsx jsx */ @@ -758,6 +850,7 @@ export namespace React { ); testOrganizeImports("JsxFragmentPragmaTsx", + /*skipDestructiveCodeActions*/ false, { path: "/test.tsx", content: `/** @jsx h */ @@ -920,17 +1013,17 @@ export * from "lib"; }); function testOrganizeExports(testName: string, testFile: TestFSWithWatch.File, ...otherFiles: TestFSWithWatch.File[]) { - testOrganizeImports(`${testName}.exports`, testFile, ...otherFiles); + testOrganizeImports(`${testName}.exports`, /*skipDestructiveCodeActions*/ true, testFile, ...otherFiles); } - function testOrganizeImports(testName: string, testFile: TestFSWithWatch.File, ...otherFiles: TestFSWithWatch.File[]) { - it(testName, () => runBaseline(`organizeImports/${testName}.ts`, testFile, ...otherFiles)); + function testOrganizeImports(testName: string, skipDestructiveCodeActions: boolean, testFile: TestFSWithWatch.File, ...otherFiles: TestFSWithWatch.File[]) { + it(testName, () => runBaseline(`organizeImports/${testName}.ts`, skipDestructiveCodeActions, testFile, ...otherFiles)); } - function runBaseline(baselinePath: string, testFile: TestFSWithWatch.File, ...otherFiles: TestFSWithWatch.File[]) { + function runBaseline(baselinePath: string, skipDestructiveCodeActions: boolean, 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 }, testFormatSettings, emptyOptions); + const changes = languageService.organizeImports({ skipDestructiveCodeActions, type: "file", fileName: testPath }, testFormatSettings, emptyOptions); assert.equal(changes.length, 1); assert.equal(changes[0].fileName, testPath); diff --git a/src/testRunner/unittests/services/transpile.ts b/src/testRunner/unittests/services/transpile.ts index 765b4f345e644..48cb85820335f 100644 --- a/src/testRunner/unittests/services/transpile.ts +++ b/src/testRunner/unittests/services/transpile.ts @@ -372,7 +372,7 @@ var x = 0;`, { }); transpilesCorrectly("Supports setting 'rootDir'", "x;", { - options: { compilerOptions: { rootDir: "./rootDir" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { rootDir: "./rootDir" }, fileName: "./rootDir/input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'rootDirs'", "x;", { diff --git a/src/testRunner/unittests/transform.ts b/src/testRunner/unittests/transform.ts index e18dd33c92c3c..470366d39098d 100644 --- a/src/testRunner/unittests/transform.ts +++ b/src/testRunner/unittests/transform.ts @@ -176,6 +176,7 @@ namespace ts { compilerOptions: { target: ScriptTarget.ESNext, newLine: NewLineKind.CarriageReturnLineFeed, + useDefineForClassFields: false, } }).outputText; }); diff --git a/src/testRunner/unittests/tsbuild/clean.ts b/src/testRunner/unittests/tsbuild/clean.ts new file mode 100644 index 0000000000000..90bb298529028 --- /dev/null +++ b/src/testRunner/unittests/tsbuild/clean.ts @@ -0,0 +1,16 @@ +namespace ts { + describe("unittests:: tsbuild - clean", () => { + verifyTsc({ + scenario: "clean", + subScenario: `file name and output name clashing`, + commandLineArgs: ["--b", "/src/tsconfig.json", "-clean"], + fs: () => loadProjectFromFiles({ + "/src/index.js": "", + "/src/bar.ts": "", + "/src/tsconfig.json": JSON.stringify({ + compilerOptions: { allowJs: true }, + }), + }), + }); + }); +} \ No newline at end of file diff --git a/src/testRunner/unittests/tsbuild/helpers.ts b/src/testRunner/unittests/tsbuild/helpers.ts index 1701f895378ba..776ef9fcb062e 100644 --- a/src/testRunner/unittests/tsbuild/helpers.ts +++ b/src/testRunner/unittests/tsbuild/helpers.ts @@ -186,7 +186,7 @@ interface Symbol { } } - export function generateSourceMapBaselineFiles(sys: System & { writtenFiles: ReadonlyCollection; }) { + export function generateSourceMapBaselineFiles(sys: System & { writtenFiles: ReadonlyCollection; }) { const mapFileNames = mapDefinedIterator(sys.writtenFiles.keys(), f => f.endsWith(".map") ? f : undefined); while (true) { const result = mapFileNames.next(); @@ -236,18 +236,89 @@ interface Symbol { } } + type ProgramBuildInfoDiagnostic = string | [string, readonly ReusableDiagnostic[]]; + type ProgramBuilderInfoFilePendingEmit = [string, "DtsOnly" | "Full"]; + interface ProgramBuildInfo { + fileNames: readonly string[]; + fileNamesList: readonly (readonly string[])[] | undefined; + fileInfos: MapLike; + options: CompilerOptions | undefined; + referencedMap?: MapLike; + exportedModulesMap?: MapLike; + semanticDiagnosticsPerFile?: readonly ProgramBuildInfoDiagnostic[]; + affectedFilesPendingEmit?: readonly ProgramBuilderInfoFilePendingEmit[]; + } + type ReadableBuildInfo = Omit & { program: ProgramBuildInfo | undefined; size: number; }; + function generateBuildInfoProgramBaseline(sys: System, originalWriteFile: System["writeFile"], buildInfoPath: string, buildInfo: BuildInfo) { + const fileInfos: ProgramBuildInfo["fileInfos"] = {}; + buildInfo.program?.fileInfos.forEach((fileInfo, index) => fileInfos[toFileName(index + 1)] = toBuilderStateFileInfo(fileInfo)); + const fileNamesList = buildInfo.program?.fileIdsList?.map(fileIdsListId => fileIdsListId.map(toFileName)); + const program: ProgramBuildInfo | undefined = buildInfo.program && { + fileNames: buildInfo.program.fileNames, + fileNamesList, + fileInfos, + options: buildInfo.program.options, + referencedMap: toMapOfReferencedSet(buildInfo.program.referencedMap), + exportedModulesMap: toMapOfReferencedSet(buildInfo.program.exportedModulesMap), + semanticDiagnosticsPerFile: buildInfo.program.semanticDiagnosticsPerFile?.map(d => + isNumber(d) ? + toFileName(d) : + [toFileName(d[0]), d[1]] + ), + affectedFilesPendingEmit: buildInfo.program.affectedFilesPendingEmit?.map(([fileId, emitKind]) => [ + toFileName(fileId), + emitKind === BuilderFileEmit.DtsOnly ? "DtsOnly" : + emitKind === BuilderFileEmit.Full ? "Full" : + Debug.assertNever(emitKind) + ]), + }; + const version = buildInfo.version === ts.version ? fakes.version : buildInfo.version; + const result: ReadableBuildInfo = { + bundle: buildInfo.bundle, + program, + version, + size: getBuildInfoText({ ...buildInfo, version }).length, + }; + // For now its just JSON.stringify + originalWriteFile.call(sys, `${buildInfoPath}.readable.baseline.txt`, JSON.stringify(result, /*replacer*/ undefined, 2)); + + function toFileName(fileId: number) { + return buildInfo.program!.fileNames[fileId - 1]; + } + + function toFileNames(fileIdsListId: number) { + return fileNamesList![fileIdsListId - 1]; + } + + function toMapOfReferencedSet(referenceMap: ProgramBuildInfoReferencedMap | undefined): MapLike | undefined { + if (!referenceMap) return undefined; + const result: MapLike = {}; + for (const [fileNamesKey, fileNamesListKey] of referenceMap) { + result[toFileName(fileNamesKey)] = toFileNames(fileNamesListKey); + } + return result; + } + } + + export function toPathWithSystem(sys: System, fileName: string): Path { + return toPath(fileName, sys.getCurrentDirectory(), createGetCanonicalFileName(sys.useCaseSensitiveFileNames)); + } + export function baselineBuildInfo( options: CompilerOptions, - sys: System & { writtenFiles: ReadonlyCollection; }, - originalReadCall?: System["readFile"] + sys: System & { writtenFiles: ReadonlyCollection; }, + originalReadCall?: System["readFile"], + originalWriteFile?: System["writeFile"], ) { - const out = outFile(options); - if (!out) return; - const { buildInfoPath, jsFilePath, declarationFilePath } = getOutputPathsForBundle(options, /*forceDts*/ false); - if (!buildInfoPath || !sys.writtenFiles.has(buildInfoPath)) return; + const buildInfoPath = getTsBuildInfoEmitOutputFilePath(options); + if (!buildInfoPath || !sys.writtenFiles.has(toPathWithSystem(sys, buildInfoPath))) return; if (!sys.fileExists(buildInfoPath)) return; const buildInfo = getBuildInfo((originalReadCall || sys.readFile).call(sys, buildInfoPath, "utf8")!); + generateBuildInfoProgramBaseline(sys, originalWriteFile || sys.writeFile, buildInfoPath, buildInfo); + + if (!outFile(options)) return; + const { jsFilePath, declarationFilePath } = getOutputPathsForBundle(options, /*forceDts*/ false); const bundle = buildInfo.bundle; if (!bundle || (!length(bundle.js && bundle.js.sections) && !length(bundle.dts && bundle.dts.sections))) return; @@ -256,14 +327,12 @@ interface Symbol { generateBundleFileSectionInfo(sys, originalReadCall || sys.readFile, baselineRecorder, bundle.js, jsFilePath); generateBundleFileSectionInfo(sys, originalReadCall || sys.readFile, baselineRecorder, bundle.dts, declarationFilePath); baselineRecorder.Close(); - const text = baselineRecorder.lines.join("\r\n"); - sys.writeFile(`${buildInfoPath}.baseline.txt`, text); + (originalWriteFile || sys.writeFile).call(sys, `${buildInfoPath}.baseline.txt`, text); } interface VerifyIncrementalCorrectness { scenario: TscCompile["scenario"]; - subScenario: TscCompile["subScenario"]; commandLineArgs: TscCompile["commandLineArgs"]; modifyFs: TscCompile["modifyFs"]; incrementalModifyFs: TscIncremental["modifyFs"]; @@ -272,10 +341,10 @@ interface Symbol { newSys: TscCompileSystem; cleanBuildDiscrepancies: TscIncremental["cleanBuildDiscrepancies"]; } - function verifyIncrementalCorrectness(input: () => VerifyIncrementalCorrectness, index: number) { - it(`Verify emit output file text is same when built clean for incremental scenario at:: ${index}`, () => { + function verifyIncrementalCorrectness(input: () => VerifyIncrementalCorrectness, index: number, subScenario: TscCompile["subScenario"]) { + it(`Verify emit output file text is same when built clean for incremental scenario at:: ${index} ${subScenario}`, () => { const { - scenario, subScenario, commandLineArgs, cleanBuildDiscrepancies, + scenario, commandLineArgs, cleanBuildDiscrepancies, modifyFs, incrementalModifyFs, tick, baseFs, newSys } = input(); @@ -289,29 +358,65 @@ interface Symbol { if (modifyFs) modifyFs(fs); incrementalModifyFs(fs); }, + disableUseFileVersionAsSignature: true, }); const discrepancies = cleanBuildDiscrepancies?.(); for (const outputFile of arrayFrom(sys.writtenFiles.keys())) { const cleanBuildText = sys.readFile(outputFile); const incrementalBuildText = newSys.readFile(outputFile); const descrepancyInClean = discrepancies?.get(outputFile); - if (!isBuildInfoFile(outputFile)) { + if (isBuildInfoFile(outputFile)) { + // Check only presence and absence and not text as we will do that for readable baseline + assert.isTrue(sys.fileExists(`${outputFile}.readable.baseline.txt`), `Readable baseline should be present in clean build:: File:: ${outputFile}`); + assert.isTrue(newSys.fileExists(`${outputFile}.readable.baseline.txt`), `Readable baseline should be present in incremental build:: File:: ${outputFile}`); + if (descrepancyInClean === undefined) { + verifyPresenceAbsence(incrementalBuildText, cleanBuildText, `Incremental and clean tsbuildinfo file presence should match:: File:: ${outputFile}`); + } + else { + verifyTextEqual(incrementalBuildText, cleanBuildText, descrepancyInClean, `File: ${outputFile}`); + } + } + else if (!fileExtensionIs(outputFile, ".tsbuildinfo.readable.baseline.txt")) { verifyTextEqual(incrementalBuildText, cleanBuildText, descrepancyInClean, `File: ${outputFile}`); } else if (incrementalBuildText !== cleanBuildText) { // Verify build info without affectedFilesPendingEmit - const { buildInfo: incrementalBuildInfo, affectedFilesPendingEmit: incrementalBuildAffectedFilesPendingEmit } = getBuildInfoForIncrementalCorrectnessCheck(incrementalBuildText); - const { buildInfo: cleanBuildInfo, affectedFilesPendingEmit: incrementalAffectedFilesPendingEmit } = getBuildInfoForIncrementalCorrectnessCheck(cleanBuildText); + const { buildInfo: incrementalBuildInfo, readableBuildInfo: incrementalReadableBuildInfo } = getBuildInfoForIncrementalCorrectnessCheck(incrementalBuildText); + const { buildInfo: cleanBuildInfo, readableBuildInfo: cleanReadableBuildInfo } = getBuildInfoForIncrementalCorrectnessCheck(cleanBuildText); verifyTextEqual(incrementalBuildInfo, cleanBuildInfo, descrepancyInClean, `TsBuild info text without affectedFilesPendingEmit ${subScenario}:: ${outputFile}::\nIncremental buildInfoText:: ${incrementalBuildText}\nClean buildInfoText:: ${cleanBuildText}`); - // Verify that incrementally pending affected file emit are in clean build since clean build can contain more files compared to incremental depending of noEmitOnError option - if (incrementalBuildAffectedFilesPendingEmit && descrepancyInClean === undefined) { - assert.isDefined(incrementalAffectedFilesPendingEmit, `Incremental build contains affectedFilesPendingEmit, clean build should also have it: ${outputFile}::\nIncremental buildInfoText:: ${incrementalBuildText}\nClean buildInfoText:: ${cleanBuildText}`); - let expectedIndex = 0; - incrementalBuildAffectedFilesPendingEmit.forEach(([actualFile]) => { - expectedIndex = findIndex(incrementalAffectedFilesPendingEmit!, ([expectedFile]) => actualFile === expectedFile, expectedIndex); - assert.notEqual(expectedIndex, -1, `Incremental build contains ${actualFile} file as pending emit, clean build should also have it: ${outputFile}::\nIncremental buildInfoText:: ${incrementalBuildText}\nClean buildInfoText:: ${cleanBuildText}`); - expectedIndex++; - }); + if (descrepancyInClean === undefined) { + // Verify file info sigantures + verifyMapLike( + incrementalReadableBuildInfo?.program?.fileInfos, + cleanReadableBuildInfo?.program?.fileInfos, + (key, incrementalFileInfo, cleanFileInfo) => { + if (incrementalFileInfo.signature !== cleanFileInfo.signature && incrementalFileInfo.signature !== incrementalFileInfo.version) { + assert.fail(`Incremental signature should either be dts signature or file version for File:: ${key}:: Incremental:: ${JSON.stringify(incrementalFileInfo)}, Clean:: ${JSON.stringify(cleanFileInfo)}}`); + } + }, + `FileInfos:: File:: ${outputFile}` + ); + // Verify exportedModulesMap + verifyMapLike( + incrementalReadableBuildInfo?.program?.exportedModulesMap, + cleanReadableBuildInfo?.program?.exportedModulesMap, + (key, incrementalReferenceSet, cleanReferenceSet) => { + if (!arrayIsEqualTo(incrementalReferenceSet, cleanReferenceSet) && !arrayIsEqualTo(incrementalReferenceSet, incrementalReadableBuildInfo!.program!.referencedMap![key])) { + assert.fail(`Incremental Reference set should either be from dts or files reference map for File:: ${key}:: Incremental:: ${JSON.stringify(incrementalReferenceSet)}, Clean:: ${JSON.stringify(cleanReferenceSet)}, referenceMap:: ${JSON.stringify(incrementalReadableBuildInfo!.program!.referencedMap![key])}}`); + } + }, + `exportedModulesMap:: File:: ${outputFile}` + ); + // Verify that incrementally pending affected file emit are in clean build since clean build can contain more files compared to incremental depending of noEmitOnError option + if (incrementalReadableBuildInfo?.program?.affectedFilesPendingEmit) { + assert.isDefined(cleanReadableBuildInfo?.program?.affectedFilesPendingEmit, `Incremental build contains affectedFilesPendingEmit, clean build should also have it: ${outputFile}::\nIncremental buildInfoText:: ${incrementalBuildText}\nClean buildInfoText:: ${cleanBuildText}`); + let expectedIndex = 0; + incrementalReadableBuildInfo.program.affectedFilesPendingEmit.forEach(([actualFile]) => { + expectedIndex = findIndex(cleanReadableBuildInfo!.program!.affectedFilesPendingEmit!, ([expectedFile]) => actualFile === expectedFile, expectedIndex); + assert.notEqual(expectedIndex, -1, `Incremental build contains ${actualFile} file as pending emit, clean build should also have it: ${outputFile}::\nIncremental buildInfoText:: ${incrementalBuildText}\nClean buildInfoText:: ${cleanBuildText}`); + expectedIndex++; + }); + } } } } @@ -335,23 +440,56 @@ interface Symbol { Debug.assertNever(descrepancyInClean); } } + + function verifyMapLike(incremental: MapLike | undefined, clean: MapLike | undefined, verifyValue: (key: string, incrementalValue: T, cleanValue: T) => void, message: string) { + verifyPresenceAbsence(incremental, clean, `Incremental and clean presence should match:: ${message}`); + if (!incremental) return; + const incrementalMap = new Map(getEntries(incremental)); + const cleanMap = new Map(getEntries(clean!)); + assert.equal(incrementalMap.size, cleanMap.size, `Incremental and clean size of map should match:: ${message}, Incremental keys: ${arrayFrom(incrementalMap.keys())} Clean: ${arrayFrom(cleanMap.keys())}${TestFSWithWatch.getDiffInKeys(incrementalMap, arrayFrom(cleanMap.keys()))}`); + cleanMap.forEach((cleanValue, key) => { + assert.isTrue(incrementalMap.has(key), `Expected to contain ${key} in incremental map:: ${message}, Incremental keys: ${arrayFrom(incrementalMap.keys())}`); + verifyValue(key, incrementalMap.get(key)!, cleanValue); + }); + } }); } - function getBuildInfoForIncrementalCorrectnessCheck(text: string | undefined): { buildInfo: string | undefined; affectedFilesPendingEmit?: ProgramBuildInfo["affectedFilesPendingEmit"]; } { - const buildInfo = text ? getBuildInfo(text) : undefined; - if (!buildInfo?.program) return { buildInfo: text }; - // Ignore noEmit since that shouldnt be reason to emit the tsbuild info and presence of it in the buildinfo file does not matter - const { program: { affectedFilesPendingEmit, options: { noEmit, ...optionsRest}, ...programRest }, ...rest } = buildInfo; - return { - buildInfo: getBuildInfoText({ - ...rest, - program: { - options: optionsRest, - ...programRest + function verifyPresenceAbsence(actual: T | undefined, expected: T | undefined, message: string) { + (expected !== undefined ? assert.isDefined : assert.isUndefined)(actual, message); + } + + function getBuildInfoForIncrementalCorrectnessCheck(text: string | undefined): { + buildInfo: string | undefined; + readableBuildInfo?: ReadableBuildInfo; + } { + if (!text) return { buildInfo: text }; + const readableBuildInfo = JSON.parse(text) as ReadableBuildInfo; + let sanitizedFileInfos: MapLike | undefined; + if (readableBuildInfo.program) { + sanitizedFileInfos = {}; + for (const id in readableBuildInfo.program.fileInfos) { + if (hasProperty(readableBuildInfo.program.fileInfos, id)) { + sanitizedFileInfos[id] = { ...readableBuildInfo.program.fileInfos[id], signature: undefined }; } - }), - affectedFilesPendingEmit + } + } + return { + buildInfo: JSON.stringify({ + ...readableBuildInfo, + program: readableBuildInfo.program && { + ...readableBuildInfo.program, + fileNames: undefined, + fileNamesList: undefined, + fileInfos: sanitizedFileInfos, + // Ignore noEmit since that shouldnt be reason to emit the tsbuild info and presence of it in the buildinfo file does not matter + options: { ...readableBuildInfo.program.options, noEmit: undefined }, + exportedModulesMap: undefined, + affectedFilesPendingEmit: undefined, + }, + size: undefined, // Size doesnt need to be equal + }, /*replacer*/ undefined, 2), + readableBuildInfo, }; } @@ -455,7 +593,6 @@ interface Symbol { verifyTscBaseline(() => newSys); verifyIncrementalCorrectness(() => ({ scenario, - subScenario: incrementalSubScenario || subScenario, baseFs, newSys, commandLineArgs: incrementalCommandLineArgs || commandLineArgs, @@ -463,7 +600,7 @@ interface Symbol { incrementalModifyFs, modifyFs, tick - }), index); + }), index, incrementalSubScenario || subScenario); }); }); }); @@ -553,7 +690,6 @@ interface Symbol { describe("incremental correctness", () => { incrementalScenarios.forEach(({ commandLineArgs: incrementalCommandLineArgs, subScenario, buildKind, cleanBuildDiscrepancies }, index) => verifyIncrementalCorrectness(() => ({ scenario, - subScenario: subScenario || buildKind, baseFs, newSys: incrementalSys[index], commandLineArgs: incrementalCommandLineArgs || commandLineArgs, @@ -565,7 +701,7 @@ interface Symbol { }, modifyFs, tick - }), index)); + }), index, subScenario || buildKind)); }); }); } diff --git a/src/testRunner/unittests/tsbuild/inferredTypeFromTransitiveModule.ts b/src/testRunner/unittests/tsbuild/inferredTypeFromTransitiveModule.ts index eccd6e41aeb1a..e2d27de684a0a 100644 --- a/src/testRunner/unittests/tsbuild/inferredTypeFromTransitiveModule.ts +++ b/src/testRunner/unittests/tsbuild/inferredTypeFromTransitiveModule.ts @@ -13,10 +13,16 @@ namespace ts { subScenario: "inferred type from transitive module", fs: () => projFs, commandLineArgs: ["--b", "/src", "--verbose"], - incrementalScenarios: [{ - buildKind: BuildKind.IncrementalDtsChange, - modifyFs: changeBarParam, - }], + incrementalScenarios: [ + { + buildKind: BuildKind.IncrementalDtsChange, + modifyFs: changeBarParam, + }, + { + buildKind: BuildKind.IncrementalDtsChange, + modifyFs: changeBarParamBack, + }, + ], }); verifyTscSerializedIncrementalEdits({ @@ -25,10 +31,16 @@ namespace ts { scenario: "inferredTypeFromTransitiveModule", commandLineArgs: ["--b", "/src", "--verbose"], modifyFs: changeToIsolatedModules, - incrementalScenarios: [{ - buildKind: BuildKind.IncrementalDtsChange, - modifyFs: changeBarParam - }] + incrementalScenarios: [ + { + buildKind: BuildKind.IncrementalDtsChange, + modifyFs: changeBarParam + }, + { + buildKind: BuildKind.IncrementalDtsChange, + modifyFs: changeBarParamBack, + }, + ] }); verifyTscSerializedIncrementalEdits({ @@ -43,6 +55,14 @@ import { default as bar } from './bar'; bar("hello");`); }, incrementalScenarios: [ + { + buildKind: BuildKind.IncrementalDtsChange, + modifyFs: changeBarParam + }, + { + buildKind: BuildKind.IncrementalDtsChange, + modifyFs: changeBarParamBack, + }, { buildKind: BuildKind.IncrementalDtsChange, modifyFs: changeBarParam @@ -63,4 +83,8 @@ bar("hello");`); function changeBarParam(fs: vfs.FileSystem) { replaceText(fs, "/src/bar.ts", "param: string", ""); } + + function changeBarParamBack(fs: vfs.FileSystem) { + replaceText(fs, "/src/bar.ts", "foobar()", "foobar(param: string)"); + } } diff --git a/src/testRunner/unittests/tsbuild/javascriptProjectEmit.ts b/src/testRunner/unittests/tsbuild/javascriptProjectEmit.ts index 6658e5a198da5..6786205bb20a1 100644 --- a/src/testRunner/unittests/tsbuild/javascriptProjectEmit.ts +++ b/src/testRunner/unittests/tsbuild/javascriptProjectEmit.ts @@ -1,5 +1,5 @@ namespace ts { - describe("unittests:: tsbuild:: javascriptProjectEmit:: loads js-based projects and emits them correctly", () => { + describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { verifyTsc({ scenario: "javascriptProjectEmit", subScenario: `loads js-based projects and emits them correctly`, @@ -87,12 +87,11 @@ namespace ts { }, symbolLibContent), commandLineArgs: ["-b", "/src"] }); - }); - describe("unittests:: tsbuild:: javascriptProjectEmit:: loads outfile js projects and concatenates them correctly", () => { - let projFs: vfs.FileSystem; - before(() => { - projFs = loadProjectFromFiles({ + verifyTscSerializedIncrementalEdits({ + scenario: "javascriptProjectEmit", + subScenario: `modifies outfile js projects and concatenates them correctly`, + fs: () => loadProjectFromFiles({ "/src/common/nominal.js": Utils.dedent` /** * @template T, Name @@ -175,30 +174,14 @@ namespace ts { "declaration": true } }`, - }, symbolLibContent); - }); - after(() => { - projFs = undefined!; - }); - verifyTsc({ - scenario: "javascriptProjectEmit", - subScenario: `loads outfile js projects and concatenates them correctly`, - fs: () => projFs, - commandLineArgs: ["-b", "/src"] - }); - verifyTscSerializedIncrementalEdits({ - scenario: "javascriptProjectEmit", - subScenario: `modifies outfile js projects and concatenates them correctly`, - fs: () => projFs, + }, symbolLibContent), commandLineArgs: ["-b", "/src"], incrementalScenarios: [{ buildKind: BuildKind.IncrementalDtsUnchanged, modifyFs: fs => replaceText(fs, "/src/sub-project/index.js", "null", "undefined") }] }); - }); - describe("unittests:: tsbuild:: javascriptProjectEmit:: loads js-based projects with non-moved json files and emits them correctly", () => { verifyTsc({ scenario: "javascriptProjectEmit", subScenario: `loads js-based projects with non-moved json files and emits them correctly`, diff --git a/src/testRunner/unittests/tsbuild/lateBoundSymbol.ts b/src/testRunner/unittests/tsbuild/lateBoundSymbol.ts index 5ea071a0ca2bf..953e7f7f045a3 100644 --- a/src/testRunner/unittests/tsbuild/lateBoundSymbol.ts +++ b/src/testRunner/unittests/tsbuild/lateBoundSymbol.ts @@ -5,10 +5,16 @@ namespace ts { fs: () => loadProjectFromDisk("tests/projects/lateBoundSymbol"), scenario: "lateBoundSymbol", commandLineArgs: ["--b", "/src/tsconfig.json", "--verbose"], - incrementalScenarios: [{ - buildKind: BuildKind.IncrementalDtsUnchanged, - modifyFs: fs => replaceText(fs, "/src/src/main.ts", "const x = 10;", ""), - }] + incrementalScenarios: [ + { + buildKind: BuildKind.IncrementalDtsUnchanged, + modifyFs: fs => replaceText(fs, "/src/src/main.ts", "const x = 10;", ""), + }, + { + buildKind: BuildKind.IncrementalDtsUnchanged, + modifyFs: fs => appendText(fs, "/src/src/main.ts", "const x = 10;"), + }, + ] }); }); } diff --git a/src/testRunner/unittests/tsbuild/moduleResolution.ts b/src/testRunner/unittests/tsbuild/moduleResolution.ts index 11403bdc18fdd..487f83196c36e 100644 --- a/src/testRunner/unittests/tsbuild/moduleResolution.ts +++ b/src/testRunner/unittests/tsbuild/moduleResolution.ts @@ -65,5 +65,25 @@ namespace ts.tscWatch { commandLineArgs: ["-b", "packages/pkg1", "--verbose", "--traceResolution"], changes: emptyArray }); + + verifyTsc({ + scenario: "moduleResolution", + subScenario: `type reference resolution uses correct options for different resolution options referenced project`, + fs: () => loadProjectFromFiles({ + "/src/packages/pkg1_index.ts": `export const theNum: TheNum = "type1";`, + "/src/packages/pkg1.tsconfig.json": JSON.stringify({ + compilerOptions: { composite: true, typeRoots: ["./typeroot1"] }, + files: ["./pkg1_index.ts"] + }), + "/src/packages/typeroot1/sometype/index.d.ts": Utils.dedent`declare type TheNum = "type1";`, + "/src/packages/pkg2_index.ts": `export const theNum: TheNum2 = "type2";`, + "/src/packages/pkg2.tsconfig.json": JSON.stringify({ + compilerOptions: { composite: true, typeRoots: ["./typeroot2"] }, + files: ["./pkg2_index.ts"] + }), + "/src/packages/typeroot2/sometype/index.d.ts": Utils.dedent`declare type TheNum2 = "type2";`, + }), + commandLineArgs: ["-b", "/src/packages/pkg1.tsconfig.json", "/src/packages/pkg2.tsconfig.json", "--verbose", "--traceResolution"], + }); }); } diff --git a/src/testRunner/unittests/tsbuild/outputPaths.ts b/src/testRunner/unittests/tsbuild/outputPaths.ts index 96298e3aeb8fb..e2a9ac549bf0a 100644 --- a/src/testRunner/unittests/tsbuild/outputPaths.ts +++ b/src/testRunner/unittests/tsbuild/outputPaths.ts @@ -23,7 +23,7 @@ namespace ts { ; assert.deepEqual( getOutputFileNames( - parseConfigFileWithSystem("/src/tsconfig.json", {}, {}, sys, noop)!, + parseConfigFileWithSystem("/src/tsconfig.json", {}, /*extendedConfigCache*/ undefined, {}, sys, noop)!, "/src/src/index.ts", /*ignoreCase*/ false ), @@ -60,11 +60,10 @@ namespace ts { noChangeRun, { ...noChangeProject, - cleanBuildDiscrepancies: () => { - const map = new Map(); - map.set("/src/dist/tsconfig.tsbuildinfo", CleanBuildDescrepancy.CleanFileTextDifferent); // tsbuildinfo will have -p setting when built using -p vs no build happens incrementally because of no change. - return map; - } + cleanBuildDiscrepancies: () => new Map([ + ["/src/dist/tsconfig.tsbuildinfo", CleanBuildDescrepancy.CleanFileTextDifferent], // tsbuildinfo will have -p setting when built using -p vs no build happens incrementally because of no change. + ["/src/dist/tsconfig.tsbuildinfo.readable.baseline.txt", CleanBuildDescrepancy.CleanFileTextDifferent] // tsbuildinfo will have -p setting when built using -p vs no build happens incrementally because of no change. + ]), } ], }, ["/src/dist/src/index.js", "/src/dist/src/index.d.ts"]); diff --git a/src/testRunner/unittests/tsbuild/publicApi.ts b/src/testRunner/unittests/tsbuild/publicApi.ts new file mode 100644 index 0000000000000..6c4e634108044 --- /dev/null +++ b/src/testRunner/unittests/tsbuild/publicApi.ts @@ -0,0 +1,124 @@ +namespace ts { + describe("unittests:: tsbuild:: Public API with custom transformers when passed to build", () => { + let sys: TscCompileSystem; + before(() => { + const initialFs = getFsWithTime(loadProjectFromFiles({ + "/src/tsconfig.json": JSON.stringify({ + references: [ + { path: "./shared/tsconfig.json" }, + { path: "./webpack/tsconfig.json" } + ], + files: [] + }), + "/src/shared/tsconfig.json": JSON.stringify({ + compilerOptions: { composite: true }, + }), + "/src/shared/index.ts": `export function f1() { } +export class c { } +export enum e { } +// leading +export function f2() { } // trailing`, + "/src/webpack/tsconfig.json": JSON.stringify({ + compilerOptions: { + composite: true, + }, + references: [{ path: "../shared/tsconfig.json" }] + }), + "/src/webpack/index.ts": `export function f2() { } +export class c2 { } +export enum e2 { } +// leading +export function f22() { } // trailing`, + })).fs.makeReadonly(); + const inputFs = initialFs.shadow(); + inputFs.makeReadonly(); + const fs = inputFs.shadow(); + + // Create system + sys = new fakes.System(fs, { executingFilePath: "/lib/tsc" }) as TscCompileSystem; + fakes.patchHostForBuildInfoReadWrite(sys); + const commandLineArgs = ["--b", "/src/tsconfig.json"]; + sys.write(`${sys.getExecutingFilePath()} ${commandLineArgs.join(" ")}\n`); + sys.exit = exitCode => sys.exitCode = exitCode; + const writtenFiles = sys.writtenFiles = new Set(); + const originalWriteFile = sys.writeFile; + sys.writeFile = (fileName, content, writeByteOrderMark) => { + const path = toPathWithSystem(sys, fileName); + assert.isFalse(writtenFiles.has(path)); + writtenFiles.add(path); + return originalWriteFile.call(sys, fileName, content, writeByteOrderMark); + }; + const { cb, getPrograms } = commandLineCallbacks(sys, /*originalReadCall*/ undefined, originalWriteFile); + const buildHost = createSolutionBuilderHost( + sys, + /*createProgram*/ undefined, + createDiagnosticReporter(sys, /*pretty*/ true), + createBuilderStatusReporter(sys, /*pretty*/ true), + errorCount => sys.write(getErrorSummaryText(errorCount, sys.newLine)) + ); + buildHost.afterProgramEmitAndDiagnostics = cb; + buildHost.afterEmitBundle = cb; + const builder = createSolutionBuilder(buildHost, [commandLineArgs[1]], { verbose: true }); + const exitStatus = builder.build(/*project*/ undefined, /*cancellationToken*/ undefined, /*writeFile*/ undefined, getCustomTransformers); + sys.exit(exitStatus); + sys.write(`exitCode:: ExitStatus.${ExitStatus[sys.exitCode as ExitStatus]}\n`); + const baseline: string[] = []; + tscWatch.baselinePrograms(baseline, getPrograms, emptyArray, /*baselineDependencies*/ false); + sys.write(baseline.join("\n")); + fs.makeReadonly(); + sys.baseLine = () => { + const baseFsPatch = inputFs.diff(/*base*/ undefined, { baseIsNotShadowRoot: true }); + const patch = fs.diff(inputFs, { includeChangedFileWithSameContent: true }); + return { + file: `tsbuild/$publicAPI/${BuildKind.Initial}/${"build with custom transformers".split(" ").join("-")}.js`, + text: `Input:: +${baseFsPatch ? vfs.formatPatch(baseFsPatch) : ""} + +Output:: +${sys.output.join("")} + +${patch ? vfs.formatPatch(patch) : ""}` + }; + }; + + function getCustomTransformers(project: string): CustomTransformers { + const before: TransformerFactory = context => { + return file => visitEachChild(file, visit, context); + function visit(node: Node): VisitResult { + switch (node.kind) { + case SyntaxKind.FunctionDeclaration: + return visitFunction(node); + default: + return visitEachChild(node, visit, context); + } + } + function visitFunction(node: FunctionDeclaration) { + addSyntheticLeadingComment(node, SyntaxKind.MultiLineCommentTrivia, `@before${project}`, /*hasTrailingNewLine*/ true); + return node; + } + }; + + const after: TransformerFactory = context => { + return file => visitEachChild(file, visit, context); + function visit(node: Node): VisitResult { + switch (node.kind) { + case SyntaxKind.VariableStatement: + return visitVariableStatement(node); + default: + return visitEachChild(node, visit, context); + } + } + function visitVariableStatement(node: VariableStatement) { + addSyntheticLeadingComment(node, SyntaxKind.SingleLineCommentTrivia, `@after${project}`); + return node; + } + }; + return { before: [before], after: [after] }; + } + }); + after(() => { + sys = undefined!; + }); + verifyTscBaseline(() => sys); + }); +} \ No newline at end of file diff --git a/src/testRunner/unittests/tsbuild/watchMode.ts b/src/testRunner/unittests/tsbuild/watchMode.ts index 56eef651a8654..65880a0c69c39 100644 --- a/src/testRunner/unittests/tsbuild/watchMode.ts +++ b/src/testRunner/unittests/tsbuild/watchMode.ts @@ -10,18 +10,6 @@ namespace ts.tscWatch { ); } - export function createSolutionBuilder(system: WatchedSystem, rootNames: readonly string[], defaultOptions?: BuildOptions) { - const host = createSolutionBuilderHost(system); - return ts.createSolutionBuilder(host, rootNames, defaultOptions || {}); - } - - export function ensureErrorFreeBuild(host: WatchedSystem, rootNames: readonly string[]) { - // ts build should succeed - const solutionBuilder = createSolutionBuilder(host, rootNames, {}); - solutionBuilder.build(); - assert.equal(host.getOutput().length, 0, JSON.stringify(host.getOutput(), /*replacer*/ undefined, " ")); - } - type OutputFileStamp = [string, Date | undefined, boolean]; function transformOutputToOutputFileStamp(f: string, host: TsBuildWatchSystem): OutputFileStamp { return [f, host.getModifiedTime(f), host.writtenFiles.has(host.toFullPath(f))] as OutputFileStamp; @@ -39,10 +27,6 @@ namespace ts.tscWatch { type ReadonlyFile = Readonly; /** [tsconfig, index] | [tsconfig, index, anotherModule, someDecl] */ type SubProjectFiles = [ReadonlyFile, ReadonlyFile] | [ReadonlyFile, ReadonlyFile, ReadonlyFile, ReadonlyFile]; - function getProjectPath(project: string) { - return `${projectsLocation}/${project}`; - } - function projectPath(subProject: SubProject) { return getFilePathInProject(project, subProject); } @@ -51,10 +35,6 @@ namespace ts.tscWatch { return `${projectPath(subProject)}/${baseFileName.toLowerCase()}`; } - function projectFileName(subProject: SubProject, baseFileName: string) { - return `${projectPath(subProject)}/${baseFileName}`; - } - function projectFile(subProject: SubProject, baseFileName: string): File { return getFileFromProject(project, `${subProject}/${baseFileName}`); } @@ -551,580 +531,6 @@ let x: string = 10;`), }); }); - describe("tsc-watch and tsserver works with project references", () => { - describe("invoking when references are already built", () => { - function verifyWatchesOfProject(host: TsBuildWatchSystem, expectedWatchedFiles: readonly string[], expectedWatchedDirectoriesRecursive: readonly string[], expectedWatchedDirectories?: readonly string[]) { - checkWatchedFilesDetailed(host, expectedWatchedFiles, 1); - checkWatchedDirectoriesDetailed(host, expectedWatchedDirectories || emptyArray, 1, /*recursive*/ false); - checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesRecursive, 1, /*recursive*/ true); - } - - function createSolutionOfProject(allFiles: readonly File[], - currentDirectory: string, - solutionBuilderconfig: string, - getOutputFileStamps: (host: TsBuildWatchSystem) => readonly OutputFileStamp[]) { - // Build the composite project - const host = createTsBuildWatchSystem(allFiles, { currentDirectory }); - const solutionBuilder = createSolutionBuilder(host, [solutionBuilderconfig], {}); - solutionBuilder.build(); - const outputFileStamps = getOutputFileStamps(host); - for (const stamp of outputFileStamps) { - assert.isDefined(stamp[1], `${stamp[0]} expected to be present`); - } - return { host, solutionBuilder }; - } - - function createSolutionAndWatchModeOfProject( - allFiles: readonly File[], - currentDirectory: string, - solutionBuilderconfig: string, - watchConfig: string, - getOutputFileStamps: (host: TsBuildWatchSystem) => readonly OutputFileStamp[]) { - // Build the composite project - const { host, solutionBuilder } = createSolutionOfProject(allFiles, currentDirectory, solutionBuilderconfig, getOutputFileStamps); - - // Build in watch mode - const watch = createWatchOfConfigFile(watchConfig, host); - checkOutputErrorsInitial(host, emptyArray); - - return { host, solutionBuilder, watch }; - } - - function createSolutionAndServiceOfProject(allFiles: readonly File[], - currentDirectory: string, - solutionBuilderconfig: string, - openFileName: string, - getOutputFileStamps: (host: TsBuildWatchSystem) => readonly OutputFileStamp[]) { - // Build the composite project - const { host, solutionBuilder } = createSolutionOfProject(allFiles, currentDirectory, solutionBuilderconfig, getOutputFileStamps); - - // service - const service = projectSystem.createProjectService(host); - service.openClientFile(openFileName); - - return { host, solutionBuilder, service }; - } - - function checkProjectActualFiles(service: projectSystem.TestProjectService, configFile: string, expectedFiles: readonly string[]) { - projectSystem.checkNumberOfProjects(service, { configuredProjects: 1 }); - projectSystem.checkProjectActualFiles(service.configuredProjects.get(configFile.toLowerCase())!, expectedFiles); - } - - function verifyDependencies(watch: Watch, filePath: string, expected: readonly string[]) { - checkArray(`${filePath} dependencies`, watch.getCurrentProgram().getAllDependencies(watch.getCurrentProgram().getSourceFile(filePath)!), expected); - } - - describe("on sample project", () => { - 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 expectedWatchedDirectoriesRecursive = projectSystem.getTypeRootsFromLocation(projectPath(SubProject.tests)); - const expectedProjectFiles = () => [libFile, ...tests, ...logic.slice(1), ...core.slice(1, core.length - 1)].map(f => f.path); - const expectedProgramFiles = () => [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, logicIndexDts]; - - function createSolutionAndWatchMode() { - return createSolutionAndWatchModeOfProject(allFiles, projectsLocation, `${project}/${SubProject.tests}`, tests[0].path, getOutputFileStamps); - } - - function createSolutionAndService() { - return createSolutionAndServiceOfProject(allFiles, projectsLocation, `${project}/${SubProject.tests}`, tests[1].path, getOutputFileStamps); - } - - function verifyWatches(host: TsBuildWatchSystem, withTsserver?: boolean) { - verifyWatchesOfProject( - host, - withTsserver ? - [...core.slice(0, core.length - 1), ...logic, tests[0], libFile].map(f => f.path.toLowerCase()) : - [core[0], logic[0], ...tests, libFile].map(f => f.path).concat([coreIndexDts, coreAnotherModuleDts, logicIndexDts].map(f => f.toLowerCase())), - expectedWatchedDirectoriesRecursive - ); - } - - function verifyScenario( - edit: (host: TsBuildWatchSystem, solutionBuilder: SolutionBuilder) => void, - expectedProgramFilesAfterEdit: () => readonly string[], - expectedProjectFilesAfterEdit: () => readonly string[] - ) { - it("with tsc-watch", () => { - const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); - - edit(host, solutionBuilder); - - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - checkProgramActualFiles(watch.getCurrentProgram().getProgram(), expectedProgramFilesAfterEdit()); - - }); - - it("with tsserver", () => { - const { host, solutionBuilder, service } = createSolutionAndService(); - - edit(host, solutionBuilder); - - host.checkTimeoutQueueLengthAndRun(2); - checkProjectActualFiles(service, tests[0].path, expectedProjectFilesAfterEdit()); - }); - } - - describe("verifies dependencies and watches", () => { - it("with tsc-watch", () => { - const { host, watch } = createSolutionAndWatchMode(); - verifyWatches(host); - verifyDependencies(watch, coreIndexDts, [coreIndexDts]); - verifyDependencies(watch, coreAnotherModuleDts, [coreAnotherModuleDts]); - verifyDependencies(watch, logicIndexDts, [logicIndexDts, coreAnotherModuleDts]); - verifyDependencies(watch, tests[1].path, expectedProgramFiles().filter(f => f !== libFile.path)); - }); - - it("with tsserver", () => { - const { host } = createSolutionAndService(); - verifyWatches(host, /*withTsserver*/ true); - }); - }); - - describe("local edit in ts file, result in watch compilation because logic.d.ts is written", () => { - verifyScenario((host, solutionBuilder) => { - host.writeFile(logic[1].path, `${logic[1].content} -function foo() { -}`); - solutionBuilder.invalidateProject(logic[0].path.toLowerCase() as ResolvedConfigFilePath); - solutionBuilder.buildNextInvalidatedProject(); - - // not ideal, but currently because of d.ts but no new file is written - // There will be timeout queued even though file contents are same - }, expectedProgramFiles, expectedProjectFiles); - }); - - describe("non local edit in ts file, rebuilds in watch compilation", () => { - verifyScenario((host, solutionBuilder) => { - host.writeFile(logic[1].path, `${logic[1].content} -export function gfoo() { -}`); - solutionBuilder.invalidateProject(logic[0].path.toLowerCase() as ResolvedConfigFilePath); - solutionBuilder.buildNextInvalidatedProject(); - }, expectedProgramFiles, expectedProjectFiles); - }); - - describe("change in project reference config file builds correctly", () => { - verifyScenario((host, solutionBuilder) => { - host.writeFile(logic[0].path, JSON.stringify({ - compilerOptions: { composite: true, declaration: true, declarationDir: "decls" }, - references: [{ path: "../core" }] - })); - solutionBuilder.invalidateProject(logic[0].path.toLowerCase() as ResolvedConfigFilePath, ConfigFileProgramReloadLevel.Full); - solutionBuilder.buildNextInvalidatedProject(); - }, () => [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, projectFilePath(SubProject.logic, "decls/index.d.ts")], expectedProjectFiles); - }); - }); - - describe("on transitive references", () => { - const project = "transitiveReferences"; - const aTsFile = getFileFromProject(project, "a.ts"); - const bTsFile = getFileFromProject(project, "b.ts"); - const cTsFile = getFileFromProject(project, "c.ts"); - const aTsconfigFile = getFileFromProject(project, "tsconfig.a.json"); - const bTsconfigFile = getFileFromProject(project, "tsconfig.b.json"); - const cTsconfigFile = getFileFromProject(project, "tsconfig.c.json"); - const refs = getFileFromProject(project, "refs/a.d.ts"); - - function getRootFile(multiFolder: boolean, fileFromDisk: File, multiFolderPath: string): File { - return multiFolder ? { - path: getFilePathInProject(project, multiFolderPath), - content: fileFromDisk.content - // Replace the relative imports - .replace("./", "../") - } : fileFromDisk; - } - - function dtsFile(extensionLessFile: string) { - return getFilePathInProject(project, `${extensionLessFile}.d.ts`); - } - - function jsFile(extensionLessFile: string) { - return getFilePathInProject(project, `${extensionLessFile}.js`); - } - - function verifyWatchState( - host: TsBuildWatchSystem, - watch: Watch, - expectedProgramFiles: readonly string[], - expectedWatchedFiles: readonly string[], - expectedWatchedDirectoriesRecursive: readonly string[], - dependencies: readonly [string, readonly string[]][], - expectedWatchedDirectories?: readonly string[]) { - checkProgramActualFiles(watch.getCurrentProgram().getProgram(), expectedProgramFiles); - verifyWatchesOfProject(host, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, expectedWatchedDirectories); - for (const [file, deps] of dependencies) { - verifyDependencies(watch, file, deps); - } - } - - function getTsConfigFile(multiFolder: boolean, fileFromDisk: File, folder: string): File { - if (!multiFolder) return fileFromDisk; - - return { - path: getFilePathInProject(project, `${folder}/tsconfig.json`), - content: fileFromDisk.content - // Replace files array - .replace(`${folder}.ts`, "index.ts") - // Replace path mappings - .replace("./*", "../*") - .replace("./refs", "../refs") - // Replace references - .replace("tsconfig.a.json", "../a") - .replace("tsconfig.b.json", "../b") - }; - } - - // function writeFile(file: File) { - // Harness.IO.writeFile(file.path.replace(projectsLocation, "c:/temp"), file.content); - // } - - function verifyTransitiveReferences(multiFolder: boolean) { - const aTs = getRootFile(multiFolder, aTsFile, "a/index.ts"); - const bTs = getRootFile(multiFolder, bTsFile, "b/index.ts"); - const cTs = getRootFile(multiFolder, cTsFile, "c/index.ts"); - - const configToBuild = multiFolder ? "c/tsconfig.json" : "tsconfig.c.json"; - const aTsconfig = getTsConfigFile(multiFolder, aTsconfigFile, "a"); - const bTsconfig = getTsConfigFile(multiFolder, bTsconfigFile, "b"); - const cTsconfig = getTsConfigFile(multiFolder, cTsconfigFile, "c"); - - // if (multiFolder) { - // writeFile(aTs); - // writeFile(bTs); - // writeFile(cTs); - // writeFile(aTsconfig); - // writeFile(bTsconfig); - // writeFile(cTsconfig); - // } - - const allFiles = [libFile, aTs, bTs, cTs, aTsconfig, bTsconfig, cTsconfig, refs]; - const aDts = dtsFile(multiFolder ? "a/index" : "a"), bDts = dtsFile(multiFolder ? "b/index" : "b"); - const expectedFiles = [jsFile(multiFolder ? "a/index" : "a"), aDts, jsFile(multiFolder ? "b/index" : "b"), bDts, jsFile(multiFolder ? "c/index" : "c")]; - const expectedProgramFiles = [cTs.path, libFile.path, aDts, refs.path, bDts]; - const expectedProjectFiles = [cTs.path, libFile.path, aTs.path, refs.path, bTs.path]; - const expectedWatchedFiles = expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase()); - const expectedProjectWatchedFiles = expectedProjectFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase()); - const expectedWatchedDirectories = multiFolder ? [ - getProjectPath(project).toLowerCase() // watches for directories created for resolution of b - ] : emptyArray; - const nrefsPath = multiFolder ? ["../nrefs/*"] : ["./nrefs/*"]; - const expectedWatchedDirectoriesRecursive = [ - ...(multiFolder ? [ - getFilePathInProject(project, "a"), // Failed to package json - getFilePathInProject(project, "b"), // Failed to package json - ] : []), - getFilePathInProject(project, "refs"), // Failed lookup since refs/a.ts does not exist - ...projectSystem.getTypeRootsFromLocation(multiFolder ? getFilePathInProject(project, "c") : getProjectPath(project)) - ].map(s => s.toLowerCase()); - - const defaultDependencies: readonly [string, readonly string[]][] = [ - [aDts, [aDts]], - [bDts, [bDts, aDts]], - [refs.path, [refs.path]], - [cTs.path, [cTs.path, refs.path, bDts, aDts]] - ]; - - function createSolutionAndWatchMode() { - return createSolutionAndWatchModeOfProject(allFiles, getProjectPath(project), configToBuild, configToBuild, getOutputFileStamps); - } - - function createSolutionAndService() { - return createSolutionAndServiceOfProject(allFiles, getProjectPath(project), configToBuild, cTs.path, getOutputFileStamps); - } - - function getOutputFileStamps(host: TsBuildWatchSystem) { - return expectedFiles.map(file => transformOutputToOutputFileStamp(file, host)); - } - - function verifyProgram(host: TsBuildWatchSystem, watch: Watch) { - verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, defaultDependencies, expectedWatchedDirectories); - } - - function verifyProject(host: TsBuildWatchSystem, service: projectSystem.TestProjectService, orphanInfos?: readonly string[]) { - verifyServerState({ host, service, expectedProjectFiles, expectedProjectWatchedFiles, expectedWatchedDirectoriesRecursive, orphanInfos }); - } - - interface VerifyServerState { - host: TsBuildWatchSystem; - service: projectSystem.TestProjectService; - expectedProjectFiles: readonly string[]; - expectedProjectWatchedFiles: readonly string[]; - expectedWatchedDirectoriesRecursive: readonly string[]; - orphanInfos?: readonly string[]; - } - function verifyServerState({ host, service, expectedProjectFiles, expectedProjectWatchedFiles, expectedWatchedDirectoriesRecursive, orphanInfos }: VerifyServerState) { - checkProjectActualFiles(service, cTsconfig.path, expectedProjectFiles.concat(cTsconfig.path)); - const watchedFiles = expectedProjectWatchedFiles.filter(f => f !== cTs.path.toLowerCase()); - const actualOrphan = arrayFrom(mapDefinedIterator( - service.filenameToScriptInfo.values(), - v => v.containingProjects.length === 0 ? v.fileName : undefined - )); - assert.equal(actualOrphan.length, orphanInfos ? orphanInfos.length : 0, `Orphans found: ${JSON.stringify(actualOrphan, /*replacer*/ undefined, " ")}`); - if (orphanInfos && orphanInfos.length) { - for (const orphan of orphanInfos) { - const info = service.getScriptInfoForPath(orphan as Path); - assert.isDefined(info, `${orphan} expected to be present. Actual: ${JSON.stringify(actualOrphan, /*replacer*/ undefined, " ")}`); - assert.equal(info!.containingProjects.length, 0); - watchedFiles.push(orphan); - } - } - verifyWatchesOfProject(host, watchedFiles, expectedWatchedDirectoriesRecursive, expectedWatchedDirectories); - } - - interface VerifyScenario { - edit: (host: TsBuildWatchSystem, solutionBuilder: SolutionBuilder) => void; - schedulesFailedWatchUpdate?: boolean; - expectedEditErrors: readonly string[]; - expectedProgramFiles: readonly string[]; - expectedProjectFiles: readonly string[]; - expectedWatchedFiles: readonly string[]; - expectedProjectWatchedFiles: readonly string[]; - expectedWatchedDirectoriesRecursive: readonly string[]; - dependencies: readonly [string, readonly string[]][]; - revert?: (host: TsBuildWatchSystem) => void; - orphanInfosAfterEdit?: readonly string[]; - orphanInfosAfterRevert?: readonly string[]; - } - function verifyScenario({ edit, schedulesFailedWatchUpdate, expectedEditErrors, expectedProgramFiles, expectedProjectFiles, expectedWatchedFiles, expectedProjectWatchedFiles, expectedWatchedDirectoriesRecursive, dependencies, revert, orphanInfosAfterEdit, orphanInfosAfterRevert }: VerifyScenario) { - it("with tsc-watch", () => { - const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); - - edit(host, solutionBuilder); - - host.checkTimeoutQueueLengthAndRun(schedulesFailedWatchUpdate ? 2 : 1); - checkOutputErrorsIncremental(host, expectedEditErrors); - verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, dependencies, expectedWatchedDirectories); - - if (revert) { - revert(host); - - host.checkTimeoutQueueLengthAndRun(schedulesFailedWatchUpdate ? 2 : 1); - checkOutputErrorsIncremental(host, emptyArray); - verifyProgram(host, watch); - } - }); - - if (!multiFolder) return; // With side by side file open is in inferred project without any settings - - it("with tsserver", () => { - const { host, solutionBuilder, service } = createSolutionAndService(); - - edit(host, solutionBuilder); - - host.checkTimeoutQueueLengthAndRun(schedulesFailedWatchUpdate ? 3 : 2); - verifyServerState({ host, service, expectedProjectFiles, expectedProjectWatchedFiles, expectedWatchedDirectoriesRecursive, orphanInfos: orphanInfosAfterEdit }); - - if (revert) { - revert(host); - - host.checkTimeoutQueueLengthAndRun(schedulesFailedWatchUpdate ? 3 : 2); - verifyProject(host, service, orphanInfosAfterRevert); - } - }); - } - - describe("verifies dependencies and watches", () => { - // Initial build - it("with tsc-watch", () => { - const { host, watch } = createSolutionAndWatchMode(); - verifyProgram(host, watch); - }); - if (!multiFolder) return; - it("with tsserver", () => { - const { host, service } = createSolutionAndService(); - verifyProject(host, service); - }); - }); - - describe("non local edit updates the program and watch correctly", () => { - verifyScenario({ - edit: (host, solutionBuilder) => { - // edit - host.writeFile(bTs.path, `${bTs.content}\nexport function gfoo() {\n}`); - solutionBuilder.invalidateProject((bTsconfig.path.toLowerCase() as ResolvedConfigFilePath)); - solutionBuilder.buildNextInvalidatedProject(); - }, - expectedEditErrors: emptyArray, - expectedProgramFiles, - expectedProjectFiles, - expectedWatchedFiles, - expectedProjectWatchedFiles, - expectedWatchedDirectoriesRecursive, - dependencies: defaultDependencies - }); - }); - - describe("edit on config file", () => { - const nrefReplacer = (f: string) => f.replace("refs", "nrefs"); - const nrefs: File = { - path: getFilePathInProject(project, "nrefs/a.d.ts"), - content: refs.content - }; - verifyScenario({ - edit: host => { - const cTsConfigJson = JSON.parse(cTsconfig.content); - host.ensureFileOrFolder(nrefs); - cTsConfigJson.compilerOptions.paths = { "@ref/*": nrefsPath }; - host.writeFile(cTsconfig.path, JSON.stringify(cTsConfigJson)); - }, - expectedEditErrors: emptyArray, - expectedProgramFiles: expectedProgramFiles.map(nrefReplacer), - expectedProjectFiles: expectedProjectFiles.map(nrefReplacer), - expectedWatchedFiles: expectedWatchedFiles.map(nrefReplacer), - expectedProjectWatchedFiles: expectedProjectWatchedFiles.map(nrefReplacer), - expectedWatchedDirectoriesRecursive: expectedWatchedDirectoriesRecursive.map(nrefReplacer), - dependencies: [ - [aDts, [aDts]], - [bDts, [bDts, aDts]], - [nrefs.path, [nrefs.path]], - [cTs.path, [cTs.path, nrefs.path, bDts, aDts]] - ], - // revert the update - revert: host => host.writeFile(cTsconfig.path, cTsconfig.content), - // AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open - orphanInfosAfterEdit: [refs.path.toLowerCase()], - // AfterRevert:: Extra watched files on server since the script infos arent deleted till next file open - orphanInfosAfterRevert: [nrefs.path.toLowerCase()] - }); - }); - - describe("edit in referenced config file", () => { - const nrefs: File = { - path: getFilePathInProject(project, "nrefs/a.d.ts"), - content: "export declare class A {}" - }; - const expectedProgramFiles = [cTs.path, bDts, nrefs.path, refs.path, libFile.path]; - const expectedProjectFiles = [cTs.path, bTs.path, nrefs.path, refs.path, libFile.path]; - const [, ...expectedWatchedDirectoriesRecursiveWithoutA] = expectedWatchedDirectoriesRecursive; // Not looking in a folder for resolution in multi folder scenario - verifyScenario({ - edit: host => { - const bTsConfigJson = JSON.parse(bTsconfig.content); - host.ensureFileOrFolder(nrefs); - bTsConfigJson.compilerOptions.paths = { "@ref/*": nrefsPath }; - host.writeFile(bTsconfig.path, JSON.stringify(bTsConfigJson)); - }, - expectedEditErrors: emptyArray, - expectedProgramFiles, - expectedProjectFiles, - expectedWatchedFiles: expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase()), - expectedProjectWatchedFiles: expectedProjectFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase()), - expectedWatchedDirectoriesRecursive: (multiFolder ? expectedWatchedDirectoriesRecursiveWithoutA : expectedWatchedDirectoriesRecursive).concat(getFilePathInProject(project, "nrefs").toLowerCase()), - dependencies: [ - [nrefs.path, [nrefs.path]], - [bDts, [bDts, nrefs.path]], - [refs.path, [refs.path]], - [cTs.path, [cTs.path, refs.path, bDts, nrefs.path]], - ], - // revert the update - revert: host => host.writeFile(bTsconfig.path, bTsconfig.content), - // AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open - orphanInfosAfterEdit: [aTs.path.toLowerCase()], - // AfterRevert:: Extra watched files on server since the script infos arent deleted till next file open - orphanInfosAfterRevert: [nrefs.path.toLowerCase()] - }); - }); - - describe("deleting referenced config file", () => { - const expectedProgramFiles = [cTs.path, bTs.path, refs.path, libFile.path]; - const expectedWatchedFiles = expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path).map(s => s.toLowerCase()); - const [, ...expectedWatchedDirectoriesRecursiveWithoutA] = expectedWatchedDirectoriesRecursive; // Not looking in a folder for resolution in multi folder scenario - // Resolutions should change now - // Should map to b.ts instead with options from our own config - verifyScenario({ - edit: host => host.deleteFile(bTsconfig.path), - schedulesFailedWatchUpdate: multiFolder, - expectedEditErrors: [ - `${multiFolder ? "c/tsconfig.json" : "tsconfig.c.json"}(9,21): error TS6053: File '/user/username/projects/transitiveReferences/${multiFolder ? "b" : "tsconfig.b.json"}' not found.\n` - ], - expectedProgramFiles, - expectedProjectFiles: expectedProgramFiles, - expectedWatchedFiles, - expectedProjectWatchedFiles: expectedWatchedFiles, - expectedWatchedDirectoriesRecursive: multiFolder ? expectedWatchedDirectoriesRecursiveWithoutA : expectedWatchedDirectoriesRecursive, - dependencies: [ - [bTs.path, [bTs.path, refs.path]], - [refs.path, [refs.path]], - [cTs.path, [cTs.path, refs.path, bTs.path]], - ], - // revert the update - revert: host => host.writeFile(bTsconfig.path, bTsconfig.content), - // AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open - orphanInfosAfterEdit: [aTs.path.toLowerCase(), aTsconfig.path.toLowerCase()], - }); - }); - - describe("deleting transitively referenced config file", () => { - verifyScenario({ - edit: host => host.deleteFile(aTsconfig.path), - schedulesFailedWatchUpdate: multiFolder, - expectedEditErrors: [ - `${multiFolder ? "b/tsconfig.json" : "tsconfig.b.json"}(10,21): error TS6053: File '/user/username/projects/transitiveReferences/${multiFolder ? "a" : "tsconfig.a.json"}' not found.\n` - ], - expectedProgramFiles: expectedProgramFiles.map(s => s.replace(aDts, aTs.path)), - expectedProjectFiles, - expectedWatchedFiles: expectedWatchedFiles.map(s => s.replace(aDts.toLowerCase(), aTs.path.toLocaleLowerCase())), - expectedProjectWatchedFiles, - expectedWatchedDirectoriesRecursive, - dependencies: [ - [aTs.path, [aTs.path]], - [bDts, [bDts, aTs.path]], - [refs.path, [refs.path]], - [cTs.path, [cTs.path, refs.path, bDts, aTs.path]], - ], - // revert the update - revert: host => host.writeFile(aTsconfig.path, aTsconfig.content), - }); - }); - } - - describe("when config files are side by side", () => { - verifyTransitiveReferences(/*multiFolder*/ false); - - it("when referenced project uses different module resolution", () => { - const bTs: File = { - path: bTsFile.path, - content: `import {A} from "a";export const b = new A();` - }; - const bTsconfig: File = { - path: bTsconfigFile.path, - content: JSON.stringify({ - compilerOptions: { composite: true, moduleResolution: "classic" }, - files: ["b.ts"], - references: [{ path: "tsconfig.a.json" }] - }) - }; - const allFiles = [libFile, aTsFile, bTs, cTsFile, aTsconfigFile, bTsconfig, cTsconfigFile, refs]; - const aDts = dtsFile("a"), bDts = dtsFile("b"); - const expectedFiles = [jsFile("a"), aDts, jsFile("b"), bDts, jsFile("c")]; - const expectedProgramFiles = [cTsFile.path, libFile.path, aDts, refs.path, bDts]; - const expectedWatchedFiles = expectedProgramFiles.concat(cTsconfigFile.path, bTsconfigFile.path, aTsconfigFile.path).map(s => s.toLowerCase()); - const expectedWatchedDirectoriesRecursive = [ - getFilePathInProject(project, "refs"), // Failed lookup since refs/a.ts does not exist - ...projectSystem.getTypeRootsFromLocation(getProjectPath(project)) - ].map(s => s.toLowerCase()); - - const defaultDependencies: readonly [string, readonly string[]][] = [ - [aDts, [aDts]], - [bDts, [bDts, aDts]], - [refs.path, [refs.path]], - [cTsFile.path, [cTsFile.path, refs.path, bDts, aDts]] - ]; - function getOutputFileStamps(host: TsBuildWatchSystem) { - return expectedFiles.map(file => transformOutputToOutputFileStamp(file, host)); - } - const { host, watch } = createSolutionAndWatchModeOfProject(allFiles, getProjectPath(project), "tsconfig.c.json", "tsconfig.c.json", getOutputFileStamps); - verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, defaultDependencies); - }); - }); - describe("when config files are in side by side folders", () => { - verifyTransitiveReferences(/*multiFolder*/ true); - }); - }); - }); - }); - verifyTscWatch({ scenario, subScenario: "incremental updates in verbose mode", @@ -1614,4 +1020,59 @@ const a: string = "hello";`), ] }); }); + + describe("unittests:: tsbuild:: watchMode:: module resolution different in referenced project", () => { + verifyTscWatch({ + scenario: "moduleResolutionCache", + subScenario: "handles the cache correctly when two projects use different module resolution settings", + sys: () => createWatchedSystem( + [ + { path: `${projectRoot}/project1/index.ts`, content: `import { foo } from "file";` }, + { path: `${projectRoot}/project1/node_modules/file/index.d.ts`, content: "export const foo = 10;" }, + { + path: `${projectRoot}/project1/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { composite: true, types: ["foo", "bar"] }, + files: ["index.ts"] + }) + }, + { path: `${projectRoot}/project2/index.ts`, content: `import { foo } from "file";` }, + { path: `${projectRoot}/project2/file.d.ts`, content: "export const foo = 10;" }, + { + path: `${projectRoot}/project2/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { composite: true, types: ["foo"], moduleResolution: "classic" }, + files: ["index.ts"] + }) + }, + { path: `${projectRoot}/node_modules/@types/foo/index.d.ts`, content: "export const foo = 10;" }, + { path: `${projectRoot}/node_modules/@types/bar/index.d.ts`, content: "export const bar = 10;" }, + { + path: `${projectRoot}/tsconfig.json`, + content: JSON.stringify({ + files: [], + references: [ + { path: "./project1" }, + { path: "./project2" } + ] + }) + }, + libFile + ], + { currentDirectory: projectRoot } + ), + commandLineArgs: ["--b", "-w", "-v"], + changes: [ + { + caption: "Append text", + change: sys => sys.appendFile(`${projectRoot}/project1/index.ts`, "const bar = 10;"), + timeouts: sys => { + sys.checkTimeoutQueueLengthAndRun(1); // build project1 + sys.checkTimeoutQueueLengthAndRun(1); // Solution + sys.checkTimeoutQueueLength(0); + } + }, + ] + }); + }); } diff --git a/src/testRunner/unittests/tsc/helpers.ts b/src/testRunner/unittests/tsc/helpers.ts index 53d0748b09d9d..11cae1cfbd8c1 100644 --- a/src/testRunner/unittests/tsc/helpers.ts +++ b/src/testRunner/unittests/tsc/helpers.ts @@ -1,7 +1,8 @@ namespace ts { export type TscCompileSystem = fakes.System & { - writtenFiles: Set; + writtenFiles: Set; baseLine(): { file: string; text: string; }; + disableUseFileVersionAsSignature?: boolean; }; export enum BuildKind { @@ -29,6 +30,8 @@ namespace ts { baselineSourceMap?: boolean; baselineReadFileCalls?: boolean; baselinePrograms?: boolean; + baselineDependencies?: boolean; + disableUseFileVersionAsSignature?: boolean; } export type CommandLineProgram = [Program, EmitAndSemanticDiagnosticsBuilderProgram?]; @@ -41,22 +44,23 @@ namespace ts { return !!(program as Program | EmitAndSemanticDiagnosticsBuilderProgram).getCompilerOptions; } export function commandLineCallbacks( - sys: System & { writtenFiles: ReadonlyCollection; }, - originalReadCall?: System["readFile"] + sys: System & { writtenFiles: ReadonlyCollection; }, + originalReadCall?: System["readFile"], + originalWriteFile?: System["writeFile"], ): CommandLineCallbacks { let programs: CommandLineProgram[] | undefined; return { cb: program => { if (isAnyProgram(program)) { - baselineBuildInfo(program.getCompilerOptions(), sys, originalReadCall); + baselineBuildInfo(program.getCompilerOptions(), sys, originalReadCall, originalWriteFile); (programs || (programs = [])).push(isBuilderProgram(program) ? [program.getProgram(), program] : [program] ); } else { - baselineBuildInfo(program.options, sys, originalReadCall); + baselineBuildInfo(program.options, sys, originalReadCall, originalWriteFile); } }, getPrograms: () => { @@ -73,7 +77,7 @@ namespace ts { const { scenario, subScenario, buildKind, commandLineArgs, modifyFs, - baselineSourceMap, baselineReadFileCalls, baselinePrograms + baselineSourceMap, baselineReadFileCalls, baselinePrograms, baselineDependencies } = input; if (modifyFs) modifyFs(inputFs); inputFs.makeReadonly(); @@ -81,12 +85,14 @@ namespace ts { // Create system const sys = new fakes.System(fs, { executingFilePath: "/lib/tsc" }) as TscCompileSystem; + if (input.disableUseFileVersionAsSignature) sys.disableUseFileVersionAsSignature = true; fakes.patchHostForBuildInfoReadWrite(sys); - const writtenFiles = sys.writtenFiles = new Set(); + const writtenFiles = sys.writtenFiles = new Set(); const originalWriteFile = sys.writeFile; sys.writeFile = (fileName, content, writeByteOrderMark) => { - assert.isFalse(writtenFiles.has(fileName)); - writtenFiles.add(fileName); + const path = toPathWithSystem(sys, fileName); + assert.isFalse(writtenFiles.has(path)); + writtenFiles.add(path); return originalWriteFile.call(sys, fileName, content, writeByteOrderMark); }; const actualReadFileMap: MapLike = {}; @@ -101,7 +107,7 @@ namespace ts { sys.write(`${sys.getExecutingFilePath()} ${commandLineArgs.join(" ")}\n`); sys.exit = exitCode => sys.exitCode = exitCode; - const { cb, getPrograms } = commandLineCallbacks(sys, originalReadFile); + const { cb, getPrograms } = commandLineCallbacks(sys, originalReadFile, originalWriteFile); executeCommandLine( sys, cb, @@ -110,7 +116,7 @@ namespace ts { sys.write(`exitCode:: ExitStatus.${ExitStatus[sys.exitCode as ExitStatus]}\n`); if (baselinePrograms) { const baseline: string[] = []; - tscWatch.baselinePrograms(baseline, getPrograms); + tscWatch.baselinePrograms(baseline, getPrograms, emptyArray, baselineDependencies); sys.write(baseline.join("\n")); } if (baselineReadFileCalls) { diff --git a/src/testRunner/unittests/tsc/incremental.ts b/src/testRunner/unittests/tsc/incremental.ts index bc728cd32aa2d..7e975b89ce6b2 100644 --- a/src/testRunner/unittests/tsc/incremental.ts +++ b/src/testRunner/unittests/tsc/incremental.ts @@ -236,7 +236,66 @@ const a: string = 10;`, "utf-8"), } }); - const jsxLibraryContent = ` + verifyTscSerializedIncrementalEdits({ + scenario: "incremental", + subScenario: `when global file is added, the signatures are updated`, + fs: () => loadProjectFromFiles({ + "/src/project/src/main.ts": Utils.dedent` + /// + /// + function main() { } + `, + "/src/project/src/anotherFileWithSameReferenes.ts": Utils.dedent` + /// + /// + function anotherFileWithSameReferenes() { } + `, + "/src/project/src/filePresent.ts": `function something() { return 10; }`, + "/src/project/tsconfig.json": JSON.stringify({ + compilerOptions: { composite: true, }, + include: ["src/**/*.ts"] + }), + }), + commandLineArgs: ["--p", "src/project"], + incrementalScenarios: [ + noChangeRun, + { + subScenario: "Modify main file", + buildKind: BuildKind.IncrementalDtsChange, + modifyFs: fs => appendText(fs, `/src/project/src/main.ts`, `something();`), + }, + { + subScenario: "Modify main file again", + buildKind: BuildKind.IncrementalDtsChange, + modifyFs: fs => appendText(fs, `/src/project/src/main.ts`, `something();`), + }, + { + subScenario: "Add new file and update main file", + buildKind: BuildKind.IncrementalDtsChange, + modifyFs: fs => { + fs.writeFileSync(`/src/project/src/newFile.ts`, "function foo() { return 20; }"); + prependText(fs, `/src/project/src/main.ts`, `/// +`); + appendText(fs, `/src/project/src/main.ts`, `foo();`); + }, + }, + { + subScenario: "Write file that could not be resolved", + buildKind: BuildKind.IncrementalDtsChange, + modifyFs: fs => fs.writeFileSync(`/src/project/src/fileNotFound.ts`, "function something2() { return 20; }"), + }, + { + subScenario: "Modify main file", + buildKind: BuildKind.IncrementalDtsChange, + modifyFs: fs => appendText(fs, `/src/project/src/main.ts`, `something();`), + }, + ], + baselinePrograms: true, + }); + + describe("when synthesized imports are added to files", () => { + function getJsxLibraryContent() { + return ` export {}; declare global { namespace JSX { @@ -248,29 +307,98 @@ declare global { } } }`; + } - verifyTsc({ - scenario: "react-jsx-emit-mode", - subScenario: "with no backing types found doesn't crash", - fs: () => loadProjectFromFiles({ - "/src/project/node_modules/react/jsx-runtime.js": "export {}", // js needs to be present so there's a resolution result - "/src/project/node_modules/@types/react/index.d.ts": jsxLibraryContent, // doesn't contain a jsx-runtime definition - "/src/project/src/index.tsx": `export const App = () =>
;`, - "/src/project/tsconfig.json": JSON.stringify({ compilerOptions: { module: "commonjs", jsx: "react-jsx", incremental: true, jsxImportSource: "react" } }) - }), - commandLineArgs: ["--p", "src/project"] + verifyTsc({ + scenario: "react-jsx-emit-mode", + subScenario: "with no backing types found doesn't crash", + fs: () => loadProjectFromFiles({ + "/src/project/node_modules/react/jsx-runtime.js": "export {}", // js needs to be present so there's a resolution result + "/src/project/node_modules/@types/react/index.d.ts": getJsxLibraryContent(), // doesn't contain a jsx-runtime definition + "/src/project/src/index.tsx": `export const App = () =>
;`, + "/src/project/tsconfig.json": JSON.stringify({ compilerOptions: { module: "commonjs", jsx: "react-jsx", incremental: true, jsxImportSource: "react" } }) + }), + commandLineArgs: ["--p", "src/project"] + }); + + verifyTsc({ + scenario: "react-jsx-emit-mode", + subScenario: "with no backing types found doesn't crash under --strict", + fs: () => loadProjectFromFiles({ + "/src/project/node_modules/react/jsx-runtime.js": "export {}", // js needs to be present so there's a resolution result + "/src/project/node_modules/@types/react/index.d.ts": getJsxLibraryContent(), // doesn't contain a jsx-runtime definition + "/src/project/src/index.tsx": `export const App = () =>
;`, + "/src/project/tsconfig.json": JSON.stringify({ compilerOptions: { module: "commonjs", jsx: "react-jsx", incremental: true, jsxImportSource: "react" } }) + }), + commandLineArgs: ["--p", "src/project", "--strict"] + }); }); - verifyTsc({ - scenario: "react-jsx-emit-mode", - subScenario: "with no backing types found doesn't crash under --strict", + verifyTscSerializedIncrementalEdits({ + scenario: "incremental", + subScenario: "when new file is added to the referenced project", + commandLineArgs: ["-i", "-p", `src/projects/project2`], fs: () => loadProjectFromFiles({ - "/src/project/node_modules/react/jsx-runtime.js": "export {}", // js needs to be present so there's a resolution result - "/src/project/node_modules/@types/react/index.d.ts": jsxLibraryContent, // doesn't contain a jsx-runtime definition - "/src/project/src/index.tsx": `export const App = () =>
;`, - "/src/project/tsconfig.json": JSON.stringify({ compilerOptions: { module: "commonjs", jsx: "react-jsx", incremental: true, jsxImportSource: "react" } }) + "/src/projects/project1/tsconfig.json": JSON.stringify({ + compilerOptions: { + module: "none", + composite: true + }, + exclude: ["temp"] + }), + "/src/projects/project1/class1.ts": `class class1 {}`, + "/src/projects/project1/class1.d.ts": `declare class class1 {}`, + "/src/projects/project2/tsconfig.json": JSON.stringify({ + compilerOptions: { + module: "none", + composite: true + }, + references: [ + { path: "../project1" } + ] + }), + "/src/projects/project2/class2.ts": `class class2 {}`, }), - commandLineArgs: ["--p", "src/project", "--strict"] + incrementalScenarios: [ + { + subScenario: "Add class3 to project1 and build it", + buildKind: BuildKind.IncrementalDtsChange, + modifyFs: fs => fs.writeFileSync("/src/projects/project1/class3.ts", `class class3 {}`, "utf-8"), + cleanBuildDiscrepancies: () => new Map([ + // Ts buildinfo will not be updated in incremental build so it will have semantic diagnostics cached from previous build + // But in clean build because of global diagnostics, semantic diagnostics are not queried so not cached in tsbuildinfo + ["/src/projects/project2/tsconfig.tsbuildinfo", CleanBuildDescrepancy.CleanFileTextDifferent] + ]), + }, + { + subScenario: "Add output of class3", + buildKind: BuildKind.IncrementalDtsChange, + modifyFs: fs => fs.writeFileSync("/src/projects/project1/class3.d.ts", `declare class class3 {}`, "utf-8"), + }, + { + subScenario: "Add excluded file to project1", + buildKind: BuildKind.IncrementalDtsUnchanged, + modifyFs: fs => { + fs.mkdirSync("/src/projects/project1/temp"); + fs.writeFileSync("/src/projects/project1/temp/file.d.ts", `declare class file {}`, "utf-8"); + }, + }, + { + subScenario: "Delete output for class3", + buildKind: BuildKind.IncrementalDtsUnchanged, + modifyFs: fs => fs.unlinkSync("/src/projects/project1/class3.d.ts"), + cleanBuildDiscrepancies: () => new Map([ + // Ts buildinfo willbe updated but will retain lib file errors from previous build and not others because they are emitted because of change which results in clearing their semantic diagnostics cache + // But in clean build because of global diagnostics, semantic diagnostics are not queried so not cached in tsbuildinfo + ["/src/projects/project2/tsconfig.tsbuildinfo", CleanBuildDescrepancy.CleanFileTextDifferent] + ]), + }, + { + subScenario: "Create output for class3", + buildKind: BuildKind.IncrementalDtsUnchanged, + modifyFs: fs => fs.writeFileSync("/src/projects/project1/class3.d.ts", `declare class class3 {}`, "utf-8"), + }, + ] }); }); } diff --git a/src/testRunner/unittests/tscWatch/emit.ts b/src/testRunner/unittests/tscWatch/emit.ts index be2d95738829b..217d4c059a5ba 100644 --- a/src/testRunner/unittests/tscWatch/emit.ts +++ b/src/testRunner/unittests/tscWatch/emit.ts @@ -26,6 +26,11 @@ namespace ts.tscWatch { caption: "Make change in the file", change: sys => sys.writeFile("/a/a.ts", "let x = 11"), timeouts: runQueuedTimeoutCallbacks + }, + { + caption: "Make change in the file again", + change: sys => sys.writeFile("/a/a.ts", "let xy = 11"), + timeouts: runQueuedTimeoutCallbacks } ] }); @@ -410,6 +415,11 @@ export var x = Foo();` caption: "Append content to f1", change: sys => sys.appendFile("/a/b/f1.ts", "export function foo2() { return 2; }"), timeouts: checkSingleTimeoutQueueLengthAndRun, + }, + { + caption: "Again Append content to f1", + change: sys => sys.appendFile("/a/b/f1.ts", "export function fooN() { return 2; }"), + timeouts: checkSingleTimeoutQueueLengthAndRun, } ], }); diff --git a/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts b/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts index d4da16b41fc2f..2a3928b6f8722 100644 --- a/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts +++ b/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts @@ -27,6 +27,17 @@ namespace ts.tscWatch { changes, baselineIncremental }); + verifyTscWatch({ + scenario: "emitAndErrorUpdates", + subScenario: `incremental/${subScenario}`, + commandLineArgs: ["--w", "--i"], + sys: () => createWatchedSystem( + [...files(), configFile(), lib?.() || libFile], + { currentDirectory: currentDirectory || projectRoot } + ), + changes, + baselineIncremental + }); } function changeCompilerOptions(input: VerifyEmitAndErrorUpdates, additionalOptions: CompilerOptions): File { @@ -97,6 +108,16 @@ console.log(b.c.d);` subScenario: `deepImportChanges/${subScenario}`, files: () => [aFile, bFile, cFile], changes: [ + { + caption: "Rename property d to d2 of class C to initialize signatures", + change: sys => sys.writeFile(cFile.path, cFile.content.replace("d", "d2")), + timeouts: runQueuedTimeoutCallbacks, + }, + { + caption: "Rename property d2 to d of class C to revert back to original text", + change: sys => sys.writeFile(cFile.path, cFile.content.replace("d2", "d")), + timeouts: runQueuedTimeoutCallbacks, + }, { caption: "Rename property d to d2 of class C", change: sys => sys.writeFile(cFile.path, cFile.content.replace("d", "d2")), @@ -197,11 +218,21 @@ getPoint().c.x;` subScenario: "file not exporting a deep multilevel import that changes", files: () => [aFile, bFile, cFile, dFile, eFile], changes: [ + { + caption: "Rename property x2 to x of interface Coords to initialize signatures", + change: sys => sys.writeFile(aFile.path, aFile.content.replace("x2", "x")), + timeouts: runQueuedTimeoutCallbacks, + }, + { + caption: "Rename property x to x2 of interface Coords to revert back to original text", + change: sys => sys.writeFile(aFile.path, aFile.content.replace("x: number", "x2: number")), + timeouts: runQueuedTimeoutCallbacks, + }, { caption: "Rename property x2 to x of interface Coords", change: sys => sys.writeFile(aFile.path, aFile.content.replace("x2", "x")), timeouts: runQueuedTimeoutCallbacks, - } + }, ] }); }); @@ -260,6 +291,16 @@ export class Data { files: () => [lib1ToolsInterface, lib1ToolsPublic, app, lib2Public, lib1Public, ...files], configFile: () => config, changes: [ + { + caption: "Rename property title to title2 of interface ITest to initialize signatures", + change: sys => sys.writeFile(lib1ToolsInterface.path, lib1ToolsInterface.content.replace("title", "title2")), + timeouts: runQueuedTimeoutCallbacks, + }, + { + caption: "Rename property title2 to title of interface ITest to revert back to original text", + change: sys => sys.writeFile(lib1ToolsInterface.path, lib1ToolsInterface.content.replace("title2", "title")), + timeouts: runQueuedTimeoutCallbacks, + }, { caption: "Rename property title to title2 of interface ITest", change: sys => sys.writeFile(lib1ToolsInterface.path, lib1ToolsInterface.content.replace("title", "title2")), diff --git a/src/testRunner/unittests/tscWatch/helpers.ts b/src/testRunner/unittests/tscWatch/helpers.ts index 982475010a2fe..fe191d1fe6f74 100644 --- a/src/testRunner/unittests/tscWatch/helpers.ts +++ b/src/testRunner/unittests/tscWatch/helpers.ts @@ -299,6 +299,7 @@ namespace ts.tscWatch { } export interface TscWatchCheckOptions { baselineSourceMap?: boolean; + baselineDependencies?: boolean; } export interface TscWatchCompileBase extends TscWatchCheckOptions { scenario: string; @@ -323,7 +324,7 @@ namespace ts.tscWatch { const { scenario, subScenario, commandLineArgs, changes, - baselineSourceMap + baselineSourceMap, baselineDependencies } = input; if (!isWatch(commandLineArgs)) sys.exit = exitCode => sys.exitCode = exitCode; @@ -342,6 +343,7 @@ namespace ts.tscWatch { oldSnap, getPrograms, baselineSourceMap, + baselineDependencies, changes, watchOrSolution }); @@ -381,16 +383,18 @@ namespace ts.tscWatch { export function runWatchBaseline({ scenario, subScenario, commandLineArgs, getPrograms, sys, baseline, oldSnap, - baselineSourceMap, + baselineSourceMap, baselineDependencies, changes, watchOrSolution }: RunWatchBaseline) { baseline.push(`${sys.getExecutingFilePath()} ${commandLineArgs.join(" ")}`); let programs = watchBaseline({ baseline, getPrograms, + oldPrograms: emptyArray, sys, oldSnap, - baselineSourceMap + baselineSourceMap, + baselineDependencies, }); for (const { caption, change, timeouts } of changes) { @@ -399,9 +403,11 @@ namespace ts.tscWatch { programs = watchBaseline({ baseline, getPrograms, + oldPrograms: programs, sys, oldSnap, - baselineSourceMap + baselineSourceMap, + baselineDependencies, }); } Harness.Baseline.runBaseline(`${isBuild(commandLineArgs) ? @@ -418,12 +424,13 @@ namespace ts.tscWatch { } export interface WatchBaseline extends Baseline, TscWatchCheckOptions { + oldPrograms: readonly (CommandLineProgram | undefined)[]; getPrograms: () => readonly CommandLineProgram[]; } - export function watchBaseline({ baseline, getPrograms, sys, oldSnap, baselineSourceMap }: WatchBaseline) { + export function watchBaseline({ baseline, getPrograms, oldPrograms, sys, oldSnap, baselineSourceMap, baselineDependencies }: WatchBaseline) { if (baselineSourceMap) generateSourceMapBaselineFiles(sys); sys.serializeOutput(baseline); - const programs = baselinePrograms(baseline, getPrograms); + const programs = baselinePrograms(baseline, getPrograms, oldPrograms, baselineDependencies); sys.serializeWatches(baseline); baseline.push(`exitCode:: ExitStatus.${ExitStatus[sys.exitCode as ExitStatus]}`, ""); sys.diff(baseline, oldSnap); @@ -434,36 +441,56 @@ namespace ts.tscWatch { return programs; } - export function baselinePrograms(baseline: string[], getPrograms: () => readonly CommandLineProgram[]) { + export function baselinePrograms(baseline: string[], getPrograms: () => readonly CommandLineProgram[], oldPrograms: readonly (CommandLineProgram | undefined)[], baselineDependencies: boolean | undefined) { const programs = getPrograms(); - for (const program of programs) { - baselineProgram(baseline, program); + for (let i = 0; i < programs.length; i++) { + baselineProgram(baseline, programs[i], oldPrograms[i], baselineDependencies); } return programs; } - function baselineProgram(baseline: string[], [program, builderProgram]: CommandLineProgram) { - const options = program.getCompilerOptions(); - baseline.push(`Program root files: ${JSON.stringify(program.getRootFileNames())}`); - baseline.push(`Program options: ${JSON.stringify(options)}`); - baseline.push(`Program structureReused: ${(ts).StructureIsReused[program.structureIsReused]}`); - baseline.push("Program files::"); - for (const file of program.getSourceFiles()) { - baseline.push(file.fileName); + function baselineProgram(baseline: string[], [program, builderProgram]: CommandLineProgram, oldProgram: CommandLineProgram | undefined, baselineDependencies: boolean | undefined) { + if (program !== oldProgram?.[0]) { + const options = program.getCompilerOptions(); + baseline.push(`Program root files: ${JSON.stringify(program.getRootFileNames())}`); + baseline.push(`Program options: ${JSON.stringify(options)}`); + baseline.push(`Program structureReused: ${(ts).StructureIsReused[program.structureIsReused]}`); + baseline.push("Program files::"); + for (const file of program.getSourceFiles()) { + baseline.push(file.fileName); + } + } + else { + baseline.push(`Program: Same as old program`); } baseline.push(""); + if (!builderProgram) return; - const state = builderProgram.getState(); - if (state.semanticDiagnosticsPerFile?.size) { - baseline.push("Semantic diagnostics in builder refreshed for::"); - for (const file of program.getSourceFiles()) { - if (!state.semanticDiagnosticsFromOldState || !state.semanticDiagnosticsFromOldState.has(file.resolvedPath)) { - baseline.push(file.fileName); + if (builderProgram !== oldProgram?.[1]) { + const state = builderProgram.getState(); + if (state.semanticDiagnosticsPerFile?.size) { + baseline.push("Semantic diagnostics in builder refreshed for::"); + for (const file of program.getSourceFiles()) { + if (!state.semanticDiagnosticsFromOldState || !state.semanticDiagnosticsFromOldState.has(file.resolvedPath)) { + baseline.push(file.fileName); + } + } + } + else { + baseline.push("No cached semantic diagnostics in the builder::"); + } + baseline.push(""); + if (!baselineDependencies) return; + baseline.push("Dependencies for::"); + for (const file of builderProgram.getSourceFiles()) { + baseline.push(`${file.fileName}:`); + for (const depenedency of builderProgram.getAllDependencies(file)) { + baseline.push(` ${depenedency}`); } } } else { - baseline.push("No cached semantic diagnostics in the builder::"); + baseline.push(`BuilderProgram: Same as old builder program`); } baseline.push(""); } @@ -492,4 +519,31 @@ namespace ts.tscWatch { const content = Debug.checkDefined(sys.readFile(file)); sys.writeFile(file, content.replace(searchValue, replaceValue)); } + + export function createSolutionBuilder(system: WatchedSystem, rootNames: readonly string[], defaultOptions?: BuildOptions) { + const host = createSolutionBuilderHost(system); + return ts.createSolutionBuilder(host, rootNames, defaultOptions || {}); + } + + export function ensureErrorFreeBuild(host: WatchedSystem, rootNames: readonly string[]) { + // ts build should succeed + const solutionBuilder = createSolutionBuilder(host, rootNames, {}); + solutionBuilder.build(); + assert.equal(host.getOutput().length, 0, JSON.stringify(host.getOutput(), /*replacer*/ undefined, " ")); + } + + export function createSystemWithSolutionBuild(solutionRoots: readonly string[], files: readonly TestFSWithWatch.FileOrFolderOrSymLink[], params?: TestFSWithWatch.TestServerHostCreationParameters) { + const sys = createWatchedSystem(files, params); + const originalReadFile = sys.readFile; + const originalWrite = sys.write; + const originalWriteFile = sys.writeFile; + const solutionBuilder = createSolutionBuilder(TestFSWithWatch.changeToHostTrackingWrittenFiles( + fakes.patchHostForBuildInfoReadWrite(sys) + ), solutionRoots, {}); + solutionBuilder.build(); + sys.readFile = originalReadFile; + sys.write = originalWrite; + sys.writeFile = originalWriteFile; + return sys; + } } diff --git a/src/testRunner/unittests/tscWatch/incremental.ts b/src/testRunner/unittests/tscWatch/incremental.ts index d54b7c7f18728..aaa58d6791493 100644 --- a/src/testRunner/unittests/tscWatch/incremental.ts +++ b/src/testRunner/unittests/tscWatch/incremental.ts @@ -32,6 +32,7 @@ namespace ts.tscWatch { if (incremental) sys.exit = exitCode => sys.exitCode = exitCode; const argsToPass = [incremental ? "-i" : "-w", ...(optionsToExtend || emptyArray)]; baseline.push(`${sys.getExecutingFilePath()} ${argsToPass.join(" ")}`); + let oldPrograms: readonly CommandLineProgram[] = emptyArray; const { cb, getPrograms } = commandLineCallbacks(sys); build(oldSnap); @@ -48,9 +49,10 @@ namespace ts.tscWatch { cb, argsToPass, ); - watchBaseline({ + oldPrograms = watchBaseline({ baseline, getPrograms, + oldPrograms, sys, oldSnap }); @@ -134,7 +136,7 @@ namespace ts.tscWatch { it("verify that state is read correctly", () => { const system = createWatchedSystem([libFile, file1, fileModified, config], { currentDirectory: project }); const reportDiagnostic = createDiagnosticReporter(system); - const parsedConfig = parseConfigFileWithSystem("tsconfig.json", {}, /*watchOptionsToExtend*/ undefined, system, reportDiagnostic)!; + const parsedConfig = parseConfigFileWithSystem("tsconfig.json", {}, /*extendedConfigCache*/ undefined, /*watchOptionsToExtend*/ undefined, system, reportDiagnostic)!; performIncrementalCompilation({ rootNames: parsedConfig.fileNames, options: parsedConfig.options, @@ -144,7 +146,7 @@ namespace ts.tscWatch { system }); - const command = parseConfigFileWithSystem("tsconfig.json", {}, /*watchOptionsToExtend*/ undefined, system, noop)!; + const command = parseConfigFileWithSystem("tsconfig.json", {}, /*extendedConfigCache*/ undefined, /*watchOptionsToExtend*/ undefined, system, noop)!; const builderProgram = createIncrementalProgram({ rootNames: command.fileNames, options: command.options, @@ -164,13 +166,13 @@ namespace ts.tscWatch { }); assert.deepEqual(state.fileInfos.get(file1.path as Path), { version: system.createHash(file1.content), - signature: system.createHash(`${file1.content.replace("export ", "export declare ")}\n`), - affectsGlobalScope: false, + signature: system.createHash(file1.content), + affectsGlobalScope: undefined, }); assert.deepEqual(state.fileInfos.get(file2.path as Path), { version: system.createHash(fileModified.content), - signature: system.createHash("export declare const y: string;\n"), - affectsGlobalScope: false, + signature: system.createHash(fileModified.content), + affectsGlobalScope: undefined, }); assert.deepEqual(state.compilerOptions, { diff --git a/src/testRunner/unittests/tscWatch/programUpdates.ts b/src/testRunner/unittests/tscWatch/programUpdates.ts index 80a4d60cf700a..c7d2e1dec26f7 100644 --- a/src/testRunner/unittests/tscWatch/programUpdates.ts +++ b/src/testRunner/unittests/tscWatch/programUpdates.ts @@ -122,6 +122,11 @@ namespace ts.tscWatch { return createWatchedSystem([libFile, commonFile1, commonFile2, configFile]); }, changes: [ + { + caption: "change file to ensure signatures are updated", + change: sys => sys.appendFile(commonFile2.path, ";let xy = 10;"), + timeouts: checkSingleTimeoutQueueLengthAndRun, + }, { caption: "delete file2", change: sys => sys.deleteFile(commonFile2.path), @@ -171,6 +176,11 @@ namespace ts.tscWatch { return createWatchedSystem([libFile, commonFile1, commonFile2, configFile]); }, changes: [ + { + caption: "change file to ensure signatures are updated", + change: sys => sys.appendFile(commonFile2.path, ";let xy = 10;"), + timeouts: checkSingleTimeoutQueueLengthAndRun, + }, { caption: "Change config", change: sys => sys.writeFile(configFilePath, `{ @@ -1696,5 +1706,114 @@ import { x } from "../b";`), }, ] }); + + verifyTscWatch({ + scenario, + subScenario: "when creating new file in symlinked folder", + commandLineArgs: ["-w", "-p", ".", "--extendedDiagnostics"], + sys: () => { + const module1: File = { + path: `${projectRoot}/client/folder1/module1.ts`, + content: `export class Module1Class { }` + }; + const module2: File = { + path: `${projectRoot}/folder2/module2.ts`, + content: `import * as M from "folder1/module1";` + }; + const symlink: SymLink = { + path: `${projectRoot}/client/linktofolder2`, + symLink: `${projectRoot}/folder2`, + }; + const config: File = { + path: `${projectRoot}/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + baseUrl: "client", + paths: { "*": ["*"] }, + }, + include: ["client/**/*", "folder2"] + }) + }; + return createWatchedSystem([module1, module2, symlink, config, libFile], { currentDirectory: projectRoot }); + }, + changes: [ + { + caption: "Add module3 to folder2", + change: sys => sys.writeFile(`${projectRoot}/client/linktofolder2/module3.ts`, `import * as M from "folder1/module1";`), + timeouts: checkSingleTimeoutQueueLengthAndRun, + }, + ] + }); + + verifyTscWatch({ + scenario, + subScenario: "when new file is added to the referenced project", + commandLineArgs: ["-w", "-p", `${projectRoot}/projects/project2/tsconfig.json`, "--extendedDiagnostics"], + sys: () => { + const config1: File = { + path: `${projectRoot}/projects/project1/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + module: "none", + composite: true + }, + exclude: ["temp"] + }) + }; + const class1: File = { + path: `${projectRoot}/projects/project1/class1.ts`, + content: `class class1 {}` + }; + // Built file + const class1Dt: File = { + path: `${projectRoot}/projects/project1/class1.d.ts`, + content: `declare class class1 {}` + }; + const config2: File = { + path: `${projectRoot}/projects/project2/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + module: "none", + composite: true + }, + references: [ + { path: "../project1" } + ] + }) + }; + const class2: File = { + path: `${projectRoot}/projects/project2/class2.ts`, + content: `class class2 {}` + }; + return createWatchedSystem([config1, class1, config2, class2, libFile, class1Dt]); + }, + changes: [ + { + caption: "Add class3 to project1", + change: sys => sys.writeFile(`${projectRoot}/projects/project1/class3.ts`, `class class3 {}`), + timeouts: checkSingleTimeoutQueueLengthAndRun, + }, + { + caption: "Add output of class3", + change: sys => sys.writeFile(`${projectRoot}/projects/project1/class3.d.ts`, `declare class class3 {}`), + timeouts: checkSingleTimeoutQueueLengthAndRun, + }, + { + caption: "Add excluded file to project1", + change: sys => sys.ensureFileOrFolder({ path: `${projectRoot}/projects/project1/temp/file.d.ts`, content: `declare class file {}` }), + timeouts: sys => sys.checkTimeoutQueueLength(0), + }, + { + caption: "Delete output of class3", + change: sys => sys.deleteFile(`${projectRoot}/projects/project1/class3.d.ts`), + timeouts: checkSingleTimeoutQueueLengthAndRun, + }, + { + caption: "Add output of class3", + change: sys => sys.writeFile(`${projectRoot}/projects/project1/class3.d.ts`, `declare class class3 {}`), + timeouts: checkSingleTimeoutQueueLengthAndRun, + }, + ] + }); }); } diff --git a/src/testRunner/unittests/tscWatch/projectsWithReferences.ts b/src/testRunner/unittests/tscWatch/projectsWithReferences.ts new file mode 100644 index 0000000000000..83b65de1bda2d --- /dev/null +++ b/src/testRunner/unittests/tscWatch/projectsWithReferences.ts @@ -0,0 +1,414 @@ +namespace ts.tscWatch { + describe("unittests:: tsc-watch:: projects with references: invoking when references are already built", () => { + verifyTscWatch({ + scenario: "projectsWithReferences", + subScenario: "on sample project", + sys: () => createSystemWithSolutionBuild( + ["tests"], + [ + libFile, + TestFSWithWatch.getTsBuildProjectFile("sample1", "core/tsconfig.json"), + TestFSWithWatch.getTsBuildProjectFile("sample1", "core/index.ts"), + TestFSWithWatch.getTsBuildProjectFile("sample1", "core/anotherModule.ts"), + TestFSWithWatch.getTsBuildProjectFile("sample1", "core/some_decl.d.ts"), + TestFSWithWatch.getTsBuildProjectFile("sample1", "logic/tsconfig.json"), + TestFSWithWatch.getTsBuildProjectFile("sample1", "logic/index.ts"), + TestFSWithWatch.getTsBuildProjectFile("sample1", "tests/tsconfig.json"), + TestFSWithWatch.getTsBuildProjectFile("sample1", "tests/index.ts"), + ], + { currentDirectory: `${TestFSWithWatch.tsbuildProjectsLocation}/sample1` } + ), + commandLineArgs: ["-w", "-p", "tests"], + changes: [ + { + caption: "local edit in logic ts, and build logic", + change: sys => { + sys.appendFile(TestFSWithWatch.getTsBuildProjectFilePath("sample1", "logic/index.ts"), `function foo() { }`); + const solutionBuilder = createSolutionBuilder(sys, ["logic"]); + solutionBuilder.build(); + }, + // not ideal, but currently because of d.ts but no new file is written + // There will be timeout queued even though file contents are same + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "non local edit in logic ts, and build logic", + change: sys => { + sys.appendFile(TestFSWithWatch.getTsBuildProjectFilePath("sample1", "logic/index.ts"), `export function gfoo() { }`); + const solutionBuilder = createSolutionBuilder(sys, ["logic"]); + solutionBuilder.build(); + }, + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "change in project reference config file builds correctly", + change: sys => { + sys.writeFile(TestFSWithWatch.getTsBuildProjectFilePath("sample1", "logic/tsconfig.json"), JSON.stringify({ + compilerOptions: { composite: true, declaration: true, declarationDir: "decls" }, + references: [{ path: "../core" }] + })); + const solutionBuilder = createSolutionBuilder(sys, ["logic"]); + solutionBuilder.build(); + }, + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + ], + baselineDependencies: true + }); + + function changeCompilerOpitonsPaths(sys: WatchedSystem, config: string, newPaths: object) { + const configJson = JSON.parse(sys.readFile(config)!); + configJson.compilerOptions.paths = newPaths; + sys.writeFile(config, JSON.stringify(configJson)); + } + + verifyTscWatch({ + scenario: "projectsWithReferences", + subScenario: "on transitive references", + sys: () => createSystemWithSolutionBuild( + ["tsconfig.c.json"], + [ + libFile, + TestFSWithWatch.getTsBuildProjectFile("transitiveReferences", "tsconfig.a.json"), + TestFSWithWatch.getTsBuildProjectFile("transitiveReferences", "tsconfig.b.json"), + TestFSWithWatch.getTsBuildProjectFile("transitiveReferences", "tsconfig.c.json"), + TestFSWithWatch.getTsBuildProjectFile("transitiveReferences", "a.ts"), + TestFSWithWatch.getTsBuildProjectFile("transitiveReferences", "b.ts"), + TestFSWithWatch.getTsBuildProjectFile("transitiveReferences", "c.ts"), + TestFSWithWatch.getTsBuildProjectFile("transitiveReferences", "refs/a.d.ts"), + ], + { currentDirectory: `${TestFSWithWatch.tsbuildProjectsLocation}/transitiveReferences` } + ), + commandLineArgs: ["-w", "-p", "tsconfig.c.json"], + changes: [ + { + caption: "non local edit b ts, and build b", + change: sys => { + sys.appendFile(TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "b.ts"), `export function gfoo() { }`); + const solutionBuilder = createSolutionBuilder(sys, ["tsconfig.b.json"]); + solutionBuilder.build(); + }, + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "edit on config file", + change: sys => { + sys.ensureFileOrFolder({ + path: TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "nrefs/a.d.ts"), + content: sys.readFile(TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "refs/a.d.ts"))! + }); + changeCompilerOpitonsPaths(sys, TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "tsconfig.c.json"), { "@ref/*": ["./nrefs/*"] }); + }, + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "Revert config file edit", + change: sys => changeCompilerOpitonsPaths(sys, TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "tsconfig.c.json"), { "@ref/*": ["./refs/*"] }), + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "edit in referenced config file", + change: sys => changeCompilerOpitonsPaths(sys, TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "tsconfig.b.json"), { "@ref/*": ["./nrefs/*"] }), + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "Revert referenced config file edit", + change: sys => changeCompilerOpitonsPaths(sys, TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "tsconfig.b.json"), { "@ref/*": ["./refs/*"] }), + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "deleting referenced config file", + change: sys => sys.deleteFile(TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "tsconfig.b.json")), + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "Revert deleting referenced config file", + change: sys => sys.ensureFileOrFolder(TestFSWithWatch.getTsBuildProjectFile("transitiveReferences", "tsconfig.b.json")), + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "deleting transitively referenced config file", + change: sys => sys.deleteFile(TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "tsconfig.a.json")), + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "Revert deleting transitively referenced config file", + change: sys => sys.ensureFileOrFolder(TestFSWithWatch.getTsBuildProjectFile("transitiveReferences", "tsconfig.a.json")), + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + ], + baselineDependencies: true, + }); + + verifyTscWatch({ + scenario: "projectsWithReferences", + subScenario: "when referenced project uses different module resolution", + sys: () => createSystemWithSolutionBuild( + ["tsconfig.c.json"], + [ + libFile, + TestFSWithWatch.getTsBuildProjectFile("transitiveReferences", "tsconfig.a.json"), + { + path: TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "tsconfig.b.json"), + content: JSON.stringify({ + compilerOptions: { composite: true, moduleResolution: "classic" }, + files: ["b.ts"], + references: [{ path: "tsconfig.a.json" }] + }) + }, + TestFSWithWatch.getTsBuildProjectFile("transitiveReferences", "tsconfig.c.json"), + TestFSWithWatch.getTsBuildProjectFile("transitiveReferences", "a.ts"), + { + path: TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "b.ts"), + content: `import {A} from "a";export const b = new A();` + }, + TestFSWithWatch.getTsBuildProjectFile("transitiveReferences", "c.ts"), + TestFSWithWatch.getTsBuildProjectFile("transitiveReferences", "refs/a.d.ts"), + ], + { currentDirectory: `${TestFSWithWatch.tsbuildProjectsLocation}/transitiveReferences` } + ), + commandLineArgs: ["-w", "-p", "tsconfig.c.json"], + changes: emptyArray, + baselineDependencies: true, + }); + + verifyTscWatch({ + scenario: "projectsWithReferences", + subScenario: "on transitive references in different folders", + sys: () => createSystemWithSolutionBuild( + ["c"], + [ + libFile, + { + path: TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "a/tsconfig.json"), + content: JSON.stringify({ + compilerOptions: { composite: true }, + files: ["index.ts"] + }), + }, + { + path: TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), + content: JSON.stringify({ + compilerOptions: { composite: true, baseUrl: "./", paths: { "@ref/*": ["../*"] } }, + files: ["index.ts"], + references: [{ path: `../a` }] + }), + }, + { + path: TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "c/tsconfig.json"), + content: JSON.stringify({ + compilerOptions: { baseUrl: "./", paths: { "@ref/*": ["../refs/*"] } }, + files: ["index.ts"], + references: [{ path: `../b` }] + }), + }, + { + path: TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "a/index.ts"), + content: `export class A {}`, + }, + { + path: TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "b/index.ts"), + content: `import {A} from '@ref/a'; +export const b = new A();`, + }, + { + path: TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "c/index.ts"), + content: `import {b} from '../b'; +import {X} from "@ref/a"; +b; +X;`, + }, + TestFSWithWatch.getTsBuildProjectFile("transitiveReferences", "refs/a.d.ts"), + ], + { currentDirectory: `${TestFSWithWatch.tsbuildProjectsLocation}/transitiveReferences` } + ), + commandLineArgs: ["-w", "-p", "c"], + changes: [ + { + caption: "non local edit b ts, and build b", + change: sys => { + sys.appendFile(TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "b/index.ts"), `export function gfoo() { }`); + const solutionBuilder = createSolutionBuilder(sys, ["b"]); + solutionBuilder.build(); + }, + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "edit on config file", + change: sys => { + sys.ensureFileOrFolder({ + path: TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "nrefs/a.d.ts"), + content: sys.readFile(TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "refs/a.d.ts"))! + }); + changeCompilerOpitonsPaths(sys, TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "c/tsconfig.json"), { "@ref/*": ["../nrefs/*"] }); + }, + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "Revert config file edit", + change: sys => changeCompilerOpitonsPaths(sys, TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "c/tsconfig.json"), { "@ref/*": ["../refs/*"] }), + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "edit in referenced config file", + change: sys => changeCompilerOpitonsPaths(sys, TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), { "@ref/*": ["../nrefs/*"] }), + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "Revert referenced config file edit", + change: sys => changeCompilerOpitonsPaths(sys, TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), { "@ref/*": ["../refs/*"] }), + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "deleting referenced config file", + change: sys => sys.deleteFile(TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json")), + timeouts: sys => sys.checkTimeoutQueueLengthAndRun(2) + }, + { + caption: "Revert deleting referenced config file", + change: sys => sys.writeFile( + TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), + JSON.stringify({ + compilerOptions: { composite: true, baseUrl: "./", paths: { "@ref/*": ["../*"] } }, + files: ["index.ts"], + references: [{ path: `../a` }] + }) + ), + timeouts: sys => sys.checkTimeoutQueueLengthAndRun(2) + }, + { + caption: "deleting transitively referenced config file", + change: sys => sys.deleteFile(TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "a/tsconfig.json")), + timeouts: sys => sys.checkTimeoutQueueLengthAndRun(2) + }, + { + caption: "Revert deleting transitively referenced config file", + change: sys => sys.writeFile( + TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "a/tsconfig.json"), + JSON.stringify({ + compilerOptions: { composite: true }, + files: ["index.ts"] + }), + ), + timeouts: sys => sys.checkTimeoutQueueLengthAndRun(2) + }, + ], + baselineDependencies: true, + }); + + verifyTscWatch({ + scenario: "projectsWithReferences", + subScenario: "on transitive references in different folders with no files clause", + sys: () => createSystemWithSolutionBuild( + ["c"], + [ + libFile, + { + path: TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "a/tsconfig.json"), + content: JSON.stringify({ compilerOptions: { composite: true } }), + }, + { + path: TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), + content: JSON.stringify({ + compilerOptions: { composite: true, baseUrl: "./", paths: { "@ref/*": ["../*"] } }, + references: [{ path: `../a` }] + }), + }, + { + path: TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "c/tsconfig.json"), + content: JSON.stringify({ + compilerOptions: { baseUrl: "./", paths: { "@ref/*": ["../refs/*"] } }, + references: [{ path: `../b` }] + }), + }, + { + path: TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "a/index.ts"), + content: `export class A {}`, + }, + { + path: TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "b/index.ts"), + content: `import {A} from '@ref/a'; +export const b = new A();`, + }, + { + path: TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "c/index.ts"), + content: `import {b} from '../b'; +import {X} from "@ref/a"; +b; +X;`, + }, + TestFSWithWatch.getTsBuildProjectFile("transitiveReferences", "refs/a.d.ts"), + ], + { currentDirectory: `${TestFSWithWatch.tsbuildProjectsLocation}/transitiveReferences` } + ), + commandLineArgs: ["-w", "-p", "c"], + changes: [ + { + caption: "non local edit b ts, and build b", + change: sys => { + sys.appendFile(TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "b/index.ts"), `export function gfoo() { }`); + const solutionBuilder = createSolutionBuilder(sys, ["b"]); + solutionBuilder.build(); + }, + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "edit on config file", + change: sys => { + sys.ensureFileOrFolder({ + path: TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "nrefs/a.d.ts"), + content: sys.readFile(TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "refs/a.d.ts"))! + }); + changeCompilerOpitonsPaths(sys, TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "c/tsconfig.json"), { "@ref/*": ["../nrefs/*"] }); + }, + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "Revert config file edit", + change: sys => changeCompilerOpitonsPaths(sys, TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "c/tsconfig.json"), { "@ref/*": ["../refs/*"] }), + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "edit in referenced config file", + change: sys => changeCompilerOpitonsPaths(sys, TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), { "@ref/*": ["../nrefs/*"] }), + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "Revert referenced config file edit", + change: sys => changeCompilerOpitonsPaths(sys, TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), { "@ref/*": ["../refs/*"] }), + timeouts: checkSingleTimeoutQueueLengthAndRun + }, + { + caption: "deleting referenced config file", + change: sys => sys.deleteFile(TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json")), + timeouts: sys => sys.checkTimeoutQueueLengthAndRun(2) + }, + { + caption: "Revert deleting referenced config file", + change: sys => sys.writeFile( + TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), + JSON.stringify({ + compilerOptions: { composite: true, baseUrl: "./", paths: { "@ref/*": ["../*"] } }, + references: [{ path: `../a` }] + }) + ), + timeouts: sys => sys.checkTimeoutQueueLengthAndRun(2) + }, + { + caption: "deleting transitively referenced config file", + change: sys => sys.deleteFile(TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "a/tsconfig.json")), + timeouts: sys => sys.checkTimeoutQueueLengthAndRun(2) + }, + { + caption: "Revert deleting transitively referenced config file", + change: sys => sys.writeFile( + TestFSWithWatch.getTsBuildProjectFilePath("transitiveReferences", "a/tsconfig.json"), + JSON.stringify({ compilerOptions: { composite: true } }), + ), + timeouts: sys => sys.checkTimeoutQueueLengthAndRun(2) + }, + ], + baselineDependencies: true, + }); + }); +} \ No newline at end of file diff --git a/src/testRunner/unittests/tscWatch/resolutionCache.ts b/src/testRunner/unittests/tscWatch/resolutionCache.ts index 03cc81752a554..b8f065ae41b82 100644 --- a/src/testRunner/unittests/tscWatch/resolutionCache.ts +++ b/src/testRunner/unittests/tscWatch/resolutionCache.ts @@ -449,5 +449,84 @@ declare namespace myapp { }, changes: emptyArray }); + + describe("works when installing something in node_modules or @types when there is no notification from fs for index file", () => { + function getNodeAtTypes() { + const nodeAtTypesIndex: File = { + path: `${projectRoot}/node_modules/@types/node/index.d.ts`, + content: `/// ` + }; + const nodeAtTypesBase: File = { + path: `${projectRoot}/node_modules/@types/node/base.d.ts`, + content: `// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// ` + }; + const nodeAtTypes36Base: File = { + path: `${projectRoot}/node_modules/@types/node/ts3.6/base.d.ts`, + content: `/// ` + }; + const nodeAtTypesGlobals: File = { + path: `${projectRoot}/node_modules/@types/node/globals.d.ts`, + content: `declare var process: NodeJS.Process; +declare namespace NodeJS { + interface Process { + on(msg: string): void; + } +}` + }; + return { nodeAtTypesIndex, nodeAtTypesBase, nodeAtTypes36Base, nodeAtTypesGlobals }; + } + verifyTscWatch({ + scenario, + subScenario: "works when installing something in node_modules or @types when there is no notification from fs for index file", + commandLineArgs: ["--w", `--extendedDiagnostics`], + sys: () => { + const file: File = { + path: `${projectRoot}/worker.ts`, + content: `process.on("uncaughtException");` + }; + const tsconfig: File = { + path: `${projectRoot}/tsconfig.json`, + content: "{}" + }; + const { nodeAtTypesIndex, nodeAtTypesBase, nodeAtTypes36Base, nodeAtTypesGlobals } = getNodeAtTypes(); + return createWatchedSystem([file, libFile, tsconfig, nodeAtTypesIndex, nodeAtTypesBase, nodeAtTypes36Base, nodeAtTypesGlobals], { currentDirectory: projectRoot }); + }, + changes: [ + { + caption: "npm ci step one: remove all node_modules files", + change: sys => sys.deleteFolder(`${projectRoot}/node_modules/@types`, /*recursive*/ true), + timeouts: runQueuedTimeoutCallbacks, + }, + { + caption: `npm ci step two: create atTypes but something else in the @types folder`, + change: sys => sys.ensureFileOrFolder({ + path: `${projectRoot}/node_modules/@types/mocha/index.d.ts`, + content: `export const foo = 10;` + }), + timeouts: runQueuedTimeoutCallbacks + }, + { + caption: `npm ci step three: create atTypes node folder`, + change: sys => sys.ensureFileOrFolder({ path: `${projectRoot}/node_modules/@types/node` }), + timeouts: runQueuedTimeoutCallbacks + }, + { + caption: `npm ci step four: create atTypes write all the files but dont invoke watcher for index.d.ts`, + change: sys => { + const { nodeAtTypesIndex, nodeAtTypesBase, nodeAtTypes36Base, nodeAtTypesGlobals } = getNodeAtTypes(); + sys.ensureFileOrFolder(nodeAtTypesBase); + sys.ensureFileOrFolder(nodeAtTypesIndex, /*ignoreWatchInvokedWithTriggerAsFileCreate*/ true); + sys.ensureFileOrFolder(nodeAtTypes36Base, /*ignoreWatchInvokedWithTriggerAsFileCreate*/ true); + sys.ensureFileOrFolder(nodeAtTypesGlobals, /*ignoreWatchInvokedWithTriggerAsFileCreate*/ true); + }, + timeouts: sys => { + sys.runQueuedTimeoutCallbacks(); // update failed lookups + sys.runQueuedTimeoutCallbacks(); // actual program update + }, + }, + ] + }); + }); }); } diff --git a/src/testRunner/unittests/tscWatch/watchApi.ts b/src/testRunner/unittests/tscWatch/watchApi.ts index 5e32bb8c16164..d71318d2de868 100644 --- a/src/testRunner/unittests/tscWatch/watchApi.ts +++ b/src/testRunner/unittests/tscWatch/watchApi.ts @@ -243,4 +243,140 @@ namespace ts.tscWatch { verifyBuilder(config, sys, emitSys, createSemanticDiagnosticsBuilderProgram, createEmitAndSemanticDiagnosticsBuilderProgram, { noEmitOnError: true }); }); }); + + describe("unittests:: tsc-watch:: watchAPI:: when getParsedCommandLine is implemented", () => { + function setup(useSourceOfProjectReferenceRedirect?: () => boolean) { + const config1: File = { + path: `${projectRoot}/projects/project1/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + module: "none", + composite: true + }, + exclude: ["temp"] + }) + }; + const class1: File = { + path: `${projectRoot}/projects/project1/class1.ts`, + content: `class class1 {}` + }; + const class1Dts: File = { + path: `${projectRoot}/projects/project1/class1.d.ts`, + content: `declare class class1 {}` + }; + const config2: File = { + path: `${projectRoot}/projects/project2/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + module: "none", + composite: true + }, + references: [ + { path: "../project1" } + ] + }) + }; + const class2: File = { + path: `${projectRoot}/projects/project2/class2.ts`, + content: `class class2 {}` + }; + const system = createWatchedSystem([config1, class1, class1Dts, config2, class2, libFile]); + const baseline = createBaseline(system); + const compilerHost = createWatchCompilerHostOfConfigFile({ + configFileName: config2.path, + system, + optionsToExtend: { extendedDiagnostics: true } + }); + compilerHost.useSourceOfProjectReferenceRedirect = useSourceOfProjectReferenceRedirect; + const calledGetParsedCommandLine = new Set(); + compilerHost.getParsedCommandLine = fileName => { + assert.isFalse(calledGetParsedCommandLine.has(fileName), `Already called on ${fileName}`); + calledGetParsedCommandLine.add(fileName); + return getParsedCommandLineOfConfigFile(fileName, /*optionsToExtend*/ undefined, { + useCaseSensitiveFileNames: true, + fileExists: path => system.fileExists(path), + readFile: path => system.readFile(path), + getCurrentDirectory: () => system.getCurrentDirectory(), + readDirectory: (path, extensions, excludes, includes, depth) => system.readDirectory(path, extensions, excludes, includes, depth), + onUnRecoverableConfigFileDiagnostic: noop, + }); + }; + const watch = createWatchProgram(compilerHost); + return { watch, baseline, config2, calledGetParsedCommandLine }; + } + + it("when new file is added to the referenced project with host implementing getParsedCommandLine", () => { + const { watch, baseline, config2, calledGetParsedCommandLine } = setup(returnTrue); + runWatchBaseline({ + scenario: "watchApi", + subScenario: "when new file is added to the referenced project with host implementing getParsedCommandLine", + commandLineArgs: ["--w", "-p", config2.path, "--extendedDiagnostics"], + ...baseline, + getPrograms: () => [[watch.getCurrentProgram().getProgram(), watch.getCurrentProgram()]], + changes: [ + { + caption: "Add class3 to project1", + change: sys => { + calledGetParsedCommandLine.clear(); + sys.writeFile(`${projectRoot}/projects/project1/class3.ts`, `class class3 {}`); + }, + timeouts: checkSingleTimeoutQueueLengthAndRun, + }, + { + caption: "Add excluded file to project1", + change: sys => sys.ensureFileOrFolder({ path: `${projectRoot}/projects/project1/temp/file.d.ts`, content: `declare class file {}` }), + timeouts: sys => sys.checkTimeoutQueueLength(0), + }, + { + caption: "Add output of class3", + change: sys => sys.writeFile(`${projectRoot}/projects/project1/class3.d.ts`, `declare class class3 {}`), + timeouts: sys => sys.checkTimeoutQueueLength(0), + }, + ], + watchOrSolution: watch + }); + }); + + it("when new file is added to the referenced project with host implementing getParsedCommandLine without implementing useSourceOfProjectReferenceRedirect", () => { + const { watch, baseline, config2, calledGetParsedCommandLine } = setup(); + runWatchBaseline({ + scenario: "watchApi", + subScenario: "when new file is added to the referenced project with host implementing getParsedCommandLine without implementing useSourceOfProjectReferenceRedirect", + commandLineArgs: ["--w", "-p", config2.path, "--extendedDiagnostics"], + ...baseline, + getPrograms: () => [[watch.getCurrentProgram().getProgram(), watch.getCurrentProgram()]], + changes: [ + { + caption: "Add class3 to project1", + change: sys => { + calledGetParsedCommandLine.clear(); + sys.writeFile(`${projectRoot}/projects/project1/class3.ts`, `class class3 {}`); + }, + timeouts: checkSingleTimeoutQueueLengthAndRun, + }, + { + caption: "Add class3 output to project1", + change: sys => sys.writeFile(`${projectRoot}/projects/project1/class3.d.ts`, `declare class class3 {}`), + timeouts: checkSingleTimeoutQueueLengthAndRun, + }, + { + caption: "Add excluded file to project1", + change: sys => sys.ensureFileOrFolder({ path: `${projectRoot}/projects/project1/temp/file.d.ts`, content: `declare class file {}` }), + timeouts: sys => sys.checkTimeoutQueueLength(0), + }, + { + caption: "Delete output of class3", + change: sys => sys.deleteFile(`${projectRoot}/projects/project1/class3.d.ts`), + timeouts: checkSingleTimeoutQueueLengthAndRun, + }, + { + caption: "Add output of class3", + change: sys => sys.writeFile(`${projectRoot}/projects/project1/class3.d.ts`, `declare class class3 {}`), + timeouts: checkSingleTimeoutQueueLengthAndRun, + }, + ], + watchOrSolution: watch + }); + }); + }); } diff --git a/src/testRunner/unittests/tscWatch/watchEnvironment.ts b/src/testRunner/unittests/tscWatch/watchEnvironment.ts index b510cf6d2f673..d02afa3137714 100644 --- a/src/testRunner/unittests/tscWatch/watchEnvironment.ts +++ b/src/testRunner/unittests/tscWatch/watchEnvironment.ts @@ -66,6 +66,90 @@ namespace ts.tscWatch { ] }); + verifyTscWatch({ + scenario, + subScenario: "watchFile/using fixed chunk size polling", + commandLineArgs: ["-w", "-p", "/a/b/tsconfig.json"], + sys: () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: JSON.stringify({ + watchOptions: { + watchFile: "FixedChunkSizePolling" + } + }) + }; + const files = [libFile, commonFile1, commonFile2, configFile]; + return createWatchedSystem(files); + }, + changes: [ + { + caption: "The timeout is to check the status of all files", + change: noop, + timeouts: (sys, programs) => { + // On each timeout file does not change + const initialProgram = programs[0][0]; + for (let index = 0; index < 4; index++) { + sys.checkTimeoutQueueLengthAndRun(1); + assert.deepEqual(programs[0][0], initialProgram); + } + }, + }, + { + caption: "Make change to file but should detect as changed and schedule program update", + // Make a change to file + change: sys => sys.writeFile(commonFile1.path, "var zz30 = 100;"), + timeouts: checkSingleTimeoutQueueLengthAndRun, + }, + { + caption: "Callbacks: queue and scheduled program update", + change: noop, + // Callbacks: scheduled program update and queue for the polling + timeouts: sys => sys.checkTimeoutQueueLengthAndRun(2), + }, + { + caption: "The timeout is to check the status of all files", + change: noop, + timeouts: (sys, programs) => { + // On each timeout file does not change + const initialProgram = programs[0][0]; + sys.checkTimeoutQueueLengthAndRun(1); + assert.deepEqual(programs[0][0], initialProgram); + }, + }, + ] + }); + + verifyTscWatch({ + scenario, + subScenario: "watchFile/setting default as fixed chunk size watch file works", + commandLineArgs: ["-w", "-p", "/a/b/tsconfig.json"], + sys: () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: "{}" + }; + const files = [libFile, commonFile1, commonFile2, configFile]; + const sys = createWatchedSystem(files); + sys.defaultWatchFileKind = () => WatchFileKind.FixedChunkSizePolling; + return sys; + }, + changes: [ + { + caption: "Make change to file but should detect as changed and schedule program update", + // Make a change to file + change: sys => sys.writeFile(commonFile1.path, "var zz30 = 100;"), + timeouts: checkSingleTimeoutQueueLengthAndRun, + }, + { + caption: "Callbacks: queue and scheduled program update", + change: noop, + // Callbacks: scheduled program update and queue for the polling + timeouts: sys => sys.checkTimeoutQueueLengthAndRun(2), + }, + ] + }); + describe("tsc-watch when watchDirectories implementation", () => { function verifyRenamingFileInSubFolder(subScenario: string, tscWatchDirectory: Tsc_WatchDirectory) { const projectFolder = "/a/username/project"; diff --git a/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts b/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts index b4a6c2f12f20a..51b5ae9f5d301 100644 --- a/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts +++ b/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts @@ -713,5 +713,40 @@ namespace ts.projectSystem { checkProjectActualFiles(project, files.map(f => f.path)); assert.deepEqual(project.getLanguageService().getSemanticDiagnostics(app.path).map(diag => diag.messageText), []); }); + + it("when creating new file in symlinked folder", () => { + const module1: File = { + path: `${tscWatch.projectRoot}/client/folder1/module1.ts`, + content: `export class Module1Class { }` + }; + const module2: File = { + path: `${tscWatch.projectRoot}/folder2/module2.ts`, + content: `import * as M from "folder1/module1";` + }; + const symlink: SymLink = { + path: `${tscWatch.projectRoot}/client/linktofolder2`, + symLink: `${tscWatch.projectRoot}/folder2`, + }; + const config: File = { + path: `${tscWatch.projectRoot}/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + baseUrl: "client", + paths: { "*": ["*"] }, + }, + include: ["client/**/*", "folder2"] + }) + }; + const host = createServerHost([module1, module2, symlink, config, libFile]); + const service = createProjectService(host); + service.openClientFile(`${symlink.path}/module2.ts`); + checkNumberOfProjects(service, { configuredProjects: 1 }); + const project = Debug.checkDefined(service.configuredProjects.get(config.path)); + checkProjectActualFiles(project, [module1.path, `${symlink.path}/module2.ts`, config.path, libFile.path]); + host.writeFile(`${symlink.path}/module3.ts`, `import * as M from "folder1/module1";`); + host.runQueuedTimeoutCallbacks(); + checkNumberOfProjects(service, { configuredProjects: 1 }); + checkProjectActualFiles(project, [module1.path, `${symlink.path}/module2.ts`, config.path, libFile.path, `${symlink.path}/module3.ts`]); + }); }); } diff --git a/src/testRunner/unittests/tsserver/completions.ts b/src/testRunner/unittests/tsserver/completions.ts index 2117d8924aa0c..ff221fdd0bed4 100644 --- a/src/testRunner/unittests/tsserver/completions.ts +++ b/src/testRunner/unittests/tsserver/completions.ts @@ -37,8 +37,12 @@ namespace ts.projectSystem { name: "foo", replacementSpan: undefined, isPackageJsonImport: undefined, + isImportStatementCompletion: undefined, sortText: Completions.SortText.AutoImportSuggestions, source: "/a", + sourceDisplay: undefined, + isSnippet: undefined, + data: { exportName: "foo", fileName: "/a.ts", ambientModuleName: undefined, isPackageJsonImport: undefined, moduleSpecifier: undefined } }; assert.deepEqual(response, { isGlobalCompletion: true, @@ -50,7 +54,7 @@ namespace ts.projectSystem { const detailsRequestArgs: protocol.CompletionDetailsRequestArgs = { ...requestLocation, - entryNames: [{ name: "foo", source: "/a" }], + entryNames: [{ name: "foo", source: "/a", data: { exportName: "foo", fileName: "/a.ts" } }], }; const detailsResponse = executeSessionRequest(session, protocol.CommandTypes.CompletionDetails, detailsRequestArgs); @@ -68,7 +72,7 @@ namespace ts.projectSystem { kindModifiers: ScriptElementKindModifier.exportedModifier, name: "foo", source: [{ text: "./a", kind: "text" }], - tags: undefined, + sourceDisplay: [{ text: "./a", kind: "text" }], }; assert.deepEqual(detailsResponse, [ { @@ -90,6 +94,7 @@ namespace ts.projectSystem { commands: undefined, }, ], + tags: [], ...detailsCommon, }, ]); @@ -116,6 +121,7 @@ namespace ts.projectSystem { commands: undefined, } ], + tags: [], ...detailsCommon, } ]); diff --git a/src/testRunner/unittests/tsserver/documentRegistry.ts b/src/testRunner/unittests/tsserver/documentRegistry.ts index 94098ab1bd9ba..8c29af51a27a0 100644 --- a/src/testRunner/unittests/tsserver/documentRegistry.ts +++ b/src/testRunner/unittests/tsserver/documentRegistry.ts @@ -27,7 +27,7 @@ namespace ts.projectSystem { assert.isDefined(moduleInfo); assert.equal(moduleInfo.isOrphan(), moduleIsOrphan); const key = service.documentRegistry.getKeyForCompilationSettings(project.getCompilationSettings()); - assert.deepEqual(service.documentRegistry.getLanguageServiceRefCounts(moduleInfo.path), [[key, moduleIsOrphan ? undefined : 1]]); + assert.deepEqual(service.documentRegistry.getLanguageServiceRefCounts(moduleInfo.path, moduleInfo.scriptKind), [[key, moduleIsOrphan ? undefined : 1]]); } function createServiceAndHost() { diff --git a/src/testRunner/unittests/tsserver/dynamicFiles.ts b/src/testRunner/unittests/tsserver/dynamicFiles.ts index 95976bffa1f9f..554c4c8c67477 100644 --- a/src/testRunner/unittests/tsserver/dynamicFiles.ts +++ b/src/testRunner/unittests/tsserver/dynamicFiles.ts @@ -121,6 +121,28 @@ var x = 10;` service.openClientFile(file.path); checkNumberOfProjects(service, { configuredProjects: 1 }); }); + + it("when changing scriptKind of the untitled files", () => { + const host = createServerHost([libFile], { useCaseSensitiveFileNames: true }); + const service = createProjectService(host, { useInferredProjectPerProjectRoot: true }); + service.openClientFile(untitledFile, "const x = 10;", ScriptKind.TS, tscWatch.projectRoot); + checkNumberOfProjects(service, { inferredProjects: 1 }); + checkProjectActualFiles(service.inferredProjects[0], [untitledFile, libFile.path]); + const program = service.inferredProjects[0].getCurrentProgram()!; + const sourceFile = program.getSourceFile(untitledFile)!; + + // Close untitled file + service.closeClientFile(untitledFile); + + // Open untitled file with different mode + service.openClientFile(untitledFile, "const x = 10;", ScriptKind.TSX, tscWatch.projectRoot); + checkNumberOfProjects(service, { inferredProjects: 1 }); + checkProjectActualFiles(service.inferredProjects[0], [untitledFile, libFile.path]); + const newProgram = service.inferredProjects[0].getCurrentProgram()!; + const newSourceFile = newProgram.getSourceFile(untitledFile)!; + assert.notStrictEqual(newProgram, program); + assert.notStrictEqual(newSourceFile, sourceFile); + }); }); describe("unittests:: tsserver:: dynamicFiles:: ", () => { diff --git a/src/testRunner/unittests/tsserver/exportMapCache.ts b/src/testRunner/unittests/tsserver/exportMapCache.ts new file mode 100644 index 0000000000000..803d8b9d62234 --- /dev/null +++ b/src/testRunner/unittests/tsserver/exportMapCache.ts @@ -0,0 +1,88 @@ +namespace ts.projectSystem { + const packageJson: File = { + path: "/package.json", + content: `{ "dependencies": { "mobx": "*" } }` + }; + const aTs: File = { + path: "/a.ts", + content: "export const foo = 0;", + }; + const bTs: File = { + path: "/b.ts", + content: "foo", + }; + const tsconfig: File = { + path: "/tsconfig.json", + content: "{}", + }; + const ambientDeclaration: File = { + path: "/ambient.d.ts", + content: "declare module 'ambient' {}" + }; + const mobxDts: File = { + path: "/node_modules/mobx/index.d.ts", + content: "export declare function observable(): unknown;" + }; + + describe("unittests:: tsserver:: exportMapCache", () => { + it("caches auto-imports in the same file", () => { + const { exportMapCache, checker } = setup(); + assert.ok(exportMapCache.get(bTs.path as Path, checker)); + }); + + it("invalidates the cache when new files are added", () => { + const { host, exportMapCache, checker } = setup(); + host.writeFile("/src/a2.ts", aTs.content); + host.runQueuedTimeoutCallbacks(); + assert.isUndefined(exportMapCache.get(bTs.path as Path, checker)); + }); + + it("invalidates the cache when files are deleted", () => { + const { host, projectService, exportMapCache, checker } = setup(); + projectService.closeClientFile(aTs.path); + host.deleteFile(aTs.path); + host.runQueuedTimeoutCallbacks(); + assert.isUndefined(exportMapCache.get(bTs.path as Path, checker)); + }); + + it("does not invalidate the cache when package.json is changed inconsequentially", () => { + const { host, exportMapCache, checker, project } = setup(); + host.writeFile("/package.json", `{ "name": "blah", "dependencies": { "mobx": "*" } }`); + host.runQueuedTimeoutCallbacks(); + project.getPackageJsonAutoImportProvider(); + assert.ok(exportMapCache.get(bTs.path as Path, checker)); + }); + + it("invalidates the cache when package.json change results in AutoImportProvider change", () => { + const { host, exportMapCache, checker, project } = setup(); + host.writeFile("/package.json", `{}`); + host.runQueuedTimeoutCallbacks(); + project.getPackageJsonAutoImportProvider(); + assert.isUndefined(exportMapCache.get(bTs.path as Path, checker)); + }); + }); + + function setup() { + const host = createServerHost([aTs, bTs, ambientDeclaration, tsconfig, packageJson, mobxDts]); + const session = createSession(host); + openFilesForSession([aTs, bTs], session); + const projectService = session.getProjectService(); + const project = configuredProjectAt(projectService, 0); + triggerCompletions(); + const checker = project.getLanguageService().getProgram()!.getTypeChecker(); + return { host, project, projectService, exportMapCache: project.getExportMapCache(), checker, triggerCompletions }; + + function triggerCompletions() { + const requestLocation: protocol.FileLocationRequestArgs = { + file: bTs.path, + line: 1, + offset: 3, + }; + executeSessionRequest(session, protocol.CommandTypes.CompletionInfo, { + ...requestLocation, + includeExternalModuleExports: true, + prefix: "foo", + }); + } + } +} diff --git a/src/testRunner/unittests/tsserver/helpers.ts b/src/testRunner/unittests/tsserver/helpers.ts index f20efe386c013..1215aaa87981a 100644 --- a/src/testRunner/unittests/tsserver/helpers.ts +++ b/src/testRunner/unittests/tsserver/helpers.ts @@ -440,6 +440,13 @@ namespace ts.projectSystem { return iterResult.value; } + export function checkOrphanScriptInfos(service: server.ProjectService, expectedFiles: readonly string[]) { + checkArray("Orphan ScriptInfos:", arrayFrom(mapDefinedIterator( + service.filenameToScriptInfo.values(), + v => v.containingProjects.length === 0 ? v.fileName : undefined + )), expectedFiles); + } + export function checkProjectActualFiles(project: server.Project, expectedFiles: readonly string[]) { checkArray(`${server.ProjectKind[project.projectKind]} project: ${project.getProjectName()}:: actual files`, project.getFileNames(), expectedFiles); } diff --git a/src/testRunner/unittests/tsserver/importSuggestionsCache.ts b/src/testRunner/unittests/tsserver/importSuggestionsCache.ts deleted file mode 100644 index 982eece3d36ad..0000000000000 --- a/src/testRunner/unittests/tsserver/importSuggestionsCache.ts +++ /dev/null @@ -1,75 +0,0 @@ -namespace ts.projectSystem { - const packageJson: File = { - path: "/package.json", - content: `{ "dependencies": { "mobx": "*" } }` - }; - const aTs: File = { - path: "/a.ts", - content: "export const foo = 0;", - }; - const bTs: File = { - path: "/b.ts", - content: "foo", - }; - const tsconfig: File = { - path: "/tsconfig.json", - content: "{}", - }; - const ambientDeclaration: File = { - path: "/ambient.d.ts", - content: "declare module 'ambient' {}" - }; - const mobxDts: File = { - path: "/node_modules/mobx/index.d.ts", - content: "export declare function observable(): unknown;" - }; - - describe("unittests:: tsserver:: importSuggestionsCache", () => { - it("caches auto-imports in the same file", () => { - const { importSuggestionsCache, checker } = setup(); - assert.ok(importSuggestionsCache.get(bTs.path, checker)); - }); - - it("invalidates the cache when new files are added", () => { - const { host, importSuggestionsCache, checker } = setup(); - host.writeFile("/src/a2.ts", aTs.content); - host.runQueuedTimeoutCallbacks(); - assert.isUndefined(importSuggestionsCache.get(bTs.path, checker)); - }); - - it("invalidates the cache when files are deleted", () => { - const { host, projectService, importSuggestionsCache, checker } = setup(); - projectService.closeClientFile(aTs.path); - host.deleteFile(aTs.path); - host.runQueuedTimeoutCallbacks(); - assert.isUndefined(importSuggestionsCache.get(bTs.path, checker)); - }); - - it("invalidates the cache when package.json is changed", () => { - const { host, importSuggestionsCache, checker } = setup(); - host.writeFile("/package.json", "{}"); - host.runQueuedTimeoutCallbacks(); - assert.isUndefined(importSuggestionsCache.get(bTs.path, checker)); - }); - }); - - function setup() { - const host = createServerHost([aTs, bTs, ambientDeclaration, tsconfig, packageJson, mobxDts]); - const session = createSession(host); - openFilesForSession([aTs, bTs], session); - const projectService = session.getProjectService(); - const project = configuredProjectAt(projectService, 0); - const requestLocation: protocol.FileLocationRequestArgs = { - file: bTs.path, - line: 1, - offset: 3, - }; - executeSessionRequest(session, protocol.CommandTypes.CompletionInfo, { - ...requestLocation, - includeExternalModuleExports: true, - prefix: "foo", - }); - const checker = project.getLanguageService().getProgram()!.getTypeChecker(); - return { host, project, projectService, importSuggestionsCache: project.getImportSuggestionsCache(), checker }; - } -} diff --git a/src/testRunner/unittests/tsserver/jsdocTag.ts b/src/testRunner/unittests/tsserver/jsdocTag.ts new file mode 100644 index 0000000000000..7699c107586e2 --- /dev/null +++ b/src/testRunner/unittests/tsserver/jsdocTag.ts @@ -0,0 +1,694 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: jsdoc @link ", () => { + const config: File = { + path: "/a/tsconfig.json", + content: `{ +"compilerOptions": { +"checkJs": true, +"noEmit": true +} +"files": ["someFile1.js"] +} +` + }; + function assertQuickInfoJSDoc(file: File, options: { + displayPartsForJSDoc: boolean, + command: protocol.CommandTypes, + tags: string | unknown[] | undefined, + documentation: string | unknown[] + }) { + + const { command, displayPartsForJSDoc, tags, documentation } = options; + const session = createSession(createServerHost([file, config])); + session.getProjectService().setHostConfiguration({ preferences: { displayPartsForJSDoc } }); + openFilesForSession([file], session); + const indexOfX = file.content.indexOf("x"); + const quickInfo = session.executeCommandSeq({ + command: command as protocol.CommandTypes.Quickinfo, + arguments: { + file: file.path, + position: indexOfX, + } as protocol.FileLocationRequestArgs + }).response; + const summaryAndLocation = command === protocol.CommandTypes.Quickinfo ? { + displayString: "var x: number", + start: { + line: 3, + offset: 5, + }, + end: { + line: 3, + offset: 6, + } + } : { + displayParts: [{ + kind: "keyword", + text: "var", + }, { + kind: "space", + text: " ", + }, { + kind: "localName", + text: "x", + }, { + kind: "punctuation", + text: ":", + }, { + kind: "space", + text: " ", + }, { + kind: "keyword", + text: "number", + }], + textSpan: { + length: 1, + start: 38, + } + }; + assert.deepEqual(quickInfo, { + kind: "var", + kindModifiers: "", + ...summaryAndLocation, + documentation, + tags + }); + } + + const linkInTag: File = { + path: "/a/someFile1.js", + content: `class C { } +/** @wat {@link C} */ +var x = 1` + }; + const linkInComment: File = { + path: "/a/someFile1.js", + content: `class C { } + /** {@link C} */ +var x = 1 +;` + }; + + it("for quickinfo, should provide display parts plus a span for a working link in a tag", () => { + assertQuickInfoJSDoc(linkInTag, { + command: protocol.CommandTypes.Quickinfo, + displayPartsForJSDoc: true, + documentation: [], + tags: [{ + name: "wat", + text: [{ + kind: "text", + text: "", + }, { + kind: "link", + text: "{@link ", + }, { + kind: "linkName", + target: { + end: { + line: 1, + offset: 12, + }, + file: "/a/someFile1.js", + start: { + line: 1, + offset: 1, + }, + }, + text: "C", + }, { + kind: "link", + text: "}", + }] + }], + }); + }); + it("for quickinfo, should provide a string for a working link in a tag", () => { + assertQuickInfoJSDoc(linkInTag, { + command: protocol.CommandTypes.Quickinfo, + displayPartsForJSDoc: false, + documentation: "", + tags: [{ + name: "wat", + text: "{@link C}" + }], + }); + }); + it("for quickinfo, should provide display parts for a working link in a comment", () => { + assertQuickInfoJSDoc(linkInComment, { + command: protocol.CommandTypes.Quickinfo, + displayPartsForJSDoc: true, + documentation: [{ + kind: "text", + text: "", + }, { + kind: "link", + text: "{@link ", + }, { + kind: "linkName", + target: { + end: { + line: 1, + offset: 12, + }, + file: "/a/someFile1.js", + start: { + line: 1, + offset: 1, + }, + }, + text: "C", + }, { + kind: "link", + text: "}", + }], + tags: [], + }); + }); + it("for quickinfo, should provide a string for a working link in a comment", () => { + assertQuickInfoJSDoc(linkInComment, { + command: protocol.CommandTypes.Quickinfo, + displayPartsForJSDoc: false, + documentation: "{@link C}", + tags: [], + }); + }); + + it("for quickinfo-full, should provide display parts plus a span for a working link in a tag", () => { + assertQuickInfoJSDoc(linkInTag, { + command: protocol.CommandTypes.QuickinfoFull, + displayPartsForJSDoc: true, + documentation: [], + tags: [{ + name: "wat", + text: [{ + kind: "text", + text: "", + }, { + kind: "link", + text: "{@link ", + }, { + kind: "linkName", + target: { + fileName: "/a/someFile1.js", + textSpan: { + length: 11, + start: 0 + }, + }, + text: "C", + }, { + kind: "link", + text: "}", + }] + }], + }); + }); + it("for quickinfo-full, should provide a string for a working link in a tag", () => { + assertQuickInfoJSDoc(linkInTag, { + command: protocol.CommandTypes.QuickinfoFull, + displayPartsForJSDoc: false, + documentation: [], + tags: [{ + name: "wat", + text: "{@link C}" + }], + }); + }); + it("for quickinfo-full, should provide display parts plus a span for a working link in a comment", () => { + assertQuickInfoJSDoc(linkInComment, { + command: protocol.CommandTypes.QuickinfoFull, + displayPartsForJSDoc: true, + documentation: [{ + kind: "text", + text: "", + }, { + kind: "link", + text: "{@link ", + }, { + kind: "linkName", + target: { + fileName: "/a/someFile1.js", + textSpan: { + length: 11, + start: 0 + }, + }, + text: "C", + }, { + kind: "link", + text: "}", + }], + tags: undefined, + }); + }); + it("for quickinfo-full, should provide a string for a working link in a comment", () => { + assertQuickInfoJSDoc(linkInComment, { + command: protocol.CommandTypes.QuickinfoFull, + displayPartsForJSDoc: false, + documentation: [{ + kind: "text", + text: "", + }, { + kind: "link", + text: "{@link ", + }, { + kind: "linkName", + target: { + fileName: "/a/someFile1.js", + textSpan: { + length: 11, + start: 0 + }, + }, + text: "C", + }, { + kind: "link", + text: "}", + }], + tags: [], + }); + }); + + function assertSignatureHelpJSDoc(options: { + displayPartsForJSDoc: boolean, + command: protocol.CommandTypes, + documentation: string | unknown[], + tags: unknown[] + }) { + const linkInParamTag: File = { + path: "/a/someFile1.js", + content: `class C { } +/** @param y - {@link C} */ +function x(y) { } +x(1)` + }; + + const { command, displayPartsForJSDoc, documentation, tags } = options; + const session = createSession(createServerHost([linkInParamTag, config])); + session.getProjectService().setHostConfiguration({ preferences: { displayPartsForJSDoc } }); + openFilesForSession([linkInParamTag], session); + const indexOfX = linkInParamTag.content.lastIndexOf("1"); + const signatureHelp = session.executeCommandSeq({ + command: command as protocol.CommandTypes.SignatureHelp, + arguments: { + triggerReason: { + kind: "invoked" + }, + file: linkInParamTag.path, + position: indexOfX, + } as protocol.SignatureHelpRequestArgs + }).response; + const applicableSpan = command === protocol.CommandTypes.SignatureHelp ? { + end: { + line: 4, + offset: 4 + }, + start: { + line: 4, + offset: 3 + } + } : { + length: 1, + start: 60 + }; + assert.deepEqual(signatureHelp, { + applicableSpan, + argumentCount: 1, + argumentIndex: 0, + selectedItemIndex: 0, + items: [{ + documentation: [], + isVariadic: false, + parameters: [{ + displayParts: [{ + kind: "parameterName", + text: "y" + }, { + kind: "punctuation", + text: ":" + }, { + kind: "space", + text: " " + }, { + kind: "keyword", + text: "any" + }], + documentation, + isOptional: false, + isRest: false, + name: "y" + }], + prefixDisplayParts: [ + { + kind: "functionName", + text: "x", + }, + { + kind: "punctuation", + text: "(", + }, + ], + separatorDisplayParts: [ + { + kind: "punctuation", + text: ",", + }, + { + kind: "space", + text: " ", + }, + ], + suffixDisplayParts: [ + { + kind: "punctuation", + text: ")", + }, + { + kind: "punctuation", + text: ":", + }, + { + kind: "space", + text: " ", + }, + { + kind: "keyword", + text: "void", + } + ], + tags, + }], + }); + } + it("for signature help, should provide a string for a working link in a comment", () => { + assertSignatureHelpJSDoc({ + command: protocol.CommandTypes.SignatureHelp, + displayPartsForJSDoc: false, + tags: [{ + name: "param", + text: "y - {@link C}" + }], + documentation: [{ + kind: "text", + text: "- " + }, { + kind: "link", + text: "{@link " + }, { + kind: "linkName", + target: { + file: "/a/someFile1.js", + start: { + line: 1, + offset: 1 + }, + end: { + line: 1, + offset: 12 + } + }, + text: "C" + }, { + kind: "link", + text: "}" + }], + }); + }); + it("for signature help, should provide display parts for a working link in a comment", () => { + const tags = [{ + name: "param", + text: [{ + kind: "parameterName", + text: "y" + }, { + kind: "space", + text: " " + }, { + kind: "text", + text: "- " + }, { + kind: "link", + text: "{@link " + }, { + kind: "linkName", + target: { + file: "/a/someFile1.js", + start: { + line: 1, + offset: 1 + }, + end: { + line: 1, + offset: 12 + } + }, + text: "C" + }, { + kind: "link", + text: "}" + }] + }]; + assertSignatureHelpJSDoc({ + command: protocol.CommandTypes.SignatureHelp, + displayPartsForJSDoc: true, + tags, + documentation: tags[0].text.slice(2) + }); + }); + it("for signature help-full, should provide a string for a working link in a comment", () => { + assertSignatureHelpJSDoc({ + command: protocol.CommandTypes.SignatureHelpFull, + displayPartsForJSDoc: false, + tags: [{ + name: "param", + text: "y - {@link C}" + }], + documentation: [{ + kind: "text", + text: "- " + }, { + kind: "link", + text: "{@link " + }, { + kind: "linkName", + target: { + fileName: "/a/someFile1.js", + textSpan: { + length: 11, + start: 0 + } + }, + text: "C" + }, { + kind: "link", + text: "}" + }], + }); + }); + it("for signature help-full, should provide display parts for a working link in a comment", () => { + const tags = [{ + name: "param", + text: [{ + kind: "parameterName", + text: "y" + }, { + kind: "space", + text: " " + }, { + kind: "text", + text: "- " + }, { + kind: "link", + text: "{@link " + }, { + kind: "linkName", + target: { + fileName: "/a/someFile1.js", + textSpan: { + length: 11, + start: 0 + } + }, + text: "C" + }, { + kind: "link", + text: "}" + }] + }]; + assertSignatureHelpJSDoc({ + command: protocol.CommandTypes.SignatureHelpFull, + displayPartsForJSDoc: true, + tags, + documentation: tags[0].text.slice(2), + }); + }); + + function assertCompletionsJSDoc(options: { + displayPartsForJSDoc: boolean, + command: protocol.CommandTypes, + tags: unknown[] + }) { + const linkInParamJSDoc: File = { + path: "/a/someFile1.js", + content: `class C { } +/** @param x - see {@link C} */ +function foo (x) { } +foo` + }; + const { command, displayPartsForJSDoc, tags } = options; + const session = createSession(createServerHost([linkInParamJSDoc, config])); + session.getProjectService().setHostConfiguration({ preferences: { displayPartsForJSDoc } }); + openFilesForSession([linkInParamJSDoc], session); + const indexOfFoo = linkInParamJSDoc.content.lastIndexOf("fo"); + const completions = session.executeCommandSeq({ + command: command as protocol.CommandTypes.CompletionDetails, + arguments: { + entryNames: ["foo"], + file: linkInParamJSDoc.path, + position: indexOfFoo, + } as protocol.CompletionDetailsRequestArgs + }).response; + assert.deepEqual(completions, [{ + codeActions: undefined, + displayParts: [{ + kind: "keyword", + text: "function", + }, { + kind: "space", + text: " ", + }, { + kind: "functionName", + text: "foo", + }, { + kind: "punctuation", + text: "(", + }, { + kind: "parameterName", + text: "x", + }, { + kind: "punctuation", + text: ":", + }, { + kind: "space", + text: " ", + }, { + kind: "keyword", + text: "any", + }, { + kind: "punctuation", + text: ")", + }, { + kind: "punctuation", + text: ":", + }, { + kind: "space", + text: " ", + }, { + kind: "keyword", + text: "void", + }], + documentation: [], + kind: "function", + kindModifiers: "", + name: "foo", + source: undefined, + sourceDisplay: undefined, + tags, + }]); + } + it("for completions, should provide display parts for a working link in a comment", () => { + assertCompletionsJSDoc({ + command: protocol.CommandTypes.CompletionDetails, + displayPartsForJSDoc: true, + tags: [{ + name: "param", + text: [{ + kind: "parameterName", + text: "x" + }, { + kind: "space", + text: " " + }, { + kind: "text", + text: "- see " + }, { + kind: "link", + text: "{@link " + }, { + kind: "linkName", + target: { + file: "/a/someFile1.js", + end: { + line: 1, + offset: 12, + }, + start: { + line: 1, + offset: 1, + } + }, + text: "C" + }, { + kind: "link", + text: "}" + }], + }], + }); + }); + it("for completions, should provide a string for a working link in a comment", () => { + assertCompletionsJSDoc({ + command: protocol.CommandTypes.CompletionDetails, + displayPartsForJSDoc: false, + tags: [{ + name: "param", + text: "x - see {@link C}", + }], + }); + }); + it("for completions-full, should provide display parts for a working link in a comment", () => { + assertCompletionsJSDoc({ + command: protocol.CommandTypes.CompletionDetailsFull, + displayPartsForJSDoc: true, + tags: [{ + name: "param", + text: [{ + kind: "parameterName", + text: "x" + }, { + kind: "space", + text: " " + }, { + kind: "text", + text: "- see " + }, { + kind: "link", + text: "{@link " + }, { + kind: "linkName", + target: { + fileName: "/a/someFile1.js", + textSpan: { + length: 11, + start: 0 + } + }, + text: "C" + }, { + kind: "link", + text: "}" + }], + }], + }); + }); + it("for completions-full, should provide a string for a working link in a comment", () => { + assertCompletionsJSDoc({ + command: protocol.CommandTypes.CompletionDetailsFull, + displayPartsForJSDoc: false, + tags: [{ + name: "param", + text: "x - see {@link C}", + }], + }); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/moduleSpecifierCache.ts b/src/testRunner/unittests/tsserver/moduleSpecifierCache.ts new file mode 100644 index 0000000000000..f109cab9d1f6e --- /dev/null +++ b/src/testRunner/unittests/tsserver/moduleSpecifierCache.ts @@ -0,0 +1,81 @@ +namespace ts.projectSystem { + const packageJson: File = { + path: "/package.json", + content: `{ "dependencies": { "mobx": "*" } }` + }; + const aTs: File = { + path: "/a.ts", + content: "export const foo = 0;", + }; + const bTs: File = { + path: "/b.ts", + content: "foo", + }; + const bSymlink: SymLink = { + path: "/b-link.ts", + symLink: "./b.ts", + }; + const tsconfig: File = { + path: "/tsconfig.json", + content: "{}", + }; + const ambientDeclaration: File = { + path: "/ambient.d.ts", + content: "declare module 'ambient' {}" + }; + const mobxDts: File = { + path: "/node_modules/mobx/index.d.ts", + content: "export declare function observable(): unknown;" + }; + + describe("unittests:: tsserver:: moduleSpecifierCache", () => { + it("caches importability within a file", () => { + const { moduleSpecifierCache } = setup(); + assert.isTrue(moduleSpecifierCache.get(bTs.path as Path, aTs.path as Path)); + }); + + it("does not invalidate the cache when new files are added", () => { + const { host, moduleSpecifierCache } = setup(); + host.writeFile("/src/a2.ts", aTs.content); + host.runQueuedTimeoutCallbacks(); + assert.isTrue(moduleSpecifierCache.get(bTs.path as Path, aTs.path as Path)); + }); + + it("invalidates the cache when symlinks are added or removed", () => { + const { host, moduleSpecifierCache } = setup(); + host.renameFile(bSymlink.path, "/b-link2.ts"); + host.runQueuedTimeoutCallbacks(); + assert.equal(moduleSpecifierCache.count(), 0); + }); + + it("invalidates the cache when package.json changes", () => { + const { host, moduleSpecifierCache } = setup(); + host.writeFile("/package.json", `{}`); + host.runQueuedTimeoutCallbacks(); + assert.isUndefined(moduleSpecifierCache.get(bTs.path as Path, aTs.path as Path)); + }); + }); + + function setup() { + const host = createServerHost([aTs, bTs, bSymlink, ambientDeclaration, tsconfig, packageJson, mobxDts]); + const session = createSession(host); + openFilesForSession([aTs, bTs], session); + const projectService = session.getProjectService(); + const project = configuredProjectAt(projectService, 0); + triggerCompletions(); + return { host, project, projectService, moduleSpecifierCache: project.getModuleSpecifierCache(), triggerCompletions }; + + function triggerCompletions() { + const requestLocation: protocol.FileLocationRequestArgs = { + file: bTs.path, + line: 1, + offset: 3, + }; + executeSessionRequest(session, protocol.CommandTypes.CompletionInfo, { + ...requestLocation, + includeExternalModuleExports: true, + prefix: "foo", + }); + } + } +} diff --git a/src/testRunner/unittests/tsserver/partialSemanticServer.ts b/src/testRunner/unittests/tsserver/partialSemanticServer.ts index 2c8b8ed14b068..f561f832a9fcb 100644 --- a/src/testRunner/unittests/tsserver/partialSemanticServer.ts +++ b/src/testRunner/unittests/tsserver/partialSemanticServer.ts @@ -1,5 +1,5 @@ namespace ts.projectSystem { - describe("unittests:: tsserver:: Semantic operations on PartialSemantic server", () => { + describe("unittests:: tsserver:: Semantic operations on partialSemanticServer", () => { function setup() { const file1: File = { path: `${tscWatch.projectRoot}/a.ts`, @@ -68,9 +68,13 @@ import { something } from "something"; hasAction: undefined, insertText: undefined, isPackageJsonImport: undefined, + isImportStatementCompletion: undefined, isRecommended: undefined, replacementSpan: undefined, - source: undefined + source: undefined, + data: undefined, + sourceDisplay: undefined, + isSnippet: undefined, }; } }); @@ -203,5 +207,20 @@ function fooB() { }` assert.isUndefined(project.getPackageJsonAutoImportProvider()); assert.deepEqual(project.getPackageJsonsForAutoImport(), emptyArray); }); + + it("should support go-to-definition on module specifiers", () => { + const { session, file1, file2 } = setup(); + openFilesForSession([file1], session); + const response = session.executeCommandSeq({ + command: protocol.CommandTypes.DefinitionAndBoundSpan, + arguments: protocolFileLocationFromSubstring(file1, `"./b"`) + }).response as protocol.DefinitionInfoAndBoundSpan; + assert.isDefined(response); + assert.deepEqual(response.definitions, [{ + file: file2.path, + start: { line: 1, offset: 1 }, + end: { line: 1, offset: 1 }, + }]); + }); }); } diff --git a/src/testRunner/unittests/tsserver/projectReferenceCompileOnSave.ts b/src/testRunner/unittests/tsserver/projectReferenceCompileOnSave.ts index 55847f2e22837..b818ce7d84a8e 100644 --- a/src/testRunner/unittests/tsserver/projectReferenceCompileOnSave.ts +++ b/src/testRunner/unittests/tsserver/projectReferenceCompileOnSave.ts @@ -33,194 +33,13 @@ fn2(); }) }; - interface VerifySingleScenarioWorker extends VerifySingleScenario { - withProject: boolean; - } - function verifySingleScenarioWorker({ - withProject, scenario, openFiles, requestArgs, change, expectedResult - }: VerifySingleScenarioWorker) { - it(scenario, () => { - const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( - createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) - ); - const session = createSession(host); - openFilesForSession(openFiles(), session); - const reqArgs = requestArgs(); - const { - expectedAffected, - expectedEmit: { expectedEmitSuccess, expectedFiles }, - expectedEmitOutput - } = expectedResult(withProject); - - if (change) { - session.executeCommandSeq({ - command: protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } - }); - const { file, insertString } = change(); - if (session.getProjectService().openFiles.has(file.path as Path)) { - const toLocation = protocolToLocation(file.content); - const location = toLocation(file.content.length); - session.executeCommandSeq({ - command: protocol.CommandTypes.Change, - arguments: { - file: file.path, - ...location, - endLine: location.line, - endOffset: location.offset, - insertString - } - }); - } - else { - host.writeFile(file.path, `${file.content}${insertString}`); - } - host.writtenFiles.clear(); - } - - const args = withProject ? reqArgs : { file: reqArgs.file }; - // Verify CompileOnSaveAffectedFileList - const actualAffectedFiles = session.executeCommandSeq({ - command: protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: args - }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; - assert.deepEqual(actualAffectedFiles, expectedAffected, "Affected files"); - - // Verify CompileOnSaveEmit - const actualEmit = session.executeCommandSeq({ - command: protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: args - }).response; - assert.deepEqual(actualEmit, expectedEmitSuccess, "Emit files"); - assert.equal(host.writtenFiles.size, expectedFiles.length); - for (const file of expectedFiles) { - assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); - assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); - } - - // Verify EmitOutput - const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ - command: protocol.CommandTypes.EmitOutput, - arguments: args - }).response as EmitOutput; - assert.deepEqual(actualEmitOutput, expectedEmitOutput, "Emit output"); - }); - } - - interface VerifySingleScenario { - scenario: string; - openFiles: () => readonly File[]; - requestArgs: () => protocol.FileRequestArgs; - skipWithoutProject?: boolean; - change?: () => SingleScenarioChange; - expectedResult: GetSingleScenarioResult; - } - function verifySingleScenario(scenario: VerifySingleScenario) { - if (!scenario.skipWithoutProject) { - describe("without specifying project file", () => { - verifySingleScenarioWorker({ - withProject: false, - ...scenario - }); - }); - } - describe("with specifying project file", () => { - verifySingleScenarioWorker({ - withProject: true, - ...scenario - }); - }); - } - - interface SingleScenarioExpectedEmit { - expectedEmitSuccess: boolean; - expectedFiles: readonly File[]; - } - interface SingleScenarioResult { - expectedAffected: protocol.CompileOnSaveAffectedFileListSingleProject[]; - expectedEmit: SingleScenarioExpectedEmit; - expectedEmitOutput: EmitOutput; - } - type GetSingleScenarioResult = (withProject: boolean) => SingleScenarioResult; - interface SingleScenarioChange { - file: File; - insertString: string; - } - interface ScenarioDetails { - scenarioName: string; - requestArgs: () => protocol.FileRequestArgs; - skipWithoutProject?: boolean; - initial: GetSingleScenarioResult; - localChangeToDependency: GetSingleScenarioResult; - localChangeToUsage: GetSingleScenarioResult; - changeToDependency: GetSingleScenarioResult; - changeToUsage: GetSingleScenarioResult; - } - interface VerifyScenario { - openFiles: () => readonly File[]; - scenarios: readonly ScenarioDetails[]; - } - const localChange = "function fn3() { }"; const change = `export ${localChange}`; const changeJs = `function fn3() { } exports.fn3 = fn3;`; const changeDts = "export declare function fn3(): void;"; - function verifyScenario({ openFiles, scenarios }: VerifyScenario) { - for (const { - scenarioName, requestArgs, skipWithoutProject, initial, - localChangeToDependency, localChangeToUsage, - changeToDependency, changeToUsage - } of scenarios) { - describe(scenarioName, () => { - verifySingleScenario({ - scenario: "with initial file open", - openFiles, - requestArgs, - skipWithoutProject, - expectedResult: initial - }); - - verifySingleScenario({ - scenario: "with local change to dependency", - openFiles, - requestArgs, - skipWithoutProject, - change: () => ({ file: dependencyTs, insertString: localChange }), - expectedResult: localChangeToDependency - }); - - verifySingleScenario({ - scenario: "with local change to usage", - openFiles, - requestArgs, - skipWithoutProject, - change: () => ({ file: usageTs, insertString: localChange }), - expectedResult: localChangeToUsage - }); - - verifySingleScenario({ - scenario: "with change to dependency", - openFiles, - requestArgs, - skipWithoutProject, - change: () => ({ file: dependencyTs, insertString: change }), - expectedResult: changeToDependency - }); - - verifySingleScenario({ - scenario: "with change to usage", - openFiles, - requestArgs, - skipWithoutProject, - change: () => ({ file: usageTs, insertString: change }), - expectedResult: changeToUsage - }); - }); - } - } - function expectedAffectedFiles(config: File, fileNames: File[]): protocol.CompileOnSaveAffectedFileListSingleProject { + function expectedAffectedFiles(config: File, fileNames: readonly File[]): protocol.CompileOnSaveAffectedFileListSingleProject { return { projectFileName: config.path, fileNames: fileNames.map(f => f.path), @@ -228,24 +47,21 @@ exports.fn3 = fn3;`; }; } - function expectedUsageEmit(appendJsText?: string): SingleScenarioExpectedEmit { + function expectedUsageEmitFiles(appendJsText?: string): readonly File[] { const appendJs = appendJsText ? `${appendJsText} ` : ""; - return { - expectedEmitSuccess: true, - expectedFiles: [{ - path: `${usageLocation}/usage.js`, - content: `"use strict"; + return [{ + path: `${usageLocation}/usage.js`, + content: `"use strict"; exports.__esModule = true;${appendJsText === changeJs ? "\nexports.fn3 = void 0;" : ""} var fns_1 = require("../decls/fns"); fns_1.fn1(); fns_1.fn2(); ${appendJs}` - }] - }; + }]; } - function expectedEmitOutput({ expectedFiles }: SingleScenarioExpectedEmit): EmitOutput { + function expectedEmitOutput(expectedFiles: readonly File[]): EmitOutput { return { outputFiles: expectedFiles.map(({ path, content }) => ({ name: path, @@ -257,17 +73,6 @@ ${appendJs}` }; } - function expectedUsageEmitOutput(appendJsText?: string): EmitOutput { - return expectedEmitOutput(expectedUsageEmit(appendJsText)); - } - - function noEmit(): SingleScenarioExpectedEmit { - return { - expectedEmitSuccess: false, - expectedFiles: emptyArray - }; - } - function noEmitOutput(): EmitOutput { return { emitSkipped: true, @@ -276,17 +81,15 @@ ${appendJs}` }; } - function expectedDependencyEmit(appendJsText?: string, appendDtsText?: string): SingleScenarioExpectedEmit { + function expectedDependencyEmitFiles(appendJsText?: string, appendDtsText?: string): readonly File[] { const appendJs = appendJsText ? `${appendJsText} ` : ""; const appendDts = appendDtsText ? `${appendDtsText} ` : ""; - return { - expectedEmitSuccess: true, - expectedFiles: [ - { - path: `${dependecyLocation}/fns.js`, - content: `"use strict"; + return [ + { + path: `${dependecyLocation}/fns.js`, + content: `"use strict"; exports.__esModule = true; ${appendJsText === changeJs ? "exports.fn3 = " : ""}exports.fn2 = exports.fn1 = void 0; function fn1() { } @@ -294,118 +97,2142 @@ exports.fn1 = fn1; function fn2() { } exports.fn2 = fn2; ${appendJs}` - }, - { - path: `${tscWatch.projectRoot}/decls/fns.d.ts`, - content: `export declare function fn1(): void; + }, + { + path: `${tscWatch.projectRoot}/decls/fns.d.ts`, + content: `export declare function fn1(): void; export declare function fn2(): void; ${appendDts}` - } - ] - }; + } + ]; } - function expectedDependencyEmitOutput(appendJsText?: string, appendDtsText?: string): EmitOutput { - return expectedEmitOutput(expectedDependencyEmit(appendJsText, appendDtsText)); - } + describe("when dependency project is not open", () => { + describe("Of usageTs", () => { + it("with initial file open, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); - function scenarioDetailsOfUsage(isDependencyOpen?: boolean): ScenarioDetails[] { - return [ - { - scenarioName: "Of usageTs", - requestArgs: () => ({ file: usageTs.path, projectFileName: usageConfig.path }), - initial: () => initialUsageTs(), - // no change to usage so same as initial only usage file - localChangeToDependency: () => initialUsageTs(), - localChangeToUsage: () => initialUsageTs(localChange), - changeToDependency: () => initialUsageTs(), - changeToUsage: () => initialUsageTs(changeJs) - }, - { - scenarioName: "Of dependencyTs in usage project", - requestArgs: () => ({ file: dependencyTs.path, projectFileName: usageConfig.path }), - skipWithoutProject: !!isDependencyOpen, - initial: () => initialDependencyTs(), - localChangeToDependency: () => initialDependencyTs(/*noUsageFiles*/ true), - localChangeToUsage: () => initialDependencyTs(/*noUsageFiles*/ true), - changeToDependency: () => initialDependencyTs(), - changeToUsage: () => initialDependencyTs(/*noUsageFiles*/ true) - } - ]; + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with initial file open, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); - function initialUsageTs(jsText?: string) { - return { - expectedAffected: [ + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ expectedAffectedFiles(usageConfig, [usageTs]) - ], - expectedEmit: expectedUsageEmit(jsText), - expectedEmitOutput: expectedUsageEmitOutput(jsText) - }; - } - - function initialDependencyTs(noUsageFiles?: true) { - return { - expectedAffected: [ - expectedAffectedFiles(usageConfig, noUsageFiles ? [] : [usageTs]) - ], - expectedEmit: noEmit(), - expectedEmitOutput: noEmitOutput() - }; - } - } + ], "Affected files"); - function scenarioDetailsOfDependencyWhenOpen(): ScenarioDetails { - return { - scenarioName: "Of dependencyTs", - requestArgs: () => ({ file: dependencyTs.path, projectFileName: dependencyConfig.path }), - initial, - localChangeToDependency: withProject => ({ - expectedAffected: withProject ? - [ - expectedAffectedFiles(dependencyConfig, [dependencyTs]) - ] : - [ - expectedAffectedFiles(usageConfig, []), - expectedAffectedFiles(dependencyConfig, [dependencyTs]) - ], - expectedEmit: expectedDependencyEmit(localChange), - expectedEmitOutput: expectedDependencyEmitOutput(localChange) - }), - localChangeToUsage: withProject => initial(withProject, /*noUsageFiles*/ true), - changeToDependency: withProject => initial(withProject, /*noUsageFiles*/ undefined, changeJs, changeDts), - changeToUsage: withProject => initial(withProject, /*noUsageFiles*/ true) - }; + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } - function initial(withProject: boolean, noUsageFiles?: true, appendJs?: string, appendDts?: string): SingleScenarioResult { - return { - expectedAffected: withProject ? - [ - expectedAffectedFiles(dependencyConfig, [dependencyTs]) - ] : - [ - expectedAffectedFiles(usageConfig, noUsageFiles ? [] : [usageTs]), - expectedAffectedFiles(dependencyConfig, [dependencyTs]) - ], - expectedEmit: expectedDependencyEmit(appendJs, appendDts), - expectedEmitOutput: expectedDependencyEmitOutput(appendJs, appendDts) - }; - } - } + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with local change to dependency, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); - describe("when dependency project is not open", () => { - verifyScenario({ - openFiles: () => [usageTs], - scenarios: scenarioDetailsOfUsage() + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + host.writeFile(dependencyTs.path, `${dependencyTs.content}${localChange}`); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with local change to dependency, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + host.writeFile(dependencyTs.path, `${dependencyTs.content}${localChange}`); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with local change to usage, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(usageTs.content); + const location = toLocation(usageTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: usageTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: localChange + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(localChange); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with local change to usage, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(usageTs.content); + const location = toLocation(usageTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: usageTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: localChange + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(localChange); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with change to dependency, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + host.writeFile(dependencyTs.path, `${dependencyTs.content}${change}`); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with change to dependency, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + host.writeFile(dependencyTs.path, `${dependencyTs.content}${change}`); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with change to usage, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(usageTs.content); + const location = toLocation(usageTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: usageTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: change + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(changeJs); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with change to usage, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(usageTs.content); + const location = toLocation(usageTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: usageTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: change + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(changeJs); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); }); - }); - describe("when the depedency file is open", () => { - verifyScenario({ - openFiles: () => [usageTs, dependencyTs], - scenarios: [ - ...scenarioDetailsOfUsage(/*isDependencyOpen*/ true), - scenarioDetailsOfDependencyWhenOpen(), - ] + describe("Of dependencyTs in usage project", () => { + it("with initial file open, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path } + }).response; + assert.isFalse(actualEmit, "Emit files"); + assert.equal(host.writtenFiles.size, 0); + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); + }); + it("with initial file open, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response; + assert.isFalse(actualEmit, "Emit files"); + assert.equal(host.writtenFiles.size, 0); + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); + }); + it("with local change to dependency, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + host.writeFile(dependencyTs.path, `${dependencyTs.content}${localChange}`); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, emptyArray) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path } + }).response; + assert.isFalse(actualEmit, "Emit files"); + assert.equal(host.writtenFiles.size, 0); + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); + }); + it("with local change to dependency, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + host.writeFile(dependencyTs.path, `${dependencyTs.content}${localChange}`); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, emptyArray) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response; + assert.isFalse(actualEmit, "Emit files"); + assert.equal(host.writtenFiles.size, 0); + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); + }); + it("with local change to usage, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(usageTs.content); + const location = toLocation(usageTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: usageTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: localChange + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, emptyArray) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path } + }).response; + assert.isFalse(actualEmit, "Emit files"); + assert.equal(host.writtenFiles.size, 0); + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); + }); + it("with local change to usage, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(usageTs.content); + const location = toLocation(usageTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: usageTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: localChange + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, emptyArray) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response; + assert.isFalse(actualEmit, "Emit files"); + assert.equal(host.writtenFiles.size, 0); + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); + }); + it("with change to dependency, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + host.writeFile(dependencyTs.path, `${dependencyTs.content}${change}`); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path } + }).response; + assert.isFalse(actualEmit, "Emit files"); + assert.equal(host.writtenFiles.size, 0); + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); + }); + it("with change to dependency, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + host.writeFile(dependencyTs.path, `${dependencyTs.content}${change}`); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response; + assert.isFalse(actualEmit, "Emit files"); + assert.equal(host.writtenFiles.size, 0); + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); + }); + it("with change to usage, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(usageTs.content); + const location = toLocation(usageTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: usageTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: change + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, emptyArray) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path } + }).response; + assert.isFalse(actualEmit, "Emit files"); + assert.equal(host.writtenFiles.size, 0); + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); + }); + it("with change to usage, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(usageTs.content); + const location = toLocation(usageTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: usageTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: change + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, emptyArray) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response; + assert.isFalse(actualEmit, "Emit files"); + assert.equal(host.writtenFiles.size, 0); + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); + }); + }); + }); + + describe("when the depedency file is open", () => { + describe("Of usageTs", () => { + it("with initial file open, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with initial file open, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with local change to dependency, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(dependencyTs.content); + const location = toLocation(dependencyTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: dependencyTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: localChange + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with local change to dependency, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(dependencyTs.content); + const location = toLocation(dependencyTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: dependencyTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: localChange + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with local change to usage, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(usageTs.content); + const location = toLocation(usageTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: usageTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: localChange + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(localChange); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with local change to usage, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(usageTs.content); + const location = toLocation(usageTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: usageTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: localChange + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(localChange); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with change to dependency, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(dependencyTs.content); + const location = toLocation(dependencyTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: dependencyTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: change + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with change to dependency, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(dependencyTs.content); + const location = toLocation(dependencyTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: dependencyTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: change + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with change to usage, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(usageTs.content); + const location = toLocation(usageTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: usageTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: change + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(changeJs); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with change to usage, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(usageTs.content); + const location = toLocation(usageTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: usageTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: change + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedUsageEmitFiles(changeJs); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: usageTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + }); + + describe("Of dependencyTs in usage project", () => { + it("with initial file open, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response; + assert.isFalse(actualEmit, "Emit files"); + assert.equal(host.writtenFiles.size, 0); + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); + }); + it("with local change to dependency, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(dependencyTs.content); + const location = toLocation(dependencyTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: dependencyTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: localChange + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, emptyArray) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response; + assert.isFalse(actualEmit, "Emit files"); + assert.equal(host.writtenFiles.size, 0); + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); + }); + it("with local change to usage, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(usageTs.content); + const location = toLocation(usageTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: usageTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: localChange + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, emptyArray) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response; + assert.isFalse(actualEmit, "Emit files"); + assert.equal(host.writtenFiles.size, 0); + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); + }); + it("with change to dependency, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(dependencyTs.content); + const location = toLocation(dependencyTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: dependencyTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: change + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response; + assert.isFalse(actualEmit, "Emit files"); + assert.equal(host.writtenFiles.size, 0); + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); + }); + it("with change to usage, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(usageTs.content); + const location = toLocation(usageTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: usageTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: change + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, emptyArray) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response; + assert.isFalse(actualEmit, "Emit files"); + assert.equal(host.writtenFiles.size, 0); + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, noEmitOutput(), "Emit output"); + }); + }); + + describe("Of dependencyTs", () => { + it("with initial file open, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]), + expectedAffectedFiles(dependencyConfig, [dependencyTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedDependencyEmitFiles(); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with initial file open, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(dependencyConfig, [dependencyTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedDependencyEmitFiles(); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with local change to dependency, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(dependencyTs.content); + const location = toLocation(dependencyTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: dependencyTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: localChange + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, emptyArray), + expectedAffectedFiles(dependencyConfig, [dependencyTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedDependencyEmitFiles(localChange); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with local change to dependency, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(dependencyTs.content); + const location = toLocation(dependencyTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: dependencyTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: localChange + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(dependencyConfig, [dependencyTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedDependencyEmitFiles(localChange); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with local change to usage, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(usageTs.content); + const location = toLocation(usageTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: usageTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: localChange + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, emptyArray), + expectedAffectedFiles(dependencyConfig, [dependencyTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedDependencyEmitFiles(); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with local change to usage, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(usageTs.content); + const location = toLocation(usageTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: usageTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: localChange + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(dependencyConfig, [dependencyTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedDependencyEmitFiles(); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with change to dependency, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(dependencyTs.content); + const location = toLocation(dependencyTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: dependencyTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: change + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, [usageTs]), + expectedAffectedFiles(dependencyConfig, [dependencyTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedDependencyEmitFiles(changeJs, changeDts); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with change to dependency, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(dependencyTs.content); + const location = toLocation(dependencyTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: dependencyTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: change + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(dependencyConfig, [dependencyTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedDependencyEmitFiles(changeJs, changeDts); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with change to usage, without specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(usageTs.content); + const location = toLocation(usageTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: usageTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: change + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(usageConfig, emptyArray), + expectedAffectedFiles(dependencyConfig, [dependencyTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedDependencyEmitFiles(); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); + it("with change to usage, with specifying project file", () => { + const host = TestFSWithWatch.changeToHostTrackingWrittenFiles( + createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile]) + ); + const session = createSession(host); + openFilesForSession([usageTs, dependencyTs], session); + + session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path } + }); + const toLocation = protocolToLocation(usageTs.content); + const location = toLocation(usageTs.content.length); + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: usageTs.path, + ...location, + endLine: location.line, + endOffset: location.offset, + insertString: change + } + }); + host.writtenFiles.clear(); + + // Verify CompileOnSaveAffectedFileList + const actualAffectedFiles = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveAffectedFileList, + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + }).response as protocol.CompileOnSaveAffectedFileListSingleProject[]; + assert.deepEqual(actualAffectedFiles, [ + expectedAffectedFiles(dependencyConfig, [dependencyTs]) + ], "Affected files"); + + // Verify CompileOnSaveEmit + const actualEmit = session.executeCommandSeq({ + command: protocol.CommandTypes.CompileOnSaveEmitFile, + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + }).response; + assert.isTrue(actualEmit, "Emit files"); + const expectedFiles = expectedDependencyEmitFiles(); + assert.equal(host.writtenFiles.size, expectedFiles.length); + for (const file of expectedFiles) { + assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`); + assert.isTrue(host.writtenFiles.has(file.path as Path), `${file.path} is newly written`); + } + + // Verify EmitOutput + const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq({ + command: protocol.CommandTypes.EmitOutput, + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + }).response as EmitOutput; + assert.deepEqual(actualEmitOutput, expectedEmitOutput(expectedFiles), "Emit output"); + }); }); }); }); @@ -486,4 +2313,4 @@ ${appendDts}` assert.equal(host.readFile(sourceJs), expectedSiblingJs); }); }); -} +} \ No newline at end of file diff --git a/src/testRunner/unittests/tsserver/projectReferences.ts b/src/testRunner/unittests/tsserver/projectReferences.ts index 103143390fc7b..1645033cd58aa 100644 --- a/src/testRunner/unittests/tsserver/projectReferences.ts +++ b/src/testRunner/unittests/tsserver/projectReferences.ts @@ -1,12 +1,12 @@ namespace ts.projectSystem { - describe("unittests:: tsserver:: with project references and tsbuild", () => { - function createHost(files: readonly TestFSWithWatch.FileOrFolderOrSymLink[], rootNames: readonly string[]) { - const host = createServerHost(files); - // ts build should succeed - tscWatch.ensureErrorFreeBuild(host, rootNames); - return host; - } + export function createHostWithSolutionBuild(files: readonly TestFSWithWatch.FileOrFolderOrSymLink[], rootNames: readonly string[]) { + const host = createServerHost(files); + // ts build should succeed + tscWatch.ensureErrorFreeBuild(host, rootNames); + return host; + } + describe("unittests:: tsserver:: with project references and tsbuild", () => { describe("with container project", () => { function getProjectFiles(project: string): [File, File] { return [ @@ -23,7 +23,7 @@ namespace ts.projectSystem { const files = [libFile, ...containerLib, ...containerExec, ...containerCompositeExec, containerConfig]; it("does not error on container only project", () => { - const host = createHost(files, [containerConfig.path]); + const host = createHostWithSolutionBuild(files, [containerConfig.path]); // Open external project for the folder const session = createSession(host); @@ -60,7 +60,7 @@ namespace ts.projectSystem { }); it("can successfully find references with --out options", () => { - const host = createHost(files, [containerConfig.path]); + const host = createHostWithSolutionBuild(files, [containerConfig.path]); const session = createSession(host); openFilesForSession([containerCompositeExec[1]], session); const service = session.getProjectService(); @@ -101,7 +101,7 @@ namespace ts.projectSystem { path: `/user/username/projects/temp/temp.ts`, content: "let x = 10" }; - const host = createHost(files.concat([tempFile]), [containerConfig.path]); + const host = createHostWithSolutionBuild(files.concat([tempFile]), [containerConfig.path]); const session = createSession(host); openFilesForSession([containerCompositeExec[1]], session); const service = session.getProjectService(); @@ -140,1105 +140,6 @@ namespace ts.projectSystem { }); }); - describe("with main and depedency project", () => { - const dependecyLocation = `${tscWatch.projectRoot}/dependency`; - const dependecyDeclsLocation = `${tscWatch.projectRoot}/decls`; - const mainLocation = `${tscWatch.projectRoot}/main`; - const dependencyTs: File = { - path: `${dependecyLocation}/FnS.ts`, - content: `export function fn1() { } -export function fn2() { } -export function fn3() { } -export function fn4() { } -export function fn5() { } -` - }; - const dependencyTsPath = dependencyTs.path.toLowerCase(); - const dependencyConfig: File = { - path: `${dependecyLocation}/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { composite: true, declarationMap: true, declarationDir: "../decls" } }) - }; - - const mainTs: File = { - path: `${mainLocation}/main.ts`, - content: `import { - fn1, - fn2, - fn3, - fn4, - fn5 -} from '../decls/fns' - -fn1(); -fn2(); -fn3(); -fn4(); -fn5(); -` - }; - const mainConfig: File = { - path: `${mainLocation}/tsconfig.json`, - content: JSON.stringify({ - compilerOptions: { composite: true, declarationMap: true }, - references: [{ path: "../dependency" }] - }) - }; - - const randomFile: File = { - path: `${tscWatch.projectRoot}/random/random.ts`, - content: "let a = 10;" - }; - const randomConfig: File = { - path: `${tscWatch.projectRoot}/random/tsconfig.json`, - content: "{}" - }; - const dtsLocation = `${dependecyDeclsLocation}/FnS.d.ts`; - const dtsPath = dtsLocation.toLowerCase() as Path; - const dtsMapLocation = `${dependecyDeclsLocation}/FnS.d.ts.map`; - const dtsMapPath = dtsMapLocation.toLowerCase() as Path; - - const files = [dependencyTs, dependencyConfig, mainTs, mainConfig, libFile, randomFile, randomConfig]; - - function verifyScriptInfos(session: TestSession, host: TestServerHost, openInfos: readonly string[], closedInfos: readonly string[], otherWatchedFiles: readonly string[], additionalInfo: string) { - checkScriptInfos(session.getProjectService(), openInfos.concat(closedInfos), additionalInfo); - checkWatchedFiles(host, closedInfos.concat(otherWatchedFiles).map(f => f.toLowerCase()), additionalInfo); - } - - function verifyInfosWithRandom(session: TestSession, host: TestServerHost, openInfos: readonly string[], closedInfos: readonly string[], otherWatchedFiles: readonly string[], reqName: string) { - verifyScriptInfos(session, host, openInfos.concat(randomFile.path), closedInfos, otherWatchedFiles.concat(randomConfig.path), reqName); - } - - function verifyOnlyRandomInfos(session: TestSession, host: TestServerHost) { - verifyScriptInfos(session, host, [randomFile.path], [libFile.path], [randomConfig.path], "Random"); - } - - function declarationSpan(fn: number): protocol.TextSpanWithContext { - return { - start: { line: fn, offset: 17 }, - end: { line: fn, offset: 20 }, - contextStart: { line: fn, offset: 1 }, - contextEnd: { line: fn, offset: 26 } - }; - } - function importSpan(fn: number): protocol.TextSpanWithContext { - return { - start: { line: fn + 1, offset: 5 }, - end: { line: fn + 1, offset: 8 }, - contextStart: { line: 1, offset: 1 }, - contextEnd: { line: 7, offset: 22 } - }; - } - function usageSpan(fn: number): protocol.TextSpan { - return { start: { line: fn + 8, offset: 1 }, end: { line: fn + 8, offset: 4 } }; - } - - function goToDefFromMainTs(fn: number): Action { - const textSpan = usageSpan(fn); - const definition: protocol.FileSpan = { file: dependencyTs.path, ...declarationSpan(fn) }; - return { - reqName: "goToDef", - request: { - command: protocol.CommandTypes.DefinitionAndBoundSpan, - arguments: { file: mainTs.path, ...textSpan.start } - }, - expectedResponse: { - // To dependency - definitions: [definition], - textSpan - } - }; - } - - function goToDefFromMainTsWithNoMap(fn: number): Action { - const textSpan = usageSpan(fn); - const definition = declarationSpan(fn); - const declareSpaceLength = "declare ".length; - return { - reqName: "goToDef", - request: { - command: protocol.CommandTypes.DefinitionAndBoundSpan, - arguments: { file: mainTs.path, ...textSpan.start } - }, - expectedResponse: { - // To the dts - definitions: [{ - file: dtsPath, - start: { line: fn, offset: definition.start.offset + declareSpaceLength }, - end: { line: fn, offset: definition.end.offset + declareSpaceLength }, - contextStart: { line: fn, offset: 1 }, - contextEnd: { line: fn, offset: 37 } - }], - textSpan - } - }; - } - - function goToDefFromMainTsWithNoDts(fn: number): Action { - const textSpan = usageSpan(fn); - return { - reqName: "goToDef", - request: { - command: protocol.CommandTypes.DefinitionAndBoundSpan, - arguments: { file: mainTs.path, ...textSpan.start } - }, - expectedResponse: { - // To import declaration - definitions: [{ file: mainTs.path, ...importSpan(fn) }], - textSpan - } - }; - } - - function goToDefFromMainTsWithDependencyChange(fn: number): Action { - const textSpan = usageSpan(fn); - return { - reqName: "goToDef", - request: { - command: protocol.CommandTypes.DefinitionAndBoundSpan, - arguments: { file: mainTs.path, ...textSpan.start } - }, - expectedResponse: { - // Definition on fn + 1 line - definitions: [{ file: dependencyTs.path, ...declarationSpan(fn + 1) }], - textSpan - } - }; - } - - function goToDefFromMainTsProjectInfoVerifier(withRefs: boolean): ProjectInfoVerifier { - return { - openFile: mainTs, - openFileLastLine: 14, - configFile: mainConfig, - expectedProjectActualFiles: withRefs ? - [mainTs.path, libFile.path, mainConfig.path, dependencyTs.path] : - [mainTs.path, libFile.path, mainConfig.path, dtsPath] - }; - } - - function renameFromDependencyTs(fn: number): Action { - const defSpan = declarationSpan(fn); - const { contextStart: _, contextEnd: _1, ...triggerSpan } = defSpan; - return { - reqName: "rename", - request: { - command: protocol.CommandTypes.Rename, - arguments: { file: dependencyTs.path, ...triggerSpan.start } - }, - expectedResponse: { - info: { - canRename: true, - fileToRename: undefined, - displayName: `fn${fn}`, - fullDisplayName: `"${dependecyLocation}/FnS".fn${fn}`, - kind: ScriptElementKind.functionElement, - kindModifiers: "export", - triggerSpan - }, - locs: [ - { file: dependencyTs.path, locs: [defSpan] } - ] - } - }; - } - - function renameFromDependencyTsWithDependencyChange(fn: number): Action { - const { expectedResponse: { info, locs }, ...rest } = renameFromDependencyTs(fn + 1); - - return { - ...rest, - expectedResponse: { - info: { - ...info as protocol.RenameInfoSuccess, - displayName: `fn${fn}`, - fullDisplayName: `"${dependecyLocation}/FnS".fn${fn}`, - }, - locs - } - }; - } - - function renameFromDependencyTsProjectInfoVerifier(): ProjectInfoVerifier { - return { - openFile: dependencyTs, - openFileLastLine: 6, - configFile: dependencyConfig, - expectedProjectActualFiles: [dependencyTs.path, libFile.path, dependencyConfig.path] - }; - } - - function renameFromDependencyTsWithBothProjectsOpen(fn: number): Action { - const { reqName, request, expectedResponse } = renameFromDependencyTs(fn); - const { info, locs } = expectedResponse; - return { - reqName, - request, - expectedResponse: { - info, - locs: [ - locs[0], - { - file: mainTs.path, - locs: [ - importSpan(fn), - usageSpan(fn) - ] - } - ] - } - }; - } - - function renameFromDependencyTsWithBothProjectsOpenWithDependencyChange(fn: number): Action { - const { reqName, request, expectedResponse, } = renameFromDependencyTsWithDependencyChange(fn); - const { info, locs } = expectedResponse; - return { - reqName, - request, - expectedResponse: { - info, - locs: [ - locs[0], - { - file: mainTs.path, - locs: [ - importSpan(fn), - usageSpan(fn) - ] - } - ] - } - }; - } - - function removePath(array: readonly string[], ...delPaths: string[]) { - return array.filter(a => { - const aLower = a.toLowerCase(); - return delPaths.every(dPath => dPath !== aLower); - }); - } - - interface Action { - reqName: string; - request: Partial; - expectedResponse: Response; - } - interface ActionInfo { - action: (fn: number) => Action; - closedInfos: readonly string[]; - otherWatchedFiles: readonly string[]; - expectsDts: boolean; - expectsMap: boolean; - freshMapInfo?: boolean; - freshDocumentMapper?: boolean; - skipDtsMapCheck?: boolean; - } - type ActionKey = keyof ActionInfoVerifier; - type ActionInfoGetterFn = () => ActionInfo; - type ActionInfoSpreader = [ - ActionKey, // Key to get initial value and pass this value to spread function - (actionInfo: ActionInfo) => Partial> - ]; - type ActionInfoGetter = ActionInfoGetterFn | ActionKey | ActionInfoSpreader; - interface ProjectInfoVerifier { - openFile: File; - openFileLastLine: number; - configFile: File; - expectedProjectActualFiles: readonly string[]; - } - interface ActionInfoVerifier { - main: ActionInfoGetter; - change: ActionInfoGetter; - dtsChange: ActionInfoGetter; - mapChange: ActionInfoGetter; - noMap: ActionInfoGetter; - mapFileCreated: ActionInfoGetter; - mapFileDeleted: ActionInfoGetter; - noDts: ActionInfoGetter; - dtsFileCreated: ActionInfoGetter; - dtsFileDeleted: ActionInfoGetter; - dependencyChange: ActionInfoGetter; - noBuild: ActionInfoGetter; - } - interface DocumentPositionMapperVerifier extends ProjectInfoVerifier, ActionInfoVerifier { - } - - interface VerifierAndWithRefs { - withRefs: boolean; - disableSourceOfProjectReferenceRedirect?: true; - verifier: (withRefs: boolean, disableSourceOfProjectReferenceRedirect?: true) => readonly DocumentPositionMapperVerifier[]; - } - - function openFiles(verifiers: readonly DocumentPositionMapperVerifier[]) { - return verifiers.map(v => v.openFile); - } - interface OpenTsFile extends VerifierAndWithRefs { - onHostCreate?: (host: TestServerHost) => void; - } - function openTsFile({ withRefs, disableSourceOfProjectReferenceRedirect, verifier, onHostCreate }: OpenTsFile) { - const host = createHost(files, [mainConfig.path]); - if (!withRefs) { - // Erase project reference - host.writeFile(mainConfig.path, JSON.stringify({ - compilerOptions: { composite: true, declarationMap: true } - })); - } - else if (disableSourceOfProjectReferenceRedirect) { - // Erase project reference - host.writeFile(mainConfig.path, JSON.stringify({ - compilerOptions: { - composite: true, - declarationMap: true, - disableSourceOfProjectReferenceRedirect: !!disableSourceOfProjectReferenceRedirect - }, - references: [{ path: "../dependency" }] - })); - } - if (onHostCreate) { - onHostCreate(host); - } - const session = createSession(host); - const verifiers = verifier(withRefs && !disableSourceOfProjectReferenceRedirect, disableSourceOfProjectReferenceRedirect); - openFilesForSession([...openFiles(verifiers), randomFile], session); - return { host, session, verifiers }; - } - - function checkProject(session: TestSession, verifiers: readonly DocumentPositionMapperVerifier[], noDts?: true) { - const service = session.getProjectService(); - checkNumberOfProjects(service, { configuredProjects: 1 + verifiers.length }); - verifiers.forEach(({ configFile, expectedProjectActualFiles }) => { - checkProjectActualFiles( - service.configuredProjects.get(configFile.path.toLowerCase())!, - noDts ? - expectedProjectActualFiles.filter(f => f.toLowerCase() !== dtsPath) : - expectedProjectActualFiles - ); - }); - } - - function firstAction(session: TestSession, verifiers: readonly DocumentPositionMapperVerifier[]) { - for (const { action } of getActionInfo(verifiers, "main")) { - const { request } = action(1); - session.executeCommandSeq(request); - } - } - - function verifyAction(session: TestSession, { reqName, request, expectedResponse }: Action) { - const { response } = session.executeCommandSeq(request); - assert.deepEqual(response, expectedResponse, `Failed Request: ${reqName}`); - } - - function verifyScriptInfoPresence(session: TestSession, path: string, expectedToBePresent: boolean, reqName: string) { - const info = session.getProjectService().filenameToScriptInfo.get(path); - if (expectedToBePresent) { - assert.isDefined(info, `${reqName}:: ${path} expected to be present`); - } - else { - assert.isUndefined(info, `${reqName}:: ${path} expected to be not present`); - } - return info; - } - - interface VerifyDocumentPositionMapper { - session: TestSession; - dependencyMap: server.ScriptInfo | undefined; - documentPositionMapper: server.ScriptInfo["documentPositionMapper"]; - equal: boolean; - debugInfo: string; - } - function verifyDocumentPositionMapper({ session, dependencyMap, documentPositionMapper, equal, debugInfo }: VerifyDocumentPositionMapper) { - assert.strictEqual(session.getProjectService().filenameToScriptInfo.get(dtsMapPath), dependencyMap, debugInfo); - if (dependencyMap) { - if (equal) { - assert.strictEqual(dependencyMap.documentPositionMapper, documentPositionMapper, debugInfo); - } - else { - assert.notStrictEqual(dependencyMap.documentPositionMapper, documentPositionMapper, debugInfo); - } - } - } - - function getActionInfoOfVerfier(verifier: DocumentPositionMapperVerifier, actionKey: ActionKey): ActionInfo { - const actionInfoGetter = verifier[actionKey]; - if (isString(actionInfoGetter)) { - return getActionInfoOfVerfier(verifier, actionInfoGetter); - } - - if (isArray(actionInfoGetter)) { - const initialValue = getActionInfoOfVerfier(verifier, actionInfoGetter[0]); - return { - ...initialValue, - ...actionInfoGetter[1](initialValue) - }; - } - - return actionInfoGetter(); - } - - function getActionInfo(verifiers: readonly DocumentPositionMapperVerifier[], actionKey: ActionKey): ActionInfo[] { - return verifiers.map(v => getActionInfoOfVerfier(v, actionKey)); - } - - interface VerifyAllFnAction { - session: TestSession; - host: TestServerHost; - verifiers: readonly DocumentPositionMapperVerifier[]; - actionKey: ActionKey; - sourceMapPath?: server.ScriptInfo["sourceMapFilePath"]; - dependencyMap?: server.ScriptInfo | undefined; - documentPositionMapper?: server.ScriptInfo["documentPositionMapper"]; - } - interface VerifyAllFnActionResult { - actionInfos: readonly ActionInfo[]; - actionKey: ActionKey; - dependencyMap: server.ScriptInfo | undefined; - documentPositionMapper: server.ScriptInfo["documentPositionMapper"] | undefined; - } - function verifyAllFnAction({ - session, - host, - verifiers, - actionKey, - dependencyMap, - documentPositionMapper, - }: VerifyAllFnAction): VerifyAllFnActionResult { - const actionInfos = getActionInfo(verifiers, actionKey); - let sourceMapPath: server.ScriptInfo["sourceMapFilePath"] | undefined; - // action - let first = true; - for (const { - action, - closedInfos, - otherWatchedFiles, - expectsDts, - expectsMap, - freshMapInfo, - freshDocumentMapper, - skipDtsMapCheck - } of actionInfos) { - for (let fn = 1; fn <= 5; fn++) { - const fnAction = action(fn); - verifyAction(session, fnAction); - const debugInfo = `${actionKey}:: ${fnAction.reqName}:: ${fn}`; - const dtsInfo = verifyScriptInfoPresence(session, dtsPath, expectsDts, debugInfo); - const dtsMapInfo = verifyScriptInfoPresence(session, dtsMapPath, expectsMap, debugInfo); - verifyInfosWithRandom( - session, - host, - openFiles(verifiers).map(f => f.path), - closedInfos, - otherWatchedFiles, - debugInfo - ); - - if (dtsInfo) { - if (first || (fn === 1 && freshMapInfo)) { - if (!skipDtsMapCheck) { - if (dtsMapInfo) { - assert.equal(dtsInfo.sourceMapFilePath, dtsMapPath, debugInfo); - } - else { - assert.isNotString(dtsInfo.sourceMapFilePath, debugInfo); - assert.isNotFalse(dtsInfo.sourceMapFilePath, debugInfo); - assert.isDefined(dtsInfo.sourceMapFilePath, debugInfo); - } - } - } - else { - assert.equal(dtsInfo.sourceMapFilePath, sourceMapPath, debugInfo); - } - } - - if (!first && (fn !== 1 || !freshMapInfo)) { - verifyDocumentPositionMapper({ - session, - dependencyMap, - documentPositionMapper, - equal: fn !== 1 || !freshDocumentMapper, - debugInfo - }); - } - sourceMapPath = dtsInfo && dtsInfo.sourceMapFilePath; - dependencyMap = dtsMapInfo; - documentPositionMapper = dependencyMap && dependencyMap.documentPositionMapper; - first = false; - } - } - - return { actionInfos, actionKey, dependencyMap, documentPositionMapper }; - } - - function verifyScriptInfoCollection( - session: TestSession, - host: TestServerHost, - verifiers: readonly DocumentPositionMapperVerifier[], - { dependencyMap, documentPositionMapper, actionInfos, actionKey }: VerifyAllFnActionResult - ) { - // Collecting at this point retains dependency.d.ts and map - closeFilesForSession([randomFile], session); - openFilesForSession([randomFile], session); - - const { closedInfos, otherWatchedFiles } = last(actionInfos); - const debugInfo = `${actionKey} Collection`; - verifyInfosWithRandom( - session, - host, - openFiles(verifiers).map(f => f.path), - closedInfos, - otherWatchedFiles, - debugInfo - ); - verifyDocumentPositionMapper({ - session, - dependencyMap, - documentPositionMapper, - equal: true, - debugInfo - }); - - // Closing open file, removes dependencies too - closeFilesForSession([...openFiles(verifiers), randomFile], session); - openFilesForSession([randomFile], session); - verifyOnlyRandomInfos(session, host); - } - - function verifyScenarioAndScriptInfoCollection( - session: TestSession, - host: TestServerHost, - verifiers: readonly DocumentPositionMapperVerifier[], - actionKey: ActionKey, - noDts?: true - ) { - // Main scenario action - const result = verifyAllFnAction({ session, host, verifiers, actionKey }); - checkProject(session, verifiers, noDts); - verifyScriptInfoCollection(session, host, verifiers, result); - } - - function verifyScenarioWithChangesWorker( - { - scenarioName, - verifier, - withRefs, - disableSourceOfProjectReferenceRedirect, - change, - afterChangeActionKey - }: VerifyScenarioWithChanges, - timeoutBeforeAction: boolean, - ) { - it(scenarioName, () => { - const { host, session, verifiers } = openTsFile({ verifier, withRefs, disableSourceOfProjectReferenceRedirect }); - - // Create DocumentPositionMapper - firstAction(session, verifiers); - const dependencyMap = session.getProjectService().filenameToScriptInfo.get(dtsMapPath); - const documentPositionMapper = dependencyMap && dependencyMap.documentPositionMapper; - - // change - change(host, session, verifiers); - if (timeoutBeforeAction) { - host.runQueuedTimeoutCallbacks(); - checkProject(session, verifiers); - verifyDocumentPositionMapper({ - session, - dependencyMap, - documentPositionMapper, - equal: true, - debugInfo: "After change timeout" - }); - } - - // action - verifyAllFnAction({ - session, - host, - verifiers, - actionKey: afterChangeActionKey, - dependencyMap, - documentPositionMapper - }); - }); - } - - interface VerifyScenarioWithChanges extends VerifierAndWithRefs { - scenarioName: string; - change: (host: TestServerHost, session: TestSession, verifiers: readonly DocumentPositionMapperVerifier[]) => void; - afterChangeActionKey: ActionKey; - } - function verifyScenarioWithChanges(verify: VerifyScenarioWithChanges) { - describe("when timeout occurs before request", () => { - verifyScenarioWithChangesWorker(verify, /*timeoutBeforeAction*/ true); - }); - - describe("when timeout does not occur before request", () => { - verifyScenarioWithChangesWorker(verify, /*timeoutBeforeAction*/ false); - }); - } - - interface VerifyScenarioWhenFileNotPresent extends VerifierAndWithRefs { - scenarioName: string; - fileLocation: string; - fileNotPresentKey: ActionKey; - fileCreatedKey: ActionKey; - fileDeletedKey: ActionKey; - noDts?: true; - } - function verifyScenarioWhenFileNotPresent({ - scenarioName, - verifier, - withRefs, - disableSourceOfProjectReferenceRedirect, - fileLocation, - fileNotPresentKey, - fileCreatedKey, - fileDeletedKey, - noDts - }: VerifyScenarioWhenFileNotPresent) { - describe(scenarioName, () => { - it("when file is not present", () => { - const { host, session, verifiers } = openTsFile({ - verifier, - withRefs, - disableSourceOfProjectReferenceRedirect, - onHostCreate: host => host.deleteFile(fileLocation) - }); - checkProject(session, verifiers, noDts); - - verifyScenarioAndScriptInfoCollection(session, host, verifiers, fileNotPresentKey, noDts); - }); - - it("when file is created after actions on projects", () => { - let fileContents: string | undefined; - const { host, session, verifiers } = openTsFile({ - verifier, - withRefs, - disableSourceOfProjectReferenceRedirect, - onHostCreate: host => { - fileContents = host.readFile(fileLocation); - host.deleteFile(fileLocation); - } - }); - firstAction(session, verifiers); - - host.writeFile(fileLocation, fileContents!); - verifyScenarioAndScriptInfoCollection(session, host, verifiers, fileCreatedKey); - }); - - it("when file is deleted after actions on the projects", () => { - const { host, session, verifiers } = openTsFile({ verifier, disableSourceOfProjectReferenceRedirect, withRefs }); - firstAction(session, verifiers); - - // The dependency file is deleted when orphan files are collected - host.deleteFile(fileLocation); - // Verify with deleted action key - verifyAllFnAction({ session, host, verifiers, actionKey: fileDeletedKey }); - checkProject(session, verifiers, noDts); - - // Script info collection should behave as fileNotPresentKey - verifyScriptInfoCollection( - session, - host, - verifiers, - { - actionInfos: getActionInfo(verifiers, fileNotPresentKey), - actionKey: fileNotPresentKey, - dependencyMap: undefined, - documentPositionMapper: undefined - } - ); - }); - }); - } - - function verifyScenarioWorker({ mainScenario, verifier }: VerifyScenario, withRefs: boolean, disableSourceOfProjectReferenceRedirect?: true) { - it(mainScenario, () => { - const { host, session, verifiers } = openTsFile({ withRefs, disableSourceOfProjectReferenceRedirect, verifier }); - checkProject(session, verifiers); - verifyScenarioAndScriptInfoCollection(session, host, verifiers, "main"); - }); - - // Edit - verifyScenarioWithChanges({ - scenarioName: "when usage file changes, document position mapper doesnt change", - verifier, - withRefs, - disableSourceOfProjectReferenceRedirect, - change: (_host, session, verifiers) => verifiers.forEach( - verifier => session.executeCommandSeq({ - command: protocol.CommandTypes.Change, - arguments: { - file: verifier.openFile.path, - line: verifier.openFileLastLine, - offset: 1, - endLine: verifier.openFileLastLine, - endOffset: 1, - insertString: "const x = 10;" - } - }) - ), - afterChangeActionKey: "change" - }); - - // Edit dts to add new fn - verifyScenarioWithChanges({ - scenarioName: "when dependency .d.ts changes, document position mapper doesnt change", - verifier, - withRefs, - disableSourceOfProjectReferenceRedirect, - change: host => host.writeFile( - dtsLocation, - host.readFile(dtsLocation)!.replace( - "//# sourceMappingURL=FnS.d.ts.map", - `export declare function fn6(): void; -//# sourceMappingURL=FnS.d.ts.map` - ) - ), - afterChangeActionKey: "dtsChange" - }); - - // Edit map file to represent added new line - verifyScenarioWithChanges({ - scenarioName: "when dependency file's map changes", - verifier, - withRefs, - disableSourceOfProjectReferenceRedirect, - change: host => host.writeFile( - dtsMapLocation, - `{"version":3,"file":"FnS.d.ts","sourceRoot":"","sources":["../dependency/FnS.ts"],"names":[],"mappings":"AAAA,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,eAAO,MAAM,CAAC,KAAK,CAAC"}` - ), - afterChangeActionKey: "mapChange" - }); - - verifyScenarioWhenFileNotPresent({ - scenarioName: "with depedency files map file", - verifier, - withRefs, - disableSourceOfProjectReferenceRedirect, - fileLocation: dtsMapLocation, - fileNotPresentKey: "noMap", - fileCreatedKey: "mapFileCreated", - fileDeletedKey: "mapFileDeleted" - }); - - verifyScenarioWhenFileNotPresent({ - scenarioName: "with depedency .d.ts file", - verifier, - withRefs, - disableSourceOfProjectReferenceRedirect, - fileLocation: dtsLocation, - fileNotPresentKey: "noDts", - fileCreatedKey: "dtsFileCreated", - fileDeletedKey: "dtsFileDeleted", - noDts: true - }); - - if (withRefs && !disableSourceOfProjectReferenceRedirect) { - verifyScenarioWithChanges({ - scenarioName: "when defining project source changes", - verifier, - withRefs, - change: (host, session, verifiers) => { - // Make change, without rebuild of solution - if (contains(openFiles(verifiers), dependencyTs)) { - session.executeCommandSeq({ - command: protocol.CommandTypes.Change, - arguments: { - file: dependencyTs.path, line: 1, offset: 1, endLine: 1, endOffset: 1, insertString: `function fooBar() { } -`} - }); - } - else { - host.writeFile(dependencyTs.path, `function fooBar() { } -${dependencyTs.content}`); - } - }, - afterChangeActionKey: "dependencyChange" - }); - - it("when projects are not built", () => { - const host = createServerHost(files); - const session = createSession(host); - const verifiers = verifier(withRefs); - openFilesForSession([...openFiles(verifiers), randomFile], session); - verifyScenarioAndScriptInfoCollection(session, host, verifiers, "noBuild"); - }); - } - } - - interface VerifyScenario { - mainScenario: string; - verifier: (withRefs: boolean, disableSourceOfProjectReferenceRedirect?: true) => readonly DocumentPositionMapperVerifier[]; - } - function verifyScenario(scenario: VerifyScenario) { - describe(scenario.mainScenario, () => { - describe("when main tsconfig doesnt have project reference", () => { - verifyScenarioWorker(scenario, /*withRefs*/ false); - }); - describe("when main tsconfig has project reference", () => { - verifyScenarioWorker(scenario, /*withRefs*/ true); - }); - describe("when main tsconfig has disableSourceOfProjectReferenceRedirect along with project reference", () => { - verifyScenarioWorker(scenario, /*withRefs*/ true, /*disableSourceOfProjectReferenceRedirect*/ true); - }); - }); - } - - describe("from project that uses dependency", () => { - verifyScenario({ - mainScenario: "can go to definition correctly", - verifier: (withRefs, disableSourceOfProjectReferenceRedirect) => [ - { - ...goToDefFromMainTsProjectInfoVerifier(withRefs), - main: () => ({ - action: goToDefFromMainTs, - closedInfos: withRefs ? - [dependencyTs.path, dependencyConfig.path, libFile.path] : - disableSourceOfProjectReferenceRedirect ? - [dependencyTs.path, libFile.path, dtsPath, dtsMapLocation, dependencyConfig.path] : - [dependencyTs.path, libFile.path, dtsPath, dtsMapLocation], - otherWatchedFiles: [mainConfig.path], - expectsDts: !withRefs, // Dts script info present only if no project reference - expectsMap: !withRefs // Map script info present only if no project reference - }), - change: "main", - dtsChange: "main", - mapChange: ["main", () => ({ - freshDocumentMapper: true - })], - noMap: withRefs ? - "main" : - ["main", main => ({ - action: goToDefFromMainTsWithNoMap, - // Because map is deleted, dts and dependency are released - closedInfos: removePath(main.closedInfos, dtsMapPath, dependencyTsPath), - // Watches deleted file - otherWatchedFiles: main.otherWatchedFiles.concat(dtsMapLocation), - expectsMap: false - })], - mapFileCreated: "main", - mapFileDeleted: withRefs ? - "main" : - ["noMap", noMap => ({ - // The script info for depedency is collected only after file open - closedInfos: noMap.closedInfos.concat(dependencyTs.path) - })], - noDts: withRefs ? - "main" : - ["main", main => ({ - action: goToDefFromMainTsWithNoDts, - // No dts, no map, no dependency - closedInfos: removePath(main.closedInfos, dtsPath, dtsMapPath, dependencyTsPath), - expectsDts: false, - expectsMap: false - })], - dtsFileCreated: "main", - dtsFileDeleted: withRefs ? - "main" : - ["noDts", noDts => ({ - // The script info for map is collected only after file open - closedInfos: noDts.closedInfos.concat(dependencyTs.path, dtsMapLocation), - expectsMap: true - })], - dependencyChange: ["main", () => ({ - action: goToDefFromMainTsWithDependencyChange, - })], - noBuild: "noDts" - } - ] - }); - }); - - describe("from defining project", () => { - verifyScenario({ - mainScenario: "rename locations from dependency", - verifier: () => [ - { - ...renameFromDependencyTsProjectInfoVerifier(), - main: () => ({ - action: renameFromDependencyTs, - closedInfos: [libFile.path, dtsLocation, dtsMapLocation], - otherWatchedFiles: [dependencyConfig.path], - expectsDts: true, - expectsMap: true - }), - change: "main", - dtsChange: "main", - mapChange: ["main", () => ({ - freshDocumentMapper: true - })], - noMap: ["main", main => ({ - // No map - closedInfos: removePath(main.closedInfos, dtsMapPath), - // watch map - otherWatchedFiles: [...main.otherWatchedFiles, dtsMapLocation], - expectsMap: false - })], - mapFileCreated: "main", - mapFileDeleted: "noMap", - noDts: ["main", main => ({ - // no dts or map since dts itself doesnt exist - closedInfos: removePath(main.closedInfos, dtsMapPath, dtsPath), - // watch deleted file - otherWatchedFiles: [...main.otherWatchedFiles, dtsLocation], - expectsDts: false, - expectsMap: false - })], - dtsFileCreated: "main", - dtsFileDeleted: ["noDts", noDts => ({ - // Map is collected after file open - closedInfos: noDts.closedInfos.concat(dtsMapLocation), - expectsMap: true - })], - dependencyChange: ["main", () => ({ - action: renameFromDependencyTsWithDependencyChange - })], - noBuild: "noDts" - } - ] - }); - }); - - describe("when opening depedency and usage project", () => { - verifyScenario({ - mainScenario: "goto Definition in usage and rename locations from defining project", - verifier: (withRefs, disableSourceOfProjectReferenceRedirect) => [ - { - ...goToDefFromMainTsProjectInfoVerifier(withRefs), - main: () => ({ - action: goToDefFromMainTs, - // DependencyTs is open, so omit it from closed infos - closedInfos: withRefs ? - [dependencyConfig.path, libFile.path] : - disableSourceOfProjectReferenceRedirect ? - [libFile.path, dtsPath, dtsMapLocation, dependencyConfig.path] : - [libFile.path, dtsPath, dtsMapLocation], - otherWatchedFiles: withRefs || disableSourceOfProjectReferenceRedirect ? - [mainConfig.path] : // dependencyConfig is in closed info - [mainConfig.path, dependencyConfig.path], - expectsDts: !withRefs, // Dts script info present only if no project reference - expectsMap: !withRefs // Map script info present only if no project reference - }), - change: withRefs ? - ["main", main => ({ - // Because before this rename is done the closed info remains same as rename's main operation - closedInfos: main.closedInfos.concat(dtsLocation, dtsMapLocation), - expectsDts: true, - expectsMap: true - })] : - "main", - dtsChange: "change", - mapChange: "change", - noMap: withRefs ? - "main" : - ["main", main => ({ - action: goToDefFromMainTsWithNoMap, - closedInfos: removePath(main.closedInfos, dtsMapPath), - otherWatchedFiles: main.otherWatchedFiles.concat(dtsMapLocation), - expectsMap: false - })], - mapFileCreated: withRefs ? - ["main", main => ({ - // Because before this rename is done the closed info remains same as rename's main - closedInfos: main.closedInfos.concat(dtsLocation), - expectsDts: true, - // This operation doesnt need map so the map info path in dts is not refreshed - skipDtsMapCheck: withRefs - })] : - "main", - mapFileDeleted: withRefs ? - ["noMap", noMap => ({ - // Because before this rename is done the closed info remains same as rename's noMap operation - closedInfos: noMap.closedInfos.concat(dtsLocation), - expectsDts: true, - // This operation doesnt need map so the map info path in dts is not refreshed - skipDtsMapCheck: true - })] : - "noMap", - noDts: withRefs ? - "main" : - ["main", main => ({ - action: goToDefFromMainTsWithNoDts, - closedInfos: removePath(main.closedInfos, dtsMapPath, dtsPath), - expectsDts: false, - expectsMap: false - })], - dtsFileCreated: withRefs ? - ["main", main => ({ - // Since the project for dependency is not updated, the watcher from rename for dts still there - otherWatchedFiles: main.otherWatchedFiles.concat(dtsLocation) - })] : - "main", - dtsFileDeleted: ["noDts", noDts => ({ - // Map collection after file open - closedInfos: noDts.closedInfos.concat(dtsMapLocation), - expectsMap: true - })], - dependencyChange: ["change", () => ({ - action: goToDefFromMainTsWithDependencyChange, - })], - noBuild: "noDts" - }, - { - ...renameFromDependencyTsProjectInfoVerifier(), - main: () => ({ - action: renameFromDependencyTsWithBothProjectsOpen, - // DependencyTs is open, so omit it from closed infos - closedInfos: withRefs ? - [dependencyConfig.path, libFile.path, dtsLocation, dtsMapLocation] : - disableSourceOfProjectReferenceRedirect ? - [libFile.path, dtsPath, dtsMapLocation, dependencyConfig.path] : - [libFile.path, dtsPath, dtsMapLocation], - otherWatchedFiles: withRefs || disableSourceOfProjectReferenceRedirect ? - [mainConfig.path] : // dependencyConfig is in closed info - [mainConfig.path, dependencyConfig.path], - expectsDts: true, - expectsMap: true, - freshMapInfo: withRefs - }), - change: ["main", () => ({ - freshMapInfo: false - })], - dtsChange: "change", - mapChange: ["main", () => ({ - freshMapInfo: false, - freshDocumentMapper: withRefs - })], - noMap: ["main", main => ({ - action: withRefs ? - renameFromDependencyTsWithBothProjectsOpen : - renameFromDependencyTs, - closedInfos: removePath(main.closedInfos, dtsMapPath), - otherWatchedFiles: main.otherWatchedFiles.concat(dtsMapLocation), - expectsMap: false, - freshDocumentMapper: withRefs - })], - mapFileCreated: "main", - mapFileDeleted: "noMap", - noDts: ["change", change => ({ - action: withRefs ? - renameFromDependencyTsWithBothProjectsOpen : - renameFromDependencyTs, - closedInfos: removePath(change.closedInfos, dtsPath, dtsMapPath), - otherWatchedFiles: change.otherWatchedFiles.concat(dtsLocation), - expectsDts: false, - expectsMap: false - })], - dtsFileCreated: "main", - dtsFileDeleted: ["noDts", noDts => ({ - // Map collection after file open - closedInfos: noDts.closedInfos.concat(dtsMapLocation), - expectsMap: true - })], - dependencyChange: ["change", () => ({ - action: renameFromDependencyTsWithBothProjectsOpenWithDependencyChange - })], - noBuild: "noDts" - } - ] - }); - }); - }); - describe("when root file is file from referenced project", () => { function verify(disableSourceOfProjectReferenceRedirect: boolean) { const projectLocation = `/user/username/projects/project`; @@ -1296,7 +197,7 @@ function foo() { } ` }; - const host = createHost( + const host = createHostWithSolutionBuild( [commonConfig, keyboardTs, keyboardTestTs, srcConfig, terminalTs, libFile], [srcConfig.path] ); @@ -1470,7 +371,7 @@ function foo() { const bConfig = config("B", extraOptions); const files = [libFile, bPackageJson, aConfig, bConfig, aTest, bFoo, bBar, bSymlink]; const host = alreadyBuilt ? - createHost(files, [aConfig.path]) : + createHostWithSolutionBuild(files, [aConfig.path]) : createServerHost(files); // Create symlink in node module @@ -1575,6 +476,88 @@ bar(); }); }); + it("when the referenced projects have allowJs and emitDeclarationOnly", () => { + const compositeConfig: File = { + path: `${tscWatch.projectRoot}/packages/emit-composite/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + composite: true, + allowJs: true, + emitDeclarationOnly: true, + outDir: "lib", + rootDir: "src" + }, + include: ["src"] + }) + }; + const compositePackageJson: File = { + path: `${tscWatch.projectRoot}/packages/emit-composite/package.json`, + content: JSON.stringify({ + name: "emit-composite", + version: "1.0.0", + main: "src/index.js", + typings: "lib/index.d.ts" + }) + }; + const compositeIndex: File = { + path: `${tscWatch.projectRoot}/packages/emit-composite/src/index.js`, + content: `const testModule = require('./testModule'); +module.exports = { + ...testModule +}` + }; + const compositeTestModule: File = { + path: `${tscWatch.projectRoot}/packages/emit-composite/src/testModule.js`, + content: `/** + * @param {string} arg + */ + const testCompositeFunction = (arg) => { +} +module.exports = { + testCompositeFunction +}` + }; + const consumerConfig: File = { + path: `${tscWatch.projectRoot}/packages/consumer/tsconfig.json`, + content: JSON.stringify({ + include: ["src"], + references: [{ path: "../emit-composite" }] + }) + }; + const consumerIndex: File = { + path: `${tscWatch.projectRoot}/packages/consumer/src/index.ts`, + content: `import { testCompositeFunction } from 'emit-composite'; +testCompositeFunction('why hello there'); +testCompositeFunction('why hello there', 42);` + }; + const symlink: SymLink = { + path: `${tscWatch.projectRoot}/node_modules/emit-composite`, + symLink: `${tscWatch.projectRoot}/packages/emit-composite` + }; + const host = createServerHost([libFile, compositeConfig, compositePackageJson, compositeIndex, compositeTestModule, consumerConfig, consumerIndex, symlink], { useCaseSensitiveFileNames: true }); + const session = createSession(host, { canUseEvents: true }); + const service = session.getProjectService(); + openFilesForSession([consumerIndex], session); + checkNumberOfProjects(service, { configuredProjects: 1 }); + checkProjectActualFiles( + service.configuredProjects.get(consumerConfig.path)!, + [consumerIndex.path, libFile.path, consumerConfig.path, compositeIndex.path, compositeTestModule.path] + ); + const secondArg = protocolTextSpanFromSubstring(consumerIndex.content, "42"); + verifyGetErrRequest({ + host, + session, + expected: [{ + file: consumerIndex, + syntax: [], + semantic: [ + createDiagnostic(secondArg.start, secondArg.end, Diagnostics.Expected_0_arguments_but_got_1, ["1", "2"]), + ], + suggestion: [] + }] + }); + }); + it("when finding local reference doesnt load ancestor/sibling projects", () => { const solutionLocation = "/user/username/projects/solution"; const solution: File = { @@ -1720,6 +703,305 @@ bar(); checkProjectActualFiles(service.configuredProjects.get(servicesConfig.path)!, [servicesFile.path, servicesConfig.path, libFile.path, typesFile.path, programFile.path]); }); + describe("special handling of localness of the definitions for findAllRefs", () => { + function setup(definition: string, usage: string) { + const solutionLocation = "/user/username/projects/solution"; + const solution: File = { + path: `${solutionLocation}/tsconfig.json`, + content: JSON.stringify({ + files: [], + references: [ + { path: "./api" }, + { path: "./app" }, + ] + }) + }; + const apiConfig: File = { + path: `${solutionLocation}/api/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + composite: true, + outDir: "dist", + rootDir: "src", + }, + include: ["src"], + references: [{ path: "../shared" }] + }) + }; + const apiFile: File = { + path: `${solutionLocation}/api/src/server.ts`, + content: `import * as shared from "../../shared/dist"; +${usage}` + }; + const appConfig: File = { + path: `${solutionLocation}/app/tsconfig.json`, + content: apiConfig.content + }; + const appFile: File = { + path: `${solutionLocation}/app/src/app.ts`, + content: apiFile.content + }; + const sharedConfig: File = { + path: `${solutionLocation}/shared/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + composite: true, + outDir: "dist", + rootDir: "src", + }, + include: ["src"] + }) + }; + const sharedFile: File = { + path: `${solutionLocation}/shared/src/index.ts`, + content: definition + }; + const host = createServerHost([libFile, solution, libFile, apiConfig, apiFile, appConfig, appFile, sharedConfig, sharedFile]); + const session = createSession(host); + const service = session.getProjectService(); + service.openClientFile(apiFile.path); + verifyApiProjectLoadAndSolutionPending(); + return { session, verifySolutionTreeLoaded, verifyApiAndSharedProjectLoadAndSolutionPending, apiFile, appFile, sharedFile }; + + function checkApiProject() { + const apiProject = service.configuredProjects.get(apiConfig.path)!; + checkProjectActualFiles(apiProject, [libFile.path, apiConfig.path, apiFile.path, sharedFile.path]); + } + function checkAppProject() { + const appProject = service.configuredProjects.get(appConfig.path)!; + checkProjectActualFiles(appProject, [libFile.path, appConfig.path, appFile.path, sharedFile.path]); + } + function checkSharedProject() { + const sharedProject = service.configuredProjects.get(sharedConfig.path)!; + checkProjectActualFiles(sharedProject, [libFile.path, sharedConfig.path, sharedFile.path]); + } + function checkSolutionLoadPending() { + const solutionProject = service.configuredProjects.get(solution.path)!; + assert.isFalse(solutionProject.isInitialLoadPending()); + } + function checkSolutionLoadComplete() { + const solutionProject = service.configuredProjects.get(solution.path)!; + assert.isTrue(solutionProject.isInitialLoadPending()); + } + function verifySolutionTreeLoaded() { + checkNumberOfProjects(service, { configuredProjects: 4 }); + checkApiProject(); + checkAppProject(); + checkSharedProject(); + checkSolutionLoadPending(); + } + + function verifyApiProjectLoadAndSolutionPending() { + checkNumberOfProjects(service, { configuredProjects: 2 }); + checkApiProject(); + checkSolutionLoadComplete(); + } + + function verifyApiAndSharedProjectLoadAndSolutionPending() { + checkNumberOfProjects(service, { configuredProjects: 3 }); + checkApiProject(); + checkSharedProject(); + checkSolutionLoadComplete(); + } + } + + it("when using arrow function assignment", () => { + const { session, apiFile, appFile, sharedFile, verifySolutionTreeLoaded } = setup( + `export const dog = () => { };`, + `shared.dog();` + ); + + // Find all references + const response = session.executeCommandSeq({ + command: protocol.CommandTypes.References, + arguments: protocolFileLocationFromSubstring(apiFile, "dog") + }).response as protocol.ReferencesResponseBody; + assert.deepEqual(response, { + refs: [ + makeReferenceItem({ + file: sharedFile, + text: "dog", + contextText: sharedFile.content, + isDefinition: true, + lineText: sharedFile.content, + }), + makeReferenceItem({ + file: apiFile, + text: "dog", + isDefinition: false, + lineText: "shared.dog();", + }), + makeReferenceItem({ + file: appFile, + text: "dog", + isDefinition: false, + lineText: "shared.dog();", + }) + ], + symbolName: "dog", + symbolStartOffset: protocolLocationFromSubstring(apiFile.content, "dog").offset, + symbolDisplayString: "const dog: () => void" + }); + verifySolutionTreeLoaded(); + }); + + it("when using arrow function as object literal property", () => { + const { session, apiFile, appFile, sharedFile, verifySolutionTreeLoaded } = setup( + `export const foo = { bar: () => { } };`, + `shared.foo.bar();` + ); + + // Find all references + const response = session.executeCommandSeq({ + command: protocol.CommandTypes.References, + arguments: protocolFileLocationFromSubstring(apiFile, "bar") + }).response as protocol.ReferencesResponseBody; + assert.deepEqual(response, { + refs: [ + makeReferenceItem({ + file: sharedFile, + text: "bar", + contextText: `bar: () => { }`, + isDefinition: true, + lineText: sharedFile.content, + }), + makeReferenceItem({ + file: apiFile, + text: "bar", + isDefinition: false, + lineText: "shared.foo.bar();", + }), + makeReferenceItem({ + file: appFile, + text: "bar", + isDefinition: false, + lineText: "shared.foo.bar();", + }) + ], + symbolName: "bar", + symbolStartOffset: protocolLocationFromSubstring(apiFile.content, "bar").offset, + symbolDisplayString: "(property) bar: () => void" + }); + verifySolutionTreeLoaded(); + }); + + it("when using object literal property", () => { + const { session, apiFile, appFile, sharedFile, verifySolutionTreeLoaded } = setup( + `export const foo = { baz: "BAZ" };`, + `shared.foo.baz;` + ); + + // Find all references + const response = session.executeCommandSeq({ + command: protocol.CommandTypes.References, + arguments: protocolFileLocationFromSubstring(apiFile, "baz") + }).response as protocol.ReferencesResponseBody; + assert.deepEqual(response, { + refs: [ + makeReferenceItem({ + file: sharedFile, + text: "baz", + contextText: `baz: "BAZ"`, + isDefinition: true, + lineText: sharedFile.content, + }), + makeReferenceItem({ + file: apiFile, + text: "baz", + isDefinition: false, + lineText: "shared.foo.baz;", + }), + makeReferenceItem({ + file: appFile, + text: "baz", + isDefinition: false, + lineText: "shared.foo.baz;", + }) + ], + symbolName: "baz", + symbolStartOffset: protocolLocationFromSubstring(apiFile.content, "baz").offset, + symbolDisplayString: `(property) baz: string` + }); + verifySolutionTreeLoaded(); + }); + + it("when using method of class expression", () => { + const { session, apiFile, appFile, sharedFile, verifySolutionTreeLoaded } = setup( + `export const foo = class { fly() {} };`, + `const instance = new shared.foo(); +instance.fly();` + ); + + // Find all references + const response = session.executeCommandSeq({ + command: protocol.CommandTypes.References, + arguments: protocolFileLocationFromSubstring(apiFile, "fly") + }).response as protocol.ReferencesResponseBody; + assert.deepEqual(response, { + refs: [ + makeReferenceItem({ + file: sharedFile, + text: "fly", + contextText: `fly() {}`, + isDefinition: true, + lineText: sharedFile.content, + }), + makeReferenceItem({ + file: apiFile, + text: "fly", + isDefinition: false, + lineText: "instance.fly();", + }), + makeReferenceItem({ + file: appFile, + text: "fly", + isDefinition: false, + lineText: "instance.fly();", + }) + ], + symbolName: "fly", + symbolStartOffset: protocolLocationFromSubstring(apiFile.content, "fly").offset, + symbolDisplayString: `(method) foo.fly(): void` + }); + verifySolutionTreeLoaded(); + }); + + it("when using arrow function as object literal property is loaded through indirect assignment with original declaration local to project is treated as local", () => { + const { session, apiFile, sharedFile, verifyApiAndSharedProjectLoadAndSolutionPending } = setup( + `const local = { bar: () => { } }; +export const foo = local;`, + `shared.foo.bar();` + ); + + // Find all references + const response = session.executeCommandSeq({ + command: protocol.CommandTypes.References, + arguments: protocolFileLocationFromSubstring(apiFile, "bar") + }).response as protocol.ReferencesResponseBody; + assert.deepEqual(response, { + refs: [ + makeReferenceItem({ + file: sharedFile, + text: "bar", + contextText: `bar: () => { }`, + isDefinition: true, + lineText: `const local = { bar: () => { } };`, + }), + makeReferenceItem({ + file: apiFile, + text: "bar", + isDefinition: false, + lineText: "shared.foo.bar();", + }), + ], + symbolName: "bar", + symbolStartOffset: protocolLocationFromSubstring(apiFile.content, "bar").offset, + symbolDisplayString: "(property) bar: () => void" + }); + verifyApiAndSharedProjectLoadAndSolutionPending(); + }); + }); + it("when disableSolutionSearching is true, solution and siblings are not loaded", () => { const solutionLocation = "/user/username/projects/solution"; const solution: File = { @@ -2515,6 +1797,160 @@ bar;` }); }); + describe("when new file is added to the referenced project", () => { + function setup(extendOptionsProject2?: CompilerOptions) { + const config1: File = { + path: `${tscWatch.projectRoot}/projects/project1/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + module: "none", + composite: true + }, + exclude: ["temp"] + }) + }; + const class1: File = { + path: `${tscWatch.projectRoot}/projects/project1/class1.ts`, + content: `class class1 {}` + }; + const class1Dts: File = { + path: `${tscWatch.projectRoot}/projects/project1/class1.d.ts`, + content: `declare class class1 {}` + }; + const config2: File = { + path: `${tscWatch.projectRoot}/projects/project2/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + module: "none", + composite: true, + ...(extendOptionsProject2 || {}) + }, + references: [ + { path: "../project1" } + ] + }) + }; + const class2: File = { + path: `${tscWatch.projectRoot}/projects/project2/class2.ts`, + content: `class class2 {}` + }; + const host = createServerHost([config1, class1, class1Dts, config2, class2, libFile]); + const session = createSession(host); + openFilesForSession([class2], session); + const service = session.getProjectService(); + return { host, session, service, class1, class1Dts, class2, config1, config2 }; + } + + it("when referenced project is not open", () => { + const { host, service, class1, class2, config2 } = setup(); + checkNumberOfProjects(service, { configuredProjects: 1 }); + const project2 = Debug.checkDefined(service.configuredProjects.get(config2.path)); + checkProjectActualFiles(project2, [class2.path, libFile.path, class1.path, config2.path]); + + // Add new class to referenced project + const class3 = `${tscWatch.projectRoot}/projects/project1/class3.ts`; + host.writeFile(class3, `class class3 {}`); + host.checkTimeoutQueueLengthAndRun(2); + checkProjectActualFiles(project2, [class2.path, libFile.path, class1.path, config2.path, class3]); + // Add excluded file to referenced project + host.ensureFileOrFolder({ path: `${tscWatch.projectRoot}/projects/project1/temp/file.d.ts`, content: `declare class file {}` }); + host.checkTimeoutQueueLengthAndRun(0); + // Add output from new class to referenced project + const class3Dts = `${tscWatch.projectRoot}/projects/project1/class3.d.ts`; + host.writeFile(class3Dts, `declare class class3 {}`); + host.checkTimeoutQueueLengthAndRun(0); + }); + + it("when referenced project is open", () => { + const { host, session, service, class1, class2, config1, config2 } = setup(); + openFilesForSession([class1], session); + checkNumberOfProjects(service, { configuredProjects: 2 }); + const project1 = Debug.checkDefined(service.configuredProjects.get(config1.path)); + checkProjectActualFiles(project1, [libFile.path, class1.path, config1.path]); + const project2 = Debug.checkDefined(service.configuredProjects.get(config2.path)); + checkProjectActualFiles(project2, [class2.path, libFile.path, class1.path, config2.path]); + + // Add new class to referenced project + const class3 = `${tscWatch.projectRoot}/projects/project1/class3.ts`; + host.writeFile(class3, `class class3 {}`); + host.checkTimeoutQueueLengthAndRun(3); + checkProjectActualFiles(project1, [libFile.path, class1.path, config1.path, class3]); + checkProjectActualFiles(project2, [class2.path, libFile.path, class1.path, config2.path, class3]); + // Add excluded file to referenced project + host.ensureFileOrFolder({ path: `${tscWatch.projectRoot}/projects/project1/temp/file.d.ts`, content: `declare class file {}` }); + host.checkTimeoutQueueLengthAndRun(0); + // Add output from new class to referenced project + const class3Dts = `${tscWatch.projectRoot}/projects/project1/class3.d.ts`; + host.writeFile(class3Dts, `declare class class3 {}`); + host.checkTimeoutQueueLengthAndRun(0); + }); + + it("when referenced project is not open with disableSourceOfProjectReferenceRedirect", () => { + const { host, service, class1Dts, class2, config2 } = setup({ disableSourceOfProjectReferenceRedirect: true }); + checkNumberOfProjects(service, { configuredProjects: 1 }); + const project2 = Debug.checkDefined(service.configuredProjects.get(config2.path)); + checkProjectActualFiles(project2, [class2.path, libFile.path, class1Dts.path, config2.path]); + + // Add new class to referenced project + const class3 = `${tscWatch.projectRoot}/projects/project1/class3.ts`; + host.writeFile(class3, `class class3 {}`); + host.checkTimeoutQueueLengthAndRun(2); + checkProjectActualFiles(project2, [class2.path, libFile.path, class1Dts.path, config2.path]); + // Add output of new class to referenced project + const class3Dts = `${tscWatch.projectRoot}/projects/project1/class3.d.ts`; + host.writeFile(class3Dts, `declare class class3 {}`); + host.checkTimeoutQueueLengthAndRun(2); + checkProjectActualFiles(project2, [class2.path, libFile.path, class1Dts.path, config2.path, class3Dts]); + // Add excluded file to referenced project + host.ensureFileOrFolder({ path: `${tscWatch.projectRoot}/projects/project1/temp/file.d.ts`, content: `declare class file {}` }); + host.checkTimeoutQueueLengthAndRun(0); + // Delete output from new class to referenced project + host.deleteFile(class3Dts); + host.checkTimeoutQueueLengthAndRun(2); + checkProjectActualFiles(project2, [class2.path, libFile.path, class1Dts.path, config2.path]); + // Write back output of new class to referenced project + host.writeFile(class3Dts, `declare class class3 {}`); + host.checkTimeoutQueueLengthAndRun(2); + checkProjectActualFiles(project2, [class2.path, libFile.path, class1Dts.path, config2.path, class3Dts]); + }); + + it("when referenced project is open with disableSourceOfProjectReferenceRedirect", () => { + const { host, session, service, class1, class1Dts, class2, config1, config2 } = setup({ disableSourceOfProjectReferenceRedirect: true }); + openFilesForSession([class1], session); + checkNumberOfProjects(service, { configuredProjects: 2 }); + const project1 = Debug.checkDefined(service.configuredProjects.get(config1.path)); + checkProjectActualFiles(project1, [libFile.path, class1.path, config1.path]); + const project2 = Debug.checkDefined(service.configuredProjects.get(config2.path)); + checkProjectActualFiles(project2, [class2.path, libFile.path, class1Dts.path, config2.path]); + + // Add new class to referenced project + const class3 = `${tscWatch.projectRoot}/projects/project1/class3.ts`; + host.writeFile(class3, `class class3 {}`); + host.checkTimeoutQueueLengthAndRun(3); + checkProjectActualFiles(project1, [libFile.path, class1.path, config1.path, class3]); + checkProjectActualFiles(project2, [class2.path, libFile.path, class1Dts.path, config2.path]); + // Add output of new class to referenced project + const class3Dts = `${tscWatch.projectRoot}/projects/project1/class3.d.ts`; + host.writeFile(class3Dts, `declare class class3 {}`); + host.checkTimeoutQueueLengthAndRun(2); + checkProjectActualFiles(project1, [libFile.path, class1.path, config1.path, class3]); + checkProjectActualFiles(project2, [class2.path, libFile.path, class1Dts.path, config2.path, class3Dts]); + // Add excluded file to referenced project + host.ensureFileOrFolder({ path: `${tscWatch.projectRoot}/projects/project1/temp/file.d.ts`, content: `declare class file {}` }); + host.checkTimeoutQueueLengthAndRun(0); + // Delete output from new class to referenced project + host.deleteFile(class3Dts); + host.checkTimeoutQueueLengthAndRun(2); + checkProjectActualFiles(project1, [libFile.path, class1.path, config1.path, class3]); + checkProjectActualFiles(project2, [class2.path, libFile.path, class1Dts.path, config2.path]); + // Write back output of new class to referenced project + host.writeFile(class3Dts, `declare class class3 {}`); + host.checkTimeoutQueueLengthAndRun(2); + checkProjectActualFiles(project1, [libFile.path, class1.path, config1.path, class3]); + checkProjectActualFiles(project2, [class2.path, libFile.path, class1Dts.path, config2.path, class3Dts]); + }); + }); + describe("auto import with referenced project", () => { function verifyAutoImport(built: boolean, disableSourceOfProjectReferenceRedirect?: boolean) { const solnConfig: File = { diff --git a/src/testRunner/unittests/tsserver/projectReferencesSourcemap.ts b/src/testRunner/unittests/tsserver/projectReferencesSourcemap.ts new file mode 100644 index 0000000000000..d50f879a60dc5 --- /dev/null +++ b/src/testRunner/unittests/tsserver/projectReferencesSourcemap.ts @@ -0,0 +1,4439 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: with project references and tsbuild source map", () => { + const dependecyLocation = `${tscWatch.projectRoot}/dependency`; + const dependecyDeclsLocation = `${tscWatch.projectRoot}/decls`; + const mainLocation = `${tscWatch.projectRoot}/main`; + const dependencyTs: File = { + path: `${dependecyLocation}/FnS.ts`, + content: `export function fn1() { } +export function fn2() { } +export function fn3() { } +export function fn4() { } +export function fn5() { } +` + }; + const dependencyTsPath = dependencyTs.path.toLowerCase(); + const dependencyConfig: File = { + path: `${dependecyLocation}/tsconfig.json`, + content: JSON.stringify({ compilerOptions: { composite: true, declarationMap: true, declarationDir: "../decls" } }) + }; + + const mainTs: File = { + path: `${mainLocation}/main.ts`, + content: `import { + fn1, + fn2, + fn3, + fn4, + fn5 +} from '../decls/fns' + +fn1(); +fn2(); +fn3(); +fn4(); +fn5(); +` + }; + const mainConfig: File = { + path: `${mainLocation}/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { composite: true, declarationMap: true }, + references: [{ path: "../dependency" }] + }) + }; + + const randomFile: File = { + path: `${tscWatch.projectRoot}/random/random.ts`, + content: "let a = 10;" + }; + const randomConfig: File = { + path: `${tscWatch.projectRoot}/random/tsconfig.json`, + content: "{}" + }; + const dtsLocation = `${dependecyDeclsLocation}/FnS.d.ts`; + const dtsPath = dtsLocation.toLowerCase() as Path; + const dtsMapLocation = `${dependecyDeclsLocation}/FnS.d.ts.map`; + const dtsMapPath = dtsMapLocation.toLowerCase() as Path; + + const files = [dependencyTs, dependencyConfig, mainTs, mainConfig, libFile, randomFile, randomConfig]; + + function changeDtsFile(host: TestServerHost) { + host.writeFile( + dtsLocation, + host.readFile(dtsLocation)!.replace( + "//# sourceMappingURL=FnS.d.ts.map", + `export declare function fn6(): void; +//# sourceMappingURL=FnS.d.ts.map` + ) + ); + } + + function changeDtsMapFile(host: TestServerHost) { + host.writeFile( + dtsMapLocation, + `{"version":3,"file":"FnS.d.ts","sourceRoot":"","sources":["../dependency/FnS.ts"],"names":[],"mappings":"AAAA,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,eAAO,MAAM,CAAC,KAAK,CAAC"}` + ); + } + + function verifyScriptInfos(session: TestSession, host: TestServerHost, openInfos: readonly string[], closedInfos: readonly string[], otherWatchedFiles: readonly string[], additionalInfo?: string) { + checkScriptInfos(session.getProjectService(), openInfos.concat(closedInfos), additionalInfo); + checkWatchedFiles(host, closedInfos.concat(otherWatchedFiles).map(f => f.toLowerCase()), additionalInfo); + } + + function verifyOnlyRandomInfos(session: TestSession, host: TestServerHost) { + verifyScriptInfos(session, host, [randomFile.path], [libFile.path], [randomConfig.path], "Random"); + } + + function declarationSpan(fn: number): protocol.TextSpanWithContext { + return { + start: { line: fn, offset: 17 }, + end: { line: fn, offset: 20 }, + contextStart: { line: fn, offset: 1 }, + contextEnd: { line: fn, offset: 26 } + }; + } + function importSpan(fn: number): protocol.TextSpanWithContext { + return { + start: { line: fn + 1, offset: 5 }, + end: { line: fn + 1, offset: 8 }, + contextStart: { line: 1, offset: 1 }, + contextEnd: { line: 7, offset: 22 } + }; + } + function usageSpan(fn: number): protocol.TextSpan { + return { start: { line: fn + 8, offset: 1 }, end: { line: fn + 8, offset: 4 } }; + } + + function goToDefFromMainTs(fn: number): Action { + const textSpan = usageSpan(fn); + const definition: protocol.FileSpan = { file: dependencyTs.path, ...declarationSpan(fn) }; + return { + reqName: "goToDef", + request: { + command: protocol.CommandTypes.DefinitionAndBoundSpan, + arguments: { file: mainTs.path, ...textSpan.start } + }, + expectedResponse: { + // To dependency + definitions: [definition], + textSpan + } + }; + } + + function goToDefFromMainTsWithNoMap(fn: number): Action { + const textSpan = usageSpan(fn); + const definition = declarationSpan(fn); + const declareSpaceLength = "declare ".length; + return { + reqName: "goToDef", + request: { + command: protocol.CommandTypes.DefinitionAndBoundSpan, + arguments: { file: mainTs.path, ...textSpan.start } + }, + expectedResponse: { + // To the dts + definitions: [{ + file: dtsPath, + start: { line: fn, offset: definition.start.offset + declareSpaceLength }, + end: { line: fn, offset: definition.end.offset + declareSpaceLength }, + contextStart: { line: fn, offset: 1 }, + contextEnd: { line: fn, offset: 37 } + }], + textSpan + } + }; + } + + function goToDefFromMainTsWithNoDts(fn: number): Action { + const textSpan = usageSpan(fn); + return { + reqName: "goToDef", + request: { + command: protocol.CommandTypes.DefinitionAndBoundSpan, + arguments: { file: mainTs.path, ...textSpan.start } + }, + expectedResponse: { + // To import declaration + definitions: [{ file: mainTs.path, ...importSpan(fn) }], + textSpan + } + }; + } + + function goToDefFromMainTsWithDependencyChange(fn: number): Action { + const textSpan = usageSpan(fn); + return { + reqName: "goToDef", + request: { + command: protocol.CommandTypes.DefinitionAndBoundSpan, + arguments: { file: mainTs.path, ...textSpan.start } + }, + expectedResponse: { + // Definition on fn + 1 line + definitions: [{ file: dependencyTs.path, ...declarationSpan(fn + 1) }], + textSpan + } + }; + } + + function renameFromDependencyTs(fn: number): Action { + const defSpan = declarationSpan(fn); + const { contextStart: _, contextEnd: _1, ...triggerSpan } = defSpan; + return { + reqName: "rename", + request: { + command: protocol.CommandTypes.Rename, + arguments: { file: dependencyTs.path, ...triggerSpan.start } + }, + expectedResponse: { + info: { + canRename: true, + fileToRename: undefined, + displayName: `fn${fn}`, + fullDisplayName: `"${dependecyLocation}/FnS".fn${fn}`, + kind: ScriptElementKind.functionElement, + kindModifiers: "export", + triggerSpan + }, + locs: [ + { file: dependencyTs.path, locs: [defSpan] } + ] + } + }; + } + + function renameFromDependencyTsWithDependencyChange(fn: number): Action { + const { expectedResponse: { info, locs }, ...rest } = renameFromDependencyTs(fn + 1); + + return { + ...rest, + expectedResponse: { + info: { + ...info as protocol.RenameInfoSuccess, + displayName: `fn${fn}`, + fullDisplayName: `"${dependecyLocation}/FnS".fn${fn}`, + }, + locs + } + }; + } + + function renameFromDependencyTsWithBothProjectsOpen(fn: number): Action { + const { reqName, request, expectedResponse } = renameFromDependencyTs(fn); + const { info, locs } = expectedResponse; + return { + reqName, + request, + expectedResponse: { + info, + locs: [ + locs[0], + { + file: mainTs.path, + locs: [ + importSpan(fn), + usageSpan(fn) + ] + } + ] + } + }; + } + + function renameFromDependencyTsWithBothProjectsOpenWithDependencyChange(fn: number): Action { + const { reqName, request, expectedResponse, } = renameFromDependencyTsWithDependencyChange(fn); + const { info, locs } = expectedResponse; + return { + reqName, + request, + expectedResponse: { + info, + locs: [ + locs[0], + { + file: mainTs.path, + locs: [ + importSpan(fn), + usageSpan(fn) + ] + } + ] + } + }; + } + + function removePath(array: readonly string[], ...delPaths: string[]) { + return array.filter(a => { + const aLower = a.toLowerCase(); + return delPaths.every(dPath => dPath !== aLower); + }); + } + + interface Action { + reqName: string; + request: Partial; + expectedResponse: Response; + } + + function verifyAction(session: TestSession, { reqName, request, expectedResponse }: Action) { + const { response } = session.executeCommandSeq(request); + assert.deepEqual(response, expectedResponse, `Failed Request: ${reqName}`); + } + + function verifyDocumentPositionMapper( + session: TestSession, + dependencyMap: server.ScriptInfo | undefined, + documentPositionMapper: server.ScriptInfo["documentPositionMapper"], + equal: boolean, + debugInfo?: string, + ) { + assert.strictEqual(session.getProjectService().filenameToScriptInfo.get(dtsMapPath), dependencyMap, `${debugInfo} dependencyMap`); + if (dependencyMap) { + verifyEquality(dependencyMap.documentPositionMapper, documentPositionMapper, equal, `${debugInfo} DocumentPositionMapper`); + } + } + + function verifyDocumentPositionMapperEqual( + session: TestSession, + dependencyMap: server.ScriptInfo | undefined, + documentPositionMapper: server.ScriptInfo["documentPositionMapper"], + debugInfo?: string, + ) { + verifyDocumentPositionMapper(session, dependencyMap, documentPositionMapper, /*equal*/ true, debugInfo); + } + + function verifyEquality(actual: T, expected: T, equal: boolean, debugInfo?: string) { + if (equal) { + assert.strictEqual(actual, expected, debugInfo); + } + else { + assert.notStrictEqual(actual, expected, debugInfo); + } + } + + function verifyAllFnAction( + session: TestSession, + host: TestServerHost, + action: (fn: number) => Action, + expectedInfos: readonly string[], + expectedWatchedFiles: readonly string[], + existingDependencyMap: server.ScriptInfo | undefined, + existingDocumentPositionMapper: server.ScriptInfo["documentPositionMapper"], + existingMapEqual: boolean, + existingDocumentPositionMapperEqual: boolean, + skipMapPathInDtsInfo?: boolean + ) { + let sourceMapPath: server.ScriptInfo["sourceMapFilePath"] | undefined; + let dependencyMap: server.ScriptInfo | undefined; + let documentPositionMapper: server.ScriptInfo["documentPositionMapper"]; + for (let fn = 1; fn <= 5; fn++) { + const fnAction = action(fn); + verifyAction(session, fnAction); + const debugInfo = `${fnAction.reqName}:: ${fn}`; + checkScriptInfos(session.getProjectService(), expectedInfos, debugInfo); + checkWatchedFiles(host, expectedWatchedFiles, debugInfo); + const dtsInfo = session.getProjectService().getScriptInfoForPath(dtsPath); + const dtsMapInfo = session.getProjectService().getScriptInfoForPath(dtsMapPath); + + if (fn === 1) { + if (dtsInfo) { + if (!skipMapPathInDtsInfo) { + if (dtsMapInfo) { + assert.equal(dtsInfo.sourceMapFilePath, dtsMapPath, `${debugInfo} sourceMapFilePath`); + } + else { + assert.isNotString(dtsInfo.sourceMapFilePath, `${debugInfo} sourceMapFilePath`); + assert.isNotFalse(dtsInfo.sourceMapFilePath, `${debugInfo} sourceMapFilePath`); + assert.isDefined(dtsInfo.sourceMapFilePath, `${debugInfo} sourceMapFilePath`); + } + } + } + verifyEquality(dtsMapInfo, existingDependencyMap, existingMapEqual, `${debugInfo} dependencyMap`); + verifyEquality(existingDocumentPositionMapper, dtsMapInfo?.documentPositionMapper, existingDocumentPositionMapperEqual, `${debugInfo} DocumentPositionMapper`); + sourceMapPath = dtsInfo?.sourceMapFilePath; + dependencyMap = dtsMapInfo; + documentPositionMapper = dependencyMap?.documentPositionMapper; + } + else { + assert.equal(dtsInfo?.sourceMapFilePath, sourceMapPath, `${debugInfo} sourceMapFilePath`); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper, debugInfo); + } + } + } + + function verifyScriptInfoCollectionWith( + session: TestSession, + host: TestServerHost, + openFiles: readonly File[], + expectedInfos: readonly string[], + expectedWatchedFiles: readonly string[], + ) { + const { dependencyMap, documentPositionMapper } = getDocumentPositionMapper(session); + + // Collecting at this point retains dependency.d.ts and map + closeFilesForSession([randomFile], session); + openFilesForSession([randomFile], session); + + checkScriptInfos(session.getProjectService(), expectedInfos); + checkWatchedFiles(host, expectedWatchedFiles); + // If map is not collected, document position mapper shouldnt change + if (session.getProjectService().filenameToScriptInfo.has(dtsMapPath)) { + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + } + + // Closing open file, removes dependencies too + closeFilesForSession([...openFiles, randomFile], session); + openFilesForSession([randomFile], session); + verifyOnlyRandomInfos(session, host); + } + + type OnHostCreate = (host: TestServerHost) => void; + type CreateSessionFn = (onHostCreate?: OnHostCreate) => { host: TestServerHost; session: TestSession; }; + function setupWith(createSession: CreateSessionFn, openFiles: readonly File[], onHostCreate: OnHostCreate | undefined) { + const result = createSession(onHostCreate); + openFilesForSession(openFiles, result.session); + return result; + } + + function setupWithMainTs(createSession: CreateSessionFn, onHostCreate: OnHostCreate | undefined) { + return setupWith(createSession, [mainTs, randomFile], onHostCreate); + } + + function setupWithDependencyTs(createSession: CreateSessionFn, onHostCreate: OnHostCreate | undefined) { + return setupWith(createSession, [dependencyTs, randomFile], onHostCreate); + } + + function setupWithMainTsAndDependencyTs(createSession: CreateSessionFn, onHostCreate: OnHostCreate | undefined) { + return setupWith(createSession, [mainTs, dependencyTs, randomFile], onHostCreate); + } + + function createSessionWithoutProjectReferences(onHostCreate?: OnHostCreate) { + const host = createHostWithSolutionBuild(files, [mainConfig.path]); + // Erase project reference + host.writeFile(mainConfig.path, JSON.stringify({ + compilerOptions: { composite: true, declarationMap: true } + })); + onHostCreate?.(host); + const session = createSession(host); + return { host, session }; + } + + function createSessionWithProjectReferences(onHostCreate?: OnHostCreate) { + const host = createHostWithSolutionBuild(files, [mainConfig.path]); + onHostCreate?.(host); + const session = createSession(host); + return { host, session }; + } + + function createSessionWithDisabledProjectReferences(onHostCreate?: OnHostCreate) { + const host = createHostWithSolutionBuild(files, [mainConfig.path]); + // Erase project reference + host.writeFile(mainConfig.path, JSON.stringify({ + compilerOptions: { + composite: true, + declarationMap: true, + disableSourceOfProjectReferenceRedirect: true + }, + references: [{ path: "../dependency" }] + })); + onHostCreate?.(host); + const session = createSession(host); + return { host, session }; + } + + function getDocumentPositionMapper(session: TestSession) { + const dependencyMap = session.getProjectService().filenameToScriptInfo.get(dtsMapPath); + const documentPositionMapper = dependencyMap?.documentPositionMapper; + return { dependencyMap, documentPositionMapper }; + } + + function checkMainProjectWithoutProjectReferences(session: TestSession) { + checkProjectActualFiles(session.getProjectService().configuredProjects.get(mainConfig.path)!, [mainTs.path, libFile.path, mainConfig.path, dtsPath]); + } + + function checkMainProjectWithoutProjectReferencesWithoutDts(session: TestSession) { + checkProjectActualFiles(session.getProjectService().configuredProjects.get(mainConfig.path)!, [mainTs.path, libFile.path, mainConfig.path]); + } + + function checkMainProjectWithProjectReferences(session: TestSession) { + checkProjectActualFiles(session.getProjectService().configuredProjects.get(mainConfig.path)!, [mainTs.path, libFile.path, mainConfig.path, dependencyTs.path]); + } + + function checkMainProjectWithDisabledProjectReferences(session: TestSession) { + checkProjectActualFiles(session.getProjectService().configuredProjects.get(mainConfig.path)!, [mainTs.path, libFile.path, mainConfig.path, dtsPath]); + } + + function checkMainProjectWithDisabledProjectReferencesWithoutDts(session: TestSession) { + checkProjectActualFiles(session.getProjectService().configuredProjects.get(mainConfig.path)!, [mainTs.path, libFile.path, mainConfig.path]); + } + + function checkDependencyProjectWith(session: TestSession) { + checkProjectActualFiles(session.getProjectService().configuredProjects.get(dependencyConfig.path)!, [dependencyTs.path, libFile.path, dependencyConfig.path]); + } + + function makeChangeToMainTs(session: TestSession) { + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: mainTs.path, + line: 14, + offset: 1, + endLine: 14, + endOffset: 1, + insertString: "const x = 10;" + } + }); + } + + function makeChangeToDependencyTs(session: TestSession) { + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: dependencyTs.path, + line: 6, + offset: 1, + endLine: 6, + endOffset: 1, + insertString: "const x = 10;" + } + }); + } + + describe("from project that uses dependency: goToDef", () => { + function setupWithActionWith(setup: (onHostCreate?: OnHostCreate) => ReturnType, onHostCreate: OnHostCreate | undefined) { + const result = setup(onHostCreate); + result.session.executeCommandSeq(goToDefFromMainTs(1).request); + return { ...result, ...getDocumentPositionMapper(result.session) }; + } + + function verifyScriptInfoCollection( + session: TestSession, + host: TestServerHost, + expectedInfos: readonly string[], + expectedWatchedFiles: readonly string[], + ) { + return verifyScriptInfoCollectionWith(session, host, [mainTs], expectedInfos, expectedWatchedFiles); + } + + describe("when main tsconfig doesnt have project reference", () => { + function setup(onHostCreate?: OnHostCreate) { + return setupWithMainTs(createSessionWithoutProjectReferences, onHostCreate); + } + + function setupWithAction(onHostCreate?: OnHostCreate) { + return setupWithActionWith(setup, onHostCreate); + } + + function checkProjects(session: TestSession) { + checkNumberOfProjects(session.getProjectService(), { configuredProjects: 2 }); + checkMainProjectWithoutProjectReferences(session); + } + + function checkProjectsWithoutDts(session: TestSession) { + checkNumberOfProjects(session.getProjectService(), { configuredProjects: 2 }); + checkMainProjectWithoutProjectReferencesWithoutDts(session); + } + + function expectedScriptInfosWhenMapped() { + return [mainTs.path, randomFile.path, dependencyTs.path, libFile.path, dtsPath, dtsMapLocation]; + } + + function expectedWatchedFilesWhenMapped() { + return [dependencyTsPath, libFile.path, dtsPath, dtsMapPath, mainConfig.path, randomConfig.path]; + } + + function expectedScriptInfosWhenNoMap() { + // Because map is deleted, map and dependency are released + return removePath(expectedScriptInfosWhenMapped(), dtsMapPath, dependencyTsPath); + } + + function expectedWatchedFilesWhenNoMap() { + // Watches deleted file + return removePath(expectedWatchedFilesWhenMapped(), dependencyTsPath); + } + + function expectedScriptInfosWhenNoDts() { + // No dts, no map, no dependency + return removePath(expectedScriptInfosWhenMapped(), dtsPath, dtsMapPath, dependencyTsPath); + } + + function expectedWatchedFilesWhenNoDts() { + return removePath(expectedWatchedFilesWhenMapped(), dtsPath, dtsMapPath, dependencyTsPath); + } + + it("can go to definition correctly", () => { + const { host, session } = setup(); + checkProjects(session); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + ); + }); + + // Edit + it(`when usage file changes, document position mapper doesnt change, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + makeChangeToMainTs(session); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when usage file changes, document position mapper doesnt change, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + makeChangeToMainTs(session); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + // Edit dts to add new fn + it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsFile(host); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsFile(host); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + // Edit map file to represent added new line + it(`when dependency file's map changes, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsMapFile(host); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false + ); + }); + it(`when dependency file's map changes, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsMapFile(host); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false + ); + }); + + it(`with depedency files map file, when file is not present`, () => { + const { host, session } = setup(host => host.deleteFile(dtsMapLocation)); + checkProjects(session); + + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithNoMap, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + ); + }); + it(`with depedency files map file, when file is created after actions on projects`, () => { + let fileContents: string; + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => { + fileContents = host.readFile(dtsMapLocation)!; + host.deleteFile(dtsMapLocation); + }); + + host.writeFile(dtsMapLocation, fileContents!); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped() + ); + }); + it(`with depedency files map file, when file is deleted after actions on the projects`, () => { + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(dtsMapLocation); + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithNoMap, + // The script info for map is collected only after file open + expectedScriptInfosWhenNoMap().concat(dependencyTs.path), + expectedWatchedFilesWhenNoMap().concat(dependencyTsPath), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + + // Script info collection should behave as fileNotPresentKey + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + ); + }); + + it(`with depedency .d.ts file, when file is not present`, () => { + const { host, session } = setup(host => host.deleteFile(dtsLocation)); + checkProjectsWithoutDts(session); + + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithNoDts, + expectedScriptInfosWhenNoDts(), + expectedWatchedFilesWhenNoDts(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjectsWithoutDts(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoDts(), + expectedWatchedFilesWhenNoDts(), + ); + }); + it(`with depedency .d.ts file, when file is created after actions on projects`, () => { + let fileContents: string; + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => { + fileContents = host.readFile(dtsLocation)!; + host.deleteFile(dtsLocation); + }); + + host.writeFile(dtsLocation, fileContents!); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped() + ); + }); + it(`with depedency .d.ts file, when file is deleted after actions on the projects`, () => { + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(dtsLocation); + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithNoDts, + // The script info for map is collected only after file open + expectedScriptInfosWhenNoDts().concat(dependencyTs.path, dtsMapLocation), + expectedWatchedFilesWhenNoDts().concat(dependencyTsPath, dtsMapPath), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjectsWithoutDts(session); + + // Script info collection should behave as "noDts" + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoDts(), + expectedWatchedFilesWhenNoDts(), + ); + }); + }); + describe("when main tsconfig has project reference", () => { + function setup(onHostCreate?: OnHostCreate) { + return setupWithMainTs(createSessionWithProjectReferences, onHostCreate); + } + + function setupWithAction(onHostCreate?: OnHostCreate) { + return setupWithActionWith(setup, onHostCreate); + } + + function checkProjects(session: TestSession) { + checkNumberOfProjects(session.getProjectService(), { configuredProjects: 2 }); + checkMainProjectWithProjectReferences(session); + } + + function expectedScriptInfos() { + return [dependencyTs.path, libFile.path, mainTs.path, randomFile.path]; + } + + function expectedWatchedFiles() { + return [dependencyTsPath, dependencyConfig.path, libFile.path, mainConfig.path, randomConfig.path]; + } + + it("can go to definition correctly", () => { + const { host, session } = setup(); + checkProjects(session); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfos(), + expectedWatchedFiles(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfos(), + expectedWatchedFiles(), + ); + }); + + // Edit + it(`when usage file changes, document position mapper doesnt change, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + makeChangeToMainTs(session); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when usage file changes, document position mapper doesnt change, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + makeChangeToMainTs(session); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + // Edit dts to add new fn + it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsFile(host); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsFile(host); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + // Edit map file to represent added new line + it(`when dependency file's map changes, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsMapFile(host); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when dependency file's map changes, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsMapFile(host); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + it(`with depedency files map file, when file is not present`, () => { + const { host, session } = setup(host => host.deleteFile(dtsMapLocation)); + checkProjects(session); + + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfos(), + expectedWatchedFiles(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfos(), + expectedWatchedFiles(), + ); + }); + it(`with depedency files map file, when file is created after actions on projects`, () => { + let fileContents: string; + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => { + fileContents = host.readFile(dtsMapLocation)!; + host.deleteFile(dtsMapLocation); + }); + + host.writeFile(dtsMapLocation, fileContents!); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfos(), + expectedWatchedFiles() + ); + }); + it(`with depedency files map file, when file is deleted after actions on the projects`, () => { + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(dtsMapLocation); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + + // Script info collection should behave as fileNotPresentKey + verifyScriptInfoCollection( + session, + host, + expectedScriptInfos(), + expectedWatchedFiles(), + ); + }); + + it(`with depedency .d.ts file, when file is not present`, () => { + const { host, session } = setup(host => host.deleteFile(dtsLocation)); + checkProjects(session); + + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfos(), + expectedWatchedFiles(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfos(), + expectedWatchedFiles(), + ); + }); + it(`with depedency .d.ts file, when file is created after actions on projects`, () => { + let fileContents: string; + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => { + fileContents = host.readFile(dtsLocation)!; + host.deleteFile(dtsLocation); + }); + + host.writeFile(dtsLocation, fileContents!); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfos(), + expectedWatchedFiles() + ); + }); + it(`with depedency .d.ts file, when file is deleted after actions on the projects`, () => { + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(dtsLocation); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + + // Script info collection should behave as "noDts" + verifyScriptInfoCollection( + session, + host, + expectedScriptInfos(), + expectedWatchedFiles(), + ); + }); + + it(`when defining project source changes, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + // Make change, without rebuild of solution + host.writeFile(dependencyTs.path, `function fooBar() { } +${dependencyTs.content}`); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithDependencyChange, + expectedScriptInfos(), + expectedWatchedFiles(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when defining project source changes, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session } = setupWithAction(); + + // change + // Make change, without rebuild of solution + host.writeFile(dependencyTs.path, `function fooBar() { } +${dependencyTs.content}`); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithDependencyChange, + expectedScriptInfos(), + expectedWatchedFiles(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + it("when projects are not built", () => { + const host = createServerHost(files); + const session = createSession(host); + openFilesForSession([mainTs, randomFile], session); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfos(), + expectedWatchedFiles(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfos(), + expectedWatchedFiles(), + ); + }); + }); + describe("when main tsconfig has disableSourceOfProjectReferenceRedirect along with project reference", () => { + function setup(onHostCreate?: OnHostCreate) { + return setupWithMainTs(createSessionWithDisabledProjectReferences, onHostCreate); + } + + function setupWithAction(onHostCreate?: OnHostCreate) { + return setupWithActionWith(setup, onHostCreate); + } + + function checkProjects(session: TestSession) { + checkNumberOfProjects(session.getProjectService(), { configuredProjects: 2 }); + checkMainProjectWithDisabledProjectReferences(session); + } + + function checkProjectsWithoutDts(session: TestSession) { + checkNumberOfProjects(session.getProjectService(), { configuredProjects: 2 }); + checkMainProjectWithDisabledProjectReferencesWithoutDts(session); + } + + function expectedScriptInfosWhenMapped() { + return [mainTs.path, randomFile.path, dependencyTs.path, libFile.path, dtsPath, dtsMapLocation]; + } + + function expectedWatchedFilesWhenMapped() { + return [dependencyTsPath, libFile.path, dtsPath, dtsMapPath, mainConfig.path, randomConfig.path, dependencyConfig.path]; + } + + function expectedScriptInfosWhenNoMap() { + // Because map is deleted, map and dependency are released + return removePath(expectedScriptInfosWhenMapped(), dtsMapPath, dependencyTsPath); + } + + function expectedWatchedFilesWhenNoMap() { + // Watches deleted file + return removePath(expectedWatchedFilesWhenMapped(), dependencyTsPath); + } + + function expectedScriptInfosWhenNoDts() { + // No dts, no map, no dependency + return removePath(expectedScriptInfosWhenMapped(), dtsPath, dtsMapPath, dependencyTsPath); + } + + function expectedWatchedFilesWhenNoDts() { + return removePath(expectedWatchedFilesWhenMapped(), dtsPath, dtsMapPath, dependencyTsPath); + } + + it("can go to definition correctly", () => { + const { host, session } = setup(); + checkProjects(session); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + ); + }); + + // Edit + it(`when usage file changes, document position mapper doesnt change, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + makeChangeToMainTs(session); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when usage file changes, document position mapper doesnt change, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + makeChangeToMainTs(session); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + // Edit dts to add new fn + it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsFile(host); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsFile(host); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + // Edit map file to represent added new line + it(`when dependency file's map changes, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsMapFile(host); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false + ); + }); + it(`when dependency file's map changes, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsMapFile(host); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false + ); + }); + + it(`with depedency files map file, when file is not present`, () => { + const { host, session } = setup(host => host.deleteFile(dtsMapLocation)); + checkProjects(session); + + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithNoMap, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + ); + }); + it(`with depedency files map file, when file is created after actions on projects`, () => { + let fileContents: string; + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => { + fileContents = host.readFile(dtsMapLocation)!; + host.deleteFile(dtsMapLocation); + }); + + host.writeFile(dtsMapLocation, fileContents!); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped() + ); + }); + it(`with depedency files map file, when file is deleted after actions on the projects`, () => { + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(dtsMapLocation); + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithNoMap, + // The script info for map is collected only after file open + expectedScriptInfosWhenNoMap().concat(dependencyTs.path), + expectedWatchedFilesWhenNoMap().concat(dependencyTsPath), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + + // Script info collection should behave as fileNotPresentKey + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + ); + }); + + it(`with depedency .d.ts file, when file is not present`, () => { + const { host, session } = setup(host => host.deleteFile(dtsLocation)); + checkProjectsWithoutDts(session); + + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithNoDts, + expectedScriptInfosWhenNoDts(), + expectedWatchedFilesWhenNoDts(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjectsWithoutDts(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoDts(), + expectedWatchedFilesWhenNoDts(), + ); + }); + it(`with depedency .d.ts file, when file is created after actions on projects`, () => { + let fileContents: string; + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => { + fileContents = host.readFile(dtsLocation)!; + host.deleteFile(dtsLocation); + }); + + host.writeFile(dtsLocation, fileContents!); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped() + ); + }); + it(`with depedency .d.ts file, when file is deleted after actions on the projects`, () => { + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(dtsLocation); + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithNoDts, + // The script info for map is collected only after file open + expectedScriptInfosWhenNoDts().concat(dependencyTs.path, dtsMapLocation), + expectedWatchedFilesWhenNoDts().concat(dependencyTsPath, dtsMapPath), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjectsWithoutDts(session); + + // Script info collection should behave as "noDts" + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoDts(), + expectedWatchedFilesWhenNoDts(), + ); + }); + }); + }); + + describe("from defining project: rename", () => { + function setupWithActionWith(setup: (onHostCreate?: OnHostCreate) => ReturnType, onHostCreate: OnHostCreate | undefined) { + const result = setup(onHostCreate); + result.session.executeCommandSeq(renameFromDependencyTs(1).request); + return { ...result, ...getDocumentPositionMapper(result.session) }; + } + + function verifyScriptInfoCollection( + session: TestSession, + host: TestServerHost, + expectedInfos: readonly string[], + expectedWatchedFiles: readonly string[], + ) { + return verifyScriptInfoCollectionWith(session, host, [dependencyTs], expectedInfos, expectedWatchedFiles); + } + + function checkProjects(session: TestSession) { + checkNumberOfProjects(session.getProjectService(), { configuredProjects: 2 }); + checkDependencyProjectWith(session); + } + + function expectedScriptInfos() { + return [libFile.path, dtsLocation, dtsMapLocation, dependencyTs.path, randomFile.path]; + } + + function expectedWatchedFiles() { + return [libFile.path, dtsPath, dtsMapPath, dependencyConfig.path, randomConfig.path]; + } + + function expectedScriptInfosWhenNoMap() { + // No map + return removePath(expectedScriptInfos(), dtsMapPath); + } + + function expectedWatchedFilesWhenNoMap() { + // Watches deleted file = map file + return expectedWatchedFiles(); + } + + function expectedScriptInfosWhenNoDts() { + // no dts or map since dts itself doesnt exist + return removePath(expectedScriptInfos(), dtsPath, dtsMapPath); + } + + function expectedWatchedFilesWhenNoDts() { + // watch deleted file + return removePath(expectedWatchedFiles(), dtsMapPath); + } + + describe("when main tsconfig doesnt have project reference", () => { + function setup(onHostCreate?: OnHostCreate) { + return setupWithDependencyTs(createSessionWithoutProjectReferences, onHostCreate); + } + + function setupWithAction(onHostCreate?: OnHostCreate) { + return setupWithActionWith(setup, onHostCreate); + } + + it("rename locations from dependency", () => { + const { host, session } = setup(); + checkProjects(session); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfos(), + expectedWatchedFiles(), + ); + }); + + // Edit + it(`when usage file changes, document position mapper doesnt change, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + makeChangeToDependencyTs(session); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when usage file changes, document position mapper doesnt change, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + makeChangeToDependencyTs(session); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + // Edit dts to add new fn + it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsFile(host); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsFile(host); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + // Edit map file to represent added new line + it(`when dependency file's map changes, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsMapFile(host); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false + ); + }); + it(`when dependency file's map changes, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsMapFile(host); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false + ); + }); + + it(`with depedency files map file, when file is not present`, () => { + const { host, session } = setup(host => host.deleteFile(dtsMapLocation)); + checkProjects(session); + + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + ); + }); + it(`with depedency files map file, when file is created after actions on projects`, () => { + let fileContents: string; + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => { + fileContents = host.readFile(dtsMapLocation)!; + host.deleteFile(dtsMapLocation); + }); + + host.writeFile(dtsMapLocation, fileContents!); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfos(), + expectedWatchedFiles() + ); + }); + it(`with depedency files map file, when file is deleted after actions on the projects`, () => { + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(dtsMapLocation); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + + // Script info collection should behave as fileNotPresentKey + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + ); + }); + + it(`with depedency .d.ts file, when file is not present`, () => { + const { host, session } = setup(host => host.deleteFile(dtsLocation)); + checkProjects(session); + + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfosWhenNoDts(), + expectedWatchedFilesWhenNoDts(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoDts(), + expectedWatchedFilesWhenNoDts(), + ); + }); + it(`with depedency .d.ts file, when file is created after actions on projects`, () => { + let fileContents: string; + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => { + fileContents = host.readFile(dtsLocation)!; + host.deleteFile(dtsLocation); + }); + + host.writeFile(dtsLocation, fileContents!); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfos(), + expectedWatchedFiles() + ); + }); + it(`with depedency .d.ts file, when file is deleted after actions on the projects`, () => { + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(dtsLocation); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + // Map is collected after file open + expectedScriptInfosWhenNoDts().concat(dtsMapLocation), + expectedWatchedFilesWhenNoDts().concat(dtsPath), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + + // Script info collection should behave as "noDts" + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoDts(), + expectedWatchedFilesWhenNoDts(), + ); + }); + }); + describe("when main tsconfig has project reference", () => { + function setup(onHostCreate?: OnHostCreate) { + return setupWithDependencyTs(createSessionWithProjectReferences, onHostCreate); + } + + function setupWithAction(onHostCreate?: OnHostCreate) { + return setupWithActionWith(setup, onHostCreate); + } + + it("rename locations from dependency", () => { + const { host, session } = setup(); + checkProjects(session); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfos(), + expectedWatchedFiles(), + ); + }); + + // Edit + it(`when usage file changes, document position mapper doesnt change, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + makeChangeToDependencyTs(session); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when usage file changes, document position mapper doesnt change, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + makeChangeToDependencyTs(session); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + // Edit dts to add new fn + it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsFile(host); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsFile(host); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + // Edit map file to represent added new line + it(`when dependency file's map changes, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsMapFile(host); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false + ); + }); + it(`when dependency file's map changes, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsMapFile(host); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false + ); + }); + + it(`with depedency files map file, when file is not present`, () => { + const { host, session } = setup(host => host.deleteFile(dtsMapLocation)); + checkProjects(session); + + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + ); + }); + it(`with depedency files map file, when file is created after actions on projects`, () => { + let fileContents: string; + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => { + fileContents = host.readFile(dtsMapLocation)!; + host.deleteFile(dtsMapLocation); + }); + + host.writeFile(dtsMapLocation, fileContents!); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfos(), + expectedWatchedFiles() + ); + }); + it(`with depedency files map file, when file is deleted after actions on the projects`, () => { + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(dtsMapLocation); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + + // Script info collection should behave as fileNotPresentKey + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + ); + }); + + it(`with depedency .d.ts file, when file is not present`, () => { + const { host, session } = setup(host => host.deleteFile(dtsLocation)); + checkProjects(session); + + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfosWhenNoDts(), + expectedWatchedFilesWhenNoDts(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoDts(), + expectedWatchedFilesWhenNoDts(), + ); + }); + it(`with depedency .d.ts file, when file is created after actions on projects`, () => { + let fileContents: string; + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => { + fileContents = host.readFile(dtsLocation)!; + host.deleteFile(dtsLocation); + }); + + host.writeFile(dtsLocation, fileContents!); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfos(), + expectedWatchedFiles() + ); + }); + it(`with depedency .d.ts file, when file is deleted after actions on the projects`, () => { + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(dtsLocation); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + // Map is collected after file open + expectedScriptInfosWhenNoDts().concat(dtsMapLocation), + expectedWatchedFilesWhenNoDts().concat(dtsPath), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + + // Script info collection should behave as "noDts" + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoDts(), + expectedWatchedFilesWhenNoDts(), + ); + }); + + it(`when defining project source changes, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + // Make change, without rebuild of solution + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: dependencyTs.path, line: 1, offset: 1, endLine: 1, endOffset: 1, insertString: `function fooBar() { } +`} + }); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithDependencyChange, + expectedScriptInfos(), + expectedWatchedFiles(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + }); + it(`when defining project source changes, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session } = setupWithAction(); + + // change + // Make change, without rebuild of solution + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: dependencyTs.path, line: 1, offset: 1, endLine: 1, endOffset: 1, insertString: `function fooBar() { } +`} + }); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithDependencyChange, + expectedScriptInfos(), + expectedWatchedFiles(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + }); + + it("when projects are not built", () => { + const host = createServerHost(files); + const session = createSession(host); + openFilesForSession([dependencyTs, randomFile], session); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfosWhenNoDts(), + expectedWatchedFilesWhenNoDts(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoDts(), + expectedWatchedFilesWhenNoDts(), + ); + }); + }); + describe("when main tsconfig has disableSourceOfProjectReferenceRedirect along with project reference", () => { + function setup(onHostCreate?: OnHostCreate) { + return setupWithDependencyTs(createSessionWithDisabledProjectReferences, onHostCreate); + } + + function setupWithAction(onHostCreate?: OnHostCreate) { + return setupWithActionWith(setup, onHostCreate); + } + + it("rename locations from dependency", () => { + const { host, session } = setup(); + checkProjects(session); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfos(), + expectedWatchedFiles(), + ); + }); + + // Edit + it(`when usage file changes, document position mapper doesnt change, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + makeChangeToDependencyTs(session); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when usage file changes, document position mapper doesnt change, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + makeChangeToDependencyTs(session); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + // Edit dts to add new fn + it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsFile(host); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsFile(host); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + // Edit map file to represent added new line + it(`when dependency file's map changes, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsMapFile(host); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false + ); + }); + it(`when dependency file's map changes, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsMapFile(host); + + // action + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false + ); + }); + + it(`with depedency files map file, when file is not present`, () => { + const { host, session } = setup(host => host.deleteFile(dtsMapLocation)); + checkProjects(session); + + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + ); + }); + it(`with depedency files map file, when file is created after actions on projects`, () => { + let fileContents: string; + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => { + fileContents = host.readFile(dtsMapLocation)!; + host.deleteFile(dtsMapLocation); + }); + + host.writeFile(dtsMapLocation, fileContents!); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfos(), + expectedWatchedFiles() + ); + }); + it(`with depedency files map file, when file is deleted after actions on the projects`, () => { + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(dtsMapLocation); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + + // Script info collection should behave as fileNotPresentKey + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + ); + }); + + it(`with depedency .d.ts file, when file is not present`, () => { + const { host, session } = setup(host => host.deleteFile(dtsLocation)); + checkProjects(session); + + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfosWhenNoDts(), + expectedWatchedFilesWhenNoDts(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoDts(), + expectedWatchedFilesWhenNoDts(), + ); + }); + it(`with depedency .d.ts file, when file is created after actions on projects`, () => { + let fileContents: string; + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => { + fileContents = host.readFile(dtsLocation)!; + host.deleteFile(dtsLocation); + }); + + host.writeFile(dtsLocation, fileContents!); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfos(), + expectedWatchedFiles(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfos(), + expectedWatchedFiles() + ); + }); + it(`with depedency .d.ts file, when file is deleted after actions on the projects`, () => { + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(dtsLocation); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + // Map is collected after file open + expectedScriptInfosWhenNoDts().concat(dtsMapLocation), + expectedWatchedFilesWhenNoDts().concat(dtsPath), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + + // Script info collection should behave as "noDts" + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoDts(), + expectedWatchedFilesWhenNoDts(), + ); + }); + }); + }); + + describe("when opening depedency and usage project: goToDef and rename", () => { + function setupWithActionWith(setup: (onHostCreate?: OnHostCreate) => ReturnType, onHostCreate: OnHostCreate | undefined) { + const result = setup(onHostCreate); + result.session.executeCommandSeq(goToDefFromMainTs(1).request); + result.session.executeCommandSeq(renameFromDependencyTsWithBothProjectsOpen(1).request); + return { ...result, ...getDocumentPositionMapper(result.session) }; + } + + function verifyScriptInfoCollection( + session: TestSession, + host: TestServerHost, + expectedInfos: readonly string[], + expectedWatchedFiles: readonly string[], + ) { + return verifyScriptInfoCollectionWith(session, host, [mainTs, dependencyTs], expectedInfos, expectedWatchedFiles); + } + + describe("when main tsconfig doesnt have project reference", () => { + function setup(onHostCreate?: OnHostCreate) { + return setupWithMainTsAndDependencyTs(createSessionWithoutProjectReferences, onHostCreate); + } + + function setupWithAction(onHostCreate?: OnHostCreate) { + return setupWithActionWith(setup, onHostCreate); + } + + function checkProjects(session: TestSession) { + checkNumberOfProjects(session.getProjectService(), { configuredProjects: 3 }); + checkMainProjectWithoutProjectReferences(session); + checkDependencyProjectWith(session); + } + + function checkProjectsWithoutDts(session: TestSession) { + checkNumberOfProjects(session.getProjectService(), { configuredProjects: 3 }); + checkMainProjectWithoutProjectReferencesWithoutDts(session); + checkDependencyProjectWith(session); + } + + function expectedScriptInfosWhenMapped() { + return [mainTs.path, randomFile.path, dependencyTs.path, libFile.path, dtsPath, dtsMapLocation]; + } + + function expectedWatchedFilesWhenMapped() { + return [libFile.path, dtsPath, dtsMapPath, mainConfig.path, randomConfig.path, dependencyConfig.path]; + } + + function expectedScriptInfosWhenNoMap() { + // Because map is deleted, map and dependency are released + return removePath(expectedScriptInfosWhenMapped(), dtsMapPath); + } + + function expectedWatchedFilesWhenNoMap() { + // Watches deleted file + return expectedWatchedFilesWhenMapped(); + } + + function expectedScriptInfosAfterGotoDefWhenNoDts() { + // No dts, no map + return removePath(expectedScriptInfosWhenMapped(), dtsPath, dtsMapPath); + } + + function expectedWatchedFilesAfterGotoDefWhenNoDts() { + return removePath(expectedWatchedFilesWhenMapped(), dtsPath, dtsMapPath); + } + + function expectedScriptInfosAfterRenameWhenNoDts() { + // No dts, no map + return removePath(expectedScriptInfosWhenMapped(), dtsPath, dtsMapPath); + } + + function expectedWatchedFilesAfterRenameWhenNoDts() { + // Watches dts file but not map file + return removePath(expectedWatchedFilesWhenMapped(), dtsMapPath); + } + + it("goto Definition in usage and rename locations from defining project", () => { + const { host, session } = setup(); + checkProjects(session); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + const { dependencyMap, documentPositionMapper } = getDocumentPositionMapper(session); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + ); + }); + + // Edit + it(`when usage file changes, document position mapper doesnt change, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + makeChangeToMainTs(session); + makeChangeToDependencyTs(session); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when usage file changes, document position mapper doesnt change, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + makeChangeToMainTs(session); + makeChangeToDependencyTs(session); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + // Edit dts to add new fn + it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsFile(host); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsFile(host); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + // Edit map file to represent added new line + it(`when dependency file's map changes, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsMapFile(host); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false + ); + const { documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + newDocumentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when dependency file's map changes, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsMapFile(host); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false + ); + const { documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + newDocumentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + it(`with depedency files map file, when file is not present`, () => { + const { host, session } = setup(host => host.deleteFile(dtsMapLocation)); + checkProjects(session); + + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithNoMap, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + ); + }); + it(`with depedency files map file, when file is created after actions on projects`, () => { + let fileContents: string; + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => { + fileContents = host.readFile(dtsMapLocation)!; + host.deleteFile(dtsMapLocation); + }); + + host.writeFile(dtsMapLocation, fileContents!); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + const { dependencyMap: newDependencyMap, documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + newDependencyMap, + newDocumentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped() + ); + }); + it(`with depedency files map file, when file is deleted after actions on the projects`, () => { + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(dtsMapLocation); + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithNoMap, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + const { dependencyMap: newDependencyMap, documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + newDependencyMap, + newDocumentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + + // Script info collection should behave as fileNotPresentKey + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + ); + }); + + it(`with depedency .d.ts file, when file is not present`, () => { + const { host, session } = setup(host => host.deleteFile(dtsLocation)); + checkProjectsWithoutDts(session); + + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithNoDts, + expectedScriptInfosAfterGotoDefWhenNoDts(), + expectedWatchedFilesAfterGotoDefWhenNoDts(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfosAfterRenameWhenNoDts(), + expectedWatchedFilesAfterRenameWhenNoDts(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjectsWithoutDts(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosAfterRenameWhenNoDts(), + expectedWatchedFilesAfterRenameWhenNoDts(), + ); + }); + it(`with depedency .d.ts file, when file is created after actions on projects`, () => { + let fileContents: string; + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => { + fileContents = host.readFile(dtsLocation)!; + host.deleteFile(dtsLocation); + }); + + host.writeFile(dtsLocation, fileContents!); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + const { dependencyMap: newDependencyMap, documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + newDependencyMap, + newDocumentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped() + ); + }); + it(`with depedency .d.ts file, when file is deleted after actions on the projects`, () => { + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(dtsLocation); + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithNoDts, + // The script info for map is collected only after file open + expectedScriptInfosAfterGotoDefWhenNoDts().concat(dtsMapLocation), + expectedWatchedFilesAfterGotoDefWhenNoDts().concat(dtsMapPath), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + // The script info for map is collected only after file open + expectedScriptInfosAfterRenameWhenNoDts().concat(dtsMapLocation), + expectedWatchedFilesAfterRenameWhenNoDts().concat(dtsMapPath), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjectsWithoutDts(session); + + // Script info collection should behave as "noDts" + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosAfterRenameWhenNoDts(), + expectedWatchedFilesAfterRenameWhenNoDts(), + ); + }); + }); + describe("when main tsconfig has project reference", () => { + function setup(onHostCreate?: OnHostCreate) { + return setupWithMainTsAndDependencyTs(createSessionWithProjectReferences, onHostCreate); + } + + function setupWithAction(onHostCreate?: OnHostCreate) { + return setupWithActionWith(setup, onHostCreate); + } + + function checkProjects(session: TestSession) { + checkNumberOfProjects(session.getProjectService(), { configuredProjects: 3 }); + checkMainProjectWithProjectReferences(session); + checkDependencyProjectWith(session); + } + + function expectedScriptInfosAfterGotoDef() { + return [dependencyTs.path, libFile.path, mainTs.path, randomFile.path]; + } + + function expectedWatchedFilesAfterGotoDef() { + return [dependencyConfig.path, libFile.path, mainConfig.path, randomConfig.path]; + } + + function expectedScriptInfosAfterRenameWhenMapped() { + return expectedScriptInfosAfterGotoDef().concat(dtsLocation, dtsMapLocation); + } + + function expectedWatchedFilesAfterRenameWhenMapped() { + return expectedWatchedFilesAfterGotoDef().concat(dtsPath, dtsMapPath); + } + + function expectedScriptInfosAfterRenameWhenNoMap() { + // Map file is not present + return removePath(expectedScriptInfosAfterRenameWhenMapped(), dtsMapPath); + } + + function expectedWatchedFilesAfterRenameWhenNoMap() { + // Watches map file + return expectedWatchedFilesAfterRenameWhenMapped(); + } + + function expectedScriptInfosAfterRenameWhenNoDts() { + // map and dts not present + return removePath(expectedScriptInfosAfterRenameWhenMapped(), dtsPath, dtsMapPath); + } + + function expectedWatchedFilesAfterRenameWhenNoDts() { + // Watches dts file but not map + return removePath(expectedWatchedFilesAfterRenameWhenMapped(), dtsMapPath); + } + + it("goto Definition in usage and rename locations from defining project", () => { + const { host, session } = setup(); + checkProjects(session); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosAfterGotoDef(), + expectedWatchedFilesAfterGotoDef(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + ); + }); + + // Edit + it(`when usage file changes, document position mapper doesnt change, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + makeChangeToMainTs(session); + makeChangeToDependencyTs(session); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when usage file changes, document position mapper doesnt change, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + makeChangeToMainTs(session); + makeChangeToDependencyTs(session); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + // Edit dts to add new fn + it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsFile(host); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsFile(host); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + // Edit map file to represent added new line + it(`when dependency file's map changes, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsMapFile(host); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false + ); + }); + it(`when dependency file's map changes, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsMapFile(host); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false + ); + }); + + it(`with depedency files map file, when file is not present`, () => { + const { host, session } = setup(host => host.deleteFile(dtsMapLocation)); + checkProjects(session); + + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosAfterGotoDef(), + expectedWatchedFilesAfterGotoDef(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosAfterRenameWhenNoMap(), + expectedWatchedFilesAfterRenameWhenNoMap(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosAfterRenameWhenNoMap(), + expectedWatchedFilesAfterRenameWhenNoMap(), + ); + }); + it(`with depedency files map file, when file is created after actions on projects`, () => { + let fileContents: string; + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => { + fileContents = host.readFile(dtsMapLocation)!; + host.deleteFile(dtsMapLocation); + }); + + host.writeFile(dtsMapLocation, fileContents!); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosAfterRenameWhenNoMap(), + // Map file is reset so its not watched any more, as this action doesnt need map + removePath(expectedWatchedFilesAfterRenameWhenNoMap(), dtsMapPath), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, + /*skipMapPathInDtsInfo*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + ); + }); + it(`with depedency files map file, when file is deleted after actions on the projects`, () => { + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(dtsMapLocation); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosAfterRenameWhenNoMap(), + // Map file is reset so its not watched any more, as this action doesnt need map + removePath(expectedWatchedFilesAfterRenameWhenNoMap(), dtsMapPath), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false, + /*skipMapPathInDtsInfo*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosAfterRenameWhenNoMap(), + expectedWatchedFilesAfterRenameWhenNoMap(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + + // Script info collection should behave as fileNotPresentKey + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosAfterRenameWhenNoMap(), + expectedWatchedFilesAfterRenameWhenNoMap(), + ); + }); + + it(`with depedency .d.ts file, when file is not present`, () => { + const { host, session } = setup(host => host.deleteFile(dtsLocation)); + checkProjects(session); + + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosAfterGotoDef(), + expectedWatchedFilesAfterGotoDef(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosAfterRenameWhenNoDts(), + expectedWatchedFilesAfterRenameWhenNoDts(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosAfterRenameWhenNoDts(), + expectedWatchedFilesAfterRenameWhenNoDts(), + ); + }); + it(`with depedency .d.ts file, when file is created after actions on projects`, () => { + let fileContents: string; + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => { + fileContents = host.readFile(dtsLocation)!; + host.deleteFile(dtsLocation); + }); + + host.writeFile(dtsLocation, fileContents!); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosAfterGotoDef(), + // Since the project for dependency is not updated, the watcher from rename for dts still there + expectedWatchedFilesAfterGotoDef().concat(dtsPath), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + ); + }); + it(`with depedency .d.ts file, when file is deleted after actions on the projects`, () => { + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(dtsLocation); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + // Map collection after file open + expectedScriptInfosAfterRenameWhenNoDts().concat(dtsMapLocation), + // not watching dts since this operation doesnt need it + removePath(expectedWatchedFilesAfterRenameWhenNoDts(), dtsPath).concat(dtsMapPath), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + // Map collection after file open + expectedScriptInfosAfterRenameWhenNoDts().concat(dtsMapLocation), + expectedWatchedFilesAfterRenameWhenNoDts().concat(dtsMapPath), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + + // Script info collection should behave as "noDts" + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosAfterRenameWhenNoDts(), + expectedWatchedFilesAfterRenameWhenNoDts(), + ); + }); + + it(`when defining project source changes, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + // Make change, without rebuild of solution + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: dependencyTs.path, line: 1, offset: 1, endLine: 1, endOffset: 1, insertString: `function fooBar() { } +`} + }); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithDependencyChange, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpenWithDependencyChange, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when defining project source changes, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + // Make change, without rebuild of solution + session.executeCommandSeq({ + command: protocol.CommandTypes.Change, + arguments: { + file: dependencyTs.path, line: 1, offset: 1, endLine: 1, endOffset: 1, insertString: `function fooBar() { } +`} + }); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithDependencyChange, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpenWithDependencyChange, + expectedScriptInfosAfterRenameWhenMapped(), + expectedWatchedFilesAfterRenameWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + it("when projects are not built", () => { + const host = createServerHost(files); + const session = createSession(host); + openFilesForSession([mainTs, dependencyTs, randomFile], session); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosAfterGotoDef(), + expectedWatchedFilesAfterGotoDef(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosAfterRenameWhenNoDts(), + expectedWatchedFilesAfterRenameWhenNoDts(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosAfterRenameWhenNoDts(), + expectedWatchedFilesAfterRenameWhenNoDts(), + ); + }); + }); + describe("when main tsconfig has disableSourceOfProjectReferenceRedirect along with project reference", () => { + function setup(onHostCreate?: OnHostCreate) { + return setupWithMainTsAndDependencyTs(createSessionWithDisabledProjectReferences, onHostCreate); + } + + function setupWithAction(onHostCreate?: OnHostCreate) { + return setupWithActionWith(setup, onHostCreate); + } + + function checkProjects(session: TestSession) { + checkNumberOfProjects(session.getProjectService(), { configuredProjects: 3 }); + checkMainProjectWithDisabledProjectReferences(session); + checkDependencyProjectWith(session); + } + + function checkProjectsWithoutDts(session: TestSession) { + checkNumberOfProjects(session.getProjectService(), { configuredProjects: 3 }); + checkMainProjectWithDisabledProjectReferencesWithoutDts(session); + checkDependencyProjectWith(session); + } + + function expectedScriptInfosWhenMapped() { + return [mainTs.path, randomFile.path, dependencyTs.path, libFile.path, dtsPath, dtsMapLocation]; + } + + function expectedWatchedFilesWhenMapped() { + return [libFile.path, dtsPath, dtsMapPath, mainConfig.path, randomConfig.path, dependencyConfig.path]; + } + + function expectedScriptInfosWhenNoMap() { + // Because map is deleted, map and dependency are released + return removePath(expectedScriptInfosWhenMapped(), dtsMapPath); + } + + function expectedWatchedFilesWhenNoMap() { + // Watches deleted file + return expectedWatchedFilesWhenMapped(); + } + + function expectedScriptInfosAfterGotoDefWhenNoDts() { + // No dts, no map + return removePath(expectedScriptInfosWhenMapped(), dtsPath, dtsMapPath); + } + + function expectedWatchedFilesAfterGotoDefWhenNoDts() { + return removePath(expectedWatchedFilesWhenMapped(), dtsPath, dtsMapPath); + } + + function expectedScriptInfosAfterRenameWhenNoDts() { + // No dts, no map + return removePath(expectedScriptInfosWhenMapped(), dtsPath, dtsMapPath); + } + + function expectedWatchedFilesAfterRenameWhenNoDts() { + // Watches dts file but not map file + return removePath(expectedWatchedFilesWhenMapped(), dtsMapPath); + } + + it("goto Definition in usage and rename locations from defining project", () => { + const { host, session } = setup(); + checkProjects(session); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + const { dependencyMap, documentPositionMapper } = getDocumentPositionMapper(session); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + ); + }); + + // Edit + it(`when usage file changes, document position mapper doesnt change, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + makeChangeToMainTs(session); + makeChangeToDependencyTs(session); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when usage file changes, document position mapper doesnt change, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + makeChangeToMainTs(session); + makeChangeToDependencyTs(session); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + // Edit dts to add new fn + it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsFile(host); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsFile(host); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + // Edit map file to represent added new line + it(`when dependency file's map changes, when timeout occurs before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsMapFile(host); + host.runQueuedTimeoutCallbacks(); + checkProjects(session); + verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false + ); + const { documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + newDocumentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + it(`when dependency file's map changes, when timeout does not occur before request`, () => { + // Create DocumentPositionMapper + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // change + changeDtsMapFile(host); + + // action + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false + ); + const { documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + newDocumentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + }); + + it(`with depedency files map file, when file is not present`, () => { + const { host, session } = setup(host => host.deleteFile(dtsMapLocation)); + checkProjects(session); + + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithNoMap, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + ); + }); + it(`with depedency files map file, when file is created after actions on projects`, () => { + let fileContents: string; + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => { + fileContents = host.readFile(dtsMapLocation)!; + host.deleteFile(dtsMapLocation); + }); + + host.writeFile(dtsMapLocation, fileContents!); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + const { dependencyMap: newDependencyMap, documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + newDependencyMap, + newDocumentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped() + ); + }); + it(`with depedency files map file, when file is deleted after actions on the projects`, () => { + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(dtsMapLocation); + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithNoMap, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + const { dependencyMap: newDependencyMap, documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + newDependencyMap, + newDocumentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + + // Script info collection should behave as fileNotPresentKey + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenNoMap(), + expectedWatchedFilesWhenNoMap(), + ); + }); + + it(`with depedency .d.ts file, when file is not present`, () => { + const { host, session } = setup(host => host.deleteFile(dtsLocation)); + checkProjectsWithoutDts(session); + + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithNoDts, + expectedScriptInfosAfterGotoDefWhenNoDts(), + expectedWatchedFilesAfterGotoDefWhenNoDts(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + expectedScriptInfosAfterRenameWhenNoDts(), + expectedWatchedFilesAfterRenameWhenNoDts(), + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjectsWithoutDts(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosAfterRenameWhenNoDts(), + expectedWatchedFilesAfterRenameWhenNoDts(), + ); + }); + it(`with depedency .d.ts file, when file is created after actions on projects`, () => { + let fileContents: string; + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => { + fileContents = host.readFile(dtsLocation)!; + host.deleteFile(dtsLocation); + }); + + host.writeFile(dtsLocation, fileContents!); + verifyAllFnAction( + session, + host, + goToDefFromMainTs, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false + ); + const { dependencyMap: newDependencyMap, documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); + verifyAllFnAction( + session, + host, + renameFromDependencyTsWithBothProjectsOpen, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped(), + newDependencyMap, + newDocumentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjects(session); + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosWhenMapped(), + expectedWatchedFilesWhenMapped() + ); + }); + it(`with depedency .d.ts file, when file is deleted after actions on the projects`, () => { + const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(); + + // The dependency file is deleted when orphan files are collected + host.deleteFile(dtsLocation); + verifyAllFnAction( + session, + host, + goToDefFromMainTsWithNoDts, + // The script info for map is collected only after file open + expectedScriptInfosAfterGotoDefWhenNoDts().concat(dtsMapLocation), + expectedWatchedFilesAfterGotoDefWhenNoDts().concat(dtsMapPath), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + verifyAllFnAction( + session, + host, + renameFromDependencyTs, + // The script info for map is collected only after file open + expectedScriptInfosAfterRenameWhenNoDts().concat(dtsMapLocation), + expectedWatchedFilesAfterRenameWhenNoDts().concat(dtsMapPath), + dependencyMap, + documentPositionMapper, + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true + ); + checkProjectsWithoutDts(session); + + // Script info collection should behave as "noDts" + verifyScriptInfoCollection( + session, + host, + expectedScriptInfosAfterRenameWhenNoDts(), + expectedWatchedFilesAfterRenameWhenNoDts(), + ); + }); + }); + }); + }); +} diff --git a/src/testRunner/unittests/tsserver/projectsWithReferences.ts b/src/testRunner/unittests/tsserver/projectsWithReferences.ts new file mode 100644 index 0000000000000..5af193a70d88e --- /dev/null +++ b/src/testRunner/unittests/tsserver/projectsWithReferences.ts @@ -0,0 +1,528 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: projects with references: invoking when references are already built", () => { + it("on sample project", () => { + const coreConfig = TestFSWithWatch.getTsBuildProjectFile("sample1", "core/tsconfig.json"); + const coreIndex = TestFSWithWatch.getTsBuildProjectFile("sample1", "core/index.ts"); + const coreAnotherModule = TestFSWithWatch.getTsBuildProjectFile("sample1", "core/anotherModule.ts"); + const coreSomeDecl = TestFSWithWatch.getTsBuildProjectFile("sample1", "core/some_decl.d.ts"); + const logicConfig = TestFSWithWatch.getTsBuildProjectFile("sample1", "logic/tsconfig.json"); + const logicIndex = TestFSWithWatch.getTsBuildProjectFile("sample1", "logic/index.ts"); + const testsConfig = TestFSWithWatch.getTsBuildProjectFile("sample1", "tests/tsconfig.json"); + const testsIndex = TestFSWithWatch.getTsBuildProjectFile("sample1", "tests/index.ts"); + const host = createServerHost([libFile, coreConfig, coreIndex, coreAnotherModule, coreSomeDecl, logicConfig, logicIndex, testsConfig, testsIndex]); + const service = createProjectService(host); + service.openClientFile(testsIndex.path); + + checkWatchedFilesDetailed(host, [coreConfig, coreIndex, coreAnotherModule, logicConfig, logicIndex, testsConfig, libFile].map(f => f.path.toLowerCase()), 1); + checkWatchedDirectoriesDetailed(host, emptyArray, 1, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, [ + TestFSWithWatch.getTsBuildProjectFilePath("sample1", "core"), + TestFSWithWatch.getTsBuildProjectFilePath("sample1", "logic"), + ...getTypeRootsFromLocation(TestFSWithWatch.getTsBuildProjectFilePath("sample1", "tests")) + ], 1, /*recursive*/ true); + + // local edit in ts file + host.appendFile(logicIndex.path, `function foo() {}`); + host.checkTimeoutQueueLengthAndRun(2); + checkNumberOfProjects(service, { configuredProjects: 1 }); + checkProjectActualFiles(service.configuredProjects.get(testsConfig.path)!, [libFile.path, coreIndex.path, coreAnotherModule.path, logicIndex.path, testsIndex.path, testsConfig.path]); + + // non local edit in ts file + host.appendFile(logicIndex.path, `export function gfoo() {}`); + host.checkTimeoutQueueLengthAndRun(2); + checkNumberOfProjects(service, { configuredProjects: 1 }); + checkProjectActualFiles(service.configuredProjects.get(testsConfig.path)!, [libFile.path, coreIndex.path, coreAnotherModule.path, logicIndex.path, testsIndex.path, testsConfig.path]); + + // change in project reference config file + host.writeFile(logicConfig.path, JSON.stringify({ + compilerOptions: { composite: true, declaration: true, declarationDir: "decls" }, + references: [{ path: "../core" }] + })); + host.checkTimeoutQueueLengthAndRun(2); + checkNumberOfProjects(service, { configuredProjects: 1 }); + checkProjectActualFiles(service.configuredProjects.get(testsConfig.path)!, [libFile.path, coreIndex.path, coreAnotherModule.path, logicIndex.path, testsIndex.path, testsConfig.path]); + }); + + describe("on transitive references in different folders", () => { + function createService() { + const aConfig: File = { + path: `${tscWatch.projectRoot}/a/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { composite: true }, + files: ["index.ts"] + }), + }; + const bConfig: File = { + path: `${tscWatch.projectRoot}/b/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { composite: true, baseUrl: "./", paths: { "@ref/*": ["../*"] } }, + files: ["index.ts"], + references: [{ path: `../a` }] + }), + }; + const cConfig: File = { + path: `${tscWatch.projectRoot}/c/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { baseUrl: "./", paths: { "@ref/*": ["../refs/*"] } }, + files: ["index.ts"], + references: [{ path: `../b` }] + }), + }; + const aTs: File = { + path: `${tscWatch.projectRoot}/a/index.ts`, + content: `export class A {}`, + }; + const bTs: File = { + path: `${tscWatch.projectRoot}/b/index.ts`, + content: `import {A} from '@ref/a'; +export const b = new A();`, + }; + const cTs: File = { + path: `${tscWatch.projectRoot}/c/index.ts`, + content: `import {b} from '../b'; +import {X} from "@ref/a"; +b; +X;`, + }; + const refsTs: File = { + path: `${tscWatch.projectRoot}/refs/a.d.ts`, + content: `export class X {} +export class A {}` + }; + const host = createServerHost([libFile, aConfig, bConfig, cConfig, aTs, bTs, cTs, refsTs]); + const service = createProjectService(host); + service.openClientFile(cTs.path); + return { host, service, aConfig, bConfig, cConfig, aTs, bTs, cTs, refsTs }; + } + + it("non local edit", () => { + const { host, service, aConfig, bConfig, cConfig, aTs, bTs, cTs, refsTs } = createService(); + checkNumberOfProjects(service, { configuredProjects: 1 }); + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, aTs.path, refsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, aConfig.path, bConfig.path, cConfig.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, [ + `${tscWatch.projectRoot}/a`, // Failed to package json + `${tscWatch.projectRoot}/b`, // Failed to package json + `${tscWatch.projectRoot}/refs`, // Failed lookup since refs/a.ts does not exist + ...getTypeRootsFromLocation(`${tscWatch.projectRoot}/c`) + ], 1, /*recursive*/ true); + checkOrphanScriptInfos(service, emptyArray); + + // non local edit + host.appendFile(bTs.path, `export function gFoo() { }`); + host.checkTimeoutQueueLengthAndRun(2); + checkNumberOfProjects(service, { configuredProjects: 1 }); + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, aTs.path, refsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, aConfig.path, bConfig.path, cConfig.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, [ + `${tscWatch.projectRoot}/a`, // Failed to package json + `${tscWatch.projectRoot}/b`, // Failed to package json + `${tscWatch.projectRoot}/refs`, // Failed lookup since refs/a.ts does not exist + ...getTypeRootsFromLocation(`${tscWatch.projectRoot}/c`) + ], 1, /*recursive*/ true); + checkOrphanScriptInfos(service, emptyArray); + }); + + it("edit on config file", () => { + const { host, service, aConfig, bConfig, cConfig, aTs, bTs, cTs, refsTs } = createService(); + const nRefsTs: File = { + path: `${tscWatch.projectRoot}/nrefs/a.d.ts`, + content: refsTs.content + }; + const cTsConfigJson = JSON.parse(cConfig.content); + host.ensureFileOrFolder(nRefsTs); + cTsConfigJson.compilerOptions.paths = { "@ref/*": ["../nrefs/*"] }; + host.writeFile(cConfig.path, JSON.stringify(cTsConfigJson)); + host.checkTimeoutQueueLengthAndRun(2); + checkNumberOfProjects(service, { configuredProjects: 1 }); + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, aTs.path, nRefsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, aConfig.path, bConfig.path, cConfig.path, nRefsTs.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, [ + `${tscWatch.projectRoot}/a`, // Failed to package json + `${tscWatch.projectRoot}/b`, // Failed to package json + `${tscWatch.projectRoot}/nrefs`, // Failed lookup since nrefs/a.ts does not exist + ...getTypeRootsFromLocation(`${tscWatch.projectRoot}/c`) + ], 1, /*recursive*/ true); + // Script infos arent deleted till next file open + checkOrphanScriptInfos(service, [refsTs.path]); + + // revert the edit on config file + host.writeFile(cConfig.path, cConfig.content); + host.checkTimeoutQueueLengthAndRun(2); + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, aTs.path, refsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, aConfig.path, bConfig.path, cConfig.path, nRefsTs.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, [ + `${tscWatch.projectRoot}/a`, // Failed to package json + `${tscWatch.projectRoot}/b`, // Failed to package json + `${tscWatch.projectRoot}/refs`, // Failed lookup since refs/a.ts does not exist + ...getTypeRootsFromLocation(`${tscWatch.projectRoot}/c`) + ], 1, /*recursive*/ true); + // Script infos arent deleted till next file open + checkOrphanScriptInfos(service, [nRefsTs.path]); + }); + + it("edit in referenced config file", () => { + const { host, service, aConfig, bConfig, cConfig, aTs, bTs, cTs, refsTs } = createService(); + const nRefsTs: File = { + path: `${tscWatch.projectRoot}/nrefs/a.d.ts`, + content: refsTs.content + }; + const bTsConfigJson = JSON.parse(bConfig.content); + host.ensureFileOrFolder(nRefsTs); + bTsConfigJson.compilerOptions.paths = { "@ref/*": ["../nrefs/*"] }; + host.writeFile(bConfig.path, JSON.stringify(bTsConfigJson)); + host.checkTimeoutQueueLengthAndRun(2); + checkNumberOfProjects(service, { configuredProjects: 1 }); + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, refsTs.path, nRefsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, aConfig.path, bConfig.path, cConfig.path, nRefsTs.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, [ + `${tscWatch.projectRoot}/b`, // Failed to package json + `${tscWatch.projectRoot}/refs`, // Failed lookup since refs/a.ts does not exist + `${tscWatch.projectRoot}/nrefs`, // Failed lookup since nrefs/a.ts does not exist + ...getTypeRootsFromLocation(`${tscWatch.projectRoot}/c`) + ], 1, /*recursive*/ true); + // Script infos arent deleted till next file open + checkOrphanScriptInfos(service, [aTs.path]); + + // revert the edit on config file + host.writeFile(bConfig.path, bConfig.content); + host.checkTimeoutQueueLengthAndRun(2); + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, aTs.path, refsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, aConfig.path, bConfig.path, cConfig.path, nRefsTs.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, [ + `${tscWatch.projectRoot}/a`, // Failed to package json + `${tscWatch.projectRoot}/b`, // Failed to package json + `${tscWatch.projectRoot}/refs`, // Failed lookup since refs/a.ts does not exist + ...getTypeRootsFromLocation(`${tscWatch.projectRoot}/c`) + ], 1, /*recursive*/ true); + // Script infos arent deleted till next file open + checkOrphanScriptInfos(service, [nRefsTs.path]); + }); + + it("deleting referenced config file", () => { + const { host, service, aConfig, bConfig, cConfig, aTs, bTs, cTs, refsTs } = createService(); + host.deleteFile(bConfig.path); + host.checkTimeoutQueueLengthAndRun(3); // Schedules failed lookup invalidation + checkNumberOfProjects(service, { configuredProjects: 1 }); + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, refsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, bConfig.path, cConfig.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, [ + `${tscWatch.projectRoot}/b`, // Failed to package json + `${tscWatch.projectRoot}/refs`, // Failed lookup since refs/a.ts does not exist + ...getTypeRootsFromLocation(`${tscWatch.projectRoot}/c`) + ], 1, /*recursive*/ true); + // Script infos arent deleted till next file open + checkOrphanScriptInfos(service, [aTs.path]); + + // revert + host.writeFile(bConfig.path, bConfig.content); + host.checkTimeoutQueueLengthAndRun(3); // Schedules failed lookup invalidation + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, aTs.path, refsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, aConfig.path, bConfig.path, cConfig.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, [ + `${tscWatch.projectRoot}/a`, // Failed to package json + `${tscWatch.projectRoot}/b`, // Failed to package json + `${tscWatch.projectRoot}/refs`, // Failed lookup since refs/a.ts does not exist + ...getTypeRootsFromLocation(`${tscWatch.projectRoot}/c`) + ], 1, /*recursive*/ true); + checkOrphanScriptInfos(service, emptyArray); + }); + + it("deleting transitively referenced config file", () => { + const { host, service, aConfig, bConfig, cConfig, aTs, bTs, cTs, refsTs } = createService(); + host.deleteFile(aConfig.path); + host.checkTimeoutQueueLengthAndRun(3); // Schedules failed lookup invalidation + checkNumberOfProjects(service, { configuredProjects: 1 }); + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, aTs.path, refsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, aConfig.path, bConfig.path, cConfig.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, [ + `${tscWatch.projectRoot}/a`, // Failed to package json + `${tscWatch.projectRoot}/b`, // Failed to package json + `${tscWatch.projectRoot}/refs`, // Failed lookup since refs/a.ts does not exist + ...getTypeRootsFromLocation(`${tscWatch.projectRoot}/c`) + ], 1, /*recursive*/ true); + checkOrphanScriptInfos(service, emptyArray); + + // revert + host.writeFile(aConfig.path, aConfig.content); + host.checkTimeoutQueueLengthAndRun(3); // Schedules failed lookup invalidation + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, aTs.path, refsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, aConfig.path, bConfig.path, cConfig.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, [ + `${tscWatch.projectRoot}/a`, // Failed to package json + `${tscWatch.projectRoot}/b`, // Failed to package json + `${tscWatch.projectRoot}/refs`, // Failed lookup since refs/a.ts does not exist + ...getTypeRootsFromLocation(`${tscWatch.projectRoot}/c`) + ], 1, /*recursive*/ true); + checkOrphanScriptInfos(service, emptyArray); + }); + }); + + describe("on transitive references in different folders without files", () => { + function createService() { + const aConfig: File = { + path: `${tscWatch.projectRoot}/a/tsconfig.json`, + content: JSON.stringify({ compilerOptions: { composite: true } }), + }; + const bConfig: File = { + path: `${tscWatch.projectRoot}/b/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { composite: true, baseUrl: "./", paths: { "@ref/*": ["../*"] } }, + references: [{ path: `../a` }] + }), + }; + const cConfig: File = { + path: `${tscWatch.projectRoot}/c/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { baseUrl: "./", paths: { "@ref/*": ["../refs/*"] } }, + references: [{ path: `../b` }] + }), + }; + const aTs: File = { + path: `${tscWatch.projectRoot}/a/index.ts`, + content: `export class A {}`, + }; + const bTs: File = { + path: `${tscWatch.projectRoot}/b/index.ts`, + content: `import {A} from '@ref/a'; +export const b = new A();`, + }; + const cTs: File = { + path: `${tscWatch.projectRoot}/c/index.ts`, + content: `import {b} from '../b'; +import {X} from "@ref/a"; +b; +X;`, + }; + const refsTs: File = { + path: `${tscWatch.projectRoot}/refs/a.d.ts`, + content: `export class X {} +export class A {}` + }; + const host = createServerHost([libFile, aConfig, bConfig, cConfig, aTs, bTs, cTs, refsTs]); + const service = createProjectService(host); + service.openClientFile(cTs.path); + return { host, service, aConfig, bConfig, cConfig, aTs, bTs, cTs, refsTs }; + } + + it("non local edit", () => { + const { host, service, aConfig, bConfig, cConfig, aTs, bTs, cTs, refsTs } = createService(); + checkNumberOfProjects(service, { configuredProjects: 1 }); + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, aTs.path, refsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, aConfig.path, bConfig.path, cConfig.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + const expectedWatchedDirectoriesDetailed = arrayToMap([ + `${tscWatch.projectRoot}/c`, // Wild card directory + `${tscWatch.projectRoot}/refs`, // Failed lookup since refs/a.ts does not exist + ...getTypeRootsFromLocation(`${tscWatch.projectRoot}/c`) + ], identity, () => 1); + expectedWatchedDirectoriesDetailed.set(`${tscWatch.projectRoot}/a`, 2); // Failed to package json and wild card directory + expectedWatchedDirectoriesDetailed.set(`${tscWatch.projectRoot}/b`, 2); // Failed to package json and wild card directory + checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesDetailed, /*recursive*/ true); + checkOrphanScriptInfos(service, emptyArray); + + // non local edit + host.appendFile(bTs.path, `export function gFoo() { }`); + host.checkTimeoutQueueLengthAndRun(2); + checkNumberOfProjects(service, { configuredProjects: 1 }); + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, aTs.path, refsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, aConfig.path, bConfig.path, cConfig.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesDetailed, /*recursive*/ true); + checkOrphanScriptInfos(service, emptyArray); + }); + + it("edit on config file", () => { + const { host, service, aConfig, bConfig, cConfig, aTs, bTs, cTs, refsTs } = createService(); + const nRefsTs: File = { + path: `${tscWatch.projectRoot}/nrefs/a.d.ts`, + content: refsTs.content + }; + const cTsConfigJson = JSON.parse(cConfig.content); + host.ensureFileOrFolder(nRefsTs); + cTsConfigJson.compilerOptions.paths = { "@ref/*": ["../nrefs/*"] }; + host.writeFile(cConfig.path, JSON.stringify(cTsConfigJson)); + host.checkTimeoutQueueLengthAndRun(2); + checkNumberOfProjects(service, { configuredProjects: 1 }); + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, aTs.path, nRefsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, aConfig.path, bConfig.path, cConfig.path, nRefsTs.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + const expectedWatchedDirectoriesDetailed = arrayToMap([ + `${tscWatch.projectRoot}/c`, // Wild card directory + `${tscWatch.projectRoot}/nrefs`, // Failed lookup since nrefs/a.ts does not exist + ...getTypeRootsFromLocation(`${tscWatch.projectRoot}/c`) + ], identity, () => 1); + expectedWatchedDirectoriesDetailed.set(`${tscWatch.projectRoot}/a`, 2); // Failed to package json and wild card directory + expectedWatchedDirectoriesDetailed.set(`${tscWatch.projectRoot}/b`, 2); // Failed to package json and wild card directory + checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesDetailed, /*recursive*/ true); + // Script infos arent deleted till next file open + checkOrphanScriptInfos(service, [refsTs.path]); + + // revert the edit on config file + host.writeFile(cConfig.path, cConfig.content); + host.checkTimeoutQueueLengthAndRun(2); + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, aTs.path, refsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, aConfig.path, bConfig.path, cConfig.path, nRefsTs.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + expectedWatchedDirectoriesDetailed.delete(`${tscWatch.projectRoot}/nrefs`); + expectedWatchedDirectoriesDetailed.set(`${tscWatch.projectRoot}/refs`, 1); // Failed lookup since refs/a.ts does not exist + checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesDetailed, /*recursive*/ true); + // Script infos arent deleted till next file open + checkOrphanScriptInfos(service, [nRefsTs.path]); + }); + + it("edit in referenced config file", () => { + const { host, service, aConfig, bConfig, cConfig, aTs, bTs, cTs, refsTs } = createService(); + const nRefsTs: File = { + path: `${tscWatch.projectRoot}/nrefs/a.d.ts`, + content: refsTs.content + }; + const bTsConfigJson = JSON.parse(bConfig.content); + host.ensureFileOrFolder(nRefsTs); + bTsConfigJson.compilerOptions.paths = { "@ref/*": ["../nrefs/*"] }; + host.writeFile(bConfig.path, JSON.stringify(bTsConfigJson)); + host.checkTimeoutQueueLengthAndRun(2); + checkNumberOfProjects(service, { configuredProjects: 1 }); + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, refsTs.path, nRefsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, aConfig.path, bConfig.path, cConfig.path, nRefsTs.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + const expectedWatchedDirectoriesDetailed = arrayToMap([ + `${tscWatch.projectRoot}/a`, // Wild card directory + `${tscWatch.projectRoot}/c`, // Wild card directory + `${tscWatch.projectRoot}/refs`, // Failed lookup since refs/a.ts does not exist + `${tscWatch.projectRoot}/nrefs`, // Failed lookup since nrefs/a.ts does not exist + ...getTypeRootsFromLocation(`${tscWatch.projectRoot}/c`) + ], identity, () => 1); + expectedWatchedDirectoriesDetailed.set(`${tscWatch.projectRoot}/b`, 2); // Failed to package json and wild card directory + checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesDetailed, /*recursive*/ true); + // Script infos arent deleted till next file open + checkOrphanScriptInfos(service, [aTs.path]); + + // revert the edit on config file + host.writeFile(bConfig.path, bConfig.content); + host.checkTimeoutQueueLengthAndRun(2); + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, aTs.path, refsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, aConfig.path, bConfig.path, cConfig.path, nRefsTs.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + expectedWatchedDirectoriesDetailed.delete(`${tscWatch.projectRoot}/nrefs`); + expectedWatchedDirectoriesDetailed.set(`${tscWatch.projectRoot}/a`, 2); // Failed to package json and wild card directory + checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesDetailed, /*recursive*/ true); + // Script infos arent deleted till next file open + checkOrphanScriptInfos(service, [nRefsTs.path]); + }); + + it("deleting referenced config file", () => { + const { host, service, aConfig, bConfig, cConfig, aTs, bTs, cTs, refsTs } = createService(); + host.deleteFile(bConfig.path); + host.checkTimeoutQueueLengthAndRun(3); // Schedules failed lookup invalidation + checkNumberOfProjects(service, { configuredProjects: 1 }); + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, refsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, bConfig.path, cConfig.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, [ + `${tscWatch.projectRoot}/c`, // Wild card directory + `${tscWatch.projectRoot}/b`, // Failed to package json + `${tscWatch.projectRoot}/refs`, // Failed lookup since refs/a.ts does not exist + ...getTypeRootsFromLocation(`${tscWatch.projectRoot}/c`) + ], 1, /*recursive*/ true); + // Script infos arent deleted till next file open + checkOrphanScriptInfos(service, [aTs.path]); + + // revert + host.writeFile(bConfig.path, bConfig.content); + host.checkTimeoutQueueLengthAndRun(3); // Schedules failed lookup invalidation + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, aTs.path, refsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, aConfig.path, bConfig.path, cConfig.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + const expectedWatchedDirectoriesDetailed = arrayToMap([ + `${tscWatch.projectRoot}/c`, // Wild card directory + `${tscWatch.projectRoot}/refs`, // Failed lookup since refs/a.ts does not exist + ...getTypeRootsFromLocation(`${tscWatch.projectRoot}/c`) + ], identity, () => 1); + expectedWatchedDirectoriesDetailed.set(`${tscWatch.projectRoot}/a`, 2); // Failed to package json and wild card directory + expectedWatchedDirectoriesDetailed.set(`${tscWatch.projectRoot}/b`, 2); // Failed to package json and wild card directory + checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesDetailed, /*recursive*/ true); + checkOrphanScriptInfos(service, emptyArray); + }); + + it("deleting transitively referenced config file", () => { + const { host, service, aConfig, bConfig, cConfig, aTs, bTs, cTs, refsTs } = createService(); + host.deleteFile(aConfig.path); + host.checkTimeoutQueueLengthAndRun(3); // Schedules failed lookup invalidation + checkNumberOfProjects(service, { configuredProjects: 1 }); + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, aTs.path, refsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, aConfig.path, bConfig.path, cConfig.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + const expectedWatchedDirectoriesDetailed = arrayToMap([ + `${tscWatch.projectRoot}/c`, // Wild card directory + `${tscWatch.projectRoot}/a`, // Failed to package json + `${tscWatch.projectRoot}/refs`, // Failed lookup since refs/a.ts does not exist + ...getTypeRootsFromLocation(`${tscWatch.projectRoot}/c`) + ], identity, () => 1); + expectedWatchedDirectoriesDetailed.set(`${tscWatch.projectRoot}/b`, 2); // Failed to package json and wild card directory + checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesDetailed, /*recursive*/ true); + checkOrphanScriptInfos(service, emptyArray); + + // revert + host.writeFile(aConfig.path, aConfig.content); + host.checkTimeoutQueueLengthAndRun(3); // Schedules failed lookup invalidation + checkProjectActualFiles(service.configuredProjects.get(cConfig.path)!, [libFile.path, cTs.path, cConfig.path, bTs.path, aTs.path, refsTs.path]); + checkWatchedFilesDetailed(host, [libFile.path, aTs.path, bTs.path, refsTs.path, aConfig.path, bConfig.path, cConfig.path], 1); + checkWatchedDirectoriesDetailed(host, [ + tscWatch.projectRoot // watches for directories created for resolution of b + ], 1, /*recursive*/ false); + expectedWatchedDirectoriesDetailed.set(`${tscWatch.projectRoot}/a`, 2); // Failed to package json and wild card directory + checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesDetailed, /*recursive*/ true); + checkOrphanScriptInfos(service, emptyArray); + }); + }); + }); +} \ No newline at end of file diff --git a/src/tsserver/nodeServer.ts b/src/tsserver/nodeServer.ts index 97aa0a198e86d..f2fadc7422706 100644 --- a/src/tsserver/nodeServer.ts +++ b/src/tsserver/nodeServer.ts @@ -180,21 +180,6 @@ namespace ts.server { const originalWatchDirectory: ServerHost["watchDirectory"] = sys.watchDirectory.bind(sys); const logger = createLogger(); - // REVIEW: for now this implementation uses polling. - // The advantage of polling is that it works reliably - // on all os and with network mounted files. - // For 90 referenced files, the average time to detect - // changes is 2*msInterval (by default 5 seconds). - // The overhead of this is .04 percent (1/2500) with - // average pause of < 1 millisecond (and max - // pause less than 1.5 milliseconds); question is - // do we anticipate reference sets in the 100s and - // do we care about waiting 10-20 seconds to detect - // changes for large reference sets? If so, do we want - // to increase the chunk size or decrease the interval - // time dynamically to match the large reference set? - const pollingWatchedFileSet = createPollingWatchedFileSet(); - const pending: Buffer[] = []; let canWrite = true; @@ -248,12 +233,20 @@ namespace ts.server { // Override sys.write because fs.writeSync is not reliable on Node 4 sys.write = (s: string) => writeMessage(sys.bufferFrom!(s, "utf8") as globalThis.Buffer); - sys.watchFile = (fileName, callback) => { - const watchedFile = pollingWatchedFileSet.addFile(fileName, callback); - return { - close: () => pollingWatchedFileSet.removeFile(watchedFile) - }; - }; + // REVIEW: for now this implementation uses polling. + // The advantage of polling is that it works reliably + // on all os and with network mounted files. + // For 90 referenced files, the average time to detect + // changes is 2*msInterval (by default 5 seconds). + // The overhead of this is .04 percent (1/2500) with + // average pause of < 1 millisecond (and max + // pause less than 1.5 milliseconds); question is + // do we anticipate reference sets in the 100s and + // do we care about waiting 10-20 seconds to detect + // changes for large reference sets? If so, do we want + // to increase the chunk size or decrease the interval + // time dynamically to match the large reference set? + sys.defaultWatchFileKind = () => WatchFileKind.FixedChunkSizePolling; /* eslint-disable no-restricted-globals */ sys.setTimeout = setTimeout; @@ -324,89 +317,6 @@ namespace ts.server { const logVerbosity = cmdLineVerbosity || envLogOptions.detailLevel; 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 - - // average async stat takes about 30 microseconds - // set chunk size to do 30 files in < 1 millisecond - function createPollingWatchedFileSet(interval = 2500, chunkSize = 30) { - const watchedFiles: WatchedFile[] = []; - let nextFileToCheck = 0; - return { getModifiedTime, poll, startWatchTimer, addFile, removeFile }; - - function getModifiedTime(fileName: string): Date { - // Caller guarantees that `fileName` exists, so there'd be no benefit from throwIfNoEntry - return fs.statSync(fileName).mtime; - } - - function poll(checkedIndex: number) { - const watchedFile = watchedFiles[checkedIndex]; - if (!watchedFile) { - return; - } - - fs.stat(watchedFile.fileName, (err, stats) => { - if (err) { - if (err.code === "ENOENT") { - if (watchedFile.mtime.getTime() !== 0) { - watchedFile.mtime = missingFileModifiedTime; - watchedFile.callback(watchedFile.fileName, FileWatcherEventKind.Deleted); - } - } - else { - watchedFile.callback(watchedFile.fileName, FileWatcherEventKind.Changed); - } - } - else { - onWatchedFileStat(watchedFile, stats.mtime); - } - }); - } - - // this implementation uses polling and - // stat due to inconsistencies of fs.watch - // and efficiency of stat on modern filesystems - function startWatchTimer() { - // eslint-disable-next-line no-restricted-globals - setInterval(() => { - let count = 0; - let nextToCheck = nextFileToCheck; - let firstCheck = -1; - while ((count < chunkSize) && (nextToCheck !== firstCheck)) { - poll(nextToCheck); - if (firstCheck < 0) { - firstCheck = nextToCheck; - } - nextToCheck++; - if (nextToCheck === watchedFiles.length) { - nextToCheck = 0; - } - count++; - } - nextFileToCheck = nextToCheck; - }, interval); - } - - function addFile(fileName: string, callback: FileWatcherCallback): WatchedFile { - const file: WatchedFile = { - fileName, - callback, - mtime: sys.fileExists(fileName) - ? getModifiedTime(fileName) - : missingFileModifiedTime // Any subsequent modification will occur after this time - }; - - watchedFiles.push(file); - if (watchedFiles.length === 1) { - startWatchTimer(); - } - return file; - } - - function removeFile(file: WatchedFile) { - unorderedRemoveItem(watchedFiles, file); - } - } function writeMessage(buf: Buffer) { if (!canWrite) { @@ -833,7 +743,7 @@ namespace ts.server { exit() { this.logger.info("Exiting..."); this.projectService.closeLog(); - tracing?.stopTracing(ts.emptyArray); + tracing?.stopTracing(); process.exit(0); } @@ -861,7 +771,7 @@ namespace ts.server { ? stripQuotes(commandLineTraceDir) : process.env.TSS_TRACE; if (traceDir) { - startTracing(tracingEnabled.Mode.Server, traceDir); + startTracing("server", traceDir); } const ioSession = new IOSession(); diff --git a/tests/baselines/reference/APISample_jsdoc.js b/tests/baselines/reference/APISample_jsdoc.js index 9c1dd5f824fdb..50288c1237ea5 100644 --- a/tests/baselines/reference/APISample_jsdoc.js +++ b/tests/baselines/reference/APISample_jsdoc.js @@ -35,7 +35,7 @@ function parseCommentsIntoDefinition(this: any, } // jsdocs are separate from comments - const jsdocs = symbol.getJsDocTags(); + const jsdocs = symbol.getJsDocTags(this.checker); jsdocs.forEach(doc => { // if we have @TJS-... annotations, we have to parse them const { name, text } = doc; @@ -59,7 +59,7 @@ function getAnnotations(this: any, node: ts.Node): Annotations | undefined { return undefined; } - const jsDocTags: ts.JSDocTagInfo[] = symbol.getJsDocTags(); + const jsDocTags: ts.JSDocTagInfo[] = symbol.getJsDocTags(this.checker); if (!jsDocTags || !jsDocTags.length) { return undefined; } @@ -143,7 +143,7 @@ function parseCommentsIntoDefinition(symbol, definition, otherAnnotations) { definition.description = comments.map(function (comment) { return comment.kind === "lineBreak" ? comment.text : comment.text.trim().replace(/\r\n/g, "\n"); }).join(""); } // jsdocs are separate from comments - var jsdocs = symbol.getJsDocTags(); + var jsdocs = symbol.getJsDocTags(this.checker); jsdocs.forEach(function (doc) { // if we have @TJS-... annotations, we have to parse them var name = doc.name, text = doc.text; @@ -162,7 +162,7 @@ function getAnnotations(node) { if (!symbol) { return undefined; } - var jsDocTags = symbol.getJsDocTags(); + var jsDocTags = symbol.getJsDocTags(this.checker); if (!jsDocTags || !jsDocTags.length) { return undefined; } diff --git a/tests/baselines/reference/ES5For-ofTypeCheck10.errors.txt b/tests/baselines/reference/ES5For-ofTypeCheck10.errors.txt index 6622033a687db..4be1397aab91a 100644 --- a/tests/baselines/reference/ES5For-ofTypeCheck10.errors.txt +++ b/tests/baselines/reference/ES5For-ofTypeCheck10.errors.txt @@ -1,5 +1,5 @@ -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. +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 TS2495: Type 'StringIterator' is not an array type or a string type. ==== tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts (2 errors) ==== @@ -13,11 +13,11 @@ tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts(14,1 } [Symbol.iterator]() { ~~~~~~ -!!! 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. +!!! 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; } } for (var v of new StringIterator) { } ~~~~~~~~~~~~~~~~~~ -!!! error TS2569: Type 'StringIterator' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators. \ No newline at end of file +!!! error TS2495: Type 'StringIterator' is not an array type or a string type. \ No newline at end of file diff --git a/tests/baselines/reference/ES5SymbolProperty1.errors.txt b/tests/baselines/reference/ES5SymbolProperty1.errors.txt deleted file mode 100644 index 1b135dcc91670..0000000000000 --- a/tests/baselines/reference/ES5SymbolProperty1.errors.txt +++ /dev/null @@ -1,16 +0,0 @@ -tests/cases/conformance/Symbols/ES5SymbolProperty1.ts(7,6): error TS2471: A computed property name of the form 'Symbol.foo' must be of type 'symbol'. - - -==== tests/cases/conformance/Symbols/ES5SymbolProperty1.ts (1 errors) ==== - interface SymbolConstructor { - foo: string; - } - var Symbol: SymbolConstructor; - - var obj = { - [Symbol.foo]: 0 - ~~~~~~~~~~ -!!! error TS2471: A computed property name of the form 'Symbol.foo' must be of type 'symbol'. - } - - obj[Symbol.foo]; \ No newline at end of file diff --git a/tests/baselines/reference/ES5SymbolProperty1.types b/tests/baselines/reference/ES5SymbolProperty1.types index ebbd3fb8112ee..7b6ac592cbc9c 100644 --- a/tests/baselines/reference/ES5SymbolProperty1.types +++ b/tests/baselines/reference/ES5SymbolProperty1.types @@ -7,8 +7,8 @@ var Symbol: SymbolConstructor; >Symbol : SymbolConstructor var obj = { ->obj : { [Symbol.foo]: number; } ->{ [Symbol.foo]: 0} : { [Symbol.foo]: number; } +>obj : { [x: string]: number; } +>{ [Symbol.foo]: 0} : { [x: string]: number; } [Symbol.foo]: 0 >[Symbol.foo] : number @@ -19,8 +19,8 @@ var obj = { } obj[Symbol.foo]; ->obj[Symbol.foo] : any ->obj : { [Symbol.foo]: number; } +>obj[Symbol.foo] : number +>obj : { [x: string]: number; } >Symbol.foo : string >Symbol : SymbolConstructor >foo : string diff --git a/tests/baselines/reference/ES5SymbolProperty2.errors.txt b/tests/baselines/reference/ES5SymbolProperty2.errors.txt index 2115ed9997913..d8b6263733b43 100644 --- a/tests/baselines/reference/ES5SymbolProperty2.errors.txt +++ b/tests/baselines/reference/ES5SymbolProperty2.errors.txt @@ -1,19 +1,16 @@ -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 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(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) ==== +==== tests/cases/conformance/Symbols/ES5SymbolProperty2.ts (1 errors) ==== module M { var Symbol: any; export class C { [Symbol.iterator]() { } - ~~~~~~~~~~~~~~~ -!!! error TS2471: A computed property name of the form 'Symbol.iterator' must be of type 'symbol'. } (new C)[Symbol.iterator]; } (new M.C)[Symbol.iterator]; ~~~~~~ -!!! 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 +!!! 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/ES5SymbolProperty3.errors.txt b/tests/baselines/reference/ES5SymbolProperty3.errors.txt deleted file mode 100644 index 2953ed6ac6ab1..0000000000000 --- a/tests/baselines/reference/ES5SymbolProperty3.errors.txt +++ /dev/null @@ -1,13 +0,0 @@ -tests/cases/conformance/Symbols/ES5SymbolProperty3.ts(4,6): error TS2471: A computed property name of the form 'Symbol.iterator' must be of type 'symbol'. - - -==== tests/cases/conformance/Symbols/ES5SymbolProperty3.ts (1 errors) ==== - var Symbol: any; - - class C { - [Symbol.iterator]() { } - ~~~~~~~~~~~~~~~ -!!! error TS2471: A computed property name of the form 'Symbol.iterator' must be of type 'symbol'. - } - - (new C)[Symbol.iterator] \ No newline at end of file diff --git a/tests/baselines/reference/ES5SymbolProperty3.types b/tests/baselines/reference/ES5SymbolProperty3.types index 73800893ac59f..979f507c2037a 100644 --- a/tests/baselines/reference/ES5SymbolProperty3.types +++ b/tests/baselines/reference/ES5SymbolProperty3.types @@ -13,7 +13,7 @@ class C { } (new C)[Symbol.iterator] ->(new C)[Symbol.iterator] : any +>(new C)[Symbol.iterator] : error >(new C) : C >new C : C >C : typeof C diff --git a/tests/baselines/reference/ES5SymbolProperty4.errors.txt b/tests/baselines/reference/ES5SymbolProperty4.errors.txt deleted file mode 100644 index 18f065c6bd5fc..0000000000000 --- a/tests/baselines/reference/ES5SymbolProperty4.errors.txt +++ /dev/null @@ -1,13 +0,0 @@ -tests/cases/conformance/Symbols/ES5SymbolProperty4.ts(4,6): error TS2471: A computed property name of the form 'Symbol.iterator' must be of type 'symbol'. - - -==== tests/cases/conformance/Symbols/ES5SymbolProperty4.ts (1 errors) ==== - var Symbol: { iterator: string }; - - class C { - [Symbol.iterator]() { } - ~~~~~~~~~~~~~~~ -!!! error TS2471: A computed property name of the form 'Symbol.iterator' must be of type 'symbol'. - } - - (new C)[Symbol.iterator] \ No newline at end of file diff --git a/tests/baselines/reference/ES5SymbolProperty4.types b/tests/baselines/reference/ES5SymbolProperty4.types index 4727bb93ec326..1dc0b90062a8d 100644 --- a/tests/baselines/reference/ES5SymbolProperty4.types +++ b/tests/baselines/reference/ES5SymbolProperty4.types @@ -14,7 +14,7 @@ class C { } (new C)[Symbol.iterator] ->(new C)[Symbol.iterator] : any +>(new C)[Symbol.iterator] : error >(new C) : C >new C : C >C : typeof C diff --git a/tests/baselines/reference/ES5SymbolProperty5.errors.txt b/tests/baselines/reference/ES5SymbolProperty5.errors.txt deleted file mode 100644 index e7aca7f484989..0000000000000 --- a/tests/baselines/reference/ES5SymbolProperty5.errors.txt +++ /dev/null @@ -1,13 +0,0 @@ -tests/cases/conformance/Symbols/ES5SymbolProperty5.ts(7,26): error TS2554: Expected 0 arguments, but got 1. - - -==== tests/cases/conformance/Symbols/ES5SymbolProperty5.ts (1 errors) ==== - var Symbol: { iterator: symbol }; - - class C { - [Symbol.iterator]() { } - } - - (new C)[Symbol.iterator](0) // Should error - ~ -!!! error TS2554: Expected 0 arguments, but got 1. \ No newline at end of file diff --git a/tests/baselines/reference/ES5SymbolProperty5.types b/tests/baselines/reference/ES5SymbolProperty5.types index 1b9ce23873744..433d5165855b8 100644 --- a/tests/baselines/reference/ES5SymbolProperty5.types +++ b/tests/baselines/reference/ES5SymbolProperty5.types @@ -14,8 +14,8 @@ class C { } (new C)[Symbol.iterator](0) // Should error ->(new C)[Symbol.iterator](0) : void ->(new C)[Symbol.iterator] : () => void +>(new C)[Symbol.iterator](0) : error +>(new C)[Symbol.iterator] : error >(new C) : C >new C : C >C : typeof C diff --git a/tests/baselines/reference/ES5SymbolProperty6.errors.txt b/tests/baselines/reference/ES5SymbolProperty6.errors.txt index 4357fe6a62fb9..5b49ecae0e5f5 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 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,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 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. +!!! 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 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 +!!! 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/ES5SymbolProperty7.errors.txt b/tests/baselines/reference/ES5SymbolProperty7.errors.txt deleted file mode 100644 index 21f6f005b3c0f..0000000000000 --- a/tests/baselines/reference/ES5SymbolProperty7.errors.txt +++ /dev/null @@ -1,13 +0,0 @@ -tests/cases/conformance/Symbols/ES5SymbolProperty7.ts(4,6): error TS2471: A computed property name of the form 'Symbol.iterator' must be of type 'symbol'. - - -==== tests/cases/conformance/Symbols/ES5SymbolProperty7.ts (1 errors) ==== - var Symbol: { iterator: any }; - - class C { - [Symbol.iterator]() { } - ~~~~~~~~~~~~~~~ -!!! error TS2471: A computed property name of the form 'Symbol.iterator' must be of type 'symbol'. - } - - (new C)[Symbol.iterator] \ No newline at end of file diff --git a/tests/baselines/reference/ES5SymbolProperty7.types b/tests/baselines/reference/ES5SymbolProperty7.types index b03c10f6a0b0f..fd1404a98ba13 100644 --- a/tests/baselines/reference/ES5SymbolProperty7.types +++ b/tests/baselines/reference/ES5SymbolProperty7.types @@ -14,7 +14,7 @@ class C { } (new C)[Symbol.iterator] ->(new C)[Symbol.iterator] : any +>(new C)[Symbol.iterator] : error >(new C) : C >new C : C >C : typeof C diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json index 1e0ef5dff87a0..d031b6e257728 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json @@ -1,9 +1,425 @@ { "kind": "JSDocComment", "pos": 0, - "end": 63, + "end": 674, "flags": "JSDoc", "modifierFlagsCache": 0, "transformFlags": 0, - "comment": "{@link first link}\nInside {@link link text} thing" + "comment": { + "0": { + "kind": "JSDocText", + "pos": 0, + "end": 7, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "" + }, + "1": { + "kind": "JSDocLink", + "pos": 7, + "end": 21, + "modifierFlagsCache": 0, + "transformFlags": 0, + "name": { + "kind": "Identifier", + "pos": 14, + "end": 19, + "modifierFlagsCache": 0, + "transformFlags": 0, + "escapedText": "first" + }, + "text": "" + }, + "2": { + "kind": "JSDocText", + "pos": 21, + "end": 32, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "\nInside " + }, + "3": { + "kind": "JSDocLink", + "pos": 32, + "end": 49, + "modifierFlagsCache": 0, + "transformFlags": 0, + "name": { + "kind": "Identifier", + "pos": 39, + "end": 43, + "modifierFlagsCache": 0, + "transformFlags": 0, + "escapedText": "link" + }, + "text": "text" + }, + "4": { + "kind": "JSDocText", + "pos": 49, + "end": 59, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": " thing" + }, + "length": 5, + "pos": 0, + "end": 59, + "hasTrailingComma": false, + "transformFlags": 0 + }, + "tags": { + "0": { + "kind": "JSDocParameterTag", + "pos": 59, + "end": 102, + "modifierFlagsCache": 0, + "transformFlags": 0, + "tagName": { + "kind": "Identifier", + "pos": 60, + "end": 65, + "modifierFlagsCache": 0, + "transformFlags": 0, + "escapedText": "param" + }, + "comment": { + "0": { + "kind": "JSDocText", + "pos": 70, + "end": 79, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "See also " + }, + "1": { + "kind": "JSDocLink", + "pos": 79, + "end": 98, + "modifierFlagsCache": 0, + "transformFlags": 0, + "name": { + "kind": "FirstNode", + "pos": 86, + "end": 97, + "modifierFlagsCache": 0, + "transformFlags": 0, + "left": { + "kind": "Identifier", + "pos": 86, + "end": 87, + "modifierFlagsCache": 0, + "transformFlags": 0, + "escapedText": "A" + }, + "right": { + "kind": "Identifier", + "pos": 88, + "end": 97, + "modifierFlagsCache": 0, + "transformFlags": 0, + "escapedText": "Reference" + } + }, + "text": "" + }, + "length": 2, + "pos": 70, + "end": 102, + "hasTrailingComma": false, + "transformFlags": 0 + }, + "name": { + "kind": "Identifier", + "pos": 66, + "end": 69, + "modifierFlagsCache": 0, + "transformFlags": 0, + "escapedText": "foo" + }, + "isNameFirst": true, + "isBracketed": false + }, + "1": { + "kind": "JSDocParameterTag", + "pos": 102, + "end": 589, + "modifierFlagsCache": 0, + "transformFlags": 0, + "tagName": { + "kind": "Identifier", + "pos": 103, + "end": 108, + "modifierFlagsCache": 0, + "transformFlags": 0, + "escapedText": "param" + }, + "comment": { + "0": { + "kind": "JSDocText", + "pos": 113, + "end": 120, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "Or see " + }, + "1": { + "kind": "JSDocLink", + "pos": 120, + "end": 152, + "modifierFlagsCache": 0, + "transformFlags": 0, + "name": { + "kind": "Identifier", + "pos": 127, + "end": 131, + "modifierFlagsCache": 0, + "transformFlags": 0, + "escapedText": "http" + }, + "text": "://www.zombocom.com " + }, + "2": { + "kind": "JSDocText", + "pos": 152, + "end": 156, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "\n" + }, + "3": { + "kind": "JSDocLink", + "pos": 156, + "end": 183, + "modifierFlagsCache": 0, + "transformFlags": 0, + "name": { + "kind": "FirstNode", + "pos": 163, + "end": 181, + "modifierFlagsCache": 0, + "transformFlags": 0, + "left": { + "kind": "Identifier", + "pos": 163, + "end": 173, + "modifierFlagsCache": 0, + "transformFlags": 0, + "escapedText": "Standalone" + }, + "right": { + "kind": "Identifier", + "pos": 174, + "end": 181, + "modifierFlagsCache": 0, + "transformFlags": 0, + "escapedText": "Complex" + } + }, + "text": "" + }, + "4": { + "kind": "JSDocText", + "pos": 183, + "end": 203, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "\nThis empty one: " + }, + "5": { + "kind": "JSDocLink", + "pos": 203, + "end": 210, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "" + }, + "6": { + "kind": "JSDocText", + "pos": 210, + "end": 244, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": " is OK.\nThis double-space one: " + }, + "7": { + "kind": "JSDocLink", + "pos": 244, + "end": 262, + "modifierFlagsCache": 0, + "transformFlags": 0, + "name": { + "kind": "Identifier", + "pos": 252, + "end": 259, + "modifierFlagsCache": 0, + "transformFlags": 0, + "escapedText": "doubled" + }, + "text": "" + }, + "8": { + "kind": "JSDocText", + "pos": 262, + "end": 326, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": " is OK too.\nThis should work, despite being badly formatted: " + }, + "9": { + "kind": "JSDocLink", + "pos": 326, + "end": 340, + "modifierFlagsCache": 0, + "transformFlags": 0, + "name": { + "kind": "FirstNode", + "pos": 333, + "end": 338, + "modifierFlagsCache": 0, + "transformFlags": 0, + "left": { + "kind": "Identifier", + "pos": 333, + "end": 335, + "modifierFlagsCache": 0, + "transformFlags": 0, + "escapedText": "oh" + }, + "right": { + "kind": "Identifier", + "pos": 336, + "end": 338, + "modifierFlagsCache": 0, + "transformFlags": 0, + "escapedText": "no" + } + }, + "text": "" + }, + "10": { + "kind": "JSDocText", + "pos": 340, + "end": 369, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "\nForgot to close this one " + }, + "11": { + "kind": "JSDocLink", + "pos": 369, + "end": 403, + "modifierFlagsCache": 0, + "transformFlags": 0, + "name": { + "kind": "Identifier", + "pos": 376, + "end": 381, + "modifierFlagsCache": 0, + "transformFlags": 0, + "escapedText": "https" + }, + "text": "://typescriptlang.org" + }, + "12": { + "kind": "JSDocText", + "pos": 403, + "end": 526, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": " * But it's still OK.\nAlthough it skips the newline so parses the asterisks in the wrong state.\nThis shouldn't work: " + }, + "13": { + "kind": "JSDocLink", + "pos": 526, + "end": 541, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "* nope" + }, + "14": { + "kind": "JSDocText", + "pos": 541, + "end": 589, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": " * }, because of the intermediate asterisks." + }, + "length": 15, + "pos": 113, + "end": 589, + "hasTrailingComma": false, + "transformFlags": 0 + }, + "name": { + "kind": "Identifier", + "pos": 109, + "end": 112, + "modifierFlagsCache": 0, + "transformFlags": 0, + "escapedText": "bar" + }, + "isNameFirst": true, + "isBracketed": false + }, + "2": { + "kind": "JSDocAuthorTag", + "pos": 589, + "end": 672, + "modifierFlagsCache": 0, + "transformFlags": 0, + "tagName": { + "kind": "Identifier", + "pos": 590, + "end": 596, + "modifierFlagsCache": 0, + "transformFlags": 0, + "escapedText": "author" + }, + "comment": { + "0": { + "kind": "JSDocText", + "pos": 597, + "end": 624, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "Alfa Romero " + }, + "1": { + "kind": "JSDocText", + "pos": 624, + "end": 643, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": " See my home page: " + }, + "2": { + "kind": "JSDocLink", + "pos": 643, + "end": 670, + "modifierFlagsCache": 0, + "transformFlags": 0, + "name": { + "kind": "Identifier", + "pos": 650, + "end": 655, + "modifierFlagsCache": 0, + "transformFlags": 0, + "escapedText": "https" + }, + "text": "://example.com" + }, + "length": 3, + "pos": 597, + "end": 672, + "hasTrailingComma": false, + "transformFlags": 0 + } + }, + "length": 3, + "pos": 59, + "end": 672, + "hasTrailingComma": false, + "transformFlags": 0 + } } \ No newline at end of file diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.authorTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.authorTag.json index 4f92b492fca66..c1f9f90589d64 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.authorTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.authorTag.json @@ -20,7 +20,21 @@ "transformFlags": 0, "escapedText": "author" }, - "comment": "John Doe " + "comment": { + "0": { + "kind": "JSDocText", + "pos": 15, + "end": 50, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "John Doe " + }, + "length": 1, + "pos": 15, + "end": 50, + "hasTrailingComma": false, + "transformFlags": 0 + } }, "1": { "kind": "JSDocAuthorTag", @@ -68,7 +82,21 @@ "transformFlags": 0, "escapedText": "author" }, - "comment": "Multiple Ats " + "comment": { + "0": { + "kind": "JSDocText", + "pos": 178, + "end": 227, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "Multiple Ats " + }, + "length": 1, + "pos": 178, + "end": 227, + "hasTrailingComma": false, + "transformFlags": 0 + } }, "4": { "kind": "JSDocAuthorTag", @@ -84,7 +112,21 @@ "transformFlags": 0, "escapedText": "author" }, - "comment": "Multiple Open Carets " + "comment": { + "0": { + "kind": "JSDocText", + "pos": 235, + "end": 272, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "Multiple Open Carets " + }, + "length": 1, + "pos": 235, + "end": 272, + "hasTrailingComma": false, + "transformFlags": 0 + } }, "5": { "kind": "JSDocAuthorTag", @@ -116,7 +158,21 @@ "transformFlags": 0, "escapedText": "author" }, - "comment": "Unclosed Carets " + "comment": { + "0": { + "kind": "JSDocText", + "pos": 406, + "end": 429, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "On One " + }, + "length": 1, + "pos": 406, + "end": 429, + "hasTrailingComma": false, + "transformFlags": 0 + } }, "9": { "kind": "JSDocAuthorTag", @@ -164,7 +248,21 @@ "transformFlags": 0, "escapedText": "author" }, - "comment": "Line" + "comment": { + "0": { + "kind": "JSDocText", + "pos": 437, + "end": 445, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "Line" + }, + "length": 1, + "pos": 437, + "end": 445, + "hasTrailingComma": false, + "transformFlags": 0 + } }, "10": { "kind": "JSDocAuthorTag", @@ -179,6 +277,21 @@ "modifierFlagsCache": 0, "transformFlags": 0, "escapedText": "author" + }, + "comment": { + "0": { + "kind": "JSDocText", + "pos": 453, + "end": 453, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "" + }, + "length": 1, + "pos": 453, + "end": 453, + "hasTrailingComma": false, + "transformFlags": 0 } }, "11": { @@ -194,6 +307,21 @@ "modifierFlagsCache": 0, "transformFlags": 0, "escapedText": "author" + }, + "comment": { + "0": { + "kind": "JSDocText", + "pos": 461, + "end": 461, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "" + }, + "length": 1, + "pos": 461, + "end": 461, + "hasTrailingComma": false, + "transformFlags": 0 } }, "12": { @@ -210,7 +338,21 @@ "transformFlags": 0, "escapedText": "author" }, - "comment": "Empty authors" + "comment": { + "0": { + "kind": "JSDocText", + "pos": 469, + "end": 486, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "Empty authors" + }, + "length": 1, + "pos": 469, + "end": 486, + "hasTrailingComma": false, + "transformFlags": 0 + } }, "13": { "kind": "JSDocAuthorTag", @@ -225,6 +367,21 @@ "modifierFlagsCache": 0, "transformFlags": 0, "escapedText": "author" + }, + "comment": { + "0": { + "kind": "JSDocText", + "pos": 497, + "end": 497, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "" + }, + "length": 1, + "pos": 497, + "end": 497, + "hasTrailingComma": false, + "transformFlags": 0 } }, "14": { @@ -241,7 +398,21 @@ "transformFlags": 0, "escapedText": "author" }, - "comment": "Comments" + "comment": { + "0": { + "kind": "JSDocText", + "pos": 510, + "end": 522, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "Comments" + }, + "length": 1, + "pos": 510, + "end": 522, + "hasTrailingComma": false, + "transformFlags": 0 + } }, "15": { "kind": "JSDocAuthorTag", @@ -257,7 +428,21 @@ "transformFlags": 0, "escapedText": "author" }, - "comment": "Early Close Caret > " + "comment": { + "0": { + "kind": "JSDocText", + "pos": 530, + "end": 559, + "modifierFlagsCache": 0, + "transformFlags": 0, + "text": "Early Close Caret > " + }, + "length": 1, + "pos": 530, + "end": 559, + "hasTrailingComma": false, + "transformFlags": 0 + } }, "16": { "kind": "JSDocAuthorTag", @@ -278,7 +463,7 @@ "17": { "kind": "JSDocTag", "pos": 599, - "end": 607, + "end": 646, "modifierFlagsCache": 0, "transformFlags": 0, "tagName": { diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.consecutive newline tokens.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.consecutive newline tokens.json index 26875d7eba7c7..19eb9bd3e4ece 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.consecutive newline tokens.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.consecutive newline tokens.json @@ -9,7 +9,7 @@ "0": { "kind": "JSDocTag", "pos": 7, - "end": 19, + "end": 53, "modifierFlagsCache": 0, "transformFlags": 0, "tagName": { @@ -24,7 +24,7 @@ }, "length": 1, "pos": 7, - "end": 19, + "end": 53, "hasTrailingComma": false, "transformFlags": 0 } diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.leadingAsterisk.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.leadingAsterisk.json index 1289886390bdf..27a284ebe7bae 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.leadingAsterisk.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.leadingAsterisk.json @@ -9,7 +9,7 @@ "0": { "kind": "JSDocTypeTag", "pos": 8, - "end": 22, + "end": 25, "modifierFlagsCache": 0, "transformFlags": 0, "tagName": { @@ -38,7 +38,7 @@ }, "length": 1, "pos": 8, - "end": 22, + "end": 25, "hasTrailingComma": false, "transformFlags": 0 } diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.no space before @ is not a new tag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.no space before @ is not a new tag.json index 3b154e039731c..fa1dfa412ae55 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.no space before @ is not a new tag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.no space before @ is not a new tag.json @@ -77,7 +77,7 @@ "3": { "kind": "JSDocTag", "pos": 62, - "end": 75, + "end": 89, "modifierFlagsCache": 0, "transformFlags": 0, "tagName": { @@ -92,7 +92,7 @@ }, "length": 4, "pos": 7, - "end": 75, + "end": 89, "hasTrailingComma": false, "transformFlags": 0 } diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noLeadingAsterisk.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noLeadingAsterisk.json index 1289886390bdf..27a284ebe7bae 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noLeadingAsterisk.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noLeadingAsterisk.json @@ -9,7 +9,7 @@ "0": { "kind": "JSDocTypeTag", "pos": 8, - "end": 22, + "end": 25, "modifierFlagsCache": 0, "transformFlags": 0, "tagName": { @@ -38,7 +38,7 @@ }, "length": 1, "pos": 8, - "end": 22, + "end": 25, "hasTrailingComma": false, "transformFlags": 0 } diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noReturnType.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noReturnType.json index e7e8b9d13d78b..052aa1c5aa6c5 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noReturnType.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noReturnType.json @@ -9,7 +9,7 @@ "0": { "kind": "JSDocReturnTag", "pos": 8, - "end": 15, + "end": 18, "modifierFlagsCache": 0, "transformFlags": 0, "tagName": { @@ -24,7 +24,7 @@ }, "length": 1, "pos": 8, - "end": 15, + "end": 18, "hasTrailingComma": false, "transformFlags": 0 } diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag1.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag1.json index a7f96aa220f0d..e5d3ee7b6149a 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag1.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag1.json @@ -9,7 +9,7 @@ "0": { "kind": "JSDocReturnTag", "pos": 8, - "end": 24, + "end": 27, "modifierFlagsCache": 0, "transformFlags": 0, "tagName": { @@ -38,7 +38,7 @@ }, "length": 1, "pos": 8, - "end": 24, + "end": 27, "hasTrailingComma": false, "transformFlags": 0 } diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag2.json index e243e4fb5e2f6..b7b5fe254828a 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag2.json @@ -9,7 +9,7 @@ "0": { "kind": "JSDocReturnTag", "pos": 8, - "end": 24, + "end": 52, "modifierFlagsCache": 0, "transformFlags": 0, "tagName": { @@ -39,7 +39,7 @@ }, "length": 1, "pos": 8, - "end": 24, + "end": 52, "hasTrailingComma": false, "transformFlags": 0 } diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnsTag1.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnsTag1.json index a0af3c57f2543..230dd41541585 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnsTag1.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnsTag1.json @@ -9,7 +9,7 @@ "0": { "kind": "JSDocReturnTag", "pos": 8, - "end": 25, + "end": 28, "modifierFlagsCache": 0, "transformFlags": 0, "tagName": { @@ -37,7 +37,7 @@ }, "length": 1, "pos": 8, - "end": 25, + "end": 28, "hasTrailingComma": false, "transformFlags": 0 } diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json index 14d338f4368c3..50c772455d0ec 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json @@ -9,7 +9,7 @@ "0": { "kind": "JSDocTemplateTag", "pos": 8, - "end": 19, + "end": 22, "modifierFlagsCache": 0, "transformFlags": 0, "tagName": { @@ -45,7 +45,7 @@ }, "length": 1, "pos": 8, - "end": 19, + "end": 22, "hasTrailingComma": false, "transformFlags": 0 } diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json index 0217b5efc5749..1b4c8e8976951 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json @@ -9,7 +9,7 @@ "0": { "kind": "JSDocTemplateTag", "pos": 8, - "end": 21, + "end": 24, "modifierFlagsCache": 0, "transformFlags": 0, "tagName": { @@ -60,7 +60,7 @@ }, "length": 1, "pos": 8, - "end": 21, + "end": 24, "hasTrailingComma": false, "transformFlags": 0 } diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json index 1761d1f67b3c4..15bab6344a35b 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json @@ -9,7 +9,7 @@ "0": { "kind": "JSDocTemplateTag", "pos": 8, - "end": 22, + "end": 25, "modifierFlagsCache": 0, "transformFlags": 0, "tagName": { @@ -60,7 +60,7 @@ }, "length": 1, "pos": 8, - "end": 22, + "end": 25, "hasTrailingComma": false, "transformFlags": 0 } diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json index 1761d1f67b3c4..15bab6344a35b 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json @@ -9,7 +9,7 @@ "0": { "kind": "JSDocTemplateTag", "pos": 8, - "end": 22, + "end": 25, "modifierFlagsCache": 0, "transformFlags": 0, "tagName": { @@ -60,7 +60,7 @@ }, "length": 1, "pos": 8, - "end": 22, + "end": 25, "hasTrailingComma": false, "transformFlags": 0 } diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json index d0faa579c0826..e3f4dceb82b74 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json @@ -9,7 +9,7 @@ "0": { "kind": "JSDocTemplateTag", "pos": 8, - "end": 23, + "end": 26, "modifierFlagsCache": 0, "transformFlags": 0, "tagName": { @@ -60,7 +60,7 @@ }, "length": 1, "pos": 8, - "end": 23, + "end": 26, "hasTrailingComma": false, "transformFlags": 0 } diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json index 874e64567fba5..29ee205ac48d9 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json @@ -9,7 +9,7 @@ "0": { "kind": "JSDocTemplateTag", "pos": 8, - "end": 24, + "end": 58, "modifierFlagsCache": 0, "transformFlags": 0, "tagName": { @@ -61,7 +61,7 @@ }, "length": 1, "pos": 8, - "end": 24, + "end": 58, "hasTrailingComma": false, "transformFlags": 0 } diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typeTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typeTag.json index 1289886390bdf..27a284ebe7bae 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typeTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typeTag.json @@ -9,7 +9,7 @@ "0": { "kind": "JSDocTypeTag", "pos": 8, - "end": 22, + "end": 25, "modifierFlagsCache": 0, "transformFlags": 0, "tagName": { @@ -38,7 +38,7 @@ }, "length": 1, "pos": 8, - "end": 22, + "end": 25, "hasTrailingComma": false, "transformFlags": 0 } diff --git a/tests/baselines/reference/abstractPropertyInConstructor.errors.txt b/tests/baselines/reference/abstractPropertyInConstructor.errors.txt index 030369d81ed66..8b98c0816e936 100644 --- a/tests/baselines/reference/abstractPropertyInConstructor.errors.txt +++ b/tests/baselines/reference/abstractPropertyInConstructor.errors.txt @@ -4,9 +4,14 @@ tests/cases/compiler/abstractPropertyInConstructor.ts(9,14): error TS2715: Abstr 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(25,18): error TS2729: Property 'prop' is used before its initialization. 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(78,15): error TS2715: Abstract property 'x' in class 'C1' cannot be accessed in the constructor. +tests/cases/compiler/abstractPropertyInConstructor.ts(78,18): error TS2715: Abstract property 'y' in class 'C1' cannot be accessed in the constructor. +tests/cases/compiler/abstractPropertyInConstructor.ts(79,12): error TS2715: Abstract property 'x' in class 'C1' cannot be accessed in the constructor. +tests/cases/compiler/abstractPropertyInConstructor.ts(79,15): error TS2715: Abstract property 'y' in class 'C1' cannot be accessed in the constructor. +tests/cases/compiler/abstractPropertyInConstructor.ts(79,22): error TS2715: Abstract property 'y' in class 'C1' cannot be accessed in the constructor. -==== tests/cases/compiler/abstractPropertyInConstructor.ts (6 errors) ==== +==== tests/cases/compiler/abstractPropertyInConstructor.ts (11 errors) ==== abstract class AbstractClass { constructor(str: string, other: AbstractClass) { this.method(parseInt(str)); @@ -90,4 +95,36 @@ tests/cases/compiler/abstractPropertyInConstructor.ts(39,22): error TS2715: Abst a.method2(); } } + + abstract class C1 { + abstract x: string; + abstract y: string; + + constructor() { + let self = this; // ok + let { x, y: y1 } = this; // error + ~ +!!! error TS2715: Abstract property 'x' in class 'C1' cannot be accessed in the constructor. + ~ +!!! error TS2715: Abstract property 'y' in class 'C1' cannot be accessed in the constructor. + ({ x, y: y1, "y": y1 } = this); // error + ~ +!!! error TS2715: Abstract property 'x' in class 'C1' cannot be accessed in the constructor. + ~ +!!! error TS2715: Abstract property 'y' in class 'C1' cannot be accessed in the constructor. + ~~~ +!!! error TS2715: Abstract property 'y' in class 'C1' cannot be accessed in the constructor. + } + } + + class C2 { + x: string; + y: string; + + constructor() { + let self = this; // ok + let { x, y: y1 } = this; // ok + ({ x, y: y1, "y": y1 } = this); // ok + } + } \ No newline at end of file diff --git a/tests/baselines/reference/abstractPropertyInConstructor.js b/tests/baselines/reference/abstractPropertyInConstructor.js index 9048a5b9c416a..95fc2bfaa09c9 100644 --- a/tests/baselines/reference/abstractPropertyInConstructor.js +++ b/tests/baselines/reference/abstractPropertyInConstructor.js @@ -69,6 +69,28 @@ class User { a.method2(); } } + +abstract class C1 { + abstract x: string; + abstract y: string; + + constructor() { + let self = this; // ok + let { x, y: y1 } = this; // error + ({ x, y: y1, "y": y1 } = this); // error + } +} + +class C2 { + x: string; + y: string; + + constructor() { + let self = this; // ok + let { x, y: y1 } = this; // ok + ({ x, y: y1, "y": y1 } = this); // ok + } +} //// [abstractPropertyInConstructor.js] @@ -148,3 +170,21 @@ var User = /** @class */ (function () { } return User; }()); +var C1 = /** @class */ (function () { + function C1() { + var _a; + var self = this; // ok + var _b = this, x = _b.x, y1 = _b.y; // error + (_a = this, x = _a.x, y1 = _a.y, y1 = _a["y"]); // error + } + return C1; +}()); +var C2 = /** @class */ (function () { + function C2() { + var _a; + var self = this; // ok + var _b = this, x = _b.x, y1 = _b.y; // ok + (_a = this, x = _a.x, y1 = _a.y, y1 = _a["y"]); // ok + } + return C2; +}()); diff --git a/tests/baselines/reference/abstractPropertyInConstructor.symbols b/tests/baselines/reference/abstractPropertyInConstructor.symbols index 628ee5c85762b..d75b31d140a2a 100644 --- a/tests/baselines/reference/abstractPropertyInConstructor.symbols +++ b/tests/baselines/reference/abstractPropertyInConstructor.symbols @@ -224,3 +224,63 @@ class User { } } +abstract class C1 { +>C1 : Symbol(C1, Decl(abstractPropertyInConstructor.ts, 69, 1)) + + abstract x: string; +>x : Symbol(C1.x, Decl(abstractPropertyInConstructor.ts, 71, 19)) + + abstract y: string; +>y : Symbol(C1.y, Decl(abstractPropertyInConstructor.ts, 72, 23)) + + constructor() { + let self = this; // ok +>self : Symbol(self, Decl(abstractPropertyInConstructor.ts, 76, 11)) +>this : Symbol(C1, Decl(abstractPropertyInConstructor.ts, 69, 1)) + + let { x, y: y1 } = this; // error +>x : Symbol(x, Decl(abstractPropertyInConstructor.ts, 77, 13)) +>y : Symbol(C1.y, Decl(abstractPropertyInConstructor.ts, 72, 23)) +>y1 : Symbol(y1, Decl(abstractPropertyInConstructor.ts, 77, 16)) +>this : Symbol(C1, Decl(abstractPropertyInConstructor.ts, 69, 1)) + + ({ x, y: y1, "y": y1 } = this); // error +>x : Symbol(x, Decl(abstractPropertyInConstructor.ts, 78, 10)) +>y : Symbol(y, Decl(abstractPropertyInConstructor.ts, 78, 13), Decl(abstractPropertyInConstructor.ts, 78, 20)) +>y1 : Symbol(y1, Decl(abstractPropertyInConstructor.ts, 77, 16)) +>"y" : Symbol(y, Decl(abstractPropertyInConstructor.ts, 78, 13), Decl(abstractPropertyInConstructor.ts, 78, 20)) +>y1 : Symbol(y1, Decl(abstractPropertyInConstructor.ts, 77, 16)) +>this : Symbol(C1, Decl(abstractPropertyInConstructor.ts, 69, 1)) + } +} + +class C2 { +>C2 : Symbol(C2, Decl(abstractPropertyInConstructor.ts, 80, 1)) + + x: string; +>x : Symbol(C2.x, Decl(abstractPropertyInConstructor.ts, 82, 10)) + + y: string; +>y : Symbol(C2.y, Decl(abstractPropertyInConstructor.ts, 83, 14)) + + constructor() { + let self = this; // ok +>self : Symbol(self, Decl(abstractPropertyInConstructor.ts, 87, 11)) +>this : Symbol(C2, Decl(abstractPropertyInConstructor.ts, 80, 1)) + + let { x, y: y1 } = this; // ok +>x : Symbol(x, Decl(abstractPropertyInConstructor.ts, 88, 13)) +>y : Symbol(C2.y, Decl(abstractPropertyInConstructor.ts, 83, 14)) +>y1 : Symbol(y1, Decl(abstractPropertyInConstructor.ts, 88, 16)) +>this : Symbol(C2, Decl(abstractPropertyInConstructor.ts, 80, 1)) + + ({ x, y: y1, "y": y1 } = this); // ok +>x : Symbol(x, Decl(abstractPropertyInConstructor.ts, 89, 10)) +>y : Symbol(y, Decl(abstractPropertyInConstructor.ts, 89, 13), Decl(abstractPropertyInConstructor.ts, 89, 20)) +>y1 : Symbol(y1, Decl(abstractPropertyInConstructor.ts, 88, 16)) +>"y" : Symbol(y, Decl(abstractPropertyInConstructor.ts, 89, 13), Decl(abstractPropertyInConstructor.ts, 89, 20)) +>y1 : Symbol(y1, Decl(abstractPropertyInConstructor.ts, 88, 16)) +>this : Symbol(C2, Decl(abstractPropertyInConstructor.ts, 80, 1)) + } +} + diff --git a/tests/baselines/reference/abstractPropertyInConstructor.types b/tests/baselines/reference/abstractPropertyInConstructor.types index 8c8bd40aff09c..ee8500d70279e 100644 --- a/tests/baselines/reference/abstractPropertyInConstructor.types +++ b/tests/baselines/reference/abstractPropertyInConstructor.types @@ -12,7 +12,7 @@ abstract class AbstractClass { >this : this >method : (num: number) => void >parseInt(str) : number ->parseInt : (s: string, radix?: number) => number +>parseInt : (string: string, radix?: number) => number >str : string let val = this.prop.toLowerCase(); @@ -250,3 +250,69 @@ class User { } } +abstract class C1 { +>C1 : C1 + + abstract x: string; +>x : string + + abstract y: string; +>y : string + + constructor() { + let self = this; // ok +>self : this +>this : this + + let { x, y: y1 } = this; // error +>x : string +>y : any +>y1 : string +>this : this + + ({ x, y: y1, "y": y1 } = this); // error +>({ x, y: y1, "y": y1 } = this) : this +>{ x, y: y1, "y": y1 } = this : this +>{ x, y: y1, "y": y1 } : { x: string; y: string; } +>x : string +>y : string +>y1 : string +>"y" : string +>y1 : string +>this : this + } +} + +class C2 { +>C2 : C2 + + x: string; +>x : string + + y: string; +>y : string + + constructor() { + let self = this; // ok +>self : this +>this : this + + let { x, y: y1 } = this; // ok +>x : string +>y : any +>y1 : string +>this : this + + ({ x, y: y1, "y": y1 } = this); // ok +>({ x, y: y1, "y": y1 } = this) : this +>{ x, y: y1, "y": y1 } = this : this +>{ x, y: y1, "y": y1 } : { x: string; y: string; } +>x : string +>y : string +>y1 : string +>"y" : string +>y1 : string +>this : this + } +} + diff --git a/tests/baselines/reference/abstractPropertyNegative.errors.txt b/tests/baselines/reference/abstractPropertyNegative.errors.txt index fd09b024213c4..d7b2fa592f839 100644 --- a/tests/baselines/reference/abstractPropertyNegative.errors.txt +++ b/tests/baselines/reference/abstractPropertyNegative.errors.txt @@ -1,5 +1,4 @@ -tests/cases/compiler/abstractPropertyNegative.ts(10,18): error TS2380: 'get' and 'set' accessor must have the same type. -tests/cases/compiler/abstractPropertyNegative.ts(11,18): error TS2380: 'get' and 'set' accessor must have the same type. +tests/cases/compiler/abstractPropertyNegative.ts(10,18): error TS2380: The return type of a 'get' accessor must be assignable to its 'set' accessor type tests/cases/compiler/abstractPropertyNegative.ts(13,7): error TS2515: Non-abstract class 'C' does not implement inherited abstract member 'm' from class 'B'. tests/cases/compiler/abstractPropertyNegative.ts(13,7): error TS2515: Non-abstract class 'C' does not implement inherited abstract member 'mismatch' from class 'B'. tests/cases/compiler/abstractPropertyNegative.ts(13,7): error TS2515: Non-abstract class 'C' does not implement inherited abstract member 'prop' from class 'B'. @@ -19,7 +18,7 @@ tests/cases/compiler/abstractPropertyNegative.ts(40,9): error TS2676: Accessors tests/cases/compiler/abstractPropertyNegative.ts(41,18): error TS2676: Accessors must both be abstract or non-abstract. -==== tests/cases/compiler/abstractPropertyNegative.ts (16 errors) ==== +==== tests/cases/compiler/abstractPropertyNegative.ts (15 errors) ==== interface A { prop: string; m(): string; @@ -31,10 +30,8 @@ tests/cases/compiler/abstractPropertyNegative.ts(41,18): error TS2676: Accessors abstract m(): string; abstract get mismatch(): string; ~~~~~~~~ -!!! error TS2380: 'get' and 'set' accessor must have the same type. +!!! error TS2380: The return type of a 'get' accessor must be assignable to its 'set' accessor type abstract set mismatch(val: number); // error, not same type - ~~~~~~~~ -!!! error TS2380: 'get' and 'set' accessor must have the same type. } class C extends B { ~ diff --git a/tests/baselines/reference/accessorBodyInTypeContext.errors.txt b/tests/baselines/reference/accessorBodyInTypeContext.errors.txt new file mode 100644 index 0000000000000..fad18097a98d7 --- /dev/null +++ b/tests/baselines/reference/accessorBodyInTypeContext.errors.txt @@ -0,0 +1,32 @@ +tests/cases/compiler/accessorBodyInTypeContext.ts(2,15): error TS1183: An implementation cannot be declared in ambient contexts. +tests/cases/compiler/accessorBodyInTypeContext.ts(6,21): error TS1183: An implementation cannot be declared in ambient contexts. +tests/cases/compiler/accessorBodyInTypeContext.ts(10,15): error TS1183: An implementation cannot be declared in ambient contexts. +tests/cases/compiler/accessorBodyInTypeContext.ts(14,21): error TS1183: An implementation cannot be declared in ambient contexts. + + +==== tests/cases/compiler/accessorBodyInTypeContext.ts (4 errors) ==== + type A = { + get foo() { return 0 } + ~~~~~~~~~~~~ +!!! error TS1183: An implementation cannot be declared in ambient contexts. + }; + + type B = { + set foo(v: any) { } + ~~~ +!!! error TS1183: An implementation cannot be declared in ambient contexts. + }; + + interface X { + get foo() { return 0 } + ~~~~~~~~~~~~ +!!! error TS1183: An implementation cannot be declared in ambient contexts. + } + + interface Y { + set foo(v: any) { } + ~~~ +!!! error TS1183: An implementation cannot be declared in ambient contexts. + } + + \ No newline at end of file diff --git a/tests/baselines/reference/accessorBodyInTypeContext.js b/tests/baselines/reference/accessorBodyInTypeContext.js new file mode 100644 index 0000000000000..d99110e329cd0 --- /dev/null +++ b/tests/baselines/reference/accessorBodyInTypeContext.js @@ -0,0 +1,20 @@ +//// [accessorBodyInTypeContext.ts] +type A = { + get foo() { return 0 } +}; + +type B = { + set foo(v: any) { } +}; + +interface X { + get foo() { return 0 } +} + +interface Y { + set foo(v: any) { } +} + + + +//// [accessorBodyInTypeContext.js] diff --git a/tests/baselines/reference/accessorBodyInTypeContext.symbols b/tests/baselines/reference/accessorBodyInTypeContext.symbols new file mode 100644 index 0000000000000..4eb8bfd31289e --- /dev/null +++ b/tests/baselines/reference/accessorBodyInTypeContext.symbols @@ -0,0 +1,34 @@ +=== tests/cases/compiler/accessorBodyInTypeContext.ts === +type A = { +>A : Symbol(A, Decl(accessorBodyInTypeContext.ts, 0, 0)) + + get foo() { return 0 } +>foo : Symbol(foo, Decl(accessorBodyInTypeContext.ts, 0, 10)) + +}; + +type B = { +>B : Symbol(B, Decl(accessorBodyInTypeContext.ts, 2, 2)) + + set foo(v: any) { } +>foo : Symbol(foo, Decl(accessorBodyInTypeContext.ts, 4, 10)) +>v : Symbol(v, Decl(accessorBodyInTypeContext.ts, 5, 12)) + +}; + +interface X { +>X : Symbol(X, Decl(accessorBodyInTypeContext.ts, 6, 2)) + + get foo() { return 0 } +>foo : Symbol(X.foo, Decl(accessorBodyInTypeContext.ts, 8, 13)) +} + +interface Y { +>Y : Symbol(Y, Decl(accessorBodyInTypeContext.ts, 10, 1)) + + set foo(v: any) { } +>foo : Symbol(Y.foo, Decl(accessorBodyInTypeContext.ts, 12, 13)) +>v : Symbol(v, Decl(accessorBodyInTypeContext.ts, 13, 12)) +} + + diff --git a/tests/baselines/reference/accessorBodyInTypeContext.types b/tests/baselines/reference/accessorBodyInTypeContext.types new file mode 100644 index 0000000000000..ad04c25524d88 --- /dev/null +++ b/tests/baselines/reference/accessorBodyInTypeContext.types @@ -0,0 +1,32 @@ +=== tests/cases/compiler/accessorBodyInTypeContext.ts === +type A = { +>A : A + + get foo() { return 0 } +>foo : number +>0 : 0 + +}; + +type B = { +>B : B + + set foo(v: any) { } +>foo : any +>v : any + +}; + +interface X { + get foo() { return 0 } +>foo : number +>0 : 0 +} + +interface Y { + set foo(v: any) { } +>foo : any +>v : any +} + + diff --git a/tests/baselines/reference/accessorWithMismatchedAccessibilityModifiers.errors.txt b/tests/baselines/reference/accessorWithMismatchedAccessibilityModifiers.errors.txt deleted file mode 100644 index 9d1b7ca9a30b5..0000000000000 --- a/tests/baselines/reference/accessorWithMismatchedAccessibilityModifiers.errors.txt +++ /dev/null @@ -1,58 +0,0 @@ -tests/cases/conformance/classes/propertyMemberDeclarations/memberAccessorDeclarations/accessorWithMismatchedAccessibilityModifiers.ts(2,9): error TS2379: Getter and setter accessors do not agree in visibility. -tests/cases/conformance/classes/propertyMemberDeclarations/memberAccessorDeclarations/accessorWithMismatchedAccessibilityModifiers.ts(5,17): error TS2379: Getter and setter accessors do not agree in visibility. -tests/cases/conformance/classes/propertyMemberDeclarations/memberAccessorDeclarations/accessorWithMismatchedAccessibilityModifiers.ts(10,19): error TS2379: Getter and setter accessors do not agree in visibility. -tests/cases/conformance/classes/propertyMemberDeclarations/memberAccessorDeclarations/accessorWithMismatchedAccessibilityModifiers.ts(13,17): error TS2379: Getter and setter accessors do not agree in visibility. -tests/cases/conformance/classes/propertyMemberDeclarations/memberAccessorDeclarations/accessorWithMismatchedAccessibilityModifiers.ts(18,19): error TS2379: Getter and setter accessors do not agree in visibility. -tests/cases/conformance/classes/propertyMemberDeclarations/memberAccessorDeclarations/accessorWithMismatchedAccessibilityModifiers.ts(20,9): error TS2379: Getter and setter accessors do not agree in visibility. -tests/cases/conformance/classes/propertyMemberDeclarations/memberAccessorDeclarations/accessorWithMismatchedAccessibilityModifiers.ts(26,26): error TS2379: Getter and setter accessors do not agree in visibility. -tests/cases/conformance/classes/propertyMemberDeclarations/memberAccessorDeclarations/accessorWithMismatchedAccessibilityModifiers.ts(28,16): error TS2379: Getter and setter accessors do not agree in visibility. - - -==== tests/cases/conformance/classes/propertyMemberDeclarations/memberAccessorDeclarations/accessorWithMismatchedAccessibilityModifiers.ts (8 errors) ==== - class C { - get x() { - ~ -!!! error TS2379: Getter and setter accessors do not agree in visibility. - return 1; - } - private set x(v) { - ~ -!!! error TS2379: Getter and setter accessors do not agree in visibility. - } - } - - class D { - protected get x() { - ~ -!!! error TS2379: Getter and setter accessors do not agree in visibility. - return 1; - } - private set x(v) { - ~ -!!! error TS2379: Getter and setter accessors do not agree in visibility. - } - } - - class E { - protected set x(v) { - ~ -!!! error TS2379: Getter and setter accessors do not agree in visibility. - } - get x() { - ~ -!!! error TS2379: Getter and setter accessors do not agree in visibility. - return 1; - } - } - - class F { - protected static set x(v) { - ~ -!!! error TS2379: Getter and setter accessors do not agree in visibility. - } - static get x() { - ~ -!!! error TS2379: Getter and setter accessors do not agree in visibility. - return 1; - } - } \ No newline at end of file diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index be1c47fd86a47..6195d669a8306 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 = "4.2"; + const versionMajorMinor = "4.3"; /** The version of the TypeScript compiler release */ const version: string; /** @@ -260,192 +260,196 @@ declare namespace ts { FromKeyword = 153, GlobalKeyword = 154, BigIntKeyword = 155, - OfKeyword = 156, - QualifiedName = 157, - ComputedPropertyName = 158, - TypeParameter = 159, - Parameter = 160, - Decorator = 161, - PropertySignature = 162, - PropertyDeclaration = 163, - MethodSignature = 164, - MethodDeclaration = 165, - Constructor = 166, - GetAccessor = 167, - SetAccessor = 168, - CallSignature = 169, - ConstructSignature = 170, - IndexSignature = 171, - TypePredicate = 172, - TypeReference = 173, - FunctionType = 174, - ConstructorType = 175, - TypeQuery = 176, - TypeLiteral = 177, - ArrayType = 178, - TupleType = 179, - OptionalType = 180, - RestType = 181, - UnionType = 182, - IntersectionType = 183, - ConditionalType = 184, - InferType = 185, - ParenthesizedType = 186, - ThisType = 187, - TypeOperator = 188, - IndexedAccessType = 189, - MappedType = 190, - LiteralType = 191, - NamedTupleMember = 192, - TemplateLiteralType = 193, - TemplateLiteralTypeSpan = 194, - ImportType = 195, - ObjectBindingPattern = 196, - ArrayBindingPattern = 197, - BindingElement = 198, - ArrayLiteralExpression = 199, - ObjectLiteralExpression = 200, - PropertyAccessExpression = 201, - ElementAccessExpression = 202, - CallExpression = 203, - NewExpression = 204, - TaggedTemplateExpression = 205, - TypeAssertionExpression = 206, - ParenthesizedExpression = 207, - FunctionExpression = 208, - ArrowFunction = 209, - DeleteExpression = 210, - TypeOfExpression = 211, - VoidExpression = 212, - AwaitExpression = 213, - PrefixUnaryExpression = 214, - PostfixUnaryExpression = 215, - BinaryExpression = 216, - ConditionalExpression = 217, - TemplateExpression = 218, - YieldExpression = 219, - SpreadElement = 220, - ClassExpression = 221, - OmittedExpression = 222, - ExpressionWithTypeArguments = 223, - AsExpression = 224, - NonNullExpression = 225, - MetaProperty = 226, - SyntheticExpression = 227, - TemplateSpan = 228, - SemicolonClassElement = 229, - Block = 230, - EmptyStatement = 231, - VariableStatement = 232, - ExpressionStatement = 233, - IfStatement = 234, - DoStatement = 235, - WhileStatement = 236, - ForStatement = 237, - ForInStatement = 238, - ForOfStatement = 239, - ContinueStatement = 240, - BreakStatement = 241, - ReturnStatement = 242, - WithStatement = 243, - SwitchStatement = 244, - LabeledStatement = 245, - ThrowStatement = 246, - TryStatement = 247, - DebuggerStatement = 248, - VariableDeclaration = 249, - VariableDeclarationList = 250, - FunctionDeclaration = 251, - ClassDeclaration = 252, - InterfaceDeclaration = 253, - TypeAliasDeclaration = 254, - EnumDeclaration = 255, - ModuleDeclaration = 256, - ModuleBlock = 257, - CaseBlock = 258, - NamespaceExportDeclaration = 259, - ImportEqualsDeclaration = 260, - ImportDeclaration = 261, - ImportClause = 262, - NamespaceImport = 263, - NamedImports = 264, - ImportSpecifier = 265, - ExportAssignment = 266, - ExportDeclaration = 267, - NamedExports = 268, - NamespaceExport = 269, - ExportSpecifier = 270, - MissingDeclaration = 271, - ExternalModuleReference = 272, - JsxElement = 273, - JsxSelfClosingElement = 274, - JsxOpeningElement = 275, - JsxClosingElement = 276, - JsxFragment = 277, - JsxOpeningFragment = 278, - JsxClosingFragment = 279, - JsxAttribute = 280, - JsxAttributes = 281, - JsxSpreadAttribute = 282, - JsxExpression = 283, - CaseClause = 284, - DefaultClause = 285, - HeritageClause = 286, - CatchClause = 287, - PropertyAssignment = 288, - ShorthandPropertyAssignment = 289, - SpreadAssignment = 290, - EnumMember = 291, - UnparsedPrologue = 292, - UnparsedPrepend = 293, - UnparsedText = 294, - UnparsedInternalText = 295, - UnparsedSyntheticReference = 296, - SourceFile = 297, - Bundle = 298, - UnparsedSource = 299, - InputFiles = 300, - JSDocTypeExpression = 301, - JSDocNameReference = 302, - JSDocAllType = 303, - JSDocUnknownType = 304, - JSDocNullableType = 305, - JSDocNonNullableType = 306, - JSDocOptionalType = 307, - JSDocFunctionType = 308, - JSDocVariadicType = 309, - JSDocNamepathType = 310, - JSDocComment = 311, - JSDocTypeLiteral = 312, - JSDocSignature = 313, - JSDocTag = 314, - JSDocAugmentsTag = 315, - JSDocImplementsTag = 316, - JSDocAuthorTag = 317, - JSDocDeprecatedTag = 318, - JSDocClassTag = 319, - JSDocPublicTag = 320, - JSDocPrivateTag = 321, - JSDocProtectedTag = 322, - JSDocReadonlyTag = 323, - JSDocCallbackTag = 324, - JSDocEnumTag = 325, - JSDocParameterTag = 326, - JSDocReturnTag = 327, - JSDocThisTag = 328, - JSDocTypeTag = 329, - JSDocTemplateTag = 330, - JSDocTypedefTag = 331, - JSDocSeeTag = 332, - JSDocPropertyTag = 333, - SyntaxList = 334, - NotEmittedStatement = 335, - PartiallyEmittedExpression = 336, - CommaListExpression = 337, - MergeDeclarationMarker = 338, - EndOfDeclarationMarker = 339, - SyntheticReferenceExpression = 340, - Count = 341, + OverrideKeyword = 156, + OfKeyword = 157, + QualifiedName = 158, + ComputedPropertyName = 159, + TypeParameter = 160, + Parameter = 161, + Decorator = 162, + PropertySignature = 163, + PropertyDeclaration = 164, + MethodSignature = 165, + MethodDeclaration = 166, + Constructor = 167, + GetAccessor = 168, + SetAccessor = 169, + CallSignature = 170, + ConstructSignature = 171, + IndexSignature = 172, + TypePredicate = 173, + TypeReference = 174, + FunctionType = 175, + ConstructorType = 176, + TypeQuery = 177, + TypeLiteral = 178, + ArrayType = 179, + TupleType = 180, + OptionalType = 181, + RestType = 182, + UnionType = 183, + IntersectionType = 184, + ConditionalType = 185, + InferType = 186, + ParenthesizedType = 187, + ThisType = 188, + TypeOperator = 189, + IndexedAccessType = 190, + MappedType = 191, + LiteralType = 192, + NamedTupleMember = 193, + TemplateLiteralType = 194, + TemplateLiteralTypeSpan = 195, + ImportType = 196, + ObjectBindingPattern = 197, + ArrayBindingPattern = 198, + BindingElement = 199, + ArrayLiteralExpression = 200, + ObjectLiteralExpression = 201, + PropertyAccessExpression = 202, + ElementAccessExpression = 203, + CallExpression = 204, + NewExpression = 205, + TaggedTemplateExpression = 206, + TypeAssertionExpression = 207, + ParenthesizedExpression = 208, + FunctionExpression = 209, + ArrowFunction = 210, + DeleteExpression = 211, + TypeOfExpression = 212, + VoidExpression = 213, + AwaitExpression = 214, + PrefixUnaryExpression = 215, + PostfixUnaryExpression = 216, + BinaryExpression = 217, + ConditionalExpression = 218, + TemplateExpression = 219, + YieldExpression = 220, + SpreadElement = 221, + ClassExpression = 222, + OmittedExpression = 223, + ExpressionWithTypeArguments = 224, + AsExpression = 225, + NonNullExpression = 226, + MetaProperty = 227, + SyntheticExpression = 228, + TemplateSpan = 229, + SemicolonClassElement = 230, + Block = 231, + EmptyStatement = 232, + VariableStatement = 233, + ExpressionStatement = 234, + IfStatement = 235, + DoStatement = 236, + WhileStatement = 237, + ForStatement = 238, + ForInStatement = 239, + ForOfStatement = 240, + ContinueStatement = 241, + BreakStatement = 242, + ReturnStatement = 243, + WithStatement = 244, + SwitchStatement = 245, + LabeledStatement = 246, + ThrowStatement = 247, + TryStatement = 248, + DebuggerStatement = 249, + VariableDeclaration = 250, + VariableDeclarationList = 251, + FunctionDeclaration = 252, + ClassDeclaration = 253, + InterfaceDeclaration = 254, + TypeAliasDeclaration = 255, + EnumDeclaration = 256, + ModuleDeclaration = 257, + ModuleBlock = 258, + CaseBlock = 259, + NamespaceExportDeclaration = 260, + ImportEqualsDeclaration = 261, + ImportDeclaration = 262, + ImportClause = 263, + NamespaceImport = 264, + NamedImports = 265, + ImportSpecifier = 266, + ExportAssignment = 267, + ExportDeclaration = 268, + NamedExports = 269, + NamespaceExport = 270, + ExportSpecifier = 271, + MissingDeclaration = 272, + ExternalModuleReference = 273, + JsxElement = 274, + JsxSelfClosingElement = 275, + JsxOpeningElement = 276, + JsxClosingElement = 277, + JsxFragment = 278, + JsxOpeningFragment = 279, + JsxClosingFragment = 280, + JsxAttribute = 281, + JsxAttributes = 282, + JsxSpreadAttribute = 283, + JsxExpression = 284, + CaseClause = 285, + DefaultClause = 286, + HeritageClause = 287, + CatchClause = 288, + PropertyAssignment = 289, + ShorthandPropertyAssignment = 290, + SpreadAssignment = 291, + EnumMember = 292, + UnparsedPrologue = 293, + UnparsedPrepend = 294, + UnparsedText = 295, + UnparsedInternalText = 296, + UnparsedSyntheticReference = 297, + SourceFile = 298, + Bundle = 299, + UnparsedSource = 300, + InputFiles = 301, + JSDocTypeExpression = 302, + JSDocNameReference = 303, + JSDocAllType = 304, + JSDocUnknownType = 305, + JSDocNullableType = 306, + JSDocNonNullableType = 307, + JSDocOptionalType = 308, + JSDocFunctionType = 309, + JSDocVariadicType = 310, + JSDocNamepathType = 311, + JSDocComment = 312, + JSDocText = 313, + JSDocTypeLiteral = 314, + JSDocSignature = 315, + JSDocLink = 316, + JSDocTag = 317, + JSDocAugmentsTag = 318, + JSDocImplementsTag = 319, + JSDocAuthorTag = 320, + JSDocDeprecatedTag = 321, + JSDocClassTag = 322, + JSDocPublicTag = 323, + JSDocPrivateTag = 324, + JSDocProtectedTag = 325, + JSDocReadonlyTag = 326, + JSDocOverrideTag = 327, + JSDocCallbackTag = 328, + JSDocEnumTag = 329, + JSDocParameterTag = 330, + JSDocReturnTag = 331, + JSDocThisTag = 332, + JSDocTypeTag = 333, + JSDocTemplateTag = 334, + JSDocTypedefTag = 335, + JSDocSeeTag = 336, + JSDocPropertyTag = 337, + SyntaxList = 338, + NotEmittedStatement = 339, + PartiallyEmittedExpression = 340, + CommaListExpression = 341, + MergeDeclarationMarker = 342, + EndOfDeclarationMarker = 343, + SyntheticReferenceExpression = 344, + Count = 345, FirstAssignment = 62, LastAssignment = 77, FirstCompoundAssignment = 63, @@ -453,15 +457,15 @@ declare namespace ts { FirstReservedWord = 80, LastReservedWord = 115, FirstKeyword = 80, - LastKeyword = 156, + LastKeyword = 157, FirstFutureReservedWord = 116, LastFutureReservedWord = 124, - FirstTypeNode = 172, - LastTypeNode = 195, + FirstTypeNode = 173, + LastTypeNode = 196, FirstPunctuation = 18, LastPunctuation = 77, FirstToken = 0, - LastToken = 156, + LastToken = 157, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, @@ -470,20 +474,20 @@ declare namespace ts { LastTemplateToken = 17, FirstBinaryOperator = 29, LastBinaryOperator = 77, - FirstStatement = 232, - LastStatement = 248, - FirstNode = 157, - FirstJSDocNode = 301, - LastJSDocNode = 333, - FirstJSDocTagNode = 314, - LastJSDocTagNode = 333, + FirstStatement = 233, + LastStatement = 249, + FirstNode = 158, + FirstJSDocNode = 302, + LastJSDocNode = 337, + FirstJSDocTagNode = 317, + LastJSDocTagNode = 337, } export type TriviaSyntaxKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; export type LiteralSyntaxKind = SyntaxKind.NumericLiteral | SyntaxKind.BigIntLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral; export type PseudoLiteralSyntaxKind = SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle | SyntaxKind.TemplateTail; export type PunctuationSyntaxKind = SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.CloseParenToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.DotToken | SyntaxKind.DotDotDotToken | SyntaxKind.SemicolonToken | SyntaxKind.CommaToken | SyntaxKind.QuestionDotToken | SyntaxKind.LessThanToken | SyntaxKind.LessThanSlashToken | SyntaxKind.GreaterThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.EqualsEqualsToken | SyntaxKind.ExclamationEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.EqualsGreaterThanToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.AsteriskToken | SyntaxKind.AsteriskAsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken | SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken | SyntaxKind.ExclamationToken | SyntaxKind.TildeToken | SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken | SyntaxKind.QuestionQuestionToken | SyntaxKind.QuestionToken | SyntaxKind.ColonToken | SyntaxKind.AtToken | SyntaxKind.BacktickToken | SyntaxKind.EqualsToken | SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken; - export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | 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.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | 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; - export type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.StaticKeyword; + export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | 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.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | 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; + export type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword; export type KeywordTypeSyntaxKind = SyntaxKind.AnyKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VoidKeyword; export type TokenSyntaxKind = SyntaxKind.Unknown | SyntaxKind.EndOfFileToken | TriviaSyntaxKind | LiteralSyntaxKind | PseudoLiteralSyntaxKind | PunctuationSyntaxKind | SyntaxKind.Identifier | KeywordSyntaxKind; export type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; @@ -533,13 +537,14 @@ declare namespace ts { Const = 2048, HasComputedJSDocModifiers = 4096, Deprecated = 8192, + Override = 16384, HasComputedFlags = 536870912, AccessibilityModifier = 28, - ParameterPropertyModifier = 92, + ParameterPropertyModifier = 16476, NonPublicAccessibilityModifier = 24, - TypeScriptModifier = 2270, + TypeScriptModifier = 18654, ExportDefault = 513, - All = 11263 + All = 27647 } export enum JsxFlags { None = 0, @@ -558,7 +563,7 @@ declare namespace ts { } export interface JSDocContainer { } - export type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | NamespaceExportDeclaration | ExportAssignment | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | NamedTupleMember | EndOfFileToken; + export type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | EmptyStatement | DebuggerStatement | Block | VariableStatement | ExpressionStatement | IfStatement | DoStatement | WhileStatement | ForStatement | ForInStatement | ForOfStatement | BreakStatement | ContinueStatement | ReturnStatement | WithStatement | SwitchStatement | LabeledStatement | ThrowStatement | TryStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | VariableDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | NamespaceExportDeclaration | ExportAssignment | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | NamedTupleMember | EndOfFileToken; export type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; export type HasTypeArguments = CallExpression | NewExpression | TaggedTemplateExpression | JsxOpeningElement | JsxSelfClosingElement; export type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; @@ -603,10 +608,11 @@ declare namespace ts { export type ProtectedKeyword = ModifierToken; export type PublicKeyword = ModifierToken; export type ReadonlyKeyword = ModifierToken; + export type OverrideKeyword = ModifierToken; export type StaticKeyword = ModifierToken; /** @deprecated Use `ReadonlyKeyword` instead. */ export type ReadonlyToken = ReadonlyKeyword; - export type Modifier = AbstractKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | ReadonlyKeyword | StaticKeyword; + export type Modifier = AbstractKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | OverrideKeyword | ReadonlyKeyword | StaticKeyword; export type AccessibilityModifier = PublicKeyword | PrivateKeyword | ProtectedKeyword; export type ParameterPropertyModifier = AccessibilityModifier | ReadonlyKeyword; export type ClassMemberModifier = AccessibilityModifier | ReadonlyKeyword | StaticKeyword; @@ -638,6 +644,7 @@ declare namespace ts { } export type EntityName = Identifier | QualifiedName; export type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | PrivateIdentifier; + export type MemberName = Identifier | PrivateIdentifier; export type DeclarationName = Identifier | PrivateIdentifier | StringLiteralLike | NumericLiteral | ComputedPropertyName | ElementAccessExpression | BindingPattern | EntityNameExpression; export interface Declaration extends Node { _declarationBrand: any; @@ -686,7 +693,7 @@ declare namespace ts { readonly kind: SyntaxKind.ConstructSignature; } export type BindingName = Identifier | BindingPattern; - export interface VariableDeclaration extends NamedDeclaration { + export interface VariableDeclaration extends NamedDeclaration, JSDocContainer { readonly kind: SyntaxKind.VariableDeclaration; readonly parent: VariableDeclarationList | CatchClause; readonly name: BindingName; @@ -820,15 +827,15 @@ declare namespace ts { readonly kind: SyntaxKind.SemicolonClassElement; readonly parent: ClassLikeDeclaration; } - export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.GetAccessor; - readonly parent: ClassLikeDeclaration | ObjectLiteralExpression; + readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; readonly name: PropertyName; readonly body?: FunctionBody; } - export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.SetAccessor; - readonly parent: ClassLikeDeclaration | ObjectLiteralExpression; + readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; readonly name: PropertyName; readonly body?: FunctionBody; } @@ -1216,11 +1223,11 @@ declare namespace ts { readonly kind: SyntaxKind.PropertyAccessExpression; readonly expression: LeftHandSideExpression; readonly questionDotToken?: QuestionDotToken; - readonly name: Identifier | PrivateIdentifier; + readonly name: MemberName; } export interface PropertyAccessChain extends PropertyAccessExpression { _optionalChainBrand: any; - readonly name: Identifier | PrivateIdentifier; + readonly name: MemberName; } export interface SuperPropertyAccessExpression extends PropertyAccessExpression { readonly expression: SuperExpression; @@ -1373,7 +1380,7 @@ declare namespace ts { readonly containsOnlyTriviaWhiteSpaces: boolean; } export type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; - export interface Statement extends Node { + export interface Statement extends Node, JSDocContainer { _statementBrand: any; } export interface NotEmittedStatement extends Statement { @@ -1401,11 +1408,11 @@ declare namespace ts { readonly kind: SyntaxKind.Block; readonly statements: NodeArray; } - export interface VariableStatement extends Statement, JSDocContainer { + export interface VariableStatement extends Statement { readonly kind: SyntaxKind.VariableStatement; readonly declarationList: VariableDeclarationList; } - export interface ExpressionStatement extends Statement, JSDocContainer { + export interface ExpressionStatement extends Statement { readonly kind: SyntaxKind.ExpressionStatement; readonly expression: Expression; } @@ -1486,7 +1493,7 @@ declare namespace ts { readonly statements: NodeArray; } export type CaseOrDefaultClause = CaseClause | DefaultClause; - export interface LabeledStatement extends Statement, JSDocContainer { + export interface LabeledStatement extends Statement { readonly kind: SyntaxKind.LabeledStatement; readonly label: Identifier; readonly statement: Statement; @@ -1606,7 +1613,7 @@ declare namespace ts { readonly parent: ImportEqualsDeclaration; readonly expression: Expression; } - export interface ImportDeclaration extends Statement, JSDocContainer { + export interface ImportDeclaration extends Statement { readonly kind: SyntaxKind.ImportDeclaration; readonly parent: SourceFile | ModuleBlock; readonly importClause?: ImportClause; @@ -1742,12 +1749,21 @@ declare namespace ts { readonly kind: SyntaxKind.JSDocComment; readonly parent: HasJSDoc; readonly tags?: NodeArray; - readonly comment?: string; + readonly comment?: string | NodeArray; } export interface JSDocTag extends Node { readonly parent: JSDoc | JSDocTypeLiteral; readonly tagName: Identifier; - readonly comment?: string; + readonly comment?: string | NodeArray; + } + export interface JSDocLink extends Node { + readonly kind: SyntaxKind.JSDocLink; + readonly name?: EntityName; + text: string; + } + export interface JSDocText extends Node { + readonly kind: SyntaxKind.JSDocText; + text: string; } export interface JSDocUnknownTag extends JSDocTag { readonly kind: SyntaxKind.JSDocTag; @@ -1789,6 +1805,9 @@ declare namespace ts { export interface JSDocReadonlyTag extends JSDocTag { readonly kind: SyntaxKind.JSDocReadonlyTag; } + export interface JSDocOverrideTag extends JSDocTag { + readonly kind: SyntaxKind.JSDocOverrideTag; + } export interface JSDocEnumTag extends JSDocTag, Declaration { readonly kind: SyntaxKind.JSDocEnumTag; readonly parent: JSDoc; @@ -2080,7 +2099,6 @@ declare namespace ts { * Gets a type checker that can be used to semantically analyze source files in the program. */ getTypeChecker(): TypeChecker; - getTypeCatalog(): readonly Type[]; getNodeCount(): number; getIdentifierCount(): number; getSymbolCount(): number; @@ -2186,7 +2204,7 @@ declare namespace ts { * The function returns the value (local variable) symbol of an identifier in the short-hand property assignment. * This is necessary as an identifier in short-hand property assignment can contains two meaning: property name and property value. */ - getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getShorthandAssignmentValueSymbol(location: Node | undefined): Symbol | undefined; getExportSpecifierLocalTargetSymbol(location: ExportSpecifier | Identifier): Symbol | undefined; /** * If a symbol is a local symbol with an associated exported symbol, returns the exported symbol. @@ -2261,6 +2279,8 @@ declare namespace ts { NoTypeReduction = 536870912, NoUndefinedOptionalParameterType = 1073741824, AllowThisInObjectLiteral = 32768, + AllowQualifiedNameInPlaceOfIdentifier = 65536, + /** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */ AllowQualifedNameInPlaceOfIdentifier = 65536, AllowAnonymousIdentifier = 131072, AllowEmptyUnionOrIntersection = 262144, @@ -2271,8 +2291,7 @@ declare namespace ts { IgnoreErrors = 70221824, InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, - InInitialEntityName = 16777216, - InReverseMappedType = 33554432 + InInitialEntityName = 16777216 } export enum TypeFormatFlags { None = 0, @@ -2405,8 +2424,8 @@ declare namespace ts { export interface Symbol { flags: SymbolFlags; escapedName: __String; - declarations: Declaration[]; - valueDeclaration: Declaration; + declarations?: Declaration[]; + valueDeclaration?: Declaration; members?: SymbolTable; exports?: SymbolTable; globalExports?: SymbolTable; @@ -2540,15 +2559,15 @@ declare namespace ts { ObjectLiteral = 128, EvolvingArray = 256, ObjectLiteralPatternWithComputedProperties = 512, - ContainsSpread = 1024, - ReverseMapped = 2048, - JsxAttributes = 4096, - MarkerType = 8192, - JSLiteral = 16384, - FreshLiteral = 32768, - ArrayLiteral = 65536, - ObjectRestType = 131072, + ReverseMapped = 1024, + JsxAttributes = 2048, + MarkerType = 4096, + JSLiteral = 8192, + FreshLiteral = 16384, + ArrayLiteral = 32768, ClassOrInterface = 3, + ContainsSpread = 4194304, + ObjectRestType = 8388608, } export interface ObjectType extends Type { objectFlags: ObjectFlags; @@ -2662,6 +2681,7 @@ declare namespace ts { type: Type; } export interface SubstitutionType extends InstantiableType { + objectFlags: ObjectFlags; baseType: Type; substitute: Type; } @@ -2686,16 +2706,17 @@ declare namespace ts { export enum InferencePriority { NakedTypeVariable = 1, SpeculativeTuple = 2, - HomomorphicMappedType = 4, - PartialHomomorphicMappedType = 8, - MappedTypeConstraint = 16, - ContravariantConditional = 32, - ReturnType = 64, - LiteralKeyof = 128, - NoConstraints = 256, - AlwaysStrict = 512, - MaxValue = 1024, - PriorityImpliesCombination = 208, + SubstituteSource = 4, + HomomorphicMappedType = 8, + PartialHomomorphicMappedType = 16, + MappedTypeConstraint = 32, + ContravariantConditional = 64, + ReturnType = 128, + LiteralKeyof = 256, + NoConstraints = 512, + AlwaysStrict = 1024, + MaxValue = 2048, + PriorityImpliesCombination = 416, Circularity = -1 } /** @deprecated Use FileExtensionInfo instead. */ @@ -2772,18 +2793,21 @@ declare namespace ts { FixedPollingInterval = 0, PriorityPollingInterval = 1, DynamicPriorityPolling = 2, - UseFsEvents = 3, - UseFsEventsOnParentDirectory = 4 + FixedChunkSizePolling = 3, + UseFsEvents = 4, + UseFsEventsOnParentDirectory = 5 } export enum WatchDirectoryKind { UseFsEvents = 0, FixedPollingInterval = 1, - DynamicPriorityPolling = 2 + DynamicPriorityPolling = 2, + FixedChunkSizePolling = 3 } export enum PollingWatchKind { FixedInterval = 0, PriorityInterval = 1, - DynamicPriority = 2 + DynamicPriority = 2, + FixedChunkSize = 3 } export type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; export interface CompilerOptions { @@ -2845,6 +2869,7 @@ declare namespace ts { outFile?: string; paths?: MapLike; preserveConstEnums?: boolean; + noImplicitOverride?: boolean; preserveSymlinks?: boolean; project?: string; reactNamespace?: string; @@ -2955,6 +2980,7 @@ declare namespace ts { ES2018 = 5, ES2019 = 6, ES2020 = 7, + ES2021 = 8, ESNext = 99, JSON = 100, Latest = 99 @@ -3128,17 +3154,21 @@ declare namespace ts { Iterator = 8388608, NoAsciiEscaping = 16777216, } - export interface EmitHelper { + export interface EmitHelperBase { readonly name: string; readonly scoped: boolean; readonly text: string | ((node: EmitHelperUniqueNameCallback) => string); readonly priority?: number; readonly dependencies?: EmitHelper[]; } - export interface UnscopedEmitHelper extends EmitHelper { + export interface ScopedEmitHelper extends EmitHelperBase { + readonly scoped: true; + } + export interface UnscopedEmitHelper extends EmitHelperBase { readonly scoped: false; readonly text: string; } + export type EmitHelper = ScopedEmitHelper | UnscopedEmitHelper; export type EmitHelperUniqueNameCallback = (name: string) => string; export enum EmitHint { SourceFile = 0, @@ -3166,14 +3196,27 @@ declare namespace ts { createStringLiteralFromNode(sourceNode: PropertyNameLiteral, isSingleQuote?: boolean): StringLiteral; createRegularExpressionLiteral(text: string): RegularExpressionLiteral; createIdentifier(text: string): Identifier; - /** Create a unique temporary variable. */ - createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; - /** Create a unique temporary variable for use in a loop. */ - createLoopVariable(): Identifier; + /** + * Create a unique temporary variable. + * @param recordTempVariable An optional callback used to record the temporary variable name. This + * should usually be a reference to `hoistVariableDeclaration` from a `TransformationContext`, but + * can be `undefined` if you plan to record the temporary variable manually. + * @param reservedInNestedScopes When `true`, reserves the temporary variable name in all nested scopes + * during emit so that the variable can be referenced in a nested function body. This is an alternative to + * setting `EmitFlags.ReuseTempVariableScope` on the nested function itself. + */ + createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, reservedInNestedScopes?: boolean): Identifier; + /** + * Create a unique temporary variable for use in a loop. + * @param reservedInNestedScopes When `true`, reserves the temporary variable name in all nested scopes + * during emit so that the variable can be referenced in a nested function body. This is an alternative to + * setting `EmitFlags.ReuseTempVariableScope` on the nested function itself. + */ + createLoopVariable(reservedInNestedScopes?: boolean): Identifier; /** Create a unique name based on the supplied text. */ createUniqueName(text: string, flags?: GeneratedIdentifierFlags): Identifier; /** Create a unique name generated for a node. */ - getGeneratedNameForNode(node: Node | undefined): Identifier; + getGeneratedNameForNode(node: Node | undefined, flags?: GeneratedIdentifierFlags): Identifier; createPrivateIdentifier(text: string): PrivateIdentifier; createToken(token: SyntaxKind.SuperKeyword): SuperExpression; createToken(token: SyntaxKind.ThisKeyword): ThisExpression; @@ -3284,10 +3327,10 @@ declare namespace ts { updateArrayLiteralExpression(node: ArrayLiteralExpression, elements: readonly Expression[]): ArrayLiteralExpression; createObjectLiteralExpression(properties?: readonly ObjectLiteralElementLike[], multiLine?: boolean): ObjectLiteralExpression; updateObjectLiteralExpression(node: ObjectLiteralExpression, properties: readonly ObjectLiteralElementLike[]): ObjectLiteralExpression; - createPropertyAccessExpression(expression: Expression, name: string | Identifier | PrivateIdentifier): PropertyAccessExpression; - updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: Identifier | PrivateIdentifier): PropertyAccessExpression; - createPropertyAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | Identifier | PrivateIdentifier): PropertyAccessChain; - updatePropertyAccessChain(node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: Identifier | PrivateIdentifier): PropertyAccessChain; + createPropertyAccessExpression(expression: Expression, name: string | MemberName): PropertyAccessExpression; + updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: MemberName): PropertyAccessExpression; + createPropertyAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | MemberName): PropertyAccessChain; + updatePropertyAccessChain(node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: MemberName): PropertyAccessChain; createElementAccessExpression(expression: Expression, index: number | Expression): ElementAccessExpression; updateElementAccessExpression(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; createElementAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, index: number | Expression): ElementAccessChain; @@ -3455,52 +3498,58 @@ declare namespace ts { updateJSDocTypeExpression(node: JSDocTypeExpression, type: TypeNode): JSDocTypeExpression; createJSDocNameReference(name: EntityName): JSDocNameReference; updateJSDocNameReference(node: JSDocNameReference, name: EntityName): JSDocNameReference; + createJSDocLink(name: EntityName | undefined, text: string): JSDocLink; + updateJSDocLink(node: JSDocLink, name: EntityName | undefined, text: string): JSDocLink; createJSDocTypeLiteral(jsDocPropertyTags?: readonly JSDocPropertyLikeTag[], isArrayType?: boolean): JSDocTypeLiteral; updateJSDocTypeLiteral(node: JSDocTypeLiteral, jsDocPropertyTags: readonly JSDocPropertyLikeTag[] | undefined, isArrayType: boolean | undefined): JSDocTypeLiteral; createJSDocSignature(typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag): JSDocSignature; updateJSDocSignature(node: JSDocSignature, typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type: JSDocReturnTag | undefined): JSDocSignature; - createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string): JSDocTemplateTag; - updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | undefined): JSDocTemplateTag; - createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string): JSDocTypedefTag; - updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | undefined): JSDocTypedefTag; - createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string): JSDocParameterTag; - updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | undefined): JSDocParameterTag; - createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string): JSDocPropertyTag; - updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | undefined): JSDocPropertyTag; - createJSDocTypeTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string): JSDocTypeTag; - updateJSDocTypeTag(node: JSDocTypeTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | undefined): JSDocTypeTag; - createJSDocSeeTag(tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string): JSDocSeeTag; - updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string): JSDocSeeTag; - createJSDocReturnTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string): JSDocReturnTag; - updateJSDocReturnTag(node: JSDocReturnTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | undefined): JSDocReturnTag; - createJSDocThisTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string): JSDocThisTag; - updateJSDocThisTag(node: JSDocThisTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | undefined): JSDocThisTag; - createJSDocEnumTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string): JSDocEnumTag; - updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | undefined): JSDocEnumTag; - createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string): JSDocCallbackTag; - updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | undefined): JSDocCallbackTag; - createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string): JSDocAugmentsTag; - updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment: string | undefined): JSDocAugmentsTag; - createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string): JSDocImplementsTag; - updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment: string | undefined): JSDocImplementsTag; - createJSDocAuthorTag(tagName: Identifier | undefined, comment?: string): JSDocAuthorTag; - updateJSDocAuthorTag(node: JSDocAuthorTag, tagName: Identifier | undefined, comment: string | undefined): JSDocAuthorTag; - createJSDocClassTag(tagName: Identifier | undefined, comment?: string): JSDocClassTag; - updateJSDocClassTag(node: JSDocClassTag, tagName: Identifier | undefined, comment: string | undefined): JSDocClassTag; - createJSDocPublicTag(tagName: Identifier | undefined, comment?: string): JSDocPublicTag; - updateJSDocPublicTag(node: JSDocPublicTag, tagName: Identifier | undefined, comment: string | undefined): JSDocPublicTag; - createJSDocPrivateTag(tagName: Identifier | undefined, comment?: string): JSDocPrivateTag; - updateJSDocPrivateTag(node: JSDocPrivateTag, tagName: Identifier | undefined, comment: string | undefined): JSDocPrivateTag; - createJSDocProtectedTag(tagName: Identifier | undefined, comment?: string): JSDocProtectedTag; - updateJSDocProtectedTag(node: JSDocProtectedTag, tagName: Identifier | undefined, comment: string | undefined): JSDocProtectedTag; - createJSDocReadonlyTag(tagName: Identifier | undefined, comment?: string): JSDocReadonlyTag; - updateJSDocReadonlyTag(node: JSDocReadonlyTag, tagName: Identifier | undefined, comment: string | undefined): JSDocReadonlyTag; - createJSDocUnknownTag(tagName: Identifier, comment?: string): JSDocUnknownTag; - updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | undefined): JSDocUnknownTag; - createJSDocDeprecatedTag(tagName: Identifier, comment?: string): JSDocDeprecatedTag; - updateJSDocDeprecatedTag(node: JSDocDeprecatedTag, tagName: Identifier, comment?: string): JSDocDeprecatedTag; - createJSDocComment(comment?: string | undefined, tags?: readonly JSDocTag[] | undefined): JSDoc; - updateJSDocComment(node: JSDoc, comment: string | undefined, tags: readonly JSDocTag[] | undefined): JSDoc; + createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray): JSDocTemplateTag; + updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | NodeArray | undefined): JSDocTemplateTag; + createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocTypedefTag; + updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocTypedefTag; + createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocParameterTag; + updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocParameterTag; + createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocPropertyTag; + updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocPropertyTag; + createJSDocTypeTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocTypeTag; + updateJSDocTypeTag(node: JSDocTypeTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined): JSDocTypeTag; + createJSDocSeeTag(tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag; + updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag; + createJSDocReturnTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray): JSDocReturnTag; + updateJSDocReturnTag(node: JSDocReturnTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined): JSDocReturnTag; + createJSDocThisTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocThisTag; + updateJSDocThisTag(node: JSDocThisTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined): JSDocThisTag; + createJSDocEnumTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocEnumTag; + updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined): JSDocEnumTag; + createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocCallbackTag; + updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocCallbackTag; + createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string | NodeArray): JSDocAugmentsTag; + updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment: string | NodeArray | undefined): JSDocAugmentsTag; + createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string | NodeArray): JSDocImplementsTag; + updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment: string | NodeArray | undefined): JSDocImplementsTag; + createJSDocAuthorTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocAuthorTag; + updateJSDocAuthorTag(node: JSDocAuthorTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocAuthorTag; + createJSDocClassTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocClassTag; + updateJSDocClassTag(node: JSDocClassTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocClassTag; + createJSDocPublicTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocPublicTag; + updateJSDocPublicTag(node: JSDocPublicTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocPublicTag; + createJSDocPrivateTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocPrivateTag; + updateJSDocPrivateTag(node: JSDocPrivateTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocPrivateTag; + createJSDocProtectedTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocProtectedTag; + updateJSDocProtectedTag(node: JSDocProtectedTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocProtectedTag; + createJSDocReadonlyTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocReadonlyTag; + updateJSDocReadonlyTag(node: JSDocReadonlyTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocReadonlyTag; + createJSDocUnknownTag(tagName: Identifier, comment?: string | NodeArray): JSDocUnknownTag; + updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | NodeArray | undefined): JSDocUnknownTag; + createJSDocDeprecatedTag(tagName: Identifier, comment?: string | NodeArray): JSDocDeprecatedTag; + updateJSDocDeprecatedTag(node: JSDocDeprecatedTag, tagName: Identifier, comment?: string | NodeArray): JSDocDeprecatedTag; + createJSDocOverrideTag(tagName: Identifier, comment?: string | NodeArray): JSDocOverrideTag; + updateJSDocOverrideTag(node: JSDocOverrideTag, tagName: Identifier, comment?: string | NodeArray): JSDocOverrideTag; + createJSDocText(text: string): JSDocText; + updateJSDocText(node: JSDocText, text: string): JSDocText; + createJSDocComment(comment?: string | NodeArray | undefined, tags?: readonly JSDocTag[] | undefined): JSDoc; + updateJSDocComment(node: JSDoc, comment: string | NodeArray | undefined, tags: readonly JSDocTag[] | undefined): JSDoc; createJsxElement(openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement; updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement; createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxSelfClosingElement; @@ -3748,12 +3797,12 @@ declare namespace ts { * }); * ``` */ - onEmitNode?(hint: EmitHint, node: Node | undefined, emitCallback: (hint: EmitHint, node: Node | undefined) => void): void; + onEmitNode?(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; /** * A hook used to check if an emit notification is required for a node. * @param node The node to emit. */ - isEmitNotificationEnabled?(node: Node | undefined): boolean; + isEmitNotificationEnabled?(node: Node): boolean; /** * A hook used by the Printer to perform just-in-time substitution of a node. This is * primarily used by node transformations that need to substitute one node for another, @@ -3867,6 +3916,8 @@ declare namespace ts { readonly disableSuggestions?: boolean; readonly quotePreference?: "auto" | "double" | "single"; readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsForImportStatements?: boolean; + readonly includeCompletionsWithSnippetText?: boolean; readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; @@ -3965,7 +4016,7 @@ declare namespace ts { scanJsxIdentifier(): SyntaxKind; scanJsxAttributeValue(): SyntaxKind; reScanJsxAttributeValue(): SyntaxKind; - reScanJsxToken(): JsxTokenSyntaxKind; + reScanJsxToken(allowMultilineJsxText?: boolean): JsxTokenSyntaxKind; reScanLessThanToken(): SyntaxKind; reScanQuestionToken(): SyntaxKind; reScanInvalidIdentifier(): SyntaxKind; @@ -4100,7 +4151,7 @@ declare namespace ts { function idText(identifierOrPrivateName: Identifier | PrivateIdentifier): string; function symbolName(symbol: Symbol): string; function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | PrivateIdentifier | undefined; - function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined; + function getNameOfDeclaration(declaration: Declaration | Expression | undefined): DeclarationName | undefined; /** * Gets the JSDoc parameter tags for the node if present. * @@ -4146,6 +4197,7 @@ declare namespace ts { function getJSDocProtectedTag(node: Node): JSDocProtectedTag | undefined; /** Gets the JSDoc protected tag for the node if present */ function getJSDocReadonlyTag(node: Node): JSDocReadonlyTag | undefined; + function getJSDocOverrideTagNoCache(node: Node): JSDocOverrideTag | undefined; /** Gets the JSDoc deprecated tag for the node if present */ function getJSDocDeprecatedTag(node: Node): JSDocDeprecatedTag | undefined; /** Gets the JSDoc enum tag for the node if present */ @@ -4183,13 +4235,15 @@ declare namespace ts { function getAllJSDocTags(node: Node, predicate: (tag: JSDocTag) => tag is T): readonly T[]; /** Gets all JSDoc tags of a specified kind */ function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): readonly JSDocTag[]; + /** Gets the text of a jsdoc comment, flattening links to their text. */ + function getTextOfJSDocComment(comment?: string | NodeArray): string | undefined; /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. */ function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): readonly TypeParameterDeclaration[]; function getEffectiveConstraintOfTypeParameter(node: TypeParameterDeclaration): TypeNode | undefined; - function isIdentifierOrPrivateIdentifier(node: Node): node is Identifier | PrivateIdentifier; + function isMemberName(node: Node): node is MemberName; function isPropertyAccessChain(node: Node): node is PropertyAccessChain; function isElementAccessChain(node: Node): node is ElementAccessChain; function isCallChain(node: Node): node is CallChain; @@ -4204,6 +4258,12 @@ declare namespace ts { function isUnparsedTextLike(node: Node): node is UnparsedTextLike; function isUnparsedNode(node: Node): node is UnparsedNode; function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag; + /** + * True if kind is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + function isTokenKind(kind: SyntaxKind): boolean; /** * True if node is of some token syntax kind. * For example, this is true for an IfKeyword but not for an IfStatement. @@ -4220,7 +4280,7 @@ declare namespace ts { function isEntityName(node: Node): node is EntityName; function isPropertyName(node: Node): node is PropertyName; function isBindingName(node: Node): node is BindingName; - function isFunctionLike(node: Node): node is SignatureDeclaration; + function isFunctionLike(node: Node | undefined): node is SignatureDeclaration; function isClassElement(node: Node): node is ClassElement; function isClassLike(node: Node): node is ClassLikeDeclaration; function isAccessor(node: Node): node is AccessorDeclaration; @@ -4346,10 +4406,14 @@ declare namespace ts { function isTemplateHead(node: Node): node is TemplateHead; function isTemplateMiddle(node: Node): node is TemplateMiddle; function isTemplateTail(node: Node): node is TemplateTail; + function isDotDotDotToken(node: Node): node is DotDotDotToken; + function isPlusToken(node: Node): node is PlusToken; + function isMinusToken(node: Node): node is MinusToken; + function isAsteriskToken(node: Node): node is AsteriskToken; function isIdentifier(node: Node): node is Identifier; + function isPrivateIdentifier(node: Node): node is PrivateIdentifier; function isQualifiedName(node: Node): node is QualifiedName; function isComputedPropertyName(node: Node): node is ComputedPropertyName; - function isPrivateIdentifier(node: Node): node is PrivateIdentifier; function isTypeParameterDeclaration(node: Node): node is TypeParameterDeclaration; function isParameter(node: Node): node is ParameterDeclaration; function isDecorator(node: Node): node is Decorator; @@ -4492,6 +4556,7 @@ declare namespace ts { function isUnparsedSource(node: Node): node is UnparsedSource; function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression; function isJSDocNameReference(node: Node): node is JSDocNameReference; + function isJSDocLink(node: Node): node is JSDocLink; function isJSDocAllType(node: Node): node is JSDocAllType; function isJSDocUnknownType(node: Node): node is JSDocUnknownType; function isJSDocNullableType(node: Node): node is JSDocNullableType; @@ -4511,6 +4576,7 @@ declare namespace ts { function isJSDocPrivateTag(node: Node): node is JSDocPrivateTag; function isJSDocProtectedTag(node: Node): node is JSDocProtectedTag; function isJSDocReadonlyTag(node: Node): node is JSDocReadonlyTag; + function isJSDocOverrideTag(node: Node): node is JSDocOverrideTag; function isJSDocDeprecatedTag(node: Node): node is JSDocDeprecatedTag; function isJSDocSeeTag(node: Node): node is JSDocSeeTag; function isJSDocEnumTag(node: Node): node is JSDocEnumTag; @@ -4575,7 +4641,7 @@ declare namespace ts { /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ - export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): ParsedCommandLine | undefined; + export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions | undefined, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): ParsedCommandLine | undefined; /** * Read tsconfig.json file * @param fileName The path to the config file @@ -4643,13 +4709,13 @@ declare namespace ts { export {}; } declare namespace ts { - function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; + export function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, cache?: TypeReferenceDirectiveResolutionCache): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -4658,30 +4724,46 @@ declare namespace ts { * More type directives might appear in the program later as a result of loading actual source files; * this list is only the set of defaults that are implicitly included. */ - function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + export function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + export interface TypeReferenceDirectiveResolutionCache extends PerDirectoryResolutionCache, PackageJsonInfoCache { + } /** - * Cached module resolutions per containing directory. + * Cached resolutions per containing directory. * This assumes that any module id will have the same resolution for sibling files located in the same folder. */ - interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { - getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + export interface PerDirectoryResolutionCache { + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + clear(): void; + /** + * Updates with the current compilerOptions the cache will operate with. + * This updates the redirects map as well if needed so module resolutions are cached if they can across the projects + */ + update(options: CompilerOptions): void; + } + export interface ModuleResolutionCache extends PerDirectoryResolutionCache, NonRelativeModuleNameResolutionCache, PackageJsonInfoCache { + getPackageJsonInfoCache(): PackageJsonInfoCache; } /** * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. */ - interface NonRelativeModuleNameResolutionCache { + export interface NonRelativeModuleNameResolutionCache extends PackageJsonInfoCache { getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; } - interface PerModuleNameCache { + export interface PackageJsonInfoCache { + clear(): void; + } + export interface PerModuleNameCache { get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; } - function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions): ModuleResolutionCache; - function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions): ModuleResolutionCache; + export function createTypeReferenceDirectiveResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions, packageJsonInfoCache?: PackageJsonInfoCache): TypeReferenceDirectiveResolutionCache; + export function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; + export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export {}; } declare namespace ts { /** @@ -4748,6 +4830,10 @@ declare namespace ts { * environment and merging hoisted declarations upon completion. */ function visitFunctionBody(node: ConciseBody, visitor: Visitor, context: TransformationContext): ConciseBody; + /** + * Visits an iteration body, adding any block-scoped variables required by the transformation. + */ + function visitIterationBody(body: Statement, visitor: Visitor, context: TransformationContext): Statement; /** * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place. * @@ -5036,6 +5122,8 @@ declare namespace ts { interface WatchCompilerHost extends ProgramHost, WatchHost { /** Instead of using output d.ts file from project reference, use its source file */ useSourceOfProjectReferenceRedirect?(): boolean; + /** If provided, use this method to get parsed command lines for referenced projects */ + getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; } @@ -5131,9 +5219,9 @@ declare namespace ts { interface SolutionBuilderWithWatchHost extends SolutionBuilderHostBase, WatchHost { } interface SolutionBuilder { - build(project?: string, cancellationToken?: CancellationToken): ExitStatus; + build(project?: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; clean(project?: string): ExitStatus; - buildReferences(project: string, cancellationToken?: CancellationToken): ExitStatus; + buildReferences(project: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; cleanReferences(project?: string): ExitStatus; getNextInvalidatedProject(cancellationToken?: CancellationToken): InvalidatedProject | undefined; } @@ -5291,7 +5379,7 @@ declare namespace ts { getName(): string; getDeclarations(): Declaration[] | undefined; getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; - getJsDocTags(): JSDocTagInfo[]; + getJsDocTags(checker?: TypeChecker): JSDocTagInfo[]; } interface Type { getFlags(): TypeFlags; @@ -5422,6 +5510,7 @@ declare namespace ts { isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; writeFile?(fileName: string, content: string): void; + getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; } type WithMetadata = T & { metadata?: unknown; @@ -5511,12 +5600,13 @@ declare namespace ts { * * @param fileName The path to the file * @param position A zero based index of the character where you want the entries - * @param entryName The name from an existing completion which came from `getCompletionsAtPosition` + * @param entryName The `name` from an existing completion which came from `getCompletionsAtPosition` * @param formatOptions How should code samples in the completions be formatted, can be undefined for backwards compatibility - * @param source Source code for the current file, can be undefined for backwards compatibility + * @param source `source` property from the completion entry * @param preferences User settings, can be undefined for backwards compatibility + * @param data `data` property from the completion entry */ - getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; + getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined, data: CompletionEntryData | undefined): CompletionEntryDetails | undefined; getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; /** * Gets semantic information about the identifier at a particular position in a @@ -5577,7 +5667,7 @@ declare namespace ts { applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise; getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined, triggerReason?: RefactorTriggerReason, kind?: string): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; - organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; + organizeImports(args: OrganizeImportsArgs, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; getProgram(): Program | undefined; @@ -5594,8 +5684,10 @@ declare namespace ts { type: "file"; fileName: string; } - type OrganizeImportsScope = CombinedCodeFixScope; - type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#"; + interface OrganizeImportsArgs extends CombinedCodeFixScope { + skipDestructiveCodeActions?: boolean; + } + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; interface GetCompletionsAtPositionOptions extends UserPreferences { /** * If the editor is asking for completions because a certain character was typed @@ -5947,6 +6039,7 @@ declare namespace ts { name: string; containerKind: ScriptElementKind; containerName: string; + unverified?: boolean; } interface DefinitionInfoAndBoundSpan { definitions?: readonly DefinitionInfo[]; @@ -5981,15 +6074,21 @@ declare namespace ts { typeParameterName = 18, enumMemberName = 19, functionName = 20, - regularExpressionLiteral = 21 + regularExpressionLiteral = 21, + link = 22, + linkName = 23, + linkText = 24 } interface SymbolDisplayPart { text: string; kind: string; } + interface JSDocLinkDisplayPart extends SymbolDisplayPart { + target: DocumentSpan; + } interface JSDocTagInfo { name: string; - text?: string; + text?: SymbolDisplayPart[]; } interface QuickInfo { kind: ScriptElementKind; @@ -6074,14 +6173,36 @@ declare namespace ts { * true when the current location also allows for a new identifier */ isNewIdentifierLocation: boolean; + /** + * Indicates to client to continue requesting completions on subsequent keystrokes. + */ + isIncomplete?: true; entries: CompletionEntry[]; } + interface CompletionEntryData { + /** The file name declaring the export's module symbol, if it was an external module */ + fileName?: string; + /** The module name (with quotes stripped) of the export's module symbol, if it was an ambient module */ + ambientModuleName?: string; + /** True if the export was found in the package.json AutoImportProvider */ + isPackageJsonImport?: true; + /** + * The name of the property or export in the module's symbol table. Differs from the completion name + * in the case of InternalSymbolName.ExportEquals and InternalSymbolName.Default. + */ + exportName: string; + /** + * Set for auto imports with eagerly resolved module specifiers. + */ + moduleSpecifier?: string; + } interface CompletionEntry { name: string; kind: ScriptElementKind; kindModifiers?: string; sortText: string; insertText?: string; + isSnippet?: true; /** * An optional span that indicates the text to be replaced by this completion item. * If present, this span should be used instead of the default one. @@ -6090,9 +6211,20 @@ declare namespace ts { replacementSpan?: TextSpan; hasAction?: true; source?: string; + sourceDisplay?: SymbolDisplayPart[]; isRecommended?: true; isFromUncheckedFile?: true; isPackageJsonImport?: true; + isImportStatementCompletion?: true; + /** + * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, + * that allows TS Server to look up the symbol represented by the completion item, disambiguating + * items with the same name. Currently only defined for auto-import completions, but the type is + * `unknown` in the protocol, so it can be changed as needed to support other kinds of completions. + * The presence of this property should generally not be used to assume that this completion entry + * is an auto-import. + */ + data?: CompletionEntryData; } interface CompletionEntryDetails { name: string; @@ -6102,7 +6234,9 @@ declare namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; codeActions?: CodeAction[]; + /** @deprecated Use `sourceDisplay` instead. */ source?: SymbolDisplayPart[]; + sourceDisplay?: SymbolDisplayPart[]; } interface OutliningSpan { /** The span of the document to actually collapse. */ @@ -6256,7 +6390,13 @@ declare namespace ts { */ jsxAttribute = "JSX attribute", /** String literal */ - string = "string" + string = "string", + /** Jsdoc @link: in `{@link C link text}`, the before and after text "{@link " and "}" */ + link = "link", + /** Jsdoc @link: in `{@link C link text}`, the entity name "C" */ + linkName = "link name", + /** Jsdoc @link: in `{@link C link text}`, the link text "link text" */ + linkText = "link text" } enum ScriptElementKindModifier { none = "", @@ -6397,8 +6537,23 @@ declare namespace ts { * @param fileName The name of the file to be released * @param compilationSettings The compilation settings used to acquire the file */ + /**@deprecated pass scriptKind for correctness */ releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + /** + * Informs the DocumentRegistry that a file is not needed any longer. + * + * Note: It is not allowed to call release on a SourceFile that was not acquired from + * this registry originally. + * + * @param fileName The name of the file to be released + * @param compilationSettings The compilation settings used to acquire the file + * @param scriptKind The script kind of the file to be released + */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind: ScriptKind): void; + /** + * @deprecated pass scriptKind for correctness */ releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind: ScriptKind): void; reportStats(): string; } type DocumentRegistryBucketKey = string & { @@ -7034,6 +7189,7 @@ declare namespace ts.server.protocol { type OrganizeImportsScope = GetCombinedCodeFixScope; interface OrganizeImportsRequestArgs { scope: OrganizeImportsScope; + skipDestructiveCodeActions?: boolean; } interface OrganizeImportsResponse extends Response { body: readonly FileCodeEdits[]; @@ -7136,6 +7292,41 @@ declare namespace ts.server.protocol { */ body?: string[]; } + /** + * A request to get encoded semantic classifications for a span in the file + */ + interface EncodedSemanticClassificationsRequest extends FileRequest { + arguments: EncodedSemanticClassificationsRequestArgs; + } + /** + * Arguments for EncodedSemanticClassificationsRequest request. + */ + interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { + /** + * Start position of the span. + */ + start: number; + /** + * Length of the span. + */ + length: number; + /** + * Optional parameter for the semantic highlighting response, if absent it + * defaults to "original". + */ + format?: "original" | "2020"; + } + /** The response for a EncodedSemanticClassificationsRequest */ + interface EncodedSemanticClassificationsResponse extends Response { + body?: EncodedSemanticClassificationsResponseBody; + } + /** + * Implementation response message. Gives series of text spans depending on the format ar. + */ + interface EncodedSemanticClassificationsResponseBody { + endOfLineState: EndOfLineState; + spans: number[]; + } /** * Arguments in document highlight request; include: filesToSearch, file, * line, offset. @@ -7205,21 +7396,36 @@ declare namespace ts.server.protocol { */ file: string; } + interface JSDocTagInfo { + /** Name of the JSDoc tag */ + name: string; + /** + * Comment text after the JSDoc tag -- the text after the tag name until the next tag or end of comment + * Display parts when UserPreferences.displayPartsForJSDoc is true, flattened to string otherwise. + */ + text?: string | SymbolDisplayPart[]; + } interface TextSpanWithContext extends TextSpan { contextStart?: Location; contextEnd?: Location; } interface FileSpanWithContext extends FileSpan, TextSpanWithContext { } + interface DefinitionInfo extends FileSpanWithContext { + /** + * When true, the file may or may not exist. + */ + unverified?: boolean; + } interface DefinitionInfoAndBoundSpan { - definitions: readonly FileSpanWithContext[]; + definitions: readonly DefinitionInfo[]; textSpan: TextSpan; } /** * Definition response message. Gives text range for definition. */ interface DefinitionResponse extends Response { - body?: FileSpanWithContext[]; + body?: DefinitionInfo[]; } interface DefinitionInfoAndBoundSpanResponse extends Response { body?: DefinitionInfoAndBoundSpan; @@ -7603,18 +7809,21 @@ declare namespace ts.server.protocol { FixedPollingInterval = "FixedPollingInterval", PriorityPollingInterval = "PriorityPollingInterval", DynamicPriorityPolling = "DynamicPriorityPolling", + FixedChunkSizePolling = "FixedChunkSizePolling", UseFsEvents = "UseFsEvents", UseFsEventsOnParentDirectory = "UseFsEventsOnParentDirectory" } enum WatchDirectoryKind { UseFsEvents = "UseFsEvents", FixedPollingInterval = "FixedPollingInterval", - DynamicPriorityPolling = "DynamicPriorityPolling" + DynamicPriorityPolling = "DynamicPriorityPolling", + FixedChunkSizePolling = "FixedChunkSizePolling" } enum PollingWatchKind { FixedInterval = "FixedInterval", PriorityInterval = "PriorityInterval", - DynamicPriority = "DynamicPriority" + DynamicPriority = "DynamicPriority", + FixedChunkSize = "FixedChunkSize" } interface WatchOptions { watchFile?: WatchFileKind | ts.WatchFileKind; @@ -7916,6 +8125,7 @@ declare namespace ts.server.protocol { */ interface QuickInfoRequest extends FileLocationRequest { command: CommandTypes.Quickinfo; + arguments: FileLocationRequestArgs; } /** * Body of QuickInfoResponse. @@ -7943,8 +8153,9 @@ declare namespace ts.server.protocol { displayString: string; /** * Documentation associated with symbol. + * Display parts when UserPreferences.displayPartsForJSDoc is true, flattened to string otherwise. */ - documentation: string; + documentation: string | SymbolDisplayPart[]; /** * JSDoc tags associated with symbol. */ @@ -8065,7 +8276,7 @@ declare namespace ts.server.protocol { command: CommandTypes.Formatonkey; arguments: FormatOnKeyRequestArgs; } - type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#"; + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; /** * Arguments for completions messages. */ @@ -8110,6 +8321,7 @@ declare namespace ts.server.protocol { interface CompletionEntryIdentifier { name: string; source?: string; + data?: unknown; } /** * Completion entry details request; value of command field is @@ -8134,6 +8346,11 @@ declare namespace ts.server.protocol { */ kind: string; } + /** A part of a symbol description that links from a jsdoc @link tag to a declaration */ + interface JSDocLinkDisplayPart extends SymbolDisplayPart { + /** The location of the declaration that the @link tag links to. */ + target: FileSpan; + } /** * An item found in a completion response. */ @@ -8161,6 +8378,10 @@ declare namespace ts.server.protocol { * coupled with `replacementSpan` to replace a dotted access with a bracket access. */ insertText?: string; + /** + * `insertText` should be interpreted as a snippet if true. + */ + isSnippet?: true; /** * An optional span that indicates the text to be replaced by this completion item. * If present, this span should be used instead of the default one. @@ -8176,6 +8397,10 @@ declare namespace ts.server.protocol { * Identifier (not necessarily human-readable) identifying where this completion came from. */ source?: string; + /** + * Human-readable description of the `source`. + */ + sourceDisplay?: SymbolDisplayPart[]; /** * If true, this completion should be highlighted as recommended. There will only be one of these. * This will be set when we know the user should write an expression with a certain type and that type is an enum or constructable class. @@ -8189,9 +8414,20 @@ declare namespace ts.server.protocol { isFromUncheckedFile?: true; /** * If true, this completion was for an auto-import of a module not yet in the program, but listed - * in the project package.json. + * in the project package.json. Used for telemetry reporting. */ isPackageJsonImport?: true; + /** + * If true, this completion was an auto-import-style completion of an import statement (i.e., the + * module specifier was inserted along with the imported identifier). Used for telemetry reporting. + */ + isImportStatementCompletion?: true; + /** + * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, + * that allows TS Server to look up the symbol represented by the completion item, disambiguating + * items with the same name. + */ + data?: unknown; } /** * Additional completion entry details, available on demand @@ -8226,9 +8462,13 @@ declare namespace ts.server.protocol { */ codeActions?: CodeAction[]; /** - * Human-readable description of the `source` from the CompletionEntry. + * @deprecated Use `sourceDisplay` instead. */ source?: SymbolDisplayPart[]; + /** + * Human-readable description of the `source` from the CompletionEntry. + */ + sourceDisplay?: SymbolDisplayPart[]; } /** @deprecated Prefer CompletionInfoResponse, which supports several top-level fields in addition to the array of entries. */ interface CompletionsResponse extends Response { @@ -8247,6 +8487,7 @@ declare namespace ts.server.protocol { * must be used to commit that completion entry. */ readonly optionalReplacementSpan?: TextSpan; + readonly isIncomplete?: boolean; readonly entries: readonly CompletionEntry[]; } interface CompletionDetailsResponse extends Response { @@ -9029,6 +9270,15 @@ declare namespace ts.server.protocol { * This affects lone identifier completions but not completions on the right hand side of `obj.`. */ readonly includeCompletionsForModuleExports?: boolean; + /** + * Enables auto-import-style completions on partially-typed import statements. E.g., allows + * `import write|` to be completed to `import { writeFile } from "fs"`. + */ + readonly includeCompletionsForImportStatements?: boolean; + /** + * Allows completions to be formatted with snippet text, indicated by `CompletionItem["isSnippet"]`. + */ + readonly includeCompletionsWithSnippetText?: boolean; /** * If enabled, the completion list will include completions with invalid identifier names. * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. @@ -9049,6 +9299,7 @@ declare namespace ts.server.protocol { readonly provideRefactorNotApplicableReason?: boolean; readonly allowRenameOfImportPath?: boolean; readonly includePackageJsonAutoImports?: "auto" | "on" | "off"; + readonly displayPartsForJSDoc?: boolean; readonly generateReturnInDocTemplate?: boolean; } interface CompilerOptions { @@ -9157,8 +9408,36 @@ declare namespace ts.server.protocol { ES2018 = "ES2018", ES2019 = "ES2019", ES2020 = "ES2020", + ES2021 = "ES2021", ESNext = "ESNext" } + enum ClassificationType { + comment = 1, + identifier = 2, + keyword = 3, + numericLiteral = 4, + operator = 5, + stringLiteral = 6, + regularExpressionLiteral = 7, + whiteSpace = 8, + text = 9, + punctuation = 10, + className = 11, + enumName = 12, + interfaceName = 13, + moduleName = 14, + typeParameterName = 15, + typeAliasName = 16, + parameterName = 17, + docCommentTagName = 18, + jsxOpenTagName = 19, + jsxCloseTagName = 20, + jsxSelfClosingTagName = 21, + jsxAttribute = 22, + jsxText = 23, + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25 + } } declare namespace ts.server { interface ScriptInfoVersion { @@ -9427,10 +9706,8 @@ declare namespace ts.server { markAsDirty(): void; getScriptFileNames(): string[]; getLanguageService(): never; - markAutoImportProviderAsDirty(): never; getModuleResolutionHostForAutoImportProvider(): never; getProjectReferences(): readonly ProjectReference[] | undefined; - useSourceOfProjectReferenceRedirect(): boolean; getTypeAcquisition(): TypeAcquisition; } /** @@ -9439,7 +9716,6 @@ declare namespace ts.server { * Otherwise it will create an InferredProject. */ class ConfiguredProject extends Project { - private directoriesWatchedForWildcards; readonly canonicalConfigFilePath: NormalizedPath; /** Ref count to the project when opened from external project */ private externalProjectRefCount; @@ -9686,14 +9962,6 @@ declare namespace ts.server { * Project size for configured or external projects */ private readonly projectToSizeMap; - /** - * This is a map of config file paths existence that doesnt need query to disk - * - The entry can be present because there is inferred project that needs to watch addition of config file to directory - * In this case the exists could be true/false based on config file is present or not - * - Or it is present if we have configured project open with config file at that location - * In this case the exists property is always true - */ - private readonly configFileExistenceInfoCache; private readonly hostConfiguration; private safelist; private readonly legacySafelist; @@ -9749,12 +10017,6 @@ declare namespace ts.server { private delayUpdateSourceInfoProjects; private delayUpdateProjectsOfScriptInfoPath; private handleDeletedFile; - /** - * This is the callback function for the config file add/remove/change at any location - * that matters to open script info but doesnt have configured project open - * for the config file - */ - private onConfigFileChangeForOpenScriptInfo; private removeProject; private assignOrphanScriptInfosToInferredProject; /** @@ -9764,22 +10026,10 @@ declare namespace ts.server { private closeOpenFile; private deleteScriptInfo; private configFileExists; - private setConfigFileExistenceByNewConfiguredProject; /** * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project */ private configFileExistenceImpactsRootOfInferredProject; - private setConfigFileExistenceInfoByClosedConfiguredProject; - private logConfigFileWatchUpdate; - /** - * Create the watcher for the configFileExistenceInfo - */ - private createConfigFileWatcherOfConfigFileExistence; - /** - * Close the config file watcher in the cached ConfigFileExistenceInfo - * if there arent any open files that are root of inferred project - */ - private closeConfigFileWatcherOfConfigFileExistenceInfo; /** * This is called on file close, so that we stop watching the config file for this script info */ @@ -9845,12 +10095,11 @@ declare namespace ts.server { * This does not reload contents of open files from disk. But we could do that if needed */ reloadProjects(): void; - private delayReloadConfiguredProjectForFiles; /** * This function goes through all the openFiles and tries to file the config file for them. * If the config file is found and it refers to existing project, it reloads it either immediately * or schedules it for reload depending on delayReload option - * If the there is no existing project it just opens the configured project for the config file + * If 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; @@ -9996,6 +10245,9 @@ declare namespace ts.server { private mapDefinitionInfoLocations; private getDefinitionAndBoundSpan; private getEmitOutput; + private mapJSDocTagInfo; + private mapDisplayParts; + private mapSignatureHelpItems; private mapDefinitionInfo; private static mapToOriginalLocation; private toFileSpan; @@ -10134,7 +10386,7 @@ declare namespace ts { /** @deprecated Use `factory.createRegularExpressionLiteral` or the factory supplied by your transformation context instead. */ const createRegularExpressionLiteral: (text: string) => RegularExpressionLiteral; /** @deprecated Use `factory.createLoopVariable` or the factory supplied by your transformation context instead. */ - const createLoopVariable: () => Identifier; + const createLoopVariable: (reservedInNestedScopes?: boolean | undefined) => Identifier; /** @deprecated Use `factory.createUniqueName` or the factory supplied by your transformation context instead. */ const createUniqueName: (text: string, flags?: GeneratedIdentifierFlags | undefined) => Identifier; /** @deprecated Use `factory.createPrivateIdentifier` or the factory supplied by your transformation context instead. */ @@ -10306,13 +10558,13 @@ declare namespace ts { /** @deprecated Use `factory.updateObjectLiteralExpression` or the factory supplied by your transformation context instead. */ const updateObjectLiteral: (node: ObjectLiteralExpression, properties: readonly ObjectLiteralElementLike[]) => ObjectLiteralExpression; /** @deprecated Use `factory.createPropertyAccessExpression` or the factory supplied by your transformation context instead. */ - const createPropertyAccess: (expression: Expression, name: string | Identifier | PrivateIdentifier) => PropertyAccessExpression; + const createPropertyAccess: (expression: Expression, name: string | MemberName) => PropertyAccessExpression; /** @deprecated Use `factory.updatePropertyAccessExpression` or the factory supplied by your transformation context instead. */ - const updatePropertyAccess: (node: PropertyAccessExpression, expression: Expression, name: Identifier | PrivateIdentifier) => PropertyAccessExpression; + const updatePropertyAccess: (node: PropertyAccessExpression, expression: Expression, name: MemberName) => PropertyAccessExpression; /** @deprecated Use `factory.createPropertyAccessChain` or the factory supplied by your transformation context instead. */ - const createPropertyAccessChain: (expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | Identifier | PrivateIdentifier) => PropertyAccessChain; + const createPropertyAccessChain: (expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | MemberName) => PropertyAccessChain; /** @deprecated Use `factory.updatePropertyAccessChain` or the factory supplied by your transformation context instead. */ - const updatePropertyAccessChain: (node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: Identifier | PrivateIdentifier) => PropertyAccessChain; + const updatePropertyAccessChain: (node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: MemberName) => PropertyAccessChain; /** @deprecated Use `factory.createElementAccessExpression` or the factory supplied by your transformation context instead. */ const createElementAccess: (expression: Expression, index: number | Expression) => ElementAccessExpression; /** @deprecated Use `factory.updateElementAccessExpression` or the factory supplied by your transformation context instead. */ @@ -10582,51 +10834,51 @@ declare namespace ts { /** @deprecated Use `factory.createJSDocTypeExpression` or the factory supplied by your transformation context instead. */ const createJSDocTypeExpression: (type: TypeNode) => JSDocTypeExpression; /** @deprecated Use `factory.createJSDocTypeTag` or the factory supplied by your transformation context instead. */ - const createJSDocTypeTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | undefined) => JSDocTypeTag; + const createJSDocTypeTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray | undefined) => JSDocTypeTag; /** @deprecated Use `factory.createJSDocReturnTag` or the factory supplied by your transformation context instead. */ - const createJSDocReturnTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | undefined, comment?: string | undefined) => JSDocReturnTag; + const createJSDocReturnTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | undefined, comment?: string | NodeArray | undefined) => JSDocReturnTag; /** @deprecated Use `factory.createJSDocThisTag` or the factory supplied by your transformation context instead. */ - const createJSDocThisTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | undefined) => JSDocThisTag; + const createJSDocThisTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray | undefined) => JSDocThisTag; /** @deprecated Use `factory.createJSDocComment` or the factory supplied by your transformation context instead. */ - const createJSDocComment: (comment?: string | undefined, tags?: readonly JSDocTag[] | undefined) => JSDoc; + const createJSDocComment: (comment?: string | NodeArray | undefined, tags?: readonly JSDocTag[] | undefined) => JSDoc; /** @deprecated Use `factory.createJSDocParameterTag` or the factory supplied by your transformation context instead. */ - const createJSDocParameterTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | undefined) => JSDocParameterTag; + const createJSDocParameterTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | NodeArray | undefined) => JSDocParameterTag; /** @deprecated Use `factory.createJSDocClassTag` or the factory supplied by your transformation context instead. */ - const createJSDocClassTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocClassTag; + const createJSDocClassTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocClassTag; /** @deprecated Use `factory.createJSDocAugmentsTag` or the factory supplied by your transformation context instead. */ const createJSDocAugmentsTag: (tagName: Identifier | undefined, className: ExpressionWithTypeArguments & { readonly expression: Identifier | PropertyAccessEntityNameExpression; - }, comment?: string | undefined) => JSDocAugmentsTag; + }, comment?: string | NodeArray | undefined) => JSDocAugmentsTag; /** @deprecated Use `factory.createJSDocEnumTag` or the factory supplied by your transformation context instead. */ - const createJSDocEnumTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | undefined) => JSDocEnumTag; + const createJSDocEnumTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray | undefined) => JSDocEnumTag; /** @deprecated Use `factory.createJSDocTemplateTag` or the factory supplied by your transformation context instead. */ - const createJSDocTemplateTag: (tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | undefined) => JSDocTemplateTag; + const createJSDocTemplateTag: (tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray | undefined) => JSDocTemplateTag; /** @deprecated Use `factory.createJSDocTypedefTag` or the factory supplied by your transformation context instead. */ - const createJSDocTypedefTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeLiteral | JSDocTypeExpression | undefined, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | undefined) => JSDocTypedefTag; + const createJSDocTypedefTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeLiteral | JSDocTypeExpression | undefined, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | NodeArray | undefined) => JSDocTypedefTag; /** @deprecated Use `factory.createJSDocCallbackTag` or the factory supplied by your transformation context instead. */ - const createJSDocCallbackTag: (tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | undefined) => JSDocCallbackTag; + const createJSDocCallbackTag: (tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | NodeArray | undefined) => JSDocCallbackTag; /** @deprecated Use `factory.createJSDocSignature` or the factory supplied by your transformation context instead. */ const createJSDocSignature: (typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag | undefined) => JSDocSignature; /** @deprecated Use `factory.createJSDocPropertyTag` or the factory supplied by your transformation context instead. */ - const createJSDocPropertyTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | undefined) => JSDocPropertyTag; + const createJSDocPropertyTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | NodeArray | undefined) => JSDocPropertyTag; /** @deprecated Use `factory.createJSDocTypeLiteral` or the factory supplied by your transformation context instead. */ const createJSDocTypeLiteral: (jsDocPropertyTags?: readonly JSDocPropertyLikeTag[] | undefined, isArrayType?: boolean | undefined) => JSDocTypeLiteral; /** @deprecated Use `factory.createJSDocImplementsTag` or the factory supplied by your transformation context instead. */ const createJSDocImplementsTag: (tagName: Identifier | undefined, className: ExpressionWithTypeArguments & { readonly expression: Identifier | PropertyAccessEntityNameExpression; - }, comment?: string | undefined) => JSDocImplementsTag; + }, comment?: string | NodeArray | undefined) => JSDocImplementsTag; /** @deprecated Use `factory.createJSDocAuthorTag` or the factory supplied by your transformation context instead. */ - const createJSDocAuthorTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocAuthorTag; + const createJSDocAuthorTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocAuthorTag; /** @deprecated Use `factory.createJSDocPublicTag` or the factory supplied by your transformation context instead. */ - const createJSDocPublicTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocPublicTag; + const createJSDocPublicTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocPublicTag; /** @deprecated Use `factory.createJSDocPrivateTag` or the factory supplied by your transformation context instead. */ - const createJSDocPrivateTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocPrivateTag; + const createJSDocPrivateTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocPrivateTag; /** @deprecated Use `factory.createJSDocProtectedTag` or the factory supplied by your transformation context instead. */ - const createJSDocProtectedTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocProtectedTag; + const createJSDocProtectedTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocProtectedTag; /** @deprecated Use `factory.createJSDocReadonlyTag` or the factory supplied by your transformation context instead. */ - const createJSDocReadonlyTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocReadonlyTag; + const createJSDocReadonlyTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocReadonlyTag; /** @deprecated Use `factory.createJSDocUnknownTag` or the factory supplied by your transformation context instead. */ - const createJSDocTag: (tagName: Identifier, comment?: string | undefined) => JSDocUnknownTag; + const createJSDocTag: (tagName: Identifier, comment?: string | NodeArray | undefined) => JSDocUnknownTag; /** @deprecated Use `factory.createJsxElement` or the factory supplied by your transformation context instead. */ const createJsxElement: (openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement) => JsxElement; /** @deprecated Use `factory.updateJsxElement` or the factory supplied by your transformation context instead. */ @@ -10882,6 +11134,10 @@ declare namespace ts { */ interface Map extends ESMap { } + /** + * @deprecated Use `isMemberName` instead. + */ + const isIdentifierOrPrivateIdentifier: (node: Node) => node is MemberName; } export = ts; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index bba168d37e720..b86a3a29970a4 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 = "4.2"; + const versionMajorMinor = "4.3"; /** The version of the TypeScript compiler release */ const version: string; /** @@ -260,192 +260,196 @@ declare namespace ts { FromKeyword = 153, GlobalKeyword = 154, BigIntKeyword = 155, - OfKeyword = 156, - QualifiedName = 157, - ComputedPropertyName = 158, - TypeParameter = 159, - Parameter = 160, - Decorator = 161, - PropertySignature = 162, - PropertyDeclaration = 163, - MethodSignature = 164, - MethodDeclaration = 165, - Constructor = 166, - GetAccessor = 167, - SetAccessor = 168, - CallSignature = 169, - ConstructSignature = 170, - IndexSignature = 171, - TypePredicate = 172, - TypeReference = 173, - FunctionType = 174, - ConstructorType = 175, - TypeQuery = 176, - TypeLiteral = 177, - ArrayType = 178, - TupleType = 179, - OptionalType = 180, - RestType = 181, - UnionType = 182, - IntersectionType = 183, - ConditionalType = 184, - InferType = 185, - ParenthesizedType = 186, - ThisType = 187, - TypeOperator = 188, - IndexedAccessType = 189, - MappedType = 190, - LiteralType = 191, - NamedTupleMember = 192, - TemplateLiteralType = 193, - TemplateLiteralTypeSpan = 194, - ImportType = 195, - ObjectBindingPattern = 196, - ArrayBindingPattern = 197, - BindingElement = 198, - ArrayLiteralExpression = 199, - ObjectLiteralExpression = 200, - PropertyAccessExpression = 201, - ElementAccessExpression = 202, - CallExpression = 203, - NewExpression = 204, - TaggedTemplateExpression = 205, - TypeAssertionExpression = 206, - ParenthesizedExpression = 207, - FunctionExpression = 208, - ArrowFunction = 209, - DeleteExpression = 210, - TypeOfExpression = 211, - VoidExpression = 212, - AwaitExpression = 213, - PrefixUnaryExpression = 214, - PostfixUnaryExpression = 215, - BinaryExpression = 216, - ConditionalExpression = 217, - TemplateExpression = 218, - YieldExpression = 219, - SpreadElement = 220, - ClassExpression = 221, - OmittedExpression = 222, - ExpressionWithTypeArguments = 223, - AsExpression = 224, - NonNullExpression = 225, - MetaProperty = 226, - SyntheticExpression = 227, - TemplateSpan = 228, - SemicolonClassElement = 229, - Block = 230, - EmptyStatement = 231, - VariableStatement = 232, - ExpressionStatement = 233, - IfStatement = 234, - DoStatement = 235, - WhileStatement = 236, - ForStatement = 237, - ForInStatement = 238, - ForOfStatement = 239, - ContinueStatement = 240, - BreakStatement = 241, - ReturnStatement = 242, - WithStatement = 243, - SwitchStatement = 244, - LabeledStatement = 245, - ThrowStatement = 246, - TryStatement = 247, - DebuggerStatement = 248, - VariableDeclaration = 249, - VariableDeclarationList = 250, - FunctionDeclaration = 251, - ClassDeclaration = 252, - InterfaceDeclaration = 253, - TypeAliasDeclaration = 254, - EnumDeclaration = 255, - ModuleDeclaration = 256, - ModuleBlock = 257, - CaseBlock = 258, - NamespaceExportDeclaration = 259, - ImportEqualsDeclaration = 260, - ImportDeclaration = 261, - ImportClause = 262, - NamespaceImport = 263, - NamedImports = 264, - ImportSpecifier = 265, - ExportAssignment = 266, - ExportDeclaration = 267, - NamedExports = 268, - NamespaceExport = 269, - ExportSpecifier = 270, - MissingDeclaration = 271, - ExternalModuleReference = 272, - JsxElement = 273, - JsxSelfClosingElement = 274, - JsxOpeningElement = 275, - JsxClosingElement = 276, - JsxFragment = 277, - JsxOpeningFragment = 278, - JsxClosingFragment = 279, - JsxAttribute = 280, - JsxAttributes = 281, - JsxSpreadAttribute = 282, - JsxExpression = 283, - CaseClause = 284, - DefaultClause = 285, - HeritageClause = 286, - CatchClause = 287, - PropertyAssignment = 288, - ShorthandPropertyAssignment = 289, - SpreadAssignment = 290, - EnumMember = 291, - UnparsedPrologue = 292, - UnparsedPrepend = 293, - UnparsedText = 294, - UnparsedInternalText = 295, - UnparsedSyntheticReference = 296, - SourceFile = 297, - Bundle = 298, - UnparsedSource = 299, - InputFiles = 300, - JSDocTypeExpression = 301, - JSDocNameReference = 302, - JSDocAllType = 303, - JSDocUnknownType = 304, - JSDocNullableType = 305, - JSDocNonNullableType = 306, - JSDocOptionalType = 307, - JSDocFunctionType = 308, - JSDocVariadicType = 309, - JSDocNamepathType = 310, - JSDocComment = 311, - JSDocTypeLiteral = 312, - JSDocSignature = 313, - JSDocTag = 314, - JSDocAugmentsTag = 315, - JSDocImplementsTag = 316, - JSDocAuthorTag = 317, - JSDocDeprecatedTag = 318, - JSDocClassTag = 319, - JSDocPublicTag = 320, - JSDocPrivateTag = 321, - JSDocProtectedTag = 322, - JSDocReadonlyTag = 323, - JSDocCallbackTag = 324, - JSDocEnumTag = 325, - JSDocParameterTag = 326, - JSDocReturnTag = 327, - JSDocThisTag = 328, - JSDocTypeTag = 329, - JSDocTemplateTag = 330, - JSDocTypedefTag = 331, - JSDocSeeTag = 332, - JSDocPropertyTag = 333, - SyntaxList = 334, - NotEmittedStatement = 335, - PartiallyEmittedExpression = 336, - CommaListExpression = 337, - MergeDeclarationMarker = 338, - EndOfDeclarationMarker = 339, - SyntheticReferenceExpression = 340, - Count = 341, + OverrideKeyword = 156, + OfKeyword = 157, + QualifiedName = 158, + ComputedPropertyName = 159, + TypeParameter = 160, + Parameter = 161, + Decorator = 162, + PropertySignature = 163, + PropertyDeclaration = 164, + MethodSignature = 165, + MethodDeclaration = 166, + Constructor = 167, + GetAccessor = 168, + SetAccessor = 169, + CallSignature = 170, + ConstructSignature = 171, + IndexSignature = 172, + TypePredicate = 173, + TypeReference = 174, + FunctionType = 175, + ConstructorType = 176, + TypeQuery = 177, + TypeLiteral = 178, + ArrayType = 179, + TupleType = 180, + OptionalType = 181, + RestType = 182, + UnionType = 183, + IntersectionType = 184, + ConditionalType = 185, + InferType = 186, + ParenthesizedType = 187, + ThisType = 188, + TypeOperator = 189, + IndexedAccessType = 190, + MappedType = 191, + LiteralType = 192, + NamedTupleMember = 193, + TemplateLiteralType = 194, + TemplateLiteralTypeSpan = 195, + ImportType = 196, + ObjectBindingPattern = 197, + ArrayBindingPattern = 198, + BindingElement = 199, + ArrayLiteralExpression = 200, + ObjectLiteralExpression = 201, + PropertyAccessExpression = 202, + ElementAccessExpression = 203, + CallExpression = 204, + NewExpression = 205, + TaggedTemplateExpression = 206, + TypeAssertionExpression = 207, + ParenthesizedExpression = 208, + FunctionExpression = 209, + ArrowFunction = 210, + DeleteExpression = 211, + TypeOfExpression = 212, + VoidExpression = 213, + AwaitExpression = 214, + PrefixUnaryExpression = 215, + PostfixUnaryExpression = 216, + BinaryExpression = 217, + ConditionalExpression = 218, + TemplateExpression = 219, + YieldExpression = 220, + SpreadElement = 221, + ClassExpression = 222, + OmittedExpression = 223, + ExpressionWithTypeArguments = 224, + AsExpression = 225, + NonNullExpression = 226, + MetaProperty = 227, + SyntheticExpression = 228, + TemplateSpan = 229, + SemicolonClassElement = 230, + Block = 231, + EmptyStatement = 232, + VariableStatement = 233, + ExpressionStatement = 234, + IfStatement = 235, + DoStatement = 236, + WhileStatement = 237, + ForStatement = 238, + ForInStatement = 239, + ForOfStatement = 240, + ContinueStatement = 241, + BreakStatement = 242, + ReturnStatement = 243, + WithStatement = 244, + SwitchStatement = 245, + LabeledStatement = 246, + ThrowStatement = 247, + TryStatement = 248, + DebuggerStatement = 249, + VariableDeclaration = 250, + VariableDeclarationList = 251, + FunctionDeclaration = 252, + ClassDeclaration = 253, + InterfaceDeclaration = 254, + TypeAliasDeclaration = 255, + EnumDeclaration = 256, + ModuleDeclaration = 257, + ModuleBlock = 258, + CaseBlock = 259, + NamespaceExportDeclaration = 260, + ImportEqualsDeclaration = 261, + ImportDeclaration = 262, + ImportClause = 263, + NamespaceImport = 264, + NamedImports = 265, + ImportSpecifier = 266, + ExportAssignment = 267, + ExportDeclaration = 268, + NamedExports = 269, + NamespaceExport = 270, + ExportSpecifier = 271, + MissingDeclaration = 272, + ExternalModuleReference = 273, + JsxElement = 274, + JsxSelfClosingElement = 275, + JsxOpeningElement = 276, + JsxClosingElement = 277, + JsxFragment = 278, + JsxOpeningFragment = 279, + JsxClosingFragment = 280, + JsxAttribute = 281, + JsxAttributes = 282, + JsxSpreadAttribute = 283, + JsxExpression = 284, + CaseClause = 285, + DefaultClause = 286, + HeritageClause = 287, + CatchClause = 288, + PropertyAssignment = 289, + ShorthandPropertyAssignment = 290, + SpreadAssignment = 291, + EnumMember = 292, + UnparsedPrologue = 293, + UnparsedPrepend = 294, + UnparsedText = 295, + UnparsedInternalText = 296, + UnparsedSyntheticReference = 297, + SourceFile = 298, + Bundle = 299, + UnparsedSource = 300, + InputFiles = 301, + JSDocTypeExpression = 302, + JSDocNameReference = 303, + JSDocAllType = 304, + JSDocUnknownType = 305, + JSDocNullableType = 306, + JSDocNonNullableType = 307, + JSDocOptionalType = 308, + JSDocFunctionType = 309, + JSDocVariadicType = 310, + JSDocNamepathType = 311, + JSDocComment = 312, + JSDocText = 313, + JSDocTypeLiteral = 314, + JSDocSignature = 315, + JSDocLink = 316, + JSDocTag = 317, + JSDocAugmentsTag = 318, + JSDocImplementsTag = 319, + JSDocAuthorTag = 320, + JSDocDeprecatedTag = 321, + JSDocClassTag = 322, + JSDocPublicTag = 323, + JSDocPrivateTag = 324, + JSDocProtectedTag = 325, + JSDocReadonlyTag = 326, + JSDocOverrideTag = 327, + JSDocCallbackTag = 328, + JSDocEnumTag = 329, + JSDocParameterTag = 330, + JSDocReturnTag = 331, + JSDocThisTag = 332, + JSDocTypeTag = 333, + JSDocTemplateTag = 334, + JSDocTypedefTag = 335, + JSDocSeeTag = 336, + JSDocPropertyTag = 337, + SyntaxList = 338, + NotEmittedStatement = 339, + PartiallyEmittedExpression = 340, + CommaListExpression = 341, + MergeDeclarationMarker = 342, + EndOfDeclarationMarker = 343, + SyntheticReferenceExpression = 344, + Count = 345, FirstAssignment = 62, LastAssignment = 77, FirstCompoundAssignment = 63, @@ -453,15 +457,15 @@ declare namespace ts { FirstReservedWord = 80, LastReservedWord = 115, FirstKeyword = 80, - LastKeyword = 156, + LastKeyword = 157, FirstFutureReservedWord = 116, LastFutureReservedWord = 124, - FirstTypeNode = 172, - LastTypeNode = 195, + FirstTypeNode = 173, + LastTypeNode = 196, FirstPunctuation = 18, LastPunctuation = 77, FirstToken = 0, - LastToken = 156, + LastToken = 157, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, @@ -470,20 +474,20 @@ declare namespace ts { LastTemplateToken = 17, FirstBinaryOperator = 29, LastBinaryOperator = 77, - FirstStatement = 232, - LastStatement = 248, - FirstNode = 157, - FirstJSDocNode = 301, - LastJSDocNode = 333, - FirstJSDocTagNode = 314, - LastJSDocTagNode = 333, + FirstStatement = 233, + LastStatement = 249, + FirstNode = 158, + FirstJSDocNode = 302, + LastJSDocNode = 337, + FirstJSDocTagNode = 317, + LastJSDocTagNode = 337, } export type TriviaSyntaxKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; export type LiteralSyntaxKind = SyntaxKind.NumericLiteral | SyntaxKind.BigIntLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral; export type PseudoLiteralSyntaxKind = SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle | SyntaxKind.TemplateTail; export type PunctuationSyntaxKind = SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.CloseParenToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.DotToken | SyntaxKind.DotDotDotToken | SyntaxKind.SemicolonToken | SyntaxKind.CommaToken | SyntaxKind.QuestionDotToken | SyntaxKind.LessThanToken | SyntaxKind.LessThanSlashToken | SyntaxKind.GreaterThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.EqualsEqualsToken | SyntaxKind.ExclamationEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.EqualsGreaterThanToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.AsteriskToken | SyntaxKind.AsteriskAsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken | SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken | SyntaxKind.ExclamationToken | SyntaxKind.TildeToken | SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken | SyntaxKind.QuestionQuestionToken | SyntaxKind.QuestionToken | SyntaxKind.ColonToken | SyntaxKind.AtToken | SyntaxKind.BacktickToken | SyntaxKind.EqualsToken | SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken; - export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | 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.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | 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; - export type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.StaticKeyword; + export type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | 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.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | 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; + export type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword; export type KeywordTypeSyntaxKind = SyntaxKind.AnyKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VoidKeyword; export type TokenSyntaxKind = SyntaxKind.Unknown | SyntaxKind.EndOfFileToken | TriviaSyntaxKind | LiteralSyntaxKind | PseudoLiteralSyntaxKind | PunctuationSyntaxKind | SyntaxKind.Identifier | KeywordSyntaxKind; export type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; @@ -533,13 +537,14 @@ declare namespace ts { Const = 2048, HasComputedJSDocModifiers = 4096, Deprecated = 8192, + Override = 16384, HasComputedFlags = 536870912, AccessibilityModifier = 28, - ParameterPropertyModifier = 92, + ParameterPropertyModifier = 16476, NonPublicAccessibilityModifier = 24, - TypeScriptModifier = 2270, + TypeScriptModifier = 18654, ExportDefault = 513, - All = 11263 + All = 27647 } export enum JsxFlags { None = 0, @@ -558,7 +563,7 @@ declare namespace ts { } export interface JSDocContainer { } - export type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | NamespaceExportDeclaration | ExportAssignment | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | NamedTupleMember | EndOfFileToken; + export type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | EmptyStatement | DebuggerStatement | Block | VariableStatement | ExpressionStatement | IfStatement | DoStatement | WhileStatement | ForStatement | ForInStatement | ForOfStatement | BreakStatement | ContinueStatement | ReturnStatement | WithStatement | SwitchStatement | LabeledStatement | ThrowStatement | TryStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | VariableDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | NamespaceExportDeclaration | ExportAssignment | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | NamedTupleMember | EndOfFileToken; export type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; export type HasTypeArguments = CallExpression | NewExpression | TaggedTemplateExpression | JsxOpeningElement | JsxSelfClosingElement; export type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; @@ -603,10 +608,11 @@ declare namespace ts { export type ProtectedKeyword = ModifierToken; export type PublicKeyword = ModifierToken; export type ReadonlyKeyword = ModifierToken; + export type OverrideKeyword = ModifierToken; export type StaticKeyword = ModifierToken; /** @deprecated Use `ReadonlyKeyword` instead. */ export type ReadonlyToken = ReadonlyKeyword; - export type Modifier = AbstractKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | ReadonlyKeyword | StaticKeyword; + export type Modifier = AbstractKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | OverrideKeyword | ReadonlyKeyword | StaticKeyword; export type AccessibilityModifier = PublicKeyword | PrivateKeyword | ProtectedKeyword; export type ParameterPropertyModifier = AccessibilityModifier | ReadonlyKeyword; export type ClassMemberModifier = AccessibilityModifier | ReadonlyKeyword | StaticKeyword; @@ -638,6 +644,7 @@ declare namespace ts { } export type EntityName = Identifier | QualifiedName; export type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | PrivateIdentifier; + export type MemberName = Identifier | PrivateIdentifier; export type DeclarationName = Identifier | PrivateIdentifier | StringLiteralLike | NumericLiteral | ComputedPropertyName | ElementAccessExpression | BindingPattern | EntityNameExpression; export interface Declaration extends Node { _declarationBrand: any; @@ -686,7 +693,7 @@ declare namespace ts { readonly kind: SyntaxKind.ConstructSignature; } export type BindingName = Identifier | BindingPattern; - export interface VariableDeclaration extends NamedDeclaration { + export interface VariableDeclaration extends NamedDeclaration, JSDocContainer { readonly kind: SyntaxKind.VariableDeclaration; readonly parent: VariableDeclarationList | CatchClause; readonly name: BindingName; @@ -820,15 +827,15 @@ declare namespace ts { readonly kind: SyntaxKind.SemicolonClassElement; readonly parent: ClassLikeDeclaration; } - export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.GetAccessor; - readonly parent: ClassLikeDeclaration | ObjectLiteralExpression; + readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; readonly name: PropertyName; readonly body?: FunctionBody; } - export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { + export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.SetAccessor; - readonly parent: ClassLikeDeclaration | ObjectLiteralExpression; + readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; readonly name: PropertyName; readonly body?: FunctionBody; } @@ -1216,11 +1223,11 @@ declare namespace ts { readonly kind: SyntaxKind.PropertyAccessExpression; readonly expression: LeftHandSideExpression; readonly questionDotToken?: QuestionDotToken; - readonly name: Identifier | PrivateIdentifier; + readonly name: MemberName; } export interface PropertyAccessChain extends PropertyAccessExpression { _optionalChainBrand: any; - readonly name: Identifier | PrivateIdentifier; + readonly name: MemberName; } export interface SuperPropertyAccessExpression extends PropertyAccessExpression { readonly expression: SuperExpression; @@ -1373,7 +1380,7 @@ declare namespace ts { readonly containsOnlyTriviaWhiteSpaces: boolean; } export type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; - export interface Statement extends Node { + export interface Statement extends Node, JSDocContainer { _statementBrand: any; } export interface NotEmittedStatement extends Statement { @@ -1401,11 +1408,11 @@ declare namespace ts { readonly kind: SyntaxKind.Block; readonly statements: NodeArray; } - export interface VariableStatement extends Statement, JSDocContainer { + export interface VariableStatement extends Statement { readonly kind: SyntaxKind.VariableStatement; readonly declarationList: VariableDeclarationList; } - export interface ExpressionStatement extends Statement, JSDocContainer { + export interface ExpressionStatement extends Statement { readonly kind: SyntaxKind.ExpressionStatement; readonly expression: Expression; } @@ -1486,7 +1493,7 @@ declare namespace ts { readonly statements: NodeArray; } export type CaseOrDefaultClause = CaseClause | DefaultClause; - export interface LabeledStatement extends Statement, JSDocContainer { + export interface LabeledStatement extends Statement { readonly kind: SyntaxKind.LabeledStatement; readonly label: Identifier; readonly statement: Statement; @@ -1606,7 +1613,7 @@ declare namespace ts { readonly parent: ImportEqualsDeclaration; readonly expression: Expression; } - export interface ImportDeclaration extends Statement, JSDocContainer { + export interface ImportDeclaration extends Statement { readonly kind: SyntaxKind.ImportDeclaration; readonly parent: SourceFile | ModuleBlock; readonly importClause?: ImportClause; @@ -1742,12 +1749,21 @@ declare namespace ts { readonly kind: SyntaxKind.JSDocComment; readonly parent: HasJSDoc; readonly tags?: NodeArray; - readonly comment?: string; + readonly comment?: string | NodeArray; } export interface JSDocTag extends Node { readonly parent: JSDoc | JSDocTypeLiteral; readonly tagName: Identifier; - readonly comment?: string; + readonly comment?: string | NodeArray; + } + export interface JSDocLink extends Node { + readonly kind: SyntaxKind.JSDocLink; + readonly name?: EntityName; + text: string; + } + export interface JSDocText extends Node { + readonly kind: SyntaxKind.JSDocText; + text: string; } export interface JSDocUnknownTag extends JSDocTag { readonly kind: SyntaxKind.JSDocTag; @@ -1789,6 +1805,9 @@ declare namespace ts { export interface JSDocReadonlyTag extends JSDocTag { readonly kind: SyntaxKind.JSDocReadonlyTag; } + export interface JSDocOverrideTag extends JSDocTag { + readonly kind: SyntaxKind.JSDocOverrideTag; + } export interface JSDocEnumTag extends JSDocTag, Declaration { readonly kind: SyntaxKind.JSDocEnumTag; readonly parent: JSDoc; @@ -2080,7 +2099,6 @@ declare namespace ts { * Gets a type checker that can be used to semantically analyze source files in the program. */ getTypeChecker(): TypeChecker; - getTypeCatalog(): readonly Type[]; getNodeCount(): number; getIdentifierCount(): number; getSymbolCount(): number; @@ -2186,7 +2204,7 @@ declare namespace ts { * The function returns the value (local variable) symbol of an identifier in the short-hand property assignment. * This is necessary as an identifier in short-hand property assignment can contains two meaning: property name and property value. */ - getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; + getShorthandAssignmentValueSymbol(location: Node | undefined): Symbol | undefined; getExportSpecifierLocalTargetSymbol(location: ExportSpecifier | Identifier): Symbol | undefined; /** * If a symbol is a local symbol with an associated exported symbol, returns the exported symbol. @@ -2261,6 +2279,8 @@ declare namespace ts { NoTypeReduction = 536870912, NoUndefinedOptionalParameterType = 1073741824, AllowThisInObjectLiteral = 32768, + AllowQualifiedNameInPlaceOfIdentifier = 65536, + /** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */ AllowQualifedNameInPlaceOfIdentifier = 65536, AllowAnonymousIdentifier = 131072, AllowEmptyUnionOrIntersection = 262144, @@ -2271,8 +2291,7 @@ declare namespace ts { IgnoreErrors = 70221824, InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, - InInitialEntityName = 16777216, - InReverseMappedType = 33554432 + InInitialEntityName = 16777216 } export enum TypeFormatFlags { None = 0, @@ -2405,8 +2424,8 @@ declare namespace ts { export interface Symbol { flags: SymbolFlags; escapedName: __String; - declarations: Declaration[]; - valueDeclaration: Declaration; + declarations?: Declaration[]; + valueDeclaration?: Declaration; members?: SymbolTable; exports?: SymbolTable; globalExports?: SymbolTable; @@ -2540,15 +2559,15 @@ declare namespace ts { ObjectLiteral = 128, EvolvingArray = 256, ObjectLiteralPatternWithComputedProperties = 512, - ContainsSpread = 1024, - ReverseMapped = 2048, - JsxAttributes = 4096, - MarkerType = 8192, - JSLiteral = 16384, - FreshLiteral = 32768, - ArrayLiteral = 65536, - ObjectRestType = 131072, + ReverseMapped = 1024, + JsxAttributes = 2048, + MarkerType = 4096, + JSLiteral = 8192, + FreshLiteral = 16384, + ArrayLiteral = 32768, ClassOrInterface = 3, + ContainsSpread = 4194304, + ObjectRestType = 8388608, } export interface ObjectType extends Type { objectFlags: ObjectFlags; @@ -2662,6 +2681,7 @@ declare namespace ts { type: Type; } export interface SubstitutionType extends InstantiableType { + objectFlags: ObjectFlags; baseType: Type; substitute: Type; } @@ -2686,16 +2706,17 @@ declare namespace ts { export enum InferencePriority { NakedTypeVariable = 1, SpeculativeTuple = 2, - HomomorphicMappedType = 4, - PartialHomomorphicMappedType = 8, - MappedTypeConstraint = 16, - ContravariantConditional = 32, - ReturnType = 64, - LiteralKeyof = 128, - NoConstraints = 256, - AlwaysStrict = 512, - MaxValue = 1024, - PriorityImpliesCombination = 208, + SubstituteSource = 4, + HomomorphicMappedType = 8, + PartialHomomorphicMappedType = 16, + MappedTypeConstraint = 32, + ContravariantConditional = 64, + ReturnType = 128, + LiteralKeyof = 256, + NoConstraints = 512, + AlwaysStrict = 1024, + MaxValue = 2048, + PriorityImpliesCombination = 416, Circularity = -1 } /** @deprecated Use FileExtensionInfo instead. */ @@ -2772,18 +2793,21 @@ declare namespace ts { FixedPollingInterval = 0, PriorityPollingInterval = 1, DynamicPriorityPolling = 2, - UseFsEvents = 3, - UseFsEventsOnParentDirectory = 4 + FixedChunkSizePolling = 3, + UseFsEvents = 4, + UseFsEventsOnParentDirectory = 5 } export enum WatchDirectoryKind { UseFsEvents = 0, FixedPollingInterval = 1, - DynamicPriorityPolling = 2 + DynamicPriorityPolling = 2, + FixedChunkSizePolling = 3 } export enum PollingWatchKind { FixedInterval = 0, PriorityInterval = 1, - DynamicPriority = 2 + DynamicPriority = 2, + FixedChunkSize = 3 } export type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; export interface CompilerOptions { @@ -2845,6 +2869,7 @@ declare namespace ts { outFile?: string; paths?: MapLike; preserveConstEnums?: boolean; + noImplicitOverride?: boolean; preserveSymlinks?: boolean; project?: string; reactNamespace?: string; @@ -2955,6 +2980,7 @@ declare namespace ts { ES2018 = 5, ES2019 = 6, ES2020 = 7, + ES2021 = 8, ESNext = 99, JSON = 100, Latest = 99 @@ -3128,17 +3154,21 @@ declare namespace ts { Iterator = 8388608, NoAsciiEscaping = 16777216, } - export interface EmitHelper { + export interface EmitHelperBase { readonly name: string; readonly scoped: boolean; readonly text: string | ((node: EmitHelperUniqueNameCallback) => string); readonly priority?: number; readonly dependencies?: EmitHelper[]; } - export interface UnscopedEmitHelper extends EmitHelper { + export interface ScopedEmitHelper extends EmitHelperBase { + readonly scoped: true; + } + export interface UnscopedEmitHelper extends EmitHelperBase { readonly scoped: false; readonly text: string; } + export type EmitHelper = ScopedEmitHelper | UnscopedEmitHelper; export type EmitHelperUniqueNameCallback = (name: string) => string; export enum EmitHint { SourceFile = 0, @@ -3166,14 +3196,27 @@ declare namespace ts { createStringLiteralFromNode(sourceNode: PropertyNameLiteral, isSingleQuote?: boolean): StringLiteral; createRegularExpressionLiteral(text: string): RegularExpressionLiteral; createIdentifier(text: string): Identifier; - /** Create a unique temporary variable. */ - createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; - /** Create a unique temporary variable for use in a loop. */ - createLoopVariable(): Identifier; + /** + * Create a unique temporary variable. + * @param recordTempVariable An optional callback used to record the temporary variable name. This + * should usually be a reference to `hoistVariableDeclaration` from a `TransformationContext`, but + * can be `undefined` if you plan to record the temporary variable manually. + * @param reservedInNestedScopes When `true`, reserves the temporary variable name in all nested scopes + * during emit so that the variable can be referenced in a nested function body. This is an alternative to + * setting `EmitFlags.ReuseTempVariableScope` on the nested function itself. + */ + createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, reservedInNestedScopes?: boolean): Identifier; + /** + * Create a unique temporary variable for use in a loop. + * @param reservedInNestedScopes When `true`, reserves the temporary variable name in all nested scopes + * during emit so that the variable can be referenced in a nested function body. This is an alternative to + * setting `EmitFlags.ReuseTempVariableScope` on the nested function itself. + */ + createLoopVariable(reservedInNestedScopes?: boolean): Identifier; /** Create a unique name based on the supplied text. */ createUniqueName(text: string, flags?: GeneratedIdentifierFlags): Identifier; /** Create a unique name generated for a node. */ - getGeneratedNameForNode(node: Node | undefined): Identifier; + getGeneratedNameForNode(node: Node | undefined, flags?: GeneratedIdentifierFlags): Identifier; createPrivateIdentifier(text: string): PrivateIdentifier; createToken(token: SyntaxKind.SuperKeyword): SuperExpression; createToken(token: SyntaxKind.ThisKeyword): ThisExpression; @@ -3284,10 +3327,10 @@ declare namespace ts { updateArrayLiteralExpression(node: ArrayLiteralExpression, elements: readonly Expression[]): ArrayLiteralExpression; createObjectLiteralExpression(properties?: readonly ObjectLiteralElementLike[], multiLine?: boolean): ObjectLiteralExpression; updateObjectLiteralExpression(node: ObjectLiteralExpression, properties: readonly ObjectLiteralElementLike[]): ObjectLiteralExpression; - createPropertyAccessExpression(expression: Expression, name: string | Identifier | PrivateIdentifier): PropertyAccessExpression; - updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: Identifier | PrivateIdentifier): PropertyAccessExpression; - createPropertyAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | Identifier | PrivateIdentifier): PropertyAccessChain; - updatePropertyAccessChain(node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: Identifier | PrivateIdentifier): PropertyAccessChain; + createPropertyAccessExpression(expression: Expression, name: string | MemberName): PropertyAccessExpression; + updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: MemberName): PropertyAccessExpression; + createPropertyAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | MemberName): PropertyAccessChain; + updatePropertyAccessChain(node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: MemberName): PropertyAccessChain; createElementAccessExpression(expression: Expression, index: number | Expression): ElementAccessExpression; updateElementAccessExpression(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; createElementAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, index: number | Expression): ElementAccessChain; @@ -3455,52 +3498,58 @@ declare namespace ts { updateJSDocTypeExpression(node: JSDocTypeExpression, type: TypeNode): JSDocTypeExpression; createJSDocNameReference(name: EntityName): JSDocNameReference; updateJSDocNameReference(node: JSDocNameReference, name: EntityName): JSDocNameReference; + createJSDocLink(name: EntityName | undefined, text: string): JSDocLink; + updateJSDocLink(node: JSDocLink, name: EntityName | undefined, text: string): JSDocLink; createJSDocTypeLiteral(jsDocPropertyTags?: readonly JSDocPropertyLikeTag[], isArrayType?: boolean): JSDocTypeLiteral; updateJSDocTypeLiteral(node: JSDocTypeLiteral, jsDocPropertyTags: readonly JSDocPropertyLikeTag[] | undefined, isArrayType: boolean | undefined): JSDocTypeLiteral; createJSDocSignature(typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag): JSDocSignature; updateJSDocSignature(node: JSDocSignature, typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type: JSDocReturnTag | undefined): JSDocSignature; - createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string): JSDocTemplateTag; - updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | undefined): JSDocTemplateTag; - createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string): JSDocTypedefTag; - updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | undefined): JSDocTypedefTag; - createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string): JSDocParameterTag; - updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | undefined): JSDocParameterTag; - createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string): JSDocPropertyTag; - updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | undefined): JSDocPropertyTag; - createJSDocTypeTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string): JSDocTypeTag; - updateJSDocTypeTag(node: JSDocTypeTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | undefined): JSDocTypeTag; - createJSDocSeeTag(tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string): JSDocSeeTag; - updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string): JSDocSeeTag; - createJSDocReturnTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string): JSDocReturnTag; - updateJSDocReturnTag(node: JSDocReturnTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | undefined): JSDocReturnTag; - createJSDocThisTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string): JSDocThisTag; - updateJSDocThisTag(node: JSDocThisTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | undefined): JSDocThisTag; - createJSDocEnumTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string): JSDocEnumTag; - updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | undefined): JSDocEnumTag; - createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string): JSDocCallbackTag; - updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | undefined): JSDocCallbackTag; - createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string): JSDocAugmentsTag; - updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment: string | undefined): JSDocAugmentsTag; - createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string): JSDocImplementsTag; - updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment: string | undefined): JSDocImplementsTag; - createJSDocAuthorTag(tagName: Identifier | undefined, comment?: string): JSDocAuthorTag; - updateJSDocAuthorTag(node: JSDocAuthorTag, tagName: Identifier | undefined, comment: string | undefined): JSDocAuthorTag; - createJSDocClassTag(tagName: Identifier | undefined, comment?: string): JSDocClassTag; - updateJSDocClassTag(node: JSDocClassTag, tagName: Identifier | undefined, comment: string | undefined): JSDocClassTag; - createJSDocPublicTag(tagName: Identifier | undefined, comment?: string): JSDocPublicTag; - updateJSDocPublicTag(node: JSDocPublicTag, tagName: Identifier | undefined, comment: string | undefined): JSDocPublicTag; - createJSDocPrivateTag(tagName: Identifier | undefined, comment?: string): JSDocPrivateTag; - updateJSDocPrivateTag(node: JSDocPrivateTag, tagName: Identifier | undefined, comment: string | undefined): JSDocPrivateTag; - createJSDocProtectedTag(tagName: Identifier | undefined, comment?: string): JSDocProtectedTag; - updateJSDocProtectedTag(node: JSDocProtectedTag, tagName: Identifier | undefined, comment: string | undefined): JSDocProtectedTag; - createJSDocReadonlyTag(tagName: Identifier | undefined, comment?: string): JSDocReadonlyTag; - updateJSDocReadonlyTag(node: JSDocReadonlyTag, tagName: Identifier | undefined, comment: string | undefined): JSDocReadonlyTag; - createJSDocUnknownTag(tagName: Identifier, comment?: string): JSDocUnknownTag; - updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | undefined): JSDocUnknownTag; - createJSDocDeprecatedTag(tagName: Identifier, comment?: string): JSDocDeprecatedTag; - updateJSDocDeprecatedTag(node: JSDocDeprecatedTag, tagName: Identifier, comment?: string): JSDocDeprecatedTag; - createJSDocComment(comment?: string | undefined, tags?: readonly JSDocTag[] | undefined): JSDoc; - updateJSDocComment(node: JSDoc, comment: string | undefined, tags: readonly JSDocTag[] | undefined): JSDoc; + createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray): JSDocTemplateTag; + updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | NodeArray | undefined): JSDocTemplateTag; + createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocTypedefTag; + updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocTypedefTag; + createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocParameterTag; + updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocParameterTag; + createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocPropertyTag; + updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocPropertyTag; + createJSDocTypeTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocTypeTag; + updateJSDocTypeTag(node: JSDocTypeTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined): JSDocTypeTag; + createJSDocSeeTag(tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag; + updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag; + createJSDocReturnTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray): JSDocReturnTag; + updateJSDocReturnTag(node: JSDocReturnTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined): JSDocReturnTag; + createJSDocThisTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocThisTag; + updateJSDocThisTag(node: JSDocThisTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined): JSDocThisTag; + createJSDocEnumTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocEnumTag; + updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined): JSDocEnumTag; + createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocCallbackTag; + updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocCallbackTag; + createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string | NodeArray): JSDocAugmentsTag; + updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment: string | NodeArray | undefined): JSDocAugmentsTag; + createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string | NodeArray): JSDocImplementsTag; + updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment: string | NodeArray | undefined): JSDocImplementsTag; + createJSDocAuthorTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocAuthorTag; + updateJSDocAuthorTag(node: JSDocAuthorTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocAuthorTag; + createJSDocClassTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocClassTag; + updateJSDocClassTag(node: JSDocClassTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocClassTag; + createJSDocPublicTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocPublicTag; + updateJSDocPublicTag(node: JSDocPublicTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocPublicTag; + createJSDocPrivateTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocPrivateTag; + updateJSDocPrivateTag(node: JSDocPrivateTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocPrivateTag; + createJSDocProtectedTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocProtectedTag; + updateJSDocProtectedTag(node: JSDocProtectedTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocProtectedTag; + createJSDocReadonlyTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocReadonlyTag; + updateJSDocReadonlyTag(node: JSDocReadonlyTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocReadonlyTag; + createJSDocUnknownTag(tagName: Identifier, comment?: string | NodeArray): JSDocUnknownTag; + updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | NodeArray | undefined): JSDocUnknownTag; + createJSDocDeprecatedTag(tagName: Identifier, comment?: string | NodeArray): JSDocDeprecatedTag; + updateJSDocDeprecatedTag(node: JSDocDeprecatedTag, tagName: Identifier, comment?: string | NodeArray): JSDocDeprecatedTag; + createJSDocOverrideTag(tagName: Identifier, comment?: string | NodeArray): JSDocOverrideTag; + updateJSDocOverrideTag(node: JSDocOverrideTag, tagName: Identifier, comment?: string | NodeArray): JSDocOverrideTag; + createJSDocText(text: string): JSDocText; + updateJSDocText(node: JSDocText, text: string): JSDocText; + createJSDocComment(comment?: string | NodeArray | undefined, tags?: readonly JSDocTag[] | undefined): JSDoc; + updateJSDocComment(node: JSDoc, comment: string | NodeArray | undefined, tags: readonly JSDocTag[] | undefined): JSDoc; createJsxElement(openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement; updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement; createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxSelfClosingElement; @@ -3748,12 +3797,12 @@ declare namespace ts { * }); * ``` */ - onEmitNode?(hint: EmitHint, node: Node | undefined, emitCallback: (hint: EmitHint, node: Node | undefined) => void): void; + onEmitNode?(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; /** * A hook used to check if an emit notification is required for a node. * @param node The node to emit. */ - isEmitNotificationEnabled?(node: Node | undefined): boolean; + isEmitNotificationEnabled?(node: Node): boolean; /** * A hook used by the Printer to perform just-in-time substitution of a node. This is * primarily used by node transformations that need to substitute one node for another, @@ -3867,6 +3916,8 @@ declare namespace ts { readonly disableSuggestions?: boolean; readonly quotePreference?: "auto" | "double" | "single"; readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsForImportStatements?: boolean; + readonly includeCompletionsWithSnippetText?: boolean; readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; @@ -3965,7 +4016,7 @@ declare namespace ts { scanJsxIdentifier(): SyntaxKind; scanJsxAttributeValue(): SyntaxKind; reScanJsxAttributeValue(): SyntaxKind; - reScanJsxToken(): JsxTokenSyntaxKind; + reScanJsxToken(allowMultilineJsxText?: boolean): JsxTokenSyntaxKind; reScanLessThanToken(): SyntaxKind; reScanQuestionToken(): SyntaxKind; reScanInvalidIdentifier(): SyntaxKind; @@ -4100,7 +4151,7 @@ declare namespace ts { function idText(identifierOrPrivateName: Identifier | PrivateIdentifier): string; function symbolName(symbol: Symbol): string; function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | PrivateIdentifier | undefined; - function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined; + function getNameOfDeclaration(declaration: Declaration | Expression | undefined): DeclarationName | undefined; /** * Gets the JSDoc parameter tags for the node if present. * @@ -4146,6 +4197,7 @@ declare namespace ts { function getJSDocProtectedTag(node: Node): JSDocProtectedTag | undefined; /** Gets the JSDoc protected tag for the node if present */ function getJSDocReadonlyTag(node: Node): JSDocReadonlyTag | undefined; + function getJSDocOverrideTagNoCache(node: Node): JSDocOverrideTag | undefined; /** Gets the JSDoc deprecated tag for the node if present */ function getJSDocDeprecatedTag(node: Node): JSDocDeprecatedTag | undefined; /** Gets the JSDoc enum tag for the node if present */ @@ -4183,13 +4235,15 @@ declare namespace ts { function getAllJSDocTags(node: Node, predicate: (tag: JSDocTag) => tag is T): readonly T[]; /** Gets all JSDoc tags of a specified kind */ function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): readonly JSDocTag[]; + /** Gets the text of a jsdoc comment, flattening links to their text. */ + function getTextOfJSDocComment(comment?: string | NodeArray): string | undefined; /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. */ function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): readonly TypeParameterDeclaration[]; function getEffectiveConstraintOfTypeParameter(node: TypeParameterDeclaration): TypeNode | undefined; - function isIdentifierOrPrivateIdentifier(node: Node): node is Identifier | PrivateIdentifier; + function isMemberName(node: Node): node is MemberName; function isPropertyAccessChain(node: Node): node is PropertyAccessChain; function isElementAccessChain(node: Node): node is ElementAccessChain; function isCallChain(node: Node): node is CallChain; @@ -4204,6 +4258,12 @@ declare namespace ts { function isUnparsedTextLike(node: Node): node is UnparsedTextLike; function isUnparsedNode(node: Node): node is UnparsedNode; function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag; + /** + * True if kind is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. + */ + function isTokenKind(kind: SyntaxKind): boolean; /** * True if node is of some token syntax kind. * For example, this is true for an IfKeyword but not for an IfStatement. @@ -4220,7 +4280,7 @@ declare namespace ts { function isEntityName(node: Node): node is EntityName; function isPropertyName(node: Node): node is PropertyName; function isBindingName(node: Node): node is BindingName; - function isFunctionLike(node: Node): node is SignatureDeclaration; + function isFunctionLike(node: Node | undefined): node is SignatureDeclaration; function isClassElement(node: Node): node is ClassElement; function isClassLike(node: Node): node is ClassLikeDeclaration; function isAccessor(node: Node): node is AccessorDeclaration; @@ -4346,10 +4406,14 @@ declare namespace ts { function isTemplateHead(node: Node): node is TemplateHead; function isTemplateMiddle(node: Node): node is TemplateMiddle; function isTemplateTail(node: Node): node is TemplateTail; + function isDotDotDotToken(node: Node): node is DotDotDotToken; + function isPlusToken(node: Node): node is PlusToken; + function isMinusToken(node: Node): node is MinusToken; + function isAsteriskToken(node: Node): node is AsteriskToken; function isIdentifier(node: Node): node is Identifier; + function isPrivateIdentifier(node: Node): node is PrivateIdentifier; function isQualifiedName(node: Node): node is QualifiedName; function isComputedPropertyName(node: Node): node is ComputedPropertyName; - function isPrivateIdentifier(node: Node): node is PrivateIdentifier; function isTypeParameterDeclaration(node: Node): node is TypeParameterDeclaration; function isParameter(node: Node): node is ParameterDeclaration; function isDecorator(node: Node): node is Decorator; @@ -4492,6 +4556,7 @@ declare namespace ts { function isUnparsedSource(node: Node): node is UnparsedSource; function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression; function isJSDocNameReference(node: Node): node is JSDocNameReference; + function isJSDocLink(node: Node): node is JSDocLink; function isJSDocAllType(node: Node): node is JSDocAllType; function isJSDocUnknownType(node: Node): node is JSDocUnknownType; function isJSDocNullableType(node: Node): node is JSDocNullableType; @@ -4511,6 +4576,7 @@ declare namespace ts { function isJSDocPrivateTag(node: Node): node is JSDocPrivateTag; function isJSDocProtectedTag(node: Node): node is JSDocProtectedTag; function isJSDocReadonlyTag(node: Node): node is JSDocReadonlyTag; + function isJSDocOverrideTag(node: Node): node is JSDocOverrideTag; function isJSDocDeprecatedTag(node: Node): node is JSDocDeprecatedTag; function isJSDocSeeTag(node: Node): node is JSDocSeeTag; function isJSDocEnumTag(node: Node): node is JSDocEnumTag; @@ -4575,7 +4641,7 @@ declare namespace ts { /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ - export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): ParsedCommandLine | undefined; + export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions | undefined, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): ParsedCommandLine | undefined; /** * Read tsconfig.json file * @param fileName The path to the config file @@ -4643,13 +4709,13 @@ declare namespace ts { export {}; } declare namespace ts { - function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; + export function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, cache?: TypeReferenceDirectiveResolutionCache): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -4658,30 +4724,46 @@ declare namespace ts { * More type directives might appear in the program later as a result of loading actual source files; * this list is only the set of defaults that are implicitly included. */ - function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + export function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + export interface TypeReferenceDirectiveResolutionCache extends PerDirectoryResolutionCache, PackageJsonInfoCache { + } /** - * Cached module resolutions per containing directory. + * Cached resolutions per containing directory. * This assumes that any module id will have the same resolution for sibling files located in the same folder. */ - interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { - getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + export interface PerDirectoryResolutionCache { + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; + clear(): void; + /** + * Updates with the current compilerOptions the cache will operate with. + * This updates the redirects map as well if needed so module resolutions are cached if they can across the projects + */ + update(options: CompilerOptions): void; + } + export interface ModuleResolutionCache extends PerDirectoryResolutionCache, NonRelativeModuleNameResolutionCache, PackageJsonInfoCache { + getPackageJsonInfoCache(): PackageJsonInfoCache; } /** * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. */ - interface NonRelativeModuleNameResolutionCache { + export interface NonRelativeModuleNameResolutionCache extends PackageJsonInfoCache { getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; } - interface PerModuleNameCache { + export interface PackageJsonInfoCache { + clear(): void; + } + export interface PerModuleNameCache { get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; } - function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions): ModuleResolutionCache; - function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions): ModuleResolutionCache; + export function createTypeReferenceDirectiveResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions, packageJsonInfoCache?: PackageJsonInfoCache): TypeReferenceDirectiveResolutionCache; + export function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; + export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + export {}; } declare namespace ts { /** @@ -4748,6 +4830,10 @@ declare namespace ts { * environment and merging hoisted declarations upon completion. */ function visitFunctionBody(node: ConciseBody, visitor: Visitor, context: TransformationContext): ConciseBody; + /** + * Visits an iteration body, adding any block-scoped variables required by the transformation. + */ + function visitIterationBody(body: Statement, visitor: Visitor, context: TransformationContext): Statement; /** * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place. * @@ -5036,6 +5122,8 @@ declare namespace ts { interface WatchCompilerHost extends ProgramHost, WatchHost { /** Instead of using output d.ts file from project reference, use its source file */ useSourceOfProjectReferenceRedirect?(): boolean; + /** If provided, use this method to get parsed command lines for referenced projects */ + getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; } @@ -5131,9 +5219,9 @@ declare namespace ts { interface SolutionBuilderWithWatchHost extends SolutionBuilderHostBase, WatchHost { } interface SolutionBuilder { - build(project?: string, cancellationToken?: CancellationToken): ExitStatus; + build(project?: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; clean(project?: string): ExitStatus; - buildReferences(project: string, cancellationToken?: CancellationToken): ExitStatus; + buildReferences(project: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; cleanReferences(project?: string): ExitStatus; getNextInvalidatedProject(cancellationToken?: CancellationToken): InvalidatedProject | undefined; } @@ -5291,7 +5379,7 @@ declare namespace ts { getName(): string; getDeclarations(): Declaration[] | undefined; getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; - getJsDocTags(): JSDocTagInfo[]; + getJsDocTags(checker?: TypeChecker): JSDocTagInfo[]; } interface Type { getFlags(): TypeFlags; @@ -5422,6 +5510,7 @@ declare namespace ts { isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; writeFile?(fileName: string, content: string): void; + getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; } type WithMetadata = T & { metadata?: unknown; @@ -5511,12 +5600,13 @@ declare namespace ts { * * @param fileName The path to the file * @param position A zero based index of the character where you want the entries - * @param entryName The name from an existing completion which came from `getCompletionsAtPosition` + * @param entryName The `name` from an existing completion which came from `getCompletionsAtPosition` * @param formatOptions How should code samples in the completions be formatted, can be undefined for backwards compatibility - * @param source Source code for the current file, can be undefined for backwards compatibility + * @param source `source` property from the completion entry * @param preferences User settings, can be undefined for backwards compatibility + * @param data `data` property from the completion entry */ - getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; + getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined, data: CompletionEntryData | undefined): CompletionEntryDetails | undefined; getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; /** * Gets semantic information about the identifier at a particular position in a @@ -5577,7 +5667,7 @@ declare namespace ts { applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise; getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined, triggerReason?: RefactorTriggerReason, kind?: string): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; - organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; + organizeImports(args: OrganizeImportsArgs, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; getProgram(): Program | undefined; @@ -5594,8 +5684,10 @@ declare namespace ts { type: "file"; fileName: string; } - type OrganizeImportsScope = CombinedCodeFixScope; - type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#"; + interface OrganizeImportsArgs extends CombinedCodeFixScope { + skipDestructiveCodeActions?: boolean; + } + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; interface GetCompletionsAtPositionOptions extends UserPreferences { /** * If the editor is asking for completions because a certain character was typed @@ -5947,6 +6039,7 @@ declare namespace ts { name: string; containerKind: ScriptElementKind; containerName: string; + unverified?: boolean; } interface DefinitionInfoAndBoundSpan { definitions?: readonly DefinitionInfo[]; @@ -5981,15 +6074,21 @@ declare namespace ts { typeParameterName = 18, enumMemberName = 19, functionName = 20, - regularExpressionLiteral = 21 + regularExpressionLiteral = 21, + link = 22, + linkName = 23, + linkText = 24 } interface SymbolDisplayPart { text: string; kind: string; } + interface JSDocLinkDisplayPart extends SymbolDisplayPart { + target: DocumentSpan; + } interface JSDocTagInfo { name: string; - text?: string; + text?: SymbolDisplayPart[]; } interface QuickInfo { kind: ScriptElementKind; @@ -6074,14 +6173,36 @@ declare namespace ts { * true when the current location also allows for a new identifier */ isNewIdentifierLocation: boolean; + /** + * Indicates to client to continue requesting completions on subsequent keystrokes. + */ + isIncomplete?: true; entries: CompletionEntry[]; } + interface CompletionEntryData { + /** The file name declaring the export's module symbol, if it was an external module */ + fileName?: string; + /** The module name (with quotes stripped) of the export's module symbol, if it was an ambient module */ + ambientModuleName?: string; + /** True if the export was found in the package.json AutoImportProvider */ + isPackageJsonImport?: true; + /** + * The name of the property or export in the module's symbol table. Differs from the completion name + * in the case of InternalSymbolName.ExportEquals and InternalSymbolName.Default. + */ + exportName: string; + /** + * Set for auto imports with eagerly resolved module specifiers. + */ + moduleSpecifier?: string; + } interface CompletionEntry { name: string; kind: ScriptElementKind; kindModifiers?: string; sortText: string; insertText?: string; + isSnippet?: true; /** * An optional span that indicates the text to be replaced by this completion item. * If present, this span should be used instead of the default one. @@ -6090,9 +6211,20 @@ declare namespace ts { replacementSpan?: TextSpan; hasAction?: true; source?: string; + sourceDisplay?: SymbolDisplayPart[]; isRecommended?: true; isFromUncheckedFile?: true; isPackageJsonImport?: true; + isImportStatementCompletion?: true; + /** + * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, + * that allows TS Server to look up the symbol represented by the completion item, disambiguating + * items with the same name. Currently only defined for auto-import completions, but the type is + * `unknown` in the protocol, so it can be changed as needed to support other kinds of completions. + * The presence of this property should generally not be used to assume that this completion entry + * is an auto-import. + */ + data?: CompletionEntryData; } interface CompletionEntryDetails { name: string; @@ -6102,7 +6234,9 @@ declare namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; codeActions?: CodeAction[]; + /** @deprecated Use `sourceDisplay` instead. */ source?: SymbolDisplayPart[]; + sourceDisplay?: SymbolDisplayPart[]; } interface OutliningSpan { /** The span of the document to actually collapse. */ @@ -6256,7 +6390,13 @@ declare namespace ts { */ jsxAttribute = "JSX attribute", /** String literal */ - string = "string" + string = "string", + /** Jsdoc @link: in `{@link C link text}`, the before and after text "{@link " and "}" */ + link = "link", + /** Jsdoc @link: in `{@link C link text}`, the entity name "C" */ + linkName = "link name", + /** Jsdoc @link: in `{@link C link text}`, the link text "link text" */ + linkText = "link text" } enum ScriptElementKindModifier { none = "", @@ -6397,8 +6537,23 @@ declare namespace ts { * @param fileName The name of the file to be released * @param compilationSettings The compilation settings used to acquire the file */ + /**@deprecated pass scriptKind for correctness */ releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + /** + * Informs the DocumentRegistry that a file is not needed any longer. + * + * Note: It is not allowed to call release on a SourceFile that was not acquired from + * this registry originally. + * + * @param fileName The name of the file to be released + * @param compilationSettings The compilation settings used to acquire the file + * @param scriptKind The script kind of the file to be released + */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind: ScriptKind): void; + /** + * @deprecated pass scriptKind for correctness */ releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void; + releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind: ScriptKind): void; reportStats(): string; } type DocumentRegistryBucketKey = string & { @@ -6469,7 +6624,7 @@ declare namespace ts { /** @deprecated Use `factory.createRegularExpressionLiteral` or the factory supplied by your transformation context instead. */ const createRegularExpressionLiteral: (text: string) => RegularExpressionLiteral; /** @deprecated Use `factory.createLoopVariable` or the factory supplied by your transformation context instead. */ - const createLoopVariable: () => Identifier; + const createLoopVariable: (reservedInNestedScopes?: boolean | undefined) => Identifier; /** @deprecated Use `factory.createUniqueName` or the factory supplied by your transformation context instead. */ const createUniqueName: (text: string, flags?: GeneratedIdentifierFlags | undefined) => Identifier; /** @deprecated Use `factory.createPrivateIdentifier` or the factory supplied by your transformation context instead. */ @@ -6641,13 +6796,13 @@ declare namespace ts { /** @deprecated Use `factory.updateObjectLiteralExpression` or the factory supplied by your transformation context instead. */ const updateObjectLiteral: (node: ObjectLiteralExpression, properties: readonly ObjectLiteralElementLike[]) => ObjectLiteralExpression; /** @deprecated Use `factory.createPropertyAccessExpression` or the factory supplied by your transformation context instead. */ - const createPropertyAccess: (expression: Expression, name: string | Identifier | PrivateIdentifier) => PropertyAccessExpression; + const createPropertyAccess: (expression: Expression, name: string | MemberName) => PropertyAccessExpression; /** @deprecated Use `factory.updatePropertyAccessExpression` or the factory supplied by your transformation context instead. */ - const updatePropertyAccess: (node: PropertyAccessExpression, expression: Expression, name: Identifier | PrivateIdentifier) => PropertyAccessExpression; + const updatePropertyAccess: (node: PropertyAccessExpression, expression: Expression, name: MemberName) => PropertyAccessExpression; /** @deprecated Use `factory.createPropertyAccessChain` or the factory supplied by your transformation context instead. */ - const createPropertyAccessChain: (expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | Identifier | PrivateIdentifier) => PropertyAccessChain; + const createPropertyAccessChain: (expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | MemberName) => PropertyAccessChain; /** @deprecated Use `factory.updatePropertyAccessChain` or the factory supplied by your transformation context instead. */ - const updatePropertyAccessChain: (node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: Identifier | PrivateIdentifier) => PropertyAccessChain; + const updatePropertyAccessChain: (node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: MemberName) => PropertyAccessChain; /** @deprecated Use `factory.createElementAccessExpression` or the factory supplied by your transformation context instead. */ const createElementAccess: (expression: Expression, index: number | Expression) => ElementAccessExpression; /** @deprecated Use `factory.updateElementAccessExpression` or the factory supplied by your transformation context instead. */ @@ -6917,51 +7072,51 @@ declare namespace ts { /** @deprecated Use `factory.createJSDocTypeExpression` or the factory supplied by your transformation context instead. */ const createJSDocTypeExpression: (type: TypeNode) => JSDocTypeExpression; /** @deprecated Use `factory.createJSDocTypeTag` or the factory supplied by your transformation context instead. */ - const createJSDocTypeTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | undefined) => JSDocTypeTag; + const createJSDocTypeTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray | undefined) => JSDocTypeTag; /** @deprecated Use `factory.createJSDocReturnTag` or the factory supplied by your transformation context instead. */ - const createJSDocReturnTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | undefined, comment?: string | undefined) => JSDocReturnTag; + const createJSDocReturnTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | undefined, comment?: string | NodeArray | undefined) => JSDocReturnTag; /** @deprecated Use `factory.createJSDocThisTag` or the factory supplied by your transformation context instead. */ - const createJSDocThisTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | undefined) => JSDocThisTag; + const createJSDocThisTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray | undefined) => JSDocThisTag; /** @deprecated Use `factory.createJSDocComment` or the factory supplied by your transformation context instead. */ - const createJSDocComment: (comment?: string | undefined, tags?: readonly JSDocTag[] | undefined) => JSDoc; + const createJSDocComment: (comment?: string | NodeArray | undefined, tags?: readonly JSDocTag[] | undefined) => JSDoc; /** @deprecated Use `factory.createJSDocParameterTag` or the factory supplied by your transformation context instead. */ - const createJSDocParameterTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | undefined) => JSDocParameterTag; + const createJSDocParameterTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | NodeArray | undefined) => JSDocParameterTag; /** @deprecated Use `factory.createJSDocClassTag` or the factory supplied by your transformation context instead. */ - const createJSDocClassTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocClassTag; + const createJSDocClassTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocClassTag; /** @deprecated Use `factory.createJSDocAugmentsTag` or the factory supplied by your transformation context instead. */ const createJSDocAugmentsTag: (tagName: Identifier | undefined, className: ExpressionWithTypeArguments & { readonly expression: Identifier | PropertyAccessEntityNameExpression; - }, comment?: string | undefined) => JSDocAugmentsTag; + }, comment?: string | NodeArray | undefined) => JSDocAugmentsTag; /** @deprecated Use `factory.createJSDocEnumTag` or the factory supplied by your transformation context instead. */ - const createJSDocEnumTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | undefined) => JSDocEnumTag; + const createJSDocEnumTag: (tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray | undefined) => JSDocEnumTag; /** @deprecated Use `factory.createJSDocTemplateTag` or the factory supplied by your transformation context instead. */ - const createJSDocTemplateTag: (tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | undefined) => JSDocTemplateTag; + const createJSDocTemplateTag: (tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray | undefined) => JSDocTemplateTag; /** @deprecated Use `factory.createJSDocTypedefTag` or the factory supplied by your transformation context instead. */ - const createJSDocTypedefTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeLiteral | JSDocTypeExpression | undefined, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | undefined) => JSDocTypedefTag; + const createJSDocTypedefTag: (tagName: Identifier | undefined, typeExpression?: JSDocTypeLiteral | JSDocTypeExpression | undefined, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | NodeArray | undefined) => JSDocTypedefTag; /** @deprecated Use `factory.createJSDocCallbackTag` or the factory supplied by your transformation context instead. */ - const createJSDocCallbackTag: (tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | undefined) => JSDocCallbackTag; + const createJSDocCallbackTag: (tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration | undefined, comment?: string | NodeArray | undefined) => JSDocCallbackTag; /** @deprecated Use `factory.createJSDocSignature` or the factory supplied by your transformation context instead. */ const createJSDocSignature: (typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag | undefined) => JSDocSignature; /** @deprecated Use `factory.createJSDocPropertyTag` or the factory supplied by your transformation context instead. */ - const createJSDocPropertyTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | undefined) => JSDocPropertyTag; + const createJSDocPropertyTag: (tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression | undefined, isNameFirst?: boolean | undefined, comment?: string | NodeArray | undefined) => JSDocPropertyTag; /** @deprecated Use `factory.createJSDocTypeLiteral` or the factory supplied by your transformation context instead. */ const createJSDocTypeLiteral: (jsDocPropertyTags?: readonly JSDocPropertyLikeTag[] | undefined, isArrayType?: boolean | undefined) => JSDocTypeLiteral; /** @deprecated Use `factory.createJSDocImplementsTag` or the factory supplied by your transformation context instead. */ const createJSDocImplementsTag: (tagName: Identifier | undefined, className: ExpressionWithTypeArguments & { readonly expression: Identifier | PropertyAccessEntityNameExpression; - }, comment?: string | undefined) => JSDocImplementsTag; + }, comment?: string | NodeArray | undefined) => JSDocImplementsTag; /** @deprecated Use `factory.createJSDocAuthorTag` or the factory supplied by your transformation context instead. */ - const createJSDocAuthorTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocAuthorTag; + const createJSDocAuthorTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocAuthorTag; /** @deprecated Use `factory.createJSDocPublicTag` or the factory supplied by your transformation context instead. */ - const createJSDocPublicTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocPublicTag; + const createJSDocPublicTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocPublicTag; /** @deprecated Use `factory.createJSDocPrivateTag` or the factory supplied by your transformation context instead. */ - const createJSDocPrivateTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocPrivateTag; + const createJSDocPrivateTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocPrivateTag; /** @deprecated Use `factory.createJSDocProtectedTag` or the factory supplied by your transformation context instead. */ - const createJSDocProtectedTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocProtectedTag; + const createJSDocProtectedTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocProtectedTag; /** @deprecated Use `factory.createJSDocReadonlyTag` or the factory supplied by your transformation context instead. */ - const createJSDocReadonlyTag: (tagName: Identifier | undefined, comment?: string | undefined) => JSDocReadonlyTag; + const createJSDocReadonlyTag: (tagName: Identifier | undefined, comment?: string | NodeArray | undefined) => JSDocReadonlyTag; /** @deprecated Use `factory.createJSDocUnknownTag` or the factory supplied by your transformation context instead. */ - const createJSDocTag: (tagName: Identifier, comment?: string | undefined) => JSDocUnknownTag; + const createJSDocTag: (tagName: Identifier, comment?: string | NodeArray | undefined) => JSDocUnknownTag; /** @deprecated Use `factory.createJsxElement` or the factory supplied by your transformation context instead. */ const createJsxElement: (openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement) => JsxElement; /** @deprecated Use `factory.updateJsxElement` or the factory supplied by your transformation context instead. */ @@ -7217,6 +7372,10 @@ declare namespace ts { */ interface Map extends ESMap { } + /** + * @deprecated Use `isMemberName` instead. + */ + const isIdentifierOrPrivateIdentifier: (node: Node) => node is MemberName; } export = ts; \ No newline at end of file diff --git a/tests/baselines/reference/argumentsObjectIterator02_ES5.errors.txt b/tests/baselines/reference/argumentsObjectIterator02_ES5.errors.txt index 4ae19920e3772..1448a605ce0ad 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 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(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 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. +!!! 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/argumentsObjectIterator02_ES6.types b/tests/baselines/reference/argumentsObjectIterator02_ES6.types index a494a45f9356b..07aa33168f15a 100644 --- a/tests/baselines/reference/argumentsObjectIterator02_ES6.types +++ b/tests/baselines/reference/argumentsObjectIterator02_ES6.types @@ -9,9 +9,9 @@ function doubleAndReturnAsArray(x: number, y: number, z: number): [number, numbe >blah : () => IterableIterator >arguments[Symbol.iterator] : () => IterableIterator >arguments : IArguments ->Symbol.iterator : symbol +>Symbol.iterator : unique symbol >Symbol : SymbolConstructor ->iterator : symbol +>iterator : unique symbol let result = []; >result : any[] diff --git a/tests/baselines/reference/arithAssignTyping.errors.txt b/tests/baselines/reference/arithAssignTyping.errors.txt index 12b5b52698dbf..143ad5cdaf8e8 100644 --- a/tests/baselines/reference/arithAssignTyping.errors.txt +++ b/tests/baselines/reference/arithAssignTyping.errors.txt @@ -1,15 +1,15 @@ -tests/cases/compiler/arithAssignTyping.ts(3,1): error TS2539: Cannot assign to 'f' because it is not a variable. -tests/cases/compiler/arithAssignTyping.ts(4,1): error TS2539: Cannot assign to 'f' because it is not a variable. -tests/cases/compiler/arithAssignTyping.ts(5,1): error TS2539: Cannot assign to 'f' because it is not a variable. -tests/cases/compiler/arithAssignTyping.ts(6,1): error TS2539: Cannot assign to 'f' because it is not a variable. -tests/cases/compiler/arithAssignTyping.ts(7,1): error TS2539: Cannot assign to 'f' because it is not a variable. -tests/cases/compiler/arithAssignTyping.ts(8,1): error TS2539: Cannot assign to 'f' because it is not a variable. -tests/cases/compiler/arithAssignTyping.ts(9,1): error TS2539: Cannot assign to 'f' because it is not a variable. -tests/cases/compiler/arithAssignTyping.ts(10,1): error TS2539: Cannot assign to 'f' because it is not a variable. -tests/cases/compiler/arithAssignTyping.ts(11,1): error TS2539: Cannot assign to 'f' because it is not a variable. -tests/cases/compiler/arithAssignTyping.ts(12,1): error TS2539: Cannot assign to 'f' because it is not a variable. -tests/cases/compiler/arithAssignTyping.ts(13,1): error TS2539: Cannot assign to 'f' because it is not a variable. -tests/cases/compiler/arithAssignTyping.ts(14,1): error TS2539: Cannot assign to 'f' because it is not a variable. +tests/cases/compiler/arithAssignTyping.ts(3,1): error TS2629: Cannot assign to 'f' because it is a class. +tests/cases/compiler/arithAssignTyping.ts(4,1): error TS2629: Cannot assign to 'f' because it is a class. +tests/cases/compiler/arithAssignTyping.ts(5,1): error TS2629: Cannot assign to 'f' because it is a class. +tests/cases/compiler/arithAssignTyping.ts(6,1): error TS2629: Cannot assign to 'f' because it is a class. +tests/cases/compiler/arithAssignTyping.ts(7,1): error TS2629: Cannot assign to 'f' because it is a class. +tests/cases/compiler/arithAssignTyping.ts(8,1): error TS2629: Cannot assign to 'f' because it is a class. +tests/cases/compiler/arithAssignTyping.ts(9,1): error TS2629: Cannot assign to 'f' because it is a class. +tests/cases/compiler/arithAssignTyping.ts(10,1): error TS2629: Cannot assign to 'f' because it is a class. +tests/cases/compiler/arithAssignTyping.ts(11,1): error TS2629: Cannot assign to 'f' because it is a class. +tests/cases/compiler/arithAssignTyping.ts(12,1): error TS2629: Cannot assign to 'f' because it is a class. +tests/cases/compiler/arithAssignTyping.ts(13,1): error TS2629: Cannot assign to 'f' because it is a class. +tests/cases/compiler/arithAssignTyping.ts(14,1): error TS2629: Cannot assign to 'f' because it is a class. ==== tests/cases/compiler/arithAssignTyping.ts (12 errors) ==== @@ -17,37 +17,37 @@ tests/cases/compiler/arithAssignTyping.ts(14,1): error TS2539: Cannot assign to f += ''; // error ~ -!!! error TS2539: Cannot assign to 'f' because it is not a variable. +!!! error TS2629: Cannot assign to 'f' because it is a class. f += 1; // error ~ -!!! error TS2539: Cannot assign to 'f' because it is not a variable. +!!! error TS2629: Cannot assign to 'f' because it is a class. f -= 1; // error ~ -!!! error TS2539: Cannot assign to 'f' because it is not a variable. +!!! error TS2629: Cannot assign to 'f' because it is a class. f *= 1; // error ~ -!!! error TS2539: Cannot assign to 'f' because it is not a variable. +!!! error TS2629: Cannot assign to 'f' because it is a class. f /= 1; // error ~ -!!! error TS2539: Cannot assign to 'f' because it is not a variable. +!!! error TS2629: Cannot assign to 'f' because it is a class. f %= 1; // error ~ -!!! error TS2539: Cannot assign to 'f' because it is not a variable. +!!! error TS2629: Cannot assign to 'f' because it is a class. f &= 1; // error ~ -!!! error TS2539: Cannot assign to 'f' because it is not a variable. +!!! error TS2629: Cannot assign to 'f' because it is a class. f |= 1; // error ~ -!!! error TS2539: Cannot assign to 'f' because it is not a variable. +!!! error TS2629: Cannot assign to 'f' because it is a class. f <<= 1; // error ~ -!!! error TS2539: Cannot assign to 'f' because it is not a variable. +!!! error TS2629: Cannot assign to 'f' because it is a class. f >>= 1; // error ~ -!!! error TS2539: Cannot assign to 'f' because it is not a variable. +!!! error TS2629: Cannot assign to 'f' because it is a class. f >>>= 1; // error ~ -!!! error TS2539: Cannot assign to 'f' because it is not a variable. +!!! error TS2629: Cannot assign to 'f' because it is a class. f ^= 1; // error ~ -!!! error TS2539: Cannot assign to 'f' because it is not a variable. \ No newline at end of file +!!! error TS2629: Cannot assign to 'f' because it is a class. \ No newline at end of file diff --git a/tests/baselines/reference/arrayLiterals3.errors.txt b/tests/baselines/reference/arrayLiterals3.errors.txt index 8ea3d1583b6fb..3b2d25d17f4ec 100644 --- a/tests/baselines/reference/arrayLiterals3.errors.txt +++ b/tests/baselines/reference/arrayLiterals3.errors.txt @@ -8,9 +8,8 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(17,5): error tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(33,5): error TS2322: Type 'number[]' is not assignable to type '[number, number, number]'. Target requires 3 element(s) but source may have fewer. tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error TS2322: Type '(string | number)[]' is not assignable to type 'myArray'. - The types returned by 'pop()' are incompatible between these types. - Type 'string | number' is not assignable to type 'Number'. - Type 'string' is not assignable to type 'Number'. + Type 'string | number' is not assignable to type 'Number'. + Type 'string' is not assignable to type 'Number'. ==== tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts (7 errors) ==== @@ -65,7 +64,6 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error var c2: myArray = [...temp1, ...temp]; // Error cannot assign (number|string)[] to number[] ~~ !!! error TS2322: Type '(string | number)[]' is not assignable to type 'myArray'. -!!! error TS2322: The types returned by 'pop()' are incompatible between these types. -!!! error TS2322: Type 'string | number' is not assignable to type 'Number'. -!!! error TS2322: Type 'string' is not assignable to type 'Number'. +!!! error TS2322: Type 'string | number' is not assignable to type 'Number'. +!!! error TS2322: Type 'string' is not assignable to type 'Number'. \ No newline at end of file diff --git a/tests/baselines/reference/assignAnyToEveryType.errors.txt b/tests/baselines/reference/assignAnyToEveryType.errors.txt index 86efb0c3019de..a1ff42218e370 100644 --- a/tests/baselines/reference/assignAnyToEveryType.errors.txt +++ b/tests/baselines/reference/assignAnyToEveryType.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/types/any/assignAnyToEveryType.ts(41,1): error TS2539: Cannot assign to 'M' because it is not a variable. +tests/cases/conformance/types/any/assignAnyToEveryType.ts(41,1): error TS2631: Cannot assign to 'M' because it is a namespace. ==== tests/cases/conformance/types/any/assignAnyToEveryType.ts (1 errors) ==== @@ -44,7 +44,7 @@ tests/cases/conformance/types/any/assignAnyToEveryType.ts(41,1): error TS2539: C M = x; ~ -!!! error TS2539: Cannot assign to 'M' because it is not a variable. +!!! error TS2631: Cannot assign to 'M' because it is a namespace. function k(a: T) { a = x; diff --git a/tests/baselines/reference/assignToEnum.errors.txt b/tests/baselines/reference/assignToEnum.errors.txt index 53b4afc186496..182cc8a5b72fd 100644 --- a/tests/baselines/reference/assignToEnum.errors.txt +++ b/tests/baselines/reference/assignToEnum.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/assignToEnum.ts(2,1): error TS2539: Cannot assign to 'A' because it is not a variable. -tests/cases/compiler/assignToEnum.ts(3,1): error TS2539: Cannot assign to 'A' because it is not a variable. +tests/cases/compiler/assignToEnum.ts(2,1): error TS2628: Cannot assign to 'A' because it is an enum. +tests/cases/compiler/assignToEnum.ts(3,1): error TS2628: Cannot assign to 'A' because it is an enum. tests/cases/compiler/assignToEnum.ts(4,3): error TS2540: Cannot assign to 'foo' because it is a read-only property. tests/cases/compiler/assignToEnum.ts(5,3): error TS2540: Cannot assign to 'foo' because it is a read-only property. @@ -8,10 +8,10 @@ tests/cases/compiler/assignToEnum.ts(5,3): error TS2540: Cannot assign to 'foo' enum A { foo, bar } A = undefined; // invalid LHS ~ -!!! error TS2539: Cannot assign to 'A' because it is not a variable. +!!! error TS2628: Cannot assign to 'A' because it is an enum. A = A.bar; // invalid LHS ~ -!!! error TS2539: Cannot assign to 'A' because it is not a variable. +!!! error TS2628: Cannot assign to 'A' because it is an enum. A.foo = 1; // invalid LHS ~~~ !!! error TS2540: Cannot assign to 'foo' because it is a read-only property. diff --git a/tests/baselines/reference/assignToExistingClass.errors.txt b/tests/baselines/reference/assignToExistingClass.errors.txt index 5f7faac9e64d7..20f6cd8823da0 100644 --- a/tests/baselines/reference/assignToExistingClass.errors.txt +++ b/tests/baselines/reference/assignToExistingClass.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/assignToExistingClass.ts(8,13): error TS2539: Cannot assign to 'Mocked' because it is not a variable. +tests/cases/compiler/assignToExistingClass.ts(8,13): error TS2629: Cannot assign to 'Mocked' because it is a class. ==== tests/cases/compiler/assignToExistingClass.ts (1 errors) ==== @@ -11,7 +11,7 @@ tests/cases/compiler/assignToExistingClass.ts(8,13): error TS2539: Cannot assign willThrowError() { Mocked = Mocked || function () { // => Error: Invalid left-hand side of assignment expression. ~~~~~~ -!!! error TS2539: Cannot assign to 'Mocked' because it is not a variable. +!!! error TS2629: Cannot assign to 'Mocked' because it is a class. return { myProp: "test" }; }; } diff --git a/tests/baselines/reference/assignmentCompatWithObjectMembersAccessibility.errors.txt b/tests/baselines/reference/assignmentCompatWithObjectMembersAccessibility.errors.txt index c1093ab0ffe87..6ca6b5e21e0ea 100644 --- a/tests/baselines/reference/assignmentCompatWithObjectMembersAccessibility.errors.txt +++ b/tests/baselines/reference/assignmentCompatWithObjectMembersAccessibility.errors.txt @@ -17,7 +17,6 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersAccessibility.ts(81,5): error TS2322: Type 'Base' is not assignable to type '{ foo: string; }'. Property 'foo' is private in type 'Base' but not in type '{ foo: string; }'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersAccessibility.ts(82,5): error TS2322: Type 'I' is not assignable to type '{ foo: string; }'. - Property 'foo' is private in type 'I' but not in type '{ foo: string; }'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersAccessibility.ts(84,5): error TS2322: Type 'E' is not assignable to type '{ foo: string; }'. Property 'foo' is private in type 'E' but not in type '{ foo: string; }'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersAccessibility.ts(86,5): error TS2322: Type '{ foo: string; }' is not assignable to type 'Base'. @@ -27,15 +26,11 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersAccessibility.ts(89,5): error TS2322: Type 'E' is not assignable to type 'Base'. Types have separate declarations of a private property 'foo'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersAccessibility.ts(92,5): error TS2322: Type '{ foo: string; }' is not assignable to type 'I'. - Property 'foo' is private in type 'I' but not in type '{ foo: string; }'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersAccessibility.ts(94,5): error TS2322: Type 'D' is not assignable to type 'I'. - Property 'foo' is private in type 'I' but not in type 'D'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersAccessibility.ts(95,5): error TS2322: Type 'E' is not assignable to type 'I'. - Types have separate declarations of a private property 'foo'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersAccessibility.ts(99,5): error TS2322: Type 'Base' is not assignable to type 'D'. Property 'foo' is private in type 'Base' but not in type 'D'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersAccessibility.ts(100,5): error TS2322: Type 'I' is not assignable to type 'D'. - Property 'foo' is private in type 'I' but not in type 'D'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersAccessibility.ts(101,5): error TS2322: Type 'E' is not assignable to type 'D'. Property 'foo' is private in type 'E' but not in type 'D'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersAccessibility.ts(103,5): error TS2322: Type '{ foo: string; }' is not assignable to type 'E'. @@ -43,7 +38,6 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersAccessibility.ts(104,5): error TS2322: Type 'Base' is not assignable to type 'E'. Types have separate declarations of a private property 'foo'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersAccessibility.ts(105,5): error TS2322: Type 'I' is not assignable to type 'E'. - Types have separate declarations of a private property 'foo'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersAccessibility.ts(106,5): error TS2322: Type 'D' is not assignable to type 'E'. Property 'foo' is private in type 'E' but not in type 'D'. @@ -160,7 +154,6 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme a = i; // error ~ !!! error TS2322: Type 'I' is not assignable to type '{ foo: string; }'. -!!! error TS2322: Property 'foo' is private in type 'I' but not in type '{ foo: string; }'. a = d; a = e; // error ~ @@ -185,16 +178,13 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme i = a; // error ~ !!! error TS2322: Type '{ foo: string; }' is not assignable to type 'I'. -!!! error TS2322: Property 'foo' is private in type 'I' but not in type '{ foo: string; }'. i = b; i = d; // error ~ !!! error TS2322: Type 'D' is not assignable to type 'I'. -!!! error TS2322: Property 'foo' is private in type 'I' but not in type 'D'. i = e; // error ~ !!! error TS2322: Type 'E' is not assignable to type 'I'. -!!! error TS2322: Types have separate declarations of a private property 'foo'. i = i; d = a; @@ -205,7 +195,6 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme d = i; // error ~ !!! error TS2322: Type 'I' is not assignable to type 'D'. -!!! error TS2322: Property 'foo' is private in type 'I' but not in type 'D'. d = e; // error ~ !!! error TS2322: Type 'E' is not assignable to type 'D'. @@ -222,7 +211,6 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme e = i; // errror ~ !!! error TS2322: Type 'I' is not assignable to type 'E'. -!!! error TS2322: Types have separate declarations of a private property 'foo'. e = d; // errror ~ !!! error TS2322: Type 'D' is not assignable to type 'E'. diff --git a/tests/baselines/reference/assignmentLHSIsValue.errors.txt b/tests/baselines/reference/assignmentLHSIsValue.errors.txt index 3064d713a122a..71809b4605f07 100644 --- a/tests/baselines/reference/assignmentLHSIsValue.errors.txt +++ b/tests/baselines/reference/assignmentLHSIsValue.errors.txt @@ -3,30 +3,31 @@ tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(7 tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(8,21): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(11,18): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(13,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(17,1): error TS2539: Cannot assign to 'M' because it is not a variable. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(19,1): error TS2539: Cannot assign to 'C' because it is not a variable. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(22,1): error TS2539: Cannot assign to 'E' because it is not a variable. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(24,1): error TS2539: Cannot assign to 'foo' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(17,1): error TS2631: Cannot assign to 'M' because it is a namespace. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(19,1): error TS2629: Cannot assign to 'C' because it is a class. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(22,1): error TS2628: Cannot assign to 'E' because it is an enum. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(24,1): error TS2630: Cannot assign to 'foo' because it is a function. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(27,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(28,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(29,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(30,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(31,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(32,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(35,9): error TS1128: Declaration or statement expected. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(35,9): error TS2809: Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(38,2): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(38,6): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(42,36): error TS1034: 'super' must be followed by an argument list or member access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(44,19): error TS1034: 'super' must be followed by an argument list or member access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(46,27): error TS1034: 'super' must be followed by an argument list or member access. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(50,20): error TS1128: Declaration or statement expected. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(51,11): error TS1005: ';' expected. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(50,20): error TS2809: Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(51,11): error TS2809: Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(51,13): error TS1005: ';' expected. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(54,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(57,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(58,2): error TS2539: Cannot assign to 'M' because it is not a variable. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(59,2): error TS2539: Cannot assign to 'C' because it is not a variable. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(60,2): error TS2539: Cannot assign to 'E' because it is not a variable. -tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(61,2): error TS2539: Cannot assign to 'foo' because it is not a variable. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(58,2): error TS2631: Cannot assign to 'M' because it is a namespace. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(59,2): error TS2629: Cannot assign to 'C' because it is a class. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(60,2): error TS2628: Cannot assign to 'E' because it is an enum. +tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(61,2): error TS2630: Cannot assign to 'foo' because it is a function. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(62,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(63,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(64,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. @@ -38,7 +39,7 @@ tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(6 tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(70,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -==== tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts (38 errors) ==== +==== tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts (39 errors) ==== // expected error for all the LHS of assignments var value: any; @@ -67,20 +68,20 @@ tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(7 module M { export var a; } M = value; ~ -!!! error TS2539: Cannot assign to 'M' because it is not a variable. +!!! error TS2631: Cannot assign to 'M' because it is a namespace. C = value; ~ -!!! error TS2539: Cannot assign to 'C' because it is not a variable. +!!! error TS2629: Cannot assign to 'C' because it is a class. enum E { } E = value; ~ -!!! error TS2539: Cannot assign to 'E' because it is not a variable. +!!! error TS2628: Cannot assign to 'E' because it is an enum. foo = value; ~~~ -!!! error TS2539: Cannot assign to 'foo' because it is not a variable. +!!! error TS2630: Cannot assign to 'foo' because it is a function. // literals null = value; @@ -105,7 +106,7 @@ tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(7 // object literals { a: 0} = value; ~ -!!! error TS1128: Declaration or statement expected. +!!! error TS2809: Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses. // array literals ['', ''] = value; @@ -132,9 +133,11 @@ tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(7 // function expression function bar() { } = value; ~ -!!! error TS1128: Declaration or statement expected. +!!! error TS2809: Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses. () => { } = value; ~ +!!! error TS2809: Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses. + ~~~~~ !!! error TS1005: ';' expected. // function calls @@ -148,16 +151,16 @@ tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts(7 !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (M) = value; ~ -!!! error TS2539: Cannot assign to 'M' because it is not a variable. +!!! error TS2631: Cannot assign to 'M' because it is a namespace. (C) = value; ~ -!!! error TS2539: Cannot assign to 'C' because it is not a variable. +!!! error TS2629: Cannot assign to 'C' because it is a class. (E) = value; ~ -!!! error TS2539: Cannot assign to 'E' because it is not a variable. +!!! error TS2628: Cannot assign to 'E' because it is an enum. (foo) = value; ~~~ -!!! error TS2539: Cannot assign to 'foo' because it is not a variable. +!!! error TS2630: Cannot assign to 'foo' because it is a function. (null) = value; ~~~~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. diff --git a/tests/baselines/reference/assignmentLHSIsValue.types b/tests/baselines/reference/assignmentLHSIsValue.types index 82dd7f026ad45..ad4905acc945c 100644 --- a/tests/baselines/reference/assignmentLHSIsValue.types +++ b/tests/baselines/reference/assignmentLHSIsValue.types @@ -146,7 +146,7 @@ function bar() { } = value; >value : any () => { } = value; ->() => { } : () => void +>() => { } = : () => void >value : any // function calls diff --git a/tests/baselines/reference/assignmentNonObjectTypeConstraints.types b/tests/baselines/reference/assignmentNonObjectTypeConstraints.types index 06af56203d4ca..fde1913876fb2 100644 --- a/tests/baselines/reference/assignmentNonObjectTypeConstraints.types +++ b/tests/baselines/reference/assignmentNonObjectTypeConstraints.types @@ -40,7 +40,7 @@ function bar(x: T) { var y: A | B = x; // Ok >y : A | B ->x : T +>x : A | B } bar(new A); diff --git a/tests/baselines/reference/assignmentToFunction.errors.txt b/tests/baselines/reference/assignmentToFunction.errors.txt index 6e9b1b3c6ddbe..f415d9c79c9c8 100644 --- a/tests/baselines/reference/assignmentToFunction.errors.txt +++ b/tests/baselines/reference/assignmentToFunction.errors.txt @@ -1,12 +1,12 @@ -tests/cases/compiler/assignmentToFunction.ts(2,1): error TS2539: Cannot assign to 'fn' because it is not a variable. -tests/cases/compiler/assignmentToFunction.ts(8,9): error TS2539: Cannot assign to 'bar' because it is not a variable. +tests/cases/compiler/assignmentToFunction.ts(2,1): error TS2630: Cannot assign to 'fn' because it is a function. +tests/cases/compiler/assignmentToFunction.ts(8,9): error TS2630: Cannot assign to 'bar' because it is a function. ==== tests/cases/compiler/assignmentToFunction.ts (2 errors) ==== function fn() { } fn = () => 3; ~~ -!!! error TS2539: Cannot assign to 'fn' because it is not a variable. +!!! error TS2630: Cannot assign to 'fn' because it is a function. module foo { function xyz() { @@ -14,6 +14,6 @@ tests/cases/compiler/assignmentToFunction.ts(8,9): error TS2539: Cannot assign t } bar = null; ~~~ -!!! error TS2539: Cannot assign to 'bar' because it is not a variable. +!!! error TS2630: Cannot assign to 'bar' because it is a function. } } \ No newline at end of file diff --git a/tests/baselines/reference/assignmentToParenthesizedIdentifiers.errors.txt b/tests/baselines/reference/assignmentToParenthesizedIdentifiers.errors.txt index 6a031ff6863be..51b15bee2aa10 100644 --- a/tests/baselines/reference/assignmentToParenthesizedIdentifiers.errors.txt +++ b/tests/baselines/reference/assignmentToParenthesizedIdentifiers.errors.txt @@ -3,14 +3,14 @@ tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesize tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(13,1): error TS2322: Type 'string' is not assignable to type 'number'. tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(14,1): error TS2322: Type 'string' is not assignable to type 'number'. tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(15,1): error TS2322: Type 'string' is not assignable to type 'number'. -tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(17,1): error TS2539: Cannot assign to 'M' because it is not a variable. -tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(18,2): error TS2539: Cannot assign to 'M' because it is not a variable. -tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(25,5): error TS2539: Cannot assign to 'M3' because it is not a variable. +tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(17,1): error TS2631: Cannot assign to 'M' because it is a namespace. +tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(18,2): error TS2631: Cannot assign to 'M' because it is a namespace. +tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(25,5): error TS2631: Cannot assign to 'M3' because it is a namespace. tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(31,11): error TS2322: Type 'string' is not assignable to type 'number'. tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(32,13): error TS2322: Type 'string' is not assignable to type 'number'. tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(33,13): error TS2322: Type 'string' is not assignable to type 'number'. -tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(37,1): error TS2539: Cannot assign to 'fn' because it is not a variable. -tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(38,2): error TS2539: Cannot assign to 'fn' because it is not a variable. +tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(37,1): error TS2630: Cannot assign to 'fn' because it is a function. +tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(38,2): error TS2630: Cannot assign to 'fn' because it is a function. tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(43,5): error TS2322: Type 'string' is not assignable to type 'number'. tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(44,5): error TS2322: Type 'string' is not assignable to type 'number'. tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(48,5): error TS2322: Type 'string' is not assignable to type 'number'. @@ -18,10 +18,10 @@ tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesize tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(54,5): error TS2322: Type 'string' is not assignable to type 'number'. tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(55,5): error TS2322: Type 'string' is not assignable to type 'number'. tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(56,5): error TS2322: Type 'string' is not assignable to type 'number'. -tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(62,1): error TS2539: Cannot assign to 'E' because it is not a variable. -tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(63,2): error TS2539: Cannot assign to 'E' because it is not a variable. -tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(69,1): error TS2539: Cannot assign to 'C' because it is not a variable. -tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(70,2): error TS2539: Cannot assign to 'C' because it is not a variable. +tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(62,1): error TS2628: Cannot assign to 'E' because it is an enum. +tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(63,2): error TS2628: Cannot assign to 'E' because it is an enum. +tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(69,1): error TS2629: Cannot assign to 'C' because it is a class. +tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts(70,2): error TS2629: Cannot assign to 'C' because it is a class. ==== tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesizedIdentifiers.ts (24 errors) ==== @@ -53,10 +53,10 @@ tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesize M = { y: 3 }; // Error ~ -!!! error TS2539: Cannot assign to 'M' because it is not a variable. +!!! error TS2631: Cannot assign to 'M' because it is a namespace. (M) = { y: 3 }; // Error ~ -!!! error TS2539: Cannot assign to 'M' because it is not a variable. +!!! error TS2631: Cannot assign to 'M' because it is a namespace. module M2 { export module M3 { @@ -65,7 +65,7 @@ tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesize M3 = { x: 3 }; // Error ~~ -!!! error TS2539: Cannot assign to 'M3' because it is not a variable. +!!! error TS2631: Cannot assign to 'M3' because it is a namespace. } M2.M3 = { x: 3 }; // OK (M2).M3 = { x: 3 }; // OK @@ -88,10 +88,10 @@ tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesize function fn() { } fn = () => 3; // Bug 823548: Should be error (fn is not a reference) ~~ -!!! error TS2539: Cannot assign to 'fn' because it is not a variable. +!!! error TS2630: Cannot assign to 'fn' because it is a function. (fn) = () => 3; // Should be error ~~ -!!! error TS2539: Cannot assign to 'fn' because it is not a variable. +!!! error TS2630: Cannot assign to 'fn' because it is a function. function fn2(x: number, y: { t: number }) { x = 3; @@ -131,10 +131,10 @@ tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesize } E = undefined; // Error ~ -!!! error TS2539: Cannot assign to 'E' because it is not a variable. +!!! error TS2628: Cannot assign to 'E' because it is an enum. (E) = undefined; // Error ~ -!!! error TS2539: Cannot assign to 'E' because it is not a variable. +!!! error TS2628: Cannot assign to 'E' because it is an enum. class C { @@ -142,8 +142,8 @@ tests/cases/conformance/expressions/valuesAndReferences/assignmentToParenthesize C = undefined; // Error ~ -!!! error TS2539: Cannot assign to 'C' because it is not a variable. +!!! error TS2629: Cannot assign to 'C' because it is a class. (C) = undefined; // Error ~ -!!! error TS2539: Cannot assign to 'C' because it is not a variable. +!!! error TS2629: Cannot assign to 'C' because it is a class. \ No newline at end of file diff --git a/tests/baselines/reference/assignmentToReferenceTypes.errors.txt b/tests/baselines/reference/assignmentToReferenceTypes.errors.txt index 5e42a2e79c657..e283ab6ec9fb6 100644 --- a/tests/baselines/reference/assignmentToReferenceTypes.errors.txt +++ b/tests/baselines/reference/assignmentToReferenceTypes.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/assignmentToReferenceTypes.ts(5,1): error TS2708: Cannot use namespace 'M' as a value. -tests/cases/compiler/assignmentToReferenceTypes.ts(9,1): error TS2539: Cannot assign to 'C' because it is not a variable. -tests/cases/compiler/assignmentToReferenceTypes.ts(13,1): error TS2539: Cannot assign to 'E' because it is not a variable. -tests/cases/compiler/assignmentToReferenceTypes.ts(16,1): error TS2539: Cannot assign to 'f' because it is not a variable. +tests/cases/compiler/assignmentToReferenceTypes.ts(9,1): error TS2629: Cannot assign to 'C' because it is a class. +tests/cases/compiler/assignmentToReferenceTypes.ts(13,1): error TS2628: Cannot assign to 'E' because it is an enum. +tests/cases/compiler/assignmentToReferenceTypes.ts(16,1): error TS2630: Cannot assign to 'f' because it is a function. ==== tests/cases/compiler/assignmentToReferenceTypes.ts (4 errors) ==== @@ -17,18 +17,18 @@ tests/cases/compiler/assignmentToReferenceTypes.ts(16,1): error TS2539: Cannot a } C = null; ~ -!!! error TS2539: Cannot assign to 'C' because it is not a variable. +!!! error TS2629: Cannot assign to 'C' because it is a class. enum E { } E = null; ~ -!!! error TS2539: Cannot assign to 'E' because it is not a variable. +!!! error TS2628: Cannot assign to 'E' because it is an enum. function f() { } f = null; ~ -!!! error TS2539: Cannot assign to 'f' because it is not a variable. +!!! error TS2630: Cannot assign to 'f' because it is a function. var x = 1; x = null; diff --git a/tests/baselines/reference/assignments.errors.txt b/tests/baselines/reference/assignments.errors.txt index 19cdbd813a615..4d06a2e31dc91 100644 --- a/tests/baselines/reference/assignments.errors.txt +++ b/tests/baselines/reference/assignments.errors.txt @@ -1,8 +1,8 @@ tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(11,1): error TS2708: Cannot use namespace 'M' as a value. -tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(14,1): error TS2539: Cannot assign to 'C' because it is not a variable. -tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(17,1): error TS2539: Cannot assign to 'E' because it is not a variable. +tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(14,1): error TS2629: Cannot assign to 'C' because it is a class. +tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(17,1): error TS2628: Cannot assign to 'E' because it is an enum. tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(18,3): error TS2540: Cannot assign to 'A' because it is a read-only property. -tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(21,1): error TS2539: Cannot assign to 'fn' because it is not a variable. +tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(21,1): error TS2630: Cannot assign to 'fn' because it is a function. tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(31,1): error TS2693: 'I' only refers to a type, but is being used as a value here. @@ -24,12 +24,12 @@ tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(31,1): er class C { } C = null; // Error ~ -!!! error TS2539: Cannot assign to 'C' because it is not a variable. +!!! error TS2629: Cannot assign to 'C' because it is a class. enum E { A } E = null; // Error ~ -!!! error TS2539: Cannot assign to 'E' because it is not a variable. +!!! error TS2628: Cannot assign to 'E' because it is an enum. E.A = null; // OK per spec, Error per implementation (509581) ~ !!! error TS2540: Cannot assign to 'A' because it is a read-only property. @@ -37,7 +37,7 @@ tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(31,1): er function fn() { } fn = null; // Should be error ~~ -!!! error TS2539: Cannot assign to 'fn' because it is not a variable. +!!! error TS2630: Cannot assign to 'fn' because it is a function. var v; v = null; // OK diff --git a/tests/baselines/reference/asyncFunctionNoReturnType.errors.txt b/tests/baselines/reference/asyncFunctionNoReturnType.errors.txt index 9155606c99fd8..e192b961fc807 100644 --- a/tests/baselines/reference/asyncFunctionNoReturnType.errors.txt +++ b/tests/baselines/reference/asyncFunctionNoReturnType.errors.txt @@ -1,12 +1,12 @@ error TS2468: Cannot find global value 'Promise'. -tests/cases/compiler/asyncFunctionNoReturnType.ts(1,1): error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option. +tests/cases/compiler/asyncFunctionNoReturnType.ts(1,1): error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option. !!! error TS2468: Cannot find global value 'Promise'. ==== tests/cases/compiler/asyncFunctionNoReturnType.ts (1 errors) ==== async () => { ~~~~~~~~~~~~~ -!!! error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option. +!!! error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option. if (window) return; } diff --git a/tests/baselines/reference/asyncFunctionReturnExpressionErrorSpans.errors.txt b/tests/baselines/reference/asyncFunctionReturnExpressionErrorSpans.errors.txt index ed65a0d367b6d..32e2309bc8e59 100644 --- a/tests/baselines/reference/asyncFunctionReturnExpressionErrorSpans.errors.txt +++ b/tests/baselines/reference/asyncFunctionReturnExpressionErrorSpans.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/asyncFunctionReturnExpressionErrorSpans.ts(11,28): error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option. +tests/cases/compiler/asyncFunctionReturnExpressionErrorSpans.ts(11,28): error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option. tests/cases/compiler/asyncFunctionReturnExpressionErrorSpans.ts(16,21): error TS2322: Type 'number' is not assignable to type 'string'. @@ -15,7 +15,7 @@ tests/cases/compiler/asyncFunctionReturnExpressionErrorSpans.ts(16,21): error TS async function asyncFoo(): Promise { ~~~~~~~~~~~~ -!!! error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option. +!!! error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option. return { bar: { baz: { diff --git a/tests/baselines/reference/awaitAndYieldInProperty.errors.txt b/tests/baselines/reference/awaitAndYieldInProperty.errors.txt index 2aec2af52788f..46a05266a4dc9 100644 --- a/tests/baselines/reference/awaitAndYieldInProperty.errors.txt +++ b/tests/baselines/reference/awaitAndYieldInProperty.errors.txt @@ -1,18 +1,18 @@ -tests/cases/conformance/classes/awaitAndYieldInProperty.ts(3,9): error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +tests/cases/conformance/classes/awaitAndYieldInProperty.ts(3,9): error TS1166: A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type. tests/cases/conformance/classes/awaitAndYieldInProperty.ts(3,21): error TS1308: 'await' expressions are only allowed within async functions and at the top levels of modules. -tests/cases/conformance/classes/awaitAndYieldInProperty.ts(4,16): error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +tests/cases/conformance/classes/awaitAndYieldInProperty.ts(4,16): error TS1166: A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type. tests/cases/conformance/classes/awaitAndYieldInProperty.ts(4,28): error TS1308: 'await' expressions are only allowed within async functions and at the top levels of modules. -tests/cases/conformance/classes/awaitAndYieldInProperty.ts(6,9): error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +tests/cases/conformance/classes/awaitAndYieldInProperty.ts(6,9): error TS1166: A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type. tests/cases/conformance/classes/awaitAndYieldInProperty.ts(6,21): error TS1163: A 'yield' expression is only allowed in a generator body. -tests/cases/conformance/classes/awaitAndYieldInProperty.ts(7,16): error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +tests/cases/conformance/classes/awaitAndYieldInProperty.ts(7,16): error TS1166: A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type. tests/cases/conformance/classes/awaitAndYieldInProperty.ts(7,28): error TS1163: A 'yield' expression is only allowed in a generator body. -tests/cases/conformance/classes/awaitAndYieldInProperty.ts(11,9): error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +tests/cases/conformance/classes/awaitAndYieldInProperty.ts(11,9): error TS1166: A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type. tests/cases/conformance/classes/awaitAndYieldInProperty.ts(11,21): error TS1308: 'await' expressions are only allowed within async functions and at the top levels of modules. -tests/cases/conformance/classes/awaitAndYieldInProperty.ts(12,16): error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +tests/cases/conformance/classes/awaitAndYieldInProperty.ts(12,16): error TS1166: A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type. tests/cases/conformance/classes/awaitAndYieldInProperty.ts(12,28): error TS1308: 'await' expressions are only allowed within async functions and at the top levels of modules. -tests/cases/conformance/classes/awaitAndYieldInProperty.ts(14,9): error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +tests/cases/conformance/classes/awaitAndYieldInProperty.ts(14,9): error TS1166: A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type. tests/cases/conformance/classes/awaitAndYieldInProperty.ts(14,21): error TS1163: A 'yield' expression is only allowed in a generator body. -tests/cases/conformance/classes/awaitAndYieldInProperty.ts(15,16): error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +tests/cases/conformance/classes/awaitAndYieldInProperty.ts(15,16): error TS1166: A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type. tests/cases/conformance/classes/awaitAndYieldInProperty.ts(15,28): error TS1163: A 'yield' expression is only allowed in a generator body. @@ -21,23 +21,23 @@ tests/cases/conformance/classes/awaitAndYieldInProperty.ts(15,28): error TS1163: class C { [await x] = await x; ~~~~~~~~~ -!!! error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +!!! error TS1166: A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type. ~~~~~ !!! error TS1308: 'await' expressions are only allowed within async functions and at the top levels of modules. static [await x] = await x; ~~~~~~~~~ -!!! error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +!!! error TS1166: A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type. ~~~~~ !!! error TS1308: 'await' expressions are only allowed within async functions and at the top levels of modules. [yield 1] = yield 2; ~~~~~~~~~ -!!! error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +!!! error TS1166: A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type. ~~~~~ !!! error TS1163: A 'yield' expression is only allowed in a generator body. static [yield 3] = yield 4; ~~~~~~~~~ -!!! error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +!!! error TS1166: A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type. ~~~~~ !!! error TS1163: A 'yield' expression is only allowed in a generator body. } @@ -45,23 +45,23 @@ tests/cases/conformance/classes/awaitAndYieldInProperty.ts(15,28): error TS1163: return class { [await x] = await x; ~~~~~~~~~ -!!! error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +!!! error TS1166: A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type. ~~~~~ !!! error TS1308: 'await' expressions are only allowed within async functions and at the top levels of modules. static [await x] = await x; ~~~~~~~~~ -!!! error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +!!! error TS1166: A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type. ~~~~~ !!! error TS1308: 'await' expressions are only allowed within async functions and at the top levels of modules. [yield 1] = yield 2; ~~~~~~~~~ -!!! error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +!!! error TS1166: A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type. ~~~~~ !!! error TS1163: A 'yield' expression is only allowed in a generator body. static [yield 3] = yield 4; ~~~~~~~~~ -!!! error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +!!! error TS1166: A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type. ~~~~~ !!! error TS1163: A 'yield' expression is only allowed in a generator body. } diff --git a/tests/baselines/reference/bigintWithoutLib.errors.txt b/tests/baselines/reference/bigintWithoutLib.errors.txt index 993607265ce62..c41d3fb44618c 100644 --- a/tests/baselines/reference/bigintWithoutLib.errors.txt +++ b/tests/baselines/reference/bigintWithoutLib.errors.txt @@ -1,16 +1,16 @@ -tests/cases/compiler/bigintWithoutLib.ts(4,25): error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. -tests/cases/compiler/bigintWithoutLib.ts(5,13): error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. -tests/cases/compiler/bigintWithoutLib.ts(6,5): error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. -tests/cases/compiler/bigintWithoutLib.ts(7,13): error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(4,25): error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(5,13): error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(6,5): error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(7,13): error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. tests/cases/compiler/bigintWithoutLib.ts(7,30): error TS2737: BigInt literals are not available when targeting lower than ES2020. -tests/cases/compiler/bigintWithoutLib.ts(8,13): error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(8,13): error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. tests/cases/compiler/bigintWithoutLib.ts(8,31): error TS2737: BigInt literals are not available when targeting lower than ES2020. tests/cases/compiler/bigintWithoutLib.ts(9,1): error TS2322: Type 'Object' is not assignable to type 'bigint'. tests/cases/compiler/bigintWithoutLib.ts(11,32): error TS2554: Expected 0 arguments, but got 1. tests/cases/compiler/bigintWithoutLib.ts(13,38): error TS2554: Expected 0 arguments, but got 1. tests/cases/compiler/bigintWithoutLib.ts(14,38): error TS2554: Expected 0 arguments, but got 2. tests/cases/compiler/bigintWithoutLib.ts(15,38): error TS2554: Expected 0 arguments, but got 2. -tests/cases/compiler/bigintWithoutLib.ts(18,18): error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(18,18): error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. tests/cases/compiler/bigintWithoutLib.ts(18,38): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? tests/cases/compiler/bigintWithoutLib.ts(19,19): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? tests/cases/compiler/bigintWithoutLib.ts(20,19): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? @@ -18,34 +18,34 @@ tests/cases/compiler/bigintWithoutLib.ts(20,34): error TS2737: BigInt literals a tests/cases/compiler/bigintWithoutLib.ts(20,38): error TS2737: BigInt literals are not available when targeting lower than ES2020. tests/cases/compiler/bigintWithoutLib.ts(20,42): error TS2737: BigInt literals are not available when targeting lower than ES2020. tests/cases/compiler/bigintWithoutLib.ts(21,19): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? -tests/cases/compiler/bigintWithoutLib.ts(22,19): error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. -tests/cases/compiler/bigintWithoutLib.ts(23,19): error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. -tests/cases/compiler/bigintWithoutLib.ts(24,19): error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. -tests/cases/compiler/bigintWithoutLib.ts(30,19): error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. -tests/cases/compiler/bigintWithoutLib.ts(30,40): error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. -tests/cases/compiler/bigintWithoutLib.ts(31,20): error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. -tests/cases/compiler/bigintWithoutLib.ts(32,20): error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(22,19): error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(23,19): error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(24,19): error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(30,19): error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(30,40): error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(31,20): error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(32,20): error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. tests/cases/compiler/bigintWithoutLib.ts(32,36): error TS2737: BigInt literals are not available when targeting lower than ES2020. tests/cases/compiler/bigintWithoutLib.ts(32,40): error TS2737: BigInt literals are not available when targeting lower than ES2020. tests/cases/compiler/bigintWithoutLib.ts(32,44): error TS2737: BigInt literals are not available when targeting lower than ES2020. -tests/cases/compiler/bigintWithoutLib.ts(33,20): error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. -tests/cases/compiler/bigintWithoutLib.ts(34,20): error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. -tests/cases/compiler/bigintWithoutLib.ts(35,20): error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. -tests/cases/compiler/bigintWithoutLib.ts(36,20): error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. -tests/cases/compiler/bigintWithoutLib.ts(43,10): error TS2550: Property 'setBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(33,20): error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(34,20): error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(35,20): error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(36,20): error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(43,10): error TS2550: Property 'setBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. tests/cases/compiler/bigintWithoutLib.ts(43,26): error TS2737: BigInt literals are not available when targeting lower than ES2020. -tests/cases/compiler/bigintWithoutLib.ts(44,10): error TS2550: Property 'setBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(44,10): error TS2550: Property 'setBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. tests/cases/compiler/bigintWithoutLib.ts(44,26): error TS2737: BigInt literals are not available when targeting lower than ES2020. -tests/cases/compiler/bigintWithoutLib.ts(45,10): error TS2550: Property 'setBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. -tests/cases/compiler/bigintWithoutLib.ts(46,10): error TS2550: Property 'setBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(45,10): error TS2550: Property 'setBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(46,10): error TS2550: Property 'setBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. tests/cases/compiler/bigintWithoutLib.ts(46,26): error TS2737: BigInt literals are not available when targeting lower than ES2020. -tests/cases/compiler/bigintWithoutLib.ts(47,10): error TS2550: Property 'setBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(47,10): error TS2550: Property 'setBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. tests/cases/compiler/bigintWithoutLib.ts(47,26): error TS2737: BigInt literals are not available when targeting lower than ES2020. -tests/cases/compiler/bigintWithoutLib.ts(48,10): error TS2550: Property 'setBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. -tests/cases/compiler/bigintWithoutLib.ts(49,22): error TS2550: Property 'getBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. -tests/cases/compiler/bigintWithoutLib.ts(50,22): error TS2550: Property 'getBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. -tests/cases/compiler/bigintWithoutLib.ts(51,22): error TS2550: Property 'getBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. -tests/cases/compiler/bigintWithoutLib.ts(52,22): error TS2550: Property 'getBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(48,10): error TS2550: Property 'setBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(49,22): error TS2550: Property 'getBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(50,22): error TS2550: Property 'getBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(51,22): error TS2550: Property 'getBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. +tests/cases/compiler/bigintWithoutLib.ts(52,22): error TS2550: Property 'getBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. tests/cases/compiler/bigintWithoutLib.ts(55,36): error TS2345: Argument of type 'bigint' is not assignable to parameter of type 'number'. tests/cases/compiler/bigintWithoutLib.ts(55,36): error TS2737: BigInt literals are not available when targeting lower than ES2020. tests/cases/compiler/bigintWithoutLib.ts(56,36): error TS2345: Argument of type 'bigint' is not assignable to parameter of type 'number'. @@ -57,21 +57,21 @@ tests/cases/compiler/bigintWithoutLib.ts(56,36): error TS2345: Argument of type // Test BigInt functions let bigintVal: bigint = BigInt(123); ~~~~~~ -!!! error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. bigintVal = BigInt("456"); ~~~~~~ -!!! error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. new BigInt(123); ~~~~~~ -!!! error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. bigintVal = BigInt.asIntN(8, 0xFFFFn); ~~~~~~ -!!! error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. ~~~~~~~ !!! error TS2737: BigInt literals are not available when targeting lower than ES2020. bigintVal = BigInt.asUintN(8, 0xFFFFn); ~~~~~~ -!!! error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2583: Cannot find name 'BigInt'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. ~~~~~~~ !!! error TS2737: BigInt literals are not available when targeting lower than ES2020. bigintVal = bigintVal.valueOf(); // should error - bigintVal inferred as {} @@ -95,7 +95,7 @@ tests/cases/compiler/bigintWithoutLib.ts(56,36): error TS2345: Argument of type // Test BigInt64Array let bigIntArray: BigInt64Array = new BigInt64Array(); ~~~~~~~~~~~~~ -!!! error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. ~~~~~~~~~~~~~ !!! error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? !!! related TS2728 tests/cases/compiler/bigintWithoutLib.ts:18:5: 'bigIntArray' is declared here. @@ -119,13 +119,13 @@ tests/cases/compiler/bigintWithoutLib.ts(56,36): error TS2345: Argument of type !!! related TS2728 tests/cases/compiler/bigintWithoutLib.ts:18:5: 'bigIntArray' is declared here. bigIntArray = new BigInt64Array(new ArrayBuffer(80)); ~~~~~~~~~~~~~ -!!! error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); ~~~~~~~~~~~~~ -!!! error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); ~~~~~~~~~~~~~ -!!! error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. let len: number = bigIntArray.length; bigIntArray.length = 10; let arrayBufferLike: ArrayBufferView = bigIntArray; @@ -133,15 +133,15 @@ tests/cases/compiler/bigintWithoutLib.ts(56,36): error TS2345: Argument of type // Test BigUint64Array let bigUintArray: BigUint64Array = new BigUint64Array(); ~~~~~~~~~~~~~~ -!!! error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. ~~~~~~~~~~~~~~ -!!! error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. bigUintArray = new BigUint64Array(10); ~~~~~~~~~~~~~~ -!!! error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. bigUintArray = new BigUint64Array([1n, 2n, 3n]); ~~~~~~~~~~~~~~ -!!! error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. ~~ !!! error TS2737: BigInt literals are not available when targeting lower than ES2020. ~~ @@ -150,16 +150,16 @@ tests/cases/compiler/bigintWithoutLib.ts(56,36): error TS2345: Argument of type !!! error TS2737: BigInt literals are not available when targeting lower than ES2020. bigUintArray = new BigUint64Array([1, 2, 3]); ~~~~~~~~~~~~~~ -!!! error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. bigUintArray = new BigUint64Array(new ArrayBuffer(80)); ~~~~~~~~~~~~~~ -!!! error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); ~~~~~~~~~~~~~~ -!!! error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); ~~~~~~~~~~~~~~ -!!! error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2583: Cannot find name 'BigUint64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. len = bigIntArray.length; bigIntArray.length = 10; arrayBufferLike = bigIntArray; @@ -168,42 +168,42 @@ tests/cases/compiler/bigintWithoutLib.ts(56,36): error TS2345: Argument of type const dataView = new DataView(new ArrayBuffer(80)); dataView.setBigInt64(1, -1n); ~~~~~~~~~~~ -!!! error TS2550: Property 'setBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2550: Property 'setBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. ~~ !!! error TS2737: BigInt literals are not available when targeting lower than ES2020. dataView.setBigInt64(1, -1n, true); ~~~~~~~~~~~ -!!! error TS2550: Property 'setBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2550: Property 'setBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. ~~ !!! error TS2737: BigInt literals are not available when targeting lower than ES2020. dataView.setBigInt64(1, -1); ~~~~~~~~~~~ -!!! error TS2550: Property 'setBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2550: Property 'setBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. dataView.setBigUint64(2, 123n); ~~~~~~~~~~~~ -!!! error TS2550: Property 'setBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2550: Property 'setBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. ~~~~ !!! error TS2737: BigInt literals are not available when targeting lower than ES2020. dataView.setBigUint64(2, 123n, true); ~~~~~~~~~~~~ -!!! error TS2550: Property 'setBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2550: Property 'setBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. ~~~~ !!! error TS2737: BigInt literals are not available when targeting lower than ES2020. dataView.setBigUint64(2, 123); ~~~~~~~~~~~~ -!!! error TS2550: Property 'setBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2550: Property 'setBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. bigintVal = dataView.getBigInt64(1); ~~~~~~~~~~~ -!!! error TS2550: Property 'getBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2550: Property 'getBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. bigintVal = dataView.getBigInt64(1, true); ~~~~~~~~~~~ -!!! error TS2550: Property 'getBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2550: Property 'getBigInt64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. bigintVal = dataView.getBigUint64(2); ~~~~~~~~~~~~ -!!! error TS2550: Property 'getBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2550: Property 'getBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. bigintVal = dataView.getBigUint64(2, true); ~~~~~~~~~~~~ -!!! error TS2550: Property 'getBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2020' or later. +!!! error TS2550: Property 'getBigUint64' does not exist on type 'DataView'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later. // Test Intl methods with new parameter type new Intl.NumberFormat("fr").format(3000n); diff --git a/tests/baselines/reference/callChain.types b/tests/baselines/reference/callChain.types index 1f1a4f1b7c918..ea4700aa9575d 100644 --- a/tests/baselines/reference/callChain.types +++ b/tests/baselines/reference/callChain.types @@ -260,7 +260,7 @@ declare const o5: () => undefined | (() => void); >o5 : () => undefined | (() => void) o5()?.(); ->o5()?.() : void +>o5()?.() : void | undefined >o5() : (() => void) | undefined >o5 : () => (() => void) | undefined diff --git a/tests/baselines/reference/callChainInference.types b/tests/baselines/reference/callChainInference.types index 3f19f66091e63..4ed4f5acf6e90 100644 --- a/tests/baselines/reference/callChainInference.types +++ b/tests/baselines/reference/callChainInference.types @@ -29,7 +29,7 @@ if (value) { } value?.foo("a"); ->value?.foo("a") : void +>value?.foo("a") : void | undefined >value?.foo : ((this: T, arg: keyof T) => void) | undefined >value : Y | undefined >foo : ((this: T, arg: keyof T) => void) | undefined diff --git a/tests/baselines/reference/callChainWithSuper(target=es2021).js b/tests/baselines/reference/callChainWithSuper(target=es2021).js new file mode 100644 index 0000000000000..30e1ad3886dc5 --- /dev/null +++ b/tests/baselines/reference/callChainWithSuper(target=es2021).js @@ -0,0 +1,18 @@ +//// [callChainWithSuper.ts] +// GH#34952 +class Base { method?() {} } +class Derived extends Base { + method1() { return super.method?.(); } + method2() { return super["method"]?.(); } +} + +//// [callChainWithSuper.js] +"use strict"; +// GH#34952 +class Base { + method() { } +} +class Derived extends Base { + method1() { return super.method?.(); } + method2() { return super["method"]?.(); } +} diff --git a/tests/baselines/reference/callOfConditionalTypeWithConcreteBranches.js b/tests/baselines/reference/callOfConditionalTypeWithConcreteBranches.js new file mode 100644 index 0000000000000..6110706773f66 --- /dev/null +++ b/tests/baselines/reference/callOfConditionalTypeWithConcreteBranches.js @@ -0,0 +1,62 @@ +//// [callOfConditionalTypeWithConcreteBranches.ts] +type Q = number extends T ? (n: number) => void : never; +function fn(arg: Q) { + // Expected: OK + // Actual: Cannot convert 10 to number & T + arg(10); +} +// Legal invocations are not problematic +fn(m => m.toFixed()); +fn(m => m.toFixed()); + +// Ensure the following real-world example that relies on substitution still works +type ExtractParameters = "parameters" extends keyof T + // The above allows "parameters" to index `T` since all later + // instances are actually implicitly `"parameters" & keyof T` + ? { + [K in keyof T["parameters"]]: T["parameters"][K]; + }[keyof T["parameters"]] + : {}; + +// Original example, but with inverted variance +type Q2 = number extends T ? (cb: (n: number) => void) => void : never; +function fn2(arg: Q2) { + function useT(_arg: T): void {} + // Expected: OK + arg(arg => useT(arg)); +} +// Legal invocations are not problematic +fn2(m => m(42)); +fn2(m => m(42)); + +// webidl-conversions example where substituion must occur, despite contravariance of the position +// due to the invariant usage in `Parameters` + +type X = V extends (...args: any[]) => any ? (...args: Parameters) => void : Function; + +// vscode - another `Parameters` example +export type AddFirstParameterToFunctions = { + [K in keyof Target]: Target[K] extends (...args: any[]) => void + ? (...args: Parameters) => void + : void +}; + +//// [callOfConditionalTypeWithConcreteBranches.js] +"use strict"; +exports.__esModule = true; +function fn(arg) { + // Expected: OK + // Actual: Cannot convert 10 to number & T + arg(10); +} +// Legal invocations are not problematic +fn(function (m) { return m.toFixed(); }); +fn(function (m) { return m.toFixed(); }); +function fn2(arg) { + function useT(_arg) { } + // Expected: OK + arg(function (arg) { return useT(arg); }); +} +// Legal invocations are not problematic +fn2(function (m) { return m(42); }); +fn2(function (m) { return m(42); }); diff --git a/tests/baselines/reference/callOfConditionalTypeWithConcreteBranches.symbols b/tests/baselines/reference/callOfConditionalTypeWithConcreteBranches.symbols new file mode 100644 index 0000000000000..c80fd32a03af1 --- /dev/null +++ b/tests/baselines/reference/callOfConditionalTypeWithConcreteBranches.symbols @@ -0,0 +1,125 @@ +=== tests/cases/compiler/callOfConditionalTypeWithConcreteBranches.ts === +type Q = number extends T ? (n: number) => void : never; +>Q : Symbol(Q, Decl(callOfConditionalTypeWithConcreteBranches.ts, 0, 0)) +>T : Symbol(T, Decl(callOfConditionalTypeWithConcreteBranches.ts, 0, 7)) +>T : Symbol(T, Decl(callOfConditionalTypeWithConcreteBranches.ts, 0, 7)) +>n : Symbol(n, Decl(callOfConditionalTypeWithConcreteBranches.ts, 0, 32)) + +function fn(arg: Q) { +>fn : Symbol(fn, Decl(callOfConditionalTypeWithConcreteBranches.ts, 0, 59)) +>T : Symbol(T, Decl(callOfConditionalTypeWithConcreteBranches.ts, 1, 12)) +>arg : Symbol(arg, Decl(callOfConditionalTypeWithConcreteBranches.ts, 1, 15)) +>Q : Symbol(Q, Decl(callOfConditionalTypeWithConcreteBranches.ts, 0, 0)) +>T : Symbol(T, Decl(callOfConditionalTypeWithConcreteBranches.ts, 1, 12)) + + // Expected: OK + // Actual: Cannot convert 10 to number & T + arg(10); +>arg : Symbol(arg, Decl(callOfConditionalTypeWithConcreteBranches.ts, 1, 15)) +} +// Legal invocations are not problematic +fn(m => m.toFixed()); +>fn : Symbol(fn, Decl(callOfConditionalTypeWithConcreteBranches.ts, 0, 59)) +>m : Symbol(m, Decl(callOfConditionalTypeWithConcreteBranches.ts, 7, 20)) +>m.toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) +>m : Symbol(m, Decl(callOfConditionalTypeWithConcreteBranches.ts, 7, 20)) +>toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) + +fn(m => m.toFixed()); +>fn : Symbol(fn, Decl(callOfConditionalTypeWithConcreteBranches.ts, 0, 59)) +>m : Symbol(m, Decl(callOfConditionalTypeWithConcreteBranches.ts, 8, 11)) +>m.toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) +>m : Symbol(m, Decl(callOfConditionalTypeWithConcreteBranches.ts, 8, 11)) +>toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) + +// Ensure the following real-world example that relies on substitution still works +type ExtractParameters = "parameters" extends keyof T +>ExtractParameters : Symbol(ExtractParameters, Decl(callOfConditionalTypeWithConcreteBranches.ts, 8, 29)) +>T : Symbol(T, Decl(callOfConditionalTypeWithConcreteBranches.ts, 11, 23)) +>T : Symbol(T, Decl(callOfConditionalTypeWithConcreteBranches.ts, 11, 23)) + + // The above allows "parameters" to index `T` since all later + // instances are actually implicitly `"parameters" & keyof T` + ? { + [K in keyof T["parameters"]]: T["parameters"][K]; +>K : Symbol(K, Decl(callOfConditionalTypeWithConcreteBranches.ts, 15, 9)) +>T : Symbol(T, Decl(callOfConditionalTypeWithConcreteBranches.ts, 11, 23)) +>T : Symbol(T, Decl(callOfConditionalTypeWithConcreteBranches.ts, 11, 23)) +>K : Symbol(K, Decl(callOfConditionalTypeWithConcreteBranches.ts, 15, 9)) + + }[keyof T["parameters"]] +>T : Symbol(T, Decl(callOfConditionalTypeWithConcreteBranches.ts, 11, 23)) + + : {}; + +// Original example, but with inverted variance +type Q2 = number extends T ? (cb: (n: number) => void) => void : never; +>Q2 : Symbol(Q2, Decl(callOfConditionalTypeWithConcreteBranches.ts, 17, 7)) +>T : Symbol(T, Decl(callOfConditionalTypeWithConcreteBranches.ts, 20, 8)) +>T : Symbol(T, Decl(callOfConditionalTypeWithConcreteBranches.ts, 20, 8)) +>cb : Symbol(cb, Decl(callOfConditionalTypeWithConcreteBranches.ts, 20, 33)) +>n : Symbol(n, Decl(callOfConditionalTypeWithConcreteBranches.ts, 20, 38)) + +function fn2(arg: Q2) { +>fn2 : Symbol(fn2, Decl(callOfConditionalTypeWithConcreteBranches.ts, 20, 74)) +>T : Symbol(T, Decl(callOfConditionalTypeWithConcreteBranches.ts, 21, 13)) +>arg : Symbol(arg, Decl(callOfConditionalTypeWithConcreteBranches.ts, 21, 16)) +>Q2 : Symbol(Q2, Decl(callOfConditionalTypeWithConcreteBranches.ts, 17, 7)) +>T : Symbol(T, Decl(callOfConditionalTypeWithConcreteBranches.ts, 21, 13)) + + function useT(_arg: T): void {} +>useT : Symbol(useT, Decl(callOfConditionalTypeWithConcreteBranches.ts, 21, 29)) +>_arg : Symbol(_arg, Decl(callOfConditionalTypeWithConcreteBranches.ts, 22, 16)) +>T : Symbol(T, Decl(callOfConditionalTypeWithConcreteBranches.ts, 21, 13)) + + // Expected: OK + arg(arg => useT(arg)); +>arg : Symbol(arg, Decl(callOfConditionalTypeWithConcreteBranches.ts, 21, 16)) +>arg : Symbol(arg, Decl(callOfConditionalTypeWithConcreteBranches.ts, 24, 6)) +>useT : Symbol(useT, Decl(callOfConditionalTypeWithConcreteBranches.ts, 21, 29)) +>arg : Symbol(arg, Decl(callOfConditionalTypeWithConcreteBranches.ts, 24, 6)) +} +// Legal invocations are not problematic +fn2(m => m(42)); +>fn2 : Symbol(fn2, Decl(callOfConditionalTypeWithConcreteBranches.ts, 20, 74)) +>m : Symbol(m, Decl(callOfConditionalTypeWithConcreteBranches.ts, 27, 21)) +>m : Symbol(m, Decl(callOfConditionalTypeWithConcreteBranches.ts, 27, 21)) + +fn2(m => m(42)); +>fn2 : Symbol(fn2, Decl(callOfConditionalTypeWithConcreteBranches.ts, 20, 74)) +>m : Symbol(m, Decl(callOfConditionalTypeWithConcreteBranches.ts, 28, 12)) +>m : Symbol(m, Decl(callOfConditionalTypeWithConcreteBranches.ts, 28, 12)) + +// webidl-conversions example where substituion must occur, despite contravariance of the position +// due to the invariant usage in `Parameters` + +type X = V extends (...args: any[]) => any ? (...args: Parameters) => void : Function; +>X : Symbol(X, Decl(callOfConditionalTypeWithConcreteBranches.ts, 28, 24)) +>V : Symbol(V, Decl(callOfConditionalTypeWithConcreteBranches.ts, 33, 7)) +>V : Symbol(V, Decl(callOfConditionalTypeWithConcreteBranches.ts, 33, 7)) +>args : Symbol(args, Decl(callOfConditionalTypeWithConcreteBranches.ts, 33, 23)) +>args : Symbol(args, Decl(callOfConditionalTypeWithConcreteBranches.ts, 33, 49)) +>Parameters : Symbol(Parameters, Decl(lib.es5.d.ts, --, --)) +>V : Symbol(V, Decl(callOfConditionalTypeWithConcreteBranches.ts, 33, 7)) +>Function : Symbol(Function, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +// vscode - another `Parameters` example +export type AddFirstParameterToFunctions = { +>AddFirstParameterToFunctions : Symbol(AddFirstParameterToFunctions, Decl(callOfConditionalTypeWithConcreteBranches.ts, 33, 92)) +>Target : Symbol(Target, Decl(callOfConditionalTypeWithConcreteBranches.ts, 36, 41)) + + [K in keyof Target]: Target[K] extends (...args: any[]) => void +>K : Symbol(K, Decl(callOfConditionalTypeWithConcreteBranches.ts, 37, 3)) +>Target : Symbol(Target, Decl(callOfConditionalTypeWithConcreteBranches.ts, 36, 41)) +>Target : Symbol(Target, Decl(callOfConditionalTypeWithConcreteBranches.ts, 36, 41)) +>K : Symbol(K, Decl(callOfConditionalTypeWithConcreteBranches.ts, 37, 3)) +>args : Symbol(args, Decl(callOfConditionalTypeWithConcreteBranches.ts, 37, 42)) + + ? (...args: Parameters) => void +>args : Symbol(args, Decl(callOfConditionalTypeWithConcreteBranches.ts, 38, 9)) +>Parameters : Symbol(Parameters, Decl(lib.es5.d.ts, --, --)) +>Target : Symbol(Target, Decl(callOfConditionalTypeWithConcreteBranches.ts, 36, 41)) +>K : Symbol(K, Decl(callOfConditionalTypeWithConcreteBranches.ts, 37, 3)) + + : void +}; diff --git a/tests/baselines/reference/callOfConditionalTypeWithConcreteBranches.types b/tests/baselines/reference/callOfConditionalTypeWithConcreteBranches.types new file mode 100644 index 0000000000000..412986f9e27e0 --- /dev/null +++ b/tests/baselines/reference/callOfConditionalTypeWithConcreteBranches.types @@ -0,0 +1,111 @@ +=== tests/cases/compiler/callOfConditionalTypeWithConcreteBranches.ts === +type Q = number extends T ? (n: number) => void : never; +>Q : Q +>n : number + +function fn(arg: Q) { +>fn : (arg: Q) => void +>arg : Q + + // Expected: OK + // Actual: Cannot convert 10 to number & T + arg(10); +>arg(10) : void +>arg : Q +>10 : 10 +} +// Legal invocations are not problematic +fn(m => m.toFixed()); +>fn(m => m.toFixed()) : void +>fn : (arg: Q) => void +>m => m.toFixed() : (m: number) => string +>m : number +>m.toFixed() : string +>m.toFixed : (fractionDigits?: number) => string +>m : number +>toFixed : (fractionDigits?: number) => string + +fn(m => m.toFixed()); +>fn(m => m.toFixed()) : void +>fn : (arg: Q) => void +>m => m.toFixed() : (m: number) => string +>m : number +>m.toFixed() : string +>m.toFixed : (fractionDigits?: number) => string +>m : number +>toFixed : (fractionDigits?: number) => string + +// Ensure the following real-world example that relies on substitution still works +type ExtractParameters = "parameters" extends keyof T +>ExtractParameters : ExtractParameters + + // The above allows "parameters" to index `T` since all later + // instances are actually implicitly `"parameters" & keyof T` + ? { + [K in keyof T["parameters"]]: T["parameters"][K]; + }[keyof T["parameters"]] + : {}; + +// Original example, but with inverted variance +type Q2 = number extends T ? (cb: (n: number) => void) => void : never; +>Q2 : Q2 +>cb : (n: number) => void +>n : number + +function fn2(arg: Q2) { +>fn2 : (arg: Q2) => void +>arg : Q2 + + function useT(_arg: T): void {} +>useT : (_arg: T) => void +>_arg : T + + // Expected: OK + arg(arg => useT(arg)); +>arg(arg => useT(arg)) : void +>arg : Q2 +>arg => useT(arg) : (arg: T & number) => void +>arg : T & number +>useT(arg) : void +>useT : (_arg: T) => void +>arg : T & number +} +// Legal invocations are not problematic +fn2(m => m(42)); +>fn2(m => m(42)) : void +>fn2 : (arg: Q2) => void +>m => m(42) : (m: (n: number) => void) => void +>m : (n: number) => void +>m(42) : void +>m : (n: number) => void +>42 : 42 + +fn2(m => m(42)); +>fn2(m => m(42)) : void +>fn2 : (arg: Q2) => void +>m => m(42) : (m: (n: number) => void) => void +>m : (n: number) => void +>m(42) : void +>m : (n: number) => void +>42 : 42 + +// webidl-conversions example where substituion must occur, despite contravariance of the position +// due to the invariant usage in `Parameters` + +type X = V extends (...args: any[]) => any ? (...args: Parameters) => void : Function; +>X : X +>args : any[] +>args : Parameters + +// vscode - another `Parameters` example +export type AddFirstParameterToFunctions = { +>AddFirstParameterToFunctions : AddFirstParameterToFunctions + + [K in keyof Target]: Target[K] extends (...args: any[]) => void +>args : any[] + + ? (...args: Parameters) => void +>args : Parameters + + : void +}; diff --git a/tests/baselines/reference/callOverload.errors.txt b/tests/baselines/reference/callOverload.errors.txt index 0f6a2ade085a0..c5b171aca492f 100644 --- a/tests/baselines/reference/callOverload.errors.txt +++ b/tests/baselines/reference/callOverload.errors.txt @@ -1,7 +1,7 @@ tests/cases/conformance/expressions/functionCalls/callOverload.ts(7,7): error TS2554: Expected 1 arguments, but got 4. tests/cases/conformance/expressions/functionCalls/callOverload.ts(8,15): error TS2554: Expected 2 arguments, but got 4. tests/cases/conformance/expressions/functionCalls/callOverload.ts(10,1): error TS2555: Expected at least 1 arguments, but got 0. -tests/cases/conformance/expressions/functionCalls/callOverload.ts(11,10): error TS2557: Expected at least 1 arguments, but got 0 or more. +tests/cases/conformance/expressions/functionCalls/callOverload.ts(11,10): error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. ==== tests/cases/conformance/expressions/functionCalls/callOverload.ts (4 errors) ==== @@ -24,5 +24,4 @@ tests/cases/conformance/expressions/functionCalls/callOverload.ts(11,10): error !!! related TS6210 tests/cases/conformance/expressions/functionCalls/callOverload.ts:3:27: An argument for 'a' was not provided. withRest(...n); ~~~~ -!!! error TS2557: Expected at least 1 arguments, but got 0 or more. -!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callOverload.ts:3:27: An argument for 'a' was not provided. \ No newline at end of file +!!! error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. \ No newline at end of file diff --git a/tests/baselines/reference/callSignatureAssignabilityInInheritance6.errors.txt b/tests/baselines/reference/callSignatureAssignabilityInInheritance6.errors.txt index 580529f6afa26..38e69a84cb80b 100644 --- a/tests/baselines/reference/callSignatureAssignabilityInInheritance6.errors.txt +++ b/tests/baselines/reference/callSignatureAssignabilityInInheritance6.errors.txt @@ -45,8 +45,6 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/callSign Types of property 'a' are incompatible. Type 'T' is not assignable to type 'T'. Two different types with this name exist, but they are unrelated. 'T' could be instantiated with an arbitrary type which could be unrelated to 'T'. - Type 'Base' is not assignable to type 'T'. - 'T' could be instantiated with an arbitrary type which could be unrelated to 'Base'. ==== tests/cases/conformance/types/typeRelationships/assignmentCompatibility/callSignatureAssignabilityInInheritance6.ts (7 errors) ==== @@ -152,7 +150,5 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/callSign !!! error TS2430: Types of property 'a' are incompatible. !!! error TS2430: Type 'T' is not assignable to type 'T'. Two different types with this name exist, but they are unrelated. !!! error TS2430: 'T' could be instantiated with an arbitrary type which could be unrelated to 'T'. -!!! error TS2430: Type 'Base' is not assignable to type 'T'. -!!! error TS2430: 'T' could be instantiated with an arbitrary type which could be unrelated to 'Base'. a16: (x: { a: T; b: T }) => T[]; } \ No newline at end of file diff --git a/tests/baselines/reference/callWithSpread2.errors.txt b/tests/baselines/reference/callWithSpread2.errors.txt index 080c229e6042e..0361c2aef336d 100644 --- a/tests/baselines/reference/callWithSpread2.errors.txt +++ b/tests/baselines/reference/callWithSpread2.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(23,13): error TS2556: Expected 1 arguments, but got 2 or more. -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(24,7): error TS2556: Expected 0 arguments, but got 1 or more. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(23,13): error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(24,7): error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(27,5): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. Type 'string' is not assignable to type 'number'. tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(28,5): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. @@ -9,10 +9,10 @@ tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(30,13): err tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(31,11): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. Type 'string' is not assignable to type 'number'. tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(32,11): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(33,8): error TS2556: Expected 1-3 arguments, but got 0 or more. -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(34,8): error TS2556: Expected 1-3 arguments, but got 0 or more. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(33,8): error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(34,8): error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(35,8): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. -tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(36,14): error TS2556: Expected 2-4 arguments, but got 1 or more. +tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(36,14): error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. ==== tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts (12 errors) ==== @@ -40,10 +40,10 @@ tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(36,14): err // extra arguments normal("g", ...ns) ~~~~~ -!!! error TS2556: Expected 1 arguments, but got 2 or more. +!!! error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. thunk(...ns) ~~~~~ -!!! error TS2556: Expected 0 arguments, but got 1 or more. +!!! error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. // bad all(...mixed) @@ -69,17 +69,14 @@ tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(36,14): err !!! error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. 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. +!!! error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. 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. +!!! error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. prefix(...tuple) ~~~~~~~~ !!! error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. prefix2("g", ...ns); ~~~~~ -!!! error TS2556: Expected 2-4 arguments, but got 1 or more. -!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts:7:37: An argument for 'n' was not provided. +!!! error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. \ No newline at end of file diff --git a/tests/baselines/reference/callWithSpread3.errors.txt b/tests/baselines/reference/callWithSpread3.errors.txt index 062c273a26a9c..34e0112003ee7 100644 --- a/tests/baselines/reference/callWithSpread3.errors.txt +++ b/tests/baselines/reference/callWithSpread3.errors.txt @@ -4,12 +4,12 @@ tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts(16,15): err tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts(17,15): error TS2554: Expected 2 arguments, but got 6. tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts(18,12): error TS2554: Expected 2 arguments, but got 3. tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts(19,5): error TS2554: Expected 2 arguments, but got 3. -tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts(20,6): error TS2557: Expected at least 2 arguments, but got 0 or more. +tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts(20,6): error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts(21,6): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. -tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts(22,13): error TS2557: Expected at least 2 arguments, but got 1 or more. -tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts(23,13): error TS2557: Expected at least 2 arguments, but got 2 or more. +tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts(22,6): error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. +tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts(23,6): error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts(25,7): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. -tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts(31,13): error TS2557: Expected at least 2 arguments, but got 4 or more. +tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts(31,6): error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. ==== tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts (12 errors) ==== @@ -46,18 +46,16 @@ tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts(31,13): err !!! error TS2554: Expected 2 arguments, but got 3. fs2_(...s_); // error on ...s_ ~~~~~ -!!! error TS2557: Expected at least 2 arguments, but got 0 or more. -!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts:9:23: An argument for 'a' was not provided. +!!! error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. fs2_(...s2n_); // error on ...s2n_ ~~~~~~~ !!! error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. - fs2_(...s_, ...s_); // error FIXME: bad error message - ~~~~~ -!!! error TS2557: Expected at least 2 arguments, but got 1 or more. -!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts:9:34: An argument for 'b' was not provided. - fs2_(...s_, ...s_, ...s_); // error FIXME: worse error message - ~~~~~~~~~~~~ -!!! error TS2557: Expected at least 2 arguments, but got 2 or more. + fs2_(...s_, ...s_); // error on ...s_ + ~~~~~ +!!! error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. + fs2_(...s_, ...s_, ...s_); // error on ...s_ + ~~~~~ +!!! error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. // fs2n_(...s2, ...s_); // FIXME: should be a type error fs2n_(...s2_); // error on ...s2_ ~~~~~~ @@ -68,8 +66,8 @@ tests/cases/conformance/expressions/functionCalls/callWithSpread3.ts(31,13): err fs2_(...s2_, ...s_); fs2_(...s2_, ...s2_); fs2_(...s_, ...s2_); - ~~~~~~ -!!! error TS2557: Expected at least 2 arguments, but got 4 or more. + ~~~~~ +!!! error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. fs2n_(...s2n_); fs2n_(...s2); // fs2n_(...s2, ...n_); // FIXME: should compile diff --git a/tests/baselines/reference/callWithSpread3.js b/tests/baselines/reference/callWithSpread3.js index f94e74b1dd434..fbd11df511ee2 100644 --- a/tests/baselines/reference/callWithSpread3.js +++ b/tests/baselines/reference/callWithSpread3.js @@ -20,8 +20,8 @@ fs2(...s2, 'a'); // error on 'a' fs2(...s3); // error on ...s3 fs2_(...s_); // error on ...s_ fs2_(...s2n_); // error on ...s2n_ -fs2_(...s_, ...s_); // error FIXME: bad error message -fs2_(...s_, ...s_, ...s_); // error FIXME: worse error message +fs2_(...s_, ...s_); // error on ...s_ +fs2_(...s_, ...s_, ...s_); // error on ...s_ // fs2n_(...s2, ...s_); // FIXME: should be a type error fs2n_(...s2_); // error on ...s2_ @@ -51,8 +51,8 @@ fs2.apply(void 0, __spreadArray(__spreadArray([], s2), ['a'])); // error on 'a' fs2.apply(void 0, s3); // error on ...s3 fs2_.apply(void 0, s_); // error on ...s_ fs2_.apply(void 0, s2n_); // error on ...s2n_ -fs2_.apply(void 0, __spreadArray(__spreadArray([], s_), s_)); // error FIXME: bad error message -fs2_.apply(void 0, __spreadArray(__spreadArray(__spreadArray([], s_), s_), s_)); // error FIXME: worse error message +fs2_.apply(void 0, __spreadArray(__spreadArray([], s_), s_)); // error on ...s_ +fs2_.apply(void 0, __spreadArray(__spreadArray(__spreadArray([], s_), s_), s_)); // error on ...s_ // fs2n_(...s2, ...s_); // FIXME: should be a type error fs2n_.apply(void 0, s2_); // error on ...s2_ // ok diff --git a/tests/baselines/reference/callWithSpread3.symbols b/tests/baselines/reference/callWithSpread3.symbols index e305b1d03ed6d..076c10a178d31 100644 --- a/tests/baselines/reference/callWithSpread3.symbols +++ b/tests/baselines/reference/callWithSpread3.symbols @@ -75,12 +75,12 @@ fs2_(...s2n_); // error on ...s2n_ >fs2_ : Symbol(fs2_, Decl(callWithSpread3.ts, 7, 49)) >s2n_ : Symbol(s2n_, Decl(callWithSpread3.ts, 5, 13)) -fs2_(...s_, ...s_); // error FIXME: bad error message +fs2_(...s_, ...s_); // error on ...s_ >fs2_ : Symbol(fs2_, Decl(callWithSpread3.ts, 7, 49)) >s_ : Symbol(s_, Decl(callWithSpread3.ts, 3, 13)) >s_ : Symbol(s_, Decl(callWithSpread3.ts, 3, 13)) -fs2_(...s_, ...s_, ...s_); // error FIXME: worse error message +fs2_(...s_, ...s_, ...s_); // error on ...s_ >fs2_ : Symbol(fs2_, Decl(callWithSpread3.ts, 7, 49)) >s_ : Symbol(s_, Decl(callWithSpread3.ts, 3, 13)) >s_ : Symbol(s_, Decl(callWithSpread3.ts, 3, 13)) diff --git a/tests/baselines/reference/callWithSpread3.types b/tests/baselines/reference/callWithSpread3.types index dc7c7b4378772..3ddc98c66c824 100644 --- a/tests/baselines/reference/callWithSpread3.types +++ b/tests/baselines/reference/callWithSpread3.types @@ -103,7 +103,7 @@ fs2_(...s2n_); // error on ...s2n_ >...s2n_ : string | number >s2n_ : [string, string, ...number[]] -fs2_(...s_, ...s_); // error FIXME: bad error message +fs2_(...s_, ...s_); // error on ...s_ >fs2_(...s_, ...s_) : void >fs2_ : (a: string, b: string, ...c: string[]) => void >...s_ : string @@ -111,7 +111,7 @@ fs2_(...s_, ...s_); // error FIXME: bad error message >...s_ : string >s_ : string[] -fs2_(...s_, ...s_, ...s_); // error FIXME: worse error message +fs2_(...s_, ...s_, ...s_); // error on ...s_ >fs2_(...s_, ...s_, ...s_) : void >fs2_ : (a: string, b: string, ...c: string[]) => void >...s_ : string diff --git a/tests/baselines/reference/callWithSpread4.errors.txt b/tests/baselines/reference/callWithSpread4.errors.txt new file mode 100644 index 0000000000000..d4d67faf14a23 --- /dev/null +++ b/tests/baselines/reference/callWithSpread4.errors.txt @@ -0,0 +1,39 @@ +tests/cases/conformance/expressions/functionCalls/callWithSpread4.ts(18,5): error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. +tests/cases/conformance/expressions/functionCalls/callWithSpread4.ts(27,6): error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. + + +==== tests/cases/conformance/expressions/functionCalls/callWithSpread4.ts (2 errors) ==== + type R = { a: number } + type W = { b: number } + type RW = { a: number, b: number } + declare const pli: { + (s1: R, s2: RW, s3: RW, s4: RW, s5: W): Promise; + (streams: ReadonlyArray): Promise; + (s1: R, s2: RW | W, ...streams: Array): Promise; + } + + declare var writes: W + declare var reads: R + declare var tr: W + declare var gun: RW[] + declare var gz: RW[] + declare var fun: (inp: any) => AsyncGenerator + pli( + reads, + ...gun, + ~~~~~~ +!!! error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. + tr, + fun, + ...gz, + writes + ); + + declare function test(x: any, y: () => string): string | undefined; + declare var anys: any[] + test(...anys) + ~~~~~~~ +!!! error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. + + pli(...[reads, writes, writes] as const) + \ No newline at end of file diff --git a/tests/baselines/reference/callWithSpread4.js b/tests/baselines/reference/callWithSpread4.js new file mode 100644 index 0000000000000..0db1129c0bb11 --- /dev/null +++ b/tests/baselines/reference/callWithSpread4.js @@ -0,0 +1,37 @@ +//// [callWithSpread4.ts] +type R = { a: number } +type W = { b: number } +type RW = { a: number, b: number } +declare const pli: { + (s1: R, s2: RW, s3: RW, s4: RW, s5: W): Promise; + (streams: ReadonlyArray): Promise; + (s1: R, s2: RW | W, ...streams: Array): Promise; +} + +declare var writes: W +declare var reads: R +declare var tr: W +declare var gun: RW[] +declare var gz: RW[] +declare var fun: (inp: any) => AsyncGenerator +pli( + reads, + ...gun, + tr, + fun, + ...gz, + writes +); + +declare function test(x: any, y: () => string): string | undefined; +declare var anys: any[] +test(...anys) + +pli(...[reads, writes, writes] as const) + + +//// [callWithSpread4.js] +"use strict"; +pli(reads, ...gun, tr, fun, ...gz, writes); +test(...anys); +pli(...[reads, writes, writes]); diff --git a/tests/baselines/reference/callWithSpread4.symbols b/tests/baselines/reference/callWithSpread4.symbols new file mode 100644 index 0000000000000..5c3e96596ef60 --- /dev/null +++ b/tests/baselines/reference/callWithSpread4.symbols @@ -0,0 +1,117 @@ +=== tests/cases/conformance/expressions/functionCalls/callWithSpread4.ts === +type R = { a: number } +>R : Symbol(R, Decl(callWithSpread4.ts, 0, 0)) +>a : Symbol(a, Decl(callWithSpread4.ts, 0, 10)) + +type W = { b: number } +>W : Symbol(W, Decl(callWithSpread4.ts, 0, 22)) +>b : Symbol(b, Decl(callWithSpread4.ts, 1, 10)) + +type RW = { a: number, b: number } +>RW : Symbol(RW, Decl(callWithSpread4.ts, 1, 22)) +>a : Symbol(a, Decl(callWithSpread4.ts, 2, 11)) +>b : Symbol(b, Decl(callWithSpread4.ts, 2, 22)) + +declare const pli: { +>pli : Symbol(pli, Decl(callWithSpread4.ts, 3, 13)) + + (s1: R, s2: RW, s3: RW, s4: RW, s5: W): Promise; +>s1 : Symbol(s1, Decl(callWithSpread4.ts, 4, 5)) +>R : Symbol(R, Decl(callWithSpread4.ts, 0, 0)) +>s2 : Symbol(s2, Decl(callWithSpread4.ts, 4, 11)) +>RW : Symbol(RW, Decl(callWithSpread4.ts, 1, 22)) +>s3 : Symbol(s3, Decl(callWithSpread4.ts, 4, 19)) +>RW : Symbol(RW, Decl(callWithSpread4.ts, 1, 22)) +>s4 : Symbol(s4, Decl(callWithSpread4.ts, 4, 27)) +>RW : Symbol(RW, Decl(callWithSpread4.ts, 1, 22)) +>s5 : Symbol(s5, Decl(callWithSpread4.ts, 4, 35)) +>W : Symbol(W, Decl(callWithSpread4.ts, 0, 22)) +>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, --, --)) + + (streams: ReadonlyArray): Promise; +>streams : Symbol(streams, Decl(callWithSpread4.ts, 5, 5)) +>ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2016.array.include.d.ts, --, --), Decl(lib.es2019.array.d.ts, --, --)) +>R : Symbol(R, Decl(callWithSpread4.ts, 0, 0)) +>W : Symbol(W, Decl(callWithSpread4.ts, 0, 22)) +>RW : Symbol(RW, Decl(callWithSpread4.ts, 1, 22)) +>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, --, --)) + + (s1: R, s2: RW | W, ...streams: Array): Promise; +>s1 : Symbol(s1, Decl(callWithSpread4.ts, 6, 5)) +>R : Symbol(R, Decl(callWithSpread4.ts, 0, 0)) +>s2 : Symbol(s2, Decl(callWithSpread4.ts, 6, 11)) +>RW : Symbol(RW, Decl(callWithSpread4.ts, 1, 22)) +>W : Symbol(W, Decl(callWithSpread4.ts, 0, 22)) +>streams : Symbol(streams, Decl(callWithSpread4.ts, 6, 23)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --) ... and 2 more) +>RW : Symbol(RW, Decl(callWithSpread4.ts, 1, 22)) +>W : Symbol(W, Decl(callWithSpread4.ts, 0, 22)) +>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, --, --)) +} + +declare var writes: W +>writes : Symbol(writes, Decl(callWithSpread4.ts, 9, 11)) +>W : Symbol(W, Decl(callWithSpread4.ts, 0, 22)) + +declare var reads: R +>reads : Symbol(reads, Decl(callWithSpread4.ts, 10, 11)) +>R : Symbol(R, Decl(callWithSpread4.ts, 0, 0)) + +declare var tr: W +>tr : Symbol(tr, Decl(callWithSpread4.ts, 11, 11)) +>W : Symbol(W, Decl(callWithSpread4.ts, 0, 22)) + +declare var gun: RW[] +>gun : Symbol(gun, Decl(callWithSpread4.ts, 12, 11)) +>RW : Symbol(RW, Decl(callWithSpread4.ts, 1, 22)) + +declare var gz: RW[] +>gz : Symbol(gz, Decl(callWithSpread4.ts, 13, 11)) +>RW : Symbol(RW, Decl(callWithSpread4.ts, 1, 22)) + +declare var fun: (inp: any) => AsyncGenerator +>fun : Symbol(fun, Decl(callWithSpread4.ts, 14, 11)) +>inp : Symbol(inp, Decl(callWithSpread4.ts, 14, 18)) +>AsyncGenerator : Symbol(AsyncGenerator, Decl(lib.es2018.asyncgenerator.d.ts, --, --)) + +pli( +>pli : Symbol(pli, Decl(callWithSpread4.ts, 3, 13)) + + reads, +>reads : Symbol(reads, Decl(callWithSpread4.ts, 10, 11)) + + ...gun, +>gun : Symbol(gun, Decl(callWithSpread4.ts, 12, 11)) + + tr, +>tr : Symbol(tr, Decl(callWithSpread4.ts, 11, 11)) + + fun, +>fun : Symbol(fun, Decl(callWithSpread4.ts, 14, 11)) + + ...gz, +>gz : Symbol(gz, Decl(callWithSpread4.ts, 13, 11)) + + writes +>writes : Symbol(writes, Decl(callWithSpread4.ts, 9, 11)) + +); + +declare function test(x: any, y: () => string): string | undefined; +>test : Symbol(test, Decl(callWithSpread4.ts, 22, 2)) +>x : Symbol(x, Decl(callWithSpread4.ts, 24, 22)) +>y : Symbol(y, Decl(callWithSpread4.ts, 24, 29)) + +declare var anys: any[] +>anys : Symbol(anys, Decl(callWithSpread4.ts, 25, 11)) + +test(...anys) +>test : Symbol(test, Decl(callWithSpread4.ts, 22, 2)) +>anys : Symbol(anys, Decl(callWithSpread4.ts, 25, 11)) + +pli(...[reads, writes, writes] as const) +>pli : Symbol(pli, Decl(callWithSpread4.ts, 3, 13)) +>reads : Symbol(reads, Decl(callWithSpread4.ts, 10, 11)) +>writes : Symbol(writes, Decl(callWithSpread4.ts, 9, 11)) +>writes : Symbol(writes, Decl(callWithSpread4.ts, 9, 11)) + diff --git a/tests/baselines/reference/callWithSpread4.types b/tests/baselines/reference/callWithSpread4.types new file mode 100644 index 0000000000000..5caef4eb70173 --- /dev/null +++ b/tests/baselines/reference/callWithSpread4.types @@ -0,0 +1,102 @@ +=== tests/cases/conformance/expressions/functionCalls/callWithSpread4.ts === +type R = { a: number } +>R : R +>a : number + +type W = { b: number } +>W : W +>b : number + +type RW = { a: number, b: number } +>RW : RW +>a : number +>b : number + +declare const pli: { +>pli : { (s1: R, s2: RW, s3: RW, s4: RW, s5: W): Promise; (streams: ReadonlyArray): Promise; (s1: R, s2: RW | W, ...streams: Array): Promise; } + + (s1: R, s2: RW, s3: RW, s4: RW, s5: W): Promise; +>s1 : R +>s2 : RW +>s3 : RW +>s4 : RW +>s5 : W + + (streams: ReadonlyArray): Promise; +>streams : readonly (R | W | RW)[] + + (s1: R, s2: RW | W, ...streams: Array): Promise; +>s1 : R +>s2 : W | RW +>streams : (W | RW)[] +} + +declare var writes: W +>writes : W + +declare var reads: R +>reads : R + +declare var tr: W +>tr : W + +declare var gun: RW[] +>gun : RW[] + +declare var gz: RW[] +>gz : RW[] + +declare var fun: (inp: any) => AsyncGenerator +>fun : (inp: any) => AsyncGenerator +>inp : any + +pli( +>pli( reads, ...gun, tr, fun, ...gz, writes) : Promise +>pli : { (s1: R, s2: RW, s3: RW, s4: RW, s5: W): Promise; (streams: readonly (R | W | RW)[]): Promise; (s1: R, s2: W | RW, ...streams: (W | RW)[]): Promise; } + + reads, +>reads : R + + ...gun, +>...gun : RW +>gun : RW[] + + tr, +>tr : W + + fun, +>fun : (inp: any) => AsyncGenerator + + ...gz, +>...gz : RW +>gz : RW[] + + writes +>writes : W + +); + +declare function test(x: any, y: () => string): string | undefined; +>test : (x: any, y: () => string) => string | undefined +>x : any +>y : () => string + +declare var anys: any[] +>anys : any[] + +test(...anys) +>test(...anys) : string | undefined +>test : (x: any, y: () => string) => string | undefined +>...anys : any +>anys : any[] + +pli(...[reads, writes, writes] as const) +>pli(...[reads, writes, writes] as const) : Promise +>pli : { (s1: R, s2: RW, s3: RW, s4: RW, s5: W): Promise; (streams: readonly (R | W | RW)[]): Promise; (s1: R, s2: W | RW, ...streams: (W | RW)[]): Promise; } +>...[reads, writes, writes] as const : R | W +>[reads, writes, writes] as const : readonly [R, W, W] +>[reads, writes, writes] : readonly [R, W, W] +>reads : R +>writes : W +>writes : W + diff --git a/tests/baselines/reference/callWithSpread5.errors.txt b/tests/baselines/reference/callWithSpread5.errors.txt new file mode 100644 index 0000000000000..28640ea5a3c99 --- /dev/null +++ b/tests/baselines/reference/callWithSpread5.errors.txt @@ -0,0 +1,14 @@ +tests/cases/conformance/expressions/functionCalls/callWithSpread5.ts(7,4): error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. + + +==== tests/cases/conformance/expressions/functionCalls/callWithSpread5.ts (1 errors) ==== + declare const x: number + declare const nnnu: [number, number, number?] + declare const nntnnnt: [number, number] | [number, number, number] + declare function fn(a: number, b: number, bb: number, ...c: number[]): number + + fn(...nnnu, x) + fn(...nntnnnt, x) + ~~~~~~~~~~ +!!! error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. + \ No newline at end of file diff --git a/tests/baselines/reference/callWithSpread5.js b/tests/baselines/reference/callWithSpread5.js new file mode 100644 index 0000000000000..3b4d1c683110b --- /dev/null +++ b/tests/baselines/reference/callWithSpread5.js @@ -0,0 +1,18 @@ +//// [callWithSpread5.ts] +declare const x: number +declare const nnnu: [number, number, number?] +declare const nntnnnt: [number, number] | [number, number, number] +declare function fn(a: number, b: number, bb: number, ...c: number[]): number + +fn(...nnnu, x) +fn(...nntnnnt, x) + + +//// [callWithSpread5.js] +var __spreadArray = (this && this.__spreadArray) || function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; +}; +fn.apply(void 0, __spreadArray(__spreadArray([], nnnu), [x])); +fn.apply(void 0, __spreadArray(__spreadArray([], nntnnnt), [x])); diff --git a/tests/baselines/reference/callWithSpread5.symbols b/tests/baselines/reference/callWithSpread5.symbols new file mode 100644 index 0000000000000..b3452ff611551 --- /dev/null +++ b/tests/baselines/reference/callWithSpread5.symbols @@ -0,0 +1,27 @@ +=== tests/cases/conformance/expressions/functionCalls/callWithSpread5.ts === +declare const x: number +>x : Symbol(x, Decl(callWithSpread5.ts, 0, 13)) + +declare const nnnu: [number, number, number?] +>nnnu : Symbol(nnnu, Decl(callWithSpread5.ts, 1, 13)) + +declare const nntnnnt: [number, number] | [number, number, number] +>nntnnnt : Symbol(nntnnnt, Decl(callWithSpread5.ts, 2, 13)) + +declare function fn(a: number, b: number, bb: number, ...c: number[]): number +>fn : Symbol(fn, Decl(callWithSpread5.ts, 2, 66)) +>a : Symbol(a, Decl(callWithSpread5.ts, 3, 20)) +>b : Symbol(b, Decl(callWithSpread5.ts, 3, 30)) +>bb : Symbol(bb, Decl(callWithSpread5.ts, 3, 41)) +>c : Symbol(c, Decl(callWithSpread5.ts, 3, 53)) + +fn(...nnnu, x) +>fn : Symbol(fn, Decl(callWithSpread5.ts, 2, 66)) +>nnnu : Symbol(nnnu, Decl(callWithSpread5.ts, 1, 13)) +>x : Symbol(x, Decl(callWithSpread5.ts, 0, 13)) + +fn(...nntnnnt, x) +>fn : Symbol(fn, Decl(callWithSpread5.ts, 2, 66)) +>nntnnnt : Symbol(nntnnnt, Decl(callWithSpread5.ts, 2, 13)) +>x : Symbol(x, Decl(callWithSpread5.ts, 0, 13)) + diff --git a/tests/baselines/reference/callWithSpread5.types b/tests/baselines/reference/callWithSpread5.types new file mode 100644 index 0000000000000..b3bd35312d6bf --- /dev/null +++ b/tests/baselines/reference/callWithSpread5.types @@ -0,0 +1,31 @@ +=== tests/cases/conformance/expressions/functionCalls/callWithSpread5.ts === +declare const x: number +>x : number + +declare const nnnu: [number, number, number?] +>nnnu : [number, number, number?] + +declare const nntnnnt: [number, number] | [number, number, number] +>nntnnnt : [number, number] | [number, number, number] + +declare function fn(a: number, b: number, bb: number, ...c: number[]): number +>fn : (a: number, b: number, bb: number, ...c: number[]) => number +>a : number +>b : number +>bb : number +>c : number[] + +fn(...nnnu, x) +>fn(...nnnu, x) : number +>fn : (a: number, b: number, bb: number, ...c: number[]) => number +>...nnnu : number +>nnnu : [number, number, number?] +>x : number + +fn(...nntnnnt, x) +>fn(...nntnnnt, x) : number +>fn : (a: number, b: number, bb: number, ...c: number[]) => number +>...nntnnnt : number +>nntnnnt : [number, number] | [number, number, number] +>x : number + diff --git a/tests/baselines/reference/callbackTagVariadicType.js b/tests/baselines/reference/callbackTagVariadicType.js new file mode 100644 index 0000000000000..c540486b5a081 --- /dev/null +++ b/tests/baselines/reference/callbackTagVariadicType.js @@ -0,0 +1,36 @@ +//// [callbackTagVariadicType.js] +/** + * @callback Foo + * @param {...string} args + * @returns {number} + */ + +/** @type {Foo} */ +export const x = () => 1 +var res = x('a', 'b') + + +//// [callbackTagVariadicType.js] +"use strict"; +/** + * @callback Foo + * @param {...string} args + * @returns {number} + */ +exports.__esModule = true; +exports.x = void 0; +/** @type {Foo} */ +var x = function () { return 1; }; +exports.x = x; +var res = exports.x('a', 'b'); + + +//// [callbackTagVariadicType.d.ts] +/** + * @callback Foo + * @param {...string} args + * @returns {number} + */ +/** @type {Foo} */ +export const x: Foo; +export type Foo = (...args: string[]) => number; diff --git a/tests/baselines/reference/callbackTagVariadicType.symbols b/tests/baselines/reference/callbackTagVariadicType.symbols new file mode 100644 index 0000000000000..7c5767ded4a9b --- /dev/null +++ b/tests/baselines/reference/callbackTagVariadicType.symbols @@ -0,0 +1,15 @@ +=== tests/cases/conformance/jsdoc/callbackTagVariadicType.js === +/** + * @callback Foo + * @param {...string} args + * @returns {number} + */ + +/** @type {Foo} */ +export const x = () => 1 +>x : Symbol(x, Decl(callbackTagVariadicType.js, 7, 12)) + +var res = x('a', 'b') +>res : Symbol(res, Decl(callbackTagVariadicType.js, 8, 3)) +>x : Symbol(x, Decl(callbackTagVariadicType.js, 7, 12)) + diff --git a/tests/baselines/reference/callbackTagVariadicType.types b/tests/baselines/reference/callbackTagVariadicType.types new file mode 100644 index 0000000000000..5858ab1642203 --- /dev/null +++ b/tests/baselines/reference/callbackTagVariadicType.types @@ -0,0 +1,20 @@ +=== tests/cases/conformance/jsdoc/callbackTagVariadicType.js === +/** + * @callback Foo + * @param {...string} args + * @returns {number} + */ + +/** @type {Foo} */ +export const x = () => 1 +>x : Foo +>() => 1 : () => number +>1 : 1 + +var res = x('a', 'b') +>res : number +>x('a', 'b') : number +>x : Foo +>'a' : "a" +>'b' : "b" + diff --git a/tests/baselines/reference/callsOnComplexSignatures.errors.txt b/tests/baselines/reference/callsOnComplexSignatures.errors.txt deleted file mode 100644 index f85a23e4ae79d..0000000000000 --- a/tests/baselines/reference/callsOnComplexSignatures.errors.txt +++ /dev/null @@ -1,110 +0,0 @@ -tests/cases/compiler/callsOnComplexSignatures.tsx(38,19): error TS7006: Parameter 'item' implicitly has an 'any' type. - - -==== tests/cases/compiler/callsOnComplexSignatures.tsx (1 errors) ==== - /// - import React from "react"; - - // Simple calls from real usecases - function test1() { - type stringType1 = "foo" | "bar"; - type stringType2 = "baz" | "bar"; - - interface Temp1 { - getValue(name: stringType1): number; - } - - interface Temp2 { - getValue(name: stringType2): string; - } - - function test(t: Temp1 | Temp2) { - const z = t.getValue("bar"); // Should be fine - } - } - - function test2() { - interface Messages { - readonly foo: (options: { [key: string]: any, b: number }) => string; - readonly bar: (options: { [key: string]: any, a: string }) => string; - } - - const messages: Messages = { - foo: (options) => "Foo", - bar: (options) => "Bar", - }; - - const test1 = (type: "foo" | "bar") => - messages[type]({ a: "A", b: 0 }); - } - - function test3(items: string[] | number[]) { - items.forEach(item => console.log(item)); - ~~~~ -!!! error TS7006: Parameter 'item' implicitly has an 'any' type. - } - - function test4( - arg1: ((...objs: {x: number}[]) => number) | ((...objs: {y: number}[]) => number), - arg2: ((a: {x: number}, b: object) => number) | ((a: object, b: {x: number}) => number), - arg3: ((a: {x: number}, ...objs: {y: number}[]) => number) | ((...objs: {x: number}[]) => number), - arg4: ((a?: {x: number}, b?: {x: number}) => number) | ((a?: {y: number}) => number), - arg5: ((a?: {x: number}, ...b: {x: number}[]) => number) | ((a?: {y: number}) => number), - arg6: ((a?: {x: number}, b?: {x: number}) => number) | ((...a: {y: number}[]) => number), - ) { - arg1(); - arg1({x: 0, y: 0}); - arg1({x: 0, y: 0}, {x: 1, y: 1}); - - arg2({x: 0}, {x: 0}); - - arg3({x: 0}); - arg3({x: 0}, {x: 0, y: 0}); - arg3({x: 0}, {x: 0, y: 0}, {x: 0, y: 0}); - - arg4(); - arg4({x: 0, y: 0}); - arg4({x: 0, y: 0}, {x: 0}); - - arg5(); - arg5({x: 0, y: 0}); - arg5({x: 0, y: 0}, {x: 0}); - - arg6(); - arg6({x: 0, y: 0}); - arg6({x: 0, y: 0}, {x: 0, y: 0}); - arg6({x: 0, y: 0}, {x: 0, y: 0}, {y: 0}); - } - - // JSX Tag names - function test5() { - // Pair of non-like intrinsics - function render(url?: string): React.ReactNode { - const Tag = url ? 'a' : 'button'; - return test; - } - - // Union of all intrinsics and components of `any` - function App(props: { component:React.ReactType }) { - const Comp: React.ReactType = props.component; - return (); - } - - // custom components with non-subset props - function render2() { - interface P1 { - p?: boolean; - c?: string; - } - interface P2 { - p?: boolean; - c?: any; - d?: any; - } - - var C: React.ComponentType | React.ComponentType = null as any; - - const a = ; - } - } - \ No newline at end of file diff --git a/tests/baselines/reference/callsOnComplexSignatures.types b/tests/baselines/reference/callsOnComplexSignatures.types index 1fa6c1f44e29a..a255300662666 100644 --- a/tests/baselines/reference/callsOnComplexSignatures.types +++ b/tests/baselines/reference/callsOnComplexSignatures.types @@ -100,13 +100,13 @@ function test3(items: string[] | number[]) { >items.forEach : ((callbackfn: (value: string, index: number, array: string[]) => void, thisArg?: any) => void) | ((callbackfn: (value: number, index: number, array: number[]) => void, thisArg?: any) => void) >items : string[] | number[] >forEach : ((callbackfn: (value: string, index: number, array: string[]) => void, thisArg?: any) => void) | ((callbackfn: (value: number, index: number, array: number[]) => void, thisArg?: any) => void) ->item => console.log(item) : (item: any) => void ->item : any +>item => console.log(item) : (item: string | number) => void +>item : string | number >console.log(item) : void >console.log : (...data: any[]) => void >console : Console >log : (...data: any[]) => void ->item : any +>item : string | number } function test4( diff --git a/tests/baselines/reference/capturedParametersInInitializers2.errors.txt b/tests/baselines/reference/capturedParametersInInitializers2.errors.txt index 4647aea937c94..aba66cbd30a58 100644 --- a/tests/baselines/reference/capturedParametersInInitializers2.errors.txt +++ b/tests/baselines/reference/capturedParametersInInitializers2.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/capturedParametersInInitializers2.ts(3,20): error TS2373: Parameter 'y' cannot reference identifier 'x' declared after it. tests/cases/compiler/capturedParametersInInitializers2.ts(4,14): error TS2373: Parameter 'y' cannot reference identifier 'x' declared after it. tests/cases/compiler/capturedParametersInInitializers2.ts(6,10): error TS2373: Parameter 'y' cannot reference identifier 'z' declared after it. -tests/cases/compiler/capturedParametersInInitializers2.ts(13,26): error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +tests/cases/compiler/capturedParametersInInitializers2.ts(13,26): error TS1166: A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type. tests/cases/compiler/capturedParametersInInitializers2.ts(13,27): error TS2373: Parameter 'y' cannot reference identifier 'x' declared after it. @@ -26,7 +26,7 @@ tests/cases/compiler/capturedParametersInInitializers2.ts(13,27): error TS2373: } function foo2(y = class {[x] = x}, x = 1) { ~~~ -!!! error TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type. +!!! error TS1166: A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type. ~ !!! error TS2373: Parameter 'y' cannot reference identifier 'x' declared after it. } \ No newline at end of file diff --git a/tests/baselines/reference/checkExportsObjectAssignProperty.types b/tests/baselines/reference/checkExportsObjectAssignProperty.types index a029a2aef6df9..60fcd84477a12 100644 --- a/tests/baselines/reference/checkExportsObjectAssignProperty.types +++ b/tests/baselines/reference/checkExportsObjectAssignProperty.types @@ -175,10 +175,10 @@ m2.setonlyAccessor = 0; === tests/cases/conformance/jsdoc/mod1.js === Object.defineProperty(exports, "thing", { value: 42, writable: true }); ->Object.defineProperty(exports, "thing", { value: 42, writable: true }) : any ->Object.defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>Object.defineProperty(exports, "thing", { value: 42, writable: true }) : typeof import("tests/cases/conformance/jsdoc/mod1") +>Object.defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Object : ObjectConstructor ->defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >exports : typeof import("tests/cases/conformance/jsdoc/mod1") >"thing" : "thing" >{ value: 42, writable: true } : { value: number; writable: true; } @@ -188,10 +188,10 @@ Object.defineProperty(exports, "thing", { value: 42, writable: true }); >true : true Object.defineProperty(exports, "readonlyProp", { value: "Smith", writable: false }); ->Object.defineProperty(exports, "readonlyProp", { value: "Smith", writable: false }) : any ->Object.defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>Object.defineProperty(exports, "readonlyProp", { value: "Smith", writable: false }) : typeof import("tests/cases/conformance/jsdoc/mod1") +>Object.defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Object : ObjectConstructor ->defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >exports : typeof import("tests/cases/conformance/jsdoc/mod1") >"readonlyProp" : "readonlyProp" >{ value: "Smith", writable: false } : { value: string; writable: false; } @@ -201,10 +201,10 @@ Object.defineProperty(exports, "readonlyProp", { value: "Smith", writable: false >false : false Object.defineProperty(exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); ->Object.defineProperty(exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }) : any ->Object.defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>Object.defineProperty(exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }) : typeof import("tests/cases/conformance/jsdoc/mod1") +>Object.defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Object : ObjectConstructor ->defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >exports : typeof import("tests/cases/conformance/jsdoc/mod1") >"rwAccessors" : "rwAccessors" >{ get() { return 98122 }, set(_) { /*ignore*/ } } : { get(): number; set(_: any): void; } @@ -214,10 +214,10 @@ Object.defineProperty(exports, "rwAccessors", { get() { return 98122 }, set(_) { >_ : any Object.defineProperty(exports, "readonlyAccessor", { get() { return 21.75 } }); ->Object.defineProperty(exports, "readonlyAccessor", { get() { return 21.75 } }) : any ->Object.defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>Object.defineProperty(exports, "readonlyAccessor", { get() { return 21.75 } }) : typeof import("tests/cases/conformance/jsdoc/mod1") +>Object.defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Object : ObjectConstructor ->defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >exports : typeof import("tests/cases/conformance/jsdoc/mod1") >"readonlyAccessor" : "readonlyAccessor" >{ get() { return 21.75 } } : { get(): number; } @@ -225,10 +225,10 @@ Object.defineProperty(exports, "readonlyAccessor", { get() { return 21.75 } }); >21.75 : 21.75 Object.defineProperty(exports, "setonlyAccessor", { ->Object.defineProperty(exports, "setonlyAccessor", { /** @param {string} str */ set(str) { this.rwAccessors = Number(str) }}) : any ->Object.defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>Object.defineProperty(exports, "setonlyAccessor", { /** @param {string} str */ set(str) { this.rwAccessors = Number(str) }}) : typeof import("tests/cases/conformance/jsdoc/mod1") +>Object.defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Object : ObjectConstructor ->defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >exports : typeof import("tests/cases/conformance/jsdoc/mod1") >"setonlyAccessor" : "setonlyAccessor" >{ /** @param {string} str */ set(str) { this.rwAccessors = Number(str) }} : { set(str: string): void; } @@ -251,10 +251,10 @@ Object.defineProperty(exports, "setonlyAccessor", { === tests/cases/conformance/jsdoc/mod2.js === Object.defineProperty(module.exports, "thing", { value: "yes", writable: true }); ->Object.defineProperty(module.exports, "thing", { value: "yes", writable: true }) : any ->Object.defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>Object.defineProperty(module.exports, "thing", { value: "yes", writable: true }) : typeof module.exports +>Object.defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Object : ObjectConstructor ->defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >module.exports : typeof module.exports >module : { exports: typeof module.exports; } >exports : typeof module.exports @@ -266,10 +266,10 @@ Object.defineProperty(module.exports, "thing", { value: "yes", writable: true }) >true : true Object.defineProperty(module.exports, "readonlyProp", { value: "Smith", writable: false }); ->Object.defineProperty(module.exports, "readonlyProp", { value: "Smith", writable: false }) : any ->Object.defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>Object.defineProperty(module.exports, "readonlyProp", { value: "Smith", writable: false }) : typeof module.exports +>Object.defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Object : ObjectConstructor ->defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >module.exports : typeof module.exports >module : { exports: typeof module.exports; } >exports : typeof module.exports @@ -281,10 +281,10 @@ Object.defineProperty(module.exports, "readonlyProp", { value: "Smith", writable >false : false Object.defineProperty(module.exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); ->Object.defineProperty(module.exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }) : any ->Object.defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>Object.defineProperty(module.exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }) : typeof module.exports +>Object.defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Object : ObjectConstructor ->defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >module.exports : typeof module.exports >module : { exports: typeof module.exports; } >exports : typeof module.exports @@ -296,10 +296,10 @@ Object.defineProperty(module.exports, "rwAccessors", { get() { return 98122 }, s >_ : any Object.defineProperty(module.exports, "readonlyAccessor", { get() { return 21.75 } }); ->Object.defineProperty(module.exports, "readonlyAccessor", { get() { return 21.75 } }) : any ->Object.defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>Object.defineProperty(module.exports, "readonlyAccessor", { get() { return 21.75 } }) : typeof module.exports +>Object.defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Object : ObjectConstructor ->defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >module.exports : typeof module.exports >module : { exports: typeof module.exports; } >exports : typeof module.exports @@ -309,10 +309,10 @@ Object.defineProperty(module.exports, "readonlyAccessor", { get() { return 21.75 >21.75 : 21.75 Object.defineProperty(module.exports, "setonlyAccessor", { ->Object.defineProperty(module.exports, "setonlyAccessor", { /** @param {string} str */ set(str) { this.rwAccessors = Number(str) }}) : any ->Object.defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>Object.defineProperty(module.exports, "setonlyAccessor", { /** @param {string} str */ set(str) { this.rwAccessors = Number(str) }}) : typeof module.exports +>Object.defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Object : ObjectConstructor ->defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >module.exports : typeof module.exports >module : { exports: typeof module.exports; } >exports : typeof module.exports diff --git a/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.types b/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.types index 085f6cf008ef9..6ea6a5ff129b8 100644 --- a/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.types +++ b/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.types @@ -129,9 +129,9 @@ Person.prototype.describe = function () { }; Object.defineProperty(Person.prototype, "thing", { value: 42, writable: true }); >Object.defineProperty(Person.prototype, "thing", { value: 42, writable: true }) : any ->Object.defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>Object.defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Object : ObjectConstructor ->defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Person.prototype : any >Person : typeof Person >prototype : any @@ -144,9 +144,9 @@ Object.defineProperty(Person.prototype, "thing", { value: 42, writable: true }); Object.defineProperty(Person.prototype, "readonlyProp", { value: "Smith", writable: false }); >Object.defineProperty(Person.prototype, "readonlyProp", { value: "Smith", writable: false }) : any ->Object.defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>Object.defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Object : ObjectConstructor ->defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Person.prototype : any >Person : typeof Person >prototype : any @@ -159,9 +159,9 @@ Object.defineProperty(Person.prototype, "readonlyProp", { value: "Smith", writab Object.defineProperty(Person.prototype, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); >Object.defineProperty(Person.prototype, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }) : any ->Object.defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>Object.defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Object : ObjectConstructor ->defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Person.prototype : any >Person : typeof Person >prototype : any @@ -174,9 +174,9 @@ Object.defineProperty(Person.prototype, "rwAccessors", { get() { return 98122 }, Object.defineProperty(Person.prototype, "readonlyAccessor", { get() { return 21.75 } }); >Object.defineProperty(Person.prototype, "readonlyAccessor", { get() { return 21.75 } }) : any ->Object.defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>Object.defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Object : ObjectConstructor ->defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Person.prototype : any >Person : typeof Person >prototype : any @@ -187,9 +187,9 @@ Object.defineProperty(Person.prototype, "readonlyAccessor", { get() { return 21. Object.defineProperty(Person.prototype, "setonlyAccessor", { >Object.defineProperty(Person.prototype, "setonlyAccessor", { /** @param {string} str */ set(str) { this.rwAccessors = Number(str) }}) : any ->Object.defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>Object.defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Object : ObjectConstructor ->defineProperty : (o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => any +>defineProperty : (o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType) => T >Person.prototype : any >Person : typeof Person >prototype : any diff --git a/tests/baselines/reference/checkJsxChildrenProperty5.errors.txt b/tests/baselines/reference/checkJsxChildrenProperty5.errors.txt index 476644ee33603..aad013f4d8544 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty5.errors.txt +++ b/tests/baselines/reference/checkJsxChildrenProperty5.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/jsx/file.tsx(20,10): error TS2741: Property 'children' is missing in type '{ a: number; b: string; }' but required in type 'Prop'. -tests/cases/conformance/jsx/file.tsx(25,9): error TS2740: Type 'Element' is missing the following properties from type 'Button': render, setState, forceUpdate, state, and 2 more. +tests/cases/conformance/jsx/file.tsx(25,9): error TS2740: Type 'ReactElement' is missing the following properties from type 'Button': render, setState, forceUpdate, state, and 2 more. tests/cases/conformance/jsx/file.tsx(29,10): error TS2740: Type 'typeof Button' is missing the following properties from type 'Button': render, setState, forceUpdate, props, and 3 more. @@ -33,7 +33,7 @@ tests/cases/conformance/jsx/file.tsx(29,10): error TS2740: Type 'typeof Button'